obs-ffmpeg-audio-encoders.c 12 KB

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