]> git.sesse.net Git - ffmpeg/blob - doc/examples/decoding_encoding.c
Merge commit 'd5c62122a7b26704bf867a1262df358623bf5edf'
[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/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>
41
42 #define INBUF_SIZE 4096
43 #define AUDIO_INBUF_SIZE 20480
44 #define AUDIO_REFILL_THRESH 4096
45
46 /* check that a given sample format is supported by the encoder */
47 static int check_sample_fmt(AVCodec *codec, enum AVSampleFormat sample_fmt)
48 {
49     const enum AVSampleFormat *p = codec->sample_fmts;
50
51     while (*p != AV_SAMPLE_FMT_NONE) {
52         if (*p == sample_fmt)
53             return 1;
54         p++;
55     }
56     return 0;
57 }
58
59 /* just pick the highest supported samplerate */
60 static int select_sample_rate(AVCodec *codec)
61 {
62     const int *p;
63     int best_samplerate = 0;
64
65     if (!codec->supported_samplerates)
66         return 44100;
67
68     p = codec->supported_samplerates;
69     while (*p) {
70         best_samplerate = FFMAX(*p, best_samplerate);
71         p++;
72     }
73     return best_samplerate;
74 }
75
76 /* select layout with the highest channel count */
77 static int select_channel_layout(AVCodec *codec)
78 {
79     const uint64_t *p;
80     uint64_t best_ch_layout = 0;
81     int best_nb_channells   = 0;
82
83     if (!codec->channel_layouts)
84         return AV_CH_LAYOUT_STEREO;
85
86     p = codec->channel_layouts;
87     while (*p) {
88         int nb_channels = av_get_channel_layout_nb_channels(*p);
89
90         if (nb_channels > best_nb_channells) {
91             best_ch_layout    = *p;
92             best_nb_channells = nb_channels;
93         }
94         p++;
95     }
96     return best_ch_layout;
97 }
98
99 /*
100  * Audio encoding example
101  */
102 static void audio_encode_example(const char *filename)
103 {
104     AVCodec *codec;
105     AVCodecContext *c= NULL;
106     AVFrame *frame;
107     AVPacket pkt;
108     int i, j, k, ret, got_output;
109     int buffer_size;
110     FILE *f;
111     uint16_t *samples;
112     float t, tincr;
113
114     printf("Encode audio file %s\n", filename);
115
116     /* find the MP2 encoder */
117     codec = avcodec_find_encoder(AV_CODEC_ID_MP2);
118     if (!codec) {
119         fprintf(stderr, "Codec not found\n");
120         exit(1);
121     }
122
123     c = avcodec_alloc_context3(codec);
124
125     /* put sample parameters */
126     c->bit_rate = 64000;
127
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));
133         exit(1);
134     }
135
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);
140
141     /* open it */
142     if (avcodec_open2(c, codec, NULL) < 0) {
143         fprintf(stderr, "Could not open codec\n");
144         exit(1);
145     }
146
147     f = fopen(filename, "wb");
148     if (!f) {
149         fprintf(stderr, "Could not open %s\n", filename);
150         exit(1);
151     }
152
153     /* frame containing input raw audio */
154     frame = avcodec_alloc_frame();
155     if (!frame) {
156         fprintf(stderr, "Could not allocate audio frame\n");
157         exit(1);
158     }
159
160     frame->nb_samples     = c->frame_size;
161     frame->format         = c->sample_fmt;
162     frame->channel_layout = c->channel_layout;
163
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,
167                                              c->sample_fmt, 0);
168     samples = av_malloc(buffer_size);
169     if (!samples) {
170         fprintf(stderr, "Could not allocate %d bytes for samples buffer\n",
171                 buffer_size);
172         exit(1);
173     }
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);
177     if (ret < 0) {
178         fprintf(stderr, "Could not setup audio frame\n");
179         exit(1);
180     }
181
182     /* encode a single tone sound */
183     t = 0;
184     tincr = 2 * M_PI * 440.0 / c->sample_rate;
185     for(i=0;i<200;i++) {
186         av_init_packet(&pkt);
187         pkt.data = NULL; // packet data will be allocated by the encoder
188         pkt.size = 0;
189
190         for (j = 0; j < c->frame_size; j++) {
191             samples[2*j] = (int)(sin(t) * 10000);
192
193             for (k = 1; k < c->channels; k++)
194                 samples[2*j + k] = samples[2*j];
195             t += tincr;
196         }
197         /* encode the samples */
198         ret = avcodec_encode_audio2(c, &pkt, frame, &got_output);
199         if (ret < 0) {
200             fprintf(stderr, "Error encoding audio frame\n");
201             exit(1);
202         }
203         if (got_output) {
204             fwrite(pkt.data, 1, pkt.size, f);
205             av_free_packet(&pkt);
206         }
207     }
208
209     /* get the delayed frames */
210     for (got_output = 1; got_output; i++) {
211         ret = avcodec_encode_audio2(c, &pkt, NULL, &got_output);
212         if (ret < 0) {
213             fprintf(stderr, "Error encoding frame\n");
214             exit(1);
215         }
216
217         if (got_output) {
218             fwrite(pkt.data, 1, pkt.size, f);
219             av_free_packet(&pkt);
220         }
221     }
222     fclose(f);
223
224     av_freep(&samples);
225     avcodec_free_frame(&frame);
226     avcodec_close(c);
227     av_free(c);
228 }
229
230 /*
231  * Audio decoding.
232  */
233 static void audio_decode_example(const char *outfilename, const char *filename)
234 {
235     AVCodec *codec;
236     AVCodecContext *c= NULL;
237     int len;
238     FILE *f, *outfile;
239     uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
240     AVPacket avpkt;
241     AVFrame *decoded_frame = NULL;
242
243     av_init_packet(&avpkt);
244
245     printf("Decode audio file %s to %s\n", filename, outfilename);
246
247     /* find the mpeg audio decoder */
248     codec = avcodec_find_decoder(AV_CODEC_ID_MP2);
249     if (!codec) {
250         fprintf(stderr, "Codec not found\n");
251         exit(1);
252     }
253
254     c = avcodec_alloc_context3(codec);
255
256     /* open it */
257     if (avcodec_open2(c, codec, NULL) < 0) {
258         fprintf(stderr, "Could not open codec\n");
259         exit(1);
260     }
261
262     f = fopen(filename, "rb");
263     if (!f) {
264         fprintf(stderr, "Could not open %s\n", filename);
265         exit(1);
266     }
267     outfile = fopen(outfilename, "wb");
268     if (!outfile) {
269         av_free(c);
270         exit(1);
271     }
272
273     /* decode until eof */
274     avpkt.data = inbuf;
275     avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
276
277     while (avpkt.size > 0) {
278         int got_frame = 0;
279
280         if (!decoded_frame) {
281             if (!(decoded_frame = avcodec_alloc_frame())) {
282                 fprintf(stderr, "Could not allocate audio frame\n");
283                 exit(1);
284             }
285         } else
286             avcodec_get_frame_defaults(decoded_frame);
287
288         len = avcodec_decode_audio4(c, decoded_frame, &got_frame, &avpkt);
289         if (len < 0) {
290             fprintf(stderr, "Error while decoding\n");
291             exit(1);
292         }
293         if (got_frame) {
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,
297                                                        c->sample_fmt, 1);
298             fwrite(decoded_frame->data[0], 1, data_size, outfile);
299         }
300         avpkt.size -= len;
301         avpkt.data += len;
302         avpkt.dts =
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
308              * libavformat. */
309             memmove(inbuf, avpkt.data, avpkt.size);
310             avpkt.data = inbuf;
311             len = fread(avpkt.data + avpkt.size, 1,
312                         AUDIO_INBUF_SIZE - avpkt.size, f);
313             if (len > 0)
314                 avpkt.size += len;
315         }
316     }
317
318     fclose(outfile);
319     fclose(f);
320
321     avcodec_close(c);
322     av_free(c);
323     avcodec_free_frame(&decoded_frame);
324 }
325
326 /*
327  * Video encoding example
328  */
329 static void video_encode_example(const char *filename, int codec_id)
330 {
331     AVCodec *codec;
332     AVCodecContext *c= NULL;
333     int i, ret, x, y, got_output;
334     FILE *f;
335     AVFrame *frame;
336     AVPacket pkt;
337     uint8_t endcode[] = { 0, 0, 1, 0xb7 };
338
339     printf("Encode video file %s\n", filename);
340
341     /* find the mpeg1 video encoder */
342     codec = avcodec_find_encoder(codec_id);
343     if (!codec) {
344         fprintf(stderr, "Codec not found\n");
345         exit(1);
346     }
347
348     c = avcodec_alloc_context3(codec);
349
350     /* put sample parameters */
351     c->bit_rate = 400000;
352     /* resolution must be a multiple of two */
353     c->width = 352;
354     c->height = 288;
355     /* frames per second */
356     c->time_base= (AVRational){1,25};
357     c->gop_size = 10; /* emit one intra frame every ten frames */
358     c->max_b_frames=1;
359     c->pix_fmt = AV_PIX_FMT_YUV420P;
360
361     if(codec_id == AV_CODEC_ID_H264)
362         av_opt_set(c->priv_data, "preset", "slow", 0);
363
364     /* open it */
365     if (avcodec_open2(c, codec, NULL) < 0) {
366         fprintf(stderr, "Could not open codec\n");
367         exit(1);
368     }
369
370     f = fopen(filename, "wb");
371     if (!f) {
372         fprintf(stderr, "Could not open %s\n", filename);
373         exit(1);
374     }
375
376     frame = avcodec_alloc_frame();
377     if (!frame) {
378         fprintf(stderr, "Could not allocate video frame\n");
379         exit(1);
380     }
381     frame->format = c->pix_fmt;
382     frame->width  = c->width;
383     frame->height = c->height;
384
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,
388                          c->pix_fmt, 32);
389     if (ret < 0) {
390         fprintf(stderr, "Could not allocate raw picture buffer\n");
391         exit(1);
392     }
393
394     /* encode 1 second of video */
395     for(i=0;i<25;i++) {
396         av_init_packet(&pkt);
397         pkt.data = NULL;    // packet data will be allocated by the encoder
398         pkt.size = 0;
399
400         fflush(stdout);
401         /* prepare a dummy image */
402         /* Y */
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;
406             }
407         }
408
409         /* Cb and Cr */
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;
414             }
415         }
416
417         frame->pts = i;
418
419         /* encode the image */
420         ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
421         if (ret < 0) {
422             fprintf(stderr, "Error encoding frame\n");
423             exit(1);
424         }
425
426         if (got_output) {
427             printf("Write frame %3d (size=%5d)\n", i, pkt.size);
428             fwrite(pkt.data, 1, pkt.size, f);
429             av_free_packet(&pkt);
430         }
431     }
432
433     /* get the delayed frames */
434     for (got_output = 1; got_output; i++) {
435         fflush(stdout);
436
437         ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);
438         if (ret < 0) {
439             fprintf(stderr, "Error encoding frame\n");
440             exit(1);
441         }
442
443         if (got_output) {
444             printf("Write frame %3d (size=%5d)\n", i, pkt.size);
445             fwrite(pkt.data, 1, pkt.size, f);
446             av_free_packet(&pkt);
447         }
448     }
449
450     /* add sequence end code to have a real mpeg file */
451     fwrite(endcode, 1, sizeof(endcode), f);
452     fclose(f);
453
454     avcodec_close(c);
455     av_free(c);
456     av_freep(&frame->data[0]);
457     avcodec_free_frame(&frame);
458     printf("\n");
459 }
460
461 /*
462  * Video decoding example
463  */
464
465 static void pgm_save(unsigned char *buf, int wrap, int xsize, int ysize,
466                      char *filename)
467 {
468     FILE *f;
469     int i;
470
471     f=fopen(filename,"w");
472     fprintf(f,"P5\n%d %d\n%d\n",xsize,ysize,255);
473     for(i=0;i<ysize;i++)
474         fwrite(buf + i * wrap,1,xsize,f);
475     fclose(f);
476 }
477
478 static void video_decode_example(const char *outfilename, const char *filename)
479 {
480     AVCodec *codec;
481     AVCodecContext *c= NULL;
482     int frame, got_picture, len;
483     FILE *f;
484     AVFrame *picture;
485     uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
486     char buf[1024];
487     AVPacket avpkt;
488
489     av_init_packet(&avpkt);
490
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);
493
494     printf("Decode video file %s to %s\n", filename, outfilename);
495
496     /* find the mpeg1 video decoder */
497     codec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO);
498     if (!codec) {
499         fprintf(stderr, "Codec not found\n");
500         exit(1);
501     }
502
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 */
506
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. */
510
511     /* open it */
512     if (avcodec_open2(c, codec, NULL) < 0) {
513         fprintf(stderr, "Could not open codec\n");
514         exit(1);
515     }
516
517     /* the codec gives us the frame size, in samples */
518
519     f = fopen(filename, "rb");
520     if (!f) {
521         fprintf(stderr, "Could not open %s\n", filename);
522         exit(1);
523     }
524
525     picture = avcodec_alloc_frame();
526     if (!picture) {
527         fprintf(stderr, "Could not allocate video frame\n");
528         exit(1);
529     }
530
531     frame = 0;
532     for(;;) {
533         avpkt.size = fread(inbuf, 1, INBUF_SIZE, f);
534         if (avpkt.size == 0)
535             break;
536
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.
540
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. */
545
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 */
549
550         /* here, we use a stream based decoder (mpeg1video), so we
551            feed decoder and see if it could decode a frame */
552         avpkt.data = inbuf;
553         while (avpkt.size > 0) {
554             len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
555             if (len < 0) {
556                 fprintf(stderr, "Error while decoding frame %d\n", frame);
557                 exit(1);
558             }
559             if (got_picture) {
560                 printf("Saving frame %3d\n", frame);
561                 fflush(stdout);
562
563                 /* the picture is allocated by the decoder. no need to
564                    free it */
565                 snprintf(buf, sizeof(buf), outfilename, frame);
566                 pgm_save(picture->data[0], picture->linesize[0],
567                          c->width, c->height, buf);
568                 frame++;
569             }
570             avpkt.size -= len;
571             avpkt.data += len;
572         }
573     }
574
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 */
578     avpkt.data = NULL;
579     avpkt.size = 0;
580     len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
581     if (got_picture) {
582         printf("Saving last frame %3d\n", frame);
583         fflush(stdout);
584
585         /* the picture is allocated by the decoder. no need to
586            free it */
587         snprintf(buf, sizeof(buf), outfilename, frame);
588         pgm_save(picture->data[0], picture->linesize[0],
589                  c->width, c->height, buf);
590         frame++;
591     }
592
593     fclose(f);
594
595     avcodec_close(c);
596     av_free(c);
597     avcodec_free_frame(&picture);
598     printf("\n");
599 }
600
601 int main(int argc, char **argv)
602 {
603     const char *output_type;
604
605     /* register all the codecs */
606     avcodec_register_all();
607
608     if (argc < 2) {
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",
615                argv[0]);
616         return 1;
617     }
618     output_type = argv[1];
619
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");
628     } else {
629         fprintf(stderr, "Invalid output type '%s', choose between 'h264', 'mp2', or 'mpg'\n",
630                 output_type);
631         return 1;
632     }
633
634     return 0;
635 }