obs-ffmpeg-output.c 21 KB

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