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