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