opusdec: Try harder to negotiate the upstream channels/rate preferences
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-base / ext / opus / gstopusdec.c
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
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
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
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
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
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
266 gst_opus_dec_get_r128_gain (gint16 r128_gain)
267 {
268   return r128_gain / (double) (1 << 8);
269 }
270
271 static double
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
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_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,
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     /* 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) {
311       GstCaps *preferred =
312           gst_caps_new_simple ("audio/x-raw", "channels", G_TYPE_INT,
313           dec->n_channels > 0 ? dec->n_channels : 2, NULL);
314       GstCaps *tmp;
315
316       tmp = gst_caps_intersect (inter, preferred);
317       if (!gst_caps_is_empty (tmp)) {
318         gst_caps_unref (inter);
319         inter = tmp;
320       }
321
322       gst_caps_unref (preferred);
323     }
324
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! */
327     {
328       GstCaps *preferred =
329           gst_caps_new_simple ("audio/x-raw", "rate", G_TYPE_INT,
330           dec->sample_rate > 0 ? dec->sample_rate : 48000, NULL);
331       GstCaps *tmp;
332
333       tmp = gst_caps_intersect (inter, preferred);
334       if (!gst_caps_is_empty (tmp)) {
335         gst_caps_unref (inter);
336         inter = tmp;
337       }
338
339       gst_caps_unref (preferred);
340     }
341
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);
350
351     gst_caps_unref (inter);
352
353     dec->sample_rate = rate;
354     dec->n_channels = channels;
355     gst_caps_unref (caps);
356   }
357
358   if (dec->n_channels == 0) {
359     GST_DEBUG_OBJECT (dec, "Using a default of 2 channels");
360     dec->n_channels = 2;
361     pos = NULL;
362   }
363
364   if (dec->sample_rate == 0) {
365     GST_DEBUG_OBJECT (dec, "Using a default of 48kHz sample rate");
366     dec->sample_rate = 48000;
367   }
368
369   GST_INFO_OBJECT (dec, "Negotiated %d channels, %d Hz", dec->n_channels,
370       dec->sample_rate);
371
372   /* pass valid order to audio info */
373   if (pos) {
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);
376   }
377
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);
383
384   /* but we still need the opus order for later reordering */
385   if (pos) {
386     memcpy (dec->opus_pos, pos, sizeof (pos[0]) * dec->n_channels);
387   } else {
388     dec->opus_pos[0] = GST_AUDIO_CHANNEL_POSITION_INVALID;
389   }
390
391   dec->info = info;
392
393   return TRUE;
394 }
395
396 static GstFlowReturn
397 gst_opus_dec_parse_header (GstOpusDec * dec, GstBuffer * buf)
398 {
399   GstAudioChannelPosition pos[64];
400   const GstAudioChannelPosition *posn = NULL;
401   guint8 n_channels;
402
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;
407   }
408
409   if (!gst_codec_utils_opus_parse_header (buf,
410           &dec->sample_rate,
411           &n_channels,
412           &dec->channel_mapping_family,
413           &dec->n_streams,
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;
419   }
420   dec->n_channels = n_channels;
421   dec->r128_gain_volume = gst_opus_dec_get_r128_volume (dec->r128_gain);
422
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);
426
427   if (dec->channel_mapping_family == 1) {
428     GST_INFO_OBJECT (dec, "Channel mapping family 1, Vorbis mapping");
429     switch (dec->n_channels) {
430       case 1:
431       case 2:
432         /* nothing */
433         break;
434       case 3:
435       case 4:
436       case 5:
437       case 6:
438       case 7:
439       case 8:
440         posn = gst_opus_channel_positions[dec->n_channels - 1];
441         break;
442       default:{
443         gint i;
444
445         GST_ELEMENT_WARNING (GST_ELEMENT (dec), STREAM, DECODE,
446             (NULL), ("Using NONE channel layout for more than 8 channels"));
447
448         for (i = 0; i < dec->n_channels; i++)
449           pos[i] = GST_AUDIO_CHANNEL_POSITION_NONE;
450
451         posn = pos;
452       }
453     }
454   } else {
455     GST_INFO_OBJECT (dec, "Channel mapping family %d",
456         dec->channel_mapping_family);
457   }
458
459   if (!gst_opus_dec_negotiate (dec, posn))
460     return GST_FLOW_NOT_NEGOTIATED;
461
462   return GST_FLOW_OK;
463 }
464
465
466 static GstFlowReturn
467 gst_opus_dec_parse_comments (GstOpusDec * dec, GstBuffer * buf)
468 {
469   return GST_FLOW_OK;
470 }
471
472 /* adapted from ext/ogg/gstoggstream.c */
473 static gint64
474 packet_duration_opus (const unsigned char *data, size_t bytes)
475 {
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 */
486   };
487
488   gint64 duration;
489   gint64 frame_duration;
490   gint nframes = 0;
491   guint8 toc;
492
493   if (bytes < 1)
494     return 0;
495
496   /* headers */
497   if (bytes >= 8 && !memcmp (data, "Opus", 4))
498     return 0;
499
500   toc = data[0];
501
502   frame_duration = durations[toc >> 3];
503   switch (toc & 3) {
504     case 0:
505       nframes = 1;
506       break;
507     case 1:
508       nframes = 2;
509       break;
510     case 2:
511       nframes = 2;
512       break;
513     case 3:
514       if (bytes < 2) {
515         GST_WARNING ("Code 3 Opus packet has less than 2 bytes");
516         return 0;
517       }
518       nframes = data[1] & 63;
519       break;
520   }
521
522   duration = nframes * frame_duration;
523   if (duration > 5760) {
524     GST_WARNING ("Opus packet duration > 120 ms, invalid");
525     return 0;
526   }
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;
530 }
531
532 static GstFlowReturn
533 opus_dec_chain_parse_data (GstOpusDec * dec, GstBuffer * buffer)
534 {
535   GstFlowReturn res = GST_FLOW_OK;
536   gsize size;
537   guint8 *data;
538   GstBuffer *outbuf, *bufd;
539   gint16 *out_data;
540   int n, err;
541   int samples;
542   unsigned int packet_size;
543   GstBuffer *buf;
544   GstMapInfo map, omap;
545   GstAudioClippingMeta *cmeta = NULL;
546
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");
551       dec->n_channels = 2;
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;
557       dec->n_streams = 1;
558       dec->n_stereo_streams = 1;
559
560       if (!gst_opus_dec_negotiate (dec, NULL))
561         return GST_FLOW_NOT_NEGOTIATED;
562     }
563
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;
569     }
570
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);
576 #endif
577
578     GST_DEBUG_OBJECT (dec, "%d streams, %d stereo", dec->n_streams,
579         dec->n_stereo_streams);
580     dec->state =
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;
585
586 #ifdef OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST
587     {
588       int err;
589       err = opus_multistream_decoder_ctl (dec->state,
590           OPUS_SET_PHASE_INVERSION_DISABLED (!dec->phase_inversion));
591       if (err != OPUS_OK)
592         GST_WARNING_OBJECT (dec, "Could not configure phase inversion: %s",
593             opus_strerror (err));
594     }
595 #else
596     GST_WARNING_OBJECT (dec, "Phase inversion request is not support by this "
597         "version of the Opus Library");
598 #endif
599   }
600
601   if (buffer) {
602     GST_DEBUG_OBJECT (dec, "Received buffer of size %" G_GSIZE_FORMAT,
603         gst_buffer_get_size (buffer));
604   } else {
605     GST_DEBUG_OBJECT (dec, "Received missing buffer");
606   }
607
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);
613     dec->primed = TRUE;
614     goto done;
615   }
616
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;
621
622   /* That's the buffer we get duration from */
623   bufd = dec->use_inband_fec ? dec->last_buffer : buffer;
624
625   if (buf && gst_buffer_get_size (buf) > 0) {
626     gst_buffer_map (buf, &map, GST_MAP_READ);
627     data = map.data;
628     size = map.size;
629     GST_DEBUG_OBJECT (dec, "Using buffer of size %" G_GSIZE_FORMAT, size);
630   } else {
631     /* concealment data, pass NULL as the bits parameters */
632     GST_DEBUG_OBJECT (dec, "Using NULL buffer");
633     data = NULL;
634     size = 0;
635   }
636
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);
641
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));
648       } else {
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;
652       }
653     }
654
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));
659
660     GST_OBJECT_LOCK (dec);
661     dec->num_gap++;
662     GST_OBJECT_UNLOCK (dec);
663
664     /* add the leftover PLC duration to that of the buffer */
665     missing_duration += dec->leftover_plc_duration;
666
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 =
670         ((missing_duration +
671             opus_plc_alignment / 2) / opus_plc_alignment) * opus_plc_alignment;
672     dec->leftover_plc_duration = missing_duration - aligned_missing_duration;
673
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));
683       goto done;
684     }
685
686     /* convert the duration (in nanoseconds) to sample count */
687     samples =
688         gst_util_uint64_scale_int (aligned_missing_duration, dec->sample_rate,
689         GST_SECOND);
690
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));
696
697     GST_OBJECT_LOCK (dec);
698     dec->plc_num_samples += samples;
699     dec->plc_duration += aligned_missing_duration;
700     GST_OBJECT_UNLOCK (dec);
701   } else {
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;
705   }
706   packet_size = samples * dec->n_channels * 2;
707
708   outbuf =
709       gst_audio_decoder_allocate_output_buffer (GST_AUDIO_DECODER (dec),
710       packet_size);
711   if (!outbuf) {
712     goto buffer_failed;
713   }
714
715   if (size > 0)
716     dec->last_known_buffer_duration = packet_duration_opus (data, size);
717
718   gst_buffer_map (outbuf, &omap, GST_MAP_WRITE);
719   out_data = (gint16 *) omap.data;
720
721   do {
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,
727             0);
728       } else {
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,
732             1);
733       }
734     } else {
735       /* normal decode */
736       GST_LOG_OBJECT (dec, "FEC disabled, decoding buffer");
737       n = opus_multistream_decode (dec->state, data, size, out_data, samples,
738           0);
739     }
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)
744         break;
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);
749       outbuf =
750           gst_audio_decoder_allocate_output_buffer (GST_AUDIO_DECODER (dec),
751           packet_size);
752       if (!outbuf) {
753         goto buffer_failed;
754       }
755       gst_buffer_map (outbuf, &omap, GST_MAP_WRITE);
756       out_data = (gint16 *) omap.data;
757     }
758   } while (n == OPUS_BUFFER_TOO_SMALL);
759   gst_buffer_unmap (outbuf, &omap);
760   if (data != NULL)
761     gst_buffer_unmap (buf, &map);
762
763   if (n < 0) {
764     GstFlowReturn ret = GST_FLOW_ERROR;
765
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);
769     return ret;
770   }
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;
774   samples = n;
775
776   cmeta = gst_buffer_get_audio_clipping_meta (buf);
777
778   g_assert (!cmeta || cmeta->format == GST_FORMAT_DEFAULT);
779
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;
786
787     gst_buffer_resize (outbuf, skip * 2 * dec->n_channels, -1);
788
789     GST_INFO_OBJECT (dec,
790         "Skipping %u samples at the beginning (%u at 48000 Hz)",
791         skip, scaled_skip);
792   }
793
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;
801
802     if (outsize > skip_bytes)
803       outsize -= skip_bytes;
804     else
805       outsize = 0;
806
807     gst_buffer_resize (outbuf, 0, outsize);
808
809     GST_INFO_OBJECT (dec,
810         "Skipping %u samples at the end (%u at 48000 Hz)", skip, scaled_skip);
811   }
812
813   if (gst_buffer_get_size (outbuf) == 0) {
814     gst_buffer_unref (outbuf);
815     outbuf = NULL;
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);
819   }
820
821   /* Apply gain */
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) {
828     gsize rsize;
829     unsigned int i, nsamples;
830     double volume = dec->r128_gain_volume;
831     gint16 *samples;
832
833     gst_buffer_map (outbuf, &omap, GST_MAP_READWRITE);
834     samples = (gint16 *) omap.data;
835     rsize = omap.size;
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;
841     }
842     gst_buffer_unmap (outbuf, &omap);
843   }
844
845   if (dec->use_inband_fec) {
846     gst_buffer_replace (&dec->last_buffer, buffer);
847   }
848
849   GST_OBJECT_LOCK (dec);
850   dec->num_pushed++;
851   GST_OBJECT_UNLOCK (dec);
852
853   res = gst_audio_decoder_finish_frame (GST_AUDIO_DECODER (dec), outbuf, 1);
854
855   if (res != GST_FLOW_OK)
856     GST_DEBUG_OBJECT (dec, "flow: %s", gst_flow_get_name (res));
857
858 done:
859   return res;
860
861 creation_failed:
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;
865
866 buffer_failed:
867   GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL),
868       ("Failed to create %u byte buffer", packet_size));
869   return GST_FLOW_ERROR;
870 }
871
872 static gboolean
873 gst_opus_dec_set_format (GstAudioDecoder * bdec, GstCaps * caps)
874 {
875   GstOpusDec *dec = GST_OPUS_DEC (bdec);
876   gboolean ret = TRUE;
877   GstStructure *s;
878   const GValue *streamheader;
879   GstCaps *old_caps;
880
881   GST_DEBUG_OBJECT (dec, "set_format: %" GST_PTR_FORMAT, caps);
882
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");
887       goto done;
888     }
889
890     GST_DEBUG_OBJECT (dec, "caps have changed, resetting decoder");
891     gst_opus_dec_reset (dec);
892     gst_caps_unref (old_caps);
893   }
894
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;
900     GstBuffer *buf;
901     GstFlowReturn res = GST_FLOW_OK;
902
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) {
908         ret = FALSE;
909         goto done;
910       }
911       gst_buffer_replace (&dec->streamheader, buf);
912     }
913
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) {
919         ret = FALSE;
920         goto done;
921       }
922       gst_buffer_replace (&dec->vorbiscomment, buf);
923     }
924   } else {
925     const GstAudioChannelPosition *posn = NULL;
926     guint8 n_channels;
927
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)) {
931       ret = FALSE;
932       goto done;
933     }
934     dec->n_channels = n_channels;
935
936     if (dec->channel_mapping_family == 1 && dec->n_channels <= 8)
937       posn = gst_opus_channel_positions[dec->n_channels - 1];
938
939     if (!gst_opus_dec_negotiate (dec, posn))
940       return FALSE;
941   }
942
943 done:
944   return ret;
945 }
946
947 static gboolean
948 memcmp_buffers (GstBuffer * buf1, GstBuffer * buf2)
949 {
950   gsize size1, size2;
951   gboolean res;
952   GstMapInfo map;
953
954   size1 = gst_buffer_get_size (buf1);
955   size2 = gst_buffer_get_size (buf2);
956
957   if (size1 != size2)
958     return FALSE;
959
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);
963
964   return res;
965 }
966
967 static GstFlowReturn
968 gst_opus_dec_handle_frame (GstAudioDecoder * adec, GstBuffer * buf)
969 {
970   GstFlowReturn res;
971   GstOpusDec *dec;
972
973   /* no fancy draining */
974   if (G_UNLIKELY (!buf))
975     return GST_FLOW_OK;
976
977   dec = GST_OPUS_DEC (adec);
978   GST_LOG_OBJECT (dec,
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)));
982
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);
989       res = GST_FLOW_OK;
990     } else if (memcmp_buffers (dec->vorbiscomment, buf)) {
991       GST_DEBUG_OBJECT (dec, "found vorbiscomments");
992       gst_audio_decoder_finish_frame (adec, NULL, 1);
993       res = GST_FLOW_OK;
994     } else {
995       res = opus_dec_chain_parse_data (dec, buf);
996     }
997   } else {
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) {
1001       case 0:
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);
1006         } else {
1007           res = opus_dec_chain_parse_data (dec, buf);
1008         }
1009         break;
1010       case 1:
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);
1015         } else {
1016           res = opus_dec_chain_parse_data (dec, buf);
1017         }
1018         break;
1019       default:
1020       {
1021         res = opus_dec_chain_parse_data (dec, buf);
1022         break;
1023       }
1024     }
1025   }
1026
1027   dec->packetno++;
1028
1029   return res;
1030 }
1031
1032 /* Called with object lock hold */
1033 static guint32
1034 get_bandwidth (GstOpusDec * self)
1035 {
1036   gint err;
1037   gint32 bw;
1038
1039   if (!self->state)
1040     return 0;
1041
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));
1046     return 0;
1047   }
1048
1049   switch (bw) {
1050     case OPUS_BANDWIDTH_NARROWBAND:
1051       return 4;
1052     case OPUS_BANDWIDTH_MEDIUMBAND:
1053       return 6;
1054     case OPUS_BANDWIDTH_WIDEBAND:
1055       return 8;
1056     case OPUS_BANDWIDTH_SUPERWIDEBAND:
1057       return 12;
1058     case OPUS_BANDWIDTH_FULLBAND:
1059       return 20;
1060     default:
1061       GST_WARNING_OBJECT (self, "Unknown bandwith enum: %d", bw);
1062       return 0;
1063   }
1064 }
1065
1066 /* Called with object lock hold */
1067 static guint32
1068 get_sample_rate (GstOpusDec * self)
1069 {
1070   gint err;
1071   gint32 rate;
1072
1073   if (!self->state)
1074     return 0;
1075
1076   err =
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));
1081     return 0;
1082   }
1083
1084   return rate;
1085 }
1086
1087 /* Called with object lock hold */
1088 static guint32
1089 get_gain (GstOpusDec * self)
1090 {
1091   gint err;
1092   gint32 gain;
1093
1094   if (!self->state)
1095     return 0;
1096
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));
1101     return 0;
1102   }
1103
1104   return gain;
1105 }
1106
1107 /* Called with object lock hold */
1108 static guint32
1109 get_last_packet_duration (GstOpusDec * self)
1110 {
1111   gint err;
1112   gint32 duration;
1113
1114   if (!self->state)
1115     return 0;
1116
1117   err =
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));
1123     return 0;
1124   }
1125
1126   return duration;
1127 }
1128
1129 static GstStructure *
1130 gst_opus_dec_create_stats (GstOpusDec * self)
1131 {
1132   GstStructure *s;
1133
1134   GST_OBJECT_LOCK (self);
1135
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);
1146
1147   GST_OBJECT_UNLOCK (self);
1148
1149   return s;
1150 }
1151
1152 static void
1153 gst_opus_dec_get_property (GObject * object, guint prop_id, GValue * value,
1154     GParamSpec * pspec)
1155 {
1156   GstOpusDec *dec = GST_OPUS_DEC (object);
1157
1158   switch (prop_id) {
1159     case PROP_USE_INBAND_FEC:
1160       g_value_set_boolean (value, dec->use_inband_fec);
1161       break;
1162     case PROP_APPLY_GAIN:
1163       g_value_set_boolean (value, dec->apply_gain);
1164       break;
1165     case PROP_PHASE_INVERSION:
1166       g_value_set_boolean (value, dec->phase_inversion);
1167       break;
1168     case PROP_STATS:
1169       g_value_take_boxed (value, gst_opus_dec_create_stats (dec));
1170       break;
1171     default:
1172       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1173       break;
1174   }
1175 }
1176
1177 static void
1178 gst_opus_dec_set_property (GObject * object, guint prop_id,
1179     const GValue * value, GParamSpec * pspec)
1180 {
1181   GstOpusDec *dec = GST_OPUS_DEC (object);
1182
1183   switch (prop_id) {
1184     case PROP_USE_INBAND_FEC:
1185       dec->use_inband_fec = g_value_get_boolean (value);
1186       break;
1187     case PROP_APPLY_GAIN:
1188       dec->apply_gain = g_value_get_boolean (value);
1189       break;
1190     case PROP_PHASE_INVERSION:
1191       dec->phase_inversion = g_value_get_boolean (value);
1192       break;
1193     default:
1194       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1195       break;
1196   }
1197 }
1198
1199 /* caps must be writable */
1200 static void
1201 gst_opus_dec_caps_extend_channels_options (GstCaps * caps)
1202 {
1203   unsigned n;
1204   int channels;
1205
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) {
1210         GValue v = { 0 };
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);
1214         g_value_unset (&v);
1215       }
1216     }
1217   }
1218 }
1219
1220 static void
1221 gst_opus_dec_value_list_append_int (GValue * list, gint i)
1222 {
1223   GValue v = { 0 };
1224
1225   g_value_init (&v, G_TYPE_INT);
1226   g_value_set_int (&v, i);
1227   gst_value_list_append_value (list, &v);
1228   g_value_unset (&v);
1229 }
1230
1231 static void
1232 gst_opus_dec_caps_extend_rate_options (GstCaps * caps)
1233 {
1234   unsigned n;
1235   GValue v = { 0 };
1236
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);
1243
1244   for (n = 0; n < gst_caps_get_size (caps); ++n) {
1245     GstStructure *s = gst_caps_get_structure (caps, n);
1246
1247     gst_structure_set_value (s, "rate", &v);
1248   }
1249   g_value_unset (&v);
1250 }
1251
1252 GstCaps *
1253 gst_opus_dec_getcaps (GstAudioDecoder * dec, GstCaps * filter)
1254 {
1255   GstCaps *caps, *proxy_filter = NULL, *ret;
1256
1257   if (filter) {
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);
1261   }
1262   caps = gst_audio_decoder_proxy_getcaps (dec, NULL, proxy_filter);
1263   if (proxy_filter)
1264     gst_caps_unref (proxy_filter);
1265   if (caps) {
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);
1269   }
1270
1271   if (filter) {
1272     ret = gst_caps_intersect (caps, filter);
1273     gst_caps_unref (caps);
1274   } else {
1275     ret = caps;
1276   }
1277   return ret;
1278 }