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