obs-ffmpeg-output.c 16 KB

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