2 * copyright (c) 2001 Fabrice Bellard
4 * This file is part of Libav.
6 * Libav is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * Libav is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with Libav; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * audio decoding with libavcodec API example
25 * @example decode_audio.c
32 #include "libavcodec/avcodec.h"
34 #include "libavutil/frame.h"
36 #define AUDIO_INBUF_SIZE 20480
37 #define AUDIO_REFILL_THRESH 4096
39 int main(int argc, char **argv)
41 const char *outfilename, *filename;
43 AVCodecContext *c= NULL;
46 uint8_t inbuf[AUDIO_INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
48 AVFrame *decoded_frame = NULL;
51 fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
55 outfilename = argv[2];
57 /* register all the codecs */
58 avcodec_register_all();
60 av_init_packet(&avpkt);
62 /* find the MPEG audio decoder */
63 codec = avcodec_find_decoder(AV_CODEC_ID_MP2);
65 fprintf(stderr, "codec not found\n");
69 c = avcodec_alloc_context3(codec);
72 if (avcodec_open2(c, codec, NULL) < 0) {
73 fprintf(stderr, "could not open codec\n");
77 f = fopen(filename, "rb");
79 fprintf(stderr, "could not open %s\n", filename);
82 outfile = fopen(outfilename, "wb");
88 /* decode until eof */
90 avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
92 while (avpkt.size > 0) {
96 if (!(decoded_frame = av_frame_alloc())) {
97 fprintf(stderr, "out of memory\n");
102 len = avcodec_decode_audio4(c, decoded_frame, &got_frame, &avpkt);
104 fprintf(stderr, "Error while decoding\n");
108 /* if a frame has been decoded, output it */
109 int data_size = av_samples_get_buffer_size(NULL, c->channels,
110 decoded_frame->nb_samples,
112 fwrite(decoded_frame->data[0], 1, data_size, outfile);
116 if (avpkt.size < AUDIO_REFILL_THRESH) {
117 /* Refill the input buffer, to avoid trying to decode
118 * incomplete frames. Instead of this, one could also use
119 * a parser, or use a proper container format through
121 memmove(inbuf, avpkt.data, avpkt.size);
123 len = fread(avpkt.data + avpkt.size, 1,
124 AUDIO_INBUF_SIZE - avpkt.size, f);
133 avcodec_free_context(&c);
134 av_frame_free(&decoded_frame);