obs-ffmpeg-output.c 22 KB

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