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;
269 GstClockTime next_pts;
270 GstClockTime next_dts;
271 GstClockTime prev_pts;
272 GstClockTime prev_dts;
273 GstClockTime frame_duration;
274 gboolean seen_keyframe;
280 guint64 data_bytecount;
281 guint64 acc_duration;
282 GstClockTime first_frame_pts;
283 GstClockTime first_frame_dts;
284 gint64 first_frame_offset;
289 guint posted_avg_bitrate;
291 /* frames/buffers that are queued and ready to go on OK */
292 GQueue queued_frames;
296 /* index entry storage, either ours or provided */
302 /* seek table entries only maintained if upstream is BYTE seekable */
303 gboolean upstream_seekable;
304 gboolean upstream_has_duration;
305 gint64 upstream_size;
306 GstFormat upstream_format;
307 /* minimum distance between two index entries */
308 GstClockTimeDiff idx_interval;
309 guint64 idx_byte_interval;
310 /* ts and offset of last entry added */
311 GstClockTime index_last_ts;
312 gint64 index_last_offset;
313 gboolean index_last_valid;
315 /* timestamps currently produced are accurate, e.g. started from 0 onwards */
316 gboolean exact_position;
317 /* seek events are temporarily kept to match them with newsegments */
318 GSList *pending_seeks;
320 /* reverse playback */
321 GSList *buffers_pending;
322 GSList *buffers_head;
323 GSList *buffers_queued;
324 GSList *buffers_send;
325 GstClockTime last_pts;
326 GstClockTime last_dts;
329 /* Pending serialized events */
330 GList *pending_events;
332 /* If baseparse has checked the caps to identify if it is
333 * handling video or audio */
334 gboolean checked_media;
336 /* offset of last parsed frame/data */
338 /* force a new frame, regardless of offset */
340 /* whether we are merely scanning for a frame */
342 /* ... and resulting frame, if any */
343 GstBaseParseFrame *scanned_frame;
345 /* TRUE if we're still detecting the format, i.e.
346 * if ::detect() is still called for future buffers */
348 GList *detect_buffers;
349 guint detect_buffers_size;
351 /* True when no buffers have been received yet */
352 gboolean first_buffer;
354 /* if TRUE, a STREAM_START event needs to be pushed */
355 gboolean push_stream_start;
357 /* When we need to skip more data than we have currently */
360 /* Tag handling (stream tags only, global tags are passed through as-is) */
361 GstTagList *upstream_tags;
362 GstTagList *parser_tags;
363 GstTagMergeMode parser_tags_merge_mode;
364 gboolean tags_changed;
367 typedef struct _GstBaseParseSeek
372 GstClockTime start_ts;
375 #define DEFAULT_DISABLE_PASSTHROUGH FALSE
380 PROP_DISABLE_PASSTHROUGH,
384 #define GST_BASE_PARSE_INDEX_LOCK(parse) \
385 g_mutex_lock (&parse->priv->index_lock);
386 #define GST_BASE_PARSE_INDEX_UNLOCK(parse) \
387 g_mutex_unlock (&parse->priv->index_lock);
389 static GstElementClass *parent_class = NULL;
391 static void gst_base_parse_class_init (GstBaseParseClass * klass);
392 static void gst_base_parse_init (GstBaseParse * parse,
393 GstBaseParseClass * klass);
396 gst_base_parse_get_type (void)
398 static volatile gsize base_parse_type = 0;
400 if (g_once_init_enter (&base_parse_type)) {
401 static const GTypeInfo base_parse_info = {
402 sizeof (GstBaseParseClass),
403 (GBaseInitFunc) NULL,
404 (GBaseFinalizeFunc) NULL,
405 (GClassInitFunc) gst_base_parse_class_init,
408 sizeof (GstBaseParse),
410 (GInstanceInitFunc) gst_base_parse_init,
414 _type = g_type_register_static (GST_TYPE_ELEMENT,
415 "GstBaseParse", &base_parse_info, G_TYPE_FLAG_ABSTRACT);
416 g_once_init_leave (&base_parse_type, _type);
418 return (GType) base_parse_type;
421 static void gst_base_parse_finalize (GObject * object);
423 static GstStateChangeReturn gst_base_parse_change_state (GstElement * element,
424 GstStateChange transition);
425 static void gst_base_parse_reset (GstBaseParse * parse);
428 static void gst_base_parse_set_index (GstElement * element, GstIndex * index);
429 static GstIndex *gst_base_parse_get_index (GstElement * element);
432 static gboolean gst_base_parse_sink_activate (GstPad * sinkpad,
434 static gboolean gst_base_parse_sink_activate_mode (GstPad * pad,
435 GstObject * parent, GstPadMode mode, gboolean active);
436 static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
438 static void gst_base_parse_set_upstream_tags (GstBaseParse * parse,
439 GstTagList * taglist);
441 static void gst_base_parse_set_property (GObject * object, guint prop_id,
442 const GValue * value, GParamSpec * pspec);
443 static void gst_base_parse_get_property (GObject * object, guint prop_id,
444 GValue * value, GParamSpec * pspec);
446 static gboolean gst_base_parse_src_event (GstPad * pad, GstObject * parent,
448 static gboolean gst_base_parse_src_query (GstPad * pad, GstObject * parent,
451 static gboolean gst_base_parse_sink_event (GstPad * pad, GstObject * parent,
453 static gboolean gst_base_parse_sink_query (GstPad * pad, GstObject * parent,
456 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstObject * parent,
458 static void gst_base_parse_loop (GstPad * pad);
460 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
461 GstBaseParseFrame * frame);
463 static gboolean gst_base_parse_sink_event_default (GstBaseParse * parse,
466 static gboolean gst_base_parse_src_event_default (GstBaseParse * parse,
469 static gboolean gst_base_parse_sink_query_default (GstBaseParse * parse,
471 static gboolean gst_base_parse_src_query_default (GstBaseParse * parse,
474 static void gst_base_parse_drain (GstBaseParse * parse);
476 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
477 GstClockTime time, gboolean before, GstClockTime * _ts);
478 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
479 GstClockTime * _time, gint64 * _offset);
481 static GstFlowReturn gst_base_parse_start_fragment (GstBaseParse * parse);
482 static GstFlowReturn gst_base_parse_finish_fragment (GstBaseParse * parse,
484 static GstFlowReturn gst_base_parse_send_buffers (GstBaseParse * parse);
486 static inline GstFlowReturn gst_base_parse_check_sync (GstBaseParse * parse);
488 static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);
490 static void gst_base_parse_push_pending_events (GstBaseParse * parse);
493 gst_base_parse_clear_queues (GstBaseParse * parse)
495 g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
496 g_slist_free (parse->priv->buffers_queued);
497 parse->priv->buffers_queued = NULL;
498 g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
500 g_slist_free (parse->priv->buffers_pending);
501 parse->priv->buffers_pending = NULL;
502 g_slist_foreach (parse->priv->buffers_head, (GFunc) gst_buffer_unref, NULL);
503 g_slist_free (parse->priv->buffers_head);
504 parse->priv->buffers_head = NULL;
505 g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
506 g_slist_free (parse->priv->buffers_send);
507 parse->priv->buffers_send = NULL;
509 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
510 g_list_free (parse->priv->detect_buffers);
511 parse->priv->detect_buffers = NULL;
512 parse->priv->detect_buffers_size = 0;
514 g_queue_foreach (&parse->priv->queued_frames,
515 (GFunc) gst_base_parse_frame_free, NULL);
516 g_queue_clear (&parse->priv->queued_frames);
518 gst_buffer_replace (&parse->priv->cache, NULL);
520 g_list_foreach (parse->priv->pending_events, (GFunc) gst_event_unref, NULL);
521 g_list_free (parse->priv->pending_events);
522 parse->priv->pending_events = NULL;
524 parse->priv->checked_media = FALSE;
528 gst_base_parse_finalize (GObject * object)
530 GstBaseParse *parse = GST_BASE_PARSE (object);
532 g_object_unref (parse->priv->adapter);
534 if (parse->priv->index) {
535 gst_object_unref (parse->priv->index);
536 parse->priv->index = NULL;
538 g_mutex_clear (&parse->priv->index_lock);
540 gst_base_parse_clear_queues (parse);
542 G_OBJECT_CLASS (parent_class)->finalize (object);
546 gst_base_parse_class_init (GstBaseParseClass * klass)
548 GObjectClass *gobject_class;
549 GstElementClass *gstelement_class;
551 gobject_class = G_OBJECT_CLASS (klass);
552 g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
553 parent_class = g_type_class_peek_parent (klass);
555 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
556 gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_base_parse_set_property);
557 gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_base_parse_get_property);
560 * GstBaseParse:disable-passthrough:
562 * If set to %TRUE, baseparse will unconditionally force parsing of the
563 * incoming data. This can be required in the rare cases where the incoming
564 * side-data (caps, pts, dts, ...) is not trusted by the user and wants to
565 * force validation and parsing of the incoming data.
566 * If set to %FALSE, decision of whether to parse the data or not is up to
567 * the implementation (standard behaviour).
569 g_object_class_install_property (gobject_class, PROP_DISABLE_PASSTHROUGH,
570 g_param_spec_boolean ("disable-passthrough", "Disable passthrough",
571 "Force processing (disables passthrough)",
572 DEFAULT_DISABLE_PASSTHROUGH,
573 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
575 gstelement_class = (GstElementClass *) klass;
576 gstelement_class->change_state =
577 GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
580 gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
581 gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
584 /* Default handlers */
585 klass->sink_event = gst_base_parse_sink_event_default;
586 klass->src_event = gst_base_parse_src_event_default;
587 klass->sink_query = gst_base_parse_sink_query_default;
588 klass->src_query = gst_base_parse_src_query_default;
589 klass->convert = gst_base_parse_convert_default;
591 GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
592 "baseparse element");
596 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
598 GstPadTemplate *pad_template;
600 GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
602 parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
605 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
606 g_return_if_fail (pad_template != NULL);
607 parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
608 gst_pad_set_event_function (parse->sinkpad,
609 GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
610 gst_pad_set_query_function (parse->sinkpad,
611 GST_DEBUG_FUNCPTR (gst_base_parse_sink_query));
612 gst_pad_set_chain_function (parse->sinkpad,
613 GST_DEBUG_FUNCPTR (gst_base_parse_chain));
614 gst_pad_set_activate_function (parse->sinkpad,
615 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
616 gst_pad_set_activatemode_function (parse->sinkpad,
617 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_mode));
618 GST_PAD_SET_PROXY_ALLOCATION (parse->sinkpad);
619 gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
621 GST_DEBUG_OBJECT (parse, "sinkpad created");
624 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
625 g_return_if_fail (pad_template != NULL);
626 parse->srcpad = gst_pad_new_from_template (pad_template, "src");
627 gst_pad_set_event_function (parse->srcpad,
628 GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
629 gst_pad_set_query_function (parse->srcpad,
630 GST_DEBUG_FUNCPTR (gst_base_parse_src_query));
631 gst_pad_use_fixed_caps (parse->srcpad);
632 gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
633 GST_DEBUG_OBJECT (parse, "src created");
635 g_queue_init (&parse->priv->queued_frames);
637 parse->priv->adapter = gst_adapter_new ();
639 parse->priv->pad_mode = GST_PAD_MODE_NONE;
641 g_mutex_init (&parse->priv->index_lock);
644 gst_base_parse_reset (parse);
645 GST_DEBUG_OBJECT (parse, "init ok");
647 GST_OBJECT_FLAG_SET (parse, GST_ELEMENT_FLAG_INDEXABLE);
649 parse->priv->upstream_tags = NULL;
650 parse->priv->parser_tags = NULL;
651 parse->priv->parser_tags_merge_mode = GST_TAG_MERGE_APPEND;
655 gst_base_parse_set_property (GObject * object, guint prop_id,
656 const GValue * value, GParamSpec * pspec)
658 GstBaseParse *parse = GST_BASE_PARSE (object);
661 case PROP_DISABLE_PASSTHROUGH:
662 parse->priv->disable_passthrough = g_value_get_boolean (value);
665 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
671 gst_base_parse_get_property (GObject * object, guint prop_id, GValue * value,
674 GstBaseParse *parse = GST_BASE_PARSE (object);
677 case PROP_DISABLE_PASSTHROUGH:
678 g_value_set_boolean (value, parse->priv->disable_passthrough);
681 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
686 static GstBaseParseFrame *
687 gst_base_parse_frame_copy (GstBaseParseFrame * frame)
689 GstBaseParseFrame *copy;
691 copy = g_slice_dup (GstBaseParseFrame, frame);
692 copy->buffer = gst_buffer_ref (frame->buffer);
693 copy->_private_flags &= ~GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
695 GST_TRACE ("copied frame %p -> %p", frame, copy);
701 gst_base_parse_frame_free (GstBaseParseFrame * frame)
703 GST_TRACE ("freeing frame %p", frame);
706 gst_buffer_unref (frame->buffer);
707 frame->buffer = NULL;
710 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
711 g_slice_free (GstBaseParseFrame, frame);
713 memset (frame, 0, sizeof (*frame));
717 G_DEFINE_BOXED_TYPE (GstBaseParseFrame, gst_base_parse_frame,
718 (GBoxedCopyFunc) gst_base_parse_frame_copy,
719 (GBoxedFreeFunc) gst_base_parse_frame_free);
722 * gst_base_parse_frame_init:
723 * @frame: #GstBaseParseFrame.
725 * Sets a #GstBaseParseFrame to initial state. Currently this means
726 * all public fields are zero-ed and a private flag is set to make
727 * sure gst_base_parse_frame_free() only frees the contents but not
728 * the actual frame. Use this function to initialise a #GstBaseParseFrame
729 * allocated on the stack.
732 gst_base_parse_frame_init (GstBaseParseFrame * frame)
734 memset (frame, 0, sizeof (GstBaseParseFrame));
735 frame->_private_flags = GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
736 GST_TRACE ("inited frame %p", frame);
740 * gst_base_parse_frame_new:
741 * @buffer: (transfer none): a #GstBuffer
743 * @overhead: number of bytes in this frame which should be counted as
744 * metadata overhead, ie. not used to calculate the average bitrate.
745 * Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
747 * Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
748 * elements written in C should usually allocate the frame on the stack and
749 * then use gst_base_parse_frame_init() to initialise it.
751 * Returns: a newly-allocated #GstBaseParseFrame. Free with
752 * gst_base_parse_frame_free() when no longer needed.
755 gst_base_parse_frame_new (GstBuffer * buffer, GstBaseParseFrameFlags flags,
758 GstBaseParseFrame *frame;
760 frame = g_slice_new0 (GstBaseParseFrame);
761 frame->buffer = gst_buffer_ref (buffer);
763 GST_TRACE ("created frame %p", frame);
768 gst_base_parse_update_flags (GstBaseParse * parse)
772 /* set flags one by one for clarity */
773 if (G_UNLIKELY (parse->priv->drain))
774 parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;
776 /* losing sync is pretty much a discont (and vice versa), no ? */
777 if (G_UNLIKELY (parse->priv->discont))
778 parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
782 gst_base_parse_update_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
784 if (G_UNLIKELY (parse->priv->discont)) {
785 GST_DEBUG_OBJECT (parse, "marking DISCONT");
786 GST_BUFFER_FLAG_SET (frame->buffer, GST_BUFFER_FLAG_DISCONT);
789 if (parse->priv->prev_offset != parse->priv->offset || parse->priv->new_frame) {
790 GST_LOG_OBJECT (parse, "marking as new frame");
791 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_NEW_FRAME;
794 frame->offset = parse->priv->prev_offset = parse->priv->offset;
798 gst_base_parse_reset (GstBaseParse * parse)
800 GST_OBJECT_LOCK (parse);
801 gst_segment_init (&parse->segment, GST_FORMAT_TIME);
802 parse->priv->duration = -1;
803 parse->priv->min_frame_size = 1;
804 parse->priv->discont = TRUE;
805 parse->priv->flushing = FALSE;
806 parse->priv->saw_gaps = FALSE;
807 parse->priv->offset = 0;
808 parse->priv->sync_offset = 0;
809 parse->priv->update_interval = -1;
810 parse->priv->fps_num = parse->priv->fps_den = 0;
811 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
812 parse->priv->lead_in = parse->priv->lead_out = 0;
813 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
814 parse->priv->bitrate = 0;
815 parse->priv->framecount = 0;
816 parse->priv->bytecount = 0;
817 parse->priv->acc_duration = 0;
818 parse->priv->first_frame_pts = GST_CLOCK_TIME_NONE;
819 parse->priv->first_frame_dts = GST_CLOCK_TIME_NONE;
820 parse->priv->first_frame_offset = -1;
821 parse->priv->estimated_duration = -1;
822 parse->priv->estimated_drift = 0;
823 parse->priv->next_pts = GST_CLOCK_TIME_NONE;
824 parse->priv->next_dts = 0;
825 parse->priv->syncable = TRUE;
826 parse->priv->disable_passthrough = DEFAULT_DISABLE_PASSTHROUGH;
827 parse->priv->passthrough = FALSE;
828 parse->priv->pts_interpolate = TRUE;
829 parse->priv->infer_ts = TRUE;
830 parse->priv->has_timing_info = FALSE;
831 parse->priv->min_bitrate = G_MAXUINT;
832 parse->priv->max_bitrate = 0;
833 parse->priv->avg_bitrate = 0;
834 parse->priv->posted_avg_bitrate = 0;
836 parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
837 parse->priv->index_last_offset = -1;
838 parse->priv->index_last_valid = TRUE;
839 parse->priv->upstream_seekable = FALSE;
840 parse->priv->upstream_size = 0;
841 parse->priv->upstream_has_duration = FALSE;
842 parse->priv->upstream_format = GST_FORMAT_UNDEFINED;
843 parse->priv->idx_interval = 0;
844 parse->priv->idx_byte_interval = 0;
845 parse->priv->exact_position = TRUE;
846 parse->priv->seen_keyframe = FALSE;
847 parse->priv->checked_media = FALSE;
849 parse->priv->last_dts = GST_CLOCK_TIME_NONE;
850 parse->priv->last_pts = GST_CLOCK_TIME_NONE;
851 parse->priv->last_offset = 0;
853 parse->priv->skip = 0;
855 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
857 g_list_free (parse->priv->pending_events);
858 parse->priv->pending_events = NULL;
860 if (parse->priv->cache) {
861 gst_buffer_unref (parse->priv->cache);
862 parse->priv->cache = NULL;
865 g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
866 g_slist_free (parse->priv->pending_seeks);
867 parse->priv->pending_seeks = NULL;
869 if (parse->priv->adapter)
870 gst_adapter_clear (parse->priv->adapter);
872 gst_base_parse_set_upstream_tags (parse, NULL);
874 if (parse->priv->parser_tags) {
875 gst_tag_list_unref (parse->priv->parser_tags);
876 parse->priv->parser_tags = NULL;
878 parse->priv->parser_tags_merge_mode = GST_TAG_MERGE_APPEND;
880 parse->priv->new_frame = TRUE;
882 parse->priv->first_buffer = TRUE;
884 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
885 g_list_free (parse->priv->detect_buffers);
886 parse->priv->detect_buffers = NULL;
887 parse->priv->detect_buffers_size = 0;
888 GST_OBJECT_UNLOCK (parse);
891 /* Queues new tag event with the current combined state of the stream tags
892 * (i.e. upstream tags merged with subclass tags and current baseparse tags) */
894 gst_base_parse_queue_tag_event_update (GstBaseParse * parse)
896 GstTagList *merged_tags;
899 GST_LOG_OBJECT (parse, "upstream : %" GST_PTR_FORMAT,
900 parse->priv->upstream_tags);
901 GST_LOG_OBJECT (parse, "parser : %" GST_PTR_FORMAT,
902 parse->priv->parser_tags);
903 GST_LOG_OBJECT (parse, "mode : %d", parse->priv->parser_tags_merge_mode);
906 gst_tag_list_merge (parse->priv->upstream_tags, parse->priv->parser_tags,
907 parse->priv->parser_tags_merge_mode);
909 GST_DEBUG_OBJECT (parse, "merged : %" GST_PTR_FORMAT, merged_tags);
911 if (merged_tags == NULL)
914 if (gst_tag_list_is_empty (merged_tags)) {
915 gst_tag_list_unref (merged_tags);
919 /* only add bitrate tags to non-empty taglists for now, and only if neither
920 * upstream tags nor the subclass sets the bitrate tag in question already */
921 if (parse->priv->min_bitrate != G_MAXUINT
922 && !gst_tag_list_get_uint (merged_tags, GST_TAG_MINIMUM_BITRATE, &n)) {
923 GST_LOG_OBJECT (parse, "adding min bitrate %u", n);
924 gst_tag_list_add (merged_tags, GST_TAG_MERGE_KEEP, GST_TAG_MINIMUM_BITRATE,
925 parse->priv->min_bitrate, NULL);
927 if (parse->priv->max_bitrate != 0
928 && !gst_tag_list_get_uint (merged_tags, GST_TAG_MAXIMUM_BITRATE, &n)) {
929 GST_LOG_OBJECT (parse, "adding max bitrate %u", n);
930 gst_tag_list_add (merged_tags, GST_TAG_MERGE_KEEP, GST_TAG_MAXIMUM_BITRATE,
931 parse->priv->max_bitrate, NULL);
933 if (parse->priv->avg_bitrate != 0
934 && !gst_tag_list_get_uint (merged_tags, GST_TAG_BITRATE, &n)) {
935 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
936 GST_LOG_OBJECT (parse, "adding avg bitrate %u", n);
937 gst_tag_list_add (merged_tags, GST_TAG_MERGE_KEEP, GST_TAG_BITRATE,
938 parse->priv->avg_bitrate, NULL);
941 parse->priv->pending_events =
942 g_list_prepend (parse->priv->pending_events,
943 gst_event_new_tag (merged_tags));
946 /* gst_base_parse_parse_frame:
947 * @parse: #GstBaseParse.
948 * @buffer: #GstBuffer.
950 * Default callback for parse_frame.
953 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
955 GstBuffer *buffer = frame->buffer;
957 if (!GST_BUFFER_PTS_IS_VALID (buffer) &&
958 GST_CLOCK_TIME_IS_VALID (parse->priv->next_pts)) {
959 GST_BUFFER_PTS (buffer) = parse->priv->next_pts;
961 if (!GST_BUFFER_DTS_IS_VALID (buffer) &&
962 GST_CLOCK_TIME_IS_VALID (parse->priv->next_dts)) {
963 GST_BUFFER_DTS (buffer) = parse->priv->next_dts;
965 if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
966 GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
967 GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
972 /* gst_base_parse_convert:
973 * @parse: #GstBaseParse.
974 * @src_format: #GstFormat describing the source format.
975 * @src_value: Source value to be converted.
976 * @dest_format: #GstFormat defining the converted format.
977 * @dest_value: Pointer where the conversion result will be put.
979 * Converts using configured "convert" vmethod in #GstBaseParse class.
981 * Returns: %TRUE if conversion was successful.
984 gst_base_parse_convert (GstBaseParse * parse,
985 GstFormat src_format,
986 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
988 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
991 g_return_val_if_fail (dest_value != NULL, FALSE);
996 ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
998 #ifndef GST_DISABLE_GST_DEBUG
1001 if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
1002 GST_LOG_OBJECT (parse,
1003 "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
1004 GST_TIME_ARGS (src_value), *dest_value);
1005 } else if (dest_format == GST_FORMAT_TIME &&
1006 src_format == GST_FORMAT_BYTES) {
1007 GST_LOG_OBJECT (parse,
1008 "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
1009 src_value, GST_TIME_ARGS (*dest_value));
1011 GST_LOG_OBJECT (parse,
1012 "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
1013 GST_STR_NULL (gst_format_get_name (src_format)),
1014 GST_STR_NULL (gst_format_get_name (dest_format)),
1015 src_value, *dest_value);
1018 GST_DEBUG_OBJECT (parse, "conversion failed");
1026 /* gst_base_parse_sink_event:
1027 * @pad: #GstPad that received the event.
1028 * @event: #GstEvent to be handled.
1030 * Handler for sink pad events.
1032 * Returns: %TRUE if the event was handled.
1035 gst_base_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1037 GstBaseParse *parse = GST_BASE_PARSE (parent);
1038 GstBaseParseClass *bclass = GST_BASE_PARSE_GET_CLASS (parse);
1041 ret = bclass->sink_event (parse, event);
1047 /* gst_base_parse_sink_event_default:
1048 * @parse: #GstBaseParse.
1049 * @event: #GstEvent to be handled.
1051 * Element-level event handler function.
1053 * The event will be unreffed only if it has been handled and this
1054 * function returns %TRUE
1056 * Returns: %TRUE if the event was handled and not need forwarding.
1059 gst_base_parse_sink_event_default (GstBaseParse * parse, GstEvent * event)
1061 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1062 gboolean ret = FALSE;
1063 gboolean forward_immediate = FALSE;
1065 GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
1066 GST_EVENT_TYPE_NAME (event));
1068 switch (GST_EVENT_TYPE (event)) {
1069 case GST_EVENT_CAPS:
1073 gst_event_parse_caps (event, &caps);
1074 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
1076 if (klass->set_sink_caps)
1077 ret = klass->set_sink_caps (parse, caps);
1081 /* will send our own caps downstream */
1082 gst_event_unref (event);
1086 case GST_EVENT_SEGMENT:
1088 const GstSegment *in_segment;
1089 GstSegment out_segment;
1090 gint64 offset = 0, next_dts;
1091 guint32 seqnum = gst_event_get_seqnum (event);
1093 gst_event_parse_segment (event, &in_segment);
1094 gst_segment_init (&out_segment, GST_FORMAT_TIME);
1095 out_segment.rate = in_segment->rate;
1096 out_segment.applied_rate = in_segment->applied_rate;
1098 GST_DEBUG_OBJECT (parse, "segment %" GST_SEGMENT_FORMAT, in_segment);
1100 parse->priv->upstream_format = in_segment->format;
1101 if (in_segment->format == GST_FORMAT_BYTES) {
1102 GstBaseParseSeek *seek = NULL;
1105 /* stop time is allowed to be open-ended, but not start & pos */
1106 offset = in_segment->time;
1108 GST_OBJECT_LOCK (parse);
1109 for (node = parse->priv->pending_seeks; node; node = node->next) {
1110 GstBaseParseSeek *tmp = node->data;
1112 if (tmp->offset == offset) {
1117 parse->priv->pending_seeks =
1118 g_slist_remove (parse->priv->pending_seeks, seek);
1119 GST_OBJECT_UNLOCK (parse);
1122 GST_DEBUG_OBJECT (parse,
1123 "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
1124 seek->accurate ? " accurate" : "", &seek->segment);
1126 out_segment.start = seek->segment.start;
1127 out_segment.stop = seek->segment.stop;
1128 out_segment.time = seek->segment.start;
1130 next_dts = seek->start_ts;
1131 parse->priv->exact_position = seek->accurate;
1134 /* best attempt convert */
1135 /* as these are only estimates, stop is kept open-ended to avoid
1136 * premature cutting */
1137 gst_base_parse_convert (parse, GST_FORMAT_BYTES, in_segment->start,
1138 GST_FORMAT_TIME, (gint64 *) & next_dts);
1140 out_segment.start = next_dts;
1141 out_segment.stop = GST_CLOCK_TIME_NONE;
1142 out_segment.time = next_dts;
1144 parse->priv->exact_position = (in_segment->start == 0);
1147 gst_event_unref (event);
1149 event = gst_event_new_segment (&out_segment);
1150 gst_event_set_seqnum (event, seqnum);
1152 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. %"
1153 GST_SEGMENT_FORMAT, in_segment);
1155 } else if (in_segment->format != GST_FORMAT_TIME) {
1156 /* Unknown incoming segment format. Output a default open-ended
1158 gst_event_unref (event);
1160 out_segment.start = 0;
1161 out_segment.stop = GST_CLOCK_TIME_NONE;
1162 out_segment.time = 0;
1164 event = gst_event_new_segment (&out_segment);
1165 gst_event_set_seqnum (event, seqnum);
1169 /* not considered BYTE seekable if it is talking to us in TIME,
1170 * whatever else it might claim */
1171 parse->priv->upstream_seekable = FALSE;
1172 next_dts = in_segment->start;
1173 gst_event_copy_segment (event, &out_segment);
1176 memcpy (&parse->segment, &out_segment, sizeof (GstSegment));
1179 gst_segment_set_newsegment (&parse->segment, update, rate,
1180 applied_rate, format, start, stop, start);
1185 /* save the segment for later, right before we push a new buffer so that
1186 * the caps are fixed and the next linked element can receive
1187 * the segment but finish the current segment */
1188 GST_DEBUG_OBJECT (parse, "draining current segment");
1189 if (in_segment->rate > 0.0)
1190 gst_base_parse_drain (parse);
1192 gst_base_parse_finish_fragment (parse, FALSE);
1193 gst_adapter_clear (parse->priv->adapter);
1195 parse->priv->offset = offset;
1196 parse->priv->sync_offset = offset;
1197 parse->priv->next_dts = next_dts;
1198 parse->priv->next_pts = GST_CLOCK_TIME_NONE;
1199 parse->priv->last_pts = GST_CLOCK_TIME_NONE;
1200 parse->priv->last_dts = GST_CLOCK_TIME_NONE;
1201 parse->priv->prev_pts = GST_CLOCK_TIME_NONE;
1202 parse->priv->prev_dts = GST_CLOCK_TIME_NONE;
1203 parse->priv->discont = TRUE;
1204 parse->priv->seen_keyframe = FALSE;
1205 parse->priv->skip = 0;
1209 case GST_EVENT_SEGMENT_DONE:
1210 /* need to drain now, rather than upon a new segment,
1211 * since that would have SEGMENT_DONE come before potential
1212 * delayed last part of the current segment */
1213 GST_DEBUG_OBJECT (parse, "draining current segment");
1214 if (parse->segment.rate > 0.0)
1215 gst_base_parse_drain (parse);
1217 gst_base_parse_finish_fragment (parse, FALSE);
1218 /* Also forward event immediately, there might be no new data
1219 * coming afterwards that would allow us to forward it later */
1220 forward_immediate = TRUE;
1223 case GST_EVENT_FLUSH_START:
1224 GST_OBJECT_LOCK (parse);
1225 parse->priv->flushing = TRUE;
1226 GST_OBJECT_UNLOCK (parse);
1229 case GST_EVENT_FLUSH_STOP:
1230 gst_adapter_clear (parse->priv->adapter);
1231 gst_base_parse_clear_queues (parse);
1232 parse->priv->flushing = FALSE;
1233 parse->priv->discont = TRUE;
1234 parse->priv->last_pts = GST_CLOCK_TIME_NONE;
1235 parse->priv->last_dts = GST_CLOCK_TIME_NONE;
1236 parse->priv->new_frame = TRUE;
1237 parse->priv->skip = 0;
1239 forward_immediate = TRUE;
1243 if (parse->segment.rate > 0.0)
1244 gst_base_parse_drain (parse);
1246 gst_base_parse_finish_fragment (parse, TRUE);
1248 /* If we STILL have zero frames processed, fire an error */
1249 if (parse->priv->framecount == 0 && !parse->priv->saw_gaps &&
1250 !parse->priv->first_buffer) {
1251 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1252 ("No valid frames found before end of stream"), (NULL));
1255 if (!parse->priv->saw_gaps
1256 && parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1257 /* We've not posted bitrate tags yet - do so now */
1258 gst_base_parse_queue_tag_event_update (parse);
1261 /* newsegment and other serialized events before eos */
1262 gst_base_parse_push_pending_events (parse);
1264 forward_immediate = TRUE;
1266 case GST_EVENT_CUSTOM_DOWNSTREAM:{
1267 /* FIXME: Code duplicated from libgstvideo because core can't depend on -base */
1268 #ifndef GST_VIDEO_EVENT_STILL_STATE_NAME
1269 #define GST_VIDEO_EVENT_STILL_STATE_NAME "GstEventStillFrame"
1272 const GstStructure *s;
1273 gboolean ev_still_state;
1275 s = gst_event_get_structure (event);
1277 gst_structure_has_name (s, GST_VIDEO_EVENT_STILL_STATE_NAME) &&
1278 gst_structure_get_boolean (s, "still-state", &ev_still_state)) {
1279 if (ev_still_state) {
1280 GST_DEBUG_OBJECT (parse, "draining current data for still-frame");
1281 if (parse->segment.rate > 0.0)
1282 gst_base_parse_drain (parse);
1284 gst_base_parse_finish_fragment (parse, TRUE);
1286 forward_immediate = TRUE;
1292 GST_DEBUG_OBJECT (parse, "draining current data due to gap event");
1294 gst_base_parse_push_pending_events (parse);
1296 if (parse->segment.rate > 0.0)
1297 gst_base_parse_drain (parse);
1299 gst_base_parse_finish_fragment (parse, TRUE);
1300 forward_immediate = TRUE;
1301 parse->priv->saw_gaps = TRUE;
1306 GstTagList *tags = NULL;
1308 gst_event_parse_tag (event, &tags);
1310 /* We only care about stream tags here, global tags we just forward */
1311 if (gst_tag_list_get_scope (tags) != GST_TAG_SCOPE_STREAM)
1314 gst_base_parse_set_upstream_tags (parse, tags);
1315 gst_base_parse_queue_tag_event_update (parse);
1316 parse->priv->tags_changed = FALSE;
1317 gst_event_unref (event);
1322 case GST_EVENT_STREAM_START:
1324 if (parse->priv->pad_mode != GST_PAD_MODE_PULL)
1325 forward_immediate = TRUE;
1327 gst_base_parse_set_upstream_tags (parse, NULL);
1328 parse->priv->tags_changed = TRUE;
1335 /* Forward non-serialized events and EOS/FLUSH_STOP immediately.
1336 * For EOS this is required because no buffer or serialized event
1337 * will come after EOS and nothing could trigger another
1338 * _finish_frame() call. *
1339 * If the subclass handles sending of EOS manually it can return
1340 * _DROPPED from ::finish() and all other subclasses should have
1341 * decoded/flushed all remaining data before this
1343 * For FLUSH_STOP this is required because it is expected
1344 * to be forwarded immediately and no buffers are queued anyway.
1347 if (!GST_EVENT_IS_SERIALIZED (event) || forward_immediate) {
1348 ret = gst_pad_push_event (parse->srcpad, event);
1350 parse->priv->pending_events =
1351 g_list_prepend (parse->priv->pending_events, event);
1356 GST_DEBUG_OBJECT (parse, "event handled");
1362 gst_base_parse_sink_query_default (GstBaseParse * parse, GstQuery * query)
1367 pad = GST_BASE_PARSE_SINK_PAD (parse);
1369 switch (GST_QUERY_TYPE (query)) {
1370 case GST_QUERY_CAPS:
1372 GstBaseParseClass *bclass;
1374 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1376 if (bclass->get_sink_caps) {
1377 GstCaps *caps, *filter;
1379 gst_query_parse_caps (query, &filter);
1380 caps = bclass->get_sink_caps (parse, filter);
1381 GST_LOG_OBJECT (parse, "sink getcaps returning caps %" GST_PTR_FORMAT,
1383 gst_query_set_caps_result (query, caps);
1384 gst_caps_unref (caps);
1388 GstCaps *caps, *template_caps, *filter;
1390 gst_query_parse_caps (query, &filter);
1391 template_caps = gst_pad_get_pad_template_caps (pad);
1392 if (filter != NULL) {
1394 gst_caps_intersect_full (filter, template_caps,
1395 GST_CAPS_INTERSECT_FIRST);
1396 gst_caps_unref (template_caps);
1398 caps = template_caps;
1400 gst_query_set_caps_result (query, caps);
1401 gst_caps_unref (caps);
1409 res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
1418 gst_base_parse_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
1420 GstBaseParseClass *bclass;
1421 GstBaseParse *parse;
1424 parse = GST_BASE_PARSE (parent);
1425 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1427 GST_DEBUG_OBJECT (parse, "%s query", GST_QUERY_TYPE_NAME (query));
1429 if (bclass->sink_query)
1430 ret = bclass->sink_query (parse, query);
1434 GST_LOG_OBJECT (parse, "%s query result: %d %" GST_PTR_FORMAT,
1435 GST_QUERY_TYPE_NAME (query), ret, query);
1441 gst_base_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1443 GstBaseParseClass *bclass;
1444 GstBaseParse *parse;
1447 parse = GST_BASE_PARSE (parent);
1448 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1450 GST_DEBUG_OBJECT (parse, "%s query: %" GST_PTR_FORMAT,
1451 GST_QUERY_TYPE_NAME (query), query);
1453 if (bclass->src_query)
1454 ret = bclass->src_query (parse, query);
1458 GST_LOG_OBJECT (parse, "%s query result: %d %" GST_PTR_FORMAT,
1459 GST_QUERY_TYPE_NAME (query), ret, query);
1464 /* gst_base_parse_src_event:
1465 * @pad: #GstPad that received the event.
1466 * @event: #GstEvent that was received.
1468 * Handler for source pad events.
1470 * Returns: %TRUE if the event was handled.
1473 gst_base_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1475 GstBaseParse *parse;
1476 GstBaseParseClass *bclass;
1477 gboolean ret = TRUE;
1479 parse = GST_BASE_PARSE (parent);
1480 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1482 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1483 GST_EVENT_TYPE_NAME (event));
1485 if (bclass->src_event)
1486 ret = bclass->src_event (parse, event);
1488 gst_event_unref (event);
1494 gst_base_parse_is_seekable (GstBaseParse * parse)
1496 /* FIXME: could do more here, e.g. check index or just send data from 0
1497 * in pull mode and let decoder/sink clip */
1498 return parse->priv->syncable;
1501 /* gst_base_parse_src_event_default:
1502 * @parse: #GstBaseParse.
1503 * @event: #GstEvent that was received.
1505 * Default srcpad event handler.
1507 * Returns: %TRUE if the event was handled and can be dropped.
1510 gst_base_parse_src_event_default (GstBaseParse * parse, GstEvent * event)
1512 gboolean res = FALSE;
1514 switch (GST_EVENT_TYPE (event)) {
1515 case GST_EVENT_SEEK:
1516 if (gst_base_parse_is_seekable (parse))
1517 res = gst_base_parse_handle_seek (parse, event);
1520 res = gst_pad_event_default (parse->srcpad, GST_OBJECT_CAST (parse),
1529 * gst_base_parse_convert_default:
1530 * @parse: #GstBaseParse.
1531 * @src_format: #GstFormat describing the source format.
1532 * @src_value: Source value to be converted.
1533 * @dest_format: #GstFormat defining the converted format.
1534 * @dest_value: Pointer where the conversion result will be put.
1536 * Default implementation of "convert" vmethod in #GstBaseParse class.
1538 * Returns: %TRUE if conversion was successful.
1541 gst_base_parse_convert_default (GstBaseParse * parse,
1542 GstFormat src_format,
1543 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1545 gboolean ret = FALSE;
1546 guint64 bytes, duration;
1548 if (G_UNLIKELY (src_format == dest_format)) {
1549 *dest_value = src_value;
1553 if (G_UNLIKELY (src_value == -1)) {
1558 if (G_UNLIKELY (src_value == 0)) {
1563 /* need at least some frames */
1564 if (!parse->priv->framecount)
1567 duration = parse->priv->acc_duration / GST_MSECOND;
1568 bytes = parse->priv->bytecount;
1570 if (G_UNLIKELY (!duration || !bytes))
1571 goto no_duration_bytes;
1573 if (src_format == GST_FORMAT_BYTES) {
1574 if (dest_format == GST_FORMAT_TIME) {
1575 /* BYTES -> TIME conversion */
1576 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1577 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1578 *dest_value *= GST_MSECOND;
1579 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1580 *dest_value / GST_MSECOND);
1583 GST_DEBUG_OBJECT (parse, "converting bytes -> other not implemented");
1585 } else if (src_format == GST_FORMAT_TIME) {
1586 if (dest_format == GST_FORMAT_BYTES) {
1587 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1588 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1590 GST_DEBUG_OBJECT (parse,
1591 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1592 src_value / GST_MSECOND, *dest_value);
1595 GST_DEBUG_OBJECT (parse, "converting time -> other not implemented");
1597 } else if (src_format == GST_FORMAT_DEFAULT) {
1598 /* DEFAULT == frame-based */
1599 if (dest_format == GST_FORMAT_TIME) {
1600 GST_DEBUG_OBJECT (parse, "converting default -> time");
1601 if (parse->priv->fps_den) {
1602 *dest_value = gst_util_uint64_scale (src_value,
1603 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1607 GST_DEBUG_OBJECT (parse, "converting default -> other not implemented");
1610 GST_DEBUG_OBJECT (parse, "conversion not implemented");
1617 GST_DEBUG_OBJECT (parse, "no framecount");
1622 GST_DEBUG_OBJECT (parse, "no duration %" G_GUINT64_FORMAT ", bytes %"
1623 G_GUINT64_FORMAT, duration, bytes);
1630 gst_base_parse_update_duration (GstBaseParse * parse)
1632 gint64 ptot, dest_value;
1634 if (!gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_BYTES, &ptot))
1637 if (!gst_base_parse_convert (parse, GST_FORMAT_BYTES, ptot,
1638 GST_FORMAT_TIME, &dest_value))
1641 /* inform if duration changed, but try to avoid spamming */
1642 parse->priv->estimated_drift += dest_value - parse->priv->estimated_duration;
1644 parse->priv->estimated_duration = dest_value;
1645 GST_LOG_OBJECT (parse,
1646 "updated estimated duration to %" GST_TIME_FORMAT,
1647 GST_TIME_ARGS (dest_value));
1649 if (parse->priv->estimated_drift > GST_SECOND ||
1650 parse->priv->estimated_drift < -GST_SECOND) {
1651 gst_element_post_message (GST_ELEMENT (parse),
1652 gst_message_new_duration_changed (GST_OBJECT (parse)));
1653 parse->priv->estimated_drift = 0;
1657 /* gst_base_parse_update_bitrates:
1658 * @parse: #GstBaseParse.
1659 * @buffer: Current frame as a #GstBuffer
1661 * Keeps track of the minimum and maximum bitrates, and also maintains a
1662 * running average bitrate of the stream so far.
1665 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1667 /* Only update the tag on a 10 kbps delta */
1668 static const gint update_threshold = 10000;
1670 guint64 data_len, frame_dur;
1671 gint overhead, frame_bitrate, old_avg_bitrate;
1672 GstBuffer *buffer = frame->buffer;
1674 overhead = frame->overhead;
1678 data_len = gst_buffer_get_size (buffer) - overhead;
1679 parse->priv->data_bytecount += data_len;
1681 /* duration should be valid by now,
1682 * either set by subclass or maybe based on fps settings */
1683 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1684 /* Calculate duration of a frame from buffer properties */
1685 frame_dur = GST_BUFFER_DURATION (buffer);
1686 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1687 parse->priv->acc_duration;
1690 /* No way to figure out frame duration (is this even possible?) */
1694 /* override if subclass provided bitrate, e.g. metadata based */
1695 if (parse->priv->bitrate) {
1696 parse->priv->avg_bitrate = parse->priv->bitrate;
1697 /* spread this (confirmed) info ASAP */
1698 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1699 parse->priv->tags_changed = TRUE;
1703 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1707 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1708 parse->priv->avg_bitrate);
1710 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
1713 if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE)
1714 parse->priv->tags_changed = TRUE;
1716 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1717 if (frame_bitrate < parse->priv->min_bitrate) {
1718 parse->priv->min_bitrate = frame_bitrate;
1719 parse->priv->tags_changed = TRUE;
1722 if (frame_bitrate > parse->priv->max_bitrate) {
1723 parse->priv->max_bitrate = frame_bitrate;
1724 parse->priv->tags_changed = TRUE;
1727 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1728 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1729 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1731 parse->priv->tags_changed = TRUE;
1736 * gst_base_parse_add_index_entry:
1737 * @parse: #GstBaseParse.
1738 * @offset: offset of entry
1739 * @ts: timestamp associated with offset
1740 * @key: whether entry refers to keyframe
1741 * @force: add entry disregarding sanity checks
1743 * Adds an entry to the index associating @offset to @ts. It is recommended
1744 * to only add keyframe entries. @force allows to bypass checks, such as
1745 * whether the stream is (upstream) seekable, another entry is already "close"
1746 * to the new entry, etc.
1748 * Returns: #gboolean indicating whether entry was added
1751 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1752 GstClockTime ts, gboolean key, gboolean force)
1754 gboolean ret = FALSE;
1755 GstIndexAssociation associations[2];
1757 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1758 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1760 if (G_LIKELY (!force)) {
1762 if (!parse->priv->upstream_seekable) {
1763 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1767 /* FIXME need better helper data structure that handles these issues
1768 * related to ongoing collecting of index entries */
1769 if (parse->priv->index_last_offset + parse->priv->idx_byte_interval >=
1771 GST_LOG_OBJECT (parse,
1772 "already have entries up to offset 0x%08" G_GINT64_MODIFIER "x",
1773 parse->priv->index_last_offset + parse->priv->idx_byte_interval);
1777 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1778 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1779 parse->priv->idx_interval) {
1780 GST_LOG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1781 GST_TIME_ARGS (parse->priv->index_last_ts));
1785 /* if last is not really the last one */
1786 if (!parse->priv->index_last_valid) {
1787 GstClockTime prev_ts;
1789 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1790 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1791 GST_LOG_OBJECT (parse,
1792 "entry too close to existing entry %" GST_TIME_FORMAT,
1793 GST_TIME_ARGS (prev_ts));
1794 parse->priv->index_last_offset = offset;
1795 parse->priv->index_last_ts = ts;
1801 associations[0].format = GST_FORMAT_TIME;
1802 associations[0].value = ts;
1803 associations[1].format = GST_FORMAT_BYTES;
1804 associations[1].value = offset;
1806 /* index might change on-the-fly, although that would be nutty app ... */
1807 GST_BASE_PARSE_INDEX_LOCK (parse);
1808 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1809 (key) ? GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT :
1810 GST_INDEX_ASSOCIATION_FLAG_DELTA_UNIT, 2,
1811 (const GstIndexAssociation *) &associations);
1812 GST_BASE_PARSE_INDEX_UNLOCK (parse);
1815 parse->priv->index_last_offset = offset;
1816 parse->priv->index_last_ts = ts;
1825 /* check for seekable upstream, above and beyond a mere query */
1827 gst_base_parse_check_seekability (GstBaseParse * parse)
1830 gboolean seekable = FALSE;
1831 gint64 start = -1, stop = -1;
1832 guint idx_interval = 0;
1833 guint64 idx_byte_interval = 0;
1835 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1836 if (!gst_pad_peer_query (parse->sinkpad, query)) {
1837 GST_DEBUG_OBJECT (parse, "seeking query failed");
1841 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1843 /* try harder to query upstream size if we didn't get it the first time */
1844 if (seekable && stop == -1) {
1845 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1846 gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_BYTES, &stop);
1849 /* if upstream doesn't know the size, it's likely that it's not seekable in
1850 * practice even if it technically may be seekable */
1851 if (seekable && (start != 0 || stop <= start)) {
1852 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1856 /* let's not put every single frame into our index */
1858 if (stop < 10 * 1024 * 1024)
1860 else if (stop < 100 * 1024 * 1024)
1863 idx_interval = 1000;
1865 /* ensure that even for large files (e.g. very long audio files), the index
1866 * stays reasonably-size, with some arbitrary limit to the total number of
1868 idx_byte_interval = (stop - start) / MAX_INDEX_ENTRIES;
1869 GST_DEBUG_OBJECT (parse,
1870 "Limiting index entries to %d, indexing byte interval %"
1871 G_GUINT64_FORMAT " bytes", MAX_INDEX_ENTRIES, idx_byte_interval);
1875 gst_query_unref (query);
1877 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1878 G_GUINT64_FORMAT ")", seekable, start, stop);
1879 parse->priv->upstream_seekable = seekable;
1880 parse->priv->upstream_size = seekable ? stop : 0;
1882 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1883 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1884 parse->priv->idx_byte_interval = idx_byte_interval;
1887 /* some misc checks on upstream */
1889 gst_base_parse_check_upstream (GstBaseParse * parse)
1893 if (gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_TIME, &stop))
1894 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1895 /* upstream has one, accept it also, and no further updates */
1896 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1897 parse->priv->upstream_has_duration = TRUE;
1900 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1901 parse->priv->upstream_has_duration);
1904 /* checks src caps to determine if dealing with audio or video */
1905 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1907 gst_base_parse_check_media (GstBaseParse * parse)
1912 caps = gst_pad_get_current_caps (parse->srcpad);
1913 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1914 parse->priv->is_video =
1915 g_str_has_prefix (gst_structure_get_name (s), "video");
1917 /* historical default */
1918 parse->priv->is_video = FALSE;
1921 gst_caps_unref (caps);
1923 parse->priv->checked_media = TRUE;
1924 GST_DEBUG_OBJECT (parse, "media is video: %d", parse->priv->is_video);
1927 /* takes ownership of frame */
1929 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1931 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1932 /* frame allocated on the heap, we can just take ownership */
1933 g_queue_push_tail (&parse->priv->queued_frames, frame);
1934 GST_TRACE ("queued frame %p", frame);
1936 GstBaseParseFrame *copy;
1938 /* probably allocated on the stack, must make a proper copy */
1939 copy = gst_base_parse_frame_copy (frame);
1940 g_queue_push_tail (&parse->priv->queued_frames, copy);
1941 GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1942 gst_base_parse_frame_free (frame);
1946 /* makes sure that @buf is properly prepared and decorated for passing
1947 * to baseclass, and an equally setup frame is returned setup with @buf.
1948 * Takes ownership of @buf. */
1949 static GstBaseParseFrame *
1950 gst_base_parse_prepare_frame (GstBaseParse * parse, GstBuffer * buffer)
1952 GstBaseParseFrame *frame = NULL;
1954 buffer = gst_buffer_make_writable (buffer);
1956 GST_LOG_OBJECT (parse,
1957 "preparing frame at offset %" G_GUINT64_FORMAT
1958 " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
1959 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1960 gst_buffer_get_size (buffer));
1962 GST_BUFFER_OFFSET (buffer) = parse->priv->offset;
1964 gst_base_parse_update_flags (parse);
1966 frame = gst_base_parse_frame_new (buffer, 0, 0);
1967 gst_buffer_unref (buffer);
1968 gst_base_parse_update_frame (parse, frame);
1970 /* clear flags for next frame */
1971 parse->priv->discont = FALSE;
1972 parse->priv->new_frame = FALSE;
1974 /* use default handler to provide initial (upstream) metadata */
1975 gst_base_parse_parse_frame (parse, frame);
1980 /* Wraps buffer in a frame and dispatches to subclass.
1981 * Also manages data skipping and offset handling (including adapter flushing).
1982 * Takes ownership of @buffer */
1983 static GstFlowReturn
1984 gst_base_parse_handle_buffer (GstBaseParse * parse, GstBuffer * buffer,
1985 gint * skip, gint * flushed)
1987 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1988 GstBaseParseFrame *frame;
1991 g_return_val_if_fail (skip != NULL || flushed != NULL, GST_FLOW_ERROR);
1993 GST_LOG_OBJECT (parse,
1994 "handling buffer of size %" G_GSIZE_FORMAT " with dts %" GST_TIME_FORMAT
1995 ", pts %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
1996 gst_buffer_get_size (buffer), GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
1997 GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
1998 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
2000 /* track what is being flushed during this single round of frame processing */
2001 parse->priv->flushed = 0;
2004 /* make it easy for _finish_frame to pick up input data */
2005 if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
2006 gst_buffer_ref (buffer);
2007 gst_adapter_push (parse->priv->adapter, buffer);
2010 frame = gst_base_parse_prepare_frame (parse, buffer);
2011 ret = klass->handle_frame (parse, frame, skip);
2013 *flushed = parse->priv->flushed;
2015 GST_LOG_OBJECT (parse, "handle_frame skipped %d, flushed %d",
2018 /* subclass can only do one of these, or semantics are too unclear */
2019 g_assert (*skip == 0 || *flushed == 0);
2021 /* track skipping */
2023 GstClockTime pts, dts;
2026 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", *skip);
2027 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2028 /* reverse playback, and no frames found yet, so we are skipping
2029 * the leading part of a fragment, which may form the tail of
2030 * fragment coming later, hopefully subclass skips efficiently ... */
2031 pts = gst_adapter_prev_pts (parse->priv->adapter, NULL);
2032 dts = gst_adapter_prev_dts (parse->priv->adapter, NULL);
2033 outbuf = gst_adapter_take_buffer (parse->priv->adapter, *skip);
2034 outbuf = gst_buffer_make_writable (outbuf);
2035 GST_BUFFER_PTS (outbuf) = pts;
2036 GST_BUFFER_DTS (outbuf) = dts;
2037 parse->priv->buffers_head =
2038 g_slist_prepend (parse->priv->buffers_head, outbuf);
2041 /* If we're asked to skip more than is available in the adapter,
2042 we need to remember what we need to skip for next iteration */
2043 gsize av = gst_adapter_available (parse->priv->adapter);
2044 GST_DEBUG ("Asked to skip %u (%" G_GSIZE_FORMAT " available)", *skip, av);
2046 gst_adapter_flush (parse->priv->adapter, *skip);
2049 ("This is more than available, flushing %" G_GSIZE_FORMAT
2050 ", storing %u to skip", av, (guint) (*skip - av));
2051 parse->priv->skip = *skip - av;
2052 gst_adapter_flush (parse->priv->adapter, av);
2056 if (!parse->priv->discont)
2057 parse->priv->sync_offset = parse->priv->offset;
2058 parse->priv->offset += *skip;
2059 parse->priv->discont = TRUE;
2060 /* check for indefinite skipping */
2061 if (ret == GST_FLOW_OK)
2062 ret = gst_base_parse_check_sync (parse);
2065 parse->priv->offset += *flushed;
2067 if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
2068 gst_adapter_clear (parse->priv->adapter);
2071 gst_base_parse_frame_free (frame);
2076 /* gst_base_parse_push_pending_events:
2077 * @parse: #GstBaseParse
2079 * Pushes the pending events
2082 gst_base_parse_push_pending_events (GstBaseParse * parse)
2084 if (G_UNLIKELY (parse->priv->pending_events)) {
2085 GList *r = g_list_reverse (parse->priv->pending_events);
2088 parse->priv->pending_events = NULL;
2089 for (l = r; l != NULL; l = l->next) {
2090 gst_pad_push_event (parse->srcpad, GST_EVENT_CAST (l->data));
2096 /* gst_base_parse_handle_and_push_frame:
2097 * @parse: #GstBaseParse.
2098 * @klass: #GstBaseParseClass.
2099 * @frame: (transfer full): a #GstBaseParseFrame
2101 * Parses the frame from given buffer and pushes it forward. Also performs
2102 * timestamp handling and checks the segment limits.
2104 * This is called with srcpad STREAM_LOCK held.
2106 * Returns: #GstFlowReturn
2108 static GstFlowReturn
2109 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
2110 GstBaseParseFrame * frame)
2115 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2117 buffer = frame->buffer;
2118 offset = frame->offset;
2120 /* check if subclass/format can provide ts.
2121 * If so, that allows and enables extra seek and duration determining options */
2122 if (G_UNLIKELY (parse->priv->first_frame_offset < 0)) {
2123 if (GST_BUFFER_PTS_IS_VALID (buffer) && parse->priv->has_timing_info
2124 && parse->priv->pad_mode == GST_PAD_MODE_PULL) {
2125 parse->priv->first_frame_offset = offset;
2126 parse->priv->first_frame_pts = GST_BUFFER_PTS (buffer);
2127 parse->priv->first_frame_dts = GST_BUFFER_DTS (buffer);
2128 GST_DEBUG_OBJECT (parse, "subclass provided dts %" GST_TIME_FORMAT
2129 ", pts %" GST_TIME_FORMAT " for first frame at offset %"
2130 G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->first_frame_dts),
2131 GST_TIME_ARGS (parse->priv->first_frame_pts),
2132 parse->priv->first_frame_offset);
2133 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
2135 GstClockTime last_ts = G_MAXINT64;
2137 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
2138 gst_base_parse_locate_time (parse, &last_ts, &off);
2139 if (GST_CLOCK_TIME_IS_VALID (last_ts))
2140 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
2143 /* disable further checks */
2144 parse->priv->first_frame_offset = 0;
2148 /* track upstream time if provided, not subclass' internal notion of it */
2149 if (parse->priv->upstream_format == GST_FORMAT_TIME) {
2150 GST_BUFFER_PTS (frame->buffer) = GST_CLOCK_TIME_NONE;
2151 GST_BUFFER_DTS (frame->buffer) = GST_CLOCK_TIME_NONE;
2154 /* interpolating and no valid pts yet,
2155 * start with dts and carry on from there */
2156 if (parse->priv->infer_ts && parse->priv->pts_interpolate
2157 && !GST_CLOCK_TIME_IS_VALID (parse->priv->next_pts))
2158 parse->priv->next_pts = parse->priv->next_dts;
2160 /* again use default handler to add missing metadata;
2161 * we may have new information on frame properties */
2162 gst_base_parse_parse_frame (parse, frame);
2164 parse->priv->next_pts = GST_CLOCK_TIME_NONE;
2165 if (GST_BUFFER_DTS_IS_VALID (buffer) && GST_BUFFER_DURATION_IS_VALID (buffer)) {
2166 parse->priv->next_dts =
2167 GST_BUFFER_DTS (buffer) + GST_BUFFER_DURATION (buffer);
2168 if (parse->priv->pts_interpolate && GST_BUFFER_PTS_IS_VALID (buffer)) {
2169 GstClockTime next_pts =
2170 GST_BUFFER_PTS (buffer) + GST_BUFFER_DURATION (buffer);
2171 if (next_pts >= parse->priv->next_dts)
2172 parse->priv->next_pts = next_pts;
2175 /* we lost track, do not produce bogus time next time around
2176 * (probably means parser subclass has given up on parsing as well) */
2177 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
2178 parse->priv->next_dts = GST_CLOCK_TIME_NONE;
2181 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
2182 GST_BUFFER_PTS_IS_VALID (buffer))
2183 gst_base_parse_add_index_entry (parse, offset,
2184 GST_BUFFER_PTS (buffer),
2185 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
2187 /* All OK, push queued frames if there are any */
2188 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
2189 GstBaseParseFrame *queued_frame;
2191 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
2192 gst_base_parse_push_frame (parse, queued_frame);
2193 gst_base_parse_frame_free (queued_frame);
2197 return gst_base_parse_push_frame (parse, frame);
2201 * gst_base_parse_push_frame:
2202 * @parse: #GstBaseParse.
2203 * @frame: (transfer none): a #GstBaseParseFrame
2205 * Pushes the frame's buffer downstream, sends any pending events and
2206 * does some timestamp and segment handling. Takes ownership of
2207 * frame's buffer, though caller retains ownership of @frame.
2209 * This must be called with sinkpad STREAM_LOCK held.
2211 * Returns: #GstFlowReturn
2214 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
2216 GstFlowReturn ret = GST_FLOW_OK;
2217 GstClockTime last_start = GST_CLOCK_TIME_NONE;
2218 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
2219 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
2223 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2224 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
2226 GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
2228 buffer = frame->buffer;
2230 GST_LOG_OBJECT (parse,
2231 "processing buffer of size %" G_GSIZE_FORMAT " with dts %" GST_TIME_FORMAT
2232 ", pts %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
2233 gst_buffer_get_size (buffer),
2234 GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
2235 GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
2236 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
2239 parse->priv->bytecount += frame->size;
2240 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
2241 parse->priv->framecount++;
2242 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
2243 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
2246 /* 0 means disabled */
2247 if (parse->priv->update_interval < 0)
2248 parse->priv->update_interval = 50;
2249 else if (parse->priv->update_interval > 0 &&
2250 (parse->priv->framecount % parse->priv->update_interval) == 0)
2251 gst_base_parse_update_duration (parse);
2253 if (GST_BUFFER_PTS_IS_VALID (buffer))
2254 last_start = last_stop = GST_BUFFER_PTS (buffer);
2255 if (last_start != GST_CLOCK_TIME_NONE
2256 && GST_BUFFER_DURATION_IS_VALID (buffer))
2257 last_stop = last_start + GST_BUFFER_DURATION (buffer);
2259 /* should have caps by now */
2260 if (!gst_pad_has_current_caps (parse->srcpad))
2263 if (G_UNLIKELY (!parse->priv->checked_media)) {
2264 /* have caps; check identity */
2265 gst_base_parse_check_media (parse);
2268 if (parse->priv->tags_changed) {
2269 gst_base_parse_queue_tag_event_update (parse);
2270 parse->priv->tags_changed = FALSE;
2273 /* Push pending events, including SEGMENT events */
2274 gst_base_parse_push_pending_events (parse);
2276 /* segment adjustment magic; only if we are running the whole show */
2277 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
2278 (parse->priv->pad_mode == GST_PAD_MODE_PULL ||
2279 parse->priv->upstream_seekable)) {
2281 if (GST_CLOCK_TIME_IS_VALID (parse->segment.position) &&
2282 GST_CLOCK_TIME_IS_VALID (last_start)) {
2283 GstClockTimeDiff diff;
2285 /* only send newsegments with increasing start times,
2286 * otherwise if these go back and forth downstream (sinks) increase
2287 * accumulated time and running_time */
2288 diff = GST_CLOCK_DIFF (parse->segment.position, last_start);
2289 if (G_UNLIKELY (diff > 2 * GST_SECOND
2290 && last_start > parse->segment.start
2291 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
2292 || last_start < parse->segment.stop))) {
2294 GST_DEBUG_OBJECT (parse,
2295 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
2296 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
2297 "Sending updated SEGMENT events", diff,
2298 GST_TIME_ARGS (parse->segment.position),
2299 GST_TIME_ARGS (last_start));
2301 /* skip gap FIXME */
2302 gst_pad_push_event (parse->srcpad,
2303 gst_event_new_segment (&parse->segment));
2305 parse->segment.position = last_start;
2310 /* update bitrates and optionally post corresponding tags
2311 * (following newsegment) */
2312 gst_base_parse_update_bitrates (parse, frame);
2314 if (klass->pre_push_frame) {
2315 ret = klass->pre_push_frame (parse, frame);
2317 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
2320 /* take final ownership of frame buffer */
2321 if (frame->out_buffer) {
2322 buffer = frame->out_buffer;
2323 frame->out_buffer = NULL;
2324 gst_buffer_replace (&frame->buffer, NULL);
2326 buffer = frame->buffer;
2327 frame->buffer = NULL;
2330 /* subclass must play nice */
2331 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2333 size = gst_buffer_get_size (buffer);
2335 parse->priv->seen_keyframe |= parse->priv->is_video &&
2336 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
2338 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
2339 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2340 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
2341 GST_BUFFER_TIMESTAMP (buffer) >
2342 parse->segment.stop + parse->priv->lead_out_ts) {
2343 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
2345 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2346 GST_BUFFER_DURATION_IS_VALID (buffer) &&
2347 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
2348 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
2349 parse->priv->lead_in_ts < parse->segment.start) {
2350 if (parse->priv->seen_keyframe) {
2351 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
2354 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
2355 ret = GST_BASE_PARSE_FLOW_DROPPED;
2362 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
2363 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) dropped", size);
2364 gst_buffer_unref (buffer);
2366 } else if (ret == GST_FLOW_OK) {
2367 if (parse->segment.rate > 0.0) {
2368 GST_LOG_OBJECT (parse, "pushing frame (%" G_GSIZE_FORMAT " bytes) now..",
2370 ret = gst_pad_push (parse->srcpad, buffer);
2371 GST_LOG_OBJECT (parse, "frame pushed, flow %s", gst_flow_get_name (ret));
2372 } else if (!parse->priv->disable_passthrough && parse->priv->passthrough) {
2374 /* in backwards playback mode, if on passthrough we need to push buffers
2375 * directly without accumulating them into the buffers_queued as baseparse
2376 * will never check for a DISCONT while on passthrough and those buffers
2377 * will never be pushed.
2379 * also, as we are on reverse playback, it might be possible that
2380 * passthrough might have just been enabled, so make sure to drain the
2381 * buffers_queued list */
2382 if (G_UNLIKELY (parse->priv->buffers_queued != NULL)) {
2383 gst_base_parse_finish_fragment (parse, TRUE);
2384 ret = gst_base_parse_send_buffers (parse);
2387 if (ret == GST_FLOW_OK) {
2388 GST_LOG_OBJECT (parse,
2389 "pushing frame (%" G_GSIZE_FORMAT " bytes) now..", size);
2390 ret = gst_pad_push (parse->srcpad, buffer);
2391 GST_LOG_OBJECT (parse, "frame pushed, flow %s",
2392 gst_flow_get_name (ret));
2394 GST_LOG_OBJECT (parse,
2395 "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s", size,
2396 gst_flow_get_name (ret));
2397 gst_buffer_unref (buffer);
2401 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) queued for now",
2403 parse->priv->buffers_queued =
2404 g_slist_prepend (parse->priv->buffers_queued, buffer);
2408 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s",
2409 size, gst_flow_get_name (ret));
2410 gst_buffer_unref (buffer);
2411 /* if we are not sufficiently in control, let upstream decide on EOS */
2412 if (ret == GST_FLOW_EOS && !parse->priv->disable_passthrough &&
2413 (parse->priv->passthrough ||
2414 (parse->priv->pad_mode == GST_PAD_MODE_PUSH &&
2415 !parse->priv->upstream_seekable)))
2419 /* Update current running segment position */
2420 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
2421 parse->segment.position < last_stop)
2422 parse->segment.position = last_stop;
2429 if (GST_PAD_IS_FLUSHING (parse->srcpad))
2430 return GST_FLOW_FLUSHING;
2432 GST_ELEMENT_ERROR (parse, STREAM, DECODE, ("No caps set"), (NULL));
2433 return GST_FLOW_ERROR;
2438 * gst_base_parse_finish_frame:
2439 * @parse: a #GstBaseParse
2440 * @frame: a #GstBaseParseFrame
2441 * @size: consumed input data represented by frame
2443 * Collects parsed data and pushes this downstream.
2444 * Source pad caps must be set when this is called.
2446 * If @frame's out_buffer is set, that will be used as subsequent frame data.
2447 * Otherwise, @size samples will be taken from the input and used for output,
2448 * and the output's metadata (timestamps etc) will be taken as (optionally)
2449 * set by the subclass on @frame's (input) buffer (which is otherwise
2450 * ignored for any but the above purpose/information).
2452 * Note that the latter buffer is invalidated by this call, whereas the
2453 * caller retains ownership of @frame.
2455 * Returns: a #GstFlowReturn that should be escalated to caller (of caller)
2458 gst_base_parse_finish_frame (GstBaseParse * parse, GstBaseParseFrame * frame,
2461 GstFlowReturn ret = GST_FLOW_OK;
2463 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2464 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
2465 g_return_val_if_fail (size > 0 || frame->out_buffer, GST_FLOW_ERROR);
2466 g_return_val_if_fail (gst_adapter_available (parse->priv->adapter) >= size,
2469 GST_LOG_OBJECT (parse, "finished frame at offset %" G_GUINT64_FORMAT ", "
2470 "flushing size %d", frame->offset, size);
2472 /* some one-time start-up */
2473 if (G_UNLIKELY (parse->priv->framecount == 0)) {
2474 gst_base_parse_check_seekability (parse);
2475 gst_base_parse_check_upstream (parse);
2478 parse->priv->flushed += size;
2480 if (parse->priv->scanning && frame->buffer) {
2481 if (!parse->priv->scanned_frame) {
2482 parse->priv->scanned_frame = gst_base_parse_frame_copy (frame);
2487 /* either PUSH or PULL mode arranges for adapter data */
2488 /* ensure output buffer */
2489 if (!frame->out_buffer) {
2490 GstBuffer *src, *dest;
2492 frame->out_buffer = gst_adapter_take_buffer (parse->priv->adapter, size);
2493 dest = frame->out_buffer;
2494 src = frame->buffer;
2495 GST_BUFFER_PTS (dest) = GST_BUFFER_PTS (src);
2496 GST_BUFFER_DTS (dest) = GST_BUFFER_DTS (src);
2497 GST_BUFFER_OFFSET (dest) = GST_BUFFER_OFFSET (src);
2498 GST_BUFFER_DURATION (dest) = GST_BUFFER_DURATION (src);
2499 GST_BUFFER_OFFSET_END (dest) = GST_BUFFER_OFFSET_END (src);
2500 GST_MINI_OBJECT_FLAGS (dest) = GST_MINI_OBJECT_FLAGS (src);
2502 gst_adapter_flush (parse->priv->adapter, size);
2505 /* use as input for subsequent processing */
2506 gst_buffer_replace (&frame->buffer, frame->out_buffer);
2507 gst_buffer_unref (frame->out_buffer);
2508 frame->out_buffer = NULL;
2510 /* mark input size consumed */
2513 /* subclass might queue frames/data internally if it needs more
2514 * frames to decide on the format, or might request us to queue here. */
2515 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_DROP) {
2516 gst_buffer_replace (&frame->buffer, NULL);
2518 } else if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_QUEUE) {
2519 GstBaseParseFrame *copy;
2521 copy = gst_base_parse_frame_copy (frame);
2522 copy->flags &= ~GST_BASE_PARSE_FRAME_FLAG_QUEUE;
2523 gst_base_parse_queue_frame (parse, copy);
2527 ret = gst_base_parse_handle_and_push_frame (parse, frame);
2533 /* gst_base_parse_drain:
2535 * Drains the adapter until it is empty. It decreases the min_frame_size to
2536 * match the current adapter size and calls chain method until the adapter
2537 * is emptied or chain returns with error.
2540 gst_base_parse_drain (GstBaseParse * parse)
2544 GST_DEBUG_OBJECT (parse, "draining");
2545 parse->priv->drain = TRUE;
2548 avail = gst_adapter_available (parse->priv->adapter);
2552 if (gst_base_parse_chain (parse->sinkpad, GST_OBJECT_CAST (parse),
2553 NULL) != GST_FLOW_OK) {
2557 /* nothing changed, maybe due to truncated frame; break infinite loop */
2558 if (avail == gst_adapter_available (parse->priv->adapter)) {
2559 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
2560 gst_adapter_clear (parse->priv->adapter);
2564 parse->priv->drain = FALSE;
2567 /* gst_base_parse_send_buffers
2569 * Sends buffers collected in send_buffers downstream, and ensures that list
2570 * is empty at the end (errors or not).
2572 static GstFlowReturn
2573 gst_base_parse_send_buffers (GstBaseParse * parse)
2575 GSList *send = NULL;
2577 GstFlowReturn ret = GST_FLOW_OK;
2578 gboolean first = TRUE;
2580 send = parse->priv->buffers_send;
2584 buf = GST_BUFFER_CAST (send->data);
2585 GST_LOG_OBJECT (parse, "pushing buffer %p, dts %"
2586 GST_TIME_FORMAT ", pts %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2587 ", offset %" G_GINT64_FORMAT, buf,
2588 GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
2589 GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
2590 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2592 /* Make sure the first buffer is always DISCONT. If we split
2593 * GOPs inside the parser this is otherwise not guaranteed */
2595 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
2599 /* iterate output queue an push downstream */
2600 ret = gst_pad_push (parse->srcpad, buf);
2601 send = g_slist_delete_link (send, send);
2603 /* clear any leftover if error */
2604 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2606 buf = GST_BUFFER_CAST (send->data);
2607 gst_buffer_unref (buf);
2608 send = g_slist_delete_link (send, send);
2613 parse->priv->buffers_send = send;
2618 /* gst_base_parse_start_fragment:
2620 * Prepares for processing a reverse playback (forward) fragment
2621 * by (re)setting proper state variables.
2623 static GstFlowReturn
2624 gst_base_parse_start_fragment (GstBaseParse * parse)
2626 GST_LOG_OBJECT (parse, "starting fragment");
2628 /* invalidate so no fall-back timestamping is performed;
2629 * ok if taken from subclass or upstream */
2630 parse->priv->next_pts = GST_CLOCK_TIME_NONE;
2631 parse->priv->prev_pts = GST_CLOCK_TIME_NONE;
2632 parse->priv->next_dts = GST_CLOCK_TIME_NONE;
2633 parse->priv->prev_dts = GST_CLOCK_TIME_NONE;
2634 /* prevent it hanging around stop all the time */
2635 parse->segment.position = GST_CLOCK_TIME_NONE;
2637 parse->priv->discont = TRUE;
2639 /* head of previous fragment is now pending tail of current fragment */
2640 parse->priv->buffers_pending = parse->priv->buffers_head;
2641 parse->priv->buffers_head = NULL;
2647 /* gst_base_parse_finish_fragment:
2649 * Processes a reverse playback (forward) fragment:
2650 * - append head of last fragment that was skipped to current fragment data
2651 * - drain the resulting current fragment data (i.e. repeated chain)
2652 * - add time/duration (if needed) to frames queued by chain
2653 * - push queued data
2655 static GstFlowReturn
2656 gst_base_parse_finish_fragment (GstBaseParse * parse, gboolean prev_head)
2659 GstFlowReturn ret = GST_FLOW_OK;
2660 gboolean seen_key = FALSE, seen_delta = FALSE;
2662 GST_LOG_OBJECT (parse, "finishing fragment");
2665 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2666 while (parse->priv->buffers_pending) {
2667 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2669 GST_LOG_OBJECT (parse, "adding pending buffer (size %" G_GSIZE_FORMAT ")",
2670 gst_buffer_get_size (buf));
2671 gst_adapter_push (parse->priv->adapter, buf);
2673 GST_LOG_OBJECT (parse, "discarding head buffer");
2674 gst_buffer_unref (buf);
2676 parse->priv->buffers_pending =
2677 g_slist_delete_link (parse->priv->buffers_pending,
2678 parse->priv->buffers_pending);
2681 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2682 /* initial skipped data is added to buffers_pending */
2683 gst_base_parse_drain (parse);
2685 if (parse->priv->buffers_send) {
2686 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2687 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2690 /* add metadata (if needed to queued buffers */
2691 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2692 GST_TIME_ARGS (parse->priv->last_pts));
2693 while (parse->priv->buffers_queued) {
2694 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2696 /* no touching if upstream or parsing provided time */
2697 if (GST_BUFFER_PTS_IS_VALID (buf)) {
2698 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2699 GST_TIME_ARGS (GST_BUFFER_PTS (buf)));
2700 } else if (GST_BUFFER_DURATION_IS_VALID (buf)) {
2701 if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_pts)) {
2702 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_pts))
2703 parse->priv->last_pts -= GST_BUFFER_DURATION (buf);
2705 parse->priv->last_pts = 0;
2706 GST_BUFFER_PTS (buf) = parse->priv->last_pts;
2707 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2708 GST_TIME_ARGS (GST_BUFFER_PTS (buf)));
2710 if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_dts)) {
2711 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_dts))
2712 parse->priv->last_dts -= GST_BUFFER_DURATION (buf);
2714 parse->priv->last_dts = 0;
2715 GST_BUFFER_DTS (buf) = parse->priv->last_dts;
2716 GST_LOG_OBJECT (parse, "applied dts %" GST_TIME_FORMAT,
2717 GST_TIME_ARGS (GST_BUFFER_DTS (buf)));
2720 /* no idea, very bad */
2721 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2724 parse->priv->last_pts = GST_BUFFER_PTS (buf);
2725 parse->priv->last_dts = GST_BUFFER_DTS (buf);
2727 /* reverse order for ascending sending */
2728 /* send downstream at keyframe not preceded by a keyframe
2729 * (e.g. that should identify start of collection of IDR nals) */
2730 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2732 ret = gst_base_parse_send_buffers (parse);
2733 /* if a problem, throw all to sending */
2734 if (ret != GST_FLOW_OK) {
2735 parse->priv->buffers_send =
2736 g_slist_reverse (parse->priv->buffers_queued);
2737 parse->priv->buffers_queued = NULL;
2747 parse->priv->buffers_send =
2748 g_slist_prepend (parse->priv->buffers_send, buf);
2749 parse->priv->buffers_queued =
2750 g_slist_delete_link (parse->priv->buffers_queued,
2751 parse->priv->buffers_queued);
2754 /* audio may have all marked as keyframe, so arrange to send here. Also
2755 * we might have ended the loop above on a keyframe, in which case we
2757 if (!seen_delta || seen_key)
2758 ret = gst_base_parse_send_buffers (parse);
2760 /* any trailing unused no longer usable (ideally none) */
2761 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2762 GST_DEBUG_OBJECT (parse, "discarding %" G_GSIZE_FORMAT " trailing bytes",
2763 gst_adapter_available (parse->priv->adapter));
2764 gst_adapter_clear (parse->priv->adapter);
2770 /* small helper that checks whether we have been trying to resync too long */
2771 static inline GstFlowReturn
2772 gst_base_parse_check_sync (GstBaseParse * parse)
2774 if (G_UNLIKELY (parse->priv->discont &&
2775 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2776 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2777 ("Failed to parse stream"), (NULL));
2778 return GST_FLOW_ERROR;
2784 static GstFlowReturn
2785 gst_base_parse_process_streamheader (GstBaseParse * parse)
2789 const GValue *value;
2790 GstFlowReturn ret = GST_FLOW_OK;
2792 caps = gst_pad_get_current_caps (GST_BASE_PARSE_SINK_PAD (parse));
2796 str = gst_caps_get_structure (caps, 0);
2797 value = gst_structure_get_value (str, "streamheader");
2801 GST_DEBUG_OBJECT (parse, "Found streamheader field on input caps");
2803 if (GST_VALUE_HOLDS_ARRAY (value)) {
2805 gsize len = gst_value_array_get_size (value);
2807 for (i = 0; i < len; i++) {
2809 gst_value_get_buffer (gst_value_array_get_value (value, i));
2811 gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2812 GST_OBJECT_CAST (parse), gst_buffer_ref (buffer));
2815 } else if (GST_VALUE_HOLDS_BUFFER (value)) {
2816 GstBuffer *buffer = gst_value_get_buffer (value);
2818 gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2819 GST_OBJECT_CAST (parse), gst_buffer_ref (buffer));
2822 gst_caps_unref (caps);
2829 gst_caps_unref (caps);
2832 GST_DEBUG_OBJECT (parse, "No streamheader on caps");
2837 static GstFlowReturn
2838 gst_base_parse_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2840 GstBaseParseClass *bclass;
2841 GstBaseParse *parse;
2842 GstFlowReturn ret = GST_FLOW_OK;
2843 GstFlowReturn old_ret = GST_FLOW_OK;
2844 GstBuffer *tmpbuf = NULL;
2848 GstClockTime pts, dts;
2850 parse = GST_BASE_PARSE (parent);
2851 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2852 GST_DEBUG_OBJECT (parent, "chain");
2854 /* early out for speed, if we need to skip */
2855 if (buffer && GST_BUFFER_IS_DISCONT (buffer))
2856 parse->priv->skip = 0;
2857 if (parse->priv->skip > 0) {
2858 gsize bsize = gst_buffer_get_size (buffer);
2859 GST_DEBUG ("Got %" G_GSIZE_FORMAT " buffer, need to skip %u", bsize,
2861 if (parse->priv->skip >= bsize) {
2862 parse->priv->skip -= bsize;
2863 GST_DEBUG ("All the buffer is skipped");
2864 parse->priv->offset += bsize;
2865 parse->priv->sync_offset = parse->priv->offset;
2868 buffer = gst_buffer_make_writable (buffer);
2869 gst_buffer_resize (buffer, parse->priv->skip, bsize - parse->priv->skip);
2870 parse->priv->offset += parse->priv->skip;
2871 GST_DEBUG ("Done skipping, we have %u left on this buffer",
2872 (unsigned) (bsize - parse->priv->skip));
2873 parse->priv->skip = 0;
2874 parse->priv->discont = TRUE;
2877 if (G_UNLIKELY (parse->priv->first_buffer)) {
2878 parse->priv->first_buffer = FALSE;
2879 if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_HEADER)) {
2880 /* this stream has no header buffers, check if we just prepend the
2881 * streamheader from caps to the stream */
2882 GST_DEBUG_OBJECT (parse, "Looking for streamheader field on caps to "
2883 "prepend to the stream");
2884 gst_base_parse_process_streamheader (parse);
2886 GST_DEBUG_OBJECT (parse, "Stream has header buffers, not prepending "
2887 "streamheader from caps");
2891 if (parse->priv->detecting) {
2892 GstBuffer *detect_buf;
2894 if (parse->priv->detect_buffers_size == 0) {
2895 detect_buf = gst_buffer_ref (buffer);
2900 detect_buf = gst_buffer_new ();
2902 for (l = parse->priv->detect_buffers; l; l = l->next) {
2903 gsize tmpsize = gst_buffer_get_size (l->data);
2905 gst_buffer_copy_into (detect_buf, GST_BUFFER_CAST (l->data),
2906 GST_BUFFER_COPY_MEMORY, offset, tmpsize);
2910 gst_buffer_copy_into (detect_buf, buffer, GST_BUFFER_COPY_MEMORY,
2911 offset, gst_buffer_get_size (buffer));
2914 ret = bclass->detect (parse, detect_buf);
2915 gst_buffer_unref (detect_buf);
2917 if (ret == GST_FLOW_OK) {
2920 /* Detected something */
2921 parse->priv->detecting = FALSE;
2923 for (l = parse->priv->detect_buffers; l; l = l->next) {
2924 if (ret == GST_FLOW_OK && !parse->priv->flushing)
2926 gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2927 parent, GST_BUFFER_CAST (l->data));
2929 gst_buffer_unref (GST_BUFFER_CAST (l->data));
2931 g_list_free (parse->priv->detect_buffers);
2932 parse->priv->detect_buffers = NULL;
2933 parse->priv->detect_buffers_size = 0;
2935 if (ret != GST_FLOW_OK) {
2939 /* Handle the current buffer */
2940 } else if (ret == GST_FLOW_NOT_NEGOTIATED) {
2941 /* Still detecting, append buffer or error out if draining */
2943 if (parse->priv->drain) {
2944 GST_DEBUG_OBJECT (parse, "Draining but did not detect format yet");
2945 return GST_FLOW_ERROR;
2946 } else if (parse->priv->flushing) {
2947 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref,
2949 g_list_free (parse->priv->detect_buffers);
2950 parse->priv->detect_buffers = NULL;
2951 parse->priv->detect_buffers_size = 0;
2953 parse->priv->detect_buffers =
2954 g_list_append (parse->priv->detect_buffers, buffer);
2955 parse->priv->detect_buffers_size += gst_buffer_get_size (buffer);
2959 /* Something went wrong, subclass responsible for error reporting */
2963 /* And now handle the current buffer if detection worked */
2966 if (G_LIKELY (buffer)) {
2967 GST_LOG_OBJECT (parse,
2968 "buffer size: %" G_GSIZE_FORMAT ", offset = %" G_GINT64_FORMAT
2969 ", dts %" GST_TIME_FORMAT ", pts %" GST_TIME_FORMAT,
2970 gst_buffer_get_size (buffer), GST_BUFFER_OFFSET (buffer),
2971 GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
2972 GST_TIME_ARGS (GST_BUFFER_PTS (buffer)));
2974 if (G_UNLIKELY (!parse->priv->disable_passthrough
2975 && parse->priv->passthrough)) {
2976 GstBaseParseFrame frame;
2978 gst_base_parse_frame_init (&frame);
2979 frame.buffer = gst_buffer_make_writable (buffer);
2980 ret = gst_base_parse_push_frame (parse, &frame);
2981 gst_base_parse_frame_free (&frame);
2984 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2985 /* upstream feeding us in reverse playback;
2986 * finish previous fragment and start new upon DISCONT */
2987 if (parse->segment.rate < 0.0) {
2988 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2989 ret = gst_base_parse_finish_fragment (parse, TRUE);
2990 gst_base_parse_start_fragment (parse);
2992 /* discont in the stream, drain and mark discont for next output */
2993 gst_base_parse_drain (parse);
2994 parse->priv->discont = TRUE;
2997 gst_adapter_push (parse->priv->adapter, buffer);
3000 /* Parse and push as many frames as possible */
3001 /* Stop either when adapter is empty or we are flushing */
3002 while (!parse->priv->flushing) {
3005 /* note: if subclass indicates MAX fsize,
3006 * this will not likely be available anyway ... */
3007 min_size = MAX (parse->priv->min_frame_size, fsize);
3008 av = gst_adapter_available (parse->priv->adapter);
3010 if (G_UNLIKELY (parse->priv->drain)) {
3012 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
3013 if (G_UNLIKELY (!min_size)) {
3018 /* Collect at least min_frame_size bytes */
3019 if (av < min_size) {
3020 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)", av);
3024 /* move along with upstream timestamp (if any),
3025 * but interpolate in between */
3026 pts = gst_adapter_prev_pts (parse->priv->adapter, NULL);
3027 dts = gst_adapter_prev_dts (parse->priv->adapter, NULL);
3028 if (GST_CLOCK_TIME_IS_VALID (pts) && (parse->priv->prev_pts != pts))
3029 parse->priv->prev_pts = parse->priv->next_pts = pts;
3031 if (GST_CLOCK_TIME_IS_VALID (dts) && (parse->priv->prev_dts != dts))
3032 parse->priv->prev_dts = parse->priv->next_dts = dts;
3034 /* we can mess with, erm interpolate, timestamps,
3035 * and incoming stuff has PTS but no DTS seen so far,
3036 * then pick up DTS from PTS and hope for the best ... */
3037 if (parse->priv->infer_ts &&
3038 parse->priv->pts_interpolate &&
3039 !GST_CLOCK_TIME_IS_VALID (dts) &&
3040 !GST_CLOCK_TIME_IS_VALID (parse->priv->prev_dts) &&
3041 GST_CLOCK_TIME_IS_VALID (pts))
3042 parse->priv->next_dts = pts;
3044 /* always pass all available data */
3045 tmpbuf = gst_adapter_get_buffer (parse->priv->adapter, av);
3047 /* already inform subclass what timestamps we have planned,
3048 * at least if provided by time-based upstream */
3049 if (parse->priv->upstream_format == GST_FORMAT_TIME) {
3050 tmpbuf = gst_buffer_make_writable (tmpbuf);
3051 GST_BUFFER_PTS (tmpbuf) = parse->priv->next_pts;
3052 GST_BUFFER_DTS (tmpbuf) = parse->priv->next_dts;
3053 GST_BUFFER_DURATION (tmpbuf) = GST_CLOCK_TIME_NONE;
3056 /* keep the adapter mapped, so keep track of what has to be flushed */
3057 ret = gst_base_parse_handle_buffer (parse, tmpbuf, &skip, &flush);
3060 if (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED) {
3063 if (skip == 0 && flush == 0) {
3064 GST_LOG_OBJECT (parse, "nothing skipped and no frames finished, "
3065 "breaking to get more data");
3066 /* ignore this return as it produced no data */
3074 GST_LOG_OBJECT (parse, "chain leaving");
3078 /* pull @size bytes at current offset,
3079 * i.e. at least try to and possibly return a shorter buffer if near the end */
3080 static GstFlowReturn
3081 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
3082 GstBuffer ** buffer)
3084 GstFlowReturn ret = GST_FLOW_OK;
3086 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
3088 /* Caching here actually makes much less difference than one would expect.
3089 * We do it mainly to avoid pulling buffers of 1 byte all the time */
3090 if (parse->priv->cache) {
3091 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
3092 gint cache_size = gst_buffer_get_size (parse->priv->cache);
3094 if (cache_offset <= parse->priv->offset &&
3095 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
3096 *buffer = gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL,
3097 parse->priv->offset - cache_offset, size);
3098 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
3101 /* not enough data in the cache, free cache and get a new one */
3102 gst_buffer_unref (parse->priv->cache);
3103 parse->priv->cache = NULL;
3106 /* refill the cache */
3108 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
3109 64 * 1024), &parse->priv->cache);
3110 if (ret != GST_FLOW_OK) {
3111 parse->priv->cache = NULL;
3115 if (gst_buffer_get_size (parse->priv->cache) >= size) {
3117 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0,
3119 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
3123 /* Not possible to get enough data, try a last time with
3124 * requesting exactly the size we need */
3125 gst_buffer_unref (parse->priv->cache);
3126 parse->priv->cache = NULL;
3128 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
3129 &parse->priv->cache);
3131 if (ret != GST_FLOW_OK) {
3132 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
3137 if (gst_buffer_get_size (parse->priv->cache) < size) {
3138 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
3139 G_GUINT64_FORMAT ": wanted %u bytes, got %" G_GSIZE_FORMAT " bytes",
3140 parse->priv->offset, size, gst_buffer_get_size (parse->priv->cache));
3142 *buffer = parse->priv->cache;
3143 parse->priv->cache = NULL;
3149 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0, size);
3150 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
3155 static GstFlowReturn
3156 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
3159 GstClockTime ts = 0;
3163 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
3164 ", last_offset = %" G_GINT64_FORMAT,
3165 GST_TIME_ARGS (parse->priv->last_pts), parse->priv->last_offset);
3167 if (!parse->priv->last_offset
3168 || parse->priv->last_pts <= parse->segment.start) {
3169 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
3170 GST_TIME_ARGS (parse->segment.start));
3175 /* last fragment started at last_offset / last_ts;
3176 * seek back 10s capped at 1MB */
3177 if (parse->priv->last_pts >= 10 * GST_SECOND)
3178 ts = parse->priv->last_pts - 10 * GST_SECOND;
3179 /* if we are exact now, we will be more so going backwards */
3180 if (parse->priv->exact_position) {
3181 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
3183 if (!gst_base_parse_convert (parse, GST_FORMAT_TIME, ts,
3184 GST_FORMAT_BYTES, &offset)) {
3185 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
3188 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
3189 parse->priv->last_offset - 1024);
3190 offset = MAX (0, offset);
3192 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
3194 parse->priv->offset = offset;
3196 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
3198 if (ret != GST_FLOW_OK)
3201 /* offset will increase again as fragment is processed/parsed */
3202 parse->priv->last_offset = offset;
3204 gst_base_parse_start_fragment (parse);
3205 gst_adapter_push (parse->priv->adapter, buffer);
3206 ret = gst_base_parse_finish_fragment (parse, TRUE);
3207 if (ret != GST_FLOW_OK)
3210 /* force previous fragment */
3211 parse->priv->offset = -1;
3218 * pull and scan for next frame starting from current offset
3219 * ajusts sync, drain and offset going along */
3220 static GstFlowReturn
3221 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass)
3224 GstFlowReturn ret = GST_FLOW_OK;
3225 guint fsize, min_size;
3229 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
3230 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
3232 /* let's make this efficient for all subclass once and for all;
3233 * maybe it does not need this much, but in the latter case, we know we are
3234 * in pull mode here and might as well try to read and supply more anyway
3235 * (so does the buffer caching mechanism) */
3239 min_size = MAX (parse->priv->min_frame_size, fsize);
3241 GST_LOG_OBJECT (parse, "reading buffer size %u", min_size);
3243 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
3244 if (ret != GST_FLOW_OK)
3247 /* if we got a short read, inform subclass we are draining leftover
3248 * and no more is to be expected */
3249 if (gst_buffer_get_size (buffer) < min_size) {
3250 GST_LOG_OBJECT (parse, "... but did not get that; marked draining");
3251 parse->priv->drain = TRUE;
3254 if (parse->priv->detecting) {
3255 ret = klass->detect (parse, buffer);
3256 if (ret == GST_FLOW_NOT_NEGOTIATED) {
3257 /* If draining we error out, otherwise request a buffer
3259 if (parse->priv->drain) {
3260 gst_buffer_unref (buffer);
3261 GST_ERROR_OBJECT (parse, "Failed to detect format but draining");
3262 return GST_FLOW_ERROR;
3265 gst_buffer_unref (buffer);
3268 } else if (ret != GST_FLOW_OK) {
3269 gst_buffer_unref (buffer);
3270 GST_ERROR_OBJECT (parse, "detect() returned %s",
3271 gst_flow_get_name (ret));
3275 /* Else handle this buffer normally */
3278 ret = gst_base_parse_handle_buffer (parse, buffer, &skip, &flushed);
3279 if (ret != GST_FLOW_OK)
3282 /* If a large amount of data was requested to be skipped, _handle_buffer
3283 might have set the priv->skip flag to an extra amount on top of skip.
3284 In pull mode, we can just pull from the new offset directly. */
3285 parse->priv->offset += parse->priv->skip;
3286 parse->priv->skip = 0;
3288 /* something flushed means something happened,
3289 * and we should bail out of this loop so as not to occupy
3290 * the task thread indefinitely */
3292 GST_LOG_OBJECT (parse, "frame finished, breaking loop");
3295 /* nothing flushed, no skip and draining, so nothing left to do */
3296 if (!skip && parse->priv->drain) {
3297 GST_LOG_OBJECT (parse, "no activity or result when draining; "
3298 "breaking loop and marking EOS");
3302 /* otherwise, get some more data
3303 * note that is checked this does not happen indefinitely */
3305 GST_LOG_OBJECT (parse, "getting some more data");
3308 parse->priv->drain = FALSE;
3315 /* Loop that is used in pull mode to retrieve data from upstream */
3317 gst_base_parse_loop (GstPad * pad)
3319 GstBaseParse *parse;
3320 GstBaseParseClass *klass;
3321 GstFlowReturn ret = GST_FLOW_OK;
3323 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
3324 klass = GST_BASE_PARSE_GET_CLASS (parse);
3326 GST_LOG_OBJECT (parse, "Entering parse loop");
3328 if (G_UNLIKELY (parse->priv->push_stream_start)) {
3333 gst_pad_create_stream_id (parse->srcpad, GST_ELEMENT_CAST (parse),
3336 event = gst_event_new_stream_start (stream_id);
3337 gst_event_set_group_id (event, gst_util_group_id_next ());
3339 GST_DEBUG_OBJECT (parse, "Pushing STREAM_START");
3340 gst_pad_push_event (parse->srcpad, event);
3341 parse->priv->push_stream_start = FALSE;
3345 /* reverse playback:
3346 * first fragment (closest to stop time) is handled normally below,
3347 * then we pull in fragments going backwards */
3348 if (parse->segment.rate < 0.0) {
3349 /* check if we jumped back to a previous fragment,
3350 * which is a post-first fragment */
3351 if (parse->priv->offset < 0) {
3352 ret = gst_base_parse_handle_previous_fragment (parse);
3357 ret = gst_base_parse_scan_frame (parse, klass);
3359 /* eat expected eos signalling past segment in reverse playback */
3360 if (parse->segment.rate < 0.0 && ret == GST_FLOW_EOS &&
3361 parse->segment.position >= parse->segment.stop) {
3362 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
3363 /* push what was accumulated during loop run */
3364 gst_base_parse_finish_fragment (parse, FALSE);
3365 /* force previous fragment */
3366 parse->priv->offset = -1;
3370 if (ret != GST_FLOW_OK)
3374 if (ret == GST_FLOW_EOS)
3376 else if (ret != GST_FLOW_OK)
3379 gst_object_unref (parse);
3386 GST_DEBUG_OBJECT (parse, "eos");
3391 gboolean push_eos = FALSE;
3393 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
3394 gst_flow_get_name (ret));
3395 gst_pad_pause_task (parse->sinkpad);
3397 if (ret == GST_FLOW_EOS) {
3398 /* handle end-of-stream/segment */
3399 if (parse->segment.flags & GST_SEGMENT_FLAG_SEGMENT) {
3402 if ((stop = parse->segment.stop) == -1)
3403 stop = parse->segment.duration;
3405 GST_DEBUG_OBJECT (parse, "sending segment_done");
3407 gst_element_post_message
3408 (GST_ELEMENT_CAST (parse),
3409 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
3410 GST_FORMAT_TIME, stop));
3411 gst_pad_push_event (parse->srcpad,
3412 gst_event_new_segment_done (GST_FORMAT_TIME, stop));
3414 /* If we STILL have zero frames processed, fire an error */
3415 if (parse->priv->framecount == 0) {
3416 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
3417 ("No valid frames found before end of stream"), (NULL));
3421 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
3422 /* for fatal errors we post an error message, wrong-state is
3423 * not fatal because it happens due to flushes and only means
3424 * that we should stop now. */
3425 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
3426 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
3430 if (parse->priv->estimated_duration <= 0) {
3431 gst_base_parse_update_duration (parse);
3433 /* Push pending events, including SEGMENT events */
3434 gst_base_parse_push_pending_events (parse);
3436 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
3438 gst_object_unref (parse);
3443 gst_base_parse_sink_activate (GstPad * sinkpad, GstObject * parent)
3445 GstSchedulingFlags sched_flags;
3446 GstBaseParse *parse;
3450 parse = GST_BASE_PARSE (parent);
3452 GST_DEBUG_OBJECT (parse, "sink activate");
3454 query = gst_query_new_scheduling ();
3455 if (!gst_pad_peer_query (sinkpad, query)) {
3456 gst_query_unref (query);
3457 goto baseparse_push;
3460 gst_query_parse_scheduling (query, &sched_flags, NULL, NULL, NULL);
3462 pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL)
3463 && ((sched_flags & GST_SCHEDULING_FLAG_SEEKABLE) != 0);
3465 gst_query_unref (query);
3468 goto baseparse_push;
3470 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
3471 if (!gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE))
3472 goto baseparse_push;
3474 parse->priv->push_stream_start = TRUE;
3476 return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
3481 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
3482 return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
3487 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
3489 GstBaseParseClass *klass;
3490 gboolean result = TRUE;
3492 GST_DEBUG_OBJECT (parse, "activate %d", active);
3494 klass = GST_BASE_PARSE_GET_CLASS (parse);
3497 if (parse->priv->pad_mode == GST_PAD_MODE_NONE && klass->start)
3498 result = klass->start (parse);
3500 /* If the subclass implements ::detect we want to
3501 * call it for the first buffers now */
3502 parse->priv->detecting = (klass->detect != NULL);
3504 /* We must make sure streaming has finished before resetting things
3505 * and calling the ::stop vfunc */
3506 GST_PAD_STREAM_LOCK (parse->sinkpad);
3507 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3509 if (parse->priv->pad_mode != GST_PAD_MODE_NONE && klass->stop)
3510 result = klass->stop (parse);
3512 parse->priv->pad_mode = GST_PAD_MODE_NONE;
3514 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
3519 gst_base_parse_sink_activate_mode (GstPad * pad, GstObject * parent,
3520 GstPadMode mode, gboolean active)
3523 GstBaseParse *parse;
3525 parse = GST_BASE_PARSE (parent);
3527 GST_DEBUG_OBJECT (parse, "sink %sactivate in %s mode",
3528 (active) ? "" : "de", gst_pad_mode_get_name (mode));
3530 if (!gst_base_parse_activate (parse, active))
3531 goto activate_failed;
3534 case GST_PAD_MODE_PULL:
3536 parse->priv->pending_events =
3537 g_list_prepend (parse->priv->pending_events,
3538 gst_event_new_segment (&parse->segment));
3541 result = gst_pad_stop_task (pad);
3549 parse->priv->pad_mode = active ? mode : GST_PAD_MODE_NONE;
3551 GST_DEBUG_OBJECT (parse, "sink activate return: %d", result);
3558 GST_DEBUG_OBJECT (parse, "activate failed");
3564 * gst_base_parse_set_duration:
3565 * @parse: #GstBaseParse.
3567 * @duration: duration value.
3568 * @interval: how often to update the duration estimate based on bitrate, or 0.
3570 * Sets the duration of the currently playing media. Subclass can use this
3571 * when it is able to determine duration and/or notices a change in the media
3572 * duration. Alternatively, if @interval is non-zero (default), then stream
3573 * duration is determined based on estimated bitrate, and updated every @interval
3577 gst_base_parse_set_duration (GstBaseParse * parse,
3578 GstFormat fmt, gint64 duration, gint interval)
3580 g_return_if_fail (parse != NULL);
3582 if (parse->priv->upstream_has_duration) {
3583 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
3587 if (duration != parse->priv->duration) {
3590 m = gst_message_new_duration_changed (GST_OBJECT (parse));
3591 gst_element_post_message (GST_ELEMENT (parse), m);
3593 /* TODO: what about duration tag? */
3595 parse->priv->duration = duration;
3596 parse->priv->duration_fmt = fmt;
3597 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
3598 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
3599 if (interval != 0) {
3600 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
3604 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
3605 parse->priv->update_interval = interval;
3611 * gst_base_parse_set_average_bitrate:
3612 * @parse: #GstBaseParse.
3613 * @bitrate: average bitrate in bits/second
3615 * Optionally sets the average bitrate detected in media (if non-zero),
3616 * e.g. based on metadata, as it will be posted to the application.
3618 * By default, announced average bitrate is estimated. The average bitrate
3619 * is used to estimate the total duration of the stream and to estimate
3620 * a seek position, if there's no index and the format is syncable
3621 * (see gst_base_parse_set_syncable()).
3624 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
3626 parse->priv->bitrate = bitrate;
3627 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
3631 * gst_base_parse_set_min_frame_size:
3632 * @parse: #GstBaseParse.
3633 * @min_size: Minimum size of the data that this base class should give to
3636 * Subclass can use this function to tell the base class that it needs to
3637 * give at least #min_size buffers.
3640 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
3642 g_return_if_fail (parse != NULL);
3644 parse->priv->min_frame_size = min_size;
3645 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
3649 * gst_base_parse_set_frame_rate:
3650 * @parse: the #GstBaseParse to set
3651 * @fps_num: frames per second (numerator).
3652 * @fps_den: frames per second (denominator).
3653 * @lead_in: frames needed before a segment for subsequent decode
3654 * @lead_out: frames needed after a segment
3656 * If frames per second is configured, parser can take care of buffer duration
3657 * and timestamping. When performing segment clipping, or seeking to a specific
3658 * location, a corresponding decoder might need an initial @lead_in and a
3659 * following @lead_out number of frames to ensure the desired segment is
3660 * entirely filled upon decoding.
3663 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
3664 guint fps_den, guint lead_in, guint lead_out)
3666 g_return_if_fail (parse != NULL);
3668 parse->priv->fps_num = fps_num;
3669 parse->priv->fps_den = fps_den;
3670 if (!fps_num || !fps_den) {
3671 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
3673 fps_num = fps_den = 0;
3674 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
3675 parse->priv->lead_in = parse->priv->lead_out = 0;
3676 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
3678 parse->priv->frame_duration =
3679 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
3680 parse->priv->lead_in = lead_in;
3681 parse->priv->lead_out = lead_out;
3682 parse->priv->lead_in_ts =
3683 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
3684 parse->priv->lead_out_ts =
3685 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
3686 /* aim for about 1.5s to estimate duration */
3687 if (parse->priv->update_interval < 0) {
3688 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
3689 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
3690 parse->priv->update_interval);
3693 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
3694 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
3695 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
3696 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
3697 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
3698 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
3702 * gst_base_parse_set_has_timing_info:
3703 * @parse: a #GstBaseParse
3704 * @has_timing: whether frames carry timing information
3706 * Set if frames carry timing information which the subclass can (generally)
3707 * parse and provide. In particular, intrinsic (rather than estimated) time
3708 * can be obtained following a seek.
3711 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3713 parse->priv->has_timing_info = has_timing;
3714 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3718 * gst_base_parse_set_syncable:
3719 * @parse: a #GstBaseParse
3720 * @syncable: set if frame starts can be identified
3722 * Set if frame starts can be identified. This is set by default and
3723 * determines whether seeking based on bitrate averages
3724 * is possible for a format/stream.
3727 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3729 parse->priv->syncable = syncable;
3730 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3734 * gst_base_parse_set_passthrough:
3735 * @parse: a #GstBaseParse
3736 * @passthrough: %TRUE if parser should run in passthrough mode
3738 * Set if the nature of the format or configuration does not allow (much)
3739 * parsing, and the parser should operate in passthrough mode (which only
3740 * applies when operating in push mode). That is, incoming buffers are
3741 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3742 * callbacks will be invoked, but @pre_push_frame will still be invoked,
3743 * so subclass can perform as much or as little is appropriate for
3744 * passthrough semantics in @pre_push_frame.
3747 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3749 parse->priv->passthrough = passthrough;
3750 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3754 * gst_base_parse_set_pts_interpolation:
3755 * @parse: a #GstBaseParse
3756 * @pts_interpolate: %TRUE if parser should interpolate PTS timestamps
3758 * By default, the base class will guess PTS timestamps using a simple
3759 * interpolation (previous timestamp + duration), which is incorrect for
3760 * data streams with reordering, where PTS can go backward. Sub-classes
3761 * implementing such formats should disable PTS interpolation.
3764 gst_base_parse_set_pts_interpolation (GstBaseParse * parse,
3765 gboolean pts_interpolate)
3767 parse->priv->pts_interpolate = pts_interpolate;
3768 GST_INFO_OBJECT (parse, "PTS interpolation: %s",
3769 (pts_interpolate) ? "yes" : "no");
3773 * gst_base_parse_set_infer_ts:
3774 * @parse: a #GstBaseParse
3775 * @infer_ts: %TRUE if parser should infer DTS/PTS from each other
3777 * By default, the base class might try to infer PTS from DTS and vice
3778 * versa. While this is generally correct for audio data, it may not
3779 * be otherwise. Sub-classes implementing such formats should disable
3780 * timestamp inferring.
3783 gst_base_parse_set_infer_ts (GstBaseParse * parse, gboolean infer_ts)
3785 parse->priv->infer_ts = infer_ts;
3786 GST_INFO_OBJECT (parse, "TS inferring: %s", (infer_ts) ? "yes" : "no");
3790 * gst_base_parse_set_latency:
3791 * @parse: a #GstBaseParse
3792 * @min_latency: minimum parse latency
3793 * @max_latency: maximum parse latency
3795 * Sets the minimum and maximum (which may likely be equal) latency introduced
3796 * by the parsing process. If there is such a latency, which depends on the
3797 * particular parsing of the format, it typically corresponds to 1 frame duration.
3800 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3801 GstClockTime max_latency)
3803 g_return_if_fail (min_latency != GST_CLOCK_TIME_NONE);
3804 g_return_if_fail (min_latency <= max_latency);
3806 GST_OBJECT_LOCK (parse);
3807 parse->priv->min_latency = min_latency;
3808 parse->priv->max_latency = max_latency;
3809 GST_OBJECT_UNLOCK (parse);
3810 GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3811 GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3812 GST_TIME_ARGS (max_latency));
3816 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3817 GstClockTime * duration)
3819 gboolean res = FALSE;
3821 g_return_val_if_fail (duration != NULL, FALSE);
3823 *duration = GST_CLOCK_TIME_NONE;
3824 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3825 GST_LOG_OBJECT (parse, "using provided duration");
3826 *duration = parse->priv->duration;
3828 } else if (parse->priv->duration != -1) {
3829 GST_LOG_OBJECT (parse, "converting provided duration");
3830 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3831 parse->priv->duration, format, (gint64 *) duration);
3832 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3833 GST_LOG_OBJECT (parse, "using estimated duration");
3834 *duration = parse->priv->estimated_duration;
3837 GST_LOG_OBJECT (parse, "cannot estimate duration");
3840 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3841 GST_TIME_ARGS (*duration));
3846 gst_base_parse_src_query_default (GstBaseParse * parse, GstQuery * query)
3848 gboolean res = FALSE;
3851 pad = GST_BASE_PARSE_SRC_PAD (parse);
3853 switch (GST_QUERY_TYPE (query)) {
3854 case GST_QUERY_POSITION:
3859 GST_DEBUG_OBJECT (parse, "position query");
3860 gst_query_parse_position (query, &format, NULL);
3862 /* try upstream first */
3863 res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
3865 /* Fall back on interpreting segment */
3866 GST_OBJECT_LOCK (parse);
3867 if (format == GST_FORMAT_BYTES) {
3868 dest_value = parse->priv->offset;
3870 } else if (format == parse->segment.format &&
3871 GST_CLOCK_TIME_IS_VALID (parse->segment.position)) {
3872 dest_value = gst_segment_to_stream_time (&parse->segment,
3873 parse->segment.format, parse->segment.position);
3876 GST_OBJECT_UNLOCK (parse);
3878 /* no precise result, upstream no idea either, then best estimate */
3879 /* priv->offset is updated in both PUSH/PULL modes */
3880 res = gst_base_parse_convert (parse,
3881 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3884 gst_query_set_position (query, format, dest_value);
3888 case GST_QUERY_DURATION:
3891 GstClockTime duration;
3893 GST_DEBUG_OBJECT (parse, "duration query");
3894 gst_query_parse_duration (query, &format, NULL);
3896 /* consult upstream */
3897 res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
3899 /* otherwise best estimate from us */
3901 res = gst_base_parse_get_duration (parse, format, &duration);
3903 gst_query_set_duration (query, format, duration);
3907 case GST_QUERY_SEEKING:
3910 GstClockTime duration = GST_CLOCK_TIME_NONE;
3911 gboolean seekable = FALSE;
3913 GST_DEBUG_OBJECT (parse, "seeking query");
3914 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3916 /* consult upstream */
3917 res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
3919 /* we may be able to help if in TIME */
3920 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3921 gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3922 /* already OK if upstream takes care */
3923 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3925 if (!(res && seekable)) {
3926 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3927 || duration == -1) {
3928 /* seekable if we still have a chance to get duration later on */
3930 parse->priv->upstream_seekable && parse->priv->update_interval;
3932 seekable = parse->priv->upstream_seekable;
3933 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3936 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3942 case GST_QUERY_FORMATS:
3943 gst_query_set_formatsv (query, 3, fmtlist);
3946 case GST_QUERY_CONVERT:
3948 GstFormat src_format, dest_format;
3949 gint64 src_value, dest_value;
3951 gst_query_parse_convert (query, &src_format, &src_value,
3952 &dest_format, &dest_value);
3954 res = gst_base_parse_convert (parse, src_format, src_value,
3955 dest_format, &dest_value);
3957 gst_query_set_convert (query, src_format, src_value,
3958 dest_format, dest_value);
3962 case GST_QUERY_LATENCY:
3964 if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3966 GstClockTime min_latency, max_latency;
3968 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3969 GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3970 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3971 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3973 GST_OBJECT_LOCK (parse);
3974 /* add our latency */
3975 min_latency += parse->priv->min_latency;
3976 if (max_latency == -1 || parse->priv->max_latency == -1)
3979 max_latency += parse->priv->max_latency;
3980 GST_OBJECT_UNLOCK (parse);
3982 gst_query_set_latency (query, live, min_latency, max_latency);
3986 case GST_QUERY_SEGMENT:
3991 format = parse->segment.format;
3994 gst_segment_to_stream_time (&parse->segment, format,
3995 parse->segment.start);
3996 if ((stop = parse->segment.stop) == -1)
3997 stop = parse->segment.duration;
3999 stop = gst_segment_to_stream_time (&parse->segment, format, stop);
4001 gst_query_set_segment (query, parse->segment.rate, format, start, stop);
4006 res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
4012 /* scans for a cluster start from @pos,
4013 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
4014 static GstFlowReturn
4015 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
4016 GstClockTime * time, GstClockTime * duration)
4018 GstBaseParseClass *klass;
4020 gboolean orig_drain, orig_discont;
4021 GstFlowReturn ret = GST_FLOW_OK;
4022 GstBuffer *buf = NULL;
4023 GstBaseParseFrame *sframe = NULL;
4025 g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
4026 g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
4027 g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
4029 klass = GST_BASE_PARSE_GET_CLASS (parse);
4031 *time = GST_CLOCK_TIME_NONE;
4032 *duration = GST_CLOCK_TIME_NONE;
4035 orig_offset = parse->priv->offset;
4036 orig_discont = parse->priv->discont;
4037 orig_drain = parse->priv->drain;
4039 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
4040 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
4042 /* jump elsewhere and locate next frame */
4043 parse->priv->offset = *pos;
4044 /* mark as scanning so frames don't get processed all the way */
4045 parse->priv->scanning = TRUE;
4046 ret = gst_base_parse_scan_frame (parse, klass);
4047 parse->priv->scanning = FALSE;
4048 /* retrieve frame found during scan */
4049 sframe = parse->priv->scanned_frame;
4050 parse->priv->scanned_frame = NULL;
4052 if (ret != GST_FLOW_OK || !sframe)
4055 /* get offset first, subclass parsing might dump other stuff in there */
4056 *pos = sframe->offset;
4057 buf = sframe->buffer;
4060 /* but it should provide proper time */
4061 *time = GST_BUFFER_TIMESTAMP (buf);
4062 *duration = GST_BUFFER_DURATION (buf);
4064 GST_LOG_OBJECT (parse,
4065 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
4066 GST_TIME_ARGS (*time), *pos);
4070 gst_base_parse_frame_free (sframe);
4073 parse->priv->offset = orig_offset;
4074 parse->priv->discont = orig_discont;
4075 parse->priv->drain = orig_drain;
4080 /* bisect and scan through file for frame starting before @time,
4081 * returns OK and @time/@offset if found, NONE and/or error otherwise
4082 * If @time == G_MAXINT64, scan for duration ( == last frame) */
4083 static GstFlowReturn
4084 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
4087 GstFlowReturn ret = GST_FLOW_OK;
4088 gint64 lpos, hpos, newpos;
4089 GstClockTime time, ltime, htime, newtime, dur;
4090 gboolean cont = TRUE;
4091 const GstClockTime tolerance = TARGET_DIFFERENCE;
4092 const guint chunk = 4 * 1024;
4094 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
4095 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
4097 GST_DEBUG_OBJECT (parse, "Bisecting for time %" GST_TIME_FORMAT,
4098 GST_TIME_ARGS (*_time));
4100 /* TODO also make keyframe aware if useful some day */
4115 /* do not know at first */
4117 *_time = GST_CLOCK_TIME_NONE;
4119 /* need initial positions; start and end */
4120 lpos = parse->priv->first_frame_offset;
4121 ltime = parse->priv->first_frame_pts;
4122 /* try other one if no luck */
4123 if (!GST_CLOCK_TIME_IS_VALID (ltime))
4124 ltime = parse->priv->first_frame_dts;
4125 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &htime)) {
4126 GST_DEBUG_OBJECT (parse, "Unknown time duration, cannot bisect");
4127 return GST_FLOW_ERROR;
4129 hpos = parse->priv->upstream_size;
4131 GST_DEBUG_OBJECT (parse,
4132 "Bisection initial bounds: bytes %" G_GINT64_FORMAT " %" G_GINT64_FORMAT
4133 ", times %" GST_TIME_FORMAT " %" GST_TIME_FORMAT, lpos, hpos,
4134 GST_TIME_ARGS (ltime), GST_TIME_ARGS (htime));
4136 /* check preconditions are satisfied;
4137 * start and end are needed, except for special case where we scan for
4138 * last frame to determine duration */
4139 if (parse->priv->pad_mode != GST_PAD_MODE_PULL || !hpos ||
4140 !GST_CLOCK_TIME_IS_VALID (ltime) ||
4141 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
4145 /* shortcut cases */
4148 } else if (time < ltime + tolerance) {
4152 } else if (time >= htime) {
4158 while (htime > ltime && cont) {
4159 GST_LOG_OBJECT (parse,
4160 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
4161 GST_TIME_ARGS (ltime));
4162 GST_LOG_OBJECT (parse,
4163 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
4164 GST_TIME_ARGS (htime));
4165 if (G_UNLIKELY (time == G_MAXINT64)) {
4167 } else if (G_LIKELY (hpos > lpos)) {
4169 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
4172 /* should mean lpos == hpos, since lpos <= hpos is invariant */
4174 /* we check this case once, but not forever, so break loop */
4179 newpos = CLAMP (newpos, lpos, hpos);
4180 GST_LOG_OBJECT (parse,
4181 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
4182 GST_TIME_ARGS (time), newpos);
4184 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
4185 if (ret == GST_FLOW_EOS) {
4186 /* heuristic HACK */
4187 hpos = MAX (lpos, hpos - chunk);
4189 } else if (ret != GST_FLOW_OK) {
4193 if (newtime == -1 || newpos == -1) {
4194 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
4198 if (G_UNLIKELY (time == G_MAXINT64)) {
4201 if (GST_CLOCK_TIME_IS_VALID (dur))
4204 } else if (newtime > time) {
4206 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
4208 } else if (newtime + tolerance > time) {
4209 /* close enough undershoot */
4213 } else if (newtime < ltime) {
4214 /* so a position beyond lpos resulted in earlier time than ltime ... */
4215 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
4218 /* undershoot too far */
4219 newpos += newpos == lpos ? chunk : 0;
4220 lpos = CLAMP (newpos, lpos, hpos);
4226 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
4227 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
4232 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
4233 gboolean before, GstClockTime * _ts)
4235 gint64 bytes = 0, ts = 0;
4236 GstIndexEntry *entry = NULL;
4238 if (time == GST_CLOCK_TIME_NONE) {
4244 GST_BASE_PARSE_INDEX_LOCK (parse);
4245 if (parse->priv->index) {
4246 /* Let's check if we have an index entry for that time */
4247 entry = gst_index_get_assoc_entry (parse->priv->index,
4248 parse->priv->index_id,
4249 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
4250 GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
4254 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
4255 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
4257 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
4258 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
4259 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
4261 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
4262 GST_TIME_ARGS (time));
4265 ts = GST_CLOCK_TIME_NONE;
4268 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4277 /* returns TRUE if seek succeeded */
4279 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
4284 GstSeekType start_type = GST_SEEK_TYPE_NONE, stop_type;
4285 gboolean flush, update, res = TRUE, accurate;
4286 gint64 start, stop, seekpos, seekstop;
4287 GstSegment seeksegment = { 0, };
4288 GstClockTime start_ts;
4290 GstEvent *segment_event;
4292 /* try upstream first, unless we're driving the streaming thread ourselves */
4293 if (parse->priv->pad_mode != GST_PAD_MODE_PULL) {
4294 res = gst_pad_push_event (parse->sinkpad, gst_event_ref (event));
4299 gst_event_parse_seek (event, &rate, &format, &flags,
4300 &start_type, &start, &stop_type, &stop);
4301 seqnum = gst_event_get_seqnum (event);
4303 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
4304 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
4305 GST_TIME_FORMAT, gst_format_get_name (format), rate,
4306 start_type, GST_TIME_ARGS (start), stop_type, GST_TIME_ARGS (stop));
4308 /* we can only handle TIME, so check if subclass can convert
4309 * to TIME format if it's some other format (such as DEFAULT) */
4310 if (format != GST_FORMAT_TIME) {
4311 if (!gst_base_parse_convert (parse, format, start, GST_FORMAT_TIME, &start)
4312 || !gst_base_parse_convert (parse, format, stop, GST_FORMAT_TIME,
4314 goto no_convert_to_time;
4316 GST_INFO_OBJECT (parse, "converted %s format to start time "
4317 "%" GST_TIME_FORMAT " and stop time %" GST_TIME_FORMAT,
4318 gst_format_get_name (format), GST_TIME_ARGS (start),
4319 GST_TIME_ARGS (stop));
4321 format = GST_FORMAT_TIME;
4324 /* no negative rates in push mode (unless upstream takes care of that, but
4325 * we've already tried upstream and it didn't handle the seek request) */
4326 if (rate < 0.0 && parse->priv->pad_mode == GST_PAD_MODE_PUSH)
4329 if (start_type != GST_SEEK_TYPE_SET ||
4330 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
4333 /* get flush flag */
4334 flush = flags & GST_SEEK_FLAG_FLUSH;
4336 /* copy segment, we need this because we still need the old
4337 * segment when we close the current segment. */
4338 gst_segment_copy_into (&parse->segment, &seeksegment);
4340 GST_DEBUG_OBJECT (parse, "configuring seek");
4341 gst_segment_do_seek (&seeksegment, rate, format, flags,
4342 start_type, start, stop_type, stop, &update);
4344 /* accurate seeking implies seek tables are used to obtain position,
4345 * and the requested segment is maintained exactly, not adjusted any way */
4346 accurate = flags & GST_SEEK_FLAG_ACCURATE;
4348 /* maybe we can be accurate for (almost) free */
4349 gst_base_parse_find_offset (parse, seeksegment.position, TRUE, &start_ts);
4350 if (seeksegment.position <= start_ts + TARGET_DIFFERENCE) {
4351 GST_DEBUG_OBJECT (parse, "accurate seek possible");
4356 GstClockTime startpos;
4358 startpos = seeksegment.position;
4362 /* accurate requested, so ... seek a bit before target */
4363 if (startpos < parse->priv->lead_in_ts)
4366 startpos -= parse->priv->lead_in_ts;
4368 if (seeksegment.stop == -1 && seeksegment.duration != -1)
4369 seeksegment.stop = seeksegment.start + seeksegment.duration;
4371 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
4372 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
4376 start_ts = seeksegment.position;
4380 if (seeksegment.stop == -1 && seeksegment.duration != -1)
4381 seeksegment.stop = seeksegment.start + seeksegment.duration;
4383 if (!gst_base_parse_convert (parse, format, start_ts,
4384 GST_FORMAT_BYTES, &seekpos))
4385 goto convert_failed;
4386 if (!gst_base_parse_convert (parse, format, seeksegment.stop,
4387 GST_FORMAT_BYTES, &seekstop))
4388 goto convert_failed;
4391 GST_DEBUG_OBJECT (parse,
4392 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
4394 GST_DEBUG_OBJECT (parse,
4395 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
4396 seeksegment.stop, seekstop);
4398 if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
4401 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
4404 if (parse->srcpad) {
4405 GstEvent *fevent = gst_event_new_flush_start ();
4406 GST_DEBUG_OBJECT (parse, "sending flush start");
4408 gst_event_set_seqnum (fevent, seqnum);
4410 gst_pad_push_event (parse->srcpad, gst_event_ref (fevent));
4411 /* unlock upstream pull_range */
4412 gst_pad_push_event (parse->sinkpad, fevent);
4415 gst_pad_pause_task (parse->sinkpad);
4418 /* we should now be able to grab the streaming thread because we stopped it
4419 * with the above flush/pause code */
4420 GST_PAD_STREAM_LOCK (parse->sinkpad);
4422 /* save current position */
4423 last_stop = parse->segment.position;
4424 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
4427 /* now commit to new position */
4429 /* prepare for streaming again */
4431 GstEvent *fevent = gst_event_new_flush_stop (TRUE);
4432 GST_DEBUG_OBJECT (parse, "sending flush stop");
4433 gst_event_set_seqnum (fevent, seqnum);
4434 gst_pad_push_event (parse->srcpad, gst_event_ref (fevent));
4435 gst_pad_push_event (parse->sinkpad, fevent);
4436 gst_base_parse_clear_queues (parse);
4438 /* keep track of our position */
4439 seeksegment.base = gst_segment_to_running_time (&seeksegment,
4440 seeksegment.format, parse->segment.position);
4443 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
4445 /* store the newsegment event so it can be sent from the streaming thread. */
4446 /* This will be sent later in _loop() */
4447 segment_event = gst_event_new_segment (&parse->segment);
4448 gst_event_set_seqnum (segment_event, seqnum);
4449 parse->priv->pending_events =
4450 g_list_prepend (parse->priv->pending_events, segment_event);
4452 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
4453 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
4454 ", time = %" GST_TIME_FORMAT, format,
4455 GST_TIME_ARGS (parse->segment.start),
4456 GST_TIME_ARGS (parse->segment.stop),
4457 GST_TIME_ARGS (parse->segment.time));
4459 /* one last chance in pull mode to stay accurate;
4460 * maybe scan and subclass can find where to go */
4463 GstClockTime ts = seeksegment.position;
4465 gst_base_parse_locate_time (parse, &ts, &scanpos);
4469 /* running collected index now consists of several intervals,
4470 * so optimized check no longer possible */
4471 parse->priv->index_last_valid = FALSE;
4472 parse->priv->index_last_offset = 0;
4473 parse->priv->index_last_ts = 0;
4477 /* mark discont if we are going to stream from another position. */
4478 if (seekpos != parse->priv->offset) {
4479 GST_DEBUG_OBJECT (parse,
4480 "mark DISCONT, we did a seek to another position");
4481 parse->priv->offset = seekpos;
4482 parse->priv->last_offset = seekpos;
4483 parse->priv->seen_keyframe = FALSE;
4484 parse->priv->discont = TRUE;
4485 parse->priv->next_dts = start_ts;
4486 parse->priv->next_pts = GST_CLOCK_TIME_NONE;
4487 parse->priv->last_dts = GST_CLOCK_TIME_NONE;
4488 parse->priv->last_pts = GST_CLOCK_TIME_NONE;
4489 parse->priv->sync_offset = seekpos;
4490 parse->priv->exact_position = accurate;
4493 /* Start streaming thread if paused */
4494 gst_pad_start_task (parse->sinkpad,
4495 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad, NULL);
4497 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
4502 GstEvent *new_event;
4503 GstBaseParseSeek *seek;
4504 GstSeekFlags flags = (flush ? GST_SEEK_FLAG_FLUSH : GST_SEEK_FLAG_NONE);
4506 /* The only thing we need to do in PUSH-mode is to send the
4507 seek event (in bytes) to upstream. Segment / flush handling happens
4508 in corresponding src event handlers */
4509 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
4510 if (seekstop >= 0 && seekstop <= seekpos)
4512 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
4513 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
4514 gst_event_set_seqnum (new_event, seqnum);
4516 /* store segment info so its precise details can be reconstructed when
4517 * receiving newsegment;
4518 * this matters for all details when accurate seeking,
4519 * is most useful to preserve NONE stop time otherwise */
4520 seek = g_new0 (GstBaseParseSeek, 1);
4521 seek->segment = seeksegment;
4522 seek->accurate = accurate;
4523 seek->offset = seekpos;
4524 seek->start_ts = start_ts;
4525 GST_OBJECT_LOCK (parse);
4526 /* less optimal, but preserves order */
4527 parse->priv->pending_seeks =
4528 g_slist_append (parse->priv->pending_seeks, seek);
4529 GST_OBJECT_UNLOCK (parse);
4531 res = gst_pad_push_event (parse->sinkpad, new_event);
4534 GST_OBJECT_LOCK (parse);
4535 parse->priv->pending_seeks =
4536 g_slist_remove (parse->priv->pending_seeks, seek);
4537 GST_OBJECT_UNLOCK (parse);
4543 gst_event_unref (event);
4549 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
4555 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
4561 GST_DEBUG_OBJECT (parse, "seek in %s format was requested, but subclass "
4562 "couldn't convert that into TIME format", gst_format_get_name (format));
4568 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
4575 gst_base_parse_set_upstream_tags (GstBaseParse * parse, GstTagList * taglist)
4577 if (taglist == parse->priv->upstream_tags)
4580 if (parse->priv->upstream_tags) {
4581 gst_tag_list_unref (parse->priv->upstream_tags);
4582 parse->priv->upstream_tags = NULL;
4585 GST_INFO_OBJECT (parse, "upstream tags: %" GST_PTR_FORMAT, taglist);
4587 if (taglist != NULL)
4588 parse->priv->upstream_tags = gst_tag_list_ref (taglist);
4593 gst_base_parse_set_index (GstElement * element, GstIndex * index)
4595 GstBaseParse *parse = GST_BASE_PARSE (element);
4597 GST_BASE_PARSE_INDEX_LOCK (parse);
4598 if (parse->priv->index)
4599 gst_object_unref (parse->priv->index);
4601 parse->priv->index = gst_object_ref (index);
4602 gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
4603 &parse->priv->index_id);
4604 parse->priv->own_index = FALSE;
4606 parse->priv->index = NULL;
4608 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4612 gst_base_parse_get_index (GstElement * element)
4614 GstBaseParse *parse = GST_BASE_PARSE (element);
4615 GstIndex *result = NULL;
4617 GST_BASE_PARSE_INDEX_LOCK (parse);
4618 if (parse->priv->index)
4619 result = gst_object_ref (parse->priv->index);
4620 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4626 static GstStateChangeReturn
4627 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
4629 GstBaseParse *parse;
4630 GstStateChangeReturn result;
4632 parse = GST_BASE_PARSE (element);
4634 switch (transition) {
4635 case GST_STATE_CHANGE_READY_TO_PAUSED:
4636 /* If this is our own index destroy it as the
4637 * old entries might be wrong for the new stream */
4638 GST_BASE_PARSE_INDEX_LOCK (parse);
4639 if (parse->priv->own_index) {
4640 gst_object_unref (parse->priv->index);
4641 parse->priv->index = NULL;
4642 parse->priv->own_index = FALSE;
4645 /* If no index was created, generate one */
4646 if (G_UNLIKELY (!parse->priv->index)) {
4647 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
4649 parse->priv->index = g_object_new (gst_mem_index_get_type (), NULL);
4650 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
4651 &parse->priv->index_id);
4652 parse->priv->own_index = TRUE;
4654 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4660 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4662 switch (transition) {
4663 case GST_STATE_CHANGE_PAUSED_TO_READY:
4664 gst_base_parse_reset (parse);
4674 * gst_base_parse_set_ts_at_offset:
4675 * @parse: a #GstBaseParse
4676 * @offset: offset into current buffer
4678 * This function should only be called from a @handle_frame implementation.
4680 * #GstBaseParse creates initial timestamps for frames by using the last
4681 * timestamp seen in the stream before the frame starts. In certain
4682 * cases, the correct timestamps will occur in the stream after the
4683 * start of the frame, but before the start of the actual picture data.
4684 * This function can be used to set the timestamps based on the offset
4685 * into the frame data that the picture starts.
4690 gst_base_parse_set_ts_at_offset (GstBaseParse * parse, gsize offset)
4692 GstClockTime pts, dts;
4694 g_return_if_fail (GST_IS_BASE_PARSE (parse));
4696 pts = gst_adapter_prev_pts_at_offset (parse->priv->adapter, offset, NULL);
4697 dts = gst_adapter_prev_dts_at_offset (parse->priv->adapter, offset, NULL);
4699 if (!GST_CLOCK_TIME_IS_VALID (pts) || !GST_CLOCK_TIME_IS_VALID (dts)) {
4700 GST_DEBUG_OBJECT (parse,
4701 "offset adapter timestamps dts=%" GST_TIME_FORMAT " pts=%"
4702 GST_TIME_FORMAT, GST_TIME_ARGS (dts), GST_TIME_ARGS (pts));
4704 if (GST_CLOCK_TIME_IS_VALID (pts) && (parse->priv->prev_pts != pts))
4705 parse->priv->prev_pts = parse->priv->next_pts = pts;
4707 if (GST_CLOCK_TIME_IS_VALID (dts) && (parse->priv->prev_dts != dts))
4708 parse->priv->prev_dts = parse->priv->next_dts = dts;
4712 * gst_base_parse_merge_tags:
4713 * @parse: a #GstBaseParse
4714 * @tags: (allow-none): a #GstTagList to merge, or NULL to unset
4715 * previously-set tags
4716 * @mode: the #GstTagMergeMode to use, usually #GST_TAG_MERGE_REPLACE
4718 * Sets the parser subclass's tags and how they should be merged with any
4719 * upstream stream tags. This will override any tags previously-set
4720 * with gst_base_parse_merge_tags().
4722 * Note that this is provided for convenience, and the subclass is
4723 * not required to use this and can still do tag handling on its own.
4728 gst_base_parse_merge_tags (GstBaseParse * parse, GstTagList * tags,
4729 GstTagMergeMode mode)
4731 g_return_if_fail (GST_IS_BASE_PARSE (parse));
4732 g_return_if_fail (tags == NULL || GST_IS_TAG_LIST (tags));
4733 g_return_if_fail (tags == NULL || mode != GST_TAG_MERGE_UNDEFINED);
4735 GST_OBJECT_LOCK (parse);
4737 if (tags != parse->priv->parser_tags) {
4738 if (parse->priv->parser_tags) {
4739 gst_tag_list_unref (parse->priv->parser_tags);
4740 parse->priv->parser_tags = NULL;
4741 parse->priv->parser_tags_merge_mode = GST_TAG_MERGE_APPEND;
4744 parse->priv->parser_tags = gst_tag_list_ref (tags);
4745 parse->priv->parser_tags_merge_mode = mode;
4748 GST_DEBUG_OBJECT (parse, "setting parser tags to %" GST_PTR_FORMAT
4749 " (mode %d)", tags, parse->priv->parser_tags_merge_mode);
4750 parse->priv->tags_changed = TRUE;
4753 GST_OBJECT_UNLOCK (parse);