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. The passed buffer
86 * is read-only. Note that @check_valid_frame might receive any small
87 * amount of input data when leftover data is being drained (e.g. at EOS).
90 * After valid frame is found, it will be passed again to subclass with
91 * @parse_frame call. Now subclass is responsible for parsing the
92 * frame contents and setting the caps, and buffer metadata (e.g.
93 * buffer timestamp and duration, or keyframe if applicable).
94 * (although the latter can also be done by GstBaseParse if it is
95 * appropriately configured, see below). Frame is provided with
96 * timestamp derived from upstream (as much as generally possible),
97 * duration obtained from configuration (see below), and offset
98 * if meaningful (in pull mode).
101 * Finally the buffer can be pushed downstream and the parsing loop starts
102 * over again. Just prior to actually pushing the buffer in question,
103 * it is passed to @pre_push_buffer which gives subclass yet one
104 * last chance to examine buffer metadata, or to send some custom (tag)
105 * events, or to perform custom (segment) filtering.
108 * During the parsing process GstBaseParseClass will handle both srcpad
109 * and sinkpad events. They will be passed to subclass if @event or
110 * @src_event callbacks have been provided.
115 * <itemizedlist><title>Shutdown phase</title>
117 * GstBaseParse class calls @stop to inform the subclass that data
118 * parsing will be stopped.
124 * Subclass is responsible for providing pad template caps for
125 * source and sink pads. The pads need to be named "sink" and "src". It also
126 * needs to set the fixed caps on srcpad, when the format is ensured (e.g.
127 * when base class calls subclass' @set_sink_caps function).
129 * This base class uses #GST_FORMAT_DEFAULT as a meaning of frames. So,
130 * subclass conversion routine needs to know that conversion from
131 * #GST_FORMAT_TIME to #GST_FORMAT_DEFAULT must return the
132 * frame number that can be found from the given byte position.
134 * GstBaseParse uses subclasses conversion methods also for seeking (or
135 * otherwise uses its own default one, see also below).
137 * Subclass @start and @stop functions will be called to inform the beginning
138 * and end of data processing.
140 * Things that subclass need to take care of:
142 * <listitem><para>Provide pad templates</para></listitem>
144 * Fixate the source pad caps when appropriate
147 * Inform base class how big data chunks should be retrieved. This is
148 * done with gst_base_parse_set_min_frame_size() function.
151 * Examine data chunks passed to subclass with @check_valid_frame
152 * and tell if they contain a valid frame
155 * Set the caps and timestamp to frame that is passed to subclass with
156 * @parse_frame function.
158 * <listitem><para>Provide conversion functions</para></listitem>
160 * Update the duration information with gst_base_parse_set_duration()
163 * Optionally passthrough using gst_base_parse_set_passthrough()
166 * Configure various baseparse parameters using
167 * gst_base_parse_set_average_bitrate(), gst_base_parse_set_syncable()
168 * and gst_base_parse_set_frame_rate().
171 * In particular, if subclass is unable to determine a duration, but
172 * parsing (or specs) yields a frames per seconds rate, then this can be
173 * provided to GstBaseParse to enable it to cater for
174 * buffer time metadata (which will be taken from upstream as much as
175 * possible). Internally keeping track of frame durations and respective
176 * sizes that have been pushed provides GstBaseParse with an estimated
177 * bitrate. A default @convert (used if not overriden) will then use these
178 * rates to perform obvious conversions. These rates are also used to
179 * update (estimated) duration at regular frame intervals.
186 * - In push mode provide a queue of adapter-"queued" buffers for upstream
188 * - Queue buffers/events until caps are set
198 #include <gst/base/gstadapter.h>
200 #include "gstbaseparse.h"
202 #define GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC (1 << 0)
204 #define MIN_FRAMES_TO_POST_BITRATE 10
205 #define TARGET_DIFFERENCE (20 * GST_SECOND)
207 GST_DEBUG_CATEGORY_STATIC (gst_base_parse_debug);
208 #define GST_CAT_DEFAULT gst_base_parse_debug
210 /* Supported formats */
211 static const GstFormat fmtlist[] = {
218 #define GST_BASE_PARSE_GET_PRIVATE(obj) \
219 (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_PARSE, GstBaseParsePrivate))
221 struct _GstBaseParsePrivate
223 GstActivateMode pad_mode;
228 GstFormat duration_fmt;
229 gint64 estimated_duration;
231 guint min_frame_size;
232 gboolean passthrough;
234 gboolean has_timing_info;
235 guint fps_num, fps_den;
236 gint update_interval;
238 guint lead_in, lead_out;
239 GstClockTime lead_in_ts, lead_out_ts;
247 GstClockTime next_ts;
248 GstClockTime prev_ts;
249 GstClockTime frame_duration;
250 gboolean seen_keyframe;
255 guint64 data_bytecount;
256 guint64 acc_duration;
257 GstClockTime first_frame_ts;
258 gint64 first_frame_offset;
260 gboolean post_min_bitrate;
261 gboolean post_avg_bitrate;
262 gboolean post_max_bitrate;
266 guint posted_avg_bitrate;
268 GList *pending_events;
270 /* frames/buffers that are queued and ready to go on OK */
271 GQueue queued_frames;
275 /* index entry storage, either ours or provided */
279 GStaticMutex index_lock;
281 /* seek table entries only maintained if upstream is BYTE seekable */
282 gboolean upstream_seekable;
283 gboolean upstream_has_duration;
284 gint64 upstream_size;
285 /* minimum distance between two index entries */
286 GstClockTimeDiff idx_interval;
287 /* ts and offset of last entry added */
288 GstClockTime index_last_ts;
289 gint64 index_last_offset;
290 gboolean index_last_valid;
292 /* timestamps currently produced are accurate, e.g. started from 0 onwards */
293 gboolean exact_position;
294 /* seek events are temporarily kept to match them with newsegments */
295 GSList *pending_seeks;
297 /* reverse playback */
298 GSList *buffers_pending;
299 GSList *buffers_queued;
300 GSList *buffers_send;
301 GstClockTime last_ts;
304 /* Newsegment event to be sent after SEEK */
305 GstEvent *pending_segment;
307 /* Segment event that closes the running segment prior to SEEK */
308 GstEvent *close_segment;
311 typedef struct _GstBaseParseSeek
316 GstClockTime start_ts;
319 static GstElementClass *parent_class = NULL;
321 static void gst_base_parse_class_init (GstBaseParseClass * klass);
322 static void gst_base_parse_init (GstBaseParse * parse,
323 GstBaseParseClass * klass);
326 gst_base_parse_get_type (void)
328 static volatile gsize base_parse_type = 0;
330 if (g_once_init_enter (&base_parse_type)) {
331 static const GTypeInfo base_parse_info = {
332 sizeof (GstBaseParseClass),
333 (GBaseInitFunc) NULL,
334 (GBaseFinalizeFunc) NULL,
335 (GClassInitFunc) gst_base_parse_class_init,
338 sizeof (GstBaseParse),
340 (GInstanceInitFunc) gst_base_parse_init,
344 _type = g_type_register_static (GST_TYPE_ELEMENT,
345 "GstBaseParse", &base_parse_info, G_TYPE_FLAG_ABSTRACT);
346 g_once_init_leave (&base_parse_type, _type);
348 return (GType) base_parse_type;
351 static void gst_base_parse_finalize (GObject * object);
353 static GstStateChangeReturn gst_base_parse_change_state (GstElement * element,
354 GstStateChange transition);
355 static void gst_base_parse_reset (GstBaseParse * parse);
357 static void gst_base_parse_set_index (GstElement * element, GstIndex * index);
358 static GstIndex *gst_base_parse_get_index (GstElement * element);
360 static gboolean gst_base_parse_sink_activate (GstPad * sinkpad);
361 static gboolean gst_base_parse_sink_activate_push (GstPad * pad,
363 static gboolean gst_base_parse_sink_activate_pull (GstPad * pad,
365 static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
367 static void gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event);
369 static gboolean gst_base_parse_src_event (GstPad * pad, GstEvent * event);
370 static gboolean gst_base_parse_sink_event (GstPad * pad, GstEvent * event);
371 static gboolean gst_base_parse_query (GstPad * pad, GstQuery ** query);
372 static gboolean gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps);
373 static const GstQueryType *gst_base_parse_get_querytypes (GstPad * pad);
375 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstBuffer * buffer);
376 static void gst_base_parse_loop (GstPad * pad);
378 static gboolean gst_base_parse_check_frame (GstBaseParse * parse,
379 GstBaseParseFrame * frame, guint * framesize, gint * skipsize);
380 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
381 GstBaseParseFrame * frame);
383 static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
386 static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
389 static void gst_base_parse_drain (GstBaseParse * parse);
391 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
392 gboolean post_min, gboolean post_avg, gboolean post_max);
394 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
395 GstClockTime time, gboolean before, GstClockTime * _ts);
396 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
397 GstClockTime * _time, gint64 * _offset);
399 static GstFlowReturn gst_base_parse_process_fragment (GstBaseParse * parse,
402 static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);
405 gst_base_parse_clear_queues (GstBaseParse * parse)
407 g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
408 g_slist_free (parse->priv->buffers_queued);
409 parse->priv->buffers_queued = NULL;
410 g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
412 g_slist_free (parse->priv->buffers_pending);
413 parse->priv->buffers_pending = NULL;
414 g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
415 g_slist_free (parse->priv->buffers_send);
416 parse->priv->buffers_send = NULL;
420 gst_base_parse_finalize (GObject * object)
422 GstBaseParse *parse = GST_BASE_PARSE (object);
425 g_object_unref (parse->priv->adapter);
427 if (parse->priv->pending_segment) {
428 p_ev = &parse->priv->pending_segment;
429 gst_event_replace (p_ev, NULL);
431 if (parse->priv->close_segment) {
432 p_ev = &parse->priv->close_segment;
433 gst_event_replace (p_ev, NULL);
436 if (parse->priv->cache) {
437 gst_buffer_unref (parse->priv->cache);
438 parse->priv->cache = NULL;
441 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
443 g_list_free (parse->priv->pending_events);
444 parse->priv->pending_events = NULL;
446 g_queue_foreach (&parse->priv->queued_frames,
447 (GFunc) gst_base_parse_frame_free, NULL);
448 g_queue_clear (&parse->priv->queued_frames);
450 if (parse->priv->index) {
451 gst_object_unref (parse->priv->index);
452 parse->priv->index = NULL;
455 g_static_mutex_free (&parse->priv->index_lock);
457 gst_base_parse_clear_queues (parse);
459 G_OBJECT_CLASS (parent_class)->finalize (object);
463 gst_base_parse_class_init (GstBaseParseClass * klass)
465 GObjectClass *gobject_class;
466 GstElementClass *gstelement_class;
468 gobject_class = G_OBJECT_CLASS (klass);
469 g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
470 parent_class = g_type_class_peek_parent (klass);
471 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
473 gstelement_class = (GstElementClass *) klass;
474 gstelement_class->change_state =
475 GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
476 gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
477 gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
479 /* Default handlers */
480 klass->check_valid_frame = gst_base_parse_check_frame;
481 klass->parse_frame = gst_base_parse_parse_frame;
482 klass->src_event = gst_base_parse_src_eventfunc;
483 klass->convert = gst_base_parse_convert_default;
485 GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
486 "baseparse element");
490 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
492 GstPadTemplate *pad_template;
494 GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
496 parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
499 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
500 g_return_if_fail (pad_template != NULL);
501 parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
502 gst_pad_set_event_function (parse->sinkpad,
503 GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
504 gst_pad_set_setcaps_function (parse->sinkpad,
505 GST_DEBUG_FUNCPTR (gst_base_parse_sink_setcaps));
506 gst_pad_set_chain_function (parse->sinkpad,
507 GST_DEBUG_FUNCPTR (gst_base_parse_chain));
508 gst_pad_set_activate_function (parse->sinkpad,
509 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
510 gst_pad_set_activatepush_function (parse->sinkpad,
511 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_push));
512 gst_pad_set_activatepull_function (parse->sinkpad,
513 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_pull));
514 gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
516 GST_DEBUG_OBJECT (parse, "sinkpad created");
519 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
520 g_return_if_fail (pad_template != NULL);
521 parse->srcpad = gst_pad_new_from_template (pad_template, "src");
522 gst_pad_set_event_function (parse->srcpad,
523 GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
524 gst_pad_set_query_type_function (parse->srcpad,
525 GST_DEBUG_FUNCPTR (gst_base_parse_get_querytypes));
526 gst_pad_set_query_function (parse->srcpad,
527 GST_DEBUG_FUNCPTR (gst_base_parse_query));
528 gst_pad_use_fixed_caps (parse->srcpad);
529 gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
530 GST_DEBUG_OBJECT (parse, "src created");
532 g_queue_init (&parse->priv->queued_frames);
534 parse->priv->adapter = gst_adapter_new ();
536 parse->priv->pad_mode = GST_ACTIVATE_NONE;
538 g_static_mutex_init (&parse->priv->index_lock);
541 gst_base_parse_reset (parse);
542 GST_DEBUG_OBJECT (parse, "init ok");
545 static GstBaseParseFrame *
546 gst_base_parse_frame_copy (GstBaseParseFrame * frame)
548 GstBaseParseFrame *copy;
550 copy = g_slice_dup (GstBaseParseFrame, frame);
551 copy->buffer = gst_buffer_ref (frame->buffer);
552 copy->_private_flags &= ~GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
554 GST_TRACE ("copied frame %p -> %p", frame, copy);
560 gst_base_parse_frame_free (GstBaseParseFrame * frame)
562 GST_TRACE ("freeing frame %p", frame);
565 gst_buffer_unref (frame->buffer);
566 frame->buffer = NULL;
569 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC))
570 g_slice_free (GstBaseParseFrame, frame);
574 gst_base_parse_frame_get_type (void)
576 static volatile gsize frame_type = 0;
578 if (g_once_init_enter (&frame_type)) {
581 _type = g_boxed_type_register_static ("GstBaseParseFrame",
582 (GBoxedCopyFunc) gst_base_parse_frame_copy,
583 (GBoxedFreeFunc) gst_base_parse_frame_free);
584 g_once_init_leave (&frame_type, _type);
586 return (GType) frame_type;
590 * gst_base_parse_frame_init:
591 * @frame: #GstBaseParseFrame.
593 * Sets a #GstBaseParseFrame to initial state. Currently this means
594 * all public fields are zero-ed and a private flag is set to make
595 * sure gst_base_parse_frame_free() only frees the contents but not
596 * the actual frame. Use this function to initialise a #GstBaseParseFrame
597 * allocated on the stack.
602 gst_base_parse_frame_init (GstBaseParseFrame * frame)
604 memset (frame, 0, sizeof (GstBaseParseFrame));
605 frame->_private_flags = GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
606 GST_TRACE ("inited frame %p", frame);
610 * gst_base_parse_frame_new:
611 * @buffer: (transfer none): a #GstBuffer
613 * @overhead: number of bytes in this frame which should be counted as
614 * metadata overhead, ie. not used to calculate the average bitrate.
615 * Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
617 * Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
618 * elements written in C should usually allocate the frame on the stack and
619 * then use gst_base_parse_frame_init() to initialise it.
621 * Returns: a newly-allocated #GstBaseParseFrame. Free with
622 * gst_base_parse_frame_free() when no longer needed, unless you gave
623 * away ownership to gst_base_parse_push_frame().
628 gst_base_parse_frame_new (GstBuffer * buffer, GstBaseParseFrameFlags flags,
631 GstBaseParseFrame *frame;
633 frame = g_slice_new0 (GstBaseParseFrame);
634 frame->buffer = gst_buffer_ref (buffer);
636 GST_TRACE ("created frame %p", frame);
641 gst_base_parse_frame_update (GstBaseParse * parse, GstBaseParseFrame * frame,
644 gst_buffer_replace (&frame->buffer, buf);
648 /* set flags one by one for clarity */
649 if (G_UNLIKELY (parse->priv->drain))
650 parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;
652 /* losing sync is pretty much a discont (and vice versa), no ? */
653 if (G_UNLIKELY (parse->priv->discont))
654 parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
658 gst_base_parse_reset (GstBaseParse * parse)
660 GST_OBJECT_LOCK (parse);
661 gst_segment_init (&parse->segment, GST_FORMAT_TIME);
662 parse->priv->duration = -1;
663 parse->priv->min_frame_size = 1;
664 parse->priv->discont = TRUE;
665 parse->priv->flushing = FALSE;
666 parse->priv->offset = 0;
667 parse->priv->sync_offset = 0;
668 parse->priv->update_interval = -1;
669 parse->priv->fps_num = parse->priv->fps_den = 0;
670 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
671 parse->priv->lead_in = parse->priv->lead_out = 0;
672 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
673 parse->priv->bitrate = 0;
674 parse->priv->framecount = 0;
675 parse->priv->bytecount = 0;
676 parse->priv->acc_duration = 0;
677 parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
678 parse->priv->first_frame_offset = -1;
679 parse->priv->estimated_duration = -1;
680 parse->priv->next_ts = 0;
681 parse->priv->syncable = TRUE;
682 parse->priv->passthrough = FALSE;
683 parse->priv->has_timing_info = FALSE;
684 parse->priv->post_min_bitrate = TRUE;
685 parse->priv->post_avg_bitrate = TRUE;
686 parse->priv->post_max_bitrate = TRUE;
687 parse->priv->min_bitrate = G_MAXUINT;
688 parse->priv->max_bitrate = 0;
689 parse->priv->avg_bitrate = 0;
690 parse->priv->posted_avg_bitrate = 0;
692 parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
693 parse->priv->index_last_offset = -1;
694 parse->priv->index_last_valid = TRUE;
695 parse->priv->upstream_seekable = FALSE;
696 parse->priv->upstream_size = 0;
697 parse->priv->upstream_has_duration = FALSE;
698 parse->priv->idx_interval = 0;
699 parse->priv->exact_position = TRUE;
700 parse->priv->seen_keyframe = FALSE;
702 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
703 parse->priv->last_offset = 0;
705 if (parse->priv->pending_segment) {
706 gst_event_unref (parse->priv->pending_segment);
707 parse->priv->pending_segment = NULL;
710 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
712 g_list_free (parse->priv->pending_events);
713 parse->priv->pending_events = NULL;
715 if (parse->priv->cache) {
716 gst_buffer_unref (parse->priv->cache);
717 parse->priv->cache = NULL;
720 g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
721 g_slist_free (parse->priv->pending_seeks);
722 parse->priv->pending_seeks = NULL;
723 GST_OBJECT_UNLOCK (parse);
726 /* gst_base_parse_check_frame:
727 * @parse: #GstBaseParse.
728 * @buffer: GstBuffer.
729 * @framesize: This will be set to tell the found frame size in bytes.
730 * @skipsize: Output parameter that tells how much data needs to be skipped
731 * in order to find the following frame header.
733 * Default callback for check_valid_frame.
735 * Returns: Always TRUE.
738 gst_base_parse_check_frame (GstBaseParse * parse,
739 GstBaseParseFrame * frame, guint * framesize, gint * skipsize)
741 *framesize = gst_buffer_get_size (frame->buffer);
747 /* gst_base_parse_parse_frame:
748 * @parse: #GstBaseParse.
749 * @buffer: #GstBuffer.
751 * Default callback for parse_frame.
754 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
756 GstBuffer *buffer = frame->buffer;
758 if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
759 GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
760 GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
762 if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
763 GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
764 GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
769 /* gst_base_parse_convert:
770 * @parse: #GstBaseParse.
771 * @src_format: #GstFormat describing the source format.
772 * @src_value: Source value to be converted.
773 * @dest_format: #GstFormat defining the converted format.
774 * @dest_value: Pointer where the conversion result will be put.
776 * Converts using configured "convert" vmethod in #GstBaseParse class.
778 * Returns: TRUE if conversion was successful.
781 gst_base_parse_convert (GstBaseParse * parse,
782 GstFormat src_format,
783 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
785 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
788 g_return_val_if_fail (dest_value != NULL, FALSE);
793 ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
795 #ifndef GST_DISABLE_GST_DEBUG
798 if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
799 GST_LOG_OBJECT (parse,
800 "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
801 GST_TIME_ARGS (src_value), *dest_value);
802 } else if (dest_format == GST_FORMAT_TIME &&
803 src_format == GST_FORMAT_BYTES) {
804 GST_LOG_OBJECT (parse,
805 "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
806 src_value, GST_TIME_ARGS (*dest_value));
808 GST_LOG_OBJECT (parse,
809 "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
810 GST_STR_NULL (gst_format_get_name (src_format)),
811 GST_STR_NULL (gst_format_get_name (dest_format)),
812 src_value, *dest_value);
815 GST_DEBUG_OBJECT (parse, "conversion failed");
823 /* gst_base_parse_sink_event:
824 * @pad: #GstPad that received the event.
825 * @event: #GstEvent to be handled.
827 * Handler for sink pad events.
829 * Returns: TRUE if the event was handled.
832 gst_base_parse_sink_event (GstPad * pad, GstEvent * event)
835 GstBaseParseClass *bclass;
836 gboolean handled = FALSE;
839 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
840 bclass = GST_BASE_PARSE_GET_CLASS (parse);
842 GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
843 GST_EVENT_TYPE_NAME (event));
845 /* Cache all events except EOS, NEWSEGMENT and FLUSH_STOP if we have a
847 if (parse->priv->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
848 && GST_EVENT_TYPE (event) != GST_EVENT_NEWSEGMENT
849 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
850 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP) {
852 if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
853 /* See if any bitrate tags were posted */
854 gst_base_parse_handle_tag (parse, event);
856 parse->priv->pending_events =
857 g_list_append (parse->priv->pending_events, event);
861 if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
862 parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
863 /* We've not posted bitrate tags yet - do so now */
864 gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
867 handled = bclass->event (parse, event);
870 handled = gst_base_parse_sink_eventfunc (parse, event);
873 ret = gst_pad_event_default (pad, event);
876 gst_object_unref (parse);
877 GST_DEBUG_OBJECT (parse, "event handled");
882 /* gst_base_parse_sink_eventfunc:
883 * @parse: #GstBaseParse.
884 * @event: #GstEvent to be handled.
886 * Element-level event handler function.
888 * The event will be unreffed only if it has been handled and this
889 * function returns %TRUE
891 * Returns: %TRUE if the event was handled and not need forwarding.
894 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
896 gboolean handled = FALSE;
899 switch (GST_EVENT_TYPE (event)) {
900 case GST_EVENT_NEWSEGMENT:
902 gdouble rate, applied_rate;
904 gint64 start, stop, pos, next_ts, offset = 0;
907 gst_event_parse_new_segment (event, &update, &rate, &applied_rate,
908 &format, &start, &stop, &pos);
910 GST_DEBUG_OBJECT (parse, "newseg rate %g, applied rate %g, "
911 "format %d, start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
912 ", pos = %" GST_TIME_FORMAT, rate, applied_rate, format,
913 GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (pos));
915 if (format == GST_FORMAT_BYTES) {
916 GstClockTime seg_start, seg_stop;
917 GstBaseParseSeek *seek = NULL;
920 /* stop time is allowed to be open-ended, but not start & pos */
921 seg_stop = GST_CLOCK_TIME_NONE;
925 GST_OBJECT_LOCK (parse);
926 for (node = parse->priv->pending_seeks; node; node = node->next) {
927 GstBaseParseSeek *tmp = node->data;
929 if (tmp->offset == pos) {
934 parse->priv->pending_seeks =
935 g_slist_remove (parse->priv->pending_seeks, seek);
936 GST_OBJECT_UNLOCK (parse);
939 GST_DEBUG_OBJECT (parse,
940 "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
941 seek->accurate ? " accurate" : "", &seek->segment);
942 seg_start = seek->segment.start;
943 seg_stop = seek->segment.stop;
944 next_ts = seek->start_ts;
945 parse->priv->exact_position = seek->accurate;
948 /* best attempt convert */
949 /* as these are only estimates, stop is kept open-ended to avoid
950 * premature cutting */
951 gst_base_parse_convert (parse, GST_FORMAT_BYTES, start,
952 GST_FORMAT_TIME, (gint64 *) & seg_start);
953 parse->priv->exact_position = (start == 0);
957 gst_event_unref (event);
958 event = gst_event_new_new_segment (update, rate, applied_rate,
959 GST_FORMAT_TIME, seg_start, seg_stop, seg_start);
960 format = GST_FORMAT_TIME;
963 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. "
964 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT,
965 GST_TIME_ARGS (seg_start), GST_TIME_ARGS (seg_stop));
966 } else if (format != GST_FORMAT_TIME) {
967 /* Unknown incoming segment format. Output a default open-ended
969 gst_event_unref (event);
970 event = gst_event_new_new_segment (update, rate, applied_rate,
971 GST_FORMAT_TIME, 0, GST_CLOCK_TIME_NONE, 0);
972 format = GST_FORMAT_TIME;
974 stop = GST_CLOCK_TIME_NONE;
976 /* not considered BYTE seekable if it is talking to us in TIME,
977 * whatever else it might claim */
978 parse->priv->upstream_seekable = FALSE;
982 gst_segment_set_newsegment (&parse->segment, update, rate,
983 applied_rate, format, start, stop, start);
985 /* save the segment for later, right before we push a new buffer so that
986 * the caps are fixed and the next linked element can receive
988 eventp = &parse->priv->pending_segment;
989 gst_event_replace (eventp, event);
990 gst_event_unref (event);
993 /* but finish the current segment */
994 GST_DEBUG_OBJECT (parse, "draining current segment");
995 if (parse->segment.rate > 0.0)
996 gst_base_parse_drain (parse);
998 gst_base_parse_process_fragment (parse, FALSE);
999 gst_adapter_clear (parse->priv->adapter);
1000 parse->priv->offset = offset;
1001 parse->priv->sync_offset = offset;
1002 parse->priv->next_ts = next_ts;
1003 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1004 parse->priv->discont = TRUE;
1005 parse->priv->seen_keyframe = FALSE;
1009 case GST_EVENT_FLUSH_START:
1010 parse->priv->flushing = TRUE;
1011 handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
1013 gst_event_unref (event);
1014 /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
1015 GST_PAD_STREAM_LOCK (parse->srcpad);
1016 GST_PAD_STREAM_UNLOCK (parse->srcpad);
1020 case GST_EVENT_FLUSH_STOP:
1021 gst_adapter_clear (parse->priv->adapter);
1022 gst_base_parse_clear_queues (parse);
1023 parse->priv->flushing = FALSE;
1024 parse->priv->discont = TRUE;
1025 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1029 if (parse->segment.rate > 0.0)
1030 gst_base_parse_drain (parse);
1032 gst_base_parse_process_fragment (parse, FALSE);
1034 /* If we STILL have zero frames processed, fire an error */
1035 if (parse->priv->framecount == 0) {
1036 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1037 ("No valid frames found before end of stream"), (NULL));
1039 /* newsegment before eos */
1040 if (parse->priv->pending_segment) {
1041 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1042 parse->priv->pending_segment = NULL;
1054 /* gst_base_parse_src_event:
1055 * @pad: #GstPad that received the event.
1056 * @event: #GstEvent that was received.
1058 * Handler for source pad events.
1060 * Returns: TRUE if the event was handled.
1063 gst_base_parse_src_event (GstPad * pad, GstEvent * event)
1065 GstBaseParse *parse;
1066 GstBaseParseClass *bclass;
1067 gboolean handled = FALSE;
1068 gboolean ret = TRUE;
1070 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
1071 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1073 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1074 GST_EVENT_TYPE_NAME (event));
1076 if (bclass->src_event)
1077 handled = bclass->src_event (parse, event);
1080 ret = gst_pad_event_default (pad, event);
1082 gst_object_unref (parse);
1087 gst_base_parse_is_seekable (GstBaseParse * parse)
1089 /* FIXME: could do more here, e.g. check index or just send data from 0
1090 * in pull mode and let decoder/sink clip */
1091 return parse->priv->syncable;
1094 /* gst_base_parse_src_eventfunc:
1095 * @parse: #GstBaseParse.
1096 * @event: #GstEvent that was received.
1098 * Default srcpad event handler.
1100 * Returns: TRUE if the event was handled and can be dropped.
1103 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1105 gboolean handled = FALSE;
1107 switch (GST_EVENT_TYPE (event)) {
1108 case GST_EVENT_SEEK:
1110 if (gst_base_parse_is_seekable (parse)) {
1111 handled = gst_base_parse_handle_seek (parse, event);
1123 * gst_base_parse_convert_default:
1124 * @parse: #GstBaseParse.
1125 * @src_format: #GstFormat describing the source format.
1126 * @src_value: Source value to be converted.
1127 * @dest_format: #GstFormat defining the converted format.
1128 * @dest_value: Pointer where the conversion result will be put.
1130 * Default implementation of "convert" vmethod in #GstBaseParse class.
1132 * Returns: TRUE if conversion was successful.
1137 gst_base_parse_convert_default (GstBaseParse * parse,
1138 GstFormat src_format,
1139 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1141 gboolean ret = FALSE;
1142 guint64 bytes, duration;
1144 if (G_UNLIKELY (src_format == dest_format)) {
1145 *dest_value = src_value;
1149 if (G_UNLIKELY (src_value == -1)) {
1154 if (G_UNLIKELY (src_value == 0)) {
1159 /* need at least some frames */
1160 if (!parse->priv->framecount)
1163 duration = parse->priv->acc_duration / GST_MSECOND;
1164 bytes = parse->priv->bytecount;
1166 if (G_UNLIKELY (!duration || !bytes))
1169 if (src_format == GST_FORMAT_BYTES) {
1170 if (dest_format == GST_FORMAT_TIME) {
1171 /* BYTES -> TIME conversion */
1172 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1173 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1174 *dest_value *= GST_MSECOND;
1175 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1176 *dest_value / GST_MSECOND);
1179 } else if (src_format == GST_FORMAT_TIME) {
1180 if (dest_format == GST_FORMAT_BYTES) {
1181 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1182 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1184 GST_DEBUG_OBJECT (parse,
1185 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1186 src_value / GST_MSECOND, *dest_value);
1189 } else if (src_format == GST_FORMAT_DEFAULT) {
1190 /* DEFAULT == frame-based */
1191 if (dest_format == GST_FORMAT_TIME) {
1192 if (parse->priv->fps_den) {
1193 *dest_value = gst_util_uint64_scale (src_value,
1194 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1197 } else if (dest_format == GST_FORMAT_BYTES) {
1205 gst_base_parse_update_duration (GstBaseParse * baseparse)
1208 GstBaseParse *parse;
1210 parse = GST_BASE_PARSE (baseparse);
1212 peer = gst_pad_get_peer (parse->sinkpad);
1214 GstFormat pformat = GST_FORMAT_BYTES;
1215 gboolean qres = FALSE;
1216 gint64 ptot, dest_value;
1218 qres = gst_pad_query_duration (peer, &pformat, &ptot);
1219 gst_object_unref (GST_OBJECT (peer));
1221 if (gst_base_parse_convert (parse, pformat, ptot,
1222 GST_FORMAT_TIME, &dest_value)) {
1223 parse->priv->estimated_duration = dest_value;
1224 GST_LOG_OBJECT (parse,
1225 "updated estimated duration to %" GST_TIME_FORMAT,
1226 GST_TIME_ARGS (dest_value));
1233 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1234 gboolean post_avg, gboolean post_max)
1236 GstTagList *taglist = NULL;
1238 if (post_min && parse->priv->post_min_bitrate) {
1239 taglist = gst_tag_list_new ();
1241 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1242 GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1245 if (post_avg && parse->priv->post_avg_bitrate) {
1246 if (taglist == NULL)
1247 taglist = gst_tag_list_new ();
1249 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1250 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1251 parse->priv->avg_bitrate, NULL);
1254 if (post_max && parse->priv->post_max_bitrate) {
1255 if (taglist == NULL)
1256 taglist = gst_tag_list_new ();
1258 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1259 GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1262 GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1263 parse->priv->min_bitrate, parse->priv->avg_bitrate,
1264 parse->priv->max_bitrate);
1266 if (taglist != NULL) {
1267 gst_element_found_tags_for_pad (GST_ELEMENT_CAST (parse), parse->srcpad,
1272 /* gst_base_parse_update_bitrates:
1273 * @parse: #GstBaseParse.
1274 * @buffer: Current frame as a #GstBuffer
1276 * Keeps track of the minimum and maximum bitrates, and also maintains a
1277 * running average bitrate of the stream so far.
1280 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1282 /* Only update the tag on a 10 kbps delta */
1283 static const gint update_threshold = 10000;
1285 guint64 data_len, frame_dur;
1286 gint overhead, frame_bitrate, old_avg_bitrate;
1287 gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1288 GstBuffer *buffer = frame->buffer;
1290 overhead = frame->overhead;
1294 data_len = gst_buffer_get_size (buffer) - overhead;
1295 parse->priv->data_bytecount += data_len;
1297 /* duration should be valid by now,
1298 * either set by subclass or maybe based on fps settings */
1299 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1300 /* Calculate duration of a frame from buffer properties */
1301 frame_dur = GST_BUFFER_DURATION (buffer);
1302 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1303 parse->priv->acc_duration;
1306 /* No way to figure out frame duration (is this even possible?) */
1310 /* override if subclass provided bitrate, e.g. metadata based */
1311 if (parse->priv->bitrate) {
1312 parse->priv->avg_bitrate = parse->priv->bitrate;
1313 /* spread this (confirmed) info ASAP */
1314 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1315 gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1319 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1323 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1324 parse->priv->avg_bitrate);
1326 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1328 } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1329 /* always post all at threshold time */
1330 update_min = update_max = update_avg = TRUE;
1333 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1334 if (frame_bitrate < parse->priv->min_bitrate) {
1335 parse->priv->min_bitrate = frame_bitrate;
1339 if (frame_bitrate > parse->priv->max_bitrate) {
1340 parse->priv->max_bitrate = frame_bitrate;
1344 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1345 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1346 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1351 if ((update_min || update_avg || update_max))
1352 gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1354 /* If average bitrate changes that much and no valid (time) duration provided,
1355 * then post a new duration message so applications can update their cached
1357 if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1358 GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1359 gst_element_post_message (GST_ELEMENT (parse),
1360 gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1367 * gst_base_parse_add_index_entry:
1368 * @parse: #GstBaseParse.
1369 * @offset: offset of entry
1370 * @ts: timestamp associated with offset
1371 * @key: whether entry refers to keyframe
1372 * @force: add entry disregarding sanity checks
1374 * Adds an entry to the index associating @offset to @ts. It is recommended
1375 * to only add keyframe entries. @force allows to bypass checks, such as
1376 * whether the stream is (upstream) seekable, another entry is already "close"
1377 * to the new entry, etc.
1379 * Returns: #gboolean indicating whether entry was added
1384 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1385 GstClockTime ts, gboolean key, gboolean force)
1387 gboolean ret = FALSE;
1388 GstIndexAssociation associations[2];
1390 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1391 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1393 if (G_LIKELY (!force)) {
1395 if (!parse->priv->upstream_seekable) {
1396 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1400 /* FIXME need better helper data structure that handles these issues
1401 * related to ongoing collecting of index entries */
1402 if (parse->priv->index_last_offset >= (gint64) offset) {
1403 GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1404 "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1408 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1409 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1410 parse->priv->idx_interval) {
1411 GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1412 GST_TIME_ARGS (parse->priv->index_last_ts));
1416 /* if last is not really the last one */
1417 if (!parse->priv->index_last_valid) {
1418 GstClockTime prev_ts;
1420 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1421 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1422 GST_DEBUG_OBJECT (parse,
1423 "entry too close to existing entry %" GST_TIME_FORMAT,
1424 GST_TIME_ARGS (prev_ts));
1425 parse->priv->index_last_offset = offset;
1426 parse->priv->index_last_ts = ts;
1432 associations[0].format = GST_FORMAT_TIME;
1433 associations[0].value = ts;
1434 associations[1].format = GST_FORMAT_BYTES;
1435 associations[1].value = offset;
1437 /* index might change on-the-fly, although that would be nutty app ... */
1438 g_static_mutex_lock (&parse->priv->index_lock);
1439 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1440 (key) ? GST_ASSOCIATION_FLAG_KEY_UNIT : GST_ASSOCIATION_FLAG_DELTA_UNIT,
1441 2, (const GstIndexAssociation *) &associations);
1442 g_static_mutex_unlock (&parse->priv->index_lock);
1445 parse->priv->index_last_offset = offset;
1446 parse->priv->index_last_ts = ts;
1455 /* check for seekable upstream, above and beyond a mere query */
1457 gst_base_parse_check_seekability (GstBaseParse * parse)
1460 gboolean seekable = FALSE;
1461 gint64 start = -1, stop = -1;
1462 guint idx_interval = 0;
1464 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1465 if (!gst_pad_peer_query (parse->sinkpad, &query)) {
1466 GST_DEBUG_OBJECT (parse, "seeking query failed");
1470 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1472 /* try harder to query upstream size if we didn't get it the first time */
1473 if (seekable && stop == -1) {
1474 GstFormat fmt = GST_FORMAT_BYTES;
1476 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1477 gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop);
1480 /* if upstream doesn't know the size, it's likely that it's not seekable in
1481 * practice even if it technically may be seekable */
1482 if (seekable && (start != 0 || stop <= start)) {
1483 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1487 /* let's not put every single frame into our index */
1489 if (stop < 10 * 1024 * 1024)
1491 else if (stop < 100 * 1024 * 1024)
1494 idx_interval = 1000;
1498 gst_query_unref (query);
1500 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1501 G_GUINT64_FORMAT ")", seekable, start, stop);
1502 parse->priv->upstream_seekable = seekable;
1503 parse->priv->upstream_size = seekable ? stop : 0;
1505 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1506 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1509 /* some misc checks on upstream */
1511 gst_base_parse_check_upstream (GstBaseParse * parse)
1513 GstFormat fmt = GST_FORMAT_TIME;
1516 if (gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop))
1517 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1518 /* upstream has one, accept it also, and no further updates */
1519 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1520 parse->priv->upstream_has_duration = TRUE;
1523 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1524 parse->priv->upstream_has_duration);
1527 /* checks src caps to determine if dealing with audio or video */
1528 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1530 gst_base_parse_check_media (GstBaseParse * parse)
1535 caps = gst_pad_get_current_caps (parse->srcpad);
1536 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1537 parse->priv->is_video =
1538 g_str_has_prefix (gst_structure_get_name (s), "video");
1540 /* historical default */
1541 parse->priv->is_video = FALSE;
1544 gst_caps_unref (caps);
1546 GST_DEBUG_OBJECT (parse, "media is video == %d", parse->priv->is_video);
1549 /* takes ownership of frame */
1551 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1553 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1554 /* frame allocated on the heap, we can just take ownership */
1555 g_queue_push_tail (&parse->priv->queued_frames, frame);
1556 GST_TRACE ("queued frame %p", frame);
1558 GstBaseParseFrame *copy;
1560 /* probably allocated on the stack, must make a proper copy */
1561 copy = gst_base_parse_frame_copy (frame);
1562 g_queue_push_tail (&parse->priv->queued_frames, copy);
1563 GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1564 gst_base_parse_frame_free (frame);
1568 /* gst_base_parse_handle_and_push_buffer:
1569 * @parse: #GstBaseParse.
1570 * @klass: #GstBaseParseClass.
1571 * @frame: (transfer full): a #GstBaseParseFrame
1573 * Parses the frame from given buffer and pushes it forward. Also performs
1574 * timestamp handling and checks the segment limits.
1576 * This is called with srcpad STREAM_LOCK held.
1578 * Returns: #GstFlowReturn
1580 static GstFlowReturn
1581 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1582 GstBaseParseClass * klass, GstBaseParseFrame * frame)
1588 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1590 buffer = frame->buffer;
1592 if (parse->priv->discont) {
1593 GST_DEBUG_OBJECT (parse, "marking DISCONT");
1594 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1595 parse->priv->discont = FALSE;
1598 /* some one-time start-up */
1599 if (G_UNLIKELY (!parse->priv->framecount)) {
1600 gst_base_parse_check_seekability (parse);
1601 gst_base_parse_check_upstream (parse);
1604 GST_LOG_OBJECT (parse,
1605 "parsing frame at offset %" G_GUINT64_FORMAT
1606 " (%#" G_GINT64_MODIFIER "x) of size %d",
1607 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1608 gst_buffer_get_size (buffer));
1610 /* use default handler to provide initial (upstream) metadata */
1611 gst_base_parse_parse_frame (parse, frame);
1613 /* store offset as it might get overwritten */
1614 offset = GST_BUFFER_OFFSET (buffer);
1615 ret = klass->parse_frame (parse, frame);
1617 buffer = frame->buffer;
1618 /* subclass must play nice */
1619 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1621 /* check if subclass/format can provide ts.
1622 * If so, that allows and enables extra seek and duration determining options */
1623 if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
1624 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && parse->priv->has_timing_info
1625 && parse->priv->pad_mode == GST_ACTIVATE_PULL) {
1626 parse->priv->first_frame_offset = offset;
1627 parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1628 GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1629 " for first frame at offset %" G_GINT64_FORMAT,
1630 GST_TIME_ARGS (parse->priv->first_frame_ts),
1631 parse->priv->first_frame_offset);
1632 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1634 GstClockTime last_ts = G_MAXINT64;
1636 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1637 gst_base_parse_locate_time (parse, &last_ts, &off);
1638 if (GST_CLOCK_TIME_IS_VALID (last_ts))
1639 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1642 /* disable further checks */
1643 parse->priv->first_frame_offset = 0;
1647 /* again use default handler to add missing metadata;
1648 * we may have new information on frame properties */
1649 gst_base_parse_parse_frame (parse, frame);
1650 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1651 GST_BUFFER_DURATION_IS_VALID (buffer)) {
1652 parse->priv->next_ts =
1653 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1655 /* we lost track, do not produce bogus time next time around
1656 * (probably means parser subclass has given up on parsing as well) */
1657 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1658 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1661 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1662 GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1663 gst_base_parse_add_index_entry (parse, offset,
1664 GST_BUFFER_TIMESTAMP (buffer),
1665 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1667 /* First buffers are dropped, this means that the subclass needs more
1668 * frames to decide on the format and queues them internally */
1669 /* convert internal flow to OK and mark discont for the next buffer. */
1670 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1671 gst_base_parse_frame_free (frame);
1673 } else if (ret == GST_BASE_PARSE_FLOW_QUEUED) {
1674 gst_base_parse_queue_frame (parse, frame);
1676 } else if (ret != GST_FLOW_OK) {
1680 /* All OK, push queued frames if there are any */
1681 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
1682 GstBaseParseFrame *queued_frame;
1684 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
1685 gst_base_parse_push_frame (parse, queued_frame);
1686 gst_base_parse_frame_free (queued_frame);
1690 return gst_base_parse_push_frame (parse, frame);
1694 * gst_base_parse_push_frame:
1695 * @parse: #GstBaseParse.
1696 * @frame: (transfer full): a #GstBaseParseFrame
1698 * Pushes the frame downstream, sends any pending events and
1699 * does some timestamp and segment handling. Takes ownership
1700 * of @frame and will clear it (if it was initialised with
1701 * gst_base_parse_frame_init()) or free it.
1703 * This must be called with sinkpad STREAM_LOCK held.
1705 * Returns: #GstFlowReturn
1710 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1712 GstFlowReturn ret = GST_FLOW_OK;
1713 GstClockTime last_start = GST_CLOCK_TIME_NONE;
1714 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1715 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1719 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1720 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
1722 GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
1724 buffer = frame->buffer;
1726 GST_LOG_OBJECT (parse,
1727 "processing buffer of size %d with ts %" GST_TIME_FORMAT
1728 ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buffer),
1729 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1730 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1733 size = gst_buffer_get_size (buffer);
1734 parse->priv->bytecount += size;
1735 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1736 parse->priv->framecount++;
1737 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1738 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1741 /* 0 means disabled */
1742 if (parse->priv->update_interval < 0)
1743 parse->priv->update_interval = 50;
1744 else if (parse->priv->update_interval > 0 &&
1745 (parse->priv->framecount % parse->priv->update_interval) == 0)
1746 gst_base_parse_update_duration (parse);
1748 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1749 last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1750 if (last_start != GST_CLOCK_TIME_NONE
1751 && GST_BUFFER_DURATION_IS_VALID (buffer))
1752 last_stop = last_start + GST_BUFFER_DURATION (buffer);
1754 /* should have caps by now */
1755 g_return_val_if_fail (gst_pad_has_current_caps (parse->srcpad),
1758 /* segment adjustment magic; only if we are running the whole show */
1759 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1760 (parse->priv->pad_mode == GST_ACTIVATE_PULL ||
1761 parse->priv->upstream_seekable)) {
1762 /* segment times are typically estimates,
1763 * actual frame data might lead subclass to different timestamps,
1764 * so override segment start from what is supplied there */
1765 if (G_UNLIKELY (parse->priv->pending_segment && !parse->priv->exact_position
1766 && GST_CLOCK_TIME_IS_VALID (last_start))) {
1767 gst_event_unref (parse->priv->pending_segment);
1768 parse->segment.start =
1769 MIN ((guint64) last_start, (guint64) parse->segment.stop);
1770 GST_DEBUG_OBJECT (parse,
1771 "adjusting pending segment start to %" GST_TIME_FORMAT,
1772 GST_TIME_ARGS (parse->segment.start));
1773 parse->priv->pending_segment =
1774 gst_event_new_new_segment (FALSE, parse->segment.rate,
1775 parse->segment.applied_rate,
1776 parse->segment.format, parse->segment.start,
1777 parse->segment.stop, parse->segment.start);
1779 /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1780 if (GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop) &&
1781 GST_CLOCK_TIME_IS_VALID (last_start)) {
1782 GstClockTimeDiff diff;
1784 /* only send newsegments with increasing start times,
1785 * otherwise if these go back and forth downstream (sinks) increase
1786 * accumulated time and running_time */
1787 diff = GST_CLOCK_DIFF (parse->segment.last_stop, last_start);
1788 if (G_UNLIKELY (diff > 2 * GST_SECOND
1789 && last_start > parse->segment.start
1790 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
1791 || last_start < parse->segment.stop))) {
1792 GST_DEBUG_OBJECT (parse,
1793 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
1794 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1795 "Sending updated NEWSEGMENT events", diff,
1796 GST_TIME_ARGS (parse->segment.last_stop),
1797 GST_TIME_ARGS (last_start));
1798 if (G_UNLIKELY (parse->priv->pending_segment)) {
1799 gst_event_unref (parse->priv->pending_segment);
1800 parse->segment.start = last_start;
1801 parse->priv->pending_segment =
1802 gst_event_new_new_segment (FALSE, parse->segment.rate,
1803 parse->segment.applied_rate,
1804 parse->segment.format, parse->segment.start,
1805 parse->segment.stop, parse->segment.start);
1807 /* send newsegment events such that the gap is not accounted in
1808 * accum time, hence running_time */
1809 /* close ahead of gap */
1810 gst_pad_push_event (parse->srcpad,
1811 gst_event_new_new_segment (TRUE, parse->segment.rate,
1812 parse->segment.applied_rate,
1813 parse->segment.format, parse->segment.last_stop,
1814 parse->segment.last_stop, parse->segment.last_stop));
1816 gst_pad_push_event (parse->srcpad,
1817 gst_event_new_new_segment (FALSE, parse->segment.rate,
1818 parse->segment.applied_rate,
1819 parse->segment.format, last_start,
1820 parse->segment.stop, last_start));
1822 /* align segment view with downstream,
1823 * prevents double-counting accum when closing segment */
1824 gst_segment_set_newsegment (&parse->segment, FALSE,
1825 parse->segment.rate, parse->segment.applied_rate,
1826 parse->segment.format, last_start, parse->segment.stop, last_start);
1827 parse->segment.last_stop = last_start;
1832 /* and should then also be linked downstream, so safe to send some events */
1833 if (G_UNLIKELY (parse->priv->close_segment)) {
1834 /* only set up by loop */
1835 GST_DEBUG_OBJECT (parse, "loop sending close segment");
1836 gst_pad_push_event (parse->srcpad, parse->priv->close_segment);
1837 parse->priv->close_segment = NULL;
1839 if (G_UNLIKELY (parse->priv->pending_segment)) {
1840 GST_DEBUG_OBJECT (parse, "%s push pending segment",
1841 parse->priv->pad_mode == GST_ACTIVATE_PULL ? "loop" : "chain");
1842 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1843 parse->priv->pending_segment = NULL;
1845 /* have caps; check identity */
1846 gst_base_parse_check_media (parse);
1849 /* update bitrates and optionally post corresponding tags
1850 * (following newsegment) */
1851 gst_base_parse_update_bitrates (parse, frame);
1853 if (G_UNLIKELY (parse->priv->pending_events)) {
1856 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1857 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1859 g_list_free (parse->priv->pending_events);
1860 parse->priv->pending_events = NULL;
1863 if (klass->pre_push_frame) {
1864 ret = klass->pre_push_frame (parse, frame);
1866 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
1869 /* take final ownership of frame buffer */
1870 buffer = frame->buffer;
1871 frame->buffer = NULL;
1873 /* subclass must play nice */
1874 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1876 parse->priv->seen_keyframe |= parse->priv->is_video &&
1877 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1879 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
1880 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1881 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
1882 GST_BUFFER_TIMESTAMP (buffer) >
1883 parse->segment.stop + parse->priv->lead_out_ts) {
1884 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
1885 ret = GST_FLOW_UNEXPECTED;
1886 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1887 GST_BUFFER_DURATION_IS_VALID (buffer) &&
1888 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
1889 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
1890 parse->priv->lead_in_ts < parse->segment.start) {
1891 if (parse->priv->seen_keyframe) {
1892 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
1895 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
1896 ret = GST_BASE_PARSE_FLOW_DROPPED;
1903 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1904 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) dropped", size);
1905 gst_buffer_unref (buffer);
1907 } else if (ret == GST_FLOW_OK) {
1908 if (parse->segment.rate > 0.0) {
1909 ret = gst_pad_push (parse->srcpad, buffer);
1910 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) pushed: %s",
1911 size, gst_flow_get_name (ret));
1913 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) queued for now",
1915 parse->priv->buffers_queued =
1916 g_slist_prepend (parse->priv->buffers_queued, buffer);
1920 gst_buffer_unref (buffer);
1921 GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s",
1922 size, gst_flow_get_name (ret));
1923 /* if we are not sufficiently in control, let upstream decide on EOS */
1924 if (ret == GST_FLOW_UNEXPECTED &&
1925 (parse->priv->passthrough ||
1926 (parse->priv->pad_mode == GST_ACTIVATE_PUSH &&
1927 !parse->priv->upstream_seekable)))
1931 /* Update current running segment position */
1932 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
1933 parse->segment.last_stop < last_stop)
1934 gst_segment_set_last_stop (&parse->segment, GST_FORMAT_TIME, last_stop);
1936 gst_base_parse_frame_free (frame);
1942 /* gst_base_parse_drain:
1944 * Drains the adapter until it is empty. It decreases the min_frame_size to
1945 * match the current adapter size and calls chain method until the adapter
1946 * is emptied or chain returns with error.
1949 gst_base_parse_drain (GstBaseParse * parse)
1953 GST_DEBUG_OBJECT (parse, "draining");
1954 parse->priv->drain = TRUE;
1957 avail = gst_adapter_available (parse->priv->adapter);
1961 if (gst_base_parse_chain (parse->sinkpad, NULL) != GST_FLOW_OK) {
1965 /* nothing changed, maybe due to truncated frame; break infinite loop */
1966 if (avail == gst_adapter_available (parse->priv->adapter)) {
1967 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
1968 gst_adapter_clear (parse->priv->adapter);
1972 parse->priv->drain = FALSE;
1975 /* gst_base_parse_send_buffers
1977 * Sends buffers collected in send_buffers downstream, and ensures that list
1978 * is empty at the end (errors or not).
1980 static GstFlowReturn
1981 gst_base_parse_send_buffers (GstBaseParse * parse)
1983 GSList *send = NULL;
1985 GstFlowReturn ret = GST_FLOW_OK;
1987 send = parse->priv->buffers_send;
1991 buf = GST_BUFFER_CAST (send->data);
1992 GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
1993 GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
1994 ", offset %" G_GINT64_FORMAT, buf,
1995 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1996 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
1998 /* iterate output queue an push downstream */
1999 ret = gst_pad_push (parse->srcpad, buf);
2000 send = g_slist_delete_link (send, send);
2002 /* clear any leftover if error */
2003 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2005 buf = GST_BUFFER_CAST (send->data);
2006 gst_buffer_unref (buf);
2007 send = g_slist_delete_link (send, send);
2012 parse->priv->buffers_send = send;
2017 /* gst_base_parse_process_fragment:
2019 * Processes a reverse playback (forward) fragment:
2020 * - append head of last fragment that was skipped to current fragment data
2021 * - drain the resulting current fragment data (i.e. repeated chain)
2022 * - add time/duration (if needed) to frames queued by chain
2023 * - push queued data
2025 static GstFlowReturn
2026 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
2029 GstFlowReturn ret = GST_FLOW_OK;
2030 gboolean seen_key = FALSE, seen_delta = FALSE;
2036 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2037 while (parse->priv->buffers_pending) {
2038 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2039 GST_LOG_OBJECT (parse, "adding pending buffer (size %d)",
2040 gst_buffer_get_size (buf));
2041 gst_adapter_push (parse->priv->adapter, buf);
2042 parse->priv->buffers_pending =
2043 g_slist_delete_link (parse->priv->buffers_pending,
2044 parse->priv->buffers_pending);
2047 /* invalidate so no fall-back timestamping is performed;
2048 * ok if taken from subclass or upstream */
2049 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
2050 /* prevent it hanging around stop all the time */
2051 parse->segment.last_stop = GST_CLOCK_TIME_NONE;
2053 parse->priv->discont = TRUE;
2055 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2056 /* initial skipped data is added to buffers_pending */
2057 gst_base_parse_drain (parse);
2060 if (parse->priv->buffers_send) {
2061 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2062 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2065 /* add metadata (if needed to queued buffers */
2066 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2067 GST_TIME_ARGS (parse->priv->last_ts));
2068 while (parse->priv->buffers_queued) {
2069 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2071 /* no touching if upstream or parsing provided time */
2072 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2073 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2074 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2075 } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
2076 GST_BUFFER_DURATION_IS_VALID (buf)) {
2077 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
2078 parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
2080 parse->priv->last_ts = 0;
2081 GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
2082 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2083 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2085 /* no idea, very bad */
2086 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2089 parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
2091 /* reverse order for ascending sending */
2092 /* send downstream at keyframe not preceded by a keyframe
2093 * (e.g. that should identify start of collection of IDR nals) */
2094 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2096 ret = gst_base_parse_send_buffers (parse);
2097 /* if a problem, throw all to sending */
2098 if (ret != GST_FLOW_OK) {
2099 parse->priv->buffers_send =
2100 g_slist_reverse (parse->priv->buffers_queued);
2101 parse->priv->buffers_queued = NULL;
2110 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2112 parse->priv->buffers_send =
2113 g_slist_prepend (parse->priv->buffers_send, buf);
2114 parse->priv->buffers_queued =
2115 g_slist_delete_link (parse->priv->buffers_queued,
2116 parse->priv->buffers_queued);
2119 /* audio may have all marked as keyframe, so arrange to send here */
2121 ret = gst_base_parse_send_buffers (parse);
2123 /* any trailing unused no longer usable (ideally none) */
2124 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2125 GST_DEBUG_OBJECT (parse, "discarding %d trailing bytes",
2126 gst_adapter_available (parse->priv->adapter));
2127 gst_adapter_clear (parse->priv->adapter);
2133 /* small helper that checks whether we have been trying to resync too long */
2134 static inline GstFlowReturn
2135 gst_base_parse_check_sync (GstBaseParse * parse)
2137 if (G_UNLIKELY (parse->priv->discont &&
2138 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2139 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2140 ("Failed to parse stream"), (NULL));
2141 return GST_FLOW_ERROR;
2147 static GstFlowReturn
2148 gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
2150 GstBaseParseClass *bclass;
2151 GstBaseParse *parse;
2152 GstFlowReturn ret = GST_FLOW_OK;
2153 GstBuffer *outbuf = NULL;
2154 GstBuffer *tmpbuf = NULL;
2158 guint old_min_size = 0, min_size, av;
2159 GstClockTime timestamp;
2160 GstBaseParseFrame _frame;
2161 GstBaseParseFrame *frame;
2163 parse = GST_BASE_PARSE (GST_OBJECT_PARENT (pad));
2164 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2167 gst_base_parse_frame_init (frame);
2169 if (G_LIKELY (buffer)) {
2170 GST_LOG_OBJECT (parse, "buffer size: %d, offset = %" G_GINT64_FORMAT,
2171 gst_buffer_get_size (buffer), GST_BUFFER_OFFSET (buffer));
2172 if (G_UNLIKELY (parse->priv->passthrough)) {
2173 frame->buffer = gst_buffer_make_writable (buffer);
2174 return gst_base_parse_push_frame (parse, frame);
2176 /* upstream feeding us in reverse playback;
2177 * gather each fragment, then process it in single run */
2178 if (parse->segment.rate < 0.0) {
2179 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2180 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2181 ret = gst_base_parse_process_fragment (parse, FALSE);
2183 gst_adapter_push (parse->priv->adapter, buffer);
2186 gst_adapter_push (parse->priv->adapter, buffer);
2189 /* Parse and push as many frames as possible */
2190 /* Stop either when adapter is empty or we are flushing */
2191 while (!parse->priv->flushing) {
2194 tmpbuf = gst_buffer_new ();
2197 /* Synchronization loop */
2199 min_size = MAX (parse->priv->min_frame_size, fsize);
2200 av = gst_adapter_available (parse->priv->adapter);
2202 /* loop safety check */
2203 if (G_UNLIKELY (old_min_size >= min_size))
2205 old_min_size = min_size;
2207 if (G_UNLIKELY (parse->priv->drain)) {
2209 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2210 if (G_UNLIKELY (!min_size)) {
2211 gst_buffer_unref (tmpbuf);
2216 /* Collect at least min_frame_size bytes */
2217 if (av < min_size) {
2218 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
2220 gst_buffer_unref (tmpbuf);
2224 /* always pass all available data */
2225 data = gst_adapter_map (parse->priv->adapter, av);
2226 gst_buffer_take_memory (tmpbuf,
2227 gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
2228 (gpointer) data, NULL, min_size, 0, min_size));
2229 GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
2231 if (parse->priv->discont) {
2232 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2233 GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2237 gst_base_parse_frame_update (parse, frame, tmpbuf);
2238 res = bclass->check_valid_frame (parse, frame, &fsize, &skip);
2239 gst_adapter_unmap (parse->priv->adapter, 0);
2240 gst_buffer_replace (&frame->buffer, NULL);
2242 if (gst_adapter_available (parse->priv->adapter) < fsize) {
2243 GST_DEBUG_OBJECT (parse,
2244 "found valid frame but not enough data available (only %d bytes)",
2245 gst_adapter_available (parse->priv->adapter));
2246 gst_buffer_unref (tmpbuf);
2249 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2253 /* subclass didn't touch this value. By default we skip 1 byte */
2257 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2258 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2259 /* reverse playback, and no frames found yet, so we are skipping
2260 * the leading part of a fragment, which may form the tail of
2261 * fragment coming later, hopefully subclass skips efficiently ... */
2262 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2263 outbuf = gst_adapter_take_buffer (parse->priv->adapter, skip);
2264 outbuf = gst_buffer_make_writable (outbuf);
2265 GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
2266 parse->priv->buffers_pending =
2267 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2270 gst_adapter_flush (parse->priv->adapter, skip);
2272 parse->priv->offset += skip;
2273 if (!parse->priv->discont)
2274 parse->priv->sync_offset = parse->priv->offset;
2275 parse->priv->discont = TRUE;
2276 /* something changed least; nullify loop check */
2279 /* skip == 0 should imply subclass set min_size to need more data;
2280 * we check this shortly */
2281 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2282 gst_buffer_unref (tmpbuf);
2286 gst_buffer_unref (tmpbuf);
2290 /* Subclass found the sync, but still wants to skip some data */
2291 GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
2292 gst_adapter_flush (parse->priv->adapter, skip);
2293 parse->priv->offset += skip;
2296 /* Grab lock to prevent a race with FLUSH_START handler */
2297 GST_PAD_STREAM_LOCK (parse->srcpad);
2299 /* FLUSH_START event causes the "flushing" flag to be set. In this
2300 * case we can leave the frame pushing loop */
2301 if (parse->priv->flushing) {
2302 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2306 /* move along with upstream timestamp (if any),
2307 * but interpolate in between */
2308 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2309 if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2310 (parse->priv->prev_ts != timestamp)) {
2311 parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2314 /* FIXME: Would it be more efficient to make a subbuffer instead? */
2315 outbuf = gst_adapter_take_buffer (parse->priv->adapter, fsize);
2316 outbuf = gst_buffer_make_writable (outbuf);
2318 /* Subclass may want to know the data offset */
2319 GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2320 parse->priv->offset += fsize;
2321 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2322 GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
2324 frame->buffer = outbuf;
2325 ret = gst_base_parse_handle_and_push_frame (parse, bclass, frame);
2326 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2328 if (ret != GST_FLOW_OK) {
2329 GST_LOG_OBJECT (parse, "push returned %d", ret);
2335 GST_LOG_OBJECT (parse, "chain leaving");
2341 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2342 ("min_size evolution %d -> %d; breaking to avoid looping",
2343 old_min_size, min_size));
2344 return GST_FLOW_ERROR;
2348 /* pull @size bytes at current offset,
2349 * i.e. at least try to and possibly return a shorter buffer if near the end */
2350 static GstFlowReturn
2351 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2352 GstBuffer ** buffer)
2354 GstFlowReturn ret = GST_FLOW_OK;
2356 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2358 /* Caching here actually makes much less difference than one would expect.
2359 * We do it mainly to avoid pulling buffers of 1 byte all the time */
2360 if (parse->priv->cache) {
2361 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2362 gint cache_size = gst_buffer_get_size (parse->priv->cache);
2364 if (cache_offset <= parse->priv->offset &&
2365 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2366 *buffer = gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL,
2367 parse->priv->offset - cache_offset, size);
2368 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2371 /* not enough data in the cache, free cache and get a new one */
2372 gst_buffer_unref (parse->priv->cache);
2373 parse->priv->cache = NULL;
2376 /* refill the cache */
2378 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2379 64 * 1024), &parse->priv->cache);
2380 if (ret != GST_FLOW_OK) {
2381 parse->priv->cache = NULL;
2385 if (gst_buffer_get_size (parse->priv->cache) >= size) {
2387 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0,
2389 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2393 /* Not possible to get enough data, try a last time with
2394 * requesting exactly the size we need */
2395 gst_buffer_unref (parse->priv->cache);
2396 parse->priv->cache = NULL;
2398 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2399 &parse->priv->cache);
2401 if (ret != GST_FLOW_OK) {
2402 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2407 if (gst_buffer_get_size (parse->priv->cache) < size) {
2408 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2409 G_GUINT64_FORMAT ": wanted %u bytes, got %u bytes", parse->priv->offset,
2410 size, gst_buffer_get_size (parse->priv->cache));
2412 *buffer = parse->priv->cache;
2413 parse->priv->cache = NULL;
2419 gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0, size);
2420 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2425 static GstFlowReturn
2426 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2429 GstClockTime ts = 0;
2433 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2434 ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2435 parse->priv->last_offset);
2437 if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2438 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2439 GST_TIME_ARGS (parse->segment.start));
2440 ret = GST_FLOW_UNEXPECTED;
2444 /* last fragment started at last_offset / last_ts;
2445 * seek back 10s capped at 1MB */
2446 if (parse->priv->last_ts >= 10 * GST_SECOND)
2447 ts = parse->priv->last_ts - 10 * GST_SECOND;
2448 /* if we are exact now, we will be more so going backwards */
2449 if (parse->priv->exact_position) {
2450 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2452 GstFormat dstformat = GST_FORMAT_BYTES;
2454 if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2455 &dstformat, &offset)) {
2456 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2459 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2460 parse->priv->last_offset - 1024);
2461 offset = MAX (0, offset);
2463 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2465 parse->priv->offset = offset;
2467 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2469 if (ret != GST_FLOW_OK)
2472 /* offset will increase again as fragment is processed/parsed */
2473 parse->priv->last_offset = offset;
2475 gst_adapter_push (parse->priv->adapter, buffer);
2476 ret = gst_base_parse_process_fragment (parse, FALSE);
2477 if (ret != GST_FLOW_OK)
2480 /* force previous fragment */
2481 parse->priv->offset = -1;
2488 * pull and scan for next frame starting from current offset
2489 * ajusts sync, drain and offset going along */
2490 static GstFlowReturn
2491 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2492 GstBaseParseFrame * frame, gboolean full)
2494 GstBuffer *buffer, *outbuf;
2495 GstFlowReturn ret = GST_FLOW_OK;
2496 guint fsize = 1, min_size, old_min_size = 0;
2499 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2501 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2502 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2507 min_size = MAX (parse->priv->min_frame_size, fsize);
2508 /* loop safety check */
2509 if (G_UNLIKELY (old_min_size >= min_size))
2511 old_min_size = min_size;
2513 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2514 if (ret != GST_FLOW_OK)
2517 if (parse->priv->discont) {
2518 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2519 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2522 /* if we got a short read, inform subclass we are draining leftover
2523 * and no more is to be expected */
2524 if (gst_buffer_get_size (buffer) < min_size)
2525 parse->priv->drain = TRUE;
2528 gst_base_parse_frame_update (parse, frame, buffer);
2529 res = klass->check_valid_frame (parse, frame, &fsize, &skip);
2530 gst_buffer_replace (&frame->buffer, NULL);
2532 parse->priv->drain = FALSE;
2533 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2536 parse->priv->drain = FALSE;
2540 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2541 if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2542 /* reverse playback, and no frames found yet, so we are skipping
2543 * the leading part of a fragment, which may form the tail of
2544 * fragment coming later, hopefully subclass skips efficiently ... */
2545 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, 0, skip);
2546 parse->priv->buffers_pending =
2547 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2550 parse->priv->offset += skip;
2551 if (!parse->priv->discont)
2552 parse->priv->sync_offset = parse->priv->offset;
2553 parse->priv->discont = TRUE;
2554 /* something changed least; nullify loop check */
2557 /* skip == 0 should imply subclass set min_size to need more data;
2558 * we check this shortly */
2559 GST_DEBUG_OBJECT (parse, "finding sync...");
2560 gst_buffer_unref (buffer);
2561 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2566 /* Does the subclass want to skip too? */
2568 parse->priv->offset += skip;
2572 if (fsize + skip <= gst_buffer_get_size (buffer)) {
2573 outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, skip, fsize);
2574 GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2575 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2576 gst_buffer_unref (buffer);
2578 gst_buffer_unref (buffer);
2579 ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2580 if (ret != GST_FLOW_OK)
2582 if (gst_buffer_get_size (outbuf) < fsize) {
2583 gst_buffer_unref (outbuf);
2584 ret = GST_FLOW_UNEXPECTED;
2588 parse->priv->offset += fsize;
2590 frame->buffer = outbuf;
2598 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2599 ("min_size evolution %d -> %d; breaking to avoid looping",
2600 old_min_size, min_size));
2601 return GST_FLOW_ERROR;
2605 /* Loop that is used in pull mode to retrieve data from upstream */
2607 gst_base_parse_loop (GstPad * pad)
2609 GstBaseParse *parse;
2610 GstBaseParseClass *klass;
2611 GstFlowReturn ret = GST_FLOW_OK;
2612 GstBaseParseFrame frame;
2614 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2615 klass = GST_BASE_PARSE_GET_CLASS (parse);
2617 /* reverse playback:
2618 * first fragment (closest to stop time) is handled normally below,
2619 * then we pull in fragments going backwards */
2620 if (parse->segment.rate < 0.0) {
2621 /* check if we jumped back to a previous fragment,
2622 * which is a post-first fragment */
2623 if (parse->priv->offset < 0) {
2624 ret = gst_base_parse_handle_previous_fragment (parse);
2629 gst_base_parse_frame_init (&frame);
2630 ret = gst_base_parse_scan_frame (parse, klass, &frame, TRUE);
2631 if (ret != GST_FLOW_OK)
2634 /* This always cleans up frame, even if error occurs */
2635 ret = gst_base_parse_handle_and_push_frame (parse, klass, &frame);
2637 /* eat expected eos signalling past segment in reverse playback */
2638 if (parse->segment.rate < 0.0 && ret == GST_FLOW_UNEXPECTED &&
2639 parse->segment.last_stop >= parse->segment.stop) {
2640 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2641 /* push what was accumulated during loop run */
2642 gst_base_parse_process_fragment (parse, TRUE);
2643 /* force previous fragment */
2644 parse->priv->offset = -1;
2649 if (ret == GST_FLOW_UNEXPECTED)
2651 else if (ret != GST_FLOW_OK)
2654 gst_object_unref (parse);
2660 ret = GST_FLOW_UNEXPECTED;
2661 GST_DEBUG_OBJECT (parse, "eos");
2666 gboolean push_eos = FALSE;
2668 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2669 gst_flow_get_name (ret));
2670 gst_pad_pause_task (parse->sinkpad);
2672 if (ret == GST_FLOW_UNEXPECTED) {
2673 /* handle end-of-stream/segment */
2674 if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2677 if ((stop = parse->segment.stop) == -1)
2678 stop = parse->segment.duration;
2680 GST_DEBUG_OBJECT (parse, "sending segment_done");
2682 gst_element_post_message
2683 (GST_ELEMENT_CAST (parse),
2684 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2685 GST_FORMAT_TIME, stop));
2687 /* If we STILL have zero frames processed, fire an error */
2688 if (parse->priv->framecount == 0) {
2689 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2690 ("No valid frames found before end of stream"), (NULL));
2694 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
2695 /* for fatal errors we post an error message, wrong-state is
2696 * not fatal because it happens due to flushes and only means
2697 * that we should stop now. */
2698 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2699 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2703 /* newsegment before eos */
2704 if (parse->priv->pending_segment) {
2705 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
2706 parse->priv->pending_segment = NULL;
2708 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2710 gst_object_unref (parse);
2715 gst_base_parse_sink_activate (GstPad * sinkpad)
2717 GstBaseParse *parse;
2718 gboolean result = TRUE;
2720 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2722 GST_DEBUG_OBJECT (parse, "sink activate");
2724 if (gst_pad_check_pull_range (sinkpad)) {
2725 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2726 result = gst_pad_activate_pull (sinkpad, TRUE);
2728 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
2729 result = gst_pad_activate_push (sinkpad, TRUE);
2732 GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
2733 gst_object_unref (parse);
2738 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
2740 GstBaseParseClass *klass;
2741 gboolean result = FALSE;
2743 GST_DEBUG_OBJECT (parse, "activate %d", active);
2745 klass = GST_BASE_PARSE_GET_CLASS (parse);
2748 if (parse->priv->pad_mode == GST_ACTIVATE_NONE && klass->start)
2749 result = klass->start (parse);
2751 /* We must make sure streaming has finished before resetting things
2752 * and calling the ::stop vfunc */
2753 GST_PAD_STREAM_LOCK (parse->sinkpad);
2754 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2756 if (parse->priv->pad_mode != GST_ACTIVATE_NONE && klass->stop)
2757 result = klass->stop (parse);
2759 parse->priv->pad_mode = GST_ACTIVATE_NONE;
2761 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
2766 gst_base_parse_sink_activate_push (GstPad * pad, gboolean active)
2768 gboolean result = TRUE;
2769 GstBaseParse *parse;
2771 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2773 GST_DEBUG_OBJECT (parse, "sink activate push %d", active);
2775 result = gst_base_parse_activate (parse, active);
2778 parse->priv->pad_mode = active ? GST_ACTIVATE_PUSH : GST_ACTIVATE_NONE;
2780 GST_DEBUG_OBJECT (parse, "sink activate push return: %d", result);
2782 gst_object_unref (parse);
2787 gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
2789 gboolean result = FALSE;
2790 GstBaseParse *parse;
2792 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2794 GST_DEBUG_OBJECT (parse, "activate pull %d", active);
2796 result = gst_base_parse_activate (parse, active);
2800 parse->priv->pending_segment = gst_event_new_new_segment (FALSE,
2801 parse->segment.rate, parse->segment.applied_rate,
2802 parse->segment.format, parse->segment.start, parse->segment.stop,
2803 parse->segment.last_stop);
2805 gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
2808 result &= gst_pad_stop_task (sinkpad);
2813 parse->priv->pad_mode = active ? GST_ACTIVATE_PULL : GST_ACTIVATE_NONE;
2815 GST_DEBUG_OBJECT (parse, "sink activate pull return: %d", result);
2817 gst_object_unref (parse);
2823 * gst_base_parse_set_duration:
2824 * @parse: #GstBaseParse.
2826 * @duration: duration value.
2827 * @interval: how often to update the duration estimate based on bitrate, or 0.
2829 * Sets the duration of the currently playing media. Subclass can use this
2830 * when it is able to determine duration and/or notices a change in the media
2831 * duration. Alternatively, if @interval is non-zero (default), then stream
2832 * duration is determined based on estimated bitrate, and updated every @interval
2838 gst_base_parse_set_duration (GstBaseParse * parse,
2839 GstFormat fmt, gint64 duration, gint interval)
2841 g_return_if_fail (parse != NULL);
2843 if (parse->priv->upstream_has_duration) {
2844 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
2848 if (duration != parse->priv->duration) {
2851 m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
2852 gst_element_post_message (GST_ELEMENT (parse), m);
2854 /* TODO: what about duration tag? */
2856 parse->priv->duration = duration;
2857 parse->priv->duration_fmt = fmt;
2858 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
2859 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
2860 if (interval != 0) {
2861 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
2865 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
2866 parse->priv->update_interval = interval;
2872 * gst_base_parse_set_average_bitrate:
2873 * @parse: #GstBaseParse.
2874 * @bitrate: average bitrate in bits/second
2876 * Optionally sets the average bitrate detected in media (if non-zero),
2877 * e.g. based on metadata, as it will be posted to the application.
2879 * By default, announced average bitrate is estimated. The average bitrate
2880 * is used to estimate the total duration of the stream and to estimate
2881 * a seek position, if there's no index and the format is syncable
2882 * (see gst_base_parse_set_syncable()).
2887 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
2889 parse->priv->bitrate = bitrate;
2890 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
2894 * gst_base_parse_set_min_frame_size:
2895 * @parse: #GstBaseParse.
2896 * @min_size: Minimum size of the data that this base class should give to
2899 * Subclass can use this function to tell the base class that it needs to
2900 * give at least #min_size buffers.
2905 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
2907 g_return_if_fail (parse != NULL);
2909 parse->priv->min_frame_size = min_size;
2910 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
2914 * gst_base_parse_set_frame_rate:
2915 * @parse: the #GstBaseParse to set
2916 * @fps_num: frames per second (numerator).
2917 * @fps_den: frames per second (denominator).
2918 * @lead_in: frames needed before a segment for subsequent decode
2919 * @lead_out: frames needed after a segment
2921 * If frames per second is configured, parser can take care of buffer duration
2922 * and timestamping. When performing segment clipping, or seeking to a specific
2923 * location, a corresponding decoder might need an initial @lead_in and a
2924 * following @lead_out number of frames to ensure the desired segment is
2925 * entirely filled upon decoding.
2930 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
2931 guint fps_den, guint lead_in, guint lead_out)
2933 g_return_if_fail (parse != NULL);
2935 parse->priv->fps_num = fps_num;
2936 parse->priv->fps_den = fps_den;
2937 if (!fps_num || !fps_den) {
2938 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
2940 fps_num = fps_den = 0;
2941 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
2942 parse->priv->lead_in = parse->priv->lead_out = 0;
2943 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
2945 parse->priv->frame_duration =
2946 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
2947 parse->priv->lead_in = lead_in;
2948 parse->priv->lead_out = lead_out;
2949 parse->priv->lead_in_ts =
2950 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
2951 parse->priv->lead_out_ts =
2952 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
2953 /* aim for about 1.5s to estimate duration */
2954 if (parse->priv->update_interval < 0) {
2955 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
2956 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
2957 parse->priv->update_interval);
2960 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
2961 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
2962 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
2963 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
2964 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
2965 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
2969 * gst_base_parse_set_has_timing_info:
2970 * @parse: a #GstBaseParse
2971 * @has_timing: whether frames carry timing information
2973 * Set if frames carry timing information which the subclass can (generally)
2974 * parse and provide. In particular, intrinsic (rather than estimated) time
2975 * can be obtained following a seek.
2980 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
2982 parse->priv->has_timing_info = has_timing;
2983 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
2987 * gst_base_parse_set_syncable:
2988 * @parse: a #GstBaseParse
2989 * @syncable: set if frame starts can be identified
2991 * Set if frame starts can be identified. This is set by default and
2992 * determines whether seeking based on bitrate averages
2993 * is possible for a format/stream.
2998 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3000 parse->priv->syncable = syncable;
3001 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3005 * gst_base_parse_set_passthrough:
3006 * @parse: a #GstBaseParse
3007 * @passthrough: %TRUE if parser should run in passthrough mode
3009 * Set if the nature of the format or configuration does not allow (much)
3010 * parsing, and the parser should operate in passthrough mode (which only
3011 * applies when operating in push mode). That is, incoming buffers are
3012 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3013 * callbacks will be invoked, but @pre_push_buffer will still be invoked,
3014 * so subclass can perform as much or as little is appropriate for
3015 * passthrough semantics in @pre_push_buffer.
3020 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3022 parse->priv->passthrough = passthrough;
3023 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3027 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3028 GstClockTime * duration)
3030 gboolean res = FALSE;
3032 g_return_val_if_fail (duration != NULL, FALSE);
3034 *duration = GST_CLOCK_TIME_NONE;
3035 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3036 GST_LOG_OBJECT (parse, "using provided duration");
3037 *duration = parse->priv->duration;
3039 } else if (parse->priv->duration != -1) {
3040 GST_LOG_OBJECT (parse, "converting provided duration");
3041 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3042 parse->priv->duration, format, (gint64 *) duration);
3043 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3044 GST_LOG_OBJECT (parse, "using estimated duration");
3045 *duration = parse->priv->estimated_duration;
3049 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3050 GST_TIME_ARGS (*duration));
3054 static const GstQueryType *
3055 gst_base_parse_get_querytypes (GstPad * pad)
3057 static const GstQueryType list[] = {
3070 gst_base_parse_query (GstPad * pad, GstQuery ** query)
3072 GstBaseParse *parse;
3073 gboolean res = FALSE;
3075 parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3077 GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3079 switch (GST_QUERY_TYPE (*query)) {
3080 case GST_QUERY_POSITION:
3085 GST_DEBUG_OBJECT (parse, "position query");
3086 gst_query_parse_position (*query, &format, NULL);
3088 GST_OBJECT_LOCK (parse);
3089 if (format == GST_FORMAT_BYTES) {
3090 dest_value = parse->priv->offset;
3092 } else if (format == parse->segment.format &&
3093 GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop)) {
3094 dest_value = parse->segment.last_stop;
3097 GST_OBJECT_UNLOCK (parse);
3100 *query = gst_query_make_writable (*query);
3101 gst_query_set_position (*query, format, dest_value);
3103 res = gst_pad_query_default (pad, query);
3105 /* no precise result, upstream no idea either, then best estimate */
3106 /* priv->offset is updated in both PUSH/PULL modes */
3107 res = gst_base_parse_convert (parse,
3108 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3113 case GST_QUERY_DURATION:
3116 GstClockTime duration;
3118 GST_DEBUG_OBJECT (parse, "duration query");
3119 gst_query_parse_duration (*query, &format, NULL);
3121 /* consult upstream */
3122 res = gst_pad_query_default (pad, query);
3124 /* otherwise best estimate from us */
3126 res = gst_base_parse_get_duration (parse, format, &duration);
3128 *query = gst_query_make_writable (*query);
3129 gst_query_set_duration (*query, format, duration);
3134 case GST_QUERY_SEEKING:
3137 GstClockTime duration = GST_CLOCK_TIME_NONE;
3138 gboolean seekable = FALSE;
3140 GST_DEBUG_OBJECT (parse, "seeking query");
3141 gst_query_parse_seeking (*query, &fmt, NULL, NULL, NULL);
3143 /* consult upstream */
3144 res = gst_pad_query_default (pad, query);
3146 /* we may be able to help if in TIME */
3147 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3148 gst_query_parse_seeking (*query, &fmt, &seekable, NULL, NULL);
3149 /* already OK if upstream takes care */
3150 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3152 if (!(res && seekable)) {
3153 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3154 || duration == -1) {
3155 /* seekable if we still have a chance to get duration later on */
3157 parse->priv->upstream_seekable && parse->priv->update_interval;
3159 seekable = parse->priv->upstream_seekable;
3160 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3163 *query = gst_query_make_writable (*query);
3164 gst_query_set_seeking (*query, GST_FORMAT_TIME, seekable, 0,
3171 case GST_QUERY_FORMATS:
3172 *query = gst_query_make_writable (*query);
3173 gst_query_set_formatsv (*query, 3, fmtlist);
3176 case GST_QUERY_CONVERT:
3178 GstFormat src_format, dest_format;
3179 gint64 src_value, dest_value;
3181 gst_query_parse_convert (*query, &src_format, &src_value,
3182 &dest_format, &dest_value);
3184 res = gst_base_parse_convert (parse, src_format, src_value,
3185 dest_format, &dest_value);
3187 *query = gst_query_make_writable (*query);
3188 gst_query_set_convert (*query, src_format, src_value,
3189 dest_format, dest_value);
3194 res = gst_pad_query_default (pad, query);
3200 /* scans for a cluster start from @pos,
3201 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3202 static GstFlowReturn
3203 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3204 GstClockTime * time, GstClockTime * duration)
3206 GstBaseParseClass *klass;
3208 gboolean orig_drain, orig_discont;
3209 GstFlowReturn ret = GST_FLOW_OK;
3210 GstBuffer *buf = NULL;
3211 GstBaseParseFrame frame;
3213 g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3214 g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3215 g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3217 klass = GST_BASE_PARSE_GET_CLASS (parse);
3219 *time = GST_CLOCK_TIME_NONE;
3220 *duration = GST_CLOCK_TIME_NONE;
3223 orig_offset = parse->priv->offset;
3224 orig_discont = parse->priv->discont;
3225 orig_drain = parse->priv->drain;
3227 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3228 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3230 gst_base_parse_frame_init (&frame);
3232 /* jump elsewhere and locate next frame */
3233 parse->priv->offset = *pos;
3234 ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3235 if (ret != GST_FLOW_OK)
3239 GST_LOG_OBJECT (parse,
3240 "peek parsing frame at offset %" G_GUINT64_FORMAT
3241 " (%#" G_GINT64_MODIFIER "x) of size %d",
3242 GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf),
3243 gst_buffer_get_size (buf));
3245 /* get offset first, subclass parsing might dump other stuff in there */
3246 *pos = GST_BUFFER_OFFSET (buf);
3247 ret = klass->parse_frame (parse, &frame);
3250 /* but it should provide proper time */
3251 *time = GST_BUFFER_TIMESTAMP (buf);
3252 *duration = GST_BUFFER_DURATION (buf);
3254 gst_base_parse_frame_free (&frame);
3256 GST_LOG_OBJECT (parse,
3257 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3258 GST_TIME_ARGS (*time), *pos);
3262 parse->priv->offset = orig_offset;
3263 parse->priv->discont = orig_discont;
3264 parse->priv->drain = orig_drain;
3269 /* bisect and scan through file for frame starting before @time,
3270 * returns OK and @time/@offset if found, NONE and/or error otherwise
3271 * If @time == G_MAXINT64, scan for duration ( == last frame) */
3272 static GstFlowReturn
3273 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3276 GstFlowReturn ret = GST_FLOW_OK;
3277 gint64 lpos, hpos, newpos;
3278 GstClockTime time, ltime, htime, newtime, dur;
3279 gboolean cont = TRUE;
3280 const GstClockTime tolerance = TARGET_DIFFERENCE;
3281 const guint chunk = 4 * 1024;
3283 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3284 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3286 /* TODO also make keyframe aware if useful some day */
3301 /* do not know at first */
3303 *_time = GST_CLOCK_TIME_NONE;
3305 /* need initial positions; start and end */
3306 lpos = parse->priv->first_frame_offset;
3307 ltime = parse->priv->first_frame_ts;
3308 htime = parse->priv->duration;
3309 hpos = parse->priv->upstream_size;
3311 /* check preconditions are satisfied;
3312 * start and end are needed, except for special case where we scan for
3313 * last frame to determine duration */
3314 if (parse->priv->pad_mode != GST_ACTIVATE_PULL || !hpos ||
3315 !GST_CLOCK_TIME_IS_VALID (ltime) ||
3316 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3320 /* shortcut cases */
3323 } else if (time < ltime + tolerance) {
3327 } else if (time >= htime) {
3333 while (htime > ltime && cont) {
3334 GST_LOG_OBJECT (parse,
3335 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3336 GST_TIME_ARGS (ltime));
3337 GST_LOG_OBJECT (parse,
3338 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3339 GST_TIME_ARGS (htime));
3340 if (G_UNLIKELY (time == G_MAXINT64)) {
3342 } else if (G_LIKELY (hpos > lpos)) {
3344 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3347 /* should mean lpos == hpos, since lpos <= hpos is invariant */
3349 /* we check this case once, but not forever, so break loop */
3354 newpos = CLAMP (newpos, lpos, hpos);
3355 GST_LOG_OBJECT (parse,
3356 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3357 GST_TIME_ARGS (time), newpos);
3359 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3360 if (ret == GST_FLOW_UNEXPECTED) {
3361 /* heuristic HACK */
3362 hpos = MAX (lpos, hpos - chunk);
3364 } else if (ret != GST_FLOW_OK) {
3368 if (newtime == -1 || newpos == -1) {
3369 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3373 if (G_UNLIKELY (time == G_MAXINT64)) {
3376 if (GST_CLOCK_TIME_IS_VALID (dur))
3379 } else if (newtime > time) {
3381 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3383 } else if (newtime + tolerance > time) {
3384 /* close enough undershoot */
3388 } else if (newtime < ltime) {
3389 /* so a position beyond lpos resulted in earlier time than ltime ... */
3390 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3393 /* undershoot too far */
3394 newpos += newpos == lpos ? chunk : 0;
3395 lpos = CLAMP (newpos, lpos, hpos);
3401 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3402 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3407 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3408 gboolean before, GstClockTime * _ts)
3410 gint64 bytes = 0, ts = 0;
3411 GstIndexEntry *entry = NULL;
3413 if (time == GST_CLOCK_TIME_NONE) {
3419 g_static_mutex_lock (&parse->priv->index_lock);
3420 if (parse->priv->index) {
3421 /* Let's check if we have an index entry for that time */
3422 entry = gst_index_get_assoc_entry (parse->priv->index,
3423 parse->priv->index_id,
3424 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3425 GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3429 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3430 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3432 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3433 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3434 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3436 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3437 GST_TIME_ARGS (time));
3440 ts = GST_CLOCK_TIME_NONE;
3443 g_static_mutex_unlock (&parse->priv->index_lock);
3452 /* returns TRUE if seek succeeded */
3454 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3459 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3460 gboolean flush, update, res = TRUE, accurate;
3461 gint64 cur, stop, seekpos, seekstop;
3462 GstSegment seeksegment = { 0, };
3463 GstFormat dstformat;
3464 GstClockTime start_ts;
3466 gst_event_parse_seek (event, &rate, &format, &flags,
3467 &cur_type, &cur, &stop_type, &stop);
3469 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3470 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3471 GST_TIME_FORMAT, gst_format_get_name (format), rate,
3472 cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3474 /* no negative rates in push mode */
3475 if (rate < 0.0 && parse->priv->pad_mode == GST_ACTIVATE_PUSH)
3478 if (cur_type != GST_SEEK_TYPE_SET ||
3479 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3482 /* For any format other than TIME, see if upstream handles
3483 * it directly or fail. For TIME, try upstream, but do it ourselves if
3484 * it fails upstream */
3485 if (format != GST_FORMAT_TIME) {
3486 /* default action delegates to upstream */
3490 gst_event_ref (event);
3491 if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3496 /* get flush flag */
3497 flush = flags & GST_SEEK_FLAG_FLUSH;
3499 /* copy segment, we need this because we still need the old
3500 * segment when we close the current segment. */
3501 memcpy (&seeksegment, &parse->segment, sizeof (GstSegment));
3503 GST_DEBUG_OBJECT (parse, "configuring seek");
3504 gst_segment_set_seek (&seeksegment, rate, format, flags,
3505 cur_type, cur, stop_type, stop, &update);
3507 /* accurate seeking implies seek tables are used to obtain position,
3508 * and the requested segment is maintained exactly, not adjusted any way */
3509 accurate = flags & GST_SEEK_FLAG_ACCURATE;
3511 /* maybe we can be accurate for (almost) free */
3512 gst_base_parse_find_offset (parse, seeksegment.last_stop, TRUE, &start_ts);
3513 if (seeksegment.last_stop <= start_ts + TARGET_DIFFERENCE) {
3514 GST_DEBUG_OBJECT (parse, "accurate seek possible");
3518 GstClockTime startpos = seeksegment.last_stop;
3520 /* accurate requested, so ... seek a bit before target */
3521 if (startpos < parse->priv->lead_in_ts)
3524 startpos -= parse->priv->lead_in_ts;
3525 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3526 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3529 start_ts = seeksegment.last_stop;
3530 dstformat = GST_FORMAT_BYTES;
3531 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.last_stop,
3532 &dstformat, &seekpos))
3533 goto convert_failed;
3534 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3535 &dstformat, &seekstop))
3536 goto convert_failed;
3539 GST_DEBUG_OBJECT (parse,
3540 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3542 GST_DEBUG_OBJECT (parse,
3543 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3544 seeksegment.stop, seekstop);
3546 if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
3549 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3552 if (parse->srcpad) {
3553 GST_DEBUG_OBJECT (parse, "sending flush start");
3554 gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3555 /* unlock upstream pull_range */
3556 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3559 gst_pad_pause_task (parse->sinkpad);
3562 /* we should now be able to grab the streaming thread because we stopped it
3563 * with the above flush/pause code */
3564 GST_PAD_STREAM_LOCK (parse->sinkpad);
3566 /* save current position */
3567 last_stop = parse->segment.last_stop;
3568 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3571 /* now commit to new position */
3573 /* prepare for streaming again */
3575 GST_DEBUG_OBJECT (parse, "sending flush stop");
3576 gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop ());
3577 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop ());
3578 gst_base_parse_clear_queues (parse);
3580 if (parse->priv->close_segment)
3581 gst_event_unref (parse->priv->close_segment);
3583 parse->priv->close_segment = gst_event_new_new_segment (TRUE,
3584 parse->segment.rate, parse->segment.applied_rate,
3585 parse->segment.format, parse->segment.accum, parse->segment.last_stop,
3586 parse->segment.accum);
3588 /* keep track of our last_stop */
3589 seeksegment.accum = parse->segment.last_stop;
3591 GST_DEBUG_OBJECT (parse, "Created close seg format %d, "
3592 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3593 ", pos = %" GST_TIME_FORMAT, format,
3594 GST_TIME_ARGS (parse->segment.accum),
3595 GST_TIME_ARGS (parse->segment.last_stop),
3596 GST_TIME_ARGS (parse->segment.accum));
3599 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3601 /* store the newsegment event so it can be sent from the streaming thread. */
3602 if (parse->priv->pending_segment)
3603 gst_event_unref (parse->priv->pending_segment);
3605 /* This will be sent later in _loop() */
3606 parse->priv->pending_segment =
3607 gst_event_new_new_segment (FALSE, parse->segment.rate,
3608 parse->segment.applied_rate,
3609 parse->segment.format, parse->segment.start,
3610 parse->segment.stop, parse->segment.start);
3612 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3613 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3614 ", pos = %" GST_TIME_FORMAT, format,
3615 GST_TIME_ARGS (parse->segment.start),
3616 GST_TIME_ARGS (parse->segment.stop),
3617 GST_TIME_ARGS (parse->segment.start));
3619 /* one last chance in pull mode to stay accurate;
3620 * maybe scan and subclass can find where to go */
3623 GstClockTime ts = seeksegment.last_stop;
3625 gst_base_parse_locate_time (parse, &ts, &scanpos);
3629 /* running collected index now consists of several intervals,
3630 * so optimized check no longer possible */
3631 parse->priv->index_last_valid = FALSE;
3632 parse->priv->index_last_offset = 0;
3633 parse->priv->index_last_ts = 0;
3637 /* mark discont if we are going to stream from another position. */
3638 if (seekpos != parse->priv->offset) {
3639 GST_DEBUG_OBJECT (parse,
3640 "mark DISCONT, we did a seek to another position");
3641 parse->priv->offset = seekpos;
3642 parse->priv->last_offset = seekpos;
3643 parse->priv->seen_keyframe = FALSE;
3644 parse->priv->discont = TRUE;
3645 parse->priv->next_ts = start_ts;
3646 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3647 parse->priv->sync_offset = seekpos;
3648 parse->priv->exact_position = accurate;
3651 /* Start streaming thread if paused */
3652 gst_pad_start_task (parse->sinkpad,
3653 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3655 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3660 GstEvent *new_event;
3661 GstBaseParseSeek *seek;
3663 /* The only thing we need to do in PUSH-mode is to send the
3664 seek event (in bytes) to upstream. Segment / flush handling happens
3665 in corresponding src event handlers */
3666 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3667 if (seekstop >= 0 && seekpos <= seekpos)
3669 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flush,
3670 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3672 /* store segment info so its precise details can be reconstructed when
3673 * receiving newsegment;
3674 * this matters for all details when accurate seeking,
3675 * is most useful to preserve NONE stop time otherwise */
3676 seek = g_new0 (GstBaseParseSeek, 1);
3677 seek->segment = seeksegment;
3678 seek->accurate = accurate;
3679 seek->offset = seekpos;
3680 seek->start_ts = start_ts;
3681 GST_OBJECT_LOCK (parse);
3682 /* less optimal, but preserves order */
3683 parse->priv->pending_seeks =
3684 g_slist_append (parse->priv->pending_seeks, seek);
3685 GST_OBJECT_UNLOCK (parse);
3687 res = gst_pad_push_event (parse->sinkpad, new_event);
3690 GST_OBJECT_LOCK (parse);
3691 parse->priv->pending_seeks =
3692 g_slist_remove (parse->priv->pending_seeks, seek);
3693 GST_OBJECT_UNLOCK (parse);
3699 /* handled event is ours to free */
3701 gst_event_unref (event);
3707 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
3713 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3719 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3725 /* Checks if bitrates are available from upstream tags so that we don't
3726 * override them later
3729 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
3731 GstTagList *taglist = NULL;
3734 gst_event_parse_tag (event, &taglist);
3736 if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
3737 GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
3738 parse->priv->post_min_bitrate = FALSE;
3740 if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
3741 GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
3742 parse->priv->post_avg_bitrate = FALSE;
3744 if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
3745 GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
3746 parse->priv->post_max_bitrate = FALSE;
3751 gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps)
3753 GstBaseParse *parse;
3754 GstBaseParseClass *klass;
3755 gboolean res = TRUE;
3757 parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3758 klass = GST_BASE_PARSE_GET_CLASS (parse);
3760 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
3762 if (klass->set_sink_caps)
3763 res = klass->set_sink_caps (parse, caps);
3769 gst_base_parse_set_index (GstElement * element, GstIndex * index)
3771 GstBaseParse *parse = GST_BASE_PARSE (element);
3773 g_static_mutex_lock (&parse->priv->index_lock);
3774 if (parse->priv->index)
3775 gst_object_unref (parse->priv->index);
3777 parse->priv->index = gst_object_ref (index);
3778 gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
3779 &parse->priv->index_id);
3780 parse->priv->own_index = FALSE;
3782 parse->priv->index = NULL;
3784 g_static_mutex_unlock (&parse->priv->index_lock);
3788 gst_base_parse_get_index (GstElement * element)
3790 GstBaseParse *parse = GST_BASE_PARSE (element);
3791 GstIndex *result = NULL;
3793 g_static_mutex_lock (&parse->priv->index_lock);
3794 if (parse->priv->index)
3795 result = gst_object_ref (parse->priv->index);
3796 g_static_mutex_unlock (&parse->priv->index_lock);
3801 static GstStateChangeReturn
3802 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
3804 GstBaseParse *parse;
3805 GstStateChangeReturn result;
3807 parse = GST_BASE_PARSE (element);
3809 switch (transition) {
3810 case GST_STATE_CHANGE_READY_TO_PAUSED:
3811 /* If this is our own index destroy it as the
3812 * old entries might be wrong for the new stream */
3813 g_static_mutex_lock (&parse->priv->index_lock);
3814 if (parse->priv->own_index) {
3815 gst_object_unref (parse->priv->index);
3816 parse->priv->index = NULL;
3817 parse->priv->own_index = FALSE;
3820 /* If no index was created, generate one */
3821 if (G_UNLIKELY (!parse->priv->index)) {
3822 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
3824 parse->priv->index = gst_index_factory_make ("memindex");
3825 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
3826 &parse->priv->index_id);
3827 parse->priv->own_index = TRUE;
3829 g_static_mutex_unlock (&parse->priv->index_lock);
3835 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3837 switch (transition) {
3838 case GST_STATE_CHANGE_PAUSED_TO_READY:
3839 gst_base_parse_reset (parse);