obs-ffmpeg-output.c 15 KB

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