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 #include "opus_celt.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 int get_silk_samplerate(int config)
76 static void opus_fade(float *out,
77 const float *in1, const float *in2,
78 const float *window, int len)
81 for (i = 0; i < len; i++)
82 out[i] = in2[i] * window[i] + in1[i] * (1.0 - window[i]);
85 static int opus_flush_resample(OpusStreamContext *s, int nb_samples)
87 int celt_size = av_audio_fifo_size(s->celt_delay);
89 ret = swr_convert(s->swr,
90 (uint8_t**)s->cur_out, nb_samples,
94 else if (ret != nb_samples) {
95 av_log(s->avctx, AV_LOG_ERROR, "Wrong number of flushed samples: %d\n",
101 if (celt_size != nb_samples) {
102 av_log(s->avctx, AV_LOG_ERROR, "Wrong number of CELT delay samples.\n");
105 av_audio_fifo_read(s->celt_delay, (void**)s->celt_output, nb_samples);
106 for (i = 0; i < s->output_channels; i++) {
107 s->fdsp->vector_fmac_scalar(s->cur_out[i],
108 s->celt_output[i], 1.0,
113 if (s->redundancy_idx) {
114 for (i = 0; i < s->output_channels; i++)
115 opus_fade(s->cur_out[i], s->cur_out[i],
116 s->redundancy_output[i] + 120 + s->redundancy_idx,
117 ff_celt_window2 + s->redundancy_idx, 120 - s->redundancy_idx);
118 s->redundancy_idx = 0;
121 s->cur_out[0] += nb_samples;
122 s->cur_out[1] += nb_samples;
123 s->remaining_out_size -= nb_samples * sizeof(float);
128 static int opus_init_resample(OpusStreamContext *s)
130 static const float delay[16] = { 0.0 };
131 const uint8_t *delayptr[2] = { (uint8_t*)delay, (uint8_t*)delay };
134 av_opt_set_int(s->swr, "in_sample_rate", s->silk_samplerate, 0);
135 ret = swr_init(s->swr);
137 av_log(s->avctx, AV_LOG_ERROR, "Error opening the resampler.\n");
141 ret = swr_convert(s->swr,
143 delayptr, silk_resample_delay[s->packet.bandwidth]);
145 av_log(s->avctx, AV_LOG_ERROR,
146 "Error feeding initial silence to the resampler.\n");
153 static int opus_decode_redundancy(OpusStreamContext *s, const uint8_t *data, int size)
155 int ret = ff_opus_rc_dec_init(&s->redundancy_rc, data, size);
158 ff_opus_rc_dec_raw_init(&s->redundancy_rc, data + size, size);
160 ret = ff_celt_decode_frame(s->celt, &s->redundancy_rc,
161 s->redundancy_output,
162 s->packet.stereo + 1, 240,
163 0, ff_celt_band_end[s->packet.bandwidth]);
169 av_log(s->avctx, AV_LOG_ERROR, "Error decoding the redundancy frame.\n");
173 static int opus_decode_frame(OpusStreamContext *s, const uint8_t *data, int size)
175 int samples = s->packet.frame_duration;
177 int redundancy_size, redundancy_pos;
178 int ret, i, consumed;
179 int delayed_samples = s->delayed_samples;
181 ret = ff_opus_rc_dec_init(&s->rc, data, size);
185 /* decode the silk frame */
186 if (s->packet.mode == OPUS_MODE_SILK || s->packet.mode == OPUS_MODE_HYBRID) {
187 if (!swr_is_initialized(s->swr)) {
188 ret = opus_init_resample(s);
193 samples = ff_silk_decode_superframe(s->silk, &s->rc, s->silk_output,
194 FFMIN(s->packet.bandwidth, OPUS_BANDWIDTH_WIDEBAND),
195 s->packet.stereo + 1,
196 silk_frame_duration_ms[s->packet.config]);
198 av_log(s->avctx, AV_LOG_ERROR, "Error decoding a SILK frame.\n");
201 samples = swr_convert(s->swr,
202 (uint8_t**)s->cur_out, s->packet.frame_duration,
203 (const uint8_t**)s->silk_output, samples);
205 av_log(s->avctx, AV_LOG_ERROR, "Error resampling SILK data.\n");
208 av_assert2((samples & 7) == 0);
209 s->delayed_samples += s->packet.frame_duration - samples;
211 ff_silk_flush(s->silk);
213 // decode redundancy information
214 consumed = opus_rc_tell(&s->rc);
215 if (s->packet.mode == OPUS_MODE_HYBRID && consumed + 37 <= size * 8)
216 redundancy = ff_opus_rc_dec_log(&s->rc, 12);
217 else if (s->packet.mode == OPUS_MODE_SILK && consumed + 17 <= size * 8)
221 redundancy_pos = ff_opus_rc_dec_log(&s->rc, 1);
223 if (s->packet.mode == OPUS_MODE_HYBRID)
224 redundancy_size = ff_opus_rc_dec_uint(&s->rc, 256) + 2;
226 redundancy_size = size - (consumed + 7) / 8;
227 size -= redundancy_size;
229 av_log(s->avctx, AV_LOG_ERROR, "Invalid redundancy frame size.\n");
230 return AVERROR_INVALIDDATA;
233 if (redundancy_pos) {
234 ret = opus_decode_redundancy(s, data + size, redundancy_size);
237 ff_celt_flush(s->celt);
241 /* decode the CELT frame */
242 if (s->packet.mode == OPUS_MODE_CELT || s->packet.mode == OPUS_MODE_HYBRID) {
243 float *out_tmp[2] = { s->cur_out[0], s->cur_out[1] };
244 float **dst = (s->packet.mode == OPUS_MODE_CELT) ?
245 out_tmp : s->celt_output;
246 int celt_output_samples = samples;
247 int delay_samples = av_audio_fifo_size(s->celt_delay);
250 if (s->packet.mode == OPUS_MODE_HYBRID) {
251 av_audio_fifo_read(s->celt_delay, (void**)s->celt_output, delay_samples);
253 for (i = 0; i < s->output_channels; i++) {
254 s->fdsp->vector_fmac_scalar(out_tmp[i], s->celt_output[i], 1.0,
256 out_tmp[i] += delay_samples;
258 celt_output_samples -= delay_samples;
260 av_log(s->avctx, AV_LOG_WARNING,
261 "Spurious CELT delay samples present.\n");
262 av_audio_fifo_drain(s->celt_delay, delay_samples);
263 if (s->avctx->err_recognition & AV_EF_EXPLODE)
268 ff_opus_rc_dec_raw_init(&s->rc, data + size, size);
270 ret = ff_celt_decode_frame(s->celt, &s->rc, dst,
271 s->packet.stereo + 1,
272 s->packet.frame_duration,
273 (s->packet.mode == OPUS_MODE_HYBRID) ? 17 : 0,
274 ff_celt_band_end[s->packet.bandwidth]);
278 if (s->packet.mode == OPUS_MODE_HYBRID) {
279 int celt_delay = s->packet.frame_duration - celt_output_samples;
280 void *delaybuf[2] = { s->celt_output[0] + celt_output_samples,
281 s->celt_output[1] + celt_output_samples };
283 for (i = 0; i < s->output_channels; i++) {
284 s->fdsp->vector_fmac_scalar(out_tmp[i],
285 s->celt_output[i], 1.0,
286 celt_output_samples);
289 ret = av_audio_fifo_write(s->celt_delay, delaybuf, celt_delay);
294 ff_celt_flush(s->celt);
296 if (s->redundancy_idx) {
297 for (i = 0; i < s->output_channels; i++)
298 opus_fade(s->cur_out[i], s->cur_out[i],
299 s->redundancy_output[i] + 120 + s->redundancy_idx,
300 ff_celt_window2 + s->redundancy_idx, 120 - s->redundancy_idx);
301 s->redundancy_idx = 0;
304 if (!redundancy_pos) {
305 ff_celt_flush(s->celt);
306 ret = opus_decode_redundancy(s, data + size, redundancy_size);
310 for (i = 0; i < s->output_channels; i++) {
311 opus_fade(s->cur_out[i] + samples - 120 + delayed_samples,
312 s->cur_out[i] + samples - 120 + delayed_samples,
313 s->redundancy_output[i] + 120,
314 ff_celt_window2, 120 - delayed_samples);
316 s->redundancy_idx = 120 - delayed_samples;
319 for (i = 0; i < s->output_channels; i++) {
320 memcpy(s->cur_out[i] + delayed_samples, s->redundancy_output[i], 120 * sizeof(float));
321 opus_fade(s->cur_out[i] + 120 + delayed_samples,
322 s->redundancy_output[i] + 120,
323 s->cur_out[i] + 120 + delayed_samples,
324 ff_celt_window2, 120);
332 static int opus_decode_subpacket(OpusStreamContext *s,
333 const uint8_t *buf, int buf_size,
336 int output_samples = 0;
337 int flush_needed = 0;
340 s->cur_out[0] = s->out[0];
341 s->cur_out[1] = s->out[1];
342 s->remaining_out_size = s->out_size;
344 /* check if we need to flush the resampler */
345 if (swr_is_initialized(s->swr)) {
347 int64_t cur_samplerate;
348 av_opt_get_int(s->swr, "in_sample_rate", 0, &cur_samplerate);
349 flush_needed = (s->packet.mode == OPUS_MODE_CELT) || (cur_samplerate != s->silk_samplerate);
351 flush_needed = !!s->delayed_samples;
355 if (!buf && !flush_needed)
358 /* use dummy output buffers if the channel is not mapped to anything */
359 if (!s->cur_out[0] ||
360 (s->output_channels == 2 && !s->cur_out[1])) {
361 av_fast_malloc(&s->out_dummy, &s->out_dummy_allocated_size,
362 s->remaining_out_size);
364 return AVERROR(ENOMEM);
366 s->cur_out[0] = s->out_dummy;
368 s->cur_out[1] = s->out_dummy;
371 /* flush the resampler if necessary */
373 ret = opus_flush_resample(s, s->delayed_samples);
375 av_log(s->avctx, AV_LOG_ERROR, "Error flushing the resampler.\n");
379 output_samples += s->delayed_samples;
380 s->delayed_samples = 0;
386 /* decode all the frames in the packet */
387 for (i = 0; i < s->packet.frame_count; i++) {
388 int size = s->packet.frame_size[i];
389 int samples = opus_decode_frame(s, buf + s->packet.frame_offset[i], size);
392 av_log(s->avctx, AV_LOG_ERROR, "Error decoding an Opus frame.\n");
393 if (s->avctx->err_recognition & AV_EF_EXPLODE)
396 for (j = 0; j < s->output_channels; j++)
397 memset(s->cur_out[j], 0, s->packet.frame_duration * sizeof(float));
398 samples = s->packet.frame_duration;
400 output_samples += samples;
402 for (j = 0; j < s->output_channels; j++)
403 s->cur_out[j] += samples;
404 s->remaining_out_size -= samples * sizeof(float);
408 s->cur_out[0] = s->cur_out[1] = NULL;
409 s->remaining_out_size = 0;
411 return output_samples;
414 static int opus_decode_packet(AVCodecContext *avctx, void *data,
415 int *got_frame_ptr, AVPacket *avpkt)
417 OpusContext *c = avctx->priv_data;
418 AVFrame *frame = data;
419 const uint8_t *buf = avpkt->data;
420 int buf_size = avpkt->size;
421 int coded_samples = 0;
422 int decoded_samples = INT_MAX;
423 int delayed_samples = 0;
426 /* calculate the number of delayed samples */
427 for (i = 0; i < c->nb_streams; i++) {
428 OpusStreamContext *s = &c->streams[i];
431 delayed_samples = FFMAX(delayed_samples,
432 s->delayed_samples + av_audio_fifo_size(s->sync_buffer));
435 /* decode the header of the first sub-packet to find out the sample count */
437 OpusPacket *pkt = &c->streams[0].packet;
438 ret = ff_opus_parse_packet(pkt, buf, buf_size, c->nb_streams > 1);
440 av_log(avctx, AV_LOG_ERROR, "Error parsing the packet header.\n");
443 coded_samples += pkt->frame_count * pkt->frame_duration;
444 c->streams[0].silk_samplerate = get_silk_samplerate(pkt->config);
447 frame->nb_samples = coded_samples + delayed_samples;
449 /* no input or buffered data => nothing to do */
450 if (!frame->nb_samples) {
455 /* setup the data buffers */
456 ret = ff_get_buffer(avctx, frame, 0);
459 frame->nb_samples = 0;
461 for (i = 0; i < avctx->channels; i++) {
462 ChannelMap *map = &c->channel_maps[i];
464 c->streams[map->stream_idx].out[map->channel_idx] = (float*)frame->extended_data[i];
467 /* read the data from the sync buffers */
468 for (i = 0; i < c->nb_streams; i++) {
469 OpusStreamContext *s = &c->streams[i];
470 float **out = s->out;
471 int sync_size = av_audio_fifo_size(s->sync_buffer);
473 float sync_dummy[32];
474 int out_dummy = (!out[0]) | ((!out[1]) << 1);
480 if (out_dummy && sync_size > FF_ARRAY_ELEMS(sync_dummy))
483 ret = av_audio_fifo_read(s->sync_buffer, (void**)out, sync_size);
496 s->out_size = frame->linesize[0] - ret * sizeof(float);
499 /* decode each sub-packet */
500 for (i = 0; i < c->nb_streams; i++) {
501 OpusStreamContext *s = &c->streams[i];
504 ret = ff_opus_parse_packet(&s->packet, buf, buf_size, i != c->nb_streams - 1);
506 av_log(avctx, AV_LOG_ERROR, "Error parsing the packet header.\n");
509 if (coded_samples != s->packet.frame_count * s->packet.frame_duration) {
510 av_log(avctx, AV_LOG_ERROR,
511 "Mismatching coded sample count in substream %d.\n", i);
512 return AVERROR_INVALIDDATA;
515 s->silk_samplerate = get_silk_samplerate(s->packet.config);
518 ret = opus_decode_subpacket(&c->streams[i], buf, s->packet.data_size,
522 s->decoded_samples = ret;
523 decoded_samples = FFMIN(decoded_samples, ret);
525 buf += s->packet.packet_size;
526 buf_size -= s->packet.packet_size;
529 /* buffer the extra samples */
530 for (i = 0; i < c->nb_streams; i++) {
531 OpusStreamContext *s = &c->streams[i];
532 int buffer_samples = s->decoded_samples - decoded_samples;
533 if (buffer_samples) {
534 float *buf[2] = { s->out[0] ? s->out[0] : (float*)frame->extended_data[0],
535 s->out[1] ? s->out[1] : (float*)frame->extended_data[0] };
536 buf[0] += decoded_samples;
537 buf[1] += decoded_samples;
538 ret = av_audio_fifo_write(s->sync_buffer, (void**)buf, buffer_samples);
544 for (i = 0; i < avctx->channels; i++) {
545 ChannelMap *map = &c->channel_maps[i];
547 /* handle copied channels */
549 memcpy(frame->extended_data[i],
550 frame->extended_data[map->copy_idx],
552 } else if (map->silence) {
553 memset(frame->extended_data[i], 0, frame->linesize[0]);
556 if (c->gain_i && decoded_samples > 0) {
557 c->fdsp->vector_fmul_scalar((float*)frame->extended_data[i],
558 (float*)frame->extended_data[i],
559 c->gain, FFALIGN(decoded_samples, 8));
563 frame->nb_samples = decoded_samples;
564 *got_frame_ptr = !!decoded_samples;
569 static av_cold void opus_decode_flush(AVCodecContext *ctx)
571 OpusContext *c = ctx->priv_data;
574 for (i = 0; i < c->nb_streams; i++) {
575 OpusStreamContext *s = &c->streams[i];
577 memset(&s->packet, 0, sizeof(s->packet));
578 s->delayed_samples = 0;
580 av_audio_fifo_drain(s->celt_delay, av_audio_fifo_size(s->celt_delay));
583 av_audio_fifo_drain(s->sync_buffer, av_audio_fifo_size(s->sync_buffer));
585 ff_silk_flush(s->silk);
586 ff_celt_flush(s->celt);
590 static av_cold int opus_decode_close(AVCodecContext *avctx)
592 OpusContext *c = avctx->priv_data;
595 for (i = 0; i < c->nb_streams; i++) {
596 OpusStreamContext *s = &c->streams[i];
598 ff_silk_free(&s->silk);
599 ff_celt_free(&s->celt);
601 av_freep(&s->out_dummy);
602 s->out_dummy_allocated_size = 0;
604 av_audio_fifo_free(s->sync_buffer);
605 av_audio_fifo_free(s->celt_delay);
609 av_freep(&c->streams);
613 av_freep(&c->channel_maps);
619 static av_cold int opus_decode_init(AVCodecContext *avctx)
621 OpusContext *c = avctx->priv_data;
624 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
625 avctx->sample_rate = 48000;
627 c->fdsp = avpriv_float_dsp_alloc(0);
629 return AVERROR(ENOMEM);
631 /* find out the channel configuration */
632 ret = ff_opus_parse_extradata(avctx, c);
636 /* allocate and init each independent decoder */
637 c->streams = av_mallocz_array(c->nb_streams, sizeof(*c->streams));
640 return AVERROR(ENOMEM);
643 for (i = 0; i < c->nb_streams; i++) {
644 OpusStreamContext *s = &c->streams[i];
647 s->output_channels = (i < c->nb_stereo_streams) ? 2 : 1;
651 for (j = 0; j < s->output_channels; j++) {
652 s->silk_output[j] = s->silk_buf[j];
653 s->celt_output[j] = s->celt_buf[j];
654 s->redundancy_output[j] = s->redundancy_buf[j];
661 return AVERROR(ENOMEM);
663 layout = (s->output_channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
664 av_opt_set_int(s->swr, "in_sample_fmt", avctx->sample_fmt, 0);
665 av_opt_set_int(s->swr, "out_sample_fmt", avctx->sample_fmt, 0);
666 av_opt_set_int(s->swr, "in_channel_layout", layout, 0);
667 av_opt_set_int(s->swr, "out_channel_layout", layout, 0);
668 av_opt_set_int(s->swr, "out_sample_rate", avctx->sample_rate, 0);
669 av_opt_set_int(s->swr, "filter_size", 16, 0);
671 ret = ff_silk_init(avctx, &s->silk, s->output_channels);
675 ret = ff_celt_init(avctx, &s->celt, s->output_channels, c->apply_phase_inv);
679 s->celt_delay = av_audio_fifo_alloc(avctx->sample_fmt,
680 s->output_channels, 1024);
682 return AVERROR(ENOMEM);
684 s->sync_buffer = av_audio_fifo_alloc(avctx->sample_fmt,
685 s->output_channels, 32);
687 return AVERROR(ENOMEM);
693 #define OFFSET(x) offsetof(OpusContext, x)
694 #define AD AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
695 static const AVOption opus_options[] = {
696 { "apply_phase_inv", "Apply intensity stereo phase inversion", OFFSET(apply_phase_inv), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, AD },
700 static const AVClass opus_class = {
701 .class_name = "Opus Decoder",
702 .item_name = av_default_item_name,
703 .option = opus_options,
704 .version = LIBAVUTIL_VERSION_INT,
707 AVCodec ff_opus_decoder = {
709 .long_name = NULL_IF_CONFIG_SMALL("Opus"),
710 .priv_class = &opus_class,
711 .type = AVMEDIA_TYPE_AUDIO,
712 .id = AV_CODEC_ID_OPUS,
713 .priv_data_size = sizeof(OpusContext),
714 .init = opus_decode_init,
715 .close = opus_decode_close,
716 .decode = opus_decode_packet,
717 .flush = opus_decode_flush,
718 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_CHANNEL_CONF,
719 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,