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