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