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