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