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.

1079 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_INT, {.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_NONE
  167. };
  168. AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
  169. if (!fmts_list)
  170. return AVERROR(ENOMEM);
  171. return ff_set_common_formats(ctx, fmts_list);
  172. }
  173. static int do_search_boundary(int pos, int plane_boundary, int search_range, int search_step)
  174. {
  175. int search_boundary;
  176. search_range = search_range / search_step * search_step;
  177. if (pos == plane_boundary) {
  178. search_boundary = plane_boundary;
  179. } else if (pos > plane_boundary) {
  180. search_boundary = pos - search_range;
  181. while (search_boundary < plane_boundary) {
  182. search_boundary += search_step;
  183. }
  184. } else {
  185. search_boundary = pos + search_range;
  186. while (search_boundary > plane_boundary) {
  187. search_boundary -= search_step;
  188. }
  189. }
  190. return search_boundary;
  191. }
  192. static int search_boundary(int plane_boundary, int search_range, int search_step, int vertical, int y, int x)
  193. {
  194. return do_search_boundary(vertical ? y : x, plane_boundary, search_range, search_step);
  195. }
  196. static int cmp_scores(const void *a, const void *b)
  197. {
  198. const struct PosPairCode *pair1 = a;
  199. const struct PosPairCode *pair2 = b;
  200. return FFDIFFSIGN(pair1->score, pair2->score);
  201. }
  202. static double do_block_ssd(BM3DContext *s, PosCode *pos, const uint8_t *src, int src_stride, int r_y, int r_x)
  203. {
  204. const uint8_t *srcp = src + pos->y * src_stride + pos->x;
  205. const uint8_t *refp = src + r_y * src_stride + r_x;
  206. const int block_size = s->block_size;
  207. double dist = 0.;
  208. int x, y;
  209. for (y = 0; y < block_size; y++) {
  210. for (x = 0; x < block_size; x++) {
  211. double temp = refp[x] - srcp[x];
  212. dist += temp * temp;
  213. }
  214. srcp += src_stride;
  215. refp += src_stride;
  216. }
  217. return dist;
  218. }
  219. static double do_block_ssd16(BM3DContext *s, PosCode *pos, const uint8_t *src, int src_stride, int r_y, int r_x)
  220. {
  221. const uint16_t *srcp = (uint16_t *)src + pos->y * src_stride / 2 + pos->x;
  222. const uint16_t *refp = (uint16_t *)src + r_y * src_stride / 2 + r_x;
  223. const int block_size = s->block_size;
  224. double dist = 0.;
  225. int x, y;
  226. for (y = 0; y < block_size; y++) {
  227. for (x = 0; x < block_size; x++) {
  228. double temp = refp[x] - srcp[x];
  229. dist += temp * temp;
  230. }
  231. srcp += src_stride / 2;
  232. refp += src_stride / 2;
  233. }
  234. return dist;
  235. }
  236. static void do_block_matching_multi(BM3DContext *s, const uint8_t *src, int src_stride, int src_range,
  237. const PosCode *search_pos, int search_size, float th_mse,
  238. int r_y, int r_x, int plane, int jobnr)
  239. {
  240. SliceContext *sc = &s->slices[jobnr];
  241. double MSE2SSE = s->group_size * s->block_size * s->block_size * src_range * src_range / (s->max * s->max);
  242. double distMul = 1. / MSE2SSE;
  243. double th_sse = th_mse * MSE2SSE;
  244. int i, index = sc->nb_match_blocks;
  245. for (i = 0; i < search_size; i++) {
  246. PosCode pos = search_pos[i];
  247. double dist;
  248. dist = s->do_block_ssd(s, &pos, src, src_stride, r_y, r_x);
  249. // Only match similar blocks but not identical blocks
  250. if (dist <= th_sse && dist != 0) {
  251. const double score = dist * distMul;
  252. if (index >= s->group_size && score >= sc->match_blocks[index - 1].score) {
  253. continue;
  254. }
  255. if (index >= s->group_size)
  256. index = s->group_size - 1;
  257. sc->match_blocks[index].score = score;
  258. sc->match_blocks[index].y = pos.y;
  259. sc->match_blocks[index].x = pos.x;
  260. index++;
  261. qsort(sc->match_blocks, index, sizeof(PosPairCode), cmp_scores);
  262. }
  263. }
  264. sc->nb_match_blocks = index;
  265. }
  266. static void block_matching_multi(BM3DContext *s, const uint8_t *ref, int ref_linesize, int y, int x,
  267. int exclude_cur_pos, int plane, int jobnr)
  268. {
  269. SliceContext *sc = &s->slices[jobnr];
  270. const int width = s->planewidth[plane];
  271. const int height = s->planeheight[plane];
  272. const int block_size = s->block_size;
  273. const int step = s->bm_step;
  274. const int range = s->bm_range / step * step;
  275. int l = search_boundary(0, range, step, 0, y, x);
  276. int r = search_boundary(width - block_size, range, step, 0, y, x);
  277. int t = search_boundary(0, range, step, 1, y, x);
  278. int b = search_boundary(height - block_size, range, step, 1, y, x);
  279. int j, i, index = 0;
  280. for (j = t; j <= b; j += step) {
  281. for (i = l; i <= r; i += step) {
  282. PosCode pos;
  283. if (exclude_cur_pos > 0 && j == y && i == x) {
  284. continue;
  285. }
  286. pos.y = j;
  287. pos.x = i;
  288. sc->search_positions[index++] = pos;
  289. }
  290. }
  291. if (exclude_cur_pos == 1) {
  292. sc->match_blocks[0].score = 0;
  293. sc->match_blocks[0].y = y;
  294. sc->match_blocks[0].x = x;
  295. sc->nb_match_blocks = 1;
  296. }
  297. do_block_matching_multi(s, ref, ref_linesize, s->bm_range,
  298. sc->search_positions, index, s->th_mse, y, x, plane, jobnr);
  299. }
  300. static void block_matching(BM3DContext *s, const uint8_t *ref, int ref_linesize,
  301. int j, int i, int plane, int jobnr)
  302. {
  303. SliceContext *sc = &s->slices[jobnr];
  304. if (s->group_size == 1 || s->th_mse <= 0.f) {
  305. sc->match_blocks[0].score = 1;
  306. sc->match_blocks[0].x = i;
  307. sc->match_blocks[0].y = j;
  308. sc->nb_match_blocks = 1;
  309. return;
  310. }
  311. sc->nb_match_blocks = 0;
  312. block_matching_multi(s, ref, ref_linesize, j, i, 1, plane, jobnr);
  313. }
  314. static void get_block_row(const uint8_t *srcp, int src_linesize,
  315. int y, int x, int block_size, float *dst)
  316. {
  317. const uint8_t *src = srcp + y * src_linesize + x;
  318. int j;
  319. for (j = 0; j < block_size; j++) {
  320. dst[j] = src[j];
  321. }
  322. }
  323. static void get_block_row16(const uint8_t *srcp, int src_linesize,
  324. int y, int x, int block_size, float *dst)
  325. {
  326. const uint16_t *src = (uint16_t *)srcp + y * src_linesize / 2 + x;
  327. int j;
  328. for (j = 0; j < block_size; j++) {
  329. dst[j] = src[j];
  330. }
  331. }
  332. static void basic_block_filtering(BM3DContext *s, const uint8_t *src, int src_linesize,
  333. const uint8_t *ref, int ref_linesize,
  334. int y, int x, int plane, int jobnr)
  335. {
  336. SliceContext *sc = &s->slices[jobnr];
  337. const int buffer_linesize = s->block_size * s->block_size;
  338. const int nb_match_blocks = sc->nb_match_blocks;
  339. const int block_size = s->block_size;
  340. const int width = s->planewidth[plane];
  341. const int pgroup_size = s->pgroup_size;
  342. const int group_size = s->group_size;
  343. float *buffer = sc->buffer;
  344. float *bufferh = sc->bufferh;
  345. float *bufferv = sc->bufferv;
  346. float *bufferz = sc->bufferz;
  347. float threshold[4];
  348. float den_weight, num_weight;
  349. int retained = 0;
  350. int i, j, k;
  351. for (k = 0; k < nb_match_blocks; k++) {
  352. const int y = sc->match_blocks[k].y;
  353. const int x = sc->match_blocks[k].x;
  354. for (i = 0; i < block_size; i++) {
  355. s->get_block_row(src, src_linesize, y + i, x, block_size, bufferh + block_size * i);
  356. av_dct_calc(sc->dctf, bufferh + block_size * i);
  357. }
  358. for (i = 0; i < block_size; i++) {
  359. for (j = 0; j < block_size; j++) {
  360. bufferv[i * block_size + j] = bufferh[j * block_size + i];
  361. }
  362. av_dct_calc(sc->dctf, bufferv + i * block_size);
  363. }
  364. for (i = 0; i < block_size; i++) {
  365. memcpy(buffer + k * buffer_linesize + i * block_size,
  366. bufferv + i * block_size, block_size * 4);
  367. }
  368. }
  369. for (i = 0; i < block_size; i++) {
  370. for (j = 0; j < block_size; j++) {
  371. for (k = 0; k < nb_match_blocks; k++)
  372. bufferz[k] = buffer[buffer_linesize * k + i * block_size + j];
  373. if (group_size > 1)
  374. av_dct_calc(sc->gdctf, bufferz);
  375. bufferz += pgroup_size;
  376. }
  377. }
  378. threshold[0] = s->hard_threshold * s->sigma;
  379. threshold[1] = threshold[0] * sqrtf(2.f);
  380. threshold[2] = threshold[0] * 2.f;
  381. threshold[3] = threshold[0] * sqrtf(8.f);
  382. bufferz = sc->bufferz;
  383. for (i = 0; i < block_size; i++) {
  384. for (j = 0; j < block_size; j++) {
  385. for (k = 0; k < nb_match_blocks; k++) {
  386. const float thresh = threshold[(j == 0) + (i == 0) + (k == 0)];
  387. if (bufferz[k] > thresh || bufferz[k] < -thresh) {
  388. retained++;
  389. } else {
  390. bufferz[k] = 0;
  391. }
  392. }
  393. bufferz += pgroup_size;
  394. }
  395. }
  396. bufferz = sc->bufferz;
  397. buffer = sc->buffer;
  398. for (i = 0; i < block_size; i++) {
  399. for (j = 0; j < block_size; j++) {
  400. if (group_size > 1)
  401. av_dct_calc(sc->gdcti, bufferz);
  402. for (k = 0; k < nb_match_blocks; k++) {
  403. buffer[buffer_linesize * k + i * block_size + j] = bufferz[k];
  404. }
  405. bufferz += pgroup_size;
  406. }
  407. }
  408. den_weight = retained < 1 ? 1.f : 1.f / retained;
  409. num_weight = den_weight;
  410. buffer = sc->buffer;
  411. for (k = 0; k < nb_match_blocks; k++) {
  412. float *num = sc->num + y * width + x;
  413. float *den = sc->den + y * width + x;
  414. for (i = 0; i < block_size; i++) {
  415. memcpy(bufferv + i * block_size,
  416. buffer + k * buffer_linesize + i * block_size,
  417. block_size * 4);
  418. }
  419. for (i = 0; i < block_size; i++) {
  420. av_dct_calc(sc->dcti, bufferv + block_size * i);
  421. for (j = 0; j < block_size; j++) {
  422. bufferh[j * block_size + i] = bufferv[i * block_size + j];
  423. }
  424. }
  425. for (i = 0; i < block_size; i++) {
  426. av_dct_calc(sc->dcti, bufferh + block_size * i);
  427. for (j = 0; j < block_size; j++) {
  428. num[j] += bufferh[i * block_size + j] * num_weight;
  429. den[j] += den_weight;
  430. }
  431. num += width;
  432. den += width;
  433. }
  434. }
  435. }
  436. static void final_block_filtering(BM3DContext *s, const uint8_t *src, int src_linesize,
  437. const uint8_t *ref, int ref_linesize,
  438. int y, int x, int plane, int jobnr)
  439. {
  440. SliceContext *sc = &s->slices[jobnr];
  441. const int buffer_linesize = s->block_size * s->block_size;
  442. const int nb_match_blocks = sc->nb_match_blocks;
  443. const int block_size = s->block_size;
  444. const int width = s->planewidth[plane];
  445. const int pgroup_size = s->pgroup_size;
  446. const int group_size = s->group_size;
  447. const float sigma_sqr = s->sigma * s->sigma;
  448. float *buffer = sc->buffer;
  449. float *bufferh = sc->bufferh;
  450. float *bufferv = sc->bufferv;
  451. float *bufferz = sc->bufferz;
  452. float *rbuffer = sc->rbuffer;
  453. float *rbufferh = sc->rbufferh;
  454. float *rbufferv = sc->rbufferv;
  455. float *rbufferz = sc->rbufferz;
  456. float den_weight, num_weight;
  457. float l2_wiener = 0;
  458. int i, j, k;
  459. for (k = 0; k < nb_match_blocks; k++) {
  460. const int y = sc->match_blocks[k].y;
  461. const int x = sc->match_blocks[k].x;
  462. for (i = 0; i < block_size; i++) {
  463. s->get_block_row(src, src_linesize, y + i, x, block_size, bufferh + block_size * i);
  464. s->get_block_row(ref, ref_linesize, y + i, x, block_size, rbufferh + block_size * i);
  465. av_dct_calc(sc->dctf, bufferh + block_size * i);
  466. av_dct_calc(sc->dctf, rbufferh + block_size * i);
  467. }
  468. for (i = 0; i < block_size; i++) {
  469. for (j = 0; j < block_size; j++) {
  470. bufferv[i * block_size + j] = bufferh[j * block_size + i];
  471. rbufferv[i * block_size + j] = rbufferh[j * block_size + i];
  472. }
  473. av_dct_calc(sc->dctf, bufferv + i * block_size);
  474. av_dct_calc(sc->dctf, rbufferv + i * block_size);
  475. }
  476. for (i = 0; i < block_size; i++) {
  477. memcpy(buffer + k * buffer_linesize + i * block_size,
  478. bufferv + i * block_size, block_size * 4);
  479. memcpy(rbuffer + k * buffer_linesize + i * block_size,
  480. rbufferv + i * block_size, block_size * 4);
  481. }
  482. }
  483. for (i = 0; i < block_size; i++) {
  484. for (j = 0; j < block_size; j++) {
  485. for (k = 0; k < nb_match_blocks; k++) {
  486. bufferz[k] = buffer[buffer_linesize * k + i * block_size + j];
  487. rbufferz[k] = rbuffer[buffer_linesize * k + i * block_size + j];
  488. }
  489. if (group_size > 1) {
  490. av_dct_calc(sc->gdctf, bufferz);
  491. av_dct_calc(sc->gdctf, rbufferz);
  492. }
  493. bufferz += pgroup_size;
  494. rbufferz += pgroup_size;
  495. }
  496. }
  497. bufferz = sc->bufferz;
  498. rbufferz = sc->rbufferz;
  499. for (i = 0; i < block_size; i++) {
  500. for (j = 0; j < block_size; j++) {
  501. for (k = 0; k < nb_match_blocks; k++) {
  502. const float ref_sqr = rbufferz[k] * rbufferz[k];
  503. float wiener_coef = ref_sqr / (ref_sqr + sigma_sqr);
  504. if (isnan(wiener_coef))
  505. wiener_coef = 1;
  506. bufferz[k] *= wiener_coef;
  507. l2_wiener += wiener_coef * wiener_coef;
  508. }
  509. bufferz += pgroup_size;
  510. rbufferz += pgroup_size;
  511. }
  512. }
  513. bufferz = sc->bufferz;
  514. buffer = sc->buffer;
  515. for (i = 0; i < block_size; i++) {
  516. for (j = 0; j < block_size; j++) {
  517. if (group_size > 1)
  518. av_dct_calc(sc->gdcti, bufferz);
  519. for (k = 0; k < nb_match_blocks; k++) {
  520. buffer[buffer_linesize * k + i * block_size + j] = bufferz[k];
  521. }
  522. bufferz += pgroup_size;
  523. }
  524. }
  525. l2_wiener = FFMAX(l2_wiener, 1e-15f);
  526. den_weight = 1.f / l2_wiener;
  527. num_weight = den_weight;
  528. for (k = 0; k < nb_match_blocks; k++) {
  529. float *num = sc->num + y * width + x;
  530. float *den = sc->den + y * width + x;
  531. for (i = 0; i < block_size; i++) {
  532. memcpy(bufferv + i * block_size,
  533. buffer + k * buffer_linesize + i * block_size,
  534. block_size * 4);
  535. }
  536. for (i = 0; i < block_size; i++) {
  537. av_dct_calc(sc->dcti, bufferv + block_size * i);
  538. for (j = 0; j < block_size; j++) {
  539. bufferh[j * block_size + i] = bufferv[i * block_size + j];
  540. }
  541. }
  542. for (i = 0; i < block_size; i++) {
  543. av_dct_calc(sc->dcti, bufferh + block_size * i);
  544. for (j = 0; j < block_size; j++) {
  545. num[j] += bufferh[i * block_size + j] * num_weight;
  546. den[j] += den_weight;
  547. }
  548. num += width;
  549. den += width;
  550. }
  551. }
  552. }
  553. static void do_output(BM3DContext *s, uint8_t *dst, int dst_linesize,
  554. int plane, int nb_jobs)
  555. {
  556. const int height = s->planeheight[plane];
  557. const int width = s->planewidth[plane];
  558. int i, j, k;
  559. for (i = 0; i < height; i++) {
  560. for (j = 0; j < width; j++) {
  561. uint8_t *dstp = dst + i * dst_linesize;
  562. float sum_den = 0.f;
  563. float sum_num = 0.f;
  564. for (k = 0; k < nb_jobs; k++) {
  565. SliceContext *sc = &s->slices[k];
  566. float num = sc->num[i * width + j];
  567. float den = sc->den[i * width + j];
  568. sum_num += num;
  569. sum_den += den;
  570. }
  571. dstp[j] = av_clip_uint8(lrintf(sum_num / sum_den));
  572. }
  573. }
  574. }
  575. static void do_output16(BM3DContext *s, uint8_t *dst, int dst_linesize,
  576. int plane, int nb_jobs)
  577. {
  578. const int height = s->planeheight[plane];
  579. const int width = s->planewidth[plane];
  580. const int depth = s->depth;
  581. int i, j, k;
  582. for (i = 0; i < height; i++) {
  583. for (j = 0; j < width; j++) {
  584. uint16_t *dstp = (uint16_t *)dst + i * dst_linesize / 2;
  585. float sum_den = 0.f;
  586. float sum_num = 0.f;
  587. for (k = 0; k < nb_jobs; k++) {
  588. SliceContext *sc = &s->slices[k];
  589. float num = sc->num[i * width + j];
  590. float den = sc->den[i * width + j];
  591. sum_num += num;
  592. sum_den += den;
  593. }
  594. dstp[j] = av_clip_uintp2_c(lrintf(sum_num / sum_den), depth);
  595. }
  596. }
  597. }
  598. static int filter_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
  599. {
  600. BM3DContext *s = ctx->priv;
  601. SliceContext *sc = &s->slices[jobnr];
  602. const int block_step = s->block_step;
  603. ThreadData *td = arg;
  604. const uint8_t *src = td->src;
  605. const uint8_t *ref = td->ref;
  606. const int src_linesize = td->src_linesize;
  607. const int ref_linesize = td->ref_linesize;
  608. const int plane = td->plane;
  609. const int width = s->planewidth[plane];
  610. const int height = s->planeheight[plane];
  611. const int block_pos_bottom = FFMAX(0, height - s->block_size);
  612. const int block_pos_right = FFMAX(0, width - s->block_size);
  613. const int slice_start = (((height + block_step - 1) / block_step) * jobnr / nb_jobs) * block_step;
  614. const int slice_end = (jobnr == nb_jobs - 1) ? block_pos_bottom + block_step :
  615. (((height + block_step - 1) / block_step) * (jobnr + 1) / nb_jobs) * block_step;
  616. int i, j;
  617. memset(sc->num, 0, width * height * sizeof(FFTSample));
  618. memset(sc->den, 0, width * height * sizeof(FFTSample));
  619. for (j = slice_start; j < slice_end; j += block_step) {
  620. if (j > block_pos_bottom) {
  621. j = block_pos_bottom;
  622. }
  623. for (i = 0; i < block_pos_right + block_step; i += block_step) {
  624. if (i > block_pos_right) {
  625. i = block_pos_right;
  626. }
  627. block_matching(s, ref, ref_linesize, j, i, plane, jobnr);
  628. s->block_filtering(s, src, src_linesize,
  629. ref, ref_linesize, j, i, plane, jobnr);
  630. }
  631. }
  632. return 0;
  633. }
  634. static int filter_frame(AVFilterContext *ctx, AVFrame **out, AVFrame *in, AVFrame *ref)
  635. {
  636. BM3DContext *s = ctx->priv;
  637. AVFilterLink *outlink = ctx->outputs[0];
  638. int p;
  639. *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
  640. if (!*out)
  641. return AVERROR(ENOMEM);
  642. av_frame_copy_props(*out, in);
  643. for (p = 0; p < s->nb_planes; p++) {
  644. const int nb_jobs = FFMAX(1, FFMIN(s->nb_threads, s->planeheight[p] / s->block_size));
  645. ThreadData td;
  646. if (!((1 << p) & s->planes) || ctx->is_disabled) {
  647. av_image_copy_plane((*out)->data[p], (*out)->linesize[p],
  648. in->data[p], in->linesize[p],
  649. s->planewidth[p], s->planeheight[p]);
  650. continue;
  651. }
  652. td.src = in->data[p];
  653. td.src_linesize = in->linesize[p];
  654. td.ref = ref->data[p];
  655. td.ref_linesize = ref->linesize[p];
  656. td.plane = p;
  657. ctx->internal->execute(ctx, filter_slice, &td, NULL, nb_jobs);
  658. s->do_output(s, (*out)->data[p], (*out)->linesize[p], p, nb_jobs);
  659. }
  660. return 0;
  661. }
  662. #define SQR(x) ((x) * (x))
  663. static int config_input(AVFilterLink *inlink)
  664. {
  665. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
  666. AVFilterContext *ctx = inlink->dst;
  667. BM3DContext *s = ctx->priv;
  668. int i, group_bits;
  669. s->nb_threads = FFMIN(ff_filter_get_nb_threads(ctx), MAX_NB_THREADS);
  670. s->nb_planes = av_pix_fmt_count_planes(inlink->format);
  671. s->depth = desc->comp[0].depth;
  672. s->max = (1 << s->depth) - 1;
  673. s->planeheight[1] = s->planeheight[2] = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
  674. s->planeheight[0] = s->planeheight[3] = inlink->h;
  675. s->planewidth[1] = s->planewidth[2] = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
  676. s->planewidth[0] = s->planewidth[3] = inlink->w;
  677. for (group_bits = 4; 1 << group_bits < s->group_size; group_bits++);
  678. s->group_bits = group_bits;
  679. s->pgroup_size = 1 << group_bits;
  680. for (i = 0; i < s->nb_threads; i++) {
  681. SliceContext *sc = &s->slices[i];
  682. sc->num = av_calloc(FFALIGN(s->planewidth[0], s->block_size) * FFALIGN(s->planeheight[0], s->block_size), sizeof(FFTSample));
  683. sc->den = av_calloc(FFALIGN(s->planewidth[0], s->block_size) * FFALIGN(s->planeheight[0], s->block_size), sizeof(FFTSample));
  684. if (!sc->num || !sc->den)
  685. return AVERROR(ENOMEM);
  686. sc->dctf = av_dct_init(av_log2(s->block_size), DCT_II);
  687. sc->dcti = av_dct_init(av_log2(s->block_size), DCT_III);
  688. if (!sc->dctf || !sc->dcti)
  689. return AVERROR(ENOMEM);
  690. if (s->group_bits > 1) {
  691. sc->gdctf = av_dct_init(s->group_bits, DCT_II);
  692. sc->gdcti = av_dct_init(s->group_bits, DCT_III);
  693. if (!sc->gdctf || !sc->gdcti)
  694. return AVERROR(ENOMEM);
  695. }
  696. sc->buffer = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->buffer));
  697. sc->bufferz = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->bufferz));
  698. sc->bufferh = av_calloc(s->block_size * s->block_size, sizeof(*sc->bufferh));
  699. sc->bufferv = av_calloc(s->block_size * s->block_size, sizeof(*sc->bufferv));
  700. if (!sc->bufferh || !sc->bufferv || !sc->buffer || !sc->bufferz)
  701. return AVERROR(ENOMEM);
  702. if (s->mode == FINAL) {
  703. sc->rbuffer = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->rbuffer));
  704. sc->rbufferz = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->rbufferz));
  705. sc->rbufferh = av_calloc(s->block_size * s->block_size, sizeof(*sc->rbufferh));
  706. sc->rbufferv = av_calloc(s->block_size * s->block_size, sizeof(*sc->rbufferv));
  707. if (!sc->rbufferh || !sc->rbufferv || !sc->rbuffer || !sc->rbufferz)
  708. return AVERROR(ENOMEM);
  709. }
  710. sc->search_positions = av_calloc(SQR(2 * s->bm_range / s->bm_step + 1), sizeof(*sc->search_positions));
  711. if (!sc->search_positions)
  712. return AVERROR(ENOMEM);
  713. }
  714. s->do_output = do_output;
  715. s->do_block_ssd = do_block_ssd;
  716. s->get_block_row = get_block_row;
  717. if (s->depth > 8) {
  718. s->do_output = do_output16;
  719. s->do_block_ssd = do_block_ssd16;
  720. s->get_block_row = get_block_row16;
  721. }
  722. return 0;
  723. }
  724. static int activate(AVFilterContext *ctx)
  725. {
  726. BM3DContext *s = ctx->priv;
  727. if (!s->ref) {
  728. AVFrame *frame = NULL;
  729. AVFrame *out = NULL;
  730. int ret, status;
  731. int64_t pts;
  732. FF_FILTER_FORWARD_STATUS_BACK(ctx->outputs[0], ctx->inputs[0]);
  733. if ((ret = ff_inlink_consume_frame(ctx->inputs[0], &frame)) > 0) {
  734. ret = filter_frame(ctx, &out, frame, frame);
  735. av_frame_free(&frame);
  736. if (ret < 0)
  737. return ret;
  738. ret = ff_filter_frame(ctx->outputs[0], out);
  739. }
  740. if (ret < 0) {
  741. return ret;
  742. } else if (ff_inlink_acknowledge_status(ctx->inputs[0], &status, &pts)) {
  743. ff_outlink_set_status(ctx->outputs[0], status, pts);
  744. return 0;
  745. } else {
  746. if (ff_outlink_frame_wanted(ctx->outputs[0]))
  747. ff_inlink_request_frame(ctx->inputs[0]);
  748. return 0;
  749. }
  750. } else {
  751. return ff_framesync_activate(&s->fs);
  752. }
  753. }
  754. static int process_frame(FFFrameSync *fs)
  755. {
  756. AVFilterContext *ctx = fs->parent;
  757. BM3DContext *s = fs->opaque;
  758. AVFilterLink *outlink = ctx->outputs[0];
  759. AVFrame *out = NULL, *src, *ref;
  760. int ret;
  761. if ((ret = ff_framesync_get_frame(&s->fs, 0, &src, 0)) < 0 ||
  762. (ret = ff_framesync_get_frame(&s->fs, 1, &ref, 0)) < 0)
  763. return ret;
  764. if ((ret = filter_frame(ctx, &out, src, ref)) < 0)
  765. return ret;
  766. out->pts = av_rescale_q(src->pts, s->fs.time_base, outlink->time_base);
  767. return ff_filter_frame(outlink, out);
  768. }
  769. static av_cold int init(AVFilterContext *ctx)
  770. {
  771. BM3DContext *s = ctx->priv;
  772. AVFilterPad pad = { 0 };
  773. int ret;
  774. if (s->mode == BASIC) {
  775. if (s->th_mse == 0.f)
  776. s->th_mse = 400.f + s->sigma * 80.f;
  777. s->block_filtering = basic_block_filtering;
  778. } else if (s->mode == FINAL) {
  779. if (!s->ref) {
  780. av_log(ctx, AV_LOG_WARNING, "Reference stream is mandatory in final estimation mode.\n");
  781. s->ref = 1;
  782. }
  783. if (s->th_mse == 0.f)
  784. s->th_mse = 200.f + s->sigma * 10.f;
  785. s->block_filtering = final_block_filtering;
  786. } else {
  787. return AVERROR_BUG;
  788. }
  789. s->block_size = 1 << s->block_size;
  790. if (s->block_step > s->block_size) {
  791. av_log(ctx, AV_LOG_WARNING, "bstep: %d can't be bigger than block size. Changing to %d.\n",
  792. s->block_step, s->block_size);
  793. s->block_step = s->block_size;
  794. }
  795. if (s->bm_step > s->bm_range) {
  796. av_log(ctx, AV_LOG_WARNING, "mstep: %d can't be bigger than block matching range. Changing to %d.\n",
  797. s->bm_step, s->bm_range);
  798. s->bm_step = s->bm_range;
  799. }
  800. pad.type = AVMEDIA_TYPE_VIDEO;
  801. pad.name = av_strdup("source");
  802. pad.config_props = config_input;
  803. if (!pad.name)
  804. return AVERROR(ENOMEM);
  805. if ((ret = ff_insert_inpad(ctx, 0, &pad)) < 0) {
  806. av_freep(&pad.name);
  807. return ret;
  808. }
  809. if (s->ref) {
  810. pad.type = AVMEDIA_TYPE_VIDEO;
  811. pad.name = av_strdup("reference");
  812. pad.config_props = NULL;
  813. if (!pad.name)
  814. return AVERROR(ENOMEM);
  815. if ((ret = ff_insert_inpad(ctx, 1, &pad)) < 0) {
  816. av_freep(&pad.name);
  817. return ret;
  818. }
  819. }
  820. return 0;
  821. }
  822. static int config_output(AVFilterLink *outlink)
  823. {
  824. AVFilterContext *ctx = outlink->src;
  825. BM3DContext *s = ctx->priv;
  826. AVFilterLink *src = ctx->inputs[0];
  827. AVFilterLink *ref;
  828. FFFrameSyncIn *in;
  829. int ret;
  830. if (s->ref) {
  831. ref = ctx->inputs[1];
  832. if (src->format != ref->format) {
  833. av_log(ctx, AV_LOG_ERROR, "inputs must be of same pixel format\n");
  834. return AVERROR(EINVAL);
  835. }
  836. if (src->w != ref->w ||
  837. src->h != ref->h) {
  838. av_log(ctx, AV_LOG_ERROR, "First input link %s parameters "
  839. "(size %dx%d) do not match the corresponding "
  840. "second input link %s parameters (%dx%d) ",
  841. ctx->input_pads[0].name, src->w, src->h,
  842. ctx->input_pads[1].name, ref->w, ref->h);
  843. return AVERROR(EINVAL);
  844. }
  845. }
  846. outlink->w = src->w;
  847. outlink->h = src->h;
  848. outlink->time_base = src->time_base;
  849. outlink->sample_aspect_ratio = src->sample_aspect_ratio;
  850. outlink->frame_rate = src->frame_rate;
  851. if (!s->ref)
  852. return 0;
  853. if ((ret = ff_framesync_init(&s->fs, ctx, 2)) < 0)
  854. return ret;
  855. in = s->fs.in;
  856. in[0].time_base = src->time_base;
  857. in[1].time_base = ref->time_base;
  858. in[0].sync = 1;
  859. in[0].before = EXT_STOP;
  860. in[0].after = EXT_STOP;
  861. in[1].sync = 1;
  862. in[1].before = EXT_STOP;
  863. in[1].after = EXT_STOP;
  864. s->fs.opaque = s;
  865. s->fs.on_event = process_frame;
  866. return ff_framesync_configure(&s->fs);
  867. }
  868. static av_cold void uninit(AVFilterContext *ctx)
  869. {
  870. BM3DContext *s = ctx->priv;
  871. int i;
  872. for (i = 0; i < ctx->nb_inputs; i++)
  873. av_freep(&ctx->input_pads[i].name);
  874. if (s->ref)
  875. ff_framesync_uninit(&s->fs);
  876. for (i = 0; i < s->nb_threads; i++) {
  877. SliceContext *sc = &s->slices[i];
  878. av_freep(&sc->num);
  879. av_freep(&sc->den);
  880. av_dct_end(sc->gdctf);
  881. av_dct_end(sc->gdcti);
  882. av_dct_end(sc->dctf);
  883. av_dct_end(sc->dcti);
  884. av_freep(&sc->buffer);
  885. av_freep(&sc->bufferh);
  886. av_freep(&sc->bufferv);
  887. av_freep(&sc->bufferz);
  888. av_freep(&sc->rbuffer);
  889. av_freep(&sc->rbufferh);
  890. av_freep(&sc->rbufferv);
  891. av_freep(&sc->rbufferz);
  892. av_freep(&sc->search_positions);
  893. }
  894. }
  895. static const AVFilterPad bm3d_outputs[] = {
  896. {
  897. .name = "default",
  898. .type = AVMEDIA_TYPE_VIDEO,
  899. .config_props = config_output,
  900. },
  901. { NULL }
  902. };
  903. AVFilter ff_vf_bm3d = {
  904. .name = "bm3d",
  905. .description = NULL_IF_CONFIG_SMALL("Block-Matching 3D denoiser."),
  906. .priv_size = sizeof(BM3DContext),
  907. .init = init,
  908. .uninit = uninit,
  909. .activate = activate,
  910. .query_formats = query_formats,
  911. .inputs = NULL,
  912. .outputs = bm3d_outputs,
  913. .priv_class = &bm3d_class,
  914. .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL |
  915. AVFILTER_FLAG_DYNAMIC_INPUTS |
  916. AVFILTER_FLAG_SLICE_THREADS,
  917. };