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