libavfilter/af_pan.c
1fbf7165
 /*
  * Copyright (c) 2002 Anders Johansson <ajh@atri.curtin.edu.au>
493ebbd7
  * Copyright (c) 2011 Clément Bœsch <u pkh me>
1fbf7165
  * Copyright (c) 2011 Nicolas George <nicolas.george@normalesup.org>
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
752344da
  * GNU Lesser General Public License for more details.
1fbf7165
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
  * @file
  * Audio panning filter (channels mixing)
  * Original code written by Anders Johansson for MPlayer,
  * reimplemented for FFmpeg.
  */
 
 #include <stdio.h>
 #include "libavutil/avstring.h"
1acd2f6b
 #include "libavutil/channel_layout.h"
6728dd37
 #include "libavutil/opt.h"
 #include "libswresample/swresample.h"
4522df52
 #include "audio.h"
1fbf7165
 #include "avfilter.h"
1cbf7fb4
 #include "formats.h"
48f30595
 #include "internal.h"
1fbf7165
 
ed5d62e5
 #define MAX_CHANNELS 64
1fbf7165
 
6728dd37
 typedef struct PanContext {
3c821e75
     const AVClass *class;
     char *args;
1fbf7165
     int64_t out_channel_layout;
4217dfe8
     double gain[MAX_CHANNELS][MAX_CHANNELS];
1fbf7165
     int64_t need_renorm;
     int need_renumber;
     int nb_output_channels;
6728dd37
 
     int pure_gains;
     /* channel mapping specific */
ce1bb4b7
     int channel_map[MAX_CHANNELS];
6728dd37
     struct SwrContext *swr;
1fbf7165
 } PanContext;
 
80116b6e
 static void skip_spaces(char **arg)
 {
     int len = 0;
 
     sscanf(*arg, " %n", &len);
     *arg += len;
 }
 
1fbf7165
 static int parse_channel_name(char **arg, int *rchannel, int *rnamed)
 {
     char buf[8];
cba4e2cb
     int len, i, channel_id = 0;
1fbf7165
     int64_t layout, layout0;
 
80116b6e
     skip_spaces(arg);
bd5080b1
     /* try to parse a channel name, e.g. "FL" */
80116b6e
     if (sscanf(*arg, "%7[A-Z]%n", buf, &len)) {
1fbf7165
         layout0 = layout = av_get_channel_layout(buf);
bd5080b1
         /* channel_id <- first set bit in layout */
1fbf7165
         for (i = 32; i > 0; i >>= 1) {
             if (layout >= (int64_t)1 << i) {
                 channel_id += i;
                 layout >>= i;
             }
         }
bd5080b1
         /* reject layouts that are not a single channel */
1fbf7165
         if (channel_id >= MAX_CHANNELS || layout0 != (int64_t)1 << channel_id)
             return AVERROR(EINVAL);
         *rchannel = channel_id;
         *rnamed = 1;
         *arg += len;
         return 0;
     }
bd5080b1
     /* try to parse a channel number, e.g. "c2" */
e3a1eb9e
     if (sscanf(*arg, "c%d%n", &channel_id, &len) &&
1fbf7165
         channel_id >= 0 && channel_id < MAX_CHANNELS) {
         *rchannel = channel_id;
         *rnamed = 0;
         *arg += len;
         return 0;
     }
     return AVERROR(EINVAL);
 }
 
fd6228e6
 static av_cold int init(AVFilterContext *ctx)
1fbf7165
 {
     PanContext *const pan = ctx->priv;
3c821e75
     char *arg, *arg0, *tokenizer, *args = av_strdup(pan->args);
48f30595
     int out_ch_id, in_ch_id, len, named, ret;
1fbf7165
     int nb_in_channels[2] = { 0, 0 }; // number of unnamed and named input channels
     double gain;
 
3c821e75
     if (!pan->args) {
66fdbcbb
         av_log(ctx, AV_LOG_ERROR,
                "pan filter needs a channel layout and a set "
b480ca4d
                "of channel definitions as parameter\n");
66fdbcbb
         return AVERROR(EINVAL);
     }
1fbf7165
     if (!args)
         return AVERROR(ENOMEM);
3c821e75
     arg = av_strtok(args, "|", &tokenizer);
4e9adc9b
     ret = ff_parse_channel_layout(&pan->out_channel_layout,
                                   &pan->nb_output_channels, arg, ctx);
48f30595
     if (ret < 0)
d2a618ab
         goto fail;
1fbf7165
 
     /* parse channel specifications */
3c821e75
     while ((arg = arg0 = av_strtok(NULL, "|", &tokenizer))) {
1fbf7165
         /* channel name */
         if (parse_channel_name(&arg, &out_ch_id, &named)) {
             av_log(ctx, AV_LOG_ERROR,
                    "Expected out channel name, got \"%.8s\"\n", arg);
d2a618ab
             ret = AVERROR(EINVAL);
             goto fail;
1fbf7165
         }
         if (named) {
             if (!((pan->out_channel_layout >> out_ch_id) & 1)) {
                 av_log(ctx, AV_LOG_ERROR,
                        "Channel \"%.8s\" does not exist in the chosen layout\n", arg0);
d2a618ab
                 ret = AVERROR(EINVAL);
                 goto fail;
1fbf7165
             }
             /* get the channel number in the output channel layout:
              * out_channel_layout & ((1 << out_ch_id) - 1) are all the
              * channels that come before out_ch_id,
              * so their count is the index of out_ch_id */
             out_ch_id = av_get_channel_layout_nb_channels(pan->out_channel_layout & (((int64_t)1 << out_ch_id) - 1));
         }
         if (out_ch_id < 0 || out_ch_id >= pan->nb_output_channels) {
             av_log(ctx, AV_LOG_ERROR,
                    "Invalid out channel name \"%.8s\"\n", arg0);
d2a618ab
             ret = AVERROR(EINVAL);
             goto fail;
1fbf7165
         }
e3a1eb9e
         skip_spaces(&arg);
1fbf7165
         if (*arg == '=') {
             arg++;
         } else if (*arg == '<') {
             pan->need_renorm |= (int64_t)1 << out_ch_id;
             arg++;
         } else {
             av_log(ctx, AV_LOG_ERROR,
                    "Syntax error after channel name in \"%.8s\"\n", arg0);
d2a618ab
             ret = AVERROR(EINVAL);
             goto fail;
1fbf7165
         }
         /* gains */
         while (1) {
             gain = 1;
e3a1eb9e
             if (sscanf(arg, "%lf%n *%n", &gain, &len, &len))
1fbf7165
                 arg += len;
             if (parse_channel_name(&arg, &in_ch_id, &named)){
                 av_log(ctx, AV_LOG_ERROR,
                        "Expected in channel name, got \"%.8s\"\n", arg);
d2a618ab
                  ret = AVERROR(EINVAL);
                  goto fail;
1fbf7165
             }
             nb_in_channels[named]++;
             if (nb_in_channels[!named]) {
                 av_log(ctx, AV_LOG_ERROR,
                        "Can not mix named and numbered channels\n");
d2a618ab
                 ret = AVERROR(EINVAL);
                 goto fail;
1fbf7165
             }
4217dfe8
             pan->gain[out_ch_id][in_ch_id] = gain;
e3a1eb9e
             skip_spaces(&arg);
1fbf7165
             if (!*arg)
                 break;
             if (*arg != '+') {
                 av_log(ctx, AV_LOG_ERROR, "Syntax error near \"%.8s\"\n", arg);
d2a618ab
                 ret = AVERROR(EINVAL);
                 goto fail;
1fbf7165
             }
             arg++;
         }
     }
     pan->need_renumber = !!nb_in_channels[1];
 
d2a618ab
     ret = 0;
 fail:
1fbf7165
     av_free(args);
d2a618ab
     return ret;
1fbf7165
 }
 
6728dd37
 static int are_gains_pure(const PanContext *pan)
 {
     int i, j;
 
     for (i = 0; i < MAX_CHANNELS; i++) {
         int nb_gain = 0;
 
         for (j = 0; j < MAX_CHANNELS; j++) {
4217dfe8
             double gain = pan->gain[i][j];
6728dd37
 
             /* channel mapping is effective only if 0% or 100% of a channel is
              * selected... */
             if (gain != 0. && gain != 1.)
                 return 0;
             /* ...and if the output channel is only composed of one input */
             if (gain && nb_gain++)
                 return 0;
         }
     }
     return 1;
 }
 
a923b6b8
 static int query_formats(AVFilterContext *ctx)
 {
     PanContext *pan = ctx->priv;
     AVFilterLink *inlink  = ctx->inputs[0];
     AVFilterLink *outlink = ctx->outputs[0];
5dbd6639
     AVFilterFormats *formats = NULL;
1cbf7fb4
     AVFilterChannelLayouts *layouts;
a923b6b8
 
     pan->pure_gains = are_gains_pure(pan);
     /* libswr supports any sample and packing formats */
1c600888
     ff_set_common_formats(ctx, ff_all_formats(AVMEDIA_TYPE_AUDIO));
a923b6b8
 
5dbd6639
     formats = ff_all_samplerates();
     if (!formats)
         return AVERROR(ENOMEM);
     ff_set_common_samplerates(ctx, formats);
 
a923b6b8
     // inlink supports any channel layout
7b0a5873
     layouts = ff_all_channel_counts();
1cbf7fb4
     ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
a923b6b8
 
     // outlink supports only requested output channel layout
1cbf7fb4
     layouts = NULL;
4e9adc9b
     ff_add_channel_layout(&layouts,
                           pan->out_channel_layout ? pan->out_channel_layout :
                           FF_COUNT2LAYOUT(pan->nb_output_channels));
1cbf7fb4
     ff_channel_layouts_ref(layouts, &outlink->in_channel_layouts);
a923b6b8
     return 0;
 }
 
1fbf7165
 static int config_props(AVFilterLink *link)
 {
     AVFilterContext *ctx = link->dst;
     PanContext *pan = ctx->priv;
     char buf[1024], *cur;
     int i, j, k, r;
     double t;
 
     if (pan->need_renumber) {
         // input channels were given by their name: renumber them
         for (i = j = 0; i < MAX_CHANNELS; i++) {
             if ((link->channel_layout >> i) & 1) {
                 for (k = 0; k < pan->nb_output_channels; k++)
4217dfe8
                     pan->gain[k][j] = pan->gain[k][i];
1fbf7165
                 j++;
             }
         }
     }
6728dd37
 
a297856b
     // sanity check; can't be done in query_formats since the inlink
     // channel layout is unknown at that time
ce1bb4b7
     if (link->channels > MAX_CHANNELS ||
         pan->nb_output_channels > MAX_CHANNELS) {
a297856b
         av_log(ctx, AV_LOG_ERROR,
b480ca4d
                "af_pan supports a maximum of %d channels. "
ce1bb4b7
                "Feel free to ask for a higher limit.\n", MAX_CHANNELS);
a297856b
         return AVERROR_PATCHWELCOME;
     }
6728dd37
 
a297856b
     // init libswresample context
     pan->swr = swr_alloc_set_opts(pan->swr,
                                   pan->out_channel_layout, link->format, link->sample_rate,
                                   link->channel_layout,    link->format, link->sample_rate,
                                   0, ctx);
     if (!pan->swr)
         return AVERROR(ENOMEM);
ced765ce
     if (!link->channel_layout) {
         if (av_opt_set_int(pan->swr, "ich", link->channels, 0) < 0)
             return AVERROR(EINVAL);
     }
     if (!pan->out_channel_layout) {
         if (av_opt_set_int(pan->swr, "och", pan->nb_output_channels, 0) < 0)
             return AVERROR(EINVAL);
     }
a44b510d
 
     // gains are pure, init the channel mapping
     if (pan->pure_gains) {
 
6728dd37
         // get channel map from the pure gains
         for (i = 0; i < pan->nb_output_channels; i++) {
             int ch_id = -1;
7b0a5873
             for (j = 0; j < link->channels; j++) {
4217dfe8
                 if (pan->gain[i][j]) {
6728dd37
                     ch_id = j;
                     break;
                 }
             }
             pan->channel_map[i] = ch_id;
         }
 
         av_opt_set_int(pan->swr, "icl", pan->out_channel_layout, 0);
         av_opt_set_int(pan->swr, "uch", pan->nb_output_channels, 0);
         swr_set_channel_mapping(pan->swr, pan->channel_map);
     } else {
94dc4a50
         // renormalize
         for (i = 0; i < pan->nb_output_channels; i++) {
             if (!((pan->need_renorm >> i) & 1))
                 continue;
             t = 0;
7b0a5873
             for (j = 0; j < link->channels; j++)
4217dfe8
                 t += pan->gain[i][j];
94dc4a50
             if (t > -1E-5 && t < 1E-5) {
                 // t is almost 0 but not exactly, this is probably a mistake
                 if (t)
                     av_log(ctx, AV_LOG_WARNING,
                            "Degenerate coefficients while renormalizing\n");
                 continue;
             }
7b0a5873
             for (j = 0; j < link->channels; j++)
4217dfe8
                 pan->gain[i][j] /= t;
1fbf7165
         }
a44b510d
         av_opt_set_int(pan->swr, "icl", link->channel_layout, 0);
         av_opt_set_int(pan->swr, "ocl", pan->out_channel_layout, 0);
4217dfe8
         swr_set_matrix(pan->swr, pan->gain[0], pan->gain[1] - pan->gain[0]);
6728dd37
     }
a44b510d
 
     r = swr_init(pan->swr);
     if (r < 0)
         return r;
 
1fbf7165
     // summary
     for (i = 0; i < pan->nb_output_channels; i++) {
         cur = buf;
7b0a5873
         for (j = 0; j < link->channels; j++) {
1fbf7165
             r = snprintf(cur, buf + sizeof(buf) - cur, "%s%.3g i%d",
4217dfe8
                          j ? " + " : "", pan->gain[i][j], j);
1fbf7165
             cur += FFMIN(buf + sizeof(buf) - cur, r);
         }
fda968aa
         av_log(ctx, AV_LOG_VERBOSE, "o%d = %s\n", i, buf);
1fbf7165
     }
6728dd37
     // add channel mapping summary if possible
     if (pan->pure_gains) {
         av_log(ctx, AV_LOG_INFO, "Pure channel mapping detected:");
         for (i = 0; i < pan->nb_output_channels; i++)
             if (pan->channel_map[i] < 0)
                 av_log(ctx, AV_LOG_INFO, " M");
             else
                 av_log(ctx, AV_LOG_INFO, " %d", pan->channel_map[i]);
         av_log(ctx, AV_LOG_INFO, "\n");
         return 0;
     }
1fbf7165
     return 0;
 }
 
a05a44e2
 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
6728dd37
 {
f8911b98
     int ret;
a05a44e2
     int n = insamples->nb_samples;
6728dd37
     AVFilterLink *const outlink = inlink->dst->outputs[0];
a05a44e2
     AVFrame *outsamples = ff_get_audio_buffer(outlink, n);
6728dd37
     PanContext *pan = inlink->dst->priv;
 
ed8373e7
     if (!outsamples)
         return AVERROR(ENOMEM);
6c27aea8
     swr_convert(pan->swr, outsamples->extended_data, n,
                 (void *)insamples->extended_data, n);
a05a44e2
     av_frame_copy_props(outsamples, insamples);
     outsamples->channel_layout = outlink->channel_layout;
cd5f50a2
     av_frame_set_channels(outsamples, outlink->channels);
85c66793
 
cd7febd3
     ret = ff_filter_frame(outlink, outsamples);
a05a44e2
     av_frame_free(&insamples);
f8911b98
     return ret;
1fbf7165
 }
 
6728dd37
 static av_cold void uninit(AVFilterContext *ctx)
 {
     PanContext *pan = ctx->priv;
     swr_free(&pan->swr);
 }
 
3c821e75
 #define OFFSET(x) offsetof(PanContext, x)
 
 static const AVOption pan_options[] = {
     { "args", NULL, OFFSET(args), AV_OPT_TYPE_STRING, { .str = NULL }, CHAR_MIN, CHAR_MAX, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_FILTERING_PARAM },
     { NULL }
 };
 
 AVFILTER_DEFINE_CLASS(pan);
 
2d9d4440
 static const AVFilterPad pan_inputs[] = {
     {
         .name         = "default",
         .type         = AVMEDIA_TYPE_AUDIO,
         .config_props = config_props,
         .filter_frame = filter_frame,
     },
     { NULL }
 };
 
 static const AVFilterPad pan_outputs[] = {
     {
         .name = "default",
         .type = AVMEDIA_TYPE_AUDIO,
     },
     { NULL }
 };
 
325f6e0a
 AVFilter ff_af_pan = {
1fbf7165
     .name          = "pan",
9d35fa43
     .description   = NULL_IF_CONFIG_SMALL("Remix channels with coefficients (panning)."),
1fbf7165
     .priv_size     = sizeof(PanContext),
3c821e75
     .priv_class    = &pan_class,
1fbf7165
     .init          = init,
6728dd37
     .uninit        = uninit,
1fbf7165
     .query_formats = query_formats,
2d9d4440
     .inputs        = pan_inputs,
     .outputs       = pan_outputs,
1fbf7165
 };