obs-ffmpeg-output.c 16 KB

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