398#include "../Core/DspMath.h"
399#include "../Core/AudioBuffer.h"
400#include "../Core/AudioSpec.h"
401#include "../Core/FFT.h"
402#include "../Core/detail/AccountedAllocator.h"
403#include "OnsetDetector.h"
418namespace detail {
template <FloatType T>
struct OfflineBeatEngine; }
431template <FloatType T>
434 template <
typename U>
435 using WorkVector = std::vector<U, detail::AccountedAllocator<U>>;
442 for (
auto* values : {&bankPeriod_, &bankCosCoef_, &bankSinCoef_, &bankDecay_,
443 &bankPrior_, &zRe_, &zIm_, &zMass_, &bankCoherence_,
444 &bankLevelRatio_, &env_, &envBal_, &local_, &cumScore_,
445 &acf_, &scratchA_, &kernel_, &localPeriod_,
446 &localTightness_, &candScore_, &candExplains_, &beatScore_,
447 &beatScratch_, &beatAhead_, &beatLogLag_, &beatWeightTable_,
448 &combRing_, &combSum_, &combTime_, &combSpec_, &combAcf_,
449 &combDelta_, &combNext_, &combStep_, &combPrior_, &combKernel_,
451 *values = WorkVector<double>(doubles);
452 for (
auto& values : envReg_) values = WorkVector<double>(doubles);
456 onset_.setLinearFlux(
true);
493 prepared_.store(
false, std::memory_order_relaxed);
496 onset_.prepare(spec);
497 hop_ = onset_.getHopSize();
498 if (hop_ < 1) hop_ = 1;
499 frameRate_ = sampleRate_ /
static_cast<double>(hop_);
500 baselineCoef_ = 1.0 - std::exp(-1.0 / std::max(1.0, kBaselineSeconds * frameRate_));
501 peakDecay_ = std::exp(-1.0 / std::max(1.0, kScorePeakSeconds * frameRate_));
503 latencySamples_.store(
static_cast<int64_t
>(onset_.getEnvelopeLatencySamples())
504 + 2 *
static_cast<int64_t
>(hop_),
505 std::memory_order_relaxed);
512 candidates_.reserve(64);
515 prepared_.store(
true, std::memory_order_relaxed);
528 if (!std::isfinite(minBpm) || !std::isfinite(maxBpm))
return;
529 if (!(minBpm > T(0)) || !(maxBpm > T(0)) || !(minBpm <= maxBpm))
return;
531 const double lo = std::clamp(
static_cast<double>(minBpm),
532 kBankMinBpm, kBankMaxBpm);
533 const double hi = std::clamp(
static_cast<double>(maxBpm),
534 kBankMinBpm, kBankMaxBpm);
535 requestedRange_.store(packTempo(
static_cast<float>(lo),
static_cast<float>(hi)),
536 std::memory_order_relaxed);
543 if (bankSize_ < 2)
return;
544 float requestedLo = 0.0f, requestedHi = 0.0f;
545 unpackTempo(requestedRange_.load(std::memory_order_relaxed), requestedLo, requestedHi);
546 const double lo =
static_cast<double>(requestedLo);
547 const double hi =
static_cast<double>(requestedHi);
551 int iLo = bpmToIndex(hi);
552 int iHi = bpmToIndex(lo);
553 iLo = std::clamp(iLo, 0, bankSize_ - 1);
554 iHi = std::clamp(iHi, 0, bankSize_ - 1);
555 if (iLo > iHi) std::swap(iLo, iHi);
560 activeRange_.store(packRange(iLo, iHi), std::memory_order_relaxed);
618 if (!std::isfinite(alpha))
return;
619 tightness_.store(std::max(kMinTightness,
static_cast<double>(alpha)),
620 std::memory_order_relaxed);
626 return static_cast<T
>(tightness_.load(std::memory_order_relaxed));
632 return static_cast<T
>(kDefaultTightness);
650 if (!prepared_.load(std::memory_order_relaxed))
return {};
678 for (
auto& r : envReg_) r.clear();
679 offlineOpen_ =
false;
680 if (!prepared_.load(std::memory_order_relaxed))
return;
683 if (expectedSamples > 0)
685 const size_t frames =
static_cast<size_t>(expectedSamples / std::max(1, hop_) + 2);
686 env_.reserve(frames);
687 envRef_.reserve(frames);
688 for (
auto& r : envReg_) r.reserve(frames);
698 if (!offlineOpen_)
return;
700 while (off < samples.size())
704 const int64_t since = offlinePushed_ %
static_cast<int64_t
>(hop_);
705 const size_t take = std::min(samples.size() - off,
706 static_cast<size_t>(
static_cast<int64_t
>(hop_) - since));
707 onset_.pushSamples(samples.subspan(off, take));
708 offlinePushed_ +=
static_cast<int64_t
>(take);
710 if (offlinePushed_ %
static_cast<int64_t
>(hop_) == 0) appendEnvelopeFrame();
720 if (!offlineOpen_)
return out;
721 offlineOpen_ =
false;
724 return finishEnvelope();
733 if (!prepared_.load(std::memory_order_relaxed) || in.getNumChannels() < 1)
735 const T* ch0 = in.getChannel(0);
736 pushSamples(std::span<const T>(ch0,
static_cast<size_t>(in.getNumSamples())));
749 if (!prepared_.load(std::memory_order_relaxed))
return;
753 while (off < samples.size())
755 const int64_t sinceFrame = samplesPushed_ %
static_cast<int64_t
>(hop_);
756 const size_t toBoundary =
static_cast<size_t>(
static_cast<int64_t
>(hop_)
758 const size_t take = std::min(samples.size() - off, toBoundary);
760 onset_.pushSamples(samples.subspan(off, take));
761 samplesPushed_ +=
static_cast<int64_t
>(take);
764 if (
static_cast<size_t>(take) == toBoundary)
766 if (advanceFrame()) fired =
true;
779 beatLatched_.store(fired, std::memory_order_release);
797 return static_cast<T
>(beatTempo_.load(std::memory_order_relaxed));
803 float bpm = 0.0f, conf = 0.0f;
804 unpackTempo(tempoAndConfidence_.load(std::memory_order_relaxed), bpm, conf);
805 return static_cast<T
>(bpm);
836 float bpm = 0.0f, conf = 0.0f;
837 unpackTempo(tempoAndConfidence_.load(std::memory_order_relaxed), bpm, conf);
838 return static_cast<T
>(conf);
852 float bpm = 0.0f, conf = 0.0f;
853 unpackTempo(tempoAndConfidence_.load(std::memory_order_relaxed), bpm, conf);
854 bpmOut =
static_cast<T
>(bpm);
855 confidenceOut =
static_cast<T
>(conf);
876 return beatLatched_.load(std::memory_order_acquire);
894 return lastBeatSample_.load(std::memory_order_relaxed);
908 return static_cast<int>(latencySamples_.load(std::memory_order_relaxed));
912 [[nodiscard]]
double getFrameRate() const noexcept {
return frameRate_; }
925 offlineOpen_ =
false;
932 Result finishEnvelope(
void* beatContext =
nullptr,
933 void (*receiveBeats)(
void*, std::span<const int64_t>) =
nullptr)
936 int iLo = 0, iHi = 0;
937 unpackRange(activeRange_.load(std::memory_order_relaxed), iLo, iHi);
939 const int n =
static_cast<int>(env_.size());
940 const double maxPeriod = bankPeriod_[
static_cast<size_t>(iHi)];
941 if (n <
static_cast<int>(kMinAnalysisBeats * maxPeriod))
952 double tau1 = 0.0, tau2 = 0.0;
953 const bool balanced = (envBal_.size() == env_.size());
954 if (balanced) env_.swap(envBal_);
955 pickCandidates(iLo, iHi, tau1, tau2);
956 if (balanced) env_.swap(envBal_);
957 if (!(tau1 > 0.0)) { resetState();
return out; }
963 if (fundamentalFound_) chooseMetricalLevel(iLo, iHi, tau1, tau2);
969 WorkVector<int64_t> win(detail::AccountedAllocator<int64_t>{&allocationAccount_});
970 if (!layGrid(tau1, win))
980 const double slope = fitBeatSlope(win);
982 receiveBeats(beatContext, {win.data(), win.size()});
984 out.beatSamples.assign(win.begin(), win.end());
985 out.tempoBpm =
static_cast<T
>((slope > 0.0) ? 60.0 * sampleRate_ / slope
986 : periodToBpm(tau1));
987 out.secondaryTempoBpm =
static_cast<T
>((tau2 > 0.0) ? periodToBpm(tau2) : 0.0);
997 const double base = coherence((slope > 0.0) ? slope /
static_cast<double>(hop_)
999 out.confidence =
static_cast<T
>(std::clamp(base * ambiguityDiscount(secondaryShare_),
1008 static constexpr double kBankMinBpm = 20.0;
1009 static constexpr double kBankMaxBpm = 480.0;
1018 static constexpr double kHarmonicReach = 5.0;
1019 static constexpr int kBinsPerOctave = 128;
1020 static constexpr double kDefaultMinBpm = 40.0;
1021 static constexpr double kDefaultMaxBpm = 240.0;
1035 static constexpr int kNumHarmonics = 3;
1036 static constexpr double kHarmonicDivisors[kNumHarmonics] = { 2.0, 3.0, 5.0 };
1042 static constexpr double kIntegrationBeats = 8.0;
1046 static constexpr double kPriorCentreSeconds = 0.5;
1047 static constexpr double kPriorWidthOctaves = 1.4;
1069 static constexpr double kTactusFastOctaves = 0.45;
1070 static constexpr double kTactusSlowOctaves = kPriorWidthOctaves;
1096 static constexpr int kLevelCandidates = 3;
1097 static constexpr int kLevelMiddle = 1;
1098 static constexpr size_t kLevelRawFeatures = 18;
1099 static constexpr size_t kLevelShareAtPeriod = 1;
1100 static constexpr size_t kLevelBalancedShareAtPeriod = 2;
1101 static constexpr size_t kLevelShareAtDouble = 7;
1102 static constexpr size_t kLevelShareAtTriple = 14;
1103 static constexpr std::array<double, kLevelCandidates> kLevelMultiples = { 0.5, 1.0, 2.0 };
1104 static constexpr std::array<double, kLevelCandidates> kLevelBias = {
1105 -0.975336646, +0.092188351, +0.883148294 };
1106 static constexpr std::array<double, 2 * kLevelRawFeatures + 1> kLevelWeights = {
1108 -0.542395096, -0.584902910, +0.498236961,
1109 +2.173179030, +0.290865194, +0.064019696,
1110 -0.056958253, -1.551139582, +2.419398334,
1111 +0.999335380, +1.771192530, +1.715518634,
1112 -0.269329648, -0.242521186, +0.512883972,
1113 +2.417326254, -4.177049390, -0.658688841,
1115 -0.740402303, -0.614477620, +0.536878776,
1116 +2.283943101, +0.321349606, +0.070567309,
1117 -0.060601959, -1.661774996, +2.331723324,
1118 +1.031193638, +1.895745003, +1.908437878,
1119 -0.571387423, -0.456177537, +0.860604058,
1120 +4.361899112, -4.360371230, -0.993521862,
1131 static constexpr std::array<double, 4> kTernaryMultiples = {
1132 1.0 / 3.0, 2.0 / 3.0, 1.5, 3.0 };
1133 static constexpr std::array<double, 4> kTernaryBias = {
1134 0.53602663631392855, -0.44218443943636193, -0.98844100123510192,
1135 -4.3780218173667675 };
1136 static constexpr std::array<double, 2 * kLevelRawFeatures + 1> kTernaryWeights = {
1137 0.135530296867787, 1.516476106187614, 0.50512741958750595,
1138 -3.2226909770906635, 0.76647827698580318, -0.5179245237669392,
1139 1.354793380662362, -2.8513739655680381, -2.7957191619709669,
1140 -0.93155463697868401, -0.59124401355810241, 0.57664680014957181,
1141 -0.83331592757939144, -0.92868430654211009, 0.72147135283011565,
1142 1.342529710852844, -0.78142066296951229, 2.2830394447846869,
1143 -0.71810354059356818, 0.89986068541218478, 0.41744186276874551,
1144 1.3685809837441467, 1.8839328472219159, -0.48244306625392142,
1145 0.89516613728223393, -0.60386251174497119, 1.8096407974850166,
1146 2.9213215771564656, 4.4113655210180074, 3.2066836727020585,
1147 2.0230309593047608, 2.7743701263252531, -2.8072203231223085,
1148 -0.60235479209693188, 0.10118126378289685, -2.5817564678948961,
1149 -0.67204847147376856 };
1163 static constexpr double kLevelContrastFloor = 0.1;
1165 static constexpr double kLevelWindowBeats = 8.0;
1169 static constexpr double kDefaultTightness = 400.0;
1170 static constexpr double kMinTightness = 1e-3;
1180 static constexpr double kMinFundamentalCoherence = 0.1;
1195 static constexpr double kAmbiguityFloor = 0.5;
1200 static constexpr double kCandidateSeparationOctaves = 0.25;
1204 static constexpr double kCandidatePeakFloor = 0.25;
1216 static constexpr double kNeighbourPeakFloor = 0.6;
1217 static constexpr double kNeighbourOctaves = 0.35;
1223 static constexpr double kFollowTightness = 25.0;
1229 static constexpr int kPeriodReachBeats = 4;
1238 static constexpr double kStepSpreadShare = 1.0 / 3.0;
1246 static constexpr double kHoldWidth = 0.08;
1256 static constexpr double kHoldSpreads = 4.0;
1257 static constexpr double kSteadyHoldWidth = 0.02;
1263 static constexpr double kHoldReachOctaves = 1.0 / 3.0;
1268 static constexpr double kRecentreOctaves = 0.03;
1275 static constexpr double kSecondTempoNear = 0.25;
1276 static constexpr double kSecondTempoFar = 2.0 * kHoldReachOctaves;
1284 static constexpr double kSecondTempoPeakFloor = 0.3;
1304 static constexpr double kSecondTempoShare = 0.25;
1305 static constexpr size_t kSecondTempoRun = 8;
1306 static constexpr double kSecondTempoGain = 1.15;
1314 static constexpr double kIntervalCapBeats = 8.0;
1321 static constexpr double kHeldShare = 0.5;
1325 static constexpr double kMinAnalysisBeats = 4.0;
1330 static constexpr double kCoherenceWindowBeats = 8.0;
1333 static constexpr double kBaselineSeconds = 1.0;
1337 static constexpr double kLocalScoreSigmaPeriods = 1.0 / 32.0;
1340 static constexpr double kSearchLowFactor = 0.5;
1341 static constexpr double kSearchHighFactor = 2.0;
1345 static constexpr double kExtendFraction = 0.125;
1353 static constexpr double kSupportFraction = 0.25;
1360 static constexpr double kEdgeSupportFraction = 0.5;
1361 static constexpr double kEdgeSeconds = 0.06;
1363 static_assert(std::atomic<std::uint64_t>::is_always_lock_free,
1364 "audio-thread stores must not lock");
1365 static_assert(std::atomic<std::uint32_t>::is_always_lock_free,
1366 "audio-thread stores must not lock");
1367 static_assert(std::atomic<std::int64_t>::is_always_lock_free,
1368 "audio-thread stores must not lock");
1369 static_assert(std::atomic<bool>::is_always_lock_free,
1370 "audio-thread stores must not lock");
1371 static_assert(std::atomic<float>::is_always_lock_free,
1372 "audio-thread stores must not lock");
1373 static_assert(std::atomic<double>::is_always_lock_free,
1374 "audio-thread stores must not lock");
1382 [[nodiscard]]
static std::uint64_t packTempo(
float bpm,
float conf)
noexcept
1384 std::uint32_t a = 0, b = 0;
1385 std::memcpy(&a, &bpm,
sizeof(a));
1386 std::memcpy(&b, &conf,
sizeof(b));
1387 return (
static_cast<std::uint64_t
>(a) << 32) |
static_cast<std::uint64_t
>(b);
1390 static void unpackTempo(std::uint64_t v,
float& bpm,
float& conf)
noexcept
1392 const std::uint32_t a =
static_cast<std::uint32_t
>(v >> 32);
1393 const std::uint32_t b =
static_cast<std::uint32_t
>(v & 0xFFFFFFFFu);
1394 std::memcpy(&bpm, &a,
sizeof(bpm));
1395 std::memcpy(&conf, &b,
sizeof(conf));
1398 [[nodiscard]]
static std::uint32_t packRange(
int lo,
int hi)
noexcept
1400 return (
static_cast<std::uint32_t
>(lo & 0xFFFF) << 16)
1401 |
static_cast<std::uint32_t
>(hi & 0xFFFF);
1404 static void unpackRange(std::uint32_t v,
int& lo,
int& hi)
noexcept
1406 lo =
static_cast<int>((v >> 16) & 0xFFFFu);
1407 hi =
static_cast<int>(v & 0xFFFFu);
1412 [[nodiscard]]
double periodToBpm(
double periodFrames)
const noexcept
1414 return (periodFrames > 0.0) ? 60.0 * frameRate_ / periodFrames : 0.0;
1417 [[nodiscard]]
double bpmToPeriod(
double bpm)
const noexcept
1419 return (bpm > 0.0) ? 60.0 * frameRate_ / bpm : 0.0;
1423 [[nodiscard]]
int bpmToIndex(
double bpm)
const noexcept
1425 const double p = bpmToPeriod(bpm);
1426 if (!(p > 0.0) || bankSize_ < 1)
return 0;
1427 const double x = std::log2(p / bankPeriod_[0])
1428 *
static_cast<double>(kBinsPerOctave);
1429 return std::clamp(
static_cast<int>(std::lround(x)), 0, bankSize_ - 1);
1434 const double pMin = bpmToPeriod(kBankMaxBpm);
1435 const double pMax = bpmToPeriod(kBankMinBpm) * kHarmonicReach;
1436 const double octaves = std::log2(pMax / pMin);
1437 bankSize_ =
static_cast<int>(std::lround(octaves
1438 *
static_cast<double>(kBinsPerOctave))) + 1;
1439 bankSize_ = std::max(bankSize_, 2 * kBinsPerOctave + 2);
1441 bankPeriod_.assign(
static_cast<size_t>(bankSize_), 0.0);
1442 bankCosCoef_.assign(
static_cast<size_t>(bankSize_), 0.0);
1443 bankSinCoef_.assign(
static_cast<size_t>(bankSize_), 0.0);
1444 bankDecay_.assign(
static_cast<size_t>(bankSize_), 0.0);
1445 bankPrior_.assign(
static_cast<size_t>(bankSize_), 0.0);
1446 zRe_.assign(
static_cast<size_t>(bankSize_), 0.0);
1447 zIm_.assign(
static_cast<size_t>(bankSize_), 0.0);
1448 zMass_.assign(
static_cast<size_t>(bankSize_), 0.0);
1449 bankCoherence_.assign(
static_cast<size_t>(bankSize_), 0.0);
1451 const double centre = kPriorCentreSeconds * frameRate_;
1452 for (
int i = 0; i < bankSize_; ++i)
1454 const double p = pMin * std::pow(2.0,
static_cast<double>(i)
1455 /
static_cast<double>(kBinsPerOctave));
1456 bankPeriod_[
static_cast<size_t>(i)] = p;
1458 const double w = 2.0 *
static_cast<double>(pi<double>) / p;
1459 const double lambda = std::exp(-1.0 / (kIntegrationBeats * p));
1460 bankDecay_[
static_cast<size_t>(i)] = lambda;
1461 bankCosCoef_[
static_cast<size_t>(i)] = lambda * std::cos(w);
1462 bankSinCoef_[
static_cast<size_t>(i)] = lambda * std::sin(w);
1464 const double lg = std::log2(p / centre) / kPriorWidthOctaves;
1465 bankPrior_[
static_cast<size_t>(i)] = std::exp(-0.5 * lg * lg);
1472 for (
int k = 0; k < kNumHarmonics; ++k)
1473 harmonicOffset_[k] =
static_cast<int>(std::lround(
1474 std::log2(kHarmonicDivisors[k]) *
static_cast<double>(kBinsPerOctave)));
1478 bankLevelRatio_.assign(
static_cast<size_t>(kNumHarmonics)
1479 *
static_cast<size_t>(bankSize_), 1.0);
1480 for (
int k = 0; k < kNumHarmonics; ++k)
1481 for (
int i = 0; i < bankSize_; ++i)
1482 bankLevelRatio_[
static_cast<size_t>(k) *
static_cast<size_t>(bankSize_)
1483 +
static_cast<size_t>(i)]
1484 = levelRatio(bankPeriod_[
static_cast<size_t>(i)], kHarmonicDivisors[k]);
1498 bool advanceFrame() noexcept
1500 const typename OnsetDetector<T>::OdfFrame f = onset_.getLastOdfFrame();
1503 const double raw = (std::isfinite(f.value) && f.value > T(0))
1504 ?
static_cast<double>(f.value) : 0.0;
1505 lastFrameRef_ = f.referenceSample;
1516 baseline_ += (raw - baseline_) * baselineCoef_;
1517 const double o = std::max(0.0, raw - baseline_);
1525 const double rawLinear = (std::isfinite(f.linear) && f.linear > T(0))
1526 ?
static_cast<double>(f.linear) : 0.0;
1527 linearBaseline_ += (rawLinear - linearBaseline_) * baselineCoef_;
1528 const double oLinear = std::max(0.0, rawLinear - linearBaseline_);
1529 scorePeak_ = std::max(o, scorePeak_ * peakDecay_);
1530 scorePeakLinear_ = std::max(oLinear, scorePeakLinear_ * peakDecay_);
1531 const double oBeat = o / std::max(kMassFloor, scorePeak_)
1532 + oLinear / std::max(kMassFloor, scorePeakLinear_);
1534 for (
int i = 0; i < bankSize_; ++i)
1536 const size_t u =
static_cast<size_t>(i);
1537 const double cr = bankCosCoef_[u];
1538 const double ci = bankSinCoef_[u];
1539 const double re = zRe_[u];
1540 const double im = zIm_[u];
1541 zRe_[u] = cr * re - ci * im + o;
1542 zIm_[u] = cr * im + ci * re;
1543 zMass_[u] = bankDecay_[u] * zMass_[u] + o;
1545 const double mass = zMass_[u];
1546 bankCoherence_[u] = (mass > kMassFloor)
1547 ? std::min(1.0, std::sqrt(zRe_[u] * zRe_[u]
1548 + zIm_[u] * zIm_[u]) / mass)
1554 updateBeatScore(oBeat);
1558 int iLo = 0, iHi = 0;
1559 unpackRange(activeRange_.load(std::memory_order_relaxed), iLo, iHi);
1560 iLo = std::clamp(iLo, 0, bankSize_ - 1);
1561 iHi = std::clamp(iHi, iLo, bankSize_ - 1);
1564 double bestScore = 0.0;
1565 for (
int i = iLo; i <= iHi; ++i)
1567 const double s = scoreAt(i);
1568 if (s > bestScore) { bestScore = s; best = i; }
1578 return advanceBeatClock();
1583 int follow = holdMetricalLevel(best, bestScore, iLo, iHi);
1590 combFollow_ = foldToFundamental(combBin_, iLo, iHi);
1591 combAlike_ = sameEventsAtHalfPeriod(combFollow_, best);
1594 follow = combAlike_ ? best : std::clamp(combFollow_, iLo, iHi);
1603 double runnerUp = 0.0;
1604 const int apart = std::max(1,
static_cast<int>(kCandidateSeparationOctaves
1606 for (
int i = iLo; i <= iHi; ++i)
1608 if (std::abs(i - best) < apart)
continue;
1609 runnerUp = std::max(runnerUp, scoreAt(i,
false));
1611 const double bestExplains = scoreAt(best,
false);
1612 const double share = (bestExplains > 0.0)
1613 ? std::clamp(runnerUp / bestExplains, 0.0, 1.0) : 0.0;
1622 const int searched = best;
1623 best = walkToCoherencePeak(best);
1625 const size_t ub =
static_cast<size_t>(best);
1626 const double period = refinePeriod(best);
1627 const double conf = std::clamp(bankCoherence_[ub] * ambiguityDiscount(share),
1632 float rangeLo = 0.0f, rangeHi = 0.0f;
1633 unpackTempo(requestedRange_.load(std::memory_order_relaxed), rangeLo, rangeHi);
1634 tempoAndConfidence_.store(packTempo(std::clamp(
static_cast<float>(periodToBpm(period)),
1636 static_cast<float>(conf)),
1637 std::memory_order_relaxed);
1644 const int held = (follow == searched) ? best : walkToCoherencePeak(follow);
1645 const size_t uh =
static_cast<size_t>(held);
1646 const double p = bankPeriod_[uh];
1647 const double w = 2.0 *
static_cast<double>(pi<double>) / p;
1648 double sinceBeat = std::atan2(zIm_[uh], zRe_[uh]) / w;
1649 while (sinceBeat < 0.0) sinceBeat += p;
1650 while (sinceBeat >= p) sinceBeat -= p;
1651 resonatorLead_ = p - sinceBeat;
1652 beatPeriod_ = (held == best) ? period : refinePeriod(held);
1653 haveBeatPeriod_ =
true;
1654 beatTempo_.store(std::clamp(
static_cast<float>(periodToBpm(beatPeriod_)), rangeLo, rangeHi),
1655 std::memory_order_relaxed);
1656 return advanceBeatClock();
1676 combLength_ = std::max(64,
static_cast<int>(std::lround(kCombSeconds * frameRate_)));
1678 while (size < 2 * combLength_) size <<= 1;
1679 combFftSize_ = size;
1680 combFft_ = std::make_unique<FFTReal<double>>(
static_cast<size_t>(size));
1681 combRing_.assign(
static_cast<size_t>(combLength_), 0.0);
1682 combSum_.assign(
static_cast<size_t>(combLength_) + 1, 0.0);
1683 combTime_.assign(
static_cast<size_t>(size), 0.0);
1684 combSpec_.assign(
static_cast<size_t>(size) + 2, 0.0);
1685 combAcf_.assign(
static_cast<size_t>(size), 0.0);
1686 combDelta_.assign(
static_cast<size_t>(bankSize_), 0.0);
1687 combNext_.assign(
static_cast<size_t>(bankSize_), 0.0);
1688 combStep_.assign(
static_cast<size_t>(bankSize_), 0.0);
1689 combPrior_.assign(
static_cast<size_t>(bankSize_), 0.0);
1690 const double beta = kCombPriorSeconds * frameRate_;
1691 for (
int i = 0; i < bankSize_; ++i)
1693 const double l = bankPeriod_[
static_cast<size_t>(i)];
1694 combPrior_[
static_cast<size_t>(i)] = l / (beta * beta) * std::exp(-0.5 * l * l / (beta * beta));
1696 const double sigma = kCombTransitionOctaves *
static_cast<double>(kBinsPerOctave);
1697 combSpan_ =
static_cast<int>(std::ceil(3.0 * sigma));
1698 combKernel_.assign(
static_cast<size_t>(2 * combSpan_ + 1), 0.0);
1699 regRing_.assign(
static_cast<size_t>(kRegisters) *
static_cast<size_t>(combLength_), 0.0);
1700 for (
int d = -combSpan_; d <= combSpan_; ++d)
1702 const double u =
static_cast<double>(d) / sigma;
1703 combKernel_[
static_cast<size_t>(d + combSpan_)] = std::exp(-0.5 * u * u);
1719 void updateComb(
double o)
noexcept
1721 if (!combFft_)
return;
1722 const int n = combLength_;
1723 combRing_[
static_cast<size_t>(combWrite_ % n)] = o;
1725 if (--combCountdown_ > 0 || combWrite_ <
static_cast<int64_t
>(n / 2))
return;
1726 combCountdown_ = kCombUpdateFrames;
1728 const int m =
static_cast<int>(std::min<int64_t>(combWrite_, n));
1729 for (
int i = 0; i < m; ++i)
1730 combSum_[
static_cast<size_t>(i) + 1] = combSum_[
static_cast<size_t>(i)]
1731 + combRing_[
static_cast<size_t>((combWrite_ - m + i) % n)];
1732 const int half = std::max(1,
static_cast<int>(std::lround(kCombThresholdSeconds * frameRate_)));
1733 std::fill(combTime_.begin(), combTime_.end(), 0.0);
1734 for (
int i = 0; i < m; ++i)
1736 const int a = std::max(0, i - half), b = std::min(m - 1, i + half);
1737 const double mean = (combSum_[
static_cast<size_t>(b) + 1] - combSum_[
static_cast<size_t>(a)])
1738 /
static_cast<double>(b - a + 1);
1739 combTime_[
static_cast<size_t>(i)] = std::max(0.0, combRing_[
static_cast<size_t>((combWrite_ - m + i) % n)] - mean);
1741 combFft_->forward(combTime_.data(), combSpec_.data());
1742 for (
int k = 0; k <= combFftSize_ / 2; ++k)
1744 const double re = combSpec_[
static_cast<size_t>(2 * k)];
1745 const double im = combSpec_[
static_cast<size_t>(2 * k + 1)];
1746 combSpec_[
static_cast<size_t>(2 * k)] = re * re + im * im;
1747 combSpec_[
static_cast<size_t>(2 * k + 1)] = 0.0;
1749 combFft_->inverse(combSpec_.data(), combAcf_.data());
1750 for (
int l = 0; l < m; ++l) combAcf_[static_cast<size_t>(l)] /=
static_cast<double>(m - l);
1752 int iLo = 0, iHi = 0;
1753 unpackRange(activeRange_.load(std::memory_order_relaxed), iLo, iHi);
1754 iLo = std::clamp(iLo, 0, bankSize_ - 1);
1755 iHi = std::clamp(iHi, iLo, bankSize_ - 1);
1761 for (
int i = iLo; i <= iHi; ++i)
1763 const double lag = bankPeriod_[
static_cast<size_t>(i)];
1765 for (
int a = 1; a <= kCombMultiples; ++a)
1767 const int w =
static_cast<int>(std::lround(
static_cast<double>(a - 1) * kCombWidthSeconds * frameRate_));
1768 const int c =
static_cast<int>(std::lround(
static_cast<double>(a) * lag));
1770 for (
int b = c - w; b <= c + w; ++b)
1771 if (b >= 0 && b < m) sum += combAcf_[
static_cast<size_t>(b)];
1772 v += sum /
static_cast<double>(2 * w + 1);
1778 const double h = 0.5 * lag;
1779 const int c0 =
static_cast<int>(h);
1780 const double fr = h -
static_cast<double>(c0);
1782 v += kCombHalfWeight * ((1.0 - fr) * combAcf_[
static_cast<size_t>(c0)]
1783 + fr * combAcf_[
static_cast<size_t>(c0) + 1]);
1785 combNext_[
static_cast<size_t>(i)] = std::max(0.0, v) * combPrior_[
static_cast<size_t>(i)];
1786 total += combNext_[
static_cast<size_t>(i)];
1788 if (!(total > 0.0))
return;
1793 const bool first = combBin_ < 0;
1794 double bestV = 0.0, norm = 0.0;
1796 for (
int j = iLo; j <= iHi; ++j)
1798 double carry = first ? 1.0 : 0.0;
1800 for (
int i = std::max(iLo, j - combSpan_); i <= std::min(iHi, j + combSpan_); ++i)
1801 carry = std::max(carry, combDelta_[
static_cast<size_t>(i)]
1802 * combKernel_[
static_cast<size_t>(i - j + combSpan_)]);
1803 const double v = carry * combNext_[
static_cast<size_t>(j)] / total;
1804 combStep_[
static_cast<size_t>(j)] = v;
1806 if (v > bestV) { bestV = v; bestI = j; }
1808 if (!(norm > 0.0) || bestI < 0)
return;
1809 std::fill(combDelta_.begin(), combDelta_.end(), 0.0);
1810 for (
int j = iLo; j <= iHi; ++j)
1811 combDelta_[
static_cast<size_t>(j)] = combStep_[
static_cast<size_t>(j)] / norm;
1832 [[nodiscard]]
int foldToFundamental(
int i,
int iLo,
int iHi)
const noexcept
1834 int j = std::clamp(i, iLo, iHi);
1835 for (
int guard = 0; guard < kNumHarmonics; ++guard)
1838 for (
int k = 0; k < kNumHarmonics && !moved; ++k)
1840 const int sub = j + harmonicOffset_[k];
1841 if (sub > iHi)
continue;
1843 for (
int q = std::max(0, sub - 3); q <= std::min(bankSize_ - 1, sub + 3); ++q)
1844 if (bankCoherence_[
static_cast<size_t>(q)] > bankCoherence_[
static_cast<size_t>(peak)])
1846 const double c = bankCoherence_[
static_cast<size_t>(peak)];
1847 if (c > kCombFoldFloor && c >= kCombFoldRatio * bankCoherence_[
static_cast<size_t>(j)])
1849 j = std::clamp(peak, iLo, iHi);
1860 void pushRegisters(
const typename OnsetDetector<T>::OdfFrame& f)
noexcept
1862 if (regRing_.empty())
return;
1863 const int n = combLength_;
1864 for (
int g = 0; g < kRegisters; ++g)
1866 const T r = f.registers[
static_cast<size_t>(g)];
1867 const double v = (std::isfinite(r) && r > T(0)) ?
static_cast<double>(r) : 0.0;
1868 regBaseline_[
static_cast<size_t>(g)] += (v - regBaseline_[
static_cast<size_t>(g)]) * baselineCoef_;
1869 regRing_[
static_cast<size_t>(g) *
static_cast<size_t>(n) +
static_cast<size_t>((combWrite_ - 1) % n)]
1870 = std::max(0.0, v - regBaseline_[
static_cast<size_t>(g)]);
1887 [[nodiscard]]
bool sameEventsAtHalfPeriod(
int level,
int fast)
const noexcept
1889 if (regRing_.empty() || level < 0 || fast < 0)
return false;
1890 const double ratio = bankPeriod_[
static_cast<size_t>(level)]
1891 / bankPeriod_[
static_cast<size_t>(fast)];
1892 if (std::abs(std::log2(ratio) - 1.0) > 0.125)
return false;
1893 const int n = combLength_;
1894 const int m =
static_cast<int>(std::min<int64_t>(combWrite_, n));
1895 const int lag =
static_cast<int>(std::lround(bankPeriod_[
static_cast<size_t>(fast)]));
1896 if (2 * lag + 2 >= m)
return false;
1899 for (
int g = 0; g < kRegisters; ++g)
1901 const double* x = ®Ring_[
static_cast<size_t>(g) *
static_cast<size_t>(n)];
1902 const auto at = [&](
int i) {
return x[
static_cast<size_t>((combWrite_ - m + i) % n)]; };
1903 const auto repetition = [&](
int l) {
1905 for (
int q = l - 2; q <= l + 2; ++q)
1907 double xy = 0.0, xx = 0.0, yy = 0.0;
1908 for (
int i = 0; i + q < m; ++i)
1910 const double a = at(i), b = at(i + q);
1911 xy += a * b; xx += a * a; yy += b * b;
1913 if (xx > 0.0 && yy > 0.0) best = std::max(best, xy / std::sqrt(xx * yy));
1917 const double slow = repetition(2 * lag);
1918 if (!(slow > kIsochronyFloor))
continue;
1920 worst = std::min(worst, repetition(lag) / slow);
1922 return any && worst >= kIsochronyRatio;
1927 [[nodiscard]]
int walkToCoherencePeak(
int i)
const noexcept
1929 for (
int guard = 0; guard < 2; ++guard)
1931 if (i > 0 && bankCoherence_[
static_cast<size_t>(i - 1)]
1932 > bankCoherence_[
static_cast<size_t>(i)]) --i;
1933 else if (i + 1 < bankSize_
1934 && bankCoherence_[
static_cast<size_t>(i + 1)]
1935 > bankCoherence_[
static_cast<size_t>(i)]) ++i;
1957 [[nodiscard]]
int holdMetricalLevel(
int best,
double bestScore,
int iLo,
int iHi)
noexcept
1959 const int apart = std::max(1,
static_cast<int>(kCandidateSeparationOctaves
1961 if (heldLevel_ < iLo || heldLevel_ > iHi) { heldLevel_ = -1; levelChallengeFrames_ = 0; }
1962 if (heldLevel_ < 0 || std::abs(best - heldLevel_) < apart)
1965 levelChallengeFrames_ = 0;
1969 const int half = apart / 2;
1971 double heldScore = 0.0;
1972 for (
int i = std::max(iLo, heldLevel_ - half); i <= std::min(iHi, heldLevel_ + half); ++i)
1974 const double sc = scoreAt(i);
1975 if (held < 0 || sc > heldScore) { heldScore = sc; held = i; }
1977 if (bestScore > heldScore) ++levelChallengeFrames_;
1978 else levelChallengeFrames_ = 0;
1979 if (
static_cast<double>(levelChallengeFrames_)
1980 >= kLevelHoldBeats * bankPeriod_[
static_cast<size_t>(best)])
1983 levelChallengeFrames_ = 0;
1996 [[nodiscard]]
double beatIntervalWeight(
int d,
double lnTau)
const noexcept
1998 const double u = beatLogLag_[
static_cast<size_t>(d)] - lnTau;
1999 const double x = (u + kBeatTableSpan) * (
static_cast<double>(kBeatTableSize - 1)
2000 / (2.0 * kBeatTableSpan));
2001 const int k =
static_cast<int>(x + 0.5);
2002 if (k < 0 || k >= kBeatTableSize)
return 0.0;
2003 return beatWeightTable_[
static_cast<size_t>(k)];
2007 void buildBeatScore()
2009 const double pMax = bpmToPeriod(kBankMinBpm);
2011 while (
static_cast<double>(len) < 3.0 * pMax + 8.0) len <<= 1;
2012 beatScoreLen_ = len;
2013 beatScore_.assign(
static_cast<size_t>(len), 0.0);
2014 beatScratch_.assign(
static_cast<size_t>(2 * len), 0.0);
2015 beatAhead_.assign(
static_cast<size_t>(len) + 2, 0.0);
2016 beatLogLag_.assign(
static_cast<size_t>(len) + 1, 0.0);
2017 for (
int d = 1; d <= len; ++d)
2018 beatLogLag_[
static_cast<size_t>(d)] = std::log(
static_cast<double>(d));
2019 beatWeightTable_.assign(
static_cast<size_t>(kBeatTableSize), 0.0);
2020 constexpr double ln2 = 0.6931471805599453;
2021 for (
int k = 0; k < kBeatTableSize; ++k)
2023 const double u = -kBeatTableSpan + 2.0 * kBeatTableSpan *
static_cast<double>(k)
2024 /
static_cast<double>(kBeatTableSize - 1);
2025 const double e = kBeatIntervalSharpness * u;
2026 beatWeightTable_[
static_cast<size_t>(k)]
2027 = (std::abs(u) <= ln2 + 1e-9) ? std::exp(-0.5 * e * e) : 0.0;
2040 void updateBeatScore(
double o)
noexcept
2042 const int mask = beatScoreLen_ - 1;
2044 if (haveBeatPeriod_)
2046 const double tau = beatPeriod_;
2047 const double lnTau = std::log(tau);
2048 const int lo = std::max(1,
static_cast<int>(std::lround(0.5 * tau)));
2049 const int hi = std::min(
static_cast<int>(std::lround(2.0 * tau)),
2050 static_cast<int>(std::min<int64_t>(beatScoreFrames_,
2051 beatScoreLen_ - 1)));
2052 for (
int d = lo; d <= hi; ++d)
2054 const double v = beatIntervalWeight(d, lnTau)
2055 * beatScore_[
static_cast<size_t>((beatScoreWrite_ - d) & mask)];
2056 if (v > best) best = v;
2059 beatScore_[
static_cast<size_t>(beatScoreWrite_ & mask)]
2060 = (1.0 - kBeatScoreFeedback) * o + kBeatScoreFeedback * best;
2082 void predictNextBeat() noexcept
2084 const double tau = beatPeriod_;
2085 const double lnTau = std::log(tau);
2086 const int span = std::max(2,
static_cast<int>(std::lround(tau)));
2087 const int lo = std::max(1,
static_cast<int>(std::lround(0.5 * tau)));
2088 const int hi =
static_cast<int>(std::lround(2.0 * tau));
2089 const int past = std::min(hi + 1,
static_cast<int>(std::min<int64_t>(beatScoreFrames_,
2090 beatScoreLen_ - 1)));
2091 const int mask = beatScoreLen_ - 1;
2092 for (
int i = 0; i < past; ++i)
2093 beatScratch_[
static_cast<size_t>(i)]
2094 = beatScore_[
static_cast<size_t>((beatScoreWrite_ - past + i) & mask)];
2096 int bestK = span / 2;
2097 double bestV = -1.0;
2098 const double centre = 0.5 * tau;
2099 const double spread = kPredictionSpread * tau;
2100 for (
int k = 1; k <= span; ++k)
2102 const int at = past - 1 + k;
2104 for (
int d = lo; d <= hi; ++d)
2106 const int j = at - d;
2108 const double v = beatIntervalWeight(d, lnTau) * beatScratch_[
static_cast<size_t>(j)];
2111 beatScratch_[
static_cast<size_t>(at)] = kBeatScoreFeedback * b;
2112 const double u = (
static_cast<double>(k) - centre) / spread;
2113 const double q = b * std::exp(-0.5 * u * u);
2114 beatAhead_[
static_cast<size_t>(k)] = q;
2115 if (q > bestV) { bestV = q; bestK = k; }
2121 for (
int k = 1; k <= span; ++k)
2123 const double v = beatAhead_[
static_cast<size_t>(k)];
2124 if (k > 1 && v < beatAhead_[
static_cast<size_t>(k - 1)])
continue;
2125 if (k < span && v < beatAhead_[
static_cast<size_t>(k + 1)])
continue;
2126 if (std::abs(wrapToPeriod(
static_cast<double>(k - bestK), tau))
2127 > kRivalSeparation * tau)
2128 rival = std::max(rival, v);
2130 if (rival >= (1.0 - kAmbiguousScore) * bestV)
2132 double lead = resonatorLead_;
2133 while (lead < 0.5) lead += tau;
2134 int k =
static_cast<int>(std::lround(lead));
2135 const int step = std::max(1,
static_cast<int>(std::lround(tau)));
2136 while (k > span) k -= step;
2137 bestK = std::max(1, k);
2140 beatCountdown_ = bestK;
2141 framesToPrediction_ = bestK +
static_cast<int>(std::lround(0.5 * tau));
2145 [[nodiscard]]
static double wrapToPeriod(
double x,
double period)
noexcept
2147 double d = std::fmod(x, period);
2148 if (d > 0.5 * period) d -= period;
2149 if (d < -0.5 * period) d += period;
2167 bool advanceBeatClock() noexcept
2172 lastBeatSample_.store(std::max<int64_t>(0, pendingBeatRef_), std::memory_order_relaxed);
2173 beatPending_ =
false;
2176 if (!haveBeatPeriod_)
return beat;
2177 if (framesToPrediction_ < 0)
2179 if (
static_cast<double>(beatScoreFrames_) >= beatPeriod_) predictNextBeat();
2182 if (beatCountdown_ > 0 && --beatCountdown_ == 0)
2184 beatPending_ =
true;
2185 pendingBeatRef_ = lastFrameRef_ -
static_cast<int64_t
>(hop_);
2187 if (--framesToPrediction_ <= 0) predictNextBeat();
2199 [[nodiscard]]
double refinePeriod(
int i)
const noexcept
2201 if (i <= 0 || i >= bankSize_ - 1)
return bankPeriod_[
static_cast<size_t>(i)];
2202 const double a = scoreAt(i - 1,
false);
2203 const double b = scoreAt(i,
false);
2204 const double c = scoreAt(i + 1,
false);
2205 const double den = a - 2.0 * b + c;
2206 if (!(std::abs(den) > 0.0))
return bankPeriod_[
static_cast<size_t>(i)];
2207 double d = 0.5 * (a - c) / den;
2208 d = std::clamp(d, -0.5, 0.5);
2209 return bankPeriod_[
static_cast<size_t>(i)]
2210 * std::pow(2.0, d /
static_cast<double>(kBinsPerOctave));
2227 [[nodiscard]]
double scoreAt(
int i,
bool withPreference =
true) const noexcept
2229 const size_t u =
static_cast<size_t>(i);
2230 double s = bankPrior_[u] * bankCoherence_[u];
2231 for (
int k = 0; k < kNumHarmonics; ++k)
2233 const int sub = i + harmonicOffset_[k];
2234 if (sub >= bankSize_)
continue;
2235 const double r = withPreference
2236 ? bankLevelRatio_[
static_cast<size_t>(k) *
static_cast<size_t>(bankSize_) + u]
2238 s *= (1.0 - std::min(1.0, r * bankCoherence_[
static_cast<size_t>(sub)]));
2263 [[nodiscard]]
static double levelPreference(
double periodSeconds)
noexcept
2265 const double lg = std::log2(periodSeconds / kPriorCentreSeconds);
2266 const double w = (lg >= 0.0) ? kTactusSlowOctaves : kTactusFastOctaves;
2267 const double x = lg / w;
2268 return std::exp(-0.5 * x * x);
2271 [[nodiscard]]
double levelRatio(
double periodFrames,
double divisor)
const noexcept
2273 if (!(frameRate_ > 0.0) || !(periodFrames > 0.0))
return 1.0;
2274 const double p = periodFrames / frameRate_;
2275 const double here = levelPreference(p);
2276 if (!(here > 0.0))
return 1.0;
2277 return std::max(1.0, levelPreference(p * divisor) / here);
2286 void appendEnvelopeFrame()
2288 const typename OnsetDetector<T>::OdfFrame f = onset_.getLastOdfFrame();
2289 const double v = std::isfinite(f.value) ?
static_cast<double>(f.value) : 0.0;
2290 env_.push_back(std::max(0.0, v));
2291 envRef_.push_back(f.referenceSample);
2292 for (
int g = 0; g < kRegisters; ++g)
2294 const double r =
static_cast<double>(f.registers[
static_cast<size_t>(g)]);
2295 envReg_[
static_cast<size_t>(g)].push_back(std::isfinite(r) ? std::max(0.0, r) : 0.0);
2310 void conditionEnvelope()
2312 const int n =
static_cast<int>(env_.size());
2330 bool haveRegisters =
false;
2331 for (
const auto& r : envReg_)
2332 if (static_cast<int>(r.size()) == n)
2333 for (const double v : r)
2334 if (v > 0.0) { haveRegisters =
true;
break; }
2342 int iLo = 0, iHi = 0;
2343 unpackRange(activeRange_.load(std::memory_order_relaxed), iLo, iHi);
2344 const int lagLo = std::max(1,
static_cast<int>(std::floor(bankPeriod_[
static_cast<size_t>(iLo)])));
2345 const int lagHi = std::min(n / 2,
static_cast<int>(std::ceil(bankPeriod_[
static_cast<size_t>(iHi)])));
2346 envBal_.assign(
static_cast<size_t>(n), 0.0);
2347 for (
auto& r : envReg_)
2349 conditionSeries(r,
true);
2351 for (
const double v : r) zero += v * v;
2352 zero /=
static_cast<double>(n);
2355 for (
int lag = lagLo; lag <= lagHi; ++lag)
2359 for (
int i = 0; i + lag < n; ++i)
2360 acc += r[
static_cast<size_t>(i)] * r[
static_cast<size_t>(i + lag)];
2361 peak = std::max(peak, acc /
static_cast<double>(n - lag) / zero);
2363 const double w = std::clamp(peak, 0.0, 1.0);
2364 for (
int i = 0; i < n; ++i) envBal_[static_cast<size_t>(i)] += w * r[
static_cast<size_t>(i)];
2366 conditionSeries(envBal_,
false);
2368 conditionSeries(env_,
true);
2372 void conditionSeries(WorkVector<double>& e,
bool removeFloor)
2374 const int n =
static_cast<int>(e.size());
2377 const int half = std::max(1,
static_cast<int>(std::lround(0.5 * kBaselineSeconds
2379 scratchA_.assign(
static_cast<size_t>(n) + 1, 0.0);
2380 for (
int i = 0; i < n; ++i)
2381 scratchA_[
static_cast<size_t>(i) + 1] = scratchA_[
static_cast<size_t>(i)]
2382 + e[
static_cast<size_t>(i)];
2385 for (
int i = 0; i < n; ++i)
2387 if ((i & 255) == 0) checkOfflineWork();
2388 const int lo = std::max(0, i - half);
2389 const int hi = std::min(n, i + half + 1);
2390 const double mean = (scratchA_[
static_cast<size_t>(hi)]
2391 - scratchA_[
static_cast<size_t>(lo)])
2392 /
static_cast<double>(hi - lo);
2393 const double v = removeFloor ? std::max(0.0, e[
static_cast<size_t>(i)] - mean)
2394 : e[static_cast<size_t>(i)];
2395 e[
static_cast<size_t>(i)] = v;
2399 const double rms = std::sqrt(sumSq /
static_cast<double>(n));
2402 const double g = 1.0 / rms;
2403 for (
int i = 0; i < n; ++i) e[static_cast<size_t>(i)] *= g;
2417 [[nodiscard]]
double coherence(
double periodFrames)
const
2419 return coherence(env_, periodFrames);
2422 [[nodiscard]]
double coherence(
const WorkVector<double>& envelope,
2423 double periodFrames)
const
2425 const int n =
static_cast<int>(envelope.size());
2426 if (n < 2 || !(periodFrames > 1.0))
return 0.0;
2428 const int win = std::max(4,
static_cast<int>(std::lround(kCoherenceWindowBeats
2430 if (win > n)
return coherenceWindow(envelope, 0, n, periodFrames);
2432 const int step = std::max(1, win / 2);
2435 for (
int start = 0; start + win <= n; start += step)
2437 acc += coherenceWindow(envelope, start, start + win, periodFrames);
2440 if (count == 0)
return coherenceWindow(envelope, 0, n, periodFrames);
2441 return acc /
static_cast<double>(count);
2444 [[nodiscard]]
double coherenceWindow(
const WorkVector<double>& envelope,
2445 int from,
int to,
double periodFrames)
const
2447 const double w = 2.0 *
static_cast<double>(pi<double>) / periodFrames;
2448 double re = 0.0, im = 0.0, mass = 0.0;
2449 for (
int i = from; i < to; ++i)
2451 if ((i & 4095) == 0) checkOfflineWork();
2452 const double v = envelope[
static_cast<size_t>(i)];
2453 const double a = w *
static_cast<double>(i);
2454 re += v * std::cos(a);
2455 im -= v * std::sin(a);
2458 if (!(mass > kMassFloor))
return 0.0;
2459 return std::min(1.0, std::sqrt(re * re + im * im) / mass);
2463 [[nodiscard]] std::array<double, 2> offlineCandidateScores(
2464 const WorkVector<double>& envelope,
double period)
const
2466 const double centre = kPriorCentreSeconds * frameRate_;
2467 const double lg = std::log2(period / centre) / kPriorWidthOctaves;
2468 const double base = std::exp(-0.5 * lg * lg) * coherence(envelope, period);
2469 double adjudicated = base, explains = base;
2470 for (
const double multiple : kHarmonicDivisors)
2472 const double share = coherence(envelope, multiple * period);
2473 adjudicated *= (1.0 - std::min(1.0, levelRatio(period, multiple) * share));
2474 explains *= (1.0 - std::min(1.0, share));
2476 return { adjudicated, explains };
2502 void pickCandidates(
int iLo,
int iHi,
double& tau1,
double& tau2)
2506 secondaryShare_ = 0.0;
2507 fundamentalFound_ =
false;
2509 const int n =
static_cast<int>(env_.size());
2510 const int lagLo = std::max(1,
static_cast<int>(std::floor(
2511 bankPeriod_[
static_cast<size_t>(iLo)])));
2512 const int lagHi = std::min(n / 2,
static_cast<int>(std::ceil(
2513 bankPeriod_[
static_cast<size_t>(iHi)])));
2514 if (lagHi <= lagLo)
return;
2519 acf_.assign(
static_cast<size_t>(lagHi + 2), 0.0);
2520 const double centre = kPriorCentreSeconds * frameRate_;
2521 for (
int lag = std::max(1, lagLo - 1); lag <= lagHi + 1; ++lag)
2525 const int m = n - lag;
2526 for (
int i = 0; i < m; ++i)
2527 s += env_[
static_cast<size_t>(i)] * env_[
static_cast<size_t>(i + lag)];
2528 s /=
static_cast<double>(m);
2529 const double lg = std::log2(
static_cast<double>(lag) / centre)
2530 / kPriorWidthOctaves;
2531 acf_[
static_cast<size_t>(lag)] = s * std::exp(-0.5 * lg * lg);
2536 candidates_.clear();
2537 for (
int lag = lagLo; lag <= lagHi; ++lag)
2539 const double v = acf_[
static_cast<size_t>(lag)];
2540 if (v > acf_[
static_cast<size_t>(lag - 1)]
2541 && v >= acf_[
static_cast<size_t>(lag + 1)] && v > 0.0)
2545 const double refined = refineLag(lag);
2546 if (refined >= bankPeriod_[
static_cast<size_t>(iLo)]
2547 && refined <= bankPeriod_[
static_cast<size_t>(iHi)])
2548 candidates_.push_back(lag);
2551 if (candidates_.empty())
return;
2563 for (
const int lag : candidates_) top = std::max(top, acf_[static_cast<size_t>(lag)]);
2565 for (
const int lag : candidates_)
2566 if (acf_[static_cast<size_t>(lag)] >= kCandidatePeakFloor * top)
2567 candidates_[w++] = lag;
2568 candidates_.resize(w);
2580 const WorkVector<int> all(candidates_.begin(), candidates_.end(),
2581 candidates_.get_allocator());
2583 for (
size_t i = 0; i < all.size(); ++i)
2585 bool shoulder =
false;
2586 for (
size_t j = 0; j < all.size() && !shoulder; ++j)
2588 && std::abs(std::log2(
static_cast<double>(all[i])
2589 /
static_cast<double>(all[j])))
2591 && kNeighbourPeakFloor * acf_[
static_cast<size_t>(all[j])]
2592 > acf_[
static_cast<size_t>(all[i])];
2593 if (!shoulder) candidates_[w++] = all[i];
2595 candidates_.resize(w);
2602 candScore_.assign(candidates_.size(), 0.0);
2603 candExplains_.assign(candidates_.size(), 0.0);
2604 for (
size_t k = 0; k < candidates_.size(); ++k)
2606 const double tau = refineLag(candidates_[k]);
2607 const auto scores = offlineCandidateScores(env_, tau);
2608 candScore_[k] = scores[0];
2609 candExplains_[k] = scores[1];
2613 for (
size_t k = 1; k < candidates_.size(); ++k)
2614 if (candScore_[k] > candScore_[k1]) k1 = k;
2625 bool anyFundamental =
false;
2626 for (
size_t k = 0; k < candidates_.size(); ++k)
2627 if (coherence(refineLag(candidates_[k])) >= kMinFundamentalCoherence)
2628 { anyFundamental =
true;
break; }
2629 fundamentalFound_ = anyFundamental;
2630 if (!anyFundamental)
2633 for (
size_t k = 1; k < candidates_.size(); ++k)
2634 if (acf_[
static_cast<size_t>(candidates_[k])]
2635 > acf_[
static_cast<size_t>(candidates_[k1])]) k1 = k;
2636 for (
size_t k = 0; k < candidates_.size(); ++k)
2637 candScore_[k] = acf_[
static_cast<size_t>(candidates_[k])];
2639 tau1 = refineLag(candidates_[k1]);
2651 double bestOther = 0.0;
2652 for (
size_t k = 0; k < candidates_.size(); ++k)
2654 const double sep = std::abs(std::log2(
static_cast<double>(candidates_[k])
2655 /
static_cast<double>(candidates_[k1])));
2656 if (sep < kCandidateSeparationOctaves)
continue;
2657 if (k2 < 0 || candScore_[k] > candScore_[
static_cast<size_t>(k2)])
2658 k2 =
static_cast<int>(k);
2659 bestOther = std::max(bestOther, candExplains_[k]);
2663 tau2 = refineLag(candidates_[
static_cast<size_t>(k2)]);
2664 const double top = candExplains_[k1];
2665 secondaryShare_ = (top > 0.0) ? std::clamp(bestOther / top, 0.0, 1.0) : 0.0;
2670 [[nodiscard]]
double refineLag(
int lag)
const noexcept
2672 if (lag <= 0 || lag + 1 >=
static_cast<int>(acf_.size()))
2673 return static_cast<double>(lag);
2674 const double a = acf_[
static_cast<size_t>(lag - 1)];
2675 const double b = acf_[
static_cast<size_t>(lag)];
2676 const double c = acf_[
static_cast<size_t>(lag + 1)];
2677 const double den = a - 2.0 * b + c;
2678 if (!(std::abs(den) > 0.0))
return static_cast<double>(lag);
2679 const double d = std::clamp(0.5 * (a - c) / den, -0.5, 0.5);
2680 return static_cast<double>(lag) + d;
2684 [[nodiscard]] std::array<double, kLevelRawFeatures> levelFeatures(
2685 double period,
const WorkVector<double>& balanced)
const noexcept
2687 std::array<double, kLevelRawFeatures> features {};
2689 features[k++] = std::log2(periodToBpm(period) / 120.0);
2690 features[k++] = pulseShare(env_, period);
2691 features[k++] = pulseShare(balanced, period);
2692 for (
const auto& r : envReg_) features[k++] = pulseShare(r, period);
2693 features[k++] = pulseShare(env_, 2.0 * period);
2694 for (
const auto& r : envReg_) features[k++] = pulseShare(r, 2.0 * period);
2695 features[k++] = repetition(env_, period);
2696 features[k++] = repetition(balanced, period);
2697 features[k++] = pulseShare(env_, 3.0 * period);
2698 features[k++] = pulseShare(envReg_[0], 3.0 * period);
2699 features[k++] = pulseShare(balanced, 2.0 * period);
2700 features[k++] = pulseShare(balanced, 3.0 * period);
2718 void chooseMetricalLevel(
int iLo,
int iHi,
double& tau1,
double& tau2)
2720 const double pMin = bankPeriod_[
static_cast<size_t>(iLo)];
2721 const double pMax = bankPeriod_[
static_cast<size_t>(iHi)];
2722 const WorkVector<double>& balanced = (envBal_.size() == env_.size()) ? envBal_ : env_;
2723 std::array<std::array<double, kLevelRawFeatures>, kLevelCandidates> raw {};
2724 for (
int c = 0; c < kLevelCandidates; ++c)
2725 raw[
static_cast<size_t>(c)] = levelFeatures(
2726 tau1 * kLevelMultiples[
static_cast<size_t>(c)], balanced);
2728 const auto& proposed = raw[
static_cast<size_t>(kLevelMiddle)];
2729 if (!(proposed[kLevelShareAtPeriod] > 0.0))
return;
2730 const double contrastFloor = kLevelContrastFloor * proposed[kLevelShareAtPeriod];
2731 int best = kLevelMiddle;
2732 if (proposed[kLevelShareAtDouble] >= contrastFloor)
2735 double bestScore = 0.0;
2736 for (
int c = 0; c < kLevelCandidates; ++c)
2738 const double period = tau1 * kLevelMultiples[
static_cast<size_t>(c)];
2739 if (c != kLevelMiddle && (period < pMin || period > pMax))
continue;
2740 const auto& f = raw[
static_cast<size_t>(c)];
2741 double score = kLevelBias[
static_cast<size_t>(c)];
2742 for (
size_t j = 0; j < kLevelRawFeatures; ++j)
2743 score += kLevelWeights[j] * f[j]
2744 + kLevelWeights[kLevelRawFeatures + j] * (f[j] - proposed[j]);
2745 score += kLevelWeights[2 * kLevelRawFeatures] * f[0] * f[0];
2746 if (best < 0 || score > bestScore) { best = c; bestScore = score; }
2750 const double binaryPeriod = tau1 * kLevelMultiples[
static_cast<size_t>(best)];
2751 double chosenPeriod = binaryPeriod;
2752 bool ternaryChosen =
false;
2753 std::array<double, kTernaryMultiples.size()> supportedPeriods {};
2754 size_t supportedCount = 0;
2755 if (std::max(proposed[kLevelShareAtDouble], proposed[kLevelShareAtTriple]) >= contrastFloor)
2757 const auto& reference = raw[
static_cast<size_t>(best)];
2758 double bestGain = 0.0;
2759 for (
size_t c = 0; c < kTernaryMultiples.size(); ++c)
2761 const double period = tau1 * kTernaryMultiples[c];
2762 if (period < pMin || period > pMax)
continue;
2763 const auto f = levelFeatures(period, balanced);
2764 if (f[kLevelBalancedShareAtPeriod] < kMinFundamentalCoherence)
continue;
2765 supportedPeriods[supportedCount++] = period;
2766 double gain = kTernaryBias[c];
2767 for (
size_t j = 0; j < kLevelRawFeatures; ++j)
2768 gain += kTernaryWeights[j] * f[j]
2769 + kTernaryWeights[kLevelRawFeatures + j] * (f[j] - reference[j]);
2770 gain += kTernaryWeights[2 * kLevelRawFeatures] * f[0] * f[0];
2771 if (gain > bestGain)
2774 chosenPeriod = period;
2775 ternaryChosen =
true;
2781 tau2 = binaryPeriod;
2782 tau1 = chosenPeriod;
2784 else if (best != kLevelMiddle)
2787 tau1 = binaryPeriod;
2789 if (ternaryChosen || best != kLevelMiddle)
2790 refreshMetricalAmbiguity(balanced, tau1, tau2,
2791 { supportedPeriods.data(), supportedCount });
2795 void refreshMetricalAmbiguity(
const WorkVector<double>& envelope,
2796 double chosen,
double displaced,
2797 std::span<const double> addedPeriods)
2799 const double top = offlineCandidateScores(envelope, chosen)[1];
2800 double bestOther = 0.0;
2801 for (
size_t k = 0; k < candidates_.size(); ++k)
2802 if (std::abs(std::log2(refineLag(candidates_[k]) / chosen))
2803 >= kCandidateSeparationOctaves)
2804 bestOther = std::max(bestOther, candExplains_[k]);
2805 const auto consider = [&](
double period) {
2806 if (period > 0.0 && std::abs(std::log2(period / chosen))
2807 >= kCandidateSeparationOctaves)
2808 bestOther = std::max(bestOther, offlineCandidateScores(envelope, period)[1]);
2810 consider(displaced);
2811 for (
const double period : addedPeriods) consider(period);
2812 secondaryShare_ = top > 0.0 ? std::clamp(bestOther / top, 0.0, 1.0)
2813 : (bestOther > 0.0 ? 1.0 : 0.0);
2826 [[nodiscard]]
static double pulseShare(
const WorkVector<double>& e,
2827 double periodFrames)
noexcept
2829 const int n =
static_cast<int>(e.size());
2830 const int win =
static_cast<int>(kLevelWindowBeats * periodFrames);
2831 if (win < 4)
return 0.0;
2832 const double w = 2.0 *
static_cast<double>(pi<double>) / periodFrames;
2833 const double dc = std::cos(w), ds = std::sin(w);
2834 double acc = 0.0, mass = 0.0;
2835 for (
int start = 0; start + win <= n; start += win / 2)
2840 double c = std::cos(w *
static_cast<double>(start));
2841 double s = std::sin(w *
static_cast<double>(start));
2842 double re = 0.0, im = 0.0, m = 0.0;
2843 for (
int i = start; i < start + win; ++i)
2845 const double v = std::max(0.0, e[
static_cast<size_t>(i)]);
2849 const double cn = c * dc - s * ds;
2850 s = s * dc + c * ds;
2853 if (m > 0.0) { acc += std::sqrt(re * re + im * im); mass += m; }
2855 return (mass > 0.0) ? acc / mass : 0.0;
2860 [[nodiscard]]
static double repetition(
const WorkVector<double>& e,
2861 double periodFrames)
noexcept
2863 const int n =
static_cast<int>(e.size());
2864 const int lag =
static_cast<int>(std::lround(periodFrames));
2865 if (lag <= 0 || lag >= n)
return 0.0;
2866 double s0 = 0.0, s = 0.0;
2867 for (
int i = 0; i < n; ++i) s0 += e[static_cast<size_t>(i)] * e[
static_cast<size_t>(i)];
2868 for (
int i = 0; i + lag < n; ++i)
2869 s += e[
static_cast<size_t>(i)] * e[
static_cast<size_t>(i + lag)];
2870 return (s0 > 0.0) ? s / s0 *
static_cast<double>(n) /
static_cast<double>(n - lag)
2916 bool layGrid(
double tau, WorkVector<int64_t>& gridOut)
2919 localPeriod_.clear();
2920 localTightness_.clear();
2924 WorkVector<int> grid(detail::AccountedAllocator<int>{&allocationAccount_});
2926 if (coherence(tau) >= kMinFundamentalCoherence)
2928 WorkVector<int> loose(detail::AccountedAllocator<int>{&allocationAccount_});
2929 const double asked = tightness_.load(std::memory_order_relaxed);
2930 alphaScale_ = std::min(1.0, kFollowTightness / asked);
2931 const bool followed = runDp(tau, loose,
true) && loose.size() >= 4;
2939 if (
const double second = secondTempo(tau); second > 0.0)
2941 const double between = std::sqrt(tau * second);
2942 WorkVector<int> both(detail::AccountedAllocator<int>{&allocationAccount_});
2943 alphaScale_ = std::min(1.0, kFollowTightness / asked);
2944 const bool laid = runDp(between, both,
true) && both.size() >= 4;
2957 taken = shareInRuns(both, tau) >= kSecondTempoShare
2958 && shareInRuns(both, second) >= kSecondTempoShare
2959 && carriedBy(both) *
static_cast<double>(loose.size())
2960 > kSecondTempoGain * carriedBy(loose)
2961 *
static_cast<double>(both.size());
2968 buildLocalScore(tau);
2971 double overall = overallPeriod(loose, given);
2972 if (std::abs(std::log2(overall / given)) > kRecentreOctaves)
2977 WorkVector<int> again(detail::AccountedAllocator<int>{&allocationAccount_});
2978 alphaScale_ = std::min(1.0, kFollowTightness / asked);
2979 const bool laid = runDp(overall, again,
true) && again.size() >= 4;
2984 overall = overallPeriod(loose, overall);
2987 buildLocalScore(given);
2989 intervalCap_ = kIntervalCapBeats * carriedBy(loose) /
static_cast<double>(loose.size());
2990 holdToGrid(loose, overall);
2991 have = runDp(overall, grid) && grid.size() >= 2;
2992 localPeriod_.clear();
2993 localTightness_.clear();
2999 if (!have || carriedBy(grid) < kHeldShare * carriedBy(loose))
3002 have = grid.size() >= 2;
3006 if (!have) have = runDp(tau, grid) && grid.size() >= 2;
3007 if (!have)
return false;
3009 gridOut.reserve(grid.size());
3010 for (
const int f : grid)
3011 gridOut.push_back(beatSample(f));
3016 [[nodiscard]]
double carriedBy(
const WorkVector<int>& beatFrames)
const noexcept
3019 for (
const int f : beatFrames) sum += local_[static_cast<size_t>(f)];
3028 [[nodiscard]]
static double centralMean(WorkVector<double>& intervals)
3030 std::sort(intervals.begin(), intervals.end());
3031 const size_t q = intervals.size() / 4;
3033 for (
size_t j = q; j < intervals.size() - q; ++j) sum += intervals[j];
3034 return sum /
static_cast<double>(intervals.size() - 2 * q);
3039 [[nodiscard]]
double overallPeriod(
const WorkVector<int>& beats,
double around)
const
3041 WorkVector<double> intervals(detail::AccountedAllocator<double>{&allocationAccount_});
3042 intervals.reserve(beats.size());
3043 for (
size_t k = 1; k < beats.size(); ++k)
3044 intervals.push_back(
static_cast<double>(beats[k] - beats[k - 1]));
3045 const double reach = std::exp2(kHoldReachOctaves);
3046 return std::clamp(centralMean(intervals), around / reach, around * reach);
3051 [[nodiscard]]
static double shareInRuns(
const WorkVector<int>& beats,
double period)
noexcept
3053 size_t inRuns = 0, run = 0;
3054 for (
size_t k = 1; k < beats.size(); ++k)
3056 if (std::abs(std::log(
static_cast<double>(beats[k] - beats[k - 1]) / period))
3062 if (run >= kSecondTempoRun) inRuns += run;
3065 if (run >= kSecondTempoRun) inRuns += run;
3066 return static_cast<double>(inRuns) /
static_cast<double>(beats.size() - 1);
3078 [[nodiscard]]
double secondTempo(
double tau)
const noexcept
3080 const auto own =
static_cast<size_t>(std::llround(tau));
3081 if (own >= acf_.size() || !(acf_[own] > 0.0))
return 0.0;
3082 double most = 0.0, second = 0.0;
3083 for (
const int lag : candidates_)
3085 const double octaves = std::abs(std::log2(
static_cast<double>(lag) / tau));
3086 if (octaves < kSecondTempoNear || octaves > kSecondTempoFar)
continue;
3087 const double v = acf_[
static_cast<size_t>(lag)];
3088 if (v >= kSecondTempoPeakFloor * acf_[own] && v > most)
3091 second =
static_cast<double>(lag);
3130 void holdToGrid(
const WorkVector<int>& beats,
double overall)
3132 const int n =
static_cast<int>(env_.size());
3133 const size_t count = beats.size() - 1;
3134 const double reach = std::exp2(kHoldReachOctaves);
3135 const detail::AccountedAllocator<double> doubles(&allocationAccount_);
3137 WorkVector<double> window(doubles);
3138 window.reserve(
static_cast<size_t>(2 * kPeriodReachBeats + 1));
3139 const auto interval = [&beats](
size_t k) {
3140 return static_cast<double>(beats[k + 1] - beats[k]);
3144 const auto read = [&window, &
interval](
size_t first,
size_t last,
3145 double& period,
double& spread) {
3147 for (
size_t j = first; j <= last; ++j) window.push_back(
interval(j));
3148 period = centralMean(window);
3150 for (
const double x : window) spread += std::abs(std::log(x / period));
3151 spread /=
static_cast<double>(window.size());
3156 WorkVector<double> away(count, 0.0, doubles), centre(count, 0.0, doubles),
3157 width(count, kHoldWidth, doubles);
3158 const size_t each =
static_cast<size_t>(kPeriodReachBeats);
3159 for (
size_t k = 0; k < count; ++k)
3161 const size_t first = (k > each ? k - each : 0);
3162 const size_t last = std::min(count - 1, k + each);
3163 double period = 0.0, spread = 0.0;
3164 read(first, last, period, spread);
3167 double steadiest = kStepSpreadShare * spread, readSpread = spread;
3168 if (k >= each && last > k)
3170 double sidePeriod = 0.0, sideSpread = 0.0;
3171 read(k - each, k, sidePeriod, sideSpread);
3172 if (sideSpread < steadiest)
3174 steadiest = readSpread = sideSpread;
3175 period = sidePeriod;
3178 if (k + each < count && first < k)
3180 double sidePeriod = 0.0, sideSpread = 0.0;
3181 read(k, k + each, sidePeriod, sideSpread);
3182 if (sideSpread < steadiest)
3184 steadiest = readSpread = sideSpread;
3185 period = sidePeriod;
3188 width[k] = std::clamp(kHoldSpreads * readSpread, kSteadyHoldWidth, kHoldWidth);
3189 away[k] = std::log(std::clamp(period, overall / reach, overall * reach) / overall);
3190 centre[k] = 0.5 *
static_cast<double>(beats[k] + beats[k + 1]);
3193 const double asked = tightness_.load(std::memory_order_relaxed);
3194 const double follow = std::min(asked, kFollowTightness);
3195 localPeriod_.assign(
static_cast<size_t>(n), overall);
3196 localTightness_.assign(
static_cast<size_t>(n), asked);
3198 for (
int i = 0; i < n; ++i)
3200 if ((i & 255) == 0) checkOfflineWork();
3201 const double at =
static_cast<double>(i) - 0.5 * overall;
3202 while (k + 2 < count && centre[k + 1] <= at) ++k;
3203 double a = away[k], w = width[k];
3204 if (at >= centre[count - 1]) { a = away[count - 1]; w = width[count - 1]; }
3205 else if (at > centre[k] && k + 1 < count)
3207 const double span = centre[k + 1] - centre[k];
3208 const double share = span > 0.0 ? std::clamp((at - centre[k]) / span, 0.0, 1.0) : 0.0;
3209 a += share * (away[k + 1] - a);
3210 w += share * (width[k + 1] - w);
3212 const double r = a / w;
3213 const double held = 1.0 / (1.0 + r * r * r * r);
3214 localPeriod_[
static_cast<size_t>(i)] = overall * std::exp((1.0 - held) * a);
3215 localTightness_[
static_cast<size_t>(i)] = follow + held * (asked - follow);
3222 [[nodiscard]]
static double ambiguityDiscount(
double share)
noexcept
3224 if (!(share > kAmbiguityFloor))
return 1.0;
3225 return std::clamp(1.0 - (share - kAmbiguityFloor) / (1.0 - kAmbiguityFloor),
3251 bool runDp(
double periodFrames, WorkVector<int>& beatFrames,
bool chainOnly =
false)
3254 const int n =
static_cast<int>(env_.size());
3255 const bool varying = (localPeriod_.size() == env_.size());
3256 const bool weighted = varying && (localTightness_.size() == env_.size());
3257 const int lo = std::max(1,
static_cast<int>(std::lround(kSearchLowFactor
3259 const int hi = std::max(lo + 1,
static_cast<int>(std::lround(kSearchHighFactor
3261 if (n <= hi + 2)
return false;
3263 buildLocalScore(periodFrames);
3265 const double alpha = tightness_.load(std::memory_order_relaxed) * alphaScale_;
3266 const double cap = intervalCap_;
3267 cumScore_.assign(
static_cast<size_t>(n), 0.0);
3268 backlink_.assign(
static_cast<size_t>(n), -1);
3270 for (
int i = 0; i < n; ++i)
3272 if ((i & 255) == 0) checkOfflineWork();
3273 const double target = varying ? localPeriod_[
static_cast<size_t>(i)]
3275 const double weight = weighted ? localTightness_[
static_cast<size_t>(i)] : alpha;
3276 const int dLo = varying
3277 ? std::max(1,
static_cast<int>(std::lround(kSearchLowFactor * target)))
3279 const int dHiBound = varying
3280 ? std::max(dLo + 1,
static_cast<int>(std::lround(kSearchHighFactor
3286 const int dHi = std::min(dHiBound, i);
3287 for (
int d = dLo; d <= dHi; ++d)
3289 const int j = i - d;
3290 const double lr = std::log(
static_cast<double>(d) / target);
3291 double cost = weight * lr * lr;
3292 if (cap > 0.0 && cost > cap) cost = cap;
3293 const double s = cumScore_[
static_cast<size_t>(j)] - cost;
3294 if (bestJ < 0 || s > best) { best = s; bestJ = j; }
3296 if (bestJ >= 0 && best < 0.0) { best = 0.0; bestJ = -1; }
3297 cumScore_[
static_cast<size_t>(i)] = local_[
static_cast<size_t>(i)]
3298 + ((bestJ >= 0) ? best : 0.0);
3299 backlink_[
static_cast<size_t>(i)] = bestJ;
3303 for (
int i = 1; i < n; ++i)
3304 if (cumScore_[
static_cast<size_t>(i)] > cumScore_[
static_cast<size_t>(end)])
3307 for (
int i = end; i >= 0; i = backlink_[
static_cast<size_t>(i)])
3309 beatFrames.push_back(i);
3310 if (backlink_[
static_cast<size_t>(i)] < 0)
break;
3312 std::reverse(beatFrames.begin(), beatFrames.end());
3314 trimBeats(beatFrames);
3315 if (beatFrames.size() < 2)
return false;
3316 if (chainOnly)
return true;
3318 extendGrid(beatFrames);
3319 return beatFrames.size() >= 2;
3324 [[nodiscard]]
int edgeFrames() const noexcept
3326 return static_cast<int>(std::ceil(kEdgeSeconds * frameRate_));
3342 void extendGrid(WorkVector<int>& beatFrames)
const
3344 if (beatFrames.size() < 3)
return;
3345 const int n =
static_cast<int>(env_.size());
3347 WorkVector<int> ibi(detail::AccountedAllocator<int>{&allocationAccount_});
3348 ibi.reserve(beatFrames.size());
3349 for (
size_t k = 1; k < beatFrames.size(); ++k)
3350 ibi.push_back(beatFrames[k] - beatFrames[k - 1]);
3351 std::sort(ibi.begin(), ibi.end());
3352 const int step = ibi[ibi.size() / 2];
3353 if (step < 2)
return;
3356 for (
const int f : beatFrames) mean += local_[static_cast<size_t>(f)];
3357 mean /=
static_cast<double>(beatFrames.size());
3358 const double floorValue = kSupportFraction * mean;
3359 const double edgeFloor = kEdgeSupportFraction * mean;
3360 const int edge = edgeFrames();
3361 const int win = std::max(1,
static_cast<int>(std::lround(step * kExtendFraction)));
3363 const auto supported = [&](
int guess,
double least) {
3365 double bestValue = least;
3366 for (
int i = std::max(0, guess - win); i <= std::min(n - 1, guess + win); ++i)
3367 if (local_[
static_cast<size_t>(i)] > bestValue)
3368 { bestValue = local_[
static_cast<size_t>(i)]; best = i; }
3372 WorkVector<int> front(detail::AccountedAllocator<int>{&allocationAccount_});
3373 for (
int guess = beatFrames.front() - step; guess >= 0; guess -= step)
3375 const int best = supported(guess, guess - win <= edge ? edgeFloor : floorValue);
3376 if (best < 0)
break;
3377 front.push_back(best);
3380 std::reverse(front.begin(), front.end());
3382 WorkVector<int> back(detail::AccountedAllocator<int>{&allocationAccount_});
3383 for (
int guess = beatFrames.back() + step; guess <= n - 1; guess += step)
3385 const int best = supported(guess, floorValue);
3386 if (best < 0)
break;
3387 back.push_back(best);
3391 if (front.empty() && back.empty())
return;
3392 WorkVector<int> merged(detail::AccountedAllocator<int>{&allocationAccount_});
3393 merged.reserve(front.size() + beatFrames.size() + back.size());
3394 merged.insert(merged.end(), front.begin(), front.end());
3395 merged.insert(merged.end(), beatFrames.begin(), beatFrames.end());
3396 merged.insert(merged.end(), back.begin(), back.end());
3397 beatFrames.swap(merged);
3403 void buildLocalScore(
double periodFrames)
3405 const int n =
static_cast<int>(env_.size());
3406 local_.assign(
static_cast<size_t>(n), 0.0);
3408 const double sigma = std::max(0.5, kLocalScoreSigmaPeriods * periodFrames);
3409 const int half = std::max(1,
static_cast<int>(std::lround(3.0 * sigma)));
3410 kernel_.assign(
static_cast<size_t>(2 * half + 1), 0.0);
3412 for (
int k = -half; k <= half; ++k)
3414 const double x =
static_cast<double>(k) / sigma;
3415 const double v = std::exp(-0.5 * x * x);
3416 kernel_[
static_cast<size_t>(k + half)] = v;
3420 for (
double& v : kernel_) v /= ksum;
3422 for (
int i = 0; i < n; ++i)
3424 if ((i & 255) == 0) checkOfflineWork();
3426 const int kLo = std::max(-half, -i);
3427 const int kHi = std::min(half, n - 1 - i);
3428 for (
int k = kLo; k <= kHi; ++k)
3429 acc += env_[
static_cast<size_t>(i + k)]
3430 * kernel_[
static_cast<size_t>(k + half)];
3431 local_[
static_cast<size_t>(i)] = acc;
3440 void trimBeats(WorkVector<int>& beatFrames)
const
3442 if (beatFrames.size() < 3)
return;
3445 for (
const int f : beatFrames) mean += local_[static_cast<size_t>(f)];
3446 mean /=
static_cast<double>(beatFrames.size());
3447 const double floorValue = kSupportFraction * mean;
3448 const double edgeFloor = kEdgeSupportFraction * mean;
3449 const int edge = edgeFrames();
3452 while (first + 2 < beatFrames.size()
3453 && local_[
static_cast<size_t>(beatFrames[first])]
3454 < (beatFrames[first] <= edge ? edgeFloor : floorValue))
3457 size_t last = beatFrames.size() - 1;
3458 while (last > first + 1
3459 && local_[
static_cast<size_t>(beatFrames[last])] < floorValue)
3462 if (first > 0 || last + 1 < beatFrames.size())
3463 beatFrames = WorkVector<int>(beatFrames.begin()
3464 +
static_cast<std::ptrdiff_t
>(first),
3466 +
static_cast<std::ptrdiff_t
>(last) + 1,
3467 beatFrames.get_allocator());
3495 [[nodiscard]] int64_t beatSample(
int f)
const noexcept
3497 const int n =
static_cast<int>(env_.size());
3498 const int64_t base = envRef_[
static_cast<size_t>(f)];
3499 if (f <= 0 || f >= n - 1)
return std::max<int64_t>(0, base);
3500 const double a = env_[
static_cast<size_t>(f - 1)];
3501 const double b = env_[
static_cast<size_t>(f)];
3502 const double c = env_[
static_cast<size_t>(f + 1)];
3503 const double den = a - 2.0 * b + c;
3504 if (!(den < 0.0))
return std::max<int64_t>(0, base);
3505 const double d = std::clamp(0.5 * (a - c) / den, -0.5, 0.5);
3506 return std::max<int64_t>(0, base +
static_cast<int64_t
>(std::llround(d *
static_cast<double>(hop_))));
3530 [[nodiscard]]
static double fitBeatSlope(
const WorkVector<int64_t>& beats)
3532 const size_t n = beats.size();
3533 if (n < 2)
return 0.0;
3534 WorkVector<double> ibi(detail::AccountedAllocator<double>{beats.get_allocator().account()});
3536 for (
size_t k = 1; k < n; ++k) ibi.push_back(
static_cast<double>(beats[k] - beats[k - 1]));
3537 WorkVector<double> sorted = ibi;
3538 std::nth_element(sorted.begin(), sorted.begin() +
static_cast<std::ptrdiff_t
>(sorted.size() / 2), sorted.end());
3539 const double med = sorted[sorted.size() / 2];
3540 if (!(med > 0.0))
return 0.0;
3545 for (
size_t j = 0; j < ibi.size(); ++j)
3546 sorted[j] = std::max(1.0, std::round(ibi[j] / med));
3547 const auto stable = [&](
size_t j) {
3548 const double r = ibi[j] / med;
3549 return r >= 0.75 && std::abs(r - std::round(r)) < 0.125;
3551 for (
size_t j = 3; j + 3 < ibi.size(); ++j)
3553 if (stable(j) || !stable(j - 1) || !stable(j - 2) || !stable(j - 3))
3555 for (
size_t width = 1; width <= 3; ++width)
3557 const size_t end = j + width;
3558 if (end + 3 > ibi.size()
3559 || !stable(end) || !stable(end + 1) || !stable(end + 2))
3562 for (
size_t q = j; q < end; ++q) total += ibi[q] / med;
3563 const double half = std::floor(total) + 0.5;
3564 if (std::abs(total - half) >= 0.125)
continue;
3565 for (
size_t q = j; q < end; ++q)
3566 sorted[q] = (ibi[q] / med) * half / total;
3572 double sx = 0.0, sy = 0.0, sxx = 0.0, sxy = 0.0, index = 0.0;
3573 for (
size_t k = 0; k < n; ++k)
3575 if (k > 0) index += sorted[k - 1];
3576 const double y =
static_cast<double>(beats[k]);
3577 sx += index; sy += y; sxx += index * index; sxy += index * y;
3579 const double dn =
static_cast<double>(n);
3580 const double den = dn * sxx - sx * sx;
3581 if (!(std::abs(den) > 0.0))
return 0.0;
3582 return (dn * sxy - sx * sy) / den;
3587 void resetState() noexcept
3590 std::fill(zRe_.begin(), zRe_.end(), 0.0);
3591 std::fill(zIm_.begin(), zIm_.end(), 0.0);
3592 std::fill(zMass_.begin(), zMass_.end(), 0.0);
3593 std::fill(bankCoherence_.begin(), bankCoherence_.end(), 0.0);
3599 linearBaseline_ = 0.0;
3601 scorePeakLinear_ = 0.0;
3602 std::fill(beatScore_.begin(), beatScore_.end(), 0.0);
3603 beatScoreWrite_ = 0;
3604 beatScoreFrames_ = 0;
3606 haveBeatPeriod_ =
false;
3607 resonatorLead_ = 0.0;
3608 framesToPrediction_ = -1;
3610 beatPending_ =
false;
3611 pendingBeatRef_ = 0;
3613 levelChallengeFrames_ = 0;
3614 std::fill(combRing_.begin(), combRing_.end(), 0.0);
3615 std::fill(combDelta_.begin(), combDelta_.end(), 0.0);
3617 combCountdown_ = kCombUpdateFrames;
3622 std::fill(regRing_.begin(), regRing_.end(), 0.0);
3623 regBaseline_.fill(0.0);
3625 tempoAndConfidence_.store(packTempo(0.0f, 0.0f), std::memory_order_relaxed);
3626 beatLatched_.store(
false, std::memory_order_relaxed);
3627 lastBeatSample_.store(-1, std::memory_order_relaxed);
3628 beatTempo_.store(0.0f, std::memory_order_relaxed);
3632 static constexpr double kBeatScoreFeedback = 0.9;
3635 static constexpr double kBeatIntervalSharpness = 5.0;
3637 static constexpr double kPredictionSpread = 4.0;
3640 static constexpr double kAmbiguousScore = 0.05;
3643 static constexpr double kRivalSeparation = 0.15;
3646 static constexpr double kLevelHoldBeats = 4.0;
3652 static constexpr double kCombSeconds = 6.0;
3653 static constexpr int kCombUpdateFrames = 32;
3654 static constexpr int kCombMultiples = 4;
3655 static constexpr double kCombPriorSeconds = 0.40;
3656 static constexpr double kCombHalfWeight = 0.5;
3658 static constexpr double kScorePeakSeconds = 10.0;
3659 static constexpr double kCombTransitionOctaves = 0.19;
3660 static constexpr double kCombThresholdSeconds = 0.081;
3661 static constexpr double kCombWidthSeconds = 0.0116;
3662 static constexpr double kCombFoldFloor = 0.5;
3663 static constexpr double kCombFoldRatio = 0.8;
3667 static constexpr double kIsochronyFloor = 0.2;
3668 static constexpr double kIsochronyRatio = 0.8;
3670 static constexpr int kBeatTableSize = 2048;
3672 static constexpr double kBeatTableSpan = 0.6931471805599453 + 0.05;
3676 static constexpr double kMassFloor = 1e-12;
3680 detail::AllocationAccount allocationAccount_;
3681 void* offlineCheckpointContext_ =
nullptr;
3682 void (*offlineCheckpoint_)(
void*) =
nullptr;
3683 void checkOfflineWork()
const
3685 if (offlineCheckpoint_) offlineCheckpoint_(offlineCheckpointContext_);
3687 OnsetDetector<T> onset_;
3689 double sampleRate_ = 44100.0;
3690 double frameRate_ = 200.0;
3695 WorkVector<double> bankPeriod_;
3696 WorkVector<double> bankCosCoef_, bankSinCoef_, bankDecay_, bankPrior_;
3697 int harmonicOffset_[kNumHarmonics] = { 0, 0, 0 };
3698 WorkVector<double> zRe_, zIm_, zMass_, bankCoherence_;
3699 WorkVector<double> bankLevelRatio_;
3702 int64_t samplesPushed_ = 0;
3703 int64_t frameIndex_ = 0;
3704 int64_t lastFrameRef_ = 0;
3705 double baseline_ = 0.0;
3706 double linearBaseline_ = 0.0;
3707 double scorePeak_ = 0.0;
3708 double scorePeakLinear_ = 0.0;
3709 double peakDecay_ = 0.9995;
3710 double baselineCoef_ = 0.005;
3712 int beatScoreLen_ = 64;
3713 WorkVector<double> beatScore_, beatScratch_, beatAhead_, beatLogLag_, beatWeightTable_;
3714 int64_t beatScoreWrite_ = 0;
3715 int64_t beatScoreFrames_ = 0;
3716 double beatPeriod_ = 0.0;
3717 bool haveBeatPeriod_ =
false;
3718 double resonatorLead_ = 0.0;
3719 int framesToPrediction_ = -1;
3720 int beatCountdown_ = 0;
3721 bool beatPending_ =
false;
3722 int64_t pendingBeatRef_ = 0;
3723 int heldLevel_ = -1;
3724 int levelChallengeFrames_ = 0;
3726 std::unique_ptr<FFTReal<double>> combFft_;
3727 WorkVector<double> combRing_, combSum_, combTime_, combSpec_, combAcf_;
3728 WorkVector<double> combDelta_, combNext_, combStep_, combPrior_, combKernel_;
3729 int combLength_ = 0;
3730 int combFftSize_ = 0;
3732 int64_t combWrite_ = 0;
3733 int combCountdown_ = kCombUpdateFrames;
3735 int combFollow_ = -1;
3736 bool combFresh_ =
false;
3737 bool combAlike_ =
false;
3738 WorkVector<double> regRing_;
3739 std::array<double, OnsetDetector<T>::kNumRegisters> regBaseline_ {};
3742 int64_t offlinePushed_ = 0;
3743 bool offlineOpen_ =
false;
3744 WorkVector<double> env_;
3745 WorkVector<int64_t> envRef_;
3747 static_assert(kRegisters == 4,
"the level model (kLevelWeights) reads four register envelopes");
3748 std::array<WorkVector<double>, kRegisters> envReg_;
3749 WorkVector<double> envBal_;
3750 double alphaScale_ = 1.0;
3751 double intervalCap_ = 0.0;
3752 WorkVector<double> local_, cumScore_, acf_, scratchA_, kernel_;
3753 WorkVector<double> localPeriod_;
3754 WorkVector<double> localTightness_;
3755 WorkVector<int> backlink_;
3756 WorkVector<int> candidates_;
3757 WorkVector<double> candScore_, candExplains_;
3758 double secondaryShare_ = 0.0;
3759 bool fundamentalFound_ =
false;
3762 std::atomic<bool> prepared_ {
false };
3763 std::atomic<std::uint64_t> tempoAndConfidence_ { 0 };
3764 std::atomic<std::uint32_t> activeRange_ { 0 };
3766 std::atomic<std::uint64_t> requestedRange_ {
3767 packTempo(
static_cast<float>(kDefaultMinBpm),
static_cast<float>(kDefaultMaxBpm)) };
3768 std::atomic<double> tightness_ { kDefaultTightness };
3769 std::atomic<bool> beatLatched_ {
false };
3770 std::atomic<std::int64_t> lastBeatSample_ { -1 };
3771 std::atomic<float> beatTempo_ { 0.0f };
3772 std::atomic<std::int64_t> latencySamples_ { 770 };
Non-owning view over audio channel data.
int getNumSamples() const noexcept
Returns the number of samples per channel.
int getNumChannels() const noexcept
Returns the number of channels in this view.
T * getChannel(int ch) const noexcept
Returns a pointer to the sample data for the given channel.
Tempo and beat tracking with an offline grid and a causal readout.
bool beatNow() const noexcept
True if a beat was reported during the most recent call.
void setTempoRange(T minBpm, T maxBpm) noexcept
Restricts the searched tempo range, in BPM. Lock free, no alloc.
void prepare(const AudioSpec &spec)
Allocates all causal state and prepares the shared front end.
void pushOffline(std::span< const T > samples)
Feeds the next piece of an offline session (channel-0 samples). No-op outside one.
T getTightness() const noexcept
Tightness currently in force.
const OnsetDetector< T > & getOnsetDetector() const noexcept
Read-only access to the front end, for callers that also want onsets and would otherwise run a second...
T getConfidence() const noexcept
Coherence of the envelope with the running tempo, in [0,1].
Result analyze(AudioBufferView< const T > whole)
Tracks tempo and beats over a whole mono buffer (channel 0).
void setTightness(T alpha) noexcept
Sets the dynamic-programming tightness (Ellis alpha).
int64_t getLastBeatSample() const noexcept
Sample index the most recent causal beat is attributed to; -1 before the first one.
void applyTempoRange() noexcept
Selects the part of the bank the requested range covers.
T getBeatTempoBpm() const noexcept
Tempo the causal beat clock runs at, in BPM; 0 before it has one. Lock-free.
void reset() noexcept
Clears all streaming state and abandons an open offline session. Not concurrent with pushSamples().
void beginOffline(int64_t expectedSamples=0)
Opens an incremental offline analysis.
Result finishOffline()
Closes the session and tracks tempo and beats over everything pushed, as analyze() does....
static constexpr T defaultTightness() noexcept
The tightness in force until setTightness() is called.
void processBlock(AudioBufferView< const T > in) noexcept
Feeds a mono block; reads channel 0 only. Const, never mutated. Lock free and allocation free....
void pushSamples(std::span< const T > samples) noexcept
Feeds a mono stream of samples. Lock free, allocation free.
void getTempoAndConfidence(T &bpmOut, T &confidenceOut) const noexcept
Running tempo and its confidence, from ONE load.
T getRunningTempoBpm() const noexcept
Running tempo estimate in BPM, 0 before the first frame.
int getLatencySamples() const noexcept
Delay between a beat and the call in which it is announced.
double getFrameRate() const noexcept
Analysis frames per second of the shared envelope.
Causal SuperFlux onset detector with lock-free readout.
static constexpr int kNumRegisters
One frame of the onset-strength envelope (the ODF before the peak picker).
constexpr int interval(const std::array< int, 7 > °, int degIdx, int skip) noexcept
Calculate semitone interval skipping 'skip' degrees in the scale.
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
double sampleRate
Sample rate in Hz.
What analyze() returns: one tempo, one grid, one number saying how much of the signal that grid expla...
std::vector< int64_t > beatSamples
Beat positions, ascending, in samples, never negative.
T secondaryTempoBpm
The competing hypothesis that lost.
T tempoBpm
Delivered tempo, fitted to the grid.
T confidence
Coherence of the envelope with the grid, [0,1].