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