2 * Copyright (c) 2016 Clément Bœsch <u pkh me>
4 * This file is part of FFmpeg.
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.
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.
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
23 * - better automatic defaults? see "Parameters" @ http://www.ipol.im/pub/art/2011/bcm_nlm/
24 * - temporal support (probably doesn't need any displacement according to
25 * "Denoising image sequences does not require motion estimation")
26 * - Bayer pixel format support for at least raw photos? (DNG support would be
28 * - FATE test (probably needs visual threshold test mechanism due to the use
32 #include "libavutil/avassert.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/pixdesc.h"
38 #include "vf_nlmeans.h"
46 #define WEIGHT_LUT_NBITS 9
47 #define WEIGHT_LUT_SIZE (1<<WEIGHT_LUT_NBITS)
49 typedef struct NLMeansContext {
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 ptrdiff_t ii_lz_32; // linesize in 32-bit units of the integral image
63 struct weighted_avg *wa; // weighted average of every pixel
64 ptrdiff_t wa_linesize; // linesize for wa in struct size unit
65 float weight_lut[WEIGHT_LUT_SIZE]; // lookup table mapping (scaled) patch differences to their associated weights
66 float 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 NLMeansDSPContext dsp;
71 #define OFFSET(x) offsetof(NLMeansContext, x)
72 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
73 static const AVOption nlmeans_options[] = {
74 { "s", "denoising strength", OFFSET(sigma), AV_OPT_TYPE_DOUBLE, { .dbl = 1.0 }, 1.0, 30.0, FLAGS },
75 { "p", "patch size", OFFSET(patch_size), AV_OPT_TYPE_INT, { .i64 = 3*2+1 }, 0, 99, FLAGS },
76 { "pc", "patch size for chroma planes", OFFSET(patch_size_uv), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 99, FLAGS },
77 { "r", "research window", OFFSET(research_size), AV_OPT_TYPE_INT, { .i64 = 7*2+1 }, 0, 99, FLAGS },
78 { "rc", "research window for chroma planes", OFFSET(research_size_uv), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 99, FLAGS },
82 AVFILTER_DEFINE_CLASS(nlmeans);
84 static int query_formats(AVFilterContext *ctx)
86 static const enum AVPixelFormat pix_fmts[] = {
87 AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
88 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
89 AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
90 AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P,
91 AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,
93 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GBRP,
97 AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
99 return AVERROR(ENOMEM);
100 return ff_set_common_formats(ctx, fmts_list);
104 * M is a discrete map where every entry contains the sum of all the entries
105 * in the rectangle from the top-left origin of M to its coordinate. In the
106 * following schema, "i" contains the sum of the whole map:
108 * M = +----------+-----------------+----+
112 * +----------+-----------------+----+
118 * +----------+-----------------+----+
121 * +----------+-----------------+----+
123 * The sum of the X box can be calculated with:
126 * See https://en.wikipedia.org/wiki/Summed_area_table
128 * The compute*_ssd functions compute the integral image M where every entry
129 * contains the sum of the squared difference of every corresponding pixels of
130 * two input planes of the same size as M.
132 static inline int get_integral_patch_value(const uint32_t *ii, int ii_lz_32, int x, int y, int p)
134 const int a = ii[(y - p - 1) * ii_lz_32 + (x - p - 1)];
135 const int b = ii[(y - p - 1) * ii_lz_32 + (x + p )];
136 const int d = ii[(y + p ) * ii_lz_32 + (x - p - 1)];
137 const int e = ii[(y + p ) * ii_lz_32 + (x + p )];
138 return e - d - b + a;
142 * Compute squared difference of the safe area (the zone where s1 and s2
143 * overlap). It is likely the largest integral zone, so it is interesting to do
144 * as little checks as possible; contrary to the unsafe version of this
145 * function, we do not need any clipping here.
147 * The line above dst and the column to its left are always readable.
149 static void compute_safe_ssd_integral_image_c(uint32_t *dst, ptrdiff_t dst_linesize_32,
150 const uint8_t *s1, ptrdiff_t linesize1,
151 const uint8_t *s2, ptrdiff_t linesize2,
155 const uint32_t *dst_top = dst - dst_linesize_32;
157 /* SIMD-friendly assumptions allowed here */
158 av_assert2(!(w & 0xf) && w >= 16 && h >= 1);
160 for (y = 0; y < h; y++) {
161 for (x = 0; x < w; x += 4) {
162 const int d0 = s1[x ] - s2[x ];
163 const int d1 = s1[x + 1] - s2[x + 1];
164 const int d2 = s1[x + 2] - s2[x + 2];
165 const int d3 = s1[x + 3] - s2[x + 3];
167 dst[x ] = dst_top[x ] - dst_top[x - 1] + d0*d0;
168 dst[x + 1] = dst_top[x + 1] - dst_top[x ] + d1*d1;
169 dst[x + 2] = dst_top[x + 2] - dst_top[x + 1] + d2*d2;
170 dst[x + 3] = dst_top[x + 3] - dst_top[x + 2] + d3*d3;
172 dst[x ] += dst[x - 1];
173 dst[x + 1] += dst[x ];
174 dst[x + 2] += dst[x + 1];
175 dst[x + 3] += dst[x + 2];
179 dst += dst_linesize_32;
180 dst_top += dst_linesize_32;
185 * Compute squared difference of an unsafe area (the zone nor s1 nor s2 could
188 * On the other hand, the line above dst and the column to its left are always
191 * There is little point in having this function SIMDified as it is likely too
192 * complex and only handle small portions of the image.
194 * @param dst integral image
195 * @param dst_linesize_32 integral image linesize (in 32-bit integers unit)
196 * @param startx integral starting x position
197 * @param starty integral starting y position
198 * @param src source plane buffer
199 * @param linesize source plane linesize
200 * @param offx source offsetting in x
201 * @param offy source offsetting in y
202 * @paran r absolute maximum source offsetting
203 * @param sw source width
204 * @param sh source height
205 * @param w width to compute
206 * @param h height to compute
208 static inline void compute_unsafe_ssd_integral_image(uint32_t *dst, ptrdiff_t dst_linesize_32,
209 int startx, int starty,
210 const uint8_t *src, ptrdiff_t linesize,
211 int offx, int offy, int r, int sw, int sh,
216 for (y = starty; y < starty + h; y++) {
217 uint32_t acc = dst[y*dst_linesize_32 + startx - 1] - dst[(y-1)*dst_linesize_32 + startx - 1];
218 const int s1y = av_clip(y - r, 0, sh - 1);
219 const int s2y = av_clip(y - (r + offy), 0, sh - 1);
221 for (x = startx; x < startx + w; x++) {
222 const int s1x = av_clip(x - r, 0, sw - 1);
223 const int s2x = av_clip(x - (r + offx), 0, sw - 1);
224 const uint8_t v1 = src[s1y*linesize + s1x];
225 const uint8_t v2 = src[s2y*linesize + s2x];
226 const int d = v1 - v2;
228 dst[y*dst_linesize_32 + x] = dst[(y-1)*dst_linesize_32 + x] + acc;
234 * Compute the sum of squared difference integral image
235 * http://www.ipol.im/pub/art/2014/57/
236 * Integral Images for Block Matching - Gabriele Facciolo, Nicolas Limare, Enric Meinhardt-Llopis
238 * @param ii integral image of dimension (w+e*2) x (h+e*2) with
239 * an additional zeroed top line and column already
240 * "applied" to the pointer value
241 * @param ii_linesize_32 integral image linesize (in 32-bit integers unit)
242 * @param src source plane buffer
243 * @param linesize source plane linesize
244 * @param offx x-offsetting ranging in [-e;e]
245 * @param offy y-offsetting ranging in [-e;e]
246 * @param w source width
247 * @param h source height
248 * @param e research padding edge
250 static void compute_ssd_integral_image(const NLMeansDSPContext *dsp,
251 uint32_t *ii, ptrdiff_t ii_linesize_32,
252 const uint8_t *src, ptrdiff_t linesize, int offx, int offy,
255 // ii has a surrounding padding of thickness "e"
256 const int ii_w = w + e*2;
257 const int ii_h = h + e*2;
259 // we center the first source
263 // 2nd source is the frame with offsetting
264 const int s2x = e + offx;
265 const int s2y = e + offy;
267 // get the dimension of the overlapping rectangle where it is always safe
268 // to compare the 2 sources pixels
269 const int startx_safe = FFMAX(s1x, s2x);
270 const int starty_safe = FFMAX(s1y, s2y);
271 const int u_endx_safe = FFMIN(s1x + w, s2x + w); // unaligned
272 const int endy_safe = FFMIN(s1y + h, s2y + h);
274 // deduce the safe area width and height
275 const int safe_pw = (u_endx_safe - startx_safe) & ~0xf;
276 const int safe_ph = endy_safe - starty_safe;
278 // adjusted end x position of the safe area after width of the safe area gets aligned
279 const int endx_safe = startx_safe + safe_pw;
281 // top part where only one of s1 and s2 is still readable, or none at all
282 compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
288 // fill the left column integral required to compute the central
290 compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
294 startx_safe, safe_ph);
296 // main and safe part of the integral
297 av_assert1(startx_safe - s1x >= 0); av_assert1(startx_safe - s1x < w);
298 av_assert1(starty_safe - s1y >= 0); av_assert1(starty_safe - s1y < h);
299 av_assert1(startx_safe - s2x >= 0); av_assert1(startx_safe - s2x < w);
300 av_assert1(starty_safe - s2y >= 0); av_assert1(starty_safe - s2y < h);
301 if (safe_pw && safe_ph)
302 dsp->compute_safe_ssd_integral_image(ii + starty_safe*ii_linesize_32 + startx_safe, ii_linesize_32,
303 src + (starty_safe - s1y) * linesize + (startx_safe - s1x), linesize,
304 src + (starty_safe - s2y) * linesize + (startx_safe - s2x), linesize,
307 // right part of the integral
308 compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
309 endx_safe, starty_safe,
312 ii_w - endx_safe, safe_ph);
314 // bottom part where only one of s1 and s2 is still readable, or none at all
315 compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
319 ii_w, ii_h - endy_safe);
322 static int config_input(AVFilterLink *inlink)
324 AVFilterContext *ctx = inlink->dst;
325 NLMeansContext *s = ctx->priv;
326 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
327 const int e = FFMAX(s->research_hsize, s->research_hsize_uv)
328 + FFMAX(s->patch_hsize, s->patch_hsize_uv);
330 s->chroma_w = FF_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
331 s->chroma_h = FF_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
332 s->nb_planes = av_pix_fmt_count_planes(inlink->format);
334 /* Allocate the integral image with extra edges of thickness "e"
336 * +_+-------------------------------+
337 * |0|0000000000000000000000000000000|
338 * +-x-------------------------------+
342 * |0| +-----------------------+ |
347 * |0| +-----------------------+ |
351 * +-+-------------------------------+
353 s->ii_w = inlink->w + e*2;
354 s->ii_h = inlink->h + e*2;
356 // align to 4 the linesize, "+1" is for the space of the left 0-column
357 s->ii_lz_32 = FFALIGN(s->ii_w + 1, 4);
359 // "+1" is for the space of the top 0-line
360 s->ii_orig = av_mallocz_array(s->ii_h + 1, s->ii_lz_32 * sizeof(*s->ii_orig));
362 return AVERROR(ENOMEM);
364 // skip top 0-line and left 0-column
365 s->ii = s->ii_orig + s->ii_lz_32 + 1;
367 // allocate weighted average for every pixel
368 s->wa_linesize = inlink->w;
369 s->wa = av_malloc_array(s->wa_linesize, inlink->h * sizeof(*s->wa));
371 return AVERROR(ENOMEM);
378 ptrdiff_t src_linesize;
381 const uint32_t *ii_start;
385 static int nlmeans_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
388 NLMeansContext *s = ctx->priv;
389 const struct thread_data *td = arg;
390 const ptrdiff_t src_linesize = td->src_linesize;
391 const int process_h = td->endy - td->starty;
392 const int slice_start = (process_h * jobnr ) / nb_jobs;
393 const int slice_end = (process_h * (jobnr+1)) / nb_jobs;
394 const int starty = td->starty + slice_start;
395 const int endy = td->starty + slice_end;
397 for (y = starty; y < endy; y++) {
398 const uint8_t *src = td->src + y*src_linesize;
399 struct weighted_avg *wa = s->wa + y*s->wa_linesize;
400 for (x = td->startx; x < td->endx; x++) {
401 const int patch_diff_sq = get_integral_patch_value(td->ii_start, s->ii_lz_32, x, y, td->p);
402 if (patch_diff_sq < s->max_meaningful_diff) {
403 const int weight_lut_idx = patch_diff_sq * s->pdiff_lut_scale;
404 const float weight = s->weight_lut[weight_lut_idx]; // exp(-patch_diff_sq * s->pdiff_scale)
405 wa[x].total_weight += weight;
406 wa[x].sum += weight * src[x];
413 static void weight_averages(uint8_t *dst, ptrdiff_t dst_linesize,
414 const uint8_t *src, ptrdiff_t src_linesize,
415 struct weighted_avg *wa, ptrdiff_t wa_linesize,
420 for (y = 0; y < h; y++) {
421 for (x = 0; x < w; x++) {
422 // Also weight the centered pixel
423 wa[x].total_weight += 1.f;
424 wa[x].sum += 1.f * src[x];
425 dst[x] = av_clip_uint8(wa[x].sum / wa[x].total_weight);
433 static int nlmeans_plane(AVFilterContext *ctx, int w, int h, int p, int r,
434 uint8_t *dst, ptrdiff_t dst_linesize,
435 const uint8_t *src, ptrdiff_t src_linesize)
438 NLMeansContext *s = ctx->priv;
439 /* patches center points cover the whole research window so the patches
440 * themselves overflow the research window */
442 /* focus an integral pointer on the centered image (s1) */
443 const uint32_t *centered_ii = s->ii + e*s->ii_lz_32 + e;
445 memset(s->wa, 0, s->wa_linesize * h * sizeof(*s->wa));
447 for (offy = -r; offy <= r; offy++) {
448 for (offx = -r; offx <= r; offx++) {
450 struct thread_data td = {
451 .src = src + offy*src_linesize + offx,
452 .src_linesize = src_linesize,
453 .startx = FFMAX(0, -offx),
454 .starty = FFMAX(0, -offy),
455 .endx = FFMIN(w, w - offx),
456 .endy = FFMIN(h, h - offy),
457 .ii_start = centered_ii + offy*s->ii_lz_32 + offx,
461 compute_ssd_integral_image(&s->dsp, s->ii, s->ii_lz_32,
463 offx, offy, e, w, h);
464 ctx->internal->execute(ctx, nlmeans_slice, &td, NULL,
465 FFMIN(td.endy - td.starty, ff_filter_get_nb_threads(ctx)));
470 weight_averages(dst, dst_linesize, src, src_linesize,
471 s->wa, s->wa_linesize, w, h);
476 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
479 AVFilterContext *ctx = inlink->dst;
480 NLMeansContext *s = ctx->priv;
481 AVFilterLink *outlink = ctx->outputs[0];
483 AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
486 return AVERROR(ENOMEM);
488 av_frame_copy_props(out, in);
490 for (i = 0; i < s->nb_planes; i++) {
491 const int w = i ? s->chroma_w : inlink->w;
492 const int h = i ? s->chroma_h : inlink->h;
493 const int p = i ? s->patch_hsize_uv : s->patch_hsize;
494 const int r = i ? s->research_hsize_uv : s->research_hsize;
495 nlmeans_plane(ctx, w, h, p, r,
496 out->data[i], out->linesize[i],
497 in->data[i], in->linesize[i]);
501 return ff_filter_frame(outlink, out);
504 #define CHECK_ODD_FIELD(field, name) do { \
505 if (!(s->field & 1)) { \
507 av_log(ctx, AV_LOG_WARNING, name " size must be odd, " \
508 "setting it to %d\n", s->field); \
512 void ff_nlmeans_init(NLMeansDSPContext *dsp)
514 dsp->compute_safe_ssd_integral_image = compute_safe_ssd_integral_image_c;
517 ff_nlmeans_init_aarch64(dsp);
520 static av_cold int init(AVFilterContext *ctx)
523 NLMeansContext *s = ctx->priv;
524 const double h = s->sigma * 10.;
526 s->pdiff_scale = 1. / (h * h);
527 s->max_meaningful_diff = -log(1/255.) / s->pdiff_scale;
528 s->pdiff_lut_scale = 1./s->max_meaningful_diff * WEIGHT_LUT_SIZE;
529 av_assert0((s->max_meaningful_diff - 1) * s->pdiff_lut_scale < FF_ARRAY_ELEMS(s->weight_lut));
530 for (i = 0; i < WEIGHT_LUT_SIZE; i++)
531 s->weight_lut[i] = exp(-i / s->pdiff_lut_scale * s->pdiff_scale);
533 CHECK_ODD_FIELD(research_size, "Luma research window");
534 CHECK_ODD_FIELD(patch_size, "Luma patch");
536 if (!s->research_size_uv) s->research_size_uv = s->research_size;
537 if (!s->patch_size_uv) s->patch_size_uv = s->patch_size;
539 CHECK_ODD_FIELD(research_size_uv, "Chroma research window");
540 CHECK_ODD_FIELD(patch_size_uv, "Chroma patch");
542 s->research_hsize = s->research_size / 2;
543 s->research_hsize_uv = s->research_size_uv / 2;
544 s->patch_hsize = s->patch_size / 2;
545 s->patch_hsize_uv = s->patch_size_uv / 2;
547 av_log(ctx, AV_LOG_INFO, "Research window: %dx%d / %dx%d, patch size: %dx%d / %dx%d\n",
548 s->research_size, s->research_size, s->research_size_uv, s->research_size_uv,
549 s->patch_size, s->patch_size, s->patch_size_uv, s->patch_size_uv);
551 ff_nlmeans_init(&s->dsp);
556 static av_cold void uninit(AVFilterContext *ctx)
558 NLMeansContext *s = ctx->priv;
559 av_freep(&s->ii_orig);
563 static const AVFilterPad nlmeans_inputs[] = {
566 .type = AVMEDIA_TYPE_VIDEO,
567 .config_props = config_input,
568 .filter_frame = filter_frame,
573 static const AVFilterPad nlmeans_outputs[] = {
576 .type = AVMEDIA_TYPE_VIDEO,
581 AVFilter ff_vf_nlmeans = {
583 .description = NULL_IF_CONFIG_SMALL("Non-local means denoiser."),
584 .priv_size = sizeof(NLMeansContext),
587 .query_formats = query_formats,
588 .inputs = nlmeans_inputs,
589 .outputs = nlmeans_outputs,
590 .priv_class = &nlmeans_class,
591 .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,