obs-ffmpeg-output.c 31 KB

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