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)
This commit is contained in:
Vadim Pisarevsky
2026-11-17 14:41:43 +03:00
committed by GitHub
parent 82028f2e5c
commit a30d2be6ea
7 changed files with 1188 additions and 322 deletions

View File

@@ -232,32 +232,74 @@ static const DFTKernels& getDFTKernels(int depth)
return depth == CV_32F ? k32 : k64;
}
/////////////////////////////// twiddle generation ///////////////////////////////
// exp(-2*pi*i*m/M) in double precision, m in [0, M): m = B*a + b -> hi[a]*lo[b] with B a power of
// two ~ sqrt(M). Both small tables are built by the rotation recurrence, re-seeded with exact
// sin/cos every 16 entries, so the error stays within a few ulps while only ~(B + M/B)/16 + 4
// trigonometric calls are made (4 for small M). Cheap to build, which matters because cv::dft()
// two ~ sqrt(M). The two small tables hold exact values (~0.5 ulp, see exact()), so every product
// is within ~3 ulps. Cheap to build (~2*sqrt(M) points at ~1.5 ns), which matters because cv::dft()
// builds a fresh plan on every call.
struct DftTwiddleGen
{
int M, logB, maskB;
int M, logB, maskB, nhi;
AutoBuffer<double, 1024> buf;
double *hi_re, *hi_im, *lo_re, *lo_im;
// re[i] + i*im[i] = w^i, i in [0, count), w = (wr, wi) = exp(i*stepAngle); the rotation
// recurrence is re-seeded with exact sin/cos every 16 entries
static void fillTable(double* re, double* im, int count, double wr, double wi, double stepAngle)
// exp(-2*pi*i*m/M) to ~0.5 ulp for m = m0, m0 + d, ..., m0 + (count-1)*d (all < M). The angle
// is reduced to [0, pi/4] in exact integer arithmetic (octant o = floor(8m/M), remainder
// (8m - oM)/M), so the only roundings are the final rational -> double conversion and the two
// Cephes polynomials (|x| <= pi/4, ~1e-16 relative): x = rem * (pi/4)/M, one rounding of the
// constant and one of the product. Two points per iteration (~1.5 ns each).
static void exact(int m0, int d, int count, int M, double* re, double* im)
{
for (int i0 = 0; i0 < count; i0 += 16)
CV_DbgAssert(m0 >= 0 && d > 0 && count > 0 && (int64)m0 + (int64)(count - 1)*d < M);
int64 rem = 8*(int64)m0, d8 = 8*(int64)d;
int o = 0;
while (rem >= M) { rem -= M; o++; }
const double S1 = 1.58962301576546568060e-10, S2 = -2.50507477628578072866e-8, S3 = 2.75573136213857245213e-6,
S4 = -1.98412698295895385996e-4, S5 = 8.33333333332211858878e-3, S6 = -1.66666666666666307295e-1,
C1 = -1.13585365213876817300e-11, C2 = 2.08757008419747316778e-9, C3 = -2.75573141792967388112e-7,
C4 = 2.48015872888517045348e-5, C5 = -1.38888888888730564116e-3, C6 = 4.16666666666665929218e-2;
const double scale = (CV_PI/4)/M;
for (int i = 0; i < count; i += 2)
{
double t0 = stepAngle*i0;
double cr = i0 == 0 ? 1 : cos(t0), ci = i0 == 0 ? 0 : sin(t0);
int i1 = std::min(i0 + 16, count);
for (int i = i0; i < i1; i++)
int oct[2]; double r[2], sn[2], cs[2];
for (int k = 0; k < 2; k++)
{
re[i] = cr; im[i] = ci;
double t = cr*wr - ci*wi;
ci = cr*wi + ci*wr;
cr = t;
oct[k] = o;
r[k] = (double)((o & 1) ? M - rem : rem); // odd octant: angle = (o+1)*pi/4 - x
rem += d8;
while (rem >= M) { rem -= M; o++; } // runs past the end on the padding point: harmless
}
#if CV_SIMD128_64F
{
v_float64x2 x = v_mul(v_float64x2(r[0], r[1]), v_setall_f64(scale));
v_float64x2 z = v_mul(x, x), z2 = v_mul(z, z);
v_float64x2 ps = v_add(v_add(v_setall_f64(S6), v_mul(v_setall_f64(S5), z)),
v_mul(z2, v_add(v_add(v_setall_f64(S4), v_mul(v_setall_f64(S3), z)),
v_mul(z2, v_add(v_setall_f64(S2), v_mul(v_setall_f64(S1), z))))));
v_float64x2 pc = v_add(v_add(v_setall_f64(C6), v_mul(v_setall_f64(C5), z)),
v_mul(z2, v_add(v_add(v_setall_f64(C4), v_mul(v_setall_f64(C3), z)),
v_mul(z2, v_add(v_setall_f64(C2), v_mul(v_setall_f64(C1), z))))));
v_store(sn, v_add(v_mul(v_mul(ps, z), x), x));
v_store(cs, v_add(v_mul(pc, z2), v_sub(v_setall_f64(1.), v_mul(v_setall_f64(0.5), z))));
}
#else
for (int k = 0; k < 2; k++)
{
double x = r[k]*scale, z = x*x, z2 = z*z;
double ps = (S6 + S5*z) + z2*((S4 + S3*z) + z2*(S2 + S1*z));
double pc = (C6 + C5*z) + z2*((C4 + C3*z) + z2*(C2 + C1*z));
sn[k] = ps*z*x + x; cs[k] = pc*z2 + (1 - 0.5*z);
}
#endif
for (int k = 0; k < 2 && i + k < count; k++)
{
int ok = oct[k];
bool swap = ((ok + 1) & 2) != 0; // octants 1, 2, 5, 6: (cos, sin) = (sin x, cos x) up to signs
double c = swap ? sn[k] : cs[k], s = swap ? cs[k] : sn[k];
if (ok >= 2 && ok <= 5) c = -c; // quadrants 2, 3
if (ok >= 4) s = -s; // lower half
re[i + k] = c; im[i + k] = -s;
}
}
}
@@ -269,14 +311,30 @@ struct DftTwiddleGen
while ((1LL << (2*logB)) < M) logB++; // B = 2^logB >= sqrt(M)
int B = 1 << logB;
maskB = B - 1;
int nhi = (M + B - 1)/B;
nhi = (M + B - 1)/B;
buf.allocate(2*(B + nhi));
hi_re = buf.data(); hi_im = hi_re + nhi;
lo_re = hi_im + nhi; lo_im = lo_re + B;
double a = -2*CV_PI/M;
// the two step angles are computed exactly (4 trigonometric calls in total for small M)
fillTable(lo_re, lo_im, B, cos(a), sin(a), a);
fillTable(hi_re, hi_im, nhi, cos(a*B), sin(a*B), a*B);
exact(0, 1, B, M, lo_re, lo_im);
if (M % (8*B) == 0)
{
// hi covers the whole circle in 8 symmetric octants: evaluate the first one, reflect the rest
int n8 = M/(8*B);
CV_DbgAssert(nhi == 8*n8);
exact(0, B, n8 + 1, M, hi_re, hi_im);
for (int a = n8 + 1; a < nhi; a++)
{
int q = a/(2*n8), rq = a - q*2*n8; // quadrant q, position within it
double c0, s0; // (cos, sin) of the angle reduced to [0, pi/2]
if (rq <= n8) { c0 = hi_re[rq]; s0 = -hi_im[rq]; }
else { c0 = -hi_im[2*n8 - rq]; s0 = hi_re[2*n8 - rq]; }
double c = q == 0 ? c0 : q == 1 ? -s0 : q == 2 ? -c0 : s0;
double s = q == 0 ? s0 : q == 1 ? c0 : q == 2 ? -s0 : -c0;
hi_re[a] = c; hi_im[a] = -s;
}
}
else
exact(0, B, nhi, M, hi_re, hi_im);
}
// exp(-2*pi*i*m/M) for any m >= 0 (the angle is periodic: only m mod M matters; callers may
@@ -292,157 +350,114 @@ struct DftTwiddleGen
}
};
static inline void dftStoreTw(double* dst, double v) { *dst = v; }
static inline void dftStoreTw(float* dst, double v) { *dst = (float)v; }
#if (CV_SIMD || CV_SIMD_SCALABLE) && CV_SIMD_64F
static inline void dftStoreTw(double* dst, const v_float64& v) { v_store(dst, v); }
static inline void dftStoreTw(float* dst, const v_float64& v) { v_store_low(dst, v_cvt_f32(v)); }
#endif
// dre[j] + i*dim[j] = scale*W_M^(j*stride), j in [0, count), W_M = exp(-2*pi*i/M), M = gen.M.
// Two-level product over j = a*B + b: lo[b] = W^(stride*b), hi[a] = W^(stride*B*a), B ~ sqrt(count).
// For stride == 1 the generator's exact seed tables serve as lo/hi (error <= ~4 ulps); otherwise
// the ~3*sqrt(count) seeds are looked up from the generator (one more product: <= ~7 ulps). The
// products themselves are vectorized, so the cost is ~0.3 ns per entry.
template<typename T>
void DftPlan::fillTables(size_t ntw, bool need_rtw, bool need_dct)
static void fillTwiddles(const DftTwiddleGen& gen, int stride, int count, double scale, T* dre, T* dim)
{
DftPlan& p = *this;
// all angles come from one base table exp(-2*pi*i*m/M), M a multiple of every angle grid used:
// C2C: M = nc; real kinds with even n: M = n (=2nc) or 4n for DCT (W_4n^k); odd real: M = n = nc.
int M = nc*(need_dct ? 8 : need_rtw ? 2 : 1);
DftTwiddleGen gen;
gen.init(M);
p.tw.allocate((ntw*sizeof(T) + sizeof(double) - 1)/sizeof(double) + 1);
T* cur = (T*)p.tw.data();
int maxL = 1;
for (int s = 0; s < p.nstages; s++)
if (p.stages[s].radix <= 8) maxL = std::max(maxL, p.stages[s].span);
AutoBuffer<double, 2048> twd_buf(2*maxL); // leg-1 twiddles of the current stage in double
double* twd = twd_buf.data();
for (int s = 0; s < p.nstages; s++)
CV_DbgAssert(count <= gen.M + 1 && stride >= 1);
const double *lr, *li, *hr, *hi;
int B;
AutoBuffer<double, 512> seeds;
if (stride == 1)
{
DftStage& st = p.stages[s];
int r = st.radix, L = st.span, ts = st.tw_stride;
T* twr = cur; T* twi = cur + (r - 1)*ts;
cur = twi + (r - 1)*ts;
int step = M/(r*L);
if (r <= 8)
{
// Leg 1 (W_{rL}^j) by K independent interleaved rotation recurrences (a single chain is
// latency-bound), each re-seeded from the exact generator every 16 of its steps; legs
// q >= 2 as t_q(j) = t_{q-1}(j)*t_1(j), independent per entry (error <= q ulps).
constexpr int K = 8;
double cr[K], ci[K], wr, wi;
gen.get(K*step, wr, wi);
double* t1r = twd; double* t1i = twd + L; // leg 1 kept in double for the products
for (int j0 = 0; j0 < L; j0 += 16*K) // blocks of 16 steps per chain
{
for (int k = 0; k < K; k++)
gen.get(std::min(j0 + k, L - 1)*step, cr[k], ci[k]);
int j1 = std::min(j0 + 16*K, L);
for (int j = j0; j < j1; j += K)
for (int k = 0; k < K && j + k < L; k++)
{
t1r[j+k] = cr[k]; t1i[j+k] = ci[k];
double t = cr[k]*wr - ci[k]*wi;
ci[k] = cr[k]*wi + ci[k]*wr;
cr[k] = t;
}
}
for (int j = 0; j < L; j++) // separate pass: vectorizes, the recurrence loop does not
{
twr[j] = (T)t1r[j]; twi[j] = (T)t1i[j];
}
for (int q = 2; q < r; q++)
{
const T* pr = twr + (q-2)*ts; const T* pi = twi + (q-2)*ts;
T* tr = twr + (q-1)*ts; T* ti = twi + (q-1)*ts;
for (int j = 0; j < L; j++)
{
double ar = pr[j], ai = pi[j], br = t1r[j], bi = t1i[j];
tr[j] = (T)(ar*br - ai*bi);
ti[j] = (T)(ar*bi + ai*br);
}
}
}
else
{
// large odd radix: exact-ish generator lookup per entry
for (int q = 1; q < r; q++)
for (int j = 0; j < L; j++)
{
double re, im;
gen.get(q*j*step, re, im);
twr[(q-1)*ts + j] = (T)re;
twi[(q-1)*ts + j] = (T)im;
}
}
st.tw_re = twr; st.tw_im = twi;
st.cs = st.sn = 0;
if (r >= 7)
{
int h = (r - 1)/2;
T* cs = cur; T* sn = cur + h*h;
cur = sn + h*h;
for (int pp = 1; pp <= h; pp++)
for (int k = 1; k <= h; k++)
{
double t = 2*CV_PI*((double)pp*k/r);
cs[(pp-1)*h + (k-1)] = (T)cos(t);
sn[(pp-1)*h + (k-1)] = (T)sin(t);
}
st.cs = cs; st.sn = sn;
}
B = gen.maskB + 1;
lr = gen.lo_re; li = gen.lo_im; hr = gen.hi_re; hi = gen.hi_im;
CV_DbgAssert((count + B - 1)/B <= gen.nhi);
}
p.rtw_re = p.rtw_im = p.dct_re = p.dct_im = 0;
if (need_rtw)
else
{
// W_n^k, k in [0, nc]
T* wr = cur; T* wi = cur + (nc + 1);
cur = wi + (nc + 1);
int step = M/n;
for (int k = 0; k <= nc; k++)
{
double re, im;
gen.get(k*step, re, im);
wr[k] = (T)re; wi[k] = (T)im;
}
p.rtw_re = wr; p.rtw_im = wi;
int logB = 0;
while ((1 << (2*logB)) < count) logB++;
B = 1 << logB;
int nhi = (count + B - 1)/B;
seeds.allocate(2*(B + nhi));
double* lr_ = seeds.data(); double* li_ = lr_ + B;
double* hr_ = li_ + B; double* hi_ = hr_ + nhi;
int M = gen.M, m = 0, sB = (int)((int64)stride*B % M);
CV_DbgAssert(stride < M);
for (int b = 0; b < B; b++, m = m + stride < M ? m + stride : m + stride - M)
gen.get(m, lr_[b], li_[b]);
m = 0;
for (int a = 0; a < nhi; a++, m = m + sB < M ? m + sB : m + sB - M)
gen.get(m, hr_[a], hi_[a]);
lr = lr_; li = li_; hr = hr_; hi = hi_;
}
if (need_dct)
for (int a = 0, j0 = 0; j0 < count; a++, j0 += B)
{
// s*W_4n^k, k in [0, nc]; s = 2*sqrt(1/(2n)) forward, sqrt(1/(2n)) inverse (the original normalization)
T* wr = cur; T* wi = cur + (nc + 1);
cur = wi + (nc + 1);
double scale = (p.kind == DFT_KIND_DCT ? 2 : 1)*std::sqrt(1./(2*n));
int step = M/(4*n);
for (int k = 0; k <= nc; k++)
int cnt = std::min(B, count - j0), b = 0;
double ar = hr[a]*scale, ai = hi[a]*scale;
T* re = dre + j0; T* im = dim + j0;
#if (CV_SIMD || CV_SIMD_SCALABLE) && CV_SIMD_64F
const int VL = VTraits<v_float64>::vlanes();
v_float64 var = vx_setall_f64(ar), vai = vx_setall_f64(ai);
for (; b + VL <= cnt; b += VL)
{
double re, im;
gen.get(k*step, re, im);
wr[k] = (T)(re*scale); wi[k] = (T)(im*scale);
v_float64 xr = vx_load(lr + b), xi = vx_load(li + b);
dftStoreTw(re + b, v_sub(v_mul(var, xr), v_mul(vai, xi)));
dftStoreTw(im + b, v_add(v_mul(var, xi), v_mul(vai, xr)));
}
#endif
for (; b < cnt; b++)
{
dftStoreTw(re + b, ar*lr[b] - ai*li[b]);
dftStoreTw(im + b, ar*li[b] + ai*lr[b]);
}
p.dct_re = wr; p.dct_im = wi;
}
}
// See dxt.hpp for the contract (in particular where `vl` must come from).
void DftPlan::build(int _kind, int _n, int _depth, int _vl)
// Stage twiddles of a radix-r stage with span L, leg-major: twr/twi[(q-1)*ts + j] = W_{rL}^{q*j}
// = gen(q*j*step), step = gen.M/(r*L)
template<typename T>
static void fillStageTwiddles(const DftTwiddleGen& gen, int r, int L, int ts, T* twr, T* twi)
{
DftPlan& p = *this;
CV_Assert(_n >= 1 && _vl >= 1);
CV_Assert(_depth == CV_32F || _depth == CV_64F);
bool real_kind = _kind != DFT_KIND_C2C;
bool dct_kind = _kind == DFT_KIND_DCT || _kind == DFT_KIND_IDCT;
if (dct_kind)
CV_Assert(_n % 2 == 0); // cv::dct() supports even n only (n == 1 is handled by the caller)
p.kind = _kind; p.n = _n; p.depth = _depth; p.vl = _vl;
p.nc = real_kind && _n % 2 == 0 ? _n/2 : _n;
CV_Assert(nc < (1 << 28));
size_t esz = depth == CV_32F ? sizeof(float) : sizeof(double);
p.real_input = kind == DFT_KIND_R2C && (n & 1) != 0;
p.need_tmp = kind == DFT_KIND_C2R || kind == DFT_KIND_DCT || kind == DFT_KIND_IDCT;
p.pingpong = false;
int step = gen.M/(r*L);
for (int q = 1; q < r; q++)
fillTwiddles<T>(gen, q*step, L, 1., twr + (q-1)*ts, twi + (q-1)*ts);
}
// factorization: 2^k part first (fused first stage r0 + radix-4 stages), then 3s, 5s, other odd.
// (A radix-8 middle stage was tried and measured slower on NEON: with per-leg twiddle tables it
// does not save loads over two radix-4 stages and keeps 16 data vectors live.)
// The real-transform twiddles W_n^k = exp(-2*pi*i*k/n), n = 2*nc, as ONE table of nc + 1 entries:
// t[k] = cos(2*pi*k/n) for k in [0, nc], and since -sin(2*pi*k/n) = cos(2*pi*(k + nc/2)/n), the
// imaginary parts are the same table shifted by nc/2 (nc even). The kernels only read k in
// [0, nc/2]. gen.M must be a multiple of n.
template<typename T>
static void fillRealTwiddles(const DftTwiddleGen& gen, int n, int nc, T* t)
{
CV_DbgAssert(nc % 2 == 0);
fillTwiddles<T>(gen, gen.M/n, nc/2, 1., t, t + nc/2);
t[nc] = (T)-1; // -sin(pi/2): the im part of k = nc/2
}
// The radix sequence of a length nc: the fused first stage r0 (1, 2, 3, 4, 5 or 8), then the
// radix-8 and radix-4 stages of the remaining 2^k part, then 3s, 5s and the other odd factors
// ascending. Even nc: r0 from the power of two. Odd nc: r0 = 5 or 3 when available (a vectorized,
// twiddle-free first stage; it also makes the spans of the following stages larger), else 1.
static int dftFactorize(int nc, int radices[DFT_MAX_STAGES], int& nst)
{
int k2 = 0, rest = nc;
while ((rest & 1) == 0) { rest >>= 1; k2++; }
int r0 = k2 == 0 ? 1 : k2 == 1 ? 2 : (k2 & 1) ? 8 : 4;
p.first_radix = r0;
int radices[DFT_MAX_STAGES], nst = 0;
for (int m = k2 - (r0 == 1 ? 0 : r0 == 2 ? 1 : r0 == 4 ? 2 : 3); m > 0; m -= 2) { CV_Assert(nst < DFT_MAX_STAGES); radices[nst++] = 4; }
rest = nc >> k2;
// 2^k2 = r0 * 8^a * 4^b: the twiddle-free first stage takes 8 whenever the rest can still be
// covered (k2 - 3 is 0 or >= 2), then as many radix-8 stages as possible, radix-4 stages last
int r0 = k2 == 0 ? (rest % 5 == 0 ? 5 : rest % 3 == 0 ? 3 : 1) : k2 == 1 ? 2 : (k2 == 2 || k2 == 4) ? 4 : 8;
nst = 0;
{
int m = k2 - (r0 == 2 ? 1 : r0 == 4 ? 2 : r0 == 8 ? 3 : 0);
int b = m % 3 == 0 ? 0 : m % 3 == 2 ? 1 : 2, a = (m - 2*b)/3;
CV_Assert(m - 2*b >= 0 && nst + a + b <= DFT_MAX_STAGES);
for (int i = 0; i < a; i++) radices[nst++] = 8;
for (int i = 0; i < b; i++) radices[nst++] = 4;
}
if (r0 == 3 || r0 == 5) rest /= r0;
while (rest % 3 == 0) { CV_Assert(nst < DFT_MAX_STAGES); radices[nst++] = 3; rest /= 3; }
while (rest % 5 == 0) { CV_Assert(nst < DFT_MAX_STAGES); radices[nst++] = 5; rest /= 5; }
for (int f = 7; rest > 1; f += 2)
@@ -455,48 +470,18 @@ void DftPlan::build(int _kind, int _n, int _depth, int _vl)
}
while (rest % f == 0) { CV_Assert(nst < DFT_MAX_STAGES); radices[nst++] = f; rest /= f; }
}
p.nstages = nst;
return r0;
}
// stages
int L = r0, max_h = 0;
size_t ntw = 0;
for (int s = 0; s < nst; s++)
{
DftStage& st = p.stages[s];
int r = radices[s];
st.radix = r; st.span = L; st.ngroups = nc/(r*L); st.tw_stride = L;
if (vl > 1 && L >= vl)
{
st.mode = DFT_STAGE_FULL;
st.nsteps = st.ngroups*((L + vl - 1)/vl);
if (L % vl != 0)
p.pingpong = true; // back-off clamp => overlapping stores => must be out-of-place
}
else
{
st.mode = DFT_STAGE_SCALAR;
st.nsteps = st.ngroups*L;
}
ntw += 2*(size_t)(r - 1)*st.tw_stride;
if (r >= 7)
{
int h = (r - 1)/2;
ntw += 2*(size_t)h*h;
max_h = std::max(max_h, h);
}
L *= r;
}
CV_Assert(L == nc);
// digit-reversal: position p = sum_s d_s*L_s holds input element sum_s d_s*M_s, M_s = nc/(L_s*r_s);
// the radix sequence is r0 (if > 1) followed by the stage radices.
// - r0 == 1 (odd nc): itab holds two element indices (re, im) per complex element for the
// scalar gather (im index unused when real_input);
// - r0 > 1: the r0 inputs of group g are the column x[base(g) + q*nc/r0]; itab[base(g)] = g*r0
// tells the transposed first stage where the outputs of column base(g) go.
int seq[DFT_MAX_STAGES + 1], nseq = 0;
if (r0 > 1) seq[nseq++] = r0;
for (int s = 0; s < nst; s++) seq[nseq++] = radices[s];
// Digit-reversal permutation for the radix sequence seq[0..nseq) (seq[0] = r0 when r0 > 1):
// position p = sum_s d_s*L_s holds input element sum_s d_s*M_s, M_s = nc/(L_s*r_s).
// - r0 == 1 (odd nc without 3 or 5): itab holds two element indices (re, im) per complex element
// for the scalar gather (im index == re index when real_input, i.e. a real source);
// - r0 > 1: the r0 inputs of group g are the column x[base(g) + q*nc/r0]; gtab[base(g)] = g*r0
// tells the transposed first stage where the outputs of column base(g) go. nc/r0 entries.
static void dftBuildPermutation(int nc, const int* seq, int nseq, bool real_input, int* itab)
{
int r0 = nseq > 0 ? seq[0] : 1;
int digits[DFT_MAX_STAGES + 1], weights[DFT_MAX_STAGES + 1];
{
int Ls = 1;
@@ -507,10 +492,10 @@ void DftPlan::build(int _kind, int _n, int _depth, int _vl)
Ls *= seq[s];
}
}
if (r0 == 1)
bool first_fused = r0 == 2 || r0 == 3 || r0 == 4 || r0 == 5 || r0 == 8;
if (!first_fused)
{
p.itab.allocate(nc*2);
int* it_all = p.itab.data();
int* it_all = itab;
// the two lowest digits are enumerated by plain nested loops, the higher ones by a counter
int n_in = std::min(nseq, 2);
int r_0 = n_in > 0 ? seq[0] : 1, w_0 = n_in > 0 ? weights[0] : 0;
@@ -521,7 +506,7 @@ void DftPlan::build(int _kind, int _n, int _depth, int _vl)
{
int rev = rev_hi + d1*w_1;
int* it = it_all + pos*2;
if (p.real_input)
if (real_input)
{
for (int d0 = 0; d0 < r_0; d0++, rev += w_0)
{
@@ -554,8 +539,7 @@ void DftPlan::build(int _kind, int _n, int _depth, int _vl)
// g follows incrementally with the digit weights gw[s] = L_s/r0. The two fastest digits
// are enumerated by plain nested loops.
int M = nc/r0;
p.itab.allocate(M);
int* gtab = p.itab.data();
int* gtab = itab;
int gw[DFT_MAX_STAGES + 1];
{
int Ls = 1;
@@ -586,24 +570,332 @@ void DftPlan::build(int _kind, int _n, int _depth, int _vl)
}
}
}
}
// twiddle tables
/////////////////////////////// static tables for 2^k lengths <= 1024 ///////////////////////////////
//
// The power-of-two lengths are the common case (matchTemplate/filter2D tiles, 256/512/1024 rows),
// and cv::dft() builds a plan per call, so their tables are built once per process and shared:
// - radix-4 stage twiddles W_{4L}^{q*j} for every span L = 2^k, 4 <= L <= 256, and radix-8
// stage twiddles W_{8L}^{q*j} for 4 <= L <= 128 (they depend on (radix, span) only, not on
// the transform length);
// - the permutation gtab of nc = 2^k, 4 <= nc <= 1024 (r0 in {4, 8});
// - W_n^k, k in [0, nc], of the even real kinds (R2C/C2R) with nc = 2^k <= 1024.
// ~90 KB for both depths. DCT tables are kind- and length-specific and stay per plan.
enum { DFT_STATIC_MAX_LOG2 = 10, DFT_STATIC_MAX_NC = 1 << DFT_STATIC_MAX_LOG2 };
template<typename T> struct DftStaticTables
{
AutoBuffer<T> tw; // stage tables, then the real twiddles
AutoBuffer<int> itab;
const T* tw_re[DFT_STATIC_MAX_LOG2]; // radix 4: [log2(L)], L in [4, 256]
const T* tw_im[DFT_STATIC_MAX_LOG2];
const T* tw8_re[DFT_STATIC_MAX_LOG2]; // radix 8: [log2(L)], L in [4, 128]
const T* tw8_im[DFT_STATIC_MAX_LOG2];
const T* rtw_re[DFT_STATIC_MAX_LOG2 + 1]; // [log2(nc)], nc in [4, 1024]; rtw_im = rtw_re + nc/2
const T* rtw_im[DFT_STATIC_MAX_LOG2 + 1];
const int* gtab[DFT_STATIC_MAX_LOG2 + 1]; // [log2(nc)], nc in [4, 1024]
DftStaticTables()
{
size_t ntw = 0, nitab = 0;
for (int k = 2; k <= DFT_STATIC_MAX_LOG2; k++)
{
int nc = 1 << k;
if (k <= 8) ntw += 6*(size_t)nc; // radix-4 stage with L = nc: 3 legs x (re, im) x L
if (k <= 7) ntw += 14*(size_t)nc; // radix-8 stage with L = nc: 7 legs x (re, im) x L
ntw += (size_t)nc + 1; // W_{2nc}^k, k in [0, nc], one table (see fillRealTwiddles)
int radices[DFT_MAX_STAGES], nst;
nitab += nc/dftFactorize(nc, radices, nst);
}
tw.allocate(ntw);
itab.allocate(nitab);
T* cur = tw.data();
int* icur = itab.data();
for (int k = 2; k <= DFT_STATIC_MAX_LOG2; k++)
{
int nc = 1 << k;
if (k <= 8)
{
int L = nc;
DftTwiddleGen gen;
gen.init(4*L);
tw_re[k] = cur; tw_im[k] = cur + 3*L;
fillStageTwiddles<T>(gen, 4, L, L, cur, cur + 3*L);
cur += 6*L;
}
if (k <= 7)
{
int L = nc;
DftTwiddleGen gen;
gen.init(8*L);
tw8_re[k] = cur; tw8_im[k] = cur + 7*L;
fillStageTwiddles<T>(gen, 8, L, L, cur, cur + 7*L);
cur += 14*L;
}
{
DftTwiddleGen gen;
gen.init(2*nc);
rtw_re[k] = cur; rtw_im[k] = cur + nc/2;
fillRealTwiddles<T>(gen, 2*nc, nc, cur);
cur += nc + 1;
}
{
int radices[DFT_MAX_STAGES], nst;
int r0 = dftFactorize(nc, radices, nst);
int seq[DFT_MAX_STAGES + 1], nseq = 0;
seq[nseq++] = r0;
for (int s = 0; s < nst; s++) seq[nseq++] = radices[s];
gtab[k] = icur;
dftBuildPermutation(nc, seq, nseq, false, icur);
icur += nc/r0;
}
}
CV_Assert(cur == tw.data() + ntw && icur == itab.data() + nitab);
}
};
template<typename T> static const DftStaticTables<T>& getDftStaticTables()
{
static const DftStaticTables<T> tables;
return tables;
}
static inline bool dftIsPow2(int x) { return x > 0 && (x & (x - 1)) == 0; }
static inline int dftLog2(int x) { int k = 0; while ((1 << k) < x) k++; return k; }
template<typename T>
void DftPlan::fillTables(T* dst, size_t ntw, bool need_rtw, bool need_dct, bool static_stages, bool static_rtw)
{
DftPlan& p = *this;
// all angles come from one base table exp(-2*pi*i*m/M), M a multiple of every angle grid used:
// C2C: M = nc; real kinds with even n: M = n (=2nc) or 4n for DCT (W_4n^k); odd real: M = n = nc.
int M = nc*(need_dct ? 8 : need_rtw ? 2 : 1);
DftTwiddleGen gen;
if (ntw > 0)
gen.init(M);
T* cur = dst;
const DftStaticTables<T>* st_tables = static_stages || static_rtw ? &getDftStaticTables<T>() : 0;
for (int s = 0; s < p.nstages; s++)
{
DftStage& st = p.stages[s];
int r = st.radix, L = st.span, ts = st.tw_stride;
st.cs = st.sn = 0;
if (static_stages)
{
CV_DbgAssert((r == 4 || r == 8) && dftIsPow2(L) && L >= 4 && L*r <= 1024 && ts == L);
int k = dftLog2(L);
if (r == 4) { st.tw_re = st_tables->tw_re[k]; st.tw_im = st_tables->tw_im[k]; }
else { st.tw_re = st_tables->tw8_re[k]; st.tw_im = st_tables->tw8_im[k]; }
continue;
}
T* twr = cur; T* twi = cur + (r - 1)*ts;
cur = twi + (r - 1)*ts;
fillStageTwiddles<T>(gen, r, L, ts, twr, twi);
st.tw_re = twr; st.tw_im = twi;
if (r >= 7)
{
// r entries (not h*h): the butterfly walks them with the cyclic index p*k mod r
T* cs = cur; T* sn = cur + r;
cur = sn + r;
for (int m = 0; m < r; m++)
{
double t = 2*CV_PI*((double)m/r);
cs[m] = (T)cos(t);
sn[m] = (T)sin(t);
}
st.cs = cs; st.sn = sn;
}
}
p.rtw_re = p.rtw_im = p.dct_re = p.dct_im = 0;
if (need_rtw)
{
if (static_rtw)
{
int k = dftLog2(nc);
p.rtw_re = st_tables->rtw_re[k]; p.rtw_im = st_tables->rtw_im[k];
}
else if (nc % 2 == 0)
{
// W_n^k, k in [0, nc], one table (see fillRealTwiddles)
T* w = cur;
cur = w + (nc + 1);
fillRealTwiddles<T>(gen, n, nc, w);
p.rtw_re = w; p.rtw_im = w + nc/2;
}
else
{
// odd nc: separate re/im tables
T* wr = cur; T* wi = cur + (nc + 1);
cur = wi + (nc + 1);
fillTwiddles<T>(gen, M/n, nc + 1, 1., wr, wi);
p.rtw_re = wr; p.rtw_im = wi;
}
}
if (need_dct)
{
// s*W_4n^k, k in [0, nc]; s = 2*sqrt(1/(2n)) forward, sqrt(1/(2n)) inverse (the original normalization)
T* wr = cur; T* wi = cur + (nc + 1);
cur = wi + (nc + 1);
double scale = (p.kind == DFT_KIND_DCT ? 2 : 1)*std::sqrt(1./(2*n));
fillTwiddles<T>(gen, M/(4*n), nc + 1, scale, wr, wi);
p.dct_re = wr; p.dct_im = wi;
}
CV_Assert((size_t)(cur - dst) == ntw);
}
// Leading stages whose groups (radix*span elements) fit into a chunk of DFT_CHUNK_BYTES per array
// are run chunk by chunk (depth-first) by the driver: the chunk stays in L2 across those stages
// instead of streaming the whole array through the cache once per stage.
enum { DFT_CHUNK_BYTES = 1 << 15 };
// See dxt.hpp for the contract (in particular where `vl` and `vl128` must come from).
void DftPlan::build(int _kind, int _n, int _depth, int _vl, int _vl128, bool with_workspace)
{
DftPlan& p = *this;
CV_Assert(_n >= 1 && _vl >= 1 && _vl128 >= 1 && _vl128 <= _vl);
CV_Assert(_depth == CV_32F || _depth == CV_64F);
bool real_kind = _kind != DFT_KIND_C2C;
bool dct_kind = _kind == DFT_KIND_DCT || _kind == DFT_KIND_IDCT;
if (dct_kind)
CV_Assert(_n % 2 == 0); // cv::dct() supports even n only (n == 1 is handled by the caller)
p.kind = _kind; p.n = _n; p.depth = _depth; p.vl = _vl;
p.nc = real_kind && _n % 2 == 0 ? _n/2 : _n;
CV_Assert(nc < (1 << 28));
size_t esz = depth == CV_32F ? sizeof(float) : sizeof(double);
p.real_input = kind == DFT_KIND_R2C && (n & 1) != 0;
p.need_tmp = kind == DFT_KIND_C2R || kind == DFT_KIND_DCT || kind == DFT_KIND_IDCT;
p.pingpong = false;
int radices[DFT_MAX_STAGES], nst = 0;
int r0 = dftFactorize(nc, radices, nst);
p.first_radix = r0;
p.nstages = nst;
// stages
int L = r0, max_h = 0;
size_t ntw = 0;
int vl128 = _vl128;
for (int s = 0; s < nst; s++)
{
DftStage& st = p.stages[s];
int r = radices[s];
st.radix = r; st.span = L; st.ngroups = nc/(r*L);
// 4K-aliasing: with a span of a 4 KB multiple all r-1 leg tables (and the r data legs)
// of one butterfly map to the same L1 set; one line of padding per leg spreads them
st.tw_stride = L + ((L*esz & 4095) == 0 ? (int)(64/esz) : 0);
if (vl > 1 && L >= vl)
{
st.mode = DFT_STAGE_FULL;
st.steps_per_group = (L + vl - 1)/vl;
if (L % vl != 0)
p.pingpong = true; // back-off clamp => overlapping stores => must be out-of-place
}
else if (vl128 > 1 && vl128 < vl && L >= vl128)
{
st.mode = DFT_STAGE_SIMD128;
st.steps_per_group = (L + vl128 - 1)/vl128;
if (L % vl128 != 0)
p.pingpong = true;
}
else
{
st.mode = DFT_STAGE_SCALAR;
st.steps_per_group = L;
}
st.nsteps = st.ngroups*st.steps_per_group;
ntw += 2*(size_t)(r - 1)*st.tw_stride;
if (r >= 7)
{
ntw += 2*(size_t)r;
max_h = std::max(max_h, (r - 1)/2);
}
L *= r;
}
CV_Assert(L == nc);
// the static tables cover the stage twiddles of nc = 2^k <= 1024 (stages of radix 4 and 8,
// r*L <= 1024), the permutation of 4 <= nc = 2^k <= 1024 and W_n^k of the even real kinds
bool static_pow2 = dftIsPow2(nc) && nc >= 4 && nc <= DFT_STATIC_MAX_NC;
bool need_rtw = real_kind && n % 2 == 0;
if (need_rtw) ntw += 2*(size_t)(nc + 1);
bool static_stages = static_pow2;
bool static_rtw = static_pow2 && need_rtw && !dct_kind;
if (static_stages)
ntw = 0;
if (need_rtw && !static_rtw) ntw += nc % 2 == 0 ? (size_t)nc + 1 : 2*(size_t)(nc + 1);
if (dct_kind) ntw += 2*(size_t)(nc + 1);
if (depth == CV_32F)
fillTables<float>(ntw, need_rtw, dct_kind);
else
fillTables<double>(ntw, need_rtw, dct_kind);
// workspace layout (from the 64-byte aligned base): pair0 (re, im), optional pair1 (re, im) or
// the interleaved temp, radix-odd scratch (a[h], b[h] complex per lane).
size_t pair_bytes = 2*(size_t)nc*esz;
size_t pad = ((size_t)nc*esz & 4095) == 0 ? 64 : 0; // see im_ofs
p.im_ofs = (size_t)nc*esz + pad;
size_t pair_bytes = alignSize(2*(size_t)nc*esz + 2*pad, 64);
bool two_pairs = p.pingpong || p.need_tmp;
p.pair1_ofs = two_pairs ? pair_bytes : 0;
p.scratch_ofs = pair_bytes*(two_pairs ? 2 : 1);
size_t scratch_bytes = 4*(size_t)max_h*std::max(vl, 1)*esz;
p.ws_bytes = p.scratch_ofs + scratch_bytes + 64;
// ONE allocation for the generated tables, the permutation and (optionally) the owner's
// workspace (see the note in dxt.hpp)
size_t nitab = static_pow2 ? 0 : r0 == 1 ? 2*(size_t)nc : (size_t)nc/r0;
size_t itab_ofs = ntw*esz;
size_t ws_ofs = alignSize(itab_ofs + nitab*sizeof(int), 64);
size_t total_bytes = ws_ofs + (with_workspace ? p.ws_bytes : 0);
p.buf.allocate(total_bytes/sizeof(double) + 1);
uchar* base = (uchar*)p.buf.data();
p.workspace = with_workspace ? base + ws_ofs : 0;
// digit-reversal permutation (see dftBuildPermutation)
int seq[DFT_MAX_STAGES + 1], nseq = 0;
if (r0 > 1) seq[nseq++] = r0;
for (int s = 0; s < nst; s++) seq[nseq++] = radices[s];
if (static_pow2)
p.itab = depth == CV_32F ? getDftStaticTables<float>().gtab[dftLog2(nc)]
: getDftStaticTables<double>().gtab[dftLog2(nc)];
else
{
int* itab_ = (int*)(base + itab_ofs);
dftBuildPermutation(nc, seq, nseq, p.real_input, itab_);
p.itab = itab_;
}
// twiddle tables
if (depth == CV_32F)
fillTables<float>((float*)base, ntw, need_rtw, dct_kind, static_stages, static_rtw);
else
fillTables<double>((double*)base, ntw, need_rtw, dct_kind, static_stages, static_rtw);
// the last radix-4/8 stage of C2C / even C2R can write the interleaved scaled output directly
p.fused_last = nst > 0 && (radices[nst - 1] == 4 || radices[nst - 1] == 8) &&
(kind == DFT_KIND_C2C || (kind == DFT_KIND_C2R && nc < n));
// depth-first chunking of the leading stages (see DFT_CHUNK_BYTES)
p.nchunk_stages = 0;
{
int chunk = (int)(DFT_CHUNK_BYTES/esz);
if (nc > chunk)
{
int m = 0, avail = nst - (p.fused_last ? 1 : 0); // the fused last stage never runs chunked
while (m < avail && p.stages[m].radix*p.stages[m].span <= chunk) m++;
// chunking pays off only if at least two stages are grouped
if (m >= 2)
p.nchunk_stages = m;
}
}
}
// one stage over [i0, i0 + len) elements of the arrays (len a multiple of radix*span)
static inline void runStage(const DFTKernels& k, const DftStage& st0, int i0, int len, size_t esz,
const uchar* sre, const uchar* sim, uchar* dre, uchar* dim, uchar* scratch)
{
DftStage st = st0;
st.ngroups = len/(st.radix*st.span);
st.nsteps = st.ngroups*st.steps_per_group;
DftStageFunc fn = st.radix == 4 ? k.radix4 : st.radix == 8 ? k.radix8 : st.radix == 3 ? k.radix3 :
st.radix == 5 ? k.radix5 : k.radixOdd;
size_t ofs = (size_t)i0*esz;
fn(st, sre + ofs, sim + ofs, dre + ofs, dim + ofs, scratch);
}
// Runs the transform described by c.plan: A (preproc) -> B stages (ping-pong) -> C (postproc).
@@ -617,9 +909,9 @@ static void runDft(const OcvDftOptions& c, const void* src, size_t sstep, void*
size_t esz = p.depth == CV_32F ? sizeof(float) : sizeof(double);
uchar* base = alignPtr(c.workspace, 64);
uchar* re0 = base;
uchar* im0 = re0 + p.nc*esz;
uchar* im0 = re0 + p.im_ofs;
uchar* re1 = base + p.pair1_ofs;
uchar* im1 = re1 + p.nc*esz;
uchar* im1 = re1 + p.im_ofs;
uchar* scratch = base + p.scratch_ofs;
const void* asrc = src;
@@ -645,25 +937,57 @@ static void runDft(const OcvDftOptions& c, const void* src, size_t sstep, void*
CV_DbgAssert(astep == 1 || p.first_radix == 1);
DftPreprocFunc pre = p.first_radix == 1 ? k.preprocRadix0 : p.first_radix == 2 ? k.preprocRadix2 :
p.first_radix == 4 ? k.preprocRadix4 : k.preprocRadix8;
p.first_radix == 3 ? k.preprocRadix3 : p.first_radix == 4 ? k.preprocRadix4 :
p.first_radix == 5 ? k.preprocRadix5 : k.preprocRadix8;
pre(p, asrc, astep, re0, im0, conj);
uchar *sre = re0, *sim = im0, *dre = re1, *dim = im1;
for (int i = 0; i < p.nstages; i++)
int nstages = p.nstages - (p.fused_last ? 1 : 0);
int s = 0;
if (p.nchunk_stages > 0)
{
// the leading stages chunk by chunk; every chunk runs the same number of stages, so the
// ping-pong parity after them is the same for all chunks
int chunk = p.stages[p.nchunk_stages].span;
for (int i0 = 0; i0 < p.nc; i0 += chunk)
{
uchar *csre = sre, *csim = sim, *cdre = dre, *cdim = dim;
for (int i = 0; i < p.nchunk_stages; i++)
{
if (p.pingpong)
{
runStage(k, p.stages[i], i0, chunk, esz, csre, csim, cdre, cdim, scratch);
std::swap(csre, cdre); std::swap(csim, cdim);
}
else
runStage(k, p.stages[i], i0, chunk, esz, csre, csim, csre, csim, scratch);
}
}
if (p.pingpong && (p.nchunk_stages & 1))
{
std::swap(sre, dre); std::swap(sim, dim);
}
s = p.nchunk_stages;
}
for (; s < nstages; s++)
{
const DftStage& st = p.stages[i];
DftStageFunc fn = st.radix == 4 ? k.radix4 : st.radix == 3 ? k.radix3 :
st.radix == 5 ? k.radix5 : k.radixOdd;
if (p.pingpong)
{
fn(st, sre, sim, dre, dim, scratch);
runStage(k, p.stages[s], 0, p.nc, esz, sre, sim, dre, dim, scratch);
std::swap(sre, dre); std::swap(sim, dim);
}
else
fn(st, sre, sim, sre, sim, scratch);
runStage(k, p.stages[s], 0, p.nc, esz, sre, sim, sre, sim, scratch);
}
double scale = c.scale;
if (p.fused_last)
{
// C2C or even C2R: last radix-4/8 stage + interleave + scale, straight into dst
const DftStage& last = p.stages[p.nstages - 1];
(last.radix == 8 ? k.radix8Last : k.radix4Last)(last, sre, sim, dst, scale, c.isInverse || p.kind == DFT_KIND_C2R ? -scale : scale);
return;
}
switch (p.kind)
{
case DFT_KIND_C2C:
@@ -840,17 +1164,19 @@ copyFromColumns_( const uchar* src, size_t src_step, T* dst, int ncols, int len
}
}
// The rows are only 4-byte aligned in general (e.g. a 32FC2 ROI starting at an odd column),
// so the 8- and 16-byte elements are copied as pairs/quads of ints, not as int64.
static void
CopyFromColumns( const uchar* src, size_t src_step, uchar* dst, int ncols, int len, size_t elem_size )
{
if( elem_size == sizeof(int) )
copyFromColumns_(src, src_step, (int*)dst, ncols, len);
else if( elem_size == sizeof(int64) )
copyFromColumns_(src, src_step, (int64*)dst, ncols, len);
else if( elem_size == sizeof(int)*2 )
copyFromColumns_(src, src_step, (Vec<int, 2>*)dst, ncols, len);
else
{
CV_Assert( elem_size == sizeof(int64)*2 );
copyFromColumns_(src, src_step, (Vec<int64, 2>*)dst, ncols, len);
CV_Assert( elem_size == sizeof(int)*4 );
copyFromColumns_(src, src_step, (Vec<int, 4>*)dst, ncols, len);
}
}
@@ -872,12 +1198,12 @@ CopyToColumns( const uchar* src, uchar* dst, size_t dst_step, int ncols, int len
{
if( elem_size == sizeof(int) )
copyToColumns_((const int*)src, dst, dst_step, ncols, len);
else if( elem_size == sizeof(int64) )
copyToColumns_((const int64*)src, dst, dst_step, ncols, len);
else if( elem_size == sizeof(int)*2 )
copyToColumns_((const Vec<int, 2>*)src, dst, dst_step, ncols, len);
else
{
CV_Assert( elem_size == sizeof(int64)*2 );
copyToColumns_((const Vec<int64, 2>*)src, dst, dst_step, ncols, len);
CV_Assert( elem_size == sizeof(int)*4 );
copyToColumns_((const Vec<int, 4>*)src, dst, dst_step, ncols, len);
}
}
@@ -2016,10 +2342,9 @@ class OcvDftBasicImpl CV_FINAL : public hal::DFT1D
{
public:
OcvDftOptions opt;
// the plan is built once in init(), the workspace is allocated once here and reused by
// the plan (with the workspace inside its block) is built once in init() and reused by
// every apply() (zero allocations per transform)
DftPlan plan;
AutoBuffer<uchar> ws;
#ifdef USE_IPP_DFT
AutoBuffer<uchar> ippbuf;
AutoBuffer<uchar> ippworkbuf;
@@ -2104,11 +2429,10 @@ public:
const DFTKernels& kernels = getDFTKernels(depth);
int kind = stage == 0 && real_transform ? (opt.isInverse ? DFT_KIND_C2R : DFT_KIND_R2C)
: DFT_KIND_C2C;
plan.build(kind, len, depth, kernels.vlanes);
ws.allocate(plan.ws_bytes);
plan.build(kind, len, depth, kernels.vlanes, kernels.vlanes128, true);
opt.plan = &plan;
opt.kernels = &kernels;
opt.workspace = ws.data();
opt.workspace = plan.workspace;
if (needBuffer)
*needBuffer = false; // the engine supports in-place for every kind
}
@@ -3641,9 +3965,8 @@ class OcvDctImpl CV_FINAL : public hal::DCT2D
public:
OcvDftOptions opt;
DCTFunc dct_func;
// per-stage plan + workspace, (re)built once per stage length, never per row
// per-stage plan (+ workspace inside), (re)built once per stage length, never per row
DftPlan plan;
AutoBuffer<uchar> ws;
bool isRowTransform;
bool isInverse;
bool isContinuous;
@@ -3727,13 +4050,10 @@ public:
if( len > 1 && (len & 1) )
CV_Error( cv::Error::StsNotImplemented, "Odd-size DCT\'s are not implemented" );
if( len > 1 )
{
plan.build(isInverse ? DFT_KIND_IDCT : DFT_KIND_DCT, len, depth, kernels.vlanes);
ws.allocate(plan.ws_bytes);
}
plan.build(isInverse ? DFT_KIND_IDCT : DFT_KIND_DCT, len, depth, kernels.vlanes, kernels.vlanes128, true);
opt.plan = &plan;
opt.kernels = &kernels;
opt.workspace = ws.data();
opt.workspace = plan.workspace;
prev_len = len;
}
// otherwise reuse the plan built on the previous stage (same length, only the steps differ)