FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
af_compand.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 1999 Chris Bagwell
3  * Copyright (c) 1999 Nick Bailey
4  * Copyright (c) 2007 Rob Sykes <robs@users.sourceforge.net>
5  * Copyright (c) 2013 Paul B Mahol
6  * Copyright (c) 2014 Andrew Kelley
7  *
8  * This file is part of FFmpeg.
9  *
10  * FFmpeg is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * FFmpeg is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with FFmpeg; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23  */
24 
25 /**
26  * @file
27  * audio compand filter
28  */
29 
30 #include "libavutil/avassert.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/samplefmt.h"
34 #include "audio.h"
35 #include "avfilter.h"
36 #include "internal.h"
37 
38 typedef struct ChanParam {
39  double attack;
40  double decay;
41  double volume;
42 } ChanParam;
43 
44 typedef struct CompandSegment {
45  double x, y;
46  double a, b;
48 
49 typedef struct CompandContext {
50  const AVClass *class;
52  char *attacks, *decays, *points;
55  double in_min_lin;
56  double out_min_lin;
57  double curve_dB;
58  double gain_dB;
60  double delay;
65  int64_t pts;
66 
69 
70 #define OFFSET(x) offsetof(CompandContext, x)
71 #define A AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
72 
73 static const AVOption compand_options[] = {
74  { "attacks", "set time over which increase of volume is determined", OFFSET(attacks), AV_OPT_TYPE_STRING, { .str = "0.3" }, 0, 0, A },
75  { "decays", "set time over which decrease of volume is determined", OFFSET(decays), AV_OPT_TYPE_STRING, { .str = "0.8" }, 0, 0, A },
76  { "points", "set points of transfer function", OFFSET(points), AV_OPT_TYPE_STRING, { .str = "-70/-70|-60/-20" }, 0, 0, A },
77  { "soft-knee", "set soft-knee", OFFSET(curve_dB), AV_OPT_TYPE_DOUBLE, { .dbl = 0.01 }, 0.01, 900, A },
78  { "gain", "set output gain", OFFSET(gain_dB), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, -900, 900, A },
79  { "volume", "set initial volume", OFFSET(initial_volume), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, -900, 0, A },
80  { "delay", "set delay for samples before sending them to volume adjuster", OFFSET(delay), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, 0, 20, A },
81  { NULL }
82 };
83 
84 AVFILTER_DEFINE_CLASS(compand);
85 
86 static av_cold int init(AVFilterContext *ctx)
87 {
88  CompandContext *s = ctx->priv;
89  s->pts = AV_NOPTS_VALUE;
90  return 0;
91 }
92 
93 static av_cold void uninit(AVFilterContext *ctx)
94 {
95  CompandContext *s = ctx->priv;
96 
97  av_freep(&s->channels);
98  av_freep(&s->segments);
100 }
101 
103 {
106  static const enum AVSampleFormat sample_fmts[] = {
109  };
110 
111  layouts = ff_all_channel_layouts();
112  if (!layouts)
113  return AVERROR(ENOMEM);
114  ff_set_common_channel_layouts(ctx, layouts);
115 
116  formats = ff_make_format_list(sample_fmts);
117  if (!formats)
118  return AVERROR(ENOMEM);
119  ff_set_common_formats(ctx, formats);
120 
121  formats = ff_all_samplerates();
122  if (!formats)
123  return AVERROR(ENOMEM);
124  ff_set_common_samplerates(ctx, formats);
125 
126  return 0;
127 }
128 
129 static void count_items(char *item_str, int *nb_items)
130 {
131  char *p;
132 
133  *nb_items = 1;
134  for (p = item_str; *p; p++) {
135  if (*p == ' ' || *p == '|')
136  (*nb_items)++;
137  }
138 }
139 
140 static void update_volume(ChanParam *cp, double in)
141 {
142  double delta = in - cp->volume;
143 
144  if (delta > 0.0)
145  cp->volume += delta * cp->attack;
146  else
147  cp->volume += delta * cp->decay;
148 }
149 
150 static double get_volume(CompandContext *s, double in_lin)
151 {
152  CompandSegment *cs;
153  double in_log, out_log;
154  int i;
155 
156  if (in_lin < s->in_min_lin)
157  return s->out_min_lin;
158 
159  in_log = log(in_lin);
160 
161  for (i = 1; i < s->nb_segments; i++)
162  if (in_log <= s->segments[i].x)
163  break;
164  cs = &s->segments[i - 1];
165  in_log -= cs->x;
166  out_log = cs->y + in_log * (cs->a * in_log + cs->b);
167 
168  return exp(out_log);
169 }
170 
172 {
173  CompandContext *s = ctx->priv;
174  AVFilterLink *inlink = ctx->inputs[0];
175  const int channels = inlink->channels;
176  const int nb_samples = frame->nb_samples;
177  AVFrame *out_frame;
178  int chan, i;
179  int err;
180 
181  if (av_frame_is_writable(frame)) {
182  out_frame = frame;
183  } else {
184  out_frame = ff_get_audio_buffer(inlink, nb_samples);
185  if (!out_frame) {
186  av_frame_free(&frame);
187  return AVERROR(ENOMEM);
188  }
189  err = av_frame_copy_props(out_frame, frame);
190  if (err < 0) {
191  av_frame_free(&out_frame);
192  av_frame_free(&frame);
193  return err;
194  }
195  }
196 
197  for (chan = 0; chan < channels; chan++) {
198  const double *src = (double *)frame->extended_data[chan];
199  double *dst = (double *)out_frame->extended_data[chan];
200  ChanParam *cp = &s->channels[chan];
201 
202  for (i = 0; i < nb_samples; i++) {
203  update_volume(cp, fabs(src[i]));
204 
205  dst[i] = av_clipd(src[i] * get_volume(s, cp->volume), -1, 1);
206  }
207  }
208 
209  if (frame != out_frame)
210  av_frame_free(&frame);
211 
212  return ff_filter_frame(ctx->outputs[0], out_frame);
213 }
214 
215 #define MOD(a, b) (((a) >= (b)) ? (a) - (b) : (a))
216 
218 {
219  CompandContext *s = ctx->priv;
220  AVFilterLink *inlink = ctx->inputs[0];
221  const int channels = inlink->channels;
222  const int nb_samples = frame->nb_samples;
223  int chan, i, av_uninit(dindex), oindex, av_uninit(count);
224  AVFrame *out_frame = NULL;
225  int err;
226 
227  if (s->pts == AV_NOPTS_VALUE) {
228  s->pts = (frame->pts == AV_NOPTS_VALUE) ? 0 : frame->pts;
229  }
230 
231  av_assert1(channels > 0); /* would corrupt delay_count and delay_index */
232 
233  for (chan = 0; chan < channels; chan++) {
234  AVFrame *delay_frame = s->delay_frame;
235  const double *src = (double *)frame->extended_data[chan];
236  double *dbuf = (double *)delay_frame->extended_data[chan];
237  ChanParam *cp = &s->channels[chan];
238  double *dst;
239 
240  count = s->delay_count;
241  dindex = s->delay_index;
242  for (i = 0, oindex = 0; i < nb_samples; i++) {
243  const double in = src[i];
244  update_volume(cp, fabs(in));
245 
246  if (count >= s->delay_samples) {
247  if (!out_frame) {
248  out_frame = ff_get_audio_buffer(inlink, nb_samples - i);
249  if (!out_frame) {
250  av_frame_free(&frame);
251  return AVERROR(ENOMEM);
252  }
253  err = av_frame_copy_props(out_frame, frame);
254  if (err < 0) {
255  av_frame_free(&out_frame);
256  av_frame_free(&frame);
257  return err;
258  }
259  out_frame->pts = s->pts;
260  s->pts += av_rescale_q(nb_samples - i,
261  (AVRational){ 1, inlink->sample_rate },
262  inlink->time_base);
263  }
264 
265  dst = (double *)out_frame->extended_data[chan];
266  dst[oindex++] = av_clipd(dbuf[dindex] *
267  get_volume(s, cp->volume), -1, 1);
268  } else {
269  count++;
270  }
271 
272  dbuf[dindex] = in;
273  dindex = MOD(dindex + 1, s->delay_samples);
274  }
275  }
276 
277  s->delay_count = count;
278  s->delay_index = dindex;
279 
280  av_frame_free(&frame);
281  return out_frame ? ff_filter_frame(ctx->outputs[0], out_frame) : 0;
282 }
283 
284 static int compand_drain(AVFilterLink *outlink)
285 {
286  AVFilterContext *ctx = outlink->src;
287  CompandContext *s = ctx->priv;
288  const int channels = outlink->channels;
289  AVFrame *frame = NULL;
290  int chan, i, dindex;
291 
292  /* 2048 is to limit output frame size during drain */
293  frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->delay_count));
294  if (!frame)
295  return AVERROR(ENOMEM);
296  frame->pts = s->pts;
297  s->pts += av_rescale_q(frame->nb_samples,
298  (AVRational){ 1, outlink->sample_rate }, outlink->time_base);
299 
300  for (chan = 0; chan < channels; chan++) {
301  AVFrame *delay_frame = s->delay_frame;
302  double *dbuf = (double *)delay_frame->extended_data[chan];
303  double *dst = (double *)frame->extended_data[chan];
304  ChanParam *cp = &s->channels[chan];
305 
306  dindex = s->delay_index;
307  for (i = 0; i < frame->nb_samples; i++) {
308  dst[i] = av_clipd(dbuf[dindex] * get_volume(s, cp->volume),
309  -1, 1);
310  dindex = MOD(dindex + 1, s->delay_samples);
311  }
312  }
313  s->delay_count -= frame->nb_samples;
314  s->delay_index = dindex;
315 
316  return ff_filter_frame(outlink, frame);
317 }
318 
319 static int config_output(AVFilterLink *outlink)
320 {
321  AVFilterContext *ctx = outlink->src;
322  CompandContext *s = ctx->priv;
323  const int sample_rate = outlink->sample_rate;
324  double radius = s->curve_dB * M_LN10 / 20.0;
325  char *p, *saveptr = NULL;
326  const int channels = outlink->channels;
327  int nb_attacks, nb_decays, nb_points;
328  int new_nb_items, num;
329  int i;
330  int err;
331 
332 
333  count_items(s->attacks, &nb_attacks);
334  count_items(s->decays, &nb_decays);
335  count_items(s->points, &nb_points);
336 
337  if (channels <= 0) {
338  av_log(ctx, AV_LOG_ERROR, "Invalid number of channels: %d\n", channels);
339  return AVERROR(EINVAL);
340  }
341 
342  if (nb_attacks > channels || nb_decays > channels) {
343  av_log(ctx, AV_LOG_ERROR,
344  "Number of attacks/decays bigger than number of channels.\n");
345  return AVERROR(EINVAL);
346  }
347 
348  uninit(ctx);
349 
350  s->channels = av_mallocz_array(channels, sizeof(*s->channels));
351  s->nb_segments = (nb_points + 4) * 2;
352  s->segments = av_mallocz_array(s->nb_segments, sizeof(*s->segments));
353 
354  if (!s->channels || !s->segments) {
355  uninit(ctx);
356  return AVERROR(ENOMEM);
357  }
358 
359  p = s->attacks;
360  for (i = 0, new_nb_items = 0; i < nb_attacks; i++) {
361  char *tstr = av_strtok(p, " |", &saveptr);
362  p = NULL;
363  new_nb_items += sscanf(tstr, "%lf", &s->channels[i].attack) == 1;
364  if (s->channels[i].attack < 0) {
365  uninit(ctx);
366  return AVERROR(EINVAL);
367  }
368  }
369  nb_attacks = new_nb_items;
370 
371  p = s->decays;
372  for (i = 0, new_nb_items = 0; i < nb_decays; i++) {
373  char *tstr = av_strtok(p, " |", &saveptr);
374  p = NULL;
375  new_nb_items += sscanf(tstr, "%lf", &s->channels[i].decay) == 1;
376  if (s->channels[i].decay < 0) {
377  uninit(ctx);
378  return AVERROR(EINVAL);
379  }
380  }
381  nb_decays = new_nb_items;
382 
383  if (nb_attacks != nb_decays) {
384  av_log(ctx, AV_LOG_ERROR,
385  "Number of attacks %d differs from number of decays %d.\n",
386  nb_attacks, nb_decays);
387  uninit(ctx);
388  return AVERROR(EINVAL);
389  }
390 
391 #define S(x) s->segments[2 * ((x) + 1)]
392  p = s->points;
393  for (i = 0, new_nb_items = 0; i < nb_points; i++) {
394  char *tstr = av_strtok(p, " |", &saveptr);
395  p = NULL;
396  if (sscanf(tstr, "%lf/%lf", &S(i).x, &S(i).y) != 2) {
397  av_log(ctx, AV_LOG_ERROR,
398  "Invalid and/or missing input/output value.\n");
399  uninit(ctx);
400  return AVERROR(EINVAL);
401  }
402  if (i && S(i - 1).x > S(i).x) {
403  av_log(ctx, AV_LOG_ERROR,
404  "Transfer function input values must be increasing.\n");
405  uninit(ctx);
406  return AVERROR(EINVAL);
407  }
408  S(i).y -= S(i).x;
409  av_log(ctx, AV_LOG_DEBUG, "%d: x=%f y=%f\n", i, S(i).x, S(i).y);
410  new_nb_items++;
411  }
412  num = new_nb_items;
413 
414  /* Add 0,0 if necessary */
415  if (num == 0 || S(num - 1).x)
416  num++;
417 
418 #undef S
419 #define S(x) s->segments[2 * (x)]
420  /* Add a tail off segment at the start */
421  S(0).x = S(1).x - 2 * s->curve_dB;
422  S(0).y = S(1).y;
423  num++;
424 
425  /* Join adjacent colinear segments */
426  for (i = 2; i < num; i++) {
427  double g1 = (S(i - 1).y - S(i - 2).y) * (S(i - 0).x - S(i - 1).x);
428  double g2 = (S(i - 0).y - S(i - 1).y) * (S(i - 1).x - S(i - 2).x);
429  int j;
430 
431  if (fabs(g1 - g2))
432  continue;
433  num--;
434  for (j = --i; j < num; j++)
435  S(j) = S(j + 1);
436  }
437 
438  for (i = 0; !i || s->segments[i - 2].x; i += 2) {
439  s->segments[i].y += s->gain_dB;
440  s->segments[i].x *= M_LN10 / 20;
441  s->segments[i].y *= M_LN10 / 20;
442  }
443 
444 #define L(x) s->segments[i - (x)]
445  for (i = 4; s->segments[i - 2].x; i += 2) {
446  double x, y, cx, cy, in1, in2, out1, out2, theta, len, r;
447 
448  L(4).a = 0;
449  L(4).b = (L(2).y - L(4).y) / (L(2).x - L(4).x);
450 
451  L(2).a = 0;
452  L(2).b = (L(0).y - L(2).y) / (L(0).x - L(2).x);
453 
454  theta = atan2(L(2).y - L(4).y, L(2).x - L(4).x);
455  len = sqrt(pow(L(2).x - L(4).x, 2.) + pow(L(2).y - L(4).y, 2.));
456  r = FFMIN(radius, len);
457  L(3).x = L(2).x - r * cos(theta);
458  L(3).y = L(2).y - r * sin(theta);
459 
460  theta = atan2(L(0).y - L(2).y, L(0).x - L(2).x);
461  len = sqrt(pow(L(0).x - L(2).x, 2.) + pow(L(0).y - L(2).y, 2.));
462  r = FFMIN(radius, len / 2);
463  x = L(2).x + r * cos(theta);
464  y = L(2).y + r * sin(theta);
465 
466  cx = (L(3).x + L(2).x + x) / 3;
467  cy = (L(3).y + L(2).y + y) / 3;
468 
469  L(2).x = x;
470  L(2).y = y;
471 
472  in1 = cx - L(3).x;
473  out1 = cy - L(3).y;
474  in2 = L(2).x - L(3).x;
475  out2 = L(2).y - L(3).y;
476  L(3).a = (out2 / in2 - out1 / in1) / (in2 - in1);
477  L(3).b = out1 / in1 - L(3).a * in1;
478  }
479  L(3).x = 0;
480  L(3).y = L(2).y;
481 
482  s->in_min_lin = exp(s->segments[1].x);
483  s->out_min_lin = exp(s->segments[1].y);
484 
485  for (i = 0; i < channels; i++) {
486  ChanParam *cp = &s->channels[i];
487 
488  if (cp->attack > 1.0 / sample_rate)
489  cp->attack = 1.0 - exp(-1.0 / (sample_rate * cp->attack));
490  else
491  cp->attack = 1.0;
492  if (cp->decay > 1.0 / sample_rate)
493  cp->decay = 1.0 - exp(-1.0 / (sample_rate * cp->decay));
494  else
495  cp->decay = 1.0;
496  cp->volume = pow(10.0, s->initial_volume / 20);
497  }
498 
499  s->delay_samples = s->delay * sample_rate;
500  if (s->delay_samples <= 0) {
502  return 0;
503  }
504 
506  if (!s->delay_frame) {
507  uninit(ctx);
508  return AVERROR(ENOMEM);
509  }
510 
511  s->delay_frame->format = outlink->format;
514 
515  err = av_frame_get_buffer(s->delay_frame, 32);
516  if (err)
517  return err;
518 
519  outlink->flags |= FF_LINK_FLAG_REQUEST_LOOP;
520  s->compand = compand_delay;
521  return 0;
522 }
523 
524 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
525 {
526  AVFilterContext *ctx = inlink->dst;
527  CompandContext *s = ctx->priv;
528 
529  return s->compand(ctx, frame);
530 }
531 
532 static int request_frame(AVFilterLink *outlink)
533 {
534  AVFilterContext *ctx = outlink->src;
535  CompandContext *s = ctx->priv;
536  int ret;
537 
538  ret = ff_request_frame(ctx->inputs[0]);
539 
540  if (ret == AVERROR_EOF && !ctx->is_disabled && s->delay_count)
541  ret = compand_drain(outlink);
542 
543  return ret;
544 }
545 
546 static const AVFilterPad compand_inputs[] = {
547  {
548  .name = "default",
549  .type = AVMEDIA_TYPE_AUDIO,
550  .filter_frame = filter_frame,
551  },
552  { NULL }
553 };
554 
555 static const AVFilterPad compand_outputs[] = {
556  {
557  .name = "default",
558  .request_frame = request_frame,
559  .config_props = config_output,
560  .type = AVMEDIA_TYPE_AUDIO,
561  },
562  { NULL }
563 };
564 
565 
567  .name = "compand",
568  .description = NULL_IF_CONFIG_SMALL(
569  "Compress or expand audio dynamic range."),
570  .query_formats = query_formats,
571  .priv_size = sizeof(CompandContext),
572  .priv_class = &compand_class,
573  .init = init,
574  .uninit = uninit,
575  .inputs = compand_inputs,
576  .outputs = compand_outputs,
577 };