]> git.sesse.net Git - ffmpeg/blob - libavcodec/libopusdec.c
Merge commit '76eef04f30a768fa80366d679f3de7e9447b67d5'
[ffmpeg] / libavcodec / libopusdec.c
1 /*
2  * Opus decoder using libopus
3  * Copyright (c) 2012 Nicolas George
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg 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  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include <opus.h>
23 #include <opus_multistream.h>
24
25 #include "libavutil/internal.h"
26 #include "libavutil/intreadwrite.h"
27 #include "libavutil/ffmath.h"
28 #include "libavutil/opt.h"
29
30 #include "avcodec.h"
31 #include "internal.h"
32 #include "vorbis.h"
33 #include "mathops.h"
34 #include "libopus.h"
35
36 struct libopus_context {
37     AVClass *class;
38     OpusMSDecoder *dec;
39     int pre_skip;
40 #ifndef OPUS_SET_GAIN
41     union { int i; double d; } gain;
42 #endif
43 #ifdef OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST
44     int apply_phase_inv;
45 #endif
46 };
47
48 #define OPUS_HEAD_SIZE 19
49
50 static av_cold int libopus_decode_init(AVCodecContext *avc)
51 {
52     struct libopus_context *opus = avc->priv_data;
53     int ret, channel_map = 0, gain_db = 0, nb_streams, nb_coupled;
54     uint8_t mapping_arr[8] = { 0, 1 }, *mapping;
55
56     avc->channels = avc->extradata_size >= 10 ? avc->extradata[9] : (avc->channels == 1) ? 1 : 2;
57     if (avc->channels <= 0) {
58         av_log(avc, AV_LOG_WARNING,
59                "Invalid number of channels %d, defaulting to stereo\n", avc->channels);
60         avc->channels = 2;
61     }
62
63     avc->sample_rate    = 48000;
64     avc->sample_fmt     = avc->request_sample_fmt == AV_SAMPLE_FMT_FLT ?
65                           AV_SAMPLE_FMT_FLT : AV_SAMPLE_FMT_S16;
66
67     if (avc->extradata_size >= OPUS_HEAD_SIZE) {
68         opus->pre_skip = AV_RL16(avc->extradata + 10);
69         gain_db     = sign_extend(AV_RL16(avc->extradata + 16), 16);
70         channel_map = AV_RL8 (avc->extradata + 18);
71     }
72     if (avc->extradata_size >= OPUS_HEAD_SIZE + 2 + avc->channels) {
73         nb_streams = avc->extradata[OPUS_HEAD_SIZE + 0];
74         nb_coupled = avc->extradata[OPUS_HEAD_SIZE + 1];
75         if (nb_streams + nb_coupled != avc->channels)
76             av_log(avc, AV_LOG_WARNING, "Inconsistent channel mapping.\n");
77         mapping = avc->extradata + OPUS_HEAD_SIZE + 2;
78     } else {
79         if (avc->channels > 2 || channel_map) {
80             av_log(avc, AV_LOG_ERROR,
81                    "No channel mapping for %d channels.\n", avc->channels);
82             return AVERROR(EINVAL);
83         }
84         nb_streams = 1;
85         nb_coupled = avc->channels > 1;
86         mapping    = mapping_arr;
87     }
88
89     if (channel_map == 1) {
90         avc->channel_layout = avc->channels > 8 ? 0 :
91                               ff_vorbis_channel_layouts[avc->channels - 1];
92         if (avc->channels > 2 && avc->channels <= 8) {
93             const uint8_t *vorbis_offset = ff_vorbis_channel_layout_offsets[avc->channels - 1];
94             int ch;
95
96             /* Remap channels from Vorbis order to ffmpeg order */
97             for (ch = 0; ch < avc->channels; ch++)
98                 mapping_arr[ch] = mapping[vorbis_offset[ch]];
99             mapping = mapping_arr;
100         }
101     } else if (channel_map == 2) {
102         int ambisonic_order = ff_sqrt(avc->channels) - 1;
103         if (avc->channels != (ambisonic_order + 1) * (ambisonic_order + 1) &&
104             avc->channels != (ambisonic_order + 1) * (ambisonic_order + 1) + 2) {
105             av_log(avc, AV_LOG_ERROR,
106                    "Channel mapping 2 is only specified for channel counts"
107                    " which can be written as (n + 1)^2 or (n + 2)^2 + 2"
108                    " for nonnegative integer n\n");
109             return AVERROR_INVALIDDATA;
110         }
111         if (avc->channels > 227) {
112             av_log(avc, AV_LOG_ERROR, "Too many channels\n");
113             return AVERROR_INVALIDDATA;
114         }
115         avc->channel_layout = 0;
116     } else {
117         avc->channel_layout = 0;
118     }
119
120     opus->dec = opus_multistream_decoder_create(avc->sample_rate, avc->channels,
121                                                 nb_streams, nb_coupled,
122                                                 mapping, &ret);
123     if (!opus->dec) {
124         av_log(avc, AV_LOG_ERROR, "Unable to create decoder: %s\n",
125                opus_strerror(ret));
126         return ff_opus_error_to_averror(ret);
127     }
128
129 #ifdef OPUS_SET_GAIN
130     ret = opus_multistream_decoder_ctl(opus->dec, OPUS_SET_GAIN(gain_db));
131     if (ret != OPUS_OK)
132         av_log(avc, AV_LOG_WARNING, "Failed to set gain: %s\n",
133                opus_strerror(ret));
134 #else
135     {
136         double gain_lin = ff_exp10(gain_db / (20.0 * 256));
137         if (avc->sample_fmt == AV_SAMPLE_FMT_FLT)
138             opus->gain.d = gain_lin;
139         else
140             opus->gain.i = FFMIN(gain_lin * 65536, INT_MAX);
141     }
142 #endif
143
144 #ifdef OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST
145     ret = opus_multistream_decoder_ctl(opus->dec,
146                                        OPUS_SET_PHASE_INVERSION_DISABLED(!opus->apply_phase_inv));
147     if (ret != OPUS_OK)
148         av_log(avc, AV_LOG_WARNING,
149                "Unable to set phase inversion: %s\n",
150                opus_strerror(ret));
151 #endif
152
153     /* Decoder delay (in samples) at 48kHz */
154     avc->delay = avc->internal->skip_samples = opus->pre_skip;
155
156     return 0;
157 }
158
159 static av_cold int libopus_decode_close(AVCodecContext *avc)
160 {
161     struct libopus_context *opus = avc->priv_data;
162
163     if (opus->dec) {
164         opus_multistream_decoder_destroy(opus->dec);
165         opus->dec = NULL;
166     }
167     return 0;
168 }
169
170 #define MAX_FRAME_SIZE (960 * 6)
171
172 static int libopus_decode(AVCodecContext *avc, void *data,
173                           int *got_frame_ptr, AVPacket *pkt)
174 {
175     struct libopus_context *opus = avc->priv_data;
176     AVFrame *frame               = data;
177     int ret, nb_samples;
178
179     frame->nb_samples = MAX_FRAME_SIZE;
180     if ((ret = ff_get_buffer(avc, frame, 0)) < 0)
181         return ret;
182
183     if (avc->sample_fmt == AV_SAMPLE_FMT_S16)
184         nb_samples = opus_multistream_decode(opus->dec, pkt->data, pkt->size,
185                                              (opus_int16 *)frame->data[0],
186                                              frame->nb_samples, 0);
187     else
188         nb_samples = opus_multistream_decode_float(opus->dec, pkt->data, pkt->size,
189                                                    (float *)frame->data[0],
190                                                    frame->nb_samples, 0);
191
192     if (nb_samples < 0) {
193         av_log(avc, AV_LOG_ERROR, "Decoding error: %s\n",
194                opus_strerror(nb_samples));
195         return ff_opus_error_to_averror(nb_samples);
196     }
197
198 #ifndef OPUS_SET_GAIN
199     {
200         int i = avc->channels * nb_samples;
201         if (avc->sample_fmt == AV_SAMPLE_FMT_FLT) {
202             float *pcm = (float *)frame->data[0];
203             for (; i > 0; i--, pcm++)
204                 *pcm = av_clipf(*pcm * opus->gain.d, -1, 1);
205         } else {
206             int16_t *pcm = (int16_t *)frame->data[0];
207             for (; i > 0; i--, pcm++)
208                 *pcm = av_clip_int16(((int64_t)opus->gain.i * *pcm) >> 16);
209         }
210     }
211 #endif
212
213     frame->nb_samples = nb_samples;
214     *got_frame_ptr    = 1;
215
216     return pkt->size;
217 }
218
219 static void libopus_flush(AVCodecContext *avc)
220 {
221     struct libopus_context *opus = avc->priv_data;
222
223     opus_multistream_decoder_ctl(opus->dec, OPUS_RESET_STATE);
224     /* The stream can have been extracted by a tool that is not Opus-aware.
225        Therefore, any packet can become the first of the stream. */
226     avc->internal->skip_samples = opus->pre_skip;
227 }
228
229
230 #define OFFSET(x) offsetof(struct libopus_context, x)
231 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
232 static const AVOption libopusdec_options[] = {
233 #ifdef OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST
234     { "apply_phase_inv", "Apply intensity stereo phase inversion", OFFSET(apply_phase_inv), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
235 #endif
236     { NULL },
237 };
238
239 static const AVClass libopusdec_class = {
240     .class_name = "libopusdec",
241     .item_name  = av_default_item_name,
242     .option     = libopusdec_options,
243     .version    = LIBAVUTIL_VERSION_INT,
244 };
245
246
247 AVCodec ff_libopus_decoder = {
248     .name           = "libopus",
249     .long_name      = NULL_IF_CONFIG_SMALL("libopus Opus"),
250     .type           = AVMEDIA_TYPE_AUDIO,
251     .id             = AV_CODEC_ID_OPUS,
252     .priv_data_size = sizeof(struct libopus_context),
253     .init           = libopus_decode_init,
254     .close          = libopus_decode_close,
255     .decode         = libopus_decode,
256     .flush          = libopus_flush,
257     .capabilities   = AV_CODEC_CAP_DR1,
258     .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
259     .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLT,
260                                                      AV_SAMPLE_FMT_S16,
261                                                      AV_SAMPLE_FMT_NONE },
262     .priv_class     = &libopusdec_class,
263     .wrapper_name   = "libopus",
264 };