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