102 if (!prepared_.load(std::memory_order_relaxed))
return info;
106 for (
int i = 0; i < kNumBins; ++i)
109 info.
rangeBlocks += lraHistogram_[i].load(std::memory_order_relaxed);
125 void prepare(
double sampleRate,
int numChannels = 2) noexcept
128 if (!std::isfinite(sampleRate) || sampleRate <= 0.0)
return;
130 sampleRate_ = sampleRate;
132 computeKWeighting(sampleRate);
136 blockSamples_ =
static_cast<int>(std::clamp(sampleRate * 0.1, 1.0, 1.0e9));
139 prepared_.store(
true, std::memory_order_relaxed);
145 prepare(spec.sampleRate, spec.numChannels);
158 const int nCh = buffer.getNumChannels();
159 const int nS = buffer.getNumSamples();
161 process(buffer.getChannel(0), buffer.getChannel(1), nS);
163 process(buffer.getChannel(0), nS);
171 void process(
const T* data,
int numSamples)
noexcept
173 if (!prepared_.load(std::memory_order_relaxed) || data ==
nullptr || numSamples <= 0)
176 truePeakMax_.store(measureTruePeak(data, 0, numSamples,
177 truePeakMax_.load(std::memory_order_relaxed)),
178 std::memory_order_relaxed);
185 using V =
typename L::V;
186 const V b0 = L::set(pre_.b0, rlb_.b0), b1 = L::set(pre_.b1, rlb_.b1);
187 const V b2 = L::set(pre_.b2, rlb_.b2), a1 = L::set(pre_.a1, rlb_.a1);
188 const V a2 = L::set(pre_.a2, rlb_.a2);
189 V z1 = L::set(preState_[0].z1, rlbState_[0].z1);
190 V z2 = L::set(preState_[0].z2, rlbState_[0].z2);
191 const auto stageOne = [&](
double x)
noexcept
194 const V y = L::step(b0, b1, b2, a1, a2, L::set(x, 0.0), t1, t2);
195 z1 = L::set(L::first(t1), L::second(z1));
196 z2 = L::set(L::first(t2), L::second(z2));
199 double pre = stageOne(
static_cast<double>(data[0]));
202 for (
int i = 1; i <= numSamples; ++i)
204 const bool more = i < numSamples;
205 const V kept1 = z1, kept2 = z2;
206 const V y = L::step(b0, b1, b2, a1, a2,
207 L::set(more ?
static_cast<double>(data[i]) : 0.0, pre), z1, z2);
209 const double filtered = L::second(y);
210 if (accumulate(filtered * filtered))
214 z1 = L::set(0.0, 0.0);
215 z2 = L::set(0.0, 0.0);
217 pre = stageOne(
static_cast<double>(data[i]));
221 z1 = L::set(L::first(kept1), L::second(z1));
222 z2 = L::set(L::first(kept2), L::second(z2));
225 preState_[0] = { L::first(z1), L::first(z2) };
226 rlbState_[0] = { L::second(z1), L::second(z2) };
235 void process(
const T* left,
const T* right,
int numSamples)
noexcept
237 if (!prepared_.load(std::memory_order_relaxed)
238 || left ==
nullptr || right ==
nullptr || numSamples <= 0)
241 const T peakLeft = measureTruePeak(left, 0, numSamples,
242 truePeakMax_.load(std::memory_order_relaxed));
243 truePeakMax_.store(measureTruePeak(right, 1, numSamples, peakLeft), std::memory_order_relaxed);
249 using V =
typename L::V;
250 const V pb0 = L::set(pre_.b0, pre_.b0), pb1 = L::set(pre_.b1, pre_.b1);
251 const V pb2 = L::set(pre_.b2, pre_.b2), pa1 = L::set(pre_.a1, pre_.a1);
252 const V pa2 = L::set(pre_.a2, pre_.a2);
253 const V rb0 = L::set(rlb_.b0, rlb_.b0), rb1 = L::set(rlb_.b1, rlb_.b1);
254 const V rb2 = L::set(rlb_.b2, rlb_.b2), ra1 = L::set(rlb_.a1, rlb_.a1);
255 const V ra2 = L::set(rlb_.a2, rlb_.a2);
256 V pz1 = L::set(preState_[0].z1, preState_[1].z1);
257 V pz2 = L::set(preState_[0].z2, preState_[1].z2);
258 V rz1 = L::set(rlbState_[0].z1, rlbState_[1].z1);
259 V rz2 = L::set(rlbState_[0].z2, rlbState_[1].z2);
260 V pending = L::step(pb0, pb1, pb2, pa1, pa2,
261 L::set(
static_cast<double>(left[0]),
static_cast<double>(right[0])),
265 for (
int i = 1; i <= numSamples; ++i)
267 const bool more = i < numSamples;
268 const V k = L::step(rb0, rb1, rb2, ra1, ra2, pending, rz1, rz2);
272 x = L::set(
static_cast<double>(left[i]),
static_cast<double>(right[i]));
273 pending = L::step(pb0, pb1, pb2, pa1, pa2, x, pz1, pz2);
275 const double filtL = L::first(k);
276 const double filtR = L::second(k);
277 if (accumulate(filtL * filtL + filtR * filtR))
281 pz1 = L::set(0.0, 0.0);
282 pz2 = L::set(0.0, 0.0);
283 rz1 = L::set(0.0, 0.0);
284 rz2 = L::set(0.0, 0.0);
286 pending = L::step(pb0, pb1, pb2, pa1, pa2, x, pz1, pz2);
289 preState_[0] = { L::first(pz1), L::first(pz2) };
290 preState_[1] = { L::second(pz1), L::second(pz2) };
291 rlbState_[0] = { L::first(rz1), L::first(rz2) };
292 rlbState_[1] = { L::second(rz1), L::second(rz2) };
301 return calculateLUFSFromBlocks(4);
310 return calculateLUFSFromBlocks(30);
322 double sumPowerUngated = 0.0;
323 uint64_t countUngated = 0;
325 for (
int i = 0; i < kNumBins; ++i)
327 sumPowerUngated += histogramPower_[i].load(std::memory_order_relaxed);
328 countUngated += histogram_[i].load(std::memory_order_relaxed);
331 if (countUngated == 0)
return T(-100);
333 double meanPowerUngated = sumPowerUngated / countUngated;
334 double ungatedLUFS = powerToLUFS(meanPowerUngated);
337 double relativeGateLUFS = ungatedLUFS - 10.0;
338 const int relativeGateBin = firstBinAtOrAbove(relativeGateLUFS);
340 double sumPowerGated = 0.0;
341 uint64_t countGated = 0;
343 for (
int i = relativeGateBin; i < kNumBins; ++i)
345 sumPowerGated += histogramPower_[i].load(std::memory_order_relaxed);
346 countGated += histogram_[i].load(std::memory_order_relaxed);
349 if (countGated == 0)
return T(-100);
351 return static_cast<T
>(powerToLUFS(sumPowerGated / countGated));
365 return measurementValid_.load(std::memory_order_relaxed);
386 return gainToDecibels(truePeakMax_.load(std::memory_order_relaxed));
400 if (!prepared_.load(std::memory_order_relaxed))
return;
401 T peak = truePeakMax_.load(std::memory_order_relaxed);
402 for (
int channel = 0; channel < kMaxChannels; ++channel)
404 const T tail =
static_cast<T
>(truePeak_.
getTailPeak(tpChannels_[
static_cast<size_t>(channel)]));
405 if (std::isfinite(tail))
406 peak = std::max(peak, tail);
408 invalidateMeasurement();
410 truePeakMax_.store(peak, std::memory_order_relaxed);
440 double sumPower = 0.0;
442 for (
int i = 0; i < kNumBins; ++i)
444 const uint32_t c = lraHistogram_[i].load(std::memory_order_relaxed);
447 sumPower += lraEnergy_[i].load(std::memory_order_relaxed);
451 if (count == 0)
return T(0);
455 const double relGateLUFS = powerToLUFS(sumPower /
static_cast<double>(count)) - 20.0;
456 const int gateCell = firstRangeCellAtOrAbove(relGateLUFS);
457 const int gateBin = gateCell / kRangeCells;
459 uint64_t gateCells[kRangeCells];
460 rangeCellCounts(gateBin, gateCells);
461 uint64_t gateBinCount = 0;
462 for (
int s = gateCell % kRangeCells; s < kRangeCells; ++s)
463 gateBinCount += gateCells[s];
466 uint64_t gatedCount = gateBinCount;
467 for (
int i = gateBin + 1; i < kNumBins; ++i)
468 gatedCount += lraHistogram_[i].load(std::memory_order_relaxed);
469 if (gatedCount == 0)
return T(0);
475 const auto rank10 =
static_cast<uint64_t
>(std::llround(0.10 *
static_cast<double>(gatedCount - 1)));
476 const auto rank95 =
static_cast<uint64_t
>(std::llround(0.95 *
static_cast<double>(gatedCount - 1)));
479 auto valueAt = [&](
int bin, uint64_t rankInBin)
noexcept {
480 uint64_t cells[kRangeCells];
481 const int first = bin == gateBin ? gateCell % kRangeCells : 0;
483 std::copy(gateCells, gateCells + kRangeCells, cells);
485 rangeCellCounts(bin, cells);
488 for (
int s = first; s < kRangeCells; ++s)
490 if (cells[s] == 0)
continue;
493 if (seen > rankInBin)
break;
497 const int cell = lastFilled >= 0 ? lastFilled : kRangeCells / 2;
498 return rangeCellCentre(bin * kRangeCells + cell);
501 double p10 = 0.0, p95 = 0.0;
502 uint64_t running = 0;
504 for (
int i = gateBin; i < kNumBins; ++i)
506 const uint64_t c = i == gateBin ? gateBinCount
507 : lraHistogram_[i].load(std::memory_order_relaxed);
508 if (c == 0)
continue;
510 if (!have10 && running + c > rank10)
512 p10 = valueAt(i, rank10 - running);
515 if (running + c > rank95)
517 p95 = valueAt(i, rank95 - running);
522 return static_cast<T
>(std::max(0.0, p95 - p10));
534 for (
int ch = 0; ch < kMaxChannels; ++ch)
540 for (
auto& power : blockPowers_)
541 power.store(0.0, std::memory_order_relaxed);
543 for (
auto& bin : histogram_)
544 bin.store(0, std::memory_order_relaxed);
545 for (
auto& energy : histogramPower_)
546 energy.store(0.0, std::memory_order_relaxed);
547 for (
auto& bin : lraHistogram_)
548 bin.store(0, std::memory_order_relaxed);
549 for (
auto& energy : lraEnergy_)
550 energy.store(0.0, std::memory_order_relaxed);
551 for (
auto& cell : lraCells_)
552 cell.store(0, std::memory_order_relaxed);
554 for (
auto& state : tpChannels_)
556 truePeakMax_.store(T(0), std::memory_order_relaxed);
558 blockWritePos_.store(0, std::memory_order_relaxed);
559 totalCommittedBlocks_ = 0;
560 currentBlockPower_ = 0.0;
561 currentBlockSamples_ = 0;
562 measurementValid_.store(
true, std::memory_order_relaxed);
566 static constexpr int kMaxChannels = 2;
569 static constexpr double kMinHistogramLUFS = -70.0;
570 static constexpr double kMaxHistogramLUFS = 30.0;
571 static constexpr double kBinWidth = 0.1;
572 static constexpr int kNumBins = 1000;
576 static constexpr int kRangeCells = 20;
577 static constexpr double kRangeCellWidth = kBinWidth / kRangeCells;
578 static constexpr int kNumRangeCells = kNumBins * kRangeCells;
579 static constexpr uint16_t kRangeCellMax = std::numeric_limits<uint16_t>::max();
589 struct BiquadState {
double z1 = 0.0, z2 = 0.0; };
590 struct BiquadCoeff {
double b0 = 1.0, b1 = 0.0, b2 = 0.0, a1 = 0.0, a2 = 0.0; };
592 void computeKWeighting(
double sr)
606 pre_ = { shelf.b0, shelf.b1, shelf.b2, shelf.a1, shelf.a2 };
608 rlb_ = { rlb.b0, rlb.b1, rlb.b2, rlb.a1, rlb.a2 };
616 template <
int W,
typename D =
double>
struct KPair
619 static V set(D a, D b)
noexcept {
return { a, b }; }
620 static D first(V v)
noexcept {
return v.
a; }
621 static D second(V v)
noexcept {
return v.b; }
622 static V step(V b0, V b1, V b2, V a1, V a2, V x, V& z1, V& z2)
noexcept
624 const V y { b0.a * x.a + z1.a, b0.b * x.b + z1.b };
625 z1 = { b1.a * x.a - a1.a * y.a + z2.a, b1.b * x.b - a1.b * y.b + z2.b };
626 z2 = { b2.a * x.a - a2.a * y.a + D(1e-18), b2.b * x.b - a2.b * y.b + D(1e-18) };
630 template <
typename D>
struct KPair<2, D>
632 using O = simd::Vec<D, 2>;
633 using V =
typename O::V;
634 static V set(D a, D b)
noexcept {
return O::set2(a, b); }
635 static D first(V v)
noexcept {
return O::lane0(v); }
636 static D second(V v)
noexcept {
return O::lane1(v); }
640 static V step(V b0, V b1, V b2, V a1, V a2, V x, V& z1, V& z2)
noexcept
642 const V y = O::madd(b0, x, z1);
643 z1 = O::add(O::mulSub(b1, x, a1, y), z2);
644 z2 = O::add(O::mulSub(b2, x, a2, y), O::set1(D(1e-18)));
648 using KLane = KPair<simd::kVecDoubleNarrow>;
652 [[nodiscard]]
bool accumulate(
double power)
noexcept
654 currentBlockPower_ += power;
655 if (!std::isfinite(currentBlockPower_))
656 invalidateMeasurement();
657 if (++currentBlockSamples_ >= blockSamples_)
658 return commitBlock();
664 bool commitBlock() noexcept
666 const double meanPower = currentBlockPower_ / currentBlockSamples_;
667 currentBlockPower_ = 0.0;
668 currentBlockSamples_ = 0;
675 if (!std::isfinite(meanPower))
677 invalidateMeasurement();
678 for (
int ch = 0; ch < kMaxChannels; ++ch)
687 int currentPos = blockWritePos_.load(std::memory_order_relaxed);
688 blockPowers_[currentPos].store(meanPower, std::memory_order_relaxed);
690 int nextPos = (currentPos + 1) % 30;
691 blockWritePos_.store(nextPos, std::memory_order_release);
692 ++totalCommittedBlocks_;
698 if (totalCommittedBlocks_ >= 4)
700 double gating400 = meanPower;
701 for (
int back = 1; back < 4; ++back)
703 int idx = (currentPos - back + 30) % 30;
704 gating400 += blockPowers_[idx].load(std::memory_order_relaxed);
708 const double lufs = powerToLUFS(gating400);
709 if (!std::isfinite(gating400) || !std::isfinite(lufs))
711 invalidateMeasurement();
713 else if (lufs >= kMinHistogramLUFS)
715 int binIndex =
static_cast<int>(std::round((lufs - kMinHistogramLUFS) / kBinWidth));
716 if (binIndex >= kNumBins)
717 invalidateMeasurement();
718 binIndex = std::clamp(binIndex, 0, kNumBins - 1);
719 incrementHistogram(histogram_[binIndex]);
720 auto& energy = histogramPower_[
static_cast<size_t>(binIndex)];
721 energy.store(energy.load(std::memory_order_relaxed) + gating400,
722 std::memory_order_relaxed);
730 if (totalCommittedBlocks_ >= 30)
732 const double stPower = meanPowerOfBlocks(30);
733 const double stLufs = powerToLUFS(stPower);
734 if (!std::isfinite(stPower) || !std::isfinite(stLufs))
736 invalidateMeasurement();
738 else if (stLufs >= kMinHistogramLUFS)
740 const double position = std::floor((stLufs - kMinHistogramLUFS + 0.5 * kBinWidth)
742 if (position >=
static_cast<double>(kNumRangeCells))
743 invalidateMeasurement();
744 const int cell =
static_cast<int>(std::clamp(position, 0.0,
745 static_cast<double>(kNumRangeCells - 1)));
746 const int bin = cell / kRangeCells;
747 if (lraHistogram_[bin].load(std::memory_order_relaxed)
748 == std::numeric_limits<uint32_t>::max())
750 invalidateMeasurement();
754 auto& cellCount = lraCells_[
static_cast<size_t>(cell)];
755 const uint16_t c = cellCount.load(std::memory_order_relaxed);
756 if (c < kRangeCellMax)
757 cellCount.store(
static_cast<uint16_t
>(c + 1), std::memory_order_relaxed);
758 auto& energy = lraEnergy_[
static_cast<size_t>(bin)];
759 energy.store(energy.load(std::memory_order_relaxed) + stPower,
760 std::memory_order_relaxed);
761 lraHistogram_[bin].fetch_add(1, std::memory_order_relaxed);
769 [[nodiscard]]
double meanPowerOfBlocks(
int numBlocks)
const noexcept
772 const int currentPos = blockWritePos_.load(std::memory_order_acquire);
773 for (
int i = 0; i < numBlocks; ++i)
775 const int idx = (currentPos - 1 - i + 30) % 30;
776 sum += blockPowers_[idx].load(std::memory_order_relaxed);
778 return sum / numBlocks;
784 void rangeCellCounts(
int bin, uint64_t (&out)[kRangeCells])
const noexcept
788 for (
int s = 0; s < kRangeCells; ++s)
790 const uint16_t v = lraCells_[
static_cast<size_t>(bin * kRangeCells + s)]
791 .load(std::memory_order_relaxed);
794 if (v == kRangeCellMax && full < 0) full = s;
796 const uint64_t total = lraHistogram_[
static_cast<size_t>(bin)].load(std::memory_order_relaxed);
797 if (full >= 0 && total > sum)
798 out[full] += total - sum;
802 [[nodiscard]]
static int firstRangeCellAtOrAbove(
double lufs)
noexcept
804 const double position
805 = std::ceil((lufs - kMinHistogramLUFS + 0.5 * kBinWidth) / kRangeCellWidth - 0.5);
806 return static_cast<int>(std::clamp(position, 0.0,
static_cast<double>(kNumRangeCells - 1)));
810 [[nodiscard]]
static double rangeCellCentre(
int cell)
noexcept
812 return kMinHistogramLUFS - 0.5 * kBinWidth + (
static_cast<double>(cell) + 0.5) * kRangeCellWidth;
818 [[nodiscard]] T measureTruePeak(
const T* x,
int channel,
int numSamples, T peak)
noexcept
820 auto& state = tpChannels_[
static_cast<size_t>(channel)];
821 for (
int start = 0; start < numSamples; start += kTruePeakChunk)
823 const int n = std::min(kTruePeakChunk, numSamples - start);
827 for (
int i = 0; i < n; ++i)
829 const T a = std::abs(x[start + i]);
830 if (!std::isfinite(a))
831 invalidateMeasurement();
835 const T chunkPeak =
static_cast<T
>(truePeak_.
processMax(state, narrow(x + start, n), n, readerFloor(peak)));
836 if (chunkPeak > peak)
844 [[nodiscard]]
static float readerFloor(T peak)
noexcept
846 if constexpr (std::is_same_v<T, float>)
852 constexpr T kFloatMax =
static_cast<T
>(std::numeric_limits<float>::max());
854 constexpr float kDown = 1.0f - 2.0f * std::numeric_limits<float>::epsilon();
855 return static_cast<float>(std::min(peak, kFloatMax)) * kDown;
863 [[nodiscard]]
const float* narrow(
const T* x,
int n)
noexcept
865 if constexpr (std::is_same_v<T, float>)
867 static_cast<void>(n);
872 constexpr T kFloatMax =
static_cast<T
>(std::numeric_limits<float>::max());
873 for (
int i = 0; i < n; ++i)
877 tpNarrow_[i] =
static_cast<float>(v > kFloatMax ? kFloatMax : (v < -kFloatMax ? -kFloatMax : v));
883 void invalidateMeasurement() noexcept
885 measurementValid_.store(
false, std::memory_order_relaxed);
888 void incrementHistogram(std::atomic<uint32_t>& bin)
noexcept
890 if (bin.load(std::memory_order_relaxed)
891 == std::numeric_limits<uint32_t>::max())
893 invalidateMeasurement();
896 bin.fetch_add(1, std::memory_order_relaxed);
899 T calculateLUFSFromBlocks(
int numBlocks)
const noexcept
902 int currentPos = blockWritePos_.load(std::memory_order_acquire);
904 for (
int i = 0; i < numBlocks; ++i)
906 int idx = (currentPos - 1 - i + 30) % 30;
907 sum += blockPowers_[idx].load(std::memory_order_relaxed);
910 return static_cast<T
>(powerToLUFS(sum / numBlocks));
915 [[nodiscard]]
static int firstBinAtOrAbove(
double lufs)
noexcept
917 const double position = std::ceil((lufs - kMinHistogramLUFS) / kBinWidth);
918 return static_cast<int>(std::clamp(position, 0.0,
static_cast<double>(kNumBins - 1)));
921 [[nodiscard]]
static double powerToLUFS(
double meanPower)
noexcept
923 if (meanPower <= 1e-10)
return -100.0;
924 return std::max(-100.0, -0.691 + 10.0 * std::log10(meanPower));
927 double sampleRate_ = 48000.0;
928 std::atomic<bool> prepared_{
false };
930 BiquadCoeff pre_, rlb_;
931 BiquadState preState_[kMaxChannels], rlbState_[kMaxChannels];
933 int blockSamples_ = 4800;
934 double currentBlockPower_ = 0.0;
935 int currentBlockSamples_ = 0;
938 std::array<std::atomic<double>, 30> blockPowers_;
939 std::atomic<int> blockWritePos_{0};
940 int64_t totalCommittedBlocks_ = 0;
944 std::array<std::atomic<uint32_t>, kNumBins> histogram_;
945 std::array<std::atomic<double>, kNumBins> histogramPower_;
949 std::array<std::atomic<uint32_t>, kNumBins> lraHistogram_;
950 std::array<std::atomic<double>, kNumBins> lraEnergy_;
951 std::array<std::atomic<uint16_t>, kNumRangeCells> lraCells_;
954 std::atomic<bool> measurementValid_ {
true };
957 TruePeakReader truePeak_;
958 std::array<TruePeakReader::Channel, kMaxChannels> tpChannels_ {};
960 float tpNarrow_[std::is_same_v<T, float> ? 1 : kTruePeakChunk] = {};
961 std::atomic<T> truePeakMax_ { T(0) };