108#include <type_traits>
117#if !defined(DSPARK_NO_EXCEPTIONS)
118 #if (defined(__GNUC__) || defined(__clang__)) && !defined(__EXCEPTIONS)
119 #define DSPARK_NO_EXCEPTIONS 1
120 #elif defined(_MSC_VER) && !defined(_CPPUNWIND)
121 #define DSPARK_NO_EXCEPTIONS 1
125#if !defined(DSPARK_NO_EXCEPTIONS)
153 [[nodiscard]]
static constexpr size_t firstBlock(
size_t n1,
size_t block)
noexcept
155 return n1 < block ? n1 : block;
162 [[nodiscard]]
static constexpr size_t index(
size_t stride,
size_t block,
size_t row,
size_t p)
noexcept
164 if (stride != 1)
return 6 * p + row;
165 const size_t l = p & (block - 1);
166 return 6 * (p - l) + row * block + l;
183#if defined(_M_AMD64) || defined(_M_X64) || defined(__x86_64__) || defined(__amd64__) \
184 || defined(_M_IX86) || defined(__i386__) || defined(__EMSCRIPTEN__)
199#if defined(DSPARK_SIMD_NEON) && !defined(__APPLE__)
219#if (defined(DSPARK_SIMD_SSE2) && !defined(DSPARK_SIMD_AVX)) || defined(DSPARK_SIMD_NEON)
234inline constexpr size_t kRealHalvesReach =
sizeof(T) ==
sizeof(
float) ? ~size_t{ 0 } :
size_t{ 2048 };
277 [[nodiscard]]
static constexpr size_t passValues(
size_t m,
size_t repeat)
noexcept
279 return 6 * repeat * (m / 2 - 1);
292 [[nodiscard]]
static constexpr bool halvesFor(
size_t size,
size_t lanes,
size_t reach)
noexcept
294 return lanes *
sizeof(T) == 32 && size <= reach;
302 [[nodiscard]]
static constexpr size_t laneBin(
size_t lanes,
size_t p,
bool byHalves)
noexcept
304 if (!byHalves)
return p;
305 const size_t run =
lanes / 4;
306 const size_t order[4] = { 0, 2, 1, 3 };
307 return run * order[p / run] + p % run;
312 [[nodiscard]]
static constexpr size_t passCount(
size_t n)
noexcept
314 return static_cast<size_t>(std::countr_zero(
n)) / 2;
320using plan::TwiddleSpan;
329template <
typename T>
inline constexpr size_t kBlock = std::is_same_v<T, double> ? 4 : 8;
332template <
typename T,
int W>
using Vec = simd::Vec<T, W>;
333template <
typename T>
inline constexpr int kWide = simd::kVecWidth<T>;
334template <
typename T>
inline constexpr int kNarrow = simd::kVecNarrowWidth<T>;
335#include "detail/FftKernels.inl"
341#if defined(DSPARK_SIMD_DISPATCH_AVX2)
343DSPARK_SIMD_AVX2_BEGIN
348template <
typename T,
int W>
using Vec = simd::avx2::Vec<T, W>;
349template <
typename T>
inline constexpr int kWide = simd::avx2::kVecWidth<T>;
350template <
typename T>
inline constexpr int kNarrow = simd::avx2::kVecNarrowWidth<T>;
351#include "detail/FftKernels.inl"
388 : count_(count), storage_(
values(count), T(0)), lead_(leadOf(storage_.data()))
393 : count_(other.count_), storage_(other.storage_.size(), T(0)), lead_(leadOf(storage_.data()))
396 std::copy_n(other.
first(), stride(count_) + count_,
first());
400 : count_(std::exchange(other.count_,
size_t{ 0 })), storage_(std::move(other.storage_)),
401 lead_(std::exchange(other.lead_,
size_t{ 0 }))
407 std::swap(count_, other.count_);
408 storage_.swap(other.storage_);
409 std::swap(lead_, other.lead_);
413 [[nodiscard]] T*
first() noexcept {
return storage_.data() + lead_; }
414 [[nodiscard]]
const T*
first() const noexcept {
return storage_.data() + lead_; }
415 [[nodiscard]] T*
second() noexcept {
return first() + stride(count_); }
416 [[nodiscard]]
const T*
second() const noexcept {
return first() + stride(count_); }
421 [[nodiscard]]
static constexpr size_t values(
size_t count)
noexcept
423 return (kLine - 1) + stride(count) + count;
427 static constexpr size_t kLine = 64 /
sizeof(T);
429 static constexpr size_t stride(
size_t count)
noexcept
431 return (count + kLine - 1) / kLine * kLine;
435 static size_t leadOf(
const T* data)
noexcept
437 const auto address =
reinterpret_cast<std::uintptr_t
>(data);
438 return static_cast<size_t>((64 - address % 64) % 64) /
sizeof(T);
442 std::vector<T> storage_;
459 explicit SplitFFT(
size_t n,
bool interleavedInput =
false) : n_(n), work_(2 * n)
463 const size_t passCount = buildPlan(n_, steps, offset);
464 passes_.assign(steps.begin(), steps.begin() +
static_cast<std::ptrdiff_t
>(passCount));
466 twiddles_.assign(offset, T(0));
467 for (
const Pass& pass : passes_)
469 if (pass.radix2 || pass.radix8)
continue;
475 constexpr size_t lanes =
static_cast<size_t>(kWide<T>);
476 T*
const w = twiddles_.data() + pass.twOffset;
477 for (
size_t p = 0; p < pass.len / 8; ++p)
479 const double a = -2.0 * std::numbers::pi_v<double> *
static_cast<double>(p)
480 /
static_cast<double>(pass.len);
481 for (
size_t k = 1; k <= 7; ++k)
483 T*
const at = w + lanes * (14 * p + 2 * (k - 1));
484 std::fill_n(at, lanes,
static_cast<T
>(std::cos(
static_cast<double>(k) * a)));
485 std::fill_n(at + lanes, lanes,
static_cast<T
>(std::sin(
static_cast<double>(k) * a)));
490 const size_t n1 = pass.len / 4;
492 T* w = twiddles_.data() + pass.twOffset;
493 for (
size_t p = 0; p < n1; ++p)
495 const double a = -2.0 * std::numbers::pi_v<double> *
static_cast<double>(p)
496 /
static_cast<double>(pass.len);
497 const double factors[6] = { std::cos(a), std::sin(a), std::cos(2.0 * a), std::sin(2.0 * a),
498 std::cos(3.0 * a), std::sin(3.0 * a) };
499 for (
size_t row = 0; row < 6; ++row)
508 if (
const size_t inLane = inLaneTwiddleCount(steps, passCount, interleavedInput); inLane > 0)
510 const Pass& first = passes_.front();
511 constexpr size_t B = kBlock<T>, q = B / 4;
512 const size_t n1 = first.
len / 4;
513 inLaneTwiddles_.assign(inLane, T(0));
514 const T* w = twiddles_.data() + first.
twOffset;
515 for (
size_t row = 0; row < 6; ++row)
516 for (
size_t p = 0; p < n1; ++p)
518 const size_t l = p % B, j = l / q;
519 const size_t from = p - l + q * ((j & 1) * 2 + (j >> 1)) + l % q;
540 const size_t passCount = buildPlan(n, steps, twiddles);
541 const size_t inLane = inLaneTwiddleCount(steps, passCount, interleavedInput);
542 const size_t allocations = 2 + (twiddles > 0 ? 1 : 0) + (inLane > 0 ? 1 : 0);
547 [[nodiscard]]
size_t size() const noexcept {
return n_; }
550 [[nodiscard]] T*
inRe() noexcept {
return work_.first(); }
551 [[nodiscard]] T*
inIm() noexcept {
return work_.first() + n_; }
558 void run(
const T*& outRe,
const T*& outIm)
noexcept
562#if defined(DSPARK_SIMD_DISPATCH_AVX2)
564 avx2::transformRun(p, b);
567 fft::transformRun(p, b);
580 void runFrom(
const T* data,
bool conjugate,
const T*& outRe,
const T*& outIm)
noexcept
582 if (passes_.size() == 1)
584 T*
const re = work_.second();
585 T*
const im = re + n_;
586 onePass([&](
size_t i, T& r, T& m) { readPair(data, conjugate, i, r, m); },
587 [&](
size_t i, T r, T m) { re[i] = r; im[i] = m; });
594#if defined(DSPARK_SIMD_DISPATCH_AVX2)
596 avx2::transformFrom(p, b, data, conjugate);
599 fft::transformFrom(p, b, data, conjugate);
612 void runFromSplit(
const T* re,
const T* im,
const T*& outRe,
const T*& outIm)
noexcept
616#if defined(DSPARK_SIMD_DISPATCH_AVX2)
618 avx2::transformFromSplit(p, b, re, im);
621 fft::transformFromSplit(p, b, re, im);
644 const T*& outRe,
const T*& outIm)
noexcept
649 const std::less<const T*> before;
650 const T*
const second = work_.second();
651 if (!before(re, second) && before(re, second + 2 * n_))
653 std::swap(b.
xr, b.
yr);
654 std::swap(b.
xi, b.
yi);
657#if defined(DSPARK_SIMD_DISPATCH_AVX2)
659 avx2::transformScaledSwap(p, b, re, im, gain, mask);
662 fft::transformScaledSwap(p, b, re, im, gain, mask);
681 const T*& outRe,
const T*& outIm)
noexcept
685#if defined(DSPARK_SIMD_DISPATCH_AVX2)
687 avx2::transformScaledSwapFolded(p, b, re, im, gain, fold);
690 fft::transformScaledSwapFolded(p, b, re, im, gain, fold);
701 void runTo(T* out, T scaleRe, T scaleIm)
noexcept
703 if (passes_.size() == 1)
705 const T*
const re = work_.first();
706 const T*
const im = re + n_;
707 onePass([&](
size_t i, T& r, T& m) { r = re[i]; m = im[i]; },
708 [&](
size_t i, T r, T m) { out[2 * i] = r * scaleRe; out[2 * i + 1] = m * scaleIm; });
714#if defined(DSPARK_SIMD_DISPATCH_AVX2)
716 avx2::transformTo(p, b, c);
719 fft::transformTo(p, b, c);
724 void runFromTo(
const T* data,
bool conjugate, T* out, T scaleRe, T scaleIm)
noexcept
726 if (passes_.size() == 1)
728 onePass([&](
size_t i, T& r, T& m) { readPair(data, conjugate, i, r, m); },
729 [&](
size_t i, T r, T m) { out[2 * i] = r * scaleRe; out[2 * i + 1] = m * scaleIm; });
735#if defined(DSPARK_SIMD_DISPATCH_AVX2)
737 avx2::transformFromTo(p, b, data, conjugate, c);
740 fft::transformFromTo(p, b, data, conjugate, c);
759 void runToStep(
size_t step, T* out, T scaleRe, T scaleIm)
noexcept
762 if ((step & 1u) != 0)
764 std::swap(b.
xr, b.
yr);
765 std::swap(b.
xi, b.
yi);
770#if defined(DSPARK_SIMD_DISPATCH_AVX2)
772 avx2::transformToStep(p, b, step, c);
775 fft::transformToStep(p, b, step, c);
781 return { work_.first(), work_.first() + n_, work_.second(), work_.second() + n_ };
785 static void readPair(
const T* data,
bool conjugate,
size_t i, T& r, T& m)
noexcept
788 m = conjugate ? -data[2 * i + 1] : data[2 * i + 1];
795 template <
typename Load,
typename Store>
796 void onePass(Load load, Store store)
const noexcept
803 store(0, ar + br, ai + bi);
804 store(1, ar - br, ai - bi);
807 T ar, ai, br, bi, cr, ci, dr, di;
812 const T apcR = ar + cr, apcI = ai + ci, amcR = ar - cr, amcI = ai - ci;
813 const T bpdR = br + dr, bpdI = bi + di, bmdR = br - dr, bmdI = bi - di;
814 store(0, apcR + bpdR, apcI + bpdI);
815 store(1, amcR + bmdI, amcI - bmdR);
816 store(2, apcR - bpdR, apcI - bpdI);
817 store(3, amcR - bmdI, amcI + bmdR);
823 [[nodiscard]] Plan<T> plan() const noexcept
825 return { passes_.data(), passes_.size(), n_, twiddles_.data(),
826 inLaneTwiddles_.empty() ? nullptr : inLaneTwiddles_.data() };
830 using PlanPasses = std::array<Pass, 40>;
846 static size_t buildPlan(
size_t n, PlanPasses& out,
size_t& twiddleValues)
noexcept
848 const size_t bits =
static_cast<size_t>(std::countr_zero(n));
849 size_t len = n, stride = 1, offset = 0, count = 0;
850 const auto radix4 = [&]()
noexcept {
851 out[count++] = { len, stride, offset,
false,
false,
false };
852 offset += 6 * (len / 4);
856 const auto twiddled8 = [&]()
noexcept {
857 out[count++] = { len, stride, offset,
false,
false,
true };
858 offset += 14 *
static_cast<size_t>(kWide<T>) * (len / 8);
864 const size_t rest = bits - 2;
865 const bool closing8 = n >= 32 && n / 8 >= kBlock<T>
869 size_t closing = 0, fours = 0, eights = 0;
872 closing = (rest & 1) == 0 ? 2 : closing8 ? 3 : 1;
873 fours = (rest - closing) / 2;
876 const size_t c = closing8 && rest >= 3 && rest != 4 ? 3 : 2;
879 const size_t between = rest - c;
881 const size_t f = (3 - between % 3) % 3;
882 const size_t e = (between - 2 * f) / 3;
884 if (between >= 2 * f && e > 0 && (
size_t{ 4 } << (2 * f)) >= kBlock<T>)
894 for (
size_t i = 0; i < fours; ++i) radix4();
895 for (
size_t i = 0; i < eights; ++i) twiddled8();
898 else if (closing == 3)
899 out[count++] = { 8, stride, offset,
false,
true,
false };
900 else if (closing == 1)
901 out[count++] = { 2, stride, offset,
true,
false,
false };
904 out[count++] = { 2, stride, offset,
true,
false,
false };
905 twiddleValues = offset;
910 static size_t inLaneTwiddleCount(
const PlanPasses& steps,
size_t count,
911 bool interleavedInput)
noexcept
913#if defined(DSPARK_SIMD_DISPATCH_AVX2)
914 constexpr bool inLaneReader =
true;
916 constexpr bool inLaneReader = kInLaneDeinterleave<T, kWide<T>>;
918 const Pass& first = steps[0];
919 if (inLaneReader && interleavedInput && count > 1 && !first.radix2 && !first.radix8
920 && (first.len / 4) % kBlock<T> == 0)
921 return 6 * (first.len / 4);
926 WorkBuffers<T> work_;
927 std::vector<T> twiddles_;
928 std::vector<T> inLaneTwiddles_;
929 std::vector<Pass> passes_;
930 bool stepAvx2_ =
false;
959 : n_(size / lanes), lanes_(lanes), wholeReach_(wholeReach),
960 halves_(
RealPlan<T>::halvesFor(size, lanes, halvesReach)), values_(
valueCount(size, lanes, wholeReach))
962 T* w = values_.data();
963 double c = 0.0, s = 0.0;
966 for (
size_t m = firstLength(n_); m < n_; m *= 4)
969 for (
size_t i = 1; i < m / 2; ++i)
970 for (
size_t j = 1; j <= 3; ++j)
972 unit(j * i, 4 * m, c, s);
973 w = std::fill_n(w, repeat,
static_cast<T
>(c));
974 w = std::fill_n(w, repeat,
static_cast<T
>(0.0 - s));
980 turn_ =
static_cast<size_t>(w - values_.data());
981 for (
size_t first = 0; first < n_ / 2; first += lanes_)
982 for (
size_t j = 1; j < lanes_; ++j)
984 for (
size_t t = 0; t < lanes_; ++t)
987 w[t] =
static_cast<T
>(c);
988 w[lanes_ + t] =
static_cast<T
>(0.0 - s);
993 edge_ =
static_cast<size_t>(w - values_.data());
994 const size_t half = lanes_ / 2;
995 for (
size_t j = 0; j < lanes_; ++j)
996 for (
size_t r = 0; r < half; ++r)
998 unit(j * (2 * r + 1), 2 * lanes_, c, s);
999 w[j * half + r] =
static_cast<T
>(c);
1000 w[lanes_ * half + j * half + r] =
static_cast<T
>(s);
1005 [[nodiscard]]
static constexpr size_t valueCount(
size_t size,
size_t lanes,
size_t wholeReach)
noexcept
1007 const size_t n = size / lanes;
1008 size_t count = (lanes - 1) * n + lanes * lanes;
1009 for (
size_t m = firstLength(n); m < n; m *= 4)
1014 [[nodiscard]]
bool empty() const noexcept {
return lanes_ == 0; }
1021 return { n_, lanes_, firstLength(n_) == 8, halves_, wholeReach_, values_.data(), values_.data() + turn_,
1022 values_.data() + edge_, T(1) /
static_cast<T
>(n_ * lanes_) };
1027 [[nodiscard]]
static constexpr size_t firstLength(
size_t n)
noexcept
1029 return (std::countr_zero(n) & 1) != 0 ? 8 : 4;
1036 static void unit(
size_t k,
size_t count,
double& c,
double& s)
noexcept
1038 const size_t quarter = count / 4;
1039 const size_t rest = k % quarter;
1040 const double step = 2.0 * std::numbers::pi_v<double> /
static_cast<double>(count);
1041 double x = 1.0, y = 0.0;
1044 if (2 * rest == quarter)
1045 x = y = 0.70710678118654752440;
1046 else if (2 * rest < quarter)
1048 x = std::cos(step *
static_cast<double>(rest));
1049 y = std::sin(step *
static_cast<double>(rest));
1053 x = std::sin(step *
static_cast<double>(quarter - rest));
1054 y = std::cos(step *
static_cast<double>(quarter - rest));
1057 switch ((k / quarter) & 3)
1059 case 0: c = x; s = y;
break;
1060 case 1: c = 0.0 - y; s = x;
break;
1061 case 2: c = 0.0 - x; s = 0.0 - y;
break;
1062 default: c = y; s = 0.0 - x;
break;
1068 size_t wholeReach_ = 0;
1069 bool halves_ =
false;
1072 std::vector<T> values_;
1092template <
typename T>
1103 : engine_(validateSize(size), true)
1111 [[nodiscard]]
size_t getSize() const noexcept {
return engine_.size(); }
1125 if (size < 2 || (size & (size - 1)) != 0)
1135 void forward(T* data)
noexcept { transform(data,
false); }
1142 void inverse(T* data)
noexcept { transform(data,
true); }
1145 static size_t validateSize(
size_t size)
1147 if (size < 2 || (size & (size - 1)) != 0)
1149#if defined(DSPARK_NO_EXCEPTIONS)
1150 assert(
false &&
"FFTComplex size must be a power of two >= 2");
1153 throw std::invalid_argument(
"FFTComplex size must be a power of two >= 2");
1159 void transform(T* data,
bool inverse)
noexcept
1163 const T scale =
inverse ? T(1) /
static_cast<T
>(engine_.size()) : T(1);
1164 engine_.runFromTo(data,
inverse, data, scale,
inverse ? -scale : scale);
1167 detail::fft::SplitFFT<T> engine_;
1195template <
typename T>
1206 : realSize_(validateSize(size))
1207 , halfSize_(realSize_ / 2)
1208 , engine_(makeEngine(realSize_))
1210 const size_t lanes = baseLanes(realSize_);
1213 computeSplitFactors();
1217 constexpr size_t halvesReach = detail::fft::plan::kRealHalvesReach<T>;
1220 if (
const size_t other = dispatchedLanes(realSize_); other != lanes)
1225 [[nodiscard]]
size_t getSize() const noexcept {
return realSize_; }
1231 [[nodiscard]]
size_t getNumBins() const noexcept {
return halfSize_ + 1; }
1245 if (size < 4 || (size & (size - 1)) != 0)
1248 const size_t lanes = baseLanes(size);
1251 + 2 * (splitFactorCount(size / 2) *
sizeof(T) + overhead);
1255 size_t allocations = 2;
1256 if (
const size_t other = dispatchedLanes(size); other != lanes)
1258 values += Tables::valueCount(size, other, 0);
1261 return values *
sizeof(T) + allocations * overhead;
1269 void forward(
const T* timeData, T* freqData)
noexcept
1271 if (!lanes_.empty())
1273 T*
const a = laneWork_.first();
1274 T*
const b = laneWork_.second();
1275#if defined(DSPARK_SIMD_DISPATCH_AVX2)
1278 detail::fft::avx2::realForward(dispatchedTables().plan(), timeData, freqData, a, b);
1282 detail::fft::realForward(lanes_.plan(), timeData, freqData, a, b);
1286 const T* zr =
nullptr;
1287 const T* zi =
nullptr;
1288 engine_.runFrom(timeData,
false, zr, zi);
1289 unpackForward(zr, zi, freqData);
1297 void inverse(
const T* freqData, T* timeData)
noexcept
1299 if (!lanes_.empty())
1301 T*
const a = laneWork_.first();
1302 T*
const b = laneWork_.second();
1303#if defined(DSPARK_SIMD_DISPATCH_AVX2)
1306 detail::fft::avx2::realInverse(dispatchedTables().plan(), freqData, timeData, a, b);
1310 detail::fft::realInverse(lanes_.plan(), freqData, timeData, a, b);
1315 packInverseConj(freqData, engine_.inRe(), engine_.inIm());
1316 const T scale = inverseScale();
1317 engine_.runTo(timeData, scale, -scale);
1324 if (!lanes_.empty())
1325 return static_cast<int>(std::max(lanes_.passes(), wideLanes_.passes())) + 1;
1326 return static_cast<int>(engine_.runToStepCount()) + 1;
1347 if (!lanes_.empty())
1356 if (step > 0 && step <= spare)
return;
1357 const size_t own = step <= 0 ?
size_t{ 0 } :
static_cast<size_t>(step - spare);
1358 T*
const a = laneWork_.first();
1359 T*
const b = laneWork_.second();
1360#if defined(DSPARK_SIMD_DISPATCH_AVX2)
1361 if (stepDispatched_)
1363 detail::fft::avx2::realInverseStep(tables.
plan(), own, freqData, timeData, a, b);
1367 detail::fft::realInverseStep(tables.
plan(), own, freqData, timeData, a, b);
1372 packInverseConj(freqData, engine_.inRe(), engine_.inIm());
1375 const T scale = inverseScale();
1376 engine_.runToStep(
static_cast<size_t>(step - 1), timeData, scale, -scale);
1386 for (
size_t k = 0; k <= halfSize_; ++k)
1388 T re = freqData[2 * k];
1389 T im = freqData[2 * k + 1];
1390 magnitudes[k] = std::sqrt(re * re + im * im);
1401 for (
size_t k = 0; k <= halfSize_; ++k)
1403 T re = freqData[2 * k];
1404 T im = freqData[2 * k + 1];
1405 phases[k] = std::atan2(im, re);
1416 for (
size_t k = 0; k <= halfSize_; ++k)
1418 T re = freqData[2 * k];
1419 T im = freqData[2 * k + 1];
1420 power[k] = re * re + im * im;
1431 [[nodiscard]]
static T
binToFrequency(
size_t binIndex,
double sampleRate,
size_t fftSize)
noexcept
1433 return static_cast<T
>(
static_cast<double>(binIndex) * sampleRate /
static_cast<double>(fftSize));
1443 [[nodiscard]]
static size_t frequencyToBin(
double frequency,
double sampleRate,
size_t fftSize)
noexcept
1445 return static_cast<size_t>(std::round(frequency *
static_cast<double>(fftSize) / sampleRate));
1453 static size_t validateSize(
size_t size)
1455 if (size < 4 || (size & (size - 1)) != 0)
1457#if defined(DSPARK_NO_EXCEPTIONS)
1458 assert(
false &&
"FFTReal size must be a power of two >= 4");
1461 throw std::invalid_argument(
"FFTReal size must be a power of two >= 4");
1468 [[nodiscard]]
static size_t splitFactorCount(
size_t m)
noexcept
1470 return std::min(m, m / 2 + detail::fft::kBlock<T>);
1473 void computeSplitFactors()
1483 const size_t m = halfSize_;
1484 const size_t used = splitFactorCount(m);
1485 splitRe_.resize(used);
1486 splitIm_.resize(used);
1487 for (
size_t k = 0; k <= m / 2; ++k)
1489 const double half = std::numbers::pi_v<double> *
static_cast<double>(k)
1490 /
static_cast<double>(realSize_);
1491 const double s = std::sin(0.25 * std::numbers::pi_v<double> - half);
1492 splitRe_[k] =
static_cast<T
>(s * s);
1493 splitIm_[k] =
static_cast<T
>(-0.5 * std::cos(2.0 * half));
1495 splitRe_[m / 2] = T(0);
1496 splitIm_[m / 2] = T(0);
1497 for (
size_t k = m / 2 + 1; k < used; ++k)
1499 splitRe_[k] = splitRe_[m - k];
1500 splitIm_[k] = -splitIm_[m - k];
1505 void unpackForward(
const T* zr,
const T* zi, T* out)
const noexcept
1507#if defined(DSPARK_SIMD_DISPATCH_AVX2)
1510 detail::fft::avx2::unpackRealForward(zr, zi, out, halfSize_, splitRe_.data(), splitIm_.data());
1514 detail::fft::unpackRealForward(zr, zi, out, halfSize_, splitRe_.data(), splitIm_.data());
1519 void packInverseConj(
const T* in, T* zr, T* zi)
const noexcept
1521#if defined(DSPARK_SIMD_DISPATCH_AVX2)
1524 detail::fft::avx2::packRealSpectrum(in, zr, zi, halfSize_, splitRe_.data(), splitIm_.data());
1528 detail::fft::packRealSpectrum(in, zr, zi, halfSize_, splitRe_.data(), splitIm_.data());
1532 [[nodiscard]] T inverseScale() const noexcept {
return T(1) /
static_cast<T
>(halfSize_); }
1543 [[nodiscard]]
static constexpr size_t lanesFor(
size_t size,
int wide,
int narrow)
noexcept
1545 const auto fits = [size](
int width)
noexcept {
1546 const size_t lanes =
static_cast<size_t>(width);
1547 return width > 1 && size >= 8 * lanes && 2 * size >= lanes * lanes * lanes;
1549 return fits(wide) ?
static_cast<size_t>(wide) : fits(narrow) ? static_cast<size_t>(narrow) : size_t{ 0 };
1553 [[nodiscard]]
static constexpr size_t baseLanes(
size_t size)
noexcept
1555 return lanesFor(size, detail::fft::kWide<T>, detail::fft::kNarrow<T>);
1560 [[nodiscard]]
static constexpr size_t dispatchedLanes(
size_t size)
noexcept
1562#if defined(DSPARK_SIMD_DISPATCH_AVX2)
1563 return lanesFor(size, detail::fft::avx2::kWide<T>, detail::fft::avx2::kNarrow<T>);
1565 return baseLanes(size);
1570 [[nodiscard]]
static detail::fft::SplitFFT<T> makeEngine(
size_t size)
1572 if (baseLanes(size) != 0)
1573 return detail::fft::SplitFFT<T>();
1574 return detail::fft::SplitFFT<T>(size / 2,
true);
1579 [[nodiscard]]
const detail::fft::RealLaneTables<T>& dispatchedTables() const noexcept
1581 return wideLanes_.empty() ? lanes_ : wideLanes_;
1586 detail::fft::SplitFFT<T> engine_;
1587 std::vector<T> splitRe_, splitIm_;
1588 detail::fft::WorkBuffers<T> laneWork_;
1589 detail::fft::RealLaneTables<T> lanes_;
1590 detail::fft::RealLaneTables<T> wideLanes_;
1591 bool stepDispatched_ =
false;
Complex FFT on interleaved data (Stockham radix-4 engine, SIMD).
FFTComplex(size_t size)
Constructs an FFT processor for the given size.
size_t getSize() const noexcept
Returns the FFT size (number of complex points).
static size_t allocationBytes(size_t size) noexcept
Upper bound of the heap bytes a constructor of this size requests, excluding the object itself,...
void forward(T *data) noexcept
Performs a forward (time->frequency) FFT in-place.
void inverse(T *data) noexcept
Performs an inverse (frequency->time) FFT in-place.
FFT optimised for real-valued input signals (the common audio case).
static size_t frequencyToBin(double frequency, double sampleRate, size_t fftSize) noexcept
Returns the bin index closest to a given frequency.
static size_t allocationBytes(size_t size) noexcept
Upper bound of the heap bytes a constructor of this size requests, excluding the object itself,...
void computePhases(const T *freqData, T *phases) const noexcept
Computes the phase angle of each frequency bin.
size_t getNumBins() const noexcept
Returns the number of frequency bins (N/2 + 1) including DC and Nyquist.
void computePowerSpectrum(const T *freqData, T *power) const noexcept
Computes the power spectrum (magnitude squared) of each bin.
int getInverseStepCount() const noexcept
Returns the number of steps inverseStep() splits inverse() into (the same for the life of the object)...
void forward(const T *timeData, T *freqData) noexcept
Forward transform: real time-domain -> complex frequency-domain.
FFTReal(size_t size)
Constructs a real FFT processor.
void inverse(const T *freqData, T *timeData) noexcept
Inverse transform: complex frequency-domain -> real time-domain.
size_t getFrequencyDomainSize() const noexcept
Returns the frequency-domain buffer size in elements (N + 2).
static T binToFrequency(size_t binIndex, double sampleRate, size_t fftSize) noexcept
Returns the frequency in Hz corresponding to a given bin index.
size_t getSize() const noexcept
Returns the number of real input samples (N).
void inverseStep(int step, const T *freqData, T *timeData) noexcept
Runs one step of inverse(), for callers that spread a large transform over several calls (a real-time...
void computeMagnitudes(const T *freqData, T *magnitudes) const noexcept
Computes the magnitude of each frequency bin.
The tables of a real transform by lanes (detail/FftKernels.inl) for one lane count,...
RealPlan< T > plan() const noexcept
bool empty() const noexcept
RealLaneTables(size_t size, size_t lanes, size_t wholeReach, size_t halvesReach)
Builds the tables of a transform of size real samples.
size_t passes() const noexcept
Passes of each lane's transform (0 when empty).
static constexpr size_t valueCount(size_t size, size_t lanes, size_t wholeReach) noexcept
Values the constructor requests (one allocation).
The shared Stockham engine: a forward complex FFT of size N on split (re, im) arrays,...
static size_t allocationBytes(size_t n, bool interleavedInput) noexcept
Upper bound of the bytes the constructor requests for a power-of-two size n: the two work buffers (on...
void runScaledSwap(const T *re, const T *im, const T *gain, size_t mask, const T *&outRe, const T *&outIm) noexcept
Transforms the spectrum product whose bin k is (im[k & mask] gain[k], re[k & mask] gain[k]),...
T * inRe() noexcept
Input buffers: fill inRe() / inIm() with N values each before run().
void runFrom(const T *data, bool conjugate, const T *&outRe, const T *&outIm) noexcept
Transforms interleaved (re, im) pairs, conjugated if asked, without first copying them into the input...
void runScaledSwapFolded(const T *re, const T *im, const T *gain, size_t fold, const T *&outRe, const T *&outIm) noexcept
runScaledSwap() of a spectrum fold times this engine's size, folded: bin k sums the products of bins ...
size_t runToStepCount() const noexcept
SplitFFT(size_t n, bool interleavedInput=false)
void run(const T *&outRe, const T *&outIm) noexcept
Runs the forward transform of the input buffers.
static constexpr size_t kAllocationOverhead
void runFromSplit(const T *re, const T *im, const T *&outRe, const T *&outIm) noexcept
Transforms N values read from two arrays of real and imaginary parts, without first copying them into...
void runToStep(size_t step, T *out, T scaleRe, T scaleIm) noexcept
Runs one step of runTo(): step s below runToStepCount() - 1 is pass s, the last step the closing pass...
size_t size() const noexcept
void runFromTo(const T *data, bool conjugate, T *out, T scaleRe, T scaleIm) noexcept
void runTo(T *out, T scaleRe, T scaleIm) noexcept
Transforms the input buffers and writes interleaved output directly.
Two buffers of the same length in one allocation, each starting on a 64-byte boundary,...
WorkBuffers(WorkBuffers &&other) noexcept
const T * first() const noexcept
WorkBuffers(const WorkBuffers &other)
WorkBuffers & operator=(WorkBuffers other) noexcept
WorkBuffers(size_t count)
Two zeroed buffers of count values each.
static constexpr size_t values(size_t count) noexcept
const T * second() const noexcept
constexpr bool kTwiddledRadix8
constexpr size_t kRealWholeTwiddleReach
constexpr size_t kRealHalvesReach
constexpr size_t kTwiddled8RowReach
constexpr size_t kClosingRowReach
bool isRuntimeDispatchActive() noexcept
Whether the AVX2+FMA kernels are selected now (see setRuntimeDispatch()).
Main namespace for the DSPark framework.
The two ping-pong buffers, [re | im] each: x is read, y is written.
Where a closing pass into interleaved output writes, and its scales.
static constexpr size_t repeatFor(size_t m, size_t lanes, size_t wholeReach) noexcept
bool halves
The joining step works by halves, its tables in the order of laneBin().
bool first8
The first pass takes eight samples (log2 n odd), not four.
const T * turn
The factors of the step that joins the lanes.
const T * edge
The factors of the lanes' middle bin.
size_t wholeReach
Passes joining spectra of up to this many points hold each twiddle lanes times.
static constexpr size_t passCount(size_t n) noexcept
constexpr size_t firstLength() const noexcept
Points of the spectra the first pass leaves.
size_t lanes
Lanes: the transform has n * lanes samples.
static constexpr size_t passValues(size_t m, size_t repeat) noexcept
const T * twiddles
The pass tables, by rising length of the spectra they join.
T scale
1 / (n * lanes), for the inverse.
static constexpr bool halvesFor(size_t size, size_t lanes, size_t reach) noexcept
size_t n
Points of each lane's transform.
static constexpr size_t laneBin(size_t lanes, size_t p, bool byHalves) noexcept
static constexpr size_t index(size_t stride, size_t block, size_t row, size_t p) noexcept
static constexpr size_t firstBlock(size_t n1, size_t block) noexcept