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