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