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 /* put sample parameters */
128 /* check that the encoder supports s16 pcm input */
129 c->sample_fmt = AV_SAMPLE_FMT_S16;
130 if (!check_sample_fmt(codec, c->sample_fmt)) {
131 fprintf(stderr, "Encoder does not support sample format %s",
132 av_get_sample_fmt_name(c->sample_fmt));
136 /* select other audio parameters supported by the encoder */
137 c->sample_rate = select_sample_rate(codec);
138 c->channel_layout = select_channel_layout(codec);
139 c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
142 if (avcodec_open2(c, codec, NULL) < 0) {
143 fprintf(stderr, "Could not open codec\n");
147 f = fopen(filename, "wb");
149 fprintf(stderr, "Could not open %s\n", filename);
153 /* frame containing input raw audio */
154 frame = avcodec_alloc_frame();
156 fprintf(stderr, "Could not allocate audio frame\n");
160 frame->nb_samples = c->frame_size;
161 frame->format = c->sample_fmt;
162 frame->channel_layout = c->channel_layout;
164 /* the codec gives us the frame size, in samples,
165 * we calculate the size of the samples buffer in bytes */
166 buffer_size = av_samples_get_buffer_size(NULL, c->channels, c->frame_size,
168 samples = av_malloc(buffer_size);
170 fprintf(stderr, "Could not allocate %d bytes for samples buffer\n",
174 /* setup the data pointers in the AVFrame */
175 ret = avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt,
176 (const uint8_t*)samples, buffer_size, 0);
178 fprintf(stderr, "Could not setup audio frame\n");
182 /* encode a single tone sound */
184 tincr = 2 * M_PI * 440.0 / c->sample_rate;
186 av_init_packet(&pkt);
187 pkt.data = NULL; // packet data will be allocated by the encoder
190 for (j = 0; j < c->frame_size; j++) {
191 samples[2*j] = (int)(sin(t) * 10000);
193 for (k = 1; k < c->channels; k++)
194 samples[2*j + k] = samples[2*j];
197 /* encode the samples */
198 ret = avcodec_encode_audio2(c, &pkt, frame, &got_output);
200 fprintf(stderr, "Error encoding audio frame\n");
204 fwrite(pkt.data, 1, pkt.size, f);
205 av_free_packet(&pkt);
209 /* get the delayed frames */
210 for (got_output = 1; got_output; i++) {
211 ret = avcodec_encode_audio2(c, &pkt, NULL, &got_output);
213 fprintf(stderr, "Error encoding frame\n");
218 fwrite(pkt.data, 1, pkt.size, f);
219 av_free_packet(&pkt);
225 avcodec_free_frame(&frame);
233 static void audio_decode_example(const char *outfilename, const char *filename)
236 AVCodecContext *c= NULL;
239 uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
241 AVFrame *decoded_frame = NULL;
243 av_init_packet(&avpkt);
245 printf("Decode audio file %s to %s\n", filename, outfilename);
247 /* find the mpeg audio decoder */
248 codec = avcodec_find_decoder(AV_CODEC_ID_MP2);
250 fprintf(stderr, "Codec not found\n");
254 c = avcodec_alloc_context3(codec);
257 if (avcodec_open2(c, codec, NULL) < 0) {
258 fprintf(stderr, "Could not open codec\n");
262 f = fopen(filename, "rb");
264 fprintf(stderr, "Could not open %s\n", filename);
267 outfile = fopen(outfilename, "wb");
273 /* decode until eof */
275 avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
277 while (avpkt.size > 0) {
280 if (!decoded_frame) {
281 if (!(decoded_frame = avcodec_alloc_frame())) {
282 fprintf(stderr, "Could not allocate audio frame\n");
286 avcodec_get_frame_defaults(decoded_frame);
288 len = avcodec_decode_audio4(c, decoded_frame, &got_frame, &avpkt);
290 fprintf(stderr, "Error while decoding\n");
294 /* if a frame has been decoded, output it */
295 int data_size = av_samples_get_buffer_size(NULL, c->channels,
296 decoded_frame->nb_samples,
298 fwrite(decoded_frame->data[0], 1, data_size, outfile);
303 avpkt.pts = AV_NOPTS_VALUE;
304 if (avpkt.size < AUDIO_REFILL_THRESH) {
305 /* Refill the input buffer, to avoid trying to decode
306 * incomplete frames. Instead of this, one could also use
307 * a parser, or use a proper container format through
309 memmove(inbuf, avpkt.data, avpkt.size);
311 len = fread(avpkt.data + avpkt.size, 1,
312 AUDIO_INBUF_SIZE - avpkt.size, f);
323 avcodec_free_frame(&decoded_frame);
327 * Video encoding example
329 static void video_encode_example(const char *filename, int codec_id)
332 AVCodecContext *c= NULL;
333 int i, ret, x, y, got_output;
337 uint8_t endcode[] = { 0, 0, 1, 0xb7 };
339 printf("Encode video file %s\n", filename);
341 /* find the mpeg1 video encoder */
342 codec = avcodec_find_encoder(codec_id);
344 fprintf(stderr, "Codec not found\n");
348 c = avcodec_alloc_context3(codec);
350 /* put sample parameters */
351 c->bit_rate = 400000;
352 /* resolution must be a multiple of two */
355 /* frames per second */
356 c->time_base= (AVRational){1,25};
357 c->gop_size = 10; /* emit one intra frame every ten frames */
359 c->pix_fmt = PIX_FMT_YUV420P;
361 if(codec_id == AV_CODEC_ID_H264)
362 av_opt_set(c->priv_data, "preset", "slow", 0);
365 if (avcodec_open2(c, codec, NULL) < 0) {
366 fprintf(stderr, "Could not open codec\n");
370 f = fopen(filename, "wb");
372 fprintf(stderr, "Could not open %s\n", filename);
376 frame = avcodec_alloc_frame();
378 fprintf(stderr, "Could not allocate video frame\n");
381 frame->format = c->pix_fmt;
382 frame->width = c->width;
383 frame->height = c->height;
385 /* the image can be allocated by any means and av_image_alloc() is
386 * just the most convenient way if av_malloc() is to be used */
387 ret = av_image_alloc(frame->data, frame->linesize, c->width, c->height,
390 fprintf(stderr, "Could not allocate raw picture buffer\n");
394 /* encode 1 second of video */
396 av_init_packet(&pkt);
397 pkt.data = NULL; // packet data will be allocated by the encoder
401 /* prepare a dummy image */
403 for(y=0;y<c->height;y++) {
404 for(x=0;x<c->width;x++) {
405 frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
410 for(y=0;y<c->height/2;y++) {
411 for(x=0;x<c->width/2;x++) {
412 frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
413 frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
419 /* encode the image */
420 ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
422 fprintf(stderr, "Error encoding frame\n");
427 printf("Write frame %3d (size=%5d)\n", i, pkt.size);
428 fwrite(pkt.data, 1, pkt.size, f);
429 av_free_packet(&pkt);
433 /* get the delayed frames */
434 for (got_output = 1; got_output; i++) {
437 ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);
439 fprintf(stderr, "Error encoding frame\n");
444 printf("Write frame %3d (size=%5d)\n", i, pkt.size);
445 fwrite(pkt.data, 1, pkt.size, f);
446 av_free_packet(&pkt);
450 /* add sequence end code to have a real mpeg file */
451 fwrite(endcode, 1, sizeof(endcode), f);
456 av_freep(&frame->data[0]);
457 avcodec_free_frame(&frame);
462 * Video decoding example
465 static void pgm_save(unsigned char *buf, int wrap, int xsize, int ysize,
471 f=fopen(filename,"w");
472 fprintf(f,"P5\n%d %d\n%d\n",xsize,ysize,255);
474 fwrite(buf + i * wrap,1,xsize,f);
478 static void video_decode_example(const char *outfilename, const char *filename)
481 AVCodecContext *c= NULL;
482 int frame, got_picture, len;
485 uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
489 av_init_packet(&avpkt);
491 /* set end of buffer to 0 (this ensures that no overreading happens for damaged mpeg streams) */
492 memset(inbuf + INBUF_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
494 printf("Decode video file %s to %s\n", filename, outfilename);
496 /* find the mpeg1 video decoder */
497 codec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO);
499 fprintf(stderr, "Codec not found\n");
503 c = avcodec_alloc_context3(codec);
504 if(codec->capabilities&CODEC_CAP_TRUNCATED)
505 c->flags|= CODEC_FLAG_TRUNCATED; /* we do not send complete frames */
507 /* For some codecs, such as msmpeg4 and mpeg4, width and height
508 MUST be initialized there because this information is not
509 available in the bitstream. */
512 if (avcodec_open2(c, codec, NULL) < 0) {
513 fprintf(stderr, "Could not open codec\n");
517 /* the codec gives us the frame size, in samples */
519 f = fopen(filename, "rb");
521 fprintf(stderr, "Could not open %s\n", filename);
525 picture = avcodec_alloc_frame();
527 fprintf(stderr, "Could not allocate video frame\n");
533 avpkt.size = fread(inbuf, 1, INBUF_SIZE, f);
537 /* NOTE1: some codecs are stream based (mpegvideo, mpegaudio)
538 and this is the only method to use them because you cannot
539 know the compressed data size before analysing it.
541 BUT some other codecs (msmpeg4, mpeg4) are inherently frame
542 based, so you must call them with all the data for one
543 frame exactly. You must also initialize 'width' and
544 'height' before initializing them. */
546 /* NOTE2: some codecs allow the raw parameters (frame size,
547 sample rate) to be changed at any frame. We handle this, so
548 you should also take care of it */
550 /* here, we use a stream based decoder (mpeg1video), so we
551 feed decoder and see if it could decode a frame */
553 while (avpkt.size > 0) {
554 len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
556 fprintf(stderr, "Error while decoding frame %d\n", frame);
560 printf("Saving frame %3d\n", frame);
563 /* the picture is allocated by the decoder. no need to
565 snprintf(buf, sizeof(buf), outfilename, frame);
566 pgm_save(picture->data[0], picture->linesize[0],
567 c->width, c->height, buf);
575 /* some codecs, such as MPEG, transmit the I and P frame with a
576 latency of one frame. You must do the following to have a
577 chance to get the last frame of the video */
580 len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
582 printf("Saving last frame %3d\n", frame);
585 /* the picture is allocated by the decoder. no need to
587 snprintf(buf, sizeof(buf), outfilename, frame);
588 pgm_save(picture->data[0], picture->linesize[0],
589 c->width, c->height, buf);
597 avcodec_free_frame(&picture);
601 int main(int argc, char **argv)
603 const char *output_type;
605 /* register all the codecs */
606 avcodec_register_all();
609 printf("usage: %s output_type\n"
610 "API example program to decode/encode a media stream with libavcodec.\n"
611 "This program generates a synthetic stream and encodes it to a file\n"
612 "named test.h264, test.mp2 or test.mpg depending on output_type.\n"
613 "The encoded stream is then decoded and written to a raw data output\n."
614 "output_type must be choosen between 'h264', 'mp2', 'mpg'\n",
618 output_type = argv[1];
620 if (!strcmp(output_type, "h264")) {
621 video_encode_example("test.h264", AV_CODEC_ID_H264);
622 } else if (!strcmp(output_type, "mp2")) {
623 audio_encode_example("test.mp2");
624 audio_decode_example("test.sw", "test.mp2");
625 } else if (!strcmp(output_type, "mpg")) {
626 video_encode_example("test.mpg", AV_CODEC_ID_MPEG1VIDEO);
627 video_decode_example("test%02d.pgm", "test.mpg");
629 fprintf(stderr, "Invalid output type '%s', choose between 'h264', 'mp2', or 'mpg'\n",