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