obs-ffmpeg-output.c 32 KB

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