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