FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
libopusenc.c
Go to the documentation of this file.
1 /*
2  * Opus encoder using libopus
3  * Copyright (c) 2012 Nathan Caldwell
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21 
22 #include <opus.h>
23 #include <opus_multistream.h>
24 
25 #include "libavutil/opt.h"
26 #include "avcodec.h"
27 #include "bytestream.h"
28 #include "internal.h"
29 #include "libopus.h"
30 #include "vorbis.h"
31 #include "audio_frame_queue.h"
32 
33 typedef struct LibopusEncOpts {
34  int vbr;
42 
43 typedef struct LibopusEncContext {
44  AVClass *class;
45  OpusMSEncoder *enc;
51 
52 static const uint8_t opus_coupled_streams[8] = {
53  0, 1, 1, 2, 2, 2, 2, 3
54 };
55 
56 /* Opus internal to Vorbis channel order mapping written in the header */
57 static const uint8_t opus_vorbis_channel_map[8][8] = {
58  { 0 },
59  { 0, 1 },
60  { 0, 2, 1 },
61  { 0, 1, 2, 3 },
62  { 0, 4, 1, 2, 3 },
63  { 0, 4, 1, 2, 3, 5 },
64  { 0, 4, 1, 2, 3, 5, 6 },
65  { 0, 6, 1, 2, 3, 4, 5, 7 },
66 };
67 
68 /* libavcodec to libopus channel order mapping, passed to libopus */
70  { 0 },
71  { 0, 1 },
72  { 0, 1, 2 },
73  { 0, 1, 2, 3 },
74  { 0, 1, 3, 4, 2 },
75  { 0, 1, 4, 5, 2, 3 },
76  { 0, 1, 5, 6, 2, 4, 3 },
77  { 0, 1, 6, 7, 4, 5, 2, 3 },
78 };
79 
80 static void libopus_write_header(AVCodecContext *avctx, int stream_count,
81  int coupled_stream_count,
82  const uint8_t *channel_mapping)
83 {
84  uint8_t *p = avctx->extradata;
85  int channels = avctx->channels;
86 
87  bytestream_put_buffer(&p, "OpusHead", 8);
88  bytestream_put_byte(&p, 1); /* Version */
89  bytestream_put_byte(&p, channels);
90  bytestream_put_le16(&p, avctx->delay); /* Lookahead samples at 48kHz */
91  bytestream_put_le32(&p, avctx->sample_rate); /* Original sample rate */
92  bytestream_put_le16(&p, 0); /* Gain of 0dB is recommended. */
93 
94  /* Channel mapping */
95  if (channels > 2) {
96  bytestream_put_byte(&p, channels <= 8 ? 1 : 255);
97  bytestream_put_byte(&p, stream_count);
98  bytestream_put_byte(&p, coupled_stream_count);
99  bytestream_put_buffer(&p, channel_mapping, channels);
100  } else {
101  bytestream_put_byte(&p, 0);
102  }
103 }
104 
105 static int libopus_configure_encoder(AVCodecContext *avctx, OpusMSEncoder *enc,
106  LibopusEncOpts *opts)
107 {
108  int ret;
109 
110  ret = opus_multistream_encoder_ctl(enc, OPUS_SET_BITRATE(avctx->bit_rate));
111  if (ret != OPUS_OK) {
112  av_log(avctx, AV_LOG_ERROR,
113  "Failed to set bitrate: %s\n", opus_strerror(ret));
114  return ret;
115  }
116 
117  ret = opus_multistream_encoder_ctl(enc,
118  OPUS_SET_COMPLEXITY(opts->complexity));
119  if (ret != OPUS_OK)
120  av_log(avctx, AV_LOG_WARNING,
121  "Unable to set complexity: %s\n", opus_strerror(ret));
122 
123  ret = opus_multistream_encoder_ctl(enc, OPUS_SET_VBR(!!opts->vbr));
124  if (ret != OPUS_OK)
125  av_log(avctx, AV_LOG_WARNING,
126  "Unable to set VBR: %s\n", opus_strerror(ret));
127 
128  ret = opus_multistream_encoder_ctl(enc,
129  OPUS_SET_VBR_CONSTRAINT(opts->vbr == 2));
130  if (ret != OPUS_OK)
131  av_log(avctx, AV_LOG_WARNING,
132  "Unable to set constrained VBR: %s\n", opus_strerror(ret));
133 
134  ret = opus_multistream_encoder_ctl(enc,
135  OPUS_SET_PACKET_LOSS_PERC(opts->packet_loss));
136  if (ret != OPUS_OK)
137  av_log(avctx, AV_LOG_WARNING,
138  "Unable to set expected packet loss percentage: %s\n",
139  opus_strerror(ret));
140 
141  if (avctx->cutoff) {
142  ret = opus_multistream_encoder_ctl(enc,
143  OPUS_SET_MAX_BANDWIDTH(opts->max_bandwidth));
144  if (ret != OPUS_OK)
145  av_log(avctx, AV_LOG_WARNING,
146  "Unable to set maximum bandwidth: %s\n", opus_strerror(ret));
147  }
148 
149  return OPUS_OK;
150 }
151 
153 {
154  LibopusEncContext *opus = avctx->priv_data;
155  const uint8_t *channel_mapping;
156  OpusMSEncoder *enc;
157  int ret = OPUS_OK;
158  int coupled_stream_count, header_size, frame_size;
159 
160  coupled_stream_count = opus_coupled_streams[avctx->channels - 1];
161  opus->stream_count = avctx->channels - coupled_stream_count;
162  channel_mapping = libavcodec_libopus_channel_map[avctx->channels - 1];
163 
164  /* FIXME: Opus can handle up to 255 channels. However, the mapping for
165  * anything greater than 8 is undefined. */
166  if (avctx->channels > 8)
167  av_log(avctx, AV_LOG_WARNING,
168  "Channel layout undefined for %d channels.\n", avctx->channels);
169 
170  if (!avctx->bit_rate) {
171  /* Sane default copied from opusenc */
172  avctx->bit_rate = 64000 * opus->stream_count +
173  32000 * coupled_stream_count;
174  av_log(avctx, AV_LOG_WARNING,
175  "No bit rate set. Defaulting to %d bps.\n", avctx->bit_rate);
176  }
177 
178  if (avctx->bit_rate < 500 || avctx->bit_rate > 256000 * avctx->channels) {
179  av_log(avctx, AV_LOG_ERROR, "The bit rate %d bps is unsupported. "
180  "Please choose a value between 500 and %d.\n", avctx->bit_rate,
181  256000 * avctx->channels);
182  return AVERROR(EINVAL);
183  }
184 
185  frame_size = opus->opts.frame_duration * 48000 / 1000;
186  switch (frame_size) {
187  case 120:
188  case 240:
189  if (opus->opts.application != OPUS_APPLICATION_RESTRICTED_LOWDELAY)
190  av_log(avctx, AV_LOG_WARNING,
191  "LPC mode cannot be used with a frame duration of less "
192  "than 10ms. Enabling restricted low-delay mode.\n"
193  "Use a longer frame duration if this is not what you want.\n");
194  /* Frame sizes less than 10 ms can only use MDCT mode, so switching to
195  * RESTRICTED_LOWDELAY avoids an unnecessary extra 2.5ms lookahead. */
196  opus->opts.application = OPUS_APPLICATION_RESTRICTED_LOWDELAY;
197  case 480:
198  case 960:
199  case 1920:
200  case 2880:
201  opus->opts.packet_size =
202  avctx->frame_size = frame_size * avctx->sample_rate / 48000;
203  break;
204  default:
205  av_log(avctx, AV_LOG_ERROR, "Invalid frame duration: %g.\n"
206  "Frame duration must be exactly one of: 2.5, 5, 10, 20, 40 or 60.\n",
207  opus->opts.frame_duration);
208  return AVERROR(EINVAL);
209  }
210 
211  if (avctx->compression_level < 0 || avctx->compression_level > 10) {
212  av_log(avctx, AV_LOG_WARNING,
213  "Compression level must be in the range 0 to 10. "
214  "Defaulting to 10.\n");
215  opus->opts.complexity = 10;
216  } else {
217  opus->opts.complexity = avctx->compression_level;
218  }
219 
220  if (avctx->cutoff) {
221  switch (avctx->cutoff) {
222  case 4000:
223  opus->opts.max_bandwidth = OPUS_BANDWIDTH_NARROWBAND;
224  break;
225  case 6000:
226  opus->opts.max_bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
227  break;
228  case 8000:
229  opus->opts.max_bandwidth = OPUS_BANDWIDTH_WIDEBAND;
230  break;
231  case 12000:
232  opus->opts.max_bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND;
233  break;
234  case 20000:
235  opus->opts.max_bandwidth = OPUS_BANDWIDTH_FULLBAND;
236  break;
237  default:
238  av_log(avctx, AV_LOG_WARNING,
239  "Invalid frequency cutoff: %d. Using default maximum bandwidth.\n"
240  "Cutoff frequency must be exactly one of: 4000, 6000, 8000, 12000 or 20000.\n",
241  avctx->cutoff);
242  avctx->cutoff = 0;
243  }
244  }
245 
246  enc = opus_multistream_encoder_create(avctx->sample_rate, avctx->channels,
247  opus->stream_count,
248  coupled_stream_count,
249  channel_mapping,
250  opus->opts.application, &ret);
251  if (ret != OPUS_OK) {
252  av_log(avctx, AV_LOG_ERROR,
253  "Failed to create encoder: %s\n", opus_strerror(ret));
254  return ff_opus_error_to_averror(ret);
255  }
256 
257  ret = libopus_configure_encoder(avctx, enc, &opus->opts);
258  if (ret != OPUS_OK) {
259  ret = ff_opus_error_to_averror(ret);
260  goto fail;
261  }
262 
263  header_size = 19 + (avctx->channels > 2 ? 2 + avctx->channels : 0);
264  avctx->extradata = av_malloc(header_size + FF_INPUT_BUFFER_PADDING_SIZE);
265  if (!avctx->extradata) {
266  av_log(avctx, AV_LOG_ERROR, "Failed to allocate extradata.\n");
267  ret = AVERROR(ENOMEM);
268  goto fail;
269  }
270  avctx->extradata_size = header_size;
271 
272  opus->samples = av_mallocz(frame_size * avctx->channels *
274  if (!opus->samples) {
275  av_log(avctx, AV_LOG_ERROR, "Failed to allocate samples buffer.\n");
276  ret = AVERROR(ENOMEM);
277  goto fail;
278  }
279 
280  ret = opus_multistream_encoder_ctl(enc, OPUS_GET_LOOKAHEAD(&avctx->delay));
281  if (ret != OPUS_OK)
282  av_log(avctx, AV_LOG_WARNING,
283  "Unable to get number of lookahead samples: %s\n",
284  opus_strerror(ret));
285 
286  libopus_write_header(avctx, opus->stream_count, coupled_stream_count,
287  opus_vorbis_channel_map[avctx->channels - 1]);
288 
289  ff_af_queue_init(avctx, &opus->afq);
290 
291  opus->enc = enc;
292 
293  return 0;
294 
295 fail:
296  opus_multistream_encoder_destroy(enc);
297  av_freep(&avctx->extradata);
298  return ret;
299 }
300 
301 static int libopus_encode(AVCodecContext *avctx, AVPacket *avpkt,
302  const AVFrame *frame, int *got_packet_ptr)
303 {
304  LibopusEncContext *opus = avctx->priv_data;
305  const int sample_size = avctx->channels *
307  uint8_t *audio;
308  int ret;
309 
310  if (frame) {
311  ff_af_queue_add(&opus->afq, frame);
312  if (frame->nb_samples < opus->opts.packet_size) {
313  audio = opus->samples;
314  memcpy(audio, frame->data[0], frame->nb_samples * sample_size);
315  } else
316  audio = frame->data[0];
317  } else {
318  if (!opus->afq.remaining_samples)
319  return 0;
320  audio = opus->samples;
321  memset(audio, 0, opus->opts.packet_size * sample_size);
322  }
323 
324  /* Maximum packet size taken from opusenc in opus-tools. 60ms packets
325  * consist of 3 frames in one packet. The maximum frame size is 1275
326  * bytes along with the largest possible packet header of 7 bytes. */
327  if (ret = ff_alloc_packet(avpkt, (1275 * 3 + 7) * opus->stream_count)) {
328  av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
329  return ret;
330  }
331 
332  if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
333  ret = opus_multistream_encode_float(opus->enc, (float *)audio,
334  opus->opts.packet_size,
335  avpkt->data, avpkt->size);
336  else
337  ret = opus_multistream_encode(opus->enc, (opus_int16 *)audio,
338  opus->opts.packet_size,
339  avpkt->data, avpkt->size);
340 
341  if (ret < 0) {
342  av_log(avctx, AV_LOG_ERROR,
343  "Error encoding frame: %s\n", opus_strerror(ret));
344  return ff_opus_error_to_averror(ret);
345  }
346 
347  av_shrink_packet(avpkt, ret);
348 
349  ff_af_queue_remove(&opus->afq, opus->opts.packet_size,
350  &avpkt->pts, &avpkt->duration);
351 
352  *got_packet_ptr = 1;
353 
354  return 0;
355 }
356 
358 {
359  LibopusEncContext *opus = avctx->priv_data;
360 
361  opus_multistream_encoder_destroy(opus->enc);
362 
363  ff_af_queue_close(&opus->afq);
364 
365  av_freep(&opus->samples);
366  av_freep(&avctx->extradata);
367 
368  return 0;
369 }
370 
371 #define OFFSET(x) offsetof(LibopusEncContext, opts.x)
372 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
373 static const AVOption libopus_options[] = {
374  { "application", "Intended application type", OFFSET(application), AV_OPT_TYPE_INT, { .i64 = OPUS_APPLICATION_AUDIO }, OPUS_APPLICATION_VOIP, OPUS_APPLICATION_RESTRICTED_LOWDELAY, FLAGS, "application" },
375  { "voip", "Favor improved speech intelligibility", 0, AV_OPT_TYPE_CONST, { .i64 = OPUS_APPLICATION_VOIP }, 0, 0, FLAGS, "application" },
376  { "audio", "Favor faithfulness to the input", 0, AV_OPT_TYPE_CONST, { .i64 = OPUS_APPLICATION_AUDIO }, 0, 0, FLAGS, "application" },
377  { "lowdelay", "Restrict to only the lowest delay modes", 0, AV_OPT_TYPE_CONST, { .i64 = OPUS_APPLICATION_RESTRICTED_LOWDELAY }, 0, 0, FLAGS, "application" },
378  { "frame_duration", "Duration of a frame in milliseconds", OFFSET(frame_duration), AV_OPT_TYPE_FLOAT, { .dbl = 10.0 }, 2.5, 60.0, FLAGS },
379  { "packet_loss", "Expected packet loss percentage", OFFSET(packet_loss), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 100, FLAGS },
380  { "vbr", "Variable bit rate mode", OFFSET(vbr), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 2, FLAGS, "vbr" },
381  { "off", "Use constant bit rate", 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, 0, 0, FLAGS, "vbr" },
382  { "on", "Use variable bit rate", 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, 0, 0, FLAGS, "vbr" },
383  { "constrained", "Use constrained VBR", 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, 0, 0, FLAGS, "vbr" },
384  { NULL },
385 };
386 
387 static const AVClass libopus_class = {
388  .class_name = "libopus",
389  .item_name = av_default_item_name,
390  .option = libopus_options,
391  .version = LIBAVUTIL_VERSION_INT,
392 };
393 
395  { "b", "0" },
396  { "compression_level", "10" },
397  { NULL },
398 };
399 
400 static const int libopus_sample_rates[] = {
401  48000, 24000, 16000, 12000, 8000, 0,
402 };
403 
405  .name = "libopus",
406  .type = AVMEDIA_TYPE_AUDIO,
407  .id = AV_CODEC_ID_OPUS,
408  .priv_data_size = sizeof(LibopusEncContext),
410  .encode2 = libopus_encode,
413  .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
416  .channel_layouts = ff_vorbis_channel_layouts,
417  .supported_samplerates = libopus_sample_rates,
418  .long_name = NULL_IF_CONFIG_SMALL("libopus Opus"),
419  .priv_class = &libopus_class,
420  .defaults = libopus_defaults,
421 };