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