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