FFmpeg
 All Data Structures Namespaces 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 <u pkh me>
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 64
41 
42 typedef struct PanContext {
43  const AVClass *class;
44  char *args;
47  int64_t need_renorm;
50 
52  /* channel mapping specific */
54  struct SwrContext *swr;
55 } PanContext;
56 
57 static void skip_spaces(char **arg)
58 {
59  int len = 0;
60 
61  sscanf(*arg, " %n", &len);
62  *arg += len;
63 }
64 
65 static int parse_channel_name(char **arg, int *rchannel, int *rnamed)
66 {
67  char buf[8];
68  int len, i, channel_id = 0;
69  int64_t layout, layout0;
70 
71  skip_spaces(arg);
72  /* try to parse a channel name, e.g. "FL" */
73  if (sscanf(*arg, "%7[A-Z]%n", buf, &len)) {
74  layout0 = layout = av_get_channel_layout(buf);
75  /* channel_id <- first set bit in layout */
76  for (i = 32; i > 0; i >>= 1) {
77  if (layout >= (int64_t)1 << i) {
78  channel_id += i;
79  layout >>= i;
80  }
81  }
82  /* reject layouts that are not a single channel */
83  if (channel_id >= MAX_CHANNELS || layout0 != (int64_t)1 << channel_id)
84  return AVERROR(EINVAL);
85  *rchannel = channel_id;
86  *rnamed = 1;
87  *arg += len;
88  return 0;
89  }
90  /* try to parse a channel number, e.g. "c2" */
91  if (sscanf(*arg, "c%d%n", &channel_id, &len) &&
92  channel_id >= 0 && channel_id < MAX_CHANNELS) {
93  *rchannel = channel_id;
94  *rnamed = 0;
95  *arg += len;
96  return 0;
97  }
98  return AVERROR(EINVAL);
99 }
100 
102 {
103  PanContext *const pan = ctx->priv;
104  char *arg, *arg0, *tokenizer, *args = av_strdup(pan->args);
105  int out_ch_id, in_ch_id, len, named, ret, sign = 1;
106  int nb_in_channels[2] = { 0, 0 }; // number of unnamed and named input channels
107  double gain;
108 
109  if (!pan->args) {
110  av_log(ctx, AV_LOG_ERROR,
111  "pan filter needs a channel layout and a set "
112  "of channel definitions as parameter\n");
113  return AVERROR(EINVAL);
114  }
115  if (!args)
116  return AVERROR(ENOMEM);
117  arg = av_strtok(args, "|", &tokenizer);
119  &pan->nb_output_channels, arg, ctx);
120  if (ret < 0)
121  goto fail;
122 
123  /* parse channel specifications */
124  while ((arg = arg0 = av_strtok(NULL, "|", &tokenizer))) {
125  /* channel name */
126  if (parse_channel_name(&arg, &out_ch_id, &named)) {
127  av_log(ctx, AV_LOG_ERROR,
128  "Expected out channel name, got \"%.8s\"\n", arg);
129  ret = AVERROR(EINVAL);
130  goto fail;
131  }
132  if (named) {
133  if (!((pan->out_channel_layout >> out_ch_id) & 1)) {
134  av_log(ctx, AV_LOG_ERROR,
135  "Channel \"%.8s\" does not exist in the chosen layout\n", arg0);
136  ret = AVERROR(EINVAL);
137  goto fail;
138  }
139  /* get the channel number in the output channel layout:
140  * out_channel_layout & ((1 << out_ch_id) - 1) are all the
141  * channels that come before out_ch_id,
142  * so their count is the index of out_ch_id */
143  out_ch_id = av_get_channel_layout_nb_channels(pan->out_channel_layout & (((int64_t)1 << out_ch_id) - 1));
144  }
145  if (out_ch_id < 0 || out_ch_id >= pan->nb_output_channels) {
146  av_log(ctx, AV_LOG_ERROR,
147  "Invalid out channel name \"%.8s\"\n", arg0);
148  ret = AVERROR(EINVAL);
149  goto fail;
150  }
151  skip_spaces(&arg);
152  if (*arg == '=') {
153  arg++;
154  } else if (*arg == '<') {
155  pan->need_renorm |= (int64_t)1 << out_ch_id;
156  arg++;
157  } else {
158  av_log(ctx, AV_LOG_ERROR,
159  "Syntax error after channel name in \"%.8s\"\n", arg0);
160  ret = AVERROR(EINVAL);
161  goto fail;
162  }
163  /* gains */
164  while (1) {
165  gain = 1;
166  if (sscanf(arg, "%lf%n *%n", &gain, &len, &len))
167  arg += len;
168  if (parse_channel_name(&arg, &in_ch_id, &named)){
169  av_log(ctx, AV_LOG_ERROR,
170  "Expected in channel name, got \"%.8s\"\n", arg);
171  ret = AVERROR(EINVAL);
172  goto fail;
173  }
174  nb_in_channels[named]++;
175  if (nb_in_channels[!named]) {
176  av_log(ctx, AV_LOG_ERROR,
177  "Can not mix named and numbered channels\n");
178  ret = AVERROR(EINVAL);
179  goto fail;
180  }
181  pan->gain[out_ch_id][in_ch_id] = sign * gain;
182  skip_spaces(&arg);
183  if (!*arg)
184  break;
185  if (*arg == '-') {
186  sign = -1;
187  } else if (*arg != '+') {
188  av_log(ctx, AV_LOG_ERROR, "Syntax error near \"%.8s\"\n", arg);
189  ret = AVERROR(EINVAL);
190  goto fail;
191  } else {
192  sign = 1;
193  }
194  arg++;
195  }
196  }
197  pan->need_renumber = !!nb_in_channels[1];
198 
199  ret = 0;
200 fail:
201  av_free(args);
202  return ret;
203 }
204 
205 static int are_gains_pure(const PanContext *pan)
206 {
207  int i, j;
208 
209  for (i = 0; i < MAX_CHANNELS; i++) {
210  int nb_gain = 0;
211 
212  for (j = 0; j < MAX_CHANNELS; j++) {
213  double gain = pan->gain[i][j];
214 
215  /* channel mapping is effective only if 0% or 100% of a channel is
216  * selected... */
217  if (gain != 0. && gain != 1.)
218  return 0;
219  /* ...and if the output channel is only composed of one input */
220  if (gain && nb_gain++)
221  return 0;
222  }
223  }
224  return 1;
225 }
226 
228 {
229  PanContext *pan = ctx->priv;
230  AVFilterLink *inlink = ctx->inputs[0];
231  AVFilterLink *outlink = ctx->outputs[0];
234  int ret;
235 
236  pan->pure_gains = are_gains_pure(pan);
237  /* libswr supports any sample and packing formats */
239  return ret;
240 
241  formats = ff_all_samplerates();
242  if ((ret = ff_set_common_samplerates(ctx, formats)) < 0)
243  return ret;
244 
245  // inlink supports any channel layout
246  layouts = ff_all_channel_counts();
247  if ((ret = ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts)) < 0)
248  return ret;
249 
250  // outlink supports only requested output channel layout
251  layouts = NULL;
252  if ((ret = ff_add_channel_layout(&layouts,
255  return ret;
256  return ff_channel_layouts_ref(layouts, &outlink->in_channel_layouts);
257 }
258 
259 static int config_props(AVFilterLink *link)
260 {
261  AVFilterContext *ctx = link->dst;
262  PanContext *pan = ctx->priv;
263  char buf[1024], *cur;
264  int i, j, k, r;
265  double t;
266 
267  if (pan->need_renumber) {
268  // input channels were given by their name: renumber them
269  for (i = j = 0; i < MAX_CHANNELS; i++) {
270  if ((link->channel_layout >> i) & 1) {
271  for (k = 0; k < pan->nb_output_channels; k++)
272  pan->gain[k][j] = pan->gain[k][i];
273  j++;
274  }
275  }
276  }
277 
278  // sanity check; can't be done in query_formats since the inlink
279  // channel layout is unknown at that time
280  if (link->channels > MAX_CHANNELS ||
282  av_log(ctx, AV_LOG_ERROR,
283  "af_pan supports a maximum of %d channels. "
284  "Feel free to ask for a higher limit.\n", MAX_CHANNELS);
285  return AVERROR_PATCHWELCOME;
286  }
287 
288  // init libswresample context
289  pan->swr = swr_alloc_set_opts(pan->swr,
290  pan->out_channel_layout, link->format, link->sample_rate,
291  link->channel_layout, link->format, link->sample_rate,
292  0, ctx);
293  if (!pan->swr)
294  return AVERROR(ENOMEM);
295  if (!link->channel_layout) {
296  if (av_opt_set_int(pan->swr, "ich", link->channels, 0) < 0)
297  return AVERROR(EINVAL);
298  }
299  if (!pan->out_channel_layout) {
300  if (av_opt_set_int(pan->swr, "och", pan->nb_output_channels, 0) < 0)
301  return AVERROR(EINVAL);
302  }
303 
304  // gains are pure, init the channel mapping
305  if (pan->pure_gains) {
306 
307  // get channel map from the pure gains
308  for (i = 0; i < pan->nb_output_channels; i++) {
309  int ch_id = -1;
310  for (j = 0; j < link->channels; j++) {
311  if (pan->gain[i][j]) {
312  ch_id = j;
313  break;
314  }
315  }
316  pan->channel_map[i] = ch_id;
317  }
318 
319  av_opt_set_int(pan->swr, "icl", pan->out_channel_layout, 0);
320  av_opt_set_int(pan->swr, "uch", pan->nb_output_channels, 0);
322  } else {
323  // renormalize
324  for (i = 0; i < pan->nb_output_channels; i++) {
325  if (!((pan->need_renorm >> i) & 1))
326  continue;
327  t = 0;
328  for (j = 0; j < link->channels; j++)
329  t += fabs(pan->gain[i][j]);
330  if (t > -1E-5 && t < 1E-5) {
331  // t is almost 0 but not exactly, this is probably a mistake
332  if (t)
333  av_log(ctx, AV_LOG_WARNING,
334  "Degenerate coefficients while renormalizing\n");
335  continue;
336  }
337  for (j = 0; j < link->channels; j++)
338  pan->gain[i][j] /= t;
339  }
340  av_opt_set_int(pan->swr, "icl", link->channel_layout, 0);
341  av_opt_set_int(pan->swr, "ocl", pan->out_channel_layout, 0);
342  swr_set_matrix(pan->swr, pan->gain[0], pan->gain[1] - pan->gain[0]);
343  }
344 
345  r = swr_init(pan->swr);
346  if (r < 0)
347  return r;
348 
349  // summary
350  for (i = 0; i < pan->nb_output_channels; i++) {
351  cur = buf;
352  for (j = 0; j < link->channels; j++) {
353  r = snprintf(cur, buf + sizeof(buf) - cur, "%s%.3g i%d",
354  j ? " + " : "", pan->gain[i][j], j);
355  cur += FFMIN(buf + sizeof(buf) - cur, r);
356  }
357  av_log(ctx, AV_LOG_VERBOSE, "o%d = %s\n", i, buf);
358  }
359  // add channel mapping summary if possible
360  if (pan->pure_gains) {
361  av_log(ctx, AV_LOG_INFO, "Pure channel mapping detected:");
362  for (i = 0; i < pan->nb_output_channels; i++)
363  if (pan->channel_map[i] < 0)
364  av_log(ctx, AV_LOG_INFO, " M");
365  else
366  av_log(ctx, AV_LOG_INFO, " %d", pan->channel_map[i]);
367  av_log(ctx, AV_LOG_INFO, "\n");
368  return 0;
369  }
370  return 0;
371 }
372 
373 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
374 {
375  int ret;
376  int n = insamples->nb_samples;
377  AVFilterLink *const outlink = inlink->dst->outputs[0];
378  AVFrame *outsamples = ff_get_audio_buffer(outlink, n);
379  PanContext *pan = inlink->dst->priv;
380 
381  if (!outsamples)
382  return AVERROR(ENOMEM);
383  swr_convert(pan->swr, outsamples->extended_data, n,
384  (void *)insamples->extended_data, n);
385  av_frame_copy_props(outsamples, insamples);
386  outsamples->channel_layout = outlink->channel_layout;
387  av_frame_set_channels(outsamples, outlink->channels);
388 
389  ret = ff_filter_frame(outlink, outsamples);
390  av_frame_free(&insamples);
391  return ret;
392 }
393 
395 {
396  PanContext *pan = ctx->priv;
397  swr_free(&pan->swr);
398 }
399 
400 #define OFFSET(x) offsetof(PanContext, x)
401 
402 static const AVOption pan_options[] = {
403  { "args", NULL, OFFSET(args), AV_OPT_TYPE_STRING, { .str = NULL }, CHAR_MIN, CHAR_MAX, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_FILTERING_PARAM },
404  { NULL }
405 };
406 
408 
409 static const AVFilterPad pan_inputs[] = {
410  {
411  .name = "default",
412  .type = AVMEDIA_TYPE_AUDIO,
413  .config_props = config_props,
414  .filter_frame = filter_frame,
415  },
416  { NULL }
417 };
418 
419 static const AVFilterPad pan_outputs[] = {
420  {
421  .name = "default",
422  .type = AVMEDIA_TYPE_AUDIO,
423  },
424  { NULL }
425 };
426 
428  .name = "pan",
429  .description = NULL_IF_CONFIG_SMALL("Remix channels with coefficients (panning)."),
430  .priv_size = sizeof(PanContext),
431  .priv_class = &pan_class,
432  .init = init,
433  .uninit = uninit,
435  .inputs = pan_inputs,
436  .outputs = pan_outputs,
437 };
void av_frame_set_channels(AVFrame *frame, int val)
#define NULL
Definition: coverity.c:32
char * args
Definition: af_pan.c:44
#define MAX_CHANNELS
Definition: af_pan.c:40
double gain[MAX_CHANNELS][MAX_CHANNELS]
Definition: af_pan.c:46
This structure describes decoded (raw) audio or video data.
Definition: frame.h:190
AVOption.
Definition: opt.h:246
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
Main libavfilter public API header.
#define AV_OPT_FLAG_AUDIO_PARAM
Definition: opt.h:281
static enum AVSampleFormat formats[]
Definition: avresample.c:163
static int config_props(AVFilterLink *link)
Definition: af_pan.c:259
int av_get_channel_layout_nb_channels(uint64_t channel_layout)
Return the number of channels in the channel layout.
static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
Definition: af_pan.c:373
const char * name
Pad name.
Definition: internal.h:59
uint64_t av_get_channel_layout(const char *name)
Return a channel layout id that matches name, or 0 if no match is found.
AVFilterLink ** inputs
array of pointers to input links
Definition: avfilter.h:315
int ff_channel_layouts_ref(AVFilterChannelLayouts *f, AVFilterChannelLayouts **ref)
Add *ref as a new reference to f.
Definition: formats.c:435
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:1189
#define av_cold
Definition: attributes.h:82
AVOptions.
int need_renumber
Definition: af_pan.c:48
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
#define av_log(a,...)
AVFilterFormats * ff_all_formats(enum AVMediaType type)
Return a list of all formats supported by FFmpeg for the given media type.
Definition: formats.c:350
static const AVFilterPad pan_inputs[]
Definition: af_pan.c:409
static const AVOption pan_options[]
Definition: af_pan.c:402
A filter pad used for either input or output.
Definition: internal.h:53
libswresample public header
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
int ff_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats)
A helper for query_formats() which sets all links to the same list of formats.
Definition: formats.c:568
int ff_add_channel_layout(AVFilterChannelLayouts **l, uint64_t channel_layout)
Definition: formats.c:343
AVFrame * ff_get_audio_buffer(AVFilterLink *link, int nb_samples)
Request an audio samples buffer with a specific set of permissions.
Definition: audio.c:64
#define AV_OPT_FLAG_FILTERING_PARAM
a generic parameter which can be set by the user for filtering
Definition: opt.h:293
#define AVERROR(e)
Definition: error.h:43
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:158
The libswresample context.
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:176
const char * r
Definition: vf_curves.c:111
void * priv
private data for use by the filter
Definition: avfilter.h:322
int ff_parse_channel_layout(int64_t *ret, int *nret, const char *arg, void *log_ctx)
Parse a channel layout or a corresponding integer representation.
Definition: formats.c:662
static int query_formats(AVFilterContext *ctx)
Definition: af_pan.c:227
const char * arg
Definition: jacosubdec.c:66
int av_opt_set_int(void *obj, const char *name, int64_t val, int search_flags)
Definition: opt.c:560
struct SwrContext * swr
Definition: af_pan.c:54
#define fail()
Definition: checkasm.h:84
static int are_gains_pure(const PanContext *pan)
Definition: af_pan.c:205
uint64_t channel_layout
Channel layout of the audio data.
Definition: frame.h:359
audio channel layout utility functions
#define E
Definition: avdct.c:32
#define FFMIN(a, b)
Definition: common.h:96
int swr_set_matrix(struct SwrContext *s, const double *matrix, int stride)
Set a customized remix matrix.
Definition: rematrix.c:64
int pure_gains
Definition: af_pan.c:51
static void skip_spaces(char **arg)
Definition: af_pan.c:57
AVFormatContext * ctx
Definition: movenc.c:48
struct SwrContext * swr_alloc_set_opts(struct SwrContext *s, int64_t out_ch_layout, enum AVSampleFormat out_sample_fmt, int out_sample_rate, int64_t in_ch_layout, enum AVSampleFormat in_sample_fmt, int in_sample_rate, int log_offset, void *log_ctx)
Allocate SwrContext if needed and set/reset common parameters.
Definition: swresample.c:59
AVFilter ff_af_pan
Definition: af_pan.c:427
int n
Definition: avisynth_c.h:684
static const AVFilterPad outputs[]
Definition: af_afftfilt.c:386
A list of supported channel layouts.
Definition: formats.h:85
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
int64_t out_channel_layout
Definition: af_pan.c:45
#define AV_LOG_INFO
Standard information.
Definition: log.h:187
static const AVFilterPad inputs[]
Definition: af_afftfilt.c:376
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:267
av_cold void swr_free(SwrContext **ss)
Free the given SwrContext and set the pointer to NULL.
Definition: swresample.c:140
void * buf
Definition: avisynth_c.h:690
int swr_set_channel_mapping(struct SwrContext *s, const int *channel_map)
Set a customized input channel mapping.
Definition: swresample.c:52
Describe the class of an AVClass context structure.
Definition: log.h:67
Filter definition.
Definition: avfilter.h:144
#define OFFSET(x)
Definition: af_pan.c:400
int64_t need_renorm
Definition: af_pan.c:47
int channel_map[MAX_CHANNELS]
Definition: af_pan.c:53
const char * name
Filter name.
Definition: avfilter.h:148
#define snprintf
Definition: snprintf.h:34
int attribute_align_arg swr_convert(struct SwrContext *s, uint8_t *out_arg[SWR_CH_MAX], int out_count, const uint8_t *in_arg[SWR_CH_MAX], int in_count)
Definition: swresample.c:707
AVFilterLink ** outputs
array of pointers to output links
Definition: avfilter.h:319
enum MovChannelLayoutTag * layouts
Definition: mov_chan.c:434
AVFilterFormats * ff_all_samplerates(void)
Definition: formats.c:395
AVFILTER_DEFINE_CLASS(pan)
char * av_strtok(char *s, const char *delim, char **saveptr)
Split the string into several tokens which can be accessed by successive calls to av_strtok()...
Definition: avstring.c:184
static int parse_channel_name(char **arg, int *rchannel, int *rnamed)
Definition: af_pan.c:65
#define av_free(p)
int len
static av_cold int init(AVFilterContext *ctx)
Definition: af_pan.c:101
A list of supported formats for one end of a filter link.
Definition: formats.h:64
uint64_t layout
An instance of a filter.
Definition: avfilter.h:307
#define FF_COUNT2LAYOUT(c)
Encode a channel count as a channel layout.
Definition: formats.h:102
internal API functions
AVFilterChannelLayouts * ff_all_channel_counts(void)
Construct an AVFilterChannelLayouts coding for any channel layout, with known or unknown disposition...
Definition: formats.c:410
uint8_t ** extended_data
pointers to the data planes/channels.
Definition: frame.h:237
int nb_samples
number of audio samples (per channel) described by this frame
Definition: frame.h:247
static av_cold void uninit(AVFilterContext *ctx)
Definition: af_pan.c:394
int ff_set_common_samplerates(AVFilterContext *ctx, AVFilterFormats *samplerates)
Definition: formats.c:556
int av_frame_copy_props(AVFrame *dst, const AVFrame *src)
Copy only "metadata" fields from src to dst.
Definition: frame.c:591
av_cold int swr_init(struct SwrContext *s)
Initialize context after user parameters have been set.
Definition: swresample.c:155
static const AVFilterPad pan_outputs[]
Definition: af_pan.c:419
int nb_output_channels
Definition: af_pan.c:49