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