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-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 "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(void)
  315. {
  316. return obs_module_text("FFmpegOutput");
  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_stop(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. };