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"
51 static const uint16_t silk_frame_duration_ms[16] = {
59 /* number of samples of silence to feed to the resampler
61 static const int silk_resample_delay[] = {
65 static const uint8_t celt_band_end[] = { 13, 17, 17, 19, 21 };
67 static int get_silk_samplerate(int config)
79 static int opus_rc_init(OpusRangeCoder *rc, const uint8_t *data, int size)
81 int ret = init_get_bits8(&rc->gb, data, size);
86 rc->value = 127 - get_bits(&rc->gb, 7);
87 rc->total_read_bits = 9;
88 opus_rc_normalize(rc);
93 static void opus_raw_init(OpusRangeCoder *rc, const uint8_t *rightend,
96 rc->rb.position = rightend;
102 static void opus_fade(float *out,
103 const float *in1, const float *in2,
104 const float *window, int len)
107 for (i = 0; i < len; i++)
108 out[i] = in2[i] * window[i] + in1[i] * (1.0 - window[i]);
111 static int opus_flush_resample(OpusStreamContext *s, int nb_samples)
113 int celt_size = av_audio_fifo_size(s->celt_delay);
115 ret = swr_convert(s->swr,
116 (uint8_t**)s->out, nb_samples,
120 else if (ret != nb_samples) {
121 av_log(s->avctx, AV_LOG_ERROR, "Wrong number of flushed samples: %d\n",
127 if (celt_size != nb_samples) {
128 av_log(s->avctx, AV_LOG_ERROR, "Wrong number of CELT delay samples.\n");
131 av_audio_fifo_read(s->celt_delay, (void**)s->celt_output, nb_samples);
132 for (i = 0; i < s->output_channels; i++) {
133 s->fdsp->vector_fmac_scalar(s->out[i],
134 s->celt_output[i], 1.0,
139 if (s->redundancy_idx) {
140 for (i = 0; i < s->output_channels; i++)
141 opus_fade(s->out[i], s->out[i],
142 s->redundancy_output[i] + 120 + s->redundancy_idx,
143 ff_celt_window2 + s->redundancy_idx, 120 - s->redundancy_idx);
144 s->redundancy_idx = 0;
147 s->out[0] += nb_samples;
148 s->out[1] += nb_samples;
149 s->out_size -= nb_samples * sizeof(float);
154 static int opus_init_resample(OpusStreamContext *s)
156 static const float delay[16] = { 0.0 };
157 const uint8_t *delayptr[2] = { (uint8_t*)delay, (uint8_t*)delay };
160 av_opt_set_int(s->swr, "in_sample_rate", s->silk_samplerate, 0);
161 ret = swr_init(s->swr);
163 av_log(s->avctx, AV_LOG_ERROR, "Error opening the resampler.\n");
167 ret = swr_convert(s->swr,
169 delayptr, silk_resample_delay[s->packet.bandwidth]);
171 av_log(s->avctx, AV_LOG_ERROR,
172 "Error feeding initial silence to the resampler.\n");
179 static int opus_decode_redundancy(OpusStreamContext *s, const uint8_t *data, int size)
182 enum OpusBandwidth bw = s->packet.bandwidth;
184 if (s->packet.mode == OPUS_MODE_SILK &&
185 bw == OPUS_BANDWIDTH_MEDIUMBAND)
186 bw = OPUS_BANDWIDTH_WIDEBAND;
188 ret = opus_rc_init(&s->redundancy_rc, data, size);
191 opus_raw_init(&s->redundancy_rc, data + size, size);
193 ret = ff_celt_decode_frame(s->celt, &s->redundancy_rc,
194 s->redundancy_output,
195 s->packet.stereo + 1, 240,
196 0, celt_band_end[s->packet.bandwidth]);
202 av_log(s->avctx, AV_LOG_ERROR, "Error decoding the redundancy frame.\n");
206 static int opus_decode_frame(OpusStreamContext *s, const uint8_t *data, int size)
208 int samples = s->packet.frame_duration;
210 int redundancy_size, redundancy_pos;
211 int ret, i, consumed;
212 int delayed_samples = s->delayed_samples;
214 ret = opus_rc_init(&s->rc, data, size);
218 /* decode the silk frame */
219 if (s->packet.mode == OPUS_MODE_SILK || s->packet.mode == OPUS_MODE_HYBRID) {
220 if (!swr_is_initialized(s->swr)) {
221 ret = opus_init_resample(s);
226 samples = ff_silk_decode_superframe(s->silk, &s->rc, s->silk_output,
227 FFMIN(s->packet.bandwidth, OPUS_BANDWIDTH_WIDEBAND),
228 s->packet.stereo + 1,
229 silk_frame_duration_ms[s->packet.config]);
231 av_log(s->avctx, AV_LOG_ERROR, "Error decoding a SILK frame.\n");
234 samples = swr_convert(s->swr,
235 (uint8_t**)s->out, s->packet.frame_duration,
236 (const uint8_t**)s->silk_output, samples);
238 av_log(s->avctx, AV_LOG_ERROR, "Error resampling SILK data.\n");
241 av_assert2((samples & 7) == 0);
242 s->delayed_samples += s->packet.frame_duration - samples;
244 ff_silk_flush(s->silk);
246 // decode redundancy information
247 consumed = opus_rc_tell(&s->rc);
248 if (s->packet.mode == OPUS_MODE_HYBRID && consumed + 37 <= size * 8)
249 redundancy = opus_rc_p2model(&s->rc, 12);
250 else if (s->packet.mode == OPUS_MODE_SILK && consumed + 17 <= size * 8)
254 redundancy_pos = opus_rc_p2model(&s->rc, 1);
256 if (s->packet.mode == OPUS_MODE_HYBRID)
257 redundancy_size = opus_rc_unimodel(&s->rc, 256) + 2;
259 redundancy_size = size - (consumed + 7) / 8;
260 size -= redundancy_size;
262 av_log(s->avctx, AV_LOG_ERROR, "Invalid redundancy frame size.\n");
263 return AVERROR_INVALIDDATA;
266 if (redundancy_pos) {
267 ret = opus_decode_redundancy(s, data + size, redundancy_size);
270 ff_celt_flush(s->celt);
274 /* decode the CELT frame */
275 if (s->packet.mode == OPUS_MODE_CELT || s->packet.mode == OPUS_MODE_HYBRID) {
276 float *out_tmp[2] = { s->out[0], s->out[1] };
277 float **dst = (s->packet.mode == OPUS_MODE_CELT) ?
278 out_tmp : s->celt_output;
279 int celt_output_samples = samples;
280 int delay_samples = av_audio_fifo_size(s->celt_delay);
283 if (s->packet.mode == OPUS_MODE_HYBRID) {
284 av_audio_fifo_read(s->celt_delay, (void**)s->celt_output, delay_samples);
286 for (i = 0; i < s->output_channels; i++) {
287 s->fdsp->vector_fmac_scalar(out_tmp[i], s->celt_output[i], 1.0,
289 out_tmp[i] += delay_samples;
291 celt_output_samples -= delay_samples;
293 av_log(s->avctx, AV_LOG_WARNING,
294 "Spurious CELT delay samples present.\n");
295 av_audio_fifo_drain(s->celt_delay, delay_samples);
296 if (s->avctx->err_recognition & AV_EF_EXPLODE)
301 opus_raw_init(&s->rc, data + size, size);
303 ret = ff_celt_decode_frame(s->celt, &s->rc, dst,
304 s->packet.stereo + 1,
305 s->packet.frame_duration,
306 (s->packet.mode == OPUS_MODE_HYBRID) ? 17 : 0,
307 celt_band_end[s->packet.bandwidth]);
311 if (s->packet.mode == OPUS_MODE_HYBRID) {
312 int celt_delay = s->packet.frame_duration - celt_output_samples;
313 void *delaybuf[2] = { s->celt_output[0] + celt_output_samples,
314 s->celt_output[1] + celt_output_samples };
316 for (i = 0; i < s->output_channels; i++) {
317 s->fdsp->vector_fmac_scalar(out_tmp[i],
318 s->celt_output[i], 1.0,
319 celt_output_samples);
322 ret = av_audio_fifo_write(s->celt_delay, delaybuf, celt_delay);
327 ff_celt_flush(s->celt);
329 if (s->redundancy_idx) {
330 for (i = 0; i < s->output_channels; i++)
331 opus_fade(s->out[i], s->out[i],
332 s->redundancy_output[i] + 120 + s->redundancy_idx,
333 ff_celt_window2 + s->redundancy_idx, 120 - s->redundancy_idx);
334 s->redundancy_idx = 0;
337 if (!redundancy_pos) {
338 ff_celt_flush(s->celt);
339 ret = opus_decode_redundancy(s, data + size, redundancy_size);
343 for (i = 0; i < s->output_channels; i++) {
344 opus_fade(s->out[i] + samples - 120 + delayed_samples,
345 s->out[i] + samples - 120 + delayed_samples,
346 s->redundancy_output[i] + 120,
347 ff_celt_window2, 120 - delayed_samples);
349 s->redundancy_idx = 120 - delayed_samples;
352 for (i = 0; i < s->output_channels; i++) {
353 memcpy(s->out[i] + delayed_samples, s->redundancy_output[i], 120 * sizeof(float));
354 opus_fade(s->out[i] + 120 + delayed_samples,
355 s->redundancy_output[i] + 120,
356 s->out[i] + 120 + delayed_samples,
357 ff_celt_window2, 120);
365 static int opus_decode_subpacket(OpusStreamContext *s,
366 const uint8_t *buf, int buf_size,
369 int output_samples = 0;
370 int flush_needed = 0;
373 /* check if we need to flush the resampler */
374 if (swr_is_initialized(s->swr)) {
376 int64_t cur_samplerate;
377 av_opt_get_int(s->swr, "in_sample_rate", 0, &cur_samplerate);
378 flush_needed = (s->packet.mode == OPUS_MODE_CELT) || (cur_samplerate != s->silk_samplerate);
380 flush_needed = !!s->delayed_samples;
384 if (!buf && !flush_needed)
387 /* use dummy output buffers if the channel is not mapped to anything */
389 (s->output_channels == 2 && !s->out[1])) {
390 av_fast_malloc(&s->out_dummy, &s->out_dummy_allocated_size, s->out_size);
392 return AVERROR(ENOMEM);
394 s->out[0] = s->out_dummy;
396 s->out[1] = s->out_dummy;
399 /* flush the resampler if necessary */
401 ret = opus_flush_resample(s, s->delayed_samples);
403 av_log(s->avctx, AV_LOG_ERROR, "Error flushing the resampler.\n");
407 output_samples += s->delayed_samples;
408 s->delayed_samples = 0;
414 /* decode all the frames in the packet */
415 for (i = 0; i < s->packet.frame_count; i++) {
416 int size = s->packet.frame_size[i];
417 int samples = opus_decode_frame(s, buf + s->packet.frame_offset[i], size);
420 av_log(s->avctx, AV_LOG_ERROR, "Error decoding an Opus frame.\n");
421 if (s->avctx->err_recognition & AV_EF_EXPLODE)
424 for (j = 0; j < s->output_channels; j++)
425 memset(s->out[j], 0, s->packet.frame_duration * sizeof(float));
426 samples = s->packet.frame_duration;
428 output_samples += samples;
430 for (j = 0; j < s->output_channels; j++)
431 s->out[j] += samples;
432 s->out_size -= samples * sizeof(float);
436 s->out[0] = s->out[1] = NULL;
439 return output_samples;
442 static int opus_decode_packet(AVCodecContext *avctx, void *data,
443 int *got_frame_ptr, AVPacket *avpkt)
445 OpusContext *c = avctx->priv_data;
446 AVFrame *frame = data;
447 const uint8_t *buf = avpkt->data;
448 int buf_size = avpkt->size;
449 int coded_samples = 0;
450 int decoded_samples = 0;
452 int delayed_samples = 0;
454 for (i = 0; i < c->nb_streams; i++) {
455 OpusStreamContext *s = &c->streams[i];
458 delayed_samples = FFMAX(delayed_samples, s->delayed_samples);
461 /* decode the header of the first sub-packet to find out the sample count */
463 OpusPacket *pkt = &c->streams[0].packet;
464 ret = ff_opus_parse_packet(pkt, buf, buf_size, c->nb_streams > 1);
466 av_log(avctx, AV_LOG_ERROR, "Error parsing the packet header.\n");
469 coded_samples += pkt->frame_count * pkt->frame_duration;
470 c->streams[0].silk_samplerate = get_silk_samplerate(pkt->config);
473 frame->nb_samples = coded_samples + delayed_samples;
475 /* no input or buffered data => nothing to do */
476 if (!frame->nb_samples) {
481 /* setup the data buffers */
482 ret = ff_get_buffer(avctx, frame, 0);
485 frame->nb_samples = 0;
487 for (i = 0; i < avctx->channels; i++) {
488 ChannelMap *map = &c->channel_maps[i];
490 c->streams[map->stream_idx].out[map->channel_idx] = (float*)frame->extended_data[i];
493 for (i = 0; i < c->nb_streams; i++)
494 c->streams[i].out_size = frame->linesize[0];
496 /* decode each sub-packet */
497 for (i = 0; i < c->nb_streams; i++) {
498 OpusStreamContext *s = &c->streams[i];
501 ret = ff_opus_parse_packet(&s->packet, buf, buf_size, i != c->nb_streams - 1);
503 av_log(avctx, AV_LOG_ERROR, "Error parsing the packet header.\n");
506 if (coded_samples != s->packet.frame_count * s->packet.frame_duration) {
507 av_log(avctx, AV_LOG_ERROR,
508 "Mismatching coded sample count in substream %d.\n", i);
509 return AVERROR_INVALIDDATA;
512 s->silk_samplerate = get_silk_samplerate(s->packet.config);
515 ret = opus_decode_subpacket(&c->streams[i], buf,
516 s->packet.data_size, coded_samples);
519 if (decoded_samples && ret != decoded_samples) {
520 av_log(avctx, AV_LOG_ERROR, "Different numbers of decoded samples "
521 "in a multi-channel stream\n");
522 return AVERROR_INVALIDDATA;
524 decoded_samples = ret;
525 buf += s->packet.packet_size;
526 buf_size -= s->packet.packet_size;
529 for (i = 0; i < avctx->channels; i++) {
530 ChannelMap *map = &c->channel_maps[i];
532 /* handle copied channels */
534 memcpy(frame->extended_data[i],
535 frame->extended_data[map->copy_idx],
537 } else if (map->silence) {
538 memset(frame->extended_data[i], 0, frame->linesize[0]);
542 c->fdsp->vector_fmul_scalar((float*)frame->extended_data[i],
543 (float*)frame->extended_data[i],
544 c->gain, FFALIGN(decoded_samples, 8));
548 frame->nb_samples = decoded_samples;
549 *got_frame_ptr = !!decoded_samples;
554 static av_cold void opus_decode_flush(AVCodecContext *ctx)
556 OpusContext *c = ctx->priv_data;
559 for (i = 0; i < c->nb_streams; i++) {
560 OpusStreamContext *s = &c->streams[i];
562 memset(&s->packet, 0, sizeof(s->packet));
563 s->delayed_samples = 0;
566 av_audio_fifo_drain(s->celt_delay, av_audio_fifo_size(s->celt_delay));
569 ff_silk_flush(s->silk);
570 ff_celt_flush(s->celt);
574 static av_cold int opus_decode_close(AVCodecContext *avctx)
576 OpusContext *c = avctx->priv_data;
579 for (i = 0; i < c->nb_streams; i++) {
580 OpusStreamContext *s = &c->streams[i];
582 ff_silk_free(&s->silk);
583 ff_celt_free(&s->celt);
585 av_freep(&s->out_dummy);
586 s->out_dummy_allocated_size = 0;
588 av_audio_fifo_free(s->celt_delay);
592 av_freep(&c->streams);
595 av_freep(&c->channel_maps);
601 static av_cold int opus_decode_init(AVCodecContext *avctx)
603 OpusContext *c = avctx->priv_data;
606 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
607 avctx->sample_rate = 48000;
609 c->fdsp = avpriv_float_dsp_alloc(0);
611 return AVERROR(ENOMEM);
613 /* find out the channel configuration */
614 ret = ff_opus_parse_extradata(avctx, c);
618 /* allocate and init each independent decoder */
619 c->streams = av_mallocz_array(c->nb_streams, sizeof(*c->streams));
622 ret = AVERROR(ENOMEM);
626 for (i = 0; i < c->nb_streams; i++) {
627 OpusStreamContext *s = &c->streams[i];
630 s->output_channels = (i < c->nb_stereo_streams) ? 2 : 1;
634 for (j = 0; j < s->output_channels; j++) {
635 s->silk_output[j] = s->silk_buf[j];
636 s->celt_output[j] = s->celt_buf[j];
637 s->redundancy_output[j] = s->redundancy_buf[j];
646 layout = (s->output_channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
647 av_opt_set_int(s->swr, "in_sample_fmt", avctx->sample_fmt, 0);
648 av_opt_set_int(s->swr, "out_sample_fmt", avctx->sample_fmt, 0);
649 av_opt_set_int(s->swr, "in_channel_layout", layout, 0);
650 av_opt_set_int(s->swr, "out_channel_layout", layout, 0);
651 av_opt_set_int(s->swr, "out_sample_rate", avctx->sample_rate, 0);
652 av_opt_set_int(s->swr, "filter_size", 16, 0);
654 ret = ff_silk_init(avctx, &s->silk, s->output_channels);
658 ret = ff_celt_init(avctx, &s->celt, s->output_channels);
662 s->celt_delay = av_audio_fifo_alloc(avctx->sample_fmt,
663 s->output_channels, 1024);
664 if (!s->celt_delay) {
665 ret = AVERROR(ENOMEM);
672 opus_decode_close(avctx);
676 AVCodec ff_opus_decoder = {
678 .long_name = NULL_IF_CONFIG_SMALL("Opus"),
679 .type = AVMEDIA_TYPE_AUDIO,
680 .id = AV_CODEC_ID_OPUS,
681 .priv_data_size = sizeof(OpusContext),
682 .init = opus_decode_init,
683 .close = opus_decode_close,
684 .decode = opus_decode_packet,
685 .flush = opus_decode_flush,
686 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY,