2 * Copyright (C) 2008 Nokia Corporation. All rights reserved.
3 * Contact: Stefan Kost <stefan.kost@nokia.com>
4 * Copyright (C) 2008 Sebastian Dröge <sebastian.droege@collabora.co.uk>.
5 * Copyright (C) 2011, Hewlett-Packard Development Company, L.P.
6 * Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>, Collabora Ltd.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public
19 * License along with this library; if not, write to the
20 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 * Boston, MA 02111-1307, USA.
25 * SECTION:gstbaseparse
26 * @short_description: Base class for stream parsers
27 * @see_also: #GstBaseTransform
29 * This base class is for parser elements that process data and splits it
30 * into separate audio/video/whatever frames.
34 * <listitem><para>provides one sink pad and one source pad</para></listitem>
35 * <listitem><para>handles state changes</para></listitem>
36 * <listitem><para>can operate in pull mode or push mode</para></listitem>
37 * <listitem><para>handles seeking in both modes</para></listitem>
38 * <listitem><para>handles events (NEWSEGMENT/EOS/FLUSH)</para></listitem>
40 * handles queries (POSITION/DURATION/SEEKING/FORMAT/CONVERT)
42 * <listitem><para>handles flushing</para></listitem>
45 * The purpose of this base class is to provide the basic functionality of
46 * a parser and share a lot of rather complex code.
48 * Description of the parsing mechanism:
51 * <itemizedlist><title>Set-up phase</title>
53 * GstBaseParse class calls @set_sink_caps to inform the subclass about
54 * incoming sinkpad caps. Subclass should set the srcpad caps accordingly.
57 * GstBaseParse calls @start to inform subclass that data processing is
61 * At least at this point subclass needs to tell the GstBaseParse class
62 * how big data chunks it wants to receive (min_frame_size). It can do
63 * this with gst_base_parse_set_min_frame_size().
66 * GstBaseParse class sets up appropriate data passing mode (pull/push)
67 * and starts to process the data.
73 * <title>Parsing phase</title>
75 * GstBaseParse gathers at least min_frame_size bytes of data either
76 * by pulling it from upstream or collecting buffers in an internal
80 * A buffer of (at least) min_frame_size bytes is passed to subclass with
81 * @check_valid_frame. Subclass checks the contents and returns TRUE
82 * if the buffer contains a valid frame. It also needs to set the
83 * @framesize according to the detected frame size. If buffer didn't
84 * contain a valid frame, this call must return FALSE and optionally
85 * set the @skipsize value to inform base class that how many bytes
86 * it needs to skip in order to find a valid frame. @framesize can always
87 * indicate a new minimum for current frame parsing. Indicating G_MAXUINT
88 * for requested amount means subclass simply needs best available
89 * subsequent data. In push mode this amounts to an additional input buffer
90 * (thus minimal additional latency), in pull mode this amounts to some
91 * arbitrary reasonable buffer size increase. The passed buffer
92 * is read-only. Note that @check_valid_frame might receive any small
93 * amount of input data when leftover data is being drained (e.g. at EOS).
96 * After valid frame is found, it will be passed again to subclass with
97 * @parse_frame call. Now subclass is responsible for parsing the
98 * frame contents and setting the caps, and buffer metadata (e.g.
99 * buffer timestamp and duration, or keyframe if applicable).
100 * (although the latter can also be done by GstBaseParse if it is
101 * appropriately configured, see below). Frame is provided with
102 * timestamp derived from upstream (as much as generally possible),
103 * duration obtained from configuration (see below), and offset
104 * if meaningful (in pull mode).
107 * Finally the buffer can be pushed downstream and the parsing loop starts
108 * over again. Just prior to actually pushing the buffer in question,
109 * it is passed to @pre_push_frame which gives subclass yet one
110 * last chance to examine buffer metadata, or to send some custom (tag)
111 * events, or to perform custom (segment) filtering.
114 * During the parsing process GstBaseParseClass will handle both srcpad
115 * and sinkpad events. They will be passed to subclass if @event or
116 * @src_event callbacks have been provided.
121 * <itemizedlist><title>Shutdown phase</title>
123 * GstBaseParse class calls @stop to inform the subclass that data
124 * parsing will be stopped.
130 * Subclass is responsible for providing pad template caps for
131 * source and sink pads. The pads need to be named "sink" and "src". It also
132 * needs to set the fixed caps on srcpad, when the format is ensured (e.g.
133 * when base class calls subclass' @set_sink_caps function).
135 * This base class uses #GST_FORMAT_DEFAULT as a meaning of frames. So,
136 * subclass conversion routine needs to know that conversion from
137 * #GST_FORMAT_TIME to #GST_FORMAT_DEFAULT must return the
138 * frame number that can be found from the given byte position.
140 * GstBaseParse uses subclasses conversion methods also for seeking (or
141 * otherwise uses its own default one, see also below).
143 * Subclass @start and @stop functions will be called to inform the beginning
144 * and end of data processing.
146 * Things that subclass need to take care of:
148 * <listitem><para>Provide pad templates</para></listitem>
150 * Fixate the source pad caps when appropriate
153 * Inform base class how big data chunks should be retrieved. This is
154 * done with gst_base_parse_set_min_frame_size() function.
157 * Examine data chunks passed to subclass with @check_valid_frame
158 * and tell if they contain a valid frame
161 * Set the caps and timestamp to frame that is passed to subclass with
162 * @parse_frame function.
164 * <listitem><para>Provide conversion functions</para></listitem>
166 * Update the duration information with gst_base_parse_set_duration()
169 * Optionally passthrough using gst_base_parse_set_passthrough()
172 * Configure various baseparse parameters using
173 * gst_base_parse_set_average_bitrate(), gst_base_parse_set_syncable()
174 * and gst_base_parse_set_frame_rate().
177 * In particular, if subclass is unable to determine a duration, but
178 * parsing (or specs) yields a frames per seconds rate, then this can be
179 * provided to GstBaseParse to enable it to cater for
180 * buffer time metadata (which will be taken from upstream as much as
181 * possible). Internally keeping track of frame durations and respective
182 * sizes that have been pushed provides GstBaseParse with an estimated
183 * bitrate. A default @convert (used if not overriden) will then use these
184 * rates to perform obvious conversions. These rates are also used to
185 * update (estimated) duration at regular frame intervals.
192 * - In push mode provide a queue of adapter-"queued" buffers for upstream
194 * - Queue buffers/events until caps are set
204 #include <gst/base/gstadapter.h>
206 #include "gstbaseparse.h"
208 #define GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC (1 << 0)
210 #define MIN_FRAMES_TO_POST_BITRATE 10
211 #define TARGET_DIFFERENCE (20 * GST_SECOND)
213 GST_DEBUG_CATEGORY_STATIC (gst_base_parse_debug);
214 #define GST_CAT_DEFAULT gst_base_parse_debug
216 /* Supported formats */
217 static const GstFormat fmtlist[] = {
224 #define GST_BASE_PARSE_GET_PRIVATE(obj) \
225 (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_PARSE, GstBaseParsePrivate))
227 struct _GstBaseParsePrivate
229 GstPadActivateMode pad_mode;
234 GstFormat duration_fmt;
235 gint64 estimated_duration;
236 gint64 estimated_drift;
238 guint min_frame_size;
239 gboolean passthrough;
241 gboolean has_timing_info;
242 guint fps_num, fps_den;
243 gint update_interval;
245 guint lead_in, lead_out;
246 GstClockTime lead_in_ts, lead_out_ts;
247 GstClockTime min_latency, max_latency;
255 GstClockTime next_ts;
256 GstClockTime prev_ts;
257 GstClockTime frame_duration;
258 gboolean seen_keyframe;
263 guint64 data_bytecount;
264 guint64 acc_duration;
265 GstClockTime first_frame_ts;
266 gint64 first_frame_offset;
268 gboolean post_min_bitrate;
269 gboolean post_avg_bitrate;
270 gboolean post_max_bitrate;
274 guint posted_avg_bitrate;
276 GList *pending_events;
278 /* frames/buffers that are queued and ready to go on OK */
279 GQueue queued_frames;
283 /* index entry storage, either ours or provided */
287 GStaticMutex index_lock;
289 /* seek table entries only maintained if upstream is BYTE seekable */
290 gboolean upstream_seekable;
291 gboolean upstream_has_duration;
292 gint64 upstream_size;
293 /* minimum distance between two index entries */
294 GstClockTimeDiff idx_interval;
295 /* ts and offset of last entry added */
296 GstClockTime index_last_ts;
297 gint64 index_last_offset;
298 gboolean index_last_valid;
300 /* timestamps currently produced are accurate, e.g. started from 0 onwards */
301 gboolean exact_position;
302 /* seek events are temporarily kept to match them with newsegments */
303 GSList *pending_seeks;
305 /* reverse playback */
306 GSList *buffers_pending;
307 GSList *buffers_queued;
308 GSList *buffers_send;
309 GstClockTime last_ts;
312 /* Newsegment event to be sent after SEEK */
313 GstEvent *pending_segment;
315 /* Segment event that closes the running segment prior to SEEK */
316 GstEvent *close_segment;
318 /* push mode helper frame */
319 GstBaseParseFrame frame;
321 /* TRUE if we're still detecting the format, i.e.
322 * if ::detect() is still called for future buffers */
324 GList *detect_buffers;
325 guint detect_buffers_size;
328 typedef struct _GstBaseParseSeek
333 GstClockTime start_ts;
336 static GstElementClass *parent_class = NULL;
338 static void gst_base_parse_class_init (GstBaseParseClass * klass);
339 static void gst_base_parse_init (GstBaseParse * parse,
340 GstBaseParseClass * klass);
343 gst_base_parse_get_type (void)
345 static volatile gsize base_parse_type = 0;
347 if (g_once_init_enter (&base_parse_type)) {
348 static const GTypeInfo base_parse_info = {
349 sizeof (GstBaseParseClass),
350 (GBaseInitFunc) NULL,
351 (GBaseFinalizeFunc) NULL,
352 (GClassInitFunc) gst_base_parse_class_init,
355 sizeof (GstBaseParse),
357 (GInstanceInitFunc) gst_base_parse_init,
361 _type = g_type_register_static (GST_TYPE_ELEMENT,
362 "GstBaseParse", &base_parse_info, G_TYPE_FLAG_ABSTRACT);
363 g_once_init_leave (&base_parse_type, _type);
365 return (GType) base_parse_type;
368 static void gst_base_parse_finalize (GObject * object);
370 static GstStateChangeReturn gst_base_parse_change_state (GstElement * element,
371 GstStateChange transition);
372 static void gst_base_parse_reset (GstBaseParse * parse);
374 static void gst_base_parse_set_index (GstElement * element, GstIndex * index);
375 static GstIndex *gst_base_parse_get_index (GstElement * element);
377 static gboolean gst_base_parse_sink_activate (GstPad * sinkpad);
378 static gboolean gst_base_parse_sink_activate_push (GstPad * pad,
380 static gboolean gst_base_parse_sink_activate_pull (GstPad * pad,
382 static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
384 static void gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event);
386 static gboolean gst_base_parse_src_event (GstPad * pad, GstObject * parent,
388 static gboolean gst_base_parse_src_query (GstPad * pad, GstObject * parent,
391 static gboolean gst_base_parse_sink_event (GstPad * pad, GstObject * parent,
393 static gboolean gst_base_parse_sink_query (GstPad * pad, GstObject * parent,
396 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstObject * parent,
398 static void gst_base_parse_loop (GstPad * pad);
400 static gboolean gst_base_parse_check_frame (GstBaseParse * parse,
401 GstBaseParseFrame * frame, guint * framesize, gint * skipsize);
402 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
403 GstBaseParseFrame * frame);
405 static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
408 static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
411 static void gst_base_parse_drain (GstBaseParse * parse);
413 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
414 gboolean post_min, gboolean post_avg, gboolean post_max);
416 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
417 GstClockTime time, gboolean before, GstClockTime * _ts);
418 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
419 GstClockTime * _time, gint64 * _offset);
421 static GstFlowReturn gst_base_parse_process_fragment (GstBaseParse * parse,
424 static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);
427 gst_base_parse_clear_queues (GstBaseParse * parse)
429 g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
430 g_slist_free (parse->priv->buffers_queued);
431 parse->priv->buffers_queued = NULL;
432 g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
434 g_slist_free (parse->priv->buffers_pending);
435 parse->priv->buffers_pending = NULL;
436 g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
437 g_slist_free (parse->priv->buffers_send);
438 parse->priv->buffers_send = NULL;
440 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
441 g_list_free (parse->priv->detect_buffers);
442 parse->priv->detect_buffers = NULL;
443 parse->priv->detect_buffers_size = 0;
447 gst_base_parse_finalize (GObject * object)
449 GstBaseParse *parse = GST_BASE_PARSE (object);
452 g_object_unref (parse->priv->adapter);
454 if (parse->priv->pending_segment) {
455 p_ev = &parse->priv->pending_segment;
456 gst_event_replace (p_ev, NULL);
458 if (parse->priv->close_segment) {
459 p_ev = &parse->priv->close_segment;
460 gst_event_replace (p_ev, NULL);
463 if (parse->priv->cache) {
464 gst_buffer_unref (parse->priv->cache);
465 parse->priv->cache = NULL;
468 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
470 g_list_free (parse->priv->pending_events);
471 parse->priv->pending_events = NULL;
473 g_queue_foreach (&parse->priv->queued_frames,
474 (GFunc) gst_base_parse_frame_free, NULL);
475 g_queue_clear (&parse->priv->queued_frames);
477 if (parse->priv->index) {
478 gst_object_unref (parse->priv->index);
479 parse->priv->index = NULL;
482 g_static_mutex_free (&parse->priv->index_lock);
484 gst_base_parse_clear_queues (parse);
486 G_OBJECT_CLASS (parent_class)->finalize (object);
490 gst_base_parse_class_init (GstBaseParseClass * klass)
492 GObjectClass *gobject_class;
493 GstElementClass *gstelement_class;
495 gobject_class = G_OBJECT_CLASS (klass);
496 g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
497 parent_class = g_type_class_peek_parent (klass);
498 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
500 gstelement_class = (GstElementClass *) klass;
501 gstelement_class->change_state =
502 GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
503 gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
504 gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
506 /* Default handlers */
507 klass->check_valid_frame = gst_base_parse_check_frame;
508 klass->parse_frame = gst_base_parse_parse_frame;
509 klass->src_event = gst_base_parse_src_eventfunc;
510 klass->convert = gst_base_parse_convert_default;
512 GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
513 "baseparse element");
517 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
519 GstPadTemplate *pad_template;
521 GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
523 parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
526 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
527 g_return_if_fail (pad_template != NULL);
528 parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
529 gst_pad_set_event_function (parse->sinkpad,
530 GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
531 gst_pad_set_query_function (parse->sinkpad,
532 GST_DEBUG_FUNCPTR (gst_base_parse_sink_query));
533 gst_pad_set_chain_function (parse->sinkpad,
534 GST_DEBUG_FUNCPTR (gst_base_parse_chain));
535 gst_pad_set_activate_function (parse->sinkpad,
536 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
537 gst_pad_set_activatepush_function (parse->sinkpad,
538 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_push));
539 gst_pad_set_activatepull_function (parse->sinkpad,
540 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_pull));
541 gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
543 GST_DEBUG_OBJECT (parse, "sinkpad created");
546 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
547 g_return_if_fail (pad_template != NULL);
548 parse->srcpad = gst_pad_new_from_template (pad_template, "src");
549 gst_pad_set_event_function (parse->srcpad,
550 GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
551 gst_pad_set_query_function (parse->srcpad,
552 GST_DEBUG_FUNCPTR (gst_base_parse_src_query));
553 gst_pad_use_fixed_caps (parse->srcpad);
554 gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
555 GST_DEBUG_OBJECT (parse, "src created");
557 g_queue_init (&parse->priv->queued_frames);
559 parse->priv->adapter = gst_adapter_new ();
561 parse->priv->pad_mode = GST_PAD_ACTIVATE_NONE;
563 g_static_mutex_init (&parse->priv->index_lock);
566 gst_base_parse_reset (parse);
567 GST_DEBUG_OBJECT (parse, "init ok");
570 static GstBaseParseFrame *
571 gst_base_parse_frame_copy (GstBaseParseFrame * frame)
573 GstBaseParseFrame *copy;
575 copy = g_slice_dup (GstBaseParseFrame, frame);
576 copy->buffer = gst_buffer_ref (frame->buffer);
577 copy->_private_flags &= ~GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
579 GST_TRACE ("copied frame %p -> %p", frame, copy);
585 gst_base_parse_frame_free (GstBaseParseFrame * frame)
587 GST_TRACE ("freeing frame %p", frame);
590 gst_buffer_unref (frame->buffer);
591 frame->buffer = NULL;
594 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
595 g_slice_free (GstBaseParseFrame, frame);
597 memset (frame, 0, sizeof (*frame));
602 gst_base_parse_frame_get_type (void)
604 static volatile gsize frame_type = 0;
606 if (g_once_init_enter (&frame_type)) {
609 _type = g_boxed_type_register_static ("GstBaseParseFrame",
610 (GBoxedCopyFunc) gst_base_parse_frame_copy,
611 (GBoxedFreeFunc) gst_base_parse_frame_free);
612 g_once_init_leave (&frame_type, _type);
614 return (GType) frame_type;
618 * gst_base_parse_frame_init:
619 * @frame: #GstBaseParseFrame.
621 * Sets a #GstBaseParseFrame to initial state. Currently this means
622 * all public fields are zero-ed and a private flag is set to make
623 * sure gst_base_parse_frame_free() only frees the contents but not
624 * the actual frame. Use this function to initialise a #GstBaseParseFrame
625 * allocated on the stack.
630 gst_base_parse_frame_init (GstBaseParseFrame * frame)
632 memset (frame, 0, sizeof (GstBaseParseFrame));
633 frame->_private_flags = GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
634 GST_TRACE ("inited frame %p", frame);
638 * gst_base_parse_frame_new:
639 * @buffer: (transfer none): a #GstBuffer
641 * @overhead: number of bytes in this frame which should be counted as
642 * metadata overhead, ie. not used to calculate the average bitrate.
643 * Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
645 * Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
646 * elements written in C should usually allocate the frame on the stack and
647 * then use gst_base_parse_frame_init() to initialise it.
649 * Returns: a newly-allocated #GstBaseParseFrame. Free with
650 * gst_base_parse_frame_free() when no longer needed, unless you gave
651 * away ownership to gst_base_parse_push_frame().
656 gst_base_parse_frame_new (GstBuffer * buffer, GstBaseParseFrameFlags flags,
659 GstBaseParseFrame *frame;
661 frame = g_slice_new0 (GstBaseParseFrame);
662 frame->buffer = gst_buffer_ref (buffer);
664 GST_TRACE ("created frame %p", frame);
669 gst_base_parse_frame_update (GstBaseParse * parse, GstBaseParseFrame * frame,
672 gst_buffer_replace (&frame->buffer, buf);
676 /* set flags one by one for clarity */
677 if (G_UNLIKELY (parse->priv->drain))
678 parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;
680 /* losing sync is pretty much a discont (and vice versa), no ? */
681 if (G_UNLIKELY (parse->priv->discont))
682 parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
686 gst_base_parse_reset (GstBaseParse * parse)
688 GST_OBJECT_LOCK (parse);
689 gst_segment_init (&parse->segment, GST_FORMAT_TIME);
690 parse->priv->duration = -1;
691 parse->priv->min_frame_size = 1;
692 parse->priv->discont = TRUE;
693 parse->priv->flushing = FALSE;
694 parse->priv->offset = 0;
695 parse->priv->sync_offset = 0;
696 parse->priv->update_interval = -1;
697 parse->priv->fps_num = parse->priv->fps_den = 0;
698 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
699 parse->priv->lead_in = parse->priv->lead_out = 0;
700 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
701 parse->priv->bitrate = 0;
702 parse->priv->framecount = 0;
703 parse->priv->bytecount = 0;
704 parse->priv->acc_duration = 0;
705 parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
706 parse->priv->first_frame_offset = -1;
707 parse->priv->estimated_duration = -1;
708 parse->priv->estimated_drift = 0;
709 parse->priv->next_ts = 0;
710 parse->priv->syncable = TRUE;
711 parse->priv->passthrough = FALSE;
712 parse->priv->has_timing_info = FALSE;
713 parse->priv->post_min_bitrate = TRUE;
714 parse->priv->post_avg_bitrate = TRUE;
715 parse->priv->post_max_bitrate = TRUE;
716 parse->priv->min_bitrate = G_MAXUINT;
717 parse->priv->max_bitrate = 0;
718 parse->priv->avg_bitrate = 0;
719 parse->priv->posted_avg_bitrate = 0;
721 parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
722 parse->priv->index_last_offset = -1;
723 parse->priv->index_last_valid = TRUE;
724 parse->priv->upstream_seekable = FALSE;
725 parse->priv->upstream_size = 0;
726 parse->priv->upstream_has_duration = FALSE;
727 parse->priv->idx_interval = 0;
728 parse->priv->exact_position = TRUE;
729 parse->priv->seen_keyframe = FALSE;
731 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
732 parse->priv->last_offset = 0;
734 if (parse->priv->pending_segment) {
735 gst_event_unref (parse->priv->pending_segment);
736 parse->priv->pending_segment = NULL;
739 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
741 g_list_free (parse->priv->pending_events);
742 parse->priv->pending_events = NULL;
744 if (parse->priv->cache) {
745 gst_buffer_unref (parse->priv->cache);
746 parse->priv->cache = NULL;
749 g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
750 g_slist_free (parse->priv->pending_seeks);
751 parse->priv->pending_seeks = NULL;
753 /* we know it is not alloc'ed, but maybe other stuff to free, some day ... */
754 parse->priv->frame._private_flags |=
755 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
756 gst_base_parse_frame_free (&parse->priv->frame);
758 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
759 g_list_free (parse->priv->detect_buffers);
760 parse->priv->detect_buffers = NULL;
761 parse->priv->detect_buffers_size = 0;
762 GST_OBJECT_UNLOCK (parse);
765 /* gst_base_parse_check_frame:
766 * @parse: #GstBaseParse.
767 * @buffer: GstBuffer.
768 * @framesize: This will be set to tell the found frame size in bytes.
769 * @skipsize: Output parameter that tells how much data needs to be skipped
770 * in order to find the following frame header.
772 * Default callback for check_valid_frame.
774 * Returns: Always TRUE.
777 gst_base_parse_check_frame (GstBaseParse * parse,
778 GstBaseParseFrame * frame, guint * framesize, gint * skipsize)
780 *framesize = gst_buffer_get_size (frame->buffer);
786 /* gst_base_parse_parse_frame:
787 * @parse: #GstBaseParse.
788 * @buffer: #GstBuffer.
790 * Default callback for parse_frame.
793 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
795 GstBuffer *buffer = frame->buffer;
797 if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
798 GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
799 GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
801 if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
802 GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
803 GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
808 /* gst_base_parse_convert:
809 * @parse: #GstBaseParse.
810 * @src_format: #GstFormat describing the source format.
811 * @src_value: Source value to be converted.
812 * @dest_format: #GstFormat defining the converted format.
813 * @dest_value: Pointer where the conversion result will be put.
815 * Converts using configured "convert" vmethod in #GstBaseParse class.
817 * Returns: TRUE if conversion was successful.
820 gst_base_parse_convert (GstBaseParse * parse,
821 GstFormat src_format,
822 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
824 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
827 g_return_val_if_fail (dest_value != NULL, FALSE);
832 ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
834 #ifndef GST_DISABLE_GST_DEBUG
837 if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
838 GST_LOG_OBJECT (parse,
839 "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
840 GST_TIME_ARGS (src_value), *dest_value);
841 } else if (dest_format == GST_FORMAT_TIME &&
842 src_format == GST_FORMAT_BYTES) {
843 GST_LOG_OBJECT (parse,
844 "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
845 src_value, GST_TIME_ARGS (*dest_value));
847 GST_LOG_OBJECT (parse,
848 "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
849 GST_STR_NULL (gst_format_get_name (src_format)),
850 GST_STR_NULL (gst_format_get_name (dest_format)),
851 src_value, *dest_value);
854 GST_DEBUG_OBJECT (parse, "conversion failed");
862 /* gst_base_parse_sink_event:
863 * @pad: #GstPad that received the event.
864 * @event: #GstEvent to be handled.
866 * Handler for sink pad events.
868 * Returns: TRUE if the event was handled.
871 gst_base_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
874 GstBaseParseClass *bclass;
875 gboolean handled = FALSE;
878 parse = GST_BASE_PARSE (parent);
879 bclass = GST_BASE_PARSE_GET_CLASS (parse);
881 GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
882 GST_EVENT_TYPE_NAME (event));
884 /* Cache all events except EOS, SEGMENT and FLUSH_STOP if we have a
886 if (parse->priv->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
887 && GST_EVENT_TYPE (event) != GST_EVENT_SEGMENT
888 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
889 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP) {
891 if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
892 /* See if any bitrate tags were posted */
893 gst_base_parse_handle_tag (parse, event);
895 parse->priv->pending_events =
896 g_list_append (parse->priv->pending_events, event);
900 if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
901 parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
902 /* We've not posted bitrate tags yet - do so now */
903 gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
906 handled = bclass->event (parse, event);
909 handled = gst_base_parse_sink_eventfunc (parse, event);
912 ret = gst_pad_event_default (pad, parent, event);
915 GST_DEBUG_OBJECT (parse, "event handled");
921 /* gst_base_parse_sink_eventfunc:
922 * @parse: #GstBaseParse.
923 * @event: #GstEvent to be handled.
925 * Element-level event handler function.
927 * The event will be unreffed only if it has been handled and this
928 * function returns %TRUE
930 * Returns: %TRUE if the event was handled and not need forwarding.
933 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
935 gboolean handled = FALSE;
938 switch (GST_EVENT_TYPE (event)) {
942 GstBaseParseClass *klass;
944 klass = GST_BASE_PARSE_GET_CLASS (parse);
946 gst_event_parse_caps (event, &caps);
947 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
949 if (klass->set_sink_caps)
950 klass->set_sink_caps (parse, caps);
952 /* will send our own caps downstream */
953 gst_event_unref (event);
957 case GST_EVENT_SEGMENT:
959 const GstSegment *in_segment;
960 GstSegment out_segment;
961 gint64 offset = 0, next_ts;
964 gdouble rate, applied_rate;
966 gint64 start, stop, pos, next_ts;
970 gst_event_parse_segment (event, &in_segment);
971 gst_segment_init (&out_segment, GST_FORMAT_TIME);
973 GST_DEBUG_OBJECT (parse, "segment %" GST_SEGMENT_FORMAT, in_segment);
975 if (in_segment->format == GST_FORMAT_BYTES) {
976 GstBaseParseSeek *seek = NULL;
979 /* stop time is allowed to be open-ended, but not start & pos */
980 offset = in_segment->time;
982 GST_OBJECT_LOCK (parse);
983 for (node = parse->priv->pending_seeks; node; node = node->next) {
984 GstBaseParseSeek *tmp = node->data;
986 if (tmp->offset == offset) {
991 parse->priv->pending_seeks =
992 g_slist_remove (parse->priv->pending_seeks, seek);
993 GST_OBJECT_UNLOCK (parse);
996 GST_DEBUG_OBJECT (parse,
997 "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
998 seek->accurate ? " accurate" : "", &seek->segment);
1000 out_segment.start = seek->segment.start;
1001 out_segment.stop = seek->segment.stop;
1002 out_segment.time = seek->segment.start;
1004 next_ts = seek->start_ts;
1005 parse->priv->exact_position = seek->accurate;
1008 /* best attempt convert */
1009 /* as these are only estimates, stop is kept open-ended to avoid
1010 * premature cutting */
1011 gst_base_parse_convert (parse, GST_FORMAT_BYTES, in_segment->start,
1012 GST_FORMAT_TIME, (gint64 *) & next_ts);
1014 out_segment.start = next_ts;
1015 out_segment.stop = GST_CLOCK_TIME_NONE;
1016 out_segment.time = next_ts;
1018 parse->priv->exact_position = (in_segment->start == 0);
1021 gst_event_unref (event);
1023 event = gst_event_new_segment (&out_segment);
1025 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. %"
1026 GST_SEGMENT_FORMAT, in_segment);
1028 } else if (in_segment->format != GST_FORMAT_TIME) {
1029 /* Unknown incoming segment format. Output a default open-ended
1031 gst_event_unref (event);
1033 out_segment.start = 0;
1034 out_segment.stop = GST_CLOCK_TIME_NONE;;
1035 out_segment.time = 0;;
1037 event = gst_event_new_segment (&out_segment);
1041 /* not considered BYTE seekable if it is talking to us in TIME,
1042 * whatever else it might claim */
1043 parse->priv->upstream_seekable = FALSE;
1044 next_ts = in_segment->start;
1047 memcpy (&parse->segment, &out_segment, sizeof (GstSegment));
1050 gst_segment_set_newsegment (&parse->segment, update, rate,
1051 applied_rate, format, start, stop, start);
1054 /* save the segment for later, right before we push a new buffer so that
1055 * the caps are fixed and the next linked element can receive
1057 eventp = &parse->priv->pending_segment;
1058 gst_event_replace (eventp, event);
1059 gst_event_unref (event);
1062 /* but finish the current segment */
1063 GST_DEBUG_OBJECT (parse, "draining current segment");
1064 if (in_segment->rate > 0.0)
1065 gst_base_parse_drain (parse);
1067 gst_base_parse_process_fragment (parse, FALSE);
1068 gst_adapter_clear (parse->priv->adapter);
1070 parse->priv->offset = offset;
1071 parse->priv->sync_offset = offset;
1072 parse->priv->next_ts = next_ts;
1073 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1074 parse->priv->discont = TRUE;
1075 parse->priv->seen_keyframe = FALSE;
1079 case GST_EVENT_FLUSH_START:
1080 parse->priv->flushing = TRUE;
1081 handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
1083 gst_event_unref (event);
1084 /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
1085 GST_PAD_STREAM_LOCK (parse->srcpad);
1086 GST_PAD_STREAM_UNLOCK (parse->srcpad);
1090 case GST_EVENT_FLUSH_STOP:
1091 gst_adapter_clear (parse->priv->adapter);
1092 gst_base_parse_clear_queues (parse);
1093 parse->priv->flushing = FALSE;
1094 parse->priv->discont = TRUE;
1095 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1096 parse->priv->frame._private_flags |=
1097 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
1098 gst_base_parse_frame_free (&parse->priv->frame);
1102 if (parse->segment.rate > 0.0)
1103 gst_base_parse_drain (parse);
1105 gst_base_parse_process_fragment (parse, FALSE);
1107 /* If we STILL have zero frames processed, fire an error */
1108 if (parse->priv->framecount == 0) {
1109 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1110 ("No valid frames found before end of stream"), (NULL));
1112 /* newsegment before eos */
1113 if (parse->priv->pending_segment) {
1114 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1115 parse->priv->pending_segment = NULL;
1127 gst_base_parse_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
1129 GstBaseParse *parse;
1130 GstBaseParseClass *bclass;
1133 parse = GST_BASE_PARSE (parent);
1134 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1136 switch (GST_QUERY_TYPE (query)) {
1137 case GST_QUERY_CAPS:
1139 if (bclass->get_sink_caps) {
1140 GstCaps *caps, *filter;
1142 gst_query_parse_caps (query, &filter);
1143 caps = bclass->get_sink_caps (parse, filter);
1144 GST_LOG_OBJECT (parse, "sink getcaps returning caps %" GST_PTR_FORMAT,
1146 gst_query_set_caps_result (query, caps);
1147 gst_caps_unref (caps);
1151 res = gst_pad_peer_query (parse->srcpad, query);
1156 res = gst_pad_query_default (pad, parent, query);
1165 /* gst_base_parse_src_event:
1166 * @pad: #GstPad that received the event.
1167 * @event: #GstEvent that was received.
1169 * Handler for source pad events.
1171 * Returns: TRUE if the event was handled.
1174 gst_base_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1176 GstBaseParse *parse;
1177 GstBaseParseClass *bclass;
1178 gboolean handled = FALSE;
1179 gboolean ret = TRUE;
1181 parse = GST_BASE_PARSE (parent);
1182 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1184 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1185 GST_EVENT_TYPE_NAME (event));
1187 if (bclass->src_event)
1188 handled = bclass->src_event (parse, event);
1191 ret = gst_pad_event_default (pad, parent, event);
1197 gst_base_parse_is_seekable (GstBaseParse * parse)
1199 /* FIXME: could do more here, e.g. check index or just send data from 0
1200 * in pull mode and let decoder/sink clip */
1201 return parse->priv->syncable;
1204 /* gst_base_parse_src_eventfunc:
1205 * @parse: #GstBaseParse.
1206 * @event: #GstEvent that was received.
1208 * Default srcpad event handler.
1210 * Returns: TRUE if the event was handled and can be dropped.
1213 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1215 gboolean handled = FALSE;
1217 switch (GST_EVENT_TYPE (event)) {
1218 case GST_EVENT_SEEK:
1220 if (gst_base_parse_is_seekable (parse)) {
1221 handled = gst_base_parse_handle_seek (parse, event);
1233 * gst_base_parse_convert_default:
1234 * @parse: #GstBaseParse.
1235 * @src_format: #GstFormat describing the source format.
1236 * @src_value: Source value to be converted.
1237 * @dest_format: #GstFormat defining the converted format.
1238 * @dest_value: Pointer where the conversion result will be put.
1240 * Default implementation of "convert" vmethod in #GstBaseParse class.
1242 * Returns: TRUE if conversion was successful.
1247 gst_base_parse_convert_default (GstBaseParse * parse,
1248 GstFormat src_format,
1249 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1251 gboolean ret = FALSE;
1252 guint64 bytes, duration;
1254 if (G_UNLIKELY (src_format == dest_format)) {
1255 *dest_value = src_value;
1259 if (G_UNLIKELY (src_value == -1)) {
1264 if (G_UNLIKELY (src_value == 0)) {
1269 /* need at least some frames */
1270 if (!parse->priv->framecount)
1273 duration = parse->priv->acc_duration / GST_MSECOND;
1274 bytes = parse->priv->bytecount;
1276 if (G_UNLIKELY (!duration || !bytes))
1279 if (src_format == GST_FORMAT_BYTES) {
1280 if (dest_format == GST_FORMAT_TIME) {
1281 /* BYTES -> TIME conversion */
1282 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1283 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1284 *dest_value *= GST_MSECOND;
1285 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1286 *dest_value / GST_MSECOND);
1289 } else if (src_format == GST_FORMAT_TIME) {
1290 if (dest_format == GST_FORMAT_BYTES) {
1291 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1292 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1294 GST_DEBUG_OBJECT (parse,
1295 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1296 src_value / GST_MSECOND, *dest_value);
1299 } else if (src_format == GST_FORMAT_DEFAULT) {
1300 /* DEFAULT == frame-based */
1301 if (dest_format == GST_FORMAT_TIME) {
1302 if (parse->priv->fps_den) {
1303 *dest_value = gst_util_uint64_scale (src_value,
1304 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1307 } else if (dest_format == GST_FORMAT_BYTES) {
1315 gst_base_parse_update_duration (GstBaseParse * baseparse)
1318 GstBaseParse *parse;
1320 parse = GST_BASE_PARSE (baseparse);
1322 peer = gst_pad_get_peer (parse->sinkpad);
1324 gboolean qres = FALSE;
1325 gint64 ptot, dest_value;
1327 qres = gst_pad_query_duration (peer, GST_FORMAT_BYTES, &ptot);
1328 gst_object_unref (GST_OBJECT (peer));
1330 if (gst_base_parse_convert (parse, GST_FORMAT_BYTES, ptot,
1331 GST_FORMAT_TIME, &dest_value)) {
1333 /* inform if duration changed, but try to avoid spamming */
1334 parse->priv->estimated_drift +=
1335 dest_value - parse->priv->estimated_duration;
1336 if (parse->priv->estimated_drift > GST_SECOND ||
1337 parse->priv->estimated_drift < -GST_SECOND) {
1338 gst_element_post_message (GST_ELEMENT (parse),
1339 gst_message_new_duration (GST_OBJECT (parse),
1340 GST_FORMAT_TIME, dest_value));
1341 parse->priv->estimated_drift = 0;
1343 parse->priv->estimated_duration = dest_value;
1344 GST_LOG_OBJECT (parse,
1345 "updated estimated duration to %" GST_TIME_FORMAT,
1346 GST_TIME_ARGS (dest_value));
1353 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1354 gboolean post_avg, gboolean post_max)
1356 GstTagList *taglist = NULL;
1358 if (post_min && parse->priv->post_min_bitrate) {
1359 taglist = gst_tag_list_new_empty ();
1361 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1362 GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1365 if (post_avg && parse->priv->post_avg_bitrate) {
1366 if (taglist == NULL)
1367 taglist = gst_tag_list_new_empty ();
1369 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1370 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1371 parse->priv->avg_bitrate, NULL);
1374 if (post_max && parse->priv->post_max_bitrate) {
1375 if (taglist == NULL)
1376 taglist = gst_tag_list_new_empty ();
1378 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1379 GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1382 GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1383 parse->priv->min_bitrate, parse->priv->avg_bitrate,
1384 parse->priv->max_bitrate);
1386 if (taglist != NULL) {
1387 gst_pad_push_event (parse->srcpad, gst_event_new_tag (taglist));
1391 /* gst_base_parse_update_bitrates:
1392 * @parse: #GstBaseParse.
1393 * @buffer: Current frame as a #GstBuffer
1395 * Keeps track of the minimum and maximum bitrates, and also maintains a
1396 * running average bitrate of the stream so far.
1399 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1401 /* Only update the tag on a 10 kbps delta */
1402 static const gint update_threshold = 10000;
1404 guint64 data_len, frame_dur;
1405 gint overhead, frame_bitrate, old_avg_bitrate;
1406 gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1407 GstBuffer *buffer = frame->buffer;
1409 overhead = frame->overhead;
1413 data_len = gst_buffer_get_size (buffer) - overhead;
1414 parse->priv->data_bytecount += data_len;
1416 /* duration should be valid by now,
1417 * either set by subclass or maybe based on fps settings */
1418 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1419 /* Calculate duration of a frame from buffer properties */
1420 frame_dur = GST_BUFFER_DURATION (buffer);
1421 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1422 parse->priv->acc_duration;
1425 /* No way to figure out frame duration (is this even possible?) */
1429 /* override if subclass provided bitrate, e.g. metadata based */
1430 if (parse->priv->bitrate) {
1431 parse->priv->avg_bitrate = parse->priv->bitrate;
1432 /* spread this (confirmed) info ASAP */
1433 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1434 gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1438 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1442 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1443 parse->priv->avg_bitrate);
1445 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1447 } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1448 /* always post all at threshold time */
1449 update_min = update_max = update_avg = TRUE;
1452 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1453 if (frame_bitrate < parse->priv->min_bitrate) {
1454 parse->priv->min_bitrate = frame_bitrate;
1458 if (frame_bitrate > parse->priv->max_bitrate) {
1459 parse->priv->max_bitrate = frame_bitrate;
1463 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1464 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1465 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1470 if ((update_min || update_avg || update_max))
1471 gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1473 /* If average bitrate changes that much and no valid (time) duration provided,
1474 * then post a new duration message so applications can update their cached
1476 if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1477 GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1478 gst_element_post_message (GST_ELEMENT (parse),
1479 gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1486 * gst_base_parse_add_index_entry:
1487 * @parse: #GstBaseParse.
1488 * @offset: offset of entry
1489 * @ts: timestamp associated with offset
1490 * @key: whether entry refers to keyframe
1491 * @force: add entry disregarding sanity checks
1493 * Adds an entry to the index associating @offset to @ts. It is recommended
1494 * to only add keyframe entries. @force allows to bypass checks, such as
1495 * whether the stream is (upstream) seekable, another entry is already "close"
1496 * to the new entry, etc.
1498 * Returns: #gboolean indicating whether entry was added
1503 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1504 GstClockTime ts, gboolean key, gboolean force)
1506 gboolean ret = FALSE;
1507 GstIndexAssociation associations[2];
1509 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1510 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1512 if (G_LIKELY (!force)) {
1514 if (!parse->priv->upstream_seekable) {
1515 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1519 /* FIXME need better helper data structure that handles these issues
1520 * related to ongoing collecting of index entries */
1521 if (parse->priv->index_last_offset >= (gint64) offset) {
1522 GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1523 "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1527 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1528 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1529 parse->priv->idx_interval) {
1530 GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1531 GST_TIME_ARGS (parse->priv->index_last_ts));
1535 /* if last is not really the last one */
1536 if (!parse->priv->index_last_valid) {
1537 GstClockTime prev_ts;
1539 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1540 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1541 GST_DEBUG_OBJECT (parse,
1542 "entry too close to existing entry %" GST_TIME_FORMAT,
1543 GST_TIME_ARGS (prev_ts));
1544 parse->priv->index_last_offset = offset;
1545 parse->priv->index_last_ts = ts;
1551 associations[0].format = GST_FORMAT_TIME;
1552 associations[0].value = ts;
1553 associations[1].format = GST_FORMAT_BYTES;
1554 associations[1].value = offset;
1556 /* index might change on-the-fly, although that would be nutty app ... */
1557 g_static_mutex_lock (&parse->priv->index_lock);
1558 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1559 (key) ? GST_ASSOCIATION_FLAG_KEY_UNIT : GST_ASSOCIATION_FLAG_DELTA_UNIT,
1560 2, (const GstIndexAssociation *) &associations);
1561 g_static_mutex_unlock (&parse->priv->index_lock);
1564 parse->priv->index_last_offset = offset;
1565 parse->priv->index_last_ts = ts;
1574 /* check for seekable upstream, above and beyond a mere query */
1576 gst_base_parse_check_seekability (GstBaseParse * parse)
1579 gboolean seekable = FALSE;
1580 gint64 start = -1, stop = -1;
1581 guint idx_interval = 0;
1583 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1584 if (!gst_pad_peer_query (parse->sinkpad, query)) {
1585 GST_DEBUG_OBJECT (parse, "seeking query failed");
1589 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1591 /* try harder to query upstream size if we didn't get it the first time */
1592 if (seekable && stop == -1) {
1593 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1594 gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_BYTES, &stop);
1597 /* if upstream doesn't know the size, it's likely that it's not seekable in
1598 * practice even if it technically may be seekable */
1599 if (seekable && (start != 0 || stop <= start)) {
1600 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1604 /* let's not put every single frame into our index */
1606 if (stop < 10 * 1024 * 1024)
1608 else if (stop < 100 * 1024 * 1024)
1611 idx_interval = 1000;
1615 gst_query_unref (query);
1617 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1618 G_GUINT64_FORMAT ")", seekable, start, stop);
1619 parse->priv->upstream_seekable = seekable;
1620 parse->priv->upstream_size = seekable ? stop : 0;
1622 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1623 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1626 /* some misc checks on upstream */
1628 gst_base_parse_check_upstream (GstBaseParse * parse)
1632 if (gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_TIME, &stop))
1633 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1634 /* upstream has one, accept it also, and no further updates */
1635 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1636 parse->priv->upstream_has_duration = TRUE;
1639 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1640 parse->priv->upstream_has_duration);
1643 /* checks src caps to determine if dealing with audio or video */
1644 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1646 gst_base_parse_check_media (GstBaseParse * parse)
1651 caps = gst_pad_get_current_caps (parse->srcpad);
1652 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1653 parse->priv->is_video =
1654 g_str_has_prefix (gst_structure_get_name (s), "video");
1656 /* historical default */
1657 parse->priv->is_video = FALSE;
1660 gst_caps_unref (caps);
1662 GST_DEBUG_OBJECT (parse, "media is video: %d", parse->priv->is_video);
1665 /* takes ownership of frame */
1667 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1669 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1670 /* frame allocated on the heap, we can just take ownership */
1671 g_queue_push_tail (&parse->priv->queued_frames, frame);
1672 GST_TRACE ("queued frame %p", frame);
1674 GstBaseParseFrame *copy;
1676 /* probably allocated on the stack, must make a proper copy */
1677 copy = gst_base_parse_frame_copy (frame);
1678 g_queue_push_tail (&parse->priv->queued_frames, copy);
1679 GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1680 gst_base_parse_frame_free (frame);
1684 /* gst_base_parse_handle_and_push_buffer:
1685 * @parse: #GstBaseParse.
1686 * @klass: #GstBaseParseClass.
1687 * @frame: (transfer full): a #GstBaseParseFrame
1689 * Parses the frame from given buffer and pushes it forward. Also performs
1690 * timestamp handling and checks the segment limits.
1692 * This is called with srcpad STREAM_LOCK held.
1694 * Returns: #GstFlowReturn
1696 static GstFlowReturn
1697 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1698 GstBaseParseClass * klass, GstBaseParseFrame * frame)
1704 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1706 buffer = frame->buffer;
1708 if (parse->priv->discont) {
1709 GST_DEBUG_OBJECT (parse, "marking DISCONT");
1710 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1711 parse->priv->discont = FALSE;
1714 /* some one-time start-up */
1715 if (G_UNLIKELY (!parse->priv->framecount)) {
1716 gst_base_parse_check_seekability (parse);
1717 gst_base_parse_check_upstream (parse);
1720 GST_LOG_OBJECT (parse,
1721 "parsing frame at offset %" G_GUINT64_FORMAT
1722 " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
1723 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1724 gst_buffer_get_size (buffer));
1726 /* use default handler to provide initial (upstream) metadata */
1727 gst_base_parse_parse_frame (parse, frame);
1729 /* store offset as it might get overwritten */
1730 offset = GST_BUFFER_OFFSET (buffer);
1731 ret = klass->parse_frame (parse, frame);
1733 buffer = frame->buffer;
1734 /* subclass must play nice */
1735 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1737 /* check if subclass/format can provide ts.
1738 * If so, that allows and enables extra seek and duration determining options */
1739 if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
1740 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && parse->priv->has_timing_info
1741 && parse->priv->pad_mode == GST_PAD_ACTIVATE_PULL) {
1742 parse->priv->first_frame_offset = offset;
1743 parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1744 GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1745 " for first frame at offset %" G_GINT64_FORMAT,
1746 GST_TIME_ARGS (parse->priv->first_frame_ts),
1747 parse->priv->first_frame_offset);
1748 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1750 GstClockTime last_ts = G_MAXINT64;
1752 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1753 gst_base_parse_locate_time (parse, &last_ts, &off);
1754 if (GST_CLOCK_TIME_IS_VALID (last_ts))
1755 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1758 /* disable further checks */
1759 parse->priv->first_frame_offset = 0;
1763 /* again use default handler to add missing metadata;
1764 * we may have new information on frame properties */
1765 gst_base_parse_parse_frame (parse, frame);
1766 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1767 GST_BUFFER_DURATION_IS_VALID (buffer)) {
1768 parse->priv->next_ts =
1769 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1771 /* we lost track, do not produce bogus time next time around
1772 * (probably means parser subclass has given up on parsing as well) */
1773 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1774 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1777 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1778 GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1779 gst_base_parse_add_index_entry (parse, offset,
1780 GST_BUFFER_TIMESTAMP (buffer),
1781 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1783 /* First buffers are dropped, this means that the subclass needs more
1784 * frames to decide on the format and queues them internally */
1785 /* convert internal flow to OK and mark discont for the next buffer. */
1786 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1787 gst_base_parse_frame_free (frame);
1789 } else if (ret == GST_BASE_PARSE_FLOW_QUEUED) {
1790 gst_base_parse_queue_frame (parse, frame);
1792 } else if (ret != GST_FLOW_OK) {
1796 /* All OK, push queued frames if there are any */
1797 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
1798 GstBaseParseFrame *queued_frame;
1800 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
1801 gst_base_parse_push_frame (parse, queued_frame);
1805 return gst_base_parse_push_frame (parse, frame);
1809 * gst_base_parse_push_frame:
1810 * @parse: #GstBaseParse.
1811 * @frame: (transfer full): a #GstBaseParseFrame
1813 * Pushes the frame downstream, sends any pending events and
1814 * does some timestamp and segment handling. Takes ownership
1815 * of @frame and will clear it (if it was initialised with
1816 * gst_base_parse_frame_init()) or free it.
1818 * This must be called with sinkpad STREAM_LOCK held.
1820 * Returns: #GstFlowReturn
1825 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1827 GstFlowReturn ret = GST_FLOW_OK;
1828 GstClockTime last_start = GST_CLOCK_TIME_NONE;
1829 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1830 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1834 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1835 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
1837 GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
1839 buffer = frame->buffer;
1841 GST_LOG_OBJECT (parse,
1842 "processing buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1843 ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buffer),
1844 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1845 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1848 size = gst_buffer_get_size (buffer);
1849 parse->priv->bytecount += size;
1850 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1851 parse->priv->framecount++;
1852 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1853 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1856 /* 0 means disabled */
1857 if (parse->priv->update_interval < 0)
1858 parse->priv->update_interval = 50;
1859 else if (parse->priv->update_interval > 0 &&
1860 (parse->priv->framecount % parse->priv->update_interval) == 0)
1861 gst_base_parse_update_duration (parse);
1863 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1864 last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1865 if (last_start != GST_CLOCK_TIME_NONE
1866 && GST_BUFFER_DURATION_IS_VALID (buffer))
1867 last_stop = last_start + GST_BUFFER_DURATION (buffer);
1869 /* should have caps by now */
1870 g_return_val_if_fail (gst_pad_has_current_caps (parse->srcpad),
1873 /* segment adjustment magic; only if we are running the whole show */
1874 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1875 (parse->priv->pad_mode == GST_PAD_ACTIVATE_PULL ||
1876 parse->priv->upstream_seekable)) {
1877 /* segment times are typically estimates,
1878 * actual frame data might lead subclass to different timestamps,
1879 * so override segment start from what is supplied there */
1880 if (G_UNLIKELY (parse->priv->pending_segment && !parse->priv->exact_position
1881 && GST_CLOCK_TIME_IS_VALID (last_start))) {
1882 gst_event_unref (parse->priv->pending_segment);
1883 parse->segment.start =
1884 MIN ((guint64) last_start, (guint64) parse->segment.stop);
1886 GST_DEBUG_OBJECT (parse,
1887 "adjusting pending segment start to %" GST_TIME_FORMAT,
1888 GST_TIME_ARGS (parse->segment.start));
1890 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
1892 /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1893 if (GST_CLOCK_TIME_IS_VALID (parse->segment.position) &&
1894 GST_CLOCK_TIME_IS_VALID (last_start)) {
1895 GstClockTimeDiff diff;
1897 /* only send newsegments with increasing start times,
1898 * otherwise if these go back and forth downstream (sinks) increase
1899 * accumulated time and running_time */
1900 diff = GST_CLOCK_DIFF (parse->segment.position, last_start);
1901 if (G_UNLIKELY (diff > 2 * GST_SECOND
1902 && last_start > parse->segment.start
1903 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
1904 || last_start < parse->segment.stop))) {
1906 GST_DEBUG_OBJECT (parse,
1907 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
1908 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1909 "Sending updated NEWSEGMENT events", diff,
1910 GST_TIME_ARGS (parse->segment.position),
1911 GST_TIME_ARGS (last_start));
1913 if (G_UNLIKELY (parse->priv->pending_segment)) {
1914 gst_event_unref (parse->priv->pending_segment);
1915 parse->segment.start = last_start;
1916 parse->segment.time = last_start;
1917 parse->priv->pending_segment =
1918 gst_event_new_segment (&parse->segment);
1920 /* skip gap FIXME */
1921 gst_pad_push_event (parse->srcpad,
1922 gst_event_new_segment (&parse->segment));
1924 parse->segment.position = last_start;
1929 /* and should then also be linked downstream, so safe to send some events */
1930 if (G_UNLIKELY (parse->priv->close_segment)) {
1931 /* only set up by loop */
1932 GST_DEBUG_OBJECT (parse, "loop sending close segment");
1933 gst_pad_push_event (parse->srcpad, parse->priv->close_segment);
1934 parse->priv->close_segment = NULL;
1936 if (G_UNLIKELY (parse->priv->pending_segment)) {
1937 GstEvent *pending_segment;
1939 pending_segment = parse->priv->pending_segment;
1940 parse->priv->pending_segment = NULL;
1942 GST_DEBUG_OBJECT (parse, "%s push pending segment",
1943 parse->priv->pad_mode == GST_PAD_ACTIVATE_PULL ? "loop" : "chain");
1944 gst_pad_push_event (parse->srcpad, pending_segment);
1946 /* have caps; check identity */
1947 gst_base_parse_check_media (parse);
1950 /* update bitrates and optionally post corresponding tags
1951 * (following newsegment) */
1952 gst_base_parse_update_bitrates (parse, frame);
1954 if (G_UNLIKELY (parse->priv->pending_events)) {
1957 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1958 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1960 g_list_free (parse->priv->pending_events);
1961 parse->priv->pending_events = NULL;
1964 if (klass->pre_push_frame) {
1965 ret = klass->pre_push_frame (parse, frame);
1967 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
1970 /* take final ownership of frame buffer */
1971 buffer = frame->buffer;
1972 frame->buffer = NULL;
1974 /* subclass must play nice */
1975 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1977 parse->priv->seen_keyframe |= parse->priv->is_video &&
1978 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1980 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
1981 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1982 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
1983 GST_BUFFER_TIMESTAMP (buffer) >
1984 parse->segment.stop + parse->priv->lead_out_ts) {
1985 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
1987 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1988 GST_BUFFER_DURATION_IS_VALID (buffer) &&
1989 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
1990 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
1991 parse->priv->lead_in_ts < parse->segment.start) {
1992 if (parse->priv->seen_keyframe) {
1993 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
1996 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
1997 ret = GST_BASE_PARSE_FLOW_DROPPED;
2004 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
2005 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) dropped", size);
2006 gst_buffer_unref (buffer);
2008 } else if (ret == GST_FLOW_OK) {
2009 if (parse->segment.rate > 0.0) {
2010 GST_LOG_OBJECT (parse, "pushing frame (%" G_GSIZE_FORMAT " bytes) now..",
2012 ret = gst_pad_push (parse->srcpad, buffer);
2013 GST_LOG_OBJECT (parse, "frame pushed, flow %s", gst_flow_get_name (ret));
2015 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) queued for now",
2017 parse->priv->buffers_queued =
2018 g_slist_prepend (parse->priv->buffers_queued, buffer);
2022 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s",
2023 size, gst_flow_get_name (ret));
2024 gst_buffer_unref (buffer);
2025 /* if we are not sufficiently in control, let upstream decide on EOS */
2026 if (ret == GST_FLOW_EOS &&
2027 (parse->priv->passthrough ||
2028 (parse->priv->pad_mode == GST_PAD_ACTIVATE_PUSH &&
2029 !parse->priv->upstream_seekable)))
2033 /* Update current running segment position */
2034 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
2035 parse->segment.position < last_stop)
2036 parse->segment.position = last_stop;
2038 gst_base_parse_frame_free (frame);
2044 /* gst_base_parse_drain:
2046 * Drains the adapter until it is empty. It decreases the min_frame_size to
2047 * match the current adapter size and calls chain method until the adapter
2048 * is emptied or chain returns with error.
2051 gst_base_parse_drain (GstBaseParse * parse)
2055 GST_DEBUG_OBJECT (parse, "draining");
2056 parse->priv->drain = TRUE;
2059 avail = gst_adapter_available (parse->priv->adapter);
2063 if (gst_base_parse_chain (parse->sinkpad, GST_OBJECT_CAST (parse),
2064 NULL) != GST_FLOW_OK) {
2068 /* nothing changed, maybe due to truncated frame; break infinite loop */
2069 if (avail == gst_adapter_available (parse->priv->adapter)) {
2070 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
2071 gst_adapter_clear (parse->priv->adapter);
2075 parse->priv->drain = FALSE;
2078 /* gst_base_parse_send_buffers
2080 * Sends buffers collected in send_buffers downstream, and ensures that list
2081 * is empty at the end (errors or not).
2083 static GstFlowReturn
2084 gst_base_parse_send_buffers (GstBaseParse * parse)
2086 GSList *send = NULL;
2088 GstFlowReturn ret = GST_FLOW_OK;
2090 send = parse->priv->buffers_send;
2094 buf = GST_BUFFER_CAST (send->data);
2095 GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
2096 GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2097 ", offset %" G_GINT64_FORMAT, buf,
2098 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2099 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2101 /* iterate output queue an push downstream */
2102 ret = gst_pad_push (parse->srcpad, buf);
2103 send = g_slist_delete_link (send, send);
2105 /* clear any leftover if error */
2106 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2108 buf = GST_BUFFER_CAST (send->data);
2109 gst_buffer_unref (buf);
2110 send = g_slist_delete_link (send, send);
2115 parse->priv->buffers_send = send;
2120 /* gst_base_parse_process_fragment:
2122 * Processes a reverse playback (forward) fragment:
2123 * - append head of last fragment that was skipped to current fragment data
2124 * - drain the resulting current fragment data (i.e. repeated chain)
2125 * - add time/duration (if needed) to frames queued by chain
2126 * - push queued data
2128 static GstFlowReturn
2129 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
2132 GstFlowReturn ret = GST_FLOW_OK;
2133 gboolean seen_key = FALSE, seen_delta = FALSE;
2139 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2140 while (parse->priv->buffers_pending) {
2141 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2142 GST_LOG_OBJECT (parse, "adding pending buffer (size %" G_GSIZE_FORMAT ")",
2143 gst_buffer_get_size (buf));
2144 gst_adapter_push (parse->priv->adapter, buf);
2145 parse->priv->buffers_pending =
2146 g_slist_delete_link (parse->priv->buffers_pending,
2147 parse->priv->buffers_pending);
2150 /* invalidate so no fall-back timestamping is performed;
2151 * ok if taken from subclass or upstream */
2152 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
2153 /* prevent it hanging around stop all the time */
2154 parse->segment.position = GST_CLOCK_TIME_NONE;
2156 parse->priv->discont = TRUE;
2158 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2159 /* initial skipped data is added to buffers_pending */
2160 gst_base_parse_drain (parse);
2163 if (parse->priv->buffers_send) {
2164 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2165 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2168 /* add metadata (if needed to queued buffers */
2169 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2170 GST_TIME_ARGS (parse->priv->last_ts));
2171 while (parse->priv->buffers_queued) {
2172 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2174 /* no touching if upstream or parsing provided time */
2175 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2176 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2177 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2178 } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
2179 GST_BUFFER_DURATION_IS_VALID (buf)) {
2180 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
2181 parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
2183 parse->priv->last_ts = 0;
2184 GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
2185 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2186 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2188 /* no idea, very bad */
2189 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2192 parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
2194 /* reverse order for ascending sending */
2195 /* send downstream at keyframe not preceded by a keyframe
2196 * (e.g. that should identify start of collection of IDR nals) */
2197 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2199 ret = gst_base_parse_send_buffers (parse);
2200 /* if a problem, throw all to sending */
2201 if (ret != GST_FLOW_OK) {
2202 parse->priv->buffers_send =
2203 g_slist_reverse (parse->priv->buffers_queued);
2204 parse->priv->buffers_queued = NULL;
2213 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2215 parse->priv->buffers_send =
2216 g_slist_prepend (parse->priv->buffers_send, buf);
2217 parse->priv->buffers_queued =
2218 g_slist_delete_link (parse->priv->buffers_queued,
2219 parse->priv->buffers_queued);
2222 /* audio may have all marked as keyframe, so arrange to send here */
2224 ret = gst_base_parse_send_buffers (parse);
2226 /* any trailing unused no longer usable (ideally none) */
2227 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2228 GST_DEBUG_OBJECT (parse, "discarding %" G_GSIZE_FORMAT " trailing bytes",
2229 gst_adapter_available (parse->priv->adapter));
2230 gst_adapter_clear (parse->priv->adapter);
2236 /* small helper that checks whether we have been trying to resync too long */
2237 static inline GstFlowReturn
2238 gst_base_parse_check_sync (GstBaseParse * parse)
2240 if (G_UNLIKELY (parse->priv->discont &&
2241 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2242 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2243 ("Failed to parse stream"), (NULL));
2244 return GST_FLOW_ERROR;
2250 static GstFlowReturn
2251 gst_base_parse_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2253 GstBaseParseClass *bclass;
2254 GstBaseParse *parse;
2255 GstFlowReturn ret = GST_FLOW_OK;
2256 GstBuffer *outbuf = NULL;
2257 GstBuffer *tmpbuf = NULL;
2261 guint old_min_size = 0, min_size, av;
2262 GstClockTime timestamp;
2263 GstBaseParseFrame *frame;
2265 parse = GST_BASE_PARSE (parent);
2266 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2268 if (parse->priv->detecting) {
2269 GstBuffer *detect_buf;
2271 if (parse->priv->detect_buffers_size == 0) {
2272 detect_buf = gst_buffer_ref (buffer);
2277 detect_buf = gst_buffer_new ();
2279 for (l = parse->priv->detect_buffers; l; l = l->next) {
2280 gsize tmpsize = gst_buffer_get_size (l->data);
2282 gst_buffer_copy_into (detect_buf, GST_BUFFER_CAST (l->data),
2283 GST_BUFFER_COPY_MEMORY, offset, tmpsize);
2287 gst_buffer_copy_into (detect_buf, buffer, GST_BUFFER_COPY_MEMORY,
2288 offset, gst_buffer_get_size (buffer));
2291 ret = bclass->detect (parse, detect_buf);
2292 gst_buffer_unref (detect_buf);
2294 if (ret == GST_FLOW_OK) {
2297 /* Detected something */
2298 parse->priv->detecting = FALSE;
2300 for (l = parse->priv->detect_buffers; l; l = l->next) {
2301 if (ret == GST_FLOW_OK && !parse->priv->flushing)
2303 gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2304 parent, GST_BUFFER_CAST (l->data));
2306 gst_buffer_unref (GST_BUFFER_CAST (l->data));
2308 g_list_free (parse->priv->detect_buffers);
2309 parse->priv->detect_buffers = NULL;
2310 parse->priv->detect_buffers_size = 0;
2312 if (ret != GST_FLOW_OK) {
2316 /* Handle the current buffer */
2317 } else if (ret == GST_FLOW_NOT_NEGOTIATED) {
2318 /* Still detecting, append buffer or error out if draining */
2320 if (parse->priv->drain) {
2321 GST_DEBUG_OBJECT (parse, "Draining but did not detect format yet");
2322 return GST_FLOW_ERROR;
2323 } else if (parse->priv->flushing) {
2324 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref,
2326 g_list_free (parse->priv->detect_buffers);
2327 parse->priv->detect_buffers = NULL;
2328 parse->priv->detect_buffers_size = 0;
2330 parse->priv->detect_buffers =
2331 g_list_append (parse->priv->detect_buffers, buffer);
2332 parse->priv->detect_buffers_size += gst_buffer_get_size (buffer);
2336 /* Something went wrong, subclass responsible for error reporting */
2340 /* And now handle the current buffer if detection worked */
2343 frame = &parse->priv->frame;
2345 if (G_LIKELY (buffer)) {
2346 GST_LOG_OBJECT (parse,
2347 "buffer size: %" G_GSIZE_FORMAT ", offset = %" G_GINT64_FORMAT,
2348 gst_buffer_get_size (buffer), GST_BUFFER_OFFSET (buffer));
2349 if (G_UNLIKELY (parse->priv->passthrough)) {
2350 gst_base_parse_frame_init (frame);
2351 frame->buffer = gst_buffer_make_writable (buffer);
2352 return gst_base_parse_push_frame (parse, frame);
2354 /* upstream feeding us in reverse playback;
2355 * gather each fragment, then process it in single run */
2356 if (parse->segment.rate < 0.0) {
2357 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2358 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2359 ret = gst_base_parse_process_fragment (parse, FALSE);
2361 gst_adapter_push (parse->priv->adapter, buffer);
2364 gst_adapter_push (parse->priv->adapter, buffer);
2367 if (G_UNLIKELY (buffer &&
2368 GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2369 frame->_private_flags |= GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
2370 gst_base_parse_frame_free (frame);
2373 /* Parse and push as many frames as possible */
2374 /* Stop either when adapter is empty or we are flushing */
2375 while (!parse->priv->flushing) {
2378 /* maintain frame state for a single frame parsing round across _chain calls,
2379 * so only init when needed */
2380 if (!frame->_private_flags)
2381 gst_base_parse_frame_init (frame);
2383 tmpbuf = gst_buffer_new ();
2386 /* Synchronization loop */
2388 /* note: if subclass indicates MAX fsize,
2389 * this will not likely be available anyway ... */
2390 min_size = MAX (parse->priv->min_frame_size, fsize);
2391 av = gst_adapter_available (parse->priv->adapter);
2393 /* loop safety check */
2394 if (G_UNLIKELY (old_min_size >= min_size))
2396 old_min_size = min_size;
2398 if (G_UNLIKELY (parse->priv->drain)) {
2400 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2401 if (G_UNLIKELY (!min_size)) {
2402 gst_buffer_unref (tmpbuf);
2407 /* Collect at least min_frame_size bytes */
2408 if (av < min_size) {
2409 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
2411 gst_buffer_unref (tmpbuf);
2415 /* always pass all available data */
2416 data = gst_adapter_map (parse->priv->adapter, av);
2417 gst_buffer_take_memory (tmpbuf, -1,
2418 gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
2419 (gpointer) data, NULL, av, 0, av));
2420 GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
2422 if (parse->priv->discont) {
2423 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2424 GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2428 gst_base_parse_frame_update (parse, frame, tmpbuf);
2429 res = bclass->check_valid_frame (parse, frame, &fsize, &skip);
2430 gst_adapter_unmap (parse->priv->adapter);
2431 gst_buffer_replace (&frame->buffer, NULL);
2432 gst_buffer_remove_memory_range (tmpbuf, 0, -1);
2434 if (gst_adapter_available (parse->priv->adapter) < fsize) {
2435 GST_DEBUG_OBJECT (parse, "found valid frame but not enough data"
2436 " available (only %" G_GSIZE_FORMAT " bytes)",
2437 gst_adapter_available (parse->priv->adapter));
2438 gst_buffer_unref (tmpbuf);
2441 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2445 /* subclass didn't touch this value. By default we skip 1 byte */
2449 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2450 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2451 /* reverse playback, and no frames found yet, so we are skipping
2452 * the leading part of a fragment, which may form the tail of
2453 * fragment coming later, hopefully subclass skips efficiently ... */
2454 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2455 outbuf = gst_adapter_take_buffer (parse->priv->adapter, skip);
2456 outbuf = gst_buffer_make_writable (outbuf);
2457 GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
2458 parse->priv->buffers_pending =
2459 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2462 gst_adapter_flush (parse->priv->adapter, skip);
2464 parse->priv->offset += skip;
2465 if (!parse->priv->discont)
2466 parse->priv->sync_offset = parse->priv->offset;
2467 parse->priv->discont = TRUE;
2468 /* something changed least; nullify loop check */
2471 /* skip == 0 should imply subclass set min_size to need more data;
2472 * we check this shortly */
2473 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2474 gst_buffer_unref (tmpbuf);
2478 gst_buffer_unref (tmpbuf);
2482 /* Subclass found the sync, but still wants to skip some data */
2483 GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
2484 gst_adapter_flush (parse->priv->adapter, skip);
2485 parse->priv->offset += skip;
2488 /* Grab lock to prevent a race with FLUSH_START handler */
2489 GST_PAD_STREAM_LOCK (parse->srcpad);
2491 /* FLUSH_START event causes the "flushing" flag to be set. In this
2492 * case we can leave the frame pushing loop */
2493 if (parse->priv->flushing) {
2494 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2498 /* move along with upstream timestamp (if any),
2499 * but interpolate in between */
2500 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2501 if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2502 (parse->priv->prev_ts != timestamp)) {
2503 parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2506 /* FIXME: Would it be more efficient to make a subbuffer instead? */
2507 outbuf = gst_adapter_take_buffer (parse->priv->adapter, fsize);
2508 outbuf = gst_buffer_make_writable (outbuf);
2510 /* Subclass may want to know the data offset */
2511 GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2512 parse->priv->offset += fsize;
2513 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2514 GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
2516 frame->buffer = outbuf;
2517 ret = gst_base_parse_handle_and_push_frame (parse, bclass, frame);
2518 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2520 if (ret != GST_FLOW_OK) {
2521 GST_LOG_OBJECT (parse, "push returned %d", ret);
2527 GST_LOG_OBJECT (parse, "chain leaving");
2533 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2534 ("min_size evolution %d -> %d; breaking to avoid looping",
2535 old_min_size, min_size));
2536 return GST_FLOW_ERROR;
2540 /* pull @size bytes at current offset,
2541 * i.e. at least try to and possibly return a shorter buffer if near the end */
2542 static GstFlowReturn
2543 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2544 GstBuffer ** buffer)
2546 GstFlowReturn ret = GST_FLOW_OK;
2548 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2550 /* Caching here actually makes much less difference than one would expect.
2551 * We do it mainly to avoid pulling buffers of 1 byte all the time */
2552 if (parse->priv->cache) {
2553 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2554 gint cache_size = gst_buffer_get_size (parse->priv->cache);
2556 if (cache_offset <= parse->priv->offset &&
2557 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2558 *buffer = gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL,
2559 parse->priv->offset - cache_offset, size);
2560 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2563 /* not enough data in the cache, free cache and get a new one */
2564 gst_buffer_unref (parse->priv->cache);
2565 parse->priv->cache = NULL;
2568 /* refill the cache */
2570 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2571 64 * 1024), &parse->priv->cache);
2572 if (ret != GST_FLOW_OK) {
2573 parse->priv->cache = NULL;
2577 if (gst_buffer_get_size (parse->priv->cache) >= size) {
2579 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0,
2581 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2585 /* Not possible to get enough data, try a last time with
2586 * requesting exactly the size we need */
2587 gst_buffer_unref (parse->priv->cache);
2588 parse->priv->cache = NULL;
2590 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2591 &parse->priv->cache);
2593 if (ret != GST_FLOW_OK) {
2594 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2599 if (gst_buffer_get_size (parse->priv->cache) < size) {
2600 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2601 G_GUINT64_FORMAT ": wanted %u bytes, got %" G_GSIZE_FORMAT " bytes",
2602 parse->priv->offset, size, gst_buffer_get_size (parse->priv->cache));
2604 *buffer = parse->priv->cache;
2605 parse->priv->cache = NULL;
2611 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0, size);
2612 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2617 static GstFlowReturn
2618 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2621 GstClockTime ts = 0;
2625 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2626 ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2627 parse->priv->last_offset);
2629 if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2630 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2631 GST_TIME_ARGS (parse->segment.start));
2636 /* last fragment started at last_offset / last_ts;
2637 * seek back 10s capped at 1MB */
2638 if (parse->priv->last_ts >= 10 * GST_SECOND)
2639 ts = parse->priv->last_ts - 10 * GST_SECOND;
2640 /* if we are exact now, we will be more so going backwards */
2641 if (parse->priv->exact_position) {
2642 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2644 if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2645 GST_FORMAT_BYTES, &offset)) {
2646 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2649 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2650 parse->priv->last_offset - 1024);
2651 offset = MAX (0, offset);
2653 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2655 parse->priv->offset = offset;
2657 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2659 if (ret != GST_FLOW_OK)
2662 /* offset will increase again as fragment is processed/parsed */
2663 parse->priv->last_offset = offset;
2665 gst_adapter_push (parse->priv->adapter, buffer);
2666 ret = gst_base_parse_process_fragment (parse, FALSE);
2667 if (ret != GST_FLOW_OK)
2670 /* force previous fragment */
2671 parse->priv->offset = -1;
2678 * pull and scan for next frame starting from current offset
2679 * ajusts sync, drain and offset going along */
2680 static GstFlowReturn
2681 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2682 GstBaseParseFrame * frame, gboolean full)
2684 GstBuffer *buffer, *outbuf;
2685 GstFlowReturn ret = GST_FLOW_OK;
2686 guint fsize = 1, min_size, old_min_size = 0;
2689 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2691 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2692 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2694 /* let's make this efficient for all subclass once and for all;
2695 * maybe it does not need this much, but in the latter case, we know we are
2696 * in pull mode here and might as well try to read and supply more anyway
2697 * (so does the buffer caching mechanism) */
2703 min_size = MAX (parse->priv->min_frame_size, fsize);
2704 /* loop safety check */
2705 if (G_UNLIKELY (old_min_size >= min_size))
2707 old_min_size = min_size;
2709 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2710 if (ret != GST_FLOW_OK)
2713 if (parse->priv->discont) {
2714 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2715 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2718 /* if we got a short read, inform subclass we are draining leftover
2719 * and no more is to be expected */
2720 if (gst_buffer_get_size (buffer) < min_size)
2721 parse->priv->drain = TRUE;
2723 if (parse->priv->detecting) {
2724 ret = klass->detect (parse, buffer);
2725 if (ret == GST_FLOW_NOT_NEGOTIATED) {
2726 /* If draining we error out, otherwise request a buffer
2728 if (parse->priv->drain) {
2729 gst_buffer_unref (buffer);
2730 GST_ERROR_OBJECT (parse, "Failed to detect format but draining");
2731 return GST_FLOW_ERROR;
2734 gst_buffer_unref (buffer);
2737 } else if (ret != GST_FLOW_OK) {
2738 gst_buffer_unref (buffer);
2739 GST_ERROR_OBJECT (parse, "detect() returned %s",
2740 gst_flow_get_name (ret));
2744 /* Else handle this buffer normally */
2748 gst_base_parse_frame_update (parse, frame, buffer);
2749 res = klass->check_valid_frame (parse, frame, &fsize, &skip);
2750 gst_buffer_replace (&frame->buffer, NULL);
2752 parse->priv->drain = FALSE;
2753 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2756 parse->priv->drain = FALSE;
2760 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2761 if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2762 /* reverse playback, and no frames found yet, so we are skipping
2763 * the leading part of a fragment, which may form the tail of
2764 * fragment coming later, hopefully subclass skips efficiently ... */
2765 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, 0, skip);
2766 parse->priv->buffers_pending =
2767 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2770 parse->priv->offset += skip;
2771 if (!parse->priv->discont)
2772 parse->priv->sync_offset = parse->priv->offset;
2773 parse->priv->discont = TRUE;
2774 /* something changed at least; nullify loop check */
2775 if (fsize == G_MAXUINT)
2776 fsize = old_min_size + 64 * 1024;
2779 /* skip == 0 should imply subclass set min_size to need more data;
2780 * we check this shortly */
2781 GST_DEBUG_OBJECT (parse, "finding sync...");
2782 gst_buffer_unref (buffer);
2783 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2788 /* Does the subclass want to skip too? */
2790 parse->priv->offset += skip;
2794 if (fsize + skip <= gst_buffer_get_size (buffer)) {
2795 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, skip, fsize);
2796 GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2797 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2798 gst_buffer_unref (buffer);
2800 gst_buffer_unref (buffer);
2801 ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2802 if (ret != GST_FLOW_OK)
2804 if (gst_buffer_get_size (outbuf) < fsize) {
2805 gst_buffer_unref (outbuf);
2810 parse->priv->offset += fsize;
2812 frame->buffer = outbuf;
2820 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2821 ("min_size evolution %d -> %d; breaking to avoid looping",
2822 old_min_size, min_size));
2823 return GST_FLOW_ERROR;
2827 /* Loop that is used in pull mode to retrieve data from upstream */
2829 gst_base_parse_loop (GstPad * pad)
2831 GstBaseParse *parse;
2832 GstBaseParseClass *klass;
2833 GstFlowReturn ret = GST_FLOW_OK;
2834 GstBaseParseFrame frame;
2836 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2837 klass = GST_BASE_PARSE_GET_CLASS (parse);
2839 /* reverse playback:
2840 * first fragment (closest to stop time) is handled normally below,
2841 * then we pull in fragments going backwards */
2842 if (parse->segment.rate < 0.0) {
2843 /* check if we jumped back to a previous fragment,
2844 * which is a post-first fragment */
2845 if (parse->priv->offset < 0) {
2846 ret = gst_base_parse_handle_previous_fragment (parse);
2851 gst_base_parse_frame_init (&frame);
2852 ret = gst_base_parse_scan_frame (parse, klass, &frame, TRUE);
2853 if (ret != GST_FLOW_OK)
2856 /* This always cleans up frame, even if error occurs */
2857 ret = gst_base_parse_handle_and_push_frame (parse, klass, &frame);
2859 /* eat expected eos signalling past segment in reverse playback */
2860 if (parse->segment.rate < 0.0 && ret == GST_FLOW_EOS &&
2861 parse->segment.position >= parse->segment.stop) {
2862 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2863 /* push what was accumulated during loop run */
2864 gst_base_parse_process_fragment (parse, TRUE);
2865 /* force previous fragment */
2866 parse->priv->offset = -1;
2871 if (ret == GST_FLOW_EOS)
2873 else if (ret != GST_FLOW_OK)
2876 gst_object_unref (parse);
2883 GST_DEBUG_OBJECT (parse, "eos");
2888 gboolean push_eos = FALSE;
2890 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2891 gst_flow_get_name (ret));
2892 gst_pad_pause_task (parse->sinkpad);
2894 if (ret == GST_FLOW_EOS) {
2895 /* handle end-of-stream/segment */
2896 if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2899 if ((stop = parse->segment.stop) == -1)
2900 stop = parse->segment.duration;
2902 GST_DEBUG_OBJECT (parse, "sending segment_done");
2904 gst_element_post_message
2905 (GST_ELEMENT_CAST (parse),
2906 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2907 GST_FORMAT_TIME, stop));
2909 /* If we STILL have zero frames processed, fire an error */
2910 if (parse->priv->framecount == 0) {
2911 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2912 ("No valid frames found before end of stream"), (NULL));
2916 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
2917 /* for fatal errors we post an error message, wrong-state is
2918 * not fatal because it happens due to flushes and only means
2919 * that we should stop now. */
2920 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2921 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2925 /* newsegment before eos */
2926 if (parse->priv->pending_segment) {
2927 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
2928 parse->priv->pending_segment = NULL;
2930 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2932 gst_object_unref (parse);
2937 gst_base_parse_sink_activate (GstPad * sinkpad)
2939 GstBaseParse *parse;
2940 gboolean result = TRUE;
2944 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2946 GST_DEBUG_OBJECT (parse, "sink activate");
2948 query = gst_query_new_scheduling ();
2949 result = gst_pad_peer_query (sinkpad, query);
2951 gst_query_parse_scheduling (query, &pull_mode, NULL, NULL, NULL, NULL,
2956 gst_query_unref (query);
2959 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2960 result = gst_pad_activate_pull (sinkpad, TRUE);
2962 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
2963 result = gst_pad_activate_push (sinkpad, TRUE);
2966 GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
2967 gst_object_unref (parse);
2972 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
2974 GstBaseParseClass *klass;
2975 gboolean result = TRUE;
2977 GST_DEBUG_OBJECT (parse, "activate %d", active);
2979 klass = GST_BASE_PARSE_GET_CLASS (parse);
2982 if (parse->priv->pad_mode == GST_PAD_ACTIVATE_NONE && klass->start)
2983 result = klass->start (parse);
2985 /* If the subclass implements ::detect we want to
2986 * call it for the first buffers now */
2987 parse->priv->detecting = (klass->detect != NULL);
2989 /* We must make sure streaming has finished before resetting things
2990 * and calling the ::stop vfunc */
2991 GST_PAD_STREAM_LOCK (parse->sinkpad);
2992 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2994 if (parse->priv->pad_mode != GST_PAD_ACTIVATE_NONE && klass->stop)
2995 result = klass->stop (parse);
2997 parse->priv->pad_mode = GST_PAD_ACTIVATE_NONE;
2999 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
3004 gst_base_parse_sink_activate_push (GstPad * pad, gboolean active)
3006 gboolean result = TRUE;
3007 GstBaseParse *parse;
3009 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
3011 GST_DEBUG_OBJECT (parse, "sink activate push %d", active);
3013 result = gst_base_parse_activate (parse, active);
3016 parse->priv->pad_mode =
3017 active ? GST_PAD_ACTIVATE_PUSH : GST_PAD_ACTIVATE_NONE;
3019 GST_DEBUG_OBJECT (parse, "sink activate push return: %d", result);
3021 gst_object_unref (parse);
3026 gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
3028 gboolean result = FALSE;
3029 GstBaseParse *parse;
3031 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
3033 GST_DEBUG_OBJECT (parse, "activate pull %d", active);
3035 result = gst_base_parse_activate (parse, active);
3039 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
3041 gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
3044 result &= gst_pad_stop_task (sinkpad);
3049 parse->priv->pad_mode =
3050 active ? GST_PAD_ACTIVATE_PULL : GST_PAD_ACTIVATE_NONE;
3052 GST_DEBUG_OBJECT (parse, "sink activate pull return: %d", result);
3054 gst_object_unref (parse);
3060 * gst_base_parse_set_duration:
3061 * @parse: #GstBaseParse.
3063 * @duration: duration value.
3064 * @interval: how often to update the duration estimate based on bitrate, or 0.
3066 * Sets the duration of the currently playing media. Subclass can use this
3067 * when it is able to determine duration and/or notices a change in the media
3068 * duration. Alternatively, if @interval is non-zero (default), then stream
3069 * duration is determined based on estimated bitrate, and updated every @interval
3075 gst_base_parse_set_duration (GstBaseParse * parse,
3076 GstFormat fmt, gint64 duration, gint interval)
3078 g_return_if_fail (parse != NULL);
3080 if (parse->priv->upstream_has_duration) {
3081 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
3085 if (duration != parse->priv->duration) {
3088 m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
3089 gst_element_post_message (GST_ELEMENT (parse), m);
3091 /* TODO: what about duration tag? */
3093 parse->priv->duration = duration;
3094 parse->priv->duration_fmt = fmt;
3095 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
3096 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
3097 if (interval != 0) {
3098 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
3102 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
3103 parse->priv->update_interval = interval;
3109 * gst_base_parse_set_average_bitrate:
3110 * @parse: #GstBaseParse.
3111 * @bitrate: average bitrate in bits/second
3113 * Optionally sets the average bitrate detected in media (if non-zero),
3114 * e.g. based on metadata, as it will be posted to the application.
3116 * By default, announced average bitrate is estimated. The average bitrate
3117 * is used to estimate the total duration of the stream and to estimate
3118 * a seek position, if there's no index and the format is syncable
3119 * (see gst_base_parse_set_syncable()).
3124 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
3126 parse->priv->bitrate = bitrate;
3127 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
3131 * gst_base_parse_set_min_frame_size:
3132 * @parse: #GstBaseParse.
3133 * @min_size: Minimum size of the data that this base class should give to
3136 * Subclass can use this function to tell the base class that it needs to
3137 * give at least #min_size buffers.
3142 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
3144 g_return_if_fail (parse != NULL);
3146 parse->priv->min_frame_size = min_size;
3147 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
3151 * gst_base_parse_set_frame_rate:
3152 * @parse: the #GstBaseParse to set
3153 * @fps_num: frames per second (numerator).
3154 * @fps_den: frames per second (denominator).
3155 * @lead_in: frames needed before a segment for subsequent decode
3156 * @lead_out: frames needed after a segment
3158 * If frames per second is configured, parser can take care of buffer duration
3159 * and timestamping. When performing segment clipping, or seeking to a specific
3160 * location, a corresponding decoder might need an initial @lead_in and a
3161 * following @lead_out number of frames to ensure the desired segment is
3162 * entirely filled upon decoding.
3167 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
3168 guint fps_den, guint lead_in, guint lead_out)
3170 g_return_if_fail (parse != NULL);
3172 parse->priv->fps_num = fps_num;
3173 parse->priv->fps_den = fps_den;
3174 if (!fps_num || !fps_den) {
3175 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
3177 fps_num = fps_den = 0;
3178 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
3179 parse->priv->lead_in = parse->priv->lead_out = 0;
3180 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
3182 parse->priv->frame_duration =
3183 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
3184 parse->priv->lead_in = lead_in;
3185 parse->priv->lead_out = lead_out;
3186 parse->priv->lead_in_ts =
3187 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
3188 parse->priv->lead_out_ts =
3189 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
3190 /* aim for about 1.5s to estimate duration */
3191 if (parse->priv->update_interval < 0) {
3192 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
3193 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
3194 parse->priv->update_interval);
3197 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
3198 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
3199 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
3200 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
3201 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
3202 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
3206 * gst_base_parse_set_has_timing_info:
3207 * @parse: a #GstBaseParse
3208 * @has_timing: whether frames carry timing information
3210 * Set if frames carry timing information which the subclass can (generally)
3211 * parse and provide. In particular, intrinsic (rather than estimated) time
3212 * can be obtained following a seek.
3217 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3219 parse->priv->has_timing_info = has_timing;
3220 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3224 * gst_base_parse_set_syncable:
3225 * @parse: a #GstBaseParse
3226 * @syncable: set if frame starts can be identified
3228 * Set if frame starts can be identified. This is set by default and
3229 * determines whether seeking based on bitrate averages
3230 * is possible for a format/stream.
3235 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3237 parse->priv->syncable = syncable;
3238 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3242 * gst_base_parse_set_passthrough:
3243 * @parse: a #GstBaseParse
3244 * @passthrough: %TRUE if parser should run in passthrough mode
3246 * Set if the nature of the format or configuration does not allow (much)
3247 * parsing, and the parser should operate in passthrough mode (which only
3248 * applies when operating in push mode). That is, incoming buffers are
3249 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3250 * callbacks will be invoked, but @pre_push_frame will still be invoked,
3251 * so subclass can perform as much or as little is appropriate for
3252 * passthrough semantics in @pre_push_frame.
3257 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3259 parse->priv->passthrough = passthrough;
3260 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3264 * gst_base_parse_set_latency:
3265 * @parse: a #GstBaseParse
3266 * @min_latency: minimum parse latency
3267 * @max_latency: maximum parse latency
3269 * Sets the minimum and maximum (which may likely be equal) latency introduced
3270 * by the parsing process. If there is such a latency, which depends on the
3271 * particular parsing of the format, it typically corresponds to 1 frame duration.
3276 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3277 GstClockTime max_latency)
3279 GST_OBJECT_LOCK (parse);
3280 parse->priv->min_latency = min_latency;
3281 parse->priv->max_latency = max_latency;
3282 GST_OBJECT_UNLOCK (parse);
3283 GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3284 GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3285 GST_TIME_ARGS (max_latency));
3289 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3290 GstClockTime * duration)
3292 gboolean res = FALSE;
3294 g_return_val_if_fail (duration != NULL, FALSE);
3296 *duration = GST_CLOCK_TIME_NONE;
3297 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3298 GST_LOG_OBJECT (parse, "using provided duration");
3299 *duration = parse->priv->duration;
3301 } else if (parse->priv->duration != -1) {
3302 GST_LOG_OBJECT (parse, "converting provided duration");
3303 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3304 parse->priv->duration, format, (gint64 *) duration);
3305 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3306 GST_LOG_OBJECT (parse, "using estimated duration");
3307 *duration = parse->priv->estimated_duration;
3311 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3312 GST_TIME_ARGS (*duration));
3317 gst_base_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
3319 GstBaseParse *parse;
3320 gboolean res = FALSE;
3322 parse = GST_BASE_PARSE (parent);
3324 GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3326 switch (GST_QUERY_TYPE (query)) {
3327 case GST_QUERY_POSITION:
3332 GST_DEBUG_OBJECT (parse, "position query");
3333 gst_query_parse_position (query, &format, NULL);
3335 /* try upstream first */
3336 res = gst_pad_query_default (pad, parent, query);
3338 /* Fall back on interpreting segment */
3339 GST_OBJECT_LOCK (parse);
3340 if (format == GST_FORMAT_BYTES) {
3341 dest_value = parse->priv->offset;
3343 } else if (format == parse->segment.format &&
3344 GST_CLOCK_TIME_IS_VALID (parse->segment.position)) {
3345 dest_value = gst_segment_to_stream_time (&parse->segment,
3346 parse->segment.format, parse->segment.position);
3349 GST_OBJECT_UNLOCK (parse);
3351 /* no precise result, upstream no idea either, then best estimate */
3352 /* priv->offset is updated in both PUSH/PULL modes */
3353 res = gst_base_parse_convert (parse,
3354 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3357 gst_query_set_position (query, format, dest_value);
3361 case GST_QUERY_DURATION:
3364 GstClockTime duration;
3366 GST_DEBUG_OBJECT (parse, "duration query");
3367 gst_query_parse_duration (query, &format, NULL);
3369 /* consult upstream */
3370 res = gst_pad_query_default (pad, parent, query);
3372 /* otherwise best estimate from us */
3374 res = gst_base_parse_get_duration (parse, format, &duration);
3376 gst_query_set_duration (query, format, duration);
3380 case GST_QUERY_SEEKING:
3383 GstClockTime duration = GST_CLOCK_TIME_NONE;
3384 gboolean seekable = FALSE;
3386 GST_DEBUG_OBJECT (parse, "seeking query");
3387 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3389 /* consult upstream */
3390 res = gst_pad_query_default (pad, parent, query);
3392 /* we may be able to help if in TIME */
3393 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3394 gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3395 /* already OK if upstream takes care */
3396 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3398 if (!(res && seekable)) {
3399 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3400 || duration == -1) {
3401 /* seekable if we still have a chance to get duration later on */
3403 parse->priv->upstream_seekable && parse->priv->update_interval;
3405 seekable = parse->priv->upstream_seekable;
3406 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3409 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3415 case GST_QUERY_FORMATS:
3416 gst_query_set_formatsv (query, 3, fmtlist);
3419 case GST_QUERY_CONVERT:
3421 GstFormat src_format, dest_format;
3422 gint64 src_value, dest_value;
3424 gst_query_parse_convert (query, &src_format, &src_value,
3425 &dest_format, &dest_value);
3427 res = gst_base_parse_convert (parse, src_format, src_value,
3428 dest_format, &dest_value);
3430 gst_query_set_convert (query, src_format, src_value,
3431 dest_format, dest_value);
3435 case GST_QUERY_LATENCY:
3437 if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3439 GstClockTime min_latency, max_latency;
3441 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3442 GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3443 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3444 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3446 GST_OBJECT_LOCK (parse);
3447 /* add our latency */
3448 if (min_latency != -1)
3449 min_latency += parse->priv->min_latency;
3450 if (max_latency != -1)
3451 max_latency += parse->priv->max_latency;
3452 GST_OBJECT_UNLOCK (parse);
3454 gst_query_set_latency (query, live, min_latency, max_latency);
3459 res = gst_pad_query_default (pad, parent, query);
3465 /* scans for a cluster start from @pos,
3466 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3467 static GstFlowReturn
3468 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3469 GstClockTime * time, GstClockTime * duration)
3471 GstBaseParseClass *klass;
3473 gboolean orig_drain, orig_discont;
3474 GstFlowReturn ret = GST_FLOW_OK;
3475 GstBuffer *buf = NULL;
3476 GstBaseParseFrame frame;
3478 g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3479 g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3480 g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3482 klass = GST_BASE_PARSE_GET_CLASS (parse);
3484 *time = GST_CLOCK_TIME_NONE;
3485 *duration = GST_CLOCK_TIME_NONE;
3488 orig_offset = parse->priv->offset;
3489 orig_discont = parse->priv->discont;
3490 orig_drain = parse->priv->drain;
3492 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3493 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3495 gst_base_parse_frame_init (&frame);
3497 /* jump elsewhere and locate next frame */
3498 parse->priv->offset = *pos;
3499 ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3500 if (ret != GST_FLOW_OK)
3504 GST_LOG_OBJECT (parse,
3505 "peek parsing frame at offset %" G_GUINT64_FORMAT
3506 " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
3507 GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf),
3508 gst_buffer_get_size (buf));
3510 /* get offset first, subclass parsing might dump other stuff in there */
3511 *pos = GST_BUFFER_OFFSET (buf);
3512 ret = klass->parse_frame (parse, &frame);
3515 /* but it should provide proper time */
3516 *time = GST_BUFFER_TIMESTAMP (buf);
3517 *duration = GST_BUFFER_DURATION (buf);
3519 gst_base_parse_frame_free (&frame);
3521 GST_LOG_OBJECT (parse,
3522 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3523 GST_TIME_ARGS (*time), *pos);
3527 parse->priv->offset = orig_offset;
3528 parse->priv->discont = orig_discont;
3529 parse->priv->drain = orig_drain;
3534 /* bisect and scan through file for frame starting before @time,
3535 * returns OK and @time/@offset if found, NONE and/or error otherwise
3536 * If @time == G_MAXINT64, scan for duration ( == last frame) */
3537 static GstFlowReturn
3538 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3541 GstFlowReturn ret = GST_FLOW_OK;
3542 gint64 lpos, hpos, newpos;
3543 GstClockTime time, ltime, htime, newtime, dur;
3544 gboolean cont = TRUE;
3545 const GstClockTime tolerance = TARGET_DIFFERENCE;
3546 const guint chunk = 4 * 1024;
3548 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3549 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3551 /* TODO also make keyframe aware if useful some day */
3566 /* do not know at first */
3568 *_time = GST_CLOCK_TIME_NONE;
3570 /* need initial positions; start and end */
3571 lpos = parse->priv->first_frame_offset;
3572 ltime = parse->priv->first_frame_ts;
3573 htime = parse->priv->duration;
3574 hpos = parse->priv->upstream_size;
3576 /* check preconditions are satisfied;
3577 * start and end are needed, except for special case where we scan for
3578 * last frame to determine duration */
3579 if (parse->priv->pad_mode != GST_PAD_ACTIVATE_PULL || !hpos ||
3580 !GST_CLOCK_TIME_IS_VALID (ltime) ||
3581 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3585 /* shortcut cases */
3588 } else if (time < ltime + tolerance) {
3592 } else if (time >= htime) {
3598 while (htime > ltime && cont) {
3599 GST_LOG_OBJECT (parse,
3600 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3601 GST_TIME_ARGS (ltime));
3602 GST_LOG_OBJECT (parse,
3603 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3604 GST_TIME_ARGS (htime));
3605 if (G_UNLIKELY (time == G_MAXINT64)) {
3607 } else if (G_LIKELY (hpos > lpos)) {
3609 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3612 /* should mean lpos == hpos, since lpos <= hpos is invariant */
3614 /* we check this case once, but not forever, so break loop */
3619 newpos = CLAMP (newpos, lpos, hpos);
3620 GST_LOG_OBJECT (parse,
3621 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3622 GST_TIME_ARGS (time), newpos);
3624 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3625 if (ret == GST_FLOW_EOS) {
3626 /* heuristic HACK */
3627 hpos = MAX (lpos, hpos - chunk);
3629 } else if (ret != GST_FLOW_OK) {
3633 if (newtime == -1 || newpos == -1) {
3634 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3638 if (G_UNLIKELY (time == G_MAXINT64)) {
3641 if (GST_CLOCK_TIME_IS_VALID (dur))
3644 } else if (newtime > time) {
3646 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3648 } else if (newtime + tolerance > time) {
3649 /* close enough undershoot */
3653 } else if (newtime < ltime) {
3654 /* so a position beyond lpos resulted in earlier time than ltime ... */
3655 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3658 /* undershoot too far */
3659 newpos += newpos == lpos ? chunk : 0;
3660 lpos = CLAMP (newpos, lpos, hpos);
3666 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3667 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3672 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3673 gboolean before, GstClockTime * _ts)
3675 gint64 bytes = 0, ts = 0;
3676 GstIndexEntry *entry = NULL;
3678 if (time == GST_CLOCK_TIME_NONE) {
3684 g_static_mutex_lock (&parse->priv->index_lock);
3685 if (parse->priv->index) {
3686 /* Let's check if we have an index entry for that time */
3687 entry = gst_index_get_assoc_entry (parse->priv->index,
3688 parse->priv->index_id,
3689 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3690 GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3694 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3695 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3697 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3698 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3699 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3701 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3702 GST_TIME_ARGS (time));
3705 ts = GST_CLOCK_TIME_NONE;
3708 g_static_mutex_unlock (&parse->priv->index_lock);
3717 /* returns TRUE if seek succeeded */
3719 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3724 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3725 gboolean flush, update, res = TRUE, accurate;
3726 gint64 cur, stop, seekpos, seekstop;
3727 GstSegment seeksegment = { 0, };
3728 GstClockTime start_ts;
3730 gst_event_parse_seek (event, &rate, &format, &flags,
3731 &cur_type, &cur, &stop_type, &stop);
3733 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3734 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3735 GST_TIME_FORMAT, gst_format_get_name (format), rate,
3736 cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3738 /* no negative rates in push mode */
3739 if (rate < 0.0 && parse->priv->pad_mode == GST_PAD_ACTIVATE_PUSH)
3742 if (cur_type != GST_SEEK_TYPE_SET ||
3743 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3746 /* For any format other than TIME, see if upstream handles
3747 * it directly or fail. For TIME, try upstream, but do it ourselves if
3748 * it fails upstream */
3749 if (format != GST_FORMAT_TIME) {
3750 /* default action delegates to upstream */
3754 gst_event_ref (event);
3755 if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3760 /* get flush flag */
3761 flush = flags & GST_SEEK_FLAG_FLUSH;
3763 /* copy segment, we need this because we still need the old
3764 * segment when we close the current segment. */
3765 gst_segment_copy_into (&parse->segment, &seeksegment);
3767 GST_DEBUG_OBJECT (parse, "configuring seek");
3768 gst_segment_do_seek (&seeksegment, rate, format, flags,
3769 cur_type, cur, stop_type, stop, &update);
3771 /* accurate seeking implies seek tables are used to obtain position,
3772 * and the requested segment is maintained exactly, not adjusted any way */
3773 accurate = flags & GST_SEEK_FLAG_ACCURATE;
3775 /* maybe we can be accurate for (almost) free */
3776 gst_base_parse_find_offset (parse, seeksegment.position, TRUE, &start_ts);
3777 if (seeksegment.position <= start_ts + TARGET_DIFFERENCE) {
3778 GST_DEBUG_OBJECT (parse, "accurate seek possible");
3782 GstClockTime startpos = seeksegment.position;
3784 /* accurate requested, so ... seek a bit before target */
3785 if (startpos < parse->priv->lead_in_ts)
3788 startpos -= parse->priv->lead_in_ts;
3789 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3790 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3793 start_ts = seeksegment.position;
3794 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.position,
3795 GST_FORMAT_BYTES, &seekpos))
3796 goto convert_failed;
3797 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3798 GST_FORMAT_BYTES, &seekstop))
3799 goto convert_failed;
3802 GST_DEBUG_OBJECT (parse,
3803 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3805 GST_DEBUG_OBJECT (parse,
3806 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3807 seeksegment.stop, seekstop);
3809 if (parse->priv->pad_mode == GST_PAD_ACTIVATE_PULL) {
3812 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3815 if (parse->srcpad) {
3816 GST_DEBUG_OBJECT (parse, "sending flush start");
3817 gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3818 /* unlock upstream pull_range */
3819 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3822 gst_pad_pause_task (parse->sinkpad);
3825 /* we should now be able to grab the streaming thread because we stopped it
3826 * with the above flush/pause code */
3827 GST_PAD_STREAM_LOCK (parse->sinkpad);
3829 /* save current position */
3830 last_stop = parse->segment.position;
3831 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3834 /* now commit to new position */
3836 /* prepare for streaming again */
3838 GST_DEBUG_OBJECT (parse, "sending flush stop");
3839 gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop (TRUE));
3840 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop (TRUE));
3841 gst_base_parse_clear_queues (parse);
3843 /* keep track of our position */
3844 seeksegment.base = gst_segment_to_running_time (&seeksegment,
3845 seeksegment.format, parse->segment.position);
3848 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3850 /* store the newsegment event so it can be sent from the streaming thread. */
3851 if (parse->priv->pending_segment)
3852 gst_event_unref (parse->priv->pending_segment);
3854 /* This will be sent later in _loop() */
3855 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
3857 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3858 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3859 ", pos = %" GST_TIME_FORMAT, format,
3860 GST_TIME_ARGS (parse->segment.start),
3861 GST_TIME_ARGS (parse->segment.stop),
3862 GST_TIME_ARGS (parse->segment.start));
3864 /* one last chance in pull mode to stay accurate;
3865 * maybe scan and subclass can find where to go */
3868 GstClockTime ts = seeksegment.position;
3870 gst_base_parse_locate_time (parse, &ts, &scanpos);
3874 /* running collected index now consists of several intervals,
3875 * so optimized check no longer possible */
3876 parse->priv->index_last_valid = FALSE;
3877 parse->priv->index_last_offset = 0;
3878 parse->priv->index_last_ts = 0;
3882 /* mark discont if we are going to stream from another position. */
3883 if (seekpos != parse->priv->offset) {
3884 GST_DEBUG_OBJECT (parse,
3885 "mark DISCONT, we did a seek to another position");
3886 parse->priv->offset = seekpos;
3887 parse->priv->last_offset = seekpos;
3888 parse->priv->seen_keyframe = FALSE;
3889 parse->priv->discont = TRUE;
3890 parse->priv->next_ts = start_ts;
3891 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3892 parse->priv->sync_offset = seekpos;
3893 parse->priv->exact_position = accurate;
3896 /* Start streaming thread if paused */
3897 gst_pad_start_task (parse->sinkpad,
3898 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3900 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3905 GstEvent *new_event;
3906 GstBaseParseSeek *seek;
3907 GstSeekFlags flags = (flush ? GST_SEEK_FLAG_FLUSH : GST_SEEK_FLAG_NONE);
3909 /* The only thing we need to do in PUSH-mode is to send the
3910 seek event (in bytes) to upstream. Segment / flush handling happens
3911 in corresponding src event handlers */
3912 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3913 if (seekstop >= 0 && seekstop <= seekpos)
3915 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
3916 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3918 /* store segment info so its precise details can be reconstructed when
3919 * receiving newsegment;
3920 * this matters for all details when accurate seeking,
3921 * is most useful to preserve NONE stop time otherwise */
3922 seek = g_new0 (GstBaseParseSeek, 1);
3923 seek->segment = seeksegment;
3924 seek->accurate = accurate;
3925 seek->offset = seekpos;
3926 seek->start_ts = start_ts;
3927 GST_OBJECT_LOCK (parse);
3928 /* less optimal, but preserves order */
3929 parse->priv->pending_seeks =
3930 g_slist_append (parse->priv->pending_seeks, seek);
3931 GST_OBJECT_UNLOCK (parse);
3933 res = gst_pad_push_event (parse->sinkpad, new_event);
3936 GST_OBJECT_LOCK (parse);
3937 parse->priv->pending_seeks =
3938 g_slist_remove (parse->priv->pending_seeks, seek);
3939 GST_OBJECT_UNLOCK (parse);
3945 /* handled event is ours to free */
3947 gst_event_unref (event);
3953 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
3959 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3965 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3971 /* Checks if bitrates are available from upstream tags so that we don't
3972 * override them later
3975 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
3977 GstTagList *taglist = NULL;
3980 gst_event_parse_tag (event, &taglist);
3982 if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
3983 GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
3984 parse->priv->post_min_bitrate = FALSE;
3986 if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
3987 GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
3988 parse->priv->post_avg_bitrate = FALSE;
3990 if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
3991 GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
3992 parse->priv->post_max_bitrate = FALSE;
3997 gst_base_parse_set_index (GstElement * element, GstIndex * index)
3999 GstBaseParse *parse = GST_BASE_PARSE (element);
4001 g_static_mutex_lock (&parse->priv->index_lock);
4002 if (parse->priv->index)
4003 gst_object_unref (parse->priv->index);
4005 parse->priv->index = gst_object_ref (index);
4006 gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
4007 &parse->priv->index_id);
4008 parse->priv->own_index = FALSE;
4010 parse->priv->index = NULL;
4012 g_static_mutex_unlock (&parse->priv->index_lock);
4016 gst_base_parse_get_index (GstElement * element)
4018 GstBaseParse *parse = GST_BASE_PARSE (element);
4019 GstIndex *result = NULL;
4021 g_static_mutex_lock (&parse->priv->index_lock);
4022 if (parse->priv->index)
4023 result = gst_object_ref (parse->priv->index);
4024 g_static_mutex_unlock (&parse->priv->index_lock);
4029 static GstStateChangeReturn
4030 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
4032 GstBaseParse *parse;
4033 GstStateChangeReturn result;
4035 parse = GST_BASE_PARSE (element);
4037 switch (transition) {
4038 case GST_STATE_CHANGE_READY_TO_PAUSED:
4039 /* If this is our own index destroy it as the
4040 * old entries might be wrong for the new stream */
4041 g_static_mutex_lock (&parse->priv->index_lock);
4042 if (parse->priv->own_index) {
4043 gst_object_unref (parse->priv->index);
4044 parse->priv->index = NULL;
4045 parse->priv->own_index = FALSE;
4048 /* If no index was created, generate one */
4049 if (G_UNLIKELY (!parse->priv->index)) {
4050 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
4052 parse->priv->index = gst_index_factory_make ("memindex");
4053 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
4054 &parse->priv->index_id);
4055 parse->priv->own_index = TRUE;
4057 g_static_mutex_unlock (&parse->priv->index_lock);
4063 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4065 switch (transition) {
4066 case GST_STATE_CHANGE_PAUSED_TO_READY:
4067 gst_base_parse_reset (parse);