From 78573bcc8e48f997d2bd2b4f3a4e680304dd6ca5 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:01:52 -0800 Subject: [PATCH 1/3] fix(audio): tone switches no longer freeze the engine; verdicts say if timed Tone switch stall: LoadPreset loads each NAM/IR slot by path and then applies its saved state, which loaded the SAME model a second time while the slot was live. The audio callback froze ~0.75 s on every switch (reproduced on ASIO: the renderer bus backed up to ~37k frames and then dropped), heard as a hard glitch plus a song-delay jump. State restore now skips a same-file reload (NAM and IR), and NAMProcessor::processBlock try-locks the model so the audio thread never waits on a swap. Verdict timing: a hit with no matched pick attack was stamped at the chart time with no flag, so consumers read a measured 0 ms. Verdicts now carry `timed` (true only when an onset was claimed), exposed by getNoteVerdicts and getSourceNoteVerdicts. Co-Authored-By: Claude Opus 5.5 --- src/audio/IRLoader.cpp | 5 ++- src/audio/NAMProcessor.cpp | 20 ++++++++++-- src/audio/NoteVerifier.cpp | 3 ++ src/audio/NoteVerifier.h | 6 ++++ src/audio/addon/DeviceBindings.cpp | 5 ++- tests/tone-load-no-stall.test.js | 51 ++++++++++++++++++++++++++++++ 6 files changed, 86 insertions(+), 4 deletions(-) create mode 100644 tests/tone-load-no-stall.test.js diff --git a/src/audio/IRLoader.cpp b/src/audio/IRLoader.cpp index 1c8d8b4..5aecf85 100644 --- a/src/audio/IRLoader.cpp +++ b/src/audio/IRLoader.cpp @@ -94,8 +94,11 @@ void IRLoader::setStateInformation(const void* data, int sizeInBytes) if (auto* obj = parsed.getDynamicObject()) { + // Same as NAMProcessor::setStateInformation: the preset already loaded + // this slot's IR by path, so only reload when the state names another. auto path = obj->getProperty("irPath").toString(); - if (path.isNotEmpty()) + if (path.isNotEmpty() + && ! (irLoaded.load() && juce::File(path) == juce::File(currentIRPath))) loadIR(juce::File(path)); if (obj->hasProperty("mix")) diff --git a/src/audio/NAMProcessor.cpp b/src/audio/NAMProcessor.cpp index 9ba8657..f7b555c 100644 --- a/src/audio/NAMProcessor.cpp +++ b/src/audio/NAMProcessor.cpp @@ -73,7 +73,16 @@ void NAMProcessor::releaseResources() void NAMProcessor::processBlock(juce::AudioBuffer& buffer, juce::MidiBuffer&) { #if SLOPSMITH_NAM_SUPPORT - const juce::ScopedLock sl(modelLock); + // Never block the audio thread on a model swap: a control thread holding + // modelLock (loadModel's swap, prepareToPlay's Reset + prewarm) would stall + // the whole device callback — guitar, song bus and all. Skip the block + // (silence) instead; a swap only ever holds the lock briefly. + const juce::ScopedTryLock sl(modelLock); + if (!sl.isLocked()) + { + buffer.clear(); + return; + } if (!model) return; @@ -150,8 +159,15 @@ void NAMProcessor::setStateInformation(const void* data, int sizeInBytes) if (auto* obj = parsed.getDynamicObject()) { + // A preset restores each NAM slot by path FIRST (LoadPreset), then + // applies this state — whose modelPath is normally that same file. + // Reloading it re-parsed and re-prewarmed the model a second time while + // the slot was already live in the chain, and the audio callback froze + // for ~0.75 s on every tone switch (measured on ASIO: the renderer bus + // backed up to ~37k frames, then dropped). Only load a DIFFERENT model. auto path = obj->getProperty("modelPath").toString(); - if (path.isNotEmpty()) + if (path.isNotEmpty() + && ! (modelLoaded.load() && juce::File(path) == juce::File(currentModelPath))) loadModel(juce::File(path)); if (obj->hasProperty("inputLevel")) diff --git a/src/audio/NoteVerifier.cpp b/src/audio/NoteVerifier.cpp index f79bdb5..a871087 100644 --- a/src/audio/NoteVerifier.cpp +++ b/src/audio/NoteVerifier.cpp @@ -377,6 +377,7 @@ void NoteVerifier::run() st.snr = st.bestSnr; double when = cn.t; + bool timed = false; if (! cn.ho && ! cn.po) { int best = -1; @@ -391,6 +392,7 @@ void NoteVerifier::run() { onsetLog[(size_t) best].claimed = true; when = onsetLog[(size_t) best].songTime; + timed = true; } } st.detectedSongTime = when; @@ -399,6 +401,7 @@ void NoteVerifier::run() v.id = cn.id; v.detected = true; v.detectedSongTime = when; + v.timed = timed; v.centsError = st.bestCents; v.snr = st.bestSnr; pending.push_back(v); diff --git a/src/audio/NoteVerifier.h b/src/audio/NoteVerifier.h index 421bc6b..f3c07be 100644 --- a/src/audio/NoteVerifier.h +++ b/src/audio/NoteVerifier.h @@ -87,6 +87,12 @@ class NoteVerifier std::string id; bool detected = false; double detectedSongTime = 0.0; // playhead at which the note was scored + // True only when detectedSongTime came from a real pick attack (an + // onset claimed from the onset log). A hit with no matching attack + // (legato, or an attack the flux detector missed: palm mutes, fast + // runs) is stamped at the chart time — "on time" by construction, not + // by measurement — so timing consumers (stats, Sync Lab) must skip it. + bool timed = false; float centsError = 0.0f; float snr = 0.0f; }; diff --git a/src/audio/addon/DeviceBindings.cpp b/src/audio/addon/DeviceBindings.cpp index 63f6656..827fb01 100644 --- a/src/audio/addon/DeviceBindings.cpp +++ b/src/audio/addon/DeviceBindings.cpp @@ -642,6 +642,7 @@ Napi::Value GetSourceNoteVerdicts(const Napi::CallbackInfo& info) entry.Set("id", v.id); entry.Set("detected", v.detected); entry.Set("detectedSongTime", v.detectedSongTime); + entry.Set("timed", v.timed); entry.Set("centsError", v.centsError); entry.Set("snr", v.snr); arr.Set((uint32_t) i, entry); @@ -812,7 +813,8 @@ Napi::Value SetSourceChart(const Napi::CallbackInfo& info) } // Drain the verdicts the NoteVerifier thread has finalized since the last -// call. Returns an array of { id, detected, detectedSongTime, centsError, snr }. +// call. Returns an array of { id, detected, detectedSongTime, timed, centsError, snr } +// (timed: detectedSongTime is a measured pick attack, not the chart time). // // Optionally also pushes the renderer's playhead: getNoteVerdicts(songTime, // playing). The plugin calls this once per detect tick, so folding the push in @@ -846,6 +848,7 @@ Napi::Value GetNoteVerdicts(const Napi::CallbackInfo& info) entry.Set("id", v.id); entry.Set("detected", v.detected); entry.Set("detectedSongTime", v.detectedSongTime); + entry.Set("timed", v.timed); entry.Set("centsError", v.centsError); entry.Set("snr", v.snr); arr.Set((uint32_t) i, entry); diff --git a/tests/tone-load-no-stall.test.js b/tests/tone-load-no-stall.test.js new file mode 100644 index 0000000..31e907c --- /dev/null +++ b/tests/tone-load-no-stall.test.js @@ -0,0 +1,51 @@ +// A tone switch froze the whole audio callback for ~0.75 s (measured on ASIO: the +// renderer bus backed up to ~37k frames, then dropped — heard as a hard glitch and a +// sync jump). LoadPreset loads each NAM/IR slot by path, then applies the slot's saved +// state, which re-loaded the SAME model a second time while the slot was live. These +// pin the fix (skip a same-file reload) and the audio-thread hardening (never block on +// the NAM model lock), plus the verdict `timed` flag timing consumers rely on. + +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const read = (p) => fs.readFileSync(path.join(__dirname, '..', p), 'utf8').replace(/\r\n/g, '\n'); + +function fnBody(src, signature) { + const start = src.indexOf(signature); + assert.ok(start !== -1, `${signature} not found`); + let i = src.indexOf('{', start + signature.length) + 1, depth = 1; + while (i < src.length && depth > 0) { if (src[i] === '{') depth++; else if (src[i] === '}') depth--; i++; } + return src.slice(start, i); +} + +test('NAM state restore skips reloading the model that is already loaded', () => { + const body = fnBody(read('src/audio/NAMProcessor.cpp'), 'void NAMProcessor::setStateInformation('); + assert.match(body, /modelLoaded\.load\(\) && juce::File\(path\) == juce::File\(currentModelPath\)/); + assert.match(body, /!\s*\(modelLoaded[\s\S]*?\)\)\s*loadModel\(/); +}); + +test('IR state restore skips reloading the IR that is already loaded', () => { + const body = fnBody(read('src/audio/IRLoader.cpp'), 'void IRLoader::setStateInformation('); + assert.match(body, /irLoaded\.load\(\) && juce::File\(path\) == juce::File\(currentIRPath\)/); +}); + +test('the NAM audio path never blocks on the model lock', () => { + const body = fnBody(read('src/audio/NAMProcessor.cpp'), 'void NAMProcessor::processBlock('); + assert.match(body, /ScopedTryLock sl\(modelLock\)/); + assert.doesNotMatch(body, /const juce::ScopedLock sl\(modelLock\)/); + assert.match(body, /if \(!sl\.isLocked\(\)\)\s*\{\s*buffer\.clear\(\);\s*return;/); +}); + +test('verdicts carry `timed`, true only when a pick attack was claimed', () => { + assert.match(read('src/audio/NoteVerifier.h'), /bool timed = false;/); + const cpp = read('src/audio/NoteVerifier.cpp'); + assert.match(cpp, /when = onsetLog\[\(size_t\) best\]\.songTime;\s*timed = true;/); + assert.match(cpp, /v\.timed = timed;/); + const bindings = read('src/audio/addon/DeviceBindings.cpp'); + assert.equal((bindings.match(/entry\.Set\("timed", v\.timed\);/g) || []).length, 2, + 'both getNoteVerdicts and getSourceNoteVerdicts expose it'); +}); From 208384882e47fe0ef81ca27c798035de23c90a8b Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Sat, 7 Nov 2026 02:01:00 -0800 Subject: [PATCH 2/3] fix(audio): heard clocks for song and guitar, measured not tuned Song (stems, ASIO/exclusive): a second renderer bus carries the song alone, each push anchored to its AudioContext frame; the output callback stamps its start, so getSongBusClock() names the context frame reaching the DAC (output latency included). Measured on ASIO4ALL: the heard delay is 26-58 ms depending on buffer size and bus fill (steady to +-1.5 ms over 3 min), where the old loopback path ran 130-180 ms and jumped 43 ms mid-run. Song (native backing): getBackingPosition() returns the heard position (the rendered block start reaches the DAC one output latency after its callback), not the end of the last rendered block. Guitar: every input block is stamped with its callback's start time; the verifier places each sample from that stamp minus the device's capture latency (reported input latency - one buffer, ASIO and JUCE WASAPI alike), on a playhead model that measures the playback rate (practice speeds were extrapolated at 1.0x) and filters IPC delay (fastest push wins). Rebuilt as the JUCE-free engine/PlayheadModel.h. Onset backdate: 525 samples (the detector's own lag, measured on synthetic picks with a known attack: tests/onset_lag), replacing a 50 ms value tuned from live medians that silently absorbed capture and display latency and was wrong at any other sample rate. Tests: engine_units renderer_bus (heard clock) + playhead_model (every buffer/latency/rate config lands < 1 ms), onset_lag, heard-clock-wiring. Co-Authored-By: Claude Opus 5.5 --- src/audio/AudioEngine.cpp | 123 ++++++++++++++- src/audio/AudioEngine.h | 44 +++++- src/audio/InputRingReader.h | 14 ++ src/audio/NodeAddon.cpp | 8 + src/audio/NoteVerifier.cpp | 67 ++++++--- src/audio/NoteVerifier.h | 7 + src/audio/OnsetDetector.cpp | 27 ++-- src/audio/OnsetDetector.h | 7 +- src/audio/SourceChain.cpp | 33 +++++ src/audio/SourceChain.h | 16 ++ src/audio/addon/Bindings.h | 4 + src/audio/addon/DeviceBindings.cpp | 70 +++++++++ src/audio/engine/BackingPlayer.h | 1 + src/audio/engine/PlayheadModel.h | 131 ++++++++++++++++ src/audio/engine/RendererBus.h | 111 +++++++++++++- src/main/audio-bridge.ts | 25 ++++ src/main/preload.ts | 15 ++ tests/CMakeLists.txt | 1 + tests/contracts/addon-exports.json | 4 + tests/contracts/ipc-channels.json | 4 + tests/contracts/preload-audio-api.json | 4 + tests/engine_units/CMakeLists.txt | 4 + tests/engine_units/playhead_model_test.cpp | 165 +++++++++++++++++++++ tests/engine_units/renderer_bus_test.cpp | 123 +++++++++++++++ tests/heard-clock-wiring.test.js | 75 ++++++++++ tests/onset_lag/CMakeLists.txt | 9 ++ tests/onset_lag/test.cpp | 155 +++++++++++++++++++ 27 files changed, 1205 insertions(+), 42 deletions(-) create mode 100644 src/audio/engine/PlayheadModel.h create mode 100644 tests/engine_units/playhead_model_test.cpp create mode 100644 tests/heard-clock-wiring.test.js create mode 100644 tests/onset_lag/CMakeLists.txt create mode 100644 tests/onset_lag/test.cpp diff --git a/src/audio/AudioEngine.cpp b/src/audio/AudioEngine.cpp index dc985b7..695688a 100644 --- a/src/audio/AudioEngine.cpp +++ b/src/audio/AudioEngine.cpp @@ -843,6 +843,11 @@ void AudioEngine::audioDeviceAboutToStart(juce::AudioIODevice* device) if (streamGuitarScratch.getNumSamples() < streamScratchCap) streamGuitarScratch.setSize(2, streamScratchCap, false, false, true); streamSink.prepareProducerScratch(); if (rendererBusPullScratch.getNumSamples() < streamScratchCap) rendererBusPullScratch.setSize(2, streamScratchCap, false, false, true); + if (songBusPullScratch.getNumSamples() < streamScratchCap) songBusPullScratch.setSize(2, streamScratchCap, false, false, true); + // Duplex: this device is the output too - its output latency places the + // heard clock. Split mode records the output device's in audioOutputAboutToStart. + if (duplexMode.load(std::memory_order_relaxed)) + outputLatencySamples.store(device->getOutputLatencyInSamples(), std::memory_order_relaxed); // Prepare each ACTIVE PRIMARY-device source's DSP and reset its rings for a // clean cold start. Inactive pooled chains stay unprepared (no threads). EXTRA- @@ -851,6 +856,22 @@ void AudioEngine::audioDeviceAboutToStart(juce::AudioIODevice* device) // primary's sample rate / block size (they run on a different hardware clock). pool.forEachActive([&](SourceChain& s) { if (s.getDeviceKey() == 0) s.prepare(sr, bs); }); + // Capture latency for verifier onset timing: how long before its block's + // callback the newest sample left the converter. Drivers report input + // latency for a block's FIRST sample (ASIO by spec, JUCE's WASAPI as + // stream latency + buffer), so subtract one buffer. Set on EVERY pooled + // chain (atomic store, any thread) so a source added later inherits it; + // an extra-device source adds its (extra − primary) delta on top via the + // verifier auto offset. Guitar timing then holds across drivers and + // buffer sizes instead of shifting with them. + { + const int inLat = device->getInputLatencyInSamples(); + const double capSec = (sr > 0.0) ? (double) juce::jmax(0, inLat - bs) / sr : 0.0; + pool.forEach([&](SourceChain& s) { s.setCaptureLatencySec(capSec); }); + if (slopsmith_vst_trace::isEnabled()) + fprintf(stderr, "[diag] capture latency: in=%d bs=%d -> %.2f ms\n", inLat, bs, capSec * 1000.0); + } + // Split mode preps the backing stretcher in audioOutputAboutToStart // instead — that callback owns the device the backing audio actually // plays on, and pulls from backingTransport at the output device's @@ -896,6 +917,7 @@ void AudioEngine::audioOutputAboutToStart(juce::AudioIODevice* device) fprintf(stderr, "[diag] audioOutputAboutToStart: dev='%s' sr=%.0f bs=%d\n", device->getName().toRawUTF8(), device->getCurrentSampleRate(), bs); outputBlockSize.store(bs, std::memory_order_relaxed); + outputLatencySamples.store(device->getOutputLatencyInSamples(), std::memory_order_relaxed); // The output callback isn't running yet for this device, so the trim state // (owned by that callback) is safe to reset here. outputRingTrim.prepare(device->getCurrentSampleRate()); @@ -976,6 +998,9 @@ void AudioEngine::audioDeviceIOCallbackWithContext( float* const* outputData, int numOutputChannels, int numSamples, const juce::AudioIODeviceCallbackContext&) { + // Heard-clock reference for the song bus (duplex: this callback is the output). + if (duplexMode.load(std::memory_order_relaxed)) + outputCallbackStartMs.store(juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed); // Flush denormals (FTZ/DAZ) for the ENTIRE realtime callback. The chain is // full of IIR state (NAM, cab IRs, VST amps/EQ/comp); after each note that // state decays toward zero and lands in the denormal range, where every op @@ -1069,6 +1094,7 @@ void AudioEngine::audioDeviceIOCallbackWithContext( if (sl.isLocked() && backing.readyLocked()) { const int outSamples = backing.renderBlockLocked(numSamples); + publishBackingStamp(outSamples); const float bVol = backingVolume.load(); streamBackingFrames = outSamples; streamBackingVol = bVol; streamBackingOn = true; const int mixChannels = juce::jmin(numOutputChannels, 2); @@ -1158,6 +1184,7 @@ void AudioEngine::audioOutputCallback(const float* const* /*inputData*/, int numOutputChannels, int numSamples) { + outputCallbackStartMs.store(juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed); // Split-mode output clock: this callback renders the backing track (phase // vocoder + loudness leveler) and mixes it with the chain output. Those // carry IIR/decay state too, so flush denormals here as well — the primary @@ -1281,6 +1308,7 @@ void AudioEngine::audioOutputCallback(const float* const* /*inputData*/, { // Shared with the duplex path so the two callbacks can't drift. const int backingOut = backing.renderBlockLocked(numSamples); + publishBackingStamp(backingOut); const float bVol = backingVolume.load(); streamBackingFrames = backingOut; streamBackingVol = bVol; streamBackingOn = true; // RMS, computed identically to the duplex path so getBackingLevel() @@ -1355,7 +1383,100 @@ int AudioEngine::pullRendererBus(juce::AudioBuffer& dest, int numSamples) // Cold start before about-to-start sized the scratch — skip, never alloc // on the RT thread (same rule as the stream scratches). if (dest.getNumSamples() < numSamples || dest.getNumChannels() < 2) return 0; - return rendererBus.pull(dest.getWritePointer(0), dest.getWritePointer(1), numSamples); + const int appFrames = rendererBus.pull(dest.getWritePointer(0), dest.getWritePointer(1), numSamples); + // The song bus mixes into the same block (both are pulled exactly once + // per output block). It stamps the heard clock with this callback's start. + if (songBusPullScratch.getNumSamples() < numSamples || songBusPullScratch.getNumChannels() < 2) + return appFrames; + const int songFrames = songBus.pull(songBusPullScratch.getWritePointer(0), + songBusPullScratch.getWritePointer(1), + numSamples, outputCallbackStartMs.load(std::memory_order_relaxed)); + if (songFrames <= 0) return appFrames; + for (int ch = 0; ch < 2; ++ch) + { + if (appFrames > 0) dest.addFrom(ch, 0, songBusPullScratch, ch, 0, songFrames); + else dest.copyFrom(ch, 0, songBusPullScratch, ch, 0, songFrames); + } + return numSamples; +} + +void AudioEngine::publishBackingStamp(int outSamples) +{ + const double sr = currentSampleRate.load(std::memory_order_relaxed); + const uint32_t seq = backingStampSeq.load(std::memory_order_relaxed); + backingStampSeq.store(seq + 1, std::memory_order_relaxed); + std::atomic_thread_fence(std::memory_order_release); + backingStampPos.store(backing.getPosition(), std::memory_order_relaxed); + backingStampBlockSec.store(sr > 0.0 ? (double) outSamples / sr : 0.0, std::memory_order_relaxed); + backingStampMs.store(outputCallbackStartMs.load(std::memory_order_relaxed), std::memory_order_relaxed); + backingStampRate.store(backing.getSpeed(), std::memory_order_relaxed); + backingStampSeq.store(seq + 2, std::memory_order_release); +} + +double AudioEngine::getBackingPosition() const +{ + const double raw = backing.getPosition(); + if (!backing.isPlaying()) return raw; + double pos = 0.0, blockSec = 0.0, ms = 0.0, rate = 1.0; + bool ok = false; + for (int attempt = 0; attempt < 8 && !ok; ++attempt) + { + const uint32_t s1 = backingStampSeq.load(std::memory_order_acquire); + if (s1 == 0 || (s1 & 1u)) continue; + pos = backingStampPos.load(std::memory_order_relaxed); + blockSec = backingStampBlockSec.load(std::memory_order_relaxed); + ms = backingStampMs.load(std::memory_order_relaxed); + rate = backingStampRate.load(std::memory_order_relaxed); + std::atomic_thread_fence(std::memory_order_acquire); + ok = backingStampSeq.load(std::memory_order_relaxed) == s1; + } + const double sr = currentSampleRate.load(std::memory_order_relaxed); + const double nowMs = juce::Time::getMillisecondCounterHiRes(); + if (!ok || !(sr > 0.0) || nowMs - ms > 250.0 || !(rate > 0.0)) return raw; + const double outLatSec = (double) outputLatencySamples.load(std::memory_order_relaxed) / sr; + const double heard = (pos - blockSec * rate) + ((nowMs - ms) / 1000.0 - outLatSec) * rate; + return juce::jmax(0.0, heard); +} + +bool AudioEngine::pushSongAudio(const float* interleavedLR, int frames, double sourceRate, double sourceStartFrame) +{ + return songBus.push(interleavedLR, frames, sourceRate, getCurrentSampleRate(), sourceStartFrame); +} + +AudioEngine::RendererBusMetrics AudioEngine::getSongBusMetrics() const +{ + const auto bm = songBus.metrics(); + RendererBusMetrics m; + m.pushedFrames = bm.pushedFrames; + m.consumedFrames = bm.consumedFrames; + m.underflowCount = bm.underflowCount; + m.overflowCount = bm.overflowCount; + m.fillFrames = bm.fillFrames; + m.capacityFrames = bm.capacityFrames; + m.enabled = bm.enabled; + return m; +} + +AudioEngine::SongBusClock AudioEngine::getSongBusClock() const +{ + SongBusClock c; + const double sr = currentSampleRate.load(std::memory_order_relaxed); + const auto h = songBus.heardClock(); + c.nowMs = juce::Time::getMillisecondCounterHiRes(); + c.fillFrames = songBus.metrics().fillFrames; + if (!h.valid || !(sr > 0.0)) return c; + const double outLatMs = 1000.0 * (double) outputLatencySamples.load(std::memory_order_relaxed) / sr; + // The block that started at h.sourceFrame was handed to the driver at + // h.wallMs and reaches the DAC outputLatency later; frames then follow at + // the device rate (h.srcPerDeviceFrame source frames each). An output + // callback that has stopped firing (> 250 ms) means nothing is playing. + const double sinceMs = c.nowMs - h.wallMs; + if (sinceMs > 250.0) return c; + c.valid = true; + c.outputLatencyMs = outLatMs; + c.sourceFramesPerSecond = sr * h.srcPerDeviceFrame; + c.heardSourceFrame = h.sourceFrame + (sinceMs - outLatMs) / 1000.0 * c.sourceFramesPerSecond; + return c; } AudioEngine::RendererBusMetrics AudioEngine::getRendererBusMetrics() const diff --git a/src/audio/AudioEngine.h b/src/audio/AudioEngine.h index 2271dc7..1edecb0 100644 --- a/src/audio/AudioEngine.h +++ b/src/audio/AudioEngine.h @@ -234,7 +234,11 @@ class AudioEngine : private juce::AudioIODeviceCallback void setBackingSpeed(double speed) { backing.setSpeed(speed); } // Non-blocking reads — never acquire the backing lock / block the audio callback bool isBackingPlaying() const { return backing.isPlaying(); } - double getBackingPosition() const { return backing.getPosition(); } + // The position being HEARD: the rendered position (end of the last + // block) moved back to where the speakers are now — the block started at + // the callback and reaches the DAC one output latency later. The raw + // render position ran ~1 block + output latency ahead of the sound. + double getBackingPosition() const; double getBackingDuration() const { return backing.getDuration(); } // Metering (read from any thread — atomic). Input level/peak are per-source @@ -283,6 +287,30 @@ class AudioEngine : private juce::AudioIODeviceCallback }; RendererBusMetrics getRendererBusMetrics() const; + // Song bus: a second renderer bus carrying ONLY the song (the stems graph, + // tapped directly in its own AudioContext). Each push carries the + // context frame of its first sample, so the engine can report exactly + // which song frame is reaching the speakers - the clock the highway must + // follow. The main renderer bus keeps carrying the rest of the app's audio + // (UI, previews, plugins) through the loopback capture, whose delay is + // unmeasurable (100-145 ms and step-changing, measured 2026-11-07). + void setSongBus(bool enabled, float gain) { songBus.setEnabled(enabled, gain); } + bool pushSongAudio(const float* interleavedLR, int frames, double sourceRate, double sourceStartFrame); + RendererBusMetrics getSongBusMetrics() const; + struct SongBusClock + { + bool valid = false; + // Source (AudioContext) frame reaching the speakers at wall time nowMs, + // output latency included; the producer's frame clock advances at + // sourceFramesPerSecond while playing. + double heardSourceFrame = 0.0; + double sourceFramesPerSecond = 0.0; + double nowMs = 0.0; + double outputLatencyMs = 0.0; + int fillFrames = 0; + }; + SongBusClock getSongBusClock() const; + float getStreamSinkLevel() const { return streamSink.getLevel(); } uint64_t getStreamUnderflowCount() const { return streamSink.getUnderflowCount(); } // Producer overflow (drop-oldest): the consumer fell a full ring behind and @@ -500,6 +528,20 @@ class AudioEngine : private juce::AudioIODeviceCallback // ── Renderer-audio bus (see engine/RendererBus.h — moved in TLC phase 2) slopsmith::RendererBus rendererBus; + slopsmith::RendererBus songBus; + juce::AudioBuffer songBusPullScratch; + // Wall time (juce hi-res ms) the live output callback started - the heard + // clock's reference: the block it fills reaches the DAC outputLatency later. + std::atomic outputCallbackStartMs{0.0}; // written by the output thread + // Backing heard stamp (seqlock): rendered position at the end of the last + // block, its length in seconds of output, the callback start, the rate. + void publishBackingStamp(int outSamples); + std::atomic backingStampSeq{0}; + std::atomic backingStampPos{0.0}; + std::atomic backingStampBlockSec{0.0}; + std::atomic backingStampMs{0.0}; + std::atomic backingStampRate{1.0}; + std::atomic outputLatencySamples{0}; // device-start threads -> any // Shared consumer step for the duplex and split output paths: drain one // block from the renderer-bus ring into `dest` (stereo, bus gain applied, // dest cleared first). Returns numSamples on success, 0 when gated diff --git a/src/audio/InputRingReader.h b/src/audio/InputRingReader.h index 5667441..1a9d144 100644 --- a/src/audio/InputRingReader.h +++ b/src/audio/InputRingReader.h @@ -26,4 +26,18 @@ class InputRingReader // The live device sample rate the ring samples were captured at. virtual double getCurrentSampleRate() const = 0; + + // Capture timing of the newest input block: `ringIndex` is the ring index + // just past its last sample, `wallMs` the juce hi-res millisecond counter + // when that block's device callback started. false until a block lands. + virtual bool getInputStamp(uint64_t& ringIndex, double& wallMs) const + { + (void) ringIndex; (void) wallMs; + return false; + } + + // How long before its block's callback the NEWEST sample of a block left + // the converter (seconds): the device's reported input latency minus one + // buffer (drivers report latency for the block's first sample). + virtual double getCaptureLatencySec() const { return 0.0; } }; diff --git a/src/audio/NodeAddon.cpp b/src/audio/NodeAddon.cpp index 4fd0037..fb6157d 100644 --- a/src/audio/NodeAddon.cpp +++ b/src/audio/NodeAddon.cpp @@ -64,6 +64,8 @@ using slopsmith::addon::GetPitchDetection; using slopsmith::addon::GetRawAudioFrame; using slopsmith::addon::GetRawPitchDetection; using slopsmith::addon::GetRendererBusMetrics; +using slopsmith::addon::GetSongBusMetrics; +using slopsmith::addon::GetSongBusClock; using slopsmith::addon::GetSampleRate; using slopsmith::addon::GetSampleRates; using slopsmith::addon::GetSourceLevels; @@ -86,6 +88,7 @@ using slopsmith::addon::LoadNoteModel; using slopsmith::addon::MoveProcessor; using slopsmith::addon::ProbeDeviceOptions; using slopsmith::addon::PushRendererAudio; +using slopsmith::addon::PushSongAudio; using slopsmith::addon::RemoveProcessor; using slopsmith::addon::RemoveSource; using slopsmith::addon::ResetPeaks; @@ -118,6 +121,7 @@ using slopsmith::addon::SetPan; using slopsmith::addon::SetParameter; using slopsmith::addon::SetPostGain; using slopsmith::addon::SetRendererBus; +using slopsmith::addon::SetSongBus; using slopsmith::addon::SetSlotState; using slopsmith::addon::SetSourceChart; using slopsmith::addon::SetSourceInputChannel; @@ -392,6 +396,10 @@ static Napi::Object InitModule(Napi::Env env, Napi::Object exports) exports.Set("setRendererBus", Napi::Function::New(env, SetRendererBus)); exports.Set("pushRendererAudio", Napi::Function::New(env, PushRendererAudio)); exports.Set("getRendererBusMetrics", Napi::Function::New(env, GetRendererBusMetrics)); + exports.Set("setSongBus", Napi::Function::New(env, SetSongBus)); + exports.Set("pushSongAudio", Napi::Function::New(env, PushSongAudio)); + exports.Set("getSongBusClock", Napi::Function::New(env, GetSongBusClock)); + exports.Set("getSongBusMetrics", Napi::Function::New(env, GetSongBusMetrics)); exports.Set("getStreamSinkLevel", Napi::Function::New(env, GetStreamSinkLevel)); exports.Set("isStreamOutputActive", Napi::Function::New(env, IsStreamOutputActive)); exports.Set("getStreamUnderflowCount", Napi::Function::New(env, GetStreamUnderflowCount)); diff --git a/src/audio/NoteVerifier.cpp b/src/audio/NoteVerifier.cpp index a871087..060e153 100644 --- a/src/audio/NoteVerifier.cpp +++ b/src/audio/NoteVerifier.cpp @@ -62,6 +62,7 @@ void NoteVerifier::setChart(const ChartUpdate& update) // stale position. lastPlayhead is worker-only but guarded by `lock` here. havePushedPlayhead.store(false); pushedPlaying = false; // plain bool, guarded by `lock` (held here) + playheadModel.reset(); lastPlayhead = 0.0; // Onset profile follows the arrangement; publish it BEFORE the reset flag // so the worker tick that observes onsetResetPending (and resets the @@ -85,6 +86,7 @@ void NoteVerifier::clearChart() // for the worker to score the next setPlayhead() against. havePushedPlayhead.store(false); pushedPlaying = false; + playheadModel.reset(); lastPlayhead = 0.0; onsetResetPending.store(true); } @@ -100,36 +102,33 @@ std::vector NoteVerifier::drainVerdicts() void NoteVerifier::setPlayhead(double songTime, bool playing) { { - // Publish the timing trio as one snapshot under `lock` so - // currentPlayhead() can never read a half-updated set. + // Updated under `lock` so playheadAt() never reads a half-updated model. const juce::ScopedLock sl(lock); - pushedReceiptMs = juce::Time::getMillisecondCounterHiRes(); + const double now = juce::Time::getMillisecondCounterHiRes(); // Shift by this source's capture-latency correction (0 on the primary). - pushedSongTime = songTime - playheadOffsetSec.load(std::memory_order_relaxed); + const double song = songTime - playheadOffsetSec.load(std::memory_order_relaxed); + playheadModel.push(song, playing, now); + pushedReceiptMs = now; + pushedSongTime = song; pushedPlaying = playing; } havePushedPlayhead.store(true); } -double NoteVerifier::currentPlayhead() const +double NoteVerifier::playheadAt(double wallMs) const { - double base, receiptMs; - bool playing; - { - const juce::ScopedLock sl(lock); - base = pushedSongTime; - receiptMs = pushedReceiptMs; - playing = pushedPlaying; - } - const double ageMs = juce::Time::getMillisecondCounterHiRes() - receiptMs; - if (ageMs > kPlayheadStaleMs) return base; // tick stopped — freeze - if (! playing) return base; // paused — hold - return base + ageMs / 1000.0; // playing — interpolate forward + const juce::ScopedLock sl(lock); + return playheadModel.songAt(wallMs, juce::Time::getMillisecondCounterHiRes()); // Note: after a stale freeze the playhead jumps forward on the first // fresh push; any note whose whole window was traversed during the freeze // finalizes as a miss next tick — correct, detection genuinely was down. } +double NoteVerifier::currentPlayhead() const +{ + return playheadAt(juce::Time::getMillisecondCounterHiRes()); +} + void NoteVerifier::prepare(double sampleRate, int /*blockSize*/) { // Match MlNoteDetector: a stop→start cycle tears the thread down before @@ -179,18 +178,36 @@ void NoteVerifier::run() appliedBassProfile = wantBass; } - // The playhead for this whole pass — interpolated from the last push so - // every note here is judged against the same chart position. - const double playhead = currentPlayhead(); + // The playhead for this whole pass, in AUDIO time: the song time at which + // the newest captured input sample left the converter — the callback's + // wall time on the playhead model, minus the device's capture latency. + // Every note here is judged against the same chart position, and the + // comb frame (the newest input) lines up with it. A stale stamp (input + // stalled) falls back to the wall-clock playhead so notes still finalize. + uint64_t stampIdx = 0; + double stampMs = 0.0; + const bool stamped = engine.getInputStamp(stampIdx, stampMs) + && juce::Time::getMillisecondCounterHiRes() - stampMs < 200.0; + const double captureLatency = engine.getCaptureLatencySec(); + double rate = 1.0; + { + const juce::ScopedLock sl(lock); + rate = playheadModel.getRate(); + } + const double stampSong = stamped ? playheadAt(stampMs) : 0.0; + const double playhead = stamped ? stampSong - captureLatency * rate : currentPlayhead(); double sr = engine.getCurrentSampleRate(); if (! std::isfinite(sr) || sr <= 0.0) sr = 48000.0; // ── Onset detection ───────────────────────────────────────────────────── // Feed every input sample captured since the last tick into the flux - // detector, and log each detected pick attack in song time. Input-ring - // index `w` ("now") corresponds to `playhead`; an earlier sample is - // proportionally earlier. + // detector, and log each detected pick attack in song time. With a capture + // stamp, ring index `stampIdx` corresponds to `playhead` exactly (both + // describe the newest captured sample) and any other sample is offset by + // its distance in samples — signed, a block that landed after the stamp + // was read sits later. Without one (no block yet), fall back to treating + // the ring head as "now". { std::vector fresh; const uint64_t w = engine.getInputSince(readCursor, fresh); @@ -202,7 +219,9 @@ void NoteVerifier::run() onsetDetector.process(fresh.data(), fresh.size(), firstIdx, onsets); for (const auto& o : onsets) { - const double songT = playhead - (double) (w - o.sampleIndex) / sr; + const double songT = stamped + ? slopsmith::onsetSongTime(stampSong, stampIdx, o.sampleIndex, sr, captureLatency, rate) + : playhead - (double) (w - o.sampleIndex) / sr * rate; onsetLog.push_back({ songT, false }); } } diff --git a/src/audio/NoteVerifier.h b/src/audio/NoteVerifier.h index f3c07be..e1d0da3 100644 --- a/src/audio/NoteVerifier.h +++ b/src/audio/NoteVerifier.h @@ -32,6 +32,7 @@ #include #include "ChordScorer.h" #include "OnsetDetector.h" +#include "engine/PlayheadModel.h" #include #include #include @@ -132,6 +133,9 @@ class NoteVerifier // song time, advanced by wall-clock elapsed since the push while playing. // Freezes on a stale push (renderer tick stopped) or when paused. double currentPlayhead() const; + // The same playhead model evaluated at any wall time (juce hi-res ms) — + // e.g. when an input block was captured. See setPlayhead for the model. + double playheadAt(double wallMs) const; // Per-note finalized state, parallel to `chart`. The harmonic-comb scores // every open-window note each tick; a note that is ever confirmed present @@ -200,6 +204,9 @@ class NoteVerifier double pushedSongTime = 0.0; double pushedReceiptMs = 0.0; // getMillisecondCounterHiRes() at push bool pushedPlaying = false; + // The song clock rebuilt from the pushes (rate-measured, IPC-delay + // filtered): see engine/PlayheadModel.h. Guarded by `lock`. + slopsmith::PlayheadModel playheadModel; // One-way latch (false→true on first push, reset by setChart). Read // lock-free at the top of run(); a slightly stale read is harmless. std::atomic havePushedPlayhead { false }; diff --git a/src/audio/OnsetDetector.cpp b/src/audio/OnsetDetector.cpp index d7b411d..6b11b00 100644 --- a/src/audio/OnsetDetector.cpp +++ b/src/audio/OnsetDetector.cpp @@ -16,12 +16,17 @@ constexpr int kFluxHistFrames = 32; constexpr float kGuitarThresholdK = 1.8f; // Minimum gap between onsets — a guitarist cannot pick faster than this. constexpr double kGuitarDebounceSeconds = 0.040; -// Net onset-timing calibration: the reported attack sits this far before the -// flux-peak frame's end. Absorbs the flux-peak-vs-attack lag (the transient -// takes time to fill the analysis window) plus residual chain latency. Tuned -// from the live timing-error median (~50 ms centres it). Stored in seconds and -// converted to samples per device rate so it holds at 44.1 kHz, 96 kHz, etc. -constexpr double kGuitarBackdateSeconds = 0.050; +// Onset backdate: the reported attack sits this far before the flux-peak +// frame's end — the detector's OWN lag (the transient has to reach the middle +// of the 1024-sample window before the flux peaks). Measured on synthetic +// picks with a known attack sample (tests/onset_lag): 497-566 samples at +// 44.1/48/96 kHz, any block size, soft or hard — a constant in SAMPLES, since +// the STFT is sized in samples. It is ONLY the detector lag: capture latency +// and the callback stamp are compensated in NoteVerifier, display latency is +// the player's A/V + guitar-latency calibration. (It was 50 ms, tuned from live +// medians — that silently absorbed ~8 ms of uncompensated capture latency and +// the tuner's own display latency, and was wrong at any other rate.) +constexpr int kGuitarBackdateSamples = 525; // Flux band: 70 Hz (below the lowest guitar fundamental's skirt) to 3 kHz — // picks carry strong broadband energy here; rumble/hiss outside only add noise. constexpr double kGuitarBandLoHz = 70.0; @@ -37,7 +42,7 @@ constexpr double kGuitarBandHiHz = 3000.0; // true attack — and should be calibrated against the bass bench. constexpr float kBassThresholdK = 1.4f; constexpr double kBassDebounceSeconds = 0.050; -constexpr double kBassBackdateSeconds = 0.060; +constexpr int kBassBackdateSamples = 680; constexpr double kBassBandLoHz = 40.0; constexpr double kBassBandHiHz = 2000.0; } // namespace @@ -74,7 +79,7 @@ void OnsetDetector::applyProfile() { thresholdK = kBassThresholdK; debounceSeconds = kBassDebounceSeconds; - backdateSeconds = kBassBackdateSeconds; + backdateSamples = kBassBackdateSamples; bandLoHz = kBassBandLoHz; bandHiHz = kBassBandHiHz; } @@ -82,7 +87,7 @@ void OnsetDetector::applyProfile() { thresholdK = kGuitarThresholdK; debounceSeconds = kGuitarDebounceSeconds; - backdateSeconds = kGuitarBackdateSeconds; + backdateSamples = kGuitarBackdateSamples; bandLoHz = kGuitarBandLoHz; bandHiHz = kGuitarBandHiHz; } @@ -91,8 +96,8 @@ void OnsetDetector::applyProfile() const double binHz = sampleRate / kWindow; loBin = std::max(1, (int) std::floor(bandLoHz / binHz)); hiBin = std::min(kWindow / 2, (int) std::ceil(bandHiHz / binHz)); - // Onset backdate in samples, so the timing calibration is rate-independent. - onsetBackdateSamples = (int) std::lround(backdateSeconds * sampleRate); + // The backdate is a detector property in samples (see kGuitarBackdateSamples). + onsetBackdateSamples = backdateSamples; } void OnsetDetector::setProfile(bool bass) diff --git a/src/audio/OnsetDetector.h b/src/audio/OnsetDetector.h index 6e52e74..6dd31e0 100644 --- a/src/audio/OnsetDetector.h +++ b/src/audio/OnsetDetector.h @@ -47,6 +47,9 @@ class OnsetDetector // process() (the NoteVerifier worker thread) — not concurrently with it. void setProfile(bool bass); + // The current report backdate, in samples (onset = flux-peak frame end - this). + int getBackdateSamples() const { return onsetBackdateSamples; } + // Feed contiguous samples whose first element sits at monotonic index // `firstSampleIndex`. Detected onsets are appended to `out`. A gap in the // index sequence (samples lost) resyncs and clears flux history. @@ -88,7 +91,7 @@ class OnsetDetector bool haveOnset = false; int loBin = 1, hiBin = 64; // flux band, set from the sample rate - int onsetBackdateSamples = 2400; // onset calibration in samples, per rate + int onsetBackdateSamples = 525; // = backdateSamples (rate-independent) // Profile-dependent tunables. prepare()/setProfile() write these from the // active profile, then derive loBin/hiBin/onsetBackdateSamples for the @@ -96,7 +99,7 @@ class OnsetDetector bool bassProfile = false; float thresholdK = 1.8f; // adaptive-threshold multiplier double debounceSeconds = 0.040; // min gap between onsets - double backdateSeconds = 0.050; // flux-peak-vs-attack + chain latency + int backdateSamples = 525; // detector lag: flux-peak frame end - attack double bandLoHz = 70.0; // flux band floor double bandHiHz = 3000.0; // flux band ceiling diff --git a/src/audio/SourceChain.cpp b/src/audio/SourceChain.cpp index 3b48661..76c22f2 100644 --- a/src/audio/SourceChain.cpp +++ b/src/audio/SourceChain.cpp @@ -23,6 +23,10 @@ void SourceChain::prepare(double sr, int blockSize) inputFrameRingWriteIndex.store(0, std::memory_order_relaxed); for (auto& slot : inputFrameRing) slot.store(0.0f, std::memory_order_relaxed); + // No capture stamp until the first block of this run lands. + inputStampSeq.store(0, std::memory_order_relaxed); + inputStampIndex.store(0, std::memory_order_relaxed); + inputStampWallMs.store(0.0, std::memory_order_relaxed); rawAudioRingWriteIndex.store(0, std::memory_order_relaxed); for (auto& slot : rawAudioRing) @@ -61,6 +65,9 @@ void SourceChain::processBlock(const float* const* inputData, int numInputChanne juce::AudioBuffer& buffer, int effectiveOutputChannels, int numSamples) noexcept { + // Wall time this block reached us — taken first, before any DSP, so the + // verifier can place every captured sample in song time (getInputStamp). + const double blockStartMs = juce::Time::getMillisecondCounterHiRes(); const float inGain = inputGain.load(); const int selectedCh = selectedInputChannel.load(); @@ -224,6 +231,14 @@ void SourceChain::processBlock(const float* const* inputData, int numInputChanne inputFrameRing[(w + (uint64_t) i) & (uint64_t) kMask] .store(monoSource[i], std::memory_order_relaxed); inputFrameRingWriteIndex.store(w + (uint64_t) numSamples, std::memory_order_release); + + // Publish the capture stamp for this block (seqlock, single writer). + const uint32_t seq = inputStampSeq.load(std::memory_order_relaxed); + inputStampSeq.store(seq + 1, std::memory_order_relaxed); + std::atomic_thread_fence(std::memory_order_release); + inputStampIndex.store(w + (uint64_t) numSamples, std::memory_order_relaxed); + inputStampWallMs.store(blockStartMs, std::memory_order_relaxed); + inputStampSeq.store(seq + 2, std::memory_order_release); } noiseGate.processBlock(buffer); @@ -362,6 +377,24 @@ std::vector SourceChain::getInputFrame(int numSamples) const return out; } +bool SourceChain::getInputStamp(uint64_t& ringIndex, double& wallMs) const +{ + for (int attempt = 0; attempt < 8; ++attempt) + { + const uint32_t s1 = inputStampSeq.load(std::memory_order_acquire); + if (s1 == 0) return false; // nothing captured this run yet + if (s1 & 1u) continue; // writer mid-update + const uint64_t idx = inputStampIndex.load(std::memory_order_relaxed); + const double ms = inputStampWallMs.load(std::memory_order_relaxed); + std::atomic_thread_fence(std::memory_order_acquire); + if (inputStampSeq.load(std::memory_order_relaxed) != s1) continue; + ringIndex = idx; + wallMs = ms; + return true; + } + return false; +} + uint64_t SourceChain::getInputSince(uint64_t fromIndex, std::vector& out) const { out.clear(); diff --git a/src/audio/SourceChain.h b/src/audio/SourceChain.h index 9e567d8..901772c 100644 --- a/src/audio/SourceChain.h +++ b/src/audio/SourceChain.h @@ -217,6 +217,15 @@ class SourceChain : public InputRingReader std::vector getInputFrame(int numSamples = 4096) const override; uint64_t getInputSince(uint64_t fromIndex, std::vector& out) const override; double getCurrentSampleRate() const override { return sampleRate.load(std::memory_order_relaxed); } + bool getInputStamp(uint64_t& ringIndex, double& wallMs) const override; + double getCaptureLatencySec() const override { return captureLatencySec.load(std::memory_order_relaxed); } + + // Device capture latency for verifier onset timing (see InputRingReader). + // Set from the device's reported input latency on every device start. + void setCaptureLatencySec(double seconds) + { + captureLatencySec.store(seconds > 0.0 && seconds < 1.0 ? seconds : 0.0, std::memory_order_relaxed); + } private: // ML-backed chord scoring against the MlNoteDetector's active-pitch set. @@ -265,6 +274,13 @@ class SourceChain : public InputRingReader std::array, kInputFrameRingCapacity> inputFrameRing{}; std::atomic inputFrameRingWriteIndex{0}; + // Capture stamp of the newest block (seqlock: odd seq = write in progress). + // Written by this source's device callback only; read by the verifier. + std::atomic inputStampSeq{0}; + std::atomic inputStampIndex{0}; + std::atomic inputStampWallMs{0.0}; + std::atomic captureLatencySec{0.0}; + static constexpr int kRawAudioRingCapacity = 16384; static_assert((kRawAudioRingCapacity & (kRawAudioRingCapacity - 1)) == 0, "kRawAudioRingCapacity must be a power of two"); diff --git a/src/audio/addon/Bindings.h b/src/audio/addon/Bindings.h index 78a4bdc..57a61b9 100644 --- a/src/audio/addon/Bindings.h +++ b/src/audio/addon/Bindings.h @@ -40,6 +40,8 @@ Napi::Value GetPitchDetection(const Napi::CallbackInfo& info); Napi::Value GetRawAudioFrame(const Napi::CallbackInfo& info); Napi::Value GetRawPitchDetection(const Napi::CallbackInfo& info); Napi::Value GetRendererBusMetrics(const Napi::CallbackInfo& info); +Napi::Value GetSongBusMetrics(const Napi::CallbackInfo& info); +Napi::Value GetSongBusClock(const Napi::CallbackInfo& info); Napi::Value GetSampleRate(const Napi::CallbackInfo& info); Napi::Value GetSampleRates(const Napi::CallbackInfo& info); Napi::Value GetSourceLevels(const Napi::CallbackInfo& info); @@ -62,6 +64,7 @@ Napi::Value LoadNoteModel(const Napi::CallbackInfo& info); Napi::Value MoveProcessor(const Napi::CallbackInfo& info); Napi::Value ProbeDeviceOptions(const Napi::CallbackInfo& info); Napi::Value PushRendererAudio(const Napi::CallbackInfo& info); +Napi::Value PushSongAudio(const Napi::CallbackInfo& info); Napi::Value RemoveProcessor(const Napi::CallbackInfo& info); Napi::Value RemoveSource(const Napi::CallbackInfo& info); Napi::Value ResetPeaks(const Napi::CallbackInfo& info); @@ -93,6 +96,7 @@ Napi::Value SetPan(const Napi::CallbackInfo& info); Napi::Value SetParameter(const Napi::CallbackInfo& info); Napi::Value SetPostGain(const Napi::CallbackInfo& info); Napi::Value SetRendererBus(const Napi::CallbackInfo& info); +Napi::Value SetSongBus(const Napi::CallbackInfo& info); Napi::Value SetSlotState(const Napi::CallbackInfo& info); Napi::Value SetSourceChart(const Napi::CallbackInfo& info); Napi::Value SetSourceInputChannel(const Napi::CallbackInfo& info); diff --git a/src/audio/addon/DeviceBindings.cpp b/src/audio/addon/DeviceBindings.cpp index 827fb01..1ff809d 100644 --- a/src/audio/addon/DeviceBindings.cpp +++ b/src/audio/addon/DeviceBindings.cpp @@ -468,6 +468,76 @@ Napi::Value GetRendererBusMetrics(const Napi::CallbackInfo& info) return obj; } +// setSongBus(enabled:boolean, gain:number) -- the song-only bus (see +// AudioEngine::setSongBus). +Napi::Value SetSongBus(const Napi::CallbackInfo& info) +{ + auto liveEngine = snapshotEngine(); + if (liveEngine && info.Length() >= 2 && info[0].IsBoolean() && info[1].IsNumber()) + liveEngine->setSongBus(info[0].As().Value(), + (float) info[1].As().DoubleValue()); + return info.Env().Undefined(); +} + +// pushSongAudio(interleavedLR:Float32Array, sourceRate:number, startFrame:number) -> boolean +// startFrame: the producer AudioContext frame of the chunk's first sample. +Napi::Value PushSongAudio(const Napi::CallbackInfo& info) +{ + auto env = info.Env(); + auto liveEngine = snapshotEngine(); + if (!liveEngine || info.Length() < 3 || !info[0].IsTypedArray() || !info[1].IsNumber() + || !info[2].IsNumber()) + return Napi::Boolean::New(env, false); + auto ta = info[0].As(); + if (ta.TypedArrayType() != napi_float32_array) + return Napi::Boolean::New(env, false); + auto f32 = info[0].As(); + const size_t samples = f32.ElementLength(); + if (samples < 2) + return Napi::Boolean::New(env, false); + const bool ok = liveEngine->pushSongAudio(f32.Data(), (int) (samples / 2), + info[1].As().DoubleValue(), info[2].As().DoubleValue()); + return Napi::Boolean::New(env, ok); +} + +// getSongBusClock() -> {valid, heardSourceFrame, sourceFramesPerSecond, +// outputLatencyMs, fillFrames, ageMs} +// heardSourceFrame is the producer-context frame reaching the speakers at +// the moment of this call (ageMs = 0 here; the renderer adds its IPC return). +Napi::Value GetSongBusClock(const Napi::CallbackInfo& info) +{ + auto env = info.Env(); + auto liveEngine = snapshotEngine(); + auto obj = Napi::Object::New(env); + obj.Set("valid", false); + if (!liveEngine) return obj; + const auto c = liveEngine->getSongBusClock(); + obj.Set("valid", c.valid); + obj.Set("heardSourceFrame", c.heardSourceFrame); + obj.Set("sourceFramesPerSecond", c.sourceFramesPerSecond); + obj.Set("outputLatencyMs", c.outputLatencyMs); + obj.Set("fillFrames", c.fillFrames); + return obj; +} + +// getSongBusMetrics() -> same shape as getRendererBusMetrics +Napi::Value GetSongBusMetrics(const Napi::CallbackInfo& info) +{ + auto env = info.Env(); + auto liveEngine = snapshotEngine(); + auto obj = Napi::Object::New(env); + if (!liveEngine) return obj; + const auto m = liveEngine->getSongBusMetrics(); + obj.Set("enabled", m.enabled); + obj.Set("fillFrames", m.fillFrames); + obj.Set("capacityFrames", m.capacityFrames); + obj.Set("pushedFrames", (double) m.pushedFrames); + obj.Set("consumedFrames", (double) m.consumedFrames); + obj.Set("underflowCount", (double) m.underflowCount); + obj.Set("overflowCount", (double) m.overflowCount); + return obj; +} + // getStreamSinkLevel() -> number (peak 0..1+) Napi::Value GetStreamSinkLevel(const Napi::CallbackInfo& info) { diff --git a/src/audio/engine/BackingPlayer.h b/src/audio/engine/BackingPlayer.h index 289cae1..b956032 100644 --- a/src/audio/engine/BackingPlayer.h +++ b/src/audio/engine/BackingPlayer.h @@ -51,6 +51,7 @@ class BackingPlayer bool isPlaying() const { return playing.load(); } double getPosition() const { return cachedPosition.load(); } double getDuration() const { return cachedDuration.load(); } + double getSpeed() const { return speed.load(); } // Re-prepare the transport + stretcher + buffers at a (new) device format. // Call from the about-to-start hook that owns backing playback (duplex: diff --git a/src/audio/engine/PlayheadModel.h b/src/audio/engine/PlayheadModel.h new file mode 100644 index 0000000..aa407cf --- /dev/null +++ b/src/audio/engine/PlayheadModel.h @@ -0,0 +1,131 @@ +#pragma once + +// PlayheadModel — the song clock the NoteVerifier scores against, rebuilt from +// the renderer's playhead pushes (one per detect tick, over IPC). +// +// While playing it is a line: song(t) = c + rate * t / 1000 (t = wall ms). +// rate is MEASURED from the pushes (slope over up to 2 s), so a practice +// speed (0.5x, 0.75x) is followed instead of assuming 1.0 — the old +// `base + age` extrapolation drifted (1 - rate) * push interval. +// c is the max over the last 300 ms of (song_i - rate * t_i): every +// push arrives LATE by its IPC delay, never early, so the fastest +// push is the truest one and a slow push can't drag the clock back. +// A seek / loop wrap / resume (a push off the line by > kJumpSeconds) starts +// a fresh line. Paused: the last pushed song time. A push stream that +// stopped (> kStaleMs) freezes the clock where it was at the last push. +// +// JUCE-free and lock-free by itself: the owner serialises calls (NoteVerifier +// holds its lock). Unit-tested in tests/engine_units/playhead_model_test.cpp. + +#include +#include +#include + +namespace slopsmith { + +class PlayheadModel +{ +public: + static constexpr double kJumpSeconds = 0.25; + static constexpr double kStaleMs = 1000.0; + static constexpr double kRateWindowMs = 2000.0; + static constexpr double kRateMinSpanMs = 300.0; + static constexpr double kOffsetWindowMs = 1000.0; + + void reset() { count = 0; playing = false; lastSong = 0.0; lastMs = 0.0; } + + void push(double song, bool isPlaying, double nowMs) + { + if (!isPlaying) + { + count = 0; + } + else + { + if (!playing || count == 0 || std::abs(song - (c + rate * nowMs / 1000.0)) > kJumpSeconds) + count = 0; + hist[head] = { song, nowMs }; + head = (head + 1) % kHistory; + if (count < kHistory) ++count; + + // Rate: least-squares slope over the pushes of the last 2 s (two + // endpoints alone would carry their IPC delays straight into it). + int n = 0; + double span = 0.0, sx = 0.0, sy = 0.0; + for (int k = 0; k < count; ++k) + { + const Sample& p = at(k); + if (nowMs - p.ms > kRateWindowMs) break; + span = nowMs - p.ms; + sx += p.ms - nowMs; sy += p.song - song; ++n; + } + if (n >= 3 && span >= kRateMinSpanMs) + { + const double mx = sx / n, my = sy / n; + double sxx = 0.0, sxy = 0.0; + for (int k = 0; k < n; ++k) + { + const Sample& p = at(k); + const double dx = (p.ms - nowMs) - mx, dy = (p.song - song) - my; + sxx += dx * dx; sxy += dx * dy; + } + double r = sxx > 0.0 ? 1000.0 * sxy / sxx : NAN; + // Speeds are set in whole percent (1.0, 0.75, 0.5 ...): an + // estimate within 0.3% of one IS that speed. Snapping removes + // the residual IPC-jitter slope error (0.1% ≈ 1 ms over 1 s). + const double snapped = std::round(r * 100.0) / 100.0; + if (std::abs(r - snapped) < 0.003) r = snapped; + if (std::isfinite(r)) rate = std::min(4.0, std::max(0.05, r)); + } + double best = -1e300; + for (int k = 0; k < count; ++k) + { + const Sample& p = at(k); + if (k > 0 && nowMs - p.ms > kOffsetWindowMs) break; + best = std::max(best, p.song - rate * p.ms / 1000.0); + } + c = best; + } + playing = isPlaying; + lastSong = song; + lastMs = nowMs; + } + + // The song time at wall time `wallMs` (which may be in the past, e.g. + // when an input block was captured), evaluated at wall time `nowMs`. + double songAt(double wallMs, double nowMs) const + { + if (!playing || count == 0) return lastSong; + if (nowMs - lastMs > kStaleMs) return c + rate * lastMs / 1000.0; + return c + rate * wallMs / 1000.0; + } + + double getRate() const { return rate; } + bool isPlaying() const { return playing; } + +private: + struct Sample { double song = 0.0; double ms = 0.0; }; + static constexpr int kHistory = 128; + const Sample& at(int k) const { return hist[(head - 1 - k + kHistory) % kHistory]; } + Sample hist[kHistory]; + int head = 0, count = 0; + double rate = 1.0, c = 0.0; + bool playing = false; + double lastSong = 0.0, lastMs = 0.0; +}; + +// Song time at which input-ring sample `sampleIndex` left the converter. +// The capture stamp says ring index `stampIndex` (just past the newest sample +// of a block) arrived with a callback that started at song time +// `stampSongTime`; that newest sample was captured `captureLatencySec` before +// the callback, and every other sample sits its distance in samples away +// (signed: a sample from a later block is later). The playback rate scales +// sample distance into song time. +inline double onsetSongTime(double stampSongTime, uint64_t stampIndex, uint64_t sampleIndex, + double sampleRate, double captureLatencySec, double rate) +{ + const double samplesBefore = (double) stampIndex - (double) sampleIndex; + return stampSongTime - (captureLatencySec + samplesBefore / sampleRate) * rate; +} + +} // namespace slopsmith diff --git a/src/audio/engine/RendererBus.h b/src/audio/engine/RendererBus.h index 2141de2..f4e1098 100644 --- a/src/audio/engine/RendererBus.h +++ b/src/audio/engine/RendererBus.h @@ -69,7 +69,13 @@ class RendererBus // `deviceRate` on the producer thread (fractional position + previous // frame carried across calls). Returns false when the bus is disabled or // the rates are unusable. Drop-oldest on overflow, counted consumer-side. - bool push(const float* interleavedLR, int frames, double sourceRate, double deviceRate) + // + // `sourceStartFrame` (optional, >= 0) is the producer clock's frame index + // of this chunk's first frame (an AudioWorklet's currentFrame). It anchors + // the heard clock: the consumer can then say which source frame is + // reaching the speakers (heardClock()). + bool push(const float* interleavedLR, int frames, double sourceRate, double deviceRate, + double sourceStartFrame = -1.0) { if (!busEnabled.load(std::memory_order_acquire)) return false; if (interleavedLR == nullptr || frames <= 0) return false; @@ -81,6 +87,8 @@ class RendererBus if (!std::isfinite(sourceRate) || sourceRate <= 0.0) sourceRate = deviceRate; uint64_t w = ring.beginWrite(); + const uint64_t chunkRingStart = w; + const double chunkSrcPos = srcPos; // source position of ring frame w, in chunk frames // Linear resample source→device rate on this (IPC) thread. `pos` is // the fractional read position into the incoming chunk; index -1 @@ -112,6 +120,11 @@ class RendererBus // Publish. Overflow (producer lapping the consumer) is handled // consumer-side with drop-oldest — only the consumer moves readIndex. + // Anchor BEFORE publishing the frames, so the consumer never reads + // a ring frame whose anchor it can't see yet. A source jump (a new + // context, a dropped worklet message) only affects frames past it. + if (written > 0 && std::isfinite(sourceStartFrame) && sourceStartFrame >= 0.0) + pushAnchor({ chunkRingStart, sourceStartFrame + chunkSrcPos, step }); ring.publish(w); pushedFrames.fetch_add(written, std::memory_order_relaxed); return true; @@ -120,7 +133,11 @@ class RendererBus // Drain one block into dl/dr (bus gain applied). Returns numSamples on // success, 0 when gated (disabled, priming, underflow). Single consumer — // call exactly once per output block. - int pull(float* dl, float* dr, int numSamples) + // + // `callbackStartMs` (optional, >= 0): wall time the output callback that + // will play this block started (any monotonic ms clock). With it, a + // successful pull publishes the heard-clock stamp (see heardClock()). + int pull(float* dl, float* dr, int numSamples, double callbackStartMs = -1.0) { // Consume a pending flush FIRST — even while disabled — so the tail // buffered before a disable is dropped by the ring's one legitimate @@ -136,7 +153,7 @@ class RendererBus if (target > ring.readIndex.load(std::memory_order_relaxed)) ring.commitRead(target); } - if (!busEnabled.load(std::memory_order_acquire)) return 0; + if (!busEnabled.load(std::memory_order_acquire)) { invalidateHeard(); return 0; } const uint64_t w = ring.writeIndex.load(std::memory_order_acquire); uint64_t r = ring.readIndex.load(std::memory_order_relaxed); if (w - r > (uint64_t) kFrames) @@ -167,6 +184,7 @@ class RendererBus if (avail < (uint64_t) kPrimeFrames) { ring.commitRead(r); + invalidateHeard(); return 0; } primed = true; @@ -178,6 +196,7 @@ class RendererBus primed = false; underflowCount.fetch_add(1, std::memory_order_relaxed); ring.commitRead(w); + invalidateHeard(); return 0; } @@ -191,9 +210,35 @@ class RendererBus } ring.commitRead(r + (uint64_t) numSamples); consumedFrames.fetch_add((uint64_t) numSamples, std::memory_order_relaxed); + if (callbackStartMs >= 0.0) publishHeard(r, callbackStartMs); return numSamples; } + // Heard clock: which producer (source) frame starts the block the latest + // output callback is playing, and when that callback started. A player + // adds the device's output latency: that frame reaches the speakers at + // wallMs + outputLatency, and later frames follow at `srcPerDeviceFrame` + // source frames per device frame. valid = false while the bus is gated + // (disabled / priming / underflow) or before any anchored push. + struct HeardClock { bool valid = false; double sourceFrame = 0.0; double wallMs = 0.0; double srcPerDeviceFrame = 1.0; }; + HeardClock heardClock() const + { + HeardClock h; + for (int attempt = 0; attempt < 8; ++attempt) + { + const uint32_t s1 = heardSeq.load(std::memory_order_acquire); + if (s1 & 1u) continue; + h.valid = heardValid.load(std::memory_order_relaxed); + h.sourceFrame = heardSrc.load(std::memory_order_relaxed); + h.wallMs = heardMs.load(std::memory_order_relaxed); + h.srcPerDeviceFrame = heardStep.load(std::memory_order_relaxed); + std::atomic_thread_fence(std::memory_order_acquire); + if (heardSeq.load(std::memory_order_relaxed) == s1) return h; + } + h.valid = false; + return h; + } + struct Metrics { uint64_t pushedFrames = 0, consumedFrames = 0, underflowCount = 0, overflowCount = 0; @@ -217,6 +262,66 @@ class RendererBus } private: + // -- Heard-clock anchors (producer -> consumer SPSC queue) -- + // One per anchored push: ring index of its first resampled frame, the + // source frame that ring frame holds, and the source step per ring frame. + struct Anchor { uint64_t ring = 0; double src = 0.0; double step = 1.0; }; + static constexpr int kAnchors = 1024; // ~10 s of 10 ms pushes + Anchor anchors[kAnchors]; + std::atomic anchorWrite{0}; // producer only + std::atomic anchorRead{0}; // consumer only + Anchor current{}; // consumer only + bool haveCurrent = false; // consumer only + + void pushAnchor(const Anchor& a) + { + const uint64_t aw = anchorWrite.load(std::memory_order_relaxed); + // Full queue (consumer stalled ~10 s): writing would overwrite an + // anchor the consumer may still read, so drop this one; its frames + // stay mapped by the previous anchor (exact unless the source jumped). + if (aw - anchorRead.load(std::memory_order_acquire) >= (uint64_t) kAnchors) return; + anchors[aw % kAnchors] = a; + anchorWrite.store(aw + 1, std::memory_order_release); + } + + void publishHeard(uint64_t readIndex, double callbackStartMs) + { + // Advance to the newest anchor at or before readIndex. + const uint64_t aw = anchorWrite.load(std::memory_order_acquire); + uint64_t ar = anchorRead.load(std::memory_order_relaxed); + while (ar < aw && anchors[ar % kAnchors].ring <= readIndex) + { + current = anchors[ar % kAnchors]; + haveCurrent = true; + ++ar; + } + anchorRead.store(ar, std::memory_order_release); + if (!haveCurrent) { invalidateHeard(); return; } + const double src = current.src + (double) (readIndex - current.ring) * current.step; + const uint32_t seq = heardSeq.load(std::memory_order_relaxed); + heardSeq.store(seq + 1, std::memory_order_relaxed); + std::atomic_thread_fence(std::memory_order_release); + heardSrc.store(src, std::memory_order_relaxed); + heardMs.store(callbackStartMs, std::memory_order_relaxed); + heardStep.store(current.step, std::memory_order_relaxed); + heardValid.store(true, std::memory_order_relaxed); + heardSeq.store(seq + 2, std::memory_order_release); + } + void invalidateHeard() + { + if (!heardValid.load(std::memory_order_relaxed)) return; + const uint32_t seq = heardSeq.load(std::memory_order_relaxed); + heardSeq.store(seq + 1, std::memory_order_relaxed); + std::atomic_thread_fence(std::memory_order_release); + heardValid.store(false, std::memory_order_relaxed); + heardSeq.store(seq + 2, std::memory_order_release); + } + std::atomic heardSeq{0}; + std::atomic heardValid{false}; + std::atomic heardSrc{0.0}; + std::atomic heardMs{0.0}; + std::atomic heardStep{1.0}; + PackedStereoRing ring; std::atomic pushedFrames{0}; std::atomic consumedFrames{0}; diff --git a/src/main/audio-bridge.ts b/src/main/audio-bridge.ts index 3a54e34..abb70c4 100644 --- a/src/main/audio-bridge.ts +++ b/src/main/audio-bridge.ts @@ -1010,6 +1010,31 @@ export function initAudioBridge(): void { return audio.getRendererBusMetrics(); }); + // ── Song bus: the song alone, frame-stamped, so the engine can report the + // song frame being heard (see AudioEngine::setSongBus). Same push model. + ipcMain.handle('audio:setSongBus', (_event, enabled: unknown, gain: unknown) => { + if (audio && typeof audio.setSongBus === 'function') { + const g = typeof gain === 'number' && Number.isFinite(gain) ? gain : 1.0; + audio.setSongBus(enabled === true, g); + } + }); + ipcMain.on('audio:pushSongAudio', (_event, chunk: unknown, sourceRate: unknown, startFrame: unknown) => { + if (audio && typeof audio.pushSongAudio === 'function' + && chunk instanceof Float32Array && chunk.length >= 2 + && typeof startFrame === 'number' && Number.isFinite(startFrame)) { + const rate = typeof sourceRate === 'number' && Number.isFinite(sourceRate) ? sourceRate : 0; + audio.pushSongAudio(chunk, rate, startFrame); + } + }); + ipcMain.handle('audio:getSongBusClock', () => { + if (!audio || typeof audio.getSongBusClock !== 'function') return null; + return audio.getSongBusClock(); + }); + ipcMain.handle('audio:getSongBusMetrics', () => { + if (!audio || typeof audio.getSongBusMetrics !== 'function') return null; + return audio.getSongBusMetrics(); + }); + ipcMain.handle('audio:getStreamSinkLevel', () => { if (!audio || typeof audio.getStreamSinkLevel !== 'function') return 0; return audio.getStreamSinkLevel(); diff --git a/src/main/preload.ts b/src/main/preload.ts index c4d8ce6..2677eaa 100644 --- a/src/main/preload.ts +++ b/src/main/preload.ts @@ -404,6 +404,21 @@ const feedBackDesktopApi = { pushedFrames: number; consumedFrames: number; underflowCount: number; overflowCount: number; } | null> => ipcRenderer.invoke('audio:getRendererBusMetrics'), + // Song bus (song audio only, frame-stamped): feeds the engine the + // stems graph directly and reports which song frame is being heard. + setSongBus: (enabled: boolean, gain: number): Promise => + ipcRenderer.invoke('audio:setSongBus', enabled, gain), + pushSongAudio: (interleavedLR: Float32Array, sourceRate: number, startFrame: number): void => + ipcRenderer.send('audio:pushSongAudio', interleavedLR, sourceRate, startFrame), + getSongBusClock: (): Promise<{ + valid: boolean; heardSourceFrame?: number; sourceFramesPerSecond?: number; + outputLatencyMs?: number; fillFrames?: number; + } | null> => ipcRenderer.invoke('audio:getSongBusClock'), + getSongBusMetrics: (): Promise<{ + enabled: boolean; fillFrames: number; capacityFrames: number; + pushedFrames: number; consumedFrames: number; + underflowCount: number; overflowCount: number; + } | null> => ipcRenderer.invoke('audio:getSongBusMetrics'), getStreamSinkLevel: (): Promise => ipcRenderer.invoke('audio:getStreamSinkLevel'), isStreamOutputActive: (): Promise => ipcRenderer.invoke('audio:isStreamOutputActive'), getStreamUnderflowCount: (): Promise => ipcRenderer.invoke('audio:getStreamUnderflowCount'), diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5143957..d41ed8b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -15,6 +15,7 @@ endif() add_subdirectory(audio_sanitize) add_subdirectory(engine_units) add_subdirectory(live_pitch) +add_subdirectory(onset_lag) # Note: enable_testing() lives in the top-level CMakeLists.txt — calling it # only here would register tests in build/tests/CTestTestfile.cmake but diff --git a/tests/contracts/addon-exports.json b/tests/contracts/addon-exports.json index 0cc2129..e87ef6b 100644 --- a/tests/contracts/addon-exports.json +++ b/tests/contracts/addon-exports.json @@ -29,6 +29,8 @@ "getRendererBusMetrics", "getSampleRate", "getSampleRates", + "getSongBusClock", + "getSongBusMetrics", "getSourceLevels", "getSourceNoteVerdicts", "getSourcePitchDetection", @@ -56,6 +58,7 @@ "openPluginEditor", "probeDeviceOptions", "pushRendererAudio", + "pushSongAudio", "releaseMonitorMuteHold", "removeProcessor", "removeSource", @@ -92,6 +95,7 @@ "setPostGain", "setRendererBus", "setSlotState", + "setSongBus", "setSourceChart", "setSourceInputChannel", "setSourceMonitorMute", diff --git a/tests/contracts/ipc-channels.json b/tests/contracts/ipc-channels.json index 7d46e67..5d6889d 100644 --- a/tests/contracts/ipc-channels.json +++ b/tests/contracts/ipc-channels.json @@ -31,6 +31,8 @@ "audio:getRendererBusMetrics", "audio:getSampleRate", "audio:getSampleRates", + "audio:getSongBusClock", + "audio:getSongBusMetrics", "audio:getSourceLevels", "audio:getSourceNoteVerdicts", "audio:getSourcePitchDetection", @@ -58,6 +60,7 @@ "audio:openPluginEditor", "audio:probeDeviceOptions", "audio:pushRendererAudio", + "audio:pushSongAudio", "audio:removeProcessor", "audio:removeSource", "audio:replaceIR", @@ -92,6 +95,7 @@ "audio:setPostGain", "audio:setRendererBus", "audio:setSlotState", + "audio:setSongBus", "audio:setSourceChart", "audio:setSourceInputChannel", "audio:setSourceMonitorMute", diff --git a/tests/contracts/preload-audio-api.json b/tests/contracts/preload-audio-api.json index f04feb5..c77018f 100644 --- a/tests/contracts/preload-audio-api.json +++ b/tests/contracts/preload-audio-api.json @@ -26,6 +26,8 @@ "getRendererBusMetrics", "getSampleRate", "getSampleRates", + "getSongBusClock", + "getSongBusMetrics", "getSourceLevels", "getSourceNoteVerdicts", "getSourcePitchDetection", @@ -53,6 +55,7 @@ "openPluginEditor", "probeDeviceOptions", "pushRendererAudio", + "pushSongAudio", "removeProcessor", "removeSource", "replaceIR", @@ -88,6 +91,7 @@ "setPostGain", "setRendererBus", "setSlotState", + "setSongBus", "setSourceChart", "setSourceInputChannel", "setSourceMonitorMute", diff --git a/tests/engine_units/CMakeLists.txt b/tests/engine_units/CMakeLists.txt index 7c11d54..d45d5b5 100644 --- a/tests/engine_units/CMakeLists.txt +++ b/tests/engine_units/CMakeLists.txt @@ -28,3 +28,7 @@ add_test(NAME rate_match COMMAND rate_match_test) add_executable(ring_residency_trim_test ring_residency_trim_test.cpp) target_compile_features(ring_residency_trim_test PRIVATE cxx_std_17) add_test(NAME ring_residency_trim COMMAND ring_residency_trim_test) + +add_executable(playhead_model_test playhead_model_test.cpp) +target_compile_features(playhead_model_test PRIVATE cxx_std_17) +add_test(NAME playhead_model COMMAND playhead_model_test) diff --git a/tests/engine_units/playhead_model_test.cpp b/tests/engine_units/playhead_model_test.cpp new file mode 100644 index 0000000..a4e76e0 --- /dev/null +++ b/tests/engine_units/playhead_model_test.cpp @@ -0,0 +1,165 @@ +// PlayheadModel + onsetSongTime (src/audio/engine/PlayheadModel.h): the clock +// note detection times pick attacks against. +// +// The end-to-end case simulates the whole capture path — a renderer pushing +// its playhead over a jittery IPC link, a device delivering input blocks with +// a reported input latency, the verifier stamping an attack — for every +// buffer size, driver latency and playback rate a player might use, and +// requires the attack to land within 1 ms of when it was really played. + +#include "../../src/audio/engine/PlayheadModel.h" + +#include +#include +#include +#include +#include +#include +#ifdef _MSC_VER +#include +#endif + +using slopsmith::PlayheadModel; +using slopsmith::onsetSongTime; + +static bool near(double a, double b, double tol) { return std::fabs(a - b) <= tol; } + +// Pushes arrive LATE by a random IPC delay; the model must not lag by it. +static void testFiltersIpcDelay() +{ + PlayheadModel m; + std::mt19937 rng(7); + std::uniform_real_distribution delay(0.0, 8.0); // ms + const double song0 = 12.0; + double worst = 0.0, warm = 0.0; + for (int i = 0; i < 400; ++i) + { + const double sendMs = 1000.0 + i * 16.7; + const double truth = song0 + (sendMs - 1000.0) / 1000.0; + const double recvMs = sendMs + delay(rng); + m.push(truth, true, recvMs); + const double probe = recvMs + 3.0; + const double want = song0 + (probe - 1000.0) / 1000.0; + const double err = std::fabs(m.songAt(probe, probe) - want); + if (i < 60) warm = std::max(warm, err); // the first second after a (re)start + else worst = std::max(worst, err); + } + std::printf(" ipc filter (0-8 ms jitter): first second %.3f ms, then worst %.3f ms\n", + warm * 1000.0, worst * 1000.0); + assert(warm < 0.008); // never worse than the jitter itself + assert(worst < 0.001); +} + +// Practice speed: the rate is measured, not assumed 1.0. +static void testFollowsPlaybackRate() +{ + for (double rate : { 0.5, 0.75, 1.0, 1.25 }) + { + PlayheadModel m; + for (int i = 0; i < 120; ++i) + { + const double ms = 5000.0 + i * 20.0; + m.push(30.0 + rate * (ms - 5000.0) / 1000.0, true, ms); + } + assert(near(m.getRate(), rate, 1e-9)); + const double probe = 5000.0 + 119 * 20.0 + 19.0; // just before the next push + assert(near(m.songAt(probe, probe), 30.0 + rate * (probe - 5000.0) / 1000.0, 1e-9)); + } +} + +static void testSeekPauseStale() +{ + PlayheadModel m; + for (int i = 0; i < 50; ++i) m.push(10.0 + i * 0.02, true, 1000.0 + i * 20.0); + // Seek forward 30 s: the old line is dropped at once. + m.push(40.0, true, 2000.0); + assert(near(m.songAt(2010.0, 2010.0), 40.01, 1e-9)); + // Loop wrap backwards. + m.push(5.0, true, 2020.0); + assert(near(m.songAt(2030.0, 2030.0), 5.01, 1e-9)); + // Pause holds the pushed time. + m.push(5.5, false, 2600.0); + assert(m.songAt(9000.0, 2700.0) == 5.5); + // Resume, then the pushes stop: frozen at the last push. + for (int i = 0; i < 20; ++i) m.push(5.5 + i * 0.02, true, 3000.0 + i * 20.0); + const double last = m.songAt(3380.0, 3380.0); + assert(near(m.songAt(3380.0, 3380.0 + 5000.0), last, 1e-9)); +} + +static void testOnsetSongTime() +{ + // Rate 1: a sample 480 frames before the stamp, 5 ms capture latency. + assert(near(onsetSongTime(10.0, 1000, 520, 48000.0, 0.005, 1.0), 10.0 - 0.005 - 0.010, 1e-12)); + // A sample from a block that landed after the stamp sits later. + assert(near(onsetSongTime(10.0, 1000, 1480, 48000.0, 0.0, 1.0), 10.010, 1e-12)); + // Half speed: wall time maps to half the song time. + assert(near(onsetSongTime(10.0, 1000, 520, 48000.0, 0.005, 0.5), 10.0 - 0.0075, 1e-12)); +} + +// End to end. For each config: the song plays at `rate`; the player strikes +// at song time T; the converter captures it at wall time t(T); the device +// delivers the block containing it to a callback that starts `inLat` after +// the block's FIRST sample was captured (the driver-reported input latency +// convention, ASIO and JUCE WASAPI alike); the verifier reads the stamp at a +// random later moment. The stamped onset must equal T. +static void testEndToEndCapture() +{ + std::mt19937 rng(11); + std::uniform_real_distribution ipc(0.0, 6.0), jitterCb(0.0, 1.5), u01(0.0, 1.0); + double worst = 0.0; + int cases = 0; + for (double sr : { 44100.0, 48000.0, 96000.0 }) + for (int bs : { 32, 64, 128, 256, 512, 1024, 2048 }) + for (int extraLat : { 0, 32, 272, 1000 }) // driver latency beyond one buffer + for (double rate : { 0.5, 0.8, 1.0, 1.2 }) + { + const int inLat = bs + extraLat; + const double capSec = (double) (inLat - bs) / sr; // what the engine computes + PlayheadModel m; + const double t0 = 10000.0, song0 = 20.0; + auto songAtWall = [&](double ms) { return song0 + rate * (ms - t0) / 1000.0; }; + // Renderer pushes for 2 s at ~60 Hz with IPC delay. + double ms = t0; + for (; ms < t0 + 2000.0; ms += 16.7) + m.push(songAtWall(ms), true, ms + ipc(rng)); + // Block k's first sample is captured at blockStart(k); its callback + // starts inLat later (plus scheduler jitter, which the stamp absorbs: + // the block's samples are still placed relative to the stamp). + const double blockMs = 1000.0 * bs / sr; + const uint64_t k = 50000; // arbitrary ring position + const double capFirst = t0 + 1500.0; // a block captured mid-run + const double callbackMs = capFirst + 1000.0 * inLat / sr; + (void) jitterCb; + const uint64_t stampIdx = k + (uint64_t) bs; // just past the block + const int at = (int) (u01(rng) * bs); // the strike's sample + const double strikeWall = capFirst + 1000.0 * at / sr; + const double T = songAtWall(strikeWall); + // A few more pushes land before the verifier tick reads the stamp. + for (int j = 0; j < 3; ++j, ms += 16.7) m.push(songAtWall(ms), true, ms + ipc(rng)); + const double nowMs = callbackMs + 4.0; + const double stampSong = m.songAt(callbackMs, nowMs); + const double got = onsetSongTime(stampSong, stampIdx, k + (uint64_t) at, sr, capSec, m.getRate()); + worst = std::max(worst, std::fabs(got - T)); + ++cases; + (void) blockMs; + } + std::printf(" end to end: %d configs, worst onset error %.3f ms\n", cases, worst * 1000.0); + assert(worst < 0.001); +} + +int main() +{ + std::setvbuf(stdout, nullptr, _IONBF, 0); +#ifdef _MSC_VER + _set_error_mode(_OUT_TO_STDERR); // a failed assert prints, no dialog + _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); + _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); +#endif + testFiltersIpcDelay(); + testFollowsPlaybackRate(); + testSeekPauseStale(); + testOnsetSongTime(); + testEndToEndCapture(); + std::puts("playhead_model: all cases passed"); + return 0; +} diff --git a/tests/engine_units/renderer_bus_test.cpp b/tests/engine_units/renderer_bus_test.cpp index b26f8f9..3d03b7b 100644 --- a/tests/engine_units/renderer_bus_test.cpp +++ b/tests/engine_units/renderer_bus_test.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include using slopsmith::RendererBus; @@ -220,6 +221,123 @@ static void testRejectsUnusableRates() assert(bus.metrics().pushedFrames > 0); } +// ── Heard clock (song bus) ────────────────────────────────────────────────── +// Each anchored push ties its first ring frame to a producer frame; each +// stamped pull publishes the producer frame that starts the block. + +// Equal rates: block start frame == the producer frame of that ring frame. +static void testHeardClockEqualRate() +{ + auto busOwner = std::make_unique(); // ~0.5 MB: keep it off the stack + RendererBus& bus = *busOwner; + bus.setEnabled(true, 1.0f); + assert(!bus.heardClock().valid); // nothing pulled yet + // Producer frames 1000.. in two contiguous chunks of 480. + const auto c1 = rampChunk(480, 0.0f, 1.0f); + const auto c2 = rampChunk(480, 480.0f, 1.0f); + assert(bus.push(c1.data(), 480, 48000.0, 48000.0, 1000.0)); + assert(bus.push(c2.data(), 480, 48000.0, 48000.0, 1480.0)); + std::vector dl(256), dr(256); + assert(bus.pull(dl.data(), dr.data(), 256, 5000.0) == 256); + auto h = bus.heardClock(); + assert(h.valid); + // Ring frame 0 holds producer frame 1000 (chunk position 0). + assert(std::fabs(h.sourceFrame - 1000.0) < 1e-9); + assert(h.wallMs == 5000.0 && h.srcPerDeviceFrame == 1.0); + // The block's samples are the producer's frames 1000.. (ramp value i). + assert(dl[0] == 0.0f && dl[255] == 255.0f); + assert(bus.pull(dl.data(), dr.data(), 256, 5005.3) == 256); + h = bus.heardClock(); + assert(std::fabs(h.sourceFrame - 1256.0) < 1e-9); + // Third block crosses into chunk 2's anchor (its first ring frame is the + // carried last frame of chunk 1 = producer 1479): still contiguous. + assert(bus.pull(dl.data(), dr.data(), 256, 5010.6) == 256); + h = bus.heardClock(); + assert(std::fabs(h.sourceFrame - 1512.0) < 1e-9); + // And the audio really is producer frame 1512 (ramp value 512). + assert(dl[0] == 512.0f); +} + +// A gap in producer frames (dropped message) is honoured exactly from the +// first ring frame of the new anchor on. +static void testHeardClockSourceJump() +{ + auto busOwner = std::make_unique(); // ~0.5 MB: keep it off the stack + RendererBus& bus = *busOwner; + bus.setEnabled(true, 1.0f); + const auto c = rampChunk(512, 0.0f, 1.0f); + assert(bus.push(c.data(), 512, 48000.0, 48000.0, 0.0)); + assert(bus.push(c.data(), 512, 48000.0, 48000.0, 10000.0)); // jumped + std::vector dl(512), dr(512); + assert(bus.pull(dl.data(), dr.data(), 512, 1.0) == 512); + assert(std::fabs(bus.heardClock().sourceFrame - 0.0) < 1e-9); + // Chunk 1 produced ring frames 0..510 (511 frames: the last frame is the + // carry), so ring 511 is chunk 2's carry slot, anchored at 10000 - 1. + assert(bus.pull(dl.data(), dr.data(), 256, 2.0) == 256); + assert(std::fabs(bus.heardClock().sourceFrame - (10000.0 - 1.0 + 1.0)) < 1e-9); +} + +// Underflow / disable invalidate the clock — nothing of the song is heard. +static void testHeardClockInvalidOnGap() +{ + auto busOwner = std::make_unique(); // ~0.5 MB: keep it off the stack + RendererBus& bus = *busOwner; + bus.setEnabled(true, 1.0f); + const auto c = rampChunk(600, 0.0f, 1.0f); + assert(bus.push(c.data(), 600, 48000.0, 48000.0, 0.0)); + std::vector dl(512), dr(512); + assert(bus.pull(dl.data(), dr.data(), 512, 1.0) == 512); + assert(bus.heardClock().valid); + assert(bus.pull(dl.data(), dr.data(), 512, 2.0) == 0); // underflow + assert(!bus.heardClock().valid); + assert(bus.push(c.data(), 600, 48000.0, 48000.0, 600.0)); + assert(bus.pull(dl.data(), dr.data(), 512, 3.0) == 512); + assert(bus.heardClock().valid); + bus.setEnabled(false, 0.0f); + assert(bus.pull(dl.data(), dr.data(), 512, 4.0) == 0); + assert(!bus.heardClock().valid); +} + +// Unanchored pushes (the app-audio bus) never produce a clock. +static void testHeardClockNeedsAnchor() +{ + auto busOwner = std::make_unique(); // ~0.5 MB: keep it off the stack + RendererBus& bus = *busOwner; + bus.setEnabled(true, 1.0f); + const auto c = rampChunk(1024, 0.0f, 1.0f); + assert(bus.push(c.data(), 1024, 48000.0, 48000.0)); + std::vector dl(512), dr(512); + assert(bus.pull(dl.data(), dr.data(), 512, 1.0) == 512); + assert(!bus.heardClock().valid); + // An unstamped pull never touches the clock either. + auto b2Owner = std::make_unique(); + RendererBus& b2 = *b2Owner; + b2.setEnabled(true, 1.0f); + assert(b2.push(c.data(), 1024, 48000.0, 48000.0, 0.0)); + assert(b2.pull(dl.data(), dr.data(), 512) == 512); + assert(!b2.heardClock().valid); +} + +// 44.1 k producer into a 48 k device: producer frames advance by 44100/48000 +// per device frame, and the published step says so. +static void testHeardClockResampled() +{ + auto busOwner = std::make_unique(); // ~0.5 MB: keep it off the stack + RendererBus& bus = *busOwner; + bus.setEnabled(true, 1.0f); + const auto c = rampChunk(2205, 0.0f, 1.0f); // ~2400 ring frames: under the fill clamp + assert(bus.push(c.data(), 2205, 44100.0, 48000.0, 0.0)); + std::vector dl(480), dr(480); + assert(bus.pull(dl.data(), dr.data(), 480, 1.0) == 480); + assert(bus.pull(dl.data(), dr.data(), 480, 11.0) == 480); + const auto h = bus.heardClock(); + assert(h.valid); + assert(std::fabs(h.srcPerDeviceFrame - 44100.0 / 48000.0) < 1e-12); + assert(std::fabs(h.sourceFrame - 480.0 * 44100.0 / 48000.0) < 1e-6); + // The audio at that block start is that producer position (ramp = frame). + assert(std::fabs(dl[0] - (float) (480.0 * 44100.0 / 48000.0)) < 1e-3); +} + int main() { testEqualRateBitExact(); @@ -232,6 +350,11 @@ int main() testGainApplied(); testFlushOnDisable(); testFlushSparesPostReEnableAudio(); + testHeardClockEqualRate(); + testHeardClockSourceJump(); + testHeardClockInvalidOnGap(); + testHeardClockNeedsAnchor(); + testHeardClockResampled(); std::puts("renderer_bus: all cases passed"); return 0; } diff --git a/tests/heard-clock-wiring.test.js b/tests/heard-clock-wiring.test.js new file mode 100644 index 0000000..bd909af --- /dev/null +++ b/tests/heard-clock-wiring.test.js @@ -0,0 +1,75 @@ +// Wiring for the heard clocks (source-level; the math itself is unit-tested in +// tests/engine_units — renderer_bus_test, playhead_model_test — and the onset +// lag in tests/onset_lag): +// - guitar: every input block is stamped at callback start, the verifier +// places each sample from that stamp minus the device's capture latency +// (reported input latency - one buffer), on a rate-measured playhead; +// - song (stems): a second, frame-stamped bus mixed into the output and +// stamped with the output callback's start, so getSongBusClock() names the +// context frame being heard (output latency included); +// - song (native backing): getBackingPosition() is the heard position. + +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const read = (p) => fs.readFileSync(path.join(__dirname, '..', p), 'latin1').replace(/\r\n/g, '\n'); + +test('capture latency = reported input latency minus one buffer, set on every pooled chain', () => { + const src = read('src/audio/AudioEngine.cpp'); + assert.match(src, /const int inLat = device->getInputLatencyInSamples\(\);\s*const double capSec = \(sr > 0\.0\) \? \(double\) juce::jmax\(0, inLat - bs\) \/ sr : 0\.0;\s*pool\.forEach\(\[&\]\(SourceChain& s\) \{ s\.setCaptureLatencySec\(capSec\); \}\);/); +}); + +test('each input block is stamped at callback start and published after its samples', () => { + const src = read('src/audio/SourceChain.cpp'); + const body = src.slice(src.indexOf('void SourceChain::processBlock(')); + const stamp = body.indexOf('const double blockStartMs = juce::Time::getMillisecondCounterHiRes();'); + const firstUse = body.indexOf('inputGain.load()'); + assert.ok(stamp !== -1 && stamp < firstUse, 'wall time taken before any DSP'); + assert.match(body, /inputFrameRingWriteIndex\.store\(w \+ \(uint64_t\) numSamples, std::memory_order_release\);\s*\n\s*\/\/ Publish the capture stamp[\s\S]{0,400}inputStampIndex\.store\(w \+ \(uint64_t\) numSamples/); +}); + +test('the verifier times onsets from the stamp, the capture latency and the measured rate', () => { + const src = read('src/audio/NoteVerifier.cpp'); + assert.match(src, /const double playhead = stamped \? stampSong - captureLatency \* rate : currentPlayhead\(\);/); + assert.match(src, /slopsmith::onsetSongTime\(stampSong, stampIdx, o\.sampleIndex, sr, captureLatency, rate\)/); + assert.match(src, /playheadModel\.push\(song, playing, now\);/); +}); + +test('onset backdate is the detector lag in samples, not a tuned time', () => { + const src = read('src/audio/OnsetDetector.cpp'); + assert.match(src, /constexpr int kGuitarBackdateSamples = 525;/); + assert.doesNotMatch(src, /BackdateSeconds/); +}); + +test('song bus: mixed into the same pull, stamped with the output callback start', () => { + const src = read('src/audio/AudioEngine.cpp'); + assert.match(src, /songBus\.pull\(songBusPullScratch\.getWritePointer\(0\),\s*songBusPullScratch\.getWritePointer\(1\),\s*numSamples, outputCallbackStartMs\.load\(std::memory_order_relaxed\)\);/); + // Both output callbacks stamp their start first thing. + assert.equal((src.match(/outputCallbackStartMs\.store\(juce::Time::getMillisecondCounterHiRes\(\)/g) || []).length, 2); + // The clock adds the device output latency. + assert.match(src, /c\.heardSourceFrame = h\.sourceFrame \+ \(sinceMs - outLatMs\) \/ 1000\.0 \* c\.sourceFramesPerSecond;/); + // Output latency is recorded on both start paths (duplex + split). + assert.equal((src.match(/outputLatencySamples\.store\(device->getOutputLatencyInSamples\(\)/g) || []).length, 2); +}); + +test('native backing reports the HEARD position', () => { + const src = read('src/audio/AudioEngine.cpp'); + assert.match(src, /const double heard = \(pos - blockSec \* rate\) \+ \(\(nowMs - ms\) \/ 1000\.0 - outLatSec\) \* rate;/); + assert.equal((src.match(/publishBackingStamp\((outSamples|backingOut)\);/g) || []).length, 2, 'both output paths stamp it'); +}); + +test('bridge + preload expose the song bus', () => { + const bridge = read('src/main/audio-bridge.ts'); + for (const ch of ['audio:setSongBus', 'audio:pushSongAudio', 'audio:getSongBusClock', 'audio:getSongBusMetrics']) + assert.ok(bridge.includes(`'${ch}'`), ch); + const preload = read('src/main/preload.ts'); + for (const k of ['setSongBus:', 'pushSongAudio:', 'getSongBusClock:', 'getSongBusMetrics:']) + assert.ok(preload.includes(k), k); + const addon = read('src/audio/NodeAddon.cpp'); + for (const k of ['setSongBus', 'pushSongAudio', 'getSongBusClock', 'getSongBusMetrics']) + assert.ok(addon.includes(`exports.Set("${k}"`), k); +}); diff --git a/tests/onset_lag/CMakeLists.txt b/tests/onset_lag/CMakeLists.txt new file mode 100644 index 0000000..842596f --- /dev/null +++ b/tests/onset_lag/CMakeLists.txt @@ -0,0 +1,9 @@ +# Onset timing ground truth: the real OnsetDetector on synthetic plucks with a +# known attack sample (see test.cpp). Needs juce_dsp for the FFT. +add_executable(onset_lag_test test.cpp ../../src/audio/OnsetDetector.cpp) +target_compile_features(onset_lag_test PRIVATE cxx_std_17) +target_link_libraries(onset_lag_test PRIVATE juce::juce_core juce::juce_dsp juce::juce_audio_basics juce::juce_audio_formats) +target_compile_definitions(onset_lag_test PRIVATE + JUCE_WEB_BROWSER=0 JUCE_USE_CURL=0 JUCE_STANDALONE_APPLICATION=1 + JUCE_DISABLE_ASSERTIONS=1 JUCE_LOG_ASSERTIONS=0 JUCE_MODAL_LOOPS_PERMITTED=0) +add_test(NAME onset_lag COMMAND onset_lag_test) diff --git a/tests/onset_lag/test.cpp b/tests/onset_lag/test.cpp new file mode 100644 index 0000000..897bff9 --- /dev/null +++ b/tests/onset_lag/test.cpp @@ -0,0 +1,155 @@ +// Onset timing ground truth for OnsetDetector (src/audio/OnsetDetector.*). +// +// Note detection times a hit by the pick attack the flux detector reports. The +// detector peaks some fixed distance after the real attack (its 1024-sample +// window has to fill), and `backdate` moves the report back by that much. This +// measures the real distance on synthetic plucks whose attack sample is known +// exactly — at every device rate, for soft and hard picking, from silence and +// over a ringing previous note — and fails if the reported attack is not +// centred on the true one. The rest of the timing chain (capture latency, +// callback stamp, playhead) is measured separately (engine_units +// playhead_model_test), so nothing here is tuned against live play. +// +// Usage: onset_lag_test run the checks +// onset_lag_test --report also print the per-case lags + +#include "../../src/audio/OnsetDetector.h" + +#include +#include +#include +#include +#include +#include + +namespace { + +struct Pluck { double freq; float amp; double riseMs; }; + +// Karplus-Strong string: a noise-burst excitation (the pick) into a damped +// delay line. `riseMs` shapes the excitation's onset (a pick ~0.3 ms, a +// fingerstyle bass pluck a few ms). The string keeps ringing until the next. +std::vector render(double sr, const std::vector>& plucks, size_t total, + float noiseFloor, unsigned seed) +{ + std::vector out(total, 0.0f); + std::mt19937 rng(seed); + std::uniform_real_distribution u(-1.0f, 1.0f); + for (size_t p = 0; p < plucks.size(); ++p) + { + const size_t at = plucks[p].first; + const Pluck pk = plucks[p].second; + const size_t end = (p + 1 < plucks.size()) ? plucks[p + 1].first + (size_t) (0.3 * sr) : total; + const int period = std::max(2, (int) std::lround(sr / pk.freq)); + std::vector line((size_t) period); + for (auto& v : line) v = u(rng); + const int rise = std::max(1, (int) std::lround(pk.riseMs * sr / 1000.0)); + size_t idx = 0; + for (size_t n = at; n < std::min(end, total); ++n, ++idx) + { + const size_t i = idx % (size_t) period, j = (idx + 1) % (size_t) period; + const float y = line[i]; + line[i] = 0.996f * 0.5f * (line[i] + line[j]); + const float env = idx < (size_t) rise ? (float) idx / (float) rise : 1.0f; + // The previous note is damped by the new pick (the player's hand). + out[n] = out[n] * (idx < (size_t) rise ? 1.0f - env * 0.7f : 0.3f) + pk.amp * env * y; + } + } + for (auto& v : out) v += noiseFloor * u(rng); + return out; +} + +struct Result { int cases = 0, missed = 0; double medianMs = 0, p10Ms = 0, p90Ms = 0, worstMs = 0; }; + +bool rawLag = false; + +Result measure(double sr, bool bass, float amp, double riseMs, bool overRinging, int blockSize, + bool report, const char* label) +{ + std::mt19937 rng(42); + std::uniform_real_distribution gap(0.18, 0.42), f(bass ? 41.0 : 82.0, bass ? 98.0 : 660.0); + std::vector> plucks; + double t = 0.5; + for (int i = 0; i < 60; ++i) + { + plucks.push_back({ (size_t) std::llround(t * sr), Pluck{ f(rng), amp, riseMs } }); + t += overRinging ? gap(rng) : gap(rng) + 0.9; // from silence: let it die first + } + const size_t total = (size_t) ((t + 1.0) * sr); + auto x = render(sr, plucks, total, 0.0005f, 7); + if (!overRinging) // decay to silence before each pick + for (size_t p = 0; p + 1 < plucks.size(); ++p) + for (size_t n = plucks[p].first + (size_t) (0.6 * sr); n < plucks[p + 1].first; ++n) x[n] *= 0.0f; + + OnsetDetector det; + det.prepare(sr); + det.setProfile(bass); + std::vector onsets; + for (size_t pos = 0; pos < total; pos += (size_t) blockSize) + { + const size_t n = std::min((size_t) blockSize, total - pos); + det.process(x.data() + pos, n, (uint64_t) pos, onsets); + } + std::vector lags; + int missed = 0; + for (const auto& p : plucks) + { + double best = 1e9; + for (const auto& o : onsets) + { + // rawLag: the detector's own lag (flux-peak frame end - attack), + // independent of the configured backdate. + const double reported = (double) o.sampleIndex + (rawLag ? (double) det.getBackdateSamples() : 0.0); + const double d = (reported - (double) p.first) / sr * 1000.0; + if (std::fabs(d) < std::fabs(best)) best = d; + } + if (std::fabs(best) > (rawLag ? 60.0 : 25.0)) { ++missed; continue; } + lags.push_back(best); + } + Result r; + r.cases = (int) plucks.size(); r.missed = missed; + std::sort(lags.begin(), lags.end()); + if (!lags.empty()) + { + r.medianMs = lags[lags.size() / 2]; + r.p10Ms = lags[lags.size() / 10]; + r.p90Ms = lags[lags.size() * 9 / 10]; + for (double v : lags) r.worstMs = std::max(r.worstMs, std::fabs(v)); + } + if (report) + std::printf(" %-34s sr=%6.0f bs=%4d median %+6.2f ms p10..p90 %+6.2f..%+6.2f |worst| %5.2f missed %d/%d\n", + label, sr, blockSize, r.medianMs, r.p10Ms, r.p90Ms, r.worstMs, r.missed, r.cases); + return r; +} + +} // namespace + +int main(int argc, char** argv) +{ + std::setvbuf(stdout, nullptr, _IONBF, 0); + const bool report = argc > 1 && (std::strcmp(argv[1], "--report") == 0 || std::strcmp(argv[1], "--raw") == 0); + rawLag = argc > 1 && std::strcmp(argv[1], "--raw") == 0; + int failures = 0; + auto check = [&](const Result& r, const char* what) + { + // Timing: centred within 3 ms (half the detector's 256-sample hop at + // 44.1 k is 2.9 ms, the resolution floor). Detection: at least 80 % of + // picks found (96 kHz over a ringing note is the weak case: the fixed + // 1024-sample window is only 10.7 ms there) — this test is about WHEN. + const bool ok = std::fabs(r.medianMs) <= 3.0 && r.missed <= r.cases / 5; + if (!ok) { std::printf("FAIL %s: median %+.2f ms, missed %d/%d\n", what, r.medianMs, r.missed, r.cases); ++failures; } + }; + for (double sr : { 44100.0, 48000.0, 96000.0 }) + for (int bs : { 64, 256, 1024 }) + { + check(measure(sr, false, 0.5f, 0.3, false, bs, report, "guitar hard pick, from silence"), "guitar hard/silence"); + check(measure(sr, false, 0.08f, 0.3, false, bs, report, "guitar soft pick, from silence"), "guitar soft/silence"); + check(measure(sr, false, 0.5f, 0.3, true, bs, report, "guitar pick over ringing note"), "guitar over ringing"); + // Bass (soft synthetic pluck) is reported, not asserted: its misses + // are detection sensitivity on this synthetic signal, not timing. + measure(sr, true, 0.5f, 2.0, true, bs, report, "bass pluck over ringing note (info)"); + } + if (failures) { std::printf("onset_lag: %d failure(s)\n", failures); return 1; } + std::puts("onset_lag: all cases centred"); + return 0; +} From e61088719cff2769470b235a887528438b462307 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Sat, 7 Nov 2026 03:11:24 -0800 Subject: [PATCH 3/3] test(audio): env-gated output->input loopback for end-to-end timing runs SLOPSMITH_TEST_LOOPBACK=1 (duplex devices only, read once at start) feeds the engine's own output back as its input, delayed by the device's reported output + input latency: an ideal cable from output jack to input. With the song's guitar stem soloed it measures the whole chain end to end. Measured: median hit timing +27/+28/+27/+28 ms at ASIO 128/256/512/1024 (the constant is the chart vs the stem) and +28..+33 ms at 0.5-0.8x. Off in normal runs. Co-Authored-By: Claude Opus 5.5 --- src/audio/AudioEngine.cpp | 43 ++++++++++++++++++++++++++++++++++++++- src/audio/AudioEngine.h | 13 ++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/src/audio/AudioEngine.cpp b/src/audio/AudioEngine.cpp index 695688a..c537c20 100644 --- a/src/audio/AudioEngine.cpp +++ b/src/audio/AudioEngine.cpp @@ -848,6 +848,18 @@ void AudioEngine::audioDeviceAboutToStart(juce::AudioIODevice* device) // heard clock. Split mode records the output device's in audioOutputAboutToStart. if (duplexMode.load(std::memory_order_relaxed)) outputLatencySamples.store(device->getOutputLatencyInSamples(), std::memory_order_relaxed); + if (testLoopback) + { + loopDelay = device->getOutputLatencyInSamples() + device->getInputLatencyInSamples(); + const int nCh = juce::jmax(2, device->getActiveInputChannels().countNumberOfSetBits()); + loopIn.assign((size_t) nCh, std::vector((size_t) juce::jmax(bs, 4096), 0.0f)); + loopInPtrs.assign((size_t) nCh, nullptr); + for (int c = 0; c < nCh; ++c) loopInPtrs[(size_t) c] = loopIn[(size_t) c].data(); + std::fill(loopRing.begin(), loopRing.end(), 0.0f); + loopWrite = 0; + fprintf(stderr, "[test-loopback] ON: delay %d samples (out %d + in %d), %d input ch\n", + loopDelay, device->getOutputLatencyInSamples(), device->getInputLatencyInSamples(), nCh); + } // Prepare each ACTIVE PRIMARY-device source's DSP and reset its rings for a // clean cold start. Inactive pooled chains stay unprepared (no threads). EXTRA- @@ -1072,7 +1084,24 @@ void AudioEngine::audioDeviceIOCallbackWithContext( // clock — never here. With no extra device every source is deviceKey 0, so // this is the single-device path unchanged. See mixSourcesForDevice for the // fast-path / multi-source rationale; it is shared with each extra callback. - pool.mixForDevice(0, inputData, numInputChannels, buffer, sourceMonitorScratch, + const float* const* chainInput = inputData; + int chainInputChannels = numInputChannels; + const bool loopNow = testLoopback && duplex && ! loopIn.empty() + && numSamples <= (int) loopIn[0].size() && numInputChannels <= (int) loopIn.size(); + if (loopNow) + { + // Input sample j of this callback left the "cable" loopDelay samples of + // output stream earlier (see AudioEngine.h). + for (int j = 0; j < numSamples; ++j) + { + const int64_t idx = (int64_t) loopWrite + j - loopDelay; + const float v = (idx >= 0 && idx < (int64_t) loopWrite) ? loopRing[(size_t) idx & (size_t) (kLoopRing - 1)] : 0.0f; + for (auto& ch : loopIn) ch[(size_t) j] = v; + } + chainInput = loopInPtrs.data(); + chainInputChannels = juce::jmax(1, numInputChannels); + } + pool.mixForDevice(0, chainInput, chainInputChannels, buffer, sourceMonitorScratch, effectiveOutputChannels, numSamples); // Duplex mixes backing + applies output gain + meters here. @@ -1151,6 +1180,18 @@ void AudioEngine::audioDeviceIOCallbackWithContext( currentOutputLevel.store(peak); float prevPeak = outputPeak.load(); if (peak > prevPeak) outputPeak.store(peak); + + if (loopNow) + { + const int nOut = juce::jmin(numOutputChannels, 2); + for (int j = 0; j < numSamples; ++j) + { + float m = 0.0f; + for (int ch = 0; ch < nOut; ++ch) m += buffer.getSample(ch, j); + loopRing[(size_t) (loopWrite + (uint64_t) j) & (size_t) (kLoopRing - 1)] = nOut > 0 ? m / (float) nOut : 0.0f; + } + loopWrite += (uint64_t) numSamples; + } } else { diff --git a/src/audio/AudioEngine.h b/src/audio/AudioEngine.h index 1edecb0..d9831d3 100644 --- a/src/audio/AudioEngine.h +++ b/src/audio/AudioEngine.h @@ -533,6 +533,19 @@ class AudioEngine : private juce::AudioIODeviceCallback // Wall time (juce hi-res ms) the live output callback started - the heard // clock's reference: the block it fills reaches the DAC outputLatency later. std::atomic outputCallbackStartMs{0.0}; // written by the output thread + // TEST ONLY (env SLOPSMITH_TEST_LOOPBACK=1, duplex devices): the input is + // replaced by the engine's own output delayed by the device's reported + // output + input latency -- an ideal cable from the output jack to the + // input. Lets the whole timing chain (song bus heard clock, capture stamp, + // onset detection, judgments) be measured end to end with the song's own + // guitar as the player. Off in normal runs: the flag is read once at start. + const bool testLoopback = [] { const char* v = std::getenv("SLOPSMITH_TEST_LOOPBACK"); return v != nullptr && v[0] == '1'; }(); + static constexpr int kLoopRing = 1 << 17; + std::vector loopRing = std::vector(testLoopback ? (size_t) kLoopRing : 0, 0.0f); + uint64_t loopWrite = 0; // audio thread only + int loopDelay = 0; // set at device start + std::vector> loopIn; // fake input channels + std::vector loopInPtrs; // Backing heard stamp (seqlock): rendered position at the end of the last // block, its length in seconds of output, the callback start, the rate. void publishBackingStamp(int outSamples);