event: Make SEGMENT event parsing API more consistent with the others
[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
2753   parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2754
2755   GST_DEBUG_OBJECT (parse, "sink activate");
2756
2757   if (gst_pad_check_pull_range (sinkpad)) {
2758     GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2759     result = gst_pad_activate_pull (sinkpad, TRUE);
2760   } else {
2761     GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
2762     result = gst_pad_activate_push (sinkpad, TRUE);
2763   }
2764
2765   GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
2766   gst_object_unref (parse);
2767   return result;
2768 }
2769
2770 static gboolean
2771 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
2772 {
2773   GstBaseParseClass *klass;
2774   gboolean result = FALSE;
2775
2776   GST_DEBUG_OBJECT (parse, "activate %d", active);
2777
2778   klass = GST_BASE_PARSE_GET_CLASS (parse);
2779
2780   if (active) {
2781     if (parse->priv->pad_mode == GST_ACTIVATE_NONE && klass->start)
2782       result = klass->start (parse);
2783   } else {
2784     /* We must make sure streaming has finished before resetting things
2785      * and calling the ::stop vfunc */
2786     GST_PAD_STREAM_LOCK (parse->sinkpad);
2787     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2788
2789     if (parse->priv->pad_mode != GST_ACTIVATE_NONE && klass->stop)
2790       result = klass->stop (parse);
2791
2792     parse->priv->pad_mode = GST_ACTIVATE_NONE;
2793   }
2794   GST_DEBUG_OBJECT (parse, "activate return: %d", result);
2795   return result;
2796 }
2797
2798 static gboolean
2799 gst_base_parse_sink_activate_push (GstPad * pad, gboolean active)
2800 {
2801   gboolean result = TRUE;
2802   GstBaseParse *parse;
2803
2804   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2805
2806   GST_DEBUG_OBJECT (parse, "sink activate push %d", active);
2807
2808   result = gst_base_parse_activate (parse, active);
2809
2810   if (result)
2811     parse->priv->pad_mode = active ? GST_ACTIVATE_PUSH : GST_ACTIVATE_NONE;
2812
2813   GST_DEBUG_OBJECT (parse, "sink activate push return: %d", result);
2814
2815   gst_object_unref (parse);
2816   return result;
2817 }
2818
2819 static gboolean
2820 gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
2821 {
2822   gboolean result = FALSE;
2823   GstBaseParse *parse;
2824
2825   parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2826
2827   GST_DEBUG_OBJECT (parse, "activate pull %d", active);
2828
2829   result = gst_base_parse_activate (parse, active);
2830
2831   if (result) {
2832     if (active) {
2833       parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
2834       result &=
2835           gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
2836           sinkpad);
2837     } else {
2838       result &= gst_pad_stop_task (sinkpad);
2839     }
2840   }
2841
2842   if (result)
2843     parse->priv->pad_mode = active ? GST_ACTIVATE_PULL : GST_ACTIVATE_NONE;
2844
2845   GST_DEBUG_OBJECT (parse, "sink activate pull return: %d", result);
2846
2847   gst_object_unref (parse);
2848   return result;
2849 }
2850
2851
2852 /**
2853  * gst_base_parse_set_duration:
2854  * @parse: #GstBaseParse.
2855  * @fmt: #GstFormat.
2856  * @duration: duration value.
2857  * @interval: how often to update the duration estimate based on bitrate, or 0.
2858  *
2859  * Sets the duration of the currently playing media. Subclass can use this
2860  * when it is able to determine duration and/or notices a change in the media
2861  * duration.  Alternatively, if @interval is non-zero (default), then stream
2862  * duration is determined based on estimated bitrate, and updated every @interval
2863  * frames.
2864  *
2865  * Since: 0.10.33
2866  */
2867 void
2868 gst_base_parse_set_duration (GstBaseParse * parse,
2869     GstFormat fmt, gint64 duration, gint interval)
2870 {
2871   g_return_if_fail (parse != NULL);
2872
2873   if (parse->priv->upstream_has_duration) {
2874     GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
2875     goto exit;
2876   }
2877
2878   if (duration != parse->priv->duration) {
2879     GstMessage *m;
2880
2881     m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
2882     gst_element_post_message (GST_ELEMENT (parse), m);
2883
2884     /* TODO: what about duration tag? */
2885   }
2886   parse->priv->duration = duration;
2887   parse->priv->duration_fmt = fmt;
2888   GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
2889   if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
2890     if (interval != 0) {
2891       GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
2892       interval = 0;
2893     }
2894   }
2895   GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
2896   parse->priv->update_interval = interval;
2897 exit:
2898   return;
2899 }
2900
2901 /**
2902  * gst_base_parse_set_average_bitrate:
2903  * @parse: #GstBaseParse.
2904  * @bitrate: average bitrate in bits/second
2905  *
2906  * Optionally sets the average bitrate detected in media (if non-zero),
2907  * e.g. based on metadata, as it will be posted to the application.
2908  *
2909  * By default, announced average bitrate is estimated. The average bitrate
2910  * is used to estimate the total duration of the stream and to estimate
2911  * a seek position, if there's no index and the format is syncable
2912  * (see gst_base_parse_set_syncable()).
2913  *
2914  * Since: 0.10.33
2915  */
2916 void
2917 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
2918 {
2919   parse->priv->bitrate = bitrate;
2920   GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
2921 }
2922
2923 /**
2924  * gst_base_parse_set_min_frame_size:
2925  * @parse: #GstBaseParse.
2926  * @min_size: Minimum size of the data that this base class should give to
2927  *            subclass.
2928  *
2929  * Subclass can use this function to tell the base class that it needs to
2930  * give at least #min_size buffers.
2931  *
2932  * Since: 0.10.33
2933  */
2934 void
2935 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
2936 {
2937   g_return_if_fail (parse != NULL);
2938
2939   parse->priv->min_frame_size = min_size;
2940   GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
2941 }
2942
2943 /**
2944  * gst_base_parse_set_frame_rate:
2945  * @parse: the #GstBaseParse to set
2946  * @fps_num: frames per second (numerator).
2947  * @fps_den: frames per second (denominator).
2948  * @lead_in: frames needed before a segment for subsequent decode
2949  * @lead_out: frames needed after a segment
2950  *
2951  * If frames per second is configured, parser can take care of buffer duration
2952  * and timestamping.  When performing segment clipping, or seeking to a specific
2953  * location, a corresponding decoder might need an initial @lead_in and a
2954  * following @lead_out number of frames to ensure the desired segment is
2955  * entirely filled upon decoding.
2956  *
2957  * Since: 0.10.33
2958  */
2959 void
2960 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
2961     guint fps_den, guint lead_in, guint lead_out)
2962 {
2963   g_return_if_fail (parse != NULL);
2964
2965   parse->priv->fps_num = fps_num;
2966   parse->priv->fps_den = fps_den;
2967   if (!fps_num || !fps_den) {
2968     GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
2969         fps_num, fps_den);
2970     fps_num = fps_den = 0;
2971     parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
2972     parse->priv->lead_in = parse->priv->lead_out = 0;
2973     parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
2974   } else {
2975     parse->priv->frame_duration =
2976         gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
2977     parse->priv->lead_in = lead_in;
2978     parse->priv->lead_out = lead_out;
2979     parse->priv->lead_in_ts =
2980         gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
2981     parse->priv->lead_out_ts =
2982         gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
2983     /* aim for about 1.5s to estimate duration */
2984     if (parse->priv->update_interval < 0) {
2985       parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
2986       GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
2987           parse->priv->update_interval);
2988     }
2989   }
2990   GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
2991       fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
2992   GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
2993       "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
2994       lead_in, parse->priv->lead_in_ts / GST_MSECOND,
2995       lead_out, parse->priv->lead_out_ts / GST_MSECOND);
2996 }
2997
2998 /**
2999  * gst_base_parse_set_has_timing_info:
3000  * @parse: a #GstBaseParse
3001  * @has_timing: whether frames carry timing information
3002  *
3003  * Set if frames carry timing information which the subclass can (generally)
3004  * parse and provide.  In particular, intrinsic (rather than estimated) time
3005  * can be obtained following a seek.
3006  *
3007  * Since: 0.10.33
3008  */
3009 void
3010 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3011 {
3012   parse->priv->has_timing_info = has_timing;
3013   GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3014 }
3015
3016 /**
3017  * gst_base_parse_set_syncable:
3018  * @parse: a #GstBaseParse
3019  * @syncable: set if frame starts can be identified
3020  *
3021  * Set if frame starts can be identified. This is set by default and
3022  * determines whether seeking based on bitrate averages
3023  * is possible for a format/stream.
3024  *
3025  * Since: 0.10.33
3026  */
3027 void
3028 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3029 {
3030   parse->priv->syncable = syncable;
3031   GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3032 }
3033
3034 /**
3035  * gst_base_parse_set_passthrough:
3036  * @parse: a #GstBaseParse
3037  * @passthrough: %TRUE if parser should run in passthrough mode
3038  *
3039  * Set if the nature of the format or configuration does not allow (much)
3040  * parsing, and the parser should operate in passthrough mode (which only
3041  * applies when operating in push mode). That is, incoming buffers are
3042  * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3043  * callbacks will be invoked, but @pre_push_buffer will still be invoked,
3044  * so subclass can perform as much or as little is appropriate for
3045  * passthrough semantics in @pre_push_buffer.
3046  *
3047  * Since: 0.10.33
3048  */
3049 void
3050 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3051 {
3052   parse->priv->passthrough = passthrough;
3053   GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3054 }
3055
3056 /**
3057  * gst_base_parse_set_latency:
3058  * @parse: a #GstBaseParse
3059  * @min_latency: minimum parse latency
3060  * @max_latency: maximum parse latency
3061  *
3062  * Sets the minimum and maximum (which may likely be equal) latency introduced
3063  * by the parsing process.  If there is such a latency, which depends on the
3064  * particular parsing of the format, it typically corresponds to 1 frame duration.
3065  *
3066  * Since: 0.10.34
3067  */
3068 void
3069 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3070     GstClockTime max_latency)
3071 {
3072   GST_OBJECT_LOCK (parse);
3073   parse->priv->min_latency = min_latency;
3074   parse->priv->max_latency = max_latency;
3075   GST_OBJECT_UNLOCK (parse);
3076   GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3077       GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3078       GST_TIME_ARGS (max_latency));
3079 }
3080
3081 static gboolean
3082 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3083     GstClockTime * duration)
3084 {
3085   gboolean res = FALSE;
3086
3087   g_return_val_if_fail (duration != NULL, FALSE);
3088
3089   *duration = GST_CLOCK_TIME_NONE;
3090   if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3091     GST_LOG_OBJECT (parse, "using provided duration");
3092     *duration = parse->priv->duration;
3093     res = TRUE;
3094   } else if (parse->priv->duration != -1) {
3095     GST_LOG_OBJECT (parse, "converting provided duration");
3096     res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3097         parse->priv->duration, format, (gint64 *) duration);
3098   } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3099     GST_LOG_OBJECT (parse, "using estimated duration");
3100     *duration = parse->priv->estimated_duration;
3101     res = TRUE;
3102   }
3103
3104   GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3105       GST_TIME_ARGS (*duration));
3106   return res;
3107 }
3108
3109 static const GstQueryType *
3110 gst_base_parse_get_querytypes (GstPad * pad)
3111 {
3112   static const GstQueryType list[] = {
3113     GST_QUERY_POSITION,
3114     GST_QUERY_DURATION,
3115     GST_QUERY_FORMATS,
3116     GST_QUERY_SEEKING,
3117     GST_QUERY_CONVERT,
3118     0
3119   };
3120
3121   return list;
3122 }
3123
3124 static gboolean
3125 gst_base_parse_query (GstPad * pad, GstQuery * query)
3126 {
3127   GstBaseParse *parse;
3128   gboolean res = FALSE;
3129
3130   parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3131
3132   GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3133
3134   switch (GST_QUERY_TYPE (query)) {
3135     case GST_QUERY_POSITION:
3136     {
3137       gint64 dest_value;
3138       GstFormat format;
3139
3140       GST_DEBUG_OBJECT (parse, "position query");
3141       gst_query_parse_position (query, &format, NULL);
3142
3143       GST_OBJECT_LOCK (parse);
3144       if (format == GST_FORMAT_BYTES) {
3145         dest_value = parse->priv->offset;
3146         res = TRUE;
3147       } else if (format == parse->segment.format &&
3148           GST_CLOCK_TIME_IS_VALID (parse->segment.position)) {
3149         dest_value = parse->segment.position;
3150         res = TRUE;
3151       }
3152       GST_OBJECT_UNLOCK (parse);
3153
3154       if (res)
3155         gst_query_set_position (query, format, dest_value);
3156       else {
3157         res = gst_pad_query_default (pad, query);
3158         if (!res) {
3159           /* no precise result, upstream no idea either, then best estimate */
3160           /* priv->offset is updated in both PUSH/PULL modes */
3161           res = gst_base_parse_convert (parse,
3162               GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3163         }
3164       }
3165       break;
3166     }
3167     case GST_QUERY_DURATION:
3168     {
3169       GstFormat format;
3170       GstClockTime duration;
3171
3172       GST_DEBUG_OBJECT (parse, "duration query");
3173       gst_query_parse_duration (query, &format, NULL);
3174
3175       /* consult upstream */
3176       res = gst_pad_query_default (pad, query);
3177
3178       /* otherwise best estimate from us */
3179       if (!res) {
3180         res = gst_base_parse_get_duration (parse, format, &duration);
3181         if (res)
3182           gst_query_set_duration (query, format, duration);
3183       }
3184       break;
3185     }
3186     case GST_QUERY_SEEKING:
3187     {
3188       GstFormat fmt;
3189       GstClockTime duration = GST_CLOCK_TIME_NONE;
3190       gboolean seekable = FALSE;
3191
3192       GST_DEBUG_OBJECT (parse, "seeking query");
3193       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3194
3195       /* consult upstream */
3196       res = gst_pad_query_default (pad, query);
3197
3198       /* we may be able to help if in TIME */
3199       if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3200         gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3201         /* already OK if upstream takes care */
3202         GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3203             res, seekable);
3204         if (!(res && seekable)) {
3205           if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3206               || duration == -1) {
3207             /* seekable if we still have a chance to get duration later on */
3208             seekable =
3209                 parse->priv->upstream_seekable && parse->priv->update_interval;
3210           } else {
3211             seekable = parse->priv->upstream_seekable;
3212             GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3213                 seekable);
3214           }
3215           gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3216           res = TRUE;
3217         }
3218       }
3219       break;
3220     }
3221     case GST_QUERY_FORMATS:
3222       gst_query_set_formatsv (query, 3, fmtlist);
3223       res = TRUE;
3224       break;
3225     case GST_QUERY_CONVERT:
3226     {
3227       GstFormat src_format, dest_format;
3228       gint64 src_value, dest_value;
3229
3230       gst_query_parse_convert (query, &src_format, &src_value,
3231           &dest_format, &dest_value);
3232
3233       res = gst_base_parse_convert (parse, src_format, src_value,
3234           dest_format, &dest_value);
3235       if (res) {
3236         gst_query_set_convert (query, src_format, src_value,
3237             dest_format, dest_value);
3238       }
3239       break;
3240     }
3241     case GST_QUERY_LATENCY:
3242     {
3243       if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3244         gboolean live;
3245         GstClockTime min_latency, max_latency;
3246
3247         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3248         GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3249             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3250             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3251
3252         GST_OBJECT_LOCK (parse);
3253         /* add our latency */
3254         if (min_latency != -1)
3255           min_latency += parse->priv->min_latency;
3256         if (max_latency != -1)
3257           max_latency += parse->priv->max_latency;
3258         GST_OBJECT_UNLOCK (parse);
3259
3260         gst_query_set_latency (query, live, min_latency, max_latency);
3261       }
3262       break;
3263     }
3264     default:
3265       res = gst_pad_query_default (pad, query);
3266       break;
3267   }
3268   return res;
3269 }
3270
3271 /* scans for a cluster start from @pos,
3272  * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3273 static GstFlowReturn
3274 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3275     GstClockTime * time, GstClockTime * duration)
3276 {
3277   GstBaseParseClass *klass;
3278   gint64 orig_offset;
3279   gboolean orig_drain, orig_discont;
3280   GstFlowReturn ret = GST_FLOW_OK;
3281   GstBuffer *buf = NULL;
3282   GstBaseParseFrame frame;
3283
3284   g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3285   g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3286   g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3287
3288   klass = GST_BASE_PARSE_GET_CLASS (parse);
3289
3290   *time = GST_CLOCK_TIME_NONE;
3291   *duration = GST_CLOCK_TIME_NONE;
3292
3293   /* save state */
3294   orig_offset = parse->priv->offset;
3295   orig_discont = parse->priv->discont;
3296   orig_drain = parse->priv->drain;
3297
3298   GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3299       " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3300
3301   gst_base_parse_frame_init (&frame);
3302
3303   /* jump elsewhere and locate next frame */
3304   parse->priv->offset = *pos;
3305   ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3306   if (ret != GST_FLOW_OK)
3307     goto done;
3308
3309   buf = frame.buffer;
3310   GST_LOG_OBJECT (parse,
3311       "peek parsing frame at offset %" G_GUINT64_FORMAT
3312       " (%#" G_GINT64_MODIFIER "x) of size %d",
3313       GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf),
3314       gst_buffer_get_size (buf));
3315
3316   /* get offset first, subclass parsing might dump other stuff in there */
3317   *pos = GST_BUFFER_OFFSET (buf);
3318   ret = klass->parse_frame (parse, &frame);
3319   buf = frame.buffer;
3320
3321   /* but it should provide proper time */
3322   *time = GST_BUFFER_TIMESTAMP (buf);
3323   *duration = GST_BUFFER_DURATION (buf);
3324
3325   gst_base_parse_frame_free (&frame);
3326
3327   GST_LOG_OBJECT (parse,
3328       "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3329       GST_TIME_ARGS (*time), *pos);
3330
3331 done:
3332   /* restore state */
3333   parse->priv->offset = orig_offset;
3334   parse->priv->discont = orig_discont;
3335   parse->priv->drain = orig_drain;
3336
3337   return ret;
3338 }
3339
3340 /* bisect and scan through file for frame starting before @time,
3341  * returns OK and @time/@offset if found, NONE and/or error otherwise
3342  * If @time == G_MAXINT64, scan for duration ( == last frame) */
3343 static GstFlowReturn
3344 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3345     gint64 * _offset)
3346 {
3347   GstFlowReturn ret = GST_FLOW_OK;
3348   gint64 lpos, hpos, newpos;
3349   GstClockTime time, ltime, htime, newtime, dur;
3350   gboolean cont = TRUE;
3351   const GstClockTime tolerance = TARGET_DIFFERENCE;
3352   const guint chunk = 4 * 1024;
3353
3354   g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3355   g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3356
3357   /* TODO also make keyframe aware if useful some day */
3358
3359   time = *_time;
3360
3361   /* basic cases */
3362   if (time == 0) {
3363     *_offset = 0;
3364     return GST_FLOW_OK;
3365   }
3366
3367   if (time == -1) {
3368     *_offset = -1;
3369     return GST_FLOW_OK;
3370   }
3371
3372   /* do not know at first */
3373   *_offset = -1;
3374   *_time = GST_CLOCK_TIME_NONE;
3375
3376   /* need initial positions; start and end */
3377   lpos = parse->priv->first_frame_offset;
3378   ltime = parse->priv->first_frame_ts;
3379   htime = parse->priv->duration;
3380   hpos = parse->priv->upstream_size;
3381
3382   /* check preconditions are satisfied;
3383    * start and end are needed, except for special case where we scan for
3384    * last frame to determine duration */
3385   if (parse->priv->pad_mode != GST_ACTIVATE_PULL || !hpos ||
3386       !GST_CLOCK_TIME_IS_VALID (ltime) ||
3387       (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3388     return GST_FLOW_OK;
3389   }
3390
3391   /* shortcut cases */
3392   if (time < ltime) {
3393     goto exit;
3394   } else if (time < ltime + tolerance) {
3395     *_offset = lpos;
3396     *_time = ltime;
3397     goto exit;
3398   } else if (time >= htime) {
3399     *_offset = hpos;
3400     *_time = htime;
3401     goto exit;
3402   }
3403
3404   while (htime > ltime && cont) {
3405     GST_LOG_OBJECT (parse,
3406         "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3407         GST_TIME_ARGS (ltime));
3408     GST_LOG_OBJECT (parse,
3409         "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3410         GST_TIME_ARGS (htime));
3411     if (G_UNLIKELY (time == G_MAXINT64)) {
3412       newpos = hpos;
3413     } else if (G_LIKELY (hpos > lpos)) {
3414       newpos =
3415           gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3416           lpos - chunk;
3417     } else {
3418       /* should mean lpos == hpos, since lpos <= hpos is invariant */
3419       newpos = lpos;
3420       /* we check this case once, but not forever, so break loop */
3421       cont = FALSE;
3422     }
3423
3424     /* ensure */
3425     newpos = CLAMP (newpos, lpos, hpos);
3426     GST_LOG_OBJECT (parse,
3427         "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3428         GST_TIME_ARGS (time), newpos);
3429
3430     ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3431     if (ret == GST_FLOW_UNEXPECTED) {
3432       /* heuristic HACK */
3433       hpos = MAX (lpos, hpos - chunk);
3434       continue;
3435     } else if (ret != GST_FLOW_OK) {
3436       goto exit;
3437     }
3438
3439     if (newtime == -1 || newpos == -1) {
3440       GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3441       break;
3442     }
3443
3444     if (G_UNLIKELY (time == G_MAXINT64)) {
3445       *_offset = newpos;
3446       *_time = newtime;
3447       if (GST_CLOCK_TIME_IS_VALID (dur))
3448         *_time += dur;
3449       break;
3450     } else if (newtime > time) {
3451       /* overshoot */
3452       hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3453       htime = newtime;
3454     } else if (newtime + tolerance > time) {
3455       /* close enough undershoot */
3456       *_offset = newpos;
3457       *_time = newtime;
3458       break;
3459     } else if (newtime < ltime) {
3460       /* so a position beyond lpos resulted in earlier time than ltime ... */
3461       GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3462       break;
3463     } else {
3464       /* undershoot too far */
3465       newpos += newpos == lpos ? chunk : 0;
3466       lpos = CLAMP (newpos, lpos, hpos);
3467       ltime = newtime;
3468     }
3469   }
3470
3471 exit:
3472   GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3473       GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3474   return ret;
3475 }
3476
3477 static gint64
3478 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3479     gboolean before, GstClockTime * _ts)
3480 {
3481   gint64 bytes = 0, ts = 0;
3482   GstIndexEntry *entry = NULL;
3483
3484   if (time == GST_CLOCK_TIME_NONE) {
3485     ts = time;
3486     bytes = -1;
3487     goto exit;
3488   }
3489
3490   g_static_mutex_lock (&parse->priv->index_lock);
3491   if (parse->priv->index) {
3492     /* Let's check if we have an index entry for that time */
3493     entry = gst_index_get_assoc_entry (parse->priv->index,
3494         parse->priv->index_id,
3495         before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3496         GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3497   }
3498
3499   if (entry) {
3500     gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3501     gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3502
3503     GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3504         " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3505         GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3506   } else {
3507     GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3508         GST_TIME_ARGS (time));
3509     if (!before) {
3510       bytes = -1;
3511       ts = GST_CLOCK_TIME_NONE;
3512     }
3513   }
3514   g_static_mutex_unlock (&parse->priv->index_lock);
3515
3516 exit:
3517   if (_ts)
3518     *_ts = ts;
3519
3520   return bytes;
3521 }
3522
3523 /* returns TRUE if seek succeeded */
3524 static gboolean
3525 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3526 {
3527   gdouble rate;
3528   GstFormat format;
3529   GstSeekFlags flags;
3530   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3531   gboolean flush, update, res = TRUE, accurate;
3532   gint64 cur, stop, seekpos, seekstop;
3533   GstSegment seeksegment = { 0, };
3534   GstFormat dstformat;
3535   GstClockTime start_ts;
3536
3537   gst_event_parse_seek (event, &rate, &format, &flags,
3538       &cur_type, &cur, &stop_type, &stop);
3539
3540   GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3541       "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3542       GST_TIME_FORMAT, gst_format_get_name (format), rate,
3543       cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3544
3545   /* no negative rates in push mode */
3546   if (rate < 0.0 && parse->priv->pad_mode == GST_ACTIVATE_PUSH)
3547     goto negative_rate;
3548
3549   if (cur_type != GST_SEEK_TYPE_SET ||
3550       (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3551     goto wrong_type;
3552
3553   /* For any format other than TIME, see if upstream handles
3554    * it directly or fail. For TIME, try upstream, but do it ourselves if
3555    * it fails upstream */
3556   if (format != GST_FORMAT_TIME) {
3557     /* default action delegates to upstream */
3558     res = FALSE;
3559     goto done;
3560   } else {
3561     gst_event_ref (event);
3562     if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3563       goto done;
3564     }
3565   }
3566
3567   /* get flush flag */
3568   flush = flags & GST_SEEK_FLAG_FLUSH;
3569
3570   /* copy segment, we need this because we still need the old
3571    * segment when we close the current segment. */
3572   gst_segment_copy_into (&parse->segment, &seeksegment);
3573
3574   GST_DEBUG_OBJECT (parse, "configuring seek");
3575   gst_segment_do_seek (&seeksegment, rate, format, flags,
3576       cur_type, cur, stop_type, stop, &update);
3577
3578   /* accurate seeking implies seek tables are used to obtain position,
3579    * and the requested segment is maintained exactly, not adjusted any way */
3580   accurate = flags & GST_SEEK_FLAG_ACCURATE;
3581
3582   /* maybe we can be accurate for (almost) free */
3583   gst_base_parse_find_offset (parse, seeksegment.position, TRUE, &start_ts);
3584   if (seeksegment.position <= start_ts + TARGET_DIFFERENCE) {
3585     GST_DEBUG_OBJECT (parse, "accurate seek possible");
3586     accurate = TRUE;
3587   }
3588   if (accurate) {
3589     GstClockTime startpos = seeksegment.position;
3590
3591     /* accurate requested, so ... seek a bit before target */
3592     if (startpos < parse->priv->lead_in_ts)
3593       startpos = 0;
3594     else
3595       startpos -= parse->priv->lead_in_ts;
3596     seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3597     seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3598         NULL);
3599   } else {
3600     start_ts = seeksegment.position;
3601     dstformat = GST_FORMAT_BYTES;
3602     if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.position,
3603             &dstformat, &seekpos))
3604       goto convert_failed;
3605     if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3606             &dstformat, &seekstop))
3607       goto convert_failed;
3608   }
3609
3610   GST_DEBUG_OBJECT (parse,
3611       "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3612       start_ts, seekpos);
3613   GST_DEBUG_OBJECT (parse,
3614       "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3615       seeksegment.stop, seekstop);
3616
3617   if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
3618     gint64 last_stop;
3619
3620     GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3621
3622     if (flush) {
3623       if (parse->srcpad) {
3624         GST_DEBUG_OBJECT (parse, "sending flush start");
3625         gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3626         /* unlock upstream pull_range */
3627         gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3628       }
3629     } else {
3630       gst_pad_pause_task (parse->sinkpad);
3631     }
3632
3633     /* we should now be able to grab the streaming thread because we stopped it
3634      * with the above flush/pause code */
3635     GST_PAD_STREAM_LOCK (parse->sinkpad);
3636
3637     /* save current position */
3638     last_stop = parse->segment.position;
3639     GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3640         last_stop);
3641
3642     /* now commit to new position */
3643
3644     /* prepare for streaming again */
3645     if (flush) {
3646       GST_DEBUG_OBJECT (parse, "sending flush stop");
3647       gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop ());
3648       gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop ());
3649       gst_base_parse_clear_queues (parse);
3650     } else {
3651       /* keep track of our position */
3652       seeksegment.base = gst_segment_to_running_time (&seeksegment,
3653           seeksegment.format, parse->segment.position);
3654     }
3655
3656     memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3657
3658     /* store the newsegment event so it can be sent from the streaming thread. */
3659     if (parse->priv->pending_segment)
3660       gst_event_unref (parse->priv->pending_segment);
3661
3662     /* This will be sent later in _loop() */
3663     parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
3664
3665     GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3666         "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3667         ", pos = %" GST_TIME_FORMAT, format,
3668         GST_TIME_ARGS (parse->segment.start),
3669         GST_TIME_ARGS (parse->segment.stop),
3670         GST_TIME_ARGS (parse->segment.start));
3671
3672     /* one last chance in pull mode to stay accurate;
3673      * maybe scan and subclass can find where to go */
3674     if (!accurate) {
3675       gint64 scanpos;
3676       GstClockTime ts = seeksegment.position;
3677
3678       gst_base_parse_locate_time (parse, &ts, &scanpos);
3679       if (scanpos >= 0) {
3680         accurate = TRUE;
3681         seekpos = scanpos;
3682         /* running collected index now consists of several intervals,
3683          * so optimized check no longer possible */
3684         parse->priv->index_last_valid = FALSE;
3685         parse->priv->index_last_offset = 0;
3686         parse->priv->index_last_ts = 0;
3687       }
3688     }
3689
3690     /* mark discont if we are going to stream from another position. */
3691     if (seekpos != parse->priv->offset) {
3692       GST_DEBUG_OBJECT (parse,
3693           "mark DISCONT, we did a seek to another position");
3694       parse->priv->offset = seekpos;
3695       parse->priv->last_offset = seekpos;
3696       parse->priv->seen_keyframe = FALSE;
3697       parse->priv->discont = TRUE;
3698       parse->priv->next_ts = start_ts;
3699       parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3700       parse->priv->sync_offset = seekpos;
3701       parse->priv->exact_position = accurate;
3702     }
3703
3704     /* Start streaming thread if paused */
3705     gst_pad_start_task (parse->sinkpad,
3706         (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3707
3708     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3709
3710     /* handled seek */
3711     res = TRUE;
3712   } else {
3713     GstEvent *new_event;
3714     GstBaseParseSeek *seek;
3715
3716     /* The only thing we need to do in PUSH-mode is to send the
3717        seek event (in bytes) to upstream. Segment / flush handling happens
3718        in corresponding src event handlers */
3719     GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3720     if (seekstop >= 0 && seekpos <= seekpos)
3721       seekstop = seekpos;
3722     new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flush,
3723         GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3724
3725     /* store segment info so its precise details can be reconstructed when
3726      * receiving newsegment;
3727      * this matters for all details when accurate seeking,
3728      * is most useful to preserve NONE stop time otherwise */
3729     seek = g_new0 (GstBaseParseSeek, 1);
3730     seek->segment = seeksegment;
3731     seek->accurate = accurate;
3732     seek->offset = seekpos;
3733     seek->start_ts = start_ts;
3734     GST_OBJECT_LOCK (parse);
3735     /* less optimal, but preserves order */
3736     parse->priv->pending_seeks =
3737         g_slist_append (parse->priv->pending_seeks, seek);
3738     GST_OBJECT_UNLOCK (parse);
3739
3740     res = gst_pad_push_event (parse->sinkpad, new_event);
3741
3742     if (!res) {
3743       GST_OBJECT_LOCK (parse);
3744       parse->priv->pending_seeks =
3745           g_slist_remove (parse->priv->pending_seeks, seek);
3746       GST_OBJECT_UNLOCK (parse);
3747       g_free (seek);
3748     }
3749   }
3750
3751 done:
3752   /* handled event is ours to free */
3753   if (res)
3754     gst_event_unref (event);
3755   return res;
3756
3757   /* ERRORS */
3758 negative_rate:
3759   {
3760     GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
3761     res = FALSE;
3762     goto done;
3763   }
3764 wrong_type:
3765   {
3766     GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3767     res = FALSE;
3768     goto done;
3769   }
3770 convert_failed:
3771   {
3772     GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3773     res = FALSE;
3774     goto done;
3775   }
3776 }
3777
3778 /* Checks if bitrates are available from upstream tags so that we don't
3779  * override them later
3780  */
3781 static void
3782 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
3783 {
3784   GstTagList *taglist = NULL;
3785   guint tmp;
3786
3787   gst_event_parse_tag (event, &taglist);
3788
3789   if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
3790     GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
3791     parse->priv->post_min_bitrate = FALSE;
3792   }
3793   if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
3794     GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
3795     parse->priv->post_avg_bitrate = FALSE;
3796   }
3797   if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
3798     GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
3799     parse->priv->post_max_bitrate = FALSE;
3800   }
3801 }
3802
3803 static gboolean
3804 gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps)
3805 {
3806   GstBaseParse *parse;
3807   GstBaseParseClass *klass;
3808   gboolean res = TRUE;
3809
3810   parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3811   klass = GST_BASE_PARSE_GET_CLASS (parse);
3812
3813   GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
3814
3815   if (klass->set_sink_caps)
3816     res = klass->set_sink_caps (parse, caps);
3817
3818   return res;
3819 }
3820
3821 static void
3822 gst_base_parse_set_index (GstElement * element, GstIndex * index)
3823 {
3824   GstBaseParse *parse = GST_BASE_PARSE (element);
3825
3826   g_static_mutex_lock (&parse->priv->index_lock);
3827   if (parse->priv->index)
3828     gst_object_unref (parse->priv->index);
3829   if (index) {
3830     parse->priv->index = gst_object_ref (index);
3831     gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
3832         &parse->priv->index_id);
3833     parse->priv->own_index = FALSE;
3834   } else {
3835     parse->priv->index = NULL;
3836   }
3837   g_static_mutex_unlock (&parse->priv->index_lock);
3838 }
3839
3840 static GstIndex *
3841 gst_base_parse_get_index (GstElement * element)
3842 {
3843   GstBaseParse *parse = GST_BASE_PARSE (element);
3844   GstIndex *result = NULL;
3845
3846   g_static_mutex_lock (&parse->priv->index_lock);
3847   if (parse->priv->index)
3848     result = gst_object_ref (parse->priv->index);
3849   g_static_mutex_unlock (&parse->priv->index_lock);
3850
3851   return result;
3852 }
3853
3854 static GstStateChangeReturn
3855 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
3856 {
3857   GstBaseParse *parse;
3858   GstStateChangeReturn result;
3859
3860   parse = GST_BASE_PARSE (element);
3861
3862   switch (transition) {
3863     case GST_STATE_CHANGE_READY_TO_PAUSED:
3864       /* If this is our own index destroy it as the
3865        * old entries might be wrong for the new stream */
3866       g_static_mutex_lock (&parse->priv->index_lock);
3867       if (parse->priv->own_index) {
3868         gst_object_unref (parse->priv->index);
3869         parse->priv->index = NULL;
3870         parse->priv->own_index = FALSE;
3871       }
3872
3873       /* If no index was created, generate one */
3874       if (G_UNLIKELY (!parse->priv->index)) {
3875         GST_DEBUG_OBJECT (parse, "no index provided creating our own");
3876
3877         parse->priv->index = gst_index_factory_make ("memindex");
3878         gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
3879             &parse->priv->index_id);
3880         parse->priv->own_index = TRUE;
3881       }
3882       g_static_mutex_unlock (&parse->priv->index_lock);
3883       break;
3884     default:
3885       break;
3886   }
3887
3888   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3889
3890   switch (transition) {
3891     case GST_STATE_CHANGE_PAUSED_TO_READY:
3892       gst_base_parse_reset (parse);
3893       break;
3894     default:
3895       break;
3896   }
3897
3898   return result;
3899 }