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