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 uint32_t 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 * Compute squared difference of the safe area (the zone where s1 and s2
105 * overlap). It is likely the largest integral zone, so it is interesting to do
106 * as little checks as possible; contrary to the unsafe version of this
107 * function, we do not need any clipping here.
109 * The line above dst and the column to its left are always readable.
111 static void compute_safe_ssd_integral_image_c(uint32_t *dst, ptrdiff_t dst_linesize_32,
112 const uint8_t *s1, ptrdiff_t linesize1,
113 const uint8_t *s2, ptrdiff_t linesize2,
117 const uint32_t *dst_top = dst - dst_linesize_32;
119 /* SIMD-friendly assumptions allowed here */
120 av_assert2(!(w & 0xf) && w >= 16 && h >= 1);
122 for (y = 0; y < h; y++) {
123 for (x = 0; x < w; x += 4) {
124 const int d0 = s1[x ] - s2[x ];
125 const int d1 = s1[x + 1] - s2[x + 1];
126 const int d2 = s1[x + 2] - s2[x + 2];
127 const int d3 = s1[x + 3] - s2[x + 3];
129 dst[x ] = dst_top[x ] - dst_top[x - 1] + d0*d0;
130 dst[x + 1] = dst_top[x + 1] - dst_top[x ] + d1*d1;
131 dst[x + 2] = dst_top[x + 2] - dst_top[x + 1] + d2*d2;
132 dst[x + 3] = dst_top[x + 3] - dst_top[x + 2] + d3*d3;
134 dst[x ] += dst[x - 1];
135 dst[x + 1] += dst[x ];
136 dst[x + 2] += dst[x + 1];
137 dst[x + 3] += dst[x + 2];
141 dst += dst_linesize_32;
142 dst_top += dst_linesize_32;
147 * Compute squared difference of an unsafe area (the zone nor s1 nor s2 could
150 * On the other hand, the line above dst and the column to its left are always
153 * There is little point in having this function SIMDified as it is likely too
154 * complex and only handle small portions of the image.
156 * @param dst integral image
157 * @param dst_linesize_32 integral image linesize (in 32-bit integers unit)
158 * @param startx integral starting x position
159 * @param starty integral starting y position
160 * @param src source plane buffer
161 * @param linesize source plane linesize
162 * @param offx source offsetting in x
163 * @param offy source offsetting in y
164 * @paran r absolute maximum source offsetting
165 * @param sw source width
166 * @param sh source height
167 * @param w width to compute
168 * @param h height to compute
170 static inline void compute_unsafe_ssd_integral_image(uint32_t *dst, ptrdiff_t dst_linesize_32,
171 int startx, int starty,
172 const uint8_t *src, ptrdiff_t linesize,
173 int offx, int offy, int r, int sw, int sh,
178 for (y = starty; y < starty + h; y++) {
179 uint32_t acc = dst[y*dst_linesize_32 + startx - 1] - dst[(y-1)*dst_linesize_32 + startx - 1];
180 const int s1y = av_clip(y - r, 0, sh - 1);
181 const int s2y = av_clip(y - (r + offy), 0, sh - 1);
183 for (x = startx; x < startx + w; x++) {
184 const int s1x = av_clip(x - r, 0, sw - 1);
185 const int s2x = av_clip(x - (r + offx), 0, sw - 1);
186 const uint8_t v1 = src[s1y*linesize + s1x];
187 const uint8_t v2 = src[s2y*linesize + s2x];
188 const int d = v1 - v2;
190 dst[y*dst_linesize_32 + x] = dst[(y-1)*dst_linesize_32 + x] + acc;
196 * Compute the sum of squared difference integral image
197 * http://www.ipol.im/pub/art/2014/57/
198 * Integral Images for Block Matching - Gabriele Facciolo, Nicolas Limare, Enric Meinhardt-Llopis
200 * @param ii integral image of dimension (w+e*2) x (h+e*2) with
201 * an additional zeroed top line and column already
202 * "applied" to the pointer value
203 * @param ii_linesize_32 integral image linesize (in 32-bit integers unit)
204 * @param src source plane buffer
205 * @param linesize source plane linesize
206 * @param offx x-offsetting ranging in [-e;e]
207 * @param offy y-offsetting ranging in [-e;e]
208 * @param w source width
209 * @param h source height
210 * @param e research padding edge
212 static void compute_ssd_integral_image(const NLMeansDSPContext *dsp,
213 uint32_t *ii, ptrdiff_t ii_linesize_32,
214 const uint8_t *src, ptrdiff_t linesize, int offx, int offy,
217 // ii has a surrounding padding of thickness "e"
218 const int ii_w = w + e*2;
219 const int ii_h = h + e*2;
221 // we center the first source
225 // 2nd source is the frame with offsetting
226 const int s2x = e + offx;
227 const int s2y = e + offy;
229 // get the dimension of the overlapping rectangle where it is always safe
230 // to compare the 2 sources pixels
231 const int startx_safe = FFMAX(s1x, s2x);
232 const int starty_safe = FFMAX(s1y, s2y);
233 const int u_endx_safe = FFMIN(s1x + w, s2x + w); // unaligned
234 const int endy_safe = FFMIN(s1y + h, s2y + h);
236 // deduce the safe area width and height
237 const int safe_pw = (u_endx_safe - startx_safe) & ~0xf;
238 const int safe_ph = endy_safe - starty_safe;
240 // adjusted end x position of the safe area after width of the safe area gets aligned
241 const int endx_safe = startx_safe + safe_pw;
243 // top part where only one of s1 and s2 is still readable, or none at all
244 compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
250 // fill the left column integral required to compute the central
252 compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
256 startx_safe, safe_ph);
258 // main and safe part of the integral
259 av_assert1(startx_safe - s1x >= 0); av_assert1(startx_safe - s1x < w);
260 av_assert1(starty_safe - s1y >= 0); av_assert1(starty_safe - s1y < h);
261 av_assert1(startx_safe - s2x >= 0); av_assert1(startx_safe - s2x < w);
262 av_assert1(starty_safe - s2y >= 0); av_assert1(starty_safe - s2y < h);
263 if (safe_pw && safe_ph)
264 dsp->compute_safe_ssd_integral_image(ii + starty_safe*ii_linesize_32 + startx_safe, ii_linesize_32,
265 src + (starty_safe - s1y) * linesize + (startx_safe - s1x), linesize,
266 src + (starty_safe - s2y) * linesize + (startx_safe - s2x), linesize,
269 // right part of the integral
270 compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
271 endx_safe, starty_safe,
274 ii_w - endx_safe, safe_ph);
276 // bottom part where only one of s1 and s2 is still readable, or none at all
277 compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
281 ii_w, ii_h - endy_safe);
284 static int config_input(AVFilterLink *inlink)
286 AVFilterContext *ctx = inlink->dst;
287 NLMeansContext *s = ctx->priv;
288 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
289 const int e = FFMAX(s->research_hsize, s->research_hsize_uv)
290 + FFMAX(s->patch_hsize, s->patch_hsize_uv);
292 s->chroma_w = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
293 s->chroma_h = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
294 s->nb_planes = av_pix_fmt_count_planes(inlink->format);
296 /* Allocate the integral image with extra edges of thickness "e"
298 * +_+-------------------------------+
299 * |0|0000000000000000000000000000000|
300 * +-x-------------------------------+
304 * |0| +-----------------------+ |
309 * |0| +-----------------------+ |
313 * +-+-------------------------------+
315 s->ii_w = inlink->w + e*2;
316 s->ii_h = inlink->h + e*2;
318 // align to 4 the linesize, "+1" is for the space of the left 0-column
319 s->ii_lz_32 = FFALIGN(s->ii_w + 1, 4);
321 // "+1" is for the space of the top 0-line
322 s->ii_orig = av_mallocz_array(s->ii_h + 1, s->ii_lz_32 * sizeof(*s->ii_orig));
324 return AVERROR(ENOMEM);
326 // skip top 0-line and left 0-column
327 s->ii = s->ii_orig + s->ii_lz_32 + 1;
329 // allocate weighted average for every pixel
330 s->wa_linesize = inlink->w;
331 s->wa = av_malloc_array(s->wa_linesize, inlink->h * sizeof(*s->wa));
333 return AVERROR(ENOMEM);
340 ptrdiff_t src_linesize;
343 const uint32_t *ii_start;
347 static int nlmeans_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
350 NLMeansContext *s = ctx->priv;
351 const struct thread_data *td = arg;
352 const ptrdiff_t src_linesize = td->src_linesize;
353 const int process_h = td->endy - td->starty;
354 const int slice_start = (process_h * jobnr ) / nb_jobs;
355 const int slice_end = (process_h * (jobnr+1)) / nb_jobs;
356 const int starty = td->starty + slice_start;
357 const int endy = td->starty + slice_end;
359 const uint32_t *ii = td->ii_start + (starty - p - 1) * s->ii_lz_32 - p - 1;
360 const int dist_b = 2*p + 1;
361 const int dist_d = dist_b * s->ii_lz_32;
362 const int dist_e = dist_d + dist_b;
364 for (y = starty; y < endy; y++) {
365 const uint8_t *src = td->src + y*src_linesize;
366 struct weighted_avg *wa = s->wa + y*s->wa_linesize;
367 for (x = td->startx; x < td->endx; x++) {
369 * M is a discrete map where every entry contains the sum of all the entries
370 * in the rectangle from the top-left origin of M to its coordinate. In the
371 * following schema, "i" contains the sum of the whole map:
373 * M = +----------+-----------------+----+
377 * +----------+-----------------+----+
383 * +----------+-----------------+----+
386 * +----------+-----------------+----+
388 * The sum of the X box can be calculated with:
391 * See https://en.wikipedia.org/wiki/Summed_area_table
393 * The compute*_ssd functions compute the integral image M where every entry
394 * contains the sum of the squared difference of every corresponding pixels of
395 * two input planes of the same size as M.
397 const uint32_t a = ii[x];
398 const uint32_t b = ii[x + dist_b];
399 const uint32_t d = ii[x + dist_d];
400 const uint32_t e = ii[x + dist_e];
401 const uint32_t patch_diff_sq = e - d - b + a;
403 if (patch_diff_sq < s->max_meaningful_diff) {
404 const unsigned weight_lut_idx = patch_diff_sq * s->pdiff_lut_scale;
405 const float weight = s->weight_lut[weight_lut_idx]; // exp(-patch_diff_sq * s->pdiff_scale)
406 wa[x].total_weight += weight;
407 wa[x].sum += weight * src[x];
415 static void weight_averages(uint8_t *dst, ptrdiff_t dst_linesize,
416 const uint8_t *src, ptrdiff_t src_linesize,
417 struct weighted_avg *wa, ptrdiff_t wa_linesize,
422 for (y = 0; y < h; y++) {
423 for (x = 0; x < w; x++) {
424 // Also weight the centered pixel
425 wa[x].total_weight += 1.f;
426 wa[x].sum += 1.f * src[x];
427 dst[x] = av_clip_uint8(wa[x].sum / wa[x].total_weight);
435 static int nlmeans_plane(AVFilterContext *ctx, int w, int h, int p, int r,
436 uint8_t *dst, ptrdiff_t dst_linesize,
437 const uint8_t *src, ptrdiff_t src_linesize)
440 NLMeansContext *s = ctx->priv;
441 /* patches center points cover the whole research window so the patches
442 * themselves overflow the research window */
444 /* focus an integral pointer on the centered image (s1) */
445 const uint32_t *centered_ii = s->ii + e*s->ii_lz_32 + e;
447 memset(s->wa, 0, s->wa_linesize * h * sizeof(*s->wa));
449 for (offy = -r; offy <= r; offy++) {
450 for (offx = -r; offx <= r; offx++) {
452 struct thread_data td = {
453 .src = src + offy*src_linesize + offx,
454 .src_linesize = src_linesize,
455 .startx = FFMAX(0, -offx),
456 .starty = FFMAX(0, -offy),
457 .endx = FFMIN(w, w - offx),
458 .endy = FFMIN(h, h - offy),
459 .ii_start = centered_ii + offy*s->ii_lz_32 + offx,
463 compute_ssd_integral_image(&s->dsp, s->ii, s->ii_lz_32,
465 offx, offy, e, w, h);
466 ctx->internal->execute(ctx, nlmeans_slice, &td, NULL,
467 FFMIN(td.endy - td.starty, ff_filter_get_nb_threads(ctx)));
472 weight_averages(dst, dst_linesize, src, src_linesize,
473 s->wa, s->wa_linesize, w, h);
478 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
481 AVFilterContext *ctx = inlink->dst;
482 NLMeansContext *s = ctx->priv;
483 AVFilterLink *outlink = ctx->outputs[0];
485 AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
488 return AVERROR(ENOMEM);
490 av_frame_copy_props(out, in);
492 for (i = 0; i < s->nb_planes; i++) {
493 const int w = i ? s->chroma_w : inlink->w;
494 const int h = i ? s->chroma_h : inlink->h;
495 const int p = i ? s->patch_hsize_uv : s->patch_hsize;
496 const int r = i ? s->research_hsize_uv : s->research_hsize;
497 nlmeans_plane(ctx, w, h, p, r,
498 out->data[i], out->linesize[i],
499 in->data[i], in->linesize[i]);
503 return ff_filter_frame(outlink, out);
506 #define CHECK_ODD_FIELD(field, name) do { \
507 if (!(s->field & 1)) { \
509 av_log(ctx, AV_LOG_WARNING, name " size must be odd, " \
510 "setting it to %d\n", s->field); \
514 void ff_nlmeans_init(NLMeansDSPContext *dsp)
516 dsp->compute_safe_ssd_integral_image = compute_safe_ssd_integral_image_c;
519 ff_nlmeans_init_aarch64(dsp);
522 static av_cold int init(AVFilterContext *ctx)
525 NLMeansContext *s = ctx->priv;
526 const double h = s->sigma * 10.;
528 s->pdiff_scale = 1. / (h * h);
529 s->max_meaningful_diff = -log(1/255.) / s->pdiff_scale;
530 s->pdiff_lut_scale = 1./s->max_meaningful_diff * WEIGHT_LUT_SIZE;
531 av_assert0((s->max_meaningful_diff - 1) * s->pdiff_lut_scale < FF_ARRAY_ELEMS(s->weight_lut));
532 for (i = 0; i < WEIGHT_LUT_SIZE; i++)
533 s->weight_lut[i] = exp(-i / s->pdiff_lut_scale * s->pdiff_scale);
535 CHECK_ODD_FIELD(research_size, "Luma research window");
536 CHECK_ODD_FIELD(patch_size, "Luma patch");
538 if (!s->research_size_uv) s->research_size_uv = s->research_size;
539 if (!s->patch_size_uv) s->patch_size_uv = s->patch_size;
541 CHECK_ODD_FIELD(research_size_uv, "Chroma research window");
542 CHECK_ODD_FIELD(patch_size_uv, "Chroma patch");
544 s->research_hsize = s->research_size / 2;
545 s->research_hsize_uv = s->research_size_uv / 2;
546 s->patch_hsize = s->patch_size / 2;
547 s->patch_hsize_uv = s->patch_size_uv / 2;
549 av_log(ctx, AV_LOG_INFO, "Research window: %dx%d / %dx%d, patch size: %dx%d / %dx%d\n",
550 s->research_size, s->research_size, s->research_size_uv, s->research_size_uv,
551 s->patch_size, s->patch_size, s->patch_size_uv, s->patch_size_uv);
553 ff_nlmeans_init(&s->dsp);
558 static av_cold void uninit(AVFilterContext *ctx)
560 NLMeansContext *s = ctx->priv;
561 av_freep(&s->ii_orig);
565 static const AVFilterPad nlmeans_inputs[] = {
568 .type = AVMEDIA_TYPE_VIDEO,
569 .config_props = config_input,
570 .filter_frame = filter_frame,
575 static const AVFilterPad nlmeans_outputs[] = {
578 .type = AVMEDIA_TYPE_VIDEO,
583 AVFilter ff_vf_nlmeans = {
585 .description = NULL_IF_CONFIG_SMALL("Non-local means denoiser."),
586 .priv_size = sizeof(NLMeansContext),
589 .query_formats = query_formats,
590 .inputs = nlmeans_inputs,
591 .outputs = nlmeans_outputs,
592 .priv_class = &nlmeans_class,
593 .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,