obs-ffmpeg-output.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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 <libavutil/opt.h>
  17. #include <libavformat/avformat.h>
  18. #include <libswscale/swscale.h>
  19. /* NOTE: much of this stuff is test stuff that was more or less copied from
  20. * the muxing.c ffmpeg example */
  21. struct ffmpeg_data {
  22. AVStream *video;
  23. AVStream *audio;
  24. AVCodec *acodec;
  25. AVCodec *vcodec;
  26. AVFormatContext *output;
  27. struct SwsContext *swscale;
  28. AVPicture dst_picture;
  29. AVFrame *vframe;
  30. int frame_size;
  31. int total_frames;
  32. uint64_t start_timestamp;
  33. uint32_t audio_samplerate;
  34. enum audio_format audio_format;
  35. size_t audio_planes;
  36. size_t audio_size;
  37. struct circlebuf excess_frames[MAX_AV_PLANES];
  38. uint8_t *samples[MAX_AV_PLANES];
  39. AVFrame *aframe;
  40. int total_samples;
  41. const char *filename_test;
  42. bool initialized;
  43. };
  44. struct ffmpeg_output {
  45. obs_output_t output;
  46. volatile bool active;
  47. struct ffmpeg_data ff_data;
  48. };
  49. /* ------------------------------------------------------------------------- */
  50. static inline enum AVPixelFormat obs_to_ffmpeg_video_format(
  51. enum video_format format)
  52. {
  53. switch (format) {
  54. case VIDEO_FORMAT_NONE: return AV_PIX_FMT_NONE;
  55. case VIDEO_FORMAT_I420: return AV_PIX_FMT_YUV420P;
  56. case VIDEO_FORMAT_NV12: return AV_PIX_FMT_NV12;
  57. case VIDEO_FORMAT_YVYU: return AV_PIX_FMT_NONE;
  58. case VIDEO_FORMAT_YUY2: return AV_PIX_FMT_YUYV422;
  59. case VIDEO_FORMAT_UYVY: return AV_PIX_FMT_UYVY422;
  60. case VIDEO_FORMAT_RGBA: return AV_PIX_FMT_RGBA;
  61. case VIDEO_FORMAT_BGRA: return AV_PIX_FMT_BGRA;
  62. case VIDEO_FORMAT_BGRX: return AV_PIX_FMT_BGRA;
  63. }
  64. return AV_PIX_FMT_NONE;
  65. }
  66. static inline enum audio_format convert_ffmpeg_sample_format(
  67. enum AVSampleFormat format)
  68. {
  69. switch ((uint32_t)format) {
  70. case AV_SAMPLE_FMT_U8: return AUDIO_FORMAT_U8BIT;
  71. case AV_SAMPLE_FMT_S16: return AUDIO_FORMAT_16BIT;
  72. case AV_SAMPLE_FMT_S32: return AUDIO_FORMAT_32BIT;
  73. case AV_SAMPLE_FMT_FLT: return AUDIO_FORMAT_FLOAT;
  74. case AV_SAMPLE_FMT_U8P: return AUDIO_FORMAT_U8BIT_PLANAR;
  75. case AV_SAMPLE_FMT_S16P: return AUDIO_FORMAT_16BIT_PLANAR;
  76. case AV_SAMPLE_FMT_S32P: return AUDIO_FORMAT_32BIT_PLANAR;
  77. case AV_SAMPLE_FMT_FLTP: return AUDIO_FORMAT_FLOAT_PLANAR;
  78. }
  79. /* shouldn't get here */
  80. return AUDIO_FORMAT_16BIT;
  81. }
  82. static bool new_stream(struct ffmpeg_data *data, AVStream **stream,
  83. AVCodec **codec, enum AVCodecID id)
  84. {
  85. *codec = avcodec_find_encoder(id);
  86. if (!*codec) {
  87. blog(LOG_ERROR, "Couldn't find encoder '%s'",
  88. avcodec_get_name(id));
  89. return false;
  90. }
  91. *stream = avformat_new_stream(data->output, *codec);
  92. if (!*stream) {
  93. blog(LOG_ERROR, "Couldn't create stream for encoder '%s'",
  94. avcodec_get_name(id));
  95. return false;
  96. }
  97. (*stream)->id = data->output->nb_streams-1;
  98. return true;
  99. }
  100. static bool open_video_codec(struct ffmpeg_data *data)
  101. {
  102. AVCodecContext *context = data->video->codec;
  103. int ret;
  104. if (data->vcodec->id == AV_CODEC_ID_H264)
  105. av_opt_set(context->priv_data, "preset", "veryfast", 0);
  106. ret = avcodec_open2(context, data->vcodec, NULL);
  107. if (ret < 0) {
  108. blog(LOG_ERROR, "Failed to open video codec: %s",
  109. av_err2str(ret));
  110. return false;
  111. }
  112. data->vframe = av_frame_alloc();
  113. if (!data->vframe) {
  114. blog(LOG_ERROR, "Failed to allocate video frame");
  115. return false;
  116. }
  117. data->vframe->format = context->pix_fmt;
  118. data->vframe->width = context->width;
  119. data->vframe->height = context->height;
  120. ret = avpicture_alloc(&data->dst_picture, context->pix_fmt,
  121. context->width, context->height);
  122. if (ret < 0) {
  123. blog(LOG_ERROR, "Failed to allocate dst_picture: %s",
  124. av_err2str(ret));
  125. return false;
  126. }
  127. *((AVPicture*)data->vframe) = data->dst_picture;
  128. return true;
  129. }
  130. static bool init_swscale(struct ffmpeg_data *data, AVCodecContext *context)
  131. {
  132. data->swscale = sws_getContext(
  133. context->width, context->height, AV_PIX_FMT_YUV420P,
  134. context->width, context->height, context->pix_fmt,
  135. SWS_BICUBIC, NULL, NULL, NULL);
  136. if (!data->swscale) {
  137. blog(LOG_ERROR, "Could not initialize swscale");
  138. return false;
  139. }
  140. return true;
  141. }
  142. static bool create_video_stream(struct ffmpeg_data *data)
  143. {
  144. AVCodecContext *context;
  145. struct obs_video_info ovi;
  146. if (!obs_get_video_info(&ovi)) {
  147. blog(LOG_ERROR, "No active video");
  148. return false;
  149. }
  150. if (!new_stream(data, &data->video, &data->vcodec,
  151. data->output->oformat->video_codec))
  152. return false;
  153. context = data->video->codec;
  154. context->codec_id = data->output->oformat->video_codec;
  155. context->bit_rate = 6000000;
  156. context->width = ovi.output_width;
  157. context->height = ovi.output_height;
  158. context->time_base.num = ovi.fps_den;
  159. context->time_base.den = ovi.fps_num;
  160. context->gop_size = 12;
  161. context->pix_fmt = AV_PIX_FMT_YUV420P;
  162. if (data->output->oformat->flags & AVFMT_GLOBALHEADER)
  163. context->flags |= CODEC_FLAG_GLOBAL_HEADER;
  164. if (!open_video_codec(data))
  165. return false;
  166. if (context->pix_fmt != AV_PIX_FMT_YUV420P)
  167. if (!init_swscale(data, context))
  168. return false;
  169. return true;
  170. }
  171. static bool open_audio_codec(struct ffmpeg_data *data)
  172. {
  173. AVCodecContext *context = data->audio->codec;
  174. int ret;
  175. data->aframe = av_frame_alloc();
  176. if (!data->aframe) {
  177. blog(LOG_ERROR, "Failed to allocate audio frame");
  178. return false;
  179. }
  180. context->strict_std_compliance = -2;
  181. ret = avcodec_open2(context, data->acodec, NULL);
  182. if (ret < 0) {
  183. blog(LOG_ERROR, "Failed to open audio codec: %s",
  184. av_err2str(ret));
  185. return false;
  186. }
  187. data->frame_size = context->frame_size ? context->frame_size : 1024;
  188. ret = av_samples_alloc(data->samples, NULL, context->channels,
  189. data->frame_size, context->sample_fmt, 0);
  190. if (ret < 0) {
  191. blog(LOG_ERROR, "Failed to create audio buffer: %s",
  192. av_err2str(ret));
  193. return false;
  194. }
  195. return true;
  196. }
  197. static bool create_audio_stream(struct ffmpeg_data *data)
  198. {
  199. AVCodecContext *context;
  200. struct audio_output_info aoi;
  201. if (!obs_get_audio_info(&aoi)) {
  202. blog(LOG_ERROR, "No active audio");
  203. return false;
  204. }
  205. if (!new_stream(data, &data->audio, &data->acodec,
  206. data->output->oformat->audio_codec))
  207. return false;
  208. context = data->audio->codec;
  209. context->bit_rate = 128000;
  210. context->channels = get_audio_channels(aoi.speakers);
  211. context->sample_rate = aoi.samples_per_sec;
  212. context->sample_fmt = data->acodec->sample_fmts ?
  213. data->acodec->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
  214. data->audio_samplerate = aoi.samples_per_sec;
  215. data->audio_format = convert_ffmpeg_sample_format(context->sample_fmt);
  216. data->audio_planes = get_audio_planes(data->audio_format, aoi.speakers);
  217. data->audio_size = get_audio_size(data->audio_format, aoi.speakers, 1);
  218. if (data->output->oformat->flags & AVFMT_GLOBALHEADER)
  219. context->flags |= CODEC_FLAG_GLOBAL_HEADER;
  220. return open_audio_codec(data);
  221. }
  222. static inline bool init_streams(struct ffmpeg_data *data)
  223. {
  224. AVOutputFormat *format = data->output->oformat;
  225. if (format->video_codec != AV_CODEC_ID_NONE)
  226. if (!create_video_stream(data))
  227. return false;
  228. if (format->audio_codec != AV_CODEC_ID_NONE)
  229. if (!create_audio_stream(data))
  230. return false;
  231. return true;
  232. }
  233. static inline bool open_output_file(struct ffmpeg_data *data)
  234. {
  235. AVOutputFormat *format = data->output->oformat;
  236. int ret;
  237. if ((format->flags & AVFMT_NOFILE) == 0) {
  238. ret = avio_open(&data->output->pb, data->filename_test,
  239. AVIO_FLAG_WRITE);
  240. if (ret < 0) {
  241. blog(LOG_ERROR, "Couldn't open file '%s', %s",
  242. data->filename_test, av_err2str(ret));
  243. return false;
  244. }
  245. }
  246. ret = avformat_write_header(data->output, NULL);
  247. if (ret < 0) {
  248. blog(LOG_ERROR, "Error opening file '%s': %s",
  249. data->filename_test, av_err2str(ret));
  250. return false;
  251. }
  252. return true;
  253. }
  254. static void close_video(struct ffmpeg_data *data)
  255. {
  256. avcodec_close(data->video->codec);
  257. avpicture_free(&data->dst_picture);
  258. av_frame_free(&data->vframe);
  259. }
  260. static void close_audio(struct ffmpeg_data *data)
  261. {
  262. for (size_t i = 0; i < MAX_AV_PLANES; i++)
  263. circlebuf_free(&data->excess_frames[i]);
  264. av_freep(&data->samples[0]);
  265. avcodec_close(data->audio->codec);
  266. av_frame_free(&data->aframe);
  267. }
  268. static void ffmpeg_data_free(struct ffmpeg_data *data)
  269. {
  270. if (data->initialized)
  271. av_write_trailer(data->output);
  272. if (data->video)
  273. close_video(data);
  274. if (data->audio)
  275. close_audio(data);
  276. if ((data->output->oformat->flags & AVFMT_NOFILE) == 0)
  277. avio_close(data->output->pb);
  278. avformat_free_context(data->output);
  279. memset(data, 0, sizeof(struct ffmpeg_data));
  280. }
  281. static bool ffmpeg_data_init(struct ffmpeg_data *data, const char *filename)
  282. {
  283. memset(data, 0, sizeof(struct ffmpeg_data));
  284. data->filename_test = filename;
  285. if (!filename || !*filename)
  286. return false;
  287. av_register_all();
  288. /* TODO: settings */
  289. avformat_alloc_output_context2(&data->output, NULL, NULL,
  290. data->filename_test);
  291. if (!data->output) {
  292. blog(LOG_ERROR, "Couldn't create avformat context");
  293. goto fail;
  294. }
  295. if (!init_streams(data))
  296. goto fail;
  297. if (!open_output_file(data))
  298. goto fail;
  299. data->initialized = true;
  300. return true;
  301. fail:
  302. blog(LOG_ERROR, "ffmpeg_data_init failed");
  303. ffmpeg_data_free(data);
  304. return false;
  305. }
  306. /* ------------------------------------------------------------------------- */
  307. static const char *ffmpeg_output_getname(const char *locale)
  308. {
  309. UNUSED_PARAMETER(locale);
  310. return "FFmpeg file output";
  311. }
  312. static void ffmpeg_log_callback(void *param, int level, const char *format,
  313. va_list args)
  314. {
  315. if (level < AV_LOG_WARNING)
  316. blogva(LOG_DEBUG, format, args);
  317. UNUSED_PARAMETER(param);
  318. }
  319. static void *ffmpeg_output_create(obs_data_t settings, obs_output_t output)
  320. {
  321. struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
  322. data->output = output;
  323. av_log_set_callback(ffmpeg_log_callback);
  324. UNUSED_PARAMETER(settings);
  325. return data;
  326. }
  327. static void ffmpeg_output_destroy(void *data)
  328. {
  329. struct ffmpeg_output *output = data;
  330. if (output) {
  331. if (output->active)
  332. ffmpeg_data_free(&output->ff_data);
  333. bfree(data);
  334. }
  335. }
  336. static inline int64_t rescale_ts(int64_t val, AVCodecContext *context,
  337. AVStream *stream)
  338. {
  339. return av_rescale_q_rnd(val, context->time_base,
  340. stream->time_base,
  341. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  342. }
  343. #define YUV420_PLANES 3
  344. static inline void copy_data(AVPicture *pic, const struct video_data *frame,
  345. int height)
  346. {
  347. for (int plane = 0; plane < YUV420_PLANES; plane++) {
  348. int frame_rowsize = (int)frame->linesize[plane];
  349. int pic_rowsize = pic->linesize[plane];
  350. int bytes = frame_rowsize < pic_rowsize ?
  351. frame_rowsize : pic_rowsize;
  352. int plane_height = plane == 0 ? height : height/2;
  353. for (int y = 0; y < plane_height; y++) {
  354. int pos_frame = y * frame_rowsize;
  355. int pos_pic = y * pic_rowsize;
  356. memcpy(pic->data[plane] + pos_pic,
  357. frame->data[plane] + pos_frame,
  358. bytes);
  359. }
  360. }
  361. }
  362. static void receive_video(void *param, const struct video_data *frame)
  363. {
  364. struct ffmpeg_output *output = param;
  365. struct ffmpeg_data *data = &output->ff_data;
  366. AVCodecContext *context = data->video->codec;
  367. AVPacket packet = {0};
  368. int ret, got_packet;
  369. av_init_packet(&packet);
  370. if (!data->start_timestamp)
  371. data->start_timestamp = frame->timestamp;
  372. if (context->pix_fmt != AV_PIX_FMT_YUV420P)
  373. sws_scale(data->swscale, frame->data,
  374. (const int*)frame->linesize,
  375. 0, context->height, data->dst_picture.data,
  376. data->dst_picture.linesize);
  377. else
  378. copy_data(&data->dst_picture, frame, context->height);
  379. if (data->output->flags & AVFMT_RAWPICTURE) {
  380. packet.flags |= AV_PKT_FLAG_KEY;
  381. packet.stream_index = data->video->index;
  382. packet.data = data->dst_picture.data[0];
  383. packet.size = sizeof(AVPicture);
  384. ret = av_interleaved_write_frame(data->output, &packet);
  385. } else {
  386. data->vframe->pts = data->total_frames;
  387. ret = avcodec_encode_video2(context, &packet, data->vframe,
  388. &got_packet);
  389. if (ret < 0) {
  390. blog(LOG_ERROR, "receive_video: Error encoding "
  391. "video: %s", av_err2str(ret));
  392. return;
  393. }
  394. if (!ret && got_packet && packet.size) {
  395. packet.pts = rescale_ts(packet.pts, context,
  396. data->video);
  397. packet.dts = rescale_ts(packet.dts, context,
  398. data->video);
  399. packet.duration = (int)av_rescale_q(packet.duration,
  400. context->time_base,
  401. data->video->time_base);
  402. ret = av_interleaved_write_frame(data->output,
  403. &packet);
  404. } else {
  405. ret = 0;
  406. }
  407. }
  408. if (ret != 0) {
  409. blog(LOG_ERROR, "receive_video: Error writing video: %s",
  410. av_err2str(ret));
  411. }
  412. data->total_frames++;
  413. }
  414. static inline void encode_audio(struct ffmpeg_data *output,
  415. struct AVCodecContext *context, size_t block_size)
  416. {
  417. AVPacket packet = {0};
  418. int ret, got_packet;
  419. size_t total_size = output->frame_size * block_size * context->channels;
  420. output->aframe->nb_samples = output->frame_size;
  421. output->aframe->pts = av_rescale_q(output->total_samples,
  422. (AVRational){1, context->sample_rate},
  423. context->time_base);
  424. ret = avcodec_fill_audio_frame(output->aframe, context->channels,
  425. context->sample_fmt, output->samples[0],
  426. (int)total_size, 1);
  427. if (ret < 0) {
  428. blog(LOG_ERROR, "receive_audio: avcodec_fill_audio_frame "
  429. "failed: %s", av_err2str(ret));
  430. return;
  431. }
  432. output->total_samples += output->frame_size;
  433. ret = avcodec_encode_audio2(context, &packet, output->aframe,
  434. &got_packet);
  435. if (ret < 0) {
  436. blog(LOG_ERROR, "receive_audio: Error encoding audio: %s",
  437. av_err2str(ret));
  438. return;
  439. }
  440. if (!got_packet)
  441. return;
  442. packet.pts = rescale_ts(packet.pts, context, output->audio);
  443. packet.dts = rescale_ts(packet.dts, context, output->audio);
  444. packet.duration = (int)av_rescale_q(packet.duration, context->time_base,
  445. output->audio->time_base);
  446. packet.stream_index = output->audio->index;
  447. ret = av_interleaved_write_frame(output->output, &packet);
  448. if (ret != 0)
  449. blog(LOG_ERROR, "receive_audio: Error writing audio: %s",
  450. av_err2str(ret));
  451. }
  452. static bool prepare_audio(struct ffmpeg_data *data,
  453. const struct audio_data *frame, struct audio_data *output)
  454. {
  455. *output = *frame;
  456. if (frame->timestamp < data->start_timestamp) {
  457. uint64_t duration = (uint64_t)frame->frames * 1000000000 /
  458. (uint64_t)data->audio_samplerate;
  459. uint64_t end_ts = (frame->timestamp + duration);
  460. uint64_t cutoff;
  461. if (end_ts <= data->start_timestamp)
  462. return false;
  463. cutoff = data->start_timestamp - frame->timestamp;
  464. cutoff = cutoff * (uint64_t)data->audio_samplerate /
  465. 1000000000;
  466. for (size_t i = 0; i < data->audio_planes; i++)
  467. output->data[i] += data->audio_size * (uint32_t)cutoff;
  468. output->frames -= (uint32_t)cutoff;
  469. }
  470. return true;
  471. }
  472. static void receive_audio(void *param, const struct audio_data *frame)
  473. {
  474. struct ffmpeg_output *output = param;
  475. struct ffmpeg_data *data = &output->ff_data;
  476. size_t frame_size_bytes;
  477. struct audio_data in;
  478. AVCodecContext *context = data->audio->codec;
  479. if (!data->start_timestamp)
  480. return;
  481. if (!prepare_audio(data, frame, &in))
  482. return;
  483. frame_size_bytes = (size_t)data->frame_size * data->audio_size;
  484. for (size_t i = 0; i < data->audio_planes; i++)
  485. circlebuf_push_back(&data->excess_frames[i], in.data[i],
  486. in.frames * data->audio_size);
  487. while (data->excess_frames[0].size >= frame_size_bytes) {
  488. for (size_t i = 0; i < data->audio_planes; i++)
  489. circlebuf_pop_front(&data->excess_frames[i],
  490. data->samples[i], frame_size_bytes);
  491. encode_audio(data, context, data->audio_size);
  492. }
  493. }
  494. static bool ffmpeg_output_start(void *data)
  495. {
  496. struct ffmpeg_output *output = data;
  497. video_t video = obs_video();
  498. audio_t audio = obs_audio();
  499. if (!video || !audio) {
  500. blog(LOG_ERROR, "ffmpeg_output_start: audio and video must "
  501. "both be active (at least as of this writing)");
  502. return false;
  503. }
  504. const char *filename_test;
  505. obs_data_t settings = obs_output_get_settings(output->output);
  506. filename_test = obs_data_getstring(settings, "filename");
  507. obs_data_release(settings);
  508. if (!filename_test || !*filename_test)
  509. return false;
  510. if (!ffmpeg_data_init(&output->ff_data, filename_test))
  511. return false;
  512. struct audio_convert_info aci = {
  513. .format = output->ff_data.audio_format
  514. };
  515. struct video_scale_info vsi = {
  516. .format = VIDEO_FORMAT_I420
  517. };
  518. video_output_connect(video, &vsi, receive_video, output);
  519. audio_output_connect(audio, &aci, receive_audio, output);
  520. output->active = true;
  521. return true;
  522. }
  523. static void ffmpeg_output_stop(void *data)
  524. {
  525. struct ffmpeg_output *output = data;
  526. if (output->active) {
  527. output->active = false;
  528. video_output_disconnect(obs_video(), receive_video, data);
  529. audio_output_disconnect(obs_audio(), receive_audio, data);
  530. ffmpeg_data_free(&output->ff_data);
  531. }
  532. }
  533. static bool ffmpeg_output_active(void *data)
  534. {
  535. struct ffmpeg_output *output = data;
  536. return output->active;
  537. }
  538. struct obs_output_info ffmpeg_output = {
  539. .id = "ffmpeg_output",
  540. .getname = ffmpeg_output_getname,
  541. .create = ffmpeg_output_create,
  542. .destroy = ffmpeg_output_destroy,
  543. .start = ffmpeg_output_start,
  544. .stop = ffmpeg_output_stop,
  545. .active = ffmpeg_output_active
  546. };