1
0

obs-ffmpeg-output.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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. int width;
  42. int height;
  43. uint64_t start_timestamp;
  44. int audio_bitrate;
  45. uint32_t audio_samplerate;
  46. enum audio_format audio_format;
  47. size_t audio_planes;
  48. size_t audio_size;
  49. struct circlebuf excess_frames[MAX_AV_PLANES];
  50. uint8_t *samples[MAX_AV_PLANES];
  51. AVFrame *aframe;
  52. int total_samples;
  53. const char *filename_test;
  54. bool initialized;
  55. };
  56. struct ffmpeg_output {
  57. obs_output_t *output;
  58. volatile bool active;
  59. struct ffmpeg_data ff_data;
  60. bool connecting;
  61. pthread_t start_thread;
  62. bool write_thread_active;
  63. pthread_mutex_t write_mutex;
  64. pthread_t write_thread;
  65. os_sem_t *write_sem;
  66. os_event_t *stop_event;
  67. DARRAY(AVPacket) packets;
  68. };
  69. /* ------------------------------------------------------------------------- */
  70. static bool new_stream(struct ffmpeg_data *data, AVStream **stream,
  71. AVCodec **codec, enum AVCodecID id)
  72. {
  73. *codec = avcodec_find_encoder(id);
  74. if (!*codec) {
  75. blog(LOG_WARNING, "Couldn't find encoder '%s'",
  76. avcodec_get_name(id));
  77. return false;
  78. }
  79. *stream = avformat_new_stream(data->output, *codec);
  80. if (!*stream) {
  81. blog(LOG_WARNING, "Couldn't create stream for encoder '%s'",
  82. avcodec_get_name(id));
  83. return false;
  84. }
  85. (*stream)->id = data->output->nb_streams-1;
  86. return true;
  87. }
  88. static bool open_video_codec(struct ffmpeg_data *data)
  89. {
  90. AVCodecContext *context = data->video->codec;
  91. int ret;
  92. if (data->vcodec->id == AV_CODEC_ID_H264)
  93. av_opt_set(context->priv_data, "preset", "veryfast", 0);
  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 = data->width;
  151. context->height = data->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, int width, int height)
  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. data->width = width;
  286. data->height = height;
  287. if (!filename || !*filename)
  288. return false;
  289. av_register_all();
  290. avformat_network_init();
  291. is_rtmp = (astrcmp_n(filename, "rtmp://", 7) == 0);
  292. /* TODO: settings */
  293. avformat_alloc_output_context2(&data->output, NULL,
  294. is_rtmp ? "flv" : NULL, data->filename_test);
  295. if (is_rtmp) {
  296. data->output->oformat->video_codec = AV_CODEC_ID_H264;
  297. data->output->oformat->audio_codec = AV_CODEC_ID_AAC;
  298. }
  299. if (!data->output) {
  300. blog(LOG_WARNING, "Couldn't create avformat context");
  301. goto fail;
  302. }
  303. if (!init_streams(data))
  304. goto fail;
  305. if (!open_output_file(data))
  306. goto fail;
  307. av_dump_format(data->output, 0, NULL, 1);
  308. data->initialized = true;
  309. return true;
  310. fail:
  311. blog(LOG_WARNING, "ffmpeg_data_init failed");
  312. ffmpeg_data_free(data);
  313. return false;
  314. }
  315. /* ------------------------------------------------------------------------- */
  316. static const char *ffmpeg_output_getname(void)
  317. {
  318. return obs_module_text("FFmpegOutput");
  319. }
  320. static void ffmpeg_log_callback(void *param, int level, const char *format,
  321. va_list args)
  322. {
  323. if (level <= AV_LOG_INFO)
  324. blogva(LOG_DEBUG, format, args);
  325. UNUSED_PARAMETER(param);
  326. }
  327. static void *ffmpeg_output_create(obs_data_t *settings, obs_output_t *output)
  328. {
  329. struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
  330. pthread_mutex_init_value(&data->write_mutex);
  331. data->output = output;
  332. if (pthread_mutex_init(&data->write_mutex, NULL) != 0)
  333. goto fail;
  334. if (os_event_init(&data->stop_event, OS_EVENT_TYPE_AUTO) != 0)
  335. goto fail;
  336. if (os_sem_init(&data->write_sem, 0) != 0)
  337. goto fail;
  338. av_log_set_callback(ffmpeg_log_callback);
  339. UNUSED_PARAMETER(settings);
  340. return data;
  341. fail:
  342. pthread_mutex_destroy(&data->write_mutex);
  343. os_event_destroy(data->stop_event);
  344. bfree(data);
  345. return NULL;
  346. }
  347. static void ffmpeg_output_stop(void *data);
  348. static void ffmpeg_output_destroy(void *data)
  349. {
  350. struct ffmpeg_output *output = data;
  351. if (output) {
  352. if (output->connecting)
  353. pthread_join(output->start_thread, NULL);
  354. ffmpeg_output_stop(output);
  355. pthread_mutex_destroy(&output->write_mutex);
  356. os_sem_destroy(output->write_sem);
  357. os_event_destroy(output->stop_event);
  358. bfree(data);
  359. }
  360. }
  361. static inline void copy_data(AVPicture *pic, const struct video_data *frame,
  362. int height)
  363. {
  364. for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
  365. if (!frame->data[plane])
  366. continue;
  367. int frame_rowsize = (int)frame->linesize[plane];
  368. int pic_rowsize = pic->linesize[plane];
  369. int bytes = frame_rowsize < pic_rowsize ?
  370. frame_rowsize : pic_rowsize;
  371. int plane_height = plane == 0 ? height : height/2;
  372. for (int y = 0; y < plane_height; y++) {
  373. int pos_frame = y * frame_rowsize;
  374. int pos_pic = y * pic_rowsize;
  375. memcpy(pic->data[plane] + pos_pic,
  376. frame->data[plane] + pos_frame,
  377. bytes);
  378. }
  379. }
  380. }
  381. static void receive_video(void *param, struct video_data *frame)
  382. {
  383. struct ffmpeg_output *output = param;
  384. struct ffmpeg_data *data = &output->ff_data;
  385. AVCodecContext *context = data->video->codec;
  386. AVPacket packet = {0};
  387. int ret = 0, got_packet;
  388. enum AVPixelFormat format;
  389. av_init_packet(&packet);
  390. if (!data->start_timestamp)
  391. data->start_timestamp = frame->timestamp;
  392. format = obs_to_ffmpeg_video_format(OBS_FFMPEG_VIDEO_FORMAT);
  393. if (context->pix_fmt != format)
  394. sws_scale(data->swscale, (const uint8_t *const *)frame->data,
  395. (const int*)frame->linesize,
  396. 0, context->height, data->dst_picture.data,
  397. data->dst_picture.linesize);
  398. else
  399. copy_data(&data->dst_picture, frame, context->height);
  400. if (data->output->flags & AVFMT_RAWPICTURE) {
  401. packet.flags |= AV_PKT_FLAG_KEY;
  402. packet.stream_index = data->video->index;
  403. packet.data = data->dst_picture.data[0];
  404. packet.size = sizeof(AVPicture);
  405. pthread_mutex_lock(&output->write_mutex);
  406. da_push_back(output->packets, &packet);
  407. pthread_mutex_unlock(&output->write_mutex);
  408. os_sem_post(output->write_sem);
  409. } else {
  410. data->vframe->pts = data->total_frames;
  411. ret = avcodec_encode_video2(context, &packet, data->vframe,
  412. &got_packet);
  413. if (ret < 0) {
  414. blog(LOG_WARNING, "receive_video: Error encoding "
  415. "video: %s", av_err2str(ret));
  416. return;
  417. }
  418. if (!ret && got_packet && packet.size) {
  419. packet.pts = rescale_ts(packet.pts, context,
  420. data->video->time_base);
  421. packet.dts = rescale_ts(packet.dts, context,
  422. data->video->time_base);
  423. packet.duration = (int)av_rescale_q(packet.duration,
  424. context->time_base,
  425. data->video->time_base);
  426. pthread_mutex_lock(&output->write_mutex);
  427. da_push_back(output->packets, &packet);
  428. pthread_mutex_unlock(&output->write_mutex);
  429. os_sem_post(output->write_sem);
  430. } else {
  431. ret = 0;
  432. }
  433. }
  434. if (ret != 0) {
  435. blog(LOG_WARNING, "receive_video: Error writing video: %s",
  436. av_err2str(ret));
  437. }
  438. data->total_frames++;
  439. }
  440. static void encode_audio(struct ffmpeg_output *output,
  441. struct AVCodecContext *context, size_t block_size)
  442. {
  443. struct ffmpeg_data *data = &output->ff_data;
  444. AVPacket packet = {0};
  445. int ret, got_packet;
  446. size_t total_size = data->frame_size * block_size * context->channels;
  447. data->aframe->nb_samples = data->frame_size;
  448. data->aframe->pts = av_rescale_q(data->total_samples,
  449. (AVRational){1, context->sample_rate},
  450. context->time_base);
  451. ret = avcodec_fill_audio_frame(data->aframe, context->channels,
  452. context->sample_fmt, data->samples[0],
  453. (int)total_size, 1);
  454. if (ret < 0) {
  455. blog(LOG_WARNING, "encode_audio: avcodec_fill_audio_frame "
  456. "failed: %s", av_err2str(ret));
  457. return;
  458. }
  459. data->total_samples += data->frame_size;
  460. ret = avcodec_encode_audio2(context, &packet, data->aframe,
  461. &got_packet);
  462. if (ret < 0) {
  463. blog(LOG_WARNING, "encode_audio: Error encoding audio: %s",
  464. av_err2str(ret));
  465. return;
  466. }
  467. if (!got_packet)
  468. return;
  469. packet.pts = rescale_ts(packet.pts, context, data->audio->time_base);
  470. packet.dts = rescale_ts(packet.dts, context, data->audio->time_base);
  471. packet.duration = (int)av_rescale_q(packet.duration, context->time_base,
  472. data->audio->time_base);
  473. packet.stream_index = data->audio->index;
  474. pthread_mutex_lock(&output->write_mutex);
  475. da_push_back(output->packets, &packet);
  476. pthread_mutex_unlock(&output->write_mutex);
  477. os_sem_post(output->write_sem);
  478. }
  479. static bool prepare_audio(struct ffmpeg_data *data,
  480. const struct audio_data *frame, struct audio_data *output)
  481. {
  482. *output = *frame;
  483. if (frame->timestamp < data->start_timestamp) {
  484. uint64_t duration = (uint64_t)frame->frames * 1000000000 /
  485. (uint64_t)data->audio_samplerate;
  486. uint64_t end_ts = (frame->timestamp + duration);
  487. uint64_t cutoff;
  488. if (end_ts <= data->start_timestamp)
  489. return false;
  490. cutoff = data->start_timestamp - frame->timestamp;
  491. cutoff = cutoff * (uint64_t)data->audio_samplerate /
  492. 1000000000;
  493. for (size_t i = 0; i < data->audio_planes; i++)
  494. output->data[i] += data->audio_size * (uint32_t)cutoff;
  495. output->frames -= (uint32_t)cutoff;
  496. }
  497. return true;
  498. }
  499. static void receive_audio(void *param, struct audio_data *frame)
  500. {
  501. struct ffmpeg_output *output = param;
  502. struct ffmpeg_data *data = &output->ff_data;
  503. size_t frame_size_bytes;
  504. struct audio_data in;
  505. AVCodecContext *context = data->audio->codec;
  506. if (!data->start_timestamp)
  507. return;
  508. if (!prepare_audio(data, frame, &in))
  509. return;
  510. frame_size_bytes = (size_t)data->frame_size * data->audio_size;
  511. for (size_t i = 0; i < data->audio_planes; i++)
  512. circlebuf_push_back(&data->excess_frames[i], in.data[i],
  513. in.frames * data->audio_size);
  514. while (data->excess_frames[0].size >= frame_size_bytes) {
  515. for (size_t i = 0; i < data->audio_planes; i++)
  516. circlebuf_pop_front(&data->excess_frames[i],
  517. data->samples[i], frame_size_bytes);
  518. encode_audio(output, context, data->audio_size);
  519. }
  520. }
  521. static bool process_packet(struct ffmpeg_output *output)
  522. {
  523. AVPacket packet;
  524. bool new_packet = false;
  525. int ret;
  526. pthread_mutex_lock(&output->write_mutex);
  527. if (output->packets.num) {
  528. packet = output->packets.array[0];
  529. da_erase(output->packets, 0);
  530. new_packet = true;
  531. }
  532. pthread_mutex_unlock(&output->write_mutex);
  533. if (!new_packet)
  534. return true;
  535. /*blog(LOG_DEBUG, "size = %d, flags = %lX, stream = %d, "
  536. "packets queued: %lu",
  537. packet.size, packet.flags,
  538. packet.stream_index, output->packets.num);*/
  539. ret = av_interleaved_write_frame(output->ff_data.output, &packet);
  540. if (ret < 0) {
  541. av_free_packet(&packet);
  542. blog(LOG_WARNING, "receive_audio: Error writing packet: %s",
  543. av_err2str(ret));
  544. return false;
  545. }
  546. return true;
  547. }
  548. static void *write_thread(void *data)
  549. {
  550. struct ffmpeg_output *output = data;
  551. while (os_sem_wait(output->write_sem) == 0) {
  552. /* check to see if shutting down */
  553. if (os_event_try(output->stop_event) == 0)
  554. break;
  555. if (!process_packet(output)) {
  556. pthread_detach(output->write_thread);
  557. output->write_thread_active = false;
  558. ffmpeg_output_stop(output);
  559. break;
  560. }
  561. }
  562. output->active = false;
  563. return NULL;
  564. }
  565. static bool try_connect(struct ffmpeg_output *output)
  566. {
  567. const char *filename_test;
  568. obs_data_t *settings;
  569. int audio_bitrate, video_bitrate;
  570. int width, height;
  571. int ret;
  572. settings = obs_output_get_settings(output->output);
  573. filename_test = obs_data_get_string(settings, "filename");
  574. video_bitrate = (int)obs_data_get_int(settings, "video_bitrate");
  575. audio_bitrate = (int)obs_data_get_int(settings, "audio_bitrate");
  576. obs_data_release(settings);
  577. if (!filename_test || !*filename_test)
  578. return false;
  579. width = (int)obs_output_get_width(output->output);
  580. height = (int)obs_output_get_height(output->output);
  581. if (!ffmpeg_data_init(&output->ff_data, filename_test,
  582. video_bitrate, audio_bitrate,
  583. width, height))
  584. return false;
  585. struct audio_convert_info aci = {
  586. .format = output->ff_data.audio_format
  587. };
  588. struct video_scale_info vsi = {
  589. .format = OBS_FFMPEG_VIDEO_FORMAT
  590. };
  591. output->active = true;
  592. if (!obs_output_can_begin_data_capture(output->output, 0))
  593. return false;
  594. ret = pthread_create(&output->write_thread, NULL, write_thread, output);
  595. if (ret != 0) {
  596. blog(LOG_WARNING, "ffmpeg_output_start: failed to create write "
  597. "thread.");
  598. ffmpeg_output_stop(output);
  599. return false;
  600. }
  601. obs_output_set_video_conversion(output->output, &vsi);
  602. obs_output_set_audio_conversion(output->output, &aci);
  603. obs_output_begin_data_capture(output->output, 0);
  604. output->write_thread_active = true;
  605. return true;
  606. }
  607. static void *start_thread(void *data)
  608. {
  609. struct ffmpeg_output *output = data;
  610. if (!try_connect(output))
  611. obs_output_signal_stop(output->output,
  612. OBS_OUTPUT_CONNECT_FAILED);
  613. output->connecting = false;
  614. return NULL;
  615. }
  616. static bool ffmpeg_output_start(void *data)
  617. {
  618. struct ffmpeg_output *output = data;
  619. int ret;
  620. if (output->connecting)
  621. return false;
  622. ret = pthread_create(&output->start_thread, NULL, start_thread, output);
  623. return (output->connecting = (ret == 0));
  624. }
  625. static void ffmpeg_output_stop(void *data)
  626. {
  627. struct ffmpeg_output *output = data;
  628. if (output->active) {
  629. obs_output_end_data_capture(output->output);
  630. if (output->write_thread_active) {
  631. os_event_signal(output->stop_event);
  632. os_sem_post(output->write_sem);
  633. pthread_join(output->write_thread, NULL);
  634. output->write_thread_active = false;
  635. }
  636. pthread_mutex_lock(&output->write_mutex);
  637. for (size_t i = 0; i < output->packets.num; i++)
  638. av_free_packet(output->packets.array+i);
  639. da_free(output->packets);
  640. pthread_mutex_unlock(&output->write_mutex);
  641. ffmpeg_data_free(&output->ff_data);
  642. }
  643. }
  644. struct obs_output_info ffmpeg_output = {
  645. .id = "ffmpeg_output",
  646. .flags = OBS_OUTPUT_AUDIO | OBS_OUTPUT_VIDEO,
  647. .get_name = ffmpeg_output_getname,
  648. .create = ffmpeg_output_create,
  649. .destroy = ffmpeg_output_destroy,
  650. .start = ffmpeg_output_start,
  651. .stop = ffmpeg_output_stop,
  652. .raw_video = receive_video,
  653. .raw_audio = receive_audio,
  654. };