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