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