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/avstring.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/common.h"
33 #include "libavutil/mathematics.h"
34 #include "libavutil/mem.h"
35 #include "libavutil/opt.h"
41 typedef struct ChanParam {
47 typedef struct CompandSegment {
52 typedef struct CompandContext {
56 char *attacks, *decays, *points;
57 CompandSegment *segments;
63 double initial_volume;
71 int (*compand)(AVFilterContext *ctx, AVFrame *frame);
74 #define OFFSET(x) offsetof(CompandContext, x)
75 #define A AV_OPT_FLAG_AUDIO_PARAM
77 static const AVOption compand_options[] = {
78 { "attacks", "set time over which increase of volume is determined", OFFSET(attacks), AV_OPT_TYPE_STRING, { .str = "0.3" }, 0, 0, A },
79 { "decays", "set time over which decrease of volume is determined", OFFSET(decays), AV_OPT_TYPE_STRING, { .str = "0.8" }, 0, 0, A },
80 { "points", "set points of transfer function", OFFSET(points), AV_OPT_TYPE_STRING, { .str = "-70/-70|-60/-20" }, 0, 0, A },
81 { "soft-knee", "set soft-knee", OFFSET(curve_dB), AV_OPT_TYPE_DOUBLE, { .dbl = 0.01 }, 0.01, 900, A },
82 { "gain", "set output gain", OFFSET(gain_dB), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, -900, 900, A },
83 { "volume", "set initial volume", OFFSET(initial_volume), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, -900, 0, A },
84 { "delay", "set delay for samples before sending them to volume adjuster", OFFSET(delay), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, 0, 20, A },
88 static const AVClass compand_class = {
89 .class_name = "compand filter",
90 .item_name = av_default_item_name,
91 .option = compand_options,
92 .version = LIBAVUTIL_VERSION_INT,
95 static av_cold int init(AVFilterContext *ctx)
97 CompandContext *s = ctx->priv;
98 s->pts = AV_NOPTS_VALUE;
102 static av_cold void uninit(AVFilterContext *ctx)
104 CompandContext *s = ctx->priv;
106 av_freep(&s->channels);
107 av_freep(&s->segments);
108 av_frame_free(&s->delay_frame);
111 static int query_formats(AVFilterContext *ctx)
113 AVFilterChannelLayouts *layouts;
114 AVFilterFormats *formats;
115 static const enum AVSampleFormat sample_fmts[] = {
120 layouts = ff_all_channel_layouts();
122 return AVERROR(ENOMEM);
123 ff_set_common_channel_layouts(ctx, layouts);
125 formats = ff_make_format_list(sample_fmts);
127 return AVERROR(ENOMEM);
128 ff_set_common_formats(ctx, formats);
130 formats = ff_all_samplerates();
132 return AVERROR(ENOMEM);
133 ff_set_common_samplerates(ctx, formats);
138 static void count_items(char *item_str, int *nb_items)
143 for (p = item_str; *p; p++) {
149 static void update_volume(ChanParam *cp, float in)
151 float delta = in - cp->volume;
154 cp->volume += delta * cp->attack;
156 cp->volume += delta * cp->decay;
159 static float get_volume(CompandContext *s, float in_lin)
162 float in_log, out_log;
165 if (in_lin < s->in_min_lin)
166 return s->out_min_lin;
168 in_log = logf(in_lin);
170 for (i = 1; i < s->nb_segments; i++)
171 if (in_log <= s->segments[i].x)
173 cs = &s->segments[i - 1];
175 out_log = cs->y + in_log * (cs->a * in_log + cs->b);
177 return expf(out_log);
180 static int compand_nodelay(AVFilterContext *ctx, AVFrame *frame)
182 CompandContext *s = ctx->priv;
183 AVFilterLink *inlink = ctx->inputs[0];
184 const int channels = s->nb_channels;
185 const int nb_samples = frame->nb_samples;
190 if (av_frame_is_writable(frame)) {
193 out_frame = ff_get_audio_buffer(inlink, nb_samples);
195 av_frame_free(&frame);
196 return AVERROR(ENOMEM);
198 err = av_frame_copy_props(out_frame, frame);
200 av_frame_free(&out_frame);
201 av_frame_free(&frame);
206 for (chan = 0; chan < channels; chan++) {
207 const float *src = (float *)frame->extended_data[chan];
208 float *dst = (float *)out_frame->extended_data[chan];
209 ChanParam *cp = &s->channels[chan];
211 for (i = 0; i < nb_samples; i++) {
212 update_volume(cp, fabs(src[i]));
214 dst[i] = av_clipf(src[i] * get_volume(s, cp->volume), -1.0f, 1.0f);
218 if (frame != out_frame)
219 av_frame_free(&frame);
221 return ff_filter_frame(ctx->outputs[0], out_frame);
224 #define MOD(a, b) (((a) >= (b)) ? (a) - (b) : (a))
226 static int compand_delay(AVFilterContext *ctx, AVFrame *frame)
228 CompandContext *s = ctx->priv;
229 AVFilterLink *inlink = ctx->inputs[0];
230 const int channels = s->nb_channels;
231 const int nb_samples = frame->nb_samples;
232 int chan, i, dindex = 0, oindex, count = 0;
233 AVFrame *out_frame = NULL;
236 if (s->pts == AV_NOPTS_VALUE) {
237 s->pts = (frame->pts == AV_NOPTS_VALUE) ? 0 : frame->pts;
240 for (chan = 0; chan < channels; chan++) {
241 AVFrame *delay_frame = s->delay_frame;
242 const float *src = (float *)frame->extended_data[chan];
243 float *dbuf = (float *)delay_frame->extended_data[chan];
244 ChanParam *cp = &s->channels[chan];
247 count = s->delay_count;
248 dindex = s->delay_index;
249 for (i = 0, oindex = 0; i < nb_samples; i++) {
250 const float in = src[i];
251 update_volume(cp, fabs(in));
253 if (count >= s->delay_samples) {
255 out_frame = ff_get_audio_buffer(inlink, nb_samples - i);
257 av_frame_free(&frame);
258 return AVERROR(ENOMEM);
260 err = av_frame_copy_props(out_frame, frame);
262 av_frame_free(&out_frame);
263 av_frame_free(&frame);
266 out_frame->pts = s->pts;
267 s->pts += av_rescale_q(nb_samples - i,
268 (AVRational){ 1, inlink->sample_rate },
272 dst = (float *)out_frame->extended_data[chan];
273 dst[oindex++] = av_clipf(dbuf[dindex] *
274 get_volume(s, cp->volume), -1.0f, 1.0f);
280 dindex = MOD(dindex + 1, s->delay_samples);
284 s->delay_count = count;
285 s->delay_index = dindex;
287 av_frame_free(&frame);
288 return out_frame ? ff_filter_frame(ctx->outputs[0], out_frame) : 0;
291 static int compand_drain(AVFilterLink *outlink)
293 AVFilterContext *ctx = outlink->src;
294 CompandContext *s = ctx->priv;
295 const int channels = s->nb_channels;
296 AVFrame *frame = NULL;
299 /* 2048 is to limit output frame size during drain */
300 frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->delay_count));
302 return AVERROR(ENOMEM);
304 s->pts += av_rescale_q(frame->nb_samples,
305 (AVRational){ 1, outlink->sample_rate }, outlink->time_base);
307 for (chan = 0; chan < channels; chan++) {
308 AVFrame *delay_frame = s->delay_frame;
309 float *dbuf = (float *)delay_frame->extended_data[chan];
310 float *dst = (float *)frame->extended_data[chan];
311 ChanParam *cp = &s->channels[chan];
313 dindex = s->delay_index;
314 for (i = 0; i < frame->nb_samples; i++) {
315 dst[i] = av_clipf(dbuf[dindex] * get_volume(s, cp->volume),
317 dindex = MOD(dindex + 1, s->delay_samples);
320 s->delay_count -= frame->nb_samples;
321 s->delay_index = dindex;
323 return ff_filter_frame(outlink, frame);
326 static int config_output(AVFilterLink *outlink)
328 AVFilterContext *ctx = outlink->src;
329 CompandContext *s = ctx->priv;
330 const int sample_rate = outlink->sample_rate;
331 double radius = s->curve_dB * M_LN10 / 20.0;
332 char *p, *saveptr = NULL;
334 av_get_channel_layout_nb_channels(outlink->channel_layout);
335 int nb_attacks, nb_decays, nb_points;
336 int new_nb_items, num;
341 count_items(s->attacks, &nb_attacks);
342 count_items(s->decays, &nb_decays);
343 count_items(s->points, &nb_points);
346 av_log(ctx, AV_LOG_ERROR, "Invalid number of channels: %d\n", channels);
347 return AVERROR(EINVAL);
350 if (nb_attacks > channels || nb_decays > channels) {
351 av_log(ctx, AV_LOG_ERROR,
352 "Number of attacks/decays bigger than number of channels.\n");
353 return AVERROR(EINVAL);
358 s->nb_channels = channels;
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);
372 new_nb_items += sscanf(tstr, "%f", &s->channels[i].attack) == 1;
373 if (s->channels[i].attack < 0) {
375 return AVERROR(EINVAL);
378 nb_attacks = new_nb_items;
381 for (i = 0, new_nb_items = 0; i < nb_decays; i++) {
382 char *tstr = av_strtok(p, "|", &saveptr);
384 new_nb_items += sscanf(tstr, "%f", &s->channels[i].decay) == 1;
385 if (s->channels[i].decay < 0) {
387 return AVERROR(EINVAL);
390 nb_decays = new_nb_items;
392 if (nb_attacks != nb_decays) {
393 av_log(ctx, AV_LOG_ERROR,
394 "Number of attacks %d differs from number of decays %d.\n",
395 nb_attacks, nb_decays);
397 return AVERROR(EINVAL);
400 #define S(x) s->segments[2 * ((x) + 1)]
402 for (i = 0, new_nb_items = 0; i < nb_points; i++) {
403 char *tstr = av_strtok(p, "|", &saveptr);
405 if (sscanf(tstr, "%f/%f", &S(i).x, &S(i).y) != 2) {
406 av_log(ctx, AV_LOG_ERROR,
407 "Invalid and/or missing input/output value.\n");
409 return AVERROR(EINVAL);
411 if (i && S(i - 1).x > S(i).x) {
412 av_log(ctx, AV_LOG_ERROR,
413 "Transfer function input values must be increasing.\n");
415 return AVERROR(EINVAL);
418 av_log(ctx, AV_LOG_DEBUG, "%d: x=%f y=%f\n", i, S(i).x, S(i).y);
423 /* Add 0,0 if necessary */
424 if (num == 0 || S(num - 1).x)
428 #define S(x) s->segments[2 * (x)]
429 /* Add a tail off segment at the start */
430 S(0).x = S(1).x - 2 * s->curve_dB;
434 /* Join adjacent colinear segments */
435 for (i = 2; i < num; i++) {
436 double g1 = (S(i - 1).y - S(i - 2).y) * (S(i - 0).x - S(i - 1).x);
437 double g2 = (S(i - 0).y - S(i - 1).y) * (S(i - 1).x - S(i - 2).x);
440 /* here we purposefully lose precision so that we can compare floats */
444 for (j = --i; j < num; j++)
448 for (i = 0; !i || s->segments[i - 2].x; i += 2) {
449 s->segments[i].y += s->gain_dB;
450 s->segments[i].x *= M_LN10 / 20;
451 s->segments[i].y *= M_LN10 / 20;
454 #define L(x) s->segments[i - (x)]
455 for (i = 4; s->segments[i - 2].x; i += 2) {
456 double x, y, cx, cy, in1, in2, out1, out2, theta, len, r;
459 L(4).b = (L(2).y - L(4).y) / (L(2).x - L(4).x);
462 L(2).b = (L(0).y - L(2).y) / (L(0).x - L(2).x);
464 theta = atan2(L(2).y - L(4).y, L(2).x - L(4).x);
465 len = sqrt(pow(L(2).x - L(4).x, 2.) + pow(L(2).y - L(4).y, 2.));
466 r = FFMIN(radius, len);
467 L(3).x = L(2).x - r * cos(theta);
468 L(3).y = L(2).y - r * sin(theta);
470 theta = atan2(L(0).y - L(2).y, L(0).x - L(2).x);
471 len = sqrt(pow(L(0).x - L(2).x, 2.) + pow(L(0).y - L(2).y, 2.));
472 r = FFMIN(radius, len / 2);
473 x = L(2).x + r * cos(theta);
474 y = L(2).y + r * sin(theta);
476 cx = (L(3).x + L(2).x + x) / 3;
477 cy = (L(3).y + L(2).y + y) / 3;
484 in2 = L(2).x - L(3).x;
485 out2 = L(2).y - L(3).y;
486 L(3).a = (out2 / in2 - out1 / in1) / (in2 - in1);
487 L(3).b = out1 / in1 - L(3).a * in1;
492 s->in_min_lin = exp(s->segments[1].x);
493 s->out_min_lin = exp(s->segments[1].y);
495 for (i = 0; i < channels; i++) {
496 ChanParam *cp = &s->channels[i];
498 if (cp->attack > 1.0 / sample_rate)
499 cp->attack = 1.0 - exp(-1.0 / (sample_rate * cp->attack));
502 if (cp->decay > 1.0 / sample_rate)
503 cp->decay = 1.0 - exp(-1.0 / (sample_rate * cp->decay));
506 cp->volume = pow(10.0, s->initial_volume / 20);
509 s->delay_samples = s->delay * sample_rate;
510 if (s->delay_samples <= 0) {
511 s->compand = compand_nodelay;
515 s->delay_frame = av_frame_alloc();
516 if (!s->delay_frame) {
518 return AVERROR(ENOMEM);
521 s->delay_frame->format = outlink->format;
522 s->delay_frame->nb_samples = s->delay_samples;
523 s->delay_frame->channel_layout = outlink->channel_layout;
525 err = av_frame_get_buffer(s->delay_frame, 32);
529 s->compand = compand_delay;
533 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
535 AVFilterContext *ctx = inlink->dst;
536 CompandContext *s = ctx->priv;
538 return s->compand(ctx, frame);
541 static int request_frame(AVFilterLink *outlink)
543 AVFilterContext *ctx = outlink->src;
544 CompandContext *s = ctx->priv;
547 ret = ff_request_frame(ctx->inputs[0]);
549 if (ret == AVERROR_EOF && s->delay_count)
550 ret = compand_drain(outlink);
555 static const AVFilterPad compand_inputs[] = {
558 .type = AVMEDIA_TYPE_AUDIO,
559 .filter_frame = filter_frame,
564 static const AVFilterPad compand_outputs[] = {
567 .request_frame = request_frame,
568 .config_props = config_output,
569 .type = AVMEDIA_TYPE_AUDIO,
575 AVFilter ff_af_compand_fork = {
576 .name = "compand_fork",
577 .description = NULL_IF_CONFIG_SMALL(
578 "Compress or expand audio dynamic range."),
579 .query_formats = query_formats,
580 .priv_size = sizeof(CompandContext),
581 .priv_class = &compand_class,
584 .inputs = compand_inputs,
585 .outputs = compand_outputs,