Browse code

lavfi: add nlmeans filter

Fixes Ticket #4910

Clément Bœsch authored on 2015/10/01 03:29:30
Showing 7 changed files
... ...
@@ -31,6 +31,7 @@ version <next>:
31 31
 - MediaCodec HEVC decoding
32 32
 - TrueHD encoder
33 33
 - Meridian Lossless Packing (MLP) encoder
34
+- Non-Local Means (nlmeans) denoising filter
34 35
 
35 36
 
36 37
 version 3.1:
... ...
@@ -9695,6 +9695,41 @@ Negate input video.
9695 9695
 It accepts an integer in input; if non-zero it negates the
9696 9696
 alpha component (if available). The default value in input is 0.
9697 9697
 
9698
+@section nlmeans
9699
+
9700
+Denoise frames using Non-Local Means algorithm.
9701
+
9702
+Each pixel is adjusted by looking for other pixels with similar contexts. This
9703
+context similarity is defined by comparing their surrounding patches of size
9704
+@option{p}x@option{p}. Patches are searched in an area of @option{r}x@option{r}
9705
+around the pixel.
9706
+
9707
+Note that the research area defines centers for patches, which means some
9708
+patches will be made of pixels outside that research area.
9709
+
9710
+The filter accepts the following options.
9711
+
9712
+@table @option
9713
+@item s
9714
+Set denoising strength.
9715
+
9716
+@item p
9717
+Set patch size.
9718
+
9719
+@item pc
9720
+Same as @option{p} but for chroma planes.
9721
+
9722
+The default value is @var{0} and means automatic.
9723
+
9724
+@item r
9725
+Set research size.
9726
+
9727
+@item rc
9728
+Same as @option{r} but for chroma planes.
9729
+
9730
+The default value is @var{0} and means automatic.
9731
+@end table
9732
+
9698 9733
 @section nnedi
9699 9734
 
9700 9735
 Deinterlace video using neural network edge directed interpolation.
... ...
@@ -220,6 +220,7 @@ OBJS-$(CONFIG_METADATA_FILTER)               += f_metadata.o
220 220
 OBJS-$(CONFIG_MINTERPOLATE_FILTER)           += vf_minterpolate.o motion_estimation.o
221 221
 OBJS-$(CONFIG_MPDECIMATE_FILTER)             += vf_mpdecimate.o
222 222
 OBJS-$(CONFIG_NEGATE_FILTER)                 += vf_lut.o
223
+OBJS-$(CONFIG_NLMEANS_FILTER)                += vf_nlmeans.o
223 224
 OBJS-$(CONFIG_NNEDI_FILTER)                  += vf_nnedi.o
224 225
 OBJS-$(CONFIG_NOFORMAT_FILTER)               += vf_format.o
225 226
 OBJS-$(CONFIG_NOISE_FILTER)                  += vf_noise.o
... ...
@@ -354,7 +355,7 @@ SKIPHEADERS-$(CONFIG_OPENCL)                 += opencl_internal.h deshake_opencl
354 354
 OBJS-$(CONFIG_SHARED)                        += log2_tab.o
355 355
 
356 356
 TOOLS     = graph2dot
357
-TESTPROGS = drawutils filtfmts formats
357
+TESTPROGS = drawutils filtfmts formats integral
358 358
 
359 359
 TOOLS-$(CONFIG_LIBZMQ) += zmqsend
360 360
 
... ...
@@ -237,6 +237,7 @@ void avfilter_register_all(void)
237 237
     REGISTER_FILTER(MINTERPOLATE,   minterpolate,   vf);
238 238
     REGISTER_FILTER(MPDECIMATE,     mpdecimate,     vf);
239 239
     REGISTER_FILTER(NEGATE,         negate,         vf);
240
+    REGISTER_FILTER(NLMEANS,        nlmeans,        vf);
240 241
     REGISTER_FILTER(NNEDI,          nnedi,          vf);
241 242
     REGISTER_FILTER(NOFORMAT,       noformat,       vf);
242 243
     REGISTER_FILTER(NOISE,          noise,          vf);
243 244
new file mode 100644
... ...
@@ -0,0 +1,92 @@
0
+/*
1
+ * This file is part of FFmpeg.
2
+ *
3
+ * FFmpeg is free software; you can redistribute it and/or
4
+ * modify it under the terms of the GNU Lesser General Public
5
+ * License as published by the Free Software Foundation; either
6
+ * version 2.1 of the License, or (at your option) any later version.
7
+ *
8
+ * FFmpeg is distributed in the hope that it will be useful,
9
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11
+ * Lesser General Public License for more details.
12
+ *
13
+ * You should have received a copy of the GNU Lesser General Public
14
+ * License along with FFmpeg; if not, write to the Free Software
15
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
+ */
17
+
18
+#include "libavfilter/vf_nlmeans.c"
19
+
20
+static void display_integral(const uint32_t *ii, int w, int h, int lz_32)
21
+{
22
+    int x, y;
23
+
24
+    for (y = 0; y < h; y++) {
25
+        for (x = 0; x < w; x++)
26
+            printf(" %7x", ii[y*lz_32 + x]);
27
+        printf("\n");
28
+    }
29
+    printf("---------------\n");
30
+}
31
+
32
+int main(void)
33
+{
34
+    int ret = 0, xoff, yoff;
35
+
36
+    // arbitrary test source of size 6x4 and linesize=8
37
+    const int w = 6, h = 5, lz = 8;
38
+    static const uint8_t src[] = {
39
+        0xb0, 0x71, 0xfb, 0xd8, 0x01, 0xd9, /***/ 0x01, 0x02,
40
+        0x51, 0x8e, 0x41, 0x0f, 0x84, 0x58, /***/ 0x03, 0x04,
41
+        0xc7, 0x8d, 0x07, 0x70, 0x5c, 0x47, /***/ 0x05, 0x06,
42
+        0x09, 0x4e, 0xfc, 0x74, 0x8f, 0x9a, /***/ 0x07, 0x08,
43
+        0x60, 0x8e, 0x20, 0xaa, 0x95, 0x7d, /***/ 0x09, 0x0a,
44
+    };
45
+
46
+    const int e = 3;
47
+    const int ii_w = w+e*2, ii_h = h+e*2;
48
+
49
+    // align to 4 the linesize, "+1" is for the space of the left 0-column
50
+    const int ii_lz_32 = ((ii_w + 1) + 3) & ~3;
51
+
52
+    // "+1" is for the space of the top 0-line
53
+    uint32_t *ii  = av_mallocz_array(ii_h + 1, ii_lz_32 * sizeof(*ii));
54
+    uint32_t *ii2 = av_mallocz_array(ii_h + 1, ii_lz_32 * sizeof(*ii2));
55
+
56
+    uint32_t *ii_start  = ii  + ii_lz_32 + 1; // skip top 0-line and left 0-column
57
+    uint32_t *ii_start2 = ii2 + ii_lz_32 + 1; // skip top 0-line and left 0-column
58
+
59
+    if (!ii || !ii2)
60
+        return -1;
61
+
62
+    for (yoff = -e; yoff <= e; yoff++) {
63
+        for (xoff = -e; xoff <= e; xoff++) {
64
+            int x, y;
65
+
66
+            printf("xoff=%d yoff=%d\n", xoff, yoff);
67
+
68
+            compute_ssd_integral_image(ii_start, ii_lz_32,
69
+                                       src, lz, xoff, yoff, e, w, h);
70
+            display_integral(ii_start, ii_w, ii_h, ii_lz_32);
71
+
72
+            compute_unsafe_ssd_integral_image(ii_start2, ii_lz_32,
73
+                                              0, 0,
74
+                                              src, lz,
75
+                                              xoff, yoff, e, w, h,
76
+                                              ii_w, ii_h);
77
+            display_integral(ii_start2, ii_w, ii_h, ii_lz_32);
78
+
79
+            if (memcmp(ii, ii2, (ii_h+1) * ii_lz_32 * sizeof(*ii))) {
80
+                printf("Integral mismatch\n");
81
+                ret = 1;
82
+                goto end;
83
+            }
84
+        }
85
+    }
86
+
87
+end:
88
+    av_freep(&ii);
89
+    av_freep(&ii2);
90
+    return ret;
91
+}
... ...
@@ -30,7 +30,7 @@
30 30
 #include "libavutil/version.h"
31 31
 
32 32
 #define LIBAVFILTER_VERSION_MAJOR   6
33
-#define LIBAVFILTER_VERSION_MINOR  62
33
+#define LIBAVFILTER_VERSION_MINOR  63
34 34
 #define LIBAVFILTER_VERSION_MICRO 100
35 35
 
36 36
 #define LIBAVFILTER_VERSION_INT AV_VERSION_INT(LIBAVFILTER_VERSION_MAJOR, \
37 37
new file mode 100644
... ...
@@ -0,0 +1,551 @@
0
+/*
1
+ * Copyright (c) 2016 Clément Bœsch <u pkh me>
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+/**
21
+ * @todo
22
+ * - SIMD for compute_safe_ssd_integral_image
23
+ * - SIMD for final weighted averaging
24
+ * - better automatic defaults? see "Parameters" @ http://www.ipol.im/pub/art/2011/bcm_nlm/
25
+ * - temporal support (probably doesn't need any displacement according to
26
+ *   "Denoising image sequences does not require motion estimation")
27
+ * - Bayer pixel format support for at least raw photos? (DNG support would be
28
+ *   handy here)
29
+ * - FATE test (probably needs visual threshold test mechanism due to the use
30
+ *   of floats)
31
+ */
32
+
33
+#include "libavutil/avassert.h"
34
+#include "libavutil/opt.h"
35
+#include "libavutil/pixdesc.h"
36
+#include "avfilter.h"
37
+#include "formats.h"
38
+#include "internal.h"
39
+#include "video.h"
40
+
41
+struct weighted_avg {
42
+    double total_weight;
43
+    double sum;
44
+};
45
+
46
+#define WEIGHT_LUT_NBITS 9
47
+#define WEIGHT_LUT_SIZE  (1<<WEIGHT_LUT_NBITS)
48
+
49
+typedef struct {
50
+    const AVClass *class;
51
+    int nb_planes;
52
+    int chroma_w, chroma_h;
53
+    double pdiff_scale;                         // invert of the filtering parameter (sigma*10) squared
54
+    double sigma;                               // denoising strength
55
+    int patch_size,    patch_hsize;             // patch size and half size
56
+    int patch_size_uv, patch_hsize_uv;          // patch size and half size for chroma planes
57
+    int research_size,    research_hsize;       // research size and half size
58
+    int research_size_uv, research_hsize_uv;    // research size and half size for chroma planes
59
+    uint32_t *ii_orig;                          // integral image
60
+    uint32_t *ii;                               // integral image starting after the 0-line and 0-column
61
+    int ii_w, ii_h;                             // width and height of the integral image
62
+    int ii_lz_32;                               // linesize in 32-bit units of the integral image
63
+    struct weighted_avg *wa;                    // weighted average of every pixel
64
+    int wa_linesize;                            // linesize for wa in struct size unit
65
+    double weight_lut[WEIGHT_LUT_SIZE];         // lookup table mapping (scaled) patch differences to their associated weights
66
+    double pdiff_lut_scale;                     // scale factor for patch differences before looking into the LUT
67
+    int max_meaningful_diff;                    // maximum difference considered (if the patch difference is too high we ignore the pixel)
68
+} NLMeansContext;
69
+
70
+#define OFFSET(x) offsetof(NLMeansContext, x)
71
+#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
72
+static const AVOption nlmeans_options[] = {
73
+    { "s",  "denoising strength", OFFSET(sigma), AV_OPT_TYPE_DOUBLE, { .dbl = 1.0 }, 1.0, 30.0, FLAGS },
74
+    { "p",  "patch size",                   OFFSET(patch_size),    AV_OPT_TYPE_INT, { .i64 = 3*2+1 }, 0, 99, FLAGS },
75
+    { "pc", "patch size for chroma planes", OFFSET(patch_size_uv), AV_OPT_TYPE_INT, { .i64 = 0 },     0, 99, FLAGS },
76
+    { "r",  "research window",                   OFFSET(research_size),    AV_OPT_TYPE_INT, { .i64 = 7*2+1 }, 0, 99, FLAGS },
77
+    { "rc", "research window for chroma planes", OFFSET(research_size_uv), AV_OPT_TYPE_INT, { .i64 = 0 },     0, 99, FLAGS },
78
+    { NULL }
79
+};
80
+
81
+AVFILTER_DEFINE_CLASS(nlmeans);
82
+
83
+static int query_formats(AVFilterContext *ctx)
84
+{
85
+    static const enum AVPixelFormat pix_fmts[] = {
86
+        AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
87
+        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
88
+        AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
89
+        AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P,
90
+        AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,
91
+        AV_PIX_FMT_YUVJ411P,
92
+        AV_PIX_FMT_GRAY8, AV_PIX_FMT_GBRP,
93
+        AV_PIX_FMT_NONE
94
+    };
95
+
96
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
97
+    if (!fmts_list)
98
+        return AVERROR(ENOMEM);
99
+    return ff_set_common_formats(ctx, fmts_list);
100
+}
101
+
102
+/*
103
+ * M is a discrete map where every entry contains the sum of all the entries
104
+ * in the rectangle from the top-left origin of M to its coordinate. In the
105
+ * following schema, "i" contains the sum of the whole map:
106
+ *
107
+ * M = +----------+-----------------+----+
108
+ *     |          |                 |    |
109
+ *     |          |                 |    |
110
+ *     |         a|                b|   c|
111
+ *     +----------+-----------------+----+
112
+ *     |          |                 |    |
113
+ *     |          |                 |    |
114
+ *     |          |        X        |    |
115
+ *     |          |                 |    |
116
+ *     |         d|                e|   f|
117
+ *     +----------+-----------------+----+
118
+ *     |          |                 |    |
119
+ *     |         g|                h|   i|
120
+ *     +----------+-----------------+----+
121
+ *
122
+ * The sum of the X box can be calculated with:
123
+ *    X = e-d-b+a
124
+ *
125
+ * See https://en.wikipedia.org/wiki/Summed_area_table
126
+ *
127
+ * The compute*_ssd functions compute the integral image M where every entry
128
+ * contains the sum of the squared difference of every corresponding pixels of
129
+ * two input planes of the same size as M.
130
+ */
131
+static inline int get_integral_patch_value(const uint32_t *ii, int ii_lz_32, int x, int y, int p)
132
+{
133
+    const int e = ii[(y + p    ) * ii_lz_32 + (x + p    )];
134
+    const int d = ii[(y + p    ) * ii_lz_32 + (x - p - 1)];
135
+    const int b = ii[(y - p - 1) * ii_lz_32 + (x + p    )];
136
+    const int a = ii[(y - p - 1) * ii_lz_32 + (x - p - 1)];
137
+    return e - d - b + a;
138
+}
139
+
140
+/**
141
+ * Compute squared difference of the safe area (the zone where s1 and s2
142
+ * overlap). It is likely the largest integral zone, so it is interesting to do
143
+ * as little checks as possible; contrary to the unsafe version of this
144
+ * function, we do not need any clipping here.
145
+ *
146
+ * The line above dst and the column to its left are always readable.
147
+ *
148
+ * This C version computes the SSD integral image using a scalar accumulator,
149
+ * while for SIMD implementation it is likely more interesting to use the
150
+ * two-loops algorithm variant.
151
+ */
152
+static void compute_safe_ssd_integral_image_c(uint32_t *dst, int dst_linesize_32,
153
+                                              const uint8_t *s1, int linesize1,
154
+                                              const uint8_t *s2, int linesize2,
155
+                                              int w, int h)
156
+{
157
+    int x, y;
158
+
159
+    for (y = 0; y < h; y++) {
160
+        uint32_t acc = dst[-1] - dst[-dst_linesize_32 - 1];
161
+
162
+        for (x = 0; x < w; x++) {
163
+            const int d  = s1[x] - s2[x];
164
+            acc += d * d;
165
+            dst[x] = dst[-dst_linesize_32 + x] + acc;
166
+        }
167
+        s1  += linesize1;
168
+        s2  += linesize2;
169
+        dst += dst_linesize_32;
170
+    }
171
+}
172
+
173
+/**
174
+ * Compute squared difference of an unsafe area (the zone nor s1 nor s2 could
175
+ * be readable).
176
+ *
177
+ * On the other hand, the line above dst and the column to its left are always
178
+ * readable.
179
+ *
180
+ * There is little point in having this function SIMDified as it is likely too
181
+ * complex and only handle small portions of the image.
182
+ *
183
+ * @param dst               integral image
184
+ * @param dst_linesize_32   integral image linesize (in 32-bit integers unit)
185
+ * @param startx            integral starting x position
186
+ * @param starty            integral starting y position
187
+ * @param src               source plane buffer
188
+ * @param linesize          source plane linesize
189
+ * @param offx              source offsetting in x
190
+ * @param offy              source offsetting in y
191
+ * @paran r                 absolute maximum source offsetting
192
+ * @param sw                source width
193
+ * @param sh                source height
194
+ * @param w                 width to compute
195
+ * @param h                 height to compute
196
+ */
197
+static inline void compute_unsafe_ssd_integral_image(uint32_t *dst, int dst_linesize_32,
198
+                                                     int startx, int starty,
199
+                                                     const uint8_t *src, int linesize,
200
+                                                     int offx, int offy, int r, int sw, int sh,
201
+                                                     int w, int h)
202
+{
203
+    int x, y;
204
+
205
+    for (y = starty; y < starty + h; y++) {
206
+        uint32_t acc = dst[y*dst_linesize_32 + startx - 1] - dst[(y-1)*dst_linesize_32 + startx - 1];
207
+        const int s1y = av_clip(y -  r,         0, sh - 1);
208
+        const int s2y = av_clip(y - (r + offy), 0, sh - 1);
209
+
210
+        for (x = startx; x < startx + w; x++) {
211
+            const int s1x = av_clip(x -  r,         0, sw - 1);
212
+            const int s2x = av_clip(x - (r + offx), 0, sw - 1);
213
+            const uint8_t v1 = src[s1y*linesize + s1x];
214
+            const uint8_t v2 = src[s2y*linesize + s2x];
215
+            const int d = v1 - v2;
216
+            acc += d * d;
217
+            dst[y*dst_linesize_32 + x] = dst[(y-1)*dst_linesize_32 + x] + acc;
218
+        }
219
+    }
220
+}
221
+
222
+/*
223
+ * Compute the sum of squared difference integral image
224
+ * http://www.ipol.im/pub/art/2014/57/
225
+ * Integral Images for Block Matching - Gabriele Facciolo, Nicolas Limare, Enric Meinhardt-Llopis
226
+ *
227
+ * @param ii                integral image of dimension (w+e*2) x (h+e*2) with
228
+ *                          an additional zeroed top line and column already
229
+ *                          "applied" to the pointer value
230
+ * @param ii_linesize_32    integral image linesize (in 32-bit integers unit)
231
+ * @param src               source plane buffer
232
+ * @param linesize          source plane linesize
233
+ * @param offx              x-offsetting ranging in [-e;e]
234
+ * @param offy              y-offsetting ranging in [-e;e]
235
+ * @param w                 source width
236
+ * @param h                 source height
237
+ * @param e                 research padding edge
238
+ */
239
+static void compute_ssd_integral_image(uint32_t *ii, int ii_linesize_32,
240
+                                       const uint8_t *src, int linesize, int offx, int offy,
241
+                                       int e, int w, int h)
242
+{
243
+    // ii has a surrounding padding of thickness "e"
244
+    const int ii_w = w + e*2;
245
+    const int ii_h = h + e*2;
246
+
247
+    // we center the first source
248
+    const int s1x = e;
249
+    const int s1y = e;
250
+
251
+    // 2nd source is the frame with offsetting
252
+    const int s2x = e + offx;
253
+    const int s2y = e + offy;
254
+
255
+    // get the dimension of the overlapping rectangle where it is always safe
256
+    // to compare the 2 sources pixels
257
+    const int startx_safe = FFMAX(s1x, s2x);
258
+    const int starty_safe = FFMAX(s1y, s2y);
259
+    const int endx_safe   = FFMIN(s1x + w, s2x + w);
260
+    const int endy_safe   = FFMIN(s1y + h, s2y + h);
261
+
262
+    // top part where only one of s1 and s2 is still readable, or none at all
263
+    compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
264
+                                      0, 0,
265
+                                      src, linesize,
266
+                                      offx, offy, e, w, h,
267
+                                      ii_w, starty_safe);
268
+
269
+    // fill the left column integral required to compute the central
270
+    // overlapping one
271
+    compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
272
+                                      0, starty_safe,
273
+                                      src, linesize,
274
+                                      offx, offy, e, w, h,
275
+                                      startx_safe, endy_safe - starty_safe);
276
+
277
+    // main and safe part of the integral
278
+    av_assert1(startx_safe - s1x >= 0); av_assert1(startx_safe - s1x < w);
279
+    av_assert1(starty_safe - s1y >= 0); av_assert1(starty_safe - s1y < h);
280
+    av_assert1(startx_safe - s2x >= 0); av_assert1(startx_safe - s2x < w);
281
+    av_assert1(starty_safe - s2y >= 0); av_assert1(starty_safe - s2y < h);
282
+    compute_safe_ssd_integral_image_c(ii + starty_safe*ii_linesize_32 + startx_safe, ii_linesize_32,
283
+                                      src + (starty_safe - s1y) * linesize + (startx_safe - s1x), linesize,
284
+                                      src + (starty_safe - s2y) * linesize + (startx_safe - s2x), linesize,
285
+                                      endx_safe - startx_safe, endy_safe - starty_safe);
286
+
287
+    // right part of the integral
288
+    compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
289
+                                      endx_safe, starty_safe,
290
+                                      src, linesize,
291
+                                      offx, offy, e, w, h,
292
+                                      ii_w - endx_safe, endy_safe - starty_safe);
293
+
294
+    // bottom part where only one of s1 and s2 is still readable, or none at all
295
+    compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
296
+                                      0, endy_safe,
297
+                                      src, linesize,
298
+                                      offx, offy, e, w, h,
299
+                                      ii_w, ii_h - endy_safe);
300
+}
301
+
302
+static int config_input(AVFilterLink *inlink)
303
+{
304
+    AVFilterContext *ctx = inlink->dst;
305
+    NLMeansContext *s = ctx->priv;
306
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
307
+    const int e = FFMAX(s->research_hsize, s->research_hsize_uv)
308
+                + FFMAX(s->patch_hsize,    s->patch_hsize_uv);
309
+
310
+    s->chroma_w = FF_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
311
+    s->chroma_h = FF_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
312
+    s->nb_planes = av_pix_fmt_count_planes(inlink->format);
313
+
314
+    /* Allocate the integral image with extra edges of thickness "e"
315
+     *
316
+     *   +_+-------------------------------+
317
+     *   |0|0000000000000000000000000000000|
318
+     *   +-x-------------------------------+
319
+     *   |0|\    ^                         |
320
+     *   |0| ii  | e                       |
321
+     *   |0|     v                         |
322
+     *   |0|   +-----------------------+   |
323
+     *   |0|   |                       |   |
324
+     *   |0|<->|                       |   |
325
+     *   |0| e |                       |   |
326
+     *   |0|   |                       |   |
327
+     *   |0|   +-----------------------+   |
328
+     *   |0|                               |
329
+     *   |0|                               |
330
+     *   |0|                               |
331
+     *   +-+-------------------------------+
332
+     */
333
+    s->ii_w = inlink->w + e*2;
334
+    s->ii_h = inlink->h + e*2;
335
+
336
+    // align to 4 the linesize, "+1" is for the space of the left 0-column
337
+    s->ii_lz_32 = FFALIGN(s->ii_w + 1, 4);
338
+
339
+    // "+1" is for the space of the top 0-line
340
+    s->ii_orig = av_mallocz_array(s->ii_h + 1, s->ii_lz_32 * sizeof(*s->ii_orig));
341
+    if (!s->ii_orig)
342
+        return AVERROR(ENOMEM);
343
+
344
+    // skip top 0-line and left 0-column
345
+    s->ii = s->ii_orig + s->ii_lz_32 + 1;
346
+
347
+    // allocate weighted average for every pixel
348
+    s->wa_linesize = inlink->w;
349
+    s->wa = av_malloc_array(s->wa_linesize, inlink->h * sizeof(*s->wa));
350
+    if (!s->wa)
351
+        return AVERROR(ENOMEM);
352
+
353
+    return 0;
354
+}
355
+
356
+struct thread_data {
357
+    const uint8_t *src;
358
+    int src_linesize;
359
+    int startx, starty;
360
+    int endx, endy;
361
+    const uint32_t *ii_start;
362
+    int p;
363
+};
364
+
365
+static int nlmeans_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
366
+{
367
+    int x, y;
368
+    NLMeansContext *s = ctx->priv;
369
+    const struct thread_data *td = arg;
370
+    const uint8_t *src = td->src;
371
+    const int src_linesize = td->src_linesize;
372
+    const int process_h = td->endy - td->starty;
373
+    const int slice_start = (process_h *  jobnr   ) / nb_jobs;
374
+    const int slice_end   = (process_h * (jobnr+1)) / nb_jobs;
375
+    const int starty = td->starty + slice_start;
376
+    const int endy   = td->starty + slice_end;
377
+
378
+    for (y = starty; y < endy; y++) {
379
+        for (x = td->startx; x < td->endx; x++) {
380
+            const int patch_diff_sq = get_integral_patch_value(td->ii_start, s->ii_lz_32, x, y, td->p);
381
+            if (patch_diff_sq < s->max_meaningful_diff) {
382
+                struct weighted_avg *wa = &s->wa[y*s->wa_linesize + x];
383
+                const int weight_lut_idx = patch_diff_sq * s->pdiff_lut_scale;
384
+                const double weight = s->weight_lut[weight_lut_idx]; // exp(-patch_diff_sq * s->pdiff_scale)
385
+                wa->total_weight += weight;
386
+                wa->sum += weight * src[y*src_linesize + x];
387
+            }
388
+        }
389
+    }
390
+    return 0;
391
+}
392
+
393
+static int nlmeans_plane(AVFilterContext *ctx, int w, int h, int p, int r,
394
+                         uint8_t *dst, int dst_linesize,
395
+                         const uint8_t *src, int src_linesize)
396
+{
397
+    int x, y;
398
+    int offx, offy;
399
+    NLMeansContext *s = ctx->priv;
400
+    /* patches center points cover the whole research window so the patches
401
+     * themselves overflow the research window */
402
+    const int e = r + p;
403
+    /* focus an integral pointer on the centered image (s1) */
404
+    const uint32_t *centered_ii = s->ii + e*s->ii_lz_32 + e;
405
+
406
+    memset(s->wa, 0, s->wa_linesize * h * sizeof(*s->wa));
407
+
408
+    for (offy = -r; offy <= r; offy++) {
409
+        for (offx = -r; offx <= r; offx++) {
410
+            if (offx || offy) {
411
+                struct thread_data td = {
412
+                    .src          = src + offy*src_linesize + offx,
413
+                    .src_linesize = src_linesize,
414
+                    .startx       = FFMAX(0, -offx),
415
+                    .starty       = FFMAX(0, -offy),
416
+                    .endx         = FFMIN(w, w - offx),
417
+                    .endy         = FFMIN(h, h - offy),
418
+                    .ii_start     = centered_ii + offy*s->ii_lz_32 + offx,
419
+                    .p            = p,
420
+                };
421
+
422
+                compute_ssd_integral_image(s->ii, s->ii_lz_32,
423
+                                           src, src_linesize,
424
+                                           offx, offy, e, w, h);
425
+                ctx->internal->execute(ctx, nlmeans_slice, &td, NULL,
426
+                                       FFMIN(td.endy - td.starty, ff_filter_get_nb_threads(ctx)));
427
+            }
428
+        }
429
+    }
430
+    for (y = 0; y < h; y++) {
431
+        for (x = 0; x < w; x++) {
432
+            struct weighted_avg *wa = &s->wa[y*s->wa_linesize + x];
433
+
434
+            // Also weight the centered pixel
435
+            wa->total_weight += 1.0;
436
+            wa->sum += 1.0 * src[y*src_linesize + x];
437
+
438
+            dst[y*dst_linesize + x] = av_clip_uint8(wa->sum / wa->total_weight);
439
+        }
440
+    }
441
+    return 0;
442
+}
443
+
444
+static int filter_frame(AVFilterLink *inlink, AVFrame *in)
445
+{
446
+    int i;
447
+    AVFilterContext *ctx = inlink->dst;
448
+    NLMeansContext *s = ctx->priv;
449
+    AVFilterLink *outlink = ctx->outputs[0];
450
+
451
+    AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
452
+    if (!out) {
453
+        av_frame_free(&in);
454
+        return AVERROR(ENOMEM);
455
+    }
456
+    av_frame_copy_props(out, in);
457
+
458
+    for (i = 0; i < s->nb_planes; i++) {
459
+        const int w = i ? s->chroma_w          : inlink->w;
460
+        const int h = i ? s->chroma_h          : inlink->h;
461
+        const int p = i ? s->patch_hsize_uv    : s->patch_hsize;
462
+        const int r = i ? s->research_hsize_uv : s->research_hsize;
463
+        nlmeans_plane(ctx, w, h, p, r,
464
+                      out->data[i], out->linesize[i],
465
+                      in->data[i],  in->linesize[i]);
466
+    }
467
+
468
+    av_frame_free(&in);
469
+    return ff_filter_frame(outlink, out);
470
+}
471
+
472
+#define CHECK_ODD_FIELD(field, name) do {                       \
473
+    if (!(s->field & 1)) {                                      \
474
+        s->field |= 1;                                          \
475
+        av_log(ctx, AV_LOG_WARNING, name " size must be odd, "  \
476
+               "setting it to %d\n", s->field);                 \
477
+    }                                                           \
478
+} while (0)
479
+
480
+static av_cold int init(AVFilterContext *ctx)
481
+{
482
+    int i;
483
+    NLMeansContext *s = ctx->priv;
484
+    const double h = s->sigma * 10.;
485
+
486
+    s->pdiff_scale = 1. / (h * h);
487
+    s->max_meaningful_diff = -log(1/255.) / s->pdiff_scale;
488
+    s->pdiff_lut_scale = 1./s->max_meaningful_diff * WEIGHT_LUT_SIZE;
489
+    av_assert0((s->max_meaningful_diff - 1) * s->pdiff_lut_scale < FF_ARRAY_ELEMS(s->weight_lut));
490
+    for (i = 0; i < WEIGHT_LUT_SIZE; i++)
491
+        s->weight_lut[i] = exp(-i / s->pdiff_lut_scale * s->pdiff_scale);
492
+
493
+    CHECK_ODD_FIELD(research_size,   "Luma research window");
494
+    CHECK_ODD_FIELD(patch_size,      "Luma patch");
495
+
496
+    if (!s->research_size_uv) s->research_size_uv = s->research_size;
497
+    if (!s->patch_size_uv)    s->patch_size_uv    = s->patch_size;
498
+
499
+    CHECK_ODD_FIELD(research_size_uv, "Chroma research window");
500
+    CHECK_ODD_FIELD(patch_size_uv,    "Chroma patch");
501
+
502
+    s->research_hsize    = s->research_size    / 2;
503
+    s->research_hsize_uv = s->research_size_uv / 2;
504
+    s->patch_hsize       = s->patch_size       / 2;
505
+    s->patch_hsize_uv    = s->patch_size_uv    / 2;
506
+
507
+    av_log(ctx, AV_LOG_INFO, "Research window: %dx%d / %dx%d, patch size: %dx%d / %dx%d\n",
508
+           s->research_size, s->research_size, s->research_size_uv, s->research_size_uv,
509
+           s->patch_size,    s->patch_size,    s->patch_size_uv,    s->patch_size_uv);
510
+
511
+    return 0;
512
+}
513
+
514
+static av_cold void uninit(AVFilterContext *ctx)
515
+{
516
+    NLMeansContext *s = ctx->priv;
517
+    av_freep(&s->ii_orig);
518
+    av_freep(&s->wa);
519
+}
520
+
521
+static const AVFilterPad nlmeans_inputs[] = {
522
+    {
523
+        .name         = "default",
524
+        .type         = AVMEDIA_TYPE_VIDEO,
525
+        .config_props = config_input,
526
+        .filter_frame = filter_frame,
527
+    },
528
+    { NULL }
529
+};
530
+
531
+static const AVFilterPad nlmeans_outputs[] = {
532
+    {
533
+        .name = "default",
534
+        .type = AVMEDIA_TYPE_VIDEO,
535
+    },
536
+    { NULL }
537
+};
538
+
539
+AVFilter ff_vf_nlmeans = {
540
+    .name          = "nlmeans",
541
+    .description   = NULL_IF_CONFIG_SMALL("Non-local means denoiser."),
542
+    .priv_size     = sizeof(NLMeansContext),
543
+    .init          = init,
544
+    .uninit        = uninit,
545
+    .query_formats = query_formats,
546
+    .inputs        = nlmeans_inputs,
547
+    .outputs       = nlmeans_outputs,
548
+    .priv_class    = &nlmeans_class,
549
+    .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
550
+};