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 libav.
10 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 * audio compand filter
32 #include "libavutil/channel_layout.h"
33 #include "libavutil/common.h"
34 #include "libavutil/mathematics.h"
35 #include "libavutil/mem.h"
36 #include "libavutil/opt.h"
42 typedef struct ChanParam {
48 typedef struct CompandSegment {
53 typedef struct CompandContext {
57 char *attacks, *decays, *points;
58 CompandSegment *segments;
64 double initial_volume;
72 int (*compand)(AVFilterContext *ctx, AVFrame *frame);
75 #define OFFSET(x) offsetof(CompandContext, x)
76 #define A AV_OPT_FLAG_AUDIO_PARAM
78 static const AVOption compand_options[] = {
79 { "attacks", "set time over which increase of volume is determined", OFFSET(attacks), AV_OPT_TYPE_STRING, { .str = "0.3" }, 0, 0, A },
80 { "decays", "set time over which decrease of volume is determined", OFFSET(decays), AV_OPT_TYPE_STRING, { .str = "0.8" }, 0, 0, A },
81 { "points", "set points of transfer function", OFFSET(points), AV_OPT_TYPE_STRING, { .str = "-70/-70|-60/-20" }, 0, 0, A },
82 { "soft-knee", "set soft-knee", OFFSET(curve_dB), AV_OPT_TYPE_DOUBLE, { .dbl = 0.01 }, 0.01, 900, A },
83 { "gain", "set output gain", OFFSET(gain_dB), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, -900, 900, A },
84 { "volume", "set initial volume", OFFSET(initial_volume), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, -900, 0, A },
85 { "delay", "set delay for samples before sending them to volume adjuster", OFFSET(delay), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, 0, 20, A },
89 static const AVClass compand_class = {
90 .class_name = "compand filter",
91 .item_name = av_default_item_name,
92 .option = compand_options,
93 .version = LIBAVUTIL_VERSION_INT,
96 static av_cold int init(AVFilterContext *ctx)
98 CompandContext *s = ctx->priv;
99 s->pts = AV_NOPTS_VALUE;
103 static av_cold void uninit(AVFilterContext *ctx)
105 CompandContext *s = ctx->priv;
107 av_freep(&s->channels);
108 av_freep(&s->segments);
109 av_frame_free(&s->delay_frame);
112 static int query_formats(AVFilterContext *ctx)
114 AVFilterChannelLayouts *layouts;
115 AVFilterFormats *formats;
116 static const enum AVSampleFormat sample_fmts[] = {
121 layouts = ff_all_channel_layouts();
123 return AVERROR(ENOMEM);
124 ff_set_common_channel_layouts(ctx, layouts);
126 formats = ff_make_format_list(sample_fmts);
128 return AVERROR(ENOMEM);
129 ff_set_common_formats(ctx, formats);
131 formats = ff_all_samplerates();
133 return AVERROR(ENOMEM);
134 ff_set_common_samplerates(ctx, formats);
139 static void count_items(char *item_str, int *nb_items)
144 for (p = item_str; *p; p++) {
150 static void update_volume(ChanParam *cp, float in)
152 float delta = in - cp->volume;
155 cp->volume += delta * cp->attack;
157 cp->volume += delta * cp->decay;
160 static float get_volume(CompandContext *s, float in_lin)
163 float in_log, out_log;
166 if (in_lin < s->in_min_lin)
167 return s->out_min_lin;
169 in_log = logf(in_lin);
171 for (i = 1; i < s->nb_segments; i++)
172 if (in_log <= s->segments[i].x)
174 cs = &s->segments[i - 1];
176 out_log = cs->y + in_log * (cs->a * in_log + cs->b);
178 return expf(out_log);
181 static int compand_nodelay(AVFilterContext *ctx, AVFrame *frame)
183 CompandContext *s = ctx->priv;
184 AVFilterLink *inlink = ctx->inputs[0];
185 const int channels = s->nb_channels;
186 const int nb_samples = frame->nb_samples;
191 if (av_frame_is_writable(frame)) {
194 out_frame = ff_get_audio_buffer(inlink, nb_samples);
196 av_frame_free(&frame);
197 return AVERROR(ENOMEM);
199 err = av_frame_copy_props(out_frame, frame);
201 av_frame_free(&out_frame);
202 av_frame_free(&frame);
207 for (chan = 0; chan < channels; chan++) {
208 const float *src = (float *)frame->extended_data[chan];
209 float *dst = (float *)out_frame->extended_data[chan];
210 ChanParam *cp = &s->channels[chan];
212 for (i = 0; i < nb_samples; i++) {
213 update_volume(cp, fabs(src[i]));
215 dst[i] = av_clipf(src[i] * get_volume(s, cp->volume), -1.0f, 1.0f);
219 if (frame != out_frame)
220 av_frame_free(&frame);
222 return ff_filter_frame(ctx->outputs[0], out_frame);
225 #define MOD(a, b) (((a) >= (b)) ? (a) - (b) : (a))
227 static int compand_delay(AVFilterContext *ctx, AVFrame *frame)
229 CompandContext *s = ctx->priv;
230 AVFilterLink *inlink = ctx->inputs[0];
231 const int channels = s->nb_channels;
232 const int nb_samples = frame->nb_samples;
233 int chan, i, dindex = 0, oindex, count = 0;
234 AVFrame *out_frame = NULL;
237 if (s->pts == AV_NOPTS_VALUE) {
238 s->pts = (frame->pts == AV_NOPTS_VALUE) ? 0 : frame->pts;
241 for (chan = 0; chan < channels; chan++) {
242 AVFrame *delay_frame = s->delay_frame;
243 const float *src = (float *)frame->extended_data[chan];
244 float *dbuf = (float *)delay_frame->extended_data[chan];
245 ChanParam *cp = &s->channels[chan];
248 count = s->delay_count;
249 dindex = s->delay_index;
250 for (i = 0, oindex = 0; i < nb_samples; i++) {
251 const float in = src[i];
252 update_volume(cp, fabs(in));
254 if (count >= s->delay_samples) {
256 out_frame = ff_get_audio_buffer(inlink, nb_samples - i);
258 av_frame_free(&frame);
259 return AVERROR(ENOMEM);
261 err = av_frame_copy_props(out_frame, frame);
263 av_frame_free(&out_frame);
264 av_frame_free(&frame);
267 out_frame->pts = s->pts;
268 s->pts += av_rescale_q(nb_samples - i,
269 (AVRational){ 1, inlink->sample_rate },
273 dst = (float *)out_frame->extended_data[chan];
274 dst[oindex++] = av_clipf(dbuf[dindex] *
275 get_volume(s, cp->volume), -1.0f, 1.0f);
281 dindex = MOD(dindex + 1, s->delay_samples);
285 s->delay_count = count;
286 s->delay_index = dindex;
288 av_frame_free(&frame);
289 return out_frame ? ff_filter_frame(ctx->outputs[0], out_frame) : 0;
292 static int compand_drain(AVFilterLink *outlink)
294 AVFilterContext *ctx = outlink->src;
295 CompandContext *s = ctx->priv;
296 const int channels = s->nb_channels;
297 AVFrame *frame = NULL;
300 /* 2048 is to limit output frame size during drain */
301 frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->delay_count));
303 return AVERROR(ENOMEM);
305 s->pts += av_rescale_q(frame->nb_samples,
306 (AVRational){ 1, outlink->sample_rate }, outlink->time_base);
308 for (chan = 0; chan < channels; chan++) {
309 AVFrame *delay_frame = s->delay_frame;
310 float *dbuf = (float *)delay_frame->extended_data[chan];
311 float *dst = (float *)frame->extended_data[chan];
312 ChanParam *cp = &s->channels[chan];
314 dindex = s->delay_index;
315 for (i = 0; i < frame->nb_samples; i++) {
316 dst[i] = av_clipf(dbuf[dindex] * get_volume(s, cp->volume),
318 dindex = MOD(dindex + 1, s->delay_samples);
321 s->delay_count -= frame->nb_samples;
322 s->delay_index = dindex;
324 return ff_filter_frame(outlink, frame);
327 static int config_output(AVFilterLink *outlink)
329 AVFilterContext *ctx = outlink->src;
330 CompandContext *s = ctx->priv;
331 const int sample_rate = outlink->sample_rate;
332 double radius = s->curve_dB * M_LN10 / 20.0;
333 char *p, *saveptr = NULL;
335 av_get_channel_layout_nb_channels(outlink->channel_layout);
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->nb_channels = channels;
360 s->channels = av_mallocz_array(channels, sizeof(*s->channels));
361 s->nb_segments = (nb_points + 4) * 2;
362 s->segments = av_mallocz_array(s->nb_segments, sizeof(*s->segments));
364 if (!s->channels || !s->segments) {
366 return AVERROR(ENOMEM);
370 for (i = 0, new_nb_items = 0; i < nb_attacks; i++) {
371 char *tstr = strtok_r(p, "|", &saveptr);
373 new_nb_items += sscanf(tstr, "%f", &s->channels[i].attack) == 1;
374 if (s->channels[i].attack < 0) {
376 return AVERROR(EINVAL);
379 nb_attacks = new_nb_items;
382 for (i = 0, new_nb_items = 0; i < nb_decays; i++) {
383 char *tstr = strtok_r(p, "|", &saveptr);
385 new_nb_items += sscanf(tstr, "%f", &s->channels[i].decay) == 1;
386 if (s->channels[i].decay < 0) {
388 return AVERROR(EINVAL);
391 nb_decays = new_nb_items;
393 if (nb_attacks != nb_decays) {
394 av_log(ctx, AV_LOG_ERROR,
395 "Number of attacks %d differs from number of decays %d.\n",
396 nb_attacks, nb_decays);
398 return AVERROR(EINVAL);
401 #define S(x) s->segments[2 * ((x) + 1)]
403 for (i = 0, new_nb_items = 0; i < nb_points; i++) {
404 char *tstr = strtok_r(p, "|", &saveptr);
406 if (sscanf(tstr, "%f/%f", &S(i).x, &S(i).y) != 2) {
407 av_log(ctx, AV_LOG_ERROR,
408 "Invalid and/or missing input/output value.\n");
410 return AVERROR(EINVAL);
412 if (i && S(i - 1).x > S(i).x) {
413 av_log(ctx, AV_LOG_ERROR,
414 "Transfer function input values must be increasing.\n");
416 return AVERROR(EINVAL);
419 av_log(ctx, AV_LOG_DEBUG, "%d: x=%f y=%f\n", i, S(i).x, S(i).y);
424 /* Add 0,0 if necessary */
425 if (num == 0 || S(num - 1).x)
429 #define S(x) s->segments[2 * (x)]
430 /* Add a tail off segment at the start */
431 S(0).x = S(1).x - 2 * s->curve_dB;
435 /* Join adjacent colinear segments */
436 for (i = 2; i < num; i++) {
437 double g1 = (S(i - 1).y - S(i - 2).y) * (S(i - 0).x - S(i - 1).x);
438 double g2 = (S(i - 0).y - S(i - 1).y) * (S(i - 1).x - S(i - 2).x);
441 /* here we purposefully lose precision so that we can compare floats */
445 for (j = --i; j < num; j++)
449 for (i = 0; !i || s->segments[i - 2].x; i += 2) {
450 s->segments[i].y += s->gain_dB;
451 s->segments[i].x *= M_LN10 / 20;
452 s->segments[i].y *= M_LN10 / 20;
455 #define L(x) s->segments[i - (x)]
456 for (i = 4; s->segments[i - 2].x; i += 2) {
457 double x, y, cx, cy, in1, in2, out1, out2, theta, len, r;
460 L(4).b = (L(2).y - L(4).y) / (L(2).x - L(4).x);
463 L(2).b = (L(0).y - L(2).y) / (L(0).x - L(2).x);
465 theta = atan2(L(2).y - L(4).y, L(2).x - L(4).x);
466 len = sqrt(pow(L(2).x - L(4).x, 2.) + pow(L(2).y - L(4).y, 2.));
467 r = FFMIN(radius, len);
468 L(3).x = L(2).x - r * cos(theta);
469 L(3).y = L(2).y - r * sin(theta);
471 theta = atan2(L(0).y - L(2).y, L(0).x - L(2).x);
472 len = sqrt(pow(L(0).x - L(2).x, 2.) + pow(L(0).y - L(2).y, 2.));
473 r = FFMIN(radius, len / 2);
474 x = L(2).x + r * cos(theta);
475 y = L(2).y + r * sin(theta);
477 cx = (L(3).x + L(2).x + x) / 3;
478 cy = (L(3).y + L(2).y + y) / 3;
485 in2 = L(2).x - L(3).x;
486 out2 = L(2).y - L(3).y;
487 L(3).a = (out2 / in2 - out1 / in1) / (in2 - in1);
488 L(3).b = out1 / in1 - L(3).a * in1;
493 s->in_min_lin = exp(s->segments[1].x);
494 s->out_min_lin = exp(s->segments[1].y);
496 for (i = 0; i < channels; i++) {
497 ChanParam *cp = &s->channels[i];
499 if (cp->attack > 1.0 / sample_rate)
500 cp->attack = 1.0 - exp(-1.0 / (sample_rate * cp->attack));
503 if (cp->decay > 1.0 / sample_rate)
504 cp->decay = 1.0 - exp(-1.0 / (sample_rate * cp->decay));
507 cp->volume = pow(10.0, s->initial_volume / 20);
510 s->delay_samples = s->delay * sample_rate;
511 if (s->delay_samples <= 0) {
512 s->compand = compand_nodelay;
516 s->delay_frame = av_frame_alloc();
517 if (!s->delay_frame) {
519 return AVERROR(ENOMEM);
522 s->delay_frame->format = outlink->format;
523 s->delay_frame->nb_samples = s->delay_samples;
524 s->delay_frame->channel_layout = outlink->channel_layout;
526 err = av_frame_get_buffer(s->delay_frame, 32);
530 s->compand = compand_delay;
534 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
536 AVFilterContext *ctx = inlink->dst;
537 CompandContext *s = ctx->priv;
539 return s->compand(ctx, frame);
542 static int request_frame(AVFilterLink *outlink)
544 AVFilterContext *ctx = outlink->src;
545 CompandContext *s = ctx->priv;
548 ret = ff_request_frame(ctx->inputs[0]);
550 if (ret == AVERROR_EOF && s->delay_count)
551 ret = compand_drain(outlink);
556 static const AVFilterPad compand_inputs[] = {
559 .type = AVMEDIA_TYPE_AUDIO,
560 .filter_frame = filter_frame,
565 static const AVFilterPad compand_outputs[] = {
568 .request_frame = request_frame,
569 .config_props = config_output,
570 .type = AVMEDIA_TYPE_AUDIO,
576 AVFilter ff_af_compand = {
578 .description = NULL_IF_CONFIG_SMALL(
579 "Compress or expand audio dynamic range."),
580 .query_formats = query_formats,
581 .priv_size = sizeof(CompandContext),
582 .priv_class = &compand_class,
585 .inputs = compand_inputs,
586 .outputs = compand_outputs,