obs-ffmpeg-audio-encoders.c 12 KB

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