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
32 #include "libavutil/imgutils.h"
33 #include "libavutil/opt.h"
34 #include "libavcodec/avcodec.h"
35 #include "libavutil/mathematics.h"
36 #include "libavutil/samplefmt.h"
38 #define INBUF_SIZE 4096
39 #define AUDIO_INBUF_SIZE 20480
40 #define AUDIO_REFILL_THRESH 4096
43 * Audio encoding example
45 static void audio_encode_example(const char *filename)
48 AVCodecContext *c= NULL;
49 int frame_size, i, j, out_size, outbuf_size;
55 printf("Audio encoding\n");
57 /* find the MP2 encoder */
58 codec = avcodec_find_encoder(CODEC_ID_MP2);
60 fprintf(stderr, "codec not found\n");
64 c = avcodec_alloc_context3(codec);
66 /* put sample parameters */
68 c->sample_rate = 44100;
70 c->sample_fmt = AV_SAMPLE_FMT_S16;
73 if (avcodec_open(c, codec) < 0) {
74 fprintf(stderr, "could not open codec\n");
78 /* the codec gives us the frame size, in samples */
79 frame_size = c->frame_size;
80 samples = malloc(frame_size * 2 * c->channels);
82 outbuf = malloc(outbuf_size);
84 f = fopen(filename, "wb");
86 fprintf(stderr, "could not open %s\n", filename);
90 /* encode a single tone sound */
92 tincr = 2 * M_PI * 440.0 / c->sample_rate;
94 for(j=0;j<frame_size;j++) {
95 samples[2*j] = (int)(sin(t) * 10000);
96 samples[2*j+1] = samples[2*j];
99 /* encode the samples */
100 out_size = avcodec_encode_audio(c, outbuf, outbuf_size, samples);
101 fwrite(outbuf, 1, out_size, f);
114 static void audio_decode_example(const char *outfilename, const char *filename)
117 AVCodecContext *c= NULL;
120 uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
122 AVFrame *decoded_frame = NULL;
124 av_init_packet(&avpkt);
126 printf("Audio decoding\n");
128 /* find the mpeg audio decoder */
129 codec = avcodec_find_decoder(CODEC_ID_MP2);
131 fprintf(stderr, "codec not found\n");
135 c = avcodec_alloc_context3(codec);
138 if (avcodec_open(c, codec) < 0) {
139 fprintf(stderr, "could not open codec\n");
143 f = fopen(filename, "rb");
145 fprintf(stderr, "could not open %s\n", filename);
148 outfile = fopen(outfilename, "wb");
154 /* decode until eof */
156 avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
158 while (avpkt.size > 0) {
161 if (!decoded_frame) {
162 if (!(decoded_frame = avcodec_alloc_frame())) {
163 fprintf(stderr, "out of memory\n");
167 avcodec_get_frame_defaults(decoded_frame);
169 len = avcodec_decode_audio4(c, decoded_frame, &got_frame, &avpkt);
171 fprintf(stderr, "Error while decoding\n");
175 /* if a frame has been decoded, output it */
176 int data_size = av_samples_get_buffer_size(NULL, c->channels,
177 decoded_frame->nb_samples,
179 fwrite(decoded_frame->data[0], 1, data_size, outfile);
183 if (avpkt.size < AUDIO_REFILL_THRESH) {
184 /* Refill the input buffer, to avoid trying to decode
185 * incomplete frames. Instead of this, one could also use
186 * a parser, or use a proper container format through
188 memmove(inbuf, avpkt.data, avpkt.size);
190 len = fread(avpkt.data + avpkt.size, 1,
191 AUDIO_INBUF_SIZE - avpkt.size, f);
202 av_free(decoded_frame);
206 * Video encoding example
208 static void video_encode_example(const char *filename, int codec_id)
211 AVCodecContext *c= NULL;
212 int i, out_size, size, x, y, outbuf_size;
217 printf("Video encoding\n");
219 /* find the mpeg1 video encoder */
220 codec = avcodec_find_encoder(codec_id);
222 fprintf(stderr, "codec not found\n");
226 c = avcodec_alloc_context3(codec);
227 picture= avcodec_alloc_frame();
229 /* put sample parameters */
230 c->bit_rate = 400000;
231 /* resolution must be a multiple of two */
234 /* frames per second */
235 c->time_base= (AVRational){1,25};
236 c->gop_size = 10; /* emit one intra frame every ten frames */
238 c->pix_fmt = PIX_FMT_YUV420P;
240 if(codec_id == CODEC_ID_H264)
241 av_opt_set(c->priv_data, "preset", "slow", 0);
244 if (avcodec_open(c, codec) < 0) {
245 fprintf(stderr, "could not open codec\n");
249 f = fopen(filename, "wb");
251 fprintf(stderr, "could not open %s\n", filename);
255 /* alloc image and output buffer */
256 outbuf_size = 100000;
257 outbuf = malloc(outbuf_size);
259 /* the image can be allocated by any means and av_image_alloc() is
260 * just the most convenient way if av_malloc() is to be used */
261 av_image_alloc(picture->data, picture->linesize,
262 c->width, c->height, c->pix_fmt, 1);
264 /* encode 1 second of video */
267 /* prepare a dummy image */
269 for(y=0;y<c->height;y++) {
270 for(x=0;x<c->width;x++) {
271 picture->data[0][y * picture->linesize[0] + x] = x + y + i * 3;
276 for(y=0;y<c->height/2;y++) {
277 for(x=0;x<c->width/2;x++) {
278 picture->data[1][y * picture->linesize[1] + x] = 128 + y + i * 2;
279 picture->data[2][y * picture->linesize[2] + x] = 64 + x + i * 5;
283 /* encode the image */
284 out_size = avcodec_encode_video(c, outbuf, outbuf_size, picture);
285 printf("encoding frame %3d (size=%5d)\n", i, out_size);
286 fwrite(outbuf, 1, out_size, f);
289 /* get the delayed frames */
290 for(; out_size; i++) {
293 out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
294 printf("write frame %3d (size=%5d)\n", i, out_size);
295 fwrite(outbuf, 1, out_size, f);
298 /* add sequence end code to have a real mpeg file */
303 fwrite(outbuf, 1, 4, f);
309 av_free(picture->data[0]);
315 * Video decoding example
318 static void pgm_save(unsigned char *buf, int wrap, int xsize, int ysize,
324 f=fopen(filename,"w");
325 fprintf(f,"P5\n%d %d\n%d\n",xsize,ysize,255);
327 fwrite(buf + i * wrap,1,xsize,f);
331 static void video_decode_example(const char *outfilename, const char *filename)
334 AVCodecContext *c= NULL;
335 int frame, got_picture, len;
338 uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
342 av_init_packet(&avpkt);
344 /* set end of buffer to 0 (this ensures that no overreading happens for damaged mpeg streams) */
345 memset(inbuf + INBUF_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
347 printf("Video decoding\n");
349 /* find the mpeg1 video decoder */
350 codec = avcodec_find_decoder(CODEC_ID_MPEG1VIDEO);
352 fprintf(stderr, "codec not found\n");
356 c = avcodec_alloc_context3(codec);
357 picture= avcodec_alloc_frame();
359 if(codec->capabilities&CODEC_CAP_TRUNCATED)
360 c->flags|= CODEC_FLAG_TRUNCATED; /* we do not send complete frames */
362 /* For some codecs, such as msmpeg4 and mpeg4, width and height
363 MUST be initialized there because this information is not
364 available in the bitstream. */
367 if (avcodec_open(c, codec) < 0) {
368 fprintf(stderr, "could not open codec\n");
372 /* the codec gives us the frame size, in samples */
374 f = fopen(filename, "rb");
376 fprintf(stderr, "could not open %s\n", filename);
382 avpkt.size = fread(inbuf, 1, INBUF_SIZE, f);
386 /* NOTE1: some codecs are stream based (mpegvideo, mpegaudio)
387 and this is the only method to use them because you cannot
388 know the compressed data size before analysing it.
390 BUT some other codecs (msmpeg4, mpeg4) are inherently frame
391 based, so you must call them with all the data for one
392 frame exactly. You must also initialize 'width' and
393 'height' before initializing them. */
395 /* NOTE2: some codecs allow the raw parameters (frame size,
396 sample rate) to be changed at any frame. We handle this, so
397 you should also take care of it */
399 /* here, we use a stream based decoder (mpeg1video), so we
400 feed decoder and see if it could decode a frame */
402 while (avpkt.size > 0) {
403 len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
405 fprintf(stderr, "Error while decoding frame %d\n", frame);
409 printf("saving frame %3d\n", frame);
412 /* the picture is allocated by the decoder. no need to
414 snprintf(buf, sizeof(buf), outfilename, frame);
415 pgm_save(picture->data[0], picture->linesize[0],
416 c->width, c->height, buf);
424 /* some codecs, such as MPEG, transmit the I and P frame with a
425 latency of one frame. You must do the following to have a
426 chance to get the last frame of the video */
429 len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
431 printf("saving last frame %3d\n", frame);
434 /* the picture is allocated by the decoder. no need to
436 snprintf(buf, sizeof(buf), outfilename, frame);
437 pgm_save(picture->data[0], picture->linesize[0],
438 c->width, c->height, buf);
450 int main(int argc, char **argv)
452 const char *filename;
454 /* must be called before using avcodec lib */
457 /* register all the codecs */
458 avcodec_register_all();
461 audio_encode_example("/tmp/test.mp2");
462 audio_decode_example("/tmp/test.sw", "/tmp/test.mp2");
464 video_encode_example("/tmp/test.h264", CODEC_ID_H264);
465 video_encode_example("/tmp/test.mpg", CODEC_ID_MPEG1VIDEO);
466 filename = "/tmp/test.mpg";
471 // audio_decode_example("/tmp/test.sw", filename);
472 video_decode_example("/tmp/test%d.pgm", filename);