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, GstEvent * event);
387 static gboolean gst_base_parse_sink_event (GstPad * pad, GstEvent * event);
388 static gboolean gst_base_parse_query (GstPad * pad, GstQuery * query);
389 static GstCaps *gst_base_parse_sink_getcaps (GstPad * pad, GstCaps * filter);
391 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstBuffer * buffer);
392 static void gst_base_parse_loop (GstPad * pad);
394 static gboolean gst_base_parse_check_frame (GstBaseParse * parse,
395 GstBaseParseFrame * frame, guint * framesize, gint * skipsize);
396 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
397 GstBaseParseFrame * frame);
399 static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
402 static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
405 static void gst_base_parse_drain (GstBaseParse * parse);
407 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
408 gboolean post_min, gboolean post_avg, gboolean post_max);
410 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
411 GstClockTime time, gboolean before, GstClockTime * _ts);
412 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
413 GstClockTime * _time, gint64 * _offset);
415 static GstFlowReturn gst_base_parse_process_fragment (GstBaseParse * parse,
418 static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);
421 gst_base_parse_clear_queues (GstBaseParse * parse)
423 g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
424 g_slist_free (parse->priv->buffers_queued);
425 parse->priv->buffers_queued = NULL;
426 g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
428 g_slist_free (parse->priv->buffers_pending);
429 parse->priv->buffers_pending = NULL;
430 g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
431 g_slist_free (parse->priv->buffers_send);
432 parse->priv->buffers_send = NULL;
434 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
435 g_list_free (parse->priv->detect_buffers);
436 parse->priv->detect_buffers = NULL;
437 parse->priv->detect_buffers_size = 0;
441 gst_base_parse_finalize (GObject * object)
443 GstBaseParse *parse = GST_BASE_PARSE (object);
446 g_object_unref (parse->priv->adapter);
448 if (parse->priv->pending_segment) {
449 p_ev = &parse->priv->pending_segment;
450 gst_event_replace (p_ev, NULL);
452 if (parse->priv->close_segment) {
453 p_ev = &parse->priv->close_segment;
454 gst_event_replace (p_ev, NULL);
457 if (parse->priv->cache) {
458 gst_buffer_unref (parse->priv->cache);
459 parse->priv->cache = NULL;
462 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
464 g_list_free (parse->priv->pending_events);
465 parse->priv->pending_events = NULL;
467 g_queue_foreach (&parse->priv->queued_frames,
468 (GFunc) gst_base_parse_frame_free, NULL);
469 g_queue_clear (&parse->priv->queued_frames);
471 if (parse->priv->index) {
472 gst_object_unref (parse->priv->index);
473 parse->priv->index = NULL;
476 g_static_mutex_free (&parse->priv->index_lock);
478 gst_base_parse_clear_queues (parse);
480 G_OBJECT_CLASS (parent_class)->finalize (object);
484 gst_base_parse_class_init (GstBaseParseClass * klass)
486 GObjectClass *gobject_class;
487 GstElementClass *gstelement_class;
489 gobject_class = G_OBJECT_CLASS (klass);
490 g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
491 parent_class = g_type_class_peek_parent (klass);
492 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
494 gstelement_class = (GstElementClass *) klass;
495 gstelement_class->change_state =
496 GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
497 gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
498 gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
500 /* Default handlers */
501 klass->check_valid_frame = gst_base_parse_check_frame;
502 klass->parse_frame = gst_base_parse_parse_frame;
503 klass->src_event = gst_base_parse_src_eventfunc;
504 klass->convert = gst_base_parse_convert_default;
506 GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
507 "baseparse element");
511 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
513 GstPadTemplate *pad_template;
515 GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
517 parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
520 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
521 g_return_if_fail (pad_template != NULL);
522 parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
523 gst_pad_set_event_function (parse->sinkpad,
524 GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
525 gst_pad_set_getcaps_function (parse->sinkpad,
526 GST_DEBUG_FUNCPTR (gst_base_parse_sink_getcaps));
527 gst_pad_set_chain_function (parse->sinkpad,
528 GST_DEBUG_FUNCPTR (gst_base_parse_chain));
529 gst_pad_set_activate_function (parse->sinkpad,
530 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
531 gst_pad_set_activatepush_function (parse->sinkpad,
532 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_push));
533 gst_pad_set_activatepull_function (parse->sinkpad,
534 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_pull));
535 gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
537 GST_DEBUG_OBJECT (parse, "sinkpad created");
540 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
541 g_return_if_fail (pad_template != NULL);
542 parse->srcpad = gst_pad_new_from_template (pad_template, "src");
543 gst_pad_set_event_function (parse->srcpad,
544 GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
545 gst_pad_set_query_function (parse->srcpad,
546 GST_DEBUG_FUNCPTR (gst_base_parse_query));
547 gst_pad_use_fixed_caps (parse->srcpad);
548 gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
549 GST_DEBUG_OBJECT (parse, "src created");
551 g_queue_init (&parse->priv->queued_frames);
553 parse->priv->adapter = gst_adapter_new ();
555 parse->priv->pad_mode = GST_PAD_ACTIVATE_NONE;
557 g_static_mutex_init (&parse->priv->index_lock);
560 gst_base_parse_reset (parse);
561 GST_DEBUG_OBJECT (parse, "init ok");
564 static GstBaseParseFrame *
565 gst_base_parse_frame_copy (GstBaseParseFrame * frame)
567 GstBaseParseFrame *copy;
569 copy = g_slice_dup (GstBaseParseFrame, frame);
570 copy->buffer = gst_buffer_ref (frame->buffer);
571 copy->_private_flags &= ~GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
573 GST_TRACE ("copied frame %p -> %p", frame, copy);
579 gst_base_parse_frame_free (GstBaseParseFrame * frame)
581 GST_TRACE ("freeing frame %p", frame);
584 gst_buffer_unref (frame->buffer);
585 frame->buffer = NULL;
588 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
589 g_slice_free (GstBaseParseFrame, frame);
591 memset (frame, 0, sizeof (*frame));
596 gst_base_parse_frame_get_type (void)
598 static volatile gsize frame_type = 0;
600 if (g_once_init_enter (&frame_type)) {
603 _type = g_boxed_type_register_static ("GstBaseParseFrame",
604 (GBoxedCopyFunc) gst_base_parse_frame_copy,
605 (GBoxedFreeFunc) gst_base_parse_frame_free);
606 g_once_init_leave (&frame_type, _type);
608 return (GType) frame_type;
612 * gst_base_parse_frame_init:
613 * @frame: #GstBaseParseFrame.
615 * Sets a #GstBaseParseFrame to initial state. Currently this means
616 * all public fields are zero-ed and a private flag is set to make
617 * sure gst_base_parse_frame_free() only frees the contents but not
618 * the actual frame. Use this function to initialise a #GstBaseParseFrame
619 * allocated on the stack.
624 gst_base_parse_frame_init (GstBaseParseFrame * frame)
626 memset (frame, 0, sizeof (GstBaseParseFrame));
627 frame->_private_flags = GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
628 GST_TRACE ("inited frame %p", frame);
632 * gst_base_parse_frame_new:
633 * @buffer: (transfer none): a #GstBuffer
635 * @overhead: number of bytes in this frame which should be counted as
636 * metadata overhead, ie. not used to calculate the average bitrate.
637 * Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
639 * Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
640 * elements written in C should usually allocate the frame on the stack and
641 * then use gst_base_parse_frame_init() to initialise it.
643 * Returns: a newly-allocated #GstBaseParseFrame. Free with
644 * gst_base_parse_frame_free() when no longer needed, unless you gave
645 * away ownership to gst_base_parse_push_frame().
650 gst_base_parse_frame_new (GstBuffer * buffer, GstBaseParseFrameFlags flags,
653 GstBaseParseFrame *frame;
655 frame = g_slice_new0 (GstBaseParseFrame);
656 frame->buffer = gst_buffer_ref (buffer);
658 GST_TRACE ("created frame %p", frame);
663 gst_base_parse_frame_update (GstBaseParse * parse, GstBaseParseFrame * frame,
666 gst_buffer_replace (&frame->buffer, buf);
670 /* set flags one by one for clarity */
671 if (G_UNLIKELY (parse->priv->drain))
672 parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;
674 /* losing sync is pretty much a discont (and vice versa), no ? */
675 if (G_UNLIKELY (parse->priv->discont))
676 parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
680 gst_base_parse_reset (GstBaseParse * parse)
682 GST_OBJECT_LOCK (parse);
683 gst_segment_init (&parse->segment, GST_FORMAT_TIME);
684 parse->priv->duration = -1;
685 parse->priv->min_frame_size = 1;
686 parse->priv->discont = TRUE;
687 parse->priv->flushing = FALSE;
688 parse->priv->offset = 0;
689 parse->priv->sync_offset = 0;
690 parse->priv->update_interval = -1;
691 parse->priv->fps_num = parse->priv->fps_den = 0;
692 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
693 parse->priv->lead_in = parse->priv->lead_out = 0;
694 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
695 parse->priv->bitrate = 0;
696 parse->priv->framecount = 0;
697 parse->priv->bytecount = 0;
698 parse->priv->acc_duration = 0;
699 parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
700 parse->priv->first_frame_offset = -1;
701 parse->priv->estimated_duration = -1;
702 parse->priv->estimated_drift = 0;
703 parse->priv->next_ts = 0;
704 parse->priv->syncable = TRUE;
705 parse->priv->passthrough = FALSE;
706 parse->priv->has_timing_info = FALSE;
707 parse->priv->post_min_bitrate = TRUE;
708 parse->priv->post_avg_bitrate = TRUE;
709 parse->priv->post_max_bitrate = TRUE;
710 parse->priv->min_bitrate = G_MAXUINT;
711 parse->priv->max_bitrate = 0;
712 parse->priv->avg_bitrate = 0;
713 parse->priv->posted_avg_bitrate = 0;
715 parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
716 parse->priv->index_last_offset = -1;
717 parse->priv->index_last_valid = TRUE;
718 parse->priv->upstream_seekable = FALSE;
719 parse->priv->upstream_size = 0;
720 parse->priv->upstream_has_duration = FALSE;
721 parse->priv->idx_interval = 0;
722 parse->priv->exact_position = TRUE;
723 parse->priv->seen_keyframe = FALSE;
725 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
726 parse->priv->last_offset = 0;
728 if (parse->priv->pending_segment) {
729 gst_event_unref (parse->priv->pending_segment);
730 parse->priv->pending_segment = NULL;
733 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
735 g_list_free (parse->priv->pending_events);
736 parse->priv->pending_events = NULL;
738 if (parse->priv->cache) {
739 gst_buffer_unref (parse->priv->cache);
740 parse->priv->cache = NULL;
743 g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
744 g_slist_free (parse->priv->pending_seeks);
745 parse->priv->pending_seeks = NULL;
747 /* we know it is not alloc'ed, but maybe other stuff to free, some day ... */
748 parse->priv->frame._private_flags |=
749 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
750 gst_base_parse_frame_free (&parse->priv->frame);
752 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
753 g_list_free (parse->priv->detect_buffers);
754 parse->priv->detect_buffers = NULL;
755 parse->priv->detect_buffers_size = 0;
756 GST_OBJECT_UNLOCK (parse);
759 /* gst_base_parse_check_frame:
760 * @parse: #GstBaseParse.
761 * @buffer: GstBuffer.
762 * @framesize: This will be set to tell the found frame size in bytes.
763 * @skipsize: Output parameter that tells how much data needs to be skipped
764 * in order to find the following frame header.
766 * Default callback for check_valid_frame.
768 * Returns: Always TRUE.
771 gst_base_parse_check_frame (GstBaseParse * parse,
772 GstBaseParseFrame * frame, guint * framesize, gint * skipsize)
774 *framesize = gst_buffer_get_size (frame->buffer);
780 /* gst_base_parse_parse_frame:
781 * @parse: #GstBaseParse.
782 * @buffer: #GstBuffer.
784 * Default callback for parse_frame.
787 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
789 GstBuffer *buffer = frame->buffer;
791 if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
792 GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
793 GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
795 if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
796 GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
797 GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
802 /* gst_base_parse_convert:
803 * @parse: #GstBaseParse.
804 * @src_format: #GstFormat describing the source format.
805 * @src_value: Source value to be converted.
806 * @dest_format: #GstFormat defining the converted format.
807 * @dest_value: Pointer where the conversion result will be put.
809 * Converts using configured "convert" vmethod in #GstBaseParse class.
811 * Returns: TRUE if conversion was successful.
814 gst_base_parse_convert (GstBaseParse * parse,
815 GstFormat src_format,
816 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
818 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
821 g_return_val_if_fail (dest_value != NULL, FALSE);
826 ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
828 #ifndef GST_DISABLE_GST_DEBUG
831 if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
832 GST_LOG_OBJECT (parse,
833 "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
834 GST_TIME_ARGS (src_value), *dest_value);
835 } else if (dest_format == GST_FORMAT_TIME &&
836 src_format == GST_FORMAT_BYTES) {
837 GST_LOG_OBJECT (parse,
838 "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
839 src_value, GST_TIME_ARGS (*dest_value));
841 GST_LOG_OBJECT (parse,
842 "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
843 GST_STR_NULL (gst_format_get_name (src_format)),
844 GST_STR_NULL (gst_format_get_name (dest_format)),
845 src_value, *dest_value);
848 GST_DEBUG_OBJECT (parse, "conversion failed");
856 /* gst_base_parse_sink_event:
857 * @pad: #GstPad that received the event.
858 * @event: #GstEvent to be handled.
860 * Handler for sink pad events.
862 * Returns: TRUE if the event was handled.
865 gst_base_parse_sink_event (GstPad * pad, GstEvent * event)
868 GstBaseParseClass *bclass;
869 gboolean handled = FALSE;
872 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
873 bclass = GST_BASE_PARSE_GET_CLASS (parse);
875 GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
876 GST_EVENT_TYPE_NAME (event));
878 /* Cache all events except EOS, SEGMENT and FLUSH_STOP if we have a
880 if (parse->priv->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
881 && GST_EVENT_TYPE (event) != GST_EVENT_SEGMENT
882 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
883 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP) {
885 if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
886 /* See if any bitrate tags were posted */
887 gst_base_parse_handle_tag (parse, event);
889 parse->priv->pending_events =
890 g_list_append (parse->priv->pending_events, event);
894 if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
895 parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
896 /* We've not posted bitrate tags yet - do so now */
897 gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
900 handled = bclass->event (parse, event);
903 handled = gst_base_parse_sink_eventfunc (parse, event);
906 ret = gst_pad_event_default (pad, event);
909 gst_object_unref (parse);
910 GST_DEBUG_OBJECT (parse, "event handled");
915 /* gst_base_parse_sink_eventfunc:
916 * @parse: #GstBaseParse.
917 * @event: #GstEvent to be handled.
919 * Element-level event handler function.
921 * The event will be unreffed only if it has been handled and this
922 * function returns %TRUE
924 * Returns: %TRUE if the event was handled and not need forwarding.
927 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
929 gboolean handled = FALSE;
932 switch (GST_EVENT_TYPE (event)) {
936 GstBaseParseClass *klass;
938 klass = GST_BASE_PARSE_GET_CLASS (parse);
940 gst_event_parse_caps (event, &caps);
941 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
943 if (klass->set_sink_caps)
944 klass->set_sink_caps (parse, caps);
946 /* will send our own caps downstream */
947 gst_event_unref (event);
951 case GST_EVENT_SEGMENT:
953 const GstSegment *in_segment;
954 GstSegment out_segment;
955 gint64 offset = 0, next_ts;
958 gdouble rate, applied_rate;
960 gint64 start, stop, pos, next_ts;
964 gst_event_parse_segment (event, &in_segment);
965 gst_segment_init (&out_segment, GST_FORMAT_TIME);
967 GST_DEBUG_OBJECT (parse, "segment %" GST_SEGMENT_FORMAT, in_segment);
969 if (in_segment->format == GST_FORMAT_BYTES) {
970 GstBaseParseSeek *seek = NULL;
973 /* stop time is allowed to be open-ended, but not start & pos */
974 offset = in_segment->time;
976 GST_OBJECT_LOCK (parse);
977 for (node = parse->priv->pending_seeks; node; node = node->next) {
978 GstBaseParseSeek *tmp = node->data;
980 if (tmp->offset == offset) {
985 parse->priv->pending_seeks =
986 g_slist_remove (parse->priv->pending_seeks, seek);
987 GST_OBJECT_UNLOCK (parse);
990 GST_DEBUG_OBJECT (parse,
991 "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
992 seek->accurate ? " accurate" : "", &seek->segment);
994 out_segment.start = seek->segment.start;
995 out_segment.stop = seek->segment.stop;
996 out_segment.time = seek->segment.start;
998 next_ts = seek->start_ts;
999 parse->priv->exact_position = seek->accurate;
1002 /* best attempt convert */
1003 /* as these are only estimates, stop is kept open-ended to avoid
1004 * premature cutting */
1005 gst_base_parse_convert (parse, GST_FORMAT_BYTES, in_segment->start,
1006 GST_FORMAT_TIME, (gint64 *) & next_ts);
1008 out_segment.start = next_ts;
1009 out_segment.stop = GST_CLOCK_TIME_NONE;
1010 out_segment.time = next_ts;
1012 parse->priv->exact_position = (in_segment->start == 0);
1015 gst_event_unref (event);
1017 event = gst_event_new_segment (&out_segment);
1019 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. %"
1020 GST_SEGMENT_FORMAT, in_segment);
1022 } else if (in_segment->format != GST_FORMAT_TIME) {
1023 /* Unknown incoming segment format. Output a default open-ended
1025 gst_event_unref (event);
1027 out_segment.start = 0;
1028 out_segment.stop = GST_CLOCK_TIME_NONE;;
1029 out_segment.time = 0;;
1031 event = gst_event_new_segment (&out_segment);
1035 /* not considered BYTE seekable if it is talking to us in TIME,
1036 * whatever else it might claim */
1037 parse->priv->upstream_seekable = FALSE;
1038 next_ts = in_segment->start;
1041 memcpy (&parse->segment, &out_segment, sizeof (GstSegment));
1044 gst_segment_set_newsegment (&parse->segment, update, rate,
1045 applied_rate, format, start, stop, start);
1048 /* save the segment for later, right before we push a new buffer so that
1049 * the caps are fixed and the next linked element can receive
1051 eventp = &parse->priv->pending_segment;
1052 gst_event_replace (eventp, event);
1053 gst_event_unref (event);
1056 /* but finish the current segment */
1057 GST_DEBUG_OBJECT (parse, "draining current segment");
1058 if (in_segment->rate > 0.0)
1059 gst_base_parse_drain (parse);
1061 gst_base_parse_process_fragment (parse, FALSE);
1062 gst_adapter_clear (parse->priv->adapter);
1064 parse->priv->offset = offset;
1065 parse->priv->sync_offset = offset;
1066 parse->priv->next_ts = next_ts;
1067 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1068 parse->priv->discont = TRUE;
1069 parse->priv->seen_keyframe = FALSE;
1073 case GST_EVENT_FLUSH_START:
1074 parse->priv->flushing = TRUE;
1075 handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
1077 gst_event_unref (event);
1078 /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
1079 GST_PAD_STREAM_LOCK (parse->srcpad);
1080 GST_PAD_STREAM_UNLOCK (parse->srcpad);
1084 case GST_EVENT_FLUSH_STOP:
1085 gst_adapter_clear (parse->priv->adapter);
1086 gst_base_parse_clear_queues (parse);
1087 parse->priv->flushing = FALSE;
1088 parse->priv->discont = TRUE;
1089 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1090 parse->priv->frame._private_flags |=
1091 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
1092 gst_base_parse_frame_free (&parse->priv->frame);
1096 if (parse->segment.rate > 0.0)
1097 gst_base_parse_drain (parse);
1099 gst_base_parse_process_fragment (parse, FALSE);
1101 /* If we STILL have zero frames processed, fire an error */
1102 if (parse->priv->framecount == 0) {
1103 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1104 ("No valid frames found before end of stream"), (NULL));
1106 /* newsegment before eos */
1107 if (parse->priv->pending_segment) {
1108 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1109 parse->priv->pending_segment = NULL;
1121 /* gst_base_parse_src_event:
1122 * @pad: #GstPad that received the event.
1123 * @event: #GstEvent that was received.
1125 * Handler for source pad events.
1127 * Returns: TRUE if the event was handled.
1130 gst_base_parse_src_event (GstPad * pad, GstEvent * event)
1132 GstBaseParse *parse;
1133 GstBaseParseClass *bclass;
1134 gboolean handled = FALSE;
1135 gboolean ret = TRUE;
1137 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
1138 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1140 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1141 GST_EVENT_TYPE_NAME (event));
1143 if (bclass->src_event)
1144 handled = bclass->src_event (parse, event);
1147 ret = gst_pad_event_default (pad, event);
1149 gst_object_unref (parse);
1154 gst_base_parse_is_seekable (GstBaseParse * parse)
1156 /* FIXME: could do more here, e.g. check index or just send data from 0
1157 * in pull mode and let decoder/sink clip */
1158 return parse->priv->syncable;
1161 /* gst_base_parse_src_eventfunc:
1162 * @parse: #GstBaseParse.
1163 * @event: #GstEvent that was received.
1165 * Default srcpad event handler.
1167 * Returns: TRUE if the event was handled and can be dropped.
1170 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1172 gboolean handled = FALSE;
1174 switch (GST_EVENT_TYPE (event)) {
1175 case GST_EVENT_SEEK:
1177 if (gst_base_parse_is_seekable (parse)) {
1178 handled = gst_base_parse_handle_seek (parse, event);
1190 * gst_base_parse_convert_default:
1191 * @parse: #GstBaseParse.
1192 * @src_format: #GstFormat describing the source format.
1193 * @src_value: Source value to be converted.
1194 * @dest_format: #GstFormat defining the converted format.
1195 * @dest_value: Pointer where the conversion result will be put.
1197 * Default implementation of "convert" vmethod in #GstBaseParse class.
1199 * Returns: TRUE if conversion was successful.
1204 gst_base_parse_convert_default (GstBaseParse * parse,
1205 GstFormat src_format,
1206 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1208 gboolean ret = FALSE;
1209 guint64 bytes, duration;
1211 if (G_UNLIKELY (src_format == dest_format)) {
1212 *dest_value = src_value;
1216 if (G_UNLIKELY (src_value == -1)) {
1221 if (G_UNLIKELY (src_value == 0)) {
1226 /* need at least some frames */
1227 if (!parse->priv->framecount)
1230 duration = parse->priv->acc_duration / GST_MSECOND;
1231 bytes = parse->priv->bytecount;
1233 if (G_UNLIKELY (!duration || !bytes))
1236 if (src_format == GST_FORMAT_BYTES) {
1237 if (dest_format == GST_FORMAT_TIME) {
1238 /* BYTES -> TIME conversion */
1239 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1240 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1241 *dest_value *= GST_MSECOND;
1242 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1243 *dest_value / GST_MSECOND);
1246 } else if (src_format == GST_FORMAT_TIME) {
1247 if (dest_format == GST_FORMAT_BYTES) {
1248 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1249 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1251 GST_DEBUG_OBJECT (parse,
1252 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1253 src_value / GST_MSECOND, *dest_value);
1256 } else if (src_format == GST_FORMAT_DEFAULT) {
1257 /* DEFAULT == frame-based */
1258 if (dest_format == GST_FORMAT_TIME) {
1259 if (parse->priv->fps_den) {
1260 *dest_value = gst_util_uint64_scale (src_value,
1261 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1264 } else if (dest_format == GST_FORMAT_BYTES) {
1272 gst_base_parse_update_duration (GstBaseParse * baseparse)
1275 GstBaseParse *parse;
1277 parse = GST_BASE_PARSE (baseparse);
1279 peer = gst_pad_get_peer (parse->sinkpad);
1281 gboolean qres = FALSE;
1282 gint64 ptot, dest_value;
1284 qres = gst_pad_query_duration (peer, GST_FORMAT_BYTES, &ptot);
1285 gst_object_unref (GST_OBJECT (peer));
1287 if (gst_base_parse_convert (parse, GST_FORMAT_BYTES, ptot,
1288 GST_FORMAT_TIME, &dest_value)) {
1290 /* inform if duration changed, but try to avoid spamming */
1291 parse->priv->estimated_drift +=
1292 dest_value - parse->priv->estimated_duration;
1293 if (parse->priv->estimated_drift > GST_SECOND ||
1294 parse->priv->estimated_drift < -GST_SECOND) {
1295 gst_element_post_message (GST_ELEMENT (parse),
1296 gst_message_new_duration (GST_OBJECT (parse),
1297 GST_FORMAT_TIME, dest_value));
1298 parse->priv->estimated_drift = 0;
1300 parse->priv->estimated_duration = dest_value;
1301 GST_LOG_OBJECT (parse,
1302 "updated estimated duration to %" GST_TIME_FORMAT,
1303 GST_TIME_ARGS (dest_value));
1310 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1311 gboolean post_avg, gboolean post_max)
1313 GstTagList *taglist = NULL;
1315 if (post_min && parse->priv->post_min_bitrate) {
1316 taglist = gst_tag_list_new_empty ();
1318 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1319 GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1322 if (post_avg && parse->priv->post_avg_bitrate) {
1323 if (taglist == NULL)
1324 taglist = gst_tag_list_new_empty ();
1326 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1327 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1328 parse->priv->avg_bitrate, NULL);
1331 if (post_max && parse->priv->post_max_bitrate) {
1332 if (taglist == NULL)
1333 taglist = gst_tag_list_new_empty ();
1335 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1336 GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1339 GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1340 parse->priv->min_bitrate, parse->priv->avg_bitrate,
1341 parse->priv->max_bitrate);
1343 if (taglist != NULL) {
1344 gst_pad_push_event (parse->srcpad, gst_event_new_tag (taglist));
1348 /* gst_base_parse_update_bitrates:
1349 * @parse: #GstBaseParse.
1350 * @buffer: Current frame as a #GstBuffer
1352 * Keeps track of the minimum and maximum bitrates, and also maintains a
1353 * running average bitrate of the stream so far.
1356 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1358 /* Only update the tag on a 10 kbps delta */
1359 static const gint update_threshold = 10000;
1361 guint64 data_len, frame_dur;
1362 gint overhead, frame_bitrate, old_avg_bitrate;
1363 gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1364 GstBuffer *buffer = frame->buffer;
1366 overhead = frame->overhead;
1370 data_len = gst_buffer_get_size (buffer) - overhead;
1371 parse->priv->data_bytecount += data_len;
1373 /* duration should be valid by now,
1374 * either set by subclass or maybe based on fps settings */
1375 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1376 /* Calculate duration of a frame from buffer properties */
1377 frame_dur = GST_BUFFER_DURATION (buffer);
1378 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1379 parse->priv->acc_duration;
1382 /* No way to figure out frame duration (is this even possible?) */
1386 /* override if subclass provided bitrate, e.g. metadata based */
1387 if (parse->priv->bitrate) {
1388 parse->priv->avg_bitrate = parse->priv->bitrate;
1389 /* spread this (confirmed) info ASAP */
1390 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1391 gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1395 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1399 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1400 parse->priv->avg_bitrate);
1402 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1404 } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1405 /* always post all at threshold time */
1406 update_min = update_max = update_avg = TRUE;
1409 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1410 if (frame_bitrate < parse->priv->min_bitrate) {
1411 parse->priv->min_bitrate = frame_bitrate;
1415 if (frame_bitrate > parse->priv->max_bitrate) {
1416 parse->priv->max_bitrate = frame_bitrate;
1420 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1421 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1422 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1427 if ((update_min || update_avg || update_max))
1428 gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1430 /* If average bitrate changes that much and no valid (time) duration provided,
1431 * then post a new duration message so applications can update their cached
1433 if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1434 GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1435 gst_element_post_message (GST_ELEMENT (parse),
1436 gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1443 * gst_base_parse_add_index_entry:
1444 * @parse: #GstBaseParse.
1445 * @offset: offset of entry
1446 * @ts: timestamp associated with offset
1447 * @key: whether entry refers to keyframe
1448 * @force: add entry disregarding sanity checks
1450 * Adds an entry to the index associating @offset to @ts. It is recommended
1451 * to only add keyframe entries. @force allows to bypass checks, such as
1452 * whether the stream is (upstream) seekable, another entry is already "close"
1453 * to the new entry, etc.
1455 * Returns: #gboolean indicating whether entry was added
1460 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1461 GstClockTime ts, gboolean key, gboolean force)
1463 gboolean ret = FALSE;
1464 GstIndexAssociation associations[2];
1466 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1467 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1469 if (G_LIKELY (!force)) {
1471 if (!parse->priv->upstream_seekable) {
1472 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1476 /* FIXME need better helper data structure that handles these issues
1477 * related to ongoing collecting of index entries */
1478 if (parse->priv->index_last_offset >= (gint64) offset) {
1479 GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1480 "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1484 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1485 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1486 parse->priv->idx_interval) {
1487 GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1488 GST_TIME_ARGS (parse->priv->index_last_ts));
1492 /* if last is not really the last one */
1493 if (!parse->priv->index_last_valid) {
1494 GstClockTime prev_ts;
1496 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1497 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1498 GST_DEBUG_OBJECT (parse,
1499 "entry too close to existing entry %" GST_TIME_FORMAT,
1500 GST_TIME_ARGS (prev_ts));
1501 parse->priv->index_last_offset = offset;
1502 parse->priv->index_last_ts = ts;
1508 associations[0].format = GST_FORMAT_TIME;
1509 associations[0].value = ts;
1510 associations[1].format = GST_FORMAT_BYTES;
1511 associations[1].value = offset;
1513 /* index might change on-the-fly, although that would be nutty app ... */
1514 g_static_mutex_lock (&parse->priv->index_lock);
1515 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1516 (key) ? GST_ASSOCIATION_FLAG_KEY_UNIT : GST_ASSOCIATION_FLAG_DELTA_UNIT,
1517 2, (const GstIndexAssociation *) &associations);
1518 g_static_mutex_unlock (&parse->priv->index_lock);
1521 parse->priv->index_last_offset = offset;
1522 parse->priv->index_last_ts = ts;
1531 /* check for seekable upstream, above and beyond a mere query */
1533 gst_base_parse_check_seekability (GstBaseParse * parse)
1536 gboolean seekable = FALSE;
1537 gint64 start = -1, stop = -1;
1538 guint idx_interval = 0;
1540 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1541 if (!gst_pad_peer_query (parse->sinkpad, query)) {
1542 GST_DEBUG_OBJECT (parse, "seeking query failed");
1546 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1548 /* try harder to query upstream size if we didn't get it the first time */
1549 if (seekable && stop == -1) {
1550 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1551 gst_pad_query_peer_duration (parse->sinkpad, GST_FORMAT_BYTES, &stop);
1554 /* if upstream doesn't know the size, it's likely that it's not seekable in
1555 * practice even if it technically may be seekable */
1556 if (seekable && (start != 0 || stop <= start)) {
1557 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1561 /* let's not put every single frame into our index */
1563 if (stop < 10 * 1024 * 1024)
1565 else if (stop < 100 * 1024 * 1024)
1568 idx_interval = 1000;
1572 gst_query_unref (query);
1574 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1575 G_GUINT64_FORMAT ")", seekable, start, stop);
1576 parse->priv->upstream_seekable = seekable;
1577 parse->priv->upstream_size = seekable ? stop : 0;
1579 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1580 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1583 /* some misc checks on upstream */
1585 gst_base_parse_check_upstream (GstBaseParse * parse)
1589 if (gst_pad_query_peer_duration (parse->sinkpad, GST_FORMAT_TIME, &stop))
1590 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1591 /* upstream has one, accept it also, and no further updates */
1592 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1593 parse->priv->upstream_has_duration = TRUE;
1596 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1597 parse->priv->upstream_has_duration);
1600 /* checks src caps to determine if dealing with audio or video */
1601 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1603 gst_base_parse_check_media (GstBaseParse * parse)
1608 caps = gst_pad_get_current_caps (parse->srcpad);
1609 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1610 parse->priv->is_video =
1611 g_str_has_prefix (gst_structure_get_name (s), "video");
1613 /* historical default */
1614 parse->priv->is_video = FALSE;
1617 gst_caps_unref (caps);
1619 GST_DEBUG_OBJECT (parse, "media is video: %d", parse->priv->is_video);
1622 /* takes ownership of frame */
1624 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1626 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1627 /* frame allocated on the heap, we can just take ownership */
1628 g_queue_push_tail (&parse->priv->queued_frames, frame);
1629 GST_TRACE ("queued frame %p", frame);
1631 GstBaseParseFrame *copy;
1633 /* probably allocated on the stack, must make a proper copy */
1634 copy = gst_base_parse_frame_copy (frame);
1635 g_queue_push_tail (&parse->priv->queued_frames, copy);
1636 GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1637 gst_base_parse_frame_free (frame);
1641 /* gst_base_parse_handle_and_push_buffer:
1642 * @parse: #GstBaseParse.
1643 * @klass: #GstBaseParseClass.
1644 * @frame: (transfer full): a #GstBaseParseFrame
1646 * Parses the frame from given buffer and pushes it forward. Also performs
1647 * timestamp handling and checks the segment limits.
1649 * This is called with srcpad STREAM_LOCK held.
1651 * Returns: #GstFlowReturn
1653 static GstFlowReturn
1654 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1655 GstBaseParseClass * klass, GstBaseParseFrame * frame)
1661 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1663 buffer = frame->buffer;
1665 if (parse->priv->discont) {
1666 GST_DEBUG_OBJECT (parse, "marking DISCONT");
1667 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1668 parse->priv->discont = FALSE;
1671 /* some one-time start-up */
1672 if (G_UNLIKELY (!parse->priv->framecount)) {
1673 gst_base_parse_check_seekability (parse);
1674 gst_base_parse_check_upstream (parse);
1677 GST_LOG_OBJECT (parse,
1678 "parsing frame at offset %" G_GUINT64_FORMAT
1679 " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
1680 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1681 gst_buffer_get_size (buffer));
1683 /* use default handler to provide initial (upstream) metadata */
1684 gst_base_parse_parse_frame (parse, frame);
1686 /* store offset as it might get overwritten */
1687 offset = GST_BUFFER_OFFSET (buffer);
1688 ret = klass->parse_frame (parse, frame);
1690 buffer = frame->buffer;
1691 /* subclass must play nice */
1692 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1694 /* check if subclass/format can provide ts.
1695 * If so, that allows and enables extra seek and duration determining options */
1696 if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
1697 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && parse->priv->has_timing_info
1698 && parse->priv->pad_mode == GST_PAD_ACTIVATE_PULL) {
1699 parse->priv->first_frame_offset = offset;
1700 parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1701 GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1702 " for first frame at offset %" G_GINT64_FORMAT,
1703 GST_TIME_ARGS (parse->priv->first_frame_ts),
1704 parse->priv->first_frame_offset);
1705 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1707 GstClockTime last_ts = G_MAXINT64;
1709 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1710 gst_base_parse_locate_time (parse, &last_ts, &off);
1711 if (GST_CLOCK_TIME_IS_VALID (last_ts))
1712 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1715 /* disable further checks */
1716 parse->priv->first_frame_offset = 0;
1720 /* again use default handler to add missing metadata;
1721 * we may have new information on frame properties */
1722 gst_base_parse_parse_frame (parse, frame);
1723 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1724 GST_BUFFER_DURATION_IS_VALID (buffer)) {
1725 parse->priv->next_ts =
1726 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1728 /* we lost track, do not produce bogus time next time around
1729 * (probably means parser subclass has given up on parsing as well) */
1730 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1731 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1734 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1735 GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1736 gst_base_parse_add_index_entry (parse, offset,
1737 GST_BUFFER_TIMESTAMP (buffer),
1738 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1740 /* First buffers are dropped, this means that the subclass needs more
1741 * frames to decide on the format and queues them internally */
1742 /* convert internal flow to OK and mark discont for the next buffer. */
1743 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1744 gst_base_parse_frame_free (frame);
1746 } else if (ret == GST_BASE_PARSE_FLOW_QUEUED) {
1747 gst_base_parse_queue_frame (parse, frame);
1749 } else if (ret != GST_FLOW_OK) {
1753 /* All OK, push queued frames if there are any */
1754 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
1755 GstBaseParseFrame *queued_frame;
1757 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
1758 gst_base_parse_push_frame (parse, queued_frame);
1762 return gst_base_parse_push_frame (parse, frame);
1766 * gst_base_parse_push_frame:
1767 * @parse: #GstBaseParse.
1768 * @frame: (transfer full): a #GstBaseParseFrame
1770 * Pushes the frame downstream, sends any pending events and
1771 * does some timestamp and segment handling. Takes ownership
1772 * of @frame and will clear it (if it was initialised with
1773 * gst_base_parse_frame_init()) or free it.
1775 * This must be called with sinkpad STREAM_LOCK held.
1777 * Returns: #GstFlowReturn
1782 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1784 GstFlowReturn ret = GST_FLOW_OK;
1785 GstClockTime last_start = GST_CLOCK_TIME_NONE;
1786 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1787 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1791 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1792 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
1794 GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
1796 buffer = frame->buffer;
1798 GST_LOG_OBJECT (parse,
1799 "processing buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1800 ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buffer),
1801 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1802 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1805 size = gst_buffer_get_size (buffer);
1806 parse->priv->bytecount += size;
1807 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1808 parse->priv->framecount++;
1809 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1810 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1813 /* 0 means disabled */
1814 if (parse->priv->update_interval < 0)
1815 parse->priv->update_interval = 50;
1816 else if (parse->priv->update_interval > 0 &&
1817 (parse->priv->framecount % parse->priv->update_interval) == 0)
1818 gst_base_parse_update_duration (parse);
1820 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1821 last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1822 if (last_start != GST_CLOCK_TIME_NONE
1823 && GST_BUFFER_DURATION_IS_VALID (buffer))
1824 last_stop = last_start + GST_BUFFER_DURATION (buffer);
1826 /* should have caps by now */
1827 g_return_val_if_fail (gst_pad_has_current_caps (parse->srcpad),
1830 /* segment adjustment magic; only if we are running the whole show */
1831 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1832 (parse->priv->pad_mode == GST_PAD_ACTIVATE_PULL ||
1833 parse->priv->upstream_seekable)) {
1834 /* segment times are typically estimates,
1835 * actual frame data might lead subclass to different timestamps,
1836 * so override segment start from what is supplied there */
1837 if (G_UNLIKELY (parse->priv->pending_segment && !parse->priv->exact_position
1838 && GST_CLOCK_TIME_IS_VALID (last_start))) {
1839 gst_event_unref (parse->priv->pending_segment);
1840 parse->segment.start =
1841 MIN ((guint64) last_start, (guint64) parse->segment.stop);
1843 GST_DEBUG_OBJECT (parse,
1844 "adjusting pending segment start to %" GST_TIME_FORMAT,
1845 GST_TIME_ARGS (parse->segment.start));
1847 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
1849 /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1850 if (GST_CLOCK_TIME_IS_VALID (parse->segment.position) &&
1851 GST_CLOCK_TIME_IS_VALID (last_start)) {
1852 GstClockTimeDiff diff;
1854 /* only send newsegments with increasing start times,
1855 * otherwise if these go back and forth downstream (sinks) increase
1856 * accumulated time and running_time */
1857 diff = GST_CLOCK_DIFF (parse->segment.position, last_start);
1858 if (G_UNLIKELY (diff > 2 * GST_SECOND
1859 && last_start > parse->segment.start
1860 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
1861 || last_start < parse->segment.stop))) {
1863 GST_DEBUG_OBJECT (parse,
1864 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
1865 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1866 "Sending updated NEWSEGMENT events", diff,
1867 GST_TIME_ARGS (parse->segment.position),
1868 GST_TIME_ARGS (last_start));
1870 if (G_UNLIKELY (parse->priv->pending_segment)) {
1871 gst_event_unref (parse->priv->pending_segment);
1872 parse->segment.start = last_start;
1873 parse->segment.time = last_start;
1874 parse->priv->pending_segment =
1875 gst_event_new_segment (&parse->segment);
1877 /* skip gap FIXME */
1878 gst_pad_push_event (parse->srcpad,
1879 gst_event_new_segment (&parse->segment));
1881 parse->segment.position = last_start;
1886 /* and should then also be linked downstream, so safe to send some events */
1887 if (G_UNLIKELY (parse->priv->close_segment)) {
1888 /* only set up by loop */
1889 GST_DEBUG_OBJECT (parse, "loop sending close segment");
1890 gst_pad_push_event (parse->srcpad, parse->priv->close_segment);
1891 parse->priv->close_segment = NULL;
1893 if (G_UNLIKELY (parse->priv->pending_segment)) {
1894 GstEvent *pending_segment;
1896 pending_segment = parse->priv->pending_segment;
1897 parse->priv->pending_segment = NULL;
1899 GST_DEBUG_OBJECT (parse, "%s push pending segment",
1900 parse->priv->pad_mode == GST_PAD_ACTIVATE_PULL ? "loop" : "chain");
1901 gst_pad_push_event (parse->srcpad, pending_segment);
1903 /* have caps; check identity */
1904 gst_base_parse_check_media (parse);
1907 /* update bitrates and optionally post corresponding tags
1908 * (following newsegment) */
1909 gst_base_parse_update_bitrates (parse, frame);
1911 if (G_UNLIKELY (parse->priv->pending_events)) {
1914 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1915 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1917 g_list_free (parse->priv->pending_events);
1918 parse->priv->pending_events = NULL;
1921 if (klass->pre_push_frame) {
1922 ret = klass->pre_push_frame (parse, frame);
1924 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
1927 /* take final ownership of frame buffer */
1928 buffer = frame->buffer;
1929 frame->buffer = NULL;
1931 /* subclass must play nice */
1932 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1934 parse->priv->seen_keyframe |= parse->priv->is_video &&
1935 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1937 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
1938 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1939 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
1940 GST_BUFFER_TIMESTAMP (buffer) >
1941 parse->segment.stop + parse->priv->lead_out_ts) {
1942 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
1944 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1945 GST_BUFFER_DURATION_IS_VALID (buffer) &&
1946 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
1947 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
1948 parse->priv->lead_in_ts < parse->segment.start) {
1949 if (parse->priv->seen_keyframe) {
1950 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
1953 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
1954 ret = GST_BASE_PARSE_FLOW_DROPPED;
1961 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1962 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) dropped", size);
1963 gst_buffer_unref (buffer);
1965 } else if (ret == GST_FLOW_OK) {
1966 if (parse->segment.rate > 0.0) {
1967 GST_LOG_OBJECT (parse, "pushing frame (%" G_GSIZE_FORMAT " bytes) now..",
1969 ret = gst_pad_push (parse->srcpad, buffer);
1970 GST_LOG_OBJECT (parse, "frame pushed, flow %s", gst_flow_get_name (ret));
1972 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) queued for now",
1974 parse->priv->buffers_queued =
1975 g_slist_prepend (parse->priv->buffers_queued, buffer);
1979 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s",
1980 size, gst_flow_get_name (ret));
1981 gst_buffer_unref (buffer);
1982 /* if we are not sufficiently in control, let upstream decide on EOS */
1983 if (ret == GST_FLOW_EOS &&
1984 (parse->priv->passthrough ||
1985 (parse->priv->pad_mode == GST_PAD_ACTIVATE_PUSH &&
1986 !parse->priv->upstream_seekable)))
1990 /* Update current running segment position */
1991 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
1992 parse->segment.position < last_stop)
1993 parse->segment.position = last_stop;
1995 gst_base_parse_frame_free (frame);
2001 /* gst_base_parse_drain:
2003 * Drains the adapter until it is empty. It decreases the min_frame_size to
2004 * match the current adapter size and calls chain method until the adapter
2005 * is emptied or chain returns with error.
2008 gst_base_parse_drain (GstBaseParse * parse)
2012 GST_DEBUG_OBJECT (parse, "draining");
2013 parse->priv->drain = TRUE;
2016 avail = gst_adapter_available (parse->priv->adapter);
2020 if (gst_base_parse_chain (parse->sinkpad, NULL) != GST_FLOW_OK) {
2024 /* nothing changed, maybe due to truncated frame; break infinite loop */
2025 if (avail == gst_adapter_available (parse->priv->adapter)) {
2026 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
2027 gst_adapter_clear (parse->priv->adapter);
2031 parse->priv->drain = FALSE;
2034 /* gst_base_parse_send_buffers
2036 * Sends buffers collected in send_buffers downstream, and ensures that list
2037 * is empty at the end (errors or not).
2039 static GstFlowReturn
2040 gst_base_parse_send_buffers (GstBaseParse * parse)
2042 GSList *send = NULL;
2044 GstFlowReturn ret = GST_FLOW_OK;
2046 send = parse->priv->buffers_send;
2050 buf = GST_BUFFER_CAST (send->data);
2051 GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
2052 GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2053 ", offset %" G_GINT64_FORMAT, buf,
2054 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2055 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2057 /* iterate output queue an push downstream */
2058 ret = gst_pad_push (parse->srcpad, buf);
2059 send = g_slist_delete_link (send, send);
2061 /* clear any leftover if error */
2062 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2064 buf = GST_BUFFER_CAST (send->data);
2065 gst_buffer_unref (buf);
2066 send = g_slist_delete_link (send, send);
2071 parse->priv->buffers_send = send;
2076 /* gst_base_parse_process_fragment:
2078 * Processes a reverse playback (forward) fragment:
2079 * - append head of last fragment that was skipped to current fragment data
2080 * - drain the resulting current fragment data (i.e. repeated chain)
2081 * - add time/duration (if needed) to frames queued by chain
2082 * - push queued data
2084 static GstFlowReturn
2085 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
2088 GstFlowReturn ret = GST_FLOW_OK;
2089 gboolean seen_key = FALSE, seen_delta = FALSE;
2095 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2096 while (parse->priv->buffers_pending) {
2097 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2098 GST_LOG_OBJECT (parse, "adding pending buffer (size %" G_GSIZE_FORMAT ")",
2099 gst_buffer_get_size (buf));
2100 gst_adapter_push (parse->priv->adapter, buf);
2101 parse->priv->buffers_pending =
2102 g_slist_delete_link (parse->priv->buffers_pending,
2103 parse->priv->buffers_pending);
2106 /* invalidate so no fall-back timestamping is performed;
2107 * ok if taken from subclass or upstream */
2108 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
2109 /* prevent it hanging around stop all the time */
2110 parse->segment.position = GST_CLOCK_TIME_NONE;
2112 parse->priv->discont = TRUE;
2114 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2115 /* initial skipped data is added to buffers_pending */
2116 gst_base_parse_drain (parse);
2119 if (parse->priv->buffers_send) {
2120 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2121 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2124 /* add metadata (if needed to queued buffers */
2125 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2126 GST_TIME_ARGS (parse->priv->last_ts));
2127 while (parse->priv->buffers_queued) {
2128 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2130 /* no touching if upstream or parsing provided time */
2131 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2132 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2133 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2134 } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
2135 GST_BUFFER_DURATION_IS_VALID (buf)) {
2136 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
2137 parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
2139 parse->priv->last_ts = 0;
2140 GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
2141 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2142 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2144 /* no idea, very bad */
2145 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2148 parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
2150 /* reverse order for ascending sending */
2151 /* send downstream at keyframe not preceded by a keyframe
2152 * (e.g. that should identify start of collection of IDR nals) */
2153 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2155 ret = gst_base_parse_send_buffers (parse);
2156 /* if a problem, throw all to sending */
2157 if (ret != GST_FLOW_OK) {
2158 parse->priv->buffers_send =
2159 g_slist_reverse (parse->priv->buffers_queued);
2160 parse->priv->buffers_queued = NULL;
2169 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2171 parse->priv->buffers_send =
2172 g_slist_prepend (parse->priv->buffers_send, buf);
2173 parse->priv->buffers_queued =
2174 g_slist_delete_link (parse->priv->buffers_queued,
2175 parse->priv->buffers_queued);
2178 /* audio may have all marked as keyframe, so arrange to send here */
2180 ret = gst_base_parse_send_buffers (parse);
2182 /* any trailing unused no longer usable (ideally none) */
2183 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2184 GST_DEBUG_OBJECT (parse, "discarding %" G_GSIZE_FORMAT " trailing bytes",
2185 gst_adapter_available (parse->priv->adapter));
2186 gst_adapter_clear (parse->priv->adapter);
2192 /* small helper that checks whether we have been trying to resync too long */
2193 static inline GstFlowReturn
2194 gst_base_parse_check_sync (GstBaseParse * parse)
2196 if (G_UNLIKELY (parse->priv->discont &&
2197 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2198 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2199 ("Failed to parse stream"), (NULL));
2200 return GST_FLOW_ERROR;
2206 static GstFlowReturn
2207 gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
2209 GstBaseParseClass *bclass;
2210 GstBaseParse *parse;
2211 GstFlowReturn ret = GST_FLOW_OK;
2212 GstBuffer *outbuf = NULL;
2213 GstBuffer *tmpbuf = NULL;
2217 guint old_min_size = 0, min_size, av;
2218 GstClockTime timestamp;
2219 GstBaseParseFrame *frame;
2221 parse = GST_BASE_PARSE (GST_OBJECT_PARENT (pad));
2222 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2224 if (parse->priv->detecting) {
2225 GstBuffer *detect_buf;
2227 if (parse->priv->detect_buffers_size == 0) {
2228 detect_buf = gst_buffer_ref (buffer);
2233 detect_buf = gst_buffer_new ();
2235 for (l = parse->priv->detect_buffers; l; l = l->next) {
2236 gsize tmpsize = gst_buffer_get_size (l->data);
2238 gst_buffer_copy_into (detect_buf, GST_BUFFER_CAST (l->data),
2239 GST_BUFFER_COPY_MEMORY, offset, tmpsize);
2243 gst_buffer_copy_into (detect_buf, buffer, GST_BUFFER_COPY_MEMORY,
2244 offset, gst_buffer_get_size (buffer));
2247 ret = bclass->detect (parse, detect_buf);
2248 gst_buffer_unref (detect_buf);
2250 if (ret == GST_FLOW_OK) {
2253 /* Detected something */
2254 parse->priv->detecting = FALSE;
2256 for (l = parse->priv->detect_buffers; l; l = l->next) {
2257 if (ret == GST_FLOW_OK && !parse->priv->flushing)
2259 gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2260 GST_BUFFER_CAST (l->data));
2262 gst_buffer_unref (GST_BUFFER_CAST (l->data));
2264 g_list_free (parse->priv->detect_buffers);
2265 parse->priv->detect_buffers = NULL;
2266 parse->priv->detect_buffers_size = 0;
2268 if (ret != GST_FLOW_OK) {
2272 /* Handle the current buffer */
2273 } else if (ret == GST_FLOW_NOT_NEGOTIATED) {
2274 /* Still detecting, append buffer or error out if draining */
2276 if (parse->priv->drain) {
2277 GST_DEBUG_OBJECT (parse, "Draining but did not detect format yet");
2278 return GST_FLOW_ERROR;
2279 } else if (parse->priv->flushing) {
2280 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref,
2282 g_list_free (parse->priv->detect_buffers);
2283 parse->priv->detect_buffers = NULL;
2284 parse->priv->detect_buffers_size = 0;
2286 parse->priv->detect_buffers =
2287 g_list_append (parse->priv->detect_buffers, buffer);
2288 parse->priv->detect_buffers_size += gst_buffer_get_size (buffer);
2292 /* Something went wrong, subclass responsible for error reporting */
2296 /* And now handle the current buffer if detection worked */
2299 frame = &parse->priv->frame;
2301 if (G_LIKELY (buffer)) {
2302 GST_LOG_OBJECT (parse,
2303 "buffer size: %" G_GSIZE_FORMAT ", offset = %" G_GINT64_FORMAT,
2304 gst_buffer_get_size (buffer), GST_BUFFER_OFFSET (buffer));
2305 if (G_UNLIKELY (parse->priv->passthrough)) {
2306 gst_base_parse_frame_init (frame);
2307 frame->buffer = gst_buffer_make_writable (buffer);
2308 return gst_base_parse_push_frame (parse, frame);
2310 /* upstream feeding us in reverse playback;
2311 * gather each fragment, then process it in single run */
2312 if (parse->segment.rate < 0.0) {
2313 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2314 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2315 ret = gst_base_parse_process_fragment (parse, FALSE);
2317 gst_adapter_push (parse->priv->adapter, buffer);
2320 gst_adapter_push (parse->priv->adapter, buffer);
2323 if (G_UNLIKELY (buffer &&
2324 GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2325 frame->_private_flags |= GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
2326 gst_base_parse_frame_free (frame);
2329 /* Parse and push as many frames as possible */
2330 /* Stop either when adapter is empty or we are flushing */
2331 while (!parse->priv->flushing) {
2334 /* maintain frame state for a single frame parsing round across _chain calls,
2335 * so only init when needed */
2336 if (!frame->_private_flags)
2337 gst_base_parse_frame_init (frame);
2339 tmpbuf = gst_buffer_new ();
2342 /* Synchronization loop */
2344 /* note: if subclass indicates MAX fsize,
2345 * this will not likely be available anyway ... */
2346 min_size = MAX (parse->priv->min_frame_size, fsize);
2347 av = gst_adapter_available (parse->priv->adapter);
2349 /* loop safety check */
2350 if (G_UNLIKELY (old_min_size >= min_size))
2352 old_min_size = min_size;
2354 if (G_UNLIKELY (parse->priv->drain)) {
2356 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2357 if (G_UNLIKELY (!min_size)) {
2358 gst_buffer_unref (tmpbuf);
2363 /* Collect at least min_frame_size bytes */
2364 if (av < min_size) {
2365 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
2367 gst_buffer_unref (tmpbuf);
2371 /* always pass all available data */
2372 data = gst_adapter_map (parse->priv->adapter, av);
2373 gst_buffer_take_memory (tmpbuf, -1,
2374 gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
2375 (gpointer) data, NULL, av, 0, av));
2376 GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
2378 if (parse->priv->discont) {
2379 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2380 GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2384 gst_base_parse_frame_update (parse, frame, tmpbuf);
2385 res = bclass->check_valid_frame (parse, frame, &fsize, &skip);
2386 gst_adapter_unmap (parse->priv->adapter, 0);
2387 gst_buffer_replace (&frame->buffer, NULL);
2388 gst_buffer_remove_memory_range (tmpbuf, 0, -1);
2390 if (gst_adapter_available (parse->priv->adapter) < fsize) {
2391 GST_DEBUG_OBJECT (parse, "found valid frame but not enough data"
2392 " available (only %" G_GSIZE_FORMAT " bytes)",
2393 gst_adapter_available (parse->priv->adapter));
2394 gst_buffer_unref (tmpbuf);
2397 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2401 /* subclass didn't touch this value. By default we skip 1 byte */
2405 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2406 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2407 /* reverse playback, and no frames found yet, so we are skipping
2408 * the leading part of a fragment, which may form the tail of
2409 * fragment coming later, hopefully subclass skips efficiently ... */
2410 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2411 outbuf = gst_adapter_take_buffer (parse->priv->adapter, skip);
2412 outbuf = gst_buffer_make_writable (outbuf);
2413 GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
2414 parse->priv->buffers_pending =
2415 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2418 gst_adapter_flush (parse->priv->adapter, skip);
2420 parse->priv->offset += skip;
2421 if (!parse->priv->discont)
2422 parse->priv->sync_offset = parse->priv->offset;
2423 parse->priv->discont = TRUE;
2424 /* something changed least; nullify loop check */
2427 /* skip == 0 should imply subclass set min_size to need more data;
2428 * we check this shortly */
2429 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2430 gst_buffer_unref (tmpbuf);
2434 gst_buffer_unref (tmpbuf);
2438 /* Subclass found the sync, but still wants to skip some data */
2439 GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
2440 gst_adapter_flush (parse->priv->adapter, skip);
2441 parse->priv->offset += skip;
2444 /* Grab lock to prevent a race with FLUSH_START handler */
2445 GST_PAD_STREAM_LOCK (parse->srcpad);
2447 /* FLUSH_START event causes the "flushing" flag to be set. In this
2448 * case we can leave the frame pushing loop */
2449 if (parse->priv->flushing) {
2450 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2454 /* move along with upstream timestamp (if any),
2455 * but interpolate in between */
2456 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2457 if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2458 (parse->priv->prev_ts != timestamp)) {
2459 parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2462 /* FIXME: Would it be more efficient to make a subbuffer instead? */
2463 outbuf = gst_adapter_take_buffer (parse->priv->adapter, fsize);
2464 outbuf = gst_buffer_make_writable (outbuf);
2466 /* Subclass may want to know the data offset */
2467 GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2468 parse->priv->offset += fsize;
2469 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2470 GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
2472 frame->buffer = outbuf;
2473 ret = gst_base_parse_handle_and_push_frame (parse, bclass, frame);
2474 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2476 if (ret != GST_FLOW_OK) {
2477 GST_LOG_OBJECT (parse, "push returned %d", ret);
2483 GST_LOG_OBJECT (parse, "chain leaving");
2489 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2490 ("min_size evolution %d -> %d; breaking to avoid looping",
2491 old_min_size, min_size));
2492 return GST_FLOW_ERROR;
2496 /* pull @size bytes at current offset,
2497 * i.e. at least try to and possibly return a shorter buffer if near the end */
2498 static GstFlowReturn
2499 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2500 GstBuffer ** buffer)
2502 GstFlowReturn ret = GST_FLOW_OK;
2504 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2506 /* Caching here actually makes much less difference than one would expect.
2507 * We do it mainly to avoid pulling buffers of 1 byte all the time */
2508 if (parse->priv->cache) {
2509 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2510 gint cache_size = gst_buffer_get_size (parse->priv->cache);
2512 if (cache_offset <= parse->priv->offset &&
2513 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2514 *buffer = gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL,
2515 parse->priv->offset - cache_offset, size);
2516 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2519 /* not enough data in the cache, free cache and get a new one */
2520 gst_buffer_unref (parse->priv->cache);
2521 parse->priv->cache = NULL;
2524 /* refill the cache */
2526 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2527 64 * 1024), &parse->priv->cache);
2528 if (ret != GST_FLOW_OK) {
2529 parse->priv->cache = NULL;
2533 if (gst_buffer_get_size (parse->priv->cache) >= size) {
2535 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0,
2537 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2541 /* Not possible to get enough data, try a last time with
2542 * requesting exactly the size we need */
2543 gst_buffer_unref (parse->priv->cache);
2544 parse->priv->cache = NULL;
2546 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2547 &parse->priv->cache);
2549 if (ret != GST_FLOW_OK) {
2550 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2555 if (gst_buffer_get_size (parse->priv->cache) < size) {
2556 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2557 G_GUINT64_FORMAT ": wanted %u bytes, got %" G_GSIZE_FORMAT " bytes",
2558 parse->priv->offset, size, gst_buffer_get_size (parse->priv->cache));
2560 *buffer = parse->priv->cache;
2561 parse->priv->cache = NULL;
2567 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0, size);
2568 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2573 static GstFlowReturn
2574 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2577 GstClockTime ts = 0;
2581 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2582 ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2583 parse->priv->last_offset);
2585 if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2586 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2587 GST_TIME_ARGS (parse->segment.start));
2592 /* last fragment started at last_offset / last_ts;
2593 * seek back 10s capped at 1MB */
2594 if (parse->priv->last_ts >= 10 * GST_SECOND)
2595 ts = parse->priv->last_ts - 10 * GST_SECOND;
2596 /* if we are exact now, we will be more so going backwards */
2597 if (parse->priv->exact_position) {
2598 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2600 if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2601 GST_FORMAT_BYTES, &offset)) {
2602 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2605 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2606 parse->priv->last_offset - 1024);
2607 offset = MAX (0, offset);
2609 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2611 parse->priv->offset = offset;
2613 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2615 if (ret != GST_FLOW_OK)
2618 /* offset will increase again as fragment is processed/parsed */
2619 parse->priv->last_offset = offset;
2621 gst_adapter_push (parse->priv->adapter, buffer);
2622 ret = gst_base_parse_process_fragment (parse, FALSE);
2623 if (ret != GST_FLOW_OK)
2626 /* force previous fragment */
2627 parse->priv->offset = -1;
2634 * pull and scan for next frame starting from current offset
2635 * ajusts sync, drain and offset going along */
2636 static GstFlowReturn
2637 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2638 GstBaseParseFrame * frame, gboolean full)
2640 GstBuffer *buffer, *outbuf;
2641 GstFlowReturn ret = GST_FLOW_OK;
2642 guint fsize = 1, min_size, old_min_size = 0;
2645 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2647 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2648 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2650 /* let's make this efficient for all subclass once and for all;
2651 * maybe it does not need this much, but in the latter case, we know we are
2652 * in pull mode here and might as well try to read and supply more anyway
2653 * (so does the buffer caching mechanism) */
2659 min_size = MAX (parse->priv->min_frame_size, fsize);
2660 /* loop safety check */
2661 if (G_UNLIKELY (old_min_size >= min_size))
2663 old_min_size = min_size;
2665 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2666 if (ret != GST_FLOW_OK)
2669 if (parse->priv->discont) {
2670 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2671 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2674 /* if we got a short read, inform subclass we are draining leftover
2675 * and no more is to be expected */
2676 if (gst_buffer_get_size (buffer) < min_size)
2677 parse->priv->drain = TRUE;
2679 if (parse->priv->detecting) {
2680 ret = klass->detect (parse, buffer);
2681 if (ret == GST_FLOW_NOT_NEGOTIATED) {
2682 /* If draining we error out, otherwise request a buffer
2684 if (parse->priv->drain) {
2685 gst_buffer_unref (buffer);
2686 GST_ERROR_OBJECT (parse, "Failed to detect format but draining");
2687 return GST_FLOW_ERROR;
2690 gst_buffer_unref (buffer);
2693 } else if (ret != GST_FLOW_OK) {
2694 gst_buffer_unref (buffer);
2695 GST_ERROR_OBJECT (parse, "detect() returned %s",
2696 gst_flow_get_name (ret));
2700 /* Else handle this buffer normally */
2704 gst_base_parse_frame_update (parse, frame, buffer);
2705 res = klass->check_valid_frame (parse, frame, &fsize, &skip);
2706 gst_buffer_replace (&frame->buffer, NULL);
2708 parse->priv->drain = FALSE;
2709 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2712 parse->priv->drain = FALSE;
2716 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2717 if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2718 /* reverse playback, and no frames found yet, so we are skipping
2719 * the leading part of a fragment, which may form the tail of
2720 * fragment coming later, hopefully subclass skips efficiently ... */
2721 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, 0, skip);
2722 parse->priv->buffers_pending =
2723 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2726 parse->priv->offset += skip;
2727 if (!parse->priv->discont)
2728 parse->priv->sync_offset = parse->priv->offset;
2729 parse->priv->discont = TRUE;
2730 /* something changed at least; nullify loop check */
2731 if (fsize == G_MAXUINT)
2732 fsize = old_min_size + 64 * 1024;
2735 /* skip == 0 should imply subclass set min_size to need more data;
2736 * we check this shortly */
2737 GST_DEBUG_OBJECT (parse, "finding sync...");
2738 gst_buffer_unref (buffer);
2739 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2744 /* Does the subclass want to skip too? */
2746 parse->priv->offset += skip;
2750 if (fsize + skip <= gst_buffer_get_size (buffer)) {
2751 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, skip, fsize);
2752 GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2753 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2754 gst_buffer_unref (buffer);
2756 gst_buffer_unref (buffer);
2757 ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2758 if (ret != GST_FLOW_OK)
2760 if (gst_buffer_get_size (outbuf) < fsize) {
2761 gst_buffer_unref (outbuf);
2766 parse->priv->offset += fsize;
2768 frame->buffer = outbuf;
2776 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2777 ("min_size evolution %d -> %d; breaking to avoid looping",
2778 old_min_size, min_size));
2779 return GST_FLOW_ERROR;
2783 /* Loop that is used in pull mode to retrieve data from upstream */
2785 gst_base_parse_loop (GstPad * pad)
2787 GstBaseParse *parse;
2788 GstBaseParseClass *klass;
2789 GstFlowReturn ret = GST_FLOW_OK;
2790 GstBaseParseFrame frame;
2792 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2793 klass = GST_BASE_PARSE_GET_CLASS (parse);
2795 /* reverse playback:
2796 * first fragment (closest to stop time) is handled normally below,
2797 * then we pull in fragments going backwards */
2798 if (parse->segment.rate < 0.0) {
2799 /* check if we jumped back to a previous fragment,
2800 * which is a post-first fragment */
2801 if (parse->priv->offset < 0) {
2802 ret = gst_base_parse_handle_previous_fragment (parse);
2807 gst_base_parse_frame_init (&frame);
2808 ret = gst_base_parse_scan_frame (parse, klass, &frame, TRUE);
2809 if (ret != GST_FLOW_OK)
2812 /* This always cleans up frame, even if error occurs */
2813 ret = gst_base_parse_handle_and_push_frame (parse, klass, &frame);
2815 /* eat expected eos signalling past segment in reverse playback */
2816 if (parse->segment.rate < 0.0 && ret == GST_FLOW_EOS &&
2817 parse->segment.position >= parse->segment.stop) {
2818 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2819 /* push what was accumulated during loop run */
2820 gst_base_parse_process_fragment (parse, TRUE);
2821 /* force previous fragment */
2822 parse->priv->offset = -1;
2827 if (ret == GST_FLOW_EOS)
2829 else if (ret != GST_FLOW_OK)
2832 gst_object_unref (parse);
2839 GST_DEBUG_OBJECT (parse, "eos");
2844 gboolean push_eos = FALSE;
2846 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2847 gst_flow_get_name (ret));
2848 gst_pad_pause_task (parse->sinkpad);
2850 if (ret == GST_FLOW_EOS) {
2851 /* handle end-of-stream/segment */
2852 if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2855 if ((stop = parse->segment.stop) == -1)
2856 stop = parse->segment.duration;
2858 GST_DEBUG_OBJECT (parse, "sending segment_done");
2860 gst_element_post_message
2861 (GST_ELEMENT_CAST (parse),
2862 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2863 GST_FORMAT_TIME, stop));
2865 /* If we STILL have zero frames processed, fire an error */
2866 if (parse->priv->framecount == 0) {
2867 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2868 ("No valid frames found before end of stream"), (NULL));
2872 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
2873 /* for fatal errors we post an error message, wrong-state is
2874 * not fatal because it happens due to flushes and only means
2875 * that we should stop now. */
2876 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2877 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2881 /* newsegment before eos */
2882 if (parse->priv->pending_segment) {
2883 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
2884 parse->priv->pending_segment = NULL;
2886 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2888 gst_object_unref (parse);
2893 gst_base_parse_sink_activate (GstPad * sinkpad)
2895 GstBaseParse *parse;
2896 gboolean result = TRUE;
2900 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2902 GST_DEBUG_OBJECT (parse, "sink activate");
2904 query = gst_query_new_scheduling ();
2905 result = gst_pad_peer_query (sinkpad, query);
2907 gst_query_parse_scheduling (query, &pull_mode, NULL, NULL, NULL, NULL,
2912 gst_query_unref (query);
2915 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2916 result = gst_pad_activate_pull (sinkpad, TRUE);
2918 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
2919 result = gst_pad_activate_push (sinkpad, TRUE);
2922 GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
2923 gst_object_unref (parse);
2928 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
2930 GstBaseParseClass *klass;
2931 gboolean result = TRUE;
2933 GST_DEBUG_OBJECT (parse, "activate %d", active);
2935 klass = GST_BASE_PARSE_GET_CLASS (parse);
2938 if (parse->priv->pad_mode == GST_PAD_ACTIVATE_NONE && klass->start)
2939 result = klass->start (parse);
2941 /* If the subclass implements ::detect we want to
2942 * call it for the first buffers now */
2943 parse->priv->detecting = (klass->detect != NULL);
2945 /* We must make sure streaming has finished before resetting things
2946 * and calling the ::stop vfunc */
2947 GST_PAD_STREAM_LOCK (parse->sinkpad);
2948 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2950 if (parse->priv->pad_mode != GST_PAD_ACTIVATE_NONE && klass->stop)
2951 result = klass->stop (parse);
2953 parse->priv->pad_mode = GST_PAD_ACTIVATE_NONE;
2955 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
2960 gst_base_parse_sink_activate_push (GstPad * pad, gboolean active)
2962 gboolean result = TRUE;
2963 GstBaseParse *parse;
2965 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2967 GST_DEBUG_OBJECT (parse, "sink activate push %d", active);
2969 result = gst_base_parse_activate (parse, active);
2972 parse->priv->pad_mode =
2973 active ? GST_PAD_ACTIVATE_PUSH : GST_PAD_ACTIVATE_NONE;
2975 GST_DEBUG_OBJECT (parse, "sink activate push return: %d", result);
2977 gst_object_unref (parse);
2982 gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
2984 gboolean result = FALSE;
2985 GstBaseParse *parse;
2987 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2989 GST_DEBUG_OBJECT (parse, "activate pull %d", active);
2991 result = gst_base_parse_activate (parse, active);
2995 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
2997 gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
3000 result &= gst_pad_stop_task (sinkpad);
3005 parse->priv->pad_mode =
3006 active ? GST_PAD_ACTIVATE_PULL : GST_PAD_ACTIVATE_NONE;
3008 GST_DEBUG_OBJECT (parse, "sink activate pull return: %d", result);
3010 gst_object_unref (parse);
3016 * gst_base_parse_set_duration:
3017 * @parse: #GstBaseParse.
3019 * @duration: duration value.
3020 * @interval: how often to update the duration estimate based on bitrate, or 0.
3022 * Sets the duration of the currently playing media. Subclass can use this
3023 * when it is able to determine duration and/or notices a change in the media
3024 * duration. Alternatively, if @interval is non-zero (default), then stream
3025 * duration is determined based on estimated bitrate, and updated every @interval
3031 gst_base_parse_set_duration (GstBaseParse * parse,
3032 GstFormat fmt, gint64 duration, gint interval)
3034 g_return_if_fail (parse != NULL);
3036 if (parse->priv->upstream_has_duration) {
3037 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
3041 if (duration != parse->priv->duration) {
3044 m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
3045 gst_element_post_message (GST_ELEMENT (parse), m);
3047 /* TODO: what about duration tag? */
3049 parse->priv->duration = duration;
3050 parse->priv->duration_fmt = fmt;
3051 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
3052 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
3053 if (interval != 0) {
3054 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
3058 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
3059 parse->priv->update_interval = interval;
3065 * gst_base_parse_set_average_bitrate:
3066 * @parse: #GstBaseParse.
3067 * @bitrate: average bitrate in bits/second
3069 * Optionally sets the average bitrate detected in media (if non-zero),
3070 * e.g. based on metadata, as it will be posted to the application.
3072 * By default, announced average bitrate is estimated. The average bitrate
3073 * is used to estimate the total duration of the stream and to estimate
3074 * a seek position, if there's no index and the format is syncable
3075 * (see gst_base_parse_set_syncable()).
3080 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
3082 parse->priv->bitrate = bitrate;
3083 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
3087 * gst_base_parse_set_min_frame_size:
3088 * @parse: #GstBaseParse.
3089 * @min_size: Minimum size of the data that this base class should give to
3092 * Subclass can use this function to tell the base class that it needs to
3093 * give at least #min_size buffers.
3098 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
3100 g_return_if_fail (parse != NULL);
3102 parse->priv->min_frame_size = min_size;
3103 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
3107 * gst_base_parse_set_frame_rate:
3108 * @parse: the #GstBaseParse to set
3109 * @fps_num: frames per second (numerator).
3110 * @fps_den: frames per second (denominator).
3111 * @lead_in: frames needed before a segment for subsequent decode
3112 * @lead_out: frames needed after a segment
3114 * If frames per second is configured, parser can take care of buffer duration
3115 * and timestamping. When performing segment clipping, or seeking to a specific
3116 * location, a corresponding decoder might need an initial @lead_in and a
3117 * following @lead_out number of frames to ensure the desired segment is
3118 * entirely filled upon decoding.
3123 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
3124 guint fps_den, guint lead_in, guint lead_out)
3126 g_return_if_fail (parse != NULL);
3128 parse->priv->fps_num = fps_num;
3129 parse->priv->fps_den = fps_den;
3130 if (!fps_num || !fps_den) {
3131 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
3133 fps_num = fps_den = 0;
3134 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
3135 parse->priv->lead_in = parse->priv->lead_out = 0;
3136 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
3138 parse->priv->frame_duration =
3139 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
3140 parse->priv->lead_in = lead_in;
3141 parse->priv->lead_out = lead_out;
3142 parse->priv->lead_in_ts =
3143 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
3144 parse->priv->lead_out_ts =
3145 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
3146 /* aim for about 1.5s to estimate duration */
3147 if (parse->priv->update_interval < 0) {
3148 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
3149 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
3150 parse->priv->update_interval);
3153 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
3154 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
3155 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
3156 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
3157 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
3158 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
3162 * gst_base_parse_set_has_timing_info:
3163 * @parse: a #GstBaseParse
3164 * @has_timing: whether frames carry timing information
3166 * Set if frames carry timing information which the subclass can (generally)
3167 * parse and provide. In particular, intrinsic (rather than estimated) time
3168 * can be obtained following a seek.
3173 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3175 parse->priv->has_timing_info = has_timing;
3176 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3180 * gst_base_parse_set_syncable:
3181 * @parse: a #GstBaseParse
3182 * @syncable: set if frame starts can be identified
3184 * Set if frame starts can be identified. This is set by default and
3185 * determines whether seeking based on bitrate averages
3186 * is possible for a format/stream.
3191 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3193 parse->priv->syncable = syncable;
3194 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3198 * gst_base_parse_set_passthrough:
3199 * @parse: a #GstBaseParse
3200 * @passthrough: %TRUE if parser should run in passthrough mode
3202 * Set if the nature of the format or configuration does not allow (much)
3203 * parsing, and the parser should operate in passthrough mode (which only
3204 * applies when operating in push mode). That is, incoming buffers are
3205 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3206 * callbacks will be invoked, but @pre_push_frame will still be invoked,
3207 * so subclass can perform as much or as little is appropriate for
3208 * passthrough semantics in @pre_push_frame.
3213 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3215 parse->priv->passthrough = passthrough;
3216 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3220 * gst_base_parse_set_latency:
3221 * @parse: a #GstBaseParse
3222 * @min_latency: minimum parse latency
3223 * @max_latency: maximum parse latency
3225 * Sets the minimum and maximum (which may likely be equal) latency introduced
3226 * by the parsing process. If there is such a latency, which depends on the
3227 * particular parsing of the format, it typically corresponds to 1 frame duration.
3232 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3233 GstClockTime max_latency)
3235 GST_OBJECT_LOCK (parse);
3236 parse->priv->min_latency = min_latency;
3237 parse->priv->max_latency = max_latency;
3238 GST_OBJECT_UNLOCK (parse);
3239 GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3240 GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3241 GST_TIME_ARGS (max_latency));
3245 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3246 GstClockTime * duration)
3248 gboolean res = FALSE;
3250 g_return_val_if_fail (duration != NULL, FALSE);
3252 *duration = GST_CLOCK_TIME_NONE;
3253 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3254 GST_LOG_OBJECT (parse, "using provided duration");
3255 *duration = parse->priv->duration;
3257 } else if (parse->priv->duration != -1) {
3258 GST_LOG_OBJECT (parse, "converting provided duration");
3259 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3260 parse->priv->duration, format, (gint64 *) duration);
3261 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3262 GST_LOG_OBJECT (parse, "using estimated duration");
3263 *duration = parse->priv->estimated_duration;
3267 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3268 GST_TIME_ARGS (*duration));
3273 gst_base_parse_query (GstPad * pad, GstQuery * query)
3275 GstBaseParse *parse;
3276 gboolean res = FALSE;
3278 parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3280 GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3282 switch (GST_QUERY_TYPE (query)) {
3283 case GST_QUERY_POSITION:
3288 GST_DEBUG_OBJECT (parse, "position query");
3289 gst_query_parse_position (query, &format, NULL);
3291 /* try upstream first */
3292 res = gst_pad_query_default (pad, query);
3294 /* Fall back on interpreting segment */
3295 GST_OBJECT_LOCK (parse);
3296 if (format == GST_FORMAT_BYTES) {
3297 dest_value = parse->priv->offset;
3299 } else if (format == parse->segment.format &&
3300 GST_CLOCK_TIME_IS_VALID (parse->segment.position)) {
3301 dest_value = gst_segment_to_stream_time (&parse->segment,
3302 parse->segment.format, parse->segment.position);
3305 GST_OBJECT_UNLOCK (parse);
3307 /* no precise result, upstream no idea either, then best estimate */
3308 /* priv->offset is updated in both PUSH/PULL modes */
3309 res = gst_base_parse_convert (parse,
3310 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3313 gst_query_set_position (query, format, dest_value);
3317 case GST_QUERY_DURATION:
3320 GstClockTime duration;
3322 GST_DEBUG_OBJECT (parse, "duration query");
3323 gst_query_parse_duration (query, &format, NULL);
3325 /* consult upstream */
3326 res = gst_pad_query_default (pad, query);
3328 /* otherwise best estimate from us */
3330 res = gst_base_parse_get_duration (parse, format, &duration);
3332 gst_query_set_duration (query, format, duration);
3336 case GST_QUERY_SEEKING:
3339 GstClockTime duration = GST_CLOCK_TIME_NONE;
3340 gboolean seekable = FALSE;
3342 GST_DEBUG_OBJECT (parse, "seeking query");
3343 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3345 /* consult upstream */
3346 res = gst_pad_query_default (pad, query);
3348 /* we may be able to help if in TIME */
3349 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3350 gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3351 /* already OK if upstream takes care */
3352 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3354 if (!(res && seekable)) {
3355 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3356 || duration == -1) {
3357 /* seekable if we still have a chance to get duration later on */
3359 parse->priv->upstream_seekable && parse->priv->update_interval;
3361 seekable = parse->priv->upstream_seekable;
3362 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3365 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3371 case GST_QUERY_FORMATS:
3372 gst_query_set_formatsv (query, 3, fmtlist);
3375 case GST_QUERY_CONVERT:
3377 GstFormat src_format, dest_format;
3378 gint64 src_value, dest_value;
3380 gst_query_parse_convert (query, &src_format, &src_value,
3381 &dest_format, &dest_value);
3383 res = gst_base_parse_convert (parse, src_format, src_value,
3384 dest_format, &dest_value);
3386 gst_query_set_convert (query, src_format, src_value,
3387 dest_format, dest_value);
3391 case GST_QUERY_LATENCY:
3393 if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3395 GstClockTime min_latency, max_latency;
3397 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3398 GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3399 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3400 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3402 GST_OBJECT_LOCK (parse);
3403 /* add our latency */
3404 if (min_latency != -1)
3405 min_latency += parse->priv->min_latency;
3406 if (max_latency != -1)
3407 max_latency += parse->priv->max_latency;
3408 GST_OBJECT_UNLOCK (parse);
3410 gst_query_set_latency (query, live, min_latency, max_latency);
3415 res = gst_pad_query_default (pad, query);
3421 /* scans for a cluster start from @pos,
3422 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3423 static GstFlowReturn
3424 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3425 GstClockTime * time, GstClockTime * duration)
3427 GstBaseParseClass *klass;
3429 gboolean orig_drain, orig_discont;
3430 GstFlowReturn ret = GST_FLOW_OK;
3431 GstBuffer *buf = NULL;
3432 GstBaseParseFrame frame;
3434 g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3435 g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3436 g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3438 klass = GST_BASE_PARSE_GET_CLASS (parse);
3440 *time = GST_CLOCK_TIME_NONE;
3441 *duration = GST_CLOCK_TIME_NONE;
3444 orig_offset = parse->priv->offset;
3445 orig_discont = parse->priv->discont;
3446 orig_drain = parse->priv->drain;
3448 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3449 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3451 gst_base_parse_frame_init (&frame);
3453 /* jump elsewhere and locate next frame */
3454 parse->priv->offset = *pos;
3455 ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3456 if (ret != GST_FLOW_OK)
3460 GST_LOG_OBJECT (parse,
3461 "peek parsing frame at offset %" G_GUINT64_FORMAT
3462 " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
3463 GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf),
3464 gst_buffer_get_size (buf));
3466 /* get offset first, subclass parsing might dump other stuff in there */
3467 *pos = GST_BUFFER_OFFSET (buf);
3468 ret = klass->parse_frame (parse, &frame);
3471 /* but it should provide proper time */
3472 *time = GST_BUFFER_TIMESTAMP (buf);
3473 *duration = GST_BUFFER_DURATION (buf);
3475 gst_base_parse_frame_free (&frame);
3477 GST_LOG_OBJECT (parse,
3478 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3479 GST_TIME_ARGS (*time), *pos);
3483 parse->priv->offset = orig_offset;
3484 parse->priv->discont = orig_discont;
3485 parse->priv->drain = orig_drain;
3490 /* bisect and scan through file for frame starting before @time,
3491 * returns OK and @time/@offset if found, NONE and/or error otherwise
3492 * If @time == G_MAXINT64, scan for duration ( == last frame) */
3493 static GstFlowReturn
3494 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3497 GstFlowReturn ret = GST_FLOW_OK;
3498 gint64 lpos, hpos, newpos;
3499 GstClockTime time, ltime, htime, newtime, dur;
3500 gboolean cont = TRUE;
3501 const GstClockTime tolerance = TARGET_DIFFERENCE;
3502 const guint chunk = 4 * 1024;
3504 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3505 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3507 /* TODO also make keyframe aware if useful some day */
3522 /* do not know at first */
3524 *_time = GST_CLOCK_TIME_NONE;
3526 /* need initial positions; start and end */
3527 lpos = parse->priv->first_frame_offset;
3528 ltime = parse->priv->first_frame_ts;
3529 htime = parse->priv->duration;
3530 hpos = parse->priv->upstream_size;
3532 /* check preconditions are satisfied;
3533 * start and end are needed, except for special case where we scan for
3534 * last frame to determine duration */
3535 if (parse->priv->pad_mode != GST_PAD_ACTIVATE_PULL || !hpos ||
3536 !GST_CLOCK_TIME_IS_VALID (ltime) ||
3537 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3541 /* shortcut cases */
3544 } else if (time < ltime + tolerance) {
3548 } else if (time >= htime) {
3554 while (htime > ltime && cont) {
3555 GST_LOG_OBJECT (parse,
3556 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3557 GST_TIME_ARGS (ltime));
3558 GST_LOG_OBJECT (parse,
3559 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3560 GST_TIME_ARGS (htime));
3561 if (G_UNLIKELY (time == G_MAXINT64)) {
3563 } else if (G_LIKELY (hpos > lpos)) {
3565 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3568 /* should mean lpos == hpos, since lpos <= hpos is invariant */
3570 /* we check this case once, but not forever, so break loop */
3575 newpos = CLAMP (newpos, lpos, hpos);
3576 GST_LOG_OBJECT (parse,
3577 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3578 GST_TIME_ARGS (time), newpos);
3580 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3581 if (ret == GST_FLOW_EOS) {
3582 /* heuristic HACK */
3583 hpos = MAX (lpos, hpos - chunk);
3585 } else if (ret != GST_FLOW_OK) {
3589 if (newtime == -1 || newpos == -1) {
3590 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3594 if (G_UNLIKELY (time == G_MAXINT64)) {
3597 if (GST_CLOCK_TIME_IS_VALID (dur))
3600 } else if (newtime > time) {
3602 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3604 } else if (newtime + tolerance > time) {
3605 /* close enough undershoot */
3609 } else if (newtime < ltime) {
3610 /* so a position beyond lpos resulted in earlier time than ltime ... */
3611 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3614 /* undershoot too far */
3615 newpos += newpos == lpos ? chunk : 0;
3616 lpos = CLAMP (newpos, lpos, hpos);
3622 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3623 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3628 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3629 gboolean before, GstClockTime * _ts)
3631 gint64 bytes = 0, ts = 0;
3632 GstIndexEntry *entry = NULL;
3634 if (time == GST_CLOCK_TIME_NONE) {
3640 g_static_mutex_lock (&parse->priv->index_lock);
3641 if (parse->priv->index) {
3642 /* Let's check if we have an index entry for that time */
3643 entry = gst_index_get_assoc_entry (parse->priv->index,
3644 parse->priv->index_id,
3645 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3646 GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3650 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3651 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3653 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3654 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3655 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3657 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3658 GST_TIME_ARGS (time));
3661 ts = GST_CLOCK_TIME_NONE;
3664 g_static_mutex_unlock (&parse->priv->index_lock);
3673 /* returns TRUE if seek succeeded */
3675 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3680 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3681 gboolean flush, update, res = TRUE, accurate;
3682 gint64 cur, stop, seekpos, seekstop;
3683 GstSegment seeksegment = { 0, };
3684 GstClockTime start_ts;
3686 gst_event_parse_seek (event, &rate, &format, &flags,
3687 &cur_type, &cur, &stop_type, &stop);
3689 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3690 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3691 GST_TIME_FORMAT, gst_format_get_name (format), rate,
3692 cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3694 /* no negative rates in push mode */
3695 if (rate < 0.0 && parse->priv->pad_mode == GST_PAD_ACTIVATE_PUSH)
3698 if (cur_type != GST_SEEK_TYPE_SET ||
3699 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3702 /* For any format other than TIME, see if upstream handles
3703 * it directly or fail. For TIME, try upstream, but do it ourselves if
3704 * it fails upstream */
3705 if (format != GST_FORMAT_TIME) {
3706 /* default action delegates to upstream */
3710 gst_event_ref (event);
3711 if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3716 /* get flush flag */
3717 flush = flags & GST_SEEK_FLAG_FLUSH;
3719 /* copy segment, we need this because we still need the old
3720 * segment when we close the current segment. */
3721 gst_segment_copy_into (&parse->segment, &seeksegment);
3723 GST_DEBUG_OBJECT (parse, "configuring seek");
3724 gst_segment_do_seek (&seeksegment, rate, format, flags,
3725 cur_type, cur, stop_type, stop, &update);
3727 /* accurate seeking implies seek tables are used to obtain position,
3728 * and the requested segment is maintained exactly, not adjusted any way */
3729 accurate = flags & GST_SEEK_FLAG_ACCURATE;
3731 /* maybe we can be accurate for (almost) free */
3732 gst_base_parse_find_offset (parse, seeksegment.position, TRUE, &start_ts);
3733 if (seeksegment.position <= start_ts + TARGET_DIFFERENCE) {
3734 GST_DEBUG_OBJECT (parse, "accurate seek possible");
3738 GstClockTime startpos = seeksegment.position;
3740 /* accurate requested, so ... seek a bit before target */
3741 if (startpos < parse->priv->lead_in_ts)
3744 startpos -= parse->priv->lead_in_ts;
3745 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3746 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3749 start_ts = seeksegment.position;
3750 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.position,
3751 GST_FORMAT_BYTES, &seekpos))
3752 goto convert_failed;
3753 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3754 GST_FORMAT_BYTES, &seekstop))
3755 goto convert_failed;
3758 GST_DEBUG_OBJECT (parse,
3759 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3761 GST_DEBUG_OBJECT (parse,
3762 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3763 seeksegment.stop, seekstop);
3765 if (parse->priv->pad_mode == GST_PAD_ACTIVATE_PULL) {
3768 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3771 if (parse->srcpad) {
3772 GST_DEBUG_OBJECT (parse, "sending flush start");
3773 gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3774 /* unlock upstream pull_range */
3775 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3778 gst_pad_pause_task (parse->sinkpad);
3781 /* we should now be able to grab the streaming thread because we stopped it
3782 * with the above flush/pause code */
3783 GST_PAD_STREAM_LOCK (parse->sinkpad);
3785 /* save current position */
3786 last_stop = parse->segment.position;
3787 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3790 /* now commit to new position */
3792 /* prepare for streaming again */
3794 GST_DEBUG_OBJECT (parse, "sending flush stop");
3795 gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop (TRUE));
3796 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop (TRUE));
3797 gst_base_parse_clear_queues (parse);
3799 /* keep track of our position */
3800 seeksegment.base = gst_segment_to_running_time (&seeksegment,
3801 seeksegment.format, parse->segment.position);
3804 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3806 /* store the newsegment event so it can be sent from the streaming thread. */
3807 if (parse->priv->pending_segment)
3808 gst_event_unref (parse->priv->pending_segment);
3810 /* This will be sent later in _loop() */
3811 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
3813 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3814 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3815 ", pos = %" GST_TIME_FORMAT, format,
3816 GST_TIME_ARGS (parse->segment.start),
3817 GST_TIME_ARGS (parse->segment.stop),
3818 GST_TIME_ARGS (parse->segment.start));
3820 /* one last chance in pull mode to stay accurate;
3821 * maybe scan and subclass can find where to go */
3824 GstClockTime ts = seeksegment.position;
3826 gst_base_parse_locate_time (parse, &ts, &scanpos);
3830 /* running collected index now consists of several intervals,
3831 * so optimized check no longer possible */
3832 parse->priv->index_last_valid = FALSE;
3833 parse->priv->index_last_offset = 0;
3834 parse->priv->index_last_ts = 0;
3838 /* mark discont if we are going to stream from another position. */
3839 if (seekpos != parse->priv->offset) {
3840 GST_DEBUG_OBJECT (parse,
3841 "mark DISCONT, we did a seek to another position");
3842 parse->priv->offset = seekpos;
3843 parse->priv->last_offset = seekpos;
3844 parse->priv->seen_keyframe = FALSE;
3845 parse->priv->discont = TRUE;
3846 parse->priv->next_ts = start_ts;
3847 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3848 parse->priv->sync_offset = seekpos;
3849 parse->priv->exact_position = accurate;
3852 /* Start streaming thread if paused */
3853 gst_pad_start_task (parse->sinkpad,
3854 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3856 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3861 GstEvent *new_event;
3862 GstBaseParseSeek *seek;
3863 GstSeekFlags flags = (flush ? GST_SEEK_FLAG_FLUSH : GST_SEEK_FLAG_NONE);
3865 /* The only thing we need to do in PUSH-mode is to send the
3866 seek event (in bytes) to upstream. Segment / flush handling happens
3867 in corresponding src event handlers */
3868 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3869 if (seekstop >= 0 && seekstop <= seekpos)
3871 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
3872 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3874 /* store segment info so its precise details can be reconstructed when
3875 * receiving newsegment;
3876 * this matters for all details when accurate seeking,
3877 * is most useful to preserve NONE stop time otherwise */
3878 seek = g_new0 (GstBaseParseSeek, 1);
3879 seek->segment = seeksegment;
3880 seek->accurate = accurate;
3881 seek->offset = seekpos;
3882 seek->start_ts = start_ts;
3883 GST_OBJECT_LOCK (parse);
3884 /* less optimal, but preserves order */
3885 parse->priv->pending_seeks =
3886 g_slist_append (parse->priv->pending_seeks, seek);
3887 GST_OBJECT_UNLOCK (parse);
3889 res = gst_pad_push_event (parse->sinkpad, new_event);
3892 GST_OBJECT_LOCK (parse);
3893 parse->priv->pending_seeks =
3894 g_slist_remove (parse->priv->pending_seeks, seek);
3895 GST_OBJECT_UNLOCK (parse);
3901 /* handled event is ours to free */
3903 gst_event_unref (event);
3909 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
3915 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3921 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3927 /* Checks if bitrates are available from upstream tags so that we don't
3928 * override them later
3931 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
3933 GstTagList *taglist = NULL;
3936 gst_event_parse_tag (event, &taglist);
3938 if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
3939 GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
3940 parse->priv->post_min_bitrate = FALSE;
3942 if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
3943 GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
3944 parse->priv->post_avg_bitrate = FALSE;
3946 if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
3947 GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
3948 parse->priv->post_max_bitrate = FALSE;
3953 gst_base_parse_sink_getcaps (GstPad * pad, GstCaps * filter)
3955 GstBaseParse *parse;
3956 GstBaseParseClass *klass;
3959 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
3960 klass = GST_BASE_PARSE_GET_CLASS (parse);
3961 g_assert (pad == GST_BASE_PARSE_SINK_PAD (parse));
3963 if (klass->get_sink_caps)
3964 caps = klass->get_sink_caps (parse, filter);
3966 caps = gst_pad_proxy_getcaps (pad, filter);
3967 gst_object_unref (parse);
3969 GST_LOG_OBJECT (parse, "sink getcaps returning caps %" GST_PTR_FORMAT, caps);
3976 gst_base_parse_set_index (GstElement * element, GstIndex * index)
3978 GstBaseParse *parse = GST_BASE_PARSE (element);
3980 g_static_mutex_lock (&parse->priv->index_lock);
3981 if (parse->priv->index)
3982 gst_object_unref (parse->priv->index);
3984 parse->priv->index = gst_object_ref (index);
3985 gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
3986 &parse->priv->index_id);
3987 parse->priv->own_index = FALSE;
3989 parse->priv->index = NULL;
3991 g_static_mutex_unlock (&parse->priv->index_lock);
3995 gst_base_parse_get_index (GstElement * element)
3997 GstBaseParse *parse = GST_BASE_PARSE (element);
3998 GstIndex *result = NULL;
4000 g_static_mutex_lock (&parse->priv->index_lock);
4001 if (parse->priv->index)
4002 result = gst_object_ref (parse->priv->index);
4003 g_static_mutex_unlock (&parse->priv->index_lock);
4008 static GstStateChangeReturn
4009 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
4011 GstBaseParse *parse;
4012 GstStateChangeReturn result;
4014 parse = GST_BASE_PARSE (element);
4016 switch (transition) {
4017 case GST_STATE_CHANGE_READY_TO_PAUSED:
4018 /* If this is our own index destroy it as the
4019 * old entries might be wrong for the new stream */
4020 g_static_mutex_lock (&parse->priv->index_lock);
4021 if (parse->priv->own_index) {
4022 gst_object_unref (parse->priv->index);
4023 parse->priv->index = NULL;
4024 parse->priv->own_index = FALSE;
4027 /* If no index was created, generate one */
4028 if (G_UNLIKELY (!parse->priv->index)) {
4029 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
4031 parse->priv->index = gst_index_factory_make ("memindex");
4032 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
4033 &parse->priv->index_id);
4034 parse->priv->own_index = TRUE;
4036 g_static_mutex_unlock (&parse->priv->index_lock);
4042 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4044 switch (transition) {
4045 case GST_STATE_CHANGE_PAUSED_TO_READY:
4046 gst_base_parse_reset (parse);