59169500525f469f98bddbab0a8dc6ada927ce1f
[platform/upstream/gstreamer.git] / libs / gst / base / gstbaseparse.c
1 /* GStreamer
2  * Copyright (C) 2008 Nokia Corporation. All rights reserved.
3  *   Contact: Stefan Kost <stefan.kost@nokia.com>
4  * Copyright (C) 2008 Sebastian Dröge <sebastian.droege@collabora.co.uk>.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /**
23  * SECTION:gstbaseparse
24  * @short_description: Base class for stream parsers
25  * @see_also: #GstBaseTransform
26  *
27  * This base class is for parser elements that process data and splits it
28  * into separate audio/video/whatever frames.
29  *
30  * It provides for:
31  * <itemizedlist>
32  *   <listitem><para>One sinkpad and one srcpad</para></listitem>
33  *   <listitem><para>Handles state changes</para></listitem>
34  *   <listitem><para>Does flushing</para></listitem>
35  *   <listitem><para>Push mode</para></listitem>
36  *   <listitem><para>Pull mode</para></listitem>
37  *   <listitem><para>Handles events (NEWSEGMENT/EOS/FLUSH)</para></listitem>
38  *   <listitem><para>Handles seeking in both modes</para></listitem>
39  *   <listitem><para>
40  *        Handles POSITION/DURATION/SEEKING/FORMAT/CONVERT queries
41  *   </para></listitem>
42  * </itemizedlist>
43  *
44  * The purpose of this base class is to provide a basic functionality of
45  * a parser and share a lot of rather complex code.
46  *
47  * Description of the parsing mechanism:
48  * <orderedlist>
49  * <listitem>
50  *   <itemizedlist><title>Set-up phase</title>
51  *   <listitem><para>
52  *     GstBaseParse class calls @set_sink_caps to inform the subclass about
53  *     incoming sinkpad caps. Subclass should set the srcpad caps accordingly.
54  *   </para></listitem>
55  *   <listitem><para>
56  *     GstBaseParse calls @start to inform subclass that data processing is
57  *     about to start now.
58  *   </para></listitem>
59  *   <listitem><para>
60  *      At least in this point subclass needs to tell the GstBaseParse class
61  *      how big data chunks it wants to receive (min_frame_size). It can do
62  *      this with @gst_base_parse_set_min_frame_size.
63  *   </para></listitem>
64  *   <listitem><para>
65  *      GstBaseParse class sets up appropriate data passing mode (pull/push)
66  *      and starts to process the data.
67  *   </para></listitem>
68  *   </itemizedlist>
69  * </listitem>
70  * <listitem>
71  *   <itemizedlist>
72  *   <title>Parsing phase</title>
73  *     <listitem><para>
74  *       GstBaseParse gathers at least min_frame_size bytes of data either
75  *       by pulling it from upstream or collecting buffers into internal
76  *       #GstAdapter.
77  *     </para></listitem>
78  *     <listitem><para>
79  *       A buffer of (at least) min_frame_size bytes is passed to subclass with
80  *       @check_valid_frame. Subclass checks the contents and returns TRUE
81  *       if the buffer contains a valid frame. It also needs to set the
82  *       @framesize according to the detected frame size. If buffer didn't
83  *       contain a valid frame, this call must return FALSE and optionally
84  *       set the @skipsize value to inform base class that how many bytes
85  *       it needs to skip in order to find a valid frame. @framesize can always
86  *       indicate a new minimum for current frame parsing.  The passed buffer
87  *       is read-only.  Note that @check_valid_frame might receive any small
88  *       amount of input data when leftover data is being drained (e.g. at EOS).
89  *     </para></listitem>
90  *     <listitem><para>
91  *       After valid frame is found, it will be passed again to subclass with
92  *       @parse_frame call. Now subclass is responsible for parsing the
93  *       frame contents and setting the caps, and buffer metadata (e.g.
94  *       buffer timestamp and duration, or keyframe if applicable).
95  *       (although the latter can also be done by GstBaseParse if it is
96  *       appropriately configured, see below).  Frame is provided with
97  *       timestamp derived from upstream (as much as generally possible),
98  *       duration obtained form configuration (see below), and offset
99  *       if meaningful (in pull mode).
100  *     </para></listitem>
101  *     <listitem><para>
102  *       Finally the buffer can be pushed downstream and parsing loop starts
103  *       over again.  Just prior to actually pushing the buffer in question,
104  *       it is passed to @pre_push_buffer which gives subclass yet one
105  *       last chance to examine buffer metadata, or to send some custom (tag)
106  *       events, or to perform custom (segment) filtering.
107  *     </para></listitem>
108  *     <listitem><para>
109  *       During the parsing process GstBaseParseClass will handle both srcpad and
110  *       sinkpad events. They will be passed to subclass if @event or
111  *       @src_event callbacks have been provided.
112  *     </para></listitem>
113  *   </itemizedlist>
114  * </listitem>
115  * <listitem>
116  *   <itemizedlist><title>Shutdown phase</title>
117  *   <listitem><para>
118  *     GstBaseParse class calls @stop to inform the subclass that data
119  *     parsing will be stopped.
120  *   </para></listitem>
121  *   </itemizedlist>
122  * </listitem>
123  * </orderedlist>
124  *
125  * Subclass is responsible for providing pad template caps for
126  * source and sink pads. The pads need to be named "sink" and "src". It also
127  * needs to set the fixed caps on srcpad, when the format is ensured (e.g.
128  * when base class calls subclass' @set_sink_caps function).
129  *
130  * This base class uses GST_FORMAT_DEFAULT as a meaning of frames. So,
131  * subclass conversion routine needs to know that conversion from
132  * GST_FORMAT_TIME to GST_FORMAT_DEFAULT must return the
133  * frame number that can be found from the given byte position.
134  *
135  * GstBaseParse uses subclasses conversion methods also for seeking (or otherwise
136  * uses its own default one, see also below).
137  *
138  * Subclass @start and @stop functions will be called to inform the beginning
139  * and end of data processing.
140  *
141  * Things that subclass need to take care of:
142  * <itemizedlist>
143  *   <listitem><para>Provide pad templates</para></listitem>
144  *   <listitem><para>
145  *      Fixate the source pad caps when appropriate
146  *   </para></listitem>
147  *   <listitem><para>
148  *      Inform base class how big data chunks should be retrieved. This is
149  *      done with @gst_base_parse_set_min_frame_size function.
150  *   </para></listitem>
151  *   <listitem><para>
152  *      Examine data chunks passed to subclass with @check_valid_frame
153  *      and tell if they contain a valid frame
154  *   </para></listitem>
155  *   <listitem><para>
156  *      Set the caps and timestamp to frame that is passed to subclass with
157  *      @parse_frame function.
158  *   </para></listitem>
159  *   <listitem><para>Provide conversion functions</para></listitem>
160  *   <listitem><para>
161  *      Update the duration information with @gst_base_parse_set_duration
162  *   </para></listitem>
163  *   <listitem><para>
164  *      Optionally passthrough using @gst_base_parse_set_format
165  *   </para></listitem>
166  *   <listitem><para>
167  *      Configure various baseparse parameters using @gst_base_parse_set_seek and
168  *      @gst_base_parse_set_frame_props.
169  *   </para></listitem>
170  *   <listitem><para>
171  *      In particular, if subclass is unable to determine a duration, but
172  *      parsing (or specs) yields a frames per seconds rate, then this can be
173  *      provided to GstBaseParse to enable it to cater for
174  *      buffer time metadata (which will be taken from upstream as much as possible).
175  *      Internally keeping track of frame durations and respective
176  *      sizes that have been pushed provides GstBaseParse with an estimated bitrate.
177  *      A default @convert (used if not overriden) will then use these
178  *      rates to perform obvious conversions.  These rates are also used to update
179  *      (estimated) duration at regular frame intervals.
180  *   </para></listitem>
181  * </itemizedlist>
182  *
183  */
184
185 /* TODO:
186  *  - In push mode provide a queue of adapter-"queued" buffers for upstream
187  *    buffer metadata
188  *  - Queue buffers/events until caps are set
189  */
190
191 #ifdef HAVE_CONFIG_H
192 #  include "config.h"
193 #endif
194
195 #include <stdlib.h>
196 #include <string.h>
197
198 #include <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_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 * aacparse)
1153 {
1154   GstPad *peer;
1155   GstBaseParse *parse;
1156
1157   parse = GST_BASE_PARSE (aacparse);
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_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_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 =
1603           gst_buffer_make_metadata_writable (queued_frame->buffer);
1604       gst_buffer_set_caps (queued_frame->buffer,
1605           GST_PAD_CAPS (GST_BASE_PARSE_SRC_PAD (parse)));
1606       gst_base_parse_push_frame (parse, queued_frame);
1607       gst_base_parse_frame_free (queued_frame);
1608     }
1609   }
1610
1611   return gst_base_parse_push_frame (parse, frame);
1612 }
1613
1614 /**
1615  * gst_base_parse_push_frame:
1616  * @parse: #GstBaseParse.
1617  * @frame: #GstBaseParseFrame.
1618  *
1619  * Pushes the frame downstream, sends any pending events and
1620  * does some timestamp and segment handling.
1621  *
1622  * This must be called with sinkpad STREAM_LOCK held.
1623  *
1624  * Returns: #GstFlowReturn
1625  *
1626  * Since: 0.10.33
1627  */
1628 GstFlowReturn
1629 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1630 {
1631   GstFlowReturn ret = GST_FLOW_OK;
1632   GstClockTime last_start = GST_CLOCK_TIME_NONE;
1633   GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1634   GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1635   GstBuffer *buffer;
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_SIZE (buffer),
1645       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1646       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1647
1648   /* update stats */
1649   parse->priv->bytecount += GST_BUFFER_SIZE (buffer);
1650   if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1651     parse->priv->framecount++;
1652     if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1653       parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1654     }
1655   }
1656   /* 0 means disabled */
1657   if (parse->priv->update_interval < 0)
1658     parse->priv->update_interval = 50;
1659   else if (parse->priv->update_interval > 0 &&
1660       (parse->priv->framecount % parse->priv->update_interval) == 0)
1661     gst_base_parse_update_duration (parse);
1662
1663   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1664     last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1665   if (last_start != GST_CLOCK_TIME_NONE
1666       && GST_BUFFER_DURATION_IS_VALID (buffer))
1667     last_stop = last_start + GST_BUFFER_DURATION (buffer);
1668
1669   /* should have caps by now */
1670   g_return_val_if_fail (GST_PAD_CAPS (parse->srcpad), GST_FLOW_ERROR);
1671
1672   /* segment adjustment magic; only if we are running the whole show */
1673   if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1674       (parse->priv->pad_mode == GST_ACTIVATE_PULL ||
1675           parse->priv->upstream_seekable)) {
1676     /* segment times are typically estimates,
1677      * actual frame data might lead subclass to different timestamps,
1678      * so override segment start from what is supplied there */
1679     if (G_UNLIKELY (parse->priv->pending_segment && !parse->priv->exact_position
1680             && GST_CLOCK_TIME_IS_VALID (last_start))) {
1681       gst_event_unref (parse->priv->pending_segment);
1682       parse->segment.start =
1683           MIN ((guint64) last_start, (guint64) parse->segment.stop);
1684       GST_DEBUG_OBJECT (parse,
1685           "adjusting pending segment start to %" GST_TIME_FORMAT,
1686           GST_TIME_ARGS (parse->segment.start));
1687       parse->priv->pending_segment =
1688           gst_event_new_new_segment (FALSE, parse->segment.rate,
1689           parse->segment.format, parse->segment.start,
1690           parse->segment.stop, parse->segment.start);
1691     }
1692     /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1693     if (GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop) &&
1694         GST_CLOCK_TIME_IS_VALID (last_start)) {
1695       GstClockTimeDiff diff;
1696
1697       /* only send newsegments with increasing start times,
1698        * otherwise if these go back and forth downstream (sinks) increase
1699        * accumulated time and running_time */
1700       diff = GST_CLOCK_DIFF (parse->segment.last_stop, last_start);
1701       if (G_UNLIKELY (diff > 2 * GST_SECOND
1702               && last_start > parse->segment.start
1703               && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
1704                   || last_start < parse->segment.stop))) {
1705         GST_DEBUG_OBJECT (parse,
1706             "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
1707             GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1708             "Sending updated NEWSEGMENT events", diff,
1709             GST_TIME_ARGS (parse->segment.last_stop),
1710             GST_TIME_ARGS (last_start));
1711         if (G_UNLIKELY (parse->priv->pending_segment)) {
1712           gst_event_unref (parse->priv->pending_segment);
1713           parse->segment.start = last_start;
1714           parse->priv->pending_segment =
1715               gst_event_new_new_segment (FALSE, parse->segment.rate,
1716               parse->segment.format, parse->segment.start,
1717               parse->segment.stop, parse->segment.start);
1718         } else {
1719           /* send newsegment events such that the gap is not accounted in
1720            * accum time, hence running_time */
1721           /* close ahead of gap */
1722           gst_pad_push_event (parse->srcpad,
1723               gst_event_new_new_segment (TRUE, parse->segment.rate,
1724                   parse->segment.format, parse->segment.last_stop,
1725                   parse->segment.last_stop, parse->segment.last_stop));
1726           /* skip gap */
1727           gst_pad_push_event (parse->srcpad,
1728               gst_event_new_new_segment (FALSE, parse->segment.rate,
1729                   parse->segment.format, last_start,
1730                   parse->segment.stop, last_start));
1731         }
1732         /* align segment view with downstream,
1733          * prevents double-counting accum when closing segment */
1734         gst_segment_set_newsegment (&parse->segment, FALSE,
1735             parse->segment.rate, parse->segment.format, last_start,
1736             parse->segment.stop, last_start);
1737         parse->segment.last_stop = last_start;
1738       }
1739     }
1740   }
1741
1742   /* and should then also be linked downstream, so safe to send some events */
1743   if (G_UNLIKELY (parse->priv->close_segment)) {
1744     /* only set up by loop */
1745     GST_DEBUG_OBJECT (parse, "loop sending close segment");
1746     gst_pad_push_event (parse->srcpad, parse->priv->close_segment);
1747     parse->priv->close_segment = NULL;
1748   }
1749   if (G_UNLIKELY (parse->priv->pending_segment)) {
1750     GST_DEBUG_OBJECT (parse, "%s push pending segment",
1751         parse->priv->pad_mode == GST_ACTIVATE_PULL ? "loop" : "chain");
1752     gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1753     parse->priv->pending_segment = NULL;
1754
1755     /* have caps; check identity */
1756     gst_base_parse_check_media (parse);
1757   }
1758
1759   /* update bitrates and optionally post corresponding tags
1760    * (following newsegment) */
1761   gst_base_parse_update_bitrates (parse, frame);
1762
1763   if (G_UNLIKELY (parse->priv->pending_events)) {
1764     GList *l;
1765
1766     for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1767       gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1768     }
1769     g_list_free (parse->priv->pending_events);
1770     parse->priv->pending_events = NULL;
1771   }
1772
1773   if (klass->pre_push_frame) {
1774     ret = klass->pre_push_frame (parse, frame);
1775   } else {
1776     frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
1777   }
1778
1779   /* take final ownership of frame buffer */
1780   buffer = frame->buffer;
1781   frame->buffer = NULL;
1782
1783   /* subclass must play nice */
1784   g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1785
1786   /* decorate */
1787   buffer = gst_buffer_make_metadata_writable (buffer);
1788   gst_buffer_set_caps (buffer, GST_PAD_CAPS (parse->srcpad));
1789
1790   parse->priv->seen_keyframe |= parse->priv->is_video &&
1791       !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1792
1793   if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
1794     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1795         GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
1796         GST_BUFFER_TIMESTAMP (buffer) >
1797         parse->segment.stop + parse->priv->lead_out_ts) {
1798       GST_LOG_OBJECT (parse, "Dropped frame, after segment");
1799       ret = GST_FLOW_UNEXPECTED;
1800     } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1801         GST_BUFFER_DURATION_IS_VALID (buffer) &&
1802         GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
1803         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
1804         parse->priv->lead_in_ts < parse->segment.start) {
1805       if (parse->priv->seen_keyframe) {
1806         GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
1807         ret = GST_FLOW_OK;
1808       } else {
1809         GST_LOG_OBJECT (parse, "Dropped frame, before segment");
1810         ret = GST_BASE_PARSE_FLOW_DROPPED;
1811       }
1812     } else {
1813       ret = GST_FLOW_OK;
1814     }
1815   }
1816
1817   if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1818     GST_LOG_OBJECT (parse, "frame (%d bytes) dropped",
1819         GST_BUFFER_SIZE (buffer));
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 (%d bytes) pushed: %s",
1826           GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
1827     } else {
1828       GST_LOG_OBJECT (parse, "frame (%d bytes) queued for now",
1829           GST_BUFFER_SIZE (buffer));
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 (%d bytes) not pushed: %s",
1837         GST_BUFFER_SIZE (buffer), 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_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_SIZE (buffer), GST_BUFFER_OFFSET (buffer));
2085     if (G_UNLIKELY (parse->priv->passthrough)) {
2086       frame->buffer = gst_buffer_make_metadata_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_peek (parse->priv->adapter, av);
2139       GST_BUFFER_DATA (tmpbuf) = (guint8 *) data;
2140       GST_BUFFER_SIZE (tmpbuf) = min_size;
2141       GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
2142       GST_BUFFER_FLAG_SET (tmpbuf, GST_MINI_OBJECT_FLAG_READONLY);
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_buffer_replace (&frame->buffer, NULL);
2153       if (res) {
2154         if (gst_adapter_available (parse->priv->adapter) < fsize) {
2155           GST_DEBUG_OBJECT (parse,
2156               "found valid frame but not enough data available (only %d bytes)",
2157               gst_adapter_available (parse->priv->adapter));
2158           gst_buffer_unref (tmpbuf);
2159           goto done;
2160         }
2161         GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2162         break;
2163       }
2164       if (skip == -1) {
2165         /* subclass didn't touch this value. By default we skip 1 byte */
2166         skip = 1;
2167       }
2168       if (skip > 0) {
2169         GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2170         if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2171           /* reverse playback, and no frames found yet, so we are skipping
2172            * the leading part of a fragment, which may form the tail of
2173            * fragment coming later, hopefully subclass skips efficiently ... */
2174           timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2175           outbuf = gst_adapter_take_buffer (parse->priv->adapter, skip);
2176           outbuf = gst_buffer_make_metadata_writable (outbuf);
2177           GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
2178           parse->priv->buffers_pending =
2179               g_slist_prepend (parse->priv->buffers_pending, outbuf);
2180           outbuf = NULL;
2181         } else {
2182           gst_adapter_flush (parse->priv->adapter, skip);
2183         }
2184         parse->priv->offset += skip;
2185         if (!parse->priv->discont)
2186           parse->priv->sync_offset = parse->priv->offset;
2187         parse->priv->discont = TRUE;
2188         /* something changed least; nullify loop check */
2189         old_min_size = 0;
2190       }
2191       /* skip == 0 should imply subclass set min_size to need more data;
2192        * we check this shortly */
2193       if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2194         gst_buffer_unref (tmpbuf);
2195         goto done;
2196       }
2197     }
2198     gst_buffer_unref (tmpbuf);
2199     tmpbuf = NULL;
2200
2201     if (skip > 0) {
2202       /* Subclass found the sync, but still wants to skip some data */
2203       GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
2204       gst_adapter_flush (parse->priv->adapter, skip);
2205       parse->priv->offset += skip;
2206     }
2207
2208     /* Grab lock to prevent a race with FLUSH_START handler */
2209     GST_PAD_STREAM_LOCK (parse->srcpad);
2210
2211     /* FLUSH_START event causes the "flushing" flag to be set. In this
2212      * case we can leave the frame pushing loop */
2213     if (parse->priv->flushing) {
2214       GST_PAD_STREAM_UNLOCK (parse->srcpad);
2215       break;
2216     }
2217
2218     /* move along with upstream timestamp (if any),
2219      * but interpolate in between */
2220     timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2221     if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2222         (parse->priv->prev_ts != timestamp)) {
2223       parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2224     }
2225
2226     /* FIXME: Would it be more efficient to make a subbuffer instead? */
2227     outbuf = gst_adapter_take_buffer (parse->priv->adapter, fsize);
2228     outbuf = gst_buffer_make_metadata_writable (outbuf);
2229
2230     /* Subclass may want to know the data offset */
2231     GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2232     parse->priv->offset += fsize;
2233     GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2234     GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
2235
2236     frame->buffer = outbuf;
2237     ret = gst_base_parse_handle_and_push_frame (parse, bclass, frame);
2238     GST_PAD_STREAM_UNLOCK (parse->srcpad);
2239
2240     if (ret != GST_FLOW_OK) {
2241       GST_LOG_OBJECT (parse, "push returned %d", ret);
2242       break;
2243     }
2244   }
2245
2246 done:
2247   GST_LOG_OBJECT (parse, "chain leaving");
2248   return ret;
2249
2250   /* ERRORS */
2251 invalid_min:
2252   {
2253     GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2254         ("min_size evolution %d -> %d; breaking to avoid looping",
2255             old_min_size, min_size));
2256     return GST_FLOW_ERROR;
2257   }
2258 }
2259
2260 /* pull @size bytes at current offset,
2261  * i.e. at least try to and possibly return a shorter buffer if near the end */
2262 static GstFlowReturn
2263 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2264     GstBuffer ** buffer)
2265 {
2266   GstFlowReturn ret = GST_FLOW_OK;
2267
2268   g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2269
2270   /* Caching here actually makes much less difference than one would expect.
2271    * We do it mainly to avoid pulling buffers of 1 byte all the time */
2272   if (parse->priv->cache) {
2273     gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2274     gint cache_size = GST_BUFFER_SIZE (parse->priv->cache);
2275
2276     if (cache_offset <= parse->priv->offset &&
2277         (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2278       *buffer = gst_buffer_create_sub (parse->priv->cache,
2279           parse->priv->offset - cache_offset, size);
2280       GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2281       return GST_FLOW_OK;
2282     }
2283     /* not enough data in the cache, free cache and get a new one */
2284     gst_buffer_unref (parse->priv->cache);
2285     parse->priv->cache = NULL;
2286   }
2287
2288   /* refill the cache */
2289   ret =
2290       gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2291           64 * 1024), &parse->priv->cache);
2292   if (ret != GST_FLOW_OK) {
2293     parse->priv->cache = NULL;
2294     return ret;
2295   }
2296
2297   if (GST_BUFFER_SIZE (parse->priv->cache) >= size) {
2298     *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
2299     GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2300     return GST_FLOW_OK;
2301   }
2302
2303   /* Not possible to get enough data, try a last time with
2304    * requesting exactly the size we need */
2305   gst_buffer_unref (parse->priv->cache);
2306   parse->priv->cache = NULL;
2307
2308   ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2309       &parse->priv->cache);
2310
2311   if (ret != GST_FLOW_OK) {
2312     GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2313     *buffer = NULL;
2314     return ret;
2315   }
2316
2317   if (GST_BUFFER_SIZE (parse->priv->cache) < size) {
2318     GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2319         G_GUINT64_FORMAT ": wanted %u bytes, got %u bytes", parse->priv->offset,
2320         size, GST_BUFFER_SIZE (parse->priv->cache));
2321
2322     *buffer = parse->priv->cache;
2323     parse->priv->cache = NULL;
2324
2325     return GST_FLOW_OK;
2326   }
2327
2328   *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
2329   GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2330
2331   return GST_FLOW_OK;
2332 }
2333
2334 static GstFlowReturn
2335 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2336 {
2337   gint64 offset = 0;
2338   GstClockTime ts = 0;
2339   GstBuffer *buffer;
2340   GstFlowReturn ret;
2341
2342   GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2343       ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2344       parse->priv->last_offset);
2345
2346   if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2347     GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2348         GST_TIME_ARGS (parse->segment.start));
2349     ret = GST_FLOW_UNEXPECTED;
2350     goto exit;
2351   }
2352
2353   /* last fragment started at last_offset / last_ts;
2354    * seek back 10s capped at 1MB */
2355   if (parse->priv->last_ts >= 10 * GST_SECOND)
2356     ts = parse->priv->last_ts - 10 * GST_SECOND;
2357   /* if we are exact now, we will be more so going backwards */
2358   if (parse->priv->exact_position) {
2359     offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2360   } else {
2361     GstFormat dstformat = GST_FORMAT_BYTES;
2362
2363     if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2364             &dstformat, &offset)) {
2365       GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2366     }
2367   }
2368   offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2369       parse->priv->last_offset - 1024);
2370   offset = MAX (0, offset);
2371
2372   GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2373       offset);
2374   parse->priv->offset = offset;
2375
2376   ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2377       &buffer);
2378   if (ret != GST_FLOW_OK)
2379     goto exit;
2380
2381   /* offset will increase again as fragment is processed/parsed */
2382   parse->priv->last_offset = offset;
2383
2384   gst_adapter_push (parse->priv->adapter, buffer);
2385   ret = gst_base_parse_process_fragment (parse, FALSE);
2386   if (ret != GST_FLOW_OK)
2387     goto exit;
2388
2389   /* force previous fragment */
2390   parse->priv->offset = -1;
2391
2392 exit:
2393   return ret;
2394 }
2395
2396 /* PULL mode:
2397  * pull and scan for next frame starting from current offset
2398  * ajusts sync, drain and offset going along */
2399 static GstFlowReturn
2400 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2401     GstBaseParseFrame * frame, gboolean full)
2402 {
2403   GstBuffer *buffer, *outbuf;
2404   GstFlowReturn ret = GST_FLOW_OK;
2405   guint fsize = 1, min_size, old_min_size = 0;
2406   gint skip = 0;
2407
2408   g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2409
2410   GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2411       " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2412
2413   while (TRUE) {
2414     gboolean res;
2415
2416     min_size = MAX (parse->priv->min_frame_size, fsize);
2417     /* loop safety check */
2418     if (G_UNLIKELY (old_min_size >= min_size))
2419       goto invalid_min;
2420     old_min_size = min_size;
2421
2422     ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2423     if (ret != GST_FLOW_OK)
2424       goto done;
2425
2426     if (parse->priv->discont) {
2427       GST_DEBUG_OBJECT (parse, "marking DISCONT");
2428       GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2429     }
2430
2431     /* if we got a short read, inform subclass we are draining leftover
2432      * and no more is to be expected */
2433     if (GST_BUFFER_SIZE (buffer) < min_size)
2434       parse->priv->drain = TRUE;
2435
2436     skip = -1;
2437     gst_base_parse_frame_update (parse, frame, buffer);
2438     res = klass->check_valid_frame (parse, frame, &fsize, &skip);
2439     gst_buffer_replace (&frame->buffer, NULL);
2440     if (res) {
2441       parse->priv->drain = FALSE;
2442       GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2443       break;
2444     }
2445     parse->priv->drain = FALSE;
2446     if (skip == -1)
2447       skip = 1;
2448     if (skip > 0) {
2449       GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2450       if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2451         /* reverse playback, and no frames found yet, so we are skipping
2452          * the leading part of a fragment, which may form the tail of
2453          * fragment coming later, hopefully subclass skips efficiently ... */
2454         outbuf = gst_buffer_create_sub (buffer, 0, skip);
2455         parse->priv->buffers_pending =
2456             g_slist_prepend (parse->priv->buffers_pending, outbuf);
2457         outbuf = NULL;
2458       }
2459       parse->priv->offset += skip;
2460       if (!parse->priv->discont)
2461         parse->priv->sync_offset = parse->priv->offset;
2462       parse->priv->discont = TRUE;
2463       /* something changed least; nullify loop check */
2464       old_min_size = 0;
2465     }
2466     /* skip == 0 should imply subclass set min_size to need more data;
2467      * we check this shortly */
2468     GST_DEBUG_OBJECT (parse, "finding sync...");
2469     gst_buffer_unref (buffer);
2470     if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2471       goto done;
2472     }
2473   }
2474
2475   /* Does the subclass want to skip too? */
2476   if (skip > 0)
2477     parse->priv->offset += skip;
2478   else if (skip < 0)
2479     skip = 0;
2480
2481   if (fsize + skip <= GST_BUFFER_SIZE (buffer)) {
2482     outbuf = gst_buffer_create_sub (buffer, skip, fsize);
2483     GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2484     GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2485     gst_buffer_unref (buffer);
2486   } else {
2487     gst_buffer_unref (buffer);
2488     ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2489     if (ret != GST_FLOW_OK)
2490       goto done;
2491     if (GST_BUFFER_SIZE (outbuf) < fsize) {
2492       gst_buffer_unref (outbuf);
2493       ret = GST_FLOW_UNEXPECTED;
2494     }
2495   }
2496
2497   parse->priv->offset += fsize;
2498
2499   frame->buffer = outbuf;
2500
2501 done:
2502   return ret;
2503
2504   /* ERRORS */
2505 invalid_min:
2506   {
2507     GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2508         ("min_size evolution %d -> %d; breaking to avoid looping",
2509             old_min_size, min_size));
2510     return GST_FLOW_ERROR;
2511   }
2512 }
2513
2514 /* Loop that is used in pull mode to retrieve data from upstream */
2515 static void
2516 gst_base_parse_loop (GstPad * pad)
2517 {
2518   GstBaseParse *parse;
2519   GstBaseParseClass *klass;
2520   GstFlowReturn ret = GST_FLOW_OK;
2521   GstBaseParseFrame frame = { 0, };
2522
2523   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2524   klass = GST_BASE_PARSE_GET_CLASS (parse);
2525
2526   /* reverse playback:
2527    * first fragment (closest to stop time) is handled normally below,
2528    * then we pull in fragments going backwards */
2529   if (parse->segment.rate < 0.0) {
2530     /* check if we jumped back to a previous fragment,
2531      * which is a post-first fragment */
2532     if (parse->priv->offset < 0) {
2533       ret = gst_base_parse_handle_previous_fragment (parse);
2534       goto done;
2535     }
2536   }
2537
2538   ret = gst_base_parse_scan_frame (parse, klass, &frame, TRUE);
2539   if (ret != GST_FLOW_OK)
2540     goto done;
2541
2542   /* This always cleans up frame, even if error occurs */
2543   ret = gst_base_parse_handle_and_push_frame (parse, klass, &frame);
2544
2545   /* eat expected eos signalling past segment in reverse playback */
2546   if (parse->segment.rate < 0.0 && ret == GST_FLOW_UNEXPECTED &&
2547       parse->segment.last_stop >= parse->segment.stop) {
2548     GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2549     /* push what was accumulated during loop run */
2550     gst_base_parse_process_fragment (parse, TRUE);
2551     /* force previous fragment */
2552     parse->priv->offset = -1;
2553     ret = GST_FLOW_OK;
2554   }
2555
2556 done:
2557   if (ret == GST_FLOW_UNEXPECTED)
2558     goto eos;
2559   else if (ret != GST_FLOW_OK)
2560     goto pause;
2561
2562   gst_object_unref (parse);
2563   return;
2564
2565   /* ERRORS */
2566 eos:
2567   {
2568     ret = GST_FLOW_UNEXPECTED;
2569     GST_DEBUG_OBJECT (parse, "eos");
2570     /* fall-through */
2571   }
2572 pause:
2573   {
2574     gboolean push_eos = FALSE;
2575
2576     GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2577         gst_flow_get_name (ret));
2578     gst_pad_pause_task (parse->sinkpad);
2579
2580     if (ret == GST_FLOW_UNEXPECTED) {
2581       /* handle end-of-stream/segment */
2582       if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2583         gint64 stop;
2584
2585         if ((stop = parse->segment.stop) == -1)
2586           stop = parse->segment.duration;
2587
2588         GST_DEBUG_OBJECT (parse, "sending segment_done");
2589
2590         gst_element_post_message
2591             (GST_ELEMENT_CAST (parse),
2592             gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2593                 GST_FORMAT_TIME, stop));
2594       } else {
2595         /* If we STILL have zero frames processed, fire an error */
2596         if (parse->priv->framecount == 0) {
2597           GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2598               ("No valid frames found before end of stream"), (NULL));
2599         }
2600         push_eos = TRUE;
2601       }
2602     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
2603       /* for fatal errors we post an error message, wrong-state is
2604        * not fatal because it happens due to flushes and only means
2605        * that we should stop now. */
2606       GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2607           ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2608       push_eos = TRUE;
2609     }
2610     if (push_eos) {
2611       /* newsegment before eos */
2612       if (parse->priv->pending_segment) {
2613         gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
2614         parse->priv->pending_segment = NULL;
2615       }
2616       gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2617     }
2618     gst_object_unref (parse);
2619   }
2620 }
2621
2622 static gboolean
2623 gst_base_parse_sink_activate (GstPad * sinkpad)
2624 {
2625   GstBaseParse *parse;
2626   gboolean result = TRUE;
2627
2628   parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2629
2630   GST_DEBUG_OBJECT (parse, "sink activate");
2631
2632   if (gst_pad_check_pull_range (sinkpad)) {
2633     GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2634     result = gst_pad_activate_pull (sinkpad, TRUE);
2635   } else {
2636     GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
2637     result = gst_pad_activate_push (sinkpad, TRUE);
2638   }
2639
2640   GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
2641   gst_object_unref (parse);
2642   return result;
2643 }
2644
2645 static gboolean
2646 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
2647 {
2648   GstBaseParseClass *klass;
2649   gboolean result = FALSE;
2650
2651   GST_DEBUG_OBJECT (parse, "activate %d", active);
2652
2653   klass = GST_BASE_PARSE_GET_CLASS (parse);
2654
2655   if (active) {
2656     if (parse->priv->pad_mode == GST_ACTIVATE_NONE && klass->start)
2657       result = klass->start (parse);
2658   } else {
2659     /* We must make sure streaming has finished before resetting things
2660      * and calling the ::stop vfunc */
2661     GST_PAD_STREAM_LOCK (parse->sinkpad);
2662     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2663
2664     if (parse->priv->pad_mode != GST_ACTIVATE_NONE && klass->stop)
2665       result = klass->stop (parse);
2666
2667     parse->priv->pad_mode = GST_ACTIVATE_NONE;
2668   }
2669   GST_DEBUG_OBJECT (parse, "activate return: %d", result);
2670   return result;
2671 }
2672
2673 static gboolean
2674 gst_base_parse_sink_activate_push (GstPad * pad, gboolean active)
2675 {
2676   gboolean result = TRUE;
2677   GstBaseParse *parse;
2678
2679   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2680
2681   GST_DEBUG_OBJECT (parse, "sink activate push %d", active);
2682
2683   result = gst_base_parse_activate (parse, active);
2684
2685   if (result)
2686     parse->priv->pad_mode = active ? GST_ACTIVATE_PUSH : GST_ACTIVATE_NONE;
2687
2688   GST_DEBUG_OBJECT (parse, "sink activate push return: %d", result);
2689
2690   gst_object_unref (parse);
2691   return result;
2692 }
2693
2694 static gboolean
2695 gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
2696 {
2697   gboolean result = FALSE;
2698   GstBaseParse *parse;
2699
2700   parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2701
2702   GST_DEBUG_OBJECT (parse, "activate pull %d", active);
2703
2704   result = gst_base_parse_activate (parse, active);
2705
2706   if (result) {
2707     if (active) {
2708       parse->priv->pending_segment = gst_event_new_new_segment (FALSE,
2709           parse->segment.rate, parse->segment.format,
2710           parse->segment.start, parse->segment.stop, parse->segment.last_stop);
2711       result &=
2712           gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
2713           sinkpad);
2714     } else {
2715       result &= gst_pad_stop_task (sinkpad);
2716     }
2717   }
2718
2719   if (result)
2720     parse->priv->pad_mode = active ? GST_ACTIVATE_PULL : GST_ACTIVATE_NONE;
2721
2722   GST_DEBUG_OBJECT (parse, "sink activate pull return: %d", result);
2723
2724   gst_object_unref (parse);
2725   return result;
2726 }
2727
2728
2729 /**
2730  * gst_base_parse_set_duration:
2731  * @parse: #GstBaseParse.
2732  * @fmt: #GstFormat.
2733  * @duration: duration value.
2734  * @interval: how often to update the duration estimate based on bitrate, or 0.
2735  *
2736  * Sets the duration of the currently playing media. Subclass can use this
2737  * when it is able to determine duration and/or notices a change in the media
2738  * duration.  Alternatively, if @interval is non-zero (default), then stream
2739  * duration is determined based on estimated bitrate, and updated every @interval
2740  * frames.
2741  *
2742  * Since: 0.10.33
2743  */
2744 void
2745 gst_base_parse_set_duration (GstBaseParse * parse,
2746     GstFormat fmt, gint64 duration, gint interval)
2747 {
2748   g_return_if_fail (parse != NULL);
2749
2750   if (parse->priv->upstream_has_duration) {
2751     GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
2752     goto exit;
2753   }
2754
2755   if (duration != parse->priv->duration) {
2756     GstMessage *m;
2757
2758     m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
2759     gst_element_post_message (GST_ELEMENT (parse), m);
2760
2761     /* TODO: what about duration tag? */
2762   }
2763   parse->priv->duration = duration;
2764   parse->priv->duration_fmt = fmt;
2765   GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
2766   if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
2767     if (interval != 0) {
2768       GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
2769       interval = 0;
2770     }
2771   }
2772   GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
2773   parse->priv->update_interval = interval;
2774 exit:
2775   return;
2776 }
2777
2778 /**
2779  * gst_base_parse_set_average_bitrate:
2780  * @parse: #GstBaseParse.
2781  * @bitrate: average bitrate in bits/second
2782  *
2783  * Optionally sets the average bitrate detected in media (if non-zero),
2784  * e.g. based on metadata, as it will be posted to the application.
2785  *
2786  * By default, announced average bitrate is estimated. The average bitrate
2787  * is used to estimate the total duration of the stream and to estimate
2788  * a seek position, if there's no index and #GST_BASE_PARSE_FORMAT_FLAG_SYNCABLE
2789  * is set.
2790  *
2791  * Since: 0.10.33
2792  */
2793 void
2794 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
2795 {
2796   parse->priv->bitrate = bitrate;
2797   GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
2798 }
2799
2800 /**
2801  * gst_base_parse_set_min_frame_size:
2802  * @parse: #GstBaseParse.
2803  * @min_size: Minimum size of the data that this base class should give to
2804  *            subclass.
2805  *
2806  * Subclass can use this function to tell the base class that it needs to
2807  * give at least #min_size buffers.
2808  *
2809  * Since: 0.10.33
2810  */
2811 void
2812 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
2813 {
2814   g_return_if_fail (parse != NULL);
2815
2816   parse->priv->min_frame_size = min_size;
2817   GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
2818 }
2819
2820 /**
2821  * gst_base_parse_set_frame_props:
2822  * @parse: the #GstBaseParse to set
2823  * @fps_num: frames per second (numerator).
2824  * @fps_den: frames per second (denominator).
2825  * @lead_in: frames needed before a segment for subsequent decode
2826  * @lead_out: frames needed after a segment
2827  *
2828  * If frames per second is configured, parser can take care of buffer duration
2829  * and timestamping.  When performing segment clipping, or seeking to a specific
2830  * location, a corresponding decoder might need an initial @lead_in and a
2831  * following @lead_out number of frames to ensure the desired segment is
2832  * entirely filled upon decoding.
2833  *
2834  * Since: 0.10.33
2835  */
2836 void
2837 gst_base_parse_set_frame_props (GstBaseParse * parse, guint fps_num,
2838     guint fps_den, guint lead_in, guint lead_out)
2839 {
2840   g_return_if_fail (parse != NULL);
2841
2842   parse->priv->fps_num = fps_num;
2843   parse->priv->fps_den = fps_den;
2844   if (!fps_num || !fps_den) {
2845     GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
2846         fps_num, fps_den);
2847     fps_num = fps_den = 0;
2848     parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
2849     parse->priv->lead_in = parse->priv->lead_out = 0;
2850     parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
2851   } else {
2852     parse->priv->frame_duration =
2853         gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
2854     parse->priv->lead_in = lead_in;
2855     parse->priv->lead_out = lead_out;
2856     parse->priv->lead_in_ts =
2857         gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
2858     parse->priv->lead_out_ts =
2859         gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
2860     /* aim for about 1.5s to estimate duration */
2861     if (parse->priv->update_interval < 0) {
2862       parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
2863       GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
2864           parse->priv->update_interval);
2865     }
2866   }
2867   GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
2868       fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
2869   GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
2870       "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
2871       lead_in, parse->priv->lead_in_ts / GST_MSECOND,
2872       lead_out, parse->priv->lead_out_ts / GST_MSECOND);
2873 }
2874
2875 /**
2876  * gst_base_parse_set_has_timing_info:
2877  * @parse: a #GstBaseParse
2878  * @has_timing: whether frames carry timing information
2879  *
2880  * Set if frames carry timing information which the subclass can (generally)
2881  * parse and provide.  In particular, intrinsic (rather than estimated) time
2882  * can be obtained following a seek.
2883  *
2884  * Since: 0.10.33
2885  */
2886 void
2887 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
2888 {
2889   parse->priv->has_timing_info = has_timing;
2890   GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
2891 }
2892
2893 /**
2894  * gst_base_parse_set_syncable:
2895  * @parse: a #GstBaseParse
2896  * @syncable: set if frame starts can be identified
2897  *
2898  * Set if frame starts can be identified. This is set by default and
2899  * determines whether seeking based on bitrate averages
2900  * is possible for a format/stream.
2901  *
2902  * Since: 0.10.33
2903  */
2904 void
2905 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
2906 {
2907   parse->priv->syncable = syncable;
2908   GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
2909 }
2910
2911 /**
2912  * gst_base_parse_set_passthrough:
2913  * @parse: a #GstBaseParse
2914  * @passthrough:
2915  *
2916  * Set if the nature of the format or configuration does not allow (much)
2917  * parsing, and the parser should operate in passthrough mode (which only
2918  * applies when operating in push mode). That is, incoming buffers are
2919  * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
2920  * callbacks will be invoked, but @pre_push_buffer will still be invoked,
2921  * so subclass can perform as much or as little is appropriate for
2922  * passthrough semantics in @pre_push_buffer.
2923  *
2924  * Since: 0.10.33
2925  */
2926 void
2927 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
2928 {
2929   parse->priv->passthrough = passthrough;
2930   GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
2931 }
2932
2933 static gboolean
2934 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
2935     GstClockTime * duration)
2936 {
2937   gboolean res = FALSE;
2938
2939   g_return_val_if_fail (duration != NULL, FALSE);
2940
2941   *duration = GST_CLOCK_TIME_NONE;
2942   if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
2943     GST_LOG_OBJECT (parse, "using provided duration");
2944     *duration = parse->priv->duration;
2945     res = TRUE;
2946   } else if (parse->priv->duration != -1) {
2947     GST_LOG_OBJECT (parse, "converting provided duration");
2948     res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
2949         parse->priv->duration, format, (gint64 *) duration);
2950   } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
2951     GST_LOG_OBJECT (parse, "using estimated duration");
2952     *duration = parse->priv->estimated_duration;
2953     res = TRUE;
2954   }
2955
2956   GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
2957       GST_TIME_ARGS (*duration));
2958   return res;
2959 }
2960
2961 static const GstQueryType *
2962 gst_base_parse_get_querytypes (GstPad * pad)
2963 {
2964   static const GstQueryType list[] = {
2965     GST_QUERY_POSITION,
2966     GST_QUERY_DURATION,
2967     GST_QUERY_FORMATS,
2968     GST_QUERY_SEEKING,
2969     GST_QUERY_CONVERT,
2970     0
2971   };
2972
2973   return list;
2974 }
2975
2976 static gboolean
2977 gst_base_parse_query (GstPad * pad, GstQuery * query)
2978 {
2979   GstBaseParse *parse;
2980   gboolean res = FALSE;
2981
2982   parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
2983
2984   GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
2985
2986   switch (GST_QUERY_TYPE (query)) {
2987     case GST_QUERY_POSITION:
2988     {
2989       gint64 dest_value;
2990       GstFormat format;
2991
2992       GST_DEBUG_OBJECT (parse, "position query");
2993       gst_query_parse_position (query, &format, NULL);
2994
2995       GST_OBJECT_LOCK (parse);
2996       if (format == GST_FORMAT_BYTES) {
2997         dest_value = parse->priv->offset;
2998         res = TRUE;
2999       } else if (format == parse->segment.format &&
3000           GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop)) {
3001         dest_value = parse->segment.last_stop;
3002         res = TRUE;
3003       }
3004       GST_OBJECT_UNLOCK (parse);
3005
3006       if (res)
3007         gst_query_set_position (query, format, dest_value);
3008       else {
3009         res = gst_pad_query_default (pad, query);
3010         if (!res) {
3011           /* no precise result, upstream no idea either, then best estimate */
3012           /* priv->offset is updated in both PUSH/PULL modes */
3013           res = gst_base_parse_convert (parse,
3014               GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3015         }
3016       }
3017       break;
3018     }
3019     case GST_QUERY_DURATION:
3020     {
3021       GstFormat format;
3022       GstClockTime duration;
3023
3024       GST_DEBUG_OBJECT (parse, "duration query");
3025       gst_query_parse_duration (query, &format, NULL);
3026
3027       /* consult upstream */
3028       res = gst_pad_query_default (pad, query);
3029
3030       /* otherwise best estimate from us */
3031       if (!res) {
3032         res = gst_base_parse_get_duration (parse, format, &duration);
3033         if (res)
3034           gst_query_set_duration (query, format, duration);
3035       }
3036       break;
3037     }
3038     case GST_QUERY_SEEKING:
3039     {
3040       GstFormat fmt;
3041       GstClockTime duration = GST_CLOCK_TIME_NONE;
3042       gboolean seekable = FALSE;
3043
3044       GST_DEBUG_OBJECT (parse, "seeking query");
3045       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3046
3047       /* consult upstream */
3048       res = gst_pad_query_default (pad, query);
3049
3050       /* we may be able to help if in TIME */
3051       if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3052         gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3053         /* already OK if upstream takes care */
3054         GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3055             res, seekable);
3056         if (!(res && seekable)) {
3057           if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3058               || duration == -1) {
3059             /* seekable if we still have a chance to get duration later on */
3060             seekable =
3061                 parse->priv->upstream_seekable && parse->priv->update_interval;
3062           } else {
3063             seekable = parse->priv->upstream_seekable;
3064             GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3065                 seekable);
3066           }
3067           gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3068           res = TRUE;
3069         }
3070       }
3071       break;
3072     }
3073     case GST_QUERY_FORMATS:
3074       gst_query_set_formatsv (query, 3, fmtlist);
3075       res = TRUE;
3076       break;
3077     case GST_QUERY_CONVERT:
3078     {
3079       GstFormat src_format, dest_format;
3080       gint64 src_value, dest_value;
3081
3082       gst_query_parse_convert (query, &src_format, &src_value,
3083           &dest_format, &dest_value);
3084
3085       res = gst_base_parse_convert (parse, src_format, src_value,
3086           dest_format, &dest_value);
3087       if (res) {
3088         gst_query_set_convert (query, src_format, src_value,
3089             dest_format, dest_value);
3090       }
3091       break;
3092     }
3093     default:
3094       res = gst_pad_query_default (pad, query);
3095       break;
3096   }
3097   return res;
3098 }
3099
3100 /* scans for a cluster start from @pos,
3101  * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3102 static GstFlowReturn
3103 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3104     GstClockTime * time, GstClockTime * duration)
3105 {
3106   GstBaseParseClass *klass;
3107   gint64 orig_offset;
3108   gboolean orig_drain, orig_discont;
3109   GstFlowReturn ret = GST_FLOW_OK;
3110   GstBuffer *buf = NULL;
3111   GstBaseParseFrame frame = { 0, };
3112
3113   g_return_val_if_fail (GST_FLOW_ERROR, pos != NULL);
3114   g_return_val_if_fail (GST_FLOW_ERROR, time != NULL);
3115   g_return_val_if_fail (GST_FLOW_ERROR, duration != NULL);
3116
3117   klass = GST_BASE_PARSE_GET_CLASS (parse);
3118
3119   *time = GST_CLOCK_TIME_NONE;
3120   *duration = GST_CLOCK_TIME_NONE;
3121
3122   /* save state */
3123   orig_offset = parse->priv->offset;
3124   orig_discont = parse->priv->discont;
3125   orig_drain = parse->priv->drain;
3126
3127   GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3128       " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3129
3130   /* jump elsewhere and locate next frame */
3131   parse->priv->offset = *pos;
3132   ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3133   if (ret != GST_FLOW_OK)
3134     goto done;
3135
3136   buf = frame.buffer;
3137   GST_LOG_OBJECT (parse,
3138       "peek parsing frame at offset %" G_GUINT64_FORMAT
3139       " (%#" G_GINT64_MODIFIER "x) of size %d",
3140       GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf), GST_BUFFER_SIZE (buf));
3141
3142   /* get offset first, subclass parsing might dump other stuff in there */
3143   *pos = GST_BUFFER_OFFSET (buf);
3144   ret = klass->parse_frame (parse, &frame);
3145   buf = frame.buffer;
3146
3147   /* but it should provide proper time */
3148   *time = GST_BUFFER_TIMESTAMP (buf);
3149   *duration = GST_BUFFER_DURATION (buf);
3150   gst_base_parse_frame_clear (parse, &frame);
3151
3152   GST_LOG_OBJECT (parse,
3153       "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3154       GST_TIME_ARGS (*time), *pos);
3155
3156 done:
3157   /* restore state */
3158   parse->priv->offset = orig_offset;
3159   parse->priv->discont = orig_discont;
3160   parse->priv->drain = orig_drain;
3161
3162   return ret;
3163 }
3164
3165 /* bisect and scan through file for frame starting before @time,
3166  * returns OK and @time/@offset if found, NONE and/or error otherwise
3167  * If @time == G_MAXINT64, scan for duration ( == last frame) */
3168 static GstFlowReturn
3169 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3170     gint64 * _offset)
3171 {
3172   GstFlowReturn ret = GST_FLOW_OK;
3173   gint64 lpos, hpos, newpos;
3174   GstClockTime time, ltime, htime, newtime, dur;
3175   gboolean cont = TRUE;
3176   const GstClockTime tolerance = TARGET_DIFFERENCE;
3177   const guint chunk = 4 * 1024;
3178
3179   g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3180   g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3181
3182   /* TODO also make keyframe aware if useful some day */
3183
3184   time = *_time;
3185
3186   /* basic cases */
3187   if (time == 0) {
3188     *_offset = 0;
3189     return GST_FLOW_OK;
3190   }
3191
3192   if (time == -1) {
3193     *_offset = -1;
3194     return GST_FLOW_OK;
3195   }
3196
3197   /* do not know at first */
3198   *_offset = -1;
3199   *_time = GST_CLOCK_TIME_NONE;
3200
3201   /* need initial positions; start and end */
3202   lpos = parse->priv->first_frame_offset;
3203   ltime = parse->priv->first_frame_ts;
3204   htime = parse->priv->duration;
3205   hpos = parse->priv->upstream_size;
3206
3207   /* check preconditions are satisfied;
3208    * start and end are needed, except for special case where we scan for
3209    * last frame to determine duration */
3210   if (parse->priv->pad_mode != GST_ACTIVATE_PULL || !hpos ||
3211       !GST_CLOCK_TIME_IS_VALID (ltime) ||
3212       (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3213     return GST_FLOW_OK;
3214   }
3215
3216   /* shortcut cases */
3217   if (time < ltime) {
3218     goto exit;
3219   } else if (time < ltime + tolerance) {
3220     *_offset = lpos;
3221     *_time = ltime;
3222     goto exit;
3223   } else if (time >= htime) {
3224     *_offset = hpos;
3225     *_time = htime;
3226     goto exit;
3227   }
3228
3229   while (htime > ltime && cont) {
3230     GST_LOG_OBJECT (parse,
3231         "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3232         GST_TIME_ARGS (ltime));
3233     GST_LOG_OBJECT (parse,
3234         "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3235         GST_TIME_ARGS (htime));
3236     if (G_UNLIKELY (time == G_MAXINT64)) {
3237       newpos = hpos;
3238     } else if (G_LIKELY (hpos > lpos)) {
3239       newpos =
3240           gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3241           lpos - chunk;
3242     } else {
3243       /* should mean lpos == hpos, since lpos <= hpos is invariant */
3244       newpos = lpos;
3245       /* we check this case once, but not forever, so break loop */
3246       cont = FALSE;
3247     }
3248
3249     /* ensure */
3250     newpos = CLAMP (newpos, lpos, hpos);
3251     GST_LOG_OBJECT (parse,
3252         "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3253         GST_TIME_ARGS (time), newpos);
3254
3255     ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3256     if (ret == GST_FLOW_UNEXPECTED) {
3257       /* heuristic HACK */
3258       hpos = MAX (lpos, hpos - chunk);
3259       continue;
3260     } else if (ret != GST_FLOW_OK) {
3261       goto exit;
3262     }
3263
3264     if (newtime == -1 || newpos == -1) {
3265       GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3266       break;
3267     }
3268
3269     if (G_UNLIKELY (time == G_MAXINT64)) {
3270       *_offset = newpos;
3271       *_time = newtime;
3272       if (GST_CLOCK_TIME_IS_VALID (dur))
3273         *_time += dur;
3274       break;
3275     } else if (newtime > time) {
3276       /* overshoot */
3277       hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3278       htime = newtime;
3279     } else if (newtime + tolerance > time) {
3280       /* close enough undershoot */
3281       *_offset = newpos;
3282       *_time = newtime;
3283       break;
3284     } else if (newtime < ltime) {
3285       /* so a position beyond lpos resulted in earlier time than ltime ... */
3286       GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3287       break;
3288     } else {
3289       /* undershoot too far */
3290       newpos += newpos == lpos ? chunk : 0;
3291       lpos = CLAMP (newpos, lpos, hpos);
3292       ltime = newtime;
3293     }
3294   }
3295
3296 exit:
3297   GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3298       GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3299   return ret;
3300 }
3301
3302 static gint64
3303 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3304     gboolean before, GstClockTime * _ts)
3305 {
3306   gint64 bytes = 0, ts = 0;
3307   GstIndexEntry *entry = NULL;
3308
3309   if (time == GST_CLOCK_TIME_NONE) {
3310     ts = time;
3311     bytes = -1;
3312     goto exit;
3313   }
3314
3315   GST_OBJECT_LOCK (parse);
3316   if (parse->priv->index) {
3317     /* Let's check if we have an index entry for that time */
3318     entry = gst_index_get_assoc_entry (parse->priv->index,
3319         parse->priv->index_id,
3320         before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3321         GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3322   }
3323
3324   if (entry) {
3325     gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3326     gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3327
3328     GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3329         " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3330         GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3331   } else {
3332     GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3333         GST_TIME_ARGS (time));
3334     if (!before) {
3335       bytes = -1;
3336       ts = GST_CLOCK_TIME_NONE;
3337     }
3338   }
3339   GST_OBJECT_UNLOCK (parse);
3340
3341 exit:
3342   if (_ts)
3343     *_ts = ts;
3344
3345   return bytes;
3346 }
3347
3348 /* returns TRUE if seek succeeded */
3349 static gboolean
3350 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3351 {
3352   gdouble rate;
3353   GstFormat format;
3354   GstSeekFlags flags;
3355   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3356   gboolean flush, update, res = TRUE, accurate;
3357   gint64 cur, stop, seekpos, seekstop;
3358   GstSegment seeksegment = { 0, };
3359   GstFormat dstformat;
3360   GstClockTime start_ts;
3361
3362   gst_event_parse_seek (event, &rate, &format, &flags,
3363       &cur_type, &cur, &stop_type, &stop);
3364
3365   GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3366       "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3367       GST_TIME_FORMAT, gst_format_get_name (format), rate,
3368       cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3369
3370   /* no negative rates in push mode */
3371   if (rate < 0.0 && parse->priv->pad_mode == GST_ACTIVATE_PUSH)
3372     goto negative_rate;
3373
3374   if (cur_type != GST_SEEK_TYPE_SET ||
3375       (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3376     goto wrong_type;
3377
3378   /* For any format other than TIME, see if upstream handles
3379    * it directly or fail. For TIME, try upstream, but do it ourselves if
3380    * it fails upstream */
3381   if (format != GST_FORMAT_TIME) {
3382     /* default action delegates to upstream */
3383     res = FALSE;
3384     goto done;
3385   } else {
3386     gst_event_ref (event);
3387     if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3388       goto done;
3389     }
3390   }
3391
3392   /* get flush flag */
3393   flush = flags & GST_SEEK_FLAG_FLUSH;
3394
3395   /* copy segment, we need this because we still need the old
3396    * segment when we close the current segment. */
3397   memcpy (&seeksegment, &parse->segment, sizeof (GstSegment));
3398
3399   GST_DEBUG_OBJECT (parse, "configuring seek");
3400   gst_segment_set_seek (&seeksegment, rate, format, flags,
3401       cur_type, cur, stop_type, stop, &update);
3402
3403   /* accurate seeking implies seek tables are used to obtain position,
3404    * and the requested segment is maintained exactly, not adjusted any way */
3405   accurate = flags & GST_SEEK_FLAG_ACCURATE;
3406
3407   /* maybe we can be accurate for (almost) free */
3408   gst_base_parse_find_offset (parse, seeksegment.last_stop, TRUE, &start_ts);
3409   if (seeksegment.last_stop <= start_ts + TARGET_DIFFERENCE) {
3410     GST_DEBUG_OBJECT (parse, "accurate seek possible");
3411     accurate = TRUE;
3412   }
3413   if (accurate) {
3414     GstClockTime startpos = seeksegment.last_stop;
3415
3416     /* accurate requested, so ... seek a bit before target */
3417     if (startpos < parse->priv->lead_in_ts)
3418       startpos = 0;
3419     else
3420       startpos -= parse->priv->lead_in_ts;
3421     seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3422     seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3423         NULL);
3424   } else {
3425     start_ts = seeksegment.last_stop;
3426     dstformat = GST_FORMAT_BYTES;
3427     if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.last_stop,
3428             &dstformat, &seekpos))
3429       goto convert_failed;
3430     if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3431             &dstformat, &seekstop))
3432       goto convert_failed;
3433   }
3434
3435   GST_DEBUG_OBJECT (parse,
3436       "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3437       start_ts, seekpos);
3438   GST_DEBUG_OBJECT (parse,
3439       "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3440       seeksegment.stop, seekstop);
3441
3442   if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
3443     gint64 last_stop;
3444
3445     GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3446
3447     if (flush) {
3448       if (parse->srcpad) {
3449         GST_DEBUG_OBJECT (parse, "sending flush start");
3450         gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3451         /* unlock upstream pull_range */
3452         gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3453       }
3454     } else {
3455       gst_pad_pause_task (parse->sinkpad);
3456     }
3457
3458     /* we should now be able to grab the streaming thread because we stopped it
3459      * with the above flush/pause code */
3460     GST_PAD_STREAM_LOCK (parse->sinkpad);
3461
3462     /* save current position */
3463     last_stop = parse->segment.last_stop;
3464     GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3465         last_stop);
3466
3467     /* now commit to new position */
3468
3469     /* prepare for streaming again */
3470     if (flush) {
3471       GST_DEBUG_OBJECT (parse, "sending flush stop");
3472       gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop ());
3473       gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop ());
3474       gst_base_parse_clear_queues (parse);
3475     } else {
3476       if (parse->priv->close_segment)
3477         gst_event_unref (parse->priv->close_segment);
3478
3479       parse->priv->close_segment = gst_event_new_new_segment (TRUE,
3480           parse->segment.rate, parse->segment.format,
3481           parse->segment.accum, parse->segment.last_stop, parse->segment.accum);
3482
3483       /* keep track of our last_stop */
3484       seeksegment.accum = parse->segment.last_stop;
3485
3486       GST_DEBUG_OBJECT (parse, "Created close seg format %d, "
3487           "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3488           ", pos = %" GST_TIME_FORMAT, format,
3489           GST_TIME_ARGS (parse->segment.accum),
3490           GST_TIME_ARGS (parse->segment.last_stop),
3491           GST_TIME_ARGS (parse->segment.accum));
3492     }
3493
3494     memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3495
3496     /* store the newsegment event so it can be sent from the streaming thread. */
3497     if (parse->priv->pending_segment)
3498       gst_event_unref (parse->priv->pending_segment);
3499
3500     /* This will be sent later in _loop() */
3501     parse->priv->pending_segment =
3502         gst_event_new_new_segment (FALSE, parse->segment.rate,
3503         parse->segment.format, parse->segment.start,
3504         parse->segment.stop, parse->segment.start);
3505
3506     GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3507         "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3508         ", pos = %" GST_TIME_FORMAT, format,
3509         GST_TIME_ARGS (parse->segment.start),
3510         GST_TIME_ARGS (parse->segment.stop),
3511         GST_TIME_ARGS (parse->segment.start));
3512
3513     /* one last chance in pull mode to stay accurate;
3514      * maybe scan and subclass can find where to go */
3515     if (!accurate) {
3516       gint64 scanpos;
3517       GstClockTime ts = seeksegment.last_stop;
3518
3519       gst_base_parse_locate_time (parse, &ts, &scanpos);
3520       if (scanpos >= 0) {
3521         accurate = TRUE;
3522         seekpos = scanpos;
3523         /* running collected index now consists of several intervals,
3524          * so optimized check no longer possible */
3525         parse->priv->index_last_valid = FALSE;
3526         parse->priv->index_last_offset = 0;
3527         parse->priv->index_last_ts = 0;
3528       }
3529     }
3530
3531     /* mark discont if we are going to stream from another position. */
3532     if (seekpos != parse->priv->offset) {
3533       GST_DEBUG_OBJECT (parse,
3534           "mark DISCONT, we did a seek to another position");
3535       parse->priv->offset = seekpos;
3536       parse->priv->last_offset = seekpos;
3537       parse->priv->seen_keyframe = FALSE;
3538       parse->priv->discont = TRUE;
3539       parse->priv->next_ts = start_ts;
3540       parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3541       parse->priv->sync_offset = seekpos;
3542       parse->priv->exact_position = accurate;
3543     }
3544
3545     /* Start streaming thread if paused */
3546     gst_pad_start_task (parse->sinkpad,
3547         (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3548
3549     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3550
3551     /* handled seek */
3552     res = TRUE;
3553   } else {
3554     GstEvent *new_event;
3555     GstBaseParseSeek *seek;
3556
3557     /* The only thing we need to do in PUSH-mode is to send the
3558        seek event (in bytes) to upstream. Segment / flush handling happens
3559        in corresponding src event handlers */
3560     GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3561     if (seekstop >= 0 && seekpos <= seekpos)
3562       seekstop = seekpos;
3563     new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flush,
3564         GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3565
3566     /* store segment info so its precise details can be reconstructed when
3567      * receiving newsegment;
3568      * this matters for all details when accurate seeking,
3569      * is most useful to preserve NONE stop time otherwise */
3570     seek = g_new0 (GstBaseParseSeek, 1);
3571     seek->segment = seeksegment;
3572     seek->accurate = accurate;
3573     seek->offset = seekpos;
3574     seek->start_ts = start_ts;
3575     GST_OBJECT_LOCK (parse);
3576     /* less optimal, but preserves order */
3577     parse->priv->pending_seeks =
3578         g_slist_append (parse->priv->pending_seeks, seek);
3579     GST_OBJECT_UNLOCK (parse);
3580
3581     res = gst_pad_push_event (parse->sinkpad, new_event);
3582
3583     if (!res) {
3584       GST_OBJECT_LOCK (parse);
3585       parse->priv->pending_seeks =
3586           g_slist_remove (parse->priv->pending_seeks, seek);
3587       GST_OBJECT_UNLOCK (parse);
3588       g_free (seek);
3589     }
3590   }
3591
3592 done:
3593   /* handled event is ours to free */
3594   if (res)
3595     gst_event_unref (event);
3596   return res;
3597
3598   /* ERRORS */
3599 negative_rate:
3600   {
3601     GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
3602     res = FALSE;
3603     goto done;
3604   }
3605 wrong_type:
3606   {
3607     GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3608     res = FALSE;
3609     goto done;
3610   }
3611 convert_failed:
3612   {
3613     GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3614     res = FALSE;
3615     goto done;
3616   }
3617 }
3618
3619 /* Checks if bitrates are available from upstream tags so that we don't
3620  * override them later
3621  */
3622 static void
3623 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
3624 {
3625   GstTagList *taglist = NULL;
3626   guint tmp;
3627
3628   gst_event_parse_tag (event, &taglist);
3629
3630   if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
3631     GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
3632     parse->priv->post_min_bitrate = FALSE;
3633   }
3634   if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
3635     GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
3636     parse->priv->post_avg_bitrate = FALSE;
3637   }
3638   if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
3639     GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
3640     parse->priv->post_max_bitrate = FALSE;
3641   }
3642 }
3643
3644 static gboolean
3645 gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps)
3646 {
3647   GstBaseParse *parse;
3648   GstBaseParseClass *klass;
3649   gboolean res = TRUE;
3650
3651   parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3652   klass = GST_BASE_PARSE_GET_CLASS (parse);
3653
3654   GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
3655
3656   if (klass->set_sink_caps)
3657     res = klass->set_sink_caps (parse, caps);
3658
3659   return res;
3660 }
3661
3662 static void
3663 gst_base_parse_set_index (GstElement * element, GstIndex * index)
3664 {
3665   GstBaseParse *parse = GST_BASE_PARSE (element);
3666
3667   GST_OBJECT_LOCK (parse);
3668   if (parse->priv->index)
3669     gst_object_unref (parse->priv->index);
3670   if (index) {
3671     parse->priv->index = gst_object_ref (index);
3672     gst_index_get_writer_id (index, GST_OBJECT (element),
3673         &parse->priv->index_id);
3674     parse->priv->own_index = FALSE;
3675   } else
3676     parse->priv->index = NULL;
3677   GST_OBJECT_UNLOCK (parse);
3678 }
3679
3680 static GstIndex *
3681 gst_base_parse_get_index (GstElement * element)
3682 {
3683   GstBaseParse *parse = GST_BASE_PARSE (element);
3684   GstIndex *result = NULL;
3685
3686   GST_OBJECT_LOCK (parse);
3687   if (parse->priv->index)
3688     result = gst_object_ref (parse->priv->index);
3689   GST_OBJECT_UNLOCK (parse);
3690
3691   return result;
3692 }
3693
3694 static GstStateChangeReturn
3695 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
3696 {
3697   GstBaseParse *parse;
3698   GstStateChangeReturn result;
3699
3700   parse = GST_BASE_PARSE (element);
3701
3702   switch (transition) {
3703     case GST_STATE_CHANGE_READY_TO_PAUSED:
3704       /* If this is our own index destroy it as the
3705        * old entries might be wrong for the new stream */
3706       if (parse->priv->own_index) {
3707         gst_object_unref (parse->priv->index);
3708         parse->priv->index = NULL;
3709         parse->priv->own_index = FALSE;
3710       }
3711
3712       /* If no index was created, generate one */
3713       if (G_UNLIKELY (!parse->priv->index)) {
3714         GST_DEBUG_OBJECT (parse, "no index provided creating our own");
3715
3716         parse->priv->index = gst_index_factory_make ("memindex");
3717         gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
3718             &parse->priv->index_id);
3719         parse->priv->own_index = TRUE;
3720       }
3721       break;
3722     default:
3723       break;
3724   }
3725
3726   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3727
3728   switch (transition) {
3729     case GST_STATE_CHANGE_PAUSED_TO_READY:
3730       gst_base_parse_reset (parse);
3731       break;
3732     default:
3733       break;
3734   }
3735
3736   return result;
3737 }