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