obs-ffmpeg-output.c 28 KB

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