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>.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
16 * You should have received a copy of the GNU Library General Public
17 * License along with this library; if not, write to the
18 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 * Boston, MA 02111-1307, USA.
23 * SECTION:gstbaseparse
24 * @short_description: Base class for stream parsers
25 * @see_also: #GstBaseTransform
27 * This base class is for parser elements that process data and splits it
28 * into separate audio/video/whatever frames.
32 * <listitem><para>provides one sink pad and one source pad</para></listitem>
33 * <listitem><para>handles state changes</para></listitem>
34 * <listitem><para>can operate in pull mode or push mode</para></listitem>
35 * <listitem><para>handles seeking in both modes</para></listitem>
36 * <listitem><para>handles events (NEWSEGMENT/EOS/FLUSH)</para></listitem>
38 * handles queries (POSITION/DURATION/SEEKING/FORMAT/CONVERT)
40 * <listitem><para>handles flushing</para></listitem>
43 * The purpose of this base class is to provide the basic functionality of
44 * a parser and share a lot of rather complex code.
46 * Description of the parsing mechanism:
49 * <itemizedlist><title>Set-up phase</title>
51 * GstBaseParse class calls @set_sink_caps to inform the subclass about
52 * incoming sinkpad caps. Subclass should set the srcpad caps accordingly.
55 * GstBaseParse calls @start to inform subclass that data processing is
59 * At least at this point subclass needs to tell the GstBaseParse class
60 * how big data chunks it wants to receive (min_frame_size). It can do
61 * this with gst_base_parse_set_min_frame_size().
64 * GstBaseParse class sets up appropriate data passing mode (pull/push)
65 * and starts to process the data.
71 * <title>Parsing phase</title>
73 * GstBaseParse gathers at least min_frame_size bytes of data either
74 * by pulling it from upstream or collecting buffers in an internal
78 * A buffer of (at least) min_frame_size bytes is passed to subclass with
79 * @check_valid_frame. Subclass checks the contents and returns TRUE
80 * if the buffer contains a valid frame. It also needs to set the
81 * @framesize according to the detected frame size. If buffer didn't
82 * contain a valid frame, this call must return FALSE and optionally
83 * set the @skipsize value to inform base class that how many bytes
84 * it needs to skip in order to find a valid frame. @framesize can always
85 * indicate a new minimum for current frame parsing. Indicating G_MAXUINT
86 * for requested amount means subclass simply needs best available
87 * subsequent data. In push mode this amounts to an additional input buffer
88 * (thus minimal additional latency), in pull mode this amounts to some
89 * arbitrary reasonable buffer size increase. The passed buffer
90 * is read-only. Note that @check_valid_frame might receive any small
91 * amount of input data when leftover data is being drained (e.g. at EOS).
94 * After valid frame is found, it will be passed again to subclass with
95 * @parse_frame call. Now subclass is responsible for parsing the
96 * frame contents and setting the caps, and buffer metadata (e.g.
97 * buffer timestamp and duration, or keyframe if applicable).
98 * (although the latter can also be done by GstBaseParse if it is
99 * appropriately configured, see below). Frame is provided with
100 * timestamp derived from upstream (as much as generally possible),
101 * duration obtained from configuration (see below), and offset
102 * if meaningful (in pull mode).
105 * Finally the buffer can be pushed downstream and the parsing loop starts
106 * over again. Just prior to actually pushing the buffer in question,
107 * it is passed to @pre_push_buffer which gives subclass yet one
108 * last chance to examine buffer metadata, or to send some custom (tag)
109 * events, or to perform custom (segment) filtering.
112 * During the parsing process GstBaseParseClass will handle both srcpad
113 * and sinkpad events. They will be passed to subclass if @event or
114 * @src_event callbacks have been provided.
119 * <itemizedlist><title>Shutdown phase</title>
121 * GstBaseParse class calls @stop to inform the subclass that data
122 * parsing will be stopped.
128 * Subclass is responsible for providing pad template caps for
129 * source and sink pads. The pads need to be named "sink" and "src". It also
130 * needs to set the fixed caps on srcpad, when the format is ensured (e.g.
131 * when base class calls subclass' @set_sink_caps function).
133 * This base class uses #GST_FORMAT_DEFAULT as a meaning of frames. So,
134 * subclass conversion routine needs to know that conversion from
135 * #GST_FORMAT_TIME to #GST_FORMAT_DEFAULT must return the
136 * frame number that can be found from the given byte position.
138 * GstBaseParse uses subclasses conversion methods also for seeking (or
139 * otherwise uses its own default one, see also below).
141 * Subclass @start and @stop functions will be called to inform the beginning
142 * and end of data processing.
144 * Things that subclass need to take care of:
146 * <listitem><para>Provide pad templates</para></listitem>
148 * Fixate the source pad caps when appropriate
151 * Inform base class how big data chunks should be retrieved. This is
152 * done with gst_base_parse_set_min_frame_size() function.
155 * Examine data chunks passed to subclass with @check_valid_frame
156 * and tell if they contain a valid frame
159 * Set the caps and timestamp to frame that is passed to subclass with
160 * @parse_frame function.
162 * <listitem><para>Provide conversion functions</para></listitem>
164 * Update the duration information with gst_base_parse_set_duration()
167 * Optionally passthrough using gst_base_parse_set_passthrough()
170 * Configure various baseparse parameters using
171 * gst_base_parse_set_average_bitrate(), gst_base_parse_set_syncable()
172 * and gst_base_parse_set_frame_rate().
175 * In particular, if subclass is unable to determine a duration, but
176 * parsing (or specs) yields a frames per seconds rate, then this can be
177 * provided to GstBaseParse to enable it to cater for
178 * buffer time metadata (which will be taken from upstream as much as
179 * possible). Internally keeping track of frame durations and respective
180 * sizes that have been pushed provides GstBaseParse with an estimated
181 * bitrate. A default @convert (used if not overriden) will then use these
182 * rates to perform obvious conversions. These rates are also used to
183 * update (estimated) duration at regular frame intervals.
190 * - In push mode provide a queue of adapter-"queued" buffers for upstream
192 * - Queue buffers/events until caps are set
202 #include <gst/base/gstadapter.h>
204 #include "gstbaseparse.h"
206 #define GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC (1 << 0)
208 #define MIN_FRAMES_TO_POST_BITRATE 10
209 #define TARGET_DIFFERENCE (20 * GST_SECOND)
211 GST_DEBUG_CATEGORY_STATIC (gst_base_parse_debug);
212 #define GST_CAT_DEFAULT gst_base_parse_debug
214 /* Supported formats */
215 static const GstFormat fmtlist[] = {
222 #define GST_BASE_PARSE_GET_PRIVATE(obj) \
223 (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_PARSE, GstBaseParsePrivate))
225 struct _GstBaseParsePrivate
227 GstActivateMode pad_mode;
232 GstFormat duration_fmt;
233 gint64 estimated_duration;
235 guint min_frame_size;
236 gboolean passthrough;
238 gboolean has_timing_info;
239 guint fps_num, fps_den;
240 gint update_interval;
242 guint lead_in, lead_out;
243 GstClockTime lead_in_ts, lead_out_ts;
244 GstClockTime min_latency, max_latency;
252 GstClockTime next_ts;
253 GstClockTime prev_ts;
254 GstClockTime frame_duration;
255 gboolean seen_keyframe;
260 guint64 data_bytecount;
261 guint64 acc_duration;
262 GstClockTime first_frame_ts;
263 gint64 first_frame_offset;
265 gboolean post_min_bitrate;
266 gboolean post_avg_bitrate;
267 gboolean post_max_bitrate;
271 guint posted_avg_bitrate;
273 GList *pending_events;
275 /* frames/buffers that are queued and ready to go on OK */
276 GQueue queued_frames;
280 /* index entry storage, either ours or provided */
284 GStaticMutex index_lock;
286 /* seek table entries only maintained if upstream is BYTE seekable */
287 gboolean upstream_seekable;
288 gboolean upstream_has_duration;
289 gint64 upstream_size;
290 /* minimum distance between two index entries */
291 GstClockTimeDiff idx_interval;
292 /* ts and offset of last entry added */
293 GstClockTime index_last_ts;
294 gint64 index_last_offset;
295 gboolean index_last_valid;
297 /* timestamps currently produced are accurate, e.g. started from 0 onwards */
298 gboolean exact_position;
299 /* seek events are temporarily kept to match them with newsegments */
300 GSList *pending_seeks;
302 /* reverse playback */
303 GSList *buffers_pending;
304 GSList *buffers_queued;
305 GSList *buffers_send;
306 GstClockTime last_ts;
309 /* Newsegment event to be sent after SEEK */
310 GstEvent *pending_segment;
312 /* Segment event that closes the running segment prior to SEEK */
313 GstEvent *close_segment;
315 /* push mode helper frame */
316 GstBaseParseFrame frame;
319 typedef struct _GstBaseParseSeek
324 GstClockTime start_ts;
327 static GstElementClass *parent_class = NULL;
329 static void gst_base_parse_class_init (GstBaseParseClass * klass);
330 static void gst_base_parse_init (GstBaseParse * parse,
331 GstBaseParseClass * klass);
334 gst_base_parse_get_type (void)
336 static volatile gsize base_parse_type = 0;
338 if (g_once_init_enter (&base_parse_type)) {
339 static const GTypeInfo base_parse_info = {
340 sizeof (GstBaseParseClass),
341 (GBaseInitFunc) NULL,
342 (GBaseFinalizeFunc) NULL,
343 (GClassInitFunc) gst_base_parse_class_init,
346 sizeof (GstBaseParse),
348 (GInstanceInitFunc) gst_base_parse_init,
352 _type = g_type_register_static (GST_TYPE_ELEMENT,
353 "GstBaseParse", &base_parse_info, G_TYPE_FLAG_ABSTRACT);
354 g_once_init_leave (&base_parse_type, _type);
356 return (GType) base_parse_type;
359 static void gst_base_parse_finalize (GObject * object);
361 static GstStateChangeReturn gst_base_parse_change_state (GstElement * element,
362 GstStateChange transition);
363 static void gst_base_parse_reset (GstBaseParse * parse);
365 static void gst_base_parse_set_index (GstElement * element, GstIndex * index);
366 static GstIndex *gst_base_parse_get_index (GstElement * element);
368 static gboolean gst_base_parse_sink_activate (GstPad * sinkpad);
369 static gboolean gst_base_parse_sink_activate_push (GstPad * pad,
371 static gboolean gst_base_parse_sink_activate_pull (GstPad * pad,
373 static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
375 static void gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event);
377 static gboolean gst_base_parse_src_event (GstPad * pad, GstEvent * event);
378 static gboolean gst_base_parse_sink_event (GstPad * pad, GstEvent * event);
379 static gboolean gst_base_parse_query (GstPad * pad, GstQuery * query);
380 static const GstQueryType *gst_base_parse_get_querytypes (GstPad * pad);
382 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstBuffer * buffer);
383 static void gst_base_parse_loop (GstPad * pad);
385 static gboolean gst_base_parse_check_frame (GstBaseParse * parse,
386 GstBaseParseFrame * frame, guint * framesize, gint * skipsize);
387 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
388 GstBaseParseFrame * frame);
390 static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
393 static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
396 static void gst_base_parse_drain (GstBaseParse * parse);
398 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
399 gboolean post_min, gboolean post_avg, gboolean post_max);
401 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
402 GstClockTime time, gboolean before, GstClockTime * _ts);
403 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
404 GstClockTime * _time, gint64 * _offset);
406 static GstFlowReturn gst_base_parse_process_fragment (GstBaseParse * parse,
409 static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);
412 gst_base_parse_clear_queues (GstBaseParse * parse)
414 g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
415 g_slist_free (parse->priv->buffers_queued);
416 parse->priv->buffers_queued = NULL;
417 g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
419 g_slist_free (parse->priv->buffers_pending);
420 parse->priv->buffers_pending = NULL;
421 g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
422 g_slist_free (parse->priv->buffers_send);
423 parse->priv->buffers_send = NULL;
427 gst_base_parse_finalize (GObject * object)
429 GstBaseParse *parse = GST_BASE_PARSE (object);
432 g_object_unref (parse->priv->adapter);
434 if (parse->priv->pending_segment) {
435 p_ev = &parse->priv->pending_segment;
436 gst_event_replace (p_ev, NULL);
438 if (parse->priv->close_segment) {
439 p_ev = &parse->priv->close_segment;
440 gst_event_replace (p_ev, NULL);
443 if (parse->priv->cache) {
444 gst_buffer_unref (parse->priv->cache);
445 parse->priv->cache = NULL;
448 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
450 g_list_free (parse->priv->pending_events);
451 parse->priv->pending_events = NULL;
453 g_queue_foreach (&parse->priv->queued_frames,
454 (GFunc) gst_base_parse_frame_free, NULL);
455 g_queue_clear (&parse->priv->queued_frames);
457 if (parse->priv->index) {
458 gst_object_unref (parse->priv->index);
459 parse->priv->index = NULL;
462 g_static_mutex_free (&parse->priv->index_lock);
464 gst_base_parse_clear_queues (parse);
466 G_OBJECT_CLASS (parent_class)->finalize (object);
470 gst_base_parse_class_init (GstBaseParseClass * klass)
472 GObjectClass *gobject_class;
473 GstElementClass *gstelement_class;
475 gobject_class = G_OBJECT_CLASS (klass);
476 g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
477 parent_class = g_type_class_peek_parent (klass);
478 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
480 gstelement_class = (GstElementClass *) klass;
481 gstelement_class->change_state =
482 GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
483 gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
484 gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
486 /* Default handlers */
487 klass->check_valid_frame = gst_base_parse_check_frame;
488 klass->parse_frame = gst_base_parse_parse_frame;
489 klass->src_event = gst_base_parse_src_eventfunc;
490 klass->convert = gst_base_parse_convert_default;
492 GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
493 "baseparse element");
497 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
499 GstPadTemplate *pad_template;
501 GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
503 parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
506 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
507 g_return_if_fail (pad_template != NULL);
508 parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
509 gst_pad_set_event_function (parse->sinkpad,
510 GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
511 gst_pad_set_chain_function (parse->sinkpad,
512 GST_DEBUG_FUNCPTR (gst_base_parse_chain));
513 gst_pad_set_activate_function (parse->sinkpad,
514 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
515 gst_pad_set_activatepush_function (parse->sinkpad,
516 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_push));
517 gst_pad_set_activatepull_function (parse->sinkpad,
518 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_pull));
519 gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
521 GST_DEBUG_OBJECT (parse, "sinkpad created");
524 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
525 g_return_if_fail (pad_template != NULL);
526 parse->srcpad = gst_pad_new_from_template (pad_template, "src");
527 gst_pad_set_event_function (parse->srcpad,
528 GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
529 gst_pad_set_query_type_function (parse->srcpad,
530 GST_DEBUG_FUNCPTR (gst_base_parse_get_querytypes));
531 gst_pad_set_query_function (parse->srcpad,
532 GST_DEBUG_FUNCPTR (gst_base_parse_query));
533 gst_pad_use_fixed_caps (parse->srcpad);
534 gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
535 GST_DEBUG_OBJECT (parse, "src created");
537 g_queue_init (&parse->priv->queued_frames);
539 parse->priv->adapter = gst_adapter_new ();
541 parse->priv->pad_mode = GST_ACTIVATE_NONE;
543 g_static_mutex_init (&parse->priv->index_lock);
546 gst_base_parse_reset (parse);
547 GST_DEBUG_OBJECT (parse, "init ok");
550 static GstBaseParseFrame *
551 gst_base_parse_frame_copy (GstBaseParseFrame * frame)
553 GstBaseParseFrame *copy;
555 copy = g_slice_dup (GstBaseParseFrame, frame);
556 copy->buffer = gst_buffer_ref (frame->buffer);
557 copy->_private_flags &= ~GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
559 GST_TRACE ("copied frame %p -> %p", frame, copy);
565 gst_base_parse_frame_free (GstBaseParseFrame * frame)
567 GST_TRACE ("freeing frame %p", frame);
570 gst_buffer_unref (frame->buffer);
571 frame->buffer = NULL;
574 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
575 g_slice_free (GstBaseParseFrame, frame);
577 memset (frame, 0, sizeof (*frame));
582 gst_base_parse_frame_get_type (void)
584 static volatile gsize frame_type = 0;
586 if (g_once_init_enter (&frame_type)) {
589 _type = g_boxed_type_register_static ("GstBaseParseFrame",
590 (GBoxedCopyFunc) gst_base_parse_frame_copy,
591 (GBoxedFreeFunc) gst_base_parse_frame_free);
592 g_once_init_leave (&frame_type, _type);
594 return (GType) frame_type;
598 * gst_base_parse_frame_init:
599 * @frame: #GstBaseParseFrame.
601 * Sets a #GstBaseParseFrame to initial state. Currently this means
602 * all public fields are zero-ed and a private flag is set to make
603 * sure gst_base_parse_frame_free() only frees the contents but not
604 * the actual frame. Use this function to initialise a #GstBaseParseFrame
605 * allocated on the stack.
610 gst_base_parse_frame_init (GstBaseParseFrame * frame)
612 memset (frame, 0, sizeof (GstBaseParseFrame));
613 frame->_private_flags = GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
614 GST_TRACE ("inited frame %p", frame);
618 * gst_base_parse_frame_new:
619 * @buffer: (transfer none): a #GstBuffer
621 * @overhead: number of bytes in this frame which should be counted as
622 * metadata overhead, ie. not used to calculate the average bitrate.
623 * Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
625 * Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
626 * elements written in C should usually allocate the frame on the stack and
627 * then use gst_base_parse_frame_init() to initialise it.
629 * Returns: a newly-allocated #GstBaseParseFrame. Free with
630 * gst_base_parse_frame_free() when no longer needed, unless you gave
631 * away ownership to gst_base_parse_push_frame().
636 gst_base_parse_frame_new (GstBuffer * buffer, GstBaseParseFrameFlags flags,
639 GstBaseParseFrame *frame;
641 frame = g_slice_new0 (GstBaseParseFrame);
642 frame->buffer = gst_buffer_ref (buffer);
644 GST_TRACE ("created frame %p", frame);
649 gst_base_parse_frame_update (GstBaseParse * parse, GstBaseParseFrame * frame,
652 gst_buffer_replace (&frame->buffer, buf);
656 /* set flags one by one for clarity */
657 if (G_UNLIKELY (parse->priv->drain))
658 parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;
660 /* losing sync is pretty much a discont (and vice versa), no ? */
661 if (G_UNLIKELY (parse->priv->discont))
662 parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
666 gst_base_parse_reset (GstBaseParse * parse)
668 GST_OBJECT_LOCK (parse);
669 gst_segment_init (&parse->segment, GST_FORMAT_TIME);
670 parse->priv->duration = -1;
671 parse->priv->min_frame_size = 1;
672 parse->priv->discont = TRUE;
673 parse->priv->flushing = FALSE;
674 parse->priv->offset = 0;
675 parse->priv->sync_offset = 0;
676 parse->priv->update_interval = -1;
677 parse->priv->fps_num = parse->priv->fps_den = 0;
678 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
679 parse->priv->lead_in = parse->priv->lead_out = 0;
680 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
681 parse->priv->bitrate = 0;
682 parse->priv->framecount = 0;
683 parse->priv->bytecount = 0;
684 parse->priv->acc_duration = 0;
685 parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
686 parse->priv->first_frame_offset = -1;
687 parse->priv->estimated_duration = -1;
688 parse->priv->next_ts = 0;
689 parse->priv->syncable = TRUE;
690 parse->priv->passthrough = FALSE;
691 parse->priv->has_timing_info = FALSE;
692 parse->priv->post_min_bitrate = TRUE;
693 parse->priv->post_avg_bitrate = TRUE;
694 parse->priv->post_max_bitrate = TRUE;
695 parse->priv->min_bitrate = G_MAXUINT;
696 parse->priv->max_bitrate = 0;
697 parse->priv->avg_bitrate = 0;
698 parse->priv->posted_avg_bitrate = 0;
700 parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
701 parse->priv->index_last_offset = -1;
702 parse->priv->index_last_valid = TRUE;
703 parse->priv->upstream_seekable = FALSE;
704 parse->priv->upstream_size = 0;
705 parse->priv->upstream_has_duration = FALSE;
706 parse->priv->idx_interval = 0;
707 parse->priv->exact_position = TRUE;
708 parse->priv->seen_keyframe = FALSE;
710 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
711 parse->priv->last_offset = 0;
713 if (parse->priv->pending_segment) {
714 gst_event_unref (parse->priv->pending_segment);
715 parse->priv->pending_segment = NULL;
718 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
720 g_list_free (parse->priv->pending_events);
721 parse->priv->pending_events = NULL;
723 if (parse->priv->cache) {
724 gst_buffer_unref (parse->priv->cache);
725 parse->priv->cache = NULL;
728 g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
729 g_slist_free (parse->priv->pending_seeks);
730 parse->priv->pending_seeks = NULL;
732 /* we know it is not alloc'ed, but maybe other stuff to free, some day ... */
733 parse->priv->frame._private_flags |=
734 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
735 gst_base_parse_frame_free (&parse->priv->frame);
736 GST_OBJECT_UNLOCK (parse);
739 /* gst_base_parse_check_frame:
740 * @parse: #GstBaseParse.
741 * @buffer: GstBuffer.
742 * @framesize: This will be set to tell the found frame size in bytes.
743 * @skipsize: Output parameter that tells how much data needs to be skipped
744 * in order to find the following frame header.
746 * Default callback for check_valid_frame.
748 * Returns: Always TRUE.
751 gst_base_parse_check_frame (GstBaseParse * parse,
752 GstBaseParseFrame * frame, guint * framesize, gint * skipsize)
754 *framesize = gst_buffer_get_size (frame->buffer);
760 /* gst_base_parse_parse_frame:
761 * @parse: #GstBaseParse.
762 * @buffer: #GstBuffer.
764 * Default callback for parse_frame.
767 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
769 GstBuffer *buffer = frame->buffer;
771 if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
772 GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
773 GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
775 if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
776 GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
777 GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
782 /* gst_base_parse_convert:
783 * @parse: #GstBaseParse.
784 * @src_format: #GstFormat describing the source format.
785 * @src_value: Source value to be converted.
786 * @dest_format: #GstFormat defining the converted format.
787 * @dest_value: Pointer where the conversion result will be put.
789 * Converts using configured "convert" vmethod in #GstBaseParse class.
791 * Returns: TRUE if conversion was successful.
794 gst_base_parse_convert (GstBaseParse * parse,
795 GstFormat src_format,
796 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
798 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
801 g_return_val_if_fail (dest_value != NULL, FALSE);
806 ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
808 #ifndef GST_DISABLE_GST_DEBUG
811 if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
812 GST_LOG_OBJECT (parse,
813 "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
814 GST_TIME_ARGS (src_value), *dest_value);
815 } else if (dest_format == GST_FORMAT_TIME &&
816 src_format == GST_FORMAT_BYTES) {
817 GST_LOG_OBJECT (parse,
818 "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
819 src_value, GST_TIME_ARGS (*dest_value));
821 GST_LOG_OBJECT (parse,
822 "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
823 GST_STR_NULL (gst_format_get_name (src_format)),
824 GST_STR_NULL (gst_format_get_name (dest_format)),
825 src_value, *dest_value);
828 GST_DEBUG_OBJECT (parse, "conversion failed");
836 /* gst_base_parse_sink_event:
837 * @pad: #GstPad that received the event.
838 * @event: #GstEvent to be handled.
840 * Handler for sink pad events.
842 * Returns: TRUE if the event was handled.
845 gst_base_parse_sink_event (GstPad * pad, GstEvent * event)
848 GstBaseParseClass *bclass;
849 gboolean handled = FALSE;
852 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
853 bclass = GST_BASE_PARSE_GET_CLASS (parse);
855 GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
856 GST_EVENT_TYPE_NAME (event));
858 /* Cache all events except EOS, SEGMENT and FLUSH_STOP if we have a
860 if (parse->priv->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
861 && GST_EVENT_TYPE (event) != GST_EVENT_SEGMENT
862 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
863 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP) {
865 if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
866 /* See if any bitrate tags were posted */
867 gst_base_parse_handle_tag (parse, event);
869 parse->priv->pending_events =
870 g_list_append (parse->priv->pending_events, event);
874 if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
875 parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
876 /* We've not posted bitrate tags yet - do so now */
877 gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
880 handled = bclass->event (parse, event);
883 handled = gst_base_parse_sink_eventfunc (parse, event);
886 ret = gst_pad_event_default (pad, event);
889 gst_object_unref (parse);
890 GST_DEBUG_OBJECT (parse, "event handled");
895 /* gst_base_parse_sink_eventfunc:
896 * @parse: #GstBaseParse.
897 * @event: #GstEvent to be handled.
899 * Element-level event handler function.
901 * The event will be unreffed only if it has been handled and this
902 * function returns %TRUE
904 * Returns: %TRUE if the event was handled and not need forwarding.
907 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
909 gboolean handled = FALSE;
912 switch (GST_EVENT_TYPE (event)) {
916 GstBaseParseClass *klass;
918 klass = GST_BASE_PARSE_GET_CLASS (parse);
920 gst_event_parse_caps (event, &caps);
921 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
923 if (klass->set_sink_caps)
924 klass->set_sink_caps (parse, caps);
929 case GST_EVENT_SEGMENT:
931 const GstSegment *in_segment;
932 GstSegment out_segment;
933 gint64 offset = 0, next_ts;
936 gdouble rate, applied_rate;
938 gint64 start, stop, pos, next_ts;
942 gst_event_parse_segment (event, &in_segment);
943 gst_segment_init (&out_segment, GST_FORMAT_TIME);
945 GST_DEBUG_OBJECT (parse, "segment %" GST_SEGMENT_FORMAT, in_segment);
947 if (in_segment->format == GST_FORMAT_BYTES) {
948 GstBaseParseSeek *seek = NULL;
951 /* stop time is allowed to be open-ended, but not start & pos */
952 offset = in_segment->time;
954 GST_OBJECT_LOCK (parse);
955 for (node = parse->priv->pending_seeks; node; node = node->next) {
956 GstBaseParseSeek *tmp = node->data;
958 if (tmp->offset == offset) {
963 parse->priv->pending_seeks =
964 g_slist_remove (parse->priv->pending_seeks, seek);
965 GST_OBJECT_UNLOCK (parse);
968 GST_DEBUG_OBJECT (parse,
969 "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
970 seek->accurate ? " accurate" : "", &seek->segment);
972 out_segment.start = seek->segment.start;
973 out_segment.stop = seek->segment.stop;
974 out_segment.time = seek->segment.start;
976 next_ts = seek->start_ts;
977 parse->priv->exact_position = seek->accurate;
980 /* best attempt convert */
981 /* as these are only estimates, stop is kept open-ended to avoid
982 * premature cutting */
983 gst_base_parse_convert (parse, GST_FORMAT_BYTES, in_segment->start,
984 GST_FORMAT_TIME, (gint64 *) & next_ts);
986 out_segment.start = next_ts;
987 out_segment.stop = GST_CLOCK_TIME_NONE;
988 out_segment.time = next_ts;
990 parse->priv->exact_position = (in_segment->start == 0);
993 gst_event_unref (event);
995 event = gst_event_new_segment (&out_segment);
997 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. "
998 GST_SEGMENT_FORMAT, in_segment);
1000 } else if (in_segment->format != GST_FORMAT_TIME) {
1001 /* Unknown incoming segment format. Output a default open-ended
1003 gst_event_unref (event);
1005 out_segment.start = 0;
1006 out_segment.stop = GST_CLOCK_TIME_NONE;;
1007 out_segment.time = 0;;
1009 event = gst_event_new_segment (&out_segment);
1013 /* not considered BYTE seekable if it is talking to us in TIME,
1014 * whatever else it might claim */
1015 parse->priv->upstream_seekable = FALSE;
1016 next_ts = in_segment->start;
1019 memcpy (&parse->segment, &out_segment, sizeof (GstSegment));
1022 gst_segment_set_newsegment (&parse->segment, update, rate,
1023 applied_rate, format, start, stop, start);
1026 /* save the segment for later, right before we push a new buffer so that
1027 * the caps are fixed and the next linked element can receive
1029 eventp = &parse->priv->pending_segment;
1030 gst_event_replace (eventp, event);
1031 gst_event_unref (event);
1034 /* but finish the current segment */
1035 GST_DEBUG_OBJECT (parse, "draining current segment");
1036 if (in_segment->rate > 0.0)
1037 gst_base_parse_drain (parse);
1039 gst_base_parse_process_fragment (parse, FALSE);
1040 gst_adapter_clear (parse->priv->adapter);
1042 parse->priv->offset = offset;
1043 parse->priv->sync_offset = offset;
1044 parse->priv->next_ts = next_ts;
1045 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1046 parse->priv->discont = TRUE;
1047 parse->priv->seen_keyframe = FALSE;
1051 case GST_EVENT_FLUSH_START:
1052 parse->priv->flushing = TRUE;
1053 handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
1055 gst_event_unref (event);
1056 /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
1057 GST_PAD_STREAM_LOCK (parse->srcpad);
1058 GST_PAD_STREAM_UNLOCK (parse->srcpad);
1062 case GST_EVENT_FLUSH_STOP:
1063 gst_adapter_clear (parse->priv->adapter);
1064 gst_base_parse_clear_queues (parse);
1065 parse->priv->flushing = FALSE;
1066 parse->priv->discont = TRUE;
1067 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1068 parse->priv->frame._private_flags |=
1069 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
1070 gst_base_parse_frame_free (&parse->priv->frame);
1074 if (parse->segment.rate > 0.0)
1075 gst_base_parse_drain (parse);
1077 gst_base_parse_process_fragment (parse, FALSE);
1079 /* If we STILL have zero frames processed, fire an error */
1080 if (parse->priv->framecount == 0) {
1081 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1082 ("No valid frames found before end of stream"), (NULL));
1084 /* newsegment before eos */
1085 if (parse->priv->pending_segment) {
1086 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1087 parse->priv->pending_segment = NULL;
1099 /* gst_base_parse_src_event:
1100 * @pad: #GstPad that received the event.
1101 * @event: #GstEvent that was received.
1103 * Handler for source pad events.
1105 * Returns: TRUE if the event was handled.
1108 gst_base_parse_src_event (GstPad * pad, GstEvent * event)
1110 GstBaseParse *parse;
1111 GstBaseParseClass *bclass;
1112 gboolean handled = FALSE;
1113 gboolean ret = TRUE;
1115 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
1116 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1118 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1119 GST_EVENT_TYPE_NAME (event));
1121 if (bclass->src_event)
1122 handled = bclass->src_event (parse, event);
1125 ret = gst_pad_event_default (pad, event);
1127 gst_object_unref (parse);
1132 gst_base_parse_is_seekable (GstBaseParse * parse)
1134 /* FIXME: could do more here, e.g. check index or just send data from 0
1135 * in pull mode and let decoder/sink clip */
1136 return parse->priv->syncable;
1139 /* gst_base_parse_src_eventfunc:
1140 * @parse: #GstBaseParse.
1141 * @event: #GstEvent that was received.
1143 * Default srcpad event handler.
1145 * Returns: TRUE if the event was handled and can be dropped.
1148 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1150 gboolean handled = FALSE;
1152 switch (GST_EVENT_TYPE (event)) {
1153 case GST_EVENT_SEEK:
1155 if (gst_base_parse_is_seekable (parse)) {
1156 handled = gst_base_parse_handle_seek (parse, event);
1168 * gst_base_parse_convert_default:
1169 * @parse: #GstBaseParse.
1170 * @src_format: #GstFormat describing the source format.
1171 * @src_value: Source value to be converted.
1172 * @dest_format: #GstFormat defining the converted format.
1173 * @dest_value: Pointer where the conversion result will be put.
1175 * Default implementation of "convert" vmethod in #GstBaseParse class.
1177 * Returns: TRUE if conversion was successful.
1182 gst_base_parse_convert_default (GstBaseParse * parse,
1183 GstFormat src_format,
1184 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1186 gboolean ret = FALSE;
1187 guint64 bytes, duration;
1189 if (G_UNLIKELY (src_format == dest_format)) {
1190 *dest_value = src_value;
1194 if (G_UNLIKELY (src_value == -1)) {
1199 if (G_UNLIKELY (src_value == 0)) {
1204 /* need at least some frames */
1205 if (!parse->priv->framecount)
1208 duration = parse->priv->acc_duration / GST_MSECOND;
1209 bytes = parse->priv->bytecount;
1211 if (G_UNLIKELY (!duration || !bytes))
1214 if (src_format == GST_FORMAT_BYTES) {
1215 if (dest_format == GST_FORMAT_TIME) {
1216 /* BYTES -> TIME conversion */
1217 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1218 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1219 *dest_value *= GST_MSECOND;
1220 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1221 *dest_value / GST_MSECOND);
1224 } else if (src_format == GST_FORMAT_TIME) {
1225 if (dest_format == GST_FORMAT_BYTES) {
1226 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1227 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1229 GST_DEBUG_OBJECT (parse,
1230 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1231 src_value / GST_MSECOND, *dest_value);
1234 } else if (src_format == GST_FORMAT_DEFAULT) {
1235 /* DEFAULT == frame-based */
1236 if (dest_format == GST_FORMAT_TIME) {
1237 if (parse->priv->fps_den) {
1238 *dest_value = gst_util_uint64_scale (src_value,
1239 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1242 } else if (dest_format == GST_FORMAT_BYTES) {
1250 gst_base_parse_update_duration (GstBaseParse * baseparse)
1253 GstBaseParse *parse;
1255 parse = GST_BASE_PARSE (baseparse);
1257 peer = gst_pad_get_peer (parse->sinkpad);
1259 GstFormat pformat = GST_FORMAT_BYTES;
1260 gboolean qres = FALSE;
1261 gint64 ptot, dest_value;
1263 qres = gst_pad_query_duration (peer, &pformat, &ptot);
1264 gst_object_unref (GST_OBJECT (peer));
1266 if (gst_base_parse_convert (parse, pformat, ptot,
1267 GST_FORMAT_TIME, &dest_value)) {
1268 parse->priv->estimated_duration = dest_value;
1269 GST_LOG_OBJECT (parse,
1270 "updated estimated duration to %" GST_TIME_FORMAT,
1271 GST_TIME_ARGS (dest_value));
1278 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1279 gboolean post_avg, gboolean post_max)
1281 GstTagList *taglist = NULL;
1283 if (post_min && parse->priv->post_min_bitrate) {
1284 taglist = gst_tag_list_new ();
1286 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1287 GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1290 if (post_avg && parse->priv->post_avg_bitrate) {
1291 if (taglist == NULL)
1292 taglist = gst_tag_list_new ();
1294 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1295 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1296 parse->priv->avg_bitrate, NULL);
1299 if (post_max && parse->priv->post_max_bitrate) {
1300 if (taglist == NULL)
1301 taglist = gst_tag_list_new ();
1303 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1304 GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1307 GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1308 parse->priv->min_bitrate, parse->priv->avg_bitrate,
1309 parse->priv->max_bitrate);
1311 if (taglist != NULL) {
1312 gst_element_found_tags_for_pad (GST_ELEMENT_CAST (parse), parse->srcpad,
1317 /* gst_base_parse_update_bitrates:
1318 * @parse: #GstBaseParse.
1319 * @buffer: Current frame as a #GstBuffer
1321 * Keeps track of the minimum and maximum bitrates, and also maintains a
1322 * running average bitrate of the stream so far.
1325 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1327 /* Only update the tag on a 10 kbps delta */
1328 static const gint update_threshold = 10000;
1330 guint64 data_len, frame_dur;
1331 gint overhead, frame_bitrate, old_avg_bitrate;
1332 gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1333 GstBuffer *buffer = frame->buffer;
1335 overhead = frame->overhead;
1339 data_len = gst_buffer_get_size (buffer) - overhead;
1340 parse->priv->data_bytecount += data_len;
1342 /* duration should be valid by now,
1343 * either set by subclass or maybe based on fps settings */
1344 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1345 /* Calculate duration of a frame from buffer properties */
1346 frame_dur = GST_BUFFER_DURATION (buffer);
1347 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1348 parse->priv->acc_duration;
1351 /* No way to figure out frame duration (is this even possible?) */
1355 /* override if subclass provided bitrate, e.g. metadata based */
1356 if (parse->priv->bitrate) {
1357 parse->priv->avg_bitrate = parse->priv->bitrate;
1358 /* spread this (confirmed) info ASAP */
1359 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1360 gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1364 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1368 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1369 parse->priv->avg_bitrate);
1371 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1373 } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1374 /* always post all at threshold time */
1375 update_min = update_max = update_avg = TRUE;
1378 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1379 if (frame_bitrate < parse->priv->min_bitrate) {
1380 parse->priv->min_bitrate = frame_bitrate;
1384 if (frame_bitrate > parse->priv->max_bitrate) {
1385 parse->priv->max_bitrate = frame_bitrate;
1389 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1390 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1391 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1396 if ((update_min || update_avg || update_max))
1397 gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1399 /* If average bitrate changes that much and no valid (time) duration provided,
1400 * then post a new duration message so applications can update their cached
1402 if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1403 GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1404 gst_element_post_message (GST_ELEMENT (parse),
1405 gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1412 * gst_base_parse_add_index_entry:
1413 * @parse: #GstBaseParse.
1414 * @offset: offset of entry
1415 * @ts: timestamp associated with offset
1416 * @key: whether entry refers to keyframe
1417 * @force: add entry disregarding sanity checks
1419 * Adds an entry to the index associating @offset to @ts. It is recommended
1420 * to only add keyframe entries. @force allows to bypass checks, such as
1421 * whether the stream is (upstream) seekable, another entry is already "close"
1422 * to the new entry, etc.
1424 * Returns: #gboolean indicating whether entry was added
1429 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1430 GstClockTime ts, gboolean key, gboolean force)
1432 gboolean ret = FALSE;
1433 GstIndexAssociation associations[2];
1435 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1436 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1438 if (G_LIKELY (!force)) {
1440 if (!parse->priv->upstream_seekable) {
1441 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1445 /* FIXME need better helper data structure that handles these issues
1446 * related to ongoing collecting of index entries */
1447 if (parse->priv->index_last_offset >= (gint64) offset) {
1448 GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1449 "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1453 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1454 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1455 parse->priv->idx_interval) {
1456 GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1457 GST_TIME_ARGS (parse->priv->index_last_ts));
1461 /* if last is not really the last one */
1462 if (!parse->priv->index_last_valid) {
1463 GstClockTime prev_ts;
1465 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1466 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1467 GST_DEBUG_OBJECT (parse,
1468 "entry too close to existing entry %" GST_TIME_FORMAT,
1469 GST_TIME_ARGS (prev_ts));
1470 parse->priv->index_last_offset = offset;
1471 parse->priv->index_last_ts = ts;
1477 associations[0].format = GST_FORMAT_TIME;
1478 associations[0].value = ts;
1479 associations[1].format = GST_FORMAT_BYTES;
1480 associations[1].value = offset;
1482 /* index might change on-the-fly, although that would be nutty app ... */
1483 g_static_mutex_lock (&parse->priv->index_lock);
1484 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1485 (key) ? GST_ASSOCIATION_FLAG_KEY_UNIT : GST_ASSOCIATION_FLAG_DELTA_UNIT,
1486 2, (const GstIndexAssociation *) &associations);
1487 g_static_mutex_unlock (&parse->priv->index_lock);
1490 parse->priv->index_last_offset = offset;
1491 parse->priv->index_last_ts = ts;
1500 /* check for seekable upstream, above and beyond a mere query */
1502 gst_base_parse_check_seekability (GstBaseParse * parse)
1505 gboolean seekable = FALSE;
1506 gint64 start = -1, stop = -1;
1507 guint idx_interval = 0;
1509 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1510 if (!gst_pad_peer_query (parse->sinkpad, query)) {
1511 GST_DEBUG_OBJECT (parse, "seeking query failed");
1515 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1517 /* try harder to query upstream size if we didn't get it the first time */
1518 if (seekable && stop == -1) {
1519 GstFormat fmt = GST_FORMAT_BYTES;
1521 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1522 gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop);
1525 /* if upstream doesn't know the size, it's likely that it's not seekable in
1526 * practice even if it technically may be seekable */
1527 if (seekable && (start != 0 || stop <= start)) {
1528 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1532 /* let's not put every single frame into our index */
1534 if (stop < 10 * 1024 * 1024)
1536 else if (stop < 100 * 1024 * 1024)
1539 idx_interval = 1000;
1543 gst_query_unref (query);
1545 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1546 G_GUINT64_FORMAT ")", seekable, start, stop);
1547 parse->priv->upstream_seekable = seekable;
1548 parse->priv->upstream_size = seekable ? stop : 0;
1550 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1551 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1554 /* some misc checks on upstream */
1556 gst_base_parse_check_upstream (GstBaseParse * parse)
1558 GstFormat fmt = GST_FORMAT_TIME;
1561 if (gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop))
1562 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1563 /* upstream has one, accept it also, and no further updates */
1564 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1565 parse->priv->upstream_has_duration = TRUE;
1568 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1569 parse->priv->upstream_has_duration);
1572 /* checks src caps to determine if dealing with audio or video */
1573 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1575 gst_base_parse_check_media (GstBaseParse * parse)
1580 caps = gst_pad_get_current_caps (parse->srcpad);
1581 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1582 parse->priv->is_video =
1583 g_str_has_prefix (gst_structure_get_name (s), "video");
1585 /* historical default */
1586 parse->priv->is_video = FALSE;
1589 gst_caps_unref (caps);
1591 GST_DEBUG_OBJECT (parse, "media is video == %d", parse->priv->is_video);
1594 /* takes ownership of frame */
1596 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1598 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1599 /* frame allocated on the heap, we can just take ownership */
1600 g_queue_push_tail (&parse->priv->queued_frames, frame);
1601 GST_TRACE ("queued frame %p", frame);
1603 GstBaseParseFrame *copy;
1605 /* probably allocated on the stack, must make a proper copy */
1606 copy = gst_base_parse_frame_copy (frame);
1607 g_queue_push_tail (&parse->priv->queued_frames, copy);
1608 GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1609 gst_base_parse_frame_free (frame);
1613 /* gst_base_parse_handle_and_push_buffer:
1614 * @parse: #GstBaseParse.
1615 * @klass: #GstBaseParseClass.
1616 * @frame: (transfer full): a #GstBaseParseFrame
1618 * Parses the frame from given buffer and pushes it forward. Also performs
1619 * timestamp handling and checks the segment limits.
1621 * This is called with srcpad STREAM_LOCK held.
1623 * Returns: #GstFlowReturn
1625 static GstFlowReturn
1626 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1627 GstBaseParseClass * klass, GstBaseParseFrame * frame)
1633 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1635 buffer = frame->buffer;
1637 if (parse->priv->discont) {
1638 GST_DEBUG_OBJECT (parse, "marking DISCONT");
1639 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1640 parse->priv->discont = FALSE;
1643 /* some one-time start-up */
1644 if (G_UNLIKELY (!parse->priv->framecount)) {
1645 gst_base_parse_check_seekability (parse);
1646 gst_base_parse_check_upstream (parse);
1649 GST_LOG_OBJECT (parse,
1650 "parsing frame at offset %" G_GUINT64_FORMAT
1651 " (%#" G_GINT64_MODIFIER "x) of size %d",
1652 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1653 gst_buffer_get_size (buffer));
1655 /* use default handler to provide initial (upstream) metadata */
1656 gst_base_parse_parse_frame (parse, frame);
1658 /* store offset as it might get overwritten */
1659 offset = GST_BUFFER_OFFSET (buffer);
1660 ret = klass->parse_frame (parse, frame);
1662 buffer = frame->buffer;
1663 /* subclass must play nice */
1664 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1666 /* check if subclass/format can provide ts.
1667 * If so, that allows and enables extra seek and duration determining options */
1668 if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
1669 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && parse->priv->has_timing_info
1670 && parse->priv->pad_mode == GST_ACTIVATE_PULL) {
1671 parse->priv->first_frame_offset = offset;
1672 parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1673 GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1674 " for first frame at offset %" G_GINT64_FORMAT,
1675 GST_TIME_ARGS (parse->priv->first_frame_ts),
1676 parse->priv->first_frame_offset);
1677 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1679 GstClockTime last_ts = G_MAXINT64;
1681 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1682 gst_base_parse_locate_time (parse, &last_ts, &off);
1683 if (GST_CLOCK_TIME_IS_VALID (last_ts))
1684 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1687 /* disable further checks */
1688 parse->priv->first_frame_offset = 0;
1692 /* again use default handler to add missing metadata;
1693 * we may have new information on frame properties */
1694 gst_base_parse_parse_frame (parse, frame);
1695 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1696 GST_BUFFER_DURATION_IS_VALID (buffer)) {
1697 parse->priv->next_ts =
1698 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1700 /* we lost track, do not produce bogus time next time around
1701 * (probably means parser subclass has given up on parsing as well) */
1702 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1703 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1706 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1707 GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1708 gst_base_parse_add_index_entry (parse, offset,
1709 GST_BUFFER_TIMESTAMP (buffer),
1710 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1712 /* First buffers are dropped, this means that the subclass needs more
1713 * frames to decide on the format and queues them internally */
1714 /* convert internal flow to OK and mark discont for the next buffer. */
1715 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1716 gst_base_parse_frame_free (frame);
1718 } else if (ret == GST_BASE_PARSE_FLOW_QUEUED) {
1719 gst_base_parse_queue_frame (parse, frame);
1721 } else if (ret != GST_FLOW_OK) {
1725 /* All OK, push queued frames if there are any */
1726 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
1727 GstBaseParseFrame *queued_frame;
1729 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
1730 gst_base_parse_push_frame (parse, queued_frame);
1731 gst_base_parse_frame_free (queued_frame);
1735 return gst_base_parse_push_frame (parse, frame);
1739 * gst_base_parse_push_frame:
1740 * @parse: #GstBaseParse.
1741 * @frame: (transfer full): a #GstBaseParseFrame
1743 * Pushes the frame downstream, sends any pending events and
1744 * does some timestamp and segment handling. Takes ownership
1745 * of @frame and will clear it (if it was initialised with
1746 * gst_base_parse_frame_init()) or free it.
1748 * This must be called with sinkpad STREAM_LOCK held.
1750 * Returns: #GstFlowReturn
1755 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1757 GstFlowReturn ret = GST_FLOW_OK;
1758 GstClockTime last_start = GST_CLOCK_TIME_NONE;
1759 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1760 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1764 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1765 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
1767 GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
1769 buffer = frame->buffer;
1771 GST_LOG_OBJECT (parse,
1772 "processing buffer of size %d with ts %" GST_TIME_FORMAT
1773 ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buffer),
1774 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1775 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1778 size = gst_buffer_get_size (buffer);
1779 parse->priv->bytecount += size;
1780 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1781 parse->priv->framecount++;
1782 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1783 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1786 /* 0 means disabled */
1787 if (parse->priv->update_interval < 0)
1788 parse->priv->update_interval = 50;
1789 else if (parse->priv->update_interval > 0 &&
1790 (parse->priv->framecount % parse->priv->update_interval) == 0)
1791 gst_base_parse_update_duration (parse);
1793 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1794 last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1795 if (last_start != GST_CLOCK_TIME_NONE
1796 && GST_BUFFER_DURATION_IS_VALID (buffer))
1797 last_stop = last_start + GST_BUFFER_DURATION (buffer);
1799 /* should have caps by now */
1800 g_return_val_if_fail (gst_pad_has_current_caps (parse->srcpad),
1803 /* segment adjustment magic; only if we are running the whole show */
1804 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1805 (parse->priv->pad_mode == GST_ACTIVATE_PULL ||
1806 parse->priv->upstream_seekable)) {
1807 /* segment times are typically estimates,
1808 * actual frame data might lead subclass to different timestamps,
1809 * so override segment start from what is supplied there */
1810 if (G_UNLIKELY (parse->priv->pending_segment && !parse->priv->exact_position
1811 && GST_CLOCK_TIME_IS_VALID (last_start))) {
1812 gst_event_unref (parse->priv->pending_segment);
1813 parse->segment.start =
1814 MIN ((guint64) last_start, (guint64) parse->segment.stop);
1816 GST_DEBUG_OBJECT (parse,
1817 "adjusting pending segment start to %" GST_TIME_FORMAT,
1818 GST_TIME_ARGS (parse->segment.start));
1820 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
1822 /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1823 if (GST_CLOCK_TIME_IS_VALID (parse->segment.position) &&
1824 GST_CLOCK_TIME_IS_VALID (last_start)) {
1825 GstClockTimeDiff diff;
1827 /* only send newsegments with increasing start times,
1828 * otherwise if these go back and forth downstream (sinks) increase
1829 * accumulated time and running_time */
1830 diff = GST_CLOCK_DIFF (parse->segment.position, last_start);
1831 if (G_UNLIKELY (diff > 2 * GST_SECOND
1832 && last_start > parse->segment.start
1833 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
1834 || last_start < parse->segment.stop))) {
1836 GST_DEBUG_OBJECT (parse,
1837 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
1838 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1839 "Sending updated NEWSEGMENT events", diff,
1840 GST_TIME_ARGS (parse->segment.position),
1841 GST_TIME_ARGS (last_start));
1843 if (G_UNLIKELY (parse->priv->pending_segment)) {
1844 gst_event_unref (parse->priv->pending_segment);
1845 parse->segment.start = last_start;
1846 parse->segment.time = last_start;
1847 parse->priv->pending_segment =
1848 gst_event_new_segment (&parse->segment);
1850 /* skip gap FIXME */
1851 gst_pad_push_event (parse->srcpad,
1852 gst_event_new_segment (&parse->segment));
1854 parse->segment.position = last_start;
1859 /* and should then also be linked downstream, so safe to send some events */
1860 if (G_UNLIKELY (parse->priv->close_segment)) {
1861 /* only set up by loop */
1862 GST_DEBUG_OBJECT (parse, "loop sending close segment");
1863 gst_pad_push_event (parse->srcpad, parse->priv->close_segment);
1864 parse->priv->close_segment = NULL;
1866 if (G_UNLIKELY (parse->priv->pending_segment)) {
1867 GST_DEBUG_OBJECT (parse, "%s push pending segment",
1868 parse->priv->pad_mode == GST_ACTIVATE_PULL ? "loop" : "chain");
1869 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1870 parse->priv->pending_segment = NULL;
1872 /* have caps; check identity */
1873 gst_base_parse_check_media (parse);
1876 /* update bitrates and optionally post corresponding tags
1877 * (following newsegment) */
1878 gst_base_parse_update_bitrates (parse, frame);
1880 if (G_UNLIKELY (parse->priv->pending_events)) {
1883 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1884 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1886 g_list_free (parse->priv->pending_events);
1887 parse->priv->pending_events = NULL;
1890 if (klass->pre_push_frame) {
1891 ret = klass->pre_push_frame (parse, frame);
1893 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
1896 /* take final ownership of frame buffer */
1897 buffer = frame->buffer;
1898 frame->buffer = NULL;
1900 /* subclass must play nice */
1901 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1903 parse->priv->seen_keyframe |= parse->priv->is_video &&
1904 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1906 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
1907 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1908 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
1909 GST_BUFFER_TIMESTAMP (buffer) >
1910 parse->segment.stop + parse->priv->lead_out_ts) {
1911 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
1912 ret = GST_FLOW_UNEXPECTED;
1913 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1914 GST_BUFFER_DURATION_IS_VALID (buffer) &&
1915 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
1916 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
1917 parse->priv->lead_in_ts < parse->segment.start) {
1918 if (parse->priv->seen_keyframe) {
1919 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
1922 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
1923 ret = GST_BASE_PARSE_FLOW_DROPPED;
1930 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1931 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) dropped", size);
1932 gst_buffer_unref (buffer);
1934 } else if (ret == GST_FLOW_OK) {
1935 if (parse->segment.rate > 0.0) {
1936 ret = gst_pad_push (parse->srcpad, buffer);
1937 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) pushed: %s",
1938 size, gst_flow_get_name (ret));
1940 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) queued for now",
1942 parse->priv->buffers_queued =
1943 g_slist_prepend (parse->priv->buffers_queued, buffer);
1947 gst_buffer_unref (buffer);
1948 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s",
1949 size, gst_flow_get_name (ret));
1950 /* if we are not sufficiently in control, let upstream decide on EOS */
1951 if (ret == GST_FLOW_UNEXPECTED &&
1952 (parse->priv->passthrough ||
1953 (parse->priv->pad_mode == GST_ACTIVATE_PUSH &&
1954 !parse->priv->upstream_seekable)))
1958 /* Update current running segment position */
1959 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
1960 parse->segment.position < last_stop)
1961 parse->segment.position = last_stop;
1963 gst_base_parse_frame_free (frame);
1969 /* gst_base_parse_drain:
1971 * Drains the adapter until it is empty. It decreases the min_frame_size to
1972 * match the current adapter size and calls chain method until the adapter
1973 * is emptied or chain returns with error.
1976 gst_base_parse_drain (GstBaseParse * parse)
1980 GST_DEBUG_OBJECT (parse, "draining");
1981 parse->priv->drain = TRUE;
1984 avail = gst_adapter_available (parse->priv->adapter);
1988 if (gst_base_parse_chain (parse->sinkpad, NULL) != GST_FLOW_OK) {
1992 /* nothing changed, maybe due to truncated frame; break infinite loop */
1993 if (avail == gst_adapter_available (parse->priv->adapter)) {
1994 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
1995 gst_adapter_clear (parse->priv->adapter);
1999 parse->priv->drain = FALSE;
2002 /* gst_base_parse_send_buffers
2004 * Sends buffers collected in send_buffers downstream, and ensures that list
2005 * is empty at the end (errors or not).
2007 static GstFlowReturn
2008 gst_base_parse_send_buffers (GstBaseParse * parse)
2010 GSList *send = NULL;
2012 GstFlowReturn ret = GST_FLOW_OK;
2014 send = parse->priv->buffers_send;
2018 buf = GST_BUFFER_CAST (send->data);
2019 GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
2020 GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2021 ", offset %" G_GINT64_FORMAT, buf,
2022 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2023 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2025 /* iterate output queue an push downstream */
2026 ret = gst_pad_push (parse->srcpad, buf);
2027 send = g_slist_delete_link (send, send);
2029 /* clear any leftover if error */
2030 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2032 buf = GST_BUFFER_CAST (send->data);
2033 gst_buffer_unref (buf);
2034 send = g_slist_delete_link (send, send);
2039 parse->priv->buffers_send = send;
2044 /* gst_base_parse_process_fragment:
2046 * Processes a reverse playback (forward) fragment:
2047 * - append head of last fragment that was skipped to current fragment data
2048 * - drain the resulting current fragment data (i.e. repeated chain)
2049 * - add time/duration (if needed) to frames queued by chain
2050 * - push queued data
2052 static GstFlowReturn
2053 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
2056 GstFlowReturn ret = GST_FLOW_OK;
2057 gboolean seen_key = FALSE, seen_delta = FALSE;
2063 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2064 while (parse->priv->buffers_pending) {
2065 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2066 GST_LOG_OBJECT (parse, "adding pending buffer (size %d)",
2067 gst_buffer_get_size (buf));
2068 gst_adapter_push (parse->priv->adapter, buf);
2069 parse->priv->buffers_pending =
2070 g_slist_delete_link (parse->priv->buffers_pending,
2071 parse->priv->buffers_pending);
2074 /* invalidate so no fall-back timestamping is performed;
2075 * ok if taken from subclass or upstream */
2076 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
2077 /* prevent it hanging around stop all the time */
2078 parse->segment.position = GST_CLOCK_TIME_NONE;
2080 parse->priv->discont = TRUE;
2082 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2083 /* initial skipped data is added to buffers_pending */
2084 gst_base_parse_drain (parse);
2087 if (parse->priv->buffers_send) {
2088 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2089 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2092 /* add metadata (if needed to queued buffers */
2093 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2094 GST_TIME_ARGS (parse->priv->last_ts));
2095 while (parse->priv->buffers_queued) {
2096 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2098 /* no touching if upstream or parsing provided time */
2099 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2100 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2101 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2102 } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
2103 GST_BUFFER_DURATION_IS_VALID (buf)) {
2104 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
2105 parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
2107 parse->priv->last_ts = 0;
2108 GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
2109 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2110 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2112 /* no idea, very bad */
2113 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2116 parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
2118 /* reverse order for ascending sending */
2119 /* send downstream at keyframe not preceded by a keyframe
2120 * (e.g. that should identify start of collection of IDR nals) */
2121 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2123 ret = gst_base_parse_send_buffers (parse);
2124 /* if a problem, throw all to sending */
2125 if (ret != GST_FLOW_OK) {
2126 parse->priv->buffers_send =
2127 g_slist_reverse (parse->priv->buffers_queued);
2128 parse->priv->buffers_queued = NULL;
2137 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2139 parse->priv->buffers_send =
2140 g_slist_prepend (parse->priv->buffers_send, buf);
2141 parse->priv->buffers_queued =
2142 g_slist_delete_link (parse->priv->buffers_queued,
2143 parse->priv->buffers_queued);
2146 /* audio may have all marked as keyframe, so arrange to send here */
2148 ret = gst_base_parse_send_buffers (parse);
2150 /* any trailing unused no longer usable (ideally none) */
2151 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2152 GST_DEBUG_OBJECT (parse, "discarding %d trailing bytes",
2153 gst_adapter_available (parse->priv->adapter));
2154 gst_adapter_clear (parse->priv->adapter);
2160 /* small helper that checks whether we have been trying to resync too long */
2161 static inline GstFlowReturn
2162 gst_base_parse_check_sync (GstBaseParse * parse)
2164 if (G_UNLIKELY (parse->priv->discont &&
2165 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2166 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2167 ("Failed to parse stream"), (NULL));
2168 return GST_FLOW_ERROR;
2174 static GstFlowReturn
2175 gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
2177 GstBaseParseClass *bclass;
2178 GstBaseParse *parse;
2179 GstFlowReturn ret = GST_FLOW_OK;
2180 GstBuffer *outbuf = NULL;
2181 GstBuffer *tmpbuf = NULL;
2185 guint old_min_size = 0, min_size, av;
2186 GstClockTime timestamp;
2187 GstBaseParseFrame *frame;
2189 parse = GST_BASE_PARSE (GST_OBJECT_PARENT (pad));
2190 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2191 frame = &parse->priv->frame;
2193 if (G_LIKELY (buffer)) {
2194 GST_LOG_OBJECT (parse, "buffer size: %d, offset = %" G_GINT64_FORMAT,
2195 gst_buffer_get_size (buffer), GST_BUFFER_OFFSET (buffer));
2196 if (G_UNLIKELY (parse->priv->passthrough)) {
2197 gst_base_parse_frame_init (frame);
2198 frame->buffer = gst_buffer_make_writable (buffer);
2199 return gst_base_parse_push_frame (parse, frame);
2201 /* upstream feeding us in reverse playback;
2202 * gather each fragment, then process it in single run */
2203 if (parse->segment.rate < 0.0) {
2204 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2205 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2206 ret = gst_base_parse_process_fragment (parse, FALSE);
2208 gst_adapter_push (parse->priv->adapter, buffer);
2211 gst_adapter_push (parse->priv->adapter, buffer);
2214 if (G_UNLIKELY (buffer &&
2215 GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2216 frame->_private_flags |= GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
2217 gst_base_parse_frame_free (frame);
2220 /* Parse and push as many frames as possible */
2221 /* Stop either when adapter is empty or we are flushing */
2222 while (!parse->priv->flushing) {
2225 /* maintain frame state for a single frame parsing round across _chain calls,
2226 * so only init when needed */
2227 if (!frame->_private_flags)
2228 gst_base_parse_frame_init (frame);
2230 tmpbuf = gst_buffer_new ();
2233 /* Synchronization loop */
2235 /* note: if subclass indicates MAX fsize,
2236 * this will not likely be available anyway ... */
2237 min_size = MAX (parse->priv->min_frame_size, fsize);
2238 av = gst_adapter_available (parse->priv->adapter);
2240 /* loop safety check */
2241 if (G_UNLIKELY (old_min_size >= min_size))
2243 old_min_size = min_size;
2245 if (G_UNLIKELY (parse->priv->drain)) {
2247 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2248 if (G_UNLIKELY (!min_size)) {
2249 gst_buffer_unref (tmpbuf);
2254 /* Collect at least min_frame_size bytes */
2255 if (av < min_size) {
2256 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
2258 gst_buffer_unref (tmpbuf);
2262 /* always pass all available data */
2263 data = gst_adapter_map (parse->priv->adapter, av);
2264 gst_buffer_take_memory (tmpbuf, -1,
2265 gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
2266 (gpointer) data, NULL, av, 0, av));
2267 GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
2269 if (parse->priv->discont) {
2270 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2271 GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2275 gst_base_parse_frame_update (parse, frame, tmpbuf);
2276 res = bclass->check_valid_frame (parse, frame, &fsize, &skip);
2277 gst_adapter_unmap (parse->priv->adapter, 0);
2278 gst_buffer_replace (&frame->buffer, NULL);
2280 if (gst_adapter_available (parse->priv->adapter) < fsize) {
2281 GST_DEBUG_OBJECT (parse,
2282 "found valid frame but not enough data available (only %d bytes)",
2283 gst_adapter_available (parse->priv->adapter));
2284 gst_buffer_unref (tmpbuf);
2287 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2291 /* subclass didn't touch this value. By default we skip 1 byte */
2295 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2296 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2297 /* reverse playback, and no frames found yet, so we are skipping
2298 * the leading part of a fragment, which may form the tail of
2299 * fragment coming later, hopefully subclass skips efficiently ... */
2300 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2301 outbuf = gst_adapter_take_buffer (parse->priv->adapter, skip);
2302 outbuf = gst_buffer_make_writable (outbuf);
2303 GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
2304 parse->priv->buffers_pending =
2305 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2308 gst_adapter_flush (parse->priv->adapter, skip);
2310 parse->priv->offset += skip;
2311 if (!parse->priv->discont)
2312 parse->priv->sync_offset = parse->priv->offset;
2313 parse->priv->discont = TRUE;
2314 /* something changed least; nullify loop check */
2317 /* skip == 0 should imply subclass set min_size to need more data;
2318 * we check this shortly */
2319 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2320 gst_buffer_unref (tmpbuf);
2324 gst_buffer_unref (tmpbuf);
2328 /* Subclass found the sync, but still wants to skip some data */
2329 GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
2330 gst_adapter_flush (parse->priv->adapter, skip);
2331 parse->priv->offset += skip;
2334 /* Grab lock to prevent a race with FLUSH_START handler */
2335 GST_PAD_STREAM_LOCK (parse->srcpad);
2337 /* FLUSH_START event causes the "flushing" flag to be set. In this
2338 * case we can leave the frame pushing loop */
2339 if (parse->priv->flushing) {
2340 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2344 /* move along with upstream timestamp (if any),
2345 * but interpolate in between */
2346 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2347 if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2348 (parse->priv->prev_ts != timestamp)) {
2349 parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2352 /* FIXME: Would it be more efficient to make a subbuffer instead? */
2353 outbuf = gst_adapter_take_buffer (parse->priv->adapter, fsize);
2354 outbuf = gst_buffer_make_writable (outbuf);
2356 /* Subclass may want to know the data offset */
2357 GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2358 parse->priv->offset += fsize;
2359 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2360 GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
2362 frame->buffer = outbuf;
2363 ret = gst_base_parse_handle_and_push_frame (parse, bclass, frame);
2364 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2366 if (ret != GST_FLOW_OK) {
2367 GST_LOG_OBJECT (parse, "push returned %d", ret);
2373 GST_LOG_OBJECT (parse, "chain leaving");
2379 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2380 ("min_size evolution %d -> %d; breaking to avoid looping",
2381 old_min_size, min_size));
2382 return GST_FLOW_ERROR;
2386 /* pull @size bytes at current offset,
2387 * i.e. at least try to and possibly return a shorter buffer if near the end */
2388 static GstFlowReturn
2389 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2390 GstBuffer ** buffer)
2392 GstFlowReturn ret = GST_FLOW_OK;
2394 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2396 /* Caching here actually makes much less difference than one would expect.
2397 * We do it mainly to avoid pulling buffers of 1 byte all the time */
2398 if (parse->priv->cache) {
2399 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2400 gint cache_size = gst_buffer_get_size (parse->priv->cache);
2402 if (cache_offset <= parse->priv->offset &&
2403 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2404 *buffer = gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL,
2405 parse->priv->offset - cache_offset, size);
2406 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2409 /* not enough data in the cache, free cache and get a new one */
2410 gst_buffer_unref (parse->priv->cache);
2411 parse->priv->cache = NULL;
2414 /* refill the cache */
2416 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2417 64 * 1024), &parse->priv->cache);
2418 if (ret != GST_FLOW_OK) {
2419 parse->priv->cache = NULL;
2423 if (gst_buffer_get_size (parse->priv->cache) >= size) {
2425 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0,
2427 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2431 /* Not possible to get enough data, try a last time with
2432 * requesting exactly the size we need */
2433 gst_buffer_unref (parse->priv->cache);
2434 parse->priv->cache = NULL;
2436 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2437 &parse->priv->cache);
2439 if (ret != GST_FLOW_OK) {
2440 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2445 if (gst_buffer_get_size (parse->priv->cache) < size) {
2446 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2447 G_GUINT64_FORMAT ": wanted %u bytes, got %u bytes", parse->priv->offset,
2448 size, gst_buffer_get_size (parse->priv->cache));
2450 *buffer = parse->priv->cache;
2451 parse->priv->cache = NULL;
2457 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0, size);
2458 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2463 static GstFlowReturn
2464 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2467 GstClockTime ts = 0;
2471 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2472 ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2473 parse->priv->last_offset);
2475 if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2476 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2477 GST_TIME_ARGS (parse->segment.start));
2478 ret = GST_FLOW_UNEXPECTED;
2482 /* last fragment started at last_offset / last_ts;
2483 * seek back 10s capped at 1MB */
2484 if (parse->priv->last_ts >= 10 * GST_SECOND)
2485 ts = parse->priv->last_ts - 10 * GST_SECOND;
2486 /* if we are exact now, we will be more so going backwards */
2487 if (parse->priv->exact_position) {
2488 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2490 GstFormat dstformat = GST_FORMAT_BYTES;
2492 if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2493 &dstformat, &offset)) {
2494 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2497 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2498 parse->priv->last_offset - 1024);
2499 offset = MAX (0, offset);
2501 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2503 parse->priv->offset = offset;
2505 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2507 if (ret != GST_FLOW_OK)
2510 /* offset will increase again as fragment is processed/parsed */
2511 parse->priv->last_offset = offset;
2513 gst_adapter_push (parse->priv->adapter, buffer);
2514 ret = gst_base_parse_process_fragment (parse, FALSE);
2515 if (ret != GST_FLOW_OK)
2518 /* force previous fragment */
2519 parse->priv->offset = -1;
2526 * pull and scan for next frame starting from current offset
2527 * ajusts sync, drain and offset going along */
2528 static GstFlowReturn
2529 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2530 GstBaseParseFrame * frame, gboolean full)
2532 GstBuffer *buffer, *outbuf;
2533 GstFlowReturn ret = GST_FLOW_OK;
2534 guint fsize = 1, min_size, old_min_size = 0;
2537 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2539 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2540 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2542 /* let's make this efficient for all subclass once and for all;
2543 * maybe it does not need this much, but in the latter case, we know we are
2544 * in pull mode here and might as well try to read and supply more anyway
2545 * (so does the buffer caching mechanism) */
2551 min_size = MAX (parse->priv->min_frame_size, fsize);
2552 /* loop safety check */
2553 if (G_UNLIKELY (old_min_size >= min_size))
2555 old_min_size = min_size;
2557 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2558 if (ret != GST_FLOW_OK)
2561 if (parse->priv->discont) {
2562 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2563 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2566 /* if we got a short read, inform subclass we are draining leftover
2567 * and no more is to be expected */
2568 if (gst_buffer_get_size (buffer) < min_size)
2569 parse->priv->drain = TRUE;
2572 gst_base_parse_frame_update (parse, frame, buffer);
2573 res = klass->check_valid_frame (parse, frame, &fsize, &skip);
2574 gst_buffer_replace (&frame->buffer, NULL);
2576 parse->priv->drain = FALSE;
2577 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2580 parse->priv->drain = FALSE;
2584 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2585 if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2586 /* reverse playback, and no frames found yet, so we are skipping
2587 * the leading part of a fragment, which may form the tail of
2588 * fragment coming later, hopefully subclass skips efficiently ... */
2589 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, 0, skip);
2590 parse->priv->buffers_pending =
2591 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2594 parse->priv->offset += skip;
2595 if (!parse->priv->discont)
2596 parse->priv->sync_offset = parse->priv->offset;
2597 parse->priv->discont = TRUE;
2598 /* something changed at least; nullify loop check */
2599 if (fsize == G_MAXUINT)
2600 fsize = old_min_size + 64 * 1024;
2603 /* skip == 0 should imply subclass set min_size to need more data;
2604 * we check this shortly */
2605 GST_DEBUG_OBJECT (parse, "finding sync...");
2606 gst_buffer_unref (buffer);
2607 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2612 /* Does the subclass want to skip too? */
2614 parse->priv->offset += skip;
2618 if (fsize + skip <= gst_buffer_get_size (buffer)) {
2619 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, skip, fsize);
2620 GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2621 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2622 gst_buffer_unref (buffer);
2624 gst_buffer_unref (buffer);
2625 ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2626 if (ret != GST_FLOW_OK)
2628 if (gst_buffer_get_size (outbuf) < fsize) {
2629 gst_buffer_unref (outbuf);
2630 ret = GST_FLOW_UNEXPECTED;
2634 parse->priv->offset += fsize;
2636 frame->buffer = outbuf;
2644 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2645 ("min_size evolution %d -> %d; breaking to avoid looping",
2646 old_min_size, min_size));
2647 return GST_FLOW_ERROR;
2651 /* Loop that is used in pull mode to retrieve data from upstream */
2653 gst_base_parse_loop (GstPad * pad)
2655 GstBaseParse *parse;
2656 GstBaseParseClass *klass;
2657 GstFlowReturn ret = GST_FLOW_OK;
2658 GstBaseParseFrame frame;
2660 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2661 klass = GST_BASE_PARSE_GET_CLASS (parse);
2663 /* reverse playback:
2664 * first fragment (closest to stop time) is handled normally below,
2665 * then we pull in fragments going backwards */
2666 if (parse->segment.rate < 0.0) {
2667 /* check if we jumped back to a previous fragment,
2668 * which is a post-first fragment */
2669 if (parse->priv->offset < 0) {
2670 ret = gst_base_parse_handle_previous_fragment (parse);
2675 gst_base_parse_frame_init (&frame);
2676 ret = gst_base_parse_scan_frame (parse, klass, &frame, TRUE);
2677 if (ret != GST_FLOW_OK)
2680 /* This always cleans up frame, even if error occurs */
2681 ret = gst_base_parse_handle_and_push_frame (parse, klass, &frame);
2683 /* eat expected eos signalling past segment in reverse playback */
2684 if (parse->segment.rate < 0.0 && ret == GST_FLOW_UNEXPECTED &&
2685 parse->segment.position >= parse->segment.stop) {
2686 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2687 /* push what was accumulated during loop run */
2688 gst_base_parse_process_fragment (parse, TRUE);
2689 /* force previous fragment */
2690 parse->priv->offset = -1;
2695 if (ret == GST_FLOW_UNEXPECTED)
2697 else if (ret != GST_FLOW_OK)
2700 gst_object_unref (parse);
2706 ret = GST_FLOW_UNEXPECTED;
2707 GST_DEBUG_OBJECT (parse, "eos");
2712 gboolean push_eos = FALSE;
2714 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2715 gst_flow_get_name (ret));
2716 gst_pad_pause_task (parse->sinkpad);
2718 if (ret == GST_FLOW_UNEXPECTED) {
2719 /* handle end-of-stream/segment */
2720 if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2723 if ((stop = parse->segment.stop) == -1)
2724 stop = parse->segment.duration;
2726 GST_DEBUG_OBJECT (parse, "sending segment_done");
2728 gst_element_post_message
2729 (GST_ELEMENT_CAST (parse),
2730 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2731 GST_FORMAT_TIME, stop));
2733 /* If we STILL have zero frames processed, fire an error */
2734 if (parse->priv->framecount == 0) {
2735 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2736 ("No valid frames found before end of stream"), (NULL));
2740 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
2741 /* for fatal errors we post an error message, wrong-state is
2742 * not fatal because it happens due to flushes and only means
2743 * that we should stop now. */
2744 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2745 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2749 /* newsegment before eos */
2750 if (parse->priv->pending_segment) {
2751 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
2752 parse->priv->pending_segment = NULL;
2754 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2756 gst_object_unref (parse);
2761 gst_base_parse_sink_activate (GstPad * sinkpad)
2763 GstBaseParse *parse;
2764 gboolean result = TRUE;
2768 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2770 GST_DEBUG_OBJECT (parse, "sink activate");
2772 query = gst_query_new_scheduling ();
2773 result = gst_pad_peer_query (sinkpad, query);
2775 gst_query_parse_scheduling (query, &pull_mode, NULL, NULL, NULL, NULL,
2780 gst_query_unref (query);
2783 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2784 result = gst_pad_activate_pull (sinkpad, TRUE);
2786 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
2787 result = gst_pad_activate_push (sinkpad, TRUE);
2790 GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
2791 gst_object_unref (parse);
2796 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
2798 GstBaseParseClass *klass;
2799 gboolean result = FALSE;
2801 GST_DEBUG_OBJECT (parse, "activate %d", active);
2803 klass = GST_BASE_PARSE_GET_CLASS (parse);
2806 if (parse->priv->pad_mode == GST_ACTIVATE_NONE && klass->start)
2807 result = klass->start (parse);
2809 /* We must make sure streaming has finished before resetting things
2810 * and calling the ::stop vfunc */
2811 GST_PAD_STREAM_LOCK (parse->sinkpad);
2812 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2814 if (parse->priv->pad_mode != GST_ACTIVATE_NONE && klass->stop)
2815 result = klass->stop (parse);
2817 parse->priv->pad_mode = GST_ACTIVATE_NONE;
2819 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
2824 gst_base_parse_sink_activate_push (GstPad * pad, gboolean active)
2826 gboolean result = TRUE;
2827 GstBaseParse *parse;
2829 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2831 GST_DEBUG_OBJECT (parse, "sink activate push %d", active);
2833 result = gst_base_parse_activate (parse, active);
2836 parse->priv->pad_mode = active ? GST_ACTIVATE_PUSH : GST_ACTIVATE_NONE;
2838 GST_DEBUG_OBJECT (parse, "sink activate push return: %d", result);
2840 gst_object_unref (parse);
2845 gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
2847 gboolean result = FALSE;
2848 GstBaseParse *parse;
2850 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2852 GST_DEBUG_OBJECT (parse, "activate pull %d", active);
2854 result = gst_base_parse_activate (parse, active);
2858 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
2860 gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
2863 result &= gst_pad_stop_task (sinkpad);
2868 parse->priv->pad_mode = active ? GST_ACTIVATE_PULL : GST_ACTIVATE_NONE;
2870 GST_DEBUG_OBJECT (parse, "sink activate pull return: %d", result);
2872 gst_object_unref (parse);
2878 * gst_base_parse_set_duration:
2879 * @parse: #GstBaseParse.
2881 * @duration: duration value.
2882 * @interval: how often to update the duration estimate based on bitrate, or 0.
2884 * Sets the duration of the currently playing media. Subclass can use this
2885 * when it is able to determine duration and/or notices a change in the media
2886 * duration. Alternatively, if @interval is non-zero (default), then stream
2887 * duration is determined based on estimated bitrate, and updated every @interval
2893 gst_base_parse_set_duration (GstBaseParse * parse,
2894 GstFormat fmt, gint64 duration, gint interval)
2896 g_return_if_fail (parse != NULL);
2898 if (parse->priv->upstream_has_duration) {
2899 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
2903 if (duration != parse->priv->duration) {
2906 m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
2907 gst_element_post_message (GST_ELEMENT (parse), m);
2909 /* TODO: what about duration tag? */
2911 parse->priv->duration = duration;
2912 parse->priv->duration_fmt = fmt;
2913 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
2914 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
2915 if (interval != 0) {
2916 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
2920 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
2921 parse->priv->update_interval = interval;
2927 * gst_base_parse_set_average_bitrate:
2928 * @parse: #GstBaseParse.
2929 * @bitrate: average bitrate in bits/second
2931 * Optionally sets the average bitrate detected in media (if non-zero),
2932 * e.g. based on metadata, as it will be posted to the application.
2934 * By default, announced average bitrate is estimated. The average bitrate
2935 * is used to estimate the total duration of the stream and to estimate
2936 * a seek position, if there's no index and the format is syncable
2937 * (see gst_base_parse_set_syncable()).
2942 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
2944 parse->priv->bitrate = bitrate;
2945 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
2949 * gst_base_parse_set_min_frame_size:
2950 * @parse: #GstBaseParse.
2951 * @min_size: Minimum size of the data that this base class should give to
2954 * Subclass can use this function to tell the base class that it needs to
2955 * give at least #min_size buffers.
2960 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
2962 g_return_if_fail (parse != NULL);
2964 parse->priv->min_frame_size = min_size;
2965 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
2969 * gst_base_parse_set_frame_rate:
2970 * @parse: the #GstBaseParse to set
2971 * @fps_num: frames per second (numerator).
2972 * @fps_den: frames per second (denominator).
2973 * @lead_in: frames needed before a segment for subsequent decode
2974 * @lead_out: frames needed after a segment
2976 * If frames per second is configured, parser can take care of buffer duration
2977 * and timestamping. When performing segment clipping, or seeking to a specific
2978 * location, a corresponding decoder might need an initial @lead_in and a
2979 * following @lead_out number of frames to ensure the desired segment is
2980 * entirely filled upon decoding.
2985 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
2986 guint fps_den, guint lead_in, guint lead_out)
2988 g_return_if_fail (parse != NULL);
2990 parse->priv->fps_num = fps_num;
2991 parse->priv->fps_den = fps_den;
2992 if (!fps_num || !fps_den) {
2993 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
2995 fps_num = fps_den = 0;
2996 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
2997 parse->priv->lead_in = parse->priv->lead_out = 0;
2998 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
3000 parse->priv->frame_duration =
3001 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
3002 parse->priv->lead_in = lead_in;
3003 parse->priv->lead_out = lead_out;
3004 parse->priv->lead_in_ts =
3005 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
3006 parse->priv->lead_out_ts =
3007 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
3008 /* aim for about 1.5s to estimate duration */
3009 if (parse->priv->update_interval < 0) {
3010 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
3011 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
3012 parse->priv->update_interval);
3015 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
3016 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
3017 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
3018 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
3019 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
3020 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
3024 * gst_base_parse_set_has_timing_info:
3025 * @parse: a #GstBaseParse
3026 * @has_timing: whether frames carry timing information
3028 * Set if frames carry timing information which the subclass can (generally)
3029 * parse and provide. In particular, intrinsic (rather than estimated) time
3030 * can be obtained following a seek.
3035 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3037 parse->priv->has_timing_info = has_timing;
3038 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3042 * gst_base_parse_set_syncable:
3043 * @parse: a #GstBaseParse
3044 * @syncable: set if frame starts can be identified
3046 * Set if frame starts can be identified. This is set by default and
3047 * determines whether seeking based on bitrate averages
3048 * is possible for a format/stream.
3053 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3055 parse->priv->syncable = syncable;
3056 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3060 * gst_base_parse_set_passthrough:
3061 * @parse: a #GstBaseParse
3062 * @passthrough: %TRUE if parser should run in passthrough mode
3064 * Set if the nature of the format or configuration does not allow (much)
3065 * parsing, and the parser should operate in passthrough mode (which only
3066 * applies when operating in push mode). That is, incoming buffers are
3067 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3068 * callbacks will be invoked, but @pre_push_buffer will still be invoked,
3069 * so subclass can perform as much or as little is appropriate for
3070 * passthrough semantics in @pre_push_buffer.
3075 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3077 parse->priv->passthrough = passthrough;
3078 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3082 * gst_base_parse_set_latency:
3083 * @parse: a #GstBaseParse
3084 * @min_latency: minimum parse latency
3085 * @max_latency: maximum parse latency
3087 * Sets the minimum and maximum (which may likely be equal) latency introduced
3088 * by the parsing process. If there is such a latency, which depends on the
3089 * particular parsing of the format, it typically corresponds to 1 frame duration.
3094 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3095 GstClockTime max_latency)
3097 GST_OBJECT_LOCK (parse);
3098 parse->priv->min_latency = min_latency;
3099 parse->priv->max_latency = max_latency;
3100 GST_OBJECT_UNLOCK (parse);
3101 GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3102 GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3103 GST_TIME_ARGS (max_latency));
3107 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3108 GstClockTime * duration)
3110 gboolean res = FALSE;
3112 g_return_val_if_fail (duration != NULL, FALSE);
3114 *duration = GST_CLOCK_TIME_NONE;
3115 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3116 GST_LOG_OBJECT (parse, "using provided duration");
3117 *duration = parse->priv->duration;
3119 } else if (parse->priv->duration != -1) {
3120 GST_LOG_OBJECT (parse, "converting provided duration");
3121 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3122 parse->priv->duration, format, (gint64 *) duration);
3123 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3124 GST_LOG_OBJECT (parse, "using estimated duration");
3125 *duration = parse->priv->estimated_duration;
3129 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3130 GST_TIME_ARGS (*duration));
3134 static const GstQueryType *
3135 gst_base_parse_get_querytypes (GstPad * pad)
3137 static const GstQueryType list[] = {
3150 gst_base_parse_query (GstPad * pad, GstQuery * query)
3152 GstBaseParse *parse;
3153 gboolean res = FALSE;
3155 parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3157 GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3159 switch (GST_QUERY_TYPE (query)) {
3160 case GST_QUERY_POSITION:
3165 GST_DEBUG_OBJECT (parse, "position query");
3166 gst_query_parse_position (query, &format, NULL);
3168 GST_OBJECT_LOCK (parse);
3169 if (format == GST_FORMAT_BYTES) {
3170 dest_value = parse->priv->offset;
3172 } else if (format == parse->segment.format &&
3173 GST_CLOCK_TIME_IS_VALID (parse->segment.position)) {
3174 dest_value = parse->segment.position;
3177 GST_OBJECT_UNLOCK (parse);
3180 gst_query_set_position (query, format, dest_value);
3182 res = gst_pad_query_default (pad, query);
3184 /* no precise result, upstream no idea either, then best estimate */
3185 /* priv->offset is updated in both PUSH/PULL modes */
3186 res = gst_base_parse_convert (parse,
3187 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3192 case GST_QUERY_DURATION:
3195 GstClockTime duration;
3197 GST_DEBUG_OBJECT (parse, "duration query");
3198 gst_query_parse_duration (query, &format, NULL);
3200 /* consult upstream */
3201 res = gst_pad_query_default (pad, query);
3203 /* otherwise best estimate from us */
3205 res = gst_base_parse_get_duration (parse, format, &duration);
3207 gst_query_set_duration (query, format, duration);
3211 case GST_QUERY_SEEKING:
3214 GstClockTime duration = GST_CLOCK_TIME_NONE;
3215 gboolean seekable = FALSE;
3217 GST_DEBUG_OBJECT (parse, "seeking query");
3218 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3220 /* consult upstream */
3221 res = gst_pad_query_default (pad, query);
3223 /* we may be able to help if in TIME */
3224 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3225 gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3226 /* already OK if upstream takes care */
3227 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3229 if (!(res && seekable)) {
3230 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3231 || duration == -1) {
3232 /* seekable if we still have a chance to get duration later on */
3234 parse->priv->upstream_seekable && parse->priv->update_interval;
3236 seekable = parse->priv->upstream_seekable;
3237 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3240 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3246 case GST_QUERY_FORMATS:
3247 gst_query_set_formatsv (query, 3, fmtlist);
3250 case GST_QUERY_CONVERT:
3252 GstFormat src_format, dest_format;
3253 gint64 src_value, dest_value;
3255 gst_query_parse_convert (query, &src_format, &src_value,
3256 &dest_format, &dest_value);
3258 res = gst_base_parse_convert (parse, src_format, src_value,
3259 dest_format, &dest_value);
3261 gst_query_set_convert (query, src_format, src_value,
3262 dest_format, dest_value);
3266 case GST_QUERY_LATENCY:
3268 if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3270 GstClockTime min_latency, max_latency;
3272 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3273 GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3274 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3275 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3277 GST_OBJECT_LOCK (parse);
3278 /* add our latency */
3279 if (min_latency != -1)
3280 min_latency += parse->priv->min_latency;
3281 if (max_latency != -1)
3282 max_latency += parse->priv->max_latency;
3283 GST_OBJECT_UNLOCK (parse);
3285 gst_query_set_latency (query, live, min_latency, max_latency);
3290 res = gst_pad_query_default (pad, query);
3296 /* scans for a cluster start from @pos,
3297 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3298 static GstFlowReturn
3299 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3300 GstClockTime * time, GstClockTime * duration)
3302 GstBaseParseClass *klass;
3304 gboolean orig_drain, orig_discont;
3305 GstFlowReturn ret = GST_FLOW_OK;
3306 GstBuffer *buf = NULL;
3307 GstBaseParseFrame frame;
3309 g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3310 g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3311 g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3313 klass = GST_BASE_PARSE_GET_CLASS (parse);
3315 *time = GST_CLOCK_TIME_NONE;
3316 *duration = GST_CLOCK_TIME_NONE;
3319 orig_offset = parse->priv->offset;
3320 orig_discont = parse->priv->discont;
3321 orig_drain = parse->priv->drain;
3323 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3324 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3326 gst_base_parse_frame_init (&frame);
3328 /* jump elsewhere and locate next frame */
3329 parse->priv->offset = *pos;
3330 ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3331 if (ret != GST_FLOW_OK)
3335 GST_LOG_OBJECT (parse,
3336 "peek parsing frame at offset %" G_GUINT64_FORMAT
3337 " (%#" G_GINT64_MODIFIER "x) of size %d",
3338 GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf),
3339 gst_buffer_get_size (buf));
3341 /* get offset first, subclass parsing might dump other stuff in there */
3342 *pos = GST_BUFFER_OFFSET (buf);
3343 ret = klass->parse_frame (parse, &frame);
3346 /* but it should provide proper time */
3347 *time = GST_BUFFER_TIMESTAMP (buf);
3348 *duration = GST_BUFFER_DURATION (buf);
3350 gst_base_parse_frame_free (&frame);
3352 GST_LOG_OBJECT (parse,
3353 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3354 GST_TIME_ARGS (*time), *pos);
3358 parse->priv->offset = orig_offset;
3359 parse->priv->discont = orig_discont;
3360 parse->priv->drain = orig_drain;
3365 /* bisect and scan through file for frame starting before @time,
3366 * returns OK and @time/@offset if found, NONE and/or error otherwise
3367 * If @time == G_MAXINT64, scan for duration ( == last frame) */
3368 static GstFlowReturn
3369 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3372 GstFlowReturn ret = GST_FLOW_OK;
3373 gint64 lpos, hpos, newpos;
3374 GstClockTime time, ltime, htime, newtime, dur;
3375 gboolean cont = TRUE;
3376 const GstClockTime tolerance = TARGET_DIFFERENCE;
3377 const guint chunk = 4 * 1024;
3379 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3380 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3382 /* TODO also make keyframe aware if useful some day */
3397 /* do not know at first */
3399 *_time = GST_CLOCK_TIME_NONE;
3401 /* need initial positions; start and end */
3402 lpos = parse->priv->first_frame_offset;
3403 ltime = parse->priv->first_frame_ts;
3404 htime = parse->priv->duration;
3405 hpos = parse->priv->upstream_size;
3407 /* check preconditions are satisfied;
3408 * start and end are needed, except for special case where we scan for
3409 * last frame to determine duration */
3410 if (parse->priv->pad_mode != GST_ACTIVATE_PULL || !hpos ||
3411 !GST_CLOCK_TIME_IS_VALID (ltime) ||
3412 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3416 /* shortcut cases */
3419 } else if (time < ltime + tolerance) {
3423 } else if (time >= htime) {
3429 while (htime > ltime && cont) {
3430 GST_LOG_OBJECT (parse,
3431 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3432 GST_TIME_ARGS (ltime));
3433 GST_LOG_OBJECT (parse,
3434 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3435 GST_TIME_ARGS (htime));
3436 if (G_UNLIKELY (time == G_MAXINT64)) {
3438 } else if (G_LIKELY (hpos > lpos)) {
3440 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3443 /* should mean lpos == hpos, since lpos <= hpos is invariant */
3445 /* we check this case once, but not forever, so break loop */
3450 newpos = CLAMP (newpos, lpos, hpos);
3451 GST_LOG_OBJECT (parse,
3452 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3453 GST_TIME_ARGS (time), newpos);
3455 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3456 if (ret == GST_FLOW_UNEXPECTED) {
3457 /* heuristic HACK */
3458 hpos = MAX (lpos, hpos - chunk);
3460 } else if (ret != GST_FLOW_OK) {
3464 if (newtime == -1 || newpos == -1) {
3465 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3469 if (G_UNLIKELY (time == G_MAXINT64)) {
3472 if (GST_CLOCK_TIME_IS_VALID (dur))
3475 } else if (newtime > time) {
3477 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3479 } else if (newtime + tolerance > time) {
3480 /* close enough undershoot */
3484 } else if (newtime < ltime) {
3485 /* so a position beyond lpos resulted in earlier time than ltime ... */
3486 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3489 /* undershoot too far */
3490 newpos += newpos == lpos ? chunk : 0;
3491 lpos = CLAMP (newpos, lpos, hpos);
3497 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3498 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3503 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3504 gboolean before, GstClockTime * _ts)
3506 gint64 bytes = 0, ts = 0;
3507 GstIndexEntry *entry = NULL;
3509 if (time == GST_CLOCK_TIME_NONE) {
3515 g_static_mutex_lock (&parse->priv->index_lock);
3516 if (parse->priv->index) {
3517 /* Let's check if we have an index entry for that time */
3518 entry = gst_index_get_assoc_entry (parse->priv->index,
3519 parse->priv->index_id,
3520 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3521 GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3525 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3526 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3528 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3529 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3530 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3532 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3533 GST_TIME_ARGS (time));
3536 ts = GST_CLOCK_TIME_NONE;
3539 g_static_mutex_unlock (&parse->priv->index_lock);
3548 /* returns TRUE if seek succeeded */
3550 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3555 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3556 gboolean flush, update, res = TRUE, accurate;
3557 gint64 cur, stop, seekpos, seekstop;
3558 GstSegment seeksegment = { 0, };
3559 GstFormat dstformat;
3560 GstClockTime start_ts;
3562 gst_event_parse_seek (event, &rate, &format, &flags,
3563 &cur_type, &cur, &stop_type, &stop);
3565 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3566 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3567 GST_TIME_FORMAT, gst_format_get_name (format), rate,
3568 cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3570 /* no negative rates in push mode */
3571 if (rate < 0.0 && parse->priv->pad_mode == GST_ACTIVATE_PUSH)
3574 if (cur_type != GST_SEEK_TYPE_SET ||
3575 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3578 /* For any format other than TIME, see if upstream handles
3579 * it directly or fail. For TIME, try upstream, but do it ourselves if
3580 * it fails upstream */
3581 if (format != GST_FORMAT_TIME) {
3582 /* default action delegates to upstream */
3586 gst_event_ref (event);
3587 if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3592 /* get flush flag */
3593 flush = flags & GST_SEEK_FLAG_FLUSH;
3595 /* copy segment, we need this because we still need the old
3596 * segment when we close the current segment. */
3597 gst_segment_copy_into (&parse->segment, &seeksegment);
3599 GST_DEBUG_OBJECT (parse, "configuring seek");
3600 gst_segment_do_seek (&seeksegment, rate, format, flags,
3601 cur_type, cur, stop_type, stop, &update);
3603 /* accurate seeking implies seek tables are used to obtain position,
3604 * and the requested segment is maintained exactly, not adjusted any way */
3605 accurate = flags & GST_SEEK_FLAG_ACCURATE;
3607 /* maybe we can be accurate for (almost) free */
3608 gst_base_parse_find_offset (parse, seeksegment.position, TRUE, &start_ts);
3609 if (seeksegment.position <= start_ts + TARGET_DIFFERENCE) {
3610 GST_DEBUG_OBJECT (parse, "accurate seek possible");
3614 GstClockTime startpos = seeksegment.position;
3616 /* accurate requested, so ... seek a bit before target */
3617 if (startpos < parse->priv->lead_in_ts)
3620 startpos -= parse->priv->lead_in_ts;
3621 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3622 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3625 start_ts = seeksegment.position;
3626 dstformat = GST_FORMAT_BYTES;
3627 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.position,
3628 &dstformat, &seekpos))
3629 goto convert_failed;
3630 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3631 &dstformat, &seekstop))
3632 goto convert_failed;
3635 GST_DEBUG_OBJECT (parse,
3636 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3638 GST_DEBUG_OBJECT (parse,
3639 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3640 seeksegment.stop, seekstop);
3642 if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
3645 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3648 if (parse->srcpad) {
3649 GST_DEBUG_OBJECT (parse, "sending flush start");
3650 gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3651 /* unlock upstream pull_range */
3652 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3655 gst_pad_pause_task (parse->sinkpad);
3658 /* we should now be able to grab the streaming thread because we stopped it
3659 * with the above flush/pause code */
3660 GST_PAD_STREAM_LOCK (parse->sinkpad);
3662 /* save current position */
3663 last_stop = parse->segment.position;
3664 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3667 /* now commit to new position */
3669 /* prepare for streaming again */
3671 GST_DEBUG_OBJECT (parse, "sending flush stop");
3672 gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop (TRUE));
3673 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop (TRUE));
3674 gst_base_parse_clear_queues (parse);
3676 /* keep track of our position */
3677 seeksegment.base = gst_segment_to_running_time (&seeksegment,
3678 seeksegment.format, parse->segment.position);
3681 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3683 /* store the newsegment event so it can be sent from the streaming thread. */
3684 if (parse->priv->pending_segment)
3685 gst_event_unref (parse->priv->pending_segment);
3687 /* This will be sent later in _loop() */
3688 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
3690 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3691 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3692 ", pos = %" GST_TIME_FORMAT, format,
3693 GST_TIME_ARGS (parse->segment.start),
3694 GST_TIME_ARGS (parse->segment.stop),
3695 GST_TIME_ARGS (parse->segment.start));
3697 /* one last chance in pull mode to stay accurate;
3698 * maybe scan and subclass can find where to go */
3701 GstClockTime ts = seeksegment.position;
3703 gst_base_parse_locate_time (parse, &ts, &scanpos);
3707 /* running collected index now consists of several intervals,
3708 * so optimized check no longer possible */
3709 parse->priv->index_last_valid = FALSE;
3710 parse->priv->index_last_offset = 0;
3711 parse->priv->index_last_ts = 0;
3715 /* mark discont if we are going to stream from another position. */
3716 if (seekpos != parse->priv->offset) {
3717 GST_DEBUG_OBJECT (parse,
3718 "mark DISCONT, we did a seek to another position");
3719 parse->priv->offset = seekpos;
3720 parse->priv->last_offset = seekpos;
3721 parse->priv->seen_keyframe = FALSE;
3722 parse->priv->discont = TRUE;
3723 parse->priv->next_ts = start_ts;
3724 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3725 parse->priv->sync_offset = seekpos;
3726 parse->priv->exact_position = accurate;
3729 /* Start streaming thread if paused */
3730 gst_pad_start_task (parse->sinkpad,
3731 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3733 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3738 GstEvent *new_event;
3739 GstBaseParseSeek *seek;
3741 /* The only thing we need to do in PUSH-mode is to send the
3742 seek event (in bytes) to upstream. Segment / flush handling happens
3743 in corresponding src event handlers */
3744 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3745 if (seekstop >= 0 && seekstop <= seekpos)
3747 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flush,
3748 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3750 /* store segment info so its precise details can be reconstructed when
3751 * receiving newsegment;
3752 * this matters for all details when accurate seeking,
3753 * is most useful to preserve NONE stop time otherwise */
3754 seek = g_new0 (GstBaseParseSeek, 1);
3755 seek->segment = seeksegment;
3756 seek->accurate = accurate;
3757 seek->offset = seekpos;
3758 seek->start_ts = start_ts;
3759 GST_OBJECT_LOCK (parse);
3760 /* less optimal, but preserves order */
3761 parse->priv->pending_seeks =
3762 g_slist_append (parse->priv->pending_seeks, seek);
3763 GST_OBJECT_UNLOCK (parse);
3765 res = gst_pad_push_event (parse->sinkpad, new_event);
3768 GST_OBJECT_LOCK (parse);
3769 parse->priv->pending_seeks =
3770 g_slist_remove (parse->priv->pending_seeks, seek);
3771 GST_OBJECT_UNLOCK (parse);
3777 /* handled event is ours to free */
3779 gst_event_unref (event);
3785 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
3791 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3797 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3803 /* Checks if bitrates are available from upstream tags so that we don't
3804 * override them later
3807 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
3809 GstTagList *taglist = NULL;
3812 gst_event_parse_tag (event, &taglist);
3814 if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
3815 GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
3816 parse->priv->post_min_bitrate = FALSE;
3818 if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
3819 GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
3820 parse->priv->post_avg_bitrate = FALSE;
3822 if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
3823 GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
3824 parse->priv->post_max_bitrate = FALSE;
3829 gst_base_parse_set_index (GstElement * element, GstIndex * index)
3831 GstBaseParse *parse = GST_BASE_PARSE (element);
3833 g_static_mutex_lock (&parse->priv->index_lock);
3834 if (parse->priv->index)
3835 gst_object_unref (parse->priv->index);
3837 parse->priv->index = gst_object_ref (index);
3838 gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
3839 &parse->priv->index_id);
3840 parse->priv->own_index = FALSE;
3842 parse->priv->index = NULL;
3844 g_static_mutex_unlock (&parse->priv->index_lock);
3848 gst_base_parse_get_index (GstElement * element)
3850 GstBaseParse *parse = GST_BASE_PARSE (element);
3851 GstIndex *result = NULL;
3853 g_static_mutex_lock (&parse->priv->index_lock);
3854 if (parse->priv->index)
3855 result = gst_object_ref (parse->priv->index);
3856 g_static_mutex_unlock (&parse->priv->index_lock);
3861 static GstStateChangeReturn
3862 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
3864 GstBaseParse *parse;
3865 GstStateChangeReturn result;
3867 parse = GST_BASE_PARSE (element);
3869 switch (transition) {
3870 case GST_STATE_CHANGE_READY_TO_PAUSED:
3871 /* If this is our own index destroy it as the
3872 * old entries might be wrong for the new stream */
3873 g_static_mutex_lock (&parse->priv->index_lock);
3874 if (parse->priv->own_index) {
3875 gst_object_unref (parse->priv->index);
3876 parse->priv->index = NULL;
3877 parse->priv->own_index = FALSE;
3880 /* If no index was created, generate one */
3881 if (G_UNLIKELY (!parse->priv->index)) {
3882 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
3884 parse->priv->index = gst_index_factory_make ("memindex");
3885 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
3886 &parse->priv->index_id);
3887 parse->priv->own_index = TRUE;
3889 g_static_mutex_unlock (&parse->priv->index_lock);
3895 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3897 switch (transition) {
3898 case GST_STATE_CHANGE_PAUSED_TO_READY:
3899 gst_base_parse_reset (parse);