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