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