obs-ffmpeg-output.c 33 KB

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