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