obs-ffmpeg-output.c 28 KB

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