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"
52 static const uint16_t silk_frame_duration_ms[16] = {
60 /* number of samples of silence to feed to the resampler
62 static const int silk_resample_delay[] = {
66 static const uint8_t celt_band_end[] = { 13, 17, 17, 19, 21 };
68 static int get_silk_samplerate(int config)
77 static void opus_fade(float *out,
78 const float *in1, const float *in2,
79 const float *window, int len)
82 for (i = 0; i < len; i++)
83 out[i] = in2[i] * window[i] + in1[i] * (1.0 - window[i]);
86 static int opus_flush_resample(OpusStreamContext *s, int nb_samples)
88 int celt_size = av_audio_fifo_size(s->celt_delay);
90 ret = swr_convert(s->swr,
91 (uint8_t**)s->out, nb_samples,
95 else if (ret != nb_samples) {
96 av_log(s->avctx, AV_LOG_ERROR, "Wrong number of flushed samples: %d\n",
102 if (celt_size != nb_samples) {
103 av_log(s->avctx, AV_LOG_ERROR, "Wrong number of CELT delay samples.\n");
106 av_audio_fifo_read(s->celt_delay, (void**)s->celt_output, nb_samples);
107 for (i = 0; i < s->output_channels; i++) {
108 s->fdsp->vector_fmac_scalar(s->out[i],
109 s->celt_output[i], 1.0,
114 if (s->redundancy_idx) {
115 for (i = 0; i < s->output_channels; i++)
116 opus_fade(s->out[i], s->out[i],
117 s->redundancy_output[i] + 120 + s->redundancy_idx,
118 ff_celt_window2 + s->redundancy_idx, 120 - s->redundancy_idx);
119 s->redundancy_idx = 0;
122 s->out[0] += nb_samples;
123 s->out[1] += nb_samples;
124 s->out_size -= nb_samples * sizeof(float);
129 static int opus_init_resample(OpusStreamContext *s)
131 static const float delay[16] = { 0.0 };
132 const uint8_t *delayptr[2] = { (uint8_t*)delay, (uint8_t*)delay };
135 av_opt_set_int(s->swr, "in_sample_rate", s->silk_samplerate, 0);
136 ret = swr_init(s->swr);
138 av_log(s->avctx, AV_LOG_ERROR, "Error opening the resampler.\n");
142 ret = swr_convert(s->swr,
144 delayptr, silk_resample_delay[s->packet.bandwidth]);
146 av_log(s->avctx, AV_LOG_ERROR,
147 "Error feeding initial silence to the resampler.\n");
154 static int opus_decode_redundancy(OpusStreamContext *s, const uint8_t *data, int size)
157 enum OpusBandwidth bw = s->packet.bandwidth;
159 if (s->packet.mode == OPUS_MODE_SILK &&
160 bw == OPUS_BANDWIDTH_MEDIUMBAND)
161 bw = OPUS_BANDWIDTH_WIDEBAND;
163 ret = ff_opus_rc_dec_init(&s->redundancy_rc, data, size);
166 ff_opus_rc_dec_raw_init(&s->redundancy_rc, data + size, size);
168 ret = ff_celt_decode_frame(s->celt, &s->redundancy_rc,
169 s->redundancy_output,
170 s->packet.stereo + 1, 240,
171 0, celt_band_end[s->packet.bandwidth]);
177 av_log(s->avctx, AV_LOG_ERROR, "Error decoding the redundancy frame.\n");
181 static int opus_decode_frame(OpusStreamContext *s, const uint8_t *data, int size)
183 int samples = s->packet.frame_duration;
185 int redundancy_size, redundancy_pos;
186 int ret, i, consumed;
187 int delayed_samples = s->delayed_samples;
189 ret = ff_opus_rc_dec_init(&s->rc, data, size);
193 /* decode the silk frame */
194 if (s->packet.mode == OPUS_MODE_SILK || s->packet.mode == OPUS_MODE_HYBRID) {
195 if (!swr_is_initialized(s->swr)) {
196 ret = opus_init_resample(s);
201 samples = ff_silk_decode_superframe(s->silk, &s->rc, s->silk_output,
202 FFMIN(s->packet.bandwidth, OPUS_BANDWIDTH_WIDEBAND),
203 s->packet.stereo + 1,
204 silk_frame_duration_ms[s->packet.config]);
206 av_log(s->avctx, AV_LOG_ERROR, "Error decoding a SILK frame.\n");
209 samples = swr_convert(s->swr,
210 (uint8_t**)s->out, s->packet.frame_duration,
211 (const uint8_t**)s->silk_output, samples);
213 av_log(s->avctx, AV_LOG_ERROR, "Error resampling SILK data.\n");
216 av_assert2((samples & 7) == 0);
217 s->delayed_samples += s->packet.frame_duration - samples;
219 ff_silk_flush(s->silk);
221 // decode redundancy information
222 consumed = opus_rc_tell(&s->rc);
223 if (s->packet.mode == OPUS_MODE_HYBRID && consumed + 37 <= size * 8)
224 redundancy = ff_opus_rc_dec_log(&s->rc, 12);
225 else if (s->packet.mode == OPUS_MODE_SILK && consumed + 17 <= size * 8)
229 redundancy_pos = ff_opus_rc_dec_log(&s->rc, 1);
231 if (s->packet.mode == OPUS_MODE_HYBRID)
232 redundancy_size = ff_opus_rc_dec_uint(&s->rc, 256) + 2;
234 redundancy_size = size - (consumed + 7) / 8;
235 size -= redundancy_size;
237 av_log(s->avctx, AV_LOG_ERROR, "Invalid redundancy frame size.\n");
238 return AVERROR_INVALIDDATA;
241 if (redundancy_pos) {
242 ret = opus_decode_redundancy(s, data + size, redundancy_size);
245 ff_celt_flush(s->celt);
249 /* decode the CELT frame */
250 if (s->packet.mode == OPUS_MODE_CELT || s->packet.mode == OPUS_MODE_HYBRID) {
251 float *out_tmp[2] = { s->out[0], s->out[1] };
252 float **dst = (s->packet.mode == OPUS_MODE_CELT) ?
253 out_tmp : s->celt_output;
254 int celt_output_samples = samples;
255 int delay_samples = av_audio_fifo_size(s->celt_delay);
258 if (s->packet.mode == OPUS_MODE_HYBRID) {
259 av_audio_fifo_read(s->celt_delay, (void**)s->celt_output, delay_samples);
261 for (i = 0; i < s->output_channels; i++) {
262 s->fdsp->vector_fmac_scalar(out_tmp[i], s->celt_output[i], 1.0,
264 out_tmp[i] += delay_samples;
266 celt_output_samples -= delay_samples;
268 av_log(s->avctx, AV_LOG_WARNING,
269 "Spurious CELT delay samples present.\n");
270 av_audio_fifo_drain(s->celt_delay, delay_samples);
271 if (s->avctx->err_recognition & AV_EF_EXPLODE)
276 ff_opus_rc_dec_raw_init(&s->rc, data + size, size);
278 ret = ff_celt_decode_frame(s->celt, &s->rc, dst,
279 s->packet.stereo + 1,
280 s->packet.frame_duration,
281 (s->packet.mode == OPUS_MODE_HYBRID) ? 17 : 0,
282 celt_band_end[s->packet.bandwidth]);
286 if (s->packet.mode == OPUS_MODE_HYBRID) {
287 int celt_delay = s->packet.frame_duration - celt_output_samples;
288 void *delaybuf[2] = { s->celt_output[0] + celt_output_samples,
289 s->celt_output[1] + celt_output_samples };
291 for (i = 0; i < s->output_channels; i++) {
292 s->fdsp->vector_fmac_scalar(out_tmp[i],
293 s->celt_output[i], 1.0,
294 celt_output_samples);
297 ret = av_audio_fifo_write(s->celt_delay, delaybuf, celt_delay);
302 ff_celt_flush(s->celt);
304 if (s->redundancy_idx) {
305 for (i = 0; i < s->output_channels; i++)
306 opus_fade(s->out[i], s->out[i],
307 s->redundancy_output[i] + 120 + s->redundancy_idx,
308 ff_celt_window2 + s->redundancy_idx, 120 - s->redundancy_idx);
309 s->redundancy_idx = 0;
312 if (!redundancy_pos) {
313 ff_celt_flush(s->celt);
314 ret = opus_decode_redundancy(s, data + size, redundancy_size);
318 for (i = 0; i < s->output_channels; i++) {
319 opus_fade(s->out[i] + samples - 120 + delayed_samples,
320 s->out[i] + samples - 120 + delayed_samples,
321 s->redundancy_output[i] + 120,
322 ff_celt_window2, 120 - delayed_samples);
324 s->redundancy_idx = 120 - delayed_samples;
327 for (i = 0; i < s->output_channels; i++) {
328 memcpy(s->out[i] + delayed_samples, s->redundancy_output[i], 120 * sizeof(float));
329 opus_fade(s->out[i] + 120 + delayed_samples,
330 s->redundancy_output[i] + 120,
331 s->out[i] + 120 + delayed_samples,
332 ff_celt_window2, 120);
340 static int opus_decode_subpacket(OpusStreamContext *s,
341 const uint8_t *buf, int buf_size,
342 float **out, int out_size,
345 int output_samples = 0;
346 int flush_needed = 0;
351 s->out_size = out_size;
353 /* check if we need to flush the resampler */
354 if (swr_is_initialized(s->swr)) {
356 int64_t cur_samplerate;
357 av_opt_get_int(s->swr, "in_sample_rate", 0, &cur_samplerate);
358 flush_needed = (s->packet.mode == OPUS_MODE_CELT) || (cur_samplerate != s->silk_samplerate);
360 flush_needed = !!s->delayed_samples;
364 if (!buf && !flush_needed)
367 /* use dummy output buffers if the channel is not mapped to anything */
369 (s->output_channels == 2 && !s->out[1])) {
370 av_fast_malloc(&s->out_dummy, &s->out_dummy_allocated_size, s->out_size);
372 return AVERROR(ENOMEM);
374 s->out[0] = s->out_dummy;
376 s->out[1] = s->out_dummy;
379 /* flush the resampler if necessary */
381 ret = opus_flush_resample(s, s->delayed_samples);
383 av_log(s->avctx, AV_LOG_ERROR, "Error flushing the resampler.\n");
387 output_samples += s->delayed_samples;
388 s->delayed_samples = 0;
394 /* decode all the frames in the packet */
395 for (i = 0; i < s->packet.frame_count; i++) {
396 int size = s->packet.frame_size[i];
397 int samples = opus_decode_frame(s, buf + s->packet.frame_offset[i], size);
400 av_log(s->avctx, AV_LOG_ERROR, "Error decoding an Opus frame.\n");
401 if (s->avctx->err_recognition & AV_EF_EXPLODE)
404 for (j = 0; j < s->output_channels; j++)
405 memset(s->out[j], 0, s->packet.frame_duration * sizeof(float));
406 samples = s->packet.frame_duration;
408 output_samples += samples;
410 for (j = 0; j < s->output_channels; j++)
411 s->out[j] += samples;
412 s->out_size -= samples * sizeof(float);
416 s->out[0] = s->out[1] = NULL;
419 return output_samples;
422 static int opus_decode_packet(AVCodecContext *avctx, void *data,
423 int *got_frame_ptr, AVPacket *avpkt)
425 OpusContext *c = avctx->priv_data;
426 AVFrame *frame = data;
427 const uint8_t *buf = avpkt->data;
428 int buf_size = avpkt->size;
429 int coded_samples = 0;
430 int decoded_samples = INT_MAX;
431 int delayed_samples = 0;
434 /* calculate the number of delayed samples */
435 for (i = 0; i < c->nb_streams; i++) {
436 OpusStreamContext *s = &c->streams[i];
439 delayed_samples = FFMAX(delayed_samples,
440 s->delayed_samples + av_audio_fifo_size(c->sync_buffers[i]));
443 /* decode the header of the first sub-packet to find out the sample count */
445 OpusPacket *pkt = &c->streams[0].packet;
446 ret = ff_opus_parse_packet(pkt, buf, buf_size, c->nb_streams > 1);
448 av_log(avctx, AV_LOG_ERROR, "Error parsing the packet header.\n");
451 coded_samples += pkt->frame_count * pkt->frame_duration;
452 c->streams[0].silk_samplerate = get_silk_samplerate(pkt->config);
455 frame->nb_samples = coded_samples + delayed_samples;
457 /* no input or buffered data => nothing to do */
458 if (!frame->nb_samples) {
463 /* setup the data buffers */
464 ret = ff_get_buffer(avctx, frame, 0);
467 frame->nb_samples = 0;
469 memset(c->out, 0, c->nb_streams * 2 * sizeof(*c->out));
470 for (i = 0; i < avctx->channels; i++) {
471 ChannelMap *map = &c->channel_maps[i];
473 c->out[2 * map->stream_idx + map->channel_idx] = (float*)frame->extended_data[i];
476 /* read the data from the sync buffers */
477 for (i = 0; i < c->nb_streams; i++) {
478 float **out = c->out + 2 * i;
479 int sync_size = av_audio_fifo_size(c->sync_buffers[i]);
481 float sync_dummy[32];
482 int out_dummy = (!out[0]) | ((!out[1]) << 1);
488 if (out_dummy && sync_size > FF_ARRAY_ELEMS(sync_dummy))
491 ret = av_audio_fifo_read(c->sync_buffers[i], (void**)out, sync_size);
504 c->out_size[i] = frame->linesize[0] - ret * sizeof(float);
507 /* decode each sub-packet */
508 for (i = 0; i < c->nb_streams; i++) {
509 OpusStreamContext *s = &c->streams[i];
512 ret = ff_opus_parse_packet(&s->packet, buf, buf_size, i != c->nb_streams - 1);
514 av_log(avctx, AV_LOG_ERROR, "Error parsing the packet header.\n");
517 if (coded_samples != s->packet.frame_count * s->packet.frame_duration) {
518 av_log(avctx, AV_LOG_ERROR,
519 "Mismatching coded sample count in substream %d.\n", i);
520 return AVERROR_INVALIDDATA;
523 s->silk_samplerate = get_silk_samplerate(s->packet.config);
526 ret = opus_decode_subpacket(&c->streams[i], buf, s->packet.data_size,
527 c->out + 2 * i, c->out_size[i], coded_samples);
530 c->decoded_samples[i] = ret;
531 decoded_samples = FFMIN(decoded_samples, ret);
533 buf += s->packet.packet_size;
534 buf_size -= s->packet.packet_size;
537 /* buffer the extra samples */
538 for (i = 0; i < c->nb_streams; i++) {
539 int buffer_samples = c->decoded_samples[i] - decoded_samples;
540 if (buffer_samples) {
541 float *buf[2] = { c->out[2 * i + 0] ? c->out[2 * i + 0] : (float*)frame->extended_data[0],
542 c->out[2 * i + 1] ? c->out[2 * i + 1] : (float*)frame->extended_data[0] };
543 buf[0] += decoded_samples;
544 buf[1] += decoded_samples;
545 ret = av_audio_fifo_write(c->sync_buffers[i], (void**)buf, buffer_samples);
551 for (i = 0; i < avctx->channels; i++) {
552 ChannelMap *map = &c->channel_maps[i];
554 /* handle copied channels */
556 memcpy(frame->extended_data[i],
557 frame->extended_data[map->copy_idx],
559 } else if (map->silence) {
560 memset(frame->extended_data[i], 0, frame->linesize[0]);
563 if (c->gain_i && decoded_samples > 0) {
564 c->fdsp->vector_fmul_scalar((float*)frame->extended_data[i],
565 (float*)frame->extended_data[i],
566 c->gain, FFALIGN(decoded_samples, 8));
570 frame->nb_samples = decoded_samples;
571 *got_frame_ptr = !!decoded_samples;
576 static av_cold void opus_decode_flush(AVCodecContext *ctx)
578 OpusContext *c = ctx->priv_data;
581 for (i = 0; i < c->nb_streams; i++) {
582 OpusStreamContext *s = &c->streams[i];
584 memset(&s->packet, 0, sizeof(s->packet));
585 s->delayed_samples = 0;
588 av_audio_fifo_drain(s->celt_delay, av_audio_fifo_size(s->celt_delay));
591 av_audio_fifo_drain(c->sync_buffers[i], av_audio_fifo_size(c->sync_buffers[i]));
593 ff_silk_flush(s->silk);
594 ff_celt_flush(s->celt);
598 static av_cold int opus_decode_close(AVCodecContext *avctx)
600 OpusContext *c = avctx->priv_data;
603 for (i = 0; i < c->nb_streams; i++) {
604 OpusStreamContext *s = &c->streams[i];
606 ff_silk_free(&s->silk);
607 ff_celt_free(&s->celt);
609 av_freep(&s->out_dummy);
610 s->out_dummy_allocated_size = 0;
612 av_audio_fifo_free(s->celt_delay);
616 av_freep(&c->streams);
618 if (c->sync_buffers) {
619 for (i = 0; i < c->nb_streams; i++)
620 av_audio_fifo_free(c->sync_buffers[i]);
622 av_freep(&c->sync_buffers);
623 av_freep(&c->decoded_samples);
625 av_freep(&c->out_size);
629 av_freep(&c->channel_maps);
635 static av_cold int opus_decode_init(AVCodecContext *avctx)
637 OpusContext *c = avctx->priv_data;
640 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
641 avctx->sample_rate = 48000;
643 c->fdsp = avpriv_float_dsp_alloc(0);
645 return AVERROR(ENOMEM);
647 /* find out the channel configuration */
648 ret = ff_opus_parse_extradata(avctx, c);
654 /* allocate and init each independent decoder */
655 c->streams = av_mallocz_array(c->nb_streams, sizeof(*c->streams));
656 c->out = av_mallocz_array(c->nb_streams, 2 * sizeof(*c->out));
657 c->out_size = av_mallocz_array(c->nb_streams, sizeof(*c->out_size));
658 c->sync_buffers = av_mallocz_array(c->nb_streams, sizeof(*c->sync_buffers));
659 c->decoded_samples = av_mallocz_array(c->nb_streams, sizeof(*c->decoded_samples));
660 if (!c->streams || !c->sync_buffers || !c->decoded_samples || !c->out || !c->out_size) {
662 ret = AVERROR(ENOMEM);
666 for (i = 0; i < c->nb_streams; i++) {
667 OpusStreamContext *s = &c->streams[i];
670 s->output_channels = (i < c->nb_stereo_streams) ? 2 : 1;
674 for (j = 0; j < s->output_channels; j++) {
675 s->silk_output[j] = s->silk_buf[j];
676 s->celt_output[j] = s->celt_buf[j];
677 s->redundancy_output[j] = s->redundancy_buf[j];
686 layout = (s->output_channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
687 av_opt_set_int(s->swr, "in_sample_fmt", avctx->sample_fmt, 0);
688 av_opt_set_int(s->swr, "out_sample_fmt", avctx->sample_fmt, 0);
689 av_opt_set_int(s->swr, "in_channel_layout", layout, 0);
690 av_opt_set_int(s->swr, "out_channel_layout", layout, 0);
691 av_opt_set_int(s->swr, "out_sample_rate", avctx->sample_rate, 0);
692 av_opt_set_int(s->swr, "filter_size", 16, 0);
694 ret = ff_silk_init(avctx, &s->silk, s->output_channels);
698 ret = ff_celt_init(avctx, &s->celt, s->output_channels);
702 s->celt_delay = av_audio_fifo_alloc(avctx->sample_fmt,
703 s->output_channels, 1024);
704 if (!s->celt_delay) {
705 ret = AVERROR(ENOMEM);
709 c->sync_buffers[i] = av_audio_fifo_alloc(avctx->sample_fmt,
710 s->output_channels, 32);
711 if (!c->sync_buffers[i]) {
712 ret = AVERROR(ENOMEM);
719 opus_decode_close(avctx);
723 AVCodec ff_opus_decoder = {
725 .long_name = NULL_IF_CONFIG_SMALL("Opus"),
726 .type = AVMEDIA_TYPE_AUDIO,
727 .id = AV_CODEC_ID_OPUS,
728 .priv_data_size = sizeof(OpusContext),
729 .init = opus_decode_init,
730 .close = opus_decode_close,
731 .decode = opus_decode_packet,
732 .flush = opus_decode_flush,
733 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY,