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