obs-ffmpeg-output.c 32 KB

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