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 "libavutil/frame.h"
33 #include "libavutil/mem.h"
35 #include "libavcodec/avcodec.h"
37 #define AUDIO_INBUF_SIZE 20480
38 #define AUDIO_REFILL_THRESH 4096
40 int main(int argc, char **argv)
42 const char *outfilename, *filename;
44 AVCodecContext *c= NULL;
47 uint8_t inbuf[AUDIO_INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
49 AVFrame *decoded_frame = NULL;
52 fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
56 outfilename = argv[2];
58 /* register all the codecs */
59 avcodec_register_all();
61 av_init_packet(&avpkt);
63 /* find the MPEG audio decoder */
64 codec = avcodec_find_decoder(AV_CODEC_ID_MP2);
66 fprintf(stderr, "codec not found\n");
70 c = avcodec_alloc_context3(codec);
73 if (avcodec_open2(c, codec, NULL) < 0) {
74 fprintf(stderr, "could not open codec\n");
78 f = fopen(filename, "rb");
80 fprintf(stderr, "could not open %s\n", filename);
83 outfile = fopen(outfilename, "wb");
89 /* decode until eof */
91 avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
93 while (avpkt.size > 0) {
97 if (!(decoded_frame = av_frame_alloc())) {
98 fprintf(stderr, "out of memory\n");
103 len = avcodec_decode_audio4(c, decoded_frame, &got_frame, &avpkt);
105 fprintf(stderr, "Error while decoding\n");
109 /* if a frame has been decoded, output it */
110 int data_size = av_samples_get_buffer_size(NULL, c->channels,
111 decoded_frame->nb_samples,
113 fwrite(decoded_frame->data[0], 1, data_size, outfile);
117 if (avpkt.size < AUDIO_REFILL_THRESH) {
118 /* Refill the input buffer, to avoid trying to decode
119 * incomplete frames. Instead of this, one could also use
120 * a parser, or use a proper container format through
122 memmove(inbuf, avpkt.data, avpkt.size);
124 len = fread(avpkt.data + avpkt.size, 1,
125 AUDIO_INBUF_SIZE - avpkt.size, f);
134 avcodec_free_context(&c);
135 av_frame_free(&decoded_frame);