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