]> 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 "avfilter.h"
34 #include "internal.h"
35
36 #define MAX_CHANNELS 63
37
38 typedef struct {
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 } PanContext;
50
51 static int parse_channel_name(char **arg, int *rchannel, int *rnamed)
52 {
53     char buf[8];
54     int len, i, channel_id;
55     int64_t layout, layout0;
56
57     if (sscanf(*arg, " %7[A-Z] %n", buf, &len)) {
58         layout0 = layout = av_get_channel_layout(buf);
59         for (i = 32; i > 0; i >>= 1) {
60             if (layout >= (int64_t)1 << i) {
61                 channel_id += i;
62                 layout >>= i;
63             }
64         }
65         if (channel_id >= MAX_CHANNELS || layout0 != (int64_t)1 << channel_id)
66             return AVERROR(EINVAL);
67         *rchannel = channel_id;
68         *rnamed = 1;
69         *arg += len;
70         return 0;
71     }
72     if (sscanf(*arg, " c%d %n", &channel_id, &len) &&
73         channel_id >= 0 && channel_id < MAX_CHANNELS) {
74         *rchannel = channel_id;
75         *rnamed = 0;
76         *arg += len;
77         return 0;
78     }
79     return AVERROR(EINVAL);
80 }
81
82 static void skip_spaces(char **arg)
83 {
84     int len = 0;
85
86     sscanf(*arg, " %n", &len);
87     *arg += len;
88 }
89
90 static av_cold int init(AVFilterContext *ctx, const char *args0, void *opaque)
91 {
92     PanContext *const pan = ctx->priv;
93     char *arg, *arg0, *tokenizer, *args = av_strdup(args0);
94     int out_ch_id, in_ch_id, len, named;
95     int nb_in_channels[2] = { 0, 0 }; // number of unnamed and named input channels
96     double gain;
97
98     if (!args)
99         return AVERROR(ENOMEM);
100     arg = av_strtok(args, ":", &tokenizer);
101     pan->out_channel_layout = av_get_channel_layout(arg);
102     if (!pan->out_channel_layout) {
103         av_log(ctx, AV_LOG_ERROR, "Unknown channel layout \"%s\"\n", arg);
104         return AVERROR(EINVAL);
105     }
106     pan->nb_output_channels = av_get_channel_layout_nb_channels(pan->out_channel_layout);
107
108     /* parse channel specifications */
109     while ((arg = arg0 = av_strtok(NULL, ":", &tokenizer))) {
110         /* channel name */
111         if (parse_channel_name(&arg, &out_ch_id, &named)) {
112             av_log(ctx, AV_LOG_ERROR,
113                    "Expected out channel name, got \"%.8s\"\n", arg);
114             return AVERROR(EINVAL);
115         }
116         if (named) {
117             if (!((pan->out_channel_layout >> out_ch_id) & 1)) {
118                 av_log(ctx, AV_LOG_ERROR,
119                        "Channel \"%.8s\" does not exist in the chosen layout\n", arg0);
120                 return AVERROR(EINVAL);
121             }
122             /* get the channel number in the output channel layout:
123              * out_channel_layout & ((1 << out_ch_id) - 1) are all the
124              * channels that come before out_ch_id,
125              * so their count is the index of out_ch_id */
126             out_ch_id = av_get_channel_layout_nb_channels(pan->out_channel_layout & (((int64_t)1 << out_ch_id) - 1));
127         }
128         if (out_ch_id < 0 || out_ch_id >= pan->nb_output_channels) {
129             av_log(ctx, AV_LOG_ERROR,
130                    "Invalid out channel name \"%.8s\"\n", arg0);
131             return AVERROR(EINVAL);
132         }
133         if (*arg == '=') {
134             arg++;
135         } else if (*arg == '<') {
136             pan->need_renorm |= (int64_t)1 << out_ch_id;
137             arg++;
138         } else {
139             av_log(ctx, AV_LOG_ERROR,
140                    "Syntax error after channel name in \"%.8s\"\n", arg0);
141             return AVERROR(EINVAL);
142         }
143         /* gains */
144         while (1) {
145             gain = 1;
146             if (sscanf(arg, " %lf %n* %n", &gain, &len, &len))
147                 arg += len;
148             if (parse_channel_name(&arg, &in_ch_id, &named)){
149                 av_log(ctx, AV_LOG_ERROR,
150                        "Expected in channel name, got \"%.8s\"\n", arg);
151                 return AVERROR(EINVAL);
152             }
153             nb_in_channels[named]++;
154             if (nb_in_channels[!named]) {
155                 av_log(ctx, AV_LOG_ERROR,
156                        "Can not mix named and numbered channels\n");
157                 return AVERROR(EINVAL);
158             }
159             pan->gain.d[out_ch_id][in_ch_id] = gain;
160             if (!*arg)
161                 break;
162             if (*arg != '+') {
163                 av_log(ctx, AV_LOG_ERROR, "Syntax error near \"%.8s\"\n", arg);
164                 return AVERROR(EINVAL);
165             }
166             arg++;
167             skip_spaces(&arg);
168         }
169     }
170     pan->need_renumber = !!nb_in_channels[1];
171
172     av_free(args);
173     return 0;
174 }
175
176 static int query_formats(AVFilterContext *ctx)
177 {
178     PanContext *pan = ctx->priv;
179     AVFilterLink *inlink  = ctx->inputs[0];
180     AVFilterLink *outlink = ctx->outputs[0];
181     AVFilterFormats *formats;
182
183     const enum AVSampleFormat sample_fmts[] = {AV_SAMPLE_FMT_S16, -1};
184     const int                packing_fmts[] = {AVFILTER_PACKED,   -1};
185
186     avfilter_set_common_sample_formats (ctx, avfilter_make_format_list(sample_fmts));
187     avfilter_set_common_packing_formats(ctx, avfilter_make_format_list(packing_fmts));
188
189     // inlink supports any channel layout
190     formats = avfilter_make_all_channel_layouts();
191     avfilter_formats_ref(formats, &inlink->out_chlayouts);
192
193     // outlink supports only requested output channel layout
194     formats = NULL;
195     avfilter_add_format(&formats, pan->out_channel_layout);
196     avfilter_formats_ref(formats, &outlink->in_chlayouts);
197     return 0;
198 }
199
200 static int config_props(AVFilterLink *link)
201 {
202     AVFilterContext *ctx = link->dst;
203     PanContext *pan = ctx->priv;
204     char buf[1024], *cur;
205     int i, j, k, r;
206     double t;
207
208     pan->nb_input_channels = av_get_channel_layout_nb_channels(link->channel_layout);
209     if (pan->need_renumber) {
210         // input channels were given by their name: renumber them
211         for (i = j = 0; i < MAX_CHANNELS; i++) {
212             if ((link->channel_layout >> i) & 1) {
213                 for (k = 0; k < pan->nb_output_channels; k++)
214                     pan->gain.d[k][j] = pan->gain.d[k][i];
215                 j++;
216             }
217         }
218     }
219     // renormalize
220     for (i = 0; i < pan->nb_output_channels; i++) {
221         if (!((pan->need_renorm >> i) & 1))
222             continue;
223         t = 0;
224         for (j = 0; j < pan->nb_input_channels; j++)
225             t += pan->gain.d[i][j];
226         if (t > -1E-5 && t < 1E-5) {
227             // t is almost 0 but not exactly, this is probably a mistake
228             if (t)
229                 av_log(ctx, AV_LOG_WARNING,
230                        "Degenerate coefficients while renormalizing\n");
231             continue;
232         }
233         for (j = 0; j < pan->nb_input_channels; j++)
234             pan->gain.d[i][j] /= t;
235     }
236     // summary
237     for (i = 0; i < pan->nb_output_channels; i++) {
238         cur = buf;
239         for (j = 0; j < pan->nb_input_channels; j++) {
240             r = snprintf(cur, buf + sizeof(buf) - cur, "%s%.3g i%d",
241                          j ? " + " : "", pan->gain.d[i][j], j);
242             cur += FFMIN(buf + sizeof(buf) - cur, r);
243         }
244         av_log(ctx, AV_LOG_INFO, "o%d = %s\n", i, buf);
245     }
246     // convert to integer
247     for (i = 0; i < pan->nb_output_channels; i++) {
248         for (j = 0; j < pan->nb_input_channels; j++) {
249             if (pan->gain.d[i][j] < -128 || pan->gain.d[i][j] > 128)
250                 av_log(ctx, AV_LOG_WARNING,
251                     "Gain #%d->#%d too large, clamped\n", j, i);
252             pan->gain.i[i][j] = av_clipf(pan->gain.d[i][j], -128, 128) * 256.0;
253         }
254     }
255     return 0;
256 }
257
258
259 static void filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
260 {
261     PanContext *const pan = inlink->dst->priv;
262     int i, o, n = insamples->audio->nb_samples;
263
264     /* input */
265     const int16_t *in     = (int16_t *)insamples->data[0];
266     const int16_t *in_end = in + n * pan->nb_input_channels;
267
268     /* output */
269     AVFilterLink *const outlink = inlink->dst->outputs[0];
270     AVFilterBufferRef *outsamples = avfilter_get_audio_buffer(outlink, AV_PERM_WRITE, n);
271     int16_t *out = (int16_t *)outsamples->data[0];
272
273     for (; in < in_end; in += pan->nb_input_channels) {
274         for (o = 0; o < pan->nb_output_channels; o++) {
275             int v = 0;
276             for (i = 0; i < pan->nb_input_channels; i++)
277                 v += pan->gain.i[o][i] * in[i];
278             *(out++) = v >> 8;
279         }
280     }
281
282     avfilter_filter_samples(outlink, outsamples);
283     avfilter_unref_buffer(insamples);
284 }
285
286 AVFilter avfilter_af_pan = {
287     .name          = "pan",
288     .description   = NULL_IF_CONFIG_SMALL("Remix channels with coefficients (panning)"),
289     .priv_size     = sizeof(PanContext),
290     .init          = init,
291     .query_formats = query_formats,
292
293     .inputs    = (const AVFilterPad[]) {
294         { .name             = "default",
295           .type             = AVMEDIA_TYPE_AUDIO,
296           .config_props     = config_props,
297           .filter_samples   = filter_samples,
298           .min_perms        = AV_PERM_READ, },
299         { .name = NULL}
300     },
301     .outputs   = (const AVFilterPad[]) {
302         { .name             = "default",
303           .type             = AVMEDIA_TYPE_AUDIO, },
304         { .name = NULL}
305     },
306 };