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