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.

1073 lines
35KB

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