obs-ffmpeg-output.c 31 KB

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