80template <FloatType T,
int MaxChannels = 16>
87 for (
auto& s : states_)
104 assert(channel >= 0 && channel < MaxChannels);
108 channel = std::clamp(channel, 0, MaxChannels - 1);
109 return processState(sample, states_[
static_cast<size_t>(channel)]);
120 assert(channel >= 0 && channel < MaxChannels);
121 channel = std::clamp(channel, 0, MaxChannels - 1);
122 auto state = states_[
static_cast<size_t>(channel)];
124 for (
int i = 0; i < kTaps - 1; ++i)
125 peak = std::max(peak, processState(T(0), state));
130 [[nodiscard]]
static constexpr int getLatency() noexcept {
return kTaps / 2; }
140 [[nodiscard]]
static constexpr int getTaps() noexcept {
return kTaps; }
143 [[nodiscard]]
static constexpr int getPhases() noexcept {
return kPhases; }
158 return kReversedCoeffs[
static_cast<size_t>(std::clamp(phase, 0, kPhases - 1))].data();
162 static constexpr int kTaps = 12;
163 static constexpr int kPhases = 4;
164 static constexpr int kHistSize = 16;
165 static constexpr int kHistMask = kHistSize - 1;
171 T history[kHistSize * 2] = {};
175 [[nodiscard]]
static T processState(T sample, State& tp)
noexcept
178 tp.history[
static_cast<size_t>(tp.writePos)] = sample;
179 tp.history[
static_cast<size_t>(tp.writePos + kHistSize)] = sample;
180 const int newest = tp.writePos;
181 tp.writePos = (tp.writePos + 1) & kHistMask;
182 const T* window = &tp.history[
static_cast<size_t>(newest + kHistSize - (kTaps - 1))];
183 T peak = std::abs(sample);
184#if defined(DSPARK_SIMD_SSE2) || defined(DSPARK_SIMD_NEON)
185 if constexpr (std::is_same_v<T, float>)
191#if defined(DSPARK_SIMD_SSE2)
192 __m128 acc = _mm_setzero_ps();
193 for (
int j = 0; j < kTaps; ++j)
194 acc = _mm_add_ps(acc, _mm_mul_ps(_mm_load_ps(kVertical.c[j]), _mm_set1_ps(window[j])));
195 acc = _mm_andnot_ps(_mm_set1_ps(-0.0f), acc);
196 __m128 m = _mm_max_ps(acc, _mm_movehl_ps(acc, acc));
197 m = _mm_max_ss(m, _mm_shuffle_ps(m, m, 1));
198 const float a = _mm_cvtss_f32(m);
200 float32x4_t acc = vdupq_n_f32(0.0f);
201 for (
int j = 0; j < kTaps; ++j)
202 acc = vaddq_f32(acc, vmulq_f32(vld1q_f32(kVertical.c[j]), vdupq_n_f32(window[j])));
203 acc = vabsq_f32(acc);
204 float32x2_t m = vpmax_f32(vget_low_f32(acc), vget_high_f32(acc));
206 const float a = vget_lane_f32(m, 0);
208 return (a > peak) ? a : peak;
211 for (
int phase = 0; phase < kPhases; ++phase)
214 kReversedCoeffs[
static_cast<size_t>(phase)].data(), window, kTaps);
215 const T a = std::abs(interp);
216 if (a > peak) peak = a;
231 [[nodiscard]]
static constexpr std::array<std::array<T, kTaps>, kPhases>
232 buildReversedPhaseTable() noexcept
234 constexpr double kAnnex2[kPhases][kTaps] = {
235 { 0.0017089843750, 0.0109863281250, -0.0196533203125,
236 0.0332031250000, -0.0594482421875, 0.1373291015625,
237 0.9721679687500, -0.1022949218750, 0.0476074218750,
238 -0.0266113281250, 0.0148925781250, -0.0083007812500 },
239 { -0.0291748046875, 0.0292968750000, -0.0517578125000,
240 0.0891113281250, -0.1665039062500, 0.4650878906250,
241 0.7797851562500, -0.2003173828125, 0.1015625000000,
242 -0.0582275390625, 0.0330810546875, -0.0189208984375 },
243 { -0.0189208984375, 0.0330810546875, -0.0582275390625,
244 0.1015625000000, -0.2003173828125, 0.7797851562500,
245 0.4650878906250, -0.1665039062500, 0.0891113281250,
246 -0.0517578125000, 0.0292968750000, -0.0291748046875 },
247 { -0.0083007812500, 0.0148925781250, -0.0266113281250,
248 0.0476074218750, -0.1022949218750, 0.9721679687500,
249 0.1373291015625, -0.0594482421875, 0.0332031250000,
250 -0.0196533203125, 0.0109863281250, 0.0017089843750 },
253 std::array<std::array<T, kTaps>, kPhases> result {};
254 for (
int phase = 0; phase < kPhases; ++phase)
255 for (
int k = 0; k < kTaps; ++k)
256 result[
static_cast<size_t>(phase)][
static_cast<size_t>(kTaps - 1 - k)]
257 =
static_cast<T
>(kAnnex2[phase][k]);
263 static constexpr std::array<std::array<T, kTaps>, kPhases> kReversedCoeffs =
264 buildReversedPhaseTable();
268 struct VerticalTable {
alignas(16)
float c[kTaps][kPhases]; };
269 [[nodiscard]]
static constexpr VerticalTable buildVerticalTable() noexcept
272 for (
int j = 0; j < kTaps; ++j)
273 for (
int p = 0; p < kPhases; ++p)
274 v.c[j][p] =
static_cast<float>(kReversedCoeffs[
static_cast<size_t>(p)][
static_cast<size_t>(j)]);
277 static constexpr VerticalTable kVertical = buildVerticalTable();
279 std::array<State, MaxChannels> states_ {};
288template <
int Count,
typename T>
291 constexpr double kPi = std::numbers::pi_v<double>;
292 const auto besselI0 = [](
double x)
noexcept {
293 double sum = 1.0, term = 1.0;
294 for (
int k = 1; k < 64; ++k)
296 const double h = x / (2.0 * k);
299 if (term < 1e-17 * sum)
break;
303 const double norm = besselI0(beta);
304 constexpr double halfTaps = Count / 2;
307 for (
int j = 0; j < Count; ++j)
310 const double d =
static_cast<double>(j) - (halfTaps - 1.0) - frac;
311 const double sinc = std::sin(kPi * d) / (kPi * d);
312 const double u = d / halfTaps;
313 const double w = besselI0(beta * std::sqrt(std::max(0.0, 1.0 - u * u))) / norm;
317 for (
int j = 0; j < Count; ++j)
318 out[j] =
static_cast<T
>(taps[j] / sum);
328 const T ab = std::abs(b);
329 const T d = (a + c) - (b + b);
330 if (ab >= std::abs(a) && ab >= std::abs(c) && b * d < T(0))
333 const T v = std::abs(b - (q * q) / (T(8) * d));
345[[nodiscard]]
inline T
gridReading(
const T* s,
const T* q,
const T* h,
const T* t,
int i)
noexcept
347 const T a0 = s[i], a4 = s[i + 1];
348 const T y0 = t[i], y1 = q[i], y2 = h[i], y3 = t[i + 1];
349 T m = std::max(std::max(std::abs(a0), std::abs(a4)),
350 std::max(std::abs(y2), std::max(std::abs(y1), std::abs(y3))));
363[[nodiscard]]
inline T
eighthCrests(
const T* a,
const T* e,
int u, T m)
noexcept
377 if (first >= n)
return;
378 T p0 = a[4 * first - 1], p1 = e[4 * first];
379 for (
int i = first; i < n; ++i)
382 for (
int k = 0; k < 4; ++k)
384 const T x = a[4 * i + k];
385 const T y = e[4 * i + k + 1];
386 m = std::max(m, std::abs(x));
387 m = std::max(m, std::abs(y));
393 peak[i] = std::max(peak[i], m);
402template <
typename T,
int W>
using Vec = simd::Vec<T, W>;
403template <
typename T>
inline constexpr int kWide = simd::kVecWidth<T>;
404template <
typename T>
inline constexpr int kNarrow = simd::kVecNarrowWidth<T>;
405#include "detail/TruePeakKernels.inl"
411#if defined(DSPARK_SIMD_DISPATCH_AVX2)
413DSPARK_SIMD_AVX2_BEGIN
418template <
typename T,
int W>
using Vec = simd::avx2::Vec<T, W>;
419template <
typename T>
inline constexpr int kWide = simd::avx2::kVecWidth<T>;
420template <
typename T>
inline constexpr int kNarrow = simd::avx2::kVecNarrowWidth<T>;
421#include "detail/TruePeakKernels.inl"
439 static void raiseToReadings(
const T* s,
const T* q,
const T* h,
const T* t, T* peak,
int n)
noexcept
441#if defined(DSPARK_SIMD_DISPATCH_AVX2)
444 truepeak::avx2::raiseToReadings(s, q, h, t, peak, n);
448 truepeak::raiseToReadings(s, q, h, t, peak, n);
455#if defined(DSPARK_SIMD_DISPATCH_AVX2)
457 return truepeak::avx2::largestFiniteReading(s, q, h, t, n, start);
459 return truepeak::largestFiniteReading(s, q, h, t, n, start);
465#if defined(DSPARK_SIMD_DISPATCH_AVX2)
468 truepeak::avx2::raiseToMagnitudes(dst, src, n);
472 truepeak::raiseToMagnitudes(dst, src, n);
478#if defined(DSPARK_SIMD_DISPATCH_AVX2)
480 return truepeak::avx2::largestFiniteMagnitude(v, count, start);
482 return truepeak::largestFiniteMagnitude(v, count, start);
489#if defined(DSPARK_SIMD_DISPATCH_AVX2)
492 truepeak::avx2::raiseToEighthReadings(a, e, peak, n);
496 truepeak::raiseToEighthReadings(a, e, peak, n);
503#if defined(DSPARK_SIMD_DISPATCH_AVX2)
505 return truepeak::avx2::largestFiniteEighthCrest(a, e, points, start);
507 return truepeak::largestFiniteEighthCrest(a, e, points, start);
557template <FloatType T>
576 for (
int p = 0; p <
kPhases; ++p)
577 detail::designSincPhase<kTaps>(coeffs_[p], 8.0,
static_cast<double>(p + 1) / 4.0);
581 [[nodiscard]]
static constexpr int getDelay() noexcept {
return kTaps / 2 + 1; }
597 void process(
Channel& channel,
const T* x,
int n, T* peak,
bool annex2Guard =
false) noexcept
599 assert(n >= 1 && n <=
kChunk);
600 n = std::clamp(n, 0,
kChunk);
601 const T* base = appendAndInterpolate(channel, x, n);
606 const T* annexBase = base + (
kTaps - kAnnexTaps);
607 for (
int p = 0; p < kAnnexPhases; ++p)
636 assert(n >= 1 && n <=
kChunk);
637 n = std::clamp(n, 0,
kChunk);
638 const T* base = appendAndInterpolate(channel, x, n);
642 const T*
const samples = base + (
kTaps / 2 - 1);
647 if (!(gridMax * T(1.25) > atLeast))
669 for (
const T v : peak) result = std::max(result, v);
678 static_assert(kAnnexTaps <=
kTaps,
"the BS.1770 window must fit the estimator history");
679 static_assert(
kTaps <=
kChunk,
"the tail is measured in one call");
684 const T* appendAndInterpolate(Channel& channel,
const T* x,
int n)
noexcept
686 T* h = channel.history;
687 if (channel.fill + n >
kChunk)
689 std::copy(h + channel.fill, h + channel.fill + (
kTaps - 1), h);
692 std::copy(x, x + n, h + (
kTaps - 1) + channel.fill);
693 const T* base = h + channel.fill;
698 T*
const t = threeQuarter();
709 static constexpr int kLead = 32 /
static_cast<int>(
sizeof(T));
710 [[nodiscard]] T* threeQuarter() noexcept {
return threeQuarter_ + (kLead - 1); }
715 T threeQuarter_[kLead +
kChunk] = {};
763template <FloatType T>
766 static constexpr int kTaps2 = 16;
767 static constexpr int kTaps3 = 8;
786 detail::designSincPhase<kTaps>(coeffs1_, 7.0, 0.5);
787 detail::designSincPhase<kTaps2>(coeffs2_, 9.0, 0.5);
788 detail::designSincPhase<kTaps3>(coeffs3_, 9.0, 0.5);
794 [[nodiscard]]
static constexpr int getDelay() noexcept
820 assert(n >= 1 && n <=
kChunk);
821 n = std::clamp(n, 0,
kChunk);
822 if (n == 0)
return T(0);
823 const T* fourth = advance(channel, x, n);
824 const int points = 4 * n;
825 constexpr T kFinite = std::numeric_limits<T>::max();
829 const T carried = std::abs(eighth()[0]);
830 const T centres = carried <= kFinite ? std::max(gridMax, carried) : gridMax;
831 if (!(centres * T(1.25) > atLeast))
859 void process(
Channel& channel,
const T* x,
int n, T* peak, T* annex2 =
nullptr) noexcept
861 assert(n >= 1 && n <=
kChunk);
862 n = std::clamp(n, 0,
kChunk);
864 const T* fourth = advance(channel, x, n);
866 if (annex2 !=
nullptr)
869 const T* annexBase = channel.
input + (channel.
fill - n) + (
kTaps - kAnnexTaps);
870 for (
int p = 0; p < kAnnexPhases; ++p)
892 constexpr T zeros[
kChunk] = {};
894 for (
int left = kTailSamples; left > 0; left -=
kChunk)
897 if (peak > result) result = peak;
907 static_assert(kAnnexTaps <=
kTaps,
"the BS.1770 window must fit the first stage history");
910 static constexpr int kDelay =
kTaps / 2 + kTaps2 / 4 + kTaps3 / 8;
913 static constexpr int kTailSamples =
kTaps / 2 + kDelay + 1;
914 static_assert(
kTaps % 2 == 0 && kTaps2 % 2 == 0 && kTaps3 % 2 == 0,
"midpoint kernels are even");
920 const T* advance(Channel& channel,
const T* x,
int n)
noexcept
922 if (channel.fill + n >
kChunk)
925 const int f = channel.fill;
926 std::copy(channel.input + f, channel.input + f + (
kTaps - 1), channel.input);
927 std::copy(channel.twice + 2 * f, channel.twice + 2 * f + (kTaps2 - 1), channel.twice);
928 std::copy(channel.fourTimes + 4 * f, channel.fourTimes + 4 * f + (kTaps3 - 1), channel.fourTimes);
931 const int f = channel.fill;
934 std::copy(x, x + n, channel.input + (
kTaps - 1) + f);
935 const T* in = channel.input + f;
937 T* twice = channel.twice + (kTaps2 - 1) + 2 * f;
938 for (
int i = 0; i < n; ++i)
940 twice[2 * i] = in[i +
kTaps / 2 - 1];
941 twice[2 * i + 1] = scratch_[i];
945 const T* two = channel.twice + 2 * f;
947 T* four = channel.fourTimes + (kTaps3 - 1) + 4 * f;
948 for (
int t = 0; t < 2 * n; ++t)
950 four[2 * t] = two[t + kTaps2 / 2 - 1];
951 four[2 * t + 1] = scratch_[t];
958 const T* base = channel.fourTimes + 4 * f;
959 T*
const e = eighth();
960 e[0] = channel.previous[1];
962 const T* fourth = base + (kTaps3 / 2 - 1);
963 channel.previous[0] = fourth[4 * n - 1];
964 channel.previous[1] = e[4 * n];
973 static constexpr int kLead = 32 /
static_cast<int>(
sizeof(T));
974 [[nodiscard]] T* eighth() noexcept {
return eighth_ + (kLead - 1); }
976 T coeffs1_[
kTaps] = {};
977 T coeffs2_[kTaps2] = {};
978 T coeffs3_[kTaps3] = {};
979 T scratch_[2 *
kChunk] = {};
980 T eighth_[kLead + 4 *
kChunk] = {};
Running-maximum reading of the band-limited reconstruction peak, for meters.
static constexpr int getDelay() noexcept
Input samples one reading reaches back: the newest 8x grid point a call reads lies this many samples ...
static constexpr int kChunk
Most samples one processMax() call takes.
static constexpr int kTaps
Taps of the first (interval midpoint) stage.
void process(Channel &channel, const T *x, int n, T *peak, T *annex2=nullptr) noexcept
Appends samples to a channel and raises each peak[i] to the reading of the 8x grid points x[i] comple...
TruePeakAnalyzer() noexcept
Designs the three interpolation stages.
T getTailPeak(const Channel &channel) noexcept
Peak of the zero-extended tail of a finite programme.
T processMax(Channel &channel, const T *x, int n, T atLeast) noexcept
Appends samples to a channel and returns the largest finite reading among the 8x grid points they com...
Per-channel 4x-oversampled inter-sample peak estimator.
static constexpr int getTaps() noexcept
Input samples one estimate is computed from (taps per phase).
static constexpr int getLatency() noexcept
Group delay of the interpolation FIR in samples (per phase).
static constexpr int getPhases() noexcept
Number of interpolation phases (4x over-sampling).
T getTailPeak(int channel) const noexcept
Measures the zero-extended interpolation tail of one channel. Evaluates getTaps()-1 zero frames on a ...
T processSample(T sample, int channel) noexcept
Feeds one sample and returns the local true-peak estimate.
static constexpr const T * getReversedPhase(int phase) noexcept
One official interpolation phase, row reversed, for callers that run the interpolator as a block FIR.
void reset() noexcept
Clears all channel histories. Safe on the audio thread.
Block-based reading of the band-limited reconstruction peak.
static constexpr int getDelay() noexcept
Input samples one reading reaches back.
T getTailPeak(const Channel &channel) noexcept
Peak of the zero-extended tail of a finite programme.
static constexpr int kPhases
Quarter, half and three-quarter points.
void process(Channel &channel, const T *x, int n, T *peak, bool annex2Guard=false) noexcept
Appends samples to a channel and raises each peak[i] to the reading of x[i]'s position.
static constexpr int kChunk
Most samples one process() call takes.
static constexpr int kTaps
Taps per interpolation phase.
TruePeakEstimator() noexcept
Designs the interpolation phases.
T processMax(Channel &channel, const T *x, int n, T atLeast) noexcept
Appends samples to a channel and returns the largest finite reading among them (0 if none),...
T gridReading(const T *s, const T *q, const T *h, const T *t, int i) noexcept
T eighthCrests(const T *a, const T *e, int u, T m) noexcept
T refineVertex(T a, T b, T c, T m) noexcept
void designSincPhase(T *out, double beta, double frac) noexcept
void raiseToEighthSamples(const T *a, const T *e, T *peak, int first, int n) noexcept
bool isRuntimeDispatchActive() noexcept
Whether the AVX2+FMA kernels are selected now (see setRuntimeDispatch()).
float dotProduct(const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int count) noexcept
Computes the dot product of two arrays.
void firCorrelate(const T *x, const T *h, int taps, T *DSPARK_RESTRICT y, int n, T gain) noexcept
Block FIR as a valid correlation: y[i] = gain * sum_j h[j] * x[i + j] for i in [0,...
Main namespace for the DSPark framework.
History of one channel (each stage's kernel span plus one chunk).
T twice[kTaps2 - 1+2 *kChunk]
2x stream, oldest first.
int fill
Input samples past the history prefix.
T input[kTaps - 1+kChunk]
Input samples, oldest first.
T fourTimes[kTaps3 - 1+4 *kChunk]
4x stream, oldest first.
T previous[2]
Last two points of the 8x grid.
History of one channel (kTaps - 1 samples plus one chunk).
T history[kTaps - 1+kChunk]
Oldest first; see process().
int fill
Samples past the history prefix.
T last
Last three-quarter point.
static T largestFiniteEighthCrest(const T *a, const T *e, int points, T start) noexcept
static void raiseToReadings(const T *s, const T *q, const T *h, const T *t, T *peak, int n) noexcept
Raises peak[i] to gridReading(s, q, h, t, i) for i in [0, n).
static void raiseToMagnitudes(T *dst, const T *src, int n) noexcept
Raises dst[i] to |src[i]| for i in [0, n).
static T largestFiniteMagnitude(const T *v, int count, T start) noexcept
The largest finite magnitude among count values and start.
static void raiseToEighthReadings(const T *a, const T *e, T *peak, int n) noexcept
static T largestFiniteReading(const T *s, const T *q, const T *h, const T *t, int n, T start) noexcept
The largest finite gridReading() of the positions [0, n) and start.