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