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 GstActivateMode 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 gboolean gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps);
390 static GstCaps *gst_base_parse_sink_getcaps (GstPad * pad);
391 static const GstQueryType *gst_base_parse_get_querytypes (GstPad * pad);
393 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstBuffer * buffer);
394 static void gst_base_parse_loop (GstPad * pad);
396 static gboolean gst_base_parse_check_frame (GstBaseParse * parse,
397 GstBaseParseFrame * frame, guint * framesize, gint * skipsize);
398 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
399 GstBaseParseFrame * frame);
401 static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
404 static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
407 static void gst_base_parse_drain (GstBaseParse * parse);
409 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
410 gboolean post_min, gboolean post_avg, gboolean post_max);
412 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
413 GstClockTime time, gboolean before, GstClockTime * _ts);
414 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
415 GstClockTime * _time, gint64 * _offset);
417 static GstFlowReturn gst_base_parse_process_fragment (GstBaseParse * parse,
420 static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);
423 gst_base_parse_clear_queues (GstBaseParse * parse)
425 g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
426 g_slist_free (parse->priv->buffers_queued);
427 parse->priv->buffers_queued = NULL;
428 g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
430 g_slist_free (parse->priv->buffers_pending);
431 parse->priv->buffers_pending = NULL;
432 g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
433 g_slist_free (parse->priv->buffers_send);
434 parse->priv->buffers_send = NULL;
436 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
437 g_list_free (parse->priv->detect_buffers);
438 parse->priv->detect_buffers = NULL;
439 parse->priv->detect_buffers_size = 0;
443 gst_base_parse_finalize (GObject * object)
445 GstBaseParse *parse = GST_BASE_PARSE (object);
448 g_object_unref (parse->priv->adapter);
450 if (parse->priv->pending_segment) {
451 p_ev = &parse->priv->pending_segment;
452 gst_event_replace (p_ev, NULL);
454 if (parse->priv->close_segment) {
455 p_ev = &parse->priv->close_segment;
456 gst_event_replace (p_ev, NULL);
459 if (parse->priv->cache) {
460 gst_buffer_unref (parse->priv->cache);
461 parse->priv->cache = NULL;
464 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
466 g_list_free (parse->priv->pending_events);
467 parse->priv->pending_events = NULL;
469 g_queue_foreach (&parse->priv->queued_frames,
470 (GFunc) gst_base_parse_frame_free, NULL);
471 g_queue_clear (&parse->priv->queued_frames);
473 if (parse->priv->index) {
474 gst_object_unref (parse->priv->index);
475 parse->priv->index = NULL;
478 g_static_mutex_free (&parse->priv->index_lock);
480 gst_base_parse_clear_queues (parse);
482 G_OBJECT_CLASS (parent_class)->finalize (object);
486 gst_base_parse_class_init (GstBaseParseClass * klass)
488 GObjectClass *gobject_class;
489 GstElementClass *gstelement_class;
491 gobject_class = G_OBJECT_CLASS (klass);
492 g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
493 parent_class = g_type_class_peek_parent (klass);
494 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
496 gstelement_class = (GstElementClass *) klass;
497 gstelement_class->change_state =
498 GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
499 gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
500 gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
502 /* Default handlers */
503 klass->check_valid_frame = gst_base_parse_check_frame;
504 klass->parse_frame = gst_base_parse_parse_frame;
505 klass->src_event = gst_base_parse_src_eventfunc;
506 klass->convert = gst_base_parse_convert_default;
508 GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
509 "baseparse element");
513 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
515 GstPadTemplate *pad_template;
517 GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
519 parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
522 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
523 g_return_if_fail (pad_template != NULL);
524 parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
525 gst_pad_set_event_function (parse->sinkpad,
526 GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
527 gst_pad_set_setcaps_function (parse->sinkpad,
528 GST_DEBUG_FUNCPTR (gst_base_parse_sink_setcaps));
529 gst_pad_set_getcaps_function (parse->sinkpad,
530 GST_DEBUG_FUNCPTR (gst_base_parse_sink_getcaps));
531 gst_pad_set_chain_function (parse->sinkpad,
532 GST_DEBUG_FUNCPTR (gst_base_parse_chain));
533 gst_pad_set_activate_function (parse->sinkpad,
534 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
535 gst_pad_set_activatepush_function (parse->sinkpad,
536 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_push));
537 gst_pad_set_activatepull_function (parse->sinkpad,
538 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_pull));
539 gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
541 GST_DEBUG_OBJECT (parse, "sinkpad created");
544 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
545 g_return_if_fail (pad_template != NULL);
546 parse->srcpad = gst_pad_new_from_template (pad_template, "src");
547 gst_pad_set_event_function (parse->srcpad,
548 GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
549 gst_pad_set_query_type_function (parse->srcpad,
550 GST_DEBUG_FUNCPTR (gst_base_parse_get_querytypes));
551 gst_pad_set_query_function (parse->srcpad,
552 GST_DEBUG_FUNCPTR (gst_base_parse_query));
553 gst_pad_use_fixed_caps (parse->srcpad);
554 gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
555 GST_DEBUG_OBJECT (parse, "src created");
557 g_queue_init (&parse->priv->queued_frames);
559 parse->priv->adapter = gst_adapter_new ();
561 parse->priv->pad_mode = GST_ACTIVATE_NONE;
563 g_static_mutex_init (&parse->priv->index_lock);
566 gst_base_parse_reset (parse);
567 GST_DEBUG_OBJECT (parse, "init ok");
570 static GstBaseParseFrame *
571 gst_base_parse_frame_copy (GstBaseParseFrame * frame)
573 GstBaseParseFrame *copy;
575 copy = g_slice_dup (GstBaseParseFrame, frame);
576 copy->buffer = gst_buffer_ref (frame->buffer);
577 copy->_private_flags &= ~GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
579 GST_TRACE ("copied frame %p -> %p", frame, copy);
585 gst_base_parse_frame_free (GstBaseParseFrame * frame)
587 GST_TRACE ("freeing frame %p", frame);
590 gst_buffer_unref (frame->buffer);
591 frame->buffer = NULL;
594 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
595 g_slice_free (GstBaseParseFrame, frame);
597 memset (frame, 0, sizeof (*frame));
602 gst_base_parse_frame_get_type (void)
604 static volatile gsize frame_type = 0;
606 if (g_once_init_enter (&frame_type)) {
609 _type = g_boxed_type_register_static ("GstBaseParseFrame",
610 (GBoxedCopyFunc) gst_base_parse_frame_copy,
611 (GBoxedFreeFunc) gst_base_parse_frame_free);
612 g_once_init_leave (&frame_type, _type);
614 return (GType) frame_type;
618 * gst_base_parse_frame_init:
619 * @frame: #GstBaseParseFrame.
621 * Sets a #GstBaseParseFrame to initial state. Currently this means
622 * all public fields are zero-ed and a private flag is set to make
623 * sure gst_base_parse_frame_free() only frees the contents but not
624 * the actual frame. Use this function to initialise a #GstBaseParseFrame
625 * allocated on the stack.
630 gst_base_parse_frame_init (GstBaseParseFrame * frame)
632 memset (frame, 0, sizeof (GstBaseParseFrame));
633 frame->_private_flags = GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
634 GST_TRACE ("inited frame %p", frame);
638 * gst_base_parse_frame_new:
639 * @buffer: (transfer none): a #GstBuffer
641 * @overhead: number of bytes in this frame which should be counted as
642 * metadata overhead, ie. not used to calculate the average bitrate.
643 * Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
645 * Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
646 * elements written in C should usually allocate the frame on the stack and
647 * then use gst_base_parse_frame_init() to initialise it.
649 * Returns: a newly-allocated #GstBaseParseFrame. Free with
650 * gst_base_parse_frame_free() when no longer needed, unless you gave
651 * away ownership to gst_base_parse_push_frame().
656 gst_base_parse_frame_new (GstBuffer * buffer, GstBaseParseFrameFlags flags,
659 GstBaseParseFrame *frame;
661 frame = g_slice_new0 (GstBaseParseFrame);
662 frame->buffer = gst_buffer_ref (buffer);
664 GST_TRACE ("created frame %p", frame);
669 gst_base_parse_frame_update (GstBaseParse * parse, GstBaseParseFrame * frame,
672 gst_buffer_replace (&frame->buffer, buf);
676 /* set flags one by one for clarity */
677 if (G_UNLIKELY (parse->priv->drain))
678 parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;
680 /* losing sync is pretty much a discont (and vice versa), no ? */
681 if (G_UNLIKELY (parse->priv->discont))
682 parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
686 gst_base_parse_reset (GstBaseParse * parse)
688 GST_OBJECT_LOCK (parse);
689 gst_segment_init (&parse->segment, GST_FORMAT_TIME);
690 parse->priv->duration = -1;
691 parse->priv->min_frame_size = 1;
692 parse->priv->discont = TRUE;
693 parse->priv->flushing = FALSE;
694 parse->priv->offset = 0;
695 parse->priv->sync_offset = 0;
696 parse->priv->update_interval = -1;
697 parse->priv->fps_num = parse->priv->fps_den = 0;
698 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
699 parse->priv->lead_in = parse->priv->lead_out = 0;
700 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
701 parse->priv->bitrate = 0;
702 parse->priv->framecount = 0;
703 parse->priv->bytecount = 0;
704 parse->priv->acc_duration = 0;
705 parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
706 parse->priv->first_frame_offset = -1;
707 parse->priv->estimated_duration = -1;
708 parse->priv->estimated_drift = 0;
709 parse->priv->next_ts = 0;
710 parse->priv->syncable = TRUE;
711 parse->priv->passthrough = FALSE;
712 parse->priv->has_timing_info = FALSE;
713 parse->priv->post_min_bitrate = TRUE;
714 parse->priv->post_avg_bitrate = TRUE;
715 parse->priv->post_max_bitrate = TRUE;
716 parse->priv->min_bitrate = G_MAXUINT;
717 parse->priv->max_bitrate = 0;
718 parse->priv->avg_bitrate = 0;
719 parse->priv->posted_avg_bitrate = 0;
721 parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
722 parse->priv->index_last_offset = -1;
723 parse->priv->index_last_valid = TRUE;
724 parse->priv->upstream_seekable = FALSE;
725 parse->priv->upstream_size = 0;
726 parse->priv->upstream_has_duration = FALSE;
727 parse->priv->idx_interval = 0;
728 parse->priv->exact_position = TRUE;
729 parse->priv->seen_keyframe = FALSE;
731 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
732 parse->priv->last_offset = 0;
734 if (parse->priv->pending_segment) {
735 gst_event_unref (parse->priv->pending_segment);
736 parse->priv->pending_segment = NULL;
739 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
741 g_list_free (parse->priv->pending_events);
742 parse->priv->pending_events = NULL;
744 if (parse->priv->cache) {
745 gst_buffer_unref (parse->priv->cache);
746 parse->priv->cache = NULL;
749 g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
750 g_slist_free (parse->priv->pending_seeks);
751 parse->priv->pending_seeks = NULL;
753 /* we know it is not alloc'ed, but maybe other stuff to free, some day ... */
754 parse->priv->frame._private_flags |=
755 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
756 gst_base_parse_frame_free (&parse->priv->frame);
758 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
759 g_list_free (parse->priv->detect_buffers);
760 parse->priv->detect_buffers = NULL;
761 parse->priv->detect_buffers_size = 0;
762 GST_OBJECT_UNLOCK (parse);
765 /* gst_base_parse_check_frame:
766 * @parse: #GstBaseParse.
767 * @buffer: GstBuffer.
768 * @framesize: This will be set to tell the found frame size in bytes.
769 * @skipsize: Output parameter that tells how much data needs to be skipped
770 * in order to find the following frame header.
772 * Default callback for check_valid_frame.
774 * Returns: Always TRUE.
777 gst_base_parse_check_frame (GstBaseParse * parse,
778 GstBaseParseFrame * frame, guint * framesize, gint * skipsize)
780 *framesize = GST_BUFFER_SIZE (frame->buffer);
786 /* gst_base_parse_parse_frame:
787 * @parse: #GstBaseParse.
788 * @buffer: #GstBuffer.
790 * Default callback for parse_frame.
793 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
795 GstBuffer *buffer = frame->buffer;
797 if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
798 GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
799 GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
801 if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
802 GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
803 GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
808 /* gst_base_parse_convert:
809 * @parse: #GstBaseParse.
810 * @src_format: #GstFormat describing the source format.
811 * @src_value: Source value to be converted.
812 * @dest_format: #GstFormat defining the converted format.
813 * @dest_value: Pointer where the conversion result will be put.
815 * Converts using configured "convert" vmethod in #GstBaseParse class.
817 * Returns: TRUE if conversion was successful.
820 gst_base_parse_convert (GstBaseParse * parse,
821 GstFormat src_format,
822 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
824 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
827 g_return_val_if_fail (dest_value != NULL, FALSE);
832 ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
834 #ifndef GST_DISABLE_GST_DEBUG
837 if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
838 GST_LOG_OBJECT (parse,
839 "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
840 GST_TIME_ARGS (src_value), *dest_value);
841 } else if (dest_format == GST_FORMAT_TIME &&
842 src_format == GST_FORMAT_BYTES) {
843 GST_LOG_OBJECT (parse,
844 "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
845 src_value, GST_TIME_ARGS (*dest_value));
847 GST_LOG_OBJECT (parse,
848 "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
849 GST_STR_NULL (gst_format_get_name (src_format)),
850 GST_STR_NULL (gst_format_get_name (dest_format)),
851 src_value, *dest_value);
854 GST_DEBUG_OBJECT (parse, "conversion failed");
862 /* gst_base_parse_sink_event:
863 * @pad: #GstPad that received the event.
864 * @event: #GstEvent to be handled.
866 * Handler for sink pad events.
868 * Returns: TRUE if the event was handled.
871 gst_base_parse_sink_event (GstPad * pad, GstEvent * event)
874 GstBaseParseClass *bclass;
875 gboolean handled = FALSE;
878 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
879 bclass = GST_BASE_PARSE_GET_CLASS (parse);
881 GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
882 GST_EVENT_TYPE_NAME (event));
884 /* Cache all events except EOS, NEWSEGMENT and FLUSH_STOP if we have a
886 if (parse->priv->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
887 && GST_EVENT_TYPE (event) != GST_EVENT_NEWSEGMENT
888 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
889 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP) {
891 if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
892 /* See if any bitrate tags were posted */
893 gst_base_parse_handle_tag (parse, event);
895 parse->priv->pending_events =
896 g_list_append (parse->priv->pending_events, event);
900 if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
901 parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
902 /* We've not posted bitrate tags yet - do so now */
903 gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
906 handled = bclass->event (parse, event);
909 handled = gst_base_parse_sink_eventfunc (parse, event);
912 ret = gst_pad_event_default (pad, event);
915 gst_object_unref (parse);
916 GST_DEBUG_OBJECT (parse, "event handled");
921 /* gst_base_parse_sink_eventfunc:
922 * @parse: #GstBaseParse.
923 * @event: #GstEvent to be handled.
925 * Element-level event handler function.
927 * The event will be unreffed only if it has been handled and this
928 * function returns %TRUE
930 * Returns: %TRUE if the event was handled and not need forwarding.
933 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
935 gboolean handled = FALSE;
938 switch (GST_EVENT_TYPE (event)) {
939 case GST_EVENT_NEWSEGMENT:
941 gdouble rate, applied_rate;
943 gint64 start, stop, pos, next_ts, offset = 0;
946 gst_event_parse_new_segment_full (event, &update, &rate, &applied_rate,
947 &format, &start, &stop, &pos);
949 GST_DEBUG_OBJECT (parse, "newseg rate %g, applied rate %g, "
950 "format %d, start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
951 ", pos = %" GST_TIME_FORMAT, rate, applied_rate, format,
952 GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (pos));
954 if (format == GST_FORMAT_BYTES) {
955 GstClockTime seg_start, seg_stop;
956 GstBaseParseSeek *seek = NULL;
959 /* stop time is allowed to be open-ended, but not start & pos */
960 seg_stop = GST_CLOCK_TIME_NONE;
964 GST_OBJECT_LOCK (parse);
965 for (node = parse->priv->pending_seeks; node; node = node->next) {
966 GstBaseParseSeek *tmp = node->data;
968 if (tmp->offset == pos) {
973 parse->priv->pending_seeks =
974 g_slist_remove (parse->priv->pending_seeks, seek);
975 GST_OBJECT_UNLOCK (parse);
978 GST_DEBUG_OBJECT (parse,
979 "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
980 seek->accurate ? " accurate" : "", &seek->segment);
981 seg_start = seek->segment.start;
982 seg_stop = seek->segment.stop;
983 next_ts = seek->start_ts;
984 parse->priv->exact_position = seek->accurate;
987 /* best attempt convert */
988 /* as these are only estimates, stop is kept open-ended to avoid
989 * premature cutting */
990 gst_base_parse_convert (parse, GST_FORMAT_BYTES, start,
991 GST_FORMAT_TIME, (gint64 *) & seg_start);
992 parse->priv->exact_position = (start == 0);
996 gst_event_unref (event);
997 event = gst_event_new_new_segment_full (update, rate, applied_rate,
998 GST_FORMAT_TIME, seg_start, seg_stop, seg_start);
999 format = GST_FORMAT_TIME;
1002 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. "
1003 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT,
1004 GST_TIME_ARGS (seg_start), GST_TIME_ARGS (seg_stop));
1005 } else if (format != GST_FORMAT_TIME) {
1006 /* Unknown incoming segment format. Output a default open-ended
1008 gst_event_unref (event);
1009 event = gst_event_new_new_segment_full (update, rate, applied_rate,
1010 GST_FORMAT_TIME, 0, GST_CLOCK_TIME_NONE, 0);
1011 format = GST_FORMAT_TIME;
1012 next_ts = start = 0;
1013 stop = GST_CLOCK_TIME_NONE;
1015 /* not considered BYTE seekable if it is talking to us in TIME,
1016 * whatever else it might claim */
1017 parse->priv->upstream_seekable = FALSE;
1021 gst_segment_set_newsegment_full (&parse->segment, update, rate,
1022 applied_rate, format, start, stop, start);
1024 /* save the segment for later, right before we push a new buffer so that
1025 * the caps are fixed and the next linked element can receive
1027 eventp = &parse->priv->pending_segment;
1028 gst_event_replace (eventp, event);
1029 gst_event_unref (event);
1032 /* but finish the current segment */
1033 GST_DEBUG_OBJECT (parse, "draining current segment");
1034 if (parse->segment.rate > 0.0)
1035 gst_base_parse_drain (parse);
1037 gst_base_parse_process_fragment (parse, FALSE);
1038 gst_adapter_clear (parse->priv->adapter);
1039 parse->priv->offset = offset;
1040 parse->priv->sync_offset = offset;
1041 parse->priv->next_ts = next_ts;
1042 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1043 parse->priv->discont = TRUE;
1044 parse->priv->seen_keyframe = FALSE;
1048 case GST_EVENT_FLUSH_START:
1049 parse->priv->flushing = TRUE;
1050 handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
1052 gst_event_unref (event);
1053 /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
1054 GST_PAD_STREAM_LOCK (parse->srcpad);
1055 GST_PAD_STREAM_UNLOCK (parse->srcpad);
1059 case GST_EVENT_FLUSH_STOP:
1060 gst_adapter_clear (parse->priv->adapter);
1061 gst_base_parse_clear_queues (parse);
1062 parse->priv->flushing = FALSE;
1063 parse->priv->discont = TRUE;
1064 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1065 parse->priv->frame._private_flags |=
1066 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
1067 gst_base_parse_frame_free (&parse->priv->frame);
1071 if (parse->segment.rate > 0.0)
1072 gst_base_parse_drain (parse);
1074 gst_base_parse_process_fragment (parse, FALSE);
1076 /* If we STILL have zero frames processed, fire an error */
1077 if (parse->priv->framecount == 0) {
1078 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1079 ("No valid frames found before end of stream"), (NULL));
1081 /* newsegment before eos */
1082 if (parse->priv->pending_segment) {
1083 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1084 parse->priv->pending_segment = NULL;
1096 /* gst_base_parse_src_event:
1097 * @pad: #GstPad that received the event.
1098 * @event: #GstEvent that was received.
1100 * Handler for source pad events.
1102 * Returns: TRUE if the event was handled.
1105 gst_base_parse_src_event (GstPad * pad, GstEvent * event)
1107 GstBaseParse *parse;
1108 GstBaseParseClass *bclass;
1109 gboolean handled = FALSE;
1110 gboolean ret = TRUE;
1112 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
1113 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1115 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1116 GST_EVENT_TYPE_NAME (event));
1118 if (bclass->src_event)
1119 handled = bclass->src_event (parse, event);
1122 ret = gst_pad_event_default (pad, event);
1124 gst_object_unref (parse);
1129 gst_base_parse_is_seekable (GstBaseParse * parse)
1131 /* FIXME: could do more here, e.g. check index or just send data from 0
1132 * in pull mode and let decoder/sink clip */
1133 return parse->priv->syncable;
1136 /* gst_base_parse_src_eventfunc:
1137 * @parse: #GstBaseParse.
1138 * @event: #GstEvent that was received.
1140 * Default srcpad event handler.
1142 * Returns: TRUE if the event was handled and can be dropped.
1145 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1147 gboolean handled = FALSE;
1149 switch (GST_EVENT_TYPE (event)) {
1150 case GST_EVENT_SEEK:
1152 if (gst_base_parse_is_seekable (parse)) {
1153 handled = gst_base_parse_handle_seek (parse, event);
1165 * gst_base_parse_convert_default:
1166 * @parse: #GstBaseParse.
1167 * @src_format: #GstFormat describing the source format.
1168 * @src_value: Source value to be converted.
1169 * @dest_format: #GstFormat defining the converted format.
1170 * @dest_value: Pointer where the conversion result will be put.
1172 * Default implementation of "convert" vmethod in #GstBaseParse class.
1174 * Returns: TRUE if conversion was successful.
1179 gst_base_parse_convert_default (GstBaseParse * parse,
1180 GstFormat src_format,
1181 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1183 gboolean ret = FALSE;
1184 guint64 bytes, duration;
1186 if (G_UNLIKELY (src_format == dest_format)) {
1187 *dest_value = src_value;
1191 if (G_UNLIKELY (src_value == -1)) {
1196 if (G_UNLIKELY (src_value == 0)) {
1201 /* need at least some frames */
1202 if (!parse->priv->framecount)
1205 duration = parse->priv->acc_duration / GST_MSECOND;
1206 bytes = parse->priv->bytecount;
1208 if (G_UNLIKELY (!duration || !bytes))
1211 if (src_format == GST_FORMAT_BYTES) {
1212 if (dest_format == GST_FORMAT_TIME) {
1213 /* BYTES -> TIME conversion */
1214 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1215 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1216 *dest_value *= GST_MSECOND;
1217 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1218 *dest_value / GST_MSECOND);
1221 } else if (src_format == GST_FORMAT_TIME) {
1222 if (dest_format == GST_FORMAT_BYTES) {
1223 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1224 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1226 GST_DEBUG_OBJECT (parse,
1227 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1228 src_value / GST_MSECOND, *dest_value);
1231 } else if (src_format == GST_FORMAT_DEFAULT) {
1232 /* DEFAULT == frame-based */
1233 if (dest_format == GST_FORMAT_TIME) {
1234 if (parse->priv->fps_den) {
1235 *dest_value = gst_util_uint64_scale (src_value,
1236 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1239 } else if (dest_format == GST_FORMAT_BYTES) {
1247 gst_base_parse_update_duration (GstBaseParse * baseparse)
1250 GstBaseParse *parse;
1252 parse = GST_BASE_PARSE (baseparse);
1254 peer = gst_pad_get_peer (parse->sinkpad);
1256 GstFormat pformat = GST_FORMAT_BYTES;
1257 gboolean qres = FALSE;
1258 gint64 ptot, dest_value;
1260 qres = gst_pad_query_duration (peer, &pformat, &ptot);
1261 gst_object_unref (GST_OBJECT (peer));
1263 if (gst_base_parse_convert (parse, pformat, ptot,
1264 GST_FORMAT_TIME, &dest_value)) {
1266 /* inform if duration changed, but try to avoid spamming */
1267 parse->priv->estimated_drift +=
1268 dest_value - parse->priv->estimated_duration;
1269 if (parse->priv->estimated_drift > GST_SECOND ||
1270 parse->priv->estimated_drift < -GST_SECOND) {
1271 gst_element_post_message (GST_ELEMENT (parse),
1272 gst_message_new_duration (GST_OBJECT (parse),
1273 GST_FORMAT_TIME, dest_value));
1274 parse->priv->estimated_drift = 0;
1276 parse->priv->estimated_duration = dest_value;
1277 GST_LOG_OBJECT (parse,
1278 "updated estimated duration to %" GST_TIME_FORMAT,
1279 GST_TIME_ARGS (dest_value));
1286 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1287 gboolean post_avg, gboolean post_max)
1289 GstTagList *taglist = NULL;
1291 if (post_min && parse->priv->post_min_bitrate) {
1292 taglist = gst_tag_list_new ();
1294 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1295 GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1298 if (post_avg && parse->priv->post_avg_bitrate) {
1299 if (taglist == NULL)
1300 taglist = gst_tag_list_new ();
1302 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1303 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1304 parse->priv->avg_bitrate, NULL);
1307 if (post_max && parse->priv->post_max_bitrate) {
1308 if (taglist == NULL)
1309 taglist = gst_tag_list_new ();
1311 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1312 GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1315 GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1316 parse->priv->min_bitrate, parse->priv->avg_bitrate,
1317 parse->priv->max_bitrate);
1319 if (taglist != NULL) {
1320 gst_element_found_tags_for_pad (GST_ELEMENT_CAST (parse), parse->srcpad,
1325 /* gst_base_parse_update_bitrates:
1326 * @parse: #GstBaseParse.
1327 * @buffer: Current frame as a #GstBuffer
1329 * Keeps track of the minimum and maximum bitrates, and also maintains a
1330 * running average bitrate of the stream so far.
1333 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1335 /* Only update the tag on a 10 kbps delta */
1336 static const gint update_threshold = 10000;
1338 guint64 data_len, frame_dur;
1339 gint overhead, frame_bitrate, old_avg_bitrate;
1340 gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1341 GstBuffer *buffer = frame->buffer;
1343 overhead = frame->overhead;
1347 data_len = GST_BUFFER_SIZE (buffer) - overhead;
1348 parse->priv->data_bytecount += data_len;
1350 /* duration should be valid by now,
1351 * either set by subclass or maybe based on fps settings */
1352 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1353 /* Calculate duration of a frame from buffer properties */
1354 frame_dur = GST_BUFFER_DURATION (buffer);
1355 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1356 parse->priv->acc_duration;
1359 /* No way to figure out frame duration (is this even possible?) */
1363 /* override if subclass provided bitrate, e.g. metadata based */
1364 if (parse->priv->bitrate) {
1365 parse->priv->avg_bitrate = parse->priv->bitrate;
1366 /* spread this (confirmed) info ASAP */
1367 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1368 gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1372 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1376 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1377 parse->priv->avg_bitrate);
1379 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1381 } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1382 /* always post all at threshold time */
1383 update_min = update_max = update_avg = TRUE;
1386 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1387 if (frame_bitrate < parse->priv->min_bitrate) {
1388 parse->priv->min_bitrate = frame_bitrate;
1392 if (frame_bitrate > parse->priv->max_bitrate) {
1393 parse->priv->max_bitrate = frame_bitrate;
1397 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1398 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1399 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1404 if ((update_min || update_avg || update_max))
1405 gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1407 /* If average bitrate changes that much and no valid (time) duration provided,
1408 * then post a new duration message so applications can update their cached
1410 if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1411 GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1412 gst_element_post_message (GST_ELEMENT (parse),
1413 gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1420 * gst_base_parse_add_index_entry:
1421 * @parse: #GstBaseParse.
1422 * @offset: offset of entry
1423 * @ts: timestamp associated with offset
1424 * @key: whether entry refers to keyframe
1425 * @force: add entry disregarding sanity checks
1427 * Adds an entry to the index associating @offset to @ts. It is recommended
1428 * to only add keyframe entries. @force allows to bypass checks, such as
1429 * whether the stream is (upstream) seekable, another entry is already "close"
1430 * to the new entry, etc.
1432 * Returns: #gboolean indicating whether entry was added
1437 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1438 GstClockTime ts, gboolean key, gboolean force)
1440 gboolean ret = FALSE;
1441 GstIndexAssociation associations[2];
1443 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1444 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1446 if (G_LIKELY (!force)) {
1448 if (!parse->priv->upstream_seekable) {
1449 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1453 /* FIXME need better helper data structure that handles these issues
1454 * related to ongoing collecting of index entries */
1455 if (parse->priv->index_last_offset >= (gint64) offset) {
1456 GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1457 "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1461 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1462 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1463 parse->priv->idx_interval) {
1464 GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1465 GST_TIME_ARGS (parse->priv->index_last_ts));
1469 /* if last is not really the last one */
1470 if (!parse->priv->index_last_valid) {
1471 GstClockTime prev_ts;
1473 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1474 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1475 GST_DEBUG_OBJECT (parse,
1476 "entry too close to existing entry %" GST_TIME_FORMAT,
1477 GST_TIME_ARGS (prev_ts));
1478 parse->priv->index_last_offset = offset;
1479 parse->priv->index_last_ts = ts;
1485 associations[0].format = GST_FORMAT_TIME;
1486 associations[0].value = ts;
1487 associations[1].format = GST_FORMAT_BYTES;
1488 associations[1].value = offset;
1490 /* index might change on-the-fly, although that would be nutty app ... */
1491 g_static_mutex_lock (&parse->priv->index_lock);
1492 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1493 (key) ? GST_ASSOCIATION_FLAG_KEY_UNIT : GST_ASSOCIATION_FLAG_DELTA_UNIT,
1494 2, (const GstIndexAssociation *) &associations);
1495 g_static_mutex_unlock (&parse->priv->index_lock);
1498 parse->priv->index_last_offset = offset;
1499 parse->priv->index_last_ts = ts;
1508 /* check for seekable upstream, above and beyond a mere query */
1510 gst_base_parse_check_seekability (GstBaseParse * parse)
1513 gboolean seekable = FALSE;
1514 gint64 start = -1, stop = -1;
1515 guint idx_interval = 0;
1517 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1518 if (!gst_pad_peer_query (parse->sinkpad, query)) {
1519 GST_DEBUG_OBJECT (parse, "seeking query failed");
1523 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1525 /* try harder to query upstream size if we didn't get it the first time */
1526 if (seekable && stop == -1) {
1527 GstFormat fmt = GST_FORMAT_BYTES;
1529 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1530 gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop);
1533 /* if upstream doesn't know the size, it's likely that it's not seekable in
1534 * practice even if it technically may be seekable */
1535 if (seekable && (start != 0 || stop <= start)) {
1536 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1540 /* let's not put every single frame into our index */
1542 if (stop < 10 * 1024 * 1024)
1544 else if (stop < 100 * 1024 * 1024)
1547 idx_interval = 1000;
1551 gst_query_unref (query);
1553 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1554 G_GUINT64_FORMAT ")", seekable, start, stop);
1555 parse->priv->upstream_seekable = seekable;
1556 parse->priv->upstream_size = seekable ? stop : 0;
1558 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1559 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1562 /* some misc checks on upstream */
1564 gst_base_parse_check_upstream (GstBaseParse * parse)
1566 GstFormat fmt = GST_FORMAT_TIME;
1569 if (gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop))
1570 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1571 /* upstream has one, accept it also, and no further updates */
1572 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1573 parse->priv->upstream_has_duration = TRUE;
1576 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1577 parse->priv->upstream_has_duration);
1580 /* checks src caps to determine if dealing with audio or video */
1581 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1583 gst_base_parse_check_media (GstBaseParse * parse)
1588 caps = GST_PAD_CAPS (parse->srcpad);
1589 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1590 parse->priv->is_video =
1591 g_str_has_prefix (gst_structure_get_name (s), "video");
1593 /* historical default */
1594 parse->priv->is_video = FALSE;
1597 GST_DEBUG_OBJECT (parse, "media is video: %d", parse->priv->is_video);
1600 /* takes ownership of frame */
1602 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1604 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1605 /* frame allocated on the heap, we can just take ownership */
1606 g_queue_push_tail (&parse->priv->queued_frames, frame);
1607 GST_TRACE ("queued frame %p", frame);
1609 GstBaseParseFrame *copy;
1611 /* probably allocated on the stack, must make a proper copy */
1612 copy = gst_base_parse_frame_copy (frame);
1613 g_queue_push_tail (&parse->priv->queued_frames, copy);
1614 GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1615 gst_base_parse_frame_free (frame);
1619 /* gst_base_parse_handle_and_push_buffer:
1620 * @parse: #GstBaseParse.
1621 * @klass: #GstBaseParseClass.
1622 * @frame: (transfer full): a #GstBaseParseFrame
1624 * Parses the frame from given buffer and pushes it forward. Also performs
1625 * timestamp handling and checks the segment limits.
1627 * This is called with srcpad STREAM_LOCK held.
1629 * Returns: #GstFlowReturn
1631 static GstFlowReturn
1632 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1633 GstBaseParseClass * klass, GstBaseParseFrame * frame)
1639 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1641 buffer = frame->buffer;
1643 if (parse->priv->discont) {
1644 GST_DEBUG_OBJECT (parse, "marking DISCONT");
1645 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1646 parse->priv->discont = FALSE;
1649 /* some one-time start-up */
1650 if (G_UNLIKELY (!parse->priv->framecount)) {
1651 gst_base_parse_check_seekability (parse);
1652 gst_base_parse_check_upstream (parse);
1655 GST_LOG_OBJECT (parse,
1656 "parsing frame at offset %" G_GUINT64_FORMAT
1657 " (%#" G_GINT64_MODIFIER "x) of size %d",
1658 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1659 GST_BUFFER_SIZE (buffer));
1661 /* use default handler to provide initial (upstream) metadata */
1662 gst_base_parse_parse_frame (parse, frame);
1664 /* store offset as it might get overwritten */
1665 offset = GST_BUFFER_OFFSET (buffer);
1666 ret = klass->parse_frame (parse, frame);
1668 buffer = frame->buffer;
1669 /* subclass must play nice */
1670 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1672 /* check if subclass/format can provide ts.
1673 * If so, that allows and enables extra seek and duration determining options */
1674 if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
1675 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && parse->priv->has_timing_info
1676 && parse->priv->pad_mode == GST_ACTIVATE_PULL) {
1677 parse->priv->first_frame_offset = offset;
1678 parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1679 GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1680 " for first frame at offset %" G_GINT64_FORMAT,
1681 GST_TIME_ARGS (parse->priv->first_frame_ts),
1682 parse->priv->first_frame_offset);
1683 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1685 GstClockTime last_ts = G_MAXINT64;
1687 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1688 gst_base_parse_locate_time (parse, &last_ts, &off);
1689 if (GST_CLOCK_TIME_IS_VALID (last_ts))
1690 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1693 /* disable further checks */
1694 parse->priv->first_frame_offset = 0;
1698 /* again use default handler to add missing metadata;
1699 * we may have new information on frame properties */
1700 gst_base_parse_parse_frame (parse, frame);
1701 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1702 GST_BUFFER_DURATION_IS_VALID (buffer)) {
1703 parse->priv->next_ts =
1704 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1706 /* we lost track, do not produce bogus time next time around
1707 * (probably means parser subclass has given up on parsing as well) */
1708 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1709 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1712 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1713 GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1714 gst_base_parse_add_index_entry (parse, offset,
1715 GST_BUFFER_TIMESTAMP (buffer),
1716 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1718 /* First buffers are dropped, this means that the subclass needs more
1719 * frames to decide on the format and queues them internally */
1720 /* convert internal flow to OK and mark discont for the next buffer. */
1721 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1722 gst_base_parse_frame_free (frame);
1724 } else if (ret == GST_BASE_PARSE_FLOW_QUEUED) {
1725 gst_base_parse_queue_frame (parse, frame);
1727 } else if (ret != GST_FLOW_OK) {
1731 /* All OK, push queued frames if there are any */
1732 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
1733 GstBaseParseFrame *queued_frame;
1735 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
1736 queued_frame->buffer =
1737 gst_buffer_make_metadata_writable (queued_frame->buffer);
1738 gst_buffer_set_caps (queued_frame->buffer,
1739 GST_PAD_CAPS (GST_BASE_PARSE_SRC_PAD (parse)));
1740 gst_base_parse_push_frame (parse, queued_frame);
1744 return gst_base_parse_push_frame (parse, frame);
1748 * gst_base_parse_push_frame:
1749 * @parse: #GstBaseParse.
1750 * @frame: (transfer full): a #GstBaseParseFrame
1752 * Pushes the frame downstream, sends any pending events and
1753 * does some timestamp and segment handling. Takes ownership
1754 * of @frame and will clear it (if it was initialised with
1755 * gst_base_parse_frame_init()) or free it.
1757 * This must be called with sinkpad STREAM_LOCK held.
1759 * Returns: #GstFlowReturn
1764 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1766 GstFlowReturn ret = GST_FLOW_OK;
1767 GstClockTime last_start = GST_CLOCK_TIME_NONE;
1768 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1769 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1772 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1773 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
1775 GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
1777 buffer = frame->buffer;
1779 GST_LOG_OBJECT (parse,
1780 "processing buffer of size %d with ts %" GST_TIME_FORMAT
1781 ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
1782 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1783 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1786 parse->priv->bytecount += GST_BUFFER_SIZE (buffer);
1787 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1788 parse->priv->framecount++;
1789 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1790 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1793 /* 0 means disabled */
1794 if (parse->priv->update_interval < 0)
1795 parse->priv->update_interval = 50;
1796 else if (parse->priv->update_interval > 0 &&
1797 (parse->priv->framecount % parse->priv->update_interval) == 0)
1798 gst_base_parse_update_duration (parse);
1800 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1801 last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1802 if (last_start != GST_CLOCK_TIME_NONE
1803 && GST_BUFFER_DURATION_IS_VALID (buffer))
1804 last_stop = last_start + GST_BUFFER_DURATION (buffer);
1806 /* should have caps by now */
1807 g_return_val_if_fail (GST_PAD_CAPS (parse->srcpad), GST_FLOW_ERROR);
1809 /* segment adjustment magic; only if we are running the whole show */
1810 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1811 (parse->priv->pad_mode == GST_ACTIVATE_PULL ||
1812 parse->priv->upstream_seekable)) {
1813 /* segment times are typically estimates,
1814 * actual frame data might lead subclass to different timestamps,
1815 * so override segment start from what is supplied there */
1816 if (G_UNLIKELY (parse->priv->pending_segment && !parse->priv->exact_position
1817 && GST_CLOCK_TIME_IS_VALID (last_start))) {
1818 gst_event_unref (parse->priv->pending_segment);
1819 parse->segment.start =
1820 MIN ((guint64) last_start, (guint64) parse->segment.stop);
1821 GST_DEBUG_OBJECT (parse,
1822 "adjusting pending segment start to %" GST_TIME_FORMAT,
1823 GST_TIME_ARGS (parse->segment.start));
1824 parse->priv->pending_segment =
1825 gst_event_new_new_segment (FALSE, parse->segment.rate,
1826 parse->segment.format, parse->segment.start,
1827 parse->segment.stop, parse->segment.start);
1829 /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1830 if (GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop) &&
1831 GST_CLOCK_TIME_IS_VALID (last_start)) {
1832 GstClockTimeDiff diff;
1834 /* only send newsegments with increasing start times,
1835 * otherwise if these go back and forth downstream (sinks) increase
1836 * accumulated time and running_time */
1837 diff = GST_CLOCK_DIFF (parse->segment.last_stop, last_start);
1838 if (G_UNLIKELY (diff > 2 * GST_SECOND
1839 && last_start > parse->segment.start
1840 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
1841 || last_start < parse->segment.stop))) {
1842 GST_DEBUG_OBJECT (parse,
1843 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
1844 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1845 "Sending updated NEWSEGMENT events", diff,
1846 GST_TIME_ARGS (parse->segment.last_stop),
1847 GST_TIME_ARGS (last_start));
1848 if (G_UNLIKELY (parse->priv->pending_segment)) {
1849 gst_event_unref (parse->priv->pending_segment);
1850 parse->segment.start = last_start;
1851 parse->priv->pending_segment =
1852 gst_event_new_new_segment (FALSE, parse->segment.rate,
1853 parse->segment.format, parse->segment.start,
1854 parse->segment.stop, parse->segment.start);
1856 /* send newsegment events such that the gap is not accounted in
1857 * accum time, hence running_time */
1858 /* close ahead of gap */
1859 gst_pad_push_event (parse->srcpad,
1860 gst_event_new_new_segment (TRUE, parse->segment.rate,
1861 parse->segment.format, parse->segment.last_stop,
1862 parse->segment.last_stop, parse->segment.last_stop));
1864 gst_pad_push_event (parse->srcpad,
1865 gst_event_new_new_segment (FALSE, parse->segment.rate,
1866 parse->segment.format, last_start,
1867 parse->segment.stop, last_start));
1869 /* align segment view with downstream,
1870 * prevents double-counting accum when closing segment */
1871 gst_segment_set_newsegment (&parse->segment, FALSE,
1872 parse->segment.rate, parse->segment.format, last_start,
1873 parse->segment.stop, last_start);
1874 parse->segment.last_stop = last_start;
1879 /* and should then also be linked downstream, so safe to send some events */
1880 if (G_UNLIKELY (parse->priv->close_segment)) {
1881 /* only set up by loop */
1882 GST_DEBUG_OBJECT (parse, "loop sending close segment");
1883 gst_pad_push_event (parse->srcpad, parse->priv->close_segment);
1884 parse->priv->close_segment = NULL;
1886 if (G_UNLIKELY (parse->priv->pending_segment)) {
1887 GstEvent *pending_segment;
1889 pending_segment = parse->priv->pending_segment;
1890 parse->priv->pending_segment = NULL;
1892 GST_DEBUG_OBJECT (parse, "%s push pending segment",
1893 parse->priv->pad_mode == GST_ACTIVATE_PULL ? "loop" : "chain");
1894 gst_pad_push_event (parse->srcpad, pending_segment);
1896 /* have caps; check identity */
1897 gst_base_parse_check_media (parse);
1900 /* update bitrates and optionally post corresponding tags
1901 * (following newsegment) */
1902 gst_base_parse_update_bitrates (parse, frame);
1904 if (G_UNLIKELY (parse->priv->pending_events)) {
1907 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1908 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1910 g_list_free (parse->priv->pending_events);
1911 parse->priv->pending_events = NULL;
1914 if (klass->pre_push_frame) {
1915 ret = klass->pre_push_frame (parse, frame);
1917 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
1920 /* take final ownership of frame buffer */
1921 buffer = frame->buffer;
1922 frame->buffer = NULL;
1924 /* subclass must play nice */
1925 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1928 buffer = gst_buffer_make_metadata_writable (buffer);
1929 gst_buffer_set_caps (buffer, GST_PAD_CAPS (parse->srcpad));
1931 parse->priv->seen_keyframe |= parse->priv->is_video &&
1932 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1934 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
1935 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1936 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
1937 GST_BUFFER_TIMESTAMP (buffer) >
1938 parse->segment.stop + parse->priv->lead_out_ts) {
1939 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
1940 ret = GST_FLOW_UNEXPECTED;
1941 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1942 GST_BUFFER_DURATION_IS_VALID (buffer) &&
1943 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
1944 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
1945 parse->priv->lead_in_ts < parse->segment.start) {
1946 if (parse->priv->seen_keyframe) {
1947 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
1950 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
1951 ret = GST_BASE_PARSE_FLOW_DROPPED;
1958 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1959 GST_LOG_OBJECT (parse, "frame (%d bytes) dropped",
1960 GST_BUFFER_SIZE (buffer));
1961 gst_buffer_unref (buffer);
1963 } else if (ret == GST_FLOW_OK) {
1964 if (parse->segment.rate > 0.0) {
1965 GST_LOG_OBJECT (parse, "pushing frame (%d bytes) now..",
1966 GST_BUFFER_SIZE (buffer));
1967 ret = gst_pad_push (parse->srcpad, buffer);
1968 GST_LOG_OBJECT (parse, "frame pushed, flow %s", gst_flow_get_name (ret));
1970 GST_LOG_OBJECT (parse, "frame (%d bytes) queued for now",
1971 GST_BUFFER_SIZE (buffer));
1972 parse->priv->buffers_queued =
1973 g_slist_prepend (parse->priv->buffers_queued, buffer);
1977 GST_LOG_OBJECT (parse, "frame (%d bytes) not pushed: %s",
1978 GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
1979 gst_buffer_unref (buffer);
1980 /* if we are not sufficiently in control, let upstream decide on EOS */
1981 if (ret == GST_FLOW_UNEXPECTED &&
1982 (parse->priv->passthrough ||
1983 (parse->priv->pad_mode == GST_ACTIVATE_PUSH &&
1984 !parse->priv->upstream_seekable)))
1988 /* Update current running segment position */
1989 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
1990 parse->segment.last_stop < last_stop)
1991 gst_segment_set_last_stop (&parse->segment, GST_FORMAT_TIME, last_stop);
1993 gst_base_parse_frame_free (frame);
1999 /* gst_base_parse_drain:
2001 * Drains the adapter until it is empty. It decreases the min_frame_size to
2002 * match the current adapter size and calls chain method until the adapter
2003 * is emptied or chain returns with error.
2006 gst_base_parse_drain (GstBaseParse * parse)
2010 GST_DEBUG_OBJECT (parse, "draining");
2011 parse->priv->drain = TRUE;
2014 avail = gst_adapter_available (parse->priv->adapter);
2018 if (gst_base_parse_chain (parse->sinkpad, NULL) != GST_FLOW_OK) {
2022 /* nothing changed, maybe due to truncated frame; break infinite loop */
2023 if (avail == gst_adapter_available (parse->priv->adapter)) {
2024 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
2025 gst_adapter_clear (parse->priv->adapter);
2029 parse->priv->drain = FALSE;
2032 /* gst_base_parse_send_buffers
2034 * Sends buffers collected in send_buffers downstream, and ensures that list
2035 * is empty at the end (errors or not).
2037 static GstFlowReturn
2038 gst_base_parse_send_buffers (GstBaseParse * parse)
2040 GSList *send = NULL;
2042 GstFlowReturn ret = GST_FLOW_OK;
2044 send = parse->priv->buffers_send;
2048 buf = GST_BUFFER_CAST (send->data);
2049 GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
2050 GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2051 ", offset %" G_GINT64_FORMAT, buf,
2052 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2053 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2055 /* iterate output queue an push downstream */
2056 ret = gst_pad_push (parse->srcpad, buf);
2057 send = g_slist_delete_link (send, send);
2059 /* clear any leftover if error */
2060 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2062 buf = GST_BUFFER_CAST (send->data);
2063 gst_buffer_unref (buf);
2064 send = g_slist_delete_link (send, send);
2069 parse->priv->buffers_send = send;
2074 /* gst_base_parse_process_fragment:
2076 * Processes a reverse playback (forward) fragment:
2077 * - append head of last fragment that was skipped to current fragment data
2078 * - drain the resulting current fragment data (i.e. repeated chain)
2079 * - add time/duration (if needed) to frames queued by chain
2080 * - push queued data
2082 static GstFlowReturn
2083 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
2086 GstFlowReturn ret = GST_FLOW_OK;
2087 gboolean seen_key = FALSE, seen_delta = FALSE;
2093 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2094 while (parse->priv->buffers_pending) {
2095 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2096 GST_LOG_OBJECT (parse, "adding pending buffer (size %d)",
2097 GST_BUFFER_SIZE (buf));
2098 gst_adapter_push (parse->priv->adapter, buf);
2099 parse->priv->buffers_pending =
2100 g_slist_delete_link (parse->priv->buffers_pending,
2101 parse->priv->buffers_pending);
2104 /* invalidate so no fall-back timestamping is performed;
2105 * ok if taken from subclass or upstream */
2106 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
2107 /* prevent it hanging around stop all the time */
2108 parse->segment.last_stop = GST_CLOCK_TIME_NONE;
2110 parse->priv->discont = TRUE;
2112 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2113 /* initial skipped data is added to buffers_pending */
2114 gst_base_parse_drain (parse);
2117 if (parse->priv->buffers_send) {
2118 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2119 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2122 /* add metadata (if needed to queued buffers */
2123 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2124 GST_TIME_ARGS (parse->priv->last_ts));
2125 while (parse->priv->buffers_queued) {
2126 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2128 /* no touching if upstream or parsing provided time */
2129 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2130 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2131 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2132 } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
2133 GST_BUFFER_DURATION_IS_VALID (buf)) {
2134 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
2135 parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
2137 parse->priv->last_ts = 0;
2138 GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
2139 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2140 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2142 /* no idea, very bad */
2143 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2146 parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
2148 /* reverse order for ascending sending */
2149 /* send downstream at keyframe not preceded by a keyframe
2150 * (e.g. that should identify start of collection of IDR nals) */
2151 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2153 ret = gst_base_parse_send_buffers (parse);
2154 /* if a problem, throw all to sending */
2155 if (ret != GST_FLOW_OK) {
2156 parse->priv->buffers_send =
2157 g_slist_reverse (parse->priv->buffers_queued);
2158 parse->priv->buffers_queued = NULL;
2167 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2169 parse->priv->buffers_send =
2170 g_slist_prepend (parse->priv->buffers_send, buf);
2171 parse->priv->buffers_queued =
2172 g_slist_delete_link (parse->priv->buffers_queued,
2173 parse->priv->buffers_queued);
2176 /* audio may have all marked as keyframe, so arrange to send here */
2178 ret = gst_base_parse_send_buffers (parse);
2180 /* any trailing unused no longer usable (ideally none) */
2181 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2182 GST_DEBUG_OBJECT (parse, "discarding %d trailing bytes",
2183 gst_adapter_available (parse->priv->adapter));
2184 gst_adapter_clear (parse->priv->adapter);
2190 /* small helper that checks whether we have been trying to resync too long */
2191 static inline GstFlowReturn
2192 gst_base_parse_check_sync (GstBaseParse * parse)
2194 if (G_UNLIKELY (parse->priv->discont &&
2195 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2196 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2197 ("Failed to parse stream"), (NULL));
2198 return GST_FLOW_ERROR;
2204 static GstFlowReturn
2205 gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
2207 GstBaseParseClass *bclass;
2208 GstBaseParse *parse;
2209 GstFlowReturn ret = GST_FLOW_OK;
2210 GstBuffer *outbuf = NULL;
2211 GstBuffer *tmpbuf = NULL;
2215 guint old_min_size = 0, min_size, av;
2216 GstClockTime timestamp;
2217 GstBaseParseFrame *frame;
2219 parse = GST_BASE_PARSE (GST_OBJECT_PARENT (pad));
2220 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2222 if (parse->priv->detecting) {
2223 GstBuffer *detect_buf;
2225 if (parse->priv->detect_buffers_size == 0) {
2226 detect_buf = gst_buffer_ref (buffer);
2232 gst_buffer_new_and_alloc (parse->priv->detect_buffers_size +
2233 (buffer ? GST_BUFFER_SIZE (buffer) : 0));
2234 for (l = parse->priv->detect_buffers; l; l = l->next) {
2235 memcpy (GST_BUFFER_DATA (detect_buf) + offset,
2236 GST_BUFFER_DATA (l->data), GST_BUFFER_SIZE (l->data));
2237 offset += GST_BUFFER_SIZE (l->data);
2240 memcpy (GST_BUFFER_DATA (detect_buf) + offset, GST_BUFFER_DATA (buffer),
2241 GST_BUFFER_SIZE (buffer));
2244 ret = bclass->detect (parse, detect_buf);
2245 gst_buffer_unref (detect_buf);
2247 if (ret == GST_FLOW_OK) {
2250 /* Detected something */
2251 parse->priv->detecting = FALSE;
2253 for (l = parse->priv->detect_buffers; l; l = l->next) {
2254 if (ret == GST_FLOW_OK && !parse->priv->flushing)
2256 gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2257 GST_BUFFER_CAST (l->data));
2259 gst_buffer_unref (GST_BUFFER_CAST (l->data));
2261 g_list_free (parse->priv->detect_buffers);
2262 parse->priv->detect_buffers = NULL;
2263 parse->priv->detect_buffers_size = 0;
2265 if (ret != GST_FLOW_OK) {
2269 /* Handle the current buffer */
2270 } else if (ret == GST_FLOW_NOT_NEGOTIATED) {
2271 /* Still detecting, append buffer or error out if draining */
2273 if (parse->priv->drain) {
2274 GST_DEBUG_OBJECT (parse, "Draining but did not detect format yet");
2275 return GST_FLOW_ERROR;
2276 } else if (parse->priv->flushing) {
2277 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref,
2279 g_list_free (parse->priv->detect_buffers);
2280 parse->priv->detect_buffers = NULL;
2281 parse->priv->detect_buffers_size = 0;
2283 parse->priv->detect_buffers =
2284 g_list_append (parse->priv->detect_buffers, buffer);
2285 parse->priv->detect_buffers_size += GST_BUFFER_SIZE (buffer);
2289 /* Something went wrong, subclass responsible for error reporting */
2293 /* And now handle the current buffer if detection worked */
2296 frame = &parse->priv->frame;
2298 if (G_LIKELY (buffer)) {
2299 GST_LOG_OBJECT (parse, "buffer size: %d, offset = %" G_GINT64_FORMAT,
2300 GST_BUFFER_SIZE (buffer), GST_BUFFER_OFFSET (buffer));
2301 if (G_UNLIKELY (parse->priv->passthrough)) {
2302 gst_base_parse_frame_init (frame);
2303 frame->buffer = gst_buffer_make_metadata_writable (buffer);
2304 return gst_base_parse_push_frame (parse, frame);
2306 /* upstream feeding us in reverse playback;
2307 * gather each fragment, then process it in single run */
2308 if (parse->segment.rate < 0.0) {
2309 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2310 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2311 ret = gst_base_parse_process_fragment (parse, FALSE);
2313 gst_adapter_push (parse->priv->adapter, buffer);
2316 gst_adapter_push (parse->priv->adapter, buffer);
2319 if (G_UNLIKELY (buffer &&
2320 GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2321 frame->_private_flags |= GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
2322 gst_base_parse_frame_free (frame);
2325 /* Parse and push as many frames as possible */
2326 /* Stop either when adapter is empty or we are flushing */
2327 while (!parse->priv->flushing) {
2330 /* maintain frame state for a single frame parsing round across _chain calls,
2331 * so only init when needed */
2332 if (!frame->_private_flags)
2333 gst_base_parse_frame_init (frame);
2335 tmpbuf = gst_buffer_new ();
2338 /* Synchronization loop */
2340 /* note: if subclass indicates MAX fsize,
2341 * this will not likely be available anyway ... */
2342 min_size = MAX (parse->priv->min_frame_size, fsize);
2343 av = gst_adapter_available (parse->priv->adapter);
2345 /* loop safety check */
2346 if (G_UNLIKELY (old_min_size >= min_size))
2348 old_min_size = min_size;
2350 if (G_UNLIKELY (parse->priv->drain)) {
2352 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2353 if (G_UNLIKELY (!min_size)) {
2354 gst_buffer_unref (tmpbuf);
2359 /* Collect at least min_frame_size bytes */
2360 if (av < min_size) {
2361 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
2363 gst_buffer_unref (tmpbuf);
2367 /* always pass all available data */
2368 data = gst_adapter_peek (parse->priv->adapter, av);
2369 GST_BUFFER_DATA (tmpbuf) = (guint8 *) data;
2370 GST_BUFFER_SIZE (tmpbuf) = av;
2371 GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
2372 GST_BUFFER_FLAG_SET (tmpbuf, GST_MINI_OBJECT_FLAG_READONLY);
2374 if (parse->priv->discont) {
2375 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2376 GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2380 gst_base_parse_frame_update (parse, frame, tmpbuf);
2381 res = bclass->check_valid_frame (parse, frame, &fsize, &skip);
2382 gst_buffer_replace (&frame->buffer, NULL);
2384 if (gst_adapter_available (parse->priv->adapter) < fsize) {
2385 GST_DEBUG_OBJECT (parse,
2386 "found valid frame but not enough data available (only %d bytes)",
2387 gst_adapter_available (parse->priv->adapter));
2388 gst_buffer_unref (tmpbuf);
2391 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2395 /* subclass didn't touch this value. By default we skip 1 byte */
2399 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2400 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2401 /* reverse playback, and no frames found yet, so we are skipping
2402 * the leading part of a fragment, which may form the tail of
2403 * fragment coming later, hopefully subclass skips efficiently ... */
2404 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2405 outbuf = gst_adapter_take_buffer (parse->priv->adapter, skip);
2406 outbuf = gst_buffer_make_metadata_writable (outbuf);
2407 GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
2408 parse->priv->buffers_pending =
2409 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2412 gst_adapter_flush (parse->priv->adapter, skip);
2414 parse->priv->offset += skip;
2415 if (!parse->priv->discont)
2416 parse->priv->sync_offset = parse->priv->offset;
2417 parse->priv->discont = TRUE;
2418 /* something changed least; nullify loop check */
2421 /* skip == 0 should imply subclass set min_size to need more data;
2422 * we check this shortly */
2423 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2424 gst_buffer_unref (tmpbuf);
2428 gst_buffer_unref (tmpbuf);
2432 /* Subclass found the sync, but still wants to skip some data */
2433 GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
2434 gst_adapter_flush (parse->priv->adapter, skip);
2435 parse->priv->offset += skip;
2438 /* Grab lock to prevent a race with FLUSH_START handler */
2439 GST_PAD_STREAM_LOCK (parse->srcpad);
2441 /* FLUSH_START event causes the "flushing" flag to be set. In this
2442 * case we can leave the frame pushing loop */
2443 if (parse->priv->flushing) {
2444 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2448 /* move along with upstream timestamp (if any),
2449 * but interpolate in between */
2450 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2451 if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2452 (parse->priv->prev_ts != timestamp)) {
2453 parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2456 /* FIXME: Would it be more efficient to make a subbuffer instead? */
2457 outbuf = gst_adapter_take_buffer (parse->priv->adapter, fsize);
2458 outbuf = gst_buffer_make_metadata_writable (outbuf);
2460 /* Subclass may want to know the data offset */
2461 GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2462 parse->priv->offset += fsize;
2463 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2464 GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
2466 frame->buffer = outbuf;
2467 ret = gst_base_parse_handle_and_push_frame (parse, bclass, frame);
2468 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2470 if (ret != GST_FLOW_OK) {
2471 GST_LOG_OBJECT (parse, "push returned %d", ret);
2477 GST_LOG_OBJECT (parse, "chain leaving");
2483 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2484 ("min_size evolution %d -> %d; breaking to avoid looping",
2485 old_min_size, min_size));
2486 return GST_FLOW_ERROR;
2490 /* pull @size bytes at current offset,
2491 * i.e. at least try to and possibly return a shorter buffer if near the end */
2492 static GstFlowReturn
2493 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2494 GstBuffer ** buffer)
2496 GstFlowReturn ret = GST_FLOW_OK;
2498 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2500 /* Caching here actually makes much less difference than one would expect.
2501 * We do it mainly to avoid pulling buffers of 1 byte all the time */
2502 if (parse->priv->cache) {
2503 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2504 gint cache_size = GST_BUFFER_SIZE (parse->priv->cache);
2506 if (cache_offset <= parse->priv->offset &&
2507 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2508 *buffer = gst_buffer_create_sub (parse->priv->cache,
2509 parse->priv->offset - cache_offset, size);
2510 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2513 /* not enough data in the cache, free cache and get a new one */
2514 gst_buffer_unref (parse->priv->cache);
2515 parse->priv->cache = NULL;
2518 /* refill the cache */
2520 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2521 64 * 1024), &parse->priv->cache);
2522 if (ret != GST_FLOW_OK) {
2523 parse->priv->cache = NULL;
2527 if (GST_BUFFER_SIZE (parse->priv->cache) >= size) {
2528 *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
2529 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2533 /* Not possible to get enough data, try a last time with
2534 * requesting exactly the size we need */
2535 gst_buffer_unref (parse->priv->cache);
2536 parse->priv->cache = NULL;
2538 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2539 &parse->priv->cache);
2541 if (ret != GST_FLOW_OK) {
2542 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2547 if (GST_BUFFER_SIZE (parse->priv->cache) < size) {
2548 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2549 G_GUINT64_FORMAT ": wanted %u bytes, got %u bytes", parse->priv->offset,
2550 size, GST_BUFFER_SIZE (parse->priv->cache));
2552 *buffer = parse->priv->cache;
2553 parse->priv->cache = NULL;
2558 *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
2559 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2564 static GstFlowReturn
2565 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2568 GstClockTime ts = 0;
2572 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2573 ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2574 parse->priv->last_offset);
2576 if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2577 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2578 GST_TIME_ARGS (parse->segment.start));
2579 ret = GST_FLOW_UNEXPECTED;
2583 /* last fragment started at last_offset / last_ts;
2584 * seek back 10s capped at 1MB */
2585 if (parse->priv->last_ts >= 10 * GST_SECOND)
2586 ts = parse->priv->last_ts - 10 * GST_SECOND;
2587 /* if we are exact now, we will be more so going backwards */
2588 if (parse->priv->exact_position) {
2589 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2591 GstFormat dstformat = GST_FORMAT_BYTES;
2593 if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2594 &dstformat, &offset)) {
2595 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2598 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2599 parse->priv->last_offset - 1024);
2600 offset = MAX (0, offset);
2602 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2604 parse->priv->offset = offset;
2606 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2608 if (ret != GST_FLOW_OK)
2611 /* offset will increase again as fragment is processed/parsed */
2612 parse->priv->last_offset = offset;
2614 gst_adapter_push (parse->priv->adapter, buffer);
2615 ret = gst_base_parse_process_fragment (parse, FALSE);
2616 if (ret != GST_FLOW_OK)
2619 /* force previous fragment */
2620 parse->priv->offset = -1;
2627 * pull and scan for next frame starting from current offset
2628 * ajusts sync, drain and offset going along */
2629 static GstFlowReturn
2630 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2631 GstBaseParseFrame * frame, gboolean full)
2633 GstBuffer *buffer, *outbuf;
2634 GstFlowReturn ret = GST_FLOW_OK;
2635 guint fsize = 1, min_size, old_min_size = 0;
2638 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2640 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2641 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2643 /* let's make this efficient for all subclass once and for all;
2644 * maybe it does not need this much, but in the latter case, we know we are
2645 * in pull mode here and might as well try to read and supply more anyway
2646 * (so does the buffer caching mechanism) */
2652 min_size = MAX (parse->priv->min_frame_size, fsize);
2653 /* loop safety check */
2654 if (G_UNLIKELY (old_min_size >= min_size))
2656 old_min_size = min_size;
2658 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2659 if (ret != GST_FLOW_OK)
2662 if (parse->priv->discont) {
2663 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2664 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2667 /* if we got a short read, inform subclass we are draining leftover
2668 * and no more is to be expected */
2669 if (GST_BUFFER_SIZE (buffer) < min_size)
2670 parse->priv->drain = TRUE;
2672 if (parse->priv->detecting) {
2673 ret = klass->detect (parse, buffer);
2674 if (ret == GST_FLOW_NOT_NEGOTIATED) {
2675 /* If draining we error out, otherwise request a buffer
2677 if (parse->priv->drain) {
2678 gst_buffer_unref (buffer);
2679 GST_ERROR_OBJECT (parse, "Failed to detect format but draining");
2680 return GST_FLOW_ERROR;
2683 gst_buffer_unref (buffer);
2686 } else if (ret != GST_FLOW_OK) {
2687 gst_buffer_unref (buffer);
2688 GST_ERROR_OBJECT (parse, "detect() returned %s",
2689 gst_flow_get_name (ret));
2693 /* Else handle this buffer normally */
2697 gst_base_parse_frame_update (parse, frame, buffer);
2698 res = klass->check_valid_frame (parse, frame, &fsize, &skip);
2699 gst_buffer_replace (&frame->buffer, NULL);
2701 parse->priv->drain = FALSE;
2702 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2705 parse->priv->drain = FALSE;
2709 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2710 if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2711 /* reverse playback, and no frames found yet, so we are skipping
2712 * the leading part of a fragment, which may form the tail of
2713 * fragment coming later, hopefully subclass skips efficiently ... */
2714 outbuf = gst_buffer_create_sub (buffer, 0, skip);
2715 parse->priv->buffers_pending =
2716 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2719 parse->priv->offset += skip;
2720 if (!parse->priv->discont)
2721 parse->priv->sync_offset = parse->priv->offset;
2722 parse->priv->discont = TRUE;
2723 /* something changed at least; nullify loop check */
2724 if (fsize == G_MAXUINT)
2725 fsize = old_min_size + 64 * 1024;
2728 /* skip == 0 should imply subclass set min_size to need more data;
2729 * we check this shortly */
2730 GST_DEBUG_OBJECT (parse, "finding sync...");
2731 gst_buffer_unref (buffer);
2732 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2737 /* Does the subclass want to skip too? */
2739 parse->priv->offset += skip;
2743 if (fsize + skip <= GST_BUFFER_SIZE (buffer)) {
2744 outbuf = gst_buffer_create_sub (buffer, skip, fsize);
2745 GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2746 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2747 gst_buffer_unref (buffer);
2749 gst_buffer_unref (buffer);
2750 ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2751 if (ret != GST_FLOW_OK)
2753 if (GST_BUFFER_SIZE (outbuf) < fsize) {
2754 gst_buffer_unref (outbuf);
2755 ret = GST_FLOW_UNEXPECTED;
2759 parse->priv->offset += fsize;
2761 frame->buffer = outbuf;
2769 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2770 ("min_size evolution %d -> %d; breaking to avoid looping",
2771 old_min_size, min_size));
2772 return GST_FLOW_ERROR;
2776 /* Loop that is used in pull mode to retrieve data from upstream */
2778 gst_base_parse_loop (GstPad * pad)
2780 GstBaseParse *parse;
2781 GstBaseParseClass *klass;
2782 GstFlowReturn ret = GST_FLOW_OK;
2783 GstBaseParseFrame frame;
2785 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2786 klass = GST_BASE_PARSE_GET_CLASS (parse);
2788 /* reverse playback:
2789 * first fragment (closest to stop time) is handled normally below,
2790 * then we pull in fragments going backwards */
2791 if (parse->segment.rate < 0.0) {
2792 /* check if we jumped back to a previous fragment,
2793 * which is a post-first fragment */
2794 if (parse->priv->offset < 0) {
2795 ret = gst_base_parse_handle_previous_fragment (parse);
2800 gst_base_parse_frame_init (&frame);
2801 ret = gst_base_parse_scan_frame (parse, klass, &frame, TRUE);
2802 if (ret != GST_FLOW_OK)
2805 /* This always cleans up frame, even if error occurs */
2806 ret = gst_base_parse_handle_and_push_frame (parse, klass, &frame);
2808 /* eat expected eos signalling past segment in reverse playback */
2809 if (parse->segment.rate < 0.0 && ret == GST_FLOW_UNEXPECTED &&
2810 parse->segment.last_stop >= parse->segment.stop) {
2811 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2812 /* push what was accumulated during loop run */
2813 gst_base_parse_process_fragment (parse, TRUE);
2814 /* force previous fragment */
2815 parse->priv->offset = -1;
2820 if (ret == GST_FLOW_UNEXPECTED)
2822 else if (ret != GST_FLOW_OK)
2825 gst_object_unref (parse);
2831 ret = GST_FLOW_UNEXPECTED;
2832 GST_DEBUG_OBJECT (parse, "eos");
2837 gboolean push_eos = FALSE;
2839 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2840 gst_flow_get_name (ret));
2841 gst_pad_pause_task (parse->sinkpad);
2843 if (ret == GST_FLOW_UNEXPECTED) {
2844 /* handle end-of-stream/segment */
2845 if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2848 if ((stop = parse->segment.stop) == -1)
2849 stop = parse->segment.duration;
2851 GST_DEBUG_OBJECT (parse, "sending segment_done");
2853 gst_element_post_message
2854 (GST_ELEMENT_CAST (parse),
2855 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2856 GST_FORMAT_TIME, stop));
2858 /* If we STILL have zero frames processed, fire an error */
2859 if (parse->priv->framecount == 0) {
2860 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2861 ("No valid frames found before end of stream"), (NULL));
2865 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
2866 /* for fatal errors we post an error message, wrong-state is
2867 * not fatal because it happens due to flushes and only means
2868 * that we should stop now. */
2869 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2870 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2874 /* newsegment before eos */
2875 if (parse->priv->pending_segment) {
2876 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
2877 parse->priv->pending_segment = NULL;
2879 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2881 gst_object_unref (parse);
2886 gst_base_parse_sink_activate (GstPad * sinkpad)
2888 GstBaseParse *parse;
2889 gboolean result = TRUE;
2891 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2893 GST_DEBUG_OBJECT (parse, "sink activate");
2895 if (gst_pad_check_pull_range (sinkpad)) {
2896 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2897 result = gst_pad_activate_pull (sinkpad, TRUE);
2899 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
2900 result = gst_pad_activate_push (sinkpad, TRUE);
2903 GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
2904 gst_object_unref (parse);
2909 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
2911 GstBaseParseClass *klass;
2912 gboolean result = TRUE;
2914 GST_DEBUG_OBJECT (parse, "activate %d", active);
2916 klass = GST_BASE_PARSE_GET_CLASS (parse);
2919 if (parse->priv->pad_mode == GST_ACTIVATE_NONE && klass->start)
2920 result = klass->start (parse);
2922 /* If the subclass implements ::detect we want to
2923 * call it for the first buffers now */
2924 parse->priv->detecting = (klass->detect != NULL);
2926 /* We must make sure streaming has finished before resetting things
2927 * and calling the ::stop vfunc */
2928 GST_PAD_STREAM_LOCK (parse->sinkpad);
2929 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2931 if (parse->priv->pad_mode != GST_ACTIVATE_NONE && klass->stop)
2932 result = klass->stop (parse);
2934 parse->priv->pad_mode = GST_ACTIVATE_NONE;
2936 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
2941 gst_base_parse_sink_activate_push (GstPad * pad, gboolean active)
2943 gboolean result = TRUE;
2944 GstBaseParse *parse;
2946 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2948 GST_DEBUG_OBJECT (parse, "sink activate push %d", active);
2950 result = gst_base_parse_activate (parse, active);
2953 parse->priv->pad_mode = active ? GST_ACTIVATE_PUSH : GST_ACTIVATE_NONE;
2955 GST_DEBUG_OBJECT (parse, "sink activate push return: %d", result);
2957 gst_object_unref (parse);
2962 gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
2964 gboolean result = FALSE;
2965 GstBaseParse *parse;
2967 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2969 GST_DEBUG_OBJECT (parse, "activate pull %d", active);
2971 result = gst_base_parse_activate (parse, active);
2975 parse->priv->pending_segment = gst_event_new_new_segment (FALSE,
2976 parse->segment.rate, parse->segment.format,
2977 parse->segment.start, parse->segment.stop, parse->segment.last_stop);
2979 gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
2982 result &= gst_pad_stop_task (sinkpad);
2987 parse->priv->pad_mode = active ? GST_ACTIVATE_PULL : GST_ACTIVATE_NONE;
2989 GST_DEBUG_OBJECT (parse, "sink activate pull return: %d", result);
2991 gst_object_unref (parse);
2997 * gst_base_parse_set_duration:
2998 * @parse: #GstBaseParse.
3000 * @duration: duration value.
3001 * @interval: how often to update the duration estimate based on bitrate, or 0.
3003 * Sets the duration of the currently playing media. Subclass can use this
3004 * when it is able to determine duration and/or notices a change in the media
3005 * duration. Alternatively, if @interval is non-zero (default), then stream
3006 * duration is determined based on estimated bitrate, and updated every @interval
3012 gst_base_parse_set_duration (GstBaseParse * parse,
3013 GstFormat fmt, gint64 duration, gint interval)
3015 g_return_if_fail (parse != NULL);
3017 if (parse->priv->upstream_has_duration) {
3018 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
3022 if (duration != parse->priv->duration) {
3025 m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
3026 gst_element_post_message (GST_ELEMENT (parse), m);
3028 /* TODO: what about duration tag? */
3030 parse->priv->duration = duration;
3031 parse->priv->duration_fmt = fmt;
3032 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
3033 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
3034 if (interval != 0) {
3035 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
3039 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
3040 parse->priv->update_interval = interval;
3046 * gst_base_parse_set_average_bitrate:
3047 * @parse: #GstBaseParse.
3048 * @bitrate: average bitrate in bits/second
3050 * Optionally sets the average bitrate detected in media (if non-zero),
3051 * e.g. based on metadata, as it will be posted to the application.
3053 * By default, announced average bitrate is estimated. The average bitrate
3054 * is used to estimate the total duration of the stream and to estimate
3055 * a seek position, if there's no index and the format is syncable
3056 * (see gst_base_parse_set_syncable()).
3061 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
3063 parse->priv->bitrate = bitrate;
3064 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
3068 * gst_base_parse_set_min_frame_size:
3069 * @parse: #GstBaseParse.
3070 * @min_size: Minimum size of the data that this base class should give to
3073 * Subclass can use this function to tell the base class that it needs to
3074 * give at least #min_size buffers.
3079 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
3081 g_return_if_fail (parse != NULL);
3083 parse->priv->min_frame_size = min_size;
3084 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
3088 * gst_base_parse_set_frame_rate:
3089 * @parse: the #GstBaseParse to set
3090 * @fps_num: frames per second (numerator).
3091 * @fps_den: frames per second (denominator).
3092 * @lead_in: frames needed before a segment for subsequent decode
3093 * @lead_out: frames needed after a segment
3095 * If frames per second is configured, parser can take care of buffer duration
3096 * and timestamping. When performing segment clipping, or seeking to a specific
3097 * location, a corresponding decoder might need an initial @lead_in and a
3098 * following @lead_out number of frames to ensure the desired segment is
3099 * entirely filled upon decoding.
3104 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
3105 guint fps_den, guint lead_in, guint lead_out)
3107 g_return_if_fail (parse != NULL);
3109 parse->priv->fps_num = fps_num;
3110 parse->priv->fps_den = fps_den;
3111 if (!fps_num || !fps_den) {
3112 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
3114 fps_num = fps_den = 0;
3115 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
3116 parse->priv->lead_in = parse->priv->lead_out = 0;
3117 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
3119 parse->priv->frame_duration =
3120 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
3121 parse->priv->lead_in = lead_in;
3122 parse->priv->lead_out = lead_out;
3123 parse->priv->lead_in_ts =
3124 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
3125 parse->priv->lead_out_ts =
3126 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
3127 /* aim for about 1.5s to estimate duration */
3128 if (parse->priv->update_interval < 0) {
3129 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
3130 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
3131 parse->priv->update_interval);
3134 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
3135 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
3136 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
3137 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
3138 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
3139 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
3143 * gst_base_parse_set_has_timing_info:
3144 * @parse: a #GstBaseParse
3145 * @has_timing: whether frames carry timing information
3147 * Set if frames carry timing information which the subclass can (generally)
3148 * parse and provide. In particular, intrinsic (rather than estimated) time
3149 * can be obtained following a seek.
3154 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3156 parse->priv->has_timing_info = has_timing;
3157 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3161 * gst_base_parse_set_syncable:
3162 * @parse: a #GstBaseParse
3163 * @syncable: set if frame starts can be identified
3165 * Set if frame starts can be identified. This is set by default and
3166 * determines whether seeking based on bitrate averages
3167 * is possible for a format/stream.
3172 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3174 parse->priv->syncable = syncable;
3175 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3179 * gst_base_parse_set_passthrough:
3180 * @parse: a #GstBaseParse
3181 * @passthrough: %TRUE if parser should run in passthrough mode
3183 * Set if the nature of the format or configuration does not allow (much)
3184 * parsing, and the parser should operate in passthrough mode (which only
3185 * applies when operating in push mode). That is, incoming buffers are
3186 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3187 * callbacks will be invoked, but @pre_push_frame will still be invoked,
3188 * so subclass can perform as much or as little is appropriate for
3189 * passthrough semantics in @pre_push_frame.
3194 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3196 parse->priv->passthrough = passthrough;
3197 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3201 * gst_base_parse_set_latency:
3202 * @parse: a #GstBaseParse
3203 * @min_latency: minimum parse latency
3204 * @max_latency: maximum parse latency
3206 * Sets the minimum and maximum (which may likely be equal) latency introduced
3207 * by the parsing process. If there is such a latency, which depends on the
3208 * particular parsing of the format, it typically corresponds to 1 frame duration.
3213 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3214 GstClockTime max_latency)
3216 GST_OBJECT_LOCK (parse);
3217 parse->priv->min_latency = min_latency;
3218 parse->priv->max_latency = max_latency;
3219 GST_OBJECT_UNLOCK (parse);
3220 GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3221 GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3222 GST_TIME_ARGS (max_latency));
3226 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3227 GstClockTime * duration)
3229 gboolean res = FALSE;
3231 g_return_val_if_fail (duration != NULL, FALSE);
3233 *duration = GST_CLOCK_TIME_NONE;
3234 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3235 GST_LOG_OBJECT (parse, "using provided duration");
3236 *duration = parse->priv->duration;
3238 } else if (parse->priv->duration != -1) {
3239 GST_LOG_OBJECT (parse, "converting provided duration");
3240 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3241 parse->priv->duration, format, (gint64 *) duration);
3242 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3243 GST_LOG_OBJECT (parse, "using estimated duration");
3244 *duration = parse->priv->estimated_duration;
3248 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3249 GST_TIME_ARGS (*duration));
3253 static const GstQueryType *
3254 gst_base_parse_get_querytypes (GstPad * pad)
3256 static const GstQueryType list[] = {
3269 gst_base_parse_query (GstPad * pad, GstQuery * query)
3271 GstBaseParse *parse;
3272 gboolean res = FALSE;
3274 parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3276 GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3278 switch (GST_QUERY_TYPE (query)) {
3279 case GST_QUERY_POSITION:
3284 GST_DEBUG_OBJECT (parse, "position query");
3285 gst_query_parse_position (query, &format, NULL);
3287 /* try upstream first */
3288 res = gst_pad_query_default (pad, query);
3290 /* Fall back on interpreting segment */
3291 GST_OBJECT_LOCK (parse);
3292 if (format == GST_FORMAT_BYTES) {
3293 dest_value = parse->priv->offset;
3295 } else if (format == parse->segment.format &&
3296 GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop)) {
3297 dest_value = gst_segment_to_stream_time (&parse->segment,
3298 parse->segment.format, parse->segment.last_stop);
3301 GST_OBJECT_UNLOCK (parse);
3303 /* no precise result, upstream no idea either, then best estimate */
3304 /* priv->offset is updated in both PUSH/PULL modes */
3305 res = gst_base_parse_convert (parse,
3306 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3309 gst_query_set_position (query, format, dest_value);
3313 case GST_QUERY_DURATION:
3316 GstClockTime duration;
3318 GST_DEBUG_OBJECT (parse, "duration query");
3319 gst_query_parse_duration (query, &format, NULL);
3321 /* consult upstream */
3322 res = gst_pad_query_default (pad, query);
3324 /* otherwise best estimate from us */
3326 res = gst_base_parse_get_duration (parse, format, &duration);
3328 gst_query_set_duration (query, format, duration);
3332 case GST_QUERY_SEEKING:
3335 GstClockTime duration = GST_CLOCK_TIME_NONE;
3336 gboolean seekable = FALSE;
3338 GST_DEBUG_OBJECT (parse, "seeking query");
3339 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3341 /* consult upstream */
3342 res = gst_pad_query_default (pad, query);
3344 /* we may be able to help if in TIME */
3345 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3346 gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3347 /* already OK if upstream takes care */
3348 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3350 if (!(res && seekable)) {
3351 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3352 || duration == -1) {
3353 /* seekable if we still have a chance to get duration later on */
3355 parse->priv->upstream_seekable && parse->priv->update_interval;
3357 seekable = parse->priv->upstream_seekable;
3358 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3361 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3367 case GST_QUERY_FORMATS:
3368 gst_query_set_formatsv (query, 3, fmtlist);
3371 case GST_QUERY_CONVERT:
3373 GstFormat src_format, dest_format;
3374 gint64 src_value, dest_value;
3376 gst_query_parse_convert (query, &src_format, &src_value,
3377 &dest_format, &dest_value);
3379 res = gst_base_parse_convert (parse, src_format, src_value,
3380 dest_format, &dest_value);
3382 gst_query_set_convert (query, src_format, src_value,
3383 dest_format, dest_value);
3387 case GST_QUERY_LATENCY:
3389 if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3391 GstClockTime min_latency, max_latency;
3393 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3394 GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3395 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3396 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3398 GST_OBJECT_LOCK (parse);
3399 /* add our latency */
3400 if (min_latency != -1)
3401 min_latency += parse->priv->min_latency;
3402 if (max_latency != -1)
3403 max_latency += parse->priv->max_latency;
3404 GST_OBJECT_UNLOCK (parse);
3406 gst_query_set_latency (query, live, min_latency, max_latency);
3411 res = gst_pad_query_default (pad, query);
3417 /* scans for a cluster start from @pos,
3418 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3419 static GstFlowReturn
3420 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3421 GstClockTime * time, GstClockTime * duration)
3423 GstBaseParseClass *klass;
3425 gboolean orig_drain, orig_discont;
3426 GstFlowReturn ret = GST_FLOW_OK;
3427 GstBuffer *buf = NULL;
3428 GstBaseParseFrame frame;
3430 g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3431 g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3432 g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3434 klass = GST_BASE_PARSE_GET_CLASS (parse);
3436 *time = GST_CLOCK_TIME_NONE;
3437 *duration = GST_CLOCK_TIME_NONE;
3440 orig_offset = parse->priv->offset;
3441 orig_discont = parse->priv->discont;
3442 orig_drain = parse->priv->drain;
3444 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3445 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3447 gst_base_parse_frame_init (&frame);
3449 /* jump elsewhere and locate next frame */
3450 parse->priv->offset = *pos;
3451 ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3452 if (ret != GST_FLOW_OK)
3456 GST_LOG_OBJECT (parse,
3457 "peek parsing frame at offset %" G_GUINT64_FORMAT
3458 " (%#" G_GINT64_MODIFIER "x) of size %d",
3459 GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf), GST_BUFFER_SIZE (buf));
3461 /* get offset first, subclass parsing might dump other stuff in there */
3462 *pos = GST_BUFFER_OFFSET (buf);
3463 ret = klass->parse_frame (parse, &frame);
3466 /* but it should provide proper time */
3467 *time = GST_BUFFER_TIMESTAMP (buf);
3468 *duration = GST_BUFFER_DURATION (buf);
3470 gst_base_parse_frame_free (&frame);
3472 GST_LOG_OBJECT (parse,
3473 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3474 GST_TIME_ARGS (*time), *pos);
3478 parse->priv->offset = orig_offset;
3479 parse->priv->discont = orig_discont;
3480 parse->priv->drain = orig_drain;
3485 /* bisect and scan through file for frame starting before @time,
3486 * returns OK and @time/@offset if found, NONE and/or error otherwise
3487 * If @time == G_MAXINT64, scan for duration ( == last frame) */
3488 static GstFlowReturn
3489 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3492 GstFlowReturn ret = GST_FLOW_OK;
3493 gint64 lpos, hpos, newpos;
3494 GstClockTime time, ltime, htime, newtime, dur;
3495 gboolean cont = TRUE;
3496 const GstClockTime tolerance = TARGET_DIFFERENCE;
3497 const guint chunk = 4 * 1024;
3499 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3500 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3502 /* TODO also make keyframe aware if useful some day */
3517 /* do not know at first */
3519 *_time = GST_CLOCK_TIME_NONE;
3521 /* need initial positions; start and end */
3522 lpos = parse->priv->first_frame_offset;
3523 ltime = parse->priv->first_frame_ts;
3524 htime = parse->priv->duration;
3525 hpos = parse->priv->upstream_size;
3527 /* check preconditions are satisfied;
3528 * start and end are needed, except for special case where we scan for
3529 * last frame to determine duration */
3530 if (parse->priv->pad_mode != GST_ACTIVATE_PULL || !hpos ||
3531 !GST_CLOCK_TIME_IS_VALID (ltime) ||
3532 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3536 /* shortcut cases */
3539 } else if (time < ltime + tolerance) {
3543 } else if (time >= htime) {
3549 while (htime > ltime && cont) {
3550 GST_LOG_OBJECT (parse,
3551 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3552 GST_TIME_ARGS (ltime));
3553 GST_LOG_OBJECT (parse,
3554 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3555 GST_TIME_ARGS (htime));
3556 if (G_UNLIKELY (time == G_MAXINT64)) {
3558 } else if (G_LIKELY (hpos > lpos)) {
3560 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3563 /* should mean lpos == hpos, since lpos <= hpos is invariant */
3565 /* we check this case once, but not forever, so break loop */
3570 newpos = CLAMP (newpos, lpos, hpos);
3571 GST_LOG_OBJECT (parse,
3572 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3573 GST_TIME_ARGS (time), newpos);
3575 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3576 if (ret == GST_FLOW_UNEXPECTED) {
3577 /* heuristic HACK */
3578 hpos = MAX (lpos, hpos - chunk);
3580 } else if (ret != GST_FLOW_OK) {
3584 if (newtime == -1 || newpos == -1) {
3585 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3589 if (G_UNLIKELY (time == G_MAXINT64)) {
3592 if (GST_CLOCK_TIME_IS_VALID (dur))
3595 } else if (newtime > time) {
3597 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3599 } else if (newtime + tolerance > time) {
3600 /* close enough undershoot */
3604 } else if (newtime < ltime) {
3605 /* so a position beyond lpos resulted in earlier time than ltime ... */
3606 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3609 /* undershoot too far */
3610 newpos += newpos == lpos ? chunk : 0;
3611 lpos = CLAMP (newpos, lpos, hpos);
3617 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3618 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3623 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3624 gboolean before, GstClockTime * _ts)
3626 gint64 bytes = 0, ts = 0;
3627 GstIndexEntry *entry = NULL;
3629 if (time == GST_CLOCK_TIME_NONE) {
3635 g_static_mutex_lock (&parse->priv->index_lock);
3636 if (parse->priv->index) {
3637 /* Let's check if we have an index entry for that time */
3638 entry = gst_index_get_assoc_entry (parse->priv->index,
3639 parse->priv->index_id,
3640 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3641 GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3645 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3646 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3648 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3649 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3650 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3652 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3653 GST_TIME_ARGS (time));
3656 ts = GST_CLOCK_TIME_NONE;
3659 g_static_mutex_unlock (&parse->priv->index_lock);
3668 /* returns TRUE if seek succeeded */
3670 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3675 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3676 gboolean flush, update, res = TRUE, accurate;
3677 gint64 cur, stop, seekpos, seekstop;
3678 GstSegment seeksegment = { 0, };
3679 GstFormat dstformat;
3680 GstClockTime start_ts;
3682 gst_event_parse_seek (event, &rate, &format, &flags,
3683 &cur_type, &cur, &stop_type, &stop);
3685 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3686 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3687 GST_TIME_FORMAT, gst_format_get_name (format), rate,
3688 cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3690 /* no negative rates in push mode */
3691 if (rate < 0.0 && parse->priv->pad_mode == GST_ACTIVATE_PUSH)
3694 if (cur_type != GST_SEEK_TYPE_SET ||
3695 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3698 /* For any format other than TIME, see if upstream handles
3699 * it directly or fail. For TIME, try upstream, but do it ourselves if
3700 * it fails upstream */
3701 if (format != GST_FORMAT_TIME) {
3702 /* default action delegates to upstream */
3706 gst_event_ref (event);
3707 if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3712 /* get flush flag */
3713 flush = flags & GST_SEEK_FLAG_FLUSH;
3715 /* copy segment, we need this because we still need the old
3716 * segment when we close the current segment. */
3717 memcpy (&seeksegment, &parse->segment, sizeof (GstSegment));
3719 GST_DEBUG_OBJECT (parse, "configuring seek");
3720 gst_segment_set_seek (&seeksegment, rate, format, flags,
3721 cur_type, cur, stop_type, stop, &update);
3723 /* accurate seeking implies seek tables are used to obtain position,
3724 * and the requested segment is maintained exactly, not adjusted any way */
3725 accurate = flags & GST_SEEK_FLAG_ACCURATE;
3727 /* maybe we can be accurate for (almost) free */
3728 gst_base_parse_find_offset (parse, seeksegment.last_stop, TRUE, &start_ts);
3729 if (seeksegment.last_stop <= start_ts + TARGET_DIFFERENCE) {
3730 GST_DEBUG_OBJECT (parse, "accurate seek possible");
3734 GstClockTime startpos = seeksegment.last_stop;
3736 /* accurate requested, so ... seek a bit before target */
3737 if (startpos < parse->priv->lead_in_ts)
3740 startpos -= parse->priv->lead_in_ts;
3741 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3742 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3745 start_ts = seeksegment.last_stop;
3746 dstformat = GST_FORMAT_BYTES;
3747 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.last_stop,
3748 &dstformat, &seekpos))
3749 goto convert_failed;
3750 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3751 &dstformat, &seekstop))
3752 goto convert_failed;
3755 GST_DEBUG_OBJECT (parse,
3756 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3758 GST_DEBUG_OBJECT (parse,
3759 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3760 seeksegment.stop, seekstop);
3762 if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
3765 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3768 if (parse->srcpad) {
3769 GST_DEBUG_OBJECT (parse, "sending flush start");
3770 gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3771 /* unlock upstream pull_range */
3772 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3775 gst_pad_pause_task (parse->sinkpad);
3778 /* we should now be able to grab the streaming thread because we stopped it
3779 * with the above flush/pause code */
3780 GST_PAD_STREAM_LOCK (parse->sinkpad);
3782 /* save current position */
3783 last_stop = parse->segment.last_stop;
3784 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3787 /* now commit to new position */
3789 /* prepare for streaming again */
3791 GST_DEBUG_OBJECT (parse, "sending flush stop");
3792 gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop ());
3793 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop ());
3794 gst_base_parse_clear_queues (parse);
3796 if (parse->priv->close_segment)
3797 gst_event_unref (parse->priv->close_segment);
3799 parse->priv->close_segment = gst_event_new_new_segment (TRUE,
3800 parse->segment.rate, parse->segment.format,
3801 parse->segment.accum, parse->segment.last_stop, parse->segment.accum);
3803 /* keep track of our last_stop */
3804 seeksegment.accum = parse->segment.last_stop;
3806 GST_DEBUG_OBJECT (parse, "Created close seg format %d, "
3807 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3808 ", pos = %" GST_TIME_FORMAT, format,
3809 GST_TIME_ARGS (parse->segment.accum),
3810 GST_TIME_ARGS (parse->segment.last_stop),
3811 GST_TIME_ARGS (parse->segment.accum));
3814 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3816 /* store the newsegment event so it can be sent from the streaming thread. */
3817 if (parse->priv->pending_segment)
3818 gst_event_unref (parse->priv->pending_segment);
3820 /* This will be sent later in _loop() */
3821 parse->priv->pending_segment =
3822 gst_event_new_new_segment (FALSE, parse->segment.rate,
3823 parse->segment.format, parse->segment.start,
3824 parse->segment.stop, parse->segment.start);
3826 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3827 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3828 ", pos = %" GST_TIME_FORMAT, format,
3829 GST_TIME_ARGS (parse->segment.start),
3830 GST_TIME_ARGS (parse->segment.stop),
3831 GST_TIME_ARGS (parse->segment.start));
3833 /* one last chance in pull mode to stay accurate;
3834 * maybe scan and subclass can find where to go */
3837 GstClockTime ts = seeksegment.last_stop;
3839 gst_base_parse_locate_time (parse, &ts, &scanpos);
3843 /* running collected index now consists of several intervals,
3844 * so optimized check no longer possible */
3845 parse->priv->index_last_valid = FALSE;
3846 parse->priv->index_last_offset = 0;
3847 parse->priv->index_last_ts = 0;
3851 /* mark discont if we are going to stream from another position. */
3852 if (seekpos != parse->priv->offset) {
3853 GST_DEBUG_OBJECT (parse,
3854 "mark DISCONT, we did a seek to another position");
3855 parse->priv->offset = seekpos;
3856 parse->priv->last_offset = seekpos;
3857 parse->priv->seen_keyframe = FALSE;
3858 parse->priv->discont = TRUE;
3859 parse->priv->next_ts = start_ts;
3860 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3861 parse->priv->sync_offset = seekpos;
3862 parse->priv->exact_position = accurate;
3865 /* Start streaming thread if paused */
3866 gst_pad_start_task (parse->sinkpad,
3867 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3869 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3874 GstEvent *new_event;
3875 GstBaseParseSeek *seek;
3876 GstSeekFlags flags = (flush ? GST_SEEK_FLAG_FLUSH : GST_SEEK_FLAG_NONE);
3878 /* The only thing we need to do in PUSH-mode is to send the
3879 seek event (in bytes) to upstream. Segment / flush handling happens
3880 in corresponding src event handlers */
3881 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3882 if (seekstop >= 0 && seekpos <= seekpos)
3884 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
3885 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3887 /* store segment info so its precise details can be reconstructed when
3888 * receiving newsegment;
3889 * this matters for all details when accurate seeking,
3890 * is most useful to preserve NONE stop time otherwise */
3891 seek = g_new0 (GstBaseParseSeek, 1);
3892 seek->segment = seeksegment;
3893 seek->accurate = accurate;
3894 seek->offset = seekpos;
3895 seek->start_ts = start_ts;
3896 GST_OBJECT_LOCK (parse);
3897 /* less optimal, but preserves order */
3898 parse->priv->pending_seeks =
3899 g_slist_append (parse->priv->pending_seeks, seek);
3900 GST_OBJECT_UNLOCK (parse);
3902 res = gst_pad_push_event (parse->sinkpad, new_event);
3905 GST_OBJECT_LOCK (parse);
3906 parse->priv->pending_seeks =
3907 g_slist_remove (parse->priv->pending_seeks, seek);
3908 GST_OBJECT_UNLOCK (parse);
3914 /* handled event is ours to free */
3916 gst_event_unref (event);
3922 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
3928 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3934 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3940 /* Checks if bitrates are available from upstream tags so that we don't
3941 * override them later
3944 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
3946 GstTagList *taglist = NULL;
3949 gst_event_parse_tag (event, &taglist);
3951 if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
3952 GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
3953 parse->priv->post_min_bitrate = FALSE;
3955 if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
3956 GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
3957 parse->priv->post_avg_bitrate = FALSE;
3959 if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
3960 GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
3961 parse->priv->post_max_bitrate = FALSE;
3966 gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps)
3968 GstBaseParse *parse;
3969 GstBaseParseClass *klass;
3970 gboolean res = TRUE;
3972 parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3973 klass = GST_BASE_PARSE_GET_CLASS (parse);
3975 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
3977 if (klass->set_sink_caps)
3978 res = klass->set_sink_caps (parse, caps);
3984 gst_base_parse_sink_getcaps (GstPad * pad)
3986 GstBaseParse *parse;
3987 GstBaseParseClass *klass;
3990 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
3991 klass = GST_BASE_PARSE_GET_CLASS (parse);
3992 g_assert (pad == GST_BASE_PARSE_SINK_PAD (parse));
3994 if (klass->get_sink_caps)
3995 caps = klass->get_sink_caps (parse);
3997 caps = gst_pad_proxy_getcaps (pad);
3998 gst_object_unref (parse);
4000 GST_LOG_OBJECT (parse, "sink getcaps returning caps %" GST_PTR_FORMAT, caps);
4007 gst_base_parse_set_index (GstElement * element, GstIndex * index)
4009 GstBaseParse *parse = GST_BASE_PARSE (element);
4011 g_static_mutex_lock (&parse->priv->index_lock);
4012 if (parse->priv->index)
4013 gst_object_unref (parse->priv->index);
4015 parse->priv->index = gst_object_ref (index);
4016 gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
4017 &parse->priv->index_id);
4018 parse->priv->own_index = FALSE;
4020 parse->priv->index = NULL;
4022 g_static_mutex_unlock (&parse->priv->index_lock);
4026 gst_base_parse_get_index (GstElement * element)
4028 GstBaseParse *parse = GST_BASE_PARSE (element);
4029 GstIndex *result = NULL;
4031 g_static_mutex_lock (&parse->priv->index_lock);
4032 if (parse->priv->index)
4033 result = gst_object_ref (parse->priv->index);
4034 g_static_mutex_unlock (&parse->priv->index_lock);
4039 static GstStateChangeReturn
4040 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
4042 GstBaseParse *parse;
4043 GstStateChangeReturn result;
4045 parse = GST_BASE_PARSE (element);
4047 switch (transition) {
4048 case GST_STATE_CHANGE_READY_TO_PAUSED:
4049 /* If this is our own index destroy it as the
4050 * old entries might be wrong for the new stream */
4051 g_static_mutex_lock (&parse->priv->index_lock);
4052 if (parse->priv->own_index) {
4053 gst_object_unref (parse->priv->index);
4054 parse->priv->index = NULL;
4055 parse->priv->own_index = FALSE;
4058 /* If no index was created, generate one */
4059 if (G_UNLIKELY (!parse->priv->index)) {
4060 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
4062 parse->priv->index = gst_index_factory_make ("memindex");
4063 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
4064 &parse->priv->index_id);
4065 parse->priv->own_index = TRUE;
4067 g_static_mutex_unlock (&parse->priv->index_lock);
4073 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4075 switch (transition) {
4076 case GST_STATE_CHANGE_PAUSED_TO_READY:
4077 gst_base_parse_reset (parse);