2 * Copyright (c) 2001 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 * libavcodec API use example.
27 * Note that libavcodec only handles codecs (mpeg, mpeg4, etc...),
28 * not file formats (avi, vob, mp4, mov, mkv, mxf, flv, mpegts, mpegps, etc...). See library 'libavformat' for the
34 #include <libavutil/opt.h>
35 #include <libavcodec/avcodec.h>
36 #include <libavutil/audioconvert.h>
37 #include <libavutil/common.h>
38 #include <libavutil/imgutils.h>
39 #include <libavutil/mathematics.h>
40 #include <libavutil/samplefmt.h>
42 #define INBUF_SIZE 4096
43 #define AUDIO_INBUF_SIZE 20480
44 #define AUDIO_REFILL_THRESH 4096
46 /* check that a given sample format is supported by the encoder */
47 static int check_sample_fmt(AVCodec *codec, enum AVSampleFormat sample_fmt)
49 const enum AVSampleFormat *p = codec->sample_fmts;
51 while (*p != AV_SAMPLE_FMT_NONE) {
59 /* just pick the highest supported samplerate */
60 static int select_sample_rate(AVCodec *codec)
63 int best_samplerate = 0;
65 if (!codec->supported_samplerates)
68 p = codec->supported_samplerates;
70 best_samplerate = FFMAX(*p, best_samplerate);
73 return best_samplerate;
76 /* select layout with the highest channel count */
77 static int select_channel_layout(AVCodec *codec)
80 uint64_t best_ch_layout = 0;
81 int best_nb_channells = 0;
83 if (!codec->channel_layouts)
84 return AV_CH_LAYOUT_STEREO;
86 p = codec->channel_layouts;
88 int nb_channels = av_get_channel_layout_nb_channels(*p);
90 if (nb_channels > best_nb_channells) {
92 best_nb_channells = nb_channels;
96 return best_ch_layout;
100 * Audio encoding example
102 static void audio_encode_example(const char *filename)
105 AVCodecContext *c= NULL;
108 int i, j, k, ret, got_output;
114 printf("Encode audio file %s\n", filename);
116 /* find the MP2 encoder */
117 codec = avcodec_find_encoder(AV_CODEC_ID_MP2);
119 fprintf(stderr, "Codec not found\n");
123 c = avcodec_alloc_context3(codec);
125 fprintf(stderr, "Could not allocate audio codec context\n");
129 /* put sample parameters */
132 /* check that the encoder supports s16 pcm input */
133 c->sample_fmt = AV_SAMPLE_FMT_S16;
134 if (!check_sample_fmt(codec, c->sample_fmt)) {
135 fprintf(stderr, "Encoder does not support sample format %s",
136 av_get_sample_fmt_name(c->sample_fmt));
140 /* select other audio parameters supported by the encoder */
141 c->sample_rate = select_sample_rate(codec);
142 c->channel_layout = select_channel_layout(codec);
143 c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
146 if (avcodec_open2(c, codec, NULL) < 0) {
147 fprintf(stderr, "Could not open codec\n");
151 f = fopen(filename, "wb");
153 fprintf(stderr, "Could not open %s\n", filename);
157 /* frame containing input raw audio */
158 frame = avcodec_alloc_frame();
160 fprintf(stderr, "Could not allocate audio frame\n");
164 frame->nb_samples = c->frame_size;
165 frame->format = c->sample_fmt;
166 frame->channel_layout = c->channel_layout;
168 /* the codec gives us the frame size, in samples,
169 * we calculate the size of the samples buffer in bytes */
170 buffer_size = av_samples_get_buffer_size(NULL, c->channels, c->frame_size,
172 samples = av_malloc(buffer_size);
174 fprintf(stderr, "Could not allocate %d bytes for samples buffer\n",
178 /* setup the data pointers in the AVFrame */
179 ret = avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt,
180 (const uint8_t*)samples, buffer_size, 0);
182 fprintf(stderr, "Could not setup audio frame\n");
186 /* encode a single tone sound */
188 tincr = 2 * M_PI * 440.0 / c->sample_rate;
190 av_init_packet(&pkt);
191 pkt.data = NULL; // packet data will be allocated by the encoder
194 for (j = 0; j < c->frame_size; j++) {
195 samples[2*j] = (int)(sin(t) * 10000);
197 for (k = 1; k < c->channels; k++)
198 samples[2*j + k] = samples[2*j];
201 /* encode the samples */
202 ret = avcodec_encode_audio2(c, &pkt, frame, &got_output);
204 fprintf(stderr, "Error encoding audio frame\n");
208 fwrite(pkt.data, 1, pkt.size, f);
209 av_free_packet(&pkt);
213 /* get the delayed frames */
214 for (got_output = 1; got_output; i++) {
215 ret = avcodec_encode_audio2(c, &pkt, NULL, &got_output);
217 fprintf(stderr, "Error encoding frame\n");
222 fwrite(pkt.data, 1, pkt.size, f);
223 av_free_packet(&pkt);
229 avcodec_free_frame(&frame);
237 static void audio_decode_example(const char *outfilename, const char *filename)
240 AVCodecContext *c= NULL;
243 uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
245 AVFrame *decoded_frame = NULL;
247 av_init_packet(&avpkt);
249 printf("Decode audio file %s to %s\n", filename, outfilename);
251 /* find the mpeg audio decoder */
252 codec = avcodec_find_decoder(AV_CODEC_ID_MP2);
254 fprintf(stderr, "Codec not found\n");
258 c = avcodec_alloc_context3(codec);
260 fprintf(stderr, "Could not allocate audio codec context\n");
265 if (avcodec_open2(c, codec, NULL) < 0) {
266 fprintf(stderr, "Could not open codec\n");
270 f = fopen(filename, "rb");
272 fprintf(stderr, "Could not open %s\n", filename);
275 outfile = fopen(outfilename, "wb");
281 /* decode until eof */
283 avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
285 while (avpkt.size > 0) {
288 if (!decoded_frame) {
289 if (!(decoded_frame = avcodec_alloc_frame())) {
290 fprintf(stderr, "Could not allocate audio frame\n");
294 avcodec_get_frame_defaults(decoded_frame);
296 len = avcodec_decode_audio4(c, decoded_frame, &got_frame, &avpkt);
298 fprintf(stderr, "Error while decoding\n");
302 /* if a frame has been decoded, output it */
303 int data_size = av_samples_get_buffer_size(NULL, c->channels,
304 decoded_frame->nb_samples,
306 fwrite(decoded_frame->data[0], 1, data_size, outfile);
311 avpkt.pts = AV_NOPTS_VALUE;
312 if (avpkt.size < AUDIO_REFILL_THRESH) {
313 /* Refill the input buffer, to avoid trying to decode
314 * incomplete frames. Instead of this, one could also use
315 * a parser, or use a proper container format through
317 memmove(inbuf, avpkt.data, avpkt.size);
319 len = fread(avpkt.data + avpkt.size, 1,
320 AUDIO_INBUF_SIZE - avpkt.size, f);
331 avcodec_free_frame(&decoded_frame);
335 * Video encoding example
337 static void video_encode_example(const char *filename, int codec_id)
340 AVCodecContext *c= NULL;
341 int i, ret, x, y, got_output;
345 uint8_t endcode[] = { 0, 0, 1, 0xb7 };
347 printf("Encode video file %s\n", filename);
349 /* find the mpeg1 video encoder */
350 codec = avcodec_find_encoder(codec_id);
352 fprintf(stderr, "Codec not found\n");
356 c = avcodec_alloc_context3(codec);
358 fprintf(stderr, "Could not allocate video codec context\n");
362 /* put sample parameters */
363 c->bit_rate = 400000;
364 /* resolution must be a multiple of two */
367 /* frames per second */
368 c->time_base= (AVRational){1,25};
369 c->gop_size = 10; /* emit one intra frame every ten frames */
371 c->pix_fmt = AV_PIX_FMT_YUV420P;
373 if(codec_id == AV_CODEC_ID_H264)
374 av_opt_set(c->priv_data, "preset", "slow", 0);
377 if (avcodec_open2(c, codec, NULL) < 0) {
378 fprintf(stderr, "Could not open codec\n");
382 f = fopen(filename, "wb");
384 fprintf(stderr, "Could not open %s\n", filename);
388 frame = avcodec_alloc_frame();
390 fprintf(stderr, "Could not allocate video frame\n");
393 frame->format = c->pix_fmt;
394 frame->width = c->width;
395 frame->height = c->height;
397 /* the image can be allocated by any means and av_image_alloc() is
398 * just the most convenient way if av_malloc() is to be used */
399 ret = av_image_alloc(frame->data, frame->linesize, c->width, c->height,
402 fprintf(stderr, "Could not allocate raw picture buffer\n");
406 /* encode 1 second of video */
408 av_init_packet(&pkt);
409 pkt.data = NULL; // packet data will be allocated by the encoder
413 /* prepare a dummy image */
415 for(y=0;y<c->height;y++) {
416 for(x=0;x<c->width;x++) {
417 frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
422 for(y=0;y<c->height/2;y++) {
423 for(x=0;x<c->width/2;x++) {
424 frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
425 frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
431 /* encode the image */
432 ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
434 fprintf(stderr, "Error encoding frame\n");
439 printf("Write frame %3d (size=%5d)\n", i, pkt.size);
440 fwrite(pkt.data, 1, pkt.size, f);
441 av_free_packet(&pkt);
445 /* get the delayed frames */
446 for (got_output = 1; got_output; i++) {
449 ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);
451 fprintf(stderr, "Error encoding frame\n");
456 printf("Write frame %3d (size=%5d)\n", i, pkt.size);
457 fwrite(pkt.data, 1, pkt.size, f);
458 av_free_packet(&pkt);
462 /* add sequence end code to have a real mpeg file */
463 fwrite(endcode, 1, sizeof(endcode), f);
468 av_freep(&frame->data[0]);
469 avcodec_free_frame(&frame);
474 * Video decoding example
477 static void pgm_save(unsigned char *buf, int wrap, int xsize, int ysize,
483 f=fopen(filename,"w");
484 fprintf(f,"P5\n%d %d\n%d\n",xsize,ysize,255);
486 fwrite(buf + i * wrap,1,xsize,f);
490 static void video_decode_example(const char *outfilename, const char *filename)
493 AVCodecContext *c= NULL;
494 int frame, got_picture, len;
497 uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
501 av_init_packet(&avpkt);
503 /* set end of buffer to 0 (this ensures that no overreading happens for damaged mpeg streams) */
504 memset(inbuf + INBUF_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
506 printf("Decode video file %s to %s\n", filename, outfilename);
508 /* find the mpeg1 video decoder */
509 codec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO);
511 fprintf(stderr, "Codec not found\n");
515 c = avcodec_alloc_context3(codec);
517 fprintf(stderr, "Could not allocate video codec context\n");
521 if(codec->capabilities&CODEC_CAP_TRUNCATED)
522 c->flags|= CODEC_FLAG_TRUNCATED; /* we do not send complete frames */
524 /* For some codecs, such as msmpeg4 and mpeg4, width and height
525 MUST be initialized there because this information is not
526 available in the bitstream. */
529 if (avcodec_open2(c, codec, NULL) < 0) {
530 fprintf(stderr, "Could not open codec\n");
534 /* the codec gives us the frame size, in samples */
536 f = fopen(filename, "rb");
538 fprintf(stderr, "Could not open %s\n", filename);
542 picture = avcodec_alloc_frame();
544 fprintf(stderr, "Could not allocate video frame\n");
550 avpkt.size = fread(inbuf, 1, INBUF_SIZE, f);
554 /* NOTE1: some codecs are stream based (mpegvideo, mpegaudio)
555 and this is the only method to use them because you cannot
556 know the compressed data size before analysing it.
558 BUT some other codecs (msmpeg4, mpeg4) are inherently frame
559 based, so you must call them with all the data for one
560 frame exactly. You must also initialize 'width' and
561 'height' before initializing them. */
563 /* NOTE2: some codecs allow the raw parameters (frame size,
564 sample rate) to be changed at any frame. We handle this, so
565 you should also take care of it */
567 /* here, we use a stream based decoder (mpeg1video), so we
568 feed decoder and see if it could decode a frame */
570 while (avpkt.size > 0) {
571 len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
573 fprintf(stderr, "Error while decoding frame %d\n", frame);
577 printf("Saving frame %3d\n", frame);
580 /* the picture is allocated by the decoder. no need to
582 snprintf(buf, sizeof(buf), outfilename, frame);
583 pgm_save(picture->data[0], picture->linesize[0],
584 c->width, c->height, buf);
592 /* some codecs, such as MPEG, transmit the I and P frame with a
593 latency of one frame. You must do the following to have a
594 chance to get the last frame of the video */
597 len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
599 printf("Saving last frame %3d\n", frame);
602 /* the picture is allocated by the decoder. no need to
604 snprintf(buf, sizeof(buf), outfilename, frame);
605 pgm_save(picture->data[0], picture->linesize[0],
606 c->width, c->height, buf);
614 avcodec_free_frame(&picture);
618 int main(int argc, char **argv)
620 const char *output_type;
622 /* register all the codecs */
623 avcodec_register_all();
626 printf("usage: %s output_type\n"
627 "API example program to decode/encode a media stream with libavcodec.\n"
628 "This program generates a synthetic stream and encodes it to a file\n"
629 "named test.h264, test.mp2 or test.mpg depending on output_type.\n"
630 "The encoded stream is then decoded and written to a raw data output\n."
631 "output_type must be choosen between 'h264', 'mp2', 'mpg'\n",
635 output_type = argv[1];
637 if (!strcmp(output_type, "h264")) {
638 video_encode_example("test.h264", AV_CODEC_ID_H264);
639 } else if (!strcmp(output_type, "mp2")) {
640 audio_encode_example("test.mp2");
641 audio_decode_example("test.sw", "test.mp2");
642 } else if (!strcmp(output_type, "mpg")) {
643 video_encode_example("test.mpg", AV_CODEC_ID_MPEG1VIDEO);
644 video_decode_example("test%02d.pgm", "test.mpg");
646 fprintf(stderr, "Invalid output type '%s', choose between 'h264', 'mp2', or 'mpg'\n",