obs-ffmpeg-output.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  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. avcodec_free_context(&data->video_ctx);
  368. av_frame_unref(data->vframe);
  369. // This format for some reason derefs video frame
  370. // too many times
  371. if (data->vcodec->id == AV_CODEC_ID_A64_MULTI ||
  372. data->vcodec->id == AV_CODEC_ID_A64_MULTI5)
  373. return;
  374. av_frame_free(&data->vframe);
  375. }
  376. static void close_audio(struct ffmpeg_data *data)
  377. {
  378. for (int idx = 0; idx < data->num_audio_streams; idx++) {
  379. for (size_t i = 0; i < MAX_AV_PLANES; i++)
  380. circlebuf_free(&data->excess_frames[idx][i]);
  381. if (data->samples[idx][0])
  382. av_freep(&data->samples[idx][0]);
  383. if (data->audio_infos[idx].ctx)
  384. avcodec_free_context(&data->audio_infos[idx].ctx);
  385. if (data->aframe[idx])
  386. av_frame_free(&data->aframe[idx]);
  387. }
  388. }
  389. void ffmpeg_data_free(struct ffmpeg_data *data)
  390. {
  391. if (data->initialized)
  392. av_write_trailer(data->output);
  393. if (data->video)
  394. close_video(data);
  395. if (data->audio_infos) {
  396. close_audio(data);
  397. free(data->audio_infos);
  398. data->audio_infos = NULL;
  399. }
  400. if (data->output) {
  401. if ((data->output->oformat->flags & AVFMT_NOFILE) == 0)
  402. avio_close(data->output->pb);
  403. avformat_free_context(data->output);
  404. }
  405. if (data->last_error)
  406. bfree(data->last_error);
  407. memset(data, 0, sizeof(struct ffmpeg_data));
  408. }
  409. static inline const char *safe_str(const char *s)
  410. {
  411. if (s == NULL)
  412. return "(NULL)";
  413. else
  414. return s;
  415. }
  416. static enum AVCodecID get_codec_id(const char *name, int id)
  417. {
  418. AVCodec *codec;
  419. if (id != 0)
  420. return (enum AVCodecID)id;
  421. if (!name || !*name)
  422. return AV_CODEC_ID_NONE;
  423. codec = avcodec_find_encoder_by_name(name);
  424. if (!codec)
  425. return AV_CODEC_ID_NONE;
  426. return codec->id;
  427. }
  428. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  429. static void set_encoder_ids(struct ffmpeg_data *data)
  430. {
  431. data->output->oformat->video_codec = get_codec_id(
  432. data->config.video_encoder, data->config.video_encoder_id);
  433. data->output->oformat->audio_codec = get_codec_id(
  434. data->config.audio_encoder, data->config.audio_encoder_id);
  435. }
  436. #endif
  437. bool ffmpeg_data_init(struct ffmpeg_data *data, struct ffmpeg_cfg *config)
  438. {
  439. bool is_rtmp = false;
  440. memset(data, 0, sizeof(struct ffmpeg_data));
  441. data->config = *config;
  442. data->num_audio_streams = config->audio_mix_count;
  443. data->audio_tracks = config->audio_tracks;
  444. if (!config->url || !*config->url)
  445. return false;
  446. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  447. av_register_all();
  448. #endif
  449. avformat_network_init();
  450. is_rtmp = (astrcmpi_n(config->url, "rtmp://", 7) == 0);
  451. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  452. AVOutputFormat *output_format;
  453. #else
  454. const AVOutputFormat *output_format;
  455. #endif
  456. output_format = av_guess_format(
  457. is_rtmp ? "flv" : data->config.format_name, data->config.url,
  458. is_rtmp ? NULL : data->config.format_mime_type);
  459. if (output_format == NULL) {
  460. ffmpeg_log_error(
  461. LOG_WARNING, data,
  462. "Couldn't find matching output format with "
  463. "parameters: name=%s, url=%s, mime=%s",
  464. safe_str(is_rtmp ? "flv" : data->config.format_name),
  465. safe_str(data->config.url),
  466. safe_str(is_rtmp ? NULL
  467. : data->config.format_mime_type));
  468. goto fail;
  469. }
  470. avformat_alloc_output_context2(&data->output, output_format, NULL,
  471. data->config.url);
  472. if (!data->output) {
  473. ffmpeg_log_error(LOG_WARNING, data,
  474. "Couldn't create avformat context");
  475. goto fail;
  476. }
  477. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  478. if (is_rtmp) {
  479. data->output->oformat->video_codec = AV_CODEC_ID_H264;
  480. data->output->oformat->audio_codec = AV_CODEC_ID_AAC;
  481. } else {
  482. if (data->config.format_name)
  483. set_encoder_ids(data);
  484. }
  485. #else
  486. if (is_rtmp) {
  487. data->config.audio_encoder = "aac";
  488. data->config.audio_encoder_id = AV_CODEC_ID_AAC;
  489. data->config.video_encoder = "libx264";
  490. data->config.video_encoder_id = AV_CODEC_ID_H264;
  491. }
  492. #endif
  493. if (!init_streams(data))
  494. goto fail;
  495. if (!open_output_file(data))
  496. goto fail;
  497. av_dump_format(data->output, 0, NULL, 1);
  498. data->initialized = true;
  499. return true;
  500. fail:
  501. blog(LOG_WARNING, "ffmpeg_data_init failed");
  502. return false;
  503. }
  504. /* ------------------------------------------------------------------------- */
  505. static inline bool stopping(struct ffmpeg_output *output)
  506. {
  507. return os_atomic_load_bool(&output->stopping);
  508. }
  509. static const char *ffmpeg_output_getname(void *unused)
  510. {
  511. UNUSED_PARAMETER(unused);
  512. return obs_module_text("FFmpegOutput");
  513. }
  514. static void ffmpeg_log_callback(void *param, int level, const char *format,
  515. va_list args)
  516. {
  517. if (level <= AV_LOG_INFO)
  518. blogva(LOG_DEBUG, format, args);
  519. UNUSED_PARAMETER(param);
  520. }
  521. static void *ffmpeg_output_create(obs_data_t *settings, obs_output_t *output)
  522. {
  523. struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
  524. pthread_mutex_init_value(&data->write_mutex);
  525. data->output = output;
  526. if (pthread_mutex_init(&data->write_mutex, NULL) != 0)
  527. goto fail;
  528. if (os_event_init(&data->stop_event, OS_EVENT_TYPE_AUTO) != 0)
  529. goto fail;
  530. if (os_sem_init(&data->write_sem, 0) != 0)
  531. goto fail;
  532. av_log_set_callback(ffmpeg_log_callback);
  533. UNUSED_PARAMETER(settings);
  534. return data;
  535. fail:
  536. pthread_mutex_destroy(&data->write_mutex);
  537. os_event_destroy(data->stop_event);
  538. bfree(data);
  539. return NULL;
  540. }
  541. static void ffmpeg_output_full_stop(void *data);
  542. static void ffmpeg_deactivate(struct ffmpeg_output *output);
  543. static void ffmpeg_output_destroy(void *data)
  544. {
  545. struct ffmpeg_output *output = data;
  546. if (output) {
  547. if (output->connecting)
  548. pthread_join(output->start_thread, NULL);
  549. ffmpeg_output_full_stop(output);
  550. pthread_mutex_destroy(&output->write_mutex);
  551. os_sem_destroy(output->write_sem);
  552. os_event_destroy(output->stop_event);
  553. bfree(data);
  554. }
  555. }
  556. static inline void copy_data(AVFrame *pic, const struct video_data *frame,
  557. int height, enum AVPixelFormat format)
  558. {
  559. int h_chroma_shift, v_chroma_shift;
  560. av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift,
  561. &v_chroma_shift);
  562. for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
  563. if (!frame->data[plane])
  564. continue;
  565. int frame_rowsize = (int)frame->linesize[plane];
  566. int pic_rowsize = pic->linesize[plane];
  567. int bytes = frame_rowsize < pic_rowsize ? frame_rowsize
  568. : pic_rowsize;
  569. int plane_height = height >> (plane ? v_chroma_shift : 0);
  570. for (int y = 0; y < plane_height; y++) {
  571. int pos_frame = y * frame_rowsize;
  572. int pos_pic = y * pic_rowsize;
  573. memcpy(pic->data[plane] + pos_pic,
  574. frame->data[plane] + pos_frame, bytes);
  575. }
  576. }
  577. }
  578. static void receive_video(void *param, struct video_data *frame)
  579. {
  580. struct ffmpeg_output *output = param;
  581. struct ffmpeg_data *data = &output->ff_data;
  582. // codec doesn't support video or none configured
  583. if (!data->video)
  584. return;
  585. AVCodecContext *context = data->video_ctx;
  586. AVPacket *packet = NULL;
  587. int ret = 0, got_packet;
  588. if (!output->video_start_ts)
  589. output->video_start_ts = frame->timestamp;
  590. if (!data->start_timestamp)
  591. data->start_timestamp = frame->timestamp;
  592. ret = av_frame_make_writable(data->vframe);
  593. if (ret < 0) {
  594. blog(LOG_WARNING,
  595. "receive_video: Error obtaining writable "
  596. "AVFrame: %s",
  597. av_err2str(ret));
  598. //FIXME: stop the encode with an error
  599. return;
  600. }
  601. if (!!data->swscale)
  602. sws_scale(data->swscale, (const uint8_t *const *)frame->data,
  603. (const int *)frame->linesize, 0, data->config.height,
  604. data->vframe->data, data->vframe->linesize);
  605. else
  606. copy_data(data->vframe, frame, context->height,
  607. context->pix_fmt);
  608. packet = av_packet_alloc();
  609. #if LIBAVFORMAT_VERSION_MAJOR < 58
  610. if (data->output->flags & AVFMT_RAWPICTURE) {
  611. packet->flags |= AV_PKT_FLAG_KEY;
  612. packet->stream_index = data->video->index;
  613. packet->data = data->vframe->data[0];
  614. packet->size = sizeof(AVPicture);
  615. pthread_mutex_lock(&output->write_mutex);
  616. da_push_back(output->packets, &packet);
  617. packet = NULL;
  618. pthread_mutex_unlock(&output->write_mutex);
  619. os_sem_post(output->write_sem);
  620. } else {
  621. #endif
  622. data->vframe->pts = data->total_frames;
  623. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  624. ret = avcodec_send_frame(context, data->vframe);
  625. if (ret == 0)
  626. ret = avcodec_receive_packet(context, packet);
  627. got_packet = (ret == 0);
  628. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  629. ret = 0;
  630. #else
  631. ret = avcodec_encode_video2(context, packet, data->vframe, &got_packet);
  632. #endif
  633. if (ret < 0) {
  634. blog(LOG_WARNING,
  635. "receive_video: Error encoding "
  636. "video: %s",
  637. av_err2str(ret));
  638. //FIXME: stop the encode with an error
  639. goto fail;
  640. }
  641. if (!ret && got_packet && packet->size) {
  642. packet->pts = rescale_ts(packet->pts, context,
  643. data->video->time_base);
  644. packet->dts = rescale_ts(packet->dts, context,
  645. data->video->time_base);
  646. packet->duration = (int)av_rescale_q(
  647. packet->duration, context->time_base,
  648. data->video->time_base);
  649. pthread_mutex_lock(&output->write_mutex);
  650. da_push_back(output->packets, &packet);
  651. packet = NULL;
  652. pthread_mutex_unlock(&output->write_mutex);
  653. os_sem_post(output->write_sem);
  654. } else {
  655. ret = 0;
  656. }
  657. #if LIBAVFORMAT_VERSION_MAJOR < 58
  658. }
  659. #endif
  660. if (ret != 0) {
  661. blog(LOG_WARNING, "receive_video: Error writing video: %s",
  662. av_err2str(ret));
  663. //FIXME: stop the encode with an error
  664. }
  665. data->total_frames++;
  666. fail:
  667. av_packet_free(&packet);
  668. }
  669. static void encode_audio(struct ffmpeg_output *output, int idx,
  670. struct AVCodecContext *context, size_t block_size)
  671. {
  672. struct ffmpeg_data *data = &output->ff_data;
  673. AVPacket *packet = NULL;
  674. int ret, got_packet;
  675. size_t total_size = data->frame_size * block_size * context->channels;
  676. data->aframe[idx]->nb_samples = data->frame_size;
  677. data->aframe[idx]->pts = av_rescale_q(
  678. data->total_samples[idx], (AVRational){1, context->sample_rate},
  679. context->time_base);
  680. ret = avcodec_fill_audio_frame(data->aframe[idx], context->channels,
  681. context->sample_fmt,
  682. data->samples[idx][0], (int)total_size,
  683. 1);
  684. if (ret < 0) {
  685. blog(LOG_WARNING,
  686. "encode_audio: avcodec_fill_audio_frame "
  687. "failed: %s",
  688. av_err2str(ret));
  689. //FIXME: stop the encode with an error
  690. return;
  691. }
  692. data->total_samples[idx] += data->frame_size;
  693. packet = av_packet_alloc();
  694. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  695. ret = avcodec_send_frame(context, data->aframe[idx]);
  696. if (ret == 0)
  697. ret = avcodec_receive_packet(context, packet);
  698. got_packet = (ret == 0);
  699. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  700. ret = 0;
  701. #else
  702. ret = avcodec_encode_audio2(context, packet, data->aframe[idx],
  703. &got_packet);
  704. #endif
  705. if (ret < 0) {
  706. blog(LOG_WARNING, "encode_audio: Error encoding audio: %s",
  707. av_err2str(ret));
  708. //FIXME: stop the encode with an error
  709. goto fail;
  710. }
  711. if (!got_packet)
  712. goto fail;
  713. packet->pts = rescale_ts(packet->pts, context,
  714. data->audio_infos[idx].stream->time_base);
  715. packet->dts = rescale_ts(packet->dts, context,
  716. data->audio_infos[idx].stream->time_base);
  717. packet->duration =
  718. (int)av_rescale_q(packet->duration, context->time_base,
  719. data->audio_infos[idx].stream->time_base);
  720. packet->stream_index = data->audio_infos[idx].stream->index;
  721. pthread_mutex_lock(&output->write_mutex);
  722. da_push_back(output->packets, &packet);
  723. pthread_mutex_unlock(&output->write_mutex);
  724. os_sem_post(output->write_sem);
  725. return;
  726. fail:
  727. av_packet_free(&packet);
  728. }
  729. /* Given a bitmask for the selected tracks and the mix index,
  730. * this returns the stream index which will be passed to the muxer. */
  731. static int get_track_order(int track_config, size_t mix_index)
  732. {
  733. int position = 0;
  734. for (size_t i = 0; i < mix_index; i++) {
  735. if (track_config & 1 << i)
  736. position++;
  737. }
  738. return position;
  739. }
  740. static void receive_audio(void *param, size_t mix_idx, struct audio_data *frame)
  741. {
  742. struct ffmpeg_output *output = param;
  743. struct ffmpeg_data *data = &output->ff_data;
  744. size_t frame_size_bytes;
  745. struct audio_data in = *frame;
  746. int track_order;
  747. // codec doesn't support audio or none configured
  748. if (!data->audio_infos)
  749. return;
  750. /* check that the track was selected */
  751. if ((data->audio_tracks & (1 << mix_idx)) == 0)
  752. return;
  753. /* get track order (first selected, etc ...) */
  754. track_order = get_track_order(data->audio_tracks, mix_idx);
  755. AVCodecContext *context = data->audio_infos[track_order].ctx;
  756. if (!data->start_timestamp && data->video)
  757. return;
  758. if (!output->audio_start_ts)
  759. output->audio_start_ts = in.timestamp;
  760. frame_size_bytes = (size_t)data->frame_size * data->audio_size;
  761. for (size_t i = 0; i < data->audio_planes; i++)
  762. circlebuf_push_back(&data->excess_frames[track_order][i],
  763. in.data[i], in.frames * data->audio_size);
  764. while (data->excess_frames[track_order][0].size >= frame_size_bytes) {
  765. for (size_t i = 0; i < data->audio_planes; i++)
  766. circlebuf_pop_front(
  767. &data->excess_frames[track_order][i],
  768. data->samples[track_order][i],
  769. frame_size_bytes);
  770. encode_audio(output, track_order, context, data->audio_size);
  771. }
  772. }
  773. static uint64_t get_packet_sys_dts(struct ffmpeg_output *output,
  774. AVPacket *packet)
  775. {
  776. struct ffmpeg_data *data = &output->ff_data;
  777. uint64_t pause_offset = obs_output_get_pause_offset(output->output);
  778. uint64_t start_ts;
  779. AVRational time_base;
  780. if (data->video && data->video->index == packet->stream_index) {
  781. time_base = data->video->time_base;
  782. start_ts = output->video_start_ts;
  783. } else {
  784. time_base = data->audio_infos[0].stream->time_base;
  785. start_ts = output->audio_start_ts;
  786. }
  787. return start_ts + pause_offset +
  788. (uint64_t)av_rescale_q(packet->dts, time_base,
  789. (AVRational){1, 1000000000});
  790. }
  791. static int process_packet(struct ffmpeg_output *output)
  792. {
  793. AVPacket *packet;
  794. bool new_packet = false;
  795. int ret;
  796. pthread_mutex_lock(&output->write_mutex);
  797. if (output->packets.num) {
  798. packet = output->packets.array[0];
  799. da_erase(output->packets, 0);
  800. new_packet = true;
  801. }
  802. pthread_mutex_unlock(&output->write_mutex);
  803. if (!new_packet)
  804. return 0;
  805. /*blog(LOG_DEBUG, "size = %d, flags = %lX, stream = %d, "
  806. "packets queued: %lu",
  807. packet.size, packet.flags,
  808. packet.stream_index, output->packets.num);*/
  809. if (stopping(output)) {
  810. uint64_t sys_ts = get_packet_sys_dts(output, packet);
  811. if (sys_ts >= output->stop_ts)
  812. return 0;
  813. }
  814. output->total_bytes += packet->size;
  815. ret = av_interleaved_write_frame(output->ff_data.output, packet);
  816. if (ret < 0) {
  817. av_packet_free(&packet);
  818. ffmpeg_log_error(LOG_WARNING, &output->ff_data,
  819. "process_packet: Error writing packet: %s",
  820. av_err2str(ret));
  821. return ret;
  822. }
  823. return 0;
  824. }
  825. static void *write_thread(void *data)
  826. {
  827. struct ffmpeg_output *output = data;
  828. while (os_sem_wait(output->write_sem) == 0) {
  829. /* check to see if shutting down */
  830. if (os_event_try(output->stop_event) == 0)
  831. break;
  832. int ret = process_packet(output);
  833. if (ret != 0) {
  834. int code = OBS_OUTPUT_ERROR;
  835. pthread_detach(output->write_thread);
  836. output->write_thread_active = false;
  837. if (ret == -ENOSPC)
  838. code = OBS_OUTPUT_NO_SPACE;
  839. obs_output_signal_stop(output->output, code);
  840. ffmpeg_deactivate(output);
  841. break;
  842. }
  843. }
  844. output->active = false;
  845. return NULL;
  846. }
  847. static inline const char *get_string_or_null(obs_data_t *settings,
  848. const char *name)
  849. {
  850. const char *value = obs_data_get_string(settings, name);
  851. if (!value || !strlen(value))
  852. return NULL;
  853. return value;
  854. }
  855. static int get_audio_mix_count(int audio_mix_mask)
  856. {
  857. int mix_count = 0;
  858. for (int i = 0; i < MAX_AUDIO_MIXES; i++) {
  859. if ((audio_mix_mask & (1 << i)) != 0) {
  860. mix_count++;
  861. }
  862. }
  863. return mix_count;
  864. }
  865. static bool try_connect(struct ffmpeg_output *output)
  866. {
  867. video_t *video = obs_output_video(output->output);
  868. const struct video_output_info *voi = video_output_get_info(video);
  869. struct ffmpeg_cfg config;
  870. obs_data_t *settings;
  871. bool success;
  872. int ret;
  873. settings = obs_output_get_settings(output->output);
  874. obs_data_set_default_int(settings, "gop_size", 120);
  875. config.url = obs_data_get_string(settings, "url");
  876. config.format_name = get_string_or_null(settings, "format_name");
  877. config.format_mime_type =
  878. get_string_or_null(settings, "format_mime_type");
  879. config.muxer_settings = obs_data_get_string(settings, "muxer_settings");
  880. config.video_bitrate = (int)obs_data_get_int(settings, "video_bitrate");
  881. config.audio_bitrate = (int)obs_data_get_int(settings, "audio_bitrate");
  882. config.gop_size = (int)obs_data_get_int(settings, "gop_size");
  883. config.video_encoder = get_string_or_null(settings, "video_encoder");
  884. config.video_encoder_id =
  885. (int)obs_data_get_int(settings, "video_encoder_id");
  886. config.audio_encoder = get_string_or_null(settings, "audio_encoder");
  887. config.audio_encoder_id =
  888. (int)obs_data_get_int(settings, "audio_encoder_id");
  889. config.video_settings = obs_data_get_string(settings, "video_settings");
  890. config.audio_settings = obs_data_get_string(settings, "audio_settings");
  891. config.scale_width = (int)obs_data_get_int(settings, "scale_width");
  892. config.scale_height = (int)obs_data_get_int(settings, "scale_height");
  893. config.width = (int)obs_output_get_width(output->output);
  894. config.height = (int)obs_output_get_height(output->output);
  895. config.format =
  896. obs_to_ffmpeg_video_format(video_output_get_format(video));
  897. config.audio_tracks = (int)obs_output_get_mixers(output->output);
  898. config.audio_mix_count = get_audio_mix_count(config.audio_tracks);
  899. config.color_range = voi->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG
  900. : AVCOL_RANGE_MPEG;
  901. config.colorspace = format_is_yuv(voi->format) ? AVCOL_SPC_BT709
  902. : AVCOL_SPC_RGB;
  903. switch (voi->colorspace) {
  904. case VIDEO_CS_601:
  905. config.color_primaries = AVCOL_PRI_SMPTE170M;
  906. config.color_trc = AVCOL_TRC_SMPTE170M;
  907. config.colorspace = AVCOL_SPC_SMPTE170M;
  908. break;
  909. case VIDEO_CS_DEFAULT:
  910. case VIDEO_CS_709:
  911. config.color_primaries = AVCOL_PRI_BT709;
  912. config.color_trc = AVCOL_TRC_BT709;
  913. config.colorspace = AVCOL_SPC_BT709;
  914. break;
  915. case VIDEO_CS_SRGB:
  916. config.color_primaries = AVCOL_PRI_BT709;
  917. config.color_trc = AVCOL_TRC_IEC61966_2_1;
  918. config.colorspace = AVCOL_SPC_BT709;
  919. break;
  920. case VIDEO_CS_2100_PQ:
  921. config.color_primaries = AVCOL_PRI_BT2020;
  922. config.color_trc = AVCOL_TRC_SMPTE2084;
  923. config.colorspace = AVCOL_SPC_BT2020_NCL;
  924. break;
  925. case VIDEO_CS_2100_HLG:
  926. config.color_primaries = AVCOL_PRI_BT2020;
  927. config.color_trc = AVCOL_TRC_ARIB_STD_B67;
  928. config.colorspace = AVCOL_SPC_BT2020_NCL;
  929. break;
  930. }
  931. if (config.format == AV_PIX_FMT_NONE) {
  932. blog(LOG_DEBUG, "invalid pixel format used for FFmpeg output");
  933. return false;
  934. }
  935. if (!config.scale_width)
  936. config.scale_width = config.width;
  937. if (!config.scale_height)
  938. config.scale_height = config.height;
  939. success = ffmpeg_data_init(&output->ff_data, &config);
  940. obs_data_release(settings);
  941. if (!success) {
  942. if (output->ff_data.last_error) {
  943. obs_output_set_last_error(output->output,
  944. output->ff_data.last_error);
  945. }
  946. ffmpeg_data_free(&output->ff_data);
  947. return false;
  948. }
  949. struct audio_convert_info aci = {.format =
  950. output->ff_data.audio_format};
  951. output->active = true;
  952. if (!obs_output_can_begin_data_capture(output->output, 0))
  953. return false;
  954. ret = pthread_create(&output->write_thread, NULL, write_thread, output);
  955. if (ret != 0) {
  956. ffmpeg_log_error(LOG_WARNING, &output->ff_data,
  957. "ffmpeg_output_start: failed to create write "
  958. "thread.");
  959. ffmpeg_output_full_stop(output);
  960. return false;
  961. }
  962. obs_output_set_video_conversion(output->output, NULL);
  963. obs_output_set_audio_conversion(output->output, &aci);
  964. obs_output_begin_data_capture(output->output, 0);
  965. output->write_thread_active = true;
  966. return true;
  967. }
  968. static void *start_thread(void *data)
  969. {
  970. struct ffmpeg_output *output = data;
  971. if (!try_connect(output))
  972. obs_output_signal_stop(output->output,
  973. OBS_OUTPUT_CONNECT_FAILED);
  974. output->connecting = false;
  975. return NULL;
  976. }
  977. static bool ffmpeg_output_start(void *data)
  978. {
  979. struct ffmpeg_output *output = data;
  980. int ret;
  981. if (output->connecting)
  982. return false;
  983. os_atomic_set_bool(&output->stopping, false);
  984. output->audio_start_ts = 0;
  985. output->video_start_ts = 0;
  986. output->total_bytes = 0;
  987. ret = pthread_create(&output->start_thread, NULL, start_thread, output);
  988. return (output->connecting = (ret == 0));
  989. }
  990. static void ffmpeg_output_full_stop(void *data)
  991. {
  992. struct ffmpeg_output *output = data;
  993. if (output->active) {
  994. obs_output_end_data_capture(output->output);
  995. ffmpeg_deactivate(output);
  996. }
  997. }
  998. static void ffmpeg_output_stop(void *data, uint64_t ts)
  999. {
  1000. struct ffmpeg_output *output = data;
  1001. if (output->active) {
  1002. if (ts > 0) {
  1003. output->stop_ts = ts;
  1004. os_atomic_set_bool(&output->stopping, true);
  1005. }
  1006. ffmpeg_output_full_stop(output);
  1007. }
  1008. }
  1009. static void ffmpeg_deactivate(struct ffmpeg_output *output)
  1010. {
  1011. if (output->write_thread_active) {
  1012. os_event_signal(output->stop_event);
  1013. os_sem_post(output->write_sem);
  1014. pthread_join(output->write_thread, NULL);
  1015. output->write_thread_active = false;
  1016. }
  1017. pthread_mutex_lock(&output->write_mutex);
  1018. for (size_t i = 0; i < output->packets.num; i++)
  1019. av_packet_free(output->packets.array + i);
  1020. da_free(output->packets);
  1021. pthread_mutex_unlock(&output->write_mutex);
  1022. ffmpeg_data_free(&output->ff_data);
  1023. }
  1024. static uint64_t ffmpeg_output_total_bytes(void *data)
  1025. {
  1026. struct ffmpeg_output *output = data;
  1027. return output->total_bytes;
  1028. }
  1029. struct obs_output_info ffmpeg_output = {
  1030. .id = "ffmpeg_output",
  1031. .flags = OBS_OUTPUT_AUDIO | OBS_OUTPUT_VIDEO | OBS_OUTPUT_MULTI_TRACK |
  1032. OBS_OUTPUT_CAN_PAUSE,
  1033. .get_name = ffmpeg_output_getname,
  1034. .create = ffmpeg_output_create,
  1035. .destroy = ffmpeg_output_destroy,
  1036. .start = ffmpeg_output_start,
  1037. .stop = ffmpeg_output_stop,
  1038. .raw_video = receive_video,
  1039. .raw_audio2 = receive_audio,
  1040. .get_total_bytes = ffmpeg_output_total_bytes,
  1041. };