From 116bd6d55044251070cd3933f2edad28722de5dc Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 13:55:11 +0700 Subject: [PATCH 01/57] feat(io2): compile qualified multi-device pins into one immutable graph input namespace --- engine/device/MultiDeviceInputPlan.h | 286 +++++++++++++++++++++++++++ 1 file changed, 286 insertions(+) create mode 100644 engine/device/MultiDeviceInputPlan.h diff --git a/engine/device/MultiDeviceInputPlan.h b/engine/device/MultiDeviceInputPlan.h new file mode 100644 index 000000000..7e9685f3c --- /dev/null +++ b/engine/device/MultiDeviceInputPlan.h @@ -0,0 +1,286 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +#include "LiveInputPortRegistry.h" +#include "../core/DynamicChannelRoster.h" +#include +#include +#include +#include +#include +#include + +// IO-2 CONTROL-prepared, device-qualified physical source mapping. +// This does NOT open a driver, mutate .smix, publish a graph or run any DSP. +// The prepared slot ordinals are the only values handed to the existing +// DynamicSourcePatch / DynamicGraphRequest physical input namespace. +// +// Immutable after successful prepare; the primary render callback may call +// assemble() without allocation, locks, driver calls, strings or graph edits. +// A missing/stale secondary yields nullptr pointers (native graph treats it +// as a silent source), never a same-numbered pin from a different device. +namespace armix::device { + +struct CaptureEndpointView final { + // CONTROL supplies this token only after verifying actual driver/endpoint + // registration. A friendly name/driver CLSID alone is NOT physical proof. + std::string_view verifiedDeviceKey; + std::uint64_t generation=0; + bool primary=false; + std::span enabledPhysicalPinsInCallbackOrder{}; +}; + +struct QualifiedInputPin final { + std::string_view deviceKey; + int physicalPin=-1; +}; + +struct QualifiedChannelSource final { + armix::mixer::ChannelId channel{}; + QualifiedInputPin left{}, right{}; + bool stereo=false; +}; + +struct PreparedChannelSource final { + armix::mixer::ChannelId channel{}; + int inputL=-1,inputR=-1; // virtual, dense callback ordinals + bool stereo=false; +}; + +struct MultiDeviceInputFault final { + enum class Kind : std::uint8_t { + none, invalidPrimaryEpoch, invalidDeviceCount, missingPrimary, + invalidDeviceIdentity, invalidGeneration, duplicateDevice, + invalidDevicePins, tooManyInputs, unsupportedSecondaryChannels, + invalidChannel, duplicateChannel, channelFormatMismatch, + missingDevice, unavailablePin, invalidStereoPair + } kind=Kind::none; + armix::mixer::ChannelId channel{}; + int device=-1,physicalPin=-1; +}; + +class MultiDeviceInputPlan final { +public: + static constexpr int maxDevices=8; + // The existing DynamicPreparedMixerBlock physicalInputs contract is 256. + static constexpr int maxVirtualInputs=256; + static constexpr int maxAssignments=256; + static constexpr int maxCallbackFrames=8192; + + struct InputSlot final { + std::uint8_t device=0; + int packedOrdinal=-1; // index in exactly this driver's callback + std::uint64_t generation=0; + }; + struct DeviceReadback final { + std::string verifiedKey; // CONTROL only, never compared in callback + std::uint64_t generation=0; + int firstVirtual=0,activePins=0; + bool primary=false; + }; + struct CaptureBlock final { + const float* const* packedChannels=nullptr; + int channels=0,frames=0; + std::uint64_t generation=0; + bool admitted=false; // actual native capture/ASRC readback + }; + struct VirtualFrame final { + std::array pointers{}; + int count=0,available=0; + }; + + // CONTROL ONLY; success commits the full plan atomically. Failed validation + // leaves the previously accepted destination untouched. + static bool prepare( + std::uint64_t primaryEpoch, + std::span devices, + std::span bindings, + std::span roster, + MultiDeviceInputPlan& destination, + MultiDeviceInputFault& error) + { + error={}; + if(primaryEpoch==0) { + error.kind=MultiDeviceInputFault::Kind::invalidPrimaryEpoch; + return false; + } + if(devices.empty()||devices.size()>maxDevices) { + error.kind=MultiDeviceInputFault::Kind::invalidDeviceCount; + return false; + } + if(!devices.front().primary) { + error.kind=MultiDeviceInputFault::Kind::missingPrimary; + return false; + } + if(bindings.size()>maxAssignments) { + error.kind=MultiDeviceInputFault::Kind::invalidChannel; + return false; + } + + MultiDeviceInputPlan candidate; + candidate.primaryEpoch_=primaryEpoch; + candidate.deviceCount_=static_cast(devices.size()); + std::array registries{}; + for(std::size_t d=0;d(d); + if(src.verifiedDeviceKey.empty()) { + error.kind=MultiDeviceInputFault::Kind::invalidDeviceIdentity; + return false; + } + if(src.generation==0 || (d==0&&src.generation!=primaryEpoch)) { + error.kind=MultiDeviceInputFault::Kind::invalidGeneration; + return false; + } + if(d!=0&&src.primary) { + error.kind=MultiDeviceInputFault::Kind::missingPrimary; + return false; + } + for(std::size_t prev=0;prev16) { + // IO-1 SecondaryCaptureClockStream max ASRC channels = 16. + error.kind=MultiDeviceInputFault::Kind::unsupportedSecondaryChannels; + return false; + } + if(src.enabledPhysicalPinsInCallbackOrder.size() > + static_cast(maxVirtualInputs-candidate.inputCount_)) { + error.kind=MultiDeviceInputFault::Kind::tooManyInputs; + return false; + } + LiveInputPortRegistry::Fault portFault{}; + if(!LiveInputPortRegistry::prepare(src.generation, + src.enabledPhysicalPinsInCallbackOrder,registries[d],portFault)) { + error.kind=MultiDeviceInputFault::Kind::invalidDevicePins; + return false; + } + auto& prepared=candidate.devices_[d]; + prepared.verifiedKey=std::string(src.verifiedDeviceKey); + prepared.generation=src.generation; + prepared.primary=src.primary; + prepared.firstVirtual=candidate.inputCount_; + prepared.activePins=registries[d].enabledCount; + for(int pin=0;pin(d); + slot.packedOrdinal=pin; + slot.generation=src.generation; + } + } + + for(const auto& binding:bindings) { + error.channel=binding.channel; + error.device=-1; + error.physicalPin=-1; + const auto definition=std::find_if(roster.begin(),roster.end(), + [&](const auto& channel){return channel.id==binding.channel;}); + if(binding.channel.value==0 || definition==roster.end() || + definition->role!=armix::mixer::ChannelRole::input) { + error.kind=MultiDeviceInputFault::Kind::invalidChannel; + return false; + } + if((definition->format==armix::mixer::ProcessingFormat::stereo) + !=binding.stereo) { + error.kind=MultiDeviceInputFault::Kind::channelFormatMismatch; + return false; + } + for(int prev=0;prevint { + for(int d=0;d blocks, + VirtualFrame& frame) const noexcept + { + frame={}; + if(!primaryEpoch_||actualPrimaryEpoch!=primaryEpoch_|| + frames<=0||frames>maxCallbackFrames|| + blocks.size()!=static_cast(deviceCount_)) + return false; + frame.count=inputCount_; + for(int i=0;i devices_{}; + std::array slots_{}; + std::array assignments_{}; +}; + +} // namespace armix::device From a1e84b575636b3c3a9de97cff9858f6c4d243c51 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 13:57:04 +0700 Subject: [PATCH 02/57] test(io2): verify source identity, packed input map and isolated stale capture frames --- tests/multi_device_input_plan_test.cpp | 180 +++++++++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 tests/multi_device_input_plan_test.cpp diff --git a/tests/multi_device_input_plan_test.cpp b/tests/multi_device_input_plan_test.cpp new file mode 100644 index 000000000..704e793f9 --- /dev/null +++ b/tests/multi_device_input_plan_test.cpp @@ -0,0 +1,180 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// IO-2 device-qualified, control-prepared source map; hardware-free and JUCE-free. +#include "../engine/device/MultiDeviceInputPlan.h" +#include +#include +#include +#include + +namespace io=armix::device; +namespace mix=armix::mixer; +static void check(bool yes,const char* what) +{ + if(!yes){std::fprintf(stderr,"IO2_INPUT_PLAN_FAIL: %s\n",what);std::abort();} +} +static std::array channels() +{ + std::array rows{}; + rows[0].id={1};rows[0].role=mix::ChannelRole::input; + rows[0].format=mix::ProcessingFormat::mono; + rows[1].id={5};rows[1].role=mix::ChannelRole::input; + rows[1].format=mix::ProcessingFormat::stereo; + return rows; +} +static void mappingAndRealtimeIsolation() +{ + const std::array aPins{0,2},bPins{0,7}; + const std::array devices{{ + {"ASIO/verified-A",91,true,aPins}, + {"ASIO/verified-B",7,false,bPins} + }}; + const std::array bindings{{ + {{1},{"ASIO/verified-A",2},{},false}, + {{5},{"ASIO/verified-B",0},{"ASIO/verified-B",7},true} + }}; + const auto roster=channels(); + io::MultiDeviceInputPlan plan; + io::MultiDeviceInputFault error; + check(io::MultiDeviceInputPlan::prepare(91,devices,bindings,roster,plan,error), + "two-device prepare must succeed"); + check(error.kind==io::MultiDeviceInputFault::Kind::none, + "success fault reset"); + check(plan.virtualInputCount()==4&&plan.deviceCount()==2&& + plan.sourceCount()==2,"one virtual namespace for four pins"); + check(plan.device(0).verifiedKey=="ASIO/verified-A"&& + plan.device(1).verifiedKey=="ASIO/verified-B", + "device qualified identity"); + check(plan.slot(0).device==0&&plan.slot(0).packedOrdinal==0&& + plan.slot(1).device==0&&plan.slot(1).packedOrdinal==1&& + plan.slot(2).device==1&&plan.slot(2).packedOrdinal==0&& + plan.slot(3).device==1&&plan.slot(3).packedOrdinal==1, + "sparse pin -> correct per-device callback ordinal"); + check(plan.source(0).channel.value==1&&plan.source(0).inputL==1&& + plan.source(0).inputR==-1&&!plan.source(0).stereo, + "primary CH01 physical pin2 = virtual ordinal1"); + check(plan.source(1).channel.value==5&&plan.source(1).inputL==2&& + plan.source(1).inputR==3&&plan.source(1).stereo, + "B Input1/Input8 to CH05 without colliding with A"); + std::array a0{0.1f,0.1f,0.1f,0.1f}; + std::array a2{0.2f,0.2f,0.2f,0.2f}; + std::array b0{0.4f,0.4f,0.4f,0.4f}; + std::array b7{0.8f,0.8f,0.8f,0.8f}; + const float* aBlock[2]={a0.data(),a2.data()}; + const float* bBlock[2]={b0.data(),b7.data()}; + std::array blocks{{ + {aBlock,2,4,91,true},{bBlock,2,4,7,true} + }}; + io::MultiDeviceInputPlan::VirtualFrame frame; + check(plan.assemble(91,4,blocks,frame),"frame assembled"); + check(frame.count==4&&frame.available==4&& + frame.pointers[0]==a0.data()&&frame.pointers[1]==a2.data()&& + frame.pointers[2]==b0.data()&&frame.pointers[3]==b7.data(), + "same graph's planar virtual pointers, no copy or second renderer"); + // Stale B epoch/detached/ASRC dropout cannot alias A.Input1. + blocks[1].generation=8; + check(plan.assemble(91,4,blocks,frame)&&frame.available==2&& + frame.pointers[0]==a0.data()&&frame.pointers[1]==a2.data()&& + frame.pointers[2]==nullptr&&frame.pointers[3]==nullptr, + "B stale generation only silences B"); + blocks[1].generation=7;blocks[1].admitted=false; + check(plan.assemble(91,4,blocks,frame)&&frame.available==2&& + frame.pointers[2]==nullptr,"B no actual PCM = silence"); + blocks[1].admitted=true;blocks[1].frames=8; + check(plan.assemble(91,4,blocks,frame)&&frame.available==2, + "stale B callback block size rejected"); + blocks[1].frames=4; + check(!plan.assemble(90,4,blocks,frame)&&frame.count==0&& + frame.available==0&&frame.pointers[1]==nullptr, + "primary epoch change invalidates entire virtual frame"); + check(!plan.assemble(91,8193,blocks,frame)&&frame.count==0, + "callback capacity guard"); + const std::array shortBlocks{ + blocks[0] + }; + check(!plan.assemble(91,4,shortBlocks,frame),"device roster dimension fence"); + + // Exact one-device parity: virtual ordinal equals primary callback ordinal. + io::MultiDeviceInputPlan single; + const std::array primaryOnly{{devices[0]}}; + const std::array primaryBind{{bindings[0]}}; + check(io::MultiDeviceInputPlan::prepare(91,primaryOnly,primaryBind,roster, + single,error),"single device prepare"); + check(single.source(0).inputL==1&&single.virtualInputCount()==2, + "direct ASIO path keeps original packed ordinal"); + check(single.assemble(91,4,shortBlocks,frame)&&frame.available==2&& + frame.pointers[1]==a2.data(),"single device pointer direct"); +} +static void negativeContracts() +{ + const std::array aPins{0,2},bPins{0,7}; + std::array devices{{ + {"ASIO/verified-A",91,true,aPins}, + {"ASIO/verified-B",7,false,bPins} + }}; + std::array bindings{{ + {{1},{"ASIO/verified-A",2},{},false}, + {{5},{"ASIO/verified-B",0},{"ASIO/verified-B",7},true} + }}; + auto roster=channels(); + io::MultiDeviceInputPlan accepted; + io::MultiDeviceInputFault err; + auto attempt=[&](io::MultiDeviceInputFault::Kind expected) { + check(!io::MultiDeviceInputPlan::prepare(91,devices,bindings,roster, + accepted,err),"expected rejection"); + check(err.kind==expected,"exact fail closed rejection class"); + check(accepted.sourceCount()==2&&accepted.source(1).inputL==2, + "failed update never mutates prior accepted plan"); + }; + check(io::MultiDeviceInputPlan::prepare(91,devices,bindings,roster,accepted,err), + "initial accepted map"); + devices[1].verifiedDeviceKey=devices[0].verifiedDeviceKey; + attempt(io::MultiDeviceInputFault::Kind::duplicateDevice); + devices[1].verifiedDeviceKey="ASIO/verified-B"; + devices[0].generation=0; + attempt(io::MultiDeviceInputFault::Kind::invalidGeneration); + devices[0].generation=91; + devices[1].verifiedDeviceKey=""; + attempt(io::MultiDeviceInputFault::Kind::invalidDeviceIdentity); + devices[1].verifiedDeviceKey="ASIO/verified-B"; + devices[1].primary=true; + attempt(io::MultiDeviceInputFault::Kind::missingPrimary); + devices[1].primary=false; + bindings[1].left.deviceKey="missing-device"; + attempt(io::MultiDeviceInputFault::Kind::missingDevice); + bindings[1].left.deviceKey="ASIO/verified-B"; + bindings[1].right.physicalPin=9; + attempt(io::MultiDeviceInputFault::Kind::unavailablePin); + bindings[1].right.physicalPin=0; + attempt(io::MultiDeviceInputFault::Kind::invalidStereoPair); + bindings[1].right.physicalPin=7; + bindings[1].right.deviceKey="ASIO/verified-A"; + attempt(io::MultiDeviceInputFault::Kind::invalidStereoPair); + bindings[1].right.deviceKey="ASIO/verified-B"; + bindings[1].channel={1}; + attempt(io::MultiDeviceInputFault::Kind::duplicateChannel); + bindings[1].channel={5}; + bindings[1].stereo=false; + attempt(io::MultiDeviceInputFault::Kind::channelFormatMismatch); + bindings[1].stereo=true; + roster[1].role=mix::ChannelRole::group; + attempt(io::MultiDeviceInputFault::Kind::invalidChannel); + roster[1].role=mix::ChannelRole::input; + const std::array duplicatePins{0,0}; + devices[1].enabledPhysicalPinsInCallbackOrder=duplicatePins; + attempt(io::MultiDeviceInputFault::Kind::invalidDevicePins); + devices[1].enabledPhysicalPinsInCallbackOrder=bPins; + const std::array tooManySecondary{}; + devices[1].enabledPhysicalPinsInCallbackOrder=tooManySecondary; + attempt(io::MultiDeviceInputFault::Kind::unsupportedSecondaryChannels); + devices[1].enabledPhysicalPinsInCallbackOrder=bPins; + devices[0].primary=false; + attempt(io::MultiDeviceInputFault::Kind::missingPrimary); +} +int main() +{ + mappingAndRealtimeIsolation(); + negativeContracts(); + std::puts("IO2_QUALIFIED_INPUT_PLAN_PASS two devices, sparse pins, " + "ChannelId mapping, native pointer staging, epoch isolation, " + "single-device parity and negative validation"); +} From 6e6738f341792073669680bacb932c8418161f52 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 13:58:57 +0700 Subject: [PATCH 03/57] fix(io2): reject swapped devices with equal generations using native unique capture leases --- engine/device/MultiDeviceInputPlan.h | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/engine/device/MultiDeviceInputPlan.h b/engine/device/MultiDeviceInputPlan.h index 7e9685f3c..157d94eb4 100644 --- a/engine/device/MultiDeviceInputPlan.h +++ b/engine/device/MultiDeviceInputPlan.h @@ -28,6 +28,7 @@ struct CaptureEndpointView final { std::uint64_t generation=0; bool primary=false; std::span enabledPhysicalPinsInCallbackOrder{}; + std::uint64_t deviceLease=0; // native-issued, unique within accepted roster }; struct QualifiedInputPin final { @@ -51,6 +52,7 @@ struct MultiDeviceInputFault final { enum class Kind : std::uint8_t { none, invalidPrimaryEpoch, invalidDeviceCount, missingPrimary, invalidDeviceIdentity, invalidGeneration, duplicateDevice, + invalidDeviceLease, duplicateDeviceLease, invalidDevicePins, tooManyInputs, unsupportedSecondaryChannels, invalidChannel, duplicateChannel, channelFormatMismatch, missingDevice, unavailablePin, invalidStereoPair @@ -71,10 +73,11 @@ class MultiDeviceInputPlan final { std::uint8_t device=0; int packedOrdinal=-1; // index in exactly this driver's callback std::uint64_t generation=0; + std::uint64_t deviceLease=0; }; struct DeviceReadback final { std::string verifiedKey; // CONTROL only, never compared in callback - std::uint64_t generation=0; + std::uint64_t generation=0,deviceLease=0; int firstVirtual=0,activePins=0; bool primary=false; }; @@ -83,6 +86,7 @@ class MultiDeviceInputPlan final { int channels=0,frames=0; std::uint64_t generation=0; bool admitted=false; // actual native capture/ASRC readback + std::uint64_t deviceLease=0; // disambiguates reordered equal epochs }; struct VirtualFrame final { std::array pointers{}; @@ -132,6 +136,10 @@ class MultiDeviceInputPlan final { error.kind=MultiDeviceInputFault::Kind::invalidGeneration; return false; } + if(src.deviceLease==0) { + error.kind=MultiDeviceInputFault::Kind::invalidDeviceLease; + return false; + } if(d!=0&&src.primary) { error.kind=MultiDeviceInputFault::Kind::missingPrimary; return false; @@ -140,6 +148,9 @@ class MultiDeviceInputPlan final { if(candidate.devices_[prev].verifiedKey==src.verifiedDeviceKey) { error.kind=MultiDeviceInputFault::Kind::duplicateDevice; return false; + } else if(candidate.devices_[prev].deviceLease==src.deviceLease) { + error.kind=MultiDeviceInputFault::Kind::duplicateDeviceLease; + return false; } if(d!=0&&src.enabledPhysicalPinsInCallbackOrder.size()>16) { // IO-1 SecondaryCaptureClockStream max ASRC channels = 16. @@ -160,6 +171,7 @@ class MultiDeviceInputPlan final { auto& prepared=candidate.devices_[d]; prepared.verifiedKey=std::string(src.verifiedDeviceKey); prepared.generation=src.generation; + prepared.deviceLease=src.deviceLease; prepared.primary=src.primary; prepared.firstVirtual=candidate.inputCount_; prepared.activePins=registries[d].enabledCount; @@ -168,6 +180,7 @@ class MultiDeviceInputPlan final { slot.device=static_cast(d); slot.packedOrdinal=pin; slot.generation=src.generation; + slot.deviceLease=src.deviceLease; } } @@ -252,6 +265,7 @@ class MultiDeviceInputPlan final { const auto& slot=slots_[i]; const auto& block=blocks[slot.device]; if(!block.admitted||block.generation!=slot.generation|| + block.deviceLease!=slot.deviceLease|| block.frames!=frames||!block.packedChannels|| block.channels!=devices_[slot.device].activePins|| !block.packedChannels[slot.packedOrdinal]) From 762cee4cd7e0e3d7ab3e8303524f4eb9fc658330 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 13:59:18 +0700 Subject: [PATCH 04/57] test(io2): prove native lease prevents device swap and fail-closed identity --- tests/multi_device_input_plan_test.cpp | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/tests/multi_device_input_plan_test.cpp b/tests/multi_device_input_plan_test.cpp index 704e793f9..fa5903b62 100644 --- a/tests/multi_device_input_plan_test.cpp +++ b/tests/multi_device_input_plan_test.cpp @@ -25,8 +25,8 @@ static void mappingAndRealtimeIsolation() { const std::array aPins{0,2},bPins{0,7}; const std::array devices{{ - {"ASIO/verified-A",91,true,aPins}, - {"ASIO/verified-B",7,false,bPins} + {"ASIO/verified-A",91,true,aPins,1001}, + {"ASIO/verified-B",7,false,bPins,2002} }}; const std::array bindings{{ {{1},{"ASIO/verified-A",2},{},false}, @@ -62,7 +62,7 @@ static void mappingAndRealtimeIsolation() const float* aBlock[2]={a0.data(),a2.data()}; const float* bBlock[2]={b0.data(),b7.data()}; std::array blocks{{ - {aBlock,2,4,91,true},{bBlock,2,4,7,true} + {aBlock,2,4,91,true,1001},{bBlock,2,4,7,true,2002} }}; io::MultiDeviceInputPlan::VirtualFrame frame; check(plan.assemble(91,4,blocks,frame),"frame assembled"); @@ -83,6 +83,10 @@ static void mappingAndRealtimeIsolation() check(plan.assemble(91,4,blocks,frame)&&frame.available==2, "stale B callback block size rejected"); blocks[1].frames=4; + blocks[1].deviceLease=1001; + check(plan.assemble(91,4,blocks,frame)&&frame.available==2, + "native device lease prevents swapped same-generation streams"); + blocks[1].deviceLease=2002; check(!plan.assemble(90,4,blocks,frame)&&frame.count==0&& frame.available==0&&frame.pointers[1]==nullptr, "primary epoch change invalidates entire virtual frame"); @@ -108,8 +112,8 @@ static void negativeContracts() { const std::array aPins{0,2},bPins{0,7}; std::array devices{{ - {"ASIO/verified-A",91,true,aPins}, - {"ASIO/verified-B",7,false,bPins} + {"ASIO/verified-A",91,true,aPins,1001}, + {"ASIO/verified-B",7,false,bPins,2002} }}; std::array bindings{{ {{1},{"ASIO/verified-A",2},{},false}, @@ -130,6 +134,12 @@ static void negativeContracts() devices[1].verifiedDeviceKey=devices[0].verifiedDeviceKey; attempt(io::MultiDeviceInputFault::Kind::duplicateDevice); devices[1].verifiedDeviceKey="ASIO/verified-B"; + devices[1].deviceLease=devices[0].deviceLease; + attempt(io::MultiDeviceInputFault::Kind::duplicateDeviceLease); + devices[1].deviceLease=2002; + devices[1].deviceLease=0; + attempt(io::MultiDeviceInputFault::Kind::invalidDeviceLease); + devices[1].deviceLease=2002; devices[0].generation=0; attempt(io::MultiDeviceInputFault::Kind::invalidGeneration); devices[0].generation=91; From 6499a21acf8395a6c4a111ee67444d46511e1878 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 14:01:49 +0700 Subject: [PATCH 05/57] test(io2): standalone cross-platform CTest target without shared root CMake collision --- tests/io2/CMakeLists.txt | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 tests/io2/CMakeLists.txt diff --git a/tests/io2/CMakeLists.txt b/tests/io2/CMakeLists.txt new file mode 100644 index 000000000..d42e89eb1 --- /dev/null +++ b/tests/io2/CMakeLists.txt @@ -0,0 +1,18 @@ +# IO-2 standalone native, no-JUCE / no-hardware CTest project. +# Deliberately NOT editing the shared root CMakeLists.txt while N-MOD PR #799 +# owns Player native build/test wiring. Root integration is a later one-owner +# application seam after exact HEAD reconciliation. +cmake_minimum_required(VERSION 3.22) +project(ARMixIO2QualifiedInputMap LANGUAGES CXX) +include(CTest) +add_executable(ARMixIO2QualifiedInputMapTests + ../multi_device_input_plan_test.cpp) +target_compile_features(ARMixIO2QualifiedInputMapTests PRIVATE cxx_std_20) +if(MSVC) + target_compile_options(ARMixIO2QualifiedInputMapTests PRIVATE /W4 /WX) +else() + target_compile_options(ARMixIO2QualifiedInputMapTests PRIVATE + -Wall -Wextra -Wpedantic -Werror) +endif() +add_test(NAME ArSonMixIO2QualifiedSourceIdentityAndPCMLease + COMMAND ARMixIO2QualifiedInputMapTests) From 5dce5b368ab1b6be59e1003d9b8f85534cd2ec07 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 14:03:06 +0700 Subject: [PATCH 06/57] chore(io2): explicit C++20 standard includes and warning-clean size bounds --- engine/device/MultiDeviceInputPlan.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/engine/device/MultiDeviceInputPlan.h b/engine/device/MultiDeviceInputPlan.h index 157d94eb4..3f717aa37 100644 --- a/engine/device/MultiDeviceInputPlan.h +++ b/engine/device/MultiDeviceInputPlan.h @@ -6,6 +6,8 @@ #include #include #include +#include +#include #include #include #include @@ -108,7 +110,7 @@ class MultiDeviceInputPlan final { error.kind=MultiDeviceInputFault::Kind::invalidPrimaryEpoch; return false; } - if(devices.empty()||devices.size()>maxDevices) { + if(devices.empty()||devices.size()>static_cast(maxDevices)) { error.kind=MultiDeviceInputFault::Kind::invalidDeviceCount; return false; } @@ -116,7 +118,7 @@ class MultiDeviceInputPlan final { error.kind=MultiDeviceInputFault::Kind::missingPrimary; return false; } - if(bindings.size()>maxAssignments) { + if(bindings.size()>static_cast(maxAssignments)) { error.kind=MultiDeviceInputFault::Kind::invalidChannel; return false; } From ad356120b43a24531f7c003ba4954e64d94d0af6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 14:04:28 +0700 Subject: [PATCH 07/57] test(io2): equal generation across two independent devices still requires unique native lease --- tests/multi_device_input_plan_test.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/multi_device_input_plan_test.cpp b/tests/multi_device_input_plan_test.cpp index fa5903b62..d40def0e5 100644 --- a/tests/multi_device_input_plan_test.cpp +++ b/tests/multi_device_input_plan_test.cpp @@ -26,7 +26,7 @@ static void mappingAndRealtimeIsolation() const std::array aPins{0,2},bPins{0,7}; const std::array devices{{ {"ASIO/verified-A",91,true,aPins,1001}, - {"ASIO/verified-B",7,false,bPins,2002} + {"ASIO/verified-B",91,false,bPins,2002} }}; const std::array bindings{{ {{1},{"ASIO/verified-A",2},{},false}, @@ -62,7 +62,7 @@ static void mappingAndRealtimeIsolation() const float* aBlock[2]={a0.data(),a2.data()}; const float* bBlock[2]={b0.data(),b7.data()}; std::array blocks{{ - {aBlock,2,4,91,true,1001},{bBlock,2,4,7,true,2002} + {aBlock,2,4,91,true,1001},{bBlock,2,4,91,true,2002} }}; io::MultiDeviceInputPlan::VirtualFrame frame; check(plan.assemble(91,4,blocks,frame),"frame assembled"); @@ -76,7 +76,7 @@ static void mappingAndRealtimeIsolation() frame.pointers[0]==a0.data()&&frame.pointers[1]==a2.data()&& frame.pointers[2]==nullptr&&frame.pointers[3]==nullptr, "B stale generation only silences B"); - blocks[1].generation=7;blocks[1].admitted=false; + blocks[1].generation=91;blocks[1].admitted=false; check(plan.assemble(91,4,blocks,frame)&&frame.available==2&& frame.pointers[2]==nullptr,"B no actual PCM = silence"); blocks[1].admitted=true;blocks[1].frames=8; @@ -113,7 +113,7 @@ static void negativeContracts() const std::array aPins{0,2},bPins{0,7}; std::array devices{{ {"ASIO/verified-A",91,true,aPins,1001}, - {"ASIO/verified-B",7,false,bPins,2002} + {"ASIO/verified-B",91,false,bPins,2002} }}; std::array bindings{{ {{1},{"ASIO/verified-A",2},{},false}, From 526297c2cf3d320ec5a9fa81d2d66fe1e3035758 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 14:06:23 +0700 Subject: [PATCH 08/57] docs(io2): define source-map native lease, one-graph integration and parallel ownership handoff --- ..._INPUT_MAP_INTEGRATION_HANDOFF_20261119.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 docs/architecture/IO2_INPUT_MAP_INTEGRATION_HANDOFF_20261119.md diff --git a/docs/architecture/IO2_INPUT_MAP_INTEGRATION_HANDOFF_20261119.md b/docs/architecture/IO2_INPUT_MAP_INTEGRATION_HANDOFF_20261119.md new file mode 100644 index 000000000..32826cfbd --- /dev/null +++ b/docs/architecture/IO2_INPUT_MAP_INTEGRATION_HANDOFF_20261119.md @@ -0,0 +1,30 @@ +# IO-2 input mapping — native integration handoff (19 November 2026) + +**Scope:** isolated IO-2 C++ control-prepared DeviceKey + physical pin -> one native ChannelId graph input map. **Not** yet an installed secondary ASIO source or an audible Windows implementation. Deliberately no existing production code, CMake root, JS or GUI changes. + +## Read before consuming this module + +- `engine/device/MultiDeviceInputPlan.h` is a deterministic CONTROL compiler (no JUCE) and RT-safe **borrowed** planar-pointer assembler. `tests/multi_device_input_plan_test.cpp` tests duplicate input 1 on devices A/B, sparse pin-to-packed-ordinal mapping, ChannelId mono/stereo, stale device/epoch, actual PCM admission, same-generation device swap and single-device parity. +- First endpoint must be **verified primary**, with generation equal to primary output epoch. Every endpoint also provides a **nonzero native-issued unique deviceLease**; two distinct capture devices can legitimately have the same generation number, so this must not be inferred from the generation. Key MUST come from actual driver/endpoint attestation, not a user-facing friendly name, and does not become permanent physical identity automatically. +- Capture blocks are indexed by CONTROL-prepared device order, and carry matching `generation`, `deviceLease`, `frames`, `channels` and `admitted` readback. A null/mismatched secondary is silent **only for its virtual slots**. The primary epoch mismatch invalidates all slots. The caller must keep borrowed pointers and the immutable plan alive throughout the primary render lease. +- The plan's `source(i)` is a verified ChannelId + virtual `inputL/inputR` pair. Use those as the physical ordinal fields of **the existing** `armix::mixer::DynamicSourcePatch` and set **the existing** `DynamicGraphRequest.physicalInputs` to `plan.virtualInputCount()`; do not create another graph, PCM owner, ASRC, or VST instance. Preserve player-deck source kind and existing accepted WIRE/BUS/MAIN edges. This conversion is a **future CONTROL integration**, not implemented here. +- For each accepted secondary output of `SecondaryCaptureClockStream::pullForPrimary` (PR [#771](https://github.com/masarray/arsonmix/pull/771)), provide its planar scratch as a `CaptureBlock` only after exact capture generation and native lease authorization. **One capture device = one producer/one bridge; the primary callback = one consumer**. Capture adapter and its scratch cannot be freed until both callbacks have quiesced via CONTROL. No callback allocations, locks or driver open/close. +- Native output permission, manual ASIO hardware FAT and independent output BUS sinks are NOT implemented by this module. Missing device and invalid pins reject the CONTROL preparation; the accepted old plan remains unchanged, and `.smix` desired offline binding must be preserved by its existing owner. A future GUI uses ONLY native accepted + installed readback, never a JS-local LIVE label. + +## Parallel ownership / merge protocol + +At this checkpoint G-MV27 [#811](https://github.com/masarray/arsonmix/pull/811) is merged; N-MOD [#799](https://github.com/masarray/arsonmix/pull/799) remains active and edits `src/Main.cpp` and root `CMakeLists.txt`. **Do not edit these files in this PR.** Keep current GUI bridge, /preview/, VST3 and the existing direct ASIO route intact. Mainline and PR heads may change: refresh them before making any integration edit. + +**Standalone regression without modifying root CMake:** + +```sh +cmake -S tests/io2 -B /tmp/arsonmix-io2-test +cmake --build /tmp/arsonmix-io2-test --config Release +ctest --test-dir /tmp/arsonmix-io2-test -C Release --output-on-failure +``` + +This portable CTest is a new independent project, not registered in main native CI by this PR. After N-MOD's root CMake ownership is released, integrate the test into the existing native CTest lane **in one application integration PR** without overwriting Player targets. + +**Hard milestone gate after IO-1 reconciliation:** single installed render callback reads B from independently verified IO-1 capture ASRC and admits it into one `DynamicPreparedMixerBlock`; native request/ACK/physical readback and .smix persist separately; tests verify A.Input1 CH01 and B.Input1 CH05, FX->BUS->MAIN once, stale B does not affect A. Only real dual-vendor hardware test can qualify physically simultaneous ASIO. + +Related coordination: [#812](https://github.com/masarray/arsonmix/issues/812) · [multi-device ARD v2](../ARD_ARSONMIX_MULTI_DEVICE_IO_V2_20261118.md) · [root AGENTS.md](../../AGENTS.md). From 7ac9557e9eb90b2cbb04e92a6133afbd26a1c3b7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 14:13:20 +0700 Subject: [PATCH 09/57] test(io2): share full device-lease identity regression with registered native IO0 CTest --- tests/io2/QualifiedInputPlanCases.h | 195 ++++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 tests/io2/QualifiedInputPlanCases.h diff --git a/tests/io2/QualifiedInputPlanCases.h b/tests/io2/QualifiedInputPlanCases.h new file mode 100644 index 000000000..372eab936 --- /dev/null +++ b/tests/io2/QualifiedInputPlanCases.h @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Shared IO-2 regression contract, compiled by existing IO-0 Windows native CTest +// and also by the isolated standalone tests/io2 CMake target. +#pragma once +#include "../../engine/device/MultiDeviceInputPlan.h" +#include +#include +#include +#include + +namespace armix::io2_test { +namespace io=armix::device; +namespace mix=armix::mixer; +static void check(bool yes,const char* what) +{ + if(!yes){std::fprintf(stderr,"IO2_INPUT_PLAN_FAIL: %s\n",what);std::abort();} +} +static std::array channels() +{ + std::array rows{}; + rows[0].id={1};rows[0].role=mix::ChannelRole::input; + rows[0].format=mix::ProcessingFormat::mono; + rows[1].id={5};rows[1].role=mix::ChannelRole::input; + rows[1].format=mix::ProcessingFormat::stereo; + return rows; +} +static void mappingAndRealtimeIsolation() +{ + const std::array aPins{0,2},bPins{0,7}; + const std::array devices{{ + {"ASIO/verified-A",91,true,aPins,1001}, + {"ASIO/verified-B",91,false,bPins,2002} + }}; + const std::array bindings{{ + {{1},{"ASIO/verified-A",2},{},false}, + {{5},{"ASIO/verified-B",0},{"ASIO/verified-B",7},true} + }}; + const auto roster=channels(); + io::MultiDeviceInputPlan plan; + io::MultiDeviceInputFault error; + check(io::MultiDeviceInputPlan::prepare(91,devices,bindings,roster,plan,error), + "two-device prepare must succeed"); + check(error.kind==io::MultiDeviceInputFault::Kind::none, + "success fault reset"); + check(plan.virtualInputCount()==4&&plan.deviceCount()==2&& + plan.sourceCount()==2,"one virtual namespace for four pins"); + check(plan.device(0).verifiedKey=="ASIO/verified-A"&& + plan.device(1).verifiedKey=="ASIO/verified-B", + "device qualified identity"); + check(plan.slot(0).device==0&&plan.slot(0).packedOrdinal==0&& + plan.slot(1).device==0&&plan.slot(1).packedOrdinal==1&& + plan.slot(2).device==1&&plan.slot(2).packedOrdinal==0&& + plan.slot(3).device==1&&plan.slot(3).packedOrdinal==1, + "sparse pin -> correct per-device callback ordinal"); + check(plan.source(0).channel.value==1&&plan.source(0).inputL==1&& + plan.source(0).inputR==-1&&!plan.source(0).stereo, + "primary CH01 physical pin2 = virtual ordinal1"); + check(plan.source(1).channel.value==5&&plan.source(1).inputL==2&& + plan.source(1).inputR==3&&plan.source(1).stereo, + "B Input1/Input8 to CH05 without colliding with A"); + std::array a0{0.1f,0.1f,0.1f,0.1f}; + std::array a2{0.2f,0.2f,0.2f,0.2f}; + std::array b0{0.4f,0.4f,0.4f,0.4f}; + std::array b7{0.8f,0.8f,0.8f,0.8f}; + const float* aBlock[2]={a0.data(),a2.data()}; + const float* bBlock[2]={b0.data(),b7.data()}; + std::array blocks{{ + {aBlock,2,4,91,true,1001},{bBlock,2,4,91,true,2002} + }}; + io::MultiDeviceInputPlan::VirtualFrame frame; + check(plan.assemble(91,4,blocks,frame),"frame assembled"); + check(frame.count==4&&frame.available==4&& + frame.pointers[0]==a0.data()&&frame.pointers[1]==a2.data()&& + frame.pointers[2]==b0.data()&&frame.pointers[3]==b7.data(), + "same graph's planar virtual pointers, no copy or second renderer"); + // Stale B epoch/detached/ASRC dropout cannot alias A.Input1. + blocks[1].generation=8; + check(plan.assemble(91,4,blocks,frame)&&frame.available==2&& + frame.pointers[0]==a0.data()&&frame.pointers[1]==a2.data()&& + frame.pointers[2]==nullptr&&frame.pointers[3]==nullptr, + "B stale generation only silences B"); + blocks[1].generation=91;blocks[1].admitted=false; + check(plan.assemble(91,4,blocks,frame)&&frame.available==2&& + frame.pointers[2]==nullptr,"B no actual PCM = silence"); + blocks[1].admitted=true;blocks[1].frames=8; + check(plan.assemble(91,4,blocks,frame)&&frame.available==2, + "stale B callback block size rejected"); + blocks[1].frames=4; + blocks[1].deviceLease=1001; + check(plan.assemble(91,4,blocks,frame)&&frame.available==2, + "native device lease prevents swapped same-generation streams"); + blocks[1].deviceLease=2002; + check(!plan.assemble(90,4,blocks,frame)&&frame.count==0&& + frame.available==0&&frame.pointers[1]==nullptr, + "primary epoch change invalidates entire virtual frame"); + check(!plan.assemble(91,8193,blocks,frame)&&frame.count==0, + "callback capacity guard"); + const std::array shortBlocks{ + blocks[0] + }; + check(!plan.assemble(91,4,shortBlocks,frame),"device roster dimension fence"); + + // Exact one-device parity: virtual ordinal equals primary callback ordinal. + io::MultiDeviceInputPlan single; + const std::array primaryOnly{{devices[0]}}; + const std::array primaryBind{{bindings[0]}}; + check(io::MultiDeviceInputPlan::prepare(91,primaryOnly,primaryBind,roster, + single,error),"single device prepare"); + check(single.source(0).inputL==1&&single.virtualInputCount()==2, + "direct ASIO path keeps original packed ordinal"); + check(single.assemble(91,4,shortBlocks,frame)&&frame.available==2&& + frame.pointers[1]==a2.data(),"single device pointer direct"); +} +static void negativeContracts() +{ + const std::array aPins{0,2},bPins{0,7}; + std::array devices{{ + {"ASIO/verified-A",91,true,aPins,1001}, + {"ASIO/verified-B",91,false,bPins,2002} + }}; + std::array bindings{{ + {{1},{"ASIO/verified-A",2},{},false}, + {{5},{"ASIO/verified-B",0},{"ASIO/verified-B",7},true} + }}; + auto roster=channels(); + io::MultiDeviceInputPlan accepted; + io::MultiDeviceInputFault err; + auto attempt=[&](io::MultiDeviceInputFault::Kind expected) { + check(!io::MultiDeviceInputPlan::prepare(91,devices,bindings,roster, + accepted,err),"expected rejection"); + check(err.kind==expected,"exact fail closed rejection class"); + check(accepted.sourceCount()==2&&accepted.source(1).inputL==2, + "failed update never mutates prior accepted plan"); + }; + check(io::MultiDeviceInputPlan::prepare(91,devices,bindings,roster,accepted,err), + "initial accepted map"); + devices[1].verifiedDeviceKey=devices[0].verifiedDeviceKey; + attempt(io::MultiDeviceInputFault::Kind::duplicateDevice); + devices[1].verifiedDeviceKey="ASIO/verified-B"; + devices[1].deviceLease=devices[0].deviceLease; + attempt(io::MultiDeviceInputFault::Kind::duplicateDeviceLease); + devices[1].deviceLease=2002; + devices[1].deviceLease=0; + attempt(io::MultiDeviceInputFault::Kind::invalidDeviceLease); + devices[1].deviceLease=2002; + devices[0].generation=0; + attempt(io::MultiDeviceInputFault::Kind::invalidGeneration); + devices[0].generation=91; + devices[1].verifiedDeviceKey=""; + attempt(io::MultiDeviceInputFault::Kind::invalidDeviceIdentity); + devices[1].verifiedDeviceKey="ASIO/verified-B"; + devices[1].primary=true; + attempt(io::MultiDeviceInputFault::Kind::missingPrimary); + devices[1].primary=false; + bindings[1].left.deviceKey="missing-device"; + attempt(io::MultiDeviceInputFault::Kind::missingDevice); + bindings[1].left.deviceKey="ASIO/verified-B"; + bindings[1].right.physicalPin=9; + attempt(io::MultiDeviceInputFault::Kind::unavailablePin); + bindings[1].right.physicalPin=0; + attempt(io::MultiDeviceInputFault::Kind::invalidStereoPair); + bindings[1].right.physicalPin=7; + bindings[1].right.deviceKey="ASIO/verified-A"; + attempt(io::MultiDeviceInputFault::Kind::invalidStereoPair); + bindings[1].right.deviceKey="ASIO/verified-B"; + bindings[1].channel={1}; + attempt(io::MultiDeviceInputFault::Kind::duplicateChannel); + bindings[1].channel={5}; + bindings[1].stereo=false; + attempt(io::MultiDeviceInputFault::Kind::channelFormatMismatch); + bindings[1].stereo=true; + roster[1].role=mix::ChannelRole::group; + attempt(io::MultiDeviceInputFault::Kind::invalidChannel); + roster[1].role=mix::ChannelRole::input; + const std::array duplicatePins{0,0}; + devices[1].enabledPhysicalPinsInCallbackOrder=duplicatePins; + attempt(io::MultiDeviceInputFault::Kind::invalidDevicePins); + devices[1].enabledPhysicalPinsInCallbackOrder=bPins; + const std::array tooManySecondary{}; + devices[1].enabledPhysicalPinsInCallbackOrder=tooManySecondary; + attempt(io::MultiDeviceInputFault::Kind::unsupportedSecondaryChannels); + devices[1].enabledPhysicalPinsInCallbackOrder=bPins; + devices[0].primary=false; + attempt(io::MultiDeviceInputFault::Kind::missingPrimary); +} +inline void run() +{ + mappingAndRealtimeIsolation(); + negativeContracts(); + std::puts("IO2_QUALIFIED_INPUT_PLAN_PASS two devices, sparse pins, " + "ChannelId mapping, native pointer staging, epoch isolation, " + "single-device parity and negative validation"); +} + +} // namespace armix::io2_test From 0b8fe0a2293ba5beaaaafb98b069edc6c9b022f0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 14:13:22 +0700 Subject: [PATCH 10/57] test(io2): use shared regression cases from standalone native CTest --- tests/multi_device_input_plan_test.cpp | 189 +------------------------ 1 file changed, 3 insertions(+), 186 deletions(-) diff --git a/tests/multi_device_input_plan_test.cpp b/tests/multi_device_input_plan_test.cpp index d40def0e5..5237038a0 100644 --- a/tests/multi_device_input_plan_test.cpp +++ b/tests/multi_device_input_plan_test.cpp @@ -1,190 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only -// IO-2 device-qualified, control-prepared source map; hardware-free and JUCE-free. -#include "../engine/device/MultiDeviceInputPlan.h" -#include -#include -#include -#include - -namespace io=armix::device; -namespace mix=armix::mixer; -static void check(bool yes,const char* what) -{ - if(!yes){std::fprintf(stderr,"IO2_INPUT_PLAN_FAIL: %s\n",what);std::abort();} -} -static std::array channels() -{ - std::array rows{}; - rows[0].id={1};rows[0].role=mix::ChannelRole::input; - rows[0].format=mix::ProcessingFormat::mono; - rows[1].id={5};rows[1].role=mix::ChannelRole::input; - rows[1].format=mix::ProcessingFormat::stereo; - return rows; -} -static void mappingAndRealtimeIsolation() -{ - const std::array aPins{0,2},bPins{0,7}; - const std::array devices{{ - {"ASIO/verified-A",91,true,aPins,1001}, - {"ASIO/verified-B",91,false,bPins,2002} - }}; - const std::array bindings{{ - {{1},{"ASIO/verified-A",2},{},false}, - {{5},{"ASIO/verified-B",0},{"ASIO/verified-B",7},true} - }}; - const auto roster=channels(); - io::MultiDeviceInputPlan plan; - io::MultiDeviceInputFault error; - check(io::MultiDeviceInputPlan::prepare(91,devices,bindings,roster,plan,error), - "two-device prepare must succeed"); - check(error.kind==io::MultiDeviceInputFault::Kind::none, - "success fault reset"); - check(plan.virtualInputCount()==4&&plan.deviceCount()==2&& - plan.sourceCount()==2,"one virtual namespace for four pins"); - check(plan.device(0).verifiedKey=="ASIO/verified-A"&& - plan.device(1).verifiedKey=="ASIO/verified-B", - "device qualified identity"); - check(plan.slot(0).device==0&&plan.slot(0).packedOrdinal==0&& - plan.slot(1).device==0&&plan.slot(1).packedOrdinal==1&& - plan.slot(2).device==1&&plan.slot(2).packedOrdinal==0&& - plan.slot(3).device==1&&plan.slot(3).packedOrdinal==1, - "sparse pin -> correct per-device callback ordinal"); - check(plan.source(0).channel.value==1&&plan.source(0).inputL==1&& - plan.source(0).inputR==-1&&!plan.source(0).stereo, - "primary CH01 physical pin2 = virtual ordinal1"); - check(plan.source(1).channel.value==5&&plan.source(1).inputL==2&& - plan.source(1).inputR==3&&plan.source(1).stereo, - "B Input1/Input8 to CH05 without colliding with A"); - std::array a0{0.1f,0.1f,0.1f,0.1f}; - std::array a2{0.2f,0.2f,0.2f,0.2f}; - std::array b0{0.4f,0.4f,0.4f,0.4f}; - std::array b7{0.8f,0.8f,0.8f,0.8f}; - const float* aBlock[2]={a0.data(),a2.data()}; - const float* bBlock[2]={b0.data(),b7.data()}; - std::array blocks{{ - {aBlock,2,4,91,true,1001},{bBlock,2,4,91,true,2002} - }}; - io::MultiDeviceInputPlan::VirtualFrame frame; - check(plan.assemble(91,4,blocks,frame),"frame assembled"); - check(frame.count==4&&frame.available==4&& - frame.pointers[0]==a0.data()&&frame.pointers[1]==a2.data()&& - frame.pointers[2]==b0.data()&&frame.pointers[3]==b7.data(), - "same graph's planar virtual pointers, no copy or second renderer"); - // Stale B epoch/detached/ASRC dropout cannot alias A.Input1. - blocks[1].generation=8; - check(plan.assemble(91,4,blocks,frame)&&frame.available==2&& - frame.pointers[0]==a0.data()&&frame.pointers[1]==a2.data()&& - frame.pointers[2]==nullptr&&frame.pointers[3]==nullptr, - "B stale generation only silences B"); - blocks[1].generation=91;blocks[1].admitted=false; - check(plan.assemble(91,4,blocks,frame)&&frame.available==2&& - frame.pointers[2]==nullptr,"B no actual PCM = silence"); - blocks[1].admitted=true;blocks[1].frames=8; - check(plan.assemble(91,4,blocks,frame)&&frame.available==2, - "stale B callback block size rejected"); - blocks[1].frames=4; - blocks[1].deviceLease=1001; - check(plan.assemble(91,4,blocks,frame)&&frame.available==2, - "native device lease prevents swapped same-generation streams"); - blocks[1].deviceLease=2002; - check(!plan.assemble(90,4,blocks,frame)&&frame.count==0&& - frame.available==0&&frame.pointers[1]==nullptr, - "primary epoch change invalidates entire virtual frame"); - check(!plan.assemble(91,8193,blocks,frame)&&frame.count==0, - "callback capacity guard"); - const std::array shortBlocks{ - blocks[0] - }; - check(!plan.assemble(91,4,shortBlocks,frame),"device roster dimension fence"); - - // Exact one-device parity: virtual ordinal equals primary callback ordinal. - io::MultiDeviceInputPlan single; - const std::array primaryOnly{{devices[0]}}; - const std::array primaryBind{{bindings[0]}}; - check(io::MultiDeviceInputPlan::prepare(91,primaryOnly,primaryBind,roster, - single,error),"single device prepare"); - check(single.source(0).inputL==1&&single.virtualInputCount()==2, - "direct ASIO path keeps original packed ordinal"); - check(single.assemble(91,4,shortBlocks,frame)&&frame.available==2&& - frame.pointers[1]==a2.data(),"single device pointer direct"); -} -static void negativeContracts() -{ - const std::array aPins{0,2},bPins{0,7}; - std::array devices{{ - {"ASIO/verified-A",91,true,aPins,1001}, - {"ASIO/verified-B",91,false,bPins,2002} - }}; - std::array bindings{{ - {{1},{"ASIO/verified-A",2},{},false}, - {{5},{"ASIO/verified-B",0},{"ASIO/verified-B",7},true} - }}; - auto roster=channels(); - io::MultiDeviceInputPlan accepted; - io::MultiDeviceInputFault err; - auto attempt=[&](io::MultiDeviceInputFault::Kind expected) { - check(!io::MultiDeviceInputPlan::prepare(91,devices,bindings,roster, - accepted,err),"expected rejection"); - check(err.kind==expected,"exact fail closed rejection class"); - check(accepted.sourceCount()==2&&accepted.source(1).inputL==2, - "failed update never mutates prior accepted plan"); - }; - check(io::MultiDeviceInputPlan::prepare(91,devices,bindings,roster,accepted,err), - "initial accepted map"); - devices[1].verifiedDeviceKey=devices[0].verifiedDeviceKey; - attempt(io::MultiDeviceInputFault::Kind::duplicateDevice); - devices[1].verifiedDeviceKey="ASIO/verified-B"; - devices[1].deviceLease=devices[0].deviceLease; - attempt(io::MultiDeviceInputFault::Kind::duplicateDeviceLease); - devices[1].deviceLease=2002; - devices[1].deviceLease=0; - attempt(io::MultiDeviceInputFault::Kind::invalidDeviceLease); - devices[1].deviceLease=2002; - devices[0].generation=0; - attempt(io::MultiDeviceInputFault::Kind::invalidGeneration); - devices[0].generation=91; - devices[1].verifiedDeviceKey=""; - attempt(io::MultiDeviceInputFault::Kind::invalidDeviceIdentity); - devices[1].verifiedDeviceKey="ASIO/verified-B"; - devices[1].primary=true; - attempt(io::MultiDeviceInputFault::Kind::missingPrimary); - devices[1].primary=false; - bindings[1].left.deviceKey="missing-device"; - attempt(io::MultiDeviceInputFault::Kind::missingDevice); - bindings[1].left.deviceKey="ASIO/verified-B"; - bindings[1].right.physicalPin=9; - attempt(io::MultiDeviceInputFault::Kind::unavailablePin); - bindings[1].right.physicalPin=0; - attempt(io::MultiDeviceInputFault::Kind::invalidStereoPair); - bindings[1].right.physicalPin=7; - bindings[1].right.deviceKey="ASIO/verified-A"; - attempt(io::MultiDeviceInputFault::Kind::invalidStereoPair); - bindings[1].right.deviceKey="ASIO/verified-B"; - bindings[1].channel={1}; - attempt(io::MultiDeviceInputFault::Kind::duplicateChannel); - bindings[1].channel={5}; - bindings[1].stereo=false; - attempt(io::MultiDeviceInputFault::Kind::channelFormatMismatch); - bindings[1].stereo=true; - roster[1].role=mix::ChannelRole::group; - attempt(io::MultiDeviceInputFault::Kind::invalidChannel); - roster[1].role=mix::ChannelRole::input; - const std::array duplicatePins{0,0}; - devices[1].enabledPhysicalPinsInCallbackOrder=duplicatePins; - attempt(io::MultiDeviceInputFault::Kind::invalidDevicePins); - devices[1].enabledPhysicalPinsInCallbackOrder=bPins; - const std::array tooManySecondary{}; - devices[1].enabledPhysicalPinsInCallbackOrder=tooManySecondary; - attempt(io::MultiDeviceInputFault::Kind::unsupportedSecondaryChannels); - devices[1].enabledPhysicalPinsInCallbackOrder=bPins; - devices[0].primary=false; - attempt(io::MultiDeviceInputFault::Kind::missingPrimary); -} +#include "io2/QualifiedInputPlanCases.h" int main() { - mappingAndRealtimeIsolation(); - negativeContracts(); - std::puts("IO2_QUALIFIED_INPUT_PLAN_PASS two devices, sparse pins, " - "ChannelId mapping, native pointer staging, epoch isolation, " - "single-device parity and negative validation"); + armix::io2_test::run(); + return 0; } From e4b2733b71a424b60e329040cb4da1ee97e64450 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 14:13:25 +0700 Subject: [PATCH 11/57] test(io2): execute full qualified input-map cases in existing Windows IO0 native CTest --- tests/dual_asio_capture_probe_policy_test.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/dual_asio_capture_probe_policy_test.cpp b/tests/dual_asio_capture_probe_policy_test.cpp index 047b4aed8..db5321079 100644 --- a/tests/dual_asio_capture_probe_policy_test.cpp +++ b/tests/dual_asio_capture_probe_policy_test.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/device/DualAsioCaptureProbePolicy.h" #include "../engine/device/ClockBridgeSizing.h" +#include "io2/QualifiedInputPlanCases.h" #include #include #include @@ -74,6 +75,7 @@ int main() const auto impossible=armix::device::ClockBridgeSizing::choose( 48000.,48000.,32768,32768,48,32768,24.); check(!impossible.valid); + armix::io2_test::run(); // same registered IO0 native CTest now compiles IO-2 std::puts("IO0_POLICY_PASS: identity, zero-output capture, exact masks, 9 clock profiles"); return 0; } From c4c8b09b576881c82afd461556eb458b7d9bcfc9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 14:19:36 +0700 Subject: [PATCH 12/57] fix(io2): preserve native independence of physical source and FX channel formats --- engine/device/MultiDeviceInputPlan.h | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/engine/device/MultiDeviceInputPlan.h b/engine/device/MultiDeviceInputPlan.h index 3f717aa37..9a2924bd0 100644 --- a/engine/device/MultiDeviceInputPlan.h +++ b/engine/device/MultiDeviceInputPlan.h @@ -56,7 +56,7 @@ struct MultiDeviceInputFault final { invalidDeviceIdentity, invalidGeneration, duplicateDevice, invalidDeviceLease, duplicateDeviceLease, invalidDevicePins, tooManyInputs, unsupportedSecondaryChannels, - invalidChannel, duplicateChannel, channelFormatMismatch, + invalidChannel, duplicateChannel, missingDevice, unavailablePin, invalidStereoPair } kind=Kind::none; armix::mixer::ChannelId channel{}; @@ -197,11 +197,9 @@ class MultiDeviceInputPlan final { error.kind=MultiDeviceInputFault::Kind::invalidChannel; return false; } - if((definition->format==armix::mixer::ProcessingFormat::stereo) - !=binding.stereo) { - error.kind=MultiDeviceInputFault::Kind::channelFormatMismatch; - return false; - } + // Native source format and channel/insert processing format are + // intentionally independent (mono mic -> stereo VST, or stereo + // capture -> mono processing). Match DynamicPreparedMixerBlock. for(int prev=0;prev Date: Thu, 19 Nov 2026 14:20:08 +0700 Subject: [PATCH 13/57] test(io2): verify mono-to-stereo FX and stereo-to-mono channel parity --- tests/io2/QualifiedInputPlanCases.h | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/tests/io2/QualifiedInputPlanCases.h b/tests/io2/QualifiedInputPlanCases.h index 372eab936..aab75d936 100644 --- a/tests/io2/QualifiedInputPlanCases.h +++ b/tests/io2/QualifiedInputPlanCases.h @@ -166,9 +166,31 @@ static void negativeContracts() bindings[1].channel={1}; attempt(io::MultiDeviceInputFault::Kind::duplicateChannel); bindings[1].channel={5}; + // Source and processing-format contracts differ. Native graph permits + // mono capture -> stereo VST, preserving the channel processing format. bindings[1].stereo=false; - attempt(io::MultiDeviceInputFault::Kind::channelFormatMismatch); + bindings[1].right={}; + io::MultiDeviceInputPlan monoToStereo; + check(io::MultiDeviceInputPlan::prepare(91,devices,bindings,roster, + monoToStereo,err), + "mono source may feed a stereo-processing channel"); + check(monoToStereo.source(1).inputL==2 && + monoToStereo.source(1).inputR==-1, + "mono source stays mono in physical patch"); bindings[1].stereo=true; + bindings[1].right={"ASIO/verified-B",7}; + // Reverse also legal: stereo physical inputs may feed mono processing. + bindings[0].stereo=true; + bindings[0].right={"ASIO/verified-A",0}; + io::MultiDeviceInputPlan stereoToMono; + check(io::MultiDeviceInputPlan::prepare(91,devices,bindings,roster, + stereoToMono,err), + "stereo capture may feed a mono-processing channel"); + check(stereoToMono.source(0).inputL==1 && + stereoToMono.source(0).inputR==0, + "physical stereo source preserves exact packed ordinals"); + bindings[0].stereo=false; + bindings[0].right={}; roster[1].role=mix::ChannelRole::group; attempt(io::MultiDeviceInputFault::Kind::invalidChannel); roster[1].role=mix::ChannelRole::input; From bee42dc3ebf6e91fd5d61a55419db403475682bb Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 14:22:32 +0700 Subject: [PATCH 14/57] docs(io2 safety): require detached control preparation and existing RT snapshot publication --- engine/device/MultiDeviceInputPlan.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/engine/device/MultiDeviceInputPlan.h b/engine/device/MultiDeviceInputPlan.h index 9a2924bd0..83ce02a20 100644 --- a/engine/device/MultiDeviceInputPlan.h +++ b/engine/device/MultiDeviceInputPlan.h @@ -95,8 +95,11 @@ class MultiDeviceInputPlan final { int count=0,available=0; }; - // CONTROL ONLY; success commits the full plan atomically. Failed validation - // leaves the previously accepted destination untouched. + // CONTROL ONLY. Prepare into a DETACHED candidate (never the live plan). + // All-or-nothing validation leaves destination unchanged on failure. + // The existing realtime graph publisher must publish its immutable + // snapshot at the safe render boundary; this assignment is NOT an + // atomic callback-visible update and must not race with assemble(). static bool prepare( std::uint64_t primaryEpoch, std::span devices, From 7fe10aa4c8591fa5ce7695aefaf5fd097b55586a Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 14:22:49 +0700 Subject: [PATCH 15/57] docs(io2): prohibit mutation of installed plan; publish via existing RT snapshot owner --- docs/architecture/IO2_INPUT_MAP_INTEGRATION_HANDOFF_20261119.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/architecture/IO2_INPUT_MAP_INTEGRATION_HANDOFF_20261119.md b/docs/architecture/IO2_INPUT_MAP_INTEGRATION_HANDOFF_20261119.md index 32826cfbd..0d43c173b 100644 --- a/docs/architecture/IO2_INPUT_MAP_INTEGRATION_HANDOFF_20261119.md +++ b/docs/architecture/IO2_INPUT_MAP_INTEGRATION_HANDOFF_20261119.md @@ -6,6 +6,7 @@ - `engine/device/MultiDeviceInputPlan.h` is a deterministic CONTROL compiler (no JUCE) and RT-safe **borrowed** planar-pointer assembler. `tests/multi_device_input_plan_test.cpp` tests duplicate input 1 on devices A/B, sparse pin-to-packed-ordinal mapping, ChannelId mono/stereo, stale device/epoch, actual PCM admission, same-generation device swap and single-device parity. - First endpoint must be **verified primary**, with generation equal to primary output epoch. Every endpoint also provides a **nonzero native-issued unique deviceLease**; two distinct capture devices can legitimately have the same generation number, so this must not be inferred from the generation. Key MUST come from actual driver/endpoint attestation, not a user-facing friendly name, and does not become permanent physical identity automatically. +- Plan preparation is **CONTROL-only and into a detached candidate**; a successful C++ move-assignment is not an atomic RT publication. Publish immutable plan/scratch with the existing native graph publisher at a safe render boundary and wait for all callback leases to quiesce before reclamation. Never call `prepare(..., activePlan, ...)` while a callback may read it. - Capture blocks are indexed by CONTROL-prepared device order, and carry matching `generation`, `deviceLease`, `frames`, `channels` and `admitted` readback. A null/mismatched secondary is silent **only for its virtual slots**. The primary epoch mismatch invalidates all slots. The caller must keep borrowed pointers and the immutable plan alive throughout the primary render lease. - The plan's `source(i)` is a verified ChannelId + virtual `inputL/inputR` pair. Use those as the physical ordinal fields of **the existing** `armix::mixer::DynamicSourcePatch` and set **the existing** `DynamicGraphRequest.physicalInputs` to `plan.virtualInputCount()`; do not create another graph, PCM owner, ASRC, or VST instance. Preserve player-deck source kind and existing accepted WIRE/BUS/MAIN edges. This conversion is a **future CONTROL integration**, not implemented here. - For each accepted secondary output of `SecondaryCaptureClockStream::pullForPrimary` (PR [#771](https://github.com/masarray/arsonmix/pull/771)), provide its planar scratch as a `CaptureBlock` only after exact capture generation and native lease authorization. **One capture device = one producer/one bridge; the primary callback = one consumer**. Capture adapter and its scratch cannot be freed until both callbacks have quiesced via CONTROL. No callback allocations, locks or driver open/close. From eab9ad35371537a8c42a688d932fc1217ea95afe Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 19:06:56 +0700 Subject: [PATCH 16/57] feat(io2b): stage qualified A/B ChannelId graph and verify BUS FX MAIN PCM once --- engine/device/QualifiedInputGraphBridge.h | 86 +++++++++++ tests/dual_asio_capture_probe_policy_test.cpp | 4 +- tests/io2/CMakeLists.txt | 4 +- tests/io2/QualifiedInputGraphBridgeCases.h | 142 ++++++++++++++++++ tests/multi_device_input_plan_test.cpp | 3 +- 5 files changed, 236 insertions(+), 3 deletions(-) create mode 100644 engine/device/QualifiedInputGraphBridge.h create mode 100644 tests/io2/QualifiedInputGraphBridgeCases.h diff --git a/engine/device/QualifiedInputGraphBridge.h b/engine/device/QualifiedInputGraphBridge.h new file mode 100644 index 000000000..ee3194de6 --- /dev/null +++ b/engine/device/QualifiedInputGraphBridge.h @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +#include "MultiDeviceInputPlan.h" +#include "../core/DynamicPreparedMixerBlock.h" +#include +#include + +// IO-2B: CONTROL-only, non-destructive conversion between one accepted +// verified DeviceKey/pin namespace and the EXISTING ChannelId PCM graph. +// No AudioDeviceManager, IO callback, DSP, VST3 instance or JS truth owner. +// The caller must publish both this namespace and the graph through ONE +// immutable native render lease. stage() alone NEVER authorizes live PCM. +namespace armix::device { + +class QualifiedInputGraphBridge final { +public: + enum class Fault : std::uint8_t { + none, invalidPlan, unqualifiedExistingSource, playerSourceCollision, + invalidPatch, duplicateSource + }; + + static bool stage(const MultiDeviceInputPlan& plan, + const armix::mixer::DynamicGraphRequest& accepted, + armix::mixer::DynamicGraphRequest& destination, + Fault& fault) { + using namespace armix::mixer; + fault=Fault::none; + if(plan.primaryEpoch()==0 || plan.deviceCount()<1 || + plan.virtualInputCount()<0 || + plan.virtualInputCount()>MultiDeviceInputPlan::maxVirtualInputs) { + fault=Fault::invalidPlan;return false; + } + // CONTROL only. Keep the entire old request, including Player decks, + // maxFrames, scratch admission, and exact saved FX/channel semantics. + auto proposed=accepted; + proposed.physicalInputs=plan.virtualInputCount(); + for(auto& source:proposed.sources) { + if(source.kind!=DynamicSourceKind::physical) + continue; + const PreparedChannelSource* qualified=nullptr; + for(int i=0;iinputL; + source.inputR=qualified->inputR; + source.stereo=qualified->stereo; + } + for(int i=0;ikind!=DynamicSourceKind::physical) { + fault=Fault::playerSourceCollision;return false; + } + continue; // already replaced the SAME physical ChannelId + } + proposed.sources.push_back({mapped.channel,mapped.inputL, + mapped.inputR,mapped.stereo,DynamicSourceKind::physical,0}); + } + // Validation is against the virtual namespace, NOT primary driver + // callback count. These are callback ordinals, not physical pin IDs. + for(std::size_t i=0;i #include #include @@ -75,7 +76,8 @@ int main() const auto impossible=armix::device::ClockBridgeSizing::choose( 48000.,48000.,32768,32768,48,32768,24.); check(!impossible.valid); - armix::io2_test::run(); // same registered IO0 native CTest now compiles IO-2 + armix::io2_test::run(); + armix::io2_graph_test::run(); // same registered IO0 native CTest now compiles IO-2 std::puts("IO0_POLICY_PASS: identity, zero-output capture, exact masks, 9 clock profiles"); return 0; } diff --git a/tests/io2/CMakeLists.txt b/tests/io2/CMakeLists.txt index d42e89eb1..803ba7414 100644 --- a/tests/io2/CMakeLists.txt +++ b/tests/io2/CMakeLists.txt @@ -6,7 +6,9 @@ cmake_minimum_required(VERSION 3.22) project(ARMixIO2QualifiedInputMap LANGUAGES CXX) include(CTest) add_executable(ARMixIO2QualifiedInputMapTests - ../multi_device_input_plan_test.cpp) + ../multi_device_input_plan_test.cpp + ../../engine/device/QualifiedInputGraphBridge.h + QualifiedInputGraphBridgeCases.h) target_compile_features(ARMixIO2QualifiedInputMapTests PRIVATE cxx_std_20) if(MSVC) target_compile_options(ARMixIO2QualifiedInputMapTests PRIVATE /W4 /WX) diff --git a/tests/io2/QualifiedInputGraphBridgeCases.h b/tests/io2/QualifiedInputGraphBridgeCases.h new file mode 100644 index 000000000..9eb983885 --- /dev/null +++ b/tests/io2/QualifiedInputGraphBridgeCases.h @@ -0,0 +1,142 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// IO-2B: real native ChannelId PCM graph, virtual A/B pin readback and +// BUS FX once-only. Deterministic no-hardware evidence, NOT dual-ASIO FAT. +#pragma once +#include "../../engine/device/QualifiedInputGraphBridge.h" +#include "../../engine/core/DynamicNativeSessionPublisher.h" +#include +#include +#include +#include + +namespace armix::io2_graph_test { +namespace d=armix::device; +namespace m=armix::mixer; +static void require(bool ok,const char* reason) { + if(!ok){std::fprintf(stderr,"IO2_NATIVE_GRAPH_FAIL %s\n",reason);std::abort();} +} +static bool near(float x,float y){return std::abs(x-y)<0.0002f;} +static m::ChannelEdit add(std::size_t index,m::ChannelRole role, + m::ProcessingFormat fmt) { + m::ChannelEdit e;e.kind=m::ChannelEdit::Kind::add;e.position=index; + e.role=role;e.format=fmt;return e; +} +static m::ChannelEdit out(m::ChannelId from,m::ChannelId to) { + m::ChannelEdit e;e.kind=m::ChannelEdit::Kind::setPrimaryOutput; + e.id=from;e.target=to;return e; +} +inline void run() { + constexpr std::uint64_t epoch=1200; + constexpr int frames=128; + m::DynamicChannelRoster roster; + const std::array create{{ + add(0,m::ChannelRole::input,m::ProcessingFormat::mono), + add(1,m::ChannelRole::input,m::ProcessingFormat::stereo), + add(2,m::ChannelRole::group,m::ProcessingFormat::stereo), + add(3,m::ChannelRole::main,m::ProcessingFormat::stereo) + }}; + const auto added=roster.edit(0,create); + require(added.ok()&&added.createdIds.size()==4,"create real ChannelIds"); + const auto a=added.createdIds[0],b=added.createdIds[1], + bus=added.createdIds[2],main=added.createdIds[3]; + const std::array routes{{out(a,bus),out(b,bus),out(bus,main)}}; + require(roster.edit(roster.revision(),routes).ok(),"one WIRE topology"); + const std::array aPins{0,2},bPins{0,7}; + const std::array devices{{ + {"vendor-A/native-verified",epoch,true,aPins,101}, + {"vendor-B/native-verified",epoch,false,bPins,202} + }}; + const std::array bindings{{ + {a,{"vendor-A/native-verified",2},{},false}, + {b,{"vendor-B/native-verified",0},{"vendor-B/native-verified",7},true} + }}; + d::MultiDeviceInputPlan plan; + d::MultiDeviceInputFault mapFault; + require(d::MultiDeviceInputPlan::prepare(epoch,devices,bindings, + roster.channels(),plan,mapFault),"qualified CONTROL input plan"); + require(plan.virtualInputCount()==4&&plan.sourceCount()==2, + "two identical physical Input1 IDs become disjoint ordinals"); + + // Existing physical A is preserved; B is added. Player/deck sources and + // legacy routing are NOT deleted by a device-only topology transition. + m::DynamicGraphRequest old;old.physicalInputs=2;old.maxFrames=frames; + old.sources={{a,1,-1,false}}; + m::DynamicGraphRequest candidate; + d::QualifiedInputGraphBridge::Fault fault; + require(d::QualifiedInputGraphBridge::stage(plan,old,candidate,fault), + "all-or-nothing source map -> one existing graph request"); + require(candidate.physicalInputs==4 && candidate.sources.size()==2 && + candidate.sources[0].id==a&&candidate.sources[0].inputL==1 && + candidate.sources[1].id==b&&candidate.sources[1].inputL==2 && + candidate.sources[1].inputR==3, + "channelId-independent physical ordinal mapping"); + const auto accepted=candidate; + auto draft=plan; // purely CONTROL; never publish a copied plan on AUDIO + + // A missing previously accepted source must not silently erase A. + const std::array onlyB{bindings[1]}; + require(d::MultiDeviceInputPlan::prepare(epoch,devices,onlyB, + roster.channels(),draft,mapFault),"alternate detached plan"); + require(!d::QualifiedInputGraphBridge::stage(draft,accepted,candidate,fault) + && fault==d::QualifiedInputGraphBridge::Fault::unqualifiedExistingSource, + "failed update retains exact accepted graph request"); + require(candidate.physicalInputs==4&&candidate.sources.size()==2, + "negative update cannot mutate prior candidate"); + m::DynamicGraphRequest playerCollision=old; + playerCollision.sources.push_back({b,-1,-1,true, + m::DynamicSourceKind::playerDeck,77}); + require(!d::QualifiedInputGraphBridge::stage(plan,playerCollision,candidate,fault) + && fault==d::QualifiedInputGraphBridge::Fault::playerSourceCollision, + "never steal a virtual Player source's ChannelId"); + m::DynamicGraphRequest duplicate=old; + duplicate.sources.push_back(old.sources.front()); + require(!d::QualifiedInputGraphBridge::stage(plan,duplicate,candidate,fault) + && fault==d::QualifiedInputGraphBridge::Fault::duplicateSource, + "duplicate physical patch rejects without mutation"); + + m::DynamicNativeSessionPublisher native; + const auto committed=native.commit(roster,accepted,0,epoch,epoch,true); + require(committed.ok()&&committed.revision==1,"one native graph publication"); + std::array a0{},a2{},b0{},b7{},l{},r{}; + a0.fill(.83f);a2.fill(.2f);b0.fill(.4f);b7.fill(.6f); + const float* primary[]{a0.data(),a2.data()}; + const float* secondary[]{b0.data(),b7.data()}; + std::array blocks{{ + {primary,2,frames,epoch,true,101}, + {secondary,2,frames,epoch,true,202} + }}; + d::MultiDeviceInputPlan::VirtualFrame virtualFrame; + const auto render=[&](int& busFxCalls) { + require(plan.assemble(epoch,frames,blocks,virtualFrame), + "same render-clock virtual frame"); + auto fx=[&](m::ChannelId id,float* ll,float* rr,int n) noexcept { + if(id==bus){ + ++busFxCalls; + for(int i=0;i BUS FX once -> MAIN"); + constexpr float center=0.7071067811865475f; + require(near(l[frames-1],2.f*(.2f*center+.4f))&& + near(r[frames-1],2.f*(.2f*center+.6f)), + "real PCM from device A and B reaches MAIN separately"); + // Device B unplug/fault is isolated; never substitute A Input1 for B. + blocks[1].admitted=false; + require(render(fxCalls)&&fxCalls==2,"B dropout never stalls A FX"); + require(near(l[frames-1],2.f*.2f*center)&& + near(r[frames-1],2.f*.2f*center), + "A remains audible while B silent"); + blocks[1].admitted=true;blocks[1].deviceLease=101; + require(render(fxCalls)&&fxCalls==3,"equal epoch but swapped B lease renders"); + require(near(l[frames-1],2.f*.2f*center), + "swapped device lease cannot leak B to MAIN"); + blocks[1].deviceLease=202; + require(!plan.assemble(epoch+1,frames,blocks,virtualFrame) && + virtualFrame.count==0,"changed primary render epoch invalidates all"); + std::puts("IO2_NATIVE_GRAPH_PASS: A+B PCM -> ChannelId -> BUS FX once -> MAIN; stale B isolated"); +} +} // namespace armix::io2_graph_test diff --git a/tests/multi_device_input_plan_test.cpp b/tests/multi_device_input_plan_test.cpp index 5237038a0..d19455a96 100644 --- a/tests/multi_device_input_plan_test.cpp +++ b/tests/multi_device_input_plan_test.cpp @@ -1,7 +1,8 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "io2/QualifiedInputPlanCases.h" +#include "io2/QualifiedInputGraphBridgeCases.h" int main() { - armix::io2_test::run(); + armix::io2_test::run(); armix::io2_graph_test::run(); return 0; } From 0b2806f1bdf014bafb1a70ead1024820ede8c209 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 19:10:42 +0700 Subject: [PATCH 17/57] feat(io2b): publish qualified input map in same ChannelId graph and FX render lease --- engine/core/DynamicNativeSessionPublisher.h | 62 ++++++++++++++++++++- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index 08df7899e..28e462106 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only #pragma once #include "DynamicPreparedMixerBlock.h" +#include "../device/MultiDeviceInputPlan.h" #include "DynamicConsoleRoutingView.h" #include "NativeMusicTempoMonitor.h" #include "NativeBeatFrameContext.h" @@ -42,6 +43,9 @@ class DynamicNativeSessionPublisher final { DynamicPreparedMixerBlock graph; DynamicConsoleRoutingView routing; FxPlan fx; // SAME lifetime and revision as native PCM graph + // IO-2B: optional immutable qualified physical source map in THIS + // same graph lease. Never publish/retire it independently of FX/PCM. + std::unique_ptr inputMap; int physicalInputs=0; bool monitor=false; }; @@ -72,7 +76,8 @@ class DynamicNativeSessionPublisher final { std::uint64_t activeDeviceEpoch, bool allOutputsDisarmed, FxPlan fx={nullptr,nullptr,nullptr,0,0,nullptr},bool verifiedInternalWireOnly=false, - bool verifiedInternalFxOnly=false) { + bool verifiedInternalFxOnly=false, + const armix::device::MultiDeviceInputPlan* qualifiedInputMap=nullptr) { CommitResult report;report.revision=publisher_.lastRevision(); if(!fx.valid() || (fx.owner && (fx.deviceEpoch!=proposedDeviceEpoch || @@ -98,6 +103,37 @@ class DynamicNativeSessionPublisher final { !verifiedInternalFxOnly) { report.fault=Fault::outputArmed;return report; } + // CONTROL: validate every physical source against ONE actual + // device-qualified map before starting a potentially costly graph + // compile. Reject mixed old/new source namespaces as a transaction. + if(qualifiedInputMap) { + if(qualifiedInputMap->primaryEpoch()!=proposedDeviceEpoch || + qualifiedInputMap->deviceCount()<1 || + qualifiedInputMap->virtualInputCount()!=request.physicalInputs) { + report.fault=Fault::invalidCandidate;return report; + } + std::size_t matched=0; + for(const auto& source:request.sources) { + if(source.kind!=DynamicSourceKind::physical)continue; + bool verified=false; + for(int i=0;isourceCount();++i) { + const auto& mapped=qualifiedInputMap->source(i); + if(source.id==mapped.channel && + source.inputL==mapped.inputL && + source.inputR==mapped.inputR && + source.stereo==mapped.stereo) { + verified=true;break; + } + } + if(!verified) { + report.fault=Fault::invalidCandidate;return report; + } + ++matched; + } + if(matched!=static_cast(qualifiedInputMap->sourceCount())) { + report.fault=Fault::invalidCandidate;return report; + } + } auto next=std::make_unique(); next->deviceEpoch=proposedDeviceEpoch; next->graphRevision=expectedRevision+1; @@ -117,6 +153,9 @@ class DynamicNativeSessionPublisher final { report.fault=Fault::invalidGraph;return report; } prepared->physicalInputs=request.physicalInputs; + if(qualifiedInputMap) + prepared->inputMap= + std::make_unique(*qualifiedInputMap); prepared->fx=std::move(fx); // one accepted control-plane publication prepared->monitor=std::any_of(roster.channels().begin(), roster.channels().end(),[](const ChannelStripDefinition& row) { @@ -168,7 +207,9 @@ class DynamicNativeSessionPublisher final { std::span channelPeaksR={}, std::span playerPcm={}, float* const* hardwareOutputs=nullptr, - int hardwareOutputCount=0) noexcept { + int hardwareOutputCount=0, + std::span + qualifiedCaptureBlocks={}) noexcept { static_assert(std::is_nothrow_invocable_v, "Realtime VST dispatch must be noexcept"); const auto clearOutputs=[&]() noexcept { @@ -201,6 +242,23 @@ class DynamicNativeSessionPublisher final { } auto lease=publisher_.acquire(); const auto* snap=lease.get(deviceEpoch); + // The source-map lifetime and its PCM DSP graph are protected by + // this SAME publisher acquire() lease; never acquire them separately. + // For installed multi-device topology, only explicit per-device + // generations + native leases authorize the borrowed input pointers. + armix::device::MultiDeviceInputPlan::VirtualFrame virtualFrame; + if(snap && snap->prepared && snap->prepared->inputMap) { + if(physical || physicalCount!=0 || + !snap->prepared->inputMap->assemble(deviceEpoch,frames, + qualifiedCaptureBlocks, + virtualFrame)) { + clearOutputs();return false; + } + physical=virtualFrame.pointers.data(); + physicalCount=virtualFrame.count; + } else if(!qualifiedCaptureBlocks.empty()) { + clearOutputs();return false; // not qualified for legacy ASIO + } if(!snap || !snap->prepared || physicalCount!=snap->prepared->physicalInputs || (snap->prepared->monitor && !monitorL) || From 55388dab7a68664c962d56fc8b9c895fd93403e8 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 19:11:41 +0700 Subject: [PATCH 18/57] test(io2b): assert atomic qualified map and ChannelId FX publication, reject stale topology --- engine/core/DynamicNativeSessionPublisher.h | 3 +++ tests/io2/QualifiedInputGraphBridgeCases.h | 14 +++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index 28e462106..76e3d4138 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -252,6 +252,9 @@ class DynamicNativeSessionPublisher final { !snap->prepared->inputMap->assemble(deviceEpoch,frames, qualifiedCaptureBlocks, virtualFrame)) { + // The installed external destinations cannot retain an + // APPLIED readback from a previous, now invalid input map. + snap->prepared->graph.invalidateAppliedExternalOutputs(); clearOutputs();return false; } physical=virtualFrame.pointers.data(); diff --git a/tests/io2/QualifiedInputGraphBridgeCases.h b/tests/io2/QualifiedInputGraphBridgeCases.h index 9eb983885..33fdbdf5f 100644 --- a/tests/io2/QualifiedInputGraphBridgeCases.h +++ b/tests/io2/QualifiedInputGraphBridgeCases.h @@ -95,7 +95,8 @@ inline void run() { "duplicate physical patch rejects without mutation"); m::DynamicNativeSessionPublisher native; - const auto committed=native.commit(roster,accepted,0,epoch,epoch,true); + const auto committed=native.commit(roster,accepted,0,epoch,epoch,true, + {},false,false,&plan); require(committed.ok()&&committed.revision==1,"one native graph publication"); std::array a0{},a2{},b0{},b7{},l{},r{}; a0.fill(.83f);a2.fill(.2f);b0.fill(.4f);b7.fill(.6f); @@ -115,11 +116,18 @@ inline void run() { for(int i=0;i BUS FX once -> MAIN"); + // A source-map change cannot mutate a published graph unless the + // qualified map and its exact virtual sources are admitted together. + const auto rejected=native.commit(roster,accepted,1,epoch,epoch,true, + {},false,false,&draft); + require(rejected.fault==m::DynamicNativeSessionPublisher::Fault::invalidCandidate + &&native.revision()==1, + "rejected remap retains old immutable PCM + FX lease"); constexpr float center=0.7071067811865475f; require(near(l[frames-1],2.f*(.2f*center+.4f))&& near(r[frames-1],2.f*(.2f*center+.6f)), From a683e149c690ea0b7efe543975c6423553ef32be Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 19:12:29 +0700 Subject: [PATCH 19/57] fix(io2b): assert existing acceptedRevision native API --- tests/io2/QualifiedInputGraphBridgeCases.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/io2/QualifiedInputGraphBridgeCases.h b/tests/io2/QualifiedInputGraphBridgeCases.h index 33fdbdf5f..b5fa6e87d 100644 --- a/tests/io2/QualifiedInputGraphBridgeCases.h +++ b/tests/io2/QualifiedInputGraphBridgeCases.h @@ -126,7 +126,7 @@ inline void run() { const auto rejected=native.commit(roster,accepted,1,epoch,epoch,true, {},false,false,&draft); require(rejected.fault==m::DynamicNativeSessionPublisher::Fault::invalidCandidate - &&native.revision()==1, + &&native.acceptedRevision()==1, "rejected remap retains old immutable PCM + FX lease"); constexpr float center=0.7071067811865475f; require(near(l[frames-1],2.f*(.2f*center+.4f))&& From 362e6f381f43dc34a9ccc3e0d9413f7bde1144f6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 19:19:24 +0700 Subject: [PATCH 20/57] fix(io2b): reject unqualified legacy source switches under native device map lease --- engine/core/DynamicNativeSessionPublisher.h | 5 +++++ tests/io2/QualifiedInputGraphBridgeCases.h | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index 76e3d4138..f01866602 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -369,6 +369,11 @@ class DynamicNativeSessionPublisher final { ChannelId id,int inputL,int inputR,bool stereo) noexcept { return publisher_.updateActiveControl(epoch,revision, [&](Prepared& active) noexcept { + // An installed qualified virtual namespace must never accept + // an ordinal-only live switch. That would bypass DeviceKey + // and physical pin attestation. Recompile/publish the full + // detached map+graph on CONTROL instead. + if(active.inputMap)return false; return active.graph.setPhysicalSource(id,inputL,inputR,stereo); }); } diff --git a/tests/io2/QualifiedInputGraphBridgeCases.h b/tests/io2/QualifiedInputGraphBridgeCases.h index b5fa6e87d..d3d309499 100644 --- a/tests/io2/QualifiedInputGraphBridgeCases.h +++ b/tests/io2/QualifiedInputGraphBridgeCases.h @@ -132,6 +132,10 @@ inline void run() { require(near(l[frames-1],2.f*(.2f*center+.4f))&& near(r[frames-1],2.f*(.2f*center+.6f)), "real PCM from device A and B reaches MAIN separately"); + require(!native.setPhysicalSource(epoch,1,a,0,-1,false), + "no legacy ordinal-only source swap under qualified map"); + require(native.setChannelMix(epoch,1,a,1.f,0.f), + "normal ChannelId fader/PAN remains editable without graph rebuild"); // Device B unplug/fault is isolated; never substitute A Input1 for B. blocks[1].admitted=false; require(render(fxCalls)&&fxCalls==2,"B dropout never stalls A FX"); From 28b089a828997ba758ad675a1660e204072ee230 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 19:21:03 +0700 Subject: [PATCH 21/57] fix(native IO2B): avoid duplicate restore copy and GCC15 Werror in logical roster --- engine/core/DynamicChannelRoster.h | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/engine/core/DynamicChannelRoster.h b/engine/core/DynamicChannelRoster.h index fb11276ff..5469b4c68 100644 --- a/engine/core/DynamicChannelRoster.h +++ b/engine/core/DynamicChannelRoster.h @@ -791,9 +791,12 @@ class DynamicChannelRoster final { // CONTROL ONLY; no audio is ever published by this operation. bool restoreExact(std::uint64_t restoredRevision, std::span entries) { - if(restoredRevision==0 || entries.empty() || - !withinBudget(std::vector(entries.begin(),entries.end()))) - return false; + if(restoredRevision==0 || entries.empty())return false; + // A single CONTROL-only candidate avoids the second full roster + // copy and the GCC 15 false-positive temporary deallocation under + // -O2 -Werror. Rejected restores never mutate the accepted roster. + auto candidate=std::vector(entries.begin(),entries.end()); + if(!withinBudget(candidate))return false; std::unordered_set ids,edges; std::uint64_t maxId=0,maxEdge=0; int mains=0,monitors=0; @@ -829,7 +832,6 @@ class DynamicChannelRoster final { for(const auto& ch:entries) for(const auto& send:ch.sends) if(ids.count(send.destination.value)==0)return false; - auto candidate=std::vector(entries.begin(),entries.end()); auto index=buildIndex(candidate); if(index.size()!=candidate.size())return false; channels_.swap(candidate); From 29daeeaa4242894e7d058d85e45ac3bb1f57be52 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 20:27:31 +0700 Subject: [PATCH 22/57] feat(io2c): bounded primary-clock reader for separately clocked verified ASIO capture --- .../device/QualifiedSecondaryCaptureReader.h | 170 ++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 engine/device/QualifiedSecondaryCaptureReader.h diff --git a/engine/device/QualifiedSecondaryCaptureReader.h b/engine/device/QualifiedSecondaryCaptureReader.h new file mode 100644 index 000000000..3a80ad6bc --- /dev/null +++ b/engine/device/QualifiedSecondaryCaptureReader.h @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +#include "MultiDeviceInputPlan.h" +#include "SecondaryCaptureClockStream.h" +#include "../core/RealtimeRenderPermit.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// IO-2C: one primary callback consuming ONE independent capture clock (B). +// This only assembles qualified borrowed PCM for the existing native graph; +// it NEVER renders FX, owns hardware, creates a callback, or publishes a +// second source of truth. The operator-verified map is published separately +// in the SAME native PCM/FX snapshot by DynamicNativeSessionPublisher. +// +// prepare/stop: CONTROL ONLY, after output disarm and callback ownership gate. +// withBlocks: PRIMARY callback ONLY. Buffer/pointer lifetime spans the entire +// caller's render invocation. Future N-device support must extend this bounded +// writer/reader ownership explicitly; sharing one SPSC between producers is +// prohibited. +namespace armix::device { + +class QualifiedSecondaryCaptureReader final { +public: + using CaptureBlock=MultiDeviceInputPlan::CaptureBlock; + static constexpr int maxSecondaryChannels=16; + static constexpr int maxCallbackFrames=8192; + struct Status { + bool ready=false; + std::uint64_t primaryBlocks=0,secondaryAccepted=0,secondarySilent=0, + rejected=0,overlaps=0; + }; + + QualifiedSecondaryCaptureReader()=default; + QualifiedSecondaryCaptureReader(const QualifiedSecondaryCaptureReader&)=delete; + QualifiedSecondaryCaptureReader& operator=(const QualifiedSecondaryCaptureReader&)=delete; + + // CONTROL: allocate once with exact size, never on the primary callback. + // The native host must detach/disarm before modifying this adapter. + bool prepare(const MultiDeviceInputPlan& qualified,int maximumFrames) { + stop(); + if(qualified.primaryEpoch()==0||qualified.deviceCount()!=2|| + maximumFrames<=0||maximumFrames>maxCallbackFrames|| + !qualified.device(0).primary||qualified.device(1).primary || + qualified.device(0).generation!=qualified.primaryEpoch()|| + qualified.device(0).deviceLease==0||qualified.device(1).deviceLease==0|| + qualified.device(0).deviceLease==qualified.device(1).deviceLease|| + qualified.device(0).activePins<1|| + qualified.device(1).activePins<1|| + qualified.device(1).activePins>maxSecondaryChannels)return false; + const int n=qualified.device(1).activePins; + const auto total=static_cast(n)* + static_cast(maximumFrames); + std::unique_ptr newScratch{new(std::nothrow) float[total]{}}; + if(!newScratch)return false; + scratch_=std::move(newScratch); + epoch_=qualified.primaryEpoch(); + primaryGeneration_=qualified.device(0).generation; + primaryLease_=qualified.device(0).deviceLease; + secondaryGeneration_=qualified.device(1).generation; + secondaryLease_=qualified.device(1).deviceLease; + primaryChannels_=qualified.device(0).activePins; + secondaryChannels_=n; + maximumFrames_=maximumFrames; + for(int c=0;c(c)*static_cast(maximumFrames); + write_[c]=channel;read_[c]=channel; + } + primaryBlocks_.store(0,std::memory_order_relaxed); + secondaryAccepted_.store(0,std::memory_order_relaxed); + secondarySilent_.store(0,std::memory_order_relaxed); + rejected_.store(0,std::memory_order_relaxed); + overlaps_.store(0,std::memory_order_relaxed); + ready_.store(true,std::memory_order_release); + return true; + } + + // CONTROL ONLY, never called inside either audio callback. + // Prevent reprepare/free while a borrowed scratch view is rendering. + void stop() noexcept { + ready_.store(false,std::memory_order_release); + while(readers_.load(std::memory_order_acquire)!=0) + std::this_thread::yield(); + scratch_.reset(); + write_={};read_={}; + epoch_=primaryGeneration_=primaryLease_=0; + secondaryGeneration_=secondaryLease_=0; + primaryChannels_=secondaryChannels_=maximumFrames_=0; + } + + // PRIMARY callback only. Render owns the view synchronously and returns + // before scratch can be reused; a broken overlapping driver fails silent. + // The caller MUST silence physical outputs on a false return. + template + bool withBlocks(std::uint64_t primaryEpoch, + const float* const* primary,int primaryChannels, + int frames,SecondaryCaptureClockStream& secondary, + Render&& render) noexcept { + static_assert(std::is_nothrow_invocable_r_v>, + "Render must synchronously consume blocks without throwing"); + readers_.fetch_add(1,std::memory_order_acq_rel); + const bool admitted=ready_.load(std::memory_order_acquire) && + scratch_ && primaryEpoch==epoch_ && + primaryChannels==primaryChannels_ && + frames>0&&frames<=maximumFrames_ && + (primaryChannels==0||primary!=nullptr); + if(!admitted) { + rejected_.fetch_add(1,std::memory_order_relaxed); + readers_.fetch_sub(1,std::memory_order_release); + return false; + } + armix::rt::RealtimeRenderPermit exclusive{consumer_}; + if(!exclusive){ + overlaps_.fetch_add(1,std::memory_order_relaxed); + readers_.fetch_sub(1,std::memory_order_release); + return false; + } + primaryBlocks_.fetch_add(1,std::memory_order_relaxed); + // Separate SPSC: B's real device callback pushes at capture rate; + // this primary callback is the sole FIFO consumer after ASRC. + const bool bReady=secondary.pull(write_.data(),secondaryChannels_, + frames,secondaryGeneration_,primaryEpoch,secondaryLease_); + if(bReady)secondaryAccepted_.fetch_add(1,std::memory_order_relaxed); + else secondarySilent_.fetch_add(1,std::memory_order_relaxed); + const std::array blocks{{ + {primary,primaryChannels,frames,primaryGeneration_,true,primaryLease_}, + {read_.data(),secondaryChannels_,frames,secondaryGeneration_, + bReady,secondaryLease_} + }}; + // The receiver must use the SAME snapshot-owned input map/graph as + // this primary callback; it cannot hold this view after return. + const bool ok=std::forward(render)( + std::span(blocks.data(),blocks.size())); + readers_.fetch_sub(1,std::memory_order_release); + return ok; + } + + Status status() const noexcept { + return {ready_.load(std::memory_order_acquire), + primaryBlocks_.load(std::memory_order_relaxed), + secondaryAccepted_.load(std::memory_order_relaxed), + secondarySilent_.load(std::memory_order_relaxed), + rejected_.load(std::memory_order_relaxed), + overlaps_.load(std::memory_order_relaxed)}; + } + +private: + // No reader can remain after stop's CONTROL quiescence barrier. + std::unique_ptr scratch_; + std::array write_{}; + std::array read_{}; + std::uint64_t epoch_=0,primaryGeneration_=0,primaryLease_=0, + secondaryGeneration_=0,secondaryLease_=0; + int primaryChannels_=0,secondaryChannels_=0,maximumFrames_=0; + std::atomic ready_{false}; + std::atomic readers_{0}; + std::atomic_flag consumer_=ATOMIC_FLAG_INIT; + std::atomic primaryBlocks_{0},secondaryAccepted_{0}, + secondarySilent_{0},rejected_{0},overlaps_{0}; +}; +} // namespace armix::device From 82bc90cd0015a421e39c474db463f7acf9d51b1c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 20:28:40 +0700 Subject: [PATCH 23/57] test(io2c): prove real ASRC B plus primary A through one ChannelId FX MAIN graph --- .../QualifiedSecondaryCaptureReaderCases.h | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 tests/io2/QualifiedSecondaryCaptureReaderCases.h diff --git a/tests/io2/QualifiedSecondaryCaptureReaderCases.h b/tests/io2/QualifiedSecondaryCaptureReaderCases.h new file mode 100644 index 000000000..52b6f99f9 --- /dev/null +++ b/tests/io2/QualifiedSecondaryCaptureReaderCases.h @@ -0,0 +1,133 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "../../engine/device/QualifiedSecondaryCaptureReader.h" +#include "../../engine/device/QualifiedInputGraphBridge.h" +#include "../../engine/core/DynamicNativeSessionPublisher.h" +#include +#include +#include +#include + +namespace armix::io2_clocked_test { +namespace d=armix::device; +namespace m=armix::mixer; +inline void check(bool ok,const char* why) { + if(!ok){std::fprintf(stderr,"IO2_CLOCKED_FAIL %s\n",why);std::abort();} +} +inline bool near(float a,float b,float tolerance=0.03f) { + return std::abs(a-b) create{}; + for(int i=0;i<3;++i){ + create[i].kind=m::ChannelEdit::Kind::add; + create[i].position=static_cast(i); + create[i].role=i==2?m::ChannelRole::main:m::ChannelRole::input; + create[i].format=i==0?m::ProcessingFormat::mono:m::ProcessingFormat::stereo; + } + const auto added=roster.edit(0,create); + check(added.ok()&&added.createdIds.size()==3,"qualified ChannelId roster"); + const auto a=added.createdIds[0],b=added.createdIds[1], + main=added.createdIds[2]; + std::array wiring{}; + for(int i=0;i<2;++i){ + wiring[i].kind=m::ChannelEdit::Kind::setPrimaryOutput; + wiring[i].id=i==0?a:b;wiring[i].target=main; + } + check(roster.edit(roster.revision(),wiring).ok(),"both inputs WIRE MAIN"); + const std::array aPins{0}; + const std::array bPins{0,7}; + const std::array devices{{ + {"verified-A",epoch,true,aPins,1001}, + {"verified-B",captureGeneration,false,bPins,2002} + }}; + const std::array bindings{{ + {a,{"verified-A",0},{},false}, + {b,{"verified-B",0},{"verified-B",7},true} + }}; + d::MultiDeviceInputPlan plan; + d::MultiDeviceInputFault err; + check(d::MultiDeviceInputPlan::prepare(epoch,devices,bindings, + roster.channels(),plan,err),"two physical namespaces qualified"); + m::DynamicGraphRequest old;old.physicalInputs=1;old.maxFrames=frames; + old.sources={{a,0,-1,false}}; + m::DynamicGraphRequest request; + d::QualifiedInputGraphBridge::Fault bridgeError{}; + check(d::QualifiedInputGraphBridge::stage(plan,old,request,bridgeError), + "control maps both verified sources into same graph"); + m::DynamicNativeSessionPublisher native; + check(native.commit(roster,request,0,epoch,epoch,true, + {},false,false,&plan).ok(),"one PCM and device map publication"); + + d::SecondaryCaptureClockStream clock; + const d::SecondaryCaptureClockStream::Format format{ + 48000.,48000.,frames,frames,2,captureGeneration,epoch,2002}; + check(clock.prepare(format)&&clock.activate(),"independent B producer ready"); + std::array bLeft{},bRight{}; + bLeft.fill(.4f);bRight.fill(.6f); + const float* bInput[]{bLeft.data(),bRight.data()}; + check(clock.push(bInput,2,4096),"producer FIFO primed before A render"); + d::QualifiedSecondaryCaptureReader reader; + check(reader.prepare(plan,frames),"reader allocates only on CONTROL"); + std::array aRaw{},left{},right{}; + aRaw.fill(.2f);const float* aInput[]{aRaw.data()}; + int aFx=0,bFx=0,mainFx=0; + const auto fx=[&](m::ChannelId id,float*,float*,int) noexcept { + if(id==a)++aFx; + if(id==b)++bFx; + if(id==main)++mainFx; + }; + const auto render=[&](bool nested=false) { + return reader.withBlocks(epoch,aInput,1,frames,clock, + [&](std::span blocks) noexcept { + if(nested) + check(!reader.withBlocks(epoch,aInput,1,frames,clock, + [](std::span) noexcept { + return true; + }),"overlap must fail silent without scratching B"); + return native.render(epoch,nullptr,0,left.data(),right.data(), + frames,false,fx,nullptr,nullptr,{},{},{},nullptr,0,blocks); + }); + }; + check(render(true),"A+B native render consumes B ASRC exactly once"); + check(aFx==1&&bFx==1&&mainFx==1,"one ChannelId FX pass per block"); + constexpr float monoCenter=.7071067811865475f; + check(near(left[frames-1],.2f*monoCenter+.4f)&& + near(right[frames-1],.2f*monoCenter+.6f), + "B's real clock bridge PCM reaches MAIN with A"); + check(reader.status().secondaryAccepted==1&&reader.status().overlaps==1, + "one successful capture consumption, overlap rejected"); + // B lost/failed is SILENCE in B channels, never relabeled A Input1. + clock.fault(); + check(render(),"faulted B cannot block verified primary A"); + check(near(left[frames-1],.2f*monoCenter,0.005f)&& + near(right[frames-1],.2f*monoCenter,0.005f), + "B dropout leaves A audible and correctly isolated"); + check(reader.status().secondarySilent==1, + "native B fault recorded without false ready"); + check(!reader.withBlocks(epoch+1,aInput,1,frames,clock, + [](std::span) noexcept { + return true; + }),"primary epoch invalidates entire callback"); + check(reader.status().rejected==1,"stale primary epoch counted"); + + // Same generation but changed physical device lease is not sufficient + // to republish audio or borrow another ASIO driver's PCM. + reader.stop(); + auto changed=devices; + changed[1].deviceLease=9999; + d::MultiDeviceInputPlan wrong; + check(d::MultiDeviceInputPlan::prepare(epoch,changed,bindings, + roster.channels(),wrong,err),"detached revised B lease prepared"); + check(reader.prepare(wrong,frames),"controlled new reader prepared"); + check(render(),"new B lease absent in ASRC must not break A"); + check(near(left[frames-1],.2f*monoCenter,0.005f), + "stale ASRC cannot be relabeled into newly leased device"); + reader.stop(); + clock.stop(); + std::puts("IO2_CLOCKED_NATIVE_PASS: two clocks -> qualified A+B -> single PCM/FX/MAIN; loss isolated"); +} +} // namespace armix::io2_clocked_test From fd103ef75a2a7ff81b114eddf008715632a42d25 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 20:29:55 +0700 Subject: [PATCH 24/57] feat(io2c): carry verified device map through native WIRE revisions and test real ASRC consumer --- engine/core/DynamicNativeSessionPublisher.h | 30 +++++++++++++------ tests/dual_asio_capture_probe_policy_test.cpp | 2 ++ .../QualifiedSecondaryCaptureReaderCases.h | 22 ++++++++++++++ 3 files changed, 45 insertions(+), 9 deletions(-) diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index f01866602..ba622dfc8 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -103,21 +103,33 @@ class DynamicNativeSessionPublisher final { !verifiedInternalFxOnly) { report.fault=Fault::outputArmed;return report; } + // CONTROL: the next BUS/WIRE/FX-only revision retains the exact + // already-qualified device map. Omitting the optional argument must + // never turn a dual-device graph into unqualified ordinal-only PCM. + // Replacing a device map is ALWAYS a hardware transaction requiring + // MAIN/MONITOR/output disarm, not a hidden in-place WIRE edit. + const auto* prior=publisher_.controlPrepared( + proposedDeviceEpoch,expectedRevision); + if(qualifiedInputMap&&!allOutputsDisarmed) { + report.fault=Fault::outputArmed;return report; + } + const auto* acceptedInputMap=qualifiedInputMap?qualifiedInputMap: + (prior&&prior->inputMap?prior->inputMap.get():nullptr); // CONTROL: validate every physical source against ONE actual // device-qualified map before starting a potentially costly graph // compile. Reject mixed old/new source namespaces as a transaction. - if(qualifiedInputMap) { - if(qualifiedInputMap->primaryEpoch()!=proposedDeviceEpoch || - qualifiedInputMap->deviceCount()<1 || - qualifiedInputMap->virtualInputCount()!=request.physicalInputs) { + if(acceptedInputMap) { + if(acceptedInputMap->primaryEpoch()!=proposedDeviceEpoch || + acceptedInputMap->deviceCount()<1 || + acceptedInputMap->virtualInputCount()!=request.physicalInputs) { report.fault=Fault::invalidCandidate;return report; } std::size_t matched=0; for(const auto& source:request.sources) { if(source.kind!=DynamicSourceKind::physical)continue; bool verified=false; - for(int i=0;isourceCount();++i) { - const auto& mapped=qualifiedInputMap->source(i); + for(int i=0;isourceCount();++i) { + const auto& mapped=acceptedInputMap->source(i); if(source.id==mapped.channel && source.inputL==mapped.inputL && source.inputR==mapped.inputR && @@ -130,7 +142,7 @@ class DynamicNativeSessionPublisher final { } ++matched; } - if(matched!=static_cast(qualifiedInputMap->sourceCount())) { + if(matched!=static_cast(acceptedInputMap->sourceCount())) { report.fault=Fault::invalidCandidate;return report; } } @@ -153,9 +165,9 @@ class DynamicNativeSessionPublisher final { report.fault=Fault::invalidGraph;return report; } prepared->physicalInputs=request.physicalInputs; - if(qualifiedInputMap) + if(acceptedInputMap) prepared->inputMap= - std::make_unique(*qualifiedInputMap); + std::make_unique(*acceptedInputMap); prepared->fx=std::move(fx); // one accepted control-plane publication prepared->monitor=std::any_of(roster.channels().begin(), roster.channels().end(),[](const ChannelStripDefinition& row) { diff --git a/tests/dual_asio_capture_probe_policy_test.cpp b/tests/dual_asio_capture_probe_policy_test.cpp index ea46f2907..0debc8057 100644 --- a/tests/dual_asio_capture_probe_policy_test.cpp +++ b/tests/dual_asio_capture_probe_policy_test.cpp @@ -3,6 +3,7 @@ #include "../engine/device/ClockBridgeSizing.h" #include "io2/QualifiedInputPlanCases.h" #include "io2/QualifiedInputGraphBridgeCases.h" +#include "io2/QualifiedSecondaryCaptureReaderCases.h" #include #include #include @@ -78,6 +79,7 @@ int main() check(!impossible.valid); armix::io2_test::run(); armix::io2_graph_test::run(); // same registered IO0 native CTest now compiles IO-2 + armix::io2_clocked_test::run(); // real producer ASRC -> native PCM/FX, B loss isolated std::puts("IO0_POLICY_PASS: identity, zero-output capture, exact masks, 9 clock profiles"); return 0; } diff --git a/tests/io2/QualifiedSecondaryCaptureReaderCases.h b/tests/io2/QualifiedSecondaryCaptureReaderCases.h index 52b6f99f9..82d261514 100644 --- a/tests/io2/QualifiedSecondaryCaptureReaderCases.h +++ b/tests/io2/QualifiedSecondaryCaptureReaderCases.h @@ -100,6 +100,28 @@ inline void run() { "B's real clock bridge PCM reaches MAIN with A"); check(reader.status().secondaryAccepted==1&&reader.status().overlaps==1, "one successful capture consumption, overlap rejected"); + // Structural WIRE/FX edits cannot silently drop the verified B map. + // An identical authenticated topology is allowed even with MAIN armed + // when the native caller proved this is internal WIRE-only. + const auto wired=native.commit(roster,request,1,epoch,epoch,false, + {},true,false); + check(wired.ok()&&wired.revision==2, + "WIRE-only graph revision inherits qualified input lease"); + check(render(),"B still audible after internal graph recompile"); + check(near(left[frames-1],.2f*monoCenter+.4f), + "committed BUS/WIRE revision retains capture B"); + auto wrongPatch=request; + wrongPatch.sources.back().inputL=1; // no longer exact B map + const auto wrong=native.commit(roster,wrongPatch,2,epoch,epoch,false, + {},true,false); + check(wrong.fault==m::DynamicNativeSessionPublisher::Fault::invalidCandidate + &&native.acceptedRevision()==2, + "cannot silently remap B by reusing native WIRE-only authorization"); + const auto whileArmed=native.commit(roster,request,2,epoch,epoch,false, + {},true,false,&plan); + check(whileArmed.fault==m::DynamicNativeSessionPublisher::Fault::outputArmed, + "explicit device map replacement must disarm MAIN first"); + // B lost/failed is SILENCE in B channels, never relabeled A Input1. clock.fault(); check(render(),"faulted B cannot block verified primary A"); From 802fd9dc51bc8d4b7a0b15eb25024841552fb340 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 20:30:22 +0700 Subject: [PATCH 25/57] test(io2c): use a genuinely wrong B ordinal in negative WIRE recompile --- tests/io2/QualifiedSecondaryCaptureReaderCases.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/io2/QualifiedSecondaryCaptureReaderCases.h b/tests/io2/QualifiedSecondaryCaptureReaderCases.h index 82d261514..6357b7459 100644 --- a/tests/io2/QualifiedSecondaryCaptureReaderCases.h +++ b/tests/io2/QualifiedSecondaryCaptureReaderCases.h @@ -111,7 +111,7 @@ inline void run() { check(near(left[frames-1],.2f*monoCenter+.4f), "committed BUS/WIRE revision retains capture B"); auto wrongPatch=request; - wrongPatch.sources.back().inputL=1; // no longer exact B map + wrongPatch.sources.back().inputL=0; // erroneously aliases A, no longer B map const auto wrong=native.commit(roster,wrongPatch,2,epoch,epoch,false, {},true,false); check(wrong.fault==m::DynamicNativeSessionPublisher::Fault::invalidCandidate From e39288c9873c176c8b5072d5e27d73df4bc7f795 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 20:34:22 +0700 Subject: [PATCH 26/57] test(io2c): run real ASRC-to-native-main proof in fast Linux C++ gate --- tests/mixer_routing_plan_test.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/mixer_routing_plan_test.cpp b/tests/mixer_routing_plan_test.cpp index 888108e35..1852d034e 100644 --- a/tests/mixer_routing_plan_test.cpp +++ b/tests/mixer_routing_plan_test.cpp @@ -4,6 +4,7 @@ #include "../engine/core/DynamicPreparedMixerBlock.h" #include "../engine/core/LegacyLiveGraphMigration.h" #include "../engine/core/DynamicNativeSessionPublisher.h" +#include "io2/QualifiedSecondaryCaptureReaderCases.h" #include #if defined(NDEBUG) #undef NDEBUG // Never skip P1A assertions in Release native CTest. @@ -1173,6 +1174,8 @@ static void verifyNativePrePostAndSendEnablePcm() { } int main() { + // Before paid Windows MSVC: prove the real IO1 ASRC feeds one native PCM graph. + armix::io2_clocked_test::run(); verifyNativePrePostAndSendEnablePcm(); verifyNativeInputGainBeforeFx(); verifyDynamicInPlacePhysicalIOBuffers(); From 48598313ef575bbd08b664bffa08c92fd147a1e5 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 20:35:52 +0700 Subject: [PATCH 27/57] fix(io2c): distinguish rejected native commit from a detached device-map test fixture --- tests/io2/QualifiedSecondaryCaptureReaderCases.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/io2/QualifiedSecondaryCaptureReaderCases.h b/tests/io2/QualifiedSecondaryCaptureReaderCases.h index 6357b7459..da4a722b9 100644 --- a/tests/io2/QualifiedSecondaryCaptureReaderCases.h +++ b/tests/io2/QualifiedSecondaryCaptureReaderCases.h @@ -112,9 +112,9 @@ inline void run() { "committed BUS/WIRE revision retains capture B"); auto wrongPatch=request; wrongPatch.sources.back().inputL=0; // erroneously aliases A, no longer B map - const auto wrong=native.commit(roster,wrongPatch,2,epoch,epoch,false, + const auto wrongCommit=native.commit(roster,wrongPatch,2,epoch,epoch,false, {},true,false); - check(wrong.fault==m::DynamicNativeSessionPublisher::Fault::invalidCandidate + check(wrongCommit.fault==m::DynamicNativeSessionPublisher::Fault::invalidCandidate &&native.acceptedRevision()==2, "cannot silently remap B by reusing native WIRE-only authorization"); const auto whileArmed=native.commit(roster,request,2,epoch,epoch,false, From fe6e4b18de18a77016c9e155739c7ce0dbdd5766 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 20:37:32 +0700 Subject: [PATCH 28/57] test(io2c): prove sample-rate conversion 44.1k B to 48k A through native MAIN --- tests/io2/QualifiedSecondaryCaptureReaderCases.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/io2/QualifiedSecondaryCaptureReaderCases.h b/tests/io2/QualifiedSecondaryCaptureReaderCases.h index da4a722b9..3dea480d5 100644 --- a/tests/io2/QualifiedSecondaryCaptureReaderCases.h +++ b/tests/io2/QualifiedSecondaryCaptureReaderCases.h @@ -64,8 +64,8 @@ inline void run() { d::SecondaryCaptureClockStream clock; const d::SecondaryCaptureClockStream::Format format{ - 48000.,48000.,frames,frames,2,captureGeneration,epoch,2002}; - check(clock.prepare(format)&&clock.activate(),"independent B producer ready"); + 44100.,48000.,frames,frames,2,captureGeneration,epoch,2002}; + check(clock.prepare(format)&&clock.activate(),"independent 44.1k B into 48k A ASRC ready"); std::array bLeft{},bRight{}; bLeft.fill(.4f);bRight.fill(.6f); const float* bInput[]{bLeft.data(),bRight.data()}; @@ -150,6 +150,6 @@ inline void run() { "stale ASRC cannot be relabeled into newly leased device"); reader.stop(); clock.stop(); - std::puts("IO2_CLOCKED_NATIVE_PASS: two clocks -> qualified A+B -> single PCM/FX/MAIN; loss isolated"); + std::puts("IO2_CLOCKED_NATIVE_PASS: 44.1k B -> ASRC -> 48k A qualified ChannelId PCM MAIN; loss isolated"); } } // namespace armix::io2_clocked_test From 74640cf511979a2521ce873f2ce2c34b533aa529 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 21:39:44 +0700 Subject: [PATCH 29/57] feat(io2d): add fail-closed A+B clock input to sole native callback Prepare LiveDryRoutingLab callback for the already-qualified two-device reader while keeping direct primary pointer path unchanged and the actual JUCE input count strictly verified. Reject partial reader/clock attachment; keep single native PCM/VST3 execution. CONTROL device opening and installed graph selection remain default-OFF and separate. --- engine/device/QualifiedCaptureHostMode.h | 15 +++++ src/LiveDryRoutingLab.h | 57 +++++++++++++++---- .../QualifiedSecondaryCaptureReaderCases.h | 13 +++++ 3 files changed, 73 insertions(+), 12 deletions(-) create mode 100644 engine/device/QualifiedCaptureHostMode.h diff --git a/engine/device/QualifiedCaptureHostMode.h b/engine/device/QualifiedCaptureHostMode.h new file mode 100644 index 000000000..a19f415a3 --- /dev/null +++ b/engine/device/QualifiedCaptureHostMode.h @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +// IO-2D: native callback selection is a pure rule, not another renderer. +// The existing qualified reader and publisher still check exact leases. +namespace armix::device { +enum class QualifiedCaptureHostMode { + directPrimary, qualifiedDual, rejectPartial +}; +constexpr QualifiedCaptureHostMode qualifiedCaptureHostMode( + bool hasReader,bool hasClock) noexcept { + if(!hasReader&&!hasClock)return QualifiedCaptureHostMode::directPrimary; + if(hasReader&&hasClock)return QualifiedCaptureHostMode::qualifiedDual; + return QualifiedCaptureHostMode::rejectPartial; +} +} // namespace armix::device diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 418465e7b..052dc4582 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -20,6 +20,8 @@ #include "../engine/core/ProductionRenderAudit.h" #include "../engine/core/LiveOutputRouteGate.h" #include "../engine/device/LiveInputPortRegistry.h" +#include "../engine/device/QualifiedSecondaryCaptureReader.h" +#include "../engine/device/QualifiedCaptureHostMode.h" #include #include #include @@ -3067,7 +3069,9 @@ class LiveDryRoutingLab final { std::array* actualMonitorPair=nullptr, bool allowMutedMetering=false, std::span playerPcm={}, - bool mainOnlyMuted=false) noexcept { + bool mainOnlyMuted=false, + armix::device::QualifiedSecondaryCaptureReader* secondaryReader=nullptr, + armix::device::SecondaryCaptureClockStream* secondaryClock=nullptr) noexcept { if(actualOutputPair)*actualOutputPair={{-1,-1}}; if(actualMonitorPair)*actualMonitorPair={{-1,-1}}; if(!active())return false; @@ -3249,17 +3253,46 @@ class LiveDryRoutingLab final { source.right?source.right+offset:nullptr}; } const auto noExtraFx=[](armix::mixer::ChannelId,float*,float*,int) noexcept {}; - processed=nativePublisher_.render( - generation,shifted.data(),inputCount, - meterOnly?mutedMain_[0].data():mainL+offset, - meterOnly?mutedMain_[1].data():mainR+offset,n,false,noExtraFx, - monitorL?(meterOnly?mutedMonitor_[0].data():monitorL+offset):nullptr, - monitorR?(meterOnly?mutedMonitor_[1].data():monitorR+offset):nullptr, - tapsL,tapsR, - std::span( - slice.data(),playerPcm.size()), - meterOnly?nullptr:outputSlices.data(), - meterOnly?0:outputCount); + // IO-2D: preserve exact physical A callback count above, + // while the accepted ChannelId graph may have A+B virtual + // capture ordinals. Only the original renderer owns FX. + // Qualified adapter is default-OFF until CONTROL installs + // a verified B clock/reader lease and matching PCM snapshot. + const auto renderNative=[&]( + std::span blocks) noexcept { + const bool qualified=!blocks.empty(); + return nativePublisher_.render( + generation,qualified?nullptr:shifted.data(), + qualified?0:inputCount, + meterOnly?mutedMain_[0].data():mainL+offset, + meterOnly?mutedMain_[1].data():mainR+offset,n,false,noExtraFx, + monitorL?(meterOnly?mutedMonitor_[0].data():monitorL+offset):nullptr, + monitorR?(meterOnly?mutedMonitor_[1].data():monitorR+offset):nullptr, + tapsL,tapsR, + std::span( + slice.data(),playerPcm.size()), + meterOnly?nullptr:outputSlices.data(), + meterOnly?0:outputCount,blocks); + }; + // Partial resource attachment must NEVER silently call raw + // A-only input ordinals against an installed A+B map. When + // qualified resources are absent, the publisher rejects + // direct raw pointers if its current PCM lease requires A+B. + switch(armix::device::qualifiedCaptureHostMode( + secondaryReader!=nullptr,secondaryClock!=nullptr)) { + case armix::device::QualifiedCaptureHostMode::directPrimary: + processed=renderNative({}); + break; + case armix::device::QualifiedCaptureHostMode::qualifiedDual: + processed=secondaryReader->withBlocks( + generation,shifted.data(),inputCount,n,*secondaryClock, + [&](std::span + blocks) noexcept { return renderNative(blocks); }); + break; + case armix::device::QualifiedCaptureHostMode::rejectPartial: + processed=false; + break; + } if(processed) { for(std::size_t ch=0;ch @@ -18,6 +19,18 @@ inline bool near(float a,float b,float tolerance=0.03f) { return std::abs(a-b) Date: Thu, 19 Nov 2026 21:42:49 +0700 Subject: [PATCH 30/57] feat(io2d): stage qualified B source and FX lease in single native transaction Add CONTROL-only admission that checks primary hardware callback pins, exact secondary ASRC generation/device lease and safe quantum, reuses existing VST3 lease bank, prepares reader off RT and commits one qualified ChannelId graph snapshot; reject stale/partial candidates without touching live PCM. Keep source default OFF and add negative deterministic tests. --- engine/device/QualifiedCaptureAdmission.h | 49 +++++++++ src/LiveDryRoutingLab.h | 99 +++++++++++++++++++ .../QualifiedSecondaryCaptureReaderCases.h | 23 +++++ 3 files changed, 171 insertions(+) create mode 100644 engine/device/QualifiedCaptureAdmission.h diff --git a/engine/device/QualifiedCaptureAdmission.h b/engine/device/QualifiedCaptureAdmission.h new file mode 100644 index 000000000..eee02635c --- /dev/null +++ b/engine/device/QualifiedCaptureAdmission.h @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "MultiDeviceInputPlan.h" +#include "SecondaryCaptureClockStream.h" +#include + +// CONTROL-side exact A/B admission; no driver query or realtime work. +// Caller MUST derive both device identities and masks from independently +// attested native hardware readback, never from display labels or .smix. +namespace armix::device { +class QualifiedCaptureAdmission final { +public: + enum class Fault { + none, stalePrimary, wrongTopology, wrongPrimaryPins, + secondaryNotReady, wrongCaptureLease, unsafeFrames + }; + static Fault verify(const MultiDeviceInputPlan& plan, + const SecondaryCaptureClockStream& clock, + std::uint64_t primaryEpoch, + int verifiedPrimaryInputCount, + int maximumRenderFrames) noexcept { + if(!primaryEpoch||plan.primaryEpoch()!=primaryEpoch|| + plan.deviceCount()!=2|| + plan.device(0).generation!=primaryEpoch) + return Fault::stalePrimary; + if(!plan.device(0).primary||plan.device(1).primary|| + !plan.device(0).deviceLease||!plan.device(1).deviceLease|| + plan.device(0).deviceLease==plan.device(1).deviceLease|| + plan.device(1).activePins<1|| + plan.device(1).activePins>16) + return Fault::wrongTopology; + if(verifiedPrimaryInputCount<1|| + plan.device(0).activePins!=verifiedPrimaryInputCount) + return Fault::wrongPrimaryPins; + if(maximumRenderFrames<1|| + maximumRenderFrames>MultiDeviceInputPlan::maxCallbackFrames) + return Fault::unsafeFrames; + if(!clock.ready())return Fault::secondaryNotReady; + const auto& format=clock.format(); // CONTROL only; not in RT + if(format.captureGeneration!=plan.device(1).generation|| + format.deviceLease!=plan.device(1).deviceLease|| + format.primaryEpoch!=primaryEpoch|| + format.channels!=plan.device(1).activePins|| + format.primaryPeriod<1||format.primaryPeriod>maximumRenderFrames) + return Fault::wrongCaptureLease; + return Fault::none; + } +}; +} // namespace armix::device diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 052dc4582..4f297d062 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -22,6 +22,8 @@ #include "../engine/device/LiveInputPortRegistry.h" #include "../engine/device/QualifiedSecondaryCaptureReader.h" #include "../engine/device/QualifiedCaptureHostMode.h" +#include "../engine/device/QualifiedCaptureAdmission.h" +#include "../engine/device/QualifiedInputGraphBridge.h" #include #include #include @@ -1980,6 +1982,103 @@ class LiveDryRoutingLab final { } } + // IO-2D CONTROL: stage B's already-open, independently attested ASIO + // capture inside THIS accepted native graph/FX lease. The caller keeps + // the output disarmed and owns the verified stream/device lifecycle; + // no GUI-local LIVE, second manager, processor, or output auto-arm. + // The matching reader/clock are then passed to process() by the same + // native host on the PRIMARY callback. No hardware is opened here. + NativeBusResult installQualifiedSecondaryInput( + std::uint64_t expectedEpoch,std::uint64_t expectedPcmRevision, + std::uint64_t expectedRosterRevision, + const armix::device::MultiDeviceInputPlan& plan, + armix::device::QualifiedSecondaryCaptureReader& reader, + armix::device::SecondaryCaptureClockStream& clock, + bool outputsDisarmed, + const std::function& beforePublish={}) { + using namespace armix::mixer; + NativeBusResult reply{}; + reply.pcmRevision=nativeAccepted_.pcmRevision; + reply.rosterRevision=nativeAccepted_.graph.roster.revision(); + if(!outputsDisarmed) { + reply.error="OUTPUT_MUST_BE_DISARMED";return reply; + } + if(!channelIdPhysicalPcmActive()||!ready()|| + expectedEpoch!=epoch()||nativeAccepted_.deviceEpoch!=expectedEpoch|| + expectedPcmRevision!=nativeAccepted_.pcmRevision|| + expectedRosterRevision!=nativeAccepted_.graph.roster.revision()|| + !nativeAccepted_.fxOwners) { + reply.error="STALE_NATIVE_CAPTURE_GRAPH";return reply; + } + if(reader.status().ready) { + reply.error="CAPTURE_READER_ALREADY_ATTACHED";return reply; + } + const auto fault=armix::device::QualifiedCaptureAdmission::verify( + plan,clock,expectedEpoch, + callbackInputCount_.load(std::memory_order_acquire), + nativeAccepted_.graph.request.maxFrames); + if(fault!=armix::device::QualifiedCaptureAdmission::Fault::none) { + reply.error="SECONDARY_CAPTURE_LEASE_OR_MASK_REJECTED";return reply; + } + try { + DynamicGraphRequest staged; + armix::device::QualifiedInputGraphBridge::Fault stageFault{}; + if(!armix::device::QualifiedInputGraphBridge::stage( + plan,nativeAccepted_.graph.request,staged,stageFault)) { + reply.error="QUALIFIED_INPUT_GRAPH_REJECTED";return reply; + } + DynamicChannelFxLeaseBank bank; + if(DynamicChannelFxLeaseBank::reuseRevision( + expectedEpoch,expectedPcmRevision+1, + *nativeAccepted_.fxOwners,bank)!= + DynamicChannelFxLeaseBank::Fault::none) { + reply.error="QUALIFIED_INPUT_FX_LEASE_REJECTED";return reply; + } + auto owner=std::make_shared(std::move(bank)); + owner->bindGlobalRackOverride(&globalFxBypassed_); + DynamicNativeSessionPublisher::FxPlan fx; + fx.owner=std::static_pointer_cast(owner); + fx.context=owner.get(); + fx.render=+[](void* ctx,ChannelId id,float* left,float* right,int n) noexcept { + (*static_cast(ctx))(id,left,right,n); + }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; + fx.deviceEpoch=expectedEpoch; + fx.graphRevision=expectedPcmRevision+1; + if(!reader.prepare(plan,staged.maxFrames)) { + reply.error="QUALIFIED_READER_PREPARE_REJECTED";return reply; + } + try { + if(beforePublish)beforePublish(); + const auto published=nativePublisher_.commit( + nativeAccepted_.graph.roster,staged,expectedPcmRevision, + expectedEpoch,epoch(),true,std::move(fx), + false,false,&plan); + if(!published.ok()) { + reader.stop(); // detached failure; old PCM remains valid + reply.error="QUALIFIED_INPUT_PCM_COMMIT_REJECTED";return reply; + } + nativeAccepted_.graph.request=std::move(staged); + nativeAccepted_.fxOwners=std::move(owner); + nativeAccepted_.pcmRevision=published.revision; + reapplyExternalOutputsSameEpoch(); + nativeStructureLive_=true; + nativeMeterEpoch_.store(0,std::memory_order_release); + reply.accepted=true;reply.error=""; + reply.pcmRevision=published.revision; + reply.rosterRevision=nativeAccepted_.graph.roster.revision(); + return reply; + }catch(...) { + reader.stop(); + reply.error="QUALIFIED_CAPTURE_PUBLICATION_FAILED";return reply; + } + }catch(...) { + reply.error="QUALIFIED_CAPTURE_PREPARE_FAILED";return reply; + } + } + // Wire a verified physical capture pin to a dynamically CREATED input. // M4-owned CH1–10 keep the original device/VST continuity contract. // Prepared topology + lease revision is published once; never patch an diff --git a/tests/io2/QualifiedSecondaryCaptureReaderCases.h b/tests/io2/QualifiedSecondaryCaptureReaderCases.h index b5cdfd9d9..9f12bf60a 100644 --- a/tests/io2/QualifiedSecondaryCaptureReaderCases.h +++ b/tests/io2/QualifiedSecondaryCaptureReaderCases.h @@ -2,6 +2,7 @@ #pragma once #include "../../engine/device/QualifiedSecondaryCaptureReader.h" #include "../../engine/device/QualifiedCaptureHostMode.h" +#include "../../engine/device/QualifiedCaptureAdmission.h" #include "../../engine/device/QualifiedInputGraphBridge.h" #include "../../engine/core/DynamicNativeSessionPublisher.h" #include @@ -79,6 +80,28 @@ inline void run() { const d::SecondaryCaptureClockStream::Format format{ 44100.,48000.,frames,frames,2,captureGeneration,epoch,2002}; check(clock.prepare(format)&&clock.activate(),"independent 44.1k B into 48k A ASRC ready"); + using Admission=d::QualifiedCaptureAdmission; + check(Admission::verify(plan,clock,epoch,1,frames)==Admission::Fault::none, + "exact two-device qualified CONTROL admission"); + check(Admission::verify(plan,clock,epoch+1,1,frames)== + Admission::Fault::stalePrimary, + "stale A output epoch cannot publish qualified PCM"); + check(Admission::verify(plan,clock,epoch,2,frames)== + Admission::Fault::wrongPrimaryPins, + "virtual A+B input count must not replace real A callback count"); + check(Admission::verify(plan,clock,epoch,1,0)== + Admission::Fault::unsafeFrames, + "no zero or unsafe native callback scratch capacity"); + auto wrongDevice=devices; + wrongDevice[1].deviceLease=3003; + d::MultiDeviceInputPlan wrongLeasePlan; + check(d::MultiDeviceInputPlan::prepare(epoch,wrongDevice,bindings, + roster.channels(),wrongLeasePlan,err), + "negative independent B lease candidate prepared"); + check(Admission::verify(wrongLeasePlan,clock,epoch,1,frames)== + Admission::Fault::wrongCaptureLease, + "driver B ASRC lease cannot silently follow device-map rebind"); + std::array bLeft{},bRight{}; bLeft.fill(.4f);bRight.fill(.6f); const float* bInput[]{bLeft.data(),bRight.data()}; From 8bff7b89886d64a5da3b3afb43e5862a86694979 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 21:55:09 +0700 Subject: [PATCH 31/57] feat(io2d): opt-in real B ASIO capture host to one accepted native graph Native control validates exact primary A driver/pin readback and B independent ASIO class, explicit B input mask, rate/period and generation/lease before preparing device-qualified ChannelId sources and one PCM/FX transaction. Sole LiveAudioEngine callback conditionally consumes verified B ASRC without a second renderer; loss of B yields silence only for B, direct A-only remains default-OFF. Preserve output mute/ARM and device lifecycle; no JS LIVE claim or .smix hardware FAT. --- engine/device/LiveSecondaryCaptureDevice.h | 3 + src/LiveAudioEngine.h | 176 ++++++++++++++++++++- src/LiveDryRoutingLab.h | 17 ++ 3 files changed, 195 insertions(+), 1 deletion(-) diff --git a/engine/device/LiveSecondaryCaptureDevice.h b/engine/device/LiveSecondaryCaptureDevice.h index 47972b05f..916171a0f 100644 --- a/engine/device/LiveSecondaryCaptureDevice.h +++ b/engine/device/LiveSecondaryCaptureDevice.h @@ -198,6 +198,9 @@ class LiveSecondaryCaptureDevice final bool ready() const noexcept{return opened_.load(std::memory_order_acquire)&& stream_.ready();} bool faulted() const noexcept{return stream_.faulted();} + // Borrowed ONLY from the one native primary callback; lifetime owned by + // this LiveSecondaryCaptureDevice and serialized CONTROL stop/close. + SecondaryCaptureClockStream& clockStream() noexcept{return stream_;} Readback readback() const // CONTROL only: called after driver lifecycle { Readback b; diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 42951518e..1afad6f40 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -18,6 +18,7 @@ #include "DiagnosticTone.h" #include "../engine/device/JuceIndependentClockDevice.h" #include "../engine/device/LiveSecondaryOutputDevice.h" +#include "../engine/device/LiveSecondaryCaptureDevice.h" #include "../engine/core/LiveOutputRouteGate.h" #include "../engine/core/NativeOutputTransition.h" #include "../engine/core/NativeRenderAuthority.h" @@ -41,6 +42,9 @@ #include #include #include +#include +#include +#include // One live stereo input path and up to 8 actual VST3 processors. // The audio callback never scans files, creates plugins, mutates the chain, @@ -292,12 +296,15 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void stop() { dryRoutingLab_.disable(); + qualifiedSecondaryInstalled_.store(false,std::memory_order_release); directFence_.suspend(); asioPinnedRegistration_ = {}; asioRegistrationScope_ = "NONE"; secondaryOutput_.stop(); // stop independent OBS consumer before audio graph teardown independent_.close(); detach(); + qualifiedSecondaryReader_.stop(); // CONTROL: all callback borrows retired + secondaryCapture_.close(); // producer driver B stops after primary detach handoff_.resetAfterStop (graphOwned_.get()); // Last owner releases vendor resources exactly once after detach. // Reused instances remain valid until their final control-owned slot. @@ -432,6 +439,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback else if(wantsMainContinuation())resumeMainAfterAsioReset_.store(true,std::memory_order_release); setOutputMuted(true); secondaryOutput_.disarm(); + qualifiedSecondaryInstalled_.store(false,std::memory_order_release); + qualifiedSecondaryReader_.stop(); // CONTROL only, while output muted + secondaryCapture_.close(); directFence_.suspend(); // Do NOT disable the accepted ChannelId graph. Audio Setup is a // device-binding operation, not an implicit CLEAR MIXER command. @@ -2366,6 +2376,156 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback true,beforePublish); }); } + // IO-2D native product host boundary. This entrypoint is deliberately + // NOT exposed as a web/JS activation yet: a serialized user-approved + // native command must provide exact verified binding intent and wait for + // independently matching installed PCM readback before displaying LIVE. + struct QualifiedPhysicalSourceChoice final { + armix::mixer::ChannelId channel{}; + bool onSecondary=false; + int leftPhysical=-1,rightPhysical=-1; + bool stereo=false; + }; + LiveDryRoutingLab::NativeBusResult installSecondaryAsioCapture( + const juce::String& secondaryDriver, + const juce::BigInteger& selectedSecondaryPins, + double requestedCaptureHz,int requestedCaptureFrames, + std::uint64_t expectedEpoch,std::uint64_t expectedPcmRevision, + std::uint64_t expectedRosterRevision, + std::span selectedSources) { + namespace d=armix::device; + LiveDryRoutingLab::NativeBusResult reply{}; + reply.error="SECONDARY_CAPTURE_NOT_ADMITTED"; + if(!allOutputsDisarmed()||independent_.active()||!attached_|| + !directFence_.permitted()||qualifiedSecondaryInstalled_.load( + std::memory_order_acquire)||secondaryCapture_.ready()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal|| + handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0|| + deviceManager_.getCurrentAudioDeviceType()!="ASIO"|| + !asioPinnedRegistration_.valid()|| + expectedEpoch!=dryRoutingLab_.epoch()|| + !dryRoutingLab_.channelIdPhysicalPcmActive()|| + selectedSources.empty())return reply; + auto* primary=deviceManager_.getCurrentAudioDevice(); + if(!primary||!primary->isOpen()||primary->getTypeName()!="ASIO") + return reply; + d::JuceActivePortSnapshot pins; + d::JuceActivePortSnapshot::Fault portFault{}; + if(!d::JuceActivePortSnapshot::capture(primary,expectedEpoch, + pins,portFault)||!dryRoutingLab_.matchesSessionDevice(pins)|| + pins.inputs.enabledCount<1) { + reply.error="PRIMARY_CAPTURE_MASK_NOT_VERIFIED";return reply; + } + if(secondaryLeaseSequence_>std::numeric_limits::max()-3) { + reply.error="SECONDARY_LEASE_EXHAUSTED";return reply; + } + // New native-issued leases every attempt; never reuse a stale B + // generation after a driver fault, disconnect or source remap. + const auto primaryLease=++secondaryLeaseSequence_; + const auto secondaryLease=++secondaryLeaseSequence_; + const auto captureGeneration=secondaryLease; + auto error=secondaryCapture_.open(secondaryDriver,primary->getName(), + selectedSecondaryPins,requestedCaptureHz,requestedCaptureFrames, + primary->getCurrentSampleRate(),primary->getCurrentBufferSizeSamples(), + captureGeneration,expectedEpoch,secondaryLease); + if(error.isNotEmpty()) { + reply.error="SECONDARY_ASIO_OPEN_REJECTED";return reply; + } + const auto rollback=[&]() noexcept { + qualifiedSecondaryReader_.stop(); + secondaryCapture_.close(); + }; + try { + const auto b=secondaryCapture_.readback(); + if(!b.ready||b.faulted|| + b.primaryEpoch!=expectedEpoch|| + b.captureGeneration!=captureGeneration|| + b.deviceLease!=secondaryLease|| + b.callbackInputs!=selectedSecondaryPins.countNumberOfSetBits()|| + b.activeInputPins!=selectedSecondaryPins) { + rollback();reply.error="SECONDARY_ASIO_READBACK_MISMATCH";return reply; + } + const auto classB=d::AsioRegistryIdentityProbe::resolve( + std::wstring(secondaryDriver.toWideCharPointer())).registration; + if(!classB.ok()|| + asioPinnedRegistration_.sameDriverClass(classB.identity)) { + rollback();reply.error="SECONDARY_ASIO_CLASS_NOT_INDEPENDENT";return reply; + } + // Ephemeral in-session keys refer to two independently attested + // native driver classes and distinct leases; NOT persistent USB + // endpoint GUIDs. Offline .smix remap remains explicitly pending. + const std::string aKey="ASIO_PRIMARY:"+ + juce::String(asioPinnedRegistration_.canonicalClsid.c_str()).toStdString()+ + ":"+std::to_string(expectedEpoch); + const std::string bKey="ASIO_CAPTURE:"+ + juce::String(classB.identity.canonicalClsid.c_str()).toStdString()+ + ":"+std::to_string(secondaryLease); + std::array primaryPins{}; + for(int i=0;i secondaryPins{}; + int bCount=0; + for(int index=b.activeInputPins.findNextSetBit(0);index>=0; + index=b.activeInputPins.findNextSetBit(index+1)) { + if(bCount>=16) { + rollback();reply.error="SECONDARY_PIN_COUNT_EXCEEDED";return reply; + } + secondaryPins[bCount++]=index; + } + std::array devices{{ + {aKey,expectedEpoch,true, + std::span(primaryPins.data(), + static_cast(pins.inputs.enabledCount)), + primaryLease}, + {bKey,captureGeneration,false, + std::span(secondaryPins.data(), + static_cast(bCount)),secondaryLease} + }}; + std::vector bindings; + bindings.reserve(selectedSources.size()); + for(const auto& row:selectedSources) { + const std::string_view key=row.onSecondary?bKey:aKey; + d::QualifiedChannelSource next; + next.channel=row.channel; + next.left={key,row.leftPhysical}; + next.stereo=row.stereo; + if(row.stereo)next.right={key,row.rightPhysical}; + bindings.push_back(next); + } + d::MultiDeviceInputPlan plan; + d::MultiDeviceInputFault planFault{}; + if(!dryRoutingLab_.prepareQualifiedCapturePlan( + expectedEpoch,devices,bindings,plan,planFault)) { + rollback();reply.error="SECONDARY_SOURCE_MAP_REJECTED";return reply; + } + const auto verified=dryRoutingLab_.installQualifiedSecondaryInput( + expectedEpoch,expectedPcmRevision,expectedRosterRevision,plan, + qualifiedSecondaryReader_,secondaryCapture_.clockStream(),true); + if(!verified.accepted) { + rollback();return verified; + } + // One release-store AFTER the same snapshot/FX publication. + // Before this flag, a qualified map rejects raw A-only inputs, + // so a transient callback is SILENT, never wrong-device PCM. + qualifiedSecondaryInstalled_.store(true,std::memory_order_release); + return verified; + } catch(...) { + rollback(); + reply.error="SECONDARY_CAPTURE_CONTROL_PREPARE_FAILED"; + return reply; + } + } + // Disconnecting B intentionally retains the already-qualified map and + // ChannelId/FX snapshot: primary A keeps playing; B slots fail SILENT. + // A future explicit new binding requires output disarm and exact remap. + void disconnectSecondaryAsioCapture() { + secondaryCapture_.close(); // CONTROL, never audio callback + } + armix::device::LiveSecondaryCaptureDevice::Readback + secondaryCaptureReadback() const {return secondaryCapture_.readback();} + template LiveDryRoutingLab::NativeBusResult editNativeInputTopology( std::uint64_t epoch,const char* unavailable,const char* exception, @@ -2926,6 +3086,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String startupFallbackReason_; // control-thread-only startup diagnostics armix::device::JuceIndependentClockDevice independent_; armix::device::LiveSecondaryOutputDevice secondaryOutput_; + // IO-2D: separate ASIO input B is capture-only. Both PCM streams enter + // the ONE existing ChannelId/FX callback only after CONTROL admission. + armix::device::LiveSecondaryCaptureDevice secondaryCapture_; + armix::device::QualifiedSecondaryCaptureReader qualifiedSecondaryReader_; + std::atomic qualifiedSecondaryInstalled_{false}; + std::uint64_t secondaryLeaseSequence_=0; // CONTROL only, never callback std::optional savedDirectSetup_; juce::AudioPluginFormatManager formats_; // Strong ownership stays on CONTROL. The admitted native ChannelId @@ -3060,6 +3226,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } setOutputMuted(true); // transient hardware gate, NOT an operator MUTE secondaryOutput_.invalidateSource(); // source clock may have changed + qualifiedSecondaryInstalled_.store(false,std::memory_order_release); + secondaryCapture_.invalidatePrimaryClock(); // RT-safe fault only dryRoutingLab_.prepareDevice(d); // exact active mask, before callback if (!independent_.active()) { @@ -3121,6 +3289,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback monitor_.store(false,std::memory_order_release); secondaryOutput_.invalidateSource(); // explicit reconnect required after device stop masterLoudness_.prepare (0.0); // clear validity across device epoch + qualifiedSecondaryInstalled_.store(false,std::memory_order_release); + secondaryCapture_.invalidatePrimaryClock(); // no driver teardown in JUCE callback dryRoutingLab_.deviceStopped(); playerDeck_.deviceRate(0.0); // invalidates old PCM generation deviceStopCount_.fetch_add (1, std::memory_order_relaxed); @@ -3381,7 +3551,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback !routeReconfiguring_.load(std::memory_order_acquire) && !topologyPublicationMute_.load(std::memory_order_acquire), std::span( - deckBlocks.data(),deckCount),mainOnlyMuted); + deckBlocks.data(),deckCount),mainOnlyMuted, + qualifiedSecondaryInstalled_.load(std::memory_order_acquire) + ?&qualifiedSecondaryReader_:nullptr, + qualifiedSecondaryInstalled_.load(std::memory_order_acquire) + ?&secondaryCapture_.clockStream():nullptr); // Constant-time, callback-local physical PCM tap. Nothing is // reconfigured or acquired from another graph generation. const auto nativeMain=armix::mixer::NativeOutputPairTap::select( diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 4f297d062..0853fe4d6 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1982,6 +1982,23 @@ class LiveDryRoutingLab final { } } + // CONTROL staging only: check the current accepted ChannelId roster. + // Source bindings and exact hardware masks must originate from genuine + // native device preflight; offline friendly names cannot authorize PCM. + bool prepareQualifiedCapturePlan( + std::uint64_t expectedEpoch, + std::span devices, + std::span bindings, + armix::device::MultiDeviceInputPlan& destination, + armix::device::MultiDeviceInputFault& fault) const { + if(!channelIdPhysicalPcmActive()||!ready()|| + expectedEpoch!=epoch()||nativeAccepted_.deviceEpoch!=expectedEpoch|| + !nativeAccepted_.fxOwners)return false; + return armix::device::MultiDeviceInputPlan::prepare( + expectedEpoch,devices,bindings, + nativeAccepted_.graph.roster.channels(),destination,fault); + } + // IO-2D CONTROL: stage B's already-open, independently attested ASIO // capture inside THIS accepted native graph/FX lease. The caller keeps // the output disarmed and owns the verified stream/device lifecycle; From 371a80e2753f48002eeb1dff820a2b39eaffd94e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 21:56:26 +0700 Subject: [PATCH 32/57] fix(io2d): sample qualified secondary callback attachment once per primary render --- src/LiveAudioEngine.h | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 1afad6f40..4d63cdabd 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -3541,6 +3541,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback playerScratch_[1].data()}; deckCount=1; } + // One acquire: CONTROL changes the admitted A+B resource pair + // atomically; a callback never observes half a pair. + const bool qualifiedInput=qualifiedSecondaryInstalled_.load( + std::memory_order_acquire); const bool routed=dryRoutingLab_.process(inputs,inputChannels,outputs, outputChannels,samples, masterGain_.load(std::memory_order_relaxed), @@ -3552,10 +3556,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback !topologyPublicationMute_.load(std::memory_order_acquire), std::span( deckBlocks.data(),deckCount),mainOnlyMuted, - qualifiedSecondaryInstalled_.load(std::memory_order_acquire) - ?&qualifiedSecondaryReader_:nullptr, - qualifiedSecondaryInstalled_.load(std::memory_order_acquire) - ?&secondaryCapture_.clockStream():nullptr); + qualifiedInput?&qualifiedSecondaryReader_:nullptr, + qualifiedInput?&secondaryCapture_.clockStream():nullptr); // Constant-time, callback-local physical PCM tap. Nothing is // reconfigured or acquired from another graph generation. const auto nativeMain=armix::mixer::NativeOutputPairTap::select( From 30d8c2593bbb79a54adeba96a4b2cc1f3e5a859e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 22:02:55 +0700 Subject: [PATCH 33/57] fix(io2d): retain A+B qualified capture across no-op Audio Setup; fail closed on real primary restart --- src/LiveAudioEngine.h | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 4d63cdabd..bbcb31612 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -297,6 +297,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { dryRoutingLab_.disable(); qualifiedSecondaryInstalled_.store(false,std::memory_order_release); + qualifiedCaptureNeedsRemap_.store(false,std::memory_order_release); directFence_.suspend(); asioPinnedRegistration_ = {}; asioRegistrationScope_ = "NONE"; @@ -439,15 +440,24 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback else if(wantsMainContinuation())resumeMainAfterAsioReset_.store(true,std::memory_order_release); setOutputMuted(true); secondaryOutput_.disarm(); - qualifiedSecondaryInstalled_.store(false,std::memory_order_release); - qualifiedSecondaryReader_.stop(); // CONTROL only, while output muted - secondaryCapture_.close(); + // A no-op AUDIO SETUP must not destroy the live A+B graph's reader: + // finishManualAudioSetup() can retain this exact same PCM lease. + // If JUCE actually restarts A, its lifecycle callback fences B and + // marks that physical binding as requiring an explicit remap. directFence_.suspend(); // Do NOT disable the accepted ChannelId graph. Audio Setup is a // device-binding operation, not an implicit CLEAR MIXER command. // The JUCE selector may change the driver before its window closes. } bool finishManualAudioSetup(bool reuseAsioBinding=true) { + if(qualifiedCaptureNeedsRemap_.load(std::memory_order_acquire)) { + // The primary hardware epoch changed. Never claim a retained + // dual-source map is installed on the newly opened ASIO class. + setOutputMuted(true); + qualifiedSecondaryReader_.stop(); + secondaryCapture_.close(); + return false; // explicit native physical remap required + } if(!approveDirectRoute())return false; using Decision=armix::device::DeviceSessionDecision; switch(armix::device::decideDeviceSession( @@ -2398,6 +2408,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback reply.error="SECONDARY_CAPTURE_NOT_ADMITTED"; if(!allOutputsDisarmed()||independent_.active()||!attached_|| !directFence_.permitted()||qualifiedSecondaryInstalled_.load( + std::memory_order_acquire)||qualifiedCaptureNeedsRemap_.load( std::memory_order_acquire)||secondaryCapture_.ready()|| routeReconfiguring_.load(std::memory_order_acquire)|| diagnosticRoute_.load(std::memory_order_acquire)!= @@ -2509,6 +2520,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // One release-store AFTER the same snapshot/FX publication. // Before this flag, a qualified map rejects raw A-only inputs, // so a transient callback is SILENT, never wrong-device PCM. + qualifiedCaptureNeedsRemap_.store(false,std::memory_order_release); qualifiedSecondaryInstalled_.store(true,std::memory_order_release); return verified; } catch(...) { @@ -3091,6 +3103,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback armix::device::LiveSecondaryCaptureDevice secondaryCapture_; armix::device::QualifiedSecondaryCaptureReader qualifiedSecondaryReader_; std::atomic qualifiedSecondaryInstalled_{false}; + std::atomic qualifiedCaptureNeedsRemap_{false}; // device lifecycle invalidated B std::uint64_t secondaryLeaseSequence_=0; // CONTROL only, never callback std::optional savedDirectSetup_; juce::AudioPluginFormatManager formats_; @@ -3226,7 +3239,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } setOutputMuted(true); // transient hardware gate, NOT an operator MUTE secondaryOutput_.invalidateSource(); // source clock may have changed - qualifiedSecondaryInstalled_.store(false,std::memory_order_release); + if(qualifiedSecondaryInstalled_.exchange(false,std::memory_order_acq_rel)) + qualifiedCaptureNeedsRemap_.store(true,std::memory_order_release); secondaryCapture_.invalidatePrimaryClock(); // RT-safe fault only dryRoutingLab_.prepareDevice(d); // exact active mask, before callback if (!independent_.active()) @@ -3289,7 +3303,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback monitor_.store(false,std::memory_order_release); secondaryOutput_.invalidateSource(); // explicit reconnect required after device stop masterLoudness_.prepare (0.0); // clear validity across device epoch - qualifiedSecondaryInstalled_.store(false,std::memory_order_release); + if(qualifiedSecondaryInstalled_.exchange(false,std::memory_order_acq_rel)) + qualifiedCaptureNeedsRemap_.store(true,std::memory_order_release); secondaryCapture_.invalidatePrimaryClock(); // no driver teardown in JUCE callback dryRoutingLab_.deviceStopped(); playerDeck_.deviceRate(0.0); // invalidates old PCM generation From 633d5973cbe1016ef9a00205181cef32a376911e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 03:59:23 +0700 Subject: [PATCH 34/57] fix(io2d): expose exact accepted qualified-map presence for safe .smix persistence gate --- engine/core/DynamicNativeSessionPublisher.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index ba622dfc8..4f1552d15 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -487,6 +487,14 @@ class DynamicNativeSessionPublisher final { const auto* p=publisher_.controlPrepared(epoch,revision); return p?p->graph.latencySamples():0; } + // CONTROL-only durability guard: v1 .smix binds only the primary A + // hardware mask. Qualified A+B virtual input ordinals cannot safely + // replace physical device-qualified saved source intent. + bool hasQualifiedInputMap(std::uint64_t epoch, + std::uint64_t revision) const noexcept { + const auto* p=publisher_.controlPrepared(epoch,revision); + return p && static_cast(p->inputMap); + } void unpublish() noexcept {publisher_.unpublish();} void pollRetirement() noexcept {publisher_.pollRetirement();} std::uint64_t acceptedRevision() const noexcept { From 5efe446c490196de0dd42647973debf11f107435 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 03:59:38 +0700 Subject: [PATCH 35/57] fix(io2d): reject unsafe .smix saves before replacing last recoverable A+B checkpoint --- src/LiveDryRoutingLab.h | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 0853fe4d6..cfec62597 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2499,6 +2499,15 @@ class LiveDryRoutingLab final { (retained && channelIdPhysicalPcmActive()) || !nativeAccepted_.matches(nativePublisher_,documentEpoch,nativeAccepted_.pcmRevision)) return "No authoritative native ChannelId graph"; + // IO-2D persistence P1: v1 .smix can store primary A physical + // HardwareBinding only. Saving a qualified A+B graph would persist + // virtual callback ordinals with no B device identity, making the + // new file unrestorable and destroying recoverable autosave state. + // Reject BEFORE writing document/blobs or enqueueing any save worker. + // IO-5 must add durable device-qualified source binding first. + if(nativePublisher_.hasQualifiedInputMap( + documentEpoch,nativeAccepted_.pcmRevision)) + return "SECONDARY_CAPTURE_NEEDS_SMIX_BINDING_SCHEMA: old checkpoint preserved; disconnect/remap B or wait for qualified persistence"; if(nativeAccepted_.fxOwners->externalChannel().value) return "External CH1 FX owner cannot yet be serialized independently"; // MAIN and STREAM are muted by the caller. Wait briefly for the From 603e623f23a07ba657fc8d248663c7012f3766c0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 03:59:50 +0700 Subject: [PATCH 36/57] test(io2d): qualified graph and WIRE revisions keep v1 .smix save fence --- tests/io2/QualifiedSecondaryCaptureReaderCases.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/io2/QualifiedSecondaryCaptureReaderCases.h b/tests/io2/QualifiedSecondaryCaptureReaderCases.h index 9f12bf60a..203ec2789 100644 --- a/tests/io2/QualifiedSecondaryCaptureReaderCases.h +++ b/tests/io2/QualifiedSecondaryCaptureReaderCases.h @@ -75,6 +75,11 @@ inline void run() { m::DynamicNativeSessionPublisher native; check(native.commit(roster,request,0,epoch,epoch,true, {},false,false,&plan).ok(),"one PCM and device map publication"); + check(native.hasQualifiedInputMap(epoch,1), + "v1 .smix cannot safely save virtual A+B input ordinals"); + check(!native.hasQualifiedInputMap(epoch+1,1)&& + !native.hasQualifiedInputMap(epoch,0), + "stale graph generation cannot authorize persistence"); d::SecondaryCaptureClockStream clock; const d::SecondaryCaptureClockStream::Format format{ @@ -143,6 +148,8 @@ inline void run() { {},true,false); check(wired.ok()&&wired.revision==2, "WIRE-only graph revision inherits qualified input lease"); + check(native.hasQualifiedInputMap(epoch,2), + "WIRE-only revision must not restore unsafe v1 .smix saving"); check(render(),"B still audible after internal graph recompile"); check(near(left[frames-1],.2f*monoCenter+.4f), "committed BUS/WIRE revision retains capture B"); From 877477ac71c6d2594dc0b90219f5b76eb97a405d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 04:06:20 +0700 Subject: [PATCH 37/57] fix(io2d): retire A+B capture admission before CLEAR PATCH or primary-only mixer replacement --- src/LiveAudioEngine.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index bbcb31612..1eabeab35 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1369,11 +1369,27 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return error; } + // CONTROL ONLY; no audio callback may block or free driver state. + // Stop the qualified view before closing B's capture producer. In-flight + // primary reads finish under the reader's own RT lease. The subsequent + // new primary-only graph then uses raw A pointers again, without a + // stale A+B map or a second render owner. + void retireQualifiedCaptureForNewGraph() noexcept { + qualifiedSecondaryInstalled_.store(false,std::memory_order_release); + qualifiedSecondaryReader_.stop(); + secondaryCapture_.close(); + qualifiedCaptureNeedsRemap_.store(false,std::memory_order_release); + } + // Historical STOP command retained as a safe CLEAR PATCH alias. // Returning to legacy CH1 is explicitly forbidden in NORMAL production. juce::String clearProductionRouting() { setOutputMuted(true); secondaryOutput_.disarm(); + // IO-2D: an A+B qualified input lease cannot be passed to the fresh + // primary-only graph. Retire both resources while CONTROL has muted + // every output, before unpublishing the old graph. + retireQualifiedCaptureForNewGraph(); dryRoutingLab_.disable(); return startUnpatchedProductionSession(); } @@ -1383,6 +1399,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const juce::var& command, const LiveDryRoutingLab::FxSelections& fx, const LiveDryRoutingLab::FxRestores* restored=nullptr) { + // A successful legacy M4 apply would supersede A+B virtual input + // layout. Require an explicit CLEAR PATCH rather than dropping its + // reader on a speculative edit that might fail validation. + if(qualifiedSecondaryInstalled_.load(std::memory_order_acquire)) + return "CLEAR PATCH and explicitly remove secondary capture before applying M4 routing"; if (dryRoutingLab_.nativeBusTopologyLive()) return "REMOVE native GROUP/FX RETURN buses before applying an M4 route"; if (!allOutputsDisarmed()) return "MUTE hardware output and DISARM STREAM before APPLY routing"; @@ -1418,6 +1439,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } void disableDryRoutingLab() noexcept { setOutputMuted(true); // never expose CH1 unexpectedly on STOP + retireQualifiedCaptureForNewGraph(); dryRoutingLab_.disable(); } // One structural graph transaction for SOURCE, OUT, M/ST and FX inserts: From ca25c4aaf6959dab2c9de37a8e3020ae7a003497 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 04:06:52 +0700 Subject: [PATCH 38/57] fix(io2d): also fence qualified B reader across primary-device diagnostic and new-session transitions --- src/LiveAudioEngine.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 1eabeab35..f5197b3da 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -723,6 +723,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // native NORMAL mixer ready, not stranded without a session. if(dryRoutingLab_.active()) { setOutputMuted(true); + retireQualifiedCaptureForNewGraph(); dryRoutingLab_.disable(); } directFence_.suspend(); // independent path bypasses only this DIRECT fence @@ -810,6 +811,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // selecting a one-sided device. No phantom hardware output or CH1 mix. if(dryRoutingLab_.active()) { setOutputMuted(true); + retireQualifiedCaptureForNewGraph(); dryRoutingLab_.disable(); } // Muting the old/new combined backend callback during an intermediate @@ -1344,6 +1346,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String startUnpatchedProductionSession() { setOutputMuted(true); secondaryOutput_.disarm(); // never carry LIVE STREAM into a new unpatched graph + if(qualifiedSecondaryInstalled_.load(std::memory_order_acquire) || + qualifiedCaptureNeedsRemap_.load(std::memory_order_acquire)) + retireQualifiedCaptureForNewGraph(); // never carry A+B into A-only PCM if(hasRetainedUnboundMixer()) return "Mixer session preserved, but device changed: full ChannelId graph and plugin-state rebind required (output stays muted)"; auto* device=deviceManager_.getCurrentAudioDevice(); From 97ab1b570529c8036e5661cc51507679753db634 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 04:54:11 +0700 Subject: [PATCH 39/57] fix(io2d): explicit muted session replacement may retire A+B map; WIRE and FX retain it --- engine/core/DynamicNativeSessionPublisher.h | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index 4f1552d15..c1d0a3e6b 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -55,6 +55,12 @@ class DynamicNativeSessionPublisher final { none, staleDevice, staleRevision, outputArmed, invalidGraph, retirementFull, invalidCandidate }; + // Explicit CONTROL transition: a persisted primary-only .smix may + // replace a qualified A+B graph. Ordinary WIRE/FX edits MUST inherit + // the prior qualified map; absence of an argument never drops it. + enum class QualifiedMapChange : std::uint8_t { + inherit, replaceWithPrimaryOnly + }; struct CommitResult final { Fault fault=Fault::none; DynamicGraphError graphError{}; @@ -77,7 +83,8 @@ class DynamicNativeSessionPublisher final { bool allOutputsDisarmed, FxPlan fx={nullptr,nullptr,nullptr,0,0,nullptr},bool verifiedInternalWireOnly=false, bool verifiedInternalFxOnly=false, - const armix::device::MultiDeviceInputPlan* qualifiedInputMap=nullptr) { + const armix::device::MultiDeviceInputPlan* qualifiedInputMap=nullptr, + QualifiedMapChange mapChange=QualifiedMapChange::inherit) { CommitResult report;report.revision=publisher_.lastRevision(); if(!fx.valid() || (fx.owner && (fx.deviceEpoch!=proposedDeviceEpoch || @@ -113,7 +120,14 @@ class DynamicNativeSessionPublisher final { if(qualifiedInputMap&&!allOutputsDisarmed) { report.fault=Fault::outputArmed;return report; } - const auto* acceptedInputMap=qualifiedInputMap?qualifiedInputMap: + const bool replacing=mapChange==QualifiedMapChange::replaceWithPrimaryOnly; + if(replacing && (!allOutputsDisarmed || qualifiedInputMap || + verifiedInternalWireOnly || verifiedInternalFxOnly || + !prior || !prior->inputMap)) { + report.fault=Fault::invalidCandidate;return report; + } + const auto* acceptedInputMap=replacing?nullptr: + qualifiedInputMap?qualifiedInputMap: (prior&&prior->inputMap?prior->inputMap.get():nullptr); // CONTROL: validate every physical source against ONE actual // device-qualified map before starting a potentially costly graph From f93c0fe690f3732d52c64263a70eeab2d621b099 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 04:54:31 +0700 Subject: [PATCH 40/57] fix(io2d): distinguish explicit persisted A-only restore from WIRE/FX qualified-map inheritance --- src/LiveDryRoutingLab.h | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index cfec62597..df8213ba8 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2686,6 +2686,12 @@ class LiveDryRoutingLab final { return true; } + // CONTROL readback of the same PCM/FX snapshot. Session replacement + // must explicitly drop this qualified map before restoring A-only .smix. + bool qualifiedInputMapActive() const noexcept { + return nativePublisher_.hasQualifiedInputMap( + nativeAccepted_.deviceEpoch,nativeAccepted_.pcmRevision); + } bool rebindRetainedAsioSession(armix::session::MixerSessionDocument document, const armix::device::JuceActivePortSnapshot& pins,int deviceFrames) { const auto next=nativeGraphRevisionForRestore(); @@ -2726,7 +2732,8 @@ class LiveDryRoutingLab final { armix::session::MixerSessionDocument document, std::shared_ptr bank, const armix::device::JuceActivePortSnapshot& pins, - bool outputsDisarmed,bool replaceActive=false) { + bool outputsDisarmed,bool replaceActive=false, + bool replaceQualifiedWithPrimaryOnly=false) { using namespace armix::mixer; if(!outputsDisarmed || (!replaceActive && channelIdPhysicalPcmActive()) || !bank) return "Restore requires a muted device"; @@ -2754,7 +2761,10 @@ class LiveDryRoutingLab final { }; const auto published=nativePublisher_.commit( document.roster,document.request,previous,generation,epoch(), - true,std::move(fx)); + true,std::move(fx),false,false,nullptr, + replaceQualifiedWithPrimaryOnly? + DynamicNativeSessionPublisher::QualifiedMapChange::replaceWithPrimaryOnly: + DynamicNativeSessionPublisher::QualifiedMapChange::inherit); if(!published.ok()) return "Native ChannelId PCM rejected persisted topology: "+ juce::String(static_cast(published.fault)); From dece60128a2539d9e313d1c22ff7eebf735db26f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 04:54:57 +0700 Subject: [PATCH 41/57] fix(io2d): transactionally restore primary-only .smix without leaking old B reader or muting A on rollback --- src/LiveAudioEngine.h | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index f5197b3da..71f539071 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1864,14 +1864,33 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Graph publication is a temporary PHYSICAL silence, not a user MUTE. // Retain MAIN intent across the accepted ChannelId/FX rebind. if(monitoring)setOutputMuted(true); + // IO-2D: explicit .smix replacement is a paired PCM+device-map + // transaction. No capture driver closes until a new A-only graph + // is accepted; on failed candidate, restore the old B admission. + // A short muted control handoff prevents old qualified PCM from + // receiving raw A-only callback pointers during the swap. + const bool hadQualifiedMap=dryRoutingLab_.qualifiedInputMapActive(); + const bool oldQualifiedAdmission=qualifiedSecondaryInstalled_.load( + std::memory_order_acquire); + if(hadQualifiedMap) + qualifiedSecondaryInstalled_.store(false,std::memory_order_release); const auto applied=dryRoutingLab_.restoreNativeMixerSession( std::move(document),std::move(bank),inspected.pins, - allOutputsDisarmed(),replaceActive); + allOutputsDisarmed(),replaceActive,hadQualifiedMap); if(applied.isNotEmpty()) { + if(hadQualifiedMap) { + if(dryRoutingLab_.qualifiedInputMapActive()) + qualifiedSecondaryInstalled_.store(oldQualifiedAdmission, + std::memory_order_release); + else + retireQualifiedCaptureForNewGraph(); // publication did complete + } if(monitoring&&ep==dryRoutingLab_.epoch()&&liveOutputArmFault(false).isEmpty()) - setOutputMuted(false); // same user intent; safe original graph + setOutputMuted(false); // only restore verified original intent return applied; } + if(hadQualifiedMap) + retireQualifiedCaptureForNewGraph(); // A-only PCM accepted, B retired acceptedWasapiBinding_=std::move(profile); acceptedMixerBinding_=std::move(inspected.live); setMasterGainLinear(gain); From c8b42aaa0908da963414f10beacdcf7a05351ed3 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 04:55:34 +0700 Subject: [PATCH 42/57] test(io2d): explicit muted A-only .smix restore drops B map; failures retain old graph --- .../QualifiedSecondaryCaptureReaderCases.h | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/tests/io2/QualifiedSecondaryCaptureReaderCases.h b/tests/io2/QualifiedSecondaryCaptureReaderCases.h index 203ec2789..6ec7c8d1a 100644 --- a/tests/io2/QualifiedSecondaryCaptureReaderCases.h +++ b/tests/io2/QualifiedSecondaryCaptureReaderCases.h @@ -193,6 +193,37 @@ inline void run() { "stale ASRC cannot be relabeled into newly leased device"); reader.stop(); clock.stop(); - std::puts("IO2_CLOCKED_NATIVE_PASS: 44.1k B -> ASRC -> 48k A qualified ChannelId PCM MAIN; loss isolated"); + // IO-2D persistence recovery: a saved primary-only .smix can replace + // A+B only by an explicit, muted native session transaction. WIRE/FX + // omission of a map still inherits B and must never silently alias pins. + using MapChange=m::DynamicNativeSessionPublisher::QualifiedMapChange; + check(native.hasQualifiedInputMap(epoch,2), + "prior A+B PCM map installed before restore"); + const auto unsafeRestore=native.commit( + roster,old,2,epoch,epoch,false,{},false,false,nullptr, + MapChange::replaceWithPrimaryOnly); + check(unsafeRestore.fault== + m::DynamicNativeSessionPublisher::Fault::outputArmed && + native.hasQualifiedInputMap(epoch,2), + "unmuted primary-only .smix replacement cannot remove B map"); + const auto restored=native.commit( + roster,old,2,epoch,epoch,true,{},false,false,nullptr, + MapChange::replaceWithPrimaryOnly); + check(restored.ok()&&restored.revision==3 && + !native.hasQualifiedInputMap(epoch,3), + "muted explicit A-only .smix publishes one new PCM without B map"); + check(native.render(epoch,aInput,1,left.data(),right.data(), + frames,false,fx,nullptr,nullptr,{},{},{},nullptr,0), + "restored A-only PCM accepts raw primary callback again"); + check(near(left[frames-1],.2f*monoCenter,0.005f)&& + near(right[frames-1],.2f*monoCenter,0.005f), + "restored primary-only .smix never aliases or sums B PCM"); + const auto doubleRemove=native.commit( + roster,old,3,epoch,epoch,true,{},false,false,nullptr, + MapChange::replaceWithPrimaryOnly); + check(doubleRemove.fault== + m::DynamicNativeSessionPublisher::Fault::invalidCandidate, + "a nonqualified A-only session cannot spoof a B map retirement"); + std::puts("IO2_CLOCKED_NATIVE_PASS: 44.1k B -> ASRC -> 48k A qualified ChannelId PCM MAIN; loss isolated; exact A-only restore"); } } // namespace armix::io2_clocked_test From e28ed10078dff9fcd44861a1f0f79348f54e8258 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 07:23:16 +0700 Subject: [PATCH 43/57] fix(io2d): atomic qualified-source removal for SOURCE NONE and Delete Track Stage immutable source-subset map preserving independently attested A/B device leases and callback ordinals; publish together with graph and VST3 FX on CONTROL. Reject unqualified ordinal retargeting under B, retain WIRE/FX map inheritance, and add negative native PCM fixture. --- engine/core/DynamicNativeSessionPublisher.h | 9 +++++++ engine/device/MultiDeviceInputPlan.h | 19 +++++++++++++ src/LiveDryRoutingLab.h | 18 +++++++++++-- .../QualifiedSecondaryCaptureReaderCases.h | 27 +++++++++++++++++++ 4 files changed, 71 insertions(+), 2 deletions(-) diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index c1d0a3e6b..28392a13f 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -509,6 +509,15 @@ class DynamicNativeSessionPublisher final { const auto* p=publisher_.controlPrepared(epoch,revision); return p && static_cast(p->inputMap); } + // CONTROL-only explicit source disconnection; never mutate the + // callback-visible prior map. WIRE/FX revisions keep inheriting it. + bool qualifiedMapWithoutSource(std::uint64_t epoch, + std::uint64_t revision,ChannelId source, + armix::device::MultiDeviceInputPlan& candidate) const { + const auto* p=publisher_.controlPrepared(epoch,revision); + return p && p->inputMap && + p->inputMap->withoutSource(source,candidate); + } void unpublish() noexcept {publisher_.unpublish();} void pollRetirement() noexcept {publisher_.pollRetirement();} std::uint64_t acceptedRevision() const noexcept { diff --git a/engine/device/MultiDeviceInputPlan.h b/engine/device/MultiDeviceInputPlan.h index 83ce02a20..1ea632b9c 100644 --- a/engine/device/MultiDeviceInputPlan.h +++ b/engine/device/MultiDeviceInputPlan.h @@ -287,6 +287,25 @@ class MultiDeviceInputPlan final { const PreparedChannelSource& source(int index) const noexcept { return assignments_[index]; } + // IO-2D: explicit SOURCE NONE / Delete Track staging. Keep *every* + // verified device generation, lease and virtual slot unchanged; remove + // only one ChannelId's PCM assignment in a DETACHED CONTROL candidate. + // The entire graph+map publishes as one immutable snapshot on success. + bool withoutSource(armix::mixer::ChannelId removed, + MultiDeviceInputPlan& destination) const { + if(!primaryEpoch_ || !removed.value)return false; + MultiDeviceInputPlan staged=*this; + int write=0; + bool found=false; + for(int i=0;i(ctx)->latencySamples(id); }; fx.deviceEpoch=expectedEpoch;fx.graphRevision=expectedPcmRevision+1; + armix::device::MultiDeviceInputPlan reducedMap; + const bool removingQualified=disconnect && + nativePublisher_.qualifiedMapWithoutSource( + expectedEpoch,expectedPcmRevision,channel,reducedMap); if(beforePublish)beforePublish(); // late PCM publication gate const auto published=nativePublisher_.commit( nativeAccepted_.graph.roster,request,expectedPcmRevision, - expectedEpoch,epoch(),true,std::move(fx)); + expectedEpoch,epoch(),true,std::move(fx), + false,false,removingQualified?&reducedMap:nullptr); if(!published.ok()) { reply.error="NATIVE_INPUT_PCM_COMMIT_REJECTED";return reply; } diff --git a/tests/io2/QualifiedSecondaryCaptureReaderCases.h b/tests/io2/QualifiedSecondaryCaptureReaderCases.h index 6ec7c8d1a..720da4929 100644 --- a/tests/io2/QualifiedSecondaryCaptureReaderCases.h +++ b/tests/io2/QualifiedSecondaryCaptureReaderCases.h @@ -66,6 +66,16 @@ inline void run() { d::MultiDeviceInputFault err; check(d::MultiDeviceInputPlan::prepare(epoch,devices,bindings, roster.channels(),plan,err),"two physical namespaces qualified"); + // SOURCE NONE and Delete Track must remove only the named ChannelId + // binding while preserving A/B device slots, generation and lease. + d::MultiDeviceInputPlan reduced; + check(plan.withoutSource(b,reduced) && reduced.sourceCount()==1 && + plan.sourceCount()==2 && reduced.virtualInputCount()==plan.virtualInputCount() && + reduced.device(1).deviceLease==plan.device(1).deviceLease && + reduced.source(0).channel==a, + "detached qualified source removal never drops B's device lease"); + check(!plan.withoutSource(main,reduced), + "deleting an unbound MAIN cannot mutate the qualified input map"); m::DynamicGraphRequest old;old.physicalInputs=1;old.maxFrames=frames; old.sources={{a,0,-1,false}}; m::DynamicGraphRequest request; @@ -80,6 +90,23 @@ inline void run() { check(!native.hasQualifiedInputMap(epoch+1,1)&& !native.hasQualifiedInputMap(epoch,0), "stale graph generation cannot authorize persistence"); + // A plain SOURCE NONE/Delete Track request is rejected if the old map + // remains unchanged. An explicit DETACHED subset is accepted atomically + // and stays qualified for the remaining A source. + auto subsetRequest=request; + std::erase_if(subsetRequest.sources,[b](const auto& row){return row.id==b;}); + m::DynamicNativeSessionPublisher subsetPcm; + check(subsetPcm.commit(roster,request,0,epoch,epoch,true, + {},false,false,&plan).ok(),"subset fixture starts with A+B map"); + check(subsetPcm.commit(roster,subsetRequest,1,epoch,epoch,true).fault== + m::DynamicNativeSessionPublisher::Fault::invalidCandidate && + subsetPcm.acceptedRevision()==1, + "implicit SOURCE NONE must not silently desynchronize old B map"); + check(subsetPcm.commit(roster,subsetRequest,1,epoch,epoch,true, + {},false,false,&reduced).ok() && + subsetPcm.hasQualifiedInputMap(epoch,2), + "explicit source subset publishes and retains exact device leases"); + d::SecondaryCaptureClockStream clock; const d::SecondaryCaptureClockStream::Format format{ From c90a10a16396b7d9bdfed4cc65f02afb1672a69d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 07:26:06 +0700 Subject: [PATCH 44/57] fix(io2d): non-destructive ASIO A restart retaining A+B mixer, WIRE and FX Stage a detached A-only primary-clock graph from the previous device-qualified map, preserving all ChannelId/WIRE/FX roster state and dropping only stale B source PCM on genuine verified same-driver restart. Never reinterpret virtual B pins as A. Retire B producer only after successful A publication, keep NEEDS_REMAP for explicit B reauthorization, preserve old graph on failed candidate. Extend real native recovery regressions. --- engine/core/DynamicNativeSessionPublisher.h | 13 ++++ .../QualifiedPrimaryRestartRecoveryPlan.h | 66 +++++++++++++++++++ src/LiveAudioEngine.h | 40 +++++++---- src/LiveDryRoutingLab.h | 13 ++++ .../QualifiedSecondaryCaptureReaderCases.h | 22 +++++++ 5 files changed, 141 insertions(+), 13 deletions(-) create mode 100644 engine/device/QualifiedPrimaryRestartRecoveryPlan.h diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index 28392a13f..2122adfcd 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -2,6 +2,7 @@ #pragma once #include "DynamicPreparedMixerBlock.h" #include "../device/MultiDeviceInputPlan.h" +#include "../device/QualifiedPrimaryRestartRecoveryPlan.h" #include "DynamicConsoleRoutingView.h" #include "NativeMusicTempoMonitor.h" #include "NativeBeatFrameContext.h" @@ -509,6 +510,18 @@ class DynamicNativeSessionPublisher final { const auto* p=publisher_.controlPrepared(epoch,revision); return p && static_cast(p->inputMap); } + // CONTROL-only primary restart: stage A-only physical sources from + // the PREVIOUS accepted A+B lease. Never reinterpret B virtual slots as + // callback indices and never destroy the original graph on failure. + bool preparePrimaryRestartFallback(std::uint64_t priorEpoch, + std::uint64_t priorRevision,int verifiedPrimaryInputs, + const DynamicGraphRequest& accepted, + DynamicGraphRequest& destination) const { + const auto* p=publisher_.controlPrepared(priorEpoch,priorRevision); + return p && p->inputMap && + armix::device::QualifiedPrimaryRestartRecoveryPlan::stage( + *p->inputMap,accepted,verifiedPrimaryInputs,destination); + } // CONTROL-only explicit source disconnection; never mutate the // callback-visible prior map. WIRE/FX revisions keep inheriting it. bool qualifiedMapWithoutSource(std::uint64_t epoch, diff --git a/engine/device/QualifiedPrimaryRestartRecoveryPlan.h b/engine/device/QualifiedPrimaryRestartRecoveryPlan.h new file mode 100644 index 000000000..c7dec428f --- /dev/null +++ b/engine/device/QualifiedPrimaryRestartRecoveryPlan.h @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +#include "MultiDeviceInputPlan.h" +#include "../core/DynamicPreparedMixerBlock.h" +#include +#include + +// IO-2D CONTROL-only, non-destructive restart fallback. Keep the entire +// ChannelId/WIRE/VST3 graph, but remove B's old physical source assignments +// from a DETACHED request after the primary ASIO clock changes. Never render +// or authorize an ordinal from the previous secondary device lease. +namespace armix::device { +class QualifiedPrimaryRestartRecoveryPlan final { +public: + static bool stage(const MultiDeviceInputPlan& prior, + const armix::mixer::DynamicGraphRequest& accepted, + int verifiedPrimaryInputs, + armix::mixer::DynamicGraphRequest& destination) { + using namespace armix::mixer; + if(prior.primaryEpoch()==0 || prior.deviceCount()!=2 || + !prior.device(0).primary || prior.device(0).firstVirtual!=0 || + prior.device(0).activePins<=0 || + verifiedPrimaryInputs!=prior.device(0).activePins || + prior.virtualInputCount()!=accepted.physicalInputs || + prior.virtualInputCount()<=verifiedPrimaryInputs) + return false; + int sourceCount=0; + for(const auto& source:accepted.sources) { + if(source.kind!=DynamicSourceKind::physical)continue; + ++sourceCount; + bool matched=false; + for(int i=0;i=prior.virtualInputCount() || + (source.stereo && + (source.inputR<0 || + source.inputR>=prior.virtualInputCount()))) + return false; + const auto device=prior.slot(source.inputL).device; + if((device==0 && source.inputL>=verifiedPrimaryInputs) || + (device!=0 && source.inputL #include @@ -82,6 +83,27 @@ inline void run() { d::QualifiedInputGraphBridge::Fault bridgeError{}; check(d::QualifiedInputGraphBridge::stage(plan,old,request,bridgeError), "control maps both verified sources into same graph"); + m::DynamicGraphRequest primaryFallback; + check(d::QualifiedPrimaryRestartRecoveryPlan::stage( + plan,request,1,primaryFallback) && + primaryFallback.physicalInputs==1 && + primaryFallback.sources.size()==1 && + primaryFallback.sources.front().id==a && + primaryFallback.sources.front().inputL==0 && + request.physicalInputs==3 && request.sources.size()==2, + "ASIO restart leaves B ChannelId/FX/WIRE roster and silences only B source"); + check(!d::QualifiedPrimaryRestartRecoveryPlan::stage( + plan,request,2,primaryFallback), + "different A input mask is never accepted by stale B virtual slot map"); + auto swapped=request; + swapped.sources.back().inputL=0; + check(!d::QualifiedPrimaryRestartRecoveryPlan::stage( + plan,swapped,1,primaryFallback), + "wrong-device B ordinal cannot relabel existing A source during restart"); + m::DynamicNativeSessionPublisher recoveredPcm; + check(recoveredPcm.commit(roster,primaryFallback,0,epoch+1,epoch+1,true).ok() && + !recoveredPcm.hasQualifiedInputMap(epoch+1,1), + "a new primary epoch publishes only verified A PCM but keeps original roster"); m::DynamicNativeSessionPublisher native; check(native.commit(roster,request,0,epoch,epoch,true, {},false,false,&plan).ok(),"one PCM and device map publication"); From e2d1df477f35a9e453278c5adcb1797167f2e10f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 07:33:20 +0700 Subject: [PATCH 45/57] fix(io2d): sustain second primary restart and admit hardware callback chunking Treat B remap as a reminder separate from presence of a qualified input map, so another A restart after A-only fallback retains the graph. Admit genuine hardware periods larger than the VST3 scratch/ASRC reader chunk budget (e.g. 512-period to 256-chunk) without weakening generation, lease or buffer hard limits. Add portable two-restart and chunk tests. --- engine/device/QualifiedCaptureAdmission.h | 8 +++++++- src/LiveAudioEngine.h | 6 +++++- tests/io2/QualifiedSecondaryCaptureReaderCases.h | 7 +++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/engine/device/QualifiedCaptureAdmission.h b/engine/device/QualifiedCaptureAdmission.h index eee02635c..19189309a 100644 --- a/engine/device/QualifiedCaptureAdmission.h +++ b/engine/device/QualifiedCaptureAdmission.h @@ -37,11 +37,17 @@ class QualifiedCaptureAdmission final { return Fault::unsafeFrames; if(!clock.ready())return Fault::secondaryNotReady; const auto& format=clock.format(); // CONTROL only; not in RT + // The ASIO callback period is a HARDWARE value. The native graph + // legitimately renders in smaller bounded chunks when the period + // exceeds the retained VST scratch quantum. Reader::prepare() and + // withBlocks() are constrained by maximumRenderFrames, not by the + // whole hardware callback size. Never reject a valid 512->256 split. if(format.captureGeneration!=plan.device(1).generation|| format.deviceLease!=plan.device(1).deviceLease|| format.primaryEpoch!=primaryEpoch|| format.channels!=plan.device(1).activePins|| - format.primaryPeriod<1||format.primaryPeriod>maximumRenderFrames) + format.primaryPeriod<1|| + format.primaryPeriod>MultiDeviceInputPlan::maxCallbackFrames) return Fault::wrongCaptureLease; return Fault::none; } diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index c2f976dbd..a6042ad28 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -587,8 +587,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback constexpr auto mode=Policy::Mode::verifiedAsioRestart; if(inspectNativeMixerSessionBinding(document,inspected,mode).isNotEmpty() || inspected.live.rate!=document.binding.rate)return false; + // The B reconnection reminder may survive an already recovered + // primary-only graph. A second ASIO A restart must NOT demand an + // A+B map that was intentionally retired after the first recovery. const bool lostB=qualifiedCaptureNeedsRemap_.load( - std::memory_order_acquire); + std::memory_order_acquire) && + dryRoutingLab_.qualifiedInputMapActive(); // Rebuild from the last genuine A+B snapshot without saving a // corrupt virtual-input .smix. The exact prior A port count is // checked against current verified hardware before any mutation. diff --git a/tests/io2/QualifiedSecondaryCaptureReaderCases.h b/tests/io2/QualifiedSecondaryCaptureReaderCases.h index ccb3bf2df..53bc88b02 100644 --- a/tests/io2/QualifiedSecondaryCaptureReaderCases.h +++ b/tests/io2/QualifiedSecondaryCaptureReaderCases.h @@ -104,6 +104,9 @@ inline void run() { check(recoveredPcm.commit(roster,primaryFallback,0,epoch+1,epoch+1,true).ok() && !recoveredPcm.hasQualifiedInputMap(epoch+1,1), "a new primary epoch publishes only verified A PCM but keeps original roster"); + check(recoveredPcm.commit(roster,primaryFallback,1,epoch+2,epoch+2,true).ok() && + !recoveredPcm.hasQualifiedInputMap(epoch+2,2), + "second A restart rebinds the recovered A-only graph without stale B map"); m::DynamicNativeSessionPublisher native; check(native.commit(roster,request,0,epoch,epoch,true, {},false,false,&plan).ok(),"one PCM and device map publication"); @@ -137,6 +140,10 @@ inline void run() { using Admission=d::QualifiedCaptureAdmission; check(Admission::verify(plan,clock,epoch,1,frames)==Admission::Fault::none, "exact two-device qualified CONTROL admission"); + check(Admission::verify(plan,clock,epoch,1,frames/2)==Admission::Fault::none, + "hardware ASIO period may exceed retained renderer chunk quantum"); + check(Admission::verify(plan,clock,epoch,1,8193)==Admission::Fault::unsafeFrames, + "reader scratch cannot exceed absolute callback hard frame limit"); check(Admission::verify(plan,clock,epoch+1,1,frames)== Admission::Fault::stalePrimary, "stale A output epoch cannot publish qualified PCM"); From ec0a71dc5013c08fb601fdd17e97e483ce0cd8be Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 09:48:18 +0700 Subject: [PATCH 46/57] fix(io2): expose revision-guarded retained device epoch only to native CONTROL --- engine/core/RealtimeRoutePublisher.h | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/engine/core/RealtimeRoutePublisher.h b/engine/core/RealtimeRoutePublisher.h index 1e72f59c3..2ce842ce2 100644 --- a/engine/core/RealtimeRoutePublisher.h +++ b/engine/core/RealtimeRoutePublisher.h @@ -160,6 +160,15 @@ class RealtimeRoutePublisher final { owned_->graphRevision==expectedRevision ?owned_->prepared.get():nullptr; } + // CONTROL only. Cross-epoch recovery may need to inspect the LAST + // accepted qualified lease for explicit transaction retirement. Do not + // expose the old epoch as a valid RT producer: ReadLease::get() remains + // exact-epoch guarded, and no stale graph may render after device START. + std::uint64_t controlOwnedEpoch(std::uint64_t revision) const noexcept { + return owned_ && owned_->prepared && revision_==revision && + owned_->graphRevision==revision + ? owned_->deviceEpoch:0; + } [[nodiscard]] ReadLease acquire(bool skip=false) noexcept {return ReadLease(*this,skip);} std::uint64_t lastRevision() const noexcept {return revision_;} // CONTROL std::size_t pendingRetirements() const noexcept {return retiredCount_;} // CONTROL From 93af723ae086576c913cb73d67be05a0eea59493 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 09:49:02 +0700 Subject: [PATCH 47/57] fix(io2): retire retained B input lease explicitly when restoring A-only across epochs --- engine/core/DynamicNativeSessionPublisher.h | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index 2122adfcd..91cddac21 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -118,13 +118,25 @@ class DynamicNativeSessionPublisher final { // MAIN/MONITOR/output disarm, not a hidden in-place WIRE edit. const auto* prior=publisher_.controlPrepared( proposedDeviceEpoch,expectedRevision); + // Old A+B input maps are still CONTROL-owned after a primary epoch + // change, but cannot render in that new epoch. Only explicit A-only + // session replacement may retire that previous qualified lease. + const auto ownedEpoch=publisher_.controlOwnedEpoch(expectedRevision); + const auto* retained=ownedEpoch? + publisher_.controlPrepared(ownedEpoch,expectedRevision):nullptr; if(qualifiedInputMap&&!allOutputsDisarmed) { report.fault=Fault::outputArmed;return report; } const bool replacing=mapChange==QualifiedMapChange::replaceWithPrimaryOnly; if(replacing && (!allOutputsDisarmed || qualifiedInputMap || verifiedInternalWireOnly || verifiedInternalFxOnly || - !prior || !prior->inputMap)) { + !retained || !retained->inputMap)) { + report.fault=Fault::invalidCandidate;return report; + } + // A cross-epoch commit missing the explicit retirement marker must + // NOT discard B's map and reinterpret its virtual pins as A inputs. + if(!replacing && retained && retained->inputMap && !prior && + !qualifiedInputMap) { report.fault=Fault::invalidCandidate;return report; } const auto* acceptedInputMap=replacing?nullptr: From 5cb7bc770a67fb96f6531613ed4709eec2488fa4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 09:50:07 +0700 Subject: [PATCH 48/57] test(io2): accepted A+B across primary ASIO epoch is replaced only by explicit disarmed A-only restore --- tests/live_channel_fx_graph_test.cpp | 75 ++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/tests/live_channel_fx_graph_test.cpp b/tests/live_channel_fx_graph_test.cpp index 7437310bb..09ace49a2 100644 --- a/tests/live_channel_fx_graph_test.cpp +++ b/tests/live_channel_fx_graph_test.cpp @@ -1831,6 +1831,80 @@ static void verifyNativePuzzleV8FixtureAndWire() { .getProperty("rawPeak",0.))==.25); } +// IO-2E: old qualified A+B lease belongs to epoch 91, while the actual +// verified primary callback has restarted into epoch 92. It may be retired +// only by an explicit, disarmed primary-only session replacement. No silent +// fallthrough from B virtual ordinals to A callback pins is ever permitted. +static void verifyQualifiedMapCrossEpochReplacement() { + namespace io=armix::device; + DynamicChannelRoster roster; + std::vector additions; + for(int i=0;i<3;++i) { + ChannelEdit add;add.kind=ChannelEdit::Kind::add;add.position=i; + add.role=i==2?ChannelRole::main:ChannelRole::input; + add.format=i==1?ProcessingFormat::stereo:ProcessingFormat::mono; + if(i==2)add.format=ProcessingFormat::stereo; + add.text=i==0?"A VOICE":i==1?"B STEREO":"MAIN"; + additions.push_back(add); + } + const auto created=roster.edit(0,additions); + assert(created.ok()&&created.createdIds.size()==3); + const auto sourceA=created.createdIds[0], + sourceB=created.createdIds[1]; + const std::array aPins{0,2},bPins{0,7}; + const std::array devices{{ + {"ASIO/verified-A",91,true,aPins,1001}, + {"ASIO/verified-B",91,false,bPins,2002} + }}; + const std::array mappings{{ + {sourceA,{"ASIO/verified-A",2},{},false}, + {sourceB,{"ASIO/verified-B",0},{"ASIO/verified-B",7},true} + }}; + io::MultiDeviceInputPlan plan; + io::MultiDeviceInputFault err; + assert(io::MultiDeviceInputPlan::prepare(91,devices,mappings, + roster.channels(),plan,err)); + assert(plan.virtualInputCount()==4); + DynamicGraphRequest qualified; + qualified.physicalInputs=4;qualified.maxFrames=64; + qualified.sources={{sourceA,1,-1,false},{sourceB,2,3,true}}; + DynamicNativeSessionPublisher owner; + assert(owner.commit(roster,qualified,0,91,91,true, + {},false,false,&plan).ok()); + assert(owner.acceptedRevision()==1); + assert(owner.hasQualifiedInputMap(91,1)); + + // A compatible persisted A-only .smix has real A callback ordinals, + // not inherited old A+B virtual ordinals. + DynamicGraphRequest primaryOnly; + primaryOnly.physicalInputs=2;primaryOnly.maxFrames=64; + primaryOnly.sources={{sourceA,1,-1,false}}; + using Change=DynamicNativeSessionPublisher::QualifiedMapChange; + using Fault=DynamicNativeSessionPublisher::Fault; + // Without an explicit map-replacement transaction, old B still owns a + // qualified map at epoch 91. Reject rather than guess about ASIO pins. + assert(owner.commit(roster,primaryOnly,1,92,92,true).fault== + Fault::invalidCandidate); + assert(owner.commit(roster,primaryOnly,1,92,93,true, + {},false,false,nullptr,Change::replaceWithPrimaryOnly).fault== + Fault::staleDevice); + assert(owner.commit(roster,primaryOnly,1,92,92,false, + {},false,false,nullptr,Change::replaceWithPrimaryOnly).fault== + Fault::outputArmed); + assert(owner.acceptedRevision()==1); + assert(owner.hasQualifiedInputMap(91,1)); + assert(owner.commit(roster,primaryOnly,1,92,92,true, + {},false,false,nullptr,Change::replaceWithPrimaryOnly).ok()); + assert(owner.acceptedRevision()==2); + assert(!owner.hasQualifiedInputMap(92,2)); + assert(!owner.hasQualifiedInputMap(91,1)); + // A second unsolicited map retirement is never admissible. + assert(owner.commit(roster,primaryOnly,2,92,92,true, + {},false,false,nullptr,Change::replaceWithPrimaryOnly).fault== + Fault::invalidCandidate); + assert(owner.acceptedRevision()==2); +} + // E2: native JUCE VST3 stays audible through a serial GROUP edit; a missing // successor FX owner rejects atomically rather than deleting hosted processing. static void verifyChannelIdGroupPreservesHostedFx() { @@ -2603,6 +2677,7 @@ int main(int argc,char** argv) { verifyNativeConsoleWireRejectsUnsupportedM4AndPreservesEpoch(); verifyFirstSoundOnePinNativeSourceDraft(); verifyNativePuzzleV8FixtureAndWire(); + verifyQualifiedMapCrossEpochReplacement(); verifyChannelIdGroupPreservesHostedFx(); verifyLatencyAlignedBypass(); verifyNativeFxRackTransactions(); From 3407c217edfee42499924c0d19250595d8c69420 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 11:06:38 +0700 Subject: [PATCH 49/57] fix(io2f): carry explicit qualified B map retirement through verified ASIO restart rebind --- src/LiveDryRoutingLab.h | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 535d534be..fe4184cee 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2719,8 +2719,13 @@ class LiveDryRoutingLab final { document.request=std::move(staged); return true; } + // IO-2F: primary-ASIO restart must carry the same explicit qualified + // map-retirement token as a verified user-requested A-only .smix restore. + // Only the owner that staged an A+B -> A-only recovery may supply true; + // an ordinary ASIO restart must not drop a still-installed B source map. bool rebindRetainedAsioSession(armix::session::MixerSessionDocument document, - const armix::device::JuceActivePortSnapshot& pins,int deviceFrames) { + const armix::device::JuceActivePortSnapshot& pins,int deviceFrames, + bool retireLostSecondaryMap) { const auto next=nativeGraphRevisionForRestore(); const auto previous=document.request.maxFrames; // Existing processors can still use their prepared quantum. Larger @@ -2732,7 +2737,11 @@ class LiveDryRoutingLab final { if(armix::mixer::DynamicChannelFxLeaseBank::rebindSameFormat( pins.epoch,next,*nativeAccepted_.fxOwners,*bank)!= armix::mixer::DynamicChannelFxLeaseBank::Fault::none)return false; - return restoreNativeMixerSession(std::move(document),std::move(bank),pins,true).isEmpty(); + if(retireLostSecondaryMap && !qualifiedInputMapActive())return false; + // The new A callback and its real pin mask were already verified. + // Never publish an implicit cross-epoch B ordinal reinterpretation. + return restoreNativeMixerSession(std::move(document),std::move(bank), + pins,true,false,retireLostSecondaryMap).isEmpty(); } // Match CONTROL's live device readback to the masks registered for the From 5f67c37a5a80f8f4b1640316ffd2a9db92203418 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 11:06:51 +0700 Subject: [PATCH 50/57] fix(io2f): propagate staged lost-B restart recovery intent to native graph publication --- src/LiveAudioEngine.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index a6042ad28..50346f7b1 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -601,7 +601,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if(Policy::apply(document,inspected.live,inspected.outputs, inspected.callbackInputs,mode).isNotEmpty() || !dryRoutingLab_.rebindRetainedAsioSession(std::move(document), - inspected.pins,inspected.live.frames))return false; + inspected.pins,inspected.live.frames,lostB))return false; if(lostB) { retireQualifiedCaptureForNewGraph(); // only AFTER A graph published qualifiedCaptureNeedsRemap_.store(true,std::memory_order_release); From 5e9f25a0c1a2bb7151ff7e41fdf39081fbc225f2 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 11:07:27 +0700 Subject: [PATCH 51/57] test(io2f): reproduce P1 retained A+B restart and verify explicit retirement plus second restart --- .../QualifiedSecondaryCaptureReaderCases.h | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/tests/io2/QualifiedSecondaryCaptureReaderCases.h b/tests/io2/QualifiedSecondaryCaptureReaderCases.h index 53bc88b02..475ca1298 100644 --- a/tests/io2/QualifiedSecondaryCaptureReaderCases.h +++ b/tests/io2/QualifiedSecondaryCaptureReaderCases.h @@ -107,6 +107,51 @@ inline void run() { check(recoveredPcm.commit(roster,primaryFallback,1,epoch+2,epoch+2,true).ok() && !recoveredPcm.hasQualifiedInputMap(epoch+2,2), "second A restart rebinds the recovered A-only graph without stale B map"); + // IO-2F caller-path regression: the REAL retained owner has an A+B + // input map on the previous epoch. Merely staging the safe A-only + // document is insufficient; ASIO restart must explicitly pass the map + // retirement token all the way through restoreNativeMixerSession(). + // The preceding A-only fixture never had B installed and missed P1. + m::DynamicNativeSessionPublisher restarted; + using Change=m::DynamicNativeSessionPublisher::QualifiedMapChange; + using Fault=m::DynamicNativeSessionPublisher::Fault; + check(restarted.commit(roster,request,0,epoch,epoch,true, + {},false,false,&plan).ok() && + restarted.hasQualifiedInputMap(epoch,1), + "actual A+B PCM installed before driver restart"); + check(restarted.commit(roster,primaryFallback,1,epoch+1,epoch+1,true).fault== + Fault::invalidCandidate && + restarted.acceptedRevision()==1 && + restarted.hasQualifiedInputMap(epoch,1), + "P1 regression reproduction: restart without explicit retirement fails closed"); + check(restarted.commit(roster,primaryFallback,1,epoch+1,epoch+2,true, + {},false,false,nullptr,Change::replaceWithPrimaryOnly).fault== + Fault::staleDevice && + restarted.hasQualifiedInputMap(epoch,1), + "mismatched live A epoch must preserve old B lease on rejected recovery"); + check(restarted.commit(roster,primaryFallback,1,epoch+1,epoch+1,false, + {},false,false,nullptr,Change::replaceWithPrimaryOnly).fault== + Fault::outputArmed && + restarted.hasQualifiedInputMap(epoch,1), + "ARM cannot pass the explicit map retirement boundary"); + check(restarted.commit(roster,primaryFallback,1,epoch+1,epoch+1,true, + {},false,false,nullptr,Change::replaceWithPrimaryOnly).ok() && + restarted.acceptedRevision()==2 && + !restarted.hasQualifiedInputMap(epoch+1,2) && + !restarted.hasQualifiedInputMap(epoch,1), + "verified A-only restart atomically retires old B map"); + const auto* retainedRouting=restarted.acceptedRouting(epoch+1,2); + check(retainedRouting && retainedRouting->find(a) && + retainedRouting->find(b) && retainedRouting->find(main), + "A, silent B, MAIN ChannelId roster survives ASIO restart"); + check(restarted.commit(roster,primaryFallback,2,epoch+2,epoch+2,true, + {},false,false,nullptr,Change::replaceWithPrimaryOnly).fault== + Fault::invalidCandidate, + "second restart must not retire nonexistent B mapping again"); + check(restarted.commit(roster,primaryFallback,2,epoch+2,epoch+2,true).ok() && + !restarted.hasQualifiedInputMap(epoch+2,3) && + restarted.acceptedRouting(epoch+2,3)->find(b), + "second ASIO restart keeps original B track silent but session usable"); m::DynamicNativeSessionPublisher native; check(native.commit(roster,request,0,epoch,epoch,true, {},false,false,&plan).ok(),"one PCM and device map publication"); From 16a0c204771773360131e69fb76f379398d6cc71 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 11:10:01 +0700 Subject: [PATCH 52/57] fix(io2f): preserve existing single-ASIO rebind callers with safe default no B retirement --- src/LiveDryRoutingLab.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index fe4184cee..45d866c45 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2725,7 +2725,7 @@ class LiveDryRoutingLab final { // an ordinary ASIO restart must not drop a still-installed B source map. bool rebindRetainedAsioSession(armix::session::MixerSessionDocument document, const armix::device::JuceActivePortSnapshot& pins,int deviceFrames, - bool retireLostSecondaryMap) { + bool retireLostSecondaryMap=false) { const auto next=nativeGraphRevisionForRestore(); const auto previous=document.request.maxFrames; // Existing processors can still use their prepared quantum. Larger From bea88420d1f13b5470d16302a22aa5f9457d1990 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 11:11:55 +0700 Subject: [PATCH 53/57] test(io2f): real JUCE fixture A+B install, retained restart handoff, .smix and second restart --- tests/native_mixer_session_store_test.cpp | 92 +++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index b5007085f..6238434d7 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -145,6 +145,97 @@ class FixtureDevice final : public juce::AudioIODevice { double rate=48000.; }; +// IO-2F: execute the actual LiveDryRoutingLab restore/rebind handoff with +// a JUCE callback fixture. No physical B driver is opened: the clock bridge +// and device lease are deterministic off-RT test objects. +static void qualifiedAsioRestartHandoffRetiresB() { + namespace d=armix::device; + FixtureDevice device; + device.frames=256; + juce::AudioPluginFormatManager formats; + LiveDryRoutingLab mixer; + mixer.prepareDevice(&device); + const auto oldEpoch=mixer.epoch(); + auto base=makeSession(); + d::JuceActivePortSnapshot pins; + d::JuceActivePortSnapshot::Fault fault{}; + assert(d::JuceActivePortSnapshot::capture(&device,oldEpoch,pins,fault)); + std::shared_ptr bank; + assert(NativeMixerSessionFxRestore::prepare(base,{},formats, + device.rate,device.frames,pins.epoch, + mixer.nativeGraphRevisionForRestore(),bank).isEmpty() && bank); + assert(mixer.restoreNativeMixerSession(base,std::move(bank), + pins,true).isEmpty()); + assert(mixer.channelIdPhysicalPcmActive()); + const std::array aPins{0,1},bPins{0,7}; + constexpr std::uint64_t bGeneration=94,bLease=2002; + const std::array endpoints{{ + {"fixture-A",oldEpoch,true,aPins,1001}, + {"fixture-B",bGeneration,false,bPins,bLease} + }}; + const std::array choices{{ + {{1},{"fixture-A",0},{},false}, + {{2},{"fixture-B",0},{"fixture-B",7},true} + }}; + d::MultiDeviceInputPlan map; + d::MultiDeviceInputFault mapFault{}; + assert(mixer.prepareQualifiedCapturePlan(oldEpoch,endpoints,choices, + map,mapFault)); + d::SecondaryCaptureClockStream clock; + const d::SecondaryCaptureClockStream::Format format{ + 44100.,device.rate,256,256,2,bGeneration,oldEpoch,bLease}; + assert(clock.prepare(format)&&clock.activate()); + d::QualifiedSecondaryCaptureReader reader; + const auto before=mixer.nativeGraphRevisionForRestore()-1; + const auto install=mixer.installQualifiedSecondaryInput( + oldEpoch,before,base.roster.revision(),map,reader,clock,true); + assert(install.accepted && mixer.qualifiedInputMapActive()); + assert(mixer.nativeGraphRevisionForRestore()==before+2); + // A normal .smix v1 cannot persist these B virtual ordinals. + MixerSessionDocument unsafe; + std::vector blobs; + assert(mixer.captureNativeMixerSession(unsafe,blobs).isNotEmpty()); + mixer.deviceStopped(); + mixer.prepareDevice(&device); + auto restartEpoch=mixer.epoch(); + MixerSessionDocument recovered; + assert(mixer.describeRetainedAsioSession(recovered)); + assert(mixer.preparePrimaryOnlyAsioRestartDocument(recovered,2)); + assert(recovered.request.physicalInputs==2 && + recovered.request.sources.size()==1 && + recovered.request.sources.front().id.value==1 && + recovered.roster.find({2})!=nullptr); + d::JuceActivePortSnapshot newPins; + assert(d::JuceActivePortSnapshot::capture(&device, + restartEpoch,newPins,fault)); + // Regression reproducer: old no-marker caller rejected, preserving A+B. + assert(!mixer.rebindRetainedAsioSession(recovered,newPins,256,false)); + assert(mixer.qualifiedInputMapActive()); + // Fixed caller supplies lostB=true only after staging verified A-only PCM. + assert(mixer.rebindRetainedAsioSession( + std::move(recovered),newPins,256,true)); + assert(!mixer.qualifiedInputMapActive()); + assert(mixer.channelIdPhysicalPcmActive()); + MixerSessionDocument durable; + assert(mixer.captureNativeMixerSession(durable,blobs).isEmpty()); + assert(durable.roster.find({2})!=nullptr && + durable.request.physicalInputs==2 && + durable.request.sources.size()==1); + // Second primary restart must use the ordinary 3-argument compatibility + // path; the old B map no longer exists and must not be retired twice. + mixer.deviceStopped(); + mixer.prepareDevice(&device); + MixerSessionDocument again; + assert(mixer.describeRetainedAsioSession(again)); + assert(d::JuceActivePortSnapshot::capture(&device, + mixer.epoch(),newPins,fault)); + assert(mixer.rebindRetainedAsioSession( + std::move(again),newPins,256)); + assert(mixer.channelIdPhysicalPcmActive() && + !mixer.qualifiedInputMapActive()); + reader.stop();clock.stop(); +} + static void outputOnlyNativeStartup() { // Real output-only callback: never invent a capture pin, but a silent // ChannelId session, its FX/WIRE bus and physical zero output are valid. @@ -1470,6 +1561,7 @@ int main(){ outputOnlyNativeStartup(); warmVst3Discovery(); nativeDeviceRecovery(); + qualifiedAsioRestartHandoffRetiresB(); auto d=makeSession(); checkRecoveryPlan(d); verifyExternalOutputPortableIntent(); From 4a58da844474e1ef51cd2626b9473c07a2f618c2 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 11:22:39 +0700 Subject: [PATCH 54/57] fix(io2g P1): atomically gate reader entry and scratch reclamation under STOP/prepare race --- .../device/QualifiedSecondaryCaptureReader.h | 36 ++++++++++++++----- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/engine/device/QualifiedSecondaryCaptureReader.h b/engine/device/QualifiedSecondaryCaptureReader.h index 3a80ad6bc..ec94b01a7 100644 --- a/engine/device/QualifiedSecondaryCaptureReader.h +++ b/engine/device/QualifiedSecondaryCaptureReader.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -32,6 +33,8 @@ class QualifiedSecondaryCaptureReader final { using CaptureBlock=MultiDeviceInputPlan::CaptureBlock; static constexpr int maxSecondaryChannels=16; static constexpr int maxCallbackFrames=8192; + // One seq-cst atomic for writer admission AND bounded callback leases. + static constexpr std::uint32_t writerFlag=1U,readerUnit=2U; struct Status { bool ready=false; std::uint64_t primaryBlocks=0,secondaryAccepted=0,secondarySilent=0, @@ -80,15 +83,21 @@ class QualifiedSecondaryCaptureReader final { rejected_.store(0,std::memory_order_relaxed); overlaps_.store(0,std::memory_order_relaxed); ready_.store(true,std::memory_order_release); + // stop() keeps the writer bit held until every scratch pointer and + // physical lease is initialized, then readers may enter atomically. + activity_.fetch_and(~writerFlag,std::memory_order_seq_cst); return true; } // CONTROL ONLY, never called inside either audio callback. // Prevent reprepare/free while a borrowed scratch view is rendering. void stop() noexcept { + // Atomically close admission before examining reader count. + // A reader that won the CAS must finish; new arrivals reject. + activity_.fetch_or(writerFlag,std::memory_order_seq_cst); ready_.store(false,std::memory_order_release); - while(readers_.load(std::memory_order_acquire)!=0) - std::this_thread::yield(); + while((activity_.load(std::memory_order_seq_cst)&~writerFlag)!=0) + std::this_thread::yield(); // CONTROL only, never audio callback scratch_.reset(); write_={};read_={}; epoch_=primaryGeneration_=primaryLease_=0; @@ -107,7 +116,16 @@ class QualifiedSecondaryCaptureReader final { static_assert(std::is_nothrow_invocable_r_v>, "Render must synchronously consume blocks without throwing"); - readers_.fetch_add(1,std::memory_order_acq_rel); + // Single non-blocking compare-exchange; no audio-thread spin. + // Counter and stop/admission flag share one linearizable state. + auto activity=activity_.load(std::memory_order_seq_cst); + if((activity&writerFlag)!=0 || + activity>std::numeric_limits::max()-readerUnit || + !activity_.compare_exchange_strong(activity,activity+readerUnit, + std::memory_order_seq_cst,std::memory_order_seq_cst)) { + rejected_.fetch_add(1,std::memory_order_relaxed); + return false; + } const bool admitted=ready_.load(std::memory_order_acquire) && scratch_ && primaryEpoch==epoch_ && primaryChannels==primaryChannels_ && @@ -115,13 +133,13 @@ class QualifiedSecondaryCaptureReader final { (primaryChannels==0||primary!=nullptr); if(!admitted) { rejected_.fetch_add(1,std::memory_order_relaxed); - readers_.fetch_sub(1,std::memory_order_release); + activity_.fetch_sub(readerUnit,std::memory_order_seq_cst); return false; } armix::rt::RealtimeRenderPermit exclusive{consumer_}; if(!exclusive){ overlaps_.fetch_add(1,std::memory_order_relaxed); - readers_.fetch_sub(1,std::memory_order_release); + activity_.fetch_sub(readerUnit,std::memory_order_seq_cst); return false; } primaryBlocks_.fetch_add(1,std::memory_order_relaxed); @@ -140,12 +158,13 @@ class QualifiedSecondaryCaptureReader final { // this primary callback; it cannot hold this view after return. const bool ok=std::forward(render)( std::span(blocks.data(),blocks.size())); - readers_.fetch_sub(1,std::memory_order_release); + activity_.fetch_sub(readerUnit,std::memory_order_seq_cst); return ok; } Status status() const noexcept { - return {ready_.load(std::memory_order_acquire), + return {ready_.load(std::memory_order_acquire) && + !(activity_.load(std::memory_order_seq_cst)&writerFlag), primaryBlocks_.load(std::memory_order_relaxed), secondaryAccepted_.load(std::memory_order_relaxed), secondarySilent_.load(std::memory_order_relaxed), @@ -155,6 +174,7 @@ class QualifiedSecondaryCaptureReader final { private: // No reader can remain after stop's CONTROL quiescence barrier. + // Same gate as RealtimeRoutePublisher: writer=bit0, each reader=+2. std::unique_ptr scratch_; std::array write_{}; std::array read_{}; @@ -162,7 +182,7 @@ class QualifiedSecondaryCaptureReader final { secondaryGeneration_=0,secondaryLease_=0; int primaryChannels_=0,secondaryChannels_=0,maximumFrames_=0; std::atomic ready_{false}; - std::atomic readers_{0}; + std::atomic activity_{writerFlag}; std::atomic_flag consumer_=ATOMIC_FLAG_INIT; std::atomic primaryBlocks_{0},secondaryAccepted_{0}, secondarySilent_{0},rejected_{0},overlaps_{0}; From 74e4c80d9ac5232d3242fc872b7ae712f27acdab Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 11:23:52 +0700 Subject: [PATCH 55/57] test(io2g): P1 concurrent callback-vs-stop deterministic fence and reprepare ASan stress --- .../QualifiedSecondaryCaptureReaderCases.h | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/tests/io2/QualifiedSecondaryCaptureReaderCases.h b/tests/io2/QualifiedSecondaryCaptureReaderCases.h index 475ca1298..5fd537759 100644 --- a/tests/io2/QualifiedSecondaryCaptureReaderCases.h +++ b/tests/io2/QualifiedSecondaryCaptureReaderCases.h @@ -10,6 +10,9 @@ #include #include #include +#include +#include +#include namespace armix::io2_clocked_test { namespace d=armix::device; @@ -292,6 +295,63 @@ inline void run() { check(render(),"new B lease absent in ASRC must not break A"); check(near(left[frames-1],.2f*monoCenter,0.005f), "stale ASRC cannot be relabeled into newly leased device"); + // IO-2G P1: CONTROL must close callback admission BEFORE reading + // count/freeing scratch. In-flight render keeps the same exact borrowed + // B pointer pinned; a concurrent late primary callback fails immediately. + check(reader.prepare(plan,frames),"race fixture uses verified A+B map"); + std::atomic entered{false},release{false},stopped{false}; + std::thread admitted([&] { + const bool ok=reader.withBlocks(epoch,aInput,1,frames,clock, + [&](std::span) noexcept { + entered.store(true,std::memory_order_release); + while(!release.load(std::memory_order_acquire)) + std::this_thread::yield(); // test-only; never production RT + return true; + }); + check(ok,"previously admitted callback completed with scratch intact"); + }); + const auto deadline=std::chrono::steady_clock::now()+ + std::chrono::seconds(5); + while(!entered.load(std::memory_order_acquire) && + std::chrono::steady_clock::now()) noexcept { + return true; + }),"late primary callback rejects without borrowing freed scratch"); + release.store(true,std::memory_order_release); + admitted.join();control.join(); + check(stopped.load(std::memory_order_acquire) && !reader.status().ready, + "CONTROL retirement finishes only after old callback exits"); + + // ASan/TSan-friendly concurrent entry vs STOP/reprepare stress. + // The capture clock is stable; only reader scratch is being retired. + check(reader.prepare(plan,frames),"reader can safely reprepare after STOP"); + std::atomic running{true}; + std::thread primary([&] { + while(running.load(std::memory_order_acquire)) + (void)reader.withBlocks(epoch,aInput,1,frames,clock, + [](std::span) + noexcept {return true;}); + }); + for(int i=0;i<1200;++i) { + reader.stop(); + check(reader.prepare(plan,frames),"CONTROL reprepare gate stress"); + } + running.store(false,std::memory_order_release); + primary.join(); reader.stop(); clock.stop(); // IO-2D persistence recovery: a saved primary-only .smix can replace From d3d5ec3fc6a4223fef4102415fdddcd87d6b4d82 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 11:32:24 +0700 Subject: [PATCH 56/57] fix(io2h P1): atomically gate B producer and A ASRC reader before stop/reset --- engine/device/SecondaryCaptureClockStream.h | 64 +++++++++++++++------ 1 file changed, 45 insertions(+), 19 deletions(-) diff --git a/engine/device/SecondaryCaptureClockStream.h b/engine/device/SecondaryCaptureClockStream.h index 60acddff3..5b6528b70 100644 --- a/engine/device/SecondaryCaptureClockStream.h +++ b/engine/device/SecondaryCaptureClockStream.h @@ -6,6 +6,7 @@ #include #include #include +#include #include namespace armix::device @@ -21,6 +22,8 @@ class SecondaryCaptureClockStream final public: static constexpr int capacityFrames=32768; static constexpr int maxCallbackFrames=8192; + // Independent atomic admission gates avoid A/B clock callback contention. + static constexpr std::uint32_t writerFlag=1U,readerUnit=2U; struct Format { double captureHz=0.,primaryHz=0.; @@ -36,12 +39,11 @@ class SecondaryCaptureClockStream final bool prepare(const Format& format,double desiredTargetMs=24.) { - if(ready_.load(std::memory_order_acquire)|| - producers_.load(std::memory_order_acquire)!=0|| - consumers_.load(std::memory_order_acquire)!=0) - return false; + if(ready_.load(std::memory_order_acquire))return false; + // Faulted callbacks may still be in flight even with ready=false. + // CONTROL closes BOTH entry gates and drains old leases before ASRC. + stop(); // leaves both writer bits held until activate() // CONTROL owns the entire format and bridge reprepare interval. - ready_.store(false,std::memory_order_release); fault_.store(false,std::memory_order_release); // A previous successfully prepared (but not activated) stream must // never survive an invalid replacement request. activate() may not @@ -75,6 +77,9 @@ class SecondaryCaptureClockStream final if(!prepared_||fault_.load(std::memory_order_acquire)) return false; ready_.store(true,std::memory_order_release); + // Complete physical format + FIR initialization before opening RT. + producerActivity_.fetch_and(~writerFlag,std::memory_order_seq_cst); + consumerActivity_.fetch_and(~writerFlag,std::memory_order_seq_cst); return true; } @@ -90,10 +95,14 @@ class SecondaryCaptureClockStream final // Never call this or yield on either audio callback. void stop() noexcept { + // Set BOTH writer bits BEFORE observing in-flight borrow counts. + // Each CAS-admitted producer/consumer must retire before resetStopped. + producerActivity_.fetch_or(writerFlag,std::memory_order_seq_cst); + consumerActivity_.fetch_or(writerFlag,std::memory_order_seq_cst); ready_.store(false,std::memory_order_release); - while(producers_.load(std::memory_order_acquire)!=0|| - consumers_.load(std::memory_order_acquire)!=0) - std::this_thread::yield(); + while((producerActivity_.load(std::memory_order_seq_cst)&~writerFlag)!=0|| + (consumerActivity_.load(std::memory_order_seq_cst)&~writerFlag)!=0) + std::this_thread::yield(); // CONTROL only, never RT prepared_=false; fault_.store(false,std::memory_order_release); bridge_.resetStopped(); // no live producer or consumer @@ -102,16 +111,23 @@ class SecondaryCaptureClockStream final bool push(const float* const* capture,int channels,int frames) noexcept { - producers_.fetch_add(1,std::memory_order_acq_rel); + // One nonblocking CAS; no spin/lock/device call on B callback. + auto state=producerActivity_.load(std::memory_order_seq_cst); + if((state&writerFlag)!=0 || + state>std::numeric_limits::max()-readerUnit || + !producerActivity_.compare_exchange_strong( + state,state+readerUnit, + std::memory_order_seq_cst,std::memory_order_seq_cst)) + return false; const bool enabled=ready_.load(std::memory_order_acquire)&& !fault_.load(std::memory_order_acquire); - if(!enabled){producers_.fetch_sub(1,std::memory_order_release);return false;} + if(!enabled){producerActivity_.fetch_sub(readerUnit,std::memory_order_seq_cst);return false;} if(!capture||channels!=format_.channels||frames<1|| frames>maxCallbackFrames) { invalidBlocks_.fetch_add(1,std::memory_order_relaxed); fault(); - producers_.fetch_sub(1,std::memory_order_release); + producerActivity_.fetch_sub(readerUnit,std::memory_order_seq_cst); return false; } for(int c=0;cstd::numeric_limits::max()-readerUnit || + !consumerActivity_.compare_exchange_strong( + state,state+readerUnit, + std::memory_order_seq_cst,std::memory_order_seq_cst)) + return false; const bool valid=output&&channels>0&&channels<=16&&frames>0&& frames<=maxCallbackFrames; if(!valid) { - consumers_.fetch_sub(1,std::memory_order_release); + consumerActivity_.fetch_sub(readerUnit,std::memory_order_seq_cst); return false; } for(int c=0;c ready_{false},fault_{false}; - std::atomic producers_{0},consumers_{0}; + std::atomic producerActivity_{writerFlag}, + consumerActivity_{writerFlag}; std::atomic captureBlocks_{0},primaryBlocks_{0}, invalidBlocks_{0},staleReads_{0}; }; From e071e16e7136d58204acf8aaab6b1eb0d54d5d28 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 20 Nov 2026 11:33:04 +0700 Subject: [PATCH 57/57] test(io2h): ASRC STOP/reprepare concurrent with primary A rendering preserves A PCM and silences B --- .../QualifiedSecondaryCaptureReaderCases.h | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/tests/io2/QualifiedSecondaryCaptureReaderCases.h b/tests/io2/QualifiedSecondaryCaptureReaderCases.h index 5fd537759..9fbddf541 100644 --- a/tests/io2/QualifiedSecondaryCaptureReaderCases.h +++ b/tests/io2/QualifiedSecondaryCaptureReaderCases.h @@ -354,6 +354,56 @@ inline void run() { primary.join(); reader.stop(); clock.stop(); + + // IO-2H P1: B capture closes/resets its ASRC while the primary render + // callback is still consuming B. Exactly the unsafe sequence on an + // intentional disconnect. No global A reader shutdown is allowed: + // qualified A+B stays installed; B must become SILENT and A stays live. + check(clock.prepare(format)&&clock.activate(), + "fresh B clock is prepared for independent disconnect race"); + check(reader.prepare(plan,frames),"same native A+B reader stays installed"); + std::atomic keepRendering{true}; + std::atomic validPrimary{0},aOnly{0}; + std::thread aCallback([&] { + while(keepRendering.load(std::memory_order_acquire)) { + if(reader.withBlocks(epoch,aInput,1,frames,clock, + [&](std::span blocks) + noexcept { + const bool ok=native.render(epoch,nullptr,0, + left.data(),right.data(),frames,false,fx, + nullptr,nullptr,{},{},{},nullptr,0,blocks); + if(ok) { + validPrimary.fetch_add(1,std::memory_order_relaxed); + if(near(left[frames-1],.2f*monoCenter,0.005f)) + aOnly.fetch_add(1,std::memory_order_relaxed); + } + return ok; + })){} // test only: single primary callback + } + }); + for(int i=0;i<160;++i) { + clock.stop(); // CONTROL must wait for both admitted clock callbacks + if(i!=159) + check(clock.prepare(format)&&clock.activate(), + "B ASRC reprepare with competing A pulls never races reset"); + } + keepRendering.store(false,std::memory_order_release); + aCallback.join(); + check(validPrimary.load(std::memory_order_relaxed)>0 && + aOnly.load(std::memory_order_relaxed)>0, + "primary ChannelId MAIN and A-only PCM survive competing B disconnect"); + // After B has fully disconnected, the same qualified reader must still + // invoke the ONE A graph and silence only the missing B source. + check(reader.withBlocks(epoch,aInput,1,frames,clock, + [&](std::span blocks) + noexcept { + return native.render(epoch,nullptr,0,left.data(),right.data(), + frames,false,fx,nullptr,nullptr,{},{},{},nullptr,0,blocks); + }) && near(left[frames-1],.2f*monoCenter,0.005f) && + near(right[frames-1],.2f*monoCenter,0.005f), + "B absent never mutes or aliases direct primary A PCM"); + reader.stop(); + clock.stop(); // IO-2D persistence recovery: a saved primary-only .smix can replace // A+B only by an explicit, muted native session transaction. WIRE/FX // omission of a map still inherits B and must never silently alias pins.