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