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