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
28 * audio compand filter
31 #include "libavutil/avassert.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/samplefmt.h"
39 typedef struct ChanParam {
45 typedef struct CompandSegment {
50 typedef struct CompandContext {
52 char *attacks, *decays, *points;
53 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=NULL}, 0, 0, A },
76 { "decays", "set time over which decrease of volume is determined", OFFSET(decays), AV_OPT_TYPE_STRING, { .str=NULL}, 0, 0, A },
77 { "points", "set points of transfer function", OFFSET(points), AV_OPT_TYPE_STRING, { .str=NULL}, 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;
92 if (!s->attacks || !s->decays || !s->points) {
93 av_log(ctx, AV_LOG_ERROR, "Missing attacks and/or decays and/or points.\n");
94 return AVERROR(EINVAL);
100 static av_cold void uninit(AVFilterContext *ctx)
102 CompandContext *s = ctx->priv;
104 av_freep(&s->channels);
105 av_freep(&s->segments);
106 av_frame_free(&s->delay_frame);
109 static int query_formats(AVFilterContext *ctx)
111 AVFilterChannelLayouts *layouts;
112 AVFilterFormats *formats;
113 static const enum AVSampleFormat sample_fmts[] = {
118 layouts = ff_all_channel_layouts();
120 return AVERROR(ENOMEM);
121 ff_set_common_channel_layouts(ctx, layouts);
123 formats = ff_make_format_list(sample_fmts);
125 return AVERROR(ENOMEM);
126 ff_set_common_formats(ctx, formats);
128 formats = ff_all_samplerates();
130 return AVERROR(ENOMEM);
131 ff_set_common_samplerates(ctx, formats);
136 static void count_items(char *item_str, int *nb_items)
141 for (p = item_str; *p; p++) {
142 if (*p == ' ' || *p == '|')
147 static void update_volume(ChanParam *cp, double in)
149 double delta = in - cp->volume;
152 cp->volume += delta * cp->attack;
154 cp->volume += delta * cp->decay;
157 static double get_volume(CompandContext *s, double in_lin)
160 double in_log, out_log;
163 if (in_lin < s->in_min_lin)
164 return s->out_min_lin;
166 in_log = log(in_lin);
168 for (i = 1; i < s->nb_segments; i++)
169 if (in_log <= s->segments[i].x)
171 cs = &s->segments[i - 1];
173 out_log = cs->y + in_log * (cs->a * in_log + cs->b);
178 static int compand_nodelay(AVFilterContext *ctx, AVFrame *frame)
180 CompandContext *s = ctx->priv;
181 AVFilterLink *inlink = ctx->inputs[0];
182 const int channels = inlink->channels;
183 const int nb_samples = frame->nb_samples;
187 if (av_frame_is_writable(frame)) {
190 out_frame = ff_get_audio_buffer(inlink, nb_samples);
192 av_frame_free(&frame);
193 return AVERROR(ENOMEM);
195 av_frame_copy_props(out_frame, frame);
198 for (chan = 0; chan < channels; chan++) {
199 const double *src = (double *)frame->extended_data[chan];
200 double *dst = (double *)out_frame->extended_data[chan];
201 ChanParam *cp = &s->channels[chan];
203 for (i = 0; i < nb_samples; i++) {
204 update_volume(cp, fabs(src[i]));
206 dst[i] = av_clipd(src[i] * get_volume(s, cp->volume), -1, 1);
210 if (frame != out_frame)
211 av_frame_free(&frame);
213 return ff_filter_frame(ctx->outputs[0], out_frame);
216 #define MOD(a, b) (((a) >= (b)) ? (a) - (b) : (a))
218 static int compand_delay(AVFilterContext *ctx, AVFrame *frame)
220 CompandContext *s = ctx->priv;
221 AVFilterLink *inlink = ctx->inputs[0];
222 const int channels = inlink->channels;
223 const int nb_samples = frame->nb_samples;
224 int chan, i, av_uninit(dindex), oindex, av_uninit(count);
225 AVFrame *out_frame = NULL;
227 if (s->pts == AV_NOPTS_VALUE) {
228 s->pts = (frame->pts == AV_NOPTS_VALUE) ? 0 : frame->pts;
231 av_assert1(channels > 0); /* would corrupt delay_count and delay_index */
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];
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));
246 if (count >= s->delay_samples) {
248 out_frame = ff_get_audio_buffer(inlink, nb_samples - i);
250 av_frame_free(&frame);
251 return AVERROR(ENOMEM);
253 av_frame_copy_props(out_frame, frame);
254 out_frame->pts = s->pts;
255 s->pts += av_rescale_q(nb_samples - i,
256 (AVRational){ 1, inlink->sample_rate },
260 dst = (double *)out_frame->extended_data[chan];
261 dst[oindex++] = av_clipd(dbuf[dindex] *
262 get_volume(s, cp->volume), -1, 1);
268 dindex = MOD(dindex + 1, s->delay_samples);
272 s->delay_count = count;
273 s->delay_index = dindex;
275 av_frame_free(&frame);
276 return out_frame ? ff_filter_frame(ctx->outputs[0], out_frame) : 0;
279 static int compand_drain(AVFilterLink *outlink)
281 AVFilterContext *ctx = outlink->src;
282 CompandContext *s = ctx->priv;
283 const int channels = outlink->channels;
285 AVFrame *frame = NULL;
287 frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->delay_count));
289 return AVERROR(ENOMEM);
291 s->pts += av_rescale_q(frame->nb_samples,
292 (AVRational){ 1, outlink->sample_rate }, outlink->time_base);
294 for (chan = 0; chan < channels; chan++) {
295 AVFrame *delay_frame = s->delay_frame;
296 double *dbuf = (double *)delay_frame->extended_data[chan];
297 double *dst = (double *)frame->extended_data[chan];
298 ChanParam *cp = &s->channels[chan];
300 dindex = s->delay_index;
301 for (i = 0; i < frame->nb_samples; i++) {
302 dst[i] = av_clipd(dbuf[dindex] * get_volume(s, cp->volume), -1, 1);
303 dindex = MOD(dindex + 1, s->delay_samples);
306 s->delay_count -= frame->nb_samples;
307 s->delay_index = dindex;
309 return ff_filter_frame(outlink, frame);
312 static int config_output(AVFilterLink *outlink)
314 AVFilterContext *ctx = outlink->src;
315 CompandContext *s = ctx->priv;
316 const int sample_rate = outlink->sample_rate;
317 double radius = s->curve_dB * M_LN10 / 20;
318 int nb_attacks, nb_decays, nb_points;
319 char *p, *saveptr = NULL;
320 int new_nb_items, num;
325 count_items(s->attacks, &nb_attacks);
326 count_items(s->decays, &nb_decays);
327 count_items(s->points, &nb_points);
329 if ((nb_attacks > outlink->channels) || (nb_decays > outlink->channels)) {
330 av_log(ctx, AV_LOG_ERROR, "Number of attacks/decays bigger than number of channels.\n");
331 return AVERROR(EINVAL);
336 s->channels = av_mallocz_array(outlink->channels, sizeof(*s->channels));
337 s->nb_segments = (nb_points + 4) * 2;
338 s->segments = av_mallocz_array(s->nb_segments, sizeof(*s->segments));
340 if (!s->channels || !s->segments) {
342 return AVERROR(ENOMEM);
346 for (i = 0, new_nb_items = 0; i < nb_attacks; i++) {
347 char *tstr = av_strtok(p, " |", &saveptr);
349 new_nb_items += sscanf(tstr, "%lf", &s->channels[i].attack) == 1;
350 if (s->channels[i].attack < 0) {
352 return AVERROR(EINVAL);
355 nb_attacks = new_nb_items;
358 for (i = 0, new_nb_items = 0; i < nb_decays; i++) {
359 char *tstr = av_strtok(p, " |", &saveptr);
361 new_nb_items += sscanf(tstr, "%lf", &s->channels[i].decay) == 1;
362 if (s->channels[i].decay < 0) {
364 return AVERROR(EINVAL);
367 nb_decays = new_nb_items;
369 if (nb_attacks != nb_decays) {
370 av_log(ctx, AV_LOG_ERROR,
371 "Number of attacks %d differs from number of decays %d.\n",
372 nb_attacks, nb_decays);
374 return AVERROR(EINVAL);
377 #define S(x) s->segments[2 * ((x) + 1)]
379 for (i = 0, new_nb_items = 0; i < nb_points; i++) {
380 char *tstr = av_strtok(p, " |", &saveptr);
382 if (sscanf(tstr, "%lf/%lf", &S(i).x, &S(i).y) != 2) {
383 av_log(ctx, AV_LOG_ERROR,
384 "Invalid and/or missing input/output value.\n");
386 return AVERROR(EINVAL);
388 if (i && S(i - 1).x > S(i).x) {
389 av_log(ctx, AV_LOG_ERROR,
390 "Transfer function input values must be increasing.\n");
392 return AVERROR(EINVAL);
395 av_log(ctx, AV_LOG_DEBUG, "%d: x=%f y=%f\n", i, S(i).x, S(i).y);
400 /* Add 0,0 if necessary */
401 if (num == 0 || S(num - 1).x)
405 #define S(x) s->segments[2 * (x)]
406 /* Add a tail off segment at the start */
407 S(0).x = S(1).x - 2 * s->curve_dB;
411 /* Join adjacent colinear segments */
412 for (i = 2; i < num; i++) {
413 double g1 = (S(i - 1).y - S(i - 2).y) * (S(i - 0).x - S(i - 1).x);
414 double g2 = (S(i - 0).y - S(i - 1).y) * (S(i - 1).x - S(i - 2).x);
420 for (j = --i; j < num; j++)
424 for (i = 0; !i || s->segments[i - 2].x; i += 2) {
425 s->segments[i].y += s->gain_dB;
426 s->segments[i].x *= M_LN10 / 20;
427 s->segments[i].y *= M_LN10 / 20;
430 #define L(x) s->segments[i - (x)]
431 for (i = 4; s->segments[i - 2].x; i += 2) {
432 double x, y, cx, cy, in1, in2, out1, out2, theta, len, r;
435 L(4).b = (L(2).y - L(4).y) / (L(2).x - L(4).x);
438 L(2).b = (L(0).y - L(2).y) / (L(0).x - L(2).x);
440 theta = atan2(L(2).y - L(4).y, L(2).x - L(4).x);
441 len = sqrt(pow(L(2).x - L(4).x, 2.) + pow(L(2).y - L(4).y, 2.));
442 r = FFMIN(radius, len);
443 L(3).x = L(2).x - r * cos(theta);
444 L(3).y = L(2).y - r * sin(theta);
446 theta = atan2(L(0).y - L(2).y, L(0).x - L(2).x);
447 len = sqrt(pow(L(0).x - L(2).x, 2.) + pow(L(0).y - L(2).y, 2.));
448 r = FFMIN(radius, len / 2);
449 x = L(2).x + r * cos(theta);
450 y = L(2).y + r * sin(theta);
452 cx = (L(3).x + L(2).x + x) / 3;
453 cy = (L(3).y + L(2).y + y) / 3;
460 in2 = L(2).x - L(3).x;
461 out2 = L(2).y - L(3).y;
462 L(3).a = (out2 / in2 - out1 / in1) / (in2 - in1);
463 L(3).b = out1 / in1 - L(3).a * in1;
468 s->in_min_lin = exp(s->segments[1].x);
469 s->out_min_lin = exp(s->segments[1].y);
471 for (i = 0; i < outlink->channels; i++) {
472 ChanParam *cp = &s->channels[i];
474 if (cp->attack > 1.0 / sample_rate)
475 cp->attack = 1.0 - exp(-1.0 / (sample_rate * cp->attack));
478 if (cp->decay > 1.0 / sample_rate)
479 cp->decay = 1.0 - exp(-1.0 / (sample_rate * cp->decay));
482 cp->volume = pow(10.0, s->initial_volume / 20);
485 s->delay_samples = s->delay * sample_rate;
486 if (s->delay_samples <= 0) {
487 s->compand = compand_nodelay;
491 s->delay_frame = av_frame_alloc();
492 if (!s->delay_frame) {
494 return AVERROR(ENOMEM);
497 s->delay_frame->format = outlink->format;
498 s->delay_frame->nb_samples = s->delay_samples;
499 s->delay_frame->channel_layout = outlink->channel_layout;
501 err = av_frame_get_buffer(s->delay_frame, 32);
505 outlink->flags |= FF_LINK_FLAG_REQUEST_LOOP;
506 s->compand = compand_delay;
510 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
512 AVFilterContext *ctx = inlink->dst;
513 CompandContext *s = ctx->priv;
515 return s->compand(ctx, frame);
518 static int request_frame(AVFilterLink *outlink)
520 AVFilterContext *ctx = outlink->src;
521 CompandContext *s = ctx->priv;
524 ret = ff_request_frame(ctx->inputs[0]);
526 if (ret == AVERROR_EOF && !ctx->is_disabled && s->delay_count)
527 ret = compand_drain(outlink);
532 static const AVFilterPad compand_inputs[] = {
535 .type = AVMEDIA_TYPE_AUDIO,
536 .filter_frame = filter_frame,
541 static const AVFilterPad compand_outputs[] = {
544 .request_frame = request_frame,
545 .config_props = config_output,
546 .type = AVMEDIA_TYPE_AUDIO,
552 AVFilter ff_af_compand = {
554 .description = NULL_IF_CONFIG_SMALL(
555 "Compress or expand audio dynamic range."),
556 .query_formats = query_formats,
557 .priv_size = sizeof(CompandContext),
558 .priv_class = &compand_class,
561 .inputs = compand_inputs,
562 .outputs = compand_outputs,