a7ee8ae5b194d3cc3ea9c7262b1c9ba5cf960d4c
[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 #define GST_FLOW_LIMIT GST_FLOW_CUSTOM_ERROR
51
52 #define GST_CHAIN_LOCK(ogg)     g_mutex_lock((ogg)->chain_lock)
53 #define GST_CHAIN_UNLOCK(ogg)   g_mutex_unlock((ogg)->chain_lock)
54
55 GST_DEBUG_CATEGORY (gst_ogg_demux_debug);
56 GST_DEBUG_CATEGORY (gst_ogg_demux_setup_debug);
57 #define GST_CAT_DEFAULT gst_ogg_demux_debug
58
59
60 static ogg_packet *
61 _ogg_packet_copy (const ogg_packet * packet)
62 {
63   ogg_packet *ret = g_new0 (ogg_packet, 1);
64
65   *ret = *packet;
66   ret->packet = g_memdup (packet->packet, packet->bytes);
67
68   return ret;
69 }
70
71 static void
72 _ogg_packet_free (ogg_packet * packet)
73 {
74   g_free (packet->packet);
75   g_free (packet);
76 }
77
78 static ogg_page *
79 gst_ogg_page_copy (ogg_page * page)
80 {
81   ogg_page *p = g_new0 (ogg_page, 1);
82
83   /* make a copy of the page */
84   p->header = g_memdup (page->header, page->header_len);
85   p->header_len = page->header_len;
86   p->body = g_memdup (page->body, page->body_len);
87   p->body_len = page->body_len;
88
89   return p;
90 }
91
92 static void
93 gst_ogg_page_free (ogg_page * page)
94 {
95   g_free (page->header);
96   g_free (page->body);
97   g_free (page);
98 }
99
100 static gboolean gst_ogg_demux_collect_chain_info (GstOggDemux * ogg,
101     GstOggChain * chain);
102 static gboolean gst_ogg_demux_activate_chain (GstOggDemux * ogg,
103     GstOggChain * chain, GstEvent * event);
104 static void gst_ogg_chain_mark_discont (GstOggChain * chain);
105
106 static gboolean gst_ogg_demux_perform_seek (GstOggDemux * ogg,
107     GstEvent * event);
108 static gboolean gst_ogg_demux_receive_event (GstElement * element,
109     GstEvent * event);
110
111 static void gst_ogg_pad_dispose (GObject * object);
112 static void gst_ogg_pad_finalize (GObject * object);
113
114 static const GstQueryType *gst_ogg_pad_query_types (GstPad * pad);
115 static gboolean gst_ogg_pad_src_query (GstPad * pad, GstQuery * query);
116 static gboolean gst_ogg_pad_event (GstPad * pad, GstEvent * event);
117 static GstCaps *gst_ogg_pad_getcaps (GstPad * pad);
118 static GstOggPad *gst_ogg_chain_get_stream (GstOggChain * chain,
119     glong serialno);
120
121 static GstFlowReturn gst_ogg_demux_combine_flows (GstOggDemux * ogg,
122     GstOggPad * pad, GstFlowReturn ret);
123 static void gst_ogg_demux_sync_streams (GstOggDemux * ogg);
124
125 GType gst_ogg_pad_get_type (void);
126 G_DEFINE_TYPE (GstOggPad, gst_ogg_pad, GST_TYPE_PAD);
127
128 static void
129 gst_ogg_pad_class_init (GstOggPadClass * klass)
130 {
131   GObjectClass *gobject_class;
132
133   gobject_class = (GObjectClass *) klass;
134
135   gobject_class->dispose = gst_ogg_pad_dispose;
136   gobject_class->finalize = gst_ogg_pad_finalize;
137 }
138
139 static void
140 gst_ogg_pad_init (GstOggPad * pad)
141 {
142   gst_pad_set_event_function (GST_PAD (pad),
143       GST_DEBUG_FUNCPTR (gst_ogg_pad_event));
144   gst_pad_set_getcaps_function (GST_PAD (pad),
145       GST_DEBUG_FUNCPTR (gst_ogg_pad_getcaps));
146   gst_pad_set_query_type_function (GST_PAD (pad),
147       GST_DEBUG_FUNCPTR (gst_ogg_pad_query_types));
148   gst_pad_set_query_function (GST_PAD (pad),
149       GST_DEBUG_FUNCPTR (gst_ogg_pad_src_query));
150
151   pad->mode = GST_OGG_PAD_MODE_INIT;
152
153   pad->current_granule = -1;
154   pad->keyframe_granule = -1;
155
156   pad->start_time = GST_CLOCK_TIME_NONE;
157
158   pad->last_stop = GST_CLOCK_TIME_NONE;
159
160   pad->have_type = FALSE;
161   pad->continued = NULL;
162   pad->map.headers = NULL;
163   pad->map.queued = NULL;
164 }
165
166 static void
167 gst_ogg_pad_dispose (GObject * object)
168 {
169   GstOggPad *pad = GST_OGG_PAD (object);
170
171   pad->chain = NULL;
172   pad->ogg = NULL;
173
174   g_list_foreach (pad->map.headers, (GFunc) _ogg_packet_free, NULL);
175   g_list_free (pad->map.headers);
176   pad->map.headers = NULL;
177   g_list_foreach (pad->map.queued, (GFunc) _ogg_packet_free, NULL);
178   g_list_free (pad->map.queued);
179   pad->map.queued = NULL;
180
181   g_free (pad->map.index);
182   pad->map.index = NULL;
183
184   /* clear continued pages */
185   g_list_foreach (pad->continued, (GFunc) gst_ogg_page_free, NULL);
186   g_list_free (pad->continued);
187   pad->continued = NULL;
188
189   if (pad->map.caps) {
190     gst_caps_unref (pad->map.caps);
191     pad->map.caps = NULL;
192   }
193
194   if (pad->map.taglist) {
195     gst_tag_list_free (pad->map.taglist);
196     pad->map.taglist = NULL;
197   }
198
199   ogg_stream_reset (&pad->map.stream);
200
201   G_OBJECT_CLASS (gst_ogg_pad_parent_class)->dispose (object);
202 }
203
204 static void
205 gst_ogg_pad_finalize (GObject * object)
206 {
207   GstOggPad *pad = GST_OGG_PAD (object);
208
209   ogg_stream_clear (&pad->map.stream);
210
211   G_OBJECT_CLASS (gst_ogg_pad_parent_class)->finalize (object);
212 }
213
214 static const GstQueryType *
215 gst_ogg_pad_query_types (GstPad * pad)
216 {
217   static const GstQueryType query_types[] = {
218     GST_QUERY_DURATION,
219     GST_QUERY_SEEKING,
220     0
221   };
222
223   return query_types;
224 }
225
226 static GstCaps *
227 gst_ogg_pad_getcaps (GstPad * pad)
228 {
229   return gst_caps_ref (GST_PAD_CAPS (pad));
230 }
231
232 static gboolean
233 gst_ogg_pad_src_query (GstPad * pad, GstQuery * query)
234 {
235   gboolean res = TRUE;
236   GstOggDemux *ogg;
237
238   ogg = GST_OGG_DEMUX (gst_pad_get_parent (pad));
239
240   switch (GST_QUERY_TYPE (query)) {
241     case GST_QUERY_DURATION:
242     {
243       GstFormat format;
244       gint64 total_time = -1;
245
246       gst_query_parse_duration (query, &format, NULL);
247       /* can only get position in time */
248       if (format != GST_FORMAT_TIME)
249         goto wrong_format;
250
251       if (ogg->total_time != -1) {
252         /* we can return the total length */
253         total_time = ogg->total_time;
254       } else {
255         gint bitrate = ogg->bitrate;
256
257         /* try with length and bitrate */
258         if (bitrate > 0) {
259           GstQuery *uquery;
260
261           /* ask upstream for total length in bytes */
262           uquery = gst_query_new_duration (GST_FORMAT_BYTES);
263           if (gst_pad_peer_query (ogg->sinkpad, uquery)) {
264             gint64 length;
265
266             gst_query_parse_duration (uquery, NULL, &length);
267
268             /* estimate using the bitrate */
269             total_time =
270                 gst_util_uint64_scale (length, 8 * GST_SECOND, bitrate);
271
272             GST_LOG_OBJECT (ogg,
273                 "length: %" G_GINT64_FORMAT ", bitrate %d, total_time %"
274                 GST_TIME_FORMAT, length, bitrate, GST_TIME_ARGS (total_time));
275           }
276           gst_query_unref (uquery);
277         }
278       }
279
280       gst_query_set_duration (query, GST_FORMAT_TIME, total_time);
281       break;
282     }
283     case GST_QUERY_SEEKING:
284     {
285       GstFormat format;
286
287       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
288       if (format == GST_FORMAT_TIME) {
289         gboolean seekable = FALSE;
290         gint64 stop = -1;
291
292         if (ogg->pullmode) {
293           seekable = TRUE;
294           stop = ogg->total_time;
295         } else if (ogg->current_chain->streams->len) {
296           gint i;
297
298           seekable = FALSE;
299           for (i = 0; i < ogg->current_chain->streams->len; i++) {
300             GstOggPad *pad =
301                 g_array_index (ogg->current_chain->streams, GstOggPad *, i);
302
303             seekable |= (pad->map.index != NULL && pad->map.n_index != 0);
304
305             if (pad->map.index != NULL && pad->map.n_index != 0) {
306               GstOggIndex *idx;
307               GstClockTime idx_time;
308
309               idx = &pad->map.index[pad->map.n_index - 1];
310               idx_time =
311                   gst_util_uint64_scale (idx->timestamp, GST_SECOND,
312                   pad->map.kp_denom);
313               if (stop == -1)
314                 stop = idx_time;
315               else
316                 stop = MAX (idx_time, stop);
317             }
318           }
319         }
320
321         gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, stop);
322       } else {
323         res = FALSE;
324       }
325       break;
326     }
327
328     default:
329       res = gst_pad_query_default (pad, query);
330       break;
331   }
332 done:
333   gst_object_unref (ogg);
334
335   return res;
336
337   /* ERRORS */
338 wrong_format:
339   {
340     GST_DEBUG_OBJECT (ogg, "only query duration on TIME is supported");
341     res = FALSE;
342     goto done;
343   }
344 }
345
346 static gboolean
347 gst_ogg_demux_receive_event (GstElement * element, GstEvent * event)
348 {
349   gboolean res;
350   GstOggDemux *ogg;
351
352   ogg = GST_OGG_DEMUX (element);
353
354   switch (GST_EVENT_TYPE (event)) {
355     case GST_EVENT_SEEK:
356       /* now do the seek */
357       res = gst_ogg_demux_perform_seek (ogg, event);
358       gst_event_unref (event);
359       break;
360     default:
361       GST_DEBUG_OBJECT (ogg, "We only handle seek events here");
362       goto error;
363   }
364
365   return res;
366
367   /* ERRORS */
368 error:
369   {
370     GST_DEBUG_OBJECT (ogg, "error handling event");
371     gst_event_unref (event);
372     return FALSE;
373   }
374 }
375
376 static gboolean
377 gst_ogg_pad_event (GstPad * pad, GstEvent * event)
378 {
379   gboolean res;
380   GstOggDemux *ogg;
381
382   ogg = GST_OGG_DEMUX (gst_pad_get_parent (pad));
383
384   switch (GST_EVENT_TYPE (event)) {
385     case GST_EVENT_SEEK:
386       /* now do the seek */
387       res = gst_ogg_demux_perform_seek (ogg, event);
388       gst_event_unref (event);
389       break;
390     default:
391       res = gst_pad_event_default (pad, event);
392       break;
393   }
394   gst_object_unref (ogg);
395
396   return res;
397 }
398
399 static void
400 gst_ogg_pad_reset (GstOggPad * pad)
401 {
402   ogg_stream_reset (&pad->map.stream);
403
404   GST_DEBUG_OBJECT (pad, "doing reset");
405
406   /* clear continued pages */
407   g_list_foreach (pad->continued, (GFunc) gst_ogg_page_free, NULL);
408   g_list_free (pad->continued);
409   pad->continued = NULL;
410
411   pad->last_ret = GST_FLOW_OK;
412   pad->last_stop = GST_CLOCK_TIME_NONE;
413   pad->current_granule = -1;
414   pad->keyframe_granule = -1;
415   pad->is_eos = FALSE;
416 }
417
418 /* queue data, basically takes the packet, puts it in a buffer and store the
419  * buffer in the queued list.  */
420 static GstFlowReturn
421 gst_ogg_demux_queue_data (GstOggPad * pad, ogg_packet * packet)
422 {
423 #ifndef GST_DISABLE_GST_DEBUG
424   GstOggDemux *ogg = pad->ogg;
425 #endif
426
427   GST_DEBUG_OBJECT (ogg, "%p queueing data serial %08lx", pad,
428       pad->map.serialno);
429
430   pad->map.queued = g_list_append (pad->map.queued, _ogg_packet_copy (packet));
431
432   /* we are ok now */
433   return GST_FLOW_OK;
434 }
435
436 static GstFlowReturn
437 gst_ogg_demux_chain_peer (GstOggPad * pad, ogg_packet * packet,
438     gboolean push_headers)
439 {
440   GstBuffer *buf = NULL;
441   GstFlowReturn ret, cret;
442   GstOggDemux *ogg = pad->ogg;
443   gint64 current_time;
444   GstOggChain *chain;
445   gint64 duration;
446   gint offset;
447   gint trim;
448   GstClockTime out_timestamp, out_duration;
449   guint64 out_offset, out_offset_end;
450   gboolean delta_unit = FALSE;
451
452   GST_DEBUG_OBJECT (ogg,
453       "%p streaming to peer serial %08lx", pad, pad->map.serialno);
454
455   if (pad->map.is_ogm) {
456     const guint8 *data;
457     long bytes;
458
459     data = packet->packet;
460     bytes = packet->bytes;
461
462     if (bytes < 1)
463       goto empty_packet;
464
465     if ((data[0] & 1) || (data[0] & 3 && pad->map.is_ogm_text)) {
466       /* We don't push header packets for OGM */
467       cret = gst_ogg_demux_combine_flows (ogg, pad, GST_FLOW_OK);
468       goto done;
469     }
470
471     offset = 1 + (((data[0] & 0xc0) >> 6) | ((data[0] & 0x02) << 1));
472     delta_unit = (((data[0] & 0x08) >> 3) == 0);
473
474     trim = 0;
475
476     /* Strip trailing \0 for subtitles */
477     if (pad->map.is_ogm_text) {
478       while (bytes && data[bytes - 1] == 0) {
479         trim++;
480         bytes--;
481       }
482     }
483   } else if (pad->map.is_vp8) {
484     if ((packet->bytes >= 7 && memcmp (packet->packet, "OVP80\2 ", 7) == 0) ||
485         packet->b_o_s ||
486         (packet->bytes >= 5 && memcmp (packet->packet, "OVP80", 5) == 0)) {
487       /* We don't push header packets for VP8 */
488       cret = gst_ogg_demux_combine_flows (ogg, pad, GST_FLOW_OK);
489       goto done;
490     }
491     offset = 0;
492     trim = 0;
493   } else {
494     offset = 0;
495     trim = 0;
496   }
497
498   /* get timing info for the packet */
499   duration = gst_ogg_stream_get_packet_duration (&pad->map, packet);
500   GST_DEBUG_OBJECT (ogg, "packet duration %" G_GUINT64_FORMAT, duration);
501
502   if (packet->b_o_s) {
503     out_timestamp = GST_CLOCK_TIME_NONE;
504     out_duration = GST_CLOCK_TIME_NONE;
505     out_offset = 0;
506     out_offset_end = -1;
507   } else {
508     if (packet->granulepos != -1) {
509       pad->current_granule = gst_ogg_stream_granulepos_to_granule (&pad->map,
510           packet->granulepos);
511       pad->keyframe_granule =
512           gst_ogg_stream_granulepos_to_key_granule (&pad->map,
513           packet->granulepos);
514       GST_DEBUG_OBJECT (ogg, "new granule %" G_GUINT64_FORMAT,
515           pad->current_granule);
516     } else if (ogg->segment.rate > 0.0 && pad->current_granule != -1) {
517       pad->current_granule += duration;
518       GST_DEBUG_OBJECT (ogg, "interpollating granule %" G_GUINT64_FORMAT,
519           pad->current_granule);
520     }
521     if (ogg->segment.rate < 0.0 && packet->granulepos == -1) {
522       /* negative rates, only set timestamp on the packets with a granulepos */
523       out_timestamp = -1;
524       out_duration = -1;
525       out_offset = -1;
526       out_offset_end = -1;
527     } else {
528       /* we only push buffers after we have a valid granule. This is done so that
529        * we nicely skip packets without a timestamp after a seek. This is ok
530        * because we base or seek on the packet after the page with the smaller
531        * timestamp. */
532       if (pad->current_granule == -1)
533         goto no_timestamp;
534
535       if (pad->map.is_ogm) {
536         out_timestamp = gst_ogg_stream_granule_to_time (&pad->map,
537             pad->current_granule);
538         out_duration = gst_util_uint64_scale (duration,
539             GST_SECOND * pad->map.granulerate_d, pad->map.granulerate_n);
540       } else if (pad->map.is_sparse) {
541         out_timestamp = gst_ogg_stream_granule_to_time (&pad->map,
542             pad->current_granule);
543         out_duration = GST_CLOCK_TIME_NONE;
544       } else {
545         out_timestamp = gst_ogg_stream_granule_to_time (&pad->map,
546             pad->current_granule - duration);
547         out_duration =
548             gst_ogg_stream_granule_to_time (&pad->map,
549             pad->current_granule) - out_timestamp;
550       }
551       out_offset_end =
552           gst_ogg_stream_granule_to_granulepos (&pad->map,
553           pad->current_granule, pad->keyframe_granule);
554       out_offset =
555           gst_ogg_stream_granule_to_time (&pad->map, pad->current_granule);
556     }
557   }
558
559   if (pad->map.is_ogm_text) {
560     /* check for invalid buffer sizes */
561     if (G_UNLIKELY (offset + trim >= packet->bytes))
562       goto empty_packet;
563   }
564
565   ret =
566       gst_pad_alloc_buffer_and_set_caps (GST_PAD_CAST (pad),
567       GST_BUFFER_OFFSET_NONE, packet->bytes - offset - trim,
568       GST_PAD_CAPS (pad), &buf);
569
570   /* combine flows */
571   cret = gst_ogg_demux_combine_flows (ogg, pad, ret);
572   if (ret != GST_FLOW_OK)
573     goto no_buffer;
574
575   /* set delta flag for OGM content */
576   if (delta_unit)
577     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
578
579   /* copy packet in buffer */
580   memcpy (buf->data, packet->packet + offset, packet->bytes - offset - trim);
581
582   GST_BUFFER_TIMESTAMP (buf) = out_timestamp;
583   GST_BUFFER_DURATION (buf) = out_duration;
584   GST_BUFFER_OFFSET (buf) = out_offset;
585   GST_BUFFER_OFFSET_END (buf) = out_offset_end;
586
587   /* Mark discont on the buffer */
588   if (pad->discont) {
589     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
590     pad->discont = FALSE;
591   }
592
593   pad->last_stop = ogg->segment.last_stop;
594
595   /* don't push the header packets when we are asked to skip them */
596   if (!packet->b_o_s || push_headers) {
597     ret = gst_pad_push (GST_PAD_CAST (pad), buf);
598     buf = NULL;
599
600     /* combine flows */
601     cret = gst_ogg_demux_combine_flows (ogg, pad, ret);
602   }
603
604   /* we're done with skeleton stuff */
605   if (pad->map.is_skeleton)
606     goto done;
607
608   /* check if valid granulepos, then we can calculate the current
609    * position. We know the granule for each packet but we only want to update
610    * the last_stop when we have a valid granulepos on the packet because else
611    * our time jumps around for the different streams. */
612   if (packet->granulepos < 0)
613     goto done;
614
615   /* convert to time */
616   current_time = gst_ogg_stream_get_end_time_for_granulepos (&pad->map,
617       packet->granulepos);
618
619   /* convert to stream time */
620   if ((chain = pad->chain)) {
621     gint64 chain_start = 0;
622
623     if (chain->segment_start != GST_CLOCK_TIME_NONE)
624       chain_start = chain->segment_start;
625
626     current_time = current_time - chain_start + chain->begin_time;
627   }
628
629   /* and store as the current position */
630   gst_segment_set_last_stop (&ogg->segment, GST_FORMAT_TIME, current_time);
631
632   GST_DEBUG_OBJECT (ogg, "ogg current time %" GST_TIME_FORMAT,
633       GST_TIME_ARGS (current_time));
634
635   /* check stream eos */
636   if ((ogg->segment.rate > 0.0 && ogg->segment.stop != GST_CLOCK_TIME_NONE &&
637           current_time > ogg->segment.stop) ||
638       (ogg->segment.rate < 0.0 && ogg->segment.start != GST_CLOCK_TIME_NONE &&
639           current_time < ogg->segment.start)) {
640     GST_DEBUG_OBJECT (ogg, "marking pad %p EOS", pad);
641     pad->is_eos = TRUE;
642   }
643
644 done:
645   if (buf)
646     gst_buffer_unref (buf);
647   /* return combined flow result */
648   return cret;
649
650   /* special cases */
651 empty_packet:
652   {
653     GST_DEBUG_OBJECT (ogg, "Skipping empty packet");
654     cret = gst_ogg_demux_combine_flows (ogg, pad, GST_FLOW_OK);
655     goto done;
656   }
657
658 no_timestamp:
659   {
660     GST_DEBUG_OBJECT (ogg, "skipping packet: no valid granule found yet");
661     cret = gst_ogg_demux_combine_flows (ogg, pad, GST_FLOW_OK);
662     goto done;
663   }
664
665 no_buffer:
666   {
667     GST_DEBUG_OBJECT (ogg,
668         "%p could not get buffer from peer %08lx, %d (%s), combined %d (%s)",
669         pad, pad->map.serialno, ret, gst_flow_get_name (ret),
670         cret, gst_flow_get_name (cret));
671     goto done;
672   }
673 }
674
675 static guint64
676 gst_ogg_demux_collect_start_time (GstOggDemux * ogg, GstOggChain * chain)
677 {
678   gint i;
679   guint64 start_time = G_MAXUINT64;
680
681   for (i = 0; i < chain->streams->len; i++) {
682     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
683
684     if (pad->map.is_sparse)
685       continue;
686
687     /*  can do this if the pad start time is not defined */
688     if (pad->start_time == GST_CLOCK_TIME_NONE) {
689       start_time = G_MAXUINT64;
690       break;
691     } else {
692       start_time = MIN (start_time, pad->start_time);
693     }
694   }
695   return start_time;
696 }
697
698 /* submit a packet to the oggpad, this function will run the
699  * typefind code for the pad if this is the first packet for this
700  * stream 
701  */
702 static GstFlowReturn
703 gst_ogg_pad_submit_packet (GstOggPad * pad, ogg_packet * packet)
704 {
705   gint64 granule;
706   GstFlowReturn ret = GST_FLOW_OK;
707
708   GstOggDemux *ogg = pad->ogg;
709
710   GST_DEBUG_OBJECT (ogg, "%p submit packet serial %08lx", pad,
711       pad->map.serialno);
712
713   if (!pad->have_type) {
714     pad->have_type = gst_ogg_stream_setup_map (&pad->map, packet);
715     if (!pad->have_type) {
716       pad->map.caps = gst_caps_new_simple ("application/x-unknown", NULL);
717     }
718     if (pad->map.is_skeleton) {
719       GST_DEBUG_OBJECT (ogg, "we have a fishead");
720       /* copy values over to global ogg level */
721       ogg->basetime = pad->map.basetime;
722       ogg->prestime = pad->map.prestime;
723
724       /* use total time to update the total ogg time */
725       if (ogg->total_time == -1) {
726         ogg->total_time = pad->map.total_time;
727       } else if (pad->map.total_time > 0) {
728         ogg->total_time = MAX (ogg->total_time, pad->map.total_time);
729       }
730     }
731     if (pad->map.caps) {
732       gst_pad_set_caps (GST_PAD (pad), pad->map.caps);
733     } else {
734       GST_WARNING_OBJECT (ogg, "stream parser didn't create src pad caps");
735     }
736   }
737
738   if (pad->map.is_skeleton) {
739     guint32 serialno;
740     GstOggPad *skel_pad;
741     GstOggSkeleton type;
742
743     /* try to parse the serialno first */
744     if (gst_ogg_map_parse_fisbone (&pad->map, packet->packet, packet->bytes,
745             &serialno, &type)) {
746
747       GST_WARNING_OBJECT (pad->ogg,
748           "got skeleton packet for stream 0x%08x", serialno);
749
750       skel_pad = gst_ogg_chain_get_stream (pad->chain, serialno);
751       if (skel_pad) {
752         switch (type) {
753           case GST_OGG_SKELETON_FISBONE:
754             /* parse the remainder of the fisbone in the pad with the serialno,
755              * note that we ignore the start_time as this is usually wrong for
756              * live streams */
757             gst_ogg_map_add_fisbone (&skel_pad->map, &pad->map, packet->packet,
758                 packet->bytes, NULL);
759             break;
760           case GST_OGG_SKELETON_INDEX:
761             gst_ogg_map_add_index (&skel_pad->map, &pad->map, packet->packet,
762                 packet->bytes);
763
764             /* use total time to update the total ogg time */
765             if (ogg->total_time == -1) {
766               ogg->total_time = skel_pad->map.total_time;
767             } else if (skel_pad->map.total_time > 0) {
768               ogg->total_time = MAX (ogg->total_time, skel_pad->map.total_time);
769             }
770             break;
771           default:
772             break;
773         }
774
775       } else {
776         GST_WARNING_OBJECT (pad->ogg,
777             "found skeleton fisbone for an unknown stream 0x%08x", serialno);
778       }
779     }
780   }
781
782   granule = gst_ogg_stream_granulepos_to_granule (&pad->map,
783       packet->granulepos);
784   if (granule != -1) {
785     GST_DEBUG_OBJECT (ogg, "%p has granulepos %" G_GINT64_FORMAT, pad, granule);
786     pad->current_granule = granule;
787   }
788
789   /* restart header packet count when seeing a b_o_s page;
790    * particularly useful following a seek or even following chain finding */
791   if (packet->b_o_s) {
792     GST_DEBUG_OBJECT (ogg, "b_o_s packet, resetting header packet count");
793     pad->map.n_header_packets_seen = 0;
794     if (!pad->map.have_headers) {
795       GST_DEBUG_OBJECT (ogg, "clearing header packets");
796       g_list_foreach (pad->map.headers, (GFunc) _ogg_packet_free, NULL);
797       g_list_free (pad->map.headers);
798       pad->map.headers = NULL;
799     }
800   }
801
802   /* Overload the value of b_o_s in ogg_packet with a flag whether or
803    * not this is a header packet.  Maybe some day this could be cleaned
804    * up.  */
805   packet->b_o_s = gst_ogg_stream_packet_is_header (&pad->map, packet);
806   if (!packet->b_o_s) {
807     GST_DEBUG ("found non-header packet");
808     pad->map.have_headers = TRUE;
809     if (pad->start_time == GST_CLOCK_TIME_NONE) {
810       gint64 duration = gst_ogg_stream_get_packet_duration (&pad->map, packet);
811       GST_DEBUG ("duration %" G_GINT64_FORMAT, duration);
812       if (duration != -1) {
813         pad->map.accumulated_granule += duration;
814         GST_DEBUG ("accumulated granule %" G_GINT64_FORMAT,
815             pad->map.accumulated_granule);
816       }
817
818       if (packet->granulepos != -1) {
819         ogg_int64_t start_granule;
820         gint64 granule;
821
822         granule = gst_ogg_stream_granulepos_to_granule (&pad->map,
823             packet->granulepos);
824
825         if (granule > pad->map.accumulated_granule)
826           start_granule = granule - pad->map.accumulated_granule;
827         else
828           start_granule = 0;
829
830         pad->start_time = gst_ogg_stream_granule_to_time (&pad->map,
831             start_granule);
832         GST_DEBUG ("start time %" G_GINT64_FORMAT, pad->start_time);
833       } else {
834         packet->granulepos = gst_ogg_stream_granule_to_granulepos (&pad->map,
835             pad->map.accumulated_granule, pad->keyframe_granule);
836       }
837     }
838   } else {
839     /* look for tags in header packet (before inc header count) */
840     gst_ogg_stream_extract_tags (&pad->map, packet);
841     pad->map.n_header_packets_seen++;
842     if (!pad->map.have_headers) {
843       pad->map.headers =
844           g_list_append (pad->map.headers, _ogg_packet_copy (packet));
845       GST_DEBUG ("keeping header packet %d", pad->map.n_header_packets_seen);
846     }
847   }
848
849   /* we know the start_time of the pad data, see if we
850    * can activate the complete chain if this is a dynamic
851    * chain. We need all the headers too for this. */
852   if (pad->start_time != GST_CLOCK_TIME_NONE && pad->map.have_headers) {
853     GstOggChain *chain = pad->chain;
854
855     /* check if complete chain has start time */
856     if (chain == ogg->building_chain) {
857       GstEvent *event = NULL;
858
859       if (ogg->resync) {
860         guint64 start_time;
861
862         GST_DEBUG_OBJECT (ogg, "need to resync");
863
864         /* when we need to resync after a seek, we wait until we have received
865          * timestamps on all streams */
866         start_time = gst_ogg_demux_collect_start_time (ogg, chain);
867
868         if (start_time != G_MAXUINT64) {
869           gint64 segment_time;
870
871           GST_DEBUG_OBJECT (ogg, "start_time:  %" GST_TIME_FORMAT,
872               GST_TIME_ARGS (start_time));
873
874           if (chain->segment_start < start_time)
875             segment_time =
876                 (start_time - chain->segment_start) + chain->begin_time;
877           else
878             segment_time = chain->begin_time;
879
880           /* create the newsegment event we are going to send out */
881           event = gst_event_new_new_segment (FALSE, ogg->segment.rate,
882               GST_FORMAT_TIME, start_time, chain->segment_stop, segment_time);
883
884           ogg->resync = FALSE;
885         }
886       } else {
887         /* see if we have enough info to activate the chain, we have enough info
888          * when all streams have a valid start time. */
889         if (gst_ogg_demux_collect_chain_info (ogg, chain)) {
890
891           GST_DEBUG_OBJECT (ogg, "segment_start: %" GST_TIME_FORMAT,
892               GST_TIME_ARGS (chain->segment_start));
893           GST_DEBUG_OBJECT (ogg, "segment_stop:  %" GST_TIME_FORMAT,
894               GST_TIME_ARGS (chain->segment_stop));
895           GST_DEBUG_OBJECT (ogg, "segment_time:  %" GST_TIME_FORMAT,
896               GST_TIME_ARGS (chain->begin_time));
897
898           /* create the newsegment event we are going to send out */
899           event = gst_event_new_new_segment (FALSE, ogg->segment.rate,
900               GST_FORMAT_TIME, chain->segment_start, chain->segment_stop,
901               chain->begin_time);
902         }
903       }
904
905       if (event) {
906         gst_event_set_seqnum (event, ogg->seqnum);
907
908         gst_ogg_demux_activate_chain (ogg, chain, event);
909
910         ogg->building_chain = NULL;
911       }
912     }
913   }
914
915   /* if we are building a chain, store buffer for when we activate
916    * it. This path is taken if we operate in streaming mode. */
917   if (ogg->building_chain) {
918     /* bos packets where stored in the header list so we can discard
919      * them here*/
920     if (!packet->b_o_s)
921       ret = gst_ogg_demux_queue_data (pad, packet);
922   }
923   /* else we are completely streaming to the peer */
924   else {
925     ret = gst_ogg_demux_chain_peer (pad, packet, !ogg->pullmode);
926   }
927   return ret;
928 }
929
930 /* flush at most @npackets from the stream layer. All packets if 
931  * @npackets is 0;
932  */
933 static GstFlowReturn
934 gst_ogg_pad_stream_out (GstOggPad * pad, gint npackets)
935 {
936   GstFlowReturn result = GST_FLOW_OK;
937   gboolean done = FALSE;
938   GstOggDemux *ogg;
939
940   ogg = pad->ogg;
941
942   while (!done) {
943     int ret;
944     ogg_packet packet;
945
946     ret = ogg_stream_packetout (&pad->map.stream, &packet);
947     switch (ret) {
948       case 0:
949         GST_LOG_OBJECT (ogg, "packetout done");
950         done = TRUE;
951         break;
952       case -1:
953         GST_LOG_OBJECT (ogg, "packetout discont");
954         gst_ogg_chain_mark_discont (pad->chain);
955         break;
956       case 1:
957         GST_LOG_OBJECT (ogg, "packetout gave packet of size %ld", packet.bytes);
958         result = gst_ogg_pad_submit_packet (pad, &packet);
959         /* not linked is not a problem, it's possible that we are still
960          * collecting headers and that we don't have exposed the pads yet */
961         if (result == GST_FLOW_NOT_LINKED)
962           break;
963         else if (result <= GST_FLOW_UNEXPECTED)
964           goto could_not_submit;
965         break;
966       default:
967         GST_WARNING_OBJECT (ogg,
968             "invalid return value %d for ogg_stream_packetout, resetting stream",
969             ret);
970         gst_ogg_pad_reset (pad);
971         break;
972     }
973     if (npackets > 0) {
974       npackets--;
975       done = (npackets == 0);
976     }
977   }
978   return result;
979
980   /* ERRORS */
981 could_not_submit:
982   {
983     GST_WARNING_OBJECT (ogg,
984         "could not submit packet for stream %08lx, error: %d",
985         pad->map.serialno, result);
986     gst_ogg_pad_reset (pad);
987     return result;
988   }
989 }
990
991 /* submit a page to an oggpad, this function will then submit all
992  * the packets in the page.
993  */
994 static GstFlowReturn
995 gst_ogg_pad_submit_page (GstOggPad * pad, ogg_page * page)
996 {
997   GstFlowReturn result = GST_FLOW_OK;
998   GstOggDemux *ogg;
999   gboolean continued = FALSE;
1000
1001   ogg = pad->ogg;
1002
1003   /* for negative rates we read pages backwards and must therefore be carefull
1004    * with continued pages */
1005   if (ogg->segment.rate < 0.0) {
1006     gint npackets;
1007
1008     continued = ogg_page_continued (page);
1009
1010     /* number of completed packets in the page */
1011     npackets = ogg_page_packets (page);
1012     if (!continued) {
1013       /* page is not continued so it contains at least one packet start. It's
1014        * possible that no packet ends on this page (npackets == 0). In that
1015        * case, the next (continued) page(s) we kept contain the remainder of the
1016        * packets. We mark npackets=1 to make us start decoding the pages in the
1017        * remainder of the algorithm. */
1018       if (npackets == 0)
1019         npackets = 1;
1020     }
1021     GST_LOG_OBJECT (ogg, "continued: %d, %d packets", continued, npackets);
1022
1023     if (npackets == 0) {
1024       GST_LOG_OBJECT (ogg, "no decodable packets, we need a previous page");
1025       goto done;
1026     }
1027   }
1028
1029   if (ogg_stream_pagein (&pad->map.stream, page) != 0)
1030     goto choked;
1031
1032   /* flush all packets in the stream layer, this might not give a packet if
1033    * the page had no packets finishing on the page (npackets == 0). */
1034   result = gst_ogg_pad_stream_out (pad, 0);
1035
1036   if (pad->continued) {
1037     ogg_packet packet;
1038
1039     /* now send the continued pages to the stream layer */
1040     while (pad->continued) {
1041       ogg_page *p = (ogg_page *) pad->continued->data;
1042
1043       GST_LOG_OBJECT (ogg, "submitting continued page %p", p);
1044       if (ogg_stream_pagein (&pad->map.stream, p) != 0)
1045         goto choked;
1046
1047       pad->continued = g_list_delete_link (pad->continued, pad->continued);
1048
1049       /* free the page */
1050       gst_ogg_page_free (p);
1051     }
1052
1053     GST_LOG_OBJECT (ogg, "flushing last continued packet");
1054     /* flush 1 continued packet in the stream layer */
1055     result = gst_ogg_pad_stream_out (pad, 1);
1056
1057     /* flush all remaining packets, we pushed them in the previous round.
1058      * We don't use _reset() because we still want to get the discont when
1059      * we submit a next page. */
1060     while (ogg_stream_packetout (&pad->map.stream, &packet) != 0);
1061   }
1062
1063 done:
1064   /* keep continued pages (only in reverse mode) */
1065   if (continued) {
1066     ogg_page *p = gst_ogg_page_copy (page);
1067
1068     GST_LOG_OBJECT (ogg, "keeping continued page %p", p);
1069     pad->continued = g_list_prepend (pad->continued, p);
1070   }
1071
1072   return result;
1073
1074 choked:
1075   {
1076     GST_WARNING_OBJECT (ogg,
1077         "ogg stream choked on page (serial %08lx), resetting stream",
1078         pad->map.serialno);
1079     gst_ogg_pad_reset (pad);
1080     /* we continue to recover */
1081     return GST_FLOW_OK;
1082   }
1083 }
1084
1085
1086 static GstOggChain *
1087 gst_ogg_chain_new (GstOggDemux * ogg)
1088 {
1089   GstOggChain *chain = g_new0 (GstOggChain, 1);
1090
1091   GST_DEBUG_OBJECT (ogg, "creating new chain %p", chain);
1092   chain->ogg = ogg;
1093   chain->offset = -1;
1094   chain->bytes = -1;
1095   chain->have_bos = FALSE;
1096   chain->streams = g_array_new (FALSE, TRUE, sizeof (GstOggPad *));
1097   chain->begin_time = GST_CLOCK_TIME_NONE;
1098   chain->segment_start = GST_CLOCK_TIME_NONE;
1099   chain->segment_stop = GST_CLOCK_TIME_NONE;
1100   chain->total_time = GST_CLOCK_TIME_NONE;
1101
1102   return chain;
1103 }
1104
1105 static void
1106 gst_ogg_chain_free (GstOggChain * chain)
1107 {
1108   gint i;
1109
1110   for (i = 0; i < chain->streams->len; i++) {
1111     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
1112
1113     gst_object_unref (pad);
1114   }
1115   g_array_free (chain->streams, TRUE);
1116   g_free (chain);
1117 }
1118
1119 static void
1120 gst_ogg_pad_mark_discont (GstOggPad * pad)
1121 {
1122   pad->discont = TRUE;
1123   pad->map.last_size = 0;
1124 }
1125
1126 static void
1127 gst_ogg_chain_mark_discont (GstOggChain * chain)
1128 {
1129   gint i;
1130
1131   for (i = 0; i < chain->streams->len; i++) {
1132     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
1133
1134     gst_ogg_pad_mark_discont (pad);
1135   }
1136 }
1137
1138 static void
1139 gst_ogg_chain_reset (GstOggChain * chain)
1140 {
1141   gint i;
1142
1143   for (i = 0; i < chain->streams->len; i++) {
1144     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
1145
1146     gst_ogg_pad_reset (pad);
1147   }
1148 }
1149
1150 static GstOggPad *
1151 gst_ogg_chain_new_stream (GstOggChain * chain, glong serialno)
1152 {
1153   GstOggPad *ret;
1154   GstTagList *list;
1155   gchar *name;
1156
1157   GST_DEBUG_OBJECT (chain->ogg, "creating new stream %08lx in chain %p",
1158       serialno, chain);
1159
1160   ret = g_object_new (GST_TYPE_OGG_PAD, NULL);
1161   /* we own this one */
1162   gst_object_ref_sink (ret);
1163
1164   GST_PAD_DIRECTION (ret) = GST_PAD_SRC;
1165   gst_ogg_pad_mark_discont (ret);
1166
1167   ret->chain = chain;
1168   ret->ogg = chain->ogg;
1169
1170   ret->map.serialno = serialno;
1171   if (ogg_stream_init (&ret->map.stream, serialno) != 0)
1172     goto init_failed;
1173
1174   name = g_strdup_printf ("serial_%08lx", serialno);
1175   gst_object_set_name (GST_OBJECT (ret), name);
1176   g_free (name);
1177
1178   /* FIXME: either do something with it or remove it */
1179   list = gst_tag_list_new ();
1180   gst_tag_list_add (list, GST_TAG_MERGE_REPLACE, GST_TAG_SERIAL, serialno,
1181       NULL);
1182   gst_tag_list_free (list);
1183
1184   GST_DEBUG_OBJECT (chain->ogg,
1185       "created new ogg src %p for stream with serial %08lx", ret, serialno);
1186
1187   g_array_append_val (chain->streams, ret);
1188
1189   return ret;
1190
1191   /* ERRORS */
1192 init_failed:
1193   {
1194     GST_ERROR ("Could not initialize ogg_stream struct for serial %08lx.",
1195         serialno);
1196     gst_object_unref (ret);
1197     return NULL;
1198   }
1199 }
1200
1201 static GstOggPad *
1202 gst_ogg_chain_get_stream (GstOggChain * chain, glong serialno)
1203 {
1204   gint i;
1205
1206   for (i = 0; i < chain->streams->len; i++) {
1207     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
1208
1209     if (pad->map.serialno == serialno)
1210       return pad;
1211   }
1212   return NULL;
1213 }
1214
1215 static gboolean
1216 gst_ogg_chain_has_stream (GstOggChain * chain, glong serialno)
1217 {
1218   return gst_ogg_chain_get_stream (chain, serialno) != NULL;
1219 }
1220
1221 /* signals and args */
1222 enum
1223 {
1224   /* FILL ME */
1225   LAST_SIGNAL
1226 };
1227
1228 enum
1229 {
1230   ARG_0
1231       /* FILL ME */
1232 };
1233
1234 static GstStaticPadTemplate ogg_demux_src_template_factory =
1235 GST_STATIC_PAD_TEMPLATE ("src_%d",
1236     GST_PAD_SRC,
1237     GST_PAD_SOMETIMES,
1238     GST_STATIC_CAPS_ANY);
1239
1240 static GstStaticPadTemplate ogg_demux_sink_template_factory =
1241     GST_STATIC_PAD_TEMPLATE ("sink",
1242     GST_PAD_SINK,
1243     GST_PAD_ALWAYS,
1244     GST_STATIC_CAPS ("application/ogg; application/x-annodex")
1245     );
1246
1247 static void gst_ogg_demux_finalize (GObject * object);
1248
1249 static GstFlowReturn gst_ogg_demux_read_chain (GstOggDemux * ogg,
1250     GstOggChain ** chain);
1251 static GstFlowReturn gst_ogg_demux_read_end_chain (GstOggDemux * ogg,
1252     GstOggChain * chain);
1253
1254 static gboolean gst_ogg_demux_sink_event (GstPad * pad, GstEvent * event);
1255 static void gst_ogg_demux_loop (GstOggPad * pad);
1256 static GstFlowReturn gst_ogg_demux_chain (GstPad * pad, GstBuffer * buffer);
1257 static gboolean gst_ogg_demux_sink_activate (GstPad * sinkpad);
1258 static gboolean gst_ogg_demux_sink_activate_pull (GstPad * sinkpad,
1259     gboolean active);
1260 static gboolean gst_ogg_demux_sink_activate_push (GstPad * sinkpad,
1261     gboolean active);
1262 static GstStateChangeReturn gst_ogg_demux_change_state (GstElement * element,
1263     GstStateChange transition);
1264 static gboolean gst_ogg_demux_send_event (GstOggDemux * ogg, GstEvent * event);
1265
1266 static void gst_ogg_print (GstOggDemux * demux);
1267
1268 GST_BOILERPLATE (GstOggDemux, gst_ogg_demux, GstElement, GST_TYPE_ELEMENT);
1269
1270 static void
1271 gst_ogg_demux_base_init (gpointer g_class)
1272 {
1273   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
1274
1275   gst_element_class_set_details_simple (element_class,
1276       "Ogg demuxer", "Codec/Demuxer",
1277       "demux ogg streams (info about ogg: http://xiph.org)",
1278       "Wim Taymans <wim@fluendo.com>");
1279
1280   gst_element_class_add_pad_template (element_class,
1281       gst_static_pad_template_get (&ogg_demux_sink_template_factory));
1282   gst_element_class_add_pad_template (element_class,
1283       gst_static_pad_template_get (&ogg_demux_src_template_factory));
1284 }
1285
1286 static void
1287 gst_ogg_demux_class_init (GstOggDemuxClass * klass)
1288 {
1289   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
1290   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1291
1292   gstelement_class->change_state = gst_ogg_demux_change_state;
1293   gstelement_class->send_event = gst_ogg_demux_receive_event;
1294
1295   gobject_class->finalize = gst_ogg_demux_finalize;
1296 }
1297
1298 static void
1299 gst_ogg_demux_init (GstOggDemux * ogg, GstOggDemuxClass * g_class)
1300 {
1301   /* create the sink pad */
1302   ogg->sinkpad =
1303       gst_pad_new_from_static_template (&ogg_demux_sink_template_factory,
1304       "sink");
1305
1306   gst_pad_set_event_function (ogg->sinkpad, gst_ogg_demux_sink_event);
1307   gst_pad_set_chain_function (ogg->sinkpad, gst_ogg_demux_chain);
1308   gst_pad_set_activate_function (ogg->sinkpad, gst_ogg_demux_sink_activate);
1309   gst_pad_set_activatepull_function (ogg->sinkpad,
1310       gst_ogg_demux_sink_activate_pull);
1311   gst_pad_set_activatepush_function (ogg->sinkpad,
1312       gst_ogg_demux_sink_activate_push);
1313   gst_element_add_pad (GST_ELEMENT (ogg), ogg->sinkpad);
1314
1315   ogg->chain_lock = g_mutex_new ();
1316   ogg->chains = g_array_new (FALSE, TRUE, sizeof (GstOggChain *));
1317
1318   ogg->newsegment = NULL;
1319 }
1320
1321 static void
1322 gst_ogg_demux_finalize (GObject * object)
1323 {
1324   GstOggDemux *ogg;
1325
1326   ogg = GST_OGG_DEMUX (object);
1327
1328   g_array_free (ogg->chains, TRUE);
1329   g_mutex_free (ogg->chain_lock);
1330   ogg_sync_clear (&ogg->sync);
1331
1332   if (ogg->newsegment)
1333     gst_event_unref (ogg->newsegment);
1334
1335   G_OBJECT_CLASS (parent_class)->finalize (object);
1336 }
1337
1338 static void
1339 gst_ogg_demux_reset_streams (GstOggDemux * ogg)
1340 {
1341   GstOggChain *chain;
1342   guint i;
1343
1344   chain = ogg->current_chain;
1345   if (chain == NULL)
1346     return;
1347
1348   for (i = 0; i < chain->streams->len; i++) {
1349     GstOggPad *stream = g_array_index (chain->streams, GstOggPad *, i);
1350
1351     stream->start_time = -1;
1352     stream->map.accumulated_granule = 0;
1353   }
1354   ogg->building_chain = chain;
1355   ogg->current_chain = NULL;
1356   ogg->resync = TRUE;
1357 }
1358
1359 static gboolean
1360 gst_ogg_demux_sink_event (GstPad * pad, GstEvent * event)
1361 {
1362   gboolean res;
1363   GstOggDemux *ogg;
1364
1365   ogg = GST_OGG_DEMUX (gst_pad_get_parent (pad));
1366
1367   switch (GST_EVENT_TYPE (event)) {
1368     case GST_EVENT_FLUSH_START:
1369       res = gst_ogg_demux_send_event (ogg, event);
1370       break;
1371     case GST_EVENT_FLUSH_STOP:
1372       GST_DEBUG_OBJECT (ogg, "got a flush stop event");
1373       ogg_sync_reset (&ogg->sync);
1374       res = gst_ogg_demux_send_event (ogg, event);
1375       gst_ogg_demux_reset_streams (ogg);
1376       break;
1377     case GST_EVENT_NEWSEGMENT:
1378       GST_DEBUG_OBJECT (ogg, "got a new segment event");
1379       gst_event_unref (event);
1380       res = TRUE;
1381       break;
1382     case GST_EVENT_EOS:
1383     {
1384       GST_DEBUG_OBJECT (ogg, "got an EOS event");
1385       res = gst_ogg_demux_send_event (ogg, event);
1386       if (ogg->current_chain == NULL) {
1387         GST_ELEMENT_ERROR (ogg, STREAM, DEMUX, (NULL),
1388             ("can't get first chain"));
1389       }
1390       break;
1391     }
1392     default:
1393       res = gst_ogg_demux_send_event (ogg, event);
1394       break;
1395   }
1396   gst_object_unref (ogg);
1397
1398   return res;
1399 }
1400
1401 /* submit the given buffer to the ogg sync.
1402  *
1403  * Returns the number of bytes submited.
1404  */
1405 static GstFlowReturn
1406 gst_ogg_demux_submit_buffer (GstOggDemux * ogg, GstBuffer * buffer)
1407 {
1408   gint size;
1409   guint8 *data;
1410   gchar *oggbuffer;
1411   GstFlowReturn ret = GST_FLOW_OK;
1412
1413   size = GST_BUFFER_SIZE (buffer);
1414   data = GST_BUFFER_DATA (buffer);
1415
1416   GST_DEBUG_OBJECT (ogg, "submitting %u bytes", size);
1417   if (G_UNLIKELY (size == 0))
1418     goto done;
1419
1420   oggbuffer = ogg_sync_buffer (&ogg->sync, size);
1421   if (G_UNLIKELY (oggbuffer == NULL))
1422     goto no_buffer;
1423
1424   memcpy (oggbuffer, data, size);
1425   if (G_UNLIKELY (ogg_sync_wrote (&ogg->sync, size) < 0))
1426     goto write_failed;
1427
1428 done:
1429   gst_buffer_unref (buffer);
1430
1431   return ret;
1432
1433   /* ERRORS */
1434 no_buffer:
1435   {
1436     GST_ELEMENT_ERROR (ogg, STREAM, DECODE,
1437         (NULL), ("failed to get ogg sync buffer"));
1438     ret = GST_FLOW_ERROR;
1439     goto done;
1440   }
1441 write_failed:
1442   {
1443     GST_ELEMENT_ERROR (ogg, STREAM, DECODE,
1444         (NULL), ("failed to write %d bytes to the sync buffer", size));
1445     ret = GST_FLOW_ERROR;
1446     goto done;
1447   }
1448 }
1449
1450 /* in random access mode this code updates the current read position
1451  * and resets the ogg sync buffer so that the next read will happen
1452  * from this new location.
1453  */
1454 static void
1455 gst_ogg_demux_seek (GstOggDemux * ogg, gint64 offset)
1456 {
1457   GST_LOG_OBJECT (ogg, "seeking to %" G_GINT64_FORMAT, offset);
1458
1459   ogg->offset = offset;
1460   ogg->read_offset = offset;
1461   ogg_sync_reset (&ogg->sync);
1462 }
1463
1464 /* read more data from the current offset and submit to
1465  * the ogg sync layer.
1466  */
1467 static GstFlowReturn
1468 gst_ogg_demux_get_data (GstOggDemux * ogg, gint64 end_offset)
1469 {
1470   GstFlowReturn ret;
1471   GstBuffer *buffer;
1472
1473   GST_LOG_OBJECT (ogg,
1474       "get data %" G_GINT64_FORMAT " %" G_GINT64_FORMAT " %" G_GINT64_FORMAT,
1475       ogg->read_offset, ogg->length, end_offset);
1476
1477   if (end_offset > 0 && ogg->read_offset >= end_offset)
1478     goto boundary_reached;
1479
1480   if (ogg->read_offset == ogg->length)
1481     goto eos;
1482
1483   ret = gst_pad_pull_range (ogg->sinkpad, ogg->read_offset, CHUNKSIZE, &buffer);
1484   if (ret != GST_FLOW_OK)
1485     goto error;
1486
1487   ogg->read_offset += GST_BUFFER_SIZE (buffer);
1488
1489   ret = gst_ogg_demux_submit_buffer (ogg, buffer);
1490
1491   return ret;
1492
1493   /* ERROR */
1494 boundary_reached:
1495   {
1496     GST_LOG_OBJECT (ogg, "reached boundary");
1497     return GST_FLOW_LIMIT;
1498   }
1499 eos:
1500   {
1501     GST_LOG_OBJECT (ogg, "reached EOS");
1502     return GST_FLOW_UNEXPECTED;
1503   }
1504 error:
1505   {
1506     GST_WARNING_OBJECT (ogg, "got %d (%s) from pull range", ret,
1507         gst_flow_get_name (ret));
1508     return ret;
1509   }
1510 }
1511
1512 /* Read the next page from the current offset.
1513  * boundary: number of bytes ahead we allow looking for;
1514  * -1 if no boundary
1515  *
1516  * @offset will contain the offset the next page starts at when this function
1517  * returns GST_FLOW_OK.
1518  *
1519  * GST_FLOW_UNEXPECTED is returned on EOS.
1520  *
1521  * GST_FLOW_LIMIT is returned when we did not find a page before the
1522  * boundary. If @boundary is -1, this is never returned.
1523  *
1524  * Any other error returned while retrieving data from the peer is returned as
1525  * is.
1526  */
1527 static GstFlowReturn
1528 gst_ogg_demux_get_next_page (GstOggDemux * ogg, ogg_page * og,
1529     gint64 boundary, gint64 * offset)
1530 {
1531   gint64 end_offset = -1;
1532   GstFlowReturn ret;
1533
1534   GST_LOG_OBJECT (ogg,
1535       "get next page, current offset %" G_GINT64_FORMAT ", bytes boundary %"
1536       G_GINT64_FORMAT, ogg->offset, boundary);
1537
1538   if (boundary >= 0)
1539     end_offset = ogg->offset + boundary;
1540
1541   while (TRUE) {
1542     glong more;
1543
1544     if (end_offset > 0 && ogg->offset >= end_offset)
1545       goto boundary_reached;
1546
1547     more = ogg_sync_pageseek (&ogg->sync, og);
1548
1549     GST_LOG_OBJECT (ogg, "pageseek gave %ld", more);
1550
1551     if (more < 0) {
1552       /* skipped n bytes */
1553       ogg->offset -= more;
1554       GST_LOG_OBJECT (ogg, "skipped %ld bytes, offset %" G_GINT64_FORMAT,
1555           more, ogg->offset);
1556     } else if (more == 0) {
1557       /* we need more data */
1558       if (boundary == 0)
1559         goto boundary_reached;
1560
1561       GST_LOG_OBJECT (ogg, "need more data");
1562       ret = gst_ogg_demux_get_data (ogg, end_offset);
1563       if (ret != GST_FLOW_OK)
1564         break;
1565     } else {
1566       gint64 res_offset = ogg->offset;
1567
1568       /* got a page.  Return the offset at the page beginning,
1569          advance the internal offset past the page end */
1570       if (offset)
1571         *offset = res_offset;
1572       ret = GST_FLOW_OK;
1573
1574       ogg->offset += more;
1575
1576       GST_LOG_OBJECT (ogg,
1577           "got page at %" G_GINT64_FORMAT ", serial %08x, end at %"
1578           G_GINT64_FORMAT ", granule %" G_GINT64_FORMAT, res_offset,
1579           ogg_page_serialno (og), ogg->offset,
1580           (gint64) ogg_page_granulepos (og));
1581       break;
1582     }
1583   }
1584   GST_LOG_OBJECT (ogg, "returning %d", ret);
1585
1586   return ret;
1587
1588   /* ERRORS */
1589 boundary_reached:
1590   {
1591     GST_LOG_OBJECT (ogg,
1592         "offset %" G_GINT64_FORMAT " >= end_offset %" G_GINT64_FORMAT,
1593         ogg->offset, end_offset);
1594     return GST_FLOW_LIMIT;
1595   }
1596 }
1597
1598 /* from the current offset, find the previous page, seeking backwards
1599  * until we find the page. 
1600  */
1601 static GstFlowReturn
1602 gst_ogg_demux_get_prev_page (GstOggDemux * ogg, ogg_page * og, gint64 * offset)
1603 {
1604   GstFlowReturn ret;
1605   gint64 begin = ogg->offset;
1606   gint64 end = begin;
1607   gint64 cur_offset = -1;
1608
1609   GST_LOG_OBJECT (ogg, "getting page before %" G_GINT64_FORMAT, begin);
1610
1611   while (cur_offset == -1) {
1612     begin -= CHUNKSIZE;
1613     if (begin < 0)
1614       begin = 0;
1615
1616     /* seek CHUNKSIZE back */
1617     gst_ogg_demux_seek (ogg, begin);
1618
1619     /* now continue reading until we run out of data, if we find a page
1620      * start, we save it. It might not be the final page as there could be
1621      * another page after this one. */
1622     while (ogg->offset < end) {
1623       gint64 new_offset;
1624
1625       ret =
1626           gst_ogg_demux_get_next_page (ogg, og, end - ogg->offset, &new_offset);
1627       /* we hit the upper limit, offset contains the last page start */
1628       if (ret == GST_FLOW_LIMIT) {
1629         GST_LOG_OBJECT (ogg, "hit limit");
1630         break;
1631       }
1632       /* something went wrong */
1633       if (ret == GST_FLOW_UNEXPECTED) {
1634         new_offset = 0;
1635         GST_LOG_OBJECT (ogg, "got unexpected");
1636       } else if (ret != GST_FLOW_OK) {
1637         GST_LOG_OBJECT (ogg, "got error %d", ret);
1638         return ret;
1639       }
1640
1641       GST_LOG_OBJECT (ogg, "found page at %" G_GINT64_FORMAT, new_offset);
1642
1643       /* offset is next page start */
1644       cur_offset = new_offset;
1645     }
1646   }
1647
1648   GST_LOG_OBJECT (ogg, "found previous page at %" G_GINT64_FORMAT, cur_offset);
1649
1650   /* we have the offset.  Actually snork and hold the page now */
1651   gst_ogg_demux_seek (ogg, cur_offset);
1652   ret = gst_ogg_demux_get_next_page (ogg, og, -1, NULL);
1653   if (ret != GST_FLOW_OK) {
1654     GST_WARNING_OBJECT (ogg, "can't get last page at %" G_GINT64_FORMAT,
1655         cur_offset);
1656     /* this shouldn't be possible */
1657     return ret;
1658   }
1659
1660   if (offset)
1661     *offset = cur_offset;
1662
1663   return ret;
1664 }
1665
1666 static gboolean
1667 gst_ogg_demux_deactivate_current_chain (GstOggDemux * ogg)
1668 {
1669   gint i;
1670   GstOggChain *chain = ogg->current_chain;
1671
1672   if (chain == NULL)
1673     return TRUE;
1674
1675   GST_DEBUG_OBJECT (ogg, "deactivating chain %p", chain);
1676
1677   /* send EOS on all the pads */
1678   for (i = 0; i < chain->streams->len; i++) {
1679     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
1680     GstEvent *event;
1681
1682     if (!pad->added)
1683       continue;
1684
1685     event = gst_event_new_eos ();
1686     gst_event_set_seqnum (event, ogg->seqnum);
1687     gst_pad_push_event (GST_PAD_CAST (pad), event);
1688
1689     GST_DEBUG_OBJECT (ogg, "removing pad %" GST_PTR_FORMAT, pad);
1690
1691     /* deactivate first */
1692     gst_pad_set_active (GST_PAD_CAST (pad), FALSE);
1693
1694     gst_element_remove_pad (GST_ELEMENT (ogg), GST_PAD_CAST (pad));
1695
1696     pad->added = FALSE;
1697   }
1698   /* if we cannot seek back to the chain, we can destroy the chain 
1699    * completely */
1700   if (!ogg->pullmode) {
1701     gst_ogg_chain_free (chain);
1702   }
1703   ogg->current_chain = NULL;
1704
1705   return TRUE;
1706 }
1707
1708 static gboolean
1709 gst_ogg_demux_activate_chain (GstOggDemux * ogg, GstOggChain * chain,
1710     GstEvent * event)
1711 {
1712   gint i;
1713   gint bitrate, idx_bitrate;
1714
1715   g_return_val_if_fail (chain != NULL, FALSE);
1716
1717   if (chain == ogg->current_chain) {
1718     if (event)
1719       gst_event_unref (event);
1720     return TRUE;
1721   }
1722
1723
1724   GST_DEBUG_OBJECT (ogg, "activating chain %p", chain);
1725
1726   bitrate = idx_bitrate = 0;
1727
1728   /* first add the pads */
1729   for (i = 0; i < chain->streams->len; i++) {
1730     GstOggPad *pad;
1731     GstStructure *structure;
1732
1733     pad = g_array_index (chain->streams, GstOggPad *, i);
1734
1735     if (pad->map.idx_bitrate)
1736       idx_bitrate = MAX (idx_bitrate, pad->map.idx_bitrate);
1737
1738     bitrate += pad->map.bitrate;
1739
1740     /* mark discont */
1741     gst_ogg_pad_mark_discont (pad);
1742     pad->last_ret = GST_FLOW_OK;
1743
1744     if (pad->map.is_skeleton || pad->added || GST_PAD_CAPS (pad) == NULL)
1745       continue;
1746
1747     GST_DEBUG_OBJECT (ogg, "adding pad %" GST_PTR_FORMAT, pad);
1748
1749     structure = gst_caps_get_structure (GST_PAD_CAPS (pad), 0);
1750
1751     /* activate first */
1752     gst_pad_set_active (GST_PAD_CAST (pad), TRUE);
1753
1754     gst_element_add_pad (GST_ELEMENT (ogg), GST_PAD_CAST (pad));
1755     pad->added = TRUE;
1756   }
1757   /* prefer the index bitrate over the ones encoded in the streams */
1758   ogg->bitrate = (idx_bitrate ? idx_bitrate : bitrate);
1759
1760   /* after adding the new pads, remove the old pads */
1761   gst_ogg_demux_deactivate_current_chain (ogg);
1762
1763   ogg->current_chain = chain;
1764
1765   /* we are finished now */
1766   gst_element_no_more_pads (GST_ELEMENT (ogg));
1767
1768   /* FIXME, must be sent from the streaming thread */
1769   if (event) {
1770     gst_ogg_demux_send_event (ogg, event);
1771
1772     gst_element_found_tags (GST_ELEMENT_CAST (ogg),
1773         gst_tag_list_new_full (GST_TAG_CONTAINER_FORMAT, "Ogg", NULL));
1774   }
1775
1776   GST_DEBUG_OBJECT (ogg, "starting chain");
1777
1778   /* then send out any headers and queued packets */
1779   for (i = 0; i < chain->streams->len; i++) {
1780     GList *walk;
1781     GstOggPad *pad;
1782
1783     pad = g_array_index (chain->streams, GstOggPad *, i);
1784
1785     /* FIXME also streaming thread */
1786     if (pad->map.taglist) {
1787       GST_DEBUG_OBJECT (ogg, "pushing tags");
1788       gst_element_found_tags_for_pad (GST_ELEMENT_CAST (ogg),
1789           GST_PAD_CAST (pad), pad->map.taglist);
1790       pad->map.taglist = NULL;
1791     }
1792
1793     GST_DEBUG_OBJECT (ogg, "pushing headers");
1794     /* push headers */
1795     for (walk = pad->map.headers; walk; walk = g_list_next (walk)) {
1796       ogg_packet *p = walk->data;
1797
1798       gst_ogg_demux_chain_peer (pad, p, TRUE);
1799     }
1800
1801     GST_DEBUG_OBJECT (ogg, "pushing queued buffers");
1802     /* push queued packets */
1803     for (walk = pad->map.queued; walk; walk = g_list_next (walk)) {
1804       ogg_packet *p = walk->data;
1805
1806       gst_ogg_demux_chain_peer (pad, p, TRUE);
1807       _ogg_packet_free (p);
1808     }
1809     /* and free the queued buffers */
1810     g_list_free (pad->map.queued);
1811     pad->map.queued = NULL;
1812   }
1813   return TRUE;
1814 }
1815
1816 static gboolean
1817 do_binary_search (GstOggDemux * ogg, GstOggChain * chain, gint64 begin,
1818     gint64 end, gint64 begintime, gint64 endtime, gint64 target,
1819     gint64 * offset)
1820 {
1821   gint64 best;
1822   GstFlowReturn ret;
1823   gint64 result = 0;
1824
1825   best = begin;
1826
1827   GST_DEBUG_OBJECT (ogg,
1828       "chain offset %" G_GINT64_FORMAT ", end offset %" G_GINT64_FORMAT,
1829       begin, end);
1830   GST_DEBUG_OBJECT (ogg,
1831       "chain begin time %" GST_TIME_FORMAT ", end time %" GST_TIME_FORMAT,
1832       GST_TIME_ARGS (begintime), GST_TIME_ARGS (endtime));
1833   GST_DEBUG_OBJECT (ogg, "target %" GST_TIME_FORMAT, GST_TIME_ARGS (target));
1834
1835   /* perform the seek */
1836   while (begin < end) {
1837     gint64 bisect;
1838
1839     if ((end - begin < CHUNKSIZE) || (endtime == begintime)) {
1840       bisect = begin;
1841     } else {
1842       /* take a (pretty decent) guess, avoiding overflow */
1843       gint64 rate = (end - begin) * GST_MSECOND / (endtime - begintime);
1844
1845       bisect = (target - begintime) / GST_MSECOND * rate + begin - CHUNKSIZE;
1846
1847       if (bisect <= begin)
1848         bisect = begin;
1849       GST_DEBUG_OBJECT (ogg, "Initial guess: %" G_GINT64_FORMAT, bisect);
1850     }
1851     gst_ogg_demux_seek (ogg, bisect);
1852
1853     while (begin < end) {
1854       ogg_page og;
1855
1856       GST_DEBUG_OBJECT (ogg,
1857           "after seek, bisect %" G_GINT64_FORMAT ", begin %" G_GINT64_FORMAT
1858           ", end %" G_GINT64_FORMAT, bisect, begin, end);
1859
1860       ret = gst_ogg_demux_get_next_page (ogg, &og, end - ogg->offset, &result);
1861       GST_LOG_OBJECT (ogg, "looking for next page returned %" G_GINT64_FORMAT,
1862           result);
1863
1864       if (ret == GST_FLOW_LIMIT) {
1865         /* we hit the upper limit, go back a bit */
1866         if (bisect <= begin + 1) {
1867           end = begin;          /* found it */
1868         } else {
1869           if (bisect == 0)
1870             goto seek_error;
1871
1872           bisect -= CHUNKSIZE;
1873           if (bisect <= begin)
1874             bisect = begin + 1;
1875
1876           gst_ogg_demux_seek (ogg, bisect);
1877         }
1878       } else if (ret == GST_FLOW_OK) {
1879         /* found offset of next ogg page */
1880         gint64 granulepos;
1881         GstClockTime granuletime;
1882         GstOggPad *pad;
1883
1884         /* get the granulepos */
1885         GST_LOG_OBJECT (ogg, "found next ogg page at %" G_GINT64_FORMAT,
1886             result);
1887         granulepos = ogg_page_granulepos (&og);
1888         if (granulepos == -1) {
1889           GST_LOG_OBJECT (ogg, "granulepos of next page is -1");
1890           continue;
1891         }
1892
1893         /* get the stream */
1894         pad = gst_ogg_chain_get_stream (chain, ogg_page_serialno (&og));
1895         if (pad == NULL || pad->map.is_skeleton)
1896           continue;
1897
1898         /* convert granulepos to time */
1899         granuletime = gst_ogg_stream_get_end_time_for_granulepos (&pad->map,
1900             granulepos);
1901         if (granuletime < pad->start_time)
1902           continue;
1903
1904         GST_LOG_OBJECT (ogg, "granulepos %" G_GINT64_FORMAT " maps to time %"
1905             GST_TIME_FORMAT, granulepos, GST_TIME_ARGS (granuletime));
1906
1907         granuletime -= pad->start_time;
1908         granuletime += chain->begin_time;
1909
1910         GST_DEBUG_OBJECT (ogg,
1911             "found page with granule %" G_GINT64_FORMAT " and time %"
1912             GST_TIME_FORMAT, granulepos, GST_TIME_ARGS (granuletime));
1913
1914         if (granuletime < target) {
1915           best = result;        /* raw offset of packet with granulepos */
1916           begin = ogg->offset;  /* raw offset of next page */
1917           begintime = granuletime;
1918
1919           bisect = begin;       /* *not* begin + 1 */
1920         } else {
1921           if (bisect <= begin + 1) {
1922             end = begin;        /* found it */
1923           } else {
1924             if (end == ogg->offset) {   /* we're pretty close - we'd be stuck in */
1925               end = result;
1926               bisect -= CHUNKSIZE;      /* an endless loop otherwise. */
1927               if (bisect <= begin)
1928                 bisect = begin + 1;
1929               gst_ogg_demux_seek (ogg, bisect);
1930             } else {
1931               end = result;
1932               endtime = granuletime;
1933               break;
1934             }
1935           }
1936         }
1937       } else
1938         goto seek_error;
1939     }
1940   }
1941   GST_DEBUG_OBJECT (ogg, "seeking to %" G_GINT64_FORMAT, best);
1942   gst_ogg_demux_seek (ogg, best);
1943   *offset = best;
1944
1945   return TRUE;
1946
1947   /* ERRORS */
1948 seek_error:
1949   {
1950     GST_DEBUG_OBJECT (ogg, "got a seek error");
1951     return FALSE;
1952   }
1953 }
1954
1955 static gboolean
1956 do_index_search (GstOggDemux * ogg, GstOggChain * chain, gint64 begin,
1957     gint64 end, gint64 begintime, gint64 endtime, gint64 target,
1958     gint64 * p_offset, gint64 * p_timestamp)
1959 {
1960   guint i;
1961   guint64 timestamp, offset;
1962   guint64 r_timestamp, r_offset;
1963   gboolean result = FALSE;
1964
1965   target -= begintime;
1966
1967   r_offset = -1;
1968   r_timestamp = -1;
1969
1970   for (i = 0; i < chain->streams->len; i++) {
1971     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
1972
1973     timestamp = target;
1974     if (gst_ogg_map_search_index (&pad->map, TRUE, &timestamp, &offset)) {
1975       GST_INFO ("found %" G_GUINT64_FORMAT " at offset %" G_GUINT64_FORMAT,
1976           timestamp, offset);
1977
1978       if (r_offset == -1 || offset < r_offset) {
1979         r_offset = offset;
1980         r_timestamp = timestamp;
1981       }
1982       result |= TRUE;
1983     }
1984   }
1985
1986   if (p_timestamp)
1987     *p_timestamp = r_timestamp;
1988   if (p_offset)
1989     *p_offset = r_offset;
1990
1991   return result;
1992 }
1993
1994 /*
1995  * do seek to time @position, return FALSE or chain and TRUE
1996  */
1997 static gboolean
1998 gst_ogg_demux_do_seek (GstOggDemux * ogg, GstSegment * segment,
1999     gboolean accurate, gboolean keyframe, GstOggChain ** rchain)
2000 {
2001   guint64 position;
2002   GstOggChain *chain = NULL;
2003   gint64 begin, end;
2004   gint64 begintime, endtime;
2005   gint64 target, keytarget;
2006   gint64 best;
2007   gint64 total;
2008   gint64 result = 0;
2009   GstFlowReturn ret;
2010   gint i, pending, len;
2011   gboolean first_parsed_page = TRUE;
2012
2013   position = segment->last_stop;
2014
2015   /* first find the chain to search in */
2016   total = ogg->total_time;
2017   if (ogg->chains->len == 0)
2018     goto no_chains;
2019
2020   for (i = ogg->chains->len - 1; i >= 0; i--) {
2021     chain = g_array_index (ogg->chains, GstOggChain *, i);
2022     total -= chain->total_time;
2023     if (position >= total)
2024       break;
2025   }
2026
2027   /* first step, locate page containing the required data */
2028   begin = chain->offset;
2029   end = chain->end_offset;
2030   begintime = chain->begin_time;
2031   endtime = begintime + chain->total_time;
2032   target = position - total + begintime;
2033
2034   if (!do_binary_search (ogg, chain, begin, end, begintime, endtime, target,
2035           &best))
2036     goto seek_error;
2037
2038   /* second step: find pages for all streams, we use the keyframe_granule to keep
2039    * track of which ones we saw. If we have seen a page for each stream we can
2040    * calculate the positions of each keyframe. */
2041   GST_DEBUG_OBJECT (ogg, "find keyframes");
2042   len = pending = chain->streams->len;
2043
2044   /* figure out where the keyframes are */
2045   keytarget = target;
2046
2047   while (TRUE) {
2048     ogg_page og;
2049     gint64 granulepos;
2050     GstOggPad *pad;
2051     GstClockTime keyframe_time, granule_time;
2052
2053     ret = gst_ogg_demux_get_next_page (ogg, &og, end - ogg->offset, &result);
2054     GST_LOG_OBJECT (ogg, "looking for next page returned %" G_GINT64_FORMAT,
2055         result);
2056     if (ret == GST_FLOW_LIMIT) {
2057       GST_LOG_OBJECT (ogg, "reached limit");
2058       break;
2059     } else if (ret != GST_FLOW_OK)
2060       goto seek_error;
2061
2062     /* get the stream */
2063     pad = gst_ogg_chain_get_stream (chain, ogg_page_serialno (&og));
2064     if (pad == NULL)
2065       continue;
2066
2067     if (pad->map.is_skeleton)
2068       goto next;
2069
2070     granulepos = ogg_page_granulepos (&og);
2071     if (granulepos == -1) {
2072       GST_LOG_OBJECT (ogg, "granulepos of next page is -1");
2073       continue;
2074     }
2075
2076     /* we only do this the first time we pass here */
2077     if (first_parsed_page) {
2078       /* Now that we have a time reference from the page, we can check
2079        * whether all streams still have pages from here on.
2080        *
2081        * This would be more elegant before the loop, but getting the page from
2082        * there without breaking anything would be more costly */
2083       granule_time = gst_ogg_stream_get_end_time_for_granulepos (&pad->map,
2084           granulepos);
2085       for (i = 0; i < len; i++) {
2086         GstOggPad *stream = g_array_index (chain->streams, GstOggPad *, i);
2087
2088         if (stream == pad)
2089           /* we already know we have at least one page (the current one)
2090            * for this stream */
2091           continue;
2092
2093         if (granule_time > stream->map.total_time)
2094           /* we won't encounter any more pages of this stream, so we don't
2095            * try finding a key frame for it */
2096           pending--;
2097       }
2098       first_parsed_page = FALSE;
2099     }
2100
2101
2102     /* in reverse we want to go past the page with the lower timestamp */
2103     if (segment->rate < 0.0) {
2104       /* get time for this pad */
2105       granule_time = gst_ogg_stream_get_end_time_for_granulepos (&pad->map,
2106           granulepos);
2107
2108       GST_LOG_OBJECT (ogg,
2109           "looking at page with ts %" GST_TIME_FORMAT ", target %"
2110           GST_TIME_FORMAT, GST_TIME_ARGS (granule_time),
2111           GST_TIME_ARGS (target));
2112       if (granule_time < target)
2113         continue;
2114     }
2115
2116     /* we've seen this pad before */
2117     if (pad->keyframe_granule != -1)
2118       continue;
2119
2120     /* convert granule of this pad to the granule of the keyframe */
2121     pad->keyframe_granule =
2122         gst_ogg_stream_granulepos_to_key_granule (&pad->map, granulepos);
2123     GST_LOG_OBJECT (ogg, "marking stream granule %" G_GINT64_FORMAT,
2124         pad->keyframe_granule);
2125
2126     /* get time of the keyframe */
2127     keyframe_time =
2128         gst_ogg_stream_granule_to_time (&pad->map, pad->keyframe_granule);
2129     GST_LOG_OBJECT (ogg, "stream %08lx granule time %" GST_TIME_FORMAT,
2130         pad->map.serialno, GST_TIME_ARGS (keyframe_time));
2131
2132     /* collect smallest value */
2133     if (keyframe_time != -1) {
2134       keyframe_time += begintime;
2135       if (keyframe_time < keytarget)
2136         keytarget = keyframe_time;
2137     }
2138
2139   next:
2140     pending--;
2141     if (pending == 0)
2142       break;
2143   }
2144
2145   /* for negative rates we will get to the keyframe backwards */
2146   if (segment->rate < 0.0)
2147     goto done;
2148
2149   if (keytarget != target) {
2150     GST_LOG_OBJECT (ogg, "final seek to target %" GST_TIME_FORMAT,
2151         GST_TIME_ARGS (keytarget));
2152
2153     /* last step, seek to the location of the keyframe */
2154     if (!do_binary_search (ogg, chain, begin, end, begintime, endtime,
2155             keytarget, &best))
2156       goto seek_error;
2157   } else {
2158     /* seek back to previous position */
2159     GST_LOG_OBJECT (ogg, "keyframe on target");
2160     gst_ogg_demux_seek (ogg, best);
2161   }
2162
2163 done:
2164   if (keyframe) {
2165     if (segment->rate > 0.0)
2166       segment->time = keytarget;
2167     segment->last_stop = keytarget - begintime;
2168   }
2169
2170   *rchain = chain;
2171
2172   return TRUE;
2173
2174 no_chains:
2175   {
2176     GST_DEBUG_OBJECT (ogg, "no chains");
2177     return FALSE;
2178   }
2179 seek_error:
2180   {
2181     GST_DEBUG_OBJECT (ogg, "got a seek error");
2182     return FALSE;
2183   }
2184 }
2185
2186 /* does not take ownership of the event */
2187 static gboolean
2188 gst_ogg_demux_perform_seek_pull (GstOggDemux * ogg, GstEvent * event)
2189 {
2190   GstOggChain *chain = NULL;
2191   gboolean res;
2192   gboolean flush, accurate, keyframe;
2193   GstFormat format;
2194   gdouble rate;
2195   GstSeekFlags flags;
2196   GstSeekType cur_type, stop_type;
2197   gint64 cur, stop;
2198   gboolean update;
2199   guint32 seqnum;
2200   GstEvent *tevent;
2201
2202   if (event) {
2203     GST_DEBUG_OBJECT (ogg, "seek with event");
2204
2205     gst_event_parse_seek (event, &rate, &format, &flags,
2206         &cur_type, &cur, &stop_type, &stop);
2207
2208     /* we can only seek on time */
2209     if (format != GST_FORMAT_TIME) {
2210       GST_DEBUG_OBJECT (ogg, "can only seek on TIME");
2211       goto error;
2212     }
2213     seqnum = gst_event_get_seqnum (event);
2214   } else {
2215     GST_DEBUG_OBJECT (ogg, "seek without event");
2216
2217     flags = 0;
2218     rate = 1.0;
2219     seqnum = gst_util_seqnum_next ();
2220   }
2221
2222   GST_DEBUG_OBJECT (ogg, "seek, rate %g", rate);
2223
2224   flush = flags & GST_SEEK_FLAG_FLUSH;
2225   accurate = flags & GST_SEEK_FLAG_ACCURATE;
2226   keyframe = flags & GST_SEEK_FLAG_KEY_UNIT;
2227
2228   /* first step is to unlock the streaming thread if it is
2229    * blocked in a chain call, we do this by starting the flush. because
2230    * we cannot yet hold any streaming lock, we have to protect the chains
2231    * with their own lock. */
2232   if (flush) {
2233     gint i;
2234
2235     tevent = gst_event_new_flush_start ();
2236     gst_event_set_seqnum (tevent, seqnum);
2237
2238     gst_event_ref (tevent);
2239     gst_pad_push_event (ogg->sinkpad, tevent);
2240
2241     GST_CHAIN_LOCK (ogg);
2242     for (i = 0; i < ogg->chains->len; i++) {
2243       GstOggChain *chain = g_array_index (ogg->chains, GstOggChain *, i);
2244       gint j;
2245
2246       for (j = 0; j < chain->streams->len; j++) {
2247         GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, j);
2248
2249         gst_event_ref (tevent);
2250         gst_pad_push_event (GST_PAD (pad), tevent);
2251       }
2252     }
2253     GST_CHAIN_UNLOCK (ogg);
2254
2255     gst_event_unref (tevent);
2256   } else {
2257     gst_pad_pause_task (ogg->sinkpad);
2258   }
2259
2260   /* now grab the stream lock so that streaming cannot continue, for
2261    * non flushing seeks when the element is in PAUSED this could block
2262    * forever. */
2263   GST_PAD_STREAM_LOCK (ogg->sinkpad);
2264
2265   if (ogg->segment_running && !flush) {
2266     /* create the segment event to close the current segment */
2267     if ((chain = ogg->current_chain)) {
2268       GstEvent *newseg;
2269       gint64 chain_start = 0;
2270
2271       if (chain->segment_start != GST_CLOCK_TIME_NONE)
2272         chain_start = chain->segment_start;
2273
2274       newseg = gst_event_new_new_segment (TRUE, ogg->segment.rate,
2275           GST_FORMAT_TIME, ogg->segment.start + chain_start,
2276           ogg->segment.last_stop + chain_start, ogg->segment.time);
2277       /* set the seqnum of the running segment */
2278       gst_event_set_seqnum (newseg, ogg->seqnum);
2279
2280       /* send segment on old chain, FIXME, must be sent from streaming thread. */
2281       gst_ogg_demux_send_event (ogg, newseg);
2282     }
2283   }
2284
2285   if (event) {
2286     gst_segment_set_seek (&ogg->segment, rate, format, flags,
2287         cur_type, cur, stop_type, stop, &update);
2288   }
2289
2290   GST_DEBUG_OBJECT (ogg, "segment positions set to %" GST_TIME_FORMAT "-%"
2291       GST_TIME_FORMAT, GST_TIME_ARGS (ogg->segment.start),
2292       GST_TIME_ARGS (ogg->segment.stop));
2293
2294   /* we need to stop flushing on the srcpad as we're going to use it
2295    * next. We can do this as we have the STREAM lock now. */
2296   if (flush) {
2297     tevent = gst_event_new_flush_stop ();
2298     gst_event_set_seqnum (tevent, seqnum);
2299     gst_pad_push_event (ogg->sinkpad, tevent);
2300   }
2301
2302   {
2303     gint i;
2304
2305     /* reset all ogg streams now, need to do this from within the lock to
2306      * make sure the streaming thread is not messing with the stream */
2307     for (i = 0; i < ogg->chains->len; i++) {
2308       GstOggChain *chain = g_array_index (ogg->chains, GstOggChain *, i);
2309
2310       gst_ogg_chain_reset (chain);
2311     }
2312   }
2313
2314   /* for reverse we will already seek accurately */
2315   res = gst_ogg_demux_do_seek (ogg, &ogg->segment, accurate, keyframe, &chain);
2316
2317   /* seek failed, make sure we continue the current chain */
2318   if (!res) {
2319     GST_DEBUG_OBJECT (ogg, "seek failed");
2320     chain = ogg->current_chain;
2321   } else {
2322     GST_DEBUG_OBJECT (ogg, "seek success");
2323   }
2324
2325   if (!chain)
2326     goto no_chain;
2327
2328   /* now we have a new position, prepare for streaming again */
2329   {
2330     GstEvent *event;
2331     gint64 stop;
2332     gint64 start;
2333     gint64 last_stop, begin_time;
2334
2335     /* we have to send the flush to the old chain, not the new one */
2336     if (flush) {
2337       tevent = gst_event_new_flush_stop ();
2338       gst_event_set_seqnum (tevent, seqnum);
2339       gst_ogg_demux_send_event (ogg, tevent);
2340     }
2341
2342     /* we need this to see how far inside the chain we need to start */
2343     if (chain->begin_time != GST_CLOCK_TIME_NONE)
2344       begin_time = chain->begin_time;
2345     else
2346       begin_time = 0;
2347
2348     /* segment.start gives the start over all chains, we calculate the amount
2349      * of time into this chain we need to start */
2350     start = ogg->segment.start - begin_time;
2351     if (chain->segment_start != GST_CLOCK_TIME_NONE)
2352       start += chain->segment_start;
2353
2354     if ((stop = ogg->segment.stop) == -1)
2355       stop = ogg->segment.duration;
2356
2357     /* segment.stop gives the stop time over all chains, calculate the amount of
2358      * time we need to stop in this chain */
2359     if (stop != -1) {
2360       if (stop > begin_time)
2361         stop -= begin_time;
2362       else
2363         stop = 0;
2364       stop += chain->segment_start;
2365       /* we must stop when this chain ends and switch to the next chain to play
2366        * the remainder of the segment. */
2367       stop = MIN (stop, chain->segment_stop);
2368     }
2369
2370     last_stop = ogg->segment.last_stop;
2371     if (chain->segment_start != GST_CLOCK_TIME_NONE)
2372       last_stop += chain->segment_start;
2373
2374     /* create the segment event we are going to send out */
2375     if (ogg->segment.rate >= 0.0)
2376       event = gst_event_new_new_segment (FALSE, ogg->segment.rate,
2377           ogg->segment.format, last_stop, stop, ogg->segment.time);
2378     else
2379       event = gst_event_new_new_segment (FALSE, ogg->segment.rate,
2380           ogg->segment.format, start, last_stop, ogg->segment.time);
2381
2382     gst_event_set_seqnum (event, seqnum);
2383
2384     if (chain != ogg->current_chain) {
2385       /* switch to different chain, send segment on new chain */
2386       gst_ogg_demux_activate_chain (ogg, chain, event);
2387     } else {
2388       /* mark discont and send segment on current chain */
2389       gst_ogg_chain_mark_discont (chain);
2390       /* This event should be sent from the streaming thread (sink pad task) */
2391       if (ogg->newsegment)
2392         gst_event_unref (ogg->newsegment);
2393       ogg->newsegment = event;
2394     }
2395
2396     /* notify start of new segment */
2397     if (ogg->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2398       GstMessage *message;
2399
2400       message = gst_message_new_segment_start (GST_OBJECT (ogg),
2401           GST_FORMAT_TIME, ogg->segment.last_stop);
2402       gst_message_set_seqnum (message, seqnum);
2403
2404       gst_element_post_message (GST_ELEMENT (ogg), message);
2405     }
2406
2407     ogg->segment_running = TRUE;
2408     ogg->seqnum = seqnum;
2409     /* restart our task since it might have been stopped when we did the 
2410      * flush. */
2411     gst_pad_start_task (ogg->sinkpad, (GstTaskFunction) gst_ogg_demux_loop,
2412         ogg->sinkpad);
2413   }
2414
2415   /* streaming can continue now */
2416   GST_PAD_STREAM_UNLOCK (ogg->sinkpad);
2417
2418   return res;
2419
2420   /* ERRORS */
2421 error:
2422   {
2423     GST_DEBUG_OBJECT (ogg, "seek failed");
2424     return FALSE;
2425   }
2426 no_chain:
2427   {
2428     GST_DEBUG_OBJECT (ogg, "no chain to seek in");
2429     GST_PAD_STREAM_UNLOCK (ogg->sinkpad);
2430     return FALSE;
2431   }
2432 }
2433
2434 static gboolean
2435 gst_ogg_demux_perform_seek_push (GstOggDemux * ogg, GstEvent * event)
2436 {
2437   gint bitrate;
2438   gboolean res = TRUE;
2439   GstFormat format;
2440   gdouble rate;
2441   GstSeekFlags flags;
2442   GstSeekType start_type, stop_type;
2443   gint64 start, stop;
2444   GstEvent *sevent;
2445   GstOggChain *chain;
2446   gint64 best, best_time;
2447
2448   gst_event_parse_seek (event, &rate, &format, &flags,
2449       &start_type, &start, &stop_type, &stop);
2450
2451   if (format != GST_FORMAT_TIME) {
2452     GST_DEBUG_OBJECT (ogg, "can only seek on TIME");
2453     goto error;
2454   }
2455
2456   chain = ogg->current_chain;
2457   if (!chain)
2458     return FALSE;
2459
2460   if (do_index_search (ogg, chain, 0, -1, 0, -1, start, &best, &best_time)) {
2461     /* the index gave some result */
2462     GST_DEBUG_OBJECT (ogg,
2463         "found offset %" G_GINT64_FORMAT " with time %" G_GUINT64_FORMAT,
2464         best, best_time);
2465     start = best;
2466   } else if ((bitrate = ogg->bitrate) > 0) {
2467     /* try with bitrate convert the seek positions to bytes */
2468     if (start_type != GST_SEEK_TYPE_NONE) {
2469       start = gst_util_uint64_scale (start, bitrate, 8 * GST_SECOND);
2470     }
2471     if (stop_type != GST_SEEK_TYPE_NONE) {
2472       stop = gst_util_uint64_scale (stop, bitrate, 8 * GST_SECOND);
2473     }
2474   } else {
2475     /* we don't know */
2476     res = FALSE;
2477   }
2478
2479   if (res) {
2480     GST_DEBUG_OBJECT (ogg,
2481         "seeking to %" G_GINT64_FORMAT " - %" G_GINT64_FORMAT, start, stop);
2482     /* do seek */
2483     sevent = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
2484         start_type, start, stop_type, stop);
2485
2486     res = gst_pad_push_event (ogg->sinkpad, sevent);
2487   }
2488
2489   return res;
2490
2491   /* ERRORS */
2492 error:
2493   {
2494     GST_DEBUG_OBJECT (ogg, "seek failed");
2495     return FALSE;
2496   }
2497 }
2498
2499 static gboolean
2500 gst_ogg_demux_perform_seek (GstOggDemux * ogg, GstEvent * event)
2501 {
2502   gboolean res;
2503
2504   if (ogg->pullmode) {
2505     res = gst_ogg_demux_perform_seek_pull (ogg, event);
2506   } else {
2507     res = gst_ogg_demux_perform_seek_push (ogg, event);
2508   }
2509   return res;
2510 }
2511
2512
2513 /* finds each bitstream link one at a time using a bisection search
2514  * (has to begin by knowing the offset of the lb's initial page).
2515  * Recurses for each link so it can alloc the link storage after
2516  * finding them all, then unroll and fill the cache at the same time
2517  */
2518 static GstFlowReturn
2519 gst_ogg_demux_bisect_forward_serialno (GstOggDemux * ogg,
2520     gint64 begin, gint64 searched, gint64 end, GstOggChain * chain, glong m)
2521 {
2522   gint64 endsearched = end;
2523   gint64 next = end;
2524   ogg_page og;
2525   GstFlowReturn ret;
2526   gint64 offset;
2527   GstOggChain *nextchain;
2528
2529   GST_LOG_OBJECT (ogg,
2530       "bisect begin: %" G_GINT64_FORMAT ", searched: %" G_GINT64_FORMAT
2531       ", end %" G_GINT64_FORMAT ", chain: %p", begin, searched, end, chain);
2532
2533   /* the below guards against garbage seperating the last and
2534    * first pages of two links. */
2535   while (searched < endsearched) {
2536     gint64 bisect;
2537
2538     if (endsearched - searched < CHUNKSIZE) {
2539       bisect = searched;
2540     } else {
2541       bisect = (searched + endsearched) / 2;
2542     }
2543
2544     gst_ogg_demux_seek (ogg, bisect);
2545     ret = gst_ogg_demux_get_next_page (ogg, &og, -1, &offset);
2546
2547     if (ret == GST_FLOW_UNEXPECTED) {
2548       endsearched = bisect;
2549     } else if (ret == GST_FLOW_OK) {
2550       glong serial = ogg_page_serialno (&og);
2551
2552       if (!gst_ogg_chain_has_stream (chain, serial)) {
2553         endsearched = bisect;
2554         next = offset;
2555       } else {
2556         searched = offset + og.header_len + og.body_len;
2557       }
2558     } else
2559       return ret;
2560   }
2561
2562   GST_LOG_OBJECT (ogg, "current chain ends at %" G_GINT64_FORMAT, searched);
2563
2564   chain->end_offset = searched;
2565   ret = gst_ogg_demux_read_end_chain (ogg, chain);
2566   if (ret != GST_FLOW_OK)
2567     return ret;
2568
2569   GST_LOG_OBJECT (ogg, "found begin at %" G_GINT64_FORMAT, next);
2570
2571   gst_ogg_demux_seek (ogg, next);
2572   ret = gst_ogg_demux_read_chain (ogg, &nextchain);
2573   if (ret == GST_FLOW_UNEXPECTED) {
2574     nextchain = NULL;
2575     ret = GST_FLOW_OK;
2576     GST_LOG_OBJECT (ogg, "no next chain");
2577   } else if (ret != GST_FLOW_OK)
2578     goto done;
2579
2580   if (searched < end && nextchain != NULL) {
2581     ret = gst_ogg_demux_bisect_forward_serialno (ogg, next, ogg->offset,
2582         end, nextchain, m + 1);
2583     if (ret != GST_FLOW_OK)
2584       goto done;
2585   }
2586   GST_LOG_OBJECT (ogg, "adding chain %p", chain);
2587
2588   g_array_insert_val (ogg->chains, 0, chain);
2589
2590 done:
2591   return ret;
2592 }
2593
2594 /* read a chain from the ogg file. This code will
2595  * read all BOS pages and will create and return a GstOggChain 
2596  * structure with the results. 
2597  * 
2598  * This function will also read N pages from each stream in the
2599  * chain and submit them to the decoders. When the decoder has
2600  * decoded the first buffer, we know the timestamp of the first
2601  * page in the chain.
2602  */
2603 static GstFlowReturn
2604 gst_ogg_demux_read_chain (GstOggDemux * ogg, GstOggChain ** res_chain)
2605 {
2606   GstFlowReturn ret;
2607   GstOggChain *chain = NULL;
2608   gint64 offset = ogg->offset;
2609   ogg_page op;
2610   gboolean done;
2611   gint i;
2612
2613   GST_LOG_OBJECT (ogg, "reading chain at %" G_GINT64_FORMAT, offset);
2614
2615   /* first read the BOS pages, do typefind on them, create
2616    * the decoders, send data to the decoders. */
2617   while (TRUE) {
2618     GstOggPad *pad;
2619     glong serial;
2620
2621     ret = gst_ogg_demux_get_next_page (ogg, &op, -1, NULL);
2622     if (ret != GST_FLOW_OK) {
2623       GST_WARNING_OBJECT (ogg, "problem reading BOS page: ret=%d", ret);
2624       break;
2625     }
2626     if (!ogg_page_bos (&op)) {
2627       GST_WARNING_OBJECT (ogg, "page is not BOS page");
2628       /* if we did not find a chain yet, assume this is a bogus stream and
2629        * ignore it */
2630       if (!chain)
2631         ret = GST_FLOW_UNEXPECTED;
2632       break;
2633     }
2634
2635     if (chain == NULL) {
2636       chain = gst_ogg_chain_new (ogg);
2637       chain->offset = offset;
2638     }
2639
2640     serial = ogg_page_serialno (&op);
2641     if (gst_ogg_chain_get_stream (chain, serial) != NULL) {
2642       GST_WARNING_OBJECT (ogg, "found serial %08lx BOS page twice, ignoring",
2643           serial);
2644       continue;
2645     }
2646
2647     pad = gst_ogg_chain_new_stream (chain, serial);
2648     gst_ogg_pad_submit_page (pad, &op);
2649   }
2650
2651   if (ret != GST_FLOW_OK || chain == NULL) {
2652     if (ret == GST_FLOW_OK) {
2653       GST_WARNING_OBJECT (ogg, "no chain was found");
2654       ret = GST_FLOW_ERROR;
2655     } else if (ret != GST_FLOW_UNEXPECTED) {
2656       GST_WARNING_OBJECT (ogg, "failed to read chain");
2657     } else {
2658       GST_DEBUG_OBJECT (ogg, "done reading chains");
2659     }
2660     if (chain) {
2661       gst_ogg_chain_free (chain);
2662     }
2663     if (res_chain)
2664       *res_chain = NULL;
2665     return ret;
2666   }
2667
2668   chain->have_bos = TRUE;
2669   GST_LOG_OBJECT (ogg, "read bos pages, init decoder now");
2670
2671   /* now read pages until we receive a buffer from each of the
2672    * stream decoders, this will tell us the timestamp of the
2673    * first packet in the chain then */
2674
2675   /* save the offset to the first non bos page in the chain: if searching for
2676    * pad->first_time we read past the end of the chain, we'll seek back to this
2677    * position
2678    */
2679   offset = ogg->offset;
2680
2681   done = FALSE;
2682   while (!done) {
2683     glong serial;
2684     gboolean known_serial = FALSE;
2685     GstFlowReturn ret;
2686
2687     serial = ogg_page_serialno (&op);
2688     done = TRUE;
2689     for (i = 0; i < chain->streams->len; i++) {
2690       GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
2691
2692       GST_LOG_OBJECT (ogg, "serial %08lx time %" GST_TIME_FORMAT,
2693           pad->map.serialno, GST_TIME_ARGS (pad->start_time));
2694
2695       if (pad->map.serialno == serial) {
2696         known_serial = TRUE;
2697
2698         /* submit the page now, this will fill in the start_time when the
2699          * internal decoder finds it */
2700         gst_ogg_pad_submit_page (pad, &op);
2701
2702         if (!pad->map.is_skeleton && pad->start_time == -1
2703             && ogg_page_eos (&op)) {
2704           /* got EOS on a pad before we could find its start_time.
2705            * We have no chance of finding a start_time for every pad so
2706            * stop searching for the other start_time(s).
2707            */
2708           done = TRUE;
2709           break;
2710         }
2711       }
2712       /* the timestamp will be filled in when we submit the pages */
2713       if (!pad->map.is_sparse)
2714         done &= (pad->start_time != GST_CLOCK_TIME_NONE);
2715
2716       GST_LOG_OBJECT (ogg, "done %08lx now %d", pad->map.serialno, done);
2717     }
2718
2719     /* we read a page not belonging to the current chain: seek back to the
2720      * beginning of the chain
2721      */
2722     if (!known_serial) {
2723       GST_LOG_OBJECT (ogg, "unknown serial %08lx", serial);
2724       gst_ogg_demux_seek (ogg, offset);
2725       break;
2726     }
2727
2728     if (!done) {
2729       ret = gst_ogg_demux_get_next_page (ogg, &op, -1, NULL);
2730       if (ret != GST_FLOW_OK)
2731         break;
2732     }
2733   }
2734   GST_LOG_OBJECT (ogg, "done reading chain");
2735   /* now we can fill in the missing info using queries */
2736   for (i = 0; i < chain->streams->len; i++) {
2737     GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
2738
2739     if (pad->map.is_skeleton)
2740       continue;
2741
2742     pad->mode = GST_OGG_PAD_MODE_STREAMING;
2743   }
2744
2745   if (res_chain)
2746     *res_chain = chain;
2747
2748   return GST_FLOW_OK;
2749 }
2750
2751 /* read the last pages from the ogg stream to get the final
2752  * page end_offsets.
2753  */
2754 static GstFlowReturn
2755 gst_ogg_demux_read_end_chain (GstOggDemux * ogg, GstOggChain * chain)
2756 {
2757   gint64 begin = chain->end_offset;
2758   gint64 end = begin;
2759   gint64 last_granule = -1;
2760   GstOggPad *last_pad = NULL;
2761   GstFlowReturn ret;
2762   gboolean done = FALSE;
2763   ogg_page og;
2764   gint i;
2765
2766   while (!done) {
2767     begin -= CHUNKSIZE;
2768     if (begin < 0)
2769       begin = 0;
2770
2771     gst_ogg_demux_seek (ogg, begin);
2772
2773     /* now continue reading until we run out of data, if we find a page
2774      * start, we save it. It might not be the final page as there could be
2775      * another page after this one. */
2776     while (ogg->offset < end) {
2777       ret = gst_ogg_demux_get_next_page (ogg, &og, end - ogg->offset, NULL);
2778
2779       if (ret == GST_FLOW_LIMIT)
2780         break;
2781       if (ret != GST_FLOW_OK)
2782         return ret;
2783
2784       for (i = 0; i < chain->streams->len; i++) {
2785         GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
2786
2787         if (pad->map.is_sparse)
2788           continue;
2789
2790         if (pad->map.serialno == ogg_page_serialno (&og)) {
2791           gint64 granulepos = ogg_page_granulepos (&og);
2792
2793           if (granulepos != -1) {
2794             last_granule = granulepos;
2795             last_pad = pad;
2796             done = TRUE;
2797           }
2798           break;
2799         }
2800       }
2801     }
2802   }
2803
2804   if (last_pad) {
2805     chain->segment_stop =
2806         gst_ogg_stream_get_end_time_for_granulepos (&last_pad->map,
2807         last_granule);
2808   } else {
2809     chain->segment_stop = GST_CLOCK_TIME_NONE;
2810   }
2811
2812   GST_INFO ("segment stop %" G_GUINT64_FORMAT, chain->segment_stop);
2813
2814   return GST_FLOW_OK;
2815 }
2816
2817 /* find a pad with a given serial number
2818  */
2819 static GstOggPad *
2820 gst_ogg_demux_find_pad (GstOggDemux * ogg, glong serialno)
2821 {
2822   GstOggPad *pad;
2823   gint i;
2824
2825   /* first look in building chain if any */
2826   if (ogg->building_chain) {
2827     pad = gst_ogg_chain_get_stream (ogg->building_chain, serialno);
2828     if (pad)
2829       return pad;
2830   }
2831
2832   /* then look in current chain if any */
2833   if (ogg->current_chain) {
2834     pad = gst_ogg_chain_get_stream (ogg->current_chain, serialno);
2835     if (pad)
2836       return pad;
2837   }
2838
2839   for (i = 0; i < ogg->chains->len; i++) {
2840     GstOggChain *chain = g_array_index (ogg->chains, GstOggChain *, i);
2841
2842     pad = gst_ogg_chain_get_stream (chain, serialno);
2843     if (pad)
2844       return pad;
2845   }
2846   return NULL;
2847 }
2848
2849 /* find a chain with a given serial number
2850  */
2851 static GstOggChain *
2852 gst_ogg_demux_find_chain (GstOggDemux * ogg, glong serialno)
2853 {
2854   GstOggPad *pad;
2855
2856   pad = gst_ogg_demux_find_pad (ogg, serialno);
2857   if (pad) {
2858     return pad->chain;
2859   }
2860   return NULL;
2861 }
2862
2863 /* returns TRUE if all streams have valid start time */
2864 static gboolean
2865 gst_ogg_demux_collect_chain_info (GstOggDemux * ogg, GstOggChain * chain)
2866 {
2867   gboolean res = TRUE;
2868
2869   chain->total_time = GST_CLOCK_TIME_NONE;
2870   GST_DEBUG_OBJECT (ogg, "trying to collect chain info");
2871
2872   /* see if we have a start time on all streams */
2873   chain->segment_start = gst_ogg_demux_collect_start_time (ogg, chain);
2874
2875   if (chain->segment_start == G_MAXUINT64) {
2876     /* not yet, stream some more data */
2877     res = FALSE;
2878   } else if (chain->segment_stop != GST_CLOCK_TIME_NONE) {
2879     /* we can calculate a total time */
2880     chain->total_time = chain->segment_stop - chain->segment_start;
2881   }
2882
2883   GST_DEBUG ("total time %" G_GUINT64_FORMAT, chain->total_time);
2884
2885   GST_DEBUG_OBJECT (ogg, "return %d", res);
2886
2887   return res;
2888 }
2889
2890 static void
2891 gst_ogg_demux_collect_info (GstOggDemux * ogg)
2892 {
2893   gint i;
2894
2895   /* collect all info */
2896   ogg->total_time = 0;
2897
2898   for (i = 0; i < ogg->chains->len; i++) {
2899     GstOggChain *chain = g_array_index (ogg->chains, GstOggChain *, i);
2900
2901     chain->begin_time = ogg->total_time;
2902
2903     gst_ogg_demux_collect_chain_info (ogg, chain);
2904
2905     ogg->total_time += chain->total_time;
2906   }
2907   gst_segment_set_duration (&ogg->segment, GST_FORMAT_TIME, ogg->total_time);
2908 }
2909
2910 /* find all the chains in the ogg file, this reads the first and
2911  * last page of the ogg stream, if they match then the ogg file has
2912  * just one chain, else we do a binary search for all chains.
2913  */
2914 static GstFlowReturn
2915 gst_ogg_demux_find_chains (GstOggDemux * ogg)
2916 {
2917   ogg_page og;
2918   GstPad *peer;
2919   GstFormat format;
2920   gboolean res;
2921   gulong serialno;
2922   GstOggChain *chain;
2923   GstFlowReturn ret;
2924
2925   /* get peer to figure out length */
2926   if ((peer = gst_pad_get_peer (ogg->sinkpad)) == NULL)
2927     goto no_peer;
2928
2929   /* find length to read last page, we store this for later use. */
2930   format = GST_FORMAT_BYTES;
2931   res = gst_pad_query_duration (peer, &format, &ogg->length);
2932   gst_object_unref (peer);
2933   if (!res || ogg->length <= 0)
2934     goto no_length;
2935
2936   GST_DEBUG_OBJECT (ogg, "file length %" G_GINT64_FORMAT, ogg->length);
2937
2938   /* read chain from offset 0, this is the first chain of the
2939    * ogg file. */
2940   gst_ogg_demux_seek (ogg, 0);
2941   ret = gst_ogg_demux_read_chain (ogg, &chain);
2942   if (ret != GST_FLOW_OK)
2943     goto no_first_chain;
2944
2945   /* read page from end offset, we use this page to check if its serial
2946    * number is contained in the first chain. If this is the case then
2947    * this ogg is not a chained ogg and we can skip the scanning. */
2948   gst_ogg_demux_seek (ogg, ogg->length);
2949   ret = gst_ogg_demux_get_prev_page (ogg, &og, NULL);
2950   if (ret != GST_FLOW_OK)
2951     goto no_last_page;
2952
2953   serialno = ogg_page_serialno (&og);
2954
2955   if (!gst_ogg_chain_has_stream (chain, serialno)) {
2956     /* the last page is not in the first stream, this means we should
2957      * find all the chains in this chained ogg. */
2958     ret =
2959         gst_ogg_demux_bisect_forward_serialno (ogg, 0, 0, ogg->length, chain,
2960         0);
2961   } else {
2962     /* we still call this function here but with an empty range so that
2963      * we can reuse the setup code in this routine. */
2964     ret =
2965         gst_ogg_demux_bisect_forward_serialno (ogg, 0, ogg->length,
2966         ogg->length, chain, 0);
2967   }
2968   if (ret != GST_FLOW_OK)
2969     goto done;
2970
2971   /* all fine, collect and print */
2972   gst_ogg_demux_collect_info (ogg);
2973
2974   /* dump our chains and streams */
2975   gst_ogg_print (ogg);
2976
2977 done:
2978   return ret;
2979
2980   /*** error cases ***/
2981 no_peer:
2982   {
2983     GST_ELEMENT_ERROR (ogg, STREAM, DEMUX, (NULL), ("we don't have a peer"));
2984     return GST_FLOW_NOT_LINKED;
2985   }
2986 no_length:
2987   {
2988     GST_ELEMENT_ERROR (ogg, STREAM, DEMUX, (NULL), ("can't get file length"));
2989     return GST_FLOW_NOT_SUPPORTED;
2990   }
2991 no_first_chain:
2992   {
2993     GST_ELEMENT_ERROR (ogg, STREAM, DEMUX, (NULL), ("can't get first chain"));
2994     return GST_FLOW_ERROR;
2995   }
2996 no_last_page:
2997   {
2998     GST_DEBUG_OBJECT (ogg, "can't get last page");
2999     if (chain)
3000       gst_ogg_chain_free (chain);
3001     return ret;
3002   }
3003 }
3004
3005 static GstFlowReturn
3006 gst_ogg_demux_handle_page (GstOggDemux * ogg, ogg_page * page)
3007 {
3008   GstOggPad *pad;
3009   gint64 granule;
3010   glong serialno;
3011   GstFlowReturn result = GST_FLOW_OK;
3012
3013   serialno = ogg_page_serialno (page);
3014   granule = ogg_page_granulepos (page);
3015
3016   GST_LOG_OBJECT (ogg,
3017       "processing ogg page (serial %08lx, pageno %ld, granulepos %"
3018       G_GINT64_FORMAT ", bos %d)",
3019       serialno, ogg_page_pageno (page), granule, ogg_page_bos (page));
3020
3021   if (ogg_page_bos (page)) {
3022     GstOggChain *chain;
3023
3024     /* first page */
3025     /* see if we know about the chain already */
3026     chain = gst_ogg_demux_find_chain (ogg, serialno);
3027     if (chain) {
3028       GstEvent *event;
3029       gint64 start = 0;
3030
3031       if (chain->segment_start != GST_CLOCK_TIME_NONE)
3032         start = chain->segment_start;
3033
3034       /* create the newsegment event we are going to send out */
3035       event = gst_event_new_new_segment (FALSE, ogg->segment.rate,
3036           GST_FORMAT_TIME, start, chain->segment_stop, chain->begin_time);
3037       gst_event_set_seqnum (event, ogg->seqnum);
3038
3039       GST_DEBUG_OBJECT (ogg,
3040           "segment: start %" GST_TIME_FORMAT ", stop %" GST_TIME_FORMAT
3041           ", time %" GST_TIME_FORMAT, GST_TIME_ARGS (start),
3042           GST_TIME_ARGS (chain->segment_stop),
3043           GST_TIME_ARGS (chain->begin_time));
3044
3045       /* activate it as it means we have a non-header, this will also deactivate
3046        * the currently running chain. */
3047       gst_ogg_demux_activate_chain (ogg, chain, event);
3048       pad = gst_ogg_demux_find_pad (ogg, serialno);
3049     } else {
3050       GstClockTime chain_time;
3051       GstOggChain *current_chain;
3052       gint64 current_time;
3053
3054       /* this can only happen in push mode */
3055       if (ogg->pullmode)
3056         goto unknown_chain;
3057
3058       current_chain = ogg->current_chain;
3059       current_time = ogg->segment.last_stop;
3060
3061       /* time of new chain is current time */
3062       chain_time = current_time;
3063
3064       if (ogg->building_chain == NULL) {
3065         GstOggChain *newchain;
3066
3067         newchain = gst_ogg_chain_new (ogg);
3068         newchain->offset = 0;
3069         /* set new chain begin time aligned with end time of old chain */
3070         newchain->begin_time = chain_time;
3071         GST_DEBUG_OBJECT (ogg, "new chain, begin time %" GST_TIME_FORMAT,
3072             GST_TIME_ARGS (chain_time));
3073
3074         /* and this is the one we are building now */
3075         ogg->building_chain = newchain;
3076       }
3077       pad = gst_ogg_chain_new_stream (ogg->building_chain, serialno);
3078     }
3079   } else {
3080     pad = gst_ogg_demux_find_pad (ogg, serialno);
3081   }
3082   if (pad) {
3083     result = gst_ogg_pad_submit_page (pad, page);
3084   } else {
3085     /* no pad. This means an ogg page without bos has been seen for this
3086      * serialno. we just ignore it but post a warning... */
3087     GST_ELEMENT_WARNING (ogg, STREAM, DECODE,
3088         (NULL), ("unknown ogg pad for serial %08lx detected", serialno));
3089     return GST_FLOW_OK;
3090   }
3091   return result;
3092
3093   /* ERRORS */
3094 unknown_chain:
3095   {
3096     GST_ELEMENT_ERROR (ogg, STREAM, DECODE,
3097         (NULL), ("unknown ogg chain for serial %08lx detected", serialno));
3098     return GST_FLOW_ERROR;
3099   }
3100 }
3101
3102 /* streaming mode, receive a buffer, parse it, create pads for
3103  * the serialno, submit pages and packets to the oggpads
3104  */
3105 static GstFlowReturn
3106 gst_ogg_demux_chain (GstPad * pad, GstBuffer * buffer)
3107 {
3108   GstOggDemux *ogg;
3109   gint ret = 0;
3110   GstFlowReturn result = GST_FLOW_OK;
3111
3112   ogg = GST_OGG_DEMUX (GST_OBJECT_PARENT (pad));
3113
3114   GST_DEBUG_OBJECT (ogg, "chain");
3115   result = gst_ogg_demux_submit_buffer (ogg, buffer);
3116
3117   while (result == GST_FLOW_OK) {
3118     ogg_page page;
3119
3120     ret = ogg_sync_pageout (&ogg->sync, &page);
3121     if (ret == 0)
3122       /* need more data */
3123       break;
3124     if (ret == -1) {
3125       /* discontinuity in the pages */
3126       GST_DEBUG_OBJECT (ogg, "discont in page found, continuing");
3127     } else {
3128       result = gst_ogg_demux_handle_page (ogg, &page);
3129     }
3130   }
3131   if (ret == 0 || result == GST_FLOW_OK) {
3132     gst_ogg_demux_sync_streams (ogg);
3133   }
3134   return result;
3135 }
3136
3137 static gboolean
3138 gst_ogg_demux_send_event (GstOggDemux * ogg, GstEvent * event)
3139 {
3140   GstOggChain *chain = ogg->current_chain;
3141   gboolean res = TRUE;
3142
3143   if (chain) {
3144     gint i;
3145
3146     for (i = 0; i < chain->streams->len; i++) {
3147       GstOggPad *pad = g_array_index (chain->streams, GstOggPad *, i);
3148
3149       gst_event_ref (event);
3150       GST_DEBUG_OBJECT (pad, "Pushing event %" GST_PTR_FORMAT, event);
3151       res &= gst_pad_push_event (GST_PAD (pad), event);
3152     }
3153   }
3154   gst_event_unref (event);
3155
3156   return res;
3157 }
3158
3159 static GstFlowReturn
3160 gst_ogg_demux_combine_flows (GstOggDemux * ogg, GstOggPad * pad,
3161     GstFlowReturn ret)
3162 {
3163   GstOggChain *chain;
3164
3165   /* store the value */
3166   pad->last_ret = ret;
3167
3168   /* any other error that is not-linked can be returned right
3169    * away */
3170   if (ret != GST_FLOW_NOT_LINKED)
3171     goto done;
3172
3173   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
3174   chain = ogg->current_chain;
3175   if (chain) {
3176     gint i;
3177
3178     for (i = 0; i < chain->streams->len; i++) {
3179       GstOggPad *opad = g_array_index (chain->streams, GstOggPad *, i);
3180
3181       ret = opad->last_ret;
3182       /* some other return value (must be SUCCESS but we can return
3183        * other values as well) */
3184       if (ret != GST_FLOW_NOT_LINKED)
3185         goto done;
3186     }
3187     /* if we get here, all other pads were unlinked and we return
3188      * NOT_LINKED then */
3189   }
3190 done:
3191   return ret;
3192 }
3193
3194 /* returns TRUE if all streams in current chain reached EOS, FALSE otherwise */
3195 static gboolean
3196 gst_ogg_demux_check_eos (GstOggDemux * ogg)
3197 {
3198   GstOggChain *chain;
3199   gboolean eos = TRUE;
3200
3201   chain = ogg->current_chain;
3202   if (G_LIKELY (chain)) {
3203     gint i;
3204
3205     for (i = 0; i < chain->streams->len; i++) {
3206       GstOggPad *opad = g_array_index (chain->streams, GstOggPad *, i);
3207
3208       eos = eos && opad->is_eos;
3209     }
3210   } else {
3211     eos = FALSE;
3212   }
3213
3214   return eos;
3215 }
3216
3217 static GstFlowReturn
3218 gst_ogg_demux_loop_forward (GstOggDemux * ogg)
3219 {
3220   GstFlowReturn ret;
3221   GstBuffer *buffer;
3222
3223   if (ogg->offset == ogg->length) {
3224     GST_LOG_OBJECT (ogg, "no more data to pull %" G_GINT64_FORMAT
3225         " == %" G_GINT64_FORMAT, ogg->offset, ogg->length);
3226     ret = GST_FLOW_UNEXPECTED;
3227     goto done;
3228   }
3229
3230   GST_LOG_OBJECT (ogg, "pull data %" G_GINT64_FORMAT, ogg->offset);
3231   ret = gst_pad_pull_range (ogg->sinkpad, ogg->offset, CHUNKSIZE, &buffer);
3232   if (ret != GST_FLOW_OK) {
3233     GST_LOG_OBJECT (ogg, "Failed pull_range");
3234     goto done;
3235   }
3236
3237   ogg->offset += GST_BUFFER_SIZE (buffer);
3238
3239   if (G_UNLIKELY (ogg->newsegment)) {
3240     gst_ogg_demux_send_event (ogg, ogg->newsegment);
3241     ogg->newsegment = NULL;
3242   }
3243
3244   ret = gst_ogg_demux_chain (ogg->sinkpad, buffer);
3245   if (ret != GST_FLOW_OK) {
3246     GST_LOG_OBJECT (ogg, "Failed demux_chain");
3247     goto done;
3248   }
3249
3250   /* check for the end of the segment */
3251   if (gst_ogg_demux_check_eos (ogg)) {
3252     GST_LOG_OBJECT (ogg, "got EOS");
3253     ret = GST_FLOW_UNEXPECTED;
3254     goto done;
3255   }
3256 done:
3257   return ret;
3258 }
3259
3260 /* reverse mode.
3261  *
3262  * We read the pages backwards and send the packets forwards. The first packet
3263  * in the page will be pushed with the DISCONT flag set.
3264  *
3265  * Special care has to be taken for continued pages, which we can only decode
3266  * when we have the previous page(s).
3267  */
3268 static GstFlowReturn
3269 gst_ogg_demux_loop_reverse (GstOggDemux * ogg)
3270 {
3271   GstFlowReturn ret;
3272   ogg_page page;
3273   gint64 offset;
3274
3275   if (ogg->offset == 0) {
3276     GST_LOG_OBJECT (ogg, "no more data to pull %" G_GINT64_FORMAT
3277         " == 0", ogg->offset);
3278     ret = GST_FLOW_UNEXPECTED;
3279     goto done;
3280   }
3281
3282   GST_LOG_OBJECT (ogg, "read page from %" G_GINT64_FORMAT, ogg->offset);
3283   ret = gst_ogg_demux_get_prev_page (ogg, &page, &offset);
3284   if (ret != GST_FLOW_OK)
3285     goto done;
3286
3287   ogg->offset = offset;
3288
3289   if (G_UNLIKELY (ogg->newsegment)) {
3290     gst_ogg_demux_send_event (ogg, ogg->newsegment);
3291     ogg->newsegment = NULL;
3292   }
3293
3294   ret = gst_ogg_demux_handle_page (ogg, &page);
3295   if (ret != GST_FLOW_OK)
3296     goto done;
3297
3298   /* check for the end of the segment */
3299   if (gst_ogg_demux_check_eos (ogg)) {
3300     GST_LOG_OBJECT (ogg, "got EOS");
3301     ret = GST_FLOW_UNEXPECTED;
3302     goto done;
3303   }
3304 done:
3305   return ret;
3306 }
3307
3308 static void
3309 gst_ogg_demux_sync_streams (GstOggDemux * ogg)
3310 {
3311   GstClockTime cur;
3312   GstOggChain *chain;
3313   guint i;
3314
3315   chain = ogg->current_chain;
3316   cur = ogg->segment.last_stop;
3317   if (chain == NULL || cur == -1)
3318     return;
3319
3320   for (i = 0; i < chain->streams->len; i++) {
3321     GstOggPad *stream = g_array_index (chain->streams, GstOggPad *, i);
3322
3323     /* Theoretically, we should be doing this for all streams, but we're only
3324      * doing it for known-to-be-sparse streams at the moment in order not to
3325      * break things for wrongly-muxed streams (like we used to produce once) */
3326     if (stream->map.is_sparse && stream->last_stop != GST_CLOCK_TIME_NONE) {
3327
3328       /* Does this stream lag? Random threshold of 2 seconds */
3329       if (GST_CLOCK_DIFF (stream->last_stop, cur) > (2 * GST_SECOND)) {
3330         GST_DEBUG_OBJECT (stream, "synchronizing stream with others by "
3331             "advancing time from %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT,
3332             GST_TIME_ARGS (stream->last_stop), GST_TIME_ARGS (cur));
3333         stream->last_stop = cur;
3334         /* advance stream time (FIXME: is this right, esp. time_pos?) */
3335         gst_pad_push_event (GST_PAD_CAST (stream),
3336             gst_event_new_new_segment (TRUE, ogg->segment.rate,
3337                 GST_FORMAT_TIME, stream->last_stop, -1, stream->last_stop));
3338       }
3339     }
3340   }
3341 }
3342
3343 /* random access code
3344  *
3345  * - first find all the chains and streams by scanning the file.
3346  * - then get and chain buffers, just like the streaming case.
3347  * - when seeking, we can use the chain info to perform the seek.
3348  */
3349 static void
3350 gst_ogg_demux_loop (GstOggPad * pad)
3351 {
3352   GstOggDemux *ogg;
3353   GstFlowReturn ret;
3354   GstEvent *event;
3355
3356   ogg = GST_OGG_DEMUX (GST_OBJECT_PARENT (pad));
3357
3358   if (ogg->need_chains) {
3359     gboolean res;
3360
3361     /* this is the only place where we write chains and thus need to lock. */
3362     GST_CHAIN_LOCK (ogg);
3363     ret = gst_ogg_demux_find_chains (ogg);
3364     GST_CHAIN_UNLOCK (ogg);
3365     if (ret != GST_FLOW_OK)
3366       goto chain_read_failed;
3367
3368     ogg->need_chains = FALSE;
3369
3370     GST_OBJECT_LOCK (ogg);
3371     ogg->running = TRUE;
3372     event = ogg->event;
3373     ogg->event = NULL;
3374     GST_OBJECT_UNLOCK (ogg);
3375
3376     /* and seek to configured positions without FLUSH */
3377     res = gst_ogg_demux_perform_seek_pull (ogg, event);
3378     if (event)
3379       gst_event_unref (event);
3380
3381     if (!res)
3382       goto seek_failed;
3383   }
3384
3385   if (ogg->segment.rate >= 0.0)
3386     ret = gst_ogg_demux_loop_forward (ogg);
3387   else
3388     ret = gst_ogg_demux_loop_reverse (ogg);
3389
3390   if (ret != GST_FLOW_OK)
3391     goto pause;
3392
3393   gst_ogg_demux_sync_streams (ogg);
3394   return;
3395
3396   /* ERRORS */
3397 chain_read_failed:
3398   {
3399     /* error was posted */
3400     goto pause;
3401   }
3402 seek_failed:
3403   {
3404     GST_ELEMENT_ERROR (ogg, STREAM, DEMUX, (NULL),
3405         ("failed to start demuxing ogg"));
3406     ret = GST_FLOW_ERROR;
3407     goto pause;
3408   }
3409 pause:
3410   {
3411     const gchar *reason = gst_flow_get_name (ret);
3412     GstEvent *event = NULL;
3413
3414     GST_LOG_OBJECT (ogg, "pausing task, reason %s", reason);
3415     ogg->segment_running = FALSE;
3416     gst_pad_pause_task (ogg->sinkpad);
3417
3418     if (ret == GST_FLOW_UNEXPECTED) {
3419       /* perform EOS logic */
3420       if (ogg->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3421         gint64 stop;
3422         GstMessage *message;
3423
3424         /* for segment playback we need to post when (in stream time)
3425          * we stopped, this is either stop (when set) or the duration. */
3426         if ((stop = ogg->segment.stop) == -1)
3427           stop = ogg->segment.duration;
3428
3429         GST_LOG_OBJECT (ogg, "Sending segment done, at end of segment");
3430         message =
3431             gst_message_new_segment_done (GST_OBJECT (ogg), GST_FORMAT_TIME,
3432             stop);
3433         gst_message_set_seqnum (message, ogg->seqnum);
3434
3435         gst_element_post_message (GST_ELEMENT (ogg), message);
3436       } else {
3437         /* normal playback, send EOS to all linked pads */
3438         GST_LOG_OBJECT (ogg, "Sending EOS, at end of stream");
3439         event = gst_event_new_eos ();
3440       }
3441     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
3442       GST_ELEMENT_ERROR (ogg, STREAM, FAILED,
3443           (_("Internal data stream error.")),
3444           ("stream stopped, reason %s", reason));
3445       event = gst_event_new_eos ();
3446     }
3447
3448     /* For wrong-state we still want to pause the task and stop
3449      * but no error message or other things are necessary.
3450      * wrong-state is no real error and will be caused by flushing,
3451      * e.g. because of a flushing seek.
3452      */
3453     if (event) {
3454       gst_event_set_seqnum (event, ogg->seqnum);
3455       gst_ogg_demux_send_event (ogg, event);
3456     }
3457     return;
3458   }
3459 }
3460
3461 static void
3462 gst_ogg_demux_clear_chains (GstOggDemux * ogg)
3463 {
3464   gint i;
3465
3466   gst_ogg_demux_deactivate_current_chain (ogg);
3467
3468   GST_CHAIN_LOCK (ogg);
3469   for (i = 0; i < ogg->chains->len; i++) {
3470     GstOggChain *chain = g_array_index (ogg->chains, GstOggChain *, i);
3471
3472     gst_ogg_chain_free (chain);
3473   }
3474   ogg->chains = g_array_set_size (ogg->chains, 0);
3475   GST_CHAIN_UNLOCK (ogg);
3476 }
3477
3478 /* this function is called when the pad is activated and should start
3479  * processing data.
3480  *
3481  * We check if we can do random access to decide if we work push or
3482  * pull based.
3483  */
3484 static gboolean
3485 gst_ogg_demux_sink_activate (GstPad * sinkpad)
3486 {
3487   if (gst_pad_check_pull_range (sinkpad)) {
3488     GST_DEBUG_OBJECT (sinkpad, "activating pull");
3489     return gst_pad_activate_pull (sinkpad, TRUE);
3490   } else {
3491     GST_DEBUG_OBJECT (sinkpad, "activating push");
3492     return gst_pad_activate_push (sinkpad, TRUE);
3493   }
3494 }
3495
3496 /* this function gets called when we activate ourselves in push mode.
3497  * We cannot seek (ourselves) in the stream */
3498 static gboolean
3499 gst_ogg_demux_sink_activate_push (GstPad * sinkpad, gboolean active)
3500 {
3501   GstOggDemux *ogg;
3502
3503   ogg = GST_OGG_DEMUX (GST_OBJECT_PARENT (sinkpad));
3504
3505   ogg->pullmode = FALSE;
3506   ogg->resync = FALSE;
3507
3508   return TRUE;
3509 }
3510
3511 /* this function gets called when we activate ourselves in pull mode.
3512  * We can perform  random access to the resource and we start a task
3513  * to start reading */
3514 static gboolean
3515 gst_ogg_demux_sink_activate_pull (GstPad * sinkpad, gboolean active)
3516 {
3517   GstOggDemux *ogg;
3518
3519   ogg = GST_OGG_DEMUX (GST_OBJECT_PARENT (sinkpad));
3520
3521   if (active) {
3522     ogg->need_chains = TRUE;
3523     ogg->pullmode = TRUE;
3524
3525     return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_ogg_demux_loop,
3526         sinkpad);
3527   } else {
3528     return gst_pad_stop_task (sinkpad);
3529   }
3530 }
3531
3532 static GstStateChangeReturn
3533 gst_ogg_demux_change_state (GstElement * element, GstStateChange transition)
3534 {
3535   GstOggDemux *ogg;
3536   GstStateChangeReturn result = GST_STATE_CHANGE_FAILURE;
3537
3538   ogg = GST_OGG_DEMUX (element);
3539
3540   switch (transition) {
3541     case GST_STATE_CHANGE_NULL_TO_READY:
3542       ogg->basetime = 0;
3543       ogg_sync_init (&ogg->sync);
3544       break;
3545     case GST_STATE_CHANGE_READY_TO_PAUSED:
3546       ogg_sync_reset (&ogg->sync);
3547       ogg->running = FALSE;
3548       ogg->bitrate = 0;
3549       ogg->segment_running = FALSE;
3550       ogg->total_time = -1;
3551       gst_segment_init (&ogg->segment, GST_FORMAT_TIME);
3552       break;
3553     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3554       break;
3555     default:
3556       break;
3557   }
3558
3559   result = parent_class->change_state (element, transition);
3560
3561   switch (transition) {
3562     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3563       break;
3564     case GST_STATE_CHANGE_PAUSED_TO_READY:
3565       gst_ogg_demux_clear_chains (ogg);
3566       GST_OBJECT_LOCK (ogg);
3567       ogg->running = FALSE;
3568       ogg->segment_running = FALSE;
3569       GST_OBJECT_UNLOCK (ogg);
3570       break;
3571     case GST_STATE_CHANGE_READY_TO_NULL:
3572       ogg_sync_clear (&ogg->sync);
3573       break;
3574     default:
3575       break;
3576   }
3577   return result;
3578 }
3579
3580 gboolean
3581 gst_ogg_demux_plugin_init (GstPlugin * plugin)
3582 {
3583   GST_DEBUG_CATEGORY_INIT (gst_ogg_demux_debug, "oggdemux", 0, "ogg demuxer");
3584   GST_DEBUG_CATEGORY_INIT (gst_ogg_demux_setup_debug, "oggdemux_setup", 0,
3585       "ogg demuxer setup stage when parsing pipeline");
3586
3587 #ifdef ENABLE_NLS
3588   GST_DEBUG ("binding text domain %s to locale dir %s", GETTEXT_PACKAGE,
3589       LOCALEDIR);
3590   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
3591   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3592 #endif
3593
3594   return gst_element_register (plugin, "oggdemux", GST_RANK_PRIMARY,
3595       GST_TYPE_OGG_DEMUX);
3596 }
3597
3598 /* prints all info about the element */
3599 #undef GST_CAT_DEFAULT
3600 #define GST_CAT_DEFAULT gst_ogg_demux_setup_debug
3601
3602 #ifdef GST_DISABLE_GST_DEBUG
3603
3604 static void
3605 gst_ogg_print (GstOggDemux * ogg)
3606 {
3607   /* NOP */
3608 }
3609
3610 #else /* !GST_DISABLE_GST_DEBUG */
3611
3612 static void
3613 gst_ogg_print (GstOggDemux * ogg)
3614 {
3615   guint j, i;
3616
3617   GST_INFO_OBJECT (ogg, "%u chains", ogg->chains->len);
3618   GST_INFO_OBJECT (ogg, " total time: %" GST_TIME_FORMAT,
3619       GST_TIME_ARGS (ogg->total_time));
3620
3621   for (i = 0; i < ogg->chains->len; i++) {
3622     GstOggChain *chain = g_array_index (ogg->chains, GstOggChain *, i);
3623
3624     GST_INFO_OBJECT (ogg, " chain %d (%u streams):", i, chain->streams->len);
3625     GST_INFO_OBJECT (ogg,
3626         "  offset: %" G_GINT64_FORMAT " - %" G_GINT64_FORMAT, chain->offset,
3627         chain->end_offset);
3628     GST_INFO_OBJECT (ogg, "  begin time: %" GST_TIME_FORMAT,
3629         GST_TIME_ARGS (chain->begin_time));
3630     GST_INFO_OBJECT (ogg, "  total time: %" GST_TIME_FORMAT,
3631         GST_TIME_ARGS (chain->total_time));
3632     GST_INFO_OBJECT (ogg, "  segment start: %" GST_TIME_FORMAT,
3633         GST_TIME_ARGS (chain->segment_start));
3634     GST_INFO_OBJECT (ogg, "  segment stop:  %" GST_TIME_FORMAT,
3635         GST_TIME_ARGS (chain->segment_stop));
3636
3637     for (j = 0; j < chain->streams->len; j++) {
3638       GstOggPad *stream = g_array_index (chain->streams, GstOggPad *, j);
3639
3640       GST_INFO_OBJECT (ogg, "  stream %08lx:", stream->map.serialno);
3641       GST_INFO_OBJECT (ogg, "   start time:       %" GST_TIME_FORMAT,
3642           GST_TIME_ARGS (stream->start_time));
3643     }
3644   }
3645 }
3646 #endif /* GST_DISABLE_GST_DEBUG */