DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
BeatTracker.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
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"
404
405#include <algorithm>
406#include <array>
407#include <atomic>
408#include <cmath>
409#include <cstddef>
410#include <cstdint>
411#include <cstring>
412#include <memory>
413#include <span>
414#include <vector>
415
416namespace dspark {
417
418namespace detail { template <FloatType T> struct OfflineBeatEngine; }
419
431template <FloatType T>
432class BeatTracker final
433{
434 template <typename U>
435 using WorkVector = std::vector<U, detail::AccountedAllocator<U>>;
436 friend struct detail::OfflineBeatEngine<T>;
437
438public:
440 {
441 const detail::AccountedAllocator<double> doubles(&allocationAccount_);
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_,
450 &regRing_})
451 *values = WorkVector<double>(doubles);
452 for (auto& values : envReg_) values = WorkVector<double>(doubles);
453 envRef_ = WorkVector<int64_t>(detail::AccountedAllocator<int64_t>(&allocationAccount_));
454 backlink_ = WorkVector<int>(detail::AccountedAllocator<int>(&allocationAccount_));
455 candidates_ = WorkVector<int>(detail::AccountedAllocator<int>(&allocationAccount_));
456 onset_.setLinearFlux(true); // the beat score reads OdfFrame::linear
457 }
458
462 struct Result
463 {
464 T tempoBpm = T(0);
465 T confidence = T(0);
467 std::vector<int64_t> beatSamples;
468 };
469
470 // -- Lifecycle -----------------------------------------------------------
471
488 void prepare(const AudioSpec& spec)
489 {
490 if (!(spec.sampleRate > 0.0) || !std::isfinite(spec.sampleRate))
491 return;
492
493 prepared_.store(false, std::memory_order_relaxed);
494
495 sampleRate_ = spec.sampleRate;
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_));
502
503 latencySamples_.store(static_cast<int64_t>(onset_.getEnvelopeLatencySamples())
504 + 2 * static_cast<int64_t>(hop_),
505 std::memory_order_relaxed);
506
507 buildBank();
508 buildComb();
510
511 // Offline scratch that does not depend on the signal length.
512 candidates_.reserve(64);
513
514 resetState();
515 prepared_.store(true, std::memory_order_relaxed);
516 }
517
526 void setTempoRange(T minBpm, T maxBpm) noexcept
527 {
528 if (!std::isfinite(minBpm) || !std::isfinite(maxBpm)) return;
529 if (!(minBpm > T(0)) || !(maxBpm > T(0)) || !(minBpm <= maxBpm)) return;
530
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);
538 }
539
541 void applyTempoRange() noexcept
542 {
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);
548
549 // Bank index runs with PERIOD, so the fastest tempo is the lowest
550 // index: the high BPM bound selects the low index bound.
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);
556
557 // The two indices are a set with an invariant (lo <= hi), so they are
558 // published as one word: half of one range combined with half of the
559 // next is a range nobody asked for, and it would be searched.
560 activeRange_.store(packRange(iLo, iHi), std::memory_order_relaxed);
561 }
562
616 void setTightness(T alpha) noexcept
617 {
618 if (!std::isfinite(alpha)) return;
619 tightness_.store(std::max(kMinTightness, static_cast<double>(alpha)),
620 std::memory_order_relaxed);
621 }
622
624 [[nodiscard]] T getTightness() const noexcept
625 {
626 return static_cast<T>(tightness_.load(std::memory_order_relaxed));
627 }
628
630 [[nodiscard]] static constexpr T defaultTightness() noexcept
631 {
632 return static_cast<T>(kDefaultTightness);
633 }
634
635 // -- Offline -------------------------------------------------------------
636
649 {
650 if (!prepared_.load(std::memory_order_relaxed)) return {};
651 if (whole.getNumChannels() < 1 || whole.getNumSamples() <= 0) return {};
652 const int n = whole.getNumSamples();
653 beginOffline(n);
654 pushOffline(std::span<const T>(whole.getChannel(0), static_cast<size_t>(n)));
655 return finishOffline();
656 }
657
674 void beginOffline(int64_t expectedSamples = 0)
675 {
676 env_.clear();
677 envRef_.clear();
678 for (auto& r : envReg_) r.clear();
679 offlineOpen_ = false;
680 if (!prepared_.load(std::memory_order_relaxed)) return;
681
682 resetState();
683 if (expectedSamples > 0)
684 {
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);
689 }
690 offlinePushed_ = 0;
691 offlineOpen_ = true;
692 }
693
696 void pushOffline(std::span<const T> samples)
697 {
698 if (!offlineOpen_) return;
699 size_t off = 0;
700 while (off < samples.size())
701 {
702 // Pieces end on the front end's frame boundaries, so each frame's
703 // envelope value is read as the frame is computed.
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);
709 off += take;
710 if (offlinePushed_ % static_cast<int64_t>(hop_) == 0) appendEnvelopeFrame();
711 }
712 }
713
718 {
719 Result out;
720 if (!offlineOpen_) return out;
721 offlineOpen_ = false;
722 onset_.reset();
723
724 return finishEnvelope();
725 }
726
727 // -- Audio path (causal, RT-safe) ---------------------------------------
728
732 {
733 if (!prepared_.load(std::memory_order_relaxed) || in.getNumChannels() < 1)
734 return;
735 const T* ch0 = in.getChannel(0);
736 pushSamples(std::span<const T>(ch0, static_cast<size_t>(in.getNumSamples())));
737 }
738
747 void pushSamples(std::span<const T> samples) noexcept
748 {
749 if (!prepared_.load(std::memory_order_relaxed)) return;
750
751 bool fired = false;
752 size_t off = 0;
753 while (off < samples.size())
754 {
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_)
757 - sinceFrame);
758 const size_t take = std::min(samples.size() - off, toBoundary);
759
760 onset_.pushSamples(samples.subspan(off, take));
761 samplesPushed_ += static_cast<int64_t>(take);
762 off += take;
763
764 if (static_cast<size_t>(take) == toBoundary)
765 {
766 if (advanceFrame()) fired = true;
767 }
768 }
769
770 // Release, and the matching acquire is in beatNow(). The latch and the
771 // beat's position are two separate words written in this same call,
772 // and a caller that sees the latch set must not then read a position
773 // from an earlier call: on a weakly ordered machine two relaxed loads
774 // of distinct objects may be observed in either order, so without this
775 // pairing a reader could be handed the PREVIOUS beat's position -- an
776 // error of one whole beat period -- while being told a beat just
777 // happened. The store is last on purpose: everything the frame wrote,
778 // the position included, is ordered before it.
779 beatLatched_.store(fired, std::memory_order_release);
780 }
781
782 // -- Readout (lock-free) -------------------------------------------------
783
795 [[nodiscard]] T getBeatTempoBpm() const noexcept
796 {
797 return static_cast<T>(beatTempo_.load(std::memory_order_relaxed));
798 }
799
801 [[nodiscard]] T getRunningTempoBpm() const noexcept
802 {
803 float bpm = 0.0f, conf = 0.0f;
804 unpackTempo(tempoAndConfidence_.load(std::memory_order_relaxed), bpm, conf);
805 return static_cast<T>(bpm);
806 }
807
834 [[nodiscard]] T getConfidence() const noexcept
835 {
836 float bpm = 0.0f, conf = 0.0f;
837 unpackTempo(tempoAndConfidence_.load(std::memory_order_relaxed), bpm, conf);
838 return static_cast<T>(conf);
839 }
840
850 void getTempoAndConfidence(T& bpmOut, T& confidenceOut) const noexcept
851 {
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);
856 }
857
874 [[nodiscard]] bool beatNow() const noexcept
875 {
876 return beatLatched_.load(std::memory_order_acquire);
877 }
878
892 [[nodiscard]] int64_t getLastBeatSample() const noexcept
893 {
894 return lastBeatSample_.load(std::memory_order_relaxed);
895 }
896
906 [[nodiscard]] int getLatencySamples() const noexcept
907 {
908 return static_cast<int>(latencySamples_.load(std::memory_order_relaxed));
909 }
910
912 [[nodiscard]] double getFrameRate() const noexcept { return frameRate_; }
913
916 [[nodiscard]] const OnsetDetector<T>& getOnsetDetector() const noexcept
917 {
918 return onset_;
919 }
920
923 void reset() noexcept
924 {
925 offlineOpen_ = false;
926 resetState();
927 }
928
929private:
930 // Shared complete-envelope engine. The legacy sample frontend and the
931 // pooled offline feature path both execute this exact arithmetic.
932 Result finishEnvelope(void* beatContext = nullptr,
933 void (*receiveBeats)(void*, std::span<const int64_t>) = nullptr)
934 {
935 Result out;
936 int iLo = 0, iHi = 0;
937 unpackRange(activeRange_.load(std::memory_order_relaxed), iLo, iHi);
938
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))
942 {
943 resetState();
944 return out;
945 }
946
947 conditionEnvelope();
948
949 // Two candidate periods from the tempo-prior-weighted autocorrelation,
950 // at least a quarter octave apart so that the runner-up is a different
951 // metrical reading and not the same peak one lag over.
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; }
958
959 // The ranking above proposes a reading; which multiple of it is the
960 // beat is settled by the level model (see chooseMetricalLevel()). Only
961 // where the signal has a pulse of its own in the range: otherwise the
962 // correlation decided on its own, and so it stays.
963 if (fundamentalFound_) chooseMetricalLevel(iLo, iHi, tau1, tau2);
964
965 // The metrical level is decided against one period for the whole
966 // signal, which is the stable model, and only then is the grid laid
967 // down: held to the period the music keeps, following where it leaves
968 // it (see layGrid()).
969 WorkVector<int64_t> win(detail::AccountedAllocator<int64_t>{&allocationAccount_});
970 if (!layGrid(tau1, win))
971 {
972 resetState();
973 return out;
974 }
975
976 // The delivered tempo is fitted to the delivered grid, not read off
977 // the autocorrelation lag: the grid spans the whole signal, so a
978 // straight-line fit through it resolves the period far below the
979 // frame spacing the lag is quantised to.
980 const double slope = fitBeatSlope(win);
981 if (receiveBeats)
982 receiveBeats(beatContext, {win.data(), win.size()});
983 else
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);
988
989 // Confidence is the coherence of the delivered grid, reduced only if
990 // the alternative explained the signal nearly as well. Coherence alone
991 // answers "does this grid fit"; it cannot answer "and is it the only
992 // grid that does", and on material that genuinely carries two pulses
993 // -- three against two, most obviously -- a tracker that reports one
994 // of them at full confidence is asserting something it has no evidence
995 // for. See kAmbiguityFloor for why the reduction has a floor under it
996 // instead of being applied in proportion.
997 const double base = coherence((slope > 0.0) ? slope / static_cast<double>(hop_)
998 : tau1);
999 out.confidence = static_cast<T>(std::clamp(base * ambiguityDiscount(secondaryShare_),
1000 0.0, 1.0));
1001
1002 resetState();
1003 return out;
1004 }
1005 // -- Constants -----------------------------------------------------------
1006
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;
1022
1035 static constexpr int kNumHarmonics = 3;
1036 static constexpr double kHarmonicDivisors[kNumHarmonics] = { 2.0, 3.0, 5.0 };
1037
1042 static constexpr double kIntegrationBeats = 8.0;
1043
1046 static constexpr double kPriorCentreSeconds = 0.5;
1047 static constexpr double kPriorWidthOctaves = 1.4;
1048
1069 static constexpr double kTactusFastOctaves = 0.45;
1070 static constexpr double kTactusSlowOctaves = kPriorWidthOctaves;
1071
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 = {
1107 // Each reading on its own:
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,
1114 // The same, relative to the proposed reading:
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,
1121 // Log tempo squared: the tapping preference.
1122 -2.979577030 };
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 };
1150
1163 static constexpr double kLevelContrastFloor = 0.1;
1165 static constexpr double kLevelWindowBeats = 8.0;
1166
1169 static constexpr double kDefaultTightness = 400.0;
1170 static constexpr double kMinTightness = 1e-3;
1171
1180 static constexpr double kMinFundamentalCoherence = 0.1;
1181
1195 static constexpr double kAmbiguityFloor = 0.5;
1196
1200 static constexpr double kCandidateSeparationOctaves = 0.25;
1201
1204 static constexpr double kCandidatePeakFloor = 0.25;
1205
1216 static constexpr double kNeighbourPeakFloor = 0.6;
1217 static constexpr double kNeighbourOctaves = 0.35;
1218
1223 static constexpr double kFollowTightness = 25.0;
1224
1229 static constexpr int kPeriodReachBeats = 4;
1230
1238 static constexpr double kStepSpreadShare = 1.0 / 3.0;
1239
1246 static constexpr double kHoldWidth = 0.08;
1247
1256 static constexpr double kHoldSpreads = 4.0;
1257 static constexpr double kSteadyHoldWidth = 0.02;
1258
1263 static constexpr double kHoldReachOctaves = 1.0 / 3.0;
1264
1268 static constexpr double kRecentreOctaves = 0.03;
1269
1275 static constexpr double kSecondTempoNear = 0.25;
1276 static constexpr double kSecondTempoFar = 2.0 * kHoldReachOctaves;
1277
1284 static constexpr double kSecondTempoPeakFloor = 0.3;
1285
1304 static constexpr double kSecondTempoShare = 0.25;
1305 static constexpr size_t kSecondTempoRun = 8;
1306 static constexpr double kSecondTempoGain = 1.15;
1307
1314 static constexpr double kIntervalCapBeats = 8.0;
1315
1321 static constexpr double kHeldShare = 0.5;
1322
1325 static constexpr double kMinAnalysisBeats = 4.0;
1326
1330 static constexpr double kCoherenceWindowBeats = 8.0;
1331
1333 static constexpr double kBaselineSeconds = 1.0;
1334
1337 static constexpr double kLocalScoreSigmaPeriods = 1.0 / 32.0;
1338
1340 static constexpr double kSearchLowFactor = 0.5;
1341 static constexpr double kSearchHighFactor = 2.0;
1342
1345 static constexpr double kExtendFraction = 0.125;
1346
1353 static constexpr double kSupportFraction = 0.25;
1354
1360 static constexpr double kEdgeSupportFraction = 0.5;
1361 static constexpr double kEdgeSeconds = 0.06;
1362
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");
1375
1376 // -- Packing -------------------------------------------------------------
1377
1382 [[nodiscard]] static std::uint64_t packTempo(float bpm, float conf) noexcept
1383 {
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);
1388 }
1389
1390 static void unpackTempo(std::uint64_t v, float& bpm, float& conf) noexcept
1391 {
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));
1396 }
1397
1398 [[nodiscard]] static std::uint32_t packRange(int lo, int hi) noexcept
1399 {
1400 return (static_cast<std::uint32_t>(lo & 0xFFFF) << 16)
1401 | static_cast<std::uint32_t>(hi & 0xFFFF);
1402 }
1403
1404 static void unpackRange(std::uint32_t v, int& lo, int& hi) noexcept
1405 {
1406 lo = static_cast<int>((v >> 16) & 0xFFFFu);
1407 hi = static_cast<int>(v & 0xFFFFu);
1408 }
1409
1410 // -- Bank ----------------------------------------------------------------
1411
1412 [[nodiscard]] double periodToBpm(double periodFrames) const noexcept
1413 {
1414 return (periodFrames > 0.0) ? 60.0 * frameRate_ / periodFrames : 0.0;
1415 }
1416
1417 [[nodiscard]] double bpmToPeriod(double bpm) const noexcept
1418 {
1419 return (bpm > 0.0) ? 60.0 * frameRate_ / bpm : 0.0;
1420 }
1421
1423 [[nodiscard]] int bpmToIndex(double bpm) const noexcept
1424 {
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);
1430 }
1431
1432 void buildBank()
1433 {
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);
1440
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);
1450
1451 const double centre = kPriorCentreSeconds * frameRate_;
1452 for (int i = 0; i < bankSize_; ++i)
1453 {
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;
1457
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);
1463
1464 const double lg = std::log2(p / centre) / kPriorWidthOctaves;
1465 bankPrior_[static_cast<size_t>(i)] = std::exp(-0.5 * lg * lg);
1466 }
1467
1468 // Index distance to each subharmonic. The bank is geometric, so a
1469 // ratio in period is a constant offset in index; rounding it to the
1470 // nearest bin is worth nothing at all here, because a resonator with a
1471 // memory of eight periods is a hundred times broader than one bin.
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)));
1475
1476 // The tactus preference of each subharmonic against its own candidate,
1477 // tabulated here so the per-frame score stays a few multiplies.
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]);
1485 buildBeatScore();
1486 }
1487
1488 // -- Causal path ---------------------------------------------------------
1489
1498 bool advanceFrame() noexcept
1499 {
1500 const typename OnsetDetector<T>::OdfFrame f = onset_.getLastOdfFrame();
1501 ++frameIndex_;
1502
1503 const double raw = (std::isfinite(f.value) && f.value > T(0))
1504 ? static_cast<double>(f.value) : 0.0;
1505 lastFrameRef_ = f.referenceSample;
1506
1507 // Same conditioning the offline path applies, in the only form a
1508 // causal path can have it: a trailing mean instead of a centred one.
1509 // Without it the log-compressed envelope's positive floor counts as
1510 // onset mass that is spread evenly in phase, so the coherence ratio
1511 // reads the noise floor of the material rather than its pulse -- on a
1512 // bed at a twentieth of the click amplitude that alone took the
1513 // published confidence from 0.98 to 0.25 while the tempo stayed
1514 // correct to a tenth of a percent, which is an under-reading a caller
1515 // gating on confidence would act on.
1516 baseline_ += (raw - baseline_) * baselineCoef_;
1517 const double o = std::max(0.0, raw - baseline_);
1518
1519 // The beat score reads both of the front end's onset functions,
1520 // each conditioned the same way and over its own running peak: the
1521 // log-compressed flux, where every register owns its share, and the
1522 // linear flux, where the loudest sound in the mix does. On
1523 // syncopated material the off-beats are often the busier sound and
1524 // the beat the louder one.
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_);
1533
1534 for (int i = 0; i < bankSize_; ++i)
1535 {
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;
1544
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)
1549 : 0.0;
1550 }
1551
1552 // The beat score is recursive over the envelope itself, so it is
1553 // updated on every frame, before the period that steers it is chosen.
1554 updateBeatScore(oBeat);
1555 updateComb(o);
1556 pushRegisters(f);
1557
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);
1562
1563 int best = -1;
1564 double bestScore = 0.0;
1565 for (int i = iLo; i <= iHi; ++i)
1566 {
1567 const double s = scoreAt(i);
1568 if (s > bestScore) { bestScore = s; best = i; }
1569 }
1570
1571 if (best < 0)
1572 {
1573 // Nothing in the searched range explains the envelope yet. Keep
1574 // the previous published pair rather than publishing a tempo of
1575 // zero and a confidence of zero, which a caller cannot tell from
1576 // a real reading of silence. The beat clock keeps running on the
1577 // period it already has.
1578 return advanceBeatClock();
1579 }
1580 // The beat clock follows the comb's metrical level once it has one,
1581 // and a held bank level before that; the published reading stays the
1582 // frame's own winner.
1583 int follow = holdMetricalLevel(best, bestScore, iLo, iHi);
1584 if (combBin_ >= 0)
1585 {
1586 // Re-decided on the frames the comb re-estimates; the test of
1587 // alike events reads the register history and is the costly part.
1588 if (combFresh_)
1589 {
1590 combFollow_ = foldToFundamental(combBin_, iLo, iHi);
1591 combAlike_ = sameEventsAtHalfPeriod(combFollow_, best);
1592 combFresh_ = false;
1593 }
1594 follow = combAlike_ ? best : std::clamp(combFollow_, iLo, iHi);
1595 }
1596
1597 // The runner-up at a different metrical level, and how nearly it
1598 // explained the envelope as well as the winner did. Same discount the
1599 // offline path applies, for the same reason and on the same scale: a
1600 // grid that fits is not the same claim as a grid that is the only one
1601 // that fits, and a caller gating on one number must be told the
1602 // difference.
1603 double runnerUp = 0.0;
1604 const int apart = std::max(1, static_cast<int>(kCandidateSeparationOctaves
1605 * kBinsPerOctave));
1606 for (int i = iLo; i <= iHi; ++i)
1607 {
1608 if (std::abs(i - best) < apart) continue;
1609 runnerUp = std::max(runnerUp, scoreAt(i, false));
1610 }
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;
1614
1615 // The level is adjudicated with a preference that changes from bin to
1616 // bin, so the bin it selects can sit one bin off the coherence peak of
1617 // the very level it selected. The period and the phase are read from
1618 // the peak itself, which is where the signal actually is: two steps
1619 // are enough, because the two functions never differ by more than the
1620 // preference's slope over one bin, and it costs -0.27% -> -0.14% on
1621 // the worst reported tempo at the top of the default range.
1622 const int searched = best;
1623 best = walkToCoherencePeak(best);
1624
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),
1628 0.0, 1.0);
1629
1630 // The walk onto the coherence peak can step past the end of the range
1631 // it was searched in; the published reading stays inside what was asked.
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)),
1635 rangeLo, rangeHi),
1636 static_cast<float>(conf)),
1637 std::memory_order_relaxed);
1638
1639 // The held level's refined period steers the beat clock. The
1640 // resonator's own phase is kept as the fallback for an ambiguous beat
1641 // score: arg(z) advances one turn per period, so the frames since the
1642 // resonator's last pulse are arg(z) scaled by the period, and its next
1643 // pulse is the rest of the turn away.
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();
1657 }
1658
1659 // -- Causal metrical level: comb-filter periodicity ----------------------
1660
1674 void buildComb()
1675 {
1676 combLength_ = std::max(64, static_cast<int>(std::lround(kCombSeconds * frameRate_)));
1677 int size = 64;
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)
1692 {
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));
1695 }
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)
1701 {
1702 const double u = static_cast<double>(d) / sigma;
1703 combKernel_[static_cast<size_t>(d + combSpan_)] = std::exp(-0.5 * u * u);
1704 }
1705 }
1706
1719 void updateComb(double o) noexcept
1720 {
1721 if (!combFft_) return;
1722 const int n = combLength_;
1723 combRing_[static_cast<size_t>(combWrite_ % n)] = o;
1724 ++combWrite_;
1725 if (--combCountdown_ > 0 || combWrite_ < static_cast<int64_t>(n / 2)) return;
1726 combCountdown_ = kCombUpdateFrames;
1727
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)
1735 {
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);
1740 }
1741 combFft_->forward(combTime_.data(), combSpec_.data());
1742 for (int k = 0; k <= combFftSize_ / 2; ++k)
1743 {
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;
1748 }
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);
1751
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);
1756
1757 // Each multiple a of the period is read as the mean of the lags within
1758 // (a - 1) * kCombWidthSeconds of it: an expressive beat drifts, and
1759 // the further multiples have drifted further.
1760 double total = 0.0;
1761 for (int i = iLo; i <= iHi; ++i)
1762 {
1763 const double lag = bankPeriod_[static_cast<size_t>(i)];
1764 double v = 0.0;
1765 for (int a = 1; a <= kCombMultiples; ++a)
1766 {
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));
1769 double sum = 0.0;
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);
1773 }
1774 // Half the period: the beat's subdivision is on the grid of a
1775 // binary level, and on no grid of a level three quarters or
1776 // three halves of it (a clave or tresillo repeats there).
1777 {
1778 const double h = 0.5 * lag;
1779 const int c0 = static_cast<int>(h);
1780 const double fr = h - static_cast<double>(c0);
1781 if (c0 + 1 < m)
1782 v += kCombHalfWeight * ((1.0 - fr) * combAcf_[static_cast<size_t>(c0)]
1783 + fr * combAcf_[static_cast<size_t>(c0) + 1]);
1784 }
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)];
1787 }
1788 if (!(total > 0.0)) return;
1789
1790 // Transition: the best predecessor under a Gaussian on log period,
1791 // times this estimate's normalised evidence. The first estimate has
1792 // no predecessor and takes the evidence alone.
1793 const bool first = combBin_ < 0;
1794 double bestV = 0.0, norm = 0.0;
1795 int bestI = -1;
1796 for (int j = iLo; j <= iHi; ++j)
1797 {
1798 double carry = first ? 1.0 : 0.0;
1799 if (!first)
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;
1805 norm += v;
1806 if (v > bestV) { bestV = v; bestI = j; }
1807 }
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;
1812 combBin_ = bestI;
1813 combFresh_ = true;
1814 }
1815
1832 [[nodiscard]] int foldToFundamental(int i, int iLo, int iHi) const noexcept
1833 {
1834 int j = std::clamp(i, iLo, iHi);
1835 for (int guard = 0; guard < kNumHarmonics; ++guard)
1836 {
1837 bool moved = false;
1838 for (int k = 0; k < kNumHarmonics && !moved; ++k)
1839 {
1840 const int sub = j + harmonicOffset_[k];
1841 if (sub > iHi) continue;
1842 int peak = sub;
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)])
1845 peak = q;
1846 const double c = bankCoherence_[static_cast<size_t>(peak)];
1847 if (c > kCombFoldFloor && c >= kCombFoldRatio * bankCoherence_[static_cast<size_t>(j)])
1848 {
1849 j = std::clamp(peak, iLo, iHi);
1850 moved = true;
1851 }
1852 }
1853 if (!moved) break;
1854 }
1855 return j;
1856 }
1857
1860 void pushRegisters(const typename OnsetDetector<T>::OdfFrame& f) noexcept
1861 {
1862 if (regRing_.empty()) return;
1863 const int n = combLength_;
1864 for (int g = 0; g < kRegisters; ++g)
1865 {
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)]);
1871 }
1872 }
1873
1887 [[nodiscard]] bool sameEventsAtHalfPeriod(int level, int fast) const noexcept
1888 {
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;
1897 double worst = 1.0;
1898 bool any = false;
1899 for (int g = 0; g < kRegisters; ++g)
1900 {
1901 const double* x = &regRing_[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) {
1904 double best = 0.0;
1905 for (int q = l - 2; q <= l + 2; ++q)
1906 {
1907 double xy = 0.0, xx = 0.0, yy = 0.0;
1908 for (int i = 0; i + q < m; ++i)
1909 {
1910 const double a = at(i), b = at(i + q);
1911 xy += a * b; xx += a * a; yy += b * b;
1912 }
1913 if (xx > 0.0 && yy > 0.0) best = std::max(best, xy / std::sqrt(xx * yy));
1914 }
1915 return best;
1916 };
1917 const double slow = repetition(2 * lag);
1918 if (!(slow > kIsochronyFloor)) continue;
1919 any = true;
1920 worst = std::min(worst, repetition(lag) / slow);
1921 }
1922 return any && worst >= kIsochronyRatio;
1923 }
1924
1927 [[nodiscard]] int walkToCoherencePeak(int i) const noexcept
1928 {
1929 for (int guard = 0; guard < 2; ++guard)
1930 {
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;
1936 else break;
1937 }
1938 return i;
1939 }
1940
1957 [[nodiscard]] int holdMetricalLevel(int best, double bestScore, int iLo, int iHi) noexcept
1958 {
1959 const int apart = std::max(1, static_cast<int>(kCandidateSeparationOctaves
1960 * kBinsPerOctave));
1961 if (heldLevel_ < iLo || heldLevel_ > iHi) { heldLevel_ = -1; levelChallengeFrames_ = 0; }
1962 if (heldLevel_ < 0 || std::abs(best - heldLevel_) < apart)
1963 {
1964 heldLevel_ = best;
1965 levelChallengeFrames_ = 0;
1966 return best;
1967 }
1968 // Best candidate within the level in force.
1969 const int half = apart / 2;
1970 int held = -1;
1971 double heldScore = 0.0;
1972 for (int i = std::max(iLo, heldLevel_ - half); i <= std::min(iHi, heldLevel_ + half); ++i)
1973 {
1974 const double sc = scoreAt(i);
1975 if (held < 0 || sc > heldScore) { heldScore = sc; held = i; }
1976 }
1977 if (bestScore > heldScore) ++levelChallengeFrames_;
1978 else levelChallengeFrames_ = 0;
1979 if (static_cast<double>(levelChallengeFrames_)
1980 >= kLevelHoldBeats * bankPeriod_[static_cast<size_t>(best)])
1981 {
1982 heldLevel_ = best;
1983 levelChallengeFrames_ = 0;
1984 }
1985 else if (held >= 0)
1986 {
1987 heldLevel_ = held;
1988 }
1989 return heldLevel_;
1990 }
1991
1992 // -- Causal beat placement -------------------------------------------------
1993
1996 [[nodiscard]] double beatIntervalWeight(int d, double lnTau) const noexcept
1997 {
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)];
2004 }
2005
2007 void buildBeatScore()
2008 {
2009 const double pMax = bpmToPeriod(kBankMinBpm);
2010 int len = 64;
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)
2022 {
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;
2028 }
2029 }
2030
2040 void updateBeatScore(double o) noexcept
2041 {
2042 const int mask = beatScoreLen_ - 1;
2043 double best = 0.0;
2044 if (haveBeatPeriod_)
2045 {
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)
2053 {
2054 const double v = beatIntervalWeight(d, lnTau)
2055 * beatScore_[static_cast<size_t>((beatScoreWrite_ - d) & mask)];
2056 if (v > best) best = v;
2057 }
2058 }
2059 beatScore_[static_cast<size_t>(beatScoreWrite_ & mask)]
2060 = (1.0 - kBeatScoreFeedback) * o + kBeatScoreFeedback * best;
2061 ++beatScoreWrite_;
2062 ++beatScoreFrames_;
2063 }
2064
2082 void predictNextBeat() noexcept
2083 {
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)];
2095
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)
2101 {
2102 const int at = past - 1 + k;
2103 double b = 0.0;
2104 for (int d = lo; d <= hi; ++d)
2105 {
2106 const int j = at - d;
2107 if (j < 0) break;
2108 const double v = beatIntervalWeight(d, lnTau) * beatScratch_[static_cast<size_t>(j)];
2109 if (v > b) b = v;
2110 }
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; }
2116 }
2117
2118 if (bestV > 0.0)
2119 {
2120 double rival = 0.0;
2121 for (int k = 1; k <= span; ++k)
2122 {
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);
2129 }
2130 if (rival >= (1.0 - kAmbiguousScore) * bestV)
2131 {
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);
2138 }
2139 }
2140 beatCountdown_ = bestK;
2141 framesToPrediction_ = bestK + static_cast<int>(std::lround(0.5 * tau));
2142 }
2143
2145 [[nodiscard]] static double wrapToPeriod(double x, double period) noexcept
2146 {
2147 double d = std::fmod(x, period);
2148 if (d > 0.5 * period) d -= period;
2149 if (d < -0.5 * period) d += period;
2150 return d;
2151 }
2152
2167 bool advanceBeatClock() noexcept
2168 {
2169 bool beat = false;
2170 if (beatPending_)
2171 {
2172 lastBeatSample_.store(std::max<int64_t>(0, pendingBeatRef_), std::memory_order_relaxed);
2173 beatPending_ = false;
2174 beat = true;
2175 }
2176 if (!haveBeatPeriod_) return beat;
2177 if (framesToPrediction_ < 0)
2178 {
2179 if (static_cast<double>(beatScoreFrames_) >= beatPeriod_) predictNextBeat();
2180 return beat;
2181 }
2182 if (beatCountdown_ > 0 && --beatCountdown_ == 0)
2183 {
2184 beatPending_ = true;
2185 pendingBeatRef_ = lastFrameRef_ - static_cast<int64_t>(hop_);
2186 }
2187 if (--framesToPrediction_ <= 0) predictNextBeat();
2188 return beat;
2189 }
2190
2199 [[nodiscard]] double refinePeriod(int i) const noexcept
2200 {
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));
2211 }
2212
2227 [[nodiscard]] double scoreAt(int i, bool withPreference = true) const noexcept
2228 {
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)
2232 {
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]
2237 : 1.0;
2238 s *= (1.0 - std::min(1.0, r * bankCoherence_[static_cast<size_t>(sub)]));
2239 }
2240 return s;
2241 }
2242
2263 [[nodiscard]] static double levelPreference(double periodSeconds) noexcept
2264 {
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);
2269 }
2270
2271 [[nodiscard]] double levelRatio(double periodFrames, double divisor) const noexcept
2272 {
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);
2278 }
2279
2280 // -- Offline stages ------------------------------------------------------
2281
2286 void appendEnvelopeFrame()
2287 {
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)
2293 {
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);
2296 }
2297 }
2298
2310 void conditionEnvelope()
2311 {
2312 const int n = static_cast<int>(env_.size());
2313 if (n < 1) return;
2314
2315 // Register balance. The onset function is a mean over quarter-tone
2316 // bands, and the upper registers own most of them: a kick lights a
2317 // handful of bands below 200 Hz while hats, strums and consonants light
2318 // a hundred. On a dense master the pulse the kick states then barely
2319 // shows in the mean, and the backbeat and syllable rhythm decide the
2320 // metrical level instead. So the level is decided on a second,
2321 // register-balanced envelope: each register conditioned on its own -
2322 // floor removed, scaled to unit spread - and the four summed, so that
2323 // a register carries evidence in proportion to how regular it is, not
2324 // to how many bands it spans. The grid itself is still laid on the
2325 // plain envelope, where every onset keeps its own weight. Measured on a limited pop master at 135
2326 // BPM (kick on every beat, snare on two and four, strummed guitar and
2327 // a syllabic vocal on top), the coherence at half the tempo falls from
2328 // 0.88 of the coherence at the beat to 0.38.
2329 envBal_.clear();
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; }
2335 if (haveRegisters)
2336 {
2337 // A register counts in proportion to how periodic it is: its
2338 // normalised autocorrelation peak over the searched lags. A
2339 // register holding one isolated event - a tone switching on - or
2340 // unpatterned material has no such peak and adds nothing, where
2341 // plain unit-spread scaling would have amplified it to equal voice.
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_)
2348 {
2349 conditionSeries(r, true);
2350 double zero = 0.0;
2351 for (const double v : r) zero += v * v;
2352 zero /= static_cast<double>(n);
2353 double peak = 0.0;
2354 if (zero > 0.0)
2355 for (int lag = lagLo; lag <= lagHi; ++lag)
2356 {
2357 checkOfflineWork();
2358 double acc = 0.0;
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);
2362 }
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)];
2365 }
2366 conditionSeries(envBal_, false); // already floor-free: rescale only
2367 }
2368 conditionSeries(env_, true);
2369 }
2370
2372 void conditionSeries(WorkVector<double>& e, bool removeFloor)
2373 {
2374 const int n = static_cast<int>(e.size());
2375 if (n < 1) return;
2376
2377 const int half = std::max(1, static_cast<int>(std::lround(0.5 * kBaselineSeconds
2378 * frameRate_)));
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)];
2383
2384 double sumSq = 0.0;
2385 for (int i = 0; i < n; ++i)
2386 {
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;
2396 sumSq += v * v;
2397 }
2398
2399 const double rms = std::sqrt(sumSq / static_cast<double>(n));
2400 if (rms > 0.0)
2401 {
2402 const double g = 1.0 / rms;
2403 for (int i = 0; i < n; ++i) e[static_cast<size_t>(i)] *= g;
2404 }
2405 }
2406
2417 [[nodiscard]] double coherence(double periodFrames) const
2418 {
2419 return coherence(env_, periodFrames);
2420 }
2421
2422 [[nodiscard]] double coherence(const WorkVector<double>& envelope,
2423 double periodFrames) const
2424 {
2425 const int n = static_cast<int>(envelope.size());
2426 if (n < 2 || !(periodFrames > 1.0)) return 0.0;
2427
2428 const int win = std::max(4, static_cast<int>(std::lround(kCoherenceWindowBeats
2429 * periodFrames)));
2430 if (win > n) return coherenceWindow(envelope, 0, n, periodFrames);
2431
2432 const int step = std::max(1, win / 2);
2433 double acc = 0.0;
2434 int count = 0;
2435 for (int start = 0; start + win <= n; start += step)
2436 {
2437 acc += coherenceWindow(envelope, start, start + win, periodFrames);
2438 ++count;
2439 }
2440 if (count == 0) return coherenceWindow(envelope, 0, n, periodFrames);
2441 return acc / static_cast<double>(count);
2442 }
2443
2444 [[nodiscard]] double coherenceWindow(const WorkVector<double>& envelope,
2445 int from, int to, double periodFrames) const
2446 {
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)
2450 {
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);
2456 mass += v;
2457 }
2458 if (!(mass > kMassFloor)) return 0.0;
2459 return std::min(1.0, std::sqrt(re * re + im * im) / mass);
2460 }
2461
2463 [[nodiscard]] std::array<double, 2> offlineCandidateScores(
2464 const WorkVector<double>& envelope, double period) const
2465 {
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)
2471 {
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));
2475 }
2476 return { adjudicated, explains };
2477 }
2478
2502 void pickCandidates(int iLo, int iHi, double& tau1, double& tau2)
2503 {
2504 tau1 = 0.0;
2505 tau2 = 0.0;
2506 secondaryShare_ = 0.0;
2507 fundamentalFound_ = false;
2508
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;
2515
2516 // Score one guard lag on either side so a genuine maximum exactly at
2517 // the requested range endpoint can be tested against both neighbors.
2518 // Previously both endpoints were excluded from candidate generation.
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)
2522 {
2523 checkOfflineWork();
2524 double s = 0.0;
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);
2532 }
2533
2534 // Peaks, not merely the argmax: the runner-up must be a peak of its
2535 // own, or it is the same peak read one lag over.
2536 candidates_.clear();
2537 for (int lag = lagLo; lag <= lagHi; ++lag)
2538 {
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)
2542 {
2543 // A guard lag helps locate the maximum; it must not introduce
2544 // an out-of-range metrical hypothesis after interpolation.
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);
2549 }
2550 }
2551 if (candidates_.empty()) return;
2552
2553 // A candidate is a lag at which the envelope actually repeats. Local
2554 // maxima of the correlation's noise floor between its real peaks - a
2555 // hundredth of their height - are lags at which it does not, and the
2556 // coherence ranking below cannot tell them apart from real pulses on
2557 // dense material, where every coherence is small: measured on a
2558 // limited 92 BPM master, a 141 BPM bump at 0.3% of the tallest peak
2559 // outranked the 92 BPM peak itself. Only peaks within a fixed ratio
2560 // of the tallest are ranked.
2561 {
2562 double top = 0.0;
2563 for (const int lag : candidates_) top = std::max(top, acf_[static_cast<size_t>(lag)]);
2564 size_t w = 0;
2565 for (const int lag : candidates_)
2566 if (acf_[static_cast<size_t>(lag)] >= kCandidatePeakFloor * top)
2567 candidates_[w++] = lag;
2568 candidates_.resize(w);
2569 }
2570
2571 // Within one reading the correlation is the judge. Candidates closer
2572 // than the nearest metrical relation (kNeighbourOctaves) are the same
2573 // reading at two tunings, and the ranking below is not built to tell
2574 // those apart: it weighs a period against its own multiples, and a
2575 // lag beside the period, whose multiples fall between the repeats,
2576 // is weighed against nothing and ranks high for it. One that
2577 // correlates less than kNeighbourPeakFloor of another within that
2578 // distance is a shoulder of the other's peak, and is not ranked.
2579 {
2580 const WorkVector<int> all(candidates_.begin(), candidates_.end(),
2581 candidates_.get_allocator());
2582 size_t w = 0;
2583 for (size_t i = 0; i < all.size(); ++i)
2584 {
2585 bool shoulder = false;
2586 for (size_t j = 0; j < all.size() && !shoulder; ++j)
2587 shoulder = j != i
2588 && std::abs(std::log2(static_cast<double>(all[i])
2589 / static_cast<double>(all[j])))
2590 < kNeighbourOctaves
2591 && kNeighbourPeakFloor * acf_[static_cast<size_t>(all[j])]
2592 > acf_[static_cast<size_t>(all[i])];
2593 if (!shoulder) candidates_[w++] = all[i];
2594 }
2595 candidates_.resize(w);
2596 }
2597
2598 // Rank by the octave discriminator, not by correlation height. Two
2599 // scores per candidate, for the two questions of scoreAt(): the
2600 // adjudicated one decides the level, the explanatory one is what the
2601 // confidence is discounted against.
2602 candScore_.assign(candidates_.size(), 0.0);
2603 candExplains_.assign(candidates_.size(), 0.0);
2604 for (size_t k = 0; k < candidates_.size(); ++k)
2605 {
2606 const double tau = refineLag(candidates_[k]);
2607 const auto scores = offlineCandidateScores(env_, tau);
2608 candScore_[k] = scores[0];
2609 candExplains_[k] = scores[1];
2610 }
2611
2612 size_t k1 = 0;
2613 for (size_t k = 1; k < candidates_.size(); ++k)
2614 if (candScore_[k] > candScore_[k1]) k1 = k;
2615
2616 // The discriminator can only choose between candidates that look like
2617 // a fundamental. When the caller has restricted the range so that the
2618 // signal's own period falls outside it, every candidate left inside is
2619 // one of that period's subharmonics -- and a subharmonic is exactly
2620 // what the coherence term is built to score at nothing, so the ranking
2621 // would be choosing between residues. That is not a failure of the
2622 // caller's request: a listener held to 60..100 BPM on a 160 BPM pulse
2623 // hears 80, and 80 is a peak of the correlation. So when no candidate
2624 // clears the floor, the correlation decides on its own.
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)
2631 {
2632 k1 = 0;
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])];
2638 }
2639 tau1 = refineLag(candidates_[k1]);
2640
2641 // The reported alternative and the ambiguity it implies are two
2642 // different quantities and are taken from the two different scores.
2643 // What gets REPORTED is the level a listener could plausibly have
2644 // tapped instead, so it is the best adjudicated alternative. What
2645 // DISCOUNTS the confidence is the best explanation of the envelope at
2646 // any other level, tapping preference set aside -- on a polyrhythm the
2647 // most competitive explanation is the tatum, which is not a level
2648 // anyone taps, and a confidence blind to it would call the signal
2649 // unambiguous because the reported alternative happens to be modest.
2650 int k2 = -1;
2651 double bestOther = 0.0;
2652 for (size_t k = 0; k < candidates_.size(); ++k)
2653 {
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]);
2660 }
2661 if (k2 >= 0)
2662 {
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;
2666 }
2667 }
2668
2670 [[nodiscard]] double refineLag(int lag) const noexcept
2671 {
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;
2681 }
2682
2684 [[nodiscard]] std::array<double, kLevelRawFeatures> levelFeatures(
2685 double period, const WorkVector<double>& balanced) const noexcept
2686 {
2687 std::array<double, kLevelRawFeatures> features {};
2688 size_t k = 0;
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);
2701 return features;
2702 }
2703
2718 void chooseMetricalLevel(int iLo, int iHi, double& tau1, double& tau2)
2719 {
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);
2727
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)
2733 {
2734 best = -1;
2735 double bestScore = 0.0;
2736 for (int c = 0; c < kLevelCandidates; ++c)
2737 {
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; }
2747 }
2748 }
2749
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)
2756 {
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)
2760 {
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)
2772 {
2773 bestGain = gain;
2774 chosenPeriod = period;
2775 ternaryChosen = true;
2776 }
2777 }
2778 }
2779 if (ternaryChosen)
2780 {
2781 tau2 = binaryPeriod;
2782 tau1 = chosenPeriod;
2783 }
2784 else if (best != kLevelMiddle)
2785 {
2786 tau2 = tau1;
2787 tau1 = binaryPeriod;
2788 }
2789 if (ternaryChosen || best != kLevelMiddle)
2790 refreshMetricalAmbiguity(balanced, tau1, tau2,
2791 { supportedPeriods.data(), supportedCount });
2792 }
2793
2795 void refreshMetricalAmbiguity(const WorkVector<double>& envelope,
2796 double chosen, double displaced,
2797 std::span<const double> addedPeriods)
2798 {
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]);
2809 };
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);
2814 }
2815
2826 [[nodiscard]] static double pulseShare(const WorkVector<double>& e,
2827 double periodFrames) noexcept
2828 {
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)
2836 {
2837 // The phasor is seeded exactly at each window start and rotated
2838 // within it; over one window the rotation's rounding is far
2839 // below anything the features resolve.
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)
2844 {
2845 const double v = std::max(0.0, e[static_cast<size_t>(i)]);
2846 re += v * c;
2847 im += v * s;
2848 m += v;
2849 const double cn = c * dc - s * ds;
2850 s = s * dc + c * ds;
2851 c = cn;
2852 }
2853 if (m > 0.0) { acc += std::sqrt(re * re + im * im); mass += m; }
2854 }
2855 return (mass > 0.0) ? acc / mass : 0.0;
2856 }
2857
2860 [[nodiscard]] static double repetition(const WorkVector<double>& e,
2861 double periodFrames) noexcept
2862 {
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)
2871 : 0.0;
2872 }
2873
2916 bool layGrid(double tau, WorkVector<int64_t>& gridOut)
2917 {
2918 gridOut.clear();
2919 localPeriod_.clear();
2920 localTightness_.clear();
2921 intervalCap_ = 0.0;
2922 alphaScale_ = 1.0;
2923
2924 WorkVector<int> grid(detail::AccountedAllocator<int>{&allocationAccount_});
2925 bool have = false;
2926 if (coherence(tau) >= kMinFundamentalCoherence)
2927 {
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;
2932 alphaScale_ = 1.0;
2933 if (followed)
2934 {
2935 // A signal at two tempi, the second out of the loose pass's
2936 // reach from the first. Laid around the period between them
2937 // the loose grid follows both.
2938 double given = tau;
2939 if (const double second = secondTempo(tau); second > 0.0)
2940 {
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;
2945 alphaScale_ = 1.0;
2946
2947 // Taken if it is a grid at the two tempi: that share of
2948 // its intervals in runs at each of the two periods, and
2949 // each of its beats carrying that much more than a beat
2950 // of the first grid, both on the score it was laid on. A
2951 // grid that settled on one period, the second or one
2952 // between the two, or that goes from one to the other
2953 // every few beats, follows another reading of the tempo,
2954 // and which reading is the beat was decided before this.
2955 bool taken = false;
2956 if (laid)
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());
2962 if (taken)
2963 {
2964 loose.swap(both);
2965 given = between;
2966 }
2967 else
2968 buildLocalScore(tau); // back on the score the first chain was laid on
2969 }
2970
2971 double overall = overallPeriod(loose, given);
2972 if (std::abs(std::log2(overall / given)) > kRecentreOctaves)
2973 {
2974 // The loose grid moves at another period than the one it
2975 // was given: laid again around its own, it no longer pays
2976 // for the distance at the far end of a tempo that swings.
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;
2980 alphaScale_ = 1.0;
2981 if (laid)
2982 {
2983 loose.swap(again);
2984 overall = overallPeriod(loose, overall);
2985 }
2986 else
2987 buildLocalScore(given); // back on the score the first chain was laid on
2988 }
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();
2994 intervalCap_ = 0.0;
2995
2996 // Both grids on the score the held one was laid on, the loose
2997 // one continued past its ends the way the held one was.
2998 extendGrid(loose);
2999 if (!have || carriedBy(grid) < kHeldShare * carriedBy(loose))
3000 {
3001 grid.swap(loose);
3002 have = grid.size() >= 2;
3003 }
3004 }
3005 }
3006 if (!have) have = runDp(tau, grid) && grid.size() >= 2;
3007 if (!have) return false;
3008
3009 gridOut.reserve(grid.size());
3010 for (const int f : grid)
3011 gridOut.push_back(beatSample(f));
3012 return true;
3013 }
3014
3016 [[nodiscard]] double carriedBy(const WorkVector<int>& beatFrames) const noexcept
3017 {
3018 double sum = 0.0;
3019 for (const int f : beatFrames) sum += local_[static_cast<size_t>(f)];
3020 return sum;
3021 }
3022
3028 [[nodiscard]] static double centralMean(WorkVector<double>& intervals)
3029 {
3030 std::sort(intervals.begin(), intervals.end());
3031 const size_t q = intervals.size() / 4;
3032 double sum = 0.0;
3033 for (size_t j = q; j < intervals.size() - q; ++j) sum += intervals[j];
3034 return sum / static_cast<double>(intervals.size() - 2 * q);
3035 }
3036
3039 [[nodiscard]] double overallPeriod(const WorkVector<int>& beats, double around) const
3040 {
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);
3047 }
3048
3051 [[nodiscard]] static double shareInRuns(const WorkVector<int>& beats, double period) noexcept
3052 {
3053 size_t inRuns = 0, run = 0;
3054 for (size_t k = 1; k < beats.size(); ++k)
3055 {
3056 if (std::abs(std::log(static_cast<double>(beats[k] - beats[k - 1]) / period))
3057 <= kHoldWidth)
3058 {
3059 ++run;
3060 continue;
3061 }
3062 if (run >= kSecondTempoRun) inRuns += run;
3063 run = 0;
3064 }
3065 if (run >= kSecondTempoRun) inRuns += run;
3066 return static_cast<double>(inRuns) / static_cast<double>(beats.size() - 1);
3067 }
3068
3078 [[nodiscard]] double secondTempo(double tau) const noexcept
3079 {
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_)
3084 {
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)
3089 {
3090 most = v;
3091 second = static_cast<double>(lag);
3092 }
3093 }
3094 return second;
3095 }
3096
3130 void holdToGrid(const WorkVector<int>& beats, double overall)
3131 {
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_);
3136
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]);
3141 };
3142
3143 // The period a run of intervals keeps, and how far they sit from it.
3144 const auto read = [&window, &interval](size_t first, size_t last,
3145 double& period, double& spread) {
3146 window.clear();
3147 for (size_t j = first; j <= last; ++j) window.push_back(interval(j));
3148 period = centralMean(window);
3149 spread = 0.0;
3150 for (const double x : window) spread += std::abs(std::log(x / period));
3151 spread /= static_cast<double>(window.size());
3152 };
3153
3154 // The local period of each interval, at the interval's centre, as
3155 // the log of its distance from the overall one.
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)
3160 {
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);
3165
3166 // One side alone, where it is whole and far the steadier.
3167 double steadiest = kStepSpreadShare * spread, readSpread = spread;
3168 if (k >= each && last > k)
3169 {
3170 double sidePeriod = 0.0, sideSpread = 0.0;
3171 read(k - each, k, sidePeriod, sideSpread);
3172 if (sideSpread < steadiest)
3173 {
3174 steadiest = readSpread = sideSpread;
3175 period = sidePeriod;
3176 }
3177 }
3178 if (k + each < count && first < k)
3179 {
3180 double sidePeriod = 0.0, sideSpread = 0.0;
3181 read(k, k + each, sidePeriod, sideSpread);
3182 if (sideSpread < steadiest)
3183 {
3184 steadiest = readSpread = sideSpread;
3185 period = sidePeriod;
3186 }
3187 }
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]);
3191 }
3192
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);
3197 size_t k = 0;
3198 for (int i = 0; i < n; ++i)
3199 {
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)
3206 {
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);
3211 }
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);
3216 }
3217 }
3218
3222 [[nodiscard]] static double ambiguityDiscount(double share) noexcept
3223 {
3224 if (!(share > kAmbiguityFloor)) return 1.0;
3225 return std::clamp(1.0 - (share - kAmbiguityFloor) / (1.0 - kAmbiguityFloor),
3226 0.0, 1.0);
3227 }
3228
3251 bool runDp(double periodFrames, WorkVector<int>& beatFrames, bool chainOnly = false)
3252 {
3253 beatFrames.clear();
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
3258 * periodFrames)));
3259 const int hi = std::max(lo + 1, static_cast<int>(std::lround(kSearchHighFactor
3260 * periodFrames)));
3261 if (n <= hi + 2) return false;
3262
3263 buildLocalScore(periodFrames);
3264
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);
3269
3270 for (int i = 0; i < n; ++i)
3271 {
3272 if ((i & 255) == 0) checkOfflineWork();
3273 const double target = varying ? localPeriod_[static_cast<size_t>(i)]
3274 : periodFrames;
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)))
3278 : lo;
3279 const int dHiBound = varying
3280 ? std::max(dLo + 1, static_cast<int>(std::lround(kSearchHighFactor
3281 * target)))
3282 : hi;
3283
3284 double best = 0.0;
3285 int bestJ = -1;
3286 const int dHi = std::min(dHiBound, i);
3287 for (int d = dLo; d <= dHi; ++d)
3288 {
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; }
3295 }
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;
3300 }
3301
3302 int end = 0;
3303 for (int i = 1; i < n; ++i)
3304 if (cumScore_[static_cast<size_t>(i)] > cumScore_[static_cast<size_t>(end)])
3305 end = i;
3306
3307 for (int i = end; i >= 0; i = backlink_[static_cast<size_t>(i)])
3308 {
3309 beatFrames.push_back(i);
3310 if (backlink_[static_cast<size_t>(i)] < 0) break;
3311 }
3312 std::reverse(beatFrames.begin(), beatFrames.end());
3313
3314 trimBeats(beatFrames);
3315 if (beatFrames.size() < 2) return false;
3316 if (chainOnly) return true;
3317
3318 extendGrid(beatFrames);
3319 return beatFrames.size() >= 2;
3320 }
3321
3324 [[nodiscard]] int edgeFrames() const noexcept
3325 {
3326 return static_cast<int>(std::ceil(kEdgeSeconds * frameRate_));
3327 }
3328
3342 void extendGrid(WorkVector<int>& beatFrames) const
3343 {
3344 if (beatFrames.size() < 3) return;
3345 const int n = static_cast<int>(env_.size());
3346
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;
3354
3355 double mean = 0.0;
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)));
3362
3363 const auto supported = [&](int guess, double least) {
3364 int best = -1;
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; }
3369 return best;
3370 };
3371
3372 WorkVector<int> front(detail::AccountedAllocator<int>{&allocationAccount_});
3373 for (int guess = beatFrames.front() - step; guess >= 0; guess -= step)
3374 {
3375 const int best = supported(guess, guess - win <= edge ? edgeFloor : floorValue);
3376 if (best < 0) break;
3377 front.push_back(best);
3378 guess = best;
3379 }
3380 std::reverse(front.begin(), front.end());
3381
3382 WorkVector<int> back(detail::AccountedAllocator<int>{&allocationAccount_});
3383 for (int guess = beatFrames.back() + step; guess <= n - 1; guess += step)
3384 {
3385 const int best = supported(guess, floorValue);
3386 if (best < 0) break;
3387 back.push_back(best);
3388 guess = best;
3389 }
3390
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);
3398 }
3399
3403 void buildLocalScore(double periodFrames)
3404 {
3405 const int n = static_cast<int>(env_.size());
3406 local_.assign(static_cast<size_t>(n), 0.0);
3407
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);
3411 double ksum = 0.0;
3412 for (int k = -half; k <= half; ++k)
3413 {
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;
3417 ksum += v;
3418 }
3419 if (ksum > 0.0)
3420 for (double& v : kernel_) v /= ksum;
3421
3422 for (int i = 0; i < n; ++i)
3423 {
3424 if ((i & 255) == 0) checkOfflineWork();
3425 double acc = 0.0;
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;
3432 }
3433 }
3434
3440 void trimBeats(WorkVector<int>& beatFrames) const
3441 {
3442 if (beatFrames.size() < 3) return;
3443
3444 double mean = 0.0;
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();
3450
3451 size_t first = 0;
3452 while (first + 2 < beatFrames.size()
3453 && local_[static_cast<size_t>(beatFrames[first])]
3454 < (beatFrames[first] <= edge ? edgeFloor : floorValue))
3455 ++first;
3456
3457 size_t last = beatFrames.size() - 1;
3458 while (last > first + 1
3459 && local_[static_cast<size_t>(beatFrames[last])] < floorValue)
3460 --last;
3461
3462 if (first > 0 || last + 1 < beatFrames.size())
3463 beatFrames = WorkVector<int>(beatFrames.begin()
3464 + static_cast<std::ptrdiff_t>(first),
3465 beatFrames.begin()
3466 + static_cast<std::ptrdiff_t>(last) + 1,
3467 beatFrames.get_allocator());
3468 }
3469
3495 [[nodiscard]] int64_t beatSample(int f) const noexcept
3496 {
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); // not a peak: nothing to interpolate
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_))));
3507 }
3508
3530 [[nodiscard]] static double fitBeatSlope(const WorkVector<int64_t>& beats)
3531 {
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()});
3535 ibi.reserve(n - 1);
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;
3541
3542 // Reuse the median scratch for interval counts. The fractional
3543 // transition ends exactly on a half-beat; its internal indices keep
3544 // their relative timing. No segment of the grid is discarded.
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;
3550 };
3551 for (size_t j = 3; j + 3 < ibi.size(); ++j)
3552 {
3553 if (stable(j) || !stable(j - 1) || !stable(j - 2) || !stable(j - 3))
3554 continue;
3555 for (size_t width = 1; width <= 3; ++width)
3556 {
3557 const size_t end = j + width;
3558 if (end + 3 > ibi.size()
3559 || !stable(end) || !stable(end + 1) || !stable(end + 2))
3560 continue;
3561 double total = 0.0;
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;
3567 j = end - 1;
3568 break;
3569 }
3570 }
3571
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)
3574 {
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;
3578 }
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;
3583 }
3584
3585 // -- State ---------------------------------------------------------------
3586
3587 void resetState() noexcept
3588 {
3589 onset_.reset();
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);
3594
3595 samplesPushed_ = 0;
3596 frameIndex_ = 0;
3597 lastFrameRef_ = 0;
3598 baseline_ = 0.0;
3599 linearBaseline_ = 0.0;
3600 scorePeak_ = 0.0;
3601 scorePeakLinear_ = 0.0;
3602 std::fill(beatScore_.begin(), beatScore_.end(), 0.0);
3603 beatScoreWrite_ = 0;
3604 beatScoreFrames_ = 0;
3605 beatPeriod_ = 0.0;
3606 haveBeatPeriod_ = false;
3607 resonatorLead_ = 0.0;
3608 framesToPrediction_ = -1;
3609 beatCountdown_ = 0;
3610 beatPending_ = false;
3611 pendingBeatRef_ = 0;
3612 heldLevel_ = -1;
3613 levelChallengeFrames_ = 0;
3614 std::fill(combRing_.begin(), combRing_.end(), 0.0);
3615 std::fill(combDelta_.begin(), combDelta_.end(), 0.0);
3616 combWrite_ = 0;
3617 combCountdown_ = kCombUpdateFrames;
3618 combBin_ = -1;
3619 combFollow_ = -1;
3620 combFresh_ = false;
3621 combAlike_ = false;
3622 std::fill(regRing_.begin(), regRing_.end(), 0.0);
3623 regBaseline_.fill(0.0);
3624
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);
3629 }
3630
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;
3673
3676 static constexpr double kMassFloor = 1e-12;
3677
3678 // -- Members -------------------------------------------------------------
3679
3680 detail::AllocationAccount allocationAccount_;
3681 void* offlineCheckpointContext_ = nullptr;
3682 void (*offlineCheckpoint_)(void*) = nullptr;
3683 void checkOfflineWork() const
3684 {
3685 if (offlineCheckpoint_) offlineCheckpoint_(offlineCheckpointContext_);
3686 }
3687 OnsetDetector<T> onset_;
3688
3689 double sampleRate_ = 44100.0;
3690 double frameRate_ = 200.0;
3691 int hop_ = 221;
3692
3693 // Resonator bank (built at prepare, read on the audio thread).
3694 int bankSize_ = 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_;
3700
3701 // Causal stream state (audio thread only).
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;
3711 // Causal beat clock (audio thread only; sized at prepare).
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;
3725 // Comb stage (audio thread only; sized at prepare).
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;
3731 int combSpan_ = 0;
3732 int64_t combWrite_ = 0;
3733 int combCountdown_ = kCombUpdateFrames;
3734 int combBin_ = -1;
3735 int combFollow_ = -1;
3736 bool combFresh_ = false;
3737 bool combAlike_ = false;
3738 WorkVector<double> regRing_;
3739 std::array<double, OnsetDetector<T>::kNumRegisters> regBaseline_ {};
3740
3741 // Offline scratch (analyze() and the offline session only).
3742 int64_t offlinePushed_ = 0;
3743 bool offlineOpen_ = false;
3744 WorkVector<double> env_;
3745 WorkVector<int64_t> envRef_;
3746 static constexpr int kRegisters = OnsetDetector<T>::kNumRegisters;
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;
3760
3761 // Published state.
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 };
3773};
3774
3775} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
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 > &deg, 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.
Definition AudioSpec.h:37
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
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].