]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_anlmdn.c
avfilter/af_anlmdn: try to recover when cache becomes negative
[ffmpeg] / libavfilter / af_anlmdn.c
1 /*
2  * Copyright (c) 2019 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 #include <float.h>
22
23 #include "libavutil/avassert.h"
24 #include "libavutil/audio_fifo.h"
25 #include "libavutil/opt.h"
26 #include "avfilter.h"
27 #include "audio.h"
28 #include "formats.h"
29
30 #include "af_anlmdndsp.h"
31
32 #define WEIGHT_LUT_NBITS 20
33 #define WEIGHT_LUT_SIZE  (1<<WEIGHT_LUT_NBITS)
34
35 #define SQR(x) ((x) * (x))
36
37 typedef struct AudioNLMeansContext {
38     const AVClass *class;
39
40     float a;
41     int64_t pd;
42     int64_t rd;
43     float m;
44     int om;
45
46     float pdiff_lut_scale;
47     float weight_lut[WEIGHT_LUT_SIZE];
48
49     int K;
50     int S;
51     int N;
52     int H;
53
54     int offset;
55     AVFrame *in;
56     AVFrame *cache;
57
58     int64_t pts;
59
60     AVAudioFifo *fifo;
61     int eof_left;
62
63     AudioNLMDNDSPContext dsp;
64 } AudioNLMeansContext;
65
66 enum OutModes {
67     IN_MODE,
68     OUT_MODE,
69     NOISE_MODE,
70     NB_MODES
71 };
72
73 #define OFFSET(x) offsetof(AudioNLMeansContext, x)
74 #define AF AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
75
76 static const AVOption anlmdn_options[] = {
77     { "s", "set denoising strength", OFFSET(a),  AV_OPT_TYPE_FLOAT,    {.dbl=0.00001},0.00001, 10, AF },
78     { "p", "set patch duration",     OFFSET(pd), AV_OPT_TYPE_DURATION, {.i64=2000}, 1000, 100000, AF },
79     { "r", "set research duration",  OFFSET(rd), AV_OPT_TYPE_DURATION, {.i64=6000}, 2000, 300000, AF },
80     { "o", "set output mode",        OFFSET(om), AV_OPT_TYPE_INT,      {.i64=OUT_MODE},  0, NB_MODES-1, AF, "mode" },
81     {  "i", "input",                 0,          AV_OPT_TYPE_CONST,    {.i64=IN_MODE},   0,  0, AF, "mode" },
82     {  "o", "output",                0,          AV_OPT_TYPE_CONST,    {.i64=OUT_MODE},  0,  0, AF, "mode" },
83     {  "n", "noise",                 0,          AV_OPT_TYPE_CONST,    {.i64=NOISE_MODE},0,  0, AF, "mode" },
84     { "m", "set smooth factor",      OFFSET(m),  AV_OPT_TYPE_FLOAT,    {.dbl=11.},       1, 15, AF },
85     { NULL }
86 };
87
88 AVFILTER_DEFINE_CLASS(anlmdn);
89
90 static int query_formats(AVFilterContext *ctx)
91 {
92     AVFilterFormats *formats = NULL;
93     AVFilterChannelLayouts *layouts = NULL;
94     static const enum AVSampleFormat sample_fmts[] = {
95         AV_SAMPLE_FMT_FLTP,
96         AV_SAMPLE_FMT_NONE
97     };
98     int ret;
99
100     formats = ff_make_format_list(sample_fmts);
101     if (!formats)
102         return AVERROR(ENOMEM);
103     ret = ff_set_common_formats(ctx, formats);
104     if (ret < 0)
105         return ret;
106
107     layouts = ff_all_channel_counts();
108     if (!layouts)
109         return AVERROR(ENOMEM);
110
111     ret = ff_set_common_channel_layouts(ctx, layouts);
112     if (ret < 0)
113         return ret;
114
115     formats = ff_all_samplerates();
116     return ff_set_common_samplerates(ctx, formats);
117 }
118
119 static float compute_distance_ssd_c(const float *f1, const float *f2, ptrdiff_t K)
120 {
121     float distance = 0.;
122
123     for (int k = -K; k <= K; k++)
124         distance += SQR(f1[k] - f2[k]);
125
126     return distance;
127 }
128
129 static void compute_cache_c(float *cache, const float *f,
130                             ptrdiff_t S, ptrdiff_t K,
131                             ptrdiff_t i, ptrdiff_t jj)
132 {
133     int v = 0;
134
135     for (int j = jj; j < jj + S; j++, v++)
136         cache[v] += -SQR(f[i - K - 1] - f[j - K - 1]) + SQR(f[i + K] - f[j + K]);
137 }
138
139 void ff_anlmdn_init(AudioNLMDNDSPContext *dsp)
140 {
141     dsp->compute_distance_ssd = compute_distance_ssd_c;
142     dsp->compute_cache        = compute_cache_c;
143
144     if (ARCH_X86)
145         ff_anlmdn_init_x86(dsp);
146 }
147
148 static int config_output(AVFilterLink *outlink)
149 {
150     AVFilterContext *ctx = outlink->src;
151     AudioNLMeansContext *s = ctx->priv;
152     int ret;
153
154     s->K = av_rescale(s->pd, outlink->sample_rate, AV_TIME_BASE);
155     s->S = av_rescale(s->rd, outlink->sample_rate, AV_TIME_BASE);
156
157     s->eof_left = -1;
158     s->pts = AV_NOPTS_VALUE;
159     s->H = s->K * 2 + 1;
160     s->N = s->H + (s->K + s->S) * 2;
161
162     av_log(ctx, AV_LOG_DEBUG, "K:%d S:%d H:%d N:%d\n", s->K, s->S, s->H, s->N);
163
164     av_frame_free(&s->in);
165     av_frame_free(&s->cache);
166     s->in = ff_get_audio_buffer(outlink, s->N);
167     if (!s->in)
168         return AVERROR(ENOMEM);
169
170     s->cache = ff_get_audio_buffer(outlink, s->S * 2);
171     if (!s->cache)
172         return AVERROR(ENOMEM);
173
174     s->fifo = av_audio_fifo_alloc(outlink->format, outlink->channels, s->N);
175     if (!s->fifo)
176         return AVERROR(ENOMEM);
177
178     ret = av_audio_fifo_write(s->fifo, (void **)s->in->extended_data, s->K + s->S);
179     if (ret < 0)
180         return ret;
181
182     s->pdiff_lut_scale = 1.f / s->m * WEIGHT_LUT_SIZE;
183     for (int i = 0; i < WEIGHT_LUT_SIZE; i++) {
184         float w = -i / s->pdiff_lut_scale;
185
186         s->weight_lut[i] = expf(w);
187     }
188
189     ff_anlmdn_init(&s->dsp);
190
191     return 0;
192 }
193
194 static int filter_channel(AVFilterContext *ctx, void *arg, int ch, int nb_jobs)
195 {
196     AudioNLMeansContext *s = ctx->priv;
197     AVFrame *out = arg;
198     const int S = s->S;
199     const int K = s->K;
200     const int om = s->om;
201     const float *f = (const float *)(s->in->extended_data[ch]) + K;
202     float *cache = (float *)s->cache->extended_data[ch];
203     const float sw = (65536.f / (4 * K + 2)) / sqrtf(s->a);
204     float *dst = (float *)out->extended_data[ch] + s->offset;
205     const float smooth = s->m;
206
207     for (int i = S; i < s->H + S; i++) {
208         float P = 0.f, Q = 0.f;
209         int v = 0;
210
211         if (i == S) {
212             for (int j = i - S; j <= i + S; j++) {
213                 if (i == j)
214                     continue;
215                 cache[v++] = s->dsp.compute_distance_ssd(f + i, f + j, K);
216             }
217         } else {
218             s->dsp.compute_cache(cache, f, S, K, i, i - S);
219             s->dsp.compute_cache(cache + S, f, S, K, i, i + 1);
220         }
221
222         for (int j = 0; j < 2 * S && !ctx->is_disabled; j++) {
223             const float distance = cache[j];
224             unsigned weight_lut_idx;
225             float w;
226
227             if (distance < 0.f) {
228                 cache[j] = 0.f;
229                 continue;
230             }
231             w = distance * sw;
232             if (w >= smooth)
233                 continue;
234             weight_lut_idx = w * s->pdiff_lut_scale;
235             av_assert2(weight_lut_idx < WEIGHT_LUT_SIZE);
236             w = s->weight_lut[weight_lut_idx];
237             P += w * f[i - S + j + (j >= S)];
238             Q += w;
239         }
240
241         P += f[i];
242         Q += 1;
243
244         switch (om) {
245         case IN_MODE:    dst[i - S] = f[i];           break;
246         case OUT_MODE:   dst[i - S] = P / Q;          break;
247         case NOISE_MODE: dst[i - S] = f[i] - (P / Q); break;
248         }
249     }
250
251     return 0;
252 }
253
254 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
255 {
256     AVFilterContext *ctx = inlink->dst;
257     AVFilterLink *outlink = ctx->outputs[0];
258     AudioNLMeansContext *s = ctx->priv;
259     AVFrame *out = NULL;
260     int available, wanted, ret;
261
262     if (s->pts == AV_NOPTS_VALUE)
263         s->pts = in->pts;
264
265     ret = av_audio_fifo_write(s->fifo, (void **)in->extended_data,
266                               in->nb_samples);
267     av_frame_free(&in);
268
269     s->offset = 0;
270     available = av_audio_fifo_size(s->fifo);
271     wanted = (available / s->H) * s->H;
272
273     if (wanted >= s->H && available >= s->N) {
274         out = ff_get_audio_buffer(outlink, wanted);
275         if (!out)
276             return AVERROR(ENOMEM);
277     }
278
279     while (available >= s->N) {
280         ret = av_audio_fifo_peek(s->fifo, (void **)s->in->extended_data, s->N);
281         if (ret < 0)
282             break;
283
284         ctx->internal->execute(ctx, filter_channel, out, NULL, inlink->channels);
285
286         av_audio_fifo_drain(s->fifo, s->H);
287
288         s->offset += s->H;
289         available -= s->H;
290     }
291
292     if (out) {
293         out->pts = s->pts;
294         out->nb_samples = s->offset;
295         if (s->eof_left >= 0) {
296             out->nb_samples = FFMIN(s->eof_left, s->offset);
297             s->eof_left -= out->nb_samples;
298         }
299         s->pts += s->offset;
300
301         return ff_filter_frame(outlink, out);
302     }
303
304     return ret;
305 }
306
307 static int request_frame(AVFilterLink *outlink)
308 {
309     AVFilterContext *ctx = outlink->src;
310     AudioNLMeansContext *s = ctx->priv;
311     int ret;
312
313     ret = ff_request_frame(ctx->inputs[0]);
314
315     if (ret == AVERROR_EOF && s->eof_left != 0) {
316         AVFrame *in;
317
318         if (s->eof_left < 0)
319             s->eof_left = av_audio_fifo_size(s->fifo) - (s->S + s->K);
320         if (s->eof_left < 0)
321             return AVERROR_EOF;
322         in = ff_get_audio_buffer(outlink, s->H);
323         if (!in)
324             return AVERROR(ENOMEM);
325
326         return filter_frame(ctx->inputs[0], in);
327     }
328
329     return ret;
330 }
331
332 static av_cold void uninit(AVFilterContext *ctx)
333 {
334     AudioNLMeansContext *s = ctx->priv;
335
336     av_audio_fifo_free(s->fifo);
337     av_frame_free(&s->in);
338     av_frame_free(&s->cache);
339 }
340
341 static const AVFilterPad inputs[] = {
342     {
343         .name         = "default",
344         .type         = AVMEDIA_TYPE_AUDIO,
345         .filter_frame = filter_frame,
346     },
347     { NULL }
348 };
349
350 static const AVFilterPad outputs[] = {
351     {
352         .name          = "default",
353         .type          = AVMEDIA_TYPE_AUDIO,
354         .config_props  = config_output,
355         .request_frame = request_frame,
356     },
357     { NULL }
358 };
359
360 AVFilter ff_af_anlmdn = {
361     .name          = "anlmdn",
362     .description   = NULL_IF_CONFIG_SMALL("Reduce broadband noise from stream using Non-Local Means."),
363     .query_formats = query_formats,
364     .priv_size     = sizeof(AudioNLMeansContext),
365     .priv_class    = &anlmdn_class,
366     .uninit        = uninit,
367     .inputs        = inputs,
368     .outputs       = outputs,
369     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL |
370                      AVFILTER_FLAG_SLICE_THREADS,
371 };