Browse code

avfilter: add sidechain compress audio filter

Signed-off-by: Paul B Mahol <onemda@gmail.com>

Paul B Mahol authored on 2015/07/18 03:44:16
Showing 6 changed files
... ...
@@ -24,6 +24,7 @@ version <next>:
24 24
 - Random filter
25 25
 - deband filter
26 26
 - AAC fixed-point decoding
27
+- sidechaincompress audio filter
27 28
 
28 29
 
29 30
 version 2.7:
... ...
@@ -622,6 +622,7 @@ slope
622 622
 Specify the band-width of a filter in width_type units.
623 623
 @end table
624 624
 
625
+@anchor{amerge}
625 626
 @section amerge
626 627
 
627 628
 Merge two or more audio streams into a single multi-channel stream.
... ...
@@ -2020,6 +2021,7 @@ Applies only to double-pole filter.
2020 2020
 The default is 0.707q and gives a Butterworth response.
2021 2021
 @end table
2022 2022
 
2023
+@anchor{pan}
2023 2024
 @section pan
2024 2025
 
2025 2026
 Mix channels with specific gain levels. The filter accepts the output
... ...
@@ -2121,6 +2123,66 @@ At end of filtering it displays @code{track_gain} and @code{track_peak}.
2121 2121
 Convert the audio sample format, sample rate and channel layout. It is
2122 2122
 not meant to be used directly.
2123 2123
 
2124
+@section sidechaincompress
2125
+
2126
+This filter acts like normal compressor but has the ability to compress
2127
+detected signal using second input signal.
2128
+It needs two input streams and returns one output stream.
2129
+First input stream will be processed depending on second stream signal.
2130
+The filtered signal then can be filtered with other filters in later stages of
2131
+processing. See @ref{pan} and @ref{amerge} filter.
2132
+
2133
+The filter accepts the following options:
2134
+
2135
+@table @option
2136
+@item threshold
2137
+If a signal of second stream raises above this level it will affect the gain
2138
+reduction of first stream.
2139
+By default is 0.125. Range is between 0.00097563 and 1.
2140
+
2141
+@item ratio
2142
+Set a ratio about which the signal is reduced. 1:2 means that if the level
2143
+raised 4dB above the threshold, it will be only 2dB above after the reduction.
2144
+Default is 2. Range is between 1 and 20.
2145
+
2146
+@item attack
2147
+Amount of milliseconds the signal has to rise above the threshold before gain
2148
+reduction starts. Default is 20. Range is between 0.01 and 2000.
2149
+
2150
+@item release
2151
+Amount of milliseconds the signal has to fall bellow the threshold before
2152
+reduction is decreased again. Default is 250. Range is between 0.01 and 9000.
2153
+
2154
+@item makeup
2155
+Set the amount by how much signal will be amplified after processing.
2156
+Default is 2. Range is from 1 and 64.
2157
+
2158
+@item knee
2159
+Curve the sharp knee around the threshold to enter gain reduction more softly.
2160
+Default is 2.82843. Range is between 1 and 8.
2161
+
2162
+@item link
2163
+Choose if the @code{average} level between all channels of side-chain stream
2164
+or the louder(@code{maximum}) channel of side-chain stream affects the
2165
+reduction. Default is @code{average}.
2166
+
2167
+@item detection
2168
+Should the exact signal be taken in case of @code{peak} or an RMS one in case
2169
+of @code{rms}. Default is @code{rms} which is mainly smoother.
2170
+@end table
2171
+
2172
+@subsection Examples
2173
+
2174
+@itemize
2175
+@item
2176
+Full ffmpeg example taking 2 audio inputs, 1st input to be compressed
2177
+depending on the signal of 2nd input and later compressed signal to be
2178
+merged with 2nd input:
2179
+@example
2180
+ffmpeg -i main.flac -i sidechain.flac -filter_complex "[1:a]asplit=2[sc][mix];[0:a][sc]sidechaincompress[compr];[compr][mix]amerge"
2181
+@end example
2182
+@end itemize
2183
+
2124 2184
 @section silencedetect
2125 2185
 
2126 2186
 Detect silence in an audio stream.
... ...
@@ -80,6 +80,7 @@ OBJS-$(CONFIG_LOWPASS_FILTER)                += af_biquads.o
80 80
 OBJS-$(CONFIG_PAN_FILTER)                    += af_pan.o
81 81
 OBJS-$(CONFIG_REPLAYGAIN_FILTER)             += af_replaygain.o
82 82
 OBJS-$(CONFIG_RESAMPLE_FILTER)               += af_resample.o
83
+OBJS-$(CONFIG_SIDECHAINCOMPRESS_FILTER)      += af_sidechaincompress.o
83 84
 OBJS-$(CONFIG_SILENCEDETECT_FILTER)          += af_silencedetect.o
84 85
 OBJS-$(CONFIG_SILENCEREMOVE_FILTER)          += af_silenceremove.o
85 86
 OBJS-$(CONFIG_TREBLE_FILTER)                 += af_biquads.o
86 87
new file mode 100644
... ...
@@ -0,0 +1,338 @@
0
+/*
1
+ * Copyright (C) 2001-2010 Krzysztof Foltman, Markus Schmidt, Thor Harald Johansen and others
2
+ * Copyright (c) 2015 Paul B Mahol
3
+ *
4
+ * This file is part of FFmpeg.
5
+ *
6
+ * FFmpeg is free software; you can redistribute it and/or
7
+ * modify it under the terms of the GNU Lesser General Public
8
+ * License as published by the Free Software Foundation; either
9
+ * version 2.1 of the License, or (at your option) any later version.
10
+ *
11
+ * FFmpeg is distributed in the hope that it will be useful,
12
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
+ * Lesser General Public License for more details.
15
+ *
16
+ * You should have received a copy of the GNU Lesser General Public
17
+ * License along with FFmpeg; if not, write to the Free Software
18
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
+ */
20
+
21
+/**
22
+ * @file
23
+ * Sidechain compressor filter
24
+ */
25
+
26
+#include "libavutil/avassert.h"
27
+#include "libavutil/channel_layout.h"
28
+#include "libavutil/common.h"
29
+#include "libavutil/opt.h"
30
+
31
+#include "audio.h"
32
+#include "avfilter.h"
33
+#include "formats.h"
34
+#include "internal.h"
35
+
36
+typedef struct SidechainCompressContext {
37
+    const AVClass *class;
38
+
39
+    double attack, attack_coeff;
40
+    double release, release_coeff;
41
+    double lin_slope;
42
+    double ratio;
43
+    double threshold;
44
+    double makeup;
45
+    double thres;
46
+    double knee;
47
+    double knee_start;
48
+    double knee_stop;
49
+    double lin_knee_start;
50
+    double compressed_knee_stop;
51
+    int link;
52
+    int detection;
53
+
54
+    AVFrame *input_frame[2];
55
+} SidechainCompressContext;
56
+
57
+#define OFFSET(x) offsetof(SidechainCompressContext, x)
58
+#define A AV_OPT_FLAG_AUDIO_PARAM
59
+#define F AV_OPT_FLAG_FILTERING_PARAM
60
+
61
+static const AVOption sidechaincompress_options[] = {
62
+    { "threshold", "set threshold",    OFFSET(threshold), AV_OPT_TYPE_DOUBLE, {.dbl=0.125}, 0.000976563,    1, A|F },
63
+    { "ratio",     "set ratio",        OFFSET(ratio),     AV_OPT_TYPE_DOUBLE, {.dbl=2},               1,   20, A|F },
64
+    { "attack",    "set attack",       OFFSET(attack),    AV_OPT_TYPE_DOUBLE, {.dbl=20},           0.01, 2000, A|F },
65
+    { "release",   "set release",      OFFSET(release),   AV_OPT_TYPE_DOUBLE, {.dbl=250},          0.01, 9000, A|F },
66
+    { "makeup",    "set make up gain", OFFSET(makeup),    AV_OPT_TYPE_DOUBLE, {.dbl=2},               1,   64, A|F },
67
+    { "knee",      "set knee",         OFFSET(knee),      AV_OPT_TYPE_DOUBLE, {.dbl=2.82843},         1,    8, A|F },
68
+    { "link",      "set link type",    OFFSET(link),      AV_OPT_TYPE_INT,    {.i64=0},               0,    1, A|F, "link" },
69
+    {   "average", 0,                  0,                 AV_OPT_TYPE_CONST,  {.i64=0},               0,    0, A|F, "link" },
70
+    {   "maximum", 0,                  0,                 AV_OPT_TYPE_CONST,  {.i64=1},               0,    0, A|F, "link" },
71
+    { "detection", "set detection",    OFFSET(detection), AV_OPT_TYPE_INT,    {.i64=1},               0,    1, A|F, "detection" },
72
+    {   "peak",    0,                  0,                 AV_OPT_TYPE_CONST,  {.i64=0},               0,    0, A|F, "detection" },
73
+    {   "rms",     0,                  0,                 AV_OPT_TYPE_CONST,  {.i64=1},               0,    0, A|F, "detection" },
74
+    { NULL }
75
+};
76
+
77
+AVFILTER_DEFINE_CLASS(sidechaincompress);
78
+
79
+static av_cold int init(AVFilterContext *ctx)
80
+{
81
+    SidechainCompressContext *s = ctx->priv;
82
+
83
+    s->thres = log(s->threshold);
84
+    s->lin_knee_start = s->threshold / sqrt(s->knee);
85
+    s->knee_start = log(s->lin_knee_start);
86
+    s->knee_stop = log(s->threshold * sqrt(s->knee));
87
+    s->compressed_knee_stop = (s->knee_stop - s->thres) / s->ratio + s->thres;
88
+
89
+    return 0;
90
+}
91
+
92
+static inline float hermite_interpolation(float x, float x0, float x1,
93
+                                          float p0, float p1,
94
+                                          float m0, float m1)
95
+{
96
+    float width = x1 - x0;
97
+    float t = (x - x0) / width;
98
+    float t2, t3;
99
+    float ct0, ct1, ct2, ct3;
100
+
101
+    m0 *= width;
102
+    m1 *= width;
103
+
104
+    t2 = t*t;
105
+    t3 = t2*t;
106
+    ct0 = p0;
107
+    ct1 = m0;
108
+
109
+    ct2 = -3 * p0 - 2 * m0 + 3 * p1 - m1;
110
+    ct3 = 2 * p0 + m0  - 2 * p1 + m1;
111
+
112
+    return ct3 * t3 + ct2 * t2 + ct1 * t + ct0;
113
+}
114
+
115
+// A fake infinity value (because real infinity may break some hosts)
116
+#define FAKE_INFINITY (65536.0 * 65536.0)
117
+
118
+// Check for infinity (with appropriate-ish tolerance)
119
+#define IS_FAKE_INFINITY(value) (fabs(value-FAKE_INFINITY) < 1.0)
120
+
121
+static double output_gain(double lin_slope, double ratio, double thres,
122
+                          double knee, double knee_start, double knee_stop,
123
+                          double compressed_knee_stop, int detection)
124
+{
125
+    double slope = log(lin_slope);
126
+    double gain = 0.0;
127
+    double delta = 0.0;
128
+
129
+    if (detection)
130
+        slope *= 0.5;
131
+
132
+    if (IS_FAKE_INFINITY(ratio)) {
133
+        gain = thres;
134
+        delta = 0.0;
135
+    } else {
136
+        gain = (slope - thres) / ratio + thres;
137
+        delta = 1.0 / ratio;
138
+    }
139
+
140
+    if (knee > 1.0 && slope < knee_stop)
141
+        gain = hermite_interpolation(slope, knee_start, knee_stop,
142
+                                     knee_start, compressed_knee_stop,
143
+                                     1.0, delta);
144
+
145
+    return exp(gain - slope);
146
+}
147
+
148
+static int filter_frame(AVFilterLink *link, AVFrame *frame)
149
+{
150
+    AVFilterContext *ctx = link->dst;
151
+    SidechainCompressContext *s = ctx->priv;
152
+    AVFilterLink *sclink = ctx->inputs[1];
153
+    AVFilterLink *outlink = ctx->outputs[0];
154
+    const double makeup = s->makeup;
155
+    const double *scsrc;
156
+    double *sample;
157
+    int nb_samples;
158
+    int ret, i, c;
159
+
160
+    for (i = 0; i < 2; i++)
161
+        if (link == ctx->inputs[i])
162
+            break;
163
+    av_assert0(!s->input_frame[i]);
164
+    s->input_frame[i] = frame;
165
+
166
+    if (!s->input_frame[0] || !s->input_frame[1])
167
+        return 0;
168
+
169
+    nb_samples = FFMIN(s->input_frame[0]->nb_samples,
170
+                       s->input_frame[1]->nb_samples);
171
+
172
+    sample = (double *)s->input_frame[0]->data[0];
173
+    scsrc = (const double *)s->input_frame[1]->data[0];
174
+
175
+    for (i = 0; i < nb_samples; i++) {
176
+        double abs_sample, gain = 1.0;
177
+
178
+        abs_sample = FFABS(scsrc[0]);
179
+
180
+        if (s->link == 1) {
181
+            for (c = 1; c < sclink->channels; c++)
182
+                abs_sample = FFMAX(FFABS(scsrc[c]), abs_sample);
183
+        } else {
184
+            for (c = 1; c < sclink->channels; c++)
185
+                abs_sample += FFABS(scsrc[c]);
186
+
187
+            abs_sample /= sclink->channels;
188
+        }
189
+
190
+        if (s->detection)
191
+            abs_sample *= abs_sample;
192
+
193
+        s->lin_slope += (abs_sample - s->lin_slope) * (abs_sample > s->lin_slope ? s->attack_coeff : s->release_coeff);
194
+
195
+        if (s->lin_slope > 0.0 && s->lin_slope > s->lin_knee_start)
196
+            gain = output_gain(s->lin_slope, s->ratio, s->thres, s->knee,
197
+                               s->knee_start, s->knee_stop,
198
+                               s->compressed_knee_stop, s->detection);
199
+
200
+        for (c = 0; c < outlink->channels; c++)
201
+            sample[c] *= gain * makeup;
202
+
203
+        sample += outlink->channels;
204
+        scsrc += sclink->channels;
205
+    }
206
+
207
+    ret = ff_filter_frame(outlink, s->input_frame[0]);
208
+
209
+    s->input_frame[0] = NULL;
210
+    av_frame_free(&s->input_frame[1]);
211
+
212
+    return ret;
213
+}
214
+
215
+static int request_frame(AVFilterLink *outlink)
216
+{
217
+    AVFilterContext *ctx = outlink->src;
218
+    SidechainCompressContext *s = ctx->priv;
219
+    int i, ret;
220
+
221
+    /* get a frame on each input */
222
+    for (i = 0; i < 2; i++) {
223
+        AVFilterLink *inlink = ctx->inputs[i];
224
+        if (!s->input_frame[i] &&
225
+            (ret = ff_request_frame(inlink)) < 0)
226
+            return ret;
227
+
228
+        /* request the same number of samples on all inputs */
229
+        if (i == 0)
230
+            ctx->inputs[1]->request_samples = s->input_frame[0]->nb_samples;
231
+    }
232
+
233
+    return 0;
234
+}
235
+
236
+static int query_formats(AVFilterContext *ctx)
237
+{
238
+    AVFilterFormats *formats;
239
+    AVFilterChannelLayouts *layouts = NULL;
240
+    static const enum AVSampleFormat sample_fmts[] = {
241
+        AV_SAMPLE_FMT_DBL,
242
+        AV_SAMPLE_FMT_NONE
243
+    };
244
+    int ret, i;
245
+
246
+    if (!ctx->inputs[0]->in_channel_layouts ||
247
+        !ctx->inputs[0]->in_channel_layouts->nb_channel_layouts) {
248
+        av_log(ctx, AV_LOG_WARNING,
249
+               "No channel layout for input 1\n");
250
+            return AVERROR(EAGAIN);
251
+    }
252
+
253
+    ff_add_channel_layout(&layouts, ctx->inputs[0]->in_channel_layouts->channel_layouts[0]);
254
+    if (!layouts)
255
+        return AVERROR(ENOMEM);
256
+    ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
257
+
258
+    for (i = 0; i < 2; i++) {
259
+        layouts = ff_all_channel_layouts();
260
+        if (!layouts)
261
+            return AVERROR(ENOMEM);
262
+        ff_channel_layouts_ref(layouts, &ctx->inputs[i]->out_channel_layouts);
263
+    }
264
+
265
+    formats = ff_make_format_list(sample_fmts);
266
+    if (!formats)
267
+        return AVERROR(ENOMEM);
268
+    ret = ff_set_common_formats(ctx, formats);
269
+    if (ret < 0)
270
+        return ret;
271
+
272
+    formats = ff_all_samplerates();
273
+    if (!formats)
274
+        return AVERROR(ENOMEM);
275
+    return ff_set_common_samplerates(ctx, formats);
276
+}
277
+
278
+static int config_output(AVFilterLink *outlink)
279
+{
280
+    AVFilterContext *ctx = outlink->src;
281
+    SidechainCompressContext *s = ctx->priv;
282
+
283
+    if (ctx->inputs[0]->sample_rate != ctx->inputs[1]->sample_rate) {
284
+        av_log(ctx, AV_LOG_ERROR,
285
+               "Inputs must have the same sample rate "
286
+               "%d for in0 vs %d for in1\n",
287
+               ctx->inputs[0]->sample_rate, ctx->inputs[1]->sample_rate);
288
+        return AVERROR(EINVAL);
289
+    }
290
+
291
+    outlink->sample_rate = ctx->inputs[0]->sample_rate;
292
+    outlink->time_base   = ctx->inputs[0]->time_base;
293
+    outlink->channel_layout = ctx->inputs[0]->channel_layout;
294
+    outlink->channels = ctx->inputs[0]->channels;
295
+
296
+    s->attack_coeff = FFMIN(1.f, 1.f / (s->attack * outlink->sample_rate / 4000.f));
297
+    s->release_coeff = FFMIN(1.f, 1.f / (s->release * outlink->sample_rate / 4000.f));
298
+
299
+    return 0;
300
+}
301
+
302
+static const AVFilterPad sidechaincompress_inputs[] = {
303
+    {
304
+        .name           = "main",
305
+        .type           = AVMEDIA_TYPE_AUDIO,
306
+        .filter_frame   = filter_frame,
307
+        .needs_writable = 1,
308
+        .needs_fifo     = 1,
309
+    },{
310
+        .name           = "sidechain",
311
+        .type           = AVMEDIA_TYPE_AUDIO,
312
+        .filter_frame   = filter_frame,
313
+        .needs_fifo     = 1,
314
+    },
315
+    { NULL }
316
+};
317
+
318
+static const AVFilterPad sidechaincompress_outputs[] = {
319
+    {
320
+        .name          = "default",
321
+        .type          = AVMEDIA_TYPE_AUDIO,
322
+        .config_props  = config_output,
323
+        .request_frame = request_frame,
324
+    },
325
+    { NULL }
326
+};
327
+
328
+AVFilter ff_af_sidechaincompress = {
329
+    .name           = "sidechaincompress",
330
+    .description    = NULL_IF_CONFIG_SMALL("Sidechain compressor."),
331
+    .priv_size      = sizeof(SidechainCompressContext),
332
+    .priv_class     = &sidechaincompress_class,
333
+    .init           = init,
334
+    .query_formats  = query_formats,
335
+    .inputs         = sidechaincompress_inputs,
336
+    .outputs        = sidechaincompress_outputs,
337
+};
... ...
@@ -96,6 +96,7 @@ void avfilter_register_all(void)
96 96
     REGISTER_FILTER(PAN,            pan,            af);
97 97
     REGISTER_FILTER(REPLAYGAIN,     replaygain,     af);
98 98
     REGISTER_FILTER(RESAMPLE,       resample,       af);
99
+    REGISTER_FILTER(SIDECHAINCOMPRESS, sidechaincompress, af);
99 100
     REGISTER_FILTER(SILENCEDETECT,  silencedetect,  af);
100 101
     REGISTER_FILTER(SILENCEREMOVE,  silenceremove,  af);
101 102
     REGISTER_FILTER(TREBLE,         treble,         af);
... ...
@@ -30,7 +30,7 @@
30 30
 #include "libavutil/version.h"
31 31
 
32 32
 #define LIBAVFILTER_VERSION_MAJOR  5
33
-#define LIBAVFILTER_VERSION_MINOR  28
33
+#define LIBAVFILTER_VERSION_MINOR  29
34 34
 #define LIBAVFILTER_VERSION_MICRO 100
35 35
 
36 36
 #define LIBAVFILTER_VERSION_INT AV_VERSION_INT(LIBAVFILTER_VERSION_MAJOR, \