• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2015-2016 mawen1250
3  * Copyright (c) 2018 Paul B Mahol
4  *
5  * This file is part of FFmpeg.
6  *
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:
13  *
14  * The above copyright notice and this permission notice shall be included in all
15  * copies or substantial portions of the Software.
16  *
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
23  * SOFTWARE.
24  */
25 
26 /**
27  * @todo
28  * - non-power of 2 DCT
29  * - opponent color space
30  * - temporal support
31  */
32 
33 #include <float.h>
34 
35 #include "libavutil/imgutils.h"
36 #include "libavutil/opt.h"
37 #include "libavutil/pixdesc.h"
38 #include "libavcodec/avfft.h"
39 #include "avfilter.h"
40 #include "filters.h"
41 #include "formats.h"
42 #include "framesync.h"
43 #include "internal.h"
44 #include "video.h"
45 
46 #define MAX_NB_THREADS 32
47 
48 enum FilterModes {
49     BASIC,
50     FINAL,
51     NB_MODES,
52 };
53 
54 typedef struct ThreadData {
55     const uint8_t *src;
56     int src_linesize;
57     const uint8_t *ref;
58     int ref_linesize;
59     int plane;
60 } ThreadData;
61 
62 typedef struct PosCode {
63     int x, y;
64 } PosCode;
65 
66 typedef struct PosPairCode {
67     double score;
68     int x, y;
69 } PosPairCode;
70 
71 typedef struct SliceContext {
72     DCTContext *gdctf, *gdcti;
73     DCTContext *dctf, *dcti;
74     FFTSample *bufferh;
75     FFTSample *bufferv;
76     FFTSample *bufferz;
77     FFTSample *buffer;
78     FFTSample *rbufferh;
79     FFTSample *rbufferv;
80     FFTSample *rbufferz;
81     FFTSample *rbuffer;
82     float *num, *den;
83     PosPairCode match_blocks[256];
84     int nb_match_blocks;
85     PosCode *search_positions;
86 } SliceContext;
87 
88 typedef struct BM3DContext {
89     const AVClass *class;
90 
91     float sigma;
92     int block_size;
93     int block_step;
94     int group_size;
95     int bm_range;
96     int bm_step;
97     float th_mse;
98     float hard_threshold;
99     int mode;
100     int ref;
101     int planes;
102 
103     int depth;
104     int max;
105     int nb_planes;
106     int planewidth[4];
107     int planeheight[4];
108     int group_bits;
109     int pgroup_size;
110 
111     SliceContext slices[MAX_NB_THREADS];
112 
113     FFFrameSync fs;
114     int nb_threads;
115 
116     void (*get_block_row)(const uint8_t *srcp, int src_linesize,
117                           int y, int x, int block_size, float *dst);
118     double (*do_block_ssd)(struct BM3DContext *s, PosCode *pos,
119                            const uint8_t *src, int src_stride,
120                            int r_y, int r_x);
121     void (*do_output)(struct BM3DContext *s, uint8_t *dst, int dst_linesize,
122                       int plane, int nb_jobs);
123     void (*block_filtering)(struct BM3DContext *s,
124                             const uint8_t *src, int src_linesize,
125                             const uint8_t *ref, int ref_linesize,
126                             int y, int x, int plane, int jobnr);
127 } BM3DContext;
128 
129 #define OFFSET(x) offsetof(BM3DContext, x)
130 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
131 static const AVOption bm3d_options[] = {
132     { "sigma",  "set denoising strength",
133         OFFSET(sigma),          AV_OPT_TYPE_FLOAT, {.dbl=1},     0,      99999.9, FLAGS },
134     { "block",  "set log2(size) of local patch",
135         OFFSET(block_size),     AV_OPT_TYPE_INT,   {.i64=4},     4,            6, FLAGS },
136     { "bstep",  "set sliding step for processing blocks",
137         OFFSET(block_step),     AV_OPT_TYPE_INT,   {.i64=4},     1,           64, FLAGS },
138     { "group",  "set maximal number of similar blocks",
139         OFFSET(group_size),     AV_OPT_TYPE_INT,   {.i64=1},     1,          256, FLAGS },
140     { "range",  "set block matching range",
141         OFFSET(bm_range),       AV_OPT_TYPE_INT,   {.i64=9},     1,    INT32_MAX, FLAGS },
142     { "mstep",  "set step for block matching",
143         OFFSET(bm_step),        AV_OPT_TYPE_INT,   {.i64=1},     1,           64, FLAGS },
144     { "thmse",  "set threshold of mean square error for block matching",
145         OFFSET(th_mse),         AV_OPT_TYPE_FLOAT, {.dbl=0},     0,    INT32_MAX, FLAGS },
146     { "hdthr",  "set hard threshold for 3D transfer domain",
147         OFFSET(hard_threshold), AV_OPT_TYPE_FLOAT, {.dbl=2.7},   0,    INT32_MAX, FLAGS },
148     { "estim",  "set filtering estimation mode",
149         OFFSET(mode),           AV_OPT_TYPE_INT,   {.i64=BASIC}, 0,   NB_MODES-1, FLAGS, "mode" },
150     { "basic",  "basic estimate",
151         0,                      AV_OPT_TYPE_CONST, {.i64=BASIC}, 0,            0, FLAGS, "mode" },
152     { "final",  "final estimate",
153         0,                      AV_OPT_TYPE_CONST, {.i64=FINAL}, 0,            0, FLAGS, "mode" },
154     { "ref",    "have reference stream",
155         OFFSET(ref),            AV_OPT_TYPE_BOOL,  {.i64=0},     0,            1, FLAGS },
156     { "planes", "set planes to filter",
157         OFFSET(planes),         AV_OPT_TYPE_INT,   {.i64=7},     0,           15, FLAGS },
158     { NULL }
159 };
160 
161 AVFILTER_DEFINE_CLASS(bm3d);
162 
163 static const enum AVPixelFormat pix_fmts[] = {
164     AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY9, AV_PIX_FMT_GRAY10,
165     AV_PIX_FMT_GRAY12, AV_PIX_FMT_GRAY14, AV_PIX_FMT_GRAY16,
166     AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
167     AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
168     AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
169     AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
170     AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P,
171     AV_PIX_FMT_YUVJ411P,
172     AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV422P9, AV_PIX_FMT_YUV444P9,
173     AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
174     AV_PIX_FMT_YUV440P10,
175     AV_PIX_FMT_YUV444P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV420P12,
176     AV_PIX_FMT_YUV440P12,
177     AV_PIX_FMT_YUV444P14, AV_PIX_FMT_YUV422P14, AV_PIX_FMT_YUV420P14,
178     AV_PIX_FMT_YUV420P16, AV_PIX_FMT_YUV422P16, AV_PIX_FMT_YUV444P16,
179     AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10,
180     AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
181     AV_PIX_FMT_YUVA420P,  AV_PIX_FMT_YUVA422P,   AV_PIX_FMT_YUVA444P,
182     AV_PIX_FMT_YUVA444P9, AV_PIX_FMT_YUVA444P10, AV_PIX_FMT_YUVA444P12, AV_PIX_FMT_YUVA444P16,
183     AV_PIX_FMT_YUVA422P9, AV_PIX_FMT_YUVA422P10, AV_PIX_FMT_YUVA422P12, AV_PIX_FMT_YUVA422P16,
184     AV_PIX_FMT_YUVA420P9, AV_PIX_FMT_YUVA420P10, AV_PIX_FMT_YUVA420P16,
185     AV_PIX_FMT_GBRAP,     AV_PIX_FMT_GBRAP10,    AV_PIX_FMT_GBRAP12,    AV_PIX_FMT_GBRAP16,
186     AV_PIX_FMT_NONE
187 };
188 
do_search_boundary(int pos,int plane_boundary,int search_range,int search_step)189 static int do_search_boundary(int pos, int plane_boundary, int search_range, int search_step)
190 {
191     int search_boundary;
192 
193     search_range = search_range / search_step * search_step;
194 
195     if (pos == plane_boundary) {
196         search_boundary = plane_boundary;
197     } else if (pos > plane_boundary) {
198         search_boundary = pos - search_range;
199 
200         while (search_boundary < plane_boundary) {
201             search_boundary += search_step;
202         }
203     } else {
204         search_boundary = pos + search_range;
205 
206         while (search_boundary > plane_boundary) {
207             search_boundary -= search_step;
208         }
209     }
210 
211     return search_boundary;
212 }
213 
search_boundary(int plane_boundary,int search_range,int search_step,int vertical,int y,int x)214 static int search_boundary(int plane_boundary, int search_range, int search_step, int vertical, int y, int x)
215 {
216     return do_search_boundary(vertical ? y : x, plane_boundary, search_range, search_step);
217 }
218 
cmp_scores(const void * a,const void * b)219 static int cmp_scores(const void *a, const void *b)
220 {
221     const struct PosPairCode *pair1 = a;
222     const struct PosPairCode *pair2 = b;
223     return FFDIFFSIGN(pair1->score, pair2->score);
224 }
225 
do_block_ssd(BM3DContext * s,PosCode * pos,const uint8_t * src,int src_stride,int r_y,int r_x)226 static double do_block_ssd(BM3DContext *s, PosCode *pos, const uint8_t *src, int src_stride, int r_y, int r_x)
227 {
228     const uint8_t *srcp = src + pos->y * src_stride + pos->x;
229     const uint8_t *refp = src + r_y * src_stride + r_x;
230     const int block_size = s->block_size;
231     double dist = 0.;
232     int x, y;
233 
234     for (y = 0; y < block_size; y++) {
235         for (x = 0; x < block_size; x++) {
236             double temp = refp[x] - srcp[x];
237             dist += temp * temp;
238         }
239 
240         srcp += src_stride;
241         refp += src_stride;
242     }
243 
244     return dist;
245 }
246 
do_block_ssd16(BM3DContext * s,PosCode * pos,const uint8_t * src,int src_stride,int r_y,int r_x)247 static double do_block_ssd16(BM3DContext *s, PosCode *pos, const uint8_t *src, int src_stride, int r_y, int r_x)
248 {
249     const uint16_t *srcp = (uint16_t *)src + pos->y * src_stride / 2 + pos->x;
250     const uint16_t *refp = (uint16_t *)src + r_y * src_stride / 2 + r_x;
251     const int block_size = s->block_size;
252     double dist = 0.;
253     int x, y;
254 
255     for (y = 0; y < block_size; y++) {
256         for (x = 0; x < block_size; x++) {
257             double temp = refp[x] - srcp[x];
258             dist += temp * temp;
259         }
260 
261         srcp += src_stride / 2;
262         refp += src_stride / 2;
263     }
264 
265     return dist;
266 }
267 
do_block_matching_multi(BM3DContext * s,const uint8_t * src,int src_stride,int src_range,const PosCode * search_pos,int search_size,float th_mse,int r_y,int r_x,int plane,int jobnr)268 static void do_block_matching_multi(BM3DContext *s, const uint8_t *src, int src_stride, int src_range,
269                                     const PosCode *search_pos, int search_size, float th_mse,
270                                     int r_y, int r_x, int plane, int jobnr)
271 {
272     SliceContext *sc = &s->slices[jobnr];
273     double MSE2SSE = s->group_size * s->block_size * s->block_size * src_range * src_range / (s->max * s->max);
274     double distMul = 1. / MSE2SSE;
275     double th_sse = th_mse * MSE2SSE;
276     int i, index = sc->nb_match_blocks;
277 
278     for (i = 0; i < search_size; i++) {
279         PosCode pos = search_pos[i];
280         double dist;
281 
282         dist = s->do_block_ssd(s, &pos, src, src_stride, r_y, r_x);
283 
284         // Only match similar blocks but not identical blocks
285         if (dist <= th_sse && dist != 0) {
286             const double score = dist * distMul;
287 
288             if (index >= s->group_size && score >= sc->match_blocks[index - 1].score) {
289                 continue;
290             }
291 
292             if (index >= s->group_size)
293                 index = s->group_size - 1;
294 
295             sc->match_blocks[index].score = score;
296             sc->match_blocks[index].y = pos.y;
297             sc->match_blocks[index].x = pos.x;
298             index++;
299             qsort(sc->match_blocks, index, sizeof(PosPairCode), cmp_scores);
300         }
301     }
302 
303     sc->nb_match_blocks = index;
304 }
305 
block_matching_multi(BM3DContext * s,const uint8_t * ref,int ref_linesize,int y,int x,int exclude_cur_pos,int plane,int jobnr)306 static void block_matching_multi(BM3DContext *s, const uint8_t *ref, int ref_linesize, int y, int x,
307                                  int exclude_cur_pos, int plane, int jobnr)
308 {
309     SliceContext *sc = &s->slices[jobnr];
310     const int width = s->planewidth[plane];
311     const int height = s->planeheight[plane];
312     const int block_size = s->block_size;
313     const int step = s->bm_step;
314     const int range = s->bm_range / step * step;
315     int l = search_boundary(0, range, step, 0, y, x);
316     int r = search_boundary(width - block_size, range, step, 0, y, x);
317     int t = search_boundary(0, range, step, 1, y, x);
318     int b = search_boundary(height - block_size, range, step, 1, y, x);
319     int j, i, index = 0;
320 
321     for (j = t; j <= b; j += step) {
322         for (i = l; i <= r; i += step) {
323             PosCode pos;
324 
325             if (exclude_cur_pos > 0 && j == y && i == x) {
326                 continue;
327             }
328 
329             pos.y = j;
330             pos.x = i;
331             sc->search_positions[index++] = pos;
332         }
333     }
334 
335     if (exclude_cur_pos == 1) {
336         sc->match_blocks[0].score = 0;
337         sc->match_blocks[0].y = y;
338         sc->match_blocks[0].x = x;
339         sc->nb_match_blocks = 1;
340     }
341 
342     do_block_matching_multi(s, ref, ref_linesize, s->bm_range,
343                             sc->search_positions, index, s->th_mse, y, x, plane, jobnr);
344 }
345 
block_matching(BM3DContext * s,const uint8_t * ref,int ref_linesize,int j,int i,int plane,int jobnr)346 static void block_matching(BM3DContext *s, const uint8_t *ref, int ref_linesize,
347                            int j, int i, int plane, int jobnr)
348 {
349     SliceContext *sc = &s->slices[jobnr];
350 
351     if (s->group_size == 1 || s->th_mse <= 0.f) {
352         sc->match_blocks[0].score = 1;
353         sc->match_blocks[0].x = i;
354         sc->match_blocks[0].y = j;
355         sc->nb_match_blocks = 1;
356         return;
357     }
358 
359     sc->nb_match_blocks = 0;
360     block_matching_multi(s, ref, ref_linesize, j, i, 1, plane, jobnr);
361 }
362 
get_block_row(const uint8_t * srcp,int src_linesize,int y,int x,int block_size,float * dst)363 static void get_block_row(const uint8_t *srcp, int src_linesize,
364                           int y, int x, int block_size, float *dst)
365 {
366     const uint8_t *src = srcp + y * src_linesize + x;
367     int j;
368 
369     for (j = 0; j < block_size; j++) {
370         dst[j] = src[j];
371     }
372 }
373 
get_block_row16(const uint8_t * srcp,int src_linesize,int y,int x,int block_size,float * dst)374 static void get_block_row16(const uint8_t *srcp, int src_linesize,
375                             int y, int x, int block_size, float *dst)
376 {
377     const uint16_t *src = (uint16_t *)srcp + y * src_linesize / 2 + x;
378     int j;
379 
380     for (j = 0; j < block_size; j++) {
381         dst[j] = src[j];
382     }
383 }
384 
basic_block_filtering(BM3DContext * s,const uint8_t * src,int src_linesize,const uint8_t * ref,int ref_linesize,int y,int x,int plane,int jobnr)385 static void basic_block_filtering(BM3DContext *s, const uint8_t *src, int src_linesize,
386                                   const uint8_t *ref, int ref_linesize,
387                                   int y, int x, int plane, int jobnr)
388 {
389     SliceContext *sc = &s->slices[jobnr];
390     const int buffer_linesize = s->block_size * s->block_size;
391     const int nb_match_blocks = sc->nb_match_blocks;
392     const int block_size = s->block_size;
393     const int width = s->planewidth[plane];
394     const int pgroup_size = s->pgroup_size;
395     const int group_size = s->group_size;
396     float *buffer = sc->buffer;
397     float *bufferh = sc->bufferh;
398     float *bufferv = sc->bufferv;
399     float *bufferz = sc->bufferz;
400     float threshold[4];
401     float den_weight, num_weight;
402     int retained = 0;
403     int i, j, k;
404 
405     for (k = 0; k < nb_match_blocks; k++) {
406         const int y = sc->match_blocks[k].y;
407         const int x = sc->match_blocks[k].x;
408 
409         for (i = 0; i < block_size; i++) {
410             s->get_block_row(src, src_linesize, y + i, x, block_size, bufferh + block_size * i);
411             av_dct_calc(sc->dctf, bufferh + block_size * i);
412         }
413 
414         for (i = 0; i < block_size; i++) {
415             for (j = 0; j < block_size; j++) {
416                 bufferv[i * block_size + j] = bufferh[j * block_size + i];
417             }
418             av_dct_calc(sc->dctf, bufferv + i * block_size);
419         }
420 
421         for (i = 0; i < block_size; i++) {
422             memcpy(buffer + k * buffer_linesize + i * block_size,
423                    bufferv + i * block_size, block_size * 4);
424         }
425     }
426 
427     for (i = 0; i < block_size; i++) {
428         for (j = 0; j < block_size; j++) {
429             for (k = 0; k < nb_match_blocks; k++)
430                 bufferz[k] = buffer[buffer_linesize * k + i * block_size + j];
431             if (group_size > 1)
432                 av_dct_calc(sc->gdctf, bufferz);
433             bufferz += pgroup_size;
434         }
435     }
436 
437     threshold[0] = s->hard_threshold * s->sigma * M_SQRT2 * block_size * block_size * (1 << (s->depth - 8)) / 255.f;
438     threshold[1] = threshold[0] * sqrtf(2.f);
439     threshold[2] = threshold[0] * 2.f;
440     threshold[3] = threshold[0] * sqrtf(8.f);
441     bufferz = sc->bufferz;
442 
443     for (i = 0; i < block_size; i++) {
444         for (j = 0; j < block_size; j++) {
445             for (k = 0; k < nb_match_blocks; k++) {
446                 const float thresh = threshold[(j == 0) + (i == 0) + (k == 0)];
447 
448                 if (bufferz[k] > thresh || bufferz[k] < -thresh) {
449                     retained++;
450                 } else {
451                     bufferz[k] = 0;
452                 }
453             }
454             bufferz += pgroup_size;
455         }
456     }
457 
458     bufferz = sc->bufferz;
459     buffer = sc->buffer;
460     for (i = 0; i < block_size; i++) {
461         for (j = 0; j < block_size; j++) {
462             if (group_size > 1)
463                 av_dct_calc(sc->gdcti, bufferz);
464             for (k = 0; k < nb_match_blocks; k++) {
465                 buffer[buffer_linesize * k + i * block_size + j] = bufferz[k];
466             }
467             bufferz += pgroup_size;
468         }
469     }
470 
471     den_weight = retained < 1 ? 1.f : 1.f / retained;
472     num_weight = den_weight;
473 
474     buffer = sc->buffer;
475     for (k = 0; k < nb_match_blocks; k++) {
476         float *num = sc->num + y * width + x;
477         float *den = sc->den + y * width + x;
478 
479         for (i = 0; i < block_size; i++) {
480             memcpy(bufferv + i * block_size,
481                    buffer + k * buffer_linesize + i * block_size,
482                    block_size * 4);
483         }
484 
485         for (i = 0; i < block_size; i++) {
486             av_dct_calc(sc->dcti, bufferv + block_size * i);
487             for (j = 0; j < block_size; j++) {
488                 bufferh[j * block_size + i] = bufferv[i * block_size + j];
489             }
490         }
491 
492         for (i = 0; i < block_size; i++) {
493             av_dct_calc(sc->dcti, bufferh + block_size * i);
494             for (j = 0; j < block_size; j++) {
495                 num[j] += bufferh[i * block_size + j] * num_weight;
496                 den[j] += den_weight;
497             }
498             num += width;
499             den += width;
500         }
501     }
502 }
503 
final_block_filtering(BM3DContext * s,const uint8_t * src,int src_linesize,const uint8_t * ref,int ref_linesize,int y,int x,int plane,int jobnr)504 static void final_block_filtering(BM3DContext *s, const uint8_t *src, int src_linesize,
505                                   const uint8_t *ref, int ref_linesize,
506                                   int y, int x, int plane, int jobnr)
507 {
508     SliceContext *sc = &s->slices[jobnr];
509     const int buffer_linesize = s->block_size * s->block_size;
510     const int nb_match_blocks = sc->nb_match_blocks;
511     const int block_size = s->block_size;
512     const int width = s->planewidth[plane];
513     const int pgroup_size = s->pgroup_size;
514     const int group_size = s->group_size;
515     const float sigma_sqr = s->sigma * s->sigma;
516     float *buffer = sc->buffer;
517     float *bufferh = sc->bufferh;
518     float *bufferv = sc->bufferv;
519     float *bufferz = sc->bufferz;
520     float *rbuffer = sc->rbuffer;
521     float *rbufferh = sc->rbufferh;
522     float *rbufferv = sc->rbufferv;
523     float *rbufferz = sc->rbufferz;
524     float den_weight, num_weight;
525     float l2_wiener = 0;
526     int i, j, k;
527 
528     for (k = 0; k < nb_match_blocks; k++) {
529         const int y = sc->match_blocks[k].y;
530         const int x = sc->match_blocks[k].x;
531 
532         for (i = 0; i < block_size; i++) {
533             s->get_block_row(src, src_linesize, y + i, x, block_size, bufferh + block_size * i);
534             s->get_block_row(ref, ref_linesize, y + i, x, block_size, rbufferh + block_size * i);
535             av_dct_calc(sc->dctf, bufferh + block_size * i);
536             av_dct_calc(sc->dctf, rbufferh + block_size * i);
537         }
538 
539         for (i = 0; i < block_size; i++) {
540             for (j = 0; j < block_size; j++) {
541                 bufferv[i * block_size + j] = bufferh[j * block_size + i];
542                 rbufferv[i * block_size + j] = rbufferh[j * block_size + i];
543             }
544             av_dct_calc(sc->dctf, bufferv + i * block_size);
545             av_dct_calc(sc->dctf, rbufferv + i * block_size);
546         }
547 
548         for (i = 0; i < block_size; i++) {
549             memcpy(buffer + k * buffer_linesize + i * block_size,
550                    bufferv + i * block_size, block_size * 4);
551             memcpy(rbuffer + k * buffer_linesize + i * block_size,
552                    rbufferv + i * block_size, block_size * 4);
553         }
554     }
555 
556     for (i = 0; i < block_size; i++) {
557         for (j = 0; j < block_size; j++) {
558             for (k = 0; k < nb_match_blocks; k++) {
559                 bufferz[k] = buffer[buffer_linesize * k + i * block_size + j];
560                 rbufferz[k] = rbuffer[buffer_linesize * k + i * block_size + j];
561             }
562             if (group_size > 1) {
563                 av_dct_calc(sc->gdctf, bufferz);
564                 av_dct_calc(sc->gdctf, rbufferz);
565             }
566             bufferz += pgroup_size;
567             rbufferz += pgroup_size;
568         }
569     }
570 
571     bufferz = sc->bufferz;
572     rbufferz = sc->rbufferz;
573 
574     for (i = 0; i < block_size; i++) {
575         for (j = 0; j < block_size; j++) {
576             for (k = 0; k < nb_match_blocks; k++) {
577                 const float ref_sqr = rbufferz[k] * rbufferz[k];
578                 float wiener_coef = ref_sqr / (ref_sqr + sigma_sqr);
579 
580                 if (isnan(wiener_coef))
581                    wiener_coef = 1;
582                 bufferz[k] *= wiener_coef;
583                 l2_wiener += wiener_coef * wiener_coef;
584             }
585             bufferz += pgroup_size;
586             rbufferz += pgroup_size;
587         }
588     }
589 
590     bufferz = sc->bufferz;
591     buffer = sc->buffer;
592     for (i = 0; i < block_size; i++) {
593         for (j = 0; j < block_size; j++) {
594             if (group_size > 1)
595                 av_dct_calc(sc->gdcti, bufferz);
596             for (k = 0; k < nb_match_blocks; k++) {
597                 buffer[buffer_linesize * k + i * block_size + j] = bufferz[k];
598             }
599             bufferz += pgroup_size;
600         }
601     }
602 
603     l2_wiener = FFMAX(l2_wiener, 1e-15f);
604     den_weight = 1.f / l2_wiener;
605     num_weight = den_weight;
606 
607     for (k = 0; k < nb_match_blocks; k++) {
608         float *num = sc->num + y * width + x;
609         float *den = sc->den + y * width + x;
610 
611         for (i = 0; i < block_size; i++) {
612             memcpy(bufferv + i * block_size,
613                    buffer + k * buffer_linesize + i * block_size,
614                    block_size * 4);
615         }
616 
617         for (i = 0; i < block_size; i++) {
618             av_dct_calc(sc->dcti, bufferv + block_size * i);
619             for (j = 0; j < block_size; j++) {
620                 bufferh[j * block_size + i] = bufferv[i * block_size + j];
621             }
622         }
623 
624         for (i = 0; i < block_size; i++) {
625             av_dct_calc(sc->dcti, bufferh + block_size * i);
626             for (j = 0; j < block_size; j++) {
627                 num[j] += bufferh[i * block_size + j] * num_weight;
628                 den[j] += den_weight;
629             }
630             num += width;
631             den += width;
632         }
633     }
634 }
635 
do_output(BM3DContext * s,uint8_t * dst,int dst_linesize,int plane,int nb_jobs)636 static void do_output(BM3DContext *s, uint8_t *dst, int dst_linesize,
637                       int plane, int nb_jobs)
638 {
639     const int height = s->planeheight[plane];
640     const int width = s->planewidth[plane];
641     int i, j, k;
642 
643     for (i = 0; i < height; i++) {
644         for (j = 0; j < width; j++) {
645             uint8_t *dstp = dst + i * dst_linesize;
646             float sum_den = 0.f;
647             float sum_num = 0.f;
648 
649             for (k = 0; k < nb_jobs; k++) {
650                 SliceContext *sc = &s->slices[k];
651                 float num = sc->num[i * width + j];
652                 float den = sc->den[i * width + j];
653 
654                 sum_num += num;
655                 sum_den += den;
656             }
657 
658             dstp[j] = av_clip_uint8(lrintf(sum_num / sum_den));
659         }
660     }
661 }
662 
do_output16(BM3DContext * s,uint8_t * dst,int dst_linesize,int plane,int nb_jobs)663 static void do_output16(BM3DContext *s, uint8_t *dst, int dst_linesize,
664                         int plane, int nb_jobs)
665 {
666     const int height = s->planeheight[plane];
667     const int width = s->planewidth[plane];
668     const int depth = s->depth;
669     int i, j, k;
670 
671     for (i = 0; i < height; i++) {
672         for (j = 0; j < width; j++) {
673             uint16_t *dstp = (uint16_t *)dst + i * dst_linesize / 2;
674             float sum_den = 0.f;
675             float sum_num = 0.f;
676 
677             for (k = 0; k < nb_jobs; k++) {
678                 SliceContext *sc = &s->slices[k];
679                 float num = sc->num[i * width + j];
680                 float den = sc->den[i * width + j];
681 
682                 sum_num += num;
683                 sum_den += den;
684             }
685 
686             dstp[j] = av_clip_uintp2_c(lrintf(sum_num / sum_den), depth);
687         }
688     }
689 }
690 
filter_slice(AVFilterContext * ctx,void * arg,int jobnr,int nb_jobs)691 static int filter_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
692 {
693     BM3DContext *s = ctx->priv;
694     SliceContext *sc = &s->slices[jobnr];
695     const int block_step = s->block_step;
696     ThreadData *td = arg;
697     const uint8_t *src = td->src;
698     const uint8_t *ref = td->ref;
699     const int src_linesize = td->src_linesize;
700     const int ref_linesize = td->ref_linesize;
701     const int plane = td->plane;
702     const int width = s->planewidth[plane];
703     const int height = s->planeheight[plane];
704     const int block_pos_bottom = FFMAX(0, height - s->block_size);
705     const int block_pos_right  = FFMAX(0, width - s->block_size);
706     const int slice_start = (((height + block_step - 1) / block_step) * jobnr / nb_jobs) * block_step;
707     const int slice_end = (jobnr == nb_jobs - 1) ? block_pos_bottom + block_step :
708                           (((height + block_step - 1) / block_step) * (jobnr + 1) / nb_jobs) * block_step;
709     int i, j;
710 
711     memset(sc->num, 0, width * height * sizeof(FFTSample));
712     memset(sc->den, 0, width * height * sizeof(FFTSample));
713 
714     for (j = slice_start; j < slice_end; j += block_step) {
715         if (j > block_pos_bottom) {
716             j = block_pos_bottom;
717         }
718 
719         for (i = 0; i < block_pos_right + block_step; i += block_step) {
720             if (i > block_pos_right) {
721                 i = block_pos_right;
722             }
723 
724             block_matching(s, ref, ref_linesize, j, i, plane, jobnr);
725 
726             s->block_filtering(s, src, src_linesize,
727                                ref, ref_linesize, j, i, plane, jobnr);
728         }
729     }
730 
731     return 0;
732 }
733 
filter_frame(AVFilterContext * ctx,AVFrame ** out,AVFrame * in,AVFrame * ref)734 static int filter_frame(AVFilterContext *ctx, AVFrame **out, AVFrame *in, AVFrame *ref)
735 {
736     BM3DContext *s = ctx->priv;
737     AVFilterLink *outlink = ctx->outputs[0];
738     int p;
739 
740     *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
741     if (!*out)
742         return AVERROR(ENOMEM);
743     av_frame_copy_props(*out, in);
744 
745     for (p = 0; p < s->nb_planes; p++) {
746         const int nb_jobs = FFMAX(1, FFMIN(s->nb_threads, s->planeheight[p] / s->block_size));
747         ThreadData td;
748 
749         if (!((1 << p) & s->planes) || ctx->is_disabled) {
750             av_image_copy_plane((*out)->data[p], (*out)->linesize[p],
751                                 in->data[p], in->linesize[p],
752                                 s->planewidth[p], s->planeheight[p]);
753             continue;
754         }
755 
756         td.src = in->data[p];
757         td.src_linesize = in->linesize[p];
758         td.ref = ref->data[p];
759         td.ref_linesize = ref->linesize[p];
760         td.plane = p;
761         ff_filter_execute(ctx, filter_slice, &td, NULL, nb_jobs);
762 
763         s->do_output(s, (*out)->data[p], (*out)->linesize[p], p, nb_jobs);
764     }
765 
766     return 0;
767 }
768 
769 #define SQR(x) ((x) * (x))
770 
config_input(AVFilterLink * inlink)771 static int config_input(AVFilterLink *inlink)
772 {
773     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
774     AVFilterContext *ctx = inlink->dst;
775     BM3DContext *s = ctx->priv;
776     int i, group_bits;
777 
778     s->nb_threads = FFMIN(ff_filter_get_nb_threads(ctx), MAX_NB_THREADS);
779     s->nb_planes = av_pix_fmt_count_planes(inlink->format);
780     s->depth = desc->comp[0].depth;
781     s->max = (1 << s->depth) - 1;
782     s->planeheight[1] = s->planeheight[2] = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
783     s->planeheight[0] = s->planeheight[3] = inlink->h;
784     s->planewidth[1]  = s->planewidth[2]  = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
785     s->planewidth[0]  = s->planewidth[3]  = inlink->w;
786 
787     for (group_bits = 4; 1 << group_bits < s->group_size; group_bits++);
788     s->group_bits = group_bits;
789     s->pgroup_size = 1 << group_bits;
790 
791     for (i = 0; i < s->nb_threads; i++) {
792         SliceContext *sc = &s->slices[i];
793 
794         sc->num = av_calloc(FFALIGN(s->planewidth[0], s->block_size) * FFALIGN(s->planeheight[0], s->block_size), sizeof(FFTSample));
795         sc->den = av_calloc(FFALIGN(s->planewidth[0], s->block_size) * FFALIGN(s->planeheight[0], s->block_size), sizeof(FFTSample));
796         if (!sc->num || !sc->den)
797             return AVERROR(ENOMEM);
798 
799         sc->dctf = av_dct_init(av_log2(s->block_size), DCT_II);
800         sc->dcti = av_dct_init(av_log2(s->block_size), DCT_III);
801         if (!sc->dctf || !sc->dcti)
802             return AVERROR(ENOMEM);
803 
804         if (s->group_bits > 1) {
805             sc->gdctf = av_dct_init(s->group_bits, DCT_II);
806             sc->gdcti = av_dct_init(s->group_bits, DCT_III);
807             if (!sc->gdctf || !sc->gdcti)
808                 return AVERROR(ENOMEM);
809         }
810 
811         sc->buffer = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->buffer));
812         sc->bufferz = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->bufferz));
813         sc->bufferh = av_calloc(s->block_size * s->block_size, sizeof(*sc->bufferh));
814         sc->bufferv = av_calloc(s->block_size * s->block_size, sizeof(*sc->bufferv));
815         if (!sc->bufferh || !sc->bufferv || !sc->buffer || !sc->bufferz)
816             return AVERROR(ENOMEM);
817 
818         if (s->mode == FINAL) {
819             sc->rbuffer = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->rbuffer));
820             sc->rbufferz = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->rbufferz));
821             sc->rbufferh = av_calloc(s->block_size * s->block_size, sizeof(*sc->rbufferh));
822             sc->rbufferv = av_calloc(s->block_size * s->block_size, sizeof(*sc->rbufferv));
823             if (!sc->rbufferh || !sc->rbufferv || !sc->rbuffer || !sc->rbufferz)
824                 return AVERROR(ENOMEM);
825         }
826 
827         sc->search_positions = av_calloc(SQR(2 * s->bm_range / s->bm_step + 1), sizeof(*sc->search_positions));
828         if (!sc->search_positions)
829             return AVERROR(ENOMEM);
830     }
831 
832     s->do_output = do_output;
833     s->do_block_ssd = do_block_ssd;
834     s->get_block_row = get_block_row;
835 
836     if (s->depth > 8) {
837         s->do_output = do_output16;
838         s->do_block_ssd = do_block_ssd16;
839         s->get_block_row = get_block_row16;
840     }
841 
842     return 0;
843 }
844 
activate(AVFilterContext * ctx)845 static int activate(AVFilterContext *ctx)
846 {
847     BM3DContext *s = ctx->priv;
848 
849     if (!s->ref) {
850         AVFrame *frame = NULL;
851         AVFrame *out = NULL;
852         int ret, status;
853         int64_t pts;
854 
855         FF_FILTER_FORWARD_STATUS_BACK(ctx->outputs[0], ctx->inputs[0]);
856 
857         if ((ret = ff_inlink_consume_frame(ctx->inputs[0], &frame)) > 0) {
858             ret = filter_frame(ctx, &out, frame, frame);
859             av_frame_free(&frame);
860             if (ret < 0)
861                 return ret;
862             ret = ff_filter_frame(ctx->outputs[0], out);
863         }
864         if (ret < 0) {
865             return ret;
866         } else if (ff_inlink_acknowledge_status(ctx->inputs[0], &status, &pts)) {
867             ff_outlink_set_status(ctx->outputs[0], status, pts);
868             return 0;
869         } else {
870             if (ff_outlink_frame_wanted(ctx->outputs[0]))
871                 ff_inlink_request_frame(ctx->inputs[0]);
872             return 0;
873         }
874     } else {
875         return ff_framesync_activate(&s->fs);
876     }
877 }
878 
process_frame(FFFrameSync * fs)879 static int process_frame(FFFrameSync *fs)
880 {
881     AVFilterContext *ctx = fs->parent;
882     BM3DContext *s = fs->opaque;
883     AVFilterLink *outlink = ctx->outputs[0];
884     AVFrame *out = NULL, *src, *ref;
885     int ret;
886 
887     if ((ret = ff_framesync_get_frame(&s->fs, 0, &src, 0)) < 0 ||
888         (ret = ff_framesync_get_frame(&s->fs, 1, &ref, 0)) < 0)
889         return ret;
890 
891     if ((ret = filter_frame(ctx, &out, src, ref)) < 0)
892         return ret;
893 
894     out->pts = av_rescale_q(src->pts, s->fs.time_base, outlink->time_base);
895 
896     return ff_filter_frame(outlink, out);
897 }
898 
init(AVFilterContext * ctx)899 static av_cold int init(AVFilterContext *ctx)
900 {
901     BM3DContext *s = ctx->priv;
902     AVFilterPad pad = { 0 };
903     int ret;
904 
905     if (s->mode == BASIC) {
906         if (s->th_mse == 0.f)
907             s->th_mse = 400.f + s->sigma * 80.f;
908         s->block_filtering = basic_block_filtering;
909     } else if (s->mode == FINAL) {
910         if (!s->ref) {
911             av_log(ctx, AV_LOG_WARNING, "Reference stream is mandatory in final estimation mode.\n");
912             s->ref = 1;
913         }
914         if (s->th_mse == 0.f)
915             s->th_mse = 200.f + s->sigma * 10.f;
916 
917         s->block_filtering = final_block_filtering;
918     } else {
919         return AVERROR_BUG;
920     }
921 
922     s->block_size = 1 << s->block_size;
923 
924     if (s->block_step > s->block_size) {
925         av_log(ctx, AV_LOG_WARNING, "bstep: %d can't be bigger than block size. Changing to %d.\n",
926                s->block_step, s->block_size);
927         s->block_step = s->block_size;
928     }
929     if (s->bm_step > s->bm_range) {
930         av_log(ctx, AV_LOG_WARNING, "mstep: %d can't be bigger than block matching range. Changing to %d.\n",
931                s->bm_step, s->bm_range);
932         s->bm_step = s->bm_range;
933     }
934 
935     pad.type         = AVMEDIA_TYPE_VIDEO;
936     pad.name         = "source";
937     pad.config_props = config_input;
938 
939     if ((ret = ff_append_inpad(ctx, &pad)) < 0)
940         return ret;
941 
942     if (s->ref) {
943         pad.type         = AVMEDIA_TYPE_VIDEO;
944         pad.name         = "reference";
945         pad.config_props = NULL;
946 
947         if ((ret = ff_append_inpad(ctx, &pad)) < 0)
948             return ret;
949     }
950 
951     return 0;
952 }
953 
config_output(AVFilterLink * outlink)954 static int config_output(AVFilterLink *outlink)
955 {
956     AVFilterContext *ctx = outlink->src;
957     BM3DContext *s = ctx->priv;
958     AVFilterLink *src = ctx->inputs[0];
959     AVFilterLink *ref;
960     FFFrameSyncIn *in;
961     int ret;
962 
963     if (s->ref) {
964         ref = ctx->inputs[1];
965 
966         if (src->w                       != ref->w ||
967             src->h                       != ref->h) {
968             av_log(ctx, AV_LOG_ERROR, "First input link %s parameters "
969                    "(size %dx%d) do not match the corresponding "
970                    "second input link %s parameters (%dx%d) ",
971                    ctx->input_pads[0].name, src->w, src->h,
972                    ctx->input_pads[1].name, ref->w, ref->h);
973             return AVERROR(EINVAL);
974         }
975     }
976 
977     outlink->w = src->w;
978     outlink->h = src->h;
979     outlink->time_base = src->time_base;
980     outlink->sample_aspect_ratio = src->sample_aspect_ratio;
981     outlink->frame_rate = src->frame_rate;
982 
983     if (!s->ref)
984         return 0;
985 
986     if ((ret = ff_framesync_init(&s->fs, ctx, 2)) < 0)
987         return ret;
988 
989     in = s->fs.in;
990     in[0].time_base = src->time_base;
991     in[1].time_base = ref->time_base;
992     in[0].sync   = 1;
993     in[0].before = EXT_STOP;
994     in[0].after  = EXT_STOP;
995     in[1].sync   = 1;
996     in[1].before = EXT_STOP;
997     in[1].after  = EXT_STOP;
998     s->fs.opaque   = s;
999     s->fs.on_event = process_frame;
1000 
1001     return ff_framesync_configure(&s->fs);
1002 }
1003 
uninit(AVFilterContext * ctx)1004 static av_cold void uninit(AVFilterContext *ctx)
1005 {
1006     BM3DContext *s = ctx->priv;
1007     int i;
1008 
1009     if (s->ref)
1010         ff_framesync_uninit(&s->fs);
1011 
1012     for (i = 0; i < s->nb_threads; i++) {
1013         SliceContext *sc = &s->slices[i];
1014 
1015         av_freep(&sc->num);
1016         av_freep(&sc->den);
1017 
1018         av_dct_end(sc->gdctf);
1019         av_dct_end(sc->gdcti);
1020         av_dct_end(sc->dctf);
1021         av_dct_end(sc->dcti);
1022 
1023         av_freep(&sc->buffer);
1024         av_freep(&sc->bufferh);
1025         av_freep(&sc->bufferv);
1026         av_freep(&sc->bufferz);
1027         av_freep(&sc->rbuffer);
1028         av_freep(&sc->rbufferh);
1029         av_freep(&sc->rbufferv);
1030         av_freep(&sc->rbufferz);
1031 
1032         av_freep(&sc->search_positions);
1033     }
1034 }
1035 
1036 static const AVFilterPad bm3d_outputs[] = {
1037     {
1038         .name         = "default",
1039         .type         = AVMEDIA_TYPE_VIDEO,
1040         .config_props = config_output,
1041     },
1042 };
1043 
1044 const AVFilter ff_vf_bm3d = {
1045     .name          = "bm3d",
1046     .description   = NULL_IF_CONFIG_SMALL("Block-Matching 3D denoiser."),
1047     .priv_size     = sizeof(BM3DContext),
1048     .init          = init,
1049     .uninit        = uninit,
1050     .activate      = activate,
1051     .inputs        = NULL,
1052     FILTER_OUTPUTS(bm3d_outputs),
1053     FILTER_PIXFMTS_ARRAY(pix_fmts),
1054     .priv_class    = &bm3d_class,
1055     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL |
1056                      AVFILTER_FLAG_DYNAMIC_INPUTS |
1057                      AVFILTER_FLAG_SLICE_THREADS,
1058 };
1059