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