]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_pan.c
lavfi: remove audio.h include from avfilter.h.
[ffmpeg] / libavfilter / af_pan.c
1 /*
2  * Copyright (c) 2002 Anders Johansson <ajh@atri.curtin.edu.au>
3  * Copyright (c) 2011 Clément Bœsch <ubitux@gmail.com>
4  * Copyright (c) 2011 Nicolas George <nicolas.george@normalesup.org>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * Audio panning filter (channels mixing)
26  * Original code written by Anders Johansson for MPlayer,
27  * reimplemented for FFmpeg.
28  */
29
30 #include <stdio.h>
31 #include "libavutil/avstring.h"
32 #include "libavutil/opt.h"
33 #include "libswresample/swresample.h"
34 #include "audio.h"
35 #include "avfilter.h"
36
37 #define MAX_CHANNELS 63
38
39 typedef struct PanContext {
40     int64_t out_channel_layout;
41     double gain[MAX_CHANNELS][MAX_CHANNELS];
42     int64_t need_renorm;
43     int need_renumber;
44     int nb_input_channels;
45     int nb_output_channels;
46
47     int pure_gains;
48     /* channel mapping specific */
49     int channel_map[SWR_CH_MAX];
50     struct SwrContext *swr;
51 } PanContext;
52
53 static int parse_channel_name(char **arg, int *rchannel, int *rnamed)
54 {
55     char buf[8];
56     int len, i, channel_id = 0;
57     int64_t layout, layout0;
58
59     /* try to parse a channel name, e.g. "FL" */
60     if (sscanf(*arg, " %7[A-Z] %n", buf, &len)) {
61         layout0 = layout = av_get_channel_layout(buf);
62         /* channel_id <- first set bit in layout */
63         for (i = 32; i > 0; i >>= 1) {
64             if (layout >= (int64_t)1 << i) {
65                 channel_id += i;
66                 layout >>= i;
67             }
68         }
69         /* reject layouts that are not a single channel */
70         if (channel_id >= MAX_CHANNELS || layout0 != (int64_t)1 << channel_id)
71             return AVERROR(EINVAL);
72         *rchannel = channel_id;
73         *rnamed = 1;
74         *arg += len;
75         return 0;
76     }
77     /* try to parse a channel number, e.g. "c2" */
78     if (sscanf(*arg, " c%d %n", &channel_id, &len) &&
79         channel_id >= 0 && channel_id < MAX_CHANNELS) {
80         *rchannel = channel_id;
81         *rnamed = 0;
82         *arg += len;
83         return 0;
84     }
85     return AVERROR(EINVAL);
86 }
87
88 static void skip_spaces(char **arg)
89 {
90     int len = 0;
91
92     sscanf(*arg, " %n", &len);
93     *arg += len;
94 }
95
96 static av_cold int init(AVFilterContext *ctx, const char *args0, void *opaque)
97 {
98     PanContext *const pan = ctx->priv;
99     char *arg, *arg0, *tokenizer, *args = av_strdup(args0);
100     int out_ch_id, in_ch_id, len, named;
101     int nb_in_channels[2] = { 0, 0 }; // number of unnamed and named input channels
102     double gain;
103
104     if (!args0) {
105         av_log(ctx, AV_LOG_ERROR,
106                "pan filter needs a channel layout and a set "
107                "of channels definitions as parameter\n");
108         return AVERROR(EINVAL);
109     }
110     if (!args)
111         return AVERROR(ENOMEM);
112     arg = av_strtok(args, ":", &tokenizer);
113     pan->out_channel_layout = av_get_channel_layout(arg);
114     if (!pan->out_channel_layout) {
115         av_log(ctx, AV_LOG_ERROR, "Unknown channel layout \"%s\"\n", arg);
116         return AVERROR(EINVAL);
117     }
118     pan->nb_output_channels = av_get_channel_layout_nb_channels(pan->out_channel_layout);
119
120     /* parse channel specifications */
121     while ((arg = arg0 = av_strtok(NULL, ":", &tokenizer))) {
122         /* channel name */
123         if (parse_channel_name(&arg, &out_ch_id, &named)) {
124             av_log(ctx, AV_LOG_ERROR,
125                    "Expected out channel name, got \"%.8s\"\n", arg);
126             return AVERROR(EINVAL);
127         }
128         if (named) {
129             if (!((pan->out_channel_layout >> out_ch_id) & 1)) {
130                 av_log(ctx, AV_LOG_ERROR,
131                        "Channel \"%.8s\" does not exist in the chosen layout\n", arg0);
132                 return AVERROR(EINVAL);
133             }
134             /* get the channel number in the output channel layout:
135              * out_channel_layout & ((1 << out_ch_id) - 1) are all the
136              * channels that come before out_ch_id,
137              * so their count is the index of out_ch_id */
138             out_ch_id = av_get_channel_layout_nb_channels(pan->out_channel_layout & (((int64_t)1 << out_ch_id) - 1));
139         }
140         if (out_ch_id < 0 || out_ch_id >= pan->nb_output_channels) {
141             av_log(ctx, AV_LOG_ERROR,
142                    "Invalid out channel name \"%.8s\"\n", arg0);
143             return AVERROR(EINVAL);
144         }
145         if (*arg == '=') {
146             arg++;
147         } else if (*arg == '<') {
148             pan->need_renorm |= (int64_t)1 << out_ch_id;
149             arg++;
150         } else {
151             av_log(ctx, AV_LOG_ERROR,
152                    "Syntax error after channel name in \"%.8s\"\n", arg0);
153             return AVERROR(EINVAL);
154         }
155         /* gains */
156         while (1) {
157             gain = 1;
158             if (sscanf(arg, " %lf %n* %n", &gain, &len, &len))
159                 arg += len;
160             if (parse_channel_name(&arg, &in_ch_id, &named)){
161                 av_log(ctx, AV_LOG_ERROR,
162                        "Expected in channel name, got \"%.8s\"\n", arg);
163                 return AVERROR(EINVAL);
164             }
165             nb_in_channels[named]++;
166             if (nb_in_channels[!named]) {
167                 av_log(ctx, AV_LOG_ERROR,
168                        "Can not mix named and numbered channels\n");
169                 return AVERROR(EINVAL);
170             }
171             pan->gain[out_ch_id][in_ch_id] = gain;
172             if (!*arg)
173                 break;
174             if (*arg != '+') {
175                 av_log(ctx, AV_LOG_ERROR, "Syntax error near \"%.8s\"\n", arg);
176                 return AVERROR(EINVAL);
177             }
178             arg++;
179             skip_spaces(&arg);
180         }
181     }
182     pan->need_renumber = !!nb_in_channels[1];
183
184     av_free(args);
185     return 0;
186 }
187
188 static int are_gains_pure(const PanContext *pan)
189 {
190     int i, j;
191
192     for (i = 0; i < MAX_CHANNELS; i++) {
193         int nb_gain = 0;
194
195         for (j = 0; j < MAX_CHANNELS; j++) {
196             double gain = pan->gain[i][j];
197
198             /* channel mapping is effective only if 0% or 100% of a channel is
199              * selected... */
200             if (gain != 0. && gain != 1.)
201                 return 0;
202             /* ...and if the output channel is only composed of one input */
203             if (gain && nb_gain++)
204                 return 0;
205         }
206     }
207     return 1;
208 }
209
210 static int query_formats(AVFilterContext *ctx)
211 {
212     PanContext *pan = ctx->priv;
213     AVFilterLink *inlink  = ctx->inputs[0];
214     AVFilterLink *outlink = ctx->outputs[0];
215     AVFilterFormats *formats;
216
217     pan->pure_gains = are_gains_pure(pan);
218     /* libswr supports any sample and packing formats */
219     avfilter_set_common_sample_formats(ctx, avfilter_make_all_formats(AVMEDIA_TYPE_AUDIO));
220     avfilter_set_common_packing_formats(ctx, avfilter_make_all_packing_formats());
221
222     // inlink supports any channel layout
223     formats = avfilter_make_all_channel_layouts();
224     avfilter_formats_ref(formats, &inlink->out_chlayouts);
225
226     // outlink supports only requested output channel layout
227     formats = NULL;
228     avfilter_add_format(&formats, pan->out_channel_layout);
229     avfilter_formats_ref(formats, &outlink->in_chlayouts);
230     return 0;
231 }
232
233 static int config_props(AVFilterLink *link)
234 {
235     AVFilterContext *ctx = link->dst;
236     PanContext *pan = ctx->priv;
237     char buf[1024], *cur;
238     int i, j, k, r;
239     double t;
240
241     pan->nb_input_channels = av_get_channel_layout_nb_channels(link->channel_layout);
242     if (pan->need_renumber) {
243         // input channels were given by their name: renumber them
244         for (i = j = 0; i < MAX_CHANNELS; i++) {
245             if ((link->channel_layout >> i) & 1) {
246                 for (k = 0; k < pan->nb_output_channels; k++)
247                     pan->gain[k][j] = pan->gain[k][i];
248                 j++;
249             }
250         }
251     }
252
253     // sanity check; can't be done in query_formats since the inlink
254     // channel layout is unknown at that time
255     if (pan->nb_input_channels > SWR_CH_MAX ||
256         pan->nb_output_channels > SWR_CH_MAX) {
257         av_log(ctx, AV_LOG_ERROR,
258                "libswresample support a maximum of %d channels. "
259                "Feel free to ask for a higher limit.\n", SWR_CH_MAX);
260         return AVERROR_PATCHWELCOME;
261     }
262
263     // init libswresample context
264     pan->swr = swr_alloc_set_opts(pan->swr,
265                                   pan->out_channel_layout, link->format, link->sample_rate,
266                                   link->channel_layout,    link->format, link->sample_rate,
267                                   0, ctx);
268     if (!pan->swr)
269         return AVERROR(ENOMEM);
270
271     // gains are pure, init the channel mapping
272     if (pan->pure_gains) {
273
274         // get channel map from the pure gains
275         for (i = 0; i < pan->nb_output_channels; i++) {
276             int ch_id = -1;
277             for (j = 0; j < pan->nb_input_channels; j++) {
278                 if (pan->gain[i][j]) {
279                     ch_id = j;
280                     break;
281                 }
282             }
283             pan->channel_map[i] = ch_id;
284         }
285
286         av_opt_set_int(pan->swr, "icl", pan->out_channel_layout, 0);
287         av_opt_set_int(pan->swr, "uch", pan->nb_output_channels, 0);
288         swr_set_channel_mapping(pan->swr, pan->channel_map);
289     } else {
290         // renormalize
291         for (i = 0; i < pan->nb_output_channels; i++) {
292             if (!((pan->need_renorm >> i) & 1))
293                 continue;
294             t = 0;
295             for (j = 0; j < pan->nb_input_channels; j++)
296                 t += pan->gain[i][j];
297             if (t > -1E-5 && t < 1E-5) {
298                 // t is almost 0 but not exactly, this is probably a mistake
299                 if (t)
300                     av_log(ctx, AV_LOG_WARNING,
301                            "Degenerate coefficients while renormalizing\n");
302                 continue;
303             }
304             for (j = 0; j < pan->nb_input_channels; j++)
305                 pan->gain[i][j] /= t;
306         }
307         av_opt_set_int(pan->swr, "icl", link->channel_layout, 0);
308         av_opt_set_int(pan->swr, "ocl", pan->out_channel_layout, 0);
309         swr_set_matrix(pan->swr, pan->gain[0], pan->gain[1] - pan->gain[0]);
310     }
311
312     r = swr_init(pan->swr);
313     if (r < 0)
314         return r;
315
316     // summary
317     for (i = 0; i < pan->nb_output_channels; i++) {
318         cur = buf;
319         for (j = 0; j < pan->nb_input_channels; j++) {
320             r = snprintf(cur, buf + sizeof(buf) - cur, "%s%.3g i%d",
321                          j ? " + " : "", pan->gain[i][j], j);
322             cur += FFMIN(buf + sizeof(buf) - cur, r);
323         }
324         av_log(ctx, AV_LOG_INFO, "o%d = %s\n", i, buf);
325     }
326     // add channel mapping summary if possible
327     if (pan->pure_gains) {
328         av_log(ctx, AV_LOG_INFO, "Pure channel mapping detected:");
329         for (i = 0; i < pan->nb_output_channels; i++)
330             if (pan->channel_map[i] < 0)
331                 av_log(ctx, AV_LOG_INFO, " M");
332             else
333                 av_log(ctx, AV_LOG_INFO, " %d", pan->channel_map[i]);
334         av_log(ctx, AV_LOG_INFO, "\n");
335         return 0;
336     }
337     return 0;
338 }
339
340 static void filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
341 {
342     int n = insamples->audio->nb_samples;
343     AVFilterLink *const outlink = inlink->dst->outputs[0];
344     AVFilterBufferRef *outsamples = ff_get_audio_buffer(outlink, AV_PERM_WRITE, n);
345     PanContext *pan = inlink->dst->priv;
346
347     swr_convert(pan->swr, outsamples->data, n, (void *)insamples->data, n);
348     avfilter_copy_buffer_ref_props(outsamples, insamples);
349     outsamples->audio->channel_layout = outlink->channel_layout;
350     outsamples->audio->planar         = outlink->planar;
351
352     ff_filter_samples(outlink, outsamples);
353     avfilter_unref_buffer(insamples);
354 }
355
356 static av_cold void uninit(AVFilterContext *ctx)
357 {
358     PanContext *pan = ctx->priv;
359     swr_free(&pan->swr);
360 }
361
362 AVFilter avfilter_af_pan = {
363     .name          = "pan",
364     .description   = NULL_IF_CONFIG_SMALL("Remix channels with coefficients (panning)."),
365     .priv_size     = sizeof(PanContext),
366     .init          = init,
367     .uninit        = uninit,
368     .query_formats = query_formats,
369
370     .inputs    = (const AVFilterPad[]) {
371         { .name             = "default",
372           .type             = AVMEDIA_TYPE_AUDIO,
373           .config_props     = config_props,
374           .filter_samples   = filter_samples,
375           .min_perms        = AV_PERM_READ, },
376         { .name = NULL}
377     },
378     .outputs   = (const AVFilterPad[]) {
379         { .name             = "default",
380           .type             = AVMEDIA_TYPE_AUDIO, },
381         { .name = NULL}
382     },
383 };