obs-ffmpeg-audio-encoders.c 11 KB

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