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
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "libavutil/avstring.h"
26 #include "libavutil/opt.h"
27 #include "libavutil/samplefmt.h"
32 typedef struct ChanParam {
38 typedef struct CompandSegment {
43 typedef struct CompandContext {
45 char *attacks, *decays, *points;
46 CompandSegment *segments;
52 double initial_volume;
60 int (*compand)(AVFilterContext *ctx, AVFrame *frame);
63 #define OFFSET(x) offsetof(CompandContext, x)
64 #define A AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
66 static const AVOption compand_options[] = {
67 { "attacks", "set time over which increase of volume is determined", OFFSET(attacks), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, A },
68 { "decays", "set time over which decrease of volume is determined", OFFSET(decays), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, A },
69 { "points", "set points of transfer function", OFFSET(points), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, A },
70 { "soft-knee", "set soft-knee", OFFSET(curve_dB), AV_OPT_TYPE_DOUBLE, {.dbl=0.01}, 0.01, 900, A },
71 { "gain", "set output gain", OFFSET(gain_dB), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -900, 900, A },
72 { "volume", "set initial volume", OFFSET(initial_volume), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -900, 0, A },
73 { "delay", "set delay for samples before sending them to volume adjuster", OFFSET(delay), AV_OPT_TYPE_DOUBLE, {.dbl=0}, 0, 20, A },
77 AVFILTER_DEFINE_CLASS(compand);
79 static av_cold int init(AVFilterContext *ctx)
81 CompandContext *s = ctx->priv;
83 if (!s->attacks || !s->decays || !s->points) {
84 av_log(ctx, AV_LOG_ERROR, "Missing attacks and/or decays and/or points.\n");
85 return AVERROR(EINVAL);
91 static av_cold void uninit(AVFilterContext *ctx)
93 CompandContext *s = ctx->priv;
95 av_freep(&s->channels);
96 av_freep(&s->segments);
98 av_freep(&s->delayptrs[0]);
99 av_freep(&s->delayptrs);
102 static int query_formats(AVFilterContext *ctx)
104 AVFilterChannelLayouts *layouts;
105 AVFilterFormats *formats;
106 static const enum AVSampleFormat sample_fmts[] = {
111 layouts = ff_all_channel_layouts();
113 return AVERROR(ENOMEM);
114 ff_set_common_channel_layouts(ctx, layouts);
116 formats = ff_make_format_list(sample_fmts);
118 return AVERROR(ENOMEM);
119 ff_set_common_formats(ctx, formats);
121 formats = ff_all_samplerates();
123 return AVERROR(ENOMEM);
124 ff_set_common_samplerates(ctx, formats);
129 static void count_items(char *item_str, int *nb_items)
134 for (p = item_str; *p; p++) {
141 static void update_volume(ChanParam *cp, double in)
143 double delta = in - cp->volume;
146 cp->volume += delta * cp->attack;
148 cp->volume += delta * cp->decay;
151 static double get_volume(CompandContext *s, double in_lin)
154 double in_log, out_log;
157 if (in_lin < s->in_min_lin)
158 return s->out_min_lin;
160 in_log = log(in_lin);
163 if (in_log <= s->segments[i + 1].x)
166 cs = &s->segments[i];
168 out_log = cs->y + in_log * (cs->a * in_log + cs->b);
173 static int compand_nodelay(AVFilterContext *ctx, AVFrame *frame)
175 CompandContext *s = ctx->priv;
176 AVFilterLink *inlink = ctx->inputs[0];
177 const int channels = inlink->channels;
178 const int nb_samples = frame->nb_samples;
182 if (av_frame_is_writable(frame)) {
185 out_frame = ff_get_audio_buffer(inlink, nb_samples);
187 return AVERROR(ENOMEM);
188 av_frame_copy_props(out_frame, frame);
191 for (chan = 0; chan < channels; chan++) {
192 const double *src = (double *)frame->data[chan];
193 double *dst = (double *)out_frame->data[chan];
194 ChanParam *cp = &s->channels[chan];
196 for (i = 0; i < nb_samples; i++) {
197 update_volume(cp, fabs(src[i]));
199 dst[i] = av_clipd(src[i] * get_volume(s, cp->volume), -1, 1);
203 if (frame != out_frame)
204 av_frame_free(&frame);
206 return ff_filter_frame(ctx->outputs[0], out_frame);
209 #define MOD(a, b) (((a) >= (b)) ? (a) - (b) : (a))
211 static int compand_delay(AVFilterContext *ctx, AVFrame *frame)
213 CompandContext *s = ctx->priv;
214 AVFilterLink *inlink = ctx->inputs[0];
215 const int channels = inlink->channels;
216 const int nb_samples = frame->nb_samples;
217 int chan, i, dindex, oindex, count;
218 AVFrame *out_frame = NULL;
220 for (chan = 0; chan < channels; chan++) {
221 const double *src = (double *)frame->data[chan];
222 double *dbuf = (double *)s->delayptrs[chan];
223 ChanParam *cp = &s->channels[chan];
226 count = s->delay_count;
227 dindex = s->delay_index;
228 for (i = 0, oindex = 0; i < nb_samples; i++) {
229 const double in = src[i];
230 update_volume(cp, fabs(in));
232 if (count >= s->delay_samples) {
234 out_frame = ff_get_audio_buffer(inlink, nb_samples - i);
236 return AVERROR(ENOMEM);
237 av_frame_copy_props(out_frame, frame);
238 out_frame->pts = s->pts;
239 s->pts += av_rescale_q(nb_samples - i, (AVRational){1, inlink->sample_rate}, inlink->time_base);
242 dst = (double *)out_frame->data[chan];
243 dst[oindex++] = av_clipd(dbuf[dindex] * get_volume(s, cp->volume), -1, 1);
249 dindex = MOD(dindex + 1, s->delay_samples);
253 s->delay_count = count;
254 s->delay_index = dindex;
256 av_frame_free(&frame);
257 return out_frame ? ff_filter_frame(ctx->outputs[0], out_frame) : 0;
260 static int compand_drain(AVFilterLink *outlink)
262 AVFilterContext *ctx = outlink->src;
263 CompandContext *s = ctx->priv;
264 const int channels = outlink->channels;
266 AVFrame *frame = NULL;
268 frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->delay_count));
270 return AVERROR(ENOMEM);
272 s->pts += av_rescale_q(frame->nb_samples, (AVRational){1, outlink->sample_rate}, outlink->time_base);
274 for (chan = 0; chan < channels; chan++) {
275 double *dbuf = (double *)s->delayptrs[chan];
276 double *dst = (double *)frame->data[chan];
277 ChanParam *cp = &s->channels[chan];
279 dindex = s->delay_index;
280 for (i = 0; i < frame->nb_samples; i++) {
281 dst[i] = av_clipd(dbuf[dindex] * get_volume(s, cp->volume), -1, 1);
282 dindex = MOD(dindex + 1, s->delay_samples);
285 s->delay_count -= frame->nb_samples;
286 s->delay_index = dindex;
288 return ff_filter_frame(outlink, frame);
291 static int config_output(AVFilterLink *outlink)
293 AVFilterContext *ctx = outlink->src;
294 CompandContext *s = ctx->priv;
295 const int sample_rate = outlink->sample_rate;
296 double radius = s->curve_dB * M_LN10 / 20;
297 int nb_attacks, nb_decays, nb_points;
298 char *p, *saveptr = NULL;
299 int new_nb_items, num;
302 count_items(s->attacks, &nb_attacks);
303 count_items(s->decays, &nb_decays);
304 count_items(s->points, &nb_points);
306 if ((nb_attacks > outlink->channels) || (nb_decays > outlink->channels)) {
307 av_log(ctx, AV_LOG_ERROR, "Number of attacks/decays bigger than number of channels.\n");
308 return AVERROR(EINVAL);
313 s->channels = av_mallocz_array(outlink->channels, sizeof(*s->channels));
314 s->segments = av_mallocz_array((nb_points + 4) * 2, sizeof(*s->segments));
316 if (!s->channels || !s->segments)
317 return AVERROR(ENOMEM);
320 for (i = 0, new_nb_items = 0; i < nb_attacks; i++) {
321 char *tstr = av_strtok(p, " ", &saveptr);
323 new_nb_items += sscanf(tstr, "%lf", &s->channels[i].attack) == 1;
324 if (s->channels[i].attack < 0)
325 return AVERROR(EINVAL);
327 nb_attacks = new_nb_items;
330 for (i = 0, new_nb_items = 0; i < nb_decays; i++) {
331 char *tstr = av_strtok(p, " ", &saveptr);
333 new_nb_items += sscanf(tstr, "%lf", &s->channels[i].decay) == 1;
334 if (s->channels[i].decay < 0)
335 return AVERROR(EINVAL);
337 nb_decays = new_nb_items;
339 if (nb_attacks != nb_decays) {
340 av_log(ctx, AV_LOG_ERROR, "Number of attacks %d differs from number of decays %d.\n", nb_attacks, nb_decays);
341 return AVERROR(EINVAL);
344 #define S(x) s->segments[2 * ((x) + 1)]
346 for (i = 0, new_nb_items = 0; i < nb_points; i++) {
347 char *tstr = av_strtok(p, " ", &saveptr);
349 if (sscanf(tstr, "%lf/%lf", &S(i).x, &S(i).y) != 2) {
350 av_log(ctx, AV_LOG_ERROR, "Invalid and/or missing input/output value.\n");
351 return AVERROR(EINVAL);
353 if (i && S(i - 1).x > S(i).x) {
354 av_log(ctx, AV_LOG_ERROR, "Transfer function input values must be increasing.\n");
355 return AVERROR(EINVAL);
358 av_log(ctx, AV_LOG_DEBUG, "%d: x=%f y=%f\n", i, S(i).x, S(i).y);
363 /* Add 0,0 if necessary */
364 if (num == 0 || S(num - 1).x)
368 #define S(x) s->segments[2 * (x)]
369 /* Add a tail off segment at the start */
370 S(0).x = S(1).x - 2 * s->curve_dB;
374 /* Join adjacent colinear segments */
375 for (i = 2; i < num; i++) {
376 double g1 = (S(i - 1).y - S(i - 2).y) * (S(i - 0).x - S(i - 1).x);
377 double g2 = (S(i - 0).y - S(i - 1).y) * (S(i - 1).x - S(i - 2).x);
383 for (j = --i; j < num; j++)
387 for (i = 0; !i || s->segments[i - 2].x; i += 2) {
388 s->segments[i].y += s->gain_dB;
389 s->segments[i].x *= M_LN10 / 20;
390 s->segments[i].y *= M_LN10 / 20;
393 #define L(x) s->segments[i - (x)]
394 for (i = 4; s->segments[i - 2].x; i += 2) {
395 double x, y, cx, cy, in1, in2, out1, out2, theta, len, r;
398 L(4).b = (L(2).y - L(4).y) / (L(2).x - L(4).x);
401 L(2).b = (L(0).y - L(2).y) / (L(0).x - L(2).x);
403 theta = atan2(L(2).y - L(4).y, L(2).x - L(4).x);
404 len = sqrt(pow(L(2).x - L(4).x, 2.) + pow(L(2).y - L(4).y, 2.));
405 r = FFMIN(radius, len);
406 L(3).x = L(2).x - r * cos(theta);
407 L(3).y = L(2).y - r * sin(theta);
409 theta = atan2(L(0).y - L(2).y, L(0).x - L(2).x);
410 len = sqrt(pow(L(0).x - L(2).x, 2.) + pow(L(0).y - L(2).y, 2.));
411 r = FFMIN(radius, len / 2);
412 x = L(2).x + r * cos(theta);
413 y = L(2).y + r * sin(theta);
415 cx = (L(3).x + L(2).x + x) / 3;
416 cy = (L(3).y + L(2).y + y) / 3;
423 in2 = L(2).x - L(3).x;
424 out2 = L(2).y - L(3).y;
425 L(3).a = (out2 / in2 - out1 / in1) / (in2-in1);
426 L(3).b = out1 / in1 - L(3).a * in1;
431 s->in_min_lin = exp(s->segments[1].x);
432 s->out_min_lin = exp(s->segments[1].y);
434 for (i = 0; i < outlink->channels; i++) {
435 ChanParam *cp = &s->channels[i];
437 if (cp->attack > 1.0 / sample_rate)
438 cp->attack = 1.0 - exp(-1.0 / (sample_rate * cp->attack));
441 if (cp->decay > 1.0 / sample_rate)
442 cp->decay = 1.0 - exp(-1.0 / (sample_rate * cp->decay));
445 cp->volume = pow(10.0, s->initial_volume / 20);
448 s->delay_samples = s->delay * sample_rate;
449 if (s->delay_samples > 0) {
451 if ((ret = av_samples_alloc_array_and_samples(&s->delayptrs, NULL,
454 outlink->format, 0)) < 0)
456 s->compand = compand_delay;
457 outlink->flags |= FF_LINK_FLAG_REQUEST_LOOP;
459 s->compand = compand_nodelay;
464 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
466 AVFilterContext *ctx = inlink->dst;
467 CompandContext *s = ctx->priv;
469 return s->compand(ctx, frame);
472 static int request_frame(AVFilterLink *outlink)
474 AVFilterContext *ctx = outlink->src;
475 CompandContext *s = ctx->priv;
478 ret = ff_request_frame(ctx->inputs[0]);
480 if (ret == AVERROR_EOF && !ctx->is_disabled && s->delay_count)
481 ret = compand_drain(outlink);
486 static const AVFilterPad compand_inputs[] = {
489 .type = AVMEDIA_TYPE_AUDIO,
490 .filter_frame = filter_frame,
495 static const AVFilterPad compand_outputs[] = {
498 .request_frame = request_frame,
499 .config_props = config_output,
500 .type = AVMEDIA_TYPE_AUDIO,
505 AVFilter avfilter_af_compand = {
507 .description = NULL_IF_CONFIG_SMALL("Compress or expand audio dynamic range."),
508 .query_formats = query_formats,
509 .priv_size = sizeof(CompandContext),
510 .priv_class = &compand_class,
513 .inputs = compand_inputs,
514 .outputs = compand_outputs,