You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

536 lines
16KB

  1. /*
  2. * Copyright (c) 2003 Fabrice Bellard
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  17. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. /**
  23. * @file
  24. * libavformat API example.
  25. *
  26. * @example output.c
  27. * Output a media file in any supported libavformat format. The default
  28. * codecs are used.
  29. */
  30. #include <stdlib.h>
  31. #include <stdio.h>
  32. #include <string.h>
  33. #include <math.h>
  34. #include "libavutil/channel_layout.h"
  35. #include "libavutil/mathematics.h"
  36. #include "libavformat/avformat.h"
  37. #include "libswscale/swscale.h"
  38. /* 5 seconds stream duration */
  39. #define STREAM_DURATION 5.0
  40. #define STREAM_FRAME_RATE 25 /* 25 images/s */
  41. #define STREAM_NB_FRAMES ((int)(STREAM_DURATION * STREAM_FRAME_RATE))
  42. #define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */
  43. static int sws_flags = SWS_BICUBIC;
  44. // a wrapper around a single output AVStream
  45. typedef struct OutputStream {
  46. AVStream *st;
  47. AVFrame *frame;
  48. AVFrame *tmp_frame;
  49. float t, tincr, tincr2;
  50. } OutputStream;
  51. /**************************************************************/
  52. /* audio output */
  53. /*
  54. * add an audio output stream
  55. */
  56. static void add_audio_stream(OutputStream *ost, AVFormatContext *oc,
  57. enum AVCodecID codec_id)
  58. {
  59. AVCodecContext *c;
  60. AVCodec *codec;
  61. /* find the audio encoder */
  62. codec = avcodec_find_encoder(codec_id);
  63. if (!codec) {
  64. fprintf(stderr, "codec not found\n");
  65. exit(1);
  66. }
  67. ost->st = avformat_new_stream(oc, codec);
  68. if (!ost->st) {
  69. fprintf(stderr, "Could not alloc stream\n");
  70. exit(1);
  71. }
  72. c = ost->st->codec;
  73. /* put sample parameters */
  74. c->sample_fmt = AV_SAMPLE_FMT_S16;
  75. c->bit_rate = 64000;
  76. c->sample_rate = 44100;
  77. c->channels = 2;
  78. c->channel_layout = AV_CH_LAYOUT_STEREO;
  79. // some formats want stream headers to be separate
  80. if (oc->oformat->flags & AVFMT_GLOBALHEADER)
  81. c->flags |= CODEC_FLAG_GLOBAL_HEADER;
  82. }
  83. static void open_audio(AVFormatContext *oc, OutputStream *ost)
  84. {
  85. AVCodecContext *c;
  86. int ret;
  87. c = ost->st->codec;
  88. /* open it */
  89. if (avcodec_open2(c, NULL, NULL) < 0) {
  90. fprintf(stderr, "could not open codec\n");
  91. exit(1);
  92. }
  93. /* init signal generator */
  94. ost->t = 0;
  95. ost->tincr = 2 * M_PI * 110.0 / c->sample_rate;
  96. /* increment frequency by 110 Hz per second */
  97. ost->tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
  98. ost->frame = av_frame_alloc();
  99. if (!ost->frame)
  100. exit(1);
  101. ost->frame->sample_rate = c->sample_rate;
  102. ost->frame->format = AV_SAMPLE_FMT_S16;
  103. ost->frame->channel_layout = c->channel_layout;
  104. if (c->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)
  105. ost->frame->nb_samples = 10000;
  106. else
  107. ost->frame->nb_samples = c->frame_size;
  108. ret = av_frame_get_buffer(ost->frame, 0);
  109. if (ret < 0) {
  110. fprintf(stderr, "Could not allocate an audio frame.\n");
  111. exit(1);
  112. }
  113. }
  114. /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
  115. * 'nb_channels' channels. */
  116. static void get_audio_frame(OutputStream *ost, AVFrame *frame, int nb_channels)
  117. {
  118. int j, i, v, ret;
  119. int16_t *q = (int16_t*)frame->data[0];
  120. /* when we pass a frame to the encoder, it may keep a reference to it
  121. * internally;
  122. * make sure we do not overwrite it here
  123. */
  124. ret = av_frame_make_writable(frame);
  125. if (ret < 0)
  126. exit(1);
  127. for (j = 0; j < frame->nb_samples; j++) {
  128. v = (int)(sin(ost->t) * 10000);
  129. for (i = 0; i < nb_channels; i++)
  130. *q++ = v;
  131. ost->t += ost->tincr;
  132. ost->tincr += ost->tincr2;
  133. }
  134. }
  135. static void write_audio_frame(AVFormatContext *oc, OutputStream *ost)
  136. {
  137. AVCodecContext *c;
  138. AVPacket pkt = { 0 }; // data and size must be 0;
  139. int got_packet, ret;
  140. av_init_packet(&pkt);
  141. c = ost->st->codec;
  142. get_audio_frame(ost, ost->frame, c->channels);
  143. avcodec_encode_audio2(c, &pkt, ost->frame, &got_packet);
  144. if (!got_packet)
  145. return;
  146. pkt.stream_index = ost->st->index;
  147. /* Write the compressed frame to the media file. */
  148. if (av_interleaved_write_frame(oc, &pkt) != 0) {
  149. fprintf(stderr, "Error while writing audio frame\n");
  150. exit(1);
  151. }
  152. }
  153. /**************************************************************/
  154. /* video output */
  155. static int frame_count;
  156. /* Add a video output stream. */
  157. static void add_video_stream(OutputStream *ost, AVFormatContext *oc,
  158. enum AVCodecID codec_id)
  159. {
  160. AVCodecContext *c;
  161. AVCodec *codec;
  162. /* find the video encoder */
  163. codec = avcodec_find_encoder(codec_id);
  164. if (!codec) {
  165. fprintf(stderr, "codec not found\n");
  166. exit(1);
  167. }
  168. ost->st = avformat_new_stream(oc, codec);
  169. if (!ost->st) {
  170. fprintf(stderr, "Could not alloc stream\n");
  171. exit(1);
  172. }
  173. c = ost->st->codec;
  174. /* Put sample parameters. */
  175. c->bit_rate = 400000;
  176. /* Resolution must be a multiple of two. */
  177. c->width = 352;
  178. c->height = 288;
  179. /* timebase: This is the fundamental unit of time (in seconds) in terms
  180. * of which frame timestamps are represented. For fixed-fps content,
  181. * timebase should be 1/framerate and timestamp increments should be
  182. * identical to 1. */
  183. c->time_base.den = STREAM_FRAME_RATE;
  184. c->time_base.num = 1;
  185. c->gop_size = 12; /* emit one intra frame every twelve frames at most */
  186. c->pix_fmt = STREAM_PIX_FMT;
  187. if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
  188. /* just for testing, we also add B frames */
  189. c->max_b_frames = 2;
  190. }
  191. if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
  192. /* Needed to avoid using macroblocks in which some coeffs overflow.
  193. * This does not happen with normal video, it just happens here as
  194. * the motion of the chroma plane does not match the luma plane. */
  195. c->mb_decision = 2;
  196. }
  197. /* Some formats want stream headers to be separate. */
  198. if (oc->oformat->flags & AVFMT_GLOBALHEADER)
  199. c->flags |= CODEC_FLAG_GLOBAL_HEADER;
  200. }
  201. static AVFrame *alloc_picture(enum AVPixelFormat pix_fmt, int width, int height)
  202. {
  203. AVFrame *picture;
  204. int ret;
  205. picture = av_frame_alloc();
  206. if (!picture)
  207. return NULL;
  208. picture->format = pix_fmt;
  209. picture->width = width;
  210. picture->height = height;
  211. /* allocate the buffers for the frame data */
  212. ret = av_frame_get_buffer(picture, 32);
  213. if (ret < 0) {
  214. fprintf(stderr, "Could not allocate frame data.\n");
  215. exit(1);
  216. }
  217. return picture;
  218. }
  219. static void open_video(AVFormatContext *oc, OutputStream *ost)
  220. {
  221. AVCodecContext *c;
  222. c = ost->st->codec;
  223. /* open the codec */
  224. if (avcodec_open2(c, NULL, NULL) < 0) {
  225. fprintf(stderr, "could not open codec\n");
  226. exit(1);
  227. }
  228. /* Allocate the encoded raw picture. */
  229. ost->frame = alloc_picture(c->pix_fmt, c->width, c->height);
  230. if (!ost->frame) {
  231. fprintf(stderr, "Could not allocate picture\n");
  232. exit(1);
  233. }
  234. /* If the output format is not YUV420P, then a temporary YUV420P
  235. * picture is needed too. It is then converted to the required
  236. * output format. */
  237. ost->tmp_frame = NULL;
  238. if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
  239. ost->tmp_frame = alloc_picture(AV_PIX_FMT_YUV420P, c->width, c->height);
  240. if (!ost->tmp_frame) {
  241. fprintf(stderr, "Could not allocate temporary picture\n");
  242. exit(1);
  243. }
  244. }
  245. }
  246. /* Prepare a dummy image. */
  247. static void fill_yuv_image(AVFrame *pict, int frame_index,
  248. int width, int height)
  249. {
  250. int x, y, i, ret;
  251. /* when we pass a frame to the encoder, it may keep a reference to it
  252. * internally;
  253. * make sure we do not overwrite it here
  254. */
  255. ret = av_frame_make_writable(pict);
  256. if (ret < 0)
  257. exit(1);
  258. i = frame_index;
  259. /* Y */
  260. for (y = 0; y < height; y++)
  261. for (x = 0; x < width; x++)
  262. pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
  263. /* Cb and Cr */
  264. for (y = 0; y < height / 2; y++) {
  265. for (x = 0; x < width / 2; x++) {
  266. pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
  267. pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
  268. }
  269. }
  270. }
  271. static void write_video_frame(AVFormatContext *oc, OutputStream *ost)
  272. {
  273. int ret;
  274. AVCodecContext *c;
  275. static struct SwsContext *img_convert_ctx;
  276. c = ost->st->codec;
  277. if (frame_count >= STREAM_NB_FRAMES) {
  278. /* No more frames to compress. The codec has a latency of a few
  279. * frames if using B-frames, so we get the last frames by
  280. * passing the same picture again. */
  281. } else {
  282. if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
  283. /* as we only generate a YUV420P picture, we must convert it
  284. * to the codec pixel format if needed */
  285. if (img_convert_ctx == NULL) {
  286. img_convert_ctx = sws_getContext(c->width, c->height,
  287. AV_PIX_FMT_YUV420P,
  288. c->width, c->height,
  289. c->pix_fmt,
  290. sws_flags, NULL, NULL, NULL);
  291. if (img_convert_ctx == NULL) {
  292. fprintf(stderr,
  293. "Cannot initialize the conversion context\n");
  294. exit(1);
  295. }
  296. }
  297. fill_yuv_image(ost->tmp_frame, frame_count, c->width, c->height);
  298. sws_scale(img_convert_ctx, ost->tmp_frame->data, ost->tmp_frame->linesize,
  299. 0, c->height, ost->frame->data, ost->frame->linesize);
  300. } else {
  301. fill_yuv_image(ost->frame, frame_count, c->width, c->height);
  302. }
  303. }
  304. if (oc->oformat->flags & AVFMT_RAWPICTURE) {
  305. /* Raw video case - the API will change slightly in the near
  306. * future for that. */
  307. AVPacket pkt;
  308. av_init_packet(&pkt);
  309. pkt.flags |= AV_PKT_FLAG_KEY;
  310. pkt.stream_index = ost->st->index;
  311. pkt.data = (uint8_t *)ost->frame;
  312. pkt.size = sizeof(AVPicture);
  313. ret = av_interleaved_write_frame(oc, &pkt);
  314. } else {
  315. AVPacket pkt = { 0 };
  316. int got_packet;
  317. av_init_packet(&pkt);
  318. /* encode the image */
  319. ret = avcodec_encode_video2(c, &pkt, ost->frame, &got_packet);
  320. /* If size is zero, it means the image was buffered. */
  321. if (!ret && got_packet && pkt.size) {
  322. av_packet_rescale_ts(&pkt, c->time_base, ost->st->time_base);
  323. pkt.stream_index = ost->st->index;
  324. /* Write the compressed frame to the media file. */
  325. ret = av_interleaved_write_frame(oc, &pkt);
  326. } else {
  327. ret = 0;
  328. }
  329. }
  330. if (ret != 0) {
  331. fprintf(stderr, "Error while writing video frame\n");
  332. exit(1);
  333. }
  334. frame_count++;
  335. }
  336. static void close_stream(AVFormatContext *oc, OutputStream *ost)
  337. {
  338. avcodec_close(ost->st->codec);
  339. av_frame_free(&ost->frame);
  340. av_frame_free(&ost->tmp_frame);
  341. }
  342. /**************************************************************/
  343. /* media file output */
  344. int main(int argc, char **argv)
  345. {
  346. OutputStream video_st = { 0 }, audio_st = { 0 };
  347. const char *filename;
  348. AVOutputFormat *fmt;
  349. AVFormatContext *oc;
  350. double audio_pts, video_pts;
  351. int have_video = 0, have_audio = 0;
  352. int i;
  353. /* Initialize libavcodec, and register all codecs and formats. */
  354. av_register_all();
  355. if (argc != 2) {
  356. printf("usage: %s output_file\n"
  357. "API example program to output a media file with libavformat.\n"
  358. "The output format is automatically guessed according to the file extension.\n"
  359. "Raw images can also be output by using '%%d' in the filename\n"
  360. "\n", argv[0]);
  361. return 1;
  362. }
  363. filename = argv[1];
  364. /* Autodetect the output format from the name. default is MPEG. */
  365. fmt = av_guess_format(NULL, filename, NULL);
  366. if (!fmt) {
  367. printf("Could not deduce output format from file extension: using MPEG.\n");
  368. fmt = av_guess_format("mpeg", NULL, NULL);
  369. }
  370. if (!fmt) {
  371. fprintf(stderr, "Could not find suitable output format\n");
  372. return 1;
  373. }
  374. /* Allocate the output media context. */
  375. oc = avformat_alloc_context();
  376. if (!oc) {
  377. fprintf(stderr, "Memory error\n");
  378. return 1;
  379. }
  380. oc->oformat = fmt;
  381. snprintf(oc->filename, sizeof(oc->filename), "%s", filename);
  382. /* Add the audio and video streams using the default format codecs
  383. * and initialize the codecs. */
  384. if (fmt->video_codec != AV_CODEC_ID_NONE) {
  385. add_video_stream(&video_st, oc, fmt->video_codec);
  386. have_video = 1;
  387. }
  388. if (fmt->audio_codec != AV_CODEC_ID_NONE) {
  389. add_audio_stream(&audio_st, oc, fmt->audio_codec);
  390. have_audio = 1;
  391. }
  392. /* Now that all the parameters are set, we can open the audio and
  393. * video codecs and allocate the necessary encode buffers. */
  394. if (have_video)
  395. open_video(oc, &video_st);
  396. if (have_audio)
  397. open_audio(oc, &audio_st);
  398. av_dump_format(oc, 0, filename, 1);
  399. /* open the output file, if needed */
  400. if (!(fmt->flags & AVFMT_NOFILE)) {
  401. if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0) {
  402. fprintf(stderr, "Could not open '%s'\n", filename);
  403. return 1;
  404. }
  405. }
  406. /* Write the stream header, if any. */
  407. avformat_write_header(oc, NULL);
  408. for (;;) {
  409. /* Compute current audio and video time. */
  410. if (have_audio)
  411. audio_pts = (double)audio_st.st->pts.val * audio_st.st->time_base.num / audio_st.st->time_base.den;
  412. else
  413. audio_pts = 0.0;
  414. if (have_video)
  415. video_pts = (double)video_st.st->pts.val * video_st.st->time_base.num /
  416. video_st.st->time_base.den;
  417. else
  418. video_pts = 0.0;
  419. if ((!have_audio || audio_pts >= STREAM_DURATION) &&
  420. (!have_video || video_pts >= STREAM_DURATION))
  421. break;
  422. /* write interleaved audio and video frames */
  423. if (!have_video || (have_video && have_audio && audio_pts < video_pts)) {
  424. write_audio_frame(oc, &audio_st);
  425. } else {
  426. write_video_frame(oc, &video_st);
  427. }
  428. }
  429. /* Write the trailer, if any. The trailer must be written before you
  430. * close the CodecContexts open when you wrote the header; otherwise
  431. * av_write_trailer() may try to use memory that was freed on
  432. * av_codec_close(). */
  433. av_write_trailer(oc);
  434. /* Close each codec. */
  435. if (have_video)
  436. close_stream(oc, &video_st);
  437. if (have_audio)
  438. close_stream(oc, &audio_st);
  439. /* Free the streams. */
  440. for (i = 0; i < oc->nb_streams; i++) {
  441. av_freep(&oc->streams[i]->codec);
  442. av_freep(&oc->streams[i]);
  443. }
  444. if (!(fmt->flags & AVFMT_NOFILE))
  445. /* Close the output file. */
  446. avio_close(oc->pb);
  447. /* free the stream */
  448. av_free(oc);
  449. return 0;
  450. }