2 * Copyright (C) 2004 Wim Taymans <wim@fluendo.com>
3 * Copyright (C) 2006 Tim-Philipp Müller <tim centricular net>
4 * Copyright (C) 2008 Sebastian Dröge <sebastian.droege@collabora.co.uk>
5 * Copyright (C) 2011-2012 Vincent Penquerc'h <vincent.penquerch@collabora.co.uk>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
17 * You should have received a copy of the GNU Library General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20 * Boston, MA 02110-1301, USA.
24 * Based on the speexdec element.
28 * SECTION:element-opusdec
30 * @see_also: opusenc, oggdemux
32 * This element decodes a OPUS stream to raw integer audio.
34 * ## Example pipelines
36 * gst-launch-1.0 -v filesrc location=opus.ogg ! oggdemux ! opusdec ! audioconvert ! audioresample ! alsasink
38 * Decode an Ogg/Opus file. To create an Ogg/Opus file refer to the documentation of opusenc.
49 #include "gstopuselements.h"
50 #include "gstopusheader.h"
51 #include "gstopuscommon.h"
52 #include "gstopusdec.h"
53 #include <gst/pbutils/pbutils.h>
55 GST_DEBUG_CATEGORY_STATIC (opusdec_debug);
56 #define GST_CAT_DEFAULT opusdec_debug
58 static GstStaticPadTemplate opus_dec_src_factory =
59 GST_STATIC_PAD_TEMPLATE ("src",
62 GST_STATIC_CAPS ("audio/x-raw, "
63 "format = (string) " GST_AUDIO_NE (S16) ", "
64 "layout = (string) interleaved, "
65 "rate = (int) { 48000, 24000, 16000, 12000, 8000 }, "
66 "channels = (int) [ 1, 8 ] ")
69 static GstStaticPadTemplate opus_dec_sink_factory =
70 GST_STATIC_PAD_TEMPLATE ("sink",
73 GST_STATIC_CAPS ("audio/x-opus, "
74 "channel-mapping-family = (int) 0; "
76 "channel-mapping-family = (int) [1, 255], "
77 "channels = (int) [1, 255], "
78 "stream-count = (int) [1, 255], " "coupled-count = (int) [0, 255]")
81 G_DEFINE_TYPE (GstOpusDec, gst_opus_dec, GST_TYPE_AUDIO_DECODER);
82 GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (opusdec, "opusdec",
83 GST_RANK_PRIMARY, GST_TYPE_OPUS_DEC, opus_element_init (plugin));
85 #define DB_TO_LINEAR(x) pow (10., (x) / 20.)
87 #define DEFAULT_USE_INBAND_FEC FALSE
88 #define DEFAULT_APPLY_GAIN TRUE
89 #define DEFAULT_PHASE_INVERSION FALSE
101 static GstFlowReturn gst_opus_dec_parse_header (GstOpusDec * dec,
103 static gboolean gst_opus_dec_start (GstAudioDecoder * dec);
104 static gboolean gst_opus_dec_stop (GstAudioDecoder * dec);
105 static GstFlowReturn gst_opus_dec_handle_frame (GstAudioDecoder * dec,
107 static gboolean gst_opus_dec_set_format (GstAudioDecoder * bdec,
109 static void gst_opus_dec_get_property (GObject * object, guint prop_id,
110 GValue * value, GParamSpec * pspec);
111 static void gst_opus_dec_set_property (GObject * object, guint prop_id,
112 const GValue * value, GParamSpec * pspec);
113 static GstCaps *gst_opus_dec_getcaps (GstAudioDecoder * dec, GstCaps * filter);
117 gst_opus_dec_class_init (GstOpusDecClass * klass)
119 GObjectClass *gobject_class;
120 GstAudioDecoderClass *adclass;
121 GstElementClass *element_class;
123 gobject_class = (GObjectClass *) klass;
124 adclass = (GstAudioDecoderClass *) klass;
125 element_class = (GstElementClass *) klass;
127 gobject_class->set_property = gst_opus_dec_set_property;
128 gobject_class->get_property = gst_opus_dec_get_property;
130 adclass->start = GST_DEBUG_FUNCPTR (gst_opus_dec_start);
131 adclass->stop = GST_DEBUG_FUNCPTR (gst_opus_dec_stop);
132 adclass->handle_frame = GST_DEBUG_FUNCPTR (gst_opus_dec_handle_frame);
133 adclass->set_format = GST_DEBUG_FUNCPTR (gst_opus_dec_set_format);
134 adclass->getcaps = GST_DEBUG_FUNCPTR (gst_opus_dec_getcaps);
136 gst_element_class_add_static_pad_template (element_class,
137 &opus_dec_src_factory);
138 gst_element_class_add_static_pad_template (element_class,
139 &opus_dec_sink_factory);
140 gst_element_class_set_static_metadata (element_class, "Opus audio decoder",
141 "Codec/Decoder/Audio/Converter", "decode opus streams to audio",
142 "Vincent Penquerc'h <vincent.penquerch@collabora.co.uk>");
143 g_object_class_install_property (gobject_class, PROP_USE_INBAND_FEC,
144 g_param_spec_boolean ("use-inband-fec", "Use in-band FEC",
145 "Use forward error correction if available (needs PLC enabled)",
146 DEFAULT_USE_INBAND_FEC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
148 g_object_class_install_property (gobject_class, PROP_APPLY_GAIN,
149 g_param_spec_boolean ("apply-gain", "Apply gain",
150 "Apply gain if any is specified in the header", DEFAULT_APPLY_GAIN,
151 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
153 #ifdef OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST
154 g_object_class_install_property (gobject_class, PROP_PHASE_INVERSION,
155 g_param_spec_boolean ("phase-inversion",
156 "Control Phase Inversion", "Set to true to enable phase inversion, "
157 "this will slightly improve stereo quality, but will have side "
158 "effects when downmixed to mono.", DEFAULT_PHASE_INVERSION,
159 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
166 * Various decoder statistics. This property returns a GstStructure
167 * with name application/x-opusdec-stats with the following fields:
169 * * #guint64 `num-pushed`: the number of packets pushed out.
170 * * #guint64 `num-gap`: the number of gap packets received.
171 * * #guint64 `plc-num-samples`: the number of samples generated using PLC
172 * * #guint64 `plc-duration`: the total duration, in ns, of samples generated using PLC
173 * * #guint32 `bandwidth`: decoder last bandpass, in kHz, or 0 if unknown
174 * * #guint32 `sample-rate`: decoder sampling rate, or 0 if unknown
175 * * #guint32 `gain`: decoder gain adjustement, in Q8 dB units, or 0 if unknown
176 * * #guint32 `last-packet-duration`: duration, in samples, of the last packet successfully decoded or concealed, or 0 if unknown
177 * * #guint `channels`: the number of channels
181 g_object_class_install_property (gobject_class, PROP_STATS,
182 g_param_spec_boxed ("stats", "Statistics",
183 "Various statistics", GST_TYPE_STRUCTURE,
184 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
186 GST_DEBUG_CATEGORY_INIT (opusdec_debug, "opusdec", 0,
187 "opus decoding element");
191 gst_opus_dec_reset (GstOpusDec * dec)
195 opus_multistream_decoder_destroy (dec->state);
199 gst_buffer_replace (&dec->streamheader, NULL);
200 gst_buffer_replace (&dec->vorbiscomment, NULL);
201 gst_buffer_replace (&dec->last_buffer, NULL);
206 dec->sample_rate = 0;
208 dec->leftover_plc_duration = 0;
209 dec->last_known_buffer_duration = GST_CLOCK_TIME_NONE;
213 gst_opus_dec_init (GstOpusDec * dec)
215 dec->use_inband_fec = FALSE;
216 dec->apply_gain = DEFAULT_APPLY_GAIN;
217 dec->phase_inversion = DEFAULT_PHASE_INVERSION;
219 gst_audio_decoder_set_needs_format (GST_AUDIO_DECODER (dec), TRUE);
220 gst_audio_decoder_set_use_default_pad_acceptcaps (GST_AUDIO_DECODER_CAST
222 GST_PAD_SET_ACCEPT_TEMPLATE (GST_AUDIO_DECODER_SINK_PAD (dec));
224 gst_opus_dec_reset (dec);
228 gst_opus_dec_start (GstAudioDecoder * dec)
230 GstOpusDec *odec = GST_OPUS_DEC (dec);
232 gst_opus_dec_reset (odec);
234 /* we know about concealment */
235 gst_audio_decoder_set_plc_aware (dec, TRUE);
237 if (odec->use_inband_fec) {
238 /* opusdec outputs samples directly from an input buffer, except if
239 * FEC is on, in which case it buffers one buffer in case one buffer
242 gst_audio_decoder_set_latency (dec, 120 * GST_MSECOND, 120 * GST_MSECOND);
245 GST_OBJECT_LOCK (dec);
246 odec->num_pushed = 0;
248 odec->plc_num_samples = 0;
249 odec->plc_duration = 0;
250 GST_OBJECT_UNLOCK (dec);
256 gst_opus_dec_stop (GstAudioDecoder * dec)
258 GstOpusDec *odec = GST_OPUS_DEC (dec);
260 gst_opus_dec_reset (odec);
266 gst_opus_dec_get_r128_gain (gint16 r128_gain)
268 return r128_gain / (double) (1 << 8);
272 gst_opus_dec_get_r128_volume (gint16 r128_gain)
274 return DB_TO_LINEAR (gst_opus_dec_get_r128_gain (r128_gain));
278 gst_opus_dec_negotiate (GstOpusDec * dec, const GstAudioChannelPosition * pos)
280 GstCaps *caps = gst_pad_get_allowed_caps (GST_AUDIO_DECODER_SRC_PAD (dec));
285 gint rate = dec->sample_rate, channels = dec->n_channels;
286 GstCaps *constraint, *inter;
288 constraint = gst_caps_new_empty_simple ("audio/x-raw");
289 if (dec->n_channels <= 2) { /* including 0 */
290 gst_caps_set_simple (constraint, "channels", GST_TYPE_INT_RANGE, 1, 2,
293 gst_caps_set_simple (constraint, "channels", G_TYPE_INT, dec->n_channels,
297 inter = gst_caps_intersect (caps, constraint);
298 gst_caps_unref (constraint);
300 if (gst_caps_is_empty (inter)) {
301 GST_DEBUG_OBJECT (dec, "Empty intersection, failed to negotiate");
302 gst_caps_unref (inter);
303 gst_caps_unref (caps);
307 /* If we have a channels preference (0 means we prefer 2), then check if
308 * we can passthrough that. The preferred channel count might not be in
309 * the first structure! */
310 if (dec->n_channels <= 2) {
312 gst_caps_new_simple ("audio/x-raw", "channels", G_TYPE_INT,
313 dec->n_channels > 0 ? dec->n_channels : 2, NULL);
316 tmp = gst_caps_intersect (inter, preferred);
317 if (!gst_caps_is_empty (tmp)) {
318 gst_caps_unref (inter);
322 gst_caps_unref (preferred);
325 /* If we have a rate preference, then check if we can passthrough that.
326 * The preferred rate might not be in the first structure! */
329 gst_caps_new_simple ("audio/x-raw", "rate", G_TYPE_INT,
330 dec->sample_rate > 0 ? dec->sample_rate : 48000, NULL);
333 tmp = gst_caps_intersect (inter, preferred);
334 if (!gst_caps_is_empty (tmp)) {
335 gst_caps_unref (inter);
339 gst_caps_unref (preferred);
342 inter = gst_caps_truncate (inter);
343 s = gst_caps_get_structure (inter, 0);
344 rate = dec->sample_rate > 0 ? dec->sample_rate : 48000;
345 gst_structure_fixate_field_nearest_int (s, "rate", dec->sample_rate);
346 gst_structure_get_int (s, "rate", &rate);
347 channels = dec->n_channels > 0 ? dec->n_channels : 2;
348 gst_structure_fixate_field_nearest_int (s, "channels", channels);
349 gst_structure_get_int (s, "channels", &channels);
351 gst_caps_unref (inter);
353 dec->sample_rate = rate;
354 dec->n_channels = channels;
355 gst_caps_unref (caps);
358 if (dec->n_channels == 0) {
359 GST_DEBUG_OBJECT (dec, "Using a default of 2 channels");
364 if (dec->sample_rate == 0) {
365 GST_DEBUG_OBJECT (dec, "Using a default of 48kHz sample rate");
366 dec->sample_rate = 48000;
369 GST_INFO_OBJECT (dec, "Negotiated %d channels, %d Hz", dec->n_channels,
372 /* pass valid order to audio info */
374 memcpy (dec->opus_pos, pos, sizeof (pos[0]) * dec->n_channels);
375 gst_audio_channel_positions_to_valid_order (dec->opus_pos, dec->n_channels);
378 /* set up source format */
379 gst_audio_info_init (&info);
380 gst_audio_info_set_format (&info, GST_AUDIO_FORMAT_S16,
381 dec->sample_rate, dec->n_channels, pos ? dec->opus_pos : NULL);
382 gst_audio_decoder_set_output_format (GST_AUDIO_DECODER (dec), &info);
384 /* but we still need the opus order for later reordering */
386 memcpy (dec->opus_pos, pos, sizeof (pos[0]) * dec->n_channels);
388 dec->opus_pos[0] = GST_AUDIO_CHANNEL_POSITION_INVALID;
397 gst_opus_dec_parse_header (GstOpusDec * dec, GstBuffer * buf)
399 GstAudioChannelPosition pos[64];
400 const GstAudioChannelPosition *posn = NULL;
403 if (!gst_opus_header_is_id_header (buf)) {
404 GST_ELEMENT_ERROR (dec, STREAM, FORMAT, (NULL),
405 ("Header is not an Opus ID header"));
406 return GST_FLOW_ERROR;
409 if (!gst_codec_utils_opus_parse_header (buf,
412 &dec->channel_mapping_family,
414 &dec->n_stereo_streams,
415 dec->channel_mapping, &dec->pre_skip, &dec->r128_gain)) {
416 GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL),
417 ("Failed to parse Opus ID header"));
418 return GST_FLOW_ERROR;
420 dec->n_channels = n_channels;
421 dec->r128_gain_volume = gst_opus_dec_get_r128_volume (dec->r128_gain);
423 GST_INFO_OBJECT (dec,
424 "Found pre-skip of %u samples, R128 gain %d (volume %f)",
425 dec->pre_skip, dec->r128_gain, dec->r128_gain_volume);
427 if (dec->channel_mapping_family == 1) {
428 GST_INFO_OBJECT (dec, "Channel mapping family 1, Vorbis mapping");
429 switch (dec->n_channels) {
440 posn = gst_opus_channel_positions[dec->n_channels - 1];
445 GST_ELEMENT_WARNING (GST_ELEMENT (dec), STREAM, DECODE,
446 (NULL), ("Using NONE channel layout for more than 8 channels"));
448 for (i = 0; i < dec->n_channels; i++)
449 pos[i] = GST_AUDIO_CHANNEL_POSITION_NONE;
455 GST_INFO_OBJECT (dec, "Channel mapping family %d",
456 dec->channel_mapping_family);
459 if (!gst_opus_dec_negotiate (dec, posn))
460 return GST_FLOW_NOT_NEGOTIATED;
467 gst_opus_dec_parse_comments (GstOpusDec * dec, GstBuffer * buf)
472 /* adapted from ext/ogg/gstoggstream.c */
474 packet_duration_opus (const unsigned char *data, size_t bytes)
476 static const guint64 durations[32] = {
477 480, 960, 1920, 2880, /* Silk NB */
478 480, 960, 1920, 2880, /* Silk MB */
479 480, 960, 1920, 2880, /* Silk WB */
480 480, 960, /* Hybrid SWB */
481 480, 960, /* Hybrid FB */
482 120, 240, 480, 960, /* CELT NB */
483 120, 240, 480, 960, /* CELT NB */
484 120, 240, 480, 960, /* CELT NB */
485 120, 240, 480, 960, /* CELT NB */
489 gint64 frame_duration;
497 if (bytes >= 8 && !memcmp (data, "Opus", 4))
502 frame_duration = durations[toc >> 3];
515 GST_WARNING ("Code 3 Opus packet has less than 2 bytes");
518 nframes = data[1] & 63;
522 duration = nframes * frame_duration;
523 if (duration > 5760) {
524 GST_WARNING ("Opus packet duration > 120 ms, invalid");
527 GST_LOG ("Opus packet: frame size %.1f ms, %d frames, duration %.1f ms",
528 frame_duration / 48.f, nframes, duration / 48.f);
529 return duration / 48.f * 1000000;
533 opus_dec_chain_parse_data (GstOpusDec * dec, GstBuffer * buffer)
535 GstFlowReturn res = GST_FLOW_OK;
538 GstBuffer *outbuf, *bufd;
542 unsigned int packet_size;
544 GstMapInfo map, omap;
545 GstAudioClippingMeta *cmeta = NULL;
547 if (dec->state == NULL) {
548 /* If we did not get any headers, default to 2 channels */
549 if (dec->n_channels == 0) {
550 GST_INFO_OBJECT (dec, "No header, assuming single stream");
552 dec->sample_rate = 48000;
553 /* default stereo mapping */
554 dec->channel_mapping_family = 0;
555 dec->channel_mapping[0] = 0;
556 dec->channel_mapping[1] = 1;
558 dec->n_stereo_streams = 1;
560 if (!gst_opus_dec_negotiate (dec, NULL))
561 return GST_FLOW_NOT_NEGOTIATED;
564 if (dec->n_channels == 2 && dec->n_streams == 1
565 && dec->n_stereo_streams == 0) {
566 /* if we are automatically decoding 2 channels, but only have
567 a single encoded one, direct both channels to it */
568 dec->channel_mapping[1] = 0;
571 GST_DEBUG_OBJECT (dec, "Creating decoder with %d channels, %d Hz",
572 dec->n_channels, dec->sample_rate);
573 #ifndef GST_DISABLE_GST_DEBUG
574 gst_opus_common_log_channel_mapping_table (GST_ELEMENT (dec), opusdec_debug,
575 "Mapping table", dec->n_channels, dec->channel_mapping);
578 GST_DEBUG_OBJECT (dec, "%d streams, %d stereo", dec->n_streams,
579 dec->n_stereo_streams);
581 opus_multistream_decoder_create (dec->sample_rate, dec->n_channels,
582 dec->n_streams, dec->n_stereo_streams, dec->channel_mapping, &err);
583 if (!dec->state || err != OPUS_OK)
584 goto creation_failed;
586 #ifdef OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST
589 err = opus_multistream_decoder_ctl (dec->state,
590 OPUS_SET_PHASE_INVERSION_DISABLED (!dec->phase_inversion));
592 GST_WARNING_OBJECT (dec, "Could not configure phase inversion: %s",
593 opus_strerror (err));
596 GST_WARNING_OBJECT (dec, "Phase inversion request is not support by this "
597 "version of the Opus Library");
602 GST_DEBUG_OBJECT (dec, "Received buffer of size %" G_GSIZE_FORMAT,
603 gst_buffer_get_size (buffer));
605 GST_DEBUG_OBJECT (dec, "Received missing buffer");
608 /* if using in-band FEC, we introdude one extra frame's delay as we need
609 to potentially wait for next buffer to decode a missing buffer */
610 if (dec->use_inband_fec && !dec->primed) {
611 GST_DEBUG_OBJECT (dec, "First buffer received in FEC mode, early out");
612 gst_buffer_replace (&dec->last_buffer, buffer);
617 /* That's the buffer we'll be sending to the opus decoder. */
618 buf = (dec->use_inband_fec
619 && gst_buffer_get_size (dec->last_buffer) >
620 0) ? dec->last_buffer : buffer;
622 /* That's the buffer we get duration from */
623 bufd = dec->use_inband_fec ? dec->last_buffer : buffer;
625 if (buf && gst_buffer_get_size (buf) > 0) {
626 gst_buffer_map (buf, &map, GST_MAP_READ);
629 GST_DEBUG_OBJECT (dec, "Using buffer of size %" G_GSIZE_FORMAT, size);
631 /* concealment data, pass NULL as the bits parameters */
632 GST_DEBUG_OBJECT (dec, "Using NULL buffer");
637 if (gst_buffer_get_size (bufd) == 0) {
638 GstClockTime const opus_plc_alignment = 2500 * GST_USECOND;
639 GstClockTime aligned_missing_duration;
640 GstClockTime missing_duration = GST_BUFFER_DURATION (bufd);
642 if (!GST_CLOCK_TIME_IS_VALID (missing_duration) || missing_duration == 0) {
643 if (GST_CLOCK_TIME_IS_VALID (dec->last_known_buffer_duration)) {
644 missing_duration = dec->last_known_buffer_duration;
645 GST_WARNING_OBJECT (dec,
646 "Missing duration, using last duration %" GST_TIME_FORMAT,
647 GST_TIME_ARGS (missing_duration));
649 GST_WARNING_OBJECT (dec,
650 "Missing buffer, but unknown duration, and no previously known duration, assuming 20 ms");
651 missing_duration = 20 * GST_MSECOND;
655 GST_DEBUG_OBJECT (dec,
656 "missing buffer, doing PLC duration %" GST_TIME_FORMAT
657 " plus leftover %" GST_TIME_FORMAT, GST_TIME_ARGS (missing_duration),
658 GST_TIME_ARGS (dec->leftover_plc_duration));
660 GST_OBJECT_LOCK (dec);
662 GST_OBJECT_UNLOCK (dec);
664 /* add the leftover PLC duration to that of the buffer */
665 missing_duration += dec->leftover_plc_duration;
667 /* align the combined buffer and leftover PLC duration to multiples
668 * of 2.5ms, rounding to nearest, and store excess duration for later */
669 aligned_missing_duration =
671 opus_plc_alignment / 2) / opus_plc_alignment) * opus_plc_alignment;
672 dec->leftover_plc_duration = missing_duration - aligned_missing_duration;
674 /* Opus' PLC cannot operate with less than 2.5ms; skip PLC
675 * and accumulate the missing duration in the leftover_plc_duration
676 * for the next PLC attempt */
677 if (aligned_missing_duration < opus_plc_alignment) {
678 GST_DEBUG_OBJECT (dec,
679 "current duration %" GST_TIME_FORMAT
680 " of missing data not enough for PLC (minimum needed: %"
681 GST_TIME_FORMAT ") - skipping", GST_TIME_ARGS (missing_duration),
682 GST_TIME_ARGS (opus_plc_alignment));
686 /* convert the duration (in nanoseconds) to sample count */
688 gst_util_uint64_scale_int (aligned_missing_duration, dec->sample_rate,
691 GST_DEBUG_OBJECT (dec,
692 "calculated PLC frame length: %" GST_TIME_FORMAT
693 " num frame samples: %d new leftover: %" GST_TIME_FORMAT,
694 GST_TIME_ARGS (aligned_missing_duration), samples,
695 GST_TIME_ARGS (dec->leftover_plc_duration));
697 GST_OBJECT_LOCK (dec);
698 dec->plc_num_samples += samples;
699 dec->plc_duration += aligned_missing_duration;
700 GST_OBJECT_UNLOCK (dec);
702 /* use maximum size (120 ms) as the number of returned samples is
703 not constant over the stream. */
704 samples = 120 * dec->sample_rate / 1000;
706 packet_size = samples * dec->n_channels * 2;
709 gst_audio_decoder_allocate_output_buffer (GST_AUDIO_DECODER (dec),
716 dec->last_known_buffer_duration = packet_duration_opus (data, size);
718 gst_buffer_map (outbuf, &omap, GST_MAP_WRITE);
719 out_data = (gint16 *) omap.data;
722 if (dec->use_inband_fec) {
723 if (gst_buffer_get_size (dec->last_buffer) > 0) {
724 /* normal delayed decode */
725 GST_LOG_OBJECT (dec, "FEC enabled, decoding last delayed buffer");
726 n = opus_multistream_decode (dec->state, data, size, out_data, samples,
729 /* FEC reconstruction decode */
730 GST_LOG_OBJECT (dec, "FEC enabled, reconstructing last buffer");
731 n = opus_multistream_decode (dec->state, data, size, out_data, samples,
736 GST_LOG_OBJECT (dec, "FEC disabled, decoding buffer");
737 n = opus_multistream_decode (dec->state, data, size, out_data, samples,
740 if (n == OPUS_BUFFER_TOO_SMALL) {
741 /* if too small, add 2.5 milliseconds and try again, up to the
742 * Opus max size of 120 milliseconds */
743 if (samples >= 120 * dec->sample_rate / 1000)
745 samples += 25 * dec->sample_rate / 10000;
746 packet_size = samples * dec->n_channels * 2;
747 gst_buffer_unmap (outbuf, &omap);
748 gst_buffer_unref (outbuf);
750 gst_audio_decoder_allocate_output_buffer (GST_AUDIO_DECODER (dec),
755 gst_buffer_map (outbuf, &omap, GST_MAP_WRITE);
756 out_data = (gint16 *) omap.data;
758 } while (n == OPUS_BUFFER_TOO_SMALL);
759 gst_buffer_unmap (outbuf, &omap);
761 gst_buffer_unmap (buf, &map);
764 GstFlowReturn ret = GST_FLOW_ERROR;
766 gst_buffer_unref (outbuf);
767 GST_AUDIO_DECODER_ERROR (dec, 1, STREAM, DECODE, (NULL),
768 ("Decoding error (%d): %s", n, opus_strerror (n)), ret);
771 GST_DEBUG_OBJECT (dec, "decoded %d samples", n);
772 gst_buffer_set_size (outbuf, n * 2 * dec->n_channels);
773 GST_BUFFER_DURATION (outbuf) = samples * GST_SECOND / dec->sample_rate;
776 cmeta = gst_buffer_get_audio_clipping_meta (buf);
778 g_assert (!cmeta || cmeta->format == GST_FORMAT_DEFAULT);
780 /* Skip any samples that need skipping */
781 if (cmeta && cmeta->start) {
782 guint pre_skip = cmeta->start;
783 guint scaled_pre_skip = pre_skip * dec->sample_rate / 48000;
784 guint skip = scaled_pre_skip > n ? n : scaled_pre_skip;
785 guint scaled_skip = skip * 48000 / dec->sample_rate;
787 gst_buffer_resize (outbuf, skip * 2 * dec->n_channels, -1);
789 GST_INFO_OBJECT (dec,
790 "Skipping %u samples at the beginning (%u at 48000 Hz)",
794 if (cmeta && cmeta->end) {
795 guint post_skip = cmeta->end;
796 guint scaled_post_skip = post_skip * dec->sample_rate / 48000;
797 guint skip = scaled_post_skip > n ? n : scaled_post_skip;
798 guint scaled_skip = skip * 48000 / dec->sample_rate;
799 guint outsize = gst_buffer_get_size (outbuf);
800 guint skip_bytes = skip * 2 * dec->n_channels;
802 if (outsize > skip_bytes)
803 outsize -= skip_bytes;
807 gst_buffer_resize (outbuf, 0, outsize);
809 GST_INFO_OBJECT (dec,
810 "Skipping %u samples at the end (%u at 48000 Hz)", skip, scaled_skip);
813 if (gst_buffer_get_size (outbuf) == 0) {
814 gst_buffer_unref (outbuf);
816 } else if (dec->opus_pos[0] != GST_AUDIO_CHANNEL_POSITION_INVALID) {
817 gst_audio_buffer_reorder_channels (outbuf, GST_AUDIO_FORMAT_S16,
818 dec->n_channels, dec->opus_pos, dec->info.position);
822 /* Would be better off leaving this to a volume element, as this is
823 a naive conversion that does too many int/float conversions.
824 However, we don't have control over the pipeline...
825 So make it optional if the user program wants to use a volume,
826 but do it by default so the correct volume goes out by default */
827 if (dec->apply_gain && outbuf && dec->r128_gain) {
829 unsigned int i, nsamples;
830 double volume = dec->r128_gain_volume;
833 gst_buffer_map (outbuf, &omap, GST_MAP_READWRITE);
834 samples = (gint16 *) omap.data;
836 GST_DEBUG_OBJECT (dec, "Applying gain: volume %f", volume);
837 nsamples = rsize / 2;
838 for (i = 0; i < nsamples; ++i) {
839 int sample = (int) (samples[i] * volume + 0.5);
840 samples[i] = sample < -32768 ? -32768 : sample > 32767 ? 32767 : sample;
842 gst_buffer_unmap (outbuf, &omap);
845 if (dec->use_inband_fec) {
846 gst_buffer_replace (&dec->last_buffer, buffer);
849 GST_OBJECT_LOCK (dec);
851 GST_OBJECT_UNLOCK (dec);
853 res = gst_audio_decoder_finish_frame (GST_AUDIO_DECODER (dec), outbuf, 1);
855 if (res != GST_FLOW_OK)
856 GST_DEBUG_OBJECT (dec, "flow: %s", gst_flow_get_name (res));
862 GST_ELEMENT_ERROR (dec, LIBRARY, INIT, ("Failed to create Opus decoder"),
863 ("Failed to create Opus decoder (%d): %s", err, opus_strerror (err)));
864 return GST_FLOW_ERROR;
867 GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL),
868 ("Failed to create %u byte buffer", packet_size));
869 return GST_FLOW_ERROR;
873 gst_opus_dec_set_format (GstAudioDecoder * bdec, GstCaps * caps)
875 GstOpusDec *dec = GST_OPUS_DEC (bdec);
878 const GValue *streamheader;
881 GST_DEBUG_OBJECT (dec, "set_format: %" GST_PTR_FORMAT, caps);
883 if ((old_caps = gst_pad_get_current_caps (GST_AUDIO_DECODER_SINK_PAD (bdec)))) {
884 if (gst_caps_is_equal (caps, old_caps)) {
885 gst_caps_unref (old_caps);
886 GST_DEBUG_OBJECT (dec, "caps didn't change");
890 GST_DEBUG_OBJECT (dec, "caps have changed, resetting decoder");
891 gst_opus_dec_reset (dec);
892 gst_caps_unref (old_caps);
895 s = gst_caps_get_structure (caps, 0);
896 if ((streamheader = gst_structure_get_value (s, "streamheader")) &&
897 G_VALUE_HOLDS (streamheader, GST_TYPE_ARRAY) &&
898 gst_value_array_get_size (streamheader) >= 2) {
899 const GValue *header, *vorbiscomment;
901 GstFlowReturn res = GST_FLOW_OK;
903 header = gst_value_array_get_value (streamheader, 0);
904 if (header && G_VALUE_HOLDS (header, GST_TYPE_BUFFER)) {
905 buf = gst_value_get_buffer (header);
906 res = gst_opus_dec_parse_header (dec, buf);
907 if (res != GST_FLOW_OK) {
911 gst_buffer_replace (&dec->streamheader, buf);
914 vorbiscomment = gst_value_array_get_value (streamheader, 1);
915 if (vorbiscomment && G_VALUE_HOLDS (vorbiscomment, GST_TYPE_BUFFER)) {
916 buf = gst_value_get_buffer (vorbiscomment);
917 res = gst_opus_dec_parse_comments (dec, buf);
918 if (res != GST_FLOW_OK) {
922 gst_buffer_replace (&dec->vorbiscomment, buf);
925 const GstAudioChannelPosition *posn = NULL;
928 if (!gst_codec_utils_opus_parse_caps (caps, &dec->sample_rate,
929 &n_channels, &dec->channel_mapping_family,
930 &dec->n_streams, &dec->n_stereo_streams, dec->channel_mapping)) {
934 dec->n_channels = n_channels;
936 if (dec->channel_mapping_family == 1 && dec->n_channels <= 8)
937 posn = gst_opus_channel_positions[dec->n_channels - 1];
939 if (!gst_opus_dec_negotiate (dec, posn))
948 memcmp_buffers (GstBuffer * buf1, GstBuffer * buf2)
954 size1 = gst_buffer_get_size (buf1);
955 size2 = gst_buffer_get_size (buf2);
960 gst_buffer_map (buf1, &map, GST_MAP_READ);
961 res = gst_buffer_memcmp (buf2, 0, map.data, map.size) == 0;
962 gst_buffer_unmap (buf1, &map);
968 gst_opus_dec_handle_frame (GstAudioDecoder * adec, GstBuffer * buf)
973 /* no fancy draining */
974 if (G_UNLIKELY (!buf))
977 dec = GST_OPUS_DEC (adec);
979 "Got buffer ts %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
980 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
981 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
983 /* If we have the streamheader and vorbiscomment from the caps already
984 * ignore them here */
985 if (dec->streamheader && dec->vorbiscomment) {
986 if (memcmp_buffers (dec->streamheader, buf)) {
987 GST_DEBUG_OBJECT (dec, "found streamheader");
988 gst_audio_decoder_finish_frame (adec, NULL, 1);
990 } else if (memcmp_buffers (dec->vorbiscomment, buf)) {
991 GST_DEBUG_OBJECT (dec, "found vorbiscomments");
992 gst_audio_decoder_finish_frame (adec, NULL, 1);
995 res = opus_dec_chain_parse_data (dec, buf);
998 /* Otherwise fall back to packet counting and assume that the
999 * first two packets might be the headers, checking magic. */
1000 switch (dec->packetno) {
1002 if (gst_opus_header_is_header (buf, "OpusHead", 8)) {
1003 GST_DEBUG_OBJECT (dec, "found streamheader");
1004 res = gst_opus_dec_parse_header (dec, buf);
1005 gst_audio_decoder_finish_frame (adec, NULL, 1);
1007 res = opus_dec_chain_parse_data (dec, buf);
1011 if (gst_opus_header_is_header (buf, "OpusTags", 8)) {
1012 GST_DEBUG_OBJECT (dec, "counted vorbiscomments");
1013 res = gst_opus_dec_parse_comments (dec, buf);
1014 gst_audio_decoder_finish_frame (adec, NULL, 1);
1016 res = opus_dec_chain_parse_data (dec, buf);
1021 res = opus_dec_chain_parse_data (dec, buf);
1032 /* Called with object lock hold */
1034 get_bandwidth (GstOpusDec * self)
1042 err = opus_multistream_decoder_ctl (self->state, OPUS_GET_BANDWIDTH (&bw));
1043 if (err != OPUS_OK) {
1044 GST_WARNING_OBJECT (self, "Could not retrieve bandwith: %s",
1045 opus_strerror (err));
1050 case OPUS_BANDWIDTH_NARROWBAND:
1052 case OPUS_BANDWIDTH_MEDIUMBAND:
1054 case OPUS_BANDWIDTH_WIDEBAND:
1056 case OPUS_BANDWIDTH_SUPERWIDEBAND:
1058 case OPUS_BANDWIDTH_FULLBAND:
1061 GST_WARNING_OBJECT (self, "Unknown bandwith enum: %d", bw);
1066 /* Called with object lock hold */
1068 get_sample_rate (GstOpusDec * self)
1077 opus_multistream_decoder_ctl (self->state, OPUS_GET_SAMPLE_RATE (&rate));
1078 if (err != OPUS_OK) {
1079 GST_WARNING_OBJECT (self, "Could not retrieve sample rate: %s",
1080 opus_strerror (err));
1087 /* Called with object lock hold */
1089 get_gain (GstOpusDec * self)
1097 err = opus_multistream_decoder_ctl (self->state, OPUS_GET_GAIN (&gain));
1098 if (err != OPUS_OK) {
1099 GST_WARNING_OBJECT (self, "Could not retrieve gain: %s",
1100 opus_strerror (err));
1107 /* Called with object lock hold */
1109 get_last_packet_duration (GstOpusDec * self)
1118 opus_multistream_decoder_ctl (self->state,
1119 OPUS_GET_LAST_PACKET_DURATION (&duration));
1120 if (err != OPUS_OK) {
1121 GST_WARNING_OBJECT (self, "Could not retrieve last packet duration: %s",
1122 opus_strerror (err));
1129 static GstStructure *
1130 gst_opus_dec_create_stats (GstOpusDec * self)
1134 GST_OBJECT_LOCK (self);
1136 s = gst_structure_new ("application/x-opusdec-stats",
1137 "num-pushed", G_TYPE_UINT64, self->num_pushed,
1138 "num-gap", G_TYPE_UINT64, self->num_gap,
1139 "plc-num-samples", G_TYPE_UINT64, self->plc_num_samples,
1140 "plc-duration", G_TYPE_UINT64, self->plc_duration,
1141 "bandwidth", G_TYPE_UINT, get_bandwidth (self),
1142 "sample-rate", G_TYPE_UINT, get_sample_rate (self),
1143 "gain", G_TYPE_UINT, get_gain (self),
1144 "last-packet-duration", G_TYPE_UINT, get_last_packet_duration (self),
1145 "channels", G_TYPE_UINT, self->n_channels, NULL);
1147 GST_OBJECT_UNLOCK (self);
1153 gst_opus_dec_get_property (GObject * object, guint prop_id, GValue * value,
1156 GstOpusDec *dec = GST_OPUS_DEC (object);
1159 case PROP_USE_INBAND_FEC:
1160 g_value_set_boolean (value, dec->use_inband_fec);
1162 case PROP_APPLY_GAIN:
1163 g_value_set_boolean (value, dec->apply_gain);
1165 case PROP_PHASE_INVERSION:
1166 g_value_set_boolean (value, dec->phase_inversion);
1169 g_value_take_boxed (value, gst_opus_dec_create_stats (dec));
1172 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1178 gst_opus_dec_set_property (GObject * object, guint prop_id,
1179 const GValue * value, GParamSpec * pspec)
1181 GstOpusDec *dec = GST_OPUS_DEC (object);
1184 case PROP_USE_INBAND_FEC:
1185 dec->use_inband_fec = g_value_get_boolean (value);
1187 case PROP_APPLY_GAIN:
1188 dec->apply_gain = g_value_get_boolean (value);
1190 case PROP_PHASE_INVERSION:
1191 dec->phase_inversion = g_value_get_boolean (value);
1194 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1199 /* caps must be writable */
1201 gst_opus_dec_caps_extend_channels_options (GstCaps * caps)
1206 for (n = 0; n < gst_caps_get_size (caps); ++n) {
1207 GstStructure *s = gst_caps_get_structure (caps, n);
1208 if (gst_structure_get_int (s, "channels", &channels)) {
1209 if (channels == 1 || channels == 2) {
1211 g_value_init (&v, GST_TYPE_INT_RANGE);
1212 gst_value_set_int_range (&v, 1, 2);
1213 gst_structure_set_value (s, "channels", &v);
1221 gst_opus_dec_value_list_append_int (GValue * list, gint i)
1225 g_value_init (&v, G_TYPE_INT);
1226 g_value_set_int (&v, i);
1227 gst_value_list_append_value (list, &v);
1232 gst_opus_dec_caps_extend_rate_options (GstCaps * caps)
1237 g_value_init (&v, GST_TYPE_LIST);
1238 gst_opus_dec_value_list_append_int (&v, 48000);
1239 gst_opus_dec_value_list_append_int (&v, 24000);
1240 gst_opus_dec_value_list_append_int (&v, 16000);
1241 gst_opus_dec_value_list_append_int (&v, 12000);
1242 gst_opus_dec_value_list_append_int (&v, 8000);
1244 for (n = 0; n < gst_caps_get_size (caps); ++n) {
1245 GstStructure *s = gst_caps_get_structure (caps, n);
1247 gst_structure_set_value (s, "rate", &v);
1253 gst_opus_dec_getcaps (GstAudioDecoder * dec, GstCaps * filter)
1255 GstCaps *caps, *proxy_filter = NULL, *ret;
1258 proxy_filter = gst_caps_copy (filter);
1259 gst_opus_dec_caps_extend_channels_options (proxy_filter);
1260 gst_opus_dec_caps_extend_rate_options (proxy_filter);
1262 caps = gst_audio_decoder_proxy_getcaps (dec, NULL, proxy_filter);
1264 gst_caps_unref (proxy_filter);
1266 caps = gst_caps_make_writable (caps);
1267 gst_opus_dec_caps_extend_channels_options (caps);
1268 gst_opus_dec_caps_extend_rate_options (caps);
1272 ret = gst_caps_intersect (caps, filter);
1273 gst_caps_unref (caps);