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