]> 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 "audio.h"
35 #include "avfilter.h"
36 #include "formats.h"
37 #include "internal.h"
38
39 #define MAX_CHANNELS 63
40
41 typedef struct PanContext {
42     int64_t out_channel_layout;
43     double gain[MAX_CHANNELS][MAX_CHANNELS];
44     int64_t need_renorm;
45     int need_renumber;
46     int nb_input_channels;
47     int nb_output_channels;
48
49     int pure_gains;
50     /* channel mapping specific */
51     int channel_map[SWR_CH_MAX];
52     struct SwrContext *swr;
53 } PanContext;
54
55 static int parse_channel_name(char **arg, int *rchannel, int *rnamed)
56 {
57     char buf[8];
58     int len, i, channel_id = 0;
59     int64_t layout, layout0;
60
61     /* try to parse a channel name, e.g. "FL" */
62     if (sscanf(*arg, " %7[A-Z] %n", buf, &len)) {
63         layout0 = layout = av_get_channel_layout(buf);
64         /* channel_id <- first set bit in layout */
65         for (i = 32; i > 0; i >>= 1) {
66             if (layout >= (int64_t)1 << i) {
67                 channel_id += i;
68                 layout >>= i;
69             }
70         }
71         /* reject layouts that are not a single channel */
72         if (channel_id >= MAX_CHANNELS || layout0 != (int64_t)1 << channel_id)
73             return AVERROR(EINVAL);
74         *rchannel = channel_id;
75         *rnamed = 1;
76         *arg += len;
77         return 0;
78     }
79     /* try to parse a channel number, e.g. "c2" */
80     if (sscanf(*arg, " c%d %n", &channel_id, &len) &&
81         channel_id >= 0 && channel_id < MAX_CHANNELS) {
82         *rchannel = channel_id;
83         *rnamed = 0;
84         *arg += len;
85         return 0;
86     }
87     return AVERROR(EINVAL);
88 }
89
90 static void skip_spaces(char **arg)
91 {
92     int len = 0;
93
94     sscanf(*arg, " %n", &len);
95     *arg += len;
96 }
97
98 static av_cold int init(AVFilterContext *ctx, const char *args0, void *opaque)
99 {
100     PanContext *const pan = ctx->priv;
101     char *arg, *arg0, *tokenizer, *args = av_strdup(args0);
102     int out_ch_id, in_ch_id, len, named, ret;
103     int nb_in_channels[2] = { 0, 0 }; // number of unnamed and named input channels
104     double gain;
105
106     if (!args0) {
107         av_log(ctx, AV_LOG_ERROR,
108                "pan filter needs a channel layout and a set "
109                "of channels definitions as parameter\n");
110         return AVERROR(EINVAL);
111     }
112     if (!args)
113         return AVERROR(ENOMEM);
114     arg = av_strtok(args, ":", &tokenizer);
115     ret = ff_parse_channel_layout(&pan->out_channel_layout, arg, ctx);
116     if (ret < 0)
117         return ret;
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 = NULL;
216     AVFilterChannelLayouts *layouts;
217
218     pan->pure_gains = are_gains_pure(pan);
219     /* libswr supports any sample and packing formats */
220     avfilter_set_common_sample_formats(ctx, avfilter_make_all_formats(AVMEDIA_TYPE_AUDIO));
221
222     formats = ff_all_samplerates();
223     if (!formats)
224         return AVERROR(ENOMEM);
225     ff_set_common_samplerates(ctx, formats);
226
227     // inlink supports any channel layout
228     layouts = ff_all_channel_layouts();
229     ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
230
231     // outlink supports only requested output channel layout
232     layouts = NULL;
233     ff_add_channel_layout(&layouts, pan->out_channel_layout);
234     ff_channel_layouts_ref(layouts, &outlink->in_channel_layouts);
235     return 0;
236 }
237
238 static int config_props(AVFilterLink *link)
239 {
240     AVFilterContext *ctx = link->dst;
241     PanContext *pan = ctx->priv;
242     char buf[1024], *cur;
243     int i, j, k, r;
244     double t;
245
246     pan->nb_input_channels = av_get_channel_layout_nb_channels(link->channel_layout);
247     if (pan->need_renumber) {
248         // input channels were given by their name: renumber them
249         for (i = j = 0; i < MAX_CHANNELS; i++) {
250             if ((link->channel_layout >> i) & 1) {
251                 for (k = 0; k < pan->nb_output_channels; k++)
252                     pan->gain[k][j] = pan->gain[k][i];
253                 j++;
254             }
255         }
256     }
257
258     // sanity check; can't be done in query_formats since the inlink
259     // channel layout is unknown at that time
260     if (pan->nb_input_channels > SWR_CH_MAX ||
261         pan->nb_output_channels > SWR_CH_MAX) {
262         av_log(ctx, AV_LOG_ERROR,
263                "libswresample support a maximum of %d channels. "
264                "Feel free to ask for a higher limit.\n", SWR_CH_MAX);
265         return AVERROR_PATCHWELCOME;
266     }
267
268     // init libswresample context
269     pan->swr = swr_alloc_set_opts(pan->swr,
270                                   pan->out_channel_layout, link->format, link->sample_rate,
271                                   link->channel_layout,    link->format, link->sample_rate,
272                                   0, ctx);
273     if (!pan->swr)
274         return AVERROR(ENOMEM);
275
276     // gains are pure, init the channel mapping
277     if (pan->pure_gains) {
278
279         // get channel map from the pure gains
280         for (i = 0; i < pan->nb_output_channels; i++) {
281             int ch_id = -1;
282             for (j = 0; j < pan->nb_input_channels; j++) {
283                 if (pan->gain[i][j]) {
284                     ch_id = j;
285                     break;
286                 }
287             }
288             pan->channel_map[i] = ch_id;
289         }
290
291         av_opt_set_int(pan->swr, "icl", pan->out_channel_layout, 0);
292         av_opt_set_int(pan->swr, "uch", pan->nb_output_channels, 0);
293         swr_set_channel_mapping(pan->swr, pan->channel_map);
294     } else {
295         // renormalize
296         for (i = 0; i < pan->nb_output_channels; i++) {
297             if (!((pan->need_renorm >> i) & 1))
298                 continue;
299             t = 0;
300             for (j = 0; j < pan->nb_input_channels; j++)
301                 t += pan->gain[i][j];
302             if (t > -1E-5 && t < 1E-5) {
303                 // t is almost 0 but not exactly, this is probably a mistake
304                 if (t)
305                     av_log(ctx, AV_LOG_WARNING,
306                            "Degenerate coefficients while renormalizing\n");
307                 continue;
308             }
309             for (j = 0; j < pan->nb_input_channels; j++)
310                 pan->gain[i][j] /= t;
311         }
312         av_opt_set_int(pan->swr, "icl", link->channel_layout, 0);
313         av_opt_set_int(pan->swr, "ocl", pan->out_channel_layout, 0);
314         swr_set_matrix(pan->swr, pan->gain[0], pan->gain[1] - pan->gain[0]);
315     }
316
317     r = swr_init(pan->swr);
318     if (r < 0)
319         return r;
320
321     // summary
322     for (i = 0; i < pan->nb_output_channels; i++) {
323         cur = buf;
324         for (j = 0; j < pan->nb_input_channels; j++) {
325             r = snprintf(cur, buf + sizeof(buf) - cur, "%s%.3g i%d",
326                          j ? " + " : "", pan->gain[i][j], j);
327             cur += FFMIN(buf + sizeof(buf) - cur, r);
328         }
329         av_log(ctx, AV_LOG_INFO, "o%d = %s\n", i, buf);
330     }
331     // add channel mapping summary if possible
332     if (pan->pure_gains) {
333         av_log(ctx, AV_LOG_INFO, "Pure channel mapping detected:");
334         for (i = 0; i < pan->nb_output_channels; i++)
335             if (pan->channel_map[i] < 0)
336                 av_log(ctx, AV_LOG_INFO, " M");
337             else
338                 av_log(ctx, AV_LOG_INFO, " %d", pan->channel_map[i]);
339         av_log(ctx, AV_LOG_INFO, "\n");
340         return 0;
341     }
342     return 0;
343 }
344
345 static void filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
346 {
347     int n = insamples->audio->nb_samples;
348     AVFilterLink *const outlink = inlink->dst->outputs[0];
349     AVFilterBufferRef *outsamples = ff_get_audio_buffer(outlink, AV_PERM_WRITE, n);
350     PanContext *pan = inlink->dst->priv;
351
352     swr_convert(pan->swr, outsamples->data, n, (void *)insamples->data, n);
353     avfilter_copy_buffer_ref_props(outsamples, insamples);
354     outsamples->audio->channel_layout = outlink->channel_layout;
355
356     ff_filter_samples(outlink, outsamples);
357     avfilter_unref_buffer(insamples);
358 }
359
360 static av_cold void uninit(AVFilterContext *ctx)
361 {
362     PanContext *pan = ctx->priv;
363     swr_free(&pan->swr);
364 }
365
366 AVFilter avfilter_af_pan = {
367     .name          = "pan",
368     .description   = NULL_IF_CONFIG_SMALL("Remix channels with coefficients (panning)."),
369     .priv_size     = sizeof(PanContext),
370     .init          = init,
371     .uninit        = uninit,
372     .query_formats = query_formats,
373
374     .inputs    = (const AVFilterPad[]) {
375         { .name             = "default",
376           .type             = AVMEDIA_TYPE_AUDIO,
377           .config_props     = config_props,
378           .filter_samples   = filter_samples,
379           .min_perms        = AV_PERM_READ, },
380         { .name = NULL}
381     },
382     .outputs   = (const AVFilterPad[]) {
383         { .name             = "default",
384           .type             = AVMEDIA_TYPE_AUDIO, },
385         { .name = NULL}
386     },
387 };