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