obs-ffmpeg-output.c 34 KB

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