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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 164 additions & 2 deletions src/audio/AudioEngine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -843,6 +843,23 @@ 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);
if (testLoopback)
{
loopDelay = device->getOutputLatencyInSamples() + device->getInputLatencyInSamples();
const int nCh = juce::jmax(2, device->getActiveInputChannels().countNumberOfSetBits());
loopIn.assign((size_t) nCh, std::vector<float>((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-
Expand All @@ -851,6 +868,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
Expand Down Expand Up @@ -896,6 +929,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());
Expand Down Expand Up @@ -976,6 +1010,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
Expand Down Expand Up @@ -1047,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.
Expand All @@ -1069,6 +1123,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);
Expand Down Expand Up @@ -1125,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
{
Expand Down Expand Up @@ -1158,6 +1225,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
Expand Down Expand Up @@ -1281,6 +1349,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()
Expand Down Expand Up @@ -1355,7 +1424,100 @@ int AudioEngine::pullRendererBus(juce::AudioBuffer<float>& 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
Expand Down
57 changes: 56 additions & 1 deletion src/audio/AudioEngine.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -500,6 +528,33 @@ 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<float> 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<double> 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<float> loopRing = std::vector<float>(testLoopback ? (size_t) kLoopRing : 0, 0.0f);
uint64_t loopWrite = 0; // audio thread only
int loopDelay = 0; // set at device start
std::vector<std::vector<float>> loopIn; // fake input channels
std::vector<const float*> 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);
std::atomic<uint32_t> backingStampSeq{0};
std::atomic<double> backingStampPos{0.0};
std::atomic<double> backingStampBlockSec{0.0};
std::atomic<double> backingStampMs{0.0};
std::atomic<double> backingStampRate{1.0};
std::atomic<int> 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
Expand Down
5 changes: 4 additions & 1 deletion src/audio/IRLoader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down
14 changes: 14 additions & 0 deletions src/audio/InputRingReader.h
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
};
Loading
Loading