From a1a3bc57485cec59ad63a57e6eb09c5ad3ce5310 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 17:02:45 +0700 Subject: [PATCH 01/26] fix(startup): admit real silent ChannelId mixer with zero hardware inputs Output-only DIRECT fences and callback mask validation now permit zero capture without inventing input pins. A verified SOURCE NONE startup publishes the same authoritative native PCM graph used for FX, track and WIRE editing. Preserve output muting and driver identity, add zero-capture regression cases. --- engine/device/DirectRouteFence.h | 11 ++++++---- engine/device/JuceActivePortSnapshot.h | 5 ++--- src/LiveAudioEngine.h | 28 +++++++++++++++++++----- src/LiveDryRoutingLab.h | 13 ++++++----- src/NativeMixerSessionDocument.h | 5 +++-- tests/direct_route_fence_test.cpp | 7 +++++- tests/juce_active_port_snapshot_test.cpp | 11 +++++++--- web/approved-native-bridge.js | 6 ++--- 8 files changed, 59 insertions(+), 27 deletions(-) diff --git a/engine/device/DirectRouteFence.h b/engine/device/DirectRouteFence.h index 8647f3e6d..02fbca3a0 100644 --- a/engine/device/DirectRouteFence.h +++ b/engine/device/DirectRouteFence.h @@ -92,8 +92,10 @@ class DirectRouteFence final std::string_view inputMask, std::string_view outputMask) noexcept { - if (type.empty() || device.empty() || !validMask(inputMask) - || !validMask(outputMask)) return 0; + // Zero capture pins are permitted ONLY for the input side of an + // output-only session. The playback mask must identify real pins. + if (type.empty() || device.empty() || !validMask(inputMask,true) + || !validMask(outputMask,false)) return 0; std::uint64_t hash=14695981039346656037ull; append(hash, type); append(hash, device); @@ -102,9 +104,10 @@ class DirectRouteFence final return hash ? hash : 1; // reserve zero for never-approved } private: - static bool validMask(std::string_view mask) noexcept + static bool validMask(std::string_view mask,bool allowZero) noexcept { - if (mask.empty() || mask.front() == '0') return false; + if (mask.empty() || (mask.front() == '0' && + !(allowZero && mask.size() == 1))) return false; for (const unsigned char c : mask) if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false; diff --git a/engine/device/JuceActivePortSnapshot.h b/engine/device/JuceActivePortSnapshot.h index 359ea9d96..feb8c1745 100644 --- a/engine/device/JuceActivePortSnapshot.h +++ b/engine/device/JuceActivePortSnapshot.h @@ -26,8 +26,8 @@ struct JuceActivePortSnapshot final { std::uint64_t epoch=0; juce::String deviceName, typeName; - // Accept a frozen copy of masks so unit tests can exercise sparse - // numbering without requiring an ASIO device. This executes off RT. + // Accept a frozen copy of masks to exercise sparse numbering and real + // output-only devices with zero capture pins. No fake input is created. static bool fromMasks(std::uint64_t epoch, const juce::BigInteger& inputMask, const juce::BigInteger& outputMask, @@ -46,7 +46,6 @@ struct JuceActivePortSnapshot final { if(p>=limit || out>=limit){error=Fault::tooManyOutputs;return false;} outputIndices[out++]=p; } - if(in==0){error=Fault::emptyInput;return false;} if(out==0){error=Fault::emptyOutput;return false;} JuceActivePortSnapshot candidate; LiveInputPortRegistry::Fault inputFault{}; diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index ae280f64d..3ff55dfc6 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -210,6 +210,19 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback + " | Windows Audio fallback unavailable"; } #endif + // On first installation only, an output-only endpoint is a valid + // playback/Player host. Never replace a saved explicit ASIO route. + // Physical output is still muted and DIRECT-fenced until verified. + if(error.isNotEmpty() && !savedRoute) { + const auto outputError=deviceManager_.initialise(0,2,nullptr,true); + const auto* candidate=deviceManager_.getCurrentAudioDevice(); + if(outputError.isEmpty() && candidate && + candidate->getActiveOutputChannels().countNumberOfSetBits()>=2) { + startupFallbackReason_="AUTO_OUTPUT_ONLY_NO_CAPTURE"; + error.clear(); + } else if(outputError.isNotEmpty()) + error+=" | Output-only startup: "+outputError; + } if (error.isNotEmpty()) return error; const auto* active = deviceManager_.getCurrentAudioDevice(); if (active == nullptr) @@ -1131,6 +1144,13 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback formats_,device->getCurrentSampleRate(), juce::jmax(32,device->getCurrentBufferSizeSamples())); if(error.isEmpty() && dryRoutingLab_.epoch()==epoch) { + // The real SOURCE NONE graph is editable before any hardware IN + // patch; one ChannelId publisher remains the PCM authority. + if(!dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count, + juce::jmax(32,device->getCurrentBufferSizeSamples()), + allOutputsDisarmed(),currentOriginalCh1Lease())) + return "Prepared silent mixer could not admit native ChannelId graph"; acceptedMixerBinding_=readMixerBinding(*device); acceptedWasapiBinding_=std::move(profile); } @@ -2321,7 +2341,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const auto rate=device->getCurrentSampleRate(); const auto frames=device->getCurrentBufferSizeSamples(); if(inputs!=setup.inputChannels || outputs!=setup.outputChannels || - inputs.isZero() || outputs.countNumberOfSetBits()<2 || + outputs.countNumberOfSetBits()<2 || !std::isfinite(rate) || rate<8000.0 || rate!=setup.sampleRate || frames<16 || frames>LiveDryRoutingLab::Block::hardFrameLimit || frames!=setup.bufferSize)return {}; @@ -2377,8 +2397,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const armix::device::AsioRegistrationPolicy::Identity* expectedAsio = nullptr) { auto* device=deviceManager_.getCurrentAudioDevice(); - if (device == nullptr || device->getActiveInputChannels().isZero() - || device->getActiveOutputChannels().isZero()) + if (device == nullptr || device->getActiveOutputChannels().isZero()) return false; // JUCE BigInteger has no fixed 64-bit channel limit: preserve all // channel bits when locking an explicitly approved ASIO/WASAPI route. @@ -2420,8 +2439,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool resumeVerifiedDirectRoute() { auto* device=deviceManager_.getCurrentAudioDevice(); - if (device == nullptr || device->getActiveInputChannels().isZero() - || device->getActiveOutputChannels().isZero()) + if (device == nullptr || device->getActiveOutputChannels().isZero()) return false; const auto backend=device->getTypeName(); const auto name=device->getName(); diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 5a0a6ac62..c5730245e 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -94,7 +94,7 @@ class LiveDryRoutingLab final { device,generation,snapshot,reason))return; const int inputs=snapshot.inputs.enabledCount; const int outputs=snapshot.outputCount; - if(inputs<=0 || outputs<2) return; // stereo monitoring LAB only + if(inputs<0 || outputs<2) return; // output-only is a real SILENT native session for(int i=0;isetProperty("channels",juce::var(channels)); const FxSelections none{}; - // Same publisher/graph as a real user APPLY, but no authorization. - // Never briefly advertise a synthetic route as LIVE. + // Genuine accepted SOURCE NONE topology: editing does not require + // microphone capture. Sound remains zero and unarmed until a verified + // source and independently authorized physical output exist. return apply(juce::var(request.release()),directPermitted, independentClock,loadedFx,none,formats, - sampleRate,deviceFrames,false); + sampleRate,deviceFrames,true); } juce::String apply (const juce::var& command, bool directPermitted, @@ -220,7 +221,7 @@ class LiveDryRoutingLab final { if(topologyFault_.load(std::memory_order_acquire)) return "Device callback channel layout changed; reopen AUDIO SETUP before applying"; const int countNow=portCount_.load(std::memory_order_acquire); - if(countNow<=0 || countNow>armix::device::LiveInputPortRegistry::limit) + if(countNow<0 || countNow>armix::device::LiveInputPortRegistry::limit) return "Invalid active device input channel mask"; std::array physicalPorts{}; for(int i=0;iarmix::device::LiveInputPortRegistry::limit) + if(inputs<0||inputs>armix::device::LiveInputPortRegistry::limit) return false; std::array ports{}; for(int i=0;i256 || - live.backend.isEmpty() || live.capture.isEmpty() || + if(!outputs.valid() || callbackInputs<0 || callbackInputs>256 || + live.backend.isEmpty() || + (callbackInputs>0 && live.capture.isEmpty()) || live.playback.isEmpty() || live.inputMask.isEmpty() || live.outputMask.isEmpty() || !std::isfinite(live.rate) || live.rate<8000. || live.rate>384000. || diff --git a/tests/direct_route_fence_test.cpp b/tests/direct_route_fence_test.cpp index afb0fbeb6..f78d4b3d8 100644 --- a/tests/direct_route_fence_test.cpp +++ b/tests/direct_route_fence_test.cpp @@ -12,7 +12,12 @@ int main() check(f.fault() == F::awaitingApproval); check(!f.observeStart("ASIO", "Live USB", "3", "3")); check(!f.approve("ASIO", "", "3", "3")); - check(!f.approve("ASIO", "Live USB", "0", "3")); + // Explicit output-only setup keeps a real zero capture mask, not fake IN. + check(f.approve("ASIO", "Live USB", "0", "3")); + check(f.observeStart("ASIO", "Live USB", "0", "3")); + check(!f.observeStart("ASIO", "Live USB", "0", "0")); + f.suspend(); + check(!f.approve("ASIO", "Live USB", "0", "0")); check(!f.approve("ASIO", "Live USB", "3", "")); check(!f.approve("ASIO", "Live USB", "03", "3")); check(!f.approve("ASIO", "Live USB", "G", "3")); diff --git a/tests/juce_active_port_snapshot_test.cpp b/tests/juce_active_port_snapshot_test.cpp index b4e76b976..e1652fc39 100644 --- a/tests/juce_active_port_snapshot_test.cpp +++ b/tests/juce_active_port_snapshot_test.cpp @@ -40,9 +40,14 @@ int main(){ out.clear(); assert(!JuceActivePortSnapshot::fromMasks(12,in,out,snap,fault)); assert(fault==JuceActivePortSnapshot::Fault::emptyOutput); - in.clear(); - assert(!JuceActivePortSnapshot::fromMasks(12,in,out,snap,fault)); - assert(fault==JuceActivePortSnapshot::Fault::emptyInput); + in.clear();out.setBit(1);out.setBit(7); + assert(JuceActivePortSnapshot::fromMasks(12,in,out,snap,fault)); + assert(snap.inputs.enabledCount==0); + assert(snap.matchesCallback(12,0,2)); + assert(!snap.matchesCallback(12,1,2)); + out.clear(); + assert(!JuceActivePortSnapshot::fromMasks(13,in,out,snap,fault)); + assert(fault==JuceActivePortSnapshot::Fault::emptyOutput); assert(snap.inputs.callbackIndex(9)==previous.inputs.callbackIndex(9)); assert(!JuceActivePortSnapshot::capture(nullptr,12,snap,fault)); assert(fault==JuceActivePortSnapshot::Fault::nullDevice); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index b202f8c60..41f8f3129 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1462,7 +1462,7 @@ hardware.device.epoch!=="0" && hardware.device.sampleRate>0 && hardware.device.bufferFrames>0 && Array.isArray(hardware.device.enabledInputs) && - hardware.device.enabledInputs.length>0 && + // Physical IN is optional; SOURCE NONE and FX/WIRE are native edits. Array.isArray(hardware.device.enabledOutputs) && hardware.device.enabledOutputs.length>=2 && (mixerSession()?.authority==="CHANNEL_ID" @@ -1513,7 +1513,7 @@ !deviceOpen?"NO VERIFIED AUDIO DEVICE": d.outputArmed?(next.admitted?"NATIVE PCM · HARDWARE FAT PENDING": "MAIN MONITOR ON · PCM ADMISSION NOT VERIFIED"): - !d.enabledInputs?.length?"NO CAPTURE INPUT · OPEN AUDIO I/O": + !d.enabledInputs?.length?"NO HARDWARE IN · MIXER/FX READY · USE PLAYER OR AUDIO I/O": legacy()?.routeAccepted?"NATIVE INPUT ROUTED · MONITOR OFF": deviceReady()?"SELECT CHANNEL IN · NATIVE MONITOR AFTER ACK": "NO VERIFIED INPUT ROUTE · OPEN AUDIO I/O"; @@ -2211,7 +2211,7 @@ deviceReady()? "NATIVE G0 · verified physical IN ready · select a channel input": hardware?.device?.enabledInputs?.length===0? - "NO CAPTURE PINS · Audio I/O: enable an actual hardware input": + "NO HARDWARE IN · FX/BUS/WIRE REMAIN AVAILABLE": "NATIVE G0 NOT READY · open Audio I/O and verify device / native route"); return; } From fda9ef50e54e274fb798095bdd485c24f4f3ab3f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 17:06:17 +0700 Subject: [PATCH 02/26] fix(native): preserve unpatched M4 contract, safely admit silent starter, persist 0-input sessions Only a verified ten-channel SOURCE NONE starter may enter native ChannelId without physical capture. Keep M4 fail-silent until admission, retain exact device fence and enable portable .smix roundtrip with zero capture. Extend tests. --- src/LiveAudioEngine.h | 2 +- src/LiveDryRoutingLab.h | 24 ++++++++++++++++------- src/NativeMixerSessionDocument.h | 10 +++++++--- tests/juce_active_port_snapshot_test.cpp | 2 +- tests/native_mixer_session_store_test.cpp | 15 ++++++++++++++ 5 files changed, 41 insertions(+), 12 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 3ff55dfc6..c6f267d56 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1149,7 +1149,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if(!dryRoutingLab_.admitChannelIdFromAcceptedM4( graphOwned_->count, juce::jmax(32,device->getCurrentBufferSizeSamples()), - allOutputsDisarmed(),currentOriginalCh1Lease())) + allOutputsDisarmed(),currentOriginalCh1Lease(),true)) return "Prepared silent mixer could not admit native ChannelId graph"; acceptedMixerBinding_=readMixerBinding(*device); acceptedWasapiBinding_=std::move(profile); diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index c5730245e..49c77cd75 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -174,12 +174,11 @@ class LiveDryRoutingLab final { } request->setProperty("channels",juce::var(channels)); const FxSelections none{}; - // Genuine accepted SOURCE NONE topology: editing does not require - // microphone capture. Sound remains zero and unarmed until a verified - // source and independently authorized physical output exist. + // Keep M4's historical unpatched/fail-silent behavior. Startup + // explicitly promotes this same genuine SOURCE NONE graph to PCM. return apply(juce::var(request.release()),directPermitted, independentClock,loadedFx,none,formats, - sampleRate,deviceFrames,true); + sampleRate,deviceFrames,false); } juce::String apply (const juce::var& command, bool directPermitted, @@ -1153,7 +1152,8 @@ class LiveDryRoutingLab final { // The published ChannelId snapshot retains this owner until RT retires. bool admitChannelIdFromAcceptedM4(int occupiedExternalCh1Fx, int deviceFrames,bool outputsDisarmed, - armix::mixer::DynamicChannelFxLeaseBank::ExternalLease externalCh1={}) { + armix::mixer::DynamicChannelFxLeaseBank::ExternalLease externalCh1={}, + bool admitSilentUnpatched=false) { // E5: a native BUS uses topology that M4 cannot represent. Never // demote its renderer on an unsupported legacy re-admission. if((nativeStructureLive_ || nativeControlDirty_) && @@ -1165,18 +1165,28 @@ class LiveDryRoutingLab final { channelIdPcmEpoch_.store(0,std::memory_order_release); nativeStructureLive_=false; try { + const bool silentStarter=admitSilentUnpatched && !hasExplicitRoute() && + sourceTemplate_.isObject() && !userPatched_.load(std::memory_order_acquire); if(!outputsDisarmed || occupiedExternalCh1Fx<0 || (occupiedExternalCh1Fx>0)!=externalCh1.populated() || - !hasExplicitRoute()||!ready() || + (!hasExplicitRoute()&&!silentStarter)||!ready() || topologyFault_.load(std::memory_order_acquire)) return false; const auto generation=epoch(),m4Revision=revision(); const auto* old=publisher_.controlPrepared(generation,m4Revision); if(!old || deviceFrames<=0) return false; + const auto& route=silentStarter?sourceTemplate_:acceptedRoute_; + // This admission never upgrades a draft with unverified capture. + if(silentStarter) { + const auto* rows=route.getProperty("channels",juce::var()).getArray(); + if(!rows || rows->size()!=count)return false; + for(const auto& row:*rows) + if(row.getProperty("mode",{}).toString()!="NONE")return false; + } armix::mixer::NativeDryRouteCommand decoded; juce::String problem; if(!armix::mixer::NativeDryRouteCommand::decode( - acceptedRoute_,decoded,problem))return false; + route,decoded,problem))return false; // A native IN is a callback ordinal, not the numerical physical // port label. Preserve original order including sparse ASIO pins. const int inputs=portCount_.load(std::memory_order_acquire); diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index ca93c1b66..d89b47a78 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -349,7 +349,7 @@ class Codec final { doc.savedMs=static_cast(ms); const auto binding=get(root,"binding"); if(!textField(get(binding,"backend"),doc.binding.backend,128)|| - !textField(get(binding,"capture"),doc.binding.capture,256)|| + !textField(get(binding,"capture"),doc.binding.capture,256,true)|| !textField(get(binding,"playback"),doc.binding.playback,256)|| !textField(get(binding,"inputMask"),doc.binding.inputMask,256)|| !textField(get(binding,"outputMask"),doc.binding.outputMask,256)) @@ -428,13 +428,17 @@ class Codec final { (doc.legacyIds.monitor.value&&!seek(doc.legacyIds.monitor,ChannelRole::monitor))) return false; auto req=get(root,"request"); - if(!integral(get(req,"physicalInputs"),doc.request.physicalInputs,1,256)|| + if(!integral(get(req,"physicalInputs"),doc.request.physicalInputs,0,256)|| !integral(get(req,"maxFrames"),doc.request.maxFrames,16,8192)|| !strictBool(get(req,"mainMonoAfterFx"),doc.request.mainMonoAfterFx)) return false; const auto sourcesVar=get(req,"sources"); const auto* sources=sourcesVar.getArray(); - if(!sources||sources->size()>channels->size())return false; + if(!sources||sources->size()>channels->size()|| + (doc.request.physicalInputs==0 && !sources->isEmpty()))return false; + if(doc.binding.capture.isEmpty() && + (doc.request.physicalInputs!=0 || doc.binding.inputMask!="0")) + return false; std::set seenSources; for(const auto& src:*sources) { DynamicSourcePatch p; diff --git a/tests/juce_active_port_snapshot_test.cpp b/tests/juce_active_port_snapshot_test.cpp index e1652fc39..06fd698b7 100644 --- a/tests/juce_active_port_snapshot_test.cpp +++ b/tests/juce_active_port_snapshot_test.cpp @@ -48,7 +48,7 @@ int main(){ out.clear(); assert(!JuceActivePortSnapshot::fromMasks(13,in,out,snap,fault)); assert(fault==JuceActivePortSnapshot::Fault::emptyOutput); - assert(snap.inputs.callbackIndex(9)==previous.inputs.callbackIndex(9)); + assert(snap.inputs.callbackIndex(9)==-1); // failed 0-OUT preserves accepted zero-input snapshot assert(!JuceActivePortSnapshot::capture(nullptr,12,snap,fault)); assert(fault==JuceActivePortSnapshot::Fault::nullDevice); } diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index bd0191557..8f34bd107 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -351,6 +351,21 @@ static void warmVst3Discovery() { } int main(){ + // Zero-input is a legitimate saved SOURCE NONE workspace, never a fake mic. + { + auto silent=makeSession(); + silent.binding={"Windows Audio","","Speakers","0","3",48000.,256}; + silent.request.sources.clear();silent.request.physicalInputs=0; + MixerSessionDocument decoded; + assert(Codec::decode(Codec::encode(silent),decoded)); + assert(decoded.request.physicalInputs==0 && decoded.request.sources.empty()); + assert(decoded.roster.revision()==silent.roster.revision()); + assert(MixerDeviceBindingPolicy::apply(decoded,decoded.binding, + decoded.outputs,0,BindingMode::exact).isEmpty()); + auto malformed=juce::JSON::parse(Codec::encode(silent)); + malformed.getProperty("binding",{}).getDynamicObject()->setProperty("inputMask","3"); + assert(!Codec::decode(juce::JSON::toString(malformed,false),decoded)); + } warmVst3Discovery(); nativeDeviceRecovery(); auto d=makeSession(); From 75e99c63a8ef46d6c361113b33f58e325848361e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 17:10:50 +0700 Subject: [PATCH 03/26] test(P0): prove output-only native silent mixer can add track and render true zero PCM Adapt startup banner contract to zero-capture no longer blocking FX, add JUCE-backed 0-IN 2-OUT ChannelId bootstrap/track/PCM test; retain M4 unpatched refusal. --- tests/approved_native_m2_contract.test.cjs | 3 +- tests/native_mixer_session_store_test.cpp | 33 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 31f2539ef..6568af4c0 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1241,7 +1241,8 @@ test("P0 native FX rack and per-slot readback update mounted strip without repla test("P0 startup banner never demands legacy Patch CH1 / Arm wizard",()=>{ const bridge=read("web/approved-native-bridge.js"); assert.match(bridge,/SELECT CHANNEL IN · NATIVE MONITOR AFTER ACK/); - assert.match(bridge,/NO CAPTURE INPUT · OPEN AUDIO I\/O/); + assert.match(bridge,/NO HARDWARE IN · MIXER\/FX READY · USE PLAYER OR AUDIO I\/O/); + assert.doesNotMatch(bridge,/hardware\.device\.enabledInputs\.length>0/); assert.match(bridge,/NO VERIFIED INPUT ROUTE · OPEN AUDIO I\/O/); assert.doesNotMatch(bridge,/NO AUDIBLE OUTPUT · PATCH INPUT \+ ARM/); assert.match(bridge,/const preparedFirstSound=session\?\.authority==="NONE"/); diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index 8f34bd107..952281888 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -93,6 +93,38 @@ class FixtureDevice final : public juce::AudioIODevice { double rate=48000.; }; +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. + FixtureDevice playback; + playback.inputMask.clear(); + LiveDryRoutingLab mixer; + juce::AudioPluginFormatManager formats; + mixer.prepareDevice(&playback); + assert(mixer.startUnpatchedSession(true,false,0,formats,48000.,480).isEmpty()); + assert(mixer.ready() && !mixer.hasExplicitRoute()); + // Legacy startup is silent before the one deliberate native migration. + assert(!mixer.admitChannelIdFromAcceptedM4(0,480,true)); + assert(mixer.admitChannelIdFromAcceptedM4(0,480,true,{},true)); + assert(mixer.hasExplicitRoute() && !mixer.hasVerifiedNativeSources()); + const auto native=mixer.nativeBusStatus(); + assert(native.isObject()); + const auto graph=static_cast( + native.getProperty("graphRevision",{}).toString().getLargeIntValue()); + const auto roster=static_cast( + native.getProperty("rosterRevision",{}).toString().getLargeIntValue()); + const auto add=mixer.createNativeInputChannel(mixer.epoch(),graph,roster, + "No Microphone Track",ProcessingFormat::stereo,true); + assert(add.accepted && !mixer.hasVerifiedNativeSources()); + std::array left{},right{}; + left.fill(1.f);right.fill(1.f); // must be cleared, not fake audio + float* outputs[]={left.data(),right.data()}; + assert(mixer.process(nullptr,0,outputs,2,480,1.f,true, + nullptr,nullptr,false,nullptr,nullptr,true)); + for(const auto s:left)assert(s==0.f); + for(const auto s:right)assert(s==0.f); +} + static void nativeDeviceRecovery() { FixtureDevice device; auto saved=makeSession(); @@ -366,6 +398,7 @@ int main(){ malformed.getProperty("binding",{}).getDynamicObject()->setProperty("inputMask","3"); assert(!Codec::decode(juce::JSON::toString(malformed,false),decoded)); } + outputOnlyNativeStartup(); warmVst3Discovery(); nativeDeviceRecovery(); auto d=makeSession(); From 178631b5b72750ae7a01f18487385c5ce18daaaa Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 17:15:18 +0700 Subject: [PATCH 04/26] test(device): update DIRECT fingerprint contract for genuine output-only playback --- tests/direct_restore_recovery_contract_test.mjs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/direct_restore_recovery_contract_test.mjs b/tests/direct_restore_recovery_contract_test.mjs index f9e1ec018..8101526d3 100644 --- a/tests/direct_restore_recovery_contract_test.mjs +++ b/tests/direct_restore_recovery_contract_test.mjs @@ -87,8 +87,10 @@ test('ASIO/WASAPI DIRECT authorizes the exact active input/output channel map',( } assert.ok(engine.includes('EXACT_ACTIVE_INPUT_AND_OUTPUT_CHANNEL_BITMASKS')); assert.ok(fence.includes('UNEXPECTED_DIRECT_BACKEND_DEVICE_OR_CHANNEL_MASK')); - assert.ok(fence.includes('!validMask(inputMask)')); - assert.ok(fence.includes('!validMask(outputMask)')); + // A real output-only playback session has the canonical zero input mask. + // The exact device fingerprint must still reject absent physical outputs. + assert.ok(fence.includes('!validMask(inputMask,true)')); + assert.ok(fence.includes('!validMask(outputMask,false)')); const callback=engine.slice(engine.indexOf('void audioDeviceIOCallbackWithContext')); assert.ok(callback.indexOf('!directFence_.permitted()')>=0); assert.ok(callback.indexOf('!directFence_.permitted()') Date: Mon, 9 Nov 2026 17:36:32 +0700 Subject: [PATCH 05/26] fix(P0): make Audio I/O output-only selection work end-to-end Allow explicit NONE capture for separate Windows audio endpoints and empty enabled capture masks for genuine ASIO devices, preserving exact verified stereo outputs, user choice, DIRECT fencing and readback. Match native bridge device Apply/ACK to accepted zero-capture graph; add regression contract. --- src/Main.cpp | 26 +++++++++++++++------- tests/approved_native_m2_contract.test.cjs | 12 ++++++++++ web/approved-native-bridge.js | 20 +++++++++++------ 3 files changed, 43 insertions(+), 15 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 4e6bed06c..09f77424a 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1359,9 +1359,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto typeName=config.getProperty("backend",{}).toString(); const auto capture=config.getProperty("captureDevice",{}).toString(); const auto playback=config.getProperty("playbackDevice",{}).toString(); - if(typeName.isEmpty()||capture.isEmpty()||playback.isEmpty()|| + if(typeName.isEmpty()||playback.isEmpty()|| typeName.length()>160||capture.length()>250||playback.length()>250) - return send(false,"REJECTED","Choose actual capture and playback devices"); + return send(false,"REJECTED","Choose an actual playback device"); auto& manager=engine_.devices(); juce::AudioIODeviceType* selectedType=nullptr; for(auto* type:manager.getAvailableDeviceTypes()) @@ -1370,8 +1370,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Do not let JS submit arbitrary names or combine unmatched ASIO devices. const auto namesIn=selectedType->getDeviceNames(true); const auto namesOut=selectedType->getDeviceNames(false); - if(!namesIn.contains(capture)||!namesOut.contains(playback)|| - (!selectedType->hasSeparateInputsAndOutputs()&&capture!=playback)) + // A separate-input/output backend can legitimately open a render + // endpoint WITHOUT capture hardware. Empty capture is a deliberate + // operator choice, never an inferred name or a fake input port. + // ASIO/non-separate drivers retain exact duplex device identity; + // they may still expose zero enabled capture *pins*. + const bool separate=selectedType->hasSeparateInputsAndOutputs(); + const bool outputOnly=separate&&capture.isEmpty(); + if((!outputOnly&&!namesIn.contains(capture))||!namesOut.contains(playback)|| + (!separate&&capture!=playback)) return send(false,"REJECTED","Device names or duplex pairing are not reported by JUCE"); auto sample=config.getProperty("sampleRate",{}), period=config.getProperty("bufferSize",{}); if(!(sample.isInt()||sample.isDouble()||sample.isInt64())|| @@ -1449,14 +1456,18 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr }; juce::BigInteger inMask,outMask; if(!parsePins(pinInput,inCount,inMask)||!parsePins(pinOutput,outCount,outMask)|| - inMask.countNumberOfSetBits()<1||outMask.countNumberOfSetBits()<2) - return send(false,"REJECTED","Choose >=1 verified capture and >=2 playback pins"); + (outputOnly&&!inMask.isZero())||outMask.countNumberOfSetBits()<2) + return send(false,"REJECTED","Select real input pins (or none) and >=2 verified playback pins"); candidate.useDefaultInputChannels=false; candidate.useDefaultOutputChannels=false; candidate.inputChannels=inMask; candidate.outputChannels=outMask; }else { - candidate.useDefaultInputChannels=true; + // The requested 0-IN option must not reopen a microphone merely + // because JUCE defaults to enabling available capture channels. + // Output pin selection still requires actual driver readback. + candidate.useDefaultInputChannels=!outputOnly; + if(outputOnly)candidate.inputChannels.clear(); candidate.useDefaultOutputChannels=true; } auto* active=manager.getCurrentAudioDevice(); @@ -1511,7 +1522,6 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr (!candidate.useDefaultOutputChannels&&actual.outputChannels!=candidate.outputChannels)|| opened->getActiveInputChannels()!=actual.inputChannels|| opened->getActiveOutputChannels()!=actual.outputChannels|| - opened->getActiveInputChannels().countNumberOfSetBits()<1|| opened->getActiveOutputChannels().countNumberOfSetBits()<2|| std::abs(opened->getCurrentSampleRate()-actual.sampleRate)>1.0|| opened->getCurrentBufferSizeSamples()!=actual.bufferSize)) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 6568af4c0..6eb2bab28 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1248,6 +1248,18 @@ test("P0 startup banner never demands legacy Patch CH1 / Arm wizard",()=>{ assert.match(bridge,/const preparedFirstSound=session\?\.authority==="NONE"/); assert.match(bridge,/const deviceReady=\(\)=>/); }); +test("P0 output-only Audio I/O is a real native configuration, never blocked by missing capture",()=>{ + const cpp=read("src/Main.cpp"),bridge=read("web/approved-native-bridge.js"); + assert.match(cpp,/const bool outputOnly=separate&&capture\.isEmpty\(\)/); + assert.match(cpp,/candidate\.useDefaultInputChannels=!outputOnly/); + assert.match(cpp,/if\(outputOnly\)candidate\.inputChannels\.clear\(\)/); + assert.match(cpp,/\(outputOnly&&!inMask\.isZero\(\)\)/); + assert.doesNotMatch(cpp,/opened->getActiveInputChannels\(\)\.countNumberOfSetBits\(\)<1/); + assert.match(bridge,/No hardware input \(Player \/ FX\)/); + assert.match(bridge,/t\?\.separate\?\["",\.\.\.\(t\.inputs\|\|\[\]\)\]/); + assert.doesNotMatch(bridge,/ack\.active\.enabledInputs\.length>0/); + assert.match(bridge,/FX\/WIRE available/); +}); test("P0 FIRST SOUND G0 offers verified input and leaves automatic MAIN to native",()=>{ const vm=require("node:vm"),sent=[],listeners=new Map(),renderedChoices=[]; let win; diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 41f8f3129..e94d52274 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1675,7 +1675,8 @@ devicePanel.querySelector("[data-audio-apply]").onclick=()=>{ if(deviceBusy||!deviceChoice||!deviceInventory?.active)return; const draft=deviceChoice,active=deviceInventory.active; - if(!draft.backend||!draft.capture||!draft.playback)return; + const separate=deviceInventory.types?.find(x=>x.name===draft.backend)?.separate===true; + if(!draft.backend||!draft.playback||(!separate&&!draft.capture))return; sendDeviceApply(); }; devicePanel.querySelector("[data-audio-remap]").onclick=()=>{ @@ -1696,7 +1697,10 @@ if(!el)return; el.replaceChildren(...values.map(value=>{ const option=document.createElement("option"); - option.value=value;option.textContent=value;return option; + option.value=value; + option.textContent=name==="capture"&&value==="" + ?"No hardware input (Player / FX)":value; + return option; })); if(values.includes(current))el.value=current; el.disabled=deviceBusy; @@ -1707,7 +1711,9 @@ if(!deviceChoice){ const backendName=active.backend||types[0]?.name||""; const selected=types.find(x=>x.name===backendName); - const capture=active.captureDevice||selected?.inputs?.[0]||""; + // Preserve an already-open output-only endpoint on repeated dialog opens. + const capture=active.open?String(active.captureDevice||""): + active.captureDevice||selected?.inputs?.[0]||""; deviceChoice={backend:backendName,capture, playback:active.playbackDevice|| (selected?.separate?selected?.outputs?.[0]:capture)||"", @@ -1720,7 +1726,8 @@ if(asio4allHint)asio4allHint.hidden=!( deviceChoice.backend==="ASIO"&&/asio4all/i.test(deviceChoice.capture)); fillAudioSelect("backend",types.map(x=>x.name),deviceChoice.backend); - fillAudioSelect("capture",t?.inputs||[],deviceChoice.capture); + fillAudioSelect("capture", + t?.separate?["",...(t.inputs||[])]:t?.inputs||[],deviceChoice.capture); fillAudioSelect("playback",t?.outputs||[],deviceChoice.playback); const same=active.open&&active.backend===deviceChoice.backend&& active.captureDevice===deviceChoice.capture&& @@ -1766,7 +1773,7 @@ "ACTIVE · "+active.backend+" · "+active.rate+" Hz / "+active.buffer+" samples": "No verified audio device. Select a supported input and output."); devicePanel.querySelector("[data-audio-apply]").disabled=deviceBusy|| - !deviceChoice.backend||!deviceChoice.capture|| + !deviceChoice.backend||(!t?.separate&&!deviceChoice.capture)|| !deviceChoice.playback; const remap=devicePanel.querySelector("[data-audio-remap]"); remap.hidden=!same || offeredPinRemap!==active.deviceGeneration; @@ -1812,13 +1819,12 @@ const accepted=ack.ok===true&&["ACCEPTED_LIVE","ACCEPTED_MUTED"].includes(ack.state) && ack.active?.open===true && ack.active?.authorized===true && Array.isArray(ack.active.enabledInputs) && - ack.active.enabledInputs.length>0 && Array.isArray(ack.active.enabledOutputs) && ack.active.enabledOutputs.length>=2; const outputReady=ack.outputMuted===false; deviceResult=accepted? (outputReady?"Mixer ready · Output live": - ack.mixerBound?"Mixer ready · Verify channel IN and output":"Audio device ready · choose a channel IN"): + ack.mixerBound?"Mixer ready · FX/WIRE available":"Audio device ready · no hardware input required"): ack.state==="NEEDS_REMAP"? "NEEDS REMAP · "+ack.error: "Device rejected · "+(ack.error||"native hardware readback failed"); From b0f485b9ed66788bf36379d3eed7b061b0ff8597 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 17:39:24 +0700 Subject: [PATCH 06/26] test(P0): Chromium verify output-only Audio I/O, Apply/ACK and no auto-mic reopen --- tests/approved_native_cold_start_smoke.py | 38 +++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index d4053e2c0..3d9764280 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -41,6 +41,44 @@ def main(): addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") page.goto((out/'index.html').as_uri()) page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__?.enabled') + # Output-only playback is a REAL Audio I/O choice, not a hidden + # capture prerequisite. Verify native intent/ACK on the approved + # assembled Windows GUI at every supported viewport. + page.locator('.command-bar [data-native-io]').click() + io_inventory={ + 'types':[{'name':'Windows Audio','separate':True, + 'inputs':['Studio Mic'],'outputs':['Speakers']}], + 'active':{'backend':'Windows Audio','captureDevice':'Studio Mic', + 'playbackDevice':'Speakers','open':True, + 'authorized':True,'deviceGeneration':23, + 'inputNames':['Mic 1'],'outputNames':['L','R'], + 'enabledInputs':[0],'enabledOutputs':[0,1], + 'rate':48000,'buffer':480, + 'rates':[48000],'buffers':[480]}} + emit(page,'arMixAudioDeviceInventory',io_inventory) + capture_select=page.locator('.armix-audio-dialog [data-audio-field="capture"]') + capture_select.select_option(value='') + assert capture_select.input_value()=='' + assert page.locator('.armix-audio-dialog [data-audio-apply]').is_enabled() + page.locator('.armix-audio-dialog [data-audio-apply]').click() + request=page.evaluate("""()=>window.__events.filter(e=> + e.payload?.action==='audioDeviceApply').at(-1)?.payload""") + assert request and request['config']['captureDevice']=='' + assert request['config']['playbackDevice']=='Speakers' + assert request['config']['enabledInputs']==[] + assert request['config']['enabledOutputs']==[] + out_active={**io_inventory['active'],'captureDevice':'', + 'inputNames':[],'enabledInputs':[]} + emit(page,'arMixAudioDeviceApplyAck',{ + 'requestId':request['requestId'],'ok':True, + 'state':'ACCEPTED_MUTED','active':out_active, + 'outputMuted':True,'mixerBound':True}) + assert page.locator('.armix-audio-shade').is_hidden() + page.locator('.command-bar [data-native-io]').click() + io_inventory['active']=out_active + emit(page,'arMixAudioDeviceInventory',io_inventory) + assert capture_select.input_value()=='' # reopening does not auto-patch a mic + page.locator('.armix-audio-dialog [data-audio-close]').click() g0=json.loads((ROOT/'integration/console-v6/fixtures.json').read_text())['g0'] g0['mixerSession']={'authority':'NONE','deviceEpoch':g0['device']['epoch'],'channels':[]} g0['legacyM4']={'active':True,'routeAccepted':False,'routingRevision':'1'} From ce326e1797abf3f89b4b9bb4e30bdb84a8443c91 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 17:46:05 +0700 Subject: [PATCH 07/26] fix(recovery): preserve genuine zero-capture WASAPI mixer across verified device restore Reject missing/stereo-incomplete playback but do not require a microphone when restoring the exact saved output-only endpoint. Retain DIRECT fingerprint and fail-silent guards. Repair advanced setup guidance and add regression test. --- src/LiveAudioEngine.h | 7 +++++-- src/Main.cpp | 4 ++-- tests/direct_restore_recovery_contract_test.mjs | 13 +++++++++++++ 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index c6f267d56..4bc90b441 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -2545,10 +2545,13 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const juce::AudioDeviceManager::AudioDeviceSetup& expected) { const auto* active = deviceManager_.getCurrentAudioDevice(); + // A previously verified OUTPUT-ONLY mixer must be recoverable with + // the same zero-capture identity. Only the physical stereo output is + // compulsory; resumeVerifiedDirectRoute() separately rechecks exact + // backend/device/input/output masks before PCM can be armed. if (active == nullptr || deviceManager_.getCurrentAudioDeviceType() != "Windows Audio" || - active->getActiveInputChannels().isZero() || - active->getActiveOutputChannels().isZero()) return false; + active->getActiveOutputChannels().countNumberOfSetBits()<2) return false; juce::AudioDeviceManager::AudioDeviceSetup current; deviceManager_.getAudioDeviceSetup (current); return current.inputDeviceName == expected.inputDeviceName diff --git a/src/Main.cpp b/src/Main.cpp index 09f77424a..389bd7a3e 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1630,11 +1630,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr else { safe->diagnostics_.record ("DIRECT_ROUTE_REJECTED", - "No valid full-duplex device; audio remains gated"); + "No verified stereo playback device; audio remains gated"); safe->emitNotice ( safe->engine_.hasRetainedUnboundMixer() ? "Mixer and plugin state retained. Device binding changed; output stays muted until a verified full-session rebind." - : "Choose a working capture and render device. Audio remains muted.", true); + : "Choose a working stereo output in Audio I/O. Input hardware is optional.", true); safe->emitApprovedNativeSnapshot(); } }); diff --git a/tests/direct_restore_recovery_contract_test.mjs b/tests/direct_restore_recovery_contract_test.mjs index 8101526d3..f91ce6bc8 100644 --- a/tests/direct_restore_recovery_contract_test.mjs +++ b/tests/direct_restore_recovery_contract_test.mjs @@ -35,6 +35,19 @@ test('actual device recoveries occur on message thread, not inside audio callbac assert.match(gate,/generation == generation_/); assert.match(gate,/State::exhausted/); }); +test('output-only SAME-device WASAPI recovery never invents or requires microphone pins',()=>{ + const begin=engine.indexOf('bool verifyRestoredDirectDevice ('); + const end=engine.indexOf('void detach()',begin); + assert.ok(begin>0&&end>begin); + const restore=engine.slice(begin,end); + assert.ok(restore.includes('active->getActiveOutputChannels().countNumberOfSetBits()<2')); + assert.ok(!restore.includes('active->getActiveInputChannels().isZero()'), + 'zero actual capture pins must not make a valid output-only mixer unrecoverable'); + assert.ok(restore.includes('current.inputDeviceName == expected.inputDeviceName')); + assert.ok(restore.includes('current.outputDeviceName == expected.outputDeviceName')); + assert.match(engine,/resumeVerifiedDirectRoute\(\)/); + assert.match(main,/No verified stereo playback device; audio remains gated/); +}); test('restore retry is bounded and disabled on success, explicit direct and setup paths',()=>{ assert.match(main,/directRestore_\.failed \(snapshot\.generation, now\)/); assert.match(main,/directRestore_\.recovered \(snapshot\.generation\)/); From 94885d7042d219aa76b2b37ab5dc6901afbc544e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 17:48:02 +0700 Subject: [PATCH 08/26] fix(FX): never gate compiled-in EQ, Compressor or Harmony on external VST3 scanner Keep verified third-party catalog and Show/backup/handoff gates, but make native built-in FX available on initial SOURCE NONE workspace while background plugin scan is busy. Add guard contract regression. --- src/Main.cpp | 9 +++++++-- tests/approved_native_m2_contract.test.cjs | 11 +++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 389bd7a3e..d306d13c8 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1082,9 +1082,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr armix::builtin_fx::ChannelCompressorProcessor::catalogIdentity; const bool builtInHarmony=catalogId== armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity; - const auto* plugin=(builtInEq||builtInComp||builtInHarmony)?nullptr:catalog_.find(catalogId); + // Built-in DSP is compiled into the native host. Its admit + // path must remain usable even while third-party VST3 metadata + // discovery blocks or scans in the background. External + // plugins still require a fully verified, idle catalog. + const bool externalCatalog=!builtInEq&&!builtInComp&&!builtInHarmony; + const auto* plugin=externalCatalog?catalog_.find(catalogId):nullptr; std::uint64_t ep=0,rev=0,roster=0,target=0; - if((!builtInEq&&!builtInComp&&!builtInHarmony&&!plugin)||catalog_.busy()||nativeShowBusy_|| + if((externalCatalog&&(!plugin||catalog_.busy()))||nativeShowBusy_|| studioBackupBusy_||engine_.isGraphSwitchPending()) { nativeError="NATIVE_VST3_CATALOG_OR_HOST_BUSY"; } else if(!armix::console::approvedNativeId( diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 6eb2bab28..2813fdf0d 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1248,6 +1248,17 @@ test("P0 startup banner never demands legacy Patch CH1 / Arm wizard",()=>{ assert.match(bridge,/const preparedFirstSound=session\?\.authority==="NONE"/); assert.match(bridge,/const deviceReady=\(\)=>/); }); +test("P0 built-in EQ/Compressor/Harmony load independent of slow external VST3 catalog scan",()=>{ + const cpp=read("src/Main.cpp"); + const gate=cpp.slice(cpp.indexOf('const bool builtInEq=catalogId=='), + cpp.indexOf('const auto result=builtInEq?',cpp.indexOf('const bool builtInEq=catalogId=='))); + assert.ok(gate.includes('const bool externalCatalog=!builtInEq&&!builtInComp&&!builtInHarmony')); + assert.ok(gate.includes('externalCatalog&&(!plugin||catalog_.busy())')); + assert.ok(!gate.includes('||catalog_.busy()||nativeShowBusy_'), + 'third-party metadata discovery must not disable compiled-in FX'); + assert.ok(gate.includes('nativeShowBusy_')&&gate.includes('studioBackupBusy_'), + 'native structural session/backup safety interlocks remain active'); +}); test("P0 output-only Audio I/O is a real native configuration, never blocked by missing capture",()=>{ const cpp=read("src/Main.cpp"),bridge=read("web/approved-native-bridge.js"); assert.match(cpp,/const bool outputOnly=separate&&capture\.isEmpty\(\)/); From 9b128a5da66c3c4963efb475bbe8d72b8b019d39 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 17:54:04 +0700 Subject: [PATCH 09/26] fix(FX picker): show genuine native EQ, Compressor and Harmony before VST3 discovery Built-in JUCE processors are already present in the executable: expose them in the approved Windows picker on first paint and after every external catalog refresh. Label their real native format, without fake vendor metadata or browser DSP. --- scripts/build_approved_native_gui.py | 4 ++-- tests/approved_native_m2_contract.test.cjs | 12 ++++++++++++ web/approved-native-bridge.js | 22 +++++++++++++++++----- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 0c7d1bcdb..c3e8e6afa 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -228,10 +228,10 @@ def accepted_pages_html() -> str: " setNativeCatalog(rows){\n" " pluginCatalog=rows.filter(x=>x&&typeof x.id==='string'&&typeof x.name==='string').map(x=>({\n" " id:x.id,name:x.name,vendor:x.vendor||'Unknown',category:x.category||'Utility',\n" - " format:'VST3',status:'ready',latencySamples:null,\n" + " format:x.format==='Native'?'Native':'VST3',status:'ready',latencySamples:null,\n" " favorite:!!x.favorite,hidden:false}));\n" " const label=document.querySelector('.plugin-disclaimer');\n" - " if(label)label.textContent='NATIVE JUCE VST3 · only verified scanned catalog entries are insertable';\n" + " if(label)label.textContent='Native EQ/Compressor/Harmony ready · external VST3 require verified scan';\n" " renderPluginCatalog();renderFastPicker();return pluginCatalog.length;\n" " },\n" " closeNativePicker(){setFastPicker(false);},\n" diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 2813fdf0d..f3741e58f 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1248,6 +1248,18 @@ test("P0 startup banner never demands legacy Patch CH1 / Arm wizard",()=>{ assert.match(bridge,/const preparedFirstSound=session\?\.authority==="NONE"/); assert.match(bridge,/const deviceReady=\(\)=>/); }); +test("P0 native built-in FX appear before vendor scan and remain after catalog refresh",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const builder=read("scripts/build_approved_native_gui.py"); + for(const id of ["armix.builtin.channel-eq.v1", + "armix.builtin.channel-compressor.v1", + "armix.builtin.arson-harmony.v1"]) + assert.ok(bridge.includes('id:"'+id+'"')); + assert.ok(bridge.includes('[...nativeBuiltins,...nativeCatalog.values()]')); + assert.ok(bridge.includes('presentFxCatalog(); // compiled native FX')); + assert.ok(builder.includes("x.format==='Native'?'Native':'VST3'")); + assert.ok(!bridge.includes('scope?.setNativeCatalog?.([])')); +}); test("P0 built-in EQ/Compressor/Harmony load independent of slow external VST3 catalog scan",()=>{ const cpp=read("src/Main.cpp"); const gate=cpp.slice(cpp.indexOf('const bool builtInEq=catalogId=='), diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index e94d52274..212cb90c7 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -983,6 +983,18 @@ return true; } let pendingFxInsert=null,fxRequestSerial=0,nativeCatalog=new Map(); + // Native JUCE processors: these are real compiled DSP, not demo effects, + // scanned VST binaries, a JS renderer or placeholder library entries. + const nativeBuiltins=Object.freeze([ + Object.freeze({id:"armix.builtin.channel-eq.v1",name:"Parametric EQ", + vendor:"ArSonMix",category:"EQ",format:"Native",source:"builtin"}), + Object.freeze({id:"armix.builtin.channel-compressor.v1",name:"Compressor", + vendor:"ArSonMix",category:"Dynamics",format:"Native",source:"builtin"}), + Object.freeze({id:"armix.builtin.arson-harmony.v1",name:"ArSon Harmony", + vendor:"ArSonMix",category:"Utility",format:"Native",source:"builtin"}) + ]); + const presentFxCatalog=()=>scope?.setNativeCatalog?.( + [...nativeBuiltins,...nativeCatalog.values()]); let nativeFxDiscoveryRequested=false,nativeFxCatalogScanning=false; // Lazy USER-triggered discovery: the first Add FX opens immediately and // starts real JUCE VST3 scanning on its dedicated non-audio worker. Never @@ -2503,7 +2515,7 @@ typeof actual?.instanceId==="string"&&actual.instanceId.length){ status("CH "+(p.channel+1)+" FX loaded · verified native VST3"); scope?.closeNativePicker?.(); - scope?.setNativeCatalog?.([...nativeCatalog.values()]); + presentFxCatalog(); controller.subscribe(); }else { const reason=ack?.error||"native FX instance missing from accepted PCM"; @@ -2518,12 +2530,12 @@ nativeCatalog=new Map(catalog.items.filter(p=> p&&typeof p.id==="string"&&p.id.length>0&& typeof p.name==="string"&&p.name.length>0).map(p=>[p.id,p])); - scope?.setNativeCatalog?.([...nativeCatalog.values()]); + presentFxCatalog(); if(nativeFxDiscoveryRequested&&!nativeFxCatalogScanning&&nativeCatalog.size===0) - status("No installed VST3 discovered · use Import VST3 in Plugin Manager"); + status("Built-in FX ready · import VST3 to add more effects"); if(hardware?.raw?.legacyM4)paintM4FxInstances(hardware.raw.legacyM4); const count=document.getElementById("pluginCount"); - if(count)count.title="Verified JUCE native VST3 catalog"; + if(count)count.title="Native built-in DSP + verified VST3 catalog"; }); backend.addEventListener("arMixScanProgress",progress=>{ const statusEl=document.getElementById("pluginScanStatus"); @@ -3154,7 +3166,7 @@ const ready=()=>{ presentNativeOnlyTools(); installFirstSoundMenu(); - scope?.setNativeCatalog?.([]); // no synthetic/demo VST3 in Windows host + presentFxCatalog(); // compiled native FX, never demo or vendor placeholders updateHardwarePanel(null); stopDemo(); status("NATIVE: subscribed · waiting for true device and accepted ChannelId graph"); From 0389e7f3e5d5bef464c7ebcf63593603b257f51e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 17:54:31 +0700 Subject: [PATCH 10/26] test(UI): ensure built-in native FX are already in cold-start picker before VST3 scan --- tests/approved_native_cold_start_smoke.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index 3d9764280..fa4c157d2 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -41,6 +41,13 @@ def main(): addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") page.goto((out/'index.html').as_uri()) page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__?.enabled') + # Built-in JUCE DSP must be discoverable before ANY third-party + # VST3 catalog response. The native host never inserts demo FX. + for native_id in ('armix.builtin.channel-eq.v1', + 'armix.builtin.channel-compressor.v1', + 'armix.builtin.arson-harmony.v1'): + assert page.locator('#fastResults [data-fast-id="'+native_id+'"]').count()==1, ( + 'Compiled native FX missing from cold-start picker: '+native_id) # Output-only playback is a REAL Audio I/O choice, not a hidden # capture prerequisite. Verify native intent/ACK on the approved # assembled Windows GUI at every supported viewport. From df15d63b8b63ae8dfdd417e61b963aae0ebbbd2b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 17:58:06 +0700 Subject: [PATCH 11/26] test(P0): reconcile native FX catalog contract with built-in processors available before VST3 scan --- tests/approved_native_m2_contract.test.cjs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index f3741e58f..2463bda6e 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -381,7 +381,10 @@ test("P0 first Add FX discovers real local VST3 lazily without an audio-thread s assert.match(bridge,/discoverFxOnFirstPickerOpen\(\);[\s\S]*?scope\?\.openFastPicker/); assert.match(native,/action == "scanVst3"[\s\S]*?catalog_\.scanDefaults\(\)/); assert.match(catalog,/struct Scanner final : juce::Thread/); - assert.match(bridge,/scope\?\.setNativeCatalog\?\.\(\[\.\.\.nativeCatalog\.values\(\)\]\)/); + // The approved picker publishes real compiled-in FX independently of + // external scanner state; the verified VST3 library follows those entries. + assert.match(bridge,/const presentFxCatalog=\(\)=>scope\?\.setNativeCatalog\?\.\(/); + assert.ok(bridge.includes('[...nativeBuiltins,...nativeCatalog.values()]')); // Neither startup nor audio callback can trigger a surprise system scan. assert.doesNotMatch(bridge.slice(0,bridge.indexOf("function discoverFxOnFirstPickerOpen")), /action:"scanVst3"/); @@ -563,7 +566,8 @@ test("P0 WIRE-to-MAIN and channel OUT use one acknowledged native transaction",( assert.match(native,/engine_\.repatchDryRoutingLabChannel\(channel,/); assert.match(bridge,/scope\?\.closeNativePicker\?\.\(\)/); assert.match(builder,/closeNativePicker\(\)\{setFastPicker\(false\);\}/); - assert.match(builder,/NATIVE JUCE VST3/); + assert.match(builder,/Native EQ\/Compressor\/Harmony ready/); + assert.match(builder,/external VST3 require verified scan/); assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); }); test("P0 typed mono-stereo, PAN detent, fader geometry & FX failure diagnostics",()=>{ From 6f1338efb2f20692ecbe57a499efe32a609ee5f7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 18:04:20 +0700 Subject: [PATCH 12/26] fix(P0): restore durable .smix over pristine native SOURCE NONE starter on cold boot The always-on ChannelId graph is real PCM, but on fresh startup must not make the saved Show unrecoverable. Permit replaceActive only for unmodified silent starter on exact verified device; do not overwrite authored FX/WIRE/track edits. Prove native 0-input saved Show restoration and regression safety. --- src/LiveAudioEngine.h | 5 +++++ src/LiveDryRoutingLab.h | 12 +++++++++++ src/Main.cpp | 17 +++++++++++++--- tests/approved_native_m2_contract.test.cjs | 12 +++++++++++ tests/native_mixer_session_store_test.cpp | 23 ++++++++++++++++++++++ 5 files changed, 66 insertions(+), 3 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 4bc90b441..a7e892f31 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1592,6 +1592,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return {}; } + // Cold-start restore ONLY: the installed native SOURCE NONE starter has + // never been edited, so the durable saved Show can safely take ownership. + bool hasPristineStartupMixer() const noexcept { + return dryRoutingLab_.canReplacePristineStartupMixer(); + } std::uint64_t dryRoutingLabEpoch() const noexcept {return dryRoutingLab_.epoch();} std::uint64_t dryRoutingLabRevision() const noexcept {return dryRoutingLab_.revision();} std::uint64_t outputArmRevision() const noexcept {return dryRoutingLab_.controlRevision();} diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 49c77cd75..932554589 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2438,6 +2438,18 @@ class LiveDryRoutingLab final { return channelIdPhysicalPcmActive() && nativeStructureLive_ ?nativeAccepted_.pcmRevision:revision(); } + // The first accepted SOURCE NONE ChannelId graph is a disposable + // bootstrap topology, not an authored Show. A persisted .smix may replace + // it once on cold start; any accepted FX, control, WIRE, BUS or source + // mutation immediately makes that replacement unsafe. + // CONTROL THREAD ONLY: hasAuthoredMixerContent traverses roster/FX. + bool canReplacePristineStartupMixer() const noexcept { + return channelIdPhysicalPcmActive() && sourceTemplate_.isObject() && + !acceptedRoute_.isObject() && !nativeStructureLive_ && + !nativeControlDirty_ && nativeAccepted_.fxOwners && + nativeAccepted_.graph.request.sources.empty() && + !hasAuthoredMixerContent(); + } bool hasVerifiedNativeSources() const noexcept { return channelIdPhysicalPcmActive() && !nativeAccepted_.graph.request.sources.empty(); } diff --git a/src/Main.cpp b/src/Main.cpp index d306d13c8..9e407759f 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -2217,11 +2217,22 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr !usedPrevious && !retained && doc.resumeMain.value_or(true); const auto live=engine_.status().getProperty("dryRoutingLab",{}); - if(static_cast(live.getProperty("nativeChannelIdPcmActive",false))) { + const bool nativeAlreadyActive=static_cast( + live.getProperty("nativeChannelIdPcmActive",false)); + // A fresh silent ChannelId starter is now admitted before the saved + // Show is inspected. Only THAT unmodified bootstrap may be replaced, + // and only by this automatic cold-start restore. User-authored FX, + // WIRE, BUS and fader edits must never be overwritten by late scan. + const bool replacePristineStartup=nativeAlreadyActive && + startupOnSavedDevice && !retained && !usedPrevious && + bindingMode==armix::session::MixerDeviceBindingPolicy::Mode::exact && + engine_.hasPristineStartupMixer(); + if(nativeAlreadyActive && !replacePristineStartup) { mixerSessionStatus_="LIVE_MIXER_UNCHANGED"; - return "Live native mixer already active; refusing to replace it"; + return "Live native mixer already edited; refusing to replace it"; } - error=engine_.restoreNativeMixerSession(std::move(doc),states,false,nullptr,bindingMode); + error=engine_.restoreNativeMixerSession(std::move(doc),states, + replacePristineStartup,nullptr,bindingMode); if(error.isNotEmpty()) { mixerSessionStatus_=error.contains("NEEDS_REMAP") ?"NEEDS_REMAP":"RESTORE_REJECTED"; diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 2463bda6e..57ec4c39d 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1242,6 +1242,18 @@ test("P0 native FX rack and per-slot readback update mounted strip without repla assert.equal(paints,2,"an actual VST instance identity change MUST re-project"); }); +test("P0 automatic cold-start Show replaces only pristine SOURCE NONE ChannelId",()=>{ + const main=read('src/Main.cpp'); + const engine=read('src/LiveAudioEngine.h'); + const route=read('src/LiveDryRoutingLab.h'); + assert.match(main,/startupOnSavedDevice && !retained && !usedPrevious/); + assert.match(main,/engine_\.hasPristineStartupMixer\(\)/); + assert.match(main,/restoreNativeMixerSession\(std::move\(doc\),states,\s*replacePristineStartup/); + assert.match(engine,/dryRoutingLab_\.canReplacePristineStartupMixer\(\)/); + assert.match(route,/bool canReplacePristineStartupMixer\(\) const noexcept/); + assert.match(route,/!nativeControlDirty_ && nativeAccepted_\.fxOwners/); +}); + test("P0 startup banner never demands legacy Patch CH1 / Arm wizard",()=>{ const bridge=read("web/approved-native-bridge.js"); assert.match(bridge,/SELECT CHANNEL IN · NATIVE MONITOR AFTER ACK/); diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index 952281888..3dadd54e1 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -107,6 +107,28 @@ static void outputOnlyNativeStartup() { assert(!mixer.admitChannelIdFromAcceptedM4(0,480,true)); assert(mixer.admitChannelIdFromAcceptedM4(0,480,true,{},true)); assert(mixer.hasExplicitRoute() && !mixer.hasVerifiedNativeSources()); + assert(mixer.canReplacePristineStartupMixer()); + // Startup automatically restores an existing .smix on precisely the + // same verified device. The saved Show must win over a never-edited + // SOURCE NONE starter, without a second publisher/audio callback. + { + auto saved=makeSession(); + saved.binding={"Windows Audio","","Verified WASAPI fixture","0","3",48000.,480}; + saved.request.physicalInputs=0; + saved.request.sources.clear(); + saved.request.maxFrames=480; + saved.rackBypassed.clear(); + armix::device::JuceActivePortSnapshot pins; + armix::device::JuceActivePortSnapshot::Fault fault; + assert(armix::device::JuceActivePortSnapshot::capture(&playback,mixer.epoch(),pins,fault)); + std::shared_ptr bank; + const auto prepare=NativeMixerSessionFxRestore::prepare(saved,{},formats, + 48000.,480,pins.epoch,mixer.nativeGraphRevisionForRestore(),bank); + assert(prepare.isEmpty() && bank); + assert(mixer.restoreNativeMixerSession(saved,std::move(bank),pins,true,true).isEmpty()); + assert(!mixer.canReplacePristineStartupMixer()); // saved Show is now authored + assert(mixer.hasExplicitRoute() && !mixer.hasVerifiedNativeSources()); + } const auto native=mixer.nativeBusStatus(); assert(native.isObject()); const auto graph=static_cast( @@ -116,6 +138,7 @@ static void outputOnlyNativeStartup() { const auto add=mixer.createNativeInputChannel(mixer.epoch(),graph,roster, "No Microphone Track",ProcessingFormat::stereo,true); assert(add.accepted && !mixer.hasVerifiedNativeSources()); + assert(!mixer.canReplacePristineStartupMixer()); // edited graph can never be replaced std::array left{},right{}; left.fill(1.f);right.fill(1.f); // must be cleared, not fake audio float* outputs[]={left.data(),right.data()}; From 9f1b5b5ac5ba4144a1c3ea3b0e4f7357a3571035 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 18:05:29 +0700 Subject: [PATCH 13/26] fix(recovery): permit verified previous checkpoint to replace untouched cold-start graph --- src/Main.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Main.cpp b/src/Main.cpp index 9e407759f..c2332c784 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -2223,8 +2223,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Show is inspected. Only THAT unmodified bootstrap may be replaced, // and only by this automatic cold-start restore. User-authored FX, // WIRE, BUS and fader edits must never be overwritten by late scan. + // A verified PREVIOUS checkpoint is also eligible: the separate + // resume policy keeps MAIN muted after recovery from corrupt HEAD. const bool replacePristineStartup=nativeAlreadyActive && - startupOnSavedDevice && !retained && !usedPrevious && + startupOnSavedDevice && !retained && bindingMode==armix::session::MixerDeviceBindingPolicy::Mode::exact && engine_.hasPristineStartupMixer(); if(nativeAlreadyActive && !replacePristineStartup) { From 36a9bccb7c1c9e90c2133d5574953eaf36f7694d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 18:05:43 +0700 Subject: [PATCH 14/26] test(recovery): verified previous .smix can replace pristine starter while MAIN remains muted --- tests/approved_native_m2_contract.test.cjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 57ec4c39d..51f903a50 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1246,7 +1246,9 @@ test("P0 automatic cold-start Show replaces only pristine SOURCE NONE ChannelId" const main=read('src/Main.cpp'); const engine=read('src/LiveAudioEngine.h'); const route=read('src/LiveDryRoutingLab.h'); - assert.match(main,/startupOnSavedDevice && !retained && !usedPrevious/); + assert.match(main,/startupOnSavedDevice && !retained &&/); + assert.doesNotMatch(main,/startupOnSavedDevice && !retained && !usedPrevious/); + assert.match(main,/!usedPrevious && !retained/); // only normal auto-resume, not recovery admission assert.match(main,/engine_\.hasPristineStartupMixer\(\)/); assert.match(main,/restoreNativeMixerSession\(std::move\(doc\),states,\s*replacePristineStartup/); assert.match(engine,/dryRoutingLab_\.canReplacePristineStartupMixer\(\)/); From b9b64f7083a04bb748a4d9a4d8b5fc9b9d142c63 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 19:28:25 +0700 Subject: [PATCH 15/26] Fix native zero-capture admission and reduce Audio I/O reopen stalls Show only the accepted native roster, open the requested backend directly under the existing output fence, and let the shipped UI test the verified MAIN pins without replacing the mixer. Report post-gate JUCE buffer peaks and source SHA for field diagnosis. --- CMakeLists.txt | 11 ++- integration/ApprovedNativeRuntimeSnapshot.h | 4 +- scripts/build_approved_native_gui.py | 7 ++ src/DiagnosticTone.h | 3 +- src/LiveAudioEngine.h | 84 ++++++++++++++--- src/LiveDryRoutingLab.h | 11 +++ src/Main.cpp | 95 ++++++++++++++++---- tests/approved_native_cold_start_smoke.py | 19 ++-- tests/approved_native_v8_projection_test.cpp | 18 +++- tests/mixer_io_operator_contract_test.mjs | 9 +- web/approved-native-bridge.js | 23 +++-- 11 files changed, 241 insertions(+), 43 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1b039ae0c..72e05dd04 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -78,13 +78,22 @@ target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h engine/bu if(MSVC) target_compile_options(ARMixConsole PRIVATE "$<$:/utf-8>") endif() +# Stamp the build source in Copy Audio Report, including Windows field trials. +execute_process(COMMAND git rev-parse --verify HEAD + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + OUTPUT_VARIABLE ARMIX_BUILD_SOURCE_SHA OUTPUT_STRIP_TRAILING_WHITESPACE + RESULT_VARIABLE ARMIX_BUILD_SOURCE_STATUS ERROR_QUIET) +if(NOT ARMIX_BUILD_SOURCE_STATUS EQUAL 0 OR NOT ARMIX_BUILD_SOURCE_SHA MATCHES "^[0-9a-f]+$") + set(ARMIX_BUILD_SOURCE_SHA "unavailable") +endif() # One JUCE mixer/PCM host on all three desktops. Device backends are OS owned. target_compile_definitions(ARMixConsole PRIVATE JUCE_WEB_BROWSER=1 JUCE_USE_CURL=0 JUCE_PLUGINHOST_VST3=1 JUCE_APPLICATION_NAME_STRING="AR MIX Studio" - JUCE_APPLICATION_VERSION_STRING="0.5.0-p2") + JUCE_APPLICATION_VERSION_STRING="0.5.0-p2" + ARMIX_BUILD_SOURCE_SHA="${ARMIX_BUILD_SOURCE_SHA}") if(WIN32) # Windows retains its proven ASIO-first / WASAPI / static WebView2 distribution. # Never link Windows loader or sound APIs into macOS/Linux builds. diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index f5065a557..2b3207ea9 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -71,7 +71,7 @@ inline bool publishVerifiedFirstSoundState(juce::var& snapshot, static_cast(routeEpoch)>0 && static_cast(revision)>0 && juce::String(static_cast(routeEpoch))==epoch.toString() && - inputs.isArray() && !inputs.getArray()->isEmpty() && + inputs.isArray() && outputs.isArray() && outputs.getArray()->size()>=2 && nativeV8Number(device.getProperty("sampleRate",{}),rate) && nativeV8Number(device.getProperty("bufferFrames",{}),frames) && @@ -267,7 +267,7 @@ inline bool projectInstalledNativeChannelIdGraph( const auto frames=device.getProperty("bufferFrames",{}); double actualRate=0.,actualFrames=0.; if (!outputMask.isArray() || !inputMask.isArray() || - outputMask.getArray()->size()<2 || inputMask.getArray()->isEmpty() || + outputMask.getArray()->size()<2 || !nativeV8Number(rate,actualRate) || !nativeV8Number(frames,actualFrames) || actualRate<8000. || actualRate>384000. || diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index c3e8e6afa..877c27e96 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -58,6 +58,13 @@ def accepted_pages_html() -> str: # HTML at native build time. Every anchor must occur exactly once: no silent # breakage if Pages GUI source evolves. No extra layout or simulated PCM. NATIVE_EVENT_HOOKS = ( + # Do not expose the reference mixer while the native host is still starting. + ("", "\n"), + ("Mixer · Reference Session", "Mixer · Native Session"), + ("Interactive visual reference. Changes are local to this mockup.", "Preparing native mixer…"), + ("SIMULATED METERS · NO REAL AUDIO", "NATIVE AUDIO"), # The published /preview/ HTML and its V28 checkpoint are immutable. # Change ONLY the compiled native WebView's operator fader travel law. # The DSP gain remains exact dB -> 10^(dB/20), and the mapping is diff --git a/src/DiagnosticTone.h b/src/DiagnosticTone.h index fbedcc300..b7647649d 100644 --- a/src/DiagnosticTone.h +++ b/src/DiagnosticTone.h @@ -7,7 +7,7 @@ namespace armix::diagnostics { // Diagnostic routes are temporary, never persisted as the chosen user device. -enum class Route : int { normal = 0, dryThrough = 1, outputOnlyTone = 2, captureOnly = 3 }; +enum class Route : int { normal = 0, dryThrough = 1, outputOnlyTone = 2, captureOnly = 3, mainOutputTone = 4 }; inline constexpr const char* routeName (Route route) noexcept { @@ -17,6 +17,7 @@ inline constexpr const char* routeName (Route route) noexcept case Route::dryThrough: return "DRY_THROUGH"; case Route::outputOnlyTone: return "OUTPUT_ONLY_TONE"; case Route::captureOnly: return "CAPTURE_ONLY"; + case Route::mainOutputTone: return "MAIN_OUTPUT_TONE"; } return "INVALID"; } diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index a7e892f31..9c82f5ae3 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -580,9 +580,35 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // user setup is restored on exit; temporary routes must not be persisted. juce::String setDiagnosticRoute (armix::diagnostics::Route wanted) { - if (dryRoutingLab_.hasAuthoredMixerContent()) - return "An authored mixer cannot enter endpoint isolation until a safe session rebind is available"; using Route = armix::diagnostics::Route; + const auto currentRoute=diagnosticRoute_.load(std::memory_order_acquire); + if(wanted==Route::mainOutputTone) { + if(currentRoute==wanted)return {}; + if(currentRoute!=Route::normal || independent_.active()) + return "Return to NORMAL on the DIRECT device before testing MAIN."; + if(const auto error=liveOutputArmFault(false);error.isNotEmpty())return error; + if(secondaryOutput_.armed()) + return "Stop STREAM before testing the physical MAIN output."; + const auto pair=dryRoutingLab_.acceptedMainCallbackPair(); + if(pair[0]<0 || pair[1]<0 || pair[0]==pair[1]) + return "No verified MAIN output pair."; + mainTestEpoch_.store(dryRoutingLab_.epoch(),std::memory_order_relaxed); + mainTestPair_.store(static_cast(pair[0]) | + (static_cast(pair[1])<<16),std::memory_order_relaxed); + mainTestWasArmed_=isMonitorEnabled(); + mainTestPeak_.store(0.f,std::memory_order_relaxed); + diagnosticRoute_.store(wanted,std::memory_order_release); + setMonitorEnabled(true); // the operator explicitly requested this isolated tone + return {}; + } + if(currentRoute==Route::mainOutputTone) { + // A diagnostic ARM does not authorize microphone audio on exit. + if(!mainTestWasArmed_)setOutputMuted(true); + diagnosticRoute_.store(Route::normal,std::memory_order_release); + if(wanted==Route::normal)return {}; + } + if (dryRoutingLab_.hasAuthoredMixerContent()) + return "Use MAIN OUTPUT TONE to test the output without reopening the authored mixer."; if (handoff_.busy()) return "Finish the pending FX graph transition first"; if (independent_.active()) return "Disable independent clock mode before endpoint isolation tests"; if (wanted == diagnosticRoute_.load (std::memory_order_acquire) && @@ -2246,6 +2272,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("peak", outputPeak_.load()); o->setProperty ("peakLeft", outputPeakL_.load()); o->setProperty ("peakRight", outputPeakR_.load()); + o->setProperty ("driverBufferPeakLeft",driverBufferPeakL_.load(std::memory_order_relaxed)); + o->setProperty ("driverBufferPeakRight",driverBufferPeakR_.load(std::memory_order_relaxed)); + o->setProperty ("driverBufferProvenance","JUCE_CALLBACK_OUTPUT_POST_GATE"); + o->setProperty ("mainTestLastPeak",mainTestPeak_.load(std::memory_order_relaxed)); const auto loudness = masterLoudness_.read(); const bool measuredDirect = !dual && loudness.supported; o->setProperty ("masterAnalysisProvenance", @@ -2496,6 +2526,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback LiveDryRoutingLab dryRoutingLab_; std::atomic diagnosticRoute_ {armix::diagnostics::Route::normal}; std::atomic routeReconfiguring_ {false}; + std::atomic mainTestEpoch_{0}; + std::atomic mainTestPair_{0}; + bool mainTestWasArmed_=false; // control thread only std::optional savedLiveSetup_; // Indexed atomic bypass flags: instant RT-safe toggles, no graph detachment. // Temporary publication silence never changes operator MONITOR or MAIN MUTE. @@ -2508,6 +2541,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback std::atomic captureObservationBlocks_ {0}; // per native device epoch, even UNPATCHED armix::rt::CaptureBoundaryEvidence captureBoundary_; // callback-only PCM continuity std::atomic outputPeakL_ { 0.f }, outputPeakR_ { 0.f }; + std::atomic driverBufferPeakL_{0.f},driverBufferPeakR_{0.f},mainTestPeak_{0.f}; std::atomic callbackInputs_ { 0 }, callbackOutputs_ { 0 }; std::atomic callbackCount_ { 0 }; // Audio-thread-only timestamp and cheap atomically published counters. @@ -2634,6 +2668,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback inputPeak_.store (0.f); postFxPeak_.store (0.f); outputPeak_.store (0.f); + publishDriverBufferPeaks(0.f,0.f); } void audioDeviceStopped() override @@ -2650,6 +2685,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback captureBoundary_.reset(); // no stale pin peaks after disconnect inputPeak_.store (0.f); outputPeak_.store (0.f); + publishDriverBufferPeaks(0.f,0.f); } // ONE original CH1 rack processor for M4 compatibility and the native @@ -2740,6 +2776,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return fx; } + void publishDriverBufferPeaks(float left,float right) noexcept { + driverBufferPeakL_.store(left,std::memory_order_relaxed); + driverBufferPeakR_.store(right,std::memory_order_relaxed); + } + void audioDeviceIOCallbackWithContext ( const float* const* inputs, int inputChannels, float* const* outputs, int outputChannels, int samples, const juce::AudioIODeviceCallbackContext&) override @@ -2749,7 +2790,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // while the user is changing devices. Atomic gate only: no name hash, // allocations, OS calls or device restart on the realtime callback. // An independent WASAPI bridge has its own verified endpoint guard. - const auto activeDiagnosticRoute = diagnosticRoute_.load (std::memory_order_relaxed); + const auto activeDiagnosticRoute = diagnosticRoute_.load (std::memory_order_acquire); // DRY_THROUGH still routes a live microphone to the hardware output: // it MUST use the same DIRECT authorization fence as NORMAL. Only // genuinely isolated OUTPUT_ONLY_TONE / CAPTURE_ONLY tests may bypass @@ -2761,6 +2802,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { for (int c=0; c (samples), std::memory_order_relaxed); return; @@ -2805,6 +2847,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback outputPeak_.store(0.f, std::memory_order_relaxed); outputPeakL_.store(0.f, std::memory_order_relaxed); outputPeakR_.store(0.f, std::memory_order_relaxed); + publishDriverBufferPeaks(0.f,0.f); handoff_.endCycle(cycle); // ACK prepared FX graph even in silence return; } @@ -2915,7 +2958,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback peak=juce::jmax(peak,std::abs(out[i])); } if(c==0)movedPeakL=peak; - else movedPeakR=peak; + else if(c==1)movedPeakR=peak; } if(routedFxMove==1 && cycle.graph) { cycle.graph->orderPacked.store( @@ -2962,6 +3005,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback for(int channel=0;channel outputPair{{0,1}}; + if(route==armix::diagnostics::Route::mainOutputTone) { + const auto packed=mainTestPair_.load(std::memory_order_relaxed); + outputPair={{static_cast(packed&0xffffu),static_cast(packed>>16)}}; + if(!dryRoutingLab_.ready() || + mainTestEpoch_.load(std::memory_order_relaxed)!=dryRoutingLab_.epoch()) + outputPair={{-1,-1}}; + } + const auto testPair=armix::mixer::NativeOutputPairTap::select(outputs,outputChannels,outputPair); const bool captureTest = route == armix::diagnostics::Route::captureOnly; - if (toneTest && outputChannels > 0) + if (toneTest && testPair[0]) testOutputFrames_.fetch_add (static_cast (samples), std::memory_order_relaxed); if (captureTest && inputChannels > 0) testCaptureFrames_.fetch_add (static_cast (samples), std::memory_order_relaxed); @@ -3010,7 +3066,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { auto* left = scratch_.getWritePointer (0); auto* right = scratch_.getWritePointer (1); - const bool audible = enabled && !masterMute_.load (std::memory_order_relaxed); + const bool audible = testPair[0] && enabled && !masterMute_.load (std::memory_order_relaxed); for (int i = 0; i < frames; ++i) left[i] = right[i] = diagnosticTone_.next (audible); } @@ -3044,6 +3100,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const float* left = scratch_.getReadPointer (0); const float* right = scratch_.getReadPointer (1); float* dst = outputs[c] + offset; + if(toneTest && (!testPair[0] || (c!=outputPair[0] && c!=outputPair[1]))) { + juce::FloatVectorOperations::clear(dst,frames); + continue; + } const float fromL = mono ? monoL : (c == 0 ? matrix.ll : matrix.rl); const float fromR = mono ? monoR : (c == 0 ? matrix.lr : matrix.rr); float channelPeak = 0.f; @@ -3063,8 +3123,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback channelPeak = juce::jmax (channelPeak, std::abs (value)); } outPeak = juce::jmax (outPeak, channelPeak); - if (c == 0) outPeakL = juce::jmax (outPeakL, channelPeak); - if (c == 1) outPeakR = juce::jmax (outPeakR, channelPeak); + if (c == outputPair[0]) outPeakL = juce::jmax (outPeakL, channelPeak); + if (c == outputPair[1]) outPeakR = juce::jmax (outPeakR, channelPeak); } } if (!independent_.active()) @@ -3077,6 +3137,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } inputPeak_.store (juce::jmin (1.f, inPeak), std::memory_order_relaxed); postFxPeak_.store (juce::jmin (1.f, postFxPeak), std::memory_order_relaxed); + publishDriverBufferPeaks(outPeakL,outPeakR); + if(route==armix::diagnostics::Route::mainOutputTone) + mainTestPeak_.store(juce::jmax(mainTestPeak_.load(std::memory_order_relaxed),outPeak), + std::memory_order_relaxed); outputPeak_.store (juce::jmin (1.f, outPeak), std::memory_order_relaxed); outputPeakL_.store (juce::jmin (1.f, outPeakL), std::memory_order_relaxed); outputPeakR_.store (juce::jmin (1.f, outPeakR), std::memory_order_relaxed); diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 932554589..5a4d019c0 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2590,6 +2590,17 @@ class LiveDryRoutingLab final { } std::uint64_t revision() const noexcept {return publisher_.lastRevision();} // control only + // Control thread only. The test uses the exact pair the current mixer + // owns, including non-contiguous physical pins mapped to compact indices. + std::array acceptedMainCallbackPair() const noexcept { + if(!ready())return {{-1,-1}}; + if(channelIdPhysicalPcmActive()) + return {{nativeAccepted_.hardware.mainL,nativeAccepted_.hardware.mainR}}; + if(const auto* graph=publisher_.controlPrepared(epoch(),revision())) + return {{graph->mainOutputLeft(),graph->mainOutputRight()}}; + return {{-1,-1}}; + } + // JUCE render callback, with a verified single-clock device. Routing // publishes at the BLOCK boundary. Missing/stale ports output SILENCE. // A failed run never falls through to an unrelated microphone/plugin path. diff --git a/src/Main.cpp b/src/Main.cpp index c2332c784..299157079 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1050,6 +1050,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // ENGINE callback. This code executes on the JUCE message thread, not RT. void handleApprovedNativeControl(const juce::var& request) { + if(audioDeviceApplyActive_) { + auto ack=std::make_unique(); + ack->setProperty("requestId",request.getProperty("requestId",{})); + ack->setProperty("status","REJECTED"); + ack->setProperty("errorCode","AUDIO_DEVICE_APPLY_IN_PROGRESS"); + browser_.emitEventIfBrowserIsVisible("arMixConsoleAck",juce::var(ack.release())); + return; + } const auto beforeLive=engine_.status(); const auto before=approvedNativeSnapshot(beforeLive); const auto route=beforeLive.getProperty("dryRoutingLab",{}); @@ -1324,11 +1332,55 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr serviceAutomaticMain(); } + bool audioDeviceApplyActive_=false; // JUCE message thread, including nested driver dispatch + + juce::String openSelectedAudioDevice(const juce::String& backend, + const juce::AudioDeviceManager::AudioDeviceSetup& setup) { + auto& manager=engine_.devices(); + if(manager.getCurrentAudioDeviceType()==backend) { + if(auto* device=manager.getCurrentAudioDevice();device && !device->isOpen()) + manager.closeAudioDevice(); + return manager.setAudioDeviceSetup(setup,true); + } + + // JUCE's setCurrentAudioDeviceType opens its remembered/default + // device first and sleeps on the message thread. Initialise the + // exact named backend and requested masks in one open instead. + auto xml=manager.createStateXml(); + if(!xml)xml=std::make_unique("DEVICESETUP"); + xml->setAttribute("deviceType",backend); + xml->removeAttribute("audioDeviceName"); + xml->setAttribute("audioInputDeviceName",setup.inputDeviceName); + xml->setAttribute("audioOutputDeviceName",setup.outputDeviceName); + xml->setAttribute("audioDeviceRate",setup.sampleRate); + xml->setAttribute("audioDeviceBufferSize",setup.bufferSize); + const auto setMask=[&](const char* key,bool useDefault,const juce::BigInteger& mask) { + if(useDefault)xml->removeAttribute(key); + else xml->setAttribute(key,mask.toString(2)); + }; + setMask("audioDeviceInChans",setup.useDefaultInputChannels,setup.inputChannels); + setMask("audioDeviceOutChans",setup.useDefaultOutputChannels,setup.outputChannels); + diagnostics_.record("CUSTOM_AUDIO_PHASE","CLOSE_PREVIOUS | "+manager.getCurrentAudioDeviceType()); + manager.closeAudioDevice(); + diagnostics_.record("CUSTOM_AUDIO_PHASE","OPEN_SELECTED | "+backend); + return manager.initialise(2,2,xml.get(),false); + } + void applyCustomAudioDevice(const juce::var& args) { - // Synchronous manager operations stay on JUCE's established message - // thread. A vendor driver may block; never pretend JS async fixes it. + // JUCE device lifecycle runs on the message thread, including ASIO's + // modal callbacks. Serialize transactions across nested dispatch. const auto id=args.getProperty("requestId",{}).toString().substring(0,64); + if(audioDeviceApplyActive_) { + auto ack=std::make_unique(); + ack->setProperty("requestId",id); + ack->setProperty("ok",false); + ack->setProperty("state","BUSY"); + ack->setProperty("error","Audio I/O is already applying a device change."); + browser_.emitEventIfBrowserIsVisible("arMixAudioDeviceApplyAck",juce::var(ack.release())); + return; + } + const juce::ScopedValueSetter applying(audioDeviceApplyActive_,true); const auto oldGeneration=engine_.status().getProperty("deviceGeneration",0); auto send=[&](bool ok,const juce::String& state,const juce::String& error, bool canReusePins=false) @@ -1355,7 +1407,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(nativeShowBusy_||studioBackupBusy_||mixerSessionWorker_.busy()|| engine_.isGraphSwitchPending()|| static_cast(nativeRoute.getProperty("pending",false))|| - engine_.independentClockActive()||engine_.hasTemporaryDiagnosticDevice()|| + engine_.independentClockActive()|| + engine_.diagnosticRoute()!=armix::diagnostics::Route::normal|| engine_.secondaryArmed()) return send(false,"REJECTED", "Stop STREAM and finish Show/FX/diagnostic/clock transition first"); @@ -1494,7 +1547,6 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto start=monotonicMilliseconds(); autoMainEpoch_=0; engine_.beginManualAudioSetup(); - if(!unchangedDevice)manager.setCurrentAudioDeviceType(typeName,false); // JUCE setAudioDeviceSetup() can return success without reopening when // setup == currentSetup and currentAudioDevice != nullptr, even when // that driver object has stopped. closeAudioDevice() deletes it but @@ -1506,9 +1558,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr typeName+" | "+(previousWasOpen?"REFRESH_ASIO_PINS":"CLOSED_DEVICE_RECOVERY")); manager.closeAudioDevice(); } - auto error=manager.getCurrentAudioDeviceType()==typeName - ?manager.setAudioDeviceSetup(candidate,true) - :juce::String("Selected audio backend could not be opened"); + diagnostics_.record("CUSTOM_AUDIO_PHASE","APPLY | "+typeName); + auto error=openSelectedAudioDevice(typeName,candidate); + diagnostics_.record("CUSTOM_AUDIO_PHASE","VERIFY_READBACK | "+typeName); juce::AudioDeviceManager::AudioDeviceSetup actual; manager.getAudioDeviceSetup(actual); auto* opened=manager.getCurrentAudioDevice(); @@ -1531,6 +1583,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr std::abs(opened->getCurrentSampleRate()-actual.sampleRate)>1.0|| opened->getCurrentBufferSizeSamples()!=actual.bufferSize)) error="Driver readback mismatch; device setting was not accepted"; + if(error.isEmpty())diagnostics_.record("CUSTOM_AUDIO_PHASE","BIND_MIXER | "+typeName); if(error.isEmpty()&&!finishAudioSetupAndRecoverMixer(true)) { if(!previousMixerBound && engine_.directRouteAuthorized() && (engine_.hasRetainedUnboundMixer() || mixerSessionRecoveryPending_)) { @@ -1564,11 +1617,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // One rollback, never blind default endpoint fallback, no auto-unmute. // A previously CLOSED device was never a verified rollback target. engine_.beginManualAudioSetup(); - if(recovery.priorKnownOpen&&manager.getCurrentAudioDeviceType()!=previousType&&previousType.isNotEmpty()) - manager.setCurrentAudioDeviceType(previousType,false); + diagnostics_.record("CUSTOM_AUDIO_PHASE","ROLLBACK | "+previousType); const auto restored=recovery.priorKnownOpen&&previousType.isNotEmpty()&& - manager.getCurrentAudioDeviceType()==previousType&& - manager.setAudioDeviceSetup(before,true).isEmpty(); + openSelectedAudioDevice(previousType,before).isEmpty()&& + manager.getCurrentAudioDeviceType()==previousType; juce::AudioDeviceManager::AudioDeviceSetup checked; manager.getAudioDeviceSetup(checked); const bool verified=restored&& @@ -1774,7 +1826,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr result.preallocateBytes (64 * 1024); result << "ARSONMIX / SMART AUDIO DIAGNOSTIC REPORT v2\n"; result << "Timestamp: " << juce::Time::getCurrentTime().toISO8601 (true) << "\n"; - result << "Build: experimental-P0 clock-instrumentation / native JUCE 8.0.15\n"; + result << "Build: " << juce::JUCEApplication::getInstance()->getApplicationVersion() + << " | Source HEAD: " << ARMIX_BUILD_SOURCE_SHA << "\n"; result << "Platform: " << juce::SystemStats::getOperatingSystemName() << "\n"; result << "CPU: " << juce::SystemStats::getCpuModel() << "\n"; result << "Logical cores: " << juce::SystemStats::getNumCpus() @@ -2388,6 +2441,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void onAction (const juce::var& args) { const auto action = args.getProperty ("action", {}).toString(); + if(audioDeviceApplyActive_ && action!="audioDeviceApply")return; const auto value = args.getProperty ("value", {}); const int slot = static_cast (args.getProperty ("slot", -1)); // User may adjust live levels, but cannot alter the persisted VST @@ -4160,7 +4214,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr lastDirectRestoreError_.clear(); // One-sided device routes are temporary and must never leak into // normal user configuration or the persisted audio-devices.xml. - if (engine_.hasTemporaryDiagnosticDevice()) + if (engine_.hasTemporaryDiagnosticDevice() || + engine_.diagnosticRoute()==armix::diagnostics::Route::mainOutputTone) { const auto error = engine_.setDiagnosticRoute (armix::diagnostics::Route::normal); if (error.isNotEmpty()) return emitNotice (error, true); @@ -4179,9 +4234,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr deviceSettingsDirty_ = true; } using Route = armix::diagnostics::Route; - const auto selected = value.toString(); + auto selected = value.toString(); + if(selected=="TOGGLE_MAIN_OUTPUT_TONE") + selected=engine_.diagnosticRoute()==Route::mainOutputTone?"NORMAL":"MAIN_OUTPUT_TONE"; auto route = Route::normal; if (selected == "OUTPUT_ONLY_TONE") route = Route::outputOnlyTone; + else if (selected == "MAIN_OUTPUT_TONE") route = Route::mainOutputTone; else if (selected == "CAPTURE_ONLY") route = Route::captureOnly; else if (selected == "DRY_THROUGH") route = Route::dryThrough; else if (selected != "NORMAL") return emitNotice ("Unsupported diagnostic mode", true); @@ -4196,8 +4254,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (route == Route::normal) deviceSettingsDirty_ = true; diagnostics_.record ("AUDIO_TEST_MODE", selected + " | " + juce::JSON::toString (engine_.status(), false)); - emitNotice ("Audio diagnostic: " + selected + - ". Use low headphone volume and MARK CRACKLE on audible faults."); + if(route==Route::mainOutputTone) + emitNotice("MAIN test tone active. Use low speaker volume. Press Test MAIN output again to stop."); + else + emitNotice ("Audio diagnostic: " + selected + + ". Use low headphone volume and MARK CRACKLE on audible faults."); } else if (action == "diagnosticMark") { @@ -4604,6 +4665,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void changeListenerCallback (juce::ChangeBroadcaster*) override { + if(audioDeviceApplyActive_)return; // synchronous transaction owns recovery // Save device state only after a real change, not on every 3-second tick. deviceSettingsDirty_ = true; // The retention gate closes only on an actual epoch/owner change. @@ -4619,6 +4681,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void timerCallback() override { + if(audioDeviceApplyActive_)return; // a vendor modal loop may re-enter JUCE // Always disabled unless the user explicitly starts a bounded trace. const bool timing = guiPerf_.active; const double tickStart = timing ? juce::Time::getMillisecondCounterHiRes() : 0.0; diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index fa4c157d2..f7016c754 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -1,4 +1,4 @@ -"""Real compiled DOM from G0: first drag without OUT priming, first native +"""Real compiled DOM: hide reference G0, first drag without OUT priming, first native FX picker insert on original CH with structural=false, then vendor editor. Backend isolation is emulated; actual latency/sample evidence is CTest. """ @@ -41,6 +41,7 @@ def main(): addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") page.goto((out/'index.html').as_uri()) page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__?.enabled') + assert page.locator('.console-pane').is_hidden() # Built-in JUCE DSP must be discoverable before ANY third-party # VST3 catalog response. The native host never inserts demo FX. for native_id in ('armix.builtin.channel-eq.v1', @@ -135,6 +136,9 @@ def show_select(value): emit(page,"arMixNativeSessionAck",{"operation":"OPEN","ok":False,"error":"Invalid mixer JSON"}) assert page.get_by_text("Invalid mixer JSON",exact=True).count()>=1 assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='monitor')") + show_click("Test MAIN output") + assert page.evaluate("()=>window.__events.at(-1).payload")=={ + "action":"diagnosticRoute","value":"TOGGLE_MAIN_OUTPUT_TONE"} show_click("Browse Shows") assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" emit(page,"arMixNativeShowListAck",{"ok":True,"items":[ @@ -169,12 +173,10 @@ def show_select(value): assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" emit(page,"arMixNativeShowListAck",{"ok":True,"items":[]}) assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='monitor')") - if 'collapsed-send' in (page.locator('.console-body').get_attribute('class') or ''): - page.locator('.section-rail [data-section="send"]').click() - # Release before bootstrap SOURCE's later native readback arrives. - drag(page,1,2) + assert page.locator('.console-pane').is_hidden() assert not page.evaluate('()=>window.__nativeIntents.length') state=snapshot() + state['device'].update(enabledInputs=[],inputEndpoints=[]) state['graph']['edges'].pop(1) # genuinely no existing channel send state['graph']['capabilities']['supportedOps'] += ['LOAD_INSERT'] for ident, role, name in [('101','GROUP','Vocal Group'), @@ -187,6 +189,10 @@ def show_select(value): state['legacyM4']={'active':True,'routeAccepted':True,'routingRevision':'77', 'nativeBusStructural':False,'fxInstances':[[] for _ in range(14)]} emit(page,'arMixConsoleSnapshot',state) + page.locator('.console-pane').wait_for(state='visible') + if 'collapsed-send' in (page.locator('.console-body').get_attribute('class') or ''): + page.locator('.section-rail [data-section="send"]').click() + drag(page,1,2) page.wait_for_function('()=>window.__nativeIntents.length===1') route=page.evaluate('()=>window.__nativeIntents[0]') assert route['operation']=='APPLY_WIRE_TRANSACTION' @@ -294,7 +300,8 @@ def show_select(value): 'state':'ACCEPTED_LIVE','active':active,'mixerBound':True,'outputMuted':False}) assert page.locator('.armix-audio-shade').is_hidden() rebound=copy.deepcopy(state) - rebound['device'].update(epoch='93',outputArmed=True) + rebound['device'].update(epoch='93',outputArmed=True, + enabledInputs=g0['device']['enabledInputs'],inputEndpoints=g0['device']['inputEndpoints']) rebound['graph']['revision']='6' rebound['graph']['capabilities']['supportedOps'].append('CREATE_CHANNEL') rebound['mixerSession'].update(deviceEpoch='93',routeRevision='6') diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index dced419c2..576c4386a 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -637,6 +637,11 @@ static void installedCallbackAdmissionRegression(const juce::var& rawBus) { =="9007199254740993"); assert(std::abs(static_cast(session.getProperty("main",{}) .getProperty("db",0.))-(-13.5))<0.00001); + // The installed graph remains editable with playback and no capture pins. + dev.getDynamicObject()->setProperty("enabledInputs",juce::var(juce::Array{})); + assert(projectInstalledNativeChannelIdGraph(snap,live)); + publishAuthoritativeMixerSession(snap); + assert(snap.getProperty("mixerSession",{}).getProperty("authority","").toString()=="CHANNEL_ID"); // Real restart: lab routing epoch counts STOP+START, unlike M2 // deviceStartCount. This G0-to-native authority switch must advance. auto disconnected=canonicalSnapshot(); @@ -826,7 +831,18 @@ static void firstSoundRouteAdmissionRegression() { auto withoutInput=juce::JSON::parse(juce::JSON::toString(snapshot,false)); withoutInput.getProperty("device",{}).getDynamicObject() ->setProperty("enabledInputs",juce::var(juce::Array{})); - assert(!publishVerifiedFirstSoundState(withoutInput,live)); + assert(publishVerifiedFirstSoundState(withoutInput,live)); + assert(withoutInput.getProperty("legacyM4",{}) + .getProperty("channels",{}).getArray()->isEmpty()); // stale MONO mapping rejected + auto noCaptureRoute=juce::JSON::parse(juce::JSON::toString(live,false)); + auto noCaptureRows=noCaptureRoute.getProperty("dryRoutingLab",{}) + .getProperty("acceptedRoute",{}).getProperty("channels",{}); + auto* unpatched=noCaptureRows[4].getDynamicObject(); + unpatched->setProperty("mode","NONE"); + unpatched->setProperty("left",-1); + assert(publishVerifiedFirstSoundState(withoutInput,noCaptureRoute)); + assert(withoutInput.getProperty("legacyM4",{}) + .getProperty("channels",{}).getArray()->size()==10); } // Control-only fixture: validates exclusive M4 session normalization, diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index 11176a98e..157d8917a 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -202,7 +202,14 @@ test('DEVICE1 existing matrix drives real JUCE manager with gated native readbac for(const flag of ['JUCE_ASIO=1','JUCE_WASAPI=1','JUCE_DIRECTSOUND=1'])assert.ok(cm.includes(flag)); assert.match(native,/manager, 1, 64, 1, 64, false, false, false, false/); // hidden fallback only assert.match(native,/action == "audioDeviceApply"/); - assert.match(native,/setAudioDeviceSetup\(candidate,true\)/); + const open=native.slice(native.indexOf('juce::String openSelectedAudioDevice('), + native.indexOf('void applyCustomAudioDevice(')); + assert.match(native,/openSelectedAudioDevice\(typeName,candidate\)/); + assert.match(native,/openSelectedAudioDevice\(previousType,before\)/); + assert.match(open,/setAudioDeviceSetup\(setup,true\)/); + assert.match(open,/manager\.initialise\(2,2,xml\.get\(\),false\)/); + assert.match(open,/manager\.closeAudioDevice\(\);[\s\S]*manager\.initialise/); + assert.doesNotMatch(open,/manager\.setCurrentAudioDeviceType\(/); assert.match(native,/beginManualAudioSetup\(\)/); assert.match(native,/finishManualAudioSetup\(\)/); assert.match(native,/RESTORED_MUTED/); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 212cb90c7..af49d6e55 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1924,6 +1924,11 @@ // Windows RAM/process paging context from the existing 1 Hz control // timer. No sampling or file I/O happens in the ASIO callback. const healthTitle=item("span","more-tools-caption","AUDIO HEALTH"); + const tone=item("button","tool","Test MAIN output"); + tone.title="Start or stop a quiet tone on the verified MAIN pair without reopening the driver"; + tone.addEventListener("click",()=>{ + backend.emitEvent("arMixAction",{action:"diagnosticRoute",value:"TOGGLE_MAIN_OUTPUT_TONE"}); + }); const mark=item("button","tool","Mark Crackle"); mark.title="Capture 5s before an audible crackle, including Windows memory"; mark.addEventListener("click",()=>{ @@ -2080,7 +2085,7 @@ if(!save)controller?.subscribe(); }); menu.append(caption,setup,muteBtn,hardwareNote, - healthTitle,mark,report,advanced, + healthTitle,tone,mark,report,advanced, showHeading,showSave,showBrowse,showSelect,showUpdate,showRecall,showRecover,showNote); // Single discoverable AUDIO I/O button next to ordinary mixer tools. // The existing More entry remains a shortcut to THIS SAME panel. @@ -2167,7 +2172,10 @@ const session=next?.raw?.mixerSession; if(!session || session.deviceEpoch!==next.device.epoch) { flags.acceptedGraphConnected=false; - status("NATIVE SESSION UNAVAILABLE · controls unchanged"); + flags.productionCallbackLive=false; + lastPaintedSignature=""; + delete document.documentElement.dataset.armixNativeRoster; + status("NATIVE SESSION UNAVAILABLE · verify Audio I/O"); return; } // Never paint unacknowledged controls; pending slider caps are kept @@ -2178,7 +2186,8 @@ reconcileM4RackReadback(next); if(session.authority==="M4" && m4Verified()) { paintM4Fallback(next); - scope?.syncVerifiedM4Wires?.(session.channels.map(ch=>ch.source),m4TrackIds); + if(scope?.syncVerifiedM4Wires?.(session.channels.map(ch=>ch.source),m4TrackIds)) + document.documentElement.dataset.armixNativeRoster="accepted"; } // A second channel's IN can be selected while the first transaction is // in flight. Always dispatch its latest choice with a FRESH native route @@ -2213,8 +2222,10 @@ pendingFxInsert=null;pendingTrackDelete=null;startupWire=null;activeWireAttempt=null; pendingWireGains.clear();pendingNativeControl.clear();liveFaderVisualTargets.clear(); const signature="retained|"+next.identity+"|"+appearanceRevision; - if(lastPaintedSignature!==signature && projectNativeGraphWithoutFocusLoss(next)) + if(lastPaintedSignature!==signature && projectNativeGraphWithoutFocusLoss(next)){ lastPaintedSignature=signature; + document.documentElement.dataset.armixNativeRoster="accepted"; + } stopDemo(); paintNativeMeters(next); status("NEEDS REMAP · mixer retained · output muted"); @@ -2223,13 +2234,14 @@ if (!nativeAdmitted) { flags.productionCallbackLive=false;flags.acceptedGraphConnected=false; lastPaintedSignature="";lastNativeTopologySignature=""; + if(!m4Verified())delete document.documentElement.dataset.armixNativeRoster; stopDemo(); status(m4Verified()? "NATIVE M4 · real PCM faders and meters · ChannelId buses not yet admitted": deviceReady()? "NATIVE G0 · verified physical IN ready · select a channel input": hardware?.device?.enabledInputs?.length===0? - "NO HARDWARE IN · FX/BUS/WIRE REMAIN AVAILABLE": + "NATIVE MIXER UNAVAILABLE · verify playback in Audio I/O": "NATIVE G0 NOT READY · open Audio I/O and verify device / native route"); return; } @@ -2249,6 +2261,7 @@ stopDemo();status("NATIVE READBACK INVALID · existing GUI controls unchanged"); return; } + document.documentElement.dataset.armixNativeRoster="accepted"; flags.productionCallbackLive=next.productLive;flags.acceptedGraphConnected=true; syncMonitorButton(next.device); lastPaintedSignature=signature;stopDemo();paintNativeMeters(next); From c9563d14ed0ff91df81b077c8630610e986fd864 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 19:32:47 +0700 Subject: [PATCH 16/26] Allow explicit MAIN pin recovery without replacing the mixer session Keep normal device Apply anchored to saved physical MAIN pins. Accept deliberate assignment of exactly two driver-verified playback pins, and retry saved-session restore over a pristine startup graph after verified device recovery. --- src/Main.cpp | 40 ++++++++++++++-------- src/NativeMixerSessionDocument.h | 13 +++---- tests/approved_native_cold_start_smoke.py | 24 +++++++++++-- tests/approved_native_m2_contract.test.cjs | 7 ++-- tests/mixer_io_operator_contract_test.mjs | 6 ++-- tests/native_mixer_session_store_test.cpp | 12 +++++++ web/approved-native-bridge.js | 16 +++++++-- 7 files changed, 88 insertions(+), 30 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 299157079..e32644a81 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1332,6 +1332,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr serviceAutomaticMain(); } + using MixerBindingMode=armix::session::MixerDeviceBindingPolicy::Mode; bool audioDeviceApplyActive_=false; // JUCE message thread, including nested driver dispatch juce::String openSelectedAudioDevice(const juce::String& backend, @@ -1458,6 +1459,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const bool previousWasOpen=previousDevice!=nullptr&&previousDevice->isOpen(); const bool previousMixerBound=engine_.hasBoundMixerRoute(); const bool previousMonitor=engine_.isMonitorEnabled(); + const auto assignMain=config.getProperty("assignSelectedPlaybackPinsToMain",false); + if(!assignMain.isBool()) + return send(false,"REJECTED","Invalid MAIN playback pin selection"); + const bool explicitMain=static_cast(assignMain); const auto confirm=config.getProperty("confirmRetainedPinMapping",false); if(!confirm.isBool()) return send(false,"REJECTED","Invalid retained mixer mapping confirmation"); @@ -1465,7 +1470,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // The first Apply must open and verify the selected device. // Confirmation binds only that exact, still-open generation; // draft rate, buffer and pin changes use the normal Apply path. - if(!sameEndpoint || !previousWasOpen || rate!=before.sampleRate || + if(explicitMain || !sameEndpoint || !previousWasOpen || rate!=before.sampleRate || block!=before.bufferSize || !engine_.confirmRetainedWasapiPortMapping()) return send(false,"NEEDS_REMAP", @@ -1498,6 +1503,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto recovery=armix::device::AudioSetupRecoveryPolicy::select( sameEndpoint,previousWasOpen,typeName=="ASIO", pinInput.isArray()&&pinOutput.isArray()); + if(explicitMain && (!recovery.reuseActivePins || + pinOutput.getArray()->size()!=2)) + return send(false,"REJECTED","Select exactly two inspected playback pins for MAIN."); if(recovery.reuseActivePins) { const auto inCount=juce::jmin(64,previousDevice->getInputChannelNames().size()); const auto outCount=juce::jmin(64,previousDevice->getOutputChannelNames().size()); @@ -1584,7 +1592,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr opened->getCurrentBufferSizeSamples()!=actual.bufferSize)) error="Driver readback mismatch; device setting was not accepted"; if(error.isEmpty())diagnostics_.record("CUSTOM_AUDIO_PHASE","BIND_MIXER | "+typeName); - if(error.isEmpty()&&!finishAudioSetupAndRecoverMixer(true)) { + const auto bindingMode=explicitMain?MixerBindingMode::verifiedMainPinApply: + MixerBindingMode::verifiedDeviceApply; + if(error.isEmpty()&&!finishAudioSetupAndRecoverMixer(bindingMode)) { if(!previousMixerBound && engine_.directRouteAuthorized() && (engine_.hasRetainedUnboundMixer() || mixerSessionRecoveryPending_)) { const juce::String needsRemap="Device opened. Mixer retained and muted; its port mapping or FX processing format needs review"; @@ -2273,14 +2283,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const bool nativeAlreadyActive=static_cast( live.getProperty("nativeChannelIdPcmActive",false)); // A fresh silent ChannelId starter is now admitted before the saved - // Show is inspected. Only THAT unmodified bootstrap may be replaced, - // and only by this automatic cold-start restore. User-authored FX, + // Show is inspected. Only THAT unmodified bootstrap may be replaced + // by cold-start restore or by verified Apply after a failed startup. User-authored FX, // WIRE, BUS and fader edits must never be overwritten by late scan. // A verified PREVIOUS checkpoint is also eligible: the separate // resume policy keeps MAIN muted after recovery from corrupt HEAD. - const bool replacePristineStartup=nativeAlreadyActive && - startupOnSavedDevice && !retained && - bindingMode==armix::session::MixerDeviceBindingPolicy::Mode::exact && + const bool recoveringAfterDeviceApply=bindingMode!=MixerBindingMode::exact && + mixerSessionRecoveryPending_; + const bool replacePristineStartup=nativeAlreadyActive && !retained && + (startupOnSavedDevice || recoveringAfterDeviceApply) && engine_.hasPristineStartupMixer(); if(nativeAlreadyActive && !replacePristineStartup) { mixerSessionStatus_="LIVE_MIXER_UNCHANGED"; @@ -4643,16 +4654,17 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } } - bool finishAudioSetupAndRecoverMixer(bool verifiedDeviceApply=false) { + bool finishAudioSetupAndRecoverMixer(MixerBindingMode bindingMode=MixerBindingMode::exact) { const bool bound=engine_.finishManualAudioSetup(); if(!engine_.directRouteAuthorized())return false; const auto lab=engine_.status().getProperty("dryRoutingLab",{}); - if(static_cast(lab.getProperty("nativeChannelIdPcmActive",false)))return true; - if(engine_.hasRetainedNativeSession() || - armix::session::NativeMixerSessionStore(settingsDirectory()).exists()) { - using BindingMode=armix::session::MixerDeviceBindingPolicy::Mode; - const auto error=restoreSavedMixerSession(false,verifiedDeviceApply? - BindingMode::verifiedDeviceApply:BindingMode::exact); + const bool hasCheckpoint=armix::session::NativeMixerSessionStore(settingsDirectory()).exists(); + const bool recoverPristine=bindingMode!=MixerBindingMode::exact && hasCheckpoint && + mixerSessionRecoveryPending_ && engine_.hasPristineStartupMixer(); + if(static_cast(lab.getProperty("nativeChannelIdPcmActive",false)) && + !recoverPristine)return true; + if(engine_.hasRetainedNativeSession() || hasCheckpoint) { + const auto error=restoreSavedMixerSession(false,bindingMode); if(error.isNotEmpty()) { mixerSessionError_=error; emitNotice("Mixer retained; "+error,true); diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index d89b47a78..bdd014941 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -65,12 +65,13 @@ struct MixerDeviceBindingPolicy final { (!a.monitorEnabled || (a.monitorL==b.monitorL && a.monitorR==b.monitorR)); } - enum class Mode { exact, verifiedDeviceApply }; + enum class Mode { exact, verifiedDeviceApply, verifiedMainPinApply }; static VerifiedNativeOutputs proposedOutputs(const MixerSessionDocument& document, const HardwareBinding& live,int count,Mode mode=Mode::exact) { const auto& saved=document.binding; - if(mode==Mode::verifiedDeviceApply && - (saved.backend!=live.backend || saved.playback!=live.playback)) + if(mode==Mode::verifiedMainPinApply || + (mode==Mode::verifiedDeviceApply && + (saved.backend!=live.backend || saved.playback!=live.playback))) return count==2?VerifiedNativeOutputs{count,0,1,-1,-1,false}: VerifiedNativeOutputs{count,-1,-1,-1,-1,false}; // A matching endpoint name does NOT prove an unchanged physical @@ -134,9 +135,9 @@ struct MixerDeviceBindingPolicy final { // ordinals; it never authorizes quietly switching MAIN to another // jack. Compare against the policy-computed remap even when a caller // supplies a valid but DIFFERENT output pair. - if(saved.backend==live.backend && saved.playback==live.playback) { - const auto mapped=proposedOutputs(document,live, - outputs.activeOutputChannels,Mode::verifiedDeviceApply); + if(mode==Mode::verifiedMainPinApply || + (saved.backend==live.backend && saved.playback==live.playback)) { + const auto mapped=proposedOutputs(document,live,outputs.activeOutputChannels,mode); if(!mapped.valid() || !sameOutputs(mapped,outputs)) return "NEEDS_REMAP: saved MAIN output pins are no longer selected; explicitly choose MAIN outputs"; } diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index f7016c754..9d0a0fec9 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -76,7 +76,8 @@ def main(): assert request['config']['enabledInputs']==[] assert request['config']['enabledOutputs']==[] out_active={**io_inventory['active'],'captureDevice':'', - 'inputNames':[],'enabledInputs':[]} + 'inputNames':[],'enabledInputs':[], + 'outputNames':['WDM L','WDM R','Realtek L','Realtek R']} emit(page,'arMixAudioDeviceApplyAck',{ 'requestId':request['requestId'],'ok':True, 'state':'ACCEPTED_MUTED','active':out_active, @@ -86,7 +87,26 @@ def main(): io_inventory['active']=out_active emit(page,'arMixAudioDeviceInventory',io_inventory) assert capture_select.input_value()=='' # reopening does not auto-patch a mic - page.locator('.armix-audio-dialog [data-audio-close]').click() + page.locator('.armix-audio-dialog details summary').click() + assign_main=page.locator('[data-audio-main-pins]') + def playback_pin(index): + return page.locator(f'[data-audio-pin="output"][data-pin-index="{index}"]') + playback_pin(0).uncheck() + assert assign_main.is_hidden() + playback_pin(1).uncheck() + playback_pin(2).check() + playback_pin(3).check() + assign_main.click() + repatch=page.evaluate("""()=>window.__events.filter(e=> + e.payload?.action==='audioDeviceApply').at(-1)?.payload""") + assert repatch['config']['assignSelectedPlaybackPinsToMain'] is True + assert repatch['config']['enabledOutputs']==[2,3] + assert repatch['config']['enabledInputs']==[] + emit(page,'arMixAudioDeviceApplyAck',{ + 'requestId':repatch['requestId'],'ok':True, + 'state':'ACCEPTED_MUTED','active':{**out_active,'enabledOutputs':[2,3]}, + 'outputMuted':True,'mixerBound':True}) + assert page.locator('.armix-audio-shade').is_hidden() g0=json.loads((ROOT/'integration/console-v6/fixtures.json').read_text())['g0'] g0['mixerSession']={'authority':'NONE','deviceEpoch':g0['device']['epoch'],'channels':[]} g0['legacyM4']={'active':True,'routeAccepted':False,'routingRevision':'1'} diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 51f903a50..8617140bc 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1246,8 +1246,9 @@ test("P0 automatic cold-start Show replaces only pristine SOURCE NONE ChannelId" const main=read('src/Main.cpp'); const engine=read('src/LiveAudioEngine.h'); const route=read('src/LiveDryRoutingLab.h'); - assert.match(main,/startupOnSavedDevice && !retained &&/); - assert.doesNotMatch(main,/startupOnSavedDevice && !retained && !usedPrevious/); + assert.match(main,/nativeAlreadyActive && !retained &&/); + assert.match(main,/\(startupOnSavedDevice \|\| recoveringAfterDeviceApply\) &&/); + assert.match(main,/recoveringAfterDeviceApply=bindingMode!=MixerBindingMode::exact &&\s*mixerSessionRecoveryPending_/); assert.match(main,/!usedPrevious && !retained/); // only normal auto-resume, not recovery admission assert.match(main,/engine_\.hasPristineStartupMixer\(\)/); assert.match(main,/restoreNativeMixerSession\(std::move\(doc\),states,\s*replacePristineStartup/); @@ -1259,7 +1260,7 @@ test("P0 automatic cold-start Show replaces only pristine SOURCE NONE ChannelId" test("P0 startup banner never demands legacy Patch CH1 / Arm wizard",()=>{ const bridge=read("web/approved-native-bridge.js"); assert.match(bridge,/SELECT CHANNEL IN · NATIVE MONITOR AFTER ACK/); - assert.match(bridge,/NO HARDWARE IN · MIXER\/FX READY · USE PLAYER OR AUDIO I\/O/); + assert.match(bridge,/next.admitted\?"NO HARDWARE IN · MIXER\/FX READY"/); assert.doesNotMatch(bridge,/hardware\.device\.enabledInputs\.length>0/); assert.match(bridge,/NO VERIFIED INPUT ROUTE · OPEN AUDIO I\/O/); assert.doesNotMatch(bridge,/NO AUDIBLE OUTPUT · PATCH INPUT \+ ARM/); diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index 157d8917a..ce8dc23f8 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -227,10 +227,12 @@ test('DEVICE1 existing matrix drives real JUCE manager with gated native readbac test('explicit device Apply restores the authored mixer after driver readback and can roll back',()=>{ const main=read('src/Main.cpp'); const apply=main.slice(main.indexOf('void applyCustomAudioDevice('),main.indexOf('void showDeviceSetup()')); - assert.match(apply,/if\(error\.isEmpty\(\)&&!finishAudioSetupAndRecoverMixer\(true\)\)/); + assert.match(apply,/if\(error\.isEmpty\(\)&&!finishAudioSetupAndRecoverMixer\(bindingMode\)\)/); assert.match(apply,/if\(!previousMixerBound && engine_\.directRouteAuthorized\(\)/); assert.match(apply,/finishAudioSetupAndRecoverMixer\(\);/); - assert.match(main,/BindingMode::verifiedDeviceApply:BindingMode::exact/); + assert.match(apply,/explicitMain\?MixerBindingMode::verifiedMainPinApply/); + assert.match(apply,/pinOutput.getArray\(\)->size\(\)!=2/); + assert.match(main,/restoreSavedMixerSession\(false,bindingMode\)/); }); test('SETUP1 honest bus patch has real AUX/MAIN/MONITOR navigation, no fake GROUP DCA',()=>{ diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index 3dadd54e1..5e9d56fb8 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -489,6 +489,18 @@ int main(){ assert(MixerDeviceBindingPolicy::apply(main34,only12,unauthorized12,2, BindingMode::verifiedDeviceApply).startsWith("NEEDS_REMAP")); assert(Codec::encode(main34)==main34Before); + // Deliberate MAIN assignment through the verified current two-pin mask + // is distinct from a normal Apply that must preserve the original pair. + auto explicitlyRepatched=main34; + const auto explicitPair=MixerDeviceBindingPolicy::proposedOutputs( + main34,only12,2,BindingMode::verifiedMainPinApply); + assert(explicitPair.valid() && explicitPair.mainL==0 && explicitPair.mainR==1); + assert(MixerDeviceBindingPolicy::apply(explicitlyRepatched,only12,explicitPair,2, + BindingMode::verifiedMainPinApply).isEmpty()); + assert(explicitlyRepatched.binding.outputMask=="3"); + assert(explicitlyRepatched.roster.revision()==main34.roster.revision()); + assert(!MixerDeviceBindingPolicy::proposedOutputs(main34,main34.binding,4, + BindingMode::verifiedMainPinApply).valid()); // If outputs 3/4 remain physically selected, ordinal 2/3 -> 0/1 // is a legal SAME-PIN remap, not an automatic route to different jacks. auto only34=main34.binding; diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index af49d6e55..1747fec56 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1525,7 +1525,8 @@ !deviceOpen?"NO VERIFIED AUDIO DEVICE": d.outputArmed?(next.admitted?"NATIVE PCM · HARDWARE FAT PENDING": "MAIN MONITOR ON · PCM ADMISSION NOT VERIFIED"): - !d.enabledInputs?.length?"NO HARDWARE IN · MIXER/FX READY · USE PLAYER OR AUDIO I/O": + !d.enabledInputs?.length?(next.admitted?"NO HARDWARE IN · MIXER/FX READY": + "MIXER SESSION UNAVAILABLE · CHECK AUDIO I/O"): legacy()?.routeAccepted?"NATIVE INPUT ROUTED · MONITOR OFF": deviceReady()?"SELECT CHANNEL IN · NATIVE MONITOR AFTER ACK": "NO VERIFIED INPUT ROUTE · OPEN AUDIO I/O"; @@ -1638,6 +1639,7 @@
+
@@ -1691,6 +1693,9 @@ if(!draft.backend||!draft.playback||(!separate&&!draft.capture))return; sendDeviceApply(); }; + devicePanel.querySelector("[data-audio-main-pins]").onclick=()=>{ + if(!deviceBusy)sendDeviceApply(false,true); + }; devicePanel.querySelector("[data-audio-remap]").onclick=()=>{ if(!deviceBusy && offeredPinRemap!==null) sendDeviceApply(true); @@ -1787,17 +1792,21 @@ devicePanel.querySelector("[data-audio-apply]").disabled=deviceBusy|| !deviceChoice.backend||(!t?.separate&&!deviceChoice.capture)|| !deviceChoice.playback; + const assignMain=devicePanel.querySelector("[data-audio-main-pins]"); + assignMain.hidden=!same || deviceChoice.outputPins?.length!==2; + assignMain.disabled=deviceBusy; const remap=devicePanel.querySelector("[data-audio-remap]"); remap.hidden=!same || offeredPinRemap!==active.deviceGeneration; remap.disabled=deviceBusy; remap.title="Reuse existing input and output pin numbers on the selected device. MONITOR stays off."; } - function sendDeviceApply(confirmRetainedPinMapping=false){ + function sendDeviceApply(confirmRetainedPinMapping=false,assignMain=false){ if(!deviceChoice||!deviceInventory?.active)return; const c=deviceChoice,a=deviceInventory.active; const same=a.open&&a.backend===c.backend&& a.captureDevice===c.capture&&a.playbackDevice===c.playback; if(confirmRetainedPinMapping && (!same || offeredPinRemap!==a.deviceGeneration))return; + if(assignMain && (!same || c.outputPins?.length!==2))return; deviceBusy=true; const requestId="approved-io-"+(++deviceRequest); devicePanel.dataset.pendingRequest=requestId; @@ -1811,7 +1820,8 @@ bufferSize:confirmRetainedPinMapping?a.buffer:same?c.buffer:0, enabledInputs:same?c.inputPins:[], enabledOutputs:same?c.outputPins:[], - ...(confirmRetainedPinMapping?{confirmRetainedPinMapping:true}:{})}}); + ...(confirmRetainedPinMapping?{confirmRetainedPinMapping:true}:{}), + ...(assignMain?{assignSelectedPlaybackPinsToMain:true}:{})}}); } if(connected){ backend.addEventListener("arMixAudioDeviceInventory",inventory=>{ From 29f29acd1495406ed3748cf0a9f0b4086ad13392 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 20:14:13 +0700 Subject: [PATCH 17/26] Recover ASIO4ALL mixer bindings by verified physical pin labels Reconcile changed compact ordinals without losing the VB-Cable source, resume same-driver restarts with a bounded pin correction, and keep authored FX on compatible device epochs. Adopt a single verified physical speaker pair on explicit Apply when the old pair is gone. --- src/LiveAudioEngine.h | 83 ++++++++++++++- src/LiveDryRoutingLab.h | 3 + src/Main.cpp | 98 ++++++++++++++++-- src/NativeMixerSessionDocument.h | 120 ++++++++++++++++------ tests/mixer_io_operator_contract_test.mjs | 7 +- tests/native_mixer_session_store_test.cpp | 81 ++++++++++++++- web/approved-native-bridge.js | 5 +- 7 files changed, 348 insertions(+), 49 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 9c82f5ae3..ba6525b18 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -396,6 +396,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // starts its new callback before the selector window is closed. void beginManualAudioSetup() noexcept { offeredWasapiBinding_.reset(); + resumeMainAfterAsioReset_.store(false,std::memory_order_release); setOutputMuted(true); secondaryOutput_.disarm(); directFence_.suspend(); @@ -403,7 +404,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // device-binding operation, not an implicit CLEAR MIXER command. // The JUCE selector may change the driver before its window closes. } - bool finishManualAudioSetup() { + bool finishManualAudioSetup(bool reuseAsioBinding=true) { if(!approveDirectRoute())return false; using Decision=armix::device::DeviceSessionDecision; switch(armix::device::decideDeviceSession( @@ -414,7 +415,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback case Decision::createFirstSilentMixer: return startUnpatchedProductionSession().isEmpty(); case Decision::retainUnboundMixer: - return rebindRetainedWasapiSession(); + return (reuseAsioBinding && reattachRetainedAsioMixer()) || rebindRetainedWasapiSession(); case Decision::rejectedDevice: return false; } @@ -444,6 +445,79 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool recoverSameWasapiMixer() { return hasRetainedUnboundMixer() && rebindRetainedWasapiSession(); } + // The JUCE ASIO device may restart itself after a control panel change. + // Reauthorize only the previously approved driver class and session. + bool authorizeRetainedAsioRestart() { + using Policy=armix::session::MixerDeviceBindingPolicy; + if(!hasRetainedNativeSession() || !acceptedMixerBinding_ || + !Policy::isAsio4All(*acceptedMixerBinding_) || !asioPinnedRegistration_.valid() || + !allOutputsDisarmed() || independent_.active() || !attached_ || handoff_.busy() || + fxMovePhase_.load(std::memory_order_acquire)!=0 || + routeReconfiguring_.load(std::memory_order_acquire) || + diagnosticRoute()!=armix::diagnostics::Route::normal)return false; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device || !device->isOpen() || device->getTypeName()!="ASIO" || + device->getName()!=acceptedMixerBinding_->playback)return false; + return approveDirectRoute(&asioPinnedRegistration_); + } + std::optional asioRestartPinCorrection() { + using Policy=armix::session::MixerDeviceBindingPolicy; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device || !acceptedMixerBinding_ || !directFence_.permitted())return {}; + const auto& previous=*acceptedMixerBinding_; + const auto live=readMixerBinding(*device); + if(live.backend!=previous.backend || live.capture!=previous.capture || + live.playback!=previous.playback)return {}; + juce::AudioDeviceManager::AudioDeviceSetup setup; + deviceManager_.getAudioDeviceSetup(setup); + const auto correct=[](const juce::String& oldMask,const juce::StringArray& oldNames, + const juce::StringArray& newNames,juce::BigInteger& mask, + bool& useDefault) { + if(oldNames==newNames)return false; + juce::BigInteger before; + before.parseString(oldMask,16); + const auto mapped=Policy::translateNamedPins(before,oldNames,newNames); + if(!mapped || *mapped==mask)return false; + mask=*mapped; + useDefault=false; + return true; + }; + const bool input=correct(previous.inputMask,previous.inputNames,live.inputNames, + setup.inputChannels,setup.useDefaultInputChannels); + const bool output=correct(previous.outputMask,previous.outputNames,live.outputNames, + setup.outputChannels,setup.useDefaultOutputChannels); + if(!input && !output)return {}; + setup.useDefaultInputChannels=false; + setup.useDefaultOutputChannels=false; + return setup; + } + bool reattachRetainedAsioMixer() { + using Policy=armix::session::MixerDeviceBindingPolicy; + if(!acceptedMixerBinding_ || !Policy::isAsio4All(*acceptedMixerBinding_) || + !hasRetainedNativeSession() || !allOutputsDisarmed() || + !directFence_.permitted() || handoff_.busy())return false; + const auto* previous=&*acceptedMixerBinding_; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device || !device->isOpen())return false; + const auto epoch=dryRoutingLab_.epoch(); + const auto live=readMixerBinding(*device); + armix::device::JuceActivePortSnapshot pins; + armix::device::JuceActivePortSnapshot::Fault fault{}; + if(!Policy::sameBinding(*previous,live) || previous->inputNames!=live.inputNames || + previous->outputNames.isEmpty() || previous->outputNames!=live.outputNames || + !armix::device::JuceActivePortSnapshot::capture(device,epoch,pins,fault) || + !dryRoutingLab_.matchesSessionDevice(pins) || + !dryRoutingLab_.rebindVerifiedDevice(dryRoutingLab_.retainedNativeEpoch(), + epoch,live.frames,false))return false; + acceptedMixerBinding_=live; + return true; + } + bool takeAsioResetMonitorIntent() noexcept { + return resumeMainAfterAsioReset_.exchange(false,std::memory_order_acq_rel); + } + void cancelAsioResetMonitorIntent() noexcept { + resumeMainAfterAsioReset_.store(false,std::memory_order_release); + } bool hasRetainedNativeSession() const noexcept { return dryRoutingLab_.hasRetainedNativeSession(); } @@ -2442,6 +2516,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const auto inputMask=device->getActiveInputChannels().toString (16); const auto outputMask=device->getActiveOutputChannels().toString (16); armix::device::AsioRegistrationPolicy::Identity candidate; + if (backend != "ASIO" && expectedAsio != nullptr)return false; if (backend == "ASIO") { const auto selected = armix::device::AsioRegistryIdentityProbe::resolve ( @@ -2534,6 +2609,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Temporary publication silence never changes operator MONITOR or MAIN MUTE. // The DIRECT device fence and physical-output verification remain separate. std::atomic topologyPublicationMute_ { false }; + std::atomic resumeMainAfterAsioReset_{false}; std::atomic monitor_ { false }, channelMute_ { false }, masterMute_ { false }, masterMono_ { false }, dryTest_ { false }; std::atomic masterGain_ { 1.f }, channelGain_ { 1.f }, channelPan_ { 0.f }; std::atomic inputPeak_ { 0.f }, postFxPeak_ { 0.f }, outputPeak_ { 0.f }; @@ -2673,7 +2749,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void audioDeviceStopped() override { - setOutputMuted(true); + if(monitor_.exchange(false,std::memory_order_acq_rel)) + resumeMainAfterAsioReset_.store(true,std::memory_order_release); secondaryOutput_.invalidateSource(); // explicit reconnect required after device stop masterLoudness_.prepare (0.0); // clear validity across device epoch dryRoutingLab_.deviceStopped(); diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 5a4d019c0..21ae5578b 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2494,6 +2494,9 @@ class LiveDryRoutingLab final { // CONTROL ONLY: hardware loss makes ready() false but does not erase // authored values, FX identity, GROUP/FX_RETURN buses or accepted WIREs. // Never downgrade this dynamic document to the fixed 10CH/4AUX schema. + std::uint64_t retainedNativeEpoch() const noexcept { + return hasRetainedNativeSession()?nativeAccepted_.deviceEpoch:0; + } bool hasRetainedNativeSession() const noexcept { return !channelIdPhysicalPcmActive() && nativeAccepted_.fxOwners && hasAuthoredMixerContent(); } diff --git a/src/Main.cpp b/src/Main.cpp index e32644a81..196cfccf6 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1275,7 +1275,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr o->setProperty("open",device!=nullptr&&device->isOpen()); o->setProperty("authorized",engine_.directRouteAuthorized()); o->setProperty("outputMuted",engine_.isOutputMuted()); - o->setProperty("deviceGeneration",engine_.status().getProperty("deviceGeneration",0)); + const auto live=engine_.status(); + o->setProperty("deviceGeneration",live.getProperty("deviceGeneration",0)); + o->setProperty("mainOutputs",live.getProperty("dryRoutingLab",{}).getProperty("mainOutputs",{})); juce::Array inputNames,outputNames,inputPins,outputPins,rates,buffers; if(device!=nullptr&&device->isOpen()) { const auto inputs=device->getInputChannelNames(); @@ -1336,9 +1338,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr bool audioDeviceApplyActive_=false; // JUCE message thread, including nested driver dispatch juce::String openSelectedAudioDevice(const juce::String& backend, - const juce::AudioDeviceManager::AudioDeviceSetup& setup) { + const juce::AudioDeviceManager::AudioDeviceSetup& setup,bool resetDefaults=false) { auto& manager=engine_.devices(); - if(manager.getCurrentAudioDeviceType()==backend) { + if(manager.getCurrentAudioDeviceType()==backend && !resetDefaults) { if(auto* device=manager.getCurrentAudioDevice();device && !device->isOpen()) manager.closeAudioDevice(); return manager.setAudioDeviceSetup(setup,true); @@ -1572,12 +1574,40 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr juce::AudioDeviceManager::AudioDeviceSetup actual; manager.getAudioDeviceSetup(actual); auto* opened=manager.getCurrentAudioDevice(); - const bool changedAsioPinLayout=error.isEmpty()&&recovery.verifyAsioPinIdentity&& + bool changedAsioPinLayout=error.isEmpty()&&recovery.verifyAsioPinIdentity&& opened!=nullptr&&opened->isOpen()&& (opened->getInputChannelNames()!=originalInputNames|| opened->getOutputChannelNames()!=originalOutputNames); + const bool refreshedAsio4All=typeName=="ASIO" && playback.startsWithIgnoreCase("ASIO4ALL") && + recovery.reuseActivePins && (changedAsioPinLayout || error.isNotEmpty()); + bool explicitPairStillIdentified=explicitMain; + if(refreshedAsio4All) { + // Never replay an index into a newly enumerated ASIO aggregate. + // Preserve verified selected names if they still exist, including + // VB-Cable capture moved past newly enabled input channels. + using BindingPolicy=armix::session::MixerDeviceBindingPolicy; + const auto freshInputNames=changedAsioPinLayout?opened->getInputChannelNames():juce::StringArray{}; + const auto freshOutputNames=changedAsioPinLayout?opened->getOutputChannelNames():juce::StringArray{}; + const auto capturePins=changedAsioPinLayout?BindingPolicy::translateNamedPins( + candidate.inputChannels,originalInputNames,freshInputNames):std::nullopt; + const auto playbackPins=changedAsioPinLayout?BindingPolicy::translateNamedPins( + candidate.outputChannels,originalOutputNames,freshOutputNames):std::nullopt; + candidate.useDefaultInputChannels=!capturePins && !candidate.inputChannels.isZero(); + candidate.useDefaultOutputChannels=!playbackPins; + if(capturePins)candidate.inputChannels=*capturePins; + if(playbackPins)candidate.outputChannels=*playbackPins; + explicitPairStillIdentified=explicitMain && playbackPins.has_value(); + diagnostics_.record("CUSTOM_AUDIO_PHASE","REFRESH_ASIO4ALL_INVENTORY"); + error=openSelectedAudioDevice(typeName,candidate,true); + manager.getAudioDeviceSetup(actual); + opened=manager.getCurrentAudioDevice(); + changedAsioPinLayout=error.isEmpty() && opened && opened->isOpen() && + ((capturePins && opened->getInputChannelNames()!=freshInputNames) || + (playbackPins && opened->getOutputChannelNames()!=freshOutputNames)); + } + asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); if(changedAsioPinLayout) - error="ASIO pin layout changed. Output remains muted; review the NEW capture and playback pins and Apply again"; + error="ASIO pin layout changed. Output remains muted; review the new playback pins."; if(error.isEmpty()&&(opened==nullptr||!opened->isOpen()|| manager.getCurrentAudioDeviceType()!=typeName|| actual.inputDeviceName!=capture||actual.outputDeviceName!=playback|| @@ -1592,12 +1622,13 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr opened->getCurrentBufferSizeSamples()!=actual.bufferSize)) error="Driver readback mismatch; device setting was not accepted"; if(error.isEmpty())diagnostics_.record("CUSTOM_AUDIO_PHASE","BIND_MIXER | "+typeName); - const auto bindingMode=explicitMain?MixerBindingMode::verifiedMainPinApply: + const auto bindingMode=explicitPairStillIdentified?MixerBindingMode::verifiedMainPinApply: MixerBindingMode::verifiedDeviceApply; if(error.isEmpty()&&!finishAudioSetupAndRecoverMixer(bindingMode)) { if(!previousMixerBound && engine_.directRouteAuthorized() && (engine_.hasRetainedUnboundMixer() || mixerSessionRecoveryPending_)) { - const juce::String needsRemap="Device opened. Mixer retained and muted; its port mapping or FX processing format needs review"; + const auto needsRemap=mixerSessionError_.isNotEmpty()?mixerSessionError_: + juce::String("Device opened, but the mixer could not bind to its playback pins."); diagnostics_.record("CUSTOM_AUDIO_NEEDS_REMAP",needsRemap); send(false,"NEEDS_REMAP",needsRemap,engine_.stageRetainedWasapiPortMapping()); emitApprovedNativeSnapshot(); @@ -1646,6 +1677,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr (manager.getCurrentAudioDevice()->getInputChannelNames()==originalInputNames&& manager.getCurrentAudioDevice()->getOutputChannelNames()==originalOutputNames))&& finishAudioSetupAndRecoverMixer(); + asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); diagnostics_.record("CUSTOM_AUDIO_APPLY_FAIL",error+" | rollback="+ (verified?"RESTORED":"RECOVERY_REQUIRED")+" | "+ juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); @@ -4623,6 +4655,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr fault=engine_.liveOutputArmFault(); if (fault.isEmpty()) { autoMainEpoch_=0; + if(!arm)engine_.cancelAsioResetMonitorIntent(); engine_.setMonitorEnabled(arm); diagnostics_.record("OUTPUT_MUTE",arm?"OFF":"ON"); } @@ -4655,7 +4688,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } bool finishAudioSetupAndRecoverMixer(MixerBindingMode bindingMode=MixerBindingMode::exact) { - const bool bound=engine_.finishManualAudioSetup(); + 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(); @@ -4675,6 +4708,54 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return bound; } + std::uint64_t asioRecoveryEpoch_=0; + void serviceAsioMixerRestart() { + const auto epoch=engine_.dryRoutingLabEpoch(); + if(epoch==asioRecoveryEpoch_ || !engine_.hasRetainedNativeSession() || + nativeShowBusy_ || studioBackupBusy_ || mixerSessionWorker_.busy() || catalog_.busy() || + engine_.isGraphSwitchPending() || + (audioSetupWindow_ && audioSetupWindow_->isVisible()))return; + auto* device=engine_.devices().getCurrentAudioDevice(); + if(!device || !device->isOpen() || device->getTypeName()!="ASIO" || + !device->getName().startsWithIgnoreCase("ASIO4ALL"))return; + asioRecoveryEpoch_=epoch; // at most one automatic bind per negotiated epoch + const juce::ScopedValueSetter applying(audioDeviceApplyActive_,true); + if(!engine_.authorizeRetainedAsioRestart())return; + if(const auto corrected=engine_.asioRestartPinCorrection()) { + // One bounded correction for JUCE's restart with the old mask. + // Keep the approved driver and preserve named physical endpoints. + const auto inputNames=device->getInputChannelNames(); + const auto outputNames=device->getOutputChannelNames(); + const auto error=openSelectedAudioDevice("ASIO",*corrected); + asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); + auto* reopened=engine_.devices().getCurrentAudioDevice(); + if(error.isNotEmpty() || !reopened || !reopened->isOpen() || + reopened->getInputChannelNames()!=inputNames || + reopened->getOutputChannelNames()!=outputNames || + reopened->getActiveInputChannels()!=corrected->inputChannels || + reopened->getActiveOutputChannels()!=corrected->outputChannels || + !engine_.authorizeRetainedAsioRestart()) { + diagnostics_.record("ASIO4ALL_PIN_CORRECTION_FAILED", + error.isNotEmpty()?error:juce::String("Readback changed during correction")); + emitApprovedNativeSnapshot(); + return; + } + } + const auto error=engine_.reattachRetainedAsioMixer()?juce::String{}: + restoreSavedMixerSession(false,MixerBindingMode::verifiedAsioRestart); + if(error.isNotEmpty()) { + diagnostics_.record("ASIO4ALL_REATTACH_FAILED",error); + emitApprovedNativeSnapshot(); + return; + } + mixerSessionStatus_="RESTORED_MUTED"; + mixerSessionError_.clear(); + if(engine_.takeAsioResetMonitorIntent())requestAutomaticMain(); + if(engine_.isMonitorEnabled())mixerSessionStatus_="RESTORED_MONITORING"; + diagnostics_.record("ASIO4ALL_REATTACHED","Verified driver and original MAIN pair"); + emitApprovedNativeSnapshot(); + } + void changeListenerCallback (juce::ChangeBroadcaster*) override { if(audioDeviceApplyActive_)return; // synchronous transaction owns recovery @@ -4780,6 +4861,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Audio thread publishes only fault flags. A bounded message-thread // restore transaction handles device failures without hot-plug spin. serviceDirectRestore(); + serviceAsioMixerRestart(); serviceAutomaticMain(); // Autosave only while ALL outputs are muted. Vendor-state reads // happen on CONTROL; disk commits run on ONE serialized IO worker. diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index bdd014941..62f201b8b 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -65,49 +65,65 @@ struct MixerDeviceBindingPolicy final { (!a.monitorEnabled || (a.monitorL==b.monitorL && a.monitorR==b.monitorR)); } - enum class Mode { exact, verifiedDeviceApply, verifiedMainPinApply }; + enum class Mode { exact, verifiedDeviceApply, verifiedMainPinApply, verifiedAsioRestart }; + static bool isAsio4All(const HardwareBinding& binding) { + return binding.backend=="ASIO" && binding.playback.startsWithIgnoreCase("ASIO4ALL"); + } + static std::optional translateNamedPins( + const juce::BigInteger& previous,const juce::StringArray& oldNames, + const juce::StringArray& newNames) { + juce::BigInteger result; + for(int pin=previous.findNextSetBit(0);pin>=0;pin=previous.findNextSetBit(pin+1)) { + const int next=findSamePin(oldNames,newNames,pin); + if(next<0 || next>=64)return {}; + result.setBit(next); + } + return result; + } static VerifiedNativeOutputs proposedOutputs(const MixerSessionDocument& document, const HardwareBinding& live,int count,Mode mode=Mode::exact) { const auto& saved=document.binding; + const VerifiedNativeOutputs unavailable{count,-1,-1,-1,-1,false}; if(mode==Mode::verifiedMainPinApply || (mode==Mode::verifiedDeviceApply && (saved.backend!=live.backend || saved.playback!=live.playback))) - return count==2?VerifiedNativeOutputs{count,0,1,-1,-1,false}: - VerifiedNativeOutputs{count,-1,-1,-1,-1,false}; - // A matching endpoint name does NOT prove an unchanged physical - // jack inventory. Reject rather than silently rebase MAIN to 1/2 - // if pin labels changed or an unknown ASIO inventory lost pins. - if(mode==Mode::verifiedDeviceApply && - ((!saved.outputNames.isEmpty() && saved.outputNames!=live.outputNames) || - (saved.outputNames.isEmpty() && live.backend=="ASIO" && - saved.outputMask!=live.outputMask))) - return {count,-1,-1,-1,-1,false}; + return count==2?VerifiedNativeOutputs{count,0,1,-1,-1,false}:unavailable; + if(mode==Mode::verifiedAsioRestart && + (!isAsio4All(live) || saved.backend!=live.backend || saved.playback!=live.playback)) + return unavailable; + if(mode==Mode::verifiedAsioRestart && saved.outputNames.isEmpty())return unavailable; auto outputs=document.outputs; outputs.activeOutputChannels=count; - if(saved.outputMask!=live.outputMask) { - const auto oldPins=mask(saved.outputMask); - const auto newPins=mask(live.outputMask); - outputs.mainL=remapPin(oldPins,newPins,outputs.mainL); - outputs.mainR=remapPin(oldPins,newPins,outputs.mainR); + const auto oldPins=mask(saved.outputMask),newPins=mask(live.outputMask); + if(mode!=Mode::exact || saved.outputMask!=live.outputMask) { + const auto remap=[&](int ordinal) { + return remapPin(oldPins,newPins,saved.outputNames,live.outputNames, + ordinal,live.backend=="ASIO"); + }; + outputs.mainL=remap(outputs.mainL); + outputs.mainR=remap(outputs.mainR); if(outputs.monitorEnabled) { - outputs.monitorL=remapPin(oldPins,newPins,outputs.monitorL); - outputs.monitorR=remapPin(oldPins,newPins,outputs.monitorR); + outputs.monitorL=remap(outputs.monitorL); + outputs.monitorR=remap(outputs.monitorR); } } if(!outputs.valid()) { outputs.monitorL=outputs.monitorR=-1; outputs.monitorEnabled=false; } - // Never substitute the first available pair when the saved MAIN - // physical connectors disappear. Audio may only return after the - // operator explicitly patches MAIN to available output pins. + // An explicit Apply can adopt the sole coherent physical pair that + // ASIO4ALL now exposes. An unsolicited restart can only resume the + // original named MAIN pair, even if another pair is now available. + if(!outputs.valid() && mode==Mode::verifiedDeviceApply && + isAsio4All(live) && count==2 && isNamedSpeakerPair(newPins,live.outputNames)) + return {count,0,1,-1,-1,false}; return outputs; } static juce::String apply(MixerSessionDocument& document, const HardwareBinding& live, const VerifiedNativeOutputs& outputs, int callbackInputs,Mode mode) { - if(!outputs.valid() || callbackInputs<0 || callbackInputs>256 || + if(callbackInputs<0 || callbackInputs>256 || live.backend.isEmpty() || (callbackInputs>0 && live.capture.isEmpty()) || live.playback.isEmpty() || live.inputMask.isEmpty() || @@ -115,6 +131,8 @@ struct MixerDeviceBindingPolicy final { live.rate<8000. || live.rate>384000. || live.frames<16 || live.frames>8192) return "NEEDS_REMAP: live device verification incomplete"; + if(!outputs.valid()) + return "NEEDS_REMAP: saved MAIN pair unavailable on the active playback pins"; const auto oldPins=mask(document.binding.inputMask); const auto newPins=mask(live.inputMask); if(oldPins.countNumberOfSetBits()!=document.request.physicalInputs || @@ -135,7 +153,7 @@ struct MixerDeviceBindingPolicy final { // ordinals; it never authorizes quietly switching MAIN to another // jack. Compare against the policy-computed remap even when a caller // supplies a valid but DIFFERENT output pair. - if(mode==Mode::verifiedMainPinApply || + if(mode==Mode::verifiedMainPinApply || mode==Mode::verifiedAsioRestart || (saved.backend==live.backend && saved.playback==live.playback)) { const auto mapped=proposedOutputs(document,live,outputs.activeOutputChannels,mode); if(!mapped.valid() || !sameOutputs(mapped,outputs)) @@ -143,19 +161,27 @@ struct MixerDeviceBindingPolicy final { } auto& sources=document.request.sources; - if(saved.backend!=live.backend || saved.capture!=live.capture || - !samePinNames(saved.inputNames,live.inputNames,live.backend)) { + if(saved.backend!=live.backend || saved.capture!=live.capture) { + if(mode==Mode::verifiedAsioRestart && !sources.empty()) + return "NEEDS_REMAP: waiting for the previous ASIO capture endpoint"; // Matching pin numbers alone cannot identify another capture source. sources.clear(); - } else if(oldPins!=newPins) { + } else if(oldPins!=newPins || saved.inputNames!=live.inputNames || + (live.backend=="ASIO" && saved.inputNames.isEmpty())) { std::vector mapped; mapped.reserve(sources.size()); for(auto source:sources) { - source.inputL=remapPin(oldPins,newPins,source.inputL); - if(source.stereo)source.inputR=remapPin(oldPins,newPins,source.inputR); + const auto remap=[&](int ordinal) { + return remapPin(oldPins,newPins,saved.inputNames,live.inputNames, + ordinal,live.backend=="ASIO"); + }; + source.inputL=remap(source.inputL); + if(source.stereo)source.inputR=remap(source.inputR); if(source.inputL>=0 && (!source.stereo || source.inputR>=0)) mapped.push_back(source); } + if(mode==Mode::verifiedAsioRestart && mapped.size()!=sources.size()) + return "NEEDS_REMAP: waiting for the previous ASIO capture pins"; sources=std::move(mapped); } document.request.physicalInputs=callbackInputs; @@ -164,21 +190,47 @@ struct MixerDeviceBindingPolicy final { return {}; } private: - static bool samePinNames(const juce::StringArray& saved,const juce::StringArray& live, - const juce::String& backend) { - return saved.isEmpty()?backend!="ASIO":saved==live; - } static juce::BigInteger mask(const juce::String& text) { juce::BigInteger bits; bits.parseString(text,16); return bits; } - static int remapPin(const juce::BigInteger& saved,const juce::BigInteger& current,int ordinal) { + static bool isNamedSpeakerPair(const juce::BigInteger& pins,const juce::StringArray& names) { + const auto left=names[pins.findNextSetBit(0)].trim().toLowerCase(); + const auto right=names[pins.getHighestBit()].trim().toLowerCase(); + return left.endsWith(" 1") && right.endsWith(" 2") && + left.dropLastCharacters(2)==right.dropLastCharacters(2) && + !left.contains("vb-audio") && !left.contains("cable") && + !left.contains("virtual") && !left.contains("loopback") && + (left.contains("realtek") || left.contains("speaker") || left.contains("output with sst")); + } + static int findSamePin(const juce::StringArray& previous,const juce::StringArray& live,int pin) { + const auto name=previous[pin]; + if(name.isEmpty() || previous.indexOf(name)!=pin || + previous.indexOf(name,false,pin+1)>=0)return -1; + const auto next=live.indexOf(name); + return next>=0 && live.indexOf(name,false,next+1)<0?next:-1; + } + static int remapPin(const juce::BigInteger& saved,const juce::BigInteger& current, + const juce::StringArray& savedNames,const juce::StringArray& currentNames, + int ordinal,bool requireNames) { if(ordinal<0)return -1; int physical=saved.findNextSetBit(0); for(int i=0;i=0;++i) physical=saved.findNextSetBit(physical+1); - if(physical<0 || !current[physical])return -1; + if(physical<0)return -1; + if(savedNames!=currentNames || requireNames) { + const auto name=savedNames[physical]; + if(name.isEmpty()) { + // Old documents without a label inventory can keep the + // exact mask. They cannot identify a newly numbered pin. + if(!savedNames.isEmpty() || (requireNames && saved!=current))return -1; + } else { + physical=findSamePin(savedNames,currentNames,physical); + if(physical<0)return -1; + } + } + if(!current[physical])return -1; int index=0; for(int pin=current.findNextSetBit(0);pinsize\(\)!=2/); assert.match(main,/restoreSavedMixerSession\(false,bindingMode\)/); + assert.match(apply,/if\(refreshedAsio4All\) \{[\s\S]*?openSelectedAudioDevice\(typeName,candidate,true\)/); + assert.match(main,/epoch==asioRecoveryEpoch_/); + assert.match(main,/authorizeRetainedAsioRestart\(\)[\s\S]*?restoreSavedMixerSession\(false,MixerBindingMode::verifiedAsioRestart\)/); }); test('SETUP1 honest bus patch has real AUX/MAIN/MONITOR navigation, no fake GROUP DCA',()=>{ diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index 5e9d56fb8..9d6fd7abf 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -307,6 +307,31 @@ static void nativeDeviceRecovery() { assert(current.inserts.size()==1 && current.inserts[0].catalogId==eqId); current.binding=saved.binding; + // Render actual PCM after a sparse ASIO4ALL re-enumeration. Two compact + // callbacks now address physical pins 2 and 3, with MAIN L at ordinal 1. + auto aggregate=current; + aggregate.binding={"ASIO","ASIO4ALL v2","ASIO4ALL v2","3","3",48000.,480, + {"VB-Audio Point 1","VB-Audio Point 2"},{"2nd output with SST 1","2nd output with SST 2"}}; + auto reenumerated=aggregate.binding; + reenumerated.inputMask=reenumerated.outputMask="6"; + reenumerated.inputNames.insert(0,"Other capture"); + reenumerated.outputNames={"Other playback","2nd output with SST 2","2nd output with SST 1"}; + const auto asioPair=MixerDeviceBindingPolicy::proposedOutputs( + aggregate,reenumerated,2,BindingMode::verifiedAsioRestart); + assert(MixerDeviceBindingPolicy::apply(aggregate,reenumerated,asioPair,2, + BindingMode::verifiedAsioRestart).isEmpty()); + mixer.deviceStopped(); + device.inputMask.setBit(2);device.inputMask.clearBit(0); + device.outputMask=device.inputMask; + mixer.prepareDevice(&device); + assert(restore(aggregate,currentStates,true).isEmpty()); + process(true); + assert(outL.back()==0.f && outR.back()==0.f); + process(false); + assert(outL.back()>.02f && outR.back()>outL.back()+.01f); + device.inputMask.clearBit(2);device.inputMask.setBit(0); + device.outputMask=device.inputMask; + // The field failure switched Realtek playback to HDMI while keeping the // same VB-Cable source and a live FX rack. The new epoch has working PCM, // existing WIRE IDs and a repatchable ChannelId graph after one Apply. @@ -533,7 +558,61 @@ int main(){ BindingMode::exact).isNotEmpty()); assert(MixerDeviceBindingPolicy::apply(reordered,reorderedPins,d.outputs,2, BindingMode::verifiedDeviceApply).isEmpty()); - assert(reordered.request.sources.empty()); + assert(reordered.request.sources.size()==d.request.sources.size()); + assert(reordered.request.sources.front().inputL==1); + assert(reordered.request.sources.front().inputR==-1); + + // ASIO4ALL can reorder the VB-Cable input and the Realtek pair even + // though JUCE still reports the same registered driver name. + auto asio=d; + asio.binding.backend="ASIO"; + asio.request.sources.front().stereo=true; + asio.request.sources.front().inputR=1; + asio.binding.capture=asio.binding.playback="ASIO4ALL v2"; + asio.binding.inputNames={"VB-Audio Point 1","VB-Audio Point 2"}; + asio.binding.outputNames={"2nd output with SST 1","2nd output with SST 2"}; + asio.binding.outputMask="3"; + asio.outputs={2,0,1,-1,-1,false}; + auto shifted=asio.binding; + shifted.inputNames={"New input","VB-Audio Point 1","VB-Audio Point 2"}; + shifted.inputMask="6"; + shifted.outputNames={"New output","2nd output with SST 2","2nd output with SST 1"}; + shifted.outputMask="6"; + const auto shiftedPair=MixerDeviceBindingPolicy::proposedOutputs(asio,shifted,2, + BindingMode::verifiedAsioRestart); + assert(shiftedPair.valid() && shiftedPair.mainL==1 && shiftedPair.mainR==0); + auto shiftedSession=asio; + assert(MixerDeviceBindingPolicy::apply(shiftedSession,shifted,shiftedPair,2, + BindingMode::verifiedAsioRestart).isEmpty()); + assert(shiftedSession.request.sources.front().inputL==0); + assert(shiftedSession.request.sources.front().inputR==1); + assert(shiftedSession.roster.revision()==asio.roster.revision()); + juce::BigInteger oldCapturePins; + oldCapturePins.setRange(0,2,true); + const auto translated=MixerDeviceBindingPolicy::translateNamedPins( + oldCapturePins,asio.binding.inputNames,shifted.inputNames); + assert(translated && translated->toString(16)=="6"); + auto temporarilyUnavailable=shifted; + temporarilyUnavailable.inputMask="3"; + assert(MixerDeviceBindingPolicy::apply(asio,temporarilyUnavailable,shiftedPair,2, + BindingMode::verifiedAsioRestart).contains("previous ASIO capture pins")); + assert(asio.binding.inputMask=="3" && asio.request.sources.front().inputR==1); + + auto nextSpeaker=asio.binding; + nextSpeaker.outputNames={"Realtek HD Audio output with SST 1","Realtek HD Audio output with SST 2"}; + assert(!MixerDeviceBindingPolicy::proposedOutputs(asio,nextSpeaker,2, + BindingMode::verifiedAsioRestart).valid()); + const auto newlyApproved=MixerDeviceBindingPolicy::proposedOutputs(asio,nextSpeaker,2, + BindingMode::verifiedDeviceApply); + assert(newlyApproved.valid() && newlyApproved.mainL==0 && newlyApproved.mainR==1); + auto virtualCable=nextSpeaker; + virtualCable.outputNames={"VB-Audio Point 1","VB-Audio Point 2"}; + assert(!MixerDeviceBindingPolicy::proposedOutputs(asio,virtualCable,2, + BindingMode::verifiedDeviceApply).valid()); + auto duplicatePins=shifted; + duplicatePins.outputNames.add("2nd output with SST 1"); + assert(!MixerDeviceBindingPolicy::proposedOutputs(asio,duplicatePins,2, + BindingMode::verifiedAsioRestart).valid()); auto exact=d; assert(MixerDeviceBindingPolicy::apply(exact,d.binding,d.outputs,2,BindingMode::exact) .isEmpty()); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 1747fec56..7cf291e3b 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1786,8 +1786,11 @@ }else pins.textContent="Apply this device first to inspect its real enabled pins."; } const activeText=devicePanel.querySelector("[data-audio-active]"); + const mainPins=Array.isArray(active.mainOutputs)?active.mainOutputs + .map(pin=>active.outputNames?.[pin]).filter(Boolean):[]; if(activeText && !deviceBusy)activeText.textContent=deviceResult||(active.open? - "ACTIVE · "+active.backend+" · "+active.rate+" Hz / "+active.buffer+" samples": + "ACTIVE · "+active.backend+" · "+active.rate+" Hz / "+active.buffer+" samples"+ + (mainPins.length===2?" · MAIN "+mainPins.join(" / "):""): "No verified audio device. Select a supported input and output."); devicePanel.querySelector("[data-audio-apply]").disabled=deviceBusy|| !deviceChoice.backend||(!t?.separate&&!deviceChoice.capture)|| From 6285f80b5286c70b2b1bd1c79828f9332633b08e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 20:16:04 +0700 Subject: [PATCH 18/26] Validate ASIO recovery in the complete Windows contract suite --- tests/independent_clock_adapter_contract_test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/independent_clock_adapter_contract_test.mjs b/tests/independent_clock_adapter_contract_test.mjs index 8d113a649..705cb1be9 100644 --- a/tests/independent_clock_adapter_contract_test.mjs +++ b/tests/independent_clock_adapter_contract_test.mjs @@ -161,7 +161,7 @@ test('P0 ASIO live direct route fence blocks hotplug substitution before DSP',() assert.match(engine,/directSuppressedFrames_\.fetch_add/); assert.match(engine,/directRouteProtection/); assert.match(host,/engine_\.beginManualAudioSetup\(\)/); - assert.match(host,/engine_\.finishManualAudioSetup\(\)/); + assert.match(host,/engine_\.finishManualAudioSetup\(bindingMode!=MixerBindingMode::verifiedMainPinApply\)/); assert.match(host,/engine_\.directRouteAuthorized\(\)/); }); From 5a923a7dd84824759bf8fcdfa5ef4280baa33d2f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 20:56:27 +0700 Subject: [PATCH 19/26] Keep ASIO4ALL mixer and FX live when capture disappears Recover playback independently, remember missing inputs by physical identity, and restore them automatically when the driver returns. Preserve compatible VST3 leases and persist pin inventories in existing mixer sessions. --- src/LiveAudioEngine.h | 58 +++++-- src/LiveDryRoutingLab.h | 36 ++++ src/Main.cpp | 59 +++++-- src/NativeMixerSessionDocument.h | 188 +++++++++++++++------ tests/approved_native_cold_start_smoke.py | 6 +- tests/approved_native_m2_contract.test.cjs | 2 +- tests/live_graph_contract_test.mjs | 2 +- tests/native_mixer_session_store_test.cpp | 65 ++++++- web/approved-native-bridge.js | 11 +- 9 files changed, 324 insertions(+), 103 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index ba6525b18..106253e3d 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -190,6 +190,20 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Prefer both input pins on a verified stereo endpoint; saved explicit // channel masks still take precedence. Outputs remain DISARMED. auto error = deviceManager_.initialise (2, 2, savedSettings, !savedRoute); + if(savedAsioPreflight && (error.isNotEmpty() || !deviceManager_.getCurrentAudioDevice() || + deviceManager_.getCurrentAudioDevice()->getActiveOutputChannels().countNumberOfSetBits()<2)) { + auto fallback=*savedSettings; + auto name=fallback.getStringAttribute("audioDeviceName"); + if(name.isEmpty())name=fallback.getStringAttribute("audioOutputDeviceName"); + if(name.startsWithIgnoreCase("ASIO4ALL")) { + const bool captureDisabled=fallback.getStringAttribute("audioDeviceInChans")=="0"; + if(!captureDisabled)fallback.removeAttribute("audioDeviceInChans"); + fallback.removeAttribute("audioDeviceOutChans"); + deviceManager_.closeAudioDevice(); + error=deviceManager_.initialise(2,2,&fallback,false); + } + } + #if defined(_WIN32) if (error.isNotEmpty() && !savedRoute && deviceManager_.singleAsioPreferred()) { @@ -394,9 +408,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Native AUDIO SETUP is the explicit user authorization boundary. // Suppress any live output while selecting/changing a device, even if JUCE // starts its new callback before the selector window is closed. - void beginManualAudioSetup() noexcept { + void beginManualAudioSetup(bool preserveMonitorIntent=false) noexcept { offeredWasapiBinding_.reset(); - resumeMainAfterAsioReset_.store(false,std::memory_order_release); + if(!preserveMonitorIntent)resumeMainAfterAsioReset_.store(false,std::memory_order_release); + else if(isMonitorEnabled())resumeMainAfterAsioReset_.store(true,std::memory_order_release); setOutputMuted(true); secondaryOutput_.disarm(); directFence_.suspend(); @@ -447,6 +462,15 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } // The JUCE ASIO device may restart itself after a control panel change. // Reauthorize only the previously approved driver class and session. + bool sameRetainedAsioDriver() { + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device || !acceptedMixerBinding_ || !asioPinnedRegistration_.valid() || + device->getTypeName()!="ASIO" || device->getName()!=acceptedMixerBinding_->playback)return false; + const auto registered=armix::device::AsioRegistryIdentityProbe::resolve( + std::wstring(device->getName().toWideCharPointer())); + return registered.registration.ok() && + asioPinnedRegistration_.sameDriverClass(registered.registration.identity); + } bool authorizeRetainedAsioRestart() { using Policy=armix::session::MixerDeviceBindingPolicy; if(!hasRetainedNativeSession() || !acceptedMixerBinding_ || @@ -484,9 +508,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback }; const bool input=correct(previous.inputMask,previous.inputNames,live.inputNames, setup.inputChannels,setup.useDefaultInputChannels); + const bool returning=Policy::addReturningCapturePins( + dryRoutingLab_.waitingAsioInputs(),live.inputNames,setup.inputChannels); const bool output=correct(previous.outputMask,previous.outputNames,live.outputNames, setup.outputChannels,setup.useDefaultOutputChannels); - if(!input && !output)return {}; + if(!input && !output && !returning)return {}; setup.useDefaultInputChannels=false; setup.useDefaultOutputChannels=false; return setup; @@ -496,20 +522,17 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if(!acceptedMixerBinding_ || !Policy::isAsio4All(*acceptedMixerBinding_) || !hasRetainedNativeSession() || !allOutputsDisarmed() || !directFence_.permitted() || handoff_.busy())return false; - const auto* previous=&*acceptedMixerBinding_; - auto* device=deviceManager_.getCurrentAudioDevice(); - if(!device || !device->isOpen())return false; - const auto epoch=dryRoutingLab_.epoch(); - const auto live=readMixerBinding(*device); - armix::device::JuceActivePortSnapshot pins; - armix::device::JuceActivePortSnapshot::Fault fault{}; - if(!Policy::sameBinding(*previous,live) || previous->inputNames!=live.inputNames || - previous->outputNames.isEmpty() || previous->outputNames!=live.outputNames || - !armix::device::JuceActivePortSnapshot::capture(device,epoch,pins,fault) || - !dryRoutingLab_.matchesSessionDevice(pins) || - !dryRoutingLab_.rebindVerifiedDevice(dryRoutingLab_.retainedNativeEpoch(), - epoch,live.frames,false))return false; - acceptedMixerBinding_=live; + armix::session::MixerSessionDocument document; + if(!dryRoutingLab_.describeRetainedAsioSession(document))return false; + document.binding=*acceptedMixerBinding_; + MixerBindingInspection inspected; + constexpr auto mode=Policy::Mode::verifiedAsioRestart; + if(inspectNativeMixerSessionBinding(document,inspected,mode).isNotEmpty() || + inspected.live.rate!=document.binding.rate || + Policy::apply(document,inspected.live,inspected.outputs,inspected.callbackInputs,mode).isNotEmpty() || + !dryRoutingLab_.rebindRetainedAsioSession(std::move(document),inspected.pins, + inspected.live.frames))return false; + acceptedMixerBinding_=std::move(inspected.live); return true; } bool takeAsioResetMonitorIntent() noexcept { @@ -2175,6 +2198,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback : deviceManager_.getCurrentAudioDevice(); auto* capture = dual ? independent_.captureDevice() : d; o->setProperty ("dryRoutingLab",dryRoutingLab_.status(capture)); + o->setProperty("waitingAsioInputs",dryRoutingLab_.waitingAsioInputCount()); // NORMAL mode is never silently served by the legacy CH1 fallback. // This state is for operator feedback; it does not authorize output. o->setProperty ("productionRoutingState", diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 21ae5578b..2c639ba61 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1759,6 +1759,7 @@ class LiveDryRoutingLab final { nativeAccepted_.graph.request=std::move(request); nativeAccepted_.fxOwners=std::move(owner); nativeAccepted_.pcmRevision=published.revision; + std::erase_if(waitingAsioInputs_,[id](const auto& pin){return pin.id==id;}); nativeStructureLive_=true; nativeMeterEpoch_.store(0,std::memory_order_release); reply.accepted=true;reply.error=""; @@ -1845,6 +1846,7 @@ class LiveDryRoutingLab final { nativeAccepted_.graph.request=std::move(request); nativeAccepted_.fxOwners=std::move(owner); nativeAccepted_.pcmRevision=published.revision; + std::erase_if(waitingAsioInputs_,[channel](const auto& pin){return pin.id==channel;}); nativeStructureLive_=true; // M4 source roster no longer authoritative nativeMeterEpoch_.store(0,std::memory_order_release); reply.accepted=true;reply.error=""; @@ -2143,6 +2145,7 @@ class LiveDryRoutingLab final { draft.legacyIds=nativeAccepted_.graph.ids; draft.outputs=nativeAccepted_.hardware; draft.request=nativeAccepted_.graph.request; + draft.waitingAsioInputs=waitingAsioInputs_; std::vector staged; std::set hashes; juce::int64 total=0; @@ -2183,6 +2186,34 @@ class LiveDryRoutingLab final { } catch(...) {return "Native graph/VST3 state capture failed";} } + bool describeRetainedAsioSession(armix::session::MixerSessionDocument& document) const { + if(!hasRetainedNativeSession() || + !nativeAccepted_.matches(nativePublisher_,nativeAccepted_.deviceEpoch, + nativeAccepted_.pcmRevision))return false; + document.roster=nativeAccepted_.graph.roster; + document.request=nativeAccepted_.graph.request; + document.legacyIds=nativeAccepted_.graph.ids; + document.outputs=nativeAccepted_.hardware; + document.waitingAsioInputs=waitingAsioInputs_; + return true; + } + + bool rebindRetainedAsioSession(armix::session::MixerSessionDocument document, + const armix::device::JuceActivePortSnapshot& pins,int deviceFrames) { + const auto next=nativeGraphRevisionForRestore(); + const auto previous=document.request.maxFrames; + // Existing processors can still use their prepared quantum. Larger + // device blocks are split by the same render path used before reset. + document.request.maxFrames=armix::device::retainedMixerQuantum(previous, + deviceFrames,Block::hardFrameLimit,false,true); + if(!next || !document.request.maxFrames || !hasRetainedNativeSession())return false; + auto bank=std::make_shared(); + 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(); + } + // Match CONTROL's live device readback to the masks registered for the // actual callback epoch. Neither a saved document nor an M4 graph // attests which physical pins the current callback can address. @@ -2241,6 +2272,7 @@ class LiveDryRoutingLab final { nativeAccepted_.graph.roster=std::move(document.roster); nativeAccepted_.graph.request=std::move(document.request); nativeAccepted_.graph.ids=document.legacyIds; + waitingAsioInputs_=std::move(document.waitingAsioInputs); nativeAccepted_.graph.revision=nativeAccepted_.graph.roster.revision(); nativeAccepted_.hardware=document.outputs; nativeAccepted_.fxOwners=std::move(bank); @@ -2450,6 +2482,8 @@ class LiveDryRoutingLab final { nativeAccepted_.graph.request.sources.empty() && !hasAuthoredMixerContent(); } + std::span waitingAsioInputs() const noexcept {return waitingAsioInputs_;} + int waitingAsioInputCount() const noexcept {return static_cast(waitingAsioInputs_.size());} bool hasVerifiedNativeSources() const noexcept { return channelIdPhysicalPcmActive() && !nativeAccepted_.graph.request.sources.empty(); } @@ -2466,6 +2500,7 @@ class LiveDryRoutingLab final { nativeControlDirty_=false; nativePublisher_.unpublish(); // CONTROL-only; audio lease retires safely nativeAccepted_=armix::mixer::UnifiedLegacyAccepted{}; + waitingAsioInputs_.clear(); userPatched_.store(false,std::memory_order_release); enabled_.store(false,std::memory_order_release); publishedEpoch_.store(0,std::memory_order_release); @@ -3021,6 +3056,7 @@ class LiveDryRoutingLab final { return juce::var(out.release()); } private: + std::vector waitingAsioInputs_; // Four 9-bit callback indices (0 means absent) and the prepared quantum. // One atomic read gives AUDIO a coherent destination/quantum contract. std::atomic nativeHardware_{0}; diff --git a/src/Main.cpp b/src/Main.cpp index 196cfccf6..4381d86c9 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1000,8 +1000,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr (void) armix::console::projectRetainedNativeChannelIdGraph (accepted, live); // Sole control-thread SessionSnapshot from the installed PCM publisher. armix::console::publishAuthoritativeMixerSession(accepted); - if(auto* obj=accepted.getDynamicObject()) + if(auto* obj=accepted.getDynamicObject()) { obj->setProperty("channelAppearance",channelAppearance_.snapshot(accepted.getProperty("graph",{}))); + obj->setProperty("waitingAsioInputs",live.getProperty("waitingAsioInputs",0)); + } return accepted; } @@ -1308,6 +1310,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // One-shot on a verified setup or startup, including the first input // patch. A later device epoch or a user MUTE cancels the pending arm. std::uint64_t autoMainEpoch_=0; + bool autoMainRequiresInput_=true; std::optional autoMainCheckedRevision_; void serviceAutomaticMain() { if(autoMainEpoch_==0)return; @@ -1322,13 +1325,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(autoMainCheckedRevision_==revision)return; if(engine_.isGraphSwitchPending()||!engine_.hasBoundMixerRoute())return; autoMainCheckedRevision_=revision; - if(engine_.liveOutputArmFault().isNotEmpty())return; + if(engine_.liveOutputArmFault(autoMainRequiresInput_).isNotEmpty())return; engine_.setMonitorEnabled(true); autoMainEpoch_=0; diagnostics_.record("MAIN_AUTO_ENABLED","Verified device, input and MAIN output"); } - void requestAutomaticMain() { + void requestAutomaticMain(bool requireInput=true) { + autoMainRequiresInput_=requireInput; autoMainEpoch_=engine_.dryRoutingLabEpoch(); autoMainCheckedRevision_.reset(); serviceAutomaticMain(); @@ -1694,7 +1698,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Suspend physical output but retain ALL authored mixer state while // the real JUCE device selector is visible (including no-change close). autoMainEpoch_=0; - engine_.beginManualAudioSetup(); + engine_.beginManualAudioSetup(true); // The native JUCE device list is cached after first construction: // reopening the settings window avoids repeating full widget setup. @@ -1717,7 +1721,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (safe == nullptr) return; if (safe->finishAudioSetupAndRecoverMixer()) { - safe->requestAutomaticMain(); + safe->requestAutomaticMain(!safe->engine_.takeAsioResetMonitorIntent()); safe->deviceSettingsDirty_ = true; safe->startupError_.clear(); safe->diagnostics_.record ("DIRECT_ROUTE_APPROVED", @@ -1732,7 +1736,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr "No verified stereo playback device; audio remains gated"); safe->emitNotice ( safe->engine_.hasRetainedUnboundMixer() - ? "Mixer and plugin state retained. Device binding changed; output stays muted until a verified full-session rebind." + ? "Playback unavailable. Mixer and plugin settings are saved." : "Choose a working stereo output in Audio I/O. Input hardware is optional.", true); safe->emitApprovedNativeSnapshot(); } @@ -2307,8 +2311,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr diagnostics_.record("DYNAMIC_MIXER_VST3_REMAP_REQUIRED",error); return error; } + if(bindingMode==MixerBindingMode::exact && startupOnSavedDevice && + armix::session::MixerDeviceBindingPolicy::isAsio4All(doc.binding)) + bindingMode=MixerBindingMode::verifiedAsioRestart; const bool resume=startupOnSavedDevice && - bindingMode==armix::session::MixerDeviceBindingPolicy::Mode::exact && + (bindingMode==MixerBindingMode::exact || bindingMode==MixerBindingMode::verifiedAsioRestart) && !usedPrevious && !retained && doc.resumeMain.value_or(true); const auto live=engine_.status().getProperty("dryRoutingLab",{}); @@ -2339,7 +2346,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return error; } mixerSessionRecoveryPending_=false; - if(resume)requestAutomaticMain(); + if(resume)requestAutomaticMain(bindingMode!=MixerBindingMode::verifiedAsioRestart); mixerSessionStatus_=engine_.isMonitorEnabled()?"RESTORED_MONITORING":"RESTORED_MUTED"; mixerSessionError_.clear(); diagnostics_.record("DYNAMIC_MIXER_RESTORED",mixerSessionStatus_); @@ -4697,10 +4704,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr 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("Mixer retained; "+error,true); + emitNotice(error.startsWith("NEEDS_REMAP:")?error.fromFirstOccurrenceOf(": ",false,false):error,true); return false; } return true; @@ -4713,13 +4722,28 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto epoch=engine_.dryRoutingLabEpoch(); if(epoch==asioRecoveryEpoch_ || !engine_.hasRetainedNativeSession() || nativeShowBusy_ || studioBackupBusy_ || mixerSessionWorker_.busy() || catalog_.busy() || - engine_.isGraphSwitchPending() || - (audioSetupWindow_ && audioSetupWindow_->isVisible()))return; + engine_.isGraphSwitchPending() || engine_.independentClockActive() || + engine_.diagnosticRoute()!=armix::diagnostics::Route::normal)return; auto* device=engine_.devices().getCurrentAudioDevice(); - if(!device || !device->isOpen() || device->getTypeName()!="ASIO" || + if(!device || device->getTypeName()!="ASIO" || !device->getName().startsWithIgnoreCase("ASIO4ALL"))return; asioRecoveryEpoch_=epoch; // at most one automatic bind per negotiated epoch const juce::ScopedValueSetter applying(audioDeviceApplyActive_,true); + if(!engine_.sameRetainedAsioDriver())return; + if(!device->isOpen() || device->getActiveOutputChannels().countNumberOfSetBits()<2) { + juce::AudioDeviceManager::AudioDeviceSetup setup; + engine_.devices().getAudioDeviceSetup(setup); + setup.useDefaultInputChannels=true; + setup.useDefaultOutputChannels=true; + const auto error=openSelectedAudioDevice("ASIO",setup,true); + asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); + device=engine_.devices().getCurrentAudioDevice(); + if(error.isNotEmpty() || !device || !device->isOpen()) { + diagnostics_.record("ASIO4ALL_REOPEN_FAILED",error); + emitApprovedNativeSnapshot(); + return; + } + } if(!engine_.authorizeRetainedAsioRestart())return; if(const auto corrected=engine_.asioRestartPinCorrection()) { // One bounded correction for JUCE's restart with the old mask. @@ -4750,9 +4774,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } mixerSessionStatus_="RESTORED_MUTED"; mixerSessionError_.clear(); - if(engine_.takeAsioResetMonitorIntent())requestAutomaticMain(); + if(engine_.takeAsioResetMonitorIntent())requestAutomaticMain(false); if(engine_.isMonitorEnabled())mixerSessionStatus_="RESTORED_MONITORING"; - diagnostics_.record("ASIO4ALL_REATTACHED","Verified driver and original MAIN pair"); + diagnostics_.record("ASIO4ALL_REATTACHED","Verified driver and current MAIN pair"); emitApprovedNativeSnapshot(); } @@ -4837,11 +4861,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr mixerSessionRecoveryPending_=true; const auto error=restoreSavedMixerSession(startupError_.isEmpty()); if(error.isNotEmpty()) - emitNotice("Saved mixer retained; "+error,true); + emitNotice(error.startsWith("NEEDS_REMAP:")?error.fromFirstOccurrenceOf(": ",false,false):error,true); else deviceSettingsDirty_=true; }else if(startupError_.isEmpty())requestAutomaticMain(); } + serviceAsioMixerRestart(); // ONE actionable notice per unexpected DIRECT reroute. The audio // callback has already zero-filled output atomically; status, log and // WebView notifications belong only on this JUCE control timer. @@ -4855,13 +4880,13 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr unexpectedRouteNoticeSent_ = true; diagnostics_.record ("DIRECT_ROUTE_BLOCKED", "A device or backend changed unexpectedly; host output held at zero"); - emitNotice ("Audio device changed unexpectedly. Live output muted; confirm your ASIO/WASAPI device in AUDIO SETUP.", true); + if(!engine_.sameRetainedAsioDriver()) + emitNotice ("Audio device changed unexpectedly. Live output muted; confirm your ASIO/WASAPI device in AUDIO SETUP.", true); } if (!blocked) unexpectedRouteNoticeSent_ = false; // Audio thread publishes only fault flags. A bounded message-thread // restore transaction handles device failures without hot-plug spin. serviceDirectRestore(); - serviceAsioMixerRestart(); serviceAutomaticMain(); // Autosave only while ALL outputs are muted. Vendor-state reads // happen on CONTROL; disk commits run on ONE serialized IO worker. diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index 62f201b8b..281f3c27a 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -24,6 +25,12 @@ struct HardwareBinding final { // still decode without inventing an ASIO pin inventory. juce::StringArray inputNames,outputNames; }; +// A disconnected source has a physical identity but no live PCM ordinal. +struct WaitingAsioInput final { + ChannelId id{}; + int left=-1,right=-1; // physical pin indices, for legacy files without labels + juce::String leftName,rightName; +}; struct StoredInsert final { ChannelId channel{}; std::size_t slot=0; @@ -39,6 +46,7 @@ struct MixerSessionDocument final { LegacyChannelIds legacyIds{}; VerifiedNativeOutputs outputs{}; HardwareBinding binding{}; + std::vector waitingAsioInputs; std::vector inserts; std::vector rackBypassed; float masterGain=1.f; @@ -80,6 +88,18 @@ struct MixerDeviceBindingPolicy final { } return result; } + static bool addReturningCapturePins(std::span waiting, + const juce::StringArray& names,juce::BigInteger& mask) { + const auto previous=mask; + for(const auto& patch:waiting) { + const int left=uniquePin(names,patch.leftName); + const int right=uniquePin(names,patch.rightName); + if(left<0 || left>=64 || (patch.right>=0 && (right<0 || right>=64 || right==left)))continue; + mask.setBit(left); + if(patch.right>=0)mask.setBit(right); + } + return mask!=previous; + } static VerifiedNativeOutputs proposedOutputs(const MixerSessionDocument& document, const HardwareBinding& live,int count,Mode mode=Mode::exact) { const auto& saved=document.binding; @@ -91,7 +111,6 @@ struct MixerDeviceBindingPolicy final { if(mode==Mode::verifiedAsioRestart && (!isAsio4All(live) || saved.backend!=live.backend || saved.playback!=live.playback)) return unavailable; - if(mode==Mode::verifiedAsioRestart && saved.outputNames.isEmpty())return unavailable; auto outputs=document.outputs; outputs.activeOutputChannels=count; const auto oldPins=mask(saved.outputMask),newPins=mask(live.outputMask); @@ -111,10 +130,9 @@ struct MixerDeviceBindingPolicy final { outputs.monitorL=outputs.monitorR=-1; outputs.monitorEnabled=false; } - // An explicit Apply can adopt the sole coherent physical pair that - // ASIO4ALL now exposes. An unsolicited restart can only resume the - // original named MAIN pair, even if another pair is now available. - if(!outputs.valid() && mode==Mode::verifiedDeviceApply && + // The same approved ASIO4ALL driver can expose a different speaker + // after a WDM selection. Adopt the sole verified physical pair. + if(!outputs.valid() && (mode==Mode::verifiedDeviceApply || mode==Mode::verifiedAsioRestart) && isAsio4All(live) && count==2 && isNamedSpeakerPair(newPins,live.outputNames)) return {count,0,1,-1,-1,false}; return outputs; @@ -148,41 +166,57 @@ struct MixerDeviceBindingPolicy final { return exact?juce::String{}:juce::String( "NEEDS_REMAP: select the saved audio device and pin layout in Audio I/O"); - // An Apply of the SAME playback endpoint must keep the saved - // physical MAIN connectors. The current mask only changes their - // ordinals; it never authorizes quietly switching MAIN to another - // jack. Compare against the policy-computed remap even when a caller - // supplies a valid but DIFFERENT output pair. if(mode==Mode::verifiedMainPinApply || mode==Mode::verifiedAsioRestart || (saved.backend==live.backend && saved.playback==live.playback)) { const auto mapped=proposedOutputs(document,live,outputs.activeOutputChannels,mode); if(!mapped.valid() || !sameOutputs(mapped,outputs)) - return "NEEDS_REMAP: saved MAIN output pins are no longer selected; explicitly choose MAIN outputs"; + return "NEEDS_REMAP: MAIN does not match the verified playback pair"; } auto& sources=document.request.sources; - if(saved.backend!=live.backend || saved.capture!=live.capture) { - if(mode==Mode::verifiedAsioRestart && !sources.empty()) - return "NEEDS_REMAP: waiting for the previous ASIO capture endpoint"; - // Matching pin numbers alone cannot identify another capture source. + if(isAsio4All(saved) && isAsio4All(live) && saved.playback==live.playback) { + // Binding playback is independent of capture. Keep the user's + // patch by physical identity until the selected input returns. + auto desired=std::move(document.waitingAsioInputs); + desired.reserve(desired.size()+sources.size()); + for(const auto& source:sources) { + const auto left=physicalAt(oldPins,source.inputL); + const auto right=physicalAt(oldPins,source.inputR); + desired.push_back({source.id,left,right, + saved.inputNames[left],saved.inputNames[right]}); + } sources.clear(); - } else if(oldPins!=newPins || saved.inputNames!=live.inputNames || - (live.backend=="ASIO" && saved.inputNames.isEmpty())) { - std::vector mapped; - mapped.reserve(sources.size()); - for(auto source:sources) { - const auto remap=[&](int ordinal) { - return remapPin(oldPins,newPins,saved.inputNames,live.inputNames, - ordinal,live.backend=="ASIO"); + document.waitingAsioInputs.clear(); + for(auto& source:desired) { + const auto* channel=document.roster.find(source.id); + if(!channel || channel->role!=ChannelRole::input)continue; + const auto resolve=[&](int previous,const juce::String& label) { + const auto pin=label.isEmpty()?previous:uniquePin(live.inputNames,label); + return callbackAt(newPins,pin); }; - source.inputL=remap(source.inputL); - if(source.stereo)source.inputR=remap(source.inputR); - if(source.inputL>=0 && (!source.stereo || source.inputR>=0)) - mapped.push_back(source); + const auto left=resolve(source.left,source.leftName); + const auto right=resolve(source.right,source.rightName); + const bool stereo=source.right>=0; + if(left>=0 && (!stereo || (right>=0 && left!=right))) + sources.push_back({source.id,left,right,stereo}); + else + document.waitingAsioInputs.push_back(std::move(source)); + } + } else { + document.waitingAsioInputs.clear(); + if(saved.backend!=live.backend || saved.capture!=live.capture) { + sources.clear(); + } else if(oldPins!=newPins || saved.inputNames!=live.inputNames) { + std::vector mapped; + mapped.reserve(sources.size()); + for(auto source:sources) { + source.inputL=remapPin(oldPins,newPins,saved.inputNames,live.inputNames,source.inputL,false); + if(source.stereo) + source.inputR=remapPin(oldPins,newPins,saved.inputNames,live.inputNames,source.inputR,false); + if(source.inputL>=0 && (!source.stereo || source.inputR>=0))mapped.push_back(source); + } + sources=std::move(mapped); } - if(mode==Mode::verifiedAsioRestart && mapped.size()!=sources.size()) - return "NEEDS_REMAP: waiting for the previous ASIO capture pins"; - sources=std::move(mapped); } document.request.physicalInputs=callbackInputs; document.binding=live; @@ -198,43 +232,49 @@ struct MixerDeviceBindingPolicy final { static bool isNamedSpeakerPair(const juce::BigInteger& pins,const juce::StringArray& names) { const auto left=names[pins.findNextSetBit(0)].trim().toLowerCase(); const auto right=names[pins.getHighestBit()].trim().toLowerCase(); - return left.endsWith(" 1") && right.endsWith(" 2") && + const auto leftPin=pins.findNextSetBit(0),rightPin=pins.getHighestBit(); + return uniquePin(names,names[leftPin])==leftPin && + uniquePin(names,names[rightPin])==rightPin && + left.endsWith(" 1") && right.endsWith(" 2") && left.dropLastCharacters(2)==right.dropLastCharacters(2) && !left.contains("vb-audio") && !left.contains("cable") && !left.contains("virtual") && !left.contains("loopback") && (left.contains("realtek") || left.contains("speaker") || left.contains("output with sst")); } + static int uniquePin(const juce::StringArray& names,const juce::String& name) { + if(name.isEmpty())return -1; + const auto pin=names.indexOf(name); + return pin>=0 && names.indexOf(name,false,pin+1)<0?pin:-1; + } static int findSamePin(const juce::StringArray& previous,const juce::StringArray& live,int pin) { const auto name=previous[pin]; - if(name.isEmpty() || previous.indexOf(name)!=pin || - previous.indexOf(name,false,pin+1)>=0)return -1; - const auto next=live.indexOf(name); - return next>=0 && live.indexOf(name,false,next+1)<0?next:-1; + return uniquePin(previous,name)==pin?uniquePin(live,name):-1; + } + static int physicalAt(const juce::BigInteger& mask,int ordinal) { + if(ordinal<0)return -1; + int pin=mask.findNextSetBit(0); + for(int i=0;i=0;++i)pin=mask.findNextSetBit(pin+1); + return pin; + } + static int callbackAt(const juce::BigInteger& mask,int physical) { + if(physical<0 || !mask[physical])return -1; + int index=0; + for(int pin=mask.findNextSetBit(0);pin=0;++i) - physical=saved.findNextSetBit(physical+1); + int physical=physicalAt(saved,ordinal); if(physical<0)return -1; if(savedNames!=currentNames || requireNames) { - const auto name=savedNames[physical]; - if(name.isEmpty()) { - // Old documents without a label inventory can keep the - // exact mask. They cannot identify a newly numbered pin. - if(!savedNames.isEmpty() || (requireNames && saved!=current))return -1; + if(savedNames.isEmpty()) { + if(requireNames && saved!=current)return -1; } else { physical=findSamePin(savedNames,currentNames,physical); - if(physical<0)return -1; } } - if(!current[physical])return -1; - int index=0; - for(int pin=current.findNextSetBit(0);pinsetProperty(k,v); } + static juce::var pinNames(const juce::StringArray& names) { + juce::Array values; + for(const auto& name:names)values.add(name); + return juce::var(values); + } + static bool readPinNames(const juce::var& value,juce::StringArray& names) { + const auto* values=value.getArray(); + if(!values || values->size()>256)return false; + for(const auto& entry:*values) { + juce::String name; + if(!textField(entry,name,256,true))return false; + names.add(name); + } + return true; + } static juce::var ids(const LegacyChannelIds& ids) { auto v=object(); juce::Array in,aux; @@ -315,7 +370,20 @@ class Codec final { set(bind,"outputMask",d.binding.outputMask); set(bind,"rate",d.binding.rate); set(bind,"frames",d.binding.frames); + if(!d.binding.inputNames.isEmpty())set(bind,"inputNames",pinNames(d.binding.inputNames)); + if(!d.binding.outputNames.isEmpty())set(bind,"outputNames",pinNames(d.binding.outputNames)); set(root,"binding",bind); + if(!d.waitingAsioInputs.empty()) { + juce::Array waiting; + for(const auto& pin:d.waitingAsioInputs) { + auto entry=object(); + set(entry,"id",decimal(pin.id.value)); + set(entry,"left",pin.left);set(entry,"right",pin.right); + set(entry,"leftName",pin.leftName);set(entry,"rightName",pin.rightName); + waiting.add(entry); + } + set(root,"waitingAsioInputs",juce::var(waiting)); + } auto output=object(); set(output,"active",d.outputs.activeOutputChannels); set(output,"mainL",d.outputs.mainL);set(output,"mainR",d.outputs.mainR); @@ -412,6 +480,10 @@ class Codec final { doc.binding.rate=n; if(!integral(get(binding,"frames"),doc.binding.frames,16,8192)) return false; + if((binding.getDynamicObject()->hasProperty("inputNames") && + !readPinNames(get(binding,"inputNames"),doc.binding.inputNames)) || + (binding.getDynamicObject()->hasProperty("outputNames") && + !readPinNames(get(binding,"outputNames"),doc.binding.outputNames)))return false; auto outputs=get(root,"outputs"); if(!integral(get(outputs,"active"),doc.outputs.activeOutputChannels,2,256)|| !integral(get(outputs,"mainL"),doc.outputs.mainL,0,255)|| @@ -506,6 +578,22 @@ class Codec final { return false; doc.request.sources.push_back(p); } + if(root.getDynamicObject()->hasProperty("waitingAsioInputs")) { + const auto waiting=get(root,"waitingAsioInputs"); + const auto* entries=waiting.getArray(); + if(!entries || entries->size()>channels->size() || + !MixerDeviceBindingPolicy::isAsio4All(doc.binding))return false; + for(const auto& entry:*entries) { + WaitingAsioInput pin; + if(!parseDecimal(get(entry,"id"),pin.id.value) || + !seenSources.insert(pin.id.value).second || !seek(pin.id,ChannelRole::input) || + !integral(get(entry,"left"),pin.left,0,255) || + !integral(get(entry,"right"),pin.right,-1,255) || pin.left==pin.right || + !textField(get(entry,"leftName"),pin.leftName,256,true) || + !textField(get(entry,"rightName"),pin.rightName,256,true))return false; + doc.waitingAsioInputs.push_back(std::move(pin)); + } + } const auto fxVar=get(root,"inserts"),racksVar=get(root,"rackBypassed"); const auto* fx=fxVar.getArray(); const auto* racks=racksVar.getArray(); diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index 9d0a0fec9..9448a846a 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -280,16 +280,16 @@ def show_select(value): channels=copy.deepcopy(retained['graph']['channels'])) emit(page,'arMixConsoleSnapshot',retained) page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__.state().current?.retained') - assert page.locator('.status-bar .warning').inner_text().startswith('NEEDS REMAP') + assert page.locator('.status-bar .warning').inner_text().startswith('PLAYBACK UNAVAILABLE') assert page.locator('[data-native-monitor]').is_disabled() assert add_track.is_disabled() assert page.locator('#tracks .strip').count()==4 - assert 'OUT NEEDS REMAP' in page.locator('#transport').inner_text() + assert 'OUTPUT WAITING FOR DEVICE' in page.locator('#transport').inner_text() page.locator('#tracks .strip[data-id="1"] .wire-node-out').click() emit(page,'arMixConsoleSnapshot',retained) assert page.locator('#tracks .strip[data-id="2"] .wire-gain').is_disabled() strip=page.locator('#tracks .strip[data-id="1"]') - assert strip.locator('select[data-field="input"]').input_value()=='NEEDS REMAP' + assert strip.locator('select[data-field="input"]').input_value()=='Waiting for device' assert strip.locator('.fx-section [data-action="openPlugin"]').first.inner_text()=='Latency VST' before=page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="routingFxEditor").length') strip.locator('.fx-section [data-action="openPlugin"]').first.click() diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 8617140bc..d033abd7f 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -707,7 +707,7 @@ test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ assert.match(engine,/MONITOR OFF: VB-Cable capture\/playback self-loop/); assert.match(bridge,/const virtualCableFeedbackPair=/); const native=read("src/Main.cpp"); - assert.match(native,/if\(engine_\.liveOutputArmFault\(\)\.isNotEmpty\(\)\)return;/); + assert.match(native,/if\(engine_\.liveOutputArmFault\(autoMainRequiresInput_\)\.isNotEmpty\(\)\)return;/); assert.match(native,/autoMainEpoch_!=engine_\.dryRoutingLabEpoch\(\)/); }); test("single /preview/ GUI: channel IN, actual OUT and correlated device safety ACK",()=>{ diff --git a/tests/live_graph_contract_test.mjs b/tests/live_graph_contract_test.mjs index 77df0958a..dad4468c4 100644 --- a/tests/live_graph_contract_test.mjs +++ b/tests/live_graph_contract_test.mjs @@ -195,7 +195,7 @@ test('R0B B3 preserves diagnostic isolation without exposing an accepted patch', assert.match(diagnostic,/dryRoutingLab_\.disable\(\)/); assert.match(diagnostic,/startUnpatchedProductionSession\(\)/); assert.match(diagnostic,/resumeVerifiedDirectRoute\(\)/); - const manual=e.slice(e.indexOf('void beginManualAudioSetup()'), + const manual=e.slice(e.indexOf('void beginManualAudioSetup('), e.indexOf('bool independentClockActive()')); assert.match(manual,/setOutputMuted\(true\)/); assert.match(manual,/secondaryOutput_\.disarm\(\)/); diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index 9d6fd7abf..01ed779b3 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -329,6 +329,34 @@ static void nativeDeviceRecovery() { assert(outL.back()==0.f && outR.back()==0.f); process(false); assert(outL.back()>.02f && outR.back()>outL.back()+.01f); + const auto reattachAsio=[&](const HardwareBinding& previous,const HardwareBinding& live) { + mixer.deviceStopped(); + mixer.prepareDevice(&device); + MixerSessionDocument draft; + assert(mixer.describeRetainedAsioSession(draft)); + draft.binding=previous; + const auto pair=MixerDeviceBindingPolicy::proposedOutputs(draft,live,2, + BindingMode::verifiedAsioRestart); + assert(MixerDeviceBindingPolicy::apply(draft,live,pair, + device.inputMask.countNumberOfSetBits(),BindingMode::verifiedAsioRestart).isEmpty()); + armix::device::JuceActivePortSnapshot pins; + armix::device::JuceActivePortSnapshot::Fault fault; + assert(armix::device::JuceActivePortSnapshot::capture(&device,mixer.epoch(),pins,fault)); + assert(mixer.rebindRetainedAsioSession(std::move(draft),pins,480)); + }; + auto noCapture=reenumerated; + noCapture.inputMask="0"; + device.inputMask.clear(); + reattachAsio(reenumerated,noCapture); + assert(mixer.channelIdPhysicalPcmActive() && mixer.waitingAsioInputCount()==1); + assert(mixer.setNativeInputMix(mixer.epoch(),mixer.controlRevision(),{1},.6f,0.f)); + process(false); + assert(outL.back()==0.f && outR.back()==0.f); + device.inputMask.setRange(1,2,true); + reattachAsio(noCapture,reenumerated); + assert(mixer.waitingAsioInputCount()==0); + process(false); + assert(outL.back()>.02f && outR.back()>outL.back()+.01f); device.inputMask.clearBit(2);device.inputMask.setBit(0); device.outputMask=device.inputMask; @@ -593,18 +621,37 @@ int main(){ oldCapturePins,asio.binding.inputNames,shifted.inputNames); assert(translated && translated->toString(16)=="6"); auto temporarilyUnavailable=shifted; - temporarilyUnavailable.inputMask="3"; - assert(MixerDeviceBindingPolicy::apply(asio,temporarilyUnavailable,shiftedPair,2, - BindingMode::verifiedAsioRestart).contains("previous ASIO capture pins")); - assert(asio.binding.inputMask=="3" && asio.request.sources.front().inputR==1); + temporarilyUnavailable.inputMask="0"; + auto waiting=shiftedSession; + assert(MixerDeviceBindingPolicy::apply(waiting,temporarilyUnavailable,shiftedPair,0, + BindingMode::verifiedAsioRestart).isEmpty()); + assert(waiting.request.physicalInputs==0 && waiting.request.sources.empty()); + assert(waiting.waitingAsioInputs.size()==1); + assert(waiting.roster.revision()==asio.roster.revision()); + assert(waiting.inserts.size()==asio.inserts.size()); + MixerSessionDocument reopenedWhileDisconnected; + assert(Codec::decode(Codec::encode(waiting),reopenedWhileDisconnected)); + assert(reopenedWhileDisconnected.binding.outputNames==shifted.outputNames); + assert(reopenedWhileDisconnected.waitingAsioInputs[0].leftName=="VB-Audio Point 1"); + juce::BigInteger returningMask; + assert(!MixerDeviceBindingPolicy::addReturningCapturePins( + reopenedWhileDisconnected.waitingAsioInputs,{"VB-Audio Point 1"},returningMask)); + assert(returningMask.isZero()); // a stereo half cannot open an unrelated capture + assert(MixerDeviceBindingPolicy::addReturningCapturePins( + reopenedWhileDisconnected.waitingAsioInputs,shifted.inputNames,returningMask)); + assert(returningMask.toString(16)=="6"); - auto nextSpeaker=asio.binding; + auto nextSpeaker=shifted; + nextSpeaker.outputMask="3"; nextSpeaker.outputNames={"Realtek HD Audio output with SST 1","Realtek HD Audio output with SST 2"}; - assert(!MixerDeviceBindingPolicy::proposedOutputs(asio,nextSpeaker,2, - BindingMode::verifiedAsioRestart).valid()); - const auto newlyApproved=MixerDeviceBindingPolicy::proposedOutputs(asio,nextSpeaker,2, - BindingMode::verifiedDeviceApply); + const auto newlyApproved=MixerDeviceBindingPolicy::proposedOutputs( + reopenedWhileDisconnected,nextSpeaker,2,BindingMode::verifiedAsioRestart); assert(newlyApproved.valid() && newlyApproved.mainL==0 && newlyApproved.mainR==1); + assert(MixerDeviceBindingPolicy::apply(reopenedWhileDisconnected,nextSpeaker,newlyApproved,2, + BindingMode::verifiedAsioRestart).isEmpty()); + assert(reopenedWhileDisconnected.waitingAsioInputs.empty()); + assert(reopenedWhileDisconnected.request.sources.front().inputL==0); + assert(reopenedWhileDisconnected.request.sources.front().inputR==1); auto virtualCable=nextSpeaker; virtualCable.outputNames={"VB-Audio Point 1","VB-Audio Point 2"}; assert(!MixerDeviceBindingPolicy::proposedOutputs(asio,virtualCable,2, diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 7cf291e3b..93909f452 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -598,7 +598,7 @@ Number.isInteger(p.port) && hardware.device.enabledInputs.includes(p.port)):[]; // BUS is verified engine state, not an available hardware input choice. const INTERNAL_BUS="Internal BUS (read-only)"; - const NEEDS_REMAP="NEEDS REMAP"; + const NEEDS_REMAP="Waiting for device"; const monoLabel=p=>"Mono · "+p.label+" [IN "+(p.port+1)+"]"; const stereoLabel=(a,b)=>"Stereo · IN "+(a.port+1)+" + "+(b.port+1); const inputChoicesFor=()=>{ @@ -1510,7 +1510,7 @@ scope.master.output=mainOutput; if(!next?.admitted && !next?.retained)scope.render?.(); } - const transport=next?.retained?"MONITOR OFF · OUT NEEDS REMAP": + const transport=next?.retained?"OUTPUT WAITING FOR DEVICE": !deviceOpen?"Audio device not ready": (d.outputArmed?"MONITOR ON":"MONITOR OFF")+" · OUT "+playback+ (virtualOut?" · VIRTUAL / NO SPEAKERS":""); @@ -1521,8 +1521,9 @@ // initiates native source publication; only its correlated ACK may // request a safe first MONITOR. If the driver exposes no physical IN, // guide the operator to the existing Audio I/O panel instead. - const warningText=next?.retained?"NEEDS REMAP · MIXER RETAINED · OUTPUT MUTED": + const warningText=next?.retained?"PLAYBACK UNAVAILABLE · MIXER SAVED": !deviceOpen?"NO VERIFIED AUDIO DEVICE": + next?.raw?.waitingAsioInputs>0?"INPUT TEMPORARILY UNAVAILABLE · AUTO-RECONNECT": d.outputArmed?(next.admitted?"NATIVE PCM · HARDWARE FAT PENDING": "MAIN MONITOR ON · PCM ADMISSION NOT VERIFIED"): !d.enabledInputs?.length?(next.admitted?"NO HARDWARE IN · MIXER/FX READY": @@ -1851,7 +1852,7 @@ (outputReady?"Mixer ready · Output live": ack.mixerBound?"Mixer ready · FX/WIRE available":"Audio device ready · no hardware input required"): ack.state==="NEEDS_REMAP"? - "NEEDS REMAP · "+ack.error: + String(ack.error||"Playback unavailable").replace(/^NEEDS_REMAP:\s*/,""): "Device rejected · "+(ack.error||"native hardware readback failed"); deviceChoice=null; if(accepted){ @@ -2241,7 +2242,7 @@ } stopDemo(); paintNativeMeters(next); - status("NEEDS REMAP · mixer retained · output muted"); + status("Playback unavailable · waiting for the audio device"); return; } if (!nativeAdmitted) { From 6177068c8e00917b28246fb716e44fc073e7fbdf Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 21:32:47 +0700 Subject: [PATCH 20/26] fix(asio4all): recover unique physical MAIN from mixed WDM pins and retry transient rebind --- src/Main.cpp | 50 +++++++++++++++++------ src/NativeMixerSessionDocument.h | 50 +++++++++++++++++------ tests/mixer_io_operator_contract_test.mjs | 15 +++++++ tests/native_mixer_session_store_test.cpp | 23 +++++++++++ 4 files changed, 113 insertions(+), 25 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 4381d86c9..abbb1bf7d 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1609,7 +1609,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr ((capturePins && opened->getInputChannelNames()!=freshInputNames) || (playbackPins && opened->getOutputChannelNames()!=freshOutputNames)); } - asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); + // Never consume the automatic recovery epoch before a mixer bind. + // A transient ASIO4ALL pin inventory can settle on the next tick. if(changedAsioPinLayout) error="ASIO pin layout changed. Output remains muted; review the new playback pins."; if(error.isEmpty()&&(opened==nullptr||!opened->isOpen()|| @@ -1645,6 +1646,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr startupError_.clear(); deviceSettingsDirty_=true; directRestore_.cancel(); + asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); diagnostics_.record("CUSTOM_AUDIO_APPLY_OK", typeName+" | "+juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); requestAutomaticMain(); @@ -1681,7 +1683,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr (manager.getCurrentAudioDevice()->getInputChannelNames()==originalInputNames&& manager.getCurrentAudioDevice()->getOutputChannelNames()==originalOutputNames))&& finishAudioSetupAndRecoverMixer(); - asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); + if(verified)asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); diagnostics_.record("CUSTOM_AUDIO_APPLY_FAIL",error+" | rollback="+ (verified?"RESTORED":"RECOVERY_REQUIRED")+" | "+ juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); @@ -4717,7 +4719,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return bound; } - std::uint64_t asioRecoveryEpoch_=0; + std::uint64_t asioRecoveryEpoch_=0; // last successfully bound generation + std::uint64_t asioRecoveryPendingEpoch_=0; + unsigned asioRecoveryAttempts_=0; + std::uint64_t asioRecoveryRetryAfterMs_=0; + void serviceAsioMixerRestart() { const auto epoch=engine_.dryRoutingLabEpoch(); if(epoch==asioRecoveryEpoch_ || !engine_.hasRetainedNativeSession() || @@ -4727,16 +4733,31 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr auto* device=engine_.devices().getCurrentAudioDevice(); if(!device || device->getTypeName()!="ASIO" || !device->getName().startsWithIgnoreCase("ASIO4ALL"))return; - asioRecoveryEpoch_=epoch; // at most one automatic bind per negotiated epoch + if(!engine_.sameRetainedAsioDriver())return; // never change driver class + if(asioRecoveryPendingEpoch_!=epoch) { + // A real external driver restart starts a fresh bounded recovery. + // Internal reopen/correction updates this epoch separately below. + asioRecoveryPendingEpoch_=epoch; + asioRecoveryAttempts_=0; + asioRecoveryRetryAfterMs_=0; + } + const auto now=monotonicMilliseconds(); + if(asioRecoveryAttempts_>=3 || now applying(audioDeviceApplyActive_,true); - if(!engine_.sameRetainedAsioDriver())return; if(!device->isOpen() || device->getActiveOutputChannels().countNumberOfSetBits()<2) { juce::AudioDeviceManager::AudioDeviceSetup setup; engine_.devices().getAudioDeviceSetup(setup); - setup.useDefaultInputChannels=true; + // Explicitly disabled capture is NOT permission to enable a mic. + if(!setup.inputChannels.isZero())setup.useDefaultInputChannels=true; + else setup.useDefaultInputChannels=false; setup.useDefaultOutputChannels=true; const auto error=openSelectedAudioDevice("ASIO",setup,true); - asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); + asioRecoveryPendingEpoch_=engine_.dryRoutingLabEpoch(); device=engine_.devices().getCurrentAudioDevice(); if(error.isNotEmpty() || !device || !device->isOpen()) { diagnostics_.record("ASIO4ALL_REOPEN_FAILED",error); @@ -4744,14 +4765,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return; } } - if(!engine_.authorizeRetainedAsioRestart())return; + if(!engine_.authorizeRetainedAsioRestart()) { + diagnostics_.record("ASIO4ALL_BIND_NOT_READY","Waiting for verified callback/readback"); + return; + } if(const auto corrected=engine_.asioRestartPinCorrection()) { - // One bounded correction for JUCE's restart with the old mask. - // Keep the approved driver and preserve named physical endpoints. const auto inputNames=device->getInputChannelNames(); const auto outputNames=device->getOutputChannelNames(); const auto error=openSelectedAudioDevice("ASIO",*corrected); - asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); + asioRecoveryPendingEpoch_=engine_.dryRoutingLabEpoch(); auto* reopened=engine_.devices().getCurrentAudioDevice(); if(error.isNotEmpty() || !reopened || !reopened->isOpen() || reopened->getInputChannelNames()!=inputNames || @@ -4770,8 +4792,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(error.isNotEmpty()) { diagnostics_.record("ASIO4ALL_REATTACH_FAILED",error); emitApprovedNativeSnapshot(); - return; + return; // keep mixer document, retry only within the bounded budget } + asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); + asioRecoveryPendingEpoch_=asioRecoveryEpoch_; + asioRecoveryAttempts_=0; + asioRecoveryRetryAfterMs_=0; mixerSessionStatus_="RESTORED_MUTED"; mixerSessionError_.clear(); if(engine_.takeAsioResetMonitorIntent())requestAutomaticMain(false); diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index 281f3c27a..5e8a1a146 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -9,6 +9,7 @@ #include #include #include +#include #include // The logical session and its hardware binding are deliberately separate. @@ -133,8 +134,14 @@ struct MixerDeviceBindingPolicy final { // The same approved ASIO4ALL driver can expose a different speaker // after a WDM selection. Adopt the sole verified physical pair. if(!outputs.valid() && (mode==Mode::verifiedDeviceApply || mode==Mode::verifiedAsioRestart) && - isAsio4All(live) && count==2 && isNamedSpeakerPair(newPins,live.outputNames)) - return {count,0,1,-1,-1,false}; + isAsio4All(live) && count>=2) { + // ASIO4ALL can expose virtual and physical WDM outputs together. + // A unique, enabled physical stereo pair is safe to recover even + // when its callback ordinals are 3/4 or arrive in reverse order. + // Ambiguous speakers and virtual-only inventories remain muted. + if(const auto pair=uniqueNamedSpeakerPair(newPins,live.outputNames)) + return {count,pair->first,pair->second,-1,-1,false}; + } return outputs; } static juce::String apply(MixerSessionDocument& document, @@ -229,17 +236,34 @@ struct MixerDeviceBindingPolicy final { bits.parseString(text,16); return bits; } - static bool isNamedSpeakerPair(const juce::BigInteger& pins,const juce::StringArray& names) { - const auto left=names[pins.findNextSetBit(0)].trim().toLowerCase(); - const auto right=names[pins.getHighestBit()].trim().toLowerCase(); - const auto leftPin=pins.findNextSetBit(0),rightPin=pins.getHighestBit(); - return uniquePin(names,names[leftPin])==leftPin && - uniquePin(names,names[rightPin])==rightPin && - left.endsWith(" 1") && right.endsWith(" 2") && - left.dropLastCharacters(2)==right.dropLastCharacters(2) && - !left.contains("vb-audio") && !left.contains("cable") && - !left.contains("virtual") && !left.contains("loopback") && - (left.contains("realtek") || left.contains("speaker") || left.contains("output with sst")); + static std::optional> uniqueNamedSpeakerPair( + const juce::BigInteger& pins,const juce::StringArray& names) { + std::optional> chosen; + for(int leftPin=pins.findNextSetBit(0);leftPin>=0; + leftPin=pins.findNextSetBit(leftPin+1)) { + if(leftPin>=names.size() || uniquePin(names,names[leftPin])!=leftPin)continue; + const auto label=names[leftPin].trim().toLowerCase(); + if(!label.endsWith(" 1"))continue; + const auto stem=label.dropLastCharacters(2); + if(stem.isEmpty() || stem.contains("vb-audio") || stem.contains("cable") || + stem.contains("virtual") || stem.contains("loopback") || + stem.contains("monitor") || + !(stem.contains("realtek") || stem.contains("speaker") || + stem.contains("output with sst")))continue; + int rightPin=-1; + for(int pin=pins.findNextSetBit(0);pin>=0;pin=pins.findNextSetBit(pin+1)) { + if(pin=0)return {}; // duplicate right endpoint + rightPin=pin; + } + } + if(rightPin<0 || uniquePin(names,names[rightPin])!=rightPin)continue; + const int left=callbackAt(pins,leftPin),right=callbackAt(pins,rightPin); + if(left<0 || right<0 || left==right || chosen)return {}; + chosen=std::make_pair(left,right); + } + return chosen; } static int uniquePin(const juce::StringArray& names,const juce::String& name) { if(name.isEmpty())return -1; diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index 88735c5ff..babc19e31 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -597,3 +597,18 @@ test('hardware input CH1/CH2/CH10 selectable on the mixer itself without an IO m assert.match(css,/\.arChannelQuickInput\{/); assert.doesNotMatch(css,/backdrop-filter|filter:blur/); }); + +// Recovery regression: a transient ASIO4ALL reopen must not consume the +// only opportunity to bind the retained ChannelId PCM graph. +test('ASIO4ALL automatic rebind has bounded retries, succeeds only after verified readback',()=>{ + const src=read('src/Main.cpp'); + const service=src.slice(src.indexOf('void serviceAsioMixerRestart()'),src.indexOf('void changeListenerCallback (')); + assert.match(service,/asioRecoveryAttempts_>=3/); + assert.match(service,/now Date: Mon, 9 Nov 2026 21:38:04 +0700 Subject: [PATCH 21/26] fix(asio4all): preserve MAIN intent and retry transient automatic ARM preflight --- src/LiveAudioEngine.h | 5 +++++ src/Main.cpp | 5 ++++- tests/mixer_io_operator_contract_test.mjs | 11 +++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 106253e3d..89f454319 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -2720,6 +2720,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void audioDeviceAboutToStart (juce::AudioIODevice* d) override { + // Some ASIO implementations announce a new callback before STOP. + // Remember the existing MAIN intent before muting this epoch; only + // the verified same-driver CONTROL rebind may resume it. No RT work. + if(monitor_.load(std::memory_order_acquire)) + resumeMainAfterAsioReset_.store(true,std::memory_order_release); setOutputMuted(true); secondaryOutput_.invalidateSource(); // source clock may have changed dryRoutingLab_.prepareDevice(d); // exact active mask, before callback diff --git a/src/Main.cpp b/src/Main.cpp index abbb1bf7d..b3e1937a5 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1324,8 +1324,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto revision=engine_.outputArmRevision(); if(autoMainCheckedRevision_==revision)return; if(engine_.isGraphSwitchPending()||!engine_.hasBoundMixerRoute())return; - autoMainCheckedRevision_=revision; + // A transient native graph/FX ACK must not permanently consume + // the only automatic MAIN attempt for this control revision. + // Retry only the cheap CONTROL preflight until it is genuinely safe. if(engine_.liveOutputArmFault(autoMainRequiresInput_).isNotEmpty())return; + autoMainCheckedRevision_=revision; engine_.setMonitorEnabled(true); autoMainEpoch_=0; diagnostics_.record("MAIN_AUTO_ENABLED","Verified device, input and MAIN output"); diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index babc19e31..1a3735a30 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -612,3 +612,14 @@ test('ASIO4ALL automatic rebind has bounded retries, succeeds only after verifie const apply=src.slice(src.indexOf('void applyCustomAudioDevice('),src.indexOf('void showDeviceSetup()')); assert.doesNotMatch(apply,/asioRecoveryEpoch_=engine_\.dryRoutingLabEpoch\(\);\s*if\(changedAsioPinLayout\)/); }); + +test('ASIO restart cannot strand MAIN off after temporary graph readiness faults',()=>{ + const main=read('src/Main.cpp'),engine=read('src/LiveAudioEngine.h'); + const arm=main.slice(main.indexOf('void serviceAutomaticMain()'),main.indexOf('void requestAutomaticMain(')); + assert.ok(arm.indexOf('liveOutputArmFault(autoMainRequiresInput_)')< + arm.indexOf('autoMainCheckedRevision_=revision;'),'only a verified ARM consumes the revision'); + const begin=engine.slice(engine.indexOf('void audioDeviceAboutToStart ('),engine.indexOf('void audioDeviceStopped()')); + assert.match(begin,/if\(monitor_\.load\(std::memory_order_acquire\)\)/); + assert.match(begin,/resumeMainAfterAsioReset_\.store\(true/); + assert.ok(begin.indexOf('resumeMainAfterAsioReset_.store(true') Date: Mon, 9 Nov 2026 21:51:22 +0700 Subject: [PATCH 22/26] fix(asio4all): separate driver reopen budget from native mixer rebind readiness --- CMakeLists.txt | 4 ++ engine/device/AsioRestartRecoveryGate.h | 68 +++++++++++++++++++++++ src/Main.cpp | 60 +++++++++++--------- tests/asio_restart_recovery_gate_test.cpp | 38 +++++++++++++ tests/mixer_io_operator_contract_test.mjs | 12 ++-- 5 files changed, 152 insertions(+), 30 deletions(-) create mode 100644 engine/device/AsioRestartRecoveryGate.h create mode 100644 tests/asio_restart_recovery_gate_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 72e05dd04..2be1c5537 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -253,6 +253,10 @@ if(BUILD_TESTING) add_executable(ARMixStreamWatchdogTests tests/independent_stream_watchdog_test.cpp) target_compile_features(ARMixStreamWatchdogTests PRIVATE cxx_std_20) add_test(NAME IndependentStreamSilenceRecovery COMMAND ARMixStreamWatchdogTests) + add_executable(ARMixAsioRestartGateTests tests/asio_restart_recovery_gate_test.cpp + engine/device/AsioRestartRecoveryGate.h) + target_compile_features(ARMixAsioRestartGateTests PRIVATE cxx_std_20) + add_test(NAME Asio4AllWdmSettleBoundedDriverTransactionsAndDeferredRebind COMMAND ARMixAsioRestartGateTests) add_executable(ARMixRecoveryTests tests/direct_restore_backoff_test.cpp) target_compile_features(ARMixRecoveryTests PRIVATE cxx_std_20) add_test(NAME BoundedDirectDeviceRecovery COMMAND ARMixRecoveryTests) diff --git a/engine/device/AsioRestartRecoveryGate.h b/engine/device/AsioRestartRecoveryGate.h new file mode 100644 index 000000000..6d0fb9685 --- /dev/null +++ b/engine/device/AsioRestartRecoveryGate.h @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include + +namespace armix::device { +// CONTROL-thread scheduler for an ASIO4ALL driver whose WDM pin inventory +// may be transient during a control-panel restart. It never opens a device, +// touches a vendor plugin, or enters the realtime PCM callback. +// Only actual driver reopen/correction calls consume the bounded budget; +// readback and native graph publication remain eligible after it is spent. +class AsioRestartRecoveryGate final { +public: + static constexpr unsigned maxDriverTransactions=3; + static constexpr std::uint64_t settleMs=350; + + void observeEpoch(std::uint64_t epoch,std::uint64_t nowMs) noexcept { + if(epoch==0 || epoch==epoch_)return; + epoch_=epoch; + driverTransactions_=0; + bindFailures_=0; + nextMs_=add(nowMs,settleMs); + } + // A restart caused by *our own* verified reopen/correction is not a new + // opportunity for an unlimited series of expensive vendor calls. + void carryInternalEpoch(std::uint64_t epoch) noexcept { + if(epoch!=0)epoch_=epoch; + } + bool due(std::uint64_t nowMs) const noexcept { + return epoch_!=0 && nowMs>=nextMs_; + } + bool mayChangeDriver() const noexcept { + return driverTransactions_30000?30000:pause); + } + void recovered() noexcept { + driverTransactions_=0; + bindFailures_=0; + nextMs_=0; + } + unsigned driverTransactions() const noexcept {return driverTransactions_;} + std::uint64_t trackedEpoch() const noexcept {return epoch_;} +private: + static std::uint64_t add(std::uint64_t a,std::uint64_t b) noexcept { + return a>std::numeric_limits::max()-b? + std::numeric_limits::max():a+b; + } + void defer(std::uint64_t nowMs,std::uint64_t millis) noexcept { + const auto deadline=add(nowMs,millis); + if(deadline>nextMs_)nextMs_=deadline; + } + std::uint64_t epoch_=0,nextMs_=0; + unsigned driverTransactions_=0,bindFailures_=0; +}; +} // namespace armix::device diff --git a/src/Main.cpp b/src/Main.cpp index b3e1937a5..040791282 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -17,6 +17,7 @@ #include "DiagnosticsRecorder.h" #include "../engine/device/DirectRestoreBackoff.h" #include "../engine/device/AudioSetupRecoveryPolicy.h" +#include "../engine/device/AsioRestartRecoveryGate.h" #include "../engine/device/PeriodCapabilityEvidence.h" #include "../engine/diagnostics/CrackleEvidenceWindow.h" #if defined(_WIN32) @@ -4723,44 +4724,38 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } std::uint64_t asioRecoveryEpoch_=0; // last successfully bound generation - std::uint64_t asioRecoveryPendingEpoch_=0; - unsigned asioRecoveryAttempts_=0; - std::uint64_t asioRecoveryRetryAfterMs_=0; + armix::device::AsioRestartRecoveryGate asioRecoveryGate_; void serviceAsioMixerRestart() { const auto epoch=engine_.dryRoutingLabEpoch(); if(epoch==asioRecoveryEpoch_ || !engine_.hasRetainedNativeSession() || + audioDeviceApplyActive_ || (audioSetupWindow_ && audioSetupWindow_->isVisible()) || nativeShowBusy_ || studioBackupBusy_ || mixerSessionWorker_.busy() || catalog_.busy() || engine_.isGraphSwitchPending() || engine_.independentClockActive() || engine_.diagnosticRoute()!=armix::diagnostics::Route::normal)return; auto* device=engine_.devices().getCurrentAudioDevice(); if(!device || device->getTypeName()!="ASIO" || !device->getName().startsWithIgnoreCase("ASIO4ALL"))return; - if(!engine_.sameRetainedAsioDriver())return; // never change driver class - if(asioRecoveryPendingEpoch_!=epoch) { - // A real external driver restart starts a fresh bounded recovery. - // Internal reopen/correction updates this epoch separately below. - asioRecoveryPendingEpoch_=epoch; - asioRecoveryAttempts_=0; - asioRecoveryRetryAfterMs_=0; - } + if(!engine_.sameRetainedAsioDriver())return; // preserve registered driver identity const auto now=monotonicMilliseconds(); - if(asioRecoveryAttempts_>=3 || now applying(audioDeviceApplyActive_,true); if(!device->isOpen() || device->getActiveOutputChannels().countNumberOfSetBits()<2) { + // A closed or output-less ASIO device requires a vendor call. + // Never reopen it repeatedly on each UI timer tick. + if(!asioRecoveryGate_.mayChangeDriver()) { + asioRecoveryGate_.waitForReadback(now); + return; + } juce::AudioDeviceManager::AudioDeviceSetup setup; engine_.devices().getAudioDeviceSetup(setup); - // Explicitly disabled capture is NOT permission to enable a mic. - if(!setup.inputChannels.isZero())setup.useDefaultInputChannels=true; - else setup.useDefaultInputChannels=false; + // A deliberate 0-IN session remains 0-IN. Never resurrect a mic. + setup.useDefaultInputChannels=!setup.inputChannels.isZero(); setup.useDefaultOutputChannels=true; + asioRecoveryGate_.driverTransaction(now); const auto error=openSelectedAudioDevice("ASIO",setup,true); - asioRecoveryPendingEpoch_=engine_.dryRoutingLabEpoch(); + asioRecoveryGate_.carryInternalEpoch(engine_.dryRoutingLabEpoch()); device=engine_.devices().getCurrentAudioDevice(); if(error.isNotEmpty() || !device || !device->isOpen()) { diagnostics_.record("ASIO4ALL_REOPEN_FAILED",error); @@ -4769,14 +4764,24 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } } if(!engine_.authorizeRetainedAsioRestart()) { + // Admission can lag driver restart without any driver call. + // It MUST NOT exhaust the bounded reopen/correction allowance. + asioRecoveryGate_.waitForReadback(now); diagnostics_.record("ASIO4ALL_BIND_NOT_READY","Waiting for verified callback/readback"); return; } if(const auto corrected=engine_.asioRestartPinCorrection()) { + if(!asioRecoveryGate_.mayChangeDriver()) { + asioRecoveryGate_.waitForReadback(now); + diagnostics_.record("ASIO4ALL_PIN_CORRECTION_DEFERRED", + "Driver transaction budget exhausted for this physical epoch"); + return; + } const auto inputNames=device->getInputChannelNames(); const auto outputNames=device->getOutputChannelNames(); + asioRecoveryGate_.driverTransaction(now); const auto error=openSelectedAudioDevice("ASIO",*corrected); - asioRecoveryPendingEpoch_=engine_.dryRoutingLabEpoch(); + asioRecoveryGate_.carryInternalEpoch(engine_.dryRoutingLabEpoch()); auto* reopened=engine_.devices().getCurrentAudioDevice(); if(error.isNotEmpty() || !reopened || !reopened->isOpen() || reopened->getInputChannelNames()!=inputNames || @@ -4793,14 +4798,17 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto error=engine_.reattachRetainedAsioMixer()?juce::String{}: restoreSavedMixerSession(false,MixerBindingMode::verifiedAsioRestart); if(error.isNotEmpty()) { + // A native graph/FX lease may become ready after the driver's + // current epoch; retry without reopening hardware at an + // exponentially bounded CONTROL cadence. + asioRecoveryGate_.bindFailed(now); diagnostics_.record("ASIO4ALL_REATTACH_FAILED",error); emitApprovedNativeSnapshot(); - return; // keep mixer document, retry only within the bounded budget + return; } asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); - asioRecoveryPendingEpoch_=asioRecoveryEpoch_; - asioRecoveryAttempts_=0; - asioRecoveryRetryAfterMs_=0; + asioRecoveryGate_.carryInternalEpoch(asioRecoveryEpoch_); + asioRecoveryGate_.recovered(); mixerSessionStatus_="RESTORED_MUTED"; mixerSessionError_.clear(); if(engine_.takeAsioResetMonitorIntent())requestAutomaticMain(false); diff --git a/tests/asio_restart_recovery_gate_test.cpp b/tests/asio_restart_recovery_gate_test.cpp new file mode 100644 index 000000000..ef0d738ad --- /dev/null +++ b/tests/asio_restart_recovery_gate_test.cpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/device/AsioRestartRecoveryGate.h" +#include +#include +#include + +int main() { + using armix::device::AsioRestartRecoveryGate; + AsioRestartRecoveryGate gate; + assert(!gate.due(999999)); + gate.observeEpoch(21,1000); + assert(!gate.due(1349) && gate.due(1350)); + gate.waitForReadback(1350); // no debit when ASIO panel is still settling + assert(gate.driverTransactions()==0 && !gate.due(2099) && gate.due(2100)); + gate.driverTransaction(2100); + gate.carryInternalEpoch(22); + gate.observeEpoch(22,2150); + assert(gate.trackedEpoch()==22 && gate.driverTransactions()==1); + assert(!gate.due(3299) && gate.due(3300)); + gate.driverTransaction(3300); // pin correction or reopened device + assert(gate.driverTransactions()==2 && !gate.due(7299)); + gate.bindFailed(3350); // never shorten a scheduled driver cool-down + assert(!gate.due(7299) && gate.due(7300)); + gate.driverTransaction(7300); + assert(!gate.mayChangeDriver()); + assert(!gate.due(15299) && gate.due(15300)); + gate.bindFailed(15300); // read-only rebind is still allowed after budget + assert(!gate.due(17699) && gate.due(17700)); + gate.observeEpoch(23,18000); // real external device change reopens budget + assert(gate.driverTransactions()==0 && gate.mayChangeDriver()); + assert(!gate.due(18349) && gate.due(18350)); + gate.recovered(); + assert(gate.driverTransactions()==0); + // avoid overflow across uptime wrap or synthetic test timestamps + gate.observeEpoch(24,std::numeric_limits::max()-10); + assert(!gate.due(std::numeric_limits::max()-1)); + assert(gate.due(std::numeric_limits::max())); +} diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index 1a3735a30..991c11d14 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -603,12 +603,16 @@ test('hardware input CH1/CH2/CH10 selectable on the mixer itself without an IO m test('ASIO4ALL automatic rebind has bounded retries, succeeds only after verified readback',()=>{ const src=read('src/Main.cpp'); const service=src.slice(src.indexOf('void serviceAsioMixerRestart()'),src.indexOf('void changeListenerCallback (')); - assert.match(service,/asioRecoveryAttempts_>=3/); - assert.match(service,/nowisVisible\(\)/); assert.match(service,/restoreSavedMixerSession\(false,MixerBindingMode::verifiedAsioRestart\)/); assert.match(service,/asioRecoveryEpoch_=engine_\.dryRoutingLabEpoch\(\)/); - assert.match(service,/!setup\.inputChannels\.isZero\(\)/); + assert.match(service,/setup\.useDefaultInputChannels=!setup\.inputChannels\.isZero\(\)/); const apply=src.slice(src.indexOf('void applyCustomAudioDevice('),src.indexOf('void showDeviceSetup()')); assert.doesNotMatch(apply,/asioRecoveryEpoch_=engine_\.dryRoutingLabEpoch\(\);\s*if\(changedAsioPinLayout\)/); }); From a5c737dd397626d7123f409465c5b2dfa24a05e7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 22:00:00 +0700 Subject: [PATCH 23/26] test(asio4all): enforce scheduler assertions in Release CTest --- tests/asio_restart_recovery_gate_test.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/asio_restart_recovery_gate_test.cpp b/tests/asio_restart_recovery_gate_test.cpp index ef0d738ad..07dc41d2e 100644 --- a/tests/asio_restart_recovery_gate_test.cpp +++ b/tests/asio_restart_recovery_gate_test.cpp @@ -1,5 +1,8 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/device/AsioRestartRecoveryGate.h" +#ifdef NDEBUG + #undef NDEBUG +#endif #include #include #include From 01fcd0978f95899e2c2ecfbb81d660021cda841c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 22:54:54 +0700 Subject: [PATCH 24/26] fix(asio4all): reopen missing JUCE device only through pinned selected driver identity --- src/LiveAudioEngine.h | 21 +++++++++++++++++++++ src/Main.cpp | 19 ++++++++++++++----- tests/mixer_io_operator_contract_test.mjs | 17 +++++++++++++++++ 3 files changed, 52 insertions(+), 5 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 89f454319..86e1adea6 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -471,6 +471,27 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return registered.registration.ok() && asioPinnedRegistration_.sameDriverClass(registered.registration.identity); } + // A vendor ASIO4ALL restart can leave JUCE with NO current device object. + // Only the previously selected, explicitly approved driver name and its + // FULL registered CLSID may be reopened; never choose a default endpoint. + // CONTROL only: registry lookup and JUCE setup are forbidden in callback. + bool selectedRetainedAsioDriverForReopen() { + using Policy=armix::session::MixerDeviceBindingPolicy; + if(deviceManager_.getCurrentAudioDevice() || !acceptedMixerBinding_ || + !Policy::isAsio4All(*acceptedMixerBinding_) || + !asioPinnedRegistration_.valid() || !attached_ || independent_.active() || + deviceManager_.getCurrentAudioDeviceType()!="ASIO")return false; + juce::AudioDeviceManager::AudioDeviceSetup setup; + deviceManager_.getAudioDeviceSetup(setup); + if(setup.outputDeviceName.isEmpty() || + setup.outputDeviceName!=acceptedMixerBinding_->playback || + (!setup.inputDeviceName.isEmpty() && + setup.inputDeviceName!=acceptedMixerBinding_->capture))return false; + const auto registered=armix::device::AsioRegistryIdentityProbe::resolve( + std::wstring(setup.outputDeviceName.toWideCharPointer())); + return registered.registration.ok() && + asioPinnedRegistration_.sameDriverClass(registered.registration.identity); + } bool authorizeRetainedAsioRestart() { using Policy=armix::session::MixerDeviceBindingPolicy; if(!hasRetainedNativeSession() || !acceptedMixerBinding_ || diff --git a/src/Main.cpp b/src/Main.cpp index 040791282..56ba1bde6 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -4734,15 +4734,22 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr engine_.isGraphSwitchPending() || engine_.independentClockActive() || engine_.diagnosticRoute()!=armix::diagnostics::Route::normal)return; auto* device=engine_.devices().getCurrentAudioDevice(); - if(!device || device->getTypeName()!="ASIO" || - !device->getName().startsWithIgnoreCase("ASIO4ALL"))return; - if(!engine_.sameRetainedAsioDriver())return; // preserve registered driver identity + if(device) { + if(device->getTypeName()!="ASIO" || + !device->getName().startsWithIgnoreCase("ASIO4ALL") || + !engine_.sameRetainedAsioDriver())return; + } else if(!engine_.selectedRetainedAsioDriverForReopen()) { + // The device pointer disappeared: never open an unapproved or + // guessed driver name, even if ASIO4ALL happens to be installed. + return; + } const auto now=monotonicMilliseconds(); asioRecoveryGate_.observeEpoch(epoch,now); if(!asioRecoveryGate_.due(now))return; // let ASIO4ALL WDM pin inventory settle const juce::ScopedValueSetter applying(audioDeviceApplyActive_,true); - if(!device->isOpen() || device->getActiveOutputChannels().countNumberOfSetBits()<2) { - // A closed or output-less ASIO device requires a vendor call. + if(!device || !device->isOpen() || + device->getActiveOutputChannels().countNumberOfSetBits()<2) { + // A missing, closed or output-less ASIO device requires a vendor call. // Never reopen it repeatedly on each UI timer tick. if(!asioRecoveryGate_.mayChangeDriver()) { asioRecoveryGate_.waitForReadback(now); @@ -4754,6 +4761,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr setup.useDefaultInputChannels=!setup.inputChannels.isZero(); setup.useDefaultOutputChannels=true; asioRecoveryGate_.driverTransaction(now); + if(!device)diagnostics_.record("ASIO4ALL_DEVICE_MISSING", + "Reopening previously approved registered ASIO driver; no fallback"); const auto error=openSelectedAudioDevice("ASIO",setup,true); asioRecoveryGate_.carryInternalEpoch(engine_.dryRoutingLabEpoch()); device=engine_.devices().getCurrentAudioDevice(); diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index 991c11d14..81bcf28f9 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -617,6 +617,23 @@ test('ASIO4ALL automatic rebind has bounded retries, succeeds only after verifie assert.doesNotMatch(apply,/asioRecoveryEpoch_=engine_\.dryRoutingLabEpoch\(\);\s*if\(changedAsioPinLayout\)/); }); +test('ASIO4ALL missing JUCE device can reopen only the pinned user-selected driver',()=>{ + const main=read('src/Main.cpp'),engine=read('src/LiveAudioEngine.h'); + const service=main.slice(main.indexOf('void serviceAsioMixerRestart()'), + main.indexOf('void changeListenerCallback (')); + assert.match(service,/else if\(!engine_\.selectedRetainedAsioDriverForReopen\(\)\)/); + assert.match(service,/if\(!device \|\| !device->isOpen\(\)/); + assert.match(service,/ASIO4ALL_DEVICE_MISSING/); + const selected=engine.slice(engine.indexOf('bool selectedRetainedAsioDriverForReopen()'), + engine.indexOf('bool authorizeRetainedAsioRestart()')); + assert.match(selected,/deviceManager_\.getCurrentAudioDevice\(\)/); + assert.match(selected,/deviceManager_\.getCurrentAudioDeviceType\(\)!="ASIO"/); + assert.match(selected,/Policy::isAsio4All\(\*acceptedMixerBinding_\)/); + assert.match(selected,/setup\.outputDeviceName!=acceptedMixerBinding_->playback/); + assert.match(selected,/setup\.inputDeviceName!=acceptedMixerBinding_->capture/); + assert.match(selected,/asioPinnedRegistration_\.sameDriverClass\(registered\.registration\.identity\)/); +}); + test('ASIO restart cannot strand MAIN off after temporary graph readiness faults',()=>{ const main=read('src/Main.cpp'),engine=read('src/LiveAudioEngine.h'); const arm=main.slice(main.indexOf('void serviceAutomaticMain()'),main.indexOf('void requestAutomaticMain(')); From 98330452899856816495f6a45dc7de08421b6d1b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 22:55:52 +0700 Subject: [PATCH 25/26] ci(asio4all): run focused missing-device and restart contracts before Windows MSVC --- .github/workflows/p1-windows.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index b7ea6f60b..9f7797bb7 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -129,6 +129,7 @@ jobs: node scripts/check_console_puzzle.mjs node --check web/approved-native-bridge.js node --check web/approved-native-contract.js + node --test --test-name-pattern="ASIO4ALL|ASIO restart" tests/mixer_io_operator_contract_test.mjs node --test tests/workstream_coordination_contract.test.mjs tests/ci_workflow_efficiency_test.mjs tests/chat_ci_dispatch_contract.test.mjs tests/approved_native_m2_contract.test.cjs tests/native_artifact_packaging_contract_test.mjs tests/windows_installer_contract_test.mjs tests/live_graph_contract_test.mjs python -m unittest discover -s tests -p approved_native_gui_bundle_test.py -v python -m unittest discover -s scripts/tests -p test_factoryfx_release_bundle.py -v From 3015960b92c0c7547049a11ef6f0fe5ecec9e487 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 23:11:50 +0700 Subject: [PATCH 26/26] fix(session): retain PlayerDeck music through ASIO4ALL 0-IN and .smix restore Preserve virtual MUSIC ChannelId, MAIN WIRE, and FX identity across all physical capture absence and return. Reject physical pin coordinates with zero input channels. Regression covers decode/encode, 0-to-2-to-0 ASIO recovery and malformed physical source. --- src/NativeMixerSessionDocument.h | 6 ++- tests/native_mixer_session_store_test.cpp | 51 +++++++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index 79bfb67c8..68ce4c659 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -604,8 +604,10 @@ class Codec final { return false; const auto sourcesVar=get(req,"sources"); const auto* sources=sourcesVar.getArray(); - if(!sources||sources->size()>channels->size()|| - (doc.request.physicalInputs==0 && !sources->isEmpty()))return false; + // An all-virtual MUSIC session is legitimate even with zero + // connected capture pins. The per-source decoder below still + // rejects EVERY physical ordinal when physicalInputs == 0. + if(!sources||sources->size()>channels->size())return false; if(doc.binding.capture.isEmpty() && (doc.request.physicalInputs!=0 || doc.binding.inputMask!="0")) return false; diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index c0198508d..0255f8f25 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -504,6 +504,57 @@ static void verifyVirtualPlayerSessionSerialization() { DynamicSourceKind::playerDeck); assert(document.request.sources.front().deckId==1); assert(document.roster.find({17})->sends.front().destination.value==15); + + // Reconciled ASIO4ALL + ArSon Player: physically disconnected inputs + // must NOT erase the mixer-owned virtual MUSIC source or its MAIN wire. + auto virtualOnly=makeSession(); + auto channels=virtualOnly.roster.channels(); + channels.push_back(player); + assert(virtualOnly.roster.restoreExact(virtualOnly.acceptedRevision,channels)); + virtualOnly.request.sources.clear(); + virtualOnly.request.sources.push_back( + {{17},-1,-1,true,DynamicSourceKind::playerDeck,1}); + virtualOnly.request.physicalInputs=0; + virtualOnly.binding.backend="ASIO"; + virtualOnly.binding.capture=virtualOnly.binding.playback="ASIO4ALL v2"; + virtualOnly.binding.inputMask="0"; + virtualOnly.binding.inputNames.clear(); + virtualOnly.binding.outputMask="3"; + virtualOnly.binding.outputNames={"Realtek Speakers 1","Realtek Speakers 2"}; + const auto onlyPlayer=Codec::encode(virtualOnly); + MixerSessionDocument restoredPlayer; + assert(Codec::decode(onlyPlayer,restoredPlayer)); + assert(restoredPlayer.request.physicalInputs==0 && + restoredPlayer.request.sources.size()==1 && + restoredPlayer.request.sources.front().kind== + DynamicSourceKind::playerDeck); + assert(Codec::encode(restoredPlayer)==onlyPlayer); + auto returned=virtualOnly.binding; + returned.inputMask="3"; + returned.inputNames={"VB-Audio Point 1","VB-Audio Point 2"}; + const auto pair=MixerDeviceBindingPolicy::proposedOutputs( + restoredPlayer,returned,2,BindingMode::verifiedAsioRestart); + assert(pair.valid()); + assert(MixerDeviceBindingPolicy::apply(restoredPlayer,returned,pair,2, + BindingMode::verifiedAsioRestart).isEmpty()); + assert(restoredPlayer.request.physicalInputs==2 && + restoredPlayer.request.sources.size()==1 && + restoredPlayer.request.sources.front().kind== + DynamicSourceKind::playerDeck); + assert(restoredPlayer.roster.find({17})->sends.front() + .destination.value==15); + // The reverse transition 2-IN -> 0-IN must also retain the same deck. + const auto absent=virtualOnly.binding; + assert(MixerDeviceBindingPolicy::apply(restoredPlayer,absent,pair,0, + BindingMode::verifiedAsioRestart).isEmpty()); + assert(restoredPlayer.request.sources.size()==1 && + restoredPlayer.request.sources.front().deckId==1); + // Never relax zero-input validation for physical mic ordinals. + auto bad=juce::JSON::parse(onlyPlayer); + auto src=bad.getProperty("request",{}).getProperty("sources",{}); + src.getArray()->getReference(0).getDynamicObject() + ->removeProperty("kind"); + assert(!Codec::decode(juce::JSON::toString(bad,false),restoredPlayer)); } // Actual production callback fixture: a freshly verified mixer needs ZERO