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