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., 51 Franklin St, Fifth Floor,
21 * Boston, MA 02110-1301, 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 (SEGMENT/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 calls @start to inform subclass that data processing is
57 * #GstBaseParse class calls @set_sink_caps to inform the subclass about
58 * incoming sinkpad caps. Subclass could already set the srcpad caps
59 * accordingly, but this might be delayed until calling
60 * gst_base_parse_finish_frame() with a non-queued frame.
63 * At least at this point subclass needs to tell the #GstBaseParse class
64 * how big data chunks it wants to receive (min_frame_size). It can do
65 * this with gst_base_parse_set_min_frame_size().
68 * #GstBaseParse class sets up appropriate data passing mode (pull/push)
69 * and starts to process the data.
75 * <title>Parsing phase</title>
77 * #GstBaseParse gathers at least min_frame_size bytes of data either
78 * by pulling it from upstream or collecting buffers in an internal
82 * A buffer of (at least) min_frame_size bytes is passed to subclass with
83 * @handle_frame. Subclass checks the contents and can optionally
84 * return GST_FLOW_OK along with an amount of data to be skipped to find
85 * a valid frame (which will result in a subsequent DISCONT).
86 * If, otherwise, the buffer does not hold a complete frame,
87 * @handle_frame can merely return and will be called again when additional
88 * data is available. In push mode this amounts to an
89 * additional input buffer (thus minimal additional latency), in pull mode
90 * this amounts to some arbitrary reasonable buffer size increase.
91 * Of course, gst_base_parse_set_min_frame_size() could also be used if a
92 * very specific known amount of additional data is required.
93 * If, however, the buffer holds a complete valid frame, it can pass
94 * the size of this frame to gst_base_parse_finish_frame().
95 * If acting as a converter, it can also merely indicate consumed input data
96 * while simultaneously providing custom output data.
97 * Note that baseclass performs some processing (such as tracking
98 * overall consumed data rate versus duration) for each finished frame,
99 * but other state is only updated upon each call to @handle_frame
100 * (such as tracking upstream input timestamp).
102 * Subclass is also responsible for setting the buffer metadata
103 * (e.g. buffer timestamp and duration, or keyframe if applicable).
104 * (although the latter can also be done by #GstBaseParse if it is
105 * appropriately configured, see below). Frame is provided with
106 * timestamp derived from upstream (as much as generally possible),
107 * duration obtained from configuration (see below), and offset
108 * if meaningful (in pull mode).
110 * Note that @check_valid_frame might receive any small
111 * amount of input data when leftover data is being drained (e.g. at EOS).
114 * As part of finish frame processing,
115 * just prior to actually pushing the buffer in question,
116 * it is passed to @pre_push_frame which gives subclass yet one
117 * last chance to examine buffer metadata, or to send some custom (tag)
118 * events, or to perform custom (segment) filtering.
121 * During the parsing process #GstBaseParseClass will handle both srcpad
122 * and sinkpad events. They will be passed to subclass if @event or
123 * @src_event callbacks have been provided.
128 * <itemizedlist><title>Shutdown phase</title>
130 * #GstBaseParse class calls @stop to inform the subclass that data
131 * parsing will be stopped.
137 * Subclass is responsible for providing pad template caps for
138 * source and sink pads. The pads need to be named "sink" and "src". It also
139 * needs to set the fixed caps on srcpad, when the format is ensured (e.g.
140 * when base class calls subclass' @set_sink_caps function).
142 * This base class uses %GST_FORMAT_DEFAULT as a meaning of frames. So,
143 * subclass conversion routine needs to know that conversion from
144 * %GST_FORMAT_TIME to %GST_FORMAT_DEFAULT must return the
145 * frame number that can be found from the given byte position.
147 * #GstBaseParse uses subclasses conversion methods also for seeking (or
148 * otherwise uses its own default one, see also below).
150 * Subclass @start and @stop functions will be called to inform the beginning
151 * and end of data processing.
153 * Things that subclass need to take care of:
155 * <listitem><para>Provide pad templates</para></listitem>
157 * Fixate the source pad caps when appropriate
160 * Inform base class how big data chunks should be retrieved. This is
161 * done with gst_base_parse_set_min_frame_size() function.
164 * Examine data chunks passed to subclass with @handle_frame and pass
165 * proper frame(s) to gst_base_parse_finish_frame(), and setting src pad
166 * caps and timestamps on frame.
168 * <listitem><para>Provide conversion functions</para></listitem>
170 * Update the duration information with gst_base_parse_set_duration()
173 * Optionally passthrough using gst_base_parse_set_passthrough()
176 * Configure various baseparse parameters using
177 * gst_base_parse_set_average_bitrate(), gst_base_parse_set_syncable()
178 * and gst_base_parse_set_frame_rate().
181 * In particular, if subclass is unable to determine a duration, but
182 * parsing (or specs) yields a frames per seconds rate, then this can be
183 * provided to #GstBaseParse to enable it to cater for
184 * buffer time metadata (which will be taken from upstream as much as
185 * possible). Internally keeping track of frame durations and respective
186 * sizes that have been pushed provides #GstBaseParse with an estimated
187 * bitrate. A default @convert (used if not overridden) will then use these
188 * rates to perform obvious conversions. These rates are also used to
189 * update (estimated) duration at regular frame intervals.
196 * - In push mode provide a queue of adapter-"queued" buffers for upstream
198 * - Queue buffers/events until caps are set
208 #include <gst/base/gstadapter.h>
210 #include "gstbaseparse.h"
212 /* FIXME: get rid of old GstIndex code */
213 #include "gstindex.h"
214 #include "gstindex.c"
215 #include "gstmemindex.c"
217 #define GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC (1 << 0)
219 #define MIN_FRAMES_TO_POST_BITRATE 10
220 #define TARGET_DIFFERENCE (20 * GST_SECOND)
221 #define MAX_INDEX_ENTRIES 4096
223 GST_DEBUG_CATEGORY_STATIC (gst_base_parse_debug);
224 #define GST_CAT_DEFAULT gst_base_parse_debug
226 /* Supported formats */
227 static const GstFormat fmtlist[] = {
234 #define GST_BASE_PARSE_GET_PRIVATE(obj) \
235 (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_PARSE, GstBaseParsePrivate))
237 struct _GstBaseParsePrivate
244 GstFormat duration_fmt;
245 gint64 estimated_duration;
246 gint64 estimated_drift;
248 guint min_frame_size;
249 gboolean disable_passthrough;
250 gboolean passthrough;
251 gboolean pts_interpolate;
254 gboolean has_timing_info;
255 guint fps_num, fps_den;
256 gint update_interval;
258 guint lead_in, lead_out;
259 GstClockTime lead_in_ts, lead_out_ts;
260 GstClockTime min_latency, max_latency;
268 GstClockTime next_pts;
269 GstClockTime next_dts;
270 GstClockTime prev_pts;
271 GstClockTime prev_dts;
272 GstClockTime frame_duration;
273 gboolean seen_keyframe;
279 guint64 data_bytecount;
280 guint64 acc_duration;
281 GstClockTime first_frame_pts;
282 GstClockTime first_frame_dts;
283 gint64 first_frame_offset;
285 gboolean post_min_bitrate;
286 gboolean post_avg_bitrate;
287 gboolean post_max_bitrate;
291 guint posted_avg_bitrate;
293 /* frames/buffers that are queued and ready to go on OK */
294 GQueue queued_frames;
298 /* index entry storage, either ours or provided */
304 /* seek table entries only maintained if upstream is BYTE seekable */
305 gboolean upstream_seekable;
306 gboolean upstream_has_duration;
307 gint64 upstream_size;
308 GstFormat upstream_format;
309 /* minimum distance between two index entries */
310 GstClockTimeDiff idx_interval;
311 guint64 idx_byte_interval;
312 /* ts and offset of last entry added */
313 GstClockTime index_last_ts;
314 gint64 index_last_offset;
315 gboolean index_last_valid;
317 /* timestamps currently produced are accurate, e.g. started from 0 onwards */
318 gboolean exact_position;
319 /* seek events are temporarily kept to match them with newsegments */
320 GSList *pending_seeks;
322 /* reverse playback */
323 GSList *buffers_pending;
324 GSList *buffers_head;
325 GSList *buffers_queued;
326 GSList *buffers_send;
327 GstClockTime last_pts;
328 GstClockTime last_dts;
331 /* Pending serialized events */
332 GList *pending_events;
334 /* If baseparse has checked the caps to identify if it is
335 * handling video or audio */
336 gboolean checked_media;
338 /* offset of last parsed frame/data */
340 /* force a new frame, regardless of offset */
342 /* whether we are merely scanning for a frame */
344 /* ... and resulting frame, if any */
345 GstBaseParseFrame *scanned_frame;
347 /* TRUE if we're still detecting the format, i.e.
348 * if ::detect() is still called for future buffers */
350 GList *detect_buffers;
351 guint detect_buffers_size;
353 /* True when no buffers have been received yet */
354 gboolean first_buffer;
356 /* if TRUE, a STREAM_START event needs to be pushed */
357 gboolean push_stream_start;
360 typedef struct _GstBaseParseSeek
365 GstClockTime start_ts;
368 #define DEFAULT_DISABLE_PASSTHROUGH FALSE
373 PROP_DISABLE_PASSTHROUGH,
377 #define GST_BASE_PARSE_INDEX_LOCK(parse) \
378 g_mutex_lock (&parse->priv->index_lock);
379 #define GST_BASE_PARSE_INDEX_UNLOCK(parse) \
380 g_mutex_unlock (&parse->priv->index_lock);
382 static GstElementClass *parent_class = NULL;
384 static void gst_base_parse_class_init (GstBaseParseClass * klass);
385 static void gst_base_parse_init (GstBaseParse * parse,
386 GstBaseParseClass * klass);
389 gst_base_parse_get_type (void)
391 static volatile gsize base_parse_type = 0;
393 if (g_once_init_enter (&base_parse_type)) {
394 static const GTypeInfo base_parse_info = {
395 sizeof (GstBaseParseClass),
396 (GBaseInitFunc) NULL,
397 (GBaseFinalizeFunc) NULL,
398 (GClassInitFunc) gst_base_parse_class_init,
401 sizeof (GstBaseParse),
403 (GInstanceInitFunc) gst_base_parse_init,
407 _type = g_type_register_static (GST_TYPE_ELEMENT,
408 "GstBaseParse", &base_parse_info, G_TYPE_FLAG_ABSTRACT);
409 g_once_init_leave (&base_parse_type, _type);
411 return (GType) base_parse_type;
414 static void gst_base_parse_finalize (GObject * object);
416 static GstStateChangeReturn gst_base_parse_change_state (GstElement * element,
417 GstStateChange transition);
418 static void gst_base_parse_reset (GstBaseParse * parse);
421 static void gst_base_parse_set_index (GstElement * element, GstIndex * index);
422 static GstIndex *gst_base_parse_get_index (GstElement * element);
425 static gboolean gst_base_parse_sink_activate (GstPad * sinkpad,
427 static gboolean gst_base_parse_sink_activate_mode (GstPad * pad,
428 GstObject * parent, GstPadMode mode, gboolean active);
429 static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
431 static void gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event);
433 static void gst_base_parse_set_property (GObject * object, guint prop_id,
434 const GValue * value, GParamSpec * pspec);
435 static void gst_base_parse_get_property (GObject * object, guint prop_id,
436 GValue * value, GParamSpec * pspec);
438 static gboolean gst_base_parse_src_event (GstPad * pad, GstObject * parent,
440 static gboolean gst_base_parse_src_query (GstPad * pad, GstObject * parent,
443 static gboolean gst_base_parse_sink_event (GstPad * pad, GstObject * parent,
445 static gboolean gst_base_parse_sink_query (GstPad * pad, GstObject * parent,
448 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstObject * parent,
450 static void gst_base_parse_loop (GstPad * pad);
452 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
453 GstBaseParseFrame * frame);
455 static gboolean gst_base_parse_sink_event_default (GstBaseParse * parse,
458 static gboolean gst_base_parse_src_event_default (GstBaseParse * parse,
461 static gboolean gst_base_parse_sink_query_default (GstBaseParse * parse,
463 static gboolean gst_base_parse_src_query_default (GstBaseParse * parse,
466 static void gst_base_parse_drain (GstBaseParse * parse);
468 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
469 gboolean post_min, gboolean post_avg, gboolean post_max);
471 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
472 GstClockTime time, gboolean before, GstClockTime * _ts);
473 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
474 GstClockTime * _time, gint64 * _offset);
476 static GstFlowReturn gst_base_parse_start_fragment (GstBaseParse * parse);
477 static GstFlowReturn gst_base_parse_finish_fragment (GstBaseParse * parse,
479 static GstFlowReturn gst_base_parse_send_buffers (GstBaseParse * parse);
481 static inline GstFlowReturn gst_base_parse_check_sync (GstBaseParse * parse);
483 static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);
485 static void gst_base_parse_push_pending_events (GstBaseParse * parse);
488 gst_base_parse_clear_queues (GstBaseParse * parse)
490 g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
491 g_slist_free (parse->priv->buffers_queued);
492 parse->priv->buffers_queued = NULL;
493 g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
495 g_slist_free (parse->priv->buffers_pending);
496 parse->priv->buffers_pending = NULL;
497 g_slist_foreach (parse->priv->buffers_head, (GFunc) gst_buffer_unref, NULL);
498 g_slist_free (parse->priv->buffers_head);
499 parse->priv->buffers_head = NULL;
500 g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
501 g_slist_free (parse->priv->buffers_send);
502 parse->priv->buffers_send = NULL;
504 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
505 g_list_free (parse->priv->detect_buffers);
506 parse->priv->detect_buffers = NULL;
507 parse->priv->detect_buffers_size = 0;
509 g_queue_foreach (&parse->priv->queued_frames,
510 (GFunc) gst_base_parse_frame_free, NULL);
511 g_queue_clear (&parse->priv->queued_frames);
513 gst_buffer_replace (&parse->priv->cache, NULL);
515 g_list_foreach (parse->priv->pending_events, (GFunc) gst_event_unref, NULL);
516 g_list_free (parse->priv->pending_events);
517 parse->priv->pending_events = NULL;
519 parse->priv->checked_media = FALSE;
523 gst_base_parse_finalize (GObject * object)
525 GstBaseParse *parse = GST_BASE_PARSE (object);
527 g_object_unref (parse->priv->adapter);
529 if (parse->priv->cache) {
530 gst_buffer_unref (parse->priv->cache);
531 parse->priv->cache = NULL;
534 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
536 g_list_free (parse->priv->pending_events);
537 parse->priv->pending_events = NULL;
539 if (parse->priv->index) {
540 gst_object_unref (parse->priv->index);
541 parse->priv->index = NULL;
543 g_mutex_clear (&parse->priv->index_lock);
545 gst_base_parse_clear_queues (parse);
547 G_OBJECT_CLASS (parent_class)->finalize (object);
551 gst_base_parse_class_init (GstBaseParseClass * klass)
553 GObjectClass *gobject_class;
554 GstElementClass *gstelement_class;
556 gobject_class = G_OBJECT_CLASS (klass);
557 g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
558 parent_class = g_type_class_peek_parent (klass);
560 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
561 gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_base_parse_set_property);
562 gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_base_parse_get_property);
565 * GstBaseParse:disable-passthrough:
567 * If set to %TRUE, baseparse will unconditionally force parsing of the
568 * incoming data. This can be required in the rare cases where the incoming
569 * side-data (caps, pts, dts, ...) is not trusted by the user and wants to
570 * force validation and parsing of the incoming data.
571 * If set to %FALSE, decision of whether to parse the data or not is up to
572 * the implementation (standard behaviour).
574 g_object_class_install_property (gobject_class, PROP_DISABLE_PASSTHROUGH,
575 g_param_spec_boolean ("disable-passthrough", "Disable passthrough",
576 "Force processing (disables passthrough)",
577 DEFAULT_DISABLE_PASSTHROUGH,
578 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
580 gstelement_class = (GstElementClass *) klass;
581 gstelement_class->change_state =
582 GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
585 gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
586 gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
589 /* Default handlers */
590 klass->sink_event = gst_base_parse_sink_event_default;
591 klass->src_event = gst_base_parse_src_event_default;
592 klass->sink_query = gst_base_parse_sink_query_default;
593 klass->src_query = gst_base_parse_src_query_default;
594 klass->convert = gst_base_parse_convert_default;
596 GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
597 "baseparse element");
601 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
603 GstPadTemplate *pad_template;
605 GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
607 parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
610 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
611 g_return_if_fail (pad_template != NULL);
612 parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
613 gst_pad_set_event_function (parse->sinkpad,
614 GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
615 gst_pad_set_query_function (parse->sinkpad,
616 GST_DEBUG_FUNCPTR (gst_base_parse_sink_query));
617 gst_pad_set_chain_function (parse->sinkpad,
618 GST_DEBUG_FUNCPTR (gst_base_parse_chain));
619 gst_pad_set_activate_function (parse->sinkpad,
620 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
621 gst_pad_set_activatemode_function (parse->sinkpad,
622 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_mode));
623 GST_PAD_SET_PROXY_ALLOCATION (parse->sinkpad);
624 gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
626 GST_DEBUG_OBJECT (parse, "sinkpad created");
629 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
630 g_return_if_fail (pad_template != NULL);
631 parse->srcpad = gst_pad_new_from_template (pad_template, "src");
632 gst_pad_set_event_function (parse->srcpad,
633 GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
634 gst_pad_set_query_function (parse->srcpad,
635 GST_DEBUG_FUNCPTR (gst_base_parse_src_query));
636 gst_pad_use_fixed_caps (parse->srcpad);
637 gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
638 GST_DEBUG_OBJECT (parse, "src created");
640 g_queue_init (&parse->priv->queued_frames);
642 parse->priv->adapter = gst_adapter_new ();
644 parse->priv->pad_mode = GST_PAD_MODE_NONE;
646 g_mutex_init (&parse->priv->index_lock);
649 gst_base_parse_reset (parse);
650 GST_DEBUG_OBJECT (parse, "init ok");
652 GST_OBJECT_FLAG_SET (parse, GST_ELEMENT_FLAG_INDEXABLE);
656 gst_base_parse_set_property (GObject * object, guint prop_id,
657 const GValue * value, GParamSpec * pspec)
659 GstBaseParse *parse = GST_BASE_PARSE (object);
662 case PROP_DISABLE_PASSTHROUGH:
663 parse->priv->disable_passthrough = g_value_get_boolean (value);
666 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
672 gst_base_parse_get_property (GObject * object, guint prop_id, GValue * value,
675 GstBaseParse *parse = GST_BASE_PARSE (object);
678 case PROP_DISABLE_PASSTHROUGH:
679 g_value_set_boolean (value, parse->priv->disable_passthrough);
682 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
687 static GstBaseParseFrame *
688 gst_base_parse_frame_copy (GstBaseParseFrame * frame)
690 GstBaseParseFrame *copy;
692 copy = g_slice_dup (GstBaseParseFrame, frame);
693 copy->buffer = gst_buffer_ref (frame->buffer);
694 copy->_private_flags &= ~GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
696 GST_TRACE ("copied frame %p -> %p", frame, copy);
702 gst_base_parse_frame_free (GstBaseParseFrame * frame)
704 GST_TRACE ("freeing frame %p", frame);
707 gst_buffer_unref (frame->buffer);
708 frame->buffer = NULL;
711 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
712 g_slice_free (GstBaseParseFrame, frame);
714 memset (frame, 0, sizeof (*frame));
718 G_DEFINE_BOXED_TYPE (GstBaseParseFrame, gst_base_parse_frame,
719 (GBoxedCopyFunc) gst_base_parse_frame_copy,
720 (GBoxedFreeFunc) gst_base_parse_frame_free);
723 * gst_base_parse_frame_init:
724 * @frame: #GstBaseParseFrame.
726 * Sets a #GstBaseParseFrame to initial state. Currently this means
727 * all public fields are zero-ed and a private flag is set to make
728 * sure gst_base_parse_frame_free() only frees the contents but not
729 * the actual frame. Use this function to initialise a #GstBaseParseFrame
730 * allocated on the stack.
733 gst_base_parse_frame_init (GstBaseParseFrame * frame)
735 memset (frame, 0, sizeof (GstBaseParseFrame));
736 frame->_private_flags = GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
737 GST_TRACE ("inited frame %p", frame);
741 * gst_base_parse_frame_new:
742 * @buffer: (transfer none): a #GstBuffer
744 * @overhead: number of bytes in this frame which should be counted as
745 * metadata overhead, ie. not used to calculate the average bitrate.
746 * Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
748 * Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
749 * elements written in C should usually allocate the frame on the stack and
750 * then use gst_base_parse_frame_init() to initialise it.
752 * Returns: a newly-allocated #GstBaseParseFrame. Free with
753 * gst_base_parse_frame_free() when no longer needed.
756 gst_base_parse_frame_new (GstBuffer * buffer, GstBaseParseFrameFlags flags,
759 GstBaseParseFrame *frame;
761 frame = g_slice_new0 (GstBaseParseFrame);
762 frame->buffer = gst_buffer_ref (buffer);
764 GST_TRACE ("created frame %p", frame);
769 gst_base_parse_frame_update (GstBaseParse * parse, GstBaseParseFrame * frame,
772 gst_buffer_replace (&frame->buffer, buf);
776 /* set flags one by one for clarity */
777 if (G_UNLIKELY (parse->priv->drain))
778 parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;
780 /* losing sync is pretty much a discont (and vice versa), no ? */
781 if (G_UNLIKELY (parse->priv->discont))
782 parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
786 gst_base_parse_reset (GstBaseParse * parse)
788 GST_OBJECT_LOCK (parse);
789 gst_segment_init (&parse->segment, GST_FORMAT_TIME);
790 parse->priv->duration = -1;
791 parse->priv->min_frame_size = 1;
792 parse->priv->discont = TRUE;
793 parse->priv->flushing = FALSE;
794 parse->priv->offset = 0;
795 parse->priv->sync_offset = 0;
796 parse->priv->update_interval = -1;
797 parse->priv->fps_num = parse->priv->fps_den = 0;
798 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
799 parse->priv->lead_in = parse->priv->lead_out = 0;
800 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
801 parse->priv->bitrate = 0;
802 parse->priv->framecount = 0;
803 parse->priv->bytecount = 0;
804 parse->priv->acc_duration = 0;
805 parse->priv->first_frame_pts = GST_CLOCK_TIME_NONE;
806 parse->priv->first_frame_dts = GST_CLOCK_TIME_NONE;
807 parse->priv->first_frame_offset = -1;
808 parse->priv->estimated_duration = -1;
809 parse->priv->estimated_drift = 0;
810 parse->priv->next_pts = GST_CLOCK_TIME_NONE;
811 parse->priv->next_dts = 0;
812 parse->priv->syncable = TRUE;
813 parse->priv->disable_passthrough = DEFAULT_DISABLE_PASSTHROUGH;
814 parse->priv->passthrough = FALSE;
815 parse->priv->pts_interpolate = TRUE;
816 parse->priv->infer_ts = TRUE;
817 parse->priv->has_timing_info = FALSE;
818 parse->priv->post_min_bitrate = TRUE;
819 parse->priv->post_avg_bitrate = TRUE;
820 parse->priv->post_max_bitrate = TRUE;
821 parse->priv->min_bitrate = G_MAXUINT;
822 parse->priv->max_bitrate = 0;
823 parse->priv->avg_bitrate = 0;
824 parse->priv->posted_avg_bitrate = 0;
826 parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
827 parse->priv->index_last_offset = -1;
828 parse->priv->index_last_valid = TRUE;
829 parse->priv->upstream_seekable = FALSE;
830 parse->priv->upstream_size = 0;
831 parse->priv->upstream_has_duration = FALSE;
832 parse->priv->upstream_format = GST_FORMAT_UNDEFINED;
833 parse->priv->idx_interval = 0;
834 parse->priv->idx_byte_interval = 0;
835 parse->priv->exact_position = TRUE;
836 parse->priv->seen_keyframe = FALSE;
837 parse->priv->checked_media = FALSE;
839 parse->priv->last_dts = GST_CLOCK_TIME_NONE;
840 parse->priv->last_pts = GST_CLOCK_TIME_NONE;
841 parse->priv->last_offset = 0;
843 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
845 g_list_free (parse->priv->pending_events);
846 parse->priv->pending_events = NULL;
848 if (parse->priv->cache) {
849 gst_buffer_unref (parse->priv->cache);
850 parse->priv->cache = NULL;
853 g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
854 g_slist_free (parse->priv->pending_seeks);
855 parse->priv->pending_seeks = NULL;
857 if (parse->priv->adapter)
858 gst_adapter_clear (parse->priv->adapter);
860 parse->priv->new_frame = TRUE;
862 parse->priv->first_buffer = TRUE;
864 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
865 g_list_free (parse->priv->detect_buffers);
866 parse->priv->detect_buffers = NULL;
867 parse->priv->detect_buffers_size = 0;
868 GST_OBJECT_UNLOCK (parse);
871 /* gst_base_parse_parse_frame:
872 * @parse: #GstBaseParse.
873 * @buffer: #GstBuffer.
875 * Default callback for parse_frame.
878 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
880 GstBuffer *buffer = frame->buffer;
882 if (!GST_BUFFER_PTS_IS_VALID (buffer) &&
883 GST_CLOCK_TIME_IS_VALID (parse->priv->next_pts)) {
884 GST_BUFFER_PTS (buffer) = parse->priv->next_pts;
886 if (!GST_BUFFER_DTS_IS_VALID (buffer) &&
887 GST_CLOCK_TIME_IS_VALID (parse->priv->next_dts)) {
888 GST_BUFFER_DTS (buffer) = parse->priv->next_dts;
890 if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
891 GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
892 GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
897 /* gst_base_parse_convert:
898 * @parse: #GstBaseParse.
899 * @src_format: #GstFormat describing the source format.
900 * @src_value: Source value to be converted.
901 * @dest_format: #GstFormat defining the converted format.
902 * @dest_value: Pointer where the conversion result will be put.
904 * Converts using configured "convert" vmethod in #GstBaseParse class.
906 * Returns: %TRUE if conversion was successful.
909 gst_base_parse_convert (GstBaseParse * parse,
910 GstFormat src_format,
911 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
913 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
916 g_return_val_if_fail (dest_value != NULL, FALSE);
921 ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
923 #ifndef GST_DISABLE_GST_DEBUG
926 if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
927 GST_LOG_OBJECT (parse,
928 "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
929 GST_TIME_ARGS (src_value), *dest_value);
930 } else if (dest_format == GST_FORMAT_TIME &&
931 src_format == GST_FORMAT_BYTES) {
932 GST_LOG_OBJECT (parse,
933 "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
934 src_value, GST_TIME_ARGS (*dest_value));
936 GST_LOG_OBJECT (parse,
937 "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
938 GST_STR_NULL (gst_format_get_name (src_format)),
939 GST_STR_NULL (gst_format_get_name (dest_format)),
940 src_value, *dest_value);
943 GST_DEBUG_OBJECT (parse, "conversion failed");
951 /* gst_base_parse_sink_event:
952 * @pad: #GstPad that received the event.
953 * @event: #GstEvent to be handled.
955 * Handler for sink pad events.
957 * Returns: %TRUE if the event was handled.
960 gst_base_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
962 GstBaseParse *parse = GST_BASE_PARSE (parent);
963 GstBaseParseClass *bclass = GST_BASE_PARSE_GET_CLASS (parse);
966 ret = bclass->sink_event (parse, event);
972 /* gst_base_parse_sink_event_default:
973 * @parse: #GstBaseParse.
974 * @event: #GstEvent to be handled.
976 * Element-level event handler function.
978 * The event will be unreffed only if it has been handled and this
979 * function returns %TRUE
981 * Returns: %TRUE if the event was handled and not need forwarding.
984 gst_base_parse_sink_event_default (GstBaseParse * parse, GstEvent * event)
986 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
987 gboolean ret = FALSE;
988 gboolean forward_immediate = FALSE;
990 GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
991 GST_EVENT_TYPE_NAME (event));
993 switch (GST_EVENT_TYPE (event)) {
998 gst_event_parse_caps (event, &caps);
999 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
1001 if (klass->set_sink_caps)
1002 ret = klass->set_sink_caps (parse, caps);
1006 /* will send our own caps downstream */
1007 gst_event_unref (event);
1011 case GST_EVENT_SEGMENT:
1013 const GstSegment *in_segment;
1014 GstSegment out_segment;
1015 gint64 offset = 0, next_dts;
1016 guint32 seqnum = gst_event_get_seqnum (event);
1018 gst_event_parse_segment (event, &in_segment);
1019 gst_segment_init (&out_segment, GST_FORMAT_TIME);
1020 out_segment.rate = in_segment->rate;
1021 out_segment.applied_rate = in_segment->applied_rate;
1023 GST_DEBUG_OBJECT (parse, "segment %" GST_SEGMENT_FORMAT, in_segment);
1025 parse->priv->upstream_format = in_segment->format;
1026 if (in_segment->format == GST_FORMAT_BYTES) {
1027 GstBaseParseSeek *seek = NULL;
1030 /* stop time is allowed to be open-ended, but not start & pos */
1031 offset = in_segment->time;
1033 GST_OBJECT_LOCK (parse);
1034 for (node = parse->priv->pending_seeks; node; node = node->next) {
1035 GstBaseParseSeek *tmp = node->data;
1037 if (tmp->offset == offset) {
1042 parse->priv->pending_seeks =
1043 g_slist_remove (parse->priv->pending_seeks, seek);
1044 GST_OBJECT_UNLOCK (parse);
1047 GST_DEBUG_OBJECT (parse,
1048 "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
1049 seek->accurate ? " accurate" : "", &seek->segment);
1051 out_segment.start = seek->segment.start;
1052 out_segment.stop = seek->segment.stop;
1053 out_segment.time = seek->segment.start;
1055 next_dts = seek->start_ts;
1056 parse->priv->exact_position = seek->accurate;
1059 /* best attempt convert */
1060 /* as these are only estimates, stop is kept open-ended to avoid
1061 * premature cutting */
1062 gst_base_parse_convert (parse, GST_FORMAT_BYTES, in_segment->start,
1063 GST_FORMAT_TIME, (gint64 *) & next_dts);
1065 out_segment.start = next_dts;
1066 out_segment.stop = GST_CLOCK_TIME_NONE;
1067 out_segment.time = next_dts;
1069 parse->priv->exact_position = (in_segment->start == 0);
1072 gst_event_unref (event);
1074 event = gst_event_new_segment (&out_segment);
1075 gst_event_set_seqnum (event, seqnum);
1077 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. %"
1078 GST_SEGMENT_FORMAT, in_segment);
1080 } else if (in_segment->format != GST_FORMAT_TIME) {
1081 /* Unknown incoming segment format. Output a default open-ended
1083 gst_event_unref (event);
1085 out_segment.start = 0;
1086 out_segment.stop = GST_CLOCK_TIME_NONE;
1087 out_segment.time = 0;
1089 event = gst_event_new_segment (&out_segment);
1090 gst_event_set_seqnum (event, seqnum);
1094 /* not considered BYTE seekable if it is talking to us in TIME,
1095 * whatever else it might claim */
1096 parse->priv->upstream_seekable = FALSE;
1097 next_dts = in_segment->start;
1098 gst_event_copy_segment (event, &out_segment);
1101 memcpy (&parse->segment, &out_segment, sizeof (GstSegment));
1104 gst_segment_set_newsegment (&parse->segment, update, rate,
1105 applied_rate, format, start, stop, start);
1110 /* save the segment for later, right before we push a new buffer so that
1111 * the caps are fixed and the next linked element can receive
1112 * the segment but finish the current segment */
1113 GST_DEBUG_OBJECT (parse, "draining current segment");
1114 if (in_segment->rate > 0.0)
1115 gst_base_parse_drain (parse);
1117 gst_base_parse_finish_fragment (parse, FALSE);
1118 gst_adapter_clear (parse->priv->adapter);
1120 parse->priv->offset = offset;
1121 parse->priv->sync_offset = offset;
1122 parse->priv->next_dts = next_dts;
1123 parse->priv->next_pts = GST_CLOCK_TIME_NONE;
1124 parse->priv->last_pts = GST_CLOCK_TIME_NONE;
1125 parse->priv->last_dts = GST_CLOCK_TIME_NONE;
1126 parse->priv->prev_pts = GST_CLOCK_TIME_NONE;
1127 parse->priv->prev_dts = GST_CLOCK_TIME_NONE;
1128 parse->priv->discont = TRUE;
1129 parse->priv->seen_keyframe = FALSE;
1133 case GST_EVENT_FLUSH_START:
1134 GST_OBJECT_LOCK (parse);
1135 parse->priv->flushing = TRUE;
1136 GST_OBJECT_UNLOCK (parse);
1139 case GST_EVENT_FLUSH_STOP:
1140 gst_adapter_clear (parse->priv->adapter);
1141 gst_base_parse_clear_queues (parse);
1142 parse->priv->flushing = FALSE;
1143 parse->priv->discont = TRUE;
1144 parse->priv->last_pts = GST_CLOCK_TIME_NONE;
1145 parse->priv->last_dts = GST_CLOCK_TIME_NONE;
1146 parse->priv->new_frame = TRUE;
1148 forward_immediate = TRUE;
1152 if (parse->segment.rate > 0.0)
1153 gst_base_parse_drain (parse);
1155 gst_base_parse_finish_fragment (parse, TRUE);
1157 /* If we STILL have zero frames processed, fire an error */
1158 if (parse->priv->framecount == 0) {
1159 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1160 ("No valid frames found before end of stream"), (NULL));
1162 /* newsegment and other serialized events before eos */
1163 gst_base_parse_push_pending_events (parse);
1165 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1166 /* We've not posted bitrate tags yet - do so now */
1167 gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
1169 forward_immediate = TRUE;
1171 case GST_EVENT_CUSTOM_DOWNSTREAM:{
1172 /* FIXME: Code duplicated from libgstvideo because core can't depend on -base */
1173 #ifndef GST_VIDEO_EVENT_STILL_STATE_NAME
1174 #define GST_VIDEO_EVENT_STILL_STATE_NAME "GstEventStillFrame"
1177 const GstStructure *s;
1178 gboolean ev_still_state;
1180 s = gst_event_get_structure (event);
1182 gst_structure_has_name (s, GST_VIDEO_EVENT_STILL_STATE_NAME) &&
1183 gst_structure_get_boolean (s, "still-state", &ev_still_state)) {
1184 if (ev_still_state) {
1185 GST_DEBUG_OBJECT (parse, "draining current data for still-frame");
1186 if (parse->segment.rate > 0.0)
1187 gst_base_parse_drain (parse);
1189 gst_base_parse_finish_fragment (parse, TRUE);
1191 forward_immediate = TRUE;
1197 GST_DEBUG_OBJECT (parse, "draining current data due to gap event");
1199 gst_base_parse_push_pending_events (parse);
1201 if (parse->segment.rate > 0.0)
1202 gst_base_parse_drain (parse);
1204 gst_base_parse_finish_fragment (parse, TRUE);
1205 forward_immediate = TRUE;
1209 /* See if any bitrate tags were posted */
1210 gst_base_parse_handle_tag (parse, event);
1213 case GST_EVENT_STREAM_START:
1214 if (parse->priv->pad_mode != GST_PAD_MODE_PULL)
1215 forward_immediate = TRUE;
1222 /* Forward non-serialized events and EOS/FLUSH_STOP immediately.
1223 * For EOS this is required because no buffer or serialized event
1224 * will come after EOS and nothing could trigger another
1225 * _finish_frame() call. *
1226 * If the subclass handles sending of EOS manually it can return
1227 * _DROPPED from ::finish() and all other subclasses should have
1228 * decoded/flushed all remaining data before this
1230 * For FLUSH_STOP this is required because it is expected
1231 * to be forwarded immediately and no buffers are queued anyway.
1234 if (!GST_EVENT_IS_SERIALIZED (event) || forward_immediate) {
1235 ret = gst_pad_push_event (parse->srcpad, event);
1237 // GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1238 parse->priv->pending_events =
1239 g_list_prepend (parse->priv->pending_events, event);
1240 // GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1245 GST_DEBUG_OBJECT (parse, "event handled");
1251 gst_base_parse_sink_query_default (GstBaseParse * parse, GstQuery * query)
1256 pad = GST_BASE_PARSE_SINK_PAD (parse);
1258 switch (GST_QUERY_TYPE (query)) {
1259 case GST_QUERY_CAPS:
1261 GstBaseParseClass *bclass;
1263 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1265 if (bclass->get_sink_caps) {
1266 GstCaps *caps, *filter;
1268 gst_query_parse_caps (query, &filter);
1269 caps = bclass->get_sink_caps (parse, filter);
1270 GST_LOG_OBJECT (parse, "sink getcaps returning caps %" GST_PTR_FORMAT,
1272 gst_query_set_caps_result (query, caps);
1273 gst_caps_unref (caps);
1277 GstCaps *caps, *template_caps, *filter;
1279 gst_query_parse_caps (query, &filter);
1280 template_caps = gst_pad_get_pad_template_caps (pad);
1281 if (filter != NULL) {
1283 gst_caps_intersect_full (filter, template_caps,
1284 GST_CAPS_INTERSECT_FIRST);
1285 gst_caps_unref (template_caps);
1287 caps = template_caps;
1289 gst_query_set_caps_result (query, caps);
1290 gst_caps_unref (caps);
1298 res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
1307 gst_base_parse_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
1309 GstBaseParseClass *bclass;
1310 GstBaseParse *parse;
1313 parse = GST_BASE_PARSE (parent);
1314 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1316 GST_DEBUG_OBJECT (parse, "%s query", GST_QUERY_TYPE_NAME (query));
1318 if (bclass->sink_query)
1319 ret = bclass->sink_query (parse, query);
1323 GST_LOG_OBJECT (parse, "%s query result: %d %" GST_PTR_FORMAT,
1324 GST_QUERY_TYPE_NAME (query), ret, query);
1330 gst_base_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1332 GstBaseParseClass *bclass;
1333 GstBaseParse *parse;
1336 parse = GST_BASE_PARSE (parent);
1337 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1339 GST_DEBUG_OBJECT (parse, "%s query: %" GST_PTR_FORMAT,
1340 GST_QUERY_TYPE_NAME (query), query);
1342 if (bclass->src_query)
1343 ret = bclass->src_query (parse, query);
1347 GST_LOG_OBJECT (parse, "%s query result: %d %" GST_PTR_FORMAT,
1348 GST_QUERY_TYPE_NAME (query), ret, query);
1353 /* gst_base_parse_src_event:
1354 * @pad: #GstPad that received the event.
1355 * @event: #GstEvent that was received.
1357 * Handler for source pad events.
1359 * Returns: %TRUE if the event was handled.
1362 gst_base_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1364 GstBaseParse *parse;
1365 GstBaseParseClass *bclass;
1366 gboolean ret = TRUE;
1368 parse = GST_BASE_PARSE (parent);
1369 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1371 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1372 GST_EVENT_TYPE_NAME (event));
1374 if (bclass->src_event)
1375 ret = bclass->src_event (parse, event);
1377 gst_event_unref (event);
1383 gst_base_parse_is_seekable (GstBaseParse * parse)
1385 /* FIXME: could do more here, e.g. check index or just send data from 0
1386 * in pull mode and let decoder/sink clip */
1387 return parse->priv->syncable;
1390 /* gst_base_parse_src_event_default:
1391 * @parse: #GstBaseParse.
1392 * @event: #GstEvent that was received.
1394 * Default srcpad event handler.
1396 * Returns: %TRUE if the event was handled and can be dropped.
1399 gst_base_parse_src_event_default (GstBaseParse * parse, GstEvent * event)
1401 gboolean res = FALSE;
1403 switch (GST_EVENT_TYPE (event)) {
1404 case GST_EVENT_SEEK:
1405 if (gst_base_parse_is_seekable (parse))
1406 res = gst_base_parse_handle_seek (parse, event);
1409 res = gst_pad_event_default (parse->srcpad, GST_OBJECT_CAST (parse),
1418 * gst_base_parse_convert_default:
1419 * @parse: #GstBaseParse.
1420 * @src_format: #GstFormat describing the source format.
1421 * @src_value: Source value to be converted.
1422 * @dest_format: #GstFormat defining the converted format.
1423 * @dest_value: Pointer where the conversion result will be put.
1425 * Default implementation of "convert" vmethod in #GstBaseParse class.
1427 * Returns: %TRUE if conversion was successful.
1430 gst_base_parse_convert_default (GstBaseParse * parse,
1431 GstFormat src_format,
1432 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1434 gboolean ret = FALSE;
1435 guint64 bytes, duration;
1437 if (G_UNLIKELY (src_format == dest_format)) {
1438 *dest_value = src_value;
1442 if (G_UNLIKELY (src_value == -1)) {
1447 if (G_UNLIKELY (src_value == 0)) {
1452 /* need at least some frames */
1453 if (!parse->priv->framecount)
1456 duration = parse->priv->acc_duration / GST_MSECOND;
1457 bytes = parse->priv->bytecount;
1459 if (G_UNLIKELY (!duration || !bytes))
1460 goto no_duration_bytes;
1462 if (src_format == GST_FORMAT_BYTES) {
1463 if (dest_format == GST_FORMAT_TIME) {
1464 /* BYTES -> TIME conversion */
1465 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1466 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1467 *dest_value *= GST_MSECOND;
1468 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1469 *dest_value / GST_MSECOND);
1472 GST_DEBUG_OBJECT (parse, "converting bytes -> other not implemented");
1474 } else if (src_format == GST_FORMAT_TIME) {
1475 if (dest_format == GST_FORMAT_BYTES) {
1476 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1477 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1479 GST_DEBUG_OBJECT (parse,
1480 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1481 src_value / GST_MSECOND, *dest_value);
1484 GST_DEBUG_OBJECT (parse, "converting time -> other not implemented");
1486 } else if (src_format == GST_FORMAT_DEFAULT) {
1487 /* DEFAULT == frame-based */
1488 if (dest_format == GST_FORMAT_TIME) {
1489 GST_DEBUG_OBJECT (parse, "converting default -> time");
1490 if (parse->priv->fps_den) {
1491 *dest_value = gst_util_uint64_scale (src_value,
1492 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1496 GST_DEBUG_OBJECT (parse, "converting default -> other not implemented");
1499 GST_DEBUG_OBJECT (parse, "conversion not implemented");
1506 GST_DEBUG_OBJECT (parse, "no framecount");
1511 GST_DEBUG_OBJECT (parse, "no duration %" G_GUINT64_FORMAT ", bytes %"
1512 G_GUINT64_FORMAT, duration, bytes);
1519 gst_base_parse_update_duration (GstBaseParse * baseparse)
1522 GstBaseParse *parse;
1524 parse = GST_BASE_PARSE (baseparse);
1526 peer = gst_pad_get_peer (parse->sinkpad);
1528 gboolean qres = FALSE;
1529 gint64 ptot, dest_value;
1531 qres = gst_pad_query_duration (peer, GST_FORMAT_BYTES, &ptot);
1532 gst_object_unref (GST_OBJECT (peer));
1534 if (gst_base_parse_convert (parse, GST_FORMAT_BYTES, ptot,
1535 GST_FORMAT_TIME, &dest_value)) {
1537 /* inform if duration changed, but try to avoid spamming */
1538 parse->priv->estimated_drift +=
1539 dest_value - parse->priv->estimated_duration;
1540 if (parse->priv->estimated_drift > GST_SECOND ||
1541 parse->priv->estimated_drift < -GST_SECOND) {
1542 gst_element_post_message (GST_ELEMENT (parse),
1543 gst_message_new_duration_changed (GST_OBJECT (parse)));
1544 parse->priv->estimated_drift = 0;
1546 parse->priv->estimated_duration = dest_value;
1547 GST_LOG_OBJECT (parse,
1548 "updated estimated duration to %" GST_TIME_FORMAT,
1549 GST_TIME_ARGS (dest_value));
1556 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1557 gboolean post_avg, gboolean post_max)
1559 GstTagList *taglist = NULL;
1561 if (post_min && parse->priv->post_min_bitrate) {
1562 taglist = gst_tag_list_new_empty ();
1564 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1565 GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1568 if (post_avg && parse->priv->post_avg_bitrate) {
1569 if (taglist == NULL)
1570 taglist = gst_tag_list_new_empty ();
1572 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1573 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1574 parse->priv->avg_bitrate, NULL);
1577 if (post_max && parse->priv->post_max_bitrate) {
1578 if (taglist == NULL)
1579 taglist = gst_tag_list_new_empty ();
1581 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1582 GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1585 GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1586 parse->priv->min_bitrate, parse->priv->avg_bitrate,
1587 parse->priv->max_bitrate);
1589 if (taglist != NULL) {
1590 gst_pad_push_event (parse->srcpad, gst_event_new_tag (taglist));
1594 /* gst_base_parse_update_bitrates:
1595 * @parse: #GstBaseParse.
1596 * @buffer: Current frame as a #GstBuffer
1598 * Keeps track of the minimum and maximum bitrates, and also maintains a
1599 * running average bitrate of the stream so far.
1602 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1604 /* Only update the tag on a 10 kbps delta */
1605 static const gint update_threshold = 10000;
1607 guint64 data_len, frame_dur;
1608 gint overhead, frame_bitrate, old_avg_bitrate;
1609 gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1610 GstBuffer *buffer = frame->buffer;
1612 overhead = frame->overhead;
1616 data_len = gst_buffer_get_size (buffer) - overhead;
1617 parse->priv->data_bytecount += data_len;
1619 /* duration should be valid by now,
1620 * either set by subclass or maybe based on fps settings */
1621 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1622 /* Calculate duration of a frame from buffer properties */
1623 frame_dur = GST_BUFFER_DURATION (buffer);
1624 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1625 parse->priv->acc_duration;
1628 /* No way to figure out frame duration (is this even possible?) */
1632 /* override if subclass provided bitrate, e.g. metadata based */
1633 if (parse->priv->bitrate) {
1634 parse->priv->avg_bitrate = parse->priv->bitrate;
1635 /* spread this (confirmed) info ASAP */
1636 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1637 gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1641 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1645 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1646 parse->priv->avg_bitrate);
1648 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1650 } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1651 /* always post all at threshold time */
1652 update_min = update_max = update_avg = TRUE;
1655 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1656 if (frame_bitrate < parse->priv->min_bitrate) {
1657 parse->priv->min_bitrate = frame_bitrate;
1661 if (frame_bitrate > parse->priv->max_bitrate) {
1662 parse->priv->max_bitrate = frame_bitrate;
1666 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1667 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1668 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1673 if ((update_min || update_avg || update_max))
1674 gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1681 * gst_base_parse_add_index_entry:
1682 * @parse: #GstBaseParse.
1683 * @offset: offset of entry
1684 * @ts: timestamp associated with offset
1685 * @key: whether entry refers to keyframe
1686 * @force: add entry disregarding sanity checks
1688 * Adds an entry to the index associating @offset to @ts. It is recommended
1689 * to only add keyframe entries. @force allows to bypass checks, such as
1690 * whether the stream is (upstream) seekable, another entry is already "close"
1691 * to the new entry, etc.
1693 * Returns: #gboolean indicating whether entry was added
1696 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1697 GstClockTime ts, gboolean key, gboolean force)
1699 gboolean ret = FALSE;
1700 GstIndexAssociation associations[2];
1702 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1703 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1705 if (G_LIKELY (!force)) {
1707 if (!parse->priv->upstream_seekable) {
1708 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1712 /* FIXME need better helper data structure that handles these issues
1713 * related to ongoing collecting of index entries */
1714 if (parse->priv->index_last_offset + parse->priv->idx_byte_interval >=
1716 GST_LOG_OBJECT (parse,
1717 "already have entries up to offset 0x%08" G_GINT64_MODIFIER "x",
1718 parse->priv->index_last_offset + parse->priv->idx_byte_interval);
1722 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1723 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1724 parse->priv->idx_interval) {
1725 GST_LOG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1726 GST_TIME_ARGS (parse->priv->index_last_ts));
1730 /* if last is not really the last one */
1731 if (!parse->priv->index_last_valid) {
1732 GstClockTime prev_ts;
1734 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1735 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1736 GST_LOG_OBJECT (parse,
1737 "entry too close to existing entry %" GST_TIME_FORMAT,
1738 GST_TIME_ARGS (prev_ts));
1739 parse->priv->index_last_offset = offset;
1740 parse->priv->index_last_ts = ts;
1746 associations[0].format = GST_FORMAT_TIME;
1747 associations[0].value = ts;
1748 associations[1].format = GST_FORMAT_BYTES;
1749 associations[1].value = offset;
1751 /* index might change on-the-fly, although that would be nutty app ... */
1752 GST_BASE_PARSE_INDEX_LOCK (parse);
1753 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1754 (key) ? GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT :
1755 GST_INDEX_ASSOCIATION_FLAG_DELTA_UNIT, 2,
1756 (const GstIndexAssociation *) &associations);
1757 GST_BASE_PARSE_INDEX_UNLOCK (parse);
1760 parse->priv->index_last_offset = offset;
1761 parse->priv->index_last_ts = ts;
1770 /* check for seekable upstream, above and beyond a mere query */
1772 gst_base_parse_check_seekability (GstBaseParse * parse)
1775 gboolean seekable = FALSE;
1776 gint64 start = -1, stop = -1;
1777 guint idx_interval = 0;
1778 guint64 idx_byte_interval = 0;
1780 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1781 if (!gst_pad_peer_query (parse->sinkpad, query)) {
1782 GST_DEBUG_OBJECT (parse, "seeking query failed");
1786 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1788 /* try harder to query upstream size if we didn't get it the first time */
1789 if (seekable && stop == -1) {
1790 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1791 gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_BYTES, &stop);
1794 /* if upstream doesn't know the size, it's likely that it's not seekable in
1795 * practice even if it technically may be seekable */
1796 if (seekable && (start != 0 || stop <= start)) {
1797 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1801 /* let's not put every single frame into our index */
1803 if (stop < 10 * 1024 * 1024)
1805 else if (stop < 100 * 1024 * 1024)
1808 idx_interval = 1000;
1810 /* ensure that even for large files (e.g. very long audio files), the index
1811 * stays reasonably-size, with some arbitrary limit to the total number of
1813 idx_byte_interval = (stop - start) / MAX_INDEX_ENTRIES;
1814 GST_DEBUG_OBJECT (parse,
1815 "Limiting index entries to %d, indexing byte interval %"
1816 G_GUINT64_FORMAT " bytes", MAX_INDEX_ENTRIES, idx_byte_interval);
1820 gst_query_unref (query);
1822 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1823 G_GUINT64_FORMAT ")", seekable, start, stop);
1824 parse->priv->upstream_seekable = seekable;
1825 parse->priv->upstream_size = seekable ? stop : 0;
1827 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1828 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1829 parse->priv->idx_byte_interval = idx_byte_interval;
1832 /* some misc checks on upstream */
1834 gst_base_parse_check_upstream (GstBaseParse * parse)
1838 if (gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_TIME, &stop))
1839 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1840 /* upstream has one, accept it also, and no further updates */
1841 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1842 parse->priv->upstream_has_duration = TRUE;
1845 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1846 parse->priv->upstream_has_duration);
1849 /* checks src caps to determine if dealing with audio or video */
1850 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1852 gst_base_parse_check_media (GstBaseParse * parse)
1857 caps = gst_pad_get_current_caps (parse->srcpad);
1858 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1859 parse->priv->is_video =
1860 g_str_has_prefix (gst_structure_get_name (s), "video");
1862 /* historical default */
1863 parse->priv->is_video = FALSE;
1866 gst_caps_unref (caps);
1868 parse->priv->checked_media = TRUE;
1869 GST_DEBUG_OBJECT (parse, "media is video: %d", parse->priv->is_video);
1872 /* takes ownership of frame */
1874 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1876 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1877 /* frame allocated on the heap, we can just take ownership */
1878 g_queue_push_tail (&parse->priv->queued_frames, frame);
1879 GST_TRACE ("queued frame %p", frame);
1881 GstBaseParseFrame *copy;
1883 /* probably allocated on the stack, must make a proper copy */
1884 copy = gst_base_parse_frame_copy (frame);
1885 g_queue_push_tail (&parse->priv->queued_frames, copy);
1886 GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1887 gst_base_parse_frame_free (frame);
1891 /* makes sure that @buf is properly prepared and decorated for passing
1892 * to baseclass, and an equally setup frame is returned setup with @buf.
1893 * Takes ownership of @buf. */
1894 static GstBaseParseFrame *
1895 gst_base_parse_prepare_frame (GstBaseParse * parse, GstBuffer * buffer)
1897 GstBaseParseFrame *frame = NULL;
1899 buffer = gst_buffer_make_writable (buffer);
1901 GST_LOG_OBJECT (parse,
1902 "preparing frame at offset %" G_GUINT64_FORMAT
1903 " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
1904 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1905 gst_buffer_get_size (buffer));
1907 if (parse->priv->discont) {
1908 GST_DEBUG_OBJECT (parse, "marking DISCONT");
1909 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1910 parse->priv->discont = FALSE;
1913 GST_BUFFER_OFFSET (buffer) = parse->priv->offset;
1915 frame = gst_base_parse_frame_new (buffer, 0, 0);
1917 /* also ensure to update state flags */
1918 gst_base_parse_frame_update (parse, frame, buffer);
1919 gst_buffer_unref (buffer);
1921 if (parse->priv->prev_offset != parse->priv->offset || parse->priv->new_frame) {
1922 GST_LOG_OBJECT (parse, "marking as new frame");
1923 parse->priv->new_frame = FALSE;
1924 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_NEW_FRAME;
1927 frame->offset = parse->priv->prev_offset = parse->priv->offset;
1929 /* use default handler to provide initial (upstream) metadata */
1930 gst_base_parse_parse_frame (parse, frame);
1935 /* Wraps buffer in a frame and dispatches to subclass.
1936 * Also manages data skipping and offset handling (including adapter flushing).
1937 * Takes ownership of @buffer */
1938 static GstFlowReturn
1939 gst_base_parse_handle_buffer (GstBaseParse * parse, GstBuffer * buffer,
1940 gint * skip, gint * flushed)
1942 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1943 GstBaseParseFrame *frame;
1946 g_return_val_if_fail (skip != NULL || flushed != NULL, GST_FLOW_ERROR);
1948 GST_LOG_OBJECT (parse,
1949 "handling buffer of size %" G_GSIZE_FORMAT " with dts %" GST_TIME_FORMAT
1950 ", pts %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
1951 gst_buffer_get_size (buffer), GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
1952 GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
1953 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1955 /* track what is being flushed during this single round of frame processing */
1956 parse->priv->flushed = 0;
1959 /* make it easy for _finish_frame to pick up input data */
1960 if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
1961 gst_buffer_ref (buffer);
1962 gst_adapter_push (parse->priv->adapter, buffer);
1965 frame = gst_base_parse_prepare_frame (parse, buffer);
1966 ret = klass->handle_frame (parse, frame, skip);
1968 *flushed = parse->priv->flushed;
1970 GST_LOG_OBJECT (parse, "handle_frame skipped %d, flushed %d",
1973 /* subclass can only do one of these, or semantics are too unclear */
1974 g_assert (*skip == 0 || *flushed == 0);
1976 /* track skipping */
1978 GstClockTime pts, dts;
1981 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", *skip);
1982 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
1983 /* reverse playback, and no frames found yet, so we are skipping
1984 * the leading part of a fragment, which may form the tail of
1985 * fragment coming later, hopefully subclass skips efficiently ... */
1986 pts = gst_adapter_prev_pts (parse->priv->adapter, NULL);
1987 dts = gst_adapter_prev_dts (parse->priv->adapter, NULL);
1988 outbuf = gst_adapter_take_buffer (parse->priv->adapter, *skip);
1989 outbuf = gst_buffer_make_writable (outbuf);
1990 GST_BUFFER_PTS (outbuf) = pts;
1991 GST_BUFFER_DTS (outbuf) = dts;
1992 parse->priv->buffers_head =
1993 g_slist_prepend (parse->priv->buffers_head, outbuf);
1996 gst_adapter_flush (parse->priv->adapter, *skip);
1998 if (!parse->priv->discont)
1999 parse->priv->sync_offset = parse->priv->offset;
2000 parse->priv->offset += *skip;
2001 parse->priv->discont = TRUE;
2002 /* check for indefinite skipping */
2003 if (ret == GST_FLOW_OK)
2004 ret = gst_base_parse_check_sync (parse);
2007 parse->priv->offset += *flushed;
2009 if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
2010 gst_adapter_clear (parse->priv->adapter);
2013 gst_base_parse_frame_free (frame);
2018 /* gst_base_parse_push_pending_events:
2019 * @parse: #GstBaseParse
2021 * Pushes the pending events
2024 gst_base_parse_push_pending_events (GstBaseParse * parse)
2026 if (G_UNLIKELY (parse->priv->pending_events)) {
2027 GList *r = g_list_reverse (parse->priv->pending_events);
2030 parse->priv->pending_events = NULL;
2031 for (l = r; l != NULL; l = l->next) {
2032 gst_pad_push_event (parse->srcpad, GST_EVENT_CAST (l->data));
2038 /* gst_base_parse_handle_and_push_frame:
2039 * @parse: #GstBaseParse.
2040 * @klass: #GstBaseParseClass.
2041 * @frame: (transfer full): a #GstBaseParseFrame
2043 * Parses the frame from given buffer and pushes it forward. Also performs
2044 * timestamp handling and checks the segment limits.
2046 * This is called with srcpad STREAM_LOCK held.
2048 * Returns: #GstFlowReturn
2050 static GstFlowReturn
2051 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
2052 GstBaseParseFrame * frame)
2057 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2059 buffer = frame->buffer;
2060 offset = frame->offset;
2062 /* check if subclass/format can provide ts.
2063 * If so, that allows and enables extra seek and duration determining options */
2064 if (G_UNLIKELY (parse->priv->first_frame_offset < 0)) {
2065 if (GST_BUFFER_PTS_IS_VALID (buffer) && parse->priv->has_timing_info
2066 && parse->priv->pad_mode == GST_PAD_MODE_PULL) {
2067 parse->priv->first_frame_offset = offset;
2068 parse->priv->first_frame_pts = GST_BUFFER_PTS (buffer);
2069 parse->priv->first_frame_dts = GST_BUFFER_DTS (buffer);
2070 GST_DEBUG_OBJECT (parse, "subclass provided dts %" GST_TIME_FORMAT
2071 ", pts %" GST_TIME_FORMAT " for first frame at offset %"
2072 G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->first_frame_dts),
2073 GST_TIME_ARGS (parse->priv->first_frame_pts),
2074 parse->priv->first_frame_offset);
2075 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
2077 GstClockTime last_ts = G_MAXINT64;
2079 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
2080 gst_base_parse_locate_time (parse, &last_ts, &off);
2081 if (GST_CLOCK_TIME_IS_VALID (last_ts))
2082 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
2085 /* disable further checks */
2086 parse->priv->first_frame_offset = 0;
2090 /* track upstream time if provided, not subclass' internal notion of it */
2091 if (parse->priv->upstream_format == GST_FORMAT_TIME) {
2092 GST_BUFFER_PTS (frame->buffer) = GST_CLOCK_TIME_NONE;
2093 GST_BUFFER_DTS (frame->buffer) = GST_CLOCK_TIME_NONE;
2096 /* interpolating and no valid pts yet,
2097 * start with dts and carry on from there */
2098 if (parse->priv->infer_ts && parse->priv->pts_interpolate
2099 && !GST_CLOCK_TIME_IS_VALID (parse->priv->next_pts))
2100 parse->priv->next_pts = parse->priv->next_dts;
2102 /* again use default handler to add missing metadata;
2103 * we may have new information on frame properties */
2104 gst_base_parse_parse_frame (parse, frame);
2106 parse->priv->next_pts = GST_CLOCK_TIME_NONE;
2107 if (GST_BUFFER_DTS_IS_VALID (buffer) && GST_BUFFER_DURATION_IS_VALID (buffer)) {
2108 parse->priv->next_dts =
2109 GST_BUFFER_DTS (buffer) + GST_BUFFER_DURATION (buffer);
2110 if (parse->priv->pts_interpolate && GST_BUFFER_PTS_IS_VALID (buffer)) {
2111 GstClockTime next_pts =
2112 GST_BUFFER_PTS (buffer) + GST_BUFFER_DURATION (buffer);
2113 if (next_pts >= parse->priv->next_dts)
2114 parse->priv->next_pts = next_pts;
2117 /* we lost track, do not produce bogus time next time around
2118 * (probably means parser subclass has given up on parsing as well) */
2119 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
2120 parse->priv->next_dts = GST_CLOCK_TIME_NONE;
2123 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
2124 GST_BUFFER_PTS_IS_VALID (buffer))
2125 gst_base_parse_add_index_entry (parse, offset,
2126 GST_BUFFER_PTS (buffer),
2127 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
2129 /* All OK, push queued frames if there are any */
2130 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
2131 GstBaseParseFrame *queued_frame;
2133 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
2134 gst_base_parse_push_frame (parse, queued_frame);
2135 gst_base_parse_frame_free (queued_frame);
2139 return gst_base_parse_push_frame (parse, frame);
2143 * gst_base_parse_push_frame:
2144 * @parse: #GstBaseParse.
2145 * @frame: (transfer none): a #GstBaseParseFrame
2147 * Pushes the frame's buffer downstream, sends any pending events and
2148 * does some timestamp and segment handling. Takes ownership of
2149 * frame's buffer, though caller retains ownership of @frame.
2151 * This must be called with sinkpad STREAM_LOCK held.
2153 * Returns: #GstFlowReturn
2156 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
2158 GstFlowReturn ret = GST_FLOW_OK;
2159 GstClockTime last_start = GST_CLOCK_TIME_NONE;
2160 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
2161 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
2165 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2166 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
2168 GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
2170 buffer = frame->buffer;
2172 GST_LOG_OBJECT (parse,
2173 "processing buffer of size %" G_GSIZE_FORMAT " with dts %" GST_TIME_FORMAT
2174 ", pts %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
2175 gst_buffer_get_size (buffer),
2176 GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
2177 GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
2178 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
2181 parse->priv->bytecount += frame->size;
2182 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
2183 parse->priv->framecount++;
2184 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
2185 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
2188 /* 0 means disabled */
2189 if (parse->priv->update_interval < 0)
2190 parse->priv->update_interval = 50;
2191 else if (parse->priv->update_interval > 0 &&
2192 (parse->priv->framecount % parse->priv->update_interval) == 0)
2193 gst_base_parse_update_duration (parse);
2195 if (GST_BUFFER_PTS_IS_VALID (buffer))
2196 last_start = last_stop = GST_BUFFER_PTS (buffer);
2197 if (last_start != GST_CLOCK_TIME_NONE
2198 && GST_BUFFER_DURATION_IS_VALID (buffer))
2199 last_stop = last_start + GST_BUFFER_DURATION (buffer);
2201 /* should have caps by now */
2202 if (!gst_pad_has_current_caps (parse->srcpad))
2205 if (G_UNLIKELY (!parse->priv->checked_media)) {
2206 /* have caps; check identity */
2207 gst_base_parse_check_media (parse);
2210 /* Push pending events, including SEGMENT events */
2211 gst_base_parse_push_pending_events (parse);
2213 /* segment adjustment magic; only if we are running the whole show */
2214 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
2215 (parse->priv->pad_mode == GST_PAD_MODE_PULL ||
2216 parse->priv->upstream_seekable)) {
2218 if (GST_CLOCK_TIME_IS_VALID (parse->segment.position) &&
2219 GST_CLOCK_TIME_IS_VALID (last_start)) {
2220 GstClockTimeDiff diff;
2222 /* only send newsegments with increasing start times,
2223 * otherwise if these go back and forth downstream (sinks) increase
2224 * accumulated time and running_time */
2225 diff = GST_CLOCK_DIFF (parse->segment.position, last_start);
2226 if (G_UNLIKELY (diff > 2 * GST_SECOND
2227 && last_start > parse->segment.start
2228 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
2229 || last_start < parse->segment.stop))) {
2231 GST_DEBUG_OBJECT (parse,
2232 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
2233 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
2234 "Sending updated SEGMENT events", diff,
2235 GST_TIME_ARGS (parse->segment.position),
2236 GST_TIME_ARGS (last_start));
2238 /* skip gap FIXME */
2239 gst_pad_push_event (parse->srcpad,
2240 gst_event_new_segment (&parse->segment));
2242 parse->segment.position = last_start;
2247 /* update bitrates and optionally post corresponding tags
2248 * (following newsegment) */
2249 gst_base_parse_update_bitrates (parse, frame);
2251 if (klass->pre_push_frame) {
2252 ret = klass->pre_push_frame (parse, frame);
2254 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
2257 /* take final ownership of frame buffer */
2258 if (frame->out_buffer) {
2259 buffer = frame->out_buffer;
2260 frame->out_buffer = NULL;
2261 gst_buffer_replace (&frame->buffer, NULL);
2263 buffer = frame->buffer;
2264 frame->buffer = NULL;
2267 /* subclass must play nice */
2268 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2270 size = gst_buffer_get_size (buffer);
2272 parse->priv->seen_keyframe |= parse->priv->is_video &&
2273 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
2275 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
2276 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2277 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
2278 GST_BUFFER_TIMESTAMP (buffer) >
2279 parse->segment.stop + parse->priv->lead_out_ts) {
2280 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
2282 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2283 GST_BUFFER_DURATION_IS_VALID (buffer) &&
2284 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
2285 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
2286 parse->priv->lead_in_ts < parse->segment.start) {
2287 if (parse->priv->seen_keyframe) {
2288 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
2291 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
2292 ret = GST_BASE_PARSE_FLOW_DROPPED;
2299 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
2300 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) dropped", size);
2301 gst_buffer_unref (buffer);
2303 } else if (ret == GST_FLOW_OK) {
2304 if (parse->segment.rate > 0.0) {
2305 GST_LOG_OBJECT (parse, "pushing frame (%" G_GSIZE_FORMAT " bytes) now..",
2307 ret = gst_pad_push (parse->srcpad, buffer);
2308 GST_LOG_OBJECT (parse, "frame pushed, flow %s", gst_flow_get_name (ret));
2309 } else if (!parse->priv->disable_passthrough && parse->priv->passthrough) {
2311 /* in backwards playback mode, if on passthrough we need to push buffers
2312 * directly without accumulating them into the buffers_queued as baseparse
2313 * will never check for a DISCONT while on passthrough and those buffers
2314 * will never be pushed.
2316 * also, as we are on reverse playback, it might be possible that
2317 * passthrough might have just been enabled, so make sure to drain the
2318 * buffers_queued list */
2319 if (G_UNLIKELY (parse->priv->buffers_queued != NULL)) {
2320 gst_base_parse_finish_fragment (parse, TRUE);
2321 ret = gst_base_parse_send_buffers (parse);
2324 if (ret == GST_FLOW_OK) {
2325 GST_LOG_OBJECT (parse,
2326 "pushing frame (%" G_GSIZE_FORMAT " bytes) now..", size);
2327 ret = gst_pad_push (parse->srcpad, buffer);
2328 GST_LOG_OBJECT (parse, "frame pushed, flow %s",
2329 gst_flow_get_name (ret));
2331 GST_LOG_OBJECT (parse,
2332 "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s", size,
2333 gst_flow_get_name (ret));
2334 gst_buffer_unref (buffer);
2338 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) queued for now",
2340 parse->priv->buffers_queued =
2341 g_slist_prepend (parse->priv->buffers_queued, buffer);
2345 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s",
2346 size, gst_flow_get_name (ret));
2347 gst_buffer_unref (buffer);
2348 /* if we are not sufficiently in control, let upstream decide on EOS */
2349 if (ret == GST_FLOW_EOS && !parse->priv->disable_passthrough &&
2350 (parse->priv->passthrough ||
2351 (parse->priv->pad_mode == GST_PAD_MODE_PUSH &&
2352 !parse->priv->upstream_seekable)))
2356 /* Update current running segment position */
2357 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
2358 parse->segment.position < last_stop)
2359 parse->segment.position = last_stop;
2366 if (GST_PAD_IS_FLUSHING (parse->srcpad))
2367 return GST_FLOW_FLUSHING;
2369 GST_ELEMENT_ERROR (parse, STREAM, DECODE, ("No caps set"), (NULL));
2370 return GST_FLOW_ERROR;
2375 * gst_base_parse_finish_frame:
2376 * @parse: a #GstBaseParse
2377 * @frame: a #GstBaseParseFrame
2378 * @size: consumed input data represented by frame
2380 * Collects parsed data and pushes this downstream.
2381 * Source pad caps must be set when this is called.
2383 * If @frame's out_buffer is set, that will be used as subsequent frame data.
2384 * Otherwise, @size samples will be taken from the input and used for output,
2385 * and the output's metadata (timestamps etc) will be taken as (optionally)
2386 * set by the subclass on @frame's (input) buffer (which is otherwise
2387 * ignored for any but the above purpose/information).
2389 * Note that the latter buffer is invalidated by this call, whereas the
2390 * caller retains ownership of @frame.
2392 * Returns: a #GstFlowReturn that should be escalated to caller (of caller)
2395 gst_base_parse_finish_frame (GstBaseParse * parse, GstBaseParseFrame * frame,
2398 GstFlowReturn ret = GST_FLOW_OK;
2400 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2401 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
2402 g_return_val_if_fail (size > 0 || frame->out_buffer, GST_FLOW_ERROR);
2403 g_return_val_if_fail (gst_adapter_available (parse->priv->adapter) >= size,
2406 GST_LOG_OBJECT (parse, "finished frame at offset %" G_GUINT64_FORMAT ", "
2407 "flushing size %d", frame->offset, size);
2409 /* some one-time start-up */
2410 if (G_UNLIKELY (parse->priv->framecount == 0)) {
2411 gst_base_parse_check_seekability (parse);
2412 gst_base_parse_check_upstream (parse);
2415 parse->priv->flushed += size;
2417 if (parse->priv->scanning && frame->buffer) {
2418 if (!parse->priv->scanned_frame) {
2419 parse->priv->scanned_frame = gst_base_parse_frame_copy (frame);
2424 /* either PUSH or PULL mode arranges for adapter data */
2425 /* ensure output buffer */
2426 if (!frame->out_buffer) {
2427 GstBuffer *src, *dest;
2429 frame->out_buffer = gst_adapter_take_buffer (parse->priv->adapter, size);
2430 dest = frame->out_buffer;
2431 src = frame->buffer;
2432 GST_BUFFER_PTS (dest) = GST_BUFFER_PTS (src);
2433 GST_BUFFER_DTS (dest) = GST_BUFFER_DTS (src);
2434 GST_BUFFER_OFFSET (dest) = GST_BUFFER_OFFSET (src);
2435 GST_BUFFER_DURATION (dest) = GST_BUFFER_DURATION (src);
2436 GST_BUFFER_OFFSET_END (dest) = GST_BUFFER_OFFSET_END (src);
2437 GST_MINI_OBJECT_FLAGS (dest) = GST_MINI_OBJECT_FLAGS (src);
2439 gst_adapter_flush (parse->priv->adapter, size);
2442 /* use as input for subsequent processing */
2443 gst_buffer_replace (&frame->buffer, frame->out_buffer);
2444 gst_buffer_unref (frame->out_buffer);
2445 frame->out_buffer = NULL;
2447 /* mark input size consumed */
2450 /* subclass might queue frames/data internally if it needs more
2451 * frames to decide on the format, or might request us to queue here. */
2452 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_DROP) {
2453 gst_buffer_replace (&frame->buffer, NULL);
2455 } else if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_QUEUE) {
2456 GstBaseParseFrame *copy;
2458 copy = gst_base_parse_frame_copy (frame);
2459 copy->flags &= ~GST_BASE_PARSE_FRAME_FLAG_QUEUE;
2460 gst_base_parse_queue_frame (parse, copy);
2464 ret = gst_base_parse_handle_and_push_frame (parse, frame);
2470 /* gst_base_parse_drain:
2472 * Drains the adapter until it is empty. It decreases the min_frame_size to
2473 * match the current adapter size and calls chain method until the adapter
2474 * is emptied or chain returns with error.
2477 gst_base_parse_drain (GstBaseParse * parse)
2481 GST_DEBUG_OBJECT (parse, "draining");
2482 parse->priv->drain = TRUE;
2485 avail = gst_adapter_available (parse->priv->adapter);
2489 if (gst_base_parse_chain (parse->sinkpad, GST_OBJECT_CAST (parse),
2490 NULL) != GST_FLOW_OK) {
2494 /* nothing changed, maybe due to truncated frame; break infinite loop */
2495 if (avail == gst_adapter_available (parse->priv->adapter)) {
2496 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
2497 gst_adapter_clear (parse->priv->adapter);
2501 parse->priv->drain = FALSE;
2504 /* gst_base_parse_send_buffers
2506 * Sends buffers collected in send_buffers downstream, and ensures that list
2507 * is empty at the end (errors or not).
2509 static GstFlowReturn
2510 gst_base_parse_send_buffers (GstBaseParse * parse)
2512 GSList *send = NULL;
2514 GstFlowReturn ret = GST_FLOW_OK;
2515 gboolean first = TRUE;
2517 send = parse->priv->buffers_send;
2521 buf = GST_BUFFER_CAST (send->data);
2522 GST_LOG_OBJECT (parse, "pushing buffer %p, dts %"
2523 GST_TIME_FORMAT ", pts %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2524 ", offset %" G_GINT64_FORMAT, buf,
2525 GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
2526 GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
2527 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2529 /* Make sure the first buffer is always DISCONT. If we split
2530 * GOPs inside the parser this is otherwise not guaranteed */
2532 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
2536 /* iterate output queue an push downstream */
2537 ret = gst_pad_push (parse->srcpad, buf);
2538 send = g_slist_delete_link (send, send);
2540 /* clear any leftover if error */
2541 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2543 buf = GST_BUFFER_CAST (send->data);
2544 gst_buffer_unref (buf);
2545 send = g_slist_delete_link (send, send);
2550 parse->priv->buffers_send = send;
2555 /* gst_base_parse_start_fragment:
2557 * Prepares for processing a reverse playback (forward) fragment
2558 * by (re)setting proper state variables.
2560 static GstFlowReturn
2561 gst_base_parse_start_fragment (GstBaseParse * parse)
2563 GST_LOG_OBJECT (parse, "starting fragment");
2565 /* invalidate so no fall-back timestamping is performed;
2566 * ok if taken from subclass or upstream */
2567 parse->priv->next_pts = GST_CLOCK_TIME_NONE;
2568 parse->priv->prev_pts = GST_CLOCK_TIME_NONE;
2569 parse->priv->next_dts = GST_CLOCK_TIME_NONE;
2570 parse->priv->prev_dts = GST_CLOCK_TIME_NONE;
2571 /* prevent it hanging around stop all the time */
2572 parse->segment.position = GST_CLOCK_TIME_NONE;
2574 parse->priv->discont = TRUE;
2576 /* head of previous fragment is now pending tail of current fragment */
2577 parse->priv->buffers_pending = parse->priv->buffers_head;
2578 parse->priv->buffers_head = NULL;
2584 /* gst_base_parse_finish_fragment:
2586 * Processes a reverse playback (forward) fragment:
2587 * - append head of last fragment that was skipped to current fragment data
2588 * - drain the resulting current fragment data (i.e. repeated chain)
2589 * - add time/duration (if needed) to frames queued by chain
2590 * - push queued data
2592 static GstFlowReturn
2593 gst_base_parse_finish_fragment (GstBaseParse * parse, gboolean prev_head)
2596 GstFlowReturn ret = GST_FLOW_OK;
2597 gboolean seen_key = FALSE, seen_delta = FALSE;
2599 GST_LOG_OBJECT (parse, "finishing fragment");
2602 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2603 while (parse->priv->buffers_pending) {
2604 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2606 GST_LOG_OBJECT (parse, "adding pending buffer (size %" G_GSIZE_FORMAT ")",
2607 gst_buffer_get_size (buf));
2608 gst_adapter_push (parse->priv->adapter, buf);
2610 GST_LOG_OBJECT (parse, "discarding head buffer");
2611 gst_buffer_unref (buf);
2613 parse->priv->buffers_pending =
2614 g_slist_delete_link (parse->priv->buffers_pending,
2615 parse->priv->buffers_pending);
2618 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2619 /* initial skipped data is added to buffers_pending */
2620 gst_base_parse_drain (parse);
2622 if (parse->priv->buffers_send) {
2623 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2624 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2627 /* add metadata (if needed to queued buffers */
2628 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2629 GST_TIME_ARGS (parse->priv->last_pts));
2630 while (parse->priv->buffers_queued) {
2631 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2633 /* no touching if upstream or parsing provided time */
2634 if (GST_BUFFER_PTS_IS_VALID (buf)) {
2635 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2636 GST_TIME_ARGS (GST_BUFFER_PTS (buf)));
2637 } else if (GST_BUFFER_DURATION_IS_VALID (buf)) {
2638 if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_pts)) {
2639 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_pts))
2640 parse->priv->last_pts -= GST_BUFFER_DURATION (buf);
2642 parse->priv->last_pts = 0;
2643 GST_BUFFER_PTS (buf) = parse->priv->last_pts;
2644 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2645 GST_TIME_ARGS (GST_BUFFER_PTS (buf)));
2647 if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_dts)) {
2648 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_dts))
2649 parse->priv->last_dts -= GST_BUFFER_DURATION (buf);
2651 parse->priv->last_dts = 0;
2652 GST_BUFFER_DTS (buf) = parse->priv->last_dts;
2653 GST_LOG_OBJECT (parse, "applied dts %" GST_TIME_FORMAT,
2654 GST_TIME_ARGS (GST_BUFFER_DTS (buf)));
2657 /* no idea, very bad */
2658 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2661 parse->priv->last_pts = GST_BUFFER_PTS (buf);
2662 parse->priv->last_dts = GST_BUFFER_DTS (buf);
2664 /* reverse order for ascending sending */
2665 /* send downstream at keyframe not preceded by a keyframe
2666 * (e.g. that should identify start of collection of IDR nals) */
2667 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2669 ret = gst_base_parse_send_buffers (parse);
2670 /* if a problem, throw all to sending */
2671 if (ret != GST_FLOW_OK) {
2672 parse->priv->buffers_send =
2673 g_slist_reverse (parse->priv->buffers_queued);
2674 parse->priv->buffers_queued = NULL;
2684 parse->priv->buffers_send =
2685 g_slist_prepend (parse->priv->buffers_send, buf);
2686 parse->priv->buffers_queued =
2687 g_slist_delete_link (parse->priv->buffers_queued,
2688 parse->priv->buffers_queued);
2691 /* audio may have all marked as keyframe, so arrange to send here. Also
2692 * we might have ended the loop above on a keyframe, in which case we
2694 if (!seen_delta || seen_key)
2695 ret = gst_base_parse_send_buffers (parse);
2697 /* any trailing unused no longer usable (ideally none) */
2698 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2699 GST_DEBUG_OBJECT (parse, "discarding %" G_GSIZE_FORMAT " trailing bytes",
2700 gst_adapter_available (parse->priv->adapter));
2701 gst_adapter_clear (parse->priv->adapter);
2707 /* small helper that checks whether we have been trying to resync too long */
2708 static inline GstFlowReturn
2709 gst_base_parse_check_sync (GstBaseParse * parse)
2711 if (G_UNLIKELY (parse->priv->discont &&
2712 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2713 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2714 ("Failed to parse stream"), (NULL));
2715 return GST_FLOW_ERROR;
2721 static GstFlowReturn
2722 gst_base_parse_process_streamheader (GstBaseParse * parse)
2726 const GValue *value;
2727 GstFlowReturn ret = GST_FLOW_OK;
2729 caps = gst_pad_get_current_caps (GST_BASE_PARSE_SINK_PAD (parse));
2733 str = gst_caps_get_structure (caps, 0);
2734 value = gst_structure_get_value (str, "streamheader");
2738 GST_DEBUG_OBJECT (parse, "Found streamheader field on input caps");
2740 if (GST_VALUE_HOLDS_ARRAY (value)) {
2742 gsize len = gst_value_array_get_size (value);
2744 for (i = 0; i < len; i++) {
2746 gst_value_get_buffer (gst_value_array_get_value (value, i));
2748 gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2749 GST_OBJECT_CAST (parse), gst_buffer_ref (buffer));
2752 } else if (GST_VALUE_HOLDS_BUFFER (value)) {
2753 GstBuffer *buffer = gst_value_get_buffer (value);
2755 gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2756 GST_OBJECT_CAST (parse), gst_buffer_ref (buffer));
2763 GST_DEBUG_OBJECT (parse, "No streamheader on caps");
2768 static GstFlowReturn
2769 gst_base_parse_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2771 GstBaseParseClass *bclass;
2772 GstBaseParse *parse;
2773 GstFlowReturn ret = GST_FLOW_OK;
2774 GstFlowReturn old_ret = GST_FLOW_OK;
2775 GstBuffer *tmpbuf = NULL;
2780 GstClockTime pts, dts;
2782 parse = GST_BASE_PARSE (parent);
2783 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2785 if (G_UNLIKELY (parse->priv->first_buffer)) {
2786 parse->priv->first_buffer = FALSE;
2787 if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_HEADER)) {
2788 /* this stream has no header buffers, check if we just prepend the
2789 * streamheader from caps to the stream */
2790 GST_DEBUG_OBJECT (parse, "Looking for streamheader field on caps to "
2791 "prepend to the stream");
2792 gst_base_parse_process_streamheader (parse);
2794 GST_DEBUG_OBJECT (parse, "Stream has header buffers, not prepending "
2795 "streamheader from caps");
2799 if (parse->priv->detecting) {
2800 GstBuffer *detect_buf;
2802 if (parse->priv->detect_buffers_size == 0) {
2803 detect_buf = gst_buffer_ref (buffer);
2808 detect_buf = gst_buffer_new ();
2810 for (l = parse->priv->detect_buffers; l; l = l->next) {
2811 gsize tmpsize = gst_buffer_get_size (l->data);
2813 gst_buffer_copy_into (detect_buf, GST_BUFFER_CAST (l->data),
2814 GST_BUFFER_COPY_MEMORY, offset, tmpsize);
2818 gst_buffer_copy_into (detect_buf, buffer, GST_BUFFER_COPY_MEMORY,
2819 offset, gst_buffer_get_size (buffer));
2822 ret = bclass->detect (parse, detect_buf);
2823 gst_buffer_unref (detect_buf);
2825 if (ret == GST_FLOW_OK) {
2828 /* Detected something */
2829 parse->priv->detecting = FALSE;
2831 for (l = parse->priv->detect_buffers; l; l = l->next) {
2832 if (ret == GST_FLOW_OK && !parse->priv->flushing)
2834 gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2835 parent, GST_BUFFER_CAST (l->data));
2837 gst_buffer_unref (GST_BUFFER_CAST (l->data));
2839 g_list_free (parse->priv->detect_buffers);
2840 parse->priv->detect_buffers = NULL;
2841 parse->priv->detect_buffers_size = 0;
2843 if (ret != GST_FLOW_OK) {
2847 /* Handle the current buffer */
2848 } else if (ret == GST_FLOW_NOT_NEGOTIATED) {
2849 /* Still detecting, append buffer or error out if draining */
2851 if (parse->priv->drain) {
2852 GST_DEBUG_OBJECT (parse, "Draining but did not detect format yet");
2853 return GST_FLOW_ERROR;
2854 } else if (parse->priv->flushing) {
2855 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref,
2857 g_list_free (parse->priv->detect_buffers);
2858 parse->priv->detect_buffers = NULL;
2859 parse->priv->detect_buffers_size = 0;
2861 parse->priv->detect_buffers =
2862 g_list_append (parse->priv->detect_buffers, buffer);
2863 parse->priv->detect_buffers_size += gst_buffer_get_size (buffer);
2867 /* Something went wrong, subclass responsible for error reporting */
2871 /* And now handle the current buffer if detection worked */
2874 if (G_LIKELY (buffer)) {
2875 GST_LOG_OBJECT (parse,
2876 "buffer size: %" G_GSIZE_FORMAT ", offset = %" G_GINT64_FORMAT
2877 ", dts %" GST_TIME_FORMAT ", pts %" GST_TIME_FORMAT,
2878 gst_buffer_get_size (buffer), GST_BUFFER_OFFSET (buffer),
2879 GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
2880 GST_TIME_ARGS (GST_BUFFER_PTS (buffer)));
2882 if (G_UNLIKELY (!parse->priv->disable_passthrough
2883 && parse->priv->passthrough)) {
2884 GstBaseParseFrame frame;
2886 gst_base_parse_frame_init (&frame);
2887 frame.buffer = gst_buffer_make_writable (buffer);
2888 ret = gst_base_parse_push_frame (parse, &frame);
2889 gst_base_parse_frame_free (&frame);
2892 /* upstream feeding us in reverse playback;
2893 * finish previous fragment and start new upon DISCONT */
2894 if (parse->segment.rate < 0.0) {
2895 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2896 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2897 ret = gst_base_parse_finish_fragment (parse, TRUE);
2898 gst_base_parse_start_fragment (parse);
2901 gst_adapter_push (parse->priv->adapter, buffer);
2904 /* Parse and push as many frames as possible */
2905 /* Stop either when adapter is empty or we are flushing */
2906 while (!parse->priv->flushing) {
2909 /* note: if subclass indicates MAX fsize,
2910 * this will not likely be available anyway ... */
2911 min_size = MAX (parse->priv->min_frame_size, fsize);
2912 av = gst_adapter_available (parse->priv->adapter);
2914 if (G_UNLIKELY (parse->priv->drain)) {
2916 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2917 if (G_UNLIKELY (!min_size)) {
2922 /* Collect at least min_frame_size bytes */
2923 if (av < min_size) {
2924 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)", av);
2928 /* move along with upstream timestamp (if any),
2929 * but interpolate in between */
2930 pts = gst_adapter_prev_pts (parse->priv->adapter, NULL);
2931 dts = gst_adapter_prev_dts (parse->priv->adapter, NULL);
2932 if (GST_CLOCK_TIME_IS_VALID (pts) && (parse->priv->prev_pts != pts))
2933 parse->priv->prev_pts = parse->priv->next_pts = pts;
2935 if (GST_CLOCK_TIME_IS_VALID (dts) && (parse->priv->prev_dts != dts))
2936 parse->priv->prev_dts = parse->priv->next_dts = dts;
2938 /* we can mess with, erm interpolate, timestamps,
2939 * and incoming stuff has PTS but no DTS seen so far,
2940 * then pick up DTS from PTS and hope for the best ... */
2941 if (parse->priv->infer_ts &&
2942 parse->priv->pts_interpolate &&
2943 !GST_CLOCK_TIME_IS_VALID (dts) &&
2944 !GST_CLOCK_TIME_IS_VALID (parse->priv->prev_dts) &&
2945 GST_CLOCK_TIME_IS_VALID (pts))
2946 parse->priv->next_dts = pts;
2948 /* always pass all available data */
2949 data = gst_adapter_map (parse->priv->adapter, av);
2950 /* arrange for actual data to be copied if subclass tries to,
2951 * since what is passed is tied to the adapter */
2952 tmpbuf = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY |
2953 GST_MEMORY_FLAG_NO_SHARE, (gpointer) data, av, 0, av, NULL, NULL);
2955 /* already inform subclass what timestamps we have planned,
2956 * at least if provided by time-based upstream */
2957 if (parse->priv->upstream_format == GST_FORMAT_TIME) {
2958 GST_BUFFER_PTS (tmpbuf) = parse->priv->next_pts;
2959 GST_BUFFER_DTS (tmpbuf) = parse->priv->next_dts;
2962 /* keep the adapter mapped, so keep track of what has to be flushed */
2963 ret = gst_base_parse_handle_buffer (parse, tmpbuf, &skip, &flush);
2966 /* probably already implicitly unmapped due to adapter operation,
2967 * but for good measure ... */
2968 gst_adapter_unmap (parse->priv->adapter);
2969 if (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED) {
2972 if (skip == 0 && flush == 0) {
2973 GST_LOG_OBJECT (parse, "nothing skipped and no frames finished, "
2974 "breaking to get more data");
2975 /* ignore this return as it produced no data */
2983 GST_LOG_OBJECT (parse, "chain leaving");
2987 /* pull @size bytes at current offset,
2988 * i.e. at least try to and possibly return a shorter buffer if near the end */
2989 static GstFlowReturn
2990 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2991 GstBuffer ** buffer)
2993 GstFlowReturn ret = GST_FLOW_OK;
2995 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2997 /* Caching here actually makes much less difference than one would expect.
2998 * We do it mainly to avoid pulling buffers of 1 byte all the time */
2999 if (parse->priv->cache) {
3000 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
3001 gint cache_size = gst_buffer_get_size (parse->priv->cache);
3003 if (cache_offset <= parse->priv->offset &&
3004 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
3005 *buffer = gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL,
3006 parse->priv->offset - cache_offset, size);
3007 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
3010 /* not enough data in the cache, free cache and get a new one */
3011 gst_buffer_unref (parse->priv->cache);
3012 parse->priv->cache = NULL;
3015 /* refill the cache */
3017 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
3018 64 * 1024), &parse->priv->cache);
3019 if (ret != GST_FLOW_OK) {
3020 parse->priv->cache = NULL;
3024 if (gst_buffer_get_size (parse->priv->cache) >= size) {
3026 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0,
3028 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
3032 /* Not possible to get enough data, try a last time with
3033 * requesting exactly the size we need */
3034 gst_buffer_unref (parse->priv->cache);
3035 parse->priv->cache = NULL;
3037 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
3038 &parse->priv->cache);
3040 if (ret != GST_FLOW_OK) {
3041 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
3046 if (gst_buffer_get_size (parse->priv->cache) < size) {
3047 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
3048 G_GUINT64_FORMAT ": wanted %u bytes, got %" G_GSIZE_FORMAT " bytes",
3049 parse->priv->offset, size, gst_buffer_get_size (parse->priv->cache));
3051 *buffer = parse->priv->cache;
3052 parse->priv->cache = NULL;
3058 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0, size);
3059 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
3064 static GstFlowReturn
3065 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
3068 GstClockTime ts = 0;
3072 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
3073 ", last_offset = %" G_GINT64_FORMAT,
3074 GST_TIME_ARGS (parse->priv->last_pts), parse->priv->last_offset);
3076 if (!parse->priv->last_offset
3077 || parse->priv->last_pts <= parse->segment.start) {
3078 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
3079 GST_TIME_ARGS (parse->segment.start));
3084 /* last fragment started at last_offset / last_ts;
3085 * seek back 10s capped at 1MB */
3086 if (parse->priv->last_pts >= 10 * GST_SECOND)
3087 ts = parse->priv->last_pts - 10 * GST_SECOND;
3088 /* if we are exact now, we will be more so going backwards */
3089 if (parse->priv->exact_position) {
3090 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
3092 if (!gst_base_parse_convert (parse, GST_FORMAT_TIME, ts,
3093 GST_FORMAT_BYTES, &offset)) {
3094 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
3097 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
3098 parse->priv->last_offset - 1024);
3099 offset = MAX (0, offset);
3101 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
3103 parse->priv->offset = offset;
3105 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
3107 if (ret != GST_FLOW_OK)
3110 /* offset will increase again as fragment is processed/parsed */
3111 parse->priv->last_offset = offset;
3113 gst_base_parse_start_fragment (parse);
3114 gst_adapter_push (parse->priv->adapter, buffer);
3115 ret = gst_base_parse_finish_fragment (parse, TRUE);
3116 if (ret != GST_FLOW_OK)
3119 /* force previous fragment */
3120 parse->priv->offset = -1;
3127 * pull and scan for next frame starting from current offset
3128 * ajusts sync, drain and offset going along */
3129 static GstFlowReturn
3130 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass)
3133 GstFlowReturn ret = GST_FLOW_OK;
3134 guint fsize, min_size;
3138 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
3139 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
3141 /* let's make this efficient for all subclass once and for all;
3142 * maybe it does not need this much, but in the latter case, we know we are
3143 * in pull mode here and might as well try to read and supply more anyway
3144 * (so does the buffer caching mechanism) */
3148 min_size = MAX (parse->priv->min_frame_size, fsize);
3150 GST_LOG_OBJECT (parse, "reading buffer size %u", min_size);
3152 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
3153 if (ret != GST_FLOW_OK)
3156 /* if we got a short read, inform subclass we are draining leftover
3157 * and no more is to be expected */
3158 if (gst_buffer_get_size (buffer) < min_size) {
3159 GST_LOG_OBJECT (parse, "... but did not get that; marked draining");
3160 parse->priv->drain = TRUE;
3163 if (parse->priv->detecting) {
3164 ret = klass->detect (parse, buffer);
3165 if (ret == GST_FLOW_NOT_NEGOTIATED) {
3166 /* If draining we error out, otherwise request a buffer
3168 if (parse->priv->drain) {
3169 gst_buffer_unref (buffer);
3170 GST_ERROR_OBJECT (parse, "Failed to detect format but draining");
3171 return GST_FLOW_ERROR;
3174 gst_buffer_unref (buffer);
3177 } else if (ret != GST_FLOW_OK) {
3178 gst_buffer_unref (buffer);
3179 GST_ERROR_OBJECT (parse, "detect() returned %s",
3180 gst_flow_get_name (ret));
3184 /* Else handle this buffer normally */
3187 ret = gst_base_parse_handle_buffer (parse, buffer, &skip, &flushed);
3188 if (ret != GST_FLOW_OK)
3191 /* something flushed means something happened,
3192 * and we should bail out of this loop so as not to occupy
3193 * the task thread indefinitely */
3195 GST_LOG_OBJECT (parse, "frame finished, breaking loop");
3198 /* nothing flushed, no skip and draining, so nothing left to do */
3199 if (!skip && parse->priv->drain) {
3200 GST_LOG_OBJECT (parse, "no activity or result when draining; "
3201 "breaking loop and marking EOS");
3205 /* otherwise, get some more data
3206 * note that is checked this does not happen indefinitely */
3208 GST_LOG_OBJECT (parse, "getting some more data");
3211 parse->priv->drain = FALSE;
3218 /* Loop that is used in pull mode to retrieve data from upstream */
3220 gst_base_parse_loop (GstPad * pad)
3222 GstBaseParse *parse;
3223 GstBaseParseClass *klass;
3224 GstFlowReturn ret = GST_FLOW_OK;
3226 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
3227 klass = GST_BASE_PARSE_GET_CLASS (parse);
3229 GST_LOG_OBJECT (parse, "Entering parse loop");
3231 if (G_UNLIKELY (parse->priv->push_stream_start)) {
3236 gst_pad_create_stream_id (parse->srcpad, GST_ELEMENT_CAST (parse),
3239 event = gst_event_new_stream_start (stream_id);
3240 gst_event_set_group_id (event, gst_util_group_id_next ());
3242 GST_DEBUG_OBJECT (parse, "Pushing STREAM_START");
3243 gst_pad_push_event (parse->srcpad, event);
3244 parse->priv->push_stream_start = FALSE;
3248 /* reverse playback:
3249 * first fragment (closest to stop time) is handled normally below,
3250 * then we pull in fragments going backwards */
3251 if (parse->segment.rate < 0.0) {
3252 /* check if we jumped back to a previous fragment,
3253 * which is a post-first fragment */
3254 if (parse->priv->offset < 0) {
3255 ret = gst_base_parse_handle_previous_fragment (parse);
3260 ret = gst_base_parse_scan_frame (parse, klass);
3261 if (ret != GST_FLOW_OK)
3264 /* eat expected eos signalling past segment in reverse playback */
3265 if (parse->segment.rate < 0.0 && ret == GST_FLOW_EOS &&
3266 parse->segment.position >= parse->segment.stop) {
3267 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
3268 /* push what was accumulated during loop run */
3269 gst_base_parse_finish_fragment (parse, FALSE);
3270 /* force previous fragment */
3271 parse->priv->offset = -1;
3276 if (ret == GST_FLOW_EOS)
3278 else if (ret != GST_FLOW_OK)
3281 gst_object_unref (parse);
3288 GST_DEBUG_OBJECT (parse, "eos");
3293 gboolean push_eos = FALSE;
3295 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
3296 gst_flow_get_name (ret));
3297 gst_pad_pause_task (parse->sinkpad);
3299 if (ret == GST_FLOW_EOS) {
3300 /* handle end-of-stream/segment */
3301 if (parse->segment.flags & GST_SEGMENT_FLAG_SEGMENT) {
3304 if ((stop = parse->segment.stop) == -1)
3305 stop = parse->segment.duration;
3307 GST_DEBUG_OBJECT (parse, "sending segment_done");
3309 gst_element_post_message
3310 (GST_ELEMENT_CAST (parse),
3311 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
3312 GST_FORMAT_TIME, stop));
3313 gst_pad_push_event (parse->srcpad,
3314 gst_event_new_segment_done (GST_FORMAT_TIME, stop));
3316 /* If we STILL have zero frames processed, fire an error */
3317 if (parse->priv->framecount == 0) {
3318 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
3319 ("No valid frames found before end of stream"), (NULL));
3323 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
3324 /* for fatal errors we post an error message, wrong-state is
3325 * not fatal because it happens due to flushes and only means
3326 * that we should stop now. */
3327 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
3328 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
3332 /* Push pending events, including SEGMENT events */
3333 gst_base_parse_push_pending_events (parse);
3335 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
3337 gst_object_unref (parse);
3342 gst_base_parse_sink_activate (GstPad * sinkpad, GstObject * parent)
3344 GstSchedulingFlags sched_flags;
3345 GstBaseParse *parse;
3349 parse = GST_BASE_PARSE (parent);
3351 GST_DEBUG_OBJECT (parse, "sink activate");
3353 query = gst_query_new_scheduling ();
3354 if (!gst_pad_peer_query (sinkpad, query)) {
3355 gst_query_unref (query);
3356 goto baseparse_push;
3359 gst_query_parse_scheduling (query, &sched_flags, NULL, NULL, NULL);
3361 pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL)
3362 && ((sched_flags & GST_SCHEDULING_FLAG_SEEKABLE) != 0);
3364 gst_query_unref (query);
3367 goto baseparse_push;
3369 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
3370 if (!gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE))
3371 goto baseparse_push;
3373 parse->priv->push_stream_start = TRUE;
3375 return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
3380 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
3381 return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
3386 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
3388 GstBaseParseClass *klass;
3389 gboolean result = TRUE;
3391 GST_DEBUG_OBJECT (parse, "activate %d", active);
3393 klass = GST_BASE_PARSE_GET_CLASS (parse);
3396 if (parse->priv->pad_mode == GST_PAD_MODE_NONE && klass->start)
3397 result = klass->start (parse);
3399 /* If the subclass implements ::detect we want to
3400 * call it for the first buffers now */
3401 parse->priv->detecting = (klass->detect != NULL);
3403 /* We must make sure streaming has finished before resetting things
3404 * and calling the ::stop vfunc */
3405 GST_PAD_STREAM_LOCK (parse->sinkpad);
3406 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3408 if (parse->priv->pad_mode != GST_PAD_MODE_NONE && klass->stop)
3409 result = klass->stop (parse);
3411 parse->priv->pad_mode = GST_PAD_MODE_NONE;
3413 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
3418 gst_base_parse_sink_activate_mode (GstPad * pad, GstObject * parent,
3419 GstPadMode mode, gboolean active)
3422 GstBaseParse *parse;
3424 parse = GST_BASE_PARSE (parent);
3426 GST_DEBUG_OBJECT (parse, "sink %sactivate in %s mode",
3427 (active) ? "" : "de", gst_pad_mode_get_name (mode));
3429 if (!gst_base_parse_activate (parse, active))
3430 goto activate_failed;
3433 case GST_PAD_MODE_PULL:
3435 parse->priv->pending_events =
3436 g_list_prepend (parse->priv->pending_events,
3437 gst_event_new_segment (&parse->segment));
3440 result = gst_pad_stop_task (pad);
3448 parse->priv->pad_mode = active ? mode : GST_PAD_MODE_NONE;
3450 GST_DEBUG_OBJECT (parse, "sink activate return: %d", result);
3457 GST_DEBUG_OBJECT (parse, "activate failed");
3463 * gst_base_parse_set_duration:
3464 * @parse: #GstBaseParse.
3466 * @duration: duration value.
3467 * @interval: how often to update the duration estimate based on bitrate, or 0.
3469 * Sets the duration of the currently playing media. Subclass can use this
3470 * when it is able to determine duration and/or notices a change in the media
3471 * duration. Alternatively, if @interval is non-zero (default), then stream
3472 * duration is determined based on estimated bitrate, and updated every @interval
3476 gst_base_parse_set_duration (GstBaseParse * parse,
3477 GstFormat fmt, gint64 duration, gint interval)
3479 g_return_if_fail (parse != NULL);
3481 if (parse->priv->upstream_has_duration) {
3482 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
3486 if (duration != parse->priv->duration) {
3489 m = gst_message_new_duration_changed (GST_OBJECT (parse));
3490 gst_element_post_message (GST_ELEMENT (parse), m);
3492 /* TODO: what about duration tag? */
3494 parse->priv->duration = duration;
3495 parse->priv->duration_fmt = fmt;
3496 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
3497 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
3498 if (interval != 0) {
3499 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
3503 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
3504 parse->priv->update_interval = interval;
3510 * gst_base_parse_set_average_bitrate:
3511 * @parse: #GstBaseParse.
3512 * @bitrate: average bitrate in bits/second
3514 * Optionally sets the average bitrate detected in media (if non-zero),
3515 * e.g. based on metadata, as it will be posted to the application.
3517 * By default, announced average bitrate is estimated. The average bitrate
3518 * is used to estimate the total duration of the stream and to estimate
3519 * a seek position, if there's no index and the format is syncable
3520 * (see gst_base_parse_set_syncable()).
3523 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
3525 parse->priv->bitrate = bitrate;
3526 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
3530 * gst_base_parse_set_min_frame_size:
3531 * @parse: #GstBaseParse.
3532 * @min_size: Minimum size of the data that this base class should give to
3535 * Subclass can use this function to tell the base class that it needs to
3536 * give at least #min_size buffers.
3539 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
3541 g_return_if_fail (parse != NULL);
3543 parse->priv->min_frame_size = min_size;
3544 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
3548 * gst_base_parse_set_frame_rate:
3549 * @parse: the #GstBaseParse to set
3550 * @fps_num: frames per second (numerator).
3551 * @fps_den: frames per second (denominator).
3552 * @lead_in: frames needed before a segment for subsequent decode
3553 * @lead_out: frames needed after a segment
3555 * If frames per second is configured, parser can take care of buffer duration
3556 * and timestamping. When performing segment clipping, or seeking to a specific
3557 * location, a corresponding decoder might need an initial @lead_in and a
3558 * following @lead_out number of frames to ensure the desired segment is
3559 * entirely filled upon decoding.
3562 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
3563 guint fps_den, guint lead_in, guint lead_out)
3565 g_return_if_fail (parse != NULL);
3567 parse->priv->fps_num = fps_num;
3568 parse->priv->fps_den = fps_den;
3569 if (!fps_num || !fps_den) {
3570 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
3572 fps_num = fps_den = 0;
3573 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
3574 parse->priv->lead_in = parse->priv->lead_out = 0;
3575 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
3577 parse->priv->frame_duration =
3578 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
3579 parse->priv->lead_in = lead_in;
3580 parse->priv->lead_out = lead_out;
3581 parse->priv->lead_in_ts =
3582 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
3583 parse->priv->lead_out_ts =
3584 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
3585 /* aim for about 1.5s to estimate duration */
3586 if (parse->priv->update_interval < 0) {
3587 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
3588 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
3589 parse->priv->update_interval);
3592 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
3593 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
3594 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
3595 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
3596 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
3597 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
3601 * gst_base_parse_set_has_timing_info:
3602 * @parse: a #GstBaseParse
3603 * @has_timing: whether frames carry timing information
3605 * Set if frames carry timing information which the subclass can (generally)
3606 * parse and provide. In particular, intrinsic (rather than estimated) time
3607 * can be obtained following a seek.
3610 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3612 parse->priv->has_timing_info = has_timing;
3613 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3617 * gst_base_parse_set_syncable:
3618 * @parse: a #GstBaseParse
3619 * @syncable: set if frame starts can be identified
3621 * Set if frame starts can be identified. This is set by default and
3622 * determines whether seeking based on bitrate averages
3623 * is possible for a format/stream.
3626 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3628 parse->priv->syncable = syncable;
3629 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3633 * gst_base_parse_set_passthrough:
3634 * @parse: a #GstBaseParse
3635 * @passthrough: %TRUE if parser should run in passthrough mode
3637 * Set if the nature of the format or configuration does not allow (much)
3638 * parsing, and the parser should operate in passthrough mode (which only
3639 * applies when operating in push mode). That is, incoming buffers are
3640 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3641 * callbacks will be invoked, but @pre_push_frame will still be invoked,
3642 * so subclass can perform as much or as little is appropriate for
3643 * passthrough semantics in @pre_push_frame.
3646 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3648 parse->priv->passthrough = passthrough;
3649 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3653 * gst_base_parse_set_pts_interpolation:
3654 * @parse: a #GstBaseParse
3655 * @pts_interpolate: %TRUE if parser should interpolate PTS timestamps
3657 * By default, the base class will guess PTS timestamps using a simple
3658 * interpolation (previous timestamp + duration), which is incorrect for
3659 * data streams with reordering, where PTS can go backward. Sub-classes
3660 * implementing such formats should disable PTS interpolation.
3663 gst_base_parse_set_pts_interpolation (GstBaseParse * parse,
3664 gboolean pts_interpolate)
3666 parse->priv->pts_interpolate = pts_interpolate;
3667 GST_INFO_OBJECT (parse, "PTS interpolation: %s",
3668 (pts_interpolate) ? "yes" : "no");
3672 * gst_base_parse_set_infer_ts:
3673 * @parse: a #GstBaseParse
3674 * @infer_ts: %TRUE if parser should infer DTS/PTS from each other
3676 * By default, the base class might try to infer PTS from DTS and vice
3677 * versa. While this is generally correct for audio data, it may not
3678 * be otherwise. Sub-classes implementing such formats should disable
3679 * timestamp inferring.
3682 gst_base_parse_set_infer_ts (GstBaseParse * parse, gboolean infer_ts)
3684 parse->priv->infer_ts = infer_ts;
3685 GST_INFO_OBJECT (parse, "TS inferring: %s", (infer_ts) ? "yes" : "no");
3689 * gst_base_parse_set_latency:
3690 * @parse: a #GstBaseParse
3691 * @min_latency: minimum parse latency
3692 * @max_latency: maximum parse latency
3694 * Sets the minimum and maximum (which may likely be equal) latency introduced
3695 * by the parsing process. If there is such a latency, which depends on the
3696 * particular parsing of the format, it typically corresponds to 1 frame duration.
3699 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3700 GstClockTime max_latency)
3702 GST_OBJECT_LOCK (parse);
3703 parse->priv->min_latency = min_latency;
3704 parse->priv->max_latency = max_latency;
3705 GST_OBJECT_UNLOCK (parse);
3706 GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3707 GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3708 GST_TIME_ARGS (max_latency));
3712 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3713 GstClockTime * duration)
3715 gboolean res = FALSE;
3717 g_return_val_if_fail (duration != NULL, FALSE);
3719 *duration = GST_CLOCK_TIME_NONE;
3720 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3721 GST_LOG_OBJECT (parse, "using provided duration");
3722 *duration = parse->priv->duration;
3724 } else if (parse->priv->duration != -1) {
3725 GST_LOG_OBJECT (parse, "converting provided duration");
3726 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3727 parse->priv->duration, format, (gint64 *) duration);
3728 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3729 GST_LOG_OBJECT (parse, "using estimated duration");
3730 *duration = parse->priv->estimated_duration;
3733 GST_LOG_OBJECT (parse, "cannot estimate duration");
3736 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3737 GST_TIME_ARGS (*duration));
3742 gst_base_parse_src_query_default (GstBaseParse * parse, GstQuery * query)
3744 gboolean res = FALSE;
3747 pad = GST_BASE_PARSE_SRC_PAD (parse);
3749 switch (GST_QUERY_TYPE (query)) {
3750 case GST_QUERY_POSITION:
3755 GST_DEBUG_OBJECT (parse, "position query");
3756 gst_query_parse_position (query, &format, NULL);
3758 /* try upstream first */
3759 res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
3761 /* Fall back on interpreting segment */
3762 GST_OBJECT_LOCK (parse);
3763 if (format == GST_FORMAT_BYTES) {
3764 dest_value = parse->priv->offset;
3766 } else if (format == parse->segment.format &&
3767 GST_CLOCK_TIME_IS_VALID (parse->segment.position)) {
3768 dest_value = gst_segment_to_stream_time (&parse->segment,
3769 parse->segment.format, parse->segment.position);
3772 GST_OBJECT_UNLOCK (parse);
3774 /* no precise result, upstream no idea either, then best estimate */
3775 /* priv->offset is updated in both PUSH/PULL modes */
3776 res = gst_base_parse_convert (parse,
3777 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3780 gst_query_set_position (query, format, dest_value);
3784 case GST_QUERY_DURATION:
3787 GstClockTime duration;
3789 GST_DEBUG_OBJECT (parse, "duration query");
3790 gst_query_parse_duration (query, &format, NULL);
3792 /* consult upstream */
3793 res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
3795 /* otherwise best estimate from us */
3797 res = gst_base_parse_get_duration (parse, format, &duration);
3799 gst_query_set_duration (query, format, duration);
3803 case GST_QUERY_SEEKING:
3806 GstClockTime duration = GST_CLOCK_TIME_NONE;
3807 gboolean seekable = FALSE;
3809 GST_DEBUG_OBJECT (parse, "seeking query");
3810 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3812 /* consult upstream */
3813 res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
3815 /* we may be able to help if in TIME */
3816 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3817 gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3818 /* already OK if upstream takes care */
3819 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3821 if (!(res && seekable)) {
3822 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3823 || duration == -1) {
3824 /* seekable if we still have a chance to get duration later on */
3826 parse->priv->upstream_seekable && parse->priv->update_interval;
3828 seekable = parse->priv->upstream_seekable;
3829 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3832 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3838 case GST_QUERY_FORMATS:
3839 gst_query_set_formatsv (query, 3, fmtlist);
3842 case GST_QUERY_CONVERT:
3844 GstFormat src_format, dest_format;
3845 gint64 src_value, dest_value;
3847 gst_query_parse_convert (query, &src_format, &src_value,
3848 &dest_format, &dest_value);
3850 res = gst_base_parse_convert (parse, src_format, src_value,
3851 dest_format, &dest_value);
3853 gst_query_set_convert (query, src_format, src_value,
3854 dest_format, dest_value);
3858 case GST_QUERY_LATENCY:
3860 if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3862 GstClockTime min_latency, max_latency;
3864 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3865 GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3866 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3867 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3869 GST_OBJECT_LOCK (parse);
3870 /* add our latency */
3871 if (min_latency != -1)
3872 min_latency += parse->priv->min_latency;
3873 if (max_latency != -1)
3874 max_latency += parse->priv->max_latency;
3875 GST_OBJECT_UNLOCK (parse);
3877 gst_query_set_latency (query, live, min_latency, max_latency);
3881 case GST_QUERY_SEGMENT:
3886 format = parse->segment.format;
3889 gst_segment_to_stream_time (&parse->segment, format,
3890 parse->segment.start);
3891 if ((stop = parse->segment.stop) == -1)
3892 stop = parse->segment.duration;
3894 stop = gst_segment_to_stream_time (&parse->segment, format, stop);
3896 gst_query_set_segment (query, parse->segment.rate, format, start, stop);
3901 res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
3907 /* scans for a cluster start from @pos,
3908 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3909 static GstFlowReturn
3910 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3911 GstClockTime * time, GstClockTime * duration)
3913 GstBaseParseClass *klass;
3915 gboolean orig_drain, orig_discont;
3916 GstFlowReturn ret = GST_FLOW_OK;
3917 GstBuffer *buf = NULL;
3918 GstBaseParseFrame *sframe = NULL;
3920 g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3921 g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3922 g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3924 klass = GST_BASE_PARSE_GET_CLASS (parse);
3926 *time = GST_CLOCK_TIME_NONE;
3927 *duration = GST_CLOCK_TIME_NONE;
3930 orig_offset = parse->priv->offset;
3931 orig_discont = parse->priv->discont;
3932 orig_drain = parse->priv->drain;
3934 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3935 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3937 /* jump elsewhere and locate next frame */
3938 parse->priv->offset = *pos;
3939 /* mark as scanning so frames don't get processed all the way */
3940 parse->priv->scanning = TRUE;
3941 ret = gst_base_parse_scan_frame (parse, klass);
3942 parse->priv->scanning = FALSE;
3943 /* retrieve frame found during scan */
3944 sframe = parse->priv->scanned_frame;
3945 parse->priv->scanned_frame = NULL;
3947 if (ret != GST_FLOW_OK || !sframe)
3950 /* get offset first, subclass parsing might dump other stuff in there */
3951 *pos = sframe->offset;
3952 buf = sframe->buffer;
3955 /* but it should provide proper time */
3956 *time = GST_BUFFER_TIMESTAMP (buf);
3957 *duration = GST_BUFFER_DURATION (buf);
3959 GST_LOG_OBJECT (parse,
3960 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3961 GST_TIME_ARGS (*time), *pos);
3965 gst_base_parse_frame_free (sframe);
3968 parse->priv->offset = orig_offset;
3969 parse->priv->discont = orig_discont;
3970 parse->priv->drain = orig_drain;
3975 /* bisect and scan through file for frame starting before @time,
3976 * returns OK and @time/@offset if found, NONE and/or error otherwise
3977 * If @time == G_MAXINT64, scan for duration ( == last frame) */
3978 static GstFlowReturn
3979 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3982 GstFlowReturn ret = GST_FLOW_OK;
3983 gint64 lpos, hpos, newpos;
3984 GstClockTime time, ltime, htime, newtime, dur;
3985 gboolean cont = TRUE;
3986 const GstClockTime tolerance = TARGET_DIFFERENCE;
3987 const guint chunk = 4 * 1024;
3989 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3990 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3992 GST_DEBUG_OBJECT (parse, "Bisecting for time %" GST_TIME_FORMAT,
3993 GST_TIME_ARGS (*_time));
3995 /* TODO also make keyframe aware if useful some day */
4010 /* do not know at first */
4012 *_time = GST_CLOCK_TIME_NONE;
4014 /* need initial positions; start and end */
4015 lpos = parse->priv->first_frame_offset;
4016 ltime = parse->priv->first_frame_pts;
4017 /* try other one if no luck */
4018 if (!GST_CLOCK_TIME_IS_VALID (ltime))
4019 ltime = parse->priv->first_frame_dts;
4020 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &htime)) {
4021 GST_DEBUG_OBJECT (parse, "Unknown time duration, cannot bisect");
4022 return GST_FLOW_ERROR;
4024 hpos = parse->priv->upstream_size;
4026 GST_DEBUG_OBJECT (parse,
4027 "Bisection initial bounds: bytes %" G_GINT64_FORMAT " %" G_GINT64_FORMAT
4028 ", times %" GST_TIME_FORMAT " %" GST_TIME_FORMAT, lpos, hpos,
4029 GST_TIME_ARGS (ltime), GST_TIME_ARGS (htime));
4031 /* check preconditions are satisfied;
4032 * start and end are needed, except for special case where we scan for
4033 * last frame to determine duration */
4034 if (parse->priv->pad_mode != GST_PAD_MODE_PULL || !hpos ||
4035 !GST_CLOCK_TIME_IS_VALID (ltime) ||
4036 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
4040 /* shortcut cases */
4043 } else if (time < ltime + tolerance) {
4047 } else if (time >= htime) {
4053 while (htime > ltime && cont) {
4054 GST_LOG_OBJECT (parse,
4055 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
4056 GST_TIME_ARGS (ltime));
4057 GST_LOG_OBJECT (parse,
4058 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
4059 GST_TIME_ARGS (htime));
4060 if (G_UNLIKELY (time == G_MAXINT64)) {
4062 } else if (G_LIKELY (hpos > lpos)) {
4064 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
4067 /* should mean lpos == hpos, since lpos <= hpos is invariant */
4069 /* we check this case once, but not forever, so break loop */
4074 newpos = CLAMP (newpos, lpos, hpos);
4075 GST_LOG_OBJECT (parse,
4076 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
4077 GST_TIME_ARGS (time), newpos);
4079 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
4080 if (ret == GST_FLOW_EOS) {
4081 /* heuristic HACK */
4082 hpos = MAX (lpos, hpos - chunk);
4084 } else if (ret != GST_FLOW_OK) {
4088 if (newtime == -1 || newpos == -1) {
4089 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
4093 if (G_UNLIKELY (time == G_MAXINT64)) {
4096 if (GST_CLOCK_TIME_IS_VALID (dur))
4099 } else if (newtime > time) {
4101 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
4103 } else if (newtime + tolerance > time) {
4104 /* close enough undershoot */
4108 } else if (newtime < ltime) {
4109 /* so a position beyond lpos resulted in earlier time than ltime ... */
4110 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
4113 /* undershoot too far */
4114 newpos += newpos == lpos ? chunk : 0;
4115 lpos = CLAMP (newpos, lpos, hpos);
4121 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
4122 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
4127 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
4128 gboolean before, GstClockTime * _ts)
4130 gint64 bytes = 0, ts = 0;
4131 GstIndexEntry *entry = NULL;
4133 if (time == GST_CLOCK_TIME_NONE) {
4139 GST_BASE_PARSE_INDEX_LOCK (parse);
4140 if (parse->priv->index) {
4141 /* Let's check if we have an index entry for that time */
4142 entry = gst_index_get_assoc_entry (parse->priv->index,
4143 parse->priv->index_id,
4144 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
4145 GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
4149 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
4150 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
4152 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
4153 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
4154 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
4156 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
4157 GST_TIME_ARGS (time));
4160 ts = GST_CLOCK_TIME_NONE;
4163 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4172 /* returns TRUE if seek succeeded */
4174 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
4179 GstSeekType start_type = GST_SEEK_TYPE_NONE, stop_type;
4180 gboolean flush, update, res = TRUE, accurate;
4181 gint64 start, stop, seekpos, seekstop;
4182 GstSegment seeksegment = { 0, };
4183 GstClockTime start_ts;
4185 GstEvent *segment_event;
4187 /* try upstream first, unless we're driving the streaming thread ourselves */
4188 if (parse->priv->pad_mode != GST_PAD_MODE_PULL) {
4189 res = gst_pad_push_event (parse->sinkpad, gst_event_ref (event));
4194 gst_event_parse_seek (event, &rate, &format, &flags,
4195 &start_type, &start, &stop_type, &stop);
4196 seqnum = gst_event_get_seqnum (event);
4198 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
4199 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
4200 GST_TIME_FORMAT, gst_format_get_name (format), rate,
4201 start_type, GST_TIME_ARGS (start), stop_type, GST_TIME_ARGS (stop));
4203 /* we can only handle TIME, so check if subclass can convert
4204 * to TIME format if it's some other format (such as DEFAULT) */
4205 if (format != GST_FORMAT_TIME) {
4206 if (!gst_base_parse_convert (parse, format, start, GST_FORMAT_TIME, &start)
4207 || !gst_base_parse_convert (parse, format, stop, GST_FORMAT_TIME,
4209 goto no_convert_to_time;
4211 GST_INFO_OBJECT (parse, "converted %s format to start time "
4212 "%" GST_TIME_FORMAT " and stop time %" GST_TIME_FORMAT,
4213 gst_format_get_name (format), GST_TIME_ARGS (start),
4214 GST_TIME_ARGS (stop));
4216 format = GST_FORMAT_TIME;
4219 /* no negative rates in push mode (unless upstream takes care of that, but
4220 * we've already tried upstream and it didn't handle the seek request) */
4221 if (rate < 0.0 && parse->priv->pad_mode == GST_PAD_MODE_PUSH)
4224 if (rate < 0.0 && parse->priv->pad_mode == GST_PAD_MODE_PULL)
4225 goto negative_rate_pull_mode;
4227 if (start_type != GST_SEEK_TYPE_SET ||
4228 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
4231 /* get flush flag */
4232 flush = flags & GST_SEEK_FLAG_FLUSH;
4234 /* copy segment, we need this because we still need the old
4235 * segment when we close the current segment. */
4236 gst_segment_copy_into (&parse->segment, &seeksegment);
4238 GST_DEBUG_OBJECT (parse, "configuring seek");
4239 gst_segment_do_seek (&seeksegment, rate, format, flags,
4240 start_type, start, stop_type, stop, &update);
4242 /* accurate seeking implies seek tables are used to obtain position,
4243 * and the requested segment is maintained exactly, not adjusted any way */
4244 accurate = flags & GST_SEEK_FLAG_ACCURATE;
4246 /* maybe we can be accurate for (almost) free */
4247 gst_base_parse_find_offset (parse, seeksegment.position, TRUE, &start_ts);
4248 if (seeksegment.position <= start_ts + TARGET_DIFFERENCE) {
4249 GST_DEBUG_OBJECT (parse, "accurate seek possible");
4253 GstClockTime startpos = seeksegment.position;
4255 /* accurate requested, so ... seek a bit before target */
4256 if (startpos < parse->priv->lead_in_ts)
4259 startpos -= parse->priv->lead_in_ts;
4260 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
4261 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
4264 start_ts = seeksegment.position;
4265 if (!gst_base_parse_convert (parse, format, seeksegment.position,
4266 GST_FORMAT_BYTES, &seekpos))
4267 goto convert_failed;
4268 if (!gst_base_parse_convert (parse, format, seeksegment.stop,
4269 GST_FORMAT_BYTES, &seekstop))
4270 goto convert_failed;
4273 GST_DEBUG_OBJECT (parse,
4274 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
4276 GST_DEBUG_OBJECT (parse,
4277 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
4278 seeksegment.stop, seekstop);
4280 if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
4283 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
4286 if (parse->srcpad) {
4287 GstEvent *fevent = gst_event_new_flush_start ();
4288 GST_DEBUG_OBJECT (parse, "sending flush start");
4290 gst_event_set_seqnum (fevent, seqnum);
4292 gst_pad_push_event (parse->srcpad, gst_event_ref (fevent));
4293 /* unlock upstream pull_range */
4294 gst_pad_push_event (parse->sinkpad, fevent);
4297 gst_pad_pause_task (parse->sinkpad);
4300 /* we should now be able to grab the streaming thread because we stopped it
4301 * with the above flush/pause code */
4302 GST_PAD_STREAM_LOCK (parse->sinkpad);
4304 /* save current position */
4305 last_stop = parse->segment.position;
4306 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
4309 /* now commit to new position */
4311 /* prepare for streaming again */
4313 GstEvent *fevent = gst_event_new_flush_stop (TRUE);
4314 GST_DEBUG_OBJECT (parse, "sending flush stop");
4315 gst_event_set_seqnum (fevent, seqnum);
4316 gst_pad_push_event (parse->srcpad, gst_event_ref (fevent));
4317 gst_pad_push_event (parse->sinkpad, fevent);
4318 gst_base_parse_clear_queues (parse);
4320 /* keep track of our position */
4321 seeksegment.base = gst_segment_to_running_time (&seeksegment,
4322 seeksegment.format, parse->segment.position);
4325 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
4327 /* store the newsegment event so it can be sent from the streaming thread. */
4328 /* This will be sent later in _loop() */
4329 segment_event = gst_event_new_segment (&parse->segment);
4330 gst_event_set_seqnum (segment_event, seqnum);
4331 parse->priv->pending_events =
4332 g_list_prepend (parse->priv->pending_events, segment_event);
4334 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
4335 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
4336 ", time = %" GST_TIME_FORMAT, format,
4337 GST_TIME_ARGS (parse->segment.start),
4338 GST_TIME_ARGS (parse->segment.stop),
4339 GST_TIME_ARGS (parse->segment.time));
4341 /* one last chance in pull mode to stay accurate;
4342 * maybe scan and subclass can find where to go */
4345 GstClockTime ts = seeksegment.position;
4347 gst_base_parse_locate_time (parse, &ts, &scanpos);
4351 /* running collected index now consists of several intervals,
4352 * so optimized check no longer possible */
4353 parse->priv->index_last_valid = FALSE;
4354 parse->priv->index_last_offset = 0;
4355 parse->priv->index_last_ts = 0;
4359 /* mark discont if we are going to stream from another position. */
4360 if (seekpos != parse->priv->offset) {
4361 GST_DEBUG_OBJECT (parse,
4362 "mark DISCONT, we did a seek to another position");
4363 parse->priv->offset = seekpos;
4364 parse->priv->last_offset = seekpos;
4365 parse->priv->seen_keyframe = FALSE;
4366 parse->priv->discont = TRUE;
4367 parse->priv->next_dts = start_ts;
4368 parse->priv->next_pts = GST_CLOCK_TIME_NONE;
4369 parse->priv->last_dts = GST_CLOCK_TIME_NONE;
4370 parse->priv->last_pts = GST_CLOCK_TIME_NONE;
4371 parse->priv->sync_offset = seekpos;
4372 parse->priv->exact_position = accurate;
4375 /* Start streaming thread if paused */
4376 gst_pad_start_task (parse->sinkpad,
4377 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad, NULL);
4379 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
4384 GstEvent *new_event;
4385 GstBaseParseSeek *seek;
4386 GstSeekFlags flags = (flush ? GST_SEEK_FLAG_FLUSH : GST_SEEK_FLAG_NONE);
4388 /* The only thing we need to do in PUSH-mode is to send the
4389 seek event (in bytes) to upstream. Segment / flush handling happens
4390 in corresponding src event handlers */
4391 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
4392 if (seekstop >= 0 && seekstop <= seekpos)
4394 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
4395 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
4396 gst_event_set_seqnum (new_event, seqnum);
4398 /* store segment info so its precise details can be reconstructed when
4399 * receiving newsegment;
4400 * this matters for all details when accurate seeking,
4401 * is most useful to preserve NONE stop time otherwise */
4402 seek = g_new0 (GstBaseParseSeek, 1);
4403 seek->segment = seeksegment;
4404 seek->accurate = accurate;
4405 seek->offset = seekpos;
4406 seek->start_ts = start_ts;
4407 GST_OBJECT_LOCK (parse);
4408 /* less optimal, but preserves order */
4409 parse->priv->pending_seeks =
4410 g_slist_append (parse->priv->pending_seeks, seek);
4411 GST_OBJECT_UNLOCK (parse);
4413 res = gst_pad_push_event (parse->sinkpad, new_event);
4416 GST_OBJECT_LOCK (parse);
4417 parse->priv->pending_seeks =
4418 g_slist_remove (parse->priv->pending_seeks, seek);
4419 GST_OBJECT_UNLOCK (parse);
4425 gst_event_unref (event);
4429 negative_rate_pull_mode:
4431 GST_FIXME_OBJECT (parse, "negative playback in pull mode needs fixing");
4437 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
4443 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
4449 GST_DEBUG_OBJECT (parse, "seek in %s format was requested, but subclass "
4450 "couldn't convert that into TIME format", gst_format_get_name (format));
4456 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
4462 /* Checks if bitrates are available from upstream tags so that we don't
4463 * override them later
4466 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
4468 GstTagList *taglist = NULL;
4471 gst_event_parse_tag (event, &taglist);
4473 /* We only care about stream tags here */
4474 if (gst_tag_list_get_scope (taglist) != GST_TAG_SCOPE_STREAM)
4477 if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
4478 GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
4479 parse->priv->post_min_bitrate = FALSE;
4481 if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
4482 GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
4483 parse->priv->post_avg_bitrate = FALSE;
4485 if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
4486 GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
4487 parse->priv->post_max_bitrate = FALSE;
4493 gst_base_parse_set_index (GstElement * element, GstIndex * index)
4495 GstBaseParse *parse = GST_BASE_PARSE (element);
4497 GST_BASE_PARSE_INDEX_LOCK (parse);
4498 if (parse->priv->index)
4499 gst_object_unref (parse->priv->index);
4501 parse->priv->index = gst_object_ref (index);
4502 gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
4503 &parse->priv->index_id);
4504 parse->priv->own_index = FALSE;
4506 parse->priv->index = NULL;
4508 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4512 gst_base_parse_get_index (GstElement * element)
4514 GstBaseParse *parse = GST_BASE_PARSE (element);
4515 GstIndex *result = NULL;
4517 GST_BASE_PARSE_INDEX_LOCK (parse);
4518 if (parse->priv->index)
4519 result = gst_object_ref (parse->priv->index);
4520 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4526 static GstStateChangeReturn
4527 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
4529 GstBaseParse *parse;
4530 GstStateChangeReturn result;
4532 parse = GST_BASE_PARSE (element);
4534 switch (transition) {
4535 case GST_STATE_CHANGE_READY_TO_PAUSED:
4536 /* If this is our own index destroy it as the
4537 * old entries might be wrong for the new stream */
4538 GST_BASE_PARSE_INDEX_LOCK (parse);
4539 if (parse->priv->own_index) {
4540 gst_object_unref (parse->priv->index);
4541 parse->priv->index = NULL;
4542 parse->priv->own_index = FALSE;
4545 /* If no index was created, generate one */
4546 if (G_UNLIKELY (!parse->priv->index)) {
4547 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
4549 parse->priv->index = g_object_new (gst_mem_index_get_type (), NULL);
4550 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
4551 &parse->priv->index_id);
4552 parse->priv->own_index = TRUE;
4554 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4560 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4562 switch (transition) {
4563 case GST_STATE_CHANGE_PAUSED_TO_READY:
4564 gst_base_parse_reset (parse);
4574 * gst_base_parse_set_ts_at_offset:
4575 * @parse: a #GstBaseParse
4576 * @offset: offset into current buffer
4578 * This function should only be called from a @handle_frame implementation.
4580 * #GstBaseParse creates initial timestamps for frames by using the last
4581 * timestamp seen in the stream before the frame starts. In certain
4582 * cases, the correct timestamps will occur in the stream after the
4583 * start of the frame, but before the start of the actual picture data.
4584 * This function can be used to set the timestamps based on the offset
4585 * into the frame data that the picture starts.
4590 gst_base_parse_set_ts_at_offset (GstBaseParse * parse, gsize offset)
4592 GstClockTime pts, dts;
4594 g_return_if_fail (GST_IS_BASE_PARSE (parse));
4596 pts = gst_adapter_prev_pts_at_offset (parse->priv->adapter, offset, NULL);
4597 dts = gst_adapter_prev_dts_at_offset (parse->priv->adapter, offset, NULL);
4599 if (!GST_CLOCK_TIME_IS_VALID (pts) || !GST_CLOCK_TIME_IS_VALID (dts)) {
4600 GST_DEBUG_OBJECT (parse,
4601 "offset adapter timestamps dts=%" GST_TIME_FORMAT " pts=%"
4602 GST_TIME_FORMAT, GST_TIME_ARGS (dts), GST_TIME_ARGS (pts));
4604 if (GST_CLOCK_TIME_IS_VALID (pts) && (parse->priv->prev_pts != pts))
4605 parse->priv->prev_pts = parse->priv->next_pts = pts;
4607 if (GST_CLOCK_TIME_IS_VALID (dts) && (parse->priv->prev_dts != dts))
4608 parse->priv->prev_dts = parse->priv->next_dts = dts;