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