obs-ffmpeg-output.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain 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 <obs-module.h>
  15. #include <util/deque.h>
  16. #include <util/threading.h>
  17. #include <util/dstr.h>
  18. #include <util/darray.h>
  19. #include <util/platform.h>
  20. #include "obs-ffmpeg-output.h"
  21. #include "obs-ffmpeg-formats.h"
  22. #include "obs-ffmpeg-compat.h"
  23. #include <libavutil/channel_layout.h>
  24. #include <libavutil/mastering_display_metadata.h>
  25. /* ------------------------------------------------------------------------- */
  26. static void ffmpeg_output_set_last_error(struct ffmpeg_data *data, const char *error)
  27. {
  28. if (data->last_error)
  29. bfree(data->last_error);
  30. data->last_error = bstrdup(error);
  31. }
  32. void ffmpeg_log_error(int log_level, struct ffmpeg_data *data, const char *format, ...)
  33. {
  34. va_list args;
  35. char out[4096];
  36. va_start(args, format);
  37. vsnprintf(out, sizeof(out), format, args);
  38. va_end(args);
  39. ffmpeg_output_set_last_error(data, out);
  40. blog(log_level, "%s", out);
  41. }
  42. static bool new_stream(struct ffmpeg_data *data, AVStream **stream, const AVCodec **codec, enum AVCodecID id,
  43. const char *name)
  44. {
  45. *codec = (!!name && *name) ? avcodec_find_encoder_by_name(name) : avcodec_find_encoder(id);
  46. if (!*codec) {
  47. ffmpeg_log_error(LOG_WARNING, data, "Couldn't find encoder '%s'", avcodec_get_name(id));
  48. return false;
  49. }
  50. *stream = avformat_new_stream(data->output, *codec);
  51. if (!*stream) {
  52. ffmpeg_log_error(LOG_WARNING, data, "Couldn't create stream for encoder '%s'", avcodec_get_name(id));
  53. return false;
  54. }
  55. (*stream)->id = data->output->nb_streams - 1;
  56. return true;
  57. }
  58. static bool parse_params(AVCodecContext *context, char **opts)
  59. {
  60. bool ret = true;
  61. if (!context || !context->priv_data)
  62. return true;
  63. while (*opts) {
  64. char *opt = *opts;
  65. char *assign = strchr(opt, '=');
  66. if (assign) {
  67. char *name = opt;
  68. char *value;
  69. *assign = 0;
  70. value = assign + 1;
  71. if (av_opt_set(context, name, value, AV_OPT_SEARCH_CHILDREN)) {
  72. blog(LOG_WARNING, "Failed to set %s=%s", name, value);
  73. ret = false;
  74. }
  75. }
  76. opts++;
  77. }
  78. return ret;
  79. }
  80. static bool open_video_codec(struct ffmpeg_data *data)
  81. {
  82. AVCodecContext *const context = data->video_ctx;
  83. char **opts = strlist_split(data->config.video_settings, ' ', false);
  84. int ret;
  85. if (strcmp(data->vcodec->name, "libx264") == 0)
  86. av_opt_set(context->priv_data, "preset", "veryfast", 0);
  87. if (opts) {
  88. // libav requires x264 parameters in a special format which may be non-obvious
  89. if (!parse_params(context, opts) && strcmp(data->vcodec->name, "libx264") == 0)
  90. blog(LOG_WARNING,
  91. "If you're trying to set x264 parameters, use x264-params=name=value:name=value");
  92. strlist_free(opts);
  93. }
  94. ret = avcodec_open2(context, data->vcodec, NULL);
  95. if (ret < 0) {
  96. ffmpeg_log_error(LOG_WARNING, data, "Failed to open video codec: %s", av_err2str(ret));
  97. return false;
  98. }
  99. data->vframe = av_frame_alloc();
  100. if (!data->vframe) {
  101. ffmpeg_log_error(LOG_WARNING, data, "Failed to allocate video frame");
  102. return false;
  103. }
  104. data->vframe->format = context->pix_fmt;
  105. data->vframe->width = context->width;
  106. data->vframe->height = context->height;
  107. data->vframe->color_range = data->config.color_range;
  108. data->vframe->color_primaries = data->config.color_primaries;
  109. data->vframe->color_trc = data->config.color_trc;
  110. data->vframe->colorspace = data->config.colorspace;
  111. data->vframe->chroma_location = determine_chroma_location(context->pix_fmt, data->config.colorspace);
  112. ret = av_frame_get_buffer(data->vframe, base_get_alignment());
  113. if (ret < 0) {
  114. ffmpeg_log_error(LOG_WARNING, data, "Failed to allocate vframe: %s", av_err2str(ret));
  115. return false;
  116. }
  117. avcodec_parameters_from_context(data->video->codecpar, context);
  118. return true;
  119. }
  120. static bool init_swscale(struct ffmpeg_data *data, AVCodecContext *context)
  121. {
  122. data->swscale = sws_getContext(data->config.width, data->config.height, data->config.format,
  123. data->config.scale_width, data->config.scale_height, context->pix_fmt,
  124. SWS_BICUBIC, NULL, NULL, NULL);
  125. if (!data->swscale) {
  126. ffmpeg_log_error(LOG_WARNING, data, "Could not initialize swscale");
  127. return false;
  128. }
  129. return true;
  130. }
  131. static bool create_video_stream(struct ffmpeg_data *data)
  132. {
  133. enum AVPixelFormat closest_format;
  134. AVCodecContext *context;
  135. struct obs_video_info ovi;
  136. const enum AVPixelFormat *pix_fmts = NULL;
  137. if (!obs_get_video_info(&ovi)) {
  138. ffmpeg_log_error(LOG_WARNING, data, "No active video");
  139. return false;
  140. }
  141. if (!new_stream(data, &data->video, &data->vcodec, data->output->oformat->video_codec,
  142. data->config.video_encoder))
  143. return false;
  144. context = avcodec_alloc_context3(data->vcodec);
  145. context->bit_rate = (int64_t)data->config.video_bitrate * 1000;
  146. context->width = data->config.scale_width;
  147. context->height = data->config.scale_height;
  148. context->time_base = (AVRational){ovi.fps_den, ovi.fps_num};
  149. context->framerate = (AVRational){ovi.fps_num, ovi.fps_den};
  150. context->gop_size = data->config.gop_size;
  151. context->color_range = data->config.color_range;
  152. context->color_primaries = data->config.color_primaries;
  153. context->color_trc = data->config.color_trc;
  154. context->colorspace = data->config.colorspace;
  155. context->thread_count = 0;
  156. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(61, 13, 100)
  157. pix_fmts = data->vcodec->pix_fmts;
  158. #else
  159. avcodec_get_supported_config(context, data->vcodec, AV_CODEC_CONFIG_PIX_FORMAT, 0, (const void **)&pix_fmts,
  160. NULL);
  161. #endif
  162. closest_format = data->config.format;
  163. if (pix_fmts) {
  164. const int has_alpha = closest_format == AV_PIX_FMT_BGRA;
  165. closest_format = avcodec_find_best_pix_fmt_of_list(pix_fmts, closest_format, has_alpha, NULL);
  166. }
  167. context->pix_fmt = closest_format;
  168. context->chroma_sample_location = determine_chroma_location(closest_format, data->config.colorspace);
  169. data->video->time_base = context->time_base;
  170. data->video->avg_frame_rate = (AVRational){ovi.fps_num, ovi.fps_den};
  171. if (data->output->oformat->flags & AVFMT_GLOBALHEADER)
  172. context->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  173. data->video_ctx = context;
  174. if (!open_video_codec(data))
  175. return false;
  176. const enum AVColorTransferCharacteristic trc = data->config.color_trc;
  177. const bool pq = trc == AVCOL_TRC_SMPTE2084;
  178. const bool hlg = trc == AVCOL_TRC_ARIB_STD_B67;
  179. if (pq || hlg) {
  180. const int hdr_nominal_peak_level = pq ? (int)obs_get_video_hdr_nominal_peak_level() : (hlg ? 1000 : 0);
  181. size_t content_size;
  182. AVContentLightMetadata *const content = av_content_light_metadata_alloc(&content_size);
  183. content->MaxCLL = hdr_nominal_peak_level;
  184. content->MaxFALL = hdr_nominal_peak_level;
  185. av_packet_side_data_add(&data->video->codecpar->coded_side_data,
  186. &data->video->codecpar->nb_coded_side_data, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
  187. (uint8_t *)content, content_size, 0);
  188. AVMasteringDisplayMetadata *const mastering = av_mastering_display_metadata_alloc();
  189. mastering->display_primaries[0][0] = av_make_q(17, 25);
  190. mastering->display_primaries[0][1] = av_make_q(8, 25);
  191. mastering->display_primaries[1][0] = av_make_q(53, 200);
  192. mastering->display_primaries[1][1] = av_make_q(69, 100);
  193. mastering->display_primaries[2][0] = av_make_q(3, 20);
  194. mastering->display_primaries[2][1] = av_make_q(3, 50);
  195. mastering->white_point[0] = av_make_q(3127, 10000);
  196. mastering->white_point[1] = av_make_q(329, 1000);
  197. mastering->min_luminance = av_make_q(0, 1);
  198. mastering->max_luminance = av_make_q(hdr_nominal_peak_level, 1);
  199. mastering->has_primaries = 1;
  200. mastering->has_luminance = 1;
  201. av_packet_side_data_add(&data->video->codecpar->coded_side_data,
  202. &data->video->codecpar->nb_coded_side_data,
  203. AV_PKT_DATA_MASTERING_DISPLAY_METADATA, (uint8_t *)mastering,
  204. sizeof(*mastering), 0);
  205. }
  206. if (context->pix_fmt != data->config.format || data->config.width != data->config.scale_width ||
  207. data->config.height != data->config.scale_height) {
  208. if (!init_swscale(data, context))
  209. return false;
  210. }
  211. return true;
  212. }
  213. static bool open_audio_codec(struct ffmpeg_data *data, int idx)
  214. {
  215. AVCodecContext *const context = data->audio_infos[idx].ctx;
  216. char **opts = strlist_split(data->config.audio_settings, ' ', false);
  217. int ret;
  218. int channels;
  219. if (opts) {
  220. parse_params(context, opts);
  221. strlist_free(opts);
  222. }
  223. data->aframe[idx] = av_frame_alloc();
  224. if (!data->aframe[idx]) {
  225. ffmpeg_log_error(LOG_WARNING, data, "Failed to allocate audio frame");
  226. return false;
  227. }
  228. data->aframe[idx]->format = context->sample_fmt;
  229. data->aframe[idx]->ch_layout = context->ch_layout;
  230. channels = context->ch_layout.nb_channels;
  231. data->aframe[idx]->sample_rate = context->sample_rate;
  232. context->strict_std_compliance = -2;
  233. ret = avcodec_open2(context, data->acodec, NULL);
  234. if (ret < 0) {
  235. ffmpeg_log_error(LOG_WARNING, data, "Failed to open audio codec: %s", av_err2str(ret));
  236. return false;
  237. }
  238. data->frame_size = context->frame_size ? context->frame_size : 1024;
  239. ret = av_samples_alloc(data->samples[idx], NULL, channels, data->frame_size, context->sample_fmt, 0);
  240. if (ret < 0) {
  241. ffmpeg_log_error(LOG_WARNING, data, "Failed to create audio buffer: %s", av_err2str(ret));
  242. return false;
  243. }
  244. avcodec_parameters_from_context(data->audio_infos[idx].stream->codecpar, context);
  245. return true;
  246. }
  247. static bool create_audio_stream(struct ffmpeg_data *data, int idx)
  248. {
  249. AVCodecContext *context;
  250. AVStream *stream;
  251. struct obs_audio_info aoi;
  252. int channels;
  253. const enum AVSampleFormat *sample_fmts = NULL;
  254. if (!obs_get_audio_info(&aoi)) {
  255. ffmpeg_log_error(LOG_WARNING, data, "No active audio");
  256. return false;
  257. }
  258. if (!new_stream(data, &stream, &data->acodec, data->output->oformat->audio_codec, data->config.audio_encoder))
  259. return false;
  260. context = avcodec_alloc_context3(data->acodec);
  261. context->bit_rate = (int64_t)data->config.audio_bitrate * 1000;
  262. context->time_base = (AVRational){1, aoi.samples_per_sec};
  263. channels = get_audio_channels(aoi.speakers);
  264. context->sample_rate = aoi.samples_per_sec;
  265. av_channel_layout_default(&context->ch_layout, channels);
  266. if (aoi.speakers == SPEAKERS_4POINT1)
  267. context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1;
  268. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(61, 13, 100)
  269. sample_fmts = data->acodec->sample_fmts;
  270. #else
  271. avcodec_get_supported_config(context, data->acodec, AV_CODEC_CONFIG_SAMPLE_FORMAT, 0,
  272. (const void **)&sample_fmts, NULL);
  273. #endif
  274. context->sample_fmt = sample_fmts ? sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
  275. stream->time_base = context->time_base;
  276. data->audio_samplerate = aoi.samples_per_sec;
  277. data->audio_format = convert_ffmpeg_sample_format(context->sample_fmt);
  278. data->audio_planes = get_audio_planes(data->audio_format, aoi.speakers);
  279. data->audio_size = get_audio_size(data->audio_format, aoi.speakers, 1);
  280. if (data->output->oformat->flags & AVFMT_GLOBALHEADER)
  281. context->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  282. data->audio_infos[idx].stream = stream;
  283. data->audio_infos[idx].ctx = context;
  284. if (data->config.audio_stream_names[idx] && *data->config.audio_stream_names[idx] != '\0')
  285. av_dict_set(&stream->metadata, "title", data->config.audio_stream_names[idx], 0);
  286. return open_audio_codec(data, idx);
  287. }
  288. static inline bool init_streams(struct ffmpeg_data *data)
  289. {
  290. const AVOutputFormat *format = data->output->oformat;
  291. if (format->video_codec != AV_CODEC_ID_NONE)
  292. if (!create_video_stream(data))
  293. return false;
  294. if (format->audio_codec != AV_CODEC_ID_NONE && data->num_audio_streams) {
  295. data->audio_infos = calloc(data->num_audio_streams, sizeof(*data->audio_infos));
  296. for (int i = 0; i < data->num_audio_streams; i++) {
  297. if (!create_audio_stream(data, i))
  298. return false;
  299. }
  300. }
  301. return true;
  302. }
  303. static inline bool open_output_file(struct ffmpeg_data *data)
  304. {
  305. const AVOutputFormat *format = data->output->oformat;
  306. int ret;
  307. AVDictionary *dict = NULL;
  308. if ((ret = av_dict_parse_string(&dict, data->config.muxer_settings, "=", " ", 0))) {
  309. ffmpeg_log_error(LOG_WARNING, data, "Failed to parse muxer settings: %s\n%s", av_err2str(ret),
  310. data->config.muxer_settings);
  311. av_dict_free(&dict);
  312. return false;
  313. }
  314. if (av_dict_count(dict) > 0) {
  315. struct dstr str = {0};
  316. AVDictionaryEntry *entry = NULL;
  317. while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX)))
  318. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  319. blog(LOG_INFO, "Using muxer settings: %s", str.array);
  320. dstr_free(&str);
  321. }
  322. if ((format->flags & AVFMT_NOFILE) == 0) {
  323. ret = avio_open2(&data->output->pb, data->config.url, AVIO_FLAG_WRITE, NULL, &dict);
  324. if (ret < 0) {
  325. ffmpeg_log_error(LOG_WARNING, data, "Couldn't open '%s', %s", data->config.url,
  326. av_err2str(ret));
  327. av_dict_free(&dict);
  328. return false;
  329. }
  330. }
  331. ret = avformat_write_header(data->output, &dict);
  332. if (ret < 0) {
  333. ffmpeg_log_error(LOG_WARNING, data, "Error opening '%s': %s", data->config.url, av_err2str(ret));
  334. return false;
  335. }
  336. if (av_dict_count(dict) > 0) {
  337. struct dstr str = {0};
  338. AVDictionaryEntry *entry = NULL;
  339. while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX)))
  340. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  341. blog(LOG_INFO, "Invalid muxer settings: %s", str.array);
  342. dstr_free(&str);
  343. }
  344. av_dict_free(&dict);
  345. return true;
  346. }
  347. static void close_video(struct ffmpeg_data *data)
  348. {
  349. avcodec_free_context(&data->video_ctx);
  350. av_frame_unref(data->vframe);
  351. // This format for some reason derefs video frame
  352. // too many times
  353. if (data->vcodec->id == AV_CODEC_ID_A64_MULTI || data->vcodec->id == AV_CODEC_ID_A64_MULTI5)
  354. return;
  355. av_frame_free(&data->vframe);
  356. }
  357. static void close_audio(struct ffmpeg_data *data)
  358. {
  359. for (int idx = 0; idx < data->num_audio_streams; idx++) {
  360. for (size_t i = 0; i < MAX_AV_PLANES; i++)
  361. deque_free(&data->excess_frames[idx][i]);
  362. if (data->samples[idx][0])
  363. av_freep(&data->samples[idx][0]);
  364. if (data->audio_infos[idx].ctx)
  365. avcodec_free_context(&data->audio_infos[idx].ctx);
  366. if (data->aframe[idx])
  367. av_frame_free(&data->aframe[idx]);
  368. }
  369. }
  370. void ffmpeg_data_free(struct ffmpeg_data *data)
  371. {
  372. if (data->initialized)
  373. av_write_trailer(data->output);
  374. if (data->video)
  375. close_video(data);
  376. if (data->audio_infos) {
  377. close_audio(data);
  378. free(data->audio_infos);
  379. data->audio_infos = NULL;
  380. }
  381. if (data->output) {
  382. if ((data->output->oformat->flags & AVFMT_NOFILE) == 0)
  383. avio_close(data->output->pb);
  384. avformat_free_context(data->output);
  385. }
  386. if (data->last_error)
  387. bfree(data->last_error);
  388. memset(data, 0, sizeof(struct ffmpeg_data));
  389. }
  390. static inline const char *safe_str(const char *s)
  391. {
  392. if (s == NULL)
  393. return "(NULL)";
  394. else
  395. return s;
  396. }
  397. bool ffmpeg_data_init(struct ffmpeg_data *data, struct ffmpeg_cfg *config)
  398. {
  399. bool is_rtmp = false;
  400. memset(data, 0, sizeof(struct ffmpeg_data));
  401. data->config = *config;
  402. data->num_audio_streams = config->audio_mix_count;
  403. data->audio_tracks = config->audio_tracks;
  404. if (!config->url || !*config->url)
  405. return false;
  406. avformat_network_init();
  407. is_rtmp = (astrcmpi_n(config->url, "rtmp://", 7) == 0);
  408. const AVOutputFormat *output_format = av_guess_format(is_rtmp ? "flv" : data->config.format_name,
  409. data->config.url,
  410. is_rtmp ? NULL : data->config.format_mime_type);
  411. if (output_format == NULL) {
  412. ffmpeg_log_error(LOG_WARNING, data,
  413. "Couldn't find matching output format with "
  414. "parameters: name=%s, url=%s, mime=%s",
  415. safe_str(is_rtmp ? "flv" : data->config.format_name), safe_str(data->config.url),
  416. safe_str(is_rtmp ? NULL : data->config.format_mime_type));
  417. goto fail;
  418. }
  419. avformat_alloc_output_context2(&data->output, output_format, NULL, data->config.url);
  420. if (!data->output) {
  421. ffmpeg_log_error(LOG_WARNING, data, "Couldn't create avformat context");
  422. goto fail;
  423. }
  424. if (is_rtmp) {
  425. data->config.audio_encoder_id = AV_CODEC_ID_AAC;
  426. data->config.video_encoder_id = AV_CODEC_ID_H264;
  427. }
  428. if (!init_streams(data))
  429. goto fail;
  430. if (!open_output_file(data))
  431. goto fail;
  432. av_dump_format(data->output, 0, NULL, 1);
  433. data->initialized = true;
  434. return true;
  435. fail:
  436. blog(LOG_WARNING, "ffmpeg_data_init failed");
  437. return false;
  438. }
  439. /* ------------------------------------------------------------------------- */
  440. static inline bool stopping(struct ffmpeg_output *output)
  441. {
  442. return os_atomic_load_bool(&output->stopping);
  443. }
  444. static const char *ffmpeg_output_getname(void *unused)
  445. {
  446. UNUSED_PARAMETER(unused);
  447. return obs_module_text("FFmpegOutput");
  448. }
  449. static void ffmpeg_log_callback(void *param, int level, const char *format, va_list args)
  450. {
  451. if (level <= AV_LOG_INFO)
  452. blogva(LOG_DEBUG, format, args);
  453. UNUSED_PARAMETER(param);
  454. }
  455. static void *ffmpeg_output_create(obs_data_t *settings, obs_output_t *output)
  456. {
  457. struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
  458. pthread_mutex_init_value(&data->write_mutex);
  459. data->output = output;
  460. if (pthread_mutex_init(&data->write_mutex, NULL) != 0)
  461. goto fail;
  462. if (os_event_init(&data->stop_event, OS_EVENT_TYPE_AUTO) != 0)
  463. goto fail;
  464. if (os_sem_init(&data->write_sem, 0) != 0)
  465. goto fail;
  466. av_log_set_callback(ffmpeg_log_callback);
  467. UNUSED_PARAMETER(settings);
  468. return data;
  469. fail:
  470. pthread_mutex_destroy(&data->write_mutex);
  471. os_event_destroy(data->stop_event);
  472. bfree(data);
  473. return NULL;
  474. }
  475. static void ffmpeg_output_full_stop(void *data);
  476. static void ffmpeg_deactivate(struct ffmpeg_output *output);
  477. static void ffmpeg_output_destroy(void *data)
  478. {
  479. struct ffmpeg_output *output = data;
  480. if (output) {
  481. if (output->connecting)
  482. pthread_join(output->start_thread, NULL);
  483. ffmpeg_output_full_stop(output);
  484. pthread_mutex_destroy(&output->write_mutex);
  485. os_sem_destroy(output->write_sem);
  486. os_event_destroy(output->stop_event);
  487. bfree(data);
  488. }
  489. }
  490. static inline void copy_data(AVFrame *pic, const struct video_data *frame, int height, enum AVPixelFormat format)
  491. {
  492. int h_chroma_shift, v_chroma_shift;
  493. av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift, &v_chroma_shift);
  494. for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
  495. if (!frame->data[plane])
  496. continue;
  497. int frame_rowsize = (int)frame->linesize[plane];
  498. int pic_rowsize = pic->linesize[plane];
  499. int bytes = frame_rowsize < pic_rowsize ? frame_rowsize : pic_rowsize;
  500. int plane_height = height >> (plane ? v_chroma_shift : 0);
  501. for (int y = 0; y < plane_height; y++) {
  502. int pos_frame = y * frame_rowsize;
  503. int pos_pic = y * pic_rowsize;
  504. memcpy(pic->data[plane] + pos_pic, frame->data[plane] + pos_frame, bytes);
  505. }
  506. }
  507. }
  508. static void receive_video(void *param, struct video_data *frame)
  509. {
  510. struct ffmpeg_output *output = param;
  511. struct ffmpeg_data *data = &output->ff_data;
  512. // codec doesn't support video or none configured
  513. if (!data->video)
  514. return;
  515. AVCodecContext *context = data->video_ctx;
  516. AVPacket *packet = NULL;
  517. int ret = 0, got_packet;
  518. if (!output->video_start_ts)
  519. output->video_start_ts = frame->timestamp;
  520. if (!data->start_timestamp)
  521. data->start_timestamp = frame->timestamp;
  522. ret = av_frame_make_writable(data->vframe);
  523. if (ret < 0) {
  524. blog(LOG_WARNING,
  525. "receive_video: Error obtaining writable "
  526. "AVFrame: %s",
  527. av_err2str(ret));
  528. //FIXME: stop the encode with an error
  529. return;
  530. }
  531. if (!!data->swscale)
  532. sws_scale(data->swscale, (const uint8_t *const *)frame->data, (const int *)frame->linesize, 0,
  533. data->config.height, data->vframe->data, data->vframe->linesize);
  534. else
  535. copy_data(data->vframe, frame, context->height, context->pix_fmt);
  536. packet = av_packet_alloc();
  537. data->vframe->pts = data->total_frames;
  538. ret = avcodec_send_frame(context, data->vframe);
  539. if (ret == 0)
  540. ret = avcodec_receive_packet(context, packet);
  541. got_packet = (ret == 0);
  542. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  543. ret = 0;
  544. if (ret < 0) {
  545. blog(LOG_WARNING,
  546. "receive_video: Error encoding "
  547. "video: %s",
  548. av_err2str(ret));
  549. //FIXME: stop the encode with an error
  550. goto fail;
  551. }
  552. if (!ret && got_packet && packet->size) {
  553. packet->pts = rescale_ts(packet->pts, context, data->video->time_base);
  554. packet->dts = rescale_ts(packet->dts, context, data->video->time_base);
  555. packet->duration = (int)av_rescale_q(packet->duration, context->time_base, data->video->time_base);
  556. pthread_mutex_lock(&output->write_mutex);
  557. da_push_back(output->packets, &packet);
  558. packet = NULL;
  559. pthread_mutex_unlock(&output->write_mutex);
  560. os_sem_post(output->write_sem);
  561. } else {
  562. ret = 0;
  563. }
  564. if (ret != 0) {
  565. blog(LOG_WARNING, "receive_video: Error writing video: %s", av_err2str(ret));
  566. //FIXME: stop the encode with an error
  567. }
  568. data->total_frames++;
  569. fail:
  570. av_packet_free(&packet);
  571. }
  572. static void encode_audio(struct ffmpeg_output *output, int idx, struct AVCodecContext *context, size_t block_size)
  573. {
  574. struct ffmpeg_data *data = &output->ff_data;
  575. AVPacket *packet = NULL;
  576. int ret, got_packet;
  577. int channels = context->ch_layout.nb_channels;
  578. size_t total_size = data->frame_size * block_size * channels;
  579. data->aframe[idx]->nb_samples = data->frame_size;
  580. data->aframe[idx]->pts =
  581. av_rescale_q(data->total_samples[idx], (AVRational){1, context->sample_rate}, context->time_base);
  582. ret = avcodec_fill_audio_frame(data->aframe[idx], channels, context->sample_fmt, data->samples[idx][0],
  583. (int)total_size, 1);
  584. if (ret < 0) {
  585. blog(LOG_WARNING,
  586. "encode_audio: avcodec_fill_audio_frame "
  587. "failed: %s",
  588. av_err2str(ret));
  589. //FIXME: stop the encode with an error
  590. return;
  591. }
  592. data->total_samples[idx] += data->frame_size;
  593. packet = av_packet_alloc();
  594. ret = avcodec_send_frame(context, data->aframe[idx]);
  595. if (ret == 0)
  596. ret = avcodec_receive_packet(context, packet);
  597. got_packet = (ret == 0);
  598. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  599. ret = 0;
  600. if (ret < 0) {
  601. blog(LOG_WARNING, "encode_audio: Error encoding audio: %s", av_err2str(ret));
  602. //FIXME: stop the encode with an error
  603. goto fail;
  604. }
  605. if (!got_packet)
  606. goto fail;
  607. packet->pts = rescale_ts(packet->pts, context, data->audio_infos[idx].stream->time_base);
  608. packet->dts = rescale_ts(packet->dts, context, data->audio_infos[idx].stream->time_base);
  609. packet->duration =
  610. (int)av_rescale_q(packet->duration, context->time_base, data->audio_infos[idx].stream->time_base);
  611. packet->stream_index = data->audio_infos[idx].stream->index;
  612. pthread_mutex_lock(&output->write_mutex);
  613. da_push_back(output->packets, &packet);
  614. pthread_mutex_unlock(&output->write_mutex);
  615. os_sem_post(output->write_sem);
  616. return;
  617. fail:
  618. av_packet_free(&packet);
  619. }
  620. /* Given a bitmask for the selected tracks and the mix index,
  621. * this returns the stream index which will be passed to the muxer. */
  622. static int get_track_order(int track_config, size_t mix_index)
  623. {
  624. int position = 0;
  625. for (size_t i = 0; i < mix_index; i++) {
  626. if (track_config & 1 << i)
  627. position++;
  628. }
  629. return position;
  630. }
  631. static void receive_audio(void *param, size_t mix_idx, struct audio_data *frame)
  632. {
  633. struct ffmpeg_output *output = param;
  634. struct ffmpeg_data *data = &output->ff_data;
  635. size_t frame_size_bytes;
  636. struct audio_data in = *frame;
  637. int track_order;
  638. // codec doesn't support audio or none configured
  639. if (!data->audio_infos)
  640. return;
  641. /* check that the track was selected */
  642. if ((data->audio_tracks & (1 << mix_idx)) == 0)
  643. return;
  644. /* get track order (first selected, etc ...) */
  645. track_order = get_track_order(data->audio_tracks, mix_idx);
  646. AVCodecContext *context = data->audio_infos[track_order].ctx;
  647. if (!data->start_timestamp && data->video)
  648. return;
  649. if (!output->audio_start_ts)
  650. output->audio_start_ts = in.timestamp;
  651. frame_size_bytes = (size_t)data->frame_size * data->audio_size;
  652. for (size_t i = 0; i < data->audio_planes; i++)
  653. deque_push_back(&data->excess_frames[track_order][i], in.data[i], in.frames * data->audio_size);
  654. while (data->excess_frames[track_order][0].size >= frame_size_bytes) {
  655. for (size_t i = 0; i < data->audio_planes; i++)
  656. deque_pop_front(&data->excess_frames[track_order][i], data->samples[track_order][i],
  657. frame_size_bytes);
  658. encode_audio(output, track_order, context, data->audio_size);
  659. }
  660. }
  661. static uint64_t get_packet_sys_dts(struct ffmpeg_output *output, AVPacket *packet)
  662. {
  663. struct ffmpeg_data *data = &output->ff_data;
  664. uint64_t pause_offset = obs_output_get_pause_offset(output->output);
  665. uint64_t start_ts;
  666. AVRational time_base;
  667. if (data->video && data->video->index == packet->stream_index) {
  668. time_base = data->video->time_base;
  669. start_ts = output->video_start_ts;
  670. } else {
  671. time_base = data->audio_infos[0].stream->time_base;
  672. start_ts = output->audio_start_ts;
  673. }
  674. return start_ts + pause_offset + (uint64_t)av_rescale_q(packet->dts, time_base, (AVRational){1, 1000000000});
  675. }
  676. static int process_packet(struct ffmpeg_output *output)
  677. {
  678. AVPacket *packet = NULL;
  679. int ret = 0;
  680. pthread_mutex_lock(&output->write_mutex);
  681. if (output->packets.num) {
  682. packet = output->packets.array[0];
  683. da_erase(output->packets, 0);
  684. }
  685. pthread_mutex_unlock(&output->write_mutex);
  686. if (!packet)
  687. return 0;
  688. /*blog(LOG_DEBUG, "size = %d, flags = %lX, stream = %d, "
  689. "packets queued: %lu",
  690. packet.size, packet.flags,
  691. packet.stream_index, output->packets.num);*/
  692. if (stopping(output)) {
  693. uint64_t sys_ts = get_packet_sys_dts(output, packet);
  694. if (sys_ts >= output->stop_ts) {
  695. ret = 0;
  696. goto end;
  697. }
  698. }
  699. output->total_bytes += packet->size;
  700. ret = av_interleaved_write_frame(output->ff_data.output, packet);
  701. if (ret < 0) {
  702. ffmpeg_log_error(LOG_WARNING, &output->ff_data, "process_packet: Error writing packet: %s",
  703. av_err2str(ret));
  704. }
  705. end:
  706. av_packet_free(&packet);
  707. return ret;
  708. }
  709. static void *write_thread(void *data)
  710. {
  711. struct ffmpeg_output *output = data;
  712. while (os_sem_wait(output->write_sem) == 0) {
  713. /* check to see if shutting down */
  714. if (os_event_try(output->stop_event) == 0)
  715. break;
  716. int ret = process_packet(output);
  717. if (ret != 0) {
  718. int code = OBS_OUTPUT_ERROR;
  719. pthread_detach(output->write_thread);
  720. output->write_thread_active = false;
  721. if (ret == -ENOSPC)
  722. code = OBS_OUTPUT_NO_SPACE;
  723. obs_output_signal_stop(output->output, code);
  724. ffmpeg_deactivate(output);
  725. break;
  726. }
  727. }
  728. output->active = false;
  729. return NULL;
  730. }
  731. static inline const char *get_string_or_null(obs_data_t *settings, const char *name)
  732. {
  733. const char *value = obs_data_get_string(settings, name);
  734. if (!value || !strlen(value))
  735. return NULL;
  736. return value;
  737. }
  738. static int get_audio_mix_count(int audio_mix_mask)
  739. {
  740. int mix_count = 0;
  741. for (int i = 0; i < MAX_AUDIO_MIXES; i++) {
  742. if ((audio_mix_mask & (1 << i)) != 0) {
  743. mix_count++;
  744. }
  745. }
  746. return mix_count;
  747. }
  748. static bool try_connect(struct ffmpeg_output *output)
  749. {
  750. video_t *video = obs_output_video(output->output);
  751. const struct video_output_info *voi = video_output_get_info(video);
  752. struct ffmpeg_cfg config;
  753. obs_data_t *settings;
  754. bool success;
  755. int ret;
  756. settings = obs_output_get_settings(output->output);
  757. obs_data_set_default_int(settings, "gop_size", 120);
  758. config.url = obs_data_get_string(settings, "url");
  759. config.format_name = get_string_or_null(settings, "format_name");
  760. config.format_mime_type = get_string_or_null(settings, "format_mime_type");
  761. config.muxer_settings = obs_data_get_string(settings, "muxer_settings");
  762. config.video_bitrate = (int)obs_data_get_int(settings, "video_bitrate");
  763. config.audio_bitrate = (int)obs_data_get_int(settings, "audio_bitrate");
  764. config.gop_size = (int)obs_data_get_int(settings, "gop_size");
  765. config.video_encoder = get_string_or_null(settings, "video_encoder");
  766. config.video_encoder_id = (int)obs_data_get_int(settings, "video_encoder_id");
  767. config.audio_encoder = get_string_or_null(settings, "audio_encoder");
  768. config.audio_encoder_id = (int)obs_data_get_int(settings, "audio_encoder_id");
  769. config.video_settings = obs_data_get_string(settings, "video_settings");
  770. config.audio_settings = obs_data_get_string(settings, "audio_settings");
  771. config.scale_width = (int)obs_data_get_int(settings, "scale_width");
  772. config.scale_height = (int)obs_data_get_int(settings, "scale_height");
  773. config.width = (int)obs_output_get_width(output->output);
  774. config.height = (int)obs_output_get_height(output->output);
  775. config.format = obs_to_ffmpeg_video_format(video_output_get_format(video));
  776. config.audio_tracks = (int)obs_output_get_mixers(output->output);
  777. config.audio_mix_count = get_audio_mix_count(config.audio_tracks);
  778. config.color_range = voi->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
  779. config.colorspace = format_is_yuv(voi->format) ? AVCOL_SPC_BT709 : AVCOL_SPC_RGB;
  780. switch (voi->colorspace) {
  781. case VIDEO_CS_601:
  782. config.color_primaries = AVCOL_PRI_SMPTE170M;
  783. config.color_trc = AVCOL_TRC_SMPTE170M;
  784. config.colorspace = AVCOL_SPC_SMPTE170M;
  785. break;
  786. case VIDEO_CS_DEFAULT:
  787. case VIDEO_CS_709:
  788. config.color_primaries = AVCOL_PRI_BT709;
  789. config.color_trc = AVCOL_TRC_BT709;
  790. config.colorspace = AVCOL_SPC_BT709;
  791. break;
  792. case VIDEO_CS_SRGB:
  793. config.color_primaries = AVCOL_PRI_BT709;
  794. config.color_trc = AVCOL_TRC_IEC61966_2_1;
  795. config.colorspace = AVCOL_SPC_BT709;
  796. break;
  797. case VIDEO_CS_2100_PQ:
  798. config.color_primaries = AVCOL_PRI_BT2020;
  799. config.color_trc = AVCOL_TRC_SMPTE2084;
  800. config.colorspace = AVCOL_SPC_BT2020_NCL;
  801. break;
  802. case VIDEO_CS_2100_HLG:
  803. config.color_primaries = AVCOL_PRI_BT2020;
  804. config.color_trc = AVCOL_TRC_ARIB_STD_B67;
  805. config.colorspace = AVCOL_SPC_BT2020_NCL;
  806. break;
  807. }
  808. if (config.format == AV_PIX_FMT_NONE) {
  809. blog(LOG_DEBUG, "invalid pixel format used for FFmpeg output");
  810. return false;
  811. }
  812. if (!config.scale_width)
  813. config.scale_width = config.width;
  814. if (!config.scale_height)
  815. config.scale_height = config.height;
  816. obs_data_array_t *audioNames = obs_data_get_array(settings, "audio_names");
  817. if (audioNames) {
  818. for (size_t i = 0, idx = 0; i < MAX_AUDIO_MIXES; i++) {
  819. if ((config.audio_tracks & (1 << i)) == 0)
  820. continue;
  821. obs_data_t *item_data = obs_data_array_item(audioNames, i);
  822. config.audio_stream_names[idx] = obs_data_get_string(item_data, "name");
  823. obs_data_release(item_data);
  824. idx++;
  825. }
  826. obs_data_array_release(audioNames);
  827. } else {
  828. for (int idx = 0; idx < config.audio_mix_count; idx++)
  829. config.audio_stream_names[idx] = NULL;
  830. }
  831. success = ffmpeg_data_init(&output->ff_data, &config);
  832. obs_data_release(settings);
  833. if (!success) {
  834. if (output->ff_data.last_error) {
  835. obs_output_set_last_error(output->output, output->ff_data.last_error);
  836. }
  837. ffmpeg_data_free(&output->ff_data);
  838. return false;
  839. }
  840. struct audio_convert_info aci = {.format = output->ff_data.audio_format};
  841. output->active = true;
  842. if (!obs_output_can_begin_data_capture(output->output, 0))
  843. return false;
  844. ret = pthread_create(&output->write_thread, NULL, write_thread, output);
  845. if (ret != 0) {
  846. ffmpeg_log_error(LOG_WARNING, &output->ff_data,
  847. "ffmpeg_output_start: failed to create write "
  848. "thread.");
  849. ffmpeg_output_full_stop(output);
  850. return false;
  851. }
  852. obs_output_set_video_conversion(output->output, NULL);
  853. obs_output_set_audio_conversion(output->output, &aci);
  854. obs_output_begin_data_capture(output->output, 0);
  855. output->write_thread_active = true;
  856. return true;
  857. }
  858. static void *start_thread(void *data)
  859. {
  860. struct ffmpeg_output *output = data;
  861. if (!try_connect(output))
  862. obs_output_signal_stop(output->output, OBS_OUTPUT_CONNECT_FAILED);
  863. output->connecting = false;
  864. return NULL;
  865. }
  866. static bool ffmpeg_output_start(void *data)
  867. {
  868. struct ffmpeg_output *output = data;
  869. int ret;
  870. if (output->connecting)
  871. return false;
  872. os_atomic_set_bool(&output->stopping, false);
  873. output->audio_start_ts = 0;
  874. output->video_start_ts = 0;
  875. output->total_bytes = 0;
  876. ret = pthread_create(&output->start_thread, NULL, start_thread, output);
  877. return (output->connecting = (ret == 0));
  878. }
  879. static void ffmpeg_output_full_stop(void *data)
  880. {
  881. struct ffmpeg_output *output = data;
  882. if (output->active) {
  883. obs_output_end_data_capture(output->output);
  884. ffmpeg_deactivate(output);
  885. }
  886. }
  887. static void ffmpeg_output_stop(void *data, uint64_t ts)
  888. {
  889. struct ffmpeg_output *output = data;
  890. if (output->active) {
  891. if (ts > 0) {
  892. output->stop_ts = ts;
  893. os_atomic_set_bool(&output->stopping, true);
  894. }
  895. ffmpeg_output_full_stop(output);
  896. }
  897. }
  898. static void ffmpeg_deactivate(struct ffmpeg_output *output)
  899. {
  900. if (output->write_thread_active) {
  901. os_event_signal(output->stop_event);
  902. os_sem_post(output->write_sem);
  903. pthread_join(output->write_thread, NULL);
  904. output->write_thread_active = false;
  905. }
  906. pthread_mutex_lock(&output->write_mutex);
  907. for (size_t i = 0; i < output->packets.num; i++)
  908. av_packet_free(output->packets.array + i);
  909. da_free(output->packets);
  910. pthread_mutex_unlock(&output->write_mutex);
  911. ffmpeg_data_free(&output->ff_data);
  912. }
  913. static uint64_t ffmpeg_output_total_bytes(void *data)
  914. {
  915. struct ffmpeg_output *output = data;
  916. return output->total_bytes;
  917. }
  918. struct obs_output_info ffmpeg_output = {
  919. .id = "ffmpeg_output",
  920. .flags = OBS_OUTPUT_AUDIO | OBS_OUTPUT_VIDEO | OBS_OUTPUT_MULTI_TRACK | OBS_OUTPUT_CAN_PAUSE,
  921. .get_name = ffmpeg_output_getname,
  922. .create = ffmpeg_output_create,
  923. .destroy = ffmpeg_output_destroy,
  924. .start = ffmpeg_output_start,
  925. .stop = ffmpeg_output_stop,
  926. .raw_video = receive_video,
  927. .raw_audio2 = receive_audio,
  928. .get_total_bytes = ffmpeg_output_total_bytes,
  929. };