obs-ffmpeg-output.c 30 KB

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