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;
91 if (!s->attacks || !s->decays || !s->points) {
92 av_log(ctx, AV_LOG_ERROR, "Missing attacks and/or decays and/or points.\n");
93 return AVERROR(EINVAL);
99 static av_cold void uninit(AVFilterContext *ctx)
101 CompandContext *s = ctx->priv;
103 av_freep(&s->channels);
104 av_freep(&s->segments);
105 av_frame_free(&s->delay_frame);
108 static int query_formats(AVFilterContext *ctx)
110 AVFilterChannelLayouts *layouts;
111 AVFilterFormats *formats;
112 static const enum AVSampleFormat sample_fmts[] = {
117 layouts = ff_all_channel_layouts();
119 return AVERROR(ENOMEM);
120 ff_set_common_channel_layouts(ctx, layouts);
122 formats = ff_make_format_list(sample_fmts);
124 return AVERROR(ENOMEM);
125 ff_set_common_formats(ctx, formats);
127 formats = ff_all_samplerates();
129 return AVERROR(ENOMEM);
130 ff_set_common_samplerates(ctx, formats);
135 static void count_items(char *item_str, int *nb_items)
140 for (p = item_str; *p; p++) {
141 if (*p == ' ' || *p == '|')
146 static void update_volume(ChanParam *cp, double in)
148 double delta = in - cp->volume;
151 cp->volume += delta * cp->attack;
153 cp->volume += delta * cp->decay;
156 static double get_volume(CompandContext *s, double in_lin)
159 double in_log, out_log;
162 if (in_lin < s->in_min_lin)
163 return s->out_min_lin;
165 in_log = log(in_lin);
167 for (i = 1; i < s->nb_segments; i++)
168 if (in_log <= s->segments[i].x)
170 cs = &s->segments[i - 1];
172 out_log = cs->y + in_log * (cs->a * in_log + cs->b);
177 static int compand_nodelay(AVFilterContext *ctx, AVFrame *frame)
179 CompandContext *s = ctx->priv;
180 AVFilterLink *inlink = ctx->inputs[0];
181 const int channels = inlink->channels;
182 const int nb_samples = frame->nb_samples;
186 if (av_frame_is_writable(frame)) {
189 out_frame = ff_get_audio_buffer(inlink, nb_samples);
191 av_frame_free(&frame);
192 return AVERROR(ENOMEM);
194 av_frame_copy_props(out_frame, frame);
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];
202 for (i = 0; i < nb_samples; i++) {
203 update_volume(cp, fabs(src[i]));
205 dst[i] = av_clipd(src[i] * get_volume(s, cp->volume), -1, 1);
209 if (frame != out_frame)
210 av_frame_free(&frame);
212 return ff_filter_frame(ctx->outputs[0], out_frame);
215 #define MOD(a, b) (((a) >= (b)) ? (a) - (b) : (a))
217 static int compand_delay(AVFilterContext *ctx, AVFrame *frame)
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;
226 av_assert1(channels > 0); /* would corrupt delay_count and delay_index */
228 for (chan = 0; chan < channels; chan++) {
229 AVFrame *delay_frame = s->delay_frame;
230 const double *src = (double *)frame->extended_data[chan];
231 double *dbuf = (double *)delay_frame->extended_data[chan];
232 ChanParam *cp = &s->channels[chan];
235 count = s->delay_count;
236 dindex = s->delay_index;
237 for (i = 0, oindex = 0; i < nb_samples; i++) {
238 const double in = src[i];
239 update_volume(cp, fabs(in));
241 if (count >= s->delay_samples) {
243 out_frame = ff_get_audio_buffer(inlink, nb_samples - i);
245 av_frame_free(&frame);
246 return AVERROR(ENOMEM);
248 av_frame_copy_props(out_frame, frame);
249 out_frame->pts = s->pts;
250 s->pts += av_rescale_q(nb_samples - i,
251 (AVRational){ 1, inlink->sample_rate },
255 dst = (double *)out_frame->extended_data[chan];
256 dst[oindex++] = av_clipd(dbuf[dindex] *
257 get_volume(s, cp->volume), -1, 1);
263 dindex = MOD(dindex + 1, s->delay_samples);
267 s->delay_count = count;
268 s->delay_index = dindex;
270 av_frame_free(&frame);
271 return out_frame ? ff_filter_frame(ctx->outputs[0], out_frame) : 0;
274 static int compand_drain(AVFilterLink *outlink)
276 AVFilterContext *ctx = outlink->src;
277 CompandContext *s = ctx->priv;
278 const int channels = outlink->channels;
280 AVFrame *frame = NULL;
282 frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->delay_count));
284 return AVERROR(ENOMEM);
286 s->pts += av_rescale_q(frame->nb_samples,
287 (AVRational){ 1, outlink->sample_rate }, outlink->time_base);
289 for (chan = 0; chan < channels; chan++) {
290 AVFrame *delay_frame = s->delay_frame;
291 double *dbuf = (double *)delay_frame->extended_data[chan];
292 double *dst = (double *)frame->extended_data[chan];
293 ChanParam *cp = &s->channels[chan];
295 dindex = s->delay_index;
296 for (i = 0; i < frame->nb_samples; i++) {
297 dst[i] = av_clipd(dbuf[dindex] * get_volume(s, cp->volume), -1, 1);
298 dindex = MOD(dindex + 1, s->delay_samples);
301 s->delay_count -= frame->nb_samples;
302 s->delay_index = dindex;
304 return ff_filter_frame(outlink, frame);
307 static int config_output(AVFilterLink *outlink)
309 AVFilterContext *ctx = outlink->src;
310 CompandContext *s = ctx->priv;
311 const int sample_rate = outlink->sample_rate;
312 double radius = s->curve_dB * M_LN10 / 20;
313 int nb_attacks, nb_decays, nb_points;
314 char *p, *saveptr = NULL;
315 int new_nb_items, num;
320 count_items(s->attacks, &nb_attacks);
321 count_items(s->decays, &nb_decays);
322 count_items(s->points, &nb_points);
324 if ((nb_attacks > outlink->channels) || (nb_decays > outlink->channels)) {
325 av_log(ctx, AV_LOG_ERROR, "Number of attacks/decays bigger than number of channels.\n");
326 return AVERROR(EINVAL);
331 s->channels = av_mallocz_array(outlink->channels, sizeof(*s->channels));
332 s->nb_segments = (nb_points + 4) * 2;
333 s->segments = av_mallocz_array(s->nb_segments, sizeof(*s->segments));
335 if (!s->channels || !s->segments) {
337 return AVERROR(ENOMEM);
341 for (i = 0, new_nb_items = 0; i < nb_attacks; i++) {
342 char *tstr = av_strtok(p, " |", &saveptr);
344 new_nb_items += sscanf(tstr, "%lf", &s->channels[i].attack) == 1;
345 if (s->channels[i].attack < 0) {
347 return AVERROR(EINVAL);
350 nb_attacks = new_nb_items;
353 for (i = 0, new_nb_items = 0; i < nb_decays; i++) {
354 char *tstr = av_strtok(p, " |", &saveptr);
356 new_nb_items += sscanf(tstr, "%lf", &s->channels[i].decay) == 1;
357 if (s->channels[i].decay < 0) {
359 return AVERROR(EINVAL);
362 nb_decays = new_nb_items;
364 if (nb_attacks != nb_decays) {
365 av_log(ctx, AV_LOG_ERROR,
366 "Number of attacks %d differs from number of decays %d.\n",
367 nb_attacks, nb_decays);
369 return AVERROR(EINVAL);
372 #define S(x) s->segments[2 * ((x) + 1)]
374 for (i = 0, new_nb_items = 0; i < nb_points; i++) {
375 char *tstr = av_strtok(p, " |", &saveptr);
377 if (sscanf(tstr, "%lf/%lf", &S(i).x, &S(i).y) != 2) {
378 av_log(ctx, AV_LOG_ERROR,
379 "Invalid and/or missing input/output value.\n");
381 return AVERROR(EINVAL);
383 if (i && S(i - 1).x > S(i).x) {
384 av_log(ctx, AV_LOG_ERROR,
385 "Transfer function input values must be increasing.\n");
387 return AVERROR(EINVAL);
390 av_log(ctx, AV_LOG_DEBUG, "%d: x=%f y=%f\n", i, S(i).x, S(i).y);
395 /* Add 0,0 if necessary */
396 if (num == 0 || S(num - 1).x)
400 #define S(x) s->segments[2 * (x)]
401 /* Add a tail off segment at the start */
402 S(0).x = S(1).x - 2 * s->curve_dB;
406 /* Join adjacent colinear segments */
407 for (i = 2; i < num; i++) {
408 double g1 = (S(i - 1).y - S(i - 2).y) * (S(i - 0).x - S(i - 1).x);
409 double g2 = (S(i - 0).y - S(i - 1).y) * (S(i - 1).x - S(i - 2).x);
415 for (j = --i; j < num; j++)
419 for (i = 0; !i || s->segments[i - 2].x; i += 2) {
420 s->segments[i].y += s->gain_dB;
421 s->segments[i].x *= M_LN10 / 20;
422 s->segments[i].y *= M_LN10 / 20;
425 #define L(x) s->segments[i - (x)]
426 for (i = 4; s->segments[i - 2].x; i += 2) {
427 double x, y, cx, cy, in1, in2, out1, out2, theta, len, r;
430 L(4).b = (L(2).y - L(4).y) / (L(2).x - L(4).x);
433 L(2).b = (L(0).y - L(2).y) / (L(0).x - L(2).x);
435 theta = atan2(L(2).y - L(4).y, L(2).x - L(4).x);
436 len = sqrt(pow(L(2).x - L(4).x, 2.) + pow(L(2).y - L(4).y, 2.));
437 r = FFMIN(radius, len);
438 L(3).x = L(2).x - r * cos(theta);
439 L(3).y = L(2).y - r * sin(theta);
441 theta = atan2(L(0).y - L(2).y, L(0).x - L(2).x);
442 len = sqrt(pow(L(0).x - L(2).x, 2.) + pow(L(0).y - L(2).y, 2.));
443 r = FFMIN(radius, len / 2);
444 x = L(2).x + r * cos(theta);
445 y = L(2).y + r * sin(theta);
447 cx = (L(3).x + L(2).x + x) / 3;
448 cy = (L(3).y + L(2).y + y) / 3;
455 in2 = L(2).x - L(3).x;
456 out2 = L(2).y - L(3).y;
457 L(3).a = (out2 / in2 - out1 / in1) / (in2 - in1);
458 L(3).b = out1 / in1 - L(3).a * in1;
463 s->in_min_lin = exp(s->segments[1].x);
464 s->out_min_lin = exp(s->segments[1].y);
466 for (i = 0; i < outlink->channels; i++) {
467 ChanParam *cp = &s->channels[i];
469 if (cp->attack > 1.0 / sample_rate)
470 cp->attack = 1.0 - exp(-1.0 / (sample_rate * cp->attack));
473 if (cp->decay > 1.0 / sample_rate)
474 cp->decay = 1.0 - exp(-1.0 / (sample_rate * cp->decay));
477 cp->volume = pow(10.0, s->initial_volume / 20);
480 s->delay_samples = s->delay * sample_rate;
481 if (s->delay_samples <= 0) {
482 s->compand = compand_nodelay;
486 s->delay_frame = av_frame_alloc();
487 if (!s->delay_frame) {
489 return AVERROR(ENOMEM);
492 s->delay_frame->format = outlink->format;
493 s->delay_frame->nb_samples = s->delay_samples;
494 s->delay_frame->channel_layout = outlink->channel_layout;
496 err = av_frame_get_buffer(s->delay_frame, 32);
500 outlink->flags |= FF_LINK_FLAG_REQUEST_LOOP;
501 s->compand = compand_delay;
505 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
507 AVFilterContext *ctx = inlink->dst;
508 CompandContext *s = ctx->priv;
510 return s->compand(ctx, frame);
513 static int request_frame(AVFilterLink *outlink)
515 AVFilterContext *ctx = outlink->src;
516 CompandContext *s = ctx->priv;
519 ret = ff_request_frame(ctx->inputs[0]);
521 if (ret == AVERROR_EOF && !ctx->is_disabled && s->delay_count)
522 ret = compand_drain(outlink);
527 static const AVFilterPad compand_inputs[] = {
530 .type = AVMEDIA_TYPE_AUDIO,
531 .filter_frame = filter_frame,
536 static const AVFilterPad compand_outputs[] = {
539 .request_frame = request_frame,
540 .config_props = config_output,
541 .type = AVMEDIA_TYPE_AUDIO,
547 AVFilter ff_af_compand = {
549 .description = NULL_IF_CONFIG_SMALL(
550 "Compress or expand audio dynamic range."),
551 .query_formats = query_formats,
552 .priv_size = sizeof(CompandContext),
553 .priv_class = &compand_class,
556 .inputs = compand_inputs,
557 .outputs = compand_outputs,