obs-ffmpeg-output.c 21 KB

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