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