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