update for activation changes
[platform/upstream/gstreamer.git] / ext / ogg / gstoggdemux.c
1 /* GStreamer
2  * Copyright (C) 2004 Wim Taymans <wim@fluendo.com>
3  *
4  * gstoggdemux.c: ogg stream demuxer
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /**
23  * SECTION:element-oggdemux
24  * @see_also: <link linkend="gst-plugins-base-plugins-oggmux">oggmux</link>
25  *
26  * This element demuxes ogg files into their encoded audio and video components.
27  *
28  * <refsect2>
29  * <title>Example pipelines</title>
30  * |[
31  * gst-launch -v filesrc location=test.ogg ! oggdemux ! vorbisdec ! audioconvert ! alsasink
32  * ]| Decodes the vorbis audio stored inside an ogg container.
33  * </refsect2>
34  *
35  * Last reviewed on 2006-12-30 (0.10.5)
36  */
37
38
39 #ifdef HAVE_CONFIG_H
40 #include "config.h"
41 #endif
42 #include <string.h>
43 #include <gst/gst-i18n-plugin.h>
44 #include <gst/tag/tag.h>
45
46 #include "gstoggdemux.h"
47
48 #define CHUNKSIZE (8500)        /* this is out of vorbisfile */
49
50 /* we hope we get a granpos within this many bytes off the end */
51 #define DURATION_CHUNK_OFFSET (64*1024)
52
53 /* stop duration checks within this much of EOS */
54 #define EOS_AVOIDANCE_THRESHOLD 8192
55
56 #define GST_FLOW_LIMIT GST_FLOW_CUSTOM_ERROR
57 #define GST_FLOW_SKIP_PUSH GST_FLOW_CUSTOM_SUCCESS_1
58
59 #define GST_CHAIN_LOCK(ogg)     g_mutex_lock((ogg)->chain_lock)
60 #define GST_CHAIN_UNLOCK(ogg)   g_mutex_unlock((ogg)->chain_lock)
61
62 #define GST_PUSH_LOCK(ogg)                  \
63   do {                                      \
64     GST_TRACE_OBJECT(ogg, "Push lock");     \
65     g_mutex_lock((ogg)->push_lock);         \
66   } while(0)
67
68 #define GST_PUSH_UNLOCK(ogg)                \
69   do {                                      \
70     GST_TRACE_OBJECT(ogg, "Push unlock");   \
71     g_mutex_unlock((ogg)->push_lock);       \
72   } while(0)
73
74 GST_DEBUG_CATEGORY (gst_ogg_demux_debug);
75 GST_DEBUG_CATEGORY (gst_ogg_demux_setup_debug);
76 #define GST_CAT_DEFAULT gst_ogg_demux_debug
77
78
79 static ogg_packet *
80 _ogg_packet_copy (const ogg_packet * packet)
81 {
82   ogg_packet *ret = g_slice_new (ogg_packet);
83
84   *ret = *packet;
85   ret->packet = g_memdup (packet->packet, packet->bytes);
86
87   return ret;
88 }
89
90 static void
91 _ogg_packet_free (ogg_packet * packet)
92 {
93   g_free (packet->packet);
94   g_slice_free (ogg_packet, packet);
95 }
96
97 static ogg_page *
98 gst_ogg_page_copy (ogg_page * page)
99 {
100   ogg_page *p = g_slice_new (ogg_page);
101
102   /* make a copy of the page */
103   p->header = g_memdup (page->header, page->header_len);
104   p->header_len = page->header_len;
105   p->body = g_memdup (page->body, page->body_len);
106   p->body_len = page->body_len;
107
108   return p;
109 }
110
111 static void
112 gst_ogg_page_free (ogg_page * page)
113 {
114   g_free (page->header);
115   g_free (page->body);
116   g_slice_free (ogg_page, page);
117 }
118
119 static gboolean gst_ogg_demux_collect_chain_info (GstOggDemux * ogg,
120     GstOggChain * chain);
121 static gboolean gst_ogg_demux_activate_chain (GstOggDemux * ogg,
122     GstOggChain * chain, GstEvent * event);
123 static void gst_ogg_pad_mark_discont (GstOggPad * pad);
124 static void gst_ogg_chain_mark_discont (GstOggChain * chain);
125
126 static gboolean gst_ogg_demux_perform_seek (GstOggDemux * ogg,
127     GstEvent * event);
128 static gboolean gst_ogg_demux_receive_event (GstElement * element,
129     GstEvent * event);
130
131 static void gst_ogg_pad_dispose (GObject * object);
132 static void gst_ogg_pad_finalize (GObject * object);
133
134 static gboolean gst_ogg_pad_src_query (GstPad * pad, GstObject * parent,
135     GstQuery * query);
136 static gboolean gst_ogg_pad_event (GstPad * pad, GstObject * parent,
137     GstEvent * event);
138 static GstOggPad *gst_ogg_chain_get_stream (GstOggChain * chain,
139     guint32 serialno);
140
141 static GstFlowReturn gst_ogg_demux_combine_flows (GstOggDemux * ogg,
142     GstOggPad * pad, GstFlowReturn ret);
143 static void gst_ogg_demux_sync_streams (GstOggDemux * ogg);
144
145 GstCaps *gst_ogg_demux_set_header_on_caps (GstOggDemux * ogg,
146     GstCaps * caps, GList * headers);
147 static gboolean gst_ogg_demux_send_event (GstOggDemux * ogg, GstEvent * event);
148 static gboolean gst_ogg_demux_perform_seek_push (GstOggDemux * ogg,
149     GstEvent * event);
150 static gboolean gst_ogg_demux_check_duration_push (GstOggDemux * ogg,
151     GstSeekFlags flags, GstEvent * event);
152
153 GType gst_ogg_pad_get_type (void);
154 G_DEFINE_TYPE (GstOggPad, gst_ogg_pad, GST_TYPE_PAD);
155
156 static void
157 gst_ogg_pad_class_init (GstOggPadClass * klass)
158 {
159   GObjectClass *gobject_class;
160
161   gobject_class = (GObjectClass *) klass;
162
163   gobject_class->dispose = gst_ogg_pad_dispose;
164   gobject_class->finalize = gst_ogg_pad_finalize;
165 }
166
167 static void
168 gst_ogg_pad_init (GstOggPad * pad)
169 {
170   gst_pad_set_event_function (GST_PAD (pad),
171       GST_DEBUG_FUNCPTR (gst_ogg_pad_event));
172   gst_pad_set_query_function (GST_PAD (pad),
173       GST_DEBUG_FUNCPTR (gst_ogg_pad_src_query));
174   gst_pad_use_fixed_caps (GST_PAD (pad));
175
176   pad->mode = GST_OGG_PAD_MODE_INIT;
177
178   pad->current_granule = -1;
179   pad->keyframe_granule = -1;
180
181   pad->start_time = GST_CLOCK_TIME_NONE;
182
183   pad->position = GST_CLOCK_TIME_NONE;
184
185   pad->have_type = FALSE;
186   pad->continued = NULL;
187   pad->map.headers = NULL;
188   pad->map.queued = NULL;
189
190   pad->map.granulerate_n = 0;
191   pad->map.granulerate_d = 0;
192   pad->map.granuleshift = -1;
193 }
194
195 static void
196 gst_ogg_pad_dispose (GObject * object)
197 {
198   GstOggPad *pad = GST_OGG_PAD (object);
199
200   pad->chain = NULL;
201   pad->ogg = NULL;
202
203   g_list_foreach (pad->map.headers, (GFunc) _ogg_packet_free, NULL);
204   g_list_free (pad->map.headers);
205   pad->map.headers = NULL;
206   g_list_foreach (pad->map.queued, (GFunc) _ogg_packet_free, NULL);
207   g_list_free (pad->map.queued);
208   pad->map.queued = NULL;
209
210   g_free (pad->map.index);
211   pad->map.index = NULL;
212
213   /* clear continued pages */
214   g_list_foreach (pad->continued, (GFunc) gst_ogg_page_free, NULL);
215   g_list_free (pad->continued);
216   pad->continued = NULL;
217
218   if (pad->map.caps) {
219     gst_caps_unref (pad->map.caps);
220     pad->map.caps = NULL;
221   }
222
223   if (pad->map.taglist) {
224     gst_tag_list_free (pad->map.taglist);
225     pad->map.taglist = NULL;
226   }
227
228   ogg_stream_reset (&pad->map.stream);
229
230   G_OBJECT_CLASS (gst_ogg_pad_parent_class)->dispose (object);
231 }
232
233 static void
234 gst_ogg_pad_finalize (GObject * object)
235 {
236   GstOggPad *pad = GST_OGG_PAD (object);
237
238   ogg_stream_clear (&pad->map.stream);
239
240   G_OBJECT_CLASS (gst_ogg_pad_parent_class)->finalize (object);
241 }
242
243 static gboolean
244 gst_ogg_pad_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
245 {
246   gboolean res = TRUE;
247   GstOggDemux *ogg;
248
249   ogg = GST_OGG_DEMUX (parent);
250
251   switch (GST_QUERY_TYPE (query)) {
252     case GST_QUERY_DURATION:
253     {
254       GstFormat format;
255       gint64 total_time = -1;
256
257       gst_query_parse_duration (query, &format, NULL);
258       /* can only get position in time */
259       if (format != GST_FORMAT_TIME)
260         goto wrong_format;
261
262       if (ogg->total_time != -1) {
263         /* we can return the total length */
264         total_time = ogg->total_time;
265       } else {
266         gint bitrate = ogg->bitrate;
267
268         /* try with length and bitrate */
269         if (bitrate > 0) {
270           GstQuery *uquery;
271
272           /* ask upstream for total length in bytes */
273           uquery = gst_query_new_duration (GST_FORMAT_BYTES);
274           if (gst_pad_peer_query (ogg->sinkpad, uquery)) {
275             gint64 length;
276
277             gst_query_parse_duration (uquery, NULL, &length);
278
279             /* estimate using the bitrate */
280             total_time =
281                 gst_util_uint64_scale (length, 8 * GST_SECOND, bitrate);
282
283             GST_LOG_OBJECT (ogg,
284                 "length: %" G_GINT64_FORMAT ", bitrate %d, total_time %"
285                 GST_TIME_FORMAT, length, bitrate, GST_TIME_ARGS (total_time));
286           }
287           gst_query_unref (uquery);
288         }
289       }
290
291       gst_query_set_duration (query, GST_FORMAT_TIME, total_time);
292       break;
293     }
294     case GST_QUERY_SEEKING:
295     {
296       GstFormat format;
297
298       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
299       if (format == GST_FORMAT_TIME) {
300         gboolean seekable = FALSE;
301         gint64 stop = -1;
302
303         if (ogg->pullmode) {
304           seekable = TRUE;
305           stop = ogg->total_time;
306         } else if (ogg->current_chain->streams->len) {
307           gint i;
308
309           seekable = FALSE;
310           for (i = 0; i < ogg->current_chain->streams->len; i++) {
311             GstOggPad *pad =
312                 g_array_index (ogg->current_chain->streams, GstOggPad *, i);
313
314             seekable = TRUE;
315             if (pad->map.index != NULL && pad->map.n_index != 0) {
316               GstOggIndex *idx;
317               GstClockTime idx_time;
318
319               idx = &pad->map.index[pad->map.n_index - 1];
320               idx_time =
321                   gst_util_uint64_scale (idx->timestamp, GST_SECOND,
322                   pad->map.kp_denom);
323               if (stop == -1)
324                 stop = idx_time;
325               else
326                 stop = MAX (idx_time, stop);
327             } else {
328               stop = -1;        /* we've no clue, sadly, without seeking */
329             }
330           }
331         }
332
333         gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, stop);
334       } else {
335         res = FALSE;
336       }
337       break;
338     }
339
340     default:
341       res = gst_pad_query_default (pad, parent, query);
342       break;
343   }
344 done:
345
346   return res;
347
348   /* ERRORS */
349 wrong_format:
350   {
351     GST_DEBUG_OBJECT (ogg, "only query duration on TIME is supported");
352     res = FALSE;
353     goto done;
354   }
355 }
356
357 static gboolean
358 gst_ogg_demux_receive_event (GstElement * element, GstEvent * event)
359 {
360   gboolean res;
361   GstOggDemux *ogg;
362
363   ogg = GST_OGG_DEMUX (element);
364
365   switch (GST_EVENT_TYPE (event)) {
366     case GST_EVENT_SEEK:
367       /* now do the seek */
368       res = gst_ogg_demux_perform_seek (ogg, event);
369       gst_event_unref (event);
370       break;
371     default:
372       GST_DEBUG_OBJECT (ogg, "We only handle seek events here");
373       goto error;
374   }
375
376   return res;
377
378   /* ERRORS */
379 error:
380   {
381     GST_DEBUG_OBJECT (ogg, "error handling event");
382     gst_event_unref (event);
383     return FALSE;
384   }
385 }
386
387 static gboolean
388 gst_ogg_pad_event (GstPad * pad, GstObject * parent, GstEvent * event)
389 {
390   gboolean res;
391   GstOggDemux *ogg;
392
393   ogg = GST_OGG_DEMUX (parent);
394
395   switch (GST_EVENT_TYPE (event)) {
396     case GST_EVENT_SEEK:
397       /* now do the seek */
398       res = gst_ogg_demux_perform_seek (ogg, event);
399       gst_event_unref (event);
400       break;
401     default:
402       res = gst_pad_event_default (pad, parent, event);
403       break;
404   }
405
406   return res;
407 }
408
409 static void
410 gst_ogg_pad_reset (GstOggPad * pad)
411 {
412   ogg_stream_reset (&pad->map.stream);
413
414   GST_DEBUG_OBJECT (pad, "doing reset");
415
416   /* clear continued pages */
417   g_list_foreach (pad->continued, (GFunc) gst_ogg_page_free, NULL);
418   g_list_free (pad->continued);
419   pad->continued = NULL;
420
421   pad->last_ret = GST_FLOW_OK;
422   pad->position = GST_CLOCK_TIME_NONE;
423   pad->current_granule = -1;
424   pad->keyframe_granule = -1;
425   pad->is_eos = FALSE;
426 }
427
428 /* queue data, basically takes the packet, puts it in a buffer and store the
429  * buffer in the queued list.  */
430 static GstFlowReturn
431 gst_ogg_demux_queue_data (GstOggPad * pad, ogg_packet * packet)
432 {
433 #ifndef GST_DISABLE_GST_DEBUG
434   GstOggDemux *ogg = pad->ogg;
435 #endif
436
437   GST_DEBUG_OBJECT (ogg, "%p queueing data serial %08x",
438       pad, pad->map.serialno);
439
440   pad->map.queued = g_list_append (pad->map.queued, _ogg_packet_copy (packet));
441
442   /* we are ok now */
443   return GST_FLOW_OK;
444 }
445
446 static GstFlowReturn
447 gst_ogg_demux_chain_peer (GstOggPad * pad, ogg_packet * packet,
448     gboolean push_headers)
449 {
450   GstBuffer *buf = NULL;
451   GstFlowReturn ret, cret;
452   GstOggDemux *ogg = pad->ogg;
453   gint64 current_time;
454   GstOggChain *chain;
455   gint64 duration;
456   gint offset;
457   gint trim;
458   GstClockTime out_timestamp, out_duration;
459   guint64 out_offset, out_offset_end;
460   gboolean delta_unit = FALSE;
461
462   cret = GST_FLOW_OK;
463
464   GST_PUSH_LOCK (ogg);
465   if (!ogg->pullmode && ogg->push_state == PUSH_PLAYING
466       && ogg->push_time_length == GST_CLOCK_TIME_NONE
467       && !ogg->push_disable_seeking) {
468     if (!ogg->building_chain) {
469       /* we got all headers, now try to get duration */
470       if (!gst_ogg_demux_check_duration_push (ogg, GST_SEEK_FLAG_FLUSH, NULL)) {
471         GST_PUSH_UNLOCK (ogg);
472         return GST_FLOW_OK;
473       }
474     }
475     GST_PUSH_UNLOCK (ogg);
476     return GST_FLOW_OK;
477   }
478   GST_PUSH_UNLOCK (ogg);
479
480   GST_DEBUG_OBJECT (ogg,
481       "%p streaming to peer serial %08x", pad, pad->map.serialno);
482
483   if (pad->map.is_ogm) {
484     const guint8 *data;
485     long bytes;
486
487     data = packet->packet;
488     bytes = packet->bytes;
489
490     if (bytes < 1)
491       goto empty_packet;
492
493     if ((data[0] & 1) || (data[0] & 3 && pad->map.is_ogm_text)) {
494       /* We don't push header packets for OGM */
495       goto done;
496     }
497
498     offset = 1 + (((data[0] & 0xc0) >> 6) | ((data[0] & 0x02) << 1));
499     delta_unit = (((data[0] & 0x08) >> 3) == 0);
500
501     trim = 0;
502
503     /* Strip trailing \0 for subtitles */
504     if (pad->map.is_ogm_text) {
505       while (bytes && data[bytes - 1] == 0) {
506         trim++;
507         bytes--;
508       }
509     }
510   } else if (pad->map.is_vp8) {
511     if ((packet->bytes >= 7 && memcmp (packet->packet, "OVP80\2 ", 7) == 0) ||
512         packet->b_o_s ||
513         (packet->bytes >= 5 && memcmp (packet->packet, "OVP80", 5) == 0)) {
514       /* We don't push header packets for VP8 */
515       goto done;
516     }
517     offset = 0;
518     trim = 0;
519   } else {
520     offset = 0;
521     trim = 0;
522   }
523
524   /* get timing info for the packet */
525   if (gst_ogg_stream_packet_is_header (&pad->map, packet)) {
526     duration = 0;
527     GST_DEBUG_OBJECT (ogg, "packet is header");
528   } else {
529     duration = gst_ogg_stream_get_packet_duration (&pad->map, packet);
530     GST_DEBUG_OBJECT (ogg, "packet duration %" G_GUINT64_FORMAT, duration);
531   }
532
533   if (packet->b_o_s) {
534     out_timestamp = GST_CLOCK_TIME_NONE;
535     out_duration = GST_CLOCK_TIME_NONE;
536     out_offset = 0;
537     out_offset_end = -1;
538   } else {
539     if (packet->granulepos != -1) {
540       pad->current_granule = gst_ogg_stream_granulepos_to_granule (&pad->map,
541           packet->granulepos);
542       pad->keyframe_granule =
543           gst_ogg_stream_granulepos_to_key_granule (&pad->map,
544           packet->granulepos);
545       GST_DEBUG_OBJECT (ogg, "new granule %" G_GUINT64_FORMAT,
546           pad->current_granule);
547     } else if (ogg->segment.rate > 0.0 && pad->current_granule != -1) {
548       pad->current_granule += duration;
549       GST_DEBUG_OBJECT (ogg, "interpollating granule %" G_GUINT64_FORMAT,
550           pad->current_granule);
551     }
552     if (ogg->segment.rate < 0.0 && packet->granulepos == -1) {
553       /* negative rates, only set timestamp on the packets with a granulepos */
554       out_timestamp = -1;
555       out_duration = -1;
556       out_offset = -1;
557       out_offset_end = -1;
558     } else {
559       /* we only push buffers after we have a valid granule. This is done so that
560        * we nicely skip packets without a timestamp after a seek. This is ok
561        * because we base or seek on the packet after the page with the smaller
562        * timestamp. */
563       if (pad->current_granule == -1)
564         goto no_timestamp;
565
566       if (pad->map.is_ogm) {
567         out_timestamp = gst_ogg_stream_granule_to_time (&pad->map,
568             pad->current_granule);
569         out_duration = gst_util_uint64_scale (duration,
570             GST_SECOND * pad->map.granulerate_d, pad->map.granulerate_n);
571       } else if (pad->map.is_sparse) {
572         out_timestamp = gst_ogg_stream_granule_to_time (&pad->map,
573             pad->current_granule);
574         if (duration == GST_CLOCK_TIME_NONE) {
575           out_duration = GST_CLOCK_TIME_NONE;
576         } else {
577           out_duration = gst_util_uint64_scale (duration,
578               GST_SECOND * pad->map.granulerate_d, pad->map.granulerate_n);
579         }
580       } else {
581         out_timestamp = gst_ogg_stream_granule_to_time (&pad->map,
582             pad->current_granule - duration);
583         out_duration =
584             gst_ogg_stream_granule_to_time (&pad->map,
585             pad->current_granule) - out_timestamp;
586       }
587       out_offset_end =
588           gst_ogg_stream_granule_to_granulepos (&pad->map,
589           pad->current_granule, pad->keyframe_granule);
590       out_offset =
591           gst_ogg_stream_granule_to_time (&pad->map, pad->current_granule);
592     }
593   }
594
595   if (pad->map.is_ogm_text) {
596     /* check for invalid buffer sizes */
597     if (G_UNLIKELY (offset + trim >= packet->bytes))
598       goto empty_packet;
599   }
600
601   if (!pad->added)
602     goto not_added;
603
604   buf = gst_buffer_new_and_alloc (packet->bytes - offset - trim);
605
606   /* set delta flag for OGM content */
607   if (delta_unit)
608     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
609
610   /* copy packet in buffer */
611   gst_buffer_fill (buf, 0, packet->packet + offset,
612       packet->bytes - offset - trim);
613
614   GST_BUFFER_TIMESTAMP (buf) = out_timestamp;
615   GST_BUFFER_DURATION (buf) = out_duration;
616   GST_BUFFER_OFFSET (buf) = out_offset;
617   GST_BUFFER_OFFSET_END (buf) = out_offset_end;
618
619   /* Mark discont on the buffer */
620   if (pad->discont) {
621     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
622     pad->discont = FALSE;
623   }
624
625   pad->position = ogg->segment.position;
626
627   /* don't push the header packets when we are asked to skip them */
628   if (!packet->b_o_s || push_headers) {
629     ret = gst_pad_push (GST_PAD_CAST (pad), buf);
630     buf = NULL;
631
632     /* combine flows */
633     cret = gst_ogg_demux_combine_flows (ogg, pad, ret);
634   }
635
636   /* we're done with skeleton stuff */
637   if (pad->map.is_skeleton)
638     goto done;
639
640   /* check if valid granulepos, then we can calculate the current
641    * position. We know the granule for each packet but we only want to update
642    * the position when we have a valid granulepos on the packet because else
643    * our time jumps around for the different streams. */
644   if (packet->granulepos < 0)
645     goto done;
646
647   /* convert to time */
648   current_time = gst_ogg_stream_get_end_time_for_granulepos (&pad->map,
649       packet->granulepos);
650
651   /* convert to stream time */
652   if ((chain = pad->chain)) {
653     gint64 chain_start = 0;
654
655     if (chain->segment_start != GST_CLOCK_TIME_NONE)
656       chain_start = chain->segment_start;
657
658     current_time = current_time - chain_start + chain->begin_time;
659   }
660
661   /* and store as the current position */
662   ogg->segment.position = current_time;
663
664   GST_DEBUG_OBJECT (ogg, "ogg current time %" GST_TIME_FORMAT,
665       GST_TIME_ARGS (current_time));
666
667   /* check stream eos */
668   if ((ogg->segment.rate > 0.0 && ogg->segment.stop != GST_CLOCK_TIME_NONE &&
669           current_time > ogg->segment.stop) ||
670       (ogg->segment.rate < 0.0 && ogg->segment.start != GST_CLOCK_TIME_NONE &&
671           current_time < ogg->segment.start)) {
672     GST_DEBUG_OBJECT (ogg, "marking pad %p EOS", pad);
673     pad->is_eos = TRUE;
674   }
675
676 done:
677   if (buf)
678     gst_buffer_unref (buf);
679   /* return combined flow result */
680   return cret;
681
682   /* special cases */
683 empty_packet:
684   {
685     GST_DEBUG_OBJECT (ogg, "Skipping empty packet");
686     goto done;
687   }
688
689 no_timestamp:
690   {
691     GST_DEBUG_OBJECT (ogg, "skipping packet: no valid granule found yet");
692     goto done;
693   }
694 not_added:
695   {
696     GST_DEBUG_OBJECT (ogg, "pad not added yet");
697     goto done;
698   }
699 }
700
701 static guint64
702 gst_ogg_demux_collect_start_time (GstOggDemux * ogg, GstOggChain * chain)
703 {
704   gint i;
705   guint64 start_time = G_MAXUINT64;
706
707   for (i = 0; i < chain->streams->len; i++) {
708     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
709
710     if (pad->map.is_skeleton)
711       continue;
712
713     /*  can do this if the pad start time is not defined */
714     GST_DEBUG_OBJECT (ogg, "Pad %08x (%s) start time is %" GST_TIME_FORMAT,
715         pad->map.serialno, gst_ogg_stream_get_media_type (&pad->map),
716         GST_TIME_ARGS (pad->start_time));
717     if (pad->start_time == GST_CLOCK_TIME_NONE) {
718       if (!pad->map.is_sparse) {
719         start_time = G_MAXUINT64;
720         break;
721       }
722     } else {
723       start_time = MIN (start_time, pad->start_time);
724     }
725   }
726   return start_time;
727 }
728
729 static GstClockTime
730 gst_ogg_demux_collect_sync_time (GstOggDemux * ogg, GstOggChain * chain)
731 {
732   gint i;
733   GstClockTime sync_time = GST_CLOCK_TIME_NONE;
734
735   if (!chain) {
736     GST_WARNING_OBJECT (ogg, "No chain!");
737     return GST_CLOCK_TIME_NONE;
738   }
739
740   for (i = 0; i < chain->streams->len; i++) {
741     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
742
743     if (pad->map.is_sparse)
744       continue;
745
746     if (pad->push_sync_time == GST_CLOCK_TIME_NONE) {
747       sync_time = GST_CLOCK_TIME_NONE;
748       break;
749     } else {
750       if (sync_time == GST_CLOCK_TIME_NONE)
751         sync_time = pad->push_sync_time;
752       else
753         sync_time = MAX (sync_time, pad->push_sync_time);
754     }
755   }
756   return sync_time;
757 }
758
759 /* submit a packet to the oggpad, this function will run the
760  * typefind code for the pad if this is the first packet for this
761  * stream 
762  */
763 static GstFlowReturn
764 gst_ogg_pad_submit_packet (GstOggPad * pad, ogg_packet * packet)
765 {
766   gint64 granule;
767   GstFlowReturn ret = GST_FLOW_OK;
768
769   GstOggDemux *ogg = pad->ogg;
770
771   GST_DEBUG_OBJECT (ogg, "%p submit packet serial %08x",
772       pad, pad->map.serialno);
773
774   if (!pad->have_type) {
775     pad->have_type = gst_ogg_stream_setup_map (&pad->map, packet);
776     if (!pad->have_type) {
777       pad->map.caps = gst_caps_new_empty_simple ("application/x-unknown");
778     }
779     if (pad->map.is_skeleton) {
780       GST_DEBUG_OBJECT (ogg, "we have a fishead");
781       /* copy values over to global ogg level */
782       ogg->basetime = pad->map.basetime;
783       ogg->prestime = pad->map.prestime;
784
785       /* use total time to update the total ogg time */
786       if (ogg->total_time == -1) {
787         ogg->total_time = pad->map.total_time;
788       } else if (pad->map.total_time > 0) {
789         ogg->total_time = MAX (ogg->total_time, pad->map.total_time);
790       }
791     }
792     if (pad->map.caps) {
793       gst_pad_set_caps (GST_PAD (pad), pad->map.caps);
794     } else {
795       GST_WARNING_OBJECT (ogg, "stream parser didn't create src pad caps");
796     }
797   }
798
799   if (pad->map.is_skeleton) {
800     guint32 serialno;
801     GstOggPad *skel_pad;
802     GstOggSkeleton type;
803
804     /* try to parse the serialno first */
805     if (gst_ogg_map_parse_fisbone (&pad->map, packet->packet, packet->bytes,
806             &serialno, &type)) {
807
808       GST_DEBUG_OBJECT (pad->ogg,
809           "got skeleton packet for stream 0x%08x", serialno);
810
811       skel_pad = gst_ogg_chain_get_stream (pad->chain, serialno);
812       if (skel_pad) {
813         switch (type) {
814           case GST_OGG_SKELETON_FISBONE:
815             /* parse the remainder of the fisbone in the pad with the serialno,
816              * note that we ignore the start_time as this is usually wrong for
817              * live streams */
818             gst_ogg_map_add_fisbone (&skel_pad->map, &pad->map, packet->packet,
819                 packet->bytes, NULL);
820             break;
821           case GST_OGG_SKELETON_INDEX:
822             gst_ogg_map_add_index (&skel_pad->map, &pad->map, packet->packet,
823                 packet->bytes);
824
825             /* use total time to update the total ogg time */
826             if (ogg->total_time == -1) {
827               ogg->total_time = skel_pad->map.total_time;
828             } else if (skel_pad->map.total_time > 0) {
829               ogg->total_time = MAX (ogg->total_time, skel_pad->map.total_time);
830             }
831             break;
832           default:
833             break;
834         }
835
836       } else {
837         GST_WARNING_OBJECT (pad->ogg,
838             "found skeleton fisbone for an unknown stream 0x%08x", serialno);
839       }
840     }
841   }
842
843   granule = gst_ogg_stream_granulepos_to_granule (&pad->map,
844       packet->granulepos);
845   if (granule != -1) {
846     GST_DEBUG_OBJECT (ogg, "%p has granulepos %" G_GINT64_FORMAT, pad, granule);
847     pad->current_granule = granule;
848   }
849
850   /* restart header packet count when seeing a b_o_s page;
851    * particularly useful following a seek or even following chain finding */
852   if (packet->b_o_s) {
853     GST_DEBUG_OBJECT (ogg, "b_o_s packet, resetting header packet count");
854     pad->map.n_header_packets_seen = 0;
855     if (!pad->map.have_headers) {
856       GST_DEBUG_OBJECT (ogg, "clearing header packets");
857       g_list_foreach (pad->map.headers, (GFunc) _ogg_packet_free, NULL);
858       g_list_free (pad->map.headers);
859       pad->map.headers = NULL;
860     }
861   }
862
863   /* Overload the value of b_o_s in ogg_packet with a flag whether or
864    * not this is a header packet.  Maybe some day this could be cleaned
865    * up.  */
866   packet->b_o_s = gst_ogg_stream_packet_is_header (&pad->map, packet);
867   if (!packet->b_o_s) {
868     GST_DEBUG ("found non-header packet");
869     pad->map.have_headers = TRUE;
870     if (pad->start_time == GST_CLOCK_TIME_NONE) {
871       gint64 duration = gst_ogg_stream_get_packet_duration (&pad->map, packet);
872       GST_DEBUG ("duration %" G_GINT64_FORMAT, duration);
873       if (duration != -1) {
874         pad->map.accumulated_granule += duration;
875         GST_DEBUG ("accumulated granule %" G_GINT64_FORMAT,
876             pad->map.accumulated_granule);
877       }
878
879       if (packet->granulepos != -1) {
880         ogg_int64_t start_granule;
881         gint64 granule;
882
883         granule = gst_ogg_stream_granulepos_to_granule (&pad->map,
884             packet->granulepos);
885
886         if (granule > pad->map.accumulated_granule)
887           start_granule = granule - pad->map.accumulated_granule;
888         else
889           start_granule = 0;
890
891         pad->start_time = gst_ogg_stream_granule_to_time (&pad->map,
892             start_granule);
893         GST_DEBUG_OBJECT (ogg,
894             "start time %" GST_TIME_FORMAT " (%" GST_TIME_FORMAT ") for %s",
895             GST_TIME_ARGS (pad->start_time), GST_TIME_ARGS (pad->start_time),
896             gst_ogg_stream_get_media_type (&pad->map));
897       } else {
898         packet->granulepos = gst_ogg_stream_granule_to_granulepos (&pad->map,
899             pad->map.accumulated_granule, pad->keyframe_granule);
900       }
901     }
902   } else {
903     /* look for tags in header packet (before inc header count) */
904     gst_ogg_stream_extract_tags (&pad->map, packet);
905     pad->map.n_header_packets_seen++;
906     if (!pad->map.have_headers) {
907       pad->map.headers =
908           g_list_append (pad->map.headers, _ogg_packet_copy (packet));
909       GST_DEBUG ("keeping header packet %d", pad->map.n_header_packets_seen);
910     }
911   }
912
913   /* we know the start_time of the pad data, see if we
914    * can activate the complete chain if this is a dynamic
915    * chain. We need all the headers too for this. */
916   if (pad->start_time != GST_CLOCK_TIME_NONE && pad->map.have_headers) {
917     GstOggChain *chain = pad->chain;
918
919     /* check if complete chain has start time */
920     if (chain == ogg->building_chain) {
921       GstEvent *event = NULL;
922
923       if (ogg->resync) {
924         guint64 start_time;
925
926         GST_DEBUG_OBJECT (ogg, "need to resync");
927
928         /* when we need to resync after a seek, we wait until we have received
929          * timestamps on all streams */
930         start_time = gst_ogg_demux_collect_start_time (ogg, chain);
931
932         if (start_time != G_MAXUINT64) {
933           gint64 segment_time;
934           GstSegment segment;
935
936           GST_DEBUG_OBJECT (ogg, "start_time:  %" GST_TIME_FORMAT,
937               GST_TIME_ARGS (start_time));
938
939           if (chain->segment_start < start_time)
940             segment_time =
941                 (start_time - chain->segment_start) + chain->begin_time;
942           else
943             segment_time = chain->begin_time;
944
945           /* create the newsegment event we are going to send out */
946           gst_segment_init (&segment, GST_FORMAT_TIME);
947
948           GST_PUSH_LOCK (ogg);
949           if (!ogg->pullmode && ogg->push_state == PUSH_LINEAR2) {
950             /* if we are fast forwarding to the actual seek target,
951                ensure previous frames are clipped */
952             GST_DEBUG_OBJECT (ogg,
953                 "Resynced, starting segment at %" GST_TIME_FORMAT
954                 ", start_time %" GST_TIME_FORMAT,
955                 GST_TIME_ARGS (ogg->push_seek_time_original_target),
956                 GST_TIME_ARGS (start_time));
957             segment.rate = ogg->push_seek_rate;
958             segment.start = ogg->push_seek_time_original_target;
959             segment.stop = -1;
960             segment.time = ogg->push_seek_time_original_target;
961             event = gst_event_new_segment (&segment);
962             ogg->push_state = PUSH_PLAYING;
963           } else {
964             segment.rate = ogg->segment.rate;
965             segment.applied_rate = ogg->segment.applied_rate;
966             segment.start = start_time;
967             segment.stop = chain->segment_stop;
968             segment.time = segment_time;
969             event = gst_event_new_segment (&segment);
970           }
971           GST_PUSH_UNLOCK (ogg);
972
973           ogg->resync = FALSE;
974         }
975       } else {
976         /* see if we have enough info to activate the chain, we have enough info
977          * when all streams have a valid start time. */
978         if (gst_ogg_demux_collect_chain_info (ogg, chain)) {
979           GstSegment segment;
980
981           GST_DEBUG_OBJECT (ogg, "segment_start: %" GST_TIME_FORMAT,
982               GST_TIME_ARGS (chain->segment_start));
983           GST_DEBUG_OBJECT (ogg, "segment_stop:  %" GST_TIME_FORMAT,
984               GST_TIME_ARGS (chain->segment_stop));
985           GST_DEBUG_OBJECT (ogg, "segment_time:  %" GST_TIME_FORMAT,
986               GST_TIME_ARGS (chain->begin_time));
987
988           /* create the newsegment event we are going to send out */
989           gst_segment_init (&segment, GST_FORMAT_TIME);
990           segment.rate = ogg->segment.rate;
991           segment.applied_rate = ogg->segment.applied_rate;
992           segment.start = chain->segment_start;
993           segment.stop = chain->segment_stop;
994           segment.time = chain->begin_time;
995           event = gst_event_new_segment (&segment);
996         }
997       }
998
999       if (event) {
1000         gst_event_set_seqnum (event, ogg->seqnum);
1001
1002         gst_ogg_demux_activate_chain (ogg, chain, event);
1003
1004         ogg->building_chain = NULL;
1005       }
1006     }
1007   }
1008
1009   /* if we are building a chain, store buffer for when we activate
1010    * it. This path is taken if we operate in streaming mode. */
1011   if (ogg->building_chain) {
1012     /* bos packets where stored in the header list so we can discard
1013      * them here*/
1014     if (!packet->b_o_s)
1015       ret = gst_ogg_demux_queue_data (pad, packet);
1016   }
1017   /* else we are completely streaming to the peer */
1018   else {
1019     ret = gst_ogg_demux_chain_peer (pad, packet, !ogg->pullmode);
1020   }
1021   return ret;
1022 }
1023
1024 /* flush at most @npackets from the stream layer. All packets if 
1025  * @npackets is 0;
1026  */
1027 static GstFlowReturn
1028 gst_ogg_pad_stream_out (GstOggPad * pad, gint npackets)
1029 {
1030   GstFlowReturn result = GST_FLOW_OK;
1031   gboolean done = FALSE;
1032   GstOggDemux *ogg;
1033
1034   ogg = pad->ogg;
1035
1036   while (!done) {
1037     int ret;
1038     ogg_packet packet;
1039
1040     ret = ogg_stream_packetout (&pad->map.stream, &packet);
1041     switch (ret) {
1042       case 0:
1043         GST_LOG_OBJECT (ogg, "packetout done");
1044         done = TRUE;
1045         break;
1046       case -1:
1047         GST_LOG_OBJECT (ogg, "packetout discont");
1048         if (!pad->map.is_sparse) {
1049           gst_ogg_chain_mark_discont (pad->chain);
1050         } else {
1051           gst_ogg_pad_mark_discont (pad);
1052         }
1053         break;
1054       case 1:
1055         GST_LOG_OBJECT (ogg, "packetout gave packet of size %ld", packet.bytes);
1056         result = gst_ogg_pad_submit_packet (pad, &packet);
1057         /* not linked is not a problem, it's possible that we are still
1058          * collecting headers and that we don't have exposed the pads yet */
1059         if (result == GST_FLOW_NOT_LINKED)
1060           break;
1061         else if (result <= GST_FLOW_EOS)
1062           goto could_not_submit;
1063         break;
1064       default:
1065         GST_WARNING_OBJECT (ogg,
1066             "invalid return value %d for ogg_stream_packetout, resetting stream",
1067             ret);
1068         gst_ogg_pad_reset (pad);
1069         break;
1070     }
1071     if (npackets > 0) {
1072       npackets--;
1073       done = (npackets == 0);
1074     }
1075   }
1076   return result;
1077
1078   /* ERRORS */
1079 could_not_submit:
1080   {
1081     GST_WARNING_OBJECT (ogg,
1082         "could not submit packet for stream %08x, "
1083         "error: %d", pad->map.serialno, result);
1084     gst_ogg_pad_reset (pad);
1085     return result;
1086   }
1087 }
1088
1089 static void
1090 gst_ogg_demux_setup_bisection_bounds (GstOggDemux * ogg)
1091 {
1092   if (ogg->push_last_seek_time >= ogg->push_seek_time_target) {
1093     GST_DEBUG_OBJECT (ogg, "We overshot by %" GST_TIME_FORMAT,
1094         GST_TIME_ARGS (ogg->push_last_seek_time - ogg->push_seek_time_target));
1095     ogg->push_offset1 = ogg->push_last_seek_offset;
1096     ogg->push_time1 = ogg->push_last_seek_time;
1097   } else {
1098     GST_DEBUG_OBJECT (ogg, "We undershot by %" GST_TIME_FORMAT,
1099         GST_TIME_ARGS (ogg->push_seek_time_target - ogg->push_last_seek_time));
1100     ogg->push_offset0 = ogg->push_last_seek_offset;
1101     ogg->push_time0 = ogg->push_last_seek_time;
1102   }
1103 }
1104
1105 static gint64
1106 gst_ogg_demux_estimate_bisection_target (GstOggDemux * ogg)
1107 {
1108   gint64 best;
1109   gint64 segment_bitrate;
1110
1111   /* we might not know the length of the stream in time,
1112      so push_time1 might not be set */
1113   GST_DEBUG_OBJECT (ogg,
1114       "push time 1: %" GST_TIME_FORMAT ", dbytes %" G_GINT64_FORMAT,
1115       GST_TIME_ARGS (ogg->push_time1), ogg->push_offset1 - ogg->push_offset0);
1116   if (ogg->push_time1 == GST_CLOCK_TIME_NONE) {
1117     GST_DEBUG_OBJECT (ogg,
1118         "New segment to consider: bytes %" G_GINT64_FORMAT " %" G_GINT64_FORMAT
1119         ", time %" GST_TIME_FORMAT " (open ended)", ogg->push_offset0,
1120         ogg->push_offset1, GST_TIME_ARGS (ogg->push_time0));
1121     if (ogg->push_last_seek_time == ogg->push_start_time) {
1122       /* if we're at start and don't know the end time, we can't estimate
1123          bitrate, so get the nominal declared bitrate as a failsafe, or some
1124          random constant which will be discarded after we made a (probably
1125          dire) first guess */
1126       segment_bitrate = (ogg->bitrate > 0 ? ogg->bitrate : 1000);
1127     } else {
1128       segment_bitrate =
1129           gst_util_uint64_scale (ogg->push_last_seek_offset - 0,
1130           8 * GST_SECOND, ogg->push_last_seek_time - ogg->push_start_time);
1131     }
1132     best =
1133         ogg->push_offset0 +
1134         gst_util_uint64_scale (ogg->push_seek_time_target - ogg->push_time0,
1135         segment_bitrate, 8 * GST_SECOND);
1136   } else {
1137     GST_DEBUG_OBJECT (ogg,
1138         "New segment to consider: bytes %" G_GINT64_FORMAT " %" G_GINT64_FORMAT
1139         ", time %" GST_TIME_FORMAT " %" GST_TIME_FORMAT, ogg->push_offset0,
1140         ogg->push_offset1, GST_TIME_ARGS (ogg->push_time0),
1141         GST_TIME_ARGS (ogg->push_time1));
1142     if (ogg->push_time0 == ogg->push_time1) {
1143       best = ogg->push_offset0;
1144     } else {
1145       segment_bitrate =
1146           gst_util_uint64_scale (ogg->push_offset1 - ogg->push_offset0,
1147           8 * GST_SECOND, ogg->push_time1 - ogg->push_time0);
1148       GST_DEBUG_OBJECT (ogg,
1149           "Local bitrate on the %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT
1150           " segment: %" G_GINT64_FORMAT, GST_TIME_ARGS (ogg->push_time0),
1151           GST_TIME_ARGS (ogg->push_time1), segment_bitrate);
1152       best =
1153           ogg->push_offset0 +
1154           gst_util_uint64_scale (ogg->push_seek_time_target - ogg->push_time0,
1155           segment_bitrate, 8 * GST_SECOND);
1156     }
1157   }
1158
1159   /* offset by typical page size */
1160   best -= CHUNKSIZE;
1161   if (best < ogg->push_offset0)
1162     best = ogg->push_offset0;
1163   if (best < 0)
1164     best = 0;
1165
1166   return best;
1167 }
1168
1169 static void
1170 gst_ogg_demux_record_keyframe_time (GstOggDemux * ogg, GstOggPad * pad,
1171     ogg_int64_t granpos)
1172 {
1173   gint64 kf_granule;
1174   GstClockTime kf_time;
1175
1176   kf_granule = gst_ogg_stream_granulepos_to_key_granule (&pad->map, granpos);
1177   kf_time = gst_ogg_stream_granule_to_time (&pad->map, kf_granule);
1178
1179   pad->push_kf_time = kf_time;
1180 }
1181
1182 /* returns the earliest keyframe time for all non sparse pads in the chain,
1183  * if known, and GST_CLOCK_TIME_NONE if not */
1184 static GstClockTime
1185 gst_ogg_demux_get_earliest_keyframe_time (GstOggDemux * ogg)
1186 {
1187   GstClockTime t = GST_CLOCK_TIME_NONE;
1188   GstOggChain *chain = ogg->building_chain;
1189   int i;
1190
1191   if (!chain) {
1192     GST_WARNING_OBJECT (ogg, "No chain!");
1193     return GST_CLOCK_TIME_NONE;
1194   }
1195   for (i = 0; i < chain->streams->len; i++) {
1196     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
1197
1198     if (pad->map.is_sparse)
1199       continue;
1200     if (pad->push_kf_time == GST_CLOCK_TIME_NONE)
1201       return GST_CLOCK_TIME_NONE;
1202     if (t == GST_CLOCK_TIME_NONE || pad->push_kf_time < t)
1203       t = pad->push_kf_time;
1204   }
1205
1206   return t;
1207 }
1208
1209 /* MUST be called with the push lock locked, and will unlock it
1210    regardless of return value. */
1211 static GstFlowReturn
1212 gst_ogg_demux_seek_back_after_push_duration_check_unlock (GstOggDemux * ogg)
1213 {
1214   GstEvent *event;
1215
1216   /* Get the delayed event, if any */
1217   event = ogg->push_mode_seek_delayed_event;
1218   ogg->push_mode_seek_delayed_event = NULL;
1219
1220   ogg->push_state = PUSH_PLAYING;
1221
1222   GST_PUSH_UNLOCK (ogg);
1223
1224   if (event) {
1225     /* If there is one, perform it */
1226     gst_ogg_demux_perform_seek_push (ogg, event);
1227   } else {
1228     /* If there wasn't, seek back at start to start normal playback */
1229     GST_INFO_OBJECT (ogg, "Seeking back to 0 after duration check");
1230     event = gst_event_new_seek (1.0, GST_FORMAT_BYTES,
1231         GST_SEEK_FLAG_ACCURATE | GST_SEEK_FLAG_FLUSH,
1232         GST_SEEK_TYPE_SET, 1, GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE);
1233     if (!gst_pad_push_event (ogg->sinkpad, event)) {
1234       GST_WARNING_OBJECT (ogg, "Failed seeking back to start");
1235       return GST_FLOW_ERROR;
1236     }
1237   }
1238
1239   return GST_FLOW_OK;
1240 }
1241
1242 static gboolean
1243 gst_ogg_pad_handle_push_mode_state (GstOggPad * pad, ogg_page * page)
1244 {
1245   GstOggDemux *ogg = pad->ogg;
1246   ogg_int64_t granpos = ogg_page_granulepos (page);
1247
1248   GST_PUSH_LOCK (ogg);
1249   if (granpos >= 0) {
1250     if (ogg->push_start_time == GST_CLOCK_TIME_NONE) {
1251       ogg->push_start_time =
1252           gst_ogg_stream_get_start_time_for_granulepos (&pad->map, granpos);
1253       GST_DEBUG_OBJECT (ogg, "Stream start time: %" GST_TIME_FORMAT,
1254           GST_TIME_ARGS (ogg->push_start_time));
1255     }
1256     ogg->push_time_offset =
1257         gst_ogg_stream_get_end_time_for_granulepos (&pad->map, granpos);
1258     if (ogg->push_time_offset > 0) {
1259       GST_DEBUG_OBJECT (ogg, "Bitrate since start: %" G_GUINT64_FORMAT,
1260           gst_util_uint64_scale (ogg->push_byte_offset, 8 * GST_SECOND,
1261               ogg->push_time_offset));
1262     }
1263
1264     if (ogg->push_state == PUSH_DURATION) {
1265       GstClockTime t =
1266           gst_ogg_stream_get_end_time_for_granulepos (&pad->map, granpos);
1267
1268       if (ogg->total_time == GST_CLOCK_TIME_NONE || t > ogg->total_time) {
1269         GST_DEBUG_OBJECT (ogg, "New total time: %" GST_TIME_FORMAT,
1270             GST_TIME_ARGS (t));
1271         ogg->total_time = t;
1272         ogg->push_time_length = t;
1273       }
1274
1275       /* If we were determining the duration of the stream, we're now done,
1276          and can get back to sending the original event we delayed.
1277          We stop a bit before the end of the stream, as if we get a EOS
1278          event and there is a queue2 upstream (such as when using playbin2),
1279          it will pause the task *after* we come back from the EOS handler,
1280          so we cannot prevent the pausing by issuing a seek. */
1281       if (ogg->push_byte_offset + EOS_AVOIDANCE_THRESHOLD >=
1282           ogg->push_byte_length) {
1283         GstMessage *message;
1284         GstFlowReturn res;
1285
1286         /* tell the pipeline we've just found out the duration */
1287         ogg->push_time_length = ogg->total_time;
1288         GST_INFO_OBJECT (ogg, "New duration found: %" GST_TIME_FORMAT,
1289             GST_TIME_ARGS (ogg->total_time));
1290         message =
1291             gst_message_new_duration (GST_OBJECT (ogg), GST_FORMAT_TIME,
1292             ogg->total_time);
1293         gst_element_post_message (GST_ELEMENT (ogg), message);
1294
1295         GST_DEBUG_OBJECT (ogg,
1296             "We're close enough to the end, and we're scared "
1297             "to get too close, seeking back to start");
1298
1299         res = gst_ogg_demux_seek_back_after_push_duration_check_unlock (ogg);
1300         if (res != GST_FLOW_OK)
1301           return res;
1302         return GST_FLOW_SKIP_PUSH;
1303       } else {
1304         GST_PUSH_UNLOCK (ogg);
1305       }
1306       return GST_FLOW_SKIP_PUSH;
1307     }
1308   }
1309
1310   /* if we're seeking, look at time, and decide what to do */
1311   if (ogg->push_state != PUSH_PLAYING && ogg->push_state != PUSH_LINEAR2) {
1312     GstClockTime t;
1313     gint64 best = -1;
1314     GstEvent *sevent;
1315     int res;
1316     gboolean close_enough;
1317
1318     /* ignore -1 granpos when seeking, we want to sync on a real granpos */
1319     if (granpos < 0) {
1320       GST_PUSH_UNLOCK (ogg);
1321       if (ogg_stream_pagein (&pad->map.stream, page) != 0)
1322         goto choked;
1323       return GST_FLOW_SKIP_PUSH;
1324     }
1325
1326     t = gst_ogg_stream_get_end_time_for_granulepos (&pad->map, granpos);
1327
1328     if (ogg->push_state == PUSH_BISECT1 || ogg->push_state == PUSH_BISECT2) {
1329       GstClockTime sync_time;
1330
1331       if (pad->push_sync_time == GST_CLOCK_TIME_NONE)
1332         pad->push_sync_time = t;
1333       GST_DEBUG_OBJECT (ogg, "Got timestamp %" GST_TIME_FORMAT " for %s",
1334           GST_TIME_ARGS (t), gst_ogg_stream_get_media_type (&pad->map));
1335       sync_time = gst_ogg_demux_collect_sync_time (ogg, ogg->building_chain);
1336       if (sync_time == GST_CLOCK_TIME_NONE) {
1337         GST_PUSH_UNLOCK (ogg);
1338         GST_DEBUG_OBJECT (ogg,
1339             "Not enough timing info collected for sync, waiting for more");
1340         if (ogg_stream_pagein (&pad->map.stream, page) != 0)
1341           goto choked;
1342         return GST_FLOW_SKIP_PUSH;
1343       }
1344       ogg->push_last_seek_time = sync_time;
1345
1346       GST_DEBUG_OBJECT (ogg,
1347           "Bisection just seeked at %" G_GINT64_FORMAT ", time %"
1348           GST_TIME_FORMAT ", target was %" GST_TIME_FORMAT,
1349           ogg->push_last_seek_offset,
1350           GST_TIME_ARGS (ogg->push_last_seek_time),
1351           GST_TIME_ARGS (ogg->push_seek_time_target));
1352
1353       if (ogg->push_time1 != GST_CLOCK_TIME_NONE) {
1354         GST_DEBUG_OBJECT (ogg,
1355             "Interval was %" G_GINT64_FORMAT " - %" G_GINT64_FORMAT " (%"
1356             G_GINT64_FORMAT "), time %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT
1357             " (%" GST_TIME_FORMAT ")", ogg->push_offset0, ogg->push_offset1,
1358             ogg->push_offset1 - ogg->push_offset0,
1359             GST_TIME_ARGS (ogg->push_time0), GST_TIME_ARGS (ogg->push_time1),
1360             GST_TIME_ARGS (ogg->push_time1 - ogg->push_time0));
1361       } else {
1362         GST_DEBUG_OBJECT (ogg,
1363             "Interval was %" G_GINT64_FORMAT " - %" G_GINT64_FORMAT " (%"
1364             G_GINT64_FORMAT "), time %" GST_TIME_FORMAT " - unknown",
1365             ogg->push_offset0, ogg->push_offset1,
1366             ogg->push_offset1 - ogg->push_offset0,
1367             GST_TIME_ARGS (ogg->push_time0));
1368       }
1369
1370       gst_ogg_demux_setup_bisection_bounds (ogg);
1371
1372       best = gst_ogg_demux_estimate_bisection_target (ogg);
1373
1374       if (ogg->push_seek_time_target == 0) {
1375         GST_DEBUG_OBJECT (ogg, "Seeking to 0, deemed close enough");
1376         close_enough = (ogg->push_last_seek_time == 0);
1377       } else {
1378         /* TODO: make this dependent on framerate ? */
1379         GstClockTime threshold = GST_SECOND / 2;
1380
1381         /* We want to be within half a second before the target */
1382         if (threshold > ogg->push_seek_time_target)
1383           threshold = ogg->push_seek_time_target;
1384         close_enough = ogg->push_last_seek_time < ogg->push_seek_time_target
1385             && ogg->push_last_seek_time >=
1386             ogg->push_seek_time_target - threshold;
1387         GST_DEBUG_OBJECT (ogg,
1388             "testing if we're close enough: %" GST_TIME_FORMAT " <= %"
1389             GST_TIME_FORMAT " < %" GST_TIME_FORMAT " ? %s",
1390             GST_TIME_ARGS (ogg->push_seek_time_target - threshold),
1391             GST_TIME_ARGS (ogg->push_last_seek_time),
1392             GST_TIME_ARGS (ogg->push_seek_time_target),
1393             close_enough ? "Yes" : "No");
1394       }
1395
1396       if (close_enough || best == ogg->push_last_seek_offset) {
1397         if (ogg->push_state == PUSH_BISECT1) {
1398           /* we now know the time segment we'll have to search for
1399              the second bisection */
1400           ogg->push_time0 = ogg->push_start_time;
1401           ogg->push_offset0 = 0;
1402
1403           GST_DEBUG_OBJECT (ogg,
1404               "Seek to %" GST_TIME_FORMAT
1405               " (%lx) done, now gathering pages for all non-sparse streams",
1406               GST_TIME_ARGS (ogg->push_seek_time_target), (long) granpos);
1407           ogg->push_state = PUSH_LINEAR1;
1408         } else {
1409           /* If we're asked for an accurate seek, we'll go forward till
1410              we get to the original seek target time, else we'll just drop
1411              here at the keyframe */
1412           if (ogg->push_seek_flags & GST_SEEK_FLAG_ACCURATE) {
1413             GST_INFO_OBJECT (ogg,
1414                 "Seek to keyframe at %" GST_TIME_FORMAT " done (we're at %"
1415                 GST_TIME_FORMAT "), skipping to original target (%"
1416                 GST_TIME_FORMAT ")",
1417                 GST_TIME_ARGS (ogg->push_seek_time_target),
1418                 GST_TIME_ARGS (sync_time),
1419                 GST_TIME_ARGS (ogg->push_seek_time_original_target));
1420             ogg->push_state = PUSH_LINEAR2;
1421           } else {
1422             GST_DEBUG_OBJECT (ogg, "Seek to keyframe done, playing");
1423
1424             /* we're synced to the seek target, so flush stream and stuff
1425                any queued pages into the stream so we start decoding there */
1426             ogg->push_state = PUSH_PLAYING;
1427           }
1428           GST_INFO_OBJECT (ogg, "Bisection needed %d + %d steps",
1429               ogg->push_bisection_steps[0], ogg->push_bisection_steps[1]);
1430         }
1431       }
1432     } else if (ogg->push_state == PUSH_LINEAR1) {
1433       if (pad->push_kf_time == GST_CLOCK_TIME_NONE) {
1434         GstClockTime earliest_keyframe_time;
1435
1436         gst_ogg_demux_record_keyframe_time (ogg, pad, granpos);
1437         GST_DEBUG_OBJECT (ogg,
1438             "Previous keyframe for %s stream at %" GST_TIME_FORMAT,
1439             gst_ogg_stream_get_media_type (&pad->map),
1440             GST_TIME_ARGS (pad->push_kf_time));
1441         earliest_keyframe_time = gst_ogg_demux_get_earliest_keyframe_time (ogg);
1442         if (earliest_keyframe_time != GST_CLOCK_TIME_NONE) {
1443           GST_DEBUG_OBJECT (ogg,
1444               "All non sparse streams now have a previous keyframe time,"
1445               "bisecting again to %" GST_TIME_FORMAT,
1446               GST_TIME_ARGS (earliest_keyframe_time));
1447           ogg->push_seek_time_target = earliest_keyframe_time;
1448
1449           ogg->push_state = PUSH_BISECT2;
1450           best = gst_ogg_demux_estimate_bisection_target (ogg);
1451         }
1452       }
1453     }
1454
1455     if (ogg->push_state == PUSH_BISECT1 || ogg->push_state == PUSH_BISECT2) {
1456       gint i;
1457
1458       ogg_sync_reset (&ogg->sync);
1459       for (i = 0; i < ogg->building_chain->streams->len; i++) {
1460         GstOggPad *pad =
1461             g_array_index (ogg->building_chain->streams, GstOggPad *, i);
1462
1463         pad->push_sync_time = GST_CLOCK_TIME_NONE;
1464         ogg_stream_reset (&pad->map.stream);
1465       }
1466
1467       GST_DEBUG_OBJECT (ogg,
1468           "seeking to %" G_GINT64_FORMAT " - %" G_GINT64_FORMAT, best,
1469           (gint64) - 1);
1470       /* do seek */
1471       g_assert (best != -1);
1472       ogg->push_bisection_steps[ogg->push_state == PUSH_BISECT2 ? 1 : 0]++;
1473       sevent =
1474           gst_event_new_seek (ogg->push_seek_rate, GST_FORMAT_BYTES,
1475           ogg->push_seek_flags, GST_SEEK_TYPE_SET, best,
1476           GST_SEEK_TYPE_NONE, -1);
1477
1478       GST_PUSH_UNLOCK (ogg);
1479       res = gst_pad_push_event (ogg->sinkpad, sevent);
1480       if (!res) {
1481         /* We failed to send the seek event, notify the pipeline */
1482         GST_ELEMENT_ERROR (ogg, RESOURCE, SEEK, (NULL), ("Failed to seek"));
1483         return GST_FLOW_ERROR;
1484       }
1485       return GST_FLOW_SKIP_PUSH;
1486     }
1487
1488     if (ogg->push_state != PUSH_PLAYING) {
1489       GST_PUSH_UNLOCK (ogg);
1490       return GST_FLOW_SKIP_PUSH;
1491     }
1492   }
1493   GST_PUSH_UNLOCK (ogg);
1494
1495   return GST_FLOW_OK;
1496
1497 choked:
1498   {
1499     GST_WARNING_OBJECT (ogg,
1500         "ogg stream choked on page (serial %08x), "
1501         "resetting stream", pad->map.serialno);
1502     gst_ogg_pad_reset (pad);
1503     /* we continue to recover */
1504     return GST_FLOW_SKIP_PUSH;
1505   }
1506 }
1507
1508 /* submit a page to an oggpad, this function will then submit all
1509  * the packets in the page.
1510  */
1511 static GstFlowReturn
1512 gst_ogg_pad_submit_page (GstOggPad * pad, ogg_page * page)
1513 {
1514   GstFlowReturn result = GST_FLOW_OK;
1515   GstOggDemux *ogg;
1516   gboolean continued = FALSE;
1517
1518   ogg = pad->ogg;
1519
1520   /* for negative rates we read pages backwards and must therefore be careful
1521    * with continued pages */
1522   if (ogg->segment.rate < 0.0) {
1523     gint npackets;
1524
1525     continued = ogg_page_continued (page);
1526
1527     /* number of completed packets in the page */
1528     npackets = ogg_page_packets (page);
1529     if (!continued) {
1530       /* page is not continued so it contains at least one packet start. It's
1531        * possible that no packet ends on this page (npackets == 0). In that
1532        * case, the next (continued) page(s) we kept contain the remainder of the
1533        * packets. We mark npackets=1 to make us start decoding the pages in the
1534        * remainder of the algorithm. */
1535       if (npackets == 0)
1536         npackets = 1;
1537     }
1538     GST_LOG_OBJECT (ogg, "continued: %d, %d packets", continued, npackets);
1539
1540     if (npackets == 0) {
1541       GST_LOG_OBJECT (ogg, "no decodable packets, we need a previous page");
1542       goto done;
1543     }
1544   }
1545
1546   /* keep track of time in push mode */
1547   if (!ogg->pullmode) {
1548     result = gst_ogg_pad_handle_push_mode_state (pad, page);
1549     if (result == GST_FLOW_SKIP_PUSH)
1550       return GST_FLOW_OK;
1551     if (result != GST_FLOW_OK)
1552       return result;
1553   }
1554
1555   if (ogg_stream_pagein (&pad->map.stream, page) != 0)
1556     goto choked;
1557
1558   /* flush all packets in the stream layer, this might not give a packet if
1559    * the page had no packets finishing on the page (npackets == 0). */
1560   result = gst_ogg_pad_stream_out (pad, 0);
1561
1562   if (pad->continued) {
1563     ogg_packet packet;
1564
1565     /* now send the continued pages to the stream layer */
1566     while (pad->continued) {
1567       ogg_page *p = (ogg_page *) pad->continued->data;
1568
1569       GST_LOG_OBJECT (ogg, "submitting continued page %p", p);
1570       if (ogg_stream_pagein (&pad->map.stream, p) != 0)
1571         goto choked;
1572
1573       pad->continued = g_list_delete_link (pad->continued, pad->continued);
1574
1575       /* free the page */
1576       gst_ogg_page_free (p);
1577     }
1578
1579     GST_LOG_OBJECT (ogg, "flushing last continued packet");
1580     /* flush 1 continued packet in the stream layer */
1581     result = gst_ogg_pad_stream_out (pad, 1);
1582
1583     /* flush all remaining packets, we pushed them in the previous round.
1584      * We don't use _reset() because we still want to get the discont when
1585      * we submit a next page. */
1586     while (ogg_stream_packetout (&pad->map.stream, &packet) != 0);
1587   }
1588
1589 done:
1590   /* keep continued pages (only in reverse mode) */
1591   if (continued) {
1592     ogg_page *p = gst_ogg_page_copy (page);
1593
1594     GST_LOG_OBJECT (ogg, "keeping continued page %p", p);
1595     pad->continued = g_list_prepend (pad->continued, p);
1596   }
1597
1598   return result;
1599
1600 choked:
1601   {
1602     GST_WARNING_OBJECT (ogg,
1603         "ogg stream choked on page (serial %08x), "
1604         "resetting stream", pad->map.serialno);
1605     gst_ogg_pad_reset (pad);
1606     /* we continue to recover */
1607     return GST_FLOW_OK;
1608   }
1609 }
1610
1611
1612 static GstOggChain *
1613 gst_ogg_chain_new (GstOggDemux * ogg)
1614 {
1615   GstOggChain *chain = g_slice_new0 (GstOggChain);
1616
1617   GST_DEBUG_OBJECT (ogg, "creating new chain %p", chain);
1618   chain->ogg = ogg;
1619   chain->offset = -1;
1620   chain->bytes = -1;
1621   chain->have_bos = FALSE;
1622   chain->streams = g_array_new (FALSE, TRUE, sizeof (GstOggPad *));
1623   chain->begin_time = GST_CLOCK_TIME_NONE;
1624   chain->segment_start = GST_CLOCK_TIME_NONE;
1625   chain->segment_stop = GST_CLOCK_TIME_NONE;
1626   chain->total_time = GST_CLOCK_TIME_NONE;
1627
1628   return chain;
1629 }
1630
1631 static void
1632 gst_ogg_chain_free (GstOggChain * chain)
1633 {
1634   gint i;
1635
1636   for (i = 0; i < chain->streams->len; i++) {
1637     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
1638
1639     gst_object_unref (pad);
1640   }
1641   g_array_free (chain->streams, TRUE);
1642   g_slice_free (GstOggChain, chain);
1643 }
1644
1645 static void
1646 gst_ogg_pad_mark_discont (GstOggPad * pad)
1647 {
1648   pad->discont = TRUE;
1649   pad->map.last_size = 0;
1650 }
1651
1652 static void
1653 gst_ogg_chain_mark_discont (GstOggChain * chain)
1654 {
1655   gint i;
1656
1657   for (i = 0; i < chain->streams->len; i++) {
1658     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
1659
1660     gst_ogg_pad_mark_discont (pad);
1661   }
1662 }
1663
1664 static void
1665 gst_ogg_chain_reset (GstOggChain * chain)
1666 {
1667   gint i;
1668
1669   for (i = 0; i < chain->streams->len; i++) {
1670     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
1671
1672     gst_ogg_pad_reset (pad);
1673   }
1674 }
1675
1676 static GstOggPad *
1677 gst_ogg_chain_new_stream (GstOggChain * chain, guint32 serialno)
1678 {
1679   GstOggPad *ret;
1680   GstTagList *list;
1681   gchar *name;
1682
1683   GST_DEBUG_OBJECT (chain->ogg,
1684       "creating new stream %08x in chain %p", serialno, chain);
1685
1686   name = g_strdup_printf ("src_%08x", serialno);
1687   ret = g_object_new (GST_TYPE_OGG_PAD, "name", name, NULL);
1688   g_free (name);
1689   /* we own this one */
1690   gst_object_ref_sink (ret);
1691
1692   GST_PAD_DIRECTION (ret) = GST_PAD_SRC;
1693   gst_ogg_pad_mark_discont (ret);
1694
1695   ret->chain = chain;
1696   ret->ogg = chain->ogg;
1697
1698   ret->map.serialno = serialno;
1699   if (ogg_stream_init (&ret->map.stream, serialno) != 0)
1700     goto init_failed;
1701
1702   /* FIXME: either do something with it or remove it */
1703   list = gst_tag_list_new_empty ();
1704   gst_tag_list_add (list, GST_TAG_MERGE_REPLACE, GST_TAG_SERIAL, serialno,
1705       NULL);
1706   gst_tag_list_free (list);
1707
1708   GST_DEBUG_OBJECT (chain->ogg,
1709       "created new ogg src %p for stream with serial %08x", ret, serialno);
1710
1711   g_array_append_val (chain->streams, ret);
1712   gst_pad_set_active (GST_PAD_CAST (ret), TRUE);
1713
1714   return ret;
1715
1716   /* ERRORS */
1717 init_failed:
1718   {
1719     GST_ERROR ("Could not initialize ogg_stream struct for serial %08x",
1720         serialno);
1721     gst_object_unref (ret);
1722     return NULL;
1723   }
1724 }
1725
1726 static GstOggPad *
1727 gst_ogg_chain_get_stream (GstOggChain * chain, guint32 serialno)
1728 {
1729   gint i;
1730
1731   for (i = 0; i < chain->streams->len; i++) {
1732     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
1733
1734     if (pad->map.serialno == serialno)
1735       return pad;
1736   }
1737   return NULL;
1738 }
1739
1740 static gboolean
1741 gst_ogg_chain_has_stream (GstOggChain * chain, guint32 serialno)
1742 {
1743   return gst_ogg_chain_get_stream (chain, serialno) != NULL;
1744 }
1745
1746 /* signals and args */
1747 enum
1748 {
1749   /* FILL ME */
1750   LAST_SIGNAL
1751 };
1752
1753 enum
1754 {
1755   ARG_0
1756       /* FILL ME */
1757 };
1758
1759 static GstStaticPadTemplate ogg_demux_src_template_factory =
1760 GST_STATIC_PAD_TEMPLATE ("src_%08x",
1761     GST_PAD_SRC,
1762     GST_PAD_SOMETIMES,
1763     GST_STATIC_CAPS_ANY);
1764
1765 static GstStaticPadTemplate ogg_demux_sink_template_factory =
1766     GST_STATIC_PAD_TEMPLATE ("sink",
1767     GST_PAD_SINK,
1768     GST_PAD_ALWAYS,
1769     GST_STATIC_CAPS ("application/ogg; application/x-annodex")
1770     );
1771
1772 static void gst_ogg_demux_finalize (GObject * object);
1773
1774 static GstFlowReturn gst_ogg_demux_read_chain (GstOggDemux * ogg,
1775     GstOggChain ** chain);
1776 static GstFlowReturn gst_ogg_demux_read_end_chain (GstOggDemux * ogg,
1777     GstOggChain * chain);
1778
1779 static gboolean gst_ogg_demux_sink_event (GstPad * pad, GstObject * parent,
1780     GstEvent * event);
1781 static void gst_ogg_demux_loop (GstOggPad * pad);
1782 static GstFlowReturn gst_ogg_demux_chain (GstPad * pad, GstObject * parent,
1783     GstBuffer * buffer);
1784 static gboolean gst_ogg_demux_sink_activate (GstPad * sinkpad,
1785     GstObject * parent);
1786 static gboolean gst_ogg_demux_sink_activate_mode (GstPad * sinkpad,
1787     GstObject * parent, GstPadMode mode, gboolean active);
1788 static GstStateChangeReturn gst_ogg_demux_change_state (GstElement * element,
1789     GstStateChange transition);
1790
1791 static void gst_ogg_print (GstOggDemux * demux);
1792
1793 #define gst_ogg_demux_parent_class parent_class
1794 G_DEFINE_TYPE (GstOggDemux, gst_ogg_demux, GST_TYPE_ELEMENT);
1795
1796 static void
1797 gst_ogg_demux_class_init (GstOggDemuxClass * klass)
1798 {
1799   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
1800   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1801
1802   gst_element_class_set_details_simple (gstelement_class,
1803       "Ogg demuxer", "Codec/Demuxer",
1804       "demux ogg streams (info about ogg: http://xiph.org)",
1805       "Wim Taymans <wim@fluendo.com>");
1806
1807   gst_element_class_add_pad_template (gstelement_class,
1808       gst_static_pad_template_get (&ogg_demux_sink_template_factory));
1809   gst_element_class_add_pad_template (gstelement_class,
1810       gst_static_pad_template_get (&ogg_demux_src_template_factory));
1811
1812   gstelement_class->change_state = gst_ogg_demux_change_state;
1813   gstelement_class->send_event = gst_ogg_demux_receive_event;
1814
1815   gobject_class->finalize = gst_ogg_demux_finalize;
1816 }
1817
1818 static void
1819 gst_ogg_demux_init (GstOggDemux * ogg)
1820 {
1821   /* create the sink pad */
1822   ogg->sinkpad =
1823       gst_pad_new_from_static_template (&ogg_demux_sink_template_factory,
1824       "sink");
1825
1826   gst_pad_set_event_function (ogg->sinkpad, gst_ogg_demux_sink_event);
1827   gst_pad_set_chain_function (ogg->sinkpad, gst_ogg_demux_chain);
1828   gst_pad_set_activate_function (ogg->sinkpad, gst_ogg_demux_sink_activate);
1829   gst_pad_set_activatemode_function (ogg->sinkpad,
1830       gst_ogg_demux_sink_activate_mode);
1831   gst_element_add_pad (GST_ELEMENT (ogg), ogg->sinkpad);
1832
1833   ogg->chain_lock = g_mutex_new ();
1834   ogg->push_lock = g_mutex_new ();
1835   ogg->chains = g_array_new (FALSE, TRUE, sizeof (GstOggChain *));
1836
1837   ogg->newsegment = NULL;
1838 }
1839
1840 static void
1841 gst_ogg_demux_finalize (GObject * object)
1842 {
1843   GstOggDemux *ogg;
1844
1845   ogg = GST_OGG_DEMUX (object);
1846
1847   g_array_free (ogg->chains, TRUE);
1848   g_mutex_free (ogg->chain_lock);
1849   g_mutex_free (ogg->push_lock);
1850   ogg_sync_clear (&ogg->sync);
1851
1852   if (ogg->newsegment)
1853     gst_event_unref (ogg->newsegment);
1854
1855   G_OBJECT_CLASS (parent_class)->finalize (object);
1856 }
1857
1858 static void
1859 gst_ogg_demux_reset_streams (GstOggDemux * ogg)
1860 {
1861   GstOggChain *chain;
1862   guint i;
1863
1864   chain = ogg->current_chain;
1865   if (chain == NULL)
1866     return;
1867
1868   for (i = 0; i < chain->streams->len; i++) {
1869     GstOggPad *stream = g_array_index (chain->streams, GstOggPad *, i);
1870
1871     stream->start_time = -1;
1872     stream->map.accumulated_granule = 0;
1873   }
1874   ogg->building_chain = chain;
1875   GST_DEBUG_OBJECT (ogg, "Resetting current chain");
1876   ogg->current_chain = NULL;
1877   ogg->resync = TRUE;
1878 }
1879
1880 static gboolean
1881 gst_ogg_demux_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1882 {
1883   gboolean res;
1884   GstOggDemux *ogg;
1885
1886   ogg = GST_OGG_DEMUX (parent);
1887
1888   switch (GST_EVENT_TYPE (event)) {
1889     case GST_EVENT_FLUSH_START:
1890       res = gst_ogg_demux_send_event (ogg, event);
1891       break;
1892     case GST_EVENT_FLUSH_STOP:
1893       GST_DEBUG_OBJECT (ogg, "got a flush stop event");
1894       ogg_sync_reset (&ogg->sync);
1895       res = gst_ogg_demux_send_event (ogg, event);
1896       if (ogg->pullmode || ogg->push_state != PUSH_DURATION) {
1897         /* it's starting to feel reaaaally dirty :(
1898            if we're on a spliced seek to get duration, don't reset streams,
1899            we'll need them for the delayed seek */
1900         gst_ogg_demux_reset_streams (ogg);
1901       }
1902       break;
1903     case GST_EVENT_SEGMENT:
1904       GST_DEBUG_OBJECT (ogg, "got a new segment event");
1905       {
1906         GstSegment segment;
1907
1908         gst_event_copy_segment (event, &segment);
1909
1910         if (segment.format == GST_FORMAT_BYTES) {
1911           GST_PUSH_LOCK (ogg);
1912           ogg->push_byte_offset = segment.start;
1913           ogg->push_last_seek_offset = segment.start;
1914           GST_PUSH_UNLOCK (ogg);
1915         } else {
1916           GST_WARNING_OBJECT (ogg, "unexpected segment format: %s",
1917               gst_format_get_name (segment.format));
1918         }
1919       }
1920       gst_event_unref (event);
1921       res = TRUE;
1922       break;
1923     case GST_EVENT_EOS:
1924     {
1925       GST_DEBUG_OBJECT (ogg, "got an EOS event");
1926 #if 0
1927       /* This would be what is needed (recover from EOS by going on to
1928          the next step (issue the delayed seek)), but it does not work
1929          if there is a queue2 upstream - see more details comment in
1930          gst_ogg_pad_submit_page.
1931          If I could find a way to bypass queue2 behavior, this should
1932          be enabled. */
1933       GST_PUSH_LOCK (ogg);
1934       if (ogg->push_state == PUSH_DURATION) {
1935         GST_DEBUG_OBJECT (ogg, "Got EOS while determining length");
1936         res = gst_ogg_demux_seek_back_after_push_duration_check_unlock (ogg);
1937         if (res != GST_FLOW_OK) {
1938           GST_DEBUG_OBJECT (ogg, "Error seeking back after duration check: %d",
1939               res);
1940         }
1941         break;
1942       }
1943       GST_PUSH_UNLOCK (ogg);
1944 #endif
1945       res = gst_ogg_demux_send_event (ogg, event);
1946       if (ogg->current_chain == NULL) {
1947         GST_ELEMENT_ERROR (ogg, STREAM, DEMUX, (NULL),
1948             ("can't get first chain"));
1949       }
1950       break;
1951     }
1952     default:
1953       res = gst_ogg_demux_send_event (ogg, event);
1954       break;
1955   }
1956
1957   return res;
1958 }
1959
1960 /* submit the given buffer to the ogg sync */
1961 static GstFlowReturn
1962 gst_ogg_demux_submit_buffer (GstOggDemux * ogg, GstBuffer * buffer)
1963 {
1964   gsize size;
1965   gchar *oggbuffer;
1966   GstFlowReturn ret = GST_FLOW_OK;
1967
1968   size = gst_buffer_get_size (buffer);
1969   GST_DEBUG_OBJECT (ogg, "submitting %" G_GSIZE_FORMAT " bytes", size);
1970   if (G_UNLIKELY (size == 0))
1971     goto done;
1972
1973   oggbuffer = ogg_sync_buffer (&ogg->sync, size);
1974   if (G_UNLIKELY (oggbuffer == NULL))
1975     goto no_buffer;
1976
1977   gst_buffer_extract (buffer, 0, oggbuffer, size);
1978
1979   if (G_UNLIKELY (ogg_sync_wrote (&ogg->sync, size) < 0))
1980     goto write_failed;
1981
1982   if (!ogg->pullmode) {
1983     GST_PUSH_LOCK (ogg);
1984     ogg->push_byte_offset += size;
1985     GST_PUSH_UNLOCK (ogg);
1986   }
1987
1988 done:
1989   gst_buffer_unref (buffer);
1990
1991   return ret;
1992
1993   /* ERRORS */
1994 no_buffer:
1995   {
1996     GST_ELEMENT_ERROR (ogg, STREAM, DECODE,
1997         (NULL), ("failed to get ogg sync buffer"));
1998     ret = GST_FLOW_ERROR;
1999     goto done;
2000   }
2001 write_failed:
2002   {
2003     GST_ELEMENT_ERROR (ogg, STREAM, DECODE, (NULL),
2004         ("failed to write %" G_GSIZE_FORMAT " bytes to the sync buffer", size));
2005     ret = GST_FLOW_ERROR;
2006     goto done;
2007   }
2008 }
2009
2010 /* in random access mode this code updates the current read position
2011  * and resets the ogg sync buffer so that the next read will happen
2012  * from this new location.
2013  */
2014 static void
2015 gst_ogg_demux_seek (GstOggDemux * ogg, gint64 offset)
2016 {
2017   GST_LOG_OBJECT (ogg, "seeking to %" G_GINT64_FORMAT, offset);
2018
2019   ogg->offset = offset;
2020   ogg->read_offset = offset;
2021   ogg_sync_reset (&ogg->sync);
2022 }
2023
2024 /* read more data from the current offset and submit to
2025  * the ogg sync layer.
2026  */
2027 static GstFlowReturn
2028 gst_ogg_demux_get_data (GstOggDemux * ogg, gint64 end_offset)
2029 {
2030   GstFlowReturn ret;
2031   GstBuffer *buffer;
2032
2033   GST_LOG_OBJECT (ogg,
2034       "get data %" G_GINT64_FORMAT " %" G_GINT64_FORMAT " %" G_GINT64_FORMAT,
2035       ogg->read_offset, ogg->length, end_offset);
2036
2037   if (end_offset > 0 && ogg->read_offset >= end_offset)
2038     goto boundary_reached;
2039
2040   if (ogg->read_offset == ogg->length)
2041     goto eos;
2042
2043   ret = gst_pad_pull_range (ogg->sinkpad, ogg->read_offset, CHUNKSIZE, &buffer);
2044   if (ret != GST_FLOW_OK)
2045     goto error;
2046
2047   ogg->read_offset += gst_buffer_get_size (buffer);
2048
2049   ret = gst_ogg_demux_submit_buffer (ogg, buffer);
2050
2051   return ret;
2052
2053   /* ERROR */
2054 boundary_reached:
2055   {
2056     GST_LOG_OBJECT (ogg, "reached boundary");
2057     return GST_FLOW_LIMIT;
2058   }
2059 eos:
2060   {
2061     GST_LOG_OBJECT (ogg, "reached EOS");
2062     return GST_FLOW_EOS;
2063   }
2064 error:
2065   {
2066     GST_WARNING_OBJECT (ogg, "got %d (%s) from pull range", ret,
2067         gst_flow_get_name (ret));
2068     return ret;
2069   }
2070 }
2071
2072 /* Read the next page from the current offset.
2073  * boundary: number of bytes ahead we allow looking for;
2074  * -1 if no boundary
2075  *
2076  * @offset will contain the offset the next page starts at when this function
2077  * returns GST_FLOW_OK.
2078  *
2079  * GST_FLOW_EOS is returned on EOS.
2080  *
2081  * GST_FLOW_LIMIT is returned when we did not find a page before the
2082  * boundary. If @boundary is -1, this is never returned.
2083  *
2084  * Any other error returned while retrieving data from the peer is returned as
2085  * is.
2086  */
2087 static GstFlowReturn
2088 gst_ogg_demux_get_next_page (GstOggDemux * ogg, ogg_page * og,
2089     gint64 boundary, gint64 * offset)
2090 {
2091   gint64 end_offset = -1;
2092   GstFlowReturn ret;
2093
2094   GST_LOG_OBJECT (ogg,
2095       "get next page, current offset %" G_GINT64_FORMAT ", bytes boundary %"
2096       G_GINT64_FORMAT, ogg->offset, boundary);
2097
2098   if (boundary >= 0)
2099     end_offset = ogg->offset + boundary;
2100
2101   while (TRUE) {
2102     glong more;
2103
2104     if (end_offset > 0 && ogg->offset >= end_offset)
2105       goto boundary_reached;
2106
2107     more = ogg_sync_pageseek (&ogg->sync, og);
2108
2109     GST_LOG_OBJECT (ogg, "pageseek gave %ld", more);
2110
2111     if (more < 0) {
2112       /* skipped n bytes */
2113       ogg->offset -= more;
2114       GST_LOG_OBJECT (ogg, "skipped %ld bytes, offset %" G_GINT64_FORMAT,
2115           more, ogg->offset);
2116     } else if (more == 0) {
2117       /* we need more data */
2118       if (boundary == 0)
2119         goto boundary_reached;
2120
2121       GST_LOG_OBJECT (ogg, "need more data");
2122       ret = gst_ogg_demux_get_data (ogg, end_offset);
2123       if (ret != GST_FLOW_OK)
2124         break;
2125     } else {
2126       gint64 res_offset = ogg->offset;
2127
2128       /* got a page.  Return the offset at the page beginning,
2129          advance the internal offset past the page end */
2130       if (offset)
2131         *offset = res_offset;
2132       ret = GST_FLOW_OK;
2133
2134       ogg->offset += more;
2135
2136       GST_LOG_OBJECT (ogg,
2137           "got page at %" G_GINT64_FORMAT ", serial %08x, end at %"
2138           G_GINT64_FORMAT ", granule %" G_GINT64_FORMAT, res_offset,
2139           ogg_page_serialno (og), ogg->offset,
2140           (gint64) ogg_page_granulepos (og));
2141       break;
2142     }
2143   }
2144   GST_LOG_OBJECT (ogg, "returning %d", ret);
2145
2146   return ret;
2147
2148   /* ERRORS */
2149 boundary_reached:
2150   {
2151     GST_LOG_OBJECT (ogg,
2152         "offset %" G_GINT64_FORMAT " >= end_offset %" G_GINT64_FORMAT,
2153         ogg->offset, end_offset);
2154     return GST_FLOW_LIMIT;
2155   }
2156 }
2157
2158 /* from the current offset, find the previous page, seeking backwards
2159  * until we find the page. 
2160  */
2161 static GstFlowReturn
2162 gst_ogg_demux_get_prev_page (GstOggDemux * ogg, ogg_page * og, gint64 * offset)
2163 {
2164   GstFlowReturn ret;
2165   gint64 begin = ogg->offset;
2166   gint64 end = begin;
2167   gint64 cur_offset = -1;
2168
2169   GST_LOG_OBJECT (ogg, "getting page before %" G_GINT64_FORMAT, begin);
2170
2171   while (cur_offset == -1) {
2172     begin -= CHUNKSIZE;
2173     if (begin < 0)
2174       begin = 0;
2175
2176     /* seek CHUNKSIZE back */
2177     gst_ogg_demux_seek (ogg, begin);
2178
2179     /* now continue reading until we run out of data, if we find a page
2180      * start, we save it. It might not be the final page as there could be
2181      * another page after this one. */
2182     while (ogg->offset < end) {
2183       gint64 new_offset;
2184
2185       ret =
2186           gst_ogg_demux_get_next_page (ogg, og, end - ogg->offset, &new_offset);
2187       /* we hit the upper limit, offset contains the last page start */
2188       if (ret == GST_FLOW_LIMIT) {
2189         GST_LOG_OBJECT (ogg, "hit limit");
2190         break;
2191       }
2192       /* something went wrong */
2193       if (ret == GST_FLOW_EOS) {
2194         new_offset = 0;
2195         GST_LOG_OBJECT (ogg, "got unexpected");
2196       } else if (ret != GST_FLOW_OK) {
2197         GST_LOG_OBJECT (ogg, "got error %d", ret);
2198         return ret;
2199       }
2200
2201       GST_LOG_OBJECT (ogg, "found page at %" G_GINT64_FORMAT, new_offset);
2202
2203       /* offset is next page start */
2204       cur_offset = new_offset;
2205     }
2206   }
2207
2208   GST_LOG_OBJECT (ogg, "found previous page at %" G_GINT64_FORMAT, cur_offset);
2209
2210   /* we have the offset.  Actually snork and hold the page now */
2211   gst_ogg_demux_seek (ogg, cur_offset);
2212   ret = gst_ogg_demux_get_next_page (ogg, og, -1, NULL);
2213   if (ret != GST_FLOW_OK) {
2214     GST_WARNING_OBJECT (ogg, "can't get last page at %" G_GINT64_FORMAT,
2215         cur_offset);
2216     /* this shouldn't be possible */
2217     return ret;
2218   }
2219
2220   if (offset)
2221     *offset = cur_offset;
2222
2223   return ret;
2224 }
2225
2226 static gboolean
2227 gst_ogg_demux_deactivate_current_chain (GstOggDemux * ogg)
2228 {
2229   gint i;
2230   GstOggChain *chain = ogg->current_chain;
2231
2232   if (chain == NULL)
2233     return TRUE;
2234
2235   GST_DEBUG_OBJECT (ogg, "deactivating chain %p", chain);
2236
2237   /* send EOS on all the pads */
2238   for (i = 0; i < chain->streams->len; i++) {
2239     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
2240     GstEvent *event;
2241
2242     if (!pad->added)
2243       continue;
2244
2245     event = gst_event_new_eos ();
2246     gst_event_set_seqnum (event, ogg->seqnum);
2247     gst_pad_push_event (GST_PAD_CAST (pad), event);
2248
2249     GST_DEBUG_OBJECT (ogg, "removing pad %" GST_PTR_FORMAT, pad);
2250
2251     /* deactivate first */
2252     gst_pad_set_active (GST_PAD_CAST (pad), FALSE);
2253
2254     gst_element_remove_pad (GST_ELEMENT (ogg), GST_PAD_CAST (pad));
2255
2256     pad->added = FALSE;
2257   }
2258   /* With push mode seeking implemented, we can now seek back to the chain,
2259      so we do not destroy it */
2260   GST_DEBUG_OBJECT (ogg, "Resetting current chain");
2261   ogg->current_chain = NULL;
2262
2263   return TRUE;
2264 }
2265
2266 GstCaps *
2267 gst_ogg_demux_set_header_on_caps (GstOggDemux * ogg, GstCaps * caps,
2268     GList * headers)
2269 {
2270   GstStructure *structure;
2271   GValue array = { 0 };
2272
2273   GST_LOG_OBJECT (ogg, "caps: %" GST_PTR_FORMAT, caps);
2274
2275   if (G_UNLIKELY (!caps))
2276     return NULL;
2277   if (G_UNLIKELY (!headers))
2278     return NULL;
2279
2280   caps = gst_caps_make_writable (caps);
2281   structure = gst_caps_get_structure (caps, 0);
2282
2283   g_value_init (&array, GST_TYPE_ARRAY);
2284
2285   while (headers) {
2286     GValue value = { 0 };
2287     GstBuffer *buffer;
2288     ogg_packet *op = headers->data;
2289     g_assert (op);
2290     buffer = gst_buffer_new_and_alloc (op->bytes);
2291     if (op->bytes)
2292       gst_buffer_fill (buffer, 0, op->packet, op->bytes);
2293     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_IN_CAPS);
2294     g_value_init (&value, GST_TYPE_BUFFER);
2295     gst_value_take_buffer (&value, buffer);
2296     gst_value_array_append_value (&array, &value);
2297     g_value_unset (&value);
2298     headers = headers->next;
2299   }
2300
2301   gst_structure_set_value (structure, "streamheader", &array);
2302   g_value_unset (&array);
2303   GST_LOG_OBJECT (ogg, "here are the newly set caps: %" GST_PTR_FORMAT, caps);
2304
2305   return caps;
2306 }
2307
2308 static void
2309 gst_ogg_demux_push_queued_buffers (GstOggDemux * ogg, GstOggPad * pad)
2310 {
2311   GList *walk;
2312
2313   /* push queued packets */
2314   for (walk = pad->map.queued; walk; walk = g_list_next (walk)) {
2315     ogg_packet *p = walk->data;
2316
2317     gst_ogg_demux_chain_peer (pad, p, TRUE);
2318     _ogg_packet_free (p);
2319   }
2320   /* and free the queued buffers */
2321   g_list_free (pad->map.queued);
2322   pad->map.queued = NULL;
2323 }
2324
2325 static gboolean
2326 gst_ogg_demux_activate_chain (GstOggDemux * ogg, GstOggChain * chain,
2327     GstEvent * event)
2328 {
2329   gint i;
2330   gint bitrate, idx_bitrate;
2331
2332   g_return_val_if_fail (chain != NULL, FALSE);
2333
2334   if (chain == ogg->current_chain) {
2335     if (event)
2336       gst_event_unref (event);
2337
2338     for (i = 0; i < chain->streams->len; i++) {
2339       GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
2340       gst_ogg_demux_push_queued_buffers (ogg, pad);
2341     }
2342     return TRUE;
2343   }
2344
2345
2346   GST_DEBUG_OBJECT (ogg, "activating chain %p", chain);
2347
2348   bitrate = idx_bitrate = 0;
2349
2350   /* first add the pads */
2351   for (i = 0; i < chain->streams->len; i++) {
2352     GstOggPad *pad;
2353
2354     pad = g_array_index (chain->streams, GstOggPad *, i);
2355
2356     if (pad->map.idx_bitrate)
2357       idx_bitrate = MAX (idx_bitrate, pad->map.idx_bitrate);
2358
2359     bitrate += pad->map.bitrate;
2360
2361     /* mark discont */
2362     gst_ogg_pad_mark_discont (pad);
2363     pad->last_ret = GST_FLOW_OK;
2364
2365     if (pad->map.is_skeleton || pad->added
2366         || !gst_pad_has_current_caps (GST_PAD_CAST (pad)))
2367       continue;
2368
2369     GST_DEBUG_OBJECT (ogg, "adding pad %" GST_PTR_FORMAT, pad);
2370
2371     /* activate first */
2372     gst_pad_set_active (GST_PAD_CAST (pad), TRUE);
2373
2374     gst_element_add_pad (GST_ELEMENT (ogg), GST_PAD_CAST (pad));
2375     pad->added = TRUE;
2376   }
2377   /* prefer the index bitrate over the ones encoded in the streams */
2378   ogg->bitrate = (idx_bitrate ? idx_bitrate : bitrate);
2379
2380   /* after adding the new pads, remove the old pads */
2381   gst_ogg_demux_deactivate_current_chain (ogg);
2382
2383   GST_DEBUG_OBJECT (ogg, "Setting current chain to %p", chain);
2384   ogg->current_chain = chain;
2385
2386   /* we are finished now */
2387   gst_element_no_more_pads (GST_ELEMENT (ogg));
2388
2389   /* FIXME, must be sent from the streaming thread */
2390   if (event) {
2391     GstTagList *tags;
2392
2393     gst_ogg_demux_send_event (ogg, event);
2394
2395     tags = gst_tag_list_new (GST_TAG_CONTAINER_FORMAT, "Ogg", NULL);
2396     gst_ogg_demux_send_event (ogg, gst_event_new_tag (tags));
2397   }
2398
2399   GST_DEBUG_OBJECT (ogg, "starting chain");
2400
2401   /* then send out any headers and queued packets */
2402   for (i = 0; i < chain->streams->len; i++) {
2403     GList *walk;
2404     GstOggPad *pad;
2405
2406     pad = g_array_index (chain->streams, GstOggPad *, i);
2407
2408     /* FIXME also streaming thread */
2409     if (pad->map.taglist) {
2410       GST_DEBUG_OBJECT (ogg, "pushing tags");
2411       gst_pad_push_event (GST_PAD_CAST (pad),
2412           gst_event_new_tag (pad->map.taglist));
2413       pad->map.taglist = NULL;
2414     }
2415
2416     /* Set headers on caps */
2417     pad->map.caps =
2418         gst_ogg_demux_set_header_on_caps (ogg, pad->map.caps, pad->map.headers);
2419     gst_pad_set_caps (GST_PAD_CAST (pad), pad->map.caps);
2420
2421     GST_DEBUG_OBJECT (ogg, "pushing headers");
2422     /* push headers */
2423     for (walk = pad->map.headers; walk; walk = g_list_next (walk)) {
2424       ogg_packet *p = walk->data;
2425
2426       gst_ogg_demux_chain_peer (pad, p, TRUE);
2427     }
2428
2429     GST_DEBUG_OBJECT (ogg, "pushing queued buffers");
2430     gst_ogg_demux_push_queued_buffers (ogg, pad);
2431   }
2432   return TRUE;
2433 }
2434
2435 static gboolean
2436 do_binary_search (GstOggDemux * ogg, GstOggChain * chain, gint64 begin,
2437     gint64 end, gint64 begintime, gint64 endtime, gint64 target,
2438     gint64 * offset)
2439 {
2440   gint64 best;
2441   GstFlowReturn ret;
2442   gint64 result = 0;
2443
2444   best = begin;
2445
2446   GST_DEBUG_OBJECT (ogg,
2447       "chain offset %" G_GINT64_FORMAT ", end offset %" G_GINT64_FORMAT,
2448       begin, end);
2449   GST_DEBUG_OBJECT (ogg,
2450       "chain begin time %" GST_TIME_FORMAT ", end time %" GST_TIME_FORMAT,
2451       GST_TIME_ARGS (begintime), GST_TIME_ARGS (endtime));
2452   GST_DEBUG_OBJECT (ogg, "target %" GST_TIME_FORMAT, GST_TIME_ARGS (target));
2453
2454   /* perform the seek */
2455   while (begin < end) {
2456     gint64 bisect;
2457
2458     if ((end - begin < CHUNKSIZE) || (endtime == begintime)) {
2459       bisect = begin;
2460     } else {
2461       /* take a (pretty decent) guess, avoiding overflow */
2462       gint64 rate = (end - begin) * GST_MSECOND / (endtime - begintime);
2463
2464       bisect = (target - begintime) / GST_MSECOND * rate + begin - CHUNKSIZE;
2465
2466       if (bisect <= begin)
2467         bisect = begin;
2468       GST_DEBUG_OBJECT (ogg, "Initial guess: %" G_GINT64_FORMAT, bisect);
2469     }
2470     gst_ogg_demux_seek (ogg, bisect);
2471
2472     while (begin < end) {
2473       ogg_page og;
2474
2475       GST_DEBUG_OBJECT (ogg,
2476           "after seek, bisect %" G_GINT64_FORMAT ", begin %" G_GINT64_FORMAT
2477           ", end %" G_GINT64_FORMAT, bisect, begin, end);
2478
2479       ret = gst_ogg_demux_get_next_page (ogg, &og, end - ogg->offset, &result);
2480       GST_LOG_OBJECT (ogg, "looking for next page returned %" G_GINT64_FORMAT,
2481           result);
2482
2483       if (ret == GST_FLOW_LIMIT) {
2484         /* we hit the upper limit, go back a bit */
2485         if (bisect <= begin + 1) {
2486           end = begin;          /* found it */
2487         } else {
2488           if (bisect == 0)
2489             goto seek_error;
2490
2491           bisect -= CHUNKSIZE;
2492           if (bisect <= begin)
2493             bisect = begin + 1;
2494
2495           gst_ogg_demux_seek (ogg, bisect);
2496         }
2497       } else if (ret == GST_FLOW_OK) {
2498         /* found offset of next ogg page */
2499         gint64 granulepos;
2500         GstClockTime granuletime;
2501         GstOggPad *pad;
2502
2503         /* get the granulepos */
2504         GST_LOG_OBJECT (ogg, "found next ogg page at %" G_GINT64_FORMAT,
2505             result);
2506         granulepos = ogg_page_granulepos (&og);
2507         if (granulepos == -1) {
2508           GST_LOG_OBJECT (ogg, "granulepos of next page is -1");
2509           continue;
2510         }
2511
2512         /* get the stream */
2513         pad = gst_ogg_chain_get_stream (chain, ogg_page_serialno (&og));
2514         if (pad == NULL || pad->map.is_skeleton)
2515           continue;
2516
2517         /* convert granulepos to time */
2518         granuletime = gst_ogg_stream_get_end_time_for_granulepos (&pad->map,
2519             granulepos);
2520         if (granuletime < pad->start_time)
2521           continue;
2522
2523         GST_LOG_OBJECT (ogg, "granulepos %" G_GINT64_FORMAT " maps to time %"
2524             GST_TIME_FORMAT, granulepos, GST_TIME_ARGS (granuletime));
2525
2526         granuletime -= pad->start_time;
2527         granuletime += chain->begin_time;
2528
2529         GST_DEBUG_OBJECT (ogg,
2530             "found page with granule %" G_GINT64_FORMAT " and time %"
2531             GST_TIME_FORMAT, granulepos, GST_TIME_ARGS (granuletime));
2532
2533         if (granuletime < target) {
2534           best = result;        /* raw offset of packet with granulepos */
2535           begin = ogg->offset;  /* raw offset of next page */
2536           begintime = granuletime;
2537
2538           bisect = begin;       /* *not* begin + 1 */
2539         } else {
2540           if (bisect <= begin + 1) {
2541             end = begin;        /* found it */
2542           } else {
2543             if (end == ogg->offset) {   /* we're pretty close - we'd be stuck in */
2544               end = result;
2545               bisect -= CHUNKSIZE;      /* an endless loop otherwise. */
2546               if (bisect <= begin)
2547                 bisect = begin + 1;
2548               gst_ogg_demux_seek (ogg, bisect);
2549             } else {
2550               end = result;
2551               endtime = granuletime;
2552               break;
2553             }
2554           }
2555         }
2556       } else
2557         goto seek_error;
2558     }
2559   }
2560   GST_DEBUG_OBJECT (ogg, "seeking to %" G_GINT64_FORMAT, best);
2561   gst_ogg_demux_seek (ogg, best);
2562   *offset = best;
2563
2564   return TRUE;
2565
2566   /* ERRORS */
2567 seek_error:
2568   {
2569     GST_DEBUG_OBJECT (ogg, "got a seek error");
2570     return FALSE;
2571   }
2572 }
2573
2574 static gboolean
2575 do_index_search (GstOggDemux * ogg, GstOggChain * chain, gint64 begin,
2576     gint64 end, gint64 begintime, gint64 endtime, gint64 target,
2577     gint64 * p_offset, gint64 * p_timestamp)
2578 {
2579   guint i;
2580   guint64 timestamp, offset;
2581   guint64 r_timestamp, r_offset;
2582   gboolean result = FALSE;
2583
2584   target -= begintime;
2585
2586   r_offset = -1;
2587   r_timestamp = -1;
2588
2589   for (i = 0; i < chain->streams->len; i++) {
2590     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
2591
2592     timestamp = target;
2593     if (gst_ogg_map_search_index (&pad->map, TRUE, &timestamp, &offset)) {
2594       GST_INFO ("found %" G_GUINT64_FORMAT " at offset %" G_GUINT64_FORMAT,
2595           timestamp, offset);
2596
2597       if (r_offset == -1 || offset < r_offset) {
2598         r_offset = offset;
2599         r_timestamp = timestamp;
2600       }
2601       result |= TRUE;
2602     }
2603   }
2604
2605   if (p_timestamp)
2606     *p_timestamp = r_timestamp;
2607   if (p_offset)
2608     *p_offset = r_offset;
2609
2610   return result;
2611 }
2612
2613 /*
2614  * do seek to time @position, return FALSE or chain and TRUE
2615  */
2616 static gboolean
2617 gst_ogg_demux_do_seek (GstOggDemux * ogg, GstSegment * segment,
2618     gboolean accurate, gboolean keyframe, GstOggChain ** rchain)
2619 {
2620   guint64 position;
2621   GstOggChain *chain = NULL;
2622   gint64 begin, end;
2623   gint64 begintime, endtime;
2624   gint64 target, keytarget;
2625   gint64 best;
2626   gint64 total;
2627   gint64 result = 0;
2628   GstFlowReturn ret;
2629   gint i, pending, len;
2630   gboolean first_parsed_page = TRUE;
2631
2632   position = segment->position;
2633
2634   /* first find the chain to search in */
2635   total = ogg->total_time;
2636   if (ogg->chains->len == 0)
2637     goto no_chains;
2638
2639   for (i = ogg->chains->len - 1; i >= 0; i--) {
2640     chain = g_array_index (ogg->chains, GstOggChain *, i);
2641     total -= chain->total_time;
2642     if (position >= total)
2643       break;
2644   }
2645
2646   /* first step, locate page containing the required data */
2647   begin = chain->offset;
2648   end = chain->end_offset;
2649   begintime = chain->begin_time;
2650   endtime = begintime + chain->total_time;
2651   target = position - total + begintime;
2652
2653   if (!do_binary_search (ogg, chain, begin, end, begintime, endtime, target,
2654           &best))
2655     goto seek_error;
2656
2657   /* second step: find pages for all streams, we use the keyframe_granule to keep
2658    * track of which ones we saw. If we have seen a page for each stream we can
2659    * calculate the positions of each keyframe. */
2660   GST_DEBUG_OBJECT (ogg, "find keyframes");
2661   len = pending = chain->streams->len;
2662
2663   /* figure out where the keyframes are */
2664   keytarget = target;
2665
2666   while (TRUE) {
2667     ogg_page og;
2668     gint64 granulepos;
2669     GstOggPad *pad;
2670     GstClockTime keyframe_time, granule_time;
2671
2672     ret = gst_ogg_demux_get_next_page (ogg, &og, end - ogg->offset, &result);
2673     GST_LOG_OBJECT (ogg, "looking for next page returned %" G_GINT64_FORMAT,
2674         result);
2675     if (ret == GST_FLOW_LIMIT) {
2676       GST_LOG_OBJECT (ogg, "reached limit");
2677       break;
2678     } else if (ret != GST_FLOW_OK)
2679       goto seek_error;
2680
2681     /* get the stream */
2682     pad = gst_ogg_chain_get_stream (chain, ogg_page_serialno (&og));
2683     if (pad == NULL)
2684       continue;
2685
2686     if (pad->map.is_skeleton)
2687       goto next;
2688
2689     granulepos = ogg_page_granulepos (&og);
2690     if (granulepos == -1 || granulepos == 0) {
2691       GST_LOG_OBJECT (ogg, "granulepos of next page is -1");
2692       continue;
2693     }
2694
2695     /* we only do this the first time we pass here */
2696     if (first_parsed_page) {
2697       /* Now that we have a time reference from the page, we can check
2698        * whether all streams still have pages from here on.
2699        *
2700        * This would be more elegant before the loop, but getting the page from
2701        * there without breaking anything would be more costly */
2702       granule_time = gst_ogg_stream_get_end_time_for_granulepos (&pad->map,
2703           granulepos);
2704       for (i = 0; i < len; i++) {
2705         GstOggPad *stream = g_array_index (chain->streams, GstOggPad *, i);
2706
2707         if (stream == pad)
2708           /* we already know we have at least one page (the current one)
2709            * for this stream */
2710           continue;
2711
2712         if (granule_time > stream->map.total_time)
2713           /* we won't encounter any more pages of this stream, so we don't
2714            * try finding a key frame for it */
2715           pending--;
2716       }
2717       first_parsed_page = FALSE;
2718     }
2719
2720
2721     /* in reverse we want to go past the page with the lower timestamp */
2722     if (segment->rate < 0.0) {
2723       /* get time for this pad */
2724       granule_time = gst_ogg_stream_get_end_time_for_granulepos (&pad->map,
2725           granulepos);
2726
2727       GST_LOG_OBJECT (ogg,
2728           "looking at page with ts %" GST_TIME_FORMAT ", target %"
2729           GST_TIME_FORMAT, GST_TIME_ARGS (granule_time),
2730           GST_TIME_ARGS (target));
2731       if (granule_time < target)
2732         continue;
2733     }
2734
2735     /* we've seen this pad before */
2736     if (pad->keyframe_granule != -1)
2737       continue;
2738
2739     /* convert granule of this pad to the granule of the keyframe */
2740     pad->keyframe_granule =
2741         gst_ogg_stream_granulepos_to_key_granule (&pad->map, granulepos);
2742     GST_LOG_OBJECT (ogg, "marking stream granule %" G_GINT64_FORMAT,
2743         pad->keyframe_granule);
2744
2745     /* get time of the keyframe */
2746     keyframe_time =
2747         gst_ogg_stream_granule_to_time (&pad->map, pad->keyframe_granule);
2748     GST_LOG_OBJECT (ogg,
2749         "stream %08x granule time %" GST_TIME_FORMAT,
2750         pad->map.serialno, GST_TIME_ARGS (keyframe_time));
2751
2752     /* collect smallest value */
2753     if (keyframe_time != -1) {
2754       keyframe_time += begintime;
2755       if (keyframe_time < keytarget)
2756         keytarget = keyframe_time;
2757     }
2758
2759   next:
2760     pending--;
2761     if (pending == 0)
2762       break;
2763   }
2764
2765   /* for negative rates we will get to the keyframe backwards */
2766   if (segment->rate < 0.0)
2767     goto done;
2768
2769   if (keytarget != target) {
2770     GST_LOG_OBJECT (ogg, "final seek to target %" GST_TIME_FORMAT,
2771         GST_TIME_ARGS (keytarget));
2772
2773     /* last step, seek to the location of the keyframe */
2774     if (!do_binary_search (ogg, chain, begin, end, begintime, endtime,
2775             keytarget, &best))
2776       goto seek_error;
2777   } else {
2778     /* seek back to previous position */
2779     GST_LOG_OBJECT (ogg, "keyframe on target");
2780     gst_ogg_demux_seek (ogg, best);
2781   }
2782
2783 done:
2784   if (keyframe) {
2785     if (segment->rate > 0.0)
2786       segment->time = keytarget;
2787     segment->position = keytarget - begintime;
2788   }
2789
2790   *rchain = chain;
2791
2792   return TRUE;
2793
2794 no_chains:
2795   {
2796     GST_DEBUG_OBJECT (ogg, "no chains");
2797     return FALSE;
2798   }
2799 seek_error:
2800   {
2801     GST_DEBUG_OBJECT (ogg, "got a seek error");
2802     return FALSE;
2803   }
2804 }
2805
2806 /* does not take ownership of the event */
2807 static gboolean
2808 gst_ogg_demux_perform_seek_pull (GstOggDemux * ogg, GstEvent * event)
2809 {
2810   GstOggChain *chain = NULL;
2811   gboolean res;
2812   gboolean flush, accurate, keyframe;
2813   GstFormat format;
2814   gdouble rate;
2815   GstSeekFlags flags;
2816   GstSeekType cur_type, stop_type;
2817   gint64 cur, stop;
2818   gboolean update;
2819   guint32 seqnum;
2820   GstEvent *tevent;
2821
2822   if (event) {
2823     GST_DEBUG_OBJECT (ogg, "seek with event");
2824
2825     gst_event_parse_seek (event, &rate, &format, &flags,
2826         &cur_type, &cur, &stop_type, &stop);
2827
2828     /* we can only seek on time */
2829     if (format != GST_FORMAT_TIME) {
2830       GST_DEBUG_OBJECT (ogg, "can only seek on TIME");
2831       goto error;
2832     }
2833     seqnum = gst_event_get_seqnum (event);
2834   } else {
2835     GST_DEBUG_OBJECT (ogg, "seek without event");
2836
2837     flags = 0;
2838     rate = 1.0;
2839     seqnum = gst_util_seqnum_next ();
2840   }
2841
2842   GST_DEBUG_OBJECT (ogg, "seek, rate %g", rate);
2843
2844   flush = flags & GST_SEEK_FLAG_FLUSH;
2845   accurate = flags & GST_SEEK_FLAG_ACCURATE;
2846   keyframe = flags & GST_SEEK_FLAG_KEY_UNIT;
2847
2848   /* first step is to unlock the streaming thread if it is
2849    * blocked in a chain call, we do this by starting the flush. because
2850    * we cannot yet hold any streaming lock, we have to protect the chains
2851    * with their own lock. */
2852   if (flush) {
2853     gint i;
2854
2855     tevent = gst_event_new_flush_start ();
2856     gst_event_set_seqnum (tevent, seqnum);
2857
2858     gst_event_ref (tevent);
2859     gst_pad_push_event (ogg->sinkpad, tevent);
2860
2861     GST_CHAIN_LOCK (ogg);
2862     for (i = 0; i < ogg->chains->len; i++) {
2863       GstOggChain *chain = g_array_index (ogg->chains, GstOggChain *, i);
2864       gint j;
2865
2866       for (j = 0; j < chain->streams->len; j++) {
2867         GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, j);
2868
2869         gst_event_ref (tevent);
2870         gst_pad_push_event (GST_PAD (pad), tevent);
2871       }
2872     }
2873     GST_CHAIN_UNLOCK (ogg);
2874
2875     gst_event_unref (tevent);
2876   } else {
2877     gst_pad_pause_task (ogg->sinkpad);
2878   }
2879
2880   /* now grab the stream lock so that streaming cannot continue, for
2881    * non flushing seeks when the element is in PAUSED this could block
2882    * forever. */
2883   GST_PAD_STREAM_LOCK (ogg->sinkpad);
2884
2885   if (event) {
2886     gst_segment_do_seek (&ogg->segment, rate, format, flags,
2887         cur_type, cur, stop_type, stop, &update);
2888   }
2889
2890   GST_DEBUG_OBJECT (ogg, "segment positions set to %" GST_TIME_FORMAT "-%"
2891       GST_TIME_FORMAT, GST_TIME_ARGS (ogg->segment.start),
2892       GST_TIME_ARGS (ogg->segment.stop));
2893
2894   /* we need to stop flushing on the srcpad as we're going to use it
2895    * next. We can do this as we have the STREAM lock now. */
2896   if (flush) {
2897     tevent = gst_event_new_flush_stop (TRUE);
2898     gst_event_set_seqnum (tevent, seqnum);
2899     gst_pad_push_event (ogg->sinkpad, tevent);
2900   }
2901
2902   {
2903     gint i;
2904
2905     /* reset all ogg streams now, need to do this from within the lock to
2906      * make sure the streaming thread is not messing with the stream */
2907     for (i = 0; i < ogg->chains->len; i++) {
2908       GstOggChain *chain = g_array_index (ogg->chains, GstOggChain *, i);
2909
2910       gst_ogg_chain_reset (chain);
2911     }
2912   }
2913
2914   /* for reverse we will already seek accurately */
2915   res = gst_ogg_demux_do_seek (ogg, &ogg->segment, accurate, keyframe, &chain);
2916
2917   /* seek failed, make sure we continue the current chain */
2918   if (!res) {
2919     GST_DEBUG_OBJECT (ogg, "seek failed");
2920     chain = ogg->current_chain;
2921   } else {
2922     GST_DEBUG_OBJECT (ogg, "seek success");
2923   }
2924
2925   if (!chain)
2926     goto no_chain;
2927
2928   /* now we have a new position, prepare for streaming again */
2929   {
2930     GstEvent *event;
2931     gint64 stop;
2932     gint64 start;
2933     gint64 position, begin_time;
2934     GstSegment segment;
2935
2936     /* we have to send the flush to the old chain, not the new one */
2937     if (flush) {
2938       tevent = gst_event_new_flush_stop (TRUE);
2939       gst_event_set_seqnum (tevent, seqnum);
2940       gst_ogg_demux_send_event (ogg, tevent);
2941     }
2942
2943     /* we need this to see how far inside the chain we need to start */
2944     if (chain->begin_time != GST_CLOCK_TIME_NONE)
2945       begin_time = chain->begin_time;
2946     else
2947       begin_time = 0;
2948
2949     /* segment.start gives the start over all chains, we calculate the amount
2950      * of time into this chain we need to start */
2951     start = ogg->segment.start - begin_time;
2952     if (chain->segment_start != GST_CLOCK_TIME_NONE)
2953       start += chain->segment_start;
2954
2955     if ((stop = ogg->segment.stop) == -1)
2956       stop = ogg->segment.duration;
2957
2958     /* segment.stop gives the stop time over all chains, calculate the amount of
2959      * time we need to stop in this chain */
2960     if (stop != -1) {
2961       if (stop > begin_time)
2962         stop -= begin_time;
2963       else
2964         stop = 0;
2965       stop += chain->segment_start;
2966       /* we must stop when this chain ends and switch to the next chain to play
2967        * the remainder of the segment. */
2968       stop = MIN (stop, chain->segment_stop);
2969     }
2970
2971     position = ogg->segment.position;
2972     if (chain->segment_start != GST_CLOCK_TIME_NONE)
2973       position += chain->segment_start;
2974
2975     gst_segment_copy_into (&ogg->segment, &segment);
2976
2977     /* create the segment event we are going to send out */
2978     if (ogg->segment.rate >= 0.0) {
2979       segment.start = position;
2980       segment.stop = stop;
2981     } else {
2982       segment.start = start;
2983       segment.stop = position;
2984     }
2985     event = gst_event_new_segment (&segment);
2986     gst_event_set_seqnum (event, seqnum);
2987
2988     if (chain != ogg->current_chain) {
2989       /* switch to different chain, send segment on new chain */
2990       gst_ogg_demux_activate_chain (ogg, chain, event);
2991     } else {
2992       /* mark discont and send segment on current chain */
2993       gst_ogg_chain_mark_discont (chain);
2994       /* This event should be sent from the streaming thread (sink pad task) */
2995       if (ogg->newsegment)
2996         gst_event_unref (ogg->newsegment);
2997       ogg->newsegment = event;
2998     }
2999
3000     /* notify start of new segment */
3001     if (ogg->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3002       GstMessage *message;
3003
3004       message = gst_message_new_segment_start (GST_OBJECT (ogg),
3005           GST_FORMAT_TIME, ogg->segment.position);
3006       gst_message_set_seqnum (message, seqnum);
3007
3008       gst_element_post_message (GST_ELEMENT (ogg), message);
3009     }
3010
3011     ogg->seqnum = seqnum;
3012     /* restart our task since it might have been stopped when we did the 
3013      * flush. */
3014     gst_pad_start_task (ogg->sinkpad, (GstTaskFunction) gst_ogg_demux_loop,
3015         ogg->sinkpad);
3016   }
3017
3018   /* streaming can continue now */
3019   GST_PAD_STREAM_UNLOCK (ogg->sinkpad);
3020
3021   return res;
3022
3023   /* ERRORS */
3024 error:
3025   {
3026     GST_DEBUG_OBJECT (ogg, "seek failed");
3027     return FALSE;
3028   }
3029 no_chain:
3030   {
3031     GST_DEBUG_OBJECT (ogg, "no chain to seek in");
3032     GST_PAD_STREAM_UNLOCK (ogg->sinkpad);
3033     return FALSE;
3034   }
3035 }
3036
3037 static gboolean
3038 gst_ogg_demux_get_duration_push (GstOggDemux * ogg, int flags)
3039 {
3040   /* In push mode, we get to the end of the stream to get the duration */
3041   gint64 position;
3042   GstEvent *sevent;
3043   gboolean res;
3044
3045   /* A full Ogg page can be almost 64 KB. There's no guarantee that there'll be a
3046      granpos there, but it's fairly likely */
3047   position =
3048       ogg->push_byte_length - DURATION_CHUNK_OFFSET - EOS_AVOIDANCE_THRESHOLD;
3049   if (position < 0)
3050     position = 0;
3051
3052   GST_DEBUG_OBJECT (ogg,
3053       "Getting duration, seeking near the end, to %" G_GINT64_FORMAT, position);
3054   ogg->push_state = PUSH_DURATION;
3055   /* do not read the last byte */
3056   sevent = gst_event_new_seek (1.0, GST_FORMAT_BYTES, flags, GST_SEEK_TYPE_SET,
3057       position, GST_SEEK_TYPE_SET, ogg->push_byte_length - 1);
3058   res = gst_pad_push_event (ogg->sinkpad, sevent);
3059   if (res) {
3060     GST_DEBUG_OBJECT (ogg, "Seek succesful");
3061     return TRUE;
3062   } else {
3063     GST_INFO_OBJECT (ogg, "Seek failed, duration will stay unknown");
3064     ogg->push_state = PUSH_PLAYING;
3065     ogg->push_disable_seeking = TRUE;
3066     return FALSE;
3067   }
3068 }
3069
3070 static gboolean
3071 gst_ogg_demux_check_duration_push (GstOggDemux * ogg, GstSeekFlags flags,
3072     GstEvent * event)
3073 {
3074   if (ogg->push_byte_length < 0) {
3075     GstPad *peer;
3076
3077     GST_DEBUG_OBJECT (ogg, "Trying to find byte/time length");
3078     if ((peer = gst_pad_get_peer (ogg->sinkpad)) != NULL) {
3079       gint64 length;
3080       int res;
3081
3082       res = gst_pad_query_duration (peer, GST_FORMAT_BYTES, &length);
3083       if (res && length > 0) {
3084         ogg->push_byte_length = length;
3085         GST_DEBUG_OBJECT (ogg,
3086             "File byte length %" G_GINT64_FORMAT, ogg->push_byte_length);
3087       }
3088       res = gst_pad_query_duration (peer, GST_FORMAT_TIME, &length);
3089       gst_object_unref (peer);
3090       if (res && length >= 0) {
3091         ogg->push_time_length = length;
3092         GST_DEBUG_OBJECT (ogg, "File time length %" GST_TIME_FORMAT,
3093             GST_TIME_ARGS (ogg->push_time_length));
3094       } else if (!ogg->push_disable_seeking) {
3095         gboolean res;
3096
3097         res = gst_ogg_demux_get_duration_push (ogg, flags);
3098         if (res) {
3099           GST_DEBUG_OBJECT (ogg,
3100               "File time length unknown, trying to determine");
3101           ogg->push_mode_seek_delayed_event = NULL;
3102           if (event) {
3103             GST_DEBUG_OBJECT (ogg,
3104                 "Let me intercept this innocent looking seek request");
3105             ogg->push_mode_seek_delayed_event = gst_event_copy (event);
3106           }
3107           return FALSE;
3108         }
3109       }
3110     }
3111   }
3112   return TRUE;
3113 }
3114
3115 static gboolean
3116 gst_ogg_demux_perform_seek_push (GstOggDemux * ogg, GstEvent * event)
3117 {
3118   gint bitrate;
3119   gboolean res = TRUE;
3120   GstFormat format;
3121   gdouble rate;
3122   GstSeekFlags flags;
3123   GstSeekType start_type, stop_type;
3124   gint64 start, stop;
3125   GstEvent *sevent;
3126   GstOggChain *chain;
3127   gint64 best, best_time;
3128   gint i;
3129
3130   GST_DEBUG_OBJECT (ogg, "Push mode seek request received");
3131
3132   gst_event_parse_seek (event, &rate, &format, &flags,
3133       &start_type, &start, &stop_type, &stop);
3134
3135   if (format != GST_FORMAT_TIME) {
3136     GST_DEBUG_OBJECT (ogg, "can only seek on TIME");
3137     goto error;
3138   }
3139
3140   if (start_type != GST_SEEK_TYPE_SET) {
3141     GST_DEBUG_OBJECT (ogg, "can only seek to a SET target");
3142     goto error;
3143   }
3144
3145   if (!(flags & GST_SEEK_FLAG_FLUSH)) {
3146     GST_DEBUG_OBJECT (ogg, "can only do flushing seeks");
3147     goto error;
3148   }
3149
3150   GST_DEBUG_OBJECT (ogg, "Push mode seek request: %" GST_TIME_FORMAT,
3151       GST_TIME_ARGS (start));
3152
3153   chain = ogg->current_chain;
3154   if (!chain) {
3155     GST_WARNING_OBJECT (ogg, "No chain to seek on");
3156     goto error;
3157   }
3158
3159   /* start accessing push_* members */
3160   GST_PUSH_LOCK (ogg);
3161
3162   /* not if we disabled seeking (chained streams) */
3163   if (ogg->push_disable_seeking) {
3164     GST_DEBUG_OBJECT (ogg, "Seeking disabled");
3165     goto error_locked;
3166   }
3167
3168   /* not when we're trying to work out duration */
3169   if (ogg->push_state == PUSH_DURATION) {
3170     GST_DEBUG_OBJECT (ogg, "Busy working out duration, try again later");
3171     goto error_locked;
3172   }
3173
3174   /* actually, not if we're doing any seeking already */
3175   if (ogg->push_state != PUSH_PLAYING) {
3176     GST_DEBUG_OBJECT (ogg, "Already doing some seeking, try again later");
3177     goto error_locked;
3178   }
3179
3180   /* on the first seek, get length if we can */
3181   if (!gst_ogg_demux_check_duration_push (ogg, flags, event)) {
3182     GST_PUSH_UNLOCK (ogg);
3183     return FALSE;
3184   }
3185
3186   if (do_index_search (ogg, chain, 0, -1, 0, -1, start, &best, &best_time)) {
3187     /* the index gave some result */
3188     GST_DEBUG_OBJECT (ogg,
3189         "found offset %" G_GINT64_FORMAT " with time %" G_GUINT64_FORMAT,
3190         best, best_time);
3191   } else {
3192     if (ogg->push_time_length > 0) {
3193       /* if we know the time length, we know the full segment bitrate */
3194       GST_DEBUG_OBJECT (ogg, "Using real file bitrate");
3195       bitrate =
3196           gst_util_uint64_scale (ogg->push_byte_length, 8 * GST_SECOND,
3197           ogg->push_time_length);
3198     } else if (ogg->push_time_offset > 0) {
3199       /* get a first approximation using known bitrate to the current position */
3200       GST_DEBUG_OBJECT (ogg, "Using file bitrate so far");
3201       bitrate =
3202           gst_util_uint64_scale (ogg->push_byte_offset, 8 * GST_SECOND,
3203           ogg->push_time_offset);
3204     } else if (ogg->bitrate > 0) {
3205       /* nominal bitrate is better than nothing, even if it lies often */
3206       GST_DEBUG_OBJECT (ogg, "Using nominal bitrate");
3207       bitrate = ogg->bitrate;
3208     } else {
3209       /* meh */
3210       GST_DEBUG_OBJECT (ogg,
3211           "At stream start, and no nominal bitrate, using some random magic "
3212           "number to seed");
3213       /* the bisection, once started, should give us a better approximation */
3214       bitrate = 1000;
3215     }
3216     best = gst_util_uint64_scale (start, bitrate, 8 * GST_SECOND);
3217   }
3218
3219   /* offset by typical page length, and ensure our best guess is within
3220      reasonable bounds */
3221   best -= CHUNKSIZE;
3222   if (best < 0)
3223     best = 0;
3224   if (ogg->push_byte_length > 0 && best >= ogg->push_byte_length)
3225     best = ogg->push_byte_length - 1;
3226
3227   /* set up bisection search */
3228   ogg->push_offset0 = 0;
3229   ogg->push_offset1 = ogg->push_byte_length - 1;
3230   ogg->push_time0 = ogg->push_start_time;
3231   ogg->push_time1 = ogg->push_time_length;
3232   ogg->push_seek_time_target = start;
3233   ogg->push_seek_time_original_target = start;
3234   ogg->push_state = PUSH_BISECT1;
3235
3236   /* reset pad push mode seeking state */
3237   for (i = 0; i < chain->streams->len; i++) {
3238     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
3239     pad->push_kf_time = GST_CLOCK_TIME_NONE;
3240     pad->push_sync_time = GST_CLOCK_TIME_NONE;
3241   }
3242
3243   GST_DEBUG_OBJECT (ogg,
3244       "Setting up bisection search for %" G_GINT64_FORMAT " - %" G_GINT64_FORMAT
3245       " (time %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT ")", ogg->push_offset0,
3246       ogg->push_offset1, GST_TIME_ARGS (ogg->push_time0),
3247       GST_TIME_ARGS (ogg->push_time1));
3248   GST_DEBUG_OBJECT (ogg,
3249       "Target time is %" GST_TIME_FORMAT ", best first guess is %"
3250       G_GINT64_FORMAT, GST_TIME_ARGS (ogg->push_seek_time_target), best);
3251
3252   ogg->push_seek_rate = rate;
3253   ogg->push_seek_flags = flags;
3254   ogg->push_mode_seek_delayed_event = NULL;
3255   ogg->push_bisection_steps[0] = 1;
3256   ogg->push_bisection_steps[1] = 0;
3257   sevent = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
3258       start_type, best, GST_SEEK_TYPE_NONE, -1);
3259
3260   GST_PUSH_UNLOCK (ogg);
3261   res = gst_pad_push_event (ogg->sinkpad, sevent);
3262
3263   return res;
3264
3265   /* ERRORS */
3266 error:
3267   {
3268     GST_DEBUG_OBJECT (ogg, "seek failed");
3269     return FALSE;
3270   }
3271
3272 error_locked:
3273   GST_PUSH_UNLOCK (ogg);
3274   goto error;
3275 }
3276
3277 static gboolean
3278 gst_ogg_demux_perform_seek (GstOggDemux * ogg, GstEvent * event)
3279 {
3280   gboolean res;
3281
3282   if (ogg->pullmode) {
3283     res = gst_ogg_demux_perform_seek_pull (ogg, event);
3284   } else {
3285     res = gst_ogg_demux_perform_seek_push (ogg, event);
3286   }
3287   return res;
3288 }
3289
3290
3291 /* finds each bitstream link one at a time using a bisection search
3292  * (has to begin by knowing the offset of the lb's initial page).
3293  * Recurses for each link so it can alloc the link storage after
3294  * finding them all, then unroll and fill the cache at the same time
3295  */
3296 static GstFlowReturn
3297 gst_ogg_demux_bisect_forward_serialno (GstOggDemux * ogg,
3298     gint64 begin, gint64 searched, gint64 end, GstOggChain * chain, glong m)
3299 {
3300   gint64 endsearched = end;
3301   gint64 next = end;
3302   ogg_page og;
3303   GstFlowReturn ret;
3304   gint64 offset;
3305   GstOggChain *nextchain;
3306
3307   GST_LOG_OBJECT (ogg,
3308       "bisect begin: %" G_GINT64_FORMAT ", searched: %" G_GINT64_FORMAT
3309       ", end %" G_GINT64_FORMAT ", chain: %p", begin, searched, end, chain);
3310
3311   /* the below guards against garbage seperating the last and
3312    * first pages of two links. */
3313   while (searched < endsearched) {
3314     gint64 bisect;
3315
3316     if (endsearched - searched < CHUNKSIZE) {
3317       bisect = searched;
3318     } else {
3319       bisect = (searched + endsearched) / 2;
3320     }
3321
3322     gst_ogg_demux_seek (ogg, bisect);
3323     ret = gst_ogg_demux_get_next_page (ogg, &og, -1, &offset);
3324
3325     if (ret == GST_FLOW_EOS) {
3326       endsearched = bisect;
3327     } else if (ret == GST_FLOW_OK) {
3328       guint32 serial = ogg_page_serialno (&og);
3329
3330       if (!gst_ogg_chain_has_stream (chain, serial)) {
3331         endsearched = bisect;
3332         next = offset;
3333       } else {
3334         searched = offset + og.header_len + og.body_len;
3335       }
3336     } else
3337       return ret;
3338   }
3339
3340   GST_LOG_OBJECT (ogg, "current chain ends at %" G_GINT64_FORMAT, searched);
3341
3342   chain->end_offset = searched;
3343   ret = gst_ogg_demux_read_end_chain (ogg, chain);
3344   if (ret != GST_FLOW_OK)
3345     return ret;
3346
3347   GST_LOG_OBJECT (ogg, "found begin at %" G_GINT64_FORMAT, next);
3348
3349   gst_ogg_demux_seek (ogg, next);
3350   ret = gst_ogg_demux_read_chain (ogg, &nextchain);
3351   if (ret == GST_FLOW_EOS) {
3352     nextchain = NULL;
3353     ret = GST_FLOW_OK;
3354     GST_LOG_OBJECT (ogg, "no next chain");
3355   } else if (ret != GST_FLOW_OK)
3356     goto done;
3357
3358   if (searched < end && nextchain != NULL) {
3359     ret = gst_ogg_demux_bisect_forward_serialno (ogg, next, ogg->offset,
3360         end, nextchain, m + 1);
3361     if (ret != GST_FLOW_OK)
3362       goto done;
3363   }
3364   GST_LOG_OBJECT (ogg, "adding chain %p", chain);
3365
3366   g_array_insert_val (ogg->chains, 0, chain);
3367
3368 done:
3369   return ret;
3370 }
3371
3372 /* read a chain from the ogg file. This code will
3373  * read all BOS pages and will create and return a GstOggChain 
3374  * structure with the results. 
3375  * 
3376  * This function will also read N pages from each stream in the
3377  * chain and submit them to the decoders. When the decoder has
3378  * decoded the first buffer, we know the timestamp of the first
3379  * page in the chain.
3380  */
3381 static GstFlowReturn
3382 gst_ogg_demux_read_chain (GstOggDemux * ogg, GstOggChain ** res_chain)
3383 {
3384   GstFlowReturn ret;
3385   GstOggChain *chain = NULL;
3386   gint64 offset = ogg->offset;
3387   ogg_page og;
3388   gboolean done;
3389   gint i;
3390
3391   GST_LOG_OBJECT (ogg, "reading chain at %" G_GINT64_FORMAT, offset);
3392
3393   /* first read the BOS pages, do typefind on them, create
3394    * the decoders, send data to the decoders. */
3395   while (TRUE) {
3396     GstOggPad *pad;
3397     guint32 serial;
3398
3399     ret = gst_ogg_demux_get_next_page (ogg, &og, -1, NULL);
3400     if (ret != GST_FLOW_OK) {
3401       if (ret == GST_FLOW_EOS) {
3402         GST_DEBUG_OBJECT (ogg, "Reached EOS, done reading end chain");
3403       } else {
3404         GST_WARNING_OBJECT (ogg, "problem reading BOS page: ret=%d", ret);
3405       }
3406       break;
3407     }
3408     if (!ogg_page_bos (&og)) {
3409       GST_INFO_OBJECT (ogg, "page is not BOS page, all streams identified");
3410       /* if we did not find a chain yet, assume this is a bogus stream and
3411        * ignore it */
3412       if (!chain) {
3413         GST_WARNING_OBJECT (ogg, "No chain found, no Ogg data in stream ?");
3414         ret = GST_FLOW_EOS;
3415       }
3416       break;
3417     }
3418
3419     if (chain == NULL) {
3420       chain = gst_ogg_chain_new (ogg);
3421       chain->offset = offset;
3422     }
3423
3424     serial = ogg_page_serialno (&og);
3425     if (gst_ogg_chain_get_stream (chain, serial) != NULL) {
3426       GST_WARNING_OBJECT (ogg,
3427           "found serial %08x BOS page twice, ignoring", serial);
3428       continue;
3429     }
3430
3431     pad = gst_ogg_chain_new_stream (chain, serial);
3432     gst_ogg_pad_submit_page (pad, &og);
3433   }
3434
3435   if (ret != GST_FLOW_OK || chain == NULL) {
3436     if (ret == GST_FLOW_OK) {
3437       GST_WARNING_OBJECT (ogg, "no chain was found");
3438       ret = GST_FLOW_ERROR;
3439     } else if (ret != GST_FLOW_EOS) {
3440       GST_WARNING_OBJECT (ogg, "failed to read chain");
3441     } else {
3442       GST_DEBUG_OBJECT (ogg, "done reading chains");
3443     }
3444     if (chain) {
3445       gst_ogg_chain_free (chain);
3446     }
3447     if (res_chain)
3448       *res_chain = NULL;
3449     return ret;
3450   }
3451
3452   chain->have_bos = TRUE;
3453   GST_LOG_OBJECT (ogg, "read bos pages, init decoder now");
3454
3455   /* now read pages until we receive a buffer from each of the
3456    * stream decoders, this will tell us the timestamp of the
3457    * first packet in the chain then */
3458
3459   /* save the offset to the first non bos page in the chain: if searching for
3460    * pad->first_time we read past the end of the chain, we'll seek back to this
3461    * position
3462    */
3463   offset = ogg->offset;
3464
3465   done = FALSE;
3466   while (!done) {
3467     guint32 serial;
3468     gboolean known_serial = FALSE;
3469     GstFlowReturn ret;
3470
3471     serial = ogg_page_serialno (&og);
3472     done = TRUE;
3473     for (i = 0; i < chain->streams->len; i++) {
3474       GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
3475
3476       GST_LOG_OBJECT (ogg,
3477           "serial %08x time %" GST_TIME_FORMAT,
3478           pad->map.serialno, GST_TIME_ARGS (pad->start_time));
3479
3480       if (pad->map.serialno == serial) {
3481         known_serial = TRUE;
3482
3483         /* submit the page now, this will fill in the start_time when the
3484          * internal decoder finds it */
3485         gst_ogg_pad_submit_page (pad, &og);
3486
3487         if (!pad->map.is_skeleton && pad->start_time == -1
3488             && ogg_page_eos (&og)) {
3489           /* got EOS on a pad before we could find its start_time.
3490            * We have no chance of finding a start_time for every pad so
3491            * stop searching for the other start_time(s).
3492            */
3493           done = TRUE;
3494           break;
3495         }
3496       }
3497       /* the timestamp will be filled in when we submit the pages */
3498       if (!pad->map.is_sparse)
3499         done &= (pad->start_time != GST_CLOCK_TIME_NONE);
3500
3501       GST_LOG_OBJECT (ogg, "done %08x now %d", pad->map.serialno, done);
3502     }
3503
3504     /* we read a page not belonging to the current chain: seek back to the
3505      * beginning of the chain
3506      */
3507     if (!known_serial) {
3508       GST_LOG_OBJECT (ogg, "unknown serial %08x", serial);
3509       gst_ogg_demux_seek (ogg, offset);
3510       break;
3511     }
3512
3513     if (!done) {
3514       ret = gst_ogg_demux_get_next_page (ogg, &og, -1, NULL);
3515       if (ret != GST_FLOW_OK)
3516         break;
3517     }
3518   }
3519   GST_LOG_OBJECT (ogg, "done reading chain");
3520   /* now we can fill in the missing info using queries */
3521   for (i = 0; i < chain->streams->len; i++) {
3522     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
3523
3524     if (pad->map.is_skeleton)
3525       continue;
3526
3527     pad->mode = GST_OGG_PAD_MODE_STREAMING;
3528   }
3529
3530   if (res_chain)
3531     *res_chain = chain;
3532
3533   return GST_FLOW_OK;
3534 }
3535
3536 /* read the last pages from the ogg stream to get the final
3537  * page end_offsets.
3538  */
3539 static GstFlowReturn
3540 gst_ogg_demux_read_end_chain (GstOggDemux * ogg, GstOggChain * chain)
3541 {
3542   gint64 begin = chain->end_offset;
3543   gint64 end = begin;
3544   gint64 last_granule = -1;
3545   GstOggPad *last_pad = NULL;
3546   GstFlowReturn ret;
3547   gboolean done = FALSE;
3548   ogg_page og;
3549   gint i;
3550
3551   while (!done) {
3552     begin -= CHUNKSIZE;
3553     if (begin < 0)
3554       begin = 0;
3555
3556     gst_ogg_demux_seek (ogg, begin);
3557
3558     /* now continue reading until we run out of data, if we find a page
3559      * start, we save it. It might not be the final page as there could be
3560      * another page after this one. */
3561     while (ogg->offset < end) {
3562       ret = gst_ogg_demux_get_next_page (ogg, &og, end - ogg->offset, NULL);
3563
3564       if (ret == GST_FLOW_LIMIT)
3565         break;
3566       if (ret != GST_FLOW_OK)
3567         return ret;
3568
3569       for (i = 0; i < chain->streams->len; i++) {
3570         GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
3571
3572         if (pad->map.is_skeleton)
3573           continue;
3574
3575         if (pad->map.serialno == ogg_page_serialno (&og)) {
3576           gint64 granulepos = ogg_page_granulepos (&og);
3577
3578           if (granulepos != -1) {
3579             last_granule = granulepos;
3580             last_pad = pad;
3581             done = TRUE;
3582           }
3583           break;
3584         }
3585       }
3586     }
3587   }
3588
3589   if (last_pad) {
3590     chain->segment_stop =
3591         gst_ogg_stream_get_end_time_for_granulepos (&last_pad->map,
3592         last_granule);
3593   } else {
3594     chain->segment_stop = GST_CLOCK_TIME_NONE;
3595   }
3596
3597   GST_INFO ("segment stop %" G_GUINT64_FORMAT, chain->segment_stop);
3598
3599   return GST_FLOW_OK;
3600 }
3601
3602 /* find a pad with a given serial number
3603  */
3604 static GstOggPad *
3605 gst_ogg_demux_find_pad (GstOggDemux * ogg, guint32 serialno)
3606 {
3607   GstOggPad *pad;
3608   gint i;
3609
3610   /* first look in building chain if any */
3611   if (ogg->building_chain) {
3612     pad = gst_ogg_chain_get_stream (ogg->building_chain, serialno);
3613     if (pad)
3614       return pad;
3615   }
3616
3617   /* then look in current chain if any */
3618   if (ogg->current_chain) {
3619     pad = gst_ogg_chain_get_stream (ogg->current_chain, serialno);
3620     if (pad)
3621       return pad;
3622   }
3623
3624   for (i = 0; i < ogg->chains->len; i++) {
3625     GstOggChain *chain = g_array_index (ogg->chains, GstOggChain *, i);
3626
3627     pad = gst_ogg_chain_get_stream (chain, serialno);
3628     if (pad)
3629       return pad;
3630   }
3631   return NULL;
3632 }
3633
3634 /* find a chain with a given serial number
3635  */
3636 static GstOggChain *
3637 gst_ogg_demux_find_chain (GstOggDemux * ogg, guint32 serialno)
3638 {
3639   GstOggPad *pad;
3640
3641   pad = gst_ogg_demux_find_pad (ogg, serialno);
3642   if (pad) {
3643     return pad->chain;
3644   }
3645   return NULL;
3646 }
3647
3648 /* returns TRUE if all streams have valid start time */
3649 static gboolean
3650 gst_ogg_demux_collect_chain_info (GstOggDemux * ogg, GstOggChain * chain)
3651 {
3652   gboolean res = TRUE;
3653
3654   chain->total_time = GST_CLOCK_TIME_NONE;
3655   GST_DEBUG_OBJECT (ogg, "trying to collect chain info");
3656
3657   /* see if we have a start time on all streams */
3658   chain->segment_start = gst_ogg_demux_collect_start_time (ogg, chain);
3659
3660   if (chain->segment_start == G_MAXUINT64) {
3661     /* not yet, stream some more data */
3662     res = FALSE;
3663   } else if (chain->segment_stop != GST_CLOCK_TIME_NONE) {
3664     /* we can calculate a total time */
3665     chain->total_time = chain->segment_stop - chain->segment_start;
3666   }
3667
3668   GST_DEBUG ("total time %" G_GUINT64_FORMAT, chain->total_time);
3669
3670   GST_DEBUG_OBJECT (ogg, "return %d", res);
3671
3672   return res;
3673 }
3674
3675 static void
3676 gst_ogg_demux_collect_info (GstOggDemux * ogg)
3677 {
3678   gint i;
3679
3680   /* collect all info */
3681   ogg->total_time = 0;
3682
3683   for (i = 0; i < ogg->chains->len; i++) {
3684     GstOggChain *chain = g_array_index (ogg->chains, GstOggChain *, i);
3685
3686     chain->begin_time = ogg->total_time;
3687
3688     gst_ogg_demux_collect_chain_info (ogg, chain);
3689
3690     ogg->total_time += chain->total_time;
3691   }
3692   ogg->segment.duration = ogg->total_time;
3693 }
3694
3695 /* find all the chains in the ogg file, this reads the first and
3696  * last page of the ogg stream, if they match then the ogg file has
3697  * just one chain, else we do a binary search for all chains.
3698  */
3699 static GstFlowReturn
3700 gst_ogg_demux_find_chains (GstOggDemux * ogg)
3701 {
3702   ogg_page og;
3703   GstPad *peer;
3704   gboolean res;
3705   guint32 serialno;
3706   GstOggChain *chain;
3707   GstFlowReturn ret;
3708
3709   /* get peer to figure out length */
3710   if ((peer = gst_pad_get_peer (ogg->sinkpad)) == NULL)
3711     goto no_peer;
3712
3713   /* find length to read last page, we store this for later use. */
3714   res = gst_pad_query_duration (peer, GST_FORMAT_BYTES, &ogg->length);
3715   gst_object_unref (peer);
3716   if (!res || ogg->length <= 0)
3717     goto no_length;
3718
3719   GST_DEBUG_OBJECT (ogg, "file length %" G_GINT64_FORMAT, ogg->length);
3720
3721   /* read chain from offset 0, this is the first chain of the
3722    * ogg file. */
3723   gst_ogg_demux_seek (ogg, 0);
3724   ret = gst_ogg_demux_read_chain (ogg, &chain);
3725   if (ret != GST_FLOW_OK)
3726     goto no_first_chain;
3727
3728   /* read page from end offset, we use this page to check if its serial
3729    * number is contained in the first chain. If this is the case then
3730    * this ogg is not a chained ogg and we can skip the scanning. */
3731   gst_ogg_demux_seek (ogg, ogg->length);
3732   ret = gst_ogg_demux_get_prev_page (ogg, &og, NULL);
3733   if (ret != GST_FLOW_OK)
3734     goto no_last_page;
3735
3736   serialno = ogg_page_serialno (&og);
3737
3738   if (!gst_ogg_chain_has_stream (chain, serialno)) {
3739     /* the last page is not in the first stream, this means we should
3740      * find all the chains in this chained ogg. */
3741     ret =
3742         gst_ogg_demux_bisect_forward_serialno (ogg, 0, 0, ogg->length, chain,
3743         0);
3744   } else {
3745     /* we still call this function here but with an empty range so that
3746      * we can reuse the setup code in this routine. */
3747     ret =
3748         gst_ogg_demux_bisect_forward_serialno (ogg, 0, ogg->length,
3749         ogg->length, chain, 0);
3750   }
3751   if (ret != GST_FLOW_OK)
3752     goto done;
3753
3754   /* all fine, collect and print */
3755   gst_ogg_demux_collect_info (ogg);
3756
3757   /* dump our chains and streams */
3758   gst_ogg_print (ogg);
3759
3760 done:
3761   return ret;
3762
3763   /*** error cases ***/
3764 no_peer:
3765   {
3766     GST_ELEMENT_ERROR (ogg, STREAM, DEMUX, (NULL), ("we don't have a peer"));
3767     return GST_FLOW_NOT_LINKED;
3768   }
3769 no_length:
3770   {
3771     GST_ELEMENT_ERROR (ogg, STREAM, DEMUX, (NULL), ("can't get file length"));
3772     return GST_FLOW_NOT_SUPPORTED;
3773   }
3774 no_first_chain:
3775   {
3776     GST_ELEMENT_ERROR (ogg, STREAM, DEMUX, (NULL), ("can't get first chain"));
3777     return GST_FLOW_ERROR;
3778   }
3779 no_last_page:
3780   {
3781     GST_DEBUG_OBJECT (ogg, "can't get last page");
3782     if (chain)
3783       gst_ogg_chain_free (chain);
3784     return ret;
3785   }
3786 }
3787
3788 static GstFlowReturn
3789 gst_ogg_demux_handle_page (GstOggDemux * ogg, ogg_page * page)
3790 {
3791   GstOggPad *pad;
3792   gint64 granule;
3793   guint32 serialno;
3794   GstFlowReturn result = GST_FLOW_OK;
3795
3796   serialno = ogg_page_serialno (page);
3797   granule = ogg_page_granulepos (page);
3798
3799   GST_LOG_OBJECT (ogg,
3800       "processing ogg page (serial %08x, "
3801       "pageno %ld, granulepos %" G_GINT64_FORMAT ", bos %d)", serialno,
3802       ogg_page_pageno (page), granule, ogg_page_bos (page));
3803
3804   if (ogg_page_bos (page)) {
3805     GstOggChain *chain;
3806
3807     /* first page */
3808     /* see if we know about the chain already */
3809     chain = gst_ogg_demux_find_chain (ogg, serialno);
3810     if (chain) {
3811       GstEvent *event;
3812       gint64 start = 0;
3813       GstSegment segment;
3814
3815       if (chain->segment_start != GST_CLOCK_TIME_NONE)
3816         start = chain->segment_start;
3817
3818       /* create the newsegment event we are going to send out */
3819       gst_segment_copy_into (&ogg->segment, &segment);
3820       segment.start = start;
3821       segment.stop = chain->segment_stop;
3822       segment.time = chain->begin_time;
3823       event = gst_event_new_segment (&segment);
3824       gst_event_set_seqnum (event, ogg->seqnum);
3825
3826       GST_DEBUG_OBJECT (ogg,
3827           "segment: start %" GST_TIME_FORMAT ", stop %" GST_TIME_FORMAT
3828           ", time %" GST_TIME_FORMAT, GST_TIME_ARGS (start),
3829           GST_TIME_ARGS (chain->segment_stop),
3830           GST_TIME_ARGS (chain->begin_time));
3831
3832       /* activate it as it means we have a non-header, this will also deactivate
3833        * the currently running chain. */
3834       gst_ogg_demux_activate_chain (ogg, chain, event);
3835       pad = gst_ogg_demux_find_pad (ogg, serialno);
3836     } else {
3837       GstClockTime chain_time;
3838       gint64 current_time;
3839
3840       /* this can only happen in push mode */
3841       if (ogg->pullmode)
3842         goto unknown_chain;
3843
3844       current_time = ogg->segment.position;
3845
3846       /* time of new chain is current time */
3847       chain_time = current_time;
3848
3849       if (ogg->building_chain == NULL) {
3850         GstOggChain *newchain;
3851
3852         newchain = gst_ogg_chain_new (ogg);
3853         newchain->offset = 0;
3854         /* set new chain begin time aligned with end time of old chain */
3855         newchain->begin_time = chain_time;
3856         GST_DEBUG_OBJECT (ogg, "new chain, begin time %" GST_TIME_FORMAT,
3857             GST_TIME_ARGS (chain_time));
3858
3859         /* and this is the one we are building now */
3860         ogg->building_chain = newchain;
3861       }
3862       pad = gst_ogg_chain_new_stream (ogg->building_chain, serialno);
3863     }
3864   } else {
3865     pad = gst_ogg_demux_find_pad (ogg, serialno);
3866   }
3867   if (pad) {
3868     result = gst_ogg_pad_submit_page (pad, page);
3869   } else {
3870     GST_PUSH_LOCK (ogg);
3871     if (!ogg->pullmode && !ogg->push_disable_seeking) {
3872       /* no pad while probing for duration, we must have a chained stream,
3873          and we don't support them, so back off */
3874       GST_INFO_OBJECT (ogg, "We seem to have a chained stream, we won't seek");
3875       if (ogg->push_state == PUSH_DURATION) {
3876         GstFlowReturn res;
3877
3878         res = gst_ogg_demux_seek_back_after_push_duration_check_unlock (ogg);
3879         if (res != GST_FLOW_OK)
3880           return res;
3881       }
3882
3883       /* only once we seeked back */
3884       GST_PUSH_LOCK (ogg);
3885       ogg->push_disable_seeking = TRUE;
3886     } else {
3887       GST_PUSH_UNLOCK (ogg);
3888       /* no pad. This means an ogg page without bos has been seen for this
3889        * serialno. we just ignore it but post a warning... */
3890       GST_ELEMENT_WARNING (ogg, STREAM, DECODE,
3891           (NULL), ("unknown ogg pad for serial %08x detected", serialno));
3892       return GST_FLOW_OK;
3893     }
3894     GST_PUSH_UNLOCK (ogg);
3895   }
3896   return result;
3897
3898   /* ERRORS */
3899 unknown_chain:
3900   {
3901     GST_ELEMENT_ERROR (ogg, STREAM, DECODE,
3902         (NULL), ("unknown ogg chain for serial %08x detected", serialno));
3903     return GST_FLOW_ERROR;
3904   }
3905 }
3906
3907 /* streaming mode, receive a buffer, parse it, create pads for
3908  * the serialno, submit pages and packets to the oggpads
3909  */
3910 static GstFlowReturn
3911 gst_ogg_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
3912 {
3913   GstOggDemux *ogg;
3914   gint ret = 0;
3915   GstFlowReturn result = GST_FLOW_OK;
3916
3917   ogg = GST_OGG_DEMUX (parent);
3918
3919   GST_DEBUG_OBJECT (ogg, "enter");
3920   result = gst_ogg_demux_submit_buffer (ogg, buffer);
3921   if (result < 0) {
3922     GST_DEBUG_OBJECT (ogg, "gst_ogg_demux_submit_buffer returned %d", result);
3923   }
3924
3925   while (result == GST_FLOW_OK) {
3926     ogg_page page;
3927
3928     ret = ogg_sync_pageout (&ogg->sync, &page);
3929     if (ret == 0)
3930       /* need more data */
3931       break;
3932     if (ret == -1) {
3933       /* discontinuity in the pages */
3934       GST_DEBUG_OBJECT (ogg, "discont in page found, continuing");
3935     } else {
3936       result = gst_ogg_demux_handle_page (ogg, &page);
3937       if (result < 0) {
3938         GST_DEBUG_OBJECT (ogg, "gst_ogg_demux_handle_page returned %d", result);
3939       }
3940     }
3941   }
3942   if (ret == 0 || result == GST_FLOW_OK) {
3943     gst_ogg_demux_sync_streams (ogg);
3944   }
3945   GST_DEBUG_OBJECT (ogg, "leave with %d", result);
3946   return result;
3947 }
3948
3949 static gboolean
3950 gst_ogg_demux_send_event (GstOggDemux * ogg, GstEvent * event)
3951 {
3952   GstOggChain *chain = ogg->current_chain;
3953   gboolean res = TRUE;
3954
3955   if (!chain)
3956     chain = ogg->building_chain;
3957
3958   if (chain) {
3959     gint i;
3960
3961     for (i = 0; i < chain->streams->len; i++) {
3962       GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
3963
3964       gst_event_ref (event);
3965       GST_DEBUG_OBJECT (pad, "Pushing event %" GST_PTR_FORMAT, event);
3966       res &= gst_pad_push_event (GST_PAD (pad), event);
3967     }
3968   } else {
3969     GST_WARNING_OBJECT (ogg, "No chain to forward event to");
3970   }
3971   gst_event_unref (event);
3972
3973   return res;
3974 }
3975
3976 static GstFlowReturn
3977 gst_ogg_demux_combine_flows (GstOggDemux * ogg, GstOggPad * pad,
3978     GstFlowReturn ret)
3979 {
3980   GstOggChain *chain;
3981
3982   /* store the value */
3983   pad->last_ret = ret;
3984
3985   /* any other error that is not-linked can be returned right
3986    * away */
3987   if (ret != GST_FLOW_NOT_LINKED)
3988     goto done;
3989
3990   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
3991   chain = ogg->current_chain;
3992   if (chain) {
3993     gint i;
3994
3995     for (i = 0; i < chain->streams->len; i++) {
3996       GstOggPad *opad = g_array_index (chain->streams, GstOggPad *, i);
3997
3998       ret = opad->last_ret;
3999       /* some other return value (must be SUCCESS but we can return
4000        * other values as well) */
4001       if (ret != GST_FLOW_NOT_LINKED)
4002         goto done;
4003     }
4004     /* if we get here, all other pads were unlinked and we return
4005      * NOT_LINKED then */
4006   }
4007 done:
4008   return ret;
4009 }
4010
4011 /* returns TRUE if all streams in current chain reached EOS, FALSE otherwise */
4012 static gboolean
4013 gst_ogg_demux_check_eos (GstOggDemux * ogg)
4014 {
4015   GstOggChain *chain;
4016   gboolean eos = TRUE;
4017
4018   chain = ogg->current_chain;
4019   if (G_LIKELY (chain)) {
4020     gint i;
4021
4022     for (i = 0; i < chain->streams->len; i++) {
4023       GstOggPad *opad = g_array_index (chain->streams, GstOggPad *, i);
4024
4025       eos = eos && opad->is_eos;
4026     }
4027   } else {
4028     eos = FALSE;
4029   }
4030
4031   return eos;
4032 }
4033
4034 static GstFlowReturn
4035 gst_ogg_demux_loop_forward (GstOggDemux * ogg)
4036 {
4037   GstFlowReturn ret;
4038   GstBuffer *buffer;
4039
4040   if (ogg->offset == ogg->length) {
4041     GST_LOG_OBJECT (ogg, "no more data to pull %" G_GINT64_FORMAT
4042         " == %" G_GINT64_FORMAT, ogg->offset, ogg->length);
4043     ret = GST_FLOW_EOS;
4044     goto done;
4045   }
4046
4047   GST_LOG_OBJECT (ogg, "pull data %" G_GINT64_FORMAT, ogg->offset);
4048   ret = gst_pad_pull_range (ogg->sinkpad, ogg->offset, CHUNKSIZE, &buffer);
4049   if (ret != GST_FLOW_OK) {
4050     GST_LOG_OBJECT (ogg, "Failed pull_range");
4051     goto done;
4052   }
4053
4054   ogg->offset += gst_buffer_get_size (buffer);
4055
4056   if (G_UNLIKELY (ogg->newsegment)) {
4057     gst_ogg_demux_send_event (ogg, ogg->newsegment);
4058     ogg->newsegment = NULL;
4059   }
4060
4061   ret = gst_ogg_demux_chain (ogg->sinkpad, GST_OBJECT_CAST (ogg), buffer);
4062   if (ret != GST_FLOW_OK) {
4063     GST_LOG_OBJECT (ogg, "Failed demux_chain");
4064     goto done;
4065   }
4066
4067   /* check for the end of the segment */
4068   if (gst_ogg_demux_check_eos (ogg)) {
4069     GST_LOG_OBJECT (ogg, "got EOS");
4070     ret = GST_FLOW_EOS;
4071     goto done;
4072   }
4073 done:
4074   return ret;
4075 }
4076
4077 /* reverse mode.
4078  *
4079  * We read the pages backwards and send the packets forwards. The first packet
4080  * in the page will be pushed with the DISCONT flag set.
4081  *
4082  * Special care has to be taken for continued pages, which we can only decode
4083  * when we have the previous page(s).
4084  */
4085 static GstFlowReturn
4086 gst_ogg_demux_loop_reverse (GstOggDemux * ogg)
4087 {
4088   GstFlowReturn ret;
4089   ogg_page page;
4090   gint64 offset;
4091
4092   if (ogg->offset == 0) {
4093     GST_LOG_OBJECT (ogg, "no more data to pull %" G_GINT64_FORMAT
4094         " == 0", ogg->offset);
4095     ret = GST_FLOW_EOS;
4096     goto done;
4097   }
4098
4099   GST_LOG_OBJECT (ogg, "read page from %" G_GINT64_FORMAT, ogg->offset);
4100   ret = gst_ogg_demux_get_prev_page (ogg, &page, &offset);
4101   if (ret != GST_FLOW_OK)
4102     goto done;
4103
4104   ogg->offset = offset;
4105
4106   if (G_UNLIKELY (ogg->newsegment)) {
4107     gst_ogg_demux_send_event (ogg, ogg->newsegment);
4108     ogg->newsegment = NULL;
4109   }
4110
4111   ret = gst_ogg_demux_handle_page (ogg, &page);
4112   if (ret != GST_FLOW_OK)
4113     goto done;
4114
4115   /* check for the end of the segment */
4116   if (gst_ogg_demux_check_eos (ogg)) {
4117     GST_LOG_OBJECT (ogg, "got EOS");
4118     ret = GST_FLOW_EOS;
4119     goto done;
4120   }
4121 done:
4122   return ret;
4123 }
4124
4125 static void
4126 gst_ogg_demux_sync_streams (GstOggDemux * ogg)
4127 {
4128   GstClockTime cur;
4129   GstOggChain *chain;
4130   guint i;
4131
4132   chain = ogg->current_chain;
4133   cur = ogg->segment.position;
4134   if (chain == NULL || cur == -1)
4135     return;
4136
4137   for (i = 0; i < chain->streams->len; i++) {
4138     GstOggPad *stream = g_array_index (chain->streams, GstOggPad *, i);
4139
4140     /* Theoretically, we should be doing this for all streams, but we're only
4141      * doing it for known-to-be-sparse streams at the moment in order not to
4142      * break things for wrongly-muxed streams (like we used to produce once) */
4143     if (stream->map.is_sparse && stream->position != GST_CLOCK_TIME_NONE) {
4144
4145       /* Does this stream lag? Random threshold of 2 seconds */
4146       if (GST_CLOCK_DIFF (stream->position, cur) > (2 * GST_SECOND)) {
4147         GST_DEBUG_OBJECT (stream, "synchronizing stream with others by "
4148             "advancing time from %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT,
4149             GST_TIME_ARGS (stream->position), GST_TIME_ARGS (cur));
4150
4151         stream->position = cur;
4152
4153 #if 0
4154         ogg->segment.base += cur - stream->position;
4155         /* advance stream time (FIXME: is this right, esp. time_pos?) */
4156         gst_pad_push_event (GST_PAD_CAST (stream),
4157             gst_event_new_new_segment (TRUE, ogg->segment.rate,
4158                 ogg->segment.applied_rate,
4159                 GST_FORMAT_TIME, stream->position, -1, stream->position));
4160 #endif
4161       }
4162     }
4163   }
4164 }
4165
4166 /* random access code
4167  *
4168  * - first find all the chains and streams by scanning the file.
4169  * - then get and chain buffers, just like the streaming case.
4170  * - when seeking, we can use the chain info to perform the seek.
4171  */
4172 static void
4173 gst_ogg_demux_loop (GstOggPad * pad)
4174 {
4175   GstOggDemux *ogg;
4176   GstFlowReturn ret;
4177   GstEvent *event;
4178
4179   ogg = GST_OGG_DEMUX (GST_OBJECT_PARENT (pad));
4180
4181   if (ogg->need_chains) {
4182     gboolean res;
4183
4184     /* this is the only place where we write chains and thus need to lock. */
4185     GST_CHAIN_LOCK (ogg);
4186     ret = gst_ogg_demux_find_chains (ogg);
4187     GST_CHAIN_UNLOCK (ogg);
4188     if (ret != GST_FLOW_OK)
4189       goto chain_read_failed;
4190
4191     ogg->need_chains = FALSE;
4192
4193     GST_OBJECT_LOCK (ogg);
4194     ogg->running = TRUE;
4195     event = ogg->event;
4196     ogg->event = NULL;
4197     GST_OBJECT_UNLOCK (ogg);
4198
4199     /* and seek to configured positions without FLUSH */
4200     res = gst_ogg_demux_perform_seek_pull (ogg, event);
4201     if (event)
4202       gst_event_unref (event);
4203
4204     if (!res)
4205       goto seek_failed;
4206   }
4207
4208   if (ogg->segment.rate >= 0.0)
4209     ret = gst_ogg_demux_loop_forward (ogg);
4210   else
4211     ret = gst_ogg_demux_loop_reverse (ogg);
4212
4213   if (ret != GST_FLOW_OK)
4214     goto pause;
4215
4216   gst_ogg_demux_sync_streams (ogg);
4217   return;
4218
4219   /* ERRORS */
4220 chain_read_failed:
4221   {
4222     /* error was posted */
4223     goto pause;
4224   }
4225 seek_failed:
4226   {
4227     GST_ELEMENT_ERROR (ogg, STREAM, DEMUX, (NULL),
4228         ("failed to start demuxing ogg"));
4229     ret = GST_FLOW_ERROR;
4230     goto pause;
4231   }
4232 pause:
4233   {
4234     const gchar *reason = gst_flow_get_name (ret);
4235     GstEvent *event = NULL;
4236
4237     GST_LOG_OBJECT (ogg, "pausing task, reason %s", reason);
4238     gst_pad_pause_task (ogg->sinkpad);
4239
4240     if (ret == GST_FLOW_EOS) {
4241       /* perform EOS logic */
4242       if (ogg->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4243         gint64 stop;
4244         GstMessage *message;
4245
4246         /* for segment playback we need to post when (in stream time)
4247          * we stopped, this is either stop (when set) or the duration. */
4248         if ((stop = ogg->segment.stop) == -1)
4249           stop = ogg->segment.duration;
4250
4251         GST_LOG_OBJECT (ogg, "Sending segment done, at end of segment");
4252         message =
4253             gst_message_new_segment_done (GST_OBJECT (ogg), GST_FORMAT_TIME,
4254             stop);
4255         gst_message_set_seqnum (message, ogg->seqnum);
4256
4257         gst_element_post_message (GST_ELEMENT (ogg), message);
4258       } else {
4259         /* normal playback, send EOS to all linked pads */
4260         GST_LOG_OBJECT (ogg, "Sending EOS, at end of stream");
4261         event = gst_event_new_eos ();
4262       }
4263     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
4264       GST_ELEMENT_ERROR (ogg, STREAM, FAILED,
4265           (_("Internal data stream error.")),
4266           ("stream stopped, reason %s", reason));
4267       event = gst_event_new_eos ();
4268     }
4269
4270     /* For wrong-state we still want to pause the task and stop
4271      * but no error message or other things are necessary.
4272      * wrong-state is no real error and will be caused by flushing,
4273      * e.g. because of a flushing seek.
4274      */
4275     if (event) {
4276       gst_event_set_seqnum (event, ogg->seqnum);
4277       gst_ogg_demux_send_event (ogg, event);
4278     }
4279     return;
4280   }
4281 }
4282
4283 static void
4284 gst_ogg_demux_clear_chains (GstOggDemux * ogg)
4285 {
4286   gint i;
4287
4288   gst_ogg_demux_deactivate_current_chain (ogg);
4289
4290   GST_CHAIN_LOCK (ogg);
4291   for (i = 0; i < ogg->chains->len; i++) {
4292     GstOggChain *chain = g_array_index (ogg->chains, GstOggChain *, i);
4293
4294     gst_ogg_chain_free (chain);
4295   }
4296   ogg->chains = g_array_set_size (ogg->chains, 0);
4297   GST_CHAIN_UNLOCK (ogg);
4298 }
4299
4300 /* this function is called when the pad is activated and should start
4301  * processing data.
4302  *
4303  * We check if we can do random access to decide if we work push or
4304  * pull based.
4305  */
4306 static gboolean
4307 gst_ogg_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
4308 {
4309   GstQuery *query;
4310   gboolean pull_mode;
4311
4312   query = gst_query_new_scheduling ();
4313
4314   if (!gst_pad_peer_query (sinkpad, query)) {
4315     gst_query_unref (query);
4316     goto activate_push;
4317   }
4318
4319   pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL);
4320   gst_query_unref (query);
4321
4322   if (!pull_mode)
4323     goto activate_push;
4324
4325   GST_DEBUG_OBJECT (sinkpad, "activating pull");
4326   return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
4327
4328 activate_push:
4329   {
4330     GST_DEBUG_OBJECT (sinkpad, "activating push");
4331     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
4332   }
4333 }
4334
4335 static gboolean
4336 gst_ogg_demux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
4337     GstPadMode mode, gboolean active)
4338 {
4339   gboolean res;
4340   GstOggDemux *ogg;
4341
4342   ogg = GST_OGG_DEMUX (parent);
4343
4344   switch (mode) {
4345     case GST_PAD_MODE_PUSH:
4346       ogg->pullmode = FALSE;
4347       ogg->resync = FALSE;
4348       res = TRUE;
4349       break;
4350     case GST_PAD_MODE_PULL:
4351       if (active) {
4352         ogg->need_chains = TRUE;
4353         ogg->pullmode = TRUE;
4354
4355         res = gst_pad_start_task (sinkpad, (GstTaskFunction) gst_ogg_demux_loop,
4356             sinkpad);
4357       } else {
4358         res = gst_pad_stop_task (sinkpad);
4359       }
4360       break;
4361     default:
4362       res = FALSE;
4363       break;
4364   }
4365   return res;
4366 }
4367
4368 static GstStateChangeReturn
4369 gst_ogg_demux_change_state (GstElement * element, GstStateChange transition)
4370 {
4371   GstOggDemux *ogg;
4372   GstStateChangeReturn result = GST_STATE_CHANGE_FAILURE;
4373
4374   ogg = GST_OGG_DEMUX (element);
4375
4376   switch (transition) {
4377     case GST_STATE_CHANGE_NULL_TO_READY:
4378       ogg->basetime = 0;
4379       ogg_sync_init (&ogg->sync);
4380       break;
4381     case GST_STATE_CHANGE_READY_TO_PAUSED:
4382       ogg_sync_reset (&ogg->sync);
4383       ogg->running = FALSE;
4384       ogg->bitrate = 0;
4385       ogg->total_time = -1;
4386       GST_PUSH_LOCK (ogg);
4387       ogg->push_byte_offset = 0;
4388       ogg->push_byte_length = -1;
4389       ogg->push_time_length = GST_CLOCK_TIME_NONE;
4390       ogg->push_time_offset = GST_CLOCK_TIME_NONE;
4391       ogg->push_disable_seeking = FALSE;
4392       ogg->push_state = PUSH_PLAYING;
4393       GST_PUSH_UNLOCK (ogg);
4394       gst_segment_init (&ogg->segment, GST_FORMAT_TIME);
4395       break;
4396     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
4397       break;
4398     default:
4399       break;
4400   }
4401
4402   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4403
4404   switch (transition) {
4405     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4406       break;
4407     case GST_STATE_CHANGE_PAUSED_TO_READY:
4408       gst_ogg_demux_clear_chains (ogg);
4409       GST_OBJECT_LOCK (ogg);
4410       ogg->running = FALSE;
4411       GST_OBJECT_UNLOCK (ogg);
4412       break;
4413     case GST_STATE_CHANGE_READY_TO_NULL:
4414       ogg_sync_clear (&ogg->sync);
4415       break;
4416     default:
4417       break;
4418   }
4419   return result;
4420 }
4421
4422 gboolean
4423 gst_ogg_demux_plugin_init (GstPlugin * plugin)
4424 {
4425   GST_DEBUG_CATEGORY_INIT (gst_ogg_demux_debug, "oggdemux", 0, "ogg demuxer");
4426   GST_DEBUG_CATEGORY_INIT (gst_ogg_demux_setup_debug, "oggdemux_setup", 0,
4427       "ogg demuxer setup stage when parsing pipeline");
4428
4429 #ifdef ENABLE_NLS
4430   GST_DEBUG ("binding text domain %s to locale dir %s", GETTEXT_PACKAGE,
4431       LOCALEDIR);
4432   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
4433   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
4434 #endif
4435
4436   return gst_element_register (plugin, "oggdemux", GST_RANK_PRIMARY,
4437       GST_TYPE_OGG_DEMUX);
4438 }
4439
4440 /* prints all info about the element */
4441 #undef GST_CAT_DEFAULT
4442 #define GST_CAT_DEFAULT gst_ogg_demux_setup_debug
4443
4444 #ifdef GST_DISABLE_GST_DEBUG
4445
4446 static void
4447 gst_ogg_print (GstOggDemux * ogg)
4448 {
4449   /* NOP */
4450 }
4451
4452 #else /* !GST_DISABLE_GST_DEBUG */
4453
4454 static void
4455 gst_ogg_print (GstOggDemux * ogg)
4456 {
4457   guint j, i;
4458
4459   GST_INFO_OBJECT (ogg, "%u chains", ogg->chains->len);
4460   GST_INFO_OBJECT (ogg, " total time: %" GST_TIME_FORMAT,
4461       GST_TIME_ARGS (ogg->total_time));
4462
4463   for (i = 0; i < ogg->chains->len; i++) {
4464     GstOggChain *chain = g_array_index (ogg->chains, GstOggChain *, i);
4465
4466     GST_INFO_OBJECT (ogg, " chain %d (%u streams):", i, chain->streams->len);
4467     GST_INFO_OBJECT (ogg,
4468         "  offset: %" G_GINT64_FORMAT " - %" G_GINT64_FORMAT, chain->offset,
4469         chain->end_offset);
4470     GST_INFO_OBJECT (ogg, "  begin time: %" GST_TIME_FORMAT,
4471         GST_TIME_ARGS (chain->begin_time));
4472     GST_INFO_OBJECT (ogg, "  total time: %" GST_TIME_FORMAT,
4473         GST_TIME_ARGS (chain->total_time));
4474     GST_INFO_OBJECT (ogg, "  segment start: %" GST_TIME_FORMAT,
4475         GST_TIME_ARGS (chain->segment_start));
4476     GST_INFO_OBJECT (ogg, "  segment stop:  %" GST_TIME_FORMAT,
4477         GST_TIME_ARGS (chain->segment_stop));
4478
4479     for (j = 0; j < chain->streams->len; j++) {
4480       GstOggPad *stream = g_array_index (chain->streams, GstOggPad *, j);
4481
4482       GST_INFO_OBJECT (ogg, "  stream %08x: %s", stream->map.serialno,
4483           gst_ogg_stream_get_media_type (&stream->map));
4484       GST_INFO_OBJECT (ogg, "   start time:       %" GST_TIME_FORMAT,
4485           GST_TIME_ARGS (stream->start_time));
4486     }
4487   }
4488 }
4489 #endif /* GST_DISABLE_GST_DEBUG */