From b449a17c36a8a901560f82dd95c5e36b27e3da95 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 11 Nov 2026 04:33:14 +0700 Subject: [PATCH 1/2] refactor(device): centralize live ASIO identity and non-destructive rebind evidence --- docs/architecture/README.md | 1 + src/Main.cpp | 60 +++++--------- src/NativeDeviceApplyCoordinator.h | 83 ++++++++++++++++++- tests/mixer_io_operator_contract_test.mjs | 13 ++- .../native_device_apply_coordinator_test.cpp | 57 +++++++++++++ 5 files changed, 171 insertions(+), 43 deletions(-) diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 402569d05..cde40b813 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -38,6 +38,7 @@ Assembled /preview/ DOM (presentation only) | Audio device policy | src/LiveAudioEngine.h; engine/device/**; src/Main.cpp currently applies device | Verified driver/pins, epochs, reopen/rebind, explicit physical output safety; independent from logical session document | | Audio device apply preflight (M2a) | src/NativeDeviceApplyCoordinator.h; src/Main.cpp (remaining orchestration) | Single message-thread transaction guard, JUCE open boundary, typed request/pin checks, accepted readback and fail-closed rollback. Next: extract full apply/rebind orchestration without duplicating DeviceManager | | Modal setup transaction (M2b) | src/Main.cpp::showDeviceSetup; NativeDeviceApplyCoordinator.h | Persistent one-owner lease across visible JUCE selector, explicit Apply and automatic ASIO restart; repeated Setup clicks never re-mute; selector close completes readback/rebind before releasing lease | +| Live hardware readback (M2c) | src/NativeDeviceApplyCoordinator.h; src/Main.cpp | Consolidated actual device-object readback on CONTROL, strict ASIO driver instance identity and live mask/rate/buffer verification before Apply/rollback; no new device owner or callback | | Production audio compatibility | src/LiveDryRoutingLab.h; engine/core/UnifiedLegacyProductionAdmission.h | Retain only proven required M4/FAT migration semantics; never create another render authority | | Built-in DSP and VST lifecycle | engine/builtin_fx/**; src/NativeBuiltInFx.h; src/FactoryFxRegistry.h; src/PluginCatalog.h; engine/core/DynamicChannelFxLeaseBank.h; src/LiveAudioEngine.h | Per-processor DSP; one built-in registration for live insert, offline prepare, restore and native picker. Specialized editors and vendor lease remain with their existing owners. | | Player | engine/player/**; src/Main.cpp dispatch | Worker decode / buffered PCM, one native graph virtual input, no independent hardware output callback | diff --git a/src/Main.cpp b/src/Main.cpp index 5e1218e3b..1fe70e22c 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1825,16 +1825,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(changedAsioPinLayout) error="ASIO pin layout changed. Output remains muted; review the new playback pins."; if(error.isEmpty()) { - armix::device::NativeDeviceApplyCoordinator::AppliedReadback observed; - observed.actual=actual; - observed.backend=manager.getCurrentAudioDeviceType(); - observed.open=opened!=nullptr&&opened->isOpen(); - if(observed.open) { - observed.activeInputs=opened->getActiveInputChannels(); - observed.activeOutputs=opened->getActiveOutputChannels(); - observed.deviceRate=opened->getCurrentSampleRate(); - observed.deviceBuffer=opened->getCurrentBufferSizeSamples(); - } + const auto observed=armix::device::NativeDeviceApplyCoordinator::inspectApplied(manager); if(!armix::device::NativeDeviceApplyCoordinator::matchesApplied( requested,candidate,observed)) error="Driver readback mismatch; device setting was not accepted"; @@ -1881,17 +1872,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto restored=recovery.priorKnownOpen&&previousType.isNotEmpty()&& openSelectedAudioDevice(previousType,before).isEmpty()&& manager.getCurrentAudioDeviceType()==previousType; - juce::AudioDeviceManager::AudioDeviceSetup checked; - manager.getAudioDeviceSetup(checked); - armix::device::NativeDeviceApplyCoordinator::RollbackReadback rollback; - rollback.actual=checked; - rollback.backend=manager.getCurrentAudioDeviceType(); - auto* recovered=manager.getCurrentAudioDevice(); - rollback.open=recovered!=nullptr&&recovered->isOpen(); - if(rollback.open) { - rollback.inputNames=recovered->getInputChannelNames(); - rollback.outputNames=recovered->getOutputChannelNames(); - } + const auto rollback=armix::device::NativeDeviceApplyCoordinator::inspectRollback(manager); const bool verified=restored&& armix::device::NativeDeviceApplyCoordinator::matchesRollback( before,previousType,originalInputNames,originalOutputNames,rollback)&& @@ -5714,24 +5695,29 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr bool finishAudioSetupAndRecoverMixer(MixerBindingMode bindingMode=MixerBindingMode::exact) { if(logicalVendorEditor_ || mixerSessionWorker_.busy())return false; const bool bound=engine_.finishManualAudioSetup(bindingMode!=MixerBindingMode::verifiedMainPinApply); - if(!engine_.directRouteAuthorized())return false; const auto lab=engine_.status().getProperty("dryRoutingLab",{}); - const bool hasCheckpoint=armix::session::NativeMixerSessionStore(settingsDirectory()).exists(); - const bool recoverPristine=hasCheckpoint && mixerSessionRecoveryPending_ && engine_.hasPristineStartupMixer(); - if(static_cast(lab.getProperty("nativeChannelIdPcmActive",false)) && - !recoverPristine)return true; - if(engine_.hasRetainedNativeSession() || hasCheckpoint) { - if(bindingMode==MixerBindingMode::exact && engine_.sameRetainedAsioDriver()) - bindingMode=MixerBindingMode::verifiedAsioRestart; - const auto error=restoreSavedMixerSession(false,bindingMode); - if(error.isNotEmpty()) { - mixerSessionError_=error; - emitNotice(error.startsWith("NEEDS_REMAP:")?error.fromFirstOccurrenceOf(": ",false,false):error,true); - return false; - } - return true; + const bool checkpoint=armix::session::NativeMixerSessionStore(settingsDirectory()).exists(); + using Coordinator=armix::device::NativeDeviceApplyCoordinator; + const auto decision=Coordinator::decideMixerRebind({ + engine_.directRouteAuthorized(), + static_cast(lab.getProperty("nativeChannelIdPcmActive",false)), + checkpoint,mixerSessionRecoveryPending_,engine_.hasPristineStartupMixer(), + engine_.hasRetainedNativeSession(),bound + }); + if(decision==Coordinator::MixerRebindAction::retainInstalled || + decision==Coordinator::MixerRebindAction::acceptFreshBound)return true; + if(decision!=Coordinator::MixerRebindAction::restoreRetained)return false; + // Only a verified retained identity may upgrade exact -> ASIO restart. + // The .smix document remains authoritative and is never reset here. + if(bindingMode==MixerBindingMode::exact && engine_.sameRetainedAsioDriver()) + bindingMode=MixerBindingMode::verifiedAsioRestart; + const auto error=restoreSavedMixerSession(false,bindingMode); + if(error.isNotEmpty()) { + mixerSessionError_=error; + emitNotice(error.startsWith("NEEDS_REMAP:")?error.fromFirstOccurrenceOf(": ",false,false):error,true); + return false; } - return bound; + return true; } std::uint64_t asioRecoveryEpoch_=0; // last successfully bound generation diff --git a/src/NativeDeviceApplyCoordinator.h b/src/NativeDeviceApplyCoordinator.h index 9948652eb..1b027714c 100644 --- a/src/NativeDeviceApplyCoordinator.h +++ b/src/NativeDeviceApplyCoordinator.h @@ -137,12 +137,30 @@ class NativeDeviceApplyCoordinator final { struct AppliedReadback { juce::AudioDeviceManager::AudioDeviceSetup actual; - juce::String backend; + juce::String backend, deviceName, deviceType; bool open=false; juce::BigInteger activeInputs,activeOutputs; double deviceRate=0.; int deviceBuffer=0; }; + // Read *both* manager configuration and the installed JUCE device object. + // The latter is the hardware evidence; it cannot be synthesized from the + // requested/stored setup. CONTROL thread only, after openSelected returns. + static AppliedReadback inspectApplied(juce::AudioDeviceManager& manager) { + AppliedReadback evidence; + manager.getAudioDeviceSetup(evidence.actual); + evidence.backend=manager.getCurrentAudioDeviceType(); + if(auto* device=manager.getCurrentAudioDevice();device && device->isOpen()) { + evidence.open=true; + evidence.deviceName=device->getName(); + evidence.deviceType=device->getTypeName(); + evidence.activeInputs=device->getActiveInputChannels(); + evidence.activeOutputs=device->getActiveOutputChannels(); + evidence.deviceRate=device->getCurrentSampleRate(); + evidence.deviceBuffer=device->getCurrentBufferSizeSamples(); + } + return evidence; + } // The acknowledgement is not permission to output sound: it proves only // that JUCE accepted the selected backend, names, masks, rate and period. static bool matchesApplied(const Request& requested, @@ -150,6 +168,10 @@ class NativeDeviceApplyCoordinator final { const AppliedReadback& live) noexcept { const auto& a=live.actual; return live.open&&live.backend==requested.backend&& + // Strict physical instance identity for ASIO: manager setup alone + // may name the intended driver while another callback is active. + (requested.backend!="ASIO" || + (live.deviceType=="ASIO" && live.deviceName==requested.playback))&& a.inputDeviceName==requested.capture&& a.outputDeviceName==requested.playback&& (requested.rate<=0.||std::abs(a.sampleRate-requested.rate)<=1.)&& @@ -164,10 +186,30 @@ class NativeDeviceApplyCoordinator final { struct RollbackReadback { juce::AudioDeviceManager::AudioDeviceSetup actual; - juce::String backend; + juce::String backend, deviceName, deviceType; bool open=false; juce::StringArray inputNames,outputNames; + juce::BigInteger activeInputs,activeOutputs; + double deviceRate=0.; + int deviceBuffer=0; }; + static RollbackReadback inspectRollback(juce::AudioDeviceManager& manager) { + RollbackReadback evidence; + manager.getAudioDeviceSetup(evidence.actual); + evidence.backend=manager.getCurrentAudioDeviceType(); + if(auto* device=manager.getCurrentAudioDevice();device && device->isOpen()) { + evidence.open=true; + evidence.deviceName=device->getName(); + evidence.deviceType=device->getTypeName(); + evidence.inputNames=device->getInputChannelNames(); + evidence.outputNames=device->getOutputChannelNames(); + evidence.activeInputs=device->getActiveInputChannels(); + evidence.activeOutputs=device->getActiveOutputChannels(); + evidence.deviceRate=device->getCurrentSampleRate(); + evidence.deviceBuffer=device->getCurrentBufferSizeSamples(); + } + return evidence; + } // Previously CLOSED driver is never a valid rollback target. For ASIO, // even a numerically equal mask is unsafe after pin names are reordered. static bool matchesRollback( @@ -178,15 +220,52 @@ class NativeDeviceApplyCoordinator final { const RollbackReadback& live) noexcept { const auto& a=live.actual; return live.open&&live.backend==previousBackend&& + (previousBackend!="ASIO" || + (live.deviceType=="ASIO" && live.deviceName==before.outputDeviceName))&& a.inputDeviceName==before.inputDeviceName&& a.outputDeviceName==before.outputDeviceName&& a.inputChannels==before.inputChannels&& a.outputChannels==before.outputChannels&& a.sampleRate==before.sampleRate&&a.bufferSize==before.bufferSize&& + // A manager can remember an old setup even if an ASIO instance + // restarted with fewer ports or a different callback quantum. + live.activeInputs==a.inputChannels&&live.activeOutputs==a.outputChannels&& + live.activeOutputs.countNumberOfSetBits()>=2&& + std::abs(live.deviceRate-a.sampleRate)<=1.&& + live.deviceBuffer==a.bufferSize&& (previousBackend!="ASIO"|| (live.inputNames==previousInputs&&live.outputNames==previousOutputs)); } + + // Device rebind owns the hardware graph, NEVER the accepted logical + // ChannelId/.smix document. Pure control-thread verdict: the caller is + // responsible for performing the exact existing native restore action. + enum class MixerRebindAction : std::uint8_t { + reject, retainInstalled, restoreRetained, acceptFreshBound + }; + struct MixerRebindEvidence { + bool physicalAuthorized=false; + bool installedChannelPcm=false; + bool storedCheckpoint=false; + bool pendingStartupRestore=false; + bool pristineStartupMixer=false; + bool retainedNativeSession=false; + bool freshBound=false; + }; + [[nodiscard]] static constexpr MixerRebindAction decideMixerRebind( + MixerRebindEvidence e) noexcept { + if(!e.physicalAuthorized)return MixerRebindAction::reject; + const bool mustRestorePristine=e.storedCheckpoint && + e.pendingStartupRestore && e.pristineStartupMixer; + if(e.installedChannelPcm && !mustRestorePristine) + return MixerRebindAction::retainInstalled; + if(e.retainedNativeSession || e.storedCheckpoint) + return MixerRebindAction::restoreRetained; + return e.freshBound?MixerRebindAction::acceptFreshBound: + MixerRebindAction::reject; + } + using RecordPhase=std::function; static juce::String openSelected(juce::AudioDeviceManager& manager, const juce::String& backend, diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index 418eb54d8..18da83a06 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -324,7 +324,9 @@ test('P0 MAONO: one APPLY MUTE-ACKs before switching and native ARM',()=>{ assert.match(js,/deviceNote=ack\?\.ok\?'DEVICE ACCEPTED · OUTPUT MUTED · '\+devicePinNextStep\(\)/); assert.match(main,/!engine_\.allOutputsDisarmed\(\)/); assert.match(main,/NativeDeviceApplyCoordinator::matchesApplied/); - assert.match(main,/observed\.activeInputs=opened->getActiveInputChannels\(\)/); + assert.match(main,/NativeDeviceApplyCoordinator::inspectApplied\(manager\)/); + assert.match(applyOwner,/evidence\.activeInputs=device->getActiveInputChannels\(\)/); + assert.match(applyOwner,/live\.deviceName==requested\.playback/); assert.match(applyOwner,/live\.activeInputs==a\.inputChannels/); assert.match(applyOwner,/std::abs\(live\.deviceRate-a\.sampleRate\)/); assert.match(engine,/return isOutputMuted\(\) && !secondaryOutput_\.armed\(\)/); @@ -360,9 +362,12 @@ test('DEVICE2 native device list is cached on overlay open; explicit scan is fai const apply=native.slice(native.indexOf('void applyCustomAudioDevice('), native.indexOf('void showDeviceSetup()',native.indexOf('void applyCustomAudioDevice('))); assert.match(apply,/NativeDeviceApplyCoordinator::matchesApplied/); - assert.match(apply,/observed\.activeInputs=opened->getActiveInputChannels\(\)/); - assert.match(apply,/observed\.activeOutputs=opened->getActiveOutputChannels\(\)/); - assert.match(apply,/observed\.deviceBuffer=opened->getCurrentBufferSizeSamples\(\)/); + assert.match(apply,/NativeDeviceApplyCoordinator::inspectApplied\(manager\)/); + assert.match(applyOwner,/evidence\.activeInputs=device->getActiveInputChannels\(\)/); + assert.match(applyOwner,/evidence\.activeOutputs=device->getActiveOutputChannels\(\)/); + assert.match(applyOwner,/evidence\.deviceBuffer=device->getCurrentBufferSizeSamples\(\)/); + assert.match(apply,/NativeDeviceApplyCoordinator::inspectRollback\(manager\)/); + assert.match(applyOwner,/live\.deviceName==before\.outputDeviceName/); assert.match(applyOwner,/live\.activeInputs==a\.inputChannels/); assert.match(applyOwner,/live\.activeOutputs==a\.outputChannels/); assert.match(applyOwner,/live\.deviceBuffer==a\.bufferSize/); diff --git a/tests/native_device_apply_coordinator_test.cpp b/tests/native_device_apply_coordinator_test.cpp index 6be22a992..321121f5a 100644 --- a/tests/native_device_apply_coordinator_test.cpp +++ b/tests/native_device_apply_coordinator_test.cpp @@ -125,12 +125,20 @@ int main() { Coordinator::AppliedReadback observed; observed.backend="ASIO"; observed.actual=candidate; + observed.deviceName="ASIO Test"; + observed.deviceType="ASIO"; observed.open=true; observed.activeInputs=candidate.inputChannels; observed.activeOutputs=candidate.outputChannels; observed.deviceRate=48000.; observed.deviceBuffer=256; assert(Coordinator::matchesApplied(request,candidate,observed)); + observed.deviceName="ASIO Different"; + assert(!Coordinator::matchesApplied(request,candidate,observed)); + observed.deviceName="ASIO Test"; + observed.deviceType="Windows Audio"; + assert(!Coordinator::matchesApplied(request,candidate,observed)); + observed.deviceType="ASIO"; observed.actual.outputChannels.clearBit(1); assert(!Coordinator::matchesApplied(request,candidate,observed)); observed.actual=candidate; @@ -147,10 +155,28 @@ int main() { rollback.open=true; rollback.backend="ASIO"; rollback.actual=candidate; + rollback.deviceName="ASIO Test"; + rollback.deviceType="ASIO"; + rollback.activeInputs=candidate.inputChannels; + rollback.activeOutputs=candidate.outputChannels; + rollback.deviceRate=48000.; + rollback.deviceBuffer=256; rollback.inputNames={"Mic 1","Mic 2"}; rollback.outputNames={"Monitor L","Monitor R"}; assert(Coordinator::matchesRollback(candidate,"ASIO",rollback.inputNames, rollback.outputNames,rollback)); + rollback.deviceName="Other ASIO"; + assert(!Coordinator::matchesRollback(candidate,"ASIO", + rollback.inputNames,rollback.outputNames,rollback)); + rollback.deviceName="ASIO Test"; + rollback.activeOutputs.clearBit(1); + assert(!Coordinator::matchesRollback(candidate,"ASIO", + rollback.inputNames,rollback.outputNames,rollback)); + rollback.activeOutputs=candidate.outputChannels; + rollback.deviceBuffer=512; + assert(!Coordinator::matchesRollback(candidate,"ASIO", + rollback.inputNames,rollback.outputNames,rollback)); + rollback.deviceBuffer=256; rollback.outputNames={"Monitor R","Monitor L"}; assert(!Coordinator::matchesRollback(candidate,"ASIO", {"Mic 1","Mic 2"},{"Monitor L","Monitor R"},rollback)); @@ -158,5 +184,36 @@ int main() { rollback.open=false; assert(!Coordinator::matchesRollback(candidate,"ASIO", rollback.inputNames,rollback.outputNames,rollback)); + + // M2c accepted session/rebind policy must be independent of a device + // dialog, DSP and any filesystem writes. Rejections never clear .smix. + using Rebind=Coordinator::MixerRebindAction; + const auto decide=Coordinator::decideMixerRebind; + Coordinator::MixerRebindEvidence e; + assert(decide(e)==Rebind::reject); + e.installedChannelPcm=true; + e.storedCheckpoint=true; + e.retainedNativeSession=true; + assert(decide(e)==Rebind::reject); // physical fence always wins + e.physicalAuthorized=true; + assert(decide(e)==Rebind::retainInstalled); // no-change dialog + e.pendingStartupRestore=true; + e.pristineStartupMixer=true; + assert(decide(e)==Rebind::restoreRetained); // must restore accepted Show + e.storedCheckpoint=false; + e.retainedNativeSession=false; + assert(decide(e)==Rebind::retainInstalled); // no file, installed graph valid + e.installedChannelPcm=false; + assert(decide(e)==Rebind::reject); // no fabricated fresh PCM admission + e.freshBound=true; + assert(decide(e)==Rebind::acceptFreshBound); + e.retainedNativeSession=true; + assert(decide(e)==Rebind::restoreRetained); + e.retainedNativeSession=false; + e.storedCheckpoint=true; + assert(decide(e)==Rebind::restoreRetained); + e.physicalAuthorized=false; + assert(decide(e)==Rebind::reject); // stale device can't replay document + std::cout<<"Native device Apply preflight/rollback: PASS\n"; } From cf2ecdbc9313d3cceb1df9fc62821b2368020593 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 11 Nov 2026 04:37:11 +0700 Subject: [PATCH 2/2] fix(device): fail closed on invalid physical sample clock and buffer readback --- src/NativeDeviceApplyCoordinator.h | 12 ++++++++++-- tests/native_device_apply_coordinator_test.cpp | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/NativeDeviceApplyCoordinator.h b/src/NativeDeviceApplyCoordinator.h index 1b027714c..31dceba31 100644 --- a/src/NativeDeviceApplyCoordinator.h +++ b/src/NativeDeviceApplyCoordinator.h @@ -161,13 +161,20 @@ class NativeDeviceApplyCoordinator final { } return evidence; } + // A driver may return an OPEN status but no usable clock/buffer evidence. + // Unknown/zero/nonfinite live formats cannot establish playable PCM. + static bool validLiveFormat(double sampleRate,int frames) noexcept { + return std::isfinite(sampleRate) && sampleRate>=8000. && + sampleRate<=384000. && frames>=16 && frames<=8192; + } // The acknowledgement is not permission to output sound: it proves only // that JUCE accepted the selected backend, names, masks, rate and period. static bool matchesApplied(const Request& requested, const juce::AudioDeviceManager::AudioDeviceSetup& candidate, const AppliedReadback& live) noexcept { const auto& a=live.actual; - return live.open&&live.backend==requested.backend&& + return live.open&&validLiveFormat(live.deviceRate,live.deviceBuffer)&& + live.backend==requested.backend&& // Strict physical instance identity for ASIO: manager setup alone // may name the intended driver while another callback is active. (requested.backend!="ASIO" || @@ -219,7 +226,8 @@ class NativeDeviceApplyCoordinator final { const juce::StringArray& previousOutputs, const RollbackReadback& live) noexcept { const auto& a=live.actual; - return live.open&&live.backend==previousBackend&& + return live.open&&validLiveFormat(live.deviceRate,live.deviceBuffer)&& + live.backend==previousBackend&& (previousBackend!="ASIO" || (live.deviceType=="ASIO" && live.deviceName==before.outputDeviceName))&& a.inputDeviceName==before.inputDeviceName&& diff --git a/tests/native_device_apply_coordinator_test.cpp b/tests/native_device_apply_coordinator_test.cpp index 321121f5a..76e47afe6 100644 --- a/tests/native_device_apply_coordinator_test.cpp +++ b/tests/native_device_apply_coordinator_test.cpp @@ -145,6 +145,12 @@ int main() { observed.deviceBuffer=128; assert(!Coordinator::matchesApplied(request,candidate,observed)); observed.deviceBuffer=256; + observed.deviceRate=0.; + assert(!Coordinator::matchesApplied(request,candidate,observed)); + observed.deviceRate=48000.; + observed.deviceBuffer=0; + assert(!Coordinator::matchesApplied(request,candidate,observed)); + observed.deviceBuffer=256; observed.backend="Windows Audio"; assert(!Coordinator::matchesApplied(request,candidate,observed)); observed.backend="ASIO"; @@ -177,6 +183,14 @@ int main() { assert(!Coordinator::matchesRollback(candidate,"ASIO", rollback.inputNames,rollback.outputNames,rollback)); rollback.deviceBuffer=256; + rollback.deviceRate=0.; + assert(!Coordinator::matchesRollback(candidate,"ASIO", + rollback.inputNames,rollback.outputNames,rollback)); + rollback.deviceRate=48000.; + rollback.deviceBuffer=0; + assert(!Coordinator::matchesRollback(candidate,"ASIO", + rollback.inputNames,rollback.outputNames,rollback)); + rollback.deviceBuffer=256; rollback.outputNames={"Monitor R","Monitor L"}; assert(!Coordinator::matchesRollback(candidate,"ASIO", {"Mic 1","Mic 2"},{"Monitor L","Monitor R"},rollback));