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