2 * Copyright (c) 2015-2016 mawen1250
3 * Copyright (c) 2018 Paul B Mahol
5 * This file is part of FFmpeg.
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 * - non-power of 2 DCT
29 * - opponent color space
35 #include "libavutil/avassert.h"
36 #include "libavutil/imgutils.h"
37 #include "libavutil/opt.h"
38 #include "libavutil/pixdesc.h"
39 #include "libavcodec/avfft.h"
43 #include "framesync.h"
47 #define MAX_NB_THREADS 32
55 typedef struct ThreadData {
63 typedef struct PosCode {
67 typedef struct PosPairCode {
72 typedef struct SliceContext {
73 DCTContext *gdctf, *gdcti;
74 DCTContext *dctf, *dcti;
84 PosPairCode match_blocks[256];
86 PosCode *search_positions;
89 typedef struct BM3DContext {
112 SliceContext slices[MAX_NB_THREADS];
117 void (*get_block_row)(const uint8_t *srcp, int src_linesize,
118 int y, int x, int block_size, float *dst);
119 double (*do_block_ssd)(struct BM3DContext *s, PosCode *pos,
120 const uint8_t *src, int src_stride,
122 void (*do_output)(struct BM3DContext *s, uint8_t *dst, int dst_linesize,
123 int plane, int nb_jobs);
124 void (*block_filtering)(struct BM3DContext *s,
125 const uint8_t *src, int src_linesize,
126 const uint8_t *ref, int ref_linesize,
127 int y, int x, int plane, int jobnr);
130 #define OFFSET(x) offsetof(BM3DContext, x)
131 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
132 static const AVOption bm3d_options[] = {
133 { "sigma", "set denoising strength",
134 OFFSET(sigma), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 99999.9, FLAGS },
135 { "block", "set log2(size) of local patch",
136 OFFSET(block_size), AV_OPT_TYPE_INT, {.i64=4}, 4, 6, FLAGS },
137 { "bstep", "set sliding step for processing blocks",
138 OFFSET(block_step), AV_OPT_TYPE_INT, {.i64=4}, 1, 64, FLAGS },
139 { "group", "set maximal number of similar blocks",
140 OFFSET(group_size), AV_OPT_TYPE_INT, {.i64=1}, 1, 256, FLAGS },
141 { "range", "set block matching range",
142 OFFSET(bm_range), AV_OPT_TYPE_INT, {.i64=9}, 1, INT32_MAX, FLAGS },
143 { "mstep", "set step for block matching",
144 OFFSET(bm_step), AV_OPT_TYPE_INT, {.i64=1}, 1, 64, FLAGS },
145 { "thmse", "set threshold of mean square error for block matching",
146 OFFSET(th_mse), AV_OPT_TYPE_FLOAT, {.dbl=0}, 0, INT32_MAX, FLAGS },
147 { "hdthr", "set hard threshold for 3D transfer domain",
148 OFFSET(hard_threshold), AV_OPT_TYPE_FLOAT, {.dbl=2.7}, 0, INT32_MAX, FLAGS },
149 { "estim", "set filtering estimation mode",
150 OFFSET(mode), AV_OPT_TYPE_INT, {.i64=BASIC}, 0, NB_MODES-1, FLAGS, "mode" },
151 { "basic", "basic estimate",
152 0, AV_OPT_TYPE_CONST, {.i64=BASIC}, 0, 0, FLAGS, "mode" },
153 { "final", "final estimate",
154 0, AV_OPT_TYPE_CONST, {.i64=FINAL}, 0, 0, FLAGS, "mode" },
155 { "ref", "have reference stream",
156 OFFSET(ref), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
157 { "planes", "set planes to filter",
158 OFFSET(planes), AV_OPT_TYPE_INT, {.i64=7}, 0, 15, FLAGS },
162 AVFILTER_DEFINE_CLASS(bm3d);
164 static int query_formats(AVFilterContext *ctx)
166 static const enum AVPixelFormat pix_fmts[] = {
167 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY9, AV_PIX_FMT_GRAY10,
168 AV_PIX_FMT_GRAY12, AV_PIX_FMT_GRAY14, AV_PIX_FMT_GRAY16,
169 AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
170 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
171 AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
172 AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
173 AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P,
175 AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV422P9, AV_PIX_FMT_YUV444P9,
176 AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
177 AV_PIX_FMT_YUV440P10,
178 AV_PIX_FMT_YUV444P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV420P12,
179 AV_PIX_FMT_YUV440P12,
180 AV_PIX_FMT_YUV444P14, AV_PIX_FMT_YUV422P14, AV_PIX_FMT_YUV420P14,
181 AV_PIX_FMT_YUV420P16, AV_PIX_FMT_YUV422P16, AV_PIX_FMT_YUV444P16,
182 AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10,
183 AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
184 AV_PIX_FMT_YUVA420P, AV_PIX_FMT_YUVA422P, AV_PIX_FMT_YUVA444P,
185 AV_PIX_FMT_YUVA444P9, AV_PIX_FMT_YUVA444P10, AV_PIX_FMT_YUVA444P12, AV_PIX_FMT_YUVA444P16,
186 AV_PIX_FMT_YUVA422P9, AV_PIX_FMT_YUVA422P10, AV_PIX_FMT_YUVA422P12, AV_PIX_FMT_YUVA422P16,
187 AV_PIX_FMT_YUVA420P9, AV_PIX_FMT_YUVA420P10, AV_PIX_FMT_YUVA420P16,
188 AV_PIX_FMT_GBRAP, AV_PIX_FMT_GBRAP10, AV_PIX_FMT_GBRAP12, AV_PIX_FMT_GBRAP16,
192 AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
194 return AVERROR(ENOMEM);
195 return ff_set_common_formats(ctx, fmts_list);
198 static int do_search_boundary(int pos, int plane_boundary, int search_range, int search_step)
202 search_range = search_range / search_step * search_step;
204 if (pos == plane_boundary) {
205 search_boundary = plane_boundary;
206 } else if (pos > plane_boundary) {
207 search_boundary = pos - search_range;
209 while (search_boundary < plane_boundary) {
210 search_boundary += search_step;
213 search_boundary = pos + search_range;
215 while (search_boundary > plane_boundary) {
216 search_boundary -= search_step;
220 return search_boundary;
223 static int search_boundary(int plane_boundary, int search_range, int search_step, int vertical, int y, int x)
225 return do_search_boundary(vertical ? y : x, plane_boundary, search_range, search_step);
228 static int cmp_scores(const void *a, const void *b)
230 const struct PosPairCode *pair1 = a;
231 const struct PosPairCode *pair2 = b;
232 return FFDIFFSIGN(pair1->score, pair2->score);
235 static double do_block_ssd(BM3DContext *s, PosCode *pos, const uint8_t *src, int src_stride, int r_y, int r_x)
237 const uint8_t *srcp = src + pos->y * src_stride + pos->x;
238 const uint8_t *refp = src + r_y * src_stride + r_x;
239 const int block_size = s->block_size;
243 for (y = 0; y < block_size; y++) {
244 for (x = 0; x < block_size; x++) {
245 double temp = refp[x] - srcp[x];
256 static double do_block_ssd16(BM3DContext *s, PosCode *pos, const uint8_t *src, int src_stride, int r_y, int r_x)
258 const uint16_t *srcp = (uint16_t *)src + pos->y * src_stride / 2 + pos->x;
259 const uint16_t *refp = (uint16_t *)src + r_y * src_stride / 2 + r_x;
260 const int block_size = s->block_size;
264 for (y = 0; y < block_size; y++) {
265 for (x = 0; x < block_size; x++) {
266 double temp = refp[x] - srcp[x];
270 srcp += src_stride / 2;
271 refp += src_stride / 2;
277 static void do_block_matching_multi(BM3DContext *s, const uint8_t *src, int src_stride, int src_range,
278 const PosCode *search_pos, int search_size, float th_mse,
279 int r_y, int r_x, int plane, int jobnr)
281 SliceContext *sc = &s->slices[jobnr];
282 double MSE2SSE = s->group_size * s->block_size * s->block_size * src_range * src_range / (s->max * s->max);
283 double distMul = 1. / MSE2SSE;
284 double th_sse = th_mse * MSE2SSE;
285 int i, index = sc->nb_match_blocks;
287 for (i = 0; i < search_size; i++) {
288 PosCode pos = search_pos[i];
291 dist = s->do_block_ssd(s, &pos, src, src_stride, r_y, r_x);
293 // Only match similar blocks but not identical blocks
294 if (dist <= th_sse && dist != 0) {
295 const double score = dist * distMul;
297 if (index >= s->group_size && score >= sc->match_blocks[index - 1].score) {
301 if (index >= s->group_size)
302 index = s->group_size - 1;
304 sc->match_blocks[index].score = score;
305 sc->match_blocks[index].y = pos.y;
306 sc->match_blocks[index].x = pos.x;
308 qsort(sc->match_blocks, index, sizeof(PosPairCode), cmp_scores);
312 sc->nb_match_blocks = index;
315 static void block_matching_multi(BM3DContext *s, const uint8_t *ref, int ref_linesize, int y, int x,
316 int exclude_cur_pos, int plane, int jobnr)
318 SliceContext *sc = &s->slices[jobnr];
319 const int width = s->planewidth[plane];
320 const int height = s->planeheight[plane];
321 const int block_size = s->block_size;
322 const int step = s->bm_step;
323 const int range = s->bm_range / step * step;
324 int l = search_boundary(0, range, step, 0, y, x);
325 int r = search_boundary(width - block_size, range, step, 0, y, x);
326 int t = search_boundary(0, range, step, 1, y, x);
327 int b = search_boundary(height - block_size, range, step, 1, y, x);
330 for (j = t; j <= b; j += step) {
331 for (i = l; i <= r; i += step) {
334 if (exclude_cur_pos > 0 && j == y && i == x) {
340 sc->search_positions[index++] = pos;
344 if (exclude_cur_pos == 1) {
345 sc->match_blocks[0].score = 0;
346 sc->match_blocks[0].y = y;
347 sc->match_blocks[0].x = x;
348 sc->nb_match_blocks = 1;
351 do_block_matching_multi(s, ref, ref_linesize, s->bm_range,
352 sc->search_positions, index, s->th_mse, y, x, plane, jobnr);
355 static void block_matching(BM3DContext *s, const uint8_t *ref, int ref_linesize,
356 int j, int i, int plane, int jobnr)
358 SliceContext *sc = &s->slices[jobnr];
360 if (s->group_size == 1 || s->th_mse <= 0.f) {
361 sc->match_blocks[0].score = 1;
362 sc->match_blocks[0].x = i;
363 sc->match_blocks[0].y = j;
364 sc->nb_match_blocks = 1;
368 sc->nb_match_blocks = 0;
369 block_matching_multi(s, ref, ref_linesize, j, i, 1, plane, jobnr);
372 static void get_block_row(const uint8_t *srcp, int src_linesize,
373 int y, int x, int block_size, float *dst)
375 const uint8_t *src = srcp + y * src_linesize + x;
378 for (j = 0; j < block_size; j++) {
383 static void get_block_row16(const uint8_t *srcp, int src_linesize,
384 int y, int x, int block_size, float *dst)
386 const uint16_t *src = (uint16_t *)srcp + y * src_linesize / 2 + x;
389 for (j = 0; j < block_size; j++) {
394 static void basic_block_filtering(BM3DContext *s, const uint8_t *src, int src_linesize,
395 const uint8_t *ref, int ref_linesize,
396 int y, int x, int plane, int jobnr)
398 SliceContext *sc = &s->slices[jobnr];
399 const int buffer_linesize = s->block_size * s->block_size;
400 const int nb_match_blocks = sc->nb_match_blocks;
401 const int block_size = s->block_size;
402 const int width = s->planewidth[plane];
403 const int pgroup_size = s->pgroup_size;
404 const int group_size = s->group_size;
405 float *buffer = sc->buffer;
406 float *bufferh = sc->bufferh;
407 float *bufferv = sc->bufferv;
408 float *bufferz = sc->bufferz;
410 float den_weight, num_weight;
414 for (k = 0; k < nb_match_blocks; k++) {
415 const int y = sc->match_blocks[k].y;
416 const int x = sc->match_blocks[k].x;
418 for (i = 0; i < block_size; i++) {
419 s->get_block_row(src, src_linesize, y + i, x, block_size, bufferh + block_size * i);
420 av_dct_calc(sc->dctf, bufferh + block_size * i);
423 for (i = 0; i < block_size; i++) {
424 for (j = 0; j < block_size; j++) {
425 bufferv[i * block_size + j] = bufferh[j * block_size + i];
427 av_dct_calc(sc->dctf, bufferv + i * block_size);
430 for (i = 0; i < block_size; i++) {
431 memcpy(buffer + k * buffer_linesize + i * block_size,
432 bufferv + i * block_size, block_size * 4);
436 for (i = 0; i < block_size; i++) {
437 for (j = 0; j < block_size; j++) {
438 for (k = 0; k < nb_match_blocks; k++)
439 bufferz[k] = buffer[buffer_linesize * k + i * block_size + j];
441 av_dct_calc(sc->gdctf, bufferz);
442 bufferz += pgroup_size;
446 threshold[0] = s->hard_threshold * s->sigma * M_SQRT2 * block_size * block_size * (1 << (s->depth - 8)) / 255.f;
447 threshold[1] = threshold[0] * sqrtf(2.f);
448 threshold[2] = threshold[0] * 2.f;
449 threshold[3] = threshold[0] * sqrtf(8.f);
450 bufferz = sc->bufferz;
452 for (i = 0; i < block_size; i++) {
453 for (j = 0; j < block_size; j++) {
454 for (k = 0; k < nb_match_blocks; k++) {
455 const float thresh = threshold[(j == 0) + (i == 0) + (k == 0)];
457 if (bufferz[k] > thresh || bufferz[k] < -thresh) {
463 bufferz += pgroup_size;
467 bufferz = sc->bufferz;
469 for (i = 0; i < block_size; i++) {
470 for (j = 0; j < block_size; j++) {
472 av_dct_calc(sc->gdcti, bufferz);
473 for (k = 0; k < nb_match_blocks; k++) {
474 buffer[buffer_linesize * k + i * block_size + j] = bufferz[k];
476 bufferz += pgroup_size;
480 den_weight = retained < 1 ? 1.f : 1.f / retained;
481 num_weight = den_weight;
484 for (k = 0; k < nb_match_blocks; k++) {
485 float *num = sc->num + y * width + x;
486 float *den = sc->den + y * width + x;
488 for (i = 0; i < block_size; i++) {
489 memcpy(bufferv + i * block_size,
490 buffer + k * buffer_linesize + i * block_size,
494 for (i = 0; i < block_size; i++) {
495 av_dct_calc(sc->dcti, bufferv + block_size * i);
496 for (j = 0; j < block_size; j++) {
497 bufferh[j * block_size + i] = bufferv[i * block_size + j];
501 for (i = 0; i < block_size; i++) {
502 av_dct_calc(sc->dcti, bufferh + block_size * i);
503 for (j = 0; j < block_size; j++) {
504 num[j] += bufferh[i * block_size + j] * num_weight;
505 den[j] += den_weight;
513 static void final_block_filtering(BM3DContext *s, const uint8_t *src, int src_linesize,
514 const uint8_t *ref, int ref_linesize,
515 int y, int x, int plane, int jobnr)
517 SliceContext *sc = &s->slices[jobnr];
518 const int buffer_linesize = s->block_size * s->block_size;
519 const int nb_match_blocks = sc->nb_match_blocks;
520 const int block_size = s->block_size;
521 const int width = s->planewidth[plane];
522 const int pgroup_size = s->pgroup_size;
523 const int group_size = s->group_size;
524 const float sigma_sqr = s->sigma * s->sigma;
525 float *buffer = sc->buffer;
526 float *bufferh = sc->bufferh;
527 float *bufferv = sc->bufferv;
528 float *bufferz = sc->bufferz;
529 float *rbuffer = sc->rbuffer;
530 float *rbufferh = sc->rbufferh;
531 float *rbufferv = sc->rbufferv;
532 float *rbufferz = sc->rbufferz;
533 float den_weight, num_weight;
537 for (k = 0; k < nb_match_blocks; k++) {
538 const int y = sc->match_blocks[k].y;
539 const int x = sc->match_blocks[k].x;
541 for (i = 0; i < block_size; i++) {
542 s->get_block_row(src, src_linesize, y + i, x, block_size, bufferh + block_size * i);
543 s->get_block_row(ref, ref_linesize, y + i, x, block_size, rbufferh + block_size * i);
544 av_dct_calc(sc->dctf, bufferh + block_size * i);
545 av_dct_calc(sc->dctf, rbufferh + block_size * i);
548 for (i = 0; i < block_size; i++) {
549 for (j = 0; j < block_size; j++) {
550 bufferv[i * block_size + j] = bufferh[j * block_size + i];
551 rbufferv[i * block_size + j] = rbufferh[j * block_size + i];
553 av_dct_calc(sc->dctf, bufferv + i * block_size);
554 av_dct_calc(sc->dctf, rbufferv + i * block_size);
557 for (i = 0; i < block_size; i++) {
558 memcpy(buffer + k * buffer_linesize + i * block_size,
559 bufferv + i * block_size, block_size * 4);
560 memcpy(rbuffer + k * buffer_linesize + i * block_size,
561 rbufferv + i * block_size, block_size * 4);
565 for (i = 0; i < block_size; i++) {
566 for (j = 0; j < block_size; j++) {
567 for (k = 0; k < nb_match_blocks; k++) {
568 bufferz[k] = buffer[buffer_linesize * k + i * block_size + j];
569 rbufferz[k] = rbuffer[buffer_linesize * k + i * block_size + j];
571 if (group_size > 1) {
572 av_dct_calc(sc->gdctf, bufferz);
573 av_dct_calc(sc->gdctf, rbufferz);
575 bufferz += pgroup_size;
576 rbufferz += pgroup_size;
580 bufferz = sc->bufferz;
581 rbufferz = sc->rbufferz;
583 for (i = 0; i < block_size; i++) {
584 for (j = 0; j < block_size; j++) {
585 for (k = 0; k < nb_match_blocks; k++) {
586 const float ref_sqr = rbufferz[k] * rbufferz[k];
587 float wiener_coef = ref_sqr / (ref_sqr + sigma_sqr);
589 if (isnan(wiener_coef))
591 bufferz[k] *= wiener_coef;
592 l2_wiener += wiener_coef * wiener_coef;
594 bufferz += pgroup_size;
595 rbufferz += pgroup_size;
599 bufferz = sc->bufferz;
601 for (i = 0; i < block_size; i++) {
602 for (j = 0; j < block_size; j++) {
604 av_dct_calc(sc->gdcti, bufferz);
605 for (k = 0; k < nb_match_blocks; k++) {
606 buffer[buffer_linesize * k + i * block_size + j] = bufferz[k];
608 bufferz += pgroup_size;
612 l2_wiener = FFMAX(l2_wiener, 1e-15f);
613 den_weight = 1.f / l2_wiener;
614 num_weight = den_weight;
616 for (k = 0; k < nb_match_blocks; k++) {
617 float *num = sc->num + y * width + x;
618 float *den = sc->den + y * width + x;
620 for (i = 0; i < block_size; i++) {
621 memcpy(bufferv + i * block_size,
622 buffer + k * buffer_linesize + i * block_size,
626 for (i = 0; i < block_size; i++) {
627 av_dct_calc(sc->dcti, bufferv + block_size * i);
628 for (j = 0; j < block_size; j++) {
629 bufferh[j * block_size + i] = bufferv[i * block_size + j];
633 for (i = 0; i < block_size; i++) {
634 av_dct_calc(sc->dcti, bufferh + block_size * i);
635 for (j = 0; j < block_size; j++) {
636 num[j] += bufferh[i * block_size + j] * num_weight;
637 den[j] += den_weight;
645 static void do_output(BM3DContext *s, uint8_t *dst, int dst_linesize,
646 int plane, int nb_jobs)
648 const int height = s->planeheight[plane];
649 const int width = s->planewidth[plane];
652 for (i = 0; i < height; i++) {
653 for (j = 0; j < width; j++) {
654 uint8_t *dstp = dst + i * dst_linesize;
658 for (k = 0; k < nb_jobs; k++) {
659 SliceContext *sc = &s->slices[k];
660 float num = sc->num[i * width + j];
661 float den = sc->den[i * width + j];
667 dstp[j] = av_clip_uint8(lrintf(sum_num / sum_den));
672 static void do_output16(BM3DContext *s, uint8_t *dst, int dst_linesize,
673 int plane, int nb_jobs)
675 const int height = s->planeheight[plane];
676 const int width = s->planewidth[plane];
677 const int depth = s->depth;
680 for (i = 0; i < height; i++) {
681 for (j = 0; j < width; j++) {
682 uint16_t *dstp = (uint16_t *)dst + i * dst_linesize / 2;
686 for (k = 0; k < nb_jobs; k++) {
687 SliceContext *sc = &s->slices[k];
688 float num = sc->num[i * width + j];
689 float den = sc->den[i * width + j];
695 dstp[j] = av_clip_uintp2_c(lrintf(sum_num / sum_den), depth);
700 static int filter_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
702 BM3DContext *s = ctx->priv;
703 SliceContext *sc = &s->slices[jobnr];
704 const int block_step = s->block_step;
705 ThreadData *td = arg;
706 const uint8_t *src = td->src;
707 const uint8_t *ref = td->ref;
708 const int src_linesize = td->src_linesize;
709 const int ref_linesize = td->ref_linesize;
710 const int plane = td->plane;
711 const int width = s->planewidth[plane];
712 const int height = s->planeheight[plane];
713 const int block_pos_bottom = FFMAX(0, height - s->block_size);
714 const int block_pos_right = FFMAX(0, width - s->block_size);
715 const int slice_start = (((height + block_step - 1) / block_step) * jobnr / nb_jobs) * block_step;
716 const int slice_end = (jobnr == nb_jobs - 1) ? block_pos_bottom + block_step :
717 (((height + block_step - 1) / block_step) * (jobnr + 1) / nb_jobs) * block_step;
720 memset(sc->num, 0, width * height * sizeof(FFTSample));
721 memset(sc->den, 0, width * height * sizeof(FFTSample));
723 for (j = slice_start; j < slice_end; j += block_step) {
724 if (j > block_pos_bottom) {
725 j = block_pos_bottom;
728 for (i = 0; i < block_pos_right + block_step; i += block_step) {
729 if (i > block_pos_right) {
733 block_matching(s, ref, ref_linesize, j, i, plane, jobnr);
735 s->block_filtering(s, src, src_linesize,
736 ref, ref_linesize, j, i, plane, jobnr);
743 static int filter_frame(AVFilterContext *ctx, AVFrame **out, AVFrame *in, AVFrame *ref)
745 BM3DContext *s = ctx->priv;
746 AVFilterLink *outlink = ctx->outputs[0];
749 *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
751 return AVERROR(ENOMEM);
752 av_frame_copy_props(*out, in);
754 for (p = 0; p < s->nb_planes; p++) {
755 const int nb_jobs = FFMAX(1, FFMIN(s->nb_threads, s->planeheight[p] / s->block_size));
758 if (!((1 << p) & s->planes) || ctx->is_disabled) {
759 av_image_copy_plane((*out)->data[p], (*out)->linesize[p],
760 in->data[p], in->linesize[p],
761 s->planewidth[p], s->planeheight[p]);
765 td.src = in->data[p];
766 td.src_linesize = in->linesize[p];
767 td.ref = ref->data[p];
768 td.ref_linesize = ref->linesize[p];
770 ctx->internal->execute(ctx, filter_slice, &td, NULL, nb_jobs);
772 s->do_output(s, (*out)->data[p], (*out)->linesize[p], p, nb_jobs);
778 #define SQR(x) ((x) * (x))
780 static int config_input(AVFilterLink *inlink)
782 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
783 AVFilterContext *ctx = inlink->dst;
784 BM3DContext *s = ctx->priv;
787 s->nb_threads = FFMIN(ff_filter_get_nb_threads(ctx), MAX_NB_THREADS);
788 s->nb_planes = av_pix_fmt_count_planes(inlink->format);
789 s->depth = desc->comp[0].depth;
790 s->max = (1 << s->depth) - 1;
791 s->planeheight[1] = s->planeheight[2] = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
792 s->planeheight[0] = s->planeheight[3] = inlink->h;
793 s->planewidth[1] = s->planewidth[2] = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
794 s->planewidth[0] = s->planewidth[3] = inlink->w;
796 for (group_bits = 4; 1 << group_bits < s->group_size; group_bits++);
797 s->group_bits = group_bits;
798 s->pgroup_size = 1 << group_bits;
800 for (i = 0; i < s->nb_threads; i++) {
801 SliceContext *sc = &s->slices[i];
803 sc->num = av_calloc(FFALIGN(s->planewidth[0], s->block_size) * FFALIGN(s->planeheight[0], s->block_size), sizeof(FFTSample));
804 sc->den = av_calloc(FFALIGN(s->planewidth[0], s->block_size) * FFALIGN(s->planeheight[0], s->block_size), sizeof(FFTSample));
805 if (!sc->num || !sc->den)
806 return AVERROR(ENOMEM);
808 sc->dctf = av_dct_init(av_log2(s->block_size), DCT_II);
809 sc->dcti = av_dct_init(av_log2(s->block_size), DCT_III);
810 if (!sc->dctf || !sc->dcti)
811 return AVERROR(ENOMEM);
813 if (s->group_bits > 1) {
814 sc->gdctf = av_dct_init(s->group_bits, DCT_II);
815 sc->gdcti = av_dct_init(s->group_bits, DCT_III);
816 if (!sc->gdctf || !sc->gdcti)
817 return AVERROR(ENOMEM);
820 sc->buffer = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->buffer));
821 sc->bufferz = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->bufferz));
822 sc->bufferh = av_calloc(s->block_size * s->block_size, sizeof(*sc->bufferh));
823 sc->bufferv = av_calloc(s->block_size * s->block_size, sizeof(*sc->bufferv));
824 if (!sc->bufferh || !sc->bufferv || !sc->buffer || !sc->bufferz)
825 return AVERROR(ENOMEM);
827 if (s->mode == FINAL) {
828 sc->rbuffer = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->rbuffer));
829 sc->rbufferz = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->rbufferz));
830 sc->rbufferh = av_calloc(s->block_size * s->block_size, sizeof(*sc->rbufferh));
831 sc->rbufferv = av_calloc(s->block_size * s->block_size, sizeof(*sc->rbufferv));
832 if (!sc->rbufferh || !sc->rbufferv || !sc->rbuffer || !sc->rbufferz)
833 return AVERROR(ENOMEM);
836 sc->search_positions = av_calloc(SQR(2 * s->bm_range / s->bm_step + 1), sizeof(*sc->search_positions));
837 if (!sc->search_positions)
838 return AVERROR(ENOMEM);
841 s->do_output = do_output;
842 s->do_block_ssd = do_block_ssd;
843 s->get_block_row = get_block_row;
846 s->do_output = do_output16;
847 s->do_block_ssd = do_block_ssd16;
848 s->get_block_row = get_block_row16;
854 static int activate(AVFilterContext *ctx)
856 BM3DContext *s = ctx->priv;
859 AVFrame *frame = NULL;
864 FF_FILTER_FORWARD_STATUS_BACK(ctx->outputs[0], ctx->inputs[0]);
866 if ((ret = ff_inlink_consume_frame(ctx->inputs[0], &frame)) > 0) {
867 ret = filter_frame(ctx, &out, frame, frame);
868 av_frame_free(&frame);
871 ret = ff_filter_frame(ctx->outputs[0], out);
875 } else if (ff_inlink_acknowledge_status(ctx->inputs[0], &status, &pts)) {
876 ff_outlink_set_status(ctx->outputs[0], status, pts);
879 if (ff_outlink_frame_wanted(ctx->outputs[0]))
880 ff_inlink_request_frame(ctx->inputs[0]);
884 return ff_framesync_activate(&s->fs);
888 static int process_frame(FFFrameSync *fs)
890 AVFilterContext *ctx = fs->parent;
891 BM3DContext *s = fs->opaque;
892 AVFilterLink *outlink = ctx->outputs[0];
893 AVFrame *out = NULL, *src, *ref;
896 if ((ret = ff_framesync_get_frame(&s->fs, 0, &src, 0)) < 0 ||
897 (ret = ff_framesync_get_frame(&s->fs, 1, &ref, 0)) < 0)
900 if ((ret = filter_frame(ctx, &out, src, ref)) < 0)
903 out->pts = av_rescale_q(src->pts, s->fs.time_base, outlink->time_base);
905 return ff_filter_frame(outlink, out);
908 static av_cold int init(AVFilterContext *ctx)
910 BM3DContext *s = ctx->priv;
911 AVFilterPad pad = { 0 };
914 if (s->mode == BASIC) {
915 if (s->th_mse == 0.f)
916 s->th_mse = 400.f + s->sigma * 80.f;
917 s->block_filtering = basic_block_filtering;
918 } else if (s->mode == FINAL) {
920 av_log(ctx, AV_LOG_WARNING, "Reference stream is mandatory in final estimation mode.\n");
923 if (s->th_mse == 0.f)
924 s->th_mse = 200.f + s->sigma * 10.f;
926 s->block_filtering = final_block_filtering;
931 s->block_size = 1 << s->block_size;
933 if (s->block_step > s->block_size) {
934 av_log(ctx, AV_LOG_WARNING, "bstep: %d can't be bigger than block size. Changing to %d.\n",
935 s->block_step, s->block_size);
936 s->block_step = s->block_size;
938 if (s->bm_step > s->bm_range) {
939 av_log(ctx, AV_LOG_WARNING, "mstep: %d can't be bigger than block matching range. Changing to %d.\n",
940 s->bm_step, s->bm_range);
941 s->bm_step = s->bm_range;
944 pad.type = AVMEDIA_TYPE_VIDEO;
946 pad.config_props = config_input;
948 if ((ret = ff_insert_inpad(ctx, 0, &pad)) < 0)
952 pad.type = AVMEDIA_TYPE_VIDEO;
953 pad.name = "reference";
954 pad.config_props = NULL;
956 if ((ret = ff_insert_inpad(ctx, 1, &pad)) < 0)
963 static int config_output(AVFilterLink *outlink)
965 AVFilterContext *ctx = outlink->src;
966 BM3DContext *s = ctx->priv;
967 AVFilterLink *src = ctx->inputs[0];
973 ref = ctx->inputs[1];
975 if (src->format != ref->format) {
976 av_log(ctx, AV_LOG_ERROR, "inputs must be of same pixel format\n");
977 return AVERROR(EINVAL);
979 if (src->w != ref->w ||
981 av_log(ctx, AV_LOG_ERROR, "First input link %s parameters "
982 "(size %dx%d) do not match the corresponding "
983 "second input link %s parameters (%dx%d) ",
984 ctx->input_pads[0].name, src->w, src->h,
985 ctx->input_pads[1].name, ref->w, ref->h);
986 return AVERROR(EINVAL);
992 outlink->time_base = src->time_base;
993 outlink->sample_aspect_ratio = src->sample_aspect_ratio;
994 outlink->frame_rate = src->frame_rate;
999 if ((ret = ff_framesync_init(&s->fs, ctx, 2)) < 0)
1003 in[0].time_base = src->time_base;
1004 in[1].time_base = ref->time_base;
1006 in[0].before = EXT_STOP;
1007 in[0].after = EXT_STOP;
1009 in[1].before = EXT_STOP;
1010 in[1].after = EXT_STOP;
1012 s->fs.on_event = process_frame;
1014 return ff_framesync_configure(&s->fs);
1017 static av_cold void uninit(AVFilterContext *ctx)
1019 BM3DContext *s = ctx->priv;
1023 ff_framesync_uninit(&s->fs);
1025 for (i = 0; i < s->nb_threads; i++) {
1026 SliceContext *sc = &s->slices[i];
1031 av_dct_end(sc->gdctf);
1032 av_dct_end(sc->gdcti);
1033 av_dct_end(sc->dctf);
1034 av_dct_end(sc->dcti);
1036 av_freep(&sc->buffer);
1037 av_freep(&sc->bufferh);
1038 av_freep(&sc->bufferv);
1039 av_freep(&sc->bufferz);
1040 av_freep(&sc->rbuffer);
1041 av_freep(&sc->rbufferh);
1042 av_freep(&sc->rbufferv);
1043 av_freep(&sc->rbufferz);
1045 av_freep(&sc->search_positions);
1049 static const AVFilterPad bm3d_outputs[] = {
1052 .type = AVMEDIA_TYPE_VIDEO,
1053 .config_props = config_output,
1058 AVFilter ff_vf_bm3d = {
1060 .description = NULL_IF_CONFIG_SMALL("Block-Matching 3D denoiser."),
1061 .priv_size = sizeof(BM3DContext),
1064 .activate = activate,
1065 .query_formats = query_formats,
1067 .outputs = bm3d_outputs,
1068 .priv_class = &bm3d_class,
1069 .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL |
1070 AVFILTER_FLAG_DYNAMIC_INPUTS |
1071 AVFILTER_FLAG_SLICE_THREADS,