]> git.sesse.net Git - ffmpeg/blob - doc/examples/filtering_audio.c
Merge commit '685e6f2e3939f124b41c7801cc541dad8252af3d'
[ffmpeg] / doc / examples / filtering_audio.c
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>
35 #include <libavfilter/avfiltergraph.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
43 static AVFormatContext *fmt_ctx;
44 static AVCodecContext *dec_ctx;
45 AVFilterContext *buffersink_ctx;
46 AVFilterContext *buffersrc_ctx;
47 AVFilterGraph *filter_graph;
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");
89     AVFilterInOut *outputs = avfilter_inout_alloc();
90     AVFilterInOut *inputs  = avfilter_inout_alloc();
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)
100         dec_ctx->channel_layout = av_get_default_channel_layout(dec_ctx->channels);
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;
172     AVFrame frame;
173     int got_frame;
174
175     if (argc != 2) {
176         fprintf(stderr, "Usage: %s file | %s\n", argv[0], player);
177         exit(1);
178     }
179
180     avcodec_register_all();
181     av_register_all();
182     avfilter_register_all();
183
184     if ((ret = open_input_file(argv[1])) < 0)
185         goto end;
186     if ((ret = init_filters(filter_descr)) < 0)
187         goto end;
188
189     /* read all packets */
190     while (1) {
191         AVFilterBufferRef *samplesref;
192         if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
193             break;
194
195         if (packet.stream_index == audio_stream_index) {
196             avcodec_get_frame_defaults(&frame);
197             got_frame = 0;
198             ret = avcodec_decode_audio4(dec_ctx, &frame, &got_frame, &packet);
199             if (ret < 0) {
200                 av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n");
201                 continue;
202             }
203
204             if (got_frame) {
205                 /* push the audio data from decoded frame into the filtergraph */
206                 if (av_buffersrc_add_frame(buffersrc_ctx, &frame, 0) < 0) {
207                     av_log(NULL, AV_LOG_ERROR, "Error while feeding the audio filtergraph\n");
208                     break;
209                 }
210
211                 /* pull filtered audio from the filtergraph */
212                 while (1) {
213                     ret = av_buffersink_get_buffer_ref(buffersink_ctx, &samplesref, 0);
214                     if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
215                         break;
216                     if(ret < 0)
217                         goto end;
218                     if (samplesref) {
219                         print_samplesref(samplesref);
220                         avfilter_unref_bufferp(&samplesref);
221                     }
222                 }
223             }
224         }
225         av_free_packet(&packet);
226     }
227 end:
228     avfilter_graph_free(&filter_graph);
229     if (dec_ctx)
230         avcodec_close(dec_ctx);
231     avformat_close_input(&fmt_ctx);
232
233     if (ret < 0 && ret != AVERROR_EOF) {
234         char buf[1024];
235         av_strerror(ret, buf, sizeof(buf));
236         fprintf(stderr, "Error occurred: %s\n", buf);
237         exit(1);
238     }
239
240     exit(0);
241 }