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