obs-ffmpeg-output.c 22 KB

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