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