3 * Copyright (c) 2012 Andrew D'Addesio
4 * Copyright (c) 2013-2014 Mozilla Corporation
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 * @author Andrew D'Addesio, Anton Khirnov
28 * Codec homepage: http://opus-codec.org/
29 * Specification: http://tools.ietf.org/html/rfc6716
30 * Ogg Opus specification: https://tools.ietf.org/html/draft-ietf-codec-oggopus-03
32 * Ogg-contained .opus files can be produced with opus-tools:
33 * http://git.xiph.org/?p=opus-tools.git
38 #include "libavutil/attributes.h"
39 #include "libavutil/audio_fifo.h"
40 #include "libavutil/channel_layout.h"
41 #include "libavutil/opt.h"
43 #include "libswresample/swresample.h"
46 #include "celp_filters.h"
53 static const uint16_t silk_frame_duration_ms[16] = {
61 /* number of samples of silence to feed to the resampler
63 static const int silk_resample_delay[] = {
67 static const uint8_t celt_band_end[] = { 13, 17, 17, 19, 21 };
69 static int get_silk_samplerate(int config)
81 static int opus_rc_init(OpusRangeCoder *rc, const uint8_t *data, int size)
83 int ret = init_get_bits8(&rc->gb, data, size);
88 rc->value = 127 - get_bits(&rc->gb, 7);
89 rc->total_read_bits = 9;
90 opus_rc_normalize(rc);
95 static void opus_raw_init(OpusRangeCoder *rc, const uint8_t *rightend,
98 rc->rb.position = rightend;
104 static void opus_fade(float *out,
105 const float *in1, const float *in2,
106 const float *window, int len)
109 for (i = 0; i < len; i++)
110 out[i] = in2[i] * window[i] + in1[i] * (1.0 - window[i]);
113 static int opus_flush_resample(OpusStreamContext *s, int nb_samples)
115 int celt_size = av_audio_fifo_size(s->celt_delay);
117 ret = swr_convert(s->swr,
118 (uint8_t**)s->out, nb_samples,
122 else if (ret != nb_samples) {
123 av_log(s->avctx, AV_LOG_ERROR, "Wrong number of flushed samples: %d\n",
129 if (celt_size != nb_samples) {
130 av_log(s->avctx, AV_LOG_ERROR, "Wrong number of CELT delay samples.\n");
133 av_audio_fifo_read(s->celt_delay, (void**)s->celt_output, nb_samples);
134 for (i = 0; i < s->output_channels; i++) {
135 s->fdsp->vector_fmac_scalar(s->out[i],
136 s->celt_output[i], 1.0,
141 if (s->redundancy_idx) {
142 for (i = 0; i < s->output_channels; i++)
143 opus_fade(s->out[i], s->out[i],
144 s->redundancy_output[i] + 120 + s->redundancy_idx,
145 ff_celt_window2 + s->redundancy_idx, 120 - s->redundancy_idx);
146 s->redundancy_idx = 0;
149 s->out[0] += nb_samples;
150 s->out[1] += nb_samples;
151 s->out_size -= nb_samples * sizeof(float);
156 static int opus_init_resample(OpusStreamContext *s)
158 static const float delay[16] = { 0.0 };
159 const uint8_t *delayptr[2] = { (uint8_t*)delay, (uint8_t*)delay };
162 av_opt_set_int(s->swr, "in_sample_rate", s->silk_samplerate, 0);
163 ret = swr_init(s->swr);
165 av_log(s->avctx, AV_LOG_ERROR, "Error opening the resampler.\n");
169 ret = swr_convert(s->swr,
171 delayptr, silk_resample_delay[s->packet.bandwidth]);
173 av_log(s->avctx, AV_LOG_ERROR,
174 "Error feeding initial silence to the resampler.\n");
181 static int opus_decode_redundancy(OpusStreamContext *s, const uint8_t *data, int size)
184 enum OpusBandwidth bw = s->packet.bandwidth;
186 if (s->packet.mode == OPUS_MODE_SILK &&
187 bw == OPUS_BANDWIDTH_MEDIUMBAND)
188 bw = OPUS_BANDWIDTH_WIDEBAND;
190 ret = opus_rc_init(&s->redundancy_rc, data, size);
193 opus_raw_init(&s->redundancy_rc, data + size, size);
195 ret = ff_celt_decode_frame(s->celt, &s->redundancy_rc,
196 s->redundancy_output,
197 s->packet.stereo + 1, 240,
198 0, celt_band_end[s->packet.bandwidth]);
204 av_log(s->avctx, AV_LOG_ERROR, "Error decoding the redundancy frame.\n");
208 static int opus_decode_frame(OpusStreamContext *s, const uint8_t *data, int size)
210 int samples = s->packet.frame_duration;
212 int redundancy_size, redundancy_pos;
213 int ret, i, consumed;
214 int delayed_samples = s->delayed_samples;
216 ret = opus_rc_init(&s->rc, data, size);
220 /* decode the silk frame */
221 if (s->packet.mode == OPUS_MODE_SILK || s->packet.mode == OPUS_MODE_HYBRID) {
222 if (!swr_is_initialized(s->swr)) {
223 ret = opus_init_resample(s);
228 samples = ff_silk_decode_superframe(s->silk, &s->rc, s->silk_output,
229 FFMIN(s->packet.bandwidth, OPUS_BANDWIDTH_WIDEBAND),
230 s->packet.stereo + 1,
231 silk_frame_duration_ms[s->packet.config]);
233 av_log(s->avctx, AV_LOG_ERROR, "Error decoding a SILK frame.\n");
236 samples = swr_convert(s->swr,
237 (uint8_t**)s->out, s->packet.frame_duration,
238 (const uint8_t**)s->silk_output, samples);
240 av_log(s->avctx, AV_LOG_ERROR, "Error resampling SILK data.\n");
243 s->delayed_samples += s->packet.frame_duration - samples;
245 ff_silk_flush(s->silk);
247 // decode redundancy information
248 consumed = opus_rc_tell(&s->rc);
249 if (s->packet.mode == OPUS_MODE_HYBRID && consumed + 37 <= size * 8)
250 redundancy = opus_rc_p2model(&s->rc, 12);
251 else if (s->packet.mode == OPUS_MODE_SILK && consumed + 17 <= size * 8)
255 redundancy_pos = opus_rc_p2model(&s->rc, 1);
257 if (s->packet.mode == OPUS_MODE_HYBRID)
258 redundancy_size = opus_rc_unimodel(&s->rc, 256) + 2;
260 redundancy_size = size - (consumed + 7) / 8;
261 size -= redundancy_size;
263 av_log(s->avctx, AV_LOG_ERROR, "Invalid redundancy frame size.\n");
264 return AVERROR_INVALIDDATA;
267 if (redundancy_pos) {
268 ret = opus_decode_redundancy(s, data + size, redundancy_size);
271 ff_celt_flush(s->celt);
275 /* decode the CELT frame */
276 if (s->packet.mode == OPUS_MODE_CELT || s->packet.mode == OPUS_MODE_HYBRID) {
277 float *out_tmp[2] = { s->out[0], s->out[1] };
278 float **dst = (s->packet.mode == OPUS_MODE_CELT) ?
279 out_tmp : s->celt_output;
280 int celt_output_samples = samples;
281 int delay_samples = av_audio_fifo_size(s->celt_delay);
284 if (s->packet.mode == OPUS_MODE_HYBRID) {
285 av_audio_fifo_read(s->celt_delay, (void**)s->celt_output, delay_samples);
287 for (i = 0; i < s->output_channels; i++) {
288 s->fdsp->vector_fmac_scalar(out_tmp[i], s->celt_output[i], 1.0,
290 out_tmp[i] += delay_samples;
292 celt_output_samples -= delay_samples;
294 av_log(s->avctx, AV_LOG_WARNING,
295 "Spurious CELT delay samples present.\n");
296 av_audio_fifo_drain(s->celt_delay, delay_samples);
297 if (s->avctx->err_recognition & AV_EF_EXPLODE)
302 opus_raw_init(&s->rc, data + size, size);
304 ret = ff_celt_decode_frame(s->celt, &s->rc, dst,
305 s->packet.stereo + 1,
306 s->packet.frame_duration,
307 (s->packet.mode == OPUS_MODE_HYBRID) ? 17 : 0,
308 celt_band_end[s->packet.bandwidth]);
312 if (s->packet.mode == OPUS_MODE_HYBRID) {
313 int celt_delay = s->packet.frame_duration - celt_output_samples;
314 void *delaybuf[2] = { s->celt_output[0] + celt_output_samples,
315 s->celt_output[1] + celt_output_samples };
317 for (i = 0; i < s->output_channels; i++) {
318 s->fdsp->vector_fmac_scalar(out_tmp[i],
319 s->celt_output[i], 1.0,
320 celt_output_samples);
323 ret = av_audio_fifo_write(s->celt_delay, delaybuf, celt_delay);
328 ff_celt_flush(s->celt);
330 if (s->redundancy_idx) {
331 for (i = 0; i < s->output_channels; i++)
332 opus_fade(s->out[i], s->out[i],
333 s->redundancy_output[i] + 120 + s->redundancy_idx,
334 ff_celt_window2 + s->redundancy_idx, 120 - s->redundancy_idx);
335 s->redundancy_idx = 0;
338 if (!redundancy_pos) {
339 ff_celt_flush(s->celt);
340 ret = opus_decode_redundancy(s, data + size, redundancy_size);
344 for (i = 0; i < s->output_channels; i++) {
345 opus_fade(s->out[i] + samples - 120 + delayed_samples,
346 s->out[i] + samples - 120 + delayed_samples,
347 s->redundancy_output[i] + 120,
348 ff_celt_window2, 120 - delayed_samples);
350 s->redundancy_idx = 120 - delayed_samples;
353 for (i = 0; i < s->output_channels; i++) {
354 memcpy(s->out[i] + delayed_samples, s->redundancy_output[i], 120 * sizeof(float));
355 opus_fade(s->out[i] + 120 + delayed_samples,
356 s->redundancy_output[i] + 120,
357 s->out[i] + 120 + delayed_samples,
358 ff_celt_window2, 120);
366 static int opus_decode_subpacket(OpusStreamContext *s,
367 const uint8_t *buf, int buf_size,
370 int output_samples = 0;
371 int flush_needed = 0;
374 /* check if we need to flush the resampler */
375 if (swr_is_initialized(s->swr)) {
377 int64_t cur_samplerate;
378 av_opt_get_int(s->swr, "in_sample_rate", 0, &cur_samplerate);
379 flush_needed = (s->packet.mode == OPUS_MODE_CELT) || (cur_samplerate != s->silk_samplerate);
381 flush_needed = !!s->delayed_samples;
385 if (!buf && !flush_needed)
388 /* use dummy output buffers if the channel is not mapped to anything */
390 (s->output_channels == 2 && !s->out[1])) {
391 av_fast_malloc(&s->out_dummy, &s->out_dummy_allocated_size, s->out_size);
393 return AVERROR(ENOMEM);
395 s->out[0] = s->out_dummy;
397 s->out[1] = s->out_dummy;
400 /* flush the resampler if necessary */
402 ret = opus_flush_resample(s, s->delayed_samples);
404 av_log(s->avctx, AV_LOG_ERROR, "Error flushing the resampler.\n");
408 output_samples += s->delayed_samples;
409 s->delayed_samples = 0;
415 /* decode all the frames in the packet */
416 for (i = 0; i < s->packet.frame_count; i++) {
417 int size = s->packet.frame_size[i];
418 int samples = opus_decode_frame(s, buf + s->packet.frame_offset[i], size);
421 av_log(s->avctx, AV_LOG_ERROR, "Error decoding an Opus frame.\n");
422 if (s->avctx->err_recognition & AV_EF_EXPLODE)
425 for (j = 0; j < s->output_channels; j++)
426 memset(s->out[j], 0, s->packet.frame_duration * sizeof(float));
427 samples = s->packet.frame_duration;
429 output_samples += samples;
431 for (j = 0; j < s->output_channels; j++)
432 s->out[j] += samples;
433 s->out_size -= samples * sizeof(float);
437 s->out[0] = s->out[1] = NULL;
440 return output_samples;
443 static int opus_decode_packet(AVCodecContext *avctx, void *data,
444 int *got_frame_ptr, AVPacket *avpkt)
446 OpusContext *c = avctx->priv_data;
447 AVFrame *frame = data;
448 const uint8_t *buf = avpkt->data;
449 int buf_size = avpkt->size;
450 int coded_samples = 0;
451 int decoded_samples = 0;
454 /* decode the header of the first sub-packet to find out the sample count */
456 OpusPacket *pkt = &c->streams[0].packet;
457 ret = ff_opus_parse_packet(pkt, buf, buf_size, c->nb_streams > 1);
459 av_log(avctx, AV_LOG_ERROR, "Error parsing the packet header.\n");
462 coded_samples += pkt->frame_count * pkt->frame_duration;
463 c->streams[0].silk_samplerate = get_silk_samplerate(pkt->config);
466 frame->nb_samples = coded_samples + c->streams[0].delayed_samples;
468 /* no input or buffered data => nothing to do */
469 if (!frame->nb_samples) {
474 /* setup the data buffers */
475 ret = ff_get_buffer(avctx, frame, 0);
477 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
480 frame->nb_samples = 0;
482 for (i = 0; i < avctx->channels; i++) {
483 ChannelMap *map = &c->channel_maps[i];
485 c->streams[map->stream_idx].out[map->channel_idx] = (float*)frame->extended_data[i];
488 for (i = 0; i < c->nb_streams; i++)
489 c->streams[i].out_size = frame->linesize[0];
491 /* decode each sub-packet */
492 for (i = 0; i < c->nb_streams; i++) {
493 OpusStreamContext *s = &c->streams[i];
496 ret = ff_opus_parse_packet(&s->packet, buf, buf_size, i != c->nb_streams - 1);
498 av_log(avctx, AV_LOG_ERROR, "Error parsing the packet header.\n");
501 s->silk_samplerate = get_silk_samplerate(s->packet.config);
504 ret = opus_decode_subpacket(&c->streams[i], buf,
505 s->packet.data_size, coded_samples);
508 if (decoded_samples && ret != decoded_samples) {
509 av_log(avctx, AV_LOG_ERROR, "Different numbers of decoded samples "
510 "in a multi-channel stream\n");
511 return AVERROR_INVALIDDATA;
513 decoded_samples = ret;
514 buf += s->packet.packet_size;
515 buf_size -= s->packet.packet_size;
518 for (i = 0; i < avctx->channels; i++) {
519 ChannelMap *map = &c->channel_maps[i];
521 /* handle copied channels */
523 memcpy(frame->extended_data[i],
524 frame->extended_data[map->copy_idx],
526 } else if (map->silence) {
527 memset(frame->extended_data[i], 0, frame->linesize[0]);
531 c->fdsp.vector_fmul_scalar((float*)frame->extended_data[i],
532 (float*)frame->extended_data[i],
533 c->gain, FFALIGN(decoded_samples, 8));
537 frame->nb_samples = decoded_samples;
538 *got_frame_ptr = !!decoded_samples;
543 static av_cold void opus_decode_flush(AVCodecContext *ctx)
545 OpusContext *c = ctx->priv_data;
548 for (i = 0; i < c->nb_streams; i++) {
549 OpusStreamContext *s = &c->streams[i];
551 memset(&s->packet, 0, sizeof(s->packet));
552 s->delayed_samples = 0;
555 av_audio_fifo_drain(s->celt_delay, av_audio_fifo_size(s->celt_delay));
558 ff_silk_flush(s->silk);
559 ff_celt_flush(s->celt);
563 static av_cold int opus_decode_close(AVCodecContext *avctx)
565 OpusContext *c = avctx->priv_data;
568 for (i = 0; i < c->nb_streams; i++) {
569 OpusStreamContext *s = &c->streams[i];
571 ff_silk_free(&s->silk);
572 ff_celt_free(&s->celt);
574 av_freep(&s->out_dummy);
575 s->out_dummy_allocated_size = 0;
577 av_audio_fifo_free(s->celt_delay);
581 av_freep(&c->streams);
584 av_freep(&c->channel_maps);
589 static av_cold int opus_decode_init(AVCodecContext *avctx)
591 OpusContext *c = avctx->priv_data;
594 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
595 avctx->sample_rate = 48000;
597 avpriv_float_dsp_init(&c->fdsp, 0);
599 /* find out the channel configuration */
600 ret = ff_opus_parse_extradata(avctx, c);
604 /* allocate and init each independent decoder */
605 c->streams = av_mallocz_array(c->nb_streams, sizeof(*c->streams));
608 ret = AVERROR(ENOMEM);
612 for (i = 0; i < c->nb_streams; i++) {
613 OpusStreamContext *s = &c->streams[i];
616 s->output_channels = (i < c->nb_stereo_streams) ? 2 : 1;
620 for (j = 0; j < s->output_channels; j++) {
621 s->silk_output[j] = s->silk_buf[j];
622 s->celt_output[j] = s->celt_buf[j];
623 s->redundancy_output[j] = s->redundancy_buf[j];
632 layout = (s->output_channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
633 av_opt_set_int(s->swr, "in_sample_fmt", avctx->sample_fmt, 0);
634 av_opt_set_int(s->swr, "out_sample_fmt", avctx->sample_fmt, 0);
635 av_opt_set_int(s->swr, "in_channel_layout", layout, 0);
636 av_opt_set_int(s->swr, "out_channel_layout", layout, 0);
637 av_opt_set_int(s->swr, "out_sample_rate", avctx->sample_rate, 0);
638 av_opt_set_int(s->swr, "filter_size", 16, 0);
640 ret = ff_silk_init(avctx, &s->silk, s->output_channels);
644 ret = ff_celt_init(avctx, &s->celt, s->output_channels);
648 s->celt_delay = av_audio_fifo_alloc(avctx->sample_fmt,
649 s->output_channels, 1024);
650 if (!s->celt_delay) {
651 ret = AVERROR(ENOMEM);
658 opus_decode_close(avctx);
662 AVCodec ff_opus_decoder = {
664 .long_name = NULL_IF_CONFIG_SMALL("Opus"),
665 .type = AVMEDIA_TYPE_AUDIO,
666 .id = AV_CODEC_ID_OPUS,
667 .priv_data_size = sizeof(OpusContext),
668 .init = opus_decode_init,
669 .close = opus_decode_close,
670 .decode = opus_decode_packet,
671 .flush = opus_decode_flush,
672 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY,