obs-ffmpeg-output.c 32 KB

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