From a909531f368f09776c0a57daf2fdd30bf9fc55d9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 8 Nov 2026 03:54:43 +0700 Subject: [PATCH 1/7] Restore mixer on verified device changes and speed up channel rename --- scripts/compose_operator_ux.py | 51 +++++++++--- src/LiveAudioEngine.h | 19 +++-- src/Main.cpp | 31 ++++--- src/NativeMixerSessionDocument.h | 83 +++++++++++-------- tests/approved_native_cold_start_smoke.py | 21 ++--- ...roved_operator_ux_native_identity_smoke.py | 18 +++- tests/mixer_io_operator_contract_test.mjs | 9 ++ tests/native_mixer_session_store_test.cpp | 54 ++++++++++-- 8 files changed, 203 insertions(+), 83 deletions(-) diff --git a/scripts/compose_operator_ux.py b/scripts/compose_operator_ux.py index a6b8e1242..697164e36 100644 --- a/scripts/compose_operator_ux.py +++ b/scripts/compose_operator_ux.py @@ -81,6 +81,8 @@ .command-bar .mixer-file-tool{display:inline-flex;align-items:center;gap:5px} .command-bar .mixer-file-tool img{display:block;flex:none;pointer-events:none} .command-bar #densitySelect,.command-bar [for="densitySelect"],.command-bar #mode{display:none!important} +#channelIdentity .identity-head{cursor:move;touch-action:none} +#channelIdentity .identity-head button{cursor:pointer} /* Every console floating editor uses one square Material close key. */ :is(#pluginClose,#identityClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose){ box-sizing:border-box!important;flex:0 0 29px!important;width:29px!important; @@ -208,21 +210,44 @@ def apply_operator_ux(html: str, assets: Path) -> str: "place editor under body outside scrolling app") html = once(html, "function openChannelIdentity(t,anchor){", - """function positionChannelIdentity(dialog,anchor){ - // One geometry read on explicit open, not in the live meter/PCM path. + """function channelIdentityViewport(){ const visual=window.visualViewport; - const vx=visual?.offsetLeft??0,vy=visual?.offsetTop??0; - const vw=visual?.width||window.innerWidth,vh=visual?.height||window.innerHeight; + return {left:visual?.offsetLeft??0,top:visual?.offsetTop??0, + width:visual?.width||window.innerWidth,height:visual?.height||window.innerHeight}; +} +function placeChannelIdentity(dialog,box,view,x,y){ const gap=8; - dialog.style.maxWidth=Math.max(1,vw-2*gap)+'px'; - dialog.style.maxHeight=Math.max(1,vh-2*gap)+'px'; + dialog.style.left=Math.max(view.left+gap,Math.min(view.left+view.width-box.width-gap,x))+'px'; + dialog.style.top=Math.max(view.top+gap,Math.min(view.top+view.height-box.height-gap,y))+'px'; +} +function positionChannelIdentity(dialog,anchor){ + // One geometry read on explicit open, not in the live meter/PCM path. + const view=channelIdentityViewport(); + dialog.style.maxWidth=Math.max(1,view.width-16)+'px'; + dialog.style.maxHeight=Math.max(1,view.height-16)+'px'; const box=dialog.getBoundingClientRect(),a=anchor?.getBoundingClientRect?.(); - const preferredX=a?a.left+a.width/2-box.width/2:vx+gap; - const preferredY=a?a.top+18:vy+gap; - const x=Math.max(vx+gap,Math.min(vx+vw-box.width-gap,preferredX)); - const y=Math.max(vy+gap,Math.min(vy+vh-box.height-gap,preferredY)); - dialog.style.left=x+'px';dialog.style.top=y+'px'; + placeChannelIdentity(dialog,box,view,a?a.left+(a.width-box.width)/2:view.left+8, + a?a.top+18:view.top+8); } +const channelIdentityCard=document.getElementById('channelIdentity'); +const channelIdentityHandle=channelIdentityCard.querySelector('.identity-head'); +let channelIdentityDrag=null; +channelIdentityHandle.addEventListener('pointerdown',e=>{ + if(e.button!==0||!e.isPrimary||e.target.closest('button'))return; + const box=channelIdentityCard.getBoundingClientRect(); + channelIdentityDrag={id:e.pointerId,box,x:e.clientX-box.left,y:e.clientY-box.top}; + channelIdentityHandle.setPointerCapture(e.pointerId); + e.preventDefault(); +}); +channelIdentityHandle.addEventListener('pointermove',e=>{ + const drag=channelIdentityDrag; + if(!drag||drag.id!==e.pointerId)return; + placeChannelIdentity(channelIdentityCard,drag.box,channelIdentityViewport(), + e.clientX-drag.x,e.clientY-drag.y); +}); +channelIdentityHandle.addEventListener('lostpointercapture',e=>{ + if(channelIdentityDrag?.id===e.pointerId)channelIdentityDrag=null; +}); function openChannelIdentity(t,anchor){""", "install measured viewport positioning") html = once(html, @@ -233,7 +258,9 @@ def apply_operator_ux(html: str, assets: Path) -> str: } document.getElementById('identityName').focus?.();""", """ positionChannelIdentity(dialog,anchor); - document.getElementById('identityName').focus({preventScroll:true});""", + const name=document.getElementById('identityName'); + name.focus({preventScroll:true}); + name.select();""", "remove mixer-relative geometry and focus scroll") targets = ("identityClose","pluginClose","fastClose", "wireConfigClose","wireWsClose","routeChoiceClose") diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 5bceac060..565d895ef 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1478,7 +1478,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Read-only control-thread verification of the currently opened pins. juce::String inspectNativeMixerSessionBinding( const armix::session::MixerSessionDocument& saved, - MixerBindingInspection& out) { + MixerBindingInspection& out, + armix::session::MixerDeviceBindingPolicy::Mode mode) { if(independent_.active()||!attached_|| !directFence_.permitted()||handoff_.busy()|| fxMovePhase_.load(std::memory_order_acquire)!=0|| @@ -1507,10 +1508,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback candidate.live={ deviceManager_.getCurrentAudioDeviceType(), setup.inputDeviceName,setup.outputDeviceName, - inputMask.toString(16),outputMask.toString(16),rate,frames}; + inputMask.toString(16),outputMask.toString(16),rate,frames, + device->getInputChannelNames(),device->getOutputChannelNames()}; candidate.callbackInputs=candidate.pins.inputs.enabledCount; candidate.outputs=armix::session::MixerDeviceBindingPolicy::proposedOutputs( - saved,candidate.live,candidate.pins.outputCount); + saved,candidate.live,candidate.pins.outputCount,mode); if(candidate.epoch!=dryRoutingLab_.epoch()) return "NEEDS_REMAP: device changed during inspection"; out=std::move(candidate); @@ -1522,7 +1524,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String restoreNativeMixerSession( armix::session::MixerSessionDocument document, const std::vector& states, - bool replaceActive=false,bool* sameLiveOutputs=nullptr) { + bool replaceActive=false,bool* sameLiveOutputs=nullptr, + armix::session::MixerDeviceBindingPolicy::Mode mode= + armix::session::MixerDeviceBindingPolicy::Mode::exact) { if((replaceActive?secondaryOutput_.armed():!allOutputsDisarmed())|| independent_.active()||!attached_|| !directFence_.permitted()||handoff_.busy()|| @@ -1532,13 +1536,13 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback routeReconfiguring_.load(std::memory_order_acquire)) return "MUTE output and verify DIRECT before restoring mixer"; MixerBindingInspection inspected; - auto bindingError=inspectNativeMixerSessionBinding(document,inspected); + auto bindingError=inspectNativeMixerSessionBinding(document,inspected,mode); if(bindingError.isNotEmpty())return bindingError; using BindingPolicy=armix::session::MixerDeviceBindingPolicy; if(sameLiveOutputs) *sameLiveOutputs=dryRoutingLab_.matchesNativeMixerOutputs(inspected.outputs); bindingError=BindingPolicy::apply(document,inspected.live,inspected.outputs, - inspected.callbackInputs,false); + inspected.callbackInputs,mode); if(bindingError.isNotEmpty())return bindingError; const auto ep=inspected.epoch; const auto next=dryRoutingLab_.nativeGraphRevisionForRestore(); @@ -2192,7 +2196,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return {deviceManager_.getCurrentAudioDeviceType(),setup.inputDeviceName, setup.outputDeviceName,device.getActiveInputChannels().toString(16), device.getActiveOutputChannels().toString(16),device.getCurrentSampleRate(), - device.getCurrentBufferSizeSamples()}; + device.getCurrentBufferSizeSamples(),device.getInputChannelNames(), + device.getOutputChannelNames()}; } struct WasapiBinding { armix::device::EndpointIdentityPolicy::Selection endpoints; diff --git a/src/Main.cpp b/src/Main.cpp index c31dcdf05..e08a8581f 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1246,7 +1246,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr static_cast(oldGeneration)) return send(false,"REJECTED","Stale device generation; refresh DEVICE / DRIVER"); const auto nativeRoute=engine_.status().getProperty("dryRoutingLab",{}); - if(nativeShowBusy_||studioBackupBusy_||engine_.isGraphSwitchPending()|| + if(nativeShowBusy_||studioBackupBusy_||mixerSessionWorker_.busy()|| + engine_.isGraphSwitchPending()|| static_cast(nativeRoute.getProperty("pending",false))|| engine_.independentClockActive()||engine_.hasTemporaryDiagnosticDevice()|| !engine_.allOutputsDisarmed()) @@ -1289,6 +1290,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr &&before.outputDeviceName==playback; auto* previousDevice=manager.getCurrentAudioDevice(); const bool previousWasOpen=previousDevice!=nullptr&&previousDevice->isOpen(); + const bool previousMixerBound=engine_.hasBoundMixerRoute(); const auto confirm=config.getProperty("confirmRetainedPinMapping",false); if(!confirm.isBool()) return send(false,"REJECTED","Invalid retained mixer mapping confirmation"); @@ -1410,8 +1412,8 @@ 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()&&!finishAudioSetupAndRecoverMixer()) { - if(engine_.directRouteAuthorized() && + if(error.isEmpty()&&!finishAudioSetupAndRecoverMixer(true)) { + 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"; diagnostics_.record("CUSTOM_AUDIO_NEEDS_REMAP",needsRemap); @@ -1419,9 +1421,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr emitApprovedNativeSnapshot(); return; } - error="Device opened but direct safe production session was rejected"; + error=mixerSessionError_.isNotEmpty()?mixerSessionError_: + juce::String("Device opened but mixer preparation was rejected"); } if(error.isEmpty()) { + startupError_.clear(); deviceSettingsDirty_=true; directRestore_.cancel(); diagnostics_.record("CUSTOM_AUDIO_APPLY_OK", @@ -1459,7 +1463,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr (previousType!="ASIO"|| (manager.getCurrentAudioDevice()->getInputChannelNames()==originalInputNames&& manager.getCurrentAudioDevice()->getOutputChannelNames()==originalOutputNames))&& - engine_.finishManualAudioSetup(); + finishAudioSetupAndRecoverMixer(); diagnostics_.record("CUSTOM_AUDIO_APPLY_FAIL",error+" | rollback="+ (verified?"RESTORED":"RECOVERY_REQUIRED")+" | "+ juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); @@ -1875,7 +1879,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return armix::session::NativeMixerSessionStore(settingsDirectory()).load(doc,blobs); } - juce::String restoreSavedMixerSession(bool startupOnSavedDevice=false) { + juce::String restoreSavedMixerSession(bool startupOnSavedDevice=false, + armix::session::MixerDeviceBindingPolicy::Mode bindingMode= + armix::session::MixerDeviceBindingPolicy::Mode::exact) { if(!engine_.allOutputsDisarmed() || mixerSessionWorker_.busy() || nativeShowBusy_ || studioBackupBusy_ || engine_.isGraphSwitchPending()) return "MUTE output and finish Studio IO before restoring mixer"; @@ -1911,14 +1917,16 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr diagnostics_.record("DYNAMIC_MIXER_VST3_REMAP_REQUIRED",error); return error; } - const bool resume=startupOnSavedDevice && !usedPrevious && !retained && + const bool resume=startupOnSavedDevice && + bindingMode==armix::session::MixerDeviceBindingPolicy::Mode::exact && + !usedPrevious && !retained && doc.resumeMain.value_or(true); const auto live=engine_.status().getProperty("dryRoutingLab",{}); if(static_cast(live.getProperty("nativeChannelIdPcmActive",false))) { mixerSessionStatus_="LIVE_MIXER_UNCHANGED"; return "Live native mixer already active; refusing to replace it"; } - error=engine_.restoreNativeMixerSession(std::move(doc),states); + error=engine_.restoreNativeMixerSession(std::move(doc),states,false,nullptr,bindingMode); if(error.isNotEmpty()) { mixerSessionStatus_=error.contains("NEEDS_REMAP") ?"NEEDS_REMAP":"RESTORE_REJECTED"; @@ -3744,15 +3752,18 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } } - bool finishAudioSetupAndRecoverMixer() { + bool finishAudioSetupAndRecoverMixer(bool verifiedDeviceApply=false) { 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()) { - const auto error=restoreSavedMixerSession(); + using BindingMode=armix::session::MixerDeviceBindingPolicy::Mode; + const auto error=restoreSavedMixerSession(false,verifiedDeviceApply? + BindingMode::verifiedDeviceApply:BindingMode::exact); if(error.isNotEmpty()) { + mixerSessionError_=error; emitNotice("Mixer retained; "+error,true); return false; } diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index a38f02a94..9e2d0e355 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -20,6 +20,9 @@ struct HardwareBinding final { juce::String backend,capture,playback,inputMask,outputMask; double rate=0.; int frames=0; + // Live pin names guard device switches in this process. Older documents + // still decode without inventing an ASIO pin inventory. + juce::StringArray inputNames,outputNames; }; struct StoredInsert final { ChannelId channel{}; @@ -62,31 +65,37 @@ struct MixerDeviceBindingPolicy final { (!a.monitorEnabled || (a.monitorL==b.monitorL && a.monitorR==b.monitorR)); } - // Preserve the selected physical pairs when they still exist. A new - // pair is only proposed here; apply() requires operator confirmation. + enum class Mode { exact, verifiedDeviceApply }; static VerifiedNativeOutputs proposedOutputs(const MixerSessionDocument& document, - const HardwareBinding& live,int count) { + 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 || + !samePinNames(saved.outputNames,live.outputNames,live.backend))) + return {count,0,1,-1,-1,false}; auto outputs=document.outputs; outputs.activeOutputChannels=count; - if(document.binding.outputMask!=live.outputMask) { - const auto saved=mask(document.binding.outputMask); - const auto current=mask(live.outputMask); - outputs.mainL=remapPin(saved,current,outputs.mainL); - outputs.mainR=remapPin(saved,current,outputs.mainR); + 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); if(outputs.monitorEnabled) { - outputs.monitorL=remapPin(saved,current,outputs.monitorL); - outputs.monitorR=remapPin(saved,current,outputs.monitorR); + outputs.monitorL=remapPin(oldPins,newPins,outputs.monitorL); + outputs.monitorR=remapPin(oldPins,newPins,outputs.monitorR); } } - if(!outputs.valid()) - outputs={count,0,1,outputs.monitorEnabled?2:-1, - outputs.monitorEnabled?3:-1,outputs.monitorEnabled}; + if(!outputs.valid()) { + outputs.monitorL=outputs.monitorR=-1; + outputs.monitorEnabled=false; + } + if(!outputs.valid())outputs={count,0,1,-1,-1,false}; return outputs; } static juce::String apply(MixerSessionDocument& document, const HardwareBinding& live, const VerifiedNativeOutputs& outputs, - int callbackInputs,bool operatorApproved) { + int callbackInputs,Mode mode) { if(!outputs.valid() || callbackInputs<1 || callbackInputs>256 || live.backend.isEmpty() || live.capture.isEmpty() || live.playback.isEmpty() || live.inputMask.isEmpty() || @@ -100,28 +109,30 @@ struct MixerDeviceBindingPolicy final { newPins.countNumberOfSetBits()!=callbackInputs || mask(live.outputMask).countNumberOfSetBits()!=outputs.activeOutputChannels) return "NEEDS_REMAP: callback pin inventory does not match device masks"; - if(sameBinding(document.binding,live) && sameOutputs(document.outputs,outputs)) - return {}; - if(!operatorApproved) - return "NEEDS_REMAP: select the saved audio device and pin layout in Audio I/O"; + const auto& saved=document.binding; + const bool knownInputChanged=!saved.inputNames.isEmpty()&&saved.inputNames!=live.inputNames; + const bool knownOutputChanged=!saved.outputNames.isEmpty()&&saved.outputNames!=live.outputNames; + const bool exact=sameBinding(saved,live)&&sameOutputs(document.outputs,outputs)&& + !knownInputChanged&&!knownOutputChanged; + if(mode==Mode::exact) + return exact?juce::String{}:juce::String( + "NEEDS_REMAP: select the saved audio device and pin layout in Audio I/O"); - if(oldPins!=newPins) { - auto& sources=document.request.sources; - if(document.binding.backend!=live.backend || document.binding.capture!=live.capture) { - // Different endpoint AND different layout: numerical overlap - // cannot establish the identity of a capture pin. - sources.clear(); - } else { - 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); - if(source.inputL>=0 && (!source.stereo || source.inputR>=0)) - mapped.push_back(source); - } - sources=std::move(mapped); + auto& sources=document.request.sources; + if(saved.backend!=live.backend || saved.capture!=live.capture || + !samePinNames(saved.inputNames,live.inputNames,live.backend)) { + // Matching pin numbers alone cannot identify another capture source. + sources.clear(); + } else if(oldPins!=newPins) { + 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); + if(source.inputL>=0 && (!source.stereo || source.inputR>=0)) + mapped.push_back(source); } + sources=std::move(mapped); } document.request.physicalInputs=callbackInputs; document.binding=live; @@ -129,6 +140,10 @@ 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); diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index 1c02fbcbb..d9eee7bc2 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -215,8 +215,7 @@ def show_select(value): # Late readback from the disconnected epoch cannot re-admit audio. emit(page,'arMixConsoleSnapshot',state) assert page.evaluate('()=>window.__ARMIX_NATIVE_M2__.state().current.retained') - # A new WASAPI pair is inspected before exposing a separate, - # explicit confirmation for the retained numbered pin mapping. + # One explicit Apply accepts the verified replacement binding. page.locator('[data-native-io]').click() backend='Windows Audio' active={'backend':backend,'captureDevice':'New Capture','playbackDevice':'New Playback', @@ -234,16 +233,7 @@ def show_select(value): emit(page,'arMixAudioDeviceApplyAck',{'requestId':'old','state':'NEEDS_REMAP', 'active':active,'canReusePins':True}) assert remap.is_hidden() - emit(page,'arMixAudioDeviceApplyAck',{'requestId':opened['requestId'],'state':'NEEDS_REMAP', - 'active':active,'canReusePins':True}) - remap.click() - binding=page.evaluate(read_apply) - assert binding['config']['confirmRetainedPinMapping'] is True - assert binding['expectedDeviceGeneration']==12 - assert binding['config']['captureDevice']=='New Capture' - assert binding['config']['playbackDevice']=='New Playback' - assert binding['config']['sampleRate']==48000 and binding['config']['bufferSize']==256 - emit(page,'arMixAudioDeviceApplyAck',{'requestId':binding['requestId'],'ok':True, + emit(page,'arMixAudioDeviceApplyAck',{'requestId':opened['requestId'],'ok':True, 'state':'ACCEPTED_MUTED','active':active,'mixerBound':True}) assert page.locator('.armix-audio-shade').is_hidden() rebound=copy.deepcopy(state) @@ -257,6 +247,13 @@ def show_select(value): assert page.locator('[data-native-monitor]').get_attribute('data-armed')=='false' assert page.locator('#tracks .strip').count()==4 assert strip.locator('.fx-section [data-action="openPlugin"]').first.inner_text()=='Latency VST' + assert strip.locator('select[data-field="input"]').is_enabled() + assert strip.locator('select[data-field="output"]').is_enabled() + strip.locator('.wire-node-out').click() + assert page.locator('#tracks .strip[data-id="2"] .wire-gain').is_enabled() + strip.locator('.fx-section .fx-pick.empty').click() + assert page.locator('#fastPicker [data-fast-id="test-vst-64"]').is_visible() + page.locator('#fastClose').click() assert page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="monitor").length')==monitor_events assert not errors, errors page.screenshot(path=f'native-cold-start-{width}.png') diff --git a/tests/approved_operator_ux_native_identity_smoke.py b/tests/approved_operator_ux_native_identity_smoke.py index d3fad1e2f..5da36734a 100644 --- a/tests/approved_operator_ux_native_identity_smoke.py +++ b/tests/approved_operator_ux_native_identity_smoke.py @@ -58,12 +58,26 @@ def open_page(): strip.locator(".strip-identity-top").dblclick() assert editor.is_visible(),"double-click header should edit" assert_still(before_editor,page.evaluate(IDENTITY_GEOMETRY),"native double-click") - page.locator("#identityName").fill("Studio Vox") + name=page.locator("#identityName") + assert name.evaluate("e=>document.activeElement===e && e.selectionStart===0 && e.selectionEnd===e.value.length") + before_move=editor.bounding_box() + handle=page.locator("#identityTitle").bounding_box() + assert before_move and handle + page.mouse.move(handle["x"]+8,handle["y"]+handle["height"]/2) + page.mouse.down() + page.mouse.move(handle["x"]+56,handle["y"]+36,steps=6) + page.mouse.up() + moved=editor.bounding_box() + assert moved and abs(moved["x"]-before_move["x"]-48)<2, (before_move,moved) + assert_still(before_editor,page.evaluate(IDENTITY_GEOMETRY),"native editor drag") + assert name.evaluate("e=>e.selectionStart===0 && e.selectionEnd===e.value.length") + page.keyboard.type("Studio Vox") + assert name.input_value()=="Studio Vox" color="#c32974" page.locator(f'#identityColors [data-identity-color="{color}"]').click() icon="🎹" page.locator(f'#identityIcons [data-identity-icon="{icon}"]').click() - page.locator("#identitySave").click() + name.press("Enter") assert editor.is_visible(),"native identity edited before ACK" assert "Studio Vox" not in strip.inner_text(),"optimistic rename without native evidence" req=page.evaluate("""()=>window.__nativeEvents.filter(e=> diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index 1817c2b1f..11176a98e 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -217,6 +217,15 @@ test('DEVICE1 existing matrix drives real JUCE manager with gated native readbac assert.doesNotMatch(io,/audioSelectDevice|setCurrentAudioDeviceType/); }); +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\(!previousMixerBound && engine_\.directRouteAuthorized\(\)/); + assert.match(apply,/finishAudioSetupAndRecoverMixer\(\);/); + assert.match(main,/BindingMode::verifiedDeviceApply:BindingMode::exact/); +}); + test('SETUP1 honest bus patch has real AUX/MAIN/MONITOR navigation, no fake GROUP DCA',()=>{ const patch=read('web/monitor.js'); assert.match(patch,/AUX \/ BUSSING/); diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index 724d32219..7af70f974 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -10,6 +10,7 @@ using namespace armix::mixer; using namespace armix::session; +using BindingMode=MixerDeviceBindingPolicy::Mode; using armix::shows::BinaryState; static MixerSessionDocument makeSession() { @@ -211,6 +212,30 @@ static void nativeDeviceRecovery() { assert(current.inserts.size()==1 && current.inserts[0].catalogId==eqId); current.binding=saved.binding; + // 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. + mixer.deviceStopped(); + device.rate=44100.; + device.frames=512; + mixer.prepareDevice(&device); + auto hdmi=current.binding; + hdmi.playback="LG TV"; + hdmi.rate=device.rate;hdmi.frames=device.frames; + const auto hdmiPair=MixerDeviceBindingPolicy::proposedOutputs( + current,hdmi,2,BindingMode::verifiedDeviceApply); + assert(MixerDeviceBindingPolicy::apply(current,hdmi,hdmiPair,2, + BindingMode::verifiedDeviceApply).isEmpty()); + assert(current.request.sources.size()==1 && current.request.sources[0].stereo); + assert(current.roster.find({1})->sends[1].edgeId==101); + current.request.maxFrames=512; + assert(restore(current,currentStates,true).isEmpty()); + process(true); + assert(outL.back()==0.f && outR.back()==0.f); + assert(mixer.channelIdPhysicalPcmActive()); + process(false); + assert(outL.back()>.02f && outR.back()>.02f); + mixer.deviceStopped(); device.inputMask.clearBit(1); device.rate=44100.; @@ -219,8 +244,8 @@ static void nativeDeviceRecovery() { auto nextBinding=current.binding; nextBinding.inputMask="1";nextBinding.rate=device.rate;nextBinding.frames=device.frames; const auto pair=MixerDeviceBindingPolicy::proposedOutputs(current,nextBinding,2); - assert(MixerDeviceBindingPolicy::apply(current,nextBinding,pair,1,false).isNotEmpty()); - assert(MixerDeviceBindingPolicy::apply(current,nextBinding,pair,1,true).isEmpty()); + assert(MixerDeviceBindingPolicy::apply(current,nextBinding,pair,1,BindingMode::exact).isNotEmpty()); + assert(MixerDeviceBindingPolicy::apply(current,nextBinding,pair,1,BindingMode::verifiedDeviceApply).isEmpty()); assert(current.request.sources.empty()); // lost stereo half is never borrowed assert(current.roster.find({1})->sends[1].edgeId==101); current.request.maxFrames=512; @@ -281,21 +306,38 @@ int main(){ VerifiedNativeOutputs verifiedPair={2,1,0,-1,-1,false}; const auto graphBefore=Codec::encode(remap); auto refusal=MixerDeviceBindingPolicy::apply(remap,replacement, - verifiedPair,2,false); + verifiedPair,2,BindingMode::exact); assert(refusal.startsWith("NEEDS_REMAP")); assert(Codec::encode(remap)==graphBefore); refusal=MixerDeviceBindingPolicy::apply(remap,replacement, - verifiedPair,1,true); + verifiedPair,1,BindingMode::verifiedDeviceApply); assert(refusal.startsWith("NEEDS_REMAP")); assert(Codec::encode(remap)==graphBefore); assert(MixerDeviceBindingPolicy::apply(remap,replacement, - verifiedPair,2,true).isEmpty()); + verifiedPair,2,BindingMode::verifiedDeviceApply).isEmpty()); assert(remap.binding.backend=="WASAPI" && remap.outputs.mainL==1); assert(remap.roster.revision()==d.roster.revision()); assert(remap.roster.find({1})->sends.size()==2 && remap.roster.find({1})->sends[0].edgeId==100); + auto captureChanged=d; + auto identicalMasks=d.binding; + identicalMasks.capture="Another capture"; + assert(MixerDeviceBindingPolicy::apply(captureChanged,identicalMasks,d.outputs,2, + BindingMode::verifiedDeviceApply).isEmpty()); + assert(captureChanged.request.sources.empty()); + assert(captureChanged.roster.find({1})->sends[0].edgeId==100); + + auto reordered=d; + reordered.binding.inputNames={"In 1","In 2"}; + auto reorderedPins=reordered.binding; + reorderedPins.inputNames={"In 2","In 1"}; + assert(MixerDeviceBindingPolicy::apply(reordered,reorderedPins,d.outputs,2, + BindingMode::exact).isNotEmpty()); + assert(MixerDeviceBindingPolicy::apply(reordered,reorderedPins,d.outputs,2, + BindingMode::verifiedDeviceApply).isEmpty()); + assert(reordered.request.sources.empty()); auto exact=d; - assert(MixerDeviceBindingPolicy::apply(exact,d.binding,d.outputs,2,false) + assert(MixerDeviceBindingPolicy::apply(exact,d.binding,d.outputs,2,BindingMode::exact) .isEmpty()); assert(Codec::encode(exact)==graphBefore); ChannelEdit newChannel; From 322c54b0085b8e823333dc942077fbce7144c3a8 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 8 Nov 2026 04:23:32 +0700 Subject: [PATCH 2/7] P0 safety: reject disappearing physical MAIN pins instead of silently rerouting after Audio I/O Apply --- src/NativeMixerSessionDocument.h | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index 9e2d0e355..57904b507 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -89,7 +89,9 @@ struct MixerDeviceBindingPolicy final { outputs.monitorL=outputs.monitorR=-1; outputs.monitorEnabled=false; } - if(!outputs.valid())outputs={count,0,1,-1,-1,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. return outputs; } static juce::String apply(MixerSessionDocument& document, @@ -118,6 +120,19 @@ 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(saved.backend==live.backend && saved.playback==live.playback && + samePinNames(saved.outputNames,live.outputNames,live.backend)) { + const auto mapped=proposedOutputs(document,live, + outputs.activeOutputChannels,Mode::verifiedDeviceApply); + if(!mapped.valid() || !sameOutputs(mapped,outputs)) + return "NEEDS_REMAP: saved MAIN output pins are no longer selected; explicitly choose MAIN outputs"; + } + auto& sources=document.request.sources; if(saved.backend!=live.backend || saved.capture!=live.capture || !samePinNames(saved.inputNames,live.inputNames,live.backend)) { From 239b6f794f37c5ba283a3c00fc1b24643b560f92 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 8 Nov 2026 04:24:21 +0700 Subject: [PATCH 3/7] Refuse same-endpoint ASIO output pin changes without provable physical port identity --- src/NativeMixerSessionDocument.h | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index 57904b507..abf6e3a2a 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -70,9 +70,16 @@ struct MixerDeviceBindingPolicy final { 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 || - !samePinNames(saved.outputNames,live.outputNames,live.backend))) + (saved.backend!=live.backend || saved.playback!=live.playback)) return {count,0,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}; auto outputs=document.outputs; outputs.activeOutputChannels=count; if(saved.outputMask!=live.outputMask) { @@ -125,8 +132,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(saved.backend==live.backend && saved.playback==live.playback && - samePinNames(saved.outputNames,live.outputNames,live.backend)) { + if(saved.backend==live.backend && saved.playback==live.playback) { const auto mapped=proposedOutputs(document,live, outputs.activeOutputChannels,Mode::verifiedDeviceApply); if(!mapped.valid() || !sameOutputs(mapped,outputs)) From 59ca808a39121205ece42dbb910fa3a7e806c73d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 8 Nov 2026 04:24:38 +0700 Subject: [PATCH 4/7] Require explicit MAIN output selection for replacement devices exposing more than one stereo pair --- src/NativeMixerSessionDocument.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index abf6e3a2a..5de3aa3f2 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -71,7 +71,8 @@ struct MixerDeviceBindingPolicy final { const auto& saved=document.binding; if(mode==Mode::verifiedDeviceApply && (saved.backend!=live.backend || saved.playback!=live.playback)) - return {count,0,1,-1,-1,false}; + 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. From cddf25b8c82a2d417d73bd09dc2d1c15b78cbf75 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 8 Nov 2026 04:25:01 +0700 Subject: [PATCH 5/7] Native regression: lost MAIN 3/4 must NEEDS_REMAP, never borrow physical 1/2 --- tests/native_mixer_session_store_test.cpp | 45 +++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index 7af70f974..58c076b6d 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -327,6 +327,51 @@ int main(){ assert(captureChanged.request.sources.empty()); assert(captureChanged.roster.find({1})->sends[0].edgeId==100); + // Output 3/4 was explicitly assigned to MAIN. Disabling those pins + // must NEVER reassign MAIN to still-enabled 1/2 after Audio I/O Apply: + // rejection keeps the original logical/physical saved session intact. + auto main34=d; + main34.binding.outputMask="f"; + main34.binding.outputNames={"OUT 1","OUT 2","OUT 3","OUT 4"}; + main34.outputs={4,2,3,-1,-1,false}; + const auto main34Before=Codec::encode(main34); + auto only12=main34.binding; + only12.outputMask="3"; + const auto missingPair=MixerDeviceBindingPolicy::proposedOutputs( + main34,only12,2,BindingMode::verifiedDeviceApply); + assert(!missingPair.valid()); // never silently return {2,0,1} + assert(MixerDeviceBindingPolicy::apply(main34,only12,missingPair,2, + BindingMode::verifiedDeviceApply).startsWith("NEEDS_REMAP")); + // Even a caller supplying a syntactically valid but unauthorized MAIN + // pair must not bypass the physical-pin identity check. + const VerifiedNativeOutputs unauthorized12={2,0,1,-1,-1,false}; + assert(MixerDeviceBindingPolicy::apply(main34,only12,unauthorized12,2, + BindingMode::verifiedDeviceApply).startsWith("NEEDS_REMAP")); + assert(Codec::encode(main34)==main34Before); + // 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; + only34.outputMask="c"; + const auto preservedMain=MixerDeviceBindingPolicy::proposedOutputs( + main34,only34,2,BindingMode::verifiedDeviceApply); + assert(preservedMain.valid() && preservedMain.mainL==0 && preservedMain.mainR==1); + auto main34Accepted=main34; + assert(MixerDeviceBindingPolicy::apply(main34Accepted,only34,preservedMain,2, + BindingMode::verifiedDeviceApply).isEmpty()); + assert(main34Accepted.outputs.mainL==0 && main34Accepted.outputs.mainR==1); + assert(main34Accepted.binding.outputMask=="c"); + assert(main34Accepted.roster.revision()==main34.roster.revision()); + // Changed ASIO output identity (or unknown inventory with changed + // mask) must fail closed until the user chooses an explicit MAIN pair. + auto renamed34=main34.binding; + renamed34.outputNames={"Other 1","Other 2","Other 3","Other 4"}; + assert(!MixerDeviceBindingPolicy::proposedOutputs(main34,renamed34,4, + BindingMode::verifiedDeviceApply).valid()); + auto newOutputs=main34.binding; + newOutputs.playback="Different playback endpoint"; + assert(!MixerDeviceBindingPolicy::proposedOutputs(main34,newOutputs,4, + BindingMode::verifiedDeviceApply).valid()); + auto reordered=d; reordered.binding.inputNames={"In 1","In 2"}; auto reorderedPins=reordered.binding; From 8af626a2f14b1463ed014870fbef85ac1563c195 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 8 Nov 2026 04:55:25 +0700 Subject: [PATCH 6/7] Enable verified MAIN automatically and cache VST3 discovery --- src/LiveAudioEngine.h | 21 +--- src/LiveDryRoutingLab.h | 8 +- src/Main.cpp | 79 +++++++++++---- src/NativeMixerSessionFxRestore.h | 9 +- src/PluginCatalog.h | 18 +++- src/Vst3DescriptionCache.h | 110 +++++++++++++++++++++ tests/approved_native_cold_start_smoke.py | 17 +++- tests/approved_native_m2_contract.test.cjs | 25 ++--- tests/native_mixer_session_store_test.cpp | 30 ++++++ web/approved-native-bridge.js | 78 +++------------ 10 files changed, 265 insertions(+), 130 deletions(-) create mode 100644 src/Vst3DescriptionCache.h diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 565d895ef..af6512a79 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -855,11 +855,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); if(!(rate>0.0) || frames>maxFrames) return "Unsupported device sample rate or buffer quantum"; - juce::OwnedArray descriptions; - fmt->findAllTypesForFile(descriptions,filename); - juce::PluginDescription* chosen=nullptr; - for(auto* d:descriptions) - if(d && d->uniqueId==uid && !d->isInstrument) { chosen=d;break; } + const auto chosen=armix::vst::DescriptionCache::resolve(*fmt,filename,uid); if(!chosen)return "Effect identity not found inside VST3 module"; juce::String error; auto instance=formats_.createPluginInstance(*chosen,rate,frames,error); @@ -967,13 +963,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if (fx.binary.getSize() > armix::storage::NativePresetArchive::maxStateBytes || !juce::File (fx.path).exists() || !fx.path.endsWithIgnoreCase (".vst3")) return "Plugin is missing or invalid: " + fx.name; - juce::OwnedArray descriptions; - fmt->findAllTypesForFile (descriptions, fx.path); - juce::PluginDescription* match = nullptr; - for (auto* candidate : descriptions) - if (candidate != nullptr && candidate->uniqueId == fx.uid && - !candidate->isInstrument) - { match = candidate; break; } + const auto match=armix::vst::DescriptionCache::resolve(*fmt,fx.path,fx.uid); if (!match) return "VST3 plugin identity missing: " + fx.name; juce::String error; @@ -1742,12 +1732,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if(!fmt||!fmt->fileMightContainThisPluginType(path)) {fail.error="NATIVE_VST3_MODULE_NOT_FOUND";return fail;} try { - juce::OwnedArray descriptions; - fmt->findAllTypesForFile(descriptions,path); - juce::PluginDescription* chosen=nullptr; - for(auto* item:descriptions) - if(item&&item->uniqueId==uid&&!item->isInstrument) - {chosen=item;break;} + const auto chosen=armix::vst::DescriptionCache::resolve(*fmt,path,uid); if(!chosen){fail.error="NATIVE_VST3_IDENTITY_NOT_FOUND";return fail;} juce::String pluginError; auto instance=formats_.createPluginInstance(*chosen,rate, diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 052949ff9..9076ba586 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1,5 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-only #pragma once +#include "Vst3DescriptionCache.h" #include "../engine/core/PreparedMixerBlock.h" #include "../engine/core/MasterOutputMonoPolicy.h" #include "../engine/core/LiveChannelFxGraph.h" @@ -386,12 +387,7 @@ class LiveDryRoutingLab final { auto* fmt=formats.getFormat(0); if(!fmt || !fmt->fileMightContainThisPluginType(req.path)) return label+": VST3 module unavailable; rescan catalog"; - juce::OwnedArray descriptions; - fmt->findAllTypesForFile(descriptions,req.path); - juce::PluginDescription* chosen=nullptr; - for(auto* item:descriptions) - if(item && item->uniqueId==req.uid && !item->isInstrument) - {chosen=item;break;} + const auto chosen=armix::vst::DescriptionCache::resolve(*fmt,req.path,req.uid); if(!chosen) return label+": selected effect identity is unavailable or instrument"; juce::String pluginError; diff --git a/src/Main.cpp b/src/Main.cpp index e08a8581f..8e365629d 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1218,6 +1218,35 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return juce::var(o.release()); } + // 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; + std::optional autoMainCheckedRevision_; + void serviceAutomaticMain() { + if(autoMainEpoch_==0)return; + if(autoMainEpoch_!=engine_.dryRoutingLabEpoch() || + engine_.isMonitorEnabled()) { + autoMainEpoch_=0; + return; + } + if(nativeShowBusy_||studioBackupBusy_||engine_.secondaryArmed()|| + engine_.diagnosticRoute()!=armix::diagnostics::Route::normal)return; + const auto revision=engine_.outputArmRevision(); + if(autoMainCheckedRevision_==revision)return; + if(engine_.isGraphSwitchPending()||!engine_.hasBoundMixerRoute())return; + autoMainCheckedRevision_=revision; + if(engine_.liveOutputArmFault().isNotEmpty())return; + engine_.setMonitorEnabled(true); + autoMainEpoch_=0; + diagnostics_.record("MAIN_AUTO_ENABLED","Verified device, input and MAIN output"); + } + + void requestAutomaticMain() { + autoMainEpoch_=engine_.dryRoutingLabEpoch(); + autoMainCheckedRevision_.reset(); + serviceAutomaticMain(); + } + void applyCustomAudioDevice(const juce::var& args) { // Synchronous manager operations stay on JUCE's established message @@ -1250,9 +1279,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr engine_.isGraphSwitchPending()|| static_cast(nativeRoute.getProperty("pending",false))|| engine_.independentClockActive()||engine_.hasTemporaryDiagnosticDevice()|| - !engine_.allOutputsDisarmed()) + engine_.secondaryArmed()) return send(false,"REJECTED", - "MUTE MAIN and secondary output; finish Show/FX/diagnostic/clock transition first"); + "Stop STREAM and finish Show/FX/diagnostic/clock transition first"); const auto config=args.getProperty("config",{}); if(!config.isObject())return send(false,"REJECTED","Missing device configuration"); const auto typeName=config.getProperty("backend",{}).toString(); @@ -1291,6 +1320,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr auto* previousDevice=manager.getCurrentAudioDevice(); const bool previousWasOpen=previousDevice!=nullptr&&previousDevice->isOpen(); const bool previousMixerBound=engine_.hasBoundMixerRoute(); + const bool previousMonitor=engine_.isMonitorEnabled(); const auto confirm=config.getProperty("confirmRetainedPinMapping",false); if(!confirm.isBool()) return send(false,"REJECTED","Invalid retained mixer mapping confirmation"); @@ -1306,7 +1336,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr deviceSettingsDirty_=true; directRestore_.cancel(); diagnostics_.record("CUSTOM_AUDIO_REMAP_ACCEPTED",typeName); - send(true,"ACCEPTED_MUTED",{}); + requestAutomaticMain(); + send(true,engine_.isMonitorEnabled()?"ACCEPTED_LIVE":"ACCEPTED_MUTED",{}); emitApprovedNativeSnapshot(); return; } @@ -1373,6 +1404,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr !engine_.abandonPendingDirectRestoreForSetup()) return send(false,"REJECTED","Failed to prepare an explicit replacement for the missing device"); const auto start=monotonicMilliseconds(); + autoMainEpoch_=0; engine_.beginManualAudioSetup(); if(!unchangedDevice)manager.setCurrentAudioDeviceType(typeName,false); // JUCE setAudioDeviceSetup() can return success without reopening when @@ -1430,7 +1462,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr directRestore_.cancel(); diagnostics_.record("CUSTOM_AUDIO_APPLY_OK", typeName+" | "+juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); - send(true,"ACCEPTED_MUTED",{}); + requestAutomaticMain(); + send(true,engine_.isMonitorEnabled()?"ACCEPTED_LIVE":"ACCEPTED_MUTED",{}); emitApprovedNativeSnapshot(); return; } @@ -1467,7 +1500,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr diagnostics_.record("CUSTOM_AUDIO_APPLY_FAIL",error+" | rollback="+ (verified?"RESTORED":"RECOVERY_REQUIRED")+" | "+ juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); - send(false,verified?"RESTORED_MUTED":"RECOVERY_REQUIRED",error); + if(verified&&previousMonitor)requestAutomaticMain(); + send(false,verified?(engine_.isMonitorEnabled()?"RESTORED_LIVE":"RESTORED_MUTED"): + "RECOVERY_REQUIRED",error); emitApprovedNativeSnapshot(); } @@ -1477,6 +1512,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (setupLaunching_) return; // 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(); // The native JUCE device list is cached after first construction: @@ -1500,6 +1536,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (safe == nullptr) return; if (safe->finishAudioSetupAndRecoverMixer()) { + safe->requestAutomaticMain(); safe->deviceSettingsDirty_ = true; safe->startupError_.clear(); safe->diagnostics_.record ("DIRECT_ROUTE_APPROVED", @@ -1935,8 +1972,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return error; } mixerSessionRecoveryPending_=false; - if(resume && engine_.liveOutputArmFault(false).isEmpty()) - engine_.setMonitorEnabled(true); + if(resume)requestAutomaticMain(); mixerSessionStatus_=engine_.isMonitorEnabled()?"RESTORED_MONITORING":"RESTORED_MUTED"; mixerSessionError_.clear(); diagnostics_.record("DYNAMIC_MIXER_RESTORED",mixerSessionStatus_); @@ -2008,6 +2044,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } void openMixerFile(const juce::File& file) { + autoMainEpoch_=0; const auto chosenEpoch=engine_.dryRoutingLabEpoch(); auto safe=juce::Component::SafePointer(this); if(!mixerSessionWorker_.load(file,[safe,chosenEpoch,file](juce::String error, @@ -3195,6 +3232,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr "Verified native Show routing and VST3 state restored in a newly prepared graph. OUTPUT remains MUTED; verify physical routing and plugin sound before unmuting."); }); if(!started)return reject("Cannot launch native Show readback worker."); + autoMainEpoch_=0; nativeShowBusy_=true; return; } @@ -3721,6 +3759,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr engine_.diagnosticRoute()==armix::diagnostics::Route::normal) fault=engine_.liveOutputArmFault(); if (fault.isEmpty()) { + autoMainEpoch_=0; engine_.setMonitorEnabled(arm); diagnostics_.record("OUTPUT_MUTE",arm?"OFF":"ON"); } @@ -3838,19 +3877,22 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr engine_.devices().addChangeListener (this); diagnostics_.record ("STARTUP", startupError_.isEmpty() ? "Audio device initialized" : startupError_); - if(!mixerSessionStartupInspected_) { - mixerSessionStartupInspected_=true; - if(armix::session::NativeMixerSessionStore(settingsDirectory()).exists()){ - mixerSessionRecoveryPending_=true; - const auto error=restoreSavedMixerSession(startupError_.isEmpty()); - if(error.isNotEmpty()) - emitNotice("Saved mixer retained; "+error,true); - else if(saved==nullptr) - deviceSettingsDirty_=true; - } - } if (onStartupStage_) onStartupStage_ (2); } + // Factory entries are published only after asynchronous manifest + // verification. Restore once they are visible, never reject a saved + // factory insert simply because the startup catalog is still busy. + if(!mixerSessionStartupInspected_ && !catalog_.busy()) { + mixerSessionStartupInspected_=true; + if(armix::session::NativeMixerSessionStore(settingsDirectory()).exists()){ + mixerSessionRecoveryPending_=true; + const auto error=restoreSavedMixerSession(startupError_.isEmpty()); + if(error.isNotEmpty()) + emitNotice("Saved mixer retained; "+error,true); + else + deviceSettingsDirty_=true; + }else if(startupError_.isEmpty())requestAutomaticMain(); + } // 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. @@ -3870,6 +3912,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(); + serviceAutomaticMain(); // Autosave only while ALL outputs are muted. Vendor-state reads // happen on CONTROL; disk commits run on ONE serialized IO worker. // A performance with armed speakers/stream is never interrupted for diff --git a/src/NativeMixerSessionFxRestore.h b/src/NativeMixerSessionFxRestore.h index 7bab6ca48..45b97911b 100644 --- a/src/NativeMixerSessionFxRestore.h +++ b/src/NativeMixerSessionFxRestore.h @@ -2,6 +2,7 @@ #pragma once #include "NativeMixerSessionDocument.h" #include "VstBusLayout.h" +#include "Vst3DescriptionCache.h" #include "../engine/builtin_fx/ChannelEqProcessor.h" #include #include @@ -77,12 +78,8 @@ class NativeMixerSessionFxRestore final { if(!format|| !format->fileMightContainThisPluginType(insert.path)) return "Saved VST3 unavailable: "+insert.catalogId; - juce::OwnedArray descriptions; - format->findAllTypesForFile(descriptions,insert.path); - juce::PluginDescription* chosen=nullptr; - for(auto* d:descriptions) - if(d&&d->uniqueId==insert.uid&&!d->isInstrument) - {chosen=d;break;} + const auto chosen=armix::vst::DescriptionCache::resolve( + *format,insert.path,insert.uid); if(!chosen)return "Saved VST3 identity not found: "+insert.catalogId; juce::String pluginError; processor=formats.createPluginInstance(*chosen,sampleRate,frames,pluginError); diff --git a/src/PluginCatalog.h b/src/PluginCatalog.h index 9b7899964..51719fae3 100644 --- a/src/PluginCatalog.h +++ b/src/PluginCatalog.h @@ -5,6 +5,7 @@ #include "PortableWorkspace.h" #include "PluginVault.h" #include "FactoryFxRegistry.h" +#include "Vst3DescriptionCache.h" #include #if JUCE_WINDOWS #include @@ -263,8 +264,21 @@ class PluginCatalog final } if (format.fileMightContainThisPluginType (path)) { - juce::OwnedArray descriptions; - format.findAllTypesForFile (descriptions, path); + armix::vst::DescriptionCache cache; + auto descriptions=factoryOnly_?cache.read(path): + armix::vst::DescriptionCache::Descriptions{}; + const bool missingFactoryType=factoryOnly_&&std::any_of( + factory.candidates.begin(),factory.candidates.end(),[&](const auto& approved){ + return approved.path==path&&std::none_of(descriptions.begin(), + descriptions.end(),[&](const auto* entry){ + return entry->uniqueId==approved.hostUniqueId&&!entry->isInstrument; + }); + }); + if(descriptions.isEmpty()||missingFactoryType) { + descriptions.clear(); + format.findAllTypesForFile(descriptions,path); + cache.remember(descriptions); + } for (int i = 0; i < descriptions.size(); ++i) { const auto* desc = descriptions[i]; diff --git a/src/Vst3DescriptionCache.h b/src/Vst3DescriptionCache.h new file mode 100644 index 000000000..aa8f43ab9 --- /dev/null +++ b/src/Vst3DescriptionCache.h @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "PortableWorkspace.h" +#include +#include +#include +#include + +namespace armix::vst { +// Machine-local discovery metadata. The host still creates a fresh processor +// and restores its state. No module scanning or file IO belongs in the callback. +class DescriptionCache final { +public: + using Descriptions=juce::OwnedArray; + + static std::optional resolve( + juce::AudioPluginFormat& format,const juce::String& path,int uid) { + if(!format.fileMightContainThisPluginType(path))return {}; + DescriptionCache cache; + if(auto saved=cache.find(path,uid))return saved; + const auto stamp=moduleStamp(juce::File(path)); + Descriptions discovered; + format.findAllTypesForFile(discovered,path); + // A module updated while scanning must not seed a warm cache. + if(stamp.isNotEmpty()&&stamp==moduleStamp(juce::File(path))) + cache.remember(discovered); + for(const auto* item:discovered) + if(item && item->uniqueId==uid && !item->isInstrument)return *item; + return {}; + } + + explicit DescriptionCache(juce::File root=storage::PortableWorkspace::machineDataRoot() + .getChildFile("Vst3Descriptions")) : root_(std::move(root)) {} + + void remember(const Descriptions& descriptions) const { + std::map> modules; + for(const auto* item:descriptions) + if(item && item->pluginFormatName=="VST3" && + juce::File::isAbsolutePath(item->fileOrIdentifier)) + modules[item->fileOrIdentifier].push_back(item); + for(const auto& [path,items]:modules) { + const auto stamp=moduleStamp(juce::File(path)); + if(stamp.isEmpty())continue; + juce::XmlElement root("VST3_DESCRIPTIONS_V1"); + root.setAttribute("stamp",stamp); + for(const auto* item:items)root.addChildElement(item->createXml().release()); + if(!root_.createDirectory().wasOk())return; + const auto xml=root.toString(); + if(xml.getNumBytesAsUTF8()<=maxBytes)fileFor(path).replaceWithText(xml); + } + } + + std::optional find(const juce::String& path,int uid) const { + const auto descriptions=read(path); + for(const auto* item:descriptions) + if(item->uniqueId==uid && !item->isInstrument)return *item; + return {}; + } + + Descriptions read(const juce::String& path) const { + Descriptions descriptions; + if(!juce::File::isAbsolutePath(path))return descriptions; + const auto file=fileFor(path); + if(!file.existsAsFile()||file.getSize()>maxBytes)return descriptions; + const auto stamp=moduleStamp(juce::File(path)); + if(stamp.isEmpty())return descriptions; + const auto root=juce::XmlDocument::parse(file); + if(!root||!root->hasTagName("VST3_DESCRIPTIONS_V1")|| + root->getStringAttribute("stamp")!=stamp)return descriptions; + for(auto* child:root->getChildIterator()) { + auto item=std::make_unique(); + if(!item->loadFromXml(*child) || item->fileOrIdentifier!=path || + item->pluginFormatName!="VST3")return {}; + descriptions.add(item.release()); + } + return descriptions; + } + +private: + static constexpr int maxBytes=1024*1024; + juce::File root_; + + juce::File fileFor(const juce::String& path) const { + return root_.getChildFile(juce::SHA256(path.toRawUTF8(), + path.getNumBytesAsUTF8()).toHexString()+".xml"); + } + + static juce::String moduleStamp(const juce::File& module) { + if(!module.hasFileExtension("vst3")||!module.exists())return {}; + juce::StringArray parts; + const auto add=[&](const juce::File& file) { + parts.add(file.getFullPathName()+"|"+juce::String(file.getSize())+"|"+ + juce::String(file.getLastModificationTime().toMilliseconds())+"|"+ + juce::String(file.getCreationTime().toMilliseconds())); + }; + if(module.existsAsFile())add(module); + else { + // Only known VST3 binary/manifest paths, not vendor asset trees. + const auto contents=module.getChildFile("Contents"); + const auto binary=contents.getChildFile("x86_64-win").getChildFile(module.getFileName()); + if(!binary.existsAsFile())return {}; + add(binary); + const auto manifest=contents.getChildFile("Resources").getChildFile("moduleinfo.json"); + if(manifest.existsAsFile())add(manifest); + } + const auto stamp=parts.joinIntoString("\n"); + return juce::SHA256(stamp.toRawUTF8(),stamp.getNumBytesAsUTF8()).toHexString(); + } +}; +} diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index d9eee7bc2..433b64d22 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -234,17 +234,17 @@ def show_select(value): 'active':active,'canReusePins':True}) assert remap.is_hidden() emit(page,'arMixAudioDeviceApplyAck',{'requestId':opened['requestId'],'ok':True, - 'state':'ACCEPTED_MUTED','active':active,'mixerBound':True}) + '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=False) + rebound['device'].update(epoch='93',outputArmed=True) rebound['graph']['revision']='6' rebound['mixerSession'].update(deviceEpoch='93',routeRevision='6') monitor_events=page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="monitor").length') emit(page,'arMixConsoleSnapshot',rebound) page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__.state().current?.admitted') assert page.locator('[data-native-monitor]').is_enabled() - assert page.locator('[data-native-monitor]').get_attribute('data-armed')=='false' + assert page.locator('[data-native-monitor]').get_attribute('data-armed')=='true' assert page.locator('#tracks .strip').count()==4 assert strip.locator('.fx-section [data-action="openPlugin"]').first.inner_text()=='Latency VST' assert strip.locator('select[data-field="input"]').is_enabled() @@ -254,6 +254,17 @@ def show_select(value): strip.locator('.fx-section .fx-pick.empty').click() assert page.locator('#fastPicker [data-fast-id="test-vst-64"]').is_visible() page.locator('#fastClose').click() + # Apply again while MAIN is live. The native transaction owns + # temporary mute and restoration without an extra browser command. + page.locator('[data-native-io]').click() + emit(page,'arMixAudioDeviceInventory',{'active':active,'types':[ + {'name':backend,'inputs':['New Capture'],'outputs':['New Playback'],'separate':True}]}) + page.locator('[data-audio-apply]').click() + repeated=page.evaluate(read_apply) + assert repeated['requestId']!=opened['requestId'] + emit(page,'arMixAudioDeviceApplyAck',{'requestId':repeated['requestId'],'ok':True, + 'state':'ACCEPTED_LIVE','active':active,'mixerBound':True,'outputMuted':False}) + assert page.locator('.armix-audio-shade').is_hidden() assert page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="monitor").length')==monitor_events assert not errors, errors page.screenshot(path=f'native-cold-start-{width}.png') diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index c02f20fbf..df731980c 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -130,7 +130,7 @@ test("P0 DAW approved Windows GUI directly binds every IN to current JUCE ports, assert.match(bridge,/const savedId = uiByNativeId\.get\(ch\.id\) \?\? m4Id/); assert.match(bridge,/action:"routingSourceSwitch"/); assert.match(bridge,/row\?\.left===p\.choice\.left/); - assert.match(bridge,/expectedEpoch:p\.epoch,expectedRevision:Number\(next\.revision\)/); + assert.match(nativeMain,/autoMainEpoch_!=engine_\.dryRoutingLabEpoch\(\)/); assert.match(bridge,/inputSelect\.hidden=true;routeBtn\.hidden=true;armBtn\.hidden=true/); assert.match(bridge,/openNativeAudioIO\(\)/); assert.match(bridge,/\.armix-audio-shade\[hidden\]\{display:none\}/); @@ -160,8 +160,7 @@ test("DAW G0 native M4 controls, source clear, OUT & monitoring are real",()=>{ assert.match(bridge,/action:"routingChannelPatch"/); assert.match(bridge,/const channel=m4Index\(t\)/); assert.match(bridge,/data-native-monitor/); - assert.match(bridge,/const firstListen=p.autoListen/); - assert.match(bridge,/next\.nativeChannelIdPcmActive===true \|\|/); + assert.match(native,/void serviceAutomaticMain\(\)/); assert.match(native,/if\(action=="routingM4Control"\)/); assert.match(native,/engine_\.setDryRoutingLabParameter\(channel,/); assert.match(native,/if\(action=="routingChannelPatch"\)/); @@ -633,9 +632,9 @@ test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ assert.match(engine,/currentSetup\.outputDeviceName/); assert.match(engine,/MONITOR OFF: VB-Cable capture\/playback self-loop/); assert.match(bridge,/const virtualCableFeedbackPair=/); - assert.match(bridge,/next\.nativeChannelIdPcmActive===true/); - assert.match(bridge,/if\(firstListen && !virtualCableFeedbackPair\(\)\)/); - assert.match(bridge,/VB-Cable feedback loop; select physical playback/); + const native=read("src/Main.cpp"); + assert.match(native,/if\(engine_\.liveOutputArmFault\(\)\.isNotEmpty\(\)\)return;/); + assert.match(native,/autoMainEpoch_!=engine_\.dryRoutingLabEpoch\(\)/); }); test("single /preview/ GUI: channel IN, actual OUT and correlated device safety ACK",()=>{ const pages=read("scripts/build_pages.py"); @@ -647,9 +646,8 @@ test("single /preview/ GUI: channel IN, actual OUT and correlated device safety assert.match(bridge,/source:"\/preview\/ approved compiled Pages GUI"/); assert.match(bridge,/field==="input"/); assert.match(bridge,/nativeUiSourcePending=null;[\s\S]*?INPUT timeout/); - assert.match(bridge,/row\?\.main===true/); - assert.match(bridge,/pendingDeviceMute=\{requestId,epoch:String\(hardware\.device\.epoch\)\}/); - assert.match(bridge,/ack\?\.requestId!==pendingDeviceMute\.requestId/); + assert.match(bridge,/ack\?\.requestId!==devicePanel.dataset.pendingRequest/); + assert.match(native,/requestAutomaticMain\(\);\s*send\(true,engine_\.isMonitorEnabled\(\)\?"ACCEPTED_LIVE":"ACCEPTED_MUTED"/); assert.match(bridge,/VIRTUAL \/ NO SPEAKERS/); assert.match(bridge,/Advanced driver recovery/); assert.match(native,/ack->setProperty\("requestId",[\s\S]*?args\.getProperty\("requestId",juce::var\(\)\)/); @@ -1179,7 +1177,7 @@ 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 FIRST SOUND G0 NONE authority exposes verified physical IN before any route and arms only after native ACK",()=>{ +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; const tracks=Array.from({length:10},(_,i)=>({ @@ -1255,11 +1253,8 @@ test("P0 FIRST SOUND G0 NONE authority exposes verified physical IN before any r }); const monitors=sent.filter(x=>x.name==="arMixAction"&& x.payload.action==="monitor"); - assert.equal(monitors.length,1, - "first accepted input routed to MAIN authorizes one automatic safe listen"); - assert.equal(monitors[0].payload.value,true); - assert.equal(monitors[0].payload.expectedEpoch,69); - assert.equal(monitors[0].payload.expectedRevision,13); + assert.equal(monitors.length,0, + "native owns automatic MAIN; the bridge never emits a second arm request"); assert.equal(tracks[4].input,"None", "GUI must wait for a subsequent independent native readback"); const none=clone(boot); diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index 58c076b6d..1d4328462 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -281,7 +281,37 @@ static void nativeDeviceRecovery() { std::cout<<"Native callback cold restore, muted meters, repeated reopen, FX, sparse remap and PCM: PASS\n"; } +static void warmVst3Discovery() { + const auto root=juce::File::getSpecialLocation(juce::File::tempDirectory) + .getNonexistentChildFile("ArSonMixVst3Cache","",false); + assert(root.createDirectory().wasOk()); + const auto module=root.getChildFile("Shell.vst3"); + assert(module.replaceWithText("module v1")); + const auto cacheRoot=root.getChildFile("Cache"); + armix::vst::DescriptionCache::Descriptions scanned; + for(int uid:{31,45,72}) { + auto item=std::make_unique(); + item->fileOrIdentifier=module.getFullPathName(); + item->pluginFormatName="VST3"; + item->name="Shell class "+juce::String(uid); + item->uniqueId=uid; + item->deprecatedUid=uid+1000; + item->isInstrument=uid==45; + scanned.add(item.release()); + } + armix::vst::DescriptionCache(cacheRoot).remember(scanned); + const armix::vst::DescriptionCache nextProcess(cacheRoot); + const auto cached=nextProcess.find(module.getFullPathName(),72); + assert(cached&&cached->name=="Shell class 72"&&cached->deprecatedUid==1072); + assert(nextProcess.read(module.getFullPathName())[1]->uniqueId==45); + assert(!nextProcess.find(module.getFullPathName(),45)); + assert(module.appendText("updated module binary")); + assert(!nextProcess.find(module.getFullPathName(),72)); + assert(root.deleteRecursively()); +} + int main(){ + warmVst3Discovery(); nativeDeviceRecovery(); auto d=makeSession(); const auto before=Codec::encode(d); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 4920ac149..2006061d3 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1324,7 +1324,7 @@ function syncMonitorButton(d) { const monitorButton=document.querySelector?.("[data-native-monitor]"); if(monitorButton){ - monitorButton.textContent=d?.outputArmed?"Monitor On":"Monitor Off"; + monitorButton.textContent=d?.outputArmed?"Mute Output":"Unmute Output"; monitorButton.setAttribute("aria-pressed",String(!!d?.outputArmed)); monitorButton.title=d?.outputArmed? "Mute actual MAIN output immediately":"Listen through verified MAIN hardware output"; @@ -1409,7 +1409,7 @@ // Only the existing AudioDeviceManager inventory/APPLY API is used. This // replaces the 740x590 default JUCE dialog for normal operator setup. let devicePanel=null,deviceInventory=null,deviceBusy=false, - deviceRequest=0,pendingDeviceMute=null,deviceChoice=null,deviceResult="", + deviceRequest=0,deviceChoice=null,deviceResult="", offeredPinRemap=null; let toastTimer=0; function nativeToast(message){ @@ -1525,29 +1525,13 @@ renderDevicePanel(); }); devicePanel.querySelector("[data-audio-apply]").onclick=()=>{ - if(deviceBusy||pendingDeviceMute||!deviceChoice||!deviceInventory?.active)return; + if(deviceBusy||!deviceChoice||!deviceInventory?.active)return; const draft=deviceChoice,active=deviceInventory.active; if(!draft.backend||!draft.capture||!draft.playback)return; - if(hardware?.device?.outputArmed){ - // Correlate one deliberate MUTE to this Apply. An unrelated ACK - // must never authorize a hardware switch. - const requestId="device-mute-"+(++deviceRequest); - pendingDeviceMute={requestId,epoch:String(hardware.device.epoch)}; - devicePanel.querySelector("[data-audio-apply]").disabled=true; - devicePanel.querySelector("[data-audio-active]").textContent= - "Muting current output before changing driver…"; - backend.emitEvent("arMixAction",{action:"monitor",value:false,requestId}); - window.setTimeout(()=>{ - if(pendingDeviceMute?.requestId!==requestId)return; - pendingDeviceMute=null; - deviceResult="Driver change cancelled: no verified MUTE acknowledgement."; - renderDevicePanel(); - },8000); - }else sendDeviceApply(); + sendDeviceApply(); }; devicePanel.querySelector("[data-audio-remap]").onclick=()=>{ - if(!deviceBusy && !pendingDeviceMute && offeredPinRemap!==null && - !hardware?.device?.outputArmed) + if(!deviceBusy && offeredPinRemap!==null) sendDeviceApply(true); }; document.body.appendChild(devicePanel); @@ -1634,11 +1618,11 @@ "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|| - !!pendingDeviceMute||!deviceChoice.backend||!deviceChoice.capture|| + !deviceChoice.backend||!deviceChoice.capture|| !deviceChoice.playback; const remap=devicePanel.querySelector("[data-audio-remap]"); remap.hidden=!same || offeredPinRemap!==active.deviceGeneration; - remap.disabled=deviceBusy || !!pendingDeviceMute; + remap.disabled=deviceBusy; remap.title="Reuse existing input and output pin numbers on the selected device. MONITOR stays off."; } function sendDeviceApply(confirmRetainedPinMapping=false){ @@ -1677,14 +1661,16 @@ ack.active?.open===true && ack.active?.authorized===true && Number.isSafeInteger(ack.active.deviceGeneration)? ack.active.deviceGeneration:null; - const accepted=ack.ok===true&&ack.state==="ACCEPTED_MUTED" && + 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? - (ack.mixerBound?"Mixer ready · MONITOR OFF":"Audio device ready · choose an IN on any channel"): + (outputReady?"Mixer ready · Output live": + ack.mixerBound?"Mixer ready · Verify channel IN and output":"Audio device ready · choose a channel IN"): ack.state==="NEEDS_REMAP"? "NEEDS REMAP · "+ack.error: "Device rejected · "+(ack.error||"native hardware readback failed"); @@ -1692,9 +1678,8 @@ if(accepted){ devicePanel.hidden=true; status("DEVICE READY · "+ack.active.backend+" · "+ - ack.active.rate+" Hz / "+ack.active.buffer+" samples · MONITOR OFF"); - nativeToast(ack.mixerBound?"Mixer ready · MONITOR OFF": - "Audio device connected · "+ack.active.backend+" · "+ack.active.rate+" Hz · choose channel IN"); + ack.active.rate+" Hz / "+ack.active.buffer+" samples"); + nativeToast(deviceResult); controller?.subscribe(); }else renderDevicePanel(); }); @@ -1956,7 +1941,7 @@ io.title="Select ASIO/WASAPI driver and capture/playback device"; io.addEventListener("click",openNativeAudioIO); toolbar.insertBefore(io,document.getElementById("moreTools")); - const monitor=item("button","tool","Monitor Off"); + const monitor=item("button","tool","Unmute Output"); monitor.dataset.nativeMonitor="true"; monitor.addEventListener("click",()=>{ const armed=hardware?.device?.outputArmed===true; @@ -1991,9 +1976,7 @@ rev=safeNativeCounter(legacy()?.routingRevision); if(ep===null||rev===null)return; const requestId=++sourceSerial; - nativeUiSourcePending={requestId,channel,choice,epoch:ep,revision:rev, - autoListen:legacy()?.routeAccepted!==true && - hardware?.device?.outputArmed!==true}; + nativeUiSourcePending={requestId,channel,choice,epoch:ep,revision:rev}; backend.emitEvent("arMixAction",{action:"routingSourceSwitch", requestId,channel,mode:choice.mode,left:choice.left,right:choice.right, deviceEpoch:ep,revision:rev}); @@ -2242,23 +2225,7 @@ // Native publisher + engine own the accepted graph; refresh the // UI only from a subsequent authoritative snapshot. controller.subscribe(); - const firstListen=p.autoListen && row?.main===true && - (next.nativeChannelIdPcmActive===true || - (Array.isArray(next.channelControls)&&next.channelControls.length===10)) && - hardware?.device?.epoch===String(p.epoch); - // Never arm physical audio when the GUI still lacks admitted PCM - // controls, or when capture and playback feed the *same* VB Cable. - // Native C++ enforces the feedback policy a second time. - if(firstListen && !virtualCableFeedbackPair()) { - backend.emitEvent("arMixAction",{action:"monitor",value:true, - expectedEpoch:p.epoch,expectedRevision:Number(next.revision)}); - } - if(firstListen && virtualCableFeedbackPair()) - status("MONITOR OFF · VB-Cable feedback loop; select physical playback"); - else if(p.autoListen && !firstListen) - status("CH "+(p.channel+1)+" routed · PCM controls not yet admitted; MONITOR OFF"); - else - status("CH "+(p.channel+1)+" native input accepted"); + status("CH "+(p.channel+1)+" native input accepted"); } else { status("NATIVE INPUT REJECTED · "+(ack?.error||"stale routing")); controller.subscribe(); @@ -2385,19 +2352,6 @@ } }); backend.addEventListener("arMixAudioArmAck", ack=>{ - if(pendingDeviceMute){ - // Reject any stale/unrelated ACK and any device epoch change. - if(ack?.requestId!==pendingDeviceMute.requestId)return; - const epochMatches=String(ack?.deviceEpoch)===pendingDeviceMute.epoch; - pendingDeviceMute=null; - if(ack?.ok===true && ack?.armed===false && epochMatches) - sendDeviceApply(); - else if(devicePanel){ - deviceResult="Device change rejected: MUTE or audio epoch not verified."; - renderDevicePanel(); - } - return; - } if(ack?.ok===true){ status(ack.armed?"NATIVE: user ARM accepted; checking real PCM.": "NATIVE: output muted."); From 4c55c801bd2b52036c2255080118602292ffa46f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 8 Nov 2026 06:29:09 +0700 Subject: [PATCH 7/7] Keep existing native scope exports together --- scripts/build_approved_native_gui.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index d66baf099..2510ce3e0 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -218,7 +218,7 @@ def accepted_pages_html() -> str: " }\n" " return true;\n" " },\n" - " make,render,revealTrack,findTrack,displayMeterDbfs,\n" + " make,render,findTrack,displayMeterDbfs,revealTrack,\n" " openChannelIdentity,closeChannelIdentity,\n" " get identityTrackId(){return identityTrackId;},\n" " get identityColor(){return identityColor;},get identityIcon(){return identityIcon;},\n"