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