obs-ffmpeg-output.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  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 = {0};
  596. int ret = 0, got_packet;
  597. av_init_packet(&packet);
  598. if (!output->video_start_ts)
  599. output->video_start_ts = frame->timestamp;
  600. if (!data->start_timestamp)
  601. data->start_timestamp = frame->timestamp;
  602. ret = av_frame_make_writable(data->vframe);
  603. if (ret < 0) {
  604. blog(LOG_WARNING,
  605. "receive_video: Error obtaining writable "
  606. "AVFrame: %s",
  607. av_err2str(ret));
  608. //FIXME: stop the encode with an error
  609. return;
  610. }
  611. if (!!data->swscale)
  612. sws_scale(data->swscale, (const uint8_t *const *)frame->data,
  613. (const int *)frame->linesize, 0, data->config.height,
  614. data->vframe->data, data->vframe->linesize);
  615. else
  616. copy_data(data->vframe, frame, context->height,
  617. context->pix_fmt);
  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. pthread_mutex_unlock(&output->write_mutex);
  627. os_sem_post(output->write_sem);
  628. } else {
  629. #endif
  630. data->vframe->pts = data->total_frames;
  631. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  632. ret = avcodec_send_frame(context, data->vframe);
  633. if (ret == 0)
  634. ret = avcodec_receive_packet(context, &packet);
  635. got_packet = (ret == 0);
  636. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  637. ret = 0;
  638. #else
  639. ret = avcodec_encode_video2(context, &packet, data->vframe,
  640. &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. return;
  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. pthread_mutex_unlock(&output->write_mutex);
  661. os_sem_post(output->write_sem);
  662. } else {
  663. ret = 0;
  664. }
  665. #if LIBAVFORMAT_VERSION_MAJOR < 58
  666. }
  667. #endif
  668. if (ret != 0) {
  669. blog(LOG_WARNING, "receive_video: Error writing video: %s",
  670. av_err2str(ret));
  671. //FIXME: stop the encode with an error
  672. }
  673. data->total_frames++;
  674. }
  675. static void encode_audio(struct ffmpeg_output *output, int idx,
  676. struct AVCodecContext *context, size_t block_size)
  677. {
  678. struct ffmpeg_data *data = &output->ff_data;
  679. AVPacket packet = {0};
  680. int ret, got_packet;
  681. size_t total_size = data->frame_size * block_size * context->channels;
  682. data->aframe[idx]->nb_samples = data->frame_size;
  683. data->aframe[idx]->pts = av_rescale_q(
  684. data->total_samples[idx], (AVRational){1, context->sample_rate},
  685. context->time_base);
  686. ret = avcodec_fill_audio_frame(data->aframe[idx], context->channels,
  687. context->sample_fmt,
  688. data->samples[idx][0], (int)total_size,
  689. 1);
  690. if (ret < 0) {
  691. blog(LOG_WARNING,
  692. "encode_audio: avcodec_fill_audio_frame "
  693. "failed: %s",
  694. av_err2str(ret));
  695. //FIXME: stop the encode with an error
  696. return;
  697. }
  698. data->total_samples[idx] += data->frame_size;
  699. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  700. ret = avcodec_send_frame(context, data->aframe[idx]);
  701. if (ret == 0)
  702. ret = avcodec_receive_packet(context, &packet);
  703. got_packet = (ret == 0);
  704. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  705. ret = 0;
  706. #else
  707. ret = avcodec_encode_audio2(context, &packet, data->aframe[idx],
  708. &got_packet);
  709. #endif
  710. if (ret < 0) {
  711. blog(LOG_WARNING, "encode_audio: Error encoding audio: %s",
  712. av_err2str(ret));
  713. //FIXME: stop the encode with an error
  714. return;
  715. }
  716. if (!got_packet)
  717. return;
  718. packet.pts = rescale_ts(packet.pts, context,
  719. data->audio_infos[idx].stream->time_base);
  720. packet.dts = rescale_ts(packet.dts, context,
  721. data->audio_infos[idx].stream->time_base);
  722. packet.duration =
  723. (int)av_rescale_q(packet.duration, context->time_base,
  724. data->audio_infos[idx].stream->time_base);
  725. packet.stream_index = data->audio_infos[idx].stream->index;
  726. pthread_mutex_lock(&output->write_mutex);
  727. da_push_back(output->packets, &packet);
  728. pthread_mutex_unlock(&output->write_mutex);
  729. os_sem_post(output->write_sem);
  730. }
  731. /* Given a bitmask for the selected tracks and the mix index,
  732. * this returns the stream index which will be passed to the muxer. */
  733. static int get_track_order(int track_config, size_t mix_index)
  734. {
  735. int position = 0;
  736. for (size_t i = 0; i < mix_index; i++) {
  737. if (track_config & 1 << i)
  738. position++;
  739. }
  740. return position;
  741. }
  742. static void receive_audio(void *param, size_t mix_idx, struct audio_data *frame)
  743. {
  744. struct ffmpeg_output *output = param;
  745. struct ffmpeg_data *data = &output->ff_data;
  746. size_t frame_size_bytes;
  747. struct audio_data in = *frame;
  748. int track_order;
  749. // codec doesn't support audio or none configured
  750. if (!data->audio_infos)
  751. return;
  752. /* check that the track was selected */
  753. if ((data->audio_tracks & (1 << mix_idx)) == 0)
  754. return;
  755. /* get track order (first selected, etc ...) */
  756. track_order = get_track_order(data->audio_tracks, mix_idx);
  757. AVCodecContext *context = data->audio_infos[track_order].ctx;
  758. if (!data->start_timestamp && data->video)
  759. return;
  760. if (!output->audio_start_ts)
  761. output->audio_start_ts = in.timestamp;
  762. frame_size_bytes = (size_t)data->frame_size * data->audio_size;
  763. for (size_t i = 0; i < data->audio_planes; i++)
  764. circlebuf_push_back(&data->excess_frames[track_order][i],
  765. in.data[i], in.frames * data->audio_size);
  766. while (data->excess_frames[track_order][0].size >= frame_size_bytes) {
  767. for (size_t i = 0; i < data->audio_planes; i++)
  768. circlebuf_pop_front(
  769. &data->excess_frames[track_order][i],
  770. data->samples[track_order][i],
  771. frame_size_bytes);
  772. encode_audio(output, track_order, context, data->audio_size);
  773. }
  774. }
  775. static uint64_t get_packet_sys_dts(struct ffmpeg_output *output,
  776. AVPacket *packet)
  777. {
  778. struct ffmpeg_data *data = &output->ff_data;
  779. uint64_t pause_offset = obs_output_get_pause_offset(output->output);
  780. uint64_t start_ts;
  781. AVRational time_base;
  782. if (data->video && data->video->index == packet->stream_index) {
  783. time_base = data->video->time_base;
  784. start_ts = output->video_start_ts;
  785. } else {
  786. time_base = data->audio_infos[0].stream->time_base;
  787. start_ts = output->audio_start_ts;
  788. }
  789. return start_ts + pause_offset +
  790. (uint64_t)av_rescale_q(packet->dts, time_base,
  791. (AVRational){1, 1000000000});
  792. }
  793. static int process_packet(struct ffmpeg_output *output)
  794. {
  795. AVPacket packet;
  796. bool new_packet = false;
  797. int ret;
  798. pthread_mutex_lock(&output->write_mutex);
  799. if (output->packets.num) {
  800. packet = output->packets.array[0];
  801. da_erase(output->packets, 0);
  802. new_packet = true;
  803. }
  804. pthread_mutex_unlock(&output->write_mutex);
  805. if (!new_packet)
  806. return 0;
  807. /*blog(LOG_DEBUG, "size = %d, flags = %lX, stream = %d, "
  808. "packets queued: %lu",
  809. packet.size, packet.flags,
  810. packet.stream_index, output->packets.num);*/
  811. if (stopping(output)) {
  812. uint64_t sys_ts = get_packet_sys_dts(output, &packet);
  813. if (sys_ts >= output->stop_ts)
  814. return 0;
  815. }
  816. output->total_bytes += packet.size;
  817. ret = av_interleaved_write_frame(output->ff_data.output, &packet);
  818. if (ret < 0) {
  819. av_free_packet(&packet);
  820. ffmpeg_log_error(LOG_WARNING, &output->ff_data,
  821. "process_packet: Error writing packet: %s",
  822. av_err2str(ret));
  823. return ret;
  824. }
  825. return 0;
  826. }
  827. static void *write_thread(void *data)
  828. {
  829. struct ffmpeg_output *output = data;
  830. while (os_sem_wait(output->write_sem) == 0) {
  831. /* check to see if shutting down */
  832. if (os_event_try(output->stop_event) == 0)
  833. break;
  834. int ret = process_packet(output);
  835. if (ret != 0) {
  836. int code = OBS_OUTPUT_ERROR;
  837. pthread_detach(output->write_thread);
  838. output->write_thread_active = false;
  839. if (ret == -ENOSPC)
  840. code = OBS_OUTPUT_NO_SPACE;
  841. obs_output_signal_stop(output->output, code);
  842. ffmpeg_deactivate(output);
  843. break;
  844. }
  845. }
  846. output->active = false;
  847. return NULL;
  848. }
  849. static inline const char *get_string_or_null(obs_data_t *settings,
  850. const char *name)
  851. {
  852. const char *value = obs_data_get_string(settings, name);
  853. if (!value || !strlen(value))
  854. return NULL;
  855. return value;
  856. }
  857. static int get_audio_mix_count(int audio_mix_mask)
  858. {
  859. int mix_count = 0;
  860. for (int i = 0; i < MAX_AUDIO_MIXES; i++) {
  861. if ((audio_mix_mask & (1 << i)) != 0) {
  862. mix_count++;
  863. }
  864. }
  865. return mix_count;
  866. }
  867. static bool try_connect(struct ffmpeg_output *output)
  868. {
  869. video_t *video = obs_output_video(output->output);
  870. const struct video_output_info *voi = video_output_get_info(video);
  871. struct ffmpeg_cfg config;
  872. obs_data_t *settings;
  873. bool success;
  874. int ret;
  875. settings = obs_output_get_settings(output->output);
  876. obs_data_set_default_int(settings, "gop_size", 120);
  877. config.url = obs_data_get_string(settings, "url");
  878. config.format_name = get_string_or_null(settings, "format_name");
  879. config.format_mime_type =
  880. get_string_or_null(settings, "format_mime_type");
  881. config.muxer_settings = obs_data_get_string(settings, "muxer_settings");
  882. config.video_bitrate = (int)obs_data_get_int(settings, "video_bitrate");
  883. config.audio_bitrate = (int)obs_data_get_int(settings, "audio_bitrate");
  884. config.gop_size = (int)obs_data_get_int(settings, "gop_size");
  885. config.video_encoder = get_string_or_null(settings, "video_encoder");
  886. config.video_encoder_id =
  887. (int)obs_data_get_int(settings, "video_encoder_id");
  888. config.audio_encoder = get_string_or_null(settings, "audio_encoder");
  889. config.audio_encoder_id =
  890. (int)obs_data_get_int(settings, "audio_encoder_id");
  891. config.video_settings = obs_data_get_string(settings, "video_settings");
  892. config.audio_settings = obs_data_get_string(settings, "audio_settings");
  893. config.scale_width = (int)obs_data_get_int(settings, "scale_width");
  894. config.scale_height = (int)obs_data_get_int(settings, "scale_height");
  895. config.width = (int)obs_output_get_width(output->output);
  896. config.height = (int)obs_output_get_height(output->output);
  897. config.format =
  898. obs_to_ffmpeg_video_format(video_output_get_format(video));
  899. config.audio_tracks = (int)obs_output_get_mixers(output->output);
  900. config.audio_mix_count = get_audio_mix_count(config.audio_tracks);
  901. config.color_range = voi->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG
  902. : AVCOL_RANGE_MPEG;
  903. switch (voi->colorspace) {
  904. case VIDEO_CS_601:
  905. config.color_primaries = AVCOL_PRI_SMPTE170M;
  906. config.color_trc = AVCOL_TRC_SMPTE170M;
  907. break;
  908. case VIDEO_CS_DEFAULT:
  909. case VIDEO_CS_709:
  910. config.color_primaries = AVCOL_PRI_BT709;
  911. config.color_trc = AVCOL_TRC_BT709;
  912. break;
  913. case VIDEO_CS_SRGB:
  914. config.color_primaries = AVCOL_PRI_BT709;
  915. config.color_trc = AVCOL_TRC_IEC61966_2_1;
  916. break;
  917. }
  918. if (format_is_yuv(voi->format)) {
  919. config.colorspace = (voi->colorspace == VIDEO_CS_601)
  920. ? AVCOL_SPC_SMPTE170M
  921. : AVCOL_SPC_BT709;
  922. } else {
  923. config.colorspace = AVCOL_SPC_RGB;
  924. }
  925. if (config.format == AV_PIX_FMT_NONE) {
  926. blog(LOG_DEBUG, "invalid pixel format used for FFmpeg output");
  927. return false;
  928. }
  929. if (!config.scale_width)
  930. config.scale_width = config.width;
  931. if (!config.scale_height)
  932. config.scale_height = config.height;
  933. success = ffmpeg_data_init(&output->ff_data, &config);
  934. obs_data_release(settings);
  935. if (!success) {
  936. if (output->ff_data.last_error) {
  937. obs_output_set_last_error(output->output,
  938. output->ff_data.last_error);
  939. }
  940. ffmpeg_data_free(&output->ff_data);
  941. return false;
  942. }
  943. struct audio_convert_info aci = {.format =
  944. output->ff_data.audio_format};
  945. output->active = true;
  946. if (!obs_output_can_begin_data_capture(output->output, 0))
  947. return false;
  948. ret = pthread_create(&output->write_thread, NULL, write_thread, output);
  949. if (ret != 0) {
  950. ffmpeg_log_error(LOG_WARNING, &output->ff_data,
  951. "ffmpeg_output_start: failed to create write "
  952. "thread.");
  953. ffmpeg_output_full_stop(output);
  954. return false;
  955. }
  956. obs_output_set_video_conversion(output->output, NULL);
  957. obs_output_set_audio_conversion(output->output, &aci);
  958. obs_output_begin_data_capture(output->output, 0);
  959. output->write_thread_active = true;
  960. return true;
  961. }
  962. static void *start_thread(void *data)
  963. {
  964. struct ffmpeg_output *output = data;
  965. if (!try_connect(output))
  966. obs_output_signal_stop(output->output,
  967. OBS_OUTPUT_CONNECT_FAILED);
  968. output->connecting = false;
  969. return NULL;
  970. }
  971. static bool ffmpeg_output_start(void *data)
  972. {
  973. struct ffmpeg_output *output = data;
  974. int ret;
  975. if (output->connecting)
  976. return false;
  977. os_atomic_set_bool(&output->stopping, false);
  978. output->audio_start_ts = 0;
  979. output->video_start_ts = 0;
  980. output->total_bytes = 0;
  981. ret = pthread_create(&output->start_thread, NULL, start_thread, output);
  982. return (output->connecting = (ret == 0));
  983. }
  984. static void ffmpeg_output_full_stop(void *data)
  985. {
  986. struct ffmpeg_output *output = data;
  987. if (output->active) {
  988. obs_output_end_data_capture(output->output);
  989. ffmpeg_deactivate(output);
  990. }
  991. }
  992. static void ffmpeg_output_stop(void *data, uint64_t ts)
  993. {
  994. struct ffmpeg_output *output = data;
  995. if (output->active) {
  996. if (ts > 0) {
  997. output->stop_ts = ts;
  998. os_atomic_set_bool(&output->stopping, true);
  999. }
  1000. ffmpeg_output_full_stop(output);
  1001. }
  1002. }
  1003. static void ffmpeg_deactivate(struct ffmpeg_output *output)
  1004. {
  1005. if (output->write_thread_active) {
  1006. os_event_signal(output->stop_event);
  1007. os_sem_post(output->write_sem);
  1008. pthread_join(output->write_thread, NULL);
  1009. output->write_thread_active = false;
  1010. }
  1011. pthread_mutex_lock(&output->write_mutex);
  1012. for (size_t i = 0; i < output->packets.num; i++)
  1013. av_free_packet(output->packets.array + i);
  1014. da_free(output->packets);
  1015. pthread_mutex_unlock(&output->write_mutex);
  1016. ffmpeg_data_free(&output->ff_data);
  1017. }
  1018. static uint64_t ffmpeg_output_total_bytes(void *data)
  1019. {
  1020. struct ffmpeg_output *output = data;
  1021. return output->total_bytes;
  1022. }
  1023. struct obs_output_info ffmpeg_output = {
  1024. .id = "ffmpeg_output",
  1025. .flags = OBS_OUTPUT_AUDIO | OBS_OUTPUT_VIDEO | OBS_OUTPUT_MULTI_TRACK |
  1026. OBS_OUTPUT_CAN_PAUSE,
  1027. .get_name = ffmpeg_output_getname,
  1028. .create = ffmpeg_output_create,
  1029. .destroy = ffmpeg_output_destroy,
  1030. .start = ffmpeg_output_start,
  1031. .stop = ffmpeg_output_stop,
  1032. .raw_video = receive_video,
  1033. .raw_audio2 = receive_audio,
  1034. .get_total_bytes = ffmpeg_output_total_bytes,
  1035. };