]> 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/audioconvert.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/opt.h"
34 #include "libswresample/swresample.h"
35 #include "audio.h"
36 #include "avfilter.h"
37 #include "formats.h"
38 #include "internal.h"
39
40 #define MAX_CHANNELS 63
41
42 typedef struct PanContext {
43     int64_t out_channel_layout;
44     double gain[MAX_CHANNELS][MAX_CHANNELS];
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)
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, ret;
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     ret = ff_parse_channel_layout(&pan->out_channel_layout, arg, ctx);
117     if (ret < 0)
118         return ret;
119     pan->nb_output_channels = av_get_channel_layout_nb_channels(pan->out_channel_layout);
120
121     /* parse channel specifications */
122     while ((arg = arg0 = av_strtok(NULL, ":", &tokenizer))) {
123         /* channel name */
124         if (parse_channel_name(&arg, &out_ch_id, &named)) {
125             av_log(ctx, AV_LOG_ERROR,
126                    "Expected out channel name, got \"%.8s\"\n", arg);
127             return AVERROR(EINVAL);
128         }
129         if (named) {
130             if (!((pan->out_channel_layout >> out_ch_id) & 1)) {
131                 av_log(ctx, AV_LOG_ERROR,
132                        "Channel \"%.8s\" does not exist in the chosen layout\n", arg0);
133                 return AVERROR(EINVAL);
134             }
135             /* get the channel number in the output channel layout:
136              * out_channel_layout & ((1 << out_ch_id) - 1) are all the
137              * channels that come before out_ch_id,
138              * so their count is the index of out_ch_id */
139             out_ch_id = av_get_channel_layout_nb_channels(pan->out_channel_layout & (((int64_t)1 << out_ch_id) - 1));
140         }
141         if (out_ch_id < 0 || out_ch_id >= pan->nb_output_channels) {
142             av_log(ctx, AV_LOG_ERROR,
143                    "Invalid out channel name \"%.8s\"\n", arg0);
144             return AVERROR(EINVAL);
145         }
146         if (*arg == '=') {
147             arg++;
148         } else if (*arg == '<') {
149             pan->need_renorm |= (int64_t)1 << out_ch_id;
150             arg++;
151         } else {
152             av_log(ctx, AV_LOG_ERROR,
153                    "Syntax error after channel name in \"%.8s\"\n", arg0);
154             return AVERROR(EINVAL);
155         }
156         /* gains */
157         while (1) {
158             gain = 1;
159             if (sscanf(arg, " %lf %n* %n", &gain, &len, &len))
160                 arg += len;
161             if (parse_channel_name(&arg, &in_ch_id, &named)){
162                 av_log(ctx, AV_LOG_ERROR,
163                        "Expected in channel name, got \"%.8s\"\n", arg);
164                 return AVERROR(EINVAL);
165             }
166             nb_in_channels[named]++;
167             if (nb_in_channels[!named]) {
168                 av_log(ctx, AV_LOG_ERROR,
169                        "Can not mix named and numbered channels\n");
170                 return AVERROR(EINVAL);
171             }
172             pan->gain[out_ch_id][in_ch_id] = gain;
173             if (!*arg)
174                 break;
175             if (*arg != '+') {
176                 av_log(ctx, AV_LOG_ERROR, "Syntax error near \"%.8s\"\n", arg);
177                 return AVERROR(EINVAL);
178             }
179             arg++;
180             skip_spaces(&arg);
181         }
182     }
183     pan->need_renumber = !!nb_in_channels[1];
184
185     av_free(args);
186     return 0;
187 }
188
189 static int are_gains_pure(const PanContext *pan)
190 {
191     int i, j;
192
193     for (i = 0; i < MAX_CHANNELS; i++) {
194         int nb_gain = 0;
195
196         for (j = 0; j < MAX_CHANNELS; j++) {
197             double gain = pan->gain[i][j];
198
199             /* channel mapping is effective only if 0% or 100% of a channel is
200              * selected... */
201             if (gain != 0. && gain != 1.)
202                 return 0;
203             /* ...and if the output channel is only composed of one input */
204             if (gain && nb_gain++)
205                 return 0;
206         }
207     }
208     return 1;
209 }
210
211 static int query_formats(AVFilterContext *ctx)
212 {
213     PanContext *pan = ctx->priv;
214     AVFilterLink *inlink  = ctx->inputs[0];
215     AVFilterLink *outlink = ctx->outputs[0];
216     AVFilterFormats *formats = NULL;
217     AVFilterChannelLayouts *layouts;
218
219     pan->pure_gains = are_gains_pure(pan);
220     /* libswr supports any sample and packing formats */
221     ff_set_common_formats(ctx, ff_all_formats(AVMEDIA_TYPE_AUDIO));
222
223     formats = ff_all_samplerates();
224     if (!formats)
225         return AVERROR(ENOMEM);
226     ff_set_common_samplerates(ctx, formats);
227
228     // inlink supports any channel layout
229     layouts = ff_all_channel_layouts();
230     ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
231
232     // outlink supports only requested output channel layout
233     layouts = NULL;
234     ff_add_channel_layout(&layouts, pan->out_channel_layout);
235     ff_channel_layouts_ref(layouts, &outlink->in_channel_layouts);
236     return 0;
237 }
238
239 static int config_props(AVFilterLink *link)
240 {
241     AVFilterContext *ctx = link->dst;
242     PanContext *pan = ctx->priv;
243     char buf[1024], *cur;
244     int i, j, k, r;
245     double t;
246
247     pan->nb_input_channels = av_get_channel_layout_nb_channels(link->channel_layout);
248     if (pan->need_renumber) {
249         // input channels were given by their name: renumber them
250         for (i = j = 0; i < MAX_CHANNELS; i++) {
251             if ((link->channel_layout >> i) & 1) {
252                 for (k = 0; k < pan->nb_output_channels; k++)
253                     pan->gain[k][j] = pan->gain[k][i];
254                 j++;
255             }
256         }
257     }
258
259     // sanity check; can't be done in query_formats since the inlink
260     // channel layout is unknown at that time
261     if (pan->nb_input_channels > SWR_CH_MAX ||
262         pan->nb_output_channels > SWR_CH_MAX) {
263         av_log(ctx, AV_LOG_ERROR,
264                "libswresample support a maximum of %d channels. "
265                "Feel free to ask for a higher limit.\n", SWR_CH_MAX);
266         return AVERROR_PATCHWELCOME;
267     }
268
269     // init libswresample context
270     pan->swr = swr_alloc_set_opts(pan->swr,
271                                   pan->out_channel_layout, link->format, link->sample_rate,
272                                   link->channel_layout,    link->format, link->sample_rate,
273                                   0, ctx);
274     if (!pan->swr)
275         return AVERROR(ENOMEM);
276
277     // gains are pure, init the channel mapping
278     if (pan->pure_gains) {
279
280         // get channel map from the pure gains
281         for (i = 0; i < pan->nb_output_channels; i++) {
282             int ch_id = -1;
283             for (j = 0; j < pan->nb_input_channels; j++) {
284                 if (pan->gain[i][j]) {
285                     ch_id = j;
286                     break;
287                 }
288             }
289             pan->channel_map[i] = ch_id;
290         }
291
292         av_opt_set_int(pan->swr, "icl", pan->out_channel_layout, 0);
293         av_opt_set_int(pan->swr, "uch", pan->nb_output_channels, 0);
294         swr_set_channel_mapping(pan->swr, pan->channel_map);
295     } else {
296         // renormalize
297         for (i = 0; i < pan->nb_output_channels; i++) {
298             if (!((pan->need_renorm >> i) & 1))
299                 continue;
300             t = 0;
301             for (j = 0; j < pan->nb_input_channels; j++)
302                 t += pan->gain[i][j];
303             if (t > -1E-5 && t < 1E-5) {
304                 // t is almost 0 but not exactly, this is probably a mistake
305                 if (t)
306                     av_log(ctx, AV_LOG_WARNING,
307                            "Degenerate coefficients while renormalizing\n");
308                 continue;
309             }
310             for (j = 0; j < pan->nb_input_channels; j++)
311                 pan->gain[i][j] /= t;
312         }
313         av_opt_set_int(pan->swr, "icl", link->channel_layout, 0);
314         av_opt_set_int(pan->swr, "ocl", pan->out_channel_layout, 0);
315         swr_set_matrix(pan->swr, pan->gain[0], pan->gain[1] - pan->gain[0]);
316     }
317
318     r = swr_init(pan->swr);
319     if (r < 0)
320         return r;
321
322     // summary
323     for (i = 0; i < pan->nb_output_channels; i++) {
324         cur = buf;
325         for (j = 0; j < pan->nb_input_channels; j++) {
326             r = snprintf(cur, buf + sizeof(buf) - cur, "%s%.3g i%d",
327                          j ? " + " : "", pan->gain[i][j], j);
328             cur += FFMIN(buf + sizeof(buf) - cur, r);
329         }
330         av_log(ctx, AV_LOG_VERBOSE, "o%d = %s\n", i, buf);
331     }
332     // add channel mapping summary if possible
333     if (pan->pure_gains) {
334         av_log(ctx, AV_LOG_INFO, "Pure channel mapping detected:");
335         for (i = 0; i < pan->nb_output_channels; i++)
336             if (pan->channel_map[i] < 0)
337                 av_log(ctx, AV_LOG_INFO, " M");
338             else
339                 av_log(ctx, AV_LOG_INFO, " %d", pan->channel_map[i]);
340         av_log(ctx, AV_LOG_INFO, "\n");
341         return 0;
342     }
343     return 0;
344 }
345
346 static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
347 {
348     int ret;
349     int n = insamples->audio->nb_samples;
350     AVFilterLink *const outlink = inlink->dst->outputs[0];
351     AVFilterBufferRef *outsamples = ff_get_audio_buffer(outlink, AV_PERM_WRITE, n);
352     PanContext *pan = inlink->dst->priv;
353
354     swr_convert(pan->swr, outsamples->data, n, (void *)insamples->data, n);
355     avfilter_copy_buffer_ref_props(outsamples, insamples);
356     outsamples->audio->channel_layout = outlink->channel_layout;
357
358     ret = ff_filter_samples(outlink, outsamples);
359     avfilter_unref_buffer(insamples);
360     return ret;
361 }
362
363 static av_cold void uninit(AVFilterContext *ctx)
364 {
365     PanContext *pan = ctx->priv;
366     swr_free(&pan->swr);
367 }
368
369 AVFilter avfilter_af_pan = {
370     .name          = "pan",
371     .description   = NULL_IF_CONFIG_SMALL("Remix channels with coefficients (panning)."),
372     .priv_size     = sizeof(PanContext),
373     .init          = init,
374     .uninit        = uninit,
375     .query_formats = query_formats,
376
377     .inputs    = (const AVFilterPad[]) {
378         { .name             = "default",
379           .type             = AVMEDIA_TYPE_AUDIO,
380           .config_props     = config_props,
381           .filter_samples   = filter_samples,
382           .min_perms        = AV_PERM_READ, },
383         { .name = NULL}
384     },
385     .outputs   = (const AVFilterPad[]) {
386         { .name             = "default",
387           .type             = AVMEDIA_TYPE_AUDIO, },
388         { .name = NULL}
389     },
390 };