obs-ffmpeg-output.c 35 KB

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