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
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,
379 static gboolean gst_base_parse_sink_activate_mode (GstPad * pad,
380 GstObject * parent, GstPadMode mode, gboolean active);
381 static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
383 static void gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event);
385 static gboolean gst_base_parse_src_event (GstPad * pad, GstObject * parent,
387 static gboolean gst_base_parse_src_query (GstPad * pad, GstObject * parent,
390 static gboolean gst_base_parse_sink_event (GstPad * pad, GstObject * parent,
392 static gboolean gst_base_parse_sink_query (GstPad * pad, GstObject * parent,
395 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstObject * parent,
397 static void gst_base_parse_loop (GstPad * pad);
399 static gboolean gst_base_parse_check_frame (GstBaseParse * parse,
400 GstBaseParseFrame * frame, guint * framesize, gint * skipsize);
401 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
402 GstBaseParseFrame * frame);
404 static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
407 static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
410 static void gst_base_parse_drain (GstBaseParse * parse);
412 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
413 gboolean post_min, gboolean post_avg, gboolean post_max);
415 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
416 GstClockTime time, gboolean before, GstClockTime * _ts);
417 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
418 GstClockTime * _time, gint64 * _offset);
420 static GstFlowReturn gst_base_parse_process_fragment (GstBaseParse * parse,
423 static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);
426 gst_base_parse_clear_queues (GstBaseParse * parse)
428 g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
429 g_slist_free (parse->priv->buffers_queued);
430 parse->priv->buffers_queued = NULL;
431 g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
433 g_slist_free (parse->priv->buffers_pending);
434 parse->priv->buffers_pending = NULL;
435 g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
436 g_slist_free (parse->priv->buffers_send);
437 parse->priv->buffers_send = NULL;
439 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
440 g_list_free (parse->priv->detect_buffers);
441 parse->priv->detect_buffers = NULL;
442 parse->priv->detect_buffers_size = 0;
446 gst_base_parse_finalize (GObject * object)
448 GstBaseParse *parse = GST_BASE_PARSE (object);
451 g_object_unref (parse->priv->adapter);
453 if (parse->priv->pending_segment) {
454 p_ev = &parse->priv->pending_segment;
455 gst_event_replace (p_ev, NULL);
457 if (parse->priv->close_segment) {
458 p_ev = &parse->priv->close_segment;
459 gst_event_replace (p_ev, NULL);
462 if (parse->priv->cache) {
463 gst_buffer_unref (parse->priv->cache);
464 parse->priv->cache = NULL;
467 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
469 g_list_free (parse->priv->pending_events);
470 parse->priv->pending_events = NULL;
472 g_queue_foreach (&parse->priv->queued_frames,
473 (GFunc) gst_base_parse_frame_free, NULL);
474 g_queue_clear (&parse->priv->queued_frames);
476 if (parse->priv->index) {
477 gst_object_unref (parse->priv->index);
478 parse->priv->index = NULL;
481 g_static_mutex_free (&parse->priv->index_lock);
483 gst_base_parse_clear_queues (parse);
485 G_OBJECT_CLASS (parent_class)->finalize (object);
489 gst_base_parse_class_init (GstBaseParseClass * klass)
491 GObjectClass *gobject_class;
492 GstElementClass *gstelement_class;
494 gobject_class = G_OBJECT_CLASS (klass);
495 g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
496 parent_class = g_type_class_peek_parent (klass);
497 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
499 gstelement_class = (GstElementClass *) klass;
500 gstelement_class->change_state =
501 GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
502 gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
503 gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
505 /* Default handlers */
506 klass->check_valid_frame = gst_base_parse_check_frame;
507 klass->parse_frame = gst_base_parse_parse_frame;
508 klass->src_event = gst_base_parse_src_eventfunc;
509 klass->convert = gst_base_parse_convert_default;
511 GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
512 "baseparse element");
516 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
518 GstPadTemplate *pad_template;
520 GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
522 parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
525 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
526 g_return_if_fail (pad_template != NULL);
527 parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
528 gst_pad_set_event_function (parse->sinkpad,
529 GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
530 gst_pad_set_query_function (parse->sinkpad,
531 GST_DEBUG_FUNCPTR (gst_base_parse_sink_query));
532 gst_pad_set_chain_function (parse->sinkpad,
533 GST_DEBUG_FUNCPTR (gst_base_parse_chain));
534 gst_pad_set_activate_function (parse->sinkpad,
535 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
536 gst_pad_set_activatemode_function (parse->sinkpad,
537 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_mode));
538 gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
540 GST_DEBUG_OBJECT (parse, "sinkpad created");
543 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
544 g_return_if_fail (pad_template != NULL);
545 parse->srcpad = gst_pad_new_from_template (pad_template, "src");
546 gst_pad_set_event_function (parse->srcpad,
547 GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
548 gst_pad_set_query_function (parse->srcpad,
549 GST_DEBUG_FUNCPTR (gst_base_parse_src_query));
550 gst_pad_use_fixed_caps (parse->srcpad);
551 gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
552 GST_DEBUG_OBJECT (parse, "src created");
554 g_queue_init (&parse->priv->queued_frames);
556 parse->priv->adapter = gst_adapter_new ();
558 parse->priv->pad_mode = GST_PAD_MODE_NONE;
560 g_static_mutex_init (&parse->priv->index_lock);
563 gst_base_parse_reset (parse);
564 GST_DEBUG_OBJECT (parse, "init ok");
567 static GstBaseParseFrame *
568 gst_base_parse_frame_copy (GstBaseParseFrame * frame)
570 GstBaseParseFrame *copy;
572 copy = g_slice_dup (GstBaseParseFrame, frame);
573 copy->buffer = gst_buffer_ref (frame->buffer);
574 copy->_private_flags &= ~GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
576 GST_TRACE ("copied frame %p -> %p", frame, copy);
582 gst_base_parse_frame_free (GstBaseParseFrame * frame)
584 GST_TRACE ("freeing frame %p", frame);
587 gst_buffer_unref (frame->buffer);
588 frame->buffer = NULL;
591 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
592 g_slice_free (GstBaseParseFrame, frame);
594 memset (frame, 0, sizeof (*frame));
599 gst_base_parse_frame_get_type (void)
601 static volatile gsize frame_type = 0;
603 if (g_once_init_enter (&frame_type)) {
606 _type = g_boxed_type_register_static ("GstBaseParseFrame",
607 (GBoxedCopyFunc) gst_base_parse_frame_copy,
608 (GBoxedFreeFunc) gst_base_parse_frame_free);
609 g_once_init_leave (&frame_type, _type);
611 return (GType) frame_type;
615 * gst_base_parse_frame_init:
616 * @frame: #GstBaseParseFrame.
618 * Sets a #GstBaseParseFrame to initial state. Currently this means
619 * all public fields are zero-ed and a private flag is set to make
620 * sure gst_base_parse_frame_free() only frees the contents but not
621 * the actual frame. Use this function to initialise a #GstBaseParseFrame
622 * allocated on the stack.
627 gst_base_parse_frame_init (GstBaseParseFrame * frame)
629 memset (frame, 0, sizeof (GstBaseParseFrame));
630 frame->_private_flags = GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
631 GST_TRACE ("inited frame %p", frame);
635 * gst_base_parse_frame_new:
636 * @buffer: (transfer none): a #GstBuffer
638 * @overhead: number of bytes in this frame which should be counted as
639 * metadata overhead, ie. not used to calculate the average bitrate.
640 * Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
642 * Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
643 * elements written in C should usually allocate the frame on the stack and
644 * then use gst_base_parse_frame_init() to initialise it.
646 * Returns: a newly-allocated #GstBaseParseFrame. Free with
647 * gst_base_parse_frame_free() when no longer needed, unless you gave
648 * away ownership to gst_base_parse_push_frame().
653 gst_base_parse_frame_new (GstBuffer * buffer, GstBaseParseFrameFlags flags,
656 GstBaseParseFrame *frame;
658 frame = g_slice_new0 (GstBaseParseFrame);
659 frame->buffer = gst_buffer_ref (buffer);
661 GST_TRACE ("created frame %p", frame);
666 gst_base_parse_frame_update (GstBaseParse * parse, GstBaseParseFrame * frame,
669 gst_buffer_replace (&frame->buffer, buf);
673 /* set flags one by one for clarity */
674 if (G_UNLIKELY (parse->priv->drain))
675 parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;
677 /* losing sync is pretty much a discont (and vice versa), no ? */
678 if (G_UNLIKELY (parse->priv->discont))
679 parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
683 gst_base_parse_reset (GstBaseParse * parse)
685 GST_OBJECT_LOCK (parse);
686 gst_segment_init (&parse->segment, GST_FORMAT_TIME);
687 parse->priv->duration = -1;
688 parse->priv->min_frame_size = 1;
689 parse->priv->discont = TRUE;
690 parse->priv->flushing = FALSE;
691 parse->priv->offset = 0;
692 parse->priv->sync_offset = 0;
693 parse->priv->update_interval = -1;
694 parse->priv->fps_num = parse->priv->fps_den = 0;
695 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
696 parse->priv->lead_in = parse->priv->lead_out = 0;
697 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
698 parse->priv->bitrate = 0;
699 parse->priv->framecount = 0;
700 parse->priv->bytecount = 0;
701 parse->priv->acc_duration = 0;
702 parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
703 parse->priv->first_frame_offset = -1;
704 parse->priv->estimated_duration = -1;
705 parse->priv->estimated_drift = 0;
706 parse->priv->next_ts = 0;
707 parse->priv->syncable = TRUE;
708 parse->priv->passthrough = FALSE;
709 parse->priv->has_timing_info = FALSE;
710 parse->priv->post_min_bitrate = TRUE;
711 parse->priv->post_avg_bitrate = TRUE;
712 parse->priv->post_max_bitrate = TRUE;
713 parse->priv->min_bitrate = G_MAXUINT;
714 parse->priv->max_bitrate = 0;
715 parse->priv->avg_bitrate = 0;
716 parse->priv->posted_avg_bitrate = 0;
718 parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
719 parse->priv->index_last_offset = -1;
720 parse->priv->index_last_valid = TRUE;
721 parse->priv->upstream_seekable = FALSE;
722 parse->priv->upstream_size = 0;
723 parse->priv->upstream_has_duration = FALSE;
724 parse->priv->idx_interval = 0;
725 parse->priv->exact_position = TRUE;
726 parse->priv->seen_keyframe = FALSE;
728 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
729 parse->priv->last_offset = 0;
731 if (parse->priv->pending_segment) {
732 gst_event_unref (parse->priv->pending_segment);
733 parse->priv->pending_segment = NULL;
736 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
738 g_list_free (parse->priv->pending_events);
739 parse->priv->pending_events = NULL;
741 if (parse->priv->cache) {
742 gst_buffer_unref (parse->priv->cache);
743 parse->priv->cache = NULL;
746 g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
747 g_slist_free (parse->priv->pending_seeks);
748 parse->priv->pending_seeks = NULL;
750 /* we know it is not alloc'ed, but maybe other stuff to free, some day ... */
751 parse->priv->frame._private_flags |=
752 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
753 gst_base_parse_frame_free (&parse->priv->frame);
755 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
756 g_list_free (parse->priv->detect_buffers);
757 parse->priv->detect_buffers = NULL;
758 parse->priv->detect_buffers_size = 0;
759 GST_OBJECT_UNLOCK (parse);
762 /* gst_base_parse_check_frame:
763 * @parse: #GstBaseParse.
764 * @buffer: GstBuffer.
765 * @framesize: This will be set to tell the found frame size in bytes.
766 * @skipsize: Output parameter that tells how much data needs to be skipped
767 * in order to find the following frame header.
769 * Default callback for check_valid_frame.
771 * Returns: Always TRUE.
774 gst_base_parse_check_frame (GstBaseParse * parse,
775 GstBaseParseFrame * frame, guint * framesize, gint * skipsize)
777 *framesize = gst_buffer_get_size (frame->buffer);
783 /* gst_base_parse_parse_frame:
784 * @parse: #GstBaseParse.
785 * @buffer: #GstBuffer.
787 * Default callback for parse_frame.
790 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
792 GstBuffer *buffer = frame->buffer;
794 if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
795 GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
796 GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
798 if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
799 GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
800 GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
805 /* gst_base_parse_convert:
806 * @parse: #GstBaseParse.
807 * @src_format: #GstFormat describing the source format.
808 * @src_value: Source value to be converted.
809 * @dest_format: #GstFormat defining the converted format.
810 * @dest_value: Pointer where the conversion result will be put.
812 * Converts using configured "convert" vmethod in #GstBaseParse class.
814 * Returns: TRUE if conversion was successful.
817 gst_base_parse_convert (GstBaseParse * parse,
818 GstFormat src_format,
819 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
821 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
824 g_return_val_if_fail (dest_value != NULL, FALSE);
829 ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
831 #ifndef GST_DISABLE_GST_DEBUG
834 if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
835 GST_LOG_OBJECT (parse,
836 "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
837 GST_TIME_ARGS (src_value), *dest_value);
838 } else if (dest_format == GST_FORMAT_TIME &&
839 src_format == GST_FORMAT_BYTES) {
840 GST_LOG_OBJECT (parse,
841 "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
842 src_value, GST_TIME_ARGS (*dest_value));
844 GST_LOG_OBJECT (parse,
845 "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
846 GST_STR_NULL (gst_format_get_name (src_format)),
847 GST_STR_NULL (gst_format_get_name (dest_format)),
848 src_value, *dest_value);
851 GST_DEBUG_OBJECT (parse, "conversion failed");
859 /* gst_base_parse_sink_event:
860 * @pad: #GstPad that received the event.
861 * @event: #GstEvent to be handled.
863 * Handler for sink pad events.
865 * Returns: TRUE if the event was handled.
868 gst_base_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
871 GstBaseParseClass *bclass;
872 gboolean handled = FALSE;
875 parse = GST_BASE_PARSE (parent);
876 bclass = GST_BASE_PARSE_GET_CLASS (parse);
878 GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
879 GST_EVENT_TYPE_NAME (event));
881 /* Cache all events except EOS, SEGMENT and FLUSH_STOP if we have a
883 if (parse->priv->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
884 && GST_EVENT_TYPE (event) != GST_EVENT_SEGMENT
885 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
886 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP
887 && GST_EVENT_TYPE (event) != GST_EVENT_CAPS) {
889 if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
890 /* See if any bitrate tags were posted */
891 gst_base_parse_handle_tag (parse, event);
893 parse->priv->pending_events =
894 g_list_append (parse->priv->pending_events, event);
898 if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
899 parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
900 /* We've not posted bitrate tags yet - do so now */
901 gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
904 handled = bclass->event (parse, event);
907 handled = gst_base_parse_sink_eventfunc (parse, event);
910 ret = gst_pad_event_default (pad, parent, event);
913 GST_DEBUG_OBJECT (parse, "event handled");
919 /* gst_base_parse_sink_eventfunc:
920 * @parse: #GstBaseParse.
921 * @event: #GstEvent to be handled.
923 * Element-level event handler function.
925 * The event will be unreffed only if it has been handled and this
926 * function returns %TRUE
928 * Returns: %TRUE if the event was handled and not need forwarding.
931 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
933 gboolean handled = FALSE;
936 switch (GST_EVENT_TYPE (event)) {
940 GstBaseParseClass *klass;
942 klass = GST_BASE_PARSE_GET_CLASS (parse);
944 gst_event_parse_caps (event, &caps);
945 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
947 if (klass->set_sink_caps)
948 klass->set_sink_caps (parse, caps);
950 /* will send our own caps downstream */
951 gst_event_unref (event);
955 case GST_EVENT_SEGMENT:
957 const GstSegment *in_segment;
958 GstSegment out_segment;
959 gint64 offset = 0, next_ts;
962 gdouble rate, applied_rate;
964 gint64 start, stop, pos, next_ts;
968 gst_event_parse_segment (event, &in_segment);
969 gst_segment_init (&out_segment, GST_FORMAT_TIME);
971 GST_DEBUG_OBJECT (parse, "segment %" GST_SEGMENT_FORMAT, in_segment);
973 if (in_segment->format == GST_FORMAT_BYTES) {
974 GstBaseParseSeek *seek = NULL;
977 /* stop time is allowed to be open-ended, but not start & pos */
978 offset = in_segment->time;
980 GST_OBJECT_LOCK (parse);
981 for (node = parse->priv->pending_seeks; node; node = node->next) {
982 GstBaseParseSeek *tmp = node->data;
984 if (tmp->offset == offset) {
989 parse->priv->pending_seeks =
990 g_slist_remove (parse->priv->pending_seeks, seek);
991 GST_OBJECT_UNLOCK (parse);
994 GST_DEBUG_OBJECT (parse,
995 "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
996 seek->accurate ? " accurate" : "", &seek->segment);
998 out_segment.start = seek->segment.start;
999 out_segment.stop = seek->segment.stop;
1000 out_segment.time = seek->segment.start;
1002 next_ts = seek->start_ts;
1003 parse->priv->exact_position = seek->accurate;
1006 /* best attempt convert */
1007 /* as these are only estimates, stop is kept open-ended to avoid
1008 * premature cutting */
1009 gst_base_parse_convert (parse, GST_FORMAT_BYTES, in_segment->start,
1010 GST_FORMAT_TIME, (gint64 *) & next_ts);
1012 out_segment.start = next_ts;
1013 out_segment.stop = GST_CLOCK_TIME_NONE;
1014 out_segment.time = next_ts;
1016 parse->priv->exact_position = (in_segment->start == 0);
1019 gst_event_unref (event);
1021 event = gst_event_new_segment (&out_segment);
1023 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. %"
1024 GST_SEGMENT_FORMAT, in_segment);
1026 } else if (in_segment->format != GST_FORMAT_TIME) {
1027 /* Unknown incoming segment format. Output a default open-ended
1029 gst_event_unref (event);
1031 out_segment.start = 0;
1032 out_segment.stop = GST_CLOCK_TIME_NONE;;
1033 out_segment.time = 0;;
1035 event = gst_event_new_segment (&out_segment);
1039 /* not considered BYTE seekable if it is talking to us in TIME,
1040 * whatever else it might claim */
1041 parse->priv->upstream_seekable = FALSE;
1042 next_ts = in_segment->start;
1045 memcpy (&parse->segment, &out_segment, sizeof (GstSegment));
1048 gst_segment_set_newsegment (&parse->segment, update, rate,
1049 applied_rate, format, start, stop, start);
1052 /* save the segment for later, right before we push a new buffer so that
1053 * the caps are fixed and the next linked element can receive
1055 eventp = &parse->priv->pending_segment;
1056 gst_event_replace (eventp, event);
1057 gst_event_unref (event);
1060 /* but finish the current segment */
1061 GST_DEBUG_OBJECT (parse, "draining current segment");
1062 if (in_segment->rate > 0.0)
1063 gst_base_parse_drain (parse);
1065 gst_base_parse_process_fragment (parse, FALSE);
1066 gst_adapter_clear (parse->priv->adapter);
1068 parse->priv->offset = offset;
1069 parse->priv->sync_offset = offset;
1070 parse->priv->next_ts = next_ts;
1071 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1072 parse->priv->discont = TRUE;
1073 parse->priv->seen_keyframe = FALSE;
1077 case GST_EVENT_FLUSH_START:
1078 parse->priv->flushing = TRUE;
1079 handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
1081 gst_event_unref (event);
1082 /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
1083 GST_PAD_STREAM_LOCK (parse->srcpad);
1084 GST_PAD_STREAM_UNLOCK (parse->srcpad);
1088 case GST_EVENT_FLUSH_STOP:
1089 gst_adapter_clear (parse->priv->adapter);
1090 gst_base_parse_clear_queues (parse);
1091 parse->priv->flushing = FALSE;
1092 parse->priv->discont = TRUE;
1093 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1094 parse->priv->frame._private_flags |=
1095 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
1096 gst_base_parse_frame_free (&parse->priv->frame);
1100 if (parse->segment.rate > 0.0)
1101 gst_base_parse_drain (parse);
1103 gst_base_parse_process_fragment (parse, FALSE);
1105 /* If we STILL have zero frames processed, fire an error */
1106 if (parse->priv->framecount == 0) {
1107 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1108 ("No valid frames found before end of stream"), (NULL));
1110 /* newsegment before eos */
1111 if (parse->priv->pending_segment) {
1112 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1113 parse->priv->pending_segment = NULL;
1125 gst_base_parse_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
1127 GstBaseParse *parse;
1128 GstBaseParseClass *bclass;
1131 parse = GST_BASE_PARSE (parent);
1132 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1134 switch (GST_QUERY_TYPE (query)) {
1135 case GST_QUERY_CAPS:
1137 if (bclass->get_sink_caps) {
1138 GstCaps *caps, *filter;
1140 gst_query_parse_caps (query, &filter);
1141 caps = bclass->get_sink_caps (parse, filter);
1142 GST_LOG_OBJECT (parse, "sink getcaps returning caps %" GST_PTR_FORMAT,
1144 gst_query_set_caps_result (query, caps);
1145 gst_caps_unref (caps);
1149 res = gst_pad_peer_query (parse->srcpad, query);
1154 res = gst_pad_query_default (pad, parent, query);
1163 /* gst_base_parse_src_event:
1164 * @pad: #GstPad that received the event.
1165 * @event: #GstEvent that was received.
1167 * Handler for source pad events.
1169 * Returns: TRUE if the event was handled.
1172 gst_base_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1174 GstBaseParse *parse;
1175 GstBaseParseClass *bclass;
1176 gboolean handled = FALSE;
1177 gboolean ret = TRUE;
1179 parse = GST_BASE_PARSE (parent);
1180 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1182 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1183 GST_EVENT_TYPE_NAME (event));
1185 if (bclass->src_event)
1186 handled = bclass->src_event (parse, event);
1189 ret = gst_pad_event_default (pad, parent, event);
1195 gst_base_parse_is_seekable (GstBaseParse * parse)
1197 /* FIXME: could do more here, e.g. check index or just send data from 0
1198 * in pull mode and let decoder/sink clip */
1199 return parse->priv->syncable;
1202 /* gst_base_parse_src_eventfunc:
1203 * @parse: #GstBaseParse.
1204 * @event: #GstEvent that was received.
1206 * Default srcpad event handler.
1208 * Returns: TRUE if the event was handled and can be dropped.
1211 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1213 gboolean handled = FALSE;
1215 switch (GST_EVENT_TYPE (event)) {
1216 case GST_EVENT_SEEK:
1218 if (gst_base_parse_is_seekable (parse)) {
1219 handled = gst_base_parse_handle_seek (parse, event);
1231 * gst_base_parse_convert_default:
1232 * @parse: #GstBaseParse.
1233 * @src_format: #GstFormat describing the source format.
1234 * @src_value: Source value to be converted.
1235 * @dest_format: #GstFormat defining the converted format.
1236 * @dest_value: Pointer where the conversion result will be put.
1238 * Default implementation of "convert" vmethod in #GstBaseParse class.
1240 * Returns: TRUE if conversion was successful.
1245 gst_base_parse_convert_default (GstBaseParse * parse,
1246 GstFormat src_format,
1247 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1249 gboolean ret = FALSE;
1250 guint64 bytes, duration;
1252 if (G_UNLIKELY (src_format == dest_format)) {
1253 *dest_value = src_value;
1257 if (G_UNLIKELY (src_value == -1)) {
1262 if (G_UNLIKELY (src_value == 0)) {
1267 /* need at least some frames */
1268 if (!parse->priv->framecount)
1271 duration = parse->priv->acc_duration / GST_MSECOND;
1272 bytes = parse->priv->bytecount;
1274 if (G_UNLIKELY (!duration || !bytes))
1277 if (src_format == GST_FORMAT_BYTES) {
1278 if (dest_format == GST_FORMAT_TIME) {
1279 /* BYTES -> TIME conversion */
1280 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1281 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1282 *dest_value *= GST_MSECOND;
1283 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1284 *dest_value / GST_MSECOND);
1287 } else if (src_format == GST_FORMAT_TIME) {
1288 if (dest_format == GST_FORMAT_BYTES) {
1289 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1290 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1292 GST_DEBUG_OBJECT (parse,
1293 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1294 src_value / GST_MSECOND, *dest_value);
1297 } else if (src_format == GST_FORMAT_DEFAULT) {
1298 /* DEFAULT == frame-based */
1299 if (dest_format == GST_FORMAT_TIME) {
1300 if (parse->priv->fps_den) {
1301 *dest_value = gst_util_uint64_scale (src_value,
1302 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1305 } else if (dest_format == GST_FORMAT_BYTES) {
1313 gst_base_parse_update_duration (GstBaseParse * baseparse)
1316 GstBaseParse *parse;
1318 parse = GST_BASE_PARSE (baseparse);
1320 peer = gst_pad_get_peer (parse->sinkpad);
1322 gboolean qres = FALSE;
1323 gint64 ptot, dest_value;
1325 qres = gst_pad_query_duration (peer, GST_FORMAT_BYTES, &ptot);
1326 gst_object_unref (GST_OBJECT (peer));
1328 if (gst_base_parse_convert (parse, GST_FORMAT_BYTES, ptot,
1329 GST_FORMAT_TIME, &dest_value)) {
1331 /* inform if duration changed, but try to avoid spamming */
1332 parse->priv->estimated_drift +=
1333 dest_value - parse->priv->estimated_duration;
1334 if (parse->priv->estimated_drift > GST_SECOND ||
1335 parse->priv->estimated_drift < -GST_SECOND) {
1336 gst_element_post_message (GST_ELEMENT (parse),
1337 gst_message_new_duration (GST_OBJECT (parse),
1338 GST_FORMAT_TIME, dest_value));
1339 parse->priv->estimated_drift = 0;
1341 parse->priv->estimated_duration = dest_value;
1342 GST_LOG_OBJECT (parse,
1343 "updated estimated duration to %" GST_TIME_FORMAT,
1344 GST_TIME_ARGS (dest_value));
1351 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1352 gboolean post_avg, gboolean post_max)
1354 GstTagList *taglist = NULL;
1356 if (post_min && parse->priv->post_min_bitrate) {
1357 taglist = gst_tag_list_new_empty ();
1359 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1360 GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1363 if (post_avg && parse->priv->post_avg_bitrate) {
1364 if (taglist == NULL)
1365 taglist = gst_tag_list_new_empty ();
1367 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1368 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1369 parse->priv->avg_bitrate, NULL);
1372 if (post_max && parse->priv->post_max_bitrate) {
1373 if (taglist == NULL)
1374 taglist = gst_tag_list_new_empty ();
1376 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1377 GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1380 GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1381 parse->priv->min_bitrate, parse->priv->avg_bitrate,
1382 parse->priv->max_bitrate);
1384 if (taglist != NULL) {
1385 gst_pad_push_event (parse->srcpad, gst_event_new_tag (taglist));
1389 /* gst_base_parse_update_bitrates:
1390 * @parse: #GstBaseParse.
1391 * @buffer: Current frame as a #GstBuffer
1393 * Keeps track of the minimum and maximum bitrates, and also maintains a
1394 * running average bitrate of the stream so far.
1397 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1399 /* Only update the tag on a 10 kbps delta */
1400 static const gint update_threshold = 10000;
1402 guint64 data_len, frame_dur;
1403 gint overhead, frame_bitrate, old_avg_bitrate;
1404 gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1405 GstBuffer *buffer = frame->buffer;
1407 overhead = frame->overhead;
1411 data_len = gst_buffer_get_size (buffer) - overhead;
1412 parse->priv->data_bytecount += data_len;
1414 /* duration should be valid by now,
1415 * either set by subclass or maybe based on fps settings */
1416 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1417 /* Calculate duration of a frame from buffer properties */
1418 frame_dur = GST_BUFFER_DURATION (buffer);
1419 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1420 parse->priv->acc_duration;
1423 /* No way to figure out frame duration (is this even possible?) */
1427 /* override if subclass provided bitrate, e.g. metadata based */
1428 if (parse->priv->bitrate) {
1429 parse->priv->avg_bitrate = parse->priv->bitrate;
1430 /* spread this (confirmed) info ASAP */
1431 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1432 gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1436 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1440 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1441 parse->priv->avg_bitrate);
1443 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1445 } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1446 /* always post all at threshold time */
1447 update_min = update_max = update_avg = TRUE;
1450 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1451 if (frame_bitrate < parse->priv->min_bitrate) {
1452 parse->priv->min_bitrate = frame_bitrate;
1456 if (frame_bitrate > parse->priv->max_bitrate) {
1457 parse->priv->max_bitrate = frame_bitrate;
1461 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1462 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1463 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1468 if ((update_min || update_avg || update_max))
1469 gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1471 /* If average bitrate changes that much and no valid (time) duration provided,
1472 * then post a new duration message so applications can update their cached
1474 if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1475 GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1476 gst_element_post_message (GST_ELEMENT (parse),
1477 gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1484 * gst_base_parse_add_index_entry:
1485 * @parse: #GstBaseParse.
1486 * @offset: offset of entry
1487 * @ts: timestamp associated with offset
1488 * @key: whether entry refers to keyframe
1489 * @force: add entry disregarding sanity checks
1491 * Adds an entry to the index associating @offset to @ts. It is recommended
1492 * to only add keyframe entries. @force allows to bypass checks, such as
1493 * whether the stream is (upstream) seekable, another entry is already "close"
1494 * to the new entry, etc.
1496 * Returns: #gboolean indicating whether entry was added
1501 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1502 GstClockTime ts, gboolean key, gboolean force)
1504 gboolean ret = FALSE;
1505 GstIndexAssociation associations[2];
1507 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1508 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1510 if (G_LIKELY (!force)) {
1512 if (!parse->priv->upstream_seekable) {
1513 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1517 /* FIXME need better helper data structure that handles these issues
1518 * related to ongoing collecting of index entries */
1519 if (parse->priv->index_last_offset >= (gint64) offset) {
1520 GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1521 "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1525 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1526 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1527 parse->priv->idx_interval) {
1528 GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1529 GST_TIME_ARGS (parse->priv->index_last_ts));
1533 /* if last is not really the last one */
1534 if (!parse->priv->index_last_valid) {
1535 GstClockTime prev_ts;
1537 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1538 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1539 GST_DEBUG_OBJECT (parse,
1540 "entry too close to existing entry %" GST_TIME_FORMAT,
1541 GST_TIME_ARGS (prev_ts));
1542 parse->priv->index_last_offset = offset;
1543 parse->priv->index_last_ts = ts;
1549 associations[0].format = GST_FORMAT_TIME;
1550 associations[0].value = ts;
1551 associations[1].format = GST_FORMAT_BYTES;
1552 associations[1].value = offset;
1554 /* index might change on-the-fly, although that would be nutty app ... */
1555 g_static_mutex_lock (&parse->priv->index_lock);
1556 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1557 (key) ? GST_ASSOCIATION_FLAG_KEY_UNIT : GST_ASSOCIATION_FLAG_DELTA_UNIT,
1558 2, (const GstIndexAssociation *) &associations);
1559 g_static_mutex_unlock (&parse->priv->index_lock);
1562 parse->priv->index_last_offset = offset;
1563 parse->priv->index_last_ts = ts;
1572 /* check for seekable upstream, above and beyond a mere query */
1574 gst_base_parse_check_seekability (GstBaseParse * parse)
1577 gboolean seekable = FALSE;
1578 gint64 start = -1, stop = -1;
1579 guint idx_interval = 0;
1581 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1582 if (!gst_pad_peer_query (parse->sinkpad, query)) {
1583 GST_DEBUG_OBJECT (parse, "seeking query failed");
1587 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1589 /* try harder to query upstream size if we didn't get it the first time */
1590 if (seekable && stop == -1) {
1591 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1592 gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_BYTES, &stop);
1595 /* if upstream doesn't know the size, it's likely that it's not seekable in
1596 * practice even if it technically may be seekable */
1597 if (seekable && (start != 0 || stop <= start)) {
1598 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1602 /* let's not put every single frame into our index */
1604 if (stop < 10 * 1024 * 1024)
1606 else if (stop < 100 * 1024 * 1024)
1609 idx_interval = 1000;
1613 gst_query_unref (query);
1615 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1616 G_GUINT64_FORMAT ")", seekable, start, stop);
1617 parse->priv->upstream_seekable = seekable;
1618 parse->priv->upstream_size = seekable ? stop : 0;
1620 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1621 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1624 /* some misc checks on upstream */
1626 gst_base_parse_check_upstream (GstBaseParse * parse)
1630 if (gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_TIME, &stop))
1631 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1632 /* upstream has one, accept it also, and no further updates */
1633 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1634 parse->priv->upstream_has_duration = TRUE;
1637 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1638 parse->priv->upstream_has_duration);
1641 /* checks src caps to determine if dealing with audio or video */
1642 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1644 gst_base_parse_check_media (GstBaseParse * parse)
1649 caps = gst_pad_get_current_caps (parse->srcpad);
1650 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1651 parse->priv->is_video =
1652 g_str_has_prefix (gst_structure_get_name (s), "video");
1654 /* historical default */
1655 parse->priv->is_video = FALSE;
1658 gst_caps_unref (caps);
1660 GST_DEBUG_OBJECT (parse, "media is video: %d", parse->priv->is_video);
1663 /* takes ownership of frame */
1665 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1667 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1668 /* frame allocated on the heap, we can just take ownership */
1669 g_queue_push_tail (&parse->priv->queued_frames, frame);
1670 GST_TRACE ("queued frame %p", frame);
1672 GstBaseParseFrame *copy;
1674 /* probably allocated on the stack, must make a proper copy */
1675 copy = gst_base_parse_frame_copy (frame);
1676 g_queue_push_tail (&parse->priv->queued_frames, copy);
1677 GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1678 gst_base_parse_frame_free (frame);
1682 /* gst_base_parse_handle_and_push_buffer:
1683 * @parse: #GstBaseParse.
1684 * @klass: #GstBaseParseClass.
1685 * @frame: (transfer full): a #GstBaseParseFrame
1687 * Parses the frame from given buffer and pushes it forward. Also performs
1688 * timestamp handling and checks the segment limits.
1690 * This is called with srcpad STREAM_LOCK held.
1692 * Returns: #GstFlowReturn
1694 static GstFlowReturn
1695 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1696 GstBaseParseClass * klass, GstBaseParseFrame * frame)
1702 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1704 buffer = frame->buffer;
1706 if (parse->priv->discont) {
1707 GST_DEBUG_OBJECT (parse, "marking DISCONT");
1708 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1709 parse->priv->discont = FALSE;
1712 /* some one-time start-up */
1713 if (G_UNLIKELY (!parse->priv->framecount)) {
1714 gst_base_parse_check_seekability (parse);
1715 gst_base_parse_check_upstream (parse);
1718 GST_LOG_OBJECT (parse,
1719 "parsing frame at offset %" G_GUINT64_FORMAT
1720 " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
1721 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1722 gst_buffer_get_size (buffer));
1724 /* use default handler to provide initial (upstream) metadata */
1725 gst_base_parse_parse_frame (parse, frame);
1727 /* store offset as it might get overwritten */
1728 offset = GST_BUFFER_OFFSET (buffer);
1729 ret = klass->parse_frame (parse, frame);
1731 buffer = frame->buffer;
1732 /* subclass must play nice */
1733 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1735 /* check if subclass/format can provide ts.
1736 * If so, that allows and enables extra seek and duration determining options */
1737 if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
1738 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && parse->priv->has_timing_info
1739 && parse->priv->pad_mode == GST_PAD_MODE_PULL) {
1740 parse->priv->first_frame_offset = offset;
1741 parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1742 GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1743 " for first frame at offset %" G_GINT64_FORMAT,
1744 GST_TIME_ARGS (parse->priv->first_frame_ts),
1745 parse->priv->first_frame_offset);
1746 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1748 GstClockTime last_ts = G_MAXINT64;
1750 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1751 gst_base_parse_locate_time (parse, &last_ts, &off);
1752 if (GST_CLOCK_TIME_IS_VALID (last_ts))
1753 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1756 /* disable further checks */
1757 parse->priv->first_frame_offset = 0;
1761 /* again use default handler to add missing metadata;
1762 * we may have new information on frame properties */
1763 gst_base_parse_parse_frame (parse, frame);
1764 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1765 GST_BUFFER_DURATION_IS_VALID (buffer)) {
1766 parse->priv->next_ts =
1767 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1769 /* we lost track, do not produce bogus time next time around
1770 * (probably means parser subclass has given up on parsing as well) */
1771 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1772 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1775 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1776 GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1777 gst_base_parse_add_index_entry (parse, offset,
1778 GST_BUFFER_TIMESTAMP (buffer),
1779 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1781 /* First buffers are dropped, this means that the subclass needs more
1782 * frames to decide on the format and queues them internally */
1783 /* convert internal flow to OK and mark discont for the next buffer. */
1784 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1785 gst_base_parse_frame_free (frame);
1787 } else if (ret == GST_BASE_PARSE_FLOW_QUEUED) {
1788 gst_base_parse_queue_frame (parse, frame);
1790 } else if (ret != GST_FLOW_OK) {
1794 /* All OK, push queued frames if there are any */
1795 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
1796 GstBaseParseFrame *queued_frame;
1798 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
1799 gst_base_parse_push_frame (parse, queued_frame);
1803 return gst_base_parse_push_frame (parse, frame);
1807 * gst_base_parse_push_frame:
1808 * @parse: #GstBaseParse.
1809 * @frame: (transfer full): a #GstBaseParseFrame
1811 * Pushes the frame downstream, sends any pending events and
1812 * does some timestamp and segment handling. Takes ownership
1813 * of @frame and will clear it (if it was initialised with
1814 * gst_base_parse_frame_init()) or free it.
1816 * This must be called with sinkpad STREAM_LOCK held.
1818 * Returns: #GstFlowReturn
1823 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1825 GstFlowReturn ret = GST_FLOW_OK;
1826 GstClockTime last_start = GST_CLOCK_TIME_NONE;
1827 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1828 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1832 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1833 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
1835 GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
1837 buffer = frame->buffer;
1839 GST_LOG_OBJECT (parse,
1840 "processing buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1841 ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buffer),
1842 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1843 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1846 size = gst_buffer_get_size (buffer);
1847 parse->priv->bytecount += size;
1848 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1849 parse->priv->framecount++;
1850 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1851 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1854 /* 0 means disabled */
1855 if (parse->priv->update_interval < 0)
1856 parse->priv->update_interval = 50;
1857 else if (parse->priv->update_interval > 0 &&
1858 (parse->priv->framecount % parse->priv->update_interval) == 0)
1859 gst_base_parse_update_duration (parse);
1861 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1862 last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1863 if (last_start != GST_CLOCK_TIME_NONE
1864 && GST_BUFFER_DURATION_IS_VALID (buffer))
1865 last_stop = last_start + GST_BUFFER_DURATION (buffer);
1867 /* should have caps by now */
1868 g_return_val_if_fail (gst_pad_has_current_caps (parse->srcpad),
1871 /* segment adjustment magic; only if we are running the whole show */
1872 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1873 (parse->priv->pad_mode == GST_PAD_MODE_PULL ||
1874 parse->priv->upstream_seekable)) {
1875 /* segment times are typically estimates,
1876 * actual frame data might lead subclass to different timestamps,
1877 * so override segment start from what is supplied there */
1878 if (G_UNLIKELY (parse->priv->pending_segment && !parse->priv->exact_position
1879 && GST_CLOCK_TIME_IS_VALID (last_start))) {
1880 gst_event_unref (parse->priv->pending_segment);
1881 parse->segment.start =
1882 MIN ((guint64) last_start, (guint64) parse->segment.stop);
1884 GST_DEBUG_OBJECT (parse,
1885 "adjusting pending segment start to %" GST_TIME_FORMAT,
1886 GST_TIME_ARGS (parse->segment.start));
1888 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
1890 /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1891 if (GST_CLOCK_TIME_IS_VALID (parse->segment.position) &&
1892 GST_CLOCK_TIME_IS_VALID (last_start)) {
1893 GstClockTimeDiff diff;
1895 /* only send newsegments with increasing start times,
1896 * otherwise if these go back and forth downstream (sinks) increase
1897 * accumulated time and running_time */
1898 diff = GST_CLOCK_DIFF (parse->segment.position, last_start);
1899 if (G_UNLIKELY (diff > 2 * GST_SECOND
1900 && last_start > parse->segment.start
1901 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
1902 || last_start < parse->segment.stop))) {
1904 GST_DEBUG_OBJECT (parse,
1905 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
1906 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1907 "Sending updated NEWSEGMENT events", diff,
1908 GST_TIME_ARGS (parse->segment.position),
1909 GST_TIME_ARGS (last_start));
1911 if (G_UNLIKELY (parse->priv->pending_segment)) {
1912 gst_event_unref (parse->priv->pending_segment);
1913 parse->segment.start = last_start;
1914 parse->segment.time = last_start;
1915 parse->priv->pending_segment =
1916 gst_event_new_segment (&parse->segment);
1918 /* skip gap FIXME */
1919 gst_pad_push_event (parse->srcpad,
1920 gst_event_new_segment (&parse->segment));
1922 parse->segment.position = last_start;
1927 /* and should then also be linked downstream, so safe to send some events */
1928 if (G_UNLIKELY (parse->priv->close_segment)) {
1929 /* only set up by loop */
1930 GST_DEBUG_OBJECT (parse, "loop sending close segment");
1931 gst_pad_push_event (parse->srcpad, parse->priv->close_segment);
1932 parse->priv->close_segment = NULL;
1934 if (G_UNLIKELY (parse->priv->pending_segment)) {
1935 GstEvent *pending_segment;
1937 pending_segment = parse->priv->pending_segment;
1938 parse->priv->pending_segment = NULL;
1940 GST_DEBUG_OBJECT (parse, "%s push pending segment",
1941 parse->priv->pad_mode == GST_PAD_MODE_PULL ? "loop" : "chain");
1942 gst_pad_push_event (parse->srcpad, pending_segment);
1944 /* have caps; check identity */
1945 gst_base_parse_check_media (parse);
1948 /* update bitrates and optionally post corresponding tags
1949 * (following newsegment) */
1950 gst_base_parse_update_bitrates (parse, frame);
1952 if (G_UNLIKELY (parse->priv->pending_events)) {
1955 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1956 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1958 g_list_free (parse->priv->pending_events);
1959 parse->priv->pending_events = NULL;
1962 if (klass->pre_push_frame) {
1963 ret = klass->pre_push_frame (parse, frame);
1965 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
1968 /* take final ownership of frame buffer */
1969 buffer = frame->buffer;
1970 frame->buffer = NULL;
1972 /* subclass must play nice */
1973 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1975 parse->priv->seen_keyframe |= parse->priv->is_video &&
1976 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1978 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
1979 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1980 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
1981 GST_BUFFER_TIMESTAMP (buffer) >
1982 parse->segment.stop + parse->priv->lead_out_ts) {
1983 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
1985 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1986 GST_BUFFER_DURATION_IS_VALID (buffer) &&
1987 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
1988 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
1989 parse->priv->lead_in_ts < parse->segment.start) {
1990 if (parse->priv->seen_keyframe) {
1991 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
1994 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
1995 ret = GST_BASE_PARSE_FLOW_DROPPED;
2002 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
2003 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) dropped", size);
2004 gst_buffer_unref (buffer);
2006 } else if (ret == GST_FLOW_OK) {
2007 if (parse->segment.rate > 0.0) {
2008 GST_LOG_OBJECT (parse, "pushing frame (%" G_GSIZE_FORMAT " bytes) now..",
2010 ret = gst_pad_push (parse->srcpad, buffer);
2011 GST_LOG_OBJECT (parse, "frame pushed, flow %s", gst_flow_get_name (ret));
2013 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) queued for now",
2015 parse->priv->buffers_queued =
2016 g_slist_prepend (parse->priv->buffers_queued, buffer);
2020 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s",
2021 size, gst_flow_get_name (ret));
2022 gst_buffer_unref (buffer);
2023 /* if we are not sufficiently in control, let upstream decide on EOS */
2024 if (ret == GST_FLOW_EOS &&
2025 (parse->priv->passthrough ||
2026 (parse->priv->pad_mode == GST_PAD_MODE_PUSH &&
2027 !parse->priv->upstream_seekable)))
2031 /* Update current running segment position */
2032 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
2033 parse->segment.position < last_stop)
2034 parse->segment.position = last_stop;
2036 gst_base_parse_frame_free (frame);
2042 /* gst_base_parse_drain:
2044 * Drains the adapter until it is empty. It decreases the min_frame_size to
2045 * match the current adapter size and calls chain method until the adapter
2046 * is emptied or chain returns with error.
2049 gst_base_parse_drain (GstBaseParse * parse)
2053 GST_DEBUG_OBJECT (parse, "draining");
2054 parse->priv->drain = TRUE;
2057 avail = gst_adapter_available (parse->priv->adapter);
2061 if (gst_base_parse_chain (parse->sinkpad, GST_OBJECT_CAST (parse),
2062 NULL) != GST_FLOW_OK) {
2066 /* nothing changed, maybe due to truncated frame; break infinite loop */
2067 if (avail == gst_adapter_available (parse->priv->adapter)) {
2068 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
2069 gst_adapter_clear (parse->priv->adapter);
2073 parse->priv->drain = FALSE;
2076 /* gst_base_parse_send_buffers
2078 * Sends buffers collected in send_buffers downstream, and ensures that list
2079 * is empty at the end (errors or not).
2081 static GstFlowReturn
2082 gst_base_parse_send_buffers (GstBaseParse * parse)
2084 GSList *send = NULL;
2086 GstFlowReturn ret = GST_FLOW_OK;
2088 send = parse->priv->buffers_send;
2092 buf = GST_BUFFER_CAST (send->data);
2093 GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
2094 GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2095 ", offset %" G_GINT64_FORMAT, buf,
2096 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2097 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2099 /* iterate output queue an push downstream */
2100 ret = gst_pad_push (parse->srcpad, buf);
2101 send = g_slist_delete_link (send, send);
2103 /* clear any leftover if error */
2104 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2106 buf = GST_BUFFER_CAST (send->data);
2107 gst_buffer_unref (buf);
2108 send = g_slist_delete_link (send, send);
2113 parse->priv->buffers_send = send;
2118 /* gst_base_parse_process_fragment:
2120 * Processes a reverse playback (forward) fragment:
2121 * - append head of last fragment that was skipped to current fragment data
2122 * - drain the resulting current fragment data (i.e. repeated chain)
2123 * - add time/duration (if needed) to frames queued by chain
2124 * - push queued data
2126 static GstFlowReturn
2127 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
2130 GstFlowReturn ret = GST_FLOW_OK;
2131 gboolean seen_key = FALSE, seen_delta = FALSE;
2137 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2138 while (parse->priv->buffers_pending) {
2139 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2140 GST_LOG_OBJECT (parse, "adding pending buffer (size %" G_GSIZE_FORMAT ")",
2141 gst_buffer_get_size (buf));
2142 gst_adapter_push (parse->priv->adapter, buf);
2143 parse->priv->buffers_pending =
2144 g_slist_delete_link (parse->priv->buffers_pending,
2145 parse->priv->buffers_pending);
2148 /* invalidate so no fall-back timestamping is performed;
2149 * ok if taken from subclass or upstream */
2150 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
2151 /* prevent it hanging around stop all the time */
2152 parse->segment.position = GST_CLOCK_TIME_NONE;
2154 parse->priv->discont = TRUE;
2156 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2157 /* initial skipped data is added to buffers_pending */
2158 gst_base_parse_drain (parse);
2161 if (parse->priv->buffers_send) {
2162 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2163 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2166 /* add metadata (if needed to queued buffers */
2167 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2168 GST_TIME_ARGS (parse->priv->last_ts));
2169 while (parse->priv->buffers_queued) {
2170 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2172 /* no touching if upstream or parsing provided time */
2173 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2174 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2175 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2176 } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
2177 GST_BUFFER_DURATION_IS_VALID (buf)) {
2178 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
2179 parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
2181 parse->priv->last_ts = 0;
2182 GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
2183 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2184 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2186 /* no idea, very bad */
2187 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2190 parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
2192 /* reverse order for ascending sending */
2193 /* send downstream at keyframe not preceded by a keyframe
2194 * (e.g. that should identify start of collection of IDR nals) */
2195 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2197 ret = gst_base_parse_send_buffers (parse);
2198 /* if a problem, throw all to sending */
2199 if (ret != GST_FLOW_OK) {
2200 parse->priv->buffers_send =
2201 g_slist_reverse (parse->priv->buffers_queued);
2202 parse->priv->buffers_queued = NULL;
2211 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2213 parse->priv->buffers_send =
2214 g_slist_prepend (parse->priv->buffers_send, buf);
2215 parse->priv->buffers_queued =
2216 g_slist_delete_link (parse->priv->buffers_queued,
2217 parse->priv->buffers_queued);
2220 /* audio may have all marked as keyframe, so arrange to send here */
2222 ret = gst_base_parse_send_buffers (parse);
2224 /* any trailing unused no longer usable (ideally none) */
2225 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2226 GST_DEBUG_OBJECT (parse, "discarding %" G_GSIZE_FORMAT " trailing bytes",
2227 gst_adapter_available (parse->priv->adapter));
2228 gst_adapter_clear (parse->priv->adapter);
2234 /* small helper that checks whether we have been trying to resync too long */
2235 static inline GstFlowReturn
2236 gst_base_parse_check_sync (GstBaseParse * parse)
2238 if (G_UNLIKELY (parse->priv->discont &&
2239 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2240 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2241 ("Failed to parse stream"), (NULL));
2242 return GST_FLOW_ERROR;
2248 static GstFlowReturn
2249 gst_base_parse_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2251 GstBaseParseClass *bclass;
2252 GstBaseParse *parse;
2253 GstFlowReturn ret = GST_FLOW_OK;
2254 GstBuffer *outbuf = NULL;
2255 GstBuffer *tmpbuf = NULL;
2259 guint old_min_size = 0, min_size, av;
2260 GstClockTime timestamp;
2261 GstBaseParseFrame *frame;
2263 parse = GST_BASE_PARSE (parent);
2264 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2266 if (parse->priv->detecting) {
2267 GstBuffer *detect_buf;
2269 if (parse->priv->detect_buffers_size == 0) {
2270 detect_buf = gst_buffer_ref (buffer);
2275 detect_buf = gst_buffer_new ();
2277 for (l = parse->priv->detect_buffers; l; l = l->next) {
2278 gsize tmpsize = gst_buffer_get_size (l->data);
2280 gst_buffer_copy_into (detect_buf, GST_BUFFER_CAST (l->data),
2281 GST_BUFFER_COPY_MEMORY, offset, tmpsize);
2285 gst_buffer_copy_into (detect_buf, buffer, GST_BUFFER_COPY_MEMORY,
2286 offset, gst_buffer_get_size (buffer));
2289 ret = bclass->detect (parse, detect_buf);
2290 gst_buffer_unref (detect_buf);
2292 if (ret == GST_FLOW_OK) {
2295 /* Detected something */
2296 parse->priv->detecting = FALSE;
2298 for (l = parse->priv->detect_buffers; l; l = l->next) {
2299 if (ret == GST_FLOW_OK && !parse->priv->flushing)
2301 gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2302 parent, GST_BUFFER_CAST (l->data));
2304 gst_buffer_unref (GST_BUFFER_CAST (l->data));
2306 g_list_free (parse->priv->detect_buffers);
2307 parse->priv->detect_buffers = NULL;
2308 parse->priv->detect_buffers_size = 0;
2310 if (ret != GST_FLOW_OK) {
2314 /* Handle the current buffer */
2315 } else if (ret == GST_FLOW_NOT_NEGOTIATED) {
2316 /* Still detecting, append buffer or error out if draining */
2318 if (parse->priv->drain) {
2319 GST_DEBUG_OBJECT (parse, "Draining but did not detect format yet");
2320 return GST_FLOW_ERROR;
2321 } else if (parse->priv->flushing) {
2322 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref,
2324 g_list_free (parse->priv->detect_buffers);
2325 parse->priv->detect_buffers = NULL;
2326 parse->priv->detect_buffers_size = 0;
2328 parse->priv->detect_buffers =
2329 g_list_append (parse->priv->detect_buffers, buffer);
2330 parse->priv->detect_buffers_size += gst_buffer_get_size (buffer);
2334 /* Something went wrong, subclass responsible for error reporting */
2338 /* And now handle the current buffer if detection worked */
2341 frame = &parse->priv->frame;
2343 if (G_LIKELY (buffer)) {
2344 GST_LOG_OBJECT (parse,
2345 "buffer size: %" G_GSIZE_FORMAT ", offset = %" G_GINT64_FORMAT,
2346 gst_buffer_get_size (buffer), GST_BUFFER_OFFSET (buffer));
2347 if (G_UNLIKELY (parse->priv->passthrough)) {
2348 gst_base_parse_frame_init (frame);
2349 frame->buffer = gst_buffer_make_writable (buffer);
2350 return gst_base_parse_push_frame (parse, frame);
2352 /* upstream feeding us in reverse playback;
2353 * gather each fragment, then process it in single run */
2354 if (parse->segment.rate < 0.0) {
2355 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2356 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2357 ret = gst_base_parse_process_fragment (parse, FALSE);
2359 gst_adapter_push (parse->priv->adapter, buffer);
2362 gst_adapter_push (parse->priv->adapter, buffer);
2365 if (G_UNLIKELY (buffer &&
2366 GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2367 frame->_private_flags |= GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
2368 gst_base_parse_frame_free (frame);
2371 /* Parse and push as many frames as possible */
2372 /* Stop either when adapter is empty or we are flushing */
2373 while (!parse->priv->flushing) {
2376 /* maintain frame state for a single frame parsing round across _chain calls,
2377 * so only init when needed */
2378 if (!frame->_private_flags)
2379 gst_base_parse_frame_init (frame);
2381 tmpbuf = gst_buffer_new ();
2384 /* Synchronization loop */
2386 /* note: if subclass indicates MAX fsize,
2387 * this will not likely be available anyway ... */
2388 min_size = MAX (parse->priv->min_frame_size, fsize);
2389 av = gst_adapter_available (parse->priv->adapter);
2391 /* loop safety check */
2392 if (G_UNLIKELY (old_min_size >= min_size))
2394 old_min_size = min_size;
2396 if (G_UNLIKELY (parse->priv->drain)) {
2398 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2399 if (G_UNLIKELY (!min_size)) {
2400 gst_buffer_unref (tmpbuf);
2405 /* Collect at least min_frame_size bytes */
2406 if (av < min_size) {
2407 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
2409 gst_buffer_unref (tmpbuf);
2413 /* always pass all available data */
2414 data = gst_adapter_map (parse->priv->adapter, av);
2415 gst_buffer_take_memory (tmpbuf, -1,
2416 gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
2417 (gpointer) data, NULL, av, 0, av));
2418 GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
2420 if (parse->priv->discont) {
2421 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2422 GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2426 gst_base_parse_frame_update (parse, frame, tmpbuf);
2427 res = bclass->check_valid_frame (parse, frame, &fsize, &skip);
2428 gst_adapter_unmap (parse->priv->adapter);
2429 gst_buffer_replace (&frame->buffer, NULL);
2430 gst_buffer_remove_memory_range (tmpbuf, 0, -1);
2432 if (gst_adapter_available (parse->priv->adapter) < fsize) {
2433 GST_DEBUG_OBJECT (parse, "found valid frame but not enough data"
2434 " available (only %" G_GSIZE_FORMAT " bytes)",
2435 gst_adapter_available (parse->priv->adapter));
2436 gst_buffer_unref (tmpbuf);
2439 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2443 /* subclass didn't touch this value. By default we skip 1 byte */
2447 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2448 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2449 /* reverse playback, and no frames found yet, so we are skipping
2450 * the leading part of a fragment, which may form the tail of
2451 * fragment coming later, hopefully subclass skips efficiently ... */
2452 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2453 outbuf = gst_adapter_take_buffer (parse->priv->adapter, skip);
2454 outbuf = gst_buffer_make_writable (outbuf);
2455 GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
2456 parse->priv->buffers_pending =
2457 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2460 gst_adapter_flush (parse->priv->adapter, skip);
2462 parse->priv->offset += skip;
2463 if (!parse->priv->discont)
2464 parse->priv->sync_offset = parse->priv->offset;
2465 parse->priv->discont = TRUE;
2466 /* something changed least; nullify loop check */
2469 /* skip == 0 should imply subclass set min_size to need more data;
2470 * we check this shortly */
2471 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2472 gst_buffer_unref (tmpbuf);
2476 gst_buffer_unref (tmpbuf);
2480 /* Subclass found the sync, but still wants to skip some data */
2481 GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
2482 gst_adapter_flush (parse->priv->adapter, skip);
2483 parse->priv->offset += skip;
2486 /* Grab lock to prevent a race with FLUSH_START handler */
2487 GST_PAD_STREAM_LOCK (parse->srcpad);
2489 /* FLUSH_START event causes the "flushing" flag to be set. In this
2490 * case we can leave the frame pushing loop */
2491 if (parse->priv->flushing) {
2492 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2496 /* move along with upstream timestamp (if any),
2497 * but interpolate in between */
2498 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2499 if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2500 (parse->priv->prev_ts != timestamp)) {
2501 parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2504 /* FIXME: Would it be more efficient to make a subbuffer instead? */
2505 outbuf = gst_adapter_take_buffer (parse->priv->adapter, fsize);
2506 outbuf = gst_buffer_make_writable (outbuf);
2508 /* Subclass may want to know the data offset */
2509 GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2510 parse->priv->offset += fsize;
2511 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2512 GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
2514 frame->buffer = outbuf;
2515 ret = gst_base_parse_handle_and_push_frame (parse, bclass, frame);
2516 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2518 if (ret != GST_FLOW_OK) {
2519 GST_LOG_OBJECT (parse, "push returned %d", ret);
2525 GST_LOG_OBJECT (parse, "chain leaving");
2531 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2532 ("min_size evolution %d -> %d; breaking to avoid looping",
2533 old_min_size, min_size));
2534 return GST_FLOW_ERROR;
2538 /* pull @size bytes at current offset,
2539 * i.e. at least try to and possibly return a shorter buffer if near the end */
2540 static GstFlowReturn
2541 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2542 GstBuffer ** buffer)
2544 GstFlowReturn ret = GST_FLOW_OK;
2546 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2548 /* Caching here actually makes much less difference than one would expect.
2549 * We do it mainly to avoid pulling buffers of 1 byte all the time */
2550 if (parse->priv->cache) {
2551 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2552 gint cache_size = gst_buffer_get_size (parse->priv->cache);
2554 if (cache_offset <= parse->priv->offset &&
2555 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2556 *buffer = gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL,
2557 parse->priv->offset - cache_offset, size);
2558 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2561 /* not enough data in the cache, free cache and get a new one */
2562 gst_buffer_unref (parse->priv->cache);
2563 parse->priv->cache = NULL;
2566 /* refill the cache */
2568 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2569 64 * 1024), &parse->priv->cache);
2570 if (ret != GST_FLOW_OK) {
2571 parse->priv->cache = NULL;
2575 if (gst_buffer_get_size (parse->priv->cache) >= size) {
2577 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0,
2579 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2583 /* Not possible to get enough data, try a last time with
2584 * requesting exactly the size we need */
2585 gst_buffer_unref (parse->priv->cache);
2586 parse->priv->cache = NULL;
2588 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2589 &parse->priv->cache);
2591 if (ret != GST_FLOW_OK) {
2592 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2597 if (gst_buffer_get_size (parse->priv->cache) < size) {
2598 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2599 G_GUINT64_FORMAT ": wanted %u bytes, got %" G_GSIZE_FORMAT " bytes",
2600 parse->priv->offset, size, gst_buffer_get_size (parse->priv->cache));
2602 *buffer = parse->priv->cache;
2603 parse->priv->cache = NULL;
2609 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0, size);
2610 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2615 static GstFlowReturn
2616 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2619 GstClockTime ts = 0;
2623 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2624 ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2625 parse->priv->last_offset);
2627 if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2628 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2629 GST_TIME_ARGS (parse->segment.start));
2634 /* last fragment started at last_offset / last_ts;
2635 * seek back 10s capped at 1MB */
2636 if (parse->priv->last_ts >= 10 * GST_SECOND)
2637 ts = parse->priv->last_ts - 10 * GST_SECOND;
2638 /* if we are exact now, we will be more so going backwards */
2639 if (parse->priv->exact_position) {
2640 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2642 if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2643 GST_FORMAT_BYTES, &offset)) {
2644 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2647 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2648 parse->priv->last_offset - 1024);
2649 offset = MAX (0, offset);
2651 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2653 parse->priv->offset = offset;
2655 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2657 if (ret != GST_FLOW_OK)
2660 /* offset will increase again as fragment is processed/parsed */
2661 parse->priv->last_offset = offset;
2663 gst_adapter_push (parse->priv->adapter, buffer);
2664 ret = gst_base_parse_process_fragment (parse, FALSE);
2665 if (ret != GST_FLOW_OK)
2668 /* force previous fragment */
2669 parse->priv->offset = -1;
2676 * pull and scan for next frame starting from current offset
2677 * ajusts sync, drain and offset going along */
2678 static GstFlowReturn
2679 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2680 GstBaseParseFrame * frame, gboolean full)
2682 GstBuffer *buffer, *outbuf;
2683 GstFlowReturn ret = GST_FLOW_OK;
2684 guint fsize = 1, min_size, old_min_size = 0;
2687 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2689 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2690 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2692 /* let's make this efficient for all subclass once and for all;
2693 * maybe it does not need this much, but in the latter case, we know we are
2694 * in pull mode here and might as well try to read and supply more anyway
2695 * (so does the buffer caching mechanism) */
2701 min_size = MAX (parse->priv->min_frame_size, fsize);
2702 /* loop safety check */
2703 if (G_UNLIKELY (old_min_size >= min_size))
2705 old_min_size = min_size;
2707 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2708 if (ret != GST_FLOW_OK)
2711 if (parse->priv->discont) {
2712 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2713 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2716 /* if we got a short read, inform subclass we are draining leftover
2717 * and no more is to be expected */
2718 if (gst_buffer_get_size (buffer) < min_size)
2719 parse->priv->drain = TRUE;
2721 if (parse->priv->detecting) {
2722 ret = klass->detect (parse, buffer);
2723 if (ret == GST_FLOW_NOT_NEGOTIATED) {
2724 /* If draining we error out, otherwise request a buffer
2726 if (parse->priv->drain) {
2727 gst_buffer_unref (buffer);
2728 GST_ERROR_OBJECT (parse, "Failed to detect format but draining");
2729 return GST_FLOW_ERROR;
2732 gst_buffer_unref (buffer);
2735 } else if (ret != GST_FLOW_OK) {
2736 gst_buffer_unref (buffer);
2737 GST_ERROR_OBJECT (parse, "detect() returned %s",
2738 gst_flow_get_name (ret));
2742 /* Else handle this buffer normally */
2746 gst_base_parse_frame_update (parse, frame, buffer);
2747 res = klass->check_valid_frame (parse, frame, &fsize, &skip);
2748 gst_buffer_replace (&frame->buffer, NULL);
2750 parse->priv->drain = FALSE;
2751 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2754 parse->priv->drain = FALSE;
2758 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2759 if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2760 /* reverse playback, and no frames found yet, so we are skipping
2761 * the leading part of a fragment, which may form the tail of
2762 * fragment coming later, hopefully subclass skips efficiently ... */
2763 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, 0, skip);
2764 parse->priv->buffers_pending =
2765 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2768 parse->priv->offset += skip;
2769 if (!parse->priv->discont)
2770 parse->priv->sync_offset = parse->priv->offset;
2771 parse->priv->discont = TRUE;
2772 /* something changed at least; nullify loop check */
2773 if (fsize == G_MAXUINT)
2774 fsize = old_min_size + 64 * 1024;
2777 /* skip == 0 should imply subclass set min_size to need more data;
2778 * we check this shortly */
2779 GST_DEBUG_OBJECT (parse, "finding sync...");
2780 gst_buffer_unref (buffer);
2781 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2786 /* Does the subclass want to skip too? */
2788 parse->priv->offset += skip;
2792 if (fsize + skip <= gst_buffer_get_size (buffer)) {
2793 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, skip, fsize);
2794 GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2795 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2796 gst_buffer_unref (buffer);
2798 gst_buffer_unref (buffer);
2799 ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2800 if (ret != GST_FLOW_OK)
2802 if (gst_buffer_get_size (outbuf) < fsize) {
2803 gst_buffer_unref (outbuf);
2808 parse->priv->offset += fsize;
2810 frame->buffer = outbuf;
2818 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2819 ("min_size evolution %d -> %d; breaking to avoid looping",
2820 old_min_size, min_size));
2821 return GST_FLOW_ERROR;
2825 /* Loop that is used in pull mode to retrieve data from upstream */
2827 gst_base_parse_loop (GstPad * pad)
2829 GstBaseParse *parse;
2830 GstBaseParseClass *klass;
2831 GstFlowReturn ret = GST_FLOW_OK;
2832 GstBaseParseFrame frame;
2834 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2835 klass = GST_BASE_PARSE_GET_CLASS (parse);
2837 /* reverse playback:
2838 * first fragment (closest to stop time) is handled normally below,
2839 * then we pull in fragments going backwards */
2840 if (parse->segment.rate < 0.0) {
2841 /* check if we jumped back to a previous fragment,
2842 * which is a post-first fragment */
2843 if (parse->priv->offset < 0) {
2844 ret = gst_base_parse_handle_previous_fragment (parse);
2849 gst_base_parse_frame_init (&frame);
2850 ret = gst_base_parse_scan_frame (parse, klass, &frame, TRUE);
2851 if (ret != GST_FLOW_OK)
2854 /* This always cleans up frame, even if error occurs */
2855 ret = gst_base_parse_handle_and_push_frame (parse, klass, &frame);
2857 /* eat expected eos signalling past segment in reverse playback */
2858 if (parse->segment.rate < 0.0 && ret == GST_FLOW_EOS &&
2859 parse->segment.position >= parse->segment.stop) {
2860 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2861 /* push what was accumulated during loop run */
2862 gst_base_parse_process_fragment (parse, TRUE);
2863 /* force previous fragment */
2864 parse->priv->offset = -1;
2869 if (ret == GST_FLOW_EOS)
2871 else if (ret != GST_FLOW_OK)
2874 gst_object_unref (parse);
2881 GST_DEBUG_OBJECT (parse, "eos");
2886 gboolean push_eos = FALSE;
2888 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2889 gst_flow_get_name (ret));
2890 gst_pad_pause_task (parse->sinkpad);
2892 if (ret == GST_FLOW_EOS) {
2893 /* handle end-of-stream/segment */
2894 if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2897 if ((stop = parse->segment.stop) == -1)
2898 stop = parse->segment.duration;
2900 GST_DEBUG_OBJECT (parse, "sending segment_done");
2902 gst_element_post_message
2903 (GST_ELEMENT_CAST (parse),
2904 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2905 GST_FORMAT_TIME, stop));
2907 /* If we STILL have zero frames processed, fire an error */
2908 if (parse->priv->framecount == 0) {
2909 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2910 ("No valid frames found before end of stream"), (NULL));
2914 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
2915 /* for fatal errors we post an error message, wrong-state is
2916 * not fatal because it happens due to flushes and only means
2917 * that we should stop now. */
2918 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2919 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2923 /* newsegment before eos */
2924 if (parse->priv->pending_segment) {
2925 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
2926 parse->priv->pending_segment = NULL;
2928 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2930 gst_object_unref (parse);
2935 gst_base_parse_sink_activate (GstPad * sinkpad, GstObject * parent)
2937 GstBaseParse *parse;
2938 gboolean result = TRUE;
2942 parse = GST_BASE_PARSE (parent);
2944 GST_DEBUG_OBJECT (parse, "sink activate");
2946 query = gst_query_new_scheduling ();
2947 result = gst_pad_peer_query (sinkpad, query);
2949 pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL);
2953 gst_query_unref (query);
2956 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2957 result = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
2959 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
2960 result = gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
2963 GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
2968 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
2970 GstBaseParseClass *klass;
2971 gboolean result = TRUE;
2973 GST_DEBUG_OBJECT (parse, "activate %d", active);
2975 klass = GST_BASE_PARSE_GET_CLASS (parse);
2978 if (parse->priv->pad_mode == GST_PAD_MODE_NONE && klass->start)
2979 result = klass->start (parse);
2981 /* If the subclass implements ::detect we want to
2982 * call it for the first buffers now */
2983 parse->priv->detecting = (klass->detect != NULL);
2985 /* We must make sure streaming has finished before resetting things
2986 * and calling the ::stop vfunc */
2987 GST_PAD_STREAM_LOCK (parse->sinkpad);
2988 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2990 if (parse->priv->pad_mode != GST_PAD_MODE_NONE && klass->stop)
2991 result = klass->stop (parse);
2993 parse->priv->pad_mode = GST_PAD_MODE_NONE;
2995 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
3000 gst_base_parse_sink_activate_mode (GstPad * pad, GstObject * parent,
3001 GstPadMode mode, gboolean active)
3003 gboolean result = TRUE;
3004 GstBaseParse *parse;
3006 parse = GST_BASE_PARSE (parent);
3008 GST_DEBUG_OBJECT (parse, "sink activate mode %d, %d", mode, active);
3010 result = gst_base_parse_activate (parse, active);
3014 case GST_PAD_MODE_PULL:
3016 parse->priv->pending_segment =
3017 gst_event_new_segment (&parse->segment);
3019 gst_pad_start_task (pad, (GstTaskFunction) gst_base_parse_loop,
3022 result &= gst_pad_stop_task (pad);
3030 parse->priv->pad_mode = active ? mode : GST_PAD_MODE_NONE;
3032 GST_DEBUG_OBJECT (parse, "sink activate return: %d", result);
3038 * gst_base_parse_set_duration:
3039 * @parse: #GstBaseParse.
3041 * @duration: duration value.
3042 * @interval: how often to update the duration estimate based on bitrate, or 0.
3044 * Sets the duration of the currently playing media. Subclass can use this
3045 * when it is able to determine duration and/or notices a change in the media
3046 * duration. Alternatively, if @interval is non-zero (default), then stream
3047 * duration is determined based on estimated bitrate, and updated every @interval
3053 gst_base_parse_set_duration (GstBaseParse * parse,
3054 GstFormat fmt, gint64 duration, gint interval)
3056 g_return_if_fail (parse != NULL);
3058 if (parse->priv->upstream_has_duration) {
3059 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
3063 if (duration != parse->priv->duration) {
3066 m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
3067 gst_element_post_message (GST_ELEMENT (parse), m);
3069 /* TODO: what about duration tag? */
3071 parse->priv->duration = duration;
3072 parse->priv->duration_fmt = fmt;
3073 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
3074 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
3075 if (interval != 0) {
3076 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
3080 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
3081 parse->priv->update_interval = interval;
3087 * gst_base_parse_set_average_bitrate:
3088 * @parse: #GstBaseParse.
3089 * @bitrate: average bitrate in bits/second
3091 * Optionally sets the average bitrate detected in media (if non-zero),
3092 * e.g. based on metadata, as it will be posted to the application.
3094 * By default, announced average bitrate is estimated. The average bitrate
3095 * is used to estimate the total duration of the stream and to estimate
3096 * a seek position, if there's no index and the format is syncable
3097 * (see gst_base_parse_set_syncable()).
3102 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
3104 parse->priv->bitrate = bitrate;
3105 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
3109 * gst_base_parse_set_min_frame_size:
3110 * @parse: #GstBaseParse.
3111 * @min_size: Minimum size of the data that this base class should give to
3114 * Subclass can use this function to tell the base class that it needs to
3115 * give at least #min_size buffers.
3120 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
3122 g_return_if_fail (parse != NULL);
3124 parse->priv->min_frame_size = min_size;
3125 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
3129 * gst_base_parse_set_frame_rate:
3130 * @parse: the #GstBaseParse to set
3131 * @fps_num: frames per second (numerator).
3132 * @fps_den: frames per second (denominator).
3133 * @lead_in: frames needed before a segment for subsequent decode
3134 * @lead_out: frames needed after a segment
3136 * If frames per second is configured, parser can take care of buffer duration
3137 * and timestamping. When performing segment clipping, or seeking to a specific
3138 * location, a corresponding decoder might need an initial @lead_in and a
3139 * following @lead_out number of frames to ensure the desired segment is
3140 * entirely filled upon decoding.
3145 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
3146 guint fps_den, guint lead_in, guint lead_out)
3148 g_return_if_fail (parse != NULL);
3150 parse->priv->fps_num = fps_num;
3151 parse->priv->fps_den = fps_den;
3152 if (!fps_num || !fps_den) {
3153 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
3155 fps_num = fps_den = 0;
3156 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
3157 parse->priv->lead_in = parse->priv->lead_out = 0;
3158 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
3160 parse->priv->frame_duration =
3161 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
3162 parse->priv->lead_in = lead_in;
3163 parse->priv->lead_out = lead_out;
3164 parse->priv->lead_in_ts =
3165 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
3166 parse->priv->lead_out_ts =
3167 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
3168 /* aim for about 1.5s to estimate duration */
3169 if (parse->priv->update_interval < 0) {
3170 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
3171 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
3172 parse->priv->update_interval);
3175 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
3176 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
3177 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
3178 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
3179 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
3180 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
3184 * gst_base_parse_set_has_timing_info:
3185 * @parse: a #GstBaseParse
3186 * @has_timing: whether frames carry timing information
3188 * Set if frames carry timing information which the subclass can (generally)
3189 * parse and provide. In particular, intrinsic (rather than estimated) time
3190 * can be obtained following a seek.
3195 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3197 parse->priv->has_timing_info = has_timing;
3198 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3202 * gst_base_parse_set_syncable:
3203 * @parse: a #GstBaseParse
3204 * @syncable: set if frame starts can be identified
3206 * Set if frame starts can be identified. This is set by default and
3207 * determines whether seeking based on bitrate averages
3208 * is possible for a format/stream.
3213 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3215 parse->priv->syncable = syncable;
3216 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3220 * gst_base_parse_set_passthrough:
3221 * @parse: a #GstBaseParse
3222 * @passthrough: %TRUE if parser should run in passthrough mode
3224 * Set if the nature of the format or configuration does not allow (much)
3225 * parsing, and the parser should operate in passthrough mode (which only
3226 * applies when operating in push mode). That is, incoming buffers are
3227 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3228 * callbacks will be invoked, but @pre_push_frame will still be invoked,
3229 * so subclass can perform as much or as little is appropriate for
3230 * passthrough semantics in @pre_push_frame.
3235 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3237 parse->priv->passthrough = passthrough;
3238 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3242 * gst_base_parse_set_latency:
3243 * @parse: a #GstBaseParse
3244 * @min_latency: minimum parse latency
3245 * @max_latency: maximum parse latency
3247 * Sets the minimum and maximum (which may likely be equal) latency introduced
3248 * by the parsing process. If there is such a latency, which depends on the
3249 * particular parsing of the format, it typically corresponds to 1 frame duration.
3254 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3255 GstClockTime max_latency)
3257 GST_OBJECT_LOCK (parse);
3258 parse->priv->min_latency = min_latency;
3259 parse->priv->max_latency = max_latency;
3260 GST_OBJECT_UNLOCK (parse);
3261 GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3262 GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3263 GST_TIME_ARGS (max_latency));
3267 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3268 GstClockTime * duration)
3270 gboolean res = FALSE;
3272 g_return_val_if_fail (duration != NULL, FALSE);
3274 *duration = GST_CLOCK_TIME_NONE;
3275 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3276 GST_LOG_OBJECT (parse, "using provided duration");
3277 *duration = parse->priv->duration;
3279 } else if (parse->priv->duration != -1) {
3280 GST_LOG_OBJECT (parse, "converting provided duration");
3281 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3282 parse->priv->duration, format, (gint64 *) duration);
3283 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3284 GST_LOG_OBJECT (parse, "using estimated duration");
3285 *duration = parse->priv->estimated_duration;
3289 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3290 GST_TIME_ARGS (*duration));
3295 gst_base_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
3297 GstBaseParse *parse;
3298 gboolean res = FALSE;
3300 parse = GST_BASE_PARSE (parent);
3302 GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3304 switch (GST_QUERY_TYPE (query)) {
3305 case GST_QUERY_POSITION:
3310 GST_DEBUG_OBJECT (parse, "position query");
3311 gst_query_parse_position (query, &format, NULL);
3313 /* try upstream first */
3314 res = gst_pad_query_default (pad, parent, query);
3316 /* Fall back on interpreting segment */
3317 GST_OBJECT_LOCK (parse);
3318 if (format == GST_FORMAT_BYTES) {
3319 dest_value = parse->priv->offset;
3321 } else if (format == parse->segment.format &&
3322 GST_CLOCK_TIME_IS_VALID (parse->segment.position)) {
3323 dest_value = gst_segment_to_stream_time (&parse->segment,
3324 parse->segment.format, parse->segment.position);
3327 GST_OBJECT_UNLOCK (parse);
3329 /* no precise result, upstream no idea either, then best estimate */
3330 /* priv->offset is updated in both PUSH/PULL modes */
3331 res = gst_base_parse_convert (parse,
3332 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3335 gst_query_set_position (query, format, dest_value);
3339 case GST_QUERY_DURATION:
3342 GstClockTime duration;
3344 GST_DEBUG_OBJECT (parse, "duration query");
3345 gst_query_parse_duration (query, &format, NULL);
3347 /* consult upstream */
3348 res = gst_pad_query_default (pad, parent, query);
3350 /* otherwise best estimate from us */
3352 res = gst_base_parse_get_duration (parse, format, &duration);
3354 gst_query_set_duration (query, format, duration);
3358 case GST_QUERY_SEEKING:
3361 GstClockTime duration = GST_CLOCK_TIME_NONE;
3362 gboolean seekable = FALSE;
3364 GST_DEBUG_OBJECT (parse, "seeking query");
3365 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3367 /* consult upstream */
3368 res = gst_pad_query_default (pad, parent, query);
3370 /* we may be able to help if in TIME */
3371 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3372 gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3373 /* already OK if upstream takes care */
3374 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3376 if (!(res && seekable)) {
3377 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3378 || duration == -1) {
3379 /* seekable if we still have a chance to get duration later on */
3381 parse->priv->upstream_seekable && parse->priv->update_interval;
3383 seekable = parse->priv->upstream_seekable;
3384 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3387 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3393 case GST_QUERY_FORMATS:
3394 gst_query_set_formatsv (query, 3, fmtlist);
3397 case GST_QUERY_CONVERT:
3399 GstFormat src_format, dest_format;
3400 gint64 src_value, dest_value;
3402 gst_query_parse_convert (query, &src_format, &src_value,
3403 &dest_format, &dest_value);
3405 res = gst_base_parse_convert (parse, src_format, src_value,
3406 dest_format, &dest_value);
3408 gst_query_set_convert (query, src_format, src_value,
3409 dest_format, dest_value);
3413 case GST_QUERY_LATENCY:
3415 if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3417 GstClockTime min_latency, max_latency;
3419 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3420 GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3421 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3422 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3424 GST_OBJECT_LOCK (parse);
3425 /* add our latency */
3426 if (min_latency != -1)
3427 min_latency += parse->priv->min_latency;
3428 if (max_latency != -1)
3429 max_latency += parse->priv->max_latency;
3430 GST_OBJECT_UNLOCK (parse);
3432 gst_query_set_latency (query, live, min_latency, max_latency);
3437 res = gst_pad_query_default (pad, parent, query);
3443 /* scans for a cluster start from @pos,
3444 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3445 static GstFlowReturn
3446 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3447 GstClockTime * time, GstClockTime * duration)
3449 GstBaseParseClass *klass;
3451 gboolean orig_drain, orig_discont;
3452 GstFlowReturn ret = GST_FLOW_OK;
3453 GstBuffer *buf = NULL;
3454 GstBaseParseFrame frame;
3456 g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3457 g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3458 g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3460 klass = GST_BASE_PARSE_GET_CLASS (parse);
3462 *time = GST_CLOCK_TIME_NONE;
3463 *duration = GST_CLOCK_TIME_NONE;
3466 orig_offset = parse->priv->offset;
3467 orig_discont = parse->priv->discont;
3468 orig_drain = parse->priv->drain;
3470 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3471 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3473 gst_base_parse_frame_init (&frame);
3475 /* jump elsewhere and locate next frame */
3476 parse->priv->offset = *pos;
3477 ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3478 if (ret != GST_FLOW_OK)
3482 GST_LOG_OBJECT (parse,
3483 "peek parsing frame at offset %" G_GUINT64_FORMAT
3484 " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
3485 GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf),
3486 gst_buffer_get_size (buf));
3488 /* get offset first, subclass parsing might dump other stuff in there */
3489 *pos = GST_BUFFER_OFFSET (buf);
3490 ret = klass->parse_frame (parse, &frame);
3493 /* but it should provide proper time */
3494 *time = GST_BUFFER_TIMESTAMP (buf);
3495 *duration = GST_BUFFER_DURATION (buf);
3497 gst_base_parse_frame_free (&frame);
3499 GST_LOG_OBJECT (parse,
3500 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3501 GST_TIME_ARGS (*time), *pos);
3505 parse->priv->offset = orig_offset;
3506 parse->priv->discont = orig_discont;
3507 parse->priv->drain = orig_drain;
3512 /* bisect and scan through file for frame starting before @time,
3513 * returns OK and @time/@offset if found, NONE and/or error otherwise
3514 * If @time == G_MAXINT64, scan for duration ( == last frame) */
3515 static GstFlowReturn
3516 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3519 GstFlowReturn ret = GST_FLOW_OK;
3520 gint64 lpos, hpos, newpos;
3521 GstClockTime time, ltime, htime, newtime, dur;
3522 gboolean cont = TRUE;
3523 const GstClockTime tolerance = TARGET_DIFFERENCE;
3524 const guint chunk = 4 * 1024;
3526 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3527 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3529 /* TODO also make keyframe aware if useful some day */
3544 /* do not know at first */
3546 *_time = GST_CLOCK_TIME_NONE;
3548 /* need initial positions; start and end */
3549 lpos = parse->priv->first_frame_offset;
3550 ltime = parse->priv->first_frame_ts;
3551 htime = parse->priv->duration;
3552 hpos = parse->priv->upstream_size;
3554 /* check preconditions are satisfied;
3555 * start and end are needed, except for special case where we scan for
3556 * last frame to determine duration */
3557 if (parse->priv->pad_mode != GST_PAD_MODE_PULL || !hpos ||
3558 !GST_CLOCK_TIME_IS_VALID (ltime) ||
3559 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3563 /* shortcut cases */
3566 } else if (time < ltime + tolerance) {
3570 } else if (time >= htime) {
3576 while (htime > ltime && cont) {
3577 GST_LOG_OBJECT (parse,
3578 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3579 GST_TIME_ARGS (ltime));
3580 GST_LOG_OBJECT (parse,
3581 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3582 GST_TIME_ARGS (htime));
3583 if (G_UNLIKELY (time == G_MAXINT64)) {
3585 } else if (G_LIKELY (hpos > lpos)) {
3587 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3590 /* should mean lpos == hpos, since lpos <= hpos is invariant */
3592 /* we check this case once, but not forever, so break loop */
3597 newpos = CLAMP (newpos, lpos, hpos);
3598 GST_LOG_OBJECT (parse,
3599 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3600 GST_TIME_ARGS (time), newpos);
3602 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3603 if (ret == GST_FLOW_EOS) {
3604 /* heuristic HACK */
3605 hpos = MAX (lpos, hpos - chunk);
3607 } else if (ret != GST_FLOW_OK) {
3611 if (newtime == -1 || newpos == -1) {
3612 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3616 if (G_UNLIKELY (time == G_MAXINT64)) {
3619 if (GST_CLOCK_TIME_IS_VALID (dur))
3622 } else if (newtime > time) {
3624 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3626 } else if (newtime + tolerance > time) {
3627 /* close enough undershoot */
3631 } else if (newtime < ltime) {
3632 /* so a position beyond lpos resulted in earlier time than ltime ... */
3633 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3636 /* undershoot too far */
3637 newpos += newpos == lpos ? chunk : 0;
3638 lpos = CLAMP (newpos, lpos, hpos);
3644 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3645 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3650 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3651 gboolean before, GstClockTime * _ts)
3653 gint64 bytes = 0, ts = 0;
3654 GstIndexEntry *entry = NULL;
3656 if (time == GST_CLOCK_TIME_NONE) {
3662 g_static_mutex_lock (&parse->priv->index_lock);
3663 if (parse->priv->index) {
3664 /* Let's check if we have an index entry for that time */
3665 entry = gst_index_get_assoc_entry (parse->priv->index,
3666 parse->priv->index_id,
3667 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3668 GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3672 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3673 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3675 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3676 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3677 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3679 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3680 GST_TIME_ARGS (time));
3683 ts = GST_CLOCK_TIME_NONE;
3686 g_static_mutex_unlock (&parse->priv->index_lock);
3695 /* returns TRUE if seek succeeded */
3697 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3702 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3703 gboolean flush, update, res = TRUE, accurate;
3704 gint64 cur, stop, seekpos, seekstop;
3705 GstSegment seeksegment = { 0, };
3706 GstClockTime start_ts;
3708 gst_event_parse_seek (event, &rate, &format, &flags,
3709 &cur_type, &cur, &stop_type, &stop);
3711 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3712 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3713 GST_TIME_FORMAT, gst_format_get_name (format), rate,
3714 cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3716 /* no negative rates in push mode */
3717 if (rate < 0.0 && parse->priv->pad_mode == GST_PAD_MODE_PUSH)
3720 if (cur_type != GST_SEEK_TYPE_SET ||
3721 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3724 /* For any format other than TIME, see if upstream handles
3725 * it directly or fail. For TIME, try upstream, but do it ourselves if
3726 * it fails upstream */
3727 if (format != GST_FORMAT_TIME) {
3728 /* default action delegates to upstream */
3732 gst_event_ref (event);
3733 if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3738 /* get flush flag */
3739 flush = flags & GST_SEEK_FLAG_FLUSH;
3741 /* copy segment, we need this because we still need the old
3742 * segment when we close the current segment. */
3743 gst_segment_copy_into (&parse->segment, &seeksegment);
3745 GST_DEBUG_OBJECT (parse, "configuring seek");
3746 gst_segment_do_seek (&seeksegment, rate, format, flags,
3747 cur_type, cur, stop_type, stop, &update);
3749 /* accurate seeking implies seek tables are used to obtain position,
3750 * and the requested segment is maintained exactly, not adjusted any way */
3751 accurate = flags & GST_SEEK_FLAG_ACCURATE;
3753 /* maybe we can be accurate for (almost) free */
3754 gst_base_parse_find_offset (parse, seeksegment.position, TRUE, &start_ts);
3755 if (seeksegment.position <= start_ts + TARGET_DIFFERENCE) {
3756 GST_DEBUG_OBJECT (parse, "accurate seek possible");
3760 GstClockTime startpos = seeksegment.position;
3762 /* accurate requested, so ... seek a bit before target */
3763 if (startpos < parse->priv->lead_in_ts)
3766 startpos -= parse->priv->lead_in_ts;
3767 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3768 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3771 start_ts = seeksegment.position;
3772 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.position,
3773 GST_FORMAT_BYTES, &seekpos))
3774 goto convert_failed;
3775 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3776 GST_FORMAT_BYTES, &seekstop))
3777 goto convert_failed;
3780 GST_DEBUG_OBJECT (parse,
3781 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3783 GST_DEBUG_OBJECT (parse,
3784 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3785 seeksegment.stop, seekstop);
3787 if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
3790 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3793 if (parse->srcpad) {
3794 GST_DEBUG_OBJECT (parse, "sending flush start");
3795 gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3796 /* unlock upstream pull_range */
3797 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3800 gst_pad_pause_task (parse->sinkpad);
3803 /* we should now be able to grab the streaming thread because we stopped it
3804 * with the above flush/pause code */
3805 GST_PAD_STREAM_LOCK (parse->sinkpad);
3807 /* save current position */
3808 last_stop = parse->segment.position;
3809 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3812 /* now commit to new position */
3814 /* prepare for streaming again */
3816 GST_DEBUG_OBJECT (parse, "sending flush stop");
3817 gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop (TRUE));
3818 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop (TRUE));
3819 gst_base_parse_clear_queues (parse);
3821 /* keep track of our position */
3822 seeksegment.base = gst_segment_to_running_time (&seeksegment,
3823 seeksegment.format, parse->segment.position);
3826 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3828 /* store the newsegment event so it can be sent from the streaming thread. */
3829 if (parse->priv->pending_segment)
3830 gst_event_unref (parse->priv->pending_segment);
3832 /* This will be sent later in _loop() */
3833 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
3835 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3836 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3837 ", pos = %" GST_TIME_FORMAT, format,
3838 GST_TIME_ARGS (parse->segment.start),
3839 GST_TIME_ARGS (parse->segment.stop),
3840 GST_TIME_ARGS (parse->segment.start));
3842 /* one last chance in pull mode to stay accurate;
3843 * maybe scan and subclass can find where to go */
3846 GstClockTime ts = seeksegment.position;
3848 gst_base_parse_locate_time (parse, &ts, &scanpos);
3852 /* running collected index now consists of several intervals,
3853 * so optimized check no longer possible */
3854 parse->priv->index_last_valid = FALSE;
3855 parse->priv->index_last_offset = 0;
3856 parse->priv->index_last_ts = 0;
3860 /* mark discont if we are going to stream from another position. */
3861 if (seekpos != parse->priv->offset) {
3862 GST_DEBUG_OBJECT (parse,
3863 "mark DISCONT, we did a seek to another position");
3864 parse->priv->offset = seekpos;
3865 parse->priv->last_offset = seekpos;
3866 parse->priv->seen_keyframe = FALSE;
3867 parse->priv->discont = TRUE;
3868 parse->priv->next_ts = start_ts;
3869 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3870 parse->priv->sync_offset = seekpos;
3871 parse->priv->exact_position = accurate;
3874 /* Start streaming thread if paused */
3875 gst_pad_start_task (parse->sinkpad,
3876 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3878 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3883 GstEvent *new_event;
3884 GstBaseParseSeek *seek;
3885 GstSeekFlags flags = (flush ? GST_SEEK_FLAG_FLUSH : GST_SEEK_FLAG_NONE);
3887 /* The only thing we need to do in PUSH-mode is to send the
3888 seek event (in bytes) to upstream. Segment / flush handling happens
3889 in corresponding src event handlers */
3890 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3891 if (seekstop >= 0 && seekstop <= seekpos)
3893 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
3894 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3896 /* store segment info so its precise details can be reconstructed when
3897 * receiving newsegment;
3898 * this matters for all details when accurate seeking,
3899 * is most useful to preserve NONE stop time otherwise */
3900 seek = g_new0 (GstBaseParseSeek, 1);
3901 seek->segment = seeksegment;
3902 seek->accurate = accurate;
3903 seek->offset = seekpos;
3904 seek->start_ts = start_ts;
3905 GST_OBJECT_LOCK (parse);
3906 /* less optimal, but preserves order */
3907 parse->priv->pending_seeks =
3908 g_slist_append (parse->priv->pending_seeks, seek);
3909 GST_OBJECT_UNLOCK (parse);
3911 res = gst_pad_push_event (parse->sinkpad, new_event);
3914 GST_OBJECT_LOCK (parse);
3915 parse->priv->pending_seeks =
3916 g_slist_remove (parse->priv->pending_seeks, seek);
3917 GST_OBJECT_UNLOCK (parse);
3923 /* handled event is ours to free */
3925 gst_event_unref (event);
3931 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
3937 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3943 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3949 /* Checks if bitrates are available from upstream tags so that we don't
3950 * override them later
3953 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
3955 GstTagList *taglist = NULL;
3958 gst_event_parse_tag (event, &taglist);
3960 if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
3961 GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
3962 parse->priv->post_min_bitrate = FALSE;
3964 if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
3965 GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
3966 parse->priv->post_avg_bitrate = FALSE;
3968 if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
3969 GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
3970 parse->priv->post_max_bitrate = FALSE;
3975 gst_base_parse_set_index (GstElement * element, GstIndex * index)
3977 GstBaseParse *parse = GST_BASE_PARSE (element);
3979 g_static_mutex_lock (&parse->priv->index_lock);
3980 if (parse->priv->index)
3981 gst_object_unref (parse->priv->index);
3983 parse->priv->index = gst_object_ref (index);
3984 gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
3985 &parse->priv->index_id);
3986 parse->priv->own_index = FALSE;
3988 parse->priv->index = NULL;
3990 g_static_mutex_unlock (&parse->priv->index_lock);
3994 gst_base_parse_get_index (GstElement * element)
3996 GstBaseParse *parse = GST_BASE_PARSE (element);
3997 GstIndex *result = NULL;
3999 g_static_mutex_lock (&parse->priv->index_lock);
4000 if (parse->priv->index)
4001 result = gst_object_ref (parse->priv->index);
4002 g_static_mutex_unlock (&parse->priv->index_lock);
4007 static GstStateChangeReturn
4008 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
4010 GstBaseParse *parse;
4011 GstStateChangeReturn result;
4013 parse = GST_BASE_PARSE (element);
4015 switch (transition) {
4016 case GST_STATE_CHANGE_READY_TO_PAUSED:
4017 /* If this is our own index destroy it as the
4018 * old entries might be wrong for the new stream */
4019 g_static_mutex_lock (&parse->priv->index_lock);
4020 if (parse->priv->own_index) {
4021 gst_object_unref (parse->priv->index);
4022 parse->priv->index = NULL;
4023 parse->priv->own_index = FALSE;
4026 /* If no index was created, generate one */
4027 if (G_UNLIKELY (!parse->priv->index)) {
4028 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
4030 parse->priv->index = gst_index_factory_make ("memindex");
4031 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
4032 &parse->priv->index_id);
4033 parse->priv->own_index = TRUE;
4035 g_static_mutex_unlock (&parse->priv->index_lock);
4041 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4043 switch (transition) {
4044 case GST_STATE_CHANGE_PAUSED_TO_READY:
4045 gst_base_parse_reset (parse);