]> git.sesse.net Git - ffmpeg/blob - doc/examples/decoding_encoding.c
movenc: Don't write the 'wave' atom or its child 'enda' for lpcm audio.
[ffmpeg] / doc / examples / decoding_encoding.c
1 /*
2  * Copyright (c) 2001 Fabrice Bellard
3  *
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:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
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
20  * THE SOFTWARE.
21  */
22
23 /**
24  * @file
25  * libavcodec API use example.
26  *
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
29  * format handling
30  */
31
32 #include <math.h>
33
34 #include <libavutil/imgutils.h>
35 #include <libavutil/opt.h>
36 #include <libavcodec/avcodec.h>
37 #include <libavutil/mathematics.h>
38 #include <libavutil/samplefmt.h>
39
40 #define INBUF_SIZE 4096
41 #define AUDIO_INBUF_SIZE 20480
42 #define AUDIO_REFILL_THRESH 4096
43
44 /*
45  * Audio encoding example
46  */
47 static void audio_encode_example(const char *filename)
48 {
49     AVCodec *codec;
50     AVCodecContext *c= NULL;
51     int frame_size, i, j, out_size, outbuf_size;
52     FILE *f;
53     short *samples;
54     float t, tincr;
55     uint8_t *outbuf;
56
57     printf("Encode audio file %s\n", filename);
58
59     /* find the MP2 encoder */
60     codec = avcodec_find_encoder(CODEC_ID_MP2);
61     if (!codec) {
62         fprintf(stderr, "codec not found\n");
63         exit(1);
64     }
65
66     c = avcodec_alloc_context3(codec);
67
68     /* put sample parameters */
69     c->bit_rate = 64000;
70     c->sample_rate = 44100;
71     c->channels = 2;
72     c->sample_fmt = AV_SAMPLE_FMT_S16;
73
74     /* open it */
75     if (avcodec_open2(c, codec, NULL) < 0) {
76         fprintf(stderr, "could not open codec\n");
77         exit(1);
78     }
79
80     /* the codec gives us the frame size, in samples */
81     frame_size = c->frame_size;
82     samples = malloc(frame_size * 2 * c->channels);
83     outbuf_size = 10000;
84     outbuf = malloc(outbuf_size);
85
86     f = fopen(filename, "wb");
87     if (!f) {
88         fprintf(stderr, "could not open %s\n", filename);
89         exit(1);
90     }
91
92     /* encode a single tone sound */
93     t = 0;
94     tincr = 2 * M_PI * 440.0 / c->sample_rate;
95     for(i=0;i<200;i++) {
96         for(j=0;j<frame_size;j++) {
97             samples[2*j] = (int)(sin(t) * 10000);
98             samples[2*j+1] = samples[2*j];
99             t += tincr;
100         }
101         /* encode the samples */
102         out_size = avcodec_encode_audio(c, outbuf, outbuf_size, samples);
103         fwrite(outbuf, 1, out_size, f);
104     }
105     fclose(f);
106     free(outbuf);
107     free(samples);
108
109     avcodec_close(c);
110     av_free(c);
111 }
112
113 /*
114  * Audio decoding.
115  */
116 static void audio_decode_example(const char *outfilename, const char *filename)
117 {
118     AVCodec *codec;
119     AVCodecContext *c= NULL;
120     int len;
121     FILE *f, *outfile;
122     uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
123     AVPacket avpkt;
124     AVFrame *decoded_frame = NULL;
125
126     av_init_packet(&avpkt);
127
128     printf("Decode audio file %s\n", filename);
129
130     /* find the mpeg audio decoder */
131     codec = avcodec_find_decoder(CODEC_ID_MP2);
132     if (!codec) {
133         fprintf(stderr, "codec not found\n");
134         exit(1);
135     }
136
137     c = avcodec_alloc_context3(codec);
138
139     /* open it */
140     if (avcodec_open2(c, codec, NULL) < 0) {
141         fprintf(stderr, "could not open codec\n");
142         exit(1);
143     }
144
145     f = fopen(filename, "rb");
146     if (!f) {
147         fprintf(stderr, "could not open %s\n", filename);
148         exit(1);
149     }
150     outfile = fopen(outfilename, "wb");
151     if (!outfile) {
152         av_free(c);
153         exit(1);
154     }
155
156     /* decode until eof */
157     avpkt.data = inbuf;
158     avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
159
160     while (avpkt.size > 0) {
161         int got_frame = 0;
162
163         if (!decoded_frame) {
164             if (!(decoded_frame = avcodec_alloc_frame())) {
165                 fprintf(stderr, "out of memory\n");
166                 exit(1);
167             }
168         } else
169             avcodec_get_frame_defaults(decoded_frame);
170
171         len = avcodec_decode_audio4(c, decoded_frame, &got_frame, &avpkt);
172         if (len < 0) {
173             fprintf(stderr, "Error while decoding\n");
174             exit(1);
175         }
176         if (got_frame) {
177             /* if a frame has been decoded, output it */
178             int data_size = av_samples_get_buffer_size(NULL, c->channels,
179                                                        decoded_frame->nb_samples,
180                                                        c->sample_fmt, 1);
181             fwrite(decoded_frame->data[0], 1, data_size, outfile);
182         }
183         avpkt.size -= len;
184         avpkt.data += len;
185         avpkt.dts =
186         avpkt.pts = AV_NOPTS_VALUE;
187         if (avpkt.size < AUDIO_REFILL_THRESH) {
188             /* Refill the input buffer, to avoid trying to decode
189              * incomplete frames. Instead of this, one could also use
190              * a parser, or use a proper container format through
191              * libavformat. */
192             memmove(inbuf, avpkt.data, avpkt.size);
193             avpkt.data = inbuf;
194             len = fread(avpkt.data + avpkt.size, 1,
195                         AUDIO_INBUF_SIZE - avpkt.size, f);
196             if (len > 0)
197                 avpkt.size += len;
198         }
199     }
200
201     fclose(outfile);
202     fclose(f);
203
204     avcodec_close(c);
205     av_free(c);
206     av_free(decoded_frame);
207 }
208
209 /*
210  * Video encoding example
211  */
212 static void video_encode_example(const char *filename, int codec_id)
213 {
214     AVCodec *codec;
215     AVCodecContext *c= NULL;
216     int i, out_size, x, y, outbuf_size;
217     FILE *f;
218     AVFrame *picture;
219     uint8_t *outbuf;
220     int had_output=0;
221
222     printf("Encode video file %s\n", filename);
223
224     /* find the mpeg1 video encoder */
225     codec = avcodec_find_encoder(codec_id);
226     if (!codec) {
227         fprintf(stderr, "codec not found\n");
228         exit(1);
229     }
230
231     c = avcodec_alloc_context3(codec);
232     picture= avcodec_alloc_frame();
233
234     /* put sample parameters */
235     c->bit_rate = 400000;
236     /* resolution must be a multiple of two */
237     c->width = 352;
238     c->height = 288;
239     /* frames per second */
240     c->time_base= (AVRational){1,25};
241     c->gop_size = 10; /* emit one intra frame every ten frames */
242     c->max_b_frames=1;
243     c->pix_fmt = PIX_FMT_YUV420P;
244
245     if(codec_id == CODEC_ID_H264)
246         av_opt_set(c->priv_data, "preset", "slow", 0);
247
248     /* open it */
249     if (avcodec_open2(c, codec, NULL) < 0) {
250         fprintf(stderr, "could not open codec\n");
251         exit(1);
252     }
253
254     f = fopen(filename, "wb");
255     if (!f) {
256         fprintf(stderr, "could not open %s\n", filename);
257         exit(1);
258     }
259
260     /* alloc image and output buffer */
261     outbuf_size = 100000 + 12*c->width*c->height;
262     outbuf = malloc(outbuf_size);
263
264     /* the image can be allocated by any means and av_image_alloc() is
265      * just the most convenient way if av_malloc() is to be used */
266     av_image_alloc(picture->data, picture->linesize,
267                    c->width, c->height, c->pix_fmt, 1);
268
269     /* encode 1 second of video */
270     for(i=0;i<25;i++) {
271         fflush(stdout);
272         /* prepare a dummy image */
273         /* Y */
274         for(y=0;y<c->height;y++) {
275             for(x=0;x<c->width;x++) {
276                 picture->data[0][y * picture->linesize[0] + x] = x + y + i * 3;
277             }
278         }
279
280         /* Cb and Cr */
281         for(y=0;y<c->height/2;y++) {
282             for(x=0;x<c->width/2;x++) {
283                 picture->data[1][y * picture->linesize[1] + x] = 128 + y + i * 2;
284                 picture->data[2][y * picture->linesize[2] + x] = 64 + x + i * 5;
285             }
286         }
287
288         /* encode the image */
289         out_size = avcodec_encode_video(c, outbuf, outbuf_size, picture);
290         had_output |= out_size;
291         printf("encoding frame %3d (size=%5d)\n", i, out_size);
292         fwrite(outbuf, 1, out_size, f);
293     }
294
295     /* get the delayed frames */
296     for(; out_size || !had_output; i++) {
297         fflush(stdout);
298
299         out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
300         had_output |= out_size;
301         printf("write frame %3d (size=%5d)\n", i, out_size);
302         fwrite(outbuf, 1, out_size, f);
303     }
304
305     /* add sequence end code to have a real mpeg file */
306     outbuf[0] = 0x00;
307     outbuf[1] = 0x00;
308     outbuf[2] = 0x01;
309     outbuf[3] = 0xb7;
310     fwrite(outbuf, 1, 4, f);
311     fclose(f);
312     free(outbuf);
313
314     avcodec_close(c);
315     av_free(c);
316     av_free(picture->data[0]);
317     av_free(picture);
318     printf("\n");
319 }
320
321 /*
322  * Video decoding example
323  */
324
325 static void pgm_save(unsigned char *buf, int wrap, int xsize, int ysize,
326                      char *filename)
327 {
328     FILE *f;
329     int i;
330
331     f=fopen(filename,"w");
332     fprintf(f,"P5\n%d %d\n%d\n",xsize,ysize,255);
333     for(i=0;i<ysize;i++)
334         fwrite(buf + i * wrap,1,xsize,f);
335     fclose(f);
336 }
337
338 static void video_decode_example(const char *outfilename, const char *filename)
339 {
340     AVCodec *codec;
341     AVCodecContext *c= NULL;
342     int frame, got_picture, len;
343     FILE *f;
344     AVFrame *picture;
345     uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
346     char buf[1024];
347     AVPacket avpkt;
348
349     av_init_packet(&avpkt);
350
351     /* set end of buffer to 0 (this ensures that no overreading happens for damaged mpeg streams) */
352     memset(inbuf + INBUF_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
353
354     printf("Decode video file %s\n", filename);
355
356     /* find the mpeg1 video decoder */
357     codec = avcodec_find_decoder(CODEC_ID_MPEG1VIDEO);
358     if (!codec) {
359         fprintf(stderr, "codec not found\n");
360         exit(1);
361     }
362
363     c = avcodec_alloc_context3(codec);
364     picture= avcodec_alloc_frame();
365
366     if(codec->capabilities&CODEC_CAP_TRUNCATED)
367         c->flags|= CODEC_FLAG_TRUNCATED; /* we do not send complete frames */
368
369     /* For some codecs, such as msmpeg4 and mpeg4, width and height
370        MUST be initialized there because this information is not
371        available in the bitstream. */
372
373     /* open it */
374     if (avcodec_open2(c, codec, NULL) < 0) {
375         fprintf(stderr, "could not open codec\n");
376         exit(1);
377     }
378
379     /* the codec gives us the frame size, in samples */
380
381     f = fopen(filename, "rb");
382     if (!f) {
383         fprintf(stderr, "could not open %s\n", filename);
384         exit(1);
385     }
386
387     frame = 0;
388     for(;;) {
389         avpkt.size = fread(inbuf, 1, INBUF_SIZE, f);
390         if (avpkt.size == 0)
391             break;
392
393         /* NOTE1: some codecs are stream based (mpegvideo, mpegaudio)
394            and this is the only method to use them because you cannot
395            know the compressed data size before analysing it.
396
397            BUT some other codecs (msmpeg4, mpeg4) are inherently frame
398            based, so you must call them with all the data for one
399            frame exactly. You must also initialize 'width' and
400            'height' before initializing them. */
401
402         /* NOTE2: some codecs allow the raw parameters (frame size,
403            sample rate) to be changed at any frame. We handle this, so
404            you should also take care of it */
405
406         /* here, we use a stream based decoder (mpeg1video), so we
407            feed decoder and see if it could decode a frame */
408         avpkt.data = inbuf;
409         while (avpkt.size > 0) {
410             len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
411             if (len < 0) {
412                 fprintf(stderr, "Error while decoding frame %d\n", frame);
413                 exit(1);
414             }
415             if (got_picture) {
416                 printf("saving frame %3d\n", frame);
417                 fflush(stdout);
418
419                 /* the picture is allocated by the decoder. no need to
420                    free it */
421                 snprintf(buf, sizeof(buf), outfilename, frame);
422                 pgm_save(picture->data[0], picture->linesize[0],
423                          c->width, c->height, buf);
424                 frame++;
425             }
426             avpkt.size -= len;
427             avpkt.data += len;
428         }
429     }
430
431     /* some codecs, such as MPEG, transmit the I and P frame with a
432        latency of one frame. You must do the following to have a
433        chance to get the last frame of the video */
434     avpkt.data = NULL;
435     avpkt.size = 0;
436     len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
437     if (got_picture) {
438         printf("saving last frame %3d\n", frame);
439         fflush(stdout);
440
441         /* the picture is allocated by the decoder. no need to
442            free it */
443         snprintf(buf, sizeof(buf), outfilename, frame);
444         pgm_save(picture->data[0], picture->linesize[0],
445                  c->width, c->height, buf);
446         frame++;
447     }
448
449     fclose(f);
450
451     avcodec_close(c);
452     av_free(c);
453     av_free(picture);
454     printf("\n");
455 }
456
457 int main(int argc, char **argv)
458 {
459     const char *filename;
460
461     /* register all the codecs */
462     avcodec_register_all();
463
464     if (argc <= 1) {
465         audio_encode_example("/tmp/test.mp2");
466         audio_decode_example("/tmp/test.sw", "/tmp/test.mp2");
467
468         video_encode_example("/tmp/test.h264", CODEC_ID_H264);
469         video_encode_example("/tmp/test.mpg", CODEC_ID_MPEG1VIDEO);
470         filename = "/tmp/test.mpg";
471     } else {
472         filename = argv[1];
473     }
474
475     //    audio_decode_example("/tmp/test.sw", filename);
476     video_decode_example("/tmp/test%d.pgm", filename);
477
478     return 0;
479 }