obs-ffmpeg-output.c 24 KB

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