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