obs-ffmpeg-output.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 = bmalloc(sizeof(struct ffmpeg_output));
  268. memset(data, 0, sizeof(struct ffmpeg_output));
  269. data->output = output;
  270. av_log_set_callback(test_callback);
  271. return data;
  272. }
  273. void ffmpeg_output_destroy(struct ffmpeg_output *data)
  274. {
  275. if (data) {
  276. if (data->active)
  277. ffmpeg_data_free(&data->ff_data);
  278. bfree(data);
  279. }
  280. }
  281. void ffmpeg_output_update(struct ffmpeg_output *data, const char *settings)
  282. {
  283. }
  284. static inline int64_t rescale_ts(int64_t val, AVCodecContext *context,
  285. AVStream *stream)
  286. {
  287. return av_rescale_q_rnd(val, context->time_base,
  288. stream->time_base,
  289. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  290. }
  291. #define YUV420_PLANES 3
  292. static inline void copy_data(AVPicture *pic, const struct video_frame *frame,
  293. int height)
  294. {
  295. for (int plane = 0; plane < YUV420_PLANES; plane++) {
  296. int frame_rowsize = (int)frame->linesize[plane];
  297. int pic_rowsize = pic->linesize[plane];
  298. int bytes = frame_rowsize < pic_rowsize ?
  299. frame_rowsize : pic_rowsize;
  300. int plane_height = plane == 0 ? height : height/2;
  301. for (int y = 0; y < plane_height; y++) {
  302. int pos_frame = y * frame_rowsize;
  303. int pos_pic = y * pic_rowsize;
  304. memcpy(pic->data[plane] + pos_pic,
  305. frame->data[plane] + pos_frame,
  306. bytes);
  307. }
  308. }
  309. }
  310. static void receive_video(void *param, const struct video_frame *frame)
  311. {
  312. struct ffmpeg_output *output = param;
  313. struct ffmpeg_data *data = &output->ff_data;
  314. AVCodecContext *context = data->video->codec;
  315. AVPacket packet = {0};
  316. int ret, got_packet;
  317. av_init_packet(&packet);
  318. if (context->pix_fmt != AV_PIX_FMT_YUV420P)
  319. sws_scale(data->swscale, frame->data, frame->linesize,
  320. 0, context->height, data->dst_picture.data,
  321. data->dst_picture.linesize);
  322. else
  323. copy_data(&data->dst_picture, frame, context->height);
  324. if (data->output->flags & AVFMT_RAWPICTURE) {
  325. packet.flags |= AV_PKT_FLAG_KEY;
  326. packet.stream_index = data->video->index;
  327. packet.data = data->dst_picture.data[0];
  328. packet.size = sizeof(AVPicture);
  329. ret = av_interleaved_write_frame(data->output, &packet);
  330. } else {
  331. data->vframe->pts = data->total_frames;
  332. ret = avcodec_encode_video2(context, &packet, data->vframe,
  333. &got_packet);
  334. if (ret < 0) {
  335. blog(LOG_ERROR, "receive_video: Error encoding "
  336. "video: %s", av_err2str(ret));
  337. return;
  338. }
  339. if (!ret && got_packet && packet.size) {
  340. packet.pts = rescale_ts(packet.pts, context,
  341. data->video);
  342. packet.dts = rescale_ts(packet.dts, context,
  343. data->video);
  344. packet.duration = (int)av_rescale_q(packet.duration,
  345. context->time_base,
  346. data->video->time_base);
  347. ret = av_interleaved_write_frame(data->output, &packet);
  348. } else {
  349. ret = 0;
  350. }
  351. }
  352. if (ret != 0) {
  353. blog(LOG_ERROR, "receive_video: Error writing video: %s",
  354. av_err2str(ret));
  355. }
  356. data->total_frames++;
  357. }
  358. static inline void encode_audio(struct ffmpeg_data *data,
  359. struct AVCodecContext *context, size_t block_size)
  360. {
  361. AVPacket packet = {0};
  362. int ret, got_packet;
  363. size_t total_size = data->frame_size * block_size * context->channels;
  364. data->aframe->nb_samples = data->frame_size;
  365. data->aframe->pts = av_rescale_q(data->total_samples,
  366. (AVRational){1, context->sample_rate},
  367. context->time_base);
  368. ret = avcodec_fill_audio_frame(data->aframe, context->channels,
  369. context->sample_fmt, data->samples[0],
  370. total_size, 1);
  371. if (ret < 0) {
  372. blog(LOG_ERROR, "receive_audio: avcodec_fill_audio_frame "
  373. "failed: %s", av_err2str(ret));
  374. return;
  375. }
  376. data->total_samples += data->frame_size;
  377. ret = avcodec_encode_audio2(context, &packet, data->aframe,
  378. &got_packet);
  379. if (ret < 0) {
  380. blog(LOG_ERROR, "receive_audio: Error encoding audio: %s",
  381. av_err2str(ret));
  382. return;
  383. }
  384. if (!got_packet)
  385. return;
  386. packet.pts = rescale_ts(packet.pts, context, data->audio);
  387. packet.dts = rescale_ts(packet.dts, context, data->audio);
  388. packet.duration = (int)av_rescale_q(packet.duration, context->time_base,
  389. data->audio->time_base);
  390. packet.stream_index = data->audio->index;
  391. ret = av_interleaved_write_frame(data->output, &packet);
  392. if (ret != 0)
  393. blog(LOG_ERROR, "receive_audio: Error writing audio: %s",
  394. av_err2str(ret));
  395. }
  396. static void receive_audio(void *param, const struct audio_data *frame)
  397. {
  398. struct ffmpeg_output *output = param;
  399. struct ffmpeg_data *data = &output->ff_data;
  400. AVCodecContext *context = data->audio->codec;
  401. size_t planes = audio_output_planes(obs_audio());
  402. size_t block_size = audio_output_blocksize(obs_audio());
  403. size_t frame_size_bytes = (size_t)data->frame_size * block_size;
  404. for (size_t i = 0; i < planes; i++)
  405. circlebuf_push_back(&data->excess_frames[i], frame->data[0],
  406. frame->frames * block_size);
  407. while (data->excess_frames[0].size >= frame_size_bytes) {
  408. for (size_t i = 0; i < planes; i++)
  409. circlebuf_pop_front(&data->excess_frames[i],
  410. data->samples[i], frame_size_bytes);
  411. encode_audio(data, context, block_size);
  412. }
  413. }
  414. bool ffmpeg_output_start(struct ffmpeg_output *data)
  415. {
  416. video_t video = obs_video();
  417. audio_t audio = obs_audio();
  418. if (!video || !audio) {
  419. blog(LOG_ERROR, "ffmpeg_output_start: audio and video must "
  420. "both be active (at least as of this writing)");
  421. return false;
  422. }
  423. if (!ffmpeg_data_init(&data->ff_data))
  424. return false;
  425. struct audio_convert_info aci;
  426. aci.samples_per_sec = SPS_TODO;
  427. aci.format = AUDIO_FORMAT_FLOAT;
  428. aci.speakers = SPEAKERS_STEREO;
  429. struct video_convert_info vci;
  430. vci.format = VIDEO_FORMAT_I420;
  431. vci.width = 0;
  432. vci.height = 0;
  433. video_output_connect(video, &vci, receive_video, data);
  434. audio_output_connect(audio, &aci, receive_audio, data);
  435. data->active = true;
  436. return true;
  437. }
  438. void ffmpeg_output_stop(struct ffmpeg_output *data)
  439. {
  440. if (data->active) {
  441. data->active = false;
  442. video_output_disconnect(obs_video(), receive_video, data);
  443. audio_output_disconnect(obs_audio(), receive_audio, data);
  444. ffmpeg_data_free(&data->ff_data);
  445. }
  446. }
  447. bool ffmpeg_output_active(struct ffmpeg_output *data)
  448. {
  449. return data->active;
  450. }