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