From 3a901639b828304cf2c8e08179791ef5419ec290 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 06:52:11 +0700 Subject: [PATCH 01/23] feat(device): prepare exact sparse live input-port masks with device epoch fence --- engine/device/LiveInputPortRegistry.h | 63 +++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 engine/device/LiveInputPortRegistry.h diff --git a/engine/device/LiveInputPortRegistry.h b/engine/device/LiveInputPortRegistry.h new file mode 100644 index 000000000..96e01f148 --- /dev/null +++ b/engine/device/LiveInputPortRegistry.h @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include + +// P1E — CONTROL-thread-only preparation from the *opened driver's active* +// channel mask. Physical channel IDs are zero-based; callback pointers are +// packed into [0..enabledCount) in the driver's enabled-channel order. +// Device names/ports must be verified by caller against the same session. +// This header deliberately has no JUCE dependency and does no callback work. +namespace armix::device { +struct LiveInputPortRegistry final { + static constexpr int limit = 256; + enum class Fault : std::uint8_t { + none, invalidEpoch, invalidPort, duplicatePort, overflow + }; + std::array callbackByPhysical {}; + std::array physicalByCallback {}; + std::uint64_t epoch = 0; + int enabledCount = 0; + + static bool prepare (std::uint64_t generation, + std::span physicalEnabledInCallbackOrder, + LiveInputPortRegistry& destination, + Fault& fault) noexcept { + fault=Fault::none; + if(generation==0) { fault=Fault::invalidEpoch; return false; } + if(physicalEnabledInCallbackOrder.size()>limit) { + fault=Fault::overflow;return false; + } + LiveInputPortRegistry next; + next.callbackByPhysical.fill(-1); + next.physicalByCallback.fill(-1); + for(std::size_t n=0;n=limit) { + fault=Fault::invalidPort;return false; + } + if(next.callbackByPhysical[id]!=-1) { + fault=Fault::duplicatePort;return false; + } + next.callbackByPhysical[id]=static_cast(n); + next.physicalByCallback[n]=id; + } + next.epoch=generation; + next.enabledCount=static_cast(physicalEnabledInCallbackOrder.size()); + destination=next; + return true; + } + int callbackIndex(int port) const noexcept { + return port>=0 && port=0 && callback Date: Wed, 28 Oct 2026 06:53:02 +0700 Subject: [PATCH 02/23] feat(audio): nonblocking epoch/revision route publisher with deferred non-RT retirement --- engine/core/RealtimeRoutePublisher.h | 117 +++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 engine/core/RealtimeRoutePublisher.h diff --git a/engine/core/RealtimeRoutePublisher.h b/engine/core/RealtimeRoutePublisher.h new file mode 100644 index 000000000..0012122ad --- /dev/null +++ b/engine/core/RealtimeRoutePublisher.h @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include +#include + +// Realtime path: two atomics per callback, one pointer read, no heap, locks, +// waiting, deallocation or device/GUI operations. One CONTROL writer. +// Prepared owns all DSP buffers; plugin objects MUST NOT be concurrently +// processed on old/new graphs (plugin lifecycle gate lives above this class). +// Old graph destruction happens only from pollRetirement() after RT readers +// have left. Do not destroy the exchange while audio callbacks are attached. +namespace armix::rt { +template +class RealtimeRoutePublisher final { + static_assert(RetiredCapacity>=2); +public: + struct Snapshot final { + std::uint64_t deviceEpoch=0; + std::uint64_t graphRevision=0; + std::unique_ptr prepared; + }; + enum class Result : std::uint8_t { + applied, invalidCandidate, staleDevice, staleRevision, retirementFull + }; + class ReadLease final { + public: + explicit ReadLease (RealtimeRoutePublisher& owner) noexcept : owner_(&owner) { + owner_->readers_.fetch_add(1,std::memory_order_acq_rel); + item_=owner_->active_.load(std::memory_order_acquire); + } + ReadLease(const ReadLease&)=delete; + ReadLease& operator=(const ReadLease&)=delete; + ReadLease(ReadLease&&)=delete; + ReadLease& operator=(ReadLease&&)=delete; + ~ReadLease() noexcept { + owner_->readers_.fetch_sub(1,std::memory_order_release); + } + const Snapshot* get(std::uint64_t currentEpoch) const noexcept { + return item_ && item_->deviceEpoch==currentEpoch + ? item_ : nullptr; + } + private: + RealtimeRoutePublisher* owner_; + const Snapshot* item_=nullptr; + }; + + RealtimeRoutePublisher()=default; + RealtimeRoutePublisher(const RealtimeRoutePublisher&)=delete; + RealtimeRoutePublisher& operator=(const RealtimeRoutePublisher&)=delete; + + // CONTROL thread, with fully prepared DSP state and explicit revision. + // Expected revision always refers to the last ACKnowledged publication. + // All failure outcomes preserve the audio callback's last valid graph. + Result publish(std::unique_ptr next, + std::uint64_t expectedRevision, + std::uint64_t deviceEpochNow) noexcept { + if(!next || !next->prepared || next->deviceEpoch==0 || + next->graphRevision==0 || next->graphRevision<=expectedRevision) + return Result::invalidCandidate; + if(next->deviceEpoch!=deviceEpochNow) + return Result::staleDevice; + if(expectedRevision!=revision_) + return Result::staleRevision; + pollRetirement(); // control thread only + if(owned_ && retiredCount_>=RetiredCapacity) + return Result::retirementFull; + if(owned_) retired_[retiredCount_++]=std::move(owned_); + owned_=std::move(next); + // Publish ownership last; readers always see a live allocation. + active_.store(owned_.get(),std::memory_order_release); + revision_=owned_->graphRevision; + return Result::applied; + } + + // CONTROL thread: gate new callback usage, then retire safely. + // Caller must ensure the audio device is stopped before destroying this + // object; asynchronous stop merely disconnects the new graph view. + void unpublish() noexcept { + pollRetirement(); + if(owned_) { + if(retiredCount_ active_{nullptr}; + std::atomic readers_{0}; + std::unique_ptr owned_; + std::array,RetiredCapacity> retired_ {}; + std::size_t retiredCount_=0; + std::uint64_t revision_=0; +}; +} // namespace armix::rt From dd64b252d376d5ede2e8e980b19594c5cd4e1042 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 06:53:47 +0700 Subject: [PATCH 03/23] fix(rt): unpublish immediately gates audio even when retired ring is saturated --- engine/core/RealtimeRoutePublisher.h | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/engine/core/RealtimeRoutePublisher.h b/engine/core/RealtimeRoutePublisher.h index 0012122ad..d58b6c345 100644 --- a/engine/core/RealtimeRoutePublisher.h +++ b/engine/core/RealtimeRoutePublisher.h @@ -80,18 +80,17 @@ class RealtimeRoutePublisher final { // Caller must ensure the audio device is stopped before destroying this // object; asynchronous stop merely disconnects the new graph view. void unpublish() noexcept { - pollRetirement(); - if(owned_) { - if(retiredCount_ Date: Wed, 28 Oct 2026 06:54:30 +0700 Subject: [PATCH 04/23] test(rt): sparse enabled pins, generation fencing, atomic snapshots and concurrent retirement --- tests/live_port_epoch_publisher_test.cpp | 124 +++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 tests/live_port_epoch_publisher_test.cpp diff --git a/tests/live_port_epoch_publisher_test.cpp b/tests/live_port_epoch_publisher_test.cpp new file mode 100644 index 000000000..cdd09ecd3 --- /dev/null +++ b/tests/live_port_epoch_publisher_test.cpp @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/core/RealtimeRoutePublisher.h" +#include "../engine/device/LiveInputPortRegistry.h" +#if defined(NDEBUG) +#undef NDEBUG +#endif +#include +#include +#include +#include +#include +#include +using namespace armix; +struct SpyGraph { + static inline std::atomic alive{0}; + int value=0; + explicit SpyGraph(int v) noexcept :value(v) {alive.fetch_add(1);} + ~SpyGraph() noexcept {alive.fetch_sub(1);} +}; +using Publisher=rt::RealtimeRoutePublisher; +static std::unique_ptr makeGraph(std::uint64_t epoch,std::uint64_t revision,int tag) { + auto x=std::make_unique(); + x->deviceEpoch=epoch;x->graphRevision=revision; + x->prepared=std::make_unique(tag); + return x; +} +int main() { + device::LiveInputPortRegistry ports;device::LiveInputPortRegistry::Fault fault; + constexpr std::array order{5,2,9}; + assert(device::LiveInputPortRegistry::prepare(7,order,ports,fault)); + assert(ports.epoch==7&&ports.enabledCount==3); + assert(ports.callbackIndex(5)==0&&ports.callbackIndex(2)==1); + assert(ports.callbackIndex(9)==2&&ports.callbackIndex(0)==-1); + assert(ports.physicalIndex(1)==2&&ports.physicalIndex(3)==-1); + assert(ports.matches(7,3)&&!ports.matches(7,4)&&!ports.matches(8,3)); + const auto old=ports; + constexpr std::array duplicates{5,2,5}; + assert(!device::LiveInputPortRegistry::prepare(7,duplicates,ports,fault)); + assert(fault==device::LiveInputPortRegistry::Fault::duplicatePort); + assert(ports.epoch==old.epoch&&ports.callbackIndex(9)==2); + constexpr std::array invalid{-1,0}; + assert(!device::LiveInputPortRegistry::prepare(7,invalid,ports,fault)); + assert(fault==device::LiveInputPortRegistry::Fault::invalidPort); + assert(!device::LiveInputPortRegistry::prepare(0,order,ports,fault)); + assert(fault==device::LiveInputPortRegistry::Fault::invalidEpoch); + + Publisher p; + assert(p.publish(makeGraph(1,1,101),0,2)==Publisher::Result::staleDevice); + assert(p.lastRevision()==0); + assert(p.publish(makeGraph(1,1,101),0,1)==Publisher::Result::applied); + assert(p.lastRevision()==1); + { + auto lease=p.acquire(); + assert(lease.get(1) && lease.get(1)->prepared->value==101); + assert(!lease.get(2)); // epoch mismatch never exposes stale audio + assert(p.publish(makeGraph(1,2,102),0,1)==Publisher::Result::staleRevision); + assert(p.publish(makeGraph(1,2,102),1,1)==Publisher::Result::applied); + assert(lease.get(1) && lease.get(1)->prepared->value==101); + assert(p.pendingRetirements()==1); + assert(!p.pollRetirement()); + assert(SpyGraph::alive==2); + assert(p.publish(makeGraph(1,3,103),2,1)==Publisher::Result::applied); + assert(p.publish(makeGraph(1,4,104),3,1)==Publisher::Result::applied); + assert(p.pendingRetirements()==3); + assert(p.publish(makeGraph(1,5,105),4,1)==Publisher::Result::retirementFull); + { + auto newer=p.acquire(); + assert(newer.get(1)&&newer.get(1)->prepared->value==104); + } + // Emergency unpublish CANNOT wait for the first active lease; but + // subsequent callbacks MUST see no valid graph immediately. + p.unpublish(); + assert(p.lastRevision()==0); + auto silenced=p.acquire(); + assert(!silenced.get(1)); + } + assert(p.pollRetirement()); + // The last unpublished owner was held until the callback could retire. + assert(SpyGraph::alive==1); + assert(p.publish(makeGraph(8,1,201),0,8)==Publisher::Result::applied); + { auto v=p.acquire();assert(v.get(8)->prepared->value==201); } + p.unpublish(); + assert(p.pollRetirement()); + assert(SpyGraph::alive==0); + + // A burst of consecutive reconfigurations does not leak retired plans + // or allocate anything in the read lease (the callback API). + for(int i=0;i<8000;++i) { + auto next=makeGraph(9,static_cast(i+1),i); + assert(p.publish(std::move(next),static_cast(i),9)==Publisher::Result::applied); + auto lease=p.acquire(); + assert(lease.get(9)&&lease.get(9)->prepared->value==i); + } + p.unpublish(); + assert(p.pollRetirement()); + assert(SpyGraph::alive==0); + + // Concurrent RT reader repeatedly observes either a whole published + // snapshot or nullptr; no old graph can be destroyed while leased. + std::atomic running{true};std::atomic observed{0}; + std::thread audio([&]{ + while(running.load(std::memory_order_relaxed)){ + auto lease=p.acquire(); + if(const auto* s=lease.get(10)){ + assert(s->deviceEpoch==10); + assert(s->prepared->value>=0); + observed.fetch_add(1,std::memory_order_relaxed); + } + } + }); + std::uint64_t ack=0; + for(int i=0;i<1000;++i) { + auto state=makeGraph(10,ack+1,i); + const auto ret=p.publish(std::move(state),ack,10); + if(ret==Publisher::Result::applied) ++ack; + else assert(ret==Publisher::Result::retirementFull); + p.pollRetirement(); + } + running.store(false,std::memory_order_release); + audio.join(); + p.unpublish(); + assert(p.pollRetirement()); + assert(SpyGraph::alive==0); +} From 1372fb6889334e62f71fd6aa67040eeb0a56121b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 06:58:00 +0700 Subject: [PATCH 05/23] feat(native): opt-in real 10-channel dry callback renderer with exact active pins and epoch ACK --- src/LiveDryRoutingLab.h | 231 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 231 insertions(+) create mode 100644 src/LiveDryRoutingLab.h diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h new file mode 100644 index 000000000..158dd051f --- /dev/null +++ b/src/LiveDryRoutingLab.h @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "../engine/core/PreparedMixerBlock.h" +#include "../engine/core/RealtimeRoutePublisher.h" +#include "../engine/device/LiveInputPortRegistry.h" +#include +#include +#include +#include +#include +#include +#include + +// P1E — user-opt-in, *DRY / NO VST3* physical multichannel routing laboratory. +// Uses the P1D core already on main, not a competing mixer/DSP engine. +// Hardware rate/port identity and DIRECT route authorization are owned by +// LiveAudioEngine. No disk I/O, heap allocation, plugin or device operation +// on process() callback. This is a FAT diagnostic, NOT performance mode. +class LiveDryRoutingLab final { +public: + using Plan=armix::mixer::PreparedRenderGraph; + using Block=armix::mixer::PreparedMixerBlock; + using Publisher=armix::rt::RealtimeRoutePublisher; + static constexpr int count=armix::mixer::stripCount; + + // JUCE calls aboutToStart after configuring the input/output device. + // One device session gets a new epoch; stored route cannot survive it. + void prepareDevice (juce::AudioIODevice* device) noexcept { + enabled_.store(false,std::memory_order_release); + const auto generation=deviceEpoch_.fetch_add(1,std::memory_order_acq_rel)+1; + registryValid_=false; + enabledPorts_.fill(-1); + portCount_=0; + if(!device) return; + const auto mask=device->getActiveInputChannels(); + int bit=mask.findNextSetBit(0); + while(bit>=0) { + if(portCount_>=armix::device::LiveInputPortRegistry::limit) + return; // no silent truncation + enabledPorts_[portCount_++]=bit; + bit=mask.findNextSetBit(bit+1); + } + armix::device::LiveInputPortRegistry::Fault fault; + registryValid_=armix::device::LiveInputPortRegistry::prepare( + generation,{enabledPorts_.data(),static_cast(portCount_)}, + registry_,fault); + callbackInputCount_.store(portCount_,std::memory_order_release); + } + void deviceStopped() noexcept { + enabled_.store(false,std::memory_order_release); + deviceEpoch_.fetch_add(1,std::memory_order_acq_rel); + callbackInputCount_.store(-1,std::memory_order_release); + peakL_.store(0.f,std::memory_order_relaxed); + peakR_.store(0.f,std::memory_order_relaxed); + } + + juce::String apply (const juce::var& command, bool directPermitted, + bool independentClock, int loadedFx) { + // Called by the native message thread only. Not callable from RT. + if(!directPermitted || independentClock) + return "Dry Routing LAB requires one verified DIRECT audio device"; + if(loadedFx>0) + return "Disable/remove Channel 1 VST3 before DRY Routing LAB (no plugin state is touched)"; + if(!registryValid_ || portCount_==0) + return "Audio device has no validated active capture ports"; + if(!command.isObject()) return "Invalid Dry Routing configuration"; + const auto currentEpoch=deviceEpoch_.load(std::memory_order_acquire); + const auto expectedEpoch=static_cast( + static_cast(command.getProperty("deviceEpoch",juce::var(0)))); + const auto expectedRevision=static_cast( + static_cast(command.getProperty("revision",juce::var(0)))); + if(currentEpoch==0 || expectedEpoch!=currentEpoch) + return "Audio device changed: reopen ROUTING to remap physical ports"; + auto* assignments=command.getProperty("channels",{}).getArray(); + if(!assignments || assignments->size()!=count) + return "Supply exactly 10 explicit channel assignments"; + armix::mixer::ChannelRoutingConfig cfg; + for(int i=0;igetReference(i); + if(!item.isObject())return "Invalid channel assignment"; + const auto mode=item.getProperty("mode",{}).toString(); + const auto left=item.getProperty("left",-1); + const auto right=item.getProperty("right",-1); + const auto gain=item.getProperty("gain",0.25); + if(!left.isInt()||!right.isInt()||!(gain.isDouble()||gain.isInt())) + return "Invalid input port number or channel level"; + const float level=static_cast(static_cast(gain)); + if(!std::isfinite(level)||level<0.f||level>1.f) + return "Channel level must be 0..1"; + auto& c=cfg.stripsAndMaster.strips[i]; + c.faderLinear=level; + c.pan=0.f; + if(mode=="NONE") { + c.source=armix::mixer::SourceMode::disconnected; + continue; + } + if(mode=="MONO") { + c.source=armix::mixer::SourceMode::mono; + c.inputA=static_cast(left); + cfg.formats[i]=armix::mixer::ChannelFormat::mono; + } else if(mode=="STEREO") { + c.source=armix::mixer::SourceMode::stereo; + c.inputA=static_cast(left); + c.inputB=static_cast(right); + cfg.formats[i]=armix::mixer::ChannelFormat::stereo; + } else return "Channel format must be NONE, MONO or STEREO"; + } + armix::mixer::SendRequest sends; // hardware dry FAT, no FX/send fabric yet + Plan plan; + armix::mixer::RenderError error; + if(!Plan::compile(cfg, + {enabledPorts_.data(),static_cast(portCount_)}, + sends,plan,error)) + return "Invalid physical routing (inactive port, format or mapping)"; + const auto revision=expectedRevision+1; + if(revision==0) return "Routing revision overflow"; + auto next=std::make_unique(); + next->deviceEpoch=currentEpoch; + next->graphRevision=revision; + next->prepared=std::make_unique(plan,Block::hardFrameLimit); + if(!next->prepared || next->prepared->capacity()==0) + return "Cannot allocate routing workspace"; + const auto result=publisher_.publish(std::move(next),expectedRevision,currentEpoch); + switch(result) { + case Publisher::Result::applied: + enabled_.store(true,std::memory_order_release); + return {}; + case Publisher::Result::staleDevice: + return "Device epoch changed during preparation"; + case Publisher::Result::staleRevision: + return "Routing changed elsewhere: refresh before applying"; + case Publisher::Result::retirementFull: + return "Routing edits are too fast; retry after callback retirement"; + default: + return "Invalid prepared route"; + } + } + + void disable() noexcept { + enabled_.store(false,std::memory_order_release); + publisher_.unpublish(); // control thread only + peakL_.store(0.f,std::memory_order_relaxed); + peakR_.store(0.f,std::memory_order_relaxed); + } + void poll() noexcept {publisher_.pollRetirement();} // message thread + bool active() const noexcept {return enabled_.load(std::memory_order_acquire);} + std::uint64_t epoch() const noexcept { + return deviceEpoch_.load(std::memory_order_acquire); + } + std::uint64_t revision() const noexcept {return publisher_.lastRevision();} // control only + + // JUCE render callback, with a verified single-clock device. Routing + // publishes at the BLOCK boundary. Missing/stale ports output SILENCE. + // A failed run never falls through to an unrelated microphone/plugin path. + bool process(const float* const* inputs,int inputCount, + float* const* outputs,int outputCount,int frames, + float masterGain,bool masterMuted) noexcept { + if(!active())return false; + if(frames<=0)return true; + for(int c=0;cprepared || + inputCount!=callbackInputCount_.load(std::memory_order_acquire)) + return true; + // Large/variable JUCE quantum is chunked using stack pointer views; + // no heap allocation or new processing object inside callback. + std::array shifted{}; + constexpr int max=Block::hardFrameLimit; + const auto noFx=[](int,float*,float*,int) noexcept {}; + float peakL=0.f,peakR=0.f; + for(int offset=0;offsetprepared->process(shifted.data(),inputCount, + outputs[0]+offset,outputs[1]+offset,n,noFx,&level)) + return true; + const float g=masterMuted?0.f:std::clamp(masterGain,0.f,2.f); + for(int i=0;i(); + out->setProperty("active",active()); + out->setProperty("epoch",static_cast(epoch())); + out->setProperty("revision",static_cast(revision())); + out->setProperty("peakL",peakL_.load(std::memory_order_relaxed)); + out->setProperty("peakR",peakR_.load(std::memory_order_relaxed)); + juce::Array ports; + if(device && registryValid_) { + const auto names=device->getInputChannelNames(); + for(int i=0;i(); + p->setProperty("port",physical); + p->setProperty("callback",i); + p->setProperty("label",physicalsetProperty("ports",juce::var(ports)); + out->setProperty("note","EXPLICIT DRY HARDWARE FAT ONLY: no channel VST3, no sends, no portable route persistence"); + return juce::var(out.release()); + } +private: + Publisher publisher_; + armix::device::LiveInputPortRegistry registry_; // device lifecycle only + std::array enabledPorts_{}; + int portCount_=0; + bool registryValid_=false; + std::atomic deviceEpoch_{0}; + std::atomic callbackInputCount_{-1}; + std::atomic enabled_{false}; + std::atomic peakL_{0.f},peakR_{0.f}; +}; From 31a9a7c78b4a061832d5d3d19b93c8b64a003055 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 06:58:27 +0700 Subject: [PATCH 06/23] fix(native): hold JUCE var assignment lifetime and bound callback port array --- src/LiveDryRoutingLab.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 158dd051f..e2d52031f 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -4,6 +4,7 @@ #include "../engine/core/RealtimeRoutePublisher.h" #include "../engine/device/LiveInputPortRegistry.h" #include +#include #include #include #include @@ -71,7 +72,8 @@ class LiveDryRoutingLab final { static_cast(command.getProperty("revision",juce::var(0)))); if(currentEpoch==0 || expectedEpoch!=currentEpoch) return "Audio device changed: reopen ROUTING to remap physical ports"; - auto* assignments=command.getProperty("channels",{}).getArray(); + const auto values=command.getProperty("channels",{}); + auto* assignments=values.getArray(); if(!assignments || assignments->size()!=count) return "Supply exactly 10 explicit channel assignments"; armix::mixer::ChannelRoutingConfig cfg; @@ -160,7 +162,9 @@ class LiveDryRoutingLab final { for(int c=0;carmix::device::LiveInputPortRegistry::limit) + return true; const auto generation=epoch(); auto lease=publisher_.acquire(); const auto* snapshot=lease.get(generation); From 20f68533905c049a8abb4a6b41290fd7fa442c6b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 06:59:30 +0700 Subject: [PATCH 07/23] safety(audio): retain explicit dry-lab silence after hotplug instead of falling through to CH1 --- src/LiveDryRoutingLab.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index e2d52031f..04be25810 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -27,7 +27,8 @@ class LiveDryRoutingLab final { // JUCE calls aboutToStart after configuring the input/output device. // One device session gets a new epoch; stored route cannot survive it. void prepareDevice (juce::AudioIODevice* device) noexcept { - enabled_.store(false,std::memory_order_release); + // Preserve explicit LAB ownership across hotplug; the new epoch + // makes the old prepared graph return silence, NEVER CH1 fallthrough. const auto generation=deviceEpoch_.fetch_add(1,std::memory_order_acq_rel)+1; registryValid_=false; enabledPorts_.fill(-1); @@ -48,7 +49,8 @@ class LiveDryRoutingLab final { callbackInputCount_.store(portCount_,std::memory_order_release); } void deviceStopped() noexcept { - enabled_.store(false,std::memory_order_release); + // Epoch invalidates output while LAB mode remains fail-closed until + // the operator explicitly disables it or applies a new device map. deviceEpoch_.fetch_add(1,std::memory_order_acq_rel); callbackInputCount_.store(-1,std::memory_order_release); peakL_.store(0.f,std::memory_order_relaxed); From 59aab264af8b5d3bd5e7a360d612bed12d1e3aad Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:00:26 +0700 Subject: [PATCH 08/23] feat(native): wire opt-in DRY 10-channel routing into verified JUCE callback without changing legacy CH1 default --- src/LiveAudioEngine.h | 62 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index b25357a2e..eee09f130 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -6,6 +6,7 @@ #include "NativePresetArchive.h" #include "VstBusLayout.h" #include "LiveGraphHandoff.h" +#include "LiveDryRoutingLab.h" #include "DiagnosticTone.h" #include "../engine/device/JuceIndependentClockDevice.h" #include "../engine/device/AsioPriorityDeviceManager.h" @@ -196,6 +197,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void stop() { + dryRoutingLab_.disable(); directFence_.suspend(); asioPinnedRegistration_ = {}; asioRegistrationScope_ = "NONE"; @@ -210,6 +212,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } graphOwned_->count = 0; deviceManager_.closeAudioDevice(); + dryRoutingLab_.poll(); } void setMonitorEnabled (bool value) noexcept { monitor_.store (value); } @@ -261,6 +264,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String setIndependentClockEnabled (bool wanted) { + if (dryRoutingLab_.active()) return "Stop DRY ROUTING LAB before changing the device clock"; if (handoff_.busy()) return "Finish pending VST3 graph switch before changing audio backend"; if (wanted == independent_.active() && !(savedDirectSetup_ && !wanted)) return {}; if (wanted && savedDirectSetup_) return "Restore old device backend before another transition"; @@ -344,6 +348,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // user setup is restored on exit; temporary routes must not be persisted. juce::String setDiagnosticRoute (armix::diagnostics::Route wanted) { + if (dryRoutingLab_.active()) return "Stop DRY ROUTING LAB before changing SIGNAL CHECK"; using Route = armix::diagnostics::Route; if (handoff_.busy()) return "Finish the pending FX graph transition first"; if (independent_.active()) return "Disable independent clock mode before endpoint isolation tests"; @@ -748,13 +753,32 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return true; } + // Explicit message-thread transaction. NO VST is processed in this LAB. + juce::String applyDryRoutingLab (const juce::var& command) { + if (handoff_.busy()) return "A VST3 graph handoff is in progress"; + if (routeReconfiguring_.load(std::memory_order_acquire)) + return "Audio device is changing; retry when stable"; + if (diagnosticRoute_.load(std::memory_order_acquire) + != armix::diagnostics::Route::normal) + return "Return SIGNAL CHECK to NORMAL before routing LAB"; + if (savedDirectSetup_ || savedLiveSetup_) + return "Restore the full DIRECT audio device before routing LAB"; + return dryRoutingLab_.apply(command,directFence_.permitted(), + independent_.active(),graphOwned_->count); + } + void disableDryRoutingLab() noexcept {dryRoutingLab_.disable();} + bool dryRoutingLabActive() const noexcept {return dryRoutingLab_.active();} + void pollDryRoutingLab() noexcept {dryRoutingLab_.poll();} + juce::var status() { + dryRoutingLab_.poll(); // off-RT reclaim after callback quiescence auto o = std::make_unique(); const bool dual = independent_.active(); auto* d = dual ? independent_.renderDevice() : deviceManager_.getCurrentAudioDevice(); auto* capture = dual ? independent_.captureDevice() : d; + o->setProperty ("dryRoutingLab",dryRoutingLab_.status(capture)); o->setProperty ("connected", d != nullptr && capture != nullptr); o->setProperty ("adaptiveClockActive", dual); o->setProperty ("adaptiveClockFaulted", dual && independent_.faulted()); @@ -1013,6 +1037,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::AudioBuffer scratch_; juce::AudioBuffer dryScratch_; armix::diagnostics::DiagnosticTone diagnosticTone_; + LiveDryRoutingLab dryRoutingLab_; std::atomic diagnosticRoute_ {armix::diagnostics::Route::normal}; std::atomic routeReconfiguring_ {false}; std::optional savedLiveSetup_; @@ -1096,6 +1121,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void audioDeviceAboutToStart (juce::AudioIODevice* d) override { + dryRoutingLab_.prepareDevice(d); // exact active mask, before callback if (!independent_.active()) { const auto backend=d->getTypeName(); @@ -1138,6 +1164,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void audioDeviceStopped() override { + dryRoutingLab_.deviceStopped(); deviceStopCount_.fetch_add (1, std::memory_order_relaxed); inputPeak_.store (0.f); outputPeak_.store (0.f); @@ -1194,6 +1221,41 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback callbackInputs_.store (inputChannels, std::memory_order_relaxed); callbackOutputs_.store (outputChannels, std::memory_order_relaxed); callbackCount_.fetch_add (1, std::memory_order_relaxed); + // P1E: the LIVE dry-routed 10-strip path is an explicit operator + // action, with an immutable preallocated P1D graph. Its own zero-VST + // callback path NEVER falls through to CH1 on stale/hotplug routes. + // DirectFence was already checked above; no output to unknown device. + if (dryRoutingLab_.active()) + { + const bool outputPermitted = monitor_.load(std::memory_order_relaxed) + && !routeReconfiguring_.load(std::memory_order_acquire) + && !masterMute_.load(std::memory_order_relaxed) + && activeDiagnosticRoute == armix::diagnostics::Route::normal + && !independent_.active(); + (void) dryRoutingLab_.process(inputs,inputChannels,outputs, + outputChannels,samples, + masterGain_.load(std::memory_order_relaxed), + !outputPermitted); + // Only measured output levels, not fake VST or other-strip meters. + const float left=dryRoutingLab_.peakLeft(); + const float right=dryRoutingLab_.peakRight(); + inputPeak_.store(0.f,std::memory_order_relaxed); + postFxPeak_.store(juce::jmin(1.f,juce::jmax(left,right)),std::memory_order_relaxed); + outputPeakL_.store(juce::jmin(1.f,left),std::memory_order_relaxed); + outputPeakR_.store(juce::jmin(1.f,right),std::memory_order_relaxed); + outputPeak_.store(juce::jmin(1.f,juce::jmax(left,right)),std::memory_order_relaxed); + // Existing FX graph is excluded at enable time. A structural + // edit during LAB is rejected on the control thread. + const auto elapsed=clockMicros()-beginUs; + lastCallbackUs_.store(elapsed,std::memory_order_relaxed); + publishMax(worstCallbackUs_,elapsed); + realtimeHistogram_.observe(elapsed,periodUs); + if(static_cast(elapsed)>periodUs*0.80) + slowCallbacks_.fetch_add(1,std::memory_order_relaxed); + if(static_cast(elapsed)>periodUs) + overBudgetCallbacks_.fetch_add(1,std::memory_order_relaxed); + return; + } const bool enabled = monitor_.load (std::memory_order_relaxed) && !routeReconfiguring_.load (std::memory_order_acquire); const auto route = diagnosticRoute_.load (std::memory_order_relaxed); From 0182c4c55e20acb98fa93fe9586f9cfbd55f98c5 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:00:52 +0700 Subject: [PATCH 09/23] fix(native): expose truthful dry LAB levels and reset stale peaks on route failure --- src/LiveDryRoutingLab.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 04be25810..aa49c94b7 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -148,6 +148,8 @@ class LiveDryRoutingLab final { } void poll() noexcept {publisher_.pollRetirement();} // message thread bool active() const noexcept {return enabled_.load(std::memory_order_acquire);} + float peakLeft() const noexcept {return peakL_.load(std::memory_order_relaxed);} + float peakRight() const noexcept {return peakR_.load(std::memory_order_relaxed);} std::uint64_t epoch() const noexcept { return deviceEpoch_.load(std::memory_order_acquire); } @@ -160,6 +162,9 @@ class LiveDryRoutingLab final { float* const* outputs,int outputCount,int frames, float masterGain,bool masterMuted) noexcept { if(!active())return false; + // Stale meters must never survive a failed device/epoch mapping. + peakL_.store(0.f,std::memory_order_relaxed); + peakR_.store(0.f,std::memory_order_relaxed); if(frames<=0)return true; for(int c=0;c Date: Wed, 28 Oct 2026 07:01:19 +0700 Subject: [PATCH 10/23] safety(native): prohibit plugin graph edits and snapshot actions during active dry multi-input FAT --- src/LiveAudioEngine.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index eee09f130..c7a7ef38d 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -513,6 +513,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String addVst3 (const juce::String& filename, int uid, const juce::String& catalogId) { + if (dryRoutingLab_.active()) return "Stop DRY ROUTING LAB before editing VST3"; 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(); @@ -563,6 +564,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // exactly once, no plugin state methods ever execute on the audio thread. juce::String captureSnapshot (armix::storage::Snapshot& snapshot) { + if (dryRoutingLab_.active()) return "Stop DRY ROUTING LAB before saving native FX state"; 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(); @@ -609,6 +611,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // or destroys a plugin. No manual output mute is required for recall. juce::String restoreSnapshot (const armix::storage::Snapshot& snapshot) { + if (dryRoutingLab_.active()) return "Stop DRY ROUTING LAB before preset recall"; if (handoff_.busy()) return "A live FX graph transition is already in progress"; if (snapshot.effects.size() > maxFx) return "Too many plugins in preset"; @@ -721,6 +724,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool removeAt (int index) { + if (dryRoutingLab_.active()) return false; if (handoff_.busy()) return false; if (index < 0 || index >= graphOwned_->count) return false; detach(); @@ -737,6 +741,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool moveSlot (int from, int to) { + if (dryRoutingLab_.active()) return false; if (handoff_.busy()) return false; if (from < 0 || from >= graphOwned_->count || to < 0 || to >= graphOwned_->count || from == to) return false; From d30d44c0c1f29514ce6d58d06479ec63a6814fee Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:01:38 +0700 Subject: [PATCH 11/23] feat(ui bridge): expose explicit native ten-channel dry Apply/Stop with ACK and diagnostics --- src/Main.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/Main.cpp b/src/Main.cpp index 9c515c21a..ef7290a6c 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -837,6 +837,36 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr action == "presetLoad" || action == "presetSave")) return emitNotice ("Return to DIRECT mode before editing VST3 graph (live-safe graph edits are a later gate).", true); + // A user-controlled hardware dry routing FAT, not a change to the + // existing 1-channel VST3 production chain. Explicit Apply/Stop. + if (action == "routingDryApply") + { + const auto error=engine_.applyDryRoutingLab(value); + auto reply=std::make_unique(); + reply->setProperty("ok",error.isEmpty()); + reply->setProperty("error",error); + const auto status=engine_.status().getProperty("dryRoutingLab",{}); + reply->setProperty("state",status); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible( + "arMixRoutingLabAck",juce::var(reply.release())); + if(error.isNotEmpty())return emitNotice(error,true); + diagnostics_.record("LIVE_DRY_ROUTING_LAB_APPLIED", + "No VST3 | actual enabled hardware mask and epoch verified"); + return emitNotice( + "DRY ROUTING LAB active: 10 native input strips, NO FX. " + "Use low headphone volume. Stop LAB before loading VST3."); + } + if (action == "routingDryStop") + { + engine_.disableDryRoutingLab(); + diagnostics_.record("LIVE_DRY_ROUTING_LAB_STOP","Restored native CH1 production path"); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible( + "arMixRoutingLabAck",engine_.status().getProperty("dryRoutingLab",{})); + return emitNotice("DRY ROUTING LAB stopped. Native CH1 path restored."); + } + if (action == "smartClock") { if (!value.isBool()) return emitNotice ("Invalid smart clock command", true); From 3a90b1814ab1222ce54ccf0c2baa2bdfbadfab84 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:03:01 +0700 Subject: [PATCH 12/23] feat(ui): add compact real hardware routing inspector with native transactional ACK --- web/monitor.js | 94 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 93 insertions(+), 1 deletion(-) diff --git a/web/monitor.js b/web/monitor.js index a84f80e2a..17a777587 100644 --- a/web/monitor.js +++ b/web/monitor.js @@ -21,6 +21,17 @@ "#arDiagnosticCopy{color:#e1f7f4;background:#166052;border:1px solid #34c8ac;border-radius:4px;padding:7px 12px;cursor:pointer}" + "#arDiagnosticCopyStatus{color:#8cdec9;font-size:10px}" + "#arSmartClockToggle{color:#f5eadb;background:#284961;border:1px solid #9bb2c5;border-radius:4px;padding:7px 12px;cursor:pointer}"; + // No blur, no animated shaders or per-strip timer. Routing draws only + // on explicit user edit; existing native health polling stays at 12 Hz. + css.textContent += + "#arRoutingLabOverlay{display:none;position:fixed;inset:0;z-index:995;background:#08121be8;align-items:center;justify-content:center}" + + "#arRoutingLabOverlay.open{display:flex}#arRoutingLabPanel{width:min(760px,94vw);max-height:86vh;overflow:auto;box-sizing:border-box;padding:16px;background:#172834;border:1px solid #637e8a;border-radius:8px;color:#dcecf3}" + + "#arRoutingLabPanel h2{font-size:17px;font-weight:600;margin:0 0 6px}#arRoutingLabPanel p{font-size:11px;line-height:1.6;color:#9cc5d4;margin:6px 0 13px}" + + ".arRouteRow{display:grid;grid-template-columns:60px 105px 1fr 1fr 110px;gap:6px;align-items:center;padding:5px 0;border-bottom:1px solid #2d4653}" + + ".arRouteRow label{font-size:11px;font-weight:600}.arRouteRow select{width:100%;min-width:0;padding:6px;background:#0d202b;border:1px solid #4d6879;border-radius:4px;color:#e1eef5;font-size:11px}" + + ".arRouteFoot{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end;margin-top:12px}.arRouteFoot button,.arRouteClose{color:#f0f7fa;background:#24475a;border:1px solid #587f91;border-radius:4px;padding:8px 12px;cursor:pointer}" + + "#arRouteApply{background:#237566;border-color:#4ba48d}#arRouteStop{background:#50343c;border-color:#a8717c}" + + "#arRouteFeedback{font-size:11px;min-height:18px;color:#8bdec1;margin-top:10px}"; document.head.appendChild(css); // Signal Check is declared in the permanent toolbar; footer holds status only. const overlay = document.createElement("div"); @@ -34,7 +45,7 @@ '
Reading native audio state...
' + '
' + '' + - '
' + + '' + '
' + ''+ + ['NONE','MONO','STEREO'].map(m=>'').join('')+''+ + ''+ + ''+ + '
'; + }).join(''); + rows.querySelectorAll('[data-route-row]').forEach(row=>{ + const model=draftRoutes[Number(row.dataset.routeRow)]; + row.querySelector('[data-route-mode]').addEventListener('change',e=>{model.mode=e.target.value;refreshMode(row);}); + row.querySelector('[data-route-left]').addEventListener('change',e=>{model.left=Number(e.target.value);}); + row.querySelector('[data-route-right]').addEventListener('change',e=>{model.right=Number(e.target.value);}); + row.querySelector('[data-route-gain]').addEventListener('change',e=>{model.gain=Number(e.target.value);}); + refreshMode(row); + }); + updateRouteLabIdentity(); + } + function refreshMode(row){ + const type=row.querySelector('[data-route-mode]').value; + row.querySelector('[data-route-left]').disabled=type==="NONE"; + row.querySelector('[data-route-right]').disabled=type!=="STEREO"; + } + function updateRouteLabIdentity(){ + const d=state.dryRoutingLab||{}; + const label=document.getElementById("arRouteIdentity"); + if(!label)return; + setTextIfChanged(label,(d.active ? (d.ready?"DRY LAB ACTIVE":"DRY LAB STALE — SILENT, REAPPLY"):"DRY LAB OFF")+ + " · device epoch "+(d.epoch||0)+" · rev "+(d.revision||0)+ + " · "+(d.ports?.length||0)+" enabled physical inputs"); + } + document.getElementById("arOpenRoutingLab").addEventListener("click",()=>{ + drawRoutes(); + routeOverlay.classList.add("open"); + overlay.classList.remove("open"); + }); + document.getElementById("arRouteClose").addEventListener("click",()=>routeOverlay.classList.remove("open")); + routeOverlay.addEventListener("click",e=>{if(e.target===routeOverlay)routeOverlay.classList.remove("open");}); + document.getElementById("arRouteApply").addEventListener("click",()=>{ + const d=state.dryRoutingLab||{}; + if(!Array.isArray(d.ports)||!d.ports.length){ + document.getElementById("arRouteFeedback").textContent="Select a real ASIO/WASAPI audio input in AUDIO SETUP first.";return; + } + document.getElementById("arRouteFeedback").textContent="Applying to actual native DSP..."; + api.emitEvent("arMixAction",{action:"routingDryApply",value:{ + deviceEpoch:Number(d.epoch)||0,revision:Number(d.revision)||0, + channels:draftRoutes.map(c=>({...c})) + }}); + }); + document.getElementById("arRouteStop").addEventListener("click",()=>api.emitEvent("arMixAction",{action:"routingDryStop"})); + api.addEventListener("arMixRoutingLabAck",reply=>{ + const result=reply?.state||reply||{}; + document.getElementById("arRouteFeedback").textContent= + reply?.ok===false?("REJECTED · "+(reply.error||"Invalid route")): + result.active?"NATIVE ACK: DRY LAB ENABLED · zero VST3 · low headphone volume":"NATIVE ACK: DRY LAB STOPPED"; + updateRouteLabIdentity(); + }); + const el = id => document.getElementById(id); // 12Hz native telemetry must not replace unchanged text nodes or cause // needless main-thread paint/layout invalidations on static header labels. @@ -85,6 +176,7 @@ return "Output armed. Speak into the microphone and inspect all three meters."; } function repaint(d) { + if(routeOverlay.classList.contains("open"))updateRouteLabIdentity(); setTextIfChanged(el("arSignalBadge"),!d.monitor ? "OUTPUT MUTED" : d.masterMute ? "MASTER MUTED" : d.channelMute ? "CH1 MUTED" : "OUTPUT ARMED"); el("arSignalBadge").style.color = d.monitor && !d.masterMute && !d.channelMute ? "#71e9cc" : "#e9be7c"; const monitorButton=document.querySelector('[data-native-action="monitor"]'); From efea4ff890e17a3e7904400a5e81dd5fff22f789 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:04:08 +0700 Subject: [PATCH 13/23] safety(live): require muted output before applying lab routes and mute on return to CH1 --- src/LiveAudioEngine.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index c7a7ef38d..a3771e3cb 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -760,6 +760,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Explicit message-thread transaction. NO VST is processed in this LAB. juce::String applyDryRoutingLab (const juce::var& command) { + if (!isOutputMuted()) return "MUTE OUTPUT before applying physical DRY LAB routing"; if (handoff_.busy()) return "A VST3 graph handoff is in progress"; if (routeReconfiguring_.load(std::memory_order_acquire)) return "Audio device is changing; retry when stable"; @@ -771,7 +772,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return dryRoutingLab_.apply(command,directFence_.permitted(), independent_.active(),graphOwned_->count); } - void disableDryRoutingLab() noexcept {dryRoutingLab_.disable();} + void disableDryRoutingLab() noexcept { + setOutputMuted(true); // never expose CH1 unexpectedly on STOP + dryRoutingLab_.disable(); + } bool dryRoutingLabActive() const noexcept {return dryRoutingLab_.active();} void pollDryRoutingLab() noexcept {dryRoutingLab_.poll();} From f3e7ae97429580449564d7e33c716eb04f02ac72 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:04:57 +0700 Subject: [PATCH 14/23] feat(audio): block-boundary 256-sample de-click and precise stale-device ready status --- src/LiveDryRoutingLab.h | 47 +++++++++++++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 6 deletions(-) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index aa49c94b7..7da1190a4 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -127,6 +127,7 @@ class LiveDryRoutingLab final { const auto result=publisher_.publish(std::move(next),expectedRevision,currentEpoch); switch(result) { case Publisher::Result::applied: + publishedEpoch_.store(currentEpoch,std::memory_order_release); enabled_.store(true,std::memory_order_release); return {}; case Publisher::Result::staleDevice: @@ -142,6 +143,7 @@ class LiveDryRoutingLab final { void disable() noexcept { enabled_.store(false,std::memory_order_release); + publishedEpoch_.store(0,std::memory_order_release); publisher_.unpublish(); // control thread only peakL_.store(0.f,std::memory_order_relaxed); peakR_.store(0.f,std::memory_order_relaxed); @@ -150,6 +152,9 @@ class LiveDryRoutingLab final { bool active() const noexcept {return enabled_.load(std::memory_order_acquire);} float peakLeft() const noexcept {return peakL_.load(std::memory_order_relaxed);} float peakRight() const noexcept {return peakR_.load(std::memory_order_relaxed);} + bool ready() const noexcept { + return active() && publishedEpoch_.load(std::memory_order_acquire)==epoch(); + } std::uint64_t epoch() const noexcept { return deviceEpoch_.load(std::memory_order_acquire); } @@ -176,8 +181,18 @@ class LiveDryRoutingLab final { auto lease=publisher_.acquire(); const auto* snapshot=lease.get(generation); if(!snapshot||!snapshot->prepared || - inputCount!=callbackInputCount_.load(std::memory_order_acquire)) + inputCount!=callbackInputCount_.load(std::memory_order_acquire)) { + fadeRemaining_=0; + lastOutputL_=lastOutputR_=0.f; return true; + } + if(snapshot->graphRevision!=audioRevision_ || generation!=audioEpoch_) { + audioRevision_=snapshot->graphRevision; + audioEpoch_=generation; + fadeRemaining_=rampFrames; + fadeFromL_=lastOutputL_; + fadeFromR_=lastOutputR_; + } // Large/variable JUCE quantum is chunked using stack pointer views; // no heap allocation or new processing object inside callback. std::array shifted{}; @@ -193,12 +208,23 @@ class LiveDryRoutingLab final { outputs[0]+offset,outputs[1]+offset,n,noFx,&level)) return true; const float g=masterMuted?0.f:std::clamp(masterGain,0.f,2.f); - for(int i=0;i0) { + const float t=1.f-static_cast(fadeRemaining_-1)/ + static_cast(rampFrames); + l=fadeFromL_+(l-fadeFromL_)*t; + r=fadeFromR_+(r-fadeFromR_)*t; + --fadeRemaining_; + } + outputs[0][offset+i]=l; + outputs[1][offset+i]=r; + lastOutputL_=l; + lastOutputR_=r; + peakL=std::max(peakL,std::abs(l)); + peakR=std::max(peakR,std::abs(r)); } - peakL=std::max(peakL,level.masterPeakL*g); - peakR=std::max(peakR,level.masterPeakR*g); } peakL_.store(peakL,std::memory_order_relaxed); peakR_.store(peakR,std::memory_order_relaxed); @@ -208,6 +234,7 @@ class LiveDryRoutingLab final { juce::var status(juce::AudioIODevice* device) const { auto out=std::make_unique(); out->setProperty("active",active()); + out->setProperty("ready",ready()); out->setProperty("epoch",static_cast(epoch())); out->setProperty("revision",static_cast(revision())); out->setProperty("peakL",peakL_.load(std::memory_order_relaxed)); @@ -236,7 +263,15 @@ class LiveDryRoutingLab final { int portCount_=0; bool registryValid_=false; std::atomic deviceEpoch_{0}; + std::atomic publishedEpoch_{0}; std::atomic callbackInputCount_{-1}; std::atomic enabled_{false}; std::atomic peakL_{0.f},peakR_{0.f}; + // Exclusive render-producer state. Bounded fade starts from the exact + // previously output sample, preventing a topology switch discontinuity. + static constexpr int rampFrames=256; + int fadeRemaining_=0; + std::uint64_t audioRevision_=0,audioEpoch_=0; + float fadeFromL_=0.f,fadeFromR_=0.f; + float lastOutputL_=0.f,lastOutputR_=0.f; }; From f2df0295d1e4eea2909bc0f13593a7b2faf2e924 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:05:27 +0700 Subject: [PATCH 15/23] build: compile native live dry-routable JUCE host and P1E concurrent epoch safety CTest --- CMakeLists.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 298af93ce..4e4d34859 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/VstOrbitController.h engine/core/MixerRoutingPlan.h engine/core/ChannelRoutingContract.h engine/core/ChannelSendPlan.h engine/core/PreparedMixerBlock.h engine/core/OrbitPhase.h engine/core/OrbitControlPolicy.h engine/core/OrbitMotion.h engine/core/OrbitDistanceMapping.h engine/core/DearVrPolarPolicy.h src/PluginCatalog.h src/PluginVault.h src/PortableWorkspace.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/core/CallbackCadenceEvidence.h engine/diagnostics/CrackleEvidenceWindow.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h engine/device/PeriodCapabilityEvidence.h engine/device/SessionLifecycle.h engine/device/WasapiCapabilityProbe.h engine/device/JuceIndependentClockDevice.h engine/device/ClockBridgeSizing.h engine/device/IndependentStreamFormatFence.h engine/device/DirectRestoreBackoff.h engine/device/IndependentStreamWatchdog.h engine/device/BridgeContinuityGate.h engine/device/EndpointIdentityPolicy.h engine/device/WasapiEndpointIdentityGuard.h engine/device/AsioStartupPolicy.h engine/device/AsioPriorityDeviceManager.h engine/device/AsioRegistrationPolicy.h engine/device/AsioRegistryIdentityProbe.h engine/device/DirectRouteFence.h) +target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/VstOrbitController.h engine/core/MixerRoutingPlan.h engine/core/ChannelRoutingContract.h engine/core/ChannelSendPlan.h engine/core/PreparedMixerBlock.h engine/core/RealtimeRoutePublisher.h engine/device/LiveInputPortRegistry.h src/LiveDryRoutingLab.h engine/core/OrbitPhase.h engine/core/OrbitControlPolicy.h engine/core/OrbitMotion.h engine/core/OrbitDistanceMapping.h engine/core/DearVrPolarPolicy.h src/PluginCatalog.h src/PluginVault.h src/PortableWorkspace.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/core/CallbackCadenceEvidence.h engine/diagnostics/CrackleEvidenceWindow.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h engine/device/PeriodCapabilityEvidence.h engine/device/SessionLifecycle.h engine/device/WasapiCapabilityProbe.h engine/device/JuceIndependentClockDevice.h engine/device/ClockBridgeSizing.h engine/device/IndependentStreamFormatFence.h engine/device/DirectRestoreBackoff.h engine/device/IndependentStreamWatchdog.h engine/device/BridgeContinuityGate.h engine/device/EndpointIdentityPolicy.h engine/device/WasapiEndpointIdentityGuard.h engine/device/AsioStartupPolicy.h engine/device/AsioPriorityDeviceManager.h engine/device/AsioRegistrationPolicy.h engine/device/AsioRegistryIdentityProbe.h engine/device/DirectRouteFence.h) target_compile_definitions(ARMixConsole PRIVATE JUCE_WEB_BROWSER=1 JUCE_USE_WIN_WEBVIEW2=1 @@ -59,6 +59,9 @@ if(BUILD_TESTING) add_executable(ARMixPreparedMixerBlockTests tests/prepared_mixer_block_test.cpp) target_compile_features(ARMixPreparedMixerBlockTests PRIVATE cxx_std_20) add_test(NAME TenChannelEndToEndPreparedAudioRender COMMAND ARMixPreparedMixerBlockTests) + add_executable(ARMixLiveRoutingEpochTests tests/live_port_epoch_publisher_test.cpp) + target_compile_features(ARMixLiveRoutingEpochTests PRIVATE cxx_std_20) + add_test(NAME P1ELivePortGenerationRevisionAndRealtimeRetirement COMMAND ARMixLiveRoutingEpochTests) add_executable(ARMixOrbitPhaseTests tests/orbit_phase_test.cpp) target_compile_features(ARMixOrbitPhaseTests PRIVATE cxx_std_20) add_test(NAME VstAzimuthOrbitRamp COMMAND ARMixOrbitPhaseTests) From 816df95e57644469496b5776925e574e43246ccd Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:05:30 +0700 Subject: [PATCH 16/23] ci: compile and execute P1E native route publication tests in existing Windows gate --- .github/workflows/p1-windows.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index a8c009405..f65898b27 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -89,7 +89,7 @@ jobs: -DBUILD_TESTING=ON -DJUCE_WEBVIEW2_PACKAGE_LOCATION="${{ github.workspace }}/.deps" - name: Build executable and native RT tests - run: cmake --build build --config Release --target ARMixConsole ARMixMixerRoutingTests ARMixChannelRoutingContractTests ARMixChannelSendTests ARMixPreparedMixerBlockTests ARMixWorkspaceTests ARMixVaultTests ARMixOrbitPhaseTests ARMixOrbitControlTests ARMixOrbitMotionTests ARMixOrbitDistanceTests ARMixFxBypassEnvelopeTests ARMixDearVrPolarPolicyTests ARMixRTTests ARMixPresetTests ARMixDiagnosticTests ARMixClockBridgeTests ARMixVirtualClockSoakTests ARMixCadenceTests ARMixCrackleWindowTests ARMixHealthTests ARMixPolicyTests ARMixPeriodEvidenceTests ARMixLifecycleTests ARMixWasapiProbeTests ARMixDualJuceTests ARMixClockSizingTests ARMixIndependentFormatTests ARMixRecoveryTests ARMixStreamWatchdogTests ARMixBridgeContinuityTests ARMixEndpointPolicyTests ARMixEndpointGuardTests ARMixAsioPolicyTests ARMixAsioBackendTests ARMixAsioRegistryIdentityTests ARMixDirectFenceTests --parallel 2 + run: cmake --build build --config Release --target ARMixConsole ARMixMixerRoutingTests ARMixChannelRoutingContractTests ARMixChannelSendTests ARMixPreparedMixerBlockTests ARMixLiveRoutingEpochTests ARMixWorkspaceTests ARMixVaultTests ARMixOrbitPhaseTests ARMixOrbitControlTests ARMixOrbitMotionTests ARMixOrbitDistanceTests ARMixFxBypassEnvelopeTests ARMixDearVrPolarPolicyTests ARMixRTTests ARMixPresetTests ARMixDiagnosticTests ARMixClockBridgeTests ARMixVirtualClockSoakTests ARMixCadenceTests ARMixCrackleWindowTests ARMixHealthTests ARMixPolicyTests ARMixPeriodEvidenceTests ARMixLifecycleTests ARMixWasapiProbeTests ARMixDualJuceTests ARMixClockSizingTests ARMixIndependentFormatTests ARMixRecoveryTests ARMixStreamWatchdogTests ARMixBridgeContinuityTests ARMixEndpointPolicyTests ARMixEndpointGuardTests ARMixAsioPolicyTests ARMixAsioBackendTests ARMixAsioRegistryIdentityTests ARMixDirectFenceTests --parallel 2 - name: Test realtime control primitives run: ctest --test-dir build -C Release --output-on-failure - name: Package verified JUCE GUI for hardware FAT From 26aa1b13e2e0c482931021f1b0d62651d542a40e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:06:08 +0700 Subject: [PATCH 17/23] fix(ui): truthful dry LAB 10-channel metering/status and safe mute-before-apply guidance --- web/monitor.js | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/web/monitor.js b/web/monitor.js index 17a777587..ae3618ece 100644 --- a/web/monitor.js +++ b/web/monitor.js @@ -124,7 +124,7 @@ if(!Array.isArray(d.ports)||!d.ports.length){ document.getElementById("arRouteFeedback").textContent="Select a real ASIO/WASAPI audio input in AUDIO SETUP first.";return; } - document.getElementById("arRouteFeedback").textContent="Applying to actual native DSP..."; + document.getElementById("arRouteFeedback").textContent="Applying native route (output must be MUTED)..."; api.emitEvent("arMixAction",{action:"routingDryApply",value:{ deviceEpoch:Number(d.epoch)||0,revision:Number(d.revision)||0, channels:draftRoutes.map(c=>({...c})) @@ -133,9 +133,10 @@ document.getElementById("arRouteStop").addEventListener("click",()=>api.emitEvent("arMixAction",{action:"routingDryStop"})); api.addEventListener("arMixRoutingLabAck",reply=>{ const result=reply?.state||reply||{}; + if(result && typeof result==="object" && "epoch" in result)state.dryRoutingLab=result; document.getElementById("arRouteFeedback").textContent= reply?.ok===false?("REJECTED · "+(reply.error||"Invalid route")): - result.active?"NATIVE ACK: DRY LAB ENABLED · zero VST3 · low headphone volume":"NATIVE ACK: DRY LAB STOPPED"; + result.active?"NATIVE ACK: DRY LAB ENABLED · zero VST3 · UNMUTE OUTPUT in SIGNAL CHECK":"NATIVE ACK: STOPPED · output remains MUTED for safety"; updateRouteLabIdentity(); }); @@ -155,6 +156,9 @@ Number(d?.backendXrunCount)>=3 && Number(d?.overBudgetCount)===0; function diagnosis(d) { + if(d.dryRoutingLab?.active) return d.dryRoutingLab.ready? + "Live 10-channel DRY ROUTING LAB: actual native inputs → dry master. No VST3, AUX or snapshot routing. Use low headphone volume.": + "Routing LAB device generation changed. Output is SILENT until you remap the real device and APPLY again."; if(d.diagnosticRoute==="OUTPUT_ONLY_TONE") return "Output-only test: capture endpoint is disconnected. Listen for tone at low headphone volume and click MARK CRACKLE when audible."; if(d.diagnosticRoute==="CAPTURE_ONLY") return "Capture-only test: hardware render endpoint is disconnected. Observe capture input and backend discontinuity count; you should hear no audio."; if(d.diagnosticRoute==="DRY_THROUGH") return "Dry-through test: microphone to output with all VST3 bypassed. MARK CRACKLE at audible glitches."; @@ -190,14 +194,15 @@ const driverLabel=document.querySelector('.spec-device strong'); setTextIfChanged(driverLabel,d.driver||"NO DRIVER"); const liveLabel=document.querySelector('.status > span:first-child > b'); - setTextIfChanged(liveLabel,"NATIVE CH1"); + setTextIfChanged(liveLabel,d.dryRoutingLab?.active?"NATIVE DRY 10CH LAB":"NATIVE CH1"); const edition=document.querySelector('.status > span:last-child'); - setTextIfChanged(edition,"AR MIX P2 · CH1 NATIVE + UI PREVIEW"); + setTextIfChanged(edition,d.dryRoutingLab?.active? + "AR MIX P1E · REAL DRY ROUTES / FX DISABLED":"AR MIX P2 · CH1 NATIVE + UI PREVIEW"); if (!overlay.classList.contains("open")) return; - el("arInputName").textContent=d.diagnosticRoute==="OUTPUT_ONLY_TONE"?"INTERNAL TEST TONE":d.inputDevice||"Input device"; - el("arFxName").textContent=d.diagnosticRoute==="OUTPUT_ONLY_TONE"?"NO INPUT / NO FX":d.diagnosticRoute!=="NORMAL"?"NO FX":d.dryTest?"DRY BYPASS":"VST3 Chain"; + el("arInputName").textContent=d.dryRoutingLab?.active?"NATIVE 10 CH INPUTS":d.diagnosticRoute==="OUTPUT_ONLY_TONE"?"INTERNAL TEST TONE":d.inputDevice||"Input device"; + el("arFxName").textContent=d.dryRoutingLab?.active?"DRY · ZERO VST3":d.diagnosticRoute==="OUTPUT_ONLY_TONE"?"NO INPUT / NO FX":d.diagnosticRoute!=="NORMAL"?"NO FX":d.dryTest?"DRY BYPASS":"VST3 Chain"; el("arOutputName").textContent=d.outputDevice||"Output device"; - el("arInputBar").style.width=percent(d.inputPeak)+"%"; + el("arInputBar").style.width=percent(d.dryRoutingLab?.active?Math.max(d.dryRoutingLab.peakL||0,d.dryRoutingLab.peakR||0):d.inputPeak)+"%"; el("arFxBar").style.width=percent(d.postFxPeak)+"%"; el("arOutputBar").style.width=percent(d.peak)+"%"; el("arSignalReason").textContent=diagnosis(d); From 37372c4b862147cc1738207868d8b78d9644911a Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:07:12 +0700 Subject: [PATCH 18/23] test(native ui): protect opt-in dry routing truth, safe ACK, device epoch and original CH1 VST behavior --- tests/live_routing_ui_contract_test.mjs | 46 +++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 tests/live_routing_ui_contract_test.mjs diff --git a/tests/live_routing_ui_contract_test.mjs b/tests/live_routing_ui_contract_test.mjs new file mode 100644 index 000000000..f22446a9c --- /dev/null +++ b/tests/live_routing_ui_contract_test.mjs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Native/GUI contract: P1E exposes REAL channel routing only under explicit +// muted-output operator action and never falsely marks CH2-10 VST inserts live. +import { readFileSync } from "node:fs"; +import assert from "node:assert/strict"; +import test from "node:test"; + +const engine=readFileSync(new URL("../src/LiveAudioEngine.h",import.meta.url),"utf8"); +const lab=readFileSync(new URL("../src/LiveDryRoutingLab.h",import.meta.url),"utf8"); +const main=readFileSync(new URL("../src/Main.cpp",import.meta.url),"utf8"); +const ui=readFileSync(new URL("../web/monitor.js",import.meta.url),"utf8"); +const bridge=readFileSync(new URL("../web/bridge.js",import.meta.url),"utf8"); + +test("P1E is opt-in; all native VST3/clock/diagnostic paths protected",()=>{ + assert.match(engine,/dryRoutingLab_\.active\(\)/); + assert.match(engine,/!isOutputMuted\(\).*MUTE OUTPUT/); + assert.match(engine,/setOutputMuted\(true\); \/\/ never expose CH1 unexpectedly/); + assert.match(engine,/dryRoutingLab_\.prepareDevice\(d\)/); + assert.match(engine,/dryRoutingLab_\.deviceStopped\(\)/); + assert.match(engine,/dryRoutingLab_\.process\(inputs,inputChannels,outputs/); + assert.match(engine,/if \(dryRoutingLab_\.active\(\)\) return "Stop DRY ROUTING LAB before editing VST3"/); + assert.match(engine,/if \(dryRoutingLab_\.active\(\)\) return "Stop DRY ROUTING LAB before preset recall"/); + assert.match(lab,/publisher_\.publish/); + assert.match(lab,/deviceEpoch_/); + assert.match(lab,/Block::hardFrameLimit/); + assert.match(lab,/rampFrames=256/); + assert.match(lab,/publishedEpoch_\.load/); + assert.match(lab,/std::array/); +}); +test("GUI exposes only truthful dry device routes and acknowledged commit",()=>{ + assert.match(ui,/ROUTING LAB · 10 CH/); + assert.match(ui,/routingDryApply/); + assert.match(ui,/routingDryStop/); + assert.match(ui,/arMixRoutingLabAck/); + assert.match(ui,/data-route-left/); + assert.match(ui,/data-route-right/); + assert.match(ui,/status|DRY LAB STALE/); + assert.match(ui,/No VST3|no VST3|no channel VST3|no VST3/i); + assert.match(main,/action == "routingDryApply"/); + assert.match(main,/action == "routingDryStop"/); + assert.match(main,/arMixRoutingLabAck/); + // Default 10 fake preview strips are intentionally not made into VST3 + // controls by the dry hardware test. + assert.match(bridge,/if\(i!==0\)/); + assert.match(bridge,/track\.dataset\.preview="1"/); +}); From 5fcd7aa951c0c3e44397224f4445dd712621d7fc Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:08:14 +0700 Subject: [PATCH 19/23] docs: real ASIO 10-input dry routing operator how-to, limits and physical FAT acceptance --- docs/P1E_NATIVE_DRY_LAB_FAT_20261028.md | 36 +++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 docs/P1E_NATIVE_DRY_LAB_FAT_20261028.md diff --git a/docs/P1E_NATIVE_DRY_LAB_FAT_20261028.md b/docs/P1E_NATIVE_DRY_LAB_FAT_20261028.md new file mode 100644 index 000000000..97c7d714a --- /dev/null +++ b/docs/P1E_NATIVE_DRY_LAB_FAT_20261028.md @@ -0,0 +1,36 @@ +# P1E — REAL 10-CHANNEL DRY ASIO/WASAPI FAT LAB (2026-10-28) + +**Native code, not just another offline graph.** The owner-approved ten-strip P1D `PreparedMixerBlock` is now callable from the live JUCE audio callback in a **separate, explicit, fail-closed DRY ROUTING LAB**. This milestone exists to prove **actual physical input channel separation, mono/stereo hardware patching, routing graph activation and Windows device continuity**, while preserving the current VST3 CH1 production path whenever the lab is OFF. + +**The lab is not a finished performance mixer.** It deliberately has NO VST3 inserts, AUX sends, independent channel fader binding, automatic portable device map restore, multi-output patchbay, PDC or FX Tail guarantees. CH2–CH10 rack buttons remain truthful preview. Never advertise ten live VST3 chains or approved #15 zero-FX crackle status based on this PR alone. + +## Open it on real Windows hardware + +1. Build Windows artifact from **the passing P1E PR head**, do NOT use a stale previously downloaded build. Set headphone volume physically LOW. +2. In **AUDIO SETUP**, choose and verify the actual ASIO/WASAPI DIRECT interface and enable the needed physical input channels in its active input mask. Do not expect `initialise(1,2)` to activate all channels automatically. +3. If a VST3 was loaded in CH1, save/stop it and remove it from the chain before the dry test. Disable Smart Clock / independent capture/render, set SIGNAL CHECK to NORMAL, and leave the verified DIRECT route selected. +4. Open **SIGNAL CHECK**, click **MUTE OUTPUT**, then **ROUTING LAB · 10 CH**. Only channels reported from the **actual opened device's enabled input-channel bitmask** appear in the selectors. If the port you need does not appear, enable it in AUDIO SETUP, which may restart the device; do not lie with phantom dropdown ports. +5. Example with an active 8-input interface: set CH1 **MONO** input 3; CH2 **STEREO** input 5(L) / 6(R); CH3 **MONO** input 1. All other CH4–CH10 **NONE**. Choose a low initial per-strip level, e.g. −18 or −12 dB. Press **APPLY TO NATIVE AUDIO**; wait for explicit native ACK, never infer audio commit from UI selection alone. +6. Close the routing lab, go back to SIGNAL CHECK, and deliberately **UNMUTE OUTPUT**. Stimulate each physical input separately and confirm that only the corresponding path is heard. Then try nonadjacent L/R mappings, duplicate input fanout and a muted/None channel. +7. MUTE OUTPUT and press **STOP LAB**. STOP also forces output mute before returning to the original CH1 VST3 engine; unmute only after selecting/validating the wanted signal path. + +### Safety and determinism + +- The lab has a separate exact input registry: `juce::BigInteger activeInputChannels` is enumerated **off callback**, mapping actual hardware ID to JUCE's packed callback pointer index. Callback channel count is checked against the prepared map for every buffer. Max 256 enabled pins accepted; larger counts fail closed. +- A monotonic **device epoch** invalidates prepared routes on device stop/restart. An active lab with a stale device does NOT fall through to old CH1 audio; it outputs silence until the operator explicitly reapplies or stops the lab. UI shows **DRY LAB STALE — SILENT**. +- Graphs compile on the message/control thread; a single atomic pointer is published with `expectedRevision` and `deviceEpoch`. Callback obtains a no-heap lease before accessing the prepared graph. Old buffers are retired only when all callback readers leave. Excess rapid edits receive a specific retry response instead of freeing audio-owned memory. +- Channel processing is bounded, uses P1D's preallocated fixed workspace, has no VST instantiation or lock in the audio callback. Variable callback quanta are chunked into the prepared hard-frame limit. On invalid buffer or stale epoch, output must be silence. +- An initial 256-sample bounded de-click fade on a new route revision starts at the previously emitted output sample. This is a topology-switch mitigation, **not yet proof of click-free behavior at any buffer rate/driver**. +- MUTE OUTPUT is a *required precondition* of every APPLY; there is never an automatic audible route to an unknown speaker. STOP forces output mute. FX add/remove, preset recall, Smart Clock mode and other diagnostic modes are blocked while LAB is active. +- The lab sends dry output to actual render callback channels 1 and 2 (0-based indices 0/1); additional output channels are cleared. No hidden ASRC/split-clock buffering is introduced on a direct ASIO path. +- If the selected input is no longer available, no plugin can synthesize signal from a dummy channel and callback output remains silent. No route is persisted to a future machine until endpoint/physical-port identities have been verified by a portable-source migration workflow. + +## Engineering validation + +`ARMixLiveRoutingEpochTests` includes sparse 5/2/9 input mapping, duplicate/invalid masks, generation mismatch, revisions, ABA-safe reader-held graph lifetime, full retirement queue and explicit STOP fail-closed, 8,000 sequential publications and 1,000 concurrent read/publish cycles, with all C++ assertions enabled even in Release. + +`tests/live_routing_ui_contract_test.mjs` asserts the opt-in event, status/ACK, mute requirements, user port selector and preservation of the original non-native VST3-preview strips. Existing Windows native build compiles the P1E JUCE header and all previous native realtime/Orbit/FX tests; Node checks validate monitor.js. + +**Real-device acceptance checklist (NOT YET PASSED):** ASIO 2/4/8 inputs; non-contiguous enabled active mask; mono→both speakers and stereo L/R isolation; unplug/replug and driver re-selection silences until remap; rapid edits/STOP while audio runs, no heap/click, 0 VST case compared with issue #15; 48/96 kHz, short buffers and controlled low-volume headphones; compare DIRECT to independent-clock diagnostics only outside LAB. Preserve logs for genuine device/render errors. + +**Merge gate:** exact-head Windows Native CTest + Chromium smoke, inspect binary artifact/provenance from Actions, reconcile all parallel PRs against latest `main` before merge. **Native GUI faders for CH2–CH10 and channel-VST3 processing are not delivered in this PR.** Follow-on P1F must implement per-strip plugin instance ownership, negotiated mono/stereo bus layouts and authentic mixer fader/FX bindings after the 0-VST3 hardware signal-path FAT is clean. From beeb88109dee09213c57c0a440c0d486ae81c8f7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:08:34 +0700 Subject: [PATCH 20/23] ci: assert native dry LAB UI/engine parity in Windows Node contract gate --- .github/workflows/p1-windows.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index f65898b27..7b61b224a 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -78,6 +78,7 @@ jobs: 'tests/native_artifact_packaging_contract_test.mjs' 'tests/portable_workspace_contract_test.mjs' 'tests/plugin_vault_contract_test.mjs' + 'tests/live_routing_ui_contract_test.mjs' ) node --test $contracts if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } From 000e56eae07175a2dd15adfc02873656de5438e8 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:17:18 +0700 Subject: [PATCH 21/23] fix(rt): eliminate device-start vs GUI status routing-map data race and reject stale publish --- src/LiveDryRoutingLab.h | 87 +++++++++++++++++++++++++++-------------- 1 file changed, 58 insertions(+), 29 deletions(-) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 7da1190a4..d6ce44719 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -27,31 +27,39 @@ class LiveDryRoutingLab final { // JUCE calls aboutToStart after configuring the input/output device. // One device session gets a new epoch; stored route cannot survive it. void prepareDevice (juce::AudioIODevice* device) noexcept { - // Preserve explicit LAB ownership across hotplug; the new epoch - // makes the old prepared graph return silence, NEVER CH1 fallthrough. + // The new epoch invalidates old DSP immediately. Publish the new + // active mask using ATOMIC port slots: JUCE can restart the driver + // while its message thread is generating a routing/status snapshot. const auto generation=deviceEpoch_.fetch_add(1,std::memory_order_acq_rel)+1; - registryValid_=false; - enabledPorts_.fill(-1); - portCount_=0; - if(!device) return; + registryValid_.store(false,std::memory_order_release); + portCount_.store(0,std::memory_order_release); + callbackInputCount_.store(-1,std::memory_order_release); + if(!device)return; + std::array candidate{}; + int count=0; const auto mask=device->getActiveInputChannels(); - int bit=mask.findNextSetBit(0); - while(bit>=0) { - if(portCount_>=armix::device::LiveInputPortRegistry::limit) - return; // no silent truncation - enabledPorts_[portCount_++]=bit; - bit=mask.findNextSetBit(bit+1); + for(int bit=mask.findNextSetBit(0);bit>=0; + bit=mask.findNextSetBit(bit+1)) { + if(count>=armix::device::LiveInputPortRegistry::limit) + return; // never truncate/alias active device ports + candidate[count++]=bit; } + armix::device::LiveInputPortRegistry prepared; armix::device::LiveInputPortRegistry::Fault fault; - registryValid_=armix::device::LiveInputPortRegistry::prepare( - generation,{enabledPorts_.data(),static_cast(portCount_)}, - registry_,fault); - callbackInputCount_.store(portCount_,std::memory_order_release); + if(!armix::device::LiveInputPortRegistry::prepare( + generation,{candidate.data(),static_cast(count)}, + prepared,fault))return; + for(int i=0;i0) return "Disable/remove Channel 1 VST3 before DRY Routing LAB (no plugin state is touched)"; - if(!registryValid_ || portCount_==0) - return "Audio device has no validated active capture ports"; if(!command.isObject()) return "Invalid Dry Routing configuration"; const auto currentEpoch=deviceEpoch_.load(std::memory_order_acquire); + if(!registryValid_.load(std::memory_order_acquire)) + return "Audio device has no validated active capture ports"; + const int countNow=portCount_.load(std::memory_order_acquire); + if(countNow<=0 || countNow>armix::device::LiveInputPortRegistry::limit) + return "Invalid active device input channel mask"; + std::array physicalPorts{}; + for(int i=0;i( static_cast(command.getProperty("deviceEpoch",juce::var(0)))); const auto expectedRevision=static_cast( @@ -113,7 +130,7 @@ class LiveDryRoutingLab final { Plan plan; armix::mixer::RenderError error; if(!Plan::compile(cfg, - {enabledPorts_.data(),static_cast(portCount_)}, + {physicalPorts.data(),static_cast(countNow)}, sends,plan,error)) return "Invalid physical routing (inactive port, format or mapping)"; const auto revision=expectedRevision+1; @@ -124,7 +141,11 @@ class LiveDryRoutingLab final { next->prepared=std::make_unique(plan,Block::hardFrameLimit); if(!next->prepared || next->prepared->capacity()==0) return "Cannot allocate routing workspace"; - const auto result=publisher_.publish(std::move(next),expectedRevision,currentEpoch); + const auto epochAtPublish=deviceEpoch_.load(std::memory_order_acquire); + if(!registryValid_.load(std::memory_order_acquire) || + epochAtPublish!=currentEpoch) + return "Audio device changed before routing publication"; + const auto result=publisher_.publish(std::move(next),expectedRevision,epochAtPublish); switch(result) { case Publisher::Result::applied: publishedEpoch_.store(currentEpoch,std::memory_order_release); @@ -240,10 +261,13 @@ class LiveDryRoutingLab final { out->setProperty("peakL",peakL_.load(std::memory_order_relaxed)); out->setProperty("peakR",peakR_.load(std::memory_order_relaxed)); juce::Array ports; - if(device && registryValid_) { + if(device && registryValid_.load(std::memory_order_acquire)) { + const auto generation=epoch(); + const int countNow=portCount_.load(std::memory_order_acquire); const auto names=device->getInputChannelNames(); - for(int i=0;i(); p->setProperty("port",physical); p->setProperty("callback",i); @@ -251,6 +275,10 @@ class LiveDryRoutingLab final { ?names[physical]:juce::String("Input ")+juce::String(physical+1)); ports.add(juce::var(p.release())); } + // Device may restart while a status report is constructed. + if(epoch()!=generation || + !registryValid_.load(std::memory_order_acquire)) + ports.clear(); } out->setProperty("ports",juce::var(ports)); out->setProperty("note","EXPLICIT DRY HARDWARE FAT ONLY: no channel VST3, no sends, no portable route persistence"); @@ -258,10 +286,11 @@ class LiveDryRoutingLab final { } private: Publisher publisher_; - armix::device::LiveInputPortRegistry registry_; // device lifecycle only - std::array enabledPorts_{}; - int portCount_=0; - bool registryValid_=false; + // All data shared between JUCE device lifecycle and GUI/control reads + // are atomic; the callback never enumerates masks or channel names. + std::array,armix::device::LiveInputPortRegistry::limit> enabledPorts_{}; + std::atomic portCount_{0}; + std::atomic registryValid_{false}; std::atomic deviceEpoch_{0}; std::atomic publishedEpoch_{0}; std::atomic callbackInputCount_{-1}; From 1bc4c1c34d8122be7a08ae031dfbb7e216c03f57 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:23:37 +0700 Subject: [PATCH 22/23] fix(P1 rt): replace unsafe reader count with seq-cst reader admission/writer gate, prevent UAF --- engine/core/RealtimeRoutePublisher.h | 86 +++++++++++++++++----------- 1 file changed, 53 insertions(+), 33 deletions(-) diff --git a/engine/core/RealtimeRoutePublisher.h b/engine/core/RealtimeRoutePublisher.h index d58b6c345..2e2c7cc4f 100644 --- a/engine/core/RealtimeRoutePublisher.h +++ b/engine/core/RealtimeRoutePublisher.h @@ -7,16 +7,23 @@ #include #include -// Realtime path: two atomics per callback, one pointer read, no heap, locks, -// waiting, deallocation or device/GUI operations. One CONTROL writer. -// Prepared owns all DSP buffers; plugin objects MUST NOT be concurrently -// processed on old/new graphs (plugin lifecycle gate lives above this class). -// Old graph destruction happens only from pollRetirement() after RT readers -// have left. Do not destroy the exchange while audio callbacks are attached. +// One control-thread writer and any number of bounded RT readers. +// IMPORTANT: Separate "reader count" and "active pointer" atomics DO NOT +// protect reclamation; a reader can enter after a zero-count observation +// and acquire a pointer which is being freed. Gate reader reservation and +// writer publication with ONE sequentially-consistent atomic state. +// +// State bit 0: writer publishing/unpublishing (RT fails closed, NO SPIN). +// High bits: +2 per active reader. Any reader registered before writer +// publication retains old lifetime until it releases the lease. +// In contrast, readers registering after the gate clears see only NEW active. +// Retired memory is reclaimed only on control thread, and only when there +// are no preexisting readers. No heap/lock/device call on RT read path. namespace armix::rt { template class RealtimeRoutePublisher final { static_assert(RetiredCapacity>=2); + static constexpr std::uint32_t writerFlag=1U, readerUnit=2U; public: struct Snapshot final { std::uint64_t deviceEpoch=0; @@ -29,15 +36,25 @@ class RealtimeRoutePublisher final { class ReadLease final { public: explicit ReadLease (RealtimeRoutePublisher& owner) noexcept : owner_(&owner) { - owner_->readers_.fetch_add(1,std::memory_order_acq_rel); - item_=owner_->active_.load(std::memory_order_acquire); + auto activity=owner_->activity_.load(std::memory_order_seq_cst); + // Do not spin/wait inside the audio callback. One silent block is + // preferable to scheduling jitter while control thread publishes. + if((activity&writerFlag)!=0 || activity>UINT32_MAX-readerUnit) + return; + if(!owner_->activity_.compare_exchange_strong( + activity,activity+readerUnit, + std::memory_order_seq_cst,std::memory_order_seq_cst)) + return; + registered_=true; + item_=owner_->active_.load(std::memory_order_seq_cst); } ReadLease(const ReadLease&)=delete; ReadLease& operator=(const ReadLease&)=delete; ReadLease(ReadLease&&)=delete; ReadLease& operator=(ReadLease&&)=delete; ~ReadLease() noexcept { - owner_->readers_.fetch_sub(1,std::memory_order_release); + if(registered_) + owner_->activity_.fetch_sub(readerUnit,std::memory_order_seq_cst); } const Snapshot* get(std::uint64_t currentEpoch) const noexcept { return item_ && item_->deviceEpoch==currentEpoch @@ -46,15 +63,15 @@ class RealtimeRoutePublisher final { private: RealtimeRoutePublisher* owner_; const Snapshot* item_=nullptr; + bool registered_=false; }; RealtimeRoutePublisher()=default; RealtimeRoutePublisher(const RealtimeRoutePublisher&)=delete; RealtimeRoutePublisher& operator=(const RealtimeRoutePublisher&)=delete; - // CONTROL thread, with fully prepared DSP state and explicit revision. - // Expected revision always refers to the last ACKnowledged publication. - // All failure outcomes preserve the audio callback's last valid graph. + // CONTROL thread only. Expected revision is last acknowledged revision; + // candidate is fully preallocated and validated before any RT publication. Result publish(std::unique_ptr next, std::uint64_t expectedRevision, std::uint64_t deviceEpochNow) noexcept { @@ -65,51 +82,54 @@ class RealtimeRoutePublisher final { return Result::staleDevice; if(expectedRevision!=revision_) return Result::staleRevision; - pollRetirement(); // control thread only + pollRetirement(); if(owned_ && retiredCount_>=RetiredCapacity) return Result::retirementFull; - if(owned_) retired_[retiredCount_++]=std::move(owned_); + // Single writer. Publish/retire happens only with the low-bit gate set. + activity_.fetch_or(writerFlag,std::memory_order_seq_cst); + if(owned_)retired_[retiredCount_++]=std::move(owned_); owned_=std::move(next); - // Publish ownership last; readers always see a live allocation. - active_.store(owned_.get(),std::memory_order_release); + active_.store(owned_.get(),std::memory_order_seq_cst); + activity_.fetch_and(~writerFlag,std::memory_order_seq_cst); revision_=owned_->graphRevision; return Result::applied; } - // CONTROL thread: gate new callback usage, then retire safely. - // Caller must ensure the audio device is stopped before destroying this - // object; asynchronous stop merely disconnects the new graph view. + // Immediately gate the last route to silence. Do NOT delete a graph + // while the audio callback could own a ReadLease to its snapshot. void unpublish() noexcept { - // The hard mute is published FIRST, even if a busy RT consumer - // prevents reclaiming the previous ownership immediately. - active_.store(nullptr,std::memory_order_release); + activity_.fetch_or(writerFlag,std::memory_order_seq_cst); + active_.store(nullptr,std::memory_order_seq_cst); + activity_.fetch_and(~writerFlag,std::memory_order_seq_cst); revision_=0; pollRetirement(); if(!owned_)return; if(retiredCount_ active_{nullptr}; - std::atomic readers_{0}; + std::atomic activity_{0}; std::unique_ptr owned_; - std::array,RetiredCapacity> retired_ {}; + std::array,RetiredCapacity> retired_{}; std::size_t retiredCount_=0; std::uint64_t revision_=0; }; From 1281a54de82e0d2e95b079eed7df3e262b337063 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 07:24:13 +0700 Subject: [PATCH 23/23] fix(P2 ui): bind routing drafts to exact audio-device epoch; reset/deny stale port intent --- web/monitor.js | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/web/monitor.js b/web/monitor.js index ae3618ece..4e91a531f 100644 --- a/web/monitor.js +++ b/web/monitor.js @@ -71,11 +71,23 @@ '
'; document.body.appendChild(routeOverlay); const draftRoutes=Array.from({length:10},()=>({mode:"NONE",left:-1,right:-1,gain:0.25})); + let draftEpoch=0; // identity of the hardware used to draw these selectors + function invalidateDraftForNewDevice(nextEpoch){ + if(draftEpoch===nextEpoch)return false; + draftEpoch=nextEpoch; + for(const route of draftRoutes) { + route.mode="NONE";route.left=-1;route.right=-1;route.gain=0.25; + } + return true; + } const safeRouteText=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const routeSelect=(port,value)=>''+port.map(p=> '').join(''); function drawRoutes(){ + // An identical numbered input on another ASIO device is NOT the same + // microphone. Clear all prior user intent if device epoch changed. + invalidateDraftForNewDevice(Number(state.dryRoutingLab?.epoch)||0); const ports=Array.isArray(state.dryRoutingLab?.ports)?state.dryRoutingLab.ports:[]; const rows=document.getElementById("arRouteRows"); rows.innerHTML=Array.from({length:10},(_,i)=>{ @@ -121,12 +133,18 @@ routeOverlay.addEventListener("click",e=>{if(e.target===routeOverlay)routeOverlay.classList.remove("open");}); document.getElementById("arRouteApply").addEventListener("click",()=>{ const d=state.dryRoutingLab||{}; + if(!draftEpoch || draftEpoch!==Number(d.epoch)){ + document.getElementById("arRouteFeedback").textContent= + "DEVICE CHANGED · old channel assignments discarded. Re-select the actual physical inputs."; + drawRoutes(); + return; // must never submit old ports with a newly observed epoch + } if(!Array.isArray(d.ports)||!d.ports.length){ document.getElementById("arRouteFeedback").textContent="Select a real ASIO/WASAPI audio input in AUDIO SETUP first.";return; } document.getElementById("arRouteFeedback").textContent="Applying native route (output must be MUTED)..."; api.emitEvent("arMixAction",{action:"routingDryApply",value:{ - deviceEpoch:Number(d.epoch)||0,revision:Number(d.revision)||0, + deviceEpoch:draftEpoch,revision:Number(d.revision)||0, channels:draftRoutes.map(c=>({...c})) }}); }); @@ -180,7 +198,13 @@ return "Output armed. Speak into the microphone and inspect all three meters."; } function repaint(d) { - if(routeOverlay.classList.contains("open"))updateRouteLabIdentity(); + if(routeOverlay.classList.contains("open")){ + if(draftEpoch!==(Number(d.dryRoutingLab?.epoch)||0)) { + drawRoutes(); // fresh port names; reset stale user assignments + document.getElementById("arRouteFeedback").textContent= + "AUDIO DEVICE CHANGED · all input assignments reset. Select ports again."; + } else updateRouteLabIdentity(); + } setTextIfChanged(el("arSignalBadge"),!d.monitor ? "OUTPUT MUTED" : d.masterMute ? "MASTER MUTED" : d.channelMute ? "CH1 MUTED" : "OUTPUT ARMED"); el("arSignalBadge").style.color = d.monitor && !d.masterMute && !d.channelMute ? "#71e9cc" : "#e9be7c"; const monitorButton=document.querySelector('[data-native-action="monitor"]');