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