Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 74 additions & 25 deletions engine/core/NativeMusicTempoMonitor.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ class MusicTempoEstimator final {
// transient detection or DAW-wide delay compensation.
std::uint64_t beatAnchorFrame=0,observationFrame=0;
bool locked=false;
// Last CONTROL-only scan's actual tempo-bin comparisons. Enables
// deterministic worst-case budget regression without wall-clock
// timing or instrumentation on the ASIO callback.
std::uint32_t scoringComparisons=0;
};
void reset() noexcept {
previous_=floor_=0.f;count_=write_=0;
Expand Down Expand Up @@ -85,30 +89,55 @@ class MusicTempoEstimator final {
// Retain the incumbent candidate's score so a transient half/double
// time accent cannot steal an already convincing song clock.
std::array<float,121> candidates{};
// CONTROL ONLY: bounded 121 candidates x 128 onsets. Emphasize
// one-beat matches; harmonics, half- and double-time are penalized.
for(int bpm=60;bpm<=180;++bpm) {
const float period=6000.f/static_cast<float>(bpm);
float score=0.f;
for(std::size_t j=1;j<count_;++j) {
const auto& later=at(j);
if(lastTick_-later.tick>1100)continue;
for(std::size_t i=j;i-->0;) {
const auto& earlier=at(i);
const float dt=static_cast<float>(later.tick-earlier.tick);
if(dt>period*3.08f)break;
const int cycles=static_cast<int>(std::lround(dt/period));
if(cycles<1||cycles>3)continue;
const float tolerance=std::max(1.4f,.022f*period*cycles);
const float error=std::abs(dt-period*cycles);
if(error>=tolerance)continue;
const float strength=std::sqrt(earlier.strength*later.strength);
score+=strength*(1.f-error/tolerance)/
(cycles==1?1.f:cycles==2?1.6f:2.25f);
// CONTROL ONLY, exact-score-preserving sparse candidate search.
// The former 121-BPM outer loop re-traversed the complete onset
// history for every candidate, adding unpredictable GUI timer work.
// Each onset pair can support only nearby BPM bins (<=3 periods).
// Enumerate each pair ONCE, derive the mathematically eligible BPM
// neighborhood, then use the original round/error/weight formula.
// Memory is the same 121-float fixed stack array; no heap, worker,
// allocations, callback scheduling or changed confidence threshold.
constexpr int minBpm=60,maxBpm=180;
constexpr float maxPairTicks=(6000.f/minBpm)*3.08f;
std::uint32_t compared=0;
for(std::size_t j=1;j<count_;++j) {
const auto& later=at(j);
if(lastTick_-later.tick>1100)continue;
for(std::size_t i=j;i-->0;) {
const auto& earlier=at(i);
const float dt=static_cast<float>(later.tick-earlier.tick);
if(dt>maxPairTicks)break;
const float strength=std::sqrt(earlier.strength*later.strength);
for(int cycles=1;cycles<=3;++cycles) {
const float targetBpm=6000.f*cycles/dt;
// The original tolerance is max(1.4 ticks, 2.2% of
// a multi-beat period). Within 60–180 BPM, its largest
// possible candidate separation is <10 BPM. +/-12
// therefore cannot discard an original valid score.
const int near=static_cast<int>(std::lround(targetBpm));
const int lo=std::max(minBpm,near-12);
const int hi=std::min(maxBpm,near+12);
for(int bpm=lo;bpm<=hi;++bpm) {
++compared;
const float period=6000.f/static_cast<float>(bpm);
if(dt>period*3.08f)continue;
if(static_cast<int>(std::lround(dt/period))!=cycles)continue;
const float tolerance=std::max(1.4f,.022f*period*cycles);
const float error=std::abs(dt-period*cycles);
if(error>=tolerance)continue;
candidates[static_cast<std::size_t>(bpm-minBpm)]+=
strength*(1.f-error/tolerance)/
(cycles==1?1.f:cycles==2?1.6f:2.25f);
}
}
}
candidates[static_cast<std::size_t>(bpm-60)]=score;
if(score>bestScore) {bestScore=score;bestBpm=bpm;}
}
result_.scoringComparisons=compared;
// Preserve deterministic ascending-BPM tie-breaking and the old
// half/double-time decision semantics exactly.
for(int bpm=minBpm;bpm<=maxBpm;++bpm) {
const float score=candidates[static_cast<std::size_t>(bpm-minBpm)];
if(score>bestScore){bestScore=score;bestBpm=bpm;}
}
if(bestBpm==0 || bestScore<2.0f)return;
if(result_.locked) {
Expand All @@ -129,10 +158,30 @@ class MusicTempoEstimator final {
if(result_.locked && std::abs(bestBpm-result_.bpm)>5.f &&
stableCount_<6)return;
if(stableCount_<3)return;
result_.bpm=static_cast<float>(candidateBpm_);
result_.confidence=std::clamp(bestScore/
// Octave hysteresis can deliberately select a weaker incumbent.
// Confidence MUST describe that selected BPM, not an alternate
// double/half-time peak that we explicitly rejected.
const float acceptedScore=
candidates[static_cast<std::size_t>(bestBpm-60)];
const float confidence=std::clamp(acceptedScore/
static_cast<float>(std::max<std::size_t>(7,count_))*.9f,0.f,1.f);
if(result_.confidence<.28f)return;
if(confidence<.28f) {
// A busy but low-confidence groove is NOT a stable beat. The
// previous code kept locked=true (and old beat-phase) while
// overwriting BPM, which could shift the next singer echo on an
// untrusted grid. Fail closed to accepted Manual/TAP, then demand
// three fresh good estimates before reacquiring Auto.
result_.confidence=confidence;
result_.locked=false;
result_.phaseLocked=false;
result_.phaseConfidence=0.f;
result_.beatAnchorFrame=0;
result_.beatAnchorTick=0;
stableCount_=candidateBpm_=0;
return;
}
result_.bpm=static_cast<float>(bestBpm);
result_.confidence=confidence;
// CONTROL: phase is a separate decision from the BPM estimate.
// Search the bounded onset set for the strongest coherent pulse
// lattice, not simply the most recent loud snare / clap.
Expand Down
35 changes: 35 additions & 0 deletions tests/native_music_tempo_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ static void lockTempo(int bpm,bool hats=false) {
check(state.tempo.locked);
check(std::abs(state.tempo.bpm-bpm)<=3.1f);
check(state.tempo.confidence>=.28f);
// Sparse pair scoring uses only qualifying BPM neighborhoods instead
// of 121 complete rescans. This is a deterministic, hardware-neutral
// CONTROL timer budget, NOT a wall-clock benchmark.
check(state.tempo.scoringComparisons>0);
check(state.tempo.scoringComparisons<120000);
check(state.tempo.phaseLocked && state.tempo.phaseConfidence>=.50f);
check(state.tempo.beatAnchorTick>0);
check(state.tempo.beatAnchorFrame>0);
Expand Down Expand Up @@ -96,16 +101,42 @@ static void harmonicAndPhaseAmbiguity() {
for(int i=1150;i<2450;++i)groove(i,.78f);
auto ambiguous=tap.poll(7,13);
check(ambiguous.tempo.locked);
check(ambiguous.tempo.scoringComparisons>0);
check(ambiguous.tempo.scoringComparisons<120000);
check(std::abs(ambiguous.tempo.bpm-120.f)<=3.f);
check(!ambiguous.tempo.phaseLocked);
// The music clears; the true quarter-note lattice should recover.
for(int i=2450;i<3650;++i)groove(i,.035f);
auto recovered=tap.poll(7,13);
check(recovered.tempo.locked);
check(recovered.tempo.scoringComparisons>0);
check(recovered.tempo.scoringComparisons<120000);
check(std::abs(recovered.tempo.bpm-120.f)<=3.f);
check(recovered.tempo.phaseLocked);
check(recovered.dropped==0);
}
// A formerly locked backing can switch to densely accented but weak
// percussion. This is enough rhythmic activity to score a candidate, yet
// NOT enough evidence to keep the old beat grid or invent a new one.
static void weakBusyGrooveMustReleaseBeatGrid() {
NativeMusicTempoMonitor tap;
check(tap.select(ChannelId{301},7,13,10000));
for(int n=0;n<1100;++n)renderWindow(tap,n,50,.78f);
auto locked=tap.poll(7,13);
check(locked.tempo.locked&&locked.tempo.phaseLocked);
for(int n=1100;n<2350;++n)renderWindow(tap,n,8,.10f);
const auto ambiguous=tap.poll(7,13);
check(ambiguous.active);
check(!ambiguous.tempo.locked && !ambiguous.tempo.phaseLocked);
check(ambiguous.tempo.confidence<.28f);
check(ambiguous.dropped==0);
// Once clear music returns the phase can be acquired again.
for(int n=2350;n<3550;++n)renderWindow(tap,n,50,.78f);
const auto recovered=tap.poll(7,13);
check(recovered.tempo.locked &&
std::abs(recovered.tempo.bpm-120.f)<=3.f);
check(recovered.tempo.phaseLocked);
}
static void steadyPadIsNotAClock() {
NativeMusicTempoMonitor tap;
check(tap.select(ChannelId{301},7,13,10000));
Expand All @@ -119,6 +150,9 @@ static void steadyPadIsNotAClock() {
}
const auto state=tap.poll(7,13);
check(!state.tempo.locked);
// A sustained pad is not evidence of rhythm. It cannot trigger a
// high-cost candidate scan simply because PCM keeps arriving.
check(state.tempo.scoringComparisons==0);
}
static void failClosed() {
NativeMusicTempoMonitor tap;
Expand Down Expand Up @@ -248,6 +282,7 @@ int main() {
lockTempo(160);
lockTempo(120,true);
harmonicAndPhaseAmbiguity();
weakBusyGrooveMustReleaseBeatGrid();
steadyPadIsNotAClock();
failClosed();
callbackClockEpochAndNestedScope();
Expand Down