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 calls @start to inform subclass that data processing is
57 * GstBaseParse class calls @set_sink_caps to inform the subclass about
58 * incoming sinkpad caps. Subclass could already set the srcpad caps
59 * accordingly, but this might be delayed until calling
60 * gst_base_parse_finish_frame() with a non-queued frame.
63 * At least at this point subclass needs to tell the GstBaseParse class
64 * how big data chunks it wants to receive (min_frame_size). It can do
65 * this with gst_base_parse_set_min_frame_size().
68 * GstBaseParse class sets up appropriate data passing mode (pull/push)
69 * and starts to process the data.
75 * <title>Parsing phase</title>
77 * GstBaseParse gathers at least min_frame_size bytes of data either
78 * by pulling it from upstream or collecting buffers in an internal
82 * A buffer of (at least) min_frame_size bytes is passed to subclass with
83 * @handle_frame. Subclass checks the contents and can optionally
84 * return GST_FLOW_OK along with an amount of data to be skipped to find
85 * a valid frame (which will result in a subsequent DISCONT).
86 * If, otherwise, the buffer does not hold a complete frame,
87 * @handle_frame can merely return and will be called again when additional
88 * data is available. In push mode this amounts to an
89 * additional input buffer (thus minimal additional latency), in pull mode
90 * this amounts to some arbitrary reasonable buffer size increase.
91 * Of course, gst_base_parse_set_min_size() could also be used if a very
92 * specific known amount of additional data is required.
93 * If, however, the buffer holds a complete valid frame, it can pass
94 * the size of this frame to gst_base_parse_finish_frame().
95 * If acting as a converter, it can also merely indicate consumed input data
96 * while simultaneously providing custom output data.
97 * Note that baseclass performs some processing (such as tracking
98 * overall consumed data rate versus duration) for each finished frame,
99 * but other state is only updated upon each call to @handle_frame
100 * (such as tracking upstream input timestamp).
102 * Subclass is also responsible for setting the buffer metadata
103 * (e.g. buffer timestamp and duration, or keyframe if applicable).
104 * (although the latter can also be done by GstBaseParse if it is
105 * appropriately configured, see below). Frame is provided with
106 * timestamp derived from upstream (as much as generally possible),
107 * duration obtained from configuration (see below), and offset
108 * if meaningful (in pull mode).
110 * Note that @check_valid_frame might receive any small
111 * amount of input data when leftover data is being drained (e.g. at EOS).
114 * As part of finish frame processing,
115 * just prior to actually pushing the buffer in question,
116 * it is passed to @pre_push_frame which gives subclass yet one
117 * last chance to examine buffer metadata, or to send some custom (tag)
118 * events, or to perform custom (segment) filtering.
121 * During the parsing process GstBaseParseClass will handle both srcpad
122 * and sinkpad events. They will be passed to subclass if @event or
123 * @src_event callbacks have been provided.
128 * <itemizedlist><title>Shutdown phase</title>
130 * GstBaseParse class calls @stop to inform the subclass that data
131 * parsing will be stopped.
137 * Subclass is responsible for providing pad template caps for
138 * source and sink pads. The pads need to be named "sink" and "src". It also
139 * needs to set the fixed caps on srcpad, when the format is ensured (e.g.
140 * when base class calls subclass' @set_sink_caps function).
142 * This base class uses #GST_FORMAT_DEFAULT as a meaning of frames. So,
143 * subclass conversion routine needs to know that conversion from
144 * #GST_FORMAT_TIME to #GST_FORMAT_DEFAULT must return the
145 * frame number that can be found from the given byte position.
147 * GstBaseParse uses subclasses conversion methods also for seeking (or
148 * otherwise uses its own default one, see also below).
150 * Subclass @start and @stop functions will be called to inform the beginning
151 * and end of data processing.
153 * Things that subclass need to take care of:
155 * <listitem><para>Provide pad templates</para></listitem>
157 * Fixate the source pad caps when appropriate
160 * Inform base class how big data chunks should be retrieved. This is
161 * done with gst_base_parse_set_min_frame_size() function.
164 * Examine data chunks passed to subclass with @handle_frame and pass
165 * proper frame(s) to gst_base_parse_finish_frame(), and setting src pad
166 * caps and timestamps on frame.
168 * <listitem><para>Provide conversion functions</para></listitem>
170 * Update the duration information with gst_base_parse_set_duration()
173 * Optionally passthrough using gst_base_parse_set_passthrough()
176 * Configure various baseparse parameters using
177 * gst_base_parse_set_average_bitrate(), gst_base_parse_set_syncable()
178 * and gst_base_parse_set_frame_rate().
181 * In particular, if subclass is unable to determine a duration, but
182 * parsing (or specs) yields a frames per seconds rate, then this can be
183 * provided to GstBaseParse to enable it to cater for
184 * buffer time metadata (which will be taken from upstream as much as
185 * possible). Internally keeping track of frame durations and respective
186 * sizes that have been pushed provides GstBaseParse with an estimated
187 * bitrate. A default @convert (used if not overriden) will then use these
188 * rates to perform obvious conversions. These rates are also used to
189 * update (estimated) duration at regular frame intervals.
196 * - In push mode provide a queue of adapter-"queued" buffers for upstream
198 * - Queue buffers/events until caps are set
208 #include <gst/base/gstadapter.h>
210 #include "gstbaseparse.h"
212 /* FIXME: get rid of old GstIndex code */
213 #include "gstindex.h"
214 #include "gstindex.c"
215 #include "gstmemindex.c"
217 #define GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC (1 << 0)
219 #define MIN_FRAMES_TO_POST_BITRATE 10
220 #define TARGET_DIFFERENCE (20 * GST_SECOND)
222 GST_DEBUG_CATEGORY_STATIC (gst_base_parse_debug);
223 #define GST_CAT_DEFAULT gst_base_parse_debug
225 /* Supported formats */
226 static const GstFormat fmtlist[] = {
233 #define GST_BASE_PARSE_GET_PRIVATE(obj) \
234 (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_PARSE, GstBaseParsePrivate))
236 struct _GstBaseParsePrivate
243 GstFormat duration_fmt;
244 gint64 estimated_duration;
245 gint64 estimated_drift;
247 guint min_frame_size;
248 gboolean passthrough;
250 gboolean has_timing_info;
251 guint fps_num, fps_den;
252 gint update_interval;
254 guint lead_in, lead_out;
255 GstClockTime lead_in_ts, lead_out_ts;
256 GstClockTime min_latency, max_latency;
264 GstClockTime next_ts;
265 GstClockTime prev_ts;
266 GstClockTime frame_duration;
267 gboolean seen_keyframe;
273 guint64 data_bytecount;
274 guint64 acc_duration;
275 GstClockTime first_frame_ts;
276 gint64 first_frame_offset;
278 gboolean post_min_bitrate;
279 gboolean post_avg_bitrate;
280 gboolean post_max_bitrate;
284 guint posted_avg_bitrate;
286 /* frames/buffers that are queued and ready to go on OK */
287 GQueue queued_frames;
291 /* index entry storage, either ours or provided */
297 /* seek table entries only maintained if upstream is BYTE seekable */
298 gboolean upstream_seekable;
299 gboolean upstream_has_duration;
300 gint64 upstream_size;
301 /* minimum distance between two index entries */
302 GstClockTimeDiff idx_interval;
303 /* ts and offset of last entry added */
304 GstClockTime index_last_ts;
305 gint64 index_last_offset;
306 gboolean index_last_valid;
308 /* timestamps currently produced are accurate, e.g. started from 0 onwards */
309 gboolean exact_position;
310 /* seek events are temporarily kept to match them with newsegments */
311 GSList *pending_seeks;
313 /* reverse playback */
314 GSList *buffers_pending;
315 GSList *buffers_head;
316 GSList *buffers_queued;
317 GSList *buffers_send;
318 GstClockTime last_ts;
321 /* Pending serialized events */
322 GList *pending_events;
323 /* Newsegment event to be sent after SEEK */
324 gboolean pending_segment;
326 /* offset of last parsed frame/data */
328 /* force a new frame, regardless of offset */
330 /* whether we are merely scanning for a frame */
332 /* ... and resulting frame, if any */
333 GstBaseParseFrame *scanned_frame;
335 /* TRUE if we're still detecting the format, i.e.
336 * if ::detect() is still called for future buffers */
338 GList *detect_buffers;
339 guint detect_buffers_size;
342 typedef struct _GstBaseParseSeek
347 GstClockTime start_ts;
350 #define GST_BASE_PARSE_INDEX_LOCK(parse) \
351 g_mutex_lock (&parse->priv->index_lock);
352 #define GST_BASE_PARSE_INDEX_UNLOCK(parse) \
353 g_mutex_unlock (&parse->priv->index_lock);
355 static GstElementClass *parent_class = NULL;
357 static void gst_base_parse_class_init (GstBaseParseClass * klass);
358 static void gst_base_parse_init (GstBaseParse * parse,
359 GstBaseParseClass * klass);
362 gst_base_parse_get_type (void)
364 static volatile gsize base_parse_type = 0;
366 if (g_once_init_enter (&base_parse_type)) {
367 static const GTypeInfo base_parse_info = {
368 sizeof (GstBaseParseClass),
369 (GBaseInitFunc) NULL,
370 (GBaseFinalizeFunc) NULL,
371 (GClassInitFunc) gst_base_parse_class_init,
374 sizeof (GstBaseParse),
376 (GInstanceInitFunc) gst_base_parse_init,
380 _type = g_type_register_static (GST_TYPE_ELEMENT,
381 "GstBaseParse", &base_parse_info, G_TYPE_FLAG_ABSTRACT);
382 g_once_init_leave (&base_parse_type, _type);
384 return (GType) base_parse_type;
387 static void gst_base_parse_finalize (GObject * object);
389 static GstStateChangeReturn gst_base_parse_change_state (GstElement * element,
390 GstStateChange transition);
391 static void gst_base_parse_reset (GstBaseParse * parse);
394 static void gst_base_parse_set_index (GstElement * element, GstIndex * index);
395 static GstIndex *gst_base_parse_get_index (GstElement * element);
398 static gboolean gst_base_parse_sink_activate (GstPad * sinkpad,
400 static gboolean gst_base_parse_sink_activate_mode (GstPad * pad,
401 GstObject * parent, GstPadMode mode, gboolean active);
402 static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
404 static void gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event);
406 static gboolean gst_base_parse_src_event (GstPad * pad, GstObject * parent,
408 static gboolean gst_base_parse_src_query (GstPad * pad, GstObject * parent,
411 static gboolean gst_base_parse_sink_event (GstPad * pad, GstObject * parent,
413 static gboolean gst_base_parse_sink_query (GstPad * pad, GstObject * parent,
416 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstObject * parent,
418 static void gst_base_parse_loop (GstPad * pad);
420 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
421 GstBaseParseFrame * frame);
423 static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
426 static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
429 static void gst_base_parse_drain (GstBaseParse * parse);
431 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
432 gboolean post_min, gboolean post_avg, gboolean post_max);
434 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
435 GstClockTime time, gboolean before, GstClockTime * _ts);
436 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
437 GstClockTime * _time, gint64 * _offset);
439 static GstFlowReturn gst_base_parse_start_fragment (GstBaseParse * parse);
440 static GstFlowReturn gst_base_parse_finish_fragment (GstBaseParse * parse,
443 static inline GstFlowReturn gst_base_parse_check_sync (GstBaseParse * parse);
445 static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);
448 gst_base_parse_clear_queues (GstBaseParse * parse)
450 g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
451 g_slist_free (parse->priv->buffers_queued);
452 parse->priv->buffers_queued = NULL;
453 g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
455 g_slist_free (parse->priv->buffers_pending);
456 parse->priv->buffers_pending = NULL;
457 g_slist_foreach (parse->priv->buffers_head, (GFunc) gst_buffer_unref, NULL);
458 g_slist_free (parse->priv->buffers_head);
459 parse->priv->buffers_head = NULL;
460 g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
461 g_slist_free (parse->priv->buffers_send);
462 parse->priv->buffers_send = NULL;
464 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
465 g_list_free (parse->priv->detect_buffers);
466 parse->priv->detect_buffers = NULL;
467 parse->priv->detect_buffers_size = 0;
469 g_queue_foreach (&parse->priv->queued_frames,
470 (GFunc) gst_base_parse_frame_free, NULL);
471 g_queue_clear (&parse->priv->queued_frames);
473 gst_buffer_replace (&parse->priv->cache, NULL);
475 g_list_foreach (parse->priv->pending_events, (GFunc) gst_event_unref, NULL);
476 g_list_free (parse->priv->pending_events);
477 parse->priv->pending_events = NULL;
478 parse->priv->pending_segment = FALSE;
482 gst_base_parse_finalize (GObject * object)
484 GstBaseParse *parse = GST_BASE_PARSE (object);
486 g_object_unref (parse->priv->adapter);
488 if (parse->priv->cache) {
489 gst_buffer_unref (parse->priv->cache);
490 parse->priv->cache = NULL;
493 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
495 g_list_free (parse->priv->pending_events);
496 parse->priv->pending_events = NULL;
497 parse->priv->pending_segment = FALSE;
499 if (parse->priv->index) {
500 gst_object_unref (parse->priv->index);
501 parse->priv->index = NULL;
503 g_mutex_clear (&parse->priv->index_lock);
505 gst_base_parse_clear_queues (parse);
507 G_OBJECT_CLASS (parent_class)->finalize (object);
511 gst_base_parse_class_init (GstBaseParseClass * klass)
513 GObjectClass *gobject_class;
514 GstElementClass *gstelement_class;
516 gobject_class = G_OBJECT_CLASS (klass);
517 g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
518 parent_class = g_type_class_peek_parent (klass);
519 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
521 gstelement_class = (GstElementClass *) klass;
522 gstelement_class->change_state =
523 GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
526 gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
527 gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
530 /* Default handlers */
531 klass->event = gst_base_parse_sink_eventfunc;
532 klass->src_event = gst_base_parse_src_eventfunc;
533 klass->convert = gst_base_parse_convert_default;
535 GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
536 "baseparse element");
540 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
542 GstPadTemplate *pad_template;
544 GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
546 parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
549 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
550 g_return_if_fail (pad_template != NULL);
551 parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
552 gst_pad_set_event_function (parse->sinkpad,
553 GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
554 gst_pad_set_query_function (parse->sinkpad,
555 GST_DEBUG_FUNCPTR (gst_base_parse_sink_query));
556 gst_pad_set_chain_function (parse->sinkpad,
557 GST_DEBUG_FUNCPTR (gst_base_parse_chain));
558 gst_pad_set_activate_function (parse->sinkpad,
559 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
560 gst_pad_set_activatemode_function (parse->sinkpad,
561 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_mode));
562 gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
564 GST_DEBUG_OBJECT (parse, "sinkpad created");
567 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
568 g_return_if_fail (pad_template != NULL);
569 parse->srcpad = gst_pad_new_from_template (pad_template, "src");
570 gst_pad_set_event_function (parse->srcpad,
571 GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
572 gst_pad_set_query_function (parse->srcpad,
573 GST_DEBUG_FUNCPTR (gst_base_parse_src_query));
574 gst_pad_use_fixed_caps (parse->srcpad);
575 gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
576 GST_DEBUG_OBJECT (parse, "src created");
578 g_queue_init (&parse->priv->queued_frames);
580 parse->priv->adapter = gst_adapter_new ();
582 parse->priv->pad_mode = GST_PAD_MODE_NONE;
584 g_mutex_init (&parse->priv->index_lock);
587 gst_base_parse_reset (parse);
588 GST_DEBUG_OBJECT (parse, "init ok");
590 GST_OBJECT_FLAG_SET (parse, GST_ELEMENT_FLAG_INDEXABLE);
593 static GstBaseParseFrame *
594 gst_base_parse_frame_copy (GstBaseParseFrame * frame)
596 GstBaseParseFrame *copy;
598 copy = g_slice_dup (GstBaseParseFrame, frame);
599 copy->buffer = gst_buffer_ref (frame->buffer);
600 copy->_private_flags &= ~GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
602 GST_TRACE ("copied frame %p -> %p", frame, copy);
608 gst_base_parse_frame_free (GstBaseParseFrame * frame)
610 GST_TRACE ("freeing frame %p", frame);
613 gst_buffer_unref (frame->buffer);
614 frame->buffer = NULL;
617 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
618 g_slice_free (GstBaseParseFrame, frame);
620 memset (frame, 0, sizeof (*frame));
624 G_DEFINE_BOXED_TYPE (GstBaseParseFrame, gst_base_parse_frame,
625 (GBoxedCopyFunc) gst_base_parse_frame_copy,
626 (GBoxedFreeFunc) gst_base_parse_frame_free);
629 * gst_base_parse_frame_init:
630 * @frame: #GstBaseParseFrame.
632 * Sets a #GstBaseParseFrame to initial state. Currently this means
633 * all public fields are zero-ed and a private flag is set to make
634 * sure gst_base_parse_frame_free() only frees the contents but not
635 * the actual frame. Use this function to initialise a #GstBaseParseFrame
636 * allocated on the stack.
641 gst_base_parse_frame_init (GstBaseParseFrame * frame)
643 memset (frame, 0, sizeof (GstBaseParseFrame));
644 frame->_private_flags = GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
645 GST_TRACE ("inited frame %p", frame);
649 * gst_base_parse_frame_new:
650 * @buffer: (transfer none): a #GstBuffer
652 * @overhead: number of bytes in this frame which should be counted as
653 * metadata overhead, ie. not used to calculate the average bitrate.
654 * Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
656 * Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
657 * elements written in C should usually allocate the frame on the stack and
658 * then use gst_base_parse_frame_init() to initialise it.
660 * Returns: a newly-allocated #GstBaseParseFrame. Free with
661 * gst_base_parse_frame_free() when no longer needed.
666 gst_base_parse_frame_new (GstBuffer * buffer, GstBaseParseFrameFlags flags,
669 GstBaseParseFrame *frame;
671 frame = g_slice_new0 (GstBaseParseFrame);
672 frame->buffer = gst_buffer_ref (buffer);
674 GST_TRACE ("created frame %p", frame);
679 gst_base_parse_frame_update (GstBaseParse * parse, GstBaseParseFrame * frame,
682 gst_buffer_replace (&frame->buffer, buf);
686 /* set flags one by one for clarity */
687 if (G_UNLIKELY (parse->priv->drain))
688 parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;
690 /* losing sync is pretty much a discont (and vice versa), no ? */
691 if (G_UNLIKELY (parse->priv->discont))
692 parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
696 gst_base_parse_reset (GstBaseParse * parse)
698 GST_OBJECT_LOCK (parse);
699 gst_segment_init (&parse->segment, GST_FORMAT_TIME);
700 parse->priv->duration = -1;
701 parse->priv->min_frame_size = 1;
702 parse->priv->discont = TRUE;
703 parse->priv->flushing = FALSE;
704 parse->priv->offset = 0;
705 parse->priv->sync_offset = 0;
706 parse->priv->update_interval = -1;
707 parse->priv->fps_num = parse->priv->fps_den = 0;
708 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
709 parse->priv->lead_in = parse->priv->lead_out = 0;
710 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
711 parse->priv->bitrate = 0;
712 parse->priv->framecount = 0;
713 parse->priv->bytecount = 0;
714 parse->priv->acc_duration = 0;
715 parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
716 parse->priv->first_frame_offset = -1;
717 parse->priv->estimated_duration = -1;
718 parse->priv->estimated_drift = 0;
719 parse->priv->next_ts = 0;
720 parse->priv->syncable = TRUE;
721 parse->priv->passthrough = FALSE;
722 parse->priv->has_timing_info = FALSE;
723 parse->priv->post_min_bitrate = TRUE;
724 parse->priv->post_avg_bitrate = TRUE;
725 parse->priv->post_max_bitrate = TRUE;
726 parse->priv->min_bitrate = G_MAXUINT;
727 parse->priv->max_bitrate = 0;
728 parse->priv->avg_bitrate = 0;
729 parse->priv->posted_avg_bitrate = 0;
731 parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
732 parse->priv->index_last_offset = -1;
733 parse->priv->index_last_valid = TRUE;
734 parse->priv->upstream_seekable = FALSE;
735 parse->priv->upstream_size = 0;
736 parse->priv->upstream_has_duration = FALSE;
737 parse->priv->idx_interval = 0;
738 parse->priv->exact_position = TRUE;
739 parse->priv->seen_keyframe = FALSE;
741 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
742 parse->priv->last_offset = 0;
744 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
746 g_list_free (parse->priv->pending_events);
747 parse->priv->pending_events = NULL;
748 parse->priv->pending_segment = FALSE;
750 if (parse->priv->cache) {
751 gst_buffer_unref (parse->priv->cache);
752 parse->priv->cache = NULL;
755 g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
756 g_slist_free (parse->priv->pending_seeks);
757 parse->priv->pending_seeks = NULL;
759 if (parse->priv->adapter)
760 gst_adapter_clear (parse->priv->adapter);
762 parse->priv->new_frame = TRUE;
764 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
765 g_list_free (parse->priv->detect_buffers);
766 parse->priv->detect_buffers = NULL;
767 parse->priv->detect_buffers_size = 0;
768 GST_OBJECT_UNLOCK (parse);
771 /* gst_base_parse_parse_frame:
772 * @parse: #GstBaseParse.
773 * @buffer: #GstBuffer.
775 * Default callback for parse_frame.
778 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
780 GstBuffer *buffer = frame->buffer;
782 if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
783 GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
784 GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
786 if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
787 GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
788 GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
793 /* gst_base_parse_convert:
794 * @parse: #GstBaseParse.
795 * @src_format: #GstFormat describing the source format.
796 * @src_value: Source value to be converted.
797 * @dest_format: #GstFormat defining the converted format.
798 * @dest_value: Pointer where the conversion result will be put.
800 * Converts using configured "convert" vmethod in #GstBaseParse class.
802 * Returns: TRUE if conversion was successful.
805 gst_base_parse_convert (GstBaseParse * parse,
806 GstFormat src_format,
807 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
809 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
812 g_return_val_if_fail (dest_value != NULL, FALSE);
817 ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
819 #ifndef GST_DISABLE_GST_DEBUG
822 if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
823 GST_LOG_OBJECT (parse,
824 "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
825 GST_TIME_ARGS (src_value), *dest_value);
826 } else if (dest_format == GST_FORMAT_TIME &&
827 src_format == GST_FORMAT_BYTES) {
828 GST_LOG_OBJECT (parse,
829 "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
830 src_value, GST_TIME_ARGS (*dest_value));
832 GST_LOG_OBJECT (parse,
833 "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
834 GST_STR_NULL (gst_format_get_name (src_format)),
835 GST_STR_NULL (gst_format_get_name (dest_format)),
836 src_value, *dest_value);
839 GST_DEBUG_OBJECT (parse, "conversion failed");
847 /* gst_base_parse_sink_event:
848 * @pad: #GstPad that received the event.
849 * @event: #GstEvent to be handled.
851 * Handler for sink pad events.
853 * Returns: TRUE if the event was handled.
856 gst_base_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
859 GstBaseParseClass *bclass;
862 parse = GST_BASE_PARSE (parent);
863 bclass = GST_BASE_PARSE_GET_CLASS (parse);
865 GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
866 GST_EVENT_TYPE_NAME (event));
868 /* Cache all serialized events except EOS, SEGMENT and FLUSH_STOP if we have a
870 if (parse->priv->pending_segment && GST_EVENT_IS_SERIALIZED (event)
871 && GST_EVENT_TYPE (event) != GST_EVENT_EOS
872 && GST_EVENT_TYPE (event) != GST_EVENT_SEGMENT
873 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
874 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP
875 && GST_EVENT_TYPE (event) != GST_EVENT_CAPS) {
877 if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
878 /* See if any bitrate tags were posted */
879 gst_base_parse_handle_tag (parse, event);
881 parse->priv->pending_events =
882 g_list_append (parse->priv->pending_events, event);
885 if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
886 parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
887 /* We've not posted bitrate tags yet - do so now */
888 gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
891 ret = bclass->event (parse, event);
893 gst_event_unref (event);
898 GST_DEBUG_OBJECT (parse, "event handled");
904 /* gst_base_parse_sink_eventfunc:
905 * @parse: #GstBaseParse.
906 * @event: #GstEvent to be handled.
908 * Element-level event handler function.
910 * The event will be unreffed only if it has been handled and this
911 * function returns %TRUE
913 * Returns: %TRUE if the event was handled and not need forwarding.
916 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
920 switch (GST_EVENT_TYPE (event)) {
924 GstBaseParseClass *klass;
926 klass = GST_BASE_PARSE_GET_CLASS (parse);
928 gst_event_parse_caps (event, &caps);
929 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
931 if (klass->set_sink_caps)
932 ret = klass->set_sink_caps (parse, caps);
936 /* will send our own caps downstream */
937 gst_event_unref (event);
940 case GST_EVENT_SEGMENT:
942 const GstSegment *in_segment;
943 GstSegment out_segment;
944 gint64 offset = 0, next_ts;
947 gdouble rate, applied_rate;
949 gint64 start, stop, pos, next_ts;
953 gst_event_parse_segment (event, &in_segment);
954 gst_segment_init (&out_segment, GST_FORMAT_TIME);
956 GST_DEBUG_OBJECT (parse, "segment %" GST_SEGMENT_FORMAT, in_segment);
958 if (in_segment->format == GST_FORMAT_BYTES) {
959 GstBaseParseSeek *seek = NULL;
962 /* stop time is allowed to be open-ended, but not start & pos */
963 offset = in_segment->time;
965 GST_OBJECT_LOCK (parse);
966 for (node = parse->priv->pending_seeks; node; node = node->next) {
967 GstBaseParseSeek *tmp = node->data;
969 if (tmp->offset == offset) {
974 parse->priv->pending_seeks =
975 g_slist_remove (parse->priv->pending_seeks, seek);
976 GST_OBJECT_UNLOCK (parse);
979 GST_DEBUG_OBJECT (parse,
980 "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
981 seek->accurate ? " accurate" : "", &seek->segment);
983 out_segment.start = seek->segment.start;
984 out_segment.stop = seek->segment.stop;
985 out_segment.time = seek->segment.start;
987 next_ts = seek->start_ts;
988 parse->priv->exact_position = seek->accurate;
991 /* best attempt convert */
992 /* as these are only estimates, stop is kept open-ended to avoid
993 * premature cutting */
994 gst_base_parse_convert (parse, GST_FORMAT_BYTES, in_segment->start,
995 GST_FORMAT_TIME, (gint64 *) & next_ts);
997 out_segment.start = next_ts;
998 out_segment.stop = GST_CLOCK_TIME_NONE;
999 out_segment.time = next_ts;
1001 parse->priv->exact_position = (in_segment->start == 0);
1004 gst_event_unref (event);
1006 event = gst_event_new_segment (&out_segment);
1008 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. %"
1009 GST_SEGMENT_FORMAT, in_segment);
1011 } else if (in_segment->format != GST_FORMAT_TIME) {
1012 /* Unknown incoming segment format. Output a default open-ended
1014 gst_event_unref (event);
1016 out_segment.start = 0;
1017 out_segment.stop = GST_CLOCK_TIME_NONE;
1018 out_segment.time = 0;
1020 event = gst_event_new_segment (&out_segment);
1024 /* not considered BYTE seekable if it is talking to us in TIME,
1025 * whatever else it might claim */
1026 parse->priv->upstream_seekable = FALSE;
1027 next_ts = in_segment->start;
1030 memcpy (&parse->segment, &out_segment, sizeof (GstSegment));
1033 gst_segment_set_newsegment (&parse->segment, update, rate,
1034 applied_rate, format, start, stop, start);
1037 /* save the segment for later, right before we push a new buffer so that
1038 * the caps are fixed and the next linked element can receive
1040 parse->priv->pending_events =
1041 g_list_append (parse->priv->pending_events, event);
1042 parse->priv->pending_segment = TRUE;
1045 /* but finish the current segment */
1046 GST_DEBUG_OBJECT (parse, "draining current segment");
1047 if (in_segment->rate > 0.0)
1048 gst_base_parse_drain (parse);
1050 gst_base_parse_finish_fragment (parse, FALSE);
1051 gst_adapter_clear (parse->priv->adapter);
1053 parse->priv->offset = offset;
1054 parse->priv->sync_offset = offset;
1055 parse->priv->next_ts = next_ts;
1056 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1057 parse->priv->discont = TRUE;
1058 parse->priv->seen_keyframe = FALSE;
1062 case GST_EVENT_FLUSH_START:
1063 parse->priv->flushing = TRUE;
1064 ret = gst_pad_push_event (parse->srcpad, event);
1065 /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
1066 GST_PAD_STREAM_LOCK (parse->srcpad);
1067 GST_PAD_STREAM_UNLOCK (parse->srcpad);
1070 case GST_EVENT_FLUSH_STOP:
1071 ret = gst_pad_push_event (parse->srcpad, event);
1072 gst_adapter_clear (parse->priv->adapter);
1073 gst_base_parse_clear_queues (parse);
1074 parse->priv->flushing = FALSE;
1075 parse->priv->discont = TRUE;
1076 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1077 parse->priv->new_frame = TRUE;
1081 if (parse->segment.rate > 0.0)
1082 gst_base_parse_drain (parse);
1084 gst_base_parse_finish_fragment (parse, TRUE);
1086 /* If we STILL have zero frames processed, fire an error */
1087 if (parse->priv->framecount == 0) {
1088 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1089 ("No valid frames found before end of stream"), (NULL));
1091 /* newsegment and other serialized events before eos */
1092 if (G_UNLIKELY (parse->priv->pending_events)) {
1095 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1096 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1098 g_list_free (parse->priv->pending_events);
1099 parse->priv->pending_events = NULL;
1100 parse->priv->pending_segment = FALSE;
1102 ret = gst_pad_push_event (parse->srcpad, event);
1107 gst_pad_event_default (parse->sinkpad, GST_OBJECT_CAST (parse),
1115 gst_base_parse_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
1117 GstBaseParse *parse;
1118 GstBaseParseClass *bclass;
1121 parse = GST_BASE_PARSE (parent);
1122 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1124 switch (GST_QUERY_TYPE (query)) {
1125 case GST_QUERY_CAPS:
1127 if (bclass->get_sink_caps) {
1128 GstCaps *caps, *filter;
1130 gst_query_parse_caps (query, &filter);
1131 caps = bclass->get_sink_caps (parse, filter);
1132 GST_LOG_OBJECT (parse, "sink getcaps returning caps %" GST_PTR_FORMAT,
1134 gst_query_set_caps_result (query, caps);
1135 gst_caps_unref (caps);
1139 GstCaps *caps, *template_caps, *filter;
1141 gst_query_parse_caps (query, &filter);
1142 template_caps = gst_pad_get_pad_template_caps (pad);
1143 if (filter != NULL) {
1145 gst_caps_intersect_full (filter, template_caps,
1146 GST_CAPS_INTERSECT_FIRST);
1147 gst_caps_unref (template_caps);
1149 caps = template_caps;
1151 gst_query_set_caps_result (query, caps);
1152 gst_caps_unref (caps);
1160 res = gst_pad_query_default (pad, parent, query);
1169 /* gst_base_parse_src_event:
1170 * @pad: #GstPad that received the event.
1171 * @event: #GstEvent that was received.
1173 * Handler for source pad events.
1175 * Returns: TRUE if the event was handled.
1178 gst_base_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1180 GstBaseParse *parse;
1181 GstBaseParseClass *bclass;
1182 gboolean ret = TRUE;
1184 parse = GST_BASE_PARSE (parent);
1185 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1187 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1188 GST_EVENT_TYPE_NAME (event));
1190 if (bclass->src_event)
1191 ret = bclass->src_event (parse, event);
1193 gst_event_unref (event);
1199 gst_base_parse_is_seekable (GstBaseParse * parse)
1201 /* FIXME: could do more here, e.g. check index or just send data from 0
1202 * in pull mode and let decoder/sink clip */
1203 return parse->priv->syncable;
1206 /* gst_base_parse_src_eventfunc:
1207 * @parse: #GstBaseParse.
1208 * @event: #GstEvent that was received.
1210 * Default srcpad event handler.
1212 * Returns: TRUE if the event was handled and can be dropped.
1215 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1217 gboolean res = FALSE;
1219 switch (GST_EVENT_TYPE (event)) {
1220 case GST_EVENT_SEEK:
1221 if (gst_base_parse_is_seekable (parse))
1222 res = gst_base_parse_handle_seek (parse, event);
1225 res = gst_pad_event_default (parse->srcpad, GST_OBJECT_CAST (parse),
1234 * gst_base_parse_convert_default:
1235 * @parse: #GstBaseParse.
1236 * @src_format: #GstFormat describing the source format.
1237 * @src_value: Source value to be converted.
1238 * @dest_format: #GstFormat defining the converted format.
1239 * @dest_value: Pointer where the conversion result will be put.
1241 * Default implementation of "convert" vmethod in #GstBaseParse class.
1243 * Returns: TRUE if conversion was successful.
1248 gst_base_parse_convert_default (GstBaseParse * parse,
1249 GstFormat src_format,
1250 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1252 gboolean ret = FALSE;
1253 guint64 bytes, duration;
1255 if (G_UNLIKELY (src_format == dest_format)) {
1256 *dest_value = src_value;
1260 if (G_UNLIKELY (src_value == -1)) {
1265 if (G_UNLIKELY (src_value == 0)) {
1270 /* need at least some frames */
1271 if (!parse->priv->framecount)
1274 duration = parse->priv->acc_duration / GST_MSECOND;
1275 bytes = parse->priv->bytecount;
1277 if (G_UNLIKELY (!duration || !bytes))
1278 goto no_duration_bytes;
1280 if (src_format == GST_FORMAT_BYTES) {
1281 if (dest_format == GST_FORMAT_TIME) {
1282 /* BYTES -> TIME conversion */
1283 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1284 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1285 *dest_value *= GST_MSECOND;
1286 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1287 *dest_value / GST_MSECOND);
1290 GST_DEBUG_OBJECT (parse, "converting bytes -> other not implemented");
1292 } else if (src_format == GST_FORMAT_TIME) {
1293 if (dest_format == GST_FORMAT_BYTES) {
1294 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1295 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1297 GST_DEBUG_OBJECT (parse,
1298 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1299 src_value / GST_MSECOND, *dest_value);
1302 GST_DEBUG_OBJECT (parse, "converting time -> other not implemented");
1304 } else if (src_format == GST_FORMAT_DEFAULT) {
1305 /* DEFAULT == frame-based */
1306 if (dest_format == GST_FORMAT_TIME) {
1307 GST_DEBUG_OBJECT (parse, "converting default -> time");
1308 if (parse->priv->fps_den) {
1309 *dest_value = gst_util_uint64_scale (src_value,
1310 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1314 GST_DEBUG_OBJECT (parse, "converting default -> other not implemented");
1317 GST_DEBUG_OBJECT (parse, "conversion not implemented");
1324 GST_DEBUG_OBJECT (parse, "no framecount");
1329 GST_DEBUG_OBJECT (parse, "no duration %" G_GUINT64_FORMAT ", bytes %"
1330 G_GUINT64_FORMAT, duration, bytes);
1337 gst_base_parse_update_duration (GstBaseParse * baseparse)
1340 GstBaseParse *parse;
1342 parse = GST_BASE_PARSE (baseparse);
1344 peer = gst_pad_get_peer (parse->sinkpad);
1346 gboolean qres = FALSE;
1347 gint64 ptot, dest_value;
1349 qres = gst_pad_query_duration (peer, GST_FORMAT_BYTES, &ptot);
1350 gst_object_unref (GST_OBJECT (peer));
1352 if (gst_base_parse_convert (parse, GST_FORMAT_BYTES, ptot,
1353 GST_FORMAT_TIME, &dest_value)) {
1355 /* inform if duration changed, but try to avoid spamming */
1356 parse->priv->estimated_drift +=
1357 dest_value - parse->priv->estimated_duration;
1358 if (parse->priv->estimated_drift > GST_SECOND ||
1359 parse->priv->estimated_drift < -GST_SECOND) {
1360 gst_element_post_message (GST_ELEMENT (parse),
1361 gst_message_new_duration (GST_OBJECT (parse),
1362 GST_FORMAT_TIME, dest_value));
1363 parse->priv->estimated_drift = 0;
1365 parse->priv->estimated_duration = dest_value;
1366 GST_LOG_OBJECT (parse,
1367 "updated estimated duration to %" GST_TIME_FORMAT,
1368 GST_TIME_ARGS (dest_value));
1375 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1376 gboolean post_avg, gboolean post_max)
1378 GstTagList *taglist = NULL;
1380 if (post_min && parse->priv->post_min_bitrate) {
1381 taglist = gst_tag_list_new_empty ();
1383 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1384 GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1387 if (post_avg && parse->priv->post_avg_bitrate) {
1388 if (taglist == NULL)
1389 taglist = gst_tag_list_new_empty ();
1391 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1392 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1393 parse->priv->avg_bitrate, NULL);
1396 if (post_max && parse->priv->post_max_bitrate) {
1397 if (taglist == NULL)
1398 taglist = gst_tag_list_new_empty ();
1400 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1401 GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1404 GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1405 parse->priv->min_bitrate, parse->priv->avg_bitrate,
1406 parse->priv->max_bitrate);
1408 if (taglist != NULL) {
1409 gst_pad_push_event (parse->srcpad, gst_event_new_tag (taglist));
1413 /* gst_base_parse_update_bitrates:
1414 * @parse: #GstBaseParse.
1415 * @buffer: Current frame as a #GstBuffer
1417 * Keeps track of the minimum and maximum bitrates, and also maintains a
1418 * running average bitrate of the stream so far.
1421 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1423 /* Only update the tag on a 10 kbps delta */
1424 static const gint update_threshold = 10000;
1426 guint64 data_len, frame_dur;
1427 gint overhead, frame_bitrate, old_avg_bitrate;
1428 gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1429 GstBuffer *buffer = frame->buffer;
1431 overhead = frame->overhead;
1435 data_len = gst_buffer_get_size (buffer) - overhead;
1436 parse->priv->data_bytecount += data_len;
1438 /* duration should be valid by now,
1439 * either set by subclass or maybe based on fps settings */
1440 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1441 /* Calculate duration of a frame from buffer properties */
1442 frame_dur = GST_BUFFER_DURATION (buffer);
1443 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1444 parse->priv->acc_duration;
1447 /* No way to figure out frame duration (is this even possible?) */
1451 /* override if subclass provided bitrate, e.g. metadata based */
1452 if (parse->priv->bitrate) {
1453 parse->priv->avg_bitrate = parse->priv->bitrate;
1454 /* spread this (confirmed) info ASAP */
1455 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1456 gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1460 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1464 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1465 parse->priv->avg_bitrate);
1467 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1469 } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1470 /* always post all at threshold time */
1471 update_min = update_max = update_avg = TRUE;
1474 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1475 if (frame_bitrate < parse->priv->min_bitrate) {
1476 parse->priv->min_bitrate = frame_bitrate;
1480 if (frame_bitrate > parse->priv->max_bitrate) {
1481 parse->priv->max_bitrate = frame_bitrate;
1485 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1486 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1487 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1492 if ((update_min || update_avg || update_max))
1493 gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1500 * gst_base_parse_add_index_entry:
1501 * @parse: #GstBaseParse.
1502 * @offset: offset of entry
1503 * @ts: timestamp associated with offset
1504 * @key: whether entry refers to keyframe
1505 * @force: add entry disregarding sanity checks
1507 * Adds an entry to the index associating @offset to @ts. It is recommended
1508 * to only add keyframe entries. @force allows to bypass checks, such as
1509 * whether the stream is (upstream) seekable, another entry is already "close"
1510 * to the new entry, etc.
1512 * Returns: #gboolean indicating whether entry was added
1517 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1518 GstClockTime ts, gboolean key, gboolean force)
1520 gboolean ret = FALSE;
1521 GstIndexAssociation associations[2];
1523 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1524 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1526 if (G_LIKELY (!force)) {
1528 if (!parse->priv->upstream_seekable) {
1529 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1533 /* FIXME need better helper data structure that handles these issues
1534 * related to ongoing collecting of index entries */
1535 if (parse->priv->index_last_offset >= (gint64) offset) {
1536 GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1537 "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1541 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1542 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1543 parse->priv->idx_interval) {
1544 GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1545 GST_TIME_ARGS (parse->priv->index_last_ts));
1549 /* if last is not really the last one */
1550 if (!parse->priv->index_last_valid) {
1551 GstClockTime prev_ts;
1553 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1554 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1555 GST_DEBUG_OBJECT (parse,
1556 "entry too close to existing entry %" GST_TIME_FORMAT,
1557 GST_TIME_ARGS (prev_ts));
1558 parse->priv->index_last_offset = offset;
1559 parse->priv->index_last_ts = ts;
1565 associations[0].format = GST_FORMAT_TIME;
1566 associations[0].value = ts;
1567 associations[1].format = GST_FORMAT_BYTES;
1568 associations[1].value = offset;
1570 /* index might change on-the-fly, although that would be nutty app ... */
1571 GST_BASE_PARSE_INDEX_LOCK (parse);
1572 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1573 (key) ? GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT :
1574 GST_INDEX_ASSOCIATION_FLAG_DELTA_UNIT, 2,
1575 (const GstIndexAssociation *) &associations);
1576 GST_BASE_PARSE_INDEX_UNLOCK (parse);
1579 parse->priv->index_last_offset = offset;
1580 parse->priv->index_last_ts = ts;
1589 /* check for seekable upstream, above and beyond a mere query */
1591 gst_base_parse_check_seekability (GstBaseParse * parse)
1594 gboolean seekable = FALSE;
1595 gint64 start = -1, stop = -1;
1596 guint idx_interval = 0;
1598 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1599 if (!gst_pad_peer_query (parse->sinkpad, query)) {
1600 GST_DEBUG_OBJECT (parse, "seeking query failed");
1604 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1606 /* try harder to query upstream size if we didn't get it the first time */
1607 if (seekable && stop == -1) {
1608 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1609 gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_BYTES, &stop);
1612 /* if upstream doesn't know the size, it's likely that it's not seekable in
1613 * practice even if it technically may be seekable */
1614 if (seekable && (start != 0 || stop <= start)) {
1615 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1619 /* let's not put every single frame into our index */
1621 if (stop < 10 * 1024 * 1024)
1623 else if (stop < 100 * 1024 * 1024)
1626 idx_interval = 1000;
1630 gst_query_unref (query);
1632 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1633 G_GUINT64_FORMAT ")", seekable, start, stop);
1634 parse->priv->upstream_seekable = seekable;
1635 parse->priv->upstream_size = seekable ? stop : 0;
1637 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1638 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1641 /* some misc checks on upstream */
1643 gst_base_parse_check_upstream (GstBaseParse * parse)
1647 if (gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_TIME, &stop))
1648 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1649 /* upstream has one, accept it also, and no further updates */
1650 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1651 parse->priv->upstream_has_duration = TRUE;
1654 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1655 parse->priv->upstream_has_duration);
1658 /* checks src caps to determine if dealing with audio or video */
1659 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1661 gst_base_parse_check_media (GstBaseParse * parse)
1666 caps = gst_pad_get_current_caps (parse->srcpad);
1667 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1668 parse->priv->is_video =
1669 g_str_has_prefix (gst_structure_get_name (s), "video");
1671 /* historical default */
1672 parse->priv->is_video = FALSE;
1675 gst_caps_unref (caps);
1677 GST_DEBUG_OBJECT (parse, "media is video: %d", parse->priv->is_video);
1680 /* takes ownership of frame */
1682 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1684 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1685 /* frame allocated on the heap, we can just take ownership */
1686 g_queue_push_tail (&parse->priv->queued_frames, frame);
1687 GST_TRACE ("queued frame %p", frame);
1689 GstBaseParseFrame *copy;
1691 /* probably allocated on the stack, must make a proper copy */
1692 copy = gst_base_parse_frame_copy (frame);
1693 g_queue_push_tail (&parse->priv->queued_frames, copy);
1694 GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1695 gst_base_parse_frame_free (frame);
1699 /* makes sure that @buf is properly prepared and decorated for passing
1700 * to baseclass, and an equally setup frame is returned setup with @buf.
1701 * Takes ownership of @buf. */
1702 static GstBaseParseFrame *
1703 gst_base_parse_prepare_frame (GstBaseParse * parse, GstBuffer * buffer)
1705 GstBaseParseFrame *frame = NULL;
1707 buffer = gst_buffer_make_writable (buffer);
1709 GST_LOG_OBJECT (parse,
1710 "preparing frame at offset %" G_GUINT64_FORMAT
1711 " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
1712 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1713 gst_buffer_get_size (buffer));
1715 if (parse->priv->discont) {
1716 GST_DEBUG_OBJECT (parse, "marking DISCONT");
1717 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1718 parse->priv->discont = FALSE;
1721 GST_BUFFER_OFFSET (buffer) = parse->priv->offset;
1723 frame = gst_base_parse_frame_new (buffer, 0, 0);
1725 /* also ensure to update state flags */
1726 gst_base_parse_frame_update (parse, frame, buffer);
1727 gst_buffer_unref (buffer);
1729 if (parse->priv->prev_offset != parse->priv->offset || parse->priv->new_frame) {
1730 GST_LOG_OBJECT (parse, "marking as new frame");
1731 parse->priv->new_frame = FALSE;
1732 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_NEW_FRAME;
1735 frame->offset = parse->priv->prev_offset = parse->priv->offset;
1737 /* use default handler to provide initial (upstream) metadata */
1738 gst_base_parse_parse_frame (parse, frame);
1743 /* Wraps buffer in a frame and dispatches to subclass.
1744 * Also manages data skipping and offset handling (including adapter flushing).
1745 * Takes ownership of @buffer */
1746 static GstFlowReturn
1747 gst_base_parse_handle_buffer (GstBaseParse * parse, GstBuffer * buffer,
1748 gint * skip, gint * flushed)
1750 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1751 GstBaseParseFrame *frame;
1754 g_return_val_if_fail (skip != NULL || flushed != NULL, GST_FLOW_ERROR);
1756 GST_LOG_OBJECT (parse,
1757 "handling buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1758 ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buffer),
1759 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1760 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1762 /* track what is being flushed during this single round of frame processing */
1763 parse->priv->flushed = 0;
1766 /* make it easy for _finish_frame to pick up input data */
1767 if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
1768 gst_buffer_ref (buffer);
1769 gst_adapter_push (parse->priv->adapter, buffer);
1772 frame = gst_base_parse_prepare_frame (parse, buffer);
1773 ret = klass->handle_frame (parse, frame, skip);
1775 *flushed = parse->priv->flushed;
1777 GST_LOG_OBJECT (parse, "handle_frame skipped %d, flushed %d",
1780 if (ret != GST_FLOW_OK) {
1781 GST_DEBUG_OBJECT (parse, "handle_frame returned %d", ret);
1785 /* subclass can only do one of these, or semantics are too unclear */
1786 g_assert (*skip == 0 || *flushed == 0);
1788 /* track skipping */
1790 GstClockTime timestamp;
1793 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", *skip);
1794 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
1795 /* reverse playback, and no frames found yet, so we are skipping
1796 * the leading part of a fragment, which may form the tail of
1797 * fragment coming later, hopefully subclass skips efficiently ... */
1798 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
1799 outbuf = gst_adapter_take_buffer (parse->priv->adapter, *skip);
1800 outbuf = gst_buffer_make_writable (outbuf);
1801 GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
1802 parse->priv->buffers_head =
1803 g_slist_prepend (parse->priv->buffers_head, outbuf);
1806 gst_adapter_flush (parse->priv->adapter, *skip);
1808 if (!parse->priv->discont)
1809 parse->priv->sync_offset = parse->priv->offset;
1810 parse->priv->offset += *skip;
1811 parse->priv->discont = TRUE;
1812 /* check for indefinite skipping */
1813 if (ret == GST_FLOW_OK)
1814 ret = gst_base_parse_check_sync (parse);
1817 parse->priv->offset += *flushed;
1820 if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
1821 gst_adapter_clear (parse->priv->adapter);
1824 gst_base_parse_frame_free (frame);
1829 /* gst_base_parse_handle_and_push_buffer:
1830 * @parse: #GstBaseParse.
1831 * @klass: #GstBaseParseClass.
1832 * @frame: (transfer full): a #GstBaseParseFrame
1834 * Parses the frame from given buffer and pushes it forward. Also performs
1835 * timestamp handling and checks the segment limits.
1837 * This is called with srcpad STREAM_LOCK held.
1839 * Returns: #GstFlowReturn
1841 static GstFlowReturn
1842 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1843 GstBaseParseFrame * frame)
1848 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1850 /* some one-time start-up */
1851 if (G_UNLIKELY (!parse->priv->framecount)) {
1852 gst_base_parse_check_seekability (parse);
1853 gst_base_parse_check_upstream (parse);
1856 buffer = frame->buffer;
1857 offset = frame->offset;
1859 /* check if subclass/format can provide ts.
1860 * If so, that allows and enables extra seek and duration determining options */
1861 if (G_UNLIKELY (parse->priv->first_frame_offset < 0)) {
1862 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && parse->priv->has_timing_info
1863 && parse->priv->pad_mode == GST_PAD_MODE_PULL) {
1864 parse->priv->first_frame_offset = offset;
1865 parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1866 GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1867 " for first frame at offset %" G_GINT64_FORMAT,
1868 GST_TIME_ARGS (parse->priv->first_frame_ts),
1869 parse->priv->first_frame_offset);
1870 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1872 GstClockTime last_ts = G_MAXINT64;
1874 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1875 gst_base_parse_locate_time (parse, &last_ts, &off);
1876 if (GST_CLOCK_TIME_IS_VALID (last_ts))
1877 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1880 /* disable further checks */
1881 parse->priv->first_frame_offset = 0;
1885 /* again use default handler to add missing metadata;
1886 * we may have new information on frame properties */
1887 gst_base_parse_parse_frame (parse, frame);
1888 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1889 GST_BUFFER_DURATION_IS_VALID (buffer)) {
1890 parse->priv->next_ts =
1891 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1893 /* we lost track, do not produce bogus time next time around
1894 * (probably means parser subclass has given up on parsing as well) */
1895 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1896 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1899 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1900 GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1901 gst_base_parse_add_index_entry (parse, offset,
1902 GST_BUFFER_TIMESTAMP (buffer),
1903 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1905 /* All OK, push queued frames if there are any */
1906 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
1907 GstBaseParseFrame *queued_frame;
1909 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
1910 gst_base_parse_push_frame (parse, queued_frame);
1914 return gst_base_parse_push_frame (parse, frame);
1918 * gst_base_parse_push_frame:
1919 * @parse: #GstBaseParse.
1920 * @frame: (transfer none): a #GstBaseParseFrame
1922 * Pushes the frame's buffer downstream, sends any pending events and
1923 * does some timestamp and segment handling. Takes ownership of
1924 * frame's buffer, though caller retains ownership of @frame.
1926 * This must be called with sinkpad STREAM_LOCK held.
1928 * Returns: #GstFlowReturn
1933 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1935 GstFlowReturn ret = GST_FLOW_OK;
1936 GstClockTime last_start = GST_CLOCK_TIME_NONE;
1937 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1938 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1942 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1943 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
1945 GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
1947 buffer = frame->buffer;
1949 GST_LOG_OBJECT (parse,
1950 "processing buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1951 ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buffer),
1952 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1953 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1956 parse->priv->bytecount += frame->size;
1957 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1958 parse->priv->framecount++;
1959 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1960 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1963 /* 0 means disabled */
1964 if (parse->priv->update_interval < 0)
1965 parse->priv->update_interval = 50;
1966 else if (parse->priv->update_interval > 0 &&
1967 (parse->priv->framecount % parse->priv->update_interval) == 0)
1968 gst_base_parse_update_duration (parse);
1970 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1971 last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1972 if (last_start != GST_CLOCK_TIME_NONE
1973 && GST_BUFFER_DURATION_IS_VALID (buffer))
1974 last_stop = last_start + GST_BUFFER_DURATION (buffer);
1976 /* should have caps by now */
1977 if (!gst_pad_has_current_caps (parse->srcpad))
1980 if (G_UNLIKELY (parse->priv->pending_segment)) {
1981 /* have caps; check identity */
1982 gst_base_parse_check_media (parse);
1985 /* Push pending events, including NEWSEGMENT events */
1986 if (G_UNLIKELY (parse->priv->pending_events)) {
1989 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1990 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1992 g_list_free (parse->priv->pending_events);
1993 parse->priv->pending_events = NULL;
1994 parse->priv->pending_segment = FALSE;
1997 /* segment adjustment magic; only if we are running the whole show */
1998 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1999 (parse->priv->pad_mode == GST_PAD_MODE_PULL ||
2000 parse->priv->upstream_seekable)) {
2002 if (GST_CLOCK_TIME_IS_VALID (parse->segment.position) &&
2003 GST_CLOCK_TIME_IS_VALID (last_start)) {
2004 GstClockTimeDiff diff;
2006 /* only send newsegments with increasing start times,
2007 * otherwise if these go back and forth downstream (sinks) increase
2008 * accumulated time and running_time */
2009 diff = GST_CLOCK_DIFF (parse->segment.position, last_start);
2010 if (G_UNLIKELY (diff > 2 * GST_SECOND
2011 && last_start > parse->segment.start
2012 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
2013 || last_start < parse->segment.stop))) {
2015 GST_DEBUG_OBJECT (parse,
2016 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
2017 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
2018 "Sending updated NEWSEGMENT events", diff,
2019 GST_TIME_ARGS (parse->segment.position),
2020 GST_TIME_ARGS (last_start));
2022 /* skip gap FIXME */
2023 gst_pad_push_event (parse->srcpad,
2024 gst_event_new_segment (&parse->segment));
2026 parse->segment.position = last_start;
2031 /* update bitrates and optionally post corresponding tags
2032 * (following newsegment) */
2033 gst_base_parse_update_bitrates (parse, frame);
2035 if (klass->pre_push_frame) {
2036 ret = klass->pre_push_frame (parse, frame);
2038 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
2041 /* take final ownership of frame buffer */
2042 if (frame->out_buffer) {
2043 buffer = frame->out_buffer;
2044 frame->out_buffer = NULL;
2045 gst_buffer_replace (&frame->buffer, NULL);
2047 buffer = frame->buffer;
2048 frame->buffer = NULL;
2051 /* subclass must play nice */
2052 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2054 size = gst_buffer_get_size (buffer);
2056 parse->priv->seen_keyframe |= parse->priv->is_video &&
2057 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
2059 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
2060 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2061 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
2062 GST_BUFFER_TIMESTAMP (buffer) >
2063 parse->segment.stop + parse->priv->lead_out_ts) {
2064 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
2066 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2067 GST_BUFFER_DURATION_IS_VALID (buffer) &&
2068 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
2069 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
2070 parse->priv->lead_in_ts < parse->segment.start) {
2071 if (parse->priv->seen_keyframe) {
2072 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
2075 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
2076 ret = GST_BASE_PARSE_FLOW_DROPPED;
2083 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
2084 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) dropped", size);
2085 gst_buffer_unref (buffer);
2087 } else if (ret == GST_FLOW_OK) {
2088 if (parse->segment.rate > 0.0) {
2089 GST_LOG_OBJECT (parse, "pushing frame (%" G_GSIZE_FORMAT " bytes) now..",
2091 ret = gst_pad_push (parse->srcpad, buffer);
2092 GST_LOG_OBJECT (parse, "frame pushed, flow %s", gst_flow_get_name (ret));
2094 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) queued for now",
2096 parse->priv->buffers_queued =
2097 g_slist_prepend (parse->priv->buffers_queued, buffer);
2101 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s",
2102 size, gst_flow_get_name (ret));
2103 gst_buffer_unref (buffer);
2104 /* if we are not sufficiently in control, let upstream decide on EOS */
2105 if (ret == GST_FLOW_EOS &&
2106 (parse->priv->passthrough ||
2107 (parse->priv->pad_mode == GST_PAD_MODE_PUSH &&
2108 !parse->priv->upstream_seekable)))
2112 /* Update current running segment position */
2113 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
2114 parse->segment.position < last_stop)
2115 parse->segment.position = last_stop;
2122 GST_ELEMENT_ERROR (parse, STREAM, DECODE, ("No caps set"), (NULL));
2123 return GST_FLOW_ERROR;
2128 * gst_base_parse_finish_frame:
2129 * @parse: a #GstBaseParse
2130 * @frame: a #GstBaseParseFrame
2131 * @size: consumed input data represented by frame
2133 * Collects parsed data and pushes this downstream.
2134 * Source pad caps must be set when this is called.
2136 * If @frame's out_buffer is set, that will be used as subsequent frame data.
2137 * Otherwise, @size samples will be taken from the input and used for output,
2138 * and the output's metadata (timestamps etc) will be taken as (optionally)
2139 * set by the subclass on @frame's (input) buffer (which is otherwise
2140 * ignored for any but the above purpose/information).
2142 * Note that the latter buffer is invalidated by this call, whereas the
2143 * caller retains ownership of @frame.
2145 * Returns: a #GstFlowReturn that should be escalated to caller (of caller)
2150 gst_base_parse_finish_frame (GstBaseParse * parse, GstBaseParseFrame * frame,
2153 GstFlowReturn ret = GST_FLOW_OK;
2155 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2156 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
2157 g_return_val_if_fail (size > 0 || frame->out_buffer, GST_FLOW_ERROR);
2158 g_return_val_if_fail (gst_adapter_available (parse->priv->adapter) >= size,
2161 GST_LOG_OBJECT (parse, "finished frame at offset %" G_GUINT64_FORMAT ", "
2162 "flushing size %d", frame->offset, size);
2164 if (parse->priv->scanning && frame->buffer) {
2165 if (!parse->priv->scanned_frame) {
2166 parse->priv->scanned_frame = gst_base_parse_frame_copy (frame);
2171 parse->priv->flushed += size;
2173 /* either PUSH or PULL mode arranges for adapter data */
2174 /* ensure output buffer */
2175 if (!frame->out_buffer) {
2176 GstBuffer *src, *dest;
2178 frame->out_buffer = gst_adapter_take_buffer (parse->priv->adapter, size);
2179 dest = frame->out_buffer;
2180 src = frame->buffer;
2181 GST_BUFFER_PTS (dest) = GST_BUFFER_PTS (src);
2182 GST_BUFFER_DTS (dest) = GST_BUFFER_DTS (src);
2183 GST_BUFFER_OFFSET (dest) = GST_BUFFER_OFFSET (src);
2184 GST_BUFFER_DURATION (dest) = GST_BUFFER_DURATION (src);
2185 GST_BUFFER_OFFSET_END (dest) = GST_BUFFER_OFFSET_END (src);
2186 GST_MINI_OBJECT_FLAGS (dest) = GST_MINI_OBJECT_FLAGS (src);
2188 gst_adapter_flush (parse->priv->adapter, size);
2191 /* use as input for subsequent processing */
2192 gst_buffer_replace (&frame->buffer, frame->out_buffer);
2193 gst_buffer_unref (frame->out_buffer);
2194 frame->out_buffer = NULL;
2196 /* mark input size consumed */
2199 /* subclass might queue frames/data internally if it needs more
2200 * frames to decide on the format, or might request us to queue here. */
2201 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_DROP) {
2202 gst_buffer_replace (&frame->buffer, NULL);
2204 } else if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_QUEUE) {
2205 GstBaseParseFrame *copy;
2207 copy = gst_base_parse_frame_copy (frame);
2208 copy->flags &= ~GST_BASE_PARSE_FRAME_FLAG_QUEUE;
2209 gst_base_parse_queue_frame (parse, copy);
2213 ret = gst_base_parse_handle_and_push_frame (parse, frame);
2219 /* gst_base_parse_drain:
2221 * Drains the adapter until it is empty. It decreases the min_frame_size to
2222 * match the current adapter size and calls chain method until the adapter
2223 * is emptied or chain returns with error.
2226 gst_base_parse_drain (GstBaseParse * parse)
2230 GST_DEBUG_OBJECT (parse, "draining");
2231 parse->priv->drain = TRUE;
2234 avail = gst_adapter_available (parse->priv->adapter);
2238 if (gst_base_parse_chain (parse->sinkpad, GST_OBJECT_CAST (parse),
2239 NULL) != GST_FLOW_OK) {
2243 /* nothing changed, maybe due to truncated frame; break infinite loop */
2244 if (avail == gst_adapter_available (parse->priv->adapter)) {
2245 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
2246 gst_adapter_clear (parse->priv->adapter);
2250 parse->priv->drain = FALSE;
2253 /* gst_base_parse_send_buffers
2255 * Sends buffers collected in send_buffers downstream, and ensures that list
2256 * is empty at the end (errors or not).
2258 static GstFlowReturn
2259 gst_base_parse_send_buffers (GstBaseParse * parse)
2261 GSList *send = NULL;
2263 GstFlowReturn ret = GST_FLOW_OK;
2265 send = parse->priv->buffers_send;
2269 buf = GST_BUFFER_CAST (send->data);
2270 GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
2271 GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2272 ", offset %" G_GINT64_FORMAT, buf,
2273 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2274 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2276 /* iterate output queue an push downstream */
2277 ret = gst_pad_push (parse->srcpad, buf);
2278 send = g_slist_delete_link (send, send);
2280 /* clear any leftover if error */
2281 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2283 buf = GST_BUFFER_CAST (send->data);
2284 gst_buffer_unref (buf);
2285 send = g_slist_delete_link (send, send);
2290 parse->priv->buffers_send = send;
2295 /* gst_base_parse_start_fragment:
2297 * Prepares for processing a reverse playback (forward) fragment
2298 * by (re)setting proper state variables.
2300 static GstFlowReturn
2301 gst_base_parse_start_fragment (GstBaseParse * parse)
2303 GST_LOG_OBJECT (parse, "starting fragment");
2305 /* invalidate so no fall-back timestamping is performed;
2306 * ok if taken from subclass or upstream */
2307 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
2308 parse->priv->prev_ts = GST_CLOCK_TIME_NONE;
2309 /* prevent it hanging around stop all the time */
2310 parse->segment.position = GST_CLOCK_TIME_NONE;
2312 parse->priv->discont = TRUE;
2314 /* head of previous fragment is now pending tail of current fragment */
2315 parse->priv->buffers_pending = parse->priv->buffers_head;
2316 parse->priv->buffers_head = NULL;
2322 /* gst_base_parse_finish_fragment:
2324 * Processes a reverse playback (forward) fragment:
2325 * - append head of last fragment that was skipped to current fragment data
2326 * - drain the resulting current fragment data (i.e. repeated chain)
2327 * - add time/duration (if needed) to frames queued by chain
2328 * - push queued data
2330 static GstFlowReturn
2331 gst_base_parse_finish_fragment (GstBaseParse * parse, gboolean prev_head)
2334 GstFlowReturn ret = GST_FLOW_OK;
2335 gboolean seen_key = FALSE, seen_delta = FALSE;
2337 GST_LOG_OBJECT (parse, "finishing fragment");
2340 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2341 while (parse->priv->buffers_pending) {
2342 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2344 GST_LOG_OBJECT (parse, "adding pending buffer (size %" G_GSIZE_FORMAT ")",
2345 gst_buffer_get_size (buf));
2346 gst_adapter_push (parse->priv->adapter, buf);
2348 GST_LOG_OBJECT (parse, "discarding head buffer");
2349 gst_buffer_unref (buf);
2351 parse->priv->buffers_pending =
2352 g_slist_delete_link (parse->priv->buffers_pending,
2353 parse->priv->buffers_pending);
2356 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2357 /* initial skipped data is added to buffers_pending */
2358 gst_base_parse_drain (parse);
2360 if (parse->priv->buffers_send) {
2361 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2362 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2365 /* add metadata (if needed to queued buffers */
2366 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2367 GST_TIME_ARGS (parse->priv->last_ts));
2368 while (parse->priv->buffers_queued) {
2369 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2371 /* no touching if upstream or parsing provided time */
2372 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2373 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2374 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2375 } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
2376 GST_BUFFER_DURATION_IS_VALID (buf)) {
2377 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
2378 parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
2380 parse->priv->last_ts = 0;
2381 GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
2382 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2383 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2385 /* no idea, very bad */
2386 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2389 parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
2391 /* reverse order for ascending sending */
2392 /* send downstream at keyframe not preceded by a keyframe
2393 * (e.g. that should identify start of collection of IDR nals) */
2394 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2396 ret = gst_base_parse_send_buffers (parse);
2397 /* if a problem, throw all to sending */
2398 if (ret != GST_FLOW_OK) {
2399 parse->priv->buffers_send =
2400 g_slist_reverse (parse->priv->buffers_queued);
2401 parse->priv->buffers_queued = NULL;
2411 parse->priv->buffers_send =
2412 g_slist_prepend (parse->priv->buffers_send, buf);
2413 parse->priv->buffers_queued =
2414 g_slist_delete_link (parse->priv->buffers_queued,
2415 parse->priv->buffers_queued);
2418 /* audio may have all marked as keyframe, so arrange to send here */
2420 ret = gst_base_parse_send_buffers (parse);
2422 /* any trailing unused no longer usable (ideally none) */
2423 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2424 GST_DEBUG_OBJECT (parse, "discarding %" G_GSIZE_FORMAT " trailing bytes",
2425 gst_adapter_available (parse->priv->adapter));
2426 gst_adapter_clear (parse->priv->adapter);
2432 /* small helper that checks whether we have been trying to resync too long */
2433 static inline GstFlowReturn
2434 gst_base_parse_check_sync (GstBaseParse * parse)
2436 if (G_UNLIKELY (parse->priv->discont &&
2437 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2438 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2439 ("Failed to parse stream"), (NULL));
2440 return GST_FLOW_ERROR;
2446 static GstFlowReturn
2447 gst_base_parse_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2449 GstBaseParseClass *bclass;
2450 GstBaseParse *parse;
2451 GstFlowReturn ret = GST_FLOW_OK;
2452 GstBuffer *tmpbuf = NULL;
2457 GstClockTime timestamp;
2459 parse = GST_BASE_PARSE (parent);
2460 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2462 if (parse->priv->detecting) {
2463 GstBuffer *detect_buf;
2465 if (parse->priv->detect_buffers_size == 0) {
2466 detect_buf = gst_buffer_ref (buffer);
2471 detect_buf = gst_buffer_new ();
2473 for (l = parse->priv->detect_buffers; l; l = l->next) {
2474 gsize tmpsize = gst_buffer_get_size (l->data);
2476 gst_buffer_copy_into (detect_buf, GST_BUFFER_CAST (l->data),
2477 GST_BUFFER_COPY_MEMORY, offset, tmpsize);
2481 gst_buffer_copy_into (detect_buf, buffer, GST_BUFFER_COPY_MEMORY,
2482 offset, gst_buffer_get_size (buffer));
2485 ret = bclass->detect (parse, detect_buf);
2486 gst_buffer_unref (detect_buf);
2488 if (ret == GST_FLOW_OK) {
2491 /* Detected something */
2492 parse->priv->detecting = FALSE;
2494 for (l = parse->priv->detect_buffers; l; l = l->next) {
2495 if (ret == GST_FLOW_OK && !parse->priv->flushing)
2497 gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2498 parent, GST_BUFFER_CAST (l->data));
2500 gst_buffer_unref (GST_BUFFER_CAST (l->data));
2502 g_list_free (parse->priv->detect_buffers);
2503 parse->priv->detect_buffers = NULL;
2504 parse->priv->detect_buffers_size = 0;
2506 if (ret != GST_FLOW_OK) {
2510 /* Handle the current buffer */
2511 } else if (ret == GST_FLOW_NOT_NEGOTIATED) {
2512 /* Still detecting, append buffer or error out if draining */
2514 if (parse->priv->drain) {
2515 GST_DEBUG_OBJECT (parse, "Draining but did not detect format yet");
2516 return GST_FLOW_ERROR;
2517 } else if (parse->priv->flushing) {
2518 g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref,
2520 g_list_free (parse->priv->detect_buffers);
2521 parse->priv->detect_buffers = NULL;
2522 parse->priv->detect_buffers_size = 0;
2524 parse->priv->detect_buffers =
2525 g_list_append (parse->priv->detect_buffers, buffer);
2526 parse->priv->detect_buffers_size += gst_buffer_get_size (buffer);
2530 /* Something went wrong, subclass responsible for error reporting */
2534 /* And now handle the current buffer if detection worked */
2537 if (G_LIKELY (buffer)) {
2538 GST_LOG_OBJECT (parse,
2539 "buffer size: %" G_GSIZE_FORMAT ", offset = %" G_GINT64_FORMAT,
2540 gst_buffer_get_size (buffer), GST_BUFFER_OFFSET (buffer));
2541 if (G_UNLIKELY (parse->priv->passthrough)) {
2542 GstBaseParseFrame frame;
2544 gst_base_parse_frame_init (&frame);
2545 frame.buffer = gst_buffer_make_writable (buffer);
2546 ret = gst_base_parse_push_frame (parse, &frame);
2547 gst_base_parse_frame_free (&frame);
2550 /* upstream feeding us in reverse playback;
2551 * finish previous fragment and start new upon DISCONT */
2552 if (parse->segment.rate < 0.0) {
2553 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2554 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2555 ret = gst_base_parse_finish_fragment (parse, TRUE);
2556 gst_base_parse_start_fragment (parse);
2559 gst_adapter_push (parse->priv->adapter, buffer);
2562 /* Parse and push as many frames as possible */
2563 /* Stop either when adapter is empty or we are flushing */
2564 while (!parse->priv->flushing) {
2567 /* note: if subclass indicates MAX fsize,
2568 * this will not likely be available anyway ... */
2569 min_size = MAX (parse->priv->min_frame_size, fsize);
2570 av = gst_adapter_available (parse->priv->adapter);
2572 if (G_UNLIKELY (parse->priv->drain)) {
2574 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2575 if (G_UNLIKELY (!min_size)) {
2580 /* Collect at least min_frame_size bytes */
2581 if (av < min_size) {
2582 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)", av);
2586 /* move along with upstream timestamp (if any),
2587 * but interpolate in between */
2588 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2589 if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2590 (parse->priv->prev_ts != timestamp)) {
2591 parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2594 /* always pass all available data */
2595 data = gst_adapter_map (parse->priv->adapter, av);
2596 /* arrange for actual data to be copied if subclass tries to,
2597 * since what is passed is tied to the adapter */
2598 tmpbuf = gst_buffer_new ();
2599 gst_buffer_take_memory (tmpbuf, -1,
2600 gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY |
2601 GST_MEMORY_FLAG_NO_SHARE, (gpointer) data, av, 0, av, NULL, NULL));
2603 /* keep the adapter mapped, so keep track of what has to be flushed */
2604 ret = gst_base_parse_handle_buffer (parse, tmpbuf, &skip, &flush);
2607 /* probably already implicitly unmapped due to adapter operation,
2608 * but for good measure ... */
2609 gst_adapter_unmap (parse->priv->adapter);
2610 if (ret != GST_FLOW_OK) {
2613 if (skip == 0 && flush == 0) {
2614 GST_LOG_OBJECT (parse, "nothing skipped and no frames finished, "
2615 "breaking to get more data");
2621 GST_LOG_OBJECT (parse, "chain leaving");
2625 /* pull @size bytes at current offset,
2626 * i.e. at least try to and possibly return a shorter buffer if near the end */
2627 static GstFlowReturn
2628 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2629 GstBuffer ** buffer)
2631 GstFlowReturn ret = GST_FLOW_OK;
2633 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2635 /* Caching here actually makes much less difference than one would expect.
2636 * We do it mainly to avoid pulling buffers of 1 byte all the time */
2637 if (parse->priv->cache) {
2638 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2639 gint cache_size = gst_buffer_get_size (parse->priv->cache);
2641 if (cache_offset <= parse->priv->offset &&
2642 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2643 *buffer = gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL,
2644 parse->priv->offset - cache_offset, size);
2645 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2648 /* not enough data in the cache, free cache and get a new one */
2649 gst_buffer_unref (parse->priv->cache);
2650 parse->priv->cache = NULL;
2653 /* refill the cache */
2655 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2656 64 * 1024), &parse->priv->cache);
2657 if (ret != GST_FLOW_OK) {
2658 parse->priv->cache = NULL;
2662 if (gst_buffer_get_size (parse->priv->cache) >= size) {
2664 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0,
2666 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2670 /* Not possible to get enough data, try a last time with
2671 * requesting exactly the size we need */
2672 gst_buffer_unref (parse->priv->cache);
2673 parse->priv->cache = NULL;
2675 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2676 &parse->priv->cache);
2678 if (ret != GST_FLOW_OK) {
2679 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2684 if (gst_buffer_get_size (parse->priv->cache) < size) {
2685 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2686 G_GUINT64_FORMAT ": wanted %u bytes, got %" G_GSIZE_FORMAT " bytes",
2687 parse->priv->offset, size, gst_buffer_get_size (parse->priv->cache));
2689 *buffer = parse->priv->cache;
2690 parse->priv->cache = NULL;
2696 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0, size);
2697 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2702 static GstFlowReturn
2703 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2706 GstClockTime ts = 0;
2710 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2711 ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2712 parse->priv->last_offset);
2714 if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2715 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2716 GST_TIME_ARGS (parse->segment.start));
2721 /* last fragment started at last_offset / last_ts;
2722 * seek back 10s capped at 1MB */
2723 if (parse->priv->last_ts >= 10 * GST_SECOND)
2724 ts = parse->priv->last_ts - 10 * GST_SECOND;
2725 /* if we are exact now, we will be more so going backwards */
2726 if (parse->priv->exact_position) {
2727 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2729 if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2730 GST_FORMAT_BYTES, &offset)) {
2731 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2734 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2735 parse->priv->last_offset - 1024);
2736 offset = MAX (0, offset);
2738 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2740 parse->priv->offset = offset;
2742 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2744 if (ret != GST_FLOW_OK)
2747 /* offset will increase again as fragment is processed/parsed */
2748 parse->priv->last_offset = offset;
2750 gst_base_parse_start_fragment (parse);
2751 gst_adapter_push (parse->priv->adapter, buffer);
2752 ret = gst_base_parse_finish_fragment (parse, TRUE);
2753 if (ret != GST_FLOW_OK)
2756 /* force previous fragment */
2757 parse->priv->offset = -1;
2764 * pull and scan for next frame starting from current offset
2765 * ajusts sync, drain and offset going along */
2766 static GstFlowReturn
2767 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2771 GstFlowReturn ret = GST_FLOW_OK;
2772 guint fsize, min_size;
2776 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2777 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2779 /* let's make this efficient for all subclass once and for all;
2780 * maybe it does not need this much, but in the latter case, we know we are
2781 * in pull mode here and might as well try to read and supply more anyway
2782 * (so does the buffer caching mechanism) */
2786 min_size = MAX (parse->priv->min_frame_size, fsize);
2788 GST_LOG_OBJECT (parse, "reading buffer size %u", min_size);
2790 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2791 if (ret != GST_FLOW_OK)
2794 /* if we got a short read, inform subclass we are draining leftover
2795 * and no more is to be expected */
2796 if (gst_buffer_get_size (buffer) < min_size) {
2797 GST_LOG_OBJECT (parse, "... but did not get that; marked draining");
2798 parse->priv->drain = TRUE;
2801 if (parse->priv->detecting) {
2802 ret = klass->detect (parse, buffer);
2803 if (ret == GST_FLOW_NOT_NEGOTIATED) {
2804 /* If draining we error out, otherwise request a buffer
2806 if (parse->priv->drain) {
2807 gst_buffer_unref (buffer);
2808 GST_ERROR_OBJECT (parse, "Failed to detect format but draining");
2809 return GST_FLOW_ERROR;
2812 gst_buffer_unref (buffer);
2815 } else if (ret != GST_FLOW_OK) {
2816 gst_buffer_unref (buffer);
2817 GST_ERROR_OBJECT (parse, "detect() returned %s",
2818 gst_flow_get_name (ret));
2822 /* Else handle this buffer normally */
2825 ret = gst_base_parse_handle_buffer (parse, buffer, &skip, &flushed);
2826 if (ret != GST_FLOW_OK)
2829 /* something flushed means something happened,
2830 * and we should bail out of this loop so as not to occupy
2831 * the task thread indefinitely */
2833 GST_LOG_OBJECT (parse, "frame finished, breaking loop");
2836 /* nothing flushed, no skip and draining, so nothing left to do */
2837 if (!skip && parse->priv->drain) {
2838 GST_LOG_OBJECT (parse, "no activity or result when draining; "
2839 "breaking loop and marking EOS");
2843 /* otherwise, get some more data
2844 * note that is checked this does not happen indefinitely */
2846 GST_LOG_OBJECT (parse, "getting some more data");
2849 parse->priv->drain = FALSE;
2856 /* Loop that is used in pull mode to retrieve data from upstream */
2858 gst_base_parse_loop (GstPad * pad)
2860 GstBaseParse *parse;
2861 GstBaseParseClass *klass;
2862 GstFlowReturn ret = GST_FLOW_OK;
2864 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2865 klass = GST_BASE_PARSE_GET_CLASS (parse);
2867 /* reverse playback:
2868 * first fragment (closest to stop time) is handled normally below,
2869 * then we pull in fragments going backwards */
2870 if (parse->segment.rate < 0.0) {
2871 /* check if we jumped back to a previous fragment,
2872 * which is a post-first fragment */
2873 if (parse->priv->offset < 0) {
2874 ret = gst_base_parse_handle_previous_fragment (parse);
2879 ret = gst_base_parse_scan_frame (parse, klass, TRUE);
2880 if (ret != GST_FLOW_OK)
2883 /* eat expected eos signalling past segment in reverse playback */
2884 if (parse->segment.rate < 0.0 && ret == GST_FLOW_EOS &&
2885 parse->segment.position >= parse->segment.stop) {
2886 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2887 /* push what was accumulated during loop run */
2888 gst_base_parse_finish_fragment (parse, FALSE);
2889 /* force previous fragment */
2890 parse->priv->offset = -1;
2895 if (ret == GST_FLOW_EOS)
2897 else if (ret != GST_FLOW_OK)
2900 gst_object_unref (parse);
2907 GST_DEBUG_OBJECT (parse, "eos");
2912 gboolean push_eos = FALSE;
2914 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2915 gst_flow_get_name (ret));
2916 gst_pad_pause_task (parse->sinkpad);
2918 if (ret == GST_FLOW_EOS) {
2919 /* handle end-of-stream/segment */
2920 if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2923 if ((stop = parse->segment.stop) == -1)
2924 stop = parse->segment.duration;
2926 GST_DEBUG_OBJECT (parse, "sending segment_done");
2928 gst_element_post_message
2929 (GST_ELEMENT_CAST (parse),
2930 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2931 GST_FORMAT_TIME, stop));
2933 /* If we STILL have zero frames processed, fire an error */
2934 if (parse->priv->framecount == 0) {
2935 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2936 ("No valid frames found before end of stream"), (NULL));
2940 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
2941 /* for fatal errors we post an error message, wrong-state is
2942 * not fatal because it happens due to flushes and only means
2943 * that we should stop now. */
2944 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2945 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2949 /* Push pending events, including NEWSEGMENT events */
2950 if (G_UNLIKELY (parse->priv->pending_events)) {
2953 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
2954 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
2956 g_list_free (parse->priv->pending_events);
2957 parse->priv->pending_events = NULL;
2958 parse->priv->pending_segment = FALSE;
2961 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2963 gst_object_unref (parse);
2968 gst_base_parse_sink_activate (GstPad * sinkpad, GstObject * parent)
2970 GstBaseParse *parse;
2974 parse = GST_BASE_PARSE (parent);
2976 GST_DEBUG_OBJECT (parse, "sink activate");
2978 query = gst_query_new_scheduling ();
2979 if (!gst_pad_peer_query (sinkpad, query)) {
2980 gst_query_unref (query);
2981 goto baseparse_push;
2984 pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL);
2985 gst_query_unref (query);
2988 goto baseparse_push;
2990 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2991 if (!gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE))
2992 goto baseparse_push;
2994 return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
2999 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
3000 return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
3005 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
3007 GstBaseParseClass *klass;
3008 gboolean result = TRUE;
3010 GST_DEBUG_OBJECT (parse, "activate %d", active);
3012 klass = GST_BASE_PARSE_GET_CLASS (parse);
3015 if (parse->priv->pad_mode == GST_PAD_MODE_NONE && klass->start)
3016 result = klass->start (parse);
3018 /* If the subclass implements ::detect we want to
3019 * call it for the first buffers now */
3020 parse->priv->detecting = (klass->detect != NULL);
3022 /* We must make sure streaming has finished before resetting things
3023 * and calling the ::stop vfunc */
3024 GST_PAD_STREAM_LOCK (parse->sinkpad);
3025 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3027 if (parse->priv->pad_mode != GST_PAD_MODE_NONE && klass->stop)
3028 result = klass->stop (parse);
3030 parse->priv->pad_mode = GST_PAD_MODE_NONE;
3032 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
3037 gst_base_parse_sink_activate_mode (GstPad * pad, GstObject * parent,
3038 GstPadMode mode, gboolean active)
3041 GstBaseParse *parse;
3043 parse = GST_BASE_PARSE (parent);
3045 GST_DEBUG_OBJECT (parse, "sink activate mode %d, %d", mode, active);
3047 if (!gst_base_parse_activate (parse, active))
3048 goto activate_failed;
3051 case GST_PAD_MODE_PULL:
3053 parse->priv->pending_events =
3054 g_list_append (parse->priv->pending_events,
3055 gst_event_new_segment (&parse->segment));
3056 parse->priv->pending_segment = TRUE;
3059 result = gst_pad_stop_task (pad);
3067 parse->priv->pad_mode = active ? mode : GST_PAD_MODE_NONE;
3069 GST_DEBUG_OBJECT (parse, "sink activate return: %d", result);
3076 GST_DEBUG_OBJECT (parse, "activate failed");
3082 * gst_base_parse_set_duration:
3083 * @parse: #GstBaseParse.
3085 * @duration: duration value.
3086 * @interval: how often to update the duration estimate based on bitrate, or 0.
3088 * Sets the duration of the currently playing media. Subclass can use this
3089 * when it is able to determine duration and/or notices a change in the media
3090 * duration. Alternatively, if @interval is non-zero (default), then stream
3091 * duration is determined based on estimated bitrate, and updated every @interval
3097 gst_base_parse_set_duration (GstBaseParse * parse,
3098 GstFormat fmt, gint64 duration, gint interval)
3100 g_return_if_fail (parse != NULL);
3102 if (parse->priv->upstream_has_duration) {
3103 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
3107 if (duration != parse->priv->duration) {
3110 m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
3111 gst_element_post_message (GST_ELEMENT (parse), m);
3113 /* TODO: what about duration tag? */
3115 parse->priv->duration = duration;
3116 parse->priv->duration_fmt = fmt;
3117 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
3118 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
3119 if (interval != 0) {
3120 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
3124 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
3125 parse->priv->update_interval = interval;
3131 * gst_base_parse_set_average_bitrate:
3132 * @parse: #GstBaseParse.
3133 * @bitrate: average bitrate in bits/second
3135 * Optionally sets the average bitrate detected in media (if non-zero),
3136 * e.g. based on metadata, as it will be posted to the application.
3138 * By default, announced average bitrate is estimated. The average bitrate
3139 * is used to estimate the total duration of the stream and to estimate
3140 * a seek position, if there's no index and the format is syncable
3141 * (see gst_base_parse_set_syncable()).
3146 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
3148 parse->priv->bitrate = bitrate;
3149 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
3153 * gst_base_parse_set_min_frame_size:
3154 * @parse: #GstBaseParse.
3155 * @min_size: Minimum size of the data that this base class should give to
3158 * Subclass can use this function to tell the base class that it needs to
3159 * give at least #min_size buffers.
3164 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
3166 g_return_if_fail (parse != NULL);
3168 parse->priv->min_frame_size = min_size;
3169 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
3173 * gst_base_parse_set_frame_rate:
3174 * @parse: the #GstBaseParse to set
3175 * @fps_num: frames per second (numerator).
3176 * @fps_den: frames per second (denominator).
3177 * @lead_in: frames needed before a segment for subsequent decode
3178 * @lead_out: frames needed after a segment
3180 * If frames per second is configured, parser can take care of buffer duration
3181 * and timestamping. When performing segment clipping, or seeking to a specific
3182 * location, a corresponding decoder might need an initial @lead_in and a
3183 * following @lead_out number of frames to ensure the desired segment is
3184 * entirely filled upon decoding.
3189 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
3190 guint fps_den, guint lead_in, guint lead_out)
3192 g_return_if_fail (parse != NULL);
3194 parse->priv->fps_num = fps_num;
3195 parse->priv->fps_den = fps_den;
3196 if (!fps_num || !fps_den) {
3197 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
3199 fps_num = fps_den = 0;
3200 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
3201 parse->priv->lead_in = parse->priv->lead_out = 0;
3202 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
3204 parse->priv->frame_duration =
3205 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
3206 parse->priv->lead_in = lead_in;
3207 parse->priv->lead_out = lead_out;
3208 parse->priv->lead_in_ts =
3209 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
3210 parse->priv->lead_out_ts =
3211 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
3212 /* aim for about 1.5s to estimate duration */
3213 if (parse->priv->update_interval < 0) {
3214 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
3215 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
3216 parse->priv->update_interval);
3219 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
3220 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
3221 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
3222 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
3223 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
3224 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
3228 * gst_base_parse_set_has_timing_info:
3229 * @parse: a #GstBaseParse
3230 * @has_timing: whether frames carry timing information
3232 * Set if frames carry timing information which the subclass can (generally)
3233 * parse and provide. In particular, intrinsic (rather than estimated) time
3234 * can be obtained following a seek.
3239 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3241 parse->priv->has_timing_info = has_timing;
3242 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3246 * gst_base_parse_set_syncable:
3247 * @parse: a #GstBaseParse
3248 * @syncable: set if frame starts can be identified
3250 * Set if frame starts can be identified. This is set by default and
3251 * determines whether seeking based on bitrate averages
3252 * is possible for a format/stream.
3257 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3259 parse->priv->syncable = syncable;
3260 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3264 * gst_base_parse_set_passthrough:
3265 * @parse: a #GstBaseParse
3266 * @passthrough: %TRUE if parser should run in passthrough mode
3268 * Set if the nature of the format or configuration does not allow (much)
3269 * parsing, and the parser should operate in passthrough mode (which only
3270 * applies when operating in push mode). That is, incoming buffers are
3271 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3272 * callbacks will be invoked, but @pre_push_frame will still be invoked,
3273 * so subclass can perform as much or as little is appropriate for
3274 * passthrough semantics in @pre_push_frame.
3279 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3281 parse->priv->passthrough = passthrough;
3282 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3286 * gst_base_parse_set_latency:
3287 * @parse: a #GstBaseParse
3288 * @min_latency: minimum parse latency
3289 * @max_latency: maximum parse latency
3291 * Sets the minimum and maximum (which may likely be equal) latency introduced
3292 * by the parsing process. If there is such a latency, which depends on the
3293 * particular parsing of the format, it typically corresponds to 1 frame duration.
3298 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3299 GstClockTime max_latency)
3301 GST_OBJECT_LOCK (parse);
3302 parse->priv->min_latency = min_latency;
3303 parse->priv->max_latency = max_latency;
3304 GST_OBJECT_UNLOCK (parse);
3305 GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3306 GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3307 GST_TIME_ARGS (max_latency));
3311 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3312 GstClockTime * duration)
3314 gboolean res = FALSE;
3316 g_return_val_if_fail (duration != NULL, FALSE);
3318 *duration = GST_CLOCK_TIME_NONE;
3319 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3320 GST_LOG_OBJECT (parse, "using provided duration");
3321 *duration = parse->priv->duration;
3323 } else if (parse->priv->duration != -1) {
3324 GST_LOG_OBJECT (parse, "converting provided duration");
3325 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3326 parse->priv->duration, format, (gint64 *) duration);
3327 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3328 GST_LOG_OBJECT (parse, "using estimated duration");
3329 *duration = parse->priv->estimated_duration;
3332 GST_LOG_OBJECT (parse, "cannot estimate duration");
3335 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3336 GST_TIME_ARGS (*duration));
3341 gst_base_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
3343 GstBaseParse *parse;
3344 gboolean res = FALSE;
3346 parse = GST_BASE_PARSE (parent);
3348 GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3350 switch (GST_QUERY_TYPE (query)) {
3351 case GST_QUERY_POSITION:
3356 GST_DEBUG_OBJECT (parse, "position query");
3357 gst_query_parse_position (query, &format, NULL);
3359 /* try upstream first */
3360 res = gst_pad_query_default (pad, parent, query);
3362 /* Fall back on interpreting segment */
3363 GST_OBJECT_LOCK (parse);
3364 if (format == GST_FORMAT_BYTES) {
3365 dest_value = parse->priv->offset;
3367 } else if (format == parse->segment.format &&
3368 GST_CLOCK_TIME_IS_VALID (parse->segment.position)) {
3369 dest_value = gst_segment_to_stream_time (&parse->segment,
3370 parse->segment.format, parse->segment.position);
3373 GST_OBJECT_UNLOCK (parse);
3375 /* no precise result, upstream no idea either, then best estimate */
3376 /* priv->offset is updated in both PUSH/PULL modes */
3377 res = gst_base_parse_convert (parse,
3378 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3381 gst_query_set_position (query, format, dest_value);
3385 case GST_QUERY_DURATION:
3388 GstClockTime duration;
3390 GST_DEBUG_OBJECT (parse, "duration query");
3391 gst_query_parse_duration (query, &format, NULL);
3393 /* consult upstream */
3394 res = gst_pad_query_default (pad, parent, query);
3396 /* otherwise best estimate from us */
3398 res = gst_base_parse_get_duration (parse, format, &duration);
3400 gst_query_set_duration (query, format, duration);
3404 case GST_QUERY_SEEKING:
3407 GstClockTime duration = GST_CLOCK_TIME_NONE;
3408 gboolean seekable = FALSE;
3410 GST_DEBUG_OBJECT (parse, "seeking query");
3411 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3413 /* consult upstream */
3414 res = gst_pad_query_default (pad, parent, query);
3416 /* we may be able to help if in TIME */
3417 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3418 gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3419 /* already OK if upstream takes care */
3420 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3422 if (!(res && seekable)) {
3423 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3424 || duration == -1) {
3425 /* seekable if we still have a chance to get duration later on */
3427 parse->priv->upstream_seekable && parse->priv->update_interval;
3429 seekable = parse->priv->upstream_seekable;
3430 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3433 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3439 case GST_QUERY_FORMATS:
3440 gst_query_set_formatsv (query, 3, fmtlist);
3443 case GST_QUERY_CONVERT:
3445 GstFormat src_format, dest_format;
3446 gint64 src_value, dest_value;
3448 gst_query_parse_convert (query, &src_format, &src_value,
3449 &dest_format, &dest_value);
3451 res = gst_base_parse_convert (parse, src_format, src_value,
3452 dest_format, &dest_value);
3454 gst_query_set_convert (query, src_format, src_value,
3455 dest_format, dest_value);
3459 case GST_QUERY_LATENCY:
3461 if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3463 GstClockTime min_latency, max_latency;
3465 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3466 GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3467 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3468 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3470 GST_OBJECT_LOCK (parse);
3471 /* add our latency */
3472 if (min_latency != -1)
3473 min_latency += parse->priv->min_latency;
3474 if (max_latency != -1)
3475 max_latency += parse->priv->max_latency;
3476 GST_OBJECT_UNLOCK (parse);
3478 gst_query_set_latency (query, live, min_latency, max_latency);
3483 res = gst_pad_query_default (pad, parent, query);
3489 /* scans for a cluster start from @pos,
3490 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3491 static GstFlowReturn
3492 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3493 GstClockTime * time, GstClockTime * duration)
3495 GstBaseParseClass *klass;
3497 gboolean orig_drain, orig_discont;
3498 GstFlowReturn ret = GST_FLOW_OK;
3499 GstBuffer *buf = NULL;
3500 GstBaseParseFrame *sframe = NULL;
3502 g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3503 g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3504 g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3506 klass = GST_BASE_PARSE_GET_CLASS (parse);
3508 *time = GST_CLOCK_TIME_NONE;
3509 *duration = GST_CLOCK_TIME_NONE;
3512 orig_offset = parse->priv->offset;
3513 orig_discont = parse->priv->discont;
3514 orig_drain = parse->priv->drain;
3516 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3517 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3519 /* jump elsewhere and locate next frame */
3520 parse->priv->offset = *pos;
3521 /* mark as scanning so frames don't get processed all the way */
3522 parse->priv->scanning = TRUE;
3523 ret = gst_base_parse_scan_frame (parse, klass, FALSE);
3524 parse->priv->scanning = FALSE;
3525 /* retrieve frame found during scan */
3526 sframe = parse->priv->scanned_frame;
3527 parse->priv->scanned_frame = NULL;
3529 if (ret != GST_FLOW_OK || !sframe)
3532 /* get offset first, subclass parsing might dump other stuff in there */
3533 *pos = sframe->offset;
3534 buf = sframe->buffer;
3537 /* but it should provide proper time */
3538 *time = GST_BUFFER_TIMESTAMP (buf);
3539 *duration = GST_BUFFER_DURATION (buf);
3541 GST_LOG_OBJECT (parse,
3542 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3543 GST_TIME_ARGS (*time), *pos);
3547 gst_base_parse_frame_free (sframe);
3550 parse->priv->offset = orig_offset;
3551 parse->priv->discont = orig_discont;
3552 parse->priv->drain = orig_drain;
3557 /* bisect and scan through file for frame starting before @time,
3558 * returns OK and @time/@offset if found, NONE and/or error otherwise
3559 * If @time == G_MAXINT64, scan for duration ( == last frame) */
3560 static GstFlowReturn
3561 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3564 GstFlowReturn ret = GST_FLOW_OK;
3565 gint64 lpos, hpos, newpos;
3566 GstClockTime time, ltime, htime, newtime, dur;
3567 gboolean cont = TRUE;
3568 const GstClockTime tolerance = TARGET_DIFFERENCE;
3569 const guint chunk = 4 * 1024;
3571 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3572 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3574 GST_DEBUG_OBJECT (parse, "Bisecting for time %" GST_TIME_FORMAT,
3575 GST_TIME_ARGS (*_time));
3577 /* TODO also make keyframe aware if useful some day */
3592 /* do not know at first */
3594 *_time = GST_CLOCK_TIME_NONE;
3596 /* need initial positions; start and end */
3597 lpos = parse->priv->first_frame_offset;
3598 ltime = parse->priv->first_frame_ts;
3599 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &htime)) {
3600 GST_DEBUG_OBJECT (parse, "Unknown time duration, cannot bisect");
3601 return GST_FLOW_ERROR;
3603 hpos = parse->priv->upstream_size;
3605 GST_DEBUG_OBJECT (parse,
3606 "Bisection initial bounds: bytes %" G_GINT64_FORMAT " %" G_GINT64_FORMAT
3607 ", times %" GST_TIME_FORMAT " %" GST_TIME_FORMAT, lpos, htime,
3608 GST_TIME_ARGS (ltime), GST_TIME_ARGS (htime));
3610 /* check preconditions are satisfied;
3611 * start and end are needed, except for special case where we scan for
3612 * last frame to determine duration */
3613 if (parse->priv->pad_mode != GST_PAD_MODE_PULL || !hpos ||
3614 !GST_CLOCK_TIME_IS_VALID (ltime) ||
3615 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3619 /* shortcut cases */
3622 } else if (time < ltime + tolerance) {
3626 } else if (time >= htime) {
3632 while (htime > ltime && cont) {
3633 GST_LOG_OBJECT (parse,
3634 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3635 GST_TIME_ARGS (ltime));
3636 GST_LOG_OBJECT (parse,
3637 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3638 GST_TIME_ARGS (htime));
3639 if (G_UNLIKELY (time == G_MAXINT64)) {
3641 } else if (G_LIKELY (hpos > lpos)) {
3643 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3646 /* should mean lpos == hpos, since lpos <= hpos is invariant */
3648 /* we check this case once, but not forever, so break loop */
3653 newpos = CLAMP (newpos, lpos, hpos);
3654 GST_LOG_OBJECT (parse,
3655 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3656 GST_TIME_ARGS (time), newpos);
3658 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3659 if (ret == GST_FLOW_EOS) {
3660 /* heuristic HACK */
3661 hpos = MAX (lpos, hpos - chunk);
3663 } else if (ret != GST_FLOW_OK) {
3667 if (newtime == -1 || newpos == -1) {
3668 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3672 if (G_UNLIKELY (time == G_MAXINT64)) {
3675 if (GST_CLOCK_TIME_IS_VALID (dur))
3678 } else if (newtime > time) {
3680 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3682 } else if (newtime + tolerance > time) {
3683 /* close enough undershoot */
3687 } else if (newtime < ltime) {
3688 /* so a position beyond lpos resulted in earlier time than ltime ... */
3689 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3692 /* undershoot too far */
3693 newpos += newpos == lpos ? chunk : 0;
3694 lpos = CLAMP (newpos, lpos, hpos);
3700 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3701 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3706 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3707 gboolean before, GstClockTime * _ts)
3709 gint64 bytes = 0, ts = 0;
3710 GstIndexEntry *entry = NULL;
3712 if (time == GST_CLOCK_TIME_NONE) {
3718 GST_BASE_PARSE_INDEX_LOCK (parse);
3719 if (parse->priv->index) {
3720 /* Let's check if we have an index entry for that time */
3721 entry = gst_index_get_assoc_entry (parse->priv->index,
3722 parse->priv->index_id,
3723 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3724 GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3728 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3729 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3731 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3732 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3733 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3735 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3736 GST_TIME_ARGS (time));
3739 ts = GST_CLOCK_TIME_NONE;
3742 GST_BASE_PARSE_INDEX_UNLOCK (parse);
3751 /* returns TRUE if seek succeeded */
3753 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3758 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3759 gboolean flush, update, res = TRUE, accurate;
3760 gint64 cur, stop, seekpos, seekstop;
3761 GstSegment seeksegment = { 0, };
3762 GstClockTime start_ts;
3764 gst_event_parse_seek (event, &rate, &format, &flags,
3765 &cur_type, &cur, &stop_type, &stop);
3767 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3768 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3769 GST_TIME_FORMAT, gst_format_get_name (format), rate,
3770 cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3772 /* no negative rates in push mode */
3773 if (rate < 0.0 && parse->priv->pad_mode == GST_PAD_MODE_PUSH)
3776 if (cur_type != GST_SEEK_TYPE_SET ||
3777 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3780 /* For any format other than TIME, see if upstream handles
3781 * it directly or fail. For TIME, try upstream, but do it ourselves if
3782 * it fails upstream */
3783 res = gst_pad_push_event (parse->sinkpad, event);
3784 if (format != GST_FORMAT_TIME || res)
3787 /* get flush flag */
3788 flush = flags & GST_SEEK_FLAG_FLUSH;
3790 /* copy segment, we need this because we still need the old
3791 * segment when we close the current segment. */
3792 gst_segment_copy_into (&parse->segment, &seeksegment);
3794 GST_DEBUG_OBJECT (parse, "configuring seek");
3795 gst_segment_do_seek (&seeksegment, rate, format, flags,
3796 cur_type, cur, stop_type, stop, &update);
3798 /* accurate seeking implies seek tables are used to obtain position,
3799 * and the requested segment is maintained exactly, not adjusted any way */
3800 accurate = flags & GST_SEEK_FLAG_ACCURATE;
3802 /* maybe we can be accurate for (almost) free */
3803 gst_base_parse_find_offset (parse, seeksegment.position, TRUE, &start_ts);
3804 if (seeksegment.position <= start_ts + TARGET_DIFFERENCE) {
3805 GST_DEBUG_OBJECT (parse, "accurate seek possible");
3809 GstClockTime startpos = seeksegment.position;
3811 /* accurate requested, so ... seek a bit before target */
3812 if (startpos < parse->priv->lead_in_ts)
3815 startpos -= parse->priv->lead_in_ts;
3816 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3817 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3820 start_ts = seeksegment.position;
3821 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.position,
3822 GST_FORMAT_BYTES, &seekpos))
3823 goto convert_failed;
3824 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3825 GST_FORMAT_BYTES, &seekstop))
3826 goto convert_failed;
3829 GST_DEBUG_OBJECT (parse,
3830 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3832 GST_DEBUG_OBJECT (parse,
3833 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3834 seeksegment.stop, seekstop);
3836 if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
3839 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3842 if (parse->srcpad) {
3843 GST_DEBUG_OBJECT (parse, "sending flush start");
3844 gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3845 /* unlock upstream pull_range */
3846 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3849 gst_pad_pause_task (parse->sinkpad);
3852 /* we should now be able to grab the streaming thread because we stopped it
3853 * with the above flush/pause code */
3854 GST_PAD_STREAM_LOCK (parse->sinkpad);
3856 /* save current position */
3857 last_stop = parse->segment.position;
3858 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3861 /* now commit to new position */
3863 /* prepare for streaming again */
3865 GST_DEBUG_OBJECT (parse, "sending flush stop");
3866 gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop (TRUE));
3867 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop (TRUE));
3868 gst_base_parse_clear_queues (parse);
3870 /* keep track of our position */
3871 seeksegment.base = gst_segment_to_running_time (&seeksegment,
3872 seeksegment.format, parse->segment.position);
3875 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3877 /* store the newsegment event so it can be sent from the streaming thread. */
3878 /* This will be sent later in _loop() */
3879 parse->priv->pending_segment = TRUE;
3880 parse->priv->pending_events =
3881 g_list_append (parse->priv->pending_events,
3882 gst_event_new_segment (&parse->segment));
3884 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3885 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3886 ", pos = %" GST_TIME_FORMAT, format,
3887 GST_TIME_ARGS (parse->segment.start),
3888 GST_TIME_ARGS (parse->segment.stop),
3889 GST_TIME_ARGS (parse->segment.start));
3891 /* one last chance in pull mode to stay accurate;
3892 * maybe scan and subclass can find where to go */
3895 GstClockTime ts = seeksegment.position;
3897 gst_base_parse_locate_time (parse, &ts, &scanpos);
3901 /* running collected index now consists of several intervals,
3902 * so optimized check no longer possible */
3903 parse->priv->index_last_valid = FALSE;
3904 parse->priv->index_last_offset = 0;
3905 parse->priv->index_last_ts = 0;
3909 /* mark discont if we are going to stream from another position. */
3910 if (seekpos != parse->priv->offset) {
3911 GST_DEBUG_OBJECT (parse,
3912 "mark DISCONT, we did a seek to another position");
3913 parse->priv->offset = seekpos;
3914 parse->priv->last_offset = seekpos;
3915 parse->priv->seen_keyframe = FALSE;
3916 parse->priv->discont = TRUE;
3917 parse->priv->next_ts = start_ts;
3918 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3919 parse->priv->sync_offset = seekpos;
3920 parse->priv->exact_position = accurate;
3923 /* Start streaming thread if paused */
3924 gst_pad_start_task (parse->sinkpad,
3925 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3927 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3932 GstEvent *new_event;
3933 GstBaseParseSeek *seek;
3934 GstSeekFlags flags = (flush ? GST_SEEK_FLAG_FLUSH : GST_SEEK_FLAG_NONE);
3936 /* The only thing we need to do in PUSH-mode is to send the
3937 seek event (in bytes) to upstream. Segment / flush handling happens
3938 in corresponding src event handlers */
3939 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3940 if (seekstop >= 0 && seekstop <= seekpos)
3942 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
3943 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3945 /* store segment info so its precise details can be reconstructed when
3946 * receiving newsegment;
3947 * this matters for all details when accurate seeking,
3948 * is most useful to preserve NONE stop time otherwise */
3949 seek = g_new0 (GstBaseParseSeek, 1);
3950 seek->segment = seeksegment;
3951 seek->accurate = accurate;
3952 seek->offset = seekpos;
3953 seek->start_ts = start_ts;
3954 GST_OBJECT_LOCK (parse);
3955 /* less optimal, but preserves order */
3956 parse->priv->pending_seeks =
3957 g_slist_append (parse->priv->pending_seeks, seek);
3958 GST_OBJECT_UNLOCK (parse);
3960 res = gst_pad_push_event (parse->sinkpad, new_event);
3963 GST_OBJECT_LOCK (parse);
3964 parse->priv->pending_seeks =
3965 g_slist_remove (parse->priv->pending_seeks, seek);
3966 GST_OBJECT_UNLOCK (parse);
3977 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
3983 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3989 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3995 /* Checks if bitrates are available from upstream tags so that we don't
3996 * override them later
3999 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
4001 GstTagList *taglist = NULL;
4004 gst_event_parse_tag (event, &taglist);
4006 if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
4007 GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
4008 parse->priv->post_min_bitrate = FALSE;
4010 if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
4011 GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
4012 parse->priv->post_avg_bitrate = FALSE;
4014 if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
4015 GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
4016 parse->priv->post_max_bitrate = FALSE;
4022 gst_base_parse_set_index (GstElement * element, GstIndex * index)
4024 GstBaseParse *parse = GST_BASE_PARSE (element);
4026 GST_BASE_PARSE_INDEX_LOCK (parse);
4027 if (parse->priv->index)
4028 gst_object_unref (parse->priv->index);
4030 parse->priv->index = gst_object_ref (index);
4031 gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
4032 &parse->priv->index_id);
4033 parse->priv->own_index = FALSE;
4035 parse->priv->index = NULL;
4037 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4041 gst_base_parse_get_index (GstElement * element)
4043 GstBaseParse *parse = GST_BASE_PARSE (element);
4044 GstIndex *result = NULL;
4046 GST_BASE_PARSE_INDEX_LOCK (parse);
4047 if (parse->priv->index)
4048 result = gst_object_ref (parse->priv->index);
4049 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4055 static GstStateChangeReturn
4056 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
4058 GstBaseParse *parse;
4059 GstStateChangeReturn result;
4061 parse = GST_BASE_PARSE (element);
4063 switch (transition) {
4064 case GST_STATE_CHANGE_READY_TO_PAUSED:
4065 /* If this is our own index destroy it as the
4066 * old entries might be wrong for the new stream */
4067 GST_BASE_PARSE_INDEX_LOCK (parse);
4068 if (parse->priv->own_index) {
4069 gst_object_unref (parse->priv->index);
4070 parse->priv->index = NULL;
4071 parse->priv->own_index = FALSE;
4074 /* If no index was created, generate one */
4075 if (G_UNLIKELY (!parse->priv->index)) {
4076 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
4078 parse->priv->index = g_object_new (gst_mem_index_get_type (), NULL);
4079 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
4080 &parse->priv->index_id);
4081 parse->priv->own_index = TRUE;
4083 GST_BASE_PARSE_INDEX_UNLOCK (parse);
4089 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4091 switch (transition) {
4092 case GST_STATE_CHANGE_PAUSED_TO_READY:
4093 gst_base_parse_reset (parse);