baseparse: turn assert into a real error
[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_INDEX_ASSOCIATION_FLAG_KEY_UNIT :
1611       GST_INDEX_ASSOCIATION_FLAG_DELTA_UNIT, 2,
1612       (const GstIndexAssociation *) &associations);
1613   GST_BASE_PARSE_INDEX_UNLOCK (parse);
1614
1615   if (key) {
1616     parse->priv->index_last_offset = offset;
1617     parse->priv->index_last_ts = ts;
1618   }
1619
1620   ret = TRUE;
1621
1622 exit:
1623   return ret;
1624 }
1625
1626 /* check for seekable upstream, above and beyond a mere query */
1627 static void
1628 gst_base_parse_check_seekability (GstBaseParse * parse)
1629 {
1630   GstQuery *query;
1631   gboolean seekable = FALSE;
1632   gint64 start = -1, stop = -1;
1633   guint idx_interval = 0;
1634
1635   query = gst_query_new_seeking (GST_FORMAT_BYTES);
1636   if (!gst_pad_peer_query (parse->sinkpad, query)) {
1637     GST_DEBUG_OBJECT (parse, "seeking query failed");
1638     goto done;
1639   }
1640
1641   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1642
1643   /* try harder to query upstream size if we didn't get it the first time */
1644   if (seekable && stop == -1) {
1645     GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1646     gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_BYTES, &stop);
1647   }
1648
1649   /* if upstream doesn't know the size, it's likely that it's not seekable in
1650    * practice even if it technically may be seekable */
1651   if (seekable && (start != 0 || stop <= start)) {
1652     GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1653     seekable = FALSE;
1654   }
1655
1656   /* let's not put every single frame into our index */
1657   if (seekable) {
1658     if (stop < 10 * 1024 * 1024)
1659       idx_interval = 100;
1660     else if (stop < 100 * 1024 * 1024)
1661       idx_interval = 500;
1662     else
1663       idx_interval = 1000;
1664   }
1665
1666 done:
1667   gst_query_unref (query);
1668
1669   GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1670       G_GUINT64_FORMAT ")", seekable, start, stop);
1671   parse->priv->upstream_seekable = seekable;
1672   parse->priv->upstream_size = seekable ? stop : 0;
1673
1674   GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1675   parse->priv->idx_interval = idx_interval * GST_MSECOND;
1676 }
1677
1678 /* some misc checks on upstream */
1679 static void
1680 gst_base_parse_check_upstream (GstBaseParse * parse)
1681 {
1682   gint64 stop;
1683
1684   if (gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_TIME, &stop))
1685     if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1686       /* upstream has one, accept it also, and no further updates */
1687       gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1688       parse->priv->upstream_has_duration = TRUE;
1689     }
1690
1691   GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1692       parse->priv->upstream_has_duration);
1693 }
1694
1695 /* checks src caps to determine if dealing with audio or video */
1696 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1697 static void
1698 gst_base_parse_check_media (GstBaseParse * parse)
1699 {
1700   GstCaps *caps;
1701   GstStructure *s;
1702
1703   caps = gst_pad_get_current_caps (parse->srcpad);
1704   if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1705     parse->priv->is_video =
1706         g_str_has_prefix (gst_structure_get_name (s), "video");
1707   } else {
1708     /* historical default */
1709     parse->priv->is_video = FALSE;
1710   }
1711   if (caps)
1712     gst_caps_unref (caps);
1713
1714   GST_DEBUG_OBJECT (parse, "media is video: %d", parse->priv->is_video);
1715 }
1716
1717 /* takes ownership of frame */
1718 static void
1719 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1720 {
1721   if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1722     /* frame allocated on the heap, we can just take ownership */
1723     g_queue_push_tail (&parse->priv->queued_frames, frame);
1724     GST_TRACE ("queued frame %p", frame);
1725   } else {
1726     GstBaseParseFrame *copy;
1727
1728     /* probably allocated on the stack, must make a proper copy */
1729     copy = gst_base_parse_frame_copy (frame);
1730     g_queue_push_tail (&parse->priv->queued_frames, copy);
1731     GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1732     gst_base_parse_frame_free (frame);
1733   }
1734 }
1735
1736 /* gst_base_parse_handle_and_push_buffer:
1737  * @parse: #GstBaseParse.
1738  * @klass: #GstBaseParseClass.
1739  * @frame: (transfer full): a #GstBaseParseFrame
1740  *
1741  * Parses the frame from given buffer and pushes it forward. Also performs
1742  * timestamp handling and checks the segment limits.
1743  *
1744  * This is called with srcpad STREAM_LOCK held.
1745  *
1746  * Returns: #GstFlowReturn
1747  */
1748 static GstFlowReturn
1749 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1750     GstBaseParseClass * klass, GstBaseParseFrame * frame)
1751 {
1752   GstFlowReturn ret;
1753   gint64 offset;
1754   GstBuffer *buffer;
1755
1756   g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1757
1758   buffer = frame->buffer;
1759
1760   if (parse->priv->discont) {
1761     GST_DEBUG_OBJECT (parse, "marking DISCONT");
1762     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1763     parse->priv->discont = FALSE;
1764   }
1765
1766   /* some one-time start-up */
1767   if (G_UNLIKELY (!parse->priv->framecount)) {
1768     gst_base_parse_check_seekability (parse);
1769     gst_base_parse_check_upstream (parse);
1770   }
1771
1772   GST_LOG_OBJECT (parse,
1773       "parsing frame at offset %" G_GUINT64_FORMAT
1774       " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
1775       GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1776       gst_buffer_get_size (buffer));
1777
1778   /* use default handler to provide initial (upstream) metadata */
1779   gst_base_parse_parse_frame (parse, frame);
1780
1781   /* store offset as it might get overwritten */
1782   offset = GST_BUFFER_OFFSET (buffer);
1783   ret = klass->parse_frame (parse, frame);
1784   /* sync */
1785   buffer = frame->buffer;
1786   /* subclass must play nice */
1787   g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1788
1789   /* check if subclass/format can provide ts.
1790    * If so, that allows and enables extra seek and duration determining options */
1791   if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
1792     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && parse->priv->has_timing_info
1793         && parse->priv->pad_mode == GST_PAD_MODE_PULL) {
1794       parse->priv->first_frame_offset = offset;
1795       parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1796       GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1797           " for first frame at offset %" G_GINT64_FORMAT,
1798           GST_TIME_ARGS (parse->priv->first_frame_ts),
1799           parse->priv->first_frame_offset);
1800       if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1801         gint64 off;
1802         GstClockTime last_ts = G_MAXINT64;
1803
1804         GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1805         gst_base_parse_locate_time (parse, &last_ts, &off);
1806         if (GST_CLOCK_TIME_IS_VALID (last_ts))
1807           gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1808       }
1809     } else {
1810       /* disable further checks */
1811       parse->priv->first_frame_offset = 0;
1812     }
1813   }
1814
1815   /* again use default handler to add missing metadata;
1816    * we may have new information on frame properties */
1817   gst_base_parse_parse_frame (parse, frame);
1818   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1819       GST_BUFFER_DURATION_IS_VALID (buffer)) {
1820     parse->priv->next_ts =
1821         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1822   } else {
1823     /* we lost track, do not produce bogus time next time around
1824      * (probably means parser subclass has given up on parsing as well) */
1825     GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1826     parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1827   }
1828
1829   if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1830       GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1831     gst_base_parse_add_index_entry (parse, offset,
1832         GST_BUFFER_TIMESTAMP (buffer),
1833         !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1834
1835   /* First buffers are dropped, this means that the subclass needs more
1836    * frames to decide on the format and queues them internally */
1837   /* convert internal flow to OK and mark discont for the next buffer. */
1838   if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1839     gst_base_parse_frame_free (frame);
1840     return GST_FLOW_OK;
1841   } else if (ret == GST_BASE_PARSE_FLOW_QUEUED) {
1842     gst_base_parse_queue_frame (parse, frame);
1843     return GST_FLOW_OK;
1844   } else if (ret != GST_FLOW_OK) {
1845     return ret;
1846   }
1847
1848   /* All OK, push queued frames if there are any */
1849   if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
1850     GstBaseParseFrame *queued_frame;
1851
1852     while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
1853       gst_base_parse_push_frame (parse, queued_frame);
1854     }
1855   }
1856
1857   return gst_base_parse_push_frame (parse, frame);
1858 }
1859
1860 /**
1861  * gst_base_parse_push_frame:
1862  * @parse: #GstBaseParse.
1863  * @frame: (transfer full): a #GstBaseParseFrame
1864  *
1865  * Pushes the frame downstream, sends any pending events and
1866  * does some timestamp and segment handling. Takes ownership
1867  * of @frame and will clear it (if it was initialised with
1868  * gst_base_parse_frame_init()) or free it.
1869  *
1870  * This must be called with sinkpad STREAM_LOCK held.
1871  *
1872  * Returns: #GstFlowReturn
1873  *
1874  * Since: 0.10.33
1875  */
1876 GstFlowReturn
1877 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1878 {
1879   GstFlowReturn ret = GST_FLOW_OK;
1880   GstClockTime last_start = GST_CLOCK_TIME_NONE;
1881   GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1882   GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1883   GstBuffer *buffer;
1884   gsize size;
1885
1886   g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1887   g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
1888
1889   GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
1890
1891   buffer = frame->buffer;
1892
1893   GST_LOG_OBJECT (parse,
1894       "processing buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1895       ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buffer),
1896       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1897       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1898
1899   /* update stats */
1900   size = gst_buffer_get_size (buffer);
1901   parse->priv->bytecount += size;
1902   if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1903     parse->priv->framecount++;
1904     if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1905       parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1906     }
1907   }
1908   /* 0 means disabled */
1909   if (parse->priv->update_interval < 0)
1910     parse->priv->update_interval = 50;
1911   else if (parse->priv->update_interval > 0 &&
1912       (parse->priv->framecount % parse->priv->update_interval) == 0)
1913     gst_base_parse_update_duration (parse);
1914
1915   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1916     last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1917   if (last_start != GST_CLOCK_TIME_NONE
1918       && GST_BUFFER_DURATION_IS_VALID (buffer))
1919     last_stop = last_start + GST_BUFFER_DURATION (buffer);
1920
1921   /* should have caps by now */
1922   if (!gst_pad_has_current_caps (parse->srcpad))
1923     goto no_caps;
1924
1925   /* segment adjustment magic; only if we are running the whole show */
1926   if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1927       (parse->priv->pad_mode == GST_PAD_MODE_PULL ||
1928           parse->priv->upstream_seekable)) {
1929     /* segment times are typically estimates,
1930      * actual frame data might lead subclass to different timestamps,
1931      * so override segment start from what is supplied there */
1932     if (G_UNLIKELY (parse->priv->pending_segment && !parse->priv->exact_position
1933             && GST_CLOCK_TIME_IS_VALID (last_start))) {
1934       gst_event_unref (parse->priv->pending_segment);
1935       parse->segment.start =
1936           MIN ((guint64) last_start, (guint64) parse->segment.stop);
1937
1938       GST_DEBUG_OBJECT (parse,
1939           "adjusting pending segment start to %" GST_TIME_FORMAT,
1940           GST_TIME_ARGS (parse->segment.start));
1941
1942       parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
1943     }
1944     /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1945     if (GST_CLOCK_TIME_IS_VALID (parse->segment.position) &&
1946         GST_CLOCK_TIME_IS_VALID (last_start)) {
1947       GstClockTimeDiff diff;
1948
1949       /* only send newsegments with increasing start times,
1950        * otherwise if these go back and forth downstream (sinks) increase
1951        * accumulated time and running_time */
1952       diff = GST_CLOCK_DIFF (parse->segment.position, last_start);
1953       if (G_UNLIKELY (diff > 2 * GST_SECOND
1954               && last_start > parse->segment.start
1955               && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
1956                   || last_start < parse->segment.stop))) {
1957
1958         GST_DEBUG_OBJECT (parse,
1959             "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
1960             GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1961             "Sending updated NEWSEGMENT events", diff,
1962             GST_TIME_ARGS (parse->segment.position),
1963             GST_TIME_ARGS (last_start));
1964
1965         if (G_UNLIKELY (parse->priv->pending_segment)) {
1966           gst_event_unref (parse->priv->pending_segment);
1967           parse->segment.start = last_start;
1968           parse->segment.time = last_start;
1969           parse->priv->pending_segment =
1970               gst_event_new_segment (&parse->segment);
1971         } else {
1972           /* skip gap FIXME */
1973           gst_pad_push_event (parse->srcpad,
1974               gst_event_new_segment (&parse->segment));
1975         }
1976         parse->segment.position = last_start;
1977       }
1978     }
1979   }
1980
1981   /* and should then also be linked downstream, so safe to send some events */
1982   if (G_UNLIKELY (parse->priv->close_segment)) {
1983     /* only set up by loop */
1984     GST_DEBUG_OBJECT (parse, "loop sending close segment");
1985     gst_pad_push_event (parse->srcpad, parse->priv->close_segment);
1986     parse->priv->close_segment = NULL;
1987   }
1988   if (G_UNLIKELY (parse->priv->pending_segment)) {
1989     GstEvent *pending_segment;
1990
1991     pending_segment = parse->priv->pending_segment;
1992     parse->priv->pending_segment = NULL;
1993
1994     GST_DEBUG_OBJECT (parse, "%s push pending segment",
1995         parse->priv->pad_mode == GST_PAD_MODE_PULL ? "loop" : "chain");
1996     gst_pad_push_event (parse->srcpad, pending_segment);
1997
1998     /* have caps; check identity */
1999     gst_base_parse_check_media (parse);
2000   }
2001
2002   /* update bitrates and optionally post corresponding tags
2003    * (following newsegment) */
2004   gst_base_parse_update_bitrates (parse, frame);
2005
2006   if (G_UNLIKELY (parse->priv->pending_events)) {
2007     GList *l;
2008
2009     for (l = parse->priv->pending_events; l != NULL; l = l->next) {
2010       gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
2011     }
2012     g_list_free (parse->priv->pending_events);
2013     parse->priv->pending_events = NULL;
2014   }
2015
2016   if (klass->pre_push_frame) {
2017     ret = klass->pre_push_frame (parse, frame);
2018   } else {
2019     frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
2020   }
2021
2022   /* take final ownership of frame buffer */
2023   buffer = frame->buffer;
2024   frame->buffer = NULL;
2025
2026   /* subclass must play nice */
2027   g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2028
2029   parse->priv->seen_keyframe |= parse->priv->is_video &&
2030       !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
2031
2032   if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
2033     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2034         GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
2035         GST_BUFFER_TIMESTAMP (buffer) >
2036         parse->segment.stop + parse->priv->lead_out_ts) {
2037       GST_LOG_OBJECT (parse, "Dropped frame, after segment");
2038       ret = GST_FLOW_EOS;
2039     } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2040         GST_BUFFER_DURATION_IS_VALID (buffer) &&
2041         GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
2042         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
2043         parse->priv->lead_in_ts < parse->segment.start) {
2044       if (parse->priv->seen_keyframe) {
2045         GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
2046         ret = GST_FLOW_OK;
2047       } else {
2048         GST_LOG_OBJECT (parse, "Dropped frame, before segment");
2049         ret = GST_BASE_PARSE_FLOW_DROPPED;
2050       }
2051     } else {
2052       ret = GST_FLOW_OK;
2053     }
2054   }
2055
2056   if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
2057     GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) dropped", size);
2058     gst_buffer_unref (buffer);
2059     ret = GST_FLOW_OK;
2060   } else if (ret == GST_FLOW_OK) {
2061     if (parse->segment.rate > 0.0) {
2062       GST_LOG_OBJECT (parse, "pushing frame (%" G_GSIZE_FORMAT " bytes) now..",
2063           size);
2064       ret = gst_pad_push (parse->srcpad, buffer);
2065       GST_LOG_OBJECT (parse, "frame pushed, flow %s", gst_flow_get_name (ret));
2066     } else {
2067       GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) queued for now",
2068           size);
2069       parse->priv->buffers_queued =
2070           g_slist_prepend (parse->priv->buffers_queued, buffer);
2071       ret = GST_FLOW_OK;
2072     }
2073   } else {
2074     GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s",
2075         size, gst_flow_get_name (ret));
2076     gst_buffer_unref (buffer);
2077     /* if we are not sufficiently in control, let upstream decide on EOS */
2078     if (ret == GST_FLOW_EOS &&
2079         (parse->priv->passthrough ||
2080             (parse->priv->pad_mode == GST_PAD_MODE_PUSH &&
2081                 !parse->priv->upstream_seekable)))
2082       ret = GST_FLOW_OK;
2083   }
2084
2085   /* Update current running segment position */
2086   if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
2087       parse->segment.position < last_stop)
2088     parse->segment.position = last_stop;
2089
2090   gst_base_parse_frame_free (frame);
2091
2092   return ret;
2093
2094   /* ERRORS */
2095 no_caps:
2096   {
2097     GST_ELEMENT_ERROR (parse, STREAM, DECODE, ("No caps set"), (NULL));
2098     return GST_FLOW_ERROR;
2099   }
2100 }
2101
2102
2103 /* gst_base_parse_drain:
2104  *
2105  * Drains the adapter until it is empty. It decreases the min_frame_size to
2106  * match the current adapter size and calls chain method until the adapter
2107  * is emptied or chain returns with error.
2108  */
2109 static void
2110 gst_base_parse_drain (GstBaseParse * parse)
2111 {
2112   guint avail;
2113
2114   GST_DEBUG_OBJECT (parse, "draining");
2115   parse->priv->drain = TRUE;
2116
2117   for (;;) {
2118     avail = gst_adapter_available (parse->priv->adapter);
2119     if (!avail)
2120       break;
2121
2122     if (gst_base_parse_chain (parse->sinkpad, GST_OBJECT_CAST (parse),
2123             NULL) != GST_FLOW_OK) {
2124       break;
2125     }
2126
2127     /* nothing changed, maybe due to truncated frame; break infinite loop */
2128     if (avail == gst_adapter_available (parse->priv->adapter)) {
2129       GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
2130       gst_adapter_clear (parse->priv->adapter);
2131     }
2132   }
2133
2134   parse->priv->drain = FALSE;
2135 }
2136
2137 /* gst_base_parse_send_buffers
2138  *
2139  * Sends buffers collected in send_buffers downstream, and ensures that list
2140  * is empty at the end (errors or not).
2141  */
2142 static GstFlowReturn
2143 gst_base_parse_send_buffers (GstBaseParse * parse)
2144 {
2145   GSList *send = NULL;
2146   GstBuffer *buf;
2147   GstFlowReturn ret = GST_FLOW_OK;
2148
2149   send = parse->priv->buffers_send;
2150
2151   /* send buffers */
2152   while (send) {
2153     buf = GST_BUFFER_CAST (send->data);
2154     GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
2155         GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2156         ", offset %" G_GINT64_FORMAT, buf,
2157         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2158         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2159
2160     /* iterate output queue an push downstream */
2161     ret = gst_pad_push (parse->srcpad, buf);
2162     send = g_slist_delete_link (send, send);
2163
2164     /* clear any leftover if error */
2165     if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2166       while (send) {
2167         buf = GST_BUFFER_CAST (send->data);
2168         gst_buffer_unref (buf);
2169         send = g_slist_delete_link (send, send);
2170       }
2171     }
2172   }
2173
2174   parse->priv->buffers_send = send;
2175
2176   return ret;
2177 }
2178
2179 /* gst_base_parse_process_fragment:
2180  *
2181  * Processes a reverse playback (forward) fragment:
2182  * - append head of last fragment that was skipped to current fragment data
2183  * - drain the resulting current fragment data (i.e. repeated chain)
2184  * - add time/duration (if needed) to frames queued by chain
2185  * - push queued data
2186  */
2187 static GstFlowReturn
2188 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
2189 {
2190   GstBuffer *buf;
2191   GstFlowReturn ret = GST_FLOW_OK;
2192   gboolean seen_key = FALSE, seen_delta = FALSE;
2193
2194   if (push_only)
2195     goto push;
2196
2197   /* restore order */
2198   parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2199   while (parse->priv->buffers_pending) {
2200     buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2201     GST_LOG_OBJECT (parse, "adding pending buffer (size %" G_GSIZE_FORMAT ")",
2202         gst_buffer_get_size (buf));
2203     gst_adapter_push (parse->priv->adapter, buf);
2204     parse->priv->buffers_pending =
2205         g_slist_delete_link (parse->priv->buffers_pending,
2206         parse->priv->buffers_pending);
2207   }
2208
2209   /* invalidate so no fall-back timestamping is performed;
2210    * ok if taken from subclass or upstream */
2211   parse->priv->next_ts = GST_CLOCK_TIME_NONE;
2212   /* prevent it hanging around stop all the time */
2213   parse->segment.position = GST_CLOCK_TIME_NONE;
2214   /* mark next run */
2215   parse->priv->discont = TRUE;
2216
2217   /* chain looks for frames and queues resulting ones (in stead of pushing) */
2218   /* initial skipped data is added to buffers_pending */
2219   gst_base_parse_drain (parse);
2220
2221 push:
2222   if (parse->priv->buffers_send) {
2223     buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2224     seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2225   }
2226
2227   /* add metadata (if needed to queued buffers */
2228   GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2229       GST_TIME_ARGS (parse->priv->last_ts));
2230   while (parse->priv->buffers_queued) {
2231     buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2232
2233     /* no touching if upstream or parsing provided time */
2234     if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2235       GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2236           GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2237     } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
2238         GST_BUFFER_DURATION_IS_VALID (buf)) {
2239       if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
2240         parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
2241       else
2242         parse->priv->last_ts = 0;
2243       GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
2244       GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2245           GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2246     } else {
2247       /* no idea, very bad */
2248       GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2249     }
2250
2251     parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
2252
2253     /* reverse order for ascending sending */
2254     /* send downstream at keyframe not preceded by a keyframe
2255      * (e.g. that should identify start of collection of IDR nals) */
2256     if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2257       if (seen_key) {
2258         ret = gst_base_parse_send_buffers (parse);
2259         /* if a problem, throw all to sending */
2260         if (ret != GST_FLOW_OK) {
2261           parse->priv->buffers_send =
2262               g_slist_reverse (parse->priv->buffers_queued);
2263           parse->priv->buffers_queued = NULL;
2264           break;
2265         }
2266         seen_key = FALSE;
2267       }
2268     } else {
2269       seen_delta = TRUE;
2270     }
2271
2272     seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2273
2274     parse->priv->buffers_send =
2275         g_slist_prepend (parse->priv->buffers_send, buf);
2276     parse->priv->buffers_queued =
2277         g_slist_delete_link (parse->priv->buffers_queued,
2278         parse->priv->buffers_queued);
2279   }
2280
2281   /* audio may have all marked as keyframe, so arrange to send here */
2282   if (!seen_delta)
2283     ret = gst_base_parse_send_buffers (parse);
2284
2285   /* any trailing unused no longer usable (ideally none) */
2286   if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2287     GST_DEBUG_OBJECT (parse, "discarding %" G_GSIZE_FORMAT " trailing bytes",
2288         gst_adapter_available (parse->priv->adapter));
2289     gst_adapter_clear (parse->priv->adapter);
2290   }
2291
2292   return ret;
2293 }
2294
2295 /* small helper that checks whether we have been trying to resync too long */
2296 static inline GstFlowReturn
2297 gst_base_parse_check_sync (GstBaseParse * parse)
2298 {
2299   if (G_UNLIKELY (parse->priv->discont &&
2300           parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2301     GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2302         ("Failed to parse stream"), (NULL));
2303     return GST_FLOW_ERROR;
2304   }
2305
2306   return GST_FLOW_OK;
2307 }
2308
2309 static GstFlowReturn
2310 gst_base_parse_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2311 {
2312   GstBaseParseClass *bclass;
2313   GstBaseParse *parse;
2314   GstFlowReturn ret = GST_FLOW_OK;
2315   GstBuffer *outbuf = NULL;
2316   GstBuffer *tmpbuf = NULL;
2317   guint fsize = 1;
2318   gint skip = -1;
2319   const guint8 *data;
2320   guint old_min_size = 0, min_size, av;
2321   GstClockTime timestamp;
2322   GstBaseParseFrame *frame;
2323
2324   parse = GST_BASE_PARSE (parent);
2325   bclass = GST_BASE_PARSE_GET_CLASS (parse);
2326
2327   if (parse->priv->detecting) {
2328     GstBuffer *detect_buf;
2329
2330     if (parse->priv->detect_buffers_size == 0) {
2331       detect_buf = gst_buffer_ref (buffer);
2332     } else {
2333       GList *l;
2334       guint offset = 0;
2335
2336       detect_buf = gst_buffer_new ();
2337
2338       for (l = parse->priv->detect_buffers; l; l = l->next) {
2339         gsize tmpsize = gst_buffer_get_size (l->data);
2340
2341         gst_buffer_copy_into (detect_buf, GST_BUFFER_CAST (l->data),
2342             GST_BUFFER_COPY_MEMORY, offset, tmpsize);
2343         offset += tmpsize;
2344       }
2345       if (buffer)
2346         gst_buffer_copy_into (detect_buf, buffer, GST_BUFFER_COPY_MEMORY,
2347             offset, gst_buffer_get_size (buffer));
2348     }
2349
2350     ret = bclass->detect (parse, detect_buf);
2351     gst_buffer_unref (detect_buf);
2352
2353     if (ret == GST_FLOW_OK) {
2354       GList *l;
2355
2356       /* Detected something */
2357       parse->priv->detecting = FALSE;
2358
2359       for (l = parse->priv->detect_buffers; l; l = l->next) {
2360         if (ret == GST_FLOW_OK && !parse->priv->flushing)
2361           ret =
2362               gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2363               parent, GST_BUFFER_CAST (l->data));
2364         else
2365           gst_buffer_unref (GST_BUFFER_CAST (l->data));
2366       }
2367       g_list_free (parse->priv->detect_buffers);
2368       parse->priv->detect_buffers = NULL;
2369       parse->priv->detect_buffers_size = 0;
2370
2371       if (ret != GST_FLOW_OK) {
2372         return ret;
2373       }
2374
2375       /* Handle the current buffer */
2376     } else if (ret == GST_FLOW_NOT_NEGOTIATED) {
2377       /* Still detecting, append buffer or error out if draining */
2378
2379       if (parse->priv->drain) {
2380         GST_DEBUG_OBJECT (parse, "Draining but did not detect format yet");
2381         return GST_FLOW_ERROR;
2382       } else if (parse->priv->flushing) {
2383         g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref,
2384             NULL);
2385         g_list_free (parse->priv->detect_buffers);
2386         parse->priv->detect_buffers = NULL;
2387         parse->priv->detect_buffers_size = 0;
2388       } else {
2389         parse->priv->detect_buffers =
2390             g_list_append (parse->priv->detect_buffers, buffer);
2391         parse->priv->detect_buffers_size += gst_buffer_get_size (buffer);
2392         return GST_FLOW_OK;
2393       }
2394     } else {
2395       /* Something went wrong, subclass responsible for error reporting */
2396       return ret;
2397     }
2398
2399     /* And now handle the current buffer if detection worked */
2400   }
2401
2402   frame = &parse->priv->frame;
2403
2404   if (G_LIKELY (buffer)) {
2405     GST_LOG_OBJECT (parse,
2406         "buffer size: %" G_GSIZE_FORMAT ", offset = %" G_GINT64_FORMAT,
2407         gst_buffer_get_size (buffer), GST_BUFFER_OFFSET (buffer));
2408     if (G_UNLIKELY (parse->priv->passthrough)) {
2409       gst_base_parse_frame_init (frame);
2410       frame->buffer = gst_buffer_make_writable (buffer);
2411       return gst_base_parse_push_frame (parse, frame);
2412     }
2413     /* upstream feeding us in reverse playback;
2414      * gather each fragment, then process it in single run */
2415     if (parse->segment.rate < 0.0) {
2416       if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2417         GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2418         ret = gst_base_parse_process_fragment (parse, FALSE);
2419       }
2420       gst_adapter_push (parse->priv->adapter, buffer);
2421       return ret;
2422     }
2423     gst_adapter_push (parse->priv->adapter, buffer);
2424   }
2425
2426   if (G_UNLIKELY (buffer &&
2427           GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2428     frame->_private_flags |= GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
2429     gst_base_parse_frame_free (frame);
2430   }
2431
2432   /* Parse and push as many frames as possible */
2433   /* Stop either when adapter is empty or we are flushing */
2434   while (!parse->priv->flushing) {
2435     gboolean res;
2436
2437     /* maintain frame state for a single frame parsing round across _chain calls,
2438      * so only init when needed */
2439     if (!frame->_private_flags)
2440       gst_base_parse_frame_init (frame);
2441
2442     tmpbuf = gst_buffer_new ();
2443
2444     old_min_size = 0;
2445     /* Synchronization loop */
2446     for (;;) {
2447       /* note: if subclass indicates MAX fsize,
2448        * this will not likely be available anyway ... */
2449       min_size = MAX (parse->priv->min_frame_size, fsize);
2450       av = gst_adapter_available (parse->priv->adapter);
2451
2452       /* loop safety check */
2453       if (G_UNLIKELY (old_min_size >= min_size))
2454         goto invalid_min;
2455       old_min_size = min_size;
2456
2457       if (G_UNLIKELY (parse->priv->drain)) {
2458         min_size = av;
2459         GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2460         if (G_UNLIKELY (!min_size)) {
2461           gst_buffer_unref (tmpbuf);
2462           goto done;
2463         }
2464       }
2465
2466       /* Collect at least min_frame_size bytes */
2467       if (av < min_size) {
2468         GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
2469             av);
2470         gst_buffer_unref (tmpbuf);
2471         goto done;
2472       }
2473
2474       /* always pass all available data */
2475       data = gst_adapter_map (parse->priv->adapter, av);
2476       gst_buffer_take_memory (tmpbuf, -1,
2477           gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
2478               (gpointer) data, NULL, av, 0, av));
2479       GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
2480
2481       if (parse->priv->discont) {
2482         GST_DEBUG_OBJECT (parse, "marking DISCONT");
2483         GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2484       }
2485
2486       skip = -1;
2487       gst_base_parse_frame_update (parse, frame, tmpbuf);
2488       res = bclass->check_valid_frame (parse, frame, &fsize, &skip);
2489       gst_adapter_unmap (parse->priv->adapter);
2490       gst_buffer_replace (&frame->buffer, NULL);
2491       gst_buffer_remove_memory_range (tmpbuf, 0, -1);
2492       if (res) {
2493         if (gst_adapter_available (parse->priv->adapter) < fsize) {
2494           GST_DEBUG_OBJECT (parse, "found valid frame but not enough data"
2495               " available (only %" G_GSIZE_FORMAT " bytes)",
2496               gst_adapter_available (parse->priv->adapter));
2497           gst_buffer_unref (tmpbuf);
2498           goto done;
2499         }
2500         GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2501         break;
2502       }
2503       if (skip == -1) {
2504         /* subclass didn't touch this value. By default we skip 1 byte */
2505         skip = 1;
2506       }
2507       if (skip > 0) {
2508         GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2509         if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2510           /* reverse playback, and no frames found yet, so we are skipping
2511            * the leading part of a fragment, which may form the tail of
2512            * fragment coming later, hopefully subclass skips efficiently ... */
2513           timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2514           outbuf = gst_adapter_take_buffer (parse->priv->adapter, skip);
2515           outbuf = gst_buffer_make_writable (outbuf);
2516           GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
2517           parse->priv->buffers_pending =
2518               g_slist_prepend (parse->priv->buffers_pending, outbuf);
2519           outbuf = NULL;
2520         } else {
2521           gst_adapter_flush (parse->priv->adapter, skip);
2522         }
2523         parse->priv->offset += skip;
2524         if (!parse->priv->discont)
2525           parse->priv->sync_offset = parse->priv->offset;
2526         parse->priv->discont = TRUE;
2527         /* something changed least; nullify loop check */
2528         old_min_size = 0;
2529       }
2530       /* skip == 0 should imply subclass set min_size to need more data;
2531        * we check this shortly */
2532       if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2533         gst_buffer_unref (tmpbuf);
2534         goto done;
2535       }
2536     }
2537     gst_buffer_unref (tmpbuf);
2538     tmpbuf = NULL;
2539
2540     if (skip > 0) {
2541       /* Subclass found the sync, but still wants to skip some data */
2542       GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
2543       gst_adapter_flush (parse->priv->adapter, skip);
2544       parse->priv->offset += skip;
2545     }
2546
2547     /* Grab lock to prevent a race with FLUSH_START handler */
2548     GST_PAD_STREAM_LOCK (parse->srcpad);
2549
2550     /* FLUSH_START event causes the "flushing" flag to be set. In this
2551      * case we can leave the frame pushing loop */
2552     if (parse->priv->flushing) {
2553       GST_PAD_STREAM_UNLOCK (parse->srcpad);
2554       break;
2555     }
2556
2557     /* move along with upstream timestamp (if any),
2558      * but interpolate in between */
2559     timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2560     if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2561         (parse->priv->prev_ts != timestamp)) {
2562       parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2563     }
2564
2565     /* FIXME: Would it be more efficient to make a subbuffer instead? */
2566     outbuf = gst_adapter_take_buffer (parse->priv->adapter, fsize);
2567     outbuf = gst_buffer_make_writable (outbuf);
2568
2569     /* Subclass may want to know the data offset */
2570     GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2571     parse->priv->offset += fsize;
2572     GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2573     GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
2574
2575     frame->buffer = outbuf;
2576     ret = gst_base_parse_handle_and_push_frame (parse, bclass, frame);
2577     GST_PAD_STREAM_UNLOCK (parse->srcpad);
2578
2579     if (ret != GST_FLOW_OK) {
2580       GST_LOG_OBJECT (parse, "push returned %d", ret);
2581       break;
2582     }
2583   }
2584
2585 done:
2586   GST_LOG_OBJECT (parse, "chain leaving");
2587   return ret;
2588
2589   /* ERRORS */
2590 invalid_min:
2591   {
2592     GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2593         ("min_size evolution %d -> %d; breaking to avoid looping",
2594             old_min_size, min_size));
2595     return GST_FLOW_ERROR;
2596   }
2597 }
2598
2599 /* pull @size bytes at current offset,
2600  * i.e. at least try to and possibly return a shorter buffer if near the end */
2601 static GstFlowReturn
2602 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2603     GstBuffer ** buffer)
2604 {
2605   GstFlowReturn ret = GST_FLOW_OK;
2606
2607   g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2608
2609   /* Caching here actually makes much less difference than one would expect.
2610    * We do it mainly to avoid pulling buffers of 1 byte all the time */
2611   if (parse->priv->cache) {
2612     gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2613     gint cache_size = gst_buffer_get_size (parse->priv->cache);
2614
2615     if (cache_offset <= parse->priv->offset &&
2616         (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2617       *buffer = gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL,
2618           parse->priv->offset - cache_offset, size);
2619       GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2620       return GST_FLOW_OK;
2621     }
2622     /* not enough data in the cache, free cache and get a new one */
2623     gst_buffer_unref (parse->priv->cache);
2624     parse->priv->cache = NULL;
2625   }
2626
2627   /* refill the cache */
2628   ret =
2629       gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2630           64 * 1024), &parse->priv->cache);
2631   if (ret != GST_FLOW_OK) {
2632     parse->priv->cache = NULL;
2633     return ret;
2634   }
2635
2636   if (gst_buffer_get_size (parse->priv->cache) >= size) {
2637     *buffer =
2638         gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0,
2639         size);
2640     GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2641     return GST_FLOW_OK;
2642   }
2643
2644   /* Not possible to get enough data, try a last time with
2645    * requesting exactly the size we need */
2646   gst_buffer_unref (parse->priv->cache);
2647   parse->priv->cache = NULL;
2648
2649   ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2650       &parse->priv->cache);
2651
2652   if (ret != GST_FLOW_OK) {
2653     GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2654     *buffer = NULL;
2655     return ret;
2656   }
2657
2658   if (gst_buffer_get_size (parse->priv->cache) < size) {
2659     GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2660         G_GUINT64_FORMAT ": wanted %u bytes, got %" G_GSIZE_FORMAT " bytes",
2661         parse->priv->offset, size, gst_buffer_get_size (parse->priv->cache));
2662
2663     *buffer = parse->priv->cache;
2664     parse->priv->cache = NULL;
2665
2666     return GST_FLOW_OK;
2667   }
2668
2669   *buffer =
2670       gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0, size);
2671   GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2672
2673   return GST_FLOW_OK;
2674 }
2675
2676 static GstFlowReturn
2677 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2678 {
2679   gint64 offset = 0;
2680   GstClockTime ts = 0;
2681   GstBuffer *buffer;
2682   GstFlowReturn ret;
2683
2684   GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2685       ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2686       parse->priv->last_offset);
2687
2688   if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2689     GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2690         GST_TIME_ARGS (parse->segment.start));
2691     ret = GST_FLOW_EOS;
2692     goto exit;
2693   }
2694
2695   /* last fragment started at last_offset / last_ts;
2696    * seek back 10s capped at 1MB */
2697   if (parse->priv->last_ts >= 10 * GST_SECOND)
2698     ts = parse->priv->last_ts - 10 * GST_SECOND;
2699   /* if we are exact now, we will be more so going backwards */
2700   if (parse->priv->exact_position) {
2701     offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2702   } else {
2703     if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2704             GST_FORMAT_BYTES, &offset)) {
2705       GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2706     }
2707   }
2708   offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2709       parse->priv->last_offset - 1024);
2710   offset = MAX (0, offset);
2711
2712   GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2713       offset);
2714   parse->priv->offset = offset;
2715
2716   ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2717       &buffer);
2718   if (ret != GST_FLOW_OK)
2719     goto exit;
2720
2721   /* offset will increase again as fragment is processed/parsed */
2722   parse->priv->last_offset = offset;
2723
2724   gst_adapter_push (parse->priv->adapter, buffer);
2725   ret = gst_base_parse_process_fragment (parse, FALSE);
2726   if (ret != GST_FLOW_OK)
2727     goto exit;
2728
2729   /* force previous fragment */
2730   parse->priv->offset = -1;
2731
2732 exit:
2733   return ret;
2734 }
2735
2736 /* PULL mode:
2737  * pull and scan for next frame starting from current offset
2738  * ajusts sync, drain and offset going along */
2739 static GstFlowReturn
2740 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2741     GstBaseParseFrame * frame, gboolean full)
2742 {
2743   GstBuffer *buffer, *outbuf;
2744   GstFlowReturn ret = GST_FLOW_OK;
2745   guint fsize = 1, min_size, old_min_size = 0;
2746   gint skip = 0;
2747
2748   g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2749
2750   GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2751       " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2752
2753   /* let's make this efficient for all subclass once and for all;
2754    * maybe it does not need this much, but in the latter case, we know we are
2755    * in pull mode here and might as well try to read and supply more anyway
2756    * (so does the buffer caching mechanism) */
2757   fsize = 64 * 1024;
2758
2759   while (TRUE) {
2760     gboolean res;
2761
2762     min_size = MAX (parse->priv->min_frame_size, fsize);
2763     /* loop safety check */
2764     if (G_UNLIKELY (old_min_size >= min_size))
2765       goto invalid_min;
2766     old_min_size = min_size;
2767
2768     ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2769     if (ret != GST_FLOW_OK)
2770       goto done;
2771
2772     if (parse->priv->discont) {
2773       GST_DEBUG_OBJECT (parse, "marking DISCONT");
2774       GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2775     }
2776
2777     /* if we got a short read, inform subclass we are draining leftover
2778      * and no more is to be expected */
2779     if (gst_buffer_get_size (buffer) < min_size)
2780       parse->priv->drain = TRUE;
2781
2782     if (parse->priv->detecting) {
2783       ret = klass->detect (parse, buffer);
2784       if (ret == GST_FLOW_NOT_NEGOTIATED) {
2785         /* If draining we error out, otherwise request a buffer
2786          * with 64kb more */
2787         if (parse->priv->drain) {
2788           gst_buffer_unref (buffer);
2789           GST_ERROR_OBJECT (parse, "Failed to detect format but draining");
2790           return GST_FLOW_ERROR;
2791         } else {
2792           fsize += 64 * 1024;
2793           gst_buffer_unref (buffer);
2794           continue;
2795         }
2796       } else if (ret != GST_FLOW_OK) {
2797         gst_buffer_unref (buffer);
2798         GST_ERROR_OBJECT (parse, "detect() returned %s",
2799             gst_flow_get_name (ret));
2800         return ret;
2801       }
2802
2803       /* Else handle this buffer normally */
2804     }
2805
2806     skip = -1;
2807     gst_base_parse_frame_update (parse, frame, buffer);
2808     res = klass->check_valid_frame (parse, frame, &fsize, &skip);
2809     gst_buffer_replace (&frame->buffer, NULL);
2810     if (res) {
2811       parse->priv->drain = FALSE;
2812       GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2813       break;
2814     }
2815     parse->priv->drain = FALSE;
2816     if (skip == -1)
2817       skip = 1;
2818     if (skip > 0) {
2819       GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2820       if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2821         /* reverse playback, and no frames found yet, so we are skipping
2822          * the leading part of a fragment, which may form the tail of
2823          * fragment coming later, hopefully subclass skips efficiently ... */
2824         outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, 0, skip);
2825         parse->priv->buffers_pending =
2826             g_slist_prepend (parse->priv->buffers_pending, outbuf);
2827         outbuf = NULL;
2828       }
2829       parse->priv->offset += skip;
2830       if (!parse->priv->discont)
2831         parse->priv->sync_offset = parse->priv->offset;
2832       parse->priv->discont = TRUE;
2833       /* something changed at least; nullify loop check */
2834       if (fsize == G_MAXUINT)
2835         fsize = old_min_size + 64 * 1024;
2836       old_min_size = 0;
2837     }
2838     /* skip == 0 should imply subclass set min_size to need more data;
2839      * we check this shortly */
2840     GST_DEBUG_OBJECT (parse, "finding sync...");
2841     gst_buffer_unref (buffer);
2842     if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2843       goto done;
2844     }
2845   }
2846
2847   /* Does the subclass want to skip too? */
2848   if (skip > 0)
2849     parse->priv->offset += skip;
2850   else if (skip < 0)
2851     skip = 0;
2852
2853   if (fsize + skip <= gst_buffer_get_size (buffer)) {
2854     outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, skip, fsize);
2855     GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2856     GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2857     gst_buffer_unref (buffer);
2858   } else {
2859     gst_buffer_unref (buffer);
2860     ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2861     if (ret != GST_FLOW_OK)
2862       goto done;
2863     if (gst_buffer_get_size (outbuf) < fsize) {
2864       gst_buffer_unref (outbuf);
2865       ret = GST_FLOW_EOS;
2866     }
2867   }
2868
2869   parse->priv->offset += fsize;
2870
2871   frame->buffer = outbuf;
2872
2873 done:
2874   return ret;
2875
2876   /* ERRORS */
2877 invalid_min:
2878   {
2879     GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2880         ("min_size evolution %d -> %d; breaking to avoid looping",
2881             old_min_size, min_size));
2882     return GST_FLOW_ERROR;
2883   }
2884 }
2885
2886 /* Loop that is used in pull mode to retrieve data from upstream */
2887 static void
2888 gst_base_parse_loop (GstPad * pad)
2889 {
2890   GstBaseParse *parse;
2891   GstBaseParseClass *klass;
2892   GstFlowReturn ret = GST_FLOW_OK;
2893   GstBaseParseFrame frame;
2894
2895   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2896   klass = GST_BASE_PARSE_GET_CLASS (parse);
2897
2898   /* reverse playback:
2899    * first fragment (closest to stop time) is handled normally below,
2900    * then we pull in fragments going backwards */
2901   if (parse->segment.rate < 0.0) {
2902     /* check if we jumped back to a previous fragment,
2903      * which is a post-first fragment */
2904     if (parse->priv->offset < 0) {
2905       ret = gst_base_parse_handle_previous_fragment (parse);
2906       goto done;
2907     }
2908   }
2909
2910   gst_base_parse_frame_init (&frame);
2911   ret = gst_base_parse_scan_frame (parse, klass, &frame, TRUE);
2912   if (ret != GST_FLOW_OK)
2913     goto done;
2914
2915   /* This always cleans up frame, even if error occurs */
2916   ret = gst_base_parse_handle_and_push_frame (parse, klass, &frame);
2917
2918   /* eat expected eos signalling past segment in reverse playback */
2919   if (parse->segment.rate < 0.0 && ret == GST_FLOW_EOS &&
2920       parse->segment.position >= parse->segment.stop) {
2921     GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2922     /* push what was accumulated during loop run */
2923     gst_base_parse_process_fragment (parse, TRUE);
2924     /* force previous fragment */
2925     parse->priv->offset = -1;
2926     ret = GST_FLOW_OK;
2927   }
2928
2929 done:
2930   if (ret == GST_FLOW_EOS)
2931     goto eos;
2932   else if (ret != GST_FLOW_OK)
2933     goto pause;
2934
2935   gst_object_unref (parse);
2936   return;
2937
2938   /* ERRORS */
2939 eos:
2940   {
2941     ret = GST_FLOW_EOS;
2942     GST_DEBUG_OBJECT (parse, "eos");
2943     /* fall-through */
2944   }
2945 pause:
2946   {
2947     gboolean push_eos = FALSE;
2948
2949     GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2950         gst_flow_get_name (ret));
2951     gst_pad_pause_task (parse->sinkpad);
2952
2953     if (ret == GST_FLOW_EOS) {
2954       /* handle end-of-stream/segment */
2955       if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2956         gint64 stop;
2957
2958         if ((stop = parse->segment.stop) == -1)
2959           stop = parse->segment.duration;
2960
2961         GST_DEBUG_OBJECT (parse, "sending segment_done");
2962
2963         gst_element_post_message
2964             (GST_ELEMENT_CAST (parse),
2965             gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2966                 GST_FORMAT_TIME, stop));
2967       } else {
2968         /* If we STILL have zero frames processed, fire an error */
2969         if (parse->priv->framecount == 0) {
2970           GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2971               ("No valid frames found before end of stream"), (NULL));
2972         }
2973         push_eos = TRUE;
2974       }
2975     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
2976       /* for fatal errors we post an error message, wrong-state is
2977        * not fatal because it happens due to flushes and only means
2978        * that we should stop now. */
2979       GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2980           ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2981       push_eos = TRUE;
2982     }
2983     if (push_eos) {
2984       /* newsegment before eos */
2985       if (parse->priv->pending_segment) {
2986         gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
2987         parse->priv->pending_segment = NULL;
2988       }
2989       gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2990     }
2991     gst_object_unref (parse);
2992   }
2993 }
2994
2995 static gboolean
2996 gst_base_parse_sink_activate (GstPad * sinkpad, GstObject * parent)
2997 {
2998   GstBaseParse *parse;
2999   gboolean result = TRUE;
3000   GstQuery *query;
3001   gboolean pull_mode;
3002
3003   parse = GST_BASE_PARSE (parent);
3004
3005   GST_DEBUG_OBJECT (parse, "sink activate");
3006
3007   query = gst_query_new_scheduling ();
3008   result = gst_pad_peer_query (sinkpad, query);
3009   if (result) {
3010     pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL);
3011   } else {
3012     pull_mode = FALSE;
3013   }
3014   gst_query_unref (query);
3015
3016   if (pull_mode) {
3017     GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
3018     result = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
3019   } else {
3020     GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
3021     result = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
3022   }
3023
3024   GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
3025   return result;
3026 }
3027
3028 static gboolean
3029 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
3030 {
3031   GstBaseParseClass *klass;
3032   gboolean result = TRUE;
3033
3034   GST_DEBUG_OBJECT (parse, "activate %d", active);
3035
3036   klass = GST_BASE_PARSE_GET_CLASS (parse);
3037
3038   if (active) {
3039     if (parse->priv->pad_mode == GST_PAD_MODE_NONE && klass->start)
3040       result = klass->start (parse);
3041
3042     /* If the subclass implements ::detect we want to
3043      * call it for the first buffers now */
3044     parse->priv->detecting = (klass->detect != NULL);
3045   } else {
3046     /* We must make sure streaming has finished before resetting things
3047      * and calling the ::stop vfunc */
3048     GST_PAD_STREAM_LOCK (parse->sinkpad);
3049     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3050
3051     if (parse->priv->pad_mode != GST_PAD_MODE_NONE && klass->stop)
3052       result = klass->stop (parse);
3053
3054     parse->priv->pad_mode = GST_PAD_MODE_NONE;
3055   }
3056   GST_DEBUG_OBJECT (parse, "activate return: %d", result);
3057   return result;
3058 }
3059
3060 static gboolean
3061 gst_base_parse_sink_activate_mode (GstPad * pad, GstObject * parent,
3062     GstPadMode mode, gboolean active)
3063 {
3064   gboolean result = TRUE;
3065   GstBaseParse *parse;
3066
3067   parse = GST_BASE_PARSE (parent);
3068
3069   GST_DEBUG_OBJECT (parse, "sink activate mode %d, %d", mode, active);
3070
3071   result = gst_base_parse_activate (parse, active);
3072
3073   if (result) {
3074     switch (mode) {
3075       case GST_PAD_MODE_PULL:
3076         if (active) {
3077           parse->priv->pending_segment =
3078               gst_event_new_segment (&parse->segment);
3079           result &=
3080               gst_pad_start_task (pad, (GstTaskFunction) gst_base_parse_loop,
3081               pad);
3082         } else {
3083           result &= gst_pad_stop_task (pad);
3084         }
3085         break;
3086       default:
3087         break;
3088     }
3089   }
3090   if (result)
3091     parse->priv->pad_mode = active ? mode : GST_PAD_MODE_NONE;
3092
3093   GST_DEBUG_OBJECT (parse, "sink activate return: %d", result);
3094
3095   return result;
3096 }
3097
3098 /**
3099  * gst_base_parse_set_duration:
3100  * @parse: #GstBaseParse.
3101  * @fmt: #GstFormat.
3102  * @duration: duration value.
3103  * @interval: how often to update the duration estimate based on bitrate, or 0.
3104  *
3105  * Sets the duration of the currently playing media. Subclass can use this
3106  * when it is able to determine duration and/or notices a change in the media
3107  * duration.  Alternatively, if @interval is non-zero (default), then stream
3108  * duration is determined based on estimated bitrate, and updated every @interval
3109  * frames.
3110  *
3111  * Since: 0.10.33
3112  */
3113 void
3114 gst_base_parse_set_duration (GstBaseParse * parse,
3115     GstFormat fmt, gint64 duration, gint interval)
3116 {
3117   g_return_if_fail (parse != NULL);
3118
3119   if (parse->priv->upstream_has_duration) {
3120     GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
3121     goto exit;
3122   }
3123
3124   if (duration != parse->priv->duration) {
3125     GstMessage *m;
3126
3127     m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
3128     gst_element_post_message (GST_ELEMENT (parse), m);
3129
3130     /* TODO: what about duration tag? */
3131   }
3132   parse->priv->duration = duration;
3133   parse->priv->duration_fmt = fmt;
3134   GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
3135   if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
3136     if (interval != 0) {
3137       GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
3138       interval = 0;
3139     }
3140   }
3141   GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
3142   parse->priv->update_interval = interval;
3143 exit:
3144   return;
3145 }
3146
3147 /**
3148  * gst_base_parse_set_average_bitrate:
3149  * @parse: #GstBaseParse.
3150  * @bitrate: average bitrate in bits/second
3151  *
3152  * Optionally sets the average bitrate detected in media (if non-zero),
3153  * e.g. based on metadata, as it will be posted to the application.
3154  *
3155  * By default, announced average bitrate is estimated. The average bitrate
3156  * is used to estimate the total duration of the stream and to estimate
3157  * a seek position, if there's no index and the format is syncable
3158  * (see gst_base_parse_set_syncable()).
3159  *
3160  * Since: 0.10.33
3161  */
3162 void
3163 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
3164 {
3165   parse->priv->bitrate = bitrate;
3166   GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
3167 }
3168
3169 /**
3170  * gst_base_parse_set_min_frame_size:
3171  * @parse: #GstBaseParse.
3172  * @min_size: Minimum size of the data that this base class should give to
3173  *            subclass.
3174  *
3175  * Subclass can use this function to tell the base class that it needs to
3176  * give at least #min_size buffers.
3177  *
3178  * Since: 0.10.33
3179  */
3180 void
3181 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
3182 {
3183   g_return_if_fail (parse != NULL);
3184
3185   parse->priv->min_frame_size = min_size;
3186   GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
3187 }
3188
3189 /**
3190  * gst_base_parse_set_frame_rate:
3191  * @parse: the #GstBaseParse to set
3192  * @fps_num: frames per second (numerator).
3193  * @fps_den: frames per second (denominator).
3194  * @lead_in: frames needed before a segment for subsequent decode
3195  * @lead_out: frames needed after a segment
3196  *
3197  * If frames per second is configured, parser can take care of buffer duration
3198  * and timestamping.  When performing segment clipping, or seeking to a specific
3199  * location, a corresponding decoder might need an initial @lead_in and a
3200  * following @lead_out number of frames to ensure the desired segment is
3201  * entirely filled upon decoding.
3202  *
3203  * Since: 0.10.33
3204  */
3205 void
3206 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
3207     guint fps_den, guint lead_in, guint lead_out)
3208 {
3209   g_return_if_fail (parse != NULL);
3210
3211   parse->priv->fps_num = fps_num;
3212   parse->priv->fps_den = fps_den;
3213   if (!fps_num || !fps_den) {
3214     GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
3215         fps_num, fps_den);
3216     fps_num = fps_den = 0;
3217     parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
3218     parse->priv->lead_in = parse->priv->lead_out = 0;
3219     parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
3220   } else {
3221     parse->priv->frame_duration =
3222         gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
3223     parse->priv->lead_in = lead_in;
3224     parse->priv->lead_out = lead_out;
3225     parse->priv->lead_in_ts =
3226         gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
3227     parse->priv->lead_out_ts =
3228         gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
3229     /* aim for about 1.5s to estimate duration */
3230     if (parse->priv->update_interval < 0) {
3231       parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
3232       GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
3233           parse->priv->update_interval);
3234     }
3235   }
3236   GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
3237       fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
3238   GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
3239       "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
3240       lead_in, parse->priv->lead_in_ts / GST_MSECOND,
3241       lead_out, parse->priv->lead_out_ts / GST_MSECOND);
3242 }
3243
3244 /**
3245  * gst_base_parse_set_has_timing_info:
3246  * @parse: a #GstBaseParse
3247  * @has_timing: whether frames carry timing information
3248  *
3249  * Set if frames carry timing information which the subclass can (generally)
3250  * parse and provide.  In particular, intrinsic (rather than estimated) time
3251  * can be obtained following a seek.
3252  *
3253  * Since: 0.10.33
3254  */
3255 void
3256 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3257 {
3258   parse->priv->has_timing_info = has_timing;
3259   GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3260 }
3261
3262 /**
3263  * gst_base_parse_set_syncable:
3264  * @parse: a #GstBaseParse
3265  * @syncable: set if frame starts can be identified
3266  *
3267  * Set if frame starts can be identified. This is set by default and
3268  * determines whether seeking based on bitrate averages
3269  * is possible for a format/stream.
3270  *
3271  * Since: 0.10.33
3272  */
3273 void
3274 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3275 {
3276   parse->priv->syncable = syncable;
3277   GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3278 }
3279
3280 /**
3281  * gst_base_parse_set_passthrough:
3282  * @parse: a #GstBaseParse
3283  * @passthrough: %TRUE if parser should run in passthrough mode
3284  *
3285  * Set if the nature of the format or configuration does not allow (much)
3286  * parsing, and the parser should operate in passthrough mode (which only
3287  * applies when operating in push mode). That is, incoming buffers are
3288  * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3289  * callbacks will be invoked, but @pre_push_frame will still be invoked,
3290  * so subclass can perform as much or as little is appropriate for
3291  * passthrough semantics in @pre_push_frame.
3292  *
3293  * Since: 0.10.33
3294  */
3295 void
3296 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3297 {
3298   parse->priv->passthrough = passthrough;
3299   GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3300 }
3301
3302 /**
3303  * gst_base_parse_set_latency:
3304  * @parse: a #GstBaseParse
3305  * @min_latency: minimum parse latency
3306  * @max_latency: maximum parse latency
3307  *
3308  * Sets the minimum and maximum (which may likely be equal) latency introduced
3309  * by the parsing process.  If there is such a latency, which depends on the
3310  * particular parsing of the format, it typically corresponds to 1 frame duration.
3311  *
3312  * Since: 0.10.36
3313  */
3314 void
3315 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3316     GstClockTime max_latency)
3317 {
3318   GST_OBJECT_LOCK (parse);
3319   parse->priv->min_latency = min_latency;
3320   parse->priv->max_latency = max_latency;
3321   GST_OBJECT_UNLOCK (parse);
3322   GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3323       GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3324       GST_TIME_ARGS (max_latency));
3325 }
3326
3327 static gboolean
3328 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3329     GstClockTime * duration)
3330 {
3331   gboolean res = FALSE;
3332
3333   g_return_val_if_fail (duration != NULL, FALSE);
3334
3335   *duration = GST_CLOCK_TIME_NONE;
3336   if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3337     GST_LOG_OBJECT (parse, "using provided duration");
3338     *duration = parse->priv->duration;
3339     res = TRUE;
3340   } else if (parse->priv->duration != -1) {
3341     GST_LOG_OBJECT (parse, "converting provided duration");
3342     res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3343         parse->priv->duration, format, (gint64 *) duration);
3344   } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3345     GST_LOG_OBJECT (parse, "using estimated duration");
3346     *duration = parse->priv->estimated_duration;
3347     res = TRUE;
3348   }
3349
3350   GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3351       GST_TIME_ARGS (*duration));
3352   return res;
3353 }
3354
3355 static gboolean
3356 gst_base_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
3357 {
3358   GstBaseParse *parse;
3359   gboolean res = FALSE;
3360
3361   parse = GST_BASE_PARSE (parent);
3362
3363   GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3364
3365   switch (GST_QUERY_TYPE (query)) {
3366     case GST_QUERY_POSITION:
3367     {
3368       gint64 dest_value;
3369       GstFormat format;
3370
3371       GST_DEBUG_OBJECT (parse, "position query");
3372       gst_query_parse_position (query, &format, NULL);
3373
3374       /* try upstream first */
3375       res = gst_pad_query_default (pad, parent, query);
3376       if (!res) {
3377         /* Fall back on interpreting segment */
3378         GST_OBJECT_LOCK (parse);
3379         if (format == GST_FORMAT_BYTES) {
3380           dest_value = parse->priv->offset;
3381           res = TRUE;
3382         } else if (format == parse->segment.format &&
3383             GST_CLOCK_TIME_IS_VALID (parse->segment.position)) {
3384           dest_value = gst_segment_to_stream_time (&parse->segment,
3385               parse->segment.format, parse->segment.position);
3386           res = TRUE;
3387         }
3388         GST_OBJECT_UNLOCK (parse);
3389         if (!res) {
3390           /* no precise result, upstream no idea either, then best estimate */
3391           /* priv->offset is updated in both PUSH/PULL modes */
3392           res = gst_base_parse_convert (parse,
3393               GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3394         }
3395         if (res)
3396           gst_query_set_position (query, format, dest_value);
3397       }
3398       break;
3399     }
3400     case GST_QUERY_DURATION:
3401     {
3402       GstFormat format;
3403       GstClockTime duration;
3404
3405       GST_DEBUG_OBJECT (parse, "duration query");
3406       gst_query_parse_duration (query, &format, NULL);
3407
3408       /* consult upstream */
3409       res = gst_pad_query_default (pad, parent, query);
3410
3411       /* otherwise best estimate from us */
3412       if (!res) {
3413         res = gst_base_parse_get_duration (parse, format, &duration);
3414         if (res)
3415           gst_query_set_duration (query, format, duration);
3416       }
3417       break;
3418     }
3419     case GST_QUERY_SEEKING:
3420     {
3421       GstFormat fmt;
3422       GstClockTime duration = GST_CLOCK_TIME_NONE;
3423       gboolean seekable = FALSE;
3424
3425       GST_DEBUG_OBJECT (parse, "seeking query");
3426       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3427
3428       /* consult upstream */
3429       res = gst_pad_query_default (pad, parent, query);
3430
3431       /* we may be able to help if in TIME */
3432       if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3433         gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3434         /* already OK if upstream takes care */
3435         GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3436             res, seekable);
3437         if (!(res && seekable)) {
3438           if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3439               || duration == -1) {
3440             /* seekable if we still have a chance to get duration later on */
3441             seekable =
3442                 parse->priv->upstream_seekable && parse->priv->update_interval;
3443           } else {
3444             seekable = parse->priv->upstream_seekable;
3445             GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3446                 seekable);
3447           }
3448           gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3449           res = TRUE;
3450         }
3451       }
3452       break;
3453     }
3454     case GST_QUERY_FORMATS:
3455       gst_query_set_formatsv (query, 3, fmtlist);
3456       res = TRUE;
3457       break;
3458     case GST_QUERY_CONVERT:
3459     {
3460       GstFormat src_format, dest_format;
3461       gint64 src_value, dest_value;
3462
3463       gst_query_parse_convert (query, &src_format, &src_value,
3464           &dest_format, &dest_value);
3465
3466       res = gst_base_parse_convert (parse, src_format, src_value,
3467           dest_format, &dest_value);
3468       if (res) {
3469         gst_query_set_convert (query, src_format, src_value,
3470             dest_format, dest_value);
3471       }
3472       break;
3473     }
3474     case GST_QUERY_LATENCY:
3475     {
3476       if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3477         gboolean live;
3478         GstClockTime min_latency, max_latency;
3479
3480         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3481         GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3482             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3483             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3484
3485         GST_OBJECT_LOCK (parse);
3486         /* add our latency */
3487         if (min_latency != -1)
3488           min_latency += parse->priv->min_latency;
3489         if (max_latency != -1)
3490           max_latency += parse->priv->max_latency;
3491         GST_OBJECT_UNLOCK (parse);
3492
3493         gst_query_set_latency (query, live, min_latency, max_latency);
3494       }
3495       break;
3496     }
3497     default:
3498       res = gst_pad_query_default (pad, parent, query);
3499       break;
3500   }
3501   return res;
3502 }
3503
3504 /* scans for a cluster start from @pos,
3505  * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3506 static GstFlowReturn
3507 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3508     GstClockTime * time, GstClockTime * duration)
3509 {
3510   GstBaseParseClass *klass;
3511   gint64 orig_offset;
3512   gboolean orig_drain, orig_discont;
3513   GstFlowReturn ret = GST_FLOW_OK;
3514   GstBuffer *buf = NULL;
3515   GstBaseParseFrame frame;
3516
3517   g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3518   g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3519   g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3520
3521   klass = GST_BASE_PARSE_GET_CLASS (parse);
3522
3523   *time = GST_CLOCK_TIME_NONE;
3524   *duration = GST_CLOCK_TIME_NONE;
3525
3526   /* save state */
3527   orig_offset = parse->priv->offset;
3528   orig_discont = parse->priv->discont;
3529   orig_drain = parse->priv->drain;
3530
3531   GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3532       " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3533
3534   gst_base_parse_frame_init (&frame);
3535
3536   /* jump elsewhere and locate next frame */
3537   parse->priv->offset = *pos;
3538   ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3539   if (ret != GST_FLOW_OK)
3540     goto done;
3541
3542   buf = frame.buffer;
3543   GST_LOG_OBJECT (parse,
3544       "peek parsing frame at offset %" G_GUINT64_FORMAT
3545       " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
3546       GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf),
3547       gst_buffer_get_size (buf));
3548
3549   /* get offset first, subclass parsing might dump other stuff in there */
3550   *pos = GST_BUFFER_OFFSET (buf);
3551   ret = klass->parse_frame (parse, &frame);
3552   buf = frame.buffer;
3553
3554   /* but it should provide proper time */
3555   *time = GST_BUFFER_TIMESTAMP (buf);
3556   *duration = GST_BUFFER_DURATION (buf);
3557
3558   gst_base_parse_frame_free (&frame);
3559
3560   GST_LOG_OBJECT (parse,
3561       "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3562       GST_TIME_ARGS (*time), *pos);
3563
3564 done:
3565   /* restore state */
3566   parse->priv->offset = orig_offset;
3567   parse->priv->discont = orig_discont;
3568   parse->priv->drain = orig_drain;
3569
3570   return ret;
3571 }
3572
3573 /* bisect and scan through file for frame starting before @time,
3574  * returns OK and @time/@offset if found, NONE and/or error otherwise
3575  * If @time == G_MAXINT64, scan for duration ( == last frame) */
3576 static GstFlowReturn
3577 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3578     gint64 * _offset)
3579 {
3580   GstFlowReturn ret = GST_FLOW_OK;
3581   gint64 lpos, hpos, newpos;
3582   GstClockTime time, ltime, htime, newtime, dur;
3583   gboolean cont = TRUE;
3584   const GstClockTime tolerance = TARGET_DIFFERENCE;
3585   const guint chunk = 4 * 1024;
3586
3587   g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3588   g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3589
3590   GST_DEBUG_OBJECT (parse, "Bisecting for time %" GST_TIME_FORMAT,
3591       GST_TIME_ARGS (*_time));
3592
3593   /* TODO also make keyframe aware if useful some day */
3594
3595   time = *_time;
3596
3597   /* basic cases */
3598   if (time == 0) {
3599     *_offset = 0;
3600     return GST_FLOW_OK;
3601   }
3602
3603   if (time == -1) {
3604     *_offset = -1;
3605     return GST_FLOW_OK;
3606   }
3607
3608   /* do not know at first */
3609   *_offset = -1;
3610   *_time = GST_CLOCK_TIME_NONE;
3611
3612   /* need initial positions; start and end */
3613   lpos = parse->priv->first_frame_offset;
3614   ltime = parse->priv->first_frame_ts;
3615   if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &htime)) {
3616     GST_DEBUG_OBJECT (parse, "Unknown time duration, cannot bisect");
3617     return GST_FLOW_ERROR;
3618   }
3619   hpos = parse->priv->upstream_size;
3620
3621   GST_DEBUG_OBJECT (parse,
3622       "Bisection initial bounds: bytes %" G_GINT64_FORMAT " %" G_GINT64_FORMAT
3623       ", times %" GST_TIME_FORMAT " %" GST_TIME_FORMAT, lpos, htime,
3624       GST_TIME_ARGS (ltime), GST_TIME_ARGS (htime));
3625
3626   /* check preconditions are satisfied;
3627    * start and end are needed, except for special case where we scan for
3628    * last frame to determine duration */
3629   if (parse->priv->pad_mode != GST_PAD_MODE_PULL || !hpos ||
3630       !GST_CLOCK_TIME_IS_VALID (ltime) ||
3631       (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3632     return GST_FLOW_OK;
3633   }
3634
3635   /* shortcut cases */
3636   if (time < ltime) {
3637     goto exit;
3638   } else if (time < ltime + tolerance) {
3639     *_offset = lpos;
3640     *_time = ltime;
3641     goto exit;
3642   } else if (time >= htime) {
3643     *_offset = hpos;
3644     *_time = htime;
3645     goto exit;
3646   }
3647
3648   while (htime > ltime && cont) {
3649     GST_LOG_OBJECT (parse,
3650         "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3651         GST_TIME_ARGS (ltime));
3652     GST_LOG_OBJECT (parse,
3653         "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3654         GST_TIME_ARGS (htime));
3655     if (G_UNLIKELY (time == G_MAXINT64)) {
3656       newpos = hpos;
3657     } else if (G_LIKELY (hpos > lpos)) {
3658       newpos =
3659           gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3660           lpos - chunk;
3661     } else {
3662       /* should mean lpos == hpos, since lpos <= hpos is invariant */
3663       newpos = lpos;
3664       /* we check this case once, but not forever, so break loop */
3665       cont = FALSE;
3666     }
3667
3668     /* ensure */
3669     newpos = CLAMP (newpos, lpos, hpos);
3670     GST_LOG_OBJECT (parse,
3671         "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3672         GST_TIME_ARGS (time), newpos);
3673
3674     ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3675     if (ret == GST_FLOW_EOS) {
3676       /* heuristic HACK */
3677       hpos = MAX (lpos, hpos - chunk);
3678       continue;
3679     } else if (ret != GST_FLOW_OK) {
3680       goto exit;
3681     }
3682
3683     if (newtime == -1 || newpos == -1) {
3684       GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3685       break;
3686     }
3687
3688     if (G_UNLIKELY (time == G_MAXINT64)) {
3689       *_offset = newpos;
3690       *_time = newtime;
3691       if (GST_CLOCK_TIME_IS_VALID (dur))
3692         *_time += dur;
3693       break;
3694     } else if (newtime > time) {
3695       /* overshoot */
3696       hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3697       htime = newtime;
3698     } else if (newtime + tolerance > time) {
3699       /* close enough undershoot */
3700       *_offset = newpos;
3701       *_time = newtime;
3702       break;
3703     } else if (newtime < ltime) {
3704       /* so a position beyond lpos resulted in earlier time than ltime ... */
3705       GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3706       break;
3707     } else {
3708       /* undershoot too far */
3709       newpos += newpos == lpos ? chunk : 0;
3710       lpos = CLAMP (newpos, lpos, hpos);
3711       ltime = newtime;
3712     }
3713   }
3714
3715 exit:
3716   GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3717       GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3718   return ret;
3719 }
3720
3721 static gint64
3722 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3723     gboolean before, GstClockTime * _ts)
3724 {
3725   gint64 bytes = 0, ts = 0;
3726   GstIndexEntry *entry = NULL;
3727
3728   if (time == GST_CLOCK_TIME_NONE) {
3729     ts = time;
3730     bytes = -1;
3731     goto exit;
3732   }
3733
3734   GST_BASE_PARSE_INDEX_LOCK (parse);
3735   if (parse->priv->index) {
3736     /* Let's check if we have an index entry for that time */
3737     entry = gst_index_get_assoc_entry (parse->priv->index,
3738         parse->priv->index_id,
3739         before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3740         GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3741   }
3742
3743   if (entry) {
3744     gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3745     gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3746
3747     GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3748         " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3749         GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3750   } else {
3751     GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3752         GST_TIME_ARGS (time));
3753     if (!before) {
3754       bytes = -1;
3755       ts = GST_CLOCK_TIME_NONE;
3756     }
3757   }
3758   GST_BASE_PARSE_INDEX_UNLOCK (parse);
3759
3760 exit:
3761   if (_ts)
3762     *_ts = ts;
3763
3764   return bytes;
3765 }
3766
3767 /* returns TRUE if seek succeeded */
3768 static gboolean
3769 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3770 {
3771   gdouble rate;
3772   GstFormat format;
3773   GstSeekFlags flags;
3774   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3775   gboolean flush, update, res = TRUE, accurate;
3776   gint64 cur, stop, seekpos, seekstop;
3777   GstSegment seeksegment = { 0, };
3778   GstClockTime start_ts;
3779
3780   gst_event_parse_seek (event, &rate, &format, &flags,
3781       &cur_type, &cur, &stop_type, &stop);
3782
3783   GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3784       "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3785       GST_TIME_FORMAT, gst_format_get_name (format), rate,
3786       cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3787
3788   /* no negative rates in push mode */
3789   if (rate < 0.0 && parse->priv->pad_mode == GST_PAD_MODE_PUSH)
3790     goto negative_rate;
3791
3792   if (cur_type != GST_SEEK_TYPE_SET ||
3793       (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3794     goto wrong_type;
3795
3796   /* For any format other than TIME, see if upstream handles
3797    * it directly or fail. For TIME, try upstream, but do it ourselves if
3798    * it fails upstream */
3799   if (format != GST_FORMAT_TIME) {
3800     /* default action delegates to upstream */
3801     res = FALSE;
3802     goto done;
3803   } else {
3804     gst_event_ref (event);
3805     if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3806       goto done;
3807     }
3808   }
3809
3810   /* get flush flag */
3811   flush = flags & GST_SEEK_FLAG_FLUSH;
3812
3813   /* copy segment, we need this because we still need the old
3814    * segment when we close the current segment. */
3815   gst_segment_copy_into (&parse->segment, &seeksegment);
3816
3817   GST_DEBUG_OBJECT (parse, "configuring seek");
3818   gst_segment_do_seek (&seeksegment, rate, format, flags,
3819       cur_type, cur, stop_type, stop, &update);
3820
3821   /* accurate seeking implies seek tables are used to obtain position,
3822    * and the requested segment is maintained exactly, not adjusted any way */
3823   accurate = flags & GST_SEEK_FLAG_ACCURATE;
3824
3825   /* maybe we can be accurate for (almost) free */
3826   gst_base_parse_find_offset (parse, seeksegment.position, TRUE, &start_ts);
3827   if (seeksegment.position <= start_ts + TARGET_DIFFERENCE) {
3828     GST_DEBUG_OBJECT (parse, "accurate seek possible");
3829     accurate = TRUE;
3830   }
3831   if (accurate) {
3832     GstClockTime startpos = seeksegment.position;
3833
3834     /* accurate requested, so ... seek a bit before target */
3835     if (startpos < parse->priv->lead_in_ts)
3836       startpos = 0;
3837     else
3838       startpos -= parse->priv->lead_in_ts;
3839     seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3840     seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3841         NULL);
3842   } else {
3843     start_ts = seeksegment.position;
3844     if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.position,
3845             GST_FORMAT_BYTES, &seekpos))
3846       goto convert_failed;
3847     if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3848             GST_FORMAT_BYTES, &seekstop))
3849       goto convert_failed;
3850   }
3851
3852   GST_DEBUG_OBJECT (parse,
3853       "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3854       start_ts, seekpos);
3855   GST_DEBUG_OBJECT (parse,
3856       "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3857       seeksegment.stop, seekstop);
3858
3859   if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
3860     gint64 last_stop;
3861
3862     GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3863
3864     if (flush) {
3865       if (parse->srcpad) {
3866         GST_DEBUG_OBJECT (parse, "sending flush start");
3867         gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3868         /* unlock upstream pull_range */
3869         gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3870       }
3871     } else {
3872       gst_pad_pause_task (parse->sinkpad);
3873     }
3874
3875     /* we should now be able to grab the streaming thread because we stopped it
3876      * with the above flush/pause code */
3877     GST_PAD_STREAM_LOCK (parse->sinkpad);
3878
3879     /* save current position */
3880     last_stop = parse->segment.position;
3881     GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3882         last_stop);
3883
3884     /* now commit to new position */
3885
3886     /* prepare for streaming again */
3887     if (flush) {
3888       GST_DEBUG_OBJECT (parse, "sending flush stop");
3889       gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop (TRUE));
3890       gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop (TRUE));
3891       gst_base_parse_clear_queues (parse);
3892     } else {
3893       /* keep track of our position */
3894       seeksegment.base = gst_segment_to_running_time (&seeksegment,
3895           seeksegment.format, parse->segment.position);
3896     }
3897
3898     memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3899
3900     /* store the newsegment event so it can be sent from the streaming thread. */
3901     if (parse->priv->pending_segment)
3902       gst_event_unref (parse->priv->pending_segment);
3903
3904     /* This will be sent later in _loop() */
3905     parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
3906
3907     GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3908         "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3909         ", pos = %" GST_TIME_FORMAT, format,
3910         GST_TIME_ARGS (parse->segment.start),
3911         GST_TIME_ARGS (parse->segment.stop),
3912         GST_TIME_ARGS (parse->segment.start));
3913
3914     /* one last chance in pull mode to stay accurate;
3915      * maybe scan and subclass can find where to go */
3916     if (!accurate) {
3917       gint64 scanpos;
3918       GstClockTime ts = seeksegment.position;
3919
3920       gst_base_parse_locate_time (parse, &ts, &scanpos);
3921       if (scanpos >= 0) {
3922         accurate = TRUE;
3923         seekpos = scanpos;
3924         /* running collected index now consists of several intervals,
3925          * so optimized check no longer possible */
3926         parse->priv->index_last_valid = FALSE;
3927         parse->priv->index_last_offset = 0;
3928         parse->priv->index_last_ts = 0;
3929       }
3930     }
3931
3932     /* mark discont if we are going to stream from another position. */
3933     if (seekpos != parse->priv->offset) {
3934       GST_DEBUG_OBJECT (parse,
3935           "mark DISCONT, we did a seek to another position");
3936       parse->priv->offset = seekpos;
3937       parse->priv->last_offset = seekpos;
3938       parse->priv->seen_keyframe = FALSE;
3939       parse->priv->discont = TRUE;
3940       parse->priv->next_ts = start_ts;
3941       parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3942       parse->priv->sync_offset = seekpos;
3943       parse->priv->exact_position = accurate;
3944     }
3945
3946     /* Start streaming thread if paused */
3947     gst_pad_start_task (parse->sinkpad,
3948         (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3949
3950     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3951
3952     /* handled seek */
3953     res = TRUE;
3954   } else {
3955     GstEvent *new_event;
3956     GstBaseParseSeek *seek;
3957     GstSeekFlags flags = (flush ? GST_SEEK_FLAG_FLUSH : GST_SEEK_FLAG_NONE);
3958
3959     /* The only thing we need to do in PUSH-mode is to send the
3960        seek event (in bytes) to upstream. Segment / flush handling happens
3961        in corresponding src event handlers */
3962     GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3963     if (seekstop >= 0 && seekstop <= seekpos)
3964       seekstop = seekpos;
3965     new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
3966         GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3967
3968     /* store segment info so its precise details can be reconstructed when
3969      * receiving newsegment;
3970      * this matters for all details when accurate seeking,
3971      * is most useful to preserve NONE stop time otherwise */
3972     seek = g_new0 (GstBaseParseSeek, 1);
3973     seek->segment = seeksegment;
3974     seek->accurate = accurate;
3975     seek->offset = seekpos;
3976     seek->start_ts = start_ts;
3977     GST_OBJECT_LOCK (parse);
3978     /* less optimal, but preserves order */
3979     parse->priv->pending_seeks =
3980         g_slist_append (parse->priv->pending_seeks, seek);
3981     GST_OBJECT_UNLOCK (parse);
3982
3983     res = gst_pad_push_event (parse->sinkpad, new_event);
3984
3985     if (!res) {
3986       GST_OBJECT_LOCK (parse);
3987       parse->priv->pending_seeks =
3988           g_slist_remove (parse->priv->pending_seeks, seek);
3989       GST_OBJECT_UNLOCK (parse);
3990       g_free (seek);
3991     }
3992   }
3993
3994 done:
3995   /* handled event is ours to free */
3996   if (res)
3997     gst_event_unref (event);
3998   return res;
3999
4000   /* ERRORS */
4001 negative_rate:
4002   {
4003     GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
4004     res = FALSE;
4005     goto done;
4006   }
4007 wrong_type:
4008   {
4009     GST_DEBUG_OBJECT (parse, "unsupported seek type.");
4010     res = FALSE;
4011     goto done;
4012   }
4013 convert_failed:
4014   {
4015     GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
4016     res = FALSE;
4017     goto done;
4018   }
4019 }
4020
4021 /* Checks if bitrates are available from upstream tags so that we don't
4022  * override them later
4023  */
4024 static void
4025 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
4026 {
4027   GstTagList *taglist = NULL;
4028   guint tmp;
4029
4030   gst_event_parse_tag (event, &taglist);
4031
4032   if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
4033     GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
4034     parse->priv->post_min_bitrate = FALSE;
4035   }
4036   if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
4037     GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
4038     parse->priv->post_avg_bitrate = FALSE;
4039   }
4040   if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
4041     GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
4042     parse->priv->post_max_bitrate = FALSE;
4043   }
4044 }
4045
4046 #if 0
4047 static void
4048 gst_base_parse_set_index (GstElement * element, GstIndex * index)
4049 {
4050   GstBaseParse *parse = GST_BASE_PARSE (element);
4051
4052   GST_BASE_PARSE_INDEX_LOCK (parse);
4053   if (parse->priv->index)
4054     gst_object_unref (parse->priv->index);
4055   if (index) {
4056     parse->priv->index = gst_object_ref (index);
4057     gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
4058         &parse->priv->index_id);
4059     parse->priv->own_index = FALSE;
4060   } else {
4061     parse->priv->index = NULL;
4062   }
4063   GST_BASE_PARSE_INDEX_UNLOCK (parse);
4064 }
4065
4066 static GstIndex *
4067 gst_base_parse_get_index (GstElement * element)
4068 {
4069   GstBaseParse *parse = GST_BASE_PARSE (element);
4070   GstIndex *result = NULL;
4071
4072   GST_BASE_PARSE_INDEX_LOCK (parse);
4073   if (parse->priv->index)
4074     result = gst_object_ref (parse->priv->index);
4075   GST_BASE_PARSE_INDEX_UNLOCK (parse);
4076
4077   return result;
4078 }
4079 #endif
4080
4081 static GstStateChangeReturn
4082 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
4083 {
4084   GstBaseParse *parse;
4085   GstStateChangeReturn result;
4086
4087   parse = GST_BASE_PARSE (element);
4088
4089   switch (transition) {
4090     case GST_STATE_CHANGE_READY_TO_PAUSED:
4091       /* If this is our own index destroy it as the
4092        * old entries might be wrong for the new stream */
4093       GST_BASE_PARSE_INDEX_LOCK (parse);
4094       if (parse->priv->own_index) {
4095         gst_object_unref (parse->priv->index);
4096         parse->priv->index = NULL;
4097         parse->priv->own_index = FALSE;
4098       }
4099
4100       /* If no index was created, generate one */
4101       if (G_UNLIKELY (!parse->priv->index)) {
4102         GST_DEBUG_OBJECT (parse, "no index provided creating our own");
4103
4104         parse->priv->index = g_object_new (gst_mem_index_get_type (), NULL);
4105         gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
4106             &parse->priv->index_id);
4107         parse->priv->own_index = TRUE;
4108       }
4109       GST_BASE_PARSE_INDEX_UNLOCK (parse);
4110       break;
4111     default:
4112       break;
4113   }
4114
4115   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4116
4117   switch (transition) {
4118     case GST_STATE_CHANGE_PAUSED_TO_READY:
4119       gst_base_parse_reset (parse);
4120       break;
4121     default:
4122       break;
4123   }
4124
4125   return result;
4126 }