vf_bm3d.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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,
  150. AV_PIX_FMT_GRAY9, AV_PIX_FMT_GRAY10,
  151. AV_PIX_FMT_GRAY12, AV_PIX_FMT_GRAY16,
  152. AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
  153. AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
  154. AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
  155. AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
  156. AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P,
  157. AV_PIX_FMT_YUVJ411P,
  158. AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV422P9, AV_PIX_FMT_YUV444P9,
  159. AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
  160. AV_PIX_FMT_YUV440P10,
  161. AV_PIX_FMT_YUV444P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV420P12,
  162. AV_PIX_FMT_YUV440P12,
  163. AV_PIX_FMT_YUV444P14, AV_PIX_FMT_YUV422P14, AV_PIX_FMT_YUV420P14,
  164. AV_PIX_FMT_YUV420P16, AV_PIX_FMT_YUV422P16, AV_PIX_FMT_YUV444P16,
  165. AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10,
  166. AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
  167. AV_PIX_FMT_NONE
  168. };
  169. AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
  170. if (!fmts_list)
  171. return AVERROR(ENOMEM);
  172. return ff_set_common_formats(ctx, fmts_list);
  173. }
  174. static int do_search_boundary(int pos, int plane_boundary, int search_range, int search_step)
  175. {
  176. int search_boundary;
  177. search_range = search_range / search_step * search_step;
  178. if (pos == plane_boundary) {
  179. search_boundary = plane_boundary;
  180. } else if (pos > plane_boundary) {
  181. search_boundary = pos - search_range;
  182. while (search_boundary < plane_boundary) {
  183. search_boundary += search_step;
  184. }
  185. } else {
  186. search_boundary = pos + search_range;
  187. while (search_boundary > plane_boundary) {
  188. search_boundary -= search_step;
  189. }
  190. }
  191. return search_boundary;
  192. }
  193. static int search_boundary(int plane_boundary, int search_range, int search_step, int vertical, int y, int x)
  194. {
  195. return do_search_boundary(vertical ? y : x, plane_boundary, search_range, search_step);
  196. }
  197. static int cmp_scores(const void *a, const void *b)
  198. {
  199. const struct PosPairCode *pair1 = a;
  200. const struct PosPairCode *pair2 = b;
  201. return FFDIFFSIGN(pair1->score, pair2->score);
  202. }
  203. static double do_block_ssd(BM3DContext *s, PosCode *pos, const uint8_t *src, int src_stride, int r_y, int r_x)
  204. {
  205. const uint8_t *srcp = src + pos->y * src_stride + pos->x;
  206. const uint8_t *refp = src + r_y * src_stride + r_x;
  207. const int block_size = s->block_size;
  208. double dist = 0.;
  209. int x, y;
  210. for (y = 0; y < block_size; y++) {
  211. for (x = 0; x < block_size; x++) {
  212. double temp = refp[x] - srcp[x];
  213. dist += temp * temp;
  214. }
  215. srcp += src_stride;
  216. refp += src_stride;
  217. }
  218. return dist;
  219. }
  220. static double do_block_ssd16(BM3DContext *s, PosCode *pos, const uint8_t *src, int src_stride, int r_y, int r_x)
  221. {
  222. const uint16_t *srcp = (uint16_t *)src + pos->y * src_stride / 2 + pos->x;
  223. const uint16_t *refp = (uint16_t *)src + r_y * src_stride / 2 + r_x;
  224. const int block_size = s->block_size;
  225. double dist = 0.;
  226. int x, y;
  227. for (y = 0; y < block_size; y++) {
  228. for (x = 0; x < block_size; x++) {
  229. double temp = refp[x] - srcp[x];
  230. dist += temp * temp;
  231. }
  232. srcp += src_stride / 2;
  233. refp += src_stride / 2;
  234. }
  235. return dist;
  236. }
  237. static void do_block_matching_multi(BM3DContext *s, const uint8_t *src, int src_stride, int src_range,
  238. const PosCode *search_pos, int search_size, float th_mse,
  239. int r_y, int r_x, int plane, int jobnr)
  240. {
  241. SliceContext *sc = &s->slices[jobnr];
  242. double MSE2SSE = s->group_size * s->block_size * s->block_size * src_range * src_range / (s->max * s->max);
  243. double distMul = 1. / MSE2SSE;
  244. double th_sse = th_mse * MSE2SSE;
  245. int i, index = sc->nb_match_blocks;
  246. for (i = 0; i < search_size; i++) {
  247. PosCode pos = search_pos[i];
  248. double dist;
  249. dist = s->do_block_ssd(s, &pos, src, src_stride, r_y, r_x);
  250. // Only match similar blocks but not identical blocks
  251. if (dist <= th_sse && dist != 0) {
  252. const double score = dist * distMul;
  253. if (index >= s->group_size && score >= sc->match_blocks[index - 1].score) {
  254. continue;
  255. }
  256. if (index >= s->group_size)
  257. index = s->group_size - 1;
  258. sc->match_blocks[index].score = score;
  259. sc->match_blocks[index].y = pos.y;
  260. sc->match_blocks[index].x = pos.x;
  261. index++;
  262. qsort(sc->match_blocks, index, sizeof(PosPairCode), cmp_scores);
  263. }
  264. }
  265. sc->nb_match_blocks = index;
  266. }
  267. static void block_matching_multi(BM3DContext *s, const uint8_t *ref, int ref_linesize, int y, int x,
  268. int exclude_cur_pos, int plane, int jobnr)
  269. {
  270. SliceContext *sc = &s->slices[jobnr];
  271. const int width = s->planewidth[plane];
  272. const int height = s->planeheight[plane];
  273. const int block_size = s->block_size;
  274. const int step = s->bm_step;
  275. const int range = s->bm_range / step * step;
  276. int l = search_boundary(0, range, step, 0, y, x);
  277. int r = search_boundary(width - block_size, range, step, 0, y, x);
  278. int t = search_boundary(0, range, step, 1, y, x);
  279. int b = search_boundary(height - block_size, range, step, 1, y, x);
  280. int j, i, index = 0;
  281. for (j = t; j <= b; j += step) {
  282. for (i = l; i <= r; i += step) {
  283. PosCode pos;
  284. if (exclude_cur_pos > 0 && j == y && i == x) {
  285. continue;
  286. }
  287. pos.y = j;
  288. pos.x = i;
  289. sc->search_positions[index++] = pos;
  290. }
  291. }
  292. if (exclude_cur_pos == 1) {
  293. sc->match_blocks[0].score = 0;
  294. sc->match_blocks[0].y = y;
  295. sc->match_blocks[0].x = x;
  296. sc->nb_match_blocks = 1;
  297. }
  298. do_block_matching_multi(s, ref, ref_linesize, s->bm_range,
  299. sc->search_positions, index, s->th_mse, y, x, plane, jobnr);
  300. }
  301. static void block_matching(BM3DContext *s, const uint8_t *ref, int ref_linesize,
  302. int j, int i, int plane, int jobnr)
  303. {
  304. SliceContext *sc = &s->slices[jobnr];
  305. if (s->group_size == 1 || s->th_mse <= 0.f) {
  306. sc->match_blocks[0].score = 1;
  307. sc->match_blocks[0].x = i;
  308. sc->match_blocks[0].y = j;
  309. sc->nb_match_blocks = 1;
  310. return;
  311. }
  312. sc->nb_match_blocks = 0;
  313. block_matching_multi(s, ref, ref_linesize, j, i, 1, plane, jobnr);
  314. }
  315. static void get_block_row(const uint8_t *srcp, int src_linesize,
  316. int y, int x, int block_size, float *dst)
  317. {
  318. const uint8_t *src = srcp + y * src_linesize + x;
  319. int j;
  320. for (j = 0; j < block_size; j++) {
  321. dst[j] = src[j];
  322. }
  323. }
  324. static void get_block_row16(const uint8_t *srcp, int src_linesize,
  325. int y, int x, int block_size, float *dst)
  326. {
  327. const uint16_t *src = (uint16_t *)srcp + y * src_linesize / 2 + x;
  328. int j;
  329. for (j = 0; j < block_size; j++) {
  330. dst[j] = src[j];
  331. }
  332. }
  333. static void basic_block_filtering(BM3DContext *s, const uint8_t *src, int src_linesize,
  334. const uint8_t *ref, int ref_linesize,
  335. int y, int x, int plane, int jobnr)
  336. {
  337. SliceContext *sc = &s->slices[jobnr];
  338. const int buffer_linesize = s->block_size * s->block_size;
  339. const int nb_match_blocks = sc->nb_match_blocks;
  340. const int block_size = s->block_size;
  341. const int width = s->planewidth[plane];
  342. const int pgroup_size = s->pgroup_size;
  343. const int group_size = s->group_size;
  344. float *buffer = sc->buffer;
  345. float *bufferh = sc->bufferh;
  346. float *bufferv = sc->bufferv;
  347. float *bufferz = sc->bufferz;
  348. float threshold[4];
  349. float den_weight, num_weight;
  350. int retained = 0;
  351. int i, j, k;
  352. for (k = 0; k < nb_match_blocks; k++) {
  353. const int y = sc->match_blocks[k].y;
  354. const int x = sc->match_blocks[k].x;
  355. for (i = 0; i < block_size; i++) {
  356. s->get_block_row(src, src_linesize, y + i, x, block_size, bufferh + block_size * i);
  357. av_dct_calc(sc->dctf, bufferh + block_size * i);
  358. }
  359. for (i = 0; i < block_size; i++) {
  360. for (j = 0; j < block_size; j++) {
  361. bufferv[i * block_size + j] = bufferh[j * block_size + i];
  362. }
  363. av_dct_calc(sc->dctf, bufferv + i * block_size);
  364. }
  365. for (i = 0; i < block_size; i++) {
  366. memcpy(buffer + k * buffer_linesize + i * block_size,
  367. bufferv + i * block_size, block_size * 4);
  368. }
  369. }
  370. for (i = 0; i < block_size; i++) {
  371. for (j = 0; j < block_size; j++) {
  372. for (k = 0; k < nb_match_blocks; k++)
  373. bufferz[k] = buffer[buffer_linesize * k + i * block_size + j];
  374. if (group_size > 1)
  375. av_dct_calc(sc->gdctf, bufferz);
  376. bufferz += pgroup_size;
  377. }
  378. }
  379. threshold[0] = s->hard_threshold * s->sigma;
  380. threshold[1] = threshold[0] * sqrtf(2.f);
  381. threshold[2] = threshold[0] * 2.f;
  382. threshold[3] = threshold[0] * sqrtf(8.f);
  383. bufferz = sc->bufferz;
  384. for (i = 0; i < block_size; i++) {
  385. for (j = 0; j < block_size; j++) {
  386. for (k = 0; k < nb_match_blocks; k++) {
  387. const float thresh = threshold[(j == 0) + (i == 0) + (k == 0)];
  388. if (bufferz[k] > thresh || bufferz[k] < -thresh) {
  389. retained++;
  390. } else {
  391. bufferz[k] = 0;
  392. }
  393. }
  394. bufferz += pgroup_size;
  395. }
  396. }
  397. bufferz = sc->bufferz;
  398. buffer = sc->buffer;
  399. for (i = 0; i < block_size; i++) {
  400. for (j = 0; j < block_size; j++) {
  401. if (group_size > 1)
  402. av_dct_calc(sc->gdcti, bufferz);
  403. for (k = 0; k < nb_match_blocks; k++) {
  404. buffer[buffer_linesize * k + i * block_size + j] = bufferz[k];
  405. }
  406. bufferz += pgroup_size;
  407. }
  408. }
  409. den_weight = retained < 1 ? 1.f : 1.f / retained;
  410. num_weight = den_weight;
  411. buffer = sc->buffer;
  412. for (k = 0; k < nb_match_blocks; k++) {
  413. float *num = sc->num + y * width + x;
  414. float *den = sc->den + y * width + x;
  415. for (i = 0; i < block_size; i++) {
  416. memcpy(bufferv + i * block_size,
  417. buffer + k * buffer_linesize + i * block_size,
  418. block_size * 4);
  419. }
  420. for (i = 0; i < block_size; i++) {
  421. av_dct_calc(sc->dcti, bufferv + block_size * i);
  422. for (j = 0; j < block_size; j++) {
  423. bufferh[j * block_size + i] = bufferv[i * block_size + j];
  424. }
  425. }
  426. for (i = 0; i < block_size; i++) {
  427. av_dct_calc(sc->dcti, bufferh + block_size * i);
  428. for (j = 0; j < block_size; j++) {
  429. num[j] += bufferh[i * block_size + j] * num_weight;
  430. den[j] += den_weight;
  431. }
  432. num += width;
  433. den += width;
  434. }
  435. }
  436. }
  437. static void final_block_filtering(BM3DContext *s, const uint8_t *src, int src_linesize,
  438. const uint8_t *ref, int ref_linesize,
  439. int y, int x, int plane, int jobnr)
  440. {
  441. SliceContext *sc = &s->slices[jobnr];
  442. const int buffer_linesize = s->block_size * s->block_size;
  443. const int nb_match_blocks = sc->nb_match_blocks;
  444. const int block_size = s->block_size;
  445. const int width = s->planewidth[plane];
  446. const int pgroup_size = s->pgroup_size;
  447. const int group_size = s->group_size;
  448. const float sigma_sqr = s->sigma * s->sigma;
  449. float *buffer = sc->buffer;
  450. float *bufferh = sc->bufferh;
  451. float *bufferv = sc->bufferv;
  452. float *bufferz = sc->bufferz;
  453. float *rbuffer = sc->rbuffer;
  454. float *rbufferh = sc->rbufferh;
  455. float *rbufferv = sc->rbufferv;
  456. float *rbufferz = sc->rbufferz;
  457. float den_weight, num_weight;
  458. float l2_wiener = 0;
  459. int i, j, k;
  460. for (k = 0; k < nb_match_blocks; k++) {
  461. const int y = sc->match_blocks[k].y;
  462. const int x = sc->match_blocks[k].x;
  463. for (i = 0; i < block_size; i++) {
  464. s->get_block_row(src, src_linesize, y + i, x, block_size, bufferh + block_size * i);
  465. s->get_block_row(ref, ref_linesize, y + i, x, block_size, rbufferh + block_size * i);
  466. av_dct_calc(sc->dctf, bufferh + block_size * i);
  467. av_dct_calc(sc->dctf, rbufferh + block_size * i);
  468. }
  469. for (i = 0; i < block_size; i++) {
  470. for (j = 0; j < block_size; j++) {
  471. bufferv[i * block_size + j] = bufferh[j * block_size + i];
  472. rbufferv[i * block_size + j] = rbufferh[j * block_size + i];
  473. }
  474. av_dct_calc(sc->dctf, bufferv + i * block_size);
  475. av_dct_calc(sc->dctf, rbufferv + i * block_size);
  476. }
  477. for (i = 0; i < block_size; i++) {
  478. memcpy(buffer + k * buffer_linesize + i * block_size,
  479. bufferv + i * block_size, block_size * 4);
  480. memcpy(rbuffer + k * buffer_linesize + i * block_size,
  481. rbufferv + i * block_size, block_size * 4);
  482. }
  483. }
  484. for (i = 0; i < block_size; i++) {
  485. for (j = 0; j < block_size; j++) {
  486. for (k = 0; k < nb_match_blocks; k++) {
  487. bufferz[k] = buffer[buffer_linesize * k + i * block_size + j];
  488. rbufferz[k] = rbuffer[buffer_linesize * k + i * block_size + j];
  489. }
  490. if (group_size > 1) {
  491. av_dct_calc(sc->gdctf, bufferz);
  492. av_dct_calc(sc->gdctf, rbufferz);
  493. }
  494. bufferz += pgroup_size;
  495. rbufferz += pgroup_size;
  496. }
  497. }
  498. bufferz = sc->bufferz;
  499. rbufferz = sc->rbufferz;
  500. for (i = 0; i < block_size; i++) {
  501. for (j = 0; j < block_size; j++) {
  502. for (k = 0; k < nb_match_blocks; k++) {
  503. const float ref_sqr = rbufferz[k] * rbufferz[k];
  504. float wiener_coef = ref_sqr / (ref_sqr + sigma_sqr);
  505. if (isnan(wiener_coef))
  506. wiener_coef = 1;
  507. bufferz[k] *= wiener_coef;
  508. l2_wiener += wiener_coef * wiener_coef;
  509. }
  510. bufferz += pgroup_size;
  511. rbufferz += pgroup_size;
  512. }
  513. }
  514. bufferz = sc->bufferz;
  515. buffer = sc->buffer;
  516. for (i = 0; i < block_size; i++) {
  517. for (j = 0; j < block_size; j++) {
  518. if (group_size > 1)
  519. av_dct_calc(sc->gdcti, bufferz);
  520. for (k = 0; k < nb_match_blocks; k++) {
  521. buffer[buffer_linesize * k + i * block_size + j] = bufferz[k];
  522. }
  523. bufferz += pgroup_size;
  524. }
  525. }
  526. l2_wiener = FFMAX(l2_wiener, 1e-15f);
  527. den_weight = 1.f / l2_wiener;
  528. num_weight = den_weight;
  529. for (k = 0; k < nb_match_blocks; k++) {
  530. float *num = sc->num + y * width + x;
  531. float *den = sc->den + y * width + x;
  532. for (i = 0; i < block_size; i++) {
  533. memcpy(bufferv + i * block_size,
  534. buffer + k * buffer_linesize + i * block_size,
  535. block_size * 4);
  536. }
  537. for (i = 0; i < block_size; i++) {
  538. av_dct_calc(sc->dcti, bufferv + block_size * i);
  539. for (j = 0; j < block_size; j++) {
  540. bufferh[j * block_size + i] = bufferv[i * block_size + j];
  541. }
  542. }
  543. for (i = 0; i < block_size; i++) {
  544. av_dct_calc(sc->dcti, bufferh + block_size * i);
  545. for (j = 0; j < block_size; j++) {
  546. num[j] += bufferh[i * block_size + j] * num_weight;
  547. den[j] += den_weight;
  548. }
  549. num += width;
  550. den += width;
  551. }
  552. }
  553. }
  554. static void do_output(BM3DContext *s, uint8_t *dst, int dst_linesize,
  555. int plane, int nb_jobs)
  556. {
  557. const int height = s->planeheight[plane];
  558. const int width = s->planewidth[plane];
  559. int i, j, k;
  560. for (i = 0; i < height; i++) {
  561. for (j = 0; j < width; j++) {
  562. uint8_t *dstp = dst + i * dst_linesize;
  563. float sum_den = 0.f;
  564. float sum_num = 0.f;
  565. for (k = 0; k < nb_jobs; k++) {
  566. SliceContext *sc = &s->slices[k];
  567. float num = sc->num[i * width + j];
  568. float den = sc->den[i * width + j];
  569. sum_num += num;
  570. sum_den += den;
  571. }
  572. dstp[j] = av_clip_uint8(sum_num / sum_den);
  573. }
  574. }
  575. }
  576. static void do_output16(BM3DContext *s, uint8_t *dst, int dst_linesize,
  577. int plane, int nb_jobs)
  578. {
  579. const int height = s->planeheight[plane];
  580. const int width = s->planewidth[plane];
  581. const int depth = s->depth;
  582. int i, j, k;
  583. for (i = 0; i < height; i++) {
  584. for (j = 0; j < width; j++) {
  585. uint16_t *dstp = (uint16_t *)dst + i * dst_linesize / 2;
  586. float sum_den = 0.f;
  587. float sum_num = 0.f;
  588. for (k = 0; k < nb_jobs; k++) {
  589. SliceContext *sc = &s->slices[k];
  590. float num = sc->num[i * width + j];
  591. float den = sc->den[i * width + j];
  592. sum_num += num;
  593. sum_den += den;
  594. }
  595. dstp[j] = av_clip_uintp2_c(sum_num / sum_den, depth);
  596. }
  597. }
  598. }
  599. static int filter_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
  600. {
  601. BM3DContext *s = ctx->priv;
  602. SliceContext *sc = &s->slices[jobnr];
  603. const int block_step = s->block_step;
  604. ThreadData *td = arg;
  605. const uint8_t *src = td->src;
  606. const uint8_t *ref = td->ref;
  607. const int src_linesize = td->src_linesize;
  608. const int ref_linesize = td->ref_linesize;
  609. const int plane = td->plane;
  610. const int width = s->planewidth[plane];
  611. const int height = s->planeheight[plane];
  612. const int block_pos_bottom = height - s->block_size;
  613. const int block_pos_right = width - s->block_size;
  614. const int slice_start = (((height + block_step - 1) / block_step) * jobnr / nb_jobs) * block_step;
  615. const int slice_end = (jobnr == nb_jobs - 1) ? block_pos_bottom + block_step :
  616. (((height + block_step - 1) / block_step) * (jobnr + 1) / nb_jobs) * block_step;
  617. int i, j;
  618. memset(sc->num, 0, width * height * sizeof(FFTSample));
  619. memset(sc->den, 0, width * height * sizeof(FFTSample));
  620. for (j = slice_start; j < slice_end; j += block_step) {
  621. if (j > block_pos_bottom) {
  622. j = block_pos_bottom;
  623. }
  624. for (i = 0; i < block_pos_right + block_step; i += block_step) {
  625. if (i > block_pos_right) {
  626. i = block_pos_right;
  627. }
  628. block_matching(s, ref, ref_linesize, j, i, plane, jobnr);
  629. s->block_filtering(s, src, src_linesize,
  630. ref, ref_linesize, j, i, plane, jobnr);
  631. }
  632. }
  633. return 0;
  634. }
  635. static int filter_frame(AVFilterContext *ctx, AVFrame **out, AVFrame *in, AVFrame *ref)
  636. {
  637. BM3DContext *s = ctx->priv;
  638. AVFilterLink *outlink = ctx->outputs[0];
  639. int p;
  640. *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
  641. if (!*out)
  642. return AVERROR(ENOMEM);
  643. av_frame_copy_props(*out, in);
  644. for (p = 0; p < s->nb_planes; p++) {
  645. const int nb_jobs = FFMIN(s->nb_threads, s->planeheight[p] / s->block_step);
  646. ThreadData td;
  647. if (!((1 << p) & s->planes) || ctx->is_disabled) {
  648. av_image_copy_plane((*out)->data[p], (*out)->linesize[p],
  649. in->data[p], in->linesize[p],
  650. s->planewidth[p], s->planeheight[p]);
  651. continue;
  652. }
  653. td.src = in->data[p];
  654. td.src_linesize = in->linesize[p];
  655. td.ref = ref->data[p];
  656. td.ref_linesize = ref->linesize[p];
  657. td.plane = p;
  658. ctx->internal->execute(ctx, filter_slice, &td, NULL, nb_jobs);
  659. s->do_output(s, (*out)->data[p], (*out)->linesize[p], p, nb_jobs);
  660. }
  661. return 0;
  662. }
  663. #define SQR(x) ((x) * (x))
  664. static int config_input(AVFilterLink *inlink)
  665. {
  666. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
  667. AVFilterContext *ctx = inlink->dst;
  668. BM3DContext *s = ctx->priv;
  669. int i, group_bits;
  670. s->nb_threads = FFMIN(ff_filter_get_nb_threads(ctx), MAX_NB_THREADS);
  671. s->nb_planes = av_pix_fmt_count_planes(inlink->format);
  672. s->depth = desc->comp[0].depth;
  673. s->max = (1 << s->depth) - 1;
  674. s->planeheight[1] = s->planeheight[2] = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
  675. s->planeheight[0] = s->planeheight[3] = inlink->h;
  676. s->planewidth[1] = s->planewidth[2] = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
  677. s->planewidth[0] = s->planewidth[3] = inlink->w;
  678. for (group_bits = 4; 1 << group_bits < s->group_size; group_bits++);
  679. s->group_bits = group_bits;
  680. s->pgroup_size = 1 << group_bits;
  681. for (i = 0; i < s->nb_threads; i++) {
  682. SliceContext *sc = &s->slices[i];
  683. sc->num = av_calloc(s->planewidth[0] * s->planeheight[0], sizeof(FFTSample));
  684. sc->den = av_calloc(s->planewidth[0] * s->planeheight[0], sizeof(FFTSample));
  685. if (!sc->num || !sc->den)
  686. return AVERROR(ENOMEM);
  687. sc->dctf = av_dct_init(av_log2(s->block_size), DCT_II);
  688. sc->dcti = av_dct_init(av_log2(s->block_size), DCT_III);
  689. if (!sc->dctf || !sc->dcti)
  690. return AVERROR(ENOMEM);
  691. if (s->group_bits > 1) {
  692. sc->gdctf = av_dct_init(s->group_bits, DCT_II);
  693. sc->gdcti = av_dct_init(s->group_bits, DCT_III);
  694. if (!sc->gdctf || !sc->gdcti)
  695. return AVERROR(ENOMEM);
  696. }
  697. sc->buffer = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->buffer));
  698. sc->bufferz = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->bufferz));
  699. sc->bufferh = av_calloc(s->block_size * s->block_size, sizeof(*sc->bufferh));
  700. sc->bufferv = av_calloc(s->block_size * s->block_size, sizeof(*sc->bufferv));
  701. if (!sc->bufferh || !sc->bufferv || !sc->buffer || !sc->bufferz)
  702. return AVERROR(ENOMEM);
  703. if (s->mode == FINAL) {
  704. sc->rbuffer = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->rbuffer));
  705. sc->rbufferz = av_calloc(s->block_size * s->block_size * s->pgroup_size, sizeof(*sc->rbufferz));
  706. sc->rbufferh = av_calloc(s->block_size * s->block_size, sizeof(*sc->rbufferh));
  707. sc->rbufferv = av_calloc(s->block_size * s->block_size, sizeof(*sc->rbufferv));
  708. if (!sc->rbufferh || !sc->rbufferv || !sc->rbuffer || !sc->rbufferz)
  709. return AVERROR(ENOMEM);
  710. }
  711. sc->search_positions = av_calloc(SQR(2 * s->bm_range / s->bm_step + 1), sizeof(*sc->search_positions));
  712. if (!sc->search_positions)
  713. return AVERROR(ENOMEM);
  714. }
  715. s->do_output = do_output;
  716. s->do_block_ssd = do_block_ssd;
  717. s->get_block_row = get_block_row;
  718. if (s->depth > 8) {
  719. s->do_output = do_output16;
  720. s->do_block_ssd = do_block_ssd16;
  721. s->get_block_row = get_block_row16;
  722. }
  723. return 0;
  724. }
  725. static int activate(AVFilterContext *ctx)
  726. {
  727. BM3DContext *s = ctx->priv;
  728. if (!s->ref) {
  729. AVFrame *frame = NULL;
  730. AVFrame *out = NULL;
  731. int ret, status;
  732. int64_t pts;
  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. };