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