2 * Libavformat API example: Output a media file in any supported
3 * libavformat format. The default codecs are used.
5 * Copyright (c) 2003 Fabrice Bellard
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
31 #define M_PI 3.1415926535897931
36 /* 5 seconds stream duration */
37 #define STREAM_DURATION 5.0
38 #define STREAM_FRAME_RATE 25 /* 25 images/s */
39 #define STREAM_NB_FRAMES ((int)(STREAM_DURATION * STREAM_FRAME_RATE))
40 #define STREAM_PIX_FMT PIX_FMT_YUV420P /* default pix_fmt */
42 /**************************************************************/
45 float t
, tincr
, tincr2
;
47 uint8_t *audio_outbuf
;
48 int audio_outbuf_size
;
49 int audio_input_frame_size
;
52 * add an audio output stream
54 static AVStream
*add_audio_stream(AVFormatContext
*oc
, int codec_id
)
59 st
= av_new_stream(oc
, 1);
61 fprintf(stderr
, "Could not alloc stream\n");
66 c
->codec_id
= codec_id
;
67 c
->codec_type
= CODEC_TYPE_AUDIO
;
69 /* put sample parameters */
71 c
->sample_rate
= 44100;
76 static void open_audio(AVFormatContext
*oc
, AVStream
*st
)
83 /* find the audio encoder */
84 codec
= avcodec_find_encoder(c
->codec_id
);
86 fprintf(stderr
, "codec not found\n");
91 if (avcodec_open(c
, codec
) < 0) {
92 fprintf(stderr
, "could not open codec\n");
96 /* init signal generator */
98 tincr
= 2 * M_PI
* 110.0 / c
->sample_rate
;
99 /* increment frequency by 110 Hz per second */
100 tincr2
= 2 * M_PI
* 110.0 / c
->sample_rate
/ c
->sample_rate
;
102 audio_outbuf_size
= 10000;
103 audio_outbuf
= malloc(audio_outbuf_size
);
105 /* ugly hack for PCM codecs (will be removed ASAP with new PCM
106 support to compute the input frame size in samples */
107 if (c
->frame_size
<= 1) {
108 audio_input_frame_size
= audio_outbuf_size
/ c
->channels
;
109 switch(st
->codec
->codec_id
) {
110 case CODEC_ID_PCM_S16LE
:
111 case CODEC_ID_PCM_S16BE
:
112 case CODEC_ID_PCM_U16LE
:
113 case CODEC_ID_PCM_U16BE
:
114 audio_input_frame_size
>>= 1;
120 audio_input_frame_size
= c
->frame_size
;
122 samples
= malloc(audio_input_frame_size
* 2 * c
->channels
);
125 /* prepare a 16 bit dummy audio frame of 'frame_size' samples and
126 'nb_channels' channels */
127 static void get_audio_frame(int16_t *samples
, int frame_size
, int nb_channels
)
133 for(j
=0;j
<frame_size
;j
++) {
134 v
= (int)(sin(t
) * 10000);
135 for(i
= 0; i
< nb_channels
; i
++)
142 static void write_audio_frame(AVFormatContext
*oc
, AVStream
*st
)
146 av_init_packet(&pkt
);
150 get_audio_frame(samples
, audio_input_frame_size
, c
->channels
);
152 pkt
.size
= avcodec_encode_audio(c
, audio_outbuf
, audio_outbuf_size
, samples
);
154 pkt
.pts
= av_rescale_q(c
->coded_frame
->pts
, c
->time_base
, st
->time_base
);
155 pkt
.flags
|= PKT_FLAG_KEY
;
156 pkt
.stream_index
= st
->index
;
157 pkt
.data
= audio_outbuf
;
159 /* write the compressed frame in the media file */
160 if (av_write_frame(oc
, &pkt
) != 0) {
161 fprintf(stderr
, "Error while writing audio frame\n");
166 static void close_audio(AVFormatContext
*oc
, AVStream
*st
)
168 avcodec_close(st
->codec
);
171 av_free(audio_outbuf
);
174 /**************************************************************/
177 AVFrame
*picture
, *tmp_picture
;
178 uint8_t *video_outbuf
;
179 int frame_count
, video_outbuf_size
;
181 /* add a video output stream */
182 static AVStream
*add_video_stream(AVFormatContext
*oc
, int codec_id
)
187 st
= av_new_stream(oc
, 0);
189 fprintf(stderr
, "Could not alloc stream\n");
194 c
->codec_id
= codec_id
;
195 c
->codec_type
= CODEC_TYPE_VIDEO
;
197 /* put sample parameters */
198 c
->bit_rate
= 400000;
199 /* resolution must be a multiple of two */
202 /* time base: this is the fundamental unit of time (in seconds) in terms
203 of which frame timestamps are represented. for fixed-fps content,
204 timebase should be 1/framerate and timestamp increments should be
206 c
->time_base
.den
= STREAM_FRAME_RATE
;
207 c
->time_base
.num
= 1;
208 c
->gop_size
= 12; /* emit one intra frame every twelve frames at most */
209 c
->pix_fmt
= STREAM_PIX_FMT
;
210 if (c
->codec_id
== CODEC_ID_MPEG2VIDEO
) {
211 /* just for testing, we also add B frames */
214 if (c
->codec_id
== CODEC_ID_MPEG1VIDEO
){
215 /* needed to avoid using macroblocks in which some coeffs overflow
216 this doesnt happen with normal video, it just happens here as the
217 motion of the chroma plane doesnt match the luma plane */
220 // some formats want stream headers to be seperate
221 if(!strcmp(oc
->oformat
->name
, "mp4") || !strcmp(oc
->oformat
->name
, "mov") || !strcmp(oc
->oformat
->name
, "3gp"))
222 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
227 static AVFrame
*alloc_picture(int pix_fmt
, int width
, int height
)
230 uint8_t *picture_buf
;
233 picture
= avcodec_alloc_frame();
236 size
= avpicture_get_size(pix_fmt
, width
, height
);
237 picture_buf
= malloc(size
);
242 avpicture_fill((AVPicture
*)picture
, picture_buf
,
243 pix_fmt
, width
, height
);
247 static void open_video(AVFormatContext
*oc
, AVStream
*st
)
254 /* find the video encoder */
255 codec
= avcodec_find_encoder(c
->codec_id
);
257 fprintf(stderr
, "codec not found\n");
262 if (avcodec_open(c
, codec
) < 0) {
263 fprintf(stderr
, "could not open codec\n");
268 if (!(oc
->oformat
->flags
& AVFMT_RAWPICTURE
)) {
269 /* allocate output buffer */
270 /* XXX: API change will be done */
271 video_outbuf_size
= 200000;
272 video_outbuf
= malloc(video_outbuf_size
);
275 /* allocate the encoded raw picture */
276 picture
= alloc_picture(c
->pix_fmt
, c
->width
, c
->height
);
278 fprintf(stderr
, "Could not allocate picture\n");
282 /* if the output format is not YUV420P, then a temporary YUV420P
283 picture is needed too. It is then converted to the required
286 if (c
->pix_fmt
!= PIX_FMT_YUV420P
) {
287 tmp_picture
= alloc_picture(PIX_FMT_YUV420P
, c
->width
, c
->height
);
289 fprintf(stderr
, "Could not allocate temporary picture\n");
295 /* prepare a dummy image */
296 static void fill_yuv_image(AVFrame
*pict
, int frame_index
, int width
, int height
)
303 for(y
=0;y
<height
;y
++) {
304 for(x
=0;x
<width
;x
++) {
305 pict
->data
[0][y
* pict
->linesize
[0] + x
] = x
+ y
+ i
* 3;
310 for(y
=0;y
<height
/2;y
++) {
311 for(x
=0;x
<width
/2;x
++) {
312 pict
->data
[1][y
* pict
->linesize
[1] + x
] = 128 + y
+ i
* 2;
313 pict
->data
[2][y
* pict
->linesize
[2] + x
] = 64 + x
+ i
* 5;
318 static void write_video_frame(AVFormatContext
*oc
, AVStream
*st
)
325 if (frame_count
>= STREAM_NB_FRAMES
) {
326 /* no more frame to compress. The codec has a latency of a few
327 frames if using B frames, so we get the last frames by
328 passing the same picture again */
330 if (c
->pix_fmt
!= PIX_FMT_YUV420P
) {
331 /* as we only generate a YUV420P picture, we must convert it
332 to the codec pixel format if needed */
333 fill_yuv_image(tmp_picture
, frame_count
, c
->width
, c
->height
);
334 img_convert((AVPicture
*)picture
, c
->pix_fmt
,
335 (AVPicture
*)tmp_picture
, PIX_FMT_YUV420P
,
336 c
->width
, c
->height
);
338 fill_yuv_image(picture
, frame_count
, c
->width
, c
->height
);
343 if (oc
->oformat
->flags
& AVFMT_RAWPICTURE
) {
344 /* raw video case. The API will change slightly in the near
347 av_init_packet(&pkt
);
349 pkt
.flags
|= PKT_FLAG_KEY
;
350 pkt
.stream_index
= st
->index
;
351 pkt
.data
= (uint8_t *)picture
;
352 pkt
.size
= sizeof(AVPicture
);
354 ret
= av_write_frame(oc
, &pkt
);
356 /* encode the image */
357 out_size
= avcodec_encode_video(c
, video_outbuf
, video_outbuf_size
, picture
);
358 /* if zero size, it means the image was buffered */
361 av_init_packet(&pkt
);
363 pkt
.pts
= av_rescale_q(c
->coded_frame
->pts
, c
->time_base
, st
->time_base
);
364 if(c
->coded_frame
->key_frame
)
365 pkt
.flags
|= PKT_FLAG_KEY
;
366 pkt
.stream_index
= st
->index
;
367 pkt
.data
= video_outbuf
;
370 /* write the compressed frame in the media file */
371 ret
= av_write_frame(oc
, &pkt
);
377 fprintf(stderr
, "Error while writing video frame\n");
383 static void close_video(AVFormatContext
*oc
, AVStream
*st
)
385 avcodec_close(st
->codec
);
386 av_free(picture
->data
[0]);
389 av_free(tmp_picture
->data
[0]);
390 av_free(tmp_picture
);
392 av_free(video_outbuf
);
395 /**************************************************************/
396 /* media file output */
398 int main(int argc
, char **argv
)
400 const char *filename
;
403 AVStream
*audio_st
, *video_st
;
404 double audio_pts
, video_pts
;
407 /* initialize libavcodec, and register all codecs and formats */
411 printf("usage: %s output_file\n"
412 "API example program to output a media file with libavformat.\n"
413 "The output format is automatically guessed according to the file extension.\n"
414 "Raw images can also be output by using '%%d' in the filename\n"
421 /* auto detect the output format from the name. default is
423 fmt
= guess_format(NULL
, filename
, NULL
);
425 printf("Could not deduce output format from file extension: using MPEG.\n");
426 fmt
= guess_format("mpeg", NULL
, NULL
);
429 fprintf(stderr
, "Could not find suitable output format\n");
433 /* allocate the output media context */
434 oc
= av_alloc_format_context();
436 fprintf(stderr
, "Memory error\n");
440 snprintf(oc
->filename
, sizeof(oc
->filename
), "%s", filename
);
442 /* add the audio and video streams using the default format codecs
443 and initialize the codecs */
446 if (fmt
->video_codec
!= CODEC_ID_NONE
) {
447 video_st
= add_video_stream(oc
, fmt
->video_codec
);
449 if (fmt
->audio_codec
!= CODEC_ID_NONE
) {
450 audio_st
= add_audio_stream(oc
, fmt
->audio_codec
);
453 /* set the output parameters (must be done even if no
455 if (av_set_parameters(oc
, NULL
) < 0) {
456 fprintf(stderr
, "Invalid output format parameters\n");
460 dump_format(oc
, 0, filename
, 1);
462 /* now that all the parameters are set, we can open the audio and
463 video codecs and allocate the necessary encode buffers */
465 open_video(oc
, video_st
);
467 open_audio(oc
, audio_st
);
469 /* open the output file, if needed */
470 if (!(fmt
->flags
& AVFMT_NOFILE
)) {
471 if (url_fopen(&oc
->pb
, filename
, URL_WRONLY
) < 0) {
472 fprintf(stderr
, "Could not open '%s'\n", filename
);
477 /* write the stream header, if any */
481 /* compute current audio and video time */
483 audio_pts
= (double)audio_st
->pts
.val
* audio_st
->time_base
.num
/ audio_st
->time_base
.den
;
488 video_pts
= (double)video_st
->pts
.val
* video_st
->time_base
.num
/ video_st
->time_base
.den
;
492 if ((!audio_st
|| audio_pts
>= STREAM_DURATION
) &&
493 (!video_st
|| video_pts
>= STREAM_DURATION
))
496 /* write interleaved audio and video frames */
497 if (!video_st
|| (video_st
&& audio_st
&& audio_pts
< video_pts
)) {
498 write_audio_frame(oc
, audio_st
);
500 write_video_frame(oc
, video_st
);
504 /* close each codec */
506 close_video(oc
, video_st
);
508 close_audio(oc
, audio_st
);
510 /* write the trailer, if any */
511 av_write_trailer(oc
);
513 /* free the streams */
514 for(i
= 0; i
< oc
->nb_streams
; i
++) {
515 av_freep(&oc
->streams
[i
]->codec
);
516 av_freep(&oc
->streams
[i
]);
519 if (!(fmt
->flags
& AVFMT_NOFILE
)) {
520 /* close the output file */
524 /* free the stream */