baesparse: fix refactor regression in loop based parsing
[platform/upstream/gstreamer.git] / gst / audioparsers / gstbaseparse.c
1 /* GStreamer
2  * Copyright (C) 2008 Nokia Corporation. All rights reserved.
3  *   Contact: Stefan Kost <stefan.kost@nokia.com>
4  * Copyright (C) 2008 Sebastian Dröge <sebastian.droege@collabora.co.uk>.
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:gstbaseparse
24  * @short_description: Base class for stream parsers
25  * @see_also: #GstBaseTransform
26  *
27  * This base class is for parser elements that process data and splits it 
28  * into separate audio/video/whatever frames.
29  *
30  * It provides for:
31  * <itemizedlist>
32  *   <listitem><para>One sinkpad and one srcpad</para></listitem>
33  *   <listitem><para>Handles state changes</para></listitem>
34  *   <listitem><para>Does flushing</para></listitem>
35  *   <listitem><para>Push mode</para></listitem>
36  *   <listitem><para>Pull mode</para></listitem>
37  *   <listitem><para>Handles events (NEWSEGMENT/EOS/FLUSH)</para></listitem>
38  *   <listitem><para>Handles seeking in both modes</para></listitem>
39  *   <listitem><para>
40  *        Handles POSITION/DURATION/SEEKING/FORMAT/CONVERT queries
41  *   </para></listitem>
42  * </itemizedlist>
43  *
44  * The purpose of this base class is to provide a basic functionality of
45  * a parser and share a lot of rather complex code.
46  *
47  * Description of the parsing mechanism:
48  * <orderedlist>
49  * <listitem>
50  *   <itemizedlist><title>Set-up phase</title>
51  *   <listitem><para>
52  *     GstBaseParse class calls @set_sink_caps to inform the subclass about
53  *     incoming sinkpad caps. Subclass should set the srcpad caps accordingly.
54  *   </para></listitem>
55  *   <listitem><para>
56  *     GstBaseParse calls @start to inform subclass that data processing is
57  *     about to start now.
58  *   </para></listitem>
59  *   <listitem><para>
60  *      At least in this point subclass needs to tell the GstBaseParse class
61  *      how big data chunks it wants to receive (min_frame_size). It can do 
62  *      this with @gst_base_parse_set_min_frame_size.
63  *   </para></listitem>
64  *   <listitem><para>
65  *      GstBaseParse class sets up appropriate data passing mode (pull/push)
66  *      and starts to process the data.
67  *   </para></listitem>
68  *   </itemizedlist>
69  * </listitem>
70  * <listitem>
71  *   <itemizedlist>
72  *   <title>Parsing phase</title>
73  *     <listitem><para>
74  *       GstBaseParse gathers at least min_frame_size bytes of data either 
75  *       by pulling it from upstream or collecting buffers into internal
76  *       #GstAdapter.
77  *     </para></listitem>
78  *     <listitem><para>
79  *       A buffer of (at least) min_frame_size bytes is passed to subclass with
80  *       @check_valid_frame. Subclass checks the contents and returns TRUE
81  *       if the buffer contains a valid frame. It also needs to set the
82  *       @framesize according to the detected frame size. If buffer didn't
83  *       contain a valid frame, this call must return FALSE and optionally
84  *       set the @skipsize value to inform base class that how many bytes
85  *       it needs to skip in order to find a valid frame. The passed buffer
86  *       is read-only.  Note that @check_valid_frame might receive any small
87  *       amount of input data when leftover data is being drained (e.g. at EOS).
88  *     </para></listitem>
89  *     <listitem><para>
90  *       After valid frame is found, it will be passed again to subclass with
91  *       @parse_frame call. Now subclass is responsible for parsing the
92  *       frame contents and setting the caps, buffer timestamp and duration
93  *       (although the latter can also be done by GstBaseParse if it is
94  *       appropriately configured, see below).
95  *     </para></listitem>
96  *     <listitem><para>
97  *       Finally the buffer can be pushed downstream and parsing loop starts
98  *       over again.  Just prior to actually pushing the buffer in question,
99  *       it is passed to @pre_push_buffer which gives subclass yet one
100  *       last chance to examine buffer metadata, or to send some custom (tag)
101  *       events, or to perform custom (segment) filtering.
102  *     </para></listitem>
103  *     <listitem><para>
104  *       During the parsing process GstBaseParseClass will handle both srcpad and
105  *       sinkpad events. They will be passed to subclass if @event or
106  *       @src_event callbacks have been provided.
107  *     </para></listitem>
108  *   </itemizedlist>
109  * </listitem>
110  * <listitem>
111  *   <itemizedlist><title>Shutdown phase</title>
112  *   <listitem><para>
113  *     GstBaseParse class calls @stop to inform the subclass that data
114  *     parsing will be stopped.
115  *   </para></listitem>
116  *   </itemizedlist>
117  * </listitem>
118  * </orderedlist>
119  *
120  * Subclass is responsible for providing pad template caps for
121  * source and sink pads. The pads need to be named "sink" and "src". It also 
122  * needs to set the fixed caps on srcpad, when the format is ensured (e.g. 
123  * when base class calls subclass' @set_sink_caps function).
124  *
125  * This base class uses GST_FORMAT_DEFAULT as a meaning of frames. So,
126  * subclass conversion routine needs to know that conversion from
127  * GST_FORMAT_TIME to GST_FORMAT_DEFAULT must return the
128  * frame number that can be found from the given byte position.
129  *
130  * GstBaseParse uses subclasses conversion methods also for seeking (or otherwise
131  * uses its own default one, see also below).
132  *
133  * Subclass @start and @stop functions will be called to inform the beginning
134  * and end of data processing.
135  *
136  * Things that subclass need to take care of:
137  * <itemizedlist>
138  *   <listitem><para>Provide pad templates</para></listitem>
139  *   <listitem><para>
140  *      Fixate the source pad caps when appropriate
141  *   </para></listitem>
142  *   <listitem><para>
143  *      Inform base class how big data chunks should be retrieved. This is
144  *      done with @gst_base_parse_set_min_frame_size function.
145  *   </para></listitem>
146  *   <listitem><para>
147  *      Examine data chunks passed to subclass with @check_valid_frame
148  *      and tell if they contain a valid frame
149  *   </para></listitem>
150  *   <listitem><para>
151  *      Set the caps and timestamp to frame that is passed to subclass with
152  *      @parse_frame function.
153  *   </para></listitem>
154  *   <listitem><para>Provide conversion functions</para></listitem>
155  *   <listitem><para>
156  *      Update the duration information with @gst_base_parse_set_duration
157  *   </para></listitem>
158  *   <listitem><para>
159  *      Optionally passthrough using @gst_base_parse_set_passthrough
160  *   </para></listitem>
161  *   <listitem><para>
162  *      Configure various baseparse parameters using @gst_base_parse_set_seek and
163  *      @gst_base_parse_set_frame_props.
164  *   </para></listitem>
165  *   <listitem><para>
166  *      In particular, if subclass is unable to determine a duration, but
167  *      parsing (or specs) yields a frames per seconds rate, then this can be
168  *      provided to GstBaseParse to enable it to cater for
169  *      buffer time metadata (which will be taken from upstream as much as possible).
170  *      Internally keeping track of frame durations and respective
171  *      sizes that have been pushed provides GstBaseParse with an estimated bitrate.
172  *      A default @convert (used if not overriden) will then use these
173  *      rates to perform obvious conversions.  These rates are also used to update
174  *      (estimated) duration at regular frame intervals.
175  *   </para></listitem>
176  * </itemizedlist>
177  *
178  */
179
180 /* TODO:
181  *  - In push mode provide a queue of adapter-"queued" buffers for upstream
182  *    buffer metadata
183  *  - Queue buffers/events until caps are set
184  */
185
186 #ifdef HAVE_CONFIG_H
187 #  include "config.h"
188 #endif
189
190 #include <stdlib.h>
191 #include <string.h>
192
193 #include "gstbaseparse.h"
194
195 #define MIN_FRAMES_TO_POST_BITRATE 10
196 #define TARGET_DIFFERENCE          (20 * GST_SECOND)
197
198 GST_DEBUG_CATEGORY_STATIC (gst_base_parse_debug);
199 #define GST_CAT_DEFAULT gst_base_parse_debug
200
201 /* Supported formats */
202 static GstFormat fmtlist[] = {
203   GST_FORMAT_DEFAULT,
204   GST_FORMAT_BYTES,
205   GST_FORMAT_TIME,
206   0
207 };
208
209 #define GST_BASE_PARSE_GET_PRIVATE(obj)  \
210     (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_PARSE, GstBaseParsePrivate))
211
212 struct _GstBaseParsePrivate
213 {
214   GstActivateMode pad_mode;
215
216   gint64 duration;
217   GstFormat duration_fmt;
218   gint64 estimated_duration;
219
220   guint min_frame_size;
221   gboolean passthrough;
222   guint fps_num, fps_den;
223   guint update_interval;
224   guint bitrate;
225   guint lead_in, lead_out;
226   GstClockTime lead_in_ts, lead_out_ts;
227   GstBaseParseSeekable seekable;
228
229   gboolean discont;
230   gboolean flushing;
231   gboolean drain;
232
233   gint64 offset;
234   gint64 sync_offset;
235   GstClockTime next_ts;
236   GstClockTime prev_ts;
237   GstClockTime frame_duration;
238   gboolean seen_keyframe;
239   gboolean is_video;
240
241   guint64 framecount;
242   guint64 bytecount;
243   guint64 data_bytecount;
244   guint64 acc_duration;
245   GstClockTime first_frame_ts;
246   gint64 first_frame_offset;
247
248   gboolean post_min_bitrate;
249   gboolean post_avg_bitrate;
250   gboolean post_max_bitrate;
251   guint min_bitrate;
252   guint avg_bitrate;
253   guint max_bitrate;
254   guint posted_avg_bitrate;
255
256   GList *pending_events;
257
258   GstBuffer *cache;
259
260   /* index entry storage, either ours or provided */
261   GstIndex *index;
262   gint index_id;
263   gboolean own_index;
264   /* seek table entries only maintained if upstream is BYTE seekable */
265   gboolean upstream_seekable;
266   gboolean upstream_has_duration;
267   gint64 upstream_size;
268   /* minimum distance between two index entries */
269   GstClockTimeDiff idx_interval;
270   /* ts and offset of last entry added */
271   GstClockTime index_last_ts;
272   guint64 index_last_offset;
273   gboolean index_last_valid;
274
275   /* timestamps currently produced are accurate, e.g. started from 0 onwards */
276   gboolean exact_position;
277   /* seek events are temporarily kept to match them with newsegments */
278   GSList *pending_seeks;
279
280   /* reverse playback */
281   GSList *buffers_pending;
282   GSList *buffers_queued;
283   GstClockTime last_ts;
284   gint64 last_offset;
285 };
286
287 typedef struct _GstBaseParseSeek
288 {
289   GstSegment segment;
290   gboolean accurate;
291   gint64 offset;
292   GstClockTime start_ts;
293 } GstBaseParseSeek;
294
295 static GstElementClass *parent_class = NULL;
296
297 static void gst_base_parse_class_init (GstBaseParseClass * klass);
298 static void gst_base_parse_init (GstBaseParse * parse,
299     GstBaseParseClass * klass);
300
301 GType
302 gst_base_parse_get_type (void)
303 {
304   static GType base_parse_type = 0;
305
306   if (!base_parse_type) {
307     static const GTypeInfo base_parse_info = {
308       sizeof (GstBaseParseClass),
309       (GBaseInitFunc) NULL,
310       (GBaseFinalizeFunc) NULL,
311       (GClassInitFunc) gst_base_parse_class_init,
312       NULL,
313       NULL,
314       sizeof (GstBaseParse),
315       0,
316       (GInstanceInitFunc) gst_base_parse_init,
317     };
318
319     base_parse_type = g_type_register_static (GST_TYPE_ELEMENT,
320         "GstAudioBaseParseBad", &base_parse_info, G_TYPE_FLAG_ABSTRACT);
321   }
322   return base_parse_type;
323 }
324
325 static void gst_base_parse_finalize (GObject * object);
326
327 static GstStateChangeReturn gst_base_parse_change_state (GstElement * element,
328     GstStateChange transition);
329 static void gst_base_parse_reset (GstBaseParse * parse);
330
331 static void gst_base_parse_set_index (GstElement * element, GstIndex * index);
332 static GstIndex *gst_base_parse_get_index (GstElement * element);
333
334 static gboolean gst_base_parse_sink_activate (GstPad * sinkpad);
335 static gboolean gst_base_parse_sink_activate_push (GstPad * pad,
336     gboolean active);
337 static gboolean gst_base_parse_sink_activate_pull (GstPad * pad,
338     gboolean active);
339 static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
340     GstEvent * event);
341 static void gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event);
342
343 static gboolean gst_base_parse_src_event (GstPad * pad, GstEvent * event);
344 static gboolean gst_base_parse_sink_event (GstPad * pad, GstEvent * event);
345 static gboolean gst_base_parse_query (GstPad * pad, GstQuery * query);
346 static gboolean gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps);
347 static const GstQueryType *gst_base_parse_get_querytypes (GstPad * pad);
348
349 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstBuffer * buffer);
350 static void gst_base_parse_loop (GstPad * pad);
351
352 static gboolean gst_base_parse_check_frame (GstBaseParse * parse,
353     GstBuffer * buffer, guint * framesize, gint * skipsize);
354
355 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
356     GstBuffer * buffer);
357
358 static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
359     GstEvent * event);
360
361 static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
362     GstEvent * event);
363
364 static void gst_base_parse_drain (GstBaseParse * parse);
365
366 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
367     gboolean post_min, gboolean post_avg, gboolean post_max);
368
369 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
370     GstClockTime time, gboolean before, GstClockTime * _ts);
371 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
372     GstClockTime * _time, gint64 * _offset);
373
374 static GstFlowReturn gst_base_parse_process_fragment (GstBaseParse * parse,
375     gboolean push_only);
376
377 static void
378 gst_base_parse_clear_queues (GstBaseParse * parse)
379 {
380   g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
381   g_slist_free (parse->priv->buffers_queued);
382   parse->priv->buffers_queued = NULL;
383   g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
384       NULL);
385   g_slist_free (parse->priv->buffers_pending);
386   parse->priv->buffers_pending = NULL;
387 }
388
389 static void
390 gst_base_parse_finalize (GObject * object)
391 {
392   GstBaseParse *parse = GST_BASE_PARSE (object);
393   GstEvent **p_ev;
394
395   g_object_unref (parse->adapter);
396
397   if (parse->pending_segment) {
398     p_ev = &parse->pending_segment;
399     gst_event_replace (p_ev, NULL);
400   }
401   if (parse->close_segment) {
402     p_ev = &parse->close_segment;
403     gst_event_replace (p_ev, NULL);
404   }
405
406   if (parse->priv->cache) {
407     gst_buffer_unref (parse->priv->cache);
408     parse->priv->cache = NULL;
409   }
410
411   g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
412       NULL);
413   g_list_free (parse->priv->pending_events);
414   parse->priv->pending_events = NULL;
415
416   if (parse->priv->index) {
417     gst_object_unref (parse->priv->index);
418     parse->priv->index = NULL;
419   }
420
421   gst_base_parse_clear_queues (parse);
422
423   G_OBJECT_CLASS (parent_class)->finalize (object);
424 }
425
426 static void
427 gst_base_parse_class_init (GstBaseParseClass * klass)
428 {
429   GObjectClass *gobject_class;
430   GstElementClass *gstelement_class;
431
432   gobject_class = G_OBJECT_CLASS (klass);
433   g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
434   parent_class = g_type_class_peek_parent (klass);
435   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
436
437   gstelement_class = (GstElementClass *) klass;
438   gstelement_class->change_state =
439       GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
440   gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
441   gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
442
443   /* Default handlers */
444   klass->check_valid_frame = gst_base_parse_check_frame;
445   klass->parse_frame = gst_base_parse_parse_frame;
446   klass->src_event = gst_base_parse_src_eventfunc;
447   klass->convert = gst_base_parse_convert_default;
448
449   GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
450       "baseparse element");
451 }
452
453 static void
454 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
455 {
456   GstPadTemplate *pad_template;
457
458   GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
459
460   parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
461
462   pad_template =
463       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
464   g_return_if_fail (pad_template != NULL);
465   parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
466   gst_pad_set_event_function (parse->sinkpad,
467       GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
468   gst_pad_set_setcaps_function (parse->sinkpad,
469       GST_DEBUG_FUNCPTR (gst_base_parse_sink_setcaps));
470   gst_pad_set_chain_function (parse->sinkpad,
471       GST_DEBUG_FUNCPTR (gst_base_parse_chain));
472   gst_pad_set_activate_function (parse->sinkpad,
473       GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
474   gst_pad_set_activatepush_function (parse->sinkpad,
475       GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_push));
476   gst_pad_set_activatepull_function (parse->sinkpad,
477       GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_pull));
478   gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
479
480   GST_DEBUG_OBJECT (parse, "sinkpad created");
481
482   pad_template =
483       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
484   g_return_if_fail (pad_template != NULL);
485   parse->srcpad = gst_pad_new_from_template (pad_template, "src");
486   gst_pad_set_event_function (parse->srcpad,
487       GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
488   gst_pad_set_query_type_function (parse->srcpad,
489       GST_DEBUG_FUNCPTR (gst_base_parse_get_querytypes));
490   gst_pad_set_query_function (parse->srcpad,
491       GST_DEBUG_FUNCPTR (gst_base_parse_query));
492   gst_pad_use_fixed_caps (parse->srcpad);
493   gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
494   GST_DEBUG_OBJECT (parse, "src created");
495
496   parse->adapter = gst_adapter_new ();
497
498   parse->priv->pad_mode = GST_ACTIVATE_NONE;
499
500   /* init state */
501   gst_base_parse_reset (parse);
502   GST_DEBUG_OBJECT (parse, "init ok");
503 }
504
505 static void
506 gst_base_parse_reset (GstBaseParse * parse)
507 {
508   GST_OBJECT_LOCK (parse);
509   gst_segment_init (&parse->segment, GST_FORMAT_TIME);
510   parse->priv->duration = -1;
511   parse->priv->min_frame_size = 1;
512   parse->priv->discont = TRUE;
513   parse->priv->flushing = FALSE;
514   parse->priv->offset = 0;
515   parse->priv->sync_offset = 0;
516   parse->priv->update_interval = 50;
517   parse->priv->fps_num = parse->priv->fps_den = 0;
518   parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
519   parse->priv->lead_in = parse->priv->lead_out = 0;
520   parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
521   parse->priv->seekable = GST_BASE_PARSE_SEEK_DEFAULT;
522   parse->priv->bitrate = 0;
523   parse->priv->framecount = 0;
524   parse->priv->bytecount = 0;
525   parse->priv->acc_duration = 0;
526   parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
527   parse->priv->first_frame_offset = -1;
528   parse->priv->estimated_duration = -1;
529   parse->priv->next_ts = 0;
530   parse->priv->passthrough = FALSE;
531   parse->priv->post_min_bitrate = TRUE;
532   parse->priv->post_avg_bitrate = TRUE;
533   parse->priv->post_max_bitrate = TRUE;
534   parse->priv->min_bitrate = G_MAXUINT;
535   parse->priv->max_bitrate = 0;
536   parse->priv->avg_bitrate = 0;
537   parse->priv->posted_avg_bitrate = 0;
538
539   parse->priv->index_last_ts = 0;
540   parse->priv->index_last_offset = 0;
541   parse->priv->index_last_valid = TRUE;
542   parse->priv->upstream_seekable = FALSE;
543   parse->priv->upstream_size = 0;
544   parse->priv->upstream_has_duration = FALSE;
545   parse->priv->idx_interval = 0;
546   parse->priv->exact_position = TRUE;
547   parse->priv->seen_keyframe = FALSE;
548
549   parse->priv->last_ts = GST_CLOCK_TIME_NONE;
550   parse->priv->last_offset = 0;
551
552   if (parse->pending_segment) {
553     gst_event_unref (parse->pending_segment);
554     parse->pending_segment = NULL;
555   }
556
557   g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
558       NULL);
559   g_list_free (parse->priv->pending_events);
560   parse->priv->pending_events = NULL;
561
562   if (parse->priv->cache) {
563     gst_buffer_unref (parse->priv->cache);
564     parse->priv->cache = NULL;
565   }
566
567   g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
568   g_slist_free (parse->priv->pending_seeks);
569   parse->priv->pending_seeks = NULL;
570
571   GST_OBJECT_UNLOCK (parse);
572 }
573
574 /**
575  * gst_base_parse_check_frame:
576  * @parse: #GstBaseParse.
577  * @buffer: GstBuffer.
578  * @framesize: This will be set to tell the found frame size in bytes.
579  * @skipsize: Output parameter that tells how much data needs to be skipped
580  *            in order to find the following frame header.
581  *
582  * Default callback for check_valid_frame.
583  * 
584  * Returns: Always TRUE.
585  */
586 static gboolean
587 gst_base_parse_check_frame (GstBaseParse * parse,
588     GstBuffer * buffer, guint * framesize, gint * skipsize)
589 {
590   *framesize = GST_BUFFER_SIZE (buffer);
591   *skipsize = 0;
592   return TRUE;
593 }
594
595
596 /**
597  * gst_base_parse_parse_frame:
598  * @parse: #GstBaseParse.
599  * @buffer: #GstBuffer.
600  *
601  * Default callback for parse_frame.
602  */
603 static GstFlowReturn
604 gst_base_parse_parse_frame (GstBaseParse * parse, GstBuffer * buffer)
605 {
606   if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
607       GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
608     GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
609   }
610   if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
611       GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
612     GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
613   }
614   return GST_FLOW_OK;
615 }
616
617 /**
618  * gst_base_parse_convert:
619  * @parse: #GstBaseParse.
620  * @src_format: #GstFormat describing the source format.
621  * @src_value: Source value to be converted.
622  * @dest_format: #GstFormat defining the converted format.
623  * @dest_value: Pointer where the conversion result will be put.
624  *
625  * Converts using configured "convert" vmethod in #GstBaseParse class.
626  *
627  * Returns: TRUE if conversion was successful.
628  */
629 static gboolean
630 gst_base_parse_convert (GstBaseParse * parse,
631     GstFormat src_format,
632     gint64 src_value, GstFormat dest_format, gint64 * dest_value)
633 {
634   GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
635   gboolean ret;
636
637   g_return_val_if_fail (dest_value != NULL, FALSE);
638
639   if (!klass->convert)
640     return FALSE;
641
642   ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
643
644 #ifndef GST_DISABLE_GST_DEBUG
645   {
646     if (ret) {
647       if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
648         GST_LOG_OBJECT (parse,
649             "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
650             GST_TIME_ARGS (src_value), *dest_value);
651       } else if (dest_format == GST_FORMAT_TIME &&
652           src_format == GST_FORMAT_BYTES) {
653         GST_LOG_OBJECT (parse,
654             "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
655             src_value, GST_TIME_ARGS (*dest_value));
656       } else {
657         GST_LOG_OBJECT (parse,
658             "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
659             GST_STR_NULL (gst_format_get_name (src_format)),
660             GST_STR_NULL (gst_format_get_name (dest_format)),
661             src_value, *dest_value);
662       }
663     } else {
664       GST_DEBUG_OBJECT (parse, "conversion failed");
665     }
666   }
667 #endif
668
669   return ret;
670 }
671
672 /**
673  * gst_base_parse_sink_event:
674  * @pad: #GstPad that received the event.
675  * @event: #GstEvent to be handled.
676  *
677  * Handler for sink pad events.
678  *
679  * Returns: TRUE if the event was handled.
680  */
681 static gboolean
682 gst_base_parse_sink_event (GstPad * pad, GstEvent * event)
683 {
684   GstBaseParse *parse;
685   GstBaseParseClass *bclass;
686   gboolean handled = FALSE;
687   gboolean ret = TRUE;
688
689   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
690   bclass = GST_BASE_PARSE_GET_CLASS (parse);
691
692   GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
693       GST_EVENT_TYPE_NAME (event));
694
695   /* Cache all events except EOS, NEWSEGMENT and FLUSH_STOP if we have a
696    * pending segment */
697   if (parse->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
698       && GST_EVENT_TYPE (event) != GST_EVENT_NEWSEGMENT
699       && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
700       && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP) {
701
702     if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
703       /* See if any bitrate tags were posted */
704       gst_base_parse_handle_tag (parse, event);
705
706     parse->priv->pending_events =
707         g_list_append (parse->priv->pending_events, event);
708     ret = TRUE;
709   } else {
710
711     if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
712         parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
713       /* We've not posted bitrate tags yet - do so now */
714       gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
715
716     if (bclass->event)
717       handled = bclass->event (parse, event);
718
719     if (!handled)
720       handled = gst_base_parse_sink_eventfunc (parse, event);
721
722     if (!handled)
723       ret = gst_pad_event_default (pad, event);
724   }
725
726   gst_object_unref (parse);
727   GST_DEBUG_OBJECT (parse, "event handled");
728   return ret;
729 }
730
731
732 /**
733  * gst_base_parse_sink_eventfunc:
734  * @parse: #GstBaseParse.
735  * @event: #GstEvent to be handled.
736  *
737  * Element-level event handler function.
738  *
739  * The event will be unreffed only if it has been handled and this
740  * function returns %TRUE
741  *
742  * Returns: %TRUE if the event was handled and not need forwarding.
743  */
744 static gboolean
745 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
746 {
747   gboolean handled = FALSE;
748   GstEvent **eventp;
749
750   switch (GST_EVENT_TYPE (event)) {
751     case GST_EVENT_NEWSEGMENT:
752     {
753       gdouble rate, applied_rate;
754       GstFormat format;
755       gint64 start, stop, pos, next_ts, offset = 0;
756       gboolean update;
757
758       gst_event_parse_new_segment_full (event, &update, &rate, &applied_rate,
759           &format, &start, &stop, &pos);
760
761       GST_DEBUG_OBJECT (parse, "newseg rate %g, applied rate %g, "
762           "format %d, start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
763           ", pos = %" GST_TIME_FORMAT, rate, applied_rate, format,
764           GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (pos));
765
766       if (format == GST_FORMAT_BYTES) {
767         GstClockTime seg_start, seg_stop;
768         GstBaseParseSeek *seek = NULL;
769         GSList *node;
770
771         /* stop time is allowed to be open-ended, but not start & pos */
772         seg_stop = GST_CLOCK_TIME_NONE;
773         seg_start = 0;
774         offset = pos;
775
776         GST_OBJECT_LOCK (parse);
777         for (node = parse->priv->pending_seeks; node; node = node->next) {
778           GstBaseParseSeek *tmp = node->data;
779
780           if (tmp->offset == pos) {
781             seek = tmp;
782             break;
783           }
784         }
785         parse->priv->pending_seeks =
786             g_slist_remove (parse->priv->pending_seeks, seek);
787         GST_OBJECT_UNLOCK (parse);
788
789         if (seek) {
790           GST_DEBUG_OBJECT (parse,
791               "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
792               seek->accurate ? " accurate" : "", &seek->segment);
793           seg_start = seek->segment.start;
794           seg_stop = seek->segment.stop;
795           next_ts = seek->start_ts;
796           parse->priv->exact_position = seek->accurate;
797           g_free (seek);
798         } else {
799           /* best attempt convert */
800           /* as these are only estimates, stop is kept open-ended to avoid
801            * premature cutting */
802           gst_base_parse_convert (parse, GST_FORMAT_BYTES, start,
803               GST_FORMAT_TIME, (gint64 *) & seg_start);
804           parse->priv->exact_position = (start == 0);
805           next_ts = seg_start;
806         }
807
808         gst_event_unref (event);
809         event = gst_event_new_new_segment_full (update, rate, applied_rate,
810             GST_FORMAT_TIME, seg_start, seg_stop, seg_start);
811         format = GST_FORMAT_TIME;
812         start = seg_start;
813         stop = seg_stop;
814         GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. "
815             "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT,
816             GST_TIME_ARGS (seg_start), GST_TIME_ARGS (seg_stop));
817       } else if (format != GST_FORMAT_TIME) {
818         /* Unknown incoming segment format. Output a default open-ended 
819          * TIME segment */
820         gst_event_unref (event);
821         event = gst_event_new_new_segment_full (update, rate, applied_rate,
822             GST_FORMAT_TIME, 0, GST_CLOCK_TIME_NONE, 0);
823         format = GST_FORMAT_TIME;
824         next_ts = start = 0;
825         stop = GST_CLOCK_TIME_NONE;
826       } else {
827         /* not considered BYTE seekable if it is talking to us in TIME,
828          * whatever else it might claim */
829         parse->priv->upstream_seekable = FALSE;
830         next_ts = start;
831       }
832
833       gst_segment_set_newsegment_full (&parse->segment, update, rate,
834           applied_rate, format, start, stop, start);
835
836       /* save the segment for later, right before we push a new buffer so that
837        * the caps are fixed and the next linked element can receive
838        * the segment. */
839       eventp = &parse->pending_segment;
840       gst_event_replace (eventp, event);
841       gst_event_unref (event);
842       handled = TRUE;
843
844       /* but finish the current segment */
845       GST_DEBUG_OBJECT (parse, "draining current segment");
846       if (parse->segment.rate > 0.0)
847         gst_base_parse_drain (parse);
848       else
849         gst_base_parse_process_fragment (parse, FALSE);
850       gst_adapter_clear (parse->adapter);
851       parse->priv->offset = offset;
852       parse->priv->sync_offset = offset;
853       parse->priv->next_ts = next_ts;
854       parse->priv->last_ts = GST_CLOCK_TIME_NONE;
855       parse->priv->discont = TRUE;
856       parse->priv->seen_keyframe = FALSE;
857       break;
858     }
859
860     case GST_EVENT_FLUSH_START:
861       parse->priv->flushing = TRUE;
862       handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
863       if (handled)
864         gst_event_unref (event);
865       /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
866       GST_PAD_STREAM_LOCK (parse->srcpad);
867       GST_PAD_STREAM_UNLOCK (parse->srcpad);
868
869       break;
870
871     case GST_EVENT_FLUSH_STOP:
872       gst_adapter_clear (parse->adapter);
873       gst_base_parse_clear_queues (parse);
874       parse->priv->flushing = FALSE;
875       parse->priv->discont = TRUE;
876       parse->priv->last_ts = GST_CLOCK_TIME_NONE;
877       break;
878
879     case GST_EVENT_EOS:
880       if (parse->segment.rate > 0.0)
881         gst_base_parse_drain (parse);
882       else
883         gst_base_parse_process_fragment (parse, FALSE);
884
885       /* If we STILL have zero frames processed, fire an error */
886       if (parse->priv->framecount == 0) {
887         GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
888             ("No valid frames found before end of stream"), (NULL));
889       }
890       /* newsegment before eos */
891       if (parse->pending_segment) {
892         gst_pad_push_event (parse->srcpad, parse->pending_segment);
893         parse->pending_segment = NULL;
894       }
895       break;
896
897     default:
898       break;
899   }
900
901   return handled;
902 }
903
904
905 /**
906  * gst_base_parse_src_event:
907  * @pad: #GstPad that received the event.
908  * @event: #GstEvent that was received.
909  *
910  * Handler for source pad events.
911  *
912  * Returns: TRUE if the event was handled.
913  */
914 static gboolean
915 gst_base_parse_src_event (GstPad * pad, GstEvent * event)
916 {
917   GstBaseParse *parse;
918   GstBaseParseClass *bclass;
919   gboolean handled = FALSE;
920   gboolean ret = TRUE;
921
922   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
923   bclass = GST_BASE_PARSE_GET_CLASS (parse);
924
925   GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
926       GST_EVENT_TYPE_NAME (event));
927
928   if (bclass->src_event)
929     handled = bclass->src_event (parse, event);
930
931   if (!handled)
932     ret = gst_pad_event_default (pad, event);
933   else
934     gst_event_unref (event);
935
936   gst_object_unref (parse);
937   return ret;
938 }
939
940
941 /**
942  * gst_base_parse_src_eventfunc:
943  * @parse: #GstBaseParse.
944  * @event: #GstEvent that was received.
945  *
946  * Default srcpad event handler.
947  *
948  * Returns: TRUE if the event was handled and can be dropped.
949  */
950 static gboolean
951 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
952 {
953   gboolean handled = FALSE;
954
955   switch (GST_EVENT_TYPE (event)) {
956     case GST_EVENT_SEEK:
957     {
958       if (parse->priv->seekable > GST_BASE_PARSE_SEEK_NONE) {
959         handled = gst_base_parse_handle_seek (parse, event);
960       }
961       break;
962     }
963     default:
964       break;
965   }
966   return handled;
967 }
968
969
970 /**
971  * gst_base_parse_convert_default:
972  * @parse: #GstBaseParse.
973  * @src_format: #GstFormat describing the source format.
974  * @src_value: Source value to be converted.
975  * @dest_format: #GstFormat defining the converted format.
976  * @dest_value: Pointer where the conversion result will be put.
977  *
978  * Default implementation of "convert" vmethod in #GstBaseParse class.
979  *
980  * Returns: TRUE if conversion was successful.
981  */
982 gboolean
983 gst_base_parse_convert_default (GstBaseParse * parse,
984     GstFormat src_format,
985     gint64 src_value, GstFormat dest_format, gint64 * dest_value)
986 {
987   gboolean ret = FALSE;
988   guint64 bytes, duration;
989
990   if (G_UNLIKELY (src_format == dest_format)) {
991     *dest_value = src_value;
992     return TRUE;
993   }
994
995   if (G_UNLIKELY (src_value == -1)) {
996     *dest_value = -1;
997     return TRUE;
998   }
999
1000   if (G_UNLIKELY (src_value == 0)) {
1001     *dest_value = 0;
1002     return TRUE;
1003   }
1004
1005   /* need at least some frames */
1006   if (!parse->priv->framecount)
1007     return FALSE;
1008
1009   duration = parse->priv->acc_duration / GST_MSECOND;
1010   bytes = parse->priv->bytecount;
1011
1012   if (G_UNLIKELY (!duration || !bytes))
1013     return FALSE;
1014
1015   if (src_format == GST_FORMAT_BYTES) {
1016     if (dest_format == GST_FORMAT_TIME) {
1017       /* BYTES -> TIME conversion */
1018       GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1019       *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1020       *dest_value *= GST_MSECOND;
1021       GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1022           *dest_value / GST_MSECOND);
1023       ret = TRUE;
1024     }
1025   } else if (src_format == GST_FORMAT_TIME) {
1026     if (dest_format == GST_FORMAT_BYTES) {
1027       GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1028       *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1029           duration);
1030       GST_DEBUG_OBJECT (parse,
1031           "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1032           src_value / GST_MSECOND, *dest_value);
1033       ret = TRUE;
1034     }
1035   } else if (src_format == GST_FORMAT_DEFAULT) {
1036     /* DEFAULT == frame-based */
1037     if (dest_format == GST_FORMAT_TIME) {
1038       if (parse->priv->fps_den) {
1039         *dest_value = gst_util_uint64_scale (src_value,
1040             GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1041         ret = TRUE;
1042       }
1043     } else if (dest_format == GST_FORMAT_BYTES) {
1044     }
1045   }
1046
1047   return ret;
1048 }
1049
1050 /**
1051  * gst_base_parse_update_duration:
1052  * @parse: #GstBaseParse.
1053  *
1054  */
1055 static void
1056 gst_base_parse_update_duration (GstBaseParse * aacparse)
1057 {
1058   GstPad *peer;
1059   GstBaseParse *parse;
1060
1061   parse = GST_BASE_PARSE (aacparse);
1062
1063   peer = gst_pad_get_peer (parse->sinkpad);
1064   if (peer) {
1065     GstFormat pformat = GST_FORMAT_BYTES;
1066     gboolean qres = FALSE;
1067     gint64 ptot, dest_value;
1068
1069     qres = gst_pad_query_duration (peer, &pformat, &ptot);
1070     gst_object_unref (GST_OBJECT (peer));
1071     if (qres) {
1072       if (gst_base_parse_convert (parse, pformat, ptot,
1073               GST_FORMAT_TIME, &dest_value))
1074         parse->priv->estimated_duration = dest_value;
1075     }
1076   }
1077 }
1078
1079 static void
1080 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1081     gboolean post_avg, gboolean post_max)
1082 {
1083   GstTagList *taglist = gst_tag_list_new ();
1084
1085   if (post_min && parse->priv->post_min_bitrate)
1086     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1087         GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1088
1089   if (post_avg && parse->priv->post_avg_bitrate) {
1090     parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1091     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1092         parse->priv->avg_bitrate, NULL);
1093   }
1094
1095   if (post_max && parse->priv->post_max_bitrate)
1096     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1097         GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1098
1099   GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1100       parse->priv->min_bitrate, parse->priv->avg_bitrate,
1101       parse->priv->max_bitrate);
1102
1103   gst_element_found_tags_for_pad (GST_ELEMENT (parse), parse->srcpad, taglist);
1104 }
1105
1106 /**
1107  * gst_base_parse_update_bitrates:
1108  * @parse: #GstBaseParse.
1109  * @buffer: Current frame as a #GstBuffer
1110  *
1111  * Keeps track of the minimum and maximum bitrates, and also maintains a
1112  * running average bitrate of the stream so far.
1113  */
1114 static void
1115 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBuffer * buffer)
1116 {
1117   /* Only update the tag on a 10 kbps delta */
1118   static const gint update_threshold = 10000;
1119
1120   GstBaseParseClass *klass;
1121   guint64 data_len, frame_dur;
1122   gint overhead = 0, frame_bitrate, old_avg_bitrate;
1123   gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1124
1125   klass = GST_BASE_PARSE_GET_CLASS (parse);
1126
1127   if (klass->get_frame_overhead) {
1128     overhead = klass->get_frame_overhead (parse, buffer);
1129     if (overhead == -1)
1130       return;
1131   }
1132
1133   data_len = GST_BUFFER_SIZE (buffer) - overhead;
1134   parse->priv->data_bytecount += data_len;
1135
1136   /* duration should be valid by now,
1137    * either set by subclass or maybe based on fps settings */
1138   if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1139     /* Calculate duration of a frame from buffer properties */
1140     frame_dur = GST_BUFFER_DURATION (buffer);
1141     parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1142         parse->priv->acc_duration;
1143
1144   } else {
1145     /* No way to figure out frame duration (is this even possible?) */
1146     return;
1147   }
1148
1149   /* override if subclass provided bitrate, e.g. metadata based */
1150   if (parse->priv->bitrate) {
1151     parse->priv->avg_bitrate = parse->priv->bitrate;
1152     /* spread this (confirmed) info ASAP */
1153     if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1154       gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1155   }
1156
1157   frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1158
1159   GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1160       parse->priv->avg_bitrate);
1161
1162   if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1163     goto exit;
1164   } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1165     /* always post all at threshold time */
1166     update_min = update_max = update_avg = TRUE;
1167   } else {
1168     if (frame_bitrate < parse->priv->min_bitrate) {
1169       parse->priv->min_bitrate = frame_bitrate;
1170       update_min = TRUE;
1171     }
1172
1173     if (frame_bitrate > parse->priv->max_bitrate) {
1174       parse->priv->max_bitrate = frame_bitrate;
1175       update_max = TRUE;
1176     }
1177
1178     old_avg_bitrate = parse->priv->posted_avg_bitrate;
1179     if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1180         || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1181         update_threshold)
1182       update_avg = TRUE;
1183   }
1184
1185   if ((update_min || update_avg || update_max))
1186     gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1187
1188   /* If average bitrate changes that much and no valid (time) duration provided,
1189    * then post a new duration message so applications can update their cached
1190    * values */
1191   if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1192           GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1193     gst_element_post_message (GST_ELEMENT (parse),
1194         gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1195
1196 exit:
1197   return;
1198 }
1199
1200 /**
1201  * gst_base_parse_add_index_entry:
1202  * @parse: #GstBaseParse.
1203  * @offset: offset of entry
1204  * @ts: timestamp associated with offset
1205  * @key: whether entry refers to keyframe
1206  * @force: add entry disregarding sanity checks
1207  *
1208  * Adds an entry to the index associating @offset to @ts.  It is recommended
1209  * to only add keyframe entries.  @force allows to bypass checks, such as
1210  * whether the stream is (upstream) seekable, another entry is already "close"
1211  * to the new entry, etc.
1212  *
1213  * Returns: #gboolean indicating whether entry was added
1214  */
1215 gboolean
1216 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1217     GstClockTime ts, gboolean key, gboolean force)
1218 {
1219   gboolean ret = FALSE;
1220   GstIndexAssociation associations[2];
1221
1222   GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1223       " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1224
1225   if (G_LIKELY (!force)) {
1226
1227     if (!parse->priv->upstream_seekable) {
1228       GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1229       goto exit;
1230     }
1231
1232     /* FIXME need better helper data structure that handles these issues
1233      * related to ongoing collecting of index entries */
1234     if (parse->priv->index_last_offset >= offset) {
1235       GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1236           "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1237       goto exit;
1238     }
1239
1240     if (GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1241         parse->priv->idx_interval) {
1242       GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1243           GST_TIME_ARGS (parse->priv->index_last_ts));
1244       goto exit;
1245     }
1246
1247     /* if last is not really the last one */
1248     if (!parse->priv->index_last_valid) {
1249       GstClockTime prev_ts;
1250
1251       gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1252       if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1253         GST_DEBUG_OBJECT (parse,
1254             "entry too close to existing entry %" GST_TIME_FORMAT,
1255             GST_TIME_ARGS (prev_ts));
1256         parse->priv->index_last_offset = offset;
1257         parse->priv->index_last_ts = ts;
1258         goto exit;
1259       }
1260     }
1261   }
1262
1263   associations[0].format = GST_FORMAT_TIME;
1264   associations[0].value = ts;
1265   associations[1].format = GST_FORMAT_BYTES;
1266   associations[1].value = offset;
1267
1268   /* index might change on-the-fly, although that would be nutty app ... */
1269   GST_OBJECT_LOCK (parse);
1270   gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1271       (key) ? GST_ASSOCIATION_FLAG_KEY_UNIT : GST_ASSOCIATION_FLAG_NONE,
1272       2, (const GstIndexAssociation *) &associations);
1273   GST_OBJECT_UNLOCK (parse);
1274
1275   if (key) {
1276     parse->priv->index_last_offset = offset;
1277     parse->priv->index_last_ts = ts;
1278   }
1279
1280   ret = TRUE;
1281
1282 exit:
1283   return ret;
1284 }
1285
1286 /* check for seekable upstream, above and beyond a mere query */
1287 static void
1288 gst_base_parse_check_seekability (GstBaseParse * parse)
1289 {
1290   GstQuery *query;
1291   gboolean seekable = FALSE;
1292   gint64 start = -1, stop = -1;
1293   guint idx_interval = 0;
1294
1295   query = gst_query_new_seeking (GST_FORMAT_BYTES);
1296   if (!gst_pad_peer_query (parse->sinkpad, query)) {
1297     GST_DEBUG_OBJECT (parse, "seeking query failed");
1298     goto done;
1299   }
1300
1301   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1302
1303   /* try harder to query upstream size if we didn't get it the first time */
1304   if (seekable && stop == -1) {
1305     GstFormat fmt = GST_FORMAT_BYTES;
1306
1307     GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1308     gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop);
1309   }
1310
1311   /* if upstream doesn't know the size, it's likely that it's not seekable in
1312    * practice even if it technically may be seekable */
1313   if (seekable && (start != 0 || stop <= start)) {
1314     GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1315     seekable = FALSE;
1316   }
1317
1318   /* let's not put every single frame into our index */
1319   if (seekable) {
1320     if (stop < 10 * 1024 * 1024)
1321       idx_interval = 100;
1322     else if (stop < 100 * 1024 * 1024)
1323       idx_interval = 500;
1324     else
1325       idx_interval = 1000;
1326   }
1327
1328 done:
1329   gst_query_unref (query);
1330
1331   GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1332       G_GUINT64_FORMAT ")", seekable, start, stop);
1333   parse->priv->upstream_seekable = seekable;
1334   parse->priv->upstream_size = seekable ? stop : 0;
1335
1336   GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1337   parse->priv->idx_interval = idx_interval * GST_MSECOND;
1338 }
1339
1340 /* some misc checks on upstream */
1341 static void
1342 gst_base_parse_check_upstream (GstBaseParse * parse)
1343 {
1344   GstFormat fmt = GST_FORMAT_TIME;
1345   gint64 stop;
1346
1347   if (gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop))
1348     if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1349       /* upstream has one, accept it also, and no further updates */
1350       gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1351       parse->priv->upstream_has_duration = TRUE;
1352     }
1353
1354   GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1355       parse->priv->upstream_has_duration);
1356 }
1357
1358 /* checks src caps to determine if dealing with audio or video */
1359 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1360 static void
1361 gst_base_parse_check_media (GstBaseParse * parse)
1362 {
1363   GstCaps *caps;
1364   GstStructure *s;
1365
1366   caps = GST_PAD_CAPS (parse->srcpad);
1367   if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1368     parse->priv->is_video =
1369         g_str_has_prefix (gst_structure_get_name (s), "video");
1370   } else {
1371     /* historical default */
1372     parse->priv->is_video = FALSE;
1373   }
1374
1375   GST_DEBUG_OBJECT (parse, "media is video == %d", parse->priv->is_video);
1376 }
1377
1378 /**
1379  * gst_base_parse_handle_and_push_buffer:
1380  * @parse: #GstBaseParse.
1381  * @klass: #GstBaseParseClass.
1382  * @buffer: #GstBuffer.
1383  *
1384  * Parses the frame from given buffer and pushes it forward. Also performs
1385  * timestamp handling and checks the segment limits.
1386  *
1387  * This is called with srcpad STREAM_LOCK held.
1388  *
1389  * Returns: #GstFlowReturn
1390  */
1391 static GstFlowReturn
1392 gst_base_parse_handle_and_push_buffer (GstBaseParse * parse,
1393     GstBaseParseClass * klass, GstBuffer * buffer)
1394 {
1395   GstFlowReturn ret;
1396   gint64 offset;
1397
1398   if (parse->priv->discont) {
1399     GST_DEBUG_OBJECT (parse, "marking DISCONT");
1400     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1401     parse->priv->discont = FALSE;
1402   }
1403
1404   /* some one-time start-up */
1405   if (G_UNLIKELY (!parse->priv->framecount)) {
1406     gst_base_parse_check_seekability (parse);
1407     gst_base_parse_check_upstream (parse);
1408   }
1409
1410   GST_LOG_OBJECT (parse,
1411       "parsing frame at offset %" G_GUINT64_FORMAT
1412       " (%#" G_GINT64_MODIFIER "x) of size %d",
1413       GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1414       GST_BUFFER_SIZE (buffer));
1415
1416   /* store offset as it might get overwritten */
1417   offset = GST_BUFFER_OFFSET (buffer);
1418   ret = klass->parse_frame (parse, buffer);
1419
1420   /* check initial frame to determine if subclass/format can provide ts.
1421    * If so, that allows and enables extra seek and duration determining options */
1422   if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
1423     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
1424       parse->priv->first_frame_offset = offset;
1425       parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1426       GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1427           " for first frame at offset %" G_GINT64_FORMAT,
1428           GST_TIME_ARGS (parse->priv->first_frame_ts),
1429           parse->priv->first_frame_offset);
1430       if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1431         gint64 off;
1432         GstClockTime last_ts = G_MAXINT64;
1433
1434         GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1435         gst_base_parse_locate_time (parse, &last_ts, &off);
1436         if (GST_CLOCK_TIME_IS_VALID (last_ts))
1437           gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1438       }
1439     } else {
1440       /* disable further checks */
1441       parse->priv->first_frame_offset = 0;
1442     }
1443   }
1444
1445   /* re-use default handler to add missing metadata as-much-as-possible */
1446   gst_base_parse_parse_frame (parse, buffer);
1447   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1448       GST_BUFFER_DURATION_IS_VALID (buffer)) {
1449     parse->priv->next_ts =
1450         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1451   } else {
1452     /* we lost track, do not produce bogus time next time around
1453      * (probably means parser subclass has given up on parsing as well) */
1454     GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1455     parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1456   }
1457
1458   if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1459       GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1460     gst_base_parse_add_index_entry (parse, offset,
1461         GST_BUFFER_TIMESTAMP (buffer),
1462         !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1463
1464   /* First buffers are dropped, this means that the subclass needs more
1465    * frames to decide on the format and queues them internally */
1466   /* convert internal flow to OK and mark discont for the next buffer. */
1467   if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1468     gst_buffer_unref (buffer);
1469     return GST_FLOW_OK;
1470   } else if (ret != GST_FLOW_OK) {
1471     return ret;
1472   }
1473
1474   return gst_base_parse_push_buffer (parse, buffer);
1475 }
1476
1477 /**
1478  * gst_base_parse_push_buffer:
1479  * @parse: #GstBaseParse.
1480  * @buffer: #GstBuffer.
1481  *
1482  * Pushes the buffer downstream, sends any pending events and
1483  * does some timestamp and segment handling.
1484  *
1485  * This must be called with srcpad STREAM_LOCK held.
1486  *
1487  * Returns: #GstFlowReturn
1488  */
1489 GstFlowReturn
1490 gst_base_parse_push_buffer (GstBaseParse * parse, GstBuffer * buffer)
1491 {
1492   GstFlowReturn ret = GST_FLOW_OK;
1493   GstClockTime last_start = GST_CLOCK_TIME_NONE;
1494   GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1495   GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1496
1497   GST_LOG_OBJECT (parse,
1498       "processing buffer of size %d with ts %" GST_TIME_FORMAT
1499       ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
1500       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1501       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1502
1503   /* update stats */
1504   parse->priv->bytecount += GST_BUFFER_SIZE (buffer);
1505   if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BASE_PARSE_BUFFER_FLAG_NO_FRAME)) {
1506     parse->priv->framecount++;
1507     if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1508       parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1509     }
1510   }
1511   GST_BUFFER_FLAG_UNSET (buffer, GST_BASE_PARSE_BUFFER_FLAG_NO_FRAME);
1512   if (parse->priv->update_interval &&
1513       (parse->priv->framecount % parse->priv->update_interval) == 0)
1514     gst_base_parse_update_duration (parse);
1515
1516   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1517     last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1518   if (last_start != GST_CLOCK_TIME_NONE
1519       && GST_BUFFER_DURATION_IS_VALID (buffer))
1520     last_stop = last_start + GST_BUFFER_DURATION (buffer);
1521
1522   /* should have caps by now */
1523   g_return_val_if_fail (GST_PAD_CAPS (parse->srcpad), GST_FLOW_ERROR);
1524
1525   gst_buffer_set_caps (buffer, GST_PAD_CAPS (parse->srcpad));
1526
1527   /* segment adjustment magic; only if we are running the whole show */
1528   if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1529       (parse->priv->pad_mode == GST_ACTIVATE_PULL ||
1530           parse->priv->upstream_seekable)) {
1531     /* segment times are typically estimates,
1532      * actual frame data might lead subclass to different timestamps,
1533      * so override segment start from what is supplied there */
1534     if (G_UNLIKELY (parse->pending_segment && !parse->priv->exact_position &&
1535             GST_CLOCK_TIME_IS_VALID (last_start))) {
1536       gst_event_unref (parse->pending_segment);
1537       parse->segment.start =
1538           MIN ((guint64) last_start, (guint64) parse->segment.stop);
1539       GST_DEBUG_OBJECT (parse,
1540           "adjusting pending segment start to %" GST_TIME_FORMAT,
1541           GST_TIME_ARGS (parse->segment.start));
1542       parse->pending_segment =
1543           gst_event_new_new_segment (FALSE, parse->segment.rate,
1544           parse->segment.format, parse->segment.start, parse->segment.stop,
1545           parse->segment.start);
1546     }
1547     /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1548     if (GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop) &&
1549         GST_CLOCK_TIME_IS_VALID (last_start)) {
1550       GstClockTimeDiff diff;
1551
1552       /* only send newsegments with increasing start times,
1553        * otherwise if these go back and forth downstream (sinks) increase
1554        * accumulated time and running_time */
1555       diff = GST_CLOCK_DIFF (parse->segment.last_stop, last_start);
1556       if (G_UNLIKELY (diff > 2 * GST_SECOND && last_start > parse->segment.start
1557               && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop) ||
1558                   last_start < parse->segment.stop))) {
1559         GST_DEBUG_OBJECT (parse,
1560             "Gap of %" G_GINT64_FORMAT " ns detected in stream "
1561             "(%" GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1562             "Sending updated NEWSEGMENT events", diff,
1563             GST_TIME_ARGS (parse->segment.last_stop),
1564             GST_TIME_ARGS (last_start));
1565         if (G_UNLIKELY (parse->pending_segment)) {
1566           gst_event_unref (parse->pending_segment);
1567           parse->segment.start = last_start;
1568           parse->pending_segment =
1569               gst_event_new_new_segment (FALSE, parse->segment.rate,
1570               parse->segment.format, parse->segment.start, parse->segment.stop,
1571               parse->segment.start);
1572         } else {
1573           /* send newsegment events such that the gap is not accounted in
1574            * accum time, hence running_time */
1575           /* close ahead of gap */
1576           gst_pad_push_event (parse->srcpad,
1577               gst_event_new_new_segment (TRUE, parse->segment.rate,
1578                   parse->segment.format, parse->segment.last_stop,
1579                   parse->segment.last_stop, parse->segment.last_stop));
1580           /* skip gap */
1581           gst_pad_push_event (parse->srcpad,
1582               gst_event_new_new_segment (FALSE, parse->segment.rate,
1583                   parse->segment.format, last_start, parse->segment.stop,
1584                   last_start));
1585         }
1586         /* align segment view with downstream,
1587          * prevents double-counting accum when closing segment */
1588         gst_segment_set_newsegment (&parse->segment, FALSE,
1589             parse->segment.rate, parse->segment.format, last_start,
1590             parse->segment.stop, last_start);
1591         parse->segment.last_stop = last_start;
1592       }
1593     }
1594   }
1595
1596   /* and should then also be linked downstream, so safe to send some events */
1597   if (G_UNLIKELY (parse->close_segment)) {
1598     /* only set up by loop */
1599     GST_DEBUG_OBJECT (parse, "loop sending close segment");
1600     gst_pad_push_event (parse->srcpad, parse->close_segment);
1601     parse->close_segment = NULL;
1602   }
1603   if (G_UNLIKELY (parse->pending_segment)) {
1604     GST_DEBUG_OBJECT (parse, "%s push pending segment",
1605         parse->priv->pad_mode == GST_ACTIVATE_PULL ? "loop" : "chain");
1606     gst_pad_push_event (parse->srcpad, parse->pending_segment);
1607     parse->pending_segment = NULL;
1608
1609     /* have caps; check identity */
1610     gst_base_parse_check_media (parse);
1611   }
1612
1613   /* update bitrates and optionally post corresponding tags
1614    * (following newsegment) */
1615   gst_base_parse_update_bitrates (parse, buffer);
1616
1617   if (G_UNLIKELY (parse->priv->pending_events)) {
1618     GList *l;
1619
1620     for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1621       gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1622     }
1623     g_list_free (parse->priv->pending_events);
1624     parse->priv->pending_events = NULL;
1625   }
1626
1627   if (klass->pre_push_buffer)
1628     ret = klass->pre_push_buffer (parse, buffer);
1629   else
1630     ret = GST_BASE_PARSE_FLOW_CLIP;
1631
1632   parse->priv->seen_keyframe |= parse->priv->is_video &&
1633       !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1634
1635   if (ret == GST_BASE_PARSE_FLOW_CLIP) {
1636     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1637         GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
1638         GST_BUFFER_TIMESTAMP (buffer) >
1639         parse->segment.stop + parse->priv->lead_out_ts) {
1640       GST_LOG_OBJECT (parse, "Dropped frame, after segment");
1641       ret = GST_FLOW_UNEXPECTED;
1642     } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1643         GST_BUFFER_DURATION_IS_VALID (buffer) &&
1644         GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
1645         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
1646         parse->priv->lead_in_ts < parse->segment.start) {
1647       if (parse->priv->seen_keyframe) {
1648         GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
1649         ret = GST_FLOW_OK;
1650       } else {
1651         GST_LOG_OBJECT (parse, "Dropped frame, before segment");
1652         ret = GST_BASE_PARSE_FLOW_DROPPED;
1653       }
1654     } else {
1655       ret = GST_FLOW_OK;
1656     }
1657   }
1658
1659   if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1660     GST_LOG_OBJECT (parse, "frame (%d bytes) dropped",
1661         GST_BUFFER_SIZE (buffer));
1662     gst_buffer_unref (buffer);
1663     ret = GST_FLOW_OK;
1664   } else if (ret == GST_FLOW_OK) {
1665     if (parse->segment.rate > 0.0) {
1666       ret = gst_pad_push (parse->srcpad, buffer);
1667       GST_LOG_OBJECT (parse, "frame (%d bytes) pushed: %s",
1668           GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
1669     } else {
1670       GST_LOG_OBJECT (parse, "frame (%d bytes) queued for now",
1671           GST_BUFFER_SIZE (buffer));
1672       parse->priv->buffers_queued =
1673           g_slist_prepend (parse->priv->buffers_queued, buffer);
1674       ret = GST_FLOW_OK;
1675     }
1676   } else {
1677     gst_buffer_unref (buffer);
1678     GST_LOG_OBJECT (parse, "frame (%d bytes) not pushed: %s",
1679         GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
1680     /* if we are not sufficiently in control, let upstream decide on EOS */
1681     if (ret == GST_FLOW_UNEXPECTED &&
1682         (parse->priv->passthrough ||
1683             (parse->priv->pad_mode == GST_ACTIVATE_PUSH &&
1684                 !parse->priv->upstream_seekable)))
1685       ret = GST_FLOW_OK;
1686   }
1687
1688   /* Update current running segment position */
1689   if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
1690       parse->segment.last_stop < last_stop)
1691     gst_segment_set_last_stop (&parse->segment, GST_FORMAT_TIME, last_stop);
1692
1693   return ret;
1694 }
1695
1696
1697 /**
1698  * gst_base_parse_drain:
1699  * @parse: #GstBaseParse.
1700  *
1701  * Drains the adapter until it is empty. It decreases the min_frame_size to
1702  * match the current adapter size and calls chain method until the adapter
1703  * is emptied or chain returns with error.
1704  */
1705 static void
1706 gst_base_parse_drain (GstBaseParse * parse)
1707 {
1708   guint avail;
1709
1710   GST_DEBUG_OBJECT (parse, "draining");
1711   parse->priv->drain = TRUE;
1712
1713   for (;;) {
1714     avail = gst_adapter_available (parse->adapter);
1715     if (!avail)
1716       break;
1717
1718     if (gst_base_parse_chain (parse->sinkpad, NULL) != GST_FLOW_OK) {
1719       break;
1720     }
1721
1722     /* nothing changed, maybe due to truncated frame; break infinite loop */
1723     if (avail == gst_adapter_available (parse->adapter)) {
1724       GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
1725       gst_adapter_clear (parse->adapter);
1726     }
1727   }
1728
1729   parse->priv->drain = FALSE;
1730 }
1731
1732 /**
1733  * gst_base_parse_process_fragment:
1734  * @parse: #GstBaseParse.
1735  *
1736  * Processes a reverse playback (forward) fragment:
1737  * - append head of last fragment that was skipped to current fragment data
1738  * - drain the resulting current fragment data (i.e. repeated chain)
1739  * - add time/duration (if needed) to frames queued by chain
1740  * - push queued data
1741  */
1742 static GstFlowReturn
1743 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
1744 {
1745   GstBuffer *buf;
1746   GstFlowReturn ret = GST_FLOW_OK;
1747   GSList *send = NULL;
1748
1749   if (push_only)
1750     goto push;
1751
1752   /* restore order */
1753   parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
1754   while (parse->priv->buffers_pending) {
1755     buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
1756     GST_LOG_OBJECT (parse, "adding pending buffer (size %d)",
1757         GST_BUFFER_SIZE (buf));
1758     gst_adapter_push (parse->adapter, buf);
1759     parse->priv->buffers_pending =
1760         g_slist_delete_link (parse->priv->buffers_pending,
1761         parse->priv->buffers_pending);
1762   }
1763
1764   /* invalidate so no fall-back timestamping is performed;
1765    * ok if taken from subclass or upstream */
1766   parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1767   /* prevent it hanging around stop all the time */
1768   parse->segment.last_stop = GST_CLOCK_TIME_NONE;
1769   /* mark next run */
1770   parse->priv->discont = TRUE;
1771
1772   /* chain looks for frames and queues resulting ones (in stead of pushing) */
1773   /* initial skipped data is added to buffers_pending */
1774   gst_base_parse_drain (parse);
1775
1776 push:
1777   /* add metadata (if needed to queued buffers */
1778   GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
1779       GST_TIME_ARGS (parse->priv->last_ts));
1780   while (parse->priv->buffers_queued) {
1781     buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
1782
1783     /* no touching if upstream or parsing provided time */
1784     if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1785       GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
1786           GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
1787     } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
1788         GST_BUFFER_DURATION_IS_VALID (buf)) {
1789       if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
1790         parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
1791       else
1792         parse->priv->last_ts = 0;
1793       GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
1794       GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
1795           GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
1796     } else {
1797       /* no idea, very bad */
1798       GST_WARNING_OBJECT (parse, "could not determine time for buffer");
1799     }
1800
1801     /* reverse order for ascending sending */
1802     send = g_slist_prepend (send, buf);
1803     parse->priv->buffers_queued =
1804         g_slist_delete_link (parse->priv->buffers_queued,
1805         parse->priv->buffers_queued);
1806   }
1807
1808   /* send buffers */
1809   while (send) {
1810     buf = GST_BUFFER_CAST (send->data);
1811     GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
1812         GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
1813         ", offset %" G_GINT64_FORMAT, buf,
1814         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1815         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
1816
1817     if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts)))
1818       parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
1819
1820     /* iterate output queue an push downstream */
1821     ret = gst_pad_push (parse->srcpad, buf);
1822     send = g_slist_delete_link (send, send);
1823
1824     /* clear any leftover if error */
1825     if (G_UNLIKELY (ret != GST_FLOW_OK)) {
1826       while (send) {
1827         buf = GST_BUFFER_CAST (send->data);
1828         gst_buffer_unref (buf);
1829         send = g_slist_delete_link (send, send);
1830       }
1831     }
1832   }
1833
1834   /* any trailing unused no longer usable (ideally none) */
1835   if (G_UNLIKELY (gst_adapter_available (parse->adapter))) {
1836     GST_DEBUG_OBJECT (parse, "discarding %d trailing bytes",
1837         gst_adapter_available (parse->adapter));
1838     gst_adapter_clear (parse->adapter);
1839   }
1840
1841   return ret;
1842 }
1843
1844 /* small helper that checks whether we have been trying to resync too long */
1845 static inline GstFlowReturn
1846 gst_base_parse_check_sync (GstBaseParse * parse)
1847 {
1848   if (G_UNLIKELY (parse->priv->discont &&
1849           parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
1850     GST_ELEMENT_ERROR (parse, STREAM, DECODE,
1851         ("Failed to parse stream"), (NULL));
1852     return GST_FLOW_ERROR;
1853   }
1854
1855   return GST_FLOW_OK;
1856 }
1857
1858
1859 /**
1860  * gst_base_parse_chain:
1861  * @pad: #GstPad.
1862  * @buffer: #GstBuffer.
1863  *
1864  * Returns: #GstFlowReturn.
1865  */
1866 static GstFlowReturn
1867 gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
1868 {
1869   GstBaseParseClass *bclass;
1870   GstBaseParse *parse;
1871   GstFlowReturn ret = GST_FLOW_OK;
1872   GstBuffer *outbuf = NULL;
1873   GstBuffer *tmpbuf = NULL;
1874   guint fsize = 0;
1875   gint skip = -1;
1876   const guint8 *data;
1877   guint min_size, av;
1878   GstClockTime timestamp;
1879
1880   parse = GST_BASE_PARSE (GST_OBJECT_PARENT (pad));
1881   bclass = GST_BASE_PARSE_GET_CLASS (parse);
1882
1883   if (G_LIKELY (buffer)) {
1884     GST_LOG_OBJECT (parse, "buffer size: %d, offset = %" G_GINT64_FORMAT,
1885         GST_BUFFER_SIZE (buffer), GST_BUFFER_OFFSET (buffer));
1886     if (G_UNLIKELY (parse->priv->passthrough)) {
1887       buffer = gst_buffer_make_metadata_writable (buffer);
1888       return gst_base_parse_push_buffer (parse, buffer);
1889     }
1890     /* upstream feeding us in reverse playback;
1891      * gather each fragment, then process it in single run */
1892     if (parse->segment.rate < 0.0) {
1893       if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
1894         GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
1895         ret = gst_base_parse_process_fragment (parse, FALSE);
1896       }
1897       gst_adapter_push (parse->adapter, buffer);
1898       return ret;
1899     }
1900     gst_adapter_push (parse->adapter, buffer);
1901   }
1902
1903   /* Parse and push as many frames as possible */
1904   /* Stop either when adapter is empty or we are flushing */
1905   while (!parse->priv->flushing) {
1906     tmpbuf = gst_buffer_new ();
1907
1908     /* Synchronization loop */
1909     for (;;) {
1910       min_size = parse->priv->min_frame_size;
1911       av = gst_adapter_available (parse->adapter);
1912
1913       if (G_UNLIKELY (parse->priv->drain)) {
1914         min_size = av;
1915         GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
1916         if (G_UNLIKELY (!min_size)) {
1917           gst_buffer_unref (tmpbuf);
1918           goto done;
1919         }
1920       }
1921
1922       /* Collect at least min_frame_size bytes */
1923       if (av < min_size) {
1924         GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
1925             av);
1926         gst_buffer_unref (tmpbuf);
1927         goto done;
1928       }
1929
1930       /* always pass all available data */
1931       data = gst_adapter_peek (parse->adapter, av);
1932       GST_BUFFER_DATA (tmpbuf) = (guint8 *) data;
1933       GST_BUFFER_SIZE (tmpbuf) = min_size;
1934       GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
1935       GST_BUFFER_FLAG_SET (tmpbuf, GST_MINI_OBJECT_FLAG_READONLY);
1936
1937       if (parse->priv->discont) {
1938         GST_DEBUG_OBJECT (parse, "marking DISCONT");
1939         GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
1940       }
1941
1942       skip = -1;
1943       if (bclass->check_valid_frame (parse, tmpbuf, &fsize, &skip)) {
1944         if (gst_adapter_available (parse->adapter) < fsize) {
1945           GST_DEBUG_OBJECT (parse,
1946               "found valid frame but not enough data available (only %d bytes)",
1947               gst_adapter_available (parse->adapter));
1948           gst_buffer_unref (tmpbuf);
1949           goto done;
1950         }
1951         GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
1952         break;
1953       }
1954       if (skip == -1) {
1955         /* subclass didn't touch this value. By default we skip 1 byte */
1956         skip = 1;
1957       }
1958       if (skip > 0) {
1959         GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
1960         if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
1961           /* reverse playback, and no frames found yet, so we are skipping
1962            * the leading part of a fragment, which may form the tail of
1963            * fragment coming later, hopefully subclass skips efficiently ... */
1964           timestamp = gst_adapter_prev_timestamp (parse->adapter, NULL);
1965           outbuf = gst_adapter_take_buffer (parse->adapter, skip);
1966           outbuf = gst_buffer_make_metadata_writable (outbuf);
1967           GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
1968           parse->priv->buffers_pending =
1969               g_slist_prepend (parse->priv->buffers_pending, outbuf);
1970           outbuf = NULL;
1971         } else {
1972           gst_adapter_flush (parse->adapter, skip);
1973         }
1974         parse->priv->offset += skip;
1975         if (!parse->priv->discont)
1976           parse->priv->sync_offset = parse->priv->offset;
1977         parse->priv->discont = TRUE;
1978       }
1979       /* There is a possibility that subclass set the skip value to zero.
1980          This means that it has probably found a frame but wants to ask
1981          more data (by increasing the min_size) to be sure of this. */
1982       if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
1983         gst_buffer_unref (tmpbuf);
1984         goto done;
1985       }
1986     }
1987     gst_buffer_unref (tmpbuf);
1988     tmpbuf = NULL;
1989
1990     if (skip > 0) {
1991       /* Subclass found the sync, but still wants to skip some data */
1992       GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
1993       gst_adapter_flush (parse->adapter, skip);
1994       parse->priv->offset += skip;
1995     }
1996
1997     /* Grab lock to prevent a race with FLUSH_START handler */
1998     GST_PAD_STREAM_LOCK (parse->srcpad);
1999
2000     /* FLUSH_START event causes the "flushing" flag to be set. In this
2001      * case we can leave the frame pushing loop */
2002     if (parse->priv->flushing) {
2003       GST_PAD_STREAM_UNLOCK (parse->srcpad);
2004       break;
2005     }
2006
2007     /* FIXME: Would it be more efficient to make a subbuffer instead? */
2008     outbuf = gst_adapter_take_buffer (parse->adapter, fsize);
2009     outbuf = gst_buffer_make_metadata_writable (outbuf);
2010
2011     /* Subclass may want to know the data offset */
2012     GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2013     parse->priv->offset += fsize;
2014     GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2015
2016     /* move along with upstream timestamp (if any),
2017      * but interpolate in between */
2018     timestamp = gst_adapter_prev_timestamp (parse->adapter, NULL);
2019     if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2020         (parse->priv->prev_ts != timestamp)) {
2021       parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2022     }
2023
2024     ret = gst_base_parse_handle_and_push_buffer (parse, bclass, outbuf);
2025     GST_PAD_STREAM_UNLOCK (parse->srcpad);
2026
2027     if (ret != GST_FLOW_OK) {
2028       GST_LOG_OBJECT (parse, "push returned %d", ret);
2029       break;
2030     }
2031   }
2032
2033 done:
2034   GST_LOG_OBJECT (parse, "chain leaving");
2035   return ret;
2036 }
2037
2038 /* pull @size bytes at current offset,
2039  * i.e. at least try to and possibly return a shorter buffer if near the end */
2040 static GstFlowReturn
2041 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2042     GstBuffer ** buffer)
2043 {
2044   GstFlowReturn ret = GST_FLOW_OK;
2045
2046   g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2047
2048   /* Caching here actually makes much less difference than one would expect.
2049    * We do it mainly to avoid pulling buffers of 1 byte all the time */
2050   if (parse->priv->cache) {
2051     gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2052     gint cache_size = GST_BUFFER_SIZE (parse->priv->cache);
2053
2054     if (cache_offset <= parse->priv->offset &&
2055         (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2056       *buffer = gst_buffer_create_sub (parse->priv->cache,
2057           parse->priv->offset - cache_offset, size);
2058       GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2059       return GST_FLOW_OK;
2060     }
2061     /* not enough data in the cache, free cache and get a new one */
2062     gst_buffer_unref (parse->priv->cache);
2063     parse->priv->cache = NULL;
2064   }
2065
2066   /* refill the cache */
2067   ret =
2068       gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2069           64 * 1024), &parse->priv->cache);
2070   if (ret != GST_FLOW_OK) {
2071     parse->priv->cache = NULL;
2072     return ret;
2073   }
2074
2075   if (GST_BUFFER_SIZE (parse->priv->cache) >= size) {
2076     *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
2077     GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2078     return GST_FLOW_OK;
2079   }
2080
2081   /* Not possible to get enough data, try a last time with
2082    * requesting exactly the size we need */
2083   gst_buffer_unref (parse->priv->cache);
2084   parse->priv->cache = NULL;
2085
2086   ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2087       &parse->priv->cache);
2088
2089   if (ret != GST_FLOW_OK) {
2090     GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2091     *buffer = NULL;
2092     return ret;
2093   }
2094
2095   if (GST_BUFFER_SIZE (parse->priv->cache) < size) {
2096     GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2097         G_GUINT64_FORMAT ": wanted %u bytes, got %u bytes", parse->priv->offset,
2098         size, GST_BUFFER_SIZE (parse->priv->cache));
2099
2100     *buffer = parse->priv->cache;
2101     parse->priv->cache = NULL;
2102
2103     return GST_FLOW_OK;
2104   }
2105
2106   *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
2107   GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2108
2109   return GST_FLOW_OK;
2110 }
2111
2112 static GstFlowReturn
2113 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2114 {
2115   gint64 offset = 0;
2116   GstClockTime ts = 0;
2117   GstBuffer *buffer;
2118   GstFlowReturn ret;
2119
2120   GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2121       ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2122       parse->priv->last_offset);
2123
2124   if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2125     GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2126         GST_TIME_ARGS (parse->segment.start));
2127     ret = GST_FLOW_UNEXPECTED;
2128     goto exit;
2129   }
2130
2131   /* last fragment started at last_offset / last_ts;
2132    * seek back 10s capped at 1MB */
2133   if (parse->priv->last_ts >= 10 * GST_SECOND)
2134     ts = parse->priv->last_ts - 10 * GST_SECOND;
2135   /* if we are exact now, we will be more so going backwards */
2136   if (parse->priv->exact_position) {
2137     offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2138   } else {
2139     GstFormat dstformat = GST_FORMAT_BYTES;
2140
2141     if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2142             &dstformat, &offset)) {
2143       GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2144     }
2145   }
2146   offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2147       parse->priv->last_offset - 1024);
2148   offset = MAX (0, offset);
2149
2150   GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2151       offset);
2152   parse->priv->offset = offset;
2153
2154   ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2155       &buffer);
2156   if (ret != GST_FLOW_OK)
2157     goto exit;
2158
2159   /* offset will increase again as fragment is processed/parsed */
2160   parse->priv->last_offset = offset;
2161
2162   gst_adapter_push (parse->adapter, buffer);
2163   ret = gst_base_parse_process_fragment (parse, FALSE);
2164   if (ret != GST_FLOW_OK)
2165     goto exit;
2166
2167   /* force previous fragment */
2168   parse->priv->offset = -1;
2169
2170 exit:
2171   return ret;
2172 }
2173
2174 /* PULL mode:
2175  * pull and scan for next frame starting from current offset
2176  * ajusts sync, drain and offset going along */
2177 static GstFlowReturn
2178 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2179     GstBuffer ** buf, gboolean full)
2180 {
2181   GstBuffer *buffer, *outbuf;
2182   GstFlowReturn ret = GST_FLOW_OK;
2183   guint fsize = 0, min_size;
2184   gint skip = 0;
2185
2186   g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
2187
2188   while (TRUE) {
2189
2190     min_size = parse->priv->min_frame_size;
2191
2192     ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2193     if (ret != GST_FLOW_OK)
2194       goto done;
2195
2196     if (parse->priv->discont) {
2197       GST_DEBUG_OBJECT (parse, "marking DISCONT");
2198       GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2199     }
2200
2201     /* if we got a short read, inform subclass we are draining leftover
2202      * and no more is to be expected */
2203     if (GST_BUFFER_SIZE (buffer) < min_size)
2204       parse->priv->drain = TRUE;
2205
2206     skip = -1;
2207     if (klass->check_valid_frame (parse, buffer, &fsize, &skip)) {
2208       parse->priv->drain = FALSE;
2209       GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2210       break;
2211     }
2212     parse->priv->drain = FALSE;
2213     if (skip == -1)
2214       skip = 1;
2215     if (skip > 0) {
2216       GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2217       if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2218         /* reverse playback, and no frames found yet, so we are skipping
2219          * the leading part of a fragment, which may form the tail of
2220          * fragment coming later, hopefully subclass skips efficiently ... */
2221         outbuf = gst_buffer_create_sub (buffer, 0, skip);
2222         parse->priv->buffers_pending =
2223             g_slist_prepend (parse->priv->buffers_pending, outbuf);
2224         outbuf = NULL;
2225       }
2226       parse->priv->offset += skip;
2227       if (!parse->priv->discont)
2228         parse->priv->sync_offset = parse->priv->offset;
2229       parse->priv->discont = TRUE;
2230     }
2231     /* skip == 0 should imply subclass set min_size to need more data ... */
2232     GST_DEBUG_OBJECT (parse, "finding sync...");
2233     gst_buffer_unref (buffer);
2234     if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2235       goto done;
2236     }
2237   }
2238
2239   /* Does the subclass want to skip too? */
2240   if (skip > 0)
2241     parse->priv->offset += skip;
2242   else if (skip < 0)
2243     skip = 0;
2244
2245   if (fsize + skip <= GST_BUFFER_SIZE (buffer)) {
2246     outbuf = gst_buffer_create_sub (buffer, skip, fsize);
2247     GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2248     GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2249     gst_buffer_unref (buffer);
2250   } else {
2251     gst_buffer_unref (buffer);
2252     ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2253     if (ret != GST_FLOW_OK)
2254       goto done;
2255     if (GST_BUFFER_SIZE (outbuf) < fsize) {
2256       gst_buffer_unref (outbuf);
2257       ret = GST_FLOW_UNEXPECTED;
2258     }
2259   }
2260
2261   parse->priv->offset += fsize;
2262
2263   *buf = outbuf;
2264
2265 done:
2266   return ret;
2267 }
2268
2269 /**
2270  * gst_base_parse_loop:
2271  * @pad: GstPad
2272  *
2273  * Loop that is used in pull mode to retrieve data from upstream.
2274  */
2275 static void
2276 gst_base_parse_loop (GstPad * pad)
2277 {
2278   GstBaseParse *parse;
2279   GstBaseParseClass *klass;
2280   GstBuffer *outbuf;
2281   GstFlowReturn ret = GST_FLOW_OK;
2282
2283   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2284   klass = GST_BASE_PARSE_GET_CLASS (parse);
2285
2286   /* reverse playback:
2287    * first fragment (closest to stop time) is handled normally below,
2288    * then we pull in fragments going backwards */
2289   if (parse->segment.rate < 0.0) {
2290     /* check if we jumped back to a previous fragment,
2291      * which is a post-first fragment */
2292     if (parse->priv->offset < 0) {
2293       ret = gst_base_parse_handle_previous_fragment (parse);
2294       goto done;
2295     }
2296   }
2297
2298   ret = gst_base_parse_scan_frame (parse, klass, &outbuf, TRUE);
2299   if (ret != GST_FLOW_OK)
2300     goto done;
2301
2302   /* This always unrefs the outbuf, even if error occurs */
2303   ret = gst_base_parse_handle_and_push_buffer (parse, klass, outbuf);
2304
2305   /* eat expected eos signalling past segment in reverse playback */
2306   if (parse->segment.rate < 0.0 && ret == GST_FLOW_UNEXPECTED &&
2307       parse->segment.last_stop >= parse->segment.stop) {
2308     GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2309     /* push what was accumulated during loop run */
2310     gst_base_parse_process_fragment (parse, TRUE);
2311     /* force previous fragment */
2312     parse->priv->offset = -1;
2313     ret = GST_FLOW_OK;
2314   }
2315
2316 done:
2317   if (ret == GST_FLOW_UNEXPECTED)
2318     goto eos;
2319   else if (ret != GST_FLOW_OK)
2320     goto pause;
2321
2322   gst_object_unref (parse);
2323   return;
2324
2325   /* ERRORS */
2326 eos:
2327   {
2328     ret = GST_FLOW_UNEXPECTED;
2329     GST_DEBUG_OBJECT (parse, "eos");
2330     /* fall-through */
2331   }
2332 pause:
2333   {
2334     gboolean push_eos = FALSE;
2335
2336     GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2337         gst_flow_get_name (ret));
2338     gst_pad_pause_task (parse->sinkpad);
2339
2340     if (ret == GST_FLOW_UNEXPECTED) {
2341       /* handle end-of-stream/segment */
2342       if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2343         gint64 stop;
2344
2345         if ((stop = parse->segment.stop) == -1)
2346           stop = parse->segment.duration;
2347
2348         GST_DEBUG_OBJECT (parse, "sending segment_done");
2349
2350         gst_element_post_message
2351             (GST_ELEMENT_CAST (parse),
2352             gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2353                 GST_FORMAT_TIME, stop));
2354       } else {
2355         /* If we STILL have zero frames processed, fire an error */
2356         if (parse->priv->framecount == 0) {
2357           GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2358               ("No valid frames found before end of stream"), (NULL));
2359         }
2360         push_eos = TRUE;
2361       }
2362     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
2363       /* for fatal errors we post an error message, wrong-state is
2364        * not fatal because it happens due to flushes and only means
2365        * that we should stop now. */
2366       GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2367           ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2368       push_eos = TRUE;
2369     }
2370     if (push_eos) {
2371       /* newsegment before eos */
2372       if (parse->pending_segment) {
2373         gst_pad_push_event (parse->srcpad, parse->pending_segment);
2374         parse->pending_segment = NULL;
2375       }
2376       gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2377     }
2378     gst_object_unref (parse);
2379   }
2380 }
2381
2382
2383 /**
2384  * gst_base_parse_sink_activate:
2385  * @sinkpad: #GstPad to be activated.
2386  *
2387  * Returns: TRUE if activation succeeded.
2388  */
2389 static gboolean
2390 gst_base_parse_sink_activate (GstPad * sinkpad)
2391 {
2392   GstBaseParse *parse;
2393   gboolean result = TRUE;
2394
2395   parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2396
2397   GST_DEBUG_OBJECT (parse, "sink activate");
2398
2399   if (gst_pad_check_pull_range (sinkpad)) {
2400     GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2401     result = gst_pad_activate_pull (sinkpad, TRUE);
2402   } else {
2403     GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
2404     result = gst_pad_activate_push (sinkpad, TRUE);
2405   }
2406
2407   GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
2408   gst_object_unref (parse);
2409   return result;
2410 }
2411
2412
2413 /**
2414  * gst_base_parse_activate:
2415  * @parse: #GstBaseParse.
2416  * @active: TRUE if element will be activated, FALSE if deactivated.
2417  *
2418  * Returns: TRUE if the operation succeeded.
2419  */
2420 static gboolean
2421 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
2422 {
2423   GstBaseParseClass *klass;
2424   gboolean result = FALSE;
2425
2426   GST_DEBUG_OBJECT (parse, "activate");
2427
2428   klass = GST_BASE_PARSE_GET_CLASS (parse);
2429
2430   if (active) {
2431     if (parse->priv->pad_mode == GST_ACTIVATE_NONE && klass->start)
2432       result = klass->start (parse);
2433   } else {
2434     /* We must make sure streaming has finished before resetting things
2435      * and calling the ::stop vfunc */
2436     GST_PAD_STREAM_LOCK (parse->sinkpad);
2437     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2438
2439     if (parse->priv->pad_mode != GST_ACTIVATE_NONE && klass->stop)
2440       result = klass->stop (parse);
2441
2442     parse->priv->pad_mode = GST_ACTIVATE_NONE;
2443   }
2444   GST_DEBUG_OBJECT (parse, "activate: %d", result);
2445   return result;
2446 }
2447
2448
2449 /**
2450  * gst_base_parse_sink_activate_push:
2451  * @pad: #GstPad to be (de)activated.
2452  * @active: TRUE when activating, FALSE when deactivating.
2453  *
2454  * Returns: TRUE if (de)activation succeeded.
2455  */
2456 static gboolean
2457 gst_base_parse_sink_activate_push (GstPad * pad, gboolean active)
2458 {
2459   gboolean result = TRUE;
2460   GstBaseParse *parse;
2461
2462   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2463
2464   GST_DEBUG_OBJECT (parse, "sink activate push");
2465
2466   result = gst_base_parse_activate (parse, active);
2467
2468   if (result)
2469     parse->priv->pad_mode = active ? GST_ACTIVATE_PUSH : GST_ACTIVATE_NONE;
2470
2471   GST_DEBUG_OBJECT (parse, "sink activate push: %d", result);
2472
2473   gst_object_unref (parse);
2474   return result;
2475 }
2476
2477
2478 /**
2479  * gst_base_parse_sink_activate_pull:
2480  * @sinkpad: #GstPad to be (de)activated.
2481  * @active: TRUE when activating, FALSE when deactivating.
2482  *
2483  * Returns: TRUE if (de)activation succeeded.
2484  */
2485 static gboolean
2486 gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
2487 {
2488   gboolean result = FALSE;
2489   GstBaseParse *parse;
2490
2491   parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2492
2493   GST_DEBUG_OBJECT (parse, "activate pull");
2494
2495   result = gst_base_parse_activate (parse, active);
2496
2497   if (result) {
2498     if (active) {
2499       parse->pending_segment = gst_event_new_new_segment (FALSE,
2500           parse->segment.rate, parse->segment.format,
2501           parse->segment.start, parse->segment.stop, parse->segment.last_stop);
2502       result &= gst_pad_start_task (sinkpad,
2503           (GstTaskFunction) gst_base_parse_loop, sinkpad);
2504     } else {
2505       result &= gst_pad_stop_task (sinkpad);
2506     }
2507   }
2508
2509   if (result)
2510     parse->priv->pad_mode = active ? GST_ACTIVATE_PULL : GST_ACTIVATE_NONE;
2511
2512   GST_DEBUG_OBJECT (parse, "sink activate pull: %d", result);
2513
2514   gst_object_unref (parse);
2515   return result;
2516 }
2517
2518
2519 /**
2520  * gst_base_parse_set_duration:
2521  * @parse: #GstBaseParse.
2522  * @fmt: #GstFormat.
2523  * @duration: duration value.
2524  *
2525  * Sets the duration of the currently playing media. Subclass can use this
2526  * when it is able to determine duration and/or notices a change in the media
2527  * duration.  Alternatively, if @interval is non-zero (default), then stream
2528  * duration is determined based on estimated bitrate, and updated every @interval
2529  * frames. */
2530 void
2531 gst_base_parse_set_duration (GstBaseParse * parse,
2532     GstFormat fmt, gint64 duration, gint interval)
2533 {
2534   g_return_if_fail (parse != NULL);
2535
2536   if (parse->priv->upstream_has_duration) {
2537     GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
2538     goto exit;
2539   }
2540
2541   if (duration != parse->priv->duration) {
2542     GstMessage *m;
2543
2544     m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
2545     gst_element_post_message (GST_ELEMENT (parse), m);
2546
2547     /* TODO: what about duration tag? */
2548   }
2549   parse->priv->duration = duration;
2550   parse->priv->duration_fmt = fmt;
2551   GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
2552   if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
2553     if (interval != 0) {
2554       GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
2555       interval = 0;
2556     }
2557   }
2558   GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
2559   parse->priv->update_interval = interval;
2560 exit:
2561   return;
2562 }
2563
2564 /**
2565  * gst_base_parse_set_seek:
2566  * @parse: #GstBaseParse.
2567  * @seek: #GstBaseParseSeekable.
2568  * @abitrate: average bitrate.
2569  *
2570  * Sets whether and how the media is seekable (in time).
2571  * Also optionally provides average bitrate detected in media (if non-zero),
2572  * e.g. based on metadata, as it will be posted to the application.
2573  *
2574  * By default, announced average bitrate is estimated, and seekability is assumed
2575  * possible based on estimated bitrate.
2576  */
2577 void
2578 gst_base_parse_set_seek (GstBaseParse * parse,
2579     GstBaseParseSeekable seek, guint bitrate)
2580 {
2581   parse->priv->seekable = seek;
2582   parse->priv->bitrate = bitrate;
2583   GST_DEBUG_OBJECT (parse, "seek %d, bitrate %d", seek, bitrate);
2584 }
2585
2586
2587 /**
2588  * gst_base_parse_set_min_frame_size:
2589  * @parse: #GstBaseParse.
2590  * @min_size: Minimum size of the data that this base class should give to
2591  *            subclass.
2592  *
2593  * Subclass can use this function to tell the base class that it needs to
2594  * give at least #min_size buffers.
2595  */
2596 void
2597 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
2598 {
2599   g_return_if_fail (parse != NULL);
2600
2601   parse->priv->min_frame_size = min_size;
2602   GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
2603 }
2604
2605 /**
2606  * gst_base_parse_set_passthrough:
2607  * @parse: the #GstBaseParse to set
2608  * @passthrough: boolean indicating passthrough mode.
2609  *
2610  * Set passthrough mode for this parser.  If operating in passthrough,
2611  * incoming buffers are pushed through unmodified.
2612  */
2613 void
2614 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
2615 {
2616   g_return_if_fail (parse != NULL);
2617
2618   parse->priv->passthrough = passthrough;
2619   GST_LOG_OBJECT (parse, "set passthrough: %d", passthrough);
2620 }
2621
2622 /**
2623  * gst_base_parse_set_frame_props:
2624  * @parse: the #GstBaseParse to set
2625  * @fps_num: frames per second (numerator).
2626  * @fps_den: frames per second (denominator).
2627  * @lead_in: frames needed before a segment for subsequent decode
2628  * @lead_out: frames needed after a segment
2629  *
2630  * If frames per second is configured, parser can take care of buffer duration
2631  * and timestamping.  When performing segment clipping, or seeking to a specific
2632  * location, a corresponding decoder might need an initial @lead_in and a
2633  * following @lead_out number of frames to ensure the desired segment is
2634  * entirely filled upon decoding.
2635  */
2636 void
2637 gst_base_parse_set_frame_props (GstBaseParse * parse, guint fps_num,
2638     guint fps_den, guint lead_in, guint lead_out)
2639 {
2640   g_return_if_fail (parse != NULL);
2641
2642   parse->priv->fps_num = fps_num;
2643   parse->priv->fps_den = fps_den;
2644   if (!fps_num || !fps_den) {
2645     GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
2646         fps_num, fps_den);
2647     fps_num = fps_den = 0;
2648     parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
2649     parse->priv->lead_in = parse->priv->lead_out = 0;
2650     parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
2651   } else {
2652     parse->priv->frame_duration =
2653         gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
2654     parse->priv->lead_in = lead_in;
2655     parse->priv->lead_out = lead_out;
2656     parse->priv->lead_in_ts =
2657         gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
2658     parse->priv->lead_out_ts =
2659         gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
2660   }
2661   GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
2662       fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
2663   GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
2664       "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
2665       lead_in, parse->priv->lead_in_ts / GST_MSECOND,
2666       lead_out, parse->priv->lead_out_ts / GST_MSECOND);
2667 }
2668
2669 /**
2670  * gst_base_parse_get_sync:
2671  * @parse: the #GstBaseParse to query
2672  *
2673  * Returns: TRUE if parser is considered 'in sync'.  That is, frames have been
2674  * continuously successfully parsed and pushed.
2675  */
2676 gboolean
2677 gst_base_parse_get_sync (GstBaseParse * parse)
2678 {
2679   gboolean ret;
2680
2681   g_return_val_if_fail (parse != NULL, FALSE);
2682
2683   /* losing sync is pretty much a discont (and vice versa), no ? */
2684   ret = !parse->priv->discont;
2685
2686   GST_DEBUG_OBJECT (parse, "sync: %d", ret);
2687   return ret;
2688 }
2689
2690 /**
2691  * gst_base_parse_get_drain:
2692  * @parse: the #GstBaseParse to query
2693  *
2694  * Returns: TRUE if parser is currently 'draining'.  That is, leftover data
2695  * (e.g. in FLUSH or EOS situation) is being parsed.
2696  */
2697 gboolean
2698 gst_base_parse_get_drain (GstBaseParse * parse)
2699 {
2700   gboolean ret;
2701
2702   g_return_val_if_fail (parse != NULL, FALSE);
2703
2704   /* losing sync is pretty much a discont (and vice versa), no ? */
2705   ret = parse->priv->drain;
2706
2707   GST_DEBUG_OBJECT (parse, "drain: %d", ret);
2708   return ret;
2709 }
2710
2711 static gboolean
2712 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
2713     GstClockTime * duration)
2714 {
2715   gboolean res = FALSE;
2716
2717   g_return_val_if_fail (duration != NULL, FALSE);
2718
2719   *duration = GST_CLOCK_TIME_NONE;
2720   if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
2721     GST_LOG_OBJECT (parse, "using provided duration");
2722     *duration = parse->priv->duration;
2723     res = TRUE;
2724   } else if (parse->priv->duration != -1) {
2725     GST_LOG_OBJECT (parse, "converting provided duration");
2726     res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
2727         parse->priv->duration, format, (gint64 *) duration);
2728   } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
2729     GST_LOG_OBJECT (parse, "using estimated duration");
2730     *duration = parse->priv->estimated_duration;
2731     res = TRUE;
2732   }
2733
2734   GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
2735       GST_TIME_ARGS (*duration));
2736   return res;
2737 }
2738
2739 /**
2740  * gst_base_parse_get_querytypes:
2741  * @pad: GstPad
2742  *
2743  * Returns: A table of #GstQueryType items describing supported query types.
2744  */
2745 static const GstQueryType *
2746 gst_base_parse_get_querytypes (GstPad * pad)
2747 {
2748   static const GstQueryType list[] = {
2749     GST_QUERY_POSITION,
2750     GST_QUERY_DURATION,
2751     GST_QUERY_FORMATS,
2752     GST_QUERY_SEEKING,
2753     GST_QUERY_CONVERT,
2754     0
2755   };
2756
2757   return list;
2758 }
2759
2760
2761 /**
2762  * gst_base_parse_query:
2763  * @pad: #GstPad.
2764  * @query: #GstQuery.
2765  *
2766  * Returns: TRUE on success.
2767  */
2768 static gboolean
2769 gst_base_parse_query (GstPad * pad, GstQuery * query)
2770 {
2771   GstBaseParse *parse;
2772   gboolean res = FALSE;
2773
2774   parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
2775
2776   GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
2777
2778   switch (GST_QUERY_TYPE (query)) {
2779     case GST_QUERY_POSITION:
2780     {
2781       gint64 dest_value;
2782       GstFormat format;
2783
2784       GST_DEBUG_OBJECT (parse, "position query");
2785       gst_query_parse_position (query, &format, NULL);
2786
2787       GST_OBJECT_LOCK (parse);
2788       if (format == GST_FORMAT_BYTES) {
2789         dest_value = parse->priv->offset;
2790         res = TRUE;
2791       } else if (format == parse->segment.format &&
2792           GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop)) {
2793         dest_value = parse->segment.last_stop;
2794         res = TRUE;
2795       }
2796       GST_OBJECT_UNLOCK (parse);
2797
2798       if (res)
2799         gst_query_set_position (query, format, dest_value);
2800       else {
2801         res = gst_pad_query_default (pad, query);
2802         if (!res) {
2803           /* no precise result, upstream no idea either, then best estimate */
2804           /* priv->offset is updated in both PUSH/PULL modes */
2805           res = gst_base_parse_convert (parse,
2806               GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
2807         }
2808       }
2809       break;
2810     }
2811     case GST_QUERY_DURATION:
2812     {
2813       GstFormat format;
2814       GstClockTime duration;
2815
2816       GST_DEBUG_OBJECT (parse, "duration query");
2817       gst_query_parse_duration (query, &format, NULL);
2818
2819       /* consult upstream */
2820       res = gst_pad_query_default (pad, query);
2821
2822       /* otherwise best estimate from us */
2823       if (!res) {
2824         res = gst_base_parse_get_duration (parse, format, &duration);
2825         if (res)
2826           gst_query_set_duration (query, format, duration);
2827       }
2828       break;
2829     }
2830     case GST_QUERY_SEEKING:
2831     {
2832       GstFormat fmt;
2833       GstClockTime duration = GST_CLOCK_TIME_NONE;
2834       gboolean seekable = FALSE;
2835
2836       GST_DEBUG_OBJECT (parse, "seeking query");
2837       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
2838
2839       /* consult upstream */
2840       res = gst_pad_query_default (pad, query);
2841
2842       /* we may be able to help if in TIME */
2843       if (fmt == GST_FORMAT_TIME &&
2844           parse->priv->seekable > GST_BASE_PARSE_SEEK_NONE) {
2845         gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
2846         /* already OK if upstream takes care */
2847         GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
2848             res, seekable);
2849         if (!(res && seekable)) {
2850           if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
2851               || duration == -1) {
2852             seekable = FALSE;
2853           } else {
2854             seekable = parse->priv->upstream_seekable;
2855             GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
2856                 seekable);
2857           }
2858           gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
2859           res = TRUE;
2860         }
2861       }
2862       break;
2863     }
2864     case GST_QUERY_FORMATS:
2865       gst_query_set_formatsv (query, 3, fmtlist);
2866       res = TRUE;
2867       break;
2868     case GST_QUERY_CONVERT:
2869     {
2870       GstFormat src_format, dest_format;
2871       gint64 src_value, dest_value;
2872
2873       gst_query_parse_convert (query, &src_format, &src_value,
2874           &dest_format, &dest_value);
2875
2876       res = gst_base_parse_convert (parse, src_format, src_value,
2877           dest_format, &dest_value);
2878       if (res) {
2879         gst_query_set_convert (query, src_format, src_value,
2880             dest_format, dest_value);
2881       }
2882       break;
2883     }
2884     default:
2885       res = gst_pad_query_default (pad, query);
2886       break;
2887   }
2888   return res;
2889 }
2890
2891 /* scans for a cluster start from @pos,
2892  * return GST_FLOW_OK and frame position/time in @pos/@time if found */
2893 static GstFlowReturn
2894 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
2895     GstClockTime * time, GstClockTime * duration)
2896 {
2897   GstBaseParseClass *klass;
2898   gint64 orig_offset;
2899   gboolean orig_drain, orig_discont;
2900   GstFlowReturn ret = GST_FLOW_OK;
2901   GstBuffer *buf = NULL;
2902
2903   g_return_val_if_fail (GST_FLOW_ERROR, pos != NULL);
2904   g_return_val_if_fail (GST_FLOW_ERROR, time != NULL);
2905   g_return_val_if_fail (GST_FLOW_ERROR, duration != NULL);
2906
2907   klass = GST_BASE_PARSE_GET_CLASS (parse);
2908
2909   *time = GST_CLOCK_TIME_NONE;
2910   *duration = GST_CLOCK_TIME_NONE;
2911
2912   /* save state */
2913   orig_offset = parse->priv->offset;
2914   orig_discont = parse->priv->discont;
2915   orig_drain = parse->priv->drain;
2916
2917   GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
2918       " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
2919
2920   /* jump elsewhere and locate next frame */
2921   parse->priv->offset = *pos;
2922   ret = gst_base_parse_scan_frame (parse, klass, &buf, FALSE);
2923   if (ret != GST_FLOW_OK)
2924     goto done;
2925
2926   GST_LOG_OBJECT (parse,
2927       "peek parsing frame at offset %" G_GUINT64_FORMAT
2928       " (%#" G_GINT64_MODIFIER "x) of size %d",
2929       GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf), GST_BUFFER_SIZE (buf));
2930
2931   /* get offset first, subclass parsing might dump other stuff in there */
2932   *pos = GST_BUFFER_OFFSET (buf);
2933   ret = klass->parse_frame (parse, buf);
2934
2935   /* but it should provide proper time */
2936   *time = GST_BUFFER_TIMESTAMP (buf);
2937   *duration = GST_BUFFER_DURATION (buf);
2938   gst_buffer_unref (buf);
2939
2940   GST_LOG_OBJECT (parse,
2941       "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
2942       GST_TIME_ARGS (*time), *pos);
2943
2944 done:
2945   /* restore state */
2946   parse->priv->offset = orig_offset;
2947   parse->priv->discont = orig_discont;
2948   parse->priv->drain = orig_drain;
2949
2950   return ret;
2951 }
2952
2953 /* bisect and scan through file for frame starting before @time,
2954  * returns OK and @time/@offset if found, NONE and/or error otherwise
2955  * If @time == G_MAXINT64, scan for duration ( == last frame) */
2956 static GstFlowReturn
2957 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
2958     gint64 * _offset)
2959 {
2960   GstFlowReturn ret = GST_FLOW_OK;
2961   gint64 lpos, hpos, newpos;
2962   GstClockTime time, ltime, htime, newtime, dur;
2963   gboolean cont = TRUE;
2964   const GstClockTime tolerance = TARGET_DIFFERENCE;
2965   const guint chunk = 4 * 1024;
2966
2967   g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
2968   g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
2969
2970   /* TODO also make keyframe aware if useful some day */
2971
2972   time = *_time;
2973
2974   /* basic cases */
2975   if (time == 0) {
2976     *_offset = 0;
2977     return GST_FLOW_OK;
2978   }
2979
2980   if (time == -1) {
2981     *_offset = -1;
2982     return GST_FLOW_OK;
2983   }
2984
2985   /* do not know at first */
2986   *_offset = -1;
2987   *_time = GST_CLOCK_TIME_NONE;
2988
2989   /* need initial positions; start and end */
2990   lpos = parse->priv->first_frame_offset;
2991   ltime = parse->priv->first_frame_ts;
2992   htime = parse->priv->duration;
2993   hpos = parse->priv->upstream_size;
2994
2995   /* check preconditions are satisfied;
2996    * start and end are needed, except for special case where we scan for
2997    * last frame to determine duration */
2998   if (parse->priv->pad_mode != GST_ACTIVATE_PULL || !hpos ||
2999       !GST_CLOCK_TIME_IS_VALID (ltime) ||
3000       (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3001     return GST_FLOW_OK;
3002   }
3003
3004   /* shortcut cases */
3005   if (time < ltime) {
3006     goto exit;
3007   } else if (time < ltime + tolerance) {
3008     *_offset = lpos;
3009     *_time = ltime;
3010     goto exit;
3011   } else if (time >= htime) {
3012     *_offset = hpos;
3013     *_time = htime;
3014     goto exit;
3015   }
3016
3017   while (htime > ltime && cont) {
3018     GST_LOG_OBJECT (parse,
3019         "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3020         GST_TIME_ARGS (ltime));
3021     GST_LOG_OBJECT (parse,
3022         "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3023         GST_TIME_ARGS (htime));
3024     if (G_UNLIKELY (time == G_MAXINT64)) {
3025       newpos = hpos;
3026     } else if (G_LIKELY (hpos > lpos)) {
3027       newpos =
3028           gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3029           lpos - chunk;
3030     } else {
3031       /* should mean lpos == hpos, since lpos <= hpos is invariant */
3032       newpos = lpos;
3033       /* we check this case once, but not forever, so break loop */
3034       cont = FALSE;
3035     }
3036
3037     /* ensure */
3038     newpos = CLAMP (newpos, lpos, hpos);
3039     GST_LOG_OBJECT (parse,
3040         "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3041         GST_TIME_ARGS (time), newpos);
3042
3043     ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3044     if (ret == GST_FLOW_UNEXPECTED) {
3045       /* heuristic HACK */
3046       hpos = MAX (lpos, hpos - chunk);
3047       continue;
3048     } else if (ret != GST_FLOW_OK) {
3049       goto exit;
3050     }
3051
3052     if (newtime == -1 || newpos == -1) {
3053       GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3054       break;
3055     }
3056
3057     if (G_UNLIKELY (time == G_MAXINT64)) {
3058       *_offset = newpos;
3059       *_time = newtime;
3060       if (GST_CLOCK_TIME_IS_VALID (dur))
3061         *_time += dur;
3062       break;
3063     } else if (newtime > time) {
3064       /* overshoot */
3065       hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3066       htime = newtime;
3067     } else if (newtime + tolerance > time) {
3068       /* close enough undershoot */
3069       *_offset = newpos;
3070       *_time = newtime;
3071       break;
3072     } else if (newtime < ltime) {
3073       /* so a position beyond lpos resulted in earlier time than ltime ... */
3074       GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3075       break;
3076     } else {
3077       /* undershoot too far */
3078       newpos += newpos == lpos ? chunk : 0;
3079       lpos = CLAMP (newpos, lpos, hpos);
3080       ltime = newtime;
3081     }
3082   }
3083
3084 exit:
3085   GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3086       GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3087   return ret;
3088 }
3089
3090 static gint64
3091 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3092     gboolean before, GstClockTime * _ts)
3093 {
3094   gint64 bytes = 0, ts = 0;
3095   GstIndexEntry *entry = NULL;
3096
3097   if (time == GST_CLOCK_TIME_NONE) {
3098     ts = time;
3099     bytes = -1;
3100     goto exit;
3101   }
3102
3103   GST_OBJECT_LOCK (parse);
3104   if (parse->priv->index) {
3105     /* Let's check if we have an index entry for that time */
3106     entry = gst_index_get_assoc_entry (parse->priv->index,
3107         parse->priv->index_id,
3108         before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3109         GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3110   }
3111
3112   if (entry) {
3113     gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3114     gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3115
3116     GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3117         " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3118         GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3119   } else {
3120     GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3121         GST_TIME_ARGS (time));
3122     if (!before) {
3123       bytes = -1;
3124       ts = GST_CLOCK_TIME_NONE;
3125     }
3126   }
3127   GST_OBJECT_UNLOCK (parse);
3128
3129 exit:
3130   if (_ts)
3131     *_ts = ts;
3132
3133   return bytes;
3134 }
3135
3136
3137 /**
3138  * gst_base_parse_handle_seek:
3139  * @parse: #GstBaseParse.
3140  * @event: #GstEvent.
3141  *
3142  * Returns: TRUE if seek succeeded.
3143  */
3144 static gboolean
3145 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3146 {
3147   gdouble rate;
3148   GstFormat format;
3149   GstSeekFlags flags;
3150   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3151   gboolean flush, update, res = TRUE, accurate;
3152   gint64 cur, stop, seekpos, seekstop;
3153   GstSegment seeksegment = { 0, };
3154   GstFormat dstformat;
3155   GstClockTime start_ts;
3156
3157   gst_event_parse_seek (event, &rate, &format, &flags,
3158       &cur_type, &cur, &stop_type, &stop);
3159
3160   GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3161       "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3162       GST_TIME_FORMAT, gst_format_get_name (format), rate,
3163       cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3164
3165   /* no negative rates in push mode */
3166   if (rate < 0.0 && parse->priv->pad_mode == GST_ACTIVATE_PUSH)
3167     goto negative_rate;
3168
3169   if (cur_type != GST_SEEK_TYPE_SET ||
3170       (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3171     goto wrong_type;
3172
3173   /* For any format other than TIME, see if upstream handles
3174    * it directly or fail. For TIME, try upstream, but do it ourselves if
3175    * it fails upstream */
3176   if (format != GST_FORMAT_TIME) {
3177     /* default action delegates to upstream */
3178     return FALSE;
3179   } else {
3180     gst_event_ref (event);
3181     if (gst_pad_push_event (parse->sinkpad, event)) {
3182       return TRUE;
3183     }
3184   }
3185
3186   /* get flush flag */
3187   flush = flags & GST_SEEK_FLAG_FLUSH;
3188
3189   /* copy segment, we need this because we still need the old
3190    * segment when we close the current segment. */
3191   memcpy (&seeksegment, &parse->segment, sizeof (GstSegment));
3192
3193   GST_DEBUG_OBJECT (parse, "configuring seek");
3194   gst_segment_set_seek (&seeksegment, rate, format, flags,
3195       cur_type, cur, stop_type, stop, &update);
3196
3197   /* accurate seeking implies seek tables are used to obtain position,
3198    * and the requested segment is maintained exactly, not adjusted any way */
3199   accurate = flags & GST_SEEK_FLAG_ACCURATE;
3200
3201   /* maybe we can be accurate for (almost) free */
3202   gst_base_parse_find_offset (parse, seeksegment.last_stop, TRUE, &start_ts);
3203   if (seeksegment.last_stop <= start_ts + TARGET_DIFFERENCE) {
3204     GST_DEBUG_OBJECT (parse, "accurate seek possible");
3205     accurate = TRUE;
3206   }
3207   if (accurate) {
3208     GstClockTime startpos = seeksegment.last_stop;
3209
3210     /* accurate requested, so ... seek a bit before target */
3211     if (startpos < parse->priv->lead_in_ts)
3212       startpos = 0;
3213     else
3214       startpos -= parse->priv->lead_in_ts;
3215     seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3216     seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3217         NULL);
3218   } else {
3219     start_ts = seeksegment.last_stop;
3220     dstformat = GST_FORMAT_BYTES;
3221     if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.last_stop,
3222             &dstformat, &seekpos))
3223       goto convert_failed;
3224     if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3225             &dstformat, &seekstop))
3226       goto convert_failed;
3227   }
3228
3229   GST_DEBUG_OBJECT (parse,
3230       "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3231       start_ts, seekpos);
3232   GST_DEBUG_OBJECT (parse,
3233       "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3234       seeksegment.stop, seekstop);
3235
3236   if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
3237     gint64 last_stop;
3238
3239     GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3240
3241     if (flush) {
3242       if (parse->srcpad) {
3243         GST_DEBUG_OBJECT (parse, "sending flush start");
3244         gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3245         /* unlock upstream pull_range */
3246         gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3247       }
3248     } else {
3249       gst_pad_pause_task (parse->sinkpad);
3250     }
3251
3252     /* we should now be able to grab the streaming thread because we stopped it
3253      * with the above flush/pause code */
3254     GST_PAD_STREAM_LOCK (parse->sinkpad);
3255
3256     /* save current position */
3257     last_stop = parse->segment.last_stop;
3258     GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3259         last_stop);
3260
3261     /* now commit to new position */
3262
3263     /* prepare for streaming again */
3264     if (flush) {
3265       GST_DEBUG_OBJECT (parse, "sending flush stop");
3266       gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop ());
3267       gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop ());
3268       gst_base_parse_clear_queues (parse);
3269     } else {
3270       if (parse->close_segment)
3271         gst_event_unref (parse->close_segment);
3272
3273       parse->close_segment = gst_event_new_new_segment (TRUE,
3274           parse->segment.rate, parse->segment.format,
3275           parse->segment.accum, parse->segment.last_stop, parse->segment.accum);
3276
3277       /* keep track of our last_stop */
3278       seeksegment.accum = parse->segment.last_stop;
3279
3280       GST_DEBUG_OBJECT (parse, "Created close seg format %d, "
3281           "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3282           ", pos = %" GST_TIME_FORMAT, format,
3283           GST_TIME_ARGS (parse->segment.accum),
3284           GST_TIME_ARGS (parse->segment.last_stop),
3285           GST_TIME_ARGS (parse->segment.accum));
3286     }
3287
3288     memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3289
3290     /* store the newsegment event so it can be sent from the streaming thread. */
3291     if (parse->pending_segment)
3292       gst_event_unref (parse->pending_segment);
3293
3294     /* This will be sent later in _loop() */
3295     parse->pending_segment =
3296         gst_event_new_new_segment (FALSE, parse->segment.rate,
3297         parse->segment.format, parse->segment.start, parse->segment.stop,
3298         parse->segment.start);
3299
3300     GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3301         "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3302         ", pos = %" GST_TIME_FORMAT, format,
3303         GST_TIME_ARGS (parse->segment.start),
3304         GST_TIME_ARGS (parse->segment.stop),
3305         GST_TIME_ARGS (parse->segment.start));
3306
3307     /* one last chance in pull mode to stay accurate;
3308      * maybe scan and subclass can find where to go */
3309     if (!accurate) {
3310       gint64 scanpos;
3311       GstClockTime ts = seeksegment.last_stop;
3312
3313       gst_base_parse_locate_time (parse, &ts, &scanpos);
3314       if (scanpos >= 0) {
3315         accurate = TRUE;
3316         seekpos = scanpos;
3317         /* running collected index now consists of several intervals,
3318          * so optimized check no longer possible */
3319         parse->priv->index_last_valid = FALSE;
3320         parse->priv->index_last_offset = 0;
3321         parse->priv->index_last_ts = 0;
3322       }
3323     }
3324
3325     /* mark discont if we are going to stream from another position. */
3326     if (seekpos != parse->priv->offset) {
3327       GST_DEBUG_OBJECT (parse,
3328           "mark DISCONT, we did a seek to another position");
3329       parse->priv->offset = seekpos;
3330       parse->priv->last_offset = seekpos;
3331       parse->priv->seen_keyframe = FALSE;
3332       parse->priv->discont = TRUE;
3333       parse->priv->next_ts = start_ts;
3334       parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3335       parse->priv->sync_offset = seekpos;
3336       parse->priv->exact_position = accurate;
3337     }
3338
3339     /* Start streaming thread if paused */
3340     gst_pad_start_task (parse->sinkpad,
3341         (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3342
3343     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3344   } else {
3345     GstEvent *new_event;
3346     GstBaseParseSeek *seek;
3347
3348     /* The only thing we need to do in PUSH-mode is to send the
3349        seek event (in bytes) to upstream. Segment / flush handling happens
3350        in corresponding src event handlers */
3351     GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3352     if (seekstop >= 0 && seekpos <= seekpos)
3353       seekstop = seekpos;
3354     new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flush,
3355         GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3356
3357     /* store segment info so its precise details can be reconstructed when
3358      * receiving newsegment;
3359      * this matters for all details when accurate seeking,
3360      * is most useful to preserve NONE stop time otherwise */
3361     seek = g_new0 (GstBaseParseSeek, 1);
3362     seek->segment = seeksegment;
3363     seek->accurate = accurate;
3364     seek->offset = seekpos;
3365     seek->start_ts = start_ts;
3366     GST_OBJECT_LOCK (parse);
3367     /* less optimal, but preserves order */
3368     parse->priv->pending_seeks =
3369         g_slist_append (parse->priv->pending_seeks, seek);
3370     GST_OBJECT_UNLOCK (parse);
3371
3372     res = gst_pad_push_event (parse->sinkpad, new_event);
3373
3374     if (!res) {
3375       GST_OBJECT_LOCK (parse);
3376       parse->priv->pending_seeks =
3377           g_slist_remove (parse->priv->pending_seeks, seek);
3378       GST_OBJECT_UNLOCK (parse);
3379       g_free (seek);
3380     }
3381   }
3382
3383 done:
3384   return res;
3385
3386   /* ERRORS */
3387 negative_rate:
3388   {
3389     GST_DEBUG_OBJECT (parse, "negative playback rates are not supported yet.");
3390     res = FALSE;
3391     goto done;
3392   }
3393 wrong_type:
3394   {
3395     GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3396     res = FALSE;
3397     goto done;
3398   }
3399 convert_failed:
3400   {
3401     GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3402     res = FALSE;
3403     goto done;
3404   }
3405 }
3406
3407 /**
3408  * gst_base_parse_handle_tag:
3409  * @parse: #GstBaseParse.
3410  * @event: #GstEvent.
3411  *
3412  * Checks if bitrates are available from upstream tags so that we don't
3413  * override them later
3414  */
3415 static void
3416 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
3417 {
3418   GstTagList *taglist = NULL;
3419   guint tmp;
3420
3421   gst_event_parse_tag (event, &taglist);
3422
3423   if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
3424     GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
3425     parse->priv->post_min_bitrate = FALSE;
3426   }
3427   if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
3428     GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
3429     parse->priv->post_avg_bitrate = FALSE;
3430   }
3431   if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
3432     GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
3433     parse->priv->post_max_bitrate = FALSE;
3434   }
3435 }
3436
3437 /**
3438  * gst_base_parse_sink_setcaps:
3439  * @pad: #GstPad.
3440  * @caps: #GstCaps.
3441  *
3442  * Returns: TRUE if caps were accepted.
3443  */
3444 static gboolean
3445 gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps)
3446 {
3447   GstBaseParse *parse;
3448   GstBaseParseClass *klass;
3449   gboolean res = TRUE;
3450
3451   parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3452   klass = GST_BASE_PARSE_GET_CLASS (parse);
3453
3454   GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
3455
3456   if (klass->set_sink_caps)
3457     res = klass->set_sink_caps (parse, caps);
3458
3459   return res && gst_pad_set_caps (pad, caps);
3460 }
3461
3462 static void
3463 gst_base_parse_set_index (GstElement * element, GstIndex * index)
3464 {
3465   GstBaseParse *parse = GST_BASE_PARSE (element);
3466
3467   GST_OBJECT_LOCK (parse);
3468   if (parse->priv->index)
3469     gst_object_unref (parse->priv->index);
3470   if (index) {
3471     parse->priv->index = gst_object_ref (index);
3472     gst_index_get_writer_id (index, GST_OBJECT (element),
3473         &parse->priv->index_id);
3474     parse->priv->own_index = FALSE;
3475   } else
3476     parse->priv->index = NULL;
3477   GST_OBJECT_UNLOCK (parse);
3478 }
3479
3480 static GstIndex *
3481 gst_base_parse_get_index (GstElement * element)
3482 {
3483   GstBaseParse *parse = GST_BASE_PARSE (element);
3484   GstIndex *result = NULL;
3485
3486   GST_OBJECT_LOCK (parse);
3487   if (parse->priv->index)
3488     result = gst_object_ref (parse->priv->index);
3489   GST_OBJECT_UNLOCK (parse);
3490
3491   return result;
3492 }
3493
3494 static GstStateChangeReturn
3495 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
3496 {
3497   GstBaseParse *parse;
3498   GstStateChangeReturn result;
3499
3500   parse = GST_BASE_PARSE (element);
3501
3502   switch (transition) {
3503     case GST_STATE_CHANGE_READY_TO_PAUSED:
3504       /* If this is our own index destroy it as the
3505        * old entries might be wrong for the new stream */
3506       if (parse->priv->own_index) {
3507         gst_object_unref (parse->priv->index);
3508         parse->priv->index = NULL;
3509         parse->priv->own_index = FALSE;
3510       }
3511
3512       /* If no index was created, generate one */
3513       if (G_UNLIKELY (!parse->priv->index)) {
3514         GST_DEBUG_OBJECT (parse, "no index provided creating our own");
3515
3516         parse->priv->index = gst_index_factory_make ("memindex");
3517         gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
3518             &parse->priv->index_id);
3519         parse->priv->own_index = TRUE;
3520       }
3521       break;
3522     default:
3523       break;
3524   }
3525
3526   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3527
3528   switch (transition) {
3529     case GST_STATE_CHANGE_PAUSED_TO_READY:
3530       gst_base_parse_reset (parse);
3531       break;
3532     default:
3533       break;
3534   }
3535
3536   return result;
3537 }