You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

427 lines
16KB

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