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