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/avassert.h"
26 #include "libavutil/avstring.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/samplefmt.h"
33 typedef struct ChanParam {
39 typedef struct CompandSegment {
44 typedef struct CompandContext {
46 char *attacks, *decays, *points;
47 CompandSegment *segments;
53 double initial_volume;
61 int (*compand)(AVFilterContext *ctx, AVFrame *frame);
64 #define OFFSET(x) offsetof(CompandContext, x)
65 #define A AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
67 static const AVOption compand_options[] = {
68 { "attacks", "set time over which increase of volume is determined", OFFSET(attacks), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, A },
69 { "decays", "set time over which decrease of volume is determined", OFFSET(decays), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, A },
70 { "points", "set points of transfer function", OFFSET(points), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, A },
71 { "soft-knee", "set soft-knee", OFFSET(curve_dB), AV_OPT_TYPE_DOUBLE, {.dbl=0.01}, 0.01, 900, A },
72 { "gain", "set output gain", OFFSET(gain_dB), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -900, 900, A },
73 { "volume", "set initial volume", OFFSET(initial_volume), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -900, 0, A },
74 { "delay", "set delay for samples before sending them to volume adjuster", OFFSET(delay), AV_OPT_TYPE_DOUBLE, {.dbl=0}, 0, 20, A },
78 AVFILTER_DEFINE_CLASS(compand);
80 static av_cold int init(AVFilterContext *ctx)
82 CompandContext *s = ctx->priv;
84 if (!s->attacks || !s->decays || !s->points) {
85 av_log(ctx, AV_LOG_ERROR, "Missing attacks and/or decays and/or points.\n");
86 return AVERROR(EINVAL);
92 static av_cold void uninit(AVFilterContext *ctx)
94 CompandContext *s = ctx->priv;
96 av_freep(&s->channels);
97 av_freep(&s->segments);
99 av_freep(&s->delayptrs[0]);
100 av_freep(&s->delayptrs);
103 static int query_formats(AVFilterContext *ctx)
105 AVFilterChannelLayouts *layouts;
106 AVFilterFormats *formats;
107 static const enum AVSampleFormat sample_fmts[] = {
112 layouts = ff_all_channel_layouts();
114 return AVERROR(ENOMEM);
115 ff_set_common_channel_layouts(ctx, layouts);
117 formats = ff_make_format_list(sample_fmts);
119 return AVERROR(ENOMEM);
120 ff_set_common_formats(ctx, formats);
122 formats = ff_all_samplerates();
124 return AVERROR(ENOMEM);
125 ff_set_common_samplerates(ctx, formats);
130 static void count_items(char *item_str, int *nb_items)
135 for (p = item_str; *p; p++) {
142 static void update_volume(ChanParam *cp, double in)
144 double delta = in - cp->volume;
147 cp->volume += delta * cp->attack;
149 cp->volume += delta * cp->decay;
152 static double get_volume(CompandContext *s, double in_lin)
155 double in_log, out_log;
158 if (in_lin < s->in_min_lin)
159 return s->out_min_lin;
161 in_log = log(in_lin);
164 if (in_log <= s->segments[i + 1].x)
167 cs = &s->segments[i];
169 out_log = cs->y + in_log * (cs->a * in_log + cs->b);
174 static int compand_nodelay(AVFilterContext *ctx, AVFrame *frame)
176 CompandContext *s = ctx->priv;
177 AVFilterLink *inlink = ctx->inputs[0];
178 const int channels = inlink->channels;
179 const int nb_samples = frame->nb_samples;
183 if (av_frame_is_writable(frame)) {
186 out_frame = ff_get_audio_buffer(inlink, nb_samples);
188 return AVERROR(ENOMEM);
189 av_frame_copy_props(out_frame, frame);
192 for (chan = 0; chan < channels; chan++) {
193 const double *src = (double *)frame->extended_data[chan];
194 double *dst = (double *)out_frame->extended_data[chan];
195 ChanParam *cp = &s->channels[chan];
197 for (i = 0; i < nb_samples; i++) {
198 update_volume(cp, fabs(src[i]));
200 dst[i] = av_clipd(src[i] * get_volume(s, cp->volume), -1, 1);
204 if (frame != out_frame)
205 av_frame_free(&frame);
207 return ff_filter_frame(ctx->outputs[0], out_frame);
210 #define MOD(a, b) (((a) >= (b)) ? (a) - (b) : (a))
212 static int compand_delay(AVFilterContext *ctx, AVFrame *frame)
214 CompandContext *s = ctx->priv;
215 AVFilterLink *inlink = ctx->inputs[0];
216 const int channels = inlink->channels;
217 const int nb_samples = frame->nb_samples;
218 int chan, i, av_uninit(dindex), oindex, av_uninit(count);
219 AVFrame *out_frame = NULL;
221 av_assert1(channels > 0); /* would corrupt delay_count and delay_index */
223 for (chan = 0; chan < channels; chan++) {
224 const double *src = (double *)frame->extended_data[chan];
225 double *dbuf = (double *)s->delayptrs[chan];
226 ChanParam *cp = &s->channels[chan];
229 count = s->delay_count;
230 dindex = s->delay_index;
231 for (i = 0, oindex = 0; i < nb_samples; i++) {
232 const double in = src[i];
233 update_volume(cp, fabs(in));
235 if (count >= s->delay_samples) {
237 out_frame = ff_get_audio_buffer(inlink, nb_samples - i);
239 return AVERROR(ENOMEM);
240 av_frame_copy_props(out_frame, frame);
241 out_frame->pts = s->pts;
242 s->pts += av_rescale_q(nb_samples - i, (AVRational){1, inlink->sample_rate}, inlink->time_base);
245 dst = (double *)out_frame->extended_data[chan];
246 dst[oindex++] = av_clipd(dbuf[dindex] * get_volume(s, cp->volume), -1, 1);
252 dindex = MOD(dindex + 1, s->delay_samples);
256 s->delay_count = count;
257 s->delay_index = dindex;
259 av_frame_free(&frame);
260 return out_frame ? ff_filter_frame(ctx->outputs[0], out_frame) : 0;
263 static int compand_drain(AVFilterLink *outlink)
265 AVFilterContext *ctx = outlink->src;
266 CompandContext *s = ctx->priv;
267 const int channels = outlink->channels;
269 AVFrame *frame = NULL;
271 frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->delay_count));
273 return AVERROR(ENOMEM);
275 s->pts += av_rescale_q(frame->nb_samples, (AVRational){1, outlink->sample_rate}, outlink->time_base);
277 for (chan = 0; chan < channels; chan++) {
278 double *dbuf = (double *)s->delayptrs[chan];
279 double *dst = (double *)frame->extended_data[chan];
280 ChanParam *cp = &s->channels[chan];
282 dindex = s->delay_index;
283 for (i = 0; i < frame->nb_samples; i++) {
284 dst[i] = av_clipd(dbuf[dindex] * get_volume(s, cp->volume), -1, 1);
285 dindex = MOD(dindex + 1, s->delay_samples);
288 s->delay_count -= frame->nb_samples;
289 s->delay_index = dindex;
291 return ff_filter_frame(outlink, frame);
294 static int config_output(AVFilterLink *outlink)
296 AVFilterContext *ctx = outlink->src;
297 CompandContext *s = ctx->priv;
298 const int sample_rate = outlink->sample_rate;
299 double radius = s->curve_dB * M_LN10 / 20;
300 int nb_attacks, nb_decays, nb_points;
301 char *p, *saveptr = NULL;
302 int new_nb_items, num;
305 count_items(s->attacks, &nb_attacks);
306 count_items(s->decays, &nb_decays);
307 count_items(s->points, &nb_points);
309 if ((nb_attacks > outlink->channels) || (nb_decays > outlink->channels)) {
310 av_log(ctx, AV_LOG_ERROR, "Number of attacks/decays bigger than number of channels.\n");
311 return AVERROR(EINVAL);
316 s->channels = av_mallocz_array(outlink->channels, sizeof(*s->channels));
317 s->segments = av_mallocz_array((nb_points + 4) * 2, sizeof(*s->segments));
319 if (!s->channels || !s->segments)
320 return AVERROR(ENOMEM);
323 for (i = 0, new_nb_items = 0; i < nb_attacks; i++) {
324 char *tstr = av_strtok(p, " ", &saveptr);
326 new_nb_items += sscanf(tstr, "%lf", &s->channels[i].attack) == 1;
327 if (s->channels[i].attack < 0)
328 return AVERROR(EINVAL);
330 nb_attacks = new_nb_items;
333 for (i = 0, new_nb_items = 0; i < nb_decays; i++) {
334 char *tstr = av_strtok(p, " ", &saveptr);
336 new_nb_items += sscanf(tstr, "%lf", &s->channels[i].decay) == 1;
337 if (s->channels[i].decay < 0)
338 return AVERROR(EINVAL);
340 nb_decays = new_nb_items;
342 if (nb_attacks != nb_decays) {
343 av_log(ctx, AV_LOG_ERROR, "Number of attacks %d differs from number of decays %d.\n", nb_attacks, nb_decays);
344 return AVERROR(EINVAL);
347 #define S(x) s->segments[2 * ((x) + 1)]
349 for (i = 0, new_nb_items = 0; i < nb_points; i++) {
350 char *tstr = av_strtok(p, " ", &saveptr);
352 if (sscanf(tstr, "%lf/%lf", &S(i).x, &S(i).y) != 2) {
353 av_log(ctx, AV_LOG_ERROR, "Invalid and/or missing input/output value.\n");
354 return AVERROR(EINVAL);
356 if (i && S(i - 1).x > S(i).x) {
357 av_log(ctx, AV_LOG_ERROR, "Transfer function input values must be increasing.\n");
358 return AVERROR(EINVAL);
361 av_log(ctx, AV_LOG_DEBUG, "%d: x=%f y=%f\n", i, S(i).x, S(i).y);
366 /* Add 0,0 if necessary */
367 if (num == 0 || S(num - 1).x)
371 #define S(x) s->segments[2 * (x)]
372 /* Add a tail off segment at the start */
373 S(0).x = S(1).x - 2 * s->curve_dB;
377 /* Join adjacent colinear segments */
378 for (i = 2; i < num; i++) {
379 double g1 = (S(i - 1).y - S(i - 2).y) * (S(i - 0).x - S(i - 1).x);
380 double g2 = (S(i - 0).y - S(i - 1).y) * (S(i - 1).x - S(i - 2).x);
386 for (j = --i; j < num; j++)
390 for (i = 0; !i || s->segments[i - 2].x; i += 2) {
391 s->segments[i].y += s->gain_dB;
392 s->segments[i].x *= M_LN10 / 20;
393 s->segments[i].y *= M_LN10 / 20;
396 #define L(x) s->segments[i - (x)]
397 for (i = 4; s->segments[i - 2].x; i += 2) {
398 double x, y, cx, cy, in1, in2, out1, out2, theta, len, r;
401 L(4).b = (L(2).y - L(4).y) / (L(2).x - L(4).x);
404 L(2).b = (L(0).y - L(2).y) / (L(0).x - L(2).x);
406 theta = atan2(L(2).y - L(4).y, L(2).x - L(4).x);
407 len = sqrt(pow(L(2).x - L(4).x, 2.) + pow(L(2).y - L(4).y, 2.));
408 r = FFMIN(radius, len);
409 L(3).x = L(2).x - r * cos(theta);
410 L(3).y = L(2).y - r * sin(theta);
412 theta = atan2(L(0).y - L(2).y, L(0).x - L(2).x);
413 len = sqrt(pow(L(0).x - L(2).x, 2.) + pow(L(0).y - L(2).y, 2.));
414 r = FFMIN(radius, len / 2);
415 x = L(2).x + r * cos(theta);
416 y = L(2).y + r * sin(theta);
418 cx = (L(3).x + L(2).x + x) / 3;
419 cy = (L(3).y + L(2).y + y) / 3;
426 in2 = L(2).x - L(3).x;
427 out2 = L(2).y - L(3).y;
428 L(3).a = (out2 / in2 - out1 / in1) / (in2-in1);
429 L(3).b = out1 / in1 - L(3).a * in1;
434 s->in_min_lin = exp(s->segments[1].x);
435 s->out_min_lin = exp(s->segments[1].y);
437 for (i = 0; i < outlink->channels; i++) {
438 ChanParam *cp = &s->channels[i];
440 if (cp->attack > 1.0 / sample_rate)
441 cp->attack = 1.0 - exp(-1.0 / (sample_rate * cp->attack));
444 if (cp->decay > 1.0 / sample_rate)
445 cp->decay = 1.0 - exp(-1.0 / (sample_rate * cp->decay));
448 cp->volume = pow(10.0, s->initial_volume / 20);
451 s->delay_samples = s->delay * sample_rate;
452 if (s->delay_samples > 0) {
454 if ((ret = av_samples_alloc_array_and_samples(&s->delayptrs, NULL,
457 outlink->format, 0)) < 0)
459 s->compand = compand_delay;
460 outlink->flags |= FF_LINK_FLAG_REQUEST_LOOP;
462 s->compand = compand_nodelay;
467 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
469 AVFilterContext *ctx = inlink->dst;
470 CompandContext *s = ctx->priv;
472 return s->compand(ctx, frame);
475 static int request_frame(AVFilterLink *outlink)
477 AVFilterContext *ctx = outlink->src;
478 CompandContext *s = ctx->priv;
481 ret = ff_request_frame(ctx->inputs[0]);
483 if (ret == AVERROR_EOF && !ctx->is_disabled && s->delay_count)
484 ret = compand_drain(outlink);
489 static const AVFilterPad compand_inputs[] = {
492 .type = AVMEDIA_TYPE_AUDIO,
493 .filter_frame = filter_frame,
498 static const AVFilterPad compand_outputs[] = {
501 .request_frame = request_frame,
502 .config_props = config_output,
503 .type = AVMEDIA_TYPE_AUDIO,
508 AVFilter avfilter_af_compand = {
510 .description = NULL_IF_CONFIG_SMALL("Compress or expand audio dynamic range."),
511 .query_formats = query_formats,
512 .priv_size = sizeof(CompandContext),
513 .priv_class = &compand_class,
516 .inputs = compand_inputs,
517 .outputs = compand_outputs,