You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

552 lines
22KB

  1. /*
  2. * Copyright (c) 2016 Clément Bœsch <u pkh me>
  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. * @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. #include "libavutil/avassert.h"
  33. #include "libavutil/opt.h"
  34. #include "libavutil/pixdesc.h"
  35. #include "avfilter.h"
  36. #include "formats.h"
  37. #include "internal.h"
  38. #include "video.h"
  39. struct weighted_avg {
  40. double total_weight;
  41. double sum;
  42. };
  43. #define WEIGHT_LUT_NBITS 9
  44. #define WEIGHT_LUT_SIZE (1<<WEIGHT_LUT_NBITS)
  45. typedef struct NLMeansContext {
  46. const AVClass *class;
  47. int nb_planes;
  48. int chroma_w, chroma_h;
  49. double pdiff_scale; // invert of the filtering parameter (sigma*10) squared
  50. double sigma; // denoising strength
  51. int patch_size, patch_hsize; // patch size and half size
  52. int patch_size_uv, patch_hsize_uv; // patch size and half size for chroma planes
  53. int research_size, research_hsize; // research size and half size
  54. int research_size_uv, research_hsize_uv; // research size and half size for chroma planes
  55. uint32_t *ii_orig; // integral image
  56. uint32_t *ii; // integral image starting after the 0-line and 0-column
  57. int ii_w, ii_h; // width and height of the integral image
  58. int ii_lz_32; // linesize in 32-bit units of the integral image
  59. struct weighted_avg *wa; // weighted average of every pixel
  60. int wa_linesize; // linesize for wa in struct size unit
  61. double weight_lut[WEIGHT_LUT_SIZE]; // lookup table mapping (scaled) patch differences to their associated weights
  62. double pdiff_lut_scale; // scale factor for patch differences before looking into the LUT
  63. int max_meaningful_diff; // maximum difference considered (if the patch difference is too high we ignore the pixel)
  64. } NLMeansContext;
  65. #define OFFSET(x) offsetof(NLMeansContext, x)
  66. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  67. static const AVOption nlmeans_options[] = {
  68. { "s", "denoising strength", OFFSET(sigma), AV_OPT_TYPE_DOUBLE, { .dbl = 1.0 }, 1.0, 30.0, FLAGS },
  69. { "p", "patch size", OFFSET(patch_size), AV_OPT_TYPE_INT, { .i64 = 3*2+1 }, 0, 99, FLAGS },
  70. { "pc", "patch size for chroma planes", OFFSET(patch_size_uv), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 99, FLAGS },
  71. { "r", "research window", OFFSET(research_size), AV_OPT_TYPE_INT, { .i64 = 7*2+1 }, 0, 99, FLAGS },
  72. { "rc", "research window for chroma planes", OFFSET(research_size_uv), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 99, FLAGS },
  73. { NULL }
  74. };
  75. AVFILTER_DEFINE_CLASS(nlmeans);
  76. static int query_formats(AVFilterContext *ctx)
  77. {
  78. static const enum AVPixelFormat pix_fmts[] = {
  79. AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
  80. AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
  81. AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
  82. AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P,
  83. AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,
  84. AV_PIX_FMT_YUVJ411P,
  85. AV_PIX_FMT_GRAY8, AV_PIX_FMT_GBRP,
  86. AV_PIX_FMT_NONE
  87. };
  88. AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
  89. if (!fmts_list)
  90. return AVERROR(ENOMEM);
  91. return ff_set_common_formats(ctx, fmts_list);
  92. }
  93. /*
  94. * M is a discrete map where every entry contains the sum of all the entries
  95. * in the rectangle from the top-left origin of M to its coordinate. In the
  96. * following schema, "i" contains the sum of the whole map:
  97. *
  98. * M = +----------+-----------------+----+
  99. * | | | |
  100. * | | | |
  101. * | a| b| c|
  102. * +----------+-----------------+----+
  103. * | | | |
  104. * | | | |
  105. * | | X | |
  106. * | | | |
  107. * | d| e| f|
  108. * +----------+-----------------+----+
  109. * | | | |
  110. * | g| h| i|
  111. * +----------+-----------------+----+
  112. *
  113. * The sum of the X box can be calculated with:
  114. * X = e-d-b+a
  115. *
  116. * See https://en.wikipedia.org/wiki/Summed_area_table
  117. *
  118. * The compute*_ssd functions compute the integral image M where every entry
  119. * contains the sum of the squared difference of every corresponding pixels of
  120. * two input planes of the same size as M.
  121. */
  122. static inline int get_integral_patch_value(const uint32_t *ii, int ii_lz_32, int x, int y, int p)
  123. {
  124. const int e = ii[(y + p ) * ii_lz_32 + (x + p )];
  125. const int d = ii[(y + p ) * ii_lz_32 + (x - p - 1)];
  126. const int b = ii[(y - p - 1) * ii_lz_32 + (x + p )];
  127. const int a = ii[(y - p - 1) * ii_lz_32 + (x - p - 1)];
  128. return e - d - b + a;
  129. }
  130. /**
  131. * Compute squared difference of the safe area (the zone where s1 and s2
  132. * overlap). It is likely the largest integral zone, so it is interesting to do
  133. * as little checks as possible; contrary to the unsafe version of this
  134. * function, we do not need any clipping here.
  135. *
  136. * The line above dst and the column to its left are always readable.
  137. *
  138. * This C version computes the SSD integral image using a scalar accumulator,
  139. * while for SIMD implementation it is likely more interesting to use the
  140. * two-loops algorithm variant.
  141. */
  142. static void compute_safe_ssd_integral_image_c(uint32_t *dst, int dst_linesize_32,
  143. const uint8_t *s1, int linesize1,
  144. const uint8_t *s2, int linesize2,
  145. int w, int h)
  146. {
  147. int x, y;
  148. for (y = 0; y < h; y++) {
  149. uint32_t acc = dst[-1] - dst[-dst_linesize_32 - 1];
  150. for (x = 0; x < w; x++) {
  151. const int d = s1[x] - s2[x];
  152. acc += d * d;
  153. dst[x] = dst[-dst_linesize_32 + x] + acc;
  154. }
  155. s1 += linesize1;
  156. s2 += linesize2;
  157. dst += dst_linesize_32;
  158. }
  159. }
  160. /**
  161. * Compute squared difference of an unsafe area (the zone nor s1 nor s2 could
  162. * be readable).
  163. *
  164. * On the other hand, the line above dst and the column to its left are always
  165. * readable.
  166. *
  167. * There is little point in having this function SIMDified as it is likely too
  168. * complex and only handle small portions of the image.
  169. *
  170. * @param dst integral image
  171. * @param dst_linesize_32 integral image linesize (in 32-bit integers unit)
  172. * @param startx integral starting x position
  173. * @param starty integral starting y position
  174. * @param src source plane buffer
  175. * @param linesize source plane linesize
  176. * @param offx source offsetting in x
  177. * @param offy source offsetting in y
  178. * @paran r absolute maximum source offsetting
  179. * @param sw source width
  180. * @param sh source height
  181. * @param w width to compute
  182. * @param h height to compute
  183. */
  184. static inline void compute_unsafe_ssd_integral_image(uint32_t *dst, int dst_linesize_32,
  185. int startx, int starty,
  186. const uint8_t *src, int linesize,
  187. int offx, int offy, int r, int sw, int sh,
  188. int w, int h)
  189. {
  190. int x, y;
  191. for (y = starty; y < starty + h; y++) {
  192. uint32_t acc = dst[y*dst_linesize_32 + startx - 1] - dst[(y-1)*dst_linesize_32 + startx - 1];
  193. const int s1y = av_clip(y - r, 0, sh - 1);
  194. const int s2y = av_clip(y - (r + offy), 0, sh - 1);
  195. for (x = startx; x < startx + w; x++) {
  196. const int s1x = av_clip(x - r, 0, sw - 1);
  197. const int s2x = av_clip(x - (r + offx), 0, sw - 1);
  198. const uint8_t v1 = src[s1y*linesize + s1x];
  199. const uint8_t v2 = src[s2y*linesize + s2x];
  200. const int d = v1 - v2;
  201. acc += d * d;
  202. dst[y*dst_linesize_32 + x] = dst[(y-1)*dst_linesize_32 + x] + acc;
  203. }
  204. }
  205. }
  206. /*
  207. * Compute the sum of squared difference integral image
  208. * http://www.ipol.im/pub/art/2014/57/
  209. * Integral Images for Block Matching - Gabriele Facciolo, Nicolas Limare, Enric Meinhardt-Llopis
  210. *
  211. * @param ii integral image of dimension (w+e*2) x (h+e*2) with
  212. * an additional zeroed top line and column already
  213. * "applied" to the pointer value
  214. * @param ii_linesize_32 integral image linesize (in 32-bit integers unit)
  215. * @param src source plane buffer
  216. * @param linesize source plane linesize
  217. * @param offx x-offsetting ranging in [-e;e]
  218. * @param offy y-offsetting ranging in [-e;e]
  219. * @param w source width
  220. * @param h source height
  221. * @param e research padding edge
  222. */
  223. static void compute_ssd_integral_image(uint32_t *ii, int ii_linesize_32,
  224. const uint8_t *src, int linesize, int offx, int offy,
  225. int e, int w, int h)
  226. {
  227. // ii has a surrounding padding of thickness "e"
  228. const int ii_w = w + e*2;
  229. const int ii_h = h + e*2;
  230. // we center the first source
  231. const int s1x = e;
  232. const int s1y = e;
  233. // 2nd source is the frame with offsetting
  234. const int s2x = e + offx;
  235. const int s2y = e + offy;
  236. // get the dimension of the overlapping rectangle where it is always safe
  237. // to compare the 2 sources pixels
  238. const int startx_safe = FFMAX(s1x, s2x);
  239. const int starty_safe = FFMAX(s1y, s2y);
  240. const int endx_safe = FFMIN(s1x + w, s2x + w);
  241. const int endy_safe = FFMIN(s1y + h, s2y + h);
  242. // top part where only one of s1 and s2 is still readable, or none at all
  243. compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
  244. 0, 0,
  245. src, linesize,
  246. offx, offy, e, w, h,
  247. ii_w, starty_safe);
  248. // fill the left column integral required to compute the central
  249. // overlapping one
  250. compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
  251. 0, starty_safe,
  252. src, linesize,
  253. offx, offy, e, w, h,
  254. startx_safe, endy_safe - starty_safe);
  255. // main and safe part of the integral
  256. av_assert1(startx_safe - s1x >= 0); av_assert1(startx_safe - s1x < w);
  257. av_assert1(starty_safe - s1y >= 0); av_assert1(starty_safe - s1y < h);
  258. av_assert1(startx_safe - s2x >= 0); av_assert1(startx_safe - s2x < w);
  259. av_assert1(starty_safe - s2y >= 0); av_assert1(starty_safe - s2y < h);
  260. compute_safe_ssd_integral_image_c(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,
  263. endx_safe - startx_safe, endy_safe - starty_safe);
  264. // right part of the integral
  265. compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
  266. endx_safe, starty_safe,
  267. src, linesize,
  268. offx, offy, e, w, h,
  269. ii_w - endx_safe, endy_safe - starty_safe);
  270. // bottom part where only one of s1 and s2 is still readable, or none at all
  271. compute_unsafe_ssd_integral_image(ii, ii_linesize_32,
  272. 0, endy_safe,
  273. src, linesize,
  274. offx, offy, e, w, h,
  275. ii_w, ii_h - endy_safe);
  276. }
  277. static int config_input(AVFilterLink *inlink)
  278. {
  279. AVFilterContext *ctx = inlink->dst;
  280. NLMeansContext *s = ctx->priv;
  281. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
  282. const int e = FFMAX(s->research_hsize, s->research_hsize_uv)
  283. + FFMAX(s->patch_hsize, s->patch_hsize_uv);
  284. s->chroma_w = FF_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
  285. s->chroma_h = FF_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
  286. s->nb_planes = av_pix_fmt_count_planes(inlink->format);
  287. /* Allocate the integral image with extra edges of thickness "e"
  288. *
  289. * +_+-------------------------------+
  290. * |0|0000000000000000000000000000000|
  291. * +-x-------------------------------+
  292. * |0|\ ^ |
  293. * |0| ii | e |
  294. * |0| v |
  295. * |0| +-----------------------+ |
  296. * |0| | | |
  297. * |0|<->| | |
  298. * |0| e | | |
  299. * |0| | | |
  300. * |0| +-----------------------+ |
  301. * |0| |
  302. * |0| |
  303. * |0| |
  304. * +-+-------------------------------+
  305. */
  306. s->ii_w = inlink->w + e*2;
  307. s->ii_h = inlink->h + e*2;
  308. // align to 4 the linesize, "+1" is for the space of the left 0-column
  309. s->ii_lz_32 = FFALIGN(s->ii_w + 1, 4);
  310. // "+1" is for the space of the top 0-line
  311. s->ii_orig = av_mallocz_array(s->ii_h + 1, s->ii_lz_32 * sizeof(*s->ii_orig));
  312. if (!s->ii_orig)
  313. return AVERROR(ENOMEM);
  314. // skip top 0-line and left 0-column
  315. s->ii = s->ii_orig + s->ii_lz_32 + 1;
  316. // allocate weighted average for every pixel
  317. s->wa_linesize = inlink->w;
  318. s->wa = av_malloc_array(s->wa_linesize, inlink->h * sizeof(*s->wa));
  319. if (!s->wa)
  320. return AVERROR(ENOMEM);
  321. return 0;
  322. }
  323. struct thread_data {
  324. const uint8_t *src;
  325. int src_linesize;
  326. int startx, starty;
  327. int endx, endy;
  328. const uint32_t *ii_start;
  329. int p;
  330. };
  331. static int nlmeans_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
  332. {
  333. int x, y;
  334. NLMeansContext *s = ctx->priv;
  335. const struct thread_data *td = arg;
  336. const uint8_t *src = td->src;
  337. const int src_linesize = td->src_linesize;
  338. const int process_h = td->endy - td->starty;
  339. const int slice_start = (process_h * jobnr ) / nb_jobs;
  340. const int slice_end = (process_h * (jobnr+1)) / nb_jobs;
  341. const int starty = td->starty + slice_start;
  342. const int endy = td->starty + slice_end;
  343. for (y = starty; y < endy; y++) {
  344. for (x = td->startx; x < td->endx; x++) {
  345. const int patch_diff_sq = get_integral_patch_value(td->ii_start, s->ii_lz_32, x, y, td->p);
  346. if (patch_diff_sq < s->max_meaningful_diff) {
  347. struct weighted_avg *wa = &s->wa[y*s->wa_linesize + x];
  348. const int weight_lut_idx = patch_diff_sq * s->pdiff_lut_scale;
  349. const double weight = s->weight_lut[weight_lut_idx]; // exp(-patch_diff_sq * s->pdiff_scale)
  350. wa->total_weight += weight;
  351. wa->sum += weight * src[y*src_linesize + x];
  352. }
  353. }
  354. }
  355. return 0;
  356. }
  357. static int nlmeans_plane(AVFilterContext *ctx, int w, int h, int p, int r,
  358. uint8_t *dst, int dst_linesize,
  359. const uint8_t *src, int src_linesize)
  360. {
  361. int x, y;
  362. int offx, offy;
  363. NLMeansContext *s = ctx->priv;
  364. /* patches center points cover the whole research window so the patches
  365. * themselves overflow the research window */
  366. const int e = r + p;
  367. /* focus an integral pointer on the centered image (s1) */
  368. const uint32_t *centered_ii = s->ii + e*s->ii_lz_32 + e;
  369. memset(s->wa, 0, s->wa_linesize * h * sizeof(*s->wa));
  370. for (offy = -r; offy <= r; offy++) {
  371. for (offx = -r; offx <= r; offx++) {
  372. if (offx || offy) {
  373. struct thread_data td = {
  374. .src = src + offy*src_linesize + offx,
  375. .src_linesize = src_linesize,
  376. .startx = FFMAX(0, -offx),
  377. .starty = FFMAX(0, -offy),
  378. .endx = FFMIN(w, w - offx),
  379. .endy = FFMIN(h, h - offy),
  380. .ii_start = centered_ii + offy*s->ii_lz_32 + offx,
  381. .p = p,
  382. };
  383. compute_ssd_integral_image(s->ii, s->ii_lz_32,
  384. src, src_linesize,
  385. offx, offy, e, w, h);
  386. ctx->internal->execute(ctx, nlmeans_slice, &td, NULL,
  387. FFMIN(td.endy - td.starty, ff_filter_get_nb_threads(ctx)));
  388. }
  389. }
  390. }
  391. for (y = 0; y < h; y++) {
  392. for (x = 0; x < w; x++) {
  393. struct weighted_avg *wa = &s->wa[y*s->wa_linesize + x];
  394. // Also weight the centered pixel
  395. wa->total_weight += 1.0;
  396. wa->sum += 1.0 * src[y*src_linesize + x];
  397. dst[y*dst_linesize + x] = av_clip_uint8(wa->sum / wa->total_weight);
  398. }
  399. }
  400. return 0;
  401. }
  402. static int filter_frame(AVFilterLink *inlink, AVFrame *in)
  403. {
  404. int i;
  405. AVFilterContext *ctx = inlink->dst;
  406. NLMeansContext *s = ctx->priv;
  407. AVFilterLink *outlink = ctx->outputs[0];
  408. AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
  409. if (!out) {
  410. av_frame_free(&in);
  411. return AVERROR(ENOMEM);
  412. }
  413. av_frame_copy_props(out, in);
  414. for (i = 0; i < s->nb_planes; i++) {
  415. const int w = i ? s->chroma_w : inlink->w;
  416. const int h = i ? s->chroma_h : inlink->h;
  417. const int p = i ? s->patch_hsize_uv : s->patch_hsize;
  418. const int r = i ? s->research_hsize_uv : s->research_hsize;
  419. nlmeans_plane(ctx, w, h, p, r,
  420. out->data[i], out->linesize[i],
  421. in->data[i], in->linesize[i]);
  422. }
  423. av_frame_free(&in);
  424. return ff_filter_frame(outlink, out);
  425. }
  426. #define CHECK_ODD_FIELD(field, name) do { \
  427. if (!(s->field & 1)) { \
  428. s->field |= 1; \
  429. av_log(ctx, AV_LOG_WARNING, name " size must be odd, " \
  430. "setting it to %d\n", s->field); \
  431. } \
  432. } while (0)
  433. static av_cold int init(AVFilterContext *ctx)
  434. {
  435. int i;
  436. NLMeansContext *s = ctx->priv;
  437. const double h = s->sigma * 10.;
  438. s->pdiff_scale = 1. / (h * h);
  439. s->max_meaningful_diff = -log(1/255.) / s->pdiff_scale;
  440. s->pdiff_lut_scale = 1./s->max_meaningful_diff * WEIGHT_LUT_SIZE;
  441. av_assert0((s->max_meaningful_diff - 1) * s->pdiff_lut_scale < FF_ARRAY_ELEMS(s->weight_lut));
  442. for (i = 0; i < WEIGHT_LUT_SIZE; i++)
  443. s->weight_lut[i] = exp(-i / s->pdiff_lut_scale * s->pdiff_scale);
  444. CHECK_ODD_FIELD(research_size, "Luma research window");
  445. CHECK_ODD_FIELD(patch_size, "Luma patch");
  446. if (!s->research_size_uv) s->research_size_uv = s->research_size;
  447. if (!s->patch_size_uv) s->patch_size_uv = s->patch_size;
  448. CHECK_ODD_FIELD(research_size_uv, "Chroma research window");
  449. CHECK_ODD_FIELD(patch_size_uv, "Chroma patch");
  450. s->research_hsize = s->research_size / 2;
  451. s->research_hsize_uv = s->research_size_uv / 2;
  452. s->patch_hsize = s->patch_size / 2;
  453. s->patch_hsize_uv = s->patch_size_uv / 2;
  454. av_log(ctx, AV_LOG_INFO, "Research window: %dx%d / %dx%d, patch size: %dx%d / %dx%d\n",
  455. s->research_size, s->research_size, s->research_size_uv, s->research_size_uv,
  456. s->patch_size, s->patch_size, s->patch_size_uv, s->patch_size_uv);
  457. return 0;
  458. }
  459. static av_cold void uninit(AVFilterContext *ctx)
  460. {
  461. NLMeansContext *s = ctx->priv;
  462. av_freep(&s->ii_orig);
  463. av_freep(&s->wa);
  464. }
  465. static const AVFilterPad nlmeans_inputs[] = {
  466. {
  467. .name = "default",
  468. .type = AVMEDIA_TYPE_VIDEO,
  469. .config_props = config_input,
  470. .filter_frame = filter_frame,
  471. },
  472. { NULL }
  473. };
  474. static const AVFilterPad nlmeans_outputs[] = {
  475. {
  476. .name = "default",
  477. .type = AVMEDIA_TYPE_VIDEO,
  478. },
  479. { NULL }
  480. };
  481. AVFilter ff_vf_nlmeans = {
  482. .name = "nlmeans",
  483. .description = NULL_IF_CONFIG_SMALL("Non-local means denoiser."),
  484. .priv_size = sizeof(NLMeansContext),
  485. .init = init,
  486. .uninit = uninit,
  487. .query_formats = query_formats,
  488. .inputs = nlmeans_inputs,
  489. .outputs = nlmeans_outputs,
  490. .priv_class = &nlmeans_class,
  491. .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
  492. };