]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_sidechaincompress.c
Merge commit '12b14382861fbf19378afcddaa19cd9a949a86a3'
[ffmpeg] / libavfilter / af_sidechaincompress.c
1 /*
2  * Copyright (C) 2001-2010 Krzysztof Foltman, Markus Schmidt, Thor Harald Johansen and others
3  * Copyright (c) 2015 Paul B Mahol
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * Audio (Sidechain) Compressor filter
25  */
26
27 #include "libavutil/avassert.h"
28 #include "libavutil/channel_layout.h"
29 #include "libavutil/common.h"
30 #include "libavutil/opt.h"
31
32 #include "audio.h"
33 #include "avfilter.h"
34 #include "formats.h"
35 #include "hermite.h"
36 #include "internal.h"
37
38 typedef struct SidechainCompressContext {
39     const AVClass *class;
40
41     double attack, attack_coeff;
42     double release, release_coeff;
43     double lin_slope;
44     double ratio;
45     double threshold;
46     double makeup;
47     double mix;
48     double thres;
49     double knee;
50     double knee_start;
51     double knee_stop;
52     double lin_knee_start;
53     double compressed_knee_stop;
54     int link;
55     int detection;
56
57     AVFrame *input_frame[2];
58 } SidechainCompressContext;
59
60 #define OFFSET(x) offsetof(SidechainCompressContext, x)
61 #define A AV_OPT_FLAG_AUDIO_PARAM
62 #define F AV_OPT_FLAG_FILTERING_PARAM
63
64 static const AVOption options[] = {
65     { "threshold", "set threshold",    OFFSET(threshold), AV_OPT_TYPE_DOUBLE, {.dbl=0.125}, 0.000976563,    1, A|F },
66     { "ratio",     "set ratio",        OFFSET(ratio),     AV_OPT_TYPE_DOUBLE, {.dbl=2},               1,   20, A|F },
67     { "attack",    "set attack",       OFFSET(attack),    AV_OPT_TYPE_DOUBLE, {.dbl=20},           0.01, 2000, A|F },
68     { "release",   "set release",      OFFSET(release),   AV_OPT_TYPE_DOUBLE, {.dbl=250},          0.01, 9000, A|F },
69     { "makeup",    "set make up gain", OFFSET(makeup),    AV_OPT_TYPE_DOUBLE, {.dbl=2},               1,   64, A|F },
70     { "knee",      "set knee",         OFFSET(knee),      AV_OPT_TYPE_DOUBLE, {.dbl=2.82843},         1,    8, A|F },
71     { "link",      "set link type",    OFFSET(link),      AV_OPT_TYPE_INT,    {.i64=0},               0,    1, A|F, "link" },
72     {   "average", 0,                  0,                 AV_OPT_TYPE_CONST,  {.i64=0},               0,    0, A|F, "link" },
73     {   "maximum", 0,                  0,                 AV_OPT_TYPE_CONST,  {.i64=1},               0,    0, A|F, "link" },
74     { "detection", "set detection",    OFFSET(detection), AV_OPT_TYPE_INT,    {.i64=1},               0,    1, A|F, "detection" },
75     {   "peak",    0,                  0,                 AV_OPT_TYPE_CONST,  {.i64=0},               0,    0, A|F, "detection" },
76     {   "rms",     0,                  0,                 AV_OPT_TYPE_CONST,  {.i64=1},               0,    0, A|F, "detection" },
77     { "mix",       "set mix",          OFFSET(mix),       AV_OPT_TYPE_DOUBLE, {.dbl=1},               0,    1, A|F },
78     { NULL }
79 };
80
81 #define sidechaincompress_options options
82 AVFILTER_DEFINE_CLASS(sidechaincompress);
83
84 static av_cold int init(AVFilterContext *ctx)
85 {
86     SidechainCompressContext *s = ctx->priv;
87
88     s->thres = log(s->threshold);
89     s->lin_knee_start = s->threshold / sqrt(s->knee);
90     s->knee_start = log(s->lin_knee_start);
91     s->knee_stop = log(s->threshold * sqrt(s->knee));
92     s->compressed_knee_stop = (s->knee_stop - s->thres) / s->ratio + s->thres;
93
94     return 0;
95 }
96
97 // A fake infinity value (because real infinity may break some hosts)
98 #define FAKE_INFINITY (65536.0 * 65536.0)
99
100 // Check for infinity (with appropriate-ish tolerance)
101 #define IS_FAKE_INFINITY(value) (fabs(value-FAKE_INFINITY) < 1.0)
102
103 static double output_gain(double lin_slope, double ratio, double thres,
104                           double knee, double knee_start, double knee_stop,
105                           double compressed_knee_stop, int detection)
106 {
107     double slope = log(lin_slope);
108     double gain = 0.0;
109     double delta = 0.0;
110
111     if (detection)
112         slope *= 0.5;
113
114     if (IS_FAKE_INFINITY(ratio)) {
115         gain = thres;
116         delta = 0.0;
117     } else {
118         gain = (slope - thres) / ratio + thres;
119         delta = 1.0 / ratio;
120     }
121
122     if (knee > 1.0 && slope < knee_stop)
123         gain = hermite_interpolation(slope, knee_start, knee_stop,
124                                      knee_start, compressed_knee_stop,
125                                      1.0, delta);
126
127     return exp(gain - slope);
128 }
129
130 static int compressor_config_output(AVFilterLink *outlink)
131 {
132     AVFilterContext *ctx = outlink->src;
133     SidechainCompressContext *s = ctx->priv;
134
135     s->attack_coeff = FFMIN(1., 1. / (s->attack * outlink->sample_rate / 4000.));
136     s->release_coeff = FFMIN(1., 1. / (s->release * outlink->sample_rate / 4000.));
137
138     return 0;
139 }
140
141 static void compressor(SidechainCompressContext *s,
142                        double *sample, const double *scsrc, int nb_samples,
143                        AVFilterLink *inlink, AVFilterLink *sclink)
144 {
145     const double makeup = s->makeup;
146     const double mix = s->mix;
147     int i, c;
148
149     for (i = 0; i < nb_samples; i++) {
150         double abs_sample, gain = 1.0;
151
152         abs_sample = fabs(scsrc[0]);
153
154         if (s->link == 1) {
155             for (c = 1; c < sclink->channels; c++)
156                 abs_sample = FFMAX(fabs(scsrc[c]), abs_sample);
157         } else {
158             for (c = 1; c < sclink->channels; c++)
159                 abs_sample += fabs(scsrc[c]);
160
161             abs_sample /= sclink->channels;
162         }
163
164         if (s->detection)
165             abs_sample *= abs_sample;
166
167         s->lin_slope += (abs_sample - s->lin_slope) * (abs_sample > s->lin_slope ? s->attack_coeff : s->release_coeff);
168
169         if (s->lin_slope > 0.0 && s->lin_slope > s->lin_knee_start)
170             gain = output_gain(s->lin_slope, s->ratio, s->thres, s->knee,
171                                s->knee_start, s->knee_stop,
172                                s->compressed_knee_stop, s->detection);
173
174         for (c = 0; c < inlink->channels; c++)
175             sample[c] *= (gain * makeup * mix + (1. - mix));
176
177         sample += inlink->channels;
178         scsrc += sclink->channels;
179     }
180 }
181
182 #if CONFIG_SIDECHAINCOMPRESS_FILTER
183 static int filter_frame(AVFilterLink *link, AVFrame *frame)
184 {
185     AVFilterContext *ctx = link->dst;
186     SidechainCompressContext *s = ctx->priv;
187     AVFilterLink *outlink = ctx->outputs[0];
188     const double *scsrc;
189     double *sample;
190     int nb_samples;
191     int ret, i;
192
193     for (i = 0; i < 2; i++)
194         if (link == ctx->inputs[i])
195             break;
196     av_assert0(i < 2 && !s->input_frame[i]);
197     s->input_frame[i] = frame;
198
199     if (!s->input_frame[0] || !s->input_frame[1])
200         return 0;
201
202     nb_samples = FFMIN(s->input_frame[0]->nb_samples,
203                        s->input_frame[1]->nb_samples);
204
205     sample = (double *)s->input_frame[0]->data[0];
206     scsrc = (const double *)s->input_frame[1]->data[0];
207
208     compressor(s, sample, scsrc, nb_samples,
209                ctx->inputs[0], ctx->inputs[1]);
210     ret = ff_filter_frame(outlink, s->input_frame[0]);
211
212     s->input_frame[0] = NULL;
213     av_frame_free(&s->input_frame[1]);
214
215     return ret;
216 }
217
218 static int request_frame(AVFilterLink *outlink)
219 {
220     AVFilterContext *ctx = outlink->src;
221     SidechainCompressContext *s = ctx->priv;
222     int i, ret;
223
224     /* get a frame on each input */
225     for (i = 0; i < 2; i++) {
226         AVFilterLink *inlink = ctx->inputs[i];
227         if (!s->input_frame[i] &&
228             (ret = ff_request_frame(inlink)) < 0)
229             return ret;
230
231         /* request the same number of samples on all inputs */
232         if (i == 0)
233             ctx->inputs[1]->request_samples = s->input_frame[0]->nb_samples;
234     }
235
236     return 0;
237 }
238
239 static int query_formats(AVFilterContext *ctx)
240 {
241     AVFilterFormats *formats;
242     AVFilterChannelLayouts *layouts = NULL;
243     static const enum AVSampleFormat sample_fmts[] = {
244         AV_SAMPLE_FMT_DBL,
245         AV_SAMPLE_FMT_NONE
246     };
247     int ret, i;
248
249     if (!ctx->inputs[0]->in_channel_layouts ||
250         !ctx->inputs[0]->in_channel_layouts->nb_channel_layouts) {
251         av_log(ctx, AV_LOG_WARNING,
252                "No channel layout for input 1\n");
253             return AVERROR(EAGAIN);
254     }
255
256     if ((ret = ff_add_channel_layout(&layouts, ctx->inputs[0]->in_channel_layouts->channel_layouts[0])) < 0 ||
257         (ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts)) < 0)
258         return ret;
259
260     for (i = 0; i < 2; i++) {
261         layouts = ff_all_channel_counts();
262         if ((ret = ff_channel_layouts_ref(layouts, &ctx->inputs[i]->out_channel_layouts)) < 0)
263             return ret;
264     }
265
266     formats = ff_make_format_list(sample_fmts);
267     if ((ret = ff_set_common_formats(ctx, formats)) < 0)
268         return ret;
269
270     formats = ff_all_samplerates();
271     return ff_set_common_samplerates(ctx, formats);
272 }
273
274 static int config_output(AVFilterLink *outlink)
275 {
276     AVFilterContext *ctx = outlink->src;
277
278     if (ctx->inputs[0]->sample_rate != ctx->inputs[1]->sample_rate) {
279         av_log(ctx, AV_LOG_ERROR,
280                "Inputs must have the same sample rate "
281                "%d for in0 vs %d for in1\n",
282                ctx->inputs[0]->sample_rate, ctx->inputs[1]->sample_rate);
283         return AVERROR(EINVAL);
284     }
285
286     outlink->sample_rate = ctx->inputs[0]->sample_rate;
287     outlink->time_base   = ctx->inputs[0]->time_base;
288     outlink->channel_layout = ctx->inputs[0]->channel_layout;
289     outlink->channels = ctx->inputs[0]->channels;
290
291     compressor_config_output(outlink);
292
293     return 0;
294 }
295
296 static const AVFilterPad sidechaincompress_inputs[] = {
297     {
298         .name           = "main",
299         .type           = AVMEDIA_TYPE_AUDIO,
300         .filter_frame   = filter_frame,
301         .needs_writable = 1,
302         .needs_fifo     = 1,
303     },{
304         .name           = "sidechain",
305         .type           = AVMEDIA_TYPE_AUDIO,
306         .filter_frame   = filter_frame,
307         .needs_fifo     = 1,
308     },
309     { NULL }
310 };
311
312 static const AVFilterPad sidechaincompress_outputs[] = {
313     {
314         .name          = "default",
315         .type          = AVMEDIA_TYPE_AUDIO,
316         .config_props  = config_output,
317         .request_frame = request_frame,
318     },
319     { NULL }
320 };
321
322 AVFilter ff_af_sidechaincompress = {
323     .name           = "sidechaincompress",
324     .description    = NULL_IF_CONFIG_SMALL("Sidechain compressor."),
325     .priv_size      = sizeof(SidechainCompressContext),
326     .priv_class     = &sidechaincompress_class,
327     .init           = init,
328     .query_formats  = query_formats,
329     .inputs         = sidechaincompress_inputs,
330     .outputs        = sidechaincompress_outputs,
331 };
332 #endif  /* CONFIG_SIDECHAINCOMPRESS_FILTER */
333
334 #if CONFIG_ACOMPRESSOR_FILTER
335 static int acompressor_filter_frame(AVFilterLink *inlink, AVFrame *frame)
336 {
337     AVFilterContext *ctx = inlink->dst;
338     SidechainCompressContext *s = ctx->priv;
339     AVFilterLink *outlink = ctx->outputs[0];
340     double *sample;
341
342     sample = (double *)frame->data[0];
343     compressor(s, sample, sample, frame->nb_samples,
344                inlink, inlink);
345
346     return ff_filter_frame(outlink, frame);
347 }
348
349 static int acompressor_query_formats(AVFilterContext *ctx)
350 {
351     AVFilterFormats *formats;
352     AVFilterChannelLayouts *layouts;
353     static const enum AVSampleFormat sample_fmts[] = {
354         AV_SAMPLE_FMT_DBL,
355         AV_SAMPLE_FMT_NONE
356     };
357     int ret;
358
359     layouts = ff_all_channel_counts();
360     if (!layouts)
361         return AVERROR(ENOMEM);
362     ret = ff_set_common_channel_layouts(ctx, layouts);
363     if (ret < 0)
364         return ret;
365
366     formats = ff_make_format_list(sample_fmts);
367     if (!formats)
368         return AVERROR(ENOMEM);
369     ret = ff_set_common_formats(ctx, formats);
370     if (ret < 0)
371         return ret;
372
373     formats = ff_all_samplerates();
374     if (!formats)
375         return AVERROR(ENOMEM);
376     return ff_set_common_samplerates(ctx, formats);
377 }
378
379 #define acompressor_options options
380 AVFILTER_DEFINE_CLASS(acompressor);
381
382 static const AVFilterPad acompressor_inputs[] = {
383     {
384         .name           = "default",
385         .type           = AVMEDIA_TYPE_AUDIO,
386         .filter_frame   = acompressor_filter_frame,
387         .needs_writable = 1,
388     },
389     { NULL }
390 };
391
392 static const AVFilterPad acompressor_outputs[] = {
393     {
394         .name          = "default",
395         .type          = AVMEDIA_TYPE_AUDIO,
396         .config_props  = compressor_config_output,
397     },
398     { NULL }
399 };
400
401 AVFilter ff_af_acompressor = {
402     .name           = "acompressor",
403     .description    = NULL_IF_CONFIG_SMALL("Audio compressor."),
404     .priv_size      = sizeof(SidechainCompressContext),
405     .priv_class     = &acompressor_class,
406     .init           = init,
407     .query_formats  = acompressor_query_formats,
408     .inputs         = acompressor_inputs,
409     .outputs        = acompressor_outputs,
410 };
411 #endif  /* CONFIG_ACOMPRESSOR_FILTER */