obs-ffmpeg-output.c 13 KB

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