diff --git a/.gitignore b/.gitignore index f34c2100f3..9efc0854e3 100644 --- a/.gitignore +++ b/.gitignore @@ -21,7 +21,7 @@ bin/ *.suo *.log *.tlog -build +build* node_modules CMakeSettings.json xcuserdata/ diff --git a/modules/core/include/opencv2/core/utility.hpp b/modules/core/include/opencv2/core/utility.hpp index 7fd923372d..bb65211e32 100644 --- a/modules/core/include/opencv2/core/utility.hpp +++ b/modules/core/include/opencv2/core/utility.hpp @@ -183,8 +183,11 @@ protected: size_t sz; //! capacity - allocated element count (>= sz). Starts at fixed_size (the local buf), grows on demand. size_t cap; - //! pre-allocated buffer. At least 1 element to confirm C++ standard requirements - _Tp buf[(fixed_size > 0) ? fixed_size : 1]; + //! pre-allocated buffer. At least 1 element to confirm C++ standard requirements. + //! Aligned to at least 8 bytes whatever _Tp is, so that a byte buffer (AutoBuffer) + //! can hold doubles/int64 even when the local storage is used; the heap path (new _Tp[]) + //! is at least that aligned on every supported platform. + alignas(alignof(_Tp) > 8 ? alignof(_Tp) : 8) _Tp buf[(fixed_size > 0) ? fixed_size : 1]; }; /** @brief Sets/resets the break-on-error mode. diff --git a/modules/core/perf/perf_dft.cpp b/modules/core/perf/perf_dft.cpp index 589d8224ca..f1c762523e 100644 --- a/modules/core/perf/perf_dft.cpp +++ b/modules/core/perf/perf_dft.cpp @@ -7,7 +7,7 @@ using namespace perf; ///////////////////////////////////////////////////////dft////////////////////////////////////////////////////////////// #define MAT_TYPES_DFT CV_32FC1, CV_32FC2, CV_64FC1 -#define MAT_SIZES_DFT cv::Size(320, 480), cv::Size(800, 600), cv::Size(1280, 1024), sz1080p, sz2K +#define MAT_SIZES_DFT cv::Size(256, 256), cv::Size(512, 512), cv::Size(320, 480), cv::Size(800, 600), cv::Size(1280, 1024), sz1080p, sz2K CV_ENUM(FlagsType, 0, DFT_INVERSE, DFT_SCALE, DFT_COMPLEX_OUTPUT, DFT_ROWS, DFT_INVERSE|DFT_COMPLEX_OUTPUT) #define TEST_MATS_DFT testing::Combine(testing::Values(MAT_SIZES_DFT), testing::Values(MAT_TYPES_DFT), FlagsType::all(), testing::Values(true, false)) diff --git a/modules/core/src/dxt.cpp b/modules/core/src/dxt.cpp index 576b642537..5fa92a4de0 100644 --- a/modules/core/src/dxt.cpp +++ b/modules/core/src/dxt.cpp @@ -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 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 -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 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 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::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 +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(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 +static void fillRealTwiddles(const DftTwiddleGen& gen, int n, int nc, T* t) +{ + CV_DbgAssert(nc % 2 == 0); + fillTwiddles(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 struct DftStaticTables +{ + AutoBuffer tw; // stage tables, then the real twiddles + AutoBuffer 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(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(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(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 static const DftStaticTables& getDftStaticTables() +{ + static const DftStaticTables 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 +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* st_tables = static_stages || static_rtw ? &getDftStaticTables() : 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(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(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(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(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(ntw, need_rtw, dct_kind); - else - fillTables(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().gtab[dftLog2(nc)] + : getDftStaticTables().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*)base, ntw, need_rtw, dct_kind, static_stages, static_rtw); + else + fillTables((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*)dst, ncols, len); else { - CV_Assert( elem_size == sizeof(int64)*2 ); - copyFromColumns_(src, src_step, (Vec*)dst, ncols, len); + CV_Assert( elem_size == sizeof(int)*4 ); + copyFromColumns_(src, src_step, (Vec*)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*)src, dst, dst_step, ncols, len); else { - CV_Assert( elem_size == sizeof(int64)*2 ); - copyToColumns_((const Vec*)src, dst, dst_step, ncols, len); + CV_Assert( elem_size == sizeof(int)*4 ); + copyToColumns_((const Vec*)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 ws; #ifdef USE_IPP_DFT AutoBuffer ippbuf; AutoBuffer 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 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) diff --git a/modules/core/src/dxt.hpp b/modules/core/src/dxt.hpp index c0fae6c93c..4ed814e65b 100644 --- a/modules/core/src/dxt.hpp +++ b/modules/core/src/dxt.hpp @@ -7,18 +7,26 @@ // 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,4,8}. Scalar. +// 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). +// 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 @@ -38,25 +46,29 @@ enum DftKind enum DftStageMode { - DFT_STAGE_SCALAR = 0, // scalar reference loop (span < VL, no SIMD for this depth, ...) - DFT_STAGE_FULL = 1 // span >= VL: vector loop with back-off clamp (brief, section 5) + 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 or an odd number >= 7 + 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 for now) + 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[p*h + k] = cos(2*pi*(p+1)*(k+1)/radix), sn[...] = sin(...), h = (radix-1)/2 + // 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; }; @@ -68,41 +80,51 @@ struct DftPlan 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, 4 or 8: the fused first stage done in preproc + 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 - AutoBuffer itab; - AutoBuffer tw; // storage for all the tables below (type T, 8-byte aligned) - const void* rtw_re; // W_n^k = exp(-2*pi*i*k/n), k in [0, n/2]; R2C/C2R/DCT/IDCT with even n - const void* rtw_im; + // 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 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), nstages(0), rtw_re(0), rtw_im(0), - dct_re(0), dct_im(0), ws_bytes(0), pair1_ofs(0), scratch_ofs(0) {} + 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` (vector lanes) MUST come from the dispatched kernel table - // (DFTKernels::vlanes), 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 it. - void build(int kind, int n, int depth, int vl); + // 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) into `tw`; ntw = total number of T entries - template void fillTables(size_t ntw, bool need_rtw, bool need_dct); + // fills the twiddle tables (stage tables, W_n^k, DCT) at `dst`; ntw = total number of T entries + template 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 the AutoBuffers: no copies + DftPlan(const DftPlan&); // tables hold raw pointers into `buf`: no copies DftPlan& operator=(const DftPlan&); }; @@ -112,13 +134,18 @@ typedef void (*DftPreprocFunc)(const DftPlan& plan, const void* src, size_t sste // (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); @@ -127,7 +154,9 @@ struct DFTKernels // 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, radixOdd; + 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 @@ -137,6 +166,7 @@ struct DFTKernels 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::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) }; } diff --git a/modules/core/src/dxt.simd.hpp b/modules/core/src/dxt.simd.hpp index 230a790637..3166932123 100644 --- a/modules/core/src/dxt.simd.hpp +++ b/modules/core/src/dxt.simd.hpp @@ -66,23 +66,25 @@ inline v_float64 v_signmask_(bool neg, double) { return v_reinterpret_as_f64(vx_ //////////////////////////////// group A: gather + first stage //////////////////////////////// // // Two flavours: -// - preprocRadix0 (first radix 1, odd nc): table-driven scalar gather, plan.itab holds two -// element indices (re, im) per complex element; im = 0 gather when plan.real_input; -// - preprocRadix2/4/8: "transposed" first stage. The r0 inputs of group g are the elements +// - preprocRadix0 (first radix 1: odd nc without a factor 3 or 5): table-driven scalar gather, +// plan.itab holds two element indices (re, im) per complex element; im = 0 gather when +// plan.real_input; +// - preprocRadix2/3/4/5/8: "transposed" first stage. The r0 inputs of group g are the elements // x[j + q*M], M = nc/r0, q = 0..r0-1, where j = base(g) runs over [0, M) in digit-reversed // order. Iterating over j instead of g makes the loads contiguous: VL lanes load the r0 legs // with v_load_deinterleave, the r0-point DFT runs in registers, and the r0 outputs of every -// lane are stored contiguously at plan.itab[j] (= g*r0) through a 4-channel +// lane are stored contiguously at plan.itab[j] (= g*r0) through a multi-channel // v_store_interleave into a small stack buffer + short copies. plan.itab has M entries. -// The source must be interleaved complex with sstep == 1; DCT input goes through -// preprocDCT (Makhoul permutation into the temp) first. +// The source must be interleaved complex with sstep == 1 (or real samples with sstep == 1 +// when plan.real_input: R2C with odd n and r0 in {3, 5}); DCT input goes through preprocDCT +// (Makhoul permutation into the temp) first. template void preprocRadix0_(const DftPlan& plan, const void* _src, size_t sstep, void* _re, void* _im, bool conj) { const T* src = (const T*)_src; T* re = (T*)_re; T* im = (T*)_im; - const int* itab = plan.itab.data(); + const int* itab = plan.itab; int nc = plan.nc; if (plan.real_input) { @@ -119,6 +121,60 @@ static inline void firstStage2_scalar(const T* x, int M, int j, T* re, T* im, T re[1] = x0r - x1r; im[1] = x0i - x1i; } +// radix-3 and radix-5 first stages also serve R2C with odd n (real samples: x[j + q*M], im = 0) +template +static inline void firstStage3_scalar(const T* x, int M, int j, T* re, T* im, T conjsign, bool realInput) +{ + const T s120 = DftConst::sin120; + T x0r, x0i, x1r, x1i, x2r, x2i; + if (realInput) + { + x0r = x[j]; x1r = x[j+M]; x2r = x[j+2*M]; x0i = x1i = x2i = 0; + } + else + { + x0r = x[j*2]; x0i = conjsign*x[j*2+1]; + x1r = x[(j+M)*2]; x1i = conjsign*x[(j+M)*2+1]; + x2r = x[(j+2*M)*2]; x2i = conjsign*x[(j+2*M)*2+1]; + } + T sr = x1r + x2r, si = x1i + x2i; + T dr = s120*(x1r - x2r), di = s120*(x1i - x2i); + T mr = x0r - (T)0.5*sr, mi = x0i - (T)0.5*si; + re[0] = x0r + sr; im[0] = x0i + si; + re[1] = mr + di; im[1] = mi - dr; + re[2] = mr - di; im[2] = mi + dr; +} + +template +static inline void firstStage5_scalar(const T* x, int M, int j, T* re, T* im, T conjsign, bool realInput) +{ + const T c5 = DftConst::fft5_2, s1 = DftConst::sin72, s2 = DftConst::sin144; + T xr[5], xi[5]; + for (int q = 0; q < 5; q++) + { + if (realInput) + { + xr[q] = x[j + q*M]; xi[q] = 0; + } + else + { + xr[q] = x[(j + q*M)*2]; xi[q] = conjsign*x[(j + q*M)*2 + 1]; + } + } + T a1r = xr[1] + xr[4], a1i = xi[1] + xi[4], b1r = xr[1] - xr[4], b1i = xi[1] - xi[4]; + T a2r = xr[2] + xr[3], a2i = xi[2] + xi[3], b2r = xr[2] - xr[3], b2i = xi[2] - xi[3]; + T tr = xr[0] - (T)0.25*(a1r + a2r), ti = xi[0] - (T)0.25*(a1i + a2i); + T ur = c5*(a1r - a2r), ui = c5*(a1i - a2i); + T v1r = s1*b1r + s2*b2r, v1i = s1*b1i + s2*b2i; + T v2r = s2*b1r - s1*b2r, v2i = s2*b1i - s1*b2i; + T pr = tr + ur, pi = ti + ui, qr = tr - ur, qi = ti - ui; + re[0] = xr[0] + a1r + a2r; im[0] = xi[0] + a1i + a2i; + re[1] = pr + v1i; im[1] = pi - v1r; + re[4] = pr - v1i; im[4] = pi + v1r; + re[2] = qr + v2i; im[2] = qi - v2r; + re[3] = qr - v2i; im[3] = qi + v2r; +} + template static inline void firstStage4_scalar(const T* x, int M, int j, T* re, T* im, T conjsign) { @@ -202,6 +258,98 @@ static void firstStage2_vec(const T* x, int M, const int* gtab, T* re, T* im, bo firstStage2_scalar(x, M, j, re + gtab[j], im + gtab[j], conjsign); } +// real samples (plan.real_input): leg q of lanes j..j+VL-1 is x[j + q*M], im = 0 +#define DFT_LOAD_LEG_REAL(q, xr, xi) \ + xr = vx_load(x + j + (q)*M); xi = zero; + +template +static void firstStage3_vec(const T* x, int M, const int* gtab, T* re, T* im, bool conj) +{ + const int VL = VTraits::vlanes(); + [[maybe_unused]] const VT imsign = v_signmask_(conj, (T)0), zero = v_setall_((T)0); // one is unused depending on realInput + const VT s120 = v_setall_((T)DftConst::sin120), half = v_setall_((T)0.5); + T bufr[3*VTraits::max_nlanes], bufi[3*VTraits::max_nlanes]; + int j = 0; + for (; j + VL <= M; j += VL) + { + VT x0r, x0i, x1r, x1i, x2r, x2i; + if constexpr (realInput) + { + DFT_LOAD_LEG_REAL(0, x0r, x0i) + DFT_LOAD_LEG_REAL(1, x1r, x1i) + DFT_LOAD_LEG_REAL(2, x2r, x2i) + } + else + { + DFT_LOAD_LEG(0, x0r, x0i) + DFT_LOAD_LEG(1, x1r, x1i) + DFT_LOAD_LEG(2, x2r, x2i) + } + VT sr = v_add(x1r, x2r), si = v_add(x1i, x2i); + VT dr = v_mul(s120, v_sub(x1r, x2r)), di = v_mul(s120, v_sub(x1i, x2i)); + VT mr = v_sub(x0r, v_mul(half, sr)), mi = v_sub(x0i, v_mul(half, si)); + v_store_interleave(bufr, v_add(x0r, sr), v_add(mr, di), v_sub(mr, di)); + v_store_interleave(bufi, v_add(x0i, si), v_sub(mi, dr), v_add(mi, dr)); + scatterLanes(bufr, bufi, re, im, gtab + j, VL); + } + T conjsign = conj ? (T)-1 : (T)1; + for (; j < M; j++) + firstStage3_scalar(x, M, j, re + gtab[j], im + gtab[j], conjsign, realInput); +} + +template +static void firstStage5_vec(const T* x, int M, const int* gtab, T* re, T* im, bool conj) +{ + const int VL = VTraits::vlanes(); + [[maybe_unused]] const VT imsign = v_signmask_(conj, (T)0), zero = v_setall_((T)0); // one is unused depending on realInput + const VT c5 = v_setall_((T)DftConst::fft5_2), s1 = v_setall_((T)DftConst::sin72); + const VT s2 = v_setall_((T)DftConst::sin144), quarter = v_setall_((T)0.25); + // outputs 0..3 lane-major in buf (4 per lane), output 4 in buf4 + T bufr[4*VTraits::max_nlanes], bufi[4*VTraits::max_nlanes]; + T buf4r[VTraits::max_nlanes], buf4i[VTraits::max_nlanes]; + int j = 0; + for (; j + VL <= M; j += VL) + { + VT x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i, x4r, x4i; + if constexpr (realInput) + { + DFT_LOAD_LEG_REAL(0, x0r, x0i) + DFT_LOAD_LEG_REAL(1, x1r, x1i) + DFT_LOAD_LEG_REAL(2, x2r, x2i) + DFT_LOAD_LEG_REAL(3, x3r, x3i) + DFT_LOAD_LEG_REAL(4, x4r, x4i) + } + else + { + DFT_LOAD_LEG(0, x0r, x0i) + DFT_LOAD_LEG(1, x1r, x1i) + DFT_LOAD_LEG(2, x2r, x2i) + DFT_LOAD_LEG(3, x3r, x3i) + DFT_LOAD_LEG(4, x4r, x4i) + } + VT a1r = v_add(x1r, x4r), a1i = v_add(x1i, x4i), b1r = v_sub(x1r, x4r), b1i = v_sub(x1i, x4i); + VT a2r = v_add(x2r, x3r), a2i = v_add(x2i, x3i), b2r = v_sub(x2r, x3r), b2i = v_sub(x2i, x3i); + VT sar = v_add(a1r, a2r), sai = v_add(a1i, a2i); + VT tr = v_sub(x0r, v_mul(quarter, sar)), ti = v_sub(x0i, v_mul(quarter, sai)); + VT ur = v_mul(c5, v_sub(a1r, a2r)), ui = v_mul(c5, v_sub(a1i, a2i)); + VT v1r = v_fma(s1, b1r, v_mul(s2, b2r)), v1i = v_fma(s1, b1i, v_mul(s2, b2i)); + VT v2r = v_sub(v_mul(s2, b1r), v_mul(s1, b2r)), v2i = v_sub(v_mul(s2, b1i), v_mul(s1, b2i)); + VT pr = v_add(tr, ur), pi = v_add(ti, ui), qr = v_sub(tr, ur), qi = v_sub(ti, ui); + v_store_interleave(bufr, v_add(x0r, sar), v_add(pr, v1i), v_add(qr, v2i), v_sub(qr, v2i)); + v_store_interleave(bufi, v_add(x0i, sai), v_sub(pi, v1r), v_sub(qi, v2r), v_add(qi, v2r)); + v_store(buf4r, v_sub(pr, v1i)); v_store(buf4i, v_add(pi, v1r)); + for (int l = 0; l < VL; l++) + { + int base = gtab[j + l]; + memcpy(re + base, bufr + l*4, 4*sizeof(T)); re[base + 4] = buf4r[l]; + memcpy(im + base, bufi + l*4, 4*sizeof(T)); im[base + 4] = buf4i[l]; + } + } + T conjsign = conj ? (T)-1 : (T)1; + for (; j < M; j++) + firstStage5_scalar(x, M, j, re + gtab[j], im + gtab[j], conjsign, realInput); +} + template static void firstStage4_vec(const T* x, int M, const int* gtab, T* re, T* im, bool conj) { @@ -272,6 +420,7 @@ static void firstStage8_vec(const T* x, int M, const int* gtab, T* re, T* im, bo } #undef DFT_LOAD_LEG +#undef DFT_LOAD_LEG_REAL #undef DFT4_VEC #endif // CV_SIMD || CV_SIMD_SCALABLE @@ -282,7 +431,7 @@ void preprocRadix2_(const DftPlan& plan, const void* _src, size_t sstep, void* _ CV_DbgAssert(sstep == 1); CV_UNUSED(sstep); const T* x = (const T*)_src; T* re = (T*)_re; T* im = (T*)_im; - const int* gtab = plan.itab.data(); + const int* gtab = plan.itab; int M = plan.nc/2; #if (CV_SIMD || CV_SIMD_SCALABLE) if constexpr (haveSIMD) @@ -296,13 +445,63 @@ void preprocRadix2_(const DftPlan& plan, const void* _src, size_t sstep, void* _ } } +template +void preprocRadix3_(const DftPlan& plan, const void* _src, size_t sstep, void* _re, void* _im, bool conj) +{ + CV_DbgAssert(sstep == 1); CV_UNUSED(sstep); + const T* x = (const T*)_src; + T* re = (T*)_re; T* im = (T*)_im; + const int* gtab = plan.itab; + int M = plan.nc/3; +#if (CV_SIMD || CV_SIMD_SCALABLE) + if constexpr (haveSIMD) + { + if (plan.real_input) + firstStage3_vec(x, M, gtab, re, im, conj); + else + firstStage3_vec(x, M, gtab, re, im, conj); + } + else +#endif + { + T conjsign = conj ? (T)-1 : (T)1; + for (int j = 0; j < M; j++) + firstStage3_scalar(x, M, j, re + gtab[j], im + gtab[j], conjsign, plan.real_input); + } +} + +template +void preprocRadix5_(const DftPlan& plan, const void* _src, size_t sstep, void* _re, void* _im, bool conj) +{ + CV_DbgAssert(sstep == 1); CV_UNUSED(sstep); + const T* x = (const T*)_src; + T* re = (T*)_re; T* im = (T*)_im; + const int* gtab = plan.itab; + int M = plan.nc/5; +#if (CV_SIMD || CV_SIMD_SCALABLE) + if constexpr (haveSIMD) + { + if (plan.real_input) + firstStage5_vec(x, M, gtab, re, im, conj); + else + firstStage5_vec(x, M, gtab, re, im, conj); + } + else +#endif + { + T conjsign = conj ? (T)-1 : (T)1; + for (int j = 0; j < M; j++) + firstStage5_scalar(x, M, j, re + gtab[j], im + gtab[j], conjsign, plan.real_input); + } +} + template void preprocRadix4_(const DftPlan& plan, const void* _src, size_t sstep, void* _re, void* _im, bool conj) { CV_DbgAssert(sstep == 1); CV_UNUSED(sstep); const T* x = (const T*)_src; T* re = (T*)_re; T* im = (T*)_im; - const int* gtab = plan.itab.data(); + const int* gtab = plan.itab; int M = plan.nc/4; #if (CV_SIMD || CV_SIMD_SCALABLE) if constexpr (haveSIMD) @@ -322,7 +521,7 @@ void preprocRadix8_(const DftPlan& plan, const void* _src, size_t sstep, void* _ CV_DbgAssert(sstep == 1); CV_UNUSED(sstep); const T* x = (const T*)_src; T* re = (T*)_re; T* im = (T*)_im; - const int* gtab = plan.itab.data(); + const int* gtab = plan.itab; int M = plan.nc/8; #if (CV_SIMD || CV_SIMD_SCALABLE) if constexpr (haveSIMD) @@ -571,6 +770,85 @@ void radix4_scalar(const DftStage& st, const T* sre, const T* sim, T* dre, T* di } } +// last radix-4 stage fused with the output interleave and scaling (C2C, even C2R) +template +void radix4Last_scalar(const DftStage& st, const T* sre, const T* sim, T* dst, T rs, T is) +{ + const T* twr = (const T*)st.tw_re; const T* twi = (const T*)st.tw_im; + int L = st.span, G = st.ngroups, ts = st.tw_stride; + for (int g = 0; g < G; g++) + { + int base = g*4*L; + for (int j = 0; j < L; j++) + { + int i0 = base + j, i1 = i0 + L, i2 = i1 + L, i3 = i2 + L; + T x0r = sre[i0], x0i = sim[i0], x1r, x1i, x2r, x2i, x3r, x3i; + T y0r, y0i, y1r, y1i, y2r, y2i, y3r, y3i; + DFT_CMUL(x1r, x1i, sre[i1], sim[i1], twr[j], twi[j]); + DFT_CMUL(x2r, x2i, sre[i2], sim[i2], twr[ts + j], twi[ts + j]); + DFT_CMUL(x3r, x3i, sre[i3], sim[i3], twr[ts*2 + j], twi[ts*2 + j]); + DFT4_SCALAR(x0r,x0i,x1r,x1i,x2r,x2i,x3r,x3i, y0r,y0i,y1r,y1i,y2r,y2i,y3r,y3i); + dst[i0*2] = y0r*rs; dst[i0*2+1] = y0i*is; + dst[i1*2] = y1r*rs; dst[i1*2+1] = y1i*is; + dst[i2*2] = y2r*rs; dst[i2*2+1] = y2i*is; + dst[i3*2] = y3r*rs; dst[i3*2+1] = y3i*is; + } + } +} + +// radix-8 DIT stage, scalar. The odd legs (1,3,5,7) are combined first: their 4-point DFT needs +// the W8 rotations (the costly part); the even legs (0,2,4,6) are pure additions and are merged +// into the outputs as they are produced. LAST: write the interleaved, scaled output (fused last). +template +void radix8_scalar(const DftStage& st, const T* sre, const T* sim, [[maybe_unused]] T* dre, [[maybe_unused]] T* dim, + [[maybe_unused]] T* dst, [[maybe_unused]] T rs, [[maybe_unused]] T is) +{ + const T* twr = (const T*)st.tw_re; const T* twi = (const T*)st.tw_im; + int L = st.span, G = st.ngroups, ts = st.tw_stride; + const T c = DftConst::sin45; + for (int g = 0; g < G; g++) + { + int base = g*8*L; + for (int j = 0; j < L; j++) + { + int i0 = base + j, i1 = i0 + L, i2 = i1 + L, i3 = i2 + L, i4 = i3 + L, i5 = i4 + L, i6 = i5 + L, i7 = i6 + L; + T x1r, x1i, x3r, x3i, x5r, x5i, x7r, x7i; + DFT_CMUL(x1r, x1i, sre[i1], sim[i1], twr[j], twi[j]); + DFT_CMUL(x5r, x5i, sre[i5], sim[i5], twr[ts*4 + j], twi[ts*4 + j]); + DFT_CMUL(x3r, x3i, sre[i3], sim[i3], twr[ts*2 + j], twi[ts*2 + j]); + DFT_CMUL(x7r, x7i, sre[i7], sim[i7], twr[ts*6 + j], twi[ts*6 + j]); + T o0r, o0i, o1r, o1i, o2r, o2i, o3r, o3i; + DFT4_SCALAR(x1r,x1i,x3r,x3i,x5r,x5i,x7r,x7i, o0r,o0i,o1r,o1i,o2r,o2i,o3r,o3i); + // O1*W8 = c*((o1r + o1i) + i(o1i - o1r)), O3*W8^3 = c*((o3i - o3r) - i(o3r + o3i)), O2*W8^2 = (o2i, -o2r) + T s1r = o1r + o1i, s1i = o1i - o1r, s3r = o3i - o3r, s3i = o3r + o3i; + T x0r = sre[i0], x0i = sim[i0], x2r, x2i, x4r, x4i, x6r, x6i; + DFT_CMUL(x4r, x4i, sre[i4], sim[i4], twr[ts*3 + j], twi[ts*3 + j]); + DFT_CMUL(x2r, x2i, sre[i2], sim[i2], twr[ts + j], twi[ts + j]); + DFT_CMUL(x6r, x6i, sre[i6], sim[i6], twr[ts*5 + j], twi[ts*5 + j]); + T e0r, e0i, e1r, e1i, e2r, e2i, e3r, e3i; + DFT4_SCALAR(x0r,x0i,x2r,x2i,x4r,x4i,x6r,x6i, e0r,e0i,e1r,e1i,e2r,e2i,e3r,e3i); + T y0r = e0r + o0r, y0i = e0i + o0i, y4r = e0r - o0r, y4i = e0i - o0i; + T y2r = e2r + o2i, y2i = e2i - o2r, y6r = e2r - o2i, y6i = e2i + o2r; + T y1r = e1r + c*s1r, y1i = e1i + c*s1i, y5r = e1r - c*s1r, y5i = e1i - c*s1i; + T y3r = e3r + c*s3r, y3i = e3i - c*s3i, y7r = e3r - c*s3r, y7i = e3i + c*s3i; + if constexpr (LAST) + { + dst[i0*2] = y0r*rs; dst[i0*2+1] = y0i*is; dst[i1*2] = y1r*rs; dst[i1*2+1] = y1i*is; + dst[i2*2] = y2r*rs; dst[i2*2+1] = y2i*is; dst[i3*2] = y3r*rs; dst[i3*2+1] = y3i*is; + dst[i4*2] = y4r*rs; dst[i4*2+1] = y4i*is; dst[i5*2] = y5r*rs; dst[i5*2+1] = y5i*is; + dst[i6*2] = y6r*rs; dst[i6*2+1] = y6i*is; dst[i7*2] = y7r*rs; dst[i7*2+1] = y7i*is; + } + else + { + dre[i0] = y0r; dim[i0] = y0i; dre[i1] = y1r; dim[i1] = y1i; + dre[i2] = y2r; dim[i2] = y2i; dre[i3] = y3r; dim[i3] = y3i; + dre[i4] = y4r; dim[i4] = y4i; dre[i5] = y5r; dim[i5] = y5i; + dre[i6] = y6r; dim[i6] = y6i; dre[i7] = y7r; dim[i7] = y7i; + } + } + } +} + template void radix5_scalar(const DftStage& st, const T* sre, const T* sim, T* dre, T* dim) { @@ -635,9 +913,10 @@ void radixOdd_scalar(const DftStage& st, const T* sre, const T* sim, T* dre, T* for (int k = 1; k <= h; k++) { T sr = x0r, si = x0i, tr = 0, ti = 0; - for (int p = 1; p <= h; p++) + for (int p = 1, m = 0; p <= h; p++) { - T c = cs[(p-1)*h + (k-1)], s = sn[(p-1)*h + (k-1)]; + m += k; m -= m >= r ? r : 0; // m = p*k mod r + T c = cs[m], s = sn[m]; sr += c*ar[p-1]; si += c*ai[p-1]; tr += s*br[p-1]; ti += s*bi[p-1]; } @@ -652,9 +931,47 @@ void radixOdd_scalar(const DftStage& st, const T* sre, const T* sim, T* dre, T* #if (CV_SIMD || CV_SIMD_SCALABLE) +// The stage kernels are instantiated for the widest vectors (v_float32/v_float64, DFT_STAGE_FULL) +// and, on ISAs wider than 128 bits, for the 128-bit vectors too (DFT_STAGE_SIMD128: spans that +// are shorter than the wide vector but not than the narrow one). Load/broadcast by vector type: +#if CV_SIMD128 && !CV_SIMD_SCALABLE +inline v_float32x4 dft_vload(const float* p, const v_float32x4*) { return v_load(p); } +inline v_float32x4 dft_vsetall(float x, const v_float32x4*) { return v_setall_f32(x); } +#if CV_SIMD128_64F +inline v_float64x2 dft_vload(const double* p, const v_float64x2*) { return v_load(p); } +inline v_float64x2 dft_vsetall(double x, const v_float64x2*) { return v_setall_f64(x); } +#endif +#endif +#if CV_SIMD256 +inline v_float32x8 dft_vload(const float* p, const v_float32x8*) { return v256_load(p); } +inline v_float32x8 dft_vsetall(float x, const v_float32x8*) { return v256_setall_f32(x); } +#if CV_SIMD256_64F +inline v_float64x4 dft_vload(const double* p, const v_float64x4*) { return v256_load(p); } +inline v_float64x4 dft_vsetall(double x, const v_float64x4*) { return v256_setall_f64(x); } +#endif +#endif +#if CV_SIMD512 +inline v_float32x16 dft_vload(const float* p, const v_float32x16*) { return v512_load(p); } +inline v_float32x16 dft_vsetall(float x, const v_float32x16*) { return v512_setall_f32(x); } +#if CV_SIMD512_64F +inline v_float64x8 dft_vload(const double* p, const v_float64x8*) { return v512_load(p); } +inline v_float64x8 dft_vsetall(double x, const v_float64x8*) { return v512_setall_f64(x); } +#endif +#endif +#if CV_SIMD_SCALABLE +inline v_float32 dft_vload(const float* p, const v_float32*) { return vx_load(p); } +inline v_float32 dft_vsetall(float x, const v_float32*) { return vx_setall_f32(x); } +#if CV_SIMD_SCALABLE_64F +inline v_float64 dft_vload(const double* p, const v_float64*) { return vx_load(p); } +inline v_float64 dft_vsetall(double x, const v_float64*) { return vx_setall_f64(x); } +#endif +#endif +#define VLOAD(p) dft_vload((p), (const VT*)0) +#define VSETALL(x) dft_vsetall((x), (const VT*)0) + // dst = a*s + c, s is a scalar constant of the stage (the compiler hoists the broadcast) template -inline VT v_fma_n(const VT& a, T s, const VT& c) { return v_fma(a, v_setall_(s), c); } +inline VT v_fma_n(const VT& a, T s, const VT& c) { return v_fma(a, dft_vsetall(s, (const VT*)0), c); } // (xr, xi) = (ar, ai) * (wr, wi) #define DFT_VCMUL(xr, xi, ar, ai, wr, wi) \ @@ -678,12 +995,12 @@ void radix3_vec(const DftStage& st, const T* sre, const T* sim, T* dre, T* dim) { const T* twr = (const T*)st.tw_re; const T* twi = (const T*)st.tw_im; const int L = st.span, ts = st.tw_stride, VL = VTraits::vlanes(); - const VT s120 = v_setall_((T)DftConst::sin120), half = v_setall_((T)0.5); + const VT s120 = VSETALL((T)DftConst::sin120), half = VSETALL((T)0.5); DFT_VLOOP_BEGIN(3) int i0 = base + j, i1 = i0 + L, i2 = i1 + L; - VT x0r = vx_load(sre + i0), x0i = vx_load(sim + i0), x1r, x1i, x2r, x2i; - DFT_VCMUL(x1r, x1i, vx_load(sre + i1), vx_load(sim + i1), vx_load(twr + j), vx_load(twi + j)); - DFT_VCMUL(x2r, x2i, vx_load(sre + i2), vx_load(sim + i2), vx_load(twr + ts + j), vx_load(twi + ts + j)); + VT x0r = VLOAD(sre + i0), x0i = VLOAD(sim + i0), x1r, x1i, x2r, x2i; + DFT_VCMUL(x1r, x1i, VLOAD(sre + i1), VLOAD(sim + i1), VLOAD(twr + j), VLOAD(twi + j)); + DFT_VCMUL(x2r, x2i, VLOAD(sre + i2), VLOAD(sim + i2), VLOAD(twr + ts + j), VLOAD(twi + ts + j)); VT sr = v_add(x1r, x2r), si = v_add(x1i, x2i); VT dr = v_mul(s120, v_sub(x1r, x2r)), di = v_mul(s120, v_sub(x1i, x2i)); VT mr = v_sub(x0r, v_mul(half, sr)), mi = v_sub(x0i, v_mul(half, si)); @@ -700,10 +1017,10 @@ void radix4_vec(const DftStage& st, const T* sre, const T* sim, T* dre, T* dim) const int L = st.span, ts = st.tw_stride, VL = VTraits::vlanes(); DFT_VLOOP_BEGIN(4) int i0 = base + j, i1 = i0 + L, i2 = i1 + L, i3 = i2 + L; - VT x0r = vx_load(sre + i0), x0i = vx_load(sim + i0), x1r, x1i, x2r, x2i, x3r, x3i; - DFT_VCMUL(x1r, x1i, vx_load(sre + i1), vx_load(sim + i1), vx_load(twr + j), vx_load(twi + j)); - DFT_VCMUL(x2r, x2i, vx_load(sre + i2), vx_load(sim + i2), vx_load(twr + ts + j), vx_load(twi + ts + j)); - DFT_VCMUL(x3r, x3i, vx_load(sre + i3), vx_load(sim + i3), vx_load(twr + ts*2 + j), vx_load(twi + ts*2 + j)); + VT x0r = VLOAD(sre + i0), x0i = VLOAD(sim + i0), x1r, x1i, x2r, x2i, x3r, x3i; + DFT_VCMUL(x1r, x1i, VLOAD(sre + i1), VLOAD(sim + i1), VLOAD(twr + j), VLOAD(twi + j)); + DFT_VCMUL(x2r, x2i, VLOAD(sre + i2), VLOAD(sim + i2), VLOAD(twr + ts + j), VLOAD(twi + ts + j)); + DFT_VCMUL(x3r, x3i, VLOAD(sre + i3), VLOAD(sim + i3), VLOAD(twr + ts*2 + j), VLOAD(twi + ts*2 + j)); VT y0r = v_add(x0r, x2r), y0i = v_add(x0i, x2i), y1r = v_sub(x0r, x2r), y1i = v_sub(x0i, x2i); VT y2r = v_add(x1r, x3r), y2i = v_add(x1i, x3i), y3r = v_sub(x1r, x3r), y3i = v_sub(x1i, x3i); v_store(dre + i0, v_add(y0r, y2r)); v_store(dim + i0, v_add(y0i, y2i)); @@ -713,27 +1030,112 @@ void radix4_vec(const DftStage& st, const T* sre, const T* sim, T* dre, T* dim) DFT_VLOOP_END(4) } +// last radix-4 stage + interleave + scale into the (interleaved complex) output; always +// out-of-place, so the back-off clamp is harmless (overlapping lanes store identical values) +template +void radix4Last_vec(const DftStage& st, const T* sre, const T* sim, T* dst, T rs, T is) +{ + const T* twr = (const T*)st.tw_re; const T* twi = (const T*)st.tw_im; + const int L = st.span, ts = st.tw_stride, VL = VTraits::vlanes(); + const VT vrs = VSETALL(rs), vis = VSETALL(is); + DFT_VLOOP_BEGIN(4) + int i0 = base + j, i1 = i0 + L, i2 = i1 + L, i3 = i2 + L; + VT x0r = VLOAD(sre + i0), x0i = VLOAD(sim + i0), x1r, x1i, x2r, x2i, x3r, x3i; + DFT_VCMUL(x1r, x1i, VLOAD(sre + i1), VLOAD(sim + i1), VLOAD(twr + j), VLOAD(twi + j)); + DFT_VCMUL(x2r, x2i, VLOAD(sre + i2), VLOAD(sim + i2), VLOAD(twr + ts + j), VLOAD(twi + ts + j)); + DFT_VCMUL(x3r, x3i, VLOAD(sre + i3), VLOAD(sim + i3), VLOAD(twr + ts*2 + j), VLOAD(twi + ts*2 + j)); + VT y0r = v_add(x0r, x2r), y0i = v_add(x0i, x2i), y1r = v_sub(x0r, x2r), y1i = v_sub(x0i, x2i); + VT y2r = v_add(x1r, x3r), y2i = v_add(x1i, x3i), y3r = v_sub(x1r, x3r), y3i = v_sub(x1i, x3i); + v_store_interleave(dst + i0*2, v_mul(v_add(y0r, y2r), vrs), v_mul(v_add(y0i, y2i), vis)); + v_store_interleave(dst + i2*2, v_mul(v_sub(y0r, y2r), vrs), v_mul(v_sub(y0i, y2i), vis)); + v_store_interleave(dst + i1*2, v_mul(v_add(y1r, y3i), vrs), v_mul(v_sub(y1i, y3r), vis)); + v_store_interleave(dst + i3*2, v_mul(v_sub(y1r, y3i), vrs), v_mul(v_add(y1i, y3r), vis)); + DFT_VLOOP_END(4) +} + +// radix-8 DIT stage, vector (see radix8_scalar for the structure). Odd legs first (4-point DFT + +// W8 rotations: the rotated values are kept as the sums s = (o1r+o1i, ...) and folded into the +// outputs with FMAs by +-sin45, as in FFTW's t1fv_8), then the even legs, whose pure additions +// go straight into the outputs. Peak live set is ~18 vectors (odd results 8 + even inputs 8 + +// temporaries), so a couple of spills are expected on 16-register ISAs; still one pass over the +// data instead of two radix-4 passes. LAST: fused interleave + scale into the user output. +template +void radix8_vec(const DftStage& st, const T* sre, const T* sim, T* dre, T* dim, T* dst, T rs, T is) +{ + const T* twr = (const T*)st.tw_re; const T* twi = (const T*)st.tw_im; + const int L = st.span, ts = st.tw_stride, VL = VTraits::vlanes(); + const VT c = VSETALL((T)DftConst::sin45), nc = VSETALL((T)-DftConst::sin45); + const VT vrs = VSETALL(rs), vis = VSETALL(is); + auto store = [&](int i, const VT& yr, const VT& yi) + { + if constexpr (LAST) + v_store_interleave(dst + i*2, v_mul(yr, vrs), v_mul(yi, vis)); + else + { + v_store(dre + i, yr); v_store(dim + i, yi); + } + }; + DFT_VLOOP_BEGIN(8) + int i0 = base + j, i1 = i0 + L, i2 = i1 + L, i3 = i2 + L, i4 = i3 + L, i5 = i4 + L, i6 = i5 + L, i7 = i6 + L; + // odd legs: b1 = x1 + x5, b5 = x1 - x5, b3 = x3 + x7, b7 = x3 - x7 + VT x1r, x1i, x5r, x5i, x3r, x3i, x7r, x7i; + DFT_VCMUL(x1r, x1i, VLOAD(sre + i1), VLOAD(sim + i1), VLOAD(twr + j), VLOAD(twi + j)); + DFT_VCMUL(x5r, x5i, VLOAD(sre + i5), VLOAD(sim + i5), VLOAD(twr + ts*4 + j), VLOAD(twi + ts*4 + j)); + VT b1r = v_add(x1r, x5r), b1i = v_add(x1i, x5i), b5r = v_sub(x1r, x5r), b5i = v_sub(x1i, x5i); + DFT_VCMUL(x3r, x3i, VLOAD(sre + i3), VLOAD(sim + i3), VLOAD(twr + ts*2 + j), VLOAD(twi + ts*2 + j)); + DFT_VCMUL(x7r, x7i, VLOAD(sre + i7), VLOAD(sim + i7), VLOAD(twr + ts*6 + j), VLOAD(twi + ts*6 + j)); + VT b3r = v_add(x3r, x7r), b3i = v_add(x3i, x7i), b7r = v_sub(x3r, x7r), b7i = v_sub(x3i, x7i); + // 4-point DFT of the odd legs: O0 = b1 + b3, O2 = b1 - b3, O1 = b5 - i*b7, O3 = b5 + i*b7; + // O1*W8 = c*(s1r + i*s1i), O3*W8^3 = c*(s3r - i*s3i), O2*W8^2 = (o2i, -o2r) + VT o0r = v_add(b1r, b3r), o0i = v_add(b1i, b3i), o2r = v_sub(b1r, b3r), o2i = v_sub(b1i, b3i); + VT o1r = v_add(b5r, b7i), o1i = v_sub(b5i, b7r), o3r = v_sub(b5r, b7i), o3i = v_add(b5i, b7r); + VT s1r = v_add(o1r, o1i), s1i = v_sub(o1i, o1r), s3r = v_sub(o3i, o3r), s3i = v_add(o3r, o3i); + // even legs: a0 = x0 + x4, a4 = x0 - x4, a2 = x2 + x6, a6 = x2 - x6 + VT x0r = VLOAD(sre + i0), x0i = VLOAD(sim + i0), x4r, x4i; + DFT_VCMUL(x4r, x4i, VLOAD(sre + i4), VLOAD(sim + i4), VLOAD(twr + ts*3 + j), VLOAD(twi + ts*3 + j)); + VT a0r = v_add(x0r, x4r), a0i = v_add(x0i, x4i), a4r = v_sub(x0r, x4r), a4i = v_sub(x0i, x4i); + VT x2r, x2i, x6r, x6i; + DFT_VCMUL(x2r, x2i, VLOAD(sre + i2), VLOAD(sim + i2), VLOAD(twr + ts + j), VLOAD(twi + ts + j)); + DFT_VCMUL(x6r, x6i, VLOAD(sre + i6), VLOAD(sim + i6), VLOAD(twr + ts*5 + j), VLOAD(twi + ts*5 + j)); + VT a2r = v_add(x2r, x6r), a2i = v_add(x2i, x6i), a6r = v_sub(x2r, x6r), a6i = v_sub(x2i, x6i); + // E0 = a0 + a2 -> y0, y4; E2 = a0 - a2 -> y2, y6 (with O2*W8^2) + VT e0r = v_add(a0r, a2r), e0i = v_add(a0i, a2i); + store(i0, v_add(e0r, o0r), v_add(e0i, o0i)); + store(i4, v_sub(e0r, o0r), v_sub(e0i, o0i)); + VT e2r = v_sub(a0r, a2r), e2i = v_sub(a0i, a2i); + store(i2, v_add(e2r, o2i), v_sub(e2i, o2r)); + store(i6, v_sub(e2r, o2i), v_add(e2i, o2r)); + // E1 = a4 - i*a6 -> y1, y5 (+- c*s1); E3 = a4 + i*a6 -> y3, y7 (+- c*(s3r, -s3i)) + VT e1r = v_add(a4r, a6i), e1i = v_sub(a4i, a6r); + store(i1, v_fma(s1r, c, e1r), v_fma(s1i, c, e1i)); + store(i5, v_fma(s1r, nc, e1r), v_fma(s1i, nc, e1i)); + VT e3r = v_sub(a4r, a6i), e3i = v_add(a4i, a6r); + store(i3, v_fma(s3r, c, e3r), v_fma(s3i, nc, e3i)); + store(i7, v_fma(s3r, nc, e3r), v_fma(s3i, c, e3i)); + DFT_VLOOP_END(8) +} + template void radix5_vec(const DftStage& st, const T* sre, const T* sim, T* dre, T* dim) { const T* twr = (const T*)st.tw_re; const T* twi = (const T*)st.tw_im; const int L = st.span, ts = st.tw_stride, VL = VTraits::vlanes(); const T c5 = DftConst::fft5_2, s1 = DftConst::sin72, s2 = DftConst::sin144; - const VT quarter = v_setall_((T)0.25); + const VT quarter = VSETALL((T)0.25); DFT_VLOOP_BEGIN(5) int i0 = base + j, i1 = i0 + L, i2 = i1 + L, i3 = i2 + L, i4 = i3 + L; - VT x0r = vx_load(sre + i0), x0i = vx_load(sim + i0), x1r, x1i, x2r, x2i, x3r, x3i, x4r, x4i; - DFT_VCMUL(x1r, x1i, vx_load(sre + i1), vx_load(sim + i1), vx_load(twr + j), vx_load(twi + j)); - DFT_VCMUL(x2r, x2i, vx_load(sre + i2), vx_load(sim + i2), vx_load(twr + ts + j), vx_load(twi + ts + j)); - DFT_VCMUL(x3r, x3i, vx_load(sre + i3), vx_load(sim + i3), vx_load(twr + ts*2 + j), vx_load(twi + ts*2 + j)); - DFT_VCMUL(x4r, x4i, vx_load(sre + i4), vx_load(sim + i4), vx_load(twr + ts*3 + j), vx_load(twi + ts*3 + j)); + VT x0r = VLOAD(sre + i0), x0i = VLOAD(sim + i0), x1r, x1i, x2r, x2i, x3r, x3i, x4r, x4i; + DFT_VCMUL(x1r, x1i, VLOAD(sre + i1), VLOAD(sim + i1), VLOAD(twr + j), VLOAD(twi + j)); + DFT_VCMUL(x2r, x2i, VLOAD(sre + i2), VLOAD(sim + i2), VLOAD(twr + ts + j), VLOAD(twi + ts + j)); + DFT_VCMUL(x3r, x3i, VLOAD(sre + i3), VLOAD(sim + i3), VLOAD(twr + ts*2 + j), VLOAD(twi + ts*2 + j)); + DFT_VCMUL(x4r, x4i, VLOAD(sre + i4), VLOAD(sim + i4), VLOAD(twr + ts*3 + j), VLOAD(twi + ts*3 + j)); VT a1r = v_add(x1r, x4r), a1i = v_add(x1i, x4i), b1r = v_sub(x1r, x4r), b1i = v_sub(x1i, x4i); VT a2r = v_add(x2r, x3r), a2i = v_add(x2i, x3i), b2r = v_sub(x2r, x3r), b2i = v_sub(x2i, x3i); VT sar = v_add(a1r, a2r), sai = v_add(a1i, a2i); VT tr = v_sub(x0r, v_mul(quarter, sar)), ti = v_sub(x0i, v_mul(quarter, sai)); - VT ur = v_mul(v_setall_(c5), v_sub(a1r, a2r)), ui = v_mul(v_setall_(c5), v_sub(a1i, a2i)); - VT v1r = v_fma_n(b1r, s1, v_mul(v_setall_(s2), b2r)), v1i = v_fma_n(b1i, s1, v_mul(v_setall_(s2), b2i)); - VT v2r = v_fma_n(b1r, s2, v_mul(v_setall_(-s1), b2r)), v2i = v_fma_n(b1i, s2, v_mul(v_setall_(-s1), b2i)); + VT ur = v_mul(VSETALL(c5), v_sub(a1r, a2r)), ui = v_mul(VSETALL(c5), v_sub(a1i, a2i)); + VT v1r = v_fma_n(b1r, s1, v_mul(VSETALL(s2), b2r)), v1i = v_fma_n(b1i, s1, v_mul(VSETALL(s2), b2i)); + VT v2r = v_fma_n(b1r, s2, v_mul(VSETALL(-s1), b2r)), v2i = v_fma_n(b1i, s2, v_mul(VSETALL(-s1), b2i)); VT pr = v_add(tr, ur), pi = v_add(ti, ui), qr = v_sub(tr, ur), qi = v_sub(ti, ui); v_store(dre + i0, v_add(x0r, sar)); v_store(dim + i0, v_add(x0i, sai)); v_store(dre + i1, v_add(pr, v1i)); v_store(dim + i1, v_sub(pi, v1r)); @@ -754,16 +1156,16 @@ void radixOdd_vec(const DftStage& st, const T* sre, const T* sim, T* dre, T* dim T* ar = scratch; T* ai = ar + h*VL; T* br = ai + h*VL; T* bi = br + h*VL; DFT_VLOOP_BEGIN(r) int i0 = base + j; - VT x0r = vx_load(sre + i0), x0i = vx_load(sim + i0); + VT x0r = VLOAD(sre + i0), x0i = VLOAD(sim + i0); VT X0r = x0r, X0i = x0i; for (int p = 1; p <= h; p++) { int ip = i0 + p*L, iq = i0 + (r-p)*L; VT xpr, xpi, xqr, xqi; - DFT_VCMUL(xpr, xpi, vx_load(sre + ip), vx_load(sim + ip), - vx_load(twr + (p-1)*ts + j), vx_load(twi + (p-1)*ts + j)); - DFT_VCMUL(xqr, xqi, vx_load(sre + iq), vx_load(sim + iq), - vx_load(twr + (r-p-1)*ts + j), vx_load(twi + (r-p-1)*ts + j)); + DFT_VCMUL(xpr, xpi, VLOAD(sre + ip), VLOAD(sim + ip), + VLOAD(twr + (p-1)*ts + j), VLOAD(twi + (p-1)*ts + j)); + DFT_VCMUL(xqr, xqi, VLOAD(sre + iq), VLOAD(sim + iq), + VLOAD(twr + (r-p-1)*ts + j), VLOAD(twi + (r-p-1)*ts + j)); VT apr = v_add(xpr, xqr), api = v_add(xpi, xqi); v_store(ar + (p-1)*VL, apr); v_store(ai + (p-1)*VL, api); v_store(br + (p-1)*VL, v_sub(xpr, xqr)); v_store(bi + (p-1)*VL, v_sub(xpi, xqi)); @@ -772,12 +1174,16 @@ void radixOdd_vec(const DftStage& st, const T* sre, const T* sim, T* dre, T* dim v_store(dre + i0, X0r); v_store(dim + i0, X0i); for (int k = 1; k <= h; k++) { - VT sr = x0r, si = x0i, tr = v_setall_((T)0), ti = tr; - for (int p = 1; p <= h; p++) + VT sr = x0r, si = x0i, tr = VSETALL((T)0), ti = tr; + for (int p = 1, m = 0; p <= h; p++) { - T c = cs[(p-1)*h + (k-1)], s = sn[(p-1)*h + (k-1)]; - sr = v_fma_n(vx_load(ar + (p-1)*VL), c, sr); si = v_fma_n(vx_load(ai + (p-1)*VL), c, si); - tr = v_fma_n(vx_load(br + (p-1)*VL), s, tr); ti = v_fma_n(vx_load(bi + (p-1)*VL), s, ti); + m += k; m -= m >= r ? r : 0; // m = p*k mod r + // explicit VT broadcasts rather than v_fma_n(.., cs[m], ..): MSVC 19.29 (VS 2019 16.11) + // with /arch:AVX2 unrolls this loop by 4 and then feeds two of the four accumulators + // with the broadcast of the last unrolled iteration only (wrong results for h >= 4) + VT c = VSETALL(cs[m]), s = VSETALL(sn[m]); + sr = v_fma(VLOAD(ar + (p-1)*VL), c, sr); si = v_fma(VLOAD(ai + (p-1)*VL), c, si); + tr = v_fma(VLOAD(br + (p-1)*VL), s, tr); ti = v_fma(VLOAD(bi + (p-1)*VL), s, ti); } v_store(dre + i0 + k*L, v_add(sr, ti)); v_store(dim + i0 + k*L, v_sub(si, tr)); v_store(dre + i0 + (r-k)*L, v_sub(sr, ti)); v_store(dim + i0 + (r-k)*L, v_add(si, tr)); @@ -788,11 +1194,13 @@ void radixOdd_vec(const DftStage& st, const T* sre, const T* sim, T* dre, T* dim #undef DFT_VLOOP_BEGIN #undef DFT_VLOOP_END #undef DFT_VCMUL +#undef VLOAD +#undef VSETALL #endif // CV_SIMD || CV_SIMD_SCALABLE // entry points: the plan's stage mode selects the body; VT = T (no SIMD for this type) means scalar only -template +template void radix3_(const DftStage& st, const void* sre, const void* sim, void* dre, void* dim, void*) { #if (CV_SIMD || CV_SIMD_SCALABLE) @@ -803,12 +1211,17 @@ void radix3_(const DftStage& st, const void* sre, const void* sim, void* dre, vo radix3_vec(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim); return; } + if (st.mode == DFT_STAGE_SIMD128) + { + radix3_vec(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim); + return; + } } #endif radix3_scalar(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim); } -template +template void radix4_(const DftStage& st, const void* sre, const void* sim, void* dre, void* dim, void*) { #if (CV_SIMD || CV_SIMD_SCALABLE) @@ -819,12 +1232,17 @@ void radix4_(const DftStage& st, const void* sre, const void* sim, void* dre, vo radix4_vec(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim); return; } + if (st.mode == DFT_STAGE_SIMD128) + { + radix4_vec(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim); + return; + } } #endif radix4_scalar(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim); } -template +template void radix5_(const DftStage& st, const void* sre, const void* sim, void* dre, void* dim, void*) { #if (CV_SIMD || CV_SIMD_SCALABLE) @@ -835,13 +1253,18 @@ void radix5_(const DftStage& st, const void* sre, const void* sim, void* dre, vo radix5_vec(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim); return; } + if (st.mode == DFT_STAGE_SIMD128) + { + radix5_vec(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim); + return; + } } #endif radix5_scalar(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim); } -template +template void radixOdd_(const DftStage& st, const void* sre, const void* sim, void* dre, void* dim, void* scratch) { #if (CV_SIMD || CV_SIMD_SCALABLE) @@ -852,11 +1275,82 @@ void radixOdd_(const DftStage& st, const void* sre, const void* sim, void* dre, radixOdd_vec(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim, (T*)scratch); return; } + if (st.mode == DFT_STAGE_SIMD128) + { + // the scratch is sized for the wide lanes, which is enough for the narrow ones + radixOdd_vec(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim, (T*)scratch); + return; + } } #endif radixOdd_scalar(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim, (T*)scratch); } +template +void radix4Last_(const DftStage& st, const void* sre, const void* sim, void* dst, double re_scale, double im_scale) +{ + T rs = (T)re_scale, is = (T)im_scale; +#if (CV_SIMD || CV_SIMD_SCALABLE) + if constexpr (haveSIMD) + { + if (st.mode == DFT_STAGE_FULL) + { + radix4Last_vec(st, (const T*)sre, (const T*)sim, (T*)dst, rs, is); + return; + } + if (st.mode == DFT_STAGE_SIMD128) + { + radix4Last_vec(st, (const T*)sre, (const T*)sim, (T*)dst, rs, is); + return; + } + } +#endif + radix4Last_scalar(st, (const T*)sre, (const T*)sim, (T*)dst, rs, is); +} + + +template +void radix8_(const DftStage& st, const void* sre, const void* sim, void* dre, void* dim, void*) +{ +#if (CV_SIMD || CV_SIMD_SCALABLE) + if constexpr (haveSIMD) + { + if (st.mode == DFT_STAGE_FULL) + { + radix8_vec(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim, 0, (T)0, (T)0); + return; + } + if (st.mode == DFT_STAGE_SIMD128) + { + radix8_vec(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim, 0, (T)0, (T)0); + return; + } + } +#endif + radix8_scalar(st, (const T*)sre, (const T*)sim, (T*)dre, (T*)dim, 0, (T)0, (T)0); +} + +template +void radix8Last_(const DftStage& st, const void* sre, const void* sim, void* dst, double re_scale, double im_scale) +{ + T rs = (T)re_scale, is = (T)im_scale; +#if (CV_SIMD || CV_SIMD_SCALABLE) + if constexpr (haveSIMD) + { + if (st.mode == DFT_STAGE_FULL) + { + radix8_vec(st, (const T*)sre, (const T*)sim, 0, 0, (T*)dst, rs, is); + return; + } + if (st.mode == DFT_STAGE_SIMD128) + { + radix8_vec(st, (const T*)sre, (const T*)sim, 0, 0, (T*)dst, rs, is); + return; + } + } +#endif + radix8_scalar(st, (const T*)sre, (const T*)sim, 0, 0, (T*)dst, rs, is); +} //////////////////////////////// group C: postprocessing //////////////////////////////// // @@ -1108,30 +1602,38 @@ void postprocIDCT_(const DftPlan& plan, const void* _re, const void* _im, void* #undef DFT4_SCALAR -template +template DFTKernels makeKernels() { DFTKernels k; k.preprocRadix0 = preprocRadix0_; k.preprocRadix2 = preprocRadix2_; + k.preprocRadix3 = preprocRadix3_; k.preprocRadix4 = preprocRadix4_; + k.preprocRadix5 = preprocRadix5_; k.preprocRadix8 = preprocRadix8_; k.preprocDCT = preprocDCT_; k.preprocCCS = preprocCCS_; k.preprocIDCT = preprocIDCT_; - k.radix3 = radix3_; - k.radix4 = radix4_; - k.radix5 = radix5_; - k.radixOdd = radixOdd_; + k.radix3 = radix3_; + k.radix4 = radix4_; + k.radix5 = radix5_; + k.radixOdd = radixOdd_; + k.radix4Last = radix4Last_; + k.radix8 = radix8_; + k.radix8Last = radix8Last_; k.postprocDFT = postprocDFT_; k.postprocRealDFT = postprocRealDFT_; k.postprocReal = postprocReal_; k.postprocDCT = postprocDCT_; k.postprocIDCT = postprocIDCT_; if constexpr (haveSIMD) + { k.vlanes = VTraits::vlanes(); + k.vlanes128 = VTraits::vlanes(); + } else - k.vlanes = 1; + k.vlanes = k.vlanes128 = 1; return k; } @@ -1139,19 +1641,29 @@ DFTKernels makeKernels() DFTKernels getDFTKernels_(int depth) { + // the 128-bit types exist alongside the wide ones on all fixed-width ISAs (not with scalable + // vectors); they are the same type as the wide ones on 128-bit ISAs if (depth == CV_32F) { #if (CV_SIMD || CV_SIMD_SCALABLE) - return makeKernels(); +#if CV_SIMD128 && !CV_SIMD_SCALABLE + return makeKernels(); #else - return makeKernels(); + return makeKernels(); +#endif +#else + return makeKernels(); #endif } CV_Assert(depth == CV_64F); #if (CV_SIMD_64F || CV_SIMD_SCALABLE_64F) - return makeKernels(); +#if CV_SIMD128_64F && !CV_SIMD_SCALABLE + return makeKernels(); #else - return makeKernels(); + return makeKernels(); +#endif +#else + return makeKernels(); #endif } diff --git a/modules/core/test/test_dxt.cpp b/modules/core/test/test_dxt.cpp index 8c02a47978..cc65a153bc 100644 --- a/modules/core/test/test_dxt.cpp +++ b/modules/core/test/test_dxt.cpp @@ -1311,7 +1311,8 @@ static std::vector dxtSweepSizes() if (m == 1) sizes.push_back(n); } - static const int extra[] = { 7, 11, 13, 14, 21, 22, 26, 49, 77, 98, 121, 143, 154, 242, 338, 1001, 2018 }; + // odd and prime lengths (generic odd radix, r0 = 1/3/5 first stages, radix >= 127 tables) + static const int extra[] = { 7, 11, 13, 14, 21, 22, 26, 49, 57, 77, 98, 121, 143, 154, 242, 257, 284, 338, 1001, 1009, 1136, 2018 }; for (size_t i = 0; i < sizeof(extra)/sizeof(extra[0]); i++) sizes.push_back(extra[i]); return sizes;