]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_agate.c
Merge commit 'a43905f4ae261bdde87c300901d867b31961f57b'
[ffmpeg] / libavfilter / af_agate.c
1 /*
2  * Copyright (C) 2001-2010 Krzysztof Foltman, Markus Schmidt, Thor Harald Johansen, Damien Zammit
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  * Audio (Sidechain) Gate filter
24  */
25
26 #include "libavutil/avassert.h"
27 #include "libavutil/channel_layout.h"
28 #include "libavutil/opt.h"
29 #include "avfilter.h"
30 #include "audio.h"
31 #include "formats.h"
32 #include "hermite.h"
33
34 typedef struct AudioGateContext {
35     const AVClass *class;
36
37     double level_in;
38     double level_sc;
39     double attack;
40     double release;
41     double threshold;
42     double ratio;
43     double knee;
44     double makeup;
45     double range;
46     int link;
47     int detection;
48
49     double thres;
50     double knee_start;
51     double lin_knee_stop;
52     double knee_stop;
53     double lin_slope;
54     double attack_coeff;
55     double release_coeff;
56
57     AVFrame *input_frame[2];
58 } AudioGateContext;
59
60 #define OFFSET(x) offsetof(AudioGateContext, x)
61 #define A AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
62
63 static const AVOption options[] = {
64     { "level_in",  "set input level",        OFFSET(level_in),  AV_OPT_TYPE_DOUBLE, {.dbl=1},           0.015625,   64, A },
65     { "range",     "set max gain reduction", OFFSET(range),     AV_OPT_TYPE_DOUBLE, {.dbl=0.06125},     0, 1, A },
66     { "threshold", "set threshold",          OFFSET(threshold), AV_OPT_TYPE_DOUBLE, {.dbl=0.125},       0, 1, A },
67     { "ratio",     "set ratio",              OFFSET(ratio),     AV_OPT_TYPE_DOUBLE, {.dbl=2},           1,  9000, A },
68     { "attack",    "set attack",             OFFSET(attack),    AV_OPT_TYPE_DOUBLE, {.dbl=20},          0.01, 9000, A },
69     { "release",   "set release",            OFFSET(release),   AV_OPT_TYPE_DOUBLE, {.dbl=250},         0.01, 9000, A },
70     { "makeup",    "set makeup gain",        OFFSET(makeup),    AV_OPT_TYPE_DOUBLE, {.dbl=1},           1,   64, A },
71     { "knee",      "set knee",               OFFSET(knee),      AV_OPT_TYPE_DOUBLE, {.dbl=2.828427125}, 1,    8, A },
72     { "detection", "set detection",          OFFSET(detection), AV_OPT_TYPE_INT,    {.i64=1},           0,    1, A, "detection" },
73     {   "peak",    0,                        0,                 AV_OPT_TYPE_CONST,  {.i64=0},           0,    0, A, "detection" },
74     {   "rms",     0,                        0,                 AV_OPT_TYPE_CONST,  {.i64=1},           0,    0, A, "detection" },
75     { "link",      "set link",               OFFSET(link),      AV_OPT_TYPE_INT,    {.i64=0},           0,    1, A, "link" },
76     {   "average", 0,                        0,                 AV_OPT_TYPE_CONST,  {.i64=0},           0,    0, A, "link" },
77     {   "maximum", 0,                        0,                 AV_OPT_TYPE_CONST,  {.i64=1},           0,    0, A, "link" },
78     { "level_sc",  "set sidechain gain",     OFFSET(level_sc),  AV_OPT_TYPE_DOUBLE, {.dbl=1},           0.015625,   64, A },
79     { NULL }
80 };
81
82 static int agate_config_input(AVFilterLink *inlink)
83 {
84     AVFilterContext *ctx = inlink->dst;
85     AudioGateContext *s = ctx->priv;
86     double lin_threshold = s->threshold;
87     double lin_knee_sqrt = sqrt(s->knee);
88     double lin_knee_start;
89
90     if (s->detection)
91         lin_threshold *= lin_threshold;
92
93     s->attack_coeff  = FFMIN(1., 1. / (s->attack * inlink->sample_rate / 4000.));
94     s->release_coeff = FFMIN(1., 1. / (s->release * inlink->sample_rate / 4000.));
95     s->lin_knee_stop = lin_threshold * lin_knee_sqrt;
96     lin_knee_start = lin_threshold / lin_knee_sqrt;
97     s->thres = log(lin_threshold);
98     s->knee_start = log(lin_knee_start);
99     s->knee_stop = log(s->lin_knee_stop);
100
101     return 0;
102 }
103
104 // A fake infinity value (because real infinity may break some hosts)
105 #define FAKE_INFINITY (65536.0 * 65536.0)
106
107 // Check for infinity (with appropriate-ish tolerance)
108 #define IS_FAKE_INFINITY(value) (fabs(value-FAKE_INFINITY) < 1.0)
109
110 static double output_gain(double lin_slope, double ratio, double thres,
111                           double knee, double knee_start, double knee_stop,
112                           double lin_knee_stop, double range)
113 {
114     if (lin_slope < lin_knee_stop) {
115         double slope = log(lin_slope);
116         double tratio = ratio;
117         double gain = 0.;
118         double delta = 0.;
119
120         if (IS_FAKE_INFINITY(ratio))
121             tratio = 1000.;
122         gain = (slope - thres) * tratio + thres;
123         delta = tratio;
124
125         if (knee > 1. && slope > knee_start) {
126             gain = hermite_interpolation(slope, knee_start, knee_stop, ((knee_start - thres) * tratio  + thres), knee_stop, delta, 1.);
127         }
128         return FFMAX(range, exp(gain - slope));
129     }
130
131     return 1.;
132 }
133
134 static void gate(AudioGateContext *s,
135                  const double *src, double *dst, const double *scsrc,
136                  int nb_samples, double level_in, double level_sc,
137                  AVFilterLink *inlink, AVFilterLink *sclink)
138 {
139     const double makeup = s->makeup;
140     const double attack_coeff = s->attack_coeff;
141     const double release_coeff = s->release_coeff;
142     int n, c;
143
144     for (n = 0; n < nb_samples; n++, src += inlink->channels, dst += inlink->channels, scsrc += sclink->channels) {
145         double abs_sample = fabs(scsrc[0] * level_sc), gain = 1.0;
146
147         if (s->link == 1) {
148             for (c = 1; c < sclink->channels; c++)
149                 abs_sample = FFMAX(fabs(scsrc[c] * level_sc), abs_sample);
150         } else {
151             for (c = 1; c < sclink->channels; c++)
152                 abs_sample += fabs(scsrc[c] * level_sc);
153
154             abs_sample /= sclink->channels;
155         }
156
157         if (s->detection)
158             abs_sample *= abs_sample;
159
160         s->lin_slope += (abs_sample - s->lin_slope) * (abs_sample > s->lin_slope ? attack_coeff : release_coeff);
161         if (s->lin_slope > 0.0)
162             gain = output_gain(s->lin_slope, s->ratio, s->thres,
163                                s->knee, s->knee_start, s->knee_stop,
164                                s->lin_knee_stop, s->range);
165
166         for (c = 0; c < inlink->channels; c++)
167             dst[c] = src[c] * level_in * gain * makeup;
168     }
169 }
170
171 #if CONFIG_AGATE_FILTER
172
173 #define agate_options options
174 AVFILTER_DEFINE_CLASS(agate);
175
176 static int query_formats(AVFilterContext *ctx)
177 {
178     AVFilterFormats *formats = NULL;
179     AVFilterChannelLayouts *layouts;
180     int ret;
181
182     if ((ret = ff_add_format(&formats, AV_SAMPLE_FMT_DBL)) < 0)
183         return ret;
184     ret = ff_set_common_formats(ctx, formats);
185     if (ret < 0)
186         return ret;
187
188     layouts = ff_all_channel_counts();
189     if (!layouts)
190         return AVERROR(ENOMEM);
191     ret = ff_set_common_channel_layouts(ctx, layouts);
192     if (ret < 0)
193         return ret;
194
195     formats = ff_all_samplerates();
196     if (!formats)
197         return AVERROR(ENOMEM);
198
199     return ff_set_common_samplerates(ctx, formats);
200 }
201
202 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
203 {
204     const double *src = (const double *)in->data[0];
205     AVFilterContext *ctx = inlink->dst;
206     AVFilterLink *outlink = ctx->outputs[0];
207     AudioGateContext *s = ctx->priv;
208     AVFrame *out;
209     double *dst;
210
211     if (av_frame_is_writable(in)) {
212         out = in;
213     } else {
214         out = ff_get_audio_buffer(inlink, in->nb_samples);
215         if (!out) {
216             av_frame_free(&in);
217             return AVERROR(ENOMEM);
218         }
219         av_frame_copy_props(out, in);
220     }
221     dst = (double *)out->data[0];
222
223     gate(s, src, dst, src, in->nb_samples,
224          s->level_in, s->level_in, inlink, inlink);
225
226     if (out != in)
227         av_frame_free(&in);
228     return ff_filter_frame(outlink, out);
229 }
230
231 static const AVFilterPad inputs[] = {
232     {
233         .name         = "default",
234         .type         = AVMEDIA_TYPE_AUDIO,
235         .filter_frame = filter_frame,
236         .config_props = agate_config_input,
237     },
238     { NULL }
239 };
240
241 static const AVFilterPad outputs[] = {
242     {
243         .name = "default",
244         .type = AVMEDIA_TYPE_AUDIO,
245     },
246     { NULL }
247 };
248
249 AVFilter ff_af_agate = {
250     .name           = "agate",
251     .description    = NULL_IF_CONFIG_SMALL("Audio gate."),
252     .query_formats  = query_formats,
253     .priv_size      = sizeof(AudioGateContext),
254     .priv_class     = &agate_class,
255     .inputs         = inputs,
256     .outputs        = outputs,
257 };
258
259 #endif /* CONFIG_AGATE_FILTER */
260
261 #if CONFIG_SIDECHAINGATE_FILTER
262
263 #define sidechaingate_options options
264 AVFILTER_DEFINE_CLASS(sidechaingate);
265
266 static int scfilter_frame(AVFilterLink *link, AVFrame *in)
267 {
268     AVFilterContext *ctx = link->dst;
269     AudioGateContext *s = ctx->priv;
270     AVFilterLink *outlink = ctx->outputs[0];
271     const double *scsrc;
272     double *sample;
273     int nb_samples;
274     int ret, i;
275
276     for (i = 0; i < 2; i++)
277         if (link == ctx->inputs[i])
278             break;
279     av_assert0(i < 2 && !s->input_frame[i]);
280     s->input_frame[i] = in;
281
282     if (!s->input_frame[0] || !s->input_frame[1])
283         return 0;
284
285     nb_samples = FFMIN(s->input_frame[0]->nb_samples,
286                        s->input_frame[1]->nb_samples);
287
288     sample = (double *)s->input_frame[0]->data[0];
289     scsrc = (const double *)s->input_frame[1]->data[0];
290
291     gate(s, sample, sample, scsrc, nb_samples,
292          s->level_in, s->level_sc,
293          ctx->inputs[0], ctx->inputs[1]);
294     ret = ff_filter_frame(outlink, s->input_frame[0]);
295
296     s->input_frame[0] = NULL;
297     av_frame_free(&s->input_frame[1]);
298
299     return ret;
300 }
301
302 static int screquest_frame(AVFilterLink *outlink)
303 {
304     AVFilterContext *ctx = outlink->src;
305     AudioGateContext *s = ctx->priv;
306     int i, ret;
307
308     /* get a frame on each input */
309     for (i = 0; i < 2; i++) {
310         AVFilterLink *inlink = ctx->inputs[i];
311         if (!s->input_frame[i] &&
312             (ret = ff_request_frame(inlink)) < 0)
313             return ret;
314
315         /* request the same number of samples on all inputs */
316         if (i == 0)
317             ctx->inputs[1]->request_samples = s->input_frame[0]->nb_samples;
318     }
319
320     return 0;
321 }
322
323 static int scquery_formats(AVFilterContext *ctx)
324 {
325     AVFilterFormats *formats;
326     AVFilterChannelLayouts *layouts = NULL;
327     static const enum AVSampleFormat sample_fmts[] = {
328         AV_SAMPLE_FMT_DBL,
329         AV_SAMPLE_FMT_NONE
330     };
331     int ret, i;
332
333     if (!ctx->inputs[0]->in_channel_layouts ||
334         !ctx->inputs[0]->in_channel_layouts->nb_channel_layouts) {
335         av_log(ctx, AV_LOG_WARNING,
336                "No channel layout for input 1\n");
337             return AVERROR(EAGAIN);
338     }
339
340     if ((ret = ff_add_channel_layout(&layouts, ctx->inputs[0]->in_channel_layouts->channel_layouts[0])) < 0 ||
341         (ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts)) < 0)
342         return ret;
343
344     for (i = 0; i < 2; i++) {
345         layouts = ff_all_channel_counts();
346         if ((ret = ff_channel_layouts_ref(layouts, &ctx->inputs[i]->out_channel_layouts)) < 0)
347             return ret;
348     }
349
350     formats = ff_make_format_list(sample_fmts);
351     if ((ret = ff_set_common_formats(ctx, formats)) < 0)
352         return ret;
353
354     formats = ff_all_samplerates();
355     return ff_set_common_samplerates(ctx, formats);
356 }
357
358 static int scconfig_output(AVFilterLink *outlink)
359 {
360     AVFilterContext *ctx = outlink->src;
361
362     if (ctx->inputs[0]->sample_rate != ctx->inputs[1]->sample_rate) {
363         av_log(ctx, AV_LOG_ERROR,
364                "Inputs must have the same sample rate "
365                "%d for in0 vs %d for in1\n",
366                ctx->inputs[0]->sample_rate, ctx->inputs[1]->sample_rate);
367         return AVERROR(EINVAL);
368     }
369
370     outlink->sample_rate = ctx->inputs[0]->sample_rate;
371     outlink->time_base   = ctx->inputs[0]->time_base;
372     outlink->channel_layout = ctx->inputs[0]->channel_layout;
373     outlink->channels = ctx->inputs[0]->channels;
374
375     agate_config_input(ctx->inputs[0]);
376
377     return 0;
378 }
379
380 static const AVFilterPad sidechaingate_inputs[] = {
381     {
382         .name           = "main",
383         .type           = AVMEDIA_TYPE_AUDIO,
384         .filter_frame   = scfilter_frame,
385         .needs_writable = 1,
386         .needs_fifo     = 1,
387     },{
388         .name           = "sidechain",
389         .type           = AVMEDIA_TYPE_AUDIO,
390         .filter_frame   = scfilter_frame,
391         .needs_fifo     = 1,
392     },
393     { NULL }
394 };
395
396 static const AVFilterPad sidechaingate_outputs[] = {
397     {
398         .name          = "default",
399         .type          = AVMEDIA_TYPE_AUDIO,
400         .config_props  = scconfig_output,
401         .request_frame = screquest_frame,
402     },
403     { NULL }
404 };
405
406 AVFilter ff_af_sidechaingate = {
407     .name           = "sidechaingate",
408     .description    = NULL_IF_CONFIG_SMALL("Audio sidechain gate."),
409     .priv_size      = sizeof(AudioGateContext),
410     .priv_class     = &sidechaingate_class,
411     .query_formats  = scquery_formats,
412     .inputs         = sidechaingate_inputs,
413     .outputs        = sidechaingate_outputs,
414 };
415 #endif  /* CONFIG_SIDECHAINGATE_FILTER */