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