obs-ffmpeg-output.c 28 KB

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