1
0

obs-ffmpeg-audio-encoders.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. /******************************************************************************
  2. Copyright (C) 2014 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <util/base.h>
  15. #include <util/circlebuf.h>
  16. #include <util/darray.h>
  17. #include <util/dstr.h>
  18. #include <obs-module.h>
  19. #include <libavutil/channel_layout.h>
  20. #include <libavutil/opt.h>
  21. #include <libavformat/avformat.h>
  22. #include "obs-ffmpeg-formats.h"
  23. #include "obs-ffmpeg-compat.h"
  24. #define do_log(level, format, ...) \
  25. blog(level, "[FFmpeg %s encoder: '%s'] " format, enc->type, \
  26. obs_encoder_get_name(enc->encoder), ##__VA_ARGS__)
  27. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  28. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  29. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  30. struct enc_encoder {
  31. obs_encoder_t *encoder;
  32. const char *type;
  33. const AVCodec *codec;
  34. AVCodecContext *context;
  35. uint8_t *samples[MAX_AV_PLANES];
  36. AVFrame *aframe;
  37. int64_t total_samples;
  38. DARRAY(uint8_t) packet_buffer;
  39. size_t audio_planes;
  40. size_t audio_size;
  41. int frame_size; /* pretty much always 1024 for AAC */
  42. int frame_size_bytes;
  43. };
  44. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 24, 100)
  45. static inline uint64_t convert_speaker_layout(enum speaker_layout layout)
  46. {
  47. switch (layout) {
  48. case SPEAKERS_UNKNOWN:
  49. return 0;
  50. case SPEAKERS_MONO:
  51. return AV_CH_LAYOUT_MONO;
  52. case SPEAKERS_STEREO:
  53. return AV_CH_LAYOUT_STEREO;
  54. case SPEAKERS_2POINT1:
  55. return AV_CH_LAYOUT_SURROUND;
  56. case SPEAKERS_4POINT0:
  57. return AV_CH_LAYOUT_4POINT0;
  58. case SPEAKERS_4POINT1:
  59. return AV_CH_LAYOUT_4POINT1;
  60. case SPEAKERS_5POINT1:
  61. return AV_CH_LAYOUT_5POINT1_BACK;
  62. case SPEAKERS_7POINT1:
  63. return AV_CH_LAYOUT_7POINT1;
  64. }
  65. /* shouldn't get here */
  66. return 0;
  67. }
  68. #endif
  69. static const char *aac_getname(void *unused)
  70. {
  71. UNUSED_PARAMETER(unused);
  72. return obs_module_text("FFmpegAAC");
  73. }
  74. static const char *opus_getname(void *unused)
  75. {
  76. UNUSED_PARAMETER(unused);
  77. return obs_module_text("FFmpegOpus");
  78. }
  79. static void enc_destroy(void *data)
  80. {
  81. struct enc_encoder *enc = data;
  82. if (enc->samples[0])
  83. av_freep(&enc->samples[0]);
  84. if (enc->context)
  85. avcodec_free_context(&enc->context);
  86. if (enc->aframe)
  87. av_frame_free(&enc->aframe);
  88. da_free(enc->packet_buffer);
  89. bfree(enc);
  90. }
  91. static bool initialize_codec(struct enc_encoder *enc)
  92. {
  93. int ret;
  94. int channels;
  95. enc->aframe = av_frame_alloc();
  96. if (!enc->aframe) {
  97. warn("Failed to allocate audio frame");
  98. return false;
  99. }
  100. ret = avcodec_open2(enc->context, enc->codec, NULL);
  101. if (ret < 0) {
  102. struct dstr error_message = {0};
  103. dstr_printf(&error_message, "Failed to open AAC codec: %s",
  104. av_err2str(ret));
  105. obs_encoder_set_last_error(enc->encoder, error_message.array);
  106. dstr_free(&error_message);
  107. warn("Failed to open AAC codec: %s", av_err2str(ret));
  108. return false;
  109. }
  110. enc->aframe->format = enc->context->sample_fmt;
  111. #if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(57, 24, 100)
  112. enc->aframe->channels = enc->context->channels;
  113. channels = enc->context->channels;
  114. #else
  115. channels = enc->context->ch_layout.nb_channels;
  116. #endif
  117. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 24, 100)
  118. enc->aframe->channel_layout = enc->context->channel_layout;
  119. #else
  120. enc->aframe->ch_layout = enc->context->ch_layout;
  121. #endif
  122. enc->aframe->sample_rate = enc->context->sample_rate;
  123. enc->frame_size = enc->context->frame_size;
  124. if (!enc->frame_size)
  125. enc->frame_size = 1024;
  126. enc->frame_size_bytes = enc->frame_size * (int)enc->audio_size;
  127. ret = av_samples_alloc(enc->samples, NULL, channels, enc->frame_size,
  128. enc->context->sample_fmt, 0);
  129. if (ret < 0) {
  130. warn("Failed to create audio buffer: %s", av_err2str(ret));
  131. return false;
  132. }
  133. return true;
  134. }
  135. static void init_sizes(struct enc_encoder *enc, audio_t *audio)
  136. {
  137. const struct audio_output_info *aoi;
  138. enum audio_format format;
  139. aoi = audio_output_get_info(audio);
  140. format = convert_ffmpeg_sample_format(enc->context->sample_fmt);
  141. enc->audio_planes = get_audio_planes(format, aoi->speakers);
  142. enc->audio_size = get_audio_size(format, aoi->speakers, 1);
  143. }
  144. #ifndef MIN
  145. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  146. #endif
  147. static void *enc_create(obs_data_t *settings, obs_encoder_t *encoder,
  148. const char *type, const char *alt)
  149. {
  150. struct enc_encoder *enc;
  151. int bitrate = (int)obs_data_get_int(settings, "bitrate");
  152. audio_t *audio = obs_encoder_audio(encoder);
  153. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  154. avcodec_register_all();
  155. #endif
  156. enc = bzalloc(sizeof(struct enc_encoder));
  157. enc->encoder = encoder;
  158. enc->codec = avcodec_find_encoder_by_name(type);
  159. enc->type = type;
  160. if (!enc->codec && alt) {
  161. enc->codec = avcodec_find_encoder_by_name(alt);
  162. enc->type = alt;
  163. }
  164. blog(LOG_INFO, "---------------------------------");
  165. if (!enc->codec) {
  166. warn("Couldn't find encoder");
  167. goto fail;
  168. }
  169. if (!bitrate) {
  170. warn("Invalid bitrate specified");
  171. return NULL;
  172. }
  173. enc->context = avcodec_alloc_context3(enc->codec);
  174. if (!enc->context) {
  175. warn("Failed to create codec context");
  176. goto fail;
  177. }
  178. enc->context->bit_rate = bitrate * 1000;
  179. const struct audio_output_info *aoi;
  180. aoi = audio_output_get_info(audio);
  181. #if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(57, 24, 100)
  182. enc->context->channels = (int)audio_output_get_channels(audio);
  183. #endif
  184. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 24, 100)
  185. enc->context->channel_layout = convert_speaker_layout(aoi->speakers);
  186. #else
  187. av_channel_layout_default(&enc->context->ch_layout,
  188. (int)audio_output_get_channels(audio));
  189. if (aoi->speakers == SPEAKERS_4POINT1)
  190. enc->context->ch_layout =
  191. (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1;
  192. if (aoi->speakers == SPEAKERS_2POINT1)
  193. enc->context->ch_layout =
  194. (AVChannelLayout)AV_CHANNEL_LAYOUT_SURROUND;
  195. #endif
  196. enc->context->sample_rate = audio_output_get_sample_rate(audio);
  197. enc->context->sample_fmt = enc->codec->sample_fmts
  198. ? enc->codec->sample_fmts[0]
  199. : AV_SAMPLE_FMT_FLTP;
  200. /* check to make sure sample rate is supported */
  201. if (enc->codec->supported_samplerates) {
  202. const int *rate = enc->codec->supported_samplerates;
  203. int cur_rate = enc->context->sample_rate;
  204. int closest = 0;
  205. while (*rate) {
  206. int dist = abs(cur_rate - *rate);
  207. int closest_dist = abs(cur_rate - closest);
  208. if (dist < closest_dist)
  209. closest = *rate;
  210. rate++;
  211. }
  212. if (closest)
  213. enc->context->sample_rate = closest;
  214. }
  215. if (strcmp(enc->codec->name, "aac") == 0) {
  216. av_opt_set(enc->context->priv_data, "aac_coder", "fast", 0);
  217. }
  218. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 24, 100)
  219. info("bitrate: %" PRId64 ", channels: %d, channel_layout: %x\n",
  220. (int64_t)enc->context->bit_rate / 1000,
  221. (int)enc->context->channels,
  222. (unsigned int)enc->context->channel_layout);
  223. #else
  224. char buf[256];
  225. av_channel_layout_describe(&enc->context->ch_layout, buf, 256);
  226. info("bitrate: %" PRId64 ", channels: %d, channel_layout: %s\n",
  227. (int64_t)enc->context->bit_rate / 1000,
  228. (int)enc->context->ch_layout.nb_channels, buf);
  229. #endif
  230. init_sizes(enc, audio);
  231. /* enable experimental FFmpeg encoder if the only one available */
  232. enc->context->strict_std_compliance = -2;
  233. enc->context->flags = CODEC_FLAG_GLOBAL_H;
  234. if (initialize_codec(enc))
  235. return enc;
  236. fail:
  237. enc_destroy(enc);
  238. return NULL;
  239. }
  240. static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder)
  241. {
  242. return enc_create(settings, encoder, "aac", NULL);
  243. }
  244. static void *opus_create(obs_data_t *settings, obs_encoder_t *encoder)
  245. {
  246. return enc_create(settings, encoder, "libopus", "opus");
  247. }
  248. static bool do_encode(struct enc_encoder *enc, struct encoder_packet *packet,
  249. bool *received_packet)
  250. {
  251. AVRational time_base = {1, enc->context->sample_rate};
  252. AVPacket avpacket = {0};
  253. int got_packet;
  254. int ret;
  255. int channels;
  256. enc->aframe->nb_samples = enc->frame_size;
  257. enc->aframe->pts = av_rescale_q(
  258. enc->total_samples, (AVRational){1, enc->context->sample_rate},
  259. enc->context->time_base);
  260. #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 24, 100)
  261. enc->aframe->ch_layout = enc->context->ch_layout;
  262. channels = enc->context->ch_layout.nb_channels;
  263. #else
  264. channels = enc->context->channels;
  265. #endif
  266. ret = avcodec_fill_audio_frame(enc->aframe, channels,
  267. enc->context->sample_fmt,
  268. enc->samples[0],
  269. enc->frame_size_bytes * channels, 1);
  270. if (ret < 0) {
  271. warn("avcodec_fill_audio_frame failed: %s", av_err2str(ret));
  272. return false;
  273. }
  274. enc->total_samples += enc->frame_size;
  275. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  276. ret = avcodec_send_frame(enc->context, enc->aframe);
  277. if (ret == 0)
  278. ret = avcodec_receive_packet(enc->context, &avpacket);
  279. got_packet = (ret == 0);
  280. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  281. ret = 0;
  282. #else
  283. ret = avcodec_encode_audio2(enc->context, &avpacket, enc->aframe,
  284. &got_packet);
  285. #endif
  286. if (ret < 0) {
  287. warn("avcodec_encode_audio2 failed: %s", av_err2str(ret));
  288. return false;
  289. }
  290. *received_packet = !!got_packet;
  291. if (!got_packet)
  292. return true;
  293. da_resize(enc->packet_buffer, 0);
  294. da_push_back_array(enc->packet_buffer, avpacket.data, avpacket.size);
  295. packet->pts = rescale_ts(avpacket.pts, enc->context, time_base);
  296. packet->dts = rescale_ts(avpacket.dts, enc->context, time_base);
  297. packet->data = enc->packet_buffer.array;
  298. packet->size = avpacket.size;
  299. packet->type = OBS_ENCODER_AUDIO;
  300. packet->timebase_num = 1;
  301. packet->timebase_den = (int32_t)enc->context->sample_rate;
  302. av_free_packet(&avpacket);
  303. return true;
  304. }
  305. static bool enc_encode(void *data, struct encoder_frame *frame,
  306. struct encoder_packet *packet, bool *received_packet)
  307. {
  308. struct enc_encoder *enc = data;
  309. for (size_t i = 0; i < enc->audio_planes; i++)
  310. memcpy(enc->samples[i], frame->data[i], enc->frame_size_bytes);
  311. return do_encode(enc, packet, received_packet);
  312. }
  313. static void enc_defaults(obs_data_t *settings)
  314. {
  315. obs_data_set_default_int(settings, "bitrate", 128);
  316. }
  317. static obs_properties_t *enc_properties(void *unused)
  318. {
  319. UNUSED_PARAMETER(unused);
  320. obs_properties_t *props = obs_properties_create();
  321. obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 64,
  322. 1024, 32);
  323. return props;
  324. }
  325. static bool enc_extra_data(void *data, uint8_t **extra_data, size_t *size)
  326. {
  327. struct enc_encoder *enc = data;
  328. *extra_data = enc->context->extradata;
  329. *size = enc->context->extradata_size;
  330. return true;
  331. }
  332. static void enc_audio_info(void *data, struct audio_convert_info *info)
  333. {
  334. struct enc_encoder *enc = data;
  335. int channels;
  336. #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 24, 100)
  337. channels = enc->context->ch_layout.nb_channels;
  338. #else
  339. channels = enc->context->channels;
  340. #endif
  341. info->format = convert_ffmpeg_sample_format(enc->context->sample_fmt);
  342. info->samples_per_sec = (uint32_t)enc->context->sample_rate;
  343. if (channels != 7 && channels <= 8)
  344. info->speakers = (enum speaker_layout)(channels);
  345. else
  346. info->speakers = SPEAKERS_UNKNOWN;
  347. }
  348. static size_t enc_frame_size(void *data)
  349. {
  350. struct enc_encoder *enc = data;
  351. return enc->frame_size;
  352. }
  353. struct obs_encoder_info aac_encoder_info = {
  354. .id = "ffmpeg_aac",
  355. .type = OBS_ENCODER_AUDIO,
  356. .codec = "AAC",
  357. .get_name = aac_getname,
  358. .create = aac_create,
  359. .destroy = enc_destroy,
  360. .encode = enc_encode,
  361. .get_frame_size = enc_frame_size,
  362. .get_defaults = enc_defaults,
  363. .get_properties = enc_properties,
  364. .get_extra_data = enc_extra_data,
  365. .get_audio_info = enc_audio_info,
  366. };
  367. struct obs_encoder_info opus_encoder_info = {
  368. .id = "ffmpeg_opus",
  369. .type = OBS_ENCODER_AUDIO,
  370. .codec = "opus",
  371. .get_name = opus_getname,
  372. .create = opus_create,
  373. .destroy = enc_destroy,
  374. .encode = enc_encode,
  375. .get_frame_size = enc_frame_size,
  376. .get_defaults = enc_defaults,
  377. .get_properties = enc_properties,
  378. .get_extra_data = enc_extra_data,
  379. .get_audio_info = enc_audio_info,
  380. };