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
8 * This file is part of FFmpeg.
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.
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.
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
27 * audio compand filter
30 #include "libavutil/avassert.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/ffmath.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/samplefmt.h"
39 typedef struct ChanParam {
45 typedef struct CompandSegment {
50 typedef struct CompandContext {
53 char *attacks, *decays, *points;
54 CompandSegment *segments;
60 double initial_volume;
68 int (*compand)(AVFilterContext *ctx, AVFrame *frame);
71 #define OFFSET(x) offsetof(CompandContext, x)
72 #define A AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
74 static const AVOption compand_options[] = {
75 { "attacks", "set time over which increase of volume is determined", OFFSET(attacks), AV_OPT_TYPE_STRING, { .str = "0" }, 0, 0, A },
76 { "decays", "set time over which decrease of volume is determined", OFFSET(decays), AV_OPT_TYPE_STRING, { .str = "0.8" }, 0, 0, A },
77 { "points", "set points of transfer function", OFFSET(points), AV_OPT_TYPE_STRING, { .str = "-70/-70|-60/-20|1/0" }, 0, 0, A },
78 { "soft-knee", "set soft-knee", OFFSET(curve_dB), AV_OPT_TYPE_DOUBLE, { .dbl = 0.01 }, 0.01, 900, A },
79 { "gain", "set output gain", OFFSET(gain_dB), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, -900, 900, A },
80 { "volume", "set initial volume", OFFSET(initial_volume), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, -900, 0, A },
81 { "delay", "set delay for samples before sending them to volume adjuster", OFFSET(delay), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, 0, 20, A },
85 AVFILTER_DEFINE_CLASS(compand);
87 static av_cold int init(AVFilterContext *ctx)
89 CompandContext *s = ctx->priv;
90 s->pts = AV_NOPTS_VALUE;
94 static av_cold void uninit(AVFilterContext *ctx)
96 CompandContext *s = ctx->priv;
98 av_freep(&s->channels);
99 av_freep(&s->segments);
100 av_frame_free(&s->delay_frame);
103 static int query_formats(AVFilterContext *ctx)
105 AVFilterChannelLayouts *layouts;
106 AVFilterFormats *formats;
107 static const enum AVSampleFormat sample_fmts[] = {
113 layouts = ff_all_channel_counts();
115 return AVERROR(ENOMEM);
116 ret = ff_set_common_channel_layouts(ctx, layouts);
120 formats = ff_make_format_list(sample_fmts);
122 return AVERROR(ENOMEM);
123 ret = ff_set_common_formats(ctx, formats);
127 formats = ff_all_samplerates();
129 return AVERROR(ENOMEM);
130 return ff_set_common_samplerates(ctx, formats);
133 static void count_items(char *item_str, int *nb_items)
138 for (p = item_str; *p; p++) {
139 if (*p == ' ' || *p == '|')
144 static void update_volume(ChanParam *cp, double in)
146 double delta = in - cp->volume;
149 cp->volume += delta * cp->attack;
151 cp->volume += delta * cp->decay;
154 static double get_volume(CompandContext *s, double in_lin)
157 double in_log, out_log;
160 if (in_lin < s->in_min_lin)
161 return s->out_min_lin;
163 in_log = log(in_lin);
165 for (i = 1; i < s->nb_segments; i++)
166 if (in_log <= s->segments[i].x)
168 cs = &s->segments[i - 1];
170 out_log = cs->y + in_log * (cs->a * in_log + cs->b);
175 static int compand_nodelay(AVFilterContext *ctx, AVFrame *frame)
177 CompandContext *s = ctx->priv;
178 AVFilterLink *inlink = ctx->inputs[0];
179 const int channels = inlink->channels;
180 const int nb_samples = frame->nb_samples;
185 if (av_frame_is_writable(frame)) {
188 out_frame = ff_get_audio_buffer(ctx->outputs[0], nb_samples);
190 av_frame_free(&frame);
191 return AVERROR(ENOMEM);
193 err = av_frame_copy_props(out_frame, frame);
195 av_frame_free(&out_frame);
196 av_frame_free(&frame);
201 for (chan = 0; chan < channels; chan++) {
202 const double *src = (double *)frame->extended_data[chan];
203 double *dst = (double *)out_frame->extended_data[chan];
204 ChanParam *cp = &s->channels[chan];
206 for (i = 0; i < nb_samples; i++) {
207 update_volume(cp, fabs(src[i]));
209 dst[i] = src[i] * get_volume(s, cp->volume);
213 if (frame != out_frame)
214 av_frame_free(&frame);
216 return ff_filter_frame(ctx->outputs[0], out_frame);
219 #define MOD(a, b) (((a) >= (b)) ? (a) - (b) : (a))
221 static int compand_delay(AVFilterContext *ctx, AVFrame *frame)
223 CompandContext *s = ctx->priv;
224 AVFilterLink *inlink = ctx->inputs[0];
225 const int channels = inlink->channels;
226 const int nb_samples = frame->nb_samples;
227 int chan, i, av_uninit(dindex), oindex, av_uninit(count);
228 AVFrame *out_frame = NULL;
231 if (s->pts == AV_NOPTS_VALUE) {
232 s->pts = (frame->pts == AV_NOPTS_VALUE) ? 0 : frame->pts;
235 av_assert1(channels > 0); /* would corrupt delay_count and delay_index */
237 for (chan = 0; chan < channels; chan++) {
238 AVFrame *delay_frame = s->delay_frame;
239 const double *src = (double *)frame->extended_data[chan];
240 double *dbuf = (double *)delay_frame->extended_data[chan];
241 ChanParam *cp = &s->channels[chan];
244 count = s->delay_count;
245 dindex = s->delay_index;
246 for (i = 0, oindex = 0; i < nb_samples; i++) {
247 const double in = src[i];
248 update_volume(cp, fabs(in));
250 if (count >= s->delay_samples) {
252 out_frame = ff_get_audio_buffer(ctx->outputs[0], nb_samples - i);
254 av_frame_free(&frame);
255 return AVERROR(ENOMEM);
257 err = av_frame_copy_props(out_frame, frame);
259 av_frame_free(&out_frame);
260 av_frame_free(&frame);
263 out_frame->pts = s->pts;
264 s->pts += av_rescale_q(nb_samples - i,
265 (AVRational){ 1, inlink->sample_rate },
269 dst = (double *)out_frame->extended_data[chan];
270 dst[oindex++] = dbuf[dindex] * get_volume(s, cp->volume);
276 dindex = MOD(dindex + 1, s->delay_samples);
280 s->delay_count = count;
281 s->delay_index = dindex;
283 av_frame_free(&frame);
286 err = ff_filter_frame(ctx->outputs[0], out_frame);
293 static int compand_drain(AVFilterLink *outlink)
295 AVFilterContext *ctx = outlink->src;
296 CompandContext *s = ctx->priv;
297 const int channels = outlink->channels;
298 AVFrame *frame = NULL;
301 /* 2048 is to limit output frame size during drain */
302 frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->delay_count));
304 return AVERROR(ENOMEM);
306 s->pts += av_rescale_q(frame->nb_samples,
307 (AVRational){ 1, outlink->sample_rate }, outlink->time_base);
309 av_assert0(channels > 0);
310 for (chan = 0; chan < channels; chan++) {
311 AVFrame *delay_frame = s->delay_frame;
312 double *dbuf = (double *)delay_frame->extended_data[chan];
313 double *dst = (double *)frame->extended_data[chan];
314 ChanParam *cp = &s->channels[chan];
316 dindex = s->delay_index;
317 for (i = 0; i < frame->nb_samples; i++) {
318 dst[i] = dbuf[dindex] * get_volume(s, cp->volume);
319 dindex = MOD(dindex + 1, s->delay_samples);
322 s->delay_count -= frame->nb_samples;
323 s->delay_index = dindex;
325 return ff_filter_frame(outlink, frame);
328 static int config_output(AVFilterLink *outlink)
330 AVFilterContext *ctx = outlink->src;
331 CompandContext *s = ctx->priv;
332 const int sample_rate = outlink->sample_rate;
333 double radius = s->curve_dB * M_LN10 / 20.0;
334 char *p, *saveptr = NULL;
335 const int channels = outlink->channels;
336 int nb_attacks, nb_decays, nb_points;
337 int new_nb_items, num;
342 count_items(s->attacks, &nb_attacks);
343 count_items(s->decays, &nb_decays);
344 count_items(s->points, &nb_points);
347 av_log(ctx, AV_LOG_ERROR, "Invalid number of channels: %d\n", channels);
348 return AVERROR(EINVAL);
351 if (nb_attacks > channels || nb_decays > channels) {
352 av_log(ctx, AV_LOG_ERROR,
353 "Number of attacks/decays bigger than number of channels.\n");
354 return AVERROR(EINVAL);
359 s->channels = av_mallocz_array(channels, sizeof(*s->channels));
360 s->nb_segments = (nb_points + 4) * 2;
361 s->segments = av_mallocz_array(s->nb_segments, sizeof(*s->segments));
363 if (!s->channels || !s->segments) {
365 return AVERROR(ENOMEM);
369 for (i = 0, new_nb_items = 0; i < nb_attacks; i++) {
370 char *tstr = av_strtok(p, " |", &saveptr);
373 return AVERROR(EINVAL);
376 new_nb_items += sscanf(tstr, "%lf", &s->channels[i].attack) == 1;
377 if (s->channels[i].attack < 0) {
379 return AVERROR(EINVAL);
382 nb_attacks = new_nb_items;
385 for (i = 0, new_nb_items = 0; i < nb_decays; i++) {
386 char *tstr = av_strtok(p, " |", &saveptr);
389 return AVERROR(EINVAL);
392 new_nb_items += sscanf(tstr, "%lf", &s->channels[i].decay) == 1;
393 if (s->channels[i].decay < 0) {
395 return AVERROR(EINVAL);
398 nb_decays = new_nb_items;
400 if (nb_attacks != nb_decays) {
401 av_log(ctx, AV_LOG_ERROR,
402 "Number of attacks %d differs from number of decays %d.\n",
403 nb_attacks, nb_decays);
405 return AVERROR(EINVAL);
408 for (i = nb_decays; i < channels; i++) {
409 s->channels[i].attack = s->channels[nb_decays - 1].attack;
410 s->channels[i].decay = s->channels[nb_decays - 1].decay;
413 #define S(x) s->segments[2 * ((x) + 1)]
415 for (i = 0, new_nb_items = 0; i < nb_points; i++) {
416 char *tstr = av_strtok(p, " |", &saveptr);
418 if (!tstr || sscanf(tstr, "%lf/%lf", &S(i).x, &S(i).y) != 2) {
419 av_log(ctx, AV_LOG_ERROR,
420 "Invalid and/or missing input/output value.\n");
422 return AVERROR(EINVAL);
424 if (i && S(i - 1).x > S(i).x) {
425 av_log(ctx, AV_LOG_ERROR,
426 "Transfer function input values must be increasing.\n");
428 return AVERROR(EINVAL);
431 av_log(ctx, AV_LOG_DEBUG, "%d: x=%f y=%f\n", i, S(i).x, S(i).y);
436 /* Add 0,0 if necessary */
437 if (num == 0 || S(num - 1).x)
441 #define S(x) s->segments[2 * (x)]
442 /* Add a tail off segment at the start */
443 S(0).x = S(1).x - 2 * s->curve_dB;
447 /* Join adjacent colinear segments */
448 for (i = 2; i < num; i++) {
449 double g1 = (S(i - 1).y - S(i - 2).y) * (S(i - 0).x - S(i - 1).x);
450 double g2 = (S(i - 0).y - S(i - 1).y) * (S(i - 1).x - S(i - 2).x);
456 for (j = --i; j < num; j++)
460 for (i = 0; i < s->nb_segments; i += 2) {
461 s->segments[i].y += s->gain_dB;
462 s->segments[i].x *= M_LN10 / 20;
463 s->segments[i].y *= M_LN10 / 20;
466 #define L(x) s->segments[i - (x)]
467 for (i = 4; i < s->nb_segments; i += 2) {
468 double x, y, cx, cy, in1, in2, out1, out2, theta, len, r;
471 L(4).b = (L(2).y - L(4).y) / (L(2).x - L(4).x);
474 L(2).b = (L(0).y - L(2).y) / (L(0).x - L(2).x);
476 theta = atan2(L(2).y - L(4).y, L(2).x - L(4).x);
477 len = hypot(L(2).x - L(4).x, L(2).y - L(4).y);
478 r = FFMIN(radius, len);
479 L(3).x = L(2).x - r * cos(theta);
480 L(3).y = L(2).y - r * sin(theta);
482 theta = atan2(L(0).y - L(2).y, L(0).x - L(2).x);
483 len = hypot(L(0).x - L(2).x, L(0).y - L(2).y);
484 r = FFMIN(radius, len / 2);
485 x = L(2).x + r * cos(theta);
486 y = L(2).y + r * sin(theta);
488 cx = (L(3).x + L(2).x + x) / 3;
489 cy = (L(3).y + L(2).y + y) / 3;
496 in2 = L(2).x - L(3).x;
497 out2 = L(2).y - L(3).y;
498 L(3).a = (out2 / in2 - out1 / in1) / (in2 - in1);
499 L(3).b = out1 / in1 - L(3).a * in1;
504 s->in_min_lin = exp(s->segments[1].x);
505 s->out_min_lin = exp(s->segments[1].y);
507 for (i = 0; i < channels; i++) {
508 ChanParam *cp = &s->channels[i];
510 if (cp->attack > 1.0 / sample_rate)
511 cp->attack = 1.0 - exp(-1.0 / (sample_rate * cp->attack));
514 if (cp->decay > 1.0 / sample_rate)
515 cp->decay = 1.0 - exp(-1.0 / (sample_rate * cp->decay));
518 cp->volume = ff_exp10(s->initial_volume / 20);
521 s->delay_samples = s->delay * sample_rate;
522 if (s->delay_samples <= 0) {
523 s->compand = compand_nodelay;
527 s->delay_frame = av_frame_alloc();
528 if (!s->delay_frame) {
530 return AVERROR(ENOMEM);
533 s->delay_frame->format = outlink->format;
534 s->delay_frame->nb_samples = s->delay_samples;
535 s->delay_frame->channel_layout = outlink->channel_layout;
537 err = av_frame_get_buffer(s->delay_frame, 32);
541 s->compand = compand_delay;
545 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
547 AVFilterContext *ctx = inlink->dst;
548 CompandContext *s = ctx->priv;
550 return s->compand(ctx, frame);
553 static int request_frame(AVFilterLink *outlink)
555 AVFilterContext *ctx = outlink->src;
556 CompandContext *s = ctx->priv;
559 ret = ff_request_frame(ctx->inputs[0]);
561 if (ret == AVERROR_EOF && !ctx->is_disabled && s->delay_count)
562 ret = compand_drain(outlink);
567 static const AVFilterPad compand_inputs[] = {
570 .type = AVMEDIA_TYPE_AUDIO,
571 .filter_frame = filter_frame,
576 static const AVFilterPad compand_outputs[] = {
579 .request_frame = request_frame,
580 .config_props = config_output,
581 .type = AVMEDIA_TYPE_AUDIO,
587 AVFilter ff_af_compand = {
589 .description = NULL_IF_CONFIG_SMALL(
590 "Compress or expand audio dynamic range."),
591 .query_formats = query_formats,
592 .priv_size = sizeof(CompandContext),
593 .priv_class = &compand_class,
596 .inputs = compand_inputs,
597 .outputs = compand_outputs,