obs-ffmpeg-output.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. #include <libavutil/frame.h>
  19. struct ffmpeg_data {
  20. AVStream *video;
  21. AVStream *audio;
  22. AVCodec *acodec;
  23. AVCodec *vcodec;
  24. AVFormatContext *output;
  25. struct SwsContext *swscale;
  26. AVPicture dst_picture;
  27. AVFrame *vframe;
  28. int frame_size;
  29. int total_frames;
  30. struct circlebuf excess_frames[MAX_AV_PLANES];
  31. uint8_t *samples[MAX_AV_PLANES];
  32. AVFrame *aframe;
  33. int total_samples;
  34. const char *filename_test;
  35. bool initialized;
  36. };
  37. struct ffmpeg_output {
  38. obs_output_t output;
  39. volatile bool active;
  40. struct ffmpeg_data ff_data;
  41. };
  42. /* ------------------------------------------------------------------------- */
  43. /* TODO: remove these later */
  44. #define SPS_TODO 44100
  45. /* NOTE: much of this stuff is test stuff that was more or less copied from
  46. * the muxing.c ffmpeg example */
  47. static inline enum AVPixelFormat obs_to_ffmpeg_video_format(
  48. enum video_format format)
  49. {
  50. switch (format) {
  51. case VIDEO_FORMAT_NONE: return AV_PIX_FMT_NONE;
  52. case VIDEO_FORMAT_I420: return AV_PIX_FMT_YUV420P;
  53. case VIDEO_FORMAT_NV12: return AV_PIX_FMT_NV12;
  54. case VIDEO_FORMAT_YVYU: return AV_PIX_FMT_NONE;
  55. case VIDEO_FORMAT_YUY2: return AV_PIX_FMT_YUYV422;
  56. case VIDEO_FORMAT_UYVY: return AV_PIX_FMT_UYVY422;
  57. case VIDEO_FORMAT_RGBA: return AV_PIX_FMT_RGBA;
  58. case VIDEO_FORMAT_BGRA: return AV_PIX_FMT_BGRA;
  59. case VIDEO_FORMAT_BGRX: return AV_PIX_FMT_BGRA;
  60. }
  61. return AV_PIX_FMT_NONE;
  62. }
  63. static bool new_stream(struct ffmpeg_data *data, AVStream **stream,
  64. AVCodec **codec, enum AVCodecID id)
  65. {
  66. *codec = avcodec_find_encoder(id);
  67. if (!*codec) {
  68. blog(LOG_ERROR, "Couldn't find encoder '%s'",
  69. avcodec_get_name(id));
  70. return false;
  71. }
  72. *stream = avformat_new_stream(data->output, *codec);
  73. if (!*stream) {
  74. blog(LOG_ERROR, "Couldn't create stream for encoder '%s'",
  75. avcodec_get_name(id));
  76. return false;
  77. }
  78. (*stream)->id = data->output->nb_streams-1;
  79. return true;
  80. }
  81. static bool open_video_codec(struct ffmpeg_data *data)
  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))
  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. {
  152. AVCodecContext *context = data->audio->codec;
  153. int ret;
  154. data->aframe = av_frame_alloc();
  155. if (!data->aframe) {
  156. blog(LOG_ERROR, "Failed to allocate audio frame");
  157. return false;
  158. }
  159. context->strict_std_compliance = -2;
  160. ret = avcodec_open2(context, data->acodec, NULL);
  161. if (ret < 0) {
  162. blog(LOG_ERROR, "Failed to open audio codec: %s",
  163. av_err2str(ret));
  164. return false;
  165. }
  166. data->frame_size = context->frame_size ? context->frame_size : 1024;
  167. ret = av_samples_alloc(data->samples, NULL, context->channels,
  168. data->frame_size, context->sample_fmt, 0);
  169. if (ret < 0) {
  170. blog(LOG_ERROR, "Failed to create audio buffer: %s",
  171. av_err2str(ret));
  172. return false;
  173. }
  174. return true;
  175. }
  176. static bool create_audio_stream(struct ffmpeg_data *data)
  177. {
  178. AVCodecContext *context;
  179. struct audio_output_info aoi;
  180. if (!obs_get_audio_info(&aoi)) {
  181. blog(LOG_ERROR, "No active audio");
  182. return false;
  183. }
  184. if (!new_stream(data, &data->audio, &data->acodec,
  185. data->output->oformat->audio_codec))
  186. return false;
  187. context = data->audio->codec;
  188. context->bit_rate = 128000;
  189. context->channels = get_audio_channels(aoi.speakers);
  190. context->sample_rate = aoi.samples_per_sec;
  191. context->sample_fmt = data->acodec->sample_fmts ?
  192. data->acodec->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
  193. if (data->output->oformat->flags & AVFMT_GLOBALHEADER)
  194. context->flags |= CODEC_FLAG_GLOBAL_HEADER;
  195. return open_audio_codec(data);
  196. }
  197. static inline bool init_streams(struct ffmpeg_data *data)
  198. {
  199. AVOutputFormat *format = data->output->oformat;
  200. if (format->video_codec != AV_CODEC_ID_NONE)
  201. if (!create_video_stream(data))
  202. return false;
  203. if (format->audio_codec != AV_CODEC_ID_NONE)
  204. if (!create_audio_stream(data))
  205. return false;
  206. return true;
  207. }
  208. static inline bool open_output_file(struct ffmpeg_data *data)
  209. {
  210. AVOutputFormat *format = data->output->oformat;
  211. int ret;
  212. if ((format->flags & AVFMT_NOFILE) == 0) {
  213. ret = avio_open(&data->output->pb, data->filename_test,
  214. AVIO_FLAG_WRITE);
  215. if (ret < 0) {
  216. blog(LOG_ERROR, "Couldn't open file '%s', %s",
  217. data->filename_test, av_err2str(ret));
  218. return false;
  219. }
  220. }
  221. ret = avformat_write_header(data->output, NULL);
  222. if (ret < 0) {
  223. blog(LOG_ERROR, "Error opening file '%s': %s",
  224. data->filename_test, av_err2str(ret));
  225. return false;
  226. }
  227. return true;
  228. }
  229. static void close_video(struct ffmpeg_data *data)
  230. {
  231. avcodec_close(data->video->codec);
  232. avpicture_free(&data->dst_picture);
  233. av_frame_free(&data->vframe);
  234. }
  235. static void close_audio(struct ffmpeg_data *data)
  236. {
  237. for (size_t i = 0; i < MAX_AV_PLANES; i++)
  238. circlebuf_free(&data->excess_frames[i]);
  239. av_freep(&data->samples[0]);
  240. avcodec_close(data->audio->codec);
  241. av_frame_free(&data->aframe);
  242. }
  243. static void ffmpeg_data_free(struct ffmpeg_data *data)
  244. {
  245. if (data->initialized)
  246. av_write_trailer(data->output);
  247. if (data->video)
  248. close_video(data);
  249. if (data->audio)
  250. close_audio(data);
  251. if ((data->output->oformat->flags & AVFMT_NOFILE) == 0)
  252. avio_close(data->output->pb);
  253. avformat_free_context(data->output);
  254. memset(data, 0, sizeof(struct ffmpeg_data));
  255. }
  256. static bool ffmpeg_data_init(struct ffmpeg_data *data, const char *filename)
  257. {
  258. memset(data, 0, sizeof(struct ffmpeg_data));
  259. data->filename_test = filename;
  260. if (!filename || !*filename)
  261. return false;
  262. av_register_all();
  263. /* TODO: settings */
  264. avformat_alloc_output_context2(&data->output, NULL, NULL,
  265. data->filename_test);
  266. if (!data->output) {
  267. blog(LOG_ERROR, "Couldn't create avformat context");
  268. goto fail;
  269. }
  270. if (!init_streams(data))
  271. goto fail;
  272. if (!open_output_file(data))
  273. goto fail;
  274. data->initialized = true;
  275. return true;
  276. fail:
  277. blog(LOG_ERROR, "ffmpeg_data_init failed");
  278. ffmpeg_data_free(data);
  279. return false;
  280. }
  281. /* ------------------------------------------------------------------------- */
  282. static const char *ffmpeg_output_getname(const char *locale)
  283. {
  284. UNUSED_PARAMETER(locale);
  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_DEBUG, format, args);
  291. UNUSED_PARAMETER(param);
  292. UNUSED_PARAMETER(bla);
  293. }
  294. static void *ffmpeg_output_create(obs_data_t settings,
  295. obs_output_t output)
  296. {
  297. struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
  298. data->output = output;
  299. av_log_set_callback(ffmpeg_log_callback);
  300. UNUSED_PARAMETER(settings);
  301. return data;
  302. }
  303. static void ffmpeg_output_destroy(void *data)
  304. {
  305. struct ffmpeg_output *output = data;
  306. if (output) {
  307. if (output->active)
  308. ffmpeg_data_free(&output->ff_data);
  309. bfree(data);
  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,
  348. (const int*)frame->linesize,
  349. 0, context->height, data->dst_picture.data,
  350. data->dst_picture.linesize);
  351. else
  352. copy_data(&data->dst_picture, frame, context->height);
  353. if (data->output->flags & AVFMT_RAWPICTURE) {
  354. packet.flags |= AV_PKT_FLAG_KEY;
  355. packet.stream_index = data->video->index;
  356. packet.data = data->dst_picture.data[0];
  357. packet.size = sizeof(AVPicture);
  358. ret = av_interleaved_write_frame(data->output, &packet);
  359. } else {
  360. data->vframe->pts = data->total_frames;
  361. ret = avcodec_encode_video2(context, &packet, data->vframe,
  362. &got_packet);
  363. if (ret < 0) {
  364. blog(LOG_ERROR, "receive_video: Error encoding "
  365. "video: %s", av_err2str(ret));
  366. return;
  367. }
  368. if (!ret && got_packet && packet.size) {
  369. packet.pts = rescale_ts(packet.pts, context,
  370. data->video);
  371. packet.dts = rescale_ts(packet.dts, context,
  372. data->video);
  373. packet.duration = (int)av_rescale_q(packet.duration,
  374. context->time_base,
  375. data->video->time_base);
  376. ret = av_interleaved_write_frame(data->output,
  377. &packet);
  378. } else {
  379. ret = 0;
  380. }
  381. }
  382. if (ret != 0) {
  383. blog(LOG_ERROR, "receive_video: Error writing video: %s",
  384. av_err2str(ret));
  385. }
  386. data->total_frames++;
  387. }
  388. static inline void encode_audio(struct ffmpeg_data *output,
  389. struct AVCodecContext *context, size_t block_size)
  390. {
  391. AVPacket packet = {0};
  392. int ret, got_packet;
  393. size_t total_size = output->frame_size * block_size * context->channels;
  394. output->aframe->nb_samples = output->frame_size;
  395. output->aframe->pts = av_rescale_q(output->total_samples,
  396. (AVRational){1, context->sample_rate},
  397. context->time_base);
  398. ret = avcodec_fill_audio_frame(output->aframe, context->channels,
  399. context->sample_fmt, output->samples[0],
  400. (int)total_size, 1);
  401. if (ret < 0) {
  402. blog(LOG_ERROR, "receive_audio: avcodec_fill_audio_frame "
  403. "failed: %s", av_err2str(ret));
  404. return;
  405. }
  406. output->total_samples += output->frame_size;
  407. ret = avcodec_encode_audio2(context, &packet, output->aframe,
  408. &got_packet);
  409. if (ret < 0) {
  410. blog(LOG_ERROR, "receive_audio: Error encoding audio: %s",
  411. av_err2str(ret));
  412. return;
  413. }
  414. if (!got_packet)
  415. return;
  416. packet.pts = rescale_ts(packet.pts, context, output->audio);
  417. packet.dts = rescale_ts(packet.dts, context, output->audio);
  418. packet.duration = (int)av_rescale_q(packet.duration, context->time_base,
  419. output->audio->time_base);
  420. packet.stream_index = output->audio->index;
  421. ret = av_interleaved_write_frame(output->output, &packet);
  422. if (ret != 0)
  423. blog(LOG_ERROR, "receive_audio: Error writing audio: %s",
  424. av_err2str(ret));
  425. }
  426. static void receive_audio(void *param, const struct audio_data *frame)
  427. {
  428. struct ffmpeg_output *output = param;
  429. struct ffmpeg_data *data = &output->ff_data;
  430. AVCodecContext *context = data->audio->codec;
  431. size_t planes = audio_output_planes(obs_audio());
  432. size_t block_size = audio_output_blocksize(obs_audio());
  433. size_t frame_size_bytes = (size_t)data->frame_size * block_size;
  434. for (size_t i = 0; i < planes; i++)
  435. circlebuf_push_back(&data->excess_frames[i], frame->data[0],
  436. frame->frames * block_size);
  437. while (data->excess_frames[0].size >= frame_size_bytes) {
  438. for (size_t i = 0; i < planes; i++)
  439. circlebuf_pop_front(&data->excess_frames[i],
  440. data->samples[i], frame_size_bytes);
  441. encode_audio(data, context, block_size);
  442. }
  443. }
  444. static bool ffmpeg_output_start(void *data)
  445. {
  446. struct ffmpeg_output *output = data;
  447. video_t video = obs_video();
  448. audio_t audio = obs_audio();
  449. if (!video || !audio) {
  450. blog(LOG_ERROR, "ffmpeg_output_start: audio and video must "
  451. "both be active (at least as of this writing)");
  452. return false;
  453. }
  454. const char *filename_test;
  455. obs_data_t settings = obs_output_get_settings(output->output);
  456. filename_test = obs_data_getstring(settings, "filename");
  457. obs_data_release(settings);
  458. if (!filename_test || !*filename_test)
  459. return false;
  460. if (!ffmpeg_data_init(&output->ff_data, filename_test))
  461. return false;
  462. struct audio_convert_info aci;
  463. aci.samples_per_sec = SPS_TODO;
  464. aci.format = AUDIO_FORMAT_FLOAT;
  465. aci.speakers = SPEAKERS_STEREO;
  466. struct video_convert_info vci;
  467. vci.format = VIDEO_FORMAT_I420;
  468. vci.width = 0;
  469. vci.height = 0;
  470. video_output_connect(video, &vci, receive_video, output);
  471. audio_output_connect(audio, &aci, receive_audio, output);
  472. output->active = true;
  473. return true;
  474. }
  475. static void ffmpeg_output_stop(void *data)
  476. {
  477. struct ffmpeg_output *output = data;
  478. if (output->active) {
  479. output->active = false;
  480. video_output_disconnect(obs_video(), receive_video, data);
  481. audio_output_disconnect(obs_audio(), receive_audio, data);
  482. ffmpeg_data_free(&output->ff_data);
  483. }
  484. }
  485. static bool ffmpeg_output_active(void *data)
  486. {
  487. struct ffmpeg_output *output = data;
  488. return output->active;
  489. }
  490. struct obs_output_info ffmpeg_output = {
  491. .id = "ffmpeg_output",
  492. .getname = ffmpeg_output_getname,
  493. .create = ffmpeg_output_create,
  494. .destroy = ffmpeg_output_destroy,
  495. .start = ffmpeg_output_start,
  496. .stop = ffmpeg_output_stop,
  497. .active = ffmpeg_output_active
  498. };