obs-ffmpeg-output.c 14 KB

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