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