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