obs-ffmpeg-output.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  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. AVPicture dst_picture;
  52. AVFrame *vframe;
  53. int frame_size;
  54. int total_frames;
  55. uint64_t start_timestamp;
  56. uint32_t audio_samplerate;
  57. enum audio_format audio_format;
  58. size_t audio_planes;
  59. size_t audio_size;
  60. struct circlebuf excess_frames[MAX_AV_PLANES];
  61. uint8_t *samples[MAX_AV_PLANES];
  62. AVFrame *aframe;
  63. int total_samples;
  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 (data->vcodec->id == AV_CODEC_ID_H264)
  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. ret = avformat_write_header(data->output, NULL);
  288. if (ret < 0) {
  289. blog(LOG_WARNING, "Error opening '%s': %s",
  290. data->config.url, av_err2str(ret));
  291. return false;
  292. }
  293. return true;
  294. }
  295. static void close_video(struct ffmpeg_data *data)
  296. {
  297. avcodec_close(data->video->codec);
  298. avpicture_free(&data->dst_picture);
  299. // This format for some reason derefs video frame
  300. // too many times
  301. if (data->vcodec->id == AV_CODEC_ID_A64_MULTI ||
  302. data->vcodec->id == AV_CODEC_ID_A64_MULTI5)
  303. return;
  304. av_frame_free(&data->vframe);
  305. }
  306. static void close_audio(struct ffmpeg_data *data)
  307. {
  308. for (size_t i = 0; i < MAX_AV_PLANES; i++)
  309. circlebuf_free(&data->excess_frames[i]);
  310. av_freep(&data->samples[0]);
  311. avcodec_close(data->audio->codec);
  312. av_frame_free(&data->aframe);
  313. }
  314. static void ffmpeg_data_free(struct ffmpeg_data *data)
  315. {
  316. if (data->initialized)
  317. av_write_trailer(data->output);
  318. if (data->video)
  319. close_video(data);
  320. if (data->audio)
  321. close_audio(data);
  322. if (data->output) {
  323. if ((data->output->oformat->flags & AVFMT_NOFILE) == 0)
  324. avio_close(data->output->pb);
  325. avformat_free_context(data->output);
  326. }
  327. memset(data, 0, sizeof(struct ffmpeg_data));
  328. }
  329. static inline const char *safe_str(const char *s)
  330. {
  331. if (s == NULL)
  332. return "(NULL)";
  333. else
  334. return s;
  335. }
  336. static bool ffmpeg_data_init(struct ffmpeg_data *data,
  337. struct ffmpeg_cfg *config)
  338. {
  339. bool is_rtmp = false;
  340. memset(data, 0, sizeof(struct ffmpeg_data));
  341. data->config = *config;
  342. if (!config->url || !*config->url)
  343. return false;
  344. av_register_all();
  345. avformat_network_init();
  346. is_rtmp = (astrcmpi_n(config->url, "rtmp://", 7) == 0);
  347. AVOutputFormat *output_format = av_guess_format(
  348. is_rtmp ? "flv" : data->config.format_name,
  349. data->config.url,
  350. is_rtmp ? NULL : data->config.format_mime_type);
  351. if (output_format == NULL) {
  352. blog(LOG_WARNING, "Couldn't find matching output format with "
  353. " parameters: name=%s, url=%s, mime=%s",
  354. safe_str(is_rtmp ?
  355. "flv" : data->config.format_name),
  356. safe_str(data->config.url),
  357. safe_str(is_rtmp ?
  358. NULL : data->config.format_mime_type));
  359. goto fail;
  360. }
  361. avformat_alloc_output_context2(&data->output, output_format,
  362. NULL, NULL);
  363. if (is_rtmp) {
  364. data->output->oformat->video_codec = AV_CODEC_ID_H264;
  365. data->output->oformat->audio_codec = AV_CODEC_ID_AAC;
  366. } else {
  367. data->output->oformat->video_codec =
  368. data->config.video_encoder_id;
  369. data->output->oformat->audio_codec =
  370. data->config.audio_encoder_id;
  371. }
  372. if (!data->output) {
  373. blog(LOG_WARNING, "Couldn't create avformat context");
  374. goto fail;
  375. }
  376. if (!init_streams(data))
  377. goto fail;
  378. if (!open_output_file(data))
  379. goto fail;
  380. av_dump_format(data->output, 0, NULL, 1);
  381. data->initialized = true;
  382. return true;
  383. fail:
  384. blog(LOG_WARNING, "ffmpeg_data_init failed");
  385. ffmpeg_data_free(data);
  386. return false;
  387. }
  388. /* ------------------------------------------------------------------------- */
  389. static const char *ffmpeg_output_getname(void)
  390. {
  391. return obs_module_text("FFmpegOutput");
  392. }
  393. static void ffmpeg_log_callback(void *param, int level, const char *format,
  394. va_list args)
  395. {
  396. if (level <= AV_LOG_INFO)
  397. blogva(LOG_DEBUG, format, args);
  398. UNUSED_PARAMETER(param);
  399. }
  400. static void *ffmpeg_output_create(obs_data_t *settings, obs_output_t *output)
  401. {
  402. struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
  403. pthread_mutex_init_value(&data->write_mutex);
  404. data->output = output;
  405. if (pthread_mutex_init(&data->write_mutex, NULL) != 0)
  406. goto fail;
  407. if (os_event_init(&data->stop_event, OS_EVENT_TYPE_AUTO) != 0)
  408. goto fail;
  409. if (os_sem_init(&data->write_sem, 0) != 0)
  410. goto fail;
  411. av_log_set_callback(ffmpeg_log_callback);
  412. UNUSED_PARAMETER(settings);
  413. return data;
  414. fail:
  415. pthread_mutex_destroy(&data->write_mutex);
  416. os_event_destroy(data->stop_event);
  417. bfree(data);
  418. return NULL;
  419. }
  420. static void ffmpeg_output_stop(void *data);
  421. static void ffmpeg_output_destroy(void *data)
  422. {
  423. struct ffmpeg_output *output = data;
  424. if (output) {
  425. if (output->connecting)
  426. pthread_join(output->start_thread, NULL);
  427. ffmpeg_output_stop(output);
  428. pthread_mutex_destroy(&output->write_mutex);
  429. os_sem_destroy(output->write_sem);
  430. os_event_destroy(output->stop_event);
  431. bfree(data);
  432. }
  433. }
  434. static inline void copy_data(AVPicture *pic, const struct video_data *frame,
  435. int height)
  436. {
  437. for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
  438. if (!frame->data[plane])
  439. continue;
  440. int frame_rowsize = (int)frame->linesize[plane];
  441. int pic_rowsize = pic->linesize[plane];
  442. int bytes = frame_rowsize < pic_rowsize ?
  443. frame_rowsize : pic_rowsize;
  444. int plane_height = plane == 0 ? height : height/2;
  445. for (int y = 0; y < plane_height; y++) {
  446. int pos_frame = y * frame_rowsize;
  447. int pos_pic = y * pic_rowsize;
  448. memcpy(pic->data[plane] + pos_pic,
  449. frame->data[plane] + pos_frame,
  450. bytes);
  451. }
  452. }
  453. }
  454. static void receive_video(void *param, struct video_data *frame)
  455. {
  456. struct ffmpeg_output *output = param;
  457. struct ffmpeg_data *data = &output->ff_data;
  458. // codec doesn't support video or none configured
  459. if (!data->video)
  460. return;
  461. AVCodecContext *context = data->video->codec;
  462. AVPacket packet = {0};
  463. int ret = 0, got_packet;
  464. av_init_packet(&packet);
  465. if (!data->start_timestamp)
  466. data->start_timestamp = frame->timestamp;
  467. if (!!data->swscale)
  468. sws_scale(data->swscale, (const uint8_t *const *)frame->data,
  469. (const int*)frame->linesize,
  470. 0, data->config.height, data->dst_picture.data,
  471. data->dst_picture.linesize);
  472. else
  473. copy_data(&data->dst_picture, frame, context->height);
  474. if (data->output->flags & AVFMT_RAWPICTURE) {
  475. packet.flags |= AV_PKT_FLAG_KEY;
  476. packet.stream_index = data->video->index;
  477. packet.data = data->dst_picture.data[0];
  478. packet.size = sizeof(AVPicture);
  479. pthread_mutex_lock(&output->write_mutex);
  480. da_push_back(output->packets, &packet);
  481. pthread_mutex_unlock(&output->write_mutex);
  482. os_sem_post(output->write_sem);
  483. } else {
  484. data->vframe->pts = data->total_frames;
  485. ret = avcodec_encode_video2(context, &packet, data->vframe,
  486. &got_packet);
  487. if (ret < 0) {
  488. blog(LOG_WARNING, "receive_video: Error encoding "
  489. "video: %s", av_err2str(ret));
  490. return;
  491. }
  492. if (!ret && got_packet && packet.size) {
  493. packet.pts = rescale_ts(packet.pts, context,
  494. data->video->time_base);
  495. packet.dts = rescale_ts(packet.dts, context,
  496. data->video->time_base);
  497. packet.duration = (int)av_rescale_q(packet.duration,
  498. context->time_base,
  499. data->video->time_base);
  500. pthread_mutex_lock(&output->write_mutex);
  501. da_push_back(output->packets, &packet);
  502. pthread_mutex_unlock(&output->write_mutex);
  503. os_sem_post(output->write_sem);
  504. } else {
  505. ret = 0;
  506. }
  507. }
  508. if (ret != 0) {
  509. blog(LOG_WARNING, "receive_video: Error writing video: %s",
  510. av_err2str(ret));
  511. }
  512. data->total_frames++;
  513. }
  514. static void encode_audio(struct ffmpeg_output *output,
  515. struct AVCodecContext *context, size_t block_size)
  516. {
  517. struct ffmpeg_data *data = &output->ff_data;
  518. AVPacket packet = {0};
  519. int ret, got_packet;
  520. size_t total_size = data->frame_size * block_size * context->channels;
  521. data->aframe->nb_samples = data->frame_size;
  522. data->aframe->pts = av_rescale_q(data->total_samples,
  523. (AVRational){1, context->sample_rate},
  524. context->time_base);
  525. ret = avcodec_fill_audio_frame(data->aframe, context->channels,
  526. context->sample_fmt, data->samples[0],
  527. (int)total_size, 1);
  528. if (ret < 0) {
  529. blog(LOG_WARNING, "encode_audio: avcodec_fill_audio_frame "
  530. "failed: %s", av_err2str(ret));
  531. return;
  532. }
  533. data->total_samples += data->frame_size;
  534. ret = avcodec_encode_audio2(context, &packet, data->aframe,
  535. &got_packet);
  536. if (ret < 0) {
  537. blog(LOG_WARNING, "encode_audio: Error encoding audio: %s",
  538. av_err2str(ret));
  539. return;
  540. }
  541. if (!got_packet)
  542. return;
  543. packet.pts = rescale_ts(packet.pts, context, data->audio->time_base);
  544. packet.dts = rescale_ts(packet.dts, context, data->audio->time_base);
  545. packet.duration = (int)av_rescale_q(packet.duration, context->time_base,
  546. data->audio->time_base);
  547. packet.stream_index = data->audio->index;
  548. pthread_mutex_lock(&output->write_mutex);
  549. da_push_back(output->packets, &packet);
  550. pthread_mutex_unlock(&output->write_mutex);
  551. os_sem_post(output->write_sem);
  552. }
  553. static bool prepare_audio(struct ffmpeg_data *data,
  554. const struct audio_data *frame, struct audio_data *output)
  555. {
  556. *output = *frame;
  557. if (frame->timestamp < data->start_timestamp) {
  558. uint64_t duration = (uint64_t)frame->frames * 1000000000 /
  559. (uint64_t)data->audio_samplerate;
  560. uint64_t end_ts = (frame->timestamp + duration);
  561. uint64_t cutoff;
  562. if (end_ts <= data->start_timestamp)
  563. return false;
  564. cutoff = data->start_timestamp - frame->timestamp;
  565. cutoff = cutoff * (uint64_t)data->audio_samplerate /
  566. 1000000000;
  567. for (size_t i = 0; i < data->audio_planes; i++)
  568. output->data[i] += data->audio_size * (uint32_t)cutoff;
  569. output->frames -= (uint32_t)cutoff;
  570. }
  571. return true;
  572. }
  573. static void receive_audio(void *param, struct audio_data *frame)
  574. {
  575. struct ffmpeg_output *output = param;
  576. struct ffmpeg_data *data = &output->ff_data;
  577. size_t frame_size_bytes;
  578. struct audio_data in;
  579. // codec doesn't support audio or none configured
  580. if (!data->audio)
  581. return;
  582. AVCodecContext *context = data->audio->codec;
  583. if (!data->start_timestamp)
  584. return;
  585. if (!prepare_audio(data, frame, &in))
  586. return;
  587. frame_size_bytes = (size_t)data->frame_size * data->audio_size;
  588. for (size_t i = 0; i < data->audio_planes; i++)
  589. circlebuf_push_back(&data->excess_frames[i], in.data[i],
  590. in.frames * data->audio_size);
  591. while (data->excess_frames[0].size >= frame_size_bytes) {
  592. for (size_t i = 0; i < data->audio_planes; i++)
  593. circlebuf_pop_front(&data->excess_frames[i],
  594. data->samples[i], frame_size_bytes);
  595. encode_audio(output, context, data->audio_size);
  596. }
  597. }
  598. static bool process_packet(struct ffmpeg_output *output)
  599. {
  600. AVPacket packet;
  601. bool new_packet = false;
  602. int ret;
  603. pthread_mutex_lock(&output->write_mutex);
  604. if (output->packets.num) {
  605. packet = output->packets.array[0];
  606. da_erase(output->packets, 0);
  607. new_packet = true;
  608. }
  609. pthread_mutex_unlock(&output->write_mutex);
  610. if (!new_packet)
  611. return true;
  612. /*blog(LOG_DEBUG, "size = %d, flags = %lX, stream = %d, "
  613. "packets queued: %lu",
  614. packet.size, packet.flags,
  615. packet.stream_index, output->packets.num);*/
  616. ret = av_interleaved_write_frame(output->ff_data.output, &packet);
  617. if (ret < 0) {
  618. av_free_packet(&packet);
  619. blog(LOG_WARNING, "receive_audio: Error writing packet: %s",
  620. av_err2str(ret));
  621. return false;
  622. }
  623. return true;
  624. }
  625. static void *write_thread(void *data)
  626. {
  627. struct ffmpeg_output *output = data;
  628. while (os_sem_wait(output->write_sem) == 0) {
  629. /* check to see if shutting down */
  630. if (os_event_try(output->stop_event) == 0)
  631. break;
  632. if (!process_packet(output)) {
  633. pthread_detach(output->write_thread);
  634. output->write_thread_active = false;
  635. ffmpeg_output_stop(output);
  636. break;
  637. }
  638. }
  639. output->active = false;
  640. return NULL;
  641. }
  642. static inline const char *get_string_or_null(obs_data_t *settings,
  643. const char *name)
  644. {
  645. const char *value = obs_data_get_string(settings, name);
  646. if (!value || !strlen(value))
  647. return NULL;
  648. return value;
  649. }
  650. static bool try_connect(struct ffmpeg_output *output)
  651. {
  652. video_t *video = obs_output_video(output->output);
  653. struct ffmpeg_cfg config;
  654. obs_data_t *settings;
  655. bool success;
  656. int ret;
  657. settings = obs_output_get_settings(output->output);
  658. config.url = obs_data_get_string(settings, "url");
  659. config.format_name = get_string_or_null(settings, "format_name");
  660. config.format_mime_type = get_string_or_null(settings,
  661. "format_mime_type");
  662. config.video_bitrate = (int)obs_data_get_int(settings, "video_bitrate");
  663. config.audio_bitrate = (int)obs_data_get_int(settings, "audio_bitrate");
  664. config.video_encoder = get_string_or_null(settings, "video_encoder");
  665. config.video_encoder_id = (int)obs_data_get_int(settings,
  666. "video_encoder_id");
  667. config.audio_encoder = get_string_or_null(settings, "audio_encoder");
  668. config.audio_encoder_id = (int)obs_data_get_int(settings,
  669. "audio_encoder_id");
  670. config.video_settings = obs_data_get_string(settings, "video_settings");
  671. config.audio_settings = obs_data_get_string(settings, "audio_settings");
  672. config.scale_width = (int)obs_data_get_int(settings, "scale_width");
  673. config.scale_height = (int)obs_data_get_int(settings, "scale_height");
  674. config.width = (int)obs_output_get_width(output->output);
  675. config.height = (int)obs_output_get_height(output->output);
  676. config.format = obs_to_ffmpeg_video_format(
  677. video_output_get_format(video));
  678. if (config.format == AV_PIX_FMT_NONE) {
  679. blog(LOG_DEBUG, "invalid pixel format used for FFmpeg output");
  680. return false;
  681. }
  682. if (!config.scale_width)
  683. config.scale_width = config.width;
  684. if (!config.scale_height)
  685. config.scale_height = config.height;
  686. success = ffmpeg_data_init(&output->ff_data, &config);
  687. obs_data_release(settings);
  688. if (!success)
  689. return false;
  690. struct audio_convert_info aci = {
  691. .format = output->ff_data.audio_format
  692. };
  693. output->active = true;
  694. if (!obs_output_can_begin_data_capture(output->output, 0))
  695. return false;
  696. ret = pthread_create(&output->write_thread, NULL, write_thread, output);
  697. if (ret != 0) {
  698. blog(LOG_WARNING, "ffmpeg_output_start: failed to create write "
  699. "thread.");
  700. ffmpeg_output_stop(output);
  701. return false;
  702. }
  703. obs_output_set_video_conversion(output->output, NULL);
  704. obs_output_set_audio_conversion(output->output, &aci);
  705. obs_output_begin_data_capture(output->output, 0);
  706. output->write_thread_active = true;
  707. return true;
  708. }
  709. static void *start_thread(void *data)
  710. {
  711. struct ffmpeg_output *output = data;
  712. if (!try_connect(output))
  713. obs_output_signal_stop(output->output,
  714. OBS_OUTPUT_CONNECT_FAILED);
  715. output->connecting = false;
  716. return NULL;
  717. }
  718. static bool ffmpeg_output_start(void *data)
  719. {
  720. struct ffmpeg_output *output = data;
  721. int ret;
  722. if (output->connecting)
  723. return false;
  724. ret = pthread_create(&output->start_thread, NULL, start_thread, output);
  725. return (output->connecting = (ret == 0));
  726. }
  727. static void ffmpeg_output_stop(void *data)
  728. {
  729. struct ffmpeg_output *output = data;
  730. if (output->active) {
  731. obs_output_end_data_capture(output->output);
  732. if (output->write_thread_active) {
  733. os_event_signal(output->stop_event);
  734. os_sem_post(output->write_sem);
  735. pthread_join(output->write_thread, NULL);
  736. output->write_thread_active = false;
  737. }
  738. pthread_mutex_lock(&output->write_mutex);
  739. for (size_t i = 0; i < output->packets.num; i++)
  740. av_free_packet(output->packets.array+i);
  741. da_free(output->packets);
  742. pthread_mutex_unlock(&output->write_mutex);
  743. ffmpeg_data_free(&output->ff_data);
  744. }
  745. }
  746. struct obs_output_info ffmpeg_output = {
  747. .id = "ffmpeg_output",
  748. .flags = OBS_OUTPUT_AUDIO | OBS_OUTPUT_VIDEO,
  749. .get_name = ffmpeg_output_getname,
  750. .create = ffmpeg_output_create,
  751. .destroy = ffmpeg_output_destroy,
  752. .start = ffmpeg_output_start,
  753. .stop = ffmpeg_output_stop,
  754. .raw_video = receive_video,
  755. .raw_audio = receive_audio,
  756. };