2 * Copyright (c) 2003 Fabrice Bellard
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:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
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
25 * libavformat API example.
27 * Output a media file in any supported libavformat format.
28 * The default codecs are used.
36 #include "libavutil/mathematics.h"
37 #include "libavformat/avformat.h"
38 #include "libswscale/swscale.h"
42 /* 5 seconds stream duration */
43 #define STREAM_DURATION 5.0
44 #define STREAM_FRAME_RATE 25 /* 25 images/s */
45 #define STREAM_NB_FRAMES ((int)(STREAM_DURATION * STREAM_FRAME_RATE))
46 #define STREAM_PIX_FMT PIX_FMT_YUV420P /* default pix_fmt */
48 static int sws_flags = SWS_BICUBIC;
50 /**************************************************************/
53 float t, tincr, tincr2;
55 uint8_t *audio_outbuf;
56 int audio_outbuf_size;
57 int audio_input_frame_size;
60 * add an audio output stream
62 static AVStream *add_audio_stream(AVFormatContext *oc, enum CodecID codec_id)
67 st = av_new_stream(oc, 1);
69 fprintf(stderr, "Could not alloc stream\n");
74 c->codec_id = codec_id;
75 c->codec_type = AVMEDIA_TYPE_AUDIO;
77 /* put sample parameters */
78 c->sample_fmt = AV_SAMPLE_FMT_S16;
80 c->sample_rate = 44100;
83 // some formats want stream headers to be separate
84 if(oc->oformat->flags & AVFMT_GLOBALHEADER)
85 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
90 static void open_audio(AVFormatContext *oc, AVStream *st)
97 /* find the audio encoder */
98 codec = avcodec_find_encoder(c->codec_id);
100 fprintf(stderr, "codec not found\n");
105 if (avcodec_open(c, codec) < 0) {
106 fprintf(stderr, "could not open codec\n");
110 /* init signal generator */
112 tincr = 2 * M_PI * 110.0 / c->sample_rate;
113 /* increment frequency by 110 Hz per second */
114 tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
116 audio_outbuf_size = 10000;
117 audio_outbuf = av_malloc(audio_outbuf_size);
119 /* ugly hack for PCM codecs (will be removed ASAP with new PCM
120 support to compute the input frame size in samples */
121 if (c->frame_size <= 1) {
122 audio_input_frame_size = audio_outbuf_size / c->channels;
123 switch(st->codec->codec_id) {
124 case CODEC_ID_PCM_S16LE:
125 case CODEC_ID_PCM_S16BE:
126 case CODEC_ID_PCM_U16LE:
127 case CODEC_ID_PCM_U16BE:
128 audio_input_frame_size >>= 1;
134 audio_input_frame_size = c->frame_size;
136 samples = av_malloc(audio_input_frame_size * 2 * c->channels);
139 /* prepare a 16 bit dummy audio frame of 'frame_size' samples and
140 'nb_channels' channels */
141 static void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)
147 for(j=0;j<frame_size;j++) {
148 v = (int)(sin(t) * 10000);
149 for(i = 0; i < nb_channels; i++)
156 static void write_audio_frame(AVFormatContext *oc, AVStream *st)
160 av_init_packet(&pkt);
164 get_audio_frame(samples, audio_input_frame_size, c->channels);
166 pkt.size= avcodec_encode_audio(c, audio_outbuf, audio_outbuf_size, samples);
168 if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
169 pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
170 pkt.flags |= AV_PKT_FLAG_KEY;
171 pkt.stream_index= st->index;
172 pkt.data= audio_outbuf;
174 /* write the compressed frame in the media file */
175 if (av_interleaved_write_frame(oc, &pkt) != 0) {
176 fprintf(stderr, "Error while writing audio frame\n");
181 static void close_audio(AVFormatContext *oc, AVStream *st)
183 avcodec_close(st->codec);
186 av_free(audio_outbuf);
189 /**************************************************************/
192 AVFrame *picture, *tmp_picture;
193 uint8_t *video_outbuf;
194 int frame_count, video_outbuf_size;
196 /* add a video output stream */
197 static AVStream *add_video_stream(AVFormatContext *oc, enum CodecID codec_id)
202 st = av_new_stream(oc, 0);
204 fprintf(stderr, "Could not alloc stream\n");
209 c->codec_id = codec_id;
210 c->codec_type = AVMEDIA_TYPE_VIDEO;
212 /* put sample parameters */
213 c->bit_rate = 400000;
214 /* resolution must be a multiple of two */
217 /* time base: this is the fundamental unit of time (in seconds) in terms
218 of which frame timestamps are represented. for fixed-fps content,
219 timebase should be 1/framerate and timestamp increments should be
221 c->time_base.den = STREAM_FRAME_RATE;
222 c->time_base.num = 1;
223 c->gop_size = 12; /* emit one intra frame every twelve frames at most */
224 c->pix_fmt = STREAM_PIX_FMT;
225 if (c->codec_id == CODEC_ID_MPEG2VIDEO) {
226 /* just for testing, we also add B frames */
229 if (c->codec_id == CODEC_ID_MPEG1VIDEO){
230 /* Needed to avoid using macroblocks in which some coeffs overflow.
231 This does not happen with normal video, it just happens here as
232 the motion of the chroma plane does not match the luma plane. */
235 // some formats want stream headers to be separate
236 if(oc->oformat->flags & AVFMT_GLOBALHEADER)
237 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
242 static AVFrame *alloc_picture(enum PixelFormat pix_fmt, int width, int height)
245 uint8_t *picture_buf;
248 picture = avcodec_alloc_frame();
251 size = avpicture_get_size(pix_fmt, width, height);
252 picture_buf = av_malloc(size);
257 avpicture_fill((AVPicture *)picture, picture_buf,
258 pix_fmt, width, height);
262 static void open_video(AVFormatContext *oc, AVStream *st)
269 /* find the video encoder */
270 codec = avcodec_find_encoder(c->codec_id);
272 fprintf(stderr, "codec not found\n");
277 if (avcodec_open(c, codec) < 0) {
278 fprintf(stderr, "could not open codec\n");
283 if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
284 /* allocate output buffer */
285 /* XXX: API change will be done */
286 /* buffers passed into lav* can be allocated any way you prefer,
287 as long as they're aligned enough for the architecture, and
288 they're freed appropriately (such as using av_free for buffers
289 allocated with av_malloc) */
290 video_outbuf_size = 200000;
291 video_outbuf = av_malloc(video_outbuf_size);
294 /* allocate the encoded raw picture */
295 picture = alloc_picture(c->pix_fmt, c->width, c->height);
297 fprintf(stderr, "Could not allocate picture\n");
301 /* if the output format is not YUV420P, then a temporary YUV420P
302 picture is needed too. It is then converted to the required
305 if (c->pix_fmt != PIX_FMT_YUV420P) {
306 tmp_picture = alloc_picture(PIX_FMT_YUV420P, c->width, c->height);
308 fprintf(stderr, "Could not allocate temporary picture\n");
314 /* prepare a dummy image */
315 static void fill_yuv_image(AVFrame *pict, int frame_index, int width, int height)
322 for(y=0;y<height;y++) {
323 for(x=0;x<width;x++) {
324 pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
329 for(y=0;y<height/2;y++) {
330 for(x=0;x<width/2;x++) {
331 pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
332 pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
337 static void write_video_frame(AVFormatContext *oc, AVStream *st)
341 static struct SwsContext *img_convert_ctx;
345 if (frame_count >= STREAM_NB_FRAMES) {
346 /* no more frame to compress. The codec has a latency of a few
347 frames if using B frames, so we get the last frames by
348 passing the same picture again */
350 if (c->pix_fmt != PIX_FMT_YUV420P) {
351 /* as we only generate a YUV420P picture, we must convert it
352 to the codec pixel format if needed */
353 if (img_convert_ctx == NULL) {
354 img_convert_ctx = sws_getContext(c->width, c->height,
358 sws_flags, NULL, NULL, NULL);
359 if (img_convert_ctx == NULL) {
360 fprintf(stderr, "Cannot initialize the conversion context\n");
364 fill_yuv_image(tmp_picture, frame_count, c->width, c->height);
365 sws_scale(img_convert_ctx, tmp_picture->data, tmp_picture->linesize,
366 0, c->height, picture->data, picture->linesize);
368 fill_yuv_image(picture, frame_count, c->width, c->height);
373 if (oc->oformat->flags & AVFMT_RAWPICTURE) {
374 /* raw video case. The API will change slightly in the near
377 av_init_packet(&pkt);
379 pkt.flags |= AV_PKT_FLAG_KEY;
380 pkt.stream_index= st->index;
381 pkt.data= (uint8_t *)picture;
382 pkt.size= sizeof(AVPicture);
384 ret = av_interleaved_write_frame(oc, &pkt);
386 /* encode the image */
387 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, picture);
388 /* if zero size, it means the image was buffered */
391 av_init_packet(&pkt);
393 if (c->coded_frame->pts != AV_NOPTS_VALUE)
394 pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
395 if(c->coded_frame->key_frame)
396 pkt.flags |= AV_PKT_FLAG_KEY;
397 pkt.stream_index= st->index;
398 pkt.data= video_outbuf;
401 /* write the compressed frame in the media file */
402 ret = av_interleaved_write_frame(oc, &pkt);
408 fprintf(stderr, "Error while writing video frame\n");
414 static void close_video(AVFormatContext *oc, AVStream *st)
416 avcodec_close(st->codec);
417 av_free(picture->data[0]);
420 av_free(tmp_picture->data[0]);
421 av_free(tmp_picture);
423 av_free(video_outbuf);
426 /**************************************************************/
427 /* media file output */
429 int main(int argc, char **argv)
431 const char *filename;
434 AVStream *audio_st, *video_st;
435 double audio_pts, video_pts;
438 /* initialize libavcodec, and register all codecs and formats */
442 printf("usage: %s output_file\n"
443 "API example program to output a media file with libavformat.\n"
444 "The output format is automatically guessed according to the file extension.\n"
445 "Raw images can also be output by using '%%d' in the filename\n"
452 /* allocate the output media context */
453 avformat_alloc_output_context2(&oc, NULL, NULL, filename);
455 printf("Could not deduce output format from file extension: using MPEG.\n");
456 avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
463 /* add the audio and video streams using the default format codecs
464 and initialize the codecs */
467 if (fmt->video_codec != CODEC_ID_NONE) {
468 video_st = add_video_stream(oc, fmt->video_codec);
470 if (fmt->audio_codec != CODEC_ID_NONE) {
471 audio_st = add_audio_stream(oc, fmt->audio_codec);
474 av_dump_format(oc, 0, filename, 1);
476 /* now that all the parameters are set, we can open the audio and
477 video codecs and allocate the necessary encode buffers */
479 open_video(oc, video_st);
481 open_audio(oc, audio_st);
483 /* open the output file, if needed */
484 if (!(fmt->flags & AVFMT_NOFILE)) {
485 if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0) {
486 fprintf(stderr, "Could not open '%s'\n", filename);
491 /* write the stream header, if any */
495 /* compute current audio and video time */
497 audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
502 video_pts = (double)video_st->pts.val * video_st->time_base.num / video_st->time_base.den;
506 if ((!audio_st || audio_pts >= STREAM_DURATION) &&
507 (!video_st || video_pts >= STREAM_DURATION))
510 /* write interleaved audio and video frames */
511 if (!video_st || (video_st && audio_st && audio_pts < video_pts)) {
512 write_audio_frame(oc, audio_st);
514 write_video_frame(oc, video_st);
518 /* write the trailer, if any. the trailer must be written
519 * before you close the CodecContexts open when you wrote the
520 * header; otherwise write_trailer may try to use memory that
521 * was freed on av_codec_close() */
522 av_write_trailer(oc);
524 /* close each codec */
526 close_video(oc, video_st);
528 close_audio(oc, audio_st);
530 /* free the streams */
531 for(i = 0; i < oc->nb_streams; i++) {
532 av_freep(&oc->streams[i]->codec);
533 av_freep(&oc->streams[i]);
536 if (!(fmt->flags & AVFMT_NOFILE)) {
537 /* close the output file */
541 /* free the stream */