From 68477d542648f614ecc5aae8cf56f0a05f737183 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 12:04:26 +0700 Subject: [PATCH 1/3] feat(p25): prepared native VST3 preset graph, callback-boundary fade handoff, deferred retirement and stress tests --- .github/workflows/p1-windows.yml | 7 +- CMakeLists.txt | 2 +- README.md | 6 + docs/P25_LIVE_GRAPH_HANDOFF.md | 32 +++++ src/LiveAudioEngine.h | 222 +++++++++++++++++++---------- src/LiveGraphHandoff.h | 85 +++++++++++ src/Main.cpp | 29 +++- tests/live_graph_contract_test.mjs | 34 +++++ tests/realtime_control_test.cpp | 57 ++++++++ web/bridge.js | 12 +- 10 files changed, 397 insertions(+), 89 deletions(-) create mode 100644 docs/P25_LIVE_GRAPH_HANDOFF.md create mode 100644 src/LiveGraphHandoff.h create mode 100644 tests/live_graph_contract_test.mjs diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 77249dfff..1d49be58a 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -1,7 +1,7 @@ name: Windows Native VST3 Host on: push: - branches: [ main, feature/p1-first-sound-windows, feature/p2-native-vst-catalog-fx-rack, feature/p2-daw-workflow-progress, fix/p2-native-output-monitor-diagnostics, fix/p2-realtime-glitch-telemetry-latest-gui, fix/p2-truthful-meter-pan-fx-toggle, feature/p2-native-state-presets, fix/p2-fabfilter-add-workflow ] + branches: [ main, feature/p1-first-sound-windows, feature/p2-native-vst-catalog-fx-rack, feature/p2-daw-workflow-progress, fix/p2-native-output-monitor-diagnostics, fix/p2-realtime-glitch-telemetry-latest-gui, fix/p2-truthful-meter-pan-fx-toggle, feature/p2-native-state-presets, fix/p2-fabfilter-add-workflow, feature/p25-live-preset-graph-swap ] pull_request: workflow_dispatch: @@ -36,6 +36,7 @@ jobs: node --test tests/native_ui_contract_test.mjs node --test tests/native_preset_contract_test.mjs node --test tests/fx_add_contract_test.mjs + node --test tests/live_graph_contract_test.mjs - name: Configure Windows x64 shell: pwsh run: > @@ -55,13 +56,13 @@ jobs: Where-Object { $_.Name -like "*AR*Mix*" -and $_.FullName -match 'Release' } | Select-Object -First 1 if (-not $exe) { throw "ARMixConsole EXE not found" } - Copy-Item $exe.FullName "dist/ArSonMix-P2-FX-Compatibility.exe" + Copy-Item $exe.FullName "dist/ArSonMix-P2.5-Live-Recall.exe" Copy-Item README.md "dist/README.md" "P2 experimental: audio routes automatically; use headphones at low level. Only Channel 1 is native. Other strips are inactive previews." | Out-File -FilePath dist/FIRST_SOUND_README.txt -Encoding utf8 - uses: actions/upload-artifact@v4 with: - name: ArSonMix-P2-FX-Compatibility-Windows-x64 + name: ArSonMix-P2.5-Live-Recall-Windows-x64 path: dist/ if-no-files-found: error retention-days: 14 diff --git a/CMakeLists.txt b/CMakeLists.txt index c0d35805a..6a19462de 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,7 +19,7 @@ juce_add_gui_app(ARMixConsole juce_add_binary_data(ARMixAssets SOURCES web/index.html web/styles.css web/app.js web/bridge.js web/monitor.js) -target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/PluginCatalog.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/VstBusLayout.h) +target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/PluginCatalog.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/VstBusLayout.h src/LiveGraphHandoff.h) target_compile_definitions(ARMixConsole PRIVATE JUCE_WEB_BROWSER=1 JUCE_USE_WIN_WEBVIEW2=1 diff --git a/README.md b/README.md index b8db110ba..93c21a0d4 100644 --- a/README.md +++ b/README.md @@ -80,3 +80,9 @@ Use MIX → Channel 1 ADD FX to select a real indexed VST3; PLUGINS opens Plugin - Each VST3 insert in the MIX view has a small ⏻ toggle with clear ON/OFF state. Bypass updates the atomic realtime control without rebuilding the plugin graph or leaving the MIX screen. - Diagnostic health JSON no longer truncates every record at 511 characters; the bounded queue slot is now 4096 bytes, with a truncation counter. - Windows CI validates the native UI contract and real DSP pan coefficient tests. Hardware verification remains necessary. + +## P2.5.1 — Live preset prepared graph + +- Pre-stage plugin binary state before live recall, publish graph at audio callback boundary, retire old graph only after callback acknowledges; de-click buffer fades. +- Does not require MUTE OUTPUT for recall; SAVE still muted-only. Old ADD/REMOVE/REORDER remains callback-detach and should not be used during performance. +- See [P2.5 live recall notes](docs/P25_LIVE_GRAPH_HANDOFF.md). This is not a full seamless dual-DSP crossfade. diff --git a/docs/P25_LIVE_GRAPH_HANDOFF.md b/docs/P25_LIVE_GRAPH_HANDOFF.md new file mode 100644 index 000000000..28c41cf5a --- /dev/null +++ b/docs/P25_LIVE_GRAPH_HANDOFF.md @@ -0,0 +1,32 @@ +# P2.5.1 — Live Preset Graph Handoff (ARD P2 safe-recall foundation) + +## Product goal +Previous P2.4 recall required MUTE OUTPUT and called JUCE removeAudioCallback/addAudioCallback around graph changes. This interrupted the hardware path. + +## Implemented +- The existing Add FX FabFilter/RX compatibility and P2.4 .armix ZIP format remain unchanged. +- Preset recall validates every archive entry, recreates all VST3 processor instances, restores each vendor binary state, and prepares DSP outside the realtime callback while the old graph continues to process audio. +- A bounded **one-slot publication** object exposes an immutable prepared Graph pointer at a buffer boundary. RT thread does no plugin creation, graph copying, mutex locking, dynamic allocation, or third-party destruction during handoff. +- In the last old callback the output gain ramps downward over one buffer; new graph is activated at callback boundary. In the first new callback output ramps upward. No double-DSP old/new crossfade occurs: avoids worst-case CPU doubling with expensive RX/FabFilter processors. +- Audio callback publishes the retired pointer. JUCE message timer takes acknowledgment and destroys old plugin instances only after old callback is finished, then announces successful recall to UI and updates Channel 1/FX Rack controls. +- Snapshot fader/PAN/mute/master settings and VST3 latency are updated at graph transition. Hardware input/output device is untouched. +- New stress test executes 12,000 cross-thread graph handoffs and validates no early reclamation, no second pending graph and expected fade endpoints. +- Counters `completedGraphSwaps` and `graphSwitchPending` are added to status and 1-Hz diagnostics. + +## Precisely what is NOT complete +- This is **buffer-boundary declick switching** with a roughly two-buffer gain dip, not genuinely seamless dual-run or delay-compensated crossfade. Effect tails do not persist through graph replacement. +- Add/Remove/Reorder FX still detach the callback and can cause a brief glitch; graph structural edits need separate migration. +- Plugin preparation and ZIP reading remain synchronous on the message thread, so UI may freeze temporarily although audio callback remains independent. Next phase must stage on background worker, coordinate JUCE plugin threading requirements and deal with plugin state APIs that require message-thread affinity. +- Simultaneous audio device change while a graph is pending should be avoided until device-lifecycle cancellation is implemented. +- Plugin compatibility and xrun telemetry must be verified with real FabFilter, iZotope RX and ASIO hardware before declaring live-ready. + +## Windows physical acceptance +1. Load FabFilter (e.g., Pro-Q) and iZotope RX, confirm both work; save as `Chain A` (P2.4 save still requires output muted). Repeat with a second preset `Chain B` containing a different sound. +2. Unmute output and play continuous signal. Open MY SOUNDS and RECALL LIVE alternating presets while listening on headphones. +3. Check graph count increases in SIGNAL CHECK diagnostic status; ensure the audio device never restarts, current and new plugin editors open correctly, and saved vendor states restore. +4. Compare interrupted signal length and xrun timing with old P2.4 and review AUDIO_HEALTH after 2 minutes. Avoid device changes during recall. +5. On any stuck load or stream loss, share `audio-diagnostics.log` and stop using the experimental release for a real broadcast. + +## Release gates +- Windows x64 MSVC, JS contract, CTest stress all green. +- Physical 30+ minute soak and plugin-specific AB listening (FabFilter, RX, ArSonKuPik) still required. Draft PR only. diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 4fc5812f7..a95868341 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -5,6 +5,7 @@ #include "StereoPan.h" #include "NativePresetArchive.h" #include "VstBusLayout.h" +#include "LiveGraphHandoff.h" #include #include #include @@ -15,7 +16,8 @@ // One live stereo input path and up to 8 actual VST3 processors. // The audio callback never scans files, creates plugins, mutates the chain, // enters UI code, locks host mutexes, logs, or changes device settings. -// Chain edits detach audio callback first (brief intentional dropout in P2). +// P2.5 recall pre-stages a graph and transitions at callback boundaries. +// Legacy Add/Remove/Move still detach; seamless structural editing is deferred. class LiveAudioEngine final : private juce::AudioIODeviceCallback { public: @@ -30,10 +32,22 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback int latency = 0; }; + struct Graph + { + std::array slots {}; + std::array, maxFx> bypassFlags {}; + int count = 0; + int latency = 0; + bool hasRecallState = false; + float channelDb = 0.f, masterDb = 0.f, pan = 0.f; + bool channelMute = false, masterMute = false; + }; + LiveAudioEngine() { formats_.addFormat (std::make_unique()); scratch_.setSize (2, maxFrames, false, true, false); + handoff_.initialize (graphOwned_.get()); } ~LiveAudioEngine() override { stop(); } @@ -56,12 +70,14 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void stop() { detach(); - for (int i = 0; i < count_; ++i) + handoff_.resetAfterStop (graphOwned_.get()); + stagedOwner_.reset(); + for (int i = 0; i < graphOwned_->count; ++i) { - if (slots_[i].processor) slots_[i].processor->releaseResources(); - slots_[i] = Slot {}; + if (graphOwned_->slots[i].processor) graphOwned_->slots[i].processor->releaseResources(); + graphOwned_->slots[i] = Slot {}; } - count_ = 0; + graphOwned_->count = 0; deviceManager_.closeAudioDevice(); } @@ -91,24 +107,42 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void setChannelMuted (bool value) noexcept { channelMute_.store (value); } void setMasterMuted (bool value) noexcept { masterMute_.store (value); } - int chainSize() const noexcept { return count_; } + int chainSize() const noexcept { return graphOwned_->count; } + bool isGraphSwitchPending() const noexcept { return handoff_.busy(); } + // Invoke from the JUCE message thread, at most once per timer tick. + // Retire only after the callback has acknowledged and left the old graph. + bool finalizeGraphSwitch() + { + auto* retired = handoff_.takeRetired(); + if (!retired) return false; + jassert (retired == graphOwned_.get()); + if (retired != graphOwned_.get() || !stagedOwner_) return false; + auto old = std::move (graphOwned_); + graphOwned_ = std::move (stagedOwner_); + for (int i = 0; i < old->count; ++i) + if (old->slots[i].processor) old->slots[i].processor->releaseResources(); + old.reset(); // Third-party destruction exclusively on message thread. + handoff_.completeRetirement(); + completedSwaps_.fetch_add (1, std::memory_order_relaxed); + return true; + } juce::AudioPluginInstance* pluginAt (int index) noexcept { - return index >= 0 && index < count_ ? slots_[index].processor.get() : nullptr; + return index >= 0 && index < graphOwned_->count ? graphOwned_->slots[index].processor.get() : nullptr; } juce::var chainState() const { juce::Array nodes; - for (int i = 0; i < count_; ++i) + for (int i = 0; i < graphOwned_->count; ++i) { auto node = std::make_unique(); node->setProperty ("index", i); - node->setProperty ("name", slots_[i].name); - node->setProperty ("id", slots_[i].catalogId); - node->setProperty ("bypass", slots_[i].bypass); - node->setProperty ("latency", slots_[i].latency); + node->setProperty ("name", graphOwned_->slots[i].name); + node->setProperty ("id", graphOwned_->slots[i].catalogId); + node->setProperty ("bypass", graphOwned_->slots[i].bypass); + node->setProperty ("latency", graphOwned_->slots[i].latency); nodes.add (juce::var (node.release())); } return juce::var (nodes); @@ -117,7 +151,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String addVst3 (const juce::String& filename, int uid, const juce::String& catalogId) { - if (count_ >= maxFx) return "FX Rack is full (maximum 8 VST3 effects)"; + if (handoff_.busy()) return "FX graph transition in progress; retry shortly"; + if (graphOwned_->count >= maxFx) return "FX Rack is full (maximum 8 VST3 effects)"; auto* device = deviceManager_.getCurrentAudioDevice(); if (device == nullptr) return "Configure a working audio input/output device first"; auto* fmt = formats_.getFormat (0); @@ -154,9 +189,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback node.path = filename; node.uid = uid; node.processor = std::move (instance); - slots_[count_] = std::move (node); - bypassFlags_[count_].store (false, std::memory_order_release); - ++count_; + graphOwned_->slots[graphOwned_->count] = std::move (node); + graphOwned_->bypassFlags[graphOwned_->count].store (false, std::memory_order_release); + ++graphOwned_->count; attach(); return {}; } @@ -167,6 +202,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String captureSnapshot (armix::storage::Snapshot& snapshot) { if (!isOutputMuted()) return "Mute hardware output before saving a native preset"; + if (handoff_.busy()) return "Finish pending FX graph transition before saving"; snapshot.effects.clear(); snapshot.channelDb = juce::Decibels::gainToDecibels ( channelGain_.load (std::memory_order_relaxed), -60.f); @@ -179,16 +215,16 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String error; try { - for (int i = 0; i < count_; ++i) + for (int i = 0; i < graphOwned_->count; ++i) { - const auto& slot = slots_[i]; + const auto& slot = graphOwned_->slots[i]; if (!slot.processor) { error = "Invalid active FX slot"; break; } armix::storage::FxState state; state.path = slot.path; state.name = slot.name; state.catalogId = slot.catalogId; state.uid = slot.uid; - state.bypass = bypassFlags_[i].load (std::memory_order_acquire); + state.bypass = graphOwned_->bypassFlags[i].load (std::memory_order_acquire); slot.processor->getStateInformation (state.binary); if (state.binary.getSize() > armix::storage::NativePresetArchive::maxStateBytes) { @@ -207,13 +243,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return error; } - // Stage every plugin/state BEFORE touching the currently operating plan. - // Caller must mute output; replacing the graph is non-RT, and no old - // processor is destroyed until the callback has been detached. + // Stage all VST3 binary states before publication; callback never owns + // or destroys a plugin. No manual output mute is required for recall. juce::String restoreSnapshot (const armix::storage::Snapshot& snapshot) { - if (!isOutputMuted()) - return "Mute hardware output before recalling a native preset"; + if (handoff_.busy()) + return "A live FX graph transition is already in progress"; if (snapshot.effects.size() > maxFx) return "Too many plugins in preset"; auto* device = deviceManager_.getCurrentAudioDevice(); if (!device) return "No active audio device"; @@ -221,8 +256,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if (!fmt) return "No VST3 format available"; const auto rate = device->getCurrentSampleRate(); const auto buffer = juce::jmax (32, device->getCurrentBufferSizeSamples()); + const auto deviceEpoch = deviceStartCount_.load (std::memory_order_acquire); - std::array staged; + std::array stagedSlots; for (int i = 0; i < static_cast (snapshot.effects.size()); ++i) { const auto& fx = snapshot.effects[static_cast (i)]; @@ -264,65 +300,82 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback slot.uid = fx.uid; slot.bypass = fx.bypass; slot.processor = std::move (processor); - staged[static_cast (i)] = std::move (slot); + stagedSlots[static_cast (i)] = std::move (slot); } - detach(); - for (int i = 0; i < count_; ++i) - if (slots_[i].processor) slots_[i].processor->releaseResources(); - auto retired = std::move (slots_); - slots_ = std::move (staged); - count_ = static_cast (snapshot.effects.size()); - for (int i = 0; i < maxFx; ++i) - bypassFlags_[i].store (i < count_ ? slots_[i].bypass : false, - std::memory_order_release); - setChannelGainDb (snapshot.channelDb); - setChannelPan (snapshot.pan); - setMasterGainDb (snapshot.masterDb); - setChannelMuted (snapshot.channelMute); - setMasterMuted (snapshot.masterMute); - attach(); - // retired instances are destroyed on the message thread, never callback. + // Reject a graph prepared against stale rate/buffer. + if (deviceEpoch != deviceStartCount_.load (std::memory_order_acquire) || + device != deviceManager_.getCurrentAudioDevice() || + rate != device->getCurrentSampleRate() || + buffer != juce::jmax (32, device->getCurrentBufferSizeSamples())) + return "Audio device changed during preset preparation. Retry recall."; + + // Ownership stays with the control thread. The audio thread switches + // only an immutable pointer at a callback boundary (never detach). + auto staged = std::make_unique(); + staged->slots = std::move (stagedSlots); + staged->count = static_cast (snapshot.effects.size()); + staged->hasRecallState = true; + staged->channelDb = snapshot.channelDb; + staged->masterDb = snapshot.masterDb; + staged->pan = snapshot.pan; + staged->channelMute = snapshot.channelMute; + staged->masterMute = snapshot.masterMute; + for (int i = 0; i < staged->count; ++i) + { + staged->bypassFlags[i].store (staged->slots[i].bypass, std::memory_order_relaxed); + staged->slots[i].latency = staged->slots[i].processor->getLatencySamples(); + if (!staged->slots[i].bypass) staged->latency += staged->slots[i].latency; + } + stagedOwner_ = std::move (staged); + if (!handoff_.stage (stagedOwner_.get())) + { + stagedOwner_.reset(); + return "Cannot schedule live FX graph swap"; + } return {}; } bool setBypass (int index, bool value) { - if (index < 0 || index >= count_) return false; + if (handoff_.busy()) return false; + if (index < 0 || index >= graphOwned_->count) return false; // Message-thread metadata and an atomic value consumed by the audio thread. - slots_[index].bypass = value; - bypassFlags_[index].store (value, std::memory_order_release); + graphOwned_->slots[index].bypass = value; + graphOwned_->bypassFlags[index].store (value, std::memory_order_release); return true; } bool removeAt (int index) { - if (index < 0 || index >= count_) return false; + if (handoff_.busy()) return false; + if (index < 0 || index >= graphOwned_->count) return false; detach(); - if (slots_[index].processor) - slots_[index].processor->releaseResources(); - for (int i = index; i + 1 < count_; ++i) - slots_[i] = std::move (slots_[i + 1]); - slots_[--count_] = Slot {}; - for (int i = 0; i < count_; ++i) - bypassFlags_[i].store (slots_[i].bypass, std::memory_order_release); + if (graphOwned_->slots[index].processor) + graphOwned_->slots[index].processor->releaseResources(); + for (int i = index; i + 1 < graphOwned_->count; ++i) + graphOwned_->slots[i] = std::move (graphOwned_->slots[i + 1]); + graphOwned_->slots[--graphOwned_->count] = Slot {}; + for (int i = 0; i < graphOwned_->count; ++i) + graphOwned_->bypassFlags[i].store (graphOwned_->slots[i].bypass, std::memory_order_release); attach(); return true; } bool moveSlot (int from, int to) { - if (from < 0 || from >= count_ || to < 0 || to >= count_ || from == to) + if (handoff_.busy()) return false; + if (from < 0 || from >= graphOwned_->count || to < 0 || to >= graphOwned_->count || from == to) return false; detach(); - auto moved = std::move (slots_[from]); + auto moved = std::move (graphOwned_->slots[from]); if (from < to) - for (int i = from; i < to; ++i) slots_[i] = std::move (slots_[i + 1]); + for (int i = from; i < to; ++i) graphOwned_->slots[i] = std::move (graphOwned_->slots[i + 1]); else - for (int i = from; i > to; --i) slots_[i] = std::move (slots_[i - 1]); - slots_[to] = std::move (moved); - for (int i = 0; i < count_; ++i) - bypassFlags_[i].store (slots_[i].bypass, std::memory_order_release); + for (int i = from; i > to; --i) graphOwned_->slots[i] = std::move (graphOwned_->slots[i - 1]); + graphOwned_->slots[to] = std::move (moved); + for (int i = 0; i < graphOwned_->count; ++i) + graphOwned_->bypassFlags[i].store (graphOwned_->slots[i].bypass, std::memory_order_release); attach(); return true; } @@ -360,11 +413,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("deviceStartCount", static_cast (deviceStartCount_.load())); o->setProperty ("deviceStopCount", static_cast (deviceStopCount_.load())); juce::Array pluginTimings; - for (int i = 0; i < count_; ++i) + for (int i = 0; i < graphOwned_->count; ++i) { auto item = std::make_unique(); item->setProperty ("slot", i + 1); - item->setProperty ("name", slots_[i].name); + item->setProperty ("name", graphOwned_->slots[i].name); item->setProperty ("lastUs", static_cast (lastPluginUsBySlot_[i].load())); item->setProperty ("worstUs", static_cast (worstPluginUsBySlot_[i].load())); pluginTimings.add (juce::var (item.release())); @@ -380,7 +433,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("peakLeft", outputPeakL_.load()); o->setProperty ("peakRight", outputPeakR_.load()); o->setProperty ("latencySamples", totalLatency_.load()); - o->setProperty ("chainCount", count_); + o->setProperty ("chainCount", graphOwned_->count); + o->setProperty ("graphSwitchPending", handoff_.busy()); + o->setProperty ("completedGraphSwaps", static_cast (completedSwaps_.load())); return juce::var (o.release()); } @@ -388,12 +443,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback static constexpr int maxFrames = 8192; juce::AudioDeviceManager deviceManager_; juce::AudioPluginFormatManager formats_; - std::array slots_; - int count_ = 0; + std::unique_ptr graphOwned_ {std::make_unique()}; + std::unique_ptr stagedOwner_; + armix::rt::LiveGraphHandoff handoff_; bool attached_ = false; juce::AudioBuffer scratch_; // Indexed atomic bypass flags: instant RT-safe toggles, no graph detachment. - std::array, maxFx> bypassFlags_ {}; std::atomic monitor_ { false }, channelMute_ { false }, masterMute_ { false }, dryTest_ { false }; std::atomic masterGain_ { 1.f }, channelGain_ { 1.f }, channelPan_ { 0.f }; std::atomic inputPeak_ { 0.f }, postFxPeak_ { 0.f }, outputPeak_ { 0.f }; @@ -426,6 +481,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback old, value, std::memory_order_relaxed)) {} } std::atomic totalLatency_ { 0 }; + std::atomic completedSwaps_ {0}; void detach() { @@ -455,16 +511,16 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } previousCallbackStartUs_ = 0; int latency = 0; - for (int i = 0; i < count_; ++i) + for (int i = 0; i < graphOwned_->count; ++i) { - auto& slot = slots_[i]; + auto& slot = graphOwned_->slots[i]; if (slot.processor) { slot.processor->releaseResources(); slot.processor->prepareToPlay (d->getCurrentSampleRate(), juce::jmax (32, d->getCurrentBufferSizeSamples())); slot.latency = slot.processor->getLatencySamples(); - if (!bypassFlags_[i].load (std::memory_order_relaxed)) latency += slot.latency; + if (!graphOwned_->bypassFlags[i].load (std::memory_order_relaxed)) latency += slot.latency; } } totalLatency_.store (latency); @@ -484,6 +540,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const float* const* inputs, int inputChannels, float* const* outputs, int outputChannels, int samples, const juce::AudioIODeviceCallbackContext&) override { + const auto cycle = handoff_.beginCycle(); const std::uint64_t beginUs = clockMicros(); const double periodUs = 1000000.0 * static_cast (samples) / sampleRateHz_; // Scheduling gaps only suggest instability: pause/suspend and WASAPI @@ -509,6 +566,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Precomputed stereo pan matrix; no trigonometry, locks or allocations // in the realtime sample loop. 0 = transparent identity matrix. const auto matrix = armix::dsp::StereoPanMatrix::fromNormalized (pan); + const float rampStep = samples > 1 ? 1.f / static_cast (samples - 1) : 0.f; float inPeak = 0.f, postFxPeak = 0.f, outPeak = 0.f; float outPeakL = 0.f, outPeakR = 0.f; for (int offset = 0; offset < samples; offset += maxFrames) @@ -531,10 +589,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::MidiBuffer midi; if (!dry) { - for (int fx = 0; fx < count_; ++fx) + for (int fx = 0; fx < cycle.graph->count; ++fx) { - auto& slot = slots_[fx]; - if (slot.processor && ! bypassFlags_[fx].load (std::memory_order_relaxed)) + auto& slot = cycle.graph->slots[fx]; + if (slot.processor && ! cycle.graph->bypassFlags[fx].load (std::memory_order_relaxed)) { const auto pluginBeginUs = clockMicros(); slot.processor->processBlock (scratch_, midi); @@ -565,7 +623,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { const float mapped = c == 0 ? matrix.ll * left[i] + matrix.lr * right[i] : matrix.rl * left[i] + matrix.rr * right[i]; - const float value = (enabled && !muted) ? mapped * gain : 0.f; + const auto phase = (offset + i) * rampStep; + const float ramp = cycle.fadeOut ? 1.f - phase + : cycle.fadeIn ? phase : 1.f; + const float value = (enabled && !muted) ? mapped * gain * ramp : 0.f; dst[i] = value; channelPeak = juce::jmax (channelPeak, std::abs (value)); } @@ -579,6 +640,21 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback outputPeak_.store (juce::jmin (1.f, outPeak), std::memory_order_relaxed); outputPeakL_.store (juce::jmin (1.f, outPeakL), std::memory_order_relaxed); outputPeakR_.store (juce::jmin (1.f, outPeakR), std::memory_order_relaxed); + if (cycle.fadeOut) + { + // Ownership remains with stagedOwner_ until message thread ack. + handoff_.endCycle (cycle); + const auto* switched = handoff_.current(); + if (switched && switched->hasRecallState) + { + setChannelGainDb (switched->channelDb); + setMasterGainDb (switched->masterDb); + setChannelPan (switched->pan); + setChannelMuted (switched->channelMute); + setMasterMuted (switched->masterMute); + totalLatency_.store (switched->latency, std::memory_order_relaxed); + } + } const auto elapsedUs = clockMicros() - beginUs; lastCallbackUs_.store (elapsedUs, std::memory_order_relaxed); publishMax (worstCallbackUs_, elapsedUs); diff --git a/src/LiveGraphHandoff.h b/src/LiveGraphHandoff.h new file mode 100644 index 000000000..e1f6f654a --- /dev/null +++ b/src/LiveGraphHandoff.h @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include + +// P2.5.1 SPSC RT graph handoff. Message thread OWNS all graphs and retires +// only after the audio callback acknowledges a buffer-boundary transition. +// The callback never copies ownership, frees memory, locks, or waits. +namespace armix::rt +{ +template +class LiveGraphHandoff final +{ +public: + struct Cycle { Graph* graph=nullptr; bool fadeOut=false; bool fadeIn=false; }; + void initialize (Graph* graph) noexcept + { + active_.store (graph, std::memory_order_release); + pending_.store (nullptr, std::memory_order_release); + retired_.store (nullptr, std::memory_order_release); + phase_.store (0, std::memory_order_release); + fadeInNext_ = false; + } + bool stage (Graph* candidate) noexcept + { + if (!candidate) return false; + int idle = 0; + if (!phase_.compare_exchange_strong (idle, 1, std::memory_order_acq_rel)) + return false; + pending_.store (candidate, std::memory_order_release); + return true; + } + bool busy() const noexcept + { + return phase_.load (std::memory_order_acquire) != 0; + } + Cycle beginCycle() noexcept + { + Cycle cycle; + cycle.graph = active_.load (std::memory_order_acquire); + cycle.fadeOut = pending_.load (std::memory_order_acquire) != nullptr; + cycle.fadeIn = fadeInNext_; + fadeInNext_ = false; + return cycle; + } + void endCycle (const Cycle& cycle) noexcept + { + if (!cycle.fadeOut) return; + // Control thread never cancels a published graph before acknowledgement. + auto* newGraph = pending_.exchange (nullptr, std::memory_order_acq_rel); + if (!newGraph) return; + active_.store (newGraph, std::memory_order_release); + phase_.store (2, std::memory_order_release); + retired_.store (cycle.graph, std::memory_order_release); + fadeInNext_ = true; + } + Graph* takeRetired() noexcept + { + return retired_.exchange (nullptr, std::memory_order_acq_rel); + } + // Called AFTER the message thread safely releases the retired graph. + void completeRetirement() noexcept + { + phase_.store (0, std::memory_order_release); + } + Graph* current() const noexcept { return active_.load (std::memory_order_acquire); } + // Caller must already have synchronously stopped/detached audio callbacks. + void resetAfterStop (Graph* graph) noexcept { initialize (graph); } +private: + std::atomic active_ {nullptr}; + std::atomic pending_ {nullptr}; + std::atomic retired_ {nullptr}; + // 0=idle, 1=queued, 2=acknowledged; closes the pending/ack gap. + std::atomic phase_ {0}; + bool fadeInNext_ = false; // audio thread exclusive +}; + +inline float linearBufferRamp (int sample, int total, bool fadeOut, bool fadeIn) noexcept +{ + if (total <= 1) return fadeOut ? 0.f : 1.f; + const auto unit = static_cast (sample) / static_cast (total-1); + if (fadeOut) return 1.f-unit; + if (fadeIn) return unit; + return 1.f; +} +} // namespace armix::rt diff --git a/src/Main.cpp b/src/Main.cpp index ded74c734..1d0926e9d 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -152,6 +152,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr bool setupLaunching_ = false; unsigned int timerTicks_ = 0; bool deviceSettingsDirty_ = false; + juce::var pendingPresetUI_; + juce::String pendingPresetName_; void emitNotice (const juce::String& message, bool error = false) { @@ -337,8 +339,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr else if (action == "presetLoad") { const auto name = args.getProperty ("name", {}).toString(); - if (!engine_.isOutputMuted()) - return emitNotice ("Mute output in SIGNAL CHECK before recalling a native sound preset.", true); + if (engine_.isGraphSwitchPending()) + return emitNotice ("FX recall is already transitioning; retry shortly.", true); editorWindow_.reset(); armix::storage::Snapshot snapshot; auto error = presets_.load (name, snapshot); @@ -350,8 +352,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } else { - diagnostics_.record ("PRESET_LOADED", name + " (" + juce::String (snapshot.effects.size()) + " VST3)"); - emitChain(); + // UI reflects state only AFTER the audio thread acknowledges + // the staged plan; avoid claiming active while it is still old. auto updated = std::make_unique(); updated->setProperty ("name", name); updated->setProperty ("channelDb", snapshot.channelDb); @@ -359,9 +361,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr updated->setProperty ("pan", snapshot.pan * 100.f); updated->setProperty ("channelMute", snapshot.channelMute); updated->setProperty ("masterMute", snapshot.masterMute); - if (browser_.loaded) - browser_.emitEventIfBrowserIsVisible ("arMixNativePresetLoaded", juce::var (updated.release())); - emitNotice ("Native sound recalled: " + name + ". Output remains muted until you unmute it."); + pendingPresetUI_ = juce::var (updated.release()); + pendingPresetName_ = name; + diagnostics_.record ("PRESET_GRAPH_QUEUED", name + " (" + + juce::String (snapshot.effects.size()) + " VST3)"); + emitNotice ("Preparing live transition to sound: " + name); } } else if (action == "openDiagnostics") @@ -479,6 +483,17 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void timerCallback() override { ++timerTicks_; + if (engine_.finalizeGraphSwitch()) + { + diagnostics_.record ("GRAPH_SWAP_ACK", pendingPresetName_); + emitChain(); + if (pendingPresetUI_.isObject() && browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixNativePresetLoaded", pendingPresetUI_); + if (pendingPresetName_.isNotEmpty()) + emitNotice ("Live sound recalled: " + pendingPresetName_); + pendingPresetUI_ = {}; + pendingPresetName_.clear(); + } if (timerTicks_ % 12 == 0) diagnostics_.record ("AUDIO_HEALTH", juce::JSON::toString (engine_.status(), false)); diff --git a/tests/live_graph_contract_test.mjs b/tests/live_graph_contract_test.mjs new file mode 100644 index 000000000..86ce65738 --- /dev/null +++ b/tests/live_graph_contract_test.mjs @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Static wiring contracts supplement the 12k native handoff stress cycles. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +const e=readFileSync('src/LiveAudioEngine.h','utf8'); +const h=readFileSync('src/LiveGraphHandoff.h','utf8'); +const m=readFileSync('src/Main.cpp','utf8'); +const b=readFileSync('web/bridge.js','utf8'); +test('live recall stages complete VST state before pointer publication',()=>{ + const restore=e.slice(e.indexOf('juce::String restoreSnapshot'), e.indexOf('bool setBypass')); + assert.match(restore,/prepareToPlay \(rate, buffer\)/); + assert.match(restore,/setStateInformation/); + assert.match(restore,/handoff_\.stage \(stagedOwner_\.get\(\)\)/); + assert.doesNotMatch(restore,/\bdetach\s*\(/); +}); +test('RT callback owns pointer switch and message thread owns third party destruction',()=>{ + assert.match(e,/handoff_\.beginCycle\(\)/); + assert.match(e,/handoff_\.endCycle \(cycle\)/); + assert.match(e,/handoff_\.takeRetired\(\)/); + assert.match(e,/handoff_\.completeRetirement\(\)/); + assert.match(h,/std::atomic active_/); + assert.match(h,/std::atomic phase_/); +}); +test('preset UI reflects callback-acknowledged state not queued state',()=>{ + assert.match(m,/if \(engine_\.finalizeGraphSwitch\(\)\)/); + assert.match(m,/pendingPresetUI_/); + assert.match(m,/arMixNativePresetLoaded/); + assert.match(b,/RECALL LIVE/); +}); +test('old structural operations remain guarded and declared as unfinished',()=>{ + assert.match(e,/if \(handoff_\.busy\(\)\) return false/); + assert.match(e,/Legacy Add\/Remove\/Move still detach/); +}); diff --git a/tests/realtime_control_test.cpp b/tests/realtime_control_test.cpp index e90023bdd..0cb920ab9 100644 --- a/tests/realtime_control_test.cpp +++ b/tests/realtime_control_test.cpp @@ -6,6 +6,7 @@ #endif #include #include "../src/StereoPan.h" +#include "../src/LiveGraphHandoff.h" #include #include #include @@ -50,5 +51,61 @@ int main(){ checkPan(0.f,0.f,1.f,0.f,1.f); checkPan(0.f,1.f,0.f,1.f,0.f); std::cout<<"PASS: native stereo pan centre, extremes, half-pan and unit-gain dual-mono\n"; + // Runtime contract for the exact RT graph publication helper. + struct FakeGraph { int id; }; + FakeGraph old{1}, next{2}, third{3}; + armix::rt::LiveGraphHandoff handoff; + handoff.initialize (&old); + assert(!handoff.busy() && handoff.current()==&old); + assert(handoff.stage(&next) && !handoff.stage(&third)); + auto first=handoff.beginCycle(); + assert(first.graph==&old && first.fadeOut && !first.fadeIn); + assert(armix::rt::linearBufferRamp(0,128,true,false)==1.f); + assert(armix::rt::linearBufferRamp(127,128,true,false)==0.f); + handoff.endCycle(first); + assert(handoff.current()==&next && handoff.busy()); + assert(!handoff.stage(&third)); + assert(handoff.takeRetired()==&old); + // Retirement acknowledgement stays pending until old owners are actually + // destroyed by control; no premature second stage in the handoff gap. + assert(!handoff.stage(&third)); + handoff.completeRetirement(); + assert(handoff.stage(&third)); + auto second=handoff.beginCycle(); + assert(second.graph==&next && second.fadeOut && second.fadeIn); + handoff.endCycle(second); + assert(handoff.takeRetired()==&next); + handoff.completeRetirement(); + assert(handoff.current()==&third); + auto last=handoff.beginCycle(); + assert(!last.fadeOut && last.fadeIn); + assert(armix::rt::linearBufferRamp(0,128,false,true)==0.f); + assert(armix::rt::linearBufferRamp(127,128,false,true)==1.f); + handoff.endCycle(last); + // Repeat thousands of publications on another callback thread and + // consume the acknowledgement only from the control thread. + armix::rt::LiveGraphHandoff threaded; + threaded.initialize (&old); + constexpr int rounds=12000; + std::atomic ended{false}; + std::thread audio([&] { + while(!ended.load(std::memory_order_acquire)) { + auto cycle=threaded.beginCycle(); + if(cycle.fadeOut)threaded.endCycle(cycle); + else std::this_thread::yield(); + } + }); + for(int i=0;i
- ${muted?"OUTPUT MUTED · Save/recall is available." - :"LIVE OUTPUT ACTIVE · Mute output first to protect your performance."} + ${muted?"OUTPUT MUTED · Save and recall available." + :"LIVE OUTPUT ACTIVE · Recall uses a short de-click fade. Mute before SAVE."} ${muted?"":''}
@@ -262,12 +262,12 @@
${state.presets.length? state.presets.map(n=>`
${escapeHtml(n)}.armix · full vendor VST3 state - +
`).join("") : '
No native sounds saved. Mute output, then save the current live FX chain.
'}
`; dlg.querySelector(".native-dialog-footer").textContent= - "Changing active FX while performing is not seamless yet. Output stays muted after recall. Do not distribute presets containing licensed plugin state without permission."; + "Live recall: prepared VST3 chain switches at a callback boundary with a brief fade-down/up (not dual-graph seamless). SAVE requires mute. Output routing is unchanged."; } function openMySounds(){ renderMySounds(); @@ -379,7 +379,9 @@ if(el.hasAttribute("data-preset-load")){ const name=el.dataset.presetLoad; if(!name)return; - if(!confirm('Recall native sound "'+name+'"? Current plugin chain will be replaced. Output must remain muted.'))return; + if(!confirm('Recall native sound "'+name+'"? The mixer will use a short de-click fade when switching FX chains.'))return; + const notice=document.querySelector("#nativeMySounds .native-status"); + if(notice)notice.textContent="Preparing new VST3 instances and binary states. Live audio remains on the current graph until the new plan is ready…"; requestAnimationFrame(()=>requestAnimationFrame(()=>send("presetLoad",{name}))); return; } From 440db646cc30d1a2a6e2f8ba5817dd76c4f06ab3 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 12:11:05 +0700 Subject: [PATCH 2/3] fix(msvc): explicitly reset pending JUCE var after acknowledged preset graph transition --- src/Main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Main.cpp b/src/Main.cpp index 1d0926e9d..c2830f83e 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -491,7 +491,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr browser_.emitEventIfBrowserIsVisible ("arMixNativePresetLoaded", pendingPresetUI_); if (pendingPresetName_.isNotEmpty()) emitNotice ("Live sound recalled: " + pendingPresetName_); - pendingPresetUI_ = {}; + pendingPresetUI_ = juce::var(); pendingPresetName_.clear(); } if (timerTicks_ % 12 == 0) From 7a769105595aeaa2f8d8e3a549143426fdba5eae Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 12:17:24 +0700 Subject: [PATCH 3/3] perf(rt): precompute snapshot gain linear coefficients before graph publication --- src/LiveAudioEngine.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index a95868341..95c437d55 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -40,6 +40,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback int latency = 0; bool hasRecallState = false; float channelDb = 0.f, masterDb = 0.f, pan = 0.f; + float channelLinear = 1.f, masterLinear = 1.f; bool channelMute = false, masterMute = false; }; @@ -318,6 +319,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback staged->hasRecallState = true; staged->channelDb = snapshot.channelDb; staged->masterDb = snapshot.masterDb; + staged->channelLinear = juce::Decibels::decibelsToGain (snapshot.channelDb); + staged->masterLinear = juce::Decibels::decibelsToGain (snapshot.masterDb); staged->pan = snapshot.pan; staged->channelMute = snapshot.channelMute; staged->masterMute = snapshot.masterMute; @@ -647,8 +650,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const auto* switched = handoff_.current(); if (switched && switched->hasRecallState) { - setChannelGainDb (switched->channelDb); - setMasterGainDb (switched->masterDb); + channelGain_.store (switched->channelLinear, std::memory_order_relaxed); + masterGain_.store (switched->masterLinear, std::memory_order_relaxed); setChannelPan (switched->pan); setChannelMuted (switched->channelMute); setMasterMuted (switched->masterMute);