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