obs-ffmpeg-output.c 32 KB

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