obs-ffmpeg-output.c 21 KB

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