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