FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
filtering_audio.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2010 Nicolas George
3  * Copyright (c) 2011 Stefano Sabatini
4  * Copyright (c) 2012 Clément Bœsch
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 /**
26  * @file
27  * API example for audio decoding and filtering
28  * @example doc/examples/filtering_audio.c
29  */
30 
31 #include <unistd.h>
32 
33 #include <libavcodec/avcodec.h>
34 #include <libavformat/avformat.h>
36 #include <libavfilter/avcodec.h>
37 #include <libavfilter/buffersink.h>
38 #include <libavfilter/buffersrc.h>
39 
40 const char *filter_descr = "aresample=8000,aconvert=s16:mono";
41 const char *player = "ffplay -f s16le -ar 8000 -ac 1 -";
42 
48 static int audio_stream_index = -1;
49 
50 static int open_input_file(const char *filename)
51 {
52  int ret;
53  AVCodec *dec;
54 
55  if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
56  av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
57  return ret;
58  }
59 
60  if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
61  av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
62  return ret;
63  }
64 
65  /* select the audio stream */
66  ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0);
67  if (ret < 0) {
68  av_log(NULL, AV_LOG_ERROR, "Cannot find a audio stream in the input file\n");
69  return ret;
70  }
71  audio_stream_index = ret;
72  dec_ctx = fmt_ctx->streams[audio_stream_index]->codec;
73 
74  /* init the audio decoder */
75  if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
76  av_log(NULL, AV_LOG_ERROR, "Cannot open audio decoder\n");
77  return ret;
78  }
79 
80  return 0;
81 }
82 
83 static int init_filters(const char *filters_descr)
84 {
85  char args[512];
86  int ret;
87  AVFilter *abuffersrc = avfilter_get_by_name("abuffer");
88  AVFilter *abuffersink = avfilter_get_by_name("ffabuffersink");
91  const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16, -1 };
92  AVABufferSinkParams *abuffersink_params;
93  const AVFilterLink *outlink;
94  AVRational time_base = fmt_ctx->streams[audio_stream_index]->time_base;
95 
96  filter_graph = avfilter_graph_alloc();
97 
98  /* buffer audio source: the decoded frames from the decoder will be inserted here. */
99  if (!dec_ctx->channel_layout)
101  snprintf(args, sizeof(args),
102  "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%"PRIx64,
103  time_base.num, time_base.den, dec_ctx->sample_rate,
104  av_get_sample_fmt_name(dec_ctx->sample_fmt), dec_ctx->channel_layout);
105  ret = avfilter_graph_create_filter(&buffersrc_ctx, abuffersrc, "in",
106  args, NULL, filter_graph);
107  if (ret < 0) {
108  av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer source\n");
109  return ret;
110  }
111 
112  /* buffer audio sink: to terminate the filter chain. */
113  abuffersink_params = av_abuffersink_params_alloc();
114  abuffersink_params->sample_fmts = sample_fmts;
115  ret = avfilter_graph_create_filter(&buffersink_ctx, abuffersink, "out",
116  NULL, abuffersink_params, filter_graph);
117  av_free(abuffersink_params);
118  if (ret < 0) {
119  av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer sink\n");
120  return ret;
121  }
122 
123  /* Endpoints for the filter graph. */
124  outputs->name = av_strdup("in");
125  outputs->filter_ctx = buffersrc_ctx;
126  outputs->pad_idx = 0;
127  outputs->next = NULL;
128 
129  inputs->name = av_strdup("out");
130  inputs->filter_ctx = buffersink_ctx;
131  inputs->pad_idx = 0;
132  inputs->next = NULL;
133 
134  if ((ret = avfilter_graph_parse(filter_graph, filters_descr,
135  &inputs, &outputs, NULL)) < 0)
136  return ret;
137 
138  if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
139  return ret;
140 
141  /* Print summary of the sink buffer
142  * Note: args buffer is reused to store channel layout string */
143  outlink = buffersink_ctx->inputs[0];
144  av_get_channel_layout_string(args, sizeof(args), -1, outlink->channel_layout);
145  av_log(NULL, AV_LOG_INFO, "Output: srate:%dHz fmt:%s chlayout:%s\n",
146  (int)outlink->sample_rate,
147  (char *)av_x_if_null(av_get_sample_fmt_name(outlink->format), "?"),
148  args);
149 
150  return 0;
151 }
152 
153 static void print_samplesref(AVFilterBufferRef *samplesref)
154 {
155  const AVFilterBufferRefAudioProps *props = samplesref->audio;
156  const int n = props->nb_samples * av_get_channel_layout_nb_channels(props->channel_layout);
157  const uint16_t *p = (uint16_t*)samplesref->data[0];
158  const uint16_t *p_end = p + n;
159 
160  while (p < p_end) {
161  fputc(*p & 0xff, stdout);
162  fputc(*p>>8 & 0xff, stdout);
163  p++;
164  }
165  fflush(stdout);
166 }
167 
168 int main(int argc, char **argv)
169 {
170  int ret;
171  AVPacket packet;
173  int got_frame;
174 
175  if (!frame) {
176  perror("Could not allocate frame");
177  exit(1);
178  }
179  if (argc != 2) {
180  fprintf(stderr, "Usage: %s file | %s\n", argv[0], player);
181  exit(1);
182  }
183 
185  av_register_all();
187 
188  if ((ret = open_input_file(argv[1])) < 0)
189  goto end;
190  if ((ret = init_filters(filter_descr)) < 0)
191  goto end;
192 
193  /* read all packets */
194  while (1) {
195  AVFilterBufferRef *samplesref;
196  if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
197  break;
198 
199  if (packet.stream_index == audio_stream_index) {
201  got_frame = 0;
202  ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, &packet);
203  if (ret < 0) {
204  av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n");
205  continue;
206  }
207 
208  if (got_frame) {
209  /* push the audio data from decoded frame into the filtergraph */
210  if (av_buffersrc_add_frame(buffersrc_ctx, frame, 0) < 0) {
211  av_log(NULL, AV_LOG_ERROR, "Error while feeding the audio filtergraph\n");
212  break;
213  }
214 
215  /* pull filtered audio from the filtergraph */
216  while (1) {
217  ret = av_buffersink_get_buffer_ref(buffersink_ctx, &samplesref, 0);
218  if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
219  break;
220  if(ret < 0)
221  goto end;
222  if (samplesref) {
223  print_samplesref(samplesref);
224  avfilter_unref_bufferp(&samplesref);
225  }
226  }
227  }
228  }
229  av_free_packet(&packet);
230  }
231 end:
232  avfilter_graph_free(&filter_graph);
233  if (dec_ctx)
234  avcodec_close(dec_ctx);
235  avformat_close_input(&fmt_ctx);
236  av_freep(&frame);
237 
238  if (ret < 0 && ret != AVERROR_EOF) {
239  char buf[1024];
240  av_strerror(ret, buf, sizeof(buf));
241  fprintf(stderr, "Error occurred: %s\n", buf);
242  exit(1);
243  }
244 
245  exit(0);
246 }