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