obs-ffmpeg-audio-encoders.c 11 KB

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