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 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 /* seek table entries only maintained if upstream is BYTE seekable */
280 gboolean upstream_seekable;
281 gboolean upstream_has_duration;
282 gint64 upstream_size;
283 /* minimum distance between two index entries */
284 GstClockTimeDiff idx_interval;
285 /* ts and offset of last entry added */
286 GstClockTime index_last_ts;
287 gint64 index_last_offset;
288 gboolean index_last_valid;
290 /* timestamps currently produced are accurate, e.g. started from 0 onwards */
291 gboolean exact_position;
292 /* seek events are temporarily kept to match them with newsegments */
293 GSList *pending_seeks;
295 /* reverse playback */
296 GSList *buffers_pending;
297 GSList *buffers_queued;
298 GSList *buffers_send;
299 GstClockTime last_ts;
302 /* Newsegment event to be sent after SEEK */
303 GstEvent *pending_segment;
305 /* Segment event that closes the running segment prior to SEEK */
306 GstEvent *close_segment;
309 typedef struct _GstBaseParseSeek
314 GstClockTime start_ts;
317 static GstElementClass *parent_class = NULL;
319 static void gst_base_parse_class_init (GstBaseParseClass * klass);
320 static void gst_base_parse_init (GstBaseParse * parse,
321 GstBaseParseClass * klass);
324 gst_base_parse_get_type (void)
326 static volatile gsize base_parse_type = 0;
328 if (g_once_init_enter (&base_parse_type)) {
329 static const GTypeInfo base_parse_info = {
330 sizeof (GstBaseParseClass),
331 (GBaseInitFunc) NULL,
332 (GBaseFinalizeFunc) NULL,
333 (GClassInitFunc) gst_base_parse_class_init,
336 sizeof (GstBaseParse),
338 (GInstanceInitFunc) gst_base_parse_init,
342 _type = g_type_register_static (GST_TYPE_ELEMENT,
343 "GstBaseParse", &base_parse_info, G_TYPE_FLAG_ABSTRACT);
344 g_once_init_leave (&base_parse_type, _type);
346 return (GType) base_parse_type;
349 static void gst_base_parse_finalize (GObject * object);
351 static GstStateChangeReturn gst_base_parse_change_state (GstElement * element,
352 GstStateChange transition);
353 static void gst_base_parse_reset (GstBaseParse * parse);
355 static void gst_base_parse_set_index (GstElement * element, GstIndex * index);
356 static GstIndex *gst_base_parse_get_index (GstElement * element);
358 static gboolean gst_base_parse_sink_activate (GstPad * sinkpad);
359 static gboolean gst_base_parse_sink_activate_push (GstPad * pad,
361 static gboolean gst_base_parse_sink_activate_pull (GstPad * pad,
363 static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
365 static void gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event);
367 static gboolean gst_base_parse_src_event (GstPad * pad, GstEvent * event);
368 static gboolean gst_base_parse_sink_event (GstPad * pad, GstEvent * event);
369 static gboolean gst_base_parse_query (GstPad * pad, GstQuery * query);
370 static gboolean gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps);
371 static const GstQueryType *gst_base_parse_get_querytypes (GstPad * pad);
373 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstBuffer * buffer);
374 static void gst_base_parse_loop (GstPad * pad);
376 static gboolean gst_base_parse_check_frame (GstBaseParse * parse,
377 GstBaseParseFrame * frame, guint * framesize, gint * skipsize);
378 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
379 GstBaseParseFrame * frame);
381 static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
384 static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
387 static void gst_base_parse_drain (GstBaseParse * parse);
389 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
390 gboolean post_min, gboolean post_avg, gboolean post_max);
392 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
393 GstClockTime time, gboolean before, GstClockTime * _ts);
394 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
395 GstClockTime * _time, gint64 * _offset);
397 static GstFlowReturn gst_base_parse_process_fragment (GstBaseParse * parse,
400 static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);
402 static void gst_base_parse_frame_free (GstBaseParseFrame * frame);
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 gst_base_parse_clear_queues (parse);
457 G_OBJECT_CLASS (parent_class)->finalize (object);
461 gst_base_parse_class_init (GstBaseParseClass * klass)
463 GObjectClass *gobject_class;
464 GstElementClass *gstelement_class;
466 gobject_class = G_OBJECT_CLASS (klass);
467 g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
468 parent_class = g_type_class_peek_parent (klass);
469 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
471 gstelement_class = (GstElementClass *) klass;
472 gstelement_class->change_state =
473 GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
474 gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
475 gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
477 /* Default handlers */
478 klass->check_valid_frame = gst_base_parse_check_frame;
479 klass->parse_frame = gst_base_parse_parse_frame;
480 klass->src_event = gst_base_parse_src_eventfunc;
481 klass->convert = gst_base_parse_convert_default;
483 GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
484 "baseparse element");
488 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
490 GstPadTemplate *pad_template;
492 GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
494 parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
497 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
498 g_return_if_fail (pad_template != NULL);
499 parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
500 gst_pad_set_event_function (parse->sinkpad,
501 GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
502 gst_pad_set_setcaps_function (parse->sinkpad,
503 GST_DEBUG_FUNCPTR (gst_base_parse_sink_setcaps));
504 gst_pad_set_chain_function (parse->sinkpad,
505 GST_DEBUG_FUNCPTR (gst_base_parse_chain));
506 gst_pad_set_activate_function (parse->sinkpad,
507 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
508 gst_pad_set_activatepush_function (parse->sinkpad,
509 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_push));
510 gst_pad_set_activatepull_function (parse->sinkpad,
511 GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_pull));
512 gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
514 GST_DEBUG_OBJECT (parse, "sinkpad created");
517 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
518 g_return_if_fail (pad_template != NULL);
519 parse->srcpad = gst_pad_new_from_template (pad_template, "src");
520 gst_pad_set_event_function (parse->srcpad,
521 GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
522 gst_pad_set_query_type_function (parse->srcpad,
523 GST_DEBUG_FUNCPTR (gst_base_parse_get_querytypes));
524 gst_pad_set_query_function (parse->srcpad,
525 GST_DEBUG_FUNCPTR (gst_base_parse_query));
526 gst_pad_use_fixed_caps (parse->srcpad);
527 gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
528 GST_DEBUG_OBJECT (parse, "src created");
530 g_queue_init (&parse->priv->queued_frames);
532 parse->priv->adapter = gst_adapter_new ();
534 parse->priv->pad_mode = GST_ACTIVATE_NONE;
537 gst_base_parse_reset (parse);
538 GST_DEBUG_OBJECT (parse, "init ok");
541 static GstBaseParseFrame *
542 gst_base_parse_frame_copy (GstBaseParseFrame * frame)
544 GstBaseParseFrame *copy;
546 copy = g_slice_dup (GstBaseParseFrame, frame);
547 copy->buffer = gst_buffer_ref (frame->buffer);
548 copy->_private_flags &= ~GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
554 gst_base_parse_frame_free (GstBaseParseFrame * frame)
557 gst_buffer_unref (frame->buffer);
558 frame->buffer = NULL;
561 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC))
562 g_slice_free (GstBaseParseFrame, frame);
566 gst_base_parse_frame_get_type (void)
568 static volatile gsize frame_type = 0;
570 if (g_once_init_enter (&frame_type)) {
573 _type = g_boxed_type_register_static ("GstBaseParseFrame",
574 (GBoxedCopyFunc) gst_base_parse_frame_copy,
575 (GBoxedFreeFunc) gst_base_parse_frame_free);
576 g_once_init_leave (&frame_type, _type);
578 return (GType) frame_type;
582 * gst_base_parse_frame_init:
583 * @frame: #GstBaseParseFrame.
585 * Sets a #GstBaseParseFrame to initial state. Currently this means
586 * all public fields are zero-ed and a private flag is set to make
587 * sure gst_base_parse_frame_free() only frees the contents but not
588 * the actual frame. Use this function to initialise a #GstBaseParseFrame
589 * allocated on the stack.
594 gst_base_parse_frame_init (GstBaseParseFrame * frame)
596 memset (frame, 0, sizeof (GstBaseParseFrame));
597 frame->_private_flags = GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
601 * gst_base_parse_frame_new:
602 * @buffer: (transfer none): a #GstBuffer
604 * @overhead: number of bytes in this frame which should be counted as
605 * metadata overhead, ie. not used to calculate the average bitrate.
606 * Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
608 * Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
609 * elements written in C should usually allocate the frame on the stack and
610 * then use gst_base_parse_frame_init() to initialise it.
612 * Returns: a newly-allocated #GstBaseParseFrame. Free with
613 * gst_base_parse_frame_free() when no longer needed, unless you gave
614 * away ownership to gst_base_parse_push_frame().
619 gst_base_parse_frame_new (GstBuffer * buffer, GstBaseParseFrameFlags flags,
622 GstBaseParseFrame *frame;
624 frame = g_slice_new0 (GstBaseParseFrame);
625 frame->buffer = gst_buffer_ref (buffer);
631 gst_base_parse_frame_update (GstBaseParse * parse, GstBaseParseFrame * frame,
634 gst_buffer_replace (&frame->buffer, buf);
638 /* set flags one by one for clarity */
639 if (G_UNLIKELY (parse->priv->drain))
640 parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;
642 /* losing sync is pretty much a discont (and vice versa), no ? */
643 if (G_UNLIKELY (parse->priv->discont))
644 parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
648 gst_base_parse_reset (GstBaseParse * parse)
650 GST_OBJECT_LOCK (parse);
651 gst_segment_init (&parse->segment, GST_FORMAT_TIME);
652 parse->priv->duration = -1;
653 parse->priv->min_frame_size = 1;
654 parse->priv->discont = TRUE;
655 parse->priv->flushing = FALSE;
656 parse->priv->offset = 0;
657 parse->priv->sync_offset = 0;
658 parse->priv->update_interval = -1;
659 parse->priv->fps_num = parse->priv->fps_den = 0;
660 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
661 parse->priv->lead_in = parse->priv->lead_out = 0;
662 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
663 parse->priv->bitrate = 0;
664 parse->priv->framecount = 0;
665 parse->priv->bytecount = 0;
666 parse->priv->acc_duration = 0;
667 parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
668 parse->priv->first_frame_offset = -1;
669 parse->priv->estimated_duration = -1;
670 parse->priv->next_ts = 0;
671 parse->priv->syncable = TRUE;
672 parse->priv->passthrough = FALSE;
673 parse->priv->has_timing_info = FALSE;
674 parse->priv->post_min_bitrate = TRUE;
675 parse->priv->post_avg_bitrate = TRUE;
676 parse->priv->post_max_bitrate = TRUE;
677 parse->priv->min_bitrate = G_MAXUINT;
678 parse->priv->max_bitrate = 0;
679 parse->priv->avg_bitrate = 0;
680 parse->priv->posted_avg_bitrate = 0;
682 parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
683 parse->priv->index_last_offset = -1;
684 parse->priv->index_last_valid = TRUE;
685 parse->priv->upstream_seekable = FALSE;
686 parse->priv->upstream_size = 0;
687 parse->priv->upstream_has_duration = FALSE;
688 parse->priv->idx_interval = 0;
689 parse->priv->exact_position = TRUE;
690 parse->priv->seen_keyframe = FALSE;
692 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
693 parse->priv->last_offset = 0;
695 if (parse->priv->pending_segment) {
696 gst_event_unref (parse->priv->pending_segment);
697 parse->priv->pending_segment = NULL;
700 g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
702 g_list_free (parse->priv->pending_events);
703 parse->priv->pending_events = NULL;
705 if (parse->priv->cache) {
706 gst_buffer_unref (parse->priv->cache);
707 parse->priv->cache = NULL;
710 g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
711 g_slist_free (parse->priv->pending_seeks);
712 parse->priv->pending_seeks = NULL;
713 GST_OBJECT_UNLOCK (parse);
716 /* gst_base_parse_check_frame:
717 * @parse: #GstBaseParse.
718 * @buffer: GstBuffer.
719 * @framesize: This will be set to tell the found frame size in bytes.
720 * @skipsize: Output parameter that tells how much data needs to be skipped
721 * in order to find the following frame header.
723 * Default callback for check_valid_frame.
725 * Returns: Always TRUE.
728 gst_base_parse_check_frame (GstBaseParse * parse,
729 GstBaseParseFrame * frame, guint * framesize, gint * skipsize)
731 *framesize = GST_BUFFER_SIZE (frame->buffer);
737 /* gst_base_parse_parse_frame:
738 * @parse: #GstBaseParse.
739 * @buffer: #GstBuffer.
741 * Default callback for parse_frame.
744 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
746 GstBuffer *buffer = frame->buffer;
748 if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
749 GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
750 GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
752 if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
753 GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
754 GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
759 /* gst_base_parse_convert:
760 * @parse: #GstBaseParse.
761 * @src_format: #GstFormat describing the source format.
762 * @src_value: Source value to be converted.
763 * @dest_format: #GstFormat defining the converted format.
764 * @dest_value: Pointer where the conversion result will be put.
766 * Converts using configured "convert" vmethod in #GstBaseParse class.
768 * Returns: TRUE if conversion was successful.
771 gst_base_parse_convert (GstBaseParse * parse,
772 GstFormat src_format,
773 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
775 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
778 g_return_val_if_fail (dest_value != NULL, FALSE);
783 ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
785 #ifndef GST_DISABLE_GST_DEBUG
788 if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
789 GST_LOG_OBJECT (parse,
790 "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
791 GST_TIME_ARGS (src_value), *dest_value);
792 } else if (dest_format == GST_FORMAT_TIME &&
793 src_format == GST_FORMAT_BYTES) {
794 GST_LOG_OBJECT (parse,
795 "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
796 src_value, GST_TIME_ARGS (*dest_value));
798 GST_LOG_OBJECT (parse,
799 "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
800 GST_STR_NULL (gst_format_get_name (src_format)),
801 GST_STR_NULL (gst_format_get_name (dest_format)),
802 src_value, *dest_value);
805 GST_DEBUG_OBJECT (parse, "conversion failed");
813 /* gst_base_parse_sink_event:
814 * @pad: #GstPad that received the event.
815 * @event: #GstEvent to be handled.
817 * Handler for sink pad events.
819 * Returns: TRUE if the event was handled.
822 gst_base_parse_sink_event (GstPad * pad, GstEvent * event)
825 GstBaseParseClass *bclass;
826 gboolean handled = FALSE;
829 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
830 bclass = GST_BASE_PARSE_GET_CLASS (parse);
832 GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
833 GST_EVENT_TYPE_NAME (event));
835 /* Cache all events except EOS, NEWSEGMENT and FLUSH_STOP if we have a
837 if (parse->priv->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
838 && GST_EVENT_TYPE (event) != GST_EVENT_NEWSEGMENT
839 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
840 && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP) {
842 if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
843 /* See if any bitrate tags were posted */
844 gst_base_parse_handle_tag (parse, event);
846 parse->priv->pending_events =
847 g_list_append (parse->priv->pending_events, event);
851 if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
852 parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
853 /* We've not posted bitrate tags yet - do so now */
854 gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
857 handled = bclass->event (parse, event);
860 handled = gst_base_parse_sink_eventfunc (parse, event);
863 ret = gst_pad_event_default (pad, event);
866 gst_object_unref (parse);
867 GST_DEBUG_OBJECT (parse, "event handled");
872 /* gst_base_parse_sink_eventfunc:
873 * @parse: #GstBaseParse.
874 * @event: #GstEvent to be handled.
876 * Element-level event handler function.
878 * The event will be unreffed only if it has been handled and this
879 * function returns %TRUE
881 * Returns: %TRUE if the event was handled and not need forwarding.
884 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
886 gboolean handled = FALSE;
889 switch (GST_EVENT_TYPE (event)) {
890 case GST_EVENT_NEWSEGMENT:
892 gdouble rate, applied_rate;
894 gint64 start, stop, pos, next_ts, offset = 0;
897 gst_event_parse_new_segment_full (event, &update, &rate, &applied_rate,
898 &format, &start, &stop, &pos);
900 GST_DEBUG_OBJECT (parse, "newseg rate %g, applied rate %g, "
901 "format %d, start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
902 ", pos = %" GST_TIME_FORMAT, rate, applied_rate, format,
903 GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (pos));
905 if (format == GST_FORMAT_BYTES) {
906 GstClockTime seg_start, seg_stop;
907 GstBaseParseSeek *seek = NULL;
910 /* stop time is allowed to be open-ended, but not start & pos */
911 seg_stop = GST_CLOCK_TIME_NONE;
915 GST_OBJECT_LOCK (parse);
916 for (node = parse->priv->pending_seeks; node; node = node->next) {
917 GstBaseParseSeek *tmp = node->data;
919 if (tmp->offset == pos) {
924 parse->priv->pending_seeks =
925 g_slist_remove (parse->priv->pending_seeks, seek);
926 GST_OBJECT_UNLOCK (parse);
929 GST_DEBUG_OBJECT (parse,
930 "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
931 seek->accurate ? " accurate" : "", &seek->segment);
932 seg_start = seek->segment.start;
933 seg_stop = seek->segment.stop;
934 next_ts = seek->start_ts;
935 parse->priv->exact_position = seek->accurate;
938 /* best attempt convert */
939 /* as these are only estimates, stop is kept open-ended to avoid
940 * premature cutting */
941 gst_base_parse_convert (parse, GST_FORMAT_BYTES, start,
942 GST_FORMAT_TIME, (gint64 *) & seg_start);
943 parse->priv->exact_position = (start == 0);
947 gst_event_unref (event);
948 event = gst_event_new_new_segment_full (update, rate, applied_rate,
949 GST_FORMAT_TIME, seg_start, seg_stop, seg_start);
950 format = GST_FORMAT_TIME;
953 GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. "
954 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT,
955 GST_TIME_ARGS (seg_start), GST_TIME_ARGS (seg_stop));
956 } else if (format != GST_FORMAT_TIME) {
957 /* Unknown incoming segment format. Output a default open-ended
959 gst_event_unref (event);
960 event = gst_event_new_new_segment_full (update, rate, applied_rate,
961 GST_FORMAT_TIME, 0, GST_CLOCK_TIME_NONE, 0);
962 format = GST_FORMAT_TIME;
964 stop = GST_CLOCK_TIME_NONE;
966 /* not considered BYTE seekable if it is talking to us in TIME,
967 * whatever else it might claim */
968 parse->priv->upstream_seekable = FALSE;
972 gst_segment_set_newsegment_full (&parse->segment, update, rate,
973 applied_rate, format, start, stop, start);
975 /* save the segment for later, right before we push a new buffer so that
976 * the caps are fixed and the next linked element can receive
978 eventp = &parse->priv->pending_segment;
979 gst_event_replace (eventp, event);
980 gst_event_unref (event);
983 /* but finish the current segment */
984 GST_DEBUG_OBJECT (parse, "draining current segment");
985 if (parse->segment.rate > 0.0)
986 gst_base_parse_drain (parse);
988 gst_base_parse_process_fragment (parse, FALSE);
989 gst_adapter_clear (parse->priv->adapter);
990 parse->priv->offset = offset;
991 parse->priv->sync_offset = offset;
992 parse->priv->next_ts = next_ts;
993 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
994 parse->priv->discont = TRUE;
995 parse->priv->seen_keyframe = FALSE;
999 case GST_EVENT_FLUSH_START:
1000 parse->priv->flushing = TRUE;
1001 handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
1003 gst_event_unref (event);
1004 /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
1005 GST_PAD_STREAM_LOCK (parse->srcpad);
1006 GST_PAD_STREAM_UNLOCK (parse->srcpad);
1010 case GST_EVENT_FLUSH_STOP:
1011 gst_adapter_clear (parse->priv->adapter);
1012 gst_base_parse_clear_queues (parse);
1013 parse->priv->flushing = FALSE;
1014 parse->priv->discont = TRUE;
1015 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
1019 if (parse->segment.rate > 0.0)
1020 gst_base_parse_drain (parse);
1022 gst_base_parse_process_fragment (parse, FALSE);
1024 /* If we STILL have zero frames processed, fire an error */
1025 if (parse->priv->framecount == 0) {
1026 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1027 ("No valid frames found before end of stream"), (NULL));
1029 /* newsegment before eos */
1030 if (parse->priv->pending_segment) {
1031 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1032 parse->priv->pending_segment = NULL;
1044 /* gst_base_parse_src_event:
1045 * @pad: #GstPad that received the event.
1046 * @event: #GstEvent that was received.
1048 * Handler for source pad events.
1050 * Returns: TRUE if the event was handled.
1053 gst_base_parse_src_event (GstPad * pad, GstEvent * event)
1055 GstBaseParse *parse;
1056 GstBaseParseClass *bclass;
1057 gboolean handled = FALSE;
1058 gboolean ret = TRUE;
1060 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
1061 bclass = GST_BASE_PARSE_GET_CLASS (parse);
1063 GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1064 GST_EVENT_TYPE_NAME (event));
1066 if (bclass->src_event)
1067 handled = bclass->src_event (parse, event);
1070 ret = gst_pad_event_default (pad, event);
1072 gst_object_unref (parse);
1077 gst_base_parse_is_seekable (GstBaseParse * parse)
1079 /* FIXME: could do more here, e.g. check index or just send data from 0
1080 * in pull mode and let decoder/sink clip */
1081 return parse->priv->syncable;
1084 /* gst_base_parse_src_eventfunc:
1085 * @parse: #GstBaseParse.
1086 * @event: #GstEvent that was received.
1088 * Default srcpad event handler.
1090 * Returns: TRUE if the event was handled and can be dropped.
1093 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1095 gboolean handled = FALSE;
1097 switch (GST_EVENT_TYPE (event)) {
1098 case GST_EVENT_SEEK:
1100 if (gst_base_parse_is_seekable (parse)) {
1101 handled = gst_base_parse_handle_seek (parse, event);
1113 * gst_base_parse_convert_default:
1114 * @parse: #GstBaseParse.
1115 * @src_format: #GstFormat describing the source format.
1116 * @src_value: Source value to be converted.
1117 * @dest_format: #GstFormat defining the converted format.
1118 * @dest_value: Pointer where the conversion result will be put.
1120 * Default implementation of "convert" vmethod in #GstBaseParse class.
1122 * Returns: TRUE if conversion was successful.
1127 gst_base_parse_convert_default (GstBaseParse * parse,
1128 GstFormat src_format,
1129 gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1131 gboolean ret = FALSE;
1132 guint64 bytes, duration;
1134 if (G_UNLIKELY (src_format == dest_format)) {
1135 *dest_value = src_value;
1139 if (G_UNLIKELY (src_value == -1)) {
1144 if (G_UNLIKELY (src_value == 0)) {
1149 /* need at least some frames */
1150 if (!parse->priv->framecount)
1153 duration = parse->priv->acc_duration / GST_MSECOND;
1154 bytes = parse->priv->bytecount;
1156 if (G_UNLIKELY (!duration || !bytes))
1159 if (src_format == GST_FORMAT_BYTES) {
1160 if (dest_format == GST_FORMAT_TIME) {
1161 /* BYTES -> TIME conversion */
1162 GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1163 *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1164 *dest_value *= GST_MSECOND;
1165 GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1166 *dest_value / GST_MSECOND);
1169 } else if (src_format == GST_FORMAT_TIME) {
1170 if (dest_format == GST_FORMAT_BYTES) {
1171 GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1172 *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1174 GST_DEBUG_OBJECT (parse,
1175 "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1176 src_value / GST_MSECOND, *dest_value);
1179 } else if (src_format == GST_FORMAT_DEFAULT) {
1180 /* DEFAULT == frame-based */
1181 if (dest_format == GST_FORMAT_TIME) {
1182 if (parse->priv->fps_den) {
1183 *dest_value = gst_util_uint64_scale (src_value,
1184 GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1187 } else if (dest_format == GST_FORMAT_BYTES) {
1195 gst_base_parse_update_duration (GstBaseParse * baseparse)
1198 GstBaseParse *parse;
1200 parse = GST_BASE_PARSE (baseparse);
1202 peer = gst_pad_get_peer (parse->sinkpad);
1204 GstFormat pformat = GST_FORMAT_BYTES;
1205 gboolean qres = FALSE;
1206 gint64 ptot, dest_value;
1208 qres = gst_pad_query_duration (peer, &pformat, &ptot);
1209 gst_object_unref (GST_OBJECT (peer));
1211 if (gst_base_parse_convert (parse, pformat, ptot,
1212 GST_FORMAT_TIME, &dest_value)) {
1213 parse->priv->estimated_duration = dest_value;
1214 GST_LOG_OBJECT (parse,
1215 "updated estimated duration to %" GST_TIME_FORMAT,
1216 GST_TIME_ARGS (dest_value));
1223 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1224 gboolean post_avg, gboolean post_max)
1226 GstTagList *taglist = gst_tag_list_new ();
1228 if (post_min && parse->priv->post_min_bitrate)
1229 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1230 GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1232 if (post_avg && parse->priv->post_avg_bitrate) {
1233 parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1234 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1235 parse->priv->avg_bitrate, NULL);
1238 if (post_max && parse->priv->post_max_bitrate)
1239 gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1240 GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1242 GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1243 parse->priv->min_bitrate, parse->priv->avg_bitrate,
1244 parse->priv->max_bitrate);
1246 gst_element_found_tags_for_pad (GST_ELEMENT (parse), parse->srcpad, taglist);
1249 /* gst_base_parse_update_bitrates:
1250 * @parse: #GstBaseParse.
1251 * @buffer: Current frame as a #GstBuffer
1253 * Keeps track of the minimum and maximum bitrates, and also maintains a
1254 * running average bitrate of the stream so far.
1257 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1259 /* Only update the tag on a 10 kbps delta */
1260 static const gint update_threshold = 10000;
1262 guint64 data_len, frame_dur;
1263 gint overhead, frame_bitrate, old_avg_bitrate;
1264 gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1265 GstBuffer *buffer = frame->buffer;
1267 overhead = frame->overhead;
1271 data_len = GST_BUFFER_SIZE (buffer) - overhead;
1272 parse->priv->data_bytecount += data_len;
1274 /* duration should be valid by now,
1275 * either set by subclass or maybe based on fps settings */
1276 if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1277 /* Calculate duration of a frame from buffer properties */
1278 frame_dur = GST_BUFFER_DURATION (buffer);
1279 parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1280 parse->priv->acc_duration;
1283 /* No way to figure out frame duration (is this even possible?) */
1287 /* override if subclass provided bitrate, e.g. metadata based */
1288 if (parse->priv->bitrate) {
1289 parse->priv->avg_bitrate = parse->priv->bitrate;
1290 /* spread this (confirmed) info ASAP */
1291 if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1292 gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1296 frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1300 GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1301 parse->priv->avg_bitrate);
1303 if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1305 } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1306 /* always post all at threshold time */
1307 update_min = update_max = update_avg = TRUE;
1310 if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1311 if (frame_bitrate < parse->priv->min_bitrate) {
1312 parse->priv->min_bitrate = frame_bitrate;
1316 if (frame_bitrate > parse->priv->max_bitrate) {
1317 parse->priv->max_bitrate = frame_bitrate;
1321 old_avg_bitrate = parse->priv->posted_avg_bitrate;
1322 if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1323 || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1328 if ((update_min || update_avg || update_max))
1329 gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1331 /* If average bitrate changes that much and no valid (time) duration provided,
1332 * then post a new duration message so applications can update their cached
1334 if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1335 GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1336 gst_element_post_message (GST_ELEMENT (parse),
1337 gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1344 * gst_base_parse_add_index_entry:
1345 * @parse: #GstBaseParse.
1346 * @offset: offset of entry
1347 * @ts: timestamp associated with offset
1348 * @key: whether entry refers to keyframe
1349 * @force: add entry disregarding sanity checks
1351 * Adds an entry to the index associating @offset to @ts. It is recommended
1352 * to only add keyframe entries. @force allows to bypass checks, such as
1353 * whether the stream is (upstream) seekable, another entry is already "close"
1354 * to the new entry, etc.
1356 * Returns: #gboolean indicating whether entry was added
1361 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1362 GstClockTime ts, gboolean key, gboolean force)
1364 gboolean ret = FALSE;
1365 GstIndexAssociation associations[2];
1367 GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1368 " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1370 if (G_LIKELY (!force)) {
1372 if (!parse->priv->upstream_seekable) {
1373 GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1377 /* FIXME need better helper data structure that handles these issues
1378 * related to ongoing collecting of index entries */
1379 if (parse->priv->index_last_offset >= (gint64) offset) {
1380 GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1381 "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1385 if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1386 GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1387 parse->priv->idx_interval) {
1388 GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1389 GST_TIME_ARGS (parse->priv->index_last_ts));
1393 /* if last is not really the last one */
1394 if (!parse->priv->index_last_valid) {
1395 GstClockTime prev_ts;
1397 gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1398 if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1399 GST_DEBUG_OBJECT (parse,
1400 "entry too close to existing entry %" GST_TIME_FORMAT,
1401 GST_TIME_ARGS (prev_ts));
1402 parse->priv->index_last_offset = offset;
1403 parse->priv->index_last_ts = ts;
1409 associations[0].format = GST_FORMAT_TIME;
1410 associations[0].value = ts;
1411 associations[1].format = GST_FORMAT_BYTES;
1412 associations[1].value = offset;
1414 /* index might change on-the-fly, although that would be nutty app ... */
1415 GST_OBJECT_LOCK (parse);
1416 gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1417 (key) ? GST_ASSOCIATION_FLAG_KEY_UNIT : GST_ASSOCIATION_FLAG_DELTA_UNIT,
1418 2, (const GstIndexAssociation *) &associations);
1419 GST_OBJECT_UNLOCK (parse);
1422 parse->priv->index_last_offset = offset;
1423 parse->priv->index_last_ts = ts;
1432 /* check for seekable upstream, above and beyond a mere query */
1434 gst_base_parse_check_seekability (GstBaseParse * parse)
1437 gboolean seekable = FALSE;
1438 gint64 start = -1, stop = -1;
1439 guint idx_interval = 0;
1441 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1442 if (!gst_pad_peer_query (parse->sinkpad, query)) {
1443 GST_DEBUG_OBJECT (parse, "seeking query failed");
1447 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1449 /* try harder to query upstream size if we didn't get it the first time */
1450 if (seekable && stop == -1) {
1451 GstFormat fmt = GST_FORMAT_BYTES;
1453 GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1454 gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop);
1457 /* if upstream doesn't know the size, it's likely that it's not seekable in
1458 * practice even if it technically may be seekable */
1459 if (seekable && (start != 0 || stop <= start)) {
1460 GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1464 /* let's not put every single frame into our index */
1466 if (stop < 10 * 1024 * 1024)
1468 else if (stop < 100 * 1024 * 1024)
1471 idx_interval = 1000;
1475 gst_query_unref (query);
1477 GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1478 G_GUINT64_FORMAT ")", seekable, start, stop);
1479 parse->priv->upstream_seekable = seekable;
1480 parse->priv->upstream_size = seekable ? stop : 0;
1482 GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1483 parse->priv->idx_interval = idx_interval * GST_MSECOND;
1486 /* some misc checks on upstream */
1488 gst_base_parse_check_upstream (GstBaseParse * parse)
1490 GstFormat fmt = GST_FORMAT_TIME;
1493 if (gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop))
1494 if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1495 /* upstream has one, accept it also, and no further updates */
1496 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1497 parse->priv->upstream_has_duration = TRUE;
1500 GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1501 parse->priv->upstream_has_duration);
1504 /* checks src caps to determine if dealing with audio or video */
1505 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1507 gst_base_parse_check_media (GstBaseParse * parse)
1512 caps = GST_PAD_CAPS (parse->srcpad);
1513 if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1514 parse->priv->is_video =
1515 g_str_has_prefix (gst_structure_get_name (s), "video");
1517 /* historical default */
1518 parse->priv->is_video = FALSE;
1521 GST_DEBUG_OBJECT (parse, "media is video == %d", parse->priv->is_video);
1524 /* gst_base_parse_handle_and_push_buffer:
1525 * @parse: #GstBaseParse.
1526 * @klass: #GstBaseParseClass.
1527 * @frame: (transfer full): a #GstBaseParseFrame
1529 * Parses the frame from given buffer and pushes it forward. Also performs
1530 * timestamp handling and checks the segment limits.
1532 * This is called with srcpad STREAM_LOCK held.
1534 * Returns: #GstFlowReturn
1536 static GstFlowReturn
1537 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1538 GstBaseParseClass * klass, GstBaseParseFrame * frame)
1544 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1546 buffer = frame->buffer;
1548 if (parse->priv->discont) {
1549 GST_DEBUG_OBJECT (parse, "marking DISCONT");
1550 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1551 parse->priv->discont = FALSE;
1554 /* some one-time start-up */
1555 if (G_UNLIKELY (!parse->priv->framecount)) {
1556 gst_base_parse_check_seekability (parse);
1557 gst_base_parse_check_upstream (parse);
1560 GST_LOG_OBJECT (parse,
1561 "parsing frame at offset %" G_GUINT64_FORMAT
1562 " (%#" G_GINT64_MODIFIER "x) of size %d",
1563 GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1564 GST_BUFFER_SIZE (buffer));
1566 /* use default handler to provide initial (upstream) metadata */
1567 gst_base_parse_parse_frame (parse, frame);
1569 /* store offset as it might get overwritten */
1570 offset = GST_BUFFER_OFFSET (buffer);
1571 ret = klass->parse_frame (parse, frame);
1573 buffer = frame->buffer;
1574 /* subclass must play nice */
1575 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1577 /* check if subclass/format can provide ts.
1578 * If so, that allows and enables extra seek and duration determining options */
1579 if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
1580 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && parse->priv->has_timing_info
1581 && parse->priv->pad_mode == GST_ACTIVATE_PULL) {
1582 parse->priv->first_frame_offset = offset;
1583 parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
1584 GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
1585 " for first frame at offset %" G_GINT64_FORMAT,
1586 GST_TIME_ARGS (parse->priv->first_frame_ts),
1587 parse->priv->first_frame_offset);
1588 if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1590 GstClockTime last_ts = G_MAXINT64;
1592 GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1593 gst_base_parse_locate_time (parse, &last_ts, &off);
1594 if (GST_CLOCK_TIME_IS_VALID (last_ts))
1595 gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1598 /* disable further checks */
1599 parse->priv->first_frame_offset = 0;
1603 /* again use default handler to add missing metadata;
1604 * we may have new information on frame properties */
1605 gst_base_parse_parse_frame (parse, frame);
1606 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1607 GST_BUFFER_DURATION_IS_VALID (buffer)) {
1608 parse->priv->next_ts =
1609 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1611 /* we lost track, do not produce bogus time next time around
1612 * (probably means parser subclass has given up on parsing as well) */
1613 GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1614 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1617 if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1618 GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1619 gst_base_parse_add_index_entry (parse, offset,
1620 GST_BUFFER_TIMESTAMP (buffer),
1621 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1623 /* First buffers are dropped, this means that the subclass needs more
1624 * frames to decide on the format and queues them internally */
1625 /* convert internal flow to OK and mark discont for the next buffer. */
1626 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1627 gst_base_parse_frame_free (frame);
1629 } else if (ret == GST_BASE_PARSE_FLOW_QUEUED) {
1630 if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1631 /* frame allocated on the heap, we can just take ownership */
1632 g_queue_push_tail (&parse->priv->queued_frames, frame);
1634 /* probably allocated on the stack, must make a proper copy */
1635 g_queue_push_tail (&parse->priv->queued_frames,
1636 gst_base_parse_frame_copy (frame));
1637 gst_base_parse_frame_free (frame);
1640 } else if (ret != GST_FLOW_OK) {
1644 /* All OK, push queued frames if there are any */
1645 if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
1646 GstBaseParseFrame *queued_frame;
1648 while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
1649 queued_frame->buffer =
1650 gst_buffer_make_metadata_writable (queued_frame->buffer);
1651 gst_buffer_set_caps (queued_frame->buffer,
1652 GST_PAD_CAPS (GST_BASE_PARSE_SRC_PAD (parse)));
1653 gst_base_parse_push_frame (parse, queued_frame);
1654 gst_base_parse_frame_free (queued_frame);
1658 return gst_base_parse_push_frame (parse, frame);
1662 * gst_base_parse_push_frame:
1663 * @parse: #GstBaseParse.
1664 * @frame: (transfer full): a #GstBaseParseFrame
1666 * Pushes the frame downstream, sends any pending events and
1667 * does some timestamp and segment handling. Takes ownership
1668 * of @frame and will clear it (if it was initialised with
1669 * gst_base_parse_frame_init()) or free it.
1671 * This must be called with sinkpad STREAM_LOCK held.
1673 * Returns: #GstFlowReturn
1678 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1680 GstFlowReturn ret = GST_FLOW_OK;
1681 GstClockTime last_start = GST_CLOCK_TIME_NONE;
1682 GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1683 GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1686 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1687 g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
1689 buffer = frame->buffer;
1691 GST_LOG_OBJECT (parse,
1692 "processing buffer of size %d with ts %" GST_TIME_FORMAT
1693 ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
1694 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1695 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1698 parse->priv->bytecount += GST_BUFFER_SIZE (buffer);
1699 if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
1700 parse->priv->framecount++;
1701 if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1702 parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1705 /* 0 means disabled */
1706 if (parse->priv->update_interval < 0)
1707 parse->priv->update_interval = 50;
1708 else if (parse->priv->update_interval > 0 &&
1709 (parse->priv->framecount % parse->priv->update_interval) == 0)
1710 gst_base_parse_update_duration (parse);
1712 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1713 last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1714 if (last_start != GST_CLOCK_TIME_NONE
1715 && GST_BUFFER_DURATION_IS_VALID (buffer))
1716 last_stop = last_start + GST_BUFFER_DURATION (buffer);
1718 /* should have caps by now */
1719 g_return_val_if_fail (GST_PAD_CAPS (parse->srcpad), GST_FLOW_ERROR);
1721 /* segment adjustment magic; only if we are running the whole show */
1722 if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1723 (parse->priv->pad_mode == GST_ACTIVATE_PULL ||
1724 parse->priv->upstream_seekable)) {
1725 /* segment times are typically estimates,
1726 * actual frame data might lead subclass to different timestamps,
1727 * so override segment start from what is supplied there */
1728 if (G_UNLIKELY (parse->priv->pending_segment && !parse->priv->exact_position
1729 && GST_CLOCK_TIME_IS_VALID (last_start))) {
1730 gst_event_unref (parse->priv->pending_segment);
1731 parse->segment.start =
1732 MIN ((guint64) last_start, (guint64) parse->segment.stop);
1733 GST_DEBUG_OBJECT (parse,
1734 "adjusting pending segment start to %" GST_TIME_FORMAT,
1735 GST_TIME_ARGS (parse->segment.start));
1736 parse->priv->pending_segment =
1737 gst_event_new_new_segment (FALSE, parse->segment.rate,
1738 parse->segment.format, parse->segment.start,
1739 parse->segment.stop, parse->segment.start);
1741 /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1742 if (GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop) &&
1743 GST_CLOCK_TIME_IS_VALID (last_start)) {
1744 GstClockTimeDiff diff;
1746 /* only send newsegments with increasing start times,
1747 * otherwise if these go back and forth downstream (sinks) increase
1748 * accumulated time and running_time */
1749 diff = GST_CLOCK_DIFF (parse->segment.last_stop, last_start);
1750 if (G_UNLIKELY (diff > 2 * GST_SECOND
1751 && last_start > parse->segment.start
1752 && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
1753 || last_start < parse->segment.stop))) {
1754 GST_DEBUG_OBJECT (parse,
1755 "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
1756 GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1757 "Sending updated NEWSEGMENT events", diff,
1758 GST_TIME_ARGS (parse->segment.last_stop),
1759 GST_TIME_ARGS (last_start));
1760 if (G_UNLIKELY (parse->priv->pending_segment)) {
1761 gst_event_unref (parse->priv->pending_segment);
1762 parse->segment.start = last_start;
1763 parse->priv->pending_segment =
1764 gst_event_new_new_segment (FALSE, parse->segment.rate,
1765 parse->segment.format, parse->segment.start,
1766 parse->segment.stop, parse->segment.start);
1768 /* send newsegment events such that the gap is not accounted in
1769 * accum time, hence running_time */
1770 /* close ahead of gap */
1771 gst_pad_push_event (parse->srcpad,
1772 gst_event_new_new_segment (TRUE, parse->segment.rate,
1773 parse->segment.format, parse->segment.last_stop,
1774 parse->segment.last_stop, parse->segment.last_stop));
1776 gst_pad_push_event (parse->srcpad,
1777 gst_event_new_new_segment (FALSE, parse->segment.rate,
1778 parse->segment.format, last_start,
1779 parse->segment.stop, last_start));
1781 /* align segment view with downstream,
1782 * prevents double-counting accum when closing segment */
1783 gst_segment_set_newsegment (&parse->segment, FALSE,
1784 parse->segment.rate, parse->segment.format, last_start,
1785 parse->segment.stop, last_start);
1786 parse->segment.last_stop = last_start;
1791 /* and should then also be linked downstream, so safe to send some events */
1792 if (G_UNLIKELY (parse->priv->close_segment)) {
1793 /* only set up by loop */
1794 GST_DEBUG_OBJECT (parse, "loop sending close segment");
1795 gst_pad_push_event (parse->srcpad, parse->priv->close_segment);
1796 parse->priv->close_segment = NULL;
1798 if (G_UNLIKELY (parse->priv->pending_segment)) {
1799 GST_DEBUG_OBJECT (parse, "%s push pending segment",
1800 parse->priv->pad_mode == GST_ACTIVATE_PULL ? "loop" : "chain");
1801 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
1802 parse->priv->pending_segment = NULL;
1804 /* have caps; check identity */
1805 gst_base_parse_check_media (parse);
1808 /* update bitrates and optionally post corresponding tags
1809 * (following newsegment) */
1810 gst_base_parse_update_bitrates (parse, frame);
1812 if (G_UNLIKELY (parse->priv->pending_events)) {
1815 for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1816 gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1818 g_list_free (parse->priv->pending_events);
1819 parse->priv->pending_events = NULL;
1822 if (klass->pre_push_frame) {
1823 ret = klass->pre_push_frame (parse, frame);
1825 frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
1828 /* take final ownership of frame buffer */
1829 buffer = frame->buffer;
1830 frame->buffer = NULL;
1832 /* subclass must play nice */
1833 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1836 buffer = gst_buffer_make_metadata_writable (buffer);
1837 gst_buffer_set_caps (buffer, GST_PAD_CAPS (parse->srcpad));
1839 parse->priv->seen_keyframe |= parse->priv->is_video &&
1840 !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1842 if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
1843 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1844 GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
1845 GST_BUFFER_TIMESTAMP (buffer) >
1846 parse->segment.stop + parse->priv->lead_out_ts) {
1847 GST_LOG_OBJECT (parse, "Dropped frame, after segment");
1848 ret = GST_FLOW_UNEXPECTED;
1849 } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1850 GST_BUFFER_DURATION_IS_VALID (buffer) &&
1851 GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
1852 GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
1853 parse->priv->lead_in_ts < parse->segment.start) {
1854 if (parse->priv->seen_keyframe) {
1855 GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
1858 GST_LOG_OBJECT (parse, "Dropped frame, before segment");
1859 ret = GST_BASE_PARSE_FLOW_DROPPED;
1866 if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1867 GST_LOG_OBJECT (parse, "frame (%d bytes) dropped",
1868 GST_BUFFER_SIZE (buffer));
1869 gst_buffer_unref (buffer);
1871 } else if (ret == GST_FLOW_OK) {
1872 if (parse->segment.rate > 0.0) {
1873 ret = gst_pad_push (parse->srcpad, buffer);
1874 GST_LOG_OBJECT (parse, "frame (%d bytes) pushed: %s",
1875 GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
1877 GST_LOG_OBJECT (parse, "frame (%d bytes) queued for now",
1878 GST_BUFFER_SIZE (buffer));
1879 parse->priv->buffers_queued =
1880 g_slist_prepend (parse->priv->buffers_queued, buffer);
1884 gst_buffer_unref (buffer);
1885 GST_LOG_OBJECT (parse, "frame (%d bytes) not pushed: %s",
1886 GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
1887 /* if we are not sufficiently in control, let upstream decide on EOS */
1888 if (ret == GST_FLOW_UNEXPECTED &&
1889 (parse->priv->passthrough ||
1890 (parse->priv->pad_mode == GST_ACTIVATE_PUSH &&
1891 !parse->priv->upstream_seekable)))
1895 /* Update current running segment position */
1896 if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
1897 parse->segment.last_stop < last_stop)
1898 gst_segment_set_last_stop (&parse->segment, GST_FORMAT_TIME, last_stop);
1900 gst_base_parse_frame_free (frame);
1906 /* gst_base_parse_drain:
1908 * Drains the adapter until it is empty. It decreases the min_frame_size to
1909 * match the current adapter size and calls chain method until the adapter
1910 * is emptied or chain returns with error.
1913 gst_base_parse_drain (GstBaseParse * parse)
1917 GST_DEBUG_OBJECT (parse, "draining");
1918 parse->priv->drain = TRUE;
1921 avail = gst_adapter_available (parse->priv->adapter);
1925 if (gst_base_parse_chain (parse->sinkpad, NULL) != GST_FLOW_OK) {
1929 /* nothing changed, maybe due to truncated frame; break infinite loop */
1930 if (avail == gst_adapter_available (parse->priv->adapter)) {
1931 GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
1932 gst_adapter_clear (parse->priv->adapter);
1936 parse->priv->drain = FALSE;
1939 /* gst_base_parse_send_buffers
1941 * Sends buffers collected in send_buffers downstream, and ensures that list
1942 * is empty at the end (errors or not).
1944 static GstFlowReturn
1945 gst_base_parse_send_buffers (GstBaseParse * parse)
1947 GSList *send = NULL;
1949 GstFlowReturn ret = GST_FLOW_OK;
1951 send = parse->priv->buffers_send;
1955 buf = GST_BUFFER_CAST (send->data);
1956 GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
1957 GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
1958 ", offset %" G_GINT64_FORMAT, buf,
1959 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1960 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
1962 /* iterate output queue an push downstream */
1963 ret = gst_pad_push (parse->srcpad, buf);
1964 send = g_slist_delete_link (send, send);
1966 /* clear any leftover if error */
1967 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
1969 buf = GST_BUFFER_CAST (send->data);
1970 gst_buffer_unref (buf);
1971 send = g_slist_delete_link (send, send);
1976 parse->priv->buffers_send = send;
1981 /* gst_base_parse_process_fragment:
1983 * Processes a reverse playback (forward) fragment:
1984 * - append head of last fragment that was skipped to current fragment data
1985 * - drain the resulting current fragment data (i.e. repeated chain)
1986 * - add time/duration (if needed) to frames queued by chain
1987 * - push queued data
1989 static GstFlowReturn
1990 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
1993 GstFlowReturn ret = GST_FLOW_OK;
1994 gboolean seen_key = FALSE, seen_delta = FALSE;
2000 parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2001 while (parse->priv->buffers_pending) {
2002 buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2003 GST_LOG_OBJECT (parse, "adding pending buffer (size %d)",
2004 GST_BUFFER_SIZE (buf));
2005 gst_adapter_push (parse->priv->adapter, buf);
2006 parse->priv->buffers_pending =
2007 g_slist_delete_link (parse->priv->buffers_pending,
2008 parse->priv->buffers_pending);
2011 /* invalidate so no fall-back timestamping is performed;
2012 * ok if taken from subclass or upstream */
2013 parse->priv->next_ts = GST_CLOCK_TIME_NONE;
2014 /* prevent it hanging around stop all the time */
2015 parse->segment.last_stop = GST_CLOCK_TIME_NONE;
2017 parse->priv->discont = TRUE;
2019 /* chain looks for frames and queues resulting ones (in stead of pushing) */
2020 /* initial skipped data is added to buffers_pending */
2021 gst_base_parse_drain (parse);
2024 if (parse->priv->buffers_send) {
2025 buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2026 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2029 /* add metadata (if needed to queued buffers */
2030 GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2031 GST_TIME_ARGS (parse->priv->last_ts));
2032 while (parse->priv->buffers_queued) {
2033 buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2035 /* no touching if upstream or parsing provided time */
2036 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2037 GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2038 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2039 } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
2040 GST_BUFFER_DURATION_IS_VALID (buf)) {
2041 if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
2042 parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
2044 parse->priv->last_ts = 0;
2045 GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
2046 GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2047 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2049 /* no idea, very bad */
2050 GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2053 parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
2055 /* reverse order for ascending sending */
2056 /* send downstream at keyframe not preceded by a keyframe
2057 * (e.g. that should identify start of collection of IDR nals) */
2058 if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2060 ret = gst_base_parse_send_buffers (parse);
2061 /* if a problem, throw all to sending */
2062 if (ret != GST_FLOW_OK) {
2063 parse->priv->buffers_send =
2064 g_slist_reverse (parse->priv->buffers_queued);
2065 parse->priv->buffers_queued = NULL;
2074 seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2076 parse->priv->buffers_send =
2077 g_slist_prepend (parse->priv->buffers_send, buf);
2078 parse->priv->buffers_queued =
2079 g_slist_delete_link (parse->priv->buffers_queued,
2080 parse->priv->buffers_queued);
2083 /* audio may have all marked as keyframe, so arrange to send here */
2085 ret = gst_base_parse_send_buffers (parse);
2087 /* any trailing unused no longer usable (ideally none) */
2088 if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2089 GST_DEBUG_OBJECT (parse, "discarding %d trailing bytes",
2090 gst_adapter_available (parse->priv->adapter));
2091 gst_adapter_clear (parse->priv->adapter);
2097 /* small helper that checks whether we have been trying to resync too long */
2098 static inline GstFlowReturn
2099 gst_base_parse_check_sync (GstBaseParse * parse)
2101 if (G_UNLIKELY (parse->priv->discont &&
2102 parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2103 GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2104 ("Failed to parse stream"), (NULL));
2105 return GST_FLOW_ERROR;
2111 static GstFlowReturn
2112 gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
2114 GstBaseParseClass *bclass;
2115 GstBaseParse *parse;
2116 GstFlowReturn ret = GST_FLOW_OK;
2117 GstBuffer *outbuf = NULL;
2118 GstBuffer *tmpbuf = NULL;
2122 guint old_min_size = 0, min_size, av;
2123 GstClockTime timestamp;
2124 GstBaseParseFrame _frame = { 0, };
2125 GstBaseParseFrame *frame;
2127 parse = GST_BASE_PARSE (GST_OBJECT_PARENT (pad));
2128 bclass = GST_BASE_PARSE_GET_CLASS (parse);
2131 if (G_LIKELY (buffer)) {
2132 GST_LOG_OBJECT (parse, "buffer size: %d, offset = %" G_GINT64_FORMAT,
2133 GST_BUFFER_SIZE (buffer), GST_BUFFER_OFFSET (buffer));
2134 if (G_UNLIKELY (parse->priv->passthrough)) {
2135 frame->buffer = gst_buffer_make_metadata_writable (buffer);
2136 return gst_base_parse_push_frame (parse, frame);
2138 /* upstream feeding us in reverse playback;
2139 * gather each fragment, then process it in single run */
2140 if (parse->segment.rate < 0.0) {
2141 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2142 GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2143 ret = gst_base_parse_process_fragment (parse, FALSE);
2145 gst_adapter_push (parse->priv->adapter, buffer);
2148 gst_adapter_push (parse->priv->adapter, buffer);
2151 /* Parse and push as many frames as possible */
2152 /* Stop either when adapter is empty or we are flushing */
2153 while (!parse->priv->flushing) {
2156 tmpbuf = gst_buffer_new ();
2159 /* Synchronization loop */
2161 min_size = MAX (parse->priv->min_frame_size, fsize);
2162 av = gst_adapter_available (parse->priv->adapter);
2164 /* loop safety check */
2165 if (G_UNLIKELY (old_min_size >= min_size))
2167 old_min_size = min_size;
2169 if (G_UNLIKELY (parse->priv->drain)) {
2171 GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2172 if (G_UNLIKELY (!min_size)) {
2173 gst_buffer_unref (tmpbuf);
2178 /* Collect at least min_frame_size bytes */
2179 if (av < min_size) {
2180 GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
2182 gst_buffer_unref (tmpbuf);
2186 /* always pass all available data */
2187 data = gst_adapter_peek (parse->priv->adapter, av);
2188 GST_BUFFER_DATA (tmpbuf) = (guint8 *) data;
2189 GST_BUFFER_SIZE (tmpbuf) = min_size;
2190 GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
2191 GST_BUFFER_FLAG_SET (tmpbuf, GST_MINI_OBJECT_FLAG_READONLY);
2193 if (parse->priv->discont) {
2194 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2195 GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2199 gst_base_parse_frame_update (parse, frame, tmpbuf);
2200 res = bclass->check_valid_frame (parse, frame, &fsize, &skip);
2201 gst_buffer_replace (&frame->buffer, NULL);
2203 if (gst_adapter_available (parse->priv->adapter) < fsize) {
2204 GST_DEBUG_OBJECT (parse,
2205 "found valid frame but not enough data available (only %d bytes)",
2206 gst_adapter_available (parse->priv->adapter));
2207 gst_buffer_unref (tmpbuf);
2210 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2214 /* subclass didn't touch this value. By default we skip 1 byte */
2218 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2219 if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2220 /* reverse playback, and no frames found yet, so we are skipping
2221 * the leading part of a fragment, which may form the tail of
2222 * fragment coming later, hopefully subclass skips efficiently ... */
2223 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2224 outbuf = gst_adapter_take_buffer (parse->priv->adapter, skip);
2225 outbuf = gst_buffer_make_metadata_writable (outbuf);
2226 GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
2227 parse->priv->buffers_pending =
2228 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2231 gst_adapter_flush (parse->priv->adapter, skip);
2233 parse->priv->offset += skip;
2234 if (!parse->priv->discont)
2235 parse->priv->sync_offset = parse->priv->offset;
2236 parse->priv->discont = TRUE;
2237 /* something changed least; nullify loop check */
2240 /* skip == 0 should imply subclass set min_size to need more data;
2241 * we check this shortly */
2242 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2243 gst_buffer_unref (tmpbuf);
2247 gst_buffer_unref (tmpbuf);
2251 /* Subclass found the sync, but still wants to skip some data */
2252 GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
2253 gst_adapter_flush (parse->priv->adapter, skip);
2254 parse->priv->offset += skip;
2257 /* Grab lock to prevent a race with FLUSH_START handler */
2258 GST_PAD_STREAM_LOCK (parse->srcpad);
2260 /* FLUSH_START event causes the "flushing" flag to be set. In this
2261 * case we can leave the frame pushing loop */
2262 if (parse->priv->flushing) {
2263 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2267 /* move along with upstream timestamp (if any),
2268 * but interpolate in between */
2269 timestamp = gst_adapter_prev_timestamp (parse->priv->adapter, NULL);
2270 if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
2271 (parse->priv->prev_ts != timestamp)) {
2272 parse->priv->prev_ts = parse->priv->next_ts = timestamp;
2275 /* FIXME: Would it be more efficient to make a subbuffer instead? */
2276 outbuf = gst_adapter_take_buffer (parse->priv->adapter, fsize);
2277 outbuf = gst_buffer_make_metadata_writable (outbuf);
2279 /* Subclass may want to know the data offset */
2280 GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
2281 parse->priv->offset += fsize;
2282 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2283 GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
2285 frame->buffer = outbuf;
2286 ret = gst_base_parse_handle_and_push_frame (parse, bclass, frame);
2287 GST_PAD_STREAM_UNLOCK (parse->srcpad);
2289 if (ret != GST_FLOW_OK) {
2290 GST_LOG_OBJECT (parse, "push returned %d", ret);
2296 GST_LOG_OBJECT (parse, "chain leaving");
2302 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2303 ("min_size evolution %d -> %d; breaking to avoid looping",
2304 old_min_size, min_size));
2305 return GST_FLOW_ERROR;
2309 /* pull @size bytes at current offset,
2310 * i.e. at least try to and possibly return a shorter buffer if near the end */
2311 static GstFlowReturn
2312 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2313 GstBuffer ** buffer)
2315 GstFlowReturn ret = GST_FLOW_OK;
2317 g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2319 /* Caching here actually makes much less difference than one would expect.
2320 * We do it mainly to avoid pulling buffers of 1 byte all the time */
2321 if (parse->priv->cache) {
2322 gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2323 gint cache_size = GST_BUFFER_SIZE (parse->priv->cache);
2325 if (cache_offset <= parse->priv->offset &&
2326 (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2327 *buffer = gst_buffer_create_sub (parse->priv->cache,
2328 parse->priv->offset - cache_offset, size);
2329 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2332 /* not enough data in the cache, free cache and get a new one */
2333 gst_buffer_unref (parse->priv->cache);
2334 parse->priv->cache = NULL;
2337 /* refill the cache */
2339 gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2340 64 * 1024), &parse->priv->cache);
2341 if (ret != GST_FLOW_OK) {
2342 parse->priv->cache = NULL;
2346 if (GST_BUFFER_SIZE (parse->priv->cache) >= size) {
2347 *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
2348 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2352 /* Not possible to get enough data, try a last time with
2353 * requesting exactly the size we need */
2354 gst_buffer_unref (parse->priv->cache);
2355 parse->priv->cache = NULL;
2357 ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2358 &parse->priv->cache);
2360 if (ret != GST_FLOW_OK) {
2361 GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2366 if (GST_BUFFER_SIZE (parse->priv->cache) < size) {
2367 GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2368 G_GUINT64_FORMAT ": wanted %u bytes, got %u bytes", parse->priv->offset,
2369 size, GST_BUFFER_SIZE (parse->priv->cache));
2371 *buffer = parse->priv->cache;
2372 parse->priv->cache = NULL;
2377 *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
2378 GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2383 static GstFlowReturn
2384 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2387 GstClockTime ts = 0;
2391 GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2392 ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
2393 parse->priv->last_offset);
2395 if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2396 GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2397 GST_TIME_ARGS (parse->segment.start));
2398 ret = GST_FLOW_UNEXPECTED;
2402 /* last fragment started at last_offset / last_ts;
2403 * seek back 10s capped at 1MB */
2404 if (parse->priv->last_ts >= 10 * GST_SECOND)
2405 ts = parse->priv->last_ts - 10 * GST_SECOND;
2406 /* if we are exact now, we will be more so going backwards */
2407 if (parse->priv->exact_position) {
2408 offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2410 GstFormat dstformat = GST_FORMAT_BYTES;
2412 if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2413 &dstformat, &offset)) {
2414 GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2417 offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2418 parse->priv->last_offset - 1024);
2419 offset = MAX (0, offset);
2421 GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2423 parse->priv->offset = offset;
2425 ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2427 if (ret != GST_FLOW_OK)
2430 /* offset will increase again as fragment is processed/parsed */
2431 parse->priv->last_offset = offset;
2433 gst_adapter_push (parse->priv->adapter, buffer);
2434 ret = gst_base_parse_process_fragment (parse, FALSE);
2435 if (ret != GST_FLOW_OK)
2438 /* force previous fragment */
2439 parse->priv->offset = -1;
2446 * pull and scan for next frame starting from current offset
2447 * ajusts sync, drain and offset going along */
2448 static GstFlowReturn
2449 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
2450 GstBaseParseFrame * frame, gboolean full)
2452 GstBuffer *buffer, *outbuf;
2453 GstFlowReturn ret = GST_FLOW_OK;
2454 guint fsize = 1, min_size, old_min_size = 0;
2457 g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2459 GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2460 " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2465 min_size = MAX (parse->priv->min_frame_size, fsize);
2466 /* loop safety check */
2467 if (G_UNLIKELY (old_min_size >= min_size))
2469 old_min_size = min_size;
2471 ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2472 if (ret != GST_FLOW_OK)
2475 if (parse->priv->discont) {
2476 GST_DEBUG_OBJECT (parse, "marking DISCONT");
2477 GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2480 /* if we got a short read, inform subclass we are draining leftover
2481 * and no more is to be expected */
2482 if (GST_BUFFER_SIZE (buffer) < min_size)
2483 parse->priv->drain = TRUE;
2486 gst_base_parse_frame_update (parse, frame, buffer);
2487 res = klass->check_valid_frame (parse, frame, &fsize, &skip);
2488 gst_buffer_replace (&frame->buffer, NULL);
2490 parse->priv->drain = FALSE;
2491 GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
2494 parse->priv->drain = FALSE;
2498 GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2499 if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2500 /* reverse playback, and no frames found yet, so we are skipping
2501 * the leading part of a fragment, which may form the tail of
2502 * fragment coming later, hopefully subclass skips efficiently ... */
2503 outbuf = gst_buffer_create_sub (buffer, 0, skip);
2504 parse->priv->buffers_pending =
2505 g_slist_prepend (parse->priv->buffers_pending, outbuf);
2508 parse->priv->offset += skip;
2509 if (!parse->priv->discont)
2510 parse->priv->sync_offset = parse->priv->offset;
2511 parse->priv->discont = TRUE;
2512 /* something changed least; nullify loop check */
2515 /* skip == 0 should imply subclass set min_size to need more data;
2516 * we check this shortly */
2517 GST_DEBUG_OBJECT (parse, "finding sync...");
2518 gst_buffer_unref (buffer);
2519 if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2524 /* Does the subclass want to skip too? */
2526 parse->priv->offset += skip;
2530 if (fsize + skip <= GST_BUFFER_SIZE (buffer)) {
2531 outbuf = gst_buffer_create_sub (buffer, skip, fsize);
2532 GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
2533 GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
2534 gst_buffer_unref (buffer);
2536 gst_buffer_unref (buffer);
2537 ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2538 if (ret != GST_FLOW_OK)
2540 if (GST_BUFFER_SIZE (outbuf) < fsize) {
2541 gst_buffer_unref (outbuf);
2542 ret = GST_FLOW_UNEXPECTED;
2546 parse->priv->offset += fsize;
2548 frame->buffer = outbuf;
2556 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2557 ("min_size evolution %d -> %d; breaking to avoid looping",
2558 old_min_size, min_size));
2559 return GST_FLOW_ERROR;
2563 /* Loop that is used in pull mode to retrieve data from upstream */
2565 gst_base_parse_loop (GstPad * pad)
2567 GstBaseParse *parse;
2568 GstBaseParseClass *klass;
2569 GstFlowReturn ret = GST_FLOW_OK;
2570 GstBaseParseFrame frame;
2572 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2573 klass = GST_BASE_PARSE_GET_CLASS (parse);
2575 /* reverse playback:
2576 * first fragment (closest to stop time) is handled normally below,
2577 * then we pull in fragments going backwards */
2578 if (parse->segment.rate < 0.0) {
2579 /* check if we jumped back to a previous fragment,
2580 * which is a post-first fragment */
2581 if (parse->priv->offset < 0) {
2582 ret = gst_base_parse_handle_previous_fragment (parse);
2587 gst_base_parse_frame_init (&frame);
2588 ret = gst_base_parse_scan_frame (parse, klass, &frame, TRUE);
2589 if (ret != GST_FLOW_OK)
2592 /* This always cleans up frame, even if error occurs */
2593 ret = gst_base_parse_handle_and_push_frame (parse, klass, &frame);
2595 /* eat expected eos signalling past segment in reverse playback */
2596 if (parse->segment.rate < 0.0 && ret == GST_FLOW_UNEXPECTED &&
2597 parse->segment.last_stop >= parse->segment.stop) {
2598 GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2599 /* push what was accumulated during loop run */
2600 gst_base_parse_process_fragment (parse, TRUE);
2601 /* force previous fragment */
2602 parse->priv->offset = -1;
2607 if (ret == GST_FLOW_UNEXPECTED)
2609 else if (ret != GST_FLOW_OK)
2612 gst_object_unref (parse);
2618 ret = GST_FLOW_UNEXPECTED;
2619 GST_DEBUG_OBJECT (parse, "eos");
2624 gboolean push_eos = FALSE;
2626 GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2627 gst_flow_get_name (ret));
2628 gst_pad_pause_task (parse->sinkpad);
2630 if (ret == GST_FLOW_UNEXPECTED) {
2631 /* handle end-of-stream/segment */
2632 if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2635 if ((stop = parse->segment.stop) == -1)
2636 stop = parse->segment.duration;
2638 GST_DEBUG_OBJECT (parse, "sending segment_done");
2640 gst_element_post_message
2641 (GST_ELEMENT_CAST (parse),
2642 gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2643 GST_FORMAT_TIME, stop));
2645 /* If we STILL have zero frames processed, fire an error */
2646 if (parse->priv->framecount == 0) {
2647 GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2648 ("No valid frames found before end of stream"), (NULL));
2652 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
2653 /* for fatal errors we post an error message, wrong-state is
2654 * not fatal because it happens due to flushes and only means
2655 * that we should stop now. */
2656 GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2657 ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2661 /* newsegment before eos */
2662 if (parse->priv->pending_segment) {
2663 gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
2664 parse->priv->pending_segment = NULL;
2666 gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2668 gst_object_unref (parse);
2673 gst_base_parse_sink_activate (GstPad * sinkpad)
2675 GstBaseParse *parse;
2676 gboolean result = TRUE;
2678 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2680 GST_DEBUG_OBJECT (parse, "sink activate");
2682 if (gst_pad_check_pull_range (sinkpad)) {
2683 GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2684 result = gst_pad_activate_pull (sinkpad, TRUE);
2686 GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
2687 result = gst_pad_activate_push (sinkpad, TRUE);
2690 GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
2691 gst_object_unref (parse);
2696 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
2698 GstBaseParseClass *klass;
2699 gboolean result = FALSE;
2701 GST_DEBUG_OBJECT (parse, "activate %d", active);
2703 klass = GST_BASE_PARSE_GET_CLASS (parse);
2706 if (parse->priv->pad_mode == GST_ACTIVATE_NONE && klass->start)
2707 result = klass->start (parse);
2709 /* We must make sure streaming has finished before resetting things
2710 * and calling the ::stop vfunc */
2711 GST_PAD_STREAM_LOCK (parse->sinkpad);
2712 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2714 if (parse->priv->pad_mode != GST_ACTIVATE_NONE && klass->stop)
2715 result = klass->stop (parse);
2717 parse->priv->pad_mode = GST_ACTIVATE_NONE;
2719 GST_DEBUG_OBJECT (parse, "activate return: %d", result);
2724 gst_base_parse_sink_activate_push (GstPad * pad, gboolean active)
2726 gboolean result = TRUE;
2727 GstBaseParse *parse;
2729 parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2731 GST_DEBUG_OBJECT (parse, "sink activate push %d", active);
2733 result = gst_base_parse_activate (parse, active);
2736 parse->priv->pad_mode = active ? GST_ACTIVATE_PUSH : GST_ACTIVATE_NONE;
2738 GST_DEBUG_OBJECT (parse, "sink activate push return: %d", result);
2740 gst_object_unref (parse);
2745 gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
2747 gboolean result = FALSE;
2748 GstBaseParse *parse;
2750 parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2752 GST_DEBUG_OBJECT (parse, "activate pull %d", active);
2754 result = gst_base_parse_activate (parse, active);
2758 parse->priv->pending_segment = gst_event_new_new_segment (FALSE,
2759 parse->segment.rate, parse->segment.format,
2760 parse->segment.start, parse->segment.stop, parse->segment.last_stop);
2762 gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
2765 result &= gst_pad_stop_task (sinkpad);
2770 parse->priv->pad_mode = active ? GST_ACTIVATE_PULL : GST_ACTIVATE_NONE;
2772 GST_DEBUG_OBJECT (parse, "sink activate pull return: %d", result);
2774 gst_object_unref (parse);
2780 * gst_base_parse_set_duration:
2781 * @parse: #GstBaseParse.
2783 * @duration: duration value.
2784 * @interval: how often to update the duration estimate based on bitrate, or 0.
2786 * Sets the duration of the currently playing media. Subclass can use this
2787 * when it is able to determine duration and/or notices a change in the media
2788 * duration. Alternatively, if @interval is non-zero (default), then stream
2789 * duration is determined based on estimated bitrate, and updated every @interval
2795 gst_base_parse_set_duration (GstBaseParse * parse,
2796 GstFormat fmt, gint64 duration, gint interval)
2798 g_return_if_fail (parse != NULL);
2800 if (parse->priv->upstream_has_duration) {
2801 GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
2805 if (duration != parse->priv->duration) {
2808 m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
2809 gst_element_post_message (GST_ELEMENT (parse), m);
2811 /* TODO: what about duration tag? */
2813 parse->priv->duration = duration;
2814 parse->priv->duration_fmt = fmt;
2815 GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
2816 if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
2817 if (interval != 0) {
2818 GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
2822 GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
2823 parse->priv->update_interval = interval;
2829 * gst_base_parse_set_average_bitrate:
2830 * @parse: #GstBaseParse.
2831 * @bitrate: average bitrate in bits/second
2833 * Optionally sets the average bitrate detected in media (if non-zero),
2834 * e.g. based on metadata, as it will be posted to the application.
2836 * By default, announced average bitrate is estimated. The average bitrate
2837 * is used to estimate the total duration of the stream and to estimate
2838 * a seek position, if there's no index and #GST_BASE_PARSE_FORMAT_FLAG_SYNCABLE
2844 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
2846 parse->priv->bitrate = bitrate;
2847 GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
2851 * gst_base_parse_set_min_frame_size:
2852 * @parse: #GstBaseParse.
2853 * @min_size: Minimum size of the data that this base class should give to
2856 * Subclass can use this function to tell the base class that it needs to
2857 * give at least #min_size buffers.
2862 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
2864 g_return_if_fail (parse != NULL);
2866 parse->priv->min_frame_size = min_size;
2867 GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
2871 * gst_base_parse_set_frame_rate:
2872 * @parse: the #GstBaseParse to set
2873 * @fps_num: frames per second (numerator).
2874 * @fps_den: frames per second (denominator).
2875 * @lead_in: frames needed before a segment for subsequent decode
2876 * @lead_out: frames needed after a segment
2878 * If frames per second is configured, parser can take care of buffer duration
2879 * and timestamping. When performing segment clipping, or seeking to a specific
2880 * location, a corresponding decoder might need an initial @lead_in and a
2881 * following @lead_out number of frames to ensure the desired segment is
2882 * entirely filled upon decoding.
2887 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
2888 guint fps_den, guint lead_in, guint lead_out)
2890 g_return_if_fail (parse != NULL);
2892 parse->priv->fps_num = fps_num;
2893 parse->priv->fps_den = fps_den;
2894 if (!fps_num || !fps_den) {
2895 GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
2897 fps_num = fps_den = 0;
2898 parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
2899 parse->priv->lead_in = parse->priv->lead_out = 0;
2900 parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
2902 parse->priv->frame_duration =
2903 gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
2904 parse->priv->lead_in = lead_in;
2905 parse->priv->lead_out = lead_out;
2906 parse->priv->lead_in_ts =
2907 gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
2908 parse->priv->lead_out_ts =
2909 gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
2910 /* aim for about 1.5s to estimate duration */
2911 if (parse->priv->update_interval < 0) {
2912 parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
2913 GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
2914 parse->priv->update_interval);
2917 GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
2918 fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
2919 GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
2920 "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
2921 lead_in, parse->priv->lead_in_ts / GST_MSECOND,
2922 lead_out, parse->priv->lead_out_ts / GST_MSECOND);
2926 * gst_base_parse_set_has_timing_info:
2927 * @parse: a #GstBaseParse
2928 * @has_timing: whether frames carry timing information
2930 * Set if frames carry timing information which the subclass can (generally)
2931 * parse and provide. In particular, intrinsic (rather than estimated) time
2932 * can be obtained following a seek.
2937 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
2939 parse->priv->has_timing_info = has_timing;
2940 GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
2944 * gst_base_parse_set_syncable:
2945 * @parse: a #GstBaseParse
2946 * @syncable: set if frame starts can be identified
2948 * Set if frame starts can be identified. This is set by default and
2949 * determines whether seeking based on bitrate averages
2950 * is possible for a format/stream.
2955 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
2957 parse->priv->syncable = syncable;
2958 GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
2962 * gst_base_parse_set_passthrough:
2963 * @parse: a #GstBaseParse
2966 * Set if the nature of the format or configuration does not allow (much)
2967 * parsing, and the parser should operate in passthrough mode (which only
2968 * applies when operating in push mode). That is, incoming buffers are
2969 * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
2970 * callbacks will be invoked, but @pre_push_buffer will still be invoked,
2971 * so subclass can perform as much or as little is appropriate for
2972 * passthrough semantics in @pre_push_buffer.
2977 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
2979 parse->priv->passthrough = passthrough;
2980 GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
2984 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
2985 GstClockTime * duration)
2987 gboolean res = FALSE;
2989 g_return_val_if_fail (duration != NULL, FALSE);
2991 *duration = GST_CLOCK_TIME_NONE;
2992 if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
2993 GST_LOG_OBJECT (parse, "using provided duration");
2994 *duration = parse->priv->duration;
2996 } else if (parse->priv->duration != -1) {
2997 GST_LOG_OBJECT (parse, "converting provided duration");
2998 res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
2999 parse->priv->duration, format, (gint64 *) duration);
3000 } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3001 GST_LOG_OBJECT (parse, "using estimated duration");
3002 *duration = parse->priv->estimated_duration;
3006 GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3007 GST_TIME_ARGS (*duration));
3011 static const GstQueryType *
3012 gst_base_parse_get_querytypes (GstPad * pad)
3014 static const GstQueryType list[] = {
3027 gst_base_parse_query (GstPad * pad, GstQuery * query)
3029 GstBaseParse *parse;
3030 gboolean res = FALSE;
3032 parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3034 GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
3036 switch (GST_QUERY_TYPE (query)) {
3037 case GST_QUERY_POSITION:
3042 GST_DEBUG_OBJECT (parse, "position query");
3043 gst_query_parse_position (query, &format, NULL);
3045 GST_OBJECT_LOCK (parse);
3046 if (format == GST_FORMAT_BYTES) {
3047 dest_value = parse->priv->offset;
3049 } else if (format == parse->segment.format &&
3050 GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop)) {
3051 dest_value = parse->segment.last_stop;
3054 GST_OBJECT_UNLOCK (parse);
3057 gst_query_set_position (query, format, dest_value);
3059 res = gst_pad_query_default (pad, query);
3061 /* no precise result, upstream no idea either, then best estimate */
3062 /* priv->offset is updated in both PUSH/PULL modes */
3063 res = gst_base_parse_convert (parse,
3064 GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3069 case GST_QUERY_DURATION:
3072 GstClockTime duration;
3074 GST_DEBUG_OBJECT (parse, "duration query");
3075 gst_query_parse_duration (query, &format, NULL);
3077 /* consult upstream */
3078 res = gst_pad_query_default (pad, query);
3080 /* otherwise best estimate from us */
3082 res = gst_base_parse_get_duration (parse, format, &duration);
3084 gst_query_set_duration (query, format, duration);
3088 case GST_QUERY_SEEKING:
3091 GstClockTime duration = GST_CLOCK_TIME_NONE;
3092 gboolean seekable = FALSE;
3094 GST_DEBUG_OBJECT (parse, "seeking query");
3095 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3097 /* consult upstream */
3098 res = gst_pad_query_default (pad, query);
3100 /* we may be able to help if in TIME */
3101 if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3102 gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3103 /* already OK if upstream takes care */
3104 GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3106 if (!(res && seekable)) {
3107 if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3108 || duration == -1) {
3109 /* seekable if we still have a chance to get duration later on */
3111 parse->priv->upstream_seekable && parse->priv->update_interval;
3113 seekable = parse->priv->upstream_seekable;
3114 GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3117 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3123 case GST_QUERY_FORMATS:
3124 gst_query_set_formatsv (query, 3, fmtlist);
3127 case GST_QUERY_CONVERT:
3129 GstFormat src_format, dest_format;
3130 gint64 src_value, dest_value;
3132 gst_query_parse_convert (query, &src_format, &src_value,
3133 &dest_format, &dest_value);
3135 res = gst_base_parse_convert (parse, src_format, src_value,
3136 dest_format, &dest_value);
3138 gst_query_set_convert (query, src_format, src_value,
3139 dest_format, dest_value);
3144 res = gst_pad_query_default (pad, query);
3150 /* scans for a cluster start from @pos,
3151 * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3152 static GstFlowReturn
3153 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3154 GstClockTime * time, GstClockTime * duration)
3156 GstBaseParseClass *klass;
3158 gboolean orig_drain, orig_discont;
3159 GstFlowReturn ret = GST_FLOW_OK;
3160 GstBuffer *buf = NULL;
3161 GstBaseParseFrame frame;
3163 g_return_val_if_fail (GST_FLOW_ERROR, pos != NULL);
3164 g_return_val_if_fail (GST_FLOW_ERROR, time != NULL);
3165 g_return_val_if_fail (GST_FLOW_ERROR, duration != NULL);
3167 klass = GST_BASE_PARSE_GET_CLASS (parse);
3169 *time = GST_CLOCK_TIME_NONE;
3170 *duration = GST_CLOCK_TIME_NONE;
3173 orig_offset = parse->priv->offset;
3174 orig_discont = parse->priv->discont;
3175 orig_drain = parse->priv->drain;
3177 GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3178 " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3180 gst_base_parse_frame_init (&frame);
3182 /* jump elsewhere and locate next frame */
3183 parse->priv->offset = *pos;
3184 ret = gst_base_parse_scan_frame (parse, klass, &frame, FALSE);
3185 if (ret != GST_FLOW_OK)
3189 GST_LOG_OBJECT (parse,
3190 "peek parsing frame at offset %" G_GUINT64_FORMAT
3191 " (%#" G_GINT64_MODIFIER "x) of size %d",
3192 GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf), GST_BUFFER_SIZE (buf));
3194 /* get offset first, subclass parsing might dump other stuff in there */
3195 *pos = GST_BUFFER_OFFSET (buf);
3196 ret = klass->parse_frame (parse, &frame);
3199 /* but it should provide proper time */
3200 *time = GST_BUFFER_TIMESTAMP (buf);
3201 *duration = GST_BUFFER_DURATION (buf);
3203 gst_base_parse_frame_free (&frame);
3205 GST_LOG_OBJECT (parse,
3206 "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3207 GST_TIME_ARGS (*time), *pos);
3211 parse->priv->offset = orig_offset;
3212 parse->priv->discont = orig_discont;
3213 parse->priv->drain = orig_drain;
3218 /* bisect and scan through file for frame starting before @time,
3219 * returns OK and @time/@offset if found, NONE and/or error otherwise
3220 * If @time == G_MAXINT64, scan for duration ( == last frame) */
3221 static GstFlowReturn
3222 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3225 GstFlowReturn ret = GST_FLOW_OK;
3226 gint64 lpos, hpos, newpos;
3227 GstClockTime time, ltime, htime, newtime, dur;
3228 gboolean cont = TRUE;
3229 const GstClockTime tolerance = TARGET_DIFFERENCE;
3230 const guint chunk = 4 * 1024;
3232 g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3233 g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3235 /* TODO also make keyframe aware if useful some day */
3250 /* do not know at first */
3252 *_time = GST_CLOCK_TIME_NONE;
3254 /* need initial positions; start and end */
3255 lpos = parse->priv->first_frame_offset;
3256 ltime = parse->priv->first_frame_ts;
3257 htime = parse->priv->duration;
3258 hpos = parse->priv->upstream_size;
3260 /* check preconditions are satisfied;
3261 * start and end are needed, except for special case where we scan for
3262 * last frame to determine duration */
3263 if (parse->priv->pad_mode != GST_ACTIVATE_PULL || !hpos ||
3264 !GST_CLOCK_TIME_IS_VALID (ltime) ||
3265 (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3269 /* shortcut cases */
3272 } else if (time < ltime + tolerance) {
3276 } else if (time >= htime) {
3282 while (htime > ltime && cont) {
3283 GST_LOG_OBJECT (parse,
3284 "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3285 GST_TIME_ARGS (ltime));
3286 GST_LOG_OBJECT (parse,
3287 "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3288 GST_TIME_ARGS (htime));
3289 if (G_UNLIKELY (time == G_MAXINT64)) {
3291 } else if (G_LIKELY (hpos > lpos)) {
3293 gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3296 /* should mean lpos == hpos, since lpos <= hpos is invariant */
3298 /* we check this case once, but not forever, so break loop */
3303 newpos = CLAMP (newpos, lpos, hpos);
3304 GST_LOG_OBJECT (parse,
3305 "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3306 GST_TIME_ARGS (time), newpos);
3308 ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3309 if (ret == GST_FLOW_UNEXPECTED) {
3310 /* heuristic HACK */
3311 hpos = MAX (lpos, hpos - chunk);
3313 } else if (ret != GST_FLOW_OK) {
3317 if (newtime == -1 || newpos == -1) {
3318 GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3322 if (G_UNLIKELY (time == G_MAXINT64)) {
3325 if (GST_CLOCK_TIME_IS_VALID (dur))
3328 } else if (newtime > time) {
3330 hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3332 } else if (newtime + tolerance > time) {
3333 /* close enough undershoot */
3337 } else if (newtime < ltime) {
3338 /* so a position beyond lpos resulted in earlier time than ltime ... */
3339 GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3342 /* undershoot too far */
3343 newpos += newpos == lpos ? chunk : 0;
3344 lpos = CLAMP (newpos, lpos, hpos);
3350 GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3351 GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3356 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3357 gboolean before, GstClockTime * _ts)
3359 gint64 bytes = 0, ts = 0;
3360 GstIndexEntry *entry = NULL;
3362 if (time == GST_CLOCK_TIME_NONE) {
3368 GST_OBJECT_LOCK (parse);
3369 if (parse->priv->index) {
3370 /* Let's check if we have an index entry for that time */
3371 entry = gst_index_get_assoc_entry (parse->priv->index,
3372 parse->priv->index_id,
3373 before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3374 GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3378 gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3379 gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3381 GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3382 " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3383 GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3385 GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3386 GST_TIME_ARGS (time));
3389 ts = GST_CLOCK_TIME_NONE;
3392 GST_OBJECT_UNLOCK (parse);
3401 /* returns TRUE if seek succeeded */
3403 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3408 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3409 gboolean flush, update, res = TRUE, accurate;
3410 gint64 cur, stop, seekpos, seekstop;
3411 GstSegment seeksegment = { 0, };
3412 GstFormat dstformat;
3413 GstClockTime start_ts;
3415 gst_event_parse_seek (event, &rate, &format, &flags,
3416 &cur_type, &cur, &stop_type, &stop);
3418 GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3419 "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3420 GST_TIME_FORMAT, gst_format_get_name (format), rate,
3421 cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
3423 /* no negative rates in push mode */
3424 if (rate < 0.0 && parse->priv->pad_mode == GST_ACTIVATE_PUSH)
3427 if (cur_type != GST_SEEK_TYPE_SET ||
3428 (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3431 /* For any format other than TIME, see if upstream handles
3432 * it directly or fail. For TIME, try upstream, but do it ourselves if
3433 * it fails upstream */
3434 if (format != GST_FORMAT_TIME) {
3435 /* default action delegates to upstream */
3439 gst_event_ref (event);
3440 if ((res = gst_pad_push_event (parse->sinkpad, event))) {
3445 /* get flush flag */
3446 flush = flags & GST_SEEK_FLAG_FLUSH;
3448 /* copy segment, we need this because we still need the old
3449 * segment when we close the current segment. */
3450 memcpy (&seeksegment, &parse->segment, sizeof (GstSegment));
3452 GST_DEBUG_OBJECT (parse, "configuring seek");
3453 gst_segment_set_seek (&seeksegment, rate, format, flags,
3454 cur_type, cur, stop_type, stop, &update);
3456 /* accurate seeking implies seek tables are used to obtain position,
3457 * and the requested segment is maintained exactly, not adjusted any way */
3458 accurate = flags & GST_SEEK_FLAG_ACCURATE;
3460 /* maybe we can be accurate for (almost) free */
3461 gst_base_parse_find_offset (parse, seeksegment.last_stop, TRUE, &start_ts);
3462 if (seeksegment.last_stop <= start_ts + TARGET_DIFFERENCE) {
3463 GST_DEBUG_OBJECT (parse, "accurate seek possible");
3467 GstClockTime startpos = seeksegment.last_stop;
3469 /* accurate requested, so ... seek a bit before target */
3470 if (startpos < parse->priv->lead_in_ts)
3473 startpos -= parse->priv->lead_in_ts;
3474 seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
3475 seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
3478 start_ts = seeksegment.last_stop;
3479 dstformat = GST_FORMAT_BYTES;
3480 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.last_stop,
3481 &dstformat, &seekpos))
3482 goto convert_failed;
3483 if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
3484 &dstformat, &seekstop))
3485 goto convert_failed;
3488 GST_DEBUG_OBJECT (parse,
3489 "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3491 GST_DEBUG_OBJECT (parse,
3492 "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
3493 seeksegment.stop, seekstop);
3495 if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
3498 GST_DEBUG_OBJECT (parse, "seek in PULL mode");
3501 if (parse->srcpad) {
3502 GST_DEBUG_OBJECT (parse, "sending flush start");
3503 gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
3504 /* unlock upstream pull_range */
3505 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
3508 gst_pad_pause_task (parse->sinkpad);
3511 /* we should now be able to grab the streaming thread because we stopped it
3512 * with the above flush/pause code */
3513 GST_PAD_STREAM_LOCK (parse->sinkpad);
3515 /* save current position */
3516 last_stop = parse->segment.last_stop;
3517 GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
3520 /* now commit to new position */
3522 /* prepare for streaming again */
3524 GST_DEBUG_OBJECT (parse, "sending flush stop");
3525 gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop ());
3526 gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop ());
3527 gst_base_parse_clear_queues (parse);
3529 if (parse->priv->close_segment)
3530 gst_event_unref (parse->priv->close_segment);
3532 parse->priv->close_segment = gst_event_new_new_segment (TRUE,
3533 parse->segment.rate, parse->segment.format,
3534 parse->segment.accum, parse->segment.last_stop, parse->segment.accum);
3536 /* keep track of our last_stop */
3537 seeksegment.accum = parse->segment.last_stop;
3539 GST_DEBUG_OBJECT (parse, "Created close seg format %d, "
3540 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3541 ", pos = %" GST_TIME_FORMAT, format,
3542 GST_TIME_ARGS (parse->segment.accum),
3543 GST_TIME_ARGS (parse->segment.last_stop),
3544 GST_TIME_ARGS (parse->segment.accum));
3547 memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
3549 /* store the newsegment event so it can be sent from the streaming thread. */
3550 if (parse->priv->pending_segment)
3551 gst_event_unref (parse->priv->pending_segment);
3553 /* This will be sent later in _loop() */
3554 parse->priv->pending_segment =
3555 gst_event_new_new_segment (FALSE, parse->segment.rate,
3556 parse->segment.format, parse->segment.start,
3557 parse->segment.stop, parse->segment.start);
3559 GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
3560 "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
3561 ", pos = %" GST_TIME_FORMAT, format,
3562 GST_TIME_ARGS (parse->segment.start),
3563 GST_TIME_ARGS (parse->segment.stop),
3564 GST_TIME_ARGS (parse->segment.start));
3566 /* one last chance in pull mode to stay accurate;
3567 * maybe scan and subclass can find where to go */
3570 GstClockTime ts = seeksegment.last_stop;
3572 gst_base_parse_locate_time (parse, &ts, &scanpos);
3576 /* running collected index now consists of several intervals,
3577 * so optimized check no longer possible */
3578 parse->priv->index_last_valid = FALSE;
3579 parse->priv->index_last_offset = 0;
3580 parse->priv->index_last_ts = 0;
3584 /* mark discont if we are going to stream from another position. */
3585 if (seekpos != parse->priv->offset) {
3586 GST_DEBUG_OBJECT (parse,
3587 "mark DISCONT, we did a seek to another position");
3588 parse->priv->offset = seekpos;
3589 parse->priv->last_offset = seekpos;
3590 parse->priv->seen_keyframe = FALSE;
3591 parse->priv->discont = TRUE;
3592 parse->priv->next_ts = start_ts;
3593 parse->priv->last_ts = GST_CLOCK_TIME_NONE;
3594 parse->priv->sync_offset = seekpos;
3595 parse->priv->exact_position = accurate;
3598 /* Start streaming thread if paused */
3599 gst_pad_start_task (parse->sinkpad,
3600 (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
3602 GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3607 GstEvent *new_event;
3608 GstBaseParseSeek *seek;
3610 /* The only thing we need to do in PUSH-mode is to send the
3611 seek event (in bytes) to upstream. Segment / flush handling happens
3612 in corresponding src event handlers */
3613 GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
3614 if (seekstop >= 0 && seekpos <= seekpos)
3616 new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flush,
3617 GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
3619 /* store segment info so its precise details can be reconstructed when
3620 * receiving newsegment;
3621 * this matters for all details when accurate seeking,
3622 * is most useful to preserve NONE stop time otherwise */
3623 seek = g_new0 (GstBaseParseSeek, 1);
3624 seek->segment = seeksegment;
3625 seek->accurate = accurate;
3626 seek->offset = seekpos;
3627 seek->start_ts = start_ts;
3628 GST_OBJECT_LOCK (parse);
3629 /* less optimal, but preserves order */
3630 parse->priv->pending_seeks =
3631 g_slist_append (parse->priv->pending_seeks, seek);
3632 GST_OBJECT_UNLOCK (parse);
3634 res = gst_pad_push_event (parse->sinkpad, new_event);
3637 GST_OBJECT_LOCK (parse);
3638 parse->priv->pending_seeks =
3639 g_slist_remove (parse->priv->pending_seeks, seek);
3640 GST_OBJECT_UNLOCK (parse);
3646 /* handled event is ours to free */
3648 gst_event_unref (event);
3654 GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
3660 GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3666 GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3672 /* Checks if bitrates are available from upstream tags so that we don't
3673 * override them later
3676 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
3678 GstTagList *taglist = NULL;
3681 gst_event_parse_tag (event, &taglist);
3683 if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
3684 GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
3685 parse->priv->post_min_bitrate = FALSE;
3687 if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
3688 GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
3689 parse->priv->post_avg_bitrate = FALSE;
3691 if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
3692 GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
3693 parse->priv->post_max_bitrate = FALSE;
3698 gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps)
3700 GstBaseParse *parse;
3701 GstBaseParseClass *klass;
3702 gboolean res = TRUE;
3704 parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3705 klass = GST_BASE_PARSE_GET_CLASS (parse);
3707 GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
3709 if (klass->set_sink_caps)
3710 res = klass->set_sink_caps (parse, caps);
3716 gst_base_parse_set_index (GstElement * element, GstIndex * index)
3718 GstBaseParse *parse = GST_BASE_PARSE (element);
3720 GST_OBJECT_LOCK (parse);
3721 if (parse->priv->index)
3722 gst_object_unref (parse->priv->index);
3724 parse->priv->index = gst_object_ref (index);
3725 gst_index_get_writer_id (index, GST_OBJECT (element),
3726 &parse->priv->index_id);
3727 parse->priv->own_index = FALSE;
3729 parse->priv->index = NULL;
3730 GST_OBJECT_UNLOCK (parse);
3734 gst_base_parse_get_index (GstElement * element)
3736 GstBaseParse *parse = GST_BASE_PARSE (element);
3737 GstIndex *result = NULL;
3739 GST_OBJECT_LOCK (parse);
3740 if (parse->priv->index)
3741 result = gst_object_ref (parse->priv->index);
3742 GST_OBJECT_UNLOCK (parse);
3747 static GstStateChangeReturn
3748 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
3750 GstBaseParse *parse;
3751 GstStateChangeReturn result;
3753 parse = GST_BASE_PARSE (element);
3755 switch (transition) {
3756 case GST_STATE_CHANGE_READY_TO_PAUSED:
3757 /* If this is our own index destroy it as the
3758 * old entries might be wrong for the new stream */
3759 if (parse->priv->own_index) {
3760 gst_object_unref (parse->priv->index);
3761 parse->priv->index = NULL;
3762 parse->priv->own_index = FALSE;
3765 /* If no index was created, generate one */
3766 if (G_UNLIKELY (!parse->priv->index)) {
3767 GST_DEBUG_OBJECT (parse, "no index provided creating our own");
3769 parse->priv->index = gst_index_factory_make ("memindex");
3770 gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
3771 &parse->priv->index_id);
3772 parse->priv->own_index = TRUE;
3779 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3781 switch (transition) {
3782 case GST_STATE_CHANGE_PAUSED_TO_READY:
3783 gst_base_parse_reset (parse);