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