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