2 * Opus encoder using libopus
3 * Copyright (c) 2012 Nathan Caldwell
5 * This file is part of FFmpeg.
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.
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.
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
23 #include <opus_multistream.h>
25 #include "libavutil/opt.h"
27 #include "bytestream.h"
31 #include "audio_frame_queue.h"
33 typedef struct LibopusEncOpts {
42 #ifdef OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST
47 typedef struct LibopusEncContext {
54 const uint8_t *encoder_channel_map;
57 static const uint8_t opus_coupled_streams[8] = {
58 0, 1, 1, 2, 2, 2, 2, 3
61 /* Opus internal to Vorbis channel order mapping written in the header */
62 static const uint8_t opus_vorbis_channel_map[8][8] = {
69 { 0, 4, 1, 2, 3, 5, 6 },
70 { 0, 6, 1, 2, 3, 4, 5, 7 },
73 /* libavcodec to libopus channel order mapping, passed to libopus */
74 static const uint8_t libavcodec_libopus_channel_map[8][8] = {
81 { 0, 1, 5, 6, 2, 4, 3 },
82 { 0, 1, 6, 7, 4, 5, 2, 3 },
85 static void libopus_write_header(AVCodecContext *avctx, int stream_count,
86 int coupled_stream_count,
88 const uint8_t *channel_mapping)
90 uint8_t *p = avctx->extradata;
91 int channels = avctx->channels;
93 bytestream_put_buffer(&p, "OpusHead", 8);
94 bytestream_put_byte(&p, 1); /* Version */
95 bytestream_put_byte(&p, channels);
96 bytestream_put_le16(&p, avctx->initial_padding); /* Lookahead samples at 48kHz */
97 bytestream_put_le32(&p, avctx->sample_rate); /* Original sample rate */
98 bytestream_put_le16(&p, 0); /* Gain of 0dB is recommended. */
100 /* Channel mapping */
101 bytestream_put_byte(&p, mapping_family);
102 if (mapping_family != 0) {
103 bytestream_put_byte(&p, stream_count);
104 bytestream_put_byte(&p, coupled_stream_count);
105 bytestream_put_buffer(&p, channel_mapping, channels);
109 static int libopus_configure_encoder(AVCodecContext *avctx, OpusMSEncoder *enc,
110 LibopusEncOpts *opts)
114 if (avctx->global_quality) {
115 av_log(avctx, AV_LOG_ERROR,
116 "Quality-based encoding not supported, "
117 "please specify a bitrate and VBR setting.\n");
118 return AVERROR(EINVAL);
121 ret = opus_multistream_encoder_ctl(enc, OPUS_SET_BITRATE(avctx->bit_rate));
122 if (ret != OPUS_OK) {
123 av_log(avctx, AV_LOG_ERROR,
124 "Failed to set bitrate: %s\n", opus_strerror(ret));
128 ret = opus_multistream_encoder_ctl(enc,
129 OPUS_SET_COMPLEXITY(opts->complexity));
131 av_log(avctx, AV_LOG_WARNING,
132 "Unable to set complexity: %s\n", opus_strerror(ret));
134 ret = opus_multistream_encoder_ctl(enc, OPUS_SET_VBR(!!opts->vbr));
136 av_log(avctx, AV_LOG_WARNING,
137 "Unable to set VBR: %s\n", opus_strerror(ret));
139 ret = opus_multistream_encoder_ctl(enc,
140 OPUS_SET_VBR_CONSTRAINT(opts->vbr == 2));
142 av_log(avctx, AV_LOG_WARNING,
143 "Unable to set constrained VBR: %s\n", opus_strerror(ret));
145 ret = opus_multistream_encoder_ctl(enc,
146 OPUS_SET_PACKET_LOSS_PERC(opts->packet_loss));
148 av_log(avctx, AV_LOG_WARNING,
149 "Unable to set expected packet loss percentage: %s\n",
153 ret = opus_multistream_encoder_ctl(enc,
154 OPUS_SET_MAX_BANDWIDTH(opts->max_bandwidth));
156 av_log(avctx, AV_LOG_WARNING,
157 "Unable to set maximum bandwidth: %s\n", opus_strerror(ret));
160 #ifdef OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST
161 ret = opus_multistream_encoder_ctl(enc,
162 OPUS_SET_PHASE_INVERSION_DISABLED(!opts->apply_phase_inv));
164 av_log(avctx, AV_LOG_WARNING,
165 "Unable to set phase inversion: %s\n",
171 static int libopus_check_max_channels(AVCodecContext *avctx,
173 if (avctx->channels > max_channels) {
174 av_log(avctx, AV_LOG_ERROR, "Opus mapping family undefined for %d channels.\n",
176 return AVERROR(EINVAL);
182 static int libopus_check_vorbis_layout(AVCodecContext *avctx, int mapping_family) {
183 av_assert2(avctx->channels < FF_ARRAY_ELEMS(ff_vorbis_channel_layouts));
185 if (!avctx->channel_layout) {
186 av_log(avctx, AV_LOG_WARNING,
187 "No channel layout specified. Opus encoder will use Vorbis "
188 "channel layout for %d channels.\n", avctx->channels);
189 } else if (avctx->channel_layout != ff_vorbis_channel_layouts[avctx->channels - 1]) {
191 av_get_channel_layout_string(name, sizeof(name), avctx->channels,
192 avctx->channel_layout);
193 av_log(avctx, AV_LOG_ERROR,
194 "Invalid channel layout %s for specified mapping family %d.\n",
195 name, mapping_family);
197 return AVERROR(EINVAL);
203 static int libopus_validate_layout_and_get_channel_map(
204 AVCodecContext *avctx,
206 const uint8_t ** channel_map_result)
208 const uint8_t * channel_map = NULL;
211 switch (mapping_family) {
213 ret = libopus_check_max_channels(avctx, 8);
215 ret = libopus_check_vorbis_layout(avctx, mapping_family);
216 /* Channels do not need to be reordered. */
221 ret = libopus_check_max_channels(avctx, 2);
223 ret = libopus_check_vorbis_layout(avctx, mapping_family);
227 /* Opus expects channels to be in Vorbis order. */
228 ret = libopus_check_max_channels(avctx, 8);
230 ret = libopus_check_vorbis_layout(avctx, mapping_family);
231 channel_map = ff_vorbis_channel_layout_offsets[avctx->channels - 1];
235 ret = libopus_check_max_channels(avctx, 254);
238 av_log(avctx, AV_LOG_WARNING,
239 "Unknown channel mapping family %d. Output channel layout may be invalid.\n",
244 *channel_map_result = channel_map;
248 static av_cold int libopus_encode_init(AVCodecContext *avctx)
250 LibopusEncContext *opus = avctx->priv_data;
252 uint8_t libopus_channel_mapping[255];
255 int coupled_stream_count, header_size, frame_size;
258 frame_size = opus->opts.frame_duration * 48000 / 1000;
259 switch (frame_size) {
262 if (opus->opts.application != OPUS_APPLICATION_RESTRICTED_LOWDELAY)
263 av_log(avctx, AV_LOG_WARNING,
264 "LPC mode cannot be used with a frame duration of less "
265 "than 10ms. Enabling restricted low-delay mode.\n"
266 "Use a longer frame duration if this is not what you want.\n");
267 /* Frame sizes less than 10 ms can only use MDCT mode, so switching to
268 * RESTRICTED_LOWDELAY avoids an unnecessary extra 2.5ms lookahead. */
269 opus->opts.application = OPUS_APPLICATION_RESTRICTED_LOWDELAY;
274 #ifdef OPUS_FRAMESIZE_120_MS
279 opus->opts.packet_size =
280 avctx->frame_size = frame_size * avctx->sample_rate / 48000;
283 av_log(avctx, AV_LOG_ERROR, "Invalid frame duration: %g.\n"
284 "Frame duration must be exactly one of: 2.5, 5, 10, 20, 40"
285 #ifdef OPUS_FRAMESIZE_120_MS
286 ", 60, 80, 100 or 120.\n",
290 opus->opts.frame_duration);
291 return AVERROR(EINVAL);
294 if (avctx->compression_level < 0 || avctx->compression_level > 10) {
295 av_log(avctx, AV_LOG_WARNING,
296 "Compression level must be in the range 0 to 10. "
297 "Defaulting to 10.\n");
298 opus->opts.complexity = 10;
300 opus->opts.complexity = avctx->compression_level;
304 switch (avctx->cutoff) {
306 opus->opts.max_bandwidth = OPUS_BANDWIDTH_NARROWBAND;
309 opus->opts.max_bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
312 opus->opts.max_bandwidth = OPUS_BANDWIDTH_WIDEBAND;
315 opus->opts.max_bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND;
318 opus->opts.max_bandwidth = OPUS_BANDWIDTH_FULLBAND;
321 av_log(avctx, AV_LOG_WARNING,
322 "Invalid frequency cutoff: %d. Using default maximum bandwidth.\n"
323 "Cutoff frequency must be exactly one of: 4000, 6000, 8000, 12000 or 20000.\n",
329 /* Channels may need to be reordered to match opus mapping. */
330 av_ret = libopus_validate_layout_and_get_channel_map(avctx, opus->opts.mapping_family,
331 &opus->encoder_channel_map);
336 if (opus->opts.mapping_family == -1) {
337 /* By default, use mapping family 1 for the header but use the older
338 * libopus multistream API to avoid surround masking. */
340 /* Set the mapping family so that the value is correct in the header */
341 mapping_family = avctx->channels > 2 ? 1 : 0;
342 coupled_stream_count = opus_coupled_streams[avctx->channels - 1];
343 opus->stream_count = avctx->channels - coupled_stream_count;
344 memcpy(libopus_channel_mapping,
345 opus_vorbis_channel_map[avctx->channels - 1],
346 avctx->channels * sizeof(*libopus_channel_mapping));
348 enc = opus_multistream_encoder_create(
349 avctx->sample_rate, avctx->channels, opus->stream_count,
350 coupled_stream_count,
351 libavcodec_libopus_channel_map[avctx->channels - 1],
352 opus->opts.application, &ret);
354 /* Use the newer multistream API. The encoder will set the channel
355 * mapping and coupled stream counts to its internal defaults and will
356 * use surround masking analysis to save bits. */
357 mapping_family = opus->opts.mapping_family;
358 enc = opus_multistream_surround_encoder_create(
359 avctx->sample_rate, avctx->channels, mapping_family,
360 &opus->stream_count, &coupled_stream_count, libopus_channel_mapping,
361 opus->opts.application, &ret);
364 if (ret != OPUS_OK) {
365 av_log(avctx, AV_LOG_ERROR,
366 "Failed to create encoder: %s\n", opus_strerror(ret));
367 return ff_opus_error_to_averror(ret);
370 if (!avctx->bit_rate) {
371 /* Sane default copied from opusenc */
372 avctx->bit_rate = 64000 * opus->stream_count +
373 32000 * coupled_stream_count;
374 av_log(avctx, AV_LOG_WARNING,
375 "No bit rate set. Defaulting to %"PRId64" bps.\n", avctx->bit_rate);
378 if (avctx->bit_rate < 500 || avctx->bit_rate > 256000 * avctx->channels) {
379 av_log(avctx, AV_LOG_ERROR, "The bit rate %"PRId64" bps is unsupported. "
380 "Please choose a value between 500 and %d.\n", avctx->bit_rate,
381 256000 * avctx->channels);
382 ret = AVERROR(EINVAL);
386 ret = libopus_configure_encoder(avctx, enc, &opus->opts);
387 if (ret != OPUS_OK) {
388 ret = ff_opus_error_to_averror(ret);
392 /* Header includes channel mapping table if and only if mapping family is NOT 0 */
393 header_size = 19 + (mapping_family == 0 ? 0 : 2 + avctx->channels);
394 avctx->extradata = av_malloc(header_size + AV_INPUT_BUFFER_PADDING_SIZE);
395 if (!avctx->extradata) {
396 av_log(avctx, AV_LOG_ERROR, "Failed to allocate extradata.\n");
397 ret = AVERROR(ENOMEM);
400 avctx->extradata_size = header_size;
402 opus->samples = av_mallocz_array(frame_size, avctx->channels *
403 av_get_bytes_per_sample(avctx->sample_fmt));
404 if (!opus->samples) {
405 av_log(avctx, AV_LOG_ERROR, "Failed to allocate samples buffer.\n");
406 ret = AVERROR(ENOMEM);
410 ret = opus_multistream_encoder_ctl(enc, OPUS_GET_LOOKAHEAD(&avctx->initial_padding));
412 av_log(avctx, AV_LOG_WARNING,
413 "Unable to get number of lookahead samples: %s\n",
416 libopus_write_header(avctx, opus->stream_count, coupled_stream_count,
417 mapping_family, libopus_channel_mapping);
419 ff_af_queue_init(avctx, &opus->afq);
426 opus_multistream_encoder_destroy(enc);
427 av_freep(&avctx->extradata);
431 static void libopus_copy_samples_with_channel_map(
432 uint8_t *dst, const uint8_t *src, const uint8_t *channel_map,
433 int nb_channels, int nb_samples, int bytes_per_sample) {
435 for (sample = 0; sample < nb_samples; ++sample) {
436 for (channel = 0; channel < nb_channels; ++channel) {
437 const size_t src_pos = bytes_per_sample * (nb_channels * sample + channel);
438 const size_t dst_pos = bytes_per_sample * (nb_channels * sample + channel_map[channel]);
440 memcpy(&dst[dst_pos], &src[src_pos], bytes_per_sample);
445 static int libopus_encode(AVCodecContext *avctx, AVPacket *avpkt,
446 const AVFrame *frame, int *got_packet_ptr)
448 LibopusEncContext *opus = avctx->priv_data;
449 const int bytes_per_sample = av_get_bytes_per_sample(avctx->sample_fmt);
450 const int sample_size = avctx->channels * bytes_per_sample;
456 ret = ff_af_queue_add(&opus->afq, frame);
459 if (opus->encoder_channel_map != NULL) {
460 audio = opus->samples;
461 libopus_copy_samples_with_channel_map(
462 audio, frame->data[0], opus->encoder_channel_map,
463 avctx->channels, frame->nb_samples, bytes_per_sample);
464 } else if (frame->nb_samples < opus->opts.packet_size) {
465 audio = opus->samples;
466 memcpy(audio, frame->data[0], frame->nb_samples * sample_size);
468 audio = frame->data[0];
470 if (!opus->afq.remaining_samples || (!opus->afq.frame_alloc && !opus->afq.frame_count))
472 audio = opus->samples;
473 memset(audio, 0, opus->opts.packet_size * sample_size);
476 /* Maximum packet size taken from opusenc in opus-tools. 120ms packets
477 * consist of 6 frames in one packet. The maximum frame size is 1275
478 * bytes along with the largest possible packet header of 7 bytes. */
479 if ((ret = ff_alloc_packet2(avctx, avpkt, (1275 * 6 + 7) * opus->stream_count, 0)) < 0)
482 if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
483 ret = opus_multistream_encode_float(opus->enc, (float *)audio,
484 opus->opts.packet_size,
485 avpkt->data, avpkt->size);
487 ret = opus_multistream_encode(opus->enc, (opus_int16 *)audio,
488 opus->opts.packet_size,
489 avpkt->data, avpkt->size);
492 av_log(avctx, AV_LOG_ERROR,
493 "Error encoding frame: %s\n", opus_strerror(ret));
494 return ff_opus_error_to_averror(ret);
497 av_shrink_packet(avpkt, ret);
499 ff_af_queue_remove(&opus->afq, opus->opts.packet_size,
500 &avpkt->pts, &avpkt->duration);
502 discard_padding = opus->opts.packet_size - avpkt->duration;
503 // Check if subtraction resulted in an overflow
504 if ((discard_padding < opus->opts.packet_size) != (avpkt->duration > 0)) {
505 av_packet_unref(avpkt);
507 return AVERROR(EINVAL);
509 if (discard_padding > 0) {
510 uint8_t* side_data = av_packet_new_side_data(avpkt,
511 AV_PKT_DATA_SKIP_SAMPLES,
514 av_packet_unref(avpkt);
516 return AVERROR(ENOMEM);
518 AV_WL32(side_data + 4, discard_padding);
526 static av_cold int libopus_encode_close(AVCodecContext *avctx)
528 LibopusEncContext *opus = avctx->priv_data;
530 opus_multistream_encoder_destroy(opus->enc);
532 ff_af_queue_close(&opus->afq);
534 av_freep(&opus->samples);
535 av_freep(&avctx->extradata);
540 #define OFFSET(x) offsetof(LibopusEncContext, opts.x)
541 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
542 static const AVOption libopus_options[] = {
543 { "application", "Intended application type", OFFSET(application), AV_OPT_TYPE_INT, { .i64 = OPUS_APPLICATION_AUDIO }, OPUS_APPLICATION_VOIP, OPUS_APPLICATION_RESTRICTED_LOWDELAY, FLAGS, "application" },
544 { "voip", "Favor improved speech intelligibility", 0, AV_OPT_TYPE_CONST, { .i64 = OPUS_APPLICATION_VOIP }, 0, 0, FLAGS, "application" },
545 { "audio", "Favor faithfulness to the input", 0, AV_OPT_TYPE_CONST, { .i64 = OPUS_APPLICATION_AUDIO }, 0, 0, FLAGS, "application" },
546 { "lowdelay", "Restrict to only the lowest delay modes", 0, AV_OPT_TYPE_CONST, { .i64 = OPUS_APPLICATION_RESTRICTED_LOWDELAY }, 0, 0, FLAGS, "application" },
547 { "frame_duration", "Duration of a frame in milliseconds", OFFSET(frame_duration), AV_OPT_TYPE_FLOAT, { .dbl = 20.0 }, 2.5, 120.0, FLAGS },
548 { "packet_loss", "Expected packet loss percentage", OFFSET(packet_loss), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 100, FLAGS },
549 { "vbr", "Variable bit rate mode", OFFSET(vbr), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 2, FLAGS, "vbr" },
550 { "off", "Use constant bit rate", 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, 0, 0, FLAGS, "vbr" },
551 { "on", "Use variable bit rate", 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, 0, 0, FLAGS, "vbr" },
552 { "constrained", "Use constrained VBR", 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, 0, 0, FLAGS, "vbr" },
553 { "mapping_family", "Channel Mapping Family", OFFSET(mapping_family), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 255, FLAGS, "mapping_family" },
554 #ifdef OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST
555 { "apply_phase_inv", "Apply intensity stereo phase inversion", OFFSET(apply_phase_inv), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
560 static const AVClass libopus_class = {
561 .class_name = "libopus",
562 .item_name = av_default_item_name,
563 .option = libopus_options,
564 .version = LIBAVUTIL_VERSION_INT,
567 static const AVCodecDefault libopus_defaults[] = {
569 { "compression_level", "10" },
573 static const int libopus_sample_rates[] = {
574 48000, 24000, 16000, 12000, 8000, 0,
577 AVCodec ff_libopus_encoder = {
579 .long_name = NULL_IF_CONFIG_SMALL("libopus Opus"),
580 .type = AVMEDIA_TYPE_AUDIO,
581 .id = AV_CODEC_ID_OPUS,
582 .priv_data_size = sizeof(LibopusEncContext),
583 .init = libopus_encode_init,
584 .encode2 = libopus_encode,
585 .close = libopus_encode_close,
586 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SMALL_LAST_FRAME,
587 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
589 AV_SAMPLE_FMT_NONE },
590 .supported_samplerates = libopus_sample_rates,
591 .priv_class = &libopus_class,
592 .defaults = libopus_defaults,
593 .wrapper_name = "libopus",