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.

426 lines
16KB

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