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 if (parse->priv->adapter)
789 gst_adapter_clear (parse->priv->adapter);
791 /* we know it is not alloc'ed, but maybe other stuff to free, some day ... */
792 parse->priv->frame._private_flags |=
793 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
794 gst_base_parse_frame_free (&parse->priv->frame);
796 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
797 g_list_free (parse->priv->detect_buffers);
798 parse->priv->detect_buffers = NULL;
799 parse->priv->detect_buffers_size = 0;
800 GST_OBJECT_UNLOCK (parse);
803 /* gst_base_parse_check_frame:
804 * @parse: #GstBaseParse.
805 * @buffer: GstBuffer.
806 * @framesize: This will be set to tell the found frame size in bytes.
807 * @skipsize: Output parameter that tells how much data needs to be skipped
808 * in order to find the following frame header.
810 * Default callback for check_valid_frame.
812 * Returns: Always TRUE.
815 gst_base_parse_check_frame (GstBaseParse * parse,
816 GstBaseParseFrame * frame, guint * framesize, gint * skipsize)
818 *framesize = gst_buffer_get_size (frame->buffer);
824 /* gst_base_parse_parse_frame:
825 * @parse: #GstBaseParse.
826 * @buffer: #GstBuffer.
828 * Default callback for parse_frame.
831 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
833 GstBuffer *buffer = frame->buffer;
835 if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
836 GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
837 GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
839 if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
840 GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
841 GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
846 /* gst_base_parse_convert:
847 * @parse: #GstBaseParse.
848 * @src_format: #GstFormat describing the source format.
849 * @src_value: Source value to be converted.
850 * @dest_format: #GstFormat defining the converted format.
851 * @dest_value: Pointer where the conversion result will be put.
853 * Converts using configured "convert" vmethod in #GstBaseParse class.
855 * Returns: TRUE if conversion was successful.
858 gst_base_parse_convert (GstBaseParse * parse,
859 GstFormat src_format,
860 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
862 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
865 g_return_val_if_fail (dest_value != NULL, FALSE);
870 ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
872 #ifndef GST_DISABLE_GST_DEBUG
875 if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
876 GST_LOG_OBJECT (parse,
877 "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
878 GST_TIME_ARGS (src_value), *dest_value);
879 } else if (dest_format == GST_FORMAT_TIME &&
880 src_format == GST_FORMAT_BYTES) {
881 GST_LOG_OBJECT (parse,
882 "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
883 src_value, GST_TIME_ARGS (*dest_value));
885 GST_LOG_OBJECT (parse,
886 "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
887 GST_STR_NULL (gst_format_get_name (src_format)),
888 GST_STR_NULL (gst_format_get_name (dest_format)),
889 src_value, *dest_value);
892 GST_DEBUG_OBJECT (parse, "conversion failed");
900 /* gst_base_parse_sink_event:
901 * @pad: #GstPad that received the event.
902 * @event: #GstEvent to be handled.
904 * Handler for sink pad events.
906 * Returns: TRUE if the event was handled.
909 gst_base_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
912 GstBaseParseClass *bclass;
913 gboolean handled = FALSE;
916 parse = GST_BASE_PARSE (parent);
917 bclass = GST_BASE_PARSE_GET_CLASS (parse);
919 GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
920 GST_EVENT_TYPE_NAME (event));
922 /* Cache all events except EOS, SEGMENT and FLUSH_STOP if we have a
924 if (parse->priv->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
925 && GST_EVENT_TYPE (event) != GST_EVENT_SEGMENT
926 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
927 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP
928 && GST_EVENT_TYPE (event) != GST_EVENT_CAPS) {
930 if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
931 /* See if any bitrate tags were posted */
932 gst_base_parse_handle_tag (parse, event);
934 parse->priv->pending_events =
935 g_list_append (parse->priv->pending_events, event);
939 if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
940 parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
941 /* We've not posted bitrate tags yet - do so now */
942 gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
945 handled = bclass->event (parse, event);
948 handled = gst_base_parse_sink_eventfunc (parse, event);
951 ret = gst_pad_event_default (pad, parent, event);
954 GST_DEBUG_OBJECT (parse, "event handled");
960 /* gst_base_parse_sink_eventfunc:
961 * @parse: #GstBaseParse.
962 * @event: #GstEvent to be handled.
964 * Element-level event handler function.
966 * The event will be unreffed only if it has been handled and this
967 * function returns %TRUE
969 * Returns: %TRUE if the event was handled and not need forwarding.
972 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
974 gboolean handled = FALSE;
977 switch (GST_EVENT_TYPE (event)) {
981 GstBaseParseClass *klass;
983 klass = GST_BASE_PARSE_GET_CLASS (parse);
985 gst_event_parse_caps (event, &caps);
986 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
988 if (klass->set_sink_caps)
989 klass->set_sink_caps (parse, caps);
991 /* will send our own caps downstream */
992 gst_event_unref (event);
996 case GST_EVENT_SEGMENT:
998 const GstSegment *in_segment;
999 GstSegment out_segment;
1000 gint64 offset = 0, next_ts;
1003 gdouble rate, applied_rate;
1005 gint64 start, stop, pos, next_ts;
1009 gst_event_parse_segment (event, &in_segment);
1010 gst_segment_init (&out_segment, GST_FORMAT_TIME);
1012 GST_DEBUG_OBJECT (parse, "segment %" GST_SEGMENT_FORMAT, in_segment);
1014 if (in_segment->format == GST_FORMAT_BYTES) {
1015 GstBaseParseSeek *seek = NULL;
1018 /* stop time is allowed to be open-ended, but not start & pos */
1019 offset = in_segment->time;
1021 GST_OBJECT_LOCK (parse);
1022 for (node = parse->priv->pending_seeks; node; node = node->next) {
1023 GstBaseParseSeek *tmp = node->data;
1025 if (tmp->offset == offset) {
1030 parse->priv->pending_seeks =
1031 g_slist_remove (parse->priv->pending_seeks, seek);
1032 GST_OBJECT_UNLOCK (parse);
1035 GST_DEBUG_OBJECT (parse,
1036 "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
1037 seek->accurate ? " accurate" : "", &seek->segment);
1039 out_segment.start = seek->segment.start;
1040 out_segment.stop = seek->segment.stop;
1041 out_segment.time = seek->segment.start;
1043 next_ts = seek->start_ts;
1044 parse->priv->exact_position = seek->accurate;
1047 /* best attempt convert */
1048 /* as these are only estimates, stop is kept open-ended to avoid
1049 * premature cutting */
1050 gst_base_parse_convert (parse, GST_FORMAT_BYTES, in_segment->start,
1051 GST_FORMAT_TIME, (gint64 *) & next_ts);
1053 out_segment.start = next_ts;
1054 out_segment.stop = GST_CLOCK_TIME_NONE;
1055 out_segment.time = next_ts;
1057 parse->priv->exact_position = (in_segment->start == 0);
1060 gst_event_unref (event);
1062 event = gst_event_new_segment (&out_segment);
1064 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. %"
1065 GST_SEGMENT_FORMAT, in_segment);
1067 } else if (in_segment->format != GST_FORMAT_TIME) {
1068 /* Unknown incoming segment format. Output a default open-ended
1070 gst_event_unref (event);
1072 out_segment.start = 0;
1073 out_segment.stop = GST_CLOCK_TIME_NONE;;
1074 out_segment.time = 0;;
1076 event = gst_event_new_segment (&out_segment);
1080 /* not considered BYTE seekable if it is talking to us in TIME,
1081 * whatever else it might claim */
1082 parse->priv->upstream_seekable = FALSE;
1083 next_ts = in_segment->start;
1086 memcpy (&parse->segment, &out_segment, sizeof (GstSegment));
1089 gst_segment_set_newsegment (&parse->segment, update, rate,
1090 applied_rate, format, start, stop, start);
1093 /* save the segment for later, right before we push a new buffer so that
1094 * the caps are fixed and the next linked element can receive
1096 eventp = &parse->priv->pending_segment;
1097 gst_event_replace (eventp, event);
1098 gst_event_unref (event);
1101 /* but finish the current segment */
1102 GST_DEBUG_OBJECT (parse, "draining current segment");
1103 if (in_segment->rate > 0.0)
1104 gst_base_parse_drain (parse);
1106 gst_base_parse_process_fragment (parse, FALSE);
1107 gst_adapter_clear (parse->priv->adapter);
1109 parse->priv->offset = offset;
1110 parse->priv->sync_offset = offset;
1111 parse->priv->next_ts = next_ts;
1112 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1113 parse->priv->discont = TRUE;
1114 parse->priv->seen_keyframe = FALSE;
1118 case GST_EVENT_FLUSH_START:
1119 parse->priv->flushing = TRUE;
1120 handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
1122 gst_event_unref (event);
1123 /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
1124 GST_PAD_STREAM_LOCK (parse->srcpad);
1125 GST_PAD_STREAM_UNLOCK (parse->srcpad);
1129 case GST_EVENT_FLUSH_STOP:
1130 gst_adapter_clear (parse->priv->adapter);
1131 gst_base_parse_clear_queues (parse);
1132 parse->priv->flushing = FALSE;
1133 parse->priv->discont = TRUE;
1134 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1135 parse->priv->frame._private_flags |=
1136 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
1137 gst_base_parse_frame_free (&parse->priv->frame);
1141 if (parse->segment.rate > 0.0)
1142 gst_base_parse_drain (parse);
1144 gst_base_parse_process_fragment (parse, FALSE);
1146 /* If we STILL have zero frames processed, fire an error */
1147 if (parse->priv->framecount == 0) {
1148 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1149 ("No valid frames found before end of stream"), (NULL));
1151 /* newsegment before eos */
1152 if (parse->priv->pending_segment) {
1153 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1154 parse->priv->pending_segment = NULL;
1166 gst_base_parse_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
1168 GstBaseParse *parse;
1169 GstBaseParseClass *bclass;
1172 parse = GST_BASE_PARSE (parent);
1173 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1175 switch (GST_QUERY_TYPE (query)) {
1176 case GST_QUERY_CAPS:
1178 if (bclass->get_sink_caps) {
1179 GstCaps *caps, *filter;
1181 gst_query_parse_caps (query, &filter);
1182 caps = bclass->get_sink_caps (parse, filter);
1183 GST_LOG_OBJECT (parse, "sink getcaps returning caps %" GST_PTR_FORMAT,
1185 gst_query_set_caps_result (query, caps);
1186 gst_caps_unref (caps);
1190 GstCaps *caps, *template_caps, *filter;
1192 gst_query_parse_caps (query, &filter);
1193 template_caps = gst_pad_get_pad_template_caps (pad);
1194 if (filter != NULL) {
1196 gst_caps_intersect_full (filter, template_caps,
1197 GST_CAPS_INTERSECT_FIRST);
1199 caps = gst_caps_copy (template_caps);
1201 gst_query_set_caps_result (query, caps);
1202 gst_caps_unref (caps);
1210 res = gst_pad_query_default (pad, parent, query);
1219 /* gst_base_parse_src_event:
1220 * @pad: #GstPad that received the event.
1221 * @event: #GstEvent that was received.
1223 * Handler for source pad events.
1225 * Returns: TRUE if the event was handled.
1228 gst_base_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1230 GstBaseParse *parse;
1231 GstBaseParseClass *bclass;
1232 gboolean handled = FALSE;
1233 gboolean ret = TRUE;
1235 parse = GST_BASE_PARSE (parent);
1236 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1238 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1239 GST_EVENT_TYPE_NAME (event));
1241 if (bclass->src_event)
1242 handled = bclass->src_event (parse, event);
1245 ret = gst_pad_event_default (pad, parent, event);
1251 gst_base_parse_is_seekable (GstBaseParse * parse)
1253 /* FIXME: could do more here, e.g. check index or just send data from 0
1254 * in pull mode and let decoder/sink clip */
1255 return parse->priv->syncable;
1258 /* gst_base_parse_src_eventfunc:
1259 * @parse: #GstBaseParse.
1260 * @event: #GstEvent that was received.
1262 * Default srcpad event handler.
1264 * Returns: TRUE if the event was handled and can be dropped.
1267 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1269 gboolean handled = FALSE;
1271 switch (GST_EVENT_TYPE (event)) {
1272 case GST_EVENT_SEEK:
1274 if (gst_base_parse_is_seekable (parse)) {
1275 handled = gst_base_parse_handle_seek (parse, event);
1287 * gst_base_parse_convert_default:
1288 * @parse: #GstBaseParse.
1289 * @src_format: #GstFormat describing the source format.
1290 * @src_value: Source value to be converted.
1291 * @dest_format: #GstFormat defining the converted format.
1292 * @dest_value: Pointer where the conversion result will be put.
1294 * Default implementation of "convert" vmethod in #GstBaseParse class.
1296 * Returns: TRUE if conversion was successful.
1301 gst_base_parse_convert_default (GstBaseParse * parse,
1302 GstFormat src_format,
1303 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1305 gboolean ret = FALSE;
1306 guint64 bytes, duration;
1308 if (G_UNLIKELY (src_format == dest_format)) {
1309 *dest_value = src_value;
1313 if (G_UNLIKELY (src_value == -1)) {
1318 if (G_UNLIKELY (src_value == 0)) {
1323 /* need at least some frames */
1324 if (!parse->priv->framecount)
1327 duration = parse->priv->acc_duration / GST_MSECOND;
1328 bytes = parse->priv->bytecount;
1330 if (G_UNLIKELY (!duration || !bytes))
1333 if (src_format == GST_FORMAT_BYTES) {
1334 if (dest_format == GST_FORMAT_TIME) {
1335 /* BYTES -> TIME conversion */
1336 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1337 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1338 *dest_value *= GST_MSECOND;
1339 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1340 *dest_value / GST_MSECOND);
1343 } else if (src_format == GST_FORMAT_TIME) {
1344 if (dest_format == GST_FORMAT_BYTES) {
1345 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1346 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1348 GST_DEBUG_OBJECT (parse,
1349 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1350 src_value / GST_MSECOND, *dest_value);
1353 } else if (src_format == GST_FORMAT_DEFAULT) {
1354 /* DEFAULT == frame-based */
1355 if (dest_format == GST_FORMAT_TIME) {
1356 if (parse->priv->fps_den) {
1357 *dest_value = gst_util_uint64_scale (src_value,
1358 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1361 } else if (dest_format == GST_FORMAT_BYTES) {
1369 gst_base_parse_update_duration (GstBaseParse * baseparse)
1372 GstBaseParse *parse;
1374 parse = GST_BASE_PARSE (baseparse);
1376 peer = gst_pad_get_peer (parse->sinkpad);
1378 gboolean qres = FALSE;
1379 gint64 ptot, dest_value;
1381 qres = gst_pad_query_duration (peer, GST_FORMAT_BYTES, &ptot);
1382 gst_object_unref (GST_OBJECT (peer));
1384 if (gst_base_parse_convert (parse, GST_FORMAT_BYTES, ptot,
1385 GST_FORMAT_TIME, &dest_value)) {
1387 /* inform if duration changed, but try to avoid spamming */
1388 parse->priv->estimated_drift +=
1389 dest_value - parse->priv->estimated_duration;
1390 if (parse->priv->estimated_drift > GST_SECOND ||
1391 parse->priv->estimated_drift < -GST_SECOND) {
1392 gst_element_post_message (GST_ELEMENT (parse),
1393 gst_message_new_duration (GST_OBJECT (parse),
1394 GST_FORMAT_TIME, dest_value));
1395 parse->priv->estimated_drift = 0;
1397 parse->priv->estimated_duration = dest_value;
1398 GST_LOG_OBJECT (parse,
1399 "updated estimated duration to %" GST_TIME_FORMAT,
1400 GST_TIME_ARGS (dest_value));
1407 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1408 gboolean post_avg, gboolean post_max)
1410 GstTagList *taglist = NULL;
1412 if (post_min && parse->priv->post_min_bitrate) {
1413 taglist = gst_tag_list_new_empty ();
1415 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1416 GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1419 if (post_avg && parse->priv->post_avg_bitrate) {
1420 if (taglist == NULL)
1421 taglist = gst_tag_list_new_empty ();
1423 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1424 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1425 parse->priv->avg_bitrate, NULL);
1428 if (post_max && parse->priv->post_max_bitrate) {
1429 if (taglist == NULL)
1430 taglist = gst_tag_list_new_empty ();
1432 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1433 GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1436 GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1437 parse->priv->min_bitrate, parse->priv->avg_bitrate,
1438 parse->priv->max_bitrate);
1440 if (taglist != NULL) {
1441 gst_pad_push_event (parse->srcpad, gst_event_new_tag (taglist));
1445 /* gst_base_parse_update_bitrates:
1446 * @parse: #GstBaseParse.
1447 * @buffer: Current frame as a #GstBuffer
1449 * Keeps track of the minimum and maximum bitrates, and also maintains a
1450 * running average bitrate of the stream so far.
1453 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1455 /* Only update the tag on a 10 kbps delta */
1456 static const gint update_threshold = 10000;
1458 guint64 data_len, frame_dur;
1459 gint overhead, frame_bitrate, old_avg_bitrate;
1460 gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1461 GstBuffer *buffer = frame->buffer;
1463 overhead = frame->overhead;
1467 data_len = gst_buffer_get_size (buffer) - overhead;
1468 parse->priv->data_bytecount += data_len;
1470 /* duration should be valid by now,
1471 * either set by subclass or maybe based on fps settings */
1472 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1473 /* Calculate duration of a frame from buffer properties */
1474 frame_dur = GST_BUFFER_DURATION (buffer);
1475 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1476 parse->priv->acc_duration;
1479 /* No way to figure out frame duration (is this even possible?) */
1483 /* override if subclass provided bitrate, e.g. metadata based */
1484 if (parse->priv->bitrate) {
1485 parse->priv->avg_bitrate = parse->priv->bitrate;
1486 /* spread this (confirmed) info ASAP */
1487 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1488 gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1492 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1496 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1497 parse->priv->avg_bitrate);
1499 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1501 } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1502 /* always post all at threshold time */
1503 update_min = update_max = update_avg = TRUE;
1506 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1507 if (frame_bitrate < parse->priv->min_bitrate) {
1508 parse->priv->min_bitrate = frame_bitrate;
1512 if (frame_bitrate > parse->priv->max_bitrate) {
1513 parse->priv->max_bitrate = frame_bitrate;
1517 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1518 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1519 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1524 if ((update_min || update_avg || update_max))
1525 gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1527 /* If average bitrate changes that much and no valid (time) duration provided,
1528 * then post a new duration message so applications can update their cached
1530 if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1531 GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1532 gst_element_post_message (GST_ELEMENT (parse),
1533 gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1540 * gst_base_parse_add_index_entry:
1541 * @parse: #GstBaseParse.
1542 * @offset: offset of entry
1543 * @ts: timestamp associated with offset
1544 * @key: whether entry refers to keyframe
1545 * @force: add entry disregarding sanity checks
1547 * Adds an entry to the index associating @offset to @ts. It is recommended
1548 * to only add keyframe entries. @force allows to bypass checks, such as
1549 * whether the stream is (upstream) seekable, another entry is already "close"
1550 * to the new entry, etc.
1552 * Returns: #gboolean indicating whether entry was added
1557 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1558 GstClockTime ts, gboolean key, gboolean force)
1560 gboolean ret = FALSE;
1561 GstIndexAssociation associations[2];
1563 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1564 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1566 if (G_LIKELY (!force)) {
1568 if (!parse->priv->upstream_seekable) {
1569 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1573 /* FIXME need better helper data structure that handles these issues
1574 * related to ongoing collecting of index entries */
1575 if (parse->priv->index_last_offset >= (gint64) offset) {
1576 GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1577 "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1581 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1582 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1583 parse->priv->idx_interval) {
1584 GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1585 GST_TIME_ARGS (parse->priv->index_last_ts));
1589 /* if last is not really the last one */
1590 if (!parse->priv->index_last_valid) {
1591 GstClockTime prev_ts;
1593 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1594 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1595 GST_DEBUG_OBJECT (parse,
1596 "entry too close to existing entry %" GST_TIME_FORMAT,
1597 GST_TIME_ARGS (prev_ts));
1598 parse->priv->index_last_offset = offset;
1599 parse->priv->index_last_ts = ts;
1605 associations[0].format = GST_FORMAT_TIME;
1606 associations[0].value = ts;
1607 associations[1].format = GST_FORMAT_BYTES;
1608 associations[1].value = offset;
1610 /* index might change on-the-fly, although that would be nutty app ... */
1611 GST_BASE_PARSE_INDEX_LOCK (parse);
1612 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1613 (key) ? GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT :
1614 GST_INDEX_ASSOCIATION_FLAG_DELTA_UNIT, 2,
1615 (const GstIndexAssociation *) &associations);
1616 GST_BASE_PARSE_INDEX_UNLOCK (parse);
1619 parse->priv->index_last_offset = offset;
1620 parse->priv->index_last_ts = ts;
1629 /* check for seekable upstream, above and beyond a mere query */
1631 gst_base_parse_check_seekability (GstBaseParse * parse)
1634 gboolean seekable = FALSE;
1635 gint64 start = -1, stop = -1;
1636 guint idx_interval = 0;
1638 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1639 if (!gst_pad_peer_query (parse->sinkpad, query)) {
1640 GST_DEBUG_OBJECT (parse, "seeking query failed");
1644 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1646 /* try harder to query upstream size if we didn't get it the first time */
1647 if (seekable && stop == -1) {
1648 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1649 gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_BYTES, &stop);
1652 /* if upstream doesn't know the size, it's likely that it's not seekable in
1653 * practice even if it technically may be seekable */
1654 if (seekable && (start != 0 || stop <= start)) {
1655 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1659 /* let's not put every single frame into our index */
1661 if (stop < 10 * 1024 * 1024)
1663 else if (stop < 100 * 1024 * 1024)
1666 idx_interval = 1000;
1670 gst_query_unref (query);
1672 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1673 G_GUINT64_FORMAT ")", seekable, start, stop);
1674 parse->priv->upstream_seekable = seekable;
1675 parse->priv->upstream_size = seekable ? stop : 0;
1677 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1678 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1681 /* some misc checks on upstream */
1683 gst_base_parse_check_upstream (GstBaseParse * parse)
1687 if (gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_TIME, &stop))
1688 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1689 /* upstream has one, accept it also, and no further updates */
1690 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1691 parse->priv->upstream_has_duration = TRUE;
1694 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1695 parse->priv->upstream_has_duration);
1698 /* checks src caps to determine if dealing with audio or video */
1699 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1701 gst_base_parse_check_media (GstBaseParse * parse)
1706 caps = gst_pad_get_current_caps (parse->srcpad);
1707 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1708 parse->priv->is_video =
1709 g_str_has_prefix (gst_structure_get_name (s), "video");
1711 /* historical default */
1712 parse->priv->is_video = FALSE;
1715 gst_caps_unref (caps);
1717 GST_DEBUG_OBJECT (parse, "media is video: %d", parse->priv->is_video);
1720 /* takes ownership of frame */
1722 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1724 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1725 /* frame allocated on the heap, we can just take ownership */
1726 g_queue_push_tail (&parse->priv->queued_frames, frame);
1727 GST_TRACE ("queued frame %p", frame);
1729 GstBaseParseFrame *copy;
1731 /* probably allocated on the stack, must make a proper copy */
1732 copy = gst_base_parse_frame_copy (frame);
1733 g_queue_push_tail (&parse->priv->queued_frames, copy);
1734 GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1735 gst_base_parse_frame_free (frame);
1739 /* gst_base_parse_handle_and_push_buffer:
1740 * @parse: #GstBaseParse.
1741 * @klass: #GstBaseParseClass.
1742 * @frame: (transfer full): a #GstBaseParseFrame
1744 * Parses the frame from given buffer and pushes it forward. Also performs
1745 * timestamp handling and checks the segment limits.
1747 * This is called with srcpad STREAM_LOCK held.
1749 * Returns: #GstFlowReturn
1751 static GstFlowReturn
1752 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1753 GstBaseParseClass * klass, GstBaseParseFrame * frame)
1759 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1761 buffer = frame->buffer;
1763 if (parse->priv->discont) {
1764 GST_DEBUG_OBJECT (parse, "marking DISCONT");
1765 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1766 parse->priv->discont = FALSE;
1769 /* some one-time start-up */
1770 if (G_UNLIKELY (!parse->priv->framecount)) {
1771 gst_base_parse_check_seekability (parse);
1772 gst_base_parse_check_upstream (parse);
1775 GST_LOG_OBJECT (parse,
1776 "parsing frame at offset %" G_GUINT64_FORMAT
1777 " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
1778 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1779 gst_buffer_get_size (buffer));
1781 /* use default handler to provide initial (upstream) metadata */
1782 gst_base_parse_parse_frame (parse, frame);
1784 /* store offset as it might get overwritten */
1785 offset = GST_BUFFER_OFFSET (buffer);
1786 ret = klass->parse_frame (parse, frame);
1788 buffer = frame->buffer;
1789 /* subclass must play nice */
1790 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1792 /* check if subclass/format can provide ts.
1793 * If so, that allows and enables extra seek and duration determining options */
1794 if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
1795 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && parse->priv->has_timing_info
1796 && parse->priv->pad_mode == GST_PAD_MODE_PULL) {
1797 parse->priv->first_frame_offset = offset;
1798 parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1799 GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1800 " for first frame at offset %" G_GINT64_FORMAT,
1801 GST_TIME_ARGS (parse->priv->first_frame_ts),
1802 parse->priv->first_frame_offset);
1803 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1805 GstClockTime last_ts = G_MAXINT64;
1807 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1808 gst_base_parse_locate_time (parse, &last_ts, &off);
1809 if (GST_CLOCK_TIME_IS_VALID (last_ts))
1810 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1813 /* disable further checks */
1814 parse->priv->first_frame_offset = 0;
1818 /* again use default handler to add missing metadata;
1819 * we may have new information on frame properties */
1820 gst_base_parse_parse_frame (parse, frame);
1821 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1822 GST_BUFFER_DURATION_IS_VALID (buffer)) {
1823 parse->priv->next_ts =
1824 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1826 /* we lost track, do not produce bogus time next time around
1827 * (probably means parser subclass has given up on parsing as well) */
1828 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1829 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1832 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1833 GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1834 gst_base_parse_add_index_entry (parse, offset,
1835 GST_BUFFER_TIMESTAMP (buffer),
1836 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1838 /* First buffers are dropped, this means that the subclass needs more
1839 * frames to decide on the format and queues them internally */
1840 /* convert internal flow to OK and mark discont for the next buffer. */
1841 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1842 gst_base_parse_frame_free (frame);
1844 } else if (ret == GST_BASE_PARSE_FLOW_QUEUED) {
1845 gst_base_parse_queue_frame (parse, frame);
1847 } else if (ret != GST_FLOW_OK) {
1851 /* All OK, push queued frames if there are any */
1852 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
1853 GstBaseParseFrame *queued_frame;
1855 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
1856 gst_base_parse_push_frame (parse, queued_frame);
1860 return gst_base_parse_push_frame (parse, frame);
1864 * gst_base_parse_push_frame:
1865 * @parse: #GstBaseParse.
1866 * @frame: (transfer full): a #GstBaseParseFrame
1868 * Pushes the frame downstream, sends any pending events and
1869 * does some timestamp and segment handling. Takes ownership
1870 * of @frame and will clear it (if it was initialised with
1871 * gst_base_parse_frame_init()) or free it.
1873 * This must be called with sinkpad STREAM_LOCK held.
1875 * Returns: #GstFlowReturn
1880 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1882 GstFlowReturn ret = GST_FLOW_OK;
1883 GstClockTime last_start = GST_CLOCK_TIME_NONE;
1884 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1885 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1889 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1890 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
1892 GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
1894 buffer = frame->buffer;
1896 GST_LOG_OBJECT (parse,
1897 "processing buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1898 ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buffer),
1899 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1900 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1903 size = gst_buffer_get_size (buffer);
1904 parse->priv->bytecount += size;
1905 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1906 parse->priv->framecount++;
1907 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1908 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1911 /* 0 means disabled */
1912 if (parse->priv->update_interval < 0)
1913 parse->priv->update_interval = 50;
1914 else if (parse->priv->update_interval > 0 &&
1915 (parse->priv->framecount % parse->priv->update_interval) == 0)
1916 gst_base_parse_update_duration (parse);
1918 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1919 last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1920 if (last_start != GST_CLOCK_TIME_NONE
1921 && GST_BUFFER_DURATION_IS_VALID (buffer))
1922 last_stop = last_start + GST_BUFFER_DURATION (buffer);
1924 /* should have caps by now */
1925 if (!gst_pad_has_current_caps (parse->srcpad))
1928 /* segment adjustment magic; only if we are running the whole show */
1929 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1930 (parse->priv->pad_mode == GST_PAD_MODE_PULL ||
1931 parse->priv->upstream_seekable)) {
1932 /* segment times are typically estimates,
1933 * actual frame data might lead subclass to different timestamps,
1934 * so override segment start from what is supplied there */
1935 if (G_UNLIKELY (parse->priv->pending_segment && !parse->priv->exact_position
1936 && GST_CLOCK_TIME_IS_VALID (last_start))) {
1937 gst_event_unref (parse->priv->pending_segment);
1938 parse->segment.start =
1939 MIN ((guint64) last_start, (guint64) parse->segment.stop);
1941 GST_DEBUG_OBJECT (parse,
1942 "adjusting pending segment start to %" GST_TIME_FORMAT,
1943 GST_TIME_ARGS (parse->segment.start));
1945 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
1947 /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1948 if (GST_CLOCK_TIME_IS_VALID (parse->segment.position) &&
1949 GST_CLOCK_TIME_IS_VALID (last_start)) {
1950 GstClockTimeDiff diff;
1952 /* only send newsegments with increasing start times,
1953 * otherwise if these go back and forth downstream (sinks) increase
1954 * accumulated time and running_time */
1955 diff = GST_CLOCK_DIFF (parse->segment.position, last_start);
1956 if (G_UNLIKELY (diff > 2 * GST_SECOND
1957 && last_start > parse->segment.start
1958 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
1959 || last_start < parse->segment.stop))) {
1961 GST_DEBUG_OBJECT (parse,
1962 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
1963 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1964 "Sending updated NEWSEGMENT events", diff,
1965 GST_TIME_ARGS (parse->segment.position),
1966 GST_TIME_ARGS (last_start));
1968 if (G_UNLIKELY (parse->priv->pending_segment)) {
1969 gst_event_unref (parse->priv->pending_segment);
1970 parse->segment.start = last_start;
1971 parse->segment.time = last_start;
1972 parse->priv->pending_segment =
1973 gst_event_new_segment (&parse->segment);
1975 /* skip gap FIXME */
1976 gst_pad_push_event (parse->srcpad,
1977 gst_event_new_segment (&parse->segment));
1979 parse->segment.position = last_start;
1984 /* and should then also be linked downstream, so safe to send some events */
1985 if (G_UNLIKELY (parse->priv->close_segment)) {
1986 /* only set up by loop */
1987 GST_DEBUG_OBJECT (parse, "loop sending close segment");
1988 gst_pad_push_event (parse->srcpad, parse->priv->close_segment);
1989 parse->priv->close_segment = NULL;
1991 if (G_UNLIKELY (parse->priv->pending_segment)) {
1992 GstEvent *pending_segment;
1994 pending_segment = parse->priv->pending_segment;
1995 parse->priv->pending_segment = NULL;
1997 GST_DEBUG_OBJECT (parse, "%s push pending segment",
1998 parse->priv->pad_mode == GST_PAD_MODE_PULL ? "loop" : "chain");
1999 gst_pad_push_event (parse->srcpad, pending_segment);
2001 /* have caps; check identity */
2002 gst_base_parse_check_media (parse);
2005 /* update bitrates and optionally post corresponding tags
2006 * (following newsegment) */
2007 gst_base_parse_update_bitrates (parse, frame);
2009 if (G_UNLIKELY (parse->priv->pending_events)) {
2012 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
2013 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
2015 g_list_free (parse->priv->pending_events);
2016 parse->priv->pending_events = NULL;
2019 if (klass->pre_push_frame) {
2020 ret = klass->pre_push_frame (parse, frame);
2022 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
2025 /* take final ownership of frame buffer */
2026 buffer = frame->buffer;
2027 frame->buffer = NULL;
2029 /* subclass must play nice */
2030 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2032 parse->priv->seen_keyframe |= parse->priv->is_video &&
2033 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
2035 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
2036 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2037 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
2038 GST_BUFFER_TIMESTAMP (buffer) >
2039 parse->segment.stop + parse->priv->lead_out_ts) {
2040 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
2042 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2043 GST_BUFFER_DURATION_IS_VALID (buffer) &&
2044 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
2045 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
2046 parse->priv->lead_in_ts < parse->segment.start) {
2047 if (parse->priv->seen_keyframe) {
2048 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
2051 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
2052 ret = GST_BASE_PARSE_FLOW_DROPPED;
2059 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
2060 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) dropped", size);
2061 gst_buffer_unref (buffer);
2063 } else if (ret == GST_FLOW_OK) {
2064 if (parse->segment.rate > 0.0) {
2065 GST_LOG_OBJECT (parse, "pushing frame (%" G_GSIZE_FORMAT " bytes) now..",
2067 ret = gst_pad_push (parse->srcpad, buffer);
2068 GST_LOG_OBJECT (parse, "frame pushed, flow %s", gst_flow_get_name (ret));
2070 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) queued for now",
2072 parse->priv->buffers_queued =
2073 g_slist_prepend (parse->priv->buffers_queued, buffer);
2077 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s",
2078 size, gst_flow_get_name (ret));
2079 gst_buffer_unref (buffer);
2080 /* if we are not sufficiently in control, let upstream decide on EOS */
2081 if (ret == GST_FLOW_EOS &&
2082 (parse->priv->passthrough ||
2083 (parse->priv->pad_mode == GST_PAD_MODE_PUSH &&
2084 !parse->priv->upstream_seekable)))
2088 /* Update current running segment position */
2089 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
2090 parse->segment.position < last_stop)
2091 parse->segment.position = last_stop;
2093 gst_base_parse_frame_free (frame);
2100 GST_ELEMENT_ERROR (parse, STREAM, DECODE, ("No caps set"), (NULL));
2101 return GST_FLOW_ERROR;
2106 /* gst_base_parse_drain:
2108 * Drains the adapter until it is empty. It decreases the min_frame_size to
2109 * match the current adapter size and calls chain method until the adapter
2110 * is emptied or chain returns with error.
2113 gst_base_parse_drain (GstBaseParse * parse)
2117 GST_DEBUG_OBJECT (parse, "draining");
2118 parse->priv->drain = TRUE;
2121 avail = gst_adapter_available (parse->priv->adapter);
2125 if (gst_base_parse_chain (parse->sinkpad, GST_OBJECT_CAST (parse),
2126 NULL) != GST_FLOW_OK) {
2130 /* nothing changed, maybe due to truncated frame; break infinite loop */
2131 if (avail == gst_adapter_available (parse->priv->adapter)) {
2132 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
2133 gst_adapter_clear (parse->priv->adapter);
2137 parse->priv->drain = FALSE;
2140 /* gst_base_parse_send_buffers
2142 * Sends buffers collected in send_buffers downstream, and ensures that list
2143 * is empty at the end (errors or not).
2145 static GstFlowReturn
2146 gst_base_parse_send_buffers (GstBaseParse * parse)
2148 GSList *send = NULL;
2150 GstFlowReturn ret = GST_FLOW_OK;
2152 send = parse->priv->buffers_send;
2156 buf = GST_BUFFER_CAST (send->data);
2157 GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
2158 GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2159 ", offset %" G_GINT64_FORMAT, buf,
2160 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2161 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2163 /* iterate output queue an push downstream */
2164 ret = gst_pad_push (parse->srcpad, buf);
2165 send = g_slist_delete_link (send, send);
2167 /* clear any leftover if error */
2168 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2170 buf = GST_BUFFER_CAST (send->data);
2171 gst_buffer_unref (buf);
2172 send = g_slist_delete_link (send, send);
2177 parse->priv->buffers_send = send;
2182 /* gst_base_parse_process_fragment:
2184 * Processes a reverse playback (forward) fragment:
2185 * - append head of last fragment that was skipped to current fragment data
2186 * - drain the resulting current fragment data (i.e. repeated chain)
2187 * - add time/duration (if needed) to frames queued by chain
2188 * - push queued data
2190 static GstFlowReturn
2191 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
2194 GstFlowReturn ret = GST_FLOW_OK;
2195 gboolean seen_key = FALSE, seen_delta = FALSE;
2201 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2202 while (parse->priv->buffers_pending) {
2203 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2204 GST_LOG_OBJECT (parse, "adding pending buffer (size %" G_GSIZE_FORMAT ")",
2205 gst_buffer_get_size (buf));
2206 gst_adapter_push (parse->priv->adapter, buf);
2207 parse->priv->buffers_pending =
2208 g_slist_delete_link (parse->priv->buffers_pending,
2209 parse->priv->buffers_pending);
2212 /* invalidate so no fall-back timestamping is performed;
2213 * ok if taken from subclass or upstream */
2214 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
2215 /* prevent it hanging around stop all the time */
2216 parse->segment.position = GST_CLOCK_TIME_NONE;
2218 parse->priv->discont = TRUE;
2220 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2221 /* initial skipped data is added to buffers_pending */
2222 gst_base_parse_drain (parse);
2225 if (parse->priv->buffers_send) {
2226 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2227 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2230 /* add metadata (if needed to queued buffers */
2231 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2232 GST_TIME_ARGS (parse->priv->last_ts));
2233 while (parse->priv->buffers_queued) {
2234 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2236 /* no touching if upstream or parsing provided time */
2237 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2238 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2239 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2240 } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
2241 GST_BUFFER_DURATION_IS_VALID (buf)) {
2242 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
2243 parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
2245 parse->priv->last_ts = 0;
2246 GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
2247 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2248 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2250 /* no idea, very bad */
2251 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2254 parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
2256 /* reverse order for ascending sending */
2257 /* send downstream at keyframe not preceded by a keyframe
2258 * (e.g. that should identify start of collection of IDR nals) */
2259 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2261 ret = gst_base_parse_send_buffers (parse);
2262 /* if a problem, throw all to sending */
2263 if (ret != GST_FLOW_OK) {
2264 parse->priv->buffers_send =
2265 g_slist_reverse (parse->priv->buffers_queued);
2266 parse->priv->buffers_queued = NULL;
2275 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2277 parse->priv->buffers_send =
2278 g_slist_prepend (parse->priv->buffers_send, buf);
2279 parse->priv->buffers_queued =
2280 g_slist_delete_link (parse->priv->buffers_queued,
2281 parse->priv->buffers_queued);
2284 /* audio may have all marked as keyframe, so arrange to send here */
2286 ret = gst_base_parse_send_buffers (parse);
2288 /* any trailing unused no longer usable (ideally none) */
2289 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2290 GST_DEBUG_OBJECT (parse, "discarding %" G_GSIZE_FORMAT " trailing bytes",
2291 gst_adapter_available (parse->priv->adapter));
2292 gst_adapter_clear (parse->priv->adapter);
2298 /* small helper that checks whether we have been trying to resync too long */
2299 static inline GstFlowReturn
2300 gst_base_parse_check_sync (GstBaseParse * parse)
2302 if (G_UNLIKELY (parse->priv->discont &&
2303 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2304 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2305 ("Failed to parse stream"), (NULL));
2306 return GST_FLOW_ERROR;
2312 static GstFlowReturn
2313 gst_base_parse_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2315 GstBaseParseClass *bclass;
2316 GstBaseParse *parse;
2317 GstFlowReturn ret = GST_FLOW_OK;
2318 GstBuffer *outbuf = NULL;
2319 GstBuffer *tmpbuf = NULL;
2323 guint old_min_size = 0, min_size, av;
2324 GstClockTime timestamp;
2325 GstBaseParseFrame *frame;
2327 parse = GST_BASE_PARSE (parent);
2328 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2330 if (parse->priv->detecting) {
2331 GstBuffer *detect_buf;
2333 if (parse->priv->detect_buffers_size == 0) {
2334 detect_buf = gst_buffer_ref (buffer);
2339 detect_buf = gst_buffer_new ();
2341 for (l = parse->priv->detect_buffers; l; l = l->next) {
2342 gsize tmpsize = gst_buffer_get_size (l->data);
2344 gst_buffer_copy_into (detect_buf, GST_BUFFER_CAST (l->data),
2345 GST_BUFFER_COPY_MEMORY, offset, tmpsize);
2349 gst_buffer_copy_into (detect_buf, buffer, GST_BUFFER_COPY_MEMORY,
2350 offset, gst_buffer_get_size (buffer));
2353 ret = bclass->detect (parse, detect_buf);
2354 gst_buffer_unref (detect_buf);
2356 if (ret == GST_FLOW_OK) {
2359 /* Detected something */
2360 parse->priv->detecting = FALSE;
2362 for (l = parse->priv->detect_buffers; l; l = l->next) {
2363 if (ret == GST_FLOW_OK && !parse->priv->flushing)
2365 gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2366 parent, GST_BUFFER_CAST (l->data));
2368 gst_buffer_unref (GST_BUFFER_CAST (l->data));
2370 g_list_free (parse->priv->detect_buffers);
2371 parse->priv->detect_buffers = NULL;
2372 parse->priv->detect_buffers_size = 0;
2374 if (ret != GST_FLOW_OK) {
2378 /* Handle the current buffer */
2379 } else if (ret == GST_FLOW_NOT_NEGOTIATED) {
2380 /* Still detecting, append buffer or error out if draining */
2382 if (parse->priv->drain) {
2383 GST_DEBUG_OBJECT (parse, "Draining but did not detect format yet");
2384 return GST_FLOW_ERROR;
2385 } else if (parse->priv->flushing) {
2386 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref,
2388 g_list_free (parse->priv->detect_buffers);
2389 parse->priv->detect_buffers = NULL;
2390 parse->priv->detect_buffers_size = 0;
2392 parse->priv->detect_buffers =
2393 g_list_append (parse->priv->detect_buffers, buffer);
2394 parse->priv->detect_buffers_size += gst_buffer_get_size (buffer);
2398 /* Something went wrong, subclass responsible for error reporting */
2402 /* And now handle the current buffer if detection worked */
2405 frame = &parse->priv->frame;
2407 if (G_LIKELY (buffer)) {
2408 GST_LOG_OBJECT (parse,
2409 "buffer size: %" G_GSIZE_FORMAT ", offset = %" G_GINT64_FORMAT,
2410 gst_buffer_get_size (buffer), GST_BUFFER_OFFSET (buffer));
2411 if (G_UNLIKELY (parse->priv->passthrough)) {
2412 gst_base_parse_frame_init (frame);
2413 frame->buffer = gst_buffer_make_writable (buffer);
2414 return gst_base_parse_push_frame (parse, frame);
2416 /* upstream feeding us in reverse playback;
2417 * gather each fragment, then process it in single run */
2418 if (parse->segment.rate < 0.0) {
2419 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2420 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2421 ret = gst_base_parse_process_fragment (parse, FALSE);
2423 gst_adapter_push (parse->priv->adapter, buffer);
2426 gst_adapter_push (parse->priv->adapter, buffer);
2429 if (G_UNLIKELY (buffer &&
2430 GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2431 frame->_private_flags |= GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
2432 gst_base_parse_frame_free (frame);
2435 /* Parse and push as many frames as possible */
2436 /* Stop either when adapter is empty or we are flushing */
2437 while (!parse->priv->flushing) {
2440 /* maintain frame state for a single frame parsing round across _chain calls,
2441 * so only init when needed */
2442 if (!frame->_private_flags)
2443 gst_base_parse_frame_init (frame);
2445 tmpbuf = gst_buffer_new ();
2448 /* Synchronization loop */
2450 /* note: if subclass indicates MAX fsize,
2451 * this will not likely be available anyway ... */
2452 min_size = MAX (parse->priv->min_frame_size, fsize);
2453 av = gst_adapter_available (parse->priv->adapter);
2455 /* loop safety check */
2456 if (G_UNLIKELY (old_min_size >= min_size))
2458 old_min_size = min_size;
2460 if (G_UNLIKELY (parse->priv->drain)) {
2462 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2463 if (G_UNLIKELY (!min_size)) {
2464 gst_buffer_unref (tmpbuf);
2469 /* Collect at least min_frame_size bytes */
2470 if (av < min_size) {
2471 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
2473 gst_buffer_unref (tmpbuf);
2477 /* always pass all available data */
2478 data = gst_adapter_map (parse->priv->adapter, av);
2479 gst_buffer_take_memory (tmpbuf, -1,
2480 gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
2481 (gpointer) data, NULL, av, 0, av));
2482 GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
2484 if (parse->priv->discont) {
2485 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2486 GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2490 gst_base_parse_frame_update (parse, frame, tmpbuf);
2491 res = bclass->check_valid_frame (parse, frame, &fsize, &skip);
2492 gst_adapter_unmap (parse->priv->adapter);
2493 gst_buffer_replace (&frame->buffer, NULL);
2494 gst_buffer_remove_memory_range (tmpbuf, 0, -1);
2496 if (gst_adapter_available (parse->priv->adapter) < fsize) {
2497 GST_DEBUG_OBJECT (parse, "found valid frame but not enough data"
2498 " available (only %" G_GSIZE_FORMAT " bytes)",
2499 gst_adapter_available (parse->priv->adapter));
2500 gst_buffer_unref (tmpbuf);
2503 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2507 /* subclass didn't touch this value. By default we skip 1 byte */
2511 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2512 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2513 /* reverse playback, and no frames found yet, so we are skipping
2514 * the leading part of a fragment, which may form the tail of
2515 * fragment coming later, hopefully subclass skips efficiently ... */
2516 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2517 outbuf = gst_adapter_take_buffer (parse->priv->adapter, skip);
2518 outbuf = gst_buffer_make_writable (outbuf);
2519 GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
2520 parse->priv->buffers_pending =
2521 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2524 gst_adapter_flush (parse->priv->adapter, skip);
2526 parse->priv->offset += skip;
2527 if (!parse->priv->discont)
2528 parse->priv->sync_offset = parse->priv->offset;
2529 parse->priv->discont = TRUE;
2530 /* something changed least; nullify loop check */
2533 /* skip == 0 should imply subclass set min_size to need more data;
2534 * we check this shortly */
2535 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2536 gst_buffer_unref (tmpbuf);
2540 gst_buffer_unref (tmpbuf);
2544 /* Subclass found the sync, but still wants to skip some data */
2545 GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
2546 gst_adapter_flush (parse->priv->adapter, skip);
2547 parse->priv->offset += skip;
2550 /* Grab lock to prevent a race with FLUSH_START handler */
2551 GST_PAD_STREAM_LOCK (parse->srcpad);
2553 /* FLUSH_START event causes the "flushing" flag to be set. In this
2554 * case we can leave the frame pushing loop */
2555 if (parse->priv->flushing) {
2556 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2560 /* move along with upstream timestamp (if any),
2561 * but interpolate in between */
2562 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2563 if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2564 (parse->priv->prev_ts != timestamp)) {
2565 parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2568 /* FIXME: Would it be more efficient to make a subbuffer instead? */
2569 outbuf = gst_adapter_take_buffer (parse->priv->adapter, fsize);
2570 outbuf = gst_buffer_make_writable (outbuf);
2572 /* Subclass may want to know the data offset */
2573 GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2574 parse->priv->offset += fsize;
2575 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2576 GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
2578 frame->buffer = outbuf;
2579 ret = gst_base_parse_handle_and_push_frame (parse, bclass, frame);
2580 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2582 if (ret != GST_FLOW_OK) {
2583 GST_LOG_OBJECT (parse, "push returned %d", ret);
2589 GST_LOG_OBJECT (parse, "chain leaving");
2595 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2596 ("min_size evolution %d -> %d; breaking to avoid looping",
2597 old_min_size, min_size));
2598 return GST_FLOW_ERROR;
2602 /* pull @size bytes at current offset,
2603 * i.e. at least try to and possibly return a shorter buffer if near the end */
2604 static GstFlowReturn
2605 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2606 GstBuffer ** buffer)
2608 GstFlowReturn ret = GST_FLOW_OK;
2610 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2612 /* Caching here actually makes much less difference than one would expect.
2613 * We do it mainly to avoid pulling buffers of 1 byte all the time */
2614 if (parse->priv->cache) {
2615 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2616 gint cache_size = gst_buffer_get_size (parse->priv->cache);
2618 if (cache_offset <= parse->priv->offset &&
2619 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2620 *buffer = gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL,
2621 parse->priv->offset - cache_offset, size);
2622 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2625 /* not enough data in the cache, free cache and get a new one */
2626 gst_buffer_unref (parse->priv->cache);
2627 parse->priv->cache = NULL;
2630 /* refill the cache */
2632 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2633 64 * 1024), &parse->priv->cache);
2634 if (ret != GST_FLOW_OK) {
2635 parse->priv->cache = NULL;
2639 if (gst_buffer_get_size (parse->priv->cache) >= size) {
2641 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0,
2643 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2647 /* Not possible to get enough data, try a last time with
2648 * requesting exactly the size we need */
2649 gst_buffer_unref (parse->priv->cache);
2650 parse->priv->cache = NULL;
2652 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2653 &parse->priv->cache);
2655 if (ret != GST_FLOW_OK) {
2656 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2661 if (gst_buffer_get_size (parse->priv->cache) < size) {
2662 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2663 G_GUINT64_FORMAT ": wanted %u bytes, got %" G_GSIZE_FORMAT " bytes",
2664 parse->priv->offset, size, gst_buffer_get_size (parse->priv->cache));
2666 *buffer = parse->priv->cache;
2667 parse->priv->cache = NULL;
2673 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0, size);
2674 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2679 static GstFlowReturn
2680 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2683 GstClockTime ts = 0;
2687 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2688 ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2689 parse->priv->last_offset);
2691 if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2692 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2693 GST_TIME_ARGS (parse->segment.start));
2698 /* last fragment started at last_offset / last_ts;
2699 * seek back 10s capped at 1MB */
2700 if (parse->priv->last_ts >= 10 * GST_SECOND)
2701 ts = parse->priv->last_ts - 10 * GST_SECOND;
2702 /* if we are exact now, we will be more so going backwards */
2703 if (parse->priv->exact_position) {
2704 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2706 if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2707 GST_FORMAT_BYTES, &offset)) {
2708 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2711 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2712 parse->priv->last_offset - 1024);
2713 offset = MAX (0, offset);
2715 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2717 parse->priv->offset = offset;
2719 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2721 if (ret != GST_FLOW_OK)
2724 /* offset will increase again as fragment is processed/parsed */
2725 parse->priv->last_offset = offset;
2727 gst_adapter_push (parse->priv->adapter, buffer);
2728 ret = gst_base_parse_process_fragment (parse, FALSE);
2729 if (ret != GST_FLOW_OK)
2732 /* force previous fragment */
2733 parse->priv->offset = -1;
2740 * pull and scan for next frame starting from current offset
2741 * ajusts sync, drain and offset going along */
2742 static GstFlowReturn
2743 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2744 GstBaseParseFrame * frame, gboolean full)
2746 GstBuffer *buffer, *outbuf;
2747 GstFlowReturn ret = GST_FLOW_OK;
2748 guint fsize = 1, min_size, old_min_size = 0;
2751 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2753 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2754 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2756 /* let's make this efficient for all subclass once and for all;
2757 * maybe it does not need this much, but in the latter case, we know we are
2758 * in pull mode here and might as well try to read and supply more anyway
2759 * (so does the buffer caching mechanism) */
2765 min_size = MAX (parse->priv->min_frame_size, fsize);
2766 /* loop safety check */
2767 if (G_UNLIKELY (old_min_size >= min_size))
2769 old_min_size = min_size;
2771 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2772 if (ret != GST_FLOW_OK)
2775 if (parse->priv->discont) {
2776 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2777 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2780 /* if we got a short read, inform subclass we are draining leftover
2781 * and no more is to be expected */
2782 if (gst_buffer_get_size (buffer) < min_size)
2783 parse->priv->drain = TRUE;
2785 if (parse->priv->detecting) {
2786 ret = klass->detect (parse, buffer);
2787 if (ret == GST_FLOW_NOT_NEGOTIATED) {
2788 /* If draining we error out, otherwise request a buffer
2790 if (parse->priv->drain) {
2791 gst_buffer_unref (buffer);
2792 GST_ERROR_OBJECT (parse, "Failed to detect format but draining");
2793 return GST_FLOW_ERROR;
2796 gst_buffer_unref (buffer);
2799 } else if (ret != GST_FLOW_OK) {
2800 gst_buffer_unref (buffer);
2801 GST_ERROR_OBJECT (parse, "detect() returned %s",
2802 gst_flow_get_name (ret));
2806 /* Else handle this buffer normally */
2810 gst_base_parse_frame_update (parse, frame, buffer);
2811 res = klass->check_valid_frame (parse, frame, &fsize, &skip);
2812 gst_buffer_replace (&frame->buffer, NULL);
2814 parse->priv->drain = FALSE;
2815 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2818 parse->priv->drain = FALSE;
2822 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2823 if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2824 /* reverse playback, and no frames found yet, so we are skipping
2825 * the leading part of a fragment, which may form the tail of
2826 * fragment coming later, hopefully subclass skips efficiently ... */
2827 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, 0, skip);
2828 parse->priv->buffers_pending =
2829 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2832 parse->priv->offset += skip;
2833 if (!parse->priv->discont)
2834 parse->priv->sync_offset = parse->priv->offset;
2835 parse->priv->discont = TRUE;
2836 /* something changed at least; nullify loop check */
2837 if (fsize == G_MAXUINT)
2838 fsize = old_min_size + 64 * 1024;
2841 /* skip == 0 should imply subclass set min_size to need more data;
2842 * we check this shortly */
2843 GST_DEBUG_OBJECT (parse, "finding sync...");
2844 gst_buffer_unref (buffer);
2845 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2850 /* Does the subclass want to skip too? */
2852 parse->priv->offset += skip;
2856 if (fsize + skip <= gst_buffer_get_size (buffer)) {
2857 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, skip, fsize);
2858 GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2859 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2860 gst_buffer_unref (buffer);
2862 gst_buffer_unref (buffer);
2863 ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2864 if (ret != GST_FLOW_OK)
2866 if (gst_buffer_get_size (outbuf) < fsize) {
2867 gst_buffer_unref (outbuf);
2872 parse->priv->offset += fsize;
2874 frame->buffer = outbuf;
2882 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2883 ("min_size evolution %d -> %d; breaking to avoid looping",
2884 old_min_size, min_size));
2885 return GST_FLOW_ERROR;
2889 /* Loop that is used in pull mode to retrieve data from upstream */
2891 gst_base_parse_loop (GstPad * pad)
2893 GstBaseParse *parse;
2894 GstBaseParseClass *klass;
2895 GstFlowReturn ret = GST_FLOW_OK;
2896 GstBaseParseFrame frame;
2898 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2899 klass = GST_BASE_PARSE_GET_CLASS (parse);
2901 /* reverse playback:
2902 * first fragment (closest to stop time) is handled normally below,
2903 * then we pull in fragments going backwards */
2904 if (parse->segment.rate < 0.0) {
2905 /* check if we jumped back to a previous fragment,
2906 * which is a post-first fragment */
2907 if (parse->priv->offset < 0) {
2908 ret = gst_base_parse_handle_previous_fragment (parse);
2913 gst_base_parse_frame_init (&frame);
2914 ret = gst_base_parse_scan_frame (parse, klass, &frame, TRUE);
2915 if (ret != GST_FLOW_OK)
2918 /* This always cleans up frame, even if error occurs */
2919 ret = gst_base_parse_handle_and_push_frame (parse, klass, &frame);
2921 /* eat expected eos signalling past segment in reverse playback */
2922 if (parse->segment.rate < 0.0 && ret == GST_FLOW_EOS &&
2923 parse->segment.position >= parse->segment.stop) {
2924 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2925 /* push what was accumulated during loop run */
2926 gst_base_parse_process_fragment (parse, TRUE);
2927 /* force previous fragment */
2928 parse->priv->offset = -1;
2933 if (ret == GST_FLOW_EOS)
2935 else if (ret != GST_FLOW_OK)
2938 gst_object_unref (parse);
2945 GST_DEBUG_OBJECT (parse, "eos");
2950 gboolean push_eos = FALSE;
2952 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2953 gst_flow_get_name (ret));
2954 gst_pad_pause_task (parse->sinkpad);
2956 if (ret == GST_FLOW_EOS) {
2957 /* handle end-of-stream/segment */
2958 if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2961 if ((stop = parse->segment.stop) == -1)
2962 stop = parse->segment.duration;
2964 GST_DEBUG_OBJECT (parse, "sending segment_done");
2966 gst_element_post_message
2967 (GST_ELEMENT_CAST (parse),
2968 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2969 GST_FORMAT_TIME, stop));
2971 /* If we STILL have zero frames processed, fire an error */
2972 if (parse->priv->framecount == 0) {
2973 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2974 ("No valid frames found before end of stream"), (NULL));
2978 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
2979 /* for fatal errors we post an error message, wrong-state is
2980 * not fatal because it happens due to flushes and only means
2981 * that we should stop now. */
2982 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2983 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2987 /* newsegment before eos */
2988 if (parse->priv->pending_segment) {
2989 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
2990 parse->priv->pending_segment = NULL;
2992 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2994 gst_object_unref (parse);
2999 gst_base_parse_sink_activate (GstPad * sinkpad, GstObject * parent)
3001 GstBaseParse *parse;
3002 gboolean result = TRUE;
3006 parse = GST_BASE_PARSE (parent);
3008 GST_DEBUG_OBJECT (parse, "sink activate");
3010 query = gst_query_new_scheduling ();
3011 result = gst_pad_peer_query (sinkpad, query);
3013 pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL);
3017 gst_query_unref (query);
3020 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
3021 result = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
3023 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
3024 result = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
3027 GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
3032 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
3034 GstBaseParseClass *klass;
3035 gboolean result = TRUE;
3037 GST_DEBUG_OBJECT (parse, "activate %d", active);
3039 klass = GST_BASE_PARSE_GET_CLASS (parse);
3042 if (parse->priv->pad_mode == GST_PAD_MODE_NONE && klass->start)
3043 result = klass->start (parse);
3045 /* If the subclass implements ::detect we want to
3046 * call it for the first buffers now */
3047 parse->priv->detecting = (klass->detect != NULL);
3049 /* We must make sure streaming has finished before resetting things
3050 * and calling the ::stop vfunc */
3051 GST_PAD_STREAM_LOCK (parse->sinkpad);
3052 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3054 if (parse->priv->pad_mode != GST_PAD_MODE_NONE && klass->stop)
3055 result = klass->stop (parse);
3057 parse->priv->pad_mode = GST_PAD_MODE_NONE;
3059 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
3064 gst_base_parse_sink_activate_mode (GstPad * pad, GstObject * parent,
3065 GstPadMode mode, gboolean active)
3067 gboolean result = TRUE;
3068 GstBaseParse *parse;
3070 parse = GST_BASE_PARSE (parent);
3072 GST_DEBUG_OBJECT (parse, "sink activate mode %d, %d", mode, active);
3074 result = gst_base_parse_activate (parse, active);
3078 case GST_PAD_MODE_PULL:
3080 parse->priv->pending_segment =
3081 gst_event_new_segment (&parse->segment);
3083 gst_pad_start_task (pad, (GstTaskFunction) gst_base_parse_loop,
3086 result &= gst_pad_stop_task (pad);
3094 parse->priv->pad_mode = active ? mode : GST_PAD_MODE_NONE;
3096 GST_DEBUG_OBJECT (parse, "sink activate return: %d", result);
3102 * gst_base_parse_set_duration:
3103 * @parse: #GstBaseParse.
3105 * @duration: duration value.
3106 * @interval: how often to update the duration estimate based on bitrate, or 0.
3108 * Sets the duration of the currently playing media. Subclass can use this
3109 * when it is able to determine duration and/or notices a change in the media
3110 * duration. Alternatively, if @interval is non-zero (default), then stream
3111 * duration is determined based on estimated bitrate, and updated every @interval
3117 gst_base_parse_set_duration (GstBaseParse * parse,
3118 GstFormat fmt, gint64 duration, gint interval)
3120 g_return_if_fail (parse != NULL);
3122 if (parse->priv->upstream_has_duration) {
3123 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
3127 if (duration != parse->priv->duration) {
3130 m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
3131 gst_element_post_message (GST_ELEMENT (parse), m);
3133 /* TODO: what about duration tag? */
3135 parse->priv->duration = duration;
3136 parse->priv->duration_fmt = fmt;
3137 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
3138 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
3139 if (interval != 0) {
3140 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
3144 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
3145 parse->priv->update_interval = interval;
3151 * gst_base_parse_set_average_bitrate:
3152 * @parse: #GstBaseParse.
3153 * @bitrate: average bitrate in bits/second
3155 * Optionally sets the average bitrate detected in media (if non-zero),
3156 * e.g. based on metadata, as it will be posted to the application.
3158 * By default, announced average bitrate is estimated. The average bitrate
3159 * is used to estimate the total duration of the stream and to estimate
3160 * a seek position, if there's no index and the format is syncable
3161 * (see gst_base_parse_set_syncable()).
3166 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
3168 parse->priv->bitrate = bitrate;
3169 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
3173 * gst_base_parse_set_min_frame_size:
3174 * @parse: #GstBaseParse.
3175 * @min_size: Minimum size of the data that this base class should give to
3178 * Subclass can use this function to tell the base class that it needs to
3179 * give at least #min_size buffers.
3184 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
3186 g_return_if_fail (parse != NULL);
3188 parse->priv->min_frame_size = min_size;
3189 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
3193 * gst_base_parse_set_frame_rate:
3194 * @parse: the #GstBaseParse to set
3195 * @fps_num: frames per second (numerator).
3196 * @fps_den: frames per second (denominator).
3197 * @lead_in: frames needed before a segment for subsequent decode
3198 * @lead_out: frames needed after a segment
3200 * If frames per second is configured, parser can take care of buffer duration
3201 * and timestamping. When performing segment clipping, or seeking to a specific
3202 * location, a corresponding decoder might need an initial @lead_in and a
3203 * following @lead_out number of frames to ensure the desired segment is
3204 * entirely filled upon decoding.
3209 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
3210 guint fps_den, guint lead_in, guint lead_out)
3212 g_return_if_fail (parse != NULL);
3214 parse->priv->fps_num = fps_num;
3215 parse->priv->fps_den = fps_den;
3216 if (!fps_num || !fps_den) {
3217 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
3219 fps_num = fps_den = 0;
3220 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
3221 parse->priv->lead_in = parse->priv->lead_out = 0;
3222 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
3224 parse->priv->frame_duration =
3225 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
3226 parse->priv->lead_in = lead_in;
3227 parse->priv->lead_out = lead_out;
3228 parse->priv->lead_in_ts =
3229 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
3230 parse->priv->lead_out_ts =
3231 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
3232 /* aim for about 1.5s to estimate duration */
3233 if (parse->priv->update_interval < 0) {
3234 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
3235 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
3236 parse->priv->update_interval);
3239 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
3240 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
3241 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
3242 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
3243 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
3244 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
3248 * gst_base_parse_set_has_timing_info:
3249 * @parse: a #GstBaseParse
3250 * @has_timing: whether frames carry timing information
3252 * Set if frames carry timing information which the subclass can (generally)
3253 * parse and provide. In particular, intrinsic (rather than estimated) time
3254 * can be obtained following a seek.
3259 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3261 parse->priv->has_timing_info = has_timing;
3262 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3266 * gst_base_parse_set_syncable:
3267 * @parse: a #GstBaseParse
3268 * @syncable: set if frame starts can be identified
3270 * Set if frame starts can be identified. This is set by default and
3271 * determines whether seeking based on bitrate averages
3272 * is possible for a format/stream.
3277 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3279 parse->priv->syncable = syncable;
3280 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3284 * gst_base_parse_set_passthrough:
3285 * @parse: a #GstBaseParse
3286 * @passthrough: %TRUE if parser should run in passthrough mode
3288 * Set if the nature of the format or configuration does not allow (much)
3289 * parsing, and the parser should operate in passthrough mode (which only
3290 * applies when operating in push mode). That is, incoming buffers are
3291 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3292 * callbacks will be invoked, but @pre_push_frame will still be invoked,
3293 * so subclass can perform as much or as little is appropriate for
3294 * passthrough semantics in @pre_push_frame.
3299 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3301 parse->priv->passthrough = passthrough;
3302 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3306 * gst_base_parse_set_latency:
3307 * @parse: a #GstBaseParse
3308 * @min_latency: minimum parse latency
3309 * @max_latency: maximum parse latency
3311 * Sets the minimum and maximum (which may likely be equal) latency introduced
3312 * by the parsing process. If there is such a latency, which depends on the
3313 * particular parsing of the format, it typically corresponds to 1 frame duration.
3318 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3319 GstClockTime max_latency)
3321 GST_OBJECT_LOCK (parse);
3322 parse->priv->min_latency = min_latency;
3323 parse->priv->max_latency = max_latency;
3324 GST_OBJECT_UNLOCK (parse);
3325 GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3326 GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3327 GST_TIME_ARGS (max_latency));
3331 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3332 GstClockTime * duration)
3334 gboolean res = FALSE;
3336 g_return_val_if_fail (duration != NULL, FALSE);
3338 *duration = GST_CLOCK_TIME_NONE;
3339 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3340 GST_LOG_OBJECT (parse, "using provided duration");
3341 *duration = parse->priv->duration;
3343 } else if (parse->priv->duration != -1) {
3344 GST_LOG_OBJECT (parse, "converting provided duration");
3345 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3346 parse->priv->duration, format, (gint64 *) duration);
3347 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3348 GST_LOG_OBJECT (parse, "using estimated duration");
3349 *duration = parse->priv->estimated_duration;
3353 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3354 GST_TIME_ARGS (*duration));
3359 gst_base_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
3361 GstBaseParse *parse;
3362 gboolean res = FALSE;
3364 parse = GST_BASE_PARSE (parent);
3366 GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3368 switch (GST_QUERY_TYPE (query)) {
3369 case GST_QUERY_POSITION:
3374 GST_DEBUG_OBJECT (parse, "position query");
3375 gst_query_parse_position (query, &format, NULL);
3377 /* try upstream first */
3378 res = gst_pad_query_default (pad, parent, query);
3380 /* Fall back on interpreting segment */
3381 GST_OBJECT_LOCK (parse);
3382 if (format == GST_FORMAT_BYTES) {
3383 dest_value = parse->priv->offset;
3385 } else if (format == parse->segment.format &&
3386 GST_CLOCK_TIME_IS_VALID (parse->segment.position)) {
3387 dest_value = gst_segment_to_stream_time (&parse->segment,
3388 parse->segment.format, parse->segment.position);
3391 GST_OBJECT_UNLOCK (parse);
3393 /* no precise result, upstream no idea either, then best estimate */
3394 /* priv->offset is updated in both PUSH/PULL modes */
3395 res = gst_base_parse_convert (parse,
3396 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3399 gst_query_set_position (query, format, dest_value);
3403 case GST_QUERY_DURATION:
3406 GstClockTime duration;
3408 GST_DEBUG_OBJECT (parse, "duration query");
3409 gst_query_parse_duration (query, &format, NULL);
3411 /* consult upstream */
3412 res = gst_pad_query_default (pad, parent, query);
3414 /* otherwise best estimate from us */
3416 res = gst_base_parse_get_duration (parse, format, &duration);
3418 gst_query_set_duration (query, format, duration);
3422 case GST_QUERY_SEEKING:
3425 GstClockTime duration = GST_CLOCK_TIME_NONE;
3426 gboolean seekable = FALSE;
3428 GST_DEBUG_OBJECT (parse, "seeking query");
3429 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3431 /* consult upstream */
3432 res = gst_pad_query_default (pad, parent, query);
3434 /* we may be able to help if in TIME */
3435 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3436 gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3437 /* already OK if upstream takes care */
3438 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3440 if (!(res && seekable)) {
3441 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3442 || duration == -1) {
3443 /* seekable if we still have a chance to get duration later on */
3445 parse->priv->upstream_seekable && parse->priv->update_interval;
3447 seekable = parse->priv->upstream_seekable;
3448 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3451 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3457 case GST_QUERY_FORMATS:
3458 gst_query_set_formatsv (query, 3, fmtlist);
3461 case GST_QUERY_CONVERT:
3463 GstFormat src_format, dest_format;
3464 gint64 src_value, dest_value;
3466 gst_query_parse_convert (query, &src_format, &src_value,
3467 &dest_format, &dest_value);
3469 res = gst_base_parse_convert (parse, src_format, src_value,
3470 dest_format, &dest_value);
3472 gst_query_set_convert (query, src_format, src_value,
3473 dest_format, dest_value);
3477 case GST_QUERY_LATENCY:
3479 if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3481 GstClockTime min_latency, max_latency;
3483 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3484 GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3485 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3486 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3488 GST_OBJECT_LOCK (parse);
3489 /* add our latency */
3490 if (min_latency != -1)
3491 min_latency += parse->priv->min_latency;
3492 if (max_latency != -1)
3493 max_latency += parse->priv->max_latency;
3494 GST_OBJECT_UNLOCK (parse);
3496 gst_query_set_latency (query, live, min_latency, max_latency);
3501 res = gst_pad_query_default (pad, parent, query);
3507 /* scans for a cluster start from @pos,
3508 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3509 static GstFlowReturn
3510 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3511 GstClockTime * time, GstClockTime * duration)
3513 GstBaseParseClass *klass;
3515 gboolean orig_drain, orig_discont;
3516 GstFlowReturn ret = GST_FLOW_OK;
3517 GstBuffer *buf = NULL;
3518 GstBaseParseFrame frame;
3520 g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3521 g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3522 g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3524 klass = GST_BASE_PARSE_GET_CLASS (parse);
3526 *time = GST_CLOCK_TIME_NONE;
3527 *duration = GST_CLOCK_TIME_NONE;
3530 orig_offset = parse->priv->offset;
3531 orig_discont = parse->priv->discont;
3532 orig_drain = parse->priv->drain;
3534 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3535 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3537 gst_base_parse_frame_init (&frame);
3539 /* jump elsewhere and locate next frame */
3540 parse->priv->offset = *pos;
3541 ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3542 if (ret != GST_FLOW_OK)
3546 GST_LOG_OBJECT (parse,
3547 "peek parsing frame at offset %" G_GUINT64_FORMAT
3548 " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
3549 GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf),
3550 gst_buffer_get_size (buf));
3552 /* get offset first, subclass parsing might dump other stuff in there */
3553 *pos = GST_BUFFER_OFFSET (buf);
3554 ret = klass->parse_frame (parse, &frame);
3557 /* but it should provide proper time */
3558 *time = GST_BUFFER_TIMESTAMP (buf);
3559 *duration = GST_BUFFER_DURATION (buf);
3561 gst_base_parse_frame_free (&frame);
3563 GST_LOG_OBJECT (parse,
3564 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3565 GST_TIME_ARGS (*time), *pos);
3569 parse->priv->offset = orig_offset;
3570 parse->priv->discont = orig_discont;
3571 parse->priv->drain = orig_drain;
3576 /* bisect and scan through file for frame starting before @time,
3577 * returns OK and @time/@offset if found, NONE and/or error otherwise
3578 * If @time == G_MAXINT64, scan for duration ( == last frame) */
3579 static GstFlowReturn
3580 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3583 GstFlowReturn ret = GST_FLOW_OK;
3584 gint64 lpos, hpos, newpos;
3585 GstClockTime time, ltime, htime, newtime, dur;
3586 gboolean cont = TRUE;
3587 const GstClockTime tolerance = TARGET_DIFFERENCE;
3588 const guint chunk = 4 * 1024;
3590 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3591 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3593 GST_DEBUG_OBJECT (parse, "Bisecting for time %" GST_TIME_FORMAT,
3594 GST_TIME_ARGS (*_time));
3596 /* TODO also make keyframe aware if useful some day */
3611 /* do not know at first */
3613 *_time = GST_CLOCK_TIME_NONE;
3615 /* need initial positions; start and end */
3616 lpos = parse->priv->first_frame_offset;
3617 ltime = parse->priv->first_frame_ts;
3618 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &htime)) {
3619 GST_DEBUG_OBJECT (parse, "Unknown time duration, cannot bisect");
3620 return GST_FLOW_ERROR;
3622 hpos = parse->priv->upstream_size;
3624 GST_DEBUG_OBJECT (parse,
3625 "Bisection initial bounds: bytes %" G_GINT64_FORMAT " %" G_GINT64_FORMAT
3626 ", times %" GST_TIME_FORMAT " %" GST_TIME_FORMAT, lpos, htime,
3627 GST_TIME_ARGS (ltime), GST_TIME_ARGS (htime));
3629 /* check preconditions are satisfied;
3630 * start and end are needed, except for special case where we scan for
3631 * last frame to determine duration */
3632 if (parse->priv->pad_mode != GST_PAD_MODE_PULL || !hpos ||
3633 !GST_CLOCK_TIME_IS_VALID (ltime) ||
3634 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3638 /* shortcut cases */
3641 } else if (time < ltime + tolerance) {
3645 } else if (time >= htime) {
3651 while (htime > ltime && cont) {
3652 GST_LOG_OBJECT (parse,
3653 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3654 GST_TIME_ARGS (ltime));
3655 GST_LOG_OBJECT (parse,
3656 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3657 GST_TIME_ARGS (htime));
3658 if (G_UNLIKELY (time == G_MAXINT64)) {
3660 } else if (G_LIKELY (hpos > lpos)) {
3662 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3665 /* should mean lpos == hpos, since lpos <= hpos is invariant */
3667 /* we check this case once, but not forever, so break loop */
3672 newpos = CLAMP (newpos, lpos, hpos);
3673 GST_LOG_OBJECT (parse,
3674 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3675 GST_TIME_ARGS (time), newpos);
3677 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3678 if (ret == GST_FLOW_EOS) {
3679 /* heuristic HACK */
3680 hpos = MAX (lpos, hpos - chunk);
3682 } else if (ret != GST_FLOW_OK) {
3686 if (newtime == -1 || newpos == -1) {
3687 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3691 if (G_UNLIKELY (time == G_MAXINT64)) {
3694 if (GST_CLOCK_TIME_IS_VALID (dur))
3697 } else if (newtime > time) {
3699 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3701 } else if (newtime + tolerance > time) {
3702 /* close enough undershoot */
3706 } else if (newtime < ltime) {
3707 /* so a position beyond lpos resulted in earlier time than ltime ... */
3708 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3711 /* undershoot too far */
3712 newpos += newpos == lpos ? chunk : 0;
3713 lpos = CLAMP (newpos, lpos, hpos);
3719 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3720 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3725 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3726 gboolean before, GstClockTime * _ts)
3728 gint64 bytes = 0, ts = 0;
3729 GstIndexEntry *entry = NULL;
3731 if (time == GST_CLOCK_TIME_NONE) {
3737 GST_BASE_PARSE_INDEX_LOCK (parse);
3738 if (parse->priv->index) {
3739 /* Let's check if we have an index entry for that time */
3740 entry = gst_index_get_assoc_entry (parse->priv->index,
3741 parse->priv->index_id,
3742 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3743 GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3747 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3748 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3750 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3751 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3752 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3754 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3755 GST_TIME_ARGS (time));
3758 ts = GST_CLOCK_TIME_NONE;
3761 GST_BASE_PARSE_INDEX_UNLOCK (parse);
3770 /* returns TRUE if seek succeeded */
3772 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3777 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3778 gboolean flush, update, res = TRUE, accurate;
3779 gint64 cur, stop, seekpos, seekstop;
3780 GstSegment seeksegment = { 0, };
3781 GstClockTime start_ts;
3783 gst_event_parse_seek (event, &rate, &format, &flags,
3784 &cur_type, &cur, &stop_type, &stop);
3786 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3787 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3788 GST_TIME_FORMAT, gst_format_get_name (format), rate,
3789 cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3791 /* no negative rates in push mode */
3792 if (rate < 0.0 && parse->priv->pad_mode == GST_PAD_MODE_PUSH)
3795 if (cur_type != GST_SEEK_TYPE_SET ||
3796 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3799 /* For any format other than TIME, see if upstream handles
3800 * it directly or fail. For TIME, try upstream, but do it ourselves if
3801 * it fails upstream */
3802 if (format != GST_FORMAT_TIME) {
3803 /* default action delegates to upstream */
3807 gst_event_ref (event);
3808 if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3813 /* get flush flag */
3814 flush = flags & GST_SEEK_FLAG_FLUSH;
3816 /* copy segment, we need this because we still need the old
3817 * segment when we close the current segment. */
3818 gst_segment_copy_into (&parse->segment, &seeksegment);
3820 GST_DEBUG_OBJECT (parse, "configuring seek");
3821 gst_segment_do_seek (&seeksegment, rate, format, flags,
3822 cur_type, cur, stop_type, stop, &update);
3824 /* accurate seeking implies seek tables are used to obtain position,
3825 * and the requested segment is maintained exactly, not adjusted any way */
3826 accurate = flags & GST_SEEK_FLAG_ACCURATE;
3828 /* maybe we can be accurate for (almost) free */
3829 gst_base_parse_find_offset (parse, seeksegment.position, TRUE, &start_ts);
3830 if (seeksegment.position <= start_ts + TARGET_DIFFERENCE) {
3831 GST_DEBUG_OBJECT (parse, "accurate seek possible");
3835 GstClockTime startpos = seeksegment.position;
3837 /* accurate requested, so ... seek a bit before target */
3838 if (startpos < parse->priv->lead_in_ts)
3841 startpos -= parse->priv->lead_in_ts;
3842 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3843 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3846 start_ts = seeksegment.position;
3847 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.position,
3848 GST_FORMAT_BYTES, &seekpos))
3849 goto convert_failed;
3850 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3851 GST_FORMAT_BYTES, &seekstop))
3852 goto convert_failed;
3855 GST_DEBUG_OBJECT (parse,
3856 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3858 GST_DEBUG_OBJECT (parse,
3859 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3860 seeksegment.stop, seekstop);
3862 if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
3865 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3868 if (parse->srcpad) {
3869 GST_DEBUG_OBJECT (parse, "sending flush start");
3870 gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3871 /* unlock upstream pull_range */
3872 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3875 gst_pad_pause_task (parse->sinkpad);
3878 /* we should now be able to grab the streaming thread because we stopped it
3879 * with the above flush/pause code */
3880 GST_PAD_STREAM_LOCK (parse->sinkpad);
3882 /* save current position */
3883 last_stop = parse->segment.position;
3884 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3887 /* now commit to new position */
3889 /* prepare for streaming again */
3891 GST_DEBUG_OBJECT (parse, "sending flush stop");
3892 gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop (TRUE));
3893 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop (TRUE));
3894 gst_base_parse_clear_queues (parse);
3896 /* keep track of our position */
3897 seeksegment.base = gst_segment_to_running_time (&seeksegment,
3898 seeksegment.format, parse->segment.position);
3901 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3903 /* store the newsegment event so it can be sent from the streaming thread. */
3904 if (parse->priv->pending_segment)
3905 gst_event_unref (parse->priv->pending_segment);
3907 /* This will be sent later in _loop() */
3908 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
3910 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3911 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3912 ", pos = %" GST_TIME_FORMAT, format,
3913 GST_TIME_ARGS (parse->segment.start),
3914 GST_TIME_ARGS (parse->segment.stop),
3915 GST_TIME_ARGS (parse->segment.start));
3917 /* one last chance in pull mode to stay accurate;
3918 * maybe scan and subclass can find where to go */
3921 GstClockTime ts = seeksegment.position;
3923 gst_base_parse_locate_time (parse, &ts, &scanpos);
3927 /* running collected index now consists of several intervals,
3928 * so optimized check no longer possible */
3929 parse->priv->index_last_valid = FALSE;
3930 parse->priv->index_last_offset = 0;
3931 parse->priv->index_last_ts = 0;
3935 /* mark discont if we are going to stream from another position. */
3936 if (seekpos != parse->priv->offset) {
3937 GST_DEBUG_OBJECT (parse,
3938 "mark DISCONT, we did a seek to another position");
3939 parse->priv->offset = seekpos;
3940 parse->priv->last_offset = seekpos;
3941 parse->priv->seen_keyframe = FALSE;
3942 parse->priv->discont = TRUE;
3943 parse->priv->next_ts = start_ts;
3944 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3945 parse->priv->sync_offset = seekpos;
3946 parse->priv->exact_position = accurate;
3949 /* Start streaming thread if paused */
3950 gst_pad_start_task (parse->sinkpad,
3951 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3953 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3958 GstEvent *new_event;
3959 GstBaseParseSeek *seek;
3960 GstSeekFlags flags = (flush ? GST_SEEK_FLAG_FLUSH : GST_SEEK_FLAG_NONE);
3962 /* The only thing we need to do in PUSH-mode is to send the
3963 seek event (in bytes) to upstream. Segment / flush handling happens
3964 in corresponding src event handlers */
3965 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3966 if (seekstop >= 0 && seekstop <= seekpos)
3968 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
3969 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3971 /* store segment info so its precise details can be reconstructed when
3972 * receiving newsegment;
3973 * this matters for all details when accurate seeking,
3974 * is most useful to preserve NONE stop time otherwise */
3975 seek = g_new0 (GstBaseParseSeek, 1);
3976 seek->segment = seeksegment;
3977 seek->accurate = accurate;
3978 seek->offset = seekpos;
3979 seek->start_ts = start_ts;
3980 GST_OBJECT_LOCK (parse);
3981 /* less optimal, but preserves order */
3982 parse->priv->pending_seeks =
3983 g_slist_append (parse->priv->pending_seeks, seek);
3984 GST_OBJECT_UNLOCK (parse);
3986 res = gst_pad_push_event (parse->sinkpad, new_event);
3989 GST_OBJECT_LOCK (parse);
3990 parse->priv->pending_seeks =
3991 g_slist_remove (parse->priv->pending_seeks, seek);
3992 GST_OBJECT_UNLOCK (parse);
3998 /* handled event is ours to free */
4000 gst_event_unref (event);
4006 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
4012 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
4018 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
4024 /* Checks if bitrates are available from upstream tags so that we don't
4025 * override them later
4028 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
4030 GstTagList *taglist = NULL;
4033 gst_event_parse_tag (event, &taglist);
4035 if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
4036 GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
4037 parse->priv->post_min_bitrate = FALSE;
4039 if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
4040 GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
4041 parse->priv->post_avg_bitrate = FALSE;
4043 if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
4044 GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
4045 parse->priv->post_max_bitrate = FALSE;
4051 gst_base_parse_set_index (GstElement * element, GstIndex * index)
4053 GstBaseParse *parse = GST_BASE_PARSE (element);
4055 GST_BASE_PARSE_INDEX_LOCK (parse);
4056 if (parse->priv->index)
4057 gst_object_unref (parse->priv->index);
4059 parse->priv->index = gst_object_ref (index);
4060 gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
4061 &parse->priv->index_id);
4062 parse->priv->own_index = FALSE;
4064 parse->priv->index = NULL;
4066 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4070 gst_base_parse_get_index (GstElement * element)
4072 GstBaseParse *parse = GST_BASE_PARSE (element);
4073 GstIndex *result = NULL;
4075 GST_BASE_PARSE_INDEX_LOCK (parse);
4076 if (parse->priv->index)
4077 result = gst_object_ref (parse->priv->index);
4078 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4084 static GstStateChangeReturn
4085 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
4087 GstBaseParse *parse;
4088 GstStateChangeReturn result;
4090 parse = GST_BASE_PARSE (element);
4092 switch (transition) {
4093 case GST_STATE_CHANGE_READY_TO_PAUSED:
4094 /* If this is our own index destroy it as the
4095 * old entries might be wrong for the new stream */
4096 GST_BASE_PARSE_INDEX_LOCK (parse);
4097 if (parse->priv->own_index) {
4098 gst_object_unref (parse->priv->index);
4099 parse->priv->index = NULL;
4100 parse->priv->own_index = FALSE;
4103 /* If no index was created, generate one */
4104 if (G_UNLIKELY (!parse->priv->index)) {
4105 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
4107 parse->priv->index = g_object_new (gst_mem_index_get_type (), NULL);
4108 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
4109 &parse->priv->index_id);
4110 parse->priv->own_index = TRUE;
4112 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4118 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4120 switch (transition) {
4121 case GST_STATE_CHANGE_PAUSED_TO_READY:
4122 gst_base_parse_reset (parse);