diff --git a/AR-MIX-Live-FX-Host-Standalone-v0.3.html b/AR-MIX-Live-FX-Host-Standalone-v0.3.html index afbc1c25b..addead97d 100644 --- a/AR-MIX-Live-FX-Host-Standalone-v0.3.html +++ b/AR-MIX-Live-FX-Host-Standalone-v0.3.html @@ -2169,6 +2169,19 @@ .arSourceChoice:hover:not(:disabled),.arSourceAdvanced:hover{border-color:#8dbcc5} .arSourceChoice:disabled{opacity:.45;cursor:default} .arSourceChooserNote{font-size:10px;line-height:1.5;color:#bbcad1;margin-top:8px} + +/* M1 logical sources: small, scrollable, driver-verified naming controls. */ +.arSourceSearch{box-sizing:border-box;width:100%;background:#0e2630;color:#e1f0f3;border:1px solid #466877;border-radius:3px;padding:7px 8px;font:11px 'Segoe UI',Arial,sans-serif;margin-bottom:7px} +.arSourceAliasRow{display:flex;align-items:stretch;gap:4px} +.arSourceAliasRow .arSourceChoice{flex:1;min-width:0} +.arSourceAliasRemove{flex:0 0 25px;border:1px solid #476473;border-radius:3px;background:#21313b;color:#adc4cc;cursor:pointer} +.arSourceAliasManager{border-top:1px solid #385463;margin-top:7px;padding-top:6px;color:#bdcfd5;font-size:10px} +.arSourceAliasManager summary{cursor:pointer;font:600 10px 'Segoe UI',Arial,sans-serif;letter-spacing:.04em} +.arSourceAliasFields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:5px;margin:7px 0} +.arSourceAliasFields input,.arSourceAliasFields select{box-sizing:border-box;min-width:0;width:100%;background:#0f2631;color:#e2ebef;border:1px solid #496876;border-radius:3px;padding:6px 5px;font:10px 'Segoe UI',Arial,sans-serif} +.arSourceAliasFields [data-source-alias-name]{grid-column:span 2} +.arSourceAliasFields [data-source-alias-save]{grid-column:span 2} +.arSourceAliasFields small{font:10px 'Segoe UI',Arial,sans-serif}
@@ -3281,6 +3294,57 @@ if(current!=='NONE'&&!options.some(v=>v[0]===current))options.push([current,'CUSTOM L/R · PATCH']); return options; }; + + // M1 named logical inputs: PRESENTATION aliases for verified native hardware + // pins. Every choice still commits through the single native route authority. + // Profile is bound to backend + capture device + the entire active pin/name + // signature; never remap silently when the driver or enabled pins change. + const aliasStorePrefix='armix:named-source:v1:'; + let aliasCacheKey='',aliasCache=[]; + const sourceIdentity=s=>{ + const d=deviceInventory?.active,pins=portList(s),enabled=d?.enabledInputs; + if(!isNative()||!s.ready||!d?.open||!d.backend||!d.captureDevice|| + !Array.isArray(enabled)||!pins.length||pins.length!==enabled.length)return ''; + const p=pins.map(x=>x.port).sort((a,b)=>a-b); + const e=enabled.map(Number).sort((a,b)=>a-b); + if(!p.every((v,i)=>v===e[i]))return ''; + const names=Array.isArray(d.inputNames)?d.inputNames:[]; + if(!pins.every(x=>names[x.port]===x.label))return ''; + // Device names are NOT guaranteed stable operating-system IDs; on any + // changed label/pin list, the prior aliases are deliberately unavailable. + return aliasStorePrefix+encodeURIComponent(JSON.stringify([ + d.backend,d.captureDevice,pins.map(x=>[x.port,x.label]).sort((a,b)=>a[0]-b[0])])); + }; + const validAlias=(a,pins)=>{ + const used=new Set(pins.map(x=>x.port)); + return !!a&&typeof a.name==='string'&&a.name.length>0&&a.name.length<=32&& + (a.mode==='MONO'||a.mode==='STEREO')&& + Number.isInteger(a.left)&&used.has(a.left)&& + (a.mode==='MONO'?(a.right===-1): + Number.isInteger(a.right)&&a.left!==a.right&&used.has(a.right)); + }; + const sourceAliases=s=>{ + const key=sourceIdentity(s); + if(key!==aliasCacheKey){ + aliasCacheKey=key;aliasCache=[]; + if(key)try { + const value=JSON.parse(localStorage.getItem(key)||'[]'); + if(Array.isArray(value))aliasCache=value.slice(0,32).filter(x=>validAlias(x,portList(s))); + }catch{} // blocked storage does not interrupt native routing + } + return key?aliasCache:[]; + }; + const saveSourceAliases=(s,items)=>{ + const key=sourceIdentity(s); + if(!key)return false; + try { + localStorage.setItem(key,JSON.stringify(items)); + aliasCacheKey=key;aliasCache=items; + return true; + }catch{return false;} + }; + const aliasValue=a=>a.mode+':'+a.left+(a.mode==='STEREO'?':'+a.right:''); + const namedRoute=(s,r)=>sourceAliases(s).find(a=>aliasValue(a)===valueFor(r)); const outputLabel=s=>{ const out=s.mainOutputs?.length===2?s.mainOutputs:s.outputPorts||[]; return s.ready&&Number.isInteger(out[0])&&Number.isInteger(out[1])? @@ -3324,6 +3388,7 @@ source=(names(r.left)||'L'+(Number(r.left)+1))+' / '+ (names(r.right)||'R'+(Number(r.right)+1)); if(ack&&r.mode==='BUS')source='INTERNAL BUS'; + if(ack&&r.mode!=='NONE'&&r.mode!=='BUS')source=namedRoute(s,r)?.name||source; if(!ack)source='NO NATIVE ACK'; const routed=ack?lastStatus.dryRoutingLab?.fxInstances?.[i]:null; const inserts=Array.isArray(routed)?routed.length:0; @@ -3353,11 +3418,16 @@ sourceChooser.hidden=true; sourceChooser.setAttribute('role','dialog'); sourceChooser.setAttribute('aria-label','Choose verified channel input source'); - sourceChooser.innerHTML='
INPUT SOURCE
'; + sourceChooser.innerHTML='
INPUT SOURCE
MANAGE NAMED INPUTS
Requires a verified device inventory; routes still require native ACK.
'; host.insertBefore(sourceChooser,mixer); let sourceChooserChannel=-1; const sourceChoices=sourceChooser.querySelector('[data-source-choices]'); const sourceNote=sourceChooser.querySelector('[data-source-note]'); + const aliasNameInput=sourceChooser.querySelector('[data-source-alias-name]'); + const aliasLeft=sourceChooser.querySelector('[data-source-alias-left]'); + const aliasRight=sourceChooser.querySelector('[data-source-alias-right]'); + const aliasMode=sourceChooser.querySelector('[data-source-alias-mode]'); + const aliasSearch=sourceChooser.querySelector('[data-source-search]'); const closeSourceChooser=()=>{ sourceChooser.hidden=true;sourceChooserChannel=-1; }; @@ -3370,29 +3440,85 @@ const pins=portList(s); const values=portsFor(s,r||{mode:'NONE',left:-1,right:-1}); const current=valueFor(r); + const aliases=sourceAliases(s),search=aliasSearch.value.trim().toLowerCase(); + const matched=title=>!search||title.toLowerCase().includes(search); + if(aliases.length){ + for(let i=0;i[String(p.port),portName(p)]); + populate(aliasLeft,pinOptions,previousLeft||String(pins[0]?.port??'')); + populate(aliasRight,pinOptions,previousRight||String(pins[1]?.port??pins[0]?.port??'')); + aliasRight.disabled=aliasMode.value!=='STEREO'; + const identified=!!sourceIdentity(s); + sourceChooser.querySelector('[data-source-alias-save]').disabled=!identified; + sourceChooser.querySelector('[data-source-alias-help]').textContent=identified? + 'Saved for this verified device and enabled-pin layout · native ACK required': + 'Awaiting actual driver inventory; naming disabled until hardware is verified'; sourceNote.textContent=!s.ready?'No verified native driver input ports': - s.monitor?'MUTE OUTPUT to safely change SOURCE · no automatic unmute': - 'Selecting SOURCE commits via existing native routing; wait for ACK'; + s.monitor?'Same-format physical input changes use native 64-sample crossfade · new patch or format requires MUTE': + 'Choose verified source; native ACK required before it is LIVE'; }; const openSourceChooser=channel=>{ if(!Number.isInteger(channel)||channel<0||channel>=10)return; sourceChooserChannel=channel;sourceChooser.hidden=false; + if(!sourceIdentity(route()))deviceRefresh(); // cached JUCE readback, not a vendor rescan renderSourceChooser(); }; + sourceChooser.addEventListener('input',event=>{ + if(event.target===aliasSearch)renderSourceChooser(); + }); + aliasMode.addEventListener('change',()=>{aliasRight.disabled=aliasMode.value!=='STEREO';}); sourceChooser.addEventListener('click',event=>{ + const remove=event.target.closest('[data-source-alias-remove]'); + if(remove){ + const s=route(),items=sourceAliases(s).slice(),index=Number(remove.dataset.sourceAliasRemove); + if(Number.isInteger(index)&&index>=0&&indexi!==index))){ + sourceNote.textContent='SOURCE NAME REMOVED · live hardware route unchanged'; + renderSourceChooser();refreshFocus(s); + }return; + } + if(event.target.closest('[data-source-alias-save]')){ + const s=route(),a={name:aliasNameInput.value.trim(),mode:aliasMode.value, + left:Number(aliasLeft.value),right:aliasMode.value==='MONO'?-1:Number(aliasRight.value)}; + if(!validAlias(a,portList(s))){sourceNote.textContent='INVALID NAME OR HARDWARE L/R PAIR';return;} + const items=sourceAliases(s).filter(x=>x.name.toLowerCase()!==a.name.toLowerCase()); + if(items.length>=32){sourceNote.textContent='32 NAMED SOURCES MAXIMUM';return;} + if(saveSourceAliases(s,[...items,a])){ + aliasNameInput.value='';aliasSearch.value='';renderSourceChooser();refreshFocus(s); + sourceNote.textContent='NAMED SOURCE SAVED · choose it to request native routing'; + }else sourceNote.textContent='DEVICE/LOCAL STORAGE UNAVAILABLE · not saved'; + return; + } if(event.target.closest('[data-source-close]')){closeSourceChooser();return;} if(event.target.closest('[data-source-advanced]')){ const ch=sourceChooserChannel;closeSourceChooser();openIO('inputs',ch);return; @@ -3402,7 +3528,7 @@ const [mode,a,b]=button.dataset.sourceChoice.split(':'); if(!['NONE','MONO','STEREO'].includes(mode))return; const channel=sourceChooserChannel; - const outcome=window.__arMixCommitMutedSource?.( + const outcome=window.__arMixCommitSelectedSource?.( channel,mode,mode==='NONE'?-1:Number(a),mode==='STEREO'?Number(b):-1); sourceNote.textContent=outcome?.ok? outcome.pending?'SOURCE PENDING · WAIT NATIVE ACK': @@ -3410,8 +3536,12 @@ outcome?.error||'Native source route rejected'; if(!outcome?.ok)return; if(outcome.pending)quickSourcePending={ - channel,epoch:outcome.epoch,value:button.dataset.sourceChoice}; + channel,epoch:outcome.epoch,value:button.dataset.sourceChoice,live:!!outcome.live}; renderSourceChooser(); + sourceNote.textContent=outcome.pending? + outcome.live?'LIVE SOURCE PENDING · 64-SAMPLE RAMP · WAIT NATIVE ACK': + 'MUTED SOURCE APPLY PENDING · WAIT NATIVE ACK': + 'SOURCE ALREADY ACKNOWLEDGED'; }); // MS5: explicit Sends-on-Faders control, scoped to a single real AUX return. // MAIN fader DOM and all audio controls remain resident and unmodified. @@ -3501,9 +3631,8 @@ refresh();drawSendEditor(); } - // MS5 Sends-on-Faders: no second audio model. One native POST send per channel - // is edited only on release/keyboard; drag movement paints CSS without - // rebuilding the mixer, invoking plugins, or dispatching audio parameters. + // M1: one native POST send, one in-flight ACK per edge, coalesced continuous + // drag input (not a per-pointer DOM rerender, FX action or structural APPLY). function leaveSof(){ if(sofDrag){document.removeEventListener('pointermove',sofMove); sofDrag.slider.classList.remove('is-dragging');sofDrag=null;} @@ -3621,7 +3750,9 @@ sofDrag=null; document.removeEventListener('pointermove',sofMove); d.slider.classList.remove('is-dragging'); - if(!cancel&&Math.abs(d.db-d.startDb)>0.005)sofStage(d.ch,'gain',+sofGain(d.db).toFixed(7)); + if(cancel&&d.sent)sofStage(d.ch,'gain',+sofGain(d.startDb).toFixed(7)); + else if(!cancel&&Math.abs(d.db-d.startDb)>0.005) + sofStage(d.ch,'gain',+sofGain(d.db).toFixed(7)); else refresh(); } function sofMove(event){ @@ -3629,6 +3760,15 @@ if(!d||d.pointerId!==event.pointerId)return; d.db=Math.max(-60,Math.min(0,d.startDb+(d.startY-event.clientY)*60/d.travel)); if(d.slider.isConnected)sofPaintLayer(d.slider.closest('.arSofLayer'),sofGain(d.db)); + // Native ACK backpressure keeps at most one pending IPC command. While + // dragging, only the latest target is retained; the audio DSP de-zippers. + const now=performance.now(); + if(Math.abs(d.db-d.lastSentDb)>=.25 && now-d.lastSentAt>=25){ + const response=window.__arMixSetLiveAuxSendGain?.({ + from:d.ch,bus:sofBus,gain:+sofGain(d.db).toFixed(7)}); + if(response?.ok){d.sent=true;d.lastSentDb=d.db;d.lastSentAt=now;} + else if(response?.error)sofStatus(response.error); + } } document.addEventListener('pointerdown',event=>{ const slider=event.target.closest?.('[data-sof-fader]'); @@ -3637,7 +3777,8 @@ if(!item||s.pending||s.epoch!==sofEpoch)return; const rect=slider.getBoundingClientRect(); sofDrag={ch,slider,pointerId:event.pointerId,startY:event.clientY, - travel:Math.max(24,rect.height-18),startDb:sofDb(item.gain),db:sofDb(item.gain)}; + travel:Math.max(24,rect.height-18),startDb:sofDb(item.gain),db:sofDb(item.gain), + lastSentDb:sofDb(item.gain),lastSentAt:0,sent:false}; slider.classList.add('is-dragging'); slider.setPointerCapture?.(event.pointerId); document.addEventListener('pointermove',sofMove,{passive:true}); @@ -4319,10 +4460,10 @@ const value=select.value,parts=value.split(':'); const mode=parts[0],left=mode==='NONE'?-1:Number(parts[1]),right=mode==='STEREO'?Number(parts[2]):-1; const direct=select.classList.contains('arBankSource'); - const response=direct?window.__arMixCommitMutedSource?.(channel,mode,left,right): + const response=direct?window.__arMixCommitSelectedSource?.(channel,mode,left,right): window.__arMixStageChannelInput?.(channel,mode,left,right); if(response?.pending)quickSourcePending={channel,epoch:response.epoch, - value:valueFor({mode,left,right})}; + value:valueFor({mode,left,right}),live:!!response.live}; if(!response?.ok){ const message=response?.error||'Native INPUT PATCH unavailable'; el('arIOFeedback').textContent=message; @@ -4372,18 +4513,23 @@ lastSignature='';refresh(); } },true); - // AUX return fader updates only after release/keyboard change; native - // DSP ramps it inside one callback. Never touch the MAIN fader or rack. - sofControls.addEventListener('change',event=>{ - if(event.target.matches('[data-sof-bus]')){sofMessage='';refresh();return;} + // AUX MASTER is a real continuous parameter as well; input and release + // share the same bounded native ACK/coalescing controller. + const sendAuxMaster=event=>{ if(!event.target.matches('[data-aux-master]'))return; const bus=Number(sofControls.querySelector('[data-sof-bus]').value); const db=Number(event.target.value); const gain=db<=-60?0:Math.pow(10,db/20); const answer=window.__arMixSetLiveAuxMasterGain?.(bus,+gain.toFixed(7)); - sofMessage=answer?.ok?'AUX MASTER · WAIT NATIVE ACK': - answer?.error||'AUX master unavailable'; - refresh(); + if(!answer?.ok)sofMessage=answer?.error||'AUX master unavailable'; + const read=sofControls.querySelector('[data-aux-master-read]'); + if(read)read.textContent=db<=-60?'OFF':db.toFixed(1)+' dB'; + }; + sofControls.addEventListener('input',sendAuxMaster); + sofControls.addEventListener('change',event=>{ + if(event.target.matches('[data-sof-bus]')){sofMessage='';refresh();return;} + if(!event.target.matches('[data-aux-master]'))return; + sendAuxMaster(event); }); // Channel focus is intentionally lightweight: point into existing MIX // modes and native controller, never create a parallel mixer/FX model. @@ -4574,6 +4720,7 @@ const hadDraft=deviceDirty(); deviceInventory=d; if(!hadDraft&&!deviceBusy)deviceDraft=makeDeviceDraft(); + if(!sourceChooser.hidden){renderSourceChooser();refreshFocus(route());} if(d?.scanState==='SCANNED') deviceNote='DEVICE LIST REFRESHED · '+Number(d.scanDurationMs||0).toFixed(0)+' ms · output remains MUTED'; else if(d?.scanState==='BLOCKED_ARMED') @@ -4613,6 +4760,19 @@ renderSourceChooser(); } }); + window.addEventListener('arMixSourceSwitchResult',event=>{ + const result=event.detail||{}; + if(quickSourcePending?.live&&quickSourcePending.channel===result.channel) + quickSourcePending=null; + const s=route(); + lastSignature='';refresh(); + if(!sourceChooser.hidden){ + renderSourceChooser(); + sourceNote.textContent=result.ok? + 'SOURCE ACK · 64-SAMPLE INPUT CROSSFADE · FX AND BUS UNCHANGED': + 'SOURCE REJECTED · '+(result.error||'Verified route unchanged'); + } + }); window.addEventListener('arMixRoutingDraftChanged',()=>{lastSignature='';refresh();}); window.addEventListener('arMixAuxMasterGainResult',event=>{ const ack=event.detail||{}; diff --git a/engine/core/LiveChannelFxGraph.h b/engine/core/LiveChannelFxGraph.h index 4083c7051..fff61df01 100644 --- a/engine/core/LiveChannelFxGraph.h +++ b/engine/core/LiveChannelFxGraph.h @@ -165,6 +165,9 @@ class LiveChannelFxGraph final { int monitorOutputLeft() const noexcept{return monitorLeft_;} int monitorOutputRight() const noexcept{return monitorRight_;} const std::array& monitorGains() const noexcept{return monitorGains_;} + bool switchPhysicalSource(int strip,SourceMode mode,int left,int right) noexcept { + return block_&&block_->setPhysicalSource(strip,mode,left,right); + } // M1: native realtime send fader on an EXISTING validated AUX POST edge. // Same prepared graph, no VST instance change or global mute. bool setAuxBusGain(int bus,float gain) noexcept { diff --git a/engine/core/PreparedMixerBlock.h b/engine/core/PreparedMixerBlock.h index 9f685b40d..d6e1e7692 100644 --- a/engine/core/PreparedMixerBlock.h +++ b/engine/core/PreparedMixerBlock.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -174,6 +175,13 @@ class PreparedMixerBlock final { : 0u, 0.f) { if (!validCapacity(maxFrames)) capacity_=0; + for(int i=0;i=stripCount||mode==SourceMode::disconnected|| + plan_.channels.base.strips[strip].mode!=mode)return false; + const int n=plan_.channels.inputPorts.enabledCount; + if(left<0||left>=n||right<0||right>=n|| + (mode==SourceMode::mono&&left!=right)|| + (mode==SourceMode::stereo&&left==right))return false; + physicalTarget_[strip].store(packSourcePair(left,right), + std::memory_order_release); + return true; + } + // Message-thread-only target update; immutable edge topology/pan/FX ownership. // Only an ALREADY EXISTING POST edge may be adjusted while output is live. // This index lookup is on CONTROL, never inside the audio callback. @@ -296,16 +319,45 @@ class PreparedMixerBlock final { const auto& source=graph.channels.base.strips[strip]; // Incoming sends are already in l/r. Add actual hardware only // when that port is valid; never overwrite internal bus returns. - if (source.mode!=SourceMode::disconnected && - physical && source.inputA>=0 && - source.inputA=0 && source.inputB(pair&0xffffu); + const int b=static_cast((pair>>16)&0xffffu); + return pair!=invalidSourcePair&&a(fade.target&0xffffu); + const int b=static_cast((fade.target>>16)&0xffffu); + if(fade.remaining==0){ + if(valid(fade.target))for(int f=0;f(fade.previous&0xffffu); + const int oldB=static_cast((fade.previous>>16)&0xffffu); + const bool oldGood=valid(fade.previous),newGood=valid(fade.target); + for(int f=0;f(--fade.remaining)/64.f; + if(oldGood){l[f]+=physical[oldA][f]*(1.f-t); + r[f]+=physical[oldB][f]*(1.f-t);} + if(newGood){l[f]+=physical[a][f]*t; + r[f]+=physical[b][f]*t;} + if(fade.remaining==0){ + if(newGood)for(int j=f+1;j(left)| + (static_cast(right)<<16); + } + struct PhysicalSourceFade final { + std::uint32_t previous=invalidSourcePair,target=invalidSourcePair; + int remaining=0; // callback-thread-only, never shared with GUI + }; // Audio-thread exclusive smoothing state plus atomically published gain // targets. No lock, heap, plugin recreation or per-block graph compile. // POST/PRE edge identity and normalized PAN are immutable per revision. @@ -487,6 +548,8 @@ class PreparedMixerBlock final { std::array right_{}; std::array auxLeft_{},auxRight_{}; std::array preGate_{},lastGainL_{},lastGainR_{}; + std::array,stripCount> physicalTarget_{}; + std::array physicalBlend_{}; std::array,maxAuxSends> auxTarget_{}; std::array auxApplied_{}; // callback thread exclusive std::array,auxBusCount> auxBusTarget_{}; diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index b7d07a3c9..00332c672 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1028,6 +1028,17 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback setOutputMuted(true); // never expose CH1 unexpectedly on STOP dryRoutingLab_.disable(); } + juce::String switchDryRoutingLabSource(int strip,std::uint64_t epoch, + std::uint64_t revision,const juce::String& mode, + int left,int right) noexcept { + if(independent_.active()||routeReconfiguring_.load(std::memory_order_acquire)|| + handoff_.busy()||!directFence_.permitted()|| + diagnosticRoute_.load(std::memory_order_acquire) + !=armix::diagnostics::Route::normal|| + savedDirectSetup_||savedLiveSetup_) + return "SOURCE SWITCH: live DIRECT device or graph unavailable"; + return dryRoutingLab_.switchPhysicalSource(strip,epoch,revision,mode,left,right); + } bool setDryRoutingLabParameter(int strip,std::uint64_t epoch, std::uint64_t revision,const juce::String& parameter, float value) noexcept { diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index fb0437c13..a363870cd 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -436,6 +436,55 @@ class LiveDryRoutingLab final { } } + // M1 direct-source parameter: only same-format physical→physical + // input on an ALREADY scheduled channel. Route DAG, VST3 lease, FX + // identity and hardware output ownership are immutable. Epoch/revision + // and actual enabled sparse port mask are checked on CONTROL thread. + juce::String switchPhysicalSource(int strip,std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,const juce::String& mode, + int physicalLeft,int physicalRight) noexcept { + if(strip<0||strip>=count||!hasExplicitRoute()|| + expectedEpoch!=epoch()||expectedRevision!=revision()|| + topologyFault_.load(std::memory_order_acquire)) + return "SOURCE SWITCH: stale native device, graph or channel"; + if(mode!="MONO"&&mode!="STEREO") + return "SOURCE SWITCH: existing MONO/STEREO format required"; + auto channels=acceptedRoute_.getProperty("channels",juce::var()); + auto* rows=channels.getArray(); + if(!rows||rows->size()!=count) + return "SOURCE SWITCH: missing accepted input routing"; + auto& row=rows->getReference(strip); + if(row.getProperty("mode",{}).toString()!=mode) + return "SOURCE SWITCH: channel format/topology change requires MUTE + APPLY"; + const int n=portCount_.load(std::memory_order_acquire); + int callbackLeft=-1,callbackRight=-1; + for(int i=0;isetProperty("left",physicalLeft); + object->setProperty("right",mode=="STEREO"?physicalRight:-1); + } + return {}; + } + // Native live control path. Only the JUCE message thread writes. No // graph recompilation, VST3 instantiation or callback detach. // Browser carries the exact acknowledged route token to reject stale diff --git a/src/Main.cpp b/src/Main.cpp index 43c7cecf8..70d18be5f 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1324,6 +1324,35 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // A user-controlled hardware dry routing FAT, not a change to the // existing 1-channel VST3 production chain. Explicit Apply/Stop. + // M1 RT source switch on an existing physical channel. Unlike + // structural routingDryApply, it does not unpatch outputs, rebuild + // VST3s, or restart the device; input PCM fades inside one graph. + if(action=="routingSourceSwitch"){ + const int requestId=static_cast(args.getProperty("requestId",0)); + const int channel=static_cast(args.getProperty("channel",-1)); + const auto mode=args.getProperty("mode",juce::var()).toString(); + const auto ep=args.getProperty("deviceEpoch",juce::var()); + const auto rv=args.getProperty("revision",juce::var()); + const int left=static_cast(args.getProperty("left",-1)); + const int right=static_cast(args.getProperty("right",-1)); + const juce::String error=requestId>0&&!ep.isVoid()&&!rv.isVoid()&& + !nativeShowBusy_&&!studioBackupBusy_? + engine_.switchDryRoutingLabSource(channel, + static_cast(static_cast(ep)), + static_cast(static_cast(rv)), + mode,left,right): + juce::String("SOURCE SWITCH: stale request or Show/backup busy"); + auto ack=std::make_unique(); + ack->setProperty("requestId",requestId); + ack->setProperty("channel",channel); + ack->setProperty("ok",error.isEmpty()); + ack->setProperty("error",error); + ack->setProperty("state",engine_.status().getProperty("dryRoutingLab",{})); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixSourceSwitchAck",juce::var(ack.release())); + if(error.isNotEmpty())emitNotice(error,true); + return; + } if (action == "routingDryApply") { LiveDryRoutingLab::FxSelections selected{}; diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index 9e5baeaf7..898b2dc15 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -228,9 +228,9 @@ test('SETUP1 honest bus patch has real AUX/MAIN/MONITOR navigation, no fake GROU }); -test('SOURCE1 mute-only instant SOURCE uses one native ACK; armed output is rejected',()=>{ +test('SOURCE quick switch is live only for verified same format; structural fallback remains muted',()=>{ const io=read('web/mixer-io.js'),monitor=read('web/monitor.js'); - assert.match(io,/__arMixCommitMutedSource\?\.\(channel,mode,left,right\)/); + assert.match(io,/__arMixCommitSelectedSource\?\.\(channel,mode,left,right\)/); assert.match(io,/quickSourcePending/); assert.match(io,/PENDING · NATIVE ACK/); assert.match(monitor,/window\.__arMixCommitMutedSource=/); @@ -268,10 +268,60 @@ test('SOURCE2 selected-channel popover selects verified physical ports without a const js=read('web/mixer-io.js'); assert.match(js,/function refreshFocus\(s\)/); assert.match(js,/const openSourceChooser=channel=>/); - assert.match(js,/window\.__arMixCommitMutedSource\?\.\(/); + assert.match(js,/window\.__arMixCommitSelectedSource\?\.\(/); assert.match(js,/sourceNote\.textContent/); assert.match(js,/sourceChooser\.addEventListener\('click'/); assert.match(js,/portsFor\(s,r\|\|/); assert.match(js,/NONADJACENT L\/R/); assert.doesNotMatch(js,/new AudioContext\(/); }); + + +test('M1 faders send continuous coalesced ACK-backed params without structural APPLY',()=>{ + const gui=read('web/mixer-io.js'),monitor=read('web/monitor.js'),html=read('AR-MIX-Live-FX-Host-Standalone-v0.3.html'); + assert.match(gui,/sofControls\.addEventListener\('input',sendAuxMaster\)/); + assert.match(gui,/const now=performance\.now\(\)/); + assert.match(gui,/Math\.abs\(d\.db-d\.lastSentDb\)>=\.25/); + assert.match(gui,/window\.__arMixSetLiveAuxSendGain\?\.\(/); + assert.match(monitor,/const liveSendLatest=new Map\(\)/); + assert.match(monitor,/const auxMasterLatest=new Map\(\)/); + assert.match(monitor,/LIVE SEND COALESCED/); + assert.match(monitor,/AUX MASTER COALESCED/); + assert.match(monitor,/if\(matched&&latest!==undefined/); + assert.match(monitor,/if\(ok&&latest!==undefined/); + assert.match(html,/Math\.abs\(d\.db-d\.lastSentDb\)>=\.25/); +}); + + +test('M1 named input sources are persisted only for native device and enabled pin identity',()=>{ + const ui=read('web/mixer-io.js'); + const html=read('AR-MIX-Live-FX-Host-Standalone-v0.3.html'); + for(const src of [ui,html]){ + assert.match(src,/const sourceIdentity=s=>/); + assert.match(src,/d\.backend,d\.captureDevice,pins\.map/); + assert.match(src,/const validAlias=\(a,pins\)=>/); + assert.match(src,/localStorage\.setItem\(key,JSON\.stringify\(items\)\)/); + assert.match(src,/const aliasValue=a=>/); + assert.match(src,/window\.__arMixCommitSelectedSource\?\.\(/); + assert.match(src,/data-source-alias-save/); + assert.match(src,/if\(!sourceIdentity\(route\(\)\)\)deviceRefresh\(\)/); + } +}); + + +test('M1 SOURCE safe unmuted handoff uses native input crossfade with immutable FX graph',()=>{ + const ui=read('web/mixer-io.js'),monitor=read('web/monitor.js'); + const main=read('src/Main.cpp'),engine=read('src/LiveAudioEngine.h'); + const lab=read('src/LiveDryRoutingLab.h'),block=read('engine/core/PreparedMixerBlock.h'); + assert.match(ui,/window\.__arMixCommitSelectedSource\?\.\(/); + assert.match(ui,/arMixSourceSwitchResult/); + assert.match(monitor,/window\.__arMixCommitSelectedSource=/); + assert.match(monitor,/action:"routingSourceSwitch"/); + assert.match(monitor,/arMixSourceSwitchAck/); + assert.match(main,/action=="routingSourceSwitch"/); + assert.match(engine,/switchDryRoutingLabSource\(/); + assert.match(lab,/switchPhysicalSource\(/); + assert.match(block,/physicalTarget_\[strip\]\.store/); + assert.match(block,/fade\.remaining=64/); + assert.doesNotMatch(ui,/new AudioContext\(/); +}); diff --git a/tests/mixer_io_smoke.py b/tests/mixer_io_smoke.py index 1dcef4813..f3232d558 100644 --- a/tests/mixer_io_smoke.py +++ b/tests/mixer_io_smoke.py @@ -98,6 +98,46 @@ async def main(): assert await page.evaluate("""()=>window.__armixTestActions.filter( x=>x.name==='arMixAction'&&x.data.action==='routingDryApply').length""")==1 assert (await page.evaluate("()=>window.__arMixRouteView().draftRoutes[1].mode"))=='NONE' + # M1: an ALREADY PATCHED MONO channel may change physical input + # while output is ARMED: one native source PARAM/ACK and no APPLY. + await page.locator('[data-mix-mode="FX"]').click() + # SOURCE follows the selected strip, not the previous editable row. + await page.evaluate("()=>chooseChannel(0)") + assert await page.locator('#mixer [data-strip="0"]').evaluate("(e)=>e.classList.contains('selected')") + await page.locator('[data-focus-step="source"]').click() + assert await page.locator('.arSourceChooser').is_visible() + await page.locator('.arSourceChoice[data-source-choice="MONO:1"]').click() + switching=await page.evaluate("""()=>window.__armixTestActions.filter(x=> + x.name==='arMixAction'&&x.data.action==='routingSourceSwitch')""") + assert len(switching)==1,(switching,await page.locator('[data-source-note]').inner_text()) + assert switching[0]['data']['requestId']==1 and switching[0]['data']['channel']==0 + assert switching[0]['data']['left']==1 and switching[0]['data']['deviceEpoch']==4 + assert (await page.evaluate("""()=>window.__armixTestActions.filter(x=> + x.name==='arMixAction'&&x.data.action==='routingDryApply').length"""))==1 + assert 'Microphone 1' in await page.locator('[data-focus-source]').inner_text() + # Stale request cannot impersonate the first accepted switch. + await page.evaluate("""status=>window.__armixTestEmit('arMixSourceSwitchAck',{ + ok:true,requestId:321,channel:0,state:status.dryRoutingLab})""",status) + assert 'Microphone 1' in await page.locator('[data-focus-source]').inner_text() + status=await page.evaluate("""status=>{ + status.dryRoutingLab.acceptedRoute.channels[0].left=1; + window.__armixTestEmit('arMixSourceSwitchAck',{ + ok:true,requestId:1,channel:0,state:status.dryRoutingLab}); + window.__armixTestEmit('arMixStatus',status);return status; + }""",status) + assert 'Microphone 2' in await page.locator('[data-focus-source]').inner_text() + # Restore original source to keep other mixer regression fixtures stable. + await page.locator('.arSourceChoice[data-source-choice="MONO:0"]').click() + status=await page.evaluate("""status=>{ + status.dryRoutingLab.acceptedRoute.channels[0].left=0; + window.__armixTestEmit('arMixSourceSwitchAck',{ + ok:true,requestId:2,channel:0,state:status.dryRoutingLab}); + window.__armixTestEmit('arMixStatus',status);return status; + }""",status) + assert 'Microphone 1' in await page.locator('[data-focus-source]').inner_text() + assert (await page.evaluate("""()=>window.__armixTestActions.filter(x=> + x.name==='arMixAction'&&x.data.action==='routingDryApply').length"""))==1 + await page.locator('[data-source-close]').click() await page.evaluate("""status=>{ status.monitor=false; window.__armixTestEmit('arMixStatus',status); @@ -303,6 +343,15 @@ async def main(): live_actions=await page.evaluate("""()=>window.__armixTestActions.filter( x=>x.name==='arMixAction'&&x.data.action==='routingAuxSendGain')""") assert len(live_actions)==1,live_actions + # During the first native ACK flight, newer moves must only replace + # one queued value. Returning to the in-flight target drops the queue. + queued=await page.evaluate("""()=>({ + first:window.__arMixSetLiveAuxSendGain({from:0,bus:0,gain:.3}), + second:window.__arMixSetLiveAuxSendGain({from:0,bus:0,gain:1}), + count:window.__armixTestActions.filter(x=> + x.name==='arMixAction'&&x.data.action==='routingAuxSendGain').length + })""") + assert queued['first']['queued'] and queued['second']['queued'] and queued['count']==1,queued gain_command=live_actions[-1]['data'] assert gain_command['from']==0 and gain_command['bus']==0 assert gain_command['deviceEpoch']==4 and gain_command['revision']==5 @@ -642,6 +691,58 @@ async def main(): }""",status) assert 'LIVE' in await page.locator('[data-io-quick-row="2"] .arIOQuickState').inner_text() assert 'LIVE' in await page.locator('[data-io-quick-row="5"] .arIOQuickState').inner_text() + # M1: a user-defined sparse stereo pair is selectable in CHANNEL SOURCE + # only when the real device identity and *all* active pins match. + await page.evaluate("""()=>window.__armixTestEmit('arMixAudioDeviceInventory',{ + currentType:'ASIO', + active:{backend:'ASIO',captureDevice:'MAONO PS22',playbackDevice:'MAONO PS22', + open:true,deviceGeneration:51,enabledInputs:[0,1,4,7], + inputNames:['MAONO Mic In 1','MAONO Mic In 2','Unused 3','Unused 4', + 'MAONO VC In L','Unused 6','Unused 7','MAONO VC In R']}, + types:[{name:'ASIO',active:true,separate:false, + inputs:['MAONO PS22'],outputs:['MAONO PS22']}]})""") + await page.locator('#arIOOverlay [data-io-close]').click() + await page.locator('[data-focus-step="source"]').click() + await page.locator('.arSourceAliasManager summary').click() + await page.locator('[data-source-alias-name]').fill('MAONO Virtual Stereo') + await page.locator('[data-source-alias-mode]').select_option('STEREO') + await page.locator('[data-source-alias-left]').select_option('4') + await page.locator('[data-source-alias-right]').select_option('7') + assert await page.locator('[data-source-alias-save]').is_enabled() + await page.locator('[data-source-alias-save]').click() + named=page.locator('[data-source-choice="STEREO:4:7"]') + assert await named.count()==1 + assert 'MAONO Virtual Stereo' in await named.inner_text() + selected=await page.evaluate("""()=>Number( + document.querySelector('.strip[data-strip].selected')?.dataset.strip||0)""") + await named.click() + native=await page.evaluate("""()=>window.__armixTestActions.filter(x=> + x.name==='arMixAction'&&x.data.action==='routingDryApply')""") + assert len(native)==2,native + target=native[-1]['data']['value']['channels'][selected] + assert target['mode']=='STEREO' and target['left']==4 and target['right']==7,target + status=await page.evaluate("""({status,selected})=>{ + status.dryRoutingLab.revision=5; + status.dryRoutingLab.acceptedRoute.channels[selected]={ + ...status.dryRoutingLab.acceptedRoute.channels[selected], + mode:'STEREO',left:4,right:7}; + window.__armixTestEmit('arMixRoutingLabAck',{ok:true,state:status.dryRoutingLab}); + window.__armixTestEmit('arMixStatus',status); + return status; + }""",{"status":status,"selected":selected}) + assert 'MAONO Virtual Stereo' in await page.locator('[data-focus-source]').inner_text() + # An altered pin mask must NOT inherit the saved alias or silently remap. + await page.evaluate("""()=>window.__armixTestEmit('arMixAudioDeviceInventory',{ + currentType:'ASIO', + active:{backend:'ASIO',captureDevice:'MAONO PS22',playbackDevice:'MAONO PS22', + open:true,deviceGeneration:52,enabledInputs:[0,1,4], + inputNames:['MAONO Mic In 1','MAONO Mic In 2','Unused 3','Unused 4','MAONO VC In L']}, + types:[{name:'ASIO',active:true,separate:false, + inputs:['MAONO PS22'],outputs:['MAONO PS22']}]})""") + # The old pin route may still appear as CUSTOM for inspection; the + # device-bound named alias itself MUST disappear on mask mismatch. + assert await page.locator('.arSourceAliasRow [data-source-choice="STEREO:4:7"]').count()==0 + assert await page.locator('[data-source-alias-save]').is_disabled() await page.screenshot(path="mixer-patch1-maono-ch3-ch6-1366.png") assert not errors,errors await browser.close() diff --git a/tests/prepared_mixer_block_test.cpp b/tests/prepared_mixer_block_test.cpp index f0c77d55f..80a7a31b5 100644 --- a/tests/prepared_mixer_block_test.cpp +++ b/tests/prepared_mixer_block_test.cpp @@ -149,4 +149,42 @@ int main() { assert(allocations.load(std::memory_order_relaxed)==pre); assert(near(outputL[0],.4f*.70710678f)); } + // M1 physical source: real PCM tap changes without graph recompile, + // plugin recreation, output mute or any audio-thread allocation. + { + constexpr std::array hardware {0,1,2}; + ChannelRoutingConfig ch; + ch.stripsAndMaster.strips[0]={SourceMode::mono,0,-1,1.f,0.f,false,false}; + SendRequest direct; + direct.toMaster[0]=true; + PreparedRenderGraph compiled;RenderError reason; + assert(PreparedRenderGraph::compile(ch,hardware,direct,compiled,reason)); + PreparedMixerBlock live(compiled,128); + std::array microphone{},alternate{},silent{}; + microphone.fill(.2f);alternate.fill(.8f); + const float* inputs[]={microphone.data(),alternate.data(),silent.data()}; + std::array left{},right{}; + auto fx=[](int,float*,float*,int) noexcept {}; + assert(!live.setPhysicalSource(0,SourceMode::stereo,1,2)); + assert(!live.setPhysicalSource(0,SourceMode::mono,1,2)); + assert(!live.setPhysicalSource(0,SourceMode::mono,20,20)); + assert(!live.setPhysicalSource(3,SourceMode::mono,1,1)); + assert(live.process(inputs,3,left.data(),right.data(),128,fx)); + const float old=left[127],newValue=.8f*.70710678118f; + assert(near(old,.2f*.70710678118f)); + assert(live.setPhysicalSource(0,SourceMode::mono,1,1)); + const auto allocationsBefore=allocations.load(std::memory_order_relaxed); + assert(live.process(inputs,3,left.data(),right.data(),128,fx)); + assert(allocations.load(std::memory_order_relaxed)==allocationsBefore); + assert(left[0]>old&&left[0]old&&left[0]v[0]===current))options.push([current,'CUSTOM L/R · PATCH']); return options; }; + + // M1 named logical inputs: PRESENTATION aliases for verified native hardware + // pins. Every choice still commits through the single native route authority. + // Profile is bound to backend + capture device + the entire active pin/name + // signature; never remap silently when the driver or enabled pins change. + const aliasStorePrefix='armix:named-source:v1:'; + let aliasCacheKey='',aliasCache=[]; + const sourceIdentity=s=>{ + const d=deviceInventory?.active,pins=portList(s),enabled=d?.enabledInputs; + if(!isNative()||!s.ready||!d?.open||!d.backend||!d.captureDevice|| + !Array.isArray(enabled)||!pins.length||pins.length!==enabled.length)return ''; + const p=pins.map(x=>x.port).sort((a,b)=>a-b); + const e=enabled.map(Number).sort((a,b)=>a-b); + if(!p.every((v,i)=>v===e[i]))return ''; + const names=Array.isArray(d.inputNames)?d.inputNames:[]; + if(!pins.every(x=>names[x.port]===x.label))return ''; + // Device names are NOT guaranteed stable operating-system IDs; on any + // changed label/pin list, the prior aliases are deliberately unavailable. + return aliasStorePrefix+encodeURIComponent(JSON.stringify([ + d.backend,d.captureDevice,pins.map(x=>[x.port,x.label]).sort((a,b)=>a[0]-b[0])])); + }; + const validAlias=(a,pins)=>{ + const used=new Set(pins.map(x=>x.port)); + return !!a&&typeof a.name==='string'&&a.name.length>0&&a.name.length<=32&& + (a.mode==='MONO'||a.mode==='STEREO')&& + Number.isInteger(a.left)&&used.has(a.left)&& + (a.mode==='MONO'?(a.right===-1): + Number.isInteger(a.right)&&a.left!==a.right&&used.has(a.right)); + }; + const sourceAliases=s=>{ + const key=sourceIdentity(s); + if(key!==aliasCacheKey){ + aliasCacheKey=key;aliasCache=[]; + if(key)try { + const value=JSON.parse(localStorage.getItem(key)||'[]'); + if(Array.isArray(value))aliasCache=value.slice(0,32).filter(x=>validAlias(x,portList(s))); + }catch{} // blocked storage does not interrupt native routing + } + return key?aliasCache:[]; + }; + const saveSourceAliases=(s,items)=>{ + const key=sourceIdentity(s); + if(!key)return false; + try { + localStorage.setItem(key,JSON.stringify(items)); + aliasCacheKey=key;aliasCache=items; + return true; + }catch{return false;} + }; + const aliasValue=a=>a.mode+':'+a.left+(a.mode==='STEREO'?':'+a.right:''); + const namedRoute=(s,r)=>sourceAliases(s).find(a=>aliasValue(a)===valueFor(r)); const outputLabel=s=>{ const out=s.mainOutputs?.length===2?s.mainOutputs:s.outputPorts||[]; return s.ready&&Number.isInteger(out[0])&&Number.isInteger(out[1])? @@ -71,6 +122,7 @@ source=(names(r.left)||'L'+(Number(r.left)+1))+' / '+ (names(r.right)||'R'+(Number(r.right)+1)); if(ack&&r.mode==='BUS')source='INTERNAL BUS'; + if(ack&&r.mode!=='NONE'&&r.mode!=='BUS')source=namedRoute(s,r)?.name||source; if(!ack)source='NO NATIVE ACK'; const routed=ack?lastStatus.dryRoutingLab?.fxInstances?.[i]:null; const inserts=Array.isArray(routed)?routed.length:0; @@ -100,11 +152,16 @@ sourceChooser.hidden=true; sourceChooser.setAttribute('role','dialog'); sourceChooser.setAttribute('aria-label','Choose verified channel input source'); - sourceChooser.innerHTML='
INPUT SOURCE
'; + sourceChooser.innerHTML='
INPUT SOURCE
MANAGE NAMED INPUTS
Requires a verified device inventory; routes still require native ACK.
'; host.insertBefore(sourceChooser,mixer); let sourceChooserChannel=-1; const sourceChoices=sourceChooser.querySelector('[data-source-choices]'); const sourceNote=sourceChooser.querySelector('[data-source-note]'); + const aliasNameInput=sourceChooser.querySelector('[data-source-alias-name]'); + const aliasLeft=sourceChooser.querySelector('[data-source-alias-left]'); + const aliasRight=sourceChooser.querySelector('[data-source-alias-right]'); + const aliasMode=sourceChooser.querySelector('[data-source-alias-mode]'); + const aliasSearch=sourceChooser.querySelector('[data-source-search]'); const closeSourceChooser=()=>{ sourceChooser.hidden=true;sourceChooserChannel=-1; }; @@ -117,29 +174,85 @@ const pins=portList(s); const values=portsFor(s,r||{mode:'NONE',left:-1,right:-1}); const current=valueFor(r); + const aliases=sourceAliases(s),search=aliasSearch.value.trim().toLowerCase(); + const matched=title=>!search||title.toLowerCase().includes(search); + if(aliases.length){ + for(let i=0;i[String(p.port),portName(p)]); + populate(aliasLeft,pinOptions,previousLeft||String(pins[0]?.port??'')); + populate(aliasRight,pinOptions,previousRight||String(pins[1]?.port??pins[0]?.port??'')); + aliasRight.disabled=aliasMode.value!=='STEREO'; + const identified=!!sourceIdentity(s); + sourceChooser.querySelector('[data-source-alias-save]').disabled=!identified; + sourceChooser.querySelector('[data-source-alias-help]').textContent=identified? + 'Saved for this verified device and enabled-pin layout · native ACK required': + 'Awaiting actual driver inventory; naming disabled until hardware is verified'; sourceNote.textContent=!s.ready?'No verified native driver input ports': - s.monitor?'MUTE OUTPUT to safely change SOURCE · no automatic unmute': - 'Selecting SOURCE commits via existing native routing; wait for ACK'; + s.monitor?'Same-format physical input changes use native 64-sample crossfade · new patch or format requires MUTE': + 'Choose verified source; native ACK required before it is LIVE'; }; const openSourceChooser=channel=>{ if(!Number.isInteger(channel)||channel<0||channel>=10)return; sourceChooserChannel=channel;sourceChooser.hidden=false; + if(!sourceIdentity(route()))deviceRefresh(); // cached JUCE readback, not a vendor rescan renderSourceChooser(); }; + sourceChooser.addEventListener('input',event=>{ + if(event.target===aliasSearch)renderSourceChooser(); + }); + aliasMode.addEventListener('change',()=>{aliasRight.disabled=aliasMode.value!=='STEREO';}); sourceChooser.addEventListener('click',event=>{ + const remove=event.target.closest('[data-source-alias-remove]'); + if(remove){ + const s=route(),items=sourceAliases(s).slice(),index=Number(remove.dataset.sourceAliasRemove); + if(Number.isInteger(index)&&index>=0&&indexi!==index))){ + sourceNote.textContent='SOURCE NAME REMOVED · live hardware route unchanged'; + renderSourceChooser();refreshFocus(s); + }return; + } + if(event.target.closest('[data-source-alias-save]')){ + const s=route(),a={name:aliasNameInput.value.trim(),mode:aliasMode.value, + left:Number(aliasLeft.value),right:aliasMode.value==='MONO'?-1:Number(aliasRight.value)}; + if(!validAlias(a,portList(s))){sourceNote.textContent='INVALID NAME OR HARDWARE L/R PAIR';return;} + const items=sourceAliases(s).filter(x=>x.name.toLowerCase()!==a.name.toLowerCase()); + if(items.length>=32){sourceNote.textContent='32 NAMED SOURCES MAXIMUM';return;} + if(saveSourceAliases(s,[...items,a])){ + aliasNameInput.value='';aliasSearch.value='';renderSourceChooser();refreshFocus(s); + sourceNote.textContent='NAMED SOURCE SAVED · choose it to request native routing'; + }else sourceNote.textContent='DEVICE/LOCAL STORAGE UNAVAILABLE · not saved'; + return; + } if(event.target.closest('[data-source-close]')){closeSourceChooser();return;} if(event.target.closest('[data-source-advanced]')){ const ch=sourceChooserChannel;closeSourceChooser();openIO('inputs',ch);return; @@ -149,7 +262,7 @@ const [mode,a,b]=button.dataset.sourceChoice.split(':'); if(!['NONE','MONO','STEREO'].includes(mode))return; const channel=sourceChooserChannel; - const outcome=window.__arMixCommitMutedSource?.( + const outcome=window.__arMixCommitSelectedSource?.( channel,mode,mode==='NONE'?-1:Number(a),mode==='STEREO'?Number(b):-1); sourceNote.textContent=outcome?.ok? outcome.pending?'SOURCE PENDING · WAIT NATIVE ACK': @@ -157,8 +270,12 @@ outcome?.error||'Native source route rejected'; if(!outcome?.ok)return; if(outcome.pending)quickSourcePending={ - channel,epoch:outcome.epoch,value:button.dataset.sourceChoice}; + channel,epoch:outcome.epoch,value:button.dataset.sourceChoice,live:!!outcome.live}; renderSourceChooser(); + sourceNote.textContent=outcome.pending? + outcome.live?'LIVE SOURCE PENDING · 64-SAMPLE RAMP · WAIT NATIVE ACK': + 'MUTED SOURCE APPLY PENDING · WAIT NATIVE ACK': + 'SOURCE ALREADY ACKNOWLEDGED'; }); // MS5: explicit Sends-on-Faders control, scoped to a single real AUX return. // MAIN fader DOM and all audio controls remain resident and unmodified. @@ -248,9 +365,8 @@ refresh();drawSendEditor(); } - // MS5 Sends-on-Faders: no second audio model. One native POST send per channel - // is edited only on release/keyboard; drag movement paints CSS without - // rebuilding the mixer, invoking plugins, or dispatching audio parameters. + // M1: one native POST send, one in-flight ACK per edge, coalesced continuous + // drag input (not a per-pointer DOM rerender, FX action or structural APPLY). function leaveSof(){ if(sofDrag){document.removeEventListener('pointermove',sofMove); sofDrag.slider.classList.remove('is-dragging');sofDrag=null;} @@ -368,7 +484,9 @@ sofDrag=null; document.removeEventListener('pointermove',sofMove); d.slider.classList.remove('is-dragging'); - if(!cancel&&Math.abs(d.db-d.startDb)>0.005)sofStage(d.ch,'gain',+sofGain(d.db).toFixed(7)); + if(cancel&&d.sent)sofStage(d.ch,'gain',+sofGain(d.startDb).toFixed(7)); + else if(!cancel&&Math.abs(d.db-d.startDb)>0.005) + sofStage(d.ch,'gain',+sofGain(d.db).toFixed(7)); else refresh(); } function sofMove(event){ @@ -376,6 +494,15 @@ if(!d||d.pointerId!==event.pointerId)return; d.db=Math.max(-60,Math.min(0,d.startDb+(d.startY-event.clientY)*60/d.travel)); if(d.slider.isConnected)sofPaintLayer(d.slider.closest('.arSofLayer'),sofGain(d.db)); + // Native ACK backpressure keeps at most one pending IPC command. While + // dragging, only the latest target is retained; the audio DSP de-zippers. + const now=performance.now(); + if(Math.abs(d.db-d.lastSentDb)>=.25 && now-d.lastSentAt>=25){ + const response=window.__arMixSetLiveAuxSendGain?.({ + from:d.ch,bus:sofBus,gain:+sofGain(d.db).toFixed(7)}); + if(response?.ok){d.sent=true;d.lastSentDb=d.db;d.lastSentAt=now;} + else if(response?.error)sofStatus(response.error); + } } document.addEventListener('pointerdown',event=>{ const slider=event.target.closest?.('[data-sof-fader]'); @@ -384,7 +511,8 @@ if(!item||s.pending||s.epoch!==sofEpoch)return; const rect=slider.getBoundingClientRect(); sofDrag={ch,slider,pointerId:event.pointerId,startY:event.clientY, - travel:Math.max(24,rect.height-18),startDb:sofDb(item.gain),db:sofDb(item.gain)}; + travel:Math.max(24,rect.height-18),startDb:sofDb(item.gain),db:sofDb(item.gain), + lastSentDb:sofDb(item.gain),lastSentAt:0,sent:false}; slider.classList.add('is-dragging'); slider.setPointerCapture?.(event.pointerId); document.addEventListener('pointermove',sofMove,{passive:true}); @@ -1066,10 +1194,10 @@ const value=select.value,parts=value.split(':'); const mode=parts[0],left=mode==='NONE'?-1:Number(parts[1]),right=mode==='STEREO'?Number(parts[2]):-1; const direct=select.classList.contains('arBankSource'); - const response=direct?window.__arMixCommitMutedSource?.(channel,mode,left,right): + const response=direct?window.__arMixCommitSelectedSource?.(channel,mode,left,right): window.__arMixStageChannelInput?.(channel,mode,left,right); if(response?.pending)quickSourcePending={channel,epoch:response.epoch, - value:valueFor({mode,left,right})}; + value:valueFor({mode,left,right}),live:!!response.live}; if(!response?.ok){ const message=response?.error||'Native INPUT PATCH unavailable'; el('arIOFeedback').textContent=message; @@ -1119,18 +1247,23 @@ lastSignature='';refresh(); } },true); - // AUX return fader updates only after release/keyboard change; native - // DSP ramps it inside one callback. Never touch the MAIN fader or rack. - sofControls.addEventListener('change',event=>{ - if(event.target.matches('[data-sof-bus]')){sofMessage='';refresh();return;} + // AUX MASTER is a real continuous parameter as well; input and release + // share the same bounded native ACK/coalescing controller. + const sendAuxMaster=event=>{ if(!event.target.matches('[data-aux-master]'))return; const bus=Number(sofControls.querySelector('[data-sof-bus]').value); const db=Number(event.target.value); const gain=db<=-60?0:Math.pow(10,db/20); const answer=window.__arMixSetLiveAuxMasterGain?.(bus,+gain.toFixed(7)); - sofMessage=answer?.ok?'AUX MASTER · WAIT NATIVE ACK': - answer?.error||'AUX master unavailable'; - refresh(); + if(!answer?.ok)sofMessage=answer?.error||'AUX master unavailable'; + const read=sofControls.querySelector('[data-aux-master-read]'); + if(read)read.textContent=db<=-60?'OFF':db.toFixed(1)+' dB'; + }; + sofControls.addEventListener('input',sendAuxMaster); + sofControls.addEventListener('change',event=>{ + if(event.target.matches('[data-sof-bus]')){sofMessage='';refresh();return;} + if(!event.target.matches('[data-aux-master]'))return; + sendAuxMaster(event); }); // Channel focus is intentionally lightweight: point into existing MIX // modes and native controller, never create a parallel mixer/FX model. @@ -1321,6 +1454,7 @@ const hadDraft=deviceDirty(); deviceInventory=d; if(!hadDraft&&!deviceBusy)deviceDraft=makeDeviceDraft(); + if(!sourceChooser.hidden){renderSourceChooser();refreshFocus(route());} if(d?.scanState==='SCANNED') deviceNote='DEVICE LIST REFRESHED · '+Number(d.scanDurationMs||0).toFixed(0)+' ms · output remains MUTED'; else if(d?.scanState==='BLOCKED_ARMED') @@ -1360,6 +1494,19 @@ renderSourceChooser(); } }); + window.addEventListener('arMixSourceSwitchResult',event=>{ + const result=event.detail||{}; + if(quickSourcePending?.live&&quickSourcePending.channel===result.channel) + quickSourcePending=null; + const s=route(); + lastSignature='';refresh(); + if(!sourceChooser.hidden){ + renderSourceChooser(); + sourceNote.textContent=result.ok? + 'SOURCE ACK · 64-SAMPLE INPUT CROSSFADE · FX AND BUS UNCHANGED': + 'SOURCE REJECTED · '+(result.error||'Verified route unchanged'); + } + }); window.addEventListener('arMixRoutingDraftChanged',()=>{lastSignature='';refresh();}); window.addEventListener('arMixAuxMasterGainResult',event=>{ const ack=event.detail||{}; diff --git a/web/monitor.js b/web/monitor.js index 55a12b7ea..a87f39449 100644 --- a/web/monitor.js +++ b/web/monitor.js @@ -1181,6 +1181,10 @@ // Creating/removing sends, editing PRE/PAN or enabling AUX is STRUCTURAL. let liveSendRequestId=1; const liveSendPending=new Map(); + // Bounded last-write-wins coalescing: one native request in flight per edge. + // No route/GUI state is promoted until ACK; no unbounded pointer backlog. + const liveSendLatest=new Map(); + const liveSendInFlightGain=new Map(); window.__arMixSetLiveAuxSendGain=({from,bus,gain}={})=>{ const fault=sendEditGate(from,bus); if(fault)return {ok:false,error:fault}; @@ -1192,8 +1196,6 @@ if(!Array.isArray(d.acceptedRoute?.sends)) return {ok:false,error:"No acknowledged native AUX send graph."}; const key=sendKey(from,bus,"POST"); - if(liveSendPending.has(key)) - return {ok:false,error:"Wait for the previous native send ACK."}; const source=d.acceptedRoute.sends.find(s=>s.from===from&& s.to===10+bus&&s.tap==="POST"); if(!source) @@ -1201,7 +1203,16 @@ if(!draftAux[bus]?.enabled||!draftSends.some(s=>s.from===from&& s.to===10+bus&&s.tap==="POST")) return {ok:false,error:"AUX return or accepted POST send unavailable."}; + if(liveSendPending.has(key)){ + // Replace the target; only the latest gesture is useful to the engine. + if(Math.abs(n-liveSendInFlightGain.get(key))<1e-7)liveSendLatest.delete(key); + else liveSendLatest.set(key,n); + return {ok:true,pending:true,queued:true,message:"LIVE SEND COALESCED · WAIT ACK"}; + } + if(Math.abs(n-Number(source.gain))<1e-7) + return {ok:true,unchanged:true,message:"LIVE SEND ALREADY ACKNOWLEDGED"}; const requestId=liveSendRequestId++; + liveSendInFlightGain.set(key,n); liveSendPending.set(key,requestId); api.emitEvent("arMixAction",{action:"routingAuxSendGain", requestId,from,bus,deviceEpoch:Number(d.epoch),revision:Number(d.revision), @@ -1213,6 +1224,7 @@ const key=sendKey(from,bus,"POST"); if(liveSendPending.get(key)!==Number(ack?.requestId))return; liveSendPending.delete(key); + liveSendInFlightGain.delete(key); const next=ack?.state||{},current=state.dryRoutingLab||{}; const matched=ack?.ok===true && next.epoch===current.epoch && next.revision===current.revision&&next.acceptedRoute; @@ -1226,11 +1238,18 @@ detail:{ok:!!matched,from,bus,gain:Number(ack?.gain), error:matched?"":String(ack?.error||"Native route changed; gain NOT applied")} })); + const latest=liveSendLatest.get(key); + liveSendLatest.delete(key); + // The ACK has updated the one authoritative accepted route; no speculative LIVE. + if(matched&&latest!==undefined&&Math.abs(latest-Number(ack.gain))>=1e-7) + window.__arMixSetLiveAuxSendGain({from,bus,gain:latest}); }); // M1 AUX MASTER: one existing enabled FX-return fader, ACK and epoch bound. // Structural AUX enabling/mute/toMaster/FX replacement still uses APPLY. let auxMasterRequestId=1; const auxMasterPending=new Map(); + const auxMasterLatest=new Map(); + const auxMasterInFlightGain=new Map(); window.__arMixSetLiveAuxMasterGain=(bus,value)=>{ const d=state.dryRoutingLab||{},gain=Number(value); if(!Number.isInteger(bus)||bus<0||bus>=4||!Number.isFinite(gain)|| @@ -1240,9 +1259,15 @@ rackFxDraft||!Array.isArray(d.acceptedRoute.auxes)|| !d.acceptedRoute.auxes[bus]?.enabled) return {ok:false,error:"AUX master unavailable: finish DRAFT and APPLY the enabled bus first."}; - if(auxMasterPending.has(bus)) - return {ok:false,error:"Wait for previous AUX master native ACK."}; + if(auxMasterPending.has(bus)){ + if(Math.abs(gain-auxMasterInFlightGain.get(bus))<1e-7)auxMasterLatest.delete(bus); + else auxMasterLatest.set(bus,gain); + return {ok:true,pending:true,queued:true,message:"AUX MASTER COALESCED · WAIT ACK"}; + } + if(Math.abs(gain-Number(d.acceptedRoute.auxes[bus].gain))<1e-7) + return {ok:true,unchanged:true,message:"AUX MASTER ALREADY ACKNOWLEDGED"}; const requestId=auxMasterRequestId++; + auxMasterInFlightGain.set(bus,gain); auxMasterPending.set(bus,requestId); api.emitEvent("arMixAction",{action:"routingAuxBusGain", bus,requestId,deviceEpoch:Number(d.epoch),revision:Number(d.revision), @@ -1253,6 +1278,7 @@ const bus=Number(ack?.bus),id=Number(ack?.requestId); if(auxMasterPending.get(bus)!==id)return; auxMasterPending.delete(bus); + auxMasterInFlightGain.delete(bus); const next=ack?.state||{},now=state.dryRoutingLab||{}; const ok=ack?.ok===true&&next.epoch===now.epoch&& next.revision===now.revision&&next.acceptedRoute&&!patchPending&& @@ -1266,6 +1292,10 @@ window.dispatchEvent(new CustomEvent("arMixAuxMasterGainResult",{ detail:{ok:!!ok,bus,gain:Number(ack?.gain), error:ok?"":String(ack?.error||"AUX native ACK stale; refresh device")}})); + const latest=auxMasterLatest.get(bus); + auxMasterLatest.delete(bus); + if(ok&&latest!==undefined&&Math.abs(latest-Number(ack.gain))>=1e-7) + window.__arMixSetLiveAuxMasterGain(bus,latest); }); window.__arMixStageAuxReturnEdit=(bus,field,value)=>{ const fault=sendEditGate(0,bus); @@ -1363,6 +1393,55 @@ return {ok:true,pending:true,epoch:Number(d.epoch), message:"SOURCE PENDING · native ACK required; output remains MUTED."}; }; + + // M1 input-only same-format crossfade. This updates one atomic physical PCM + // source in the existing native graph, never changes FX/bus/output topology. + let liveSourceRequestId=1,liveSourcePending=null; + window.__arMixCommitSelectedSource=(channel,mode,left,right)=>{ + const d=state.dryRoutingLab||{},r=d.acceptedRoute?.channels?.[channel]; + if(!r||r.mode!==mode||!["MONO","STEREO"].includes(mode)) + return window.__arMixCommitMutedSource(channel,mode,left,right); + if(!d.ready||!d.active||draftEpoch!==Number(d.epoch)|| + patchPending||mixerDraftActive||rackFxDraft||nativeShowBusy|| + liveSendPending.size) + return {ok:false,error:"Finish native APPLY, FX/SEND draft or Show before SOURCE switching."}; + if(liveSourcePending)return {ok:false,error:"Wait for previous SOURCE native ACK."}; + const active=new Set(patchPorts().map(p=>p.port)); + if(!active.has(left)||(mode==="STEREO"&&(!active.has(right)||left===right))) + return {ok:false,error:"SOURCE requires verified enabled driver pins."}; + const targetRight=mode==="STEREO"?right:-1; + if(r.left===left&&r.right===targetRight) + return {ok:true,unchanged:true,message:"SOURCE ALREADY ACKNOWLEDGED"}; + const id=liveSourceRequestId++; + liveSourcePending={id,channel,mode,left,right:targetRight, + epoch:Number(d.epoch),revision:Number(d.revision)}; + api.emitEvent("arMixAction",{action:"routingSourceSwitch", + requestId:id,channel,mode,left,right:targetRight, + deviceEpoch:Number(d.epoch),revision:Number(d.revision)}); + return {ok:true,pending:true,live:true,epoch:Number(d.epoch), + message:"LIVE INPUT CROSSFADE · WAIT NATIVE ACK"}; + }; + api.addEventListener("arMixSourceSwitchAck",ack=>{ + const p=liveSourcePending; + if(!p||Number(ack?.requestId)!==p.id||Number(ack?.channel)!==p.channel)return; + liveSourcePending=null; + const next=ack?.state||{},old=state.dryRoutingLab||{}; + const accepted=next.acceptedRoute?.channels?.[p.channel]; + const ok=ack?.ok===true&&Number(next.epoch)===p.epoch&& + Number(next.revision)===p.revision&&Number(old.epoch)===p.epoch&& + Number(old.revision)===p.revision&&accepted?.mode===p.mode&& + accepted.left===p.left&&accepted.right===p.right; + if(ok){ + state.dryRoutingLab=next; + hydrateAcceptedRoute(); + renderPatchMatrix();updateRouteLabIdentity(); + window.dispatchEvent(new Event("arMixRoutingDraftChanged")); + } + window.dispatchEvent(new CustomEvent("arMixSourceSwitchResult",{detail:{ + ok,channel:p.channel, + error:ok?"":String(ack?.error||"Source changed or native ACK mismatch") + }})); + }); window.__arMixOpenChannelPatch=(channel,tab="input")=>{ if(!Number.isInteger(channel)||channel<0||channel>=10)return; openRoutingLab();