FFmpeg
decode_audio.c
Go to the documentation of this file.
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 libavcodec audio decoding API usage example
25  * @example decode_audio.c
26  *
27  * Decode data from an MP2 input file and generate a raw audio file to
28  * be played with ffplay.
29  */
30 
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 
35 #include <libavutil/frame.h>
36 #include <libavutil/mem.h>
37 
38 #include <libavcodec/avcodec.h>
39 
40 #define AUDIO_INBUF_SIZE 20480
41 #define AUDIO_REFILL_THRESH 4096
42 
43 static int get_format_from_sample_fmt(const char **fmt,
44  enum AVSampleFormat sample_fmt)
45 {
46  int i;
47  struct sample_fmt_entry {
48  enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
49  } sample_fmt_entries[] = {
50  { AV_SAMPLE_FMT_U8, "u8", "u8" },
51  { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
52  { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
53  { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
54  { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
55  };
56  *fmt = NULL;
57 
58  for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
59  struct sample_fmt_entry *entry = &sample_fmt_entries[i];
60  if (sample_fmt == entry->sample_fmt) {
61  *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
62  return 0;
63  }
64  }
65 
66  fprintf(stderr,
67  "sample format %s is not supported as output format\n",
68  av_get_sample_fmt_name(sample_fmt));
69  return -1;
70 }
71 
73  FILE *outfile)
74 {
75  int i, ch;
76  int ret, data_size;
77 
78  /* send the packet with the compressed data to the decoder */
80  if (ret < 0) {
81  fprintf(stderr, "Error submitting the packet to the decoder\n");
82  exit(1);
83  }
84 
85  /* read all the output frames (in general there may be any number of them */
86  while (ret >= 0) {
88  if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
89  return;
90  else if (ret < 0) {
91  fprintf(stderr, "Error during decoding\n");
92  exit(1);
93  }
95  if (data_size < 0) {
96  /* This should not occur, checking just for paranoia */
97  fprintf(stderr, "Failed to calculate data size\n");
98  exit(1);
99  }
100  for (i = 0; i < frame->nb_samples; i++)
101  for (ch = 0; ch < dec_ctx->ch_layout.nb_channels; ch++)
102  fwrite(frame->data[ch] + data_size*i, 1, data_size, outfile);
103  }
104 }
105 
106 int main(int argc, char **argv)
107 {
108  const char *outfilename, *filename;
109  const AVCodec *codec;
111  AVCodecParserContext *parser = NULL;
112  int len, ret;
113  FILE *f, *outfile;
115  uint8_t *data;
116  size_t data_size;
117  AVPacket *pkt;
118  AVFrame *decoded_frame = NULL;
119  enum AVSampleFormat sfmt;
120  int n_channels = 0;
121  const char *fmt;
122 
123  if (argc <= 2) {
124  fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
125  exit(0);
126  }
127  filename = argv[1];
128  outfilename = argv[2];
129 
130  pkt = av_packet_alloc();
131  if (!pkt) {
132  fprintf(stderr, "Could not allocate AVPacket\n");
133  exit(1); /* or proper cleanup and returning */
134  }
135 
136  /* find the MPEG audio decoder */
138  if (!codec) {
139  fprintf(stderr, "Codec not found\n");
140  exit(1);
141  }
142 
143  parser = av_parser_init(codec->id);
144  if (!parser) {
145  fprintf(stderr, "Parser not found\n");
146  exit(1);
147  }
148 
149  c = avcodec_alloc_context3(codec);
150  if (!c) {
151  fprintf(stderr, "Could not allocate audio codec context\n");
152  exit(1);
153  }
154 
155  /* open it */
156  if (avcodec_open2(c, codec, NULL) < 0) {
157  fprintf(stderr, "Could not open codec\n");
158  exit(1);
159  }
160 
161  f = fopen(filename, "rb");
162  if (!f) {
163  fprintf(stderr, "Could not open %s\n", filename);
164  exit(1);
165  }
166  outfile = fopen(outfilename, "wb");
167  if (!outfile) {
168  fprintf(stderr, "Could not open %s\n", outfilename);
169  exit(1);
170  }
171 
172  /* decode until eof */
173  data = inbuf;
174  data_size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
175 
176  while (data_size > 0) {
177  if (!decoded_frame) {
178  if (!(decoded_frame = av_frame_alloc())) {
179  fprintf(stderr, "Could not allocate audio frame\n");
180  exit(1);
181  }
182  }
183 
184  ret = av_parser_parse2(parser, c, &pkt->data, &pkt->size,
185  data, data_size,
187  if (ret < 0) {
188  fprintf(stderr, "Error while parsing\n");
189  exit(1);
190  }
191  data += ret;
192  data_size -= ret;
193 
194  if (pkt->size)
195  decode(c, pkt, decoded_frame, outfile);
196 
197  if (data_size < AUDIO_REFILL_THRESH) {
198  memmove(inbuf, data, data_size);
199  data = inbuf;
200  len = fread(data + data_size, 1,
201  AUDIO_INBUF_SIZE - data_size, f);
202  if (len > 0)
203  data_size += len;
204  }
205  }
206 
207  /* flush the decoder */
208  pkt->data = NULL;
209  pkt->size = 0;
210  decode(c, pkt, decoded_frame, outfile);
211 
212  /* print output pcm infomations, because there have no metadata of pcm */
213  sfmt = c->sample_fmt;
214 
215  if (av_sample_fmt_is_planar(sfmt)) {
216  const char *packed = av_get_sample_fmt_name(sfmt);
217  printf("Warning: the sample format the decoder produced is planar "
218  "(%s). This example will output the first channel only.\n",
219  packed ? packed : "?");
220  sfmt = av_get_packed_sample_fmt(sfmt);
221  }
222 
223  n_channels = c->ch_layout.nb_channels;
224  if ((ret = get_format_from_sample_fmt(&fmt, sfmt)) < 0)
225  goto end;
226 
227  printf("Play the output audio file with the command:\n"
228  "ffplay -f %s -ac %d -ar %d %s\n",
229  fmt, n_channels, c->sample_rate,
230  outfilename);
231 end:
232  fclose(outfile);
233  fclose(f);
234 
236  av_parser_close(parser);
237  av_frame_free(&decoded_frame);
239 
240  return 0;
241 }
AVCodec
AVCodec.
Definition: codec.h:172
entry
#define entry
Definition: aom_film_grain_template.c:66
dec_ctx
static AVCodecContext * dec_ctx
Definition: decode_filter_audio.c:45
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
printf
__device__ int printf(const char *,...)
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition: error.h:57
av_frame_free
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:64
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:427
AVPacket::data
uint8_t * data
Definition: packet.h:558
outfile
FILE * outfile
Definition: audiogen.c:96
data
const char data[16]
Definition: mxf.c:149
AVChannelLayout::nb_channels
int nb_channels
Number of channels in this layout.
Definition: channel_layout.h:329
av_packet_free
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition: packet.c:75
AVCodecContext::ch_layout
AVChannelLayout ch_layout
Audio channel layout.
Definition: avcodec.h:1039
av_parser_init
AVCodecParserContext * av_parser_init(int codec_id)
Definition: parser.c:32
av_frame_alloc
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:52
pkt
AVPacket * pkt
Definition: movenc.c:60
FF_ARRAY_ELEMS
#define FF_ARRAY_ELEMS(a)
Definition: sinewin_tablegen.c:29
AUDIO_REFILL_THRESH
#define AUDIO_REFILL_THRESH
Definition: decode_audio.c:41
decode
static void decode(AVCodecContext *dec_ctx, AVPacket *pkt, AVFrame *frame, FILE *outfile)
Definition: decode_audio.c:72
avcodec_alloc_context3
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition: options.c:149
AV_NE
#define AV_NE(be, le)
Definition: macros.h:33
AV_CODEC_ID_MP2
@ AV_CODEC_ID_MP2
Definition: codec_id.h:451
avcodec_receive_frame
int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
Return decoded output data from a decoder or encoder (when the AV_CODEC_FLAG_RECON_FRAME flag is used...
Definition: avcodec.c:708
av_sample_fmt_is_planar
int av_sample_fmt_is_planar(enum AVSampleFormat sample_fmt)
Check if the sample format is planar.
Definition: samplefmt.c:114
av_get_sample_fmt_name
const char * av_get_sample_fmt_name(enum AVSampleFormat sample_fmt)
Return the name of sample_fmt, or NULL if sample_fmt is not recognized.
Definition: samplefmt.c:51
NULL
#define NULL
Definition: coverity.c:32
avcodec_free_context
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer.
Definition: options.c:164
get_format_from_sample_fmt
static int get_format_from_sample_fmt(const char **fmt, enum AVSampleFormat sample_fmt)
Definition: decode_audio.c:43
avcodec_open2
int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition: avcodec.c:145
c
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C it is not safe even if the output of undefined operations is unused The unsafety may seem nit picking but Optimizing compilers have in fact optimized code on the assumption that no undefined Behavior occurs Optimizing code based on wrong assumptions can and has in some cases lead to effects beyond the output of computations The signed integer overflow problem in speed critical code Code which is highly optimized and works with signed integers sometimes has the problem that often the output of the computation does not c
Definition: undefined.txt:32
avcodec_find_decoder
const AVCodec * avcodec_find_decoder(enum AVCodecID id)
Find a registered decoder with a matching codec ID.
Definition: allcodecs.c:1027
f
f
Definition: af_crystalizer.c:122
AVPacket::size
int size
Definition: packet.h:559
AUDIO_INBUF_SIZE
#define AUDIO_INBUF_SIZE
Definition: decode_audio.c:40
AVCodecContext::sample_fmt
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1031
AV_NOPTS_VALUE
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:247
frame.h
av_packet_alloc
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition: packet.c:64
AVCodec::id
enum AVCodecID id
Definition: codec.h:186
avcodec_send_packet
int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
Supply raw packet data as input to a decoder.
Definition: decode.c:704
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:256
av_get_bytes_per_sample
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition: samplefmt.c:108
AV_SAMPLE_FMT_U8
@ AV_SAMPLE_FMT_U8
unsigned 8 bits
Definition: samplefmt.h:57
AVSampleFormat
AVSampleFormat
Audio sample formats.
Definition: samplefmt.h:55
AV_SAMPLE_FMT_S16
@ AV_SAMPLE_FMT_S16
signed 16 bits
Definition: samplefmt.h:58
len
int len
Definition: vorbis_enc_data.h:426
avcodec.h
AVCodecParserContext
Definition: avcodec.h:2575
ret
ret
Definition: filter_design.txt:187
main
int main(int argc, char **argv)
Definition: decode_audio.c:106
frame
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a it should directly call filter_frame on the corresponding output For a if there are queued frames already one of these frames should be pushed If the filter should request a frame on one of its repeatedly until at least one frame has been pushed Return or at least make progress towards producing a frame
Definition: filter_design.txt:265
AV_INPUT_BUFFER_PADDING_SIZE
#define AV_INPUT_BUFFER_PADDING_SIZE
Definition: defs.h:40
AVCodecContext
main external API structure.
Definition: avcodec.h:431
av_get_packed_sample_fmt
enum AVSampleFormat av_get_packed_sample_fmt(enum AVSampleFormat sample_fmt)
Get the packed alternative form of the given sample format.
Definition: samplefmt.c:77
av_parser_parse2
int av_parser_parse2(AVCodecParserContext *s, AVCodecContext *avctx, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int64_t pts, int64_t dts, int64_t pos)
Parse a packet.
Definition: parser.c:115
mem.h
AVPacket
This structure stores compressed data.
Definition: packet.h:535
AV_SAMPLE_FMT_DBL
@ AV_SAMPLE_FMT_DBL
double
Definition: samplefmt.h:61
AV_SAMPLE_FMT_S32
@ AV_SAMPLE_FMT_S32
signed 32 bits
Definition: samplefmt.h:59
AV_SAMPLE_FMT_FLT
@ AV_SAMPLE_FMT_FLT
float
Definition: samplefmt.h:60
av_parser_close
void av_parser_close(AVCodecParserContext *s)
Definition: parser.c:193