• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* GStreamer
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>
6  *
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.
11  *
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.
16  *
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.
21  */
22 
23 /*
24  * Based on the speexdec element.
25  */
26 
27 /**
28  * SECTION:element-opusdec
29  * @title: opusdec
30  * @see_also: opusenc, oggdemux
31  *
32  * This element decodes a OPUS stream to raw integer audio.
33  *
34  * ## Example pipelines
35  * |[
36  * gst-launch-1.0 -v filesrc location=opus.ogg ! oggdemux ! opusdec ! audioconvert ! audioresample ! alsasink
37  * ]|
38  * Decode an Ogg/Opus file. To create an Ogg/Opus file refer to the documentation of opusenc.
39  *
40  */
41 
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
45 
46 #include <math.h>
47 #include <string.h>
48 #include <stdio.h>
49 #include "gstopuselements.h"
50 #include "gstopusheader.h"
51 #include "gstopuscommon.h"
52 #include "gstopusdec.h"
53 #include <gst/pbutils/pbutils.h>
54 
55 GST_DEBUG_CATEGORY_STATIC (opusdec_debug);
56 #define GST_CAT_DEFAULT opusdec_debug
57 
58 static GstStaticPadTemplate opus_dec_src_factory =
59 GST_STATIC_PAD_TEMPLATE ("src",
60     GST_PAD_SRC,
61     GST_PAD_ALWAYS,
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 ] ")
67     );
68 
69 static GstStaticPadTemplate opus_dec_sink_factory =
70     GST_STATIC_PAD_TEMPLATE ("sink",
71     GST_PAD_SINK,
72     GST_PAD_ALWAYS,
73     GST_STATIC_CAPS ("audio/x-opus, "
74         "channel-mapping-family = (int) 0; "
75         "audio/x-opus, "
76         "channel-mapping-family = (int) [1, 255], "
77         "channels = (int) [1, 255], "
78         "stream-count = (int) [1, 255], " "coupled-count = (int) [0, 255]")
79     );
80 
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));
84 
85 #define DB_TO_LINEAR(x) pow (10., (x) / 20.)
86 
87 #define DEFAULT_USE_INBAND_FEC FALSE
88 #define DEFAULT_APPLY_GAIN TRUE
89 #define DEFAULT_PHASE_INVERSION FALSE
90 
91 enum
92 {
93   PROP_0,
94   PROP_USE_INBAND_FEC,
95   PROP_APPLY_GAIN,
96   PROP_PHASE_INVERSION,
97   PROP_STATS,
98 };
99 
100 
101 static GstFlowReturn gst_opus_dec_parse_header (GstOpusDec * dec,
102     GstBuffer * buf);
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,
106     GstBuffer * buffer);
107 static gboolean gst_opus_dec_set_format (GstAudioDecoder * bdec,
108     GstCaps * caps);
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);
114 
115 
116 static void
gst_opus_dec_class_init(GstOpusDecClass * klass)117 gst_opus_dec_class_init (GstOpusDecClass * klass)
118 {
119   GObjectClass *gobject_class;
120   GstAudioDecoderClass *adclass;
121   GstElementClass *element_class;
122 
123   gobject_class = (GObjectClass *) klass;
124   adclass = (GstAudioDecoderClass *) klass;
125   element_class = (GstElementClass *) klass;
126 
127   gobject_class->set_property = gst_opus_dec_set_property;
128   gobject_class->get_property = gst_opus_dec_get_property;
129 
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);
135 
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));
147 
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));
152 
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));
160 
161 #endif
162 
163   /**
164    * GstOpusDec:stats:
165    *
166    * Various decoder statistics. This property returns a GstStructure
167    * with name application/x-opusdec-stats with the following fields:
168    *
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
178    *
179    * Since: 1.18
180    */
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));
185 
186   GST_DEBUG_CATEGORY_INIT (opusdec_debug, "opusdec", 0,
187       "opus decoding element");
188 }
189 
190 static void
gst_opus_dec_reset(GstOpusDec * dec)191 gst_opus_dec_reset (GstOpusDec * dec)
192 {
193   dec->packetno = 0;
194   if (dec->state) {
195     opus_multistream_decoder_destroy (dec->state);
196     dec->state = NULL;
197   }
198 
199   gst_buffer_replace (&dec->streamheader, NULL);
200   gst_buffer_replace (&dec->vorbiscomment, NULL);
201   gst_buffer_replace (&dec->last_buffer, NULL);
202   dec->primed = FALSE;
203 
204   dec->pre_skip = 0;
205   dec->r128_gain = 0;
206   dec->sample_rate = 0;
207   dec->n_channels = 0;
208   dec->leftover_plc_duration = 0;
209   dec->last_known_buffer_duration = GST_CLOCK_TIME_NONE;
210 }
211 
212 static void
gst_opus_dec_init(GstOpusDec * dec)213 gst_opus_dec_init (GstOpusDec * dec)
214 {
215   dec->use_inband_fec = FALSE;
216   dec->apply_gain = DEFAULT_APPLY_GAIN;
217   dec->phase_inversion = DEFAULT_PHASE_INVERSION;
218 
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
221       (dec), TRUE);
222   GST_PAD_SET_ACCEPT_TEMPLATE (GST_AUDIO_DECODER_SINK_PAD (dec));
223 
224   gst_opus_dec_reset (dec);
225 }
226 
227 static gboolean
gst_opus_dec_start(GstAudioDecoder * dec)228 gst_opus_dec_start (GstAudioDecoder * dec)
229 {
230   GstOpusDec *odec = GST_OPUS_DEC (dec);
231 
232   gst_opus_dec_reset (odec);
233 
234   /* we know about concealment */
235   gst_audio_decoder_set_plc_aware (dec, TRUE);
236 
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
240      * goes missing.
241      */
242     gst_audio_decoder_set_latency (dec, 120 * GST_MSECOND, 120 * GST_MSECOND);
243   }
244 
245   GST_OBJECT_LOCK (dec);
246   odec->num_pushed = 0;
247   odec->num_gap = 0;
248   odec->plc_num_samples = 0;
249   odec->plc_duration = 0;
250   GST_OBJECT_UNLOCK (dec);
251 
252   return TRUE;
253 }
254 
255 static gboolean
gst_opus_dec_stop(GstAudioDecoder * dec)256 gst_opus_dec_stop (GstAudioDecoder * dec)
257 {
258   GstOpusDec *odec = GST_OPUS_DEC (dec);
259 
260   gst_opus_dec_reset (odec);
261 
262   return TRUE;
263 }
264 
265 static double
gst_opus_dec_get_r128_gain(gint16 r128_gain)266 gst_opus_dec_get_r128_gain (gint16 r128_gain)
267 {
268   return r128_gain / (double) (1 << 8);
269 }
270 
271 static double
gst_opus_dec_get_r128_volume(gint16 r128_gain)272 gst_opus_dec_get_r128_volume (gint16 r128_gain)
273 {
274   return DB_TO_LINEAR (gst_opus_dec_get_r128_gain (r128_gain));
275 }
276 
277 static gboolean
gst_opus_dec_negotiate(GstOpusDec * dec,const GstAudioChannelPosition * pos)278 gst_opus_dec_negotiate (GstOpusDec * dec, const GstAudioChannelPosition * pos)
279 {
280   GstCaps *caps = gst_pad_get_allowed_caps (GST_AUDIO_DECODER_SRC_PAD (dec));
281   GstStructure *s;
282   GstAudioInfo info;
283 
284   if (caps) {
285     gint rate = dec->sample_rate, channels = dec->n_channels;
286     GstCaps *constraint, *inter;
287 
288     constraint = gst_caps_from_string ("audio/x-raw");
289     if (dec->n_channels <= 2) { /* including 0 */
290       gst_caps_set_simple (constraint, "channels", GST_TYPE_INT_RANGE, 1, 2,
291           NULL);
292     } else {
293       gst_caps_set_simple (constraint, "channels", G_TYPE_INT, dec->n_channels,
294           NULL);
295     }
296 
297     inter = gst_caps_intersect (caps, constraint);
298     gst_caps_unref (constraint);
299 
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);
304       return FALSE;
305     }
306 
307     inter = gst_caps_truncate (inter);
308     s = gst_caps_get_structure (inter, 0);
309     rate = dec->sample_rate > 0 ? dec->sample_rate : 48000;
310     gst_structure_fixate_field_nearest_int (s, "rate", dec->sample_rate);
311     gst_structure_get_int (s, "rate", &rate);
312     channels = dec->n_channels > 0 ? dec->n_channels : 2;
313     gst_structure_fixate_field_nearest_int (s, "channels", dec->n_channels);
314     gst_structure_get_int (s, "channels", &channels);
315 
316     gst_caps_unref (inter);
317 
318     dec->sample_rate = rate;
319     dec->n_channels = channels;
320     gst_caps_unref (caps);
321   }
322 
323   if (dec->n_channels == 0) {
324     GST_DEBUG_OBJECT (dec, "Using a default of 2 channels");
325     dec->n_channels = 2;
326     pos = NULL;
327   }
328 
329   if (dec->sample_rate == 0) {
330     GST_DEBUG_OBJECT (dec, "Using a default of 48kHz sample rate");
331     dec->sample_rate = 48000;
332   }
333 
334   GST_INFO_OBJECT (dec, "Negotiated %d channels, %d Hz", dec->n_channels,
335       dec->sample_rate);
336 
337   /* pass valid order to audio info */
338   if (pos) {
339     memcpy (dec->opus_pos, pos, sizeof (pos[0]) * dec->n_channels);
340     gst_audio_channel_positions_to_valid_order (dec->opus_pos, dec->n_channels);
341   }
342 
343   /* set up source format */
344   gst_audio_info_init (&info);
345   gst_audio_info_set_format (&info, GST_AUDIO_FORMAT_S16,
346       dec->sample_rate, dec->n_channels, pos ? dec->opus_pos : NULL);
347   gst_audio_decoder_set_output_format (GST_AUDIO_DECODER (dec), &info);
348 
349   /* but we still need the opus order for later reordering */
350   if (pos) {
351     memcpy (dec->opus_pos, pos, sizeof (pos[0]) * dec->n_channels);
352   } else {
353     dec->opus_pos[0] = GST_AUDIO_CHANNEL_POSITION_INVALID;
354   }
355 
356   dec->info = info;
357 
358   return TRUE;
359 }
360 
361 static GstFlowReturn
gst_opus_dec_parse_header(GstOpusDec * dec,GstBuffer * buf)362 gst_opus_dec_parse_header (GstOpusDec * dec, GstBuffer * buf)
363 {
364   GstAudioChannelPosition pos[64];
365   const GstAudioChannelPosition *posn = NULL;
366 
367   if (!gst_opus_header_is_id_header (buf)) {
368     GST_ELEMENT_ERROR (dec, STREAM, FORMAT, (NULL),
369         ("Header is not an Opus ID header"));
370     return GST_FLOW_ERROR;
371   }
372 
373   if (!gst_codec_utils_opus_parse_header (buf,
374           &dec->sample_rate,
375           (guint8 *) & dec->n_channels,
376           &dec->channel_mapping_family,
377           &dec->n_streams,
378           &dec->n_stereo_streams,
379           dec->channel_mapping, &dec->pre_skip, &dec->r128_gain)) {
380     GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL),
381         ("Failed to parse Opus ID header"));
382     return GST_FLOW_ERROR;
383   }
384   dec->r128_gain_volume = gst_opus_dec_get_r128_volume (dec->r128_gain);
385 
386   GST_INFO_OBJECT (dec,
387       "Found pre-skip of %u samples, R128 gain %d (volume %f)",
388       dec->pre_skip, dec->r128_gain, dec->r128_gain_volume);
389 
390   if (dec->channel_mapping_family == 1) {
391     GST_INFO_OBJECT (dec, "Channel mapping family 1, Vorbis mapping");
392     switch (dec->n_channels) {
393       case 1:
394       case 2:
395         /* nothing */
396         break;
397       case 3:
398       case 4:
399       case 5:
400       case 6:
401       case 7:
402       case 8:
403         posn = gst_opus_channel_positions[dec->n_channels - 1];
404         break;
405       default:{
406         gint i;
407 
408         GST_ELEMENT_WARNING (GST_ELEMENT (dec), STREAM, DECODE,
409             (NULL), ("Using NONE channel layout for more than 8 channels"));
410 
411         for (i = 0; i < dec->n_channels; i++)
412           pos[i] = GST_AUDIO_CHANNEL_POSITION_NONE;
413 
414         posn = pos;
415       }
416     }
417   } else {
418     GST_INFO_OBJECT (dec, "Channel mapping family %d",
419         dec->channel_mapping_family);
420   }
421 
422   if (!gst_opus_dec_negotiate (dec, posn))
423     return GST_FLOW_NOT_NEGOTIATED;
424 
425   return GST_FLOW_OK;
426 }
427 
428 
429 static GstFlowReturn
gst_opus_dec_parse_comments(GstOpusDec * dec,GstBuffer * buf)430 gst_opus_dec_parse_comments (GstOpusDec * dec, GstBuffer * buf)
431 {
432   return GST_FLOW_OK;
433 }
434 
435 /* adapted from ext/ogg/gstoggstream.c */
436 static gint64
packet_duration_opus(const unsigned char * data,size_t bytes)437 packet_duration_opus (const unsigned char *data, size_t bytes)
438 {
439   static const guint64 durations[32] = {
440     480, 960, 1920, 2880,       /* Silk NB */
441     480, 960, 1920, 2880,       /* Silk MB */
442     480, 960, 1920, 2880,       /* Silk WB */
443     480, 960,                   /* Hybrid SWB */
444     480, 960,                   /* Hybrid FB */
445     120, 240, 480, 960,         /* CELT NB */
446     120, 240, 480, 960,         /* CELT NB */
447     120, 240, 480, 960,         /* CELT NB */
448     120, 240, 480, 960,         /* CELT NB */
449   };
450 
451   gint64 duration;
452   gint64 frame_duration;
453   gint nframes = 0;
454   guint8 toc;
455 
456   if (bytes < 1)
457     return 0;
458 
459   /* headers */
460   if (bytes >= 8 && !memcmp (data, "Opus", 4))
461     return 0;
462 
463   toc = data[0];
464 
465   frame_duration = durations[toc >> 3];
466   switch (toc & 3) {
467     case 0:
468       nframes = 1;
469       break;
470     case 1:
471       nframes = 2;
472       break;
473     case 2:
474       nframes = 2;
475       break;
476     case 3:
477       if (bytes < 2) {
478         GST_WARNING ("Code 3 Opus packet has less than 2 bytes");
479         return 0;
480       }
481       nframes = data[1] & 63;
482       break;
483   }
484 
485   duration = nframes * frame_duration;
486   if (duration > 5760) {
487     GST_WARNING ("Opus packet duration > 120 ms, invalid");
488     return 0;
489   }
490   GST_LOG ("Opus packet: frame size %.1f ms, %d frames, duration %.1f ms",
491       frame_duration / 48.f, nframes, duration / 48.f);
492   return duration / 48.f * 1000000;
493 }
494 
495 static GstFlowReturn
opus_dec_chain_parse_data(GstOpusDec * dec,GstBuffer * buffer)496 opus_dec_chain_parse_data (GstOpusDec * dec, GstBuffer * buffer)
497 {
498   GstFlowReturn res = GST_FLOW_OK;
499   gsize size;
500   guint8 *data;
501   GstBuffer *outbuf, *bufd;
502   gint16 *out_data;
503   int n, err;
504   int samples;
505   unsigned int packet_size;
506   GstBuffer *buf;
507   GstMapInfo map, omap;
508   GstAudioClippingMeta *cmeta = NULL;
509 
510   if (dec->state == NULL) {
511     /* If we did not get any headers, default to 2 channels */
512     if (dec->n_channels == 0) {
513       GST_INFO_OBJECT (dec, "No header, assuming single stream");
514       dec->n_channels = 2;
515       dec->sample_rate = 48000;
516       /* default stereo mapping */
517       dec->channel_mapping_family = 0;
518       dec->channel_mapping[0] = 0;
519       dec->channel_mapping[1] = 1;
520       dec->n_streams = 1;
521       dec->n_stereo_streams = 1;
522 
523       if (!gst_opus_dec_negotiate (dec, NULL))
524         return GST_FLOW_NOT_NEGOTIATED;
525     }
526 
527     if (dec->n_channels == 2 && dec->n_streams == 1
528         && dec->n_stereo_streams == 0) {
529       /* if we are automatically decoding 2 channels, but only have
530          a single encoded one, direct both channels to it */
531       dec->channel_mapping[1] = 0;
532     }
533 
534     GST_DEBUG_OBJECT (dec, "Creating decoder with %d channels, %d Hz",
535         dec->n_channels, dec->sample_rate);
536 #ifndef GST_DISABLE_GST_DEBUG
537     gst_opus_common_log_channel_mapping_table (GST_ELEMENT (dec), opusdec_debug,
538         "Mapping table", dec->n_channels, dec->channel_mapping);
539 #endif
540 
541     GST_DEBUG_OBJECT (dec, "%d streams, %d stereo", dec->n_streams,
542         dec->n_stereo_streams);
543     dec->state =
544         opus_multistream_decoder_create (dec->sample_rate, dec->n_channels,
545         dec->n_streams, dec->n_stereo_streams, dec->channel_mapping, &err);
546     if (!dec->state || err != OPUS_OK)
547       goto creation_failed;
548 
549 #ifdef OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST
550     {
551       int err;
552       err = opus_multistream_decoder_ctl (dec->state,
553           OPUS_SET_PHASE_INVERSION_DISABLED (!dec->phase_inversion));
554       if (err != OPUS_OK)
555         GST_WARNING_OBJECT (dec, "Could not configure phase inversion: %s",
556             opus_strerror (err));
557     }
558 #else
559     GST_WARNING_OBJECT (dec, "Phase inversion request is not support by this "
560         "version of the Opus Library");
561 #endif
562   }
563 
564   if (buffer) {
565     GST_DEBUG_OBJECT (dec, "Received buffer of size %" G_GSIZE_FORMAT,
566         gst_buffer_get_size (buffer));
567   } else {
568     GST_DEBUG_OBJECT (dec, "Received missing buffer");
569   }
570 
571   /* if using in-band FEC, we introdude one extra frame's delay as we need
572      to potentially wait for next buffer to decode a missing buffer */
573   if (dec->use_inband_fec && !dec->primed) {
574     GST_DEBUG_OBJECT (dec, "First buffer received in FEC mode, early out");
575     gst_buffer_replace (&dec->last_buffer, buffer);
576     dec->primed = TRUE;
577     goto done;
578   }
579 
580   /* That's the buffer we'll be sending to the opus decoder. */
581   buf = (dec->use_inband_fec
582       && gst_buffer_get_size (dec->last_buffer) >
583       0) ? dec->last_buffer : buffer;
584 
585   /* That's the buffer we get duration from */
586   bufd = dec->use_inband_fec ? dec->last_buffer : buffer;
587 
588   if (buf && gst_buffer_get_size (buf) > 0) {
589     gst_buffer_map (buf, &map, GST_MAP_READ);
590     data = map.data;
591     size = map.size;
592     GST_DEBUG_OBJECT (dec, "Using buffer of size %" G_GSIZE_FORMAT, size);
593   } else {
594     /* concealment data, pass NULL as the bits parameters */
595     GST_DEBUG_OBJECT (dec, "Using NULL buffer");
596     data = NULL;
597     size = 0;
598   }
599 
600   if (gst_buffer_get_size (bufd) == 0) {
601     GstClockTime const opus_plc_alignment = 2500 * GST_USECOND;
602     GstClockTime aligned_missing_duration;
603     GstClockTime missing_duration = GST_BUFFER_DURATION (bufd);
604 
605     if (!GST_CLOCK_TIME_IS_VALID (missing_duration) || missing_duration == 0) {
606       if (GST_CLOCK_TIME_IS_VALID (dec->last_known_buffer_duration)) {
607         missing_duration = dec->last_known_buffer_duration;
608         GST_WARNING_OBJECT (dec,
609             "Missing duration, using last duration %" GST_TIME_FORMAT,
610             GST_TIME_ARGS (missing_duration));
611       } else {
612         GST_WARNING_OBJECT (dec,
613             "Missing buffer, but unknown duration, and no previously known duration, assuming 20 ms");
614         missing_duration = 20 * GST_MSECOND;
615       }
616     }
617 
618     GST_DEBUG_OBJECT (dec,
619         "missing buffer, doing PLC duration %" GST_TIME_FORMAT
620         " plus leftover %" GST_TIME_FORMAT, GST_TIME_ARGS (missing_duration),
621         GST_TIME_ARGS (dec->leftover_plc_duration));
622 
623     GST_OBJECT_LOCK (dec);
624     dec->num_gap++;
625     GST_OBJECT_UNLOCK (dec);
626 
627     /* add the leftover PLC duration to that of the buffer */
628     missing_duration += dec->leftover_plc_duration;
629 
630     /* align the combined buffer and leftover PLC duration to multiples
631      * of 2.5ms, rounding to nearest, and store excess duration for later */
632     aligned_missing_duration =
633         ((missing_duration +
634             opus_plc_alignment / 2) / opus_plc_alignment) * opus_plc_alignment;
635     dec->leftover_plc_duration = missing_duration - aligned_missing_duration;
636 
637     /* Opus' PLC cannot operate with less than 2.5ms; skip PLC
638      * and accumulate the missing duration in the leftover_plc_duration
639      * for the next PLC attempt */
640     if (aligned_missing_duration < opus_plc_alignment) {
641       GST_DEBUG_OBJECT (dec,
642           "current duration %" GST_TIME_FORMAT
643           " of missing data not enough for PLC (minimum needed: %"
644           GST_TIME_FORMAT ") - skipping", GST_TIME_ARGS (missing_duration),
645           GST_TIME_ARGS (opus_plc_alignment));
646       goto done;
647     }
648 
649     /* convert the duration (in nanoseconds) to sample count */
650     samples =
651         gst_util_uint64_scale_int (aligned_missing_duration, dec->sample_rate,
652         GST_SECOND);
653 
654     GST_DEBUG_OBJECT (dec,
655         "calculated PLC frame length: %" GST_TIME_FORMAT
656         " num frame samples: %d new leftover: %" GST_TIME_FORMAT,
657         GST_TIME_ARGS (aligned_missing_duration), samples,
658         GST_TIME_ARGS (dec->leftover_plc_duration));
659 
660     GST_OBJECT_LOCK (dec);
661     dec->plc_num_samples += samples;
662     dec->plc_duration += aligned_missing_duration;
663     GST_OBJECT_UNLOCK (dec);
664   } else {
665     /* use maximum size (120 ms) as the number of returned samples is
666        not constant over the stream. */
667     samples = 120 * dec->sample_rate / 1000;
668   }
669   packet_size = samples * dec->n_channels * 2;
670 
671   outbuf =
672       gst_audio_decoder_allocate_output_buffer (GST_AUDIO_DECODER (dec),
673       packet_size);
674   if (!outbuf) {
675     goto buffer_failed;
676   }
677 
678   if (size > 0)
679     dec->last_known_buffer_duration = packet_duration_opus (data, size);
680 
681   gst_buffer_map (outbuf, &omap, GST_MAP_WRITE);
682   out_data = (gint16 *) omap.data;
683 
684   do {
685     if (dec->use_inband_fec) {
686       if (gst_buffer_get_size (dec->last_buffer) > 0) {
687         /* normal delayed decode */
688         GST_LOG_OBJECT (dec, "FEC enabled, decoding last delayed buffer");
689         n = opus_multistream_decode (dec->state, data, size, out_data, samples,
690             0);
691       } else {
692         /* FEC reconstruction decode */
693         GST_LOG_OBJECT (dec, "FEC enabled, reconstructing last buffer");
694         n = opus_multistream_decode (dec->state, data, size, out_data, samples,
695             1);
696       }
697     } else {
698       /* normal decode */
699       GST_LOG_OBJECT (dec, "FEC disabled, decoding buffer");
700       n = opus_multistream_decode (dec->state, data, size, out_data, samples,
701           0);
702     }
703     if (n == OPUS_BUFFER_TOO_SMALL) {
704       /* if too small, add 2.5 milliseconds and try again, up to the
705        * Opus max size of 120 milliseconds */
706       if (samples >= 120 * dec->sample_rate / 1000)
707         break;
708       samples += 25 * dec->sample_rate / 10000;
709       packet_size = samples * dec->n_channels * 2;
710       gst_buffer_unmap (outbuf, &omap);
711       gst_buffer_unref (outbuf);
712       outbuf =
713           gst_audio_decoder_allocate_output_buffer (GST_AUDIO_DECODER (dec),
714           packet_size);
715       if (!outbuf) {
716         goto buffer_failed;
717       }
718       gst_buffer_map (outbuf, &omap, GST_MAP_WRITE);
719       out_data = (gint16 *) omap.data;
720     }
721   } while (n == OPUS_BUFFER_TOO_SMALL);
722   gst_buffer_unmap (outbuf, &omap);
723   if (data != NULL)
724     gst_buffer_unmap (buf, &map);
725 
726   if (n < 0) {
727     GstFlowReturn ret = GST_FLOW_ERROR;
728 
729     gst_buffer_unref (outbuf);
730     GST_AUDIO_DECODER_ERROR (dec, 1, STREAM, DECODE, (NULL),
731         ("Decoding error (%d): %s", n, opus_strerror (n)), ret);
732     return ret;
733   }
734   GST_DEBUG_OBJECT (dec, "decoded %d samples", n);
735   gst_buffer_set_size (outbuf, n * 2 * dec->n_channels);
736   GST_BUFFER_DURATION (outbuf) = samples * GST_SECOND / dec->sample_rate;
737   samples = n;
738 
739   cmeta = gst_buffer_get_audio_clipping_meta (buf);
740 
741   g_assert (!cmeta || cmeta->format == GST_FORMAT_DEFAULT);
742 
743   /* Skip any samples that need skipping */
744   if (cmeta && cmeta->start) {
745     guint pre_skip = cmeta->start;
746     guint scaled_pre_skip = pre_skip * dec->sample_rate / 48000;
747     guint skip = scaled_pre_skip > n ? n : scaled_pre_skip;
748     guint scaled_skip = skip * 48000 / dec->sample_rate;
749 
750     gst_buffer_resize (outbuf, skip * 2 * dec->n_channels, -1);
751 
752     GST_INFO_OBJECT (dec,
753         "Skipping %u samples at the beginning (%u at 48000 Hz)",
754         skip, scaled_skip);
755   }
756 
757   if (cmeta && cmeta->end) {
758     guint post_skip = cmeta->end;
759     guint scaled_post_skip = post_skip * dec->sample_rate / 48000;
760     guint skip = scaled_post_skip > n ? n : scaled_post_skip;
761     guint scaled_skip = skip * 48000 / dec->sample_rate;
762     guint outsize = gst_buffer_get_size (outbuf);
763     guint skip_bytes = skip * 2 * dec->n_channels;
764 
765     if (outsize > skip_bytes)
766       outsize -= skip_bytes;
767     else
768       outsize = 0;
769 
770     gst_buffer_resize (outbuf, 0, outsize);
771 
772     GST_INFO_OBJECT (dec,
773         "Skipping %u samples at the end (%u at 48000 Hz)", skip, scaled_skip);
774   }
775 
776   if (gst_buffer_get_size (outbuf) == 0) {
777     gst_buffer_unref (outbuf);
778     outbuf = NULL;
779   } else if (dec->opus_pos[0] != GST_AUDIO_CHANNEL_POSITION_INVALID) {
780     gst_audio_buffer_reorder_channels (outbuf, GST_AUDIO_FORMAT_S16,
781         dec->n_channels, dec->opus_pos, dec->info.position);
782   }
783 
784   /* Apply gain */
785   /* Would be better off leaving this to a volume element, as this is
786      a naive conversion that does too many int/float conversions.
787      However, we don't have control over the pipeline...
788      So make it optional if the user program wants to use a volume,
789      but do it by default so the correct volume goes out by default */
790   if (dec->apply_gain && outbuf && dec->r128_gain) {
791     gsize rsize;
792     unsigned int i, nsamples;
793     double volume = dec->r128_gain_volume;
794     gint16 *samples;
795 
796     gst_buffer_map (outbuf, &omap, GST_MAP_READWRITE);
797     samples = (gint16 *) omap.data;
798     rsize = omap.size;
799     GST_DEBUG_OBJECT (dec, "Applying gain: volume %f", volume);
800     nsamples = rsize / 2;
801     for (i = 0; i < nsamples; ++i) {
802       int sample = (int) (samples[i] * volume + 0.5);
803       samples[i] = sample < -32768 ? -32768 : sample > 32767 ? 32767 : sample;
804     }
805     gst_buffer_unmap (outbuf, &omap);
806   }
807 
808   if (dec->use_inband_fec) {
809     gst_buffer_replace (&dec->last_buffer, buffer);
810   }
811 
812   GST_OBJECT_LOCK (dec);
813   dec->num_pushed++;
814   GST_OBJECT_UNLOCK (dec);
815 
816   res = gst_audio_decoder_finish_frame (GST_AUDIO_DECODER (dec), outbuf, 1);
817 
818   if (res != GST_FLOW_OK)
819     GST_DEBUG_OBJECT (dec, "flow: %s", gst_flow_get_name (res));
820 
821 done:
822   return res;
823 
824 creation_failed:
825   GST_ELEMENT_ERROR (dec, LIBRARY, INIT, ("Failed to create Opus decoder"),
826       ("Failed to create Opus decoder (%d): %s", err, opus_strerror (err)));
827   return GST_FLOW_ERROR;
828 
829 buffer_failed:
830   GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL),
831       ("Failed to create %u byte buffer", packet_size));
832   return GST_FLOW_ERROR;
833 }
834 
835 static gboolean
gst_opus_dec_set_format(GstAudioDecoder * bdec,GstCaps * caps)836 gst_opus_dec_set_format (GstAudioDecoder * bdec, GstCaps * caps)
837 {
838   GstOpusDec *dec = GST_OPUS_DEC (bdec);
839   gboolean ret = TRUE;
840   GstStructure *s;
841   const GValue *streamheader;
842   GstCaps *old_caps;
843 
844   GST_DEBUG_OBJECT (dec, "set_format: %" GST_PTR_FORMAT, caps);
845 
846   if ((old_caps = gst_pad_get_current_caps (GST_AUDIO_DECODER_SINK_PAD (bdec)))) {
847     if (gst_caps_is_equal (caps, old_caps)) {
848       gst_caps_unref (old_caps);
849       GST_DEBUG_OBJECT (dec, "caps didn't change");
850       goto done;
851     }
852 
853     GST_DEBUG_OBJECT (dec, "caps have changed, resetting decoder");
854     gst_opus_dec_reset (dec);
855     gst_caps_unref (old_caps);
856   }
857 
858   s = gst_caps_get_structure (caps, 0);
859   if ((streamheader = gst_structure_get_value (s, "streamheader")) &&
860       G_VALUE_HOLDS (streamheader, GST_TYPE_ARRAY) &&
861       gst_value_array_get_size (streamheader) >= 2) {
862     const GValue *header, *vorbiscomment;
863     GstBuffer *buf;
864     GstFlowReturn res = GST_FLOW_OK;
865 
866     header = gst_value_array_get_value (streamheader, 0);
867     if (header && G_VALUE_HOLDS (header, GST_TYPE_BUFFER)) {
868       buf = gst_value_get_buffer (header);
869       res = gst_opus_dec_parse_header (dec, buf);
870       if (res != GST_FLOW_OK) {
871         ret = FALSE;
872         goto done;
873       }
874       gst_buffer_replace (&dec->streamheader, buf);
875     }
876 
877     vorbiscomment = gst_value_array_get_value (streamheader, 1);
878     if (vorbiscomment && G_VALUE_HOLDS (vorbiscomment, GST_TYPE_BUFFER)) {
879       buf = gst_value_get_buffer (vorbiscomment);
880       res = gst_opus_dec_parse_comments (dec, buf);
881       if (res != GST_FLOW_OK) {
882         ret = FALSE;
883         goto done;
884       }
885       gst_buffer_replace (&dec->vorbiscomment, buf);
886     }
887   } else {
888     const GstAudioChannelPosition *posn = NULL;
889 
890     if (!gst_codec_utils_opus_parse_caps (caps, &dec->sample_rate,
891             (guint8 *) & dec->n_channels, &dec->channel_mapping_family,
892             &dec->n_streams, &dec->n_stereo_streams, dec->channel_mapping)) {
893       ret = FALSE;
894       goto done;
895     }
896 
897     if (dec->channel_mapping_family == 1 && dec->n_channels <= 8)
898       posn = gst_opus_channel_positions[dec->n_channels - 1];
899 
900     if (!gst_opus_dec_negotiate (dec, posn))
901       return FALSE;
902   }
903 
904 done:
905   return ret;
906 }
907 
908 static gboolean
memcmp_buffers(GstBuffer * buf1,GstBuffer * buf2)909 memcmp_buffers (GstBuffer * buf1, GstBuffer * buf2)
910 {
911   gsize size1, size2;
912   gboolean res;
913   GstMapInfo map;
914 
915   size1 = gst_buffer_get_size (buf1);
916   size2 = gst_buffer_get_size (buf2);
917 
918   if (size1 != size2)
919     return FALSE;
920 
921   gst_buffer_map (buf1, &map, GST_MAP_READ);
922   res = gst_buffer_memcmp (buf2, 0, map.data, map.size) == 0;
923   gst_buffer_unmap (buf1, &map);
924 
925   return res;
926 }
927 
928 static GstFlowReturn
gst_opus_dec_handle_frame(GstAudioDecoder * adec,GstBuffer * buf)929 gst_opus_dec_handle_frame (GstAudioDecoder * adec, GstBuffer * buf)
930 {
931   GstFlowReturn res;
932   GstOpusDec *dec;
933 
934   /* no fancy draining */
935   if (G_UNLIKELY (!buf))
936     return GST_FLOW_OK;
937 
938   dec = GST_OPUS_DEC (adec);
939   GST_LOG_OBJECT (dec,
940       "Got buffer ts %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
941       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
942       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
943 
944   /* If we have the streamheader and vorbiscomment from the caps already
945    * ignore them here */
946   if (dec->streamheader && dec->vorbiscomment) {
947     if (memcmp_buffers (dec->streamheader, buf)) {
948       GST_DEBUG_OBJECT (dec, "found streamheader");
949       gst_audio_decoder_finish_frame (adec, NULL, 1);
950       res = GST_FLOW_OK;
951     } else if (memcmp_buffers (dec->vorbiscomment, buf)) {
952       GST_DEBUG_OBJECT (dec, "found vorbiscomments");
953       gst_audio_decoder_finish_frame (adec, NULL, 1);
954       res = GST_FLOW_OK;
955     } else {
956       res = opus_dec_chain_parse_data (dec, buf);
957     }
958   } else {
959     /* Otherwise fall back to packet counting and assume that the
960      * first two packets might be the headers, checking magic. */
961     switch (dec->packetno) {
962       case 0:
963         if (gst_opus_header_is_header (buf, "OpusHead", 8)) {
964           GST_DEBUG_OBJECT (dec, "found streamheader");
965           res = gst_opus_dec_parse_header (dec, buf);
966           gst_audio_decoder_finish_frame (adec, NULL, 1);
967         } else {
968           res = opus_dec_chain_parse_data (dec, buf);
969         }
970         break;
971       case 1:
972         if (gst_opus_header_is_header (buf, "OpusTags", 8)) {
973           GST_DEBUG_OBJECT (dec, "counted vorbiscomments");
974           res = gst_opus_dec_parse_comments (dec, buf);
975           gst_audio_decoder_finish_frame (adec, NULL, 1);
976         } else {
977           res = opus_dec_chain_parse_data (dec, buf);
978         }
979         break;
980       default:
981       {
982         res = opus_dec_chain_parse_data (dec, buf);
983         break;
984       }
985     }
986   }
987 
988   dec->packetno++;
989 
990   return res;
991 }
992 
993 /* Called with object lock hold */
994 static guint32
get_bandwidth(GstOpusDec * self)995 get_bandwidth (GstOpusDec * self)
996 {
997   gint err;
998   gint32 bw;
999 
1000   if (!self->state)
1001     return 0;
1002 
1003   err = opus_multistream_decoder_ctl (self->state, OPUS_GET_BANDWIDTH (&bw));
1004   if (err != OPUS_OK) {
1005     GST_WARNING_OBJECT (self, "Could not retrieve bandwith: %s",
1006         opus_strerror (err));
1007     return 0;
1008   }
1009 
1010   switch (bw) {
1011     case OPUS_BANDWIDTH_NARROWBAND:
1012       return 4;
1013     case OPUS_BANDWIDTH_MEDIUMBAND:
1014       return 6;
1015     case OPUS_BANDWIDTH_WIDEBAND:
1016       return 8;
1017     case OPUS_BANDWIDTH_SUPERWIDEBAND:
1018       return 12;
1019     case OPUS_BANDWIDTH_FULLBAND:
1020       return 20;
1021     default:
1022       GST_WARNING_OBJECT (self, "Unknown bandwith enum: %d", bw);
1023       return 0;
1024   }
1025 }
1026 
1027 /* Called with object lock hold */
1028 static guint32
get_sample_rate(GstOpusDec * self)1029 get_sample_rate (GstOpusDec * self)
1030 {
1031   gint err;
1032   gint32 rate;
1033 
1034   if (!self->state)
1035     return 0;
1036 
1037   err =
1038       opus_multistream_decoder_ctl (self->state, OPUS_GET_SAMPLE_RATE (&rate));
1039   if (err != OPUS_OK) {
1040     GST_WARNING_OBJECT (self, "Could not retrieve sample rate: %s",
1041         opus_strerror (err));
1042     return 0;
1043   }
1044 
1045   return rate;
1046 }
1047 
1048 /* Called with object lock hold */
1049 static guint32
get_gain(GstOpusDec * self)1050 get_gain (GstOpusDec * self)
1051 {
1052   gint err;
1053   gint32 gain;
1054 
1055   if (!self->state)
1056     return 0;
1057 
1058   err = opus_multistream_decoder_ctl (self->state, OPUS_GET_GAIN (&gain));
1059   if (err != OPUS_OK) {
1060     GST_WARNING_OBJECT (self, "Could not retrieve gain: %s",
1061         opus_strerror (err));
1062     return 0;
1063   }
1064 
1065   return gain;
1066 }
1067 
1068 /* Called with object lock hold */
1069 static guint32
get_last_packet_duration(GstOpusDec * self)1070 get_last_packet_duration (GstOpusDec * self)
1071 {
1072   gint err;
1073   gint32 duration;
1074 
1075   if (!self->state)
1076     return 0;
1077 
1078   err =
1079       opus_multistream_decoder_ctl (self->state,
1080       OPUS_GET_LAST_PACKET_DURATION (&duration));
1081   if (err != OPUS_OK) {
1082     GST_WARNING_OBJECT (self, "Could not retrieve last packet duration: %s",
1083         opus_strerror (err));
1084     return 0;
1085   }
1086 
1087   return duration;
1088 }
1089 
1090 static GstStructure *
gst_opus_dec_create_stats(GstOpusDec * self)1091 gst_opus_dec_create_stats (GstOpusDec * self)
1092 {
1093   GstStructure *s;
1094 
1095   GST_OBJECT_LOCK (self);
1096 
1097   s = gst_structure_new ("application/x-opusdec-stats",
1098       "num-pushed", G_TYPE_UINT64, self->num_pushed,
1099       "num-gap", G_TYPE_UINT64, self->num_gap,
1100       "plc-num-samples", G_TYPE_UINT64, self->plc_num_samples,
1101       "plc-duration", G_TYPE_UINT64, self->plc_duration,
1102       "bandwidth", G_TYPE_UINT, get_bandwidth (self),
1103       "sample-rate", G_TYPE_UINT, get_sample_rate (self),
1104       "gain", G_TYPE_UINT, get_gain (self),
1105       "last-packet-duration", G_TYPE_UINT, get_last_packet_duration (self),
1106       "channels", G_TYPE_UINT, self->n_channels, NULL);
1107 
1108   GST_OBJECT_UNLOCK (self);
1109 
1110   return s;
1111 }
1112 
1113 static void
gst_opus_dec_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)1114 gst_opus_dec_get_property (GObject * object, guint prop_id, GValue * value,
1115     GParamSpec * pspec)
1116 {
1117   GstOpusDec *dec = GST_OPUS_DEC (object);
1118 
1119   switch (prop_id) {
1120     case PROP_USE_INBAND_FEC:
1121       g_value_set_boolean (value, dec->use_inband_fec);
1122       break;
1123     case PROP_APPLY_GAIN:
1124       g_value_set_boolean (value, dec->apply_gain);
1125       break;
1126     case PROP_PHASE_INVERSION:
1127       g_value_set_boolean (value, dec->phase_inversion);
1128       break;
1129     case PROP_STATS:
1130       g_value_take_boxed (value, gst_opus_dec_create_stats (dec));
1131       break;
1132     default:
1133       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1134       break;
1135   }
1136 }
1137 
1138 static void
gst_opus_dec_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)1139 gst_opus_dec_set_property (GObject * object, guint prop_id,
1140     const GValue * value, GParamSpec * pspec)
1141 {
1142   GstOpusDec *dec = GST_OPUS_DEC (object);
1143 
1144   switch (prop_id) {
1145     case PROP_USE_INBAND_FEC:
1146       dec->use_inband_fec = g_value_get_boolean (value);
1147       break;
1148     case PROP_APPLY_GAIN:
1149       dec->apply_gain = g_value_get_boolean (value);
1150       break;
1151     case PROP_PHASE_INVERSION:
1152       dec->phase_inversion = g_value_get_boolean (value);
1153       break;
1154     default:
1155       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1156       break;
1157   }
1158 }
1159 
1160 /* caps must be writable */
1161 static void
gst_opus_dec_caps_extend_channels_options(GstCaps * caps)1162 gst_opus_dec_caps_extend_channels_options (GstCaps * caps)
1163 {
1164   unsigned n;
1165   int channels;
1166 
1167   for (n = 0; n < gst_caps_get_size (caps); ++n) {
1168     GstStructure *s = gst_caps_get_structure (caps, n);
1169     if (gst_structure_get_int (s, "channels", &channels)) {
1170       if (channels == 1 || channels == 2) {
1171         GValue v = { 0 };
1172         g_value_init (&v, GST_TYPE_INT_RANGE);
1173         gst_value_set_int_range (&v, 1, 2);
1174         gst_structure_set_value (s, "channels", &v);
1175         g_value_unset (&v);
1176       }
1177     }
1178   }
1179 }
1180 
1181 static void
gst_opus_dec_value_list_append_int(GValue * list,gint i)1182 gst_opus_dec_value_list_append_int (GValue * list, gint i)
1183 {
1184   GValue v = { 0 };
1185 
1186   g_value_init (&v, G_TYPE_INT);
1187   g_value_set_int (&v, i);
1188   gst_value_list_append_value (list, &v);
1189   g_value_unset (&v);
1190 }
1191 
1192 static void
gst_opus_dec_caps_extend_rate_options(GstCaps * caps)1193 gst_opus_dec_caps_extend_rate_options (GstCaps * caps)
1194 {
1195   unsigned n;
1196   GValue v = { 0 };
1197 
1198   g_value_init (&v, GST_TYPE_LIST);
1199   gst_opus_dec_value_list_append_int (&v, 48000);
1200   gst_opus_dec_value_list_append_int (&v, 24000);
1201   gst_opus_dec_value_list_append_int (&v, 16000);
1202   gst_opus_dec_value_list_append_int (&v, 12000);
1203   gst_opus_dec_value_list_append_int (&v, 8000);
1204 
1205   for (n = 0; n < gst_caps_get_size (caps); ++n) {
1206     GstStructure *s = gst_caps_get_structure (caps, n);
1207 
1208     gst_structure_set_value (s, "rate", &v);
1209   }
1210   g_value_unset (&v);
1211 }
1212 
1213 GstCaps *
gst_opus_dec_getcaps(GstAudioDecoder * dec,GstCaps * filter)1214 gst_opus_dec_getcaps (GstAudioDecoder * dec, GstCaps * filter)
1215 {
1216   GstCaps *caps, *proxy_filter = NULL, *ret;
1217 
1218   if (filter) {
1219     proxy_filter = gst_caps_copy (filter);
1220     gst_opus_dec_caps_extend_channels_options (proxy_filter);
1221     gst_opus_dec_caps_extend_rate_options (proxy_filter);
1222   }
1223   caps = gst_audio_decoder_proxy_getcaps (dec, NULL, proxy_filter);
1224   if (proxy_filter)
1225     gst_caps_unref (proxy_filter);
1226   if (caps) {
1227     caps = gst_caps_make_writable (caps);
1228     gst_opus_dec_caps_extend_channels_options (caps);
1229     gst_opus_dec_caps_extend_rate_options (caps);
1230   }
1231 
1232   if (filter) {
1233     ret = gst_caps_intersect (caps, filter);
1234     gst_caps_unref (caps);
1235   } else {
1236     ret = caps;
1237   }
1238   return ret;
1239 }
1240