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 gboolean gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps);
381 static const GstQueryType *gst_base_parse_get_querytypes (GstPad * pad);
383 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstBuffer * buffer);
384 static void gst_base_parse_loop (GstPad * pad);
386 static gboolean gst_base_parse_check_frame (GstBaseParse * parse,
387 GstBaseParseFrame * frame, guint * framesize, gint * skipsize);
388 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
389 GstBaseParseFrame * frame);
391 static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
394 static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
397 static void gst_base_parse_drain (GstBaseParse * parse);
399 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
400 gboolean post_min, gboolean post_avg, gboolean post_max);
402 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
403 GstClockTime time, gboolean before, GstClockTime * _ts);
404 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
405 GstClockTime * _time, gint64 * _offset);
407 static GstFlowReturn gst_base_parse_process_fragment (GstBaseParse * parse,
410 static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);
413 gst_base_parse_clear_queues (GstBaseParse * parse)
415 g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
416 g_slist_free (parse->priv->buffers_queued);
417 parse->priv->buffers_queued = NULL;
418 g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
420 g_slist_free (parse->priv->buffers_pending);
421 parse->priv->buffers_pending = NULL;
422 g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
423 g_slist_free (parse->priv->buffers_send);
424 parse->priv->buffers_send = NULL;
428 gst_base_parse_finalize (GObject * object)
430 GstBaseParse *parse = GST_BASE_PARSE (object);
433 g_object_unref (parse->priv->adapter);
435 if (parse->priv->pending_segment) {
436 p_ev = &parse->priv->pending_segment;
437 gst_event_replace (p_ev, NULL);
439 if (parse->priv->close_segment) {
440 p_ev = &parse->priv->close_segment;
441 gst_event_replace (p_ev, NULL);
444 if (parse->priv->cache) {
445 gst_buffer_unref (parse->priv->cache);
446 parse->priv->cache = NULL;
449 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
451 g_list_free (parse->priv->pending_events);
452 parse->priv->pending_events = NULL;
454 g_queue_foreach (&parse->priv->queued_frames,
455 (GFunc) gst_base_parse_frame_free, NULL);
456 g_queue_clear (&parse->priv->queued_frames);
458 if (parse->priv->index) {
459 gst_object_unref (parse->priv->index);
460 parse->priv->index = NULL;
463 g_static_mutex_free (&parse->priv->index_lock);
465 gst_base_parse_clear_queues (parse);
467 G_OBJECT_CLASS (parent_class)->finalize (object);
471 gst_base_parse_class_init (GstBaseParseClass * klass)
473 GObjectClass *gobject_class;
474 GstElementClass *gstelement_class;
476 gobject_class = G_OBJECT_CLASS (klass);
477 g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
478 parent_class = g_type_class_peek_parent (klass);
479 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
481 gstelement_class = (GstElementClass *) klass;
482 gstelement_class->change_state =
483 GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
484 gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
485 gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
487 /* Default handlers */
488 klass->check_valid_frame = gst_base_parse_check_frame;
489 klass->parse_frame = gst_base_parse_parse_frame;
490 klass->src_event = gst_base_parse_src_eventfunc;
491 klass->convert = gst_base_parse_convert_default;
493 GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
494 "baseparse element");
498 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
500 GstPadTemplate *pad_template;
502 GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
504 parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
507 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
508 g_return_if_fail (pad_template != NULL);
509 parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
510 gst_pad_set_event_function (parse->sinkpad,
511 GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
512 gst_pad_set_setcaps_function (parse->sinkpad,
513 GST_DEBUG_FUNCPTR (gst_base_parse_sink_setcaps));
514 gst_pad_set_chain_function (parse->sinkpad,
515 GST_DEBUG_FUNCPTR (gst_base_parse_chain));
516 gst_pad_set_activate_function (parse->sinkpad,
517 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
518 gst_pad_set_activatepush_function (parse->sinkpad,
519 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_push));
520 gst_pad_set_activatepull_function (parse->sinkpad,
521 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_pull));
522 gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
524 GST_DEBUG_OBJECT (parse, "sinkpad created");
527 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
528 g_return_if_fail (pad_template != NULL);
529 parse->srcpad = gst_pad_new_from_template (pad_template, "src");
530 gst_pad_set_event_function (parse->srcpad,
531 GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
532 gst_pad_set_query_type_function (parse->srcpad,
533 GST_DEBUG_FUNCPTR (gst_base_parse_get_querytypes));
534 gst_pad_set_query_function (parse->srcpad,
535 GST_DEBUG_FUNCPTR (gst_base_parse_query));
536 gst_pad_use_fixed_caps (parse->srcpad);
537 gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
538 GST_DEBUG_OBJECT (parse, "src created");
540 g_queue_init (&parse->priv->queued_frames);
542 parse->priv->adapter = gst_adapter_new ();
544 parse->priv->pad_mode = GST_ACTIVATE_NONE;
546 g_static_mutex_init (&parse->priv->index_lock);
549 gst_base_parse_reset (parse);
550 GST_DEBUG_OBJECT (parse, "init ok");
553 static GstBaseParseFrame *
554 gst_base_parse_frame_copy (GstBaseParseFrame * frame)
556 GstBaseParseFrame *copy;
558 copy = g_slice_dup (GstBaseParseFrame, frame);
559 copy->buffer = gst_buffer_ref (frame->buffer);
560 copy->_private_flags &= ~GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
562 GST_TRACE ("copied frame %p -> %p", frame, copy);
568 gst_base_parse_frame_free (GstBaseParseFrame * frame)
570 GST_TRACE ("freeing frame %p", frame);
573 gst_buffer_unref (frame->buffer);
574 frame->buffer = NULL;
577 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
578 g_slice_free (GstBaseParseFrame, frame);
580 memset (frame, 0, sizeof (*frame));
585 gst_base_parse_frame_get_type (void)
587 static volatile gsize frame_type = 0;
589 if (g_once_init_enter (&frame_type)) {
592 _type = g_boxed_type_register_static ("GstBaseParseFrame",
593 (GBoxedCopyFunc) gst_base_parse_frame_copy,
594 (GBoxedFreeFunc) gst_base_parse_frame_free);
595 g_once_init_leave (&frame_type, _type);
597 return (GType) frame_type;
601 * gst_base_parse_frame_init:
602 * @frame: #GstBaseParseFrame.
604 * Sets a #GstBaseParseFrame to initial state. Currently this means
605 * all public fields are zero-ed and a private flag is set to make
606 * sure gst_base_parse_frame_free() only frees the contents but not
607 * the actual frame. Use this function to initialise a #GstBaseParseFrame
608 * allocated on the stack.
613 gst_base_parse_frame_init (GstBaseParseFrame * frame)
615 memset (frame, 0, sizeof (GstBaseParseFrame));
616 frame->_private_flags = GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
617 GST_TRACE ("inited frame %p", frame);
621 * gst_base_parse_frame_new:
622 * @buffer: (transfer none): a #GstBuffer
624 * @overhead: number of bytes in this frame which should be counted as
625 * metadata overhead, ie. not used to calculate the average bitrate.
626 * Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
628 * Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
629 * elements written in C should usually allocate the frame on the stack and
630 * then use gst_base_parse_frame_init() to initialise it.
632 * Returns: a newly-allocated #GstBaseParseFrame. Free with
633 * gst_base_parse_frame_free() when no longer needed, unless you gave
634 * away ownership to gst_base_parse_push_frame().
639 gst_base_parse_frame_new (GstBuffer * buffer, GstBaseParseFrameFlags flags,
642 GstBaseParseFrame *frame;
644 frame = g_slice_new0 (GstBaseParseFrame);
645 frame->buffer = gst_buffer_ref (buffer);
647 GST_TRACE ("created frame %p", frame);
652 gst_base_parse_frame_update (GstBaseParse * parse, GstBaseParseFrame * frame,
655 gst_buffer_replace (&frame->buffer, buf);
659 /* set flags one by one for clarity */
660 if (G_UNLIKELY (parse->priv->drain))
661 parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;
663 /* losing sync is pretty much a discont (and vice versa), no ? */
664 if (G_UNLIKELY (parse->priv->discont))
665 parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
669 gst_base_parse_reset (GstBaseParse * parse)
671 GST_OBJECT_LOCK (parse);
672 gst_segment_init (&parse->segment, GST_FORMAT_TIME);
673 parse->priv->duration = -1;
674 parse->priv->min_frame_size = 1;
675 parse->priv->discont = TRUE;
676 parse->priv->flushing = FALSE;
677 parse->priv->offset = 0;
678 parse->priv->sync_offset = 0;
679 parse->priv->update_interval = -1;
680 parse->priv->fps_num = parse->priv->fps_den = 0;
681 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
682 parse->priv->lead_in = parse->priv->lead_out = 0;
683 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
684 parse->priv->bitrate = 0;
685 parse->priv->framecount = 0;
686 parse->priv->bytecount = 0;
687 parse->priv->acc_duration = 0;
688 parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
689 parse->priv->first_frame_offset = -1;
690 parse->priv->estimated_duration = -1;
691 parse->priv->next_ts = 0;
692 parse->priv->syncable = TRUE;
693 parse->priv->passthrough = FALSE;
694 parse->priv->has_timing_info = FALSE;
695 parse->priv->post_min_bitrate = TRUE;
696 parse->priv->post_avg_bitrate = TRUE;
697 parse->priv->post_max_bitrate = TRUE;
698 parse->priv->min_bitrate = G_MAXUINT;
699 parse->priv->max_bitrate = 0;
700 parse->priv->avg_bitrate = 0;
701 parse->priv->posted_avg_bitrate = 0;
703 parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
704 parse->priv->index_last_offset = -1;
705 parse->priv->index_last_valid = TRUE;
706 parse->priv->upstream_seekable = FALSE;
707 parse->priv->upstream_size = 0;
708 parse->priv->upstream_has_duration = FALSE;
709 parse->priv->idx_interval = 0;
710 parse->priv->exact_position = TRUE;
711 parse->priv->seen_keyframe = FALSE;
713 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
714 parse->priv->last_offset = 0;
716 if (parse->priv->pending_segment) {
717 gst_event_unref (parse->priv->pending_segment);
718 parse->priv->pending_segment = NULL;
721 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
723 g_list_free (parse->priv->pending_events);
724 parse->priv->pending_events = NULL;
726 if (parse->priv->cache) {
727 gst_buffer_unref (parse->priv->cache);
728 parse->priv->cache = NULL;
731 g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
732 g_slist_free (parse->priv->pending_seeks);
733 parse->priv->pending_seeks = NULL;
735 /* we know it is not alloc'ed, but maybe other stuff to free, some day ... */
736 parse->priv->frame._private_flags |=
737 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
738 gst_base_parse_frame_free (&parse->priv->frame);
739 GST_OBJECT_UNLOCK (parse);
742 /* gst_base_parse_check_frame:
743 * @parse: #GstBaseParse.
744 * @buffer: GstBuffer.
745 * @framesize: This will be set to tell the found frame size in bytes.
746 * @skipsize: Output parameter that tells how much data needs to be skipped
747 * in order to find the following frame header.
749 * Default callback for check_valid_frame.
751 * Returns: Always TRUE.
754 gst_base_parse_check_frame (GstBaseParse * parse,
755 GstBaseParseFrame * frame, guint * framesize, gint * skipsize)
757 *framesize = gst_buffer_get_size (frame->buffer);
763 /* gst_base_parse_parse_frame:
764 * @parse: #GstBaseParse.
765 * @buffer: #GstBuffer.
767 * Default callback for parse_frame.
770 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
772 GstBuffer *buffer = frame->buffer;
774 if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
775 GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
776 GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
778 if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
779 GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
780 GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
785 /* gst_base_parse_convert:
786 * @parse: #GstBaseParse.
787 * @src_format: #GstFormat describing the source format.
788 * @src_value: Source value to be converted.
789 * @dest_format: #GstFormat defining the converted format.
790 * @dest_value: Pointer where the conversion result will be put.
792 * Converts using configured "convert" vmethod in #GstBaseParse class.
794 * Returns: TRUE if conversion was successful.
797 gst_base_parse_convert (GstBaseParse * parse,
798 GstFormat src_format,
799 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
801 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
804 g_return_val_if_fail (dest_value != NULL, FALSE);
809 ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
811 #ifndef GST_DISABLE_GST_DEBUG
814 if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
815 GST_LOG_OBJECT (parse,
816 "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
817 GST_TIME_ARGS (src_value), *dest_value);
818 } else if (dest_format == GST_FORMAT_TIME &&
819 src_format == GST_FORMAT_BYTES) {
820 GST_LOG_OBJECT (parse,
821 "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
822 src_value, GST_TIME_ARGS (*dest_value));
824 GST_LOG_OBJECT (parse,
825 "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
826 GST_STR_NULL (gst_format_get_name (src_format)),
827 GST_STR_NULL (gst_format_get_name (dest_format)),
828 src_value, *dest_value);
831 GST_DEBUG_OBJECT (parse, "conversion failed");
839 /* gst_base_parse_sink_event:
840 * @pad: #GstPad that received the event.
841 * @event: #GstEvent to be handled.
843 * Handler for sink pad events.
845 * Returns: TRUE if the event was handled.
848 gst_base_parse_sink_event (GstPad * pad, GstEvent * event)
851 GstBaseParseClass *bclass;
852 gboolean handled = FALSE;
855 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
856 bclass = GST_BASE_PARSE_GET_CLASS (parse);
858 GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
859 GST_EVENT_TYPE_NAME (event));
861 /* Cache all events except EOS, SEGMENT and FLUSH_STOP if we have a
863 if (parse->priv->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
864 && GST_EVENT_TYPE (event) != GST_EVENT_SEGMENT
865 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
866 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP) {
868 if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
869 /* See if any bitrate tags were posted */
870 gst_base_parse_handle_tag (parse, event);
872 parse->priv->pending_events =
873 g_list_append (parse->priv->pending_events, event);
877 if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
878 parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
879 /* We've not posted bitrate tags yet - do so now */
880 gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
883 handled = bclass->event (parse, event);
886 handled = gst_base_parse_sink_eventfunc (parse, event);
889 ret = gst_pad_event_default (pad, event);
892 gst_object_unref (parse);
893 GST_DEBUG_OBJECT (parse, "event handled");
898 /* gst_base_parse_sink_eventfunc:
899 * @parse: #GstBaseParse.
900 * @event: #GstEvent to be handled.
902 * Element-level event handler function.
904 * The event will be unreffed only if it has been handled and this
905 * function returns %TRUE
907 * Returns: %TRUE if the event was handled and not need forwarding.
910 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
912 gboolean handled = FALSE;
915 switch (GST_EVENT_TYPE (event)) {
916 case GST_EVENT_SEGMENT:
918 const GstSegment *in_segment;
919 GstSegment out_segment;
920 gint64 offset = 0, next_ts;
923 gdouble rate, applied_rate;
925 gint64 start, stop, pos, next_ts;
929 gst_event_parse_segment (event, &in_segment);
930 gst_segment_init (&out_segment, GST_FORMAT_TIME);
932 GST_DEBUG_OBJECT (parse, "segment %" GST_SEGMENT_FORMAT, in_segment);
934 if (in_segment->format == GST_FORMAT_BYTES) {
935 GstBaseParseSeek *seek = NULL;
938 /* stop time is allowed to be open-ended, but not start & pos */
939 offset = in_segment->time;
941 GST_OBJECT_LOCK (parse);
942 for (node = parse->priv->pending_seeks; node; node = node->next) {
943 GstBaseParseSeek *tmp = node->data;
945 if (tmp->offset == offset) {
950 parse->priv->pending_seeks =
951 g_slist_remove (parse->priv->pending_seeks, seek);
952 GST_OBJECT_UNLOCK (parse);
955 GST_DEBUG_OBJECT (parse,
956 "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
957 seek->accurate ? " accurate" : "", &seek->segment);
959 out_segment.start = seek->segment.start;
960 out_segment.stop = seek->segment.stop;
961 out_segment.time = seek->segment.start;
963 next_ts = seek->start_ts;
964 parse->priv->exact_position = seek->accurate;
967 /* best attempt convert */
968 /* as these are only estimates, stop is kept open-ended to avoid
969 * premature cutting */
970 gst_base_parse_convert (parse, GST_FORMAT_BYTES, in_segment->start,
971 GST_FORMAT_TIME, (gint64 *) & next_ts);
973 out_segment.start = next_ts;
974 out_segment.stop = GST_CLOCK_TIME_NONE;
975 out_segment.time = next_ts;
977 parse->priv->exact_position = (in_segment->start == 0);
980 gst_event_unref (event);
982 event = gst_event_new_segment (&out_segment);
984 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. "
985 GST_SEGMENT_FORMAT, in_segment);
987 } else if (in_segment->format != GST_FORMAT_TIME) {
988 /* Unknown incoming segment format. Output a default open-ended
990 gst_event_unref (event);
992 out_segment.start = 0;
993 out_segment.stop = GST_CLOCK_TIME_NONE;;
994 out_segment.time = 0;;
996 event = gst_event_new_segment (&out_segment);
1000 /* not considered BYTE seekable if it is talking to us in TIME,
1001 * whatever else it might claim */
1002 parse->priv->upstream_seekable = FALSE;
1003 next_ts = in_segment->start;
1006 memcpy (&parse->segment, &out_segment, sizeof (GstSegment));
1009 gst_segment_set_newsegment (&parse->segment, update, rate,
1010 applied_rate, format, start, stop, start);
1013 /* save the segment for later, right before we push a new buffer so that
1014 * the caps are fixed and the next linked element can receive
1016 eventp = &parse->priv->pending_segment;
1017 gst_event_replace (eventp, event);
1018 gst_event_unref (event);
1021 /* but finish the current segment */
1022 GST_DEBUG_OBJECT (parse, "draining current segment");
1023 if (in_segment->rate > 0.0)
1024 gst_base_parse_drain (parse);
1026 gst_base_parse_process_fragment (parse, FALSE);
1027 gst_adapter_clear (parse->priv->adapter);
1029 parse->priv->offset = offset;
1030 parse->priv->sync_offset = offset;
1031 parse->priv->next_ts = next_ts;
1032 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1033 parse->priv->discont = TRUE;
1034 parse->priv->seen_keyframe = FALSE;
1038 case GST_EVENT_FLUSH_START:
1039 parse->priv->flushing = TRUE;
1040 handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
1042 gst_event_unref (event);
1043 /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
1044 GST_PAD_STREAM_LOCK (parse->srcpad);
1045 GST_PAD_STREAM_UNLOCK (parse->srcpad);
1049 case GST_EVENT_FLUSH_STOP:
1050 gst_adapter_clear (parse->priv->adapter);
1051 gst_base_parse_clear_queues (parse);
1052 parse->priv->flushing = FALSE;
1053 parse->priv->discont = TRUE;
1054 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1055 parse->priv->frame._private_flags |=
1056 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
1057 gst_base_parse_frame_free (&parse->priv->frame);
1061 if (parse->segment.rate > 0.0)
1062 gst_base_parse_drain (parse);
1064 gst_base_parse_process_fragment (parse, FALSE);
1066 /* If we STILL have zero frames processed, fire an error */
1067 if (parse->priv->framecount == 0) {
1068 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1069 ("No valid frames found before end of stream"), (NULL));
1071 /* newsegment before eos */
1072 if (parse->priv->pending_segment) {
1073 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1074 parse->priv->pending_segment = NULL;
1086 /* gst_base_parse_src_event:
1087 * @pad: #GstPad that received the event.
1088 * @event: #GstEvent that was received.
1090 * Handler for source pad events.
1092 * Returns: TRUE if the event was handled.
1095 gst_base_parse_src_event (GstPad * pad, GstEvent * event)
1097 GstBaseParse *parse;
1098 GstBaseParseClass *bclass;
1099 gboolean handled = FALSE;
1100 gboolean ret = TRUE;
1102 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
1103 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1105 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1106 GST_EVENT_TYPE_NAME (event));
1108 if (bclass->src_event)
1109 handled = bclass->src_event (parse, event);
1112 ret = gst_pad_event_default (pad, event);
1114 gst_object_unref (parse);
1119 gst_base_parse_is_seekable (GstBaseParse * parse)
1121 /* FIXME: could do more here, e.g. check index or just send data from 0
1122 * in pull mode and let decoder/sink clip */
1123 return parse->priv->syncable;
1126 /* gst_base_parse_src_eventfunc:
1127 * @parse: #GstBaseParse.
1128 * @event: #GstEvent that was received.
1130 * Default srcpad event handler.
1132 * Returns: TRUE if the event was handled and can be dropped.
1135 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1137 gboolean handled = FALSE;
1139 switch (GST_EVENT_TYPE (event)) {
1140 case GST_EVENT_SEEK:
1142 if (gst_base_parse_is_seekable (parse)) {
1143 handled = gst_base_parse_handle_seek (parse, event);
1155 * gst_base_parse_convert_default:
1156 * @parse: #GstBaseParse.
1157 * @src_format: #GstFormat describing the source format.
1158 * @src_value: Source value to be converted.
1159 * @dest_format: #GstFormat defining the converted format.
1160 * @dest_value: Pointer where the conversion result will be put.
1162 * Default implementation of "convert" vmethod in #GstBaseParse class.
1164 * Returns: TRUE if conversion was successful.
1169 gst_base_parse_convert_default (GstBaseParse * parse,
1170 GstFormat src_format,
1171 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1173 gboolean ret = FALSE;
1174 guint64 bytes, duration;
1176 if (G_UNLIKELY (src_format == dest_format)) {
1177 *dest_value = src_value;
1181 if (G_UNLIKELY (src_value == -1)) {
1186 if (G_UNLIKELY (src_value == 0)) {
1191 /* need at least some frames */
1192 if (!parse->priv->framecount)
1195 duration = parse->priv->acc_duration / GST_MSECOND;
1196 bytes = parse->priv->bytecount;
1198 if (G_UNLIKELY (!duration || !bytes))
1201 if (src_format == GST_FORMAT_BYTES) {
1202 if (dest_format == GST_FORMAT_TIME) {
1203 /* BYTES -> TIME conversion */
1204 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1205 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1206 *dest_value *= GST_MSECOND;
1207 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1208 *dest_value / GST_MSECOND);
1211 } else if (src_format == GST_FORMAT_TIME) {
1212 if (dest_format == GST_FORMAT_BYTES) {
1213 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1214 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1216 GST_DEBUG_OBJECT (parse,
1217 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1218 src_value / GST_MSECOND, *dest_value);
1221 } else if (src_format == GST_FORMAT_DEFAULT) {
1222 /* DEFAULT == frame-based */
1223 if (dest_format == GST_FORMAT_TIME) {
1224 if (parse->priv->fps_den) {
1225 *dest_value = gst_util_uint64_scale (src_value,
1226 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1229 } else if (dest_format == GST_FORMAT_BYTES) {
1237 gst_base_parse_update_duration (GstBaseParse * baseparse)
1240 GstBaseParse *parse;
1242 parse = GST_BASE_PARSE (baseparse);
1244 peer = gst_pad_get_peer (parse->sinkpad);
1246 GstFormat pformat = GST_FORMAT_BYTES;
1247 gboolean qres = FALSE;
1248 gint64 ptot, dest_value;
1250 qres = gst_pad_query_duration (peer, &pformat, &ptot);
1251 gst_object_unref (GST_OBJECT (peer));
1253 if (gst_base_parse_convert (parse, pformat, ptot,
1254 GST_FORMAT_TIME, &dest_value)) {
1255 parse->priv->estimated_duration = dest_value;
1256 GST_LOG_OBJECT (parse,
1257 "updated estimated duration to %" GST_TIME_FORMAT,
1258 GST_TIME_ARGS (dest_value));
1265 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1266 gboolean post_avg, gboolean post_max)
1268 GstTagList *taglist = NULL;
1270 if (post_min && parse->priv->post_min_bitrate) {
1271 taglist = gst_tag_list_new ();
1273 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1274 GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1277 if (post_avg && parse->priv->post_avg_bitrate) {
1278 if (taglist == NULL)
1279 taglist = gst_tag_list_new ();
1281 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1282 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1283 parse->priv->avg_bitrate, NULL);
1286 if (post_max && parse->priv->post_max_bitrate) {
1287 if (taglist == NULL)
1288 taglist = gst_tag_list_new ();
1290 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1291 GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1294 GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1295 parse->priv->min_bitrate, parse->priv->avg_bitrate,
1296 parse->priv->max_bitrate);
1298 if (taglist != NULL) {
1299 gst_element_found_tags_for_pad (GST_ELEMENT_CAST (parse), parse->srcpad,
1304 /* gst_base_parse_update_bitrates:
1305 * @parse: #GstBaseParse.
1306 * @buffer: Current frame as a #GstBuffer
1308 * Keeps track of the minimum and maximum bitrates, and also maintains a
1309 * running average bitrate of the stream so far.
1312 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1314 /* Only update the tag on a 10 kbps delta */
1315 static const gint update_threshold = 10000;
1317 guint64 data_len, frame_dur;
1318 gint overhead, frame_bitrate, old_avg_bitrate;
1319 gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1320 GstBuffer *buffer = frame->buffer;
1322 overhead = frame->overhead;
1326 data_len = gst_buffer_get_size (buffer) - overhead;
1327 parse->priv->data_bytecount += data_len;
1329 /* duration should be valid by now,
1330 * either set by subclass or maybe based on fps settings */
1331 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1332 /* Calculate duration of a frame from buffer properties */
1333 frame_dur = GST_BUFFER_DURATION (buffer);
1334 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1335 parse->priv->acc_duration;
1338 /* No way to figure out frame duration (is this even possible?) */
1342 /* override if subclass provided bitrate, e.g. metadata based */
1343 if (parse->priv->bitrate) {
1344 parse->priv->avg_bitrate = parse->priv->bitrate;
1345 /* spread this (confirmed) info ASAP */
1346 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1347 gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1351 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1355 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1356 parse->priv->avg_bitrate);
1358 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1360 } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1361 /* always post all at threshold time */
1362 update_min = update_max = update_avg = TRUE;
1365 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1366 if (frame_bitrate < parse->priv->min_bitrate) {
1367 parse->priv->min_bitrate = frame_bitrate;
1371 if (frame_bitrate > parse->priv->max_bitrate) {
1372 parse->priv->max_bitrate = frame_bitrate;
1376 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1377 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1378 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1383 if ((update_min || update_avg || update_max))
1384 gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1386 /* If average bitrate changes that much and no valid (time) duration provided,
1387 * then post a new duration message so applications can update their cached
1389 if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1390 GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1391 gst_element_post_message (GST_ELEMENT (parse),
1392 gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1399 * gst_base_parse_add_index_entry:
1400 * @parse: #GstBaseParse.
1401 * @offset: offset of entry
1402 * @ts: timestamp associated with offset
1403 * @key: whether entry refers to keyframe
1404 * @force: add entry disregarding sanity checks
1406 * Adds an entry to the index associating @offset to @ts. It is recommended
1407 * to only add keyframe entries. @force allows to bypass checks, such as
1408 * whether the stream is (upstream) seekable, another entry is already "close"
1409 * to the new entry, etc.
1411 * Returns: #gboolean indicating whether entry was added
1416 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1417 GstClockTime ts, gboolean key, gboolean force)
1419 gboolean ret = FALSE;
1420 GstIndexAssociation associations[2];
1422 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1423 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1425 if (G_LIKELY (!force)) {
1427 if (!parse->priv->upstream_seekable) {
1428 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1432 /* FIXME need better helper data structure that handles these issues
1433 * related to ongoing collecting of index entries */
1434 if (parse->priv->index_last_offset >= (gint64) offset) {
1435 GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1436 "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1440 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1441 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1442 parse->priv->idx_interval) {
1443 GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1444 GST_TIME_ARGS (parse->priv->index_last_ts));
1448 /* if last is not really the last one */
1449 if (!parse->priv->index_last_valid) {
1450 GstClockTime prev_ts;
1452 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1453 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1454 GST_DEBUG_OBJECT (parse,
1455 "entry too close to existing entry %" GST_TIME_FORMAT,
1456 GST_TIME_ARGS (prev_ts));
1457 parse->priv->index_last_offset = offset;
1458 parse->priv->index_last_ts = ts;
1464 associations[0].format = GST_FORMAT_TIME;
1465 associations[0].value = ts;
1466 associations[1].format = GST_FORMAT_BYTES;
1467 associations[1].value = offset;
1469 /* index might change on-the-fly, although that would be nutty app ... */
1470 g_static_mutex_lock (&parse->priv->index_lock);
1471 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1472 (key) ? GST_ASSOCIATION_FLAG_KEY_UNIT : GST_ASSOCIATION_FLAG_DELTA_UNIT,
1473 2, (const GstIndexAssociation *) &associations);
1474 g_static_mutex_unlock (&parse->priv->index_lock);
1477 parse->priv->index_last_offset = offset;
1478 parse->priv->index_last_ts = ts;
1487 /* check for seekable upstream, above and beyond a mere query */
1489 gst_base_parse_check_seekability (GstBaseParse * parse)
1492 gboolean seekable = FALSE;
1493 gint64 start = -1, stop = -1;
1494 guint idx_interval = 0;
1496 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1497 if (!gst_pad_peer_query (parse->sinkpad, query)) {
1498 GST_DEBUG_OBJECT (parse, "seeking query failed");
1502 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1504 /* try harder to query upstream size if we didn't get it the first time */
1505 if (seekable && stop == -1) {
1506 GstFormat fmt = GST_FORMAT_BYTES;
1508 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1509 gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop);
1512 /* if upstream doesn't know the size, it's likely that it's not seekable in
1513 * practice even if it technically may be seekable */
1514 if (seekable && (start != 0 || stop <= start)) {
1515 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1519 /* let's not put every single frame into our index */
1521 if (stop < 10 * 1024 * 1024)
1523 else if (stop < 100 * 1024 * 1024)
1526 idx_interval = 1000;
1530 gst_query_unref (query);
1532 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1533 G_GUINT64_FORMAT ")", seekable, start, stop);
1534 parse->priv->upstream_seekable = seekable;
1535 parse->priv->upstream_size = seekable ? stop : 0;
1537 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1538 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1541 /* some misc checks on upstream */
1543 gst_base_parse_check_upstream (GstBaseParse * parse)
1545 GstFormat fmt = GST_FORMAT_TIME;
1548 if (gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop))
1549 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1550 /* upstream has one, accept it also, and no further updates */
1551 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1552 parse->priv->upstream_has_duration = TRUE;
1555 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1556 parse->priv->upstream_has_duration);
1559 /* checks src caps to determine if dealing with audio or video */
1560 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1562 gst_base_parse_check_media (GstBaseParse * parse)
1567 caps = gst_pad_get_current_caps (parse->srcpad);
1568 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1569 parse->priv->is_video =
1570 g_str_has_prefix (gst_structure_get_name (s), "video");
1572 /* historical default */
1573 parse->priv->is_video = FALSE;
1576 gst_caps_unref (caps);
1578 GST_DEBUG_OBJECT (parse, "media is video == %d", parse->priv->is_video);
1581 /* takes ownership of frame */
1583 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1585 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1586 /* frame allocated on the heap, we can just take ownership */
1587 g_queue_push_tail (&parse->priv->queued_frames, frame);
1588 GST_TRACE ("queued frame %p", frame);
1590 GstBaseParseFrame *copy;
1592 /* probably allocated on the stack, must make a proper copy */
1593 copy = gst_base_parse_frame_copy (frame);
1594 g_queue_push_tail (&parse->priv->queued_frames, copy);
1595 GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1596 gst_base_parse_frame_free (frame);
1600 /* gst_base_parse_handle_and_push_buffer:
1601 * @parse: #GstBaseParse.
1602 * @klass: #GstBaseParseClass.
1603 * @frame: (transfer full): a #GstBaseParseFrame
1605 * Parses the frame from given buffer and pushes it forward. Also performs
1606 * timestamp handling and checks the segment limits.
1608 * This is called with srcpad STREAM_LOCK held.
1610 * Returns: #GstFlowReturn
1612 static GstFlowReturn
1613 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1614 GstBaseParseClass * klass, GstBaseParseFrame * frame)
1620 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1622 buffer = frame->buffer;
1624 if (parse->priv->discont) {
1625 GST_DEBUG_OBJECT (parse, "marking DISCONT");
1626 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1627 parse->priv->discont = FALSE;
1630 /* some one-time start-up */
1631 if (G_UNLIKELY (!parse->priv->framecount)) {
1632 gst_base_parse_check_seekability (parse);
1633 gst_base_parse_check_upstream (parse);
1636 GST_LOG_OBJECT (parse,
1637 "parsing frame at offset %" G_GUINT64_FORMAT
1638 " (%#" G_GINT64_MODIFIER "x) of size %d",
1639 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1640 gst_buffer_get_size (buffer));
1642 /* use default handler to provide initial (upstream) metadata */
1643 gst_base_parse_parse_frame (parse, frame);
1645 /* store offset as it might get overwritten */
1646 offset = GST_BUFFER_OFFSET (buffer);
1647 ret = klass->parse_frame (parse, frame);
1649 buffer = frame->buffer;
1650 /* subclass must play nice */
1651 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1653 /* check if subclass/format can provide ts.
1654 * If so, that allows and enables extra seek and duration determining options */
1655 if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
1656 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && parse->priv->has_timing_info
1657 && parse->priv->pad_mode == GST_ACTIVATE_PULL) {
1658 parse->priv->first_frame_offset = offset;
1659 parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1660 GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1661 " for first frame at offset %" G_GINT64_FORMAT,
1662 GST_TIME_ARGS (parse->priv->first_frame_ts),
1663 parse->priv->first_frame_offset);
1664 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1666 GstClockTime last_ts = G_MAXINT64;
1668 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1669 gst_base_parse_locate_time (parse, &last_ts, &off);
1670 if (GST_CLOCK_TIME_IS_VALID (last_ts))
1671 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1674 /* disable further checks */
1675 parse->priv->first_frame_offset = 0;
1679 /* again use default handler to add missing metadata;
1680 * we may have new information on frame properties */
1681 gst_base_parse_parse_frame (parse, frame);
1682 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1683 GST_BUFFER_DURATION_IS_VALID (buffer)) {
1684 parse->priv->next_ts =
1685 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1687 /* we lost track, do not produce bogus time next time around
1688 * (probably means parser subclass has given up on parsing as well) */
1689 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1690 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1693 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1694 GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1695 gst_base_parse_add_index_entry (parse, offset,
1696 GST_BUFFER_TIMESTAMP (buffer),
1697 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1699 /* First buffers are dropped, this means that the subclass needs more
1700 * frames to decide on the format and queues them internally */
1701 /* convert internal flow to OK and mark discont for the next buffer. */
1702 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1703 gst_base_parse_frame_free (frame);
1705 } else if (ret == GST_BASE_PARSE_FLOW_QUEUED) {
1706 gst_base_parse_queue_frame (parse, frame);
1708 } else if (ret != GST_FLOW_OK) {
1712 /* All OK, push queued frames if there are any */
1713 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
1714 GstBaseParseFrame *queued_frame;
1716 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
1717 gst_base_parse_push_frame (parse, queued_frame);
1718 gst_base_parse_frame_free (queued_frame);
1722 return gst_base_parse_push_frame (parse, frame);
1726 * gst_base_parse_push_frame:
1727 * @parse: #GstBaseParse.
1728 * @frame: (transfer full): a #GstBaseParseFrame
1730 * Pushes the frame downstream, sends any pending events and
1731 * does some timestamp and segment handling. Takes ownership
1732 * of @frame and will clear it (if it was initialised with
1733 * gst_base_parse_frame_init()) or free it.
1735 * This must be called with sinkpad STREAM_LOCK held.
1737 * Returns: #GstFlowReturn
1742 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1744 GstFlowReturn ret = GST_FLOW_OK;
1745 GstClockTime last_start = GST_CLOCK_TIME_NONE;
1746 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1747 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1751 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1752 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
1754 GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
1756 buffer = frame->buffer;
1758 GST_LOG_OBJECT (parse,
1759 "processing buffer of size %d with ts %" GST_TIME_FORMAT
1760 ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buffer),
1761 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1762 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1765 size = gst_buffer_get_size (buffer);
1766 parse->priv->bytecount += size;
1767 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1768 parse->priv->framecount++;
1769 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1770 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1773 /* 0 means disabled */
1774 if (parse->priv->update_interval < 0)
1775 parse->priv->update_interval = 50;
1776 else if (parse->priv->update_interval > 0 &&
1777 (parse->priv->framecount % parse->priv->update_interval) == 0)
1778 gst_base_parse_update_duration (parse);
1780 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1781 last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1782 if (last_start != GST_CLOCK_TIME_NONE
1783 && GST_BUFFER_DURATION_IS_VALID (buffer))
1784 last_stop = last_start + GST_BUFFER_DURATION (buffer);
1786 /* should have caps by now */
1787 g_return_val_if_fail (gst_pad_has_current_caps (parse->srcpad),
1790 /* segment adjustment magic; only if we are running the whole show */
1791 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1792 (parse->priv->pad_mode == GST_ACTIVATE_PULL ||
1793 parse->priv->upstream_seekable)) {
1794 /* segment times are typically estimates,
1795 * actual frame data might lead subclass to different timestamps,
1796 * so override segment start from what is supplied there */
1797 if (G_UNLIKELY (parse->priv->pending_segment && !parse->priv->exact_position
1798 && GST_CLOCK_TIME_IS_VALID (last_start))) {
1799 gst_event_unref (parse->priv->pending_segment);
1800 parse->segment.start =
1801 MIN ((guint64) last_start, (guint64) parse->segment.stop);
1803 GST_DEBUG_OBJECT (parse,
1804 "adjusting pending segment start to %" GST_TIME_FORMAT,
1805 GST_TIME_ARGS (parse->segment.start));
1807 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
1809 /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1810 if (GST_CLOCK_TIME_IS_VALID (parse->segment.position) &&
1811 GST_CLOCK_TIME_IS_VALID (last_start)) {
1812 GstClockTimeDiff diff;
1814 /* only send newsegments with increasing start times,
1815 * otherwise if these go back and forth downstream (sinks) increase
1816 * accumulated time and running_time */
1817 diff = GST_CLOCK_DIFF (parse->segment.position, last_start);
1818 if (G_UNLIKELY (diff > 2 * GST_SECOND
1819 && last_start > parse->segment.start
1820 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
1821 || last_start < parse->segment.stop))) {
1823 GST_DEBUG_OBJECT (parse,
1824 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
1825 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1826 "Sending updated NEWSEGMENT events", diff,
1827 GST_TIME_ARGS (parse->segment.position),
1828 GST_TIME_ARGS (last_start));
1830 if (G_UNLIKELY (parse->priv->pending_segment)) {
1831 gst_event_unref (parse->priv->pending_segment);
1832 parse->segment.start = last_start;
1833 parse->segment.time = last_start;
1834 parse->priv->pending_segment =
1835 gst_event_new_segment (&parse->segment);
1837 /* skip gap FIXME */
1838 gst_pad_push_event (parse->srcpad,
1839 gst_event_new_segment (&parse->segment));
1841 parse->segment.position = last_start;
1846 /* and should then also be linked downstream, so safe to send some events */
1847 if (G_UNLIKELY (parse->priv->close_segment)) {
1848 /* only set up by loop */
1849 GST_DEBUG_OBJECT (parse, "loop sending close segment");
1850 gst_pad_push_event (parse->srcpad, parse->priv->close_segment);
1851 parse->priv->close_segment = NULL;
1853 if (G_UNLIKELY (parse->priv->pending_segment)) {
1854 GST_DEBUG_OBJECT (parse, "%s push pending segment",
1855 parse->priv->pad_mode == GST_ACTIVATE_PULL ? "loop" : "chain");
1856 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1857 parse->priv->pending_segment = NULL;
1859 /* have caps; check identity */
1860 gst_base_parse_check_media (parse);
1863 /* update bitrates and optionally post corresponding tags
1864 * (following newsegment) */
1865 gst_base_parse_update_bitrates (parse, frame);
1867 if (G_UNLIKELY (parse->priv->pending_events)) {
1870 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1871 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1873 g_list_free (parse->priv->pending_events);
1874 parse->priv->pending_events = NULL;
1877 if (klass->pre_push_frame) {
1878 ret = klass->pre_push_frame (parse, frame);
1880 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
1883 /* take final ownership of frame buffer */
1884 buffer = frame->buffer;
1885 frame->buffer = NULL;
1887 /* subclass must play nice */
1888 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1890 parse->priv->seen_keyframe |= parse->priv->is_video &&
1891 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1893 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
1894 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1895 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
1896 GST_BUFFER_TIMESTAMP (buffer) >
1897 parse->segment.stop + parse->priv->lead_out_ts) {
1898 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
1899 ret = GST_FLOW_UNEXPECTED;
1900 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1901 GST_BUFFER_DURATION_IS_VALID (buffer) &&
1902 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
1903 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
1904 parse->priv->lead_in_ts < parse->segment.start) {
1905 if (parse->priv->seen_keyframe) {
1906 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
1909 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
1910 ret = GST_BASE_PARSE_FLOW_DROPPED;
1917 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1918 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) dropped", size);
1919 gst_buffer_unref (buffer);
1921 } else if (ret == GST_FLOW_OK) {
1922 if (parse->segment.rate > 0.0) {
1923 ret = gst_pad_push (parse->srcpad, buffer);
1924 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) pushed: %s",
1925 size, gst_flow_get_name (ret));
1927 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) queued for now",
1929 parse->priv->buffers_queued =
1930 g_slist_prepend (parse->priv->buffers_queued, buffer);
1934 gst_buffer_unref (buffer);
1935 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s",
1936 size, gst_flow_get_name (ret));
1937 /* if we are not sufficiently in control, let upstream decide on EOS */
1938 if (ret == GST_FLOW_UNEXPECTED &&
1939 (parse->priv->passthrough ||
1940 (parse->priv->pad_mode == GST_ACTIVATE_PUSH &&
1941 !parse->priv->upstream_seekable)))
1945 /* Update current running segment position */
1946 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
1947 parse->segment.position < last_stop)
1948 parse->segment.position = last_stop;
1950 gst_base_parse_frame_free (frame);
1956 /* gst_base_parse_drain:
1958 * Drains the adapter until it is empty. It decreases the min_frame_size to
1959 * match the current adapter size and calls chain method until the adapter
1960 * is emptied or chain returns with error.
1963 gst_base_parse_drain (GstBaseParse * parse)
1967 GST_DEBUG_OBJECT (parse, "draining");
1968 parse->priv->drain = TRUE;
1971 avail = gst_adapter_available (parse->priv->adapter);
1975 if (gst_base_parse_chain (parse->sinkpad, NULL) != GST_FLOW_OK) {
1979 /* nothing changed, maybe due to truncated frame; break infinite loop */
1980 if (avail == gst_adapter_available (parse->priv->adapter)) {
1981 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
1982 gst_adapter_clear (parse->priv->adapter);
1986 parse->priv->drain = FALSE;
1989 /* gst_base_parse_send_buffers
1991 * Sends buffers collected in send_buffers downstream, and ensures that list
1992 * is empty at the end (errors or not).
1994 static GstFlowReturn
1995 gst_base_parse_send_buffers (GstBaseParse * parse)
1997 GSList *send = NULL;
1999 GstFlowReturn ret = GST_FLOW_OK;
2001 send = parse->priv->buffers_send;
2005 buf = GST_BUFFER_CAST (send->data);
2006 GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
2007 GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2008 ", offset %" G_GINT64_FORMAT, buf,
2009 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2010 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2012 /* iterate output queue an push downstream */
2013 ret = gst_pad_push (parse->srcpad, buf);
2014 send = g_slist_delete_link (send, send);
2016 /* clear any leftover if error */
2017 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2019 buf = GST_BUFFER_CAST (send->data);
2020 gst_buffer_unref (buf);
2021 send = g_slist_delete_link (send, send);
2026 parse->priv->buffers_send = send;
2031 /* gst_base_parse_process_fragment:
2033 * Processes a reverse playback (forward) fragment:
2034 * - append head of last fragment that was skipped to current fragment data
2035 * - drain the resulting current fragment data (i.e. repeated chain)
2036 * - add time/duration (if needed) to frames queued by chain
2037 * - push queued data
2039 static GstFlowReturn
2040 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
2043 GstFlowReturn ret = GST_FLOW_OK;
2044 gboolean seen_key = FALSE, seen_delta = FALSE;
2050 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2051 while (parse->priv->buffers_pending) {
2052 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2053 GST_LOG_OBJECT (parse, "adding pending buffer (size %d)",
2054 gst_buffer_get_size (buf));
2055 gst_adapter_push (parse->priv->adapter, buf);
2056 parse->priv->buffers_pending =
2057 g_slist_delete_link (parse->priv->buffers_pending,
2058 parse->priv->buffers_pending);
2061 /* invalidate so no fall-back timestamping is performed;
2062 * ok if taken from subclass or upstream */
2063 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
2064 /* prevent it hanging around stop all the time */
2065 parse->segment.position = GST_CLOCK_TIME_NONE;
2067 parse->priv->discont = TRUE;
2069 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2070 /* initial skipped data is added to buffers_pending */
2071 gst_base_parse_drain (parse);
2074 if (parse->priv->buffers_send) {
2075 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2076 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2079 /* add metadata (if needed to queued buffers */
2080 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2081 GST_TIME_ARGS (parse->priv->last_ts));
2082 while (parse->priv->buffers_queued) {
2083 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2085 /* no touching if upstream or parsing provided time */
2086 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2087 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2088 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2089 } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
2090 GST_BUFFER_DURATION_IS_VALID (buf)) {
2091 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
2092 parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
2094 parse->priv->last_ts = 0;
2095 GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
2096 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2097 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2099 /* no idea, very bad */
2100 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2103 parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
2105 /* reverse order for ascending sending */
2106 /* send downstream at keyframe not preceded by a keyframe
2107 * (e.g. that should identify start of collection of IDR nals) */
2108 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2110 ret = gst_base_parse_send_buffers (parse);
2111 /* if a problem, throw all to sending */
2112 if (ret != GST_FLOW_OK) {
2113 parse->priv->buffers_send =
2114 g_slist_reverse (parse->priv->buffers_queued);
2115 parse->priv->buffers_queued = NULL;
2124 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2126 parse->priv->buffers_send =
2127 g_slist_prepend (parse->priv->buffers_send, buf);
2128 parse->priv->buffers_queued =
2129 g_slist_delete_link (parse->priv->buffers_queued,
2130 parse->priv->buffers_queued);
2133 /* audio may have all marked as keyframe, so arrange to send here */
2135 ret = gst_base_parse_send_buffers (parse);
2137 /* any trailing unused no longer usable (ideally none) */
2138 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2139 GST_DEBUG_OBJECT (parse, "discarding %d trailing bytes",
2140 gst_adapter_available (parse->priv->adapter));
2141 gst_adapter_clear (parse->priv->adapter);
2147 /* small helper that checks whether we have been trying to resync too long */
2148 static inline GstFlowReturn
2149 gst_base_parse_check_sync (GstBaseParse * parse)
2151 if (G_UNLIKELY (parse->priv->discont &&
2152 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2153 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2154 ("Failed to parse stream"), (NULL));
2155 return GST_FLOW_ERROR;
2161 static GstFlowReturn
2162 gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
2164 GstBaseParseClass *bclass;
2165 GstBaseParse *parse;
2166 GstFlowReturn ret = GST_FLOW_OK;
2167 GstBuffer *outbuf = NULL;
2168 GstBuffer *tmpbuf = NULL;
2172 guint old_min_size = 0, min_size, av;
2173 GstClockTime timestamp;
2174 GstBaseParseFrame *frame;
2176 parse = GST_BASE_PARSE (GST_OBJECT_PARENT (pad));
2177 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2178 frame = &parse->priv->frame;
2180 if (G_LIKELY (buffer)) {
2181 GST_LOG_OBJECT (parse, "buffer size: %d, offset = %" G_GINT64_FORMAT,
2182 gst_buffer_get_size (buffer), GST_BUFFER_OFFSET (buffer));
2183 if (G_UNLIKELY (parse->priv->passthrough)) {
2184 gst_base_parse_frame_init (frame);
2185 frame->buffer = gst_buffer_make_writable (buffer);
2186 return gst_base_parse_push_frame (parse, frame);
2188 /* upstream feeding us in reverse playback;
2189 * gather each fragment, then process it in single run */
2190 if (parse->segment.rate < 0.0) {
2191 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2192 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2193 ret = gst_base_parse_process_fragment (parse, FALSE);
2195 gst_adapter_push (parse->priv->adapter, buffer);
2198 gst_adapter_push (parse->priv->adapter, buffer);
2201 if (G_UNLIKELY (buffer &&
2202 GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2203 frame->_private_flags |= GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
2204 gst_base_parse_frame_free (frame);
2207 /* Parse and push as many frames as possible */
2208 /* Stop either when adapter is empty or we are flushing */
2209 while (!parse->priv->flushing) {
2212 /* maintain frame state for a single frame parsing round across _chain calls,
2213 * so only init when needed */
2214 if (!frame->_private_flags)
2215 gst_base_parse_frame_init (frame);
2217 tmpbuf = gst_buffer_new ();
2220 /* Synchronization loop */
2222 /* note: if subclass indicates MAX fsize,
2223 * this will not likely be available anyway ... */
2224 min_size = MAX (parse->priv->min_frame_size, fsize);
2225 av = gst_adapter_available (parse->priv->adapter);
2227 /* loop safety check */
2228 if (G_UNLIKELY (old_min_size >= min_size))
2230 old_min_size = min_size;
2232 if (G_UNLIKELY (parse->priv->drain)) {
2234 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2235 if (G_UNLIKELY (!min_size)) {
2236 gst_buffer_unref (tmpbuf);
2241 /* Collect at least min_frame_size bytes */
2242 if (av < min_size) {
2243 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
2245 gst_buffer_unref (tmpbuf);
2249 /* always pass all available data */
2250 data = gst_adapter_map (parse->priv->adapter, av);
2251 gst_buffer_take_memory (tmpbuf,
2252 gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
2253 (gpointer) data, NULL, av, 0, av));
2254 GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
2256 if (parse->priv->discont) {
2257 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2258 GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2262 gst_base_parse_frame_update (parse, frame, tmpbuf);
2263 res = bclass->check_valid_frame (parse, frame, &fsize, &skip);
2264 gst_adapter_unmap (parse->priv->adapter, 0);
2265 gst_buffer_replace (&frame->buffer, NULL);
2267 if (gst_adapter_available (parse->priv->adapter) < fsize) {
2268 GST_DEBUG_OBJECT (parse,
2269 "found valid frame but not enough data available (only %d bytes)",
2270 gst_adapter_available (parse->priv->adapter));
2271 gst_buffer_unref (tmpbuf);
2274 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2278 /* subclass didn't touch this value. By default we skip 1 byte */
2282 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2283 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2284 /* reverse playback, and no frames found yet, so we are skipping
2285 * the leading part of a fragment, which may form the tail of
2286 * fragment coming later, hopefully subclass skips efficiently ... */
2287 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2288 outbuf = gst_adapter_take_buffer (parse->priv->adapter, skip);
2289 outbuf = gst_buffer_make_writable (outbuf);
2290 GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
2291 parse->priv->buffers_pending =
2292 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2295 gst_adapter_flush (parse->priv->adapter, skip);
2297 parse->priv->offset += skip;
2298 if (!parse->priv->discont)
2299 parse->priv->sync_offset = parse->priv->offset;
2300 parse->priv->discont = TRUE;
2301 /* something changed least; nullify loop check */
2304 /* skip == 0 should imply subclass set min_size to need more data;
2305 * we check this shortly */
2306 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2307 gst_buffer_unref (tmpbuf);
2311 gst_buffer_unref (tmpbuf);
2315 /* Subclass found the sync, but still wants to skip some data */
2316 GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
2317 gst_adapter_flush (parse->priv->adapter, skip);
2318 parse->priv->offset += skip;
2321 /* Grab lock to prevent a race with FLUSH_START handler */
2322 GST_PAD_STREAM_LOCK (parse->srcpad);
2324 /* FLUSH_START event causes the "flushing" flag to be set. In this
2325 * case we can leave the frame pushing loop */
2326 if (parse->priv->flushing) {
2327 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2331 /* move along with upstream timestamp (if any),
2332 * but interpolate in between */
2333 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2334 if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2335 (parse->priv->prev_ts != timestamp)) {
2336 parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2339 /* FIXME: Would it be more efficient to make a subbuffer instead? */
2340 outbuf = gst_adapter_take_buffer (parse->priv->adapter, fsize);
2341 outbuf = gst_buffer_make_writable (outbuf);
2343 /* Subclass may want to know the data offset */
2344 GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2345 parse->priv->offset += fsize;
2346 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2347 GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
2349 frame->buffer = outbuf;
2350 ret = gst_base_parse_handle_and_push_frame (parse, bclass, frame);
2351 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2353 if (ret != GST_FLOW_OK) {
2354 GST_LOG_OBJECT (parse, "push returned %d", ret);
2360 GST_LOG_OBJECT (parse, "chain leaving");
2366 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2367 ("min_size evolution %d -> %d; breaking to avoid looping",
2368 old_min_size, min_size));
2369 return GST_FLOW_ERROR;
2373 /* pull @size bytes at current offset,
2374 * i.e. at least try to and possibly return a shorter buffer if near the end */
2375 static GstFlowReturn
2376 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2377 GstBuffer ** buffer)
2379 GstFlowReturn ret = GST_FLOW_OK;
2381 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2383 /* Caching here actually makes much less difference than one would expect.
2384 * We do it mainly to avoid pulling buffers of 1 byte all the time */
2385 if (parse->priv->cache) {
2386 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2387 gint cache_size = gst_buffer_get_size (parse->priv->cache);
2389 if (cache_offset <= parse->priv->offset &&
2390 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2391 *buffer = gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL,
2392 parse->priv->offset - cache_offset, size);
2393 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2396 /* not enough data in the cache, free cache and get a new one */
2397 gst_buffer_unref (parse->priv->cache);
2398 parse->priv->cache = NULL;
2401 /* refill the cache */
2403 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2404 64 * 1024), &parse->priv->cache);
2405 if (ret != GST_FLOW_OK) {
2406 parse->priv->cache = NULL;
2410 if (gst_buffer_get_size (parse->priv->cache) >= size) {
2412 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0,
2414 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2418 /* Not possible to get enough data, try a last time with
2419 * requesting exactly the size we need */
2420 gst_buffer_unref (parse->priv->cache);
2421 parse->priv->cache = NULL;
2423 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2424 &parse->priv->cache);
2426 if (ret != GST_FLOW_OK) {
2427 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2432 if (gst_buffer_get_size (parse->priv->cache) < size) {
2433 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2434 G_GUINT64_FORMAT ": wanted %u bytes, got %u bytes", parse->priv->offset,
2435 size, gst_buffer_get_size (parse->priv->cache));
2437 *buffer = parse->priv->cache;
2438 parse->priv->cache = NULL;
2444 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0, size);
2445 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2450 static GstFlowReturn
2451 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2454 GstClockTime ts = 0;
2458 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2459 ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2460 parse->priv->last_offset);
2462 if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2463 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2464 GST_TIME_ARGS (parse->segment.start));
2465 ret = GST_FLOW_UNEXPECTED;
2469 /* last fragment started at last_offset / last_ts;
2470 * seek back 10s capped at 1MB */
2471 if (parse->priv->last_ts >= 10 * GST_SECOND)
2472 ts = parse->priv->last_ts - 10 * GST_SECOND;
2473 /* if we are exact now, we will be more so going backwards */
2474 if (parse->priv->exact_position) {
2475 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2477 GstFormat dstformat = GST_FORMAT_BYTES;
2479 if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2480 &dstformat, &offset)) {
2481 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2484 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2485 parse->priv->last_offset - 1024);
2486 offset = MAX (0, offset);
2488 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2490 parse->priv->offset = offset;
2492 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2494 if (ret != GST_FLOW_OK)
2497 /* offset will increase again as fragment is processed/parsed */
2498 parse->priv->last_offset = offset;
2500 gst_adapter_push (parse->priv->adapter, buffer);
2501 ret = gst_base_parse_process_fragment (parse, FALSE);
2502 if (ret != GST_FLOW_OK)
2505 /* force previous fragment */
2506 parse->priv->offset = -1;
2513 * pull and scan for next frame starting from current offset
2514 * ajusts sync, drain and offset going along */
2515 static GstFlowReturn
2516 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2517 GstBaseParseFrame * frame, gboolean full)
2519 GstBuffer *buffer, *outbuf;
2520 GstFlowReturn ret = GST_FLOW_OK;
2521 guint fsize = 1, min_size, old_min_size = 0;
2524 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2526 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2527 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2529 /* let's make this efficient for all subclass once and for all;
2530 * maybe it does not need this much, but in the latter case, we know we are
2531 * in pull mode here and might as well try to read and supply more anyway
2532 * (so does the buffer caching mechanism) */
2538 min_size = MAX (parse->priv->min_frame_size, fsize);
2539 /* loop safety check */
2540 if (G_UNLIKELY (old_min_size >= min_size))
2542 old_min_size = min_size;
2544 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2545 if (ret != GST_FLOW_OK)
2548 if (parse->priv->discont) {
2549 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2550 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2553 /* if we got a short read, inform subclass we are draining leftover
2554 * and no more is to be expected */
2555 if (gst_buffer_get_size (buffer) < min_size)
2556 parse->priv->drain = TRUE;
2559 gst_base_parse_frame_update (parse, frame, buffer);
2560 res = klass->check_valid_frame (parse, frame, &fsize, &skip);
2561 gst_buffer_replace (&frame->buffer, NULL);
2563 parse->priv->drain = FALSE;
2564 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2567 parse->priv->drain = FALSE;
2571 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2572 if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2573 /* reverse playback, and no frames found yet, so we are skipping
2574 * the leading part of a fragment, which may form the tail of
2575 * fragment coming later, hopefully subclass skips efficiently ... */
2576 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, 0, skip);
2577 parse->priv->buffers_pending =
2578 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2581 parse->priv->offset += skip;
2582 if (!parse->priv->discont)
2583 parse->priv->sync_offset = parse->priv->offset;
2584 parse->priv->discont = TRUE;
2585 /* something changed at least; nullify loop check */
2586 if (fsize == G_MAXUINT)
2587 fsize = old_min_size + 64 * 1024;
2590 /* skip == 0 should imply subclass set min_size to need more data;
2591 * we check this shortly */
2592 GST_DEBUG_OBJECT (parse, "finding sync...");
2593 gst_buffer_unref (buffer);
2594 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2599 /* Does the subclass want to skip too? */
2601 parse->priv->offset += skip;
2605 if (fsize + skip <= gst_buffer_get_size (buffer)) {
2606 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, skip, fsize);
2607 GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2608 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2609 gst_buffer_unref (buffer);
2611 gst_buffer_unref (buffer);
2612 ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2613 if (ret != GST_FLOW_OK)
2615 if (gst_buffer_get_size (outbuf) < fsize) {
2616 gst_buffer_unref (outbuf);
2617 ret = GST_FLOW_UNEXPECTED;
2621 parse->priv->offset += fsize;
2623 frame->buffer = outbuf;
2631 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2632 ("min_size evolution %d -> %d; breaking to avoid looping",
2633 old_min_size, min_size));
2634 return GST_FLOW_ERROR;
2638 /* Loop that is used in pull mode to retrieve data from upstream */
2640 gst_base_parse_loop (GstPad * pad)
2642 GstBaseParse *parse;
2643 GstBaseParseClass *klass;
2644 GstFlowReturn ret = GST_FLOW_OK;
2645 GstBaseParseFrame frame;
2647 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2648 klass = GST_BASE_PARSE_GET_CLASS (parse);
2650 /* reverse playback:
2651 * first fragment (closest to stop time) is handled normally below,
2652 * then we pull in fragments going backwards */
2653 if (parse->segment.rate < 0.0) {
2654 /* check if we jumped back to a previous fragment,
2655 * which is a post-first fragment */
2656 if (parse->priv->offset < 0) {
2657 ret = gst_base_parse_handle_previous_fragment (parse);
2662 gst_base_parse_frame_init (&frame);
2663 ret = gst_base_parse_scan_frame (parse, klass, &frame, TRUE);
2664 if (ret != GST_FLOW_OK)
2667 /* This always cleans up frame, even if error occurs */
2668 ret = gst_base_parse_handle_and_push_frame (parse, klass, &frame);
2670 /* eat expected eos signalling past segment in reverse playback */
2671 if (parse->segment.rate < 0.0 && ret == GST_FLOW_UNEXPECTED &&
2672 parse->segment.position >= parse->segment.stop) {
2673 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2674 /* push what was accumulated during loop run */
2675 gst_base_parse_process_fragment (parse, TRUE);
2676 /* force previous fragment */
2677 parse->priv->offset = -1;
2682 if (ret == GST_FLOW_UNEXPECTED)
2684 else if (ret != GST_FLOW_OK)
2687 gst_object_unref (parse);
2693 ret = GST_FLOW_UNEXPECTED;
2694 GST_DEBUG_OBJECT (parse, "eos");
2699 gboolean push_eos = FALSE;
2701 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2702 gst_flow_get_name (ret));
2703 gst_pad_pause_task (parse->sinkpad);
2705 if (ret == GST_FLOW_UNEXPECTED) {
2706 /* handle end-of-stream/segment */
2707 if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2710 if ((stop = parse->segment.stop) == -1)
2711 stop = parse->segment.duration;
2713 GST_DEBUG_OBJECT (parse, "sending segment_done");
2715 gst_element_post_message
2716 (GST_ELEMENT_CAST (parse),
2717 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2718 GST_FORMAT_TIME, stop));
2720 /* If we STILL have zero frames processed, fire an error */
2721 if (parse->priv->framecount == 0) {
2722 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2723 ("No valid frames found before end of stream"), (NULL));
2727 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
2728 /* for fatal errors we post an error message, wrong-state is
2729 * not fatal because it happens due to flushes and only means
2730 * that we should stop now. */
2731 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2732 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2736 /* newsegment before eos */
2737 if (parse->priv->pending_segment) {
2738 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
2739 parse->priv->pending_segment = NULL;
2741 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2743 gst_object_unref (parse);
2748 gst_base_parse_sink_activate (GstPad * sinkpad)
2750 GstBaseParse *parse;
2751 gboolean result = TRUE;
2753 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2755 GST_DEBUG_OBJECT (parse, "sink activate");
2757 if (gst_pad_check_pull_range (sinkpad)) {
2758 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2759 result = gst_pad_activate_pull (sinkpad, TRUE);
2761 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
2762 result = gst_pad_activate_push (sinkpad, TRUE);
2765 GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
2766 gst_object_unref (parse);
2771 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
2773 GstBaseParseClass *klass;
2774 gboolean result = FALSE;
2776 GST_DEBUG_OBJECT (parse, "activate %d", active);
2778 klass = GST_BASE_PARSE_GET_CLASS (parse);
2781 if (parse->priv->pad_mode == GST_ACTIVATE_NONE && klass->start)
2782 result = klass->start (parse);
2784 /* We must make sure streaming has finished before resetting things
2785 * and calling the ::stop vfunc */
2786 GST_PAD_STREAM_LOCK (parse->sinkpad);
2787 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2789 if (parse->priv->pad_mode != GST_ACTIVATE_NONE && klass->stop)
2790 result = klass->stop (parse);
2792 parse->priv->pad_mode = GST_ACTIVATE_NONE;
2794 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
2799 gst_base_parse_sink_activate_push (GstPad * pad, gboolean active)
2801 gboolean result = TRUE;
2802 GstBaseParse *parse;
2804 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2806 GST_DEBUG_OBJECT (parse, "sink activate push %d", active);
2808 result = gst_base_parse_activate (parse, active);
2811 parse->priv->pad_mode = active ? GST_ACTIVATE_PUSH : GST_ACTIVATE_NONE;
2813 GST_DEBUG_OBJECT (parse, "sink activate push return: %d", result);
2815 gst_object_unref (parse);
2820 gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
2822 gboolean result = FALSE;
2823 GstBaseParse *parse;
2825 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2827 GST_DEBUG_OBJECT (parse, "activate pull %d", active);
2829 result = gst_base_parse_activate (parse, active);
2833 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
2835 gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
2838 result &= gst_pad_stop_task (sinkpad);
2843 parse->priv->pad_mode = active ? GST_ACTIVATE_PULL : GST_ACTIVATE_NONE;
2845 GST_DEBUG_OBJECT (parse, "sink activate pull return: %d", result);
2847 gst_object_unref (parse);
2853 * gst_base_parse_set_duration:
2854 * @parse: #GstBaseParse.
2856 * @duration: duration value.
2857 * @interval: how often to update the duration estimate based on bitrate, or 0.
2859 * Sets the duration of the currently playing media. Subclass can use this
2860 * when it is able to determine duration and/or notices a change in the media
2861 * duration. Alternatively, if @interval is non-zero (default), then stream
2862 * duration is determined based on estimated bitrate, and updated every @interval
2868 gst_base_parse_set_duration (GstBaseParse * parse,
2869 GstFormat fmt, gint64 duration, gint interval)
2871 g_return_if_fail (parse != NULL);
2873 if (parse->priv->upstream_has_duration) {
2874 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
2878 if (duration != parse->priv->duration) {
2881 m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
2882 gst_element_post_message (GST_ELEMENT (parse), m);
2884 /* TODO: what about duration tag? */
2886 parse->priv->duration = duration;
2887 parse->priv->duration_fmt = fmt;
2888 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
2889 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
2890 if (interval != 0) {
2891 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
2895 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
2896 parse->priv->update_interval = interval;
2902 * gst_base_parse_set_average_bitrate:
2903 * @parse: #GstBaseParse.
2904 * @bitrate: average bitrate in bits/second
2906 * Optionally sets the average bitrate detected in media (if non-zero),
2907 * e.g. based on metadata, as it will be posted to the application.
2909 * By default, announced average bitrate is estimated. The average bitrate
2910 * is used to estimate the total duration of the stream and to estimate
2911 * a seek position, if there's no index and the format is syncable
2912 * (see gst_base_parse_set_syncable()).
2917 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
2919 parse->priv->bitrate = bitrate;
2920 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
2924 * gst_base_parse_set_min_frame_size:
2925 * @parse: #GstBaseParse.
2926 * @min_size: Minimum size of the data that this base class should give to
2929 * Subclass can use this function to tell the base class that it needs to
2930 * give at least #min_size buffers.
2935 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
2937 g_return_if_fail (parse != NULL);
2939 parse->priv->min_frame_size = min_size;
2940 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
2944 * gst_base_parse_set_frame_rate:
2945 * @parse: the #GstBaseParse to set
2946 * @fps_num: frames per second (numerator).
2947 * @fps_den: frames per second (denominator).
2948 * @lead_in: frames needed before a segment for subsequent decode
2949 * @lead_out: frames needed after a segment
2951 * If frames per second is configured, parser can take care of buffer duration
2952 * and timestamping. When performing segment clipping, or seeking to a specific
2953 * location, a corresponding decoder might need an initial @lead_in and a
2954 * following @lead_out number of frames to ensure the desired segment is
2955 * entirely filled upon decoding.
2960 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
2961 guint fps_den, guint lead_in, guint lead_out)
2963 g_return_if_fail (parse != NULL);
2965 parse->priv->fps_num = fps_num;
2966 parse->priv->fps_den = fps_den;
2967 if (!fps_num || !fps_den) {
2968 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
2970 fps_num = fps_den = 0;
2971 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
2972 parse->priv->lead_in = parse->priv->lead_out = 0;
2973 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
2975 parse->priv->frame_duration =
2976 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
2977 parse->priv->lead_in = lead_in;
2978 parse->priv->lead_out = lead_out;
2979 parse->priv->lead_in_ts =
2980 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
2981 parse->priv->lead_out_ts =
2982 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
2983 /* aim for about 1.5s to estimate duration */
2984 if (parse->priv->update_interval < 0) {
2985 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
2986 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
2987 parse->priv->update_interval);
2990 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
2991 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
2992 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
2993 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
2994 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
2995 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
2999 * gst_base_parse_set_has_timing_info:
3000 * @parse: a #GstBaseParse
3001 * @has_timing: whether frames carry timing information
3003 * Set if frames carry timing information which the subclass can (generally)
3004 * parse and provide. In particular, intrinsic (rather than estimated) time
3005 * can be obtained following a seek.
3010 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3012 parse->priv->has_timing_info = has_timing;
3013 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3017 * gst_base_parse_set_syncable:
3018 * @parse: a #GstBaseParse
3019 * @syncable: set if frame starts can be identified
3021 * Set if frame starts can be identified. This is set by default and
3022 * determines whether seeking based on bitrate averages
3023 * is possible for a format/stream.
3028 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3030 parse->priv->syncable = syncable;
3031 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3035 * gst_base_parse_set_passthrough:
3036 * @parse: a #GstBaseParse
3037 * @passthrough: %TRUE if parser should run in passthrough mode
3039 * Set if the nature of the format or configuration does not allow (much)
3040 * parsing, and the parser should operate in passthrough mode (which only
3041 * applies when operating in push mode). That is, incoming buffers are
3042 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3043 * callbacks will be invoked, but @pre_push_buffer will still be invoked,
3044 * so subclass can perform as much or as little is appropriate for
3045 * passthrough semantics in @pre_push_buffer.
3050 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3052 parse->priv->passthrough = passthrough;
3053 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3057 * gst_base_parse_set_latency:
3058 * @parse: a #GstBaseParse
3059 * @min_latency: minimum parse latency
3060 * @max_latency: maximum parse latency
3062 * Sets the minimum and maximum (which may likely be equal) latency introduced
3063 * by the parsing process. If there is such a latency, which depends on the
3064 * particular parsing of the format, it typically corresponds to 1 frame duration.
3069 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3070 GstClockTime max_latency)
3072 GST_OBJECT_LOCK (parse);
3073 parse->priv->min_latency = min_latency;
3074 parse->priv->max_latency = max_latency;
3075 GST_OBJECT_UNLOCK (parse);
3076 GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3077 GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3078 GST_TIME_ARGS (max_latency));
3082 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3083 GstClockTime * duration)
3085 gboolean res = FALSE;
3087 g_return_val_if_fail (duration != NULL, FALSE);
3089 *duration = GST_CLOCK_TIME_NONE;
3090 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3091 GST_LOG_OBJECT (parse, "using provided duration");
3092 *duration = parse->priv->duration;
3094 } else if (parse->priv->duration != -1) {
3095 GST_LOG_OBJECT (parse, "converting provided duration");
3096 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3097 parse->priv->duration, format, (gint64 *) duration);
3098 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3099 GST_LOG_OBJECT (parse, "using estimated duration");
3100 *duration = parse->priv->estimated_duration;
3104 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3105 GST_TIME_ARGS (*duration));
3109 static const GstQueryType *
3110 gst_base_parse_get_querytypes (GstPad * pad)
3112 static const GstQueryType list[] = {
3125 gst_base_parse_query (GstPad * pad, GstQuery * query)
3127 GstBaseParse *parse;
3128 gboolean res = FALSE;
3130 parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3132 GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3134 switch (GST_QUERY_TYPE (query)) {
3135 case GST_QUERY_POSITION:
3140 GST_DEBUG_OBJECT (parse, "position query");
3141 gst_query_parse_position (query, &format, NULL);
3143 GST_OBJECT_LOCK (parse);
3144 if (format == GST_FORMAT_BYTES) {
3145 dest_value = parse->priv->offset;
3147 } else if (format == parse->segment.format &&
3148 GST_CLOCK_TIME_IS_VALID (parse->segment.position)) {
3149 dest_value = parse->segment.position;
3152 GST_OBJECT_UNLOCK (parse);
3155 gst_query_set_position (query, format, dest_value);
3157 res = gst_pad_query_default (pad, query);
3159 /* no precise result, upstream no idea either, then best estimate */
3160 /* priv->offset is updated in both PUSH/PULL modes */
3161 res = gst_base_parse_convert (parse,
3162 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3167 case GST_QUERY_DURATION:
3170 GstClockTime duration;
3172 GST_DEBUG_OBJECT (parse, "duration query");
3173 gst_query_parse_duration (query, &format, NULL);
3175 /* consult upstream */
3176 res = gst_pad_query_default (pad, query);
3178 /* otherwise best estimate from us */
3180 res = gst_base_parse_get_duration (parse, format, &duration);
3182 gst_query_set_duration (query, format, duration);
3186 case GST_QUERY_SEEKING:
3189 GstClockTime duration = GST_CLOCK_TIME_NONE;
3190 gboolean seekable = FALSE;
3192 GST_DEBUG_OBJECT (parse, "seeking query");
3193 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3195 /* consult upstream */
3196 res = gst_pad_query_default (pad, query);
3198 /* we may be able to help if in TIME */
3199 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3200 gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3201 /* already OK if upstream takes care */
3202 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3204 if (!(res && seekable)) {
3205 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3206 || duration == -1) {
3207 /* seekable if we still have a chance to get duration later on */
3209 parse->priv->upstream_seekable && parse->priv->update_interval;
3211 seekable = parse->priv->upstream_seekable;
3212 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3215 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3221 case GST_QUERY_FORMATS:
3222 gst_query_set_formatsv (query, 3, fmtlist);
3225 case GST_QUERY_CONVERT:
3227 GstFormat src_format, dest_format;
3228 gint64 src_value, dest_value;
3230 gst_query_parse_convert (query, &src_format, &src_value,
3231 &dest_format, &dest_value);
3233 res = gst_base_parse_convert (parse, src_format, src_value,
3234 dest_format, &dest_value);
3236 gst_query_set_convert (query, src_format, src_value,
3237 dest_format, dest_value);
3241 case GST_QUERY_LATENCY:
3243 if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3245 GstClockTime min_latency, max_latency;
3247 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3248 GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3249 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3250 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3252 GST_OBJECT_LOCK (parse);
3253 /* add our latency */
3254 if (min_latency != -1)
3255 min_latency += parse->priv->min_latency;
3256 if (max_latency != -1)
3257 max_latency += parse->priv->max_latency;
3258 GST_OBJECT_UNLOCK (parse);
3260 gst_query_set_latency (query, live, min_latency, max_latency);
3265 res = gst_pad_query_default (pad, query);
3271 /* scans for a cluster start from @pos,
3272 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3273 static GstFlowReturn
3274 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3275 GstClockTime * time, GstClockTime * duration)
3277 GstBaseParseClass *klass;
3279 gboolean orig_drain, orig_discont;
3280 GstFlowReturn ret = GST_FLOW_OK;
3281 GstBuffer *buf = NULL;
3282 GstBaseParseFrame frame;
3284 g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3285 g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3286 g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3288 klass = GST_BASE_PARSE_GET_CLASS (parse);
3290 *time = GST_CLOCK_TIME_NONE;
3291 *duration = GST_CLOCK_TIME_NONE;
3294 orig_offset = parse->priv->offset;
3295 orig_discont = parse->priv->discont;
3296 orig_drain = parse->priv->drain;
3298 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3299 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3301 gst_base_parse_frame_init (&frame);
3303 /* jump elsewhere and locate next frame */
3304 parse->priv->offset = *pos;
3305 ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3306 if (ret != GST_FLOW_OK)
3310 GST_LOG_OBJECT (parse,
3311 "peek parsing frame at offset %" G_GUINT64_FORMAT
3312 " (%#" G_GINT64_MODIFIER "x) of size %d",
3313 GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf),
3314 gst_buffer_get_size (buf));
3316 /* get offset first, subclass parsing might dump other stuff in there */
3317 *pos = GST_BUFFER_OFFSET (buf);
3318 ret = klass->parse_frame (parse, &frame);
3321 /* but it should provide proper time */
3322 *time = GST_BUFFER_TIMESTAMP (buf);
3323 *duration = GST_BUFFER_DURATION (buf);
3325 gst_base_parse_frame_free (&frame);
3327 GST_LOG_OBJECT (parse,
3328 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3329 GST_TIME_ARGS (*time), *pos);
3333 parse->priv->offset = orig_offset;
3334 parse->priv->discont = orig_discont;
3335 parse->priv->drain = orig_drain;
3340 /* bisect and scan through file for frame starting before @time,
3341 * returns OK and @time/@offset if found, NONE and/or error otherwise
3342 * If @time == G_MAXINT64, scan for duration ( == last frame) */
3343 static GstFlowReturn
3344 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3347 GstFlowReturn ret = GST_FLOW_OK;
3348 gint64 lpos, hpos, newpos;
3349 GstClockTime time, ltime, htime, newtime, dur;
3350 gboolean cont = TRUE;
3351 const GstClockTime tolerance = TARGET_DIFFERENCE;
3352 const guint chunk = 4 * 1024;
3354 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3355 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3357 /* TODO also make keyframe aware if useful some day */
3372 /* do not know at first */
3374 *_time = GST_CLOCK_TIME_NONE;
3376 /* need initial positions; start and end */
3377 lpos = parse->priv->first_frame_offset;
3378 ltime = parse->priv->first_frame_ts;
3379 htime = parse->priv->duration;
3380 hpos = parse->priv->upstream_size;
3382 /* check preconditions are satisfied;
3383 * start and end are needed, except for special case where we scan for
3384 * last frame to determine duration */
3385 if (parse->priv->pad_mode != GST_ACTIVATE_PULL || !hpos ||
3386 !GST_CLOCK_TIME_IS_VALID (ltime) ||
3387 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3391 /* shortcut cases */
3394 } else if (time < ltime + tolerance) {
3398 } else if (time >= htime) {
3404 while (htime > ltime && cont) {
3405 GST_LOG_OBJECT (parse,
3406 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3407 GST_TIME_ARGS (ltime));
3408 GST_LOG_OBJECT (parse,
3409 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3410 GST_TIME_ARGS (htime));
3411 if (G_UNLIKELY (time == G_MAXINT64)) {
3413 } else if (G_LIKELY (hpos > lpos)) {
3415 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3418 /* should mean lpos == hpos, since lpos <= hpos is invariant */
3420 /* we check this case once, but not forever, so break loop */
3425 newpos = CLAMP (newpos, lpos, hpos);
3426 GST_LOG_OBJECT (parse,
3427 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3428 GST_TIME_ARGS (time), newpos);
3430 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3431 if (ret == GST_FLOW_UNEXPECTED) {
3432 /* heuristic HACK */
3433 hpos = MAX (lpos, hpos - chunk);
3435 } else if (ret != GST_FLOW_OK) {
3439 if (newtime == -1 || newpos == -1) {
3440 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3444 if (G_UNLIKELY (time == G_MAXINT64)) {
3447 if (GST_CLOCK_TIME_IS_VALID (dur))
3450 } else if (newtime > time) {
3452 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3454 } else if (newtime + tolerance > time) {
3455 /* close enough undershoot */
3459 } else if (newtime < ltime) {
3460 /* so a position beyond lpos resulted in earlier time than ltime ... */
3461 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3464 /* undershoot too far */
3465 newpos += newpos == lpos ? chunk : 0;
3466 lpos = CLAMP (newpos, lpos, hpos);
3472 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3473 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3478 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3479 gboolean before, GstClockTime * _ts)
3481 gint64 bytes = 0, ts = 0;
3482 GstIndexEntry *entry = NULL;
3484 if (time == GST_CLOCK_TIME_NONE) {
3490 g_static_mutex_lock (&parse->priv->index_lock);
3491 if (parse->priv->index) {
3492 /* Let's check if we have an index entry for that time */
3493 entry = gst_index_get_assoc_entry (parse->priv->index,
3494 parse->priv->index_id,
3495 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3496 GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3500 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3501 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3503 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3504 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3505 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3507 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3508 GST_TIME_ARGS (time));
3511 ts = GST_CLOCK_TIME_NONE;
3514 g_static_mutex_unlock (&parse->priv->index_lock);
3523 /* returns TRUE if seek succeeded */
3525 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3530 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3531 gboolean flush, update, res = TRUE, accurate;
3532 gint64 cur, stop, seekpos, seekstop;
3533 GstSegment seeksegment = { 0, };
3534 GstFormat dstformat;
3535 GstClockTime start_ts;
3537 gst_event_parse_seek (event, &rate, &format, &flags,
3538 &cur_type, &cur, &stop_type, &stop);
3540 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3541 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3542 GST_TIME_FORMAT, gst_format_get_name (format), rate,
3543 cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3545 /* no negative rates in push mode */
3546 if (rate < 0.0 && parse->priv->pad_mode == GST_ACTIVATE_PUSH)
3549 if (cur_type != GST_SEEK_TYPE_SET ||
3550 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3553 /* For any format other than TIME, see if upstream handles
3554 * it directly or fail. For TIME, try upstream, but do it ourselves if
3555 * it fails upstream */
3556 if (format != GST_FORMAT_TIME) {
3557 /* default action delegates to upstream */
3561 gst_event_ref (event);
3562 if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3567 /* get flush flag */
3568 flush = flags & GST_SEEK_FLAG_FLUSH;
3570 /* copy segment, we need this because we still need the old
3571 * segment when we close the current segment. */
3572 gst_segment_copy_into (&parse->segment, &seeksegment);
3574 GST_DEBUG_OBJECT (parse, "configuring seek");
3575 gst_segment_do_seek (&seeksegment, rate, format, flags,
3576 cur_type, cur, stop_type, stop, &update);
3578 /* accurate seeking implies seek tables are used to obtain position,
3579 * and the requested segment is maintained exactly, not adjusted any way */
3580 accurate = flags & GST_SEEK_FLAG_ACCURATE;
3582 /* maybe we can be accurate for (almost) free */
3583 gst_base_parse_find_offset (parse, seeksegment.position, TRUE, &start_ts);
3584 if (seeksegment.position <= start_ts + TARGET_DIFFERENCE) {
3585 GST_DEBUG_OBJECT (parse, "accurate seek possible");
3589 GstClockTime startpos = seeksegment.position;
3591 /* accurate requested, so ... seek a bit before target */
3592 if (startpos < parse->priv->lead_in_ts)
3595 startpos -= parse->priv->lead_in_ts;
3596 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3597 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3600 start_ts = seeksegment.position;
3601 dstformat = GST_FORMAT_BYTES;
3602 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.position,
3603 &dstformat, &seekpos))
3604 goto convert_failed;
3605 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3606 &dstformat, &seekstop))
3607 goto convert_failed;
3610 GST_DEBUG_OBJECT (parse,
3611 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3613 GST_DEBUG_OBJECT (parse,
3614 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3615 seeksegment.stop, seekstop);
3617 if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
3620 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3623 if (parse->srcpad) {
3624 GST_DEBUG_OBJECT (parse, "sending flush start");
3625 gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3626 /* unlock upstream pull_range */
3627 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3630 gst_pad_pause_task (parse->sinkpad);
3633 /* we should now be able to grab the streaming thread because we stopped it
3634 * with the above flush/pause code */
3635 GST_PAD_STREAM_LOCK (parse->sinkpad);
3637 /* save current position */
3638 last_stop = parse->segment.position;
3639 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3642 /* now commit to new position */
3644 /* prepare for streaming again */
3646 GST_DEBUG_OBJECT (parse, "sending flush stop");
3647 gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop ());
3648 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop ());
3649 gst_base_parse_clear_queues (parse);
3651 /* keep track of our position */
3652 seeksegment.base = gst_segment_to_running_time (&seeksegment,
3653 seeksegment.format, parse->segment.position);
3656 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3658 /* store the newsegment event so it can be sent from the streaming thread. */
3659 if (parse->priv->pending_segment)
3660 gst_event_unref (parse->priv->pending_segment);
3662 /* This will be sent later in _loop() */
3663 parse->priv->pending_segment = gst_event_new_segment (&parse->segment);
3665 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3666 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3667 ", pos = %" GST_TIME_FORMAT, format,
3668 GST_TIME_ARGS (parse->segment.start),
3669 GST_TIME_ARGS (parse->segment.stop),
3670 GST_TIME_ARGS (parse->segment.start));
3672 /* one last chance in pull mode to stay accurate;
3673 * maybe scan and subclass can find where to go */
3676 GstClockTime ts = seeksegment.position;
3678 gst_base_parse_locate_time (parse, &ts, &scanpos);
3682 /* running collected index now consists of several intervals,
3683 * so optimized check no longer possible */
3684 parse->priv->index_last_valid = FALSE;
3685 parse->priv->index_last_offset = 0;
3686 parse->priv->index_last_ts = 0;
3690 /* mark discont if we are going to stream from another position. */
3691 if (seekpos != parse->priv->offset) {
3692 GST_DEBUG_OBJECT (parse,
3693 "mark DISCONT, we did a seek to another position");
3694 parse->priv->offset = seekpos;
3695 parse->priv->last_offset = seekpos;
3696 parse->priv->seen_keyframe = FALSE;
3697 parse->priv->discont = TRUE;
3698 parse->priv->next_ts = start_ts;
3699 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3700 parse->priv->sync_offset = seekpos;
3701 parse->priv->exact_position = accurate;
3704 /* Start streaming thread if paused */
3705 gst_pad_start_task (parse->sinkpad,
3706 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3708 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3713 GstEvent *new_event;
3714 GstBaseParseSeek *seek;
3716 /* The only thing we need to do in PUSH-mode is to send the
3717 seek event (in bytes) to upstream. Segment / flush handling happens
3718 in corresponding src event handlers */
3719 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3720 if (seekstop >= 0 && seekpos <= seekpos)
3722 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flush,
3723 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3725 /* store segment info so its precise details can be reconstructed when
3726 * receiving newsegment;
3727 * this matters for all details when accurate seeking,
3728 * is most useful to preserve NONE stop time otherwise */
3729 seek = g_new0 (GstBaseParseSeek, 1);
3730 seek->segment = seeksegment;
3731 seek->accurate = accurate;
3732 seek->offset = seekpos;
3733 seek->start_ts = start_ts;
3734 GST_OBJECT_LOCK (parse);
3735 /* less optimal, but preserves order */
3736 parse->priv->pending_seeks =
3737 g_slist_append (parse->priv->pending_seeks, seek);
3738 GST_OBJECT_UNLOCK (parse);
3740 res = gst_pad_push_event (parse->sinkpad, new_event);
3743 GST_OBJECT_LOCK (parse);
3744 parse->priv->pending_seeks =
3745 g_slist_remove (parse->priv->pending_seeks, seek);
3746 GST_OBJECT_UNLOCK (parse);
3752 /* handled event is ours to free */
3754 gst_event_unref (event);
3760 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
3766 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3772 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3778 /* Checks if bitrates are available from upstream tags so that we don't
3779 * override them later
3782 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
3784 GstTagList *taglist = NULL;
3787 gst_event_parse_tag (event, &taglist);
3789 if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
3790 GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
3791 parse->priv->post_min_bitrate = FALSE;
3793 if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
3794 GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
3795 parse->priv->post_avg_bitrate = FALSE;
3797 if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
3798 GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
3799 parse->priv->post_max_bitrate = FALSE;
3804 gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps)
3806 GstBaseParse *parse;
3807 GstBaseParseClass *klass;
3808 gboolean res = TRUE;
3810 parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3811 klass = GST_BASE_PARSE_GET_CLASS (parse);
3813 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
3815 if (klass->set_sink_caps)
3816 res = klass->set_sink_caps (parse, caps);
3822 gst_base_parse_set_index (GstElement * element, GstIndex * index)
3824 GstBaseParse *parse = GST_BASE_PARSE (element);
3826 g_static_mutex_lock (&parse->priv->index_lock);
3827 if (parse->priv->index)
3828 gst_object_unref (parse->priv->index);
3830 parse->priv->index = gst_object_ref (index);
3831 gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
3832 &parse->priv->index_id);
3833 parse->priv->own_index = FALSE;
3835 parse->priv->index = NULL;
3837 g_static_mutex_unlock (&parse->priv->index_lock);
3841 gst_base_parse_get_index (GstElement * element)
3843 GstBaseParse *parse = GST_BASE_PARSE (element);
3844 GstIndex *result = NULL;
3846 g_static_mutex_lock (&parse->priv->index_lock);
3847 if (parse->priv->index)
3848 result = gst_object_ref (parse->priv->index);
3849 g_static_mutex_unlock (&parse->priv->index_lock);
3854 static GstStateChangeReturn
3855 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
3857 GstBaseParse *parse;
3858 GstStateChangeReturn result;
3860 parse = GST_BASE_PARSE (element);
3862 switch (transition) {
3863 case GST_STATE_CHANGE_READY_TO_PAUSED:
3864 /* If this is our own index destroy it as the
3865 * old entries might be wrong for the new stream */
3866 g_static_mutex_lock (&parse->priv->index_lock);
3867 if (parse->priv->own_index) {
3868 gst_object_unref (parse->priv->index);
3869 parse->priv->index = NULL;
3870 parse->priv->own_index = FALSE;
3873 /* If no index was created, generate one */
3874 if (G_UNLIKELY (!parse->priv->index)) {
3875 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
3877 parse->priv->index = gst_index_factory_make ("memindex");
3878 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
3879 &parse->priv->index_id);
3880 parse->priv->own_index = TRUE;
3882 g_static_mutex_unlock (&parse->priv->index_lock);
3888 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3890 switch (transition) {
3891 case GST_STATE_CHANGE_PAUSED_TO_READY:
3892 gst_base_parse_reset (parse);