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.

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