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