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 typedef struct NLMeansContext {
49 int chroma_w, chroma_h;
50 double pdiff_scale; // invert of the filtering parameter (sigma*10) squared
51 double sigma; // denoising strength
52 int patch_size, patch_hsize; // patch size and half size
53 int patch_size_uv, patch_hsize_uv; // patch size and half size for chroma planes
54 int research_size, research_hsize; // research size and half size
55 int research_size_uv, research_hsize_uv; // research size and half size for chroma planes
56 uint32_t *ii_orig; // integral image
57 uint32_t *ii; // integral image starting after the 0-line and 0-column
58 int ii_w, ii_h; // width and height of the integral image
59 ptrdiff_t ii_lz_32; // linesize in 32-bit units of the integral image
60 struct weighted_avg *wa; // weighted average of every pixel
61 ptrdiff_t wa_linesize; // linesize for wa in struct size unit
62 float *weight_lut; // lookup table mapping (scaled) patch differences to their associated weights
63 uint32_t max_meaningful_diff; // maximum difference considered (if the patch difference is too high we ignore the pixel)
64 NLMeansDSPContext dsp;
67 #define OFFSET(x) offsetof(NLMeansContext, x)
68 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
69 static const AVOption nlmeans_options[] = {
70 { "s", "denoising strength", OFFSET(sigma), AV_OPT_TYPE_DOUBLE, { .dbl = 1.0 }, 1.0, 30.0, FLAGS },
71 { "p", "patch size", OFFSET(patch_size), AV_OPT_TYPE_INT, { .i64 = 3*2+1 }, 0, 99, FLAGS },
72 { "pc", "patch size for chroma planes", OFFSET(patch_size_uv), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 99, FLAGS },
73 { "r", "research window", OFFSET(research_size), AV_OPT_TYPE_INT, { .i64 = 7*2+1 }, 0, 99, FLAGS },
74 { "rc", "research window for chroma planes", OFFSET(research_size_uv), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 99, FLAGS },
78 AVFILTER_DEFINE_CLASS(nlmeans);
80 static int query_formats(AVFilterContext *ctx)
82 static const enum AVPixelFormat pix_fmts[] = {
83 AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
84 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
85 AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
86 AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P,
87 AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,
89 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GBRP,
93 AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
95 return AVERROR(ENOMEM);
96 return ff_set_common_formats(ctx, fmts_list);
100 * Compute squared difference of the safe area (the zone where s1 and s2
101 * overlap). It is likely the largest integral zone, so it is interesting to do
102 * as little checks as possible; contrary to the unsafe version of this
103 * function, we do not need any clipping here.
105 * The line above dst and the column to its left are always readable.
107 static void compute_safe_ssd_integral_image_c(uint32_t *dst, ptrdiff_t dst_linesize_32,
108 const uint8_t *s1, ptrdiff_t linesize1,
109 const uint8_t *s2, ptrdiff_t linesize2,
113 const uint32_t *dst_top = dst - dst_linesize_32;
115 /* SIMD-friendly assumptions allowed here */
116 av_assert2(!(w & 0xf) && w >= 16 && h >= 1);
118 for (y = 0; y < h; y++) {
119 for (x = 0; x < w; x += 4) {
120 const int d0 = s1[x ] - s2[x ];
121 const int d1 = s1[x + 1] - s2[x + 1];
122 const int d2 = s1[x + 2] - s2[x + 2];
123 const int d3 = s1[x + 3] - s2[x + 3];
125 dst[x ] = dst_top[x ] - dst_top[x - 1] + d0*d0;
126 dst[x + 1] = dst_top[x + 1] - dst_top[x ] + d1*d1;
127 dst[x + 2] = dst_top[x + 2] - dst_top[x + 1] + d2*d2;
128 dst[x + 3] = dst_top[x + 3] - dst_top[x + 2] + d3*d3;
130 dst[x ] += dst[x - 1];
131 dst[x + 1] += dst[x ];
132 dst[x + 2] += dst[x + 1];
133 dst[x + 3] += dst[x + 2];
137 dst += dst_linesize_32;
138 dst_top += dst_linesize_32;
143 * Compute squared difference of an unsafe area (the zone nor s1 nor s2 could
146 * On the other hand, the line above dst and the column to its left are always
149 * There is little point in having this function SIMDified as it is likely too
150 * complex and only handle small portions of the image.
152 * @param dst integral image
153 * @param dst_linesize_32 integral image linesize (in 32-bit integers unit)
154 * @param startx integral starting x position
155 * @param starty integral starting y position
156 * @param src source plane buffer
157 * @param linesize source plane linesize
158 * @param offx source offsetting in x
159 * @param offy source offsetting in y
160 * @paran r absolute maximum source offsetting
161 * @param sw source width
162 * @param sh source height
163 * @param w width to compute
164 * @param h height to compute
166 static inline void compute_unsafe_ssd_integral_image(uint32_t *dst, ptrdiff_t dst_linesize_32,
167 int startx, int starty,
168 const uint8_t *src, ptrdiff_t linesize,
169 int offx, int offy, int r, int sw, int sh,
174 for (y = starty; y < starty + h; y++) {
175 uint32_t acc = dst[y*dst_linesize_32 + startx - 1] - dst[(y-1)*dst_linesize_32 + startx - 1];
176 const int s1y = av_clip(y - r, 0, sh - 1);
177 const int s2y = av_clip(y - (r + offy), 0, sh - 1);
179 for (x = startx; x < startx + w; x++) {
180 const int s1x = av_clip(x - r, 0, sw - 1);
181 const int s2x = av_clip(x - (r + offx), 0, sw - 1);
182 const uint8_t v1 = src[s1y*linesize + s1x];
183 const uint8_t v2 = src[s2y*linesize + s2x];
184 const int d = v1 - v2;
186 dst[y*dst_linesize_32 + x] = dst[(y-1)*dst_linesize_32 + x] + acc;
192 * Compute the sum of squared difference integral image
193 * http://www.ipol.im/pub/art/2014/57/
194 * Integral Images for Block Matching - Gabriele Facciolo, Nicolas Limare, Enric Meinhardt-Llopis
196 * @param ii integral image of dimension (w+e*2) x (h+e*2) with
197 * an additional zeroed top line and column already
198 * "applied" to the pointer value
199 * @param ii_linesize_32 integral image linesize (in 32-bit integers unit)
200 * @param src source plane buffer
201 * @param linesize source plane linesize
202 * @param offx x-offsetting ranging in [-e;e]
203 * @param offy y-offsetting ranging in [-e;e]
204 * @param w source width
205 * @param h source height
206 * @param e research padding edge
208 static void compute_ssd_integral_image(const NLMeansDSPContext *dsp,
209 uint32_t *ii, ptrdiff_t ii_linesize_32,
210 const uint8_t *src, ptrdiff_t linesize, int offx, int offy,
213 // ii has a surrounding padding of thickness "e"
214 const int ii_w = w + e*2;
215 const int ii_h = h + e*2;
217 // we center the first source
221 // 2nd source is the frame with offsetting
222 const int s2x = e + offx;
223 const int s2y = e + offy;
225 // get the dimension of the overlapping rectangle where it is always safe
226 // to compare the 2 sources pixels
227 const int startx_safe = FFMAX(s1x, s2x);
228 const int starty_safe = FFMAX(s1y, s2y);
229 const int u_endx_safe = FFMIN(s1x + w, s2x + w); // unaligned
230 const int endy_safe = FFMIN(s1y + h, s2y + h);
232 // deduce the safe area width and height
233 const int safe_pw = (u_endx_safe - startx_safe) & ~0xf;
234 const int safe_ph = endy_safe - starty_safe;
236 // adjusted end x position of the safe area after width of the safe area gets aligned
237 const int endx_safe = startx_safe + safe_pw;
239 // top part where only one of s1 and s2 is still readable, or none at all
240 compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
246 // fill the left column integral required to compute the central
248 compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
252 startx_safe, safe_ph);
254 // main and safe part of the integral
255 av_assert1(startx_safe - s1x >= 0); av_assert1(startx_safe - s1x < w);
256 av_assert1(starty_safe - s1y >= 0); av_assert1(starty_safe - s1y < h);
257 av_assert1(startx_safe - s2x >= 0); av_assert1(startx_safe - s2x < w);
258 av_assert1(starty_safe - s2y >= 0); av_assert1(starty_safe - s2y < h);
259 if (safe_pw && safe_ph)
260 dsp->compute_safe_ssd_integral_image(ii + starty_safe*ii_linesize_32 + startx_safe, ii_linesize_32,
261 src + (starty_safe - s1y) * linesize + (startx_safe - s1x), linesize,
262 src + (starty_safe - s2y) * linesize + (startx_safe - s2x), linesize,
265 // right part of the integral
266 compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
267 endx_safe, starty_safe,
270 ii_w - endx_safe, safe_ph);
272 // bottom part where only one of s1 and s2 is still readable, or none at all
273 compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
277 ii_w, ii_h - endy_safe);
280 static int config_input(AVFilterLink *inlink)
282 AVFilterContext *ctx = inlink->dst;
283 NLMeansContext *s = ctx->priv;
284 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
285 const int e = FFMAX(s->research_hsize, s->research_hsize_uv)
286 + FFMAX(s->patch_hsize, s->patch_hsize_uv);
288 s->chroma_w = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
289 s->chroma_h = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
290 s->nb_planes = av_pix_fmt_count_planes(inlink->format);
292 /* Allocate the integral image with extra edges of thickness "e"
294 * +_+-------------------------------+
295 * |0|0000000000000000000000000000000|
296 * +-x-------------------------------+
300 * |0| +-----------------------+ |
305 * |0| +-----------------------+ |
309 * +-+-------------------------------+
311 s->ii_w = inlink->w + e*2;
312 s->ii_h = inlink->h + e*2;
314 // align to 4 the linesize, "+1" is for the space of the left 0-column
315 s->ii_lz_32 = FFALIGN(s->ii_w + 1, 4);
317 // "+1" is for the space of the top 0-line
318 s->ii_orig = av_mallocz_array(s->ii_h + 1, s->ii_lz_32 * sizeof(*s->ii_orig));
320 return AVERROR(ENOMEM);
322 // skip top 0-line and left 0-column
323 s->ii = s->ii_orig + s->ii_lz_32 + 1;
325 // allocate weighted average for every pixel
326 s->wa_linesize = inlink->w;
327 s->wa = av_malloc_array(s->wa_linesize, inlink->h * sizeof(*s->wa));
329 return AVERROR(ENOMEM);
336 ptrdiff_t src_linesize;
339 const uint32_t *ii_start;
343 static int nlmeans_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
346 NLMeansContext *s = ctx->priv;
347 const struct thread_data *td = arg;
348 const ptrdiff_t src_linesize = td->src_linesize;
349 const int process_h = td->endy - td->starty;
350 const int slice_start = (process_h * jobnr ) / nb_jobs;
351 const int slice_end = (process_h * (jobnr+1)) / nb_jobs;
352 const int starty = td->starty + slice_start;
353 const int endy = td->starty + slice_end;
355 const uint32_t *ii = td->ii_start + (starty - p - 1) * s->ii_lz_32 - p - 1;
356 const int dist_b = 2*p + 1;
357 const int dist_d = dist_b * s->ii_lz_32;
358 const int dist_e = dist_d + dist_b;
360 for (y = starty; y < endy; y++) {
361 const uint8_t *src = td->src + y*src_linesize;
362 struct weighted_avg *wa = s->wa + y*s->wa_linesize;
363 for (x = td->startx; x < td->endx; x++) {
365 * M is a discrete map where every entry contains the sum of all the entries
366 * in the rectangle from the top-left origin of M to its coordinate. In the
367 * following schema, "i" contains the sum of the whole map:
369 * M = +----------+-----------------+----+
373 * +----------+-----------------+----+
379 * +----------+-----------------+----+
382 * +----------+-----------------+----+
384 * The sum of the X box can be calculated with:
387 * See https://en.wikipedia.org/wiki/Summed_area_table
389 * The compute*_ssd functions compute the integral image M where every entry
390 * contains the sum of the squared difference of every corresponding pixels of
391 * two input planes of the same size as M.
393 const uint32_t a = ii[x];
394 const uint32_t b = ii[x + dist_b];
395 const uint32_t d = ii[x + dist_d];
396 const uint32_t e = ii[x + dist_e];
397 const uint32_t patch_diff_sq = e - d - b + a;
399 if (patch_diff_sq < s->max_meaningful_diff) {
400 const float weight = s->weight_lut[patch_diff_sq]; // exp(-patch_diff_sq * s->pdiff_scale)
401 wa[x].total_weight += weight;
402 wa[x].sum += weight * src[x];
410 static void weight_averages(uint8_t *dst, ptrdiff_t dst_linesize,
411 const uint8_t *src, ptrdiff_t src_linesize,
412 struct weighted_avg *wa, ptrdiff_t wa_linesize,
417 for (y = 0; y < h; y++) {
418 for (x = 0; x < w; x++) {
419 // Also weight the centered pixel
420 wa[x].total_weight += 1.f;
421 wa[x].sum += 1.f * src[x];
422 dst[x] = av_clip_uint8(wa[x].sum / wa[x].total_weight);
430 static int nlmeans_plane(AVFilterContext *ctx, int w, int h, int p, int r,
431 uint8_t *dst, ptrdiff_t dst_linesize,
432 const uint8_t *src, ptrdiff_t src_linesize)
435 NLMeansContext *s = ctx->priv;
436 /* patches center points cover the whole research window so the patches
437 * themselves overflow the research window */
439 /* focus an integral pointer on the centered image (s1) */
440 const uint32_t *centered_ii = s->ii + e*s->ii_lz_32 + e;
442 memset(s->wa, 0, s->wa_linesize * h * sizeof(*s->wa));
444 for (offy = -r; offy <= r; offy++) {
445 for (offx = -r; offx <= r; offx++) {
447 struct thread_data td = {
448 .src = src + offy*src_linesize + offx,
449 .src_linesize = src_linesize,
450 .startx = FFMAX(0, -offx),
451 .starty = FFMAX(0, -offy),
452 .endx = FFMIN(w, w - offx),
453 .endy = FFMIN(h, h - offy),
454 .ii_start = centered_ii + offy*s->ii_lz_32 + offx,
458 compute_ssd_integral_image(&s->dsp, s->ii, s->ii_lz_32,
460 offx, offy, e, w, h);
461 ctx->internal->execute(ctx, nlmeans_slice, &td, NULL,
462 FFMIN(td.endy - td.starty, ff_filter_get_nb_threads(ctx)));
467 weight_averages(dst, dst_linesize, src, src_linesize,
468 s->wa, s->wa_linesize, w, h);
473 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
476 AVFilterContext *ctx = inlink->dst;
477 NLMeansContext *s = ctx->priv;
478 AVFilterLink *outlink = ctx->outputs[0];
480 AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
483 return AVERROR(ENOMEM);
485 av_frame_copy_props(out, in);
487 for (i = 0; i < s->nb_planes; i++) {
488 const int w = i ? s->chroma_w : inlink->w;
489 const int h = i ? s->chroma_h : inlink->h;
490 const int p = i ? s->patch_hsize_uv : s->patch_hsize;
491 const int r = i ? s->research_hsize_uv : s->research_hsize;
492 nlmeans_plane(ctx, w, h, p, r,
493 out->data[i], out->linesize[i],
494 in->data[i], in->linesize[i]);
498 return ff_filter_frame(outlink, out);
501 #define CHECK_ODD_FIELD(field, name) do { \
502 if (!(s->field & 1)) { \
504 av_log(ctx, AV_LOG_WARNING, name " size must be odd, " \
505 "setting it to %d\n", s->field); \
509 void ff_nlmeans_init(NLMeansDSPContext *dsp)
511 dsp->compute_safe_ssd_integral_image = compute_safe_ssd_integral_image_c;
514 ff_nlmeans_init_aarch64(dsp);
517 static av_cold int init(AVFilterContext *ctx)
520 NLMeansContext *s = ctx->priv;
521 const double h = s->sigma * 10.;
523 s->pdiff_scale = 1. / (h * h);
524 s->max_meaningful_diff = log(255.) / s->pdiff_scale;
525 s->weight_lut = av_calloc(s->max_meaningful_diff, sizeof(*s->weight_lut));
527 return AVERROR(ENOMEM);
528 for (i = 0; i < s->max_meaningful_diff; i++)
529 s->weight_lut[i] = exp(-i * s->pdiff_scale);
531 CHECK_ODD_FIELD(research_size, "Luma research window");
532 CHECK_ODD_FIELD(patch_size, "Luma patch");
534 if (!s->research_size_uv) s->research_size_uv = s->research_size;
535 if (!s->patch_size_uv) s->patch_size_uv = s->patch_size;
537 CHECK_ODD_FIELD(research_size_uv, "Chroma research window");
538 CHECK_ODD_FIELD(patch_size_uv, "Chroma patch");
540 s->research_hsize = s->research_size / 2;
541 s->research_hsize_uv = s->research_size_uv / 2;
542 s->patch_hsize = s->patch_size / 2;
543 s->patch_hsize_uv = s->patch_size_uv / 2;
545 av_log(ctx, AV_LOG_INFO, "Research window: %dx%d / %dx%d, patch size: %dx%d / %dx%d\n",
546 s->research_size, s->research_size, s->research_size_uv, s->research_size_uv,
547 s->patch_size, s->patch_size, s->patch_size_uv, s->patch_size_uv);
549 ff_nlmeans_init(&s->dsp);
554 static av_cold void uninit(AVFilterContext *ctx)
556 NLMeansContext *s = ctx->priv;
557 av_freep(&s->weight_lut);
558 av_freep(&s->ii_orig);
562 static const AVFilterPad nlmeans_inputs[] = {
565 .type = AVMEDIA_TYPE_VIDEO,
566 .config_props = config_input,
567 .filter_frame = filter_frame,
572 static const AVFilterPad nlmeans_outputs[] = {
575 .type = AVMEDIA_TYPE_VIDEO,
580 AVFilter ff_vf_nlmeans = {
582 .description = NULL_IF_CONFIG_SMALL("Non-local means denoiser."),
583 .priv_size = sizeof(NLMeansContext),
586 .query_formats = query_formats,
587 .inputs = nlmeans_inputs,
588 .outputs = nlmeans_outputs,
589 .priv_class = &nlmeans_class,
590 .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,