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 * Copyright (C) 2011, Hewlett-Packard Development Company, L.P.
6 * Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>, Collabora Ltd.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public
19 * License along with this library; if not, write to the
20 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 * Boston, MA 02111-1307, USA.
25 * SECTION:gstbaseparse
26 * @short_description: Base class for stream parsers
27 * @see_also: #GstBaseTransform
29 * This base class is for parser elements that process data and splits it
30 * into separate audio/video/whatever frames.
34 * <listitem><para>provides one sink pad and one source pad</para></listitem>
35 * <listitem><para>handles state changes</para></listitem>
36 * <listitem><para>can operate in pull mode or push mode</para></listitem>
37 * <listitem><para>handles seeking in both modes</para></listitem>
38 * <listitem><para>handles events (NEWSEGMENT/EOS/FLUSH)</para></listitem>
40 * handles queries (POSITION/DURATION/SEEKING/FORMAT/CONVERT)
42 * <listitem><para>handles flushing</para></listitem>
45 * The purpose of this base class is to provide the basic functionality of
46 * a parser and share a lot of rather complex code.
48 * Description of the parsing mechanism:
51 * <itemizedlist><title>Set-up phase</title>
53 * GstBaseParse class calls @set_sink_caps to inform the subclass about
54 * incoming sinkpad caps. Subclass should set the srcpad caps accordingly.
57 * GstBaseParse calls @start to inform subclass that data processing is
61 * At least at this point subclass needs to tell the GstBaseParse class
62 * how big data chunks it wants to receive (min_frame_size). It can do
63 * this with gst_base_parse_set_min_frame_size().
66 * GstBaseParse class sets up appropriate data passing mode (pull/push)
67 * and starts to process the data.
73 * <title>Parsing phase</title>
75 * GstBaseParse gathers at least min_frame_size bytes of data either
76 * by pulling it from upstream or collecting buffers in an internal
80 * A buffer of (at least) min_frame_size bytes is passed to subclass with
81 * @check_valid_frame. Subclass checks the contents and returns TRUE
82 * if the buffer contains a valid frame. It also needs to set the
83 * @framesize according to the detected frame size. If buffer didn't
84 * contain a valid frame, this call must return FALSE and optionally
85 * set the @skipsize value to inform base class that how many bytes
86 * it needs to skip in order to find a valid frame. @framesize can always
87 * indicate a new minimum for current frame parsing. Indicating G_MAXUINT
88 * for requested amount means subclass simply needs best available
89 * subsequent data. In push mode this amounts to an additional input buffer
90 * (thus minimal additional latency), in pull mode this amounts to some
91 * arbitrary reasonable buffer size increase. The passed buffer
92 * is read-only. Note that @check_valid_frame might receive any small
93 * amount of input data when leftover data is being drained (e.g. at EOS).
96 * After valid frame is found, it will be passed again to subclass with
97 * @parse_frame call. Now subclass is responsible for parsing the
98 * frame contents and setting the caps, and buffer metadata (e.g.
99 * buffer timestamp and duration, or keyframe if applicable).
100 * (although the latter can also be done by GstBaseParse if it is
101 * appropriately configured, see below). Frame is provided with
102 * timestamp derived from upstream (as much as generally possible),
103 * duration obtained from configuration (see below), and offset
104 * if meaningful (in pull mode).
107 * Finally the buffer can be pushed downstream and the parsing loop starts
108 * over again. Just prior to actually pushing the buffer in question,
109 * it is passed to @pre_push_frame which gives subclass yet one
110 * last chance to examine buffer metadata, or to send some custom (tag)
111 * events, or to perform custom (segment) filtering.
114 * During the parsing process GstBaseParseClass will handle both srcpad
115 * and sinkpad events. They will be passed to subclass if @event or
116 * @src_event callbacks have been provided.
121 * <itemizedlist><title>Shutdown phase</title>
123 * GstBaseParse class calls @stop to inform the subclass that data
124 * parsing will be stopped.
130 * Subclass is responsible for providing pad template caps for
131 * source and sink pads. The pads need to be named "sink" and "src". It also
132 * needs to set the fixed caps on srcpad, when the format is ensured (e.g.
133 * when base class calls subclass' @set_sink_caps function).
135 * This base class uses #GST_FORMAT_DEFAULT as a meaning of frames. So,
136 * subclass conversion routine needs to know that conversion from
137 * #GST_FORMAT_TIME to #GST_FORMAT_DEFAULT must return the
138 * frame number that can be found from the given byte position.
140 * GstBaseParse uses subclasses conversion methods also for seeking (or
141 * otherwise uses its own default one, see also below).
143 * Subclass @start and @stop functions will be called to inform the beginning
144 * and end of data processing.
146 * Things that subclass need to take care of:
148 * <listitem><para>Provide pad templates</para></listitem>
150 * Fixate the source pad caps when appropriate
153 * Inform base class how big data chunks should be retrieved. This is
154 * done with gst_base_parse_set_min_frame_size() function.
157 * Examine data chunks passed to subclass with @check_valid_frame
158 * and tell if they contain a valid frame
161 * Set the caps and timestamp to frame that is passed to subclass with
162 * @parse_frame function.
164 * <listitem><para>Provide conversion functions</para></listitem>
166 * Update the duration information with gst_base_parse_set_duration()
169 * Optionally passthrough using gst_base_parse_set_passthrough()
172 * Configure various baseparse parameters using
173 * gst_base_parse_set_average_bitrate(), gst_base_parse_set_syncable()
174 * and gst_base_parse_set_frame_rate().
177 * In particular, if subclass is unable to determine a duration, but
178 * parsing (or specs) yields a frames per seconds rate, then this can be
179 * provided to GstBaseParse to enable it to cater for
180 * buffer time metadata (which will be taken from upstream as much as
181 * possible). Internally keeping track of frame durations and respective
182 * sizes that have been pushed provides GstBaseParse with an estimated
183 * bitrate. A default @convert (used if not overriden) will then use these
184 * rates to perform obvious conversions. These rates are also used to
185 * update (estimated) duration at regular frame intervals.
192 * - In push mode provide a queue of adapter-"queued" buffers for upstream
194 * - Queue buffers/events until caps are set
204 /* FIXME 0.11: suppress warnings for deprecated API such as GStaticRecMutex
205 * with newer GLib versions (>= 2.31.0) */
206 #define GLIB_DISABLE_DEPRECATION_WARNINGS
207 #include <gst/base/gstadapter.h>
209 #include "gstbaseparse.h"
211 /* FIXME: get rid of old GstIndex code */
212 #include "gstindex.h"
213 #include "gstindex.c"
214 #include "gstmemindex.c"
216 #define GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC (1 << 0)
218 #define MIN_FRAMES_TO_POST_BITRATE 10
219 #define TARGET_DIFFERENCE (20 * GST_SECOND)
221 GST_DEBUG_CATEGORY_STATIC (gst_base_parse_debug);
222 #define GST_CAT_DEFAULT gst_base_parse_debug
224 /* Supported formats */
225 static const GstFormat fmtlist[] = {
232 #define GST_BASE_PARSE_GET_PRIVATE(obj) \
233 (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_PARSE, GstBaseParsePrivate))
235 struct _GstBaseParsePrivate
242 GstFormat duration_fmt;
243 gint64 estimated_duration;
244 gint64 estimated_drift;
246 guint min_frame_size;
247 gboolean passthrough;
249 gboolean has_timing_info;
250 guint fps_num, fps_den;
251 gint update_interval;
253 guint lead_in, lead_out;
254 GstClockTime lead_in_ts, lead_out_ts;
255 GstClockTime min_latency, max_latency;
263 GstClockTime next_ts;
264 GstClockTime prev_ts;
265 GstClockTime frame_duration;
266 gboolean seen_keyframe;
271 guint64 data_bytecount;
272 guint64 acc_duration;
273 GstClockTime first_frame_ts;
274 gint64 first_frame_offset;
276 gboolean post_min_bitrate;
277 gboolean post_avg_bitrate;
278 gboolean post_max_bitrate;
282 guint posted_avg_bitrate;
284 GList *pending_events;
286 /* frames/buffers that are queued and ready to go on OK */
287 GQueue queued_frames;
291 /* index entry storage, either ours or provided */
295 #if !GLIB_CHECK_VERSION (2, 31, 0)
296 GStaticMutex index_lock;
301 /* seek table entries only maintained if upstream is BYTE seekable */
302 gboolean upstream_seekable;
303 gboolean upstream_has_duration;
304 gint64 upstream_size;
305 /* minimum distance between two index entries */
306 GstClockTimeDiff idx_interval;
307 /* ts and offset of last entry added */
308 GstClockTime index_last_ts;
309 gint64 index_last_offset;
310 gboolean index_last_valid;
312 /* timestamps currently produced are accurate, e.g. started from 0 onwards */
313 gboolean exact_position;
314 /* seek events are temporarily kept to match them with newsegments */
315 GSList *pending_seeks;
317 /* reverse playback */
318 GSList *buffers_pending;
319 GSList *buffers_queued;
320 GSList *buffers_send;
321 GstClockTime last_ts;
324 /* Newsegment event to be sent after SEEK */
325 GstEvent *pending_segment;
327 /* Segment event that closes the running segment prior to SEEK */
328 GstEvent *close_segment;
330 /* push mode helper frame */
331 GstBaseParseFrame frame;
333 /* TRUE if we're still detecting the format, i.e.
334 * if ::detect() is still called for future buffers */
336 GList *detect_buffers;
337 guint detect_buffers_size;
340 typedef struct _GstBaseParseSeek
345 GstClockTime start_ts;
348 #if !GLIB_CHECK_VERSION (2, 31, 0)
349 #define GST_BASE_PARSE_INDEX_LOCK(parse) \
350 g_static_mutex_lock (&parse->priv->index_lock);
351 #define GST_BASE_PARSE_INDEX_UNLOCK(parse) \
352 g_static_mutex_unlock (&parse->priv->index_lock);
354 #define GST_BASE_PARSE_INDEX_LOCK(parse) \
355 g_mutex_lock (&parse->priv->index_lock);
356 #define GST_BASE_PARSE_INDEX_UNLOCK(parse) \
357 g_mutex_unlock (&parse->priv->index_lock);
360 static GstElementClass *parent_class = NULL;
362 static void gst_base_parse_class_init (GstBaseParseClass * klass);
363 static void gst_base_parse_init (GstBaseParse * parse,
364 GstBaseParseClass * klass);
367 gst_base_parse_get_type (void)
369 static volatile gsize base_parse_type = 0;
371 if (g_once_init_enter (&base_parse_type)) {
372 static const GTypeInfo base_parse_info = {
373 sizeof (GstBaseParseClass),
374 (GBaseInitFunc) NULL,
375 (GBaseFinalizeFunc) NULL,
376 (GClassInitFunc) gst_base_parse_class_init,
379 sizeof (GstBaseParse),
381 (GInstanceInitFunc) gst_base_parse_init,
385 _type = g_type_register_static (GST_TYPE_ELEMENT,
386 "GstBaseParse", &base_parse_info, G_TYPE_FLAG_ABSTRACT);
387 g_once_init_leave (&base_parse_type, _type);
389 return (GType) base_parse_type;
392 static void gst_base_parse_finalize (GObject * object);
394 static GstStateChangeReturn gst_base_parse_change_state (GstElement * element,
395 GstStateChange transition);
396 static void gst_base_parse_reset (GstBaseParse * parse);
399 static void gst_base_parse_set_index (GstElement * element, GstIndex * index);
400 static GstIndex *gst_base_parse_get_index (GstElement * element);
403 static gboolean gst_base_parse_sink_activate (GstPad * sinkpad,
405 static gboolean gst_base_parse_sink_activate_mode (GstPad * pad,
406 GstObject * parent, GstPadMode mode, gboolean active);
407 static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
409 static void gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event);
411 static gboolean gst_base_parse_src_event (GstPad * pad, GstObject * parent,
413 static gboolean gst_base_parse_src_query (GstPad * pad, GstObject * parent,
416 static gboolean gst_base_parse_sink_event (GstPad * pad, GstObject * parent,
418 static gboolean gst_base_parse_sink_query (GstPad * pad, GstObject * parent,
421 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstObject * parent,
423 static void gst_base_parse_loop (GstPad * pad);
425 static gboolean gst_base_parse_check_frame (GstBaseParse * parse,
426 GstBaseParseFrame * frame, guint * framesize, gint * skipsize);
427 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
428 GstBaseParseFrame * frame);
430 static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
433 static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
436 static void gst_base_parse_drain (GstBaseParse * parse);
438 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
439 gboolean post_min, gboolean post_avg, gboolean post_max);
441 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
442 GstClockTime time, gboolean before, GstClockTime * _ts);
443 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
444 GstClockTime * _time, gint64 * _offset);
446 static GstFlowReturn gst_base_parse_process_fragment (GstBaseParse * parse,
449 static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);
452 gst_base_parse_clear_queues (GstBaseParse * parse)
454 g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
455 g_slist_free (parse->priv->buffers_queued);
456 parse->priv->buffers_queued = NULL;
457 g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
459 g_slist_free (parse->priv->buffers_pending);
460 parse->priv->buffers_pending = NULL;
461 g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
462 g_slist_free (parse->priv->buffers_send);
463 parse->priv->buffers_send = NULL;
465 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
466 g_list_free (parse->priv->detect_buffers);
467 parse->priv->detect_buffers = NULL;
468 parse->priv->detect_buffers_size = 0;
470 g_queue_foreach (&parse->priv->queued_frames,
471 (GFunc) gst_base_parse_frame_free, NULL);
472 g_queue_clear (&parse->priv->queued_frames);
476 gst_base_parse_finalize (GObject * object)
478 GstBaseParse *parse = GST_BASE_PARSE (object);
481 g_object_unref (parse->priv->adapter);
483 if (parse->priv->pending_segment) {
484 p_ev = &parse->priv->pending_segment;
485 gst_event_replace (p_ev, NULL);
487 if (parse->priv->close_segment) {
488 p_ev = &parse->priv->close_segment;
489 gst_event_replace (p_ev, NULL);
492 if (parse->priv->cache) {
493 gst_buffer_unref (parse->priv->cache);
494 parse->priv->cache = NULL;
497 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
499 g_list_free (parse->priv->pending_events);
500 parse->priv->pending_events = NULL;
502 if (parse->priv->index) {
503 gst_object_unref (parse->priv->index);
504 parse->priv->index = NULL;
506 #if !GLIB_CHECK_VERSION (2, 31, 0)
507 g_static_mutex_free (&parse->priv->index_lock);
509 g_mutex_clear (&parse->priv->index_lock);
512 gst_base_parse_clear_queues (parse);
514 G_OBJECT_CLASS (parent_class)->finalize (object);
518 gst_base_parse_class_init (GstBaseParseClass * klass)
520 GObjectClass *gobject_class;
521 GstElementClass *gstelement_class;
523 gobject_class = G_OBJECT_CLASS (klass);
524 g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
525 parent_class = g_type_class_peek_parent (klass);
526 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
528 gstelement_class = (GstElementClass *) klass;
529 gstelement_class->change_state =
530 GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
533 gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
534 gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
537 /* Default handlers */
538 klass->check_valid_frame = gst_base_parse_check_frame;
539 klass->parse_frame = gst_base_parse_parse_frame;
540 klass->src_event = gst_base_parse_src_eventfunc;
541 klass->convert = gst_base_parse_convert_default;
543 GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
544 "baseparse element");
548 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
550 GstPadTemplate *pad_template;
552 GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
554 parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
557 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
558 g_return_if_fail (pad_template != NULL);
559 parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
560 gst_pad_set_event_function (parse->sinkpad,
561 GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
562 gst_pad_set_query_function (parse->sinkpad,
563 GST_DEBUG_FUNCPTR (gst_base_parse_sink_query));
564 gst_pad_set_chain_function (parse->sinkpad,
565 GST_DEBUG_FUNCPTR (gst_base_parse_chain));
566 gst_pad_set_activate_function (parse->sinkpad,
567 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
568 gst_pad_set_activatemode_function (parse->sinkpad,
569 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_mode));
570 gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
572 GST_DEBUG_OBJECT (parse, "sinkpad created");
575 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
576 g_return_if_fail (pad_template != NULL);
577 parse->srcpad = gst_pad_new_from_template (pad_template, "src");
578 gst_pad_set_event_function (parse->srcpad,
579 GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
580 gst_pad_set_query_function (parse->srcpad,
581 GST_DEBUG_FUNCPTR (gst_base_parse_src_query));
582 gst_pad_use_fixed_caps (parse->srcpad);
583 gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
584 GST_DEBUG_OBJECT (parse, "src created");
586 g_queue_init (&parse->priv->queued_frames);
588 parse->priv->adapter = gst_adapter_new ();
590 parse->priv->pad_mode = GST_PAD_MODE_NONE;
592 #if !GLIB_CHECK_VERSION (2, 31, 0)
593 g_static_mutex_init (&parse->priv->index_lock);
595 g_mutex_init (&parse->priv->index_lock);
599 gst_base_parse_reset (parse);
600 GST_DEBUG_OBJECT (parse, "init ok");
602 GST_OBJECT_FLAG_SET (parse, GST_ELEMENT_FLAG_INDEXABLE);
605 static GstBaseParseFrame *
606 gst_base_parse_frame_copy (GstBaseParseFrame * frame)
608 GstBaseParseFrame *copy;
610 copy = g_slice_dup (GstBaseParseFrame, frame);
611 copy->buffer = gst_buffer_ref (frame->buffer);
612 copy->_private_flags &= ~GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
614 GST_TRACE ("copied frame %p -> %p", frame, copy);
620 gst_base_parse_frame_free (GstBaseParseFrame * frame)
622 GST_TRACE ("freeing frame %p", frame);
625 gst_buffer_unref (frame->buffer);
626 frame->buffer = NULL;
629 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
630 g_slice_free (GstBaseParseFrame, frame);
632 memset (frame, 0, sizeof (*frame));
637 gst_base_parse_frame_get_type (void)
639 static volatile gsize frame_type = 0;
641 if (g_once_init_enter (&frame_type)) {
644 _type = g_boxed_type_register_static ("GstBaseParseFrame",
645 (GBoxedCopyFunc) gst_base_parse_frame_copy,
646 (GBoxedFreeFunc) gst_base_parse_frame_free);
647 g_once_init_leave (&frame_type, _type);
649 return (GType) frame_type;
653 * gst_base_parse_frame_init:
654 * @frame: #GstBaseParseFrame.
656 * Sets a #GstBaseParseFrame to initial state. Currently this means
657 * all public fields are zero-ed and a private flag is set to make
658 * sure gst_base_parse_frame_free() only frees the contents but not
659 * the actual frame. Use this function to initialise a #GstBaseParseFrame
660 * allocated on the stack.
665 gst_base_parse_frame_init (GstBaseParseFrame * frame)
667 memset (frame, 0, sizeof (GstBaseParseFrame));
668 frame->_private_flags = GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
669 GST_TRACE ("inited frame %p", frame);
673 * gst_base_parse_frame_new:
674 * @buffer: (transfer none): a #GstBuffer
676 * @overhead: number of bytes in this frame which should be counted as
677 * metadata overhead, ie. not used to calculate the average bitrate.
678 * Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
680 * Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
681 * elements written in C should usually allocate the frame on the stack and
682 * then use gst_base_parse_frame_init() to initialise it.
684 * Returns: a newly-allocated #GstBaseParseFrame. Free with
685 * gst_base_parse_frame_free() when no longer needed, unless you gave
686 * away ownership to gst_base_parse_push_frame().
691 gst_base_parse_frame_new (GstBuffer * buffer, GstBaseParseFrameFlags flags,
694 GstBaseParseFrame *frame;
696 frame = g_slice_new0 (GstBaseParseFrame);
697 frame->buffer = gst_buffer_ref (buffer);
699 GST_TRACE ("created frame %p", frame);
704 gst_base_parse_frame_update (GstBaseParse * parse, GstBaseParseFrame * frame,
707 gst_buffer_replace (&frame->buffer, buf);
711 /* set flags one by one for clarity */
712 if (G_UNLIKELY (parse->priv->drain))
713 parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;
715 /* losing sync is pretty much a discont (and vice versa), no ? */
716 if (G_UNLIKELY (parse->priv->discont))
717 parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
721 gst_base_parse_reset (GstBaseParse * parse)
723 GST_OBJECT_LOCK (parse);
724 gst_segment_init (&parse->segment, GST_FORMAT_TIME);
725 parse->priv->duration = -1;
726 parse->priv->min_frame_size = 1;
727 parse->priv->discont = TRUE;
728 parse->priv->flushing = FALSE;
729 parse->priv->offset = 0;
730 parse->priv->sync_offset = 0;
731 parse->priv->update_interval = -1;
732 parse->priv->fps_num = parse->priv->fps_den = 0;
733 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
734 parse->priv->lead_in = parse->priv->lead_out = 0;
735 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
736 parse->priv->bitrate = 0;
737 parse->priv->framecount = 0;
738 parse->priv->bytecount = 0;
739 parse->priv->acc_duration = 0;
740 parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
741 parse->priv->first_frame_offset = -1;
742 parse->priv->estimated_duration = -1;
743 parse->priv->estimated_drift = 0;
744 parse->priv->next_ts = 0;
745 parse->priv->syncable = TRUE;
746 parse->priv->passthrough = FALSE;
747 parse->priv->has_timing_info = FALSE;
748 parse->priv->post_min_bitrate = TRUE;
749 parse->priv->post_avg_bitrate = TRUE;
750 parse->priv->post_max_bitrate = TRUE;
751 parse->priv->min_bitrate = G_MAXUINT;
752 parse->priv->max_bitrate = 0;
753 parse->priv->avg_bitrate = 0;
754 parse->priv->posted_avg_bitrate = 0;
756 parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
757 parse->priv->index_last_offset = -1;
758 parse->priv->index_last_valid = TRUE;
759 parse->priv->upstream_seekable = FALSE;
760 parse->priv->upstream_size = 0;
761 parse->priv->upstream_has_duration = FALSE;
762 parse->priv->idx_interval = 0;
763 parse->priv->exact_position = TRUE;
764 parse->priv->seen_keyframe = FALSE;
766 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
767 parse->priv->last_offset = 0;
769 if (parse->priv->pending_segment) {
770 gst_event_unref (parse->priv->pending_segment);
771 parse->priv->pending_segment = NULL;
774 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
776 g_list_free (parse->priv->pending_events);
777 parse->priv->pending_events = NULL;
779 if (parse->priv->cache) {
780 gst_buffer_unref (parse->priv->cache);
781 parse->priv->cache = NULL;
784 g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
785 g_slist_free (parse->priv->pending_seeks);
786 parse->priv->pending_seeks = NULL;
788 /* we know it is not alloc'ed, but maybe other stuff to free, some day ... */
789 parse->priv->frame._private_flags |=
790 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
791 gst_base_parse_frame_free (&parse->priv->frame);
793 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
794 g_list_free (parse->priv->detect_buffers);
795 parse->priv->detect_buffers = NULL;
796 parse->priv->detect_buffers_size = 0;
797 GST_OBJECT_UNLOCK (parse);
800 /* gst_base_parse_check_frame:
801 * @parse: #GstBaseParse.
802 * @buffer: GstBuffer.
803 * @framesize: This will be set to tell the found frame size in bytes.
804 * @skipsize: Output parameter that tells how much data needs to be skipped
805 * in order to find the following frame header.
807 * Default callback for check_valid_frame.
809 * Returns: Always TRUE.
812 gst_base_parse_check_frame (GstBaseParse * parse,
813 GstBaseParseFrame * frame, guint * framesize, gint * skipsize)
815 *framesize = gst_buffer_get_size (frame->buffer);
821 /* gst_base_parse_parse_frame:
822 * @parse: #GstBaseParse.
823 * @buffer: #GstBuffer.
825 * Default callback for parse_frame.
828 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
830 GstBuffer *buffer = frame->buffer;
832 if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
833 GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
834 GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
836 if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
837 GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
838 GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
843 /* gst_base_parse_convert:
844 * @parse: #GstBaseParse.
845 * @src_format: #GstFormat describing the source format.
846 * @src_value: Source value to be converted.
847 * @dest_format: #GstFormat defining the converted format.
848 * @dest_value: Pointer where the conversion result will be put.
850 * Converts using configured "convert" vmethod in #GstBaseParse class.
852 * Returns: TRUE if conversion was successful.
855 gst_base_parse_convert (GstBaseParse * parse,
856 GstFormat src_format,
857 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
859 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
862 g_return_val_if_fail (dest_value != NULL, FALSE);
867 ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
869 #ifndef GST_DISABLE_GST_DEBUG
872 if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
873 GST_LOG_OBJECT (parse,
874 "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
875 GST_TIME_ARGS (src_value), *dest_value);
876 } else if (dest_format == GST_FORMAT_TIME &&
877 src_format == GST_FORMAT_BYTES) {
878 GST_LOG_OBJECT (parse,
879 "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
880 src_value, GST_TIME_ARGS (*dest_value));
882 GST_LOG_OBJECT (parse,
883 "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
884 GST_STR_NULL (gst_format_get_name (src_format)),
885 GST_STR_NULL (gst_format_get_name (dest_format)),
886 src_value, *dest_value);
889 GST_DEBUG_OBJECT (parse, "conversion failed");
897 /* gst_base_parse_sink_event:
898 * @pad: #GstPad that received the event.
899 * @event: #GstEvent to be handled.
901 * Handler for sink pad events.
903 * Returns: TRUE if the event was handled.
906 gst_base_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
909 GstBaseParseClass *bclass;
910 gboolean handled = FALSE;
913 parse = GST_BASE_PARSE (parent);
914 bclass = GST_BASE_PARSE_GET_CLASS (parse);
916 GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
917 GST_EVENT_TYPE_NAME (event));
919 /* Cache all events except EOS, SEGMENT and FLUSH_STOP if we have a
921 if (parse->priv->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
922 && GST_EVENT_TYPE (event) != GST_EVENT_SEGMENT
923 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
924 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP
925 && GST_EVENT_TYPE (event) != GST_EVENT_CAPS) {
927 if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
928 /* See if any bitrate tags were posted */
929 gst_base_parse_handle_tag (parse, event);
931 parse->priv->pending_events =
932 g_list_append (parse->priv->pending_events, event);
936 if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
937 parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
938 /* We've not posted bitrate tags yet - do so now */
939 gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
942 handled = bclass->event (parse, event);
945 handled = gst_base_parse_sink_eventfunc (parse, event);
948 ret = gst_pad_event_default (pad, parent, event);
951 GST_DEBUG_OBJECT (parse, "event handled");
957 /* gst_base_parse_sink_eventfunc:
958 * @parse: #GstBaseParse.
959 * @event: #GstEvent to be handled.
961 * Element-level event handler function.
963 * The event will be unreffed only if it has been handled and this
964 * function returns %TRUE
966 * Returns: %TRUE if the event was handled and not need forwarding.
969 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
971 gboolean handled = FALSE;
974 switch (GST_EVENT_TYPE (event)) {
978 GstBaseParseClass *klass;
980 klass = GST_BASE_PARSE_GET_CLASS (parse);
982 gst_event_parse_caps (event, &caps);
983 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
985 if (klass->set_sink_caps)
986 klass->set_sink_caps (parse, caps);
988 /* will send our own caps downstream */
989 gst_event_unref (event);
993 case GST_EVENT_SEGMENT:
995 const GstSegment *in_segment;
996 GstSegment out_segment;
997 gint64 offset = 0, next_ts;
1000 gdouble rate, applied_rate;
1002 gint64 start, stop, pos, next_ts;
1006 gst_event_parse_segment (event, &in_segment);
1007 gst_segment_init (&out_segment, GST_FORMAT_TIME);
1009 GST_DEBUG_OBJECT (parse, "segment %" GST_SEGMENT_FORMAT, in_segment);
1011 if (in_segment->format == GST_FORMAT_BYTES) {
1012 GstBaseParseSeek *seek = NULL;
1015 /* stop time is allowed to be open-ended, but not start & pos */
1016 offset = in_segment->time;
1018 GST_OBJECT_LOCK (parse);
1019 for (node = parse->priv->pending_seeks; node; node = node->next) {
1020 GstBaseParseSeek *tmp = node->data;
1022 if (tmp->offset == offset) {
1027 parse->priv->pending_seeks =
1028 g_slist_remove (parse->priv->pending_seeks, seek);
1029 GST_OBJECT_UNLOCK (parse);
1032 GST_DEBUG_OBJECT (parse,
1033 "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
1034 seek->accurate ? " accurate" : "", &seek->segment);
1036 out_segment.start = seek->segment.start;
1037 out_segment.stop = seek->segment.stop;
1038 out_segment.time = seek->segment.start;
1040 next_ts = seek->start_ts;
1041 parse->priv->exact_position = seek->accurate;
1044 /* best attempt convert */
1045 /* as these are only estimates, stop is kept open-ended to avoid
1046 * premature cutting */
1047 gst_base_parse_convert (parse, GST_FORMAT_BYTES, in_segment->start,
1048 GST_FORMAT_TIME, (gint64 *) & next_ts);
1050 out_segment.start = next_ts;
1051 out_segment.stop = GST_CLOCK_TIME_NONE;
1052 out_segment.time = next_ts;
1054 parse->priv->exact_position = (in_segment->start == 0);
1057 gst_event_unref (event);
1059 event = gst_event_new_segment (&out_segment);
1061 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. %"
1062 GST_SEGMENT_FORMAT, in_segment);
1064 } else if (in_segment->format != GST_FORMAT_TIME) {
1065 /* Unknown incoming segment format. Output a default open-ended
1067 gst_event_unref (event);
1069 out_segment.start = 0;
1070 out_segment.stop = GST_CLOCK_TIME_NONE;;
1071 out_segment.time = 0;;
1073 event = gst_event_new_segment (&out_segment);
1077 /* not considered BYTE seekable if it is talking to us in TIME,
1078 * whatever else it might claim */
1079 parse->priv->upstream_seekable = FALSE;
1080 next_ts = in_segment->start;
1083 memcpy (&parse->segment, &out_segment, sizeof (GstSegment));
1086 gst_segment_set_newsegment (&parse->segment, update, rate,
1087 applied_rate, format, start, stop, start);
1090 /* save the segment for later, right before we push a new buffer so that
1091 * the caps are fixed and the next linked element can receive
1093 eventp = &parse->priv->pending_segment;
1094 gst_event_replace (eventp, event);
1095 gst_event_unref (event);
1098 /* but finish the current segment */
1099 GST_DEBUG_OBJECT (parse, "draining current segment");
1100 if (in_segment->rate > 0.0)
1101 gst_base_parse_drain (parse);
1103 gst_base_parse_process_fragment (parse, FALSE);
1104 gst_adapter_clear (parse->priv->adapter);
1106 parse->priv->offset = offset;
1107 parse->priv->sync_offset = offset;
1108 parse->priv->next_ts = next_ts;
1109 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1110 parse->priv->discont = TRUE;
1111 parse->priv->seen_keyframe = FALSE;
1115 case GST_EVENT_FLUSH_START:
1116 parse->priv->flushing = TRUE;
1117 handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
1119 gst_event_unref (event);
1120 /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
1121 GST_PAD_STREAM_LOCK (parse->srcpad);
1122 GST_PAD_STREAM_UNLOCK (parse->srcpad);
1126 case GST_EVENT_FLUSH_STOP:
1127 gst_adapter_clear (parse->priv->adapter);
1128 gst_base_parse_clear_queues (parse);
1129 parse->priv->flushing = FALSE;
1130 parse->priv->discont = TRUE;
1131 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1132 parse->priv->frame._private_flags |=
1133 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
1134 gst_base_parse_frame_free (&parse->priv->frame);
1138 if (parse->segment.rate > 0.0)
1139 gst_base_parse_drain (parse);
1141 gst_base_parse_process_fragment (parse, FALSE);
1143 /* If we STILL have zero frames processed, fire an error */
1144 if (parse->priv->framecount == 0) {
1145 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1146 ("No valid frames found before end of stream"), (NULL));
1148 /* newsegment before eos */
1149 if (parse->priv->pending_segment) {
1150 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1151 parse->priv->pending_segment = NULL;
1163 gst_base_parse_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
1165 GstBaseParse *parse;
1166 GstBaseParseClass *bclass;
1169 parse = GST_BASE_PARSE (parent);
1170 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1172 switch (GST_QUERY_TYPE (query)) {
1173 case GST_QUERY_CAPS:
1175 if (bclass->get_sink_caps) {
1176 GstCaps *caps, *filter;
1178 gst_query_parse_caps (query, &filter);
1179 caps = bclass->get_sink_caps (parse, filter);
1180 GST_LOG_OBJECT (parse, "sink getcaps returning caps %" GST_PTR_FORMAT,
1182 gst_query_set_caps_result (query, caps);
1183 gst_caps_unref (caps);
1187 GstCaps *caps, *template_caps, *filter;
1189 gst_query_parse_caps (query, &filter);
1190 template_caps = gst_pad_get_pad_template_caps (pad);
1191 if (filter != NULL) {
1193 gst_caps_intersect_full (filter, template_caps,
1194 GST_CAPS_INTERSECT_FIRST);
1196 caps = gst_caps_copy (template_caps);
1198 gst_query_set_caps_result (query, caps);
1199 gst_caps_unref (caps);
1207 res = gst_pad_query_default (pad, parent, query);
1216 /* gst_base_parse_src_event:
1217 * @pad: #GstPad that received the event.
1218 * @event: #GstEvent that was received.
1220 * Handler for source pad events.
1222 * Returns: TRUE if the event was handled.
1225 gst_base_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1227 GstBaseParse *parse;
1228 GstBaseParseClass *bclass;
1229 gboolean handled = FALSE;
1230 gboolean ret = TRUE;
1232 parse = GST_BASE_PARSE (parent);
1233 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1235 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1236 GST_EVENT_TYPE_NAME (event));
1238 if (bclass->src_event)
1239 handled = bclass->src_event (parse, event);
1242 ret = gst_pad_event_default (pad, parent, event);
1248 gst_base_parse_is_seekable (GstBaseParse * parse)
1250 /* FIXME: could do more here, e.g. check index or just send data from 0
1251 * in pull mode and let decoder/sink clip */
1252 return parse->priv->syncable;
1255 /* gst_base_parse_src_eventfunc:
1256 * @parse: #GstBaseParse.
1257 * @event: #GstEvent that was received.
1259 * Default srcpad event handler.
1261 * Returns: TRUE if the event was handled and can be dropped.
1264 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1266 gboolean handled = FALSE;
1268 switch (GST_EVENT_TYPE (event)) {
1269 case GST_EVENT_SEEK:
1271 if (gst_base_parse_is_seekable (parse)) {
1272 handled = gst_base_parse_handle_seek (parse, event);
1284 * gst_base_parse_convert_default:
1285 * @parse: #GstBaseParse.
1286 * @src_format: #GstFormat describing the source format.
1287 * @src_value: Source value to be converted.
1288 * @dest_format: #GstFormat defining the converted format.
1289 * @dest_value: Pointer where the conversion result will be put.
1291 * Default implementation of "convert" vmethod in #GstBaseParse class.
1293 * Returns: TRUE if conversion was successful.
1298 gst_base_parse_convert_default (GstBaseParse * parse,
1299 GstFormat src_format,
1300 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1302 gboolean ret = FALSE;
1303 guint64 bytes, duration;
1305 if (G_UNLIKELY (src_format == dest_format)) {
1306 *dest_value = src_value;
1310 if (G_UNLIKELY (src_value == -1)) {
1315 if (G_UNLIKELY (src_value == 0)) {
1320 /* need at least some frames */
1321 if (!parse->priv->framecount)
1324 duration = parse->priv->acc_duration / GST_MSECOND;
1325 bytes = parse->priv->bytecount;
1327 if (G_UNLIKELY (!duration || !bytes))
1330 if (src_format == GST_FORMAT_BYTES) {
1331 if (dest_format == GST_FORMAT_TIME) {
1332 /* BYTES -> TIME conversion */
1333 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1334 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1335 *dest_value *= GST_MSECOND;
1336 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1337 *dest_value / GST_MSECOND);
1340 } else if (src_format == GST_FORMAT_TIME) {
1341 if (dest_format == GST_FORMAT_BYTES) {
1342 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1343 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1345 GST_DEBUG_OBJECT (parse,
1346 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1347 src_value / GST_MSECOND, *dest_value);
1350 } else if (src_format == GST_FORMAT_DEFAULT) {
1351 /* DEFAULT == frame-based */
1352 if (dest_format == GST_FORMAT_TIME) {
1353 if (parse->priv->fps_den) {
1354 *dest_value = gst_util_uint64_scale (src_value,
1355 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1358 } else if (dest_format == GST_FORMAT_BYTES) {
1366 gst_base_parse_update_duration (GstBaseParse * baseparse)
1369 GstBaseParse *parse;
1371 parse = GST_BASE_PARSE (baseparse);
1373 peer = gst_pad_get_peer (parse->sinkpad);
1375 gboolean qres = FALSE;
1376 gint64 ptot, dest_value;
1378 qres = gst_pad_query_duration (peer, GST_FORMAT_BYTES, &ptot);
1379 gst_object_unref (GST_OBJECT (peer));
1381 if (gst_base_parse_convert (parse, GST_FORMAT_BYTES, ptot,
1382 GST_FORMAT_TIME, &dest_value)) {
1384 /* inform if duration changed, but try to avoid spamming */
1385 parse->priv->estimated_drift +=
1386 dest_value - parse->priv->estimated_duration;
1387 if (parse->priv->estimated_drift > GST_SECOND ||
1388 parse->priv->estimated_drift < -GST_SECOND) {
1389 gst_element_post_message (GST_ELEMENT (parse),
1390 gst_message_new_duration (GST_OBJECT (parse),
1391 GST_FORMAT_TIME, dest_value));
1392 parse->priv->estimated_drift = 0;
1394 parse->priv->estimated_duration = dest_value;
1395 GST_LOG_OBJECT (parse,
1396 "updated estimated duration to %" GST_TIME_FORMAT,
1397 GST_TIME_ARGS (dest_value));
1404 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1405 gboolean post_avg, gboolean post_max)
1407 GstTagList *taglist = NULL;
1409 if (post_min && parse->priv->post_min_bitrate) {
1410 taglist = gst_tag_list_new_empty ();
1412 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1413 GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1416 if (post_avg && parse->priv->post_avg_bitrate) {
1417 if (taglist == NULL)
1418 taglist = gst_tag_list_new_empty ();
1420 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1421 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1422 parse->priv->avg_bitrate, NULL);
1425 if (post_max && parse->priv->post_max_bitrate) {
1426 if (taglist == NULL)
1427 taglist = gst_tag_list_new_empty ();
1429 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1430 GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1433 GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1434 parse->priv->min_bitrate, parse->priv->avg_bitrate,
1435 parse->priv->max_bitrate);
1437 if (taglist != NULL) {
1438 gst_pad_push_event (parse->srcpad, gst_event_new_tag (taglist));
1442 /* gst_base_parse_update_bitrates:
1443 * @parse: #GstBaseParse.
1444 * @buffer: Current frame as a #GstBuffer
1446 * Keeps track of the minimum and maximum bitrates, and also maintains a
1447 * running average bitrate of the stream so far.
1450 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1452 /* Only update the tag on a 10 kbps delta */
1453 static const gint update_threshold = 10000;
1455 guint64 data_len, frame_dur;
1456 gint overhead, frame_bitrate, old_avg_bitrate;
1457 gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1458 GstBuffer *buffer = frame->buffer;
1460 overhead = frame->overhead;
1464 data_len = gst_buffer_get_size (buffer) - overhead;
1465 parse->priv->data_bytecount += data_len;
1467 /* duration should be valid by now,
1468 * either set by subclass or maybe based on fps settings */
1469 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1470 /* Calculate duration of a frame from buffer properties */
1471 frame_dur = GST_BUFFER_DURATION (buffer);
1472 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1473 parse->priv->acc_duration;
1476 /* No way to figure out frame duration (is this even possible?) */
1480 /* override if subclass provided bitrate, e.g. metadata based */
1481 if (parse->priv->bitrate) {
1482 parse->priv->avg_bitrate = parse->priv->bitrate;
1483 /* spread this (confirmed) info ASAP */
1484 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1485 gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1489 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1493 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1494 parse->priv->avg_bitrate);
1496 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1498 } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1499 /* always post all at threshold time */
1500 update_min = update_max = update_avg = TRUE;
1503 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1504 if (frame_bitrate < parse->priv->min_bitrate) {
1505 parse->priv->min_bitrate = frame_bitrate;
1509 if (frame_bitrate > parse->priv->max_bitrate) {
1510 parse->priv->max_bitrate = frame_bitrate;
1514 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1515 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1516 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1521 if ((update_min || update_avg || update_max))
1522 gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1524 /* If average bitrate changes that much and no valid (time) duration provided,
1525 * then post a new duration message so applications can update their cached
1527 if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1528 GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1529 gst_element_post_message (GST_ELEMENT (parse),
1530 gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1537 * gst_base_parse_add_index_entry:
1538 * @parse: #GstBaseParse.
1539 * @offset: offset of entry
1540 * @ts: timestamp associated with offset
1541 * @key: whether entry refers to keyframe
1542 * @force: add entry disregarding sanity checks
1544 * Adds an entry to the index associating @offset to @ts. It is recommended
1545 * to only add keyframe entries. @force allows to bypass checks, such as
1546 * whether the stream is (upstream) seekable, another entry is already "close"
1547 * to the new entry, etc.
1549 * Returns: #gboolean indicating whether entry was added
1554 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1555 GstClockTime ts, gboolean key, gboolean force)
1557 gboolean ret = FALSE;
1558 GstIndexAssociation associations[2];
1560 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1561 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1563 if (G_LIKELY (!force)) {
1565 if (!parse->priv->upstream_seekable) {
1566 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1570 /* FIXME need better helper data structure that handles these issues
1571 * related to ongoing collecting of index entries */
1572 if (parse->priv->index_last_offset >= (gint64) offset) {
1573 GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1574 "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1578 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1579 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1580 parse->priv->idx_interval) {
1581 GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1582 GST_TIME_ARGS (parse->priv->index_last_ts));
1586 /* if last is not really the last one */
1587 if (!parse->priv->index_last_valid) {
1588 GstClockTime prev_ts;
1590 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1591 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1592 GST_DEBUG_OBJECT (parse,
1593 "entry too close to existing entry %" GST_TIME_FORMAT,
1594 GST_TIME_ARGS (prev_ts));
1595 parse->priv->index_last_offset = offset;
1596 parse->priv->index_last_ts = ts;
1602 associations[0].format = GST_FORMAT_TIME;
1603 associations[0].value = ts;
1604 associations[1].format = GST_FORMAT_BYTES;
1605 associations[1].value = offset;
1607 /* index might change on-the-fly, although that would be nutty app ... */
1608 GST_BASE_PARSE_INDEX_LOCK (parse);
1609 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1610 (key) ? GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT :
1611 GST_INDEX_ASSOCIATION_FLAG_DELTA_UNIT, 2,
1612 (const GstIndexAssociation *) &associations);
1613 GST_BASE_PARSE_INDEX_UNLOCK (parse);
1616 parse->priv->index_last_offset = offset;
1617 parse->priv->index_last_ts = ts;
1626 /* check for seekable upstream, above and beyond a mere query */
1628 gst_base_parse_check_seekability (GstBaseParse * parse)
1631 gboolean seekable = FALSE;
1632 gint64 start = -1, stop = -1;
1633 guint idx_interval = 0;
1635 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1636 if (!gst_pad_peer_query (parse->sinkpad, query)) {
1637 GST_DEBUG_OBJECT (parse, "seeking query failed");
1641 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1643 /* try harder to query upstream size if we didn't get it the first time */
1644 if (seekable && stop == -1) {
1645 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1646 gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_BYTES, &stop);
1649 /* if upstream doesn't know the size, it's likely that it's not seekable in
1650 * practice even if it technically may be seekable */
1651 if (seekable && (start != 0 || stop <= start)) {
1652 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1656 /* let's not put every single frame into our index */
1658 if (stop < 10 * 1024 * 1024)
1660 else if (stop < 100 * 1024 * 1024)
1663 idx_interval = 1000;
1667 gst_query_unref (query);
1669 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1670 G_GUINT64_FORMAT ")", seekable, start, stop);
1671 parse->priv->upstream_seekable = seekable;
1672 parse->priv->upstream_size = seekable ? stop : 0;
1674 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1675 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1678 /* some misc checks on upstream */
1680 gst_base_parse_check_upstream (GstBaseParse * parse)
1684 if (gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_TIME, &stop))
1685 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1686 /* upstream has one, accept it also, and no further updates */
1687 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1688 parse->priv->upstream_has_duration = TRUE;
1691 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1692 parse->priv->upstream_has_duration);
1695 /* checks src caps to determine if dealing with audio or video */
1696 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1698 gst_base_parse_check_media (GstBaseParse * parse)
1703 caps = gst_pad_get_current_caps (parse->srcpad);
1704 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1705 parse->priv->is_video =
1706 g_str_has_prefix (gst_structure_get_name (s), "video");
1708 /* historical default */
1709 parse->priv->is_video = FALSE;
1712 gst_caps_unref (caps);
1714 GST_DEBUG_OBJECT (parse, "media is video: %d", parse->priv->is_video);
1717 /* takes ownership of frame */
1719 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1721 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1722 /* frame allocated on the heap, we can just take ownership */
1723 g_queue_push_tail (&parse->priv->queued_frames, frame);
1724 GST_TRACE ("queued frame %p", frame);
1726 GstBaseParseFrame *copy;
1728 /* probably allocated on the stack, must make a proper copy */
1729 copy = gst_base_parse_frame_copy (frame);
1730 g_queue_push_tail (&parse->priv->queued_frames, copy);
1731 GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1732 gst_base_parse_frame_free (frame);
1736 /* gst_base_parse_handle_and_push_buffer:
1737 * @parse: #GstBaseParse.
1738 * @klass: #GstBaseParseClass.
1739 * @frame: (transfer full): a #GstBaseParseFrame
1741 * Parses the frame from given buffer and pushes it forward. Also performs
1742 * timestamp handling and checks the segment limits.
1744 * This is called with srcpad STREAM_LOCK held.
1746 * Returns: #GstFlowReturn
1748 static GstFlowReturn
1749 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1750 GstBaseParseClass * klass, GstBaseParseFrame * frame)
1756 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1758 buffer = frame->buffer;
1760 if (parse->priv->discont) {
1761 GST_DEBUG_OBJECT (parse, "marking DISCONT");
1762 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1763 parse->priv->discont = FALSE;
1766 /* some one-time start-up */
1767 if (G_UNLIKELY (!parse->priv->framecount)) {
1768 gst_base_parse_check_seekability (parse);
1769 gst_base_parse_check_upstream (parse);
1772 GST_LOG_OBJECT (parse,
1773 "parsing frame at offset %" G_GUINT64_FORMAT
1774 " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
1775 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1776 gst_buffer_get_size (buffer));
1778 /* use default handler to provide initial (upstream) metadata */
1779 gst_base_parse_parse_frame (parse, frame);
1781 /* store offset as it might get overwritten */
1782 offset = GST_BUFFER_OFFSET (buffer);
1783 ret = klass->parse_frame (parse, frame);
1785 buffer = frame->buffer;
1786 /* subclass must play nice */
1787 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1789 /* check if subclass/format can provide ts.
1790 * If so, that allows and enables extra seek and duration determining options */
1791 if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
1792 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && parse->priv->has_timing_info
1793 && parse->priv->pad_mode == GST_PAD_MODE_PULL) {
1794 parse->priv->first_frame_offset = offset;
1795 parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1796 GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1797 " for first frame at offset %" G_GINT64_FORMAT,
1798 GST_TIME_ARGS (parse->priv->first_frame_ts),
1799 parse->priv->first_frame_offset);
1800 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1802 GstClockTime last_ts = G_MAXINT64;
1804 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1805 gst_base_parse_locate_time (parse, &last_ts, &off);
1806 if (GST_CLOCK_TIME_IS_VALID (last_ts))
1807 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1810 /* disable further checks */
1811 parse->priv->first_frame_offset = 0;
1815 /* again use default handler to add missing metadata;
1816 * we may have new information on frame properties */
1817 gst_base_parse_parse_frame (parse, frame);
1818 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1819 GST_BUFFER_DURATION_IS_VALID (buffer)) {
1820 parse->priv->next_ts =
1821 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1823 /* we lost track, do not produce bogus time next time around
1824 * (probably means parser subclass has given up on parsing as well) */
1825 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1826 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1829 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1830 GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1831 gst_base_parse_add_index_entry (parse, offset,
1832 GST_BUFFER_TIMESTAMP (buffer),
1833 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1835 /* First buffers are dropped, this means that the subclass needs more
1836 * frames to decide on the format and queues them internally */
1837 /* convert internal flow to OK and mark discont for the next buffer. */
1838 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1839 gst_base_parse_frame_free (frame);
1841 } else if (ret == GST_BASE_PARSE_FLOW_QUEUED) {
1842 gst_base_parse_queue_frame (parse, frame);
1844 } else if (ret != GST_FLOW_OK) {
1848 /* All OK, push queued frames if there are any */
1849 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
1850 GstBaseParseFrame *queued_frame;
1852 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
1853 gst_base_parse_push_frame (parse, queued_frame);
1857 return gst_base_parse_push_frame (parse, frame);
1861 * gst_base_parse_push_frame:
1862 * @parse: #GstBaseParse.
1863 * @frame: (transfer full): a #GstBaseParseFrame
1865 * Pushes the frame downstream, sends any pending events and
1866 * does some timestamp and segment handling. Takes ownership
1867 * of @frame and will clear it (if it was initialised with
1868 * gst_base_parse_frame_init()) or free it.
1870 * This must be called with sinkpad STREAM_LOCK held.
1872 * Returns: #GstFlowReturn
1877 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1879 GstFlowReturn ret = GST_FLOW_OK;
1880 GstClockTime last_start = GST_CLOCK_TIME_NONE;
1881 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1882 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1886 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1887 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
1889 GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
1891 buffer = frame->buffer;
1893 GST_LOG_OBJECT (parse,
1894 "processing buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1895 ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buffer),
1896 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1897 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1900 size = gst_buffer_get_size (buffer);
1901 parse->priv->bytecount += size;
1902 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1903 parse->priv->framecount++;
1904 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1905 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1908 /* 0 means disabled */
1909 if (parse->priv->update_interval < 0)
1910 parse->priv->update_interval = 50;
1911 else if (parse->priv->update_interval > 0 &&
1912 (parse->priv->framecount % parse->priv->update_interval) == 0)
1913 gst_base_parse_update_duration (parse);
1915 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1916 last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1917 if (last_start != GST_CLOCK_TIME_NONE
1918 && GST_BUFFER_DURATION_IS_VALID (buffer))
1919 last_stop = last_start + GST_BUFFER_DURATION (buffer);
1921 /* should have caps by now */
1922 if (!gst_pad_has_current_caps (parse->srcpad))
1925 /* segment adjustment magic; only if we are running the whole show */
1926 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1927 (parse->priv->pad_mode == GST_PAD_MODE_PULL ||
1928 parse->priv->upstream_seekable)) {
1929 /* segment times are typically estimates,
1930 * actual frame data might lead subclass to different timestamps,
1931 * so override segment start from what is supplied there */
1932 if (G_UNLIKELY (parse->priv->pending_segment && !parse->priv->exact_position
1933 && GST_CLOCK_TIME_IS_VALID (last_start))) {
1934 gst_event_unref (parse->priv->pending_segment);
1935 parse->segment.start =
1936 MIN ((guint64) last_start, (guint64) parse->segment.stop);
1938 GST_DEBUG_OBJECT (parse,
1939 "adjusting pending segment start to %" GST_TIME_FORMAT,
1940 GST_TIME_ARGS (parse->segment.start));
1942 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
1944 /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1945 if (GST_CLOCK_TIME_IS_VALID (parse->segment.position) &&
1946 GST_CLOCK_TIME_IS_VALID (last_start)) {
1947 GstClockTimeDiff diff;
1949 /* only send newsegments with increasing start times,
1950 * otherwise if these go back and forth downstream (sinks) increase
1951 * accumulated time and running_time */
1952 diff = GST_CLOCK_DIFF (parse->segment.position, last_start);
1953 if (G_UNLIKELY (diff > 2 * GST_SECOND
1954 && last_start > parse->segment.start
1955 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
1956 || last_start < parse->segment.stop))) {
1958 GST_DEBUG_OBJECT (parse,
1959 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
1960 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1961 "Sending updated NEWSEGMENT events", diff,
1962 GST_TIME_ARGS (parse->segment.position),
1963 GST_TIME_ARGS (last_start));
1965 if (G_UNLIKELY (parse->priv->pending_segment)) {
1966 gst_event_unref (parse->priv->pending_segment);
1967 parse->segment.start = last_start;
1968 parse->segment.time = last_start;
1969 parse->priv->pending_segment =
1970 gst_event_new_segment (&parse->segment);
1972 /* skip gap FIXME */
1973 gst_pad_push_event (parse->srcpad,
1974 gst_event_new_segment (&parse->segment));
1976 parse->segment.position = last_start;
1981 /* and should then also be linked downstream, so safe to send some events */
1982 if (G_UNLIKELY (parse->priv->close_segment)) {
1983 /* only set up by loop */
1984 GST_DEBUG_OBJECT (parse, "loop sending close segment");
1985 gst_pad_push_event (parse->srcpad, parse->priv->close_segment);
1986 parse->priv->close_segment = NULL;
1988 if (G_UNLIKELY (parse->priv->pending_segment)) {
1989 GstEvent *pending_segment;
1991 pending_segment = parse->priv->pending_segment;
1992 parse->priv->pending_segment = NULL;
1994 GST_DEBUG_OBJECT (parse, "%s push pending segment",
1995 parse->priv->pad_mode == GST_PAD_MODE_PULL ? "loop" : "chain");
1996 gst_pad_push_event (parse->srcpad, pending_segment);
1998 /* have caps; check identity */
1999 gst_base_parse_check_media (parse);
2002 /* update bitrates and optionally post corresponding tags
2003 * (following newsegment) */
2004 gst_base_parse_update_bitrates (parse, frame);
2006 if (G_UNLIKELY (parse->priv->pending_events)) {
2009 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
2010 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
2012 g_list_free (parse->priv->pending_events);
2013 parse->priv->pending_events = NULL;
2016 if (klass->pre_push_frame) {
2017 ret = klass->pre_push_frame (parse, frame);
2019 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
2022 /* take final ownership of frame buffer */
2023 buffer = frame->buffer;
2024 frame->buffer = NULL;
2026 /* subclass must play nice */
2027 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2029 parse->priv->seen_keyframe |= parse->priv->is_video &&
2030 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
2032 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
2033 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2034 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
2035 GST_BUFFER_TIMESTAMP (buffer) >
2036 parse->segment.stop + parse->priv->lead_out_ts) {
2037 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
2039 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2040 GST_BUFFER_DURATION_IS_VALID (buffer) &&
2041 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
2042 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
2043 parse->priv->lead_in_ts < parse->segment.start) {
2044 if (parse->priv->seen_keyframe) {
2045 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
2048 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
2049 ret = GST_BASE_PARSE_FLOW_DROPPED;
2056 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
2057 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) dropped", size);
2058 gst_buffer_unref (buffer);
2060 } else if (ret == GST_FLOW_OK) {
2061 if (parse->segment.rate > 0.0) {
2062 GST_LOG_OBJECT (parse, "pushing frame (%" G_GSIZE_FORMAT " bytes) now..",
2064 ret = gst_pad_push (parse->srcpad, buffer);
2065 GST_LOG_OBJECT (parse, "frame pushed, flow %s", gst_flow_get_name (ret));
2067 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) queued for now",
2069 parse->priv->buffers_queued =
2070 g_slist_prepend (parse->priv->buffers_queued, buffer);
2074 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s",
2075 size, gst_flow_get_name (ret));
2076 gst_buffer_unref (buffer);
2077 /* if we are not sufficiently in control, let upstream decide on EOS */
2078 if (ret == GST_FLOW_EOS &&
2079 (parse->priv->passthrough ||
2080 (parse->priv->pad_mode == GST_PAD_MODE_PUSH &&
2081 !parse->priv->upstream_seekable)))
2085 /* Update current running segment position */
2086 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
2087 parse->segment.position < last_stop)
2088 parse->segment.position = last_stop;
2090 gst_base_parse_frame_free (frame);
2097 GST_ELEMENT_ERROR (parse, STREAM, DECODE, ("No caps set"), (NULL));
2098 return GST_FLOW_ERROR;
2103 /* gst_base_parse_drain:
2105 * Drains the adapter until it is empty. It decreases the min_frame_size to
2106 * match the current adapter size and calls chain method until the adapter
2107 * is emptied or chain returns with error.
2110 gst_base_parse_drain (GstBaseParse * parse)
2114 GST_DEBUG_OBJECT (parse, "draining");
2115 parse->priv->drain = TRUE;
2118 avail = gst_adapter_available (parse->priv->adapter);
2122 if (gst_base_parse_chain (parse->sinkpad, GST_OBJECT_CAST (parse),
2123 NULL) != GST_FLOW_OK) {
2127 /* nothing changed, maybe due to truncated frame; break infinite loop */
2128 if (avail == gst_adapter_available (parse->priv->adapter)) {
2129 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
2130 gst_adapter_clear (parse->priv->adapter);
2134 parse->priv->drain = FALSE;
2137 /* gst_base_parse_send_buffers
2139 * Sends buffers collected in send_buffers downstream, and ensures that list
2140 * is empty at the end (errors or not).
2142 static GstFlowReturn
2143 gst_base_parse_send_buffers (GstBaseParse * parse)
2145 GSList *send = NULL;
2147 GstFlowReturn ret = GST_FLOW_OK;
2149 send = parse->priv->buffers_send;
2153 buf = GST_BUFFER_CAST (send->data);
2154 GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
2155 GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2156 ", offset %" G_GINT64_FORMAT, buf,
2157 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2158 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2160 /* iterate output queue an push downstream */
2161 ret = gst_pad_push (parse->srcpad, buf);
2162 send = g_slist_delete_link (send, send);
2164 /* clear any leftover if error */
2165 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2167 buf = GST_BUFFER_CAST (send->data);
2168 gst_buffer_unref (buf);
2169 send = g_slist_delete_link (send, send);
2174 parse->priv->buffers_send = send;
2179 /* gst_base_parse_process_fragment:
2181 * Processes a reverse playback (forward) fragment:
2182 * - append head of last fragment that was skipped to current fragment data
2183 * - drain the resulting current fragment data (i.e. repeated chain)
2184 * - add time/duration (if needed) to frames queued by chain
2185 * - push queued data
2187 static GstFlowReturn
2188 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
2191 GstFlowReturn ret = GST_FLOW_OK;
2192 gboolean seen_key = FALSE, seen_delta = FALSE;
2198 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2199 while (parse->priv->buffers_pending) {
2200 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2201 GST_LOG_OBJECT (parse, "adding pending buffer (size %" G_GSIZE_FORMAT ")",
2202 gst_buffer_get_size (buf));
2203 gst_adapter_push (parse->priv->adapter, buf);
2204 parse->priv->buffers_pending =
2205 g_slist_delete_link (parse->priv->buffers_pending,
2206 parse->priv->buffers_pending);
2209 /* invalidate so no fall-back timestamping is performed;
2210 * ok if taken from subclass or upstream */
2211 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
2212 /* prevent it hanging around stop all the time */
2213 parse->segment.position = GST_CLOCK_TIME_NONE;
2215 parse->priv->discont = TRUE;
2217 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2218 /* initial skipped data is added to buffers_pending */
2219 gst_base_parse_drain (parse);
2222 if (parse->priv->buffers_send) {
2223 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2224 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2227 /* add metadata (if needed to queued buffers */
2228 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2229 GST_TIME_ARGS (parse->priv->last_ts));
2230 while (parse->priv->buffers_queued) {
2231 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2233 /* no touching if upstream or parsing provided time */
2234 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2235 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2236 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2237 } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
2238 GST_BUFFER_DURATION_IS_VALID (buf)) {
2239 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
2240 parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
2242 parse->priv->last_ts = 0;
2243 GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
2244 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2245 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2247 /* no idea, very bad */
2248 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2251 parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
2253 /* reverse order for ascending sending */
2254 /* send downstream at keyframe not preceded by a keyframe
2255 * (e.g. that should identify start of collection of IDR nals) */
2256 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2258 ret = gst_base_parse_send_buffers (parse);
2259 /* if a problem, throw all to sending */
2260 if (ret != GST_FLOW_OK) {
2261 parse->priv->buffers_send =
2262 g_slist_reverse (parse->priv->buffers_queued);
2263 parse->priv->buffers_queued = NULL;
2272 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2274 parse->priv->buffers_send =
2275 g_slist_prepend (parse->priv->buffers_send, buf);
2276 parse->priv->buffers_queued =
2277 g_slist_delete_link (parse->priv->buffers_queued,
2278 parse->priv->buffers_queued);
2281 /* audio may have all marked as keyframe, so arrange to send here */
2283 ret = gst_base_parse_send_buffers (parse);
2285 /* any trailing unused no longer usable (ideally none) */
2286 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2287 GST_DEBUG_OBJECT (parse, "discarding %" G_GSIZE_FORMAT " trailing bytes",
2288 gst_adapter_available (parse->priv->adapter));
2289 gst_adapter_clear (parse->priv->adapter);
2295 /* small helper that checks whether we have been trying to resync too long */
2296 static inline GstFlowReturn
2297 gst_base_parse_check_sync (GstBaseParse * parse)
2299 if (G_UNLIKELY (parse->priv->discont &&
2300 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2301 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2302 ("Failed to parse stream"), (NULL));
2303 return GST_FLOW_ERROR;
2309 static GstFlowReturn
2310 gst_base_parse_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2312 GstBaseParseClass *bclass;
2313 GstBaseParse *parse;
2314 GstFlowReturn ret = GST_FLOW_OK;
2315 GstBuffer *outbuf = NULL;
2316 GstBuffer *tmpbuf = NULL;
2320 guint old_min_size = 0, min_size, av;
2321 GstClockTime timestamp;
2322 GstBaseParseFrame *frame;
2324 parse = GST_BASE_PARSE (parent);
2325 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2327 if (parse->priv->detecting) {
2328 GstBuffer *detect_buf;
2330 if (parse->priv->detect_buffers_size == 0) {
2331 detect_buf = gst_buffer_ref (buffer);
2336 detect_buf = gst_buffer_new ();
2338 for (l = parse->priv->detect_buffers; l; l = l->next) {
2339 gsize tmpsize = gst_buffer_get_size (l->data);
2341 gst_buffer_copy_into (detect_buf, GST_BUFFER_CAST (l->data),
2342 GST_BUFFER_COPY_MEMORY, offset, tmpsize);
2346 gst_buffer_copy_into (detect_buf, buffer, GST_BUFFER_COPY_MEMORY,
2347 offset, gst_buffer_get_size (buffer));
2350 ret = bclass->detect (parse, detect_buf);
2351 gst_buffer_unref (detect_buf);
2353 if (ret == GST_FLOW_OK) {
2356 /* Detected something */
2357 parse->priv->detecting = FALSE;
2359 for (l = parse->priv->detect_buffers; l; l = l->next) {
2360 if (ret == GST_FLOW_OK && !parse->priv->flushing)
2362 gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2363 parent, GST_BUFFER_CAST (l->data));
2365 gst_buffer_unref (GST_BUFFER_CAST (l->data));
2367 g_list_free (parse->priv->detect_buffers);
2368 parse->priv->detect_buffers = NULL;
2369 parse->priv->detect_buffers_size = 0;
2371 if (ret != GST_FLOW_OK) {
2375 /* Handle the current buffer */
2376 } else if (ret == GST_FLOW_NOT_NEGOTIATED) {
2377 /* Still detecting, append buffer or error out if draining */
2379 if (parse->priv->drain) {
2380 GST_DEBUG_OBJECT (parse, "Draining but did not detect format yet");
2381 return GST_FLOW_ERROR;
2382 } else if (parse->priv->flushing) {
2383 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref,
2385 g_list_free (parse->priv->detect_buffers);
2386 parse->priv->detect_buffers = NULL;
2387 parse->priv->detect_buffers_size = 0;
2389 parse->priv->detect_buffers =
2390 g_list_append (parse->priv->detect_buffers, buffer);
2391 parse->priv->detect_buffers_size += gst_buffer_get_size (buffer);
2395 /* Something went wrong, subclass responsible for error reporting */
2399 /* And now handle the current buffer if detection worked */
2402 frame = &parse->priv->frame;
2404 if (G_LIKELY (buffer)) {
2405 GST_LOG_OBJECT (parse,
2406 "buffer size: %" G_GSIZE_FORMAT ", offset = %" G_GINT64_FORMAT,
2407 gst_buffer_get_size (buffer), GST_BUFFER_OFFSET (buffer));
2408 if (G_UNLIKELY (parse->priv->passthrough)) {
2409 gst_base_parse_frame_init (frame);
2410 frame->buffer = gst_buffer_make_writable (buffer);
2411 return gst_base_parse_push_frame (parse, frame);
2413 /* upstream feeding us in reverse playback;
2414 * gather each fragment, then process it in single run */
2415 if (parse->segment.rate < 0.0) {
2416 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2417 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2418 ret = gst_base_parse_process_fragment (parse, FALSE);
2420 gst_adapter_push (parse->priv->adapter, buffer);
2423 gst_adapter_push (parse->priv->adapter, buffer);
2426 if (G_UNLIKELY (buffer &&
2427 GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2428 frame->_private_flags |= GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
2429 gst_base_parse_frame_free (frame);
2432 /* Parse and push as many frames as possible */
2433 /* Stop either when adapter is empty or we are flushing */
2434 while (!parse->priv->flushing) {
2437 /* maintain frame state for a single frame parsing round across _chain calls,
2438 * so only init when needed */
2439 if (!frame->_private_flags)
2440 gst_base_parse_frame_init (frame);
2442 tmpbuf = gst_buffer_new ();
2445 /* Synchronization loop */
2447 /* note: if subclass indicates MAX fsize,
2448 * this will not likely be available anyway ... */
2449 min_size = MAX (parse->priv->min_frame_size, fsize);
2450 av = gst_adapter_available (parse->priv->adapter);
2452 /* loop safety check */
2453 if (G_UNLIKELY (old_min_size >= min_size))
2455 old_min_size = min_size;
2457 if (G_UNLIKELY (parse->priv->drain)) {
2459 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2460 if (G_UNLIKELY (!min_size)) {
2461 gst_buffer_unref (tmpbuf);
2466 /* Collect at least min_frame_size bytes */
2467 if (av < min_size) {
2468 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
2470 gst_buffer_unref (tmpbuf);
2474 /* always pass all available data */
2475 data = gst_adapter_map (parse->priv->adapter, av);
2476 gst_buffer_take_memory (tmpbuf, -1,
2477 gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
2478 (gpointer) data, NULL, av, 0, av));
2479 GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
2481 if (parse->priv->discont) {
2482 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2483 GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2487 gst_base_parse_frame_update (parse, frame, tmpbuf);
2488 res = bclass->check_valid_frame (parse, frame, &fsize, &skip);
2489 gst_adapter_unmap (parse->priv->adapter);
2490 gst_buffer_replace (&frame->buffer, NULL);
2491 gst_buffer_remove_memory_range (tmpbuf, 0, -1);
2493 if (gst_adapter_available (parse->priv->adapter) < fsize) {
2494 GST_DEBUG_OBJECT (parse, "found valid frame but not enough data"
2495 " available (only %" G_GSIZE_FORMAT " bytes)",
2496 gst_adapter_available (parse->priv->adapter));
2497 gst_buffer_unref (tmpbuf);
2500 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2504 /* subclass didn't touch this value. By default we skip 1 byte */
2508 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2509 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2510 /* reverse playback, and no frames found yet, so we are skipping
2511 * the leading part of a fragment, which may form the tail of
2512 * fragment coming later, hopefully subclass skips efficiently ... */
2513 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2514 outbuf = gst_adapter_take_buffer (parse->priv->adapter, skip);
2515 outbuf = gst_buffer_make_writable (outbuf);
2516 GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
2517 parse->priv->buffers_pending =
2518 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2521 gst_adapter_flush (parse->priv->adapter, skip);
2523 parse->priv->offset += skip;
2524 if (!parse->priv->discont)
2525 parse->priv->sync_offset = parse->priv->offset;
2526 parse->priv->discont = TRUE;
2527 /* something changed least; nullify loop check */
2530 /* skip == 0 should imply subclass set min_size to need more data;
2531 * we check this shortly */
2532 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2533 gst_buffer_unref (tmpbuf);
2537 gst_buffer_unref (tmpbuf);
2541 /* Subclass found the sync, but still wants to skip some data */
2542 GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
2543 gst_adapter_flush (parse->priv->adapter, skip);
2544 parse->priv->offset += skip;
2547 /* Grab lock to prevent a race with FLUSH_START handler */
2548 GST_PAD_STREAM_LOCK (parse->srcpad);
2550 /* FLUSH_START event causes the "flushing" flag to be set. In this
2551 * case we can leave the frame pushing loop */
2552 if (parse->priv->flushing) {
2553 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2557 /* move along with upstream timestamp (if any),
2558 * but interpolate in between */
2559 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2560 if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2561 (parse->priv->prev_ts != timestamp)) {
2562 parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2565 /* FIXME: Would it be more efficient to make a subbuffer instead? */
2566 outbuf = gst_adapter_take_buffer (parse->priv->adapter, fsize);
2567 outbuf = gst_buffer_make_writable (outbuf);
2569 /* Subclass may want to know the data offset */
2570 GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2571 parse->priv->offset += fsize;
2572 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2573 GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
2575 frame->buffer = outbuf;
2576 ret = gst_base_parse_handle_and_push_frame (parse, bclass, frame);
2577 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2579 if (ret != GST_FLOW_OK) {
2580 GST_LOG_OBJECT (parse, "push returned %d", ret);
2586 GST_LOG_OBJECT (parse, "chain leaving");
2592 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2593 ("min_size evolution %d -> %d; breaking to avoid looping",
2594 old_min_size, min_size));
2595 return GST_FLOW_ERROR;
2599 /* pull @size bytes at current offset,
2600 * i.e. at least try to and possibly return a shorter buffer if near the end */
2601 static GstFlowReturn
2602 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2603 GstBuffer ** buffer)
2605 GstFlowReturn ret = GST_FLOW_OK;
2607 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2609 /* Caching here actually makes much less difference than one would expect.
2610 * We do it mainly to avoid pulling buffers of 1 byte all the time */
2611 if (parse->priv->cache) {
2612 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2613 gint cache_size = gst_buffer_get_size (parse->priv->cache);
2615 if (cache_offset <= parse->priv->offset &&
2616 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2617 *buffer = gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL,
2618 parse->priv->offset - cache_offset, size);
2619 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2622 /* not enough data in the cache, free cache and get a new one */
2623 gst_buffer_unref (parse->priv->cache);
2624 parse->priv->cache = NULL;
2627 /* refill the cache */
2629 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2630 64 * 1024), &parse->priv->cache);
2631 if (ret != GST_FLOW_OK) {
2632 parse->priv->cache = NULL;
2636 if (gst_buffer_get_size (parse->priv->cache) >= size) {
2638 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0,
2640 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2644 /* Not possible to get enough data, try a last time with
2645 * requesting exactly the size we need */
2646 gst_buffer_unref (parse->priv->cache);
2647 parse->priv->cache = NULL;
2649 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2650 &parse->priv->cache);
2652 if (ret != GST_FLOW_OK) {
2653 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2658 if (gst_buffer_get_size (parse->priv->cache) < size) {
2659 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2660 G_GUINT64_FORMAT ": wanted %u bytes, got %" G_GSIZE_FORMAT " bytes",
2661 parse->priv->offset, size, gst_buffer_get_size (parse->priv->cache));
2663 *buffer = parse->priv->cache;
2664 parse->priv->cache = NULL;
2670 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0, size);
2671 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2676 static GstFlowReturn
2677 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2680 GstClockTime ts = 0;
2684 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2685 ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2686 parse->priv->last_offset);
2688 if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2689 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2690 GST_TIME_ARGS (parse->segment.start));
2695 /* last fragment started at last_offset / last_ts;
2696 * seek back 10s capped at 1MB */
2697 if (parse->priv->last_ts >= 10 * GST_SECOND)
2698 ts = parse->priv->last_ts - 10 * GST_SECOND;
2699 /* if we are exact now, we will be more so going backwards */
2700 if (parse->priv->exact_position) {
2701 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2703 if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2704 GST_FORMAT_BYTES, &offset)) {
2705 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2708 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2709 parse->priv->last_offset - 1024);
2710 offset = MAX (0, offset);
2712 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2714 parse->priv->offset = offset;
2716 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2718 if (ret != GST_FLOW_OK)
2721 /* offset will increase again as fragment is processed/parsed */
2722 parse->priv->last_offset = offset;
2724 gst_adapter_push (parse->priv->adapter, buffer);
2725 ret = gst_base_parse_process_fragment (parse, FALSE);
2726 if (ret != GST_FLOW_OK)
2729 /* force previous fragment */
2730 parse->priv->offset = -1;
2737 * pull and scan for next frame starting from current offset
2738 * ajusts sync, drain and offset going along */
2739 static GstFlowReturn
2740 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2741 GstBaseParseFrame * frame, gboolean full)
2743 GstBuffer *buffer, *outbuf;
2744 GstFlowReturn ret = GST_FLOW_OK;
2745 guint fsize = 1, min_size, old_min_size = 0;
2748 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2750 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2751 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2753 /* let's make this efficient for all subclass once and for all;
2754 * maybe it does not need this much, but in the latter case, we know we are
2755 * in pull mode here and might as well try to read and supply more anyway
2756 * (so does the buffer caching mechanism) */
2762 min_size = MAX (parse->priv->min_frame_size, fsize);
2763 /* loop safety check */
2764 if (G_UNLIKELY (old_min_size >= min_size))
2766 old_min_size = min_size;
2768 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2769 if (ret != GST_FLOW_OK)
2772 if (parse->priv->discont) {
2773 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2774 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2777 /* if we got a short read, inform subclass we are draining leftover
2778 * and no more is to be expected */
2779 if (gst_buffer_get_size (buffer) < min_size)
2780 parse->priv->drain = TRUE;
2782 if (parse->priv->detecting) {
2783 ret = klass->detect (parse, buffer);
2784 if (ret == GST_FLOW_NOT_NEGOTIATED) {
2785 /* If draining we error out, otherwise request a buffer
2787 if (parse->priv->drain) {
2788 gst_buffer_unref (buffer);
2789 GST_ERROR_OBJECT (parse, "Failed to detect format but draining");
2790 return GST_FLOW_ERROR;
2793 gst_buffer_unref (buffer);
2796 } else if (ret != GST_FLOW_OK) {
2797 gst_buffer_unref (buffer);
2798 GST_ERROR_OBJECT (parse, "detect() returned %s",
2799 gst_flow_get_name (ret));
2803 /* Else handle this buffer normally */
2807 gst_base_parse_frame_update (parse, frame, buffer);
2808 res = klass->check_valid_frame (parse, frame, &fsize, &skip);
2809 gst_buffer_replace (&frame->buffer, NULL);
2811 parse->priv->drain = FALSE;
2812 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2815 parse->priv->drain = FALSE;
2819 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2820 if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2821 /* reverse playback, and no frames found yet, so we are skipping
2822 * the leading part of a fragment, which may form the tail of
2823 * fragment coming later, hopefully subclass skips efficiently ... */
2824 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, 0, skip);
2825 parse->priv->buffers_pending =
2826 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2829 parse->priv->offset += skip;
2830 if (!parse->priv->discont)
2831 parse->priv->sync_offset = parse->priv->offset;
2832 parse->priv->discont = TRUE;
2833 /* something changed at least; nullify loop check */
2834 if (fsize == G_MAXUINT)
2835 fsize = old_min_size + 64 * 1024;
2838 /* skip == 0 should imply subclass set min_size to need more data;
2839 * we check this shortly */
2840 GST_DEBUG_OBJECT (parse, "finding sync...");
2841 gst_buffer_unref (buffer);
2842 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2847 /* Does the subclass want to skip too? */
2849 parse->priv->offset += skip;
2853 if (fsize + skip <= gst_buffer_get_size (buffer)) {
2854 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, skip, fsize);
2855 GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2856 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2857 gst_buffer_unref (buffer);
2859 gst_buffer_unref (buffer);
2860 ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2861 if (ret != GST_FLOW_OK)
2863 if (gst_buffer_get_size (outbuf) < fsize) {
2864 gst_buffer_unref (outbuf);
2869 parse->priv->offset += fsize;
2871 frame->buffer = outbuf;
2879 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2880 ("min_size evolution %d -> %d; breaking to avoid looping",
2881 old_min_size, min_size));
2882 return GST_FLOW_ERROR;
2886 /* Loop that is used in pull mode to retrieve data from upstream */
2888 gst_base_parse_loop (GstPad * pad)
2890 GstBaseParse *parse;
2891 GstBaseParseClass *klass;
2892 GstFlowReturn ret = GST_FLOW_OK;
2893 GstBaseParseFrame frame;
2895 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2896 klass = GST_BASE_PARSE_GET_CLASS (parse);
2898 /* reverse playback:
2899 * first fragment (closest to stop time) is handled normally below,
2900 * then we pull in fragments going backwards */
2901 if (parse->segment.rate < 0.0) {
2902 /* check if we jumped back to a previous fragment,
2903 * which is a post-first fragment */
2904 if (parse->priv->offset < 0) {
2905 ret = gst_base_parse_handle_previous_fragment (parse);
2910 gst_base_parse_frame_init (&frame);
2911 ret = gst_base_parse_scan_frame (parse, klass, &frame, TRUE);
2912 if (ret != GST_FLOW_OK)
2915 /* This always cleans up frame, even if error occurs */
2916 ret = gst_base_parse_handle_and_push_frame (parse, klass, &frame);
2918 /* eat expected eos signalling past segment in reverse playback */
2919 if (parse->segment.rate < 0.0 && ret == GST_FLOW_EOS &&
2920 parse->segment.position >= parse->segment.stop) {
2921 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2922 /* push what was accumulated during loop run */
2923 gst_base_parse_process_fragment (parse, TRUE);
2924 /* force previous fragment */
2925 parse->priv->offset = -1;
2930 if (ret == GST_FLOW_EOS)
2932 else if (ret != GST_FLOW_OK)
2935 gst_object_unref (parse);
2942 GST_DEBUG_OBJECT (parse, "eos");
2947 gboolean push_eos = FALSE;
2949 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2950 gst_flow_get_name (ret));
2951 gst_pad_pause_task (parse->sinkpad);
2953 if (ret == GST_FLOW_EOS) {
2954 /* handle end-of-stream/segment */
2955 if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2958 if ((stop = parse->segment.stop) == -1)
2959 stop = parse->segment.duration;
2961 GST_DEBUG_OBJECT (parse, "sending segment_done");
2963 gst_element_post_message
2964 (GST_ELEMENT_CAST (parse),
2965 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2966 GST_FORMAT_TIME, stop));
2968 /* If we STILL have zero frames processed, fire an error */
2969 if (parse->priv->framecount == 0) {
2970 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2971 ("No valid frames found before end of stream"), (NULL));
2975 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
2976 /* for fatal errors we post an error message, wrong-state is
2977 * not fatal because it happens due to flushes and only means
2978 * that we should stop now. */
2979 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2980 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2984 /* newsegment before eos */
2985 if (parse->priv->pending_segment) {
2986 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
2987 parse->priv->pending_segment = NULL;
2989 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2991 gst_object_unref (parse);
2996 gst_base_parse_sink_activate (GstPad * sinkpad, GstObject * parent)
2998 GstBaseParse *parse;
2999 gboolean result = TRUE;
3003 parse = GST_BASE_PARSE (parent);
3005 GST_DEBUG_OBJECT (parse, "sink activate");
3007 query = gst_query_new_scheduling ();
3008 result = gst_pad_peer_query (sinkpad, query);
3010 pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL);
3014 gst_query_unref (query);
3017 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
3018 result = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
3020 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
3021 result = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
3024 GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
3029 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
3031 GstBaseParseClass *klass;
3032 gboolean result = TRUE;
3034 GST_DEBUG_OBJECT (parse, "activate %d", active);
3036 klass = GST_BASE_PARSE_GET_CLASS (parse);
3039 if (parse->priv->pad_mode == GST_PAD_MODE_NONE && klass->start)
3040 result = klass->start (parse);
3042 /* If the subclass implements ::detect we want to
3043 * call it for the first buffers now */
3044 parse->priv->detecting = (klass->detect != NULL);
3046 /* We must make sure streaming has finished before resetting things
3047 * and calling the ::stop vfunc */
3048 GST_PAD_STREAM_LOCK (parse->sinkpad);
3049 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3051 if (parse->priv->pad_mode != GST_PAD_MODE_NONE && klass->stop)
3052 result = klass->stop (parse);
3054 parse->priv->pad_mode = GST_PAD_MODE_NONE;
3056 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
3061 gst_base_parse_sink_activate_mode (GstPad * pad, GstObject * parent,
3062 GstPadMode mode, gboolean active)
3064 gboolean result = TRUE;
3065 GstBaseParse *parse;
3067 parse = GST_BASE_PARSE (parent);
3069 GST_DEBUG_OBJECT (parse, "sink activate mode %d, %d", mode, active);
3071 result = gst_base_parse_activate (parse, active);
3075 case GST_PAD_MODE_PULL:
3077 parse->priv->pending_segment =
3078 gst_event_new_segment (&parse->segment);
3080 gst_pad_start_task (pad, (GstTaskFunction) gst_base_parse_loop,
3083 result &= gst_pad_stop_task (pad);
3091 parse->priv->pad_mode = active ? mode : GST_PAD_MODE_NONE;
3093 GST_DEBUG_OBJECT (parse, "sink activate return: %d", result);
3099 * gst_base_parse_set_duration:
3100 * @parse: #GstBaseParse.
3102 * @duration: duration value.
3103 * @interval: how often to update the duration estimate based on bitrate, or 0.
3105 * Sets the duration of the currently playing media. Subclass can use this
3106 * when it is able to determine duration and/or notices a change in the media
3107 * duration. Alternatively, if @interval is non-zero (default), then stream
3108 * duration is determined based on estimated bitrate, and updated every @interval
3114 gst_base_parse_set_duration (GstBaseParse * parse,
3115 GstFormat fmt, gint64 duration, gint interval)
3117 g_return_if_fail (parse != NULL);
3119 if (parse->priv->upstream_has_duration) {
3120 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
3124 if (duration != parse->priv->duration) {
3127 m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
3128 gst_element_post_message (GST_ELEMENT (parse), m);
3130 /* TODO: what about duration tag? */
3132 parse->priv->duration = duration;
3133 parse->priv->duration_fmt = fmt;
3134 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
3135 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
3136 if (interval != 0) {
3137 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
3141 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
3142 parse->priv->update_interval = interval;
3148 * gst_base_parse_set_average_bitrate:
3149 * @parse: #GstBaseParse.
3150 * @bitrate: average bitrate in bits/second
3152 * Optionally sets the average bitrate detected in media (if non-zero),
3153 * e.g. based on metadata, as it will be posted to the application.
3155 * By default, announced average bitrate is estimated. The average bitrate
3156 * is used to estimate the total duration of the stream and to estimate
3157 * a seek position, if there's no index and the format is syncable
3158 * (see gst_base_parse_set_syncable()).
3163 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
3165 parse->priv->bitrate = bitrate;
3166 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
3170 * gst_base_parse_set_min_frame_size:
3171 * @parse: #GstBaseParse.
3172 * @min_size: Minimum size of the data that this base class should give to
3175 * Subclass can use this function to tell the base class that it needs to
3176 * give at least #min_size buffers.
3181 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
3183 g_return_if_fail (parse != NULL);
3185 parse->priv->min_frame_size = min_size;
3186 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
3190 * gst_base_parse_set_frame_rate:
3191 * @parse: the #GstBaseParse to set
3192 * @fps_num: frames per second (numerator).
3193 * @fps_den: frames per second (denominator).
3194 * @lead_in: frames needed before a segment for subsequent decode
3195 * @lead_out: frames needed after a segment
3197 * If frames per second is configured, parser can take care of buffer duration
3198 * and timestamping. When performing segment clipping, or seeking to a specific
3199 * location, a corresponding decoder might need an initial @lead_in and a
3200 * following @lead_out number of frames to ensure the desired segment is
3201 * entirely filled upon decoding.
3206 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
3207 guint fps_den, guint lead_in, guint lead_out)
3209 g_return_if_fail (parse != NULL);
3211 parse->priv->fps_num = fps_num;
3212 parse->priv->fps_den = fps_den;
3213 if (!fps_num || !fps_den) {
3214 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
3216 fps_num = fps_den = 0;
3217 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
3218 parse->priv->lead_in = parse->priv->lead_out = 0;
3219 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
3221 parse->priv->frame_duration =
3222 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
3223 parse->priv->lead_in = lead_in;
3224 parse->priv->lead_out = lead_out;
3225 parse->priv->lead_in_ts =
3226 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
3227 parse->priv->lead_out_ts =
3228 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
3229 /* aim for about 1.5s to estimate duration */
3230 if (parse->priv->update_interval < 0) {
3231 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
3232 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
3233 parse->priv->update_interval);
3236 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
3237 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
3238 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
3239 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
3240 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
3241 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
3245 * gst_base_parse_set_has_timing_info:
3246 * @parse: a #GstBaseParse
3247 * @has_timing: whether frames carry timing information
3249 * Set if frames carry timing information which the subclass can (generally)
3250 * parse and provide. In particular, intrinsic (rather than estimated) time
3251 * can be obtained following a seek.
3256 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3258 parse->priv->has_timing_info = has_timing;
3259 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3263 * gst_base_parse_set_syncable:
3264 * @parse: a #GstBaseParse
3265 * @syncable: set if frame starts can be identified
3267 * Set if frame starts can be identified. This is set by default and
3268 * determines whether seeking based on bitrate averages
3269 * is possible for a format/stream.
3274 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3276 parse->priv->syncable = syncable;
3277 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3281 * gst_base_parse_set_passthrough:
3282 * @parse: a #GstBaseParse
3283 * @passthrough: %TRUE if parser should run in passthrough mode
3285 * Set if the nature of the format or configuration does not allow (much)
3286 * parsing, and the parser should operate in passthrough mode (which only
3287 * applies when operating in push mode). That is, incoming buffers are
3288 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3289 * callbacks will be invoked, but @pre_push_frame will still be invoked,
3290 * so subclass can perform as much or as little is appropriate for
3291 * passthrough semantics in @pre_push_frame.
3296 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3298 parse->priv->passthrough = passthrough;
3299 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3303 * gst_base_parse_set_latency:
3304 * @parse: a #GstBaseParse
3305 * @min_latency: minimum parse latency
3306 * @max_latency: maximum parse latency
3308 * Sets the minimum and maximum (which may likely be equal) latency introduced
3309 * by the parsing process. If there is such a latency, which depends on the
3310 * particular parsing of the format, it typically corresponds to 1 frame duration.
3315 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3316 GstClockTime max_latency)
3318 GST_OBJECT_LOCK (parse);
3319 parse->priv->min_latency = min_latency;
3320 parse->priv->max_latency = max_latency;
3321 GST_OBJECT_UNLOCK (parse);
3322 GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3323 GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3324 GST_TIME_ARGS (max_latency));
3328 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3329 GstClockTime * duration)
3331 gboolean res = FALSE;
3333 g_return_val_if_fail (duration != NULL, FALSE);
3335 *duration = GST_CLOCK_TIME_NONE;
3336 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3337 GST_LOG_OBJECT (parse, "using provided duration");
3338 *duration = parse->priv->duration;
3340 } else if (parse->priv->duration != -1) {
3341 GST_LOG_OBJECT (parse, "converting provided duration");
3342 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3343 parse->priv->duration, format, (gint64 *) duration);
3344 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3345 GST_LOG_OBJECT (parse, "using estimated duration");
3346 *duration = parse->priv->estimated_duration;
3350 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3351 GST_TIME_ARGS (*duration));
3356 gst_base_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
3358 GstBaseParse *parse;
3359 gboolean res = FALSE;
3361 parse = GST_BASE_PARSE (parent);
3363 GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3365 switch (GST_QUERY_TYPE (query)) {
3366 case GST_QUERY_POSITION:
3371 GST_DEBUG_OBJECT (parse, "position query");
3372 gst_query_parse_position (query, &format, NULL);
3374 /* try upstream first */
3375 res = gst_pad_query_default (pad, parent, query);
3377 /* Fall back on interpreting segment */
3378 GST_OBJECT_LOCK (parse);
3379 if (format == GST_FORMAT_BYTES) {
3380 dest_value = parse->priv->offset;
3382 } else if (format == parse->segment.format &&
3383 GST_CLOCK_TIME_IS_VALID (parse->segment.position)) {
3384 dest_value = gst_segment_to_stream_time (&parse->segment,
3385 parse->segment.format, parse->segment.position);
3388 GST_OBJECT_UNLOCK (parse);
3390 /* no precise result, upstream no idea either, then best estimate */
3391 /* priv->offset is updated in both PUSH/PULL modes */
3392 res = gst_base_parse_convert (parse,
3393 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3396 gst_query_set_position (query, format, dest_value);
3400 case GST_QUERY_DURATION:
3403 GstClockTime duration;
3405 GST_DEBUG_OBJECT (parse, "duration query");
3406 gst_query_parse_duration (query, &format, NULL);
3408 /* consult upstream */
3409 res = gst_pad_query_default (pad, parent, query);
3411 /* otherwise best estimate from us */
3413 res = gst_base_parse_get_duration (parse, format, &duration);
3415 gst_query_set_duration (query, format, duration);
3419 case GST_QUERY_SEEKING:
3422 GstClockTime duration = GST_CLOCK_TIME_NONE;
3423 gboolean seekable = FALSE;
3425 GST_DEBUG_OBJECT (parse, "seeking query");
3426 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3428 /* consult upstream */
3429 res = gst_pad_query_default (pad, parent, query);
3431 /* we may be able to help if in TIME */
3432 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3433 gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3434 /* already OK if upstream takes care */
3435 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3437 if (!(res && seekable)) {
3438 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3439 || duration == -1) {
3440 /* seekable if we still have a chance to get duration later on */
3442 parse->priv->upstream_seekable && parse->priv->update_interval;
3444 seekable = parse->priv->upstream_seekable;
3445 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3448 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3454 case GST_QUERY_FORMATS:
3455 gst_query_set_formatsv (query, 3, fmtlist);
3458 case GST_QUERY_CONVERT:
3460 GstFormat src_format, dest_format;
3461 gint64 src_value, dest_value;
3463 gst_query_parse_convert (query, &src_format, &src_value,
3464 &dest_format, &dest_value);
3466 res = gst_base_parse_convert (parse, src_format, src_value,
3467 dest_format, &dest_value);
3469 gst_query_set_convert (query, src_format, src_value,
3470 dest_format, dest_value);
3474 case GST_QUERY_LATENCY:
3476 if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3478 GstClockTime min_latency, max_latency;
3480 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3481 GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3482 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3483 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3485 GST_OBJECT_LOCK (parse);
3486 /* add our latency */
3487 if (min_latency != -1)
3488 min_latency += parse->priv->min_latency;
3489 if (max_latency != -1)
3490 max_latency += parse->priv->max_latency;
3491 GST_OBJECT_UNLOCK (parse);
3493 gst_query_set_latency (query, live, min_latency, max_latency);
3498 res = gst_pad_query_default (pad, parent, query);
3504 /* scans for a cluster start from @pos,
3505 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3506 static GstFlowReturn
3507 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3508 GstClockTime * time, GstClockTime * duration)
3510 GstBaseParseClass *klass;
3512 gboolean orig_drain, orig_discont;
3513 GstFlowReturn ret = GST_FLOW_OK;
3514 GstBuffer *buf = NULL;
3515 GstBaseParseFrame frame;
3517 g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3518 g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3519 g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3521 klass = GST_BASE_PARSE_GET_CLASS (parse);
3523 *time = GST_CLOCK_TIME_NONE;
3524 *duration = GST_CLOCK_TIME_NONE;
3527 orig_offset = parse->priv->offset;
3528 orig_discont = parse->priv->discont;
3529 orig_drain = parse->priv->drain;
3531 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3532 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3534 gst_base_parse_frame_init (&frame);
3536 /* jump elsewhere and locate next frame */
3537 parse->priv->offset = *pos;
3538 ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3539 if (ret != GST_FLOW_OK)
3543 GST_LOG_OBJECT (parse,
3544 "peek parsing frame at offset %" G_GUINT64_FORMAT
3545 " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
3546 GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf),
3547 gst_buffer_get_size (buf));
3549 /* get offset first, subclass parsing might dump other stuff in there */
3550 *pos = GST_BUFFER_OFFSET (buf);
3551 ret = klass->parse_frame (parse, &frame);
3554 /* but it should provide proper time */
3555 *time = GST_BUFFER_TIMESTAMP (buf);
3556 *duration = GST_BUFFER_DURATION (buf);
3558 gst_base_parse_frame_free (&frame);
3560 GST_LOG_OBJECT (parse,
3561 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3562 GST_TIME_ARGS (*time), *pos);
3566 parse->priv->offset = orig_offset;
3567 parse->priv->discont = orig_discont;
3568 parse->priv->drain = orig_drain;
3573 /* bisect and scan through file for frame starting before @time,
3574 * returns OK and @time/@offset if found, NONE and/or error otherwise
3575 * If @time == G_MAXINT64, scan for duration ( == last frame) */
3576 static GstFlowReturn
3577 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3580 GstFlowReturn ret = GST_FLOW_OK;
3581 gint64 lpos, hpos, newpos;
3582 GstClockTime time, ltime, htime, newtime, dur;
3583 gboolean cont = TRUE;
3584 const GstClockTime tolerance = TARGET_DIFFERENCE;
3585 const guint chunk = 4 * 1024;
3587 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3588 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3590 GST_DEBUG_OBJECT (parse, "Bisecting for time %" GST_TIME_FORMAT,
3591 GST_TIME_ARGS (*_time));
3593 /* TODO also make keyframe aware if useful some day */
3608 /* do not know at first */
3610 *_time = GST_CLOCK_TIME_NONE;
3612 /* need initial positions; start and end */
3613 lpos = parse->priv->first_frame_offset;
3614 ltime = parse->priv->first_frame_ts;
3615 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &htime)) {
3616 GST_DEBUG_OBJECT (parse, "Unknown time duration, cannot bisect");
3617 return GST_FLOW_ERROR;
3619 hpos = parse->priv->upstream_size;
3621 GST_DEBUG_OBJECT (parse,
3622 "Bisection initial bounds: bytes %" G_GINT64_FORMAT " %" G_GINT64_FORMAT
3623 ", times %" GST_TIME_FORMAT " %" GST_TIME_FORMAT, lpos, htime,
3624 GST_TIME_ARGS (ltime), GST_TIME_ARGS (htime));
3626 /* check preconditions are satisfied;
3627 * start and end are needed, except for special case where we scan for
3628 * last frame to determine duration */
3629 if (parse->priv->pad_mode != GST_PAD_MODE_PULL || !hpos ||
3630 !GST_CLOCK_TIME_IS_VALID (ltime) ||
3631 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3635 /* shortcut cases */
3638 } else if (time < ltime + tolerance) {
3642 } else if (time >= htime) {
3648 while (htime > ltime && cont) {
3649 GST_LOG_OBJECT (parse,
3650 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3651 GST_TIME_ARGS (ltime));
3652 GST_LOG_OBJECT (parse,
3653 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3654 GST_TIME_ARGS (htime));
3655 if (G_UNLIKELY (time == G_MAXINT64)) {
3657 } else if (G_LIKELY (hpos > lpos)) {
3659 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3662 /* should mean lpos == hpos, since lpos <= hpos is invariant */
3664 /* we check this case once, but not forever, so break loop */
3669 newpos = CLAMP (newpos, lpos, hpos);
3670 GST_LOG_OBJECT (parse,
3671 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3672 GST_TIME_ARGS (time), newpos);
3674 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3675 if (ret == GST_FLOW_EOS) {
3676 /* heuristic HACK */
3677 hpos = MAX (lpos, hpos - chunk);
3679 } else if (ret != GST_FLOW_OK) {
3683 if (newtime == -1 || newpos == -1) {
3684 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3688 if (G_UNLIKELY (time == G_MAXINT64)) {
3691 if (GST_CLOCK_TIME_IS_VALID (dur))
3694 } else if (newtime > time) {
3696 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3698 } else if (newtime + tolerance > time) {
3699 /* close enough undershoot */
3703 } else if (newtime < ltime) {
3704 /* so a position beyond lpos resulted in earlier time than ltime ... */
3705 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3708 /* undershoot too far */
3709 newpos += newpos == lpos ? chunk : 0;
3710 lpos = CLAMP (newpos, lpos, hpos);
3716 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3717 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3722 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3723 gboolean before, GstClockTime * _ts)
3725 gint64 bytes = 0, ts = 0;
3726 GstIndexEntry *entry = NULL;
3728 if (time == GST_CLOCK_TIME_NONE) {
3734 GST_BASE_PARSE_INDEX_LOCK (parse);
3735 if (parse->priv->index) {
3736 /* Let's check if we have an index entry for that time */
3737 entry = gst_index_get_assoc_entry (parse->priv->index,
3738 parse->priv->index_id,
3739 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3740 GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3744 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3745 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3747 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3748 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3749 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3751 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3752 GST_TIME_ARGS (time));
3755 ts = GST_CLOCK_TIME_NONE;
3758 GST_BASE_PARSE_INDEX_UNLOCK (parse);
3767 /* returns TRUE if seek succeeded */
3769 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3774 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3775 gboolean flush, update, res = TRUE, accurate;
3776 gint64 cur, stop, seekpos, seekstop;
3777 GstSegment seeksegment = { 0, };
3778 GstClockTime start_ts;
3780 gst_event_parse_seek (event, &rate, &format, &flags,
3781 &cur_type, &cur, &stop_type, &stop);
3783 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3784 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3785 GST_TIME_FORMAT, gst_format_get_name (format), rate,
3786 cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3788 /* no negative rates in push mode */
3789 if (rate < 0.0 && parse->priv->pad_mode == GST_PAD_MODE_PUSH)
3792 if (cur_type != GST_SEEK_TYPE_SET ||
3793 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3796 /* For any format other than TIME, see if upstream handles
3797 * it directly or fail. For TIME, try upstream, but do it ourselves if
3798 * it fails upstream */
3799 if (format != GST_FORMAT_TIME) {
3800 /* default action delegates to upstream */
3804 gst_event_ref (event);
3805 if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3810 /* get flush flag */
3811 flush = flags & GST_SEEK_FLAG_FLUSH;
3813 /* copy segment, we need this because we still need the old
3814 * segment when we close the current segment. */
3815 gst_segment_copy_into (&parse->segment, &seeksegment);
3817 GST_DEBUG_OBJECT (parse, "configuring seek");
3818 gst_segment_do_seek (&seeksegment, rate, format, flags,
3819 cur_type, cur, stop_type, stop, &update);
3821 /* accurate seeking implies seek tables are used to obtain position,
3822 * and the requested segment is maintained exactly, not adjusted any way */
3823 accurate = flags & GST_SEEK_FLAG_ACCURATE;
3825 /* maybe we can be accurate for (almost) free */
3826 gst_base_parse_find_offset (parse, seeksegment.position, TRUE, &start_ts);
3827 if (seeksegment.position <= start_ts + TARGET_DIFFERENCE) {
3828 GST_DEBUG_OBJECT (parse, "accurate seek possible");
3832 GstClockTime startpos = seeksegment.position;
3834 /* accurate requested, so ... seek a bit before target */
3835 if (startpos < parse->priv->lead_in_ts)
3838 startpos -= parse->priv->lead_in_ts;
3839 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3840 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3843 start_ts = seeksegment.position;
3844 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.position,
3845 GST_FORMAT_BYTES, &seekpos))
3846 goto convert_failed;
3847 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3848 GST_FORMAT_BYTES, &seekstop))
3849 goto convert_failed;
3852 GST_DEBUG_OBJECT (parse,
3853 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3855 GST_DEBUG_OBJECT (parse,
3856 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3857 seeksegment.stop, seekstop);
3859 if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
3862 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3865 if (parse->srcpad) {
3866 GST_DEBUG_OBJECT (parse, "sending flush start");
3867 gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3868 /* unlock upstream pull_range */
3869 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3872 gst_pad_pause_task (parse->sinkpad);
3875 /* we should now be able to grab the streaming thread because we stopped it
3876 * with the above flush/pause code */
3877 GST_PAD_STREAM_LOCK (parse->sinkpad);
3879 /* save current position */
3880 last_stop = parse->segment.position;
3881 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3884 /* now commit to new position */
3886 /* prepare for streaming again */
3888 GST_DEBUG_OBJECT (parse, "sending flush stop");
3889 gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop (TRUE));
3890 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop (TRUE));
3891 gst_base_parse_clear_queues (parse);
3893 /* keep track of our position */
3894 seeksegment.base = gst_segment_to_running_time (&seeksegment,
3895 seeksegment.format, parse->segment.position);
3898 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3900 /* store the newsegment event so it can be sent from the streaming thread. */
3901 if (parse->priv->pending_segment)
3902 gst_event_unref (parse->priv->pending_segment);
3904 /* This will be sent later in _loop() */
3905 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
3907 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3908 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3909 ", pos = %" GST_TIME_FORMAT, format,
3910 GST_TIME_ARGS (parse->segment.start),
3911 GST_TIME_ARGS (parse->segment.stop),
3912 GST_TIME_ARGS (parse->segment.start));
3914 /* one last chance in pull mode to stay accurate;
3915 * maybe scan and subclass can find where to go */
3918 GstClockTime ts = seeksegment.position;
3920 gst_base_parse_locate_time (parse, &ts, &scanpos);
3924 /* running collected index now consists of several intervals,
3925 * so optimized check no longer possible */
3926 parse->priv->index_last_valid = FALSE;
3927 parse->priv->index_last_offset = 0;
3928 parse->priv->index_last_ts = 0;
3932 /* mark discont if we are going to stream from another position. */
3933 if (seekpos != parse->priv->offset) {
3934 GST_DEBUG_OBJECT (parse,
3935 "mark DISCONT, we did a seek to another position");
3936 parse->priv->offset = seekpos;
3937 parse->priv->last_offset = seekpos;
3938 parse->priv->seen_keyframe = FALSE;
3939 parse->priv->discont = TRUE;
3940 parse->priv->next_ts = start_ts;
3941 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3942 parse->priv->sync_offset = seekpos;
3943 parse->priv->exact_position = accurate;
3946 /* Start streaming thread if paused */
3947 gst_pad_start_task (parse->sinkpad,
3948 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3950 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3955 GstEvent *new_event;
3956 GstBaseParseSeek *seek;
3957 GstSeekFlags flags = (flush ? GST_SEEK_FLAG_FLUSH : GST_SEEK_FLAG_NONE);
3959 /* The only thing we need to do in PUSH-mode is to send the
3960 seek event (in bytes) to upstream. Segment / flush handling happens
3961 in corresponding src event handlers */
3962 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3963 if (seekstop >= 0 && seekstop <= seekpos)
3965 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
3966 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3968 /* store segment info so its precise details can be reconstructed when
3969 * receiving newsegment;
3970 * this matters for all details when accurate seeking,
3971 * is most useful to preserve NONE stop time otherwise */
3972 seek = g_new0 (GstBaseParseSeek, 1);
3973 seek->segment = seeksegment;
3974 seek->accurate = accurate;
3975 seek->offset = seekpos;
3976 seek->start_ts = start_ts;
3977 GST_OBJECT_LOCK (parse);
3978 /* less optimal, but preserves order */
3979 parse->priv->pending_seeks =
3980 g_slist_append (parse->priv->pending_seeks, seek);
3981 GST_OBJECT_UNLOCK (parse);
3983 res = gst_pad_push_event (parse->sinkpad, new_event);
3986 GST_OBJECT_LOCK (parse);
3987 parse->priv->pending_seeks =
3988 g_slist_remove (parse->priv->pending_seeks, seek);
3989 GST_OBJECT_UNLOCK (parse);
3995 /* handled event is ours to free */
3997 gst_event_unref (event);
4003 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
4009 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
4015 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
4021 /* Checks if bitrates are available from upstream tags so that we don't
4022 * override them later
4025 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
4027 GstTagList *taglist = NULL;
4030 gst_event_parse_tag (event, &taglist);
4032 if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
4033 GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
4034 parse->priv->post_min_bitrate = FALSE;
4036 if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
4037 GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
4038 parse->priv->post_avg_bitrate = FALSE;
4040 if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
4041 GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
4042 parse->priv->post_max_bitrate = FALSE;
4048 gst_base_parse_set_index (GstElement * element, GstIndex * index)
4050 GstBaseParse *parse = GST_BASE_PARSE (element);
4052 GST_BASE_PARSE_INDEX_LOCK (parse);
4053 if (parse->priv->index)
4054 gst_object_unref (parse->priv->index);
4056 parse->priv->index = gst_object_ref (index);
4057 gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
4058 &parse->priv->index_id);
4059 parse->priv->own_index = FALSE;
4061 parse->priv->index = NULL;
4063 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4067 gst_base_parse_get_index (GstElement * element)
4069 GstBaseParse *parse = GST_BASE_PARSE (element);
4070 GstIndex *result = NULL;
4072 GST_BASE_PARSE_INDEX_LOCK (parse);
4073 if (parse->priv->index)
4074 result = gst_object_ref (parse->priv->index);
4075 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4081 static GstStateChangeReturn
4082 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
4084 GstBaseParse *parse;
4085 GstStateChangeReturn result;
4087 parse = GST_BASE_PARSE (element);
4089 switch (transition) {
4090 case GST_STATE_CHANGE_READY_TO_PAUSED:
4091 /* If this is our own index destroy it as the
4092 * old entries might be wrong for the new stream */
4093 GST_BASE_PARSE_INDEX_LOCK (parse);
4094 if (parse->priv->own_index) {
4095 gst_object_unref (parse->priv->index);
4096 parse->priv->index = NULL;
4097 parse->priv->own_index = FALSE;
4100 /* If no index was created, generate one */
4101 if (G_UNLIKELY (!parse->priv->index)) {
4102 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
4104 parse->priv->index = g_object_new (gst_mem_index_get_type (), NULL);
4105 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
4106 &parse->priv->index_id);
4107 parse->priv->own_index = TRUE;
4109 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4115 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4117 switch (transition) {
4118 case GST_STATE_CHANGE_PAUSED_TO_READY:
4119 gst_base_parse_reset (parse);