obs-ffmpeg-output.c 29 KB

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