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