obs-ffmpeg-output.c 34 KB

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