diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index e93910d68..9b161d488 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -21,7 +21,8 @@ ROOT = Path(__file__).resolve().parents[1] CANONICAL = ROOT / "site" / "preview-v2" NATIVE_ADAPTER = ROOT / "web" / "approved-native-bridge.js" -ADAPTER_MARKER = ('\n' +ADAPTER_MARKER = ('\n' + '\n' '') SCHEMA = "arsonmix.approved-native-pages-bundle.v2" @@ -57,6 +58,11 @@ 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 = ( + # The approved Pages HTML stays byte-for-byte unchanged; these two + # reversible native-only hooks expose verified mixer hardware choices. + ("const option=(values,selected)=>values.map(x=>'').join('');\n", "const option=(values,selected)=>values.map(x=>{const value=Array.isArray(x)?x[0]:x,label=Array.isArray(x)?x[1]:x;return '';}).join('');\n"), + ("const channelOptions=(t,type)=>{\n", + "const channelOptions=(t,type)=>{\n if(window.__JUCE__?.backend){\n const native=window.__ARMIX_NATIVE_M2__?.channelOptions?.(t,type);\n if(native)return native;\n return type==='input'?[['None','Choose audio device…']]:type==='output'?[[t.output||'Master','MAIN']]:['None'];\n }\n"), ("function wireGraphCommit(ops,{record=true}={}){\n", "function wireGraphCommit(ops,{record=true}={}){\n" " if(window.__JUCE__?.backend){window.__ARMIX_NATIVE_M2__?.consumeWire?.(ops);return false;}\n"), @@ -186,6 +192,8 @@ def stage(out: Path) -> dict: out.mkdir(parents=True) shutil.copytree(pages / "assets", out / "assets") shutil.copy2(NATIVE_ADAPTER, out / "assets" / "approved-native-bridge.js") + shutil.copy2(ROOT / "web" / "approved-native-io.css", + out / "assets" / "approved-native-io.css") shutil.copy2(ROOT / "web" / "approved-native-contract.js", out / "assets" / "approved-native-contract.js") native = native_html(approved.decode("utf-8")).encode("utf-8") diff --git a/src/Main.cpp b/src/Main.cpp index f410bce6b..6fde37f5f 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -783,17 +783,31 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(engine_.dryRoutingLabActive() && channel>=1 && channel<=LiveDryRoutingLab::count && (name=="faderDb"||name=="pan"||name=="mute"||name=="solo")) { + // Audition-style live mixer control: all ten strip faders/pans/ + // mute/solo target their REAL native PCM owner, never the Pages + // demo model or hardcoded legacy CH1. No UI-thread graph rebuild. const auto ep=args.getProperty("routeEpoch",juce::var()); const auto rev=args.getProperty("routeRevision",juce::var()); + bool accepted=false; if(!ep.isVoid()&&!rev.isVoid() && ((name=="mute"||name=="solo")?value.isBool(): (value.isDouble()||value.isInt()))) { const auto epoch=static_cast(static_cast(ep)); const auto revision=static_cast(static_cast(rev)); const float liveValue=value.isBool()?(bool(value)?1.f:0.f):valueNumber; - (void)engine_.setDryRoutingLabParameter(channel-1,epoch,revision, + accepted=engine_.setDryRoutingLabParameter(channel-1,epoch,revision, name,liveValue); } + auto ack=std::make_unique(); + ack->setProperty("channel",channel); + ack->setProperty("parameter",name); + ack->setProperty("ok",accepted); + ack->setProperty("routeEpoch", + static_cast(engine_.dryRoutingLabEpoch())); + ack->setProperty("routeRevision", + static_cast(engine_.dryRoutingLabRevision())); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible("arMixM4ControlAck",juce::var(ack.release())); return; } if (name == "masterGain" && (value.isDouble() || value.isInt())) diff --git a/src/NativeVerifiedSourcePatch.h b/src/NativeVerifiedSourcePatch.h index ca9927d87..677be1000 100644 --- a/src/NativeVerifiedSourcePatch.h +++ b/src/NativeVerifiedSourcePatch.h @@ -23,9 +23,11 @@ struct NativeVerifiedSourcePatch final { actualRevision>static_cast(std::numeric_limits::max()) || !accepted.isObject() || channel<0 || channel>=10) return "SOURCE: stale device epoch or invalid native channel"; - if(mode!="MONO"&&mode!="STEREO") - return "SOURCE: MONO or STEREO mode required"; - if(physicalLeft<0 || enabledPhysicalPorts.empty()) + if(mode!="NONE"&&mode!="MONO"&&mode!="STEREO") + return "SOURCE: NONE, MONO or STEREO mode required"; + if(mode=="NONE" && (physicalLeft!=-1||physicalRight!=-1)) + return "SOURCE: clear input requires no physical capture pins"; + if(mode!="NONE"&&(physicalLeft<0||enabledPhysicalPorts.empty())) return "SOURCE: select an enabled physical capture pin"; if(static_cast(accepted.getProperty("deviceEpoch",juce::var(-1))) != static_cast(actualEpoch)) @@ -35,8 +37,8 @@ struct NativeVerifiedSourcePatch final { if(port==physicalLeft)validLeft=true; if(port==physicalRight)validRight=true; } - if(!validLeft || (mode=="STEREO" && - (!validRight || physicalLeft==physicalRight))) + if(mode!="NONE"&&(!validLeft || (mode=="STEREO" && + (!validRight || physicalLeft==physicalRight)))) return "SOURCE: STEREO requires two distinct active physical pins; MONO accepts one"; // JUCE var assignment shares the underlying DynamicObject. Deep // clone before touching a row, or failed prepare would silently @@ -62,11 +64,11 @@ struct NativeVerifiedSourcePatch final { const auto width=row->getProperty("channelFormat").toString(); if(width!="MONO" && width!="STEREO") return "SOURCE: native processing format missing or invalid"; - row->setProperty("sourceKind","PHYSICAL"); + row->setProperty("sourceKind",mode=="NONE"?"NONE":"PHYSICAL"); row->setProperty("sourceFormat",mode); } row->setProperty("mode",mode); - row->setProperty("left",physicalLeft); + row->setProperty("left",mode=="NONE"?-1:physicalLeft); row->setProperty("right",mode=="STEREO"?physicalRight:-1); // The existing M4 producer handles revision/epoch publication and // fails back to its prior accepted graph on any bad plugin/routing. diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 2b584dd09..f84e50e36 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -416,6 +416,85 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a assert.equal(scope.edges.length,0,"accepted snapshot replaces reference wire"); }); +test("verified Windows CH10 selects sparse hardware IN3 then native ACK starts MAIN; M4 fader targets CH10",()=>{ + const vm=require("node:vm"),events=[],listeners=new Map(); + const tracks=Array.from({length:10},(_,i)=>({ + id:30+i,name:"CH"+(i+1),kind:"audio",input:"None",output:"Master", + level:-12,pan:0,mute:false,solo:false + })); + const scope={tracks,master:{id:90,name:"MAIN",level:0,mute:false}, + render(){},stopDemo(){},findTrack(el){return el.track;}, + displayMeterDbfs(){}}; + const backend={ + emitEvent(name,payload){events.push({name,payload});}, + addEventListener(name,cb){listeners.set(name,cb);} + }; + const preview={disabled:false}; + const document={ + readyState:"complete",documentElement:{dataset:{}}, + getElementById:id=>id==="info"?{textContent:""}:id==="preview"?preview:null, + querySelector(){return null;},addEventListener(){} + }; + const window={__JUCE__:{backend},ArSonApprovedNativeContract:protocol, + __ARMIX_NATIVE_SCOPE__:scope,setTimeout(){return 0;}}; + vm.runInNewContext(read("web/approved-native-bridge.js"), + {window,document,performance:{now:()=>0},console},{timeout:1500}); + const g0=clone(fixtures.g0); + g0.device.enabledInputs=[0,2]; + g0.device.inputEndpoints=[ + {id:"in:0",port:0,callback:0,label:"Mic 1",active:true}, + {id:"in:2",port:2,callback:1,label:"Mic 3",active:true} + ]; + g0.legacyM4={active:true,routeAccepted:false,routingRevision:"12"}; + listeners.get("arMixConsoleSnapshot")(g0); + listeners.get("arMixStatus")({ + connected:true,directRouteAuthorized:true,adaptiveClockActive:false, + monitor:false,dryRoutingLab:{active:true,ready:true,topologyFault:false, + hasAcceptedRoute:false,epoch:69,revision:12} + }); + const choices=window.__ARMIX_NATIVE_M2__.channelOptions(tracks[9],"input"); + assert.ok(choices.some(x=>x[0]==="MONO:2"),"sparse physical input is real"); + assert.ok(!choices.some(x=>/CABLE Output L\/R \(Stereo\)/.test(x[0])), + "fake Pages CABLE list must not be selectable as hardware"); + const picker={dataset:{field:"input"},value:"MONO:2",track:tracks[9]}; + assert.equal(window.__ARMIX_NATIVE_M2__.consumeField({target:picker,type:"change"}),true); + const req=events.findLast(x=>x.payload?.action==="routingSourceSwitch"); + assert.ok(req); + assert.equal(req.payload.channel,9,"CH10 routes its OWN hardware input"); + assert.equal(req.payload.left,2); + assert.equal(req.payload.mode,"MONO"); + assert.equal(req.payload.deviceEpoch,69); + assert.equal(req.payload.revision,12); + const rows=Array.from({length:10},(_,i)=>i===9? + {mode:"MONO",left:2,right:-1,main:true}: + {mode:"NONE",left:-1,right:-1,main:true}); + listeners.get("arMixSourceSwitchAck")({ + ok:true,requestId:req.payload.requestId,channel:9, + state:{active:true,ready:true,topologyFault:false, + hasAcceptedRoute:true,epoch:69,revision:13, + acceptedRoute:{channels:rows}} + }); + const monitor=events.findLast(x=>x.payload?.action==="monitor"); + assert.ok(monitor); + assert.equal(monitor.payload.value,true); + assert.equal(monitor.payload.expectedRevision,13); + assert.equal(tracks[9].input,"MONO:2"); + listeners.get("arMixAudioArmAck")({ok:true,armed:true,deviceEpoch:69}); + const armed=clone(g0); + armed.legacyM4={active:true,routeAccepted:true,routingRevision:"13"}; + armed.device.outputArmed=true; + listeners.get("arMixConsoleSnapshot")(armed); + const fader={dataset:{field:"level"},value:"-18",track:tracks[9]}; + window.__ARMIX_NATIVE_M2__.consumeField({target:fader,type:"change"}); + const param=events.findLast(x=>x.name==="arMixParameter"); + assert.ok(param,"M4 CH10 fader reaches real native parameter transport"); + assert.equal(param.payload.channel,10); + assert.equal(param.payload.parameter,"faderDb"); + assert.equal(param.payload.routeEpoch,69); + assert.equal(param.payload.routeRevision,13); + assert.equal(param.payload.value,-18); +}); + test("M3 Windows bundle owns pointerup fader gesture and fences native FX keyboard reorder",()=>{ const builder=read("scripts/build_approved_native_gui.py"); const bridge=read("web/approved-native-bridge.js"); @@ -428,29 +507,51 @@ test("M3 Windows bundle owns pointerup fader gesture and fences native FX keyboa assert.ok(!bridge.includes('window.addEventListener("pointerup"')); }); -test("native Windows operator can explicitly patch first physical input, arm and mute",()=>{ +test("Windows mixer uses Audition-style native IN on any channel, no hidden CH1 arm wizard",()=>{ const js=read("web/approved-native-bridge.js"); const main=read("src/Main.cpp"); const engine=read("src/LiveAudioEngine.h"); - assert.match(js,/REAL AUDIO · FIRST SOUND/); - assert.match(js,/action:"audioSetup"/); - assert.match(js,/d\.inputEndpoints\.filter\(p=>/); - assert.match(js,/d\.enabledInputs\.includes\(p\.port\)/); - assert.match(js,/action:"routingSourceSwitch",requestId:pendingSourceId/); - assert.match(js,/channel:0,mode:"MONO",left:pin,right:-1/); - assert.match(js,/action:"monitor",value:true/); + const page=read("site/preview-v2/index.html"); + const builder=read("scripts/build_approved_native_gui.py"); + assert.match(js,/channelOptions:nativeChannelOptions/); + assert.match(js,/const chooseNativePhysicalInput=\(track,value\)=>/); + assert.match(js,/const channel=inputAt\(track\)/); + assert.match(js,/action:"routingSourceSwitch",requestId:p.id,channel:p.channel/); + assert.match(js,/inputAt\(track\)/); + assert.match(js,/nativeSourcePending\.phase="mute"/); assert.match(js,/action:"monitor",value:false/); - assert.match(js,/expectedEpoch:epoch,expectedRevision:revision/); + assert.match(js,/action:"monitor",value:true/); assert.match(js,/arMixSourceSwitchAck/); assert.match(js,/arMixAudioArmAck/); - assert.match(js,/if\(ack\.ok===true\)/); - assert.match(js,/NATIVE PATCH REJECTED:/); - assert.match(js,/NO VERIFIED AUDIO DEVICE/); - assert.match(js,/NATIVE PCM · HARDWARE FAT PENDING/); - assert.match(js,/MAIN ARMED · PCM NOT YET ADMITTED/); + assert.match(js,/deviceEpoch:p.epoch,revision:p.revision/); + assert.match(js,/arMixAudioDeviceApplyAck/); + assert.match(js,/arMixAudioDeviceInventory/); + assert.match(js,/Audio I\/O Settings/); + assert.match(js,/Driver Recovery…/); + assert.doesNotMatch(js,/Patch CH1|Arm output/); + assert.doesNotMatch(page,/__ARMIX_NATIVE_M2__/,"public approved Pages must remain byte-identical"); + assert.match(builder,/const channelOptions=\(t,type\)=>/); + assert.match(builder,/Array\.isArray\(x\)\?x\[0\]:x/); + assert.match(builder,/approved-native-io\.css/); assert.match(main,/action=="routingSourceSwitch"/); assert.match(main,/engine_\.liveOutputArmFault\(\)/); - assert.match(main,/safe->emitApprovedNativeSnapshot\(\)/); assert.match(engine,/juce::String switchDryRoutingLabSource\(/); assert.match(engine,/setOutputMuted\(true\)/); }); +test("G0 M4 real mixer fader/pan/mute/solo work before universal ChannelId admission",()=>{ + const js=read("web/approved-native-bridge.js"); + const main=read("src/Main.cpp"); + const dry=read("src/LiveDryRoutingLab.h"); + assert.match(js,/verifiedM4\(\)/); + assert.match(js,/m4Parameter\(t,"faderDb",numeric\)/); + assert.match(js,/m4Parameter\(t,"pan",pan\)/); + assert.match(js,/m4Parameter\(t,action,!t\[action\]\)/); + assert.match(js,/channel:channel\+1,value,routeEpoch:epoch,routeRevision:revision/); + assert.match(js,/renderMeasuredM4\(live\)/); + assert.match(js,/channelPeaksL/); + assert.match(js,/channelPeaksR/); + assert.match(main,/accepted=engine_\.setDryRoutingLabParameter\(channel-1/); + assert.match(main,/arMixM4ControlAck/); + assert.match(dry,/publisher_\.updateActiveControl\(expectedEpoch,expectedRevision/); +}); + diff --git a/tests/native_dry_route_command_test.cpp b/tests/native_dry_route_command_test.cpp index 4b8d3239f..b8700c410 100644 --- a/tests/native_dry_route_command_test.cpp +++ b/tests/native_dry_route_command_test.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/core/NativeDryRouteCommand.h" #include "../engine/core/PreparedMixerBlock.h" +#include "../src/NativeVerifiedSourcePatch.h" #if defined(NDEBUG) #undef NDEBUG #endif @@ -139,6 +140,35 @@ int main(){ assert(near(l[0],0.5f*0.70710678118f)); assert(near(r[0],0.5f*0.70710678118f)); + // Audition-style IN=None on ANY previously routed native channel is a + // complete typed source patch, not an invalid physical input/guessed pin. + // The accepted reference stays unchanged until the graph is republished. + auto sourceTemplate=juce::JSON::parse(juce::JSON::toString(typed,false)); + sourceTemplate.getDynamicObject()->setProperty("deviceEpoch",juce::int64(91)); + sourceTemplate.getDynamicObject()->setProperty("revision",juce::int64(7)); + sourceTemplate.getDynamicObject()->setProperty("sends", + juce::var(juce::Array{})); + juce::var noSource,invalidClear; + assert(NativeVerifiedSourcePatch::prepare(sourceTemplate,0,"NONE",-1,-1, + ports,91,7,noSource).isEmpty()); + const auto cleared=noSource.getProperty("channels",{}).getArray()->getReference(0); + assert(cleared.getProperty("mode",{}).toString()=="NONE"); + assert(cleared.getProperty("sourceKind",{}).toString()=="NONE"); + assert(cleared.getProperty("sourceFormat",{}).toString()=="NONE"); + assert(static_cast(cleared.getProperty("left",0))==-1); + assert(static_cast(cleared.getProperty("right",0))==-1); + assert(sourceTemplate.getProperty("channels",{}).getArray() + ->getReference(0).getProperty("mode",{}).toString()=="MONO"); + assert(NativeVerifiedSourcePatch::prepare(sourceTemplate,0,"NONE",2,-1, + ports,91,7,invalidClear).isNotEmpty()); + assert(invalidClear.isVoid()); + assert(NativeVerifiedSourcePatch::prepare(sourceTemplate,0,"NONE",-1,-1, + ports,92,7,invalidClear).isNotEmpty()); // wrong driver epoch + NativeDryRouteCommand clearedPlan; + assert(NativeDryRouteCommand::decode(noSource,clearedPlan,error)); + assert(clearedPlan.channels.stripsAndMaster.strips[0].source==SourceMode::disconnected); + assert(clearedPlan.channels.formats[0]==ChannelFormat::stereo); + // Fail-closed: one type mismatch, old decoded plan unchanged. const auto before=v2; auto* ch0=typed.getProperty("channels",juce::var()) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 7e548a6e3..fa31b966b 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -145,137 +145,498 @@ } } - // Native-only operator controls in the EXISTING approved More menu: - // user selects REAL JUCE active pin -> explicitly patches CH1 -> arms output. - // No auto-arm, demo PCM, guessed physical port or second GUI. - let hardware=null, inputSelect=null, routeBtn=null, armBtn=null, muteBtn=null; - let hardwareNote=null, pendingSourceId=0, sourceSerial=100; - const safeNativeCounter=x=>{ - if(typeof x!=="string" || !/^[1-9]\d*$/.test(x))return null; - const number=Number(x); - return Number.isSafeInteger(number)&&number>0?number:null; - }; + // Exactly one device configuration flow: reuse the existing custom + // Audio I/O panel, not a second large JUCE AudioDeviceSelectorComponent. + // It remains available as an Advanced driver-recovery tool in native host. + let hardware=null, hardwareNote=null, lastDryReadback=null; const legacy=()=>hardware?.raw?.legacyM4; const deviceReady=()=>!!(hardware?.device?.backend && hardware.device.sampleRate>0 && hardware.device.enabledInputs.length>0 && hardware.device.enabledOutputs.length>=2 && legacy()?.active===true); + const verifiedM4=()=>{ + const d=lastDryReadback; + return deviceReady() && legacy()?.routeAccepted===true && + d?.ready===true && d?.hasAcceptedRoute===true && !d?.topologyFault && + String(d.epoch)===hardware.device.epoch && + String(d.revision)===legacy().routingRevision; + }; function updateHardwarePanel(next) { - hardware=next || null; + hardware=next||null; const d=next?.device; const deviceOpen=Boolean(d?.backend && d.sampleRate>0 && d.enabledOutputs.length>=2); const label=document.getElementById("transport"); - if(label)label.textContent=!deviceOpen?"Device not ready": - d.outputArmed?"Output armed":"Output muted"; + if(label)label.textContent=!deviceOpen?"Choose audio device": + d.outputArmed?"MAIN monitoring on":"MAIN monitoring off"; + const warning=document.querySelector?.(".status-bar .warning"); - if(warning)warning.textContent=!deviceOpen?"NO VERIFIED AUDIO DEVICE": + if(warning)warning.textContent=!deviceOpen?"CHOOSE AUDIO OUTPUT": d.outputArmed?(next.admitted?"NATIVE PCM · HARDWARE FAT PENDING": - "MAIN ARMED · PCM NOT YET ADMITTED"): - legacy()?.routeAccepted?"INPUT PATCHED · OUTPUT MUTED": - "NO AUDIBLE OUTPUT · PATCH INPUT + ARM"; - if(!inputSelect)return; - const pins=deviceOpen?d.inputEndpoints.filter(p=> - p.active===true && d.enabledInputs.includes(p.port)):[]; - const key=pins.map(p=>p.id+"|"+p.label).join(";"); - if(inputSelect.dataset.pins!==key) { - const before=inputSelect.value; - inputSelect.dataset.pins=key; - inputSelect.replaceChildren(); - const option=document.createElement("option"); - option.value="";option.textContent="Physical input for CH1"; - inputSelect.appendChild(option); - for(const pin of pins){ - const item=document.createElement("option"); - item.value=String(pin.port); - item.textContent=pin.label+" · IN "+(pin.port+1); - inputSelect.appendChild(item); - } - if(pins.some(p=>String(p.port)===before))inputSelect.value=before; - } - inputSelect.disabled=!deviceReady(); - if(routeBtn)routeBtn.disabled=!deviceReady() || - inputSelect.value==="" || pendingSourceId!==0; - if(armBtn)armBtn.disabled=!deviceReady() || - legacy()?.routeAccepted!==true || d.outputArmed; - if(muteBtn)muteBtn.disabled=!deviceOpen || !d.outputArmed; + "MAIN MONITOR ON · VERIFY SOUND"): + "CHOOSE CHANNEL IN · THEN MONITOR"; if(hardwareNote) { - const evidence=protocol.diagnoseFirstSound?.(next,inputSelect.value); - // Human-readable PCM stages from the ORIGINAL native callback only. - // These values are NOT evidence that the DAC or speaker is audible. - hardwareNote.textContent=evidence? - evidence.readout+" · "+evidence.nextAction: - "No verified hardware PCM readback available."; + const observed=protocol.diagnoseFirstSound?.(next,null); + hardwareNote.textContent=!deviceOpen? + "Audio I/O: choose the hardware input and actual listening/output device.": + (observed?observed.readout+" · ":"")+ + "Choose IN on any mixer channel. Routing and monitoring use native readback."; } } function installFirstSoundMenu() { const menu=document.querySelector?.("#moreTools .more-tools-panel"); if(!menu || typeof document.createElement!=="function")return; - const item=(tag,cls,label)=>{ - const el=document.createElement(tag); - el.className=cls;el.textContent=label; - if(tag==="button")el.type="button"; - return el; - }; - const caption=item("span","more-tools-caption","REAL AUDIO · FIRST SOUND"); - const setup=item("button","tool","Audio Setup"); + const caption=document.createElement("span"); + caption.className="more-tools-caption"; + caption.textContent="AUDIO · DEVICE SETTINGS"; + const setup=document.createElement("button"); + setup.className="tool";setup.type="button";setup.textContent="Audio I/O Settings"; + setup.dataset.nativeAction="audioSetup"; setup.addEventListener("click",()=>{ - backend.emitEvent("arMixAction",{action:"audioSetup"}); - status("NATIVE: select actual ASIO/WASAPI input + output in Audio Setup."); + // Event may be intercepted by the existing mixer-io.js capture handler. + // When handled there, do not emit the old JUCE setup command. + if(window.__arMixOpenAudioIO){ + window.__arMixOpenAudioIO("device"); + status("Choose actual capture and playback devices in Audio I/O."); + }else status("Audio I/O panel unavailable; do not open a second setup wizard."); }); - inputSelect=item("select","toolbar-select",""); - inputSelect.setAttribute("aria-label","JUCE physical input for CH1"); - inputSelect.addEventListener("change",()=>updateHardwarePanel(hardware)); - routeBtn=item("button","tool","Patch CH1"); - routeBtn.addEventListener("click",()=>{ - const d=hardware?.device,l=legacy(); - const epoch=safeNativeCounter(d?.epoch); - const revision=safeNativeCounter(l?.routingRevision); - const pin=Number(inputSelect?.value); - if(!deviceReady()||inputSelect.value==="" || - epoch===null||revision===null|| - !Number.isInteger(pin)||!d.enabledInputs.includes(pin)){ - status("NATIVE: invalid input pin, epoch or route revision.");return; - } - pendingSourceId=++sourceSerial; - routeBtn.disabled=true; - backend.emitEvent("arMixAction",{ - action:"routingSourceSwitch",requestId:pendingSourceId, - channel:0,mode:"MONO",left:pin,right:-1, - deviceEpoch:epoch,revision - }); - status("NATIVE: CH1 physical input patch pending real ACK."); + hardwareNote=document.createElement("span"); + hardwareNote.className="more-tools-caption"; + hardwareNote.style.whiteSpace="normal"; + menu.append(caption,setup,hardwareNote); + updateHardwarePanel(hardware); + } + // Compact Audio I/O is native-only. The EXISTING JUCE AudioDeviceManager + // remains the single owner, via its already-tested inventory/Apply APIs. + // No AudioDeviceSelectorComponent popup or additional device callback in the + // normal workflow; the stock JUCE selector remains Advanced recovery. + let ioRoot=null,ioDraft=null,ioInventory=null,ioBusy=false, + ioMutePending=false,ioRequest="",ioCounter=0,ioMessage=""; + const ioElement=(tag,cls,label)=>{ + const n=document.createElement(tag); + if(cls)n.className=cls;if(label!==undefined)n.textContent=label; + if(tag==="button")n.type="button"; + return n; + }; + const ioType=()=>ioInventory?.types?.find(t=>t.name===ioDraft?.backend); + const ioField=(parent,id,label)=>{ + const row=ioElement("div","ar-native-io-field"); + const text=ioElement("label","",label);text.htmlFor=id; + const select=ioElement("select");select.id=id;row.append(text,select); + parent.appendChild(row);return select; + }; + const ioPopulate=(select,items,current)=>{ + const key=JSON.stringify(items); + if(select.dataset.options!==key){ + select.dataset.options=key; + select.replaceChildren(...items.map(([value,label])=>new Option(label,value))); + } + if(items.some(x=>x[0]===current))select.value=current; + else select.value=items[0]?.[0]??""; + }; + const actualIo=()=>ioInventory?.active||{}; + const setIoDraftFromActual=()=>{ + const a=actualIo(),types=ioInventory?.types||[]; + const name=a.backend||types.find(t=>/ASIO/i.test(t.name))?.name|| + types[0]?.name||""; + const selected=types.find(t=>t.name===name); + const capture=a.open&&a.backend===name?a.captureDevice: + selected?.inputs?.[0]||selected?.outputs?.[0]||""; + const playback=a.open&&a.backend===name?a.playbackDevice: + selected?.outputs?.[0]||""; + ioDraft={backend:name,captureDevice:capture,playbackDevice:playback, + sampleRate:a.open&&a.backend===name?Number(a.rate)||0:0, + bufferSize:a.open&&a.backend===name?Number(a.buffer)||0:0}; + }; + const ioSameDevice=()=>{ + const a=actualIo(),d=ioDraft; + return !!(a?.open&&d&&a.backend===d.backend&& + a.captureDevice===d.captureDevice&&a.playbackDevice===d.playbackDevice); + }; + const ioVirtualOutput=name=>/virtual|vb-audio|cable input|loopback|obs/i.test(name||""); + // A single VB-Cable's capture endpoint fed to its own playback endpoint + // is a self-loop, not a speaker monitor. Do not auto-arm this configuration. + const ioFeedbackLoop=(capture,playback)=> + /^cable output\b/i.test(capture||"") && + /^cable input\b/i.test(playback||"") && + /vb-audio virtual cable/i.test(capture||"") && + /vb-audio virtual cable/i.test(playback||""); + function renderNativeIo(){ + if(!ioRoot)return; + const a=actualIo(),d=ioDraft||{},types=ioInventory?.types||[],type=ioType(); + const backendSelect=ioRoot.querySelector("#arNativeBackend"); + const capture=ioRoot.querySelector("#arNativeCapture"); + const playback=ioRoot.querySelector("#arNativePlayback"); + const rate=ioRoot.querySelector("#arNativeRate"); + const buffer=ioRoot.querySelector("#arNativeBuffer"); + ioPopulate(backendSelect,types.map(t=>[t.name,t.name]),d.backend); + const inputs=type?.inputs||[],outputs=type?.outputs||[]; + ioPopulate(capture,inputs.map(x=>[x,x]),d.captureDevice); + ioPopulate(playback,outputs.map(x=>[x,x]),d.playbackDevice); + capture.disabled=!!ioBusy||!type?.separate; + if(!type?.separate && outputs.length){ + ioDraft.captureDevice=ioDraft.playbackDevice; + ioPopulate(capture,[[ioDraft.captureDevice,ioDraft.captureDevice]],ioDraft.captureDevice); + } + const same=ioSameDevice(); + ioPopulate(rate,[["0","Auto / driver default"], + ...(same?(a.rates||[]).map(x=>[String(x),Number(x).toLocaleString()+" Hz"]):[])], + String(same?d.sampleRate:0)); + ioPopulate(buffer,[["0","Auto / driver default"], + ...(same?(a.buffers||[]).map(x=>[String(x),x+" samples"]):[])], + String(same?d.bufferSize:0)); + for(const select of [backendSelect,playback,rate,buffer]) + select.disabled=!!ioBusy||!select.options.length; + const status=ioRoot.querySelector("#arNativeIoActual"); + status.textContent=a.open? + "ACTIVE · "+a.backend+" · "+a.captureDevice+" → "+a.playbackDevice+ + " · "+Math.round(Number(a.rate)||0)+" Hz / "+(a.buffer||0)+" samples"+ + (a.outputMuted?" · MAIN muted":" · MAIN monitoring"): + "NO VERIFIED AUDIO DEVICE · choose driver, input and output"; + const virtual=ioRoot.querySelector("#arNativeIoVirtual"); + virtual.textContent=ioFeedbackLoop(d.captureDevice,d.playbackDevice)? + "LOOPBACK RISK: VB-Cable CABLE Output capture → CABLE Input playback returns to the SAME virtual cable. Select a different monitoring output before listening.": + ioVirtualOutput(d.playbackDevice)? + "Virtual playback endpoint: this may feed another app, not your headphones. Choose a physical speaker/headphone output to listen directly.":""; + const note=ioRoot.querySelector("#arNativeIoNote"); + note.textContent=ioMessage||"Apply hardware once. Then select IN on any mixer channel."; + ioRoot.querySelector("#arNativeIoApply").disabled=ioBusy|| + !d.backend||!d.captureDevice||!d.playbackDevice||!a|| + !ioInventory?.types?.length; + ioRoot.querySelector("#arNativeIoApply").textContent=ioBusy?"Verifying…":"Apply Device"; + } + function installNativeIoPanel(){ + if(ioRoot)return; + ioRoot=ioElement("div","ar-native-io");ioRoot.id="arNativeAudioIo"; + ioRoot.hidden=true;ioRoot.setAttribute("role","dialog"); + ioRoot.setAttribute("aria-label","Audio hardware setup"); + ioRoot.setAttribute("aria-modal","true"); + const panel=ioElement("section","ar-native-io-panel"); + const head=ioElement("header","ar-native-io-header"); + head.append(ioElement("strong","","Audio I/O · Driver & Monitoring")); + const close=ioElement("button","ar-native-io-close","×"); + close.setAttribute("aria-label","Close audio settings"); + close.addEventListener("click",()=>{ioRoot.hidden=true;}); + head.append(close);panel.append(head); + const body=ioElement("div","ar-native-io-body"); + const readback=ioElement("div","ar-native-io-readback");readback.id="arNativeIoActual"; + body.append(readback); + const backendSelect=ioField(body,"arNativeBackend","Audio driver"); + const capture=ioField(body,"arNativeCapture","Capture / input"); + const playback=ioField(body,"arNativePlayback","Playback / output"); + backendSelect.addEventListener("change",()=>{ + const type=(ioInventory?.types||[]).find(t=>t.name===backendSelect.value); + ioDraft={backend:backendSelect.value, + captureDevice:type?.separate?(type.inputs?.[0]||""):(type?.outputs?.[0]||""), + playbackDevice:type?.outputs?.[0]||"",sampleRate:0,bufferSize:0}; + ioMessage="Device selection is a draft until Apply Device succeeds."; + renderNativeIo(); }); - armBtn=item("button","tool","Arm output"); - armBtn.addEventListener("click",()=>{ - if(!deviceReady()||legacy()?.routeAccepted!==true)return; - const epoch=safeNativeCounter(hardware.device.epoch); - const revision=safeNativeCounter(legacy().routingRevision); - if(epoch===null||revision===null)return; - backend.emitEvent("arMixAction",{action:"monitor",value:true, - expectedEpoch:epoch,expectedRevision:revision}); - status("NATIVE: output ARM requested; awaiting JUCE ACK."); + capture.addEventListener("change",()=>{ioDraft.captureDevice=capture.value;renderNativeIo();}); + playback.addEventListener("change",()=>{ + ioDraft.playbackDevice=playback.value; + if(!ioType()?.separate)ioDraft.captureDevice=playback.value; + renderNativeIo(); + }); + const warning=ioElement("div","ar-native-io-notice");warning.id="arNativeIoVirtual"; + body.append(warning); + const advanced=ioElement("details",""); + const summary=ioElement("summary","","Advanced · sample rate & buffer"); + advanced.append(summary); + const fields=ioElement("div","ar-native-io-body"); + const rate=ioField(fields,"arNativeRate","Sample rate"); + const buffer=ioField(fields,"arNativeBuffer","Buffer"); + rate.addEventListener("change",()=>{ioDraft.sampleRate=Number(rate.value);}); + buffer.addEventListener("change",()=>{ioDraft.bufferSize=Number(buffer.value);}); + advanced.append(fields);body.append(advanced); + const actions=ioElement("div","ar-native-io-controls"); + const apply=ioElement("button","primary","Apply Device");apply.id="arNativeIoApply"; + apply.addEventListener("click",applyNativeAudioIO); + const recover=ioElement("button","","Driver Recovery…"); + recover.title="Advanced JUCE selector — only for driver troubleshooting"; + recover.addEventListener("click",()=>{ + ioRoot.hidden=true; + backend.emitEvent("arMixAction",{action:"audioSetup"}); }); - muteBtn=item("button","tool","Mute output"); - muteBtn.addEventListener("click",()=>{ + actions.append(apply,recover);body.append(actions); + const note=ioElement("div","ar-native-io-busy");note.id="arNativeIoNote"; + body.append(note);panel.append(body);ioRoot.append(panel); + ioRoot.addEventListener("click",e=>{if(e.target===ioRoot)ioRoot.hidden=true;}); + document.body.appendChild(ioRoot); + } + function openNativeAudioIO(){ + installNativeIoPanel(); + ioRoot.hidden=false; + ioMessage="Reading verified driver inventory…"; + renderNativeIo(); + backend.emitEvent("arMixAction",{action:"audioDeviceInventory"}); + } + function applyNativeAudioIO(){ + if(ioBusy||!ioDraft||!ioInventory)return; + const d=ioDraft; + if(!d.backend||!d.captureDevice||!d.playbackDevice){ + ioMessage="Choose a valid input and playback device.";renderNativeIo();return; + } + ioBusy=true; + ioMessage="Applying driver selection · verify hardware ACK before using audio."; + if(hardware?.device?.outputArmed){ + ioMutePending=true; backend.emitEvent("arMixAction",{action:"monitor",value:false}); - status("NATIVE: output MUTE requested; awaiting JUCE ACK."); + }else submitDeviceApply(); + renderNativeIo(); + } + function submitDeviceApply(){ + const d=ioDraft,a=actualIo(),same=ioSameDevice(); + ioRequest="io-"+(++ioCounter); + backend.emitEvent("arMixAction",{action:"audioDeviceApply", + requestId:ioRequest,expectedDeviceGeneration:Number(a.deviceGeneration)||0, + config:{backend:d.backend,captureDevice:d.captureDevice, + playbackDevice:d.playbackDevice, + sampleRate:same?Number(d.sampleRate)||0:0, + bufferSize:same?Number(d.bufferSize)||0:0, + enabledInputs:same?a.enabledInputs:null, + enabledOutputs:same?a.enabledOutputs:null}}); + } + // Same operator contract as Adobe/FL: every processing strip selects + // its own VERIFIED hardware input; output initially targets MAIN. No + // forced CH1, no draft graph, no separate Start or Arm button. + const inputAt=track=>{ + const index=scope?.tracks?.indexOf(track)??-1; + return index>=0&&index<10?index:-1; + }; + const routeRow=index=>(lastDryReadback?.acceptedRoute?.channels|| + lastDryReadback?.preparedM4Route?.channels||[])[index]; + const routeValue=r=>r?.mode==="MONO"?"MONO:"+r.left: + r?.mode==="STEREO"?"STEREO:"+r.left+":"+r.right:"None"; + const hardwareInputs=()=>{ + const d=hardware?.device; + if(!deviceReady()||!Array.isArray(d?.inputEndpoints))return []; + const enabled=new Set(d.enabledInputs); + return d.inputEndpoints.filter(p=>p?.active===true && + Number.isInteger(p.port)&&enabled.has(p.port) && p.port>=0&&p.port<64); + }; + let nativeSourcePending=null,nativeSourceSerial=1500000; + const signalSourceResult=message=>{status(message);}; + const stopSource=error=>{ + const p=nativeSourcePending; + nativeSourcePending=null; + const alreadyPatched=!!p?.accepted; + signalSourceResult((alreadyPatched?"INPUT CONNECTED · MONITOR OFF · ":"INPUT NEEDS VERIFICATION · ")+ + error+". Inspect Audio I/O and native readback before trying again."); + controller?.subscribe(); // lost ACK or hotplug: never trust optimistic UI + }; + const submitSource=()=>{ + const p=nativeSourcePending,d=lastDryReadback||{}; + if(!p||!deviceReady()||!d.ready||d.topologyFault|| + String(d.epoch)!==String(p.epoch)||Number(d.revision)!==p.revision){ + stopSource("device or route became stale");return; + } + p.phase="source"; + backend.emitEvent("arMixAction",{ + action:"routingSourceSwitch",requestId:p.id,channel:p.channel, + mode:p.mode,left:p.left,right:p.right, + deviceEpoch:p.epoch,revision:p.revision }); - hardwareNote=item("span","more-tools-caption","Device not initialized"); - hardwareNote.style.whiteSpace="normal"; - menu.append(caption,setup,inputSelect,routeBtn,armBtn,muteBtn,hardwareNote); - updateHardwarePanel(hardware); + signalSourceResult("CH "+(p.channel+1)+" · connecting verified hardware source…"); + }; + const monitorAfterSource=()=>{ + const p=nativeSourcePending,d=p?.accepted; + if(!p||!d?.ready||!d.hasAcceptedRoute||d.topologyFault|| + String(d.epoch)!==String(p.epoch)){ + stopSource("output cannot be monitored until route is verified");return; + } + if(ioFeedbackLoop(hardware?.device?.captureDevice,hardware?.device?.playbackDevice)){ + const channel=p.channel; + nativeSourcePending=null; + signalSourceResult("CH "+(channel+1)+" routed; MAIN monitoring stays OFF: input and output loop back through the same VB-Cable. Choose a physical output in Audio I/O."); + return; + } + if(!p.wasMonitoring){ + const channel=p.channel; + nativeSourcePending=null; + signalSourceResult("CH "+(channel+1)+" → MAIN · input connected, output remains MUTED. Use the existing MAIN MUTE button to monitor."); + return; + } + p.phase="monitor";p.revision=Number(d.revision); + backend.emitEvent("arMixAction",{action:"monitor",value:true, + expectedEpoch:p.epoch,expectedRevision:p.revision}); + signalSourceResult("CH "+(p.channel+1)+" · enabling MAIN monitoring…"); + }; + const chooseNativePhysicalInput=(track,value)=>{ + const channel=inputAt(track),d=lastDryReadback||{}; + if(channel<0)return false; + if(value==="__IO__"){openNativeAudioIO();return true;} + if(nativeSourcePending) {signalSourceResult("Previous input is still being verified.");return true;} + if(!deviceReady()||!d.ready||d.topologyFault||!d.active|| + String(d.epoch)!==hardware.device.epoch){ + signalSourceResult("Choose Audio I/O and a valid input/output device first."); + return true; + } + const mode=value==="None"?"NONE":value.startsWith("MONO:")?"MONO": + value.startsWith("STEREO:")?"STEREO":"INVALID"; + if(mode==="INVALID"){signalSourceResult("Input unavailable on this hardware.");return true;} + const pins=hardwareInputs(),set=new Set(pins.map(p=>p.port)); + const parts=value.split(":"),left=mode==="NONE"?-1:Number(parts[1]), + right=mode==="STEREO"?Number(parts[2]):-1; + if(mode==="MONO"&&(!set.has(left)||parts.length!==2) || + mode==="STEREO"&&(!set.has(left)||!set.has(right)||left===right||parts.length!==3)){ + signalSourceResult("This input is not enabled by the selected audio driver.");return true; + } + const before=routeRow(channel); + const unchanged=routeValue(before)===value; + if(unchanged)return true; // never change monitoring consent on no-op + const epoch=Number(d.epoch),revision=Number(d.revision); + if(!Number.isSafeInteger(epoch)||epoch<=0||!Number.isSafeInteger(revision)||revision<1){ + signalSourceResult("Native route revision is not ready.");return true; + } + nativeSourcePending={id:++nativeSourceSerial,channel,mode,left,right, + epoch,revision,phase:"source",wasMonitoring:hardware.device.outputArmed===true}; + const ticket=nativeSourcePending.id; + // One bounded operator-request timeout, never a realtime callback timer. + // Driver/ACK can be lost: force a new authoritative snapshot and unblock IN. + window.setTimeout(()=>{ + if(nativeSourcePending?.id===ticket) + stopSource("native source/monitor ACK did not arrive"); + },8000); + // Native M4 applies SAME-FORMAT source changes in 64-sample crossfade. + // Structural changes while monitored mute on the existing control thread + // before preparing the immutable graph, then resume only after real ACK. + if(hardware.device.outputArmed && !unchanged&&before?.mode!==mode){ + nativeSourcePending.phase="mute"; + backend.emitEvent("arMixAction",{action:"monitor",value:false, + expectedEpoch:epoch,expectedRevision:revision}); + }else if(unchanged){ + nativeSourcePending.accepted=d; + monitorAfterSource(); + }else submitSource(); + return true; + }; + function nativeChannelOptions(track,type){ + if(type==="input"){ + if(inputAt(track)<0)return [["None","No input"]]; + const pins=hardwareInputs(),list=[["None","No input"]]; + for(const pin of pins) + list.push(["MONO:"+pin.port,"Mono · IN "+(pin.port+1)+" · "+(pin.label||"Input")]); + for(let i=0;i+1