Files
opencv-MIRROR/modules/core/src/dxt.hpp
Vadim Pisarevsky a30d2be6ea Merge pull request #30618 from vpisarev:dft_opt
Further FFT/DFT/DCT optimizations - #30618

Merge together with https://github.com/opencv/opencv_extra/pull/1456

### Summary

Follow-up to #30061 and relates to #30467. It fixes the 64F 1D regressions measured on x86 after that PR, removes the O(r²) memory of the big prime radix, adds radix-8 stages, and makes the twiddle tables ~1 ulp accurate. Everything below was measured without IPP (`WITH_IPP=OFF`), so the numbers compare the OpenCV code paths only; the IPP logic is not touched.

Four commits, each self-contained:

1. **Memory, plan overhead, vectorization** (784be814b2)
   - Root cause of the x86 1D regressions: `cv::dft()` builds a plan per call, and at n = 65536 the engine allocated three MB-sized blocks per call (twiddles, permutation, workspace). glibc trims the heap after every free (its dynamic trim threshold is 2x the largest freed block), so every call page-faulted the buffers again: 65536 64FC2 ran at 620 us, ~215 us of it outside the transform. Fix: tables, permutation and the owner's workspace are **one allocation** per plan. No memory is retained between calls, no plan cache.
   - Static, lazily built tables for power-of-two lengths nc ≤ 1024 (stage twiddles, digit-reversal, real-FFT twiddles): plan building for 256..2048 points is table lookups only (0.06 us).
   - Generic odd radix: `cs/sn` tables of r entries with a cyclic index instead of h×h (h = (r−1)/2). n = 4093 in double: peak RSS 72.6 MB → 7.7 MB.
   - `DFT_STAGE_SIMD128`: stages with span shorter than the full vector but ≥ 128 bits run on `v_float32x4`/`v_float64x2` instead of scalar code (span 4 on AVX2 floats, i.e. every 4^k length).
   - Fused twiddle-free first stage of radix 3 and 5 for odd lengths (e.g. 4725), fused last radix-4 stage writing the interleaved scaled output, depth-first chunking of the leading stages for long transforms.
2. **`AutoBuffer` alignment** (02c6f39c82): `alignas(max(alignof(_Tp), 8))` on the local storage, so `AutoBuffer<uchar>` used as raw storage for double/int64 data is 8-byte aligned on every platform (it was only 4-byte aligned on 32-bit targets).
3. **Radix-8 stages and cache-set padding** (c7bf418d06): the power-of-two part is factored as r0·8^a·4^b (256: 2 middle stages instead of 3, 4096: 3 instead of 5, 65536: 5 instead of 7). The butterfly follows FFTW's `t1fv_8` (odd legs first, W8 rotations folded into the outputs with FMAs). The real reason an earlier radix-8 attempt was slower turned out to be **4K aliasing**: with a span of a 4 KB multiple, the data legs, the twiddle leg tables and the re/im arrays of one butterfly all map to one L1 set. One cache line of padding between the twiddle legs and between re and im gives 1.3–1.4x at n ≥ 16384 on its own; radix-8 adds 1.1–1.4x on top for complex transforms.
4. **Accurate twiddle generation** (2831df79c8): the tables were built by rotation recurrences and chained leg products and were 12–27 ulps off in double. Now every entry is one product of exactly computed seeds (Cephes sin/cos polynomials on an integer-reduced octant, ~0.5 ulp), computed in double, vectorized and rounded once. The real-FFT twiddles are stored as one table (`rtw_im = rtw_re + nc/2`).

Also: `perf_dft.cpp` gains 256x256 and 512x512 2D sizes (matchTemplate / filter2D tile sizes); `test_dxt.cpp` sweep gains prime and 2·prime lengths (257, 1009, 2018).

### Performance vs 5.x head (c4f7634256)

Environment: Intel Core Ultra 7 255H, Ubuntu 26.04, GCC 15.2, Release, default `CPU_BASELINE`/`CPU_DISPATCH` (AVX2 kernels are dispatched), `WITH_IPP=OFF`. Each binary was run twice and the minimum per case taken; the tables show the speedup `t(5.x) / t(PR)` as geomean over the flags (and row/column for 1D). Everything single-threaded unless stated.

**1D DFT (`dft1d`)**

|  | 32FC1 | 64FC1 | 32FC2 | 64FC2 |
|---|---|---|---|---|
| 256 | 2.11 | 1.84 | 2.25 | 1.73 |
| 1000 | 1.39 | 1.17 | 0.99 | 1.04 |
| 1024 | 2.62 | 2.07 | 2.49 | 1.68 |
| 4096 | 1.38 | 1.36 | 1.58 | 1.44 |
| 4725 | 1.81 | 1.71 | 1.86 | 1.72 |
| 65536 | 1.79 | 1.55 | 2.05 | 1.38 |

geomean 1.66 over 192 cases, min 0.98.

**1D DCT (`dct1d`)**

|  | 32FC1 | 64FC1 |
|---|---|---|
| 256 | 1.65 | 1.51 |
| 1000 | 1.50 | 1.22 |
| 1024 | 1.96 | 1.63 |
| 4096 | 1.52 | 1.37 |
| 65536 | 1.82 | 1.29 |

**2D DFT, 1 thread** (geomean over flags; `DFT_ROWS` cases in the second group)

|  | 32FC1 | 64FC1 | 32FC2 | | ROWS 32FC1 | ROWS 64FC1 | ROWS 32FC2 |
|---|---|---|---|---|---|---|---|
| 256x256 | 1.14 | 1.02 | 1.33 | | 0.97 | 0.97 | 1.70 |
| 512x512 | 1.14 | 1.04 | 1.04 | | 1.44 | 1.01 | 1.09 |
| 320x480 | 0.98 | 1.00 | 1.16 | | 0.98 | 1.00 | 1.62 |
| 800x600 | 1.10 | 1.00 | 0.99 | | 1.34 | 0.98 | 1.00 |
| 1280x1024 | 1.12 | 1.02 | 1.26 | | 1.00 | 1.00 | 1.43 |
| 1920x1080 | 1.12 | 1.00 | 0.99 | | 1.39 | 1.03 | 1.00 |
| 2048x2048 | 1.09 | 1.04 | 1.07 | | 1.34 | 0.99 | 1.21 |

2D DCT, 1 thread: 0.99–1.23 (geomean 1.06). With the default number of threads the 2D geomeans are the same (dft 1.07, dct 1.09) but individual cases are noisy on this hybrid-core CPU (0.75–1.76 between runs of the same code).

**imgproc**: matchTemplate 1.00–1.25 per image/template size (geomean 1.07), filter2D 1.00–1.03.

The one case consistently below 0.95 in the 1-thread tables, 2D 256x256 32FC2 `DFT_INVERSE` (0.84), is bimodal (0.11 / 0.19 ms) with both the old and the new library: it depends on the addresses malloc returns for the row buffers (set aliasing between src/dst and the 2D driver's buffers), so the per-run winner is luck. It is a candidate for a follow-up.

**Plain `cv::dft()` loop** (outside the perf harness, one thread, time per call in us, `create` = plan + workspace, `apply` = transform):

| n | type | 5.x total | PR total | 5.x create / apply | PR create / apply |
|---|---|---|---|---|---|
| 256 | 32FC1 | 0.54 | 0.23 | 0.35 / 0.09 | 0.06 / 0.09 |
| 1024 | 32FC2 | 1.88 | 0.76 | 0.82 / 0.97 | 0.06 / 0.58 |
| 4096 | 64FC2 | 13.3 | 8.7 | 5.1 / 9.1 | 2.3 / 5.7 |
| 4725 | 64FC2 | 47.6 | 17.9 | 8.2 / 24.7 | 3.0 / 14.5 |
| 65536 | 32FC2 | 358 | 109 | 97 / 175 | 26 / 80 |
| 65536 | 64FC2 | 632 | 199 | 155 / 255 | 33 / 159 |

At 65536 the 5.x numbers include ~90–220 us of page faults per call (the glibc trimming described above); the perf harness hides part of this because its warm-up changes the heap state.

### Accuracy

`cv::dft` output vs a long double reference, error in units of eps (2^−52 for double):

| n | impulse response, 5.x | PR | random input (rel. to max\|X\|), 5.x | PR |
|---|---|---|---|---|
| 256 | 12.1 | 0.9 | 15.9 | 0.8 |
| 1024 | 2.4 | 1.1 | 5.2 | 1.25 |
| 4096 | 26.6 | 1.35 | 29.5 | 1.1 |
| 65536 | 11.7 | 1.2 | | |
| 1048576 | 26.4 | 1.4 | | |

Float tables are correctly rounded (0.25 eps). Round trip `idft(dft(x))` at n = 4093 (generic odd radix): max error 5.2e-13 → 7.0e-15.

### Memory

n = 4093 64FC2 (prime length → generic odd radix 4093): peak RSS 72.6 MB → 7.7 MB. No memory is kept between calls apart from the static tables of the power-of-two lengths ≤ 1024 (34 KB float + 67 KB double, built on first use).

### Tests

- `opencv_test_core` (18297 tests) with AVX2 and with `OPENCV_CPU_DISABLE=AVX2`; `Core_DFT`/`Core_DCT` sweeps now include prime lengths.
- `opencv_test_imgproc` matchTemplate / filter2D / phaseCorrelate.
- `dxt.cpp` / `dxt.simd.hpp` syntax-checked for aarch64 NEON, riscv64 RVV, x86 without SIMD, AVX2 baseline, and with `-Wall -Wextra -Wshadow`.

### Pull Request Readiness Checklist

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
- [ ] The feature is well documented and sample code can be built with the project CMake

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-11-17 14:41:43 +03:00

175 lines
10 KiB
C++

// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
// Shared, ISA-independent types of the 1D DFT/DCT engine (dxt.cpp + dxt.simd.hpp).
//
// The engine runs a 1D transform in three groups of passes:
// A (preproc): table-driven gather from the user input (or from an interleaved temp) into
// split re[]/im[] workspace, fused with the first twiddle-free radix-r0 stage,
// r0 in {1,2,3,4,5,8} (vectorized for r0 > 1, scalar table gather for r0 == 1).
// B (stages): mixed-radix decimation-in-time stages with growing span, direction-free
// (forward twiddles only), out-of-place (src pair -> dst pair, ping-pong) or
// in-place when the plan says it is legal. Vectorized with universal intrinsics.
// For long transforms the leading stages run chunk by chunk (depth-first) so
// that their data stays in L2.
// C (postproc): interleave / CCS packing / DCT ordering with fused scaling into the user output.
// For C2C (and even C2R) the last radix-4/8 stage writes the interleaved, scaled
// output itself (fused last stage), saving one pass over the data.
//
// Inverse transforms use the conjugation trick: conj() on the gather, im_scale = -scale on output.
// Buffers keep fixed semantics (re is always re).
//
// Plans are immutable after construction and shared read-only by all rows of a batch; the
// workspace is a separate, per-executor, mutable buffer allocated ONCE by the owner (never per
// call). The owner's workspace can live in the plan's single allocation (build(..., true)):
// one malloc per cv::dft() call instead of three, which also matters for glibc, whose heap
// trimming (and the page faults that follow on every call) is triggered by two freed MB-sized
// blocks but not by one twice as big. The tables of the power-of-two lengths up to 1024 are
// shared, static tables (see dxt.cpp).
#ifndef OPENCV_CORE_SRC_DXT_HPP
#define OPENCV_CORE_SRC_DXT_HPP
#include "opencv2/core/utility.hpp"
namespace cv {
enum DftKind
{
DFT_KIND_C2C = 0, // complex -> complex (forward or inverse)
DFT_KIND_R2C, // real -> CCS-packed (or "half complex") spectrum, forward only
DFT_KIND_C2R, // CCS-packed (or full complex) spectrum -> real, inverse only
DFT_KIND_DCT, // DCT-II, even n only
DFT_KIND_IDCT // DCT-III, even n only
};
enum DftStageMode
{
DFT_STAGE_SCALAR = 0, // scalar reference loop (span < any vector width, no SIMD for this depth, ...)
DFT_STAGE_FULL = 1, // span >= VL: vector loop with back-off clamp (brief, section 5)
DFT_STAGE_SIMD128 = 2 // 128-bit lanes < span < VL (wide ISAs only): the same loop on 128-bit vectors
};
enum { DFT_MAX_STAGES = 40 };
struct DftStage
{
int radix; // 3, 4, 5, 8 or an odd number >= 7
int span; // L: length of the sub-DFTs combined by this stage
int ngroups; // G = nc / (radix*span)
int nsteps; // number of (vector) iterations of the flat loop, precomputed by the plan
int steps_per_group; // nsteps / ngroups (the driver re-derives nsteps for chunked runs)
int mode; // DftStageMode
int tw_stride; // per-leg twiddle table length: span, plus one cache line of padding when
// span*esz is a multiple of 4 KB (the legs must not share one cache set)
// Per-stage twiddles, split layout, leg-major: tw_re[(q-1)*tw_stride + j] = cos(-2*pi*q*j/(radix*span)),
// q in [1, radix), j in [0, span). Type T of the plan.
const void* tw_re;
const void* tw_im;
// radix-odd (>=7) only: cs[m] = cos(2*pi*m/radix), sn[m] = sin(2*pi*m/radix), m in [0, radix);
// the butterfly addresses them with the cyclic index m = p*k mod radix
const void* cs;
const void* sn;
};
struct DftPlan
{
int kind; // DftKind
int n; // logical transform length (real length for R2C/C2R/DCT/IDCT)
int nc; // complex length actually run through the stages (n/2 for even real kinds)
int depth; // CV_32F or CV_64F
int vl; // vector lanes of the kernels this plan was built for (DFTKernels::vlanes)
int first_radix; // 1, 2, 3, 4, 5 or 8: the fused first stage done in preproc
bool real_input; // R2C with odd n: gather real samples, im = 0
bool pingpong; // stages must alternate between two workspace pairs
bool need_tmp; // C2R / DCT / IDCT: a temp of 2*nc elements (interleaved complex or the Makhoul-permuted reals)
bool fused_last; // the last stage is radix 4 or 8 and writes the interleaved scaled output itself (C2C, even C2R)
int nchunk_stages; // leading stages run chunk by chunk (chunk = stages[nchunk_stages].span); 0 = none
int nstages;
DftStage stages[DFT_MAX_STAGES];
// first_radix == 1: 2*nc element indices into the (real-typed) source (re index, im index);
// first_radix > 1: nc/first_radix output positions (g*first_radix) of the input columns j.
// Points into `buf` or into the static tables.
const int* itab;
AutoBuffer<double> buf; // ONE block: generated tables (type T, 8-byte aligned), itab and,
// when requested, the owner's workspace; the stage/rtw tables of
// 2^k lengths <= 1024 are static and not stored here
uchar* workspace; // ws_bytes inside `buf` when built with with_workspace, else 0
const void* rtw_re; // W_n^k = exp(-2*pi*i*k/n); R2C/C2R/DCT/IDCT with even n. Only k in
const void* rtw_im; // [0, nc/2] may be read: for even nc rtw_im is rtw_re + nc/2 (one table)
const void* dct_re; // s*W_4n^k, k in [0, n/2]; DCT/IDCT (s = DCT normalization)
const void* dct_im;
size_t ws_bytes; // workspace size (incl. 64 bytes for alignment)
size_t im_ofs; // byte offset of im from re inside a pair: nc*esz plus one cache line when
// nc*esz is a multiple of 4 KB (keeps the re and im streams out of one cache set)
size_t pair1_ofs; // byte offset of the second (re, im) pair or of the temp, from the aligned base
size_t scratch_ofs; // byte offset of the radix-odd scratch area
DftPlan() : kind(0), n(0), nc(0), depth(0), vl(0), first_radix(1), real_input(false),
pingpong(false), need_tmp(false), fused_last(false), nchunk_stages(0), nstages(0),
itab(0), workspace(0), rtw_re(0), rtw_im(0), dct_re(0), dct_im(0), ws_bytes(0),
im_ofs(0), pair1_ofs(0), scratch_ofs(0) {}
// Builds the plan for a 1D transform of the given kind (DftKind) and length.
//
// IMPORTANT: `vl` and `vl128` (vector lanes of the widest and of the 128-bit vectors) MUST
// come from the dispatched kernel table (DFTKernels::vlanes, ::vlanes128), never from
// VTraits<> in dxt.cpp, which is compiled for the baseline ISA and reports the wrong lane
// count on AVX2/AVX512/RVV builds. Stage modes and step counts depend on them.
// with_workspace: also reserve ws_bytes for the owner's workspace in the same block (`workspace`).
void build(int kind, int n, int depth, int vl, int vl128, bool with_workspace = false);
private:
// fills the twiddle tables (stage tables, W_n^k, DCT) at `dst`; ntw = total number of T entries
template<typename T> void fillTables(T* dst, size_t ntw, bool need_rtw, bool need_dct, bool static_stages, bool static_rtw);
DftPlan(const DftPlan&); // tables hold raw pointers into `buf`: no copies
DftPlan& operator=(const DftPlan&);
};
// (plan, src, src_step (in elements), re, im, conj)
typedef void (*DftPreprocFunc)(const DftPlan& plan, const void* src, size_t sstep,
void* re, void* im, bool conj);
// (stage, src_re, src_im, dst_re, dst_im, scratch); src == dst allowed only when !plan.pingpong
typedef void (*DftStageFunc)(const DftStage& st, const void* sre, const void* sim,
void* dre, void* dim, void* scratch);
// fused last stage: (stage, src_re, src_im, interleaved dst, re_scale, im_scale)
typedef void (*DftLastStageFunc)(const DftStage& st, const void* sre, const void* sim,
void* dst, double re_scale, double im_scale);
struct DFTKernels
{
// group A
DftPreprocFunc preprocRadix0; // gather + deinterleave only
DftPreprocFunc preprocRadix2; // + fused twiddle-free radix-2
DftPreprocFunc preprocRadix3; // + fused twiddle-free radix-3 (odd nc)
DftPreprocFunc preprocRadix4; // + fused twiddle-free radix-4
DftPreprocFunc preprocRadix5; // + fused twiddle-free radix-5 (odd nc)
DftPreprocFunc preprocRadix8; // + fused twiddle-free radix-8
// C2R: CCS (or full complex, complex_input) spectrum -> interleaved "2Z" temp (2*nc elements)
void (*preprocCCS)(const DftPlan& plan, const void* src, void* tmp, bool complex_input);
// DCT: Makhoul permutation of the (possibly strided) input into the temp
void (*preprocDCT)(const DftPlan& plan, const void* src, size_t sstep, void* tmp);
// IDCT: pre-twiddle + CCS untangle -> interleaved temp
void (*preprocIDCT)(const DftPlan& plan, const void* src, size_t sstep, void* tmp);
// group B
DftStageFunc radix3, radix4, radix5, radix8, radixOdd;
DftLastStageFunc radix4Last; // radix-4 stage + interleave + scale into the user output
DftLastStageFunc radix8Last; // the same for a radix-8 last stage
// group C
void (*postprocDFT)(const DftPlan& plan, const void* re, const void* im, void* dst,
double re_scale, double im_scale); // split -> interleaved complex
void (*postprocRealDFT)(const DftPlan& plan, const void* re, const void* im, void* dst,
double scale, bool complex_output); // R2C untangle + CCS/complex packing
void (*postprocReal)(const DftPlan& plan, const void* re, void* dst, double scale); // re only
void (*postprocDCT)(const DftPlan& plan, const void* re, const void* im, void* dst, size_t dstep);
void (*postprocIDCT)(const DftPlan& plan, const void* re, const void* im, void* dst, size_t dstep);
int vlanes; // VTraits<v_T>::vlanes() of the ISA these pointers belong to (1 = no SIMD)
int vlanes128; // lanes of the 128-bit vectors used by DFT_STAGE_SIMD128 (== vlanes when not wider)
};
}
#endif