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_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, NEWSEGMENT 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_NEWSEGMENT
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_NEWSEGMENT:
918 gdouble rate, applied_rate;
920 gint64 start, stop, pos, next_ts, offset = 0;
923 gst_event_parse_new_segment_full (event, &update, &rate, &applied_rate,
924 &format, &start, &stop, &pos);
926 GST_DEBUG_OBJECT (parse, "newseg rate %g, applied rate %g, "
927 "format %d, start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
928 ", pos = %" GST_TIME_FORMAT, rate, applied_rate, format,
929 GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (pos));
931 if (format == GST_FORMAT_BYTES) {
932 GstClockTime seg_start, seg_stop;
933 GstBaseParseSeek *seek = NULL;
936 /* stop time is allowed to be open-ended, but not start & pos */
937 seg_stop = GST_CLOCK_TIME_NONE;
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 == pos) {
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);
958 seg_start = seek->segment.start;
959 seg_stop = seek->segment.stop;
960 next_ts = seek->start_ts;
961 parse->priv->exact_position = seek->accurate;
964 /* best attempt convert */
965 /* as these are only estimates, stop is kept open-ended to avoid
966 * premature cutting */
967 gst_base_parse_convert (parse, GST_FORMAT_BYTES, start,
968 GST_FORMAT_TIME, (gint64 *) & seg_start);
969 parse->priv->exact_position = (start == 0);
973 gst_event_unref (event);
974 event = gst_event_new_new_segment_full (update, rate, applied_rate,
975 GST_FORMAT_TIME, seg_start, seg_stop, seg_start);
976 format = GST_FORMAT_TIME;
979 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. "
980 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT,
981 GST_TIME_ARGS (seg_start), GST_TIME_ARGS (seg_stop));
982 } else if (format != GST_FORMAT_TIME) {
983 /* Unknown incoming segment format. Output a default open-ended
985 gst_event_unref (event);
986 event = gst_event_new_new_segment_full (update, rate, applied_rate,
987 GST_FORMAT_TIME, 0, GST_CLOCK_TIME_NONE, 0);
988 format = GST_FORMAT_TIME;
990 stop = GST_CLOCK_TIME_NONE;
992 /* not considered BYTE seekable if it is talking to us in TIME,
993 * whatever else it might claim */
994 parse->priv->upstream_seekable = FALSE;
998 gst_segment_set_newsegment_full (&parse->segment, update, rate,
999 applied_rate, format, start, stop, start);
1001 /* save the segment for later, right before we push a new buffer so that
1002 * the caps are fixed and the next linked element can receive
1004 eventp = &parse->priv->pending_segment;
1005 gst_event_replace (eventp, event);
1006 gst_event_unref (event);
1009 /* but finish the current segment */
1010 GST_DEBUG_OBJECT (parse, "draining current segment");
1011 if (parse->segment.rate > 0.0)
1012 gst_base_parse_drain (parse);
1014 gst_base_parse_process_fragment (parse, FALSE);
1015 gst_adapter_clear (parse->priv->adapter);
1016 parse->priv->offset = offset;
1017 parse->priv->sync_offset = offset;
1018 parse->priv->next_ts = next_ts;
1019 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1020 parse->priv->discont = TRUE;
1021 parse->priv->seen_keyframe = FALSE;
1025 case GST_EVENT_FLUSH_START:
1026 parse->priv->flushing = TRUE;
1027 handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
1029 gst_event_unref (event);
1030 /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
1031 GST_PAD_STREAM_LOCK (parse->srcpad);
1032 GST_PAD_STREAM_UNLOCK (parse->srcpad);
1036 case GST_EVENT_FLUSH_STOP:
1037 gst_adapter_clear (parse->priv->adapter);
1038 gst_base_parse_clear_queues (parse);
1039 parse->priv->flushing = FALSE;
1040 parse->priv->discont = TRUE;
1041 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1042 parse->priv->frame._private_flags |=
1043 GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
1044 gst_base_parse_frame_free (&parse->priv->frame);
1048 if (parse->segment.rate > 0.0)
1049 gst_base_parse_drain (parse);
1051 gst_base_parse_process_fragment (parse, FALSE);
1053 /* If we STILL have zero frames processed, fire an error */
1054 if (parse->priv->framecount == 0) {
1055 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1056 ("No valid frames found before end of stream"), (NULL));
1058 /* newsegment before eos */
1059 if (parse->priv->pending_segment) {
1060 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1061 parse->priv->pending_segment = NULL;
1073 /* gst_base_parse_src_event:
1074 * @pad: #GstPad that received the event.
1075 * @event: #GstEvent that was received.
1077 * Handler for source pad events.
1079 * Returns: TRUE if the event was handled.
1082 gst_base_parse_src_event (GstPad * pad, GstEvent * event)
1084 GstBaseParse *parse;
1085 GstBaseParseClass *bclass;
1086 gboolean handled = FALSE;
1087 gboolean ret = TRUE;
1089 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
1090 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1092 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1093 GST_EVENT_TYPE_NAME (event));
1095 if (bclass->src_event)
1096 handled = bclass->src_event (parse, event);
1099 ret = gst_pad_event_default (pad, event);
1101 gst_object_unref (parse);
1106 gst_base_parse_is_seekable (GstBaseParse * parse)
1108 /* FIXME: could do more here, e.g. check index or just send data from 0
1109 * in pull mode and let decoder/sink clip */
1110 return parse->priv->syncable;
1113 /* gst_base_parse_src_eventfunc:
1114 * @parse: #GstBaseParse.
1115 * @event: #GstEvent that was received.
1117 * Default srcpad event handler.
1119 * Returns: TRUE if the event was handled and can be dropped.
1122 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1124 gboolean handled = FALSE;
1126 switch (GST_EVENT_TYPE (event)) {
1127 case GST_EVENT_SEEK:
1129 if (gst_base_parse_is_seekable (parse)) {
1130 handled = gst_base_parse_handle_seek (parse, event);
1142 * gst_base_parse_convert_default:
1143 * @parse: #GstBaseParse.
1144 * @src_format: #GstFormat describing the source format.
1145 * @src_value: Source value to be converted.
1146 * @dest_format: #GstFormat defining the converted format.
1147 * @dest_value: Pointer where the conversion result will be put.
1149 * Default implementation of "convert" vmethod in #GstBaseParse class.
1151 * Returns: TRUE if conversion was successful.
1156 gst_base_parse_convert_default (GstBaseParse * parse,
1157 GstFormat src_format,
1158 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1160 gboolean ret = FALSE;
1161 guint64 bytes, duration;
1163 if (G_UNLIKELY (src_format == dest_format)) {
1164 *dest_value = src_value;
1168 if (G_UNLIKELY (src_value == -1)) {
1173 if (G_UNLIKELY (src_value == 0)) {
1178 /* need at least some frames */
1179 if (!parse->priv->framecount)
1182 duration = parse->priv->acc_duration / GST_MSECOND;
1183 bytes = parse->priv->bytecount;
1185 if (G_UNLIKELY (!duration || !bytes))
1188 if (src_format == GST_FORMAT_BYTES) {
1189 if (dest_format == GST_FORMAT_TIME) {
1190 /* BYTES -> TIME conversion */
1191 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1192 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1193 *dest_value *= GST_MSECOND;
1194 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1195 *dest_value / GST_MSECOND);
1198 } else if (src_format == GST_FORMAT_TIME) {
1199 if (dest_format == GST_FORMAT_BYTES) {
1200 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1201 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1203 GST_DEBUG_OBJECT (parse,
1204 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1205 src_value / GST_MSECOND, *dest_value);
1208 } else if (src_format == GST_FORMAT_DEFAULT) {
1209 /* DEFAULT == frame-based */
1210 if (dest_format == GST_FORMAT_TIME) {
1211 if (parse->priv->fps_den) {
1212 *dest_value = gst_util_uint64_scale (src_value,
1213 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1216 } else if (dest_format == GST_FORMAT_BYTES) {
1224 gst_base_parse_update_duration (GstBaseParse * baseparse)
1227 GstBaseParse *parse;
1229 parse = GST_BASE_PARSE (baseparse);
1231 peer = gst_pad_get_peer (parse->sinkpad);
1233 GstFormat pformat = GST_FORMAT_BYTES;
1234 gboolean qres = FALSE;
1235 gint64 ptot, dest_value;
1237 qres = gst_pad_query_duration (peer, &pformat, &ptot);
1238 gst_object_unref (GST_OBJECT (peer));
1240 if (gst_base_parse_convert (parse, pformat, ptot,
1241 GST_FORMAT_TIME, &dest_value)) {
1242 parse->priv->estimated_duration = dest_value;
1243 GST_LOG_OBJECT (parse,
1244 "updated estimated duration to %" GST_TIME_FORMAT,
1245 GST_TIME_ARGS (dest_value));
1252 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1253 gboolean post_avg, gboolean post_max)
1255 GstTagList *taglist = NULL;
1257 if (post_min && parse->priv->post_min_bitrate) {
1258 taglist = gst_tag_list_new ();
1260 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1261 GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1264 if (post_avg && parse->priv->post_avg_bitrate) {
1265 if (taglist == NULL)
1266 taglist = gst_tag_list_new ();
1268 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1269 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1270 parse->priv->avg_bitrate, NULL);
1273 if (post_max && parse->priv->post_max_bitrate) {
1274 if (taglist == NULL)
1275 taglist = gst_tag_list_new ();
1277 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1278 GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1281 GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1282 parse->priv->min_bitrate, parse->priv->avg_bitrate,
1283 parse->priv->max_bitrate);
1285 if (taglist != NULL) {
1286 gst_element_found_tags_for_pad (GST_ELEMENT_CAST (parse), parse->srcpad,
1291 /* gst_base_parse_update_bitrates:
1292 * @parse: #GstBaseParse.
1293 * @buffer: Current frame as a #GstBuffer
1295 * Keeps track of the minimum and maximum bitrates, and also maintains a
1296 * running average bitrate of the stream so far.
1299 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1301 /* Only update the tag on a 10 kbps delta */
1302 static const gint update_threshold = 10000;
1304 guint64 data_len, frame_dur;
1305 gint overhead, frame_bitrate, old_avg_bitrate;
1306 gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1307 GstBuffer *buffer = frame->buffer;
1309 overhead = frame->overhead;
1313 data_len = GST_BUFFER_SIZE (buffer) - overhead;
1314 parse->priv->data_bytecount += data_len;
1316 /* duration should be valid by now,
1317 * either set by subclass or maybe based on fps settings */
1318 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1319 /* Calculate duration of a frame from buffer properties */
1320 frame_dur = GST_BUFFER_DURATION (buffer);
1321 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1322 parse->priv->acc_duration;
1325 /* No way to figure out frame duration (is this even possible?) */
1329 /* override if subclass provided bitrate, e.g. metadata based */
1330 if (parse->priv->bitrate) {
1331 parse->priv->avg_bitrate = parse->priv->bitrate;
1332 /* spread this (confirmed) info ASAP */
1333 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1334 gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1338 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1342 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1343 parse->priv->avg_bitrate);
1345 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1347 } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1348 /* always post all at threshold time */
1349 update_min = update_max = update_avg = TRUE;
1352 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1353 if (frame_bitrate < parse->priv->min_bitrate) {
1354 parse->priv->min_bitrate = frame_bitrate;
1358 if (frame_bitrate > parse->priv->max_bitrate) {
1359 parse->priv->max_bitrate = frame_bitrate;
1363 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1364 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1365 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1370 if ((update_min || update_avg || update_max))
1371 gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1373 /* If average bitrate changes that much and no valid (time) duration provided,
1374 * then post a new duration message so applications can update their cached
1376 if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1377 GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1378 gst_element_post_message (GST_ELEMENT (parse),
1379 gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1386 * gst_base_parse_add_index_entry:
1387 * @parse: #GstBaseParse.
1388 * @offset: offset of entry
1389 * @ts: timestamp associated with offset
1390 * @key: whether entry refers to keyframe
1391 * @force: add entry disregarding sanity checks
1393 * Adds an entry to the index associating @offset to @ts. It is recommended
1394 * to only add keyframe entries. @force allows to bypass checks, such as
1395 * whether the stream is (upstream) seekable, another entry is already "close"
1396 * to the new entry, etc.
1398 * Returns: #gboolean indicating whether entry was added
1403 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1404 GstClockTime ts, gboolean key, gboolean force)
1406 gboolean ret = FALSE;
1407 GstIndexAssociation associations[2];
1409 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1410 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1412 if (G_LIKELY (!force)) {
1414 if (!parse->priv->upstream_seekable) {
1415 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1419 /* FIXME need better helper data structure that handles these issues
1420 * related to ongoing collecting of index entries */
1421 if (parse->priv->index_last_offset >= (gint64) offset) {
1422 GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1423 "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1427 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1428 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1429 parse->priv->idx_interval) {
1430 GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1431 GST_TIME_ARGS (parse->priv->index_last_ts));
1435 /* if last is not really the last one */
1436 if (!parse->priv->index_last_valid) {
1437 GstClockTime prev_ts;
1439 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1440 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1441 GST_DEBUG_OBJECT (parse,
1442 "entry too close to existing entry %" GST_TIME_FORMAT,
1443 GST_TIME_ARGS (prev_ts));
1444 parse->priv->index_last_offset = offset;
1445 parse->priv->index_last_ts = ts;
1451 associations[0].format = GST_FORMAT_TIME;
1452 associations[0].value = ts;
1453 associations[1].format = GST_FORMAT_BYTES;
1454 associations[1].value = offset;
1456 /* index might change on-the-fly, although that would be nutty app ... */
1457 g_static_mutex_lock (&parse->priv->index_lock);
1458 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1459 (key) ? GST_ASSOCIATION_FLAG_KEY_UNIT : GST_ASSOCIATION_FLAG_DELTA_UNIT,
1460 2, (const GstIndexAssociation *) &associations);
1461 g_static_mutex_unlock (&parse->priv->index_lock);
1464 parse->priv->index_last_offset = offset;
1465 parse->priv->index_last_ts = ts;
1474 /* check for seekable upstream, above and beyond a mere query */
1476 gst_base_parse_check_seekability (GstBaseParse * parse)
1479 gboolean seekable = FALSE;
1480 gint64 start = -1, stop = -1;
1481 guint idx_interval = 0;
1483 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1484 if (!gst_pad_peer_query (parse->sinkpad, query)) {
1485 GST_DEBUG_OBJECT (parse, "seeking query failed");
1489 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1491 /* try harder to query upstream size if we didn't get it the first time */
1492 if (seekable && stop == -1) {
1493 GstFormat fmt = GST_FORMAT_BYTES;
1495 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1496 gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop);
1499 /* if upstream doesn't know the size, it's likely that it's not seekable in
1500 * practice even if it technically may be seekable */
1501 if (seekable && (start != 0 || stop <= start)) {
1502 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1506 /* let's not put every single frame into our index */
1508 if (stop < 10 * 1024 * 1024)
1510 else if (stop < 100 * 1024 * 1024)
1513 idx_interval = 1000;
1517 gst_query_unref (query);
1519 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1520 G_GUINT64_FORMAT ")", seekable, start, stop);
1521 parse->priv->upstream_seekable = seekable;
1522 parse->priv->upstream_size = seekable ? stop : 0;
1524 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1525 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1528 /* some misc checks on upstream */
1530 gst_base_parse_check_upstream (GstBaseParse * parse)
1532 GstFormat fmt = GST_FORMAT_TIME;
1535 if (gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop))
1536 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1537 /* upstream has one, accept it also, and no further updates */
1538 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1539 parse->priv->upstream_has_duration = TRUE;
1542 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1543 parse->priv->upstream_has_duration);
1546 /* checks src caps to determine if dealing with audio or video */
1547 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1549 gst_base_parse_check_media (GstBaseParse * parse)
1554 caps = GST_PAD_CAPS (parse->srcpad);
1555 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1556 parse->priv->is_video =
1557 g_str_has_prefix (gst_structure_get_name (s), "video");
1559 /* historical default */
1560 parse->priv->is_video = FALSE;
1563 GST_DEBUG_OBJECT (parse, "media is video: %d", parse->priv->is_video);
1566 /* takes ownership of frame */
1568 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1570 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1571 /* frame allocated on the heap, we can just take ownership */
1572 g_queue_push_tail (&parse->priv->queued_frames, frame);
1573 GST_TRACE ("queued frame %p", frame);
1575 GstBaseParseFrame *copy;
1577 /* probably allocated on the stack, must make a proper copy */
1578 copy = gst_base_parse_frame_copy (frame);
1579 g_queue_push_tail (&parse->priv->queued_frames, copy);
1580 GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1581 gst_base_parse_frame_free (frame);
1585 /* gst_base_parse_handle_and_push_buffer:
1586 * @parse: #GstBaseParse.
1587 * @klass: #GstBaseParseClass.
1588 * @frame: (transfer full): a #GstBaseParseFrame
1590 * Parses the frame from given buffer and pushes it forward. Also performs
1591 * timestamp handling and checks the segment limits.
1593 * This is called with srcpad STREAM_LOCK held.
1595 * Returns: #GstFlowReturn
1597 static GstFlowReturn
1598 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1599 GstBaseParseClass * klass, GstBaseParseFrame * frame)
1605 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1607 buffer = frame->buffer;
1609 if (parse->priv->discont) {
1610 GST_DEBUG_OBJECT (parse, "marking DISCONT");
1611 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1612 parse->priv->discont = FALSE;
1615 /* some one-time start-up */
1616 if (G_UNLIKELY (!parse->priv->framecount)) {
1617 gst_base_parse_check_seekability (parse);
1618 gst_base_parse_check_upstream (parse);
1621 GST_LOG_OBJECT (parse,
1622 "parsing frame at offset %" G_GUINT64_FORMAT
1623 " (%#" G_GINT64_MODIFIER "x) of size %d",
1624 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1625 GST_BUFFER_SIZE (buffer));
1627 /* use default handler to provide initial (upstream) metadata */
1628 gst_base_parse_parse_frame (parse, frame);
1630 /* store offset as it might get overwritten */
1631 offset = GST_BUFFER_OFFSET (buffer);
1632 ret = klass->parse_frame (parse, frame);
1634 buffer = frame->buffer;
1635 /* subclass must play nice */
1636 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1638 /* check if subclass/format can provide ts.
1639 * If so, that allows and enables extra seek and duration determining options */
1640 if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
1641 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && parse->priv->has_timing_info
1642 && parse->priv->pad_mode == GST_ACTIVATE_PULL) {
1643 parse->priv->first_frame_offset = offset;
1644 parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1645 GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1646 " for first frame at offset %" G_GINT64_FORMAT,
1647 GST_TIME_ARGS (parse->priv->first_frame_ts),
1648 parse->priv->first_frame_offset);
1649 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1651 GstClockTime last_ts = G_MAXINT64;
1653 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1654 gst_base_parse_locate_time (parse, &last_ts, &off);
1655 if (GST_CLOCK_TIME_IS_VALID (last_ts))
1656 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1659 /* disable further checks */
1660 parse->priv->first_frame_offset = 0;
1664 /* again use default handler to add missing metadata;
1665 * we may have new information on frame properties */
1666 gst_base_parse_parse_frame (parse, frame);
1667 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1668 GST_BUFFER_DURATION_IS_VALID (buffer)) {
1669 parse->priv->next_ts =
1670 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1672 /* we lost track, do not produce bogus time next time around
1673 * (probably means parser subclass has given up on parsing as well) */
1674 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1675 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1678 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1679 GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1680 gst_base_parse_add_index_entry (parse, offset,
1681 GST_BUFFER_TIMESTAMP (buffer),
1682 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1684 /* First buffers are dropped, this means that the subclass needs more
1685 * frames to decide on the format and queues them internally */
1686 /* convert internal flow to OK and mark discont for the next buffer. */
1687 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1688 gst_base_parse_frame_free (frame);
1690 } else if (ret == GST_BASE_PARSE_FLOW_QUEUED) {
1691 gst_base_parse_queue_frame (parse, frame);
1693 } else if (ret != GST_FLOW_OK) {
1697 /* All OK, push queued frames if there are any */
1698 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
1699 GstBaseParseFrame *queued_frame;
1701 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
1702 queued_frame->buffer =
1703 gst_buffer_make_metadata_writable (queued_frame->buffer);
1704 gst_buffer_set_caps (queued_frame->buffer,
1705 GST_PAD_CAPS (GST_BASE_PARSE_SRC_PAD (parse)));
1706 gst_base_parse_push_frame (parse, queued_frame);
1707 gst_base_parse_frame_free (queued_frame);
1711 return gst_base_parse_push_frame (parse, frame);
1715 * gst_base_parse_push_frame:
1716 * @parse: #GstBaseParse.
1717 * @frame: (transfer full): a #GstBaseParseFrame
1719 * Pushes the frame downstream, sends any pending events and
1720 * does some timestamp and segment handling. Takes ownership
1721 * of @frame and will clear it (if it was initialised with
1722 * gst_base_parse_frame_init()) or free it.
1724 * This must be called with sinkpad STREAM_LOCK held.
1726 * Returns: #GstFlowReturn
1731 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1733 GstFlowReturn ret = GST_FLOW_OK;
1734 GstClockTime last_start = GST_CLOCK_TIME_NONE;
1735 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1736 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1739 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1740 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
1742 GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
1744 buffer = frame->buffer;
1746 GST_LOG_OBJECT (parse,
1747 "processing buffer of size %d with ts %" GST_TIME_FORMAT
1748 ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
1749 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1750 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1753 parse->priv->bytecount += GST_BUFFER_SIZE (buffer);
1754 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1755 parse->priv->framecount++;
1756 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1757 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1760 /* 0 means disabled */
1761 if (parse->priv->update_interval < 0)
1762 parse->priv->update_interval = 50;
1763 else if (parse->priv->update_interval > 0 &&
1764 (parse->priv->framecount % parse->priv->update_interval) == 0)
1765 gst_base_parse_update_duration (parse);
1767 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1768 last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1769 if (last_start != GST_CLOCK_TIME_NONE
1770 && GST_BUFFER_DURATION_IS_VALID (buffer))
1771 last_stop = last_start + GST_BUFFER_DURATION (buffer);
1773 /* should have caps by now */
1774 g_return_val_if_fail (GST_PAD_CAPS (parse->srcpad), GST_FLOW_ERROR);
1776 /* segment adjustment magic; only if we are running the whole show */
1777 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1778 (parse->priv->pad_mode == GST_ACTIVATE_PULL ||
1779 parse->priv->upstream_seekable)) {
1780 /* segment times are typically estimates,
1781 * actual frame data might lead subclass to different timestamps,
1782 * so override segment start from what is supplied there */
1783 if (G_UNLIKELY (parse->priv->pending_segment && !parse->priv->exact_position
1784 && GST_CLOCK_TIME_IS_VALID (last_start))) {
1785 gst_event_unref (parse->priv->pending_segment);
1786 parse->segment.start =
1787 MIN ((guint64) last_start, (guint64) parse->segment.stop);
1788 GST_DEBUG_OBJECT (parse,
1789 "adjusting pending segment start to %" GST_TIME_FORMAT,
1790 GST_TIME_ARGS (parse->segment.start));
1791 parse->priv->pending_segment =
1792 gst_event_new_new_segment (FALSE, parse->segment.rate,
1793 parse->segment.format, parse->segment.start,
1794 parse->segment.stop, parse->segment.start);
1796 /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1797 if (GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop) &&
1798 GST_CLOCK_TIME_IS_VALID (last_start)) {
1799 GstClockTimeDiff diff;
1801 /* only send newsegments with increasing start times,
1802 * otherwise if these go back and forth downstream (sinks) increase
1803 * accumulated time and running_time */
1804 diff = GST_CLOCK_DIFF (parse->segment.last_stop, last_start);
1805 if (G_UNLIKELY (diff > 2 * GST_SECOND
1806 && last_start > parse->segment.start
1807 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
1808 || last_start < parse->segment.stop))) {
1809 GST_DEBUG_OBJECT (parse,
1810 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
1811 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1812 "Sending updated NEWSEGMENT events", diff,
1813 GST_TIME_ARGS (parse->segment.last_stop),
1814 GST_TIME_ARGS (last_start));
1815 if (G_UNLIKELY (parse->priv->pending_segment)) {
1816 gst_event_unref (parse->priv->pending_segment);
1817 parse->segment.start = last_start;
1818 parse->priv->pending_segment =
1819 gst_event_new_new_segment (FALSE, parse->segment.rate,
1820 parse->segment.format, parse->segment.start,
1821 parse->segment.stop, parse->segment.start);
1823 /* send newsegment events such that the gap is not accounted in
1824 * accum time, hence running_time */
1825 /* close ahead of gap */
1826 gst_pad_push_event (parse->srcpad,
1827 gst_event_new_new_segment (TRUE, parse->segment.rate,
1828 parse->segment.format, parse->segment.last_stop,
1829 parse->segment.last_stop, parse->segment.last_stop));
1831 gst_pad_push_event (parse->srcpad,
1832 gst_event_new_new_segment (FALSE, parse->segment.rate,
1833 parse->segment.format, last_start,
1834 parse->segment.stop, last_start));
1836 /* align segment view with downstream,
1837 * prevents double-counting accum when closing segment */
1838 gst_segment_set_newsegment (&parse->segment, FALSE,
1839 parse->segment.rate, parse->segment.format, last_start,
1840 parse->segment.stop, last_start);
1841 parse->segment.last_stop = 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 GstEvent *pending_segment;
1856 pending_segment = parse->priv->pending_segment;
1857 parse->priv->pending_segment = NULL;
1859 GST_DEBUG_OBJECT (parse, "%s push pending segment",
1860 parse->priv->pad_mode == GST_ACTIVATE_PULL ? "loop" : "chain");
1861 gst_pad_push_event (parse->srcpad, pending_segment);
1863 /* have caps; check identity */
1864 gst_base_parse_check_media (parse);
1867 /* update bitrates and optionally post corresponding tags
1868 * (following newsegment) */
1869 gst_base_parse_update_bitrates (parse, frame);
1871 if (G_UNLIKELY (parse->priv->pending_events)) {
1874 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1875 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1877 g_list_free (parse->priv->pending_events);
1878 parse->priv->pending_events = NULL;
1881 if (klass->pre_push_frame) {
1882 ret = klass->pre_push_frame (parse, frame);
1884 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
1887 /* take final ownership of frame buffer */
1888 buffer = frame->buffer;
1889 frame->buffer = NULL;
1891 /* subclass must play nice */
1892 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1895 buffer = gst_buffer_make_metadata_writable (buffer);
1896 gst_buffer_set_caps (buffer, GST_PAD_CAPS (parse->srcpad));
1898 parse->priv->seen_keyframe |= parse->priv->is_video &&
1899 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1901 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
1902 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1903 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
1904 GST_BUFFER_TIMESTAMP (buffer) >
1905 parse->segment.stop + parse->priv->lead_out_ts) {
1906 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
1907 ret = GST_FLOW_UNEXPECTED;
1908 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1909 GST_BUFFER_DURATION_IS_VALID (buffer) &&
1910 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
1911 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
1912 parse->priv->lead_in_ts < parse->segment.start) {
1913 if (parse->priv->seen_keyframe) {
1914 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
1917 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
1918 ret = GST_BASE_PARSE_FLOW_DROPPED;
1925 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1926 GST_LOG_OBJECT (parse, "frame (%d bytes) dropped",
1927 GST_BUFFER_SIZE (buffer));
1928 gst_buffer_unref (buffer);
1930 } else if (ret == GST_FLOW_OK) {
1931 if (parse->segment.rate > 0.0) {
1932 GST_LOG_OBJECT (parse, "pushing frame (%d bytes) now..",
1933 GST_BUFFER_SIZE (buffer));
1934 ret = gst_pad_push (parse->srcpad, buffer);
1935 GST_LOG_OBJECT (parse, "frame pushed, flow %s", gst_flow_get_name (ret));
1937 GST_LOG_OBJECT (parse, "frame (%d bytes) queued for now",
1938 GST_BUFFER_SIZE (buffer));
1939 parse->priv->buffers_queued =
1940 g_slist_prepend (parse->priv->buffers_queued, buffer);
1944 GST_LOG_OBJECT (parse, "frame (%d bytes) not pushed: %s",
1945 GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
1946 gst_buffer_unref (buffer);
1947 /* if we are not sufficiently in control, let upstream decide on EOS */
1948 if (ret == GST_FLOW_UNEXPECTED &&
1949 (parse->priv->passthrough ||
1950 (parse->priv->pad_mode == GST_ACTIVATE_PUSH &&
1951 !parse->priv->upstream_seekable)))
1955 /* Update current running segment position */
1956 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
1957 parse->segment.last_stop < last_stop)
1958 gst_segment_set_last_stop (&parse->segment, GST_FORMAT_TIME, last_stop);
1960 gst_base_parse_frame_free (frame);
1966 /* gst_base_parse_drain:
1968 * Drains the adapter until it is empty. It decreases the min_frame_size to
1969 * match the current adapter size and calls chain method until the adapter
1970 * is emptied or chain returns with error.
1973 gst_base_parse_drain (GstBaseParse * parse)
1977 GST_DEBUG_OBJECT (parse, "draining");
1978 parse->priv->drain = TRUE;
1981 avail = gst_adapter_available (parse->priv->adapter);
1985 if (gst_base_parse_chain (parse->sinkpad, NULL) != GST_FLOW_OK) {
1989 /* nothing changed, maybe due to truncated frame; break infinite loop */
1990 if (avail == gst_adapter_available (parse->priv->adapter)) {
1991 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
1992 gst_adapter_clear (parse->priv->adapter);
1996 parse->priv->drain = FALSE;
1999 /* gst_base_parse_send_buffers
2001 * Sends buffers collected in send_buffers downstream, and ensures that list
2002 * is empty at the end (errors or not).
2004 static GstFlowReturn
2005 gst_base_parse_send_buffers (GstBaseParse * parse)
2007 GSList *send = NULL;
2009 GstFlowReturn ret = GST_FLOW_OK;
2011 send = parse->priv->buffers_send;
2015 buf = GST_BUFFER_CAST (send->data);
2016 GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
2017 GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2018 ", offset %" G_GINT64_FORMAT, buf,
2019 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2020 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2022 /* iterate output queue an push downstream */
2023 ret = gst_pad_push (parse->srcpad, buf);
2024 send = g_slist_delete_link (send, send);
2026 /* clear any leftover if error */
2027 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2029 buf = GST_BUFFER_CAST (send->data);
2030 gst_buffer_unref (buf);
2031 send = g_slist_delete_link (send, send);
2036 parse->priv->buffers_send = send;
2041 /* gst_base_parse_process_fragment:
2043 * Processes a reverse playback (forward) fragment:
2044 * - append head of last fragment that was skipped to current fragment data
2045 * - drain the resulting current fragment data (i.e. repeated chain)
2046 * - add time/duration (if needed) to frames queued by chain
2047 * - push queued data
2049 static GstFlowReturn
2050 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
2053 GstFlowReturn ret = GST_FLOW_OK;
2054 gboolean seen_key = FALSE, seen_delta = FALSE;
2060 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2061 while (parse->priv->buffers_pending) {
2062 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2063 GST_LOG_OBJECT (parse, "adding pending buffer (size %d)",
2064 GST_BUFFER_SIZE (buf));
2065 gst_adapter_push (parse->priv->adapter, buf);
2066 parse->priv->buffers_pending =
2067 g_slist_delete_link (parse->priv->buffers_pending,
2068 parse->priv->buffers_pending);
2071 /* invalidate so no fall-back timestamping is performed;
2072 * ok if taken from subclass or upstream */
2073 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
2074 /* prevent it hanging around stop all the time */
2075 parse->segment.last_stop = GST_CLOCK_TIME_NONE;
2077 parse->priv->discont = TRUE;
2079 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2080 /* initial skipped data is added to buffers_pending */
2081 gst_base_parse_drain (parse);
2084 if (parse->priv->buffers_send) {
2085 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2086 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2089 /* add metadata (if needed to queued buffers */
2090 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2091 GST_TIME_ARGS (parse->priv->last_ts));
2092 while (parse->priv->buffers_queued) {
2093 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2095 /* no touching if upstream or parsing provided time */
2096 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2097 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2098 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2099 } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
2100 GST_BUFFER_DURATION_IS_VALID (buf)) {
2101 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
2102 parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
2104 parse->priv->last_ts = 0;
2105 GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
2106 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2107 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2109 /* no idea, very bad */
2110 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2113 parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
2115 /* reverse order for ascending sending */
2116 /* send downstream at keyframe not preceded by a keyframe
2117 * (e.g. that should identify start of collection of IDR nals) */
2118 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2120 ret = gst_base_parse_send_buffers (parse);
2121 /* if a problem, throw all to sending */
2122 if (ret != GST_FLOW_OK) {
2123 parse->priv->buffers_send =
2124 g_slist_reverse (parse->priv->buffers_queued);
2125 parse->priv->buffers_queued = NULL;
2134 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2136 parse->priv->buffers_send =
2137 g_slist_prepend (parse->priv->buffers_send, buf);
2138 parse->priv->buffers_queued =
2139 g_slist_delete_link (parse->priv->buffers_queued,
2140 parse->priv->buffers_queued);
2143 /* audio may have all marked as keyframe, so arrange to send here */
2145 ret = gst_base_parse_send_buffers (parse);
2147 /* any trailing unused no longer usable (ideally none) */
2148 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2149 GST_DEBUG_OBJECT (parse, "discarding %d trailing bytes",
2150 gst_adapter_available (parse->priv->adapter));
2151 gst_adapter_clear (parse->priv->adapter);
2157 /* small helper that checks whether we have been trying to resync too long */
2158 static inline GstFlowReturn
2159 gst_base_parse_check_sync (GstBaseParse * parse)
2161 if (G_UNLIKELY (parse->priv->discont &&
2162 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2163 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2164 ("Failed to parse stream"), (NULL));
2165 return GST_FLOW_ERROR;
2171 static GstFlowReturn
2172 gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
2174 GstBaseParseClass *bclass;
2175 GstBaseParse *parse;
2176 GstFlowReturn ret = GST_FLOW_OK;
2177 GstBuffer *outbuf = NULL;
2178 GstBuffer *tmpbuf = NULL;
2182 guint old_min_size = 0, min_size, av;
2183 GstClockTime timestamp;
2184 GstBaseParseFrame *frame;
2186 parse = GST_BASE_PARSE (GST_OBJECT_PARENT (pad));
2187 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2188 frame = &parse->priv->frame;
2190 if (G_LIKELY (buffer)) {
2191 GST_LOG_OBJECT (parse, "buffer size: %d, offset = %" G_GINT64_FORMAT,
2192 GST_BUFFER_SIZE (buffer), GST_BUFFER_OFFSET (buffer));
2193 if (G_UNLIKELY (parse->priv->passthrough)) {
2194 gst_base_parse_frame_init (frame);
2195 frame->buffer = gst_buffer_make_metadata_writable (buffer);
2196 return gst_base_parse_push_frame (parse, frame);
2198 /* upstream feeding us in reverse playback;
2199 * gather each fragment, then process it in single run */
2200 if (parse->segment.rate < 0.0) {
2201 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2202 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2203 ret = gst_base_parse_process_fragment (parse, FALSE);
2205 gst_adapter_push (parse->priv->adapter, buffer);
2208 gst_adapter_push (parse->priv->adapter, buffer);
2211 if (G_UNLIKELY (buffer &&
2212 GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2213 frame->_private_flags |= GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
2214 gst_base_parse_frame_free (frame);
2217 /* Parse and push as many frames as possible */
2218 /* Stop either when adapter is empty or we are flushing */
2219 while (!parse->priv->flushing) {
2222 /* maintain frame state for a single frame parsing round across _chain calls,
2223 * so only init when needed */
2224 if (!frame->_private_flags)
2225 gst_base_parse_frame_init (frame);
2227 tmpbuf = gst_buffer_new ();
2230 /* Synchronization loop */
2232 /* note: if subclass indicates MAX fsize,
2233 * this will not likely be available anyway ... */
2234 min_size = MAX (parse->priv->min_frame_size, fsize);
2235 av = gst_adapter_available (parse->priv->adapter);
2237 /* loop safety check */
2238 if (G_UNLIKELY (old_min_size >= min_size))
2240 old_min_size = min_size;
2242 if (G_UNLIKELY (parse->priv->drain)) {
2244 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2245 if (G_UNLIKELY (!min_size)) {
2246 gst_buffer_unref (tmpbuf);
2251 /* Collect at least min_frame_size bytes */
2252 if (av < min_size) {
2253 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
2255 gst_buffer_unref (tmpbuf);
2259 /* always pass all available data */
2260 data = gst_adapter_peek (parse->priv->adapter, av);
2261 GST_BUFFER_DATA (tmpbuf) = (guint8 *) data;
2262 GST_BUFFER_SIZE (tmpbuf) = av;
2263 GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
2264 GST_BUFFER_FLAG_SET (tmpbuf, GST_MINI_OBJECT_FLAG_READONLY);
2266 if (parse->priv->discont) {
2267 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2268 GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2272 gst_base_parse_frame_update (parse, frame, tmpbuf);
2273 res = bclass->check_valid_frame (parse, frame, &fsize, &skip);
2274 gst_buffer_replace (&frame->buffer, NULL);
2276 if (gst_adapter_available (parse->priv->adapter) < fsize) {
2277 GST_DEBUG_OBJECT (parse,
2278 "found valid frame but not enough data available (only %d bytes)",
2279 gst_adapter_available (parse->priv->adapter));
2280 gst_buffer_unref (tmpbuf);
2283 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2287 /* subclass didn't touch this value. By default we skip 1 byte */
2291 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2292 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2293 /* reverse playback, and no frames found yet, so we are skipping
2294 * the leading part of a fragment, which may form the tail of
2295 * fragment coming later, hopefully subclass skips efficiently ... */
2296 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2297 outbuf = gst_adapter_take_buffer (parse->priv->adapter, skip);
2298 outbuf = gst_buffer_make_metadata_writable (outbuf);
2299 GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
2300 parse->priv->buffers_pending =
2301 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2304 gst_adapter_flush (parse->priv->adapter, skip);
2306 parse->priv->offset += skip;
2307 if (!parse->priv->discont)
2308 parse->priv->sync_offset = parse->priv->offset;
2309 parse->priv->discont = TRUE;
2310 /* something changed least; nullify loop check */
2313 /* skip == 0 should imply subclass set min_size to need more data;
2314 * we check this shortly */
2315 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2316 gst_buffer_unref (tmpbuf);
2320 gst_buffer_unref (tmpbuf);
2324 /* Subclass found the sync, but still wants to skip some data */
2325 GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
2326 gst_adapter_flush (parse->priv->adapter, skip);
2327 parse->priv->offset += skip;
2330 /* Grab lock to prevent a race with FLUSH_START handler */
2331 GST_PAD_STREAM_LOCK (parse->srcpad);
2333 /* FLUSH_START event causes the "flushing" flag to be set. In this
2334 * case we can leave the frame pushing loop */
2335 if (parse->priv->flushing) {
2336 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2340 /* move along with upstream timestamp (if any),
2341 * but interpolate in between */
2342 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2343 if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2344 (parse->priv->prev_ts != timestamp)) {
2345 parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2348 /* FIXME: Would it be more efficient to make a subbuffer instead? */
2349 outbuf = gst_adapter_take_buffer (parse->priv->adapter, fsize);
2350 outbuf = gst_buffer_make_metadata_writable (outbuf);
2352 /* Subclass may want to know the data offset */
2353 GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2354 parse->priv->offset += fsize;
2355 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2356 GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
2358 frame->buffer = outbuf;
2359 ret = gst_base_parse_handle_and_push_frame (parse, bclass, frame);
2360 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2362 if (ret != GST_FLOW_OK) {
2363 GST_LOG_OBJECT (parse, "push returned %d", ret);
2369 GST_LOG_OBJECT (parse, "chain leaving");
2375 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2376 ("min_size evolution %d -> %d; breaking to avoid looping",
2377 old_min_size, min_size));
2378 return GST_FLOW_ERROR;
2382 /* pull @size bytes at current offset,
2383 * i.e. at least try to and possibly return a shorter buffer if near the end */
2384 static GstFlowReturn
2385 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2386 GstBuffer ** buffer)
2388 GstFlowReturn ret = GST_FLOW_OK;
2390 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2392 /* Caching here actually makes much less difference than one would expect.
2393 * We do it mainly to avoid pulling buffers of 1 byte all the time */
2394 if (parse->priv->cache) {
2395 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2396 gint cache_size = GST_BUFFER_SIZE (parse->priv->cache);
2398 if (cache_offset <= parse->priv->offset &&
2399 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2400 *buffer = gst_buffer_create_sub (parse->priv->cache,
2401 parse->priv->offset - cache_offset, size);
2402 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2405 /* not enough data in the cache, free cache and get a new one */
2406 gst_buffer_unref (parse->priv->cache);
2407 parse->priv->cache = NULL;
2410 /* refill the cache */
2412 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2413 64 * 1024), &parse->priv->cache);
2414 if (ret != GST_FLOW_OK) {
2415 parse->priv->cache = NULL;
2419 if (GST_BUFFER_SIZE (parse->priv->cache) >= size) {
2420 *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
2421 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2425 /* Not possible to get enough data, try a last time with
2426 * requesting exactly the size we need */
2427 gst_buffer_unref (parse->priv->cache);
2428 parse->priv->cache = NULL;
2430 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2431 &parse->priv->cache);
2433 if (ret != GST_FLOW_OK) {
2434 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2439 if (GST_BUFFER_SIZE (parse->priv->cache) < size) {
2440 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2441 G_GUINT64_FORMAT ": wanted %u bytes, got %u bytes", parse->priv->offset,
2442 size, GST_BUFFER_SIZE (parse->priv->cache));
2444 *buffer = parse->priv->cache;
2445 parse->priv->cache = NULL;
2450 *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
2451 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2456 static GstFlowReturn
2457 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2460 GstClockTime ts = 0;
2464 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2465 ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2466 parse->priv->last_offset);
2468 if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2469 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2470 GST_TIME_ARGS (parse->segment.start));
2471 ret = GST_FLOW_UNEXPECTED;
2475 /* last fragment started at last_offset / last_ts;
2476 * seek back 10s capped at 1MB */
2477 if (parse->priv->last_ts >= 10 * GST_SECOND)
2478 ts = parse->priv->last_ts - 10 * GST_SECOND;
2479 /* if we are exact now, we will be more so going backwards */
2480 if (parse->priv->exact_position) {
2481 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2483 GstFormat dstformat = GST_FORMAT_BYTES;
2485 if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2486 &dstformat, &offset)) {
2487 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2490 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2491 parse->priv->last_offset - 1024);
2492 offset = MAX (0, offset);
2494 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2496 parse->priv->offset = offset;
2498 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2500 if (ret != GST_FLOW_OK)
2503 /* offset will increase again as fragment is processed/parsed */
2504 parse->priv->last_offset = offset;
2506 gst_adapter_push (parse->priv->adapter, buffer);
2507 ret = gst_base_parse_process_fragment (parse, FALSE);
2508 if (ret != GST_FLOW_OK)
2511 /* force previous fragment */
2512 parse->priv->offset = -1;
2519 * pull and scan for next frame starting from current offset
2520 * ajusts sync, drain and offset going along */
2521 static GstFlowReturn
2522 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2523 GstBaseParseFrame * frame, gboolean full)
2525 GstBuffer *buffer, *outbuf;
2526 GstFlowReturn ret = GST_FLOW_OK;
2527 guint fsize = 1, min_size, old_min_size = 0;
2530 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2532 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2533 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2535 /* let's make this efficient for all subclass once and for all;
2536 * maybe it does not need this much, but in the latter case, we know we are
2537 * in pull mode here and might as well try to read and supply more anyway
2538 * (so does the buffer caching mechanism) */
2544 min_size = MAX (parse->priv->min_frame_size, fsize);
2545 /* loop safety check */
2546 if (G_UNLIKELY (old_min_size >= min_size))
2548 old_min_size = min_size;
2550 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2551 if (ret != GST_FLOW_OK)
2554 if (parse->priv->discont) {
2555 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2556 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2559 /* if we got a short read, inform subclass we are draining leftover
2560 * and no more is to be expected */
2561 if (GST_BUFFER_SIZE (buffer) < min_size)
2562 parse->priv->drain = TRUE;
2565 gst_base_parse_frame_update (parse, frame, buffer);
2566 res = klass->check_valid_frame (parse, frame, &fsize, &skip);
2567 gst_buffer_replace (&frame->buffer, NULL);
2569 parse->priv->drain = FALSE;
2570 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2573 parse->priv->drain = FALSE;
2577 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2578 if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2579 /* reverse playback, and no frames found yet, so we are skipping
2580 * the leading part of a fragment, which may form the tail of
2581 * fragment coming later, hopefully subclass skips efficiently ... */
2582 outbuf = gst_buffer_create_sub (buffer, 0, skip);
2583 parse->priv->buffers_pending =
2584 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2587 parse->priv->offset += skip;
2588 if (!parse->priv->discont)
2589 parse->priv->sync_offset = parse->priv->offset;
2590 parse->priv->discont = TRUE;
2591 /* something changed at least; nullify loop check */
2592 if (fsize == G_MAXUINT)
2593 fsize = old_min_size + 64 * 1024;
2596 /* skip == 0 should imply subclass set min_size to need more data;
2597 * we check this shortly */
2598 GST_DEBUG_OBJECT (parse, "finding sync...");
2599 gst_buffer_unref (buffer);
2600 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2605 /* Does the subclass want to skip too? */
2607 parse->priv->offset += skip;
2611 if (fsize + skip <= GST_BUFFER_SIZE (buffer)) {
2612 outbuf = gst_buffer_create_sub (buffer, skip, fsize);
2613 GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2614 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2615 gst_buffer_unref (buffer);
2617 gst_buffer_unref (buffer);
2618 ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2619 if (ret != GST_FLOW_OK)
2621 if (GST_BUFFER_SIZE (outbuf) < fsize) {
2622 gst_buffer_unref (outbuf);
2623 ret = GST_FLOW_UNEXPECTED;
2627 parse->priv->offset += fsize;
2629 frame->buffer = outbuf;
2637 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2638 ("min_size evolution %d -> %d; breaking to avoid looping",
2639 old_min_size, min_size));
2640 return GST_FLOW_ERROR;
2644 /* Loop that is used in pull mode to retrieve data from upstream */
2646 gst_base_parse_loop (GstPad * pad)
2648 GstBaseParse *parse;
2649 GstBaseParseClass *klass;
2650 GstFlowReturn ret = GST_FLOW_OK;
2651 GstBaseParseFrame frame;
2653 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2654 klass = GST_BASE_PARSE_GET_CLASS (parse);
2656 /* reverse playback:
2657 * first fragment (closest to stop time) is handled normally below,
2658 * then we pull in fragments going backwards */
2659 if (parse->segment.rate < 0.0) {
2660 /* check if we jumped back to a previous fragment,
2661 * which is a post-first fragment */
2662 if (parse->priv->offset < 0) {
2663 ret = gst_base_parse_handle_previous_fragment (parse);
2668 gst_base_parse_frame_init (&frame);
2669 ret = gst_base_parse_scan_frame (parse, klass, &frame, TRUE);
2670 if (ret != GST_FLOW_OK)
2673 /* This always cleans up frame, even if error occurs */
2674 ret = gst_base_parse_handle_and_push_frame (parse, klass, &frame);
2676 /* eat expected eos signalling past segment in reverse playback */
2677 if (parse->segment.rate < 0.0 && ret == GST_FLOW_UNEXPECTED &&
2678 parse->segment.last_stop >= parse->segment.stop) {
2679 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2680 /* push what was accumulated during loop run */
2681 gst_base_parse_process_fragment (parse, TRUE);
2682 /* force previous fragment */
2683 parse->priv->offset = -1;
2688 if (ret == GST_FLOW_UNEXPECTED)
2690 else if (ret != GST_FLOW_OK)
2693 gst_object_unref (parse);
2699 ret = GST_FLOW_UNEXPECTED;
2700 GST_DEBUG_OBJECT (parse, "eos");
2705 gboolean push_eos = FALSE;
2707 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2708 gst_flow_get_name (ret));
2709 gst_pad_pause_task (parse->sinkpad);
2711 if (ret == GST_FLOW_UNEXPECTED) {
2712 /* handle end-of-stream/segment */
2713 if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2716 if ((stop = parse->segment.stop) == -1)
2717 stop = parse->segment.duration;
2719 GST_DEBUG_OBJECT (parse, "sending segment_done");
2721 gst_element_post_message
2722 (GST_ELEMENT_CAST (parse),
2723 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2724 GST_FORMAT_TIME, stop));
2726 /* If we STILL have zero frames processed, fire an error */
2727 if (parse->priv->framecount == 0) {
2728 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2729 ("No valid frames found before end of stream"), (NULL));
2733 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
2734 /* for fatal errors we post an error message, wrong-state is
2735 * not fatal because it happens due to flushes and only means
2736 * that we should stop now. */
2737 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2738 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2742 /* newsegment before eos */
2743 if (parse->priv->pending_segment) {
2744 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
2745 parse->priv->pending_segment = NULL;
2747 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2749 gst_object_unref (parse);
2754 gst_base_parse_sink_activate (GstPad * sinkpad)
2756 GstBaseParse *parse;
2757 gboolean result = TRUE;
2759 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2761 GST_DEBUG_OBJECT (parse, "sink activate");
2763 if (gst_pad_check_pull_range (sinkpad)) {
2764 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2765 result = gst_pad_activate_pull (sinkpad, TRUE);
2767 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
2768 result = gst_pad_activate_push (sinkpad, TRUE);
2771 GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
2772 gst_object_unref (parse);
2777 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
2779 GstBaseParseClass *klass;
2780 gboolean result = TRUE;
2782 GST_DEBUG_OBJECT (parse, "activate %d", active);
2784 klass = GST_BASE_PARSE_GET_CLASS (parse);
2787 if (parse->priv->pad_mode == GST_ACTIVATE_NONE && klass->start)
2788 result = klass->start (parse);
2790 /* We must make sure streaming has finished before resetting things
2791 * and calling the ::stop vfunc */
2792 GST_PAD_STREAM_LOCK (parse->sinkpad);
2793 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2795 if (parse->priv->pad_mode != GST_ACTIVATE_NONE && klass->stop)
2796 result = klass->stop (parse);
2798 parse->priv->pad_mode = GST_ACTIVATE_NONE;
2800 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
2805 gst_base_parse_sink_activate_push (GstPad * pad, gboolean active)
2807 gboolean result = TRUE;
2808 GstBaseParse *parse;
2810 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2812 GST_DEBUG_OBJECT (parse, "sink activate push %d", active);
2814 result = gst_base_parse_activate (parse, active);
2817 parse->priv->pad_mode = active ? GST_ACTIVATE_PUSH : GST_ACTIVATE_NONE;
2819 GST_DEBUG_OBJECT (parse, "sink activate push return: %d", result);
2821 gst_object_unref (parse);
2826 gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
2828 gboolean result = FALSE;
2829 GstBaseParse *parse;
2831 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2833 GST_DEBUG_OBJECT (parse, "activate pull %d", active);
2835 result = gst_base_parse_activate (parse, active);
2839 parse->priv->pending_segment = gst_event_new_new_segment (FALSE,
2840 parse->segment.rate, parse->segment.format,
2841 parse->segment.start, parse->segment.stop, parse->segment.last_stop);
2843 gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
2846 result &= gst_pad_stop_task (sinkpad);
2851 parse->priv->pad_mode = active ? GST_ACTIVATE_PULL : GST_ACTIVATE_NONE;
2853 GST_DEBUG_OBJECT (parse, "sink activate pull return: %d", result);
2855 gst_object_unref (parse);
2861 * gst_base_parse_set_duration:
2862 * @parse: #GstBaseParse.
2864 * @duration: duration value.
2865 * @interval: how often to update the duration estimate based on bitrate, or 0.
2867 * Sets the duration of the currently playing media. Subclass can use this
2868 * when it is able to determine duration and/or notices a change in the media
2869 * duration. Alternatively, if @interval is non-zero (default), then stream
2870 * duration is determined based on estimated bitrate, and updated every @interval
2876 gst_base_parse_set_duration (GstBaseParse * parse,
2877 GstFormat fmt, gint64 duration, gint interval)
2879 g_return_if_fail (parse != NULL);
2881 if (parse->priv->upstream_has_duration) {
2882 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
2886 if (duration != parse->priv->duration) {
2889 m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
2890 gst_element_post_message (GST_ELEMENT (parse), m);
2892 /* TODO: what about duration tag? */
2894 parse->priv->duration = duration;
2895 parse->priv->duration_fmt = fmt;
2896 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
2897 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
2898 if (interval != 0) {
2899 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
2903 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
2904 parse->priv->update_interval = interval;
2910 * gst_base_parse_set_average_bitrate:
2911 * @parse: #GstBaseParse.
2912 * @bitrate: average bitrate in bits/second
2914 * Optionally sets the average bitrate detected in media (if non-zero),
2915 * e.g. based on metadata, as it will be posted to the application.
2917 * By default, announced average bitrate is estimated. The average bitrate
2918 * is used to estimate the total duration of the stream and to estimate
2919 * a seek position, if there's no index and the format is syncable
2920 * (see gst_base_parse_set_syncable()).
2925 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
2927 parse->priv->bitrate = bitrate;
2928 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
2932 * gst_base_parse_set_min_frame_size:
2933 * @parse: #GstBaseParse.
2934 * @min_size: Minimum size of the data that this base class should give to
2937 * Subclass can use this function to tell the base class that it needs to
2938 * give at least #min_size buffers.
2943 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
2945 g_return_if_fail (parse != NULL);
2947 parse->priv->min_frame_size = min_size;
2948 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
2952 * gst_base_parse_set_frame_rate:
2953 * @parse: the #GstBaseParse to set
2954 * @fps_num: frames per second (numerator).
2955 * @fps_den: frames per second (denominator).
2956 * @lead_in: frames needed before a segment for subsequent decode
2957 * @lead_out: frames needed after a segment
2959 * If frames per second is configured, parser can take care of buffer duration
2960 * and timestamping. When performing segment clipping, or seeking to a specific
2961 * location, a corresponding decoder might need an initial @lead_in and a
2962 * following @lead_out number of frames to ensure the desired segment is
2963 * entirely filled upon decoding.
2968 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
2969 guint fps_den, guint lead_in, guint lead_out)
2971 g_return_if_fail (parse != NULL);
2973 parse->priv->fps_num = fps_num;
2974 parse->priv->fps_den = fps_den;
2975 if (!fps_num || !fps_den) {
2976 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
2978 fps_num = fps_den = 0;
2979 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
2980 parse->priv->lead_in = parse->priv->lead_out = 0;
2981 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
2983 parse->priv->frame_duration =
2984 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
2985 parse->priv->lead_in = lead_in;
2986 parse->priv->lead_out = lead_out;
2987 parse->priv->lead_in_ts =
2988 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
2989 parse->priv->lead_out_ts =
2990 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
2991 /* aim for about 1.5s to estimate duration */
2992 if (parse->priv->update_interval < 0) {
2993 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
2994 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
2995 parse->priv->update_interval);
2998 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
2999 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
3000 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
3001 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
3002 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
3003 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
3007 * gst_base_parse_set_has_timing_info:
3008 * @parse: a #GstBaseParse
3009 * @has_timing: whether frames carry timing information
3011 * Set if frames carry timing information which the subclass can (generally)
3012 * parse and provide. In particular, intrinsic (rather than estimated) time
3013 * can be obtained following a seek.
3018 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3020 parse->priv->has_timing_info = has_timing;
3021 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3025 * gst_base_parse_set_syncable:
3026 * @parse: a #GstBaseParse
3027 * @syncable: set if frame starts can be identified
3029 * Set if frame starts can be identified. This is set by default and
3030 * determines whether seeking based on bitrate averages
3031 * is possible for a format/stream.
3036 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3038 parse->priv->syncable = syncable;
3039 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3043 * gst_base_parse_set_passthrough:
3044 * @parse: a #GstBaseParse
3045 * @passthrough: %TRUE if parser should run in passthrough mode
3047 * Set if the nature of the format or configuration does not allow (much)
3048 * parsing, and the parser should operate in passthrough mode (which only
3049 * applies when operating in push mode). That is, incoming buffers are
3050 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3051 * callbacks will be invoked, but @pre_push_buffer will still be invoked,
3052 * so subclass can perform as much or as little is appropriate for
3053 * passthrough semantics in @pre_push_buffer.
3058 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3060 parse->priv->passthrough = passthrough;
3061 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3065 * gst_base_parse_set_latency:
3066 * @parse: a #GstBaseParse
3067 * @min_latency: minimum parse latency
3068 * @max_latency: maximum parse latency
3070 * Sets the minimum and maximum (which may likely be equal) latency introduced
3071 * by the parsing process. If there is such a latency, which depends on the
3072 * particular parsing of the format, it typically corresponds to 1 frame duration.
3077 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3078 GstClockTime max_latency)
3080 GST_OBJECT_LOCK (parse);
3081 parse->priv->min_latency = min_latency;
3082 parse->priv->max_latency = max_latency;
3083 GST_OBJECT_UNLOCK (parse);
3084 GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3085 GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3086 GST_TIME_ARGS (max_latency));
3090 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3091 GstClockTime * duration)
3093 gboolean res = FALSE;
3095 g_return_val_if_fail (duration != NULL, FALSE);
3097 *duration = GST_CLOCK_TIME_NONE;
3098 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3099 GST_LOG_OBJECT (parse, "using provided duration");
3100 *duration = parse->priv->duration;
3102 } else if (parse->priv->duration != -1) {
3103 GST_LOG_OBJECT (parse, "converting provided duration");
3104 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3105 parse->priv->duration, format, (gint64 *) duration);
3106 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3107 GST_LOG_OBJECT (parse, "using estimated duration");
3108 *duration = parse->priv->estimated_duration;
3112 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3113 GST_TIME_ARGS (*duration));
3117 static const GstQueryType *
3118 gst_base_parse_get_querytypes (GstPad * pad)
3120 static const GstQueryType list[] = {
3133 gst_base_parse_query (GstPad * pad, GstQuery * query)
3135 GstBaseParse *parse;
3136 gboolean res = FALSE;
3138 parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3140 GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3142 switch (GST_QUERY_TYPE (query)) {
3143 case GST_QUERY_POSITION:
3148 GST_DEBUG_OBJECT (parse, "position query");
3149 gst_query_parse_position (query, &format, NULL);
3151 /* try upstream first */
3152 res = gst_pad_query_default (pad, query);
3154 /* Fall back on interpreting segment */
3155 GST_OBJECT_LOCK (parse);
3156 if (format == GST_FORMAT_BYTES) {
3157 dest_value = parse->priv->offset;
3159 } else if (format == parse->segment.format &&
3160 GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop)) {
3161 dest_value = gst_segment_to_stream_time (&parse->segment,
3162 parse->segment.format, parse->segment.last_stop);
3165 GST_OBJECT_UNLOCK (parse);
3167 /* no precise result, upstream no idea either, then best estimate */
3168 /* priv->offset is updated in both PUSH/PULL modes */
3169 res = gst_base_parse_convert (parse,
3170 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3173 gst_query_set_position (query, format, dest_value);
3177 case GST_QUERY_DURATION:
3180 GstClockTime duration;
3182 GST_DEBUG_OBJECT (parse, "duration query");
3183 gst_query_parse_duration (query, &format, NULL);
3185 /* consult upstream */
3186 res = gst_pad_query_default (pad, query);
3188 /* otherwise best estimate from us */
3190 res = gst_base_parse_get_duration (parse, format, &duration);
3192 gst_query_set_duration (query, format, duration);
3196 case GST_QUERY_SEEKING:
3199 GstClockTime duration = GST_CLOCK_TIME_NONE;
3200 gboolean seekable = FALSE;
3202 GST_DEBUG_OBJECT (parse, "seeking query");
3203 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3205 /* consult upstream */
3206 res = gst_pad_query_default (pad, query);
3208 /* we may be able to help if in TIME */
3209 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3210 gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3211 /* already OK if upstream takes care */
3212 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3214 if (!(res && seekable)) {
3215 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3216 || duration == -1) {
3217 /* seekable if we still have a chance to get duration later on */
3219 parse->priv->upstream_seekable && parse->priv->update_interval;
3221 seekable = parse->priv->upstream_seekable;
3222 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3225 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3231 case GST_QUERY_FORMATS:
3232 gst_query_set_formatsv (query, 3, fmtlist);
3235 case GST_QUERY_CONVERT:
3237 GstFormat src_format, dest_format;
3238 gint64 src_value, dest_value;
3240 gst_query_parse_convert (query, &src_format, &src_value,
3241 &dest_format, &dest_value);
3243 res = gst_base_parse_convert (parse, src_format, src_value,
3244 dest_format, &dest_value);
3246 gst_query_set_convert (query, src_format, src_value,
3247 dest_format, dest_value);
3251 case GST_QUERY_LATENCY:
3253 if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3255 GstClockTime min_latency, max_latency;
3257 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3258 GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3259 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3260 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3262 GST_OBJECT_LOCK (parse);
3263 /* add our latency */
3264 if (min_latency != -1)
3265 min_latency += parse->priv->min_latency;
3266 if (max_latency != -1)
3267 max_latency += parse->priv->max_latency;
3268 GST_OBJECT_UNLOCK (parse);
3270 gst_query_set_latency (query, live, min_latency, max_latency);
3275 res = gst_pad_query_default (pad, query);
3281 /* scans for a cluster start from @pos,
3282 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3283 static GstFlowReturn
3284 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3285 GstClockTime * time, GstClockTime * duration)
3287 GstBaseParseClass *klass;
3289 gboolean orig_drain, orig_discont;
3290 GstFlowReturn ret = GST_FLOW_OK;
3291 GstBuffer *buf = NULL;
3292 GstBaseParseFrame frame;
3294 g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3295 g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3296 g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3298 klass = GST_BASE_PARSE_GET_CLASS (parse);
3300 *time = GST_CLOCK_TIME_NONE;
3301 *duration = GST_CLOCK_TIME_NONE;
3304 orig_offset = parse->priv->offset;
3305 orig_discont = parse->priv->discont;
3306 orig_drain = parse->priv->drain;
3308 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3309 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3311 gst_base_parse_frame_init (&frame);
3313 /* jump elsewhere and locate next frame */
3314 parse->priv->offset = *pos;
3315 ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3316 if (ret != GST_FLOW_OK)
3320 GST_LOG_OBJECT (parse,
3321 "peek parsing frame at offset %" G_GUINT64_FORMAT
3322 " (%#" G_GINT64_MODIFIER "x) of size %d",
3323 GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf), GST_BUFFER_SIZE (buf));
3325 /* get offset first, subclass parsing might dump other stuff in there */
3326 *pos = GST_BUFFER_OFFSET (buf);
3327 ret = klass->parse_frame (parse, &frame);
3330 /* but it should provide proper time */
3331 *time = GST_BUFFER_TIMESTAMP (buf);
3332 *duration = GST_BUFFER_DURATION (buf);
3334 gst_base_parse_frame_free (&frame);
3336 GST_LOG_OBJECT (parse,
3337 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3338 GST_TIME_ARGS (*time), *pos);
3342 parse->priv->offset = orig_offset;
3343 parse->priv->discont = orig_discont;
3344 parse->priv->drain = orig_drain;
3349 /* bisect and scan through file for frame starting before @time,
3350 * returns OK and @time/@offset if found, NONE and/or error otherwise
3351 * If @time == G_MAXINT64, scan for duration ( == last frame) */
3352 static GstFlowReturn
3353 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3356 GstFlowReturn ret = GST_FLOW_OK;
3357 gint64 lpos, hpos, newpos;
3358 GstClockTime time, ltime, htime, newtime, dur;
3359 gboolean cont = TRUE;
3360 const GstClockTime tolerance = TARGET_DIFFERENCE;
3361 const guint chunk = 4 * 1024;
3363 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3364 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3366 /* TODO also make keyframe aware if useful some day */
3381 /* do not know at first */
3383 *_time = GST_CLOCK_TIME_NONE;
3385 /* need initial positions; start and end */
3386 lpos = parse->priv->first_frame_offset;
3387 ltime = parse->priv->first_frame_ts;
3388 htime = parse->priv->duration;
3389 hpos = parse->priv->upstream_size;
3391 /* check preconditions are satisfied;
3392 * start and end are needed, except for special case where we scan for
3393 * last frame to determine duration */
3394 if (parse->priv->pad_mode != GST_ACTIVATE_PULL || !hpos ||
3395 !GST_CLOCK_TIME_IS_VALID (ltime) ||
3396 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3400 /* shortcut cases */
3403 } else if (time < ltime + tolerance) {
3407 } else if (time >= htime) {
3413 while (htime > ltime && cont) {
3414 GST_LOG_OBJECT (parse,
3415 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3416 GST_TIME_ARGS (ltime));
3417 GST_LOG_OBJECT (parse,
3418 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3419 GST_TIME_ARGS (htime));
3420 if (G_UNLIKELY (time == G_MAXINT64)) {
3422 } else if (G_LIKELY (hpos > lpos)) {
3424 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3427 /* should mean lpos == hpos, since lpos <= hpos is invariant */
3429 /* we check this case once, but not forever, so break loop */
3434 newpos = CLAMP (newpos, lpos, hpos);
3435 GST_LOG_OBJECT (parse,
3436 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3437 GST_TIME_ARGS (time), newpos);
3439 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3440 if (ret == GST_FLOW_UNEXPECTED) {
3441 /* heuristic HACK */
3442 hpos = MAX (lpos, hpos - chunk);
3444 } else if (ret != GST_FLOW_OK) {
3448 if (newtime == -1 || newpos == -1) {
3449 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3453 if (G_UNLIKELY (time == G_MAXINT64)) {
3456 if (GST_CLOCK_TIME_IS_VALID (dur))
3459 } else if (newtime > time) {
3461 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3463 } else if (newtime + tolerance > time) {
3464 /* close enough undershoot */
3468 } else if (newtime < ltime) {
3469 /* so a position beyond lpos resulted in earlier time than ltime ... */
3470 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3473 /* undershoot too far */
3474 newpos += newpos == lpos ? chunk : 0;
3475 lpos = CLAMP (newpos, lpos, hpos);
3481 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3482 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3487 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3488 gboolean before, GstClockTime * _ts)
3490 gint64 bytes = 0, ts = 0;
3491 GstIndexEntry *entry = NULL;
3493 if (time == GST_CLOCK_TIME_NONE) {
3499 g_static_mutex_lock (&parse->priv->index_lock);
3500 if (parse->priv->index) {
3501 /* Let's check if we have an index entry for that time */
3502 entry = gst_index_get_assoc_entry (parse->priv->index,
3503 parse->priv->index_id,
3504 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3505 GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3509 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3510 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3512 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3513 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3514 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3516 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3517 GST_TIME_ARGS (time));
3520 ts = GST_CLOCK_TIME_NONE;
3523 g_static_mutex_unlock (&parse->priv->index_lock);
3532 /* returns TRUE if seek succeeded */
3534 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3539 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3540 gboolean flush, update, res = TRUE, accurate;
3541 gint64 cur, stop, seekpos, seekstop;
3542 GstSegment seeksegment = { 0, };
3543 GstFormat dstformat;
3544 GstClockTime start_ts;
3546 gst_event_parse_seek (event, &rate, &format, &flags,
3547 &cur_type, &cur, &stop_type, &stop);
3549 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3550 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3551 GST_TIME_FORMAT, gst_format_get_name (format), rate,
3552 cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3554 /* no negative rates in push mode */
3555 if (rate < 0.0 && parse->priv->pad_mode == GST_ACTIVATE_PUSH)
3558 if (cur_type != GST_SEEK_TYPE_SET ||
3559 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3562 /* For any format other than TIME, see if upstream handles
3563 * it directly or fail. For TIME, try upstream, but do it ourselves if
3564 * it fails upstream */
3565 if (format != GST_FORMAT_TIME) {
3566 /* default action delegates to upstream */
3570 gst_event_ref (event);
3571 if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3576 /* get flush flag */
3577 flush = flags & GST_SEEK_FLAG_FLUSH;
3579 /* copy segment, we need this because we still need the old
3580 * segment when we close the current segment. */
3581 memcpy (&seeksegment, &parse->segment, sizeof (GstSegment));
3583 GST_DEBUG_OBJECT (parse, "configuring seek");
3584 gst_segment_set_seek (&seeksegment, rate, format, flags,
3585 cur_type, cur, stop_type, stop, &update);
3587 /* accurate seeking implies seek tables are used to obtain position,
3588 * and the requested segment is maintained exactly, not adjusted any way */
3589 accurate = flags & GST_SEEK_FLAG_ACCURATE;
3591 /* maybe we can be accurate for (almost) free */
3592 gst_base_parse_find_offset (parse, seeksegment.last_stop, TRUE, &start_ts);
3593 if (seeksegment.last_stop <= start_ts + TARGET_DIFFERENCE) {
3594 GST_DEBUG_OBJECT (parse, "accurate seek possible");
3598 GstClockTime startpos = seeksegment.last_stop;
3600 /* accurate requested, so ... seek a bit before target */
3601 if (startpos < parse->priv->lead_in_ts)
3604 startpos -= parse->priv->lead_in_ts;
3605 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3606 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3609 start_ts = seeksegment.last_stop;
3610 dstformat = GST_FORMAT_BYTES;
3611 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.last_stop,
3612 &dstformat, &seekpos))
3613 goto convert_failed;
3614 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3615 &dstformat, &seekstop))
3616 goto convert_failed;
3619 GST_DEBUG_OBJECT (parse,
3620 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3622 GST_DEBUG_OBJECT (parse,
3623 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3624 seeksegment.stop, seekstop);
3626 if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
3629 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3632 if (parse->srcpad) {
3633 GST_DEBUG_OBJECT (parse, "sending flush start");
3634 gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3635 /* unlock upstream pull_range */
3636 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3639 gst_pad_pause_task (parse->sinkpad);
3642 /* we should now be able to grab the streaming thread because we stopped it
3643 * with the above flush/pause code */
3644 GST_PAD_STREAM_LOCK (parse->sinkpad);
3646 /* save current position */
3647 last_stop = parse->segment.last_stop;
3648 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3651 /* now commit to new position */
3653 /* prepare for streaming again */
3655 GST_DEBUG_OBJECT (parse, "sending flush stop");
3656 gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop ());
3657 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop ());
3658 gst_base_parse_clear_queues (parse);
3660 if (parse->priv->close_segment)
3661 gst_event_unref (parse->priv->close_segment);
3663 parse->priv->close_segment = gst_event_new_new_segment (TRUE,
3664 parse->segment.rate, parse->segment.format,
3665 parse->segment.accum, parse->segment.last_stop, parse->segment.accum);
3667 /* keep track of our last_stop */
3668 seeksegment.accum = parse->segment.last_stop;
3670 GST_DEBUG_OBJECT (parse, "Created close seg format %d, "
3671 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3672 ", pos = %" GST_TIME_FORMAT, format,
3673 GST_TIME_ARGS (parse->segment.accum),
3674 GST_TIME_ARGS (parse->segment.last_stop),
3675 GST_TIME_ARGS (parse->segment.accum));
3678 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3680 /* store the newsegment event so it can be sent from the streaming thread. */
3681 if (parse->priv->pending_segment)
3682 gst_event_unref (parse->priv->pending_segment);
3684 /* This will be sent later in _loop() */
3685 parse->priv->pending_segment =
3686 gst_event_new_new_segment (FALSE, parse->segment.rate,
3687 parse->segment.format, parse->segment.start,
3688 parse->segment.stop, parse->segment.start);
3690 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3691 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3692 ", pos = %" GST_TIME_FORMAT, format,
3693 GST_TIME_ARGS (parse->segment.start),
3694 GST_TIME_ARGS (parse->segment.stop),
3695 GST_TIME_ARGS (parse->segment.start));
3697 /* one last chance in pull mode to stay accurate;
3698 * maybe scan and subclass can find where to go */
3701 GstClockTime ts = seeksegment.last_stop;
3703 gst_base_parse_locate_time (parse, &ts, &scanpos);
3707 /* running collected index now consists of several intervals,
3708 * so optimized check no longer possible */
3709 parse->priv->index_last_valid = FALSE;
3710 parse->priv->index_last_offset = 0;
3711 parse->priv->index_last_ts = 0;
3715 /* mark discont if we are going to stream from another position. */
3716 if (seekpos != parse->priv->offset) {
3717 GST_DEBUG_OBJECT (parse,
3718 "mark DISCONT, we did a seek to another position");
3719 parse->priv->offset = seekpos;
3720 parse->priv->last_offset = seekpos;
3721 parse->priv->seen_keyframe = FALSE;
3722 parse->priv->discont = TRUE;
3723 parse->priv->next_ts = start_ts;
3724 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3725 parse->priv->sync_offset = seekpos;
3726 parse->priv->exact_position = accurate;
3729 /* Start streaming thread if paused */
3730 gst_pad_start_task (parse->sinkpad,
3731 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3733 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3738 GstEvent *new_event;
3739 GstBaseParseSeek *seek;
3740 GstSeekFlags flags = (flush ? GST_SEEK_FLAG_FLUSH : GST_SEEK_FLAG_NONE);
3742 /* The only thing we need to do in PUSH-mode is to send the
3743 seek event (in bytes) to upstream. Segment / flush handling happens
3744 in corresponding src event handlers */
3745 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3746 if (seekstop >= 0 && seekpos <= seekpos)
3748 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
3749 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3751 /* store segment info so its precise details can be reconstructed when
3752 * receiving newsegment;
3753 * this matters for all details when accurate seeking,
3754 * is most useful to preserve NONE stop time otherwise */
3755 seek = g_new0 (GstBaseParseSeek, 1);
3756 seek->segment = seeksegment;
3757 seek->accurate = accurate;
3758 seek->offset = seekpos;
3759 seek->start_ts = start_ts;
3760 GST_OBJECT_LOCK (parse);
3761 /* less optimal, but preserves order */
3762 parse->priv->pending_seeks =
3763 g_slist_append (parse->priv->pending_seeks, seek);
3764 GST_OBJECT_UNLOCK (parse);
3766 res = gst_pad_push_event (parse->sinkpad, new_event);
3769 GST_OBJECT_LOCK (parse);
3770 parse->priv->pending_seeks =
3771 g_slist_remove (parse->priv->pending_seeks, seek);
3772 GST_OBJECT_UNLOCK (parse);
3778 /* handled event is ours to free */
3780 gst_event_unref (event);
3786 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
3792 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3798 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3804 /* Checks if bitrates are available from upstream tags so that we don't
3805 * override them later
3808 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
3810 GstTagList *taglist = NULL;
3813 gst_event_parse_tag (event, &taglist);
3815 if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
3816 GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
3817 parse->priv->post_min_bitrate = FALSE;
3819 if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
3820 GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
3821 parse->priv->post_avg_bitrate = FALSE;
3823 if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
3824 GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
3825 parse->priv->post_max_bitrate = FALSE;
3830 gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps)
3832 GstBaseParse *parse;
3833 GstBaseParseClass *klass;
3834 gboolean res = TRUE;
3836 parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3837 klass = GST_BASE_PARSE_GET_CLASS (parse);
3839 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
3841 if (klass->set_sink_caps)
3842 res = klass->set_sink_caps (parse, caps);
3848 gst_base_parse_set_index (GstElement * element, GstIndex * index)
3850 GstBaseParse *parse = GST_BASE_PARSE (element);
3852 g_static_mutex_lock (&parse->priv->index_lock);
3853 if (parse->priv->index)
3854 gst_object_unref (parse->priv->index);
3856 parse->priv->index = gst_object_ref (index);
3857 gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
3858 &parse->priv->index_id);
3859 parse->priv->own_index = FALSE;
3861 parse->priv->index = NULL;
3863 g_static_mutex_unlock (&parse->priv->index_lock);
3867 gst_base_parse_get_index (GstElement * element)
3869 GstBaseParse *parse = GST_BASE_PARSE (element);
3870 GstIndex *result = NULL;
3872 g_static_mutex_lock (&parse->priv->index_lock);
3873 if (parse->priv->index)
3874 result = gst_object_ref (parse->priv->index);
3875 g_static_mutex_unlock (&parse->priv->index_lock);
3880 static GstStateChangeReturn
3881 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
3883 GstBaseParse *parse;
3884 GstStateChangeReturn result;
3886 parse = GST_BASE_PARSE (element);
3888 switch (transition) {
3889 case GST_STATE_CHANGE_READY_TO_PAUSED:
3890 /* If this is our own index destroy it as the
3891 * old entries might be wrong for the new stream */
3892 g_static_mutex_lock (&parse->priv->index_lock);
3893 if (parse->priv->own_index) {
3894 gst_object_unref (parse->priv->index);
3895 parse->priv->index = NULL;
3896 parse->priv->own_index = FALSE;
3899 /* If no index was created, generate one */
3900 if (G_UNLIKELY (!parse->priv->index)) {
3901 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
3903 parse->priv->index = gst_index_factory_make ("memindex");
3904 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
3905 &parse->priv->index_id);
3906 parse->priv->own_index = TRUE;
3908 g_static_mutex_unlock (&parse->priv->index_lock);
3914 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3916 switch (transition) {
3917 case GST_STATE_CHANGE_PAUSED_TO_READY:
3918 gst_base_parse_reset (parse);