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