diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 965bd2fbf..63ce63875 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -16,6 +16,9 @@ on: # Native Windows gate executes this JS integration contract; source-only # contract corrections must not leave a stale failed release gate. - 'tests/live_routing_ui_contract_test.mjs' + - 'tests/console_v6_fat_gate_test.mjs' + - 'tests/native_embedded_gui_assets_contract_test.mjs' + - 'scripts/collect_hardware_fat_windows.ps1' - 'scripts/package_native_windows.ps1' - 'scripts/verify_native_windows_artifact.ps1' - 'scripts/factoryfx_release_bundle.py' @@ -35,6 +38,9 @@ on: - 'tests/*native*contract*.mjs' - 'tests/live_graph_contract_test.mjs' - 'tests/ci_workflow_efficiency_test.mjs' + - 'tests/console_v6_fat_gate_test.mjs' + - 'tests/native_embedded_gui_assets_contract_test.mjs' + - 'scripts/collect_hardware_fat_windows.ps1' - 'scripts/package_native_windows.ps1' - 'scripts/verify_native_windows_artifact.ps1' - 'scripts/factoryfx_release_bundle.py' @@ -57,14 +63,32 @@ jobs: timeout-minutes: 50 steps: - uses: actions/checkout@v4 + with: + # PR default is a transient refs/pull/*/merge. Test and package + # the precise approved ENGINE SHA, never a synthetic merge. + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + - name: Attest exact source SHA before native compile or packaging + shell: pwsh + run: | + $expected = "${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}" + $actual = (& git rev-parse HEAD).Trim() + if ($expected -notmatch '^[0-9a-f]{40}$' -or $actual -ne $expected) { + throw "ENGINE SOURCE SHA MISMATCH: expected=$expected checkout=$actual" + } + Write-Host "ENGINE_EXACT_SOURCE_SHA_VERIFIED: $actual" - name: Cheap canonical Console v6 puzzle socket gate (no JUCE) - run: node scripts/check_console_puzzle.mjs + run: | + node --test tests/engine_runtime_reconciliation_test.mjs + node scripts/check_console_puzzle.mjs - name: Stop incomplete integrated product promotion before JUCE checkout if: ${{ github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-') }} run: node scripts/check_console_puzzle.mjs --release - name: Fast offline FactoryFX release and integrity contract tests shell: pwsh run: | + $tokens=$null; $parseErrors=$null + [System.Management.Automation.Language.Parser]::ParseFile('scripts/collect_hardware_fat_windows.ps1',[ref]$tokens,[ref]$parseErrors) | Out-Null + if (@($parseErrors).Count -gt 0) { throw ($parseErrors | Out-String) } python -m unittest discover -s scripts/tests -p test_factoryfx_release_bundle.py -v if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Checkout JUCE 8 pinned @@ -81,7 +105,7 @@ jobs: run: | # Do not hide earlier Node failures with the exit code of the LAST # command. One Node invocation also avoids repeated startup costs. - foreach ($file in @('web/bridge.js', 'web/plugin-ui.js', 'web/monitor.js', 'web/app.js', 'web/mixer-io.js', 'web/mixer-layout.js')) { + foreach ($file in @('web/bridge.js', 'web/plugin-ui.js', 'web/monitor.js', 'web/app.js', 'web/mixer-io.js', 'web/mixer-layout.js', 'web/hardware-keys.js')) { node --check $file if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } @@ -100,6 +124,8 @@ jobs: 'tests/independent_clock_adapter_contract_test.mjs' 'tests/direct_restore_recovery_contract_test.mjs' 'tests/native_artifact_packaging_contract_test.mjs' + 'tests/console_v6_fat_gate_test.mjs' + 'tests/native_embedded_gui_assets_contract_test.mjs' 'tests/portable_workspace_contract_test.mjs' 'tests/plugin_vault_contract_test.mjs' 'tests/plugin_ui_contract_test.mjs' @@ -137,12 +163,12 @@ jobs: & ./scripts/verify_native_windows_artifact.ps1 -OutputDir dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } # PRs compile/CTest/package but never silently publish a stable build. - # This single M4 FAT branch is explicitly allowed to upload an - # UNQUALIFIED experimental ZIP for real physical hardware testing. + # Exactly one joined ENGINE+GUI+FAT PR can upload an UNQUALIFIED + # experimental executable. This does not enable universal claims. - uses: actions/upload-artifact@v4 - if: ${{ github.event_name != 'pull_request' || github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101' }} + if: ${{ github.event_name != 'pull_request' || github.head_ref == 'milestone/m5-universal-channelid-vst3-lease-migration-20261101' || github.head_ref == 'work/integration-fat-console-v6' }} with: - name: ${{ github.event_name == 'pull_request' && 'ArSonMix-M4-EXPERIMENTAL-Hardware-FAT-Windows-x64' || 'ArSonMix-GUI10CH-P012-Verified-Hardware-FAT-Windows-x64' }} + name: ${{ github.event_name == 'pull_request' && (github.head_ref == 'work/integration-fat-console-v6' && 'ArSonMix-JOINED-10CH4AUX-EXPERIMENTAL-Hardware-FAT-Windows-x64' || 'ArSonMix-ENGINE-10CH4AUX-EXPERIMENTAL-Hardware-FAT-Windows-x64') || 'ArSonMix-GUI10CH-P012-Verified-Hardware-FAT-Windows-x64' }} path: dist/ if-no-files-found: error retention-days: 14 diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 4ed052310..e5c90d0f9 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -26,7 +26,7 @@ on: - 'tests/*gui*contract*.mjs' - 'tests/native_ui_contract_test.mjs' - 'tests/native_orbit_ui_smoke.py' - - 'tests/ci_workflow_efficiency_test.mjs' + - 'tests/ci_workflow_efficiency_test.mjs tests/console_v6_fat_gate_test.mjs tests/native_embedded_gui_assets_contract_test.mjs' - '.github/workflows/ui-smoke.yml' - '.github/workflows/pages-publish.yml' workflow_dispatch: diff --git a/AR-MIX-Live-FX-Host-Standalone-v0.3.html b/AR-MIX-Live-FX-Host-Standalone-v0.3.html index d280a1443..2a8f9b2f9 100644 --- a/AR-MIX-Live-FX-Host-Standalone-v0.3.html +++ b/AR-MIX-Live-FX-Host-Standalone-v0.3.html @@ -612,7 +612,7 @@ Semantic colors alone define the latched state; only the transient :active pointer press moves the cap inward by 1px without changing its layout slot. */ :root{ - --b180-off:#cbd1d1;--b180-edge:#747f7f;--b180-off-ink:#172229; + --b180-off:#E7EFF0;--b180-edge:#747f7f;--b180-off-ink:#172229; --b180-color:var(--b180-off);--b180-border:var(--b180-edge); --b180-ink:var(--b180-off-ink); --b180-on-cyan:#94e8ed;--b180-on-green:#91edac; @@ -1448,6 +1448,163 @@ background-clip:content-box;border:0;box-shadow:none; } #app #mixer .meter .clip-led.latched{box-shadow:none!important} +/* Owner-approved V5 graphite hardware keys, production native/legacy console. + ONE SVG cutout legend, ONE white edge shine, asymmetric occluded leakage. + No hover repaint, SVG filters, blur, infinite animation, or fake audio state. + This module is LAST in the deterministic CSS build, replacing BTN-180 only + on opt-in tactile mixer buttons. Navigation, routing pins, meters, faders, + editor launchers, dropdowns and ordinary dialog actions are NOT backlit. */ +#app button.mx-hw-key { + --mx-hw-led:210,225,234; + position:relative!important; + display:inline-block!important; + box-sizing:border-box!important; + min-width:0!important; + padding:2px!important; + overflow:hidden!important; + isolation:isolate!important; + border:1px solid #0c151b!important; + border-radius:5px!important; + background:linear-gradient(180deg,#0b141b,#25343d)!important; + box-shadow:inset 0 2px 4px #03080db5!important; + color:transparent!important; + text-shadow:none!important; + letter-spacing:0!important; + line-height:normal!important; + filter:none!important; + backdrop-filter:none!important; + -webkit-backdrop-filter:none!important; + transform:none!important; + transition:none!important; + text-align:center!important; + cursor:pointer; + touch-action:manipulation; +} +#app button.mx-hw-key.mx-hw-mute {--mx-hw-led:255,64,85} +#app button.mx-hw-key.mx-hw-solo {--mx-hw-led:255,208,44} +#app button.mx-hw-key.mx-hw-cue {--mx-hw-led:90,200,231} +#app button.mx-hw-key.mx-hw-processing {--mx-hw-led:87,211,189} +#app button.mx-hw-key.mx-hw-phase {--mx-hw-led:243,164,81} +#app button.mx-hw-key.mx-hw-link {--mx-hw-led:163,141,235} +#app button.mx-hw-key.mx-hw-neutral {--mx-hw-led:210,225,234} +/* V5 leakage strategy: four tiny STATIC gradients only in the closest + 1–2px gap, unequal sides, lower-center stronger; top almost occluded. */ +#app button.mx-hw-key::before { + content:""!important; + display:block!important; + position:absolute!important; + inset:1px!important; + border:0!important; + border-radius:4px!important; + width:auto!important;height:auto!important; + transform:none!important; + pointer-events:none!important; + z-index:2!important; + opacity:0!important; + box-shadow:none!important; + background: + linear-gradient(90deg,transparent 0%,rgba(var(--mx-hw-led),.035) 18%, + rgba(var(--mx-hw-led),.16) 33%,rgba(var(--mx-hw-led),.46) 49%, + rgba(var(--mx-hw-led),.27) 63%,rgba(var(--mx-hw-led),.07) 80%,transparent 100%) + center bottom / calc(100% - 12px) 2px no-repeat, + linear-gradient(180deg,transparent 0%,transparent 30%, + rgba(var(--mx-hw-led),.045) 50%,rgba(var(--mx-hw-led),.21) 75%, + rgba(var(--mx-hw-led),.1) 88%,transparent 100%) + left bottom / 2px 100% no-repeat, + linear-gradient(180deg,transparent 0%,transparent 44%, + rgba(var(--mx-hw-led),.075) 65%,rgba(var(--mx-hw-led),.17) 85%, + transparent 100%) + right bottom / 2px 100% no-repeat, + linear-gradient(90deg,transparent 0%,transparent 34%, + rgba(var(--mx-hw-led),.055) 50%,transparent 67%,transparent 100%) + center top / calc(100% - 18px) 1px no-repeat!important; +} +#app button.mx-hw-key::after{content:none!important;display:none!important} +#app button.mx-hw-key[aria-pressed="true"]::before, +#app button.mx-hw-key.active::before, +#app button.mx-hw-key.selected::before, +#app button.mx-hw-key.power-on::before, +#app button.mx-hw-key[data-mx-hw-on="true"]::before {opacity:1!important} +#app button.mx-hw-key > svg.mx-hw-face { + position:absolute!important; + z-index:1!important; + top:2px!important;right:2px!important;bottom:2px!important;left:2px!important; + width:calc(100% - 4px)!important; + height:calc(100% - 4px)!important; + display:block!important; + min-height:0!important; + overflow:hidden!important; + pointer-events:none!important; + transform:translateY(0)!important; + transition:none!important; + filter:none!important; +} +#app button.mx-hw-key svg .mx-hw-lamp {opacity:0!important} +#app button.mx-hw-key[aria-pressed="true"] svg .mx-hw-lamp, +#app button.mx-hw-key.active svg .mx-hw-lamp, +#app button.mx-hw-key.selected svg .mx-hw-lamp, +#app button.mx-hw-key.power-on svg .mx-hw-lamp, +#app button.mx-hw-key[data-mx-hw-on="true"] svg .mx-hw-lamp {opacity:1!important} +#app button.mx-hw-key[aria-pressed="true"] > svg.mx-hw-face, +#app button.mx-hw-key.active > svg.mx-hw-face, +#app button.mx-hw-key[data-mx-hw-on="true"] > svg.mx-hw-face { + transform:translateY(1px)!important; +} +#app button.mx-hw-key > .mx-hw-screen-reader{ + position:absolute!important; + width:1px!important;height:1px!important; + margin:-1px!important;padding:0!important; + border:0!important;overflow:hidden!important; + clip-path:inset(50%)!important; + white-space:nowrap!important; +} +#app button.mx-hw-key:hover:not(:disabled){ + filter:none!important; + background:linear-gradient(180deg,#0b141b,#25343d)!important; + box-shadow:inset 0 2px 4px #03080db5!important; +} +#app button.mx-hw-key:active:not(:disabled){ + transform:none!important; + background:linear-gradient(180deg,#0b141b,#25343d)!important; + box-shadow:inset 0 2px 4px #03080db5!important; +} +#app button.mx-hw-key:active:not(:disabled) > svg.mx-hw-face{ + transform:translateY(1px)!important; +} +#app button.mx-hw-key:focus-visible{ + outline:2px solid #9bbecd!important; + outline-offset:2px!important; +} +#app button.mx-hw-key:disabled { + cursor:not-allowed!important; + opacity:.47!important; + filter:none!important; +} +#app button.mx-hw-key:disabled::before{opacity:0!important} +#app button.mx-hw-key:disabled svg .mx-hw-lamp{opacity:0!important} +/* Keep target strip geometry intact, bypassing the legacy BTN-180 face. */ +#app #mixer .channel-actions button.mx-hw-key, +#app #mixer .utility-row button.mx-hw-key { + flex:1 1 0; +} +/* The legacy MASTER MUTE was sized only by .candy. Own its 29px geometry + explicitly after replacing that obsolete class, matching every strip. */ +#app #masterLeft .master-actions button.mx-hw-key, +#app #masterMute.mx-hw-key{ + height:29px!important; + min-height:29px!important; + max-height:29px!important; + align-self:center!important; +} +#app #mixer [data-channel-format-toggle].mx-hw-key{ + min-width:20px!important; +} +#app .arV6Controls button.mx-hw-key{width:28px!important;height:28px!important;padding:2px!important} +#app .arV6FxSlot button.mx-hw-key{min-width:27px!important;min-height:22px!important;padding:2px!important} +#app .arV6Send button.mx-hw-key{min-width:34px!important;min-height:20px!important;padding:2px!important} +@media(prefers-reduced-motion:reduce){ + #app button.mx-hw-key,#app button.mx-hw-key > svg.mx-hw-face{transition:none!important} +}
@@ -2401,7 +3892,7 @@ ['Backing','♫',['EQ','Reverb'],-3.6,-25], ['Guitar','♬',['EQ','Compressor','Delay'],-7.9,30], ['Keyboard','▥',['EQ','Reverb'],-14.2,0], - ['FX Return','◎',['Reverb'],-5.1,0] + ['Input 10','♩',['Reverb'],-5.1,0] ]; const channels=raw.map((a,i)=>({id:i+1,name:a[0],icon:a[1],color:colors[i],inserts:[...a[2]],fader:a[3],pan:a[4],trim:0,mute:false,solo:false,pre:false,hpf:i%4!==0,stereo:i>=6})); let currentChannel=0, masterSelected=false, view='MIX', sceneIdx=0, timer=0; @@ -2656,19 +4147,38 @@ document.querySelectorAll('.strip.identity-editing').forEach(el=>el.classList.remove('identity-editing')); } function commitChannelIdentity(){ - if(editingChannel<0)return;const index=editingChannel; - const name=$('identityName').value.trim().replace(/\s+/g,' ').slice(0,26); + if(editingChannel<0)return; + const index=editingChannel, name=$('identityName').value.trim().replace(/\s+/g,' ').slice(0,26); if(!name){flash('Enter a channel name');$('identityName').focus();return} - channels[index].name=name;channels[index].icon=channelIcons.includes(editingIcon)?editingIcon:'♩'; - channels[index].color=channelPalette.includes(editingColor)?editingColor:colors[index]; - closeChannelIdentity();currentChannel=index;renderMixer(); + if(channels.some((c,i)=>i!==index&&c.name.trim().toLowerCase()===name.toLowerCase())){ + flash('Channel name already used');$('identityName').focus();return; + } + const ch=channels[index]; + ch.name=name;ch.icon=channelIcons.includes(editingIcon)?editingIcon:'♩'; + ch.color=channelPalette.includes(editingColor)?editingColor:colors[index]; + closeChannelIdentity();currentChannel=index; + // UI identity is not a native graph change. Do not remount any live FX/fader node. + const strip=document.querySelector('#mixer [data-strip="'+index+'"]'); + if(strip){ + strip.style.setProperty('--ch',ch.color); + for(const [sel,val] of [['.arChannelTopName',ch.name],['.arChannelTopIcon',ch.icon], + ['.strip-name .strip-caption',ch.name],['.strip-name .track-icon',ch.icon]]){ + const item=strip.querySelector(sel);if(item)item.textContent=val; + } + strip.querySelector('[data-identity-open]')?.setAttribute('aria-label','Edit '+ch.name+' name, icon and color'); + strip.querySelector('[data-editstrip]')?.setAttribute('aria-label','Double-click to edit '+ch.name+' name, icon and color'); + strip.querySelector('[data-fader]')?.setAttribute('aria-label',ch.name+' fader'); + const meter=strip.querySelector('.vu-bank'); + if(meter)meter.setAttribute('aria-label',ch.name+(ch.stereo?' stereo left and right meters':' mono meter')); + } + createSide(); if(view==='FX RACK')renderRackWorkspace(); - persistSession();flash('Channel identity updated'); + persistSession();flash('Channel label updated · native audio route unchanged'); } window.addEventListener('resize',positionChannelIdentity); $('mixer').addEventListener('scroll',positionChannelIdentity,{passive:true}); function makeStrip(ch,i){let inserts=ch.inserts.slice(0,6);while(inserts.length<6) inserts.push('');return `
-
${i+1}
${inserts.map((n,j)=>`
${n?``:''}
`).join('')}
+
CH ${String(i+1).padStart(2,'0')}
${inserts.map((n,j)=>`
${n?``:''}
`).join('')}
TRIM
dB
${fmt(ch.trim)}
${knobMarkup('trim',i,ch.trim,'Trim')}
${panMarkup(ch,i)}
${panText(ch.pan)}
${fmt(ch.fader)}
${ch.stereo?meterUnit(String(i)+'L','L')+meterUnit(String(i)+'R','R'):meterUnit(String(i),'')}${meterScaleMarkup()}
${faderScaleMarkup()}
@@ -2695,7 +4205,7 @@ window.__arMixSyncAcceptedChannelFormat=syncStripFormat; function renderMixer(){ const x=$('mixer'),scroll=x.scrollLeft; - x.innerHTML=channels.map(makeStrip).join('')+'
'; + x.innerHTML=channels.map(makeStrip).join('')+'
'; renderMaster();x.scrollLeft=scroll;createSide(); } let masterGain=-.1,masterPan=0,masterMute=false,masterMono=false,phones=-12,masterInserts=['Studio EQ','Brickwall Limiter'],masterBypassed={},pendingMasterSlot=null; @@ -2717,7 +4227,7 @@ function meterUnit(key,label){return `
`} function renderMaster(){ const host=$('masterLeft');if(!host)return; - host.innerHTML=`
MASTER
+ host.innerHTML=`
MAIN
${masterFxRows()}
@@ -2839,6 +4349,11 @@ if(b.dataset.pluginManager!==undefined){flash('Plugin Manager is available in the Windows desktop app');return} if(b.dataset.mySounds!==undefined){flash('Native VST3 presets are available in the Windows desktop app');return} if(b.dataset.choose!==undefined){chooseChannel(+b.dataset.choose);return} + if(b.dataset.identityOpen!==undefined){ + const index=Number(b.dataset.identityOpen); + if(Number.isInteger(index)&&index>=0&&index=channels.length)return; @@ -2854,11 +4369,11 @@ if(b.dataset.mute!==undefined){toggleState(+b.dataset.mute,'mute');return}if(b.dataset.solo!==undefined){toggleState(+b.dataset.solo,'solo');return} if(b.dataset.pre!==undefined){let i=+b.dataset.pre;channels[i].pre=!channels[i].pre;b.classList.toggle('active');send('phase',channels[i].pre,i);return} if(b.dataset.hpf!==undefined){let i=+b.dataset.hpf;channels[i].hpf=!channels[i].hpf;b.classList.toggle('active');send('hpf',channels[i].hpf,i);return} - if(b.dataset.masterInsert!==undefined){pendingMasterSlot=+b.dataset.masterInsert;openPluginBrowser(currentChannel,true);return} + if(b.dataset.masterInsert!==undefined){pendingMasterSlot=+b.dataset.masterInsert;if(!window.__JUCE__?.backend?.emitEvent)openQuickFx(currentChannel,pendingMasterSlot,b,true);return} if(b.dataset.masterPower!==undefined){const slot=+b.dataset.masterPower;masterBypassed[slot]=!masterBypassed[slot];renderMaster();persistSession();send('masterFxBypass',{slot,bypass:masterBypassed[slot]},-1);return} if(b.dataset.clip!==undefined){resetClip(b.dataset.clip);return} if(b.dataset.fxpower!==undefined){const [i,j]=b.dataset.fxpower.split(':').map(Number);setFxBypass(i,j,!bypassed[fxKey(i,j)]);return} - if(b.dataset.insert){let [i,j]=b.dataset.insert.split(':').map(Number);currentChannel=i;pendingSlot=j;openPluginBrowser(i);return} + if(b.dataset.insert){let [i,j]=b.dataset.insert.split(':').map(Number);if(!window.__JUCE__?.backend?.emitEvent)openQuickFx(i,j,b);return} if(b.dataset.deleteScene!==undefined){deleteMixerSnapshot(b.dataset.deleteScene);return} if(b.dataset.scene!==undefined){loadSnapshotByIndex(+b.dataset.scene);return} if(b.dataset.preset){applyQuickPreset(b.dataset.preset);return} @@ -3148,8 +4663,74 @@ return; } $('rackWorkspace').innerHTML=`
NO TECHNICAL PATCHBAY REQUIRED

Signal Flow — See where your voice goes

A beginner-first view of the real-time audio path. Select your audio device in Setup.

01 · INPUTMicrophoneAudio Interface
ASIO or WASAPI
➜
02 · FX CHAINVST3 PluginsEQ · Dynamics
Reverb · Delay
➜
03 · MIXERMix & MonitorFader · Pan
Master · Meters
➜
04 · OUTPUTSpeakers / StreamAudio Device
Streaming bridge later
⚠ In this trial the audio flow is a visual concept; no microphone is captured and no audio is sent to a livestream.
`} + +// Adopt PR #278 V5 contextual quick-insert on the ORIGINAL mixer. +// Desktop native operations remain owned by bridge.js; this uses preview +// catalog ONLY when JUCE is absent, never as a fabricated VST3 instance. +const arV5Quick=document.createElement('section'); +arV5Quick.className='arV5QuickFx';arV5Quick.hidden=true; +arV5Quick.setAttribute('role','dialog'); +arV5Quick.setAttribute('aria-label','Quick add effect'); +arV5Quick.innerHTML='
ADD FX
'+ + ''+ + '
'+ + '
Enter: insert · Esc: close
'; +document.querySelector('#app .workbench')?.append(arV5Quick); +const arV5Search=arV5Quick.querySelector('.arV5QuickSearch'), + arV5Results=arV5Quick.querySelector('.arV5QuickResults'); +let arV5Anchor=null; +function closeQuickFx(focus=false){ + if(arV5Quick.hidden)return; + arV5Quick.hidden=true; + if(focus&&arV5Anchor?.isConnected)arV5Anchor.focus(); + arV5Anchor=null; +} +function renderQuickFx(){ + if(arV5Quick.hidden)return; + arV5Results.replaceChildren(); + const q=arV5Search.value.trim().toLocaleLowerCase(); + const found=pluginCatalog.filter(p=> + (p.name+' '+p.type+' '+(p.hint||'')).toLocaleLowerCase().includes(q)); + for(const fx of found.slice(0,64)){ + const b=document.createElement('button');b.type='button'; + b.className='arV5QuickResult';b.dataset.fastPlugin=fx.name; + const title=document.createElement('span');title.textContent=fx.name; + const kind=document.createElement('small');kind.textContent=fx.type; + b.append(title,kind);arV5Results.append(b); + } + if(!found.length){const p=document.createElement('p');p.textContent='No matching demo effects';arV5Results.append(p);} +} +function openQuickFx(channel,slot,anchor,isMaster=false){ + if(window.__JUCE__?.backend?.emitEvent)return false; + if(!isMaster){currentChannel=channel;pendingMasterSlot=null;pendingSlot=slot;} + else pendingMasterSlot=slot; + arV5Anchor=anchor; + arV5Quick.querySelector('.arV5QuickHead strong').textContent= + (isMaster?'MAIN':channels[channel]?.name||'CHANNEL')+' · FX '+(slot+1)+' · UI PREVIEW'; + const host=arV5Quick.parentElement,r=anchor?.getBoundingClientRect(),p=host?.getBoundingClientRect(); + if(r&&p){arV5Quick.style.left=Math.max(6,Math.min(r.left-p.left,p.width-320))+'px'; + arV5Quick.style.top=Math.max(6,Math.min(r.bottom-p.top+4,p.height-360))+'px';} + arV5Quick.hidden=false;arV5Search.value='';renderQuickFx();arV5Search.focus();return true; +} +arV5Search.addEventListener('input',renderQuickFx); +arV5Quick.addEventListener('click',e=>{ + if(e.target.closest('[data-fast-close]')){closeQuickFx(true);return;} + if(e.target.closest('[data-fast-manager]')){ + closeQuickFx();openPluginBrowser(currentChannel,pendingMasterSlot!==null);return;} + const b=e.target.closest('[data-fast-plugin]');if(!b)return; + if(!pluginCatalog.some(p=>p.name===b.dataset.fastPlugin))return; + closeQuickFx();insertPlugin(b.dataset.fastPlugin); +}); +arV5Quick.addEventListener('keydown',e=>{ + if(e.key==='Escape'){e.preventDefault();e.stopPropagation();closeQuickFx(true);} + if(e.key==='Enter'&&e.target===arV5Search){ + const first=arV5Results.querySelector('[data-fast-plugin]'); + if(first){e.preventDefault();first.click();} + } +}); + function openPluginBrowser(idx,isMaster=false){if(!isMaster){currentChannel=idx;pendingMasterSlot=null}activeCategory='All';$('pluginModal').classList.remove('hidden');$('pluginTarget').textContent=isMaster?'Adding to MASTER bus · demo FX catalog':'Adding to '+channels[idx].name+' · virtual effects catalog';$('pluginSearch').value='';renderPluginBrowser();$('pluginSearch').focus()} -function closePluginBrowser(){$('pluginModal').classList.add('hidden')} +function closePluginBrowser(){closeQuickFx();$('pluginModal').classList.add('hidden')} function renderPluginBrowser(){document.querySelectorAll('[data-category]').forEach(b=>b.classList.toggle('active',b.dataset.category===activeCategory));const q=$('pluginSearch').value.trim().toLowerCase();let pool=pluginCatalog.filter(p=>(activeCategory==='All'||p.type===activeCategory)&&`${p.name} ${p.type} ${p.hint}`.toLowerCase().includes(q));$('pluginResults').innerHTML=pool.map(p=>``).join('')||'

No matching demo effects.

'} function insertPlugin(name){ if(pendingMasterSlot!==null){ @@ -3369,7 +4950,7 @@ $('pluginModal').addEventListener('click',e=>{if(e.target===$('pluginModal'))closePluginBrowser()}); $('channelIdentity').addEventListener('click',e=>{if(e.target===$('channelIdentity'))closeChannelIdentity()}); $('identityName').addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();commitChannelIdentity()}}); -document.addEventListener('keydown',e=>{if(e.key==='Escape'){closePluginBrowser();closeChannelIdentity()}if((e.key==='Enter'||e.key===' ')&&e.target.matches('[data-editstrip]')){e.preventDefault();openChannelIdentity(+e.target.dataset.editstrip)}}); +document.addEventListener('keydown',e=>{if(e.key==='F8'&&!e.repeat&&!document.documentElement.classList.contains('ar-v6-active')){e.preventDefault();if(window.__JUCE__?.backend?.emitEvent)document.querySelector('[data-plugin-manager]')?.click();else{closeQuickFx();openPluginBrowser(currentChannel,pendingMasterSlot!==null)}return;}if(e.key==='Escape'){closeQuickFx();closePluginBrowser();closeChannelIdentity()}if((e.key==='Enter'||e.key===' ')&&e.target.matches('[data-editstrip]')){e.preventDefault();openChannelIdentity(+e.target.dataset.editstrip)}}); document.addEventListener('change',e=>{if(e.target.id==='rackChannel')chooseChannel(+e.target.value)}); document.addEventListener('click',e=>{const id=e.target.closest('button')?.id;if(id==='saveFxFromRack')saveFxChainPreset();else if(id==='recallFxPreset')recallFxChain();else if(id==='openSetupFromFlow')$('audioSetupBtn')?.click();else if(id==='flowFxButton')setView('FX RACK');else if(id==='backMixer')setView('MIX')}); // The UI-only envelope remains one atomic storage transaction, never a 5s @@ -3465,11 +5046,11 @@ const mixer=document.getElementById('mixer'); const host=document.querySelector('.workbench'); if(!mixer||!host)return; - let mode='FX', lastStatus={}, deviceInventory=null, ioTab='device', lastSignature='', focusedInput=2; + let mode='CONSOLE', lastStatus={}, deviceInventory=null, ioTab='device', lastSignature='', focusedInput=0; let monitorSendsExpanded=false; // DEVICE1: staged selections are UI-only; only positive native ACK changes active hardware. let deviceDraft=null,deviceBusy=false,deviceNote='',deviceRequest='',deviceRequestSeq=0,lastDeviceRefresh=0,lastDeviceRescan=0,applyMutePending=false,applyAfterDevice=null,applyBaseEpoch=0; - let deviceMatrixView='inputs',deviceMatrixWaitEpoch=null; // Never display old hardware pins after an APPLY ACK. + let deviceMatrixView='inputs',deviceMatrixWaitEpoch=null,deviceMatrixOpen=false; // Never display old hardware pins after an APPLY ACK. // Pending SOURCE ACK is a UI projection only; monitor.js owns the native route. let quickSourcePending=null; const el=id=>document.getElementById(id); @@ -3707,13 +5288,19 @@ return section; } + // Only an ACKed physical MAIN pair is a MAIN route. Available output pins + // are merely inventory, never proof that a route has been selected. const outputLabel=s=>{ - const out=s.mainOutputs?.length===2?s.mainOutputs:s.outputPorts||[]; - return s.ready&&Number.isInteger(out[0])&&Number.isInteger(out[1])? - 'MAIN → HW '+(out[0]+1)+'/'+(out[1]+1):'MAIN → NO HW OUTPUT'; + const out=s.mainOutputs,enabled=new Set(s.outputPorts||[]); + if(!s.ready)return 'MAIN → NO DEVICE'; + if(!Array.isArray(out)||out.length!==2)return 'MAIN → UNPATCHED'; + if(!Number.isInteger(out[0])||!Number.isInteger(out[1])|| + out[0]===out[1]||!enabled.has(out[0])||!enabled.has(out[1])) + return 'MAIN → INVALID L/R'; + return 'MAIN → HW '+(out[0]+1)+'/'+(out[1]+1); }; const toolbar=node('div','arMixerBankBar'); - toolbar.innerHTML='
NO HARDWARE · PREVIEW
'; + toolbar.innerHTML='
NO HARDWARE · PREVIEW
'; host.insertBefore(toolbar,mixer); // One genuinely selected-channel journey, NOT another DSP or source registry. // Four compact steps show ACKNOWLEDGED state, never stage a hidden graph. @@ -3912,7 +5499,7 @@ sofControls.hidden=true;toolbar.appendChild(sofControls); const overlay=node('div','arIOOverlay'); overlay.id='arIOOverlay';overlay.hidden=true; - overlay.innerHTML=''; + overlay.innerHTML=''; document.body.appendChild(overlay); const audioPath=node('div','arIOAudioPath');audioPath.id='arIOAudioPath'; audioPath.innerHTML='CAPTURE · WAITROUTE · WAITMIXER · WAITOUTPUT · WAIT'; @@ -4228,7 +5815,7 @@ window.__arMixOpenAudioIO=openIO; function closeIO(){overlay.hidden=true;matrixDraft.clear();matrixSide.clear();matrixMessage='';} function setMode(next){ - if(!['FX','ROUTE','SENDS'].includes(next))return; + if(!['CONSOLE','FX','ROUTE','SENDS'].includes(next))return; if(next!=='SENDS'&&sofBus>=0)leaveSof(); mode=next;mixer.dataset.ioMode=mode; toolbar.querySelectorAll('[data-mix-mode]').forEach(b=>{const selected=b.dataset.mixMode===mode;b.classList.toggle('active',selected);b.setAttribute('aria-pressed',String(selected));}); @@ -4247,7 +5834,7 @@ } if(strip.querySelector('.arChannelBank'))continue; const bank=node('div','arChannelBank'); - bank.innerHTML='
INPUT SOURCE · NATIVEOUTPUT DESTINATIONMAIN · UNKNOWN
NATIVE PATCH REQUIRED
AUX SENDS · PRE / POST
'; + bank.innerHTML='
INPUT SOURCE · NATIVEOUTPUT DESTINATION
NATIVE PATCH REQUIRED
AUX SENDS · PRE / POST
'; strip.querySelector('.rack')?.insertAdjacentElement('afterend',bank); } } @@ -4287,8 +5874,22 @@ const dirty=current!==valueFor(accepted)||channelFormat(r)!==channelFormat(accepted); const stage=strip.querySelector('.arBankStage'); const sourcePending=quickSourcePending?.channel===i&&quickSourcePending.epoch===s.epoch; - stage.textContent=!s.ready?'NO LIVE DEVICE':sourcePending?'PENDING · NATIVE ACK':dirty?'DRAFT · NOT APPLIED':r.mode==='NONE'?'UNPATCHED · SILENT':'LIVE · NATIVE ACK'; - stage.dataset.state=!s.ready?'offline':sourcePending?'draft':dirty?'draft':r.mode==='NONE'?'offline':'live'; + const verified=new Set(portList(s).map(p=>p.port)); + const validInput=r.mode==='NONE'|| + (r.mode==='MONO'&&verified.has(r.left)&&r.right===-1)|| + (r.mode==='STEREO'&&r.left!==r.right&&verified.has(r.left)&&verified.has(r.right)); + const acceptedValid=!accepted||accepted.mode==='NONE'|| + (accepted.mode==='MONO'&&verified.has(accepted.left)&&accepted.right===-1)|| + (accepted.mode==='STEREO'&&accepted.left!==accepted.right&&verified.has(accepted.left)&&verified.has(accepted.right)); + // Source is real hardware, processing M/ST is independent. A restored + // invalid legacy alias is NEVER 'ACK/LIVE', even after a native route ACK. + stage.textContent=!s.ready?'NO VERIFIED DEVICE': + sourcePending?'PENDING · NATIVE ACK': + (!validInput||!acceptedValid)?'INVALID PHYSICAL INPUT · RE-PATCH': + dirty?'DRAFT · NOT APPLIED':r.mode==='NONE'?'UNPATCHED · NO INPUT': + 'ROUTE ACK · PCM UNVERIFIED'; + stage.dataset.state=!s.ready?'offline':sourcePending||dirty?'draft': + (!validInput||!acceptedValid)?'invalid':r.mode==='NONE'?'offline':'ack'; // Four native AUX destinations are always visible, even when empty. // Render only after a topology change, never on meter telemetry. const slots=Array.from({length:4},(_,bus)=>{ @@ -4328,6 +5929,28 @@ if(info.textContent!==caption)info.textContent=caption; toolbar.querySelector('[data-mix-apply]').disabled=!isNative()||!s.ready||!!s.pending||(!overlay.hidden&&matrixDraft.size>0); for(const strip of mixer.querySelectorAll('.strip[data-strip]'))refreshStrip(strip,s); + // Read-only pinned MAIN route. Reattach on master DOM regeneration but + // do not alter its fader, meters, FX, callback or native router. + const master=mixer.querySelector('#masterLeft'); + if(master){ + let summary=master.querySelector('.arMainOutSummary'); + if(!summary){ + summary=node('div','arMainOutSummary'); + summary.setAttribute('aria-label','Accepted physical MAIN routing'); + const heading=node('span','arMainOutHeading','MAIN OUT · NATIVE'); + const output=node('button','arMainOutAction'); + output.type='button';output.dataset.mixPatch='output'; + output.dataset.master='1';output.title='Configure physical MAIN L/R (native ACK)'; + summary.append(heading,output); + master.querySelector('.master-ch-id')?.insertAdjacentElement('afterend',summary); + } + const output=summary.querySelector('.arMainOutAction'); + if(output){ + const next=outputLabel(s); + if(output.textContent!==next)output.textContent=next; + output.disabled=!isNative()||!s.ready; + } + } if(!overlay.hidden)refreshIO(); if(!sendEditor.hidden)drawSendEditor(); sofRefresh(s); @@ -4375,7 +5998,7 @@ const title=node('header','arIOQuickHeader'); const words=node('div',''); words.append(node('strong','','1 · INTERFACE INPUT → MIXER CHANNEL'), - node('small','','Choose a channel, mono/stereo source and actual driver input(s). STAGE → MUTE → APPLY.')); + node('small','','Choose one channel and one or two distinct verified capture pins. USE INPUT commits through native ACK.')); const jump=node('select','arIOJump'); jump.dataset.ioJump='1';jump.setAttribute('aria-label','Find mixer channel'); for(let i=0;i<10;i++){ @@ -4403,15 +6026,20 @@ for(let i=0;i<10;i++){ const r=channelState(s,i),accepted=s.acceptedRoute?.channels?.[i]; const row=node('div','arIOQuickRow');row.dataset.ioQuickRow=String(i); + row.hidden=i!==focusedInput; row.dataset.state=!s.ready?'offline':valueFor(r)!==valueFor(accepted)?'draft': r.mode==='NONE'?'empty':'live'; const identity=node('div','arIOQuickIdentity'); identity.append(node('strong','','CH '+String(i+1).padStart(2,'0')),node('small','',matrixLogicalName(i))); const mode=node('select','arIOQuickMode');mode.dataset.ioQuickMode='1'; mode.setAttribute('aria-label','CH '+(i+1)+' physical input type'); - for(const pair of [['NONE','NO INPUT'],['MONO','MONO'],['STEREO','STEREO'], + for(const pair of [['NONE','NO INPUT'],['MONO','MONO'],['STEREO','STEREO · 2 PINS'], ...(r.mode==='BUS'?[['BUS','INTERNAL BUS']]:[])]){ - const option=node('option','',pair[1]);option.value=pair[0];option.selected=r.mode===pair[0];mode.appendChild(option); + const option=node('option','',pair[1]);option.value=pair[0];option.selected=r.mode===pair[0]; + // An accepted legacy invalid stereo route must remain inspectable, + // but new STEREO selection requires two distinct enabled driver pins. + if(pair[0]==='STEREO'&&verified.length<2&&r.mode!=='STEREO')option.disabled=true; + mode.appendChild(option); } const left=sourceSelect(i,'left',r.left),right=sourceSelect(i,'right',r.right); left.disabled=!hardwareReady(s)||r.mode==='NONE'||r.mode==='BUS'; @@ -4421,12 +6049,23 @@ const stage=node('button','btn-180 arIOQuickStage','USE INPUT'); stage.dataset.ioQuickStage='1';stage.type='button'; stage.disabled=!hardwareReady(s)||r.mode==='BUS'; - action.append(stage,node('small','arIOQuickState',r.mode==='BUS'?'INTERNAL BUS': + const stereoInvalid=r.mode==='STEREO'&&(!verified.some(p=>p.port===r.left)|| + !verified.some(p=>p.port===r.right)||r.left===r.right); + if(stereoInvalid){ + row.dataset.state='invalid'; + // On a one-pin device, the accepted legacy stereo L=R route cannot + // be usable stereo. Offer ONE explicit native-safe MONO correction. + if(verified.length===1&&verified[0].port===r.left){ + stage.textContent='FIX AS MONO';stage.dataset.ioQuickFix='1'; + } + } + action.append(stage,node('small','arIOQuickState',stereoInvalid? + 'INVALID STEREO · SELECT DISTINCT L/R':r.mode==='BUS'?'INTERNAL BUS': !s.ready?'NO DEVICE':row.dataset.state==='draft'?'DRAFT · NOT LIVE': - row.dataset.state==='live'?'LIVE · ACK':'UNPATCHED')); + row.dataset.state==='live'?'ROUTE ACK · CHECK PCM':'UNPATCHED')); row.append(identity,mode,left,right,action);section.appendChild(row); } - section.appendChild(node('p','arIOQuickFooter','Select verified inputs, click USE INPUT. Native routing handles any required safe mute, ACK and re-arm automatically.')); + section.appendChild(node('p','arIOQuickFooter','ONE ACTION: USE INPUT → native safe route/ACK. No input PCM? Send playback into the selected recording endpoint, then check SIGNAL CHECK.')); return section; } function stageQuickInput(button){ @@ -4434,7 +6073,8 @@ const s=route(),pins=new Set(matrixPorts(s,'inputs')); if(!row||!Number.isInteger(channel)||channel<0||channel>=10||!hardwareReady(s)) return matrixSay('Choose an active driver and wait for any previous APPLY.'); - const mode=row.querySelector('[data-io-quick-mode]').value, + const mode=button.dataset.ioQuickFix==='1'?'MONO': + row.querySelector('[data-io-quick-mode]').value, left=Number(row.querySelector('[data-io-quick-pin="left"]').value), right=Number(row.querySelector('[data-io-quick-pin="right"]').value); if(mode==='MONO'&&!pins.has(left))return matrixSay('CH '+(channel+1)+' · choose a valid mono input.'); @@ -4856,7 +6496,7 @@ hidden.value=d.backend;panel.appendChild(hidden); } const same=deviceSameEndpoint(d),advanced=node('details','arIODeviceAdvanced'); - advanced.appendChild(node('summary','','BUFFER / SAMPLE RATE / HARDWARE PIN ENABLE')); + advanced.appendChild(node('summary','','ADVANCED · BUFFER / SAMPLE RATE')); const fields=node('div','arIODeviceFields'); const rateOpts=[[0,'AUTO · driver default']],bufferOpts=[[0,'AUTO · driver default']]; if(same){ @@ -4871,6 +6511,12 @@ deviceSelect('arIODeviceBuffer',d.bufferSize,bufferOpts,deviceBusy||!isNative()))); advanced.appendChild(fields); const pins=node('div','arIODevicePins'); + const pinHeading=node('div','arIOPinHeading'); + const enabledCount=Array.isArray(d.enabledInputs)?d.enabledInputs.length:0; + pinHeading.append(node('strong','','HARDWARE PORTS · ENABLE INPUTS / OUTPUTS'), + node('span','',enabledCount+' capture pin(s) selected · '+(enabledCount<2? + 'MONO ONLY until a second distinct input is enabled':'MONO / STEREO PAIRS POSSIBLE'))); + panel.appendChild(pinHeading); for(const [direction,names,selectedPins] of [ ['INPUT',same?a.inputNames:[],d.enabledInputs], ['OUTPUT',same?a.outputNames:[],d.enabledOutputs]]){ @@ -4890,7 +6536,9 @@ }); pins.appendChild(side); } - advanced.appendChild(pins);panel.appendChild(advanced); + // Input/output pin enabling is a BASIC step, not an advanced matrix. + // The original native device draft/ACK path remains unchanged. + panel.appendChild(pins);panel.appendChild(advanced); } const actions=node('div','arIODeviceActions'); const refresh=node('button','btn-180 arIODeviceRefresh','REFRESH DEVICES'); @@ -4910,9 +6558,18 @@ devicePinNextStep())); panel.appendChild(actions);body.appendChild(panel); - const matrixSection=node('section','arIODevicePatchMatrix'); - const heading=node('div','arIODeviceMatrixHeading'); - heading.appendChild(node('strong','','AUDIO I/O · REAL PORT MATRIX')); + const matrixSection=node('details','arIODevicePatchMatrix'); + matrixSection.open=deviceMatrixOpen; + matrixSection.addEventListener('toggle',()=>{ + if(deviceMatrixOpen!==matrixSection.open){ + deviceMatrixOpen=matrixSection.open; + // Expensive crosspoints are constructed on demand, never just hidden + // behind CSS while a 12Hz native readback refreshes the device panel. + lastSignature='';refreshIO(); + } + }); + const heading=node('summary','arIODeviceMatrixHeading'); + heading.appendChild(node('strong','','ADVANCED · HARDWARE PORT MATRIX (OPTIONAL)')); const tabs=node('div','arIODeviceMatrixSwitch'); for(const [value,label] of [['inputs','INPUTS'],['outputs','OUTPUTS']]){ const b=node('button','arIODeviceMatrixTab',label);b.type='button'; @@ -4921,6 +6578,12 @@ tabs.appendChild(b); } heading.appendChild(tabs);matrixSection.appendChild(heading); + if(!deviceMatrixOpen){ + matrixSection.appendChild(node('p','arIODeviceMatrixEmpty', + 'Optional engineering crosspoints. Open only for advanced pin patching.')); + body.appendChild(matrixSection); + return; + } const live=!!d&&deviceSameEndpoint(d)&&a.authorized!==false; const s=route(); if(deviceMatrixWaitEpoch!==null&&s.epoch!==deviceMatrixWaitEpoch&&s.ready&&s.active) @@ -4961,7 +6624,10 @@ }); overlay.dataset.activeTab=ioTab; const matrixInDevice=ioTab==='device'&&deviceSameEndpoint(deviceDraft)&&hardwareReady(s); - overlay.querySelector('[data-mix-apply]').hidden=ioTab==='device'; + overlay.querySelector('[data-mix-apply]').hidden=ioTab==='device'|| + (ioTab==='inputs'&&!advancedMatrixOpen); + overlay.querySelector('[data-mix-apply]').textContent= + ioTab==='outputs'?'APPLY MAIN OUT':'APPLY ADVANCED'; overlay.querySelector('[data-io-revert]').hidden=ioTab==='device'&&!matrixInDevice; overlay.querySelector('[data-io-internal]').hidden=ioTab==='device'; overlay.querySelector('[data-io-device-apply]').hidden=ioTab!=='device'; @@ -4987,6 +6653,8 @@ if(previous)advancedMatrixOpen=previous.open; const previousDirect=body.querySelector('.arIODeviceDirectMatrix'); if(previousDirect)directMatrixOpen=previousDirect.open; + const previousHardware=body.querySelector('.arIODevicePatchMatrix'); + if(previousHardware)deviceMatrixOpen=previousHardware.open; body.replaceChildren(); if(ioTab!=='device'){ const identity=node('div','arIOHardwareHeader'); @@ -5002,10 +6670,43 @@ body.appendChild(makeQuickInputs(s)); const advanced=node('details','arIOAdvancedMatrix'); advanced.open=advancedMatrixOpen; - advanced.appendChild(node('summary','','ADVANCED M / L / R CROSSPOINT · SAME NATIVE ROUTING')); + advanced.addEventListener('toggle',()=>{ + advancedMatrixOpen=advanced.open; + overlay.querySelector('[data-mix-apply]').hidden=!advanced.open; + }); + advanced.appendChild(node('summary','','ADVANCED · MANUAL INPUT CROSSPOINTS')); advanced.appendChild(makeMatrix(s,ioTab)); body.appendChild(advanced); - }else body.appendChild(makeMatrix(s,ioTab)); + }else{ + // MAIN Left/Right must be visible before the engineering matrix. + // The same __arMixStageMainOutputs owns both paths. + const simple=node('section','arIOSimpleMain'); + simple.append(node('strong','','MAIN OUTPUT · STEREO PAIR'), + node('p','','Select two different enabled hardware outputs. APPLY OUTPUT publishes native routing; no browser sound is generated.')); + const outputPorts=matrixPorts(s,'outputs'); + const accepted=s.mainOutputs?.length===2?s.mainOutputs:[]; + const picked=s.draftMainOutputs?.length===2?s.draftMainOutputs:accepted; + const pickers=node('div','arIOSimpleMainRow'); + for(let side=0;side<2;side++){ + const label=node('label','arIOSimpleMainField'); + label.append(node('span','',side===0?'MAIN LEFT':'MAIN RIGHT')); + const select=node('select','arIOMainOutput');select.dataset.side=String(side); + const empty=node('option','','Choose verified output…');empty.value='-1';select.append(empty); + for(const port of outputPorts){ + const opt=node('option','','HW OUT '+(port+1));opt.value=String(port); + opt.selected=port===picked[side];select.appendChild(opt); + } + select.disabled=!hardwareReady(s)||s.pending||outputPorts.length<2; + label.append(select);pickers.append(label); + } + simple.append(pickers); + body.append(simple); + const advanced=node('details','arIOAdvancedMatrix'); + advanced.open=advancedMatrixOpen; + advanced.append(node('summary','','ADVANCED · OUTPUT CROSSPOINTS / MONITOR')); + advanced.append(makeMatrix(s,ioTab)); + body.append(advanced); + } } if(ioTab==='inputs'){ body.appendChild(node('p','arIOHint','MAONO PS22 virtual inputs appear here ONLY if its selected driver enumerates them as capture ports. Configure MAONO Routing Center and select the appropriate PS22 ASIO/recording endpoint in DEVICE / DRIVER. Separate Windows capture endpoints cannot be silently combined into one device. Processing MONO/STEREO is independent of physical source mode.')); @@ -5043,26 +6744,9 @@ body.appendChild(node('p','arIOHint','LIVE MONITOR: '+ (monitorLive.length===2?'HW '+(monitorLive[0]+1)+'/'+(monitorLive[1]+1):'DISABLED')+ ' · Independent POST-fader mix; all changes require MUTE → APPLY → ACK.')); - const details=node('details','arIOQuickMap'); - details.appendChild(node('summary','','QUICK OUTPUT SELECTION · ACCESSIBLE ALTERNATIVE')); - const accepted=s.mainOutputs?.length===2?s.mainOutputs:[]; - const draft=s.draftMainOutputs?.length===2?s.draftMainOutputs:accepted; - const ports=matrixPorts(s,'outputs'); - for(const [i,label] of ['MAIN LEFT','MAIN RIGHT'].entries()){ - const row=node('label','arIOOutputRow'); - const selector=node('select','arIOMainOutput'); - selector.dataset.side=String(i); - selector.setAttribute('aria-label',label+' destination'); - for(const p of ports){ - const option=node('option','','HW OUT '+(p+1)); - option.value=String(p);option.selected=p===draft[i];selector.appendChild(option); - } - selector.disabled=!hardwareReady(s)||ports.length<2; - row.append(node('strong','',label),selector);details.appendChild(row); - } - body.appendChild(details); - body.appendChild(node('p','arIOHint','LIVE MAIN: '+(accepted.length===2?'HW '+(accepted[0]+1)+'/'+(accepted[1]+1):'UNAVAILABLE')+ - ' · Only native-ACKed MAIN/MONITOR pairs can carry sound. AUX1–4 are internal stereo FX returns, not physical output sockets.')); + const acknowledged=s.mainOutputs?.length===2?s.mainOutputs:[]; + body.appendChild(node('p','arIOHint','NATIVE MAIN: '+(acknowledged.length===2?'HW '+(acknowledged[0]+1)+' / '+(acknowledged[1]+1):'UNAVAILABLE')+ + ' · Selection is DRAFT until native APPLY/ACK. AUX1–4 are internal FX returns, not hardware ports.')); }else{ renderCustomDevice(body); } @@ -5111,6 +6795,7 @@ } if(e.target.matches('[data-io-jump]')){ focusedInput=Number(e.target.value); + lastSignature='';refreshIO(); overlay.querySelector('[data-io-quick-row="'+focusedInput+'"]')?.scrollIntoView({block:'nearest'}); return; } @@ -5176,6 +6861,7 @@ if(!route().ready)openIO('device'); else openSourceChooser(index); } else if(step==='fx'){ + // The existing FX-only engineering layer remains an optional inspector. setMode('FX'); if(typeof chooseChannel==='function')chooseChannel(index); strip?.querySelector('.rack')?.scrollIntoView?.({block:'nearest',inline:'nearest'}); @@ -5349,6 +7035,7 @@ e.preventDefault();e.stopImmediatePropagation(); const strip=b.closest('[data-strip]'),channel=Number(strip?.dataset.strip)||0; if(b.dataset.mixPatch==='input')openIO('inputs',channel); + else if(b.dataset.mixPatch==='output')openIO('outputs',channel); else window.__arMixOpenChannelPatch?.(channel,b.dataset.mixPatch); return; } @@ -5536,7 +7223,8 @@ closeSendEditor(); } },true); - setMode('FX'); + // The ACTUAL M4 WebView2 mixer now opens as one integrated operator console. + setMode('CONSOLE'); })(); + diff --git a/CMakeLists.txt b/CMakeLists.txt index c169f8269..dcec36a1f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,9 +17,16 @@ juce_add_gui_app(ARMixConsole NEEDS_CURL FALSE) juce_add_binary_data(ARMixAssets SOURCES - web/index.html web/styles.css web/plugin-ui.css web/app.js web/plugin-ui.js web/bridge.js web/monitor.js web/mixer-io.js web/mixer-io.css web/mixer-layout.js web/mixer-layout.css web/assets/audio-interface.svg) + web/index.html web/styles.css web/plugin-ui.css web/app.js web/plugin-ui.js web/bridge.js web/monitor.js web/mixer-io.js web/mixer-io.css web/mixer-layout.js web/mixer-layout.css web/assets/audio-interface.svg + web/hardware-keys.js + web/assets/fader-silver2.png + web/assets/faders/FADER-ARI-SILVER.png + web/assets/faders/FADER-ARI-ROSEGOLD.png + web/assets/faders/FADER-ARI-GOLD.png + web/assets/pan/PAN-SLIDER.png + web/assets/knob-ICON.svg) -target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/VstOrbitController.h engine/core/MixerRoutingPlan.h engine/core/ChannelRoutingContract.h engine/core/ChannelSendPlan.h engine/core/AuxBusPlan.h engine/core/PreparedMixerBlock.h engine/core/MasterOutputMonoPolicy.h engine/core/LiveChannelFxGraph.h engine/core/PreparedNativeMixerSession.h engine/core/NativeDryRouteCommand.h engine/core/RealtimeRoutePublisher.h engine/device/LiveInputPortRegistry.h src/LiveDryRoutingLab.h engine/core/OrbitPhase.h engine/core/OrbitControlPolicy.h engine/core/OrbitMotion.h engine/core/OrbitDistanceMapping.h engine/core/DearVrPolarPolicy.h src/PluginCatalog.h src/FactoryFxRegistry.h src/PluginVault.h src/PortableWorkspace.h src/StudioBackup.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/NativeShowSchema.h src/NativeDryShowRecall.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/core/CallbackCadenceEvidence.h engine/diagnostics/CrackleEvidenceWindow.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h engine/device/PeriodCapabilityEvidence.h engine/device/SessionLifecycle.h engine/device/WasapiCapabilityProbe.h engine/device/JuceIndependentClockDevice.h engine/device/LiveSecondaryOutputDevice.h engine/core/LiveOutputRouteGate.h engine/device/ClockBridgeSizing.h engine/device/IndependentStreamFormatFence.h engine/device/DirectRestoreBackoff.h engine/device/IndependentStreamWatchdog.h engine/device/BridgeContinuityGate.h engine/device/EndpointIdentityPolicy.h engine/device/WasapiEndpointIdentityGuard.h engine/device/AsioStartupPolicy.h engine/device/AsioPriorityDeviceManager.h engine/device/JuceActivePortSnapshot.h engine/device/AsioRegistrationPolicy.h engine/device/AsioRegistryIdentityProbe.h engine/device/DirectRouteFence.h) +target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/VstOrbitController.h engine/core/MixerRoutingPlan.h engine/core/ChannelRoutingContract.h engine/core/ChannelSendPlan.h engine/core/AuxBusPlan.h engine/core/PreparedMixerBlock.h engine/core/MasterOutputMonoPolicy.h engine/core/LiveChannelFxGraph.h engine/core/NativeDryRouteCommand.h engine/core/RealtimeRoutePublisher.h engine/device/LiveInputPortRegistry.h src/LiveDryRoutingLab.h engine/core/OrbitPhase.h engine/core/OrbitControlPolicy.h engine/core/OrbitMotion.h engine/core/OrbitDistanceMapping.h engine/core/DearVrPolarPolicy.h src/PluginCatalog.h src/FactoryFxRegistry.h src/PluginVault.h src/PortableWorkspace.h src/StudioBackup.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/NativeShowSchema.h src/NativeDryShowRecall.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/core/CallbackCadenceEvidence.h engine/diagnostics/CrackleEvidenceWindow.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h engine/device/PeriodCapabilityEvidence.h engine/device/SessionLifecycle.h engine/device/WasapiCapabilityProbe.h engine/device/JuceIndependentClockDevice.h engine/device/LiveSecondaryOutputDevice.h engine/core/LiveOutputRouteGate.h engine/core/NativeRenderAuthority.h engine/device/ClockBridgeSizing.h engine/device/IndependentStreamFormatFence.h engine/device/DirectRestoreBackoff.h engine/device/IndependentStreamWatchdog.h engine/device/BridgeContinuityGate.h engine/device/EndpointIdentityPolicy.h engine/device/WasapiEndpointIdentityGuard.h engine/device/AsioStartupPolicy.h engine/device/AsioPriorityDeviceManager.h engine/device/JuceActivePortSnapshot.h engine/device/AsioRegistrationPolicy.h engine/device/AsioRegistryIdentityProbe.h engine/device/DirectRouteFence.h) target_compile_definitions(ARMixConsole PRIVATE JUCE_WEB_BROWSER=1 JUCE_USE_WIN_WEBVIEW2=1 diff --git a/docs/CONSOLE_BRIDGE_INTEGRATION_CONTRACT_V6.md b/docs/CONSOLE_BRIDGE_INTEGRATION_CONTRACT_V6.md index 2fddeb837..09eecbbb7 100644 --- a/docs/CONSOLE_BRIDGE_INTEGRATION_CONTRACT_V6.md +++ b/docs/CONSOLE_BRIDGE_INTEGRATION_CONTRACT_V6.md @@ -8,7 +8,7 @@ This document describes **implemented integration types and executable PCM/readb - \`tests/console_native_integration_test.cpp\` renders actual native offline PCM for IN1→CH7, IN2→CH2, sends to MONITOR, Group Selected with exclusive primary OUT, parallel wet FX Return, stale-device/invalid-pin rollback and mute. The test refuses to call this offline graph physically LIVE. ## Fields (target UI serialization) -All \`ChannelId\`, destination IDs and request IDs are decimal **strings** in JS (64-bit native identity must not be downcast to Number). Only version 6 represents these roles. Sample: +**Wire synchronization v6 (integration patch):** `ChannelId` and destination IDs are canonical unsigned **decimal strings**, never JS Number; `requestId` is a bounded printable **opaque string** per WebView session (e.g. `gui-live:41`) echoed unchanged by ACK, not a native integer or a global monotonically increasing counter. `device.epoch`, `graph.revision` and roster revisions are canonical decimal **strings** on GUI #271; native must preserve all uint64 bits and GUI compares with BigInt. Only v6 represents these roles. Sample: \`\`\`json { "schemaVersion": 6, @@ -35,7 +35,7 @@ All \`ChannelId\`, destination IDs and request IDs are decimal **strings** in JS \`\`\` The snippet is **illustrative**, not evidence that physical INPUT 1 is bound to ChannelId 7. A device callback pin number is not a sparse Windows hardware pin ID. The native source/physical-output owner must supply separate verified \`sourceBinding\` and actual \`OUTPUT ARMED\` readback. No fallback to IN1 or mock data if missing. -Intent envelope: \`{requestId,deviceEpoch,baseGraphRevision,baseRosterRevision,operation,targetChannelId}\`. A single native writer should reject stale epoch/revision, a previously completed duplicate ID and unsupported operations, then dispatch an existing native graph edit. ACK reports the same requestId, accepted/rejected, **current accepted** revisions and precise reason. An accepted graph **does not** imply physically audible LIVE: a full-fidelity production callback plus verified device/output gate is needed. +Intent envelope: `{requestId,deviceEpoch,baseRevision,baseRosterRevision,op,targetChannelId,payload}` as currently emitted by GUI #271. Native maps `baseRevision` to the internal `baseGraphRevision`, checks exact device epoch and accepted revisions, canonical decimal ChannelIds, and validates the operation against **runtime native supportedOps**, not the UI fixture. A single native writer maintains a **bounded recent completed-ID cache** (not an arbitrary numerical sequence comparator) across editor reconnects and rejects duplicate IDs, stale epoch/revision and unsupported operations before dispatching an existing accepted native graph edit. This adapter is control-plane *preflight* and does not yet instantiate that native writer. ACK reports the same requestId, accepted/rejected, **current accepted** revisions and precise reason. An accepted graph **does not** imply physically audible LIVE: a full-fidelity production callback plus verified device/output gate is needed. ## Invariants and merge gate 1. On rejected native intent, the accepted graph revision, source bindings and PCM remain unchanged. Never send an optimistic UI 'LIVE'. @@ -45,3 +45,9 @@ Intent envelope: \`{requestId,deviceEpoch,baseGraphRevision,baseRosterRevision,o 5. ENGINE owns adding source/FX readback from the native accepted snapshot in #266. GUI owns serialization/rendering in #268. Integration test owner does not edit those files. **Scope note:** This is one integration prerequisite, not the full Universal Live Console milestone. Do not merge this test as a claim that CH11, Group or FX Return have shipped. + +## Wire identity / duplicate ACK regression (2026-11-01) +The integration C++ test now proves an opaque `requestId` is echoed unchanged in both accepted and rejected replies, previously completed requests are rejected even across multiple editor IDs, a new editor restarting from sequence 1 is permitted, invalid control characters/overlong tokens are rejected, and native uint64 ChannelId strings reject overflow, leading zero and UI-fixture aliases. Snapshot projection refuses a JS-unsafe epoch/revision. The actual native WebView command dispatcher in ENGINE #266 must implement this v6 mapping and ACK/replay; the existence of the C++ test is not evidence of production bridge or physical sound. + +## Serialization-ready accepted readback (no fake physical LIVE) +`toConsoleWireReadbackV6` converts the accepted native revision to decimal-string tokens and role/format text values expected by GUI #271: INPUT, GROUP, FX_RETURN, MONITOR, MAIN; MONO/STEREO. Golden C++ tests now include >2^53 numeric preservation. This helper is a **control-thread DTO** only. It neither emits JUCE JSON nor supplies actual device pins, VST3 state, callback ownership or hardware sound, which remain ENGINE #266's integration responsibility. diff --git a/docs/CONSOLE_V6_FAT_EVIDENCE_GATE_20261101.md b/docs/CONSOLE_V6_FAT_EVIDENCE_GATE_20261101.md new file mode 100644 index 000000000..4e0bfd99b --- /dev/null +++ b/docs/CONSOLE_V6_FAT_EVIDENCE_GATE_20261101.md @@ -0,0 +1,52 @@ +# ArSonMix v6 — integration/FAT evidence gate +2026-11-01. Owns integration evidence only. Coordination: #192, ENGINE PR #266, GUI issue #268, hardware blocker #15. Source authority: docs/RELEASE_TRAIN_UNIVERSAL_CONSOLE_V7_20261101.md + docs/workstreams/INTEGRATION_RELEASE_DELIVERY_V7.md (v6 safety retained). + +## New validation +The offline CLI scripts/console_v6_fat_gate.mjs has three modes: +- node scripts/console_v6_fat_gate.mjs trace NATIVE_EVENTS.json +- node scripts/console_v6_fat_gate.mjs pcm NATIVE_PCM.json +- node scripts/console_v6_fat_gate.mjs release RELEASE_RECORD.json dist +- node --test tests/console_v6_fat_gate_test.mjs + +Trace schema v2: `arsonmix.console-v6.acceptance-trace.v2` validates actual native WebView `arMixConsoleSnapshot`, `arMixConsoleIntent`, `arMixConsoleAck` event envelopes, `schemaVersion:6`, decimal-string uint64 device epoch, accepted graph+roster revisions, ChannelId, native physical pin masks, explicit outputArmed, supportedOps, and telemetry. Intent requires unique session-scoped opaque `requestId`, `baseGraphRevision`, `baseRosterRevision`, `operation`, `targetChannelId`, typed `payload`. ACK must be followed by matching full accepted snapshot; stale/replayed/unsupported intents and invalid duplicated stereo physical pins fail closed. Synthetic self-tests use `provenance.kind=SYNTHETIC`; native exports require explicit source SHA and producer marker, still subject to independent review. **A structurally valid trace does not prove actual JUCE callback or clean physical PCM.** Existing M4 physical OUTPUT can be ARMED with `productionCallbackLive:false`: this is a truthful legacy-output readback, NOT the new universal callback. Never falsify the device output flag to make a v6 fixture pass. + +v7 G0 blockers: Native #272 is a control-plane readback without a real JUCE emitter; ENGINE #266 must install the publisher and produce source-owned JSON. GUI #271 still sends resettable `requestId=String(++requestSeq)`; GUI owner must make it unique per WebView session. FAT #270 is NOT G0-complete until source-produced trace and both consumers agree on one SHA. #276 Windows First Sound is staging ONLY, never user UAT. + +PCM schema: arsonmix.console-v6.pcm-evidence.v1. Four numeric sample cases: independent_inputs maps distinct IN1->CH7 and IN2->CH2; group_fx_return checks serial GROUP gain, parallel wet-only FX Return, no double-dry and separate GROUP/return mutes; monitor_isolation checks separate physical destinations and MONITOR mute not changing MAIN; physical_mute checks MAIN PCM silence. This checks supplied numerical arrays, NOT their authenticity, plugin vendor identity, VST editor, Show round-trip, real output DAC, or audible cleanliness. The self-tests are synthetic and are not evidence from the actual production callback. ENGINE must export trace/PCM from the genuine production native renderer and include actual device epoch, output pin list, and source SHA; coordinate any wire format changes with both owners in #192. Do not add JS DSP or a second native audio graph. + +Release intake requires exact 40-character source SHA, both successful native Windows and Chromium CI rows at exactly that SHA, normal Windows verifier + CTest + Playwright records, actual packaged EXE SHA-256 checked against BUILD_PROVENANCE.json/sourceCommit, and separate ZIP/trace/PCM hashes. The validator does NOT fetch CI run results or ZIP bytes: review Actions links, artifact ZIP hash and WebView2/PE findings independently. Existing scripts/package_native_windows.ps1 and scripts/verify_native_windows_artifact.ps1 remain authoritative for binary packaging. The intake also requires #15 wired 0FX physical run for >=1800 seconds with actual backend/rate/buffer/pins and OUTPUT_ONLY_TONE, CAPTURE_ONLY, DRY_THROUGH reports, full report SHA and human witness. This is an operator evidence record, **not** physical certification; even a complete record returns certified:false and ACOUSTIC_REVIEW_REQUIRED. + +## Reconciled audit (not rolling assertions) +| Exact tree SHA | Native CI | Chromium | Artifact | Physical | +| --- | --- | --- | --- | --- | +| bb6dff6b42158ba2db4666e0def54bb89abda4f8 (main baseline) | PASS [41263965810](https://github.com/masarray/arsonmix/actions/runs/41263965810) | PASS [41263965813](https://github.com/masarray/arsonmix/actions/runs/41263965813) | Windows 10CH/4AUX FAT candidate; NOT universal | #15 BLOCKED | +| b911c07260388448ab3bfc33084ea114773fe487 (main docs) | No observed exact-head native run at audit | No observed exact-head UI run at audit | Cannot relabel bb6dff6 EXE as newer SHA | #15 BLOCKED | +| 2bbf9f08b5495c3ad61b7d8d0ec5190177bdb55c (engine PR #266) | PASS [41252951831](https://github.com/masarray/arsonmix/actions/runs/41252951831), prepared graph only | Not combined-tree integration | No production callback cutover | #15 BLOCKED | + +## Release stop rules +Do not promote until ENGINE migrates occupied CH1 vendor VST/editor/Orbit, other channels, AUX, MAIN/MONITOR, secondary output and Show to ONE actual callback; real CH11, serial Group, wet FX Return and independent monitor pass native PCM + rollback; GUI reflects ONLY accepted state; one combined exact-head Windows CTest and Chromium+Playwright build and verified Windows GUI artifact pass; physical user+engineer listen to 0FX wired output >=30min without crackle, follow with multiFX/Show/device hotplug and record reports. Do not confuse capture discontinuity or callback timing with render underrun. Never claim 0ms physical latency or sound clean from GitHub CI. + + +## Field FAT milestone — packaged collector +A verified Windows FAT artifact includes `ArSonMix-Hardware-FAT.ps1` bound to the package manifest by `fatCollectorSha256`; the release verifier also checks its ZIP entry bytes. `Verify`, `Start`, `Stop`, and `Summary` actions record actual operator-timed OUTPUT_ONLY_TONE, CAPTURE_ONLY and >=30-minute wired DRY_THROUGH_0FX into `FAT_RUNS.json`, with diagnostic report SHA-256; `FAT_SUMMARY.json` always sets `hardwareCertified=false`. This is a field record, not acoustic telemetry or an app-controlled audio test. Do not use old ZIPs without this built-in collector; their original FIRST SOUND guide still applies. All device/route/ARM control remains native and manual. The script never tries to load a VST, set a device or authorize output. + + +## G3 release evidence hardening — real files, one source SHA +The v7 \`release\` action now requires \`artifacts:{zip,nativeTrace,nativePcm,hardwareReport}\` as four safe **basenames** under the extracted local evidence directory, hashes **each real file**, compares their actual SHA-256 to \`artifactSha256\`, \`traceSha256\`, \`pcmSha256\` and \`hardware.fullReportSha256\`, and validates the EXE bytes against \`BUILD_PROVENANCE.json\`. ZIP magic is a fast sanity check only: \`scripts/verify_native_windows_artifact.ps1\` remains the independent full ZIP-entry and embedded BinaryData verifier. All provenance/CIs must refer to **the same exact source SHA**; GitHub workflow status itself still must be independently checked (this CLI does not call GitHub). + +The trace file MUST be schema v2 WebView native ACK/PCM state with \`provenance:{kind:"NATIVE_JUCE",sourceSha:"...",producer:"JUCE_WEBVIEW"}\`, and its last accepted native snapshot must advertise **actual** ChannelId production callback, vendor FX/Show/pin-admission, dynamic CH11+, GROUP, FX_RETURN, MONITOR, physically armed output, and live raw/MAIN/MONITOR telemetry. PCM JSON must have the existing four golden PCM cases plus \`provenance:{kind:"NATIVE_JUCE",sourceSha:"...",producer:"JUCE_CALLBACK"}\`. For any missing producer field, **G3 fails closed until ENGINE actually exports it**: never fill the gap with fabricated or manually edited data. An attacker could forge text labels or binary fixture files; therefore native CTest, source-checked real JUCE publisher, Windows package verifier, CI run evidence, and independent human hardware FAT remain separate mandatory checks. The structural unit tests explicitly use fabricated fixture bytes and their expected final result is always \`certified:false\`. This script NEVER authorizes or starts a customer UAT. + + +## Mandatory #278 GUI authority gate +`scripts/check_pr278_console_authority.mjs` pins isolated approved #278 visual source `eda57f931ae3cc2872579df29cdf4e1486592b64` (study blob `1bbd9f50eefbb3c54d05d8e36e5afd3bd5e6d709`) **only as a visual reference**. The controlled integration tree must include its study HTML, not run demo DSP. `node scripts/check_console_puzzle.mjs --release` blocks universal production Console drift in top/bottom channel identity, one graphite chassis, BTN-180, equal-width pinned MAIN and native IN/OUT/FX/Cue/ACK. GUI #271 owns implementation. Passing this source gate is NOT screenshot parity, PCM or acoustic certification. + + +### PR #278 V8 — adaptive geometry (2 Nov 2026) +The newest isolated design study `eda57f931ae3cc2872579df29cdf4e1486592b64` adds density-aware bank capacity (Comfort 150px, Standard 125px, Compact 105px), corrected 32px rail budget and pinned MAIN at the same channel width. Folded Route, FX and Send children must be `display:none`, never clipped into 23px. Source authority gate now reports these as native GUI blockers; actual Chromium rendered geometry remains a separate test (`design-references/audition-mixer-study/visual_layout_audit_v8.py`). No simulated DSP from the reference enters the app. + + +### Joined hardware 1FX comparison recorder (3 Nov 2026) + +The native Windows FAT ZIP now includes a source+EXE hash-bound offline collector with a fourth explicit mode, `LIVE_THROUGH_1FX`, alongside OUTPUT_ONLY_TONE, CAPTURE_ONLY and DRY_THROUGH_0FX. The 1FX mode requires a **completed witnessed 1800-second wired 0FX baseline with full report** before starting. Its native GUI operator-reported VST3 name and count=1 are journalled, and the backend, rate, frames, capture/render endpoint names and ordered physical pins must exactly match the baseline. A second 1800-second wired 1FX run and separate full diagnostic report are required for the summary to become `EVIDENCE_READY_FOR_HUMAN_REVIEW`. The first mismatch is rejected before starting the timer. + +This is stricter than the legacy v6 automated release-intake minimum, which already requires 0FX issue #15 evidence. The new fourth-mode summary requirement is **field review evidence**; it neither changes the native PCM gate nor fabricates plugin telemetry, acoustic measurements, hardware certification or universal ChannelId readiness. The existing independent `console_v6_fat_gate.mjs` continues to return `certified:false`. diff --git a/docs/ENGINE_RUNTIME_AUTHORITY_20261103.md b/docs/ENGINE_RUNTIME_AUTHORITY_20261103.md new file mode 100644 index 000000000..0b62f88f9 --- /dev/null +++ b/docs/ENGINE_RUNTIME_AUTHORITY_20261103.md @@ -0,0 +1,63 @@ +# ArSonMix — ONE production engine, GUI-directed ownership +Date: 2026-11-03. Status: **binding engine ownership map** (code-enforced for existing M4 callback, NOT universal live certification). + +## Only one runtime authority + +```text +PR #278 + #285 approved GUI workflow (reference only, not audio) + | +PR #271 web native renderer → ConsoleLiveBridgeV6 snapshot/intent/ACK + | + Native JUCE LiveAudioEngine + | + NativeRenderAuthority (one selector) + | | | + UNPATCHED ACCEPTED M4 DIAGNOSTIC + silence one real mixer test-only 0FX + | + LiveDryRoutingLab + LiveChannelFxGraph + PreparedMixerBlock + | + existing CH1 original VST/Orbit lease + AUX / MAIN / MONITOR + | + actual verified device pins +``` + +The `NativeRenderAuthority` is an explicit, fixed-cost callback selector. **There is no second simultaneously running mixer.** The former standalone stereo plugin dispatch inside the diagnostic-only remainder was unreachable and is deleted, not hidden behind another flag. An unpatched NORMAL route stays silent and cannot silently fall back to stereo CH1. + +## What is active, what is migration-only, what is test-only + +| Ownership | Modules | Decision | +| --- | --- | --- | +| **PRODUCTION, temporary compatibility** | `src/LiveAudioEngine.h`, `src/LiveDryRoutingLab.h`, `engine/core/LiveChannelFxGraph.h`, `engine/core/PreparedMixerBlock.h`, native CH1 VST/Orbit lease | KEEP until truly equivalent unified render; bugfixes only, no new competing features | +| **Future canonical ChannelId engine (prepared, not yet production)** | `DynamicChannelRoster`, `DynamicPreparedMixerBlock`, `DynamicNativeSessionPublisher`, `DynamicChannelFxLeaseBank`, `UnifiedLegacyProductionAdmission`, `DynamicAcceptedSession` | KEEP as one migration target; **do not attach as a second callback** or advertise LIVE | +| **Compatibility translation** | `LegacyLiveGraphMigration`, accepted device epoch / actual port pin mapping | KEEP until cutover with exact PCM, VST/editor and Show parity; then retire in one controlled transaction | +| **Testing-only** | `PreparedNativeMixerSession.h`, dedicated offline dynamic test targets | No longer list testing-only session as shipped `ARMixConsole` source; keep its separate CTest target | +| **Diagnostics, no effect graph** | old stereo scratch path in `LiveAudioEngine`, diagnostic tone/capture, health and 0FX evidence | KEEP isolated with NO vendor plugin processing and NO production fallback | +| **Single non-RT worker** | `NativeShowSaveWorker` | KEEP Show I/O on worker, not on callback; no extra per-channel/per-plugin worker | + +## Stop rules — prevents return of mixed engines + +1. The approved reference GUI is the *workflow authority*. Native accepted snapshots, stable ChannelIds, real device pins and ACK remain the *data/PCM authority*. Never let JS or a browser mock own audio routing or create fake FX. +2. There is **one** `audioDeviceIOCallbackWithContext` production entry point and **one** selected render owner at any time. Do not run M4 and dynamic PCM, or duplicate native vendor VST3 instances. +3. New channels, Group, FX Return and WIRE must go into the **universal ChannelId graph**. No new business feature is allowed to extend fixed 10CH/M4 design, except fixes for actual physical audio reliability. +4. Freeze old plugin-feature experiments; preserve external #15 0FX crackle evidence and driver safety research (including draft #251). No destructive deletion or premature PR closure while hardware equivalence is unknown. +5. When universal graph passes real M4 migration/production gates, **remove** M4 callback selection, ordinal-as-identity adapters and legacy CH1 special cases in the **same integration PR**. The real diagnostic tone/capture remains a separate legitimate service, not a mixer. +6. Integration #270 alone certifies exact combined GUI/native SHA, Windows CTest/Chromium, VST/editor/Show parity and measured physical audio. Do not mark GUI as LIVE from screenshots or offline data. + +## Decommission gates (NOT met yet) + +- Real 10CH + 4AUX, MAIN/MONITOR, CH1 original vendor/Orbit/editor and Show state are rendered by the same accepted ChannelId graph. +- Normal continuous fader/MUTE/SOLO/SEND controls remain audible without mandatory device restart; no lost plugin tail or duplicated dry output. +- Native ACK/epoch/revision, output disarm/rearm and physical sparse port map are verified. +- Windows exact-SHA build/CTest and physical ASIO/WASAPI 0FX + 1FX FAT pass. + +**Result:** no obsolete active stereo plugin engine remains available from the diagnostic fallback; current M4 compatibility is intentionally quarantined and will be retired only when the unified engine demonstrably replaces it. + +## Reconciliation notice (2026-11-03) +ENGINE #266 is now the sole source branch after folding former #287. Cross-branch ownership, upstream drift, CI authority gate and the next real callback cutover are documented in [ENGINE_SINGLE_OWNER_HANDOFF_20261103.md](workstreams/ENGINE_SINGLE_OWNER_HANDOFF_20261103.md). The M1 experimental ZIP policy is historical; do not make another branch-specific Windows FAT producer without #270 integration ownership. + +## Single-owner Windows hardware FAT (2026-11-03) +ENGINE PR #266 alone can upload a 10CH/4AUX **experimental, unqualified** Windows GUI ZIP after exact SHA native compile, all CTests, PE32+ Windows GUI subsystem and embedded GUI/SHA verification. Former M4 branches no longer have a second artifact publication exception. This is physical first-sound evidence only; NOT a live universal ChannelId engine or joined new-GUI release. See the packaged `HARDWARE_FAT_GUIDE.md`. diff --git a/docs/FIRST_SOUND_FAT_QUICKSTART_20261101.md b/docs/FIRST_SOUND_FAT_QUICKSTART_20261101.md index baa97a730..86566177a 100644 --- a/docs/FIRST_SOUND_FAT_QUICKSTART_20261101.md +++ b/docs/FIRST_SOUND_FAT_QUICKSTART_20261101.md @@ -1,5 +1,5 @@ # ArSonMix — Windows First Sound / Hardware FAT -Date: 1 November 2026. Current production: **10 input channels + 4 AUX**, one JUCE callback, MAIN/MONITOR and native VST3. The experimental dynamic CH11/Group engine has **not** replaced the production callback. The outstanding 0FX hardware crackle issue is #15. This is a FAT **candidate**, not hardware certified or guaranteed zero physical latency. +Date: 1 November 2026. M1 hardware candidate addendum: 2 November 2026. Current production: **10 input channels + 4 AUX**, one JUCE callback, MAIN/MONITOR and native VST3. The experimental dynamic CH11/Group engine has **not** replaced the production callback. The outstanding 0FX hardware crackle issue is #15. This is a FAT **candidate**, not hardware certified or guaranteed zero physical latency. ## 1. Verify package Extract the complete Windows Actions ZIP to a writable folder. `BUILD_PROVENANCE.json` must show the same `sourceCommit` as the GitHub run; EXE SHA-256 must equal `exeSha256`. Keep `portable_mode.txt`, never delete an existing `Studio` workspace. The file is a Windows x64 JUCE GUI executable; Microsoft Edge WebView2 Runtime and the correct audio hardware driver are required. @@ -28,3 +28,37 @@ Send: (a) screenshot of active driver/rate/buffer/pins, (b) accepted CH01 patch **PASS is hardware-grounded:** correct MAIN source path, verified mute/fader control, no wrong-endpoint output, clean 0FX wired audio for >=30 minutes on the recorded device/rate/buffer, followed by real plugin testing. A green Windows CTest/Chromium CI is not a substitute. Historical full test matrix remains `docs/HARDWARE_FAT_GUI10_ENGINE_P012_20261027.md`. This packaged guide supersedes obsolete manual START AUDIO instructions. + +## 5. M1 candidate — structured physical acceptance (not an M5 universal graph) + +The **ArSonMix-ENGINE-10CH4AUX-EXPERIMENTAL-Hardware-FAT-Windows-x64** artifact comes from the **single canonical ENGINE #266 branch** (not the retired M4 branch) and is uploaded only if the exact PR SHA completes Windows compile, all CTests, packaging and ZIP/embedded-GUI SHA256 verification. Get the ZIP from the successful ENGINE #266 GitHub Actions run's **Artifacts** section. Extract, then compare `BUILD_PROVENANCE.json` `sourceCommit` against the exact successful run's SHA and the EXE file hash against `exeSha256`. A mismatch means STOP. A PR artifact is not a public stable release. The EXE preserves the existing **native M4 10CH + 4AUX** callback, not a live CH11/group universal engine. DO NOT apply an unqualified artifact on a live public-performance show. + +One real device, one verified I/O clock, wired monitoring, LOW output gain and initially **0 VST3**. Start at a supported buffer of 256 samples, then 128 and 64 only after the earlier stage has passed; document actual negotiated values, don't assume the driver honored the request. For each supported buffer: + +| Native check | Operator action and expected physical result | Hard fail / retain evidence | +|---|---|---| +| Unpatched startup | Launch without input patch; MAIN stays silent and unarmed | Any unexpected output/audio or wrong endpoint | +| Device isolation | Select real active ASIO or WASAPI endpoint; verify L/R physical pins, rate and epoch | Invalid pins, auto re-arm on hotplug, unexpected fallback | +| Real 0FX | Patch CH01 mic/line input, explicitly ARM; record 30-minute continuous wired output | Pops/crackle: Mark Crackle and Copy Full Report | +| Short-buffer gain | Move CH01 fader repeatedly and reverse while moving; listen for clicks, watch true meters | Zipper clicks, freezes, inconsistent physical gain | +| AUX gain/edge | Connect a validated SEND to AUX; change send and AUX return levels with effects bypassed | Silence despite accepted change, stale/reverted controls, double direct signal | +| Monitor isolation | If a separate hardware pair exists, enable MONITOR intentionally | MONITOR leaking to MAIN or shared hardware pair | +| Vendor/plugin | Only after 0FX clean, insert real VST3 and toggle bypass/editor | Stuck UI, plugin recreation, audio gap, FX state loss | +| Show lifecycle | Save and recall same route/plugin states, check output is never armed implicitly | Stale device epoch, missing FX, corrupt restoration | +| Safe shutdown | Stop/restart and unplug/replug device, reselect/ARM deliberately | Audio on unexpected pins, leaked resource or crash | + +**Required evidence**: download artifact name and exact 40-character SHA from `BUILD_PROVENANCE.json`; SHA256 of installed EXE; physical device name/driver/rate/buffer and enabled port mapping; 0FX duration; crackle report if any; one short video or screenshots demonstrating CH01, AUX, MONITOR and Show. The test passes only for the exact device and configuration tested, and never proves every VST3 or absolute crash-proof operation. + +### SHA authority for native PR builds +The Windows workflow explicitly checks out **`github.event.pull_request.head.sha`**, verifies it against `git rev-parse HEAD` **before** building, and packages the same `sourceCommit`. This avoids GitHub Actions' default transient PR merge commit being mislabelled as the ENGINE HEAD. If provenance SHA differs from the run's exact source SHA, **STOP**; do not start hardware FAT. The GUI and ENGINE on the *new integration branch* still require their own joined exact-SHA test before final UAT. + + +## Matched 0FX / 1FX physical FAT — experimental joined executable (3 Nov 2026) + +The packaged `ArSonMix-Hardware-FAT.ps1` collects human-observed evidence, never starts audio or validates acoustic quality by itself. From the **extracted verified Windows ZIP**, run `-Action Verify` first. Use the **same native-verified ASIO/WASAPI driver, device name, 48 kHz/other actual rate, buffer, physical input and output pins** for both runs; enter only what AUDIO SETUP / SIGNAL CHECK actually displays. Do not type illustrative sample values as if they were hardware readings. + +Complete `-Mode DRY_THROUGH_0FX` with all VST3 inserts removed, `-Wired`, low listening level, `-Action Start`, at least **1800 seconds**, then `-Action Stop -ReportPath "" -Result CLEAR/CRACKLE -Witness ""`. This baseline must have the full report, witness and a conclusive observation before starting 1FX. + +Next load **exactly one real native VST3** into the applicable audio channel, ensure it is active/not bypassed and the native audio route still matches. Use `-Action Start -Mode LIVE_THROUGH_1FX -FxCount 1 -Vst3Name "" -Wired` plus **identical** `-Backend`, `-SampleRate`, `-BufferFrames`, `-InputPins`, `-OutputPins`, `-CaptureEndpoint` and `-RenderEndpoint` as the 0FX run. The collector refuses to begin if any detail or the witnessed baseline is missing/mismatched. Run another **1800-second** wired observation, then `-Action Stop` with the new full diagnostic report and witness. Run `-Action Summary` to create `FAT_SUMMARY.json`. + +The existing OUTPUT_ONLY_TONE and CAPTURE_ONLY isolation runs are also required in the summary. `EVIDENCE_READY_FOR_HUMAN_REVIEW` requires all four modes and matching 0FX/1FX conditions. The VST3 name/count, audibility and crackle observations are **operator reports**, not measurements automatically obtained from the plugin or DAC. `hardwareCertified` and `physicalAudibilityVerifiedBySoftware` always remain **false**; issue #15 and GUI/ChannelId universal release blockers are not cleared by running the script. diff --git a/docs/M1_REALTIME_CORE_STABILIZATION_20261102.md b/docs/M1_REALTIME_CORE_STABILIZATION_20261102.md new file mode 100644 index 000000000..d21b30f21 --- /dev/null +++ b/docs/M1_REALTIME_CORE_STABILIZATION_20261102.md @@ -0,0 +1,27 @@ +# M1 — Realtime core stabilization (2026-11-02) + +**Stacked source**: ENGINE #266 at `40a059785993cc6a4bb593020bf9749de92746f9`. No competing DSP, native callback, GUI or worker per channel. + +This checkpoint repairs the Windows CTest AUX static/offline regression and corrects native fader/PAN de-zippering to remain **64 audio samples across variable callback frames** (4/16/32/12), including reverse direction. Existing live PRE/POST sends and AUX return faders retain their prepared 64-sample ramp; offline/no-live paths must not inherit old live AUX targets. All work uses fixed-size arrays and no new callback heap allocations. + +The existing `RealtimeRoutePublisher` owns bounded retirement. New tests hold a real leased reader across two graph publications, verify refusal when the queue is full, and verify all four prepared owners are reclaimed after the reader leaves. All tests run in the existing CTest executables with no additional CI matrix. + +**Runtime invariant:** `LiveAudioEngine::audioDeviceIOCallbackWithContext` is still M4 until the full CH1 external/Orbit owner, native vendor FX/editor/Show, physical input/output pins and monitor can migrate together. Never enable universal supportedOps or silently render the new graph alongside M4. Worker-only work belongs to existing control/Show-save processing, NOT the real-time callback. + +**Remaining M1 release gates:** pass exact-SHA Windows MSVC/CTest, integrate a single full-fidelity ChannelId callback with atomic admission and no FX loss, then qualify ASIO/WASAPI and zero-FX crackle on actual hardware. This change alone is **not M1 complete**, not UAT, not acoustic FAT. + +## Worker payload lifetime hardening +`NativeShowSaveWorker` validates Show IDs before reserving, releases snapshot/blob/closure memory immediately on start failure, and moves the completion closure rather than retaining a second copy after IO completion. The long-lived worker is reused; no new OS thread or realtime allocation has been introduced. Windows JUCE compilation and runtime verification are release gates. + +## Exact CI evidence and hardware artifact scope (revision 2) +Windows run `41479462759` compiled successfully but 52/54 CTests passed. The remaining two failures were analyzed and corrected together: +1. Native `setAuxSendGain` / `setAuxBusGain` is **one atomic automation plane** even without separate strip controls, as exercised by `dedicated_aux_bus_test.cpp`. The old conditional gate silenced actual physical AUX level edits. In the routing CTest, a newly built `PreparedMixerBlock` establishes fresh compiled defaults, while an already automated block retains its explicit target. +2. The graph-retirement test needed to count the rejected candidate's destructor too: 3 original accepted + 1 rejected + 1 newly accepted = **5 distinct prepared instances**. The lifetime test checks that saturation safely rejects and reader-owned graphs are not reclaimed early. + +This patch also authorizes **one** exact-branch `M1-EXPERIMENTAL` GitHub Actions artifact **only after** all CTests and package/provenance validation pass. This does not enable universal routing/CH11, promote stable release, or change hardware patch/ARM policy. The packaged FAT guide now includes explicit pass/fail cases for wired 0FX ASIO, AUX/monitor, state recall and hotplug. No parallel CI matrix or redundant always-on worker. + +## 2026-11-03 single production authority cleanup +Real-time callback now routes through the explicit `NativeRenderAuthority` decision. The no-longer-reachable legacy stereo FX processing code has been removed from the diagnostic-only path; this does not change accepted 10CH/4AUX production routing. `PreparedNativeMixerSession.h` remains tested but is no longer listed in the shipping GUI application target. See `docs/ENGINE_RUNTIME_AUTHORITY_20261103.md` for the decommission map and strict migration gates. + +## Ownership reconciliation — 2026-11-03 +M1 stabilization is folded into **ENGINE #266**; PR #287 is retired to avoid parallel production engine branches. Its existing Windows M1 experimental FAT artifact remains historical, NOT a universal UAT release. Future exact joined Windows artifact and UAT promotion are owned by integration #270. See `docs/workstreams/ENGINE_SINGLE_OWNER_HANDOFF_20261103.md`. diff --git a/docs/M5_UNIVERSAL_CHANNELID_VST3_LEASE_MIGRATION_20261101.md b/docs/M5_UNIVERSAL_CHANNELID_VST3_LEASE_MIGRATION_20261101.md new file mode 100644 index 000000000..7e52b2855 --- /dev/null +++ b/docs/M5_UNIVERSAL_CHANNELID_VST3_LEASE_MIGRATION_20261101.md @@ -0,0 +1,46 @@ +# M5 — Universal ChannelId / native VST3 lease migration + +**Scope:** ArSonMix is a realtime live-performance digital mixer, NOT a DAW arranger/editor. This milestone migrates the actual M4 per-channel vendor processor ownership model into a ChannelId-keyed native DSP graph. It is the required shared FX seam for real CH11+, Group and FX Return parity. It does **not** activate the old dry-only M3E #263 pilot in production. + +## Why + +Current shipped M4 supports native VST3 on fixed CH1..CH10 and four AUX lanes, with stateful FX instance identity, bypass fade and correct control-thread retirement. Prior M3E pilot could create a new Group native PCM but refused any existing VST3/AUX/MONITOR/Show. Replacing an accepted M4 mix with an FX-free graph would silently discard reverb and compressor state. This is unacceptable for live karaoke, podcast, streaming or stage use. + +Top global console contracts are consistent: +- Fender Studio Pro: Bus submixes, FX Channel return with independent sends, pre/post send choices, Group channel input fan-in, nested Bus and direct output routing. https://fenderstudiopromanual.fender.com/en/Content/Mixing_Topics/The_Console.htm +- Waves eMotion LV1: Channel and Group processing, separate Aux/FX/Monitor/MATRIX layers and physical routing patches. https://www.waves.com/emotion-lv1-tutorial-4-2-mixer-channels-groups-aux + +## Implemented M5 native architecture + +### `engine/core/DynamicChannelFxLeaseBank.h` +- A **stable ChannelId → M4 FX rack** map. Identities survive reordering and channel-bank viewport changes. Works for arbitrary dynamically admitted Mono/Stereo input, Group, and FX Return IDs; no CH10 borrowing. +- `captureLegacy`: imports each already-accepted M4 native vendor **FxInstance lease** using exact opaque `instanceId`, never a catalog-name substitute or processor recreation. The actual `juce::AudioProcessor`, parameters, binary state, internal delay/reverb tail, bypass envelope and MIDI scratch remain owned. +- `prepare`: one control-thread transaction preallocates and validates mapping, 8-insert bound, mono/stereo Node contract, stereo VST bus layout, missing lease, reused native processor in multiple simultaneous lanes, invalid device epoch or repeated ChannelId. Failed preparation leaves the previously accepted bank unchanged. +- `operator()(ChannelId,float*,float*,frames) noexcept`: callback dispatch is read-only, binary search by immutable ID with raw processor pointers, no `shared_ptr` copy, allocation, waiting, mutex, VST scan, new callback or dynamic catalog lookup. +- **Lifecycle requirement:** lease bank MUST be owned/retired by the SAME native prepared PCM publication/snapshot as its routing plan. A final owner must never disappear inside a callback. Two graphs sharing the same plugin may NOT render concurrently; existing `FxInstance::render` fail-closed atomic gate is an additional safety fence, not a dual-render design. + +### `src/LiveDryRoutingLab.h` +- `captureDynamicFxLeases(expectedEpoch,expectedRevision,ids,...)` now exposes exactly 10 input + 4 AUX M4 VST rack owners for native M5 conversion, from the actual publisher accepted revision. No device switching and no modification to the active M4 graph. Stale/invalid device epochs fail closed. + +### `tests/live_channel_fx_graph_test.cpp` +- Native JUCE `AudioProcessor::processBlock` through ONE `DynamicNativeSessionPublisher` PCM graph: **CH1 FX + CH11 FX → GROUP FX → MAIN** while CH11 also has a parallel POST SEND to an independent FX Return with its own processor. +- Proves an actual output sum with no doubled dry signal and correct -6 dB Group fader, opaque M4 instance token reuse after the old owner graph is retired, no audio-callback heap allocations, one native render, duplicate vendor instance rejection, and wrong-epoch output fail-silent. +- Reuses existing `ARMixLiveChannelFxTests` Windows MSVC/CTest executable; no separate CI matrix and no expensive external vendor plugins for deterministic tests. + +## Integration admission — do not skip + +1. Merge this bank only after exact-head native Windows CTest and test fixture pass. +2. Refactor M3E dynamic publisher to **own Bank alongside native prepared PCM**, so an epoch/revision ACK refers to the same routing + FX instance generation. No separate second render path. Use the M4 off-RT plugin editor/Show save-restore; CH1 legacy external owner must be migrated independently (the legacy routed graph can have an empty CH1 FX lane while the special CH1 host still has FX). Never claim a complete CH1 transfer until that owner is connected. +3. Migrate the entire accepted legacy Show/AUX/PRE/POST/MONITOR/MAIN/secondary output via the existing `LegacyGraphMigration` bridge. Support one hardware device pin mask per accepted render; no hidden coercion to ASIO/OBS. +4. Permit Add Channel/Group/FX Return in the single native producer **after** passing true CH11 mono/stereo, plugin preset state, nested Group and send/monitor tests. Build GUI strip IDs from the exact native ACK. Hardware FAT follows from a Windows executable at that head. +5. Keep existing M4/FAST3 one-APPLY and emergency MUTE, adaptive channel bank R7, P0 #15 0FX crackle evidence and realtime performance counters intact. + +**Honest status:** This is a substantive native FX/state migration seam with real processor PCM tests, **not yet a publicly usable full dynamic Studio One-equivalent Console**. No physical zero-latency guarantee and no field MAONO PS22 FAT has been executed for this M5 branch. + +## M-U1 full native admission transaction — added after initial M5 bridge + +`engine/core/UnifiedLegacyProductionAdmission.h` now composes the **existing** `LegacyGraphMigration` of the full 10-input + 4-AUX scene, FX PRE/POST sends, MAIN, independent MONITOR, effective mono/stereo format and physical capture port order with the actual M4 `FxInstance` ownership into **one native accepted PCM+VST publication**. `LegacyMigratedGraph.request` is retained verbatim from the validated old physical port map, not recreated from browser controls. A single snapshot binds hardware output callback pairs, exact device epoch, next PCM graph revision and all 14 M4 FX lane leases. Existing committed session/PCM/plugins remain unmodified on failed migration. + +The new native golden test renders real JUCE M4 processors BEFORE the conversion and compares it to output from the same instance objects AFTER the legacy graph owner is destroyed: MAIN L/R and independently routed MONITOR L/R, channel→bus sends and AUX return. It also checks no RT allocation, wrong physical MAIN/MONITOR alias, hotplug epoch, OUTPUT ARMED, external CH1/Orbit owner admission and post-reject audio continuity. A successful test is preparation evidence only; the production callback is NOT yet switched, hardware FAT is still required. + +**Critical safety gate:** an occupied legacy external CH1 FX chain/Orbit is explicitly rejected, not discarded or accidentally duplicated. The next M-U1 phase must migrate that separate owner and Show/editor state, then atomically choose the unified render in `LiveAudioEngine`; only after that can unrestricted +CHANNEL, Group Selected and +FX Return UI become live. diff --git a/docs/workstreams/ENGINE_SINGLE_OWNER_HANDOFF_20261103.md b/docs/workstreams/ENGINE_SINGLE_OWNER_HANDOFF_20261103.md new file mode 100644 index 000000000..19102ebdd --- /dev/null +++ b/docs/workstreams/ENGINE_SINGLE_OWNER_HANDOFF_20261103.md @@ -0,0 +1,113 @@ +# ArSonMix ENGINE — One Owner Reconciliation / Next Work Handoff +Date: 2026-11-03. **ENGINE workstream only**, binding on the #266 implementation branch. + +## Reconciled branch ownership (avoid two parallel engines) + +| Scope | Single owner | Allowed work | +|---|---|---| +| Native ENGINE | **PR #266** `milestone/m5-universal-channelid-vst3-lease-migration-20261101` | ONE `LiveAudioEngine` callback, full-fidelity M4→ChannelId retirement, VST3 instance/editor/Show ownership, native FX/CPU/memory, device/epoch | +| M1 stabilization | Former **PR #287**, absorbed as FAST-FORWARD ancestors of #266; close #287 after verification | No independent engine feature branch. The 64-sample fader, AUX parity, bounded graph retirement, Show worker lifetime, removal of dead diagnostic FX must stay in #266 | +| GUI production adapter | PR #271 | WebView renderer consumes **accepted** snapshot/ACK, never owns PCM | +| GUI reference | PR #278 + #285 | Visual and WIRE workflow only; no browser FX or duplicate JS graph may be merged into DSP | +| Final integration and physical FAT | PR #270 / issue #192; physical crackle issue #15 | One joined Windows exact-SHA artifact, real hardware tests. Not an ENGINE branch | + +**Important:** At reconciliation, comparison of `main@1859fa147b360e607b29a8eba636af33288a3a36` with ENGINE #287 `1e21bf0a0d8aff33b02b56cec5c2e5c328fd41d1` was **diverged** (78 commits missing from ENGINE's source history, 62 ENGINE-side commits). This is a warning, not a merge resolution. Refresh main and reconcile line-by-line against existing native behavior before production merge. Do not overwrite 78 upstream changes with a branch checkout or careless `git reset`. + +## Single native render truth NOW + +```text +Approved GUI workflow (#278/#285) → native GUI (#271) + → ConsoleLiveBridgeV6: schemaVersion=6, canonical decimal ChannelIds, + unique requestId, accepted snapshot/ACK and truthful capability flags + → Native JUCE LiveAudioEngine (ONE production callback) + ├─ NORMAL, unpatched → SILENT (no hidden CH1) + ├─ accepted M4 → LiveDryRoutingLab + original CH1 vendor/Orbit lease + │ + 10 input + 4 AUX + MAIN/MONITOR (real PCM) + └─ diagnostic mode (no M4 owner) → isolated 0FX test tone/capture + × DynamicChannelRoster/FX/Publisher: prepared/offline only, NOT currently live +``` + +Do not confuse multiple **types** in the tree with multiple **active** engines: their runtime entry point and ownership decide whether they are a problem. `PreparedNativeMixerSession` is testing-only; `NativeShowSaveWorker` is I/O, not a render worker. Legacy M4 render path is a deliberately **quarantined compatibility implementation**, not an approved target for new GUI features. + +## CLEAN / FROZEN / RETIRE inventory + +- **CLEAN NOW**: old diagnostic stereo VST graph removed; one explicit `NativeRenderAuthority` selector; separate test-only source registration; M1 live AUX/fader, bounded retirement, worker resource release tests. +- **FROZEN**: M4 fixed ordinal 10CH+4AUX may only receive production bug/safety fixes (driver, crackle, VST/Show regressions). Do not implement CH11, Group, new FX Return or WIRE semantics as another M4 feature. +- **PRESERVE**: CH1 original prepared VST3/Orbit/editor/Show, other strip/aux FX, independent MONITOR, AUX PRE/POST, sparse device port maps, direct route fence, mute and diagnostic capture evidence. Do not delete before parity. +- **UNADMITTED**: dynamic ChannelId graph, `UnifiedLegacyProductionAdmission`, `DynamicNativeSessionPublisher` are one planned replacement; not an alternate live callback, and `productionCallbackLive=false`, `supportedOps=[]` are intentional. +- **HISTORICAL**: separate draft experiments (including #251 WASAPI and #225 FactoryFX) do not acquire production engine ownership by existence. Do not close unrelated issues without evidence; do not blindly merge. + +## Non-negotiable invariants (automatically guarded) + +The cheap `tests/engine_runtime_reconciliation_test.mjs` runs **before** JUCE checkout in the existing Windows job. It fails on extra production callback, double M4 PCM render, test-only mixer listed as native app source, diagnostic VST resurrection, lost CH1 vendor lease, false ChannelId LIVE capabilities, or the loss of Show worker isolation. These are **migration stage gates**: a deliberate universal cutover must update them in the same exact-SHA commit that establishes real callback/VST/GUI/FAT proof; never bypass by changing a string only. + +## Next ENGINE milestone (one substantial outcome) + +1. Rebase/reconcile #266 on current `main` **without** overwriting GUI/native/diagnostic changes. Detect conflicts particularly in `src/LiveAudioEngine.h`, `src/Main.cpp`, `src/LiveDryRoutingLab.h`, `engine/core/PreparedMixerBlock.h`, `CMakeLists.txt` and mixed native/JS source contracts. +2. Migrate the **actual** M4 owners to one accepted ChannelId graph: CH1 original vendor/Orbit editor, CH2–10, AUX1–4, MAIN/MONITOR, Show states and sparse real hardware pins; no reinstantiate on routine fader/mute/send edits. Prepare on control/worker, not callback. +3. Switch the existing JUCE callback **once** with a full-fidelity native epoch/graph ACK; maintain one output pathway, no phantom channel and no double FX. Device/clock/FX owner changes fail closed until proven safe. +4. Update `ConsoleLiveBridgeV6` supportedOps/capabilities only from **real admitted callback**; integrate #271 operator intent and #278/#285 approved WIRE through the **same graph**; #270 owns combined exact SHA release. +5. Remove M4 compatibility adapter and ordinal CH1 paths **in the same** production integration only after golden 10CH/AUX/monitor PCM and real vendor/editor/Show parity, approved Windows native CI and ASIO 0FX/1FX hardware FAT. + +### Definition of ready for hardware/UAT + +A green PR-specific CTest is valuable but **insufficient**. Require exact joined Windows EXE provenance, hardware driver/rate/buffer/pins, 0FX clean wired audio, real VST3 editor/state, MUTE/SOLO/AUX/MONITOR, Show recall, and measured output latency/crackle evidence. Do not claim zero physical latency, zero crash risk from arbitrary in-process third-party VST3, or universal CH11 before hardware validation. + +**Do not start another ENGINE PR while #266 is open.** Future ENGINE edits and test evidence go into #266; #271 (GUI) and #270 (FAT) receive only explicit contract handoffs. + +## M-U2 canonical realtime control kernel — 2026-11-03 +The prepared universal `DynamicPreparedMixerBlock` now uses **one reusable** `RealtimeSlew64` for ChannelId fader/PAN stereo targets and all PRE/POST SEND targets. CONTROL writes one atomic/latest target per logical control; AUDIO reads once per channel/send per block and advances exactly 64 samples across variable 4/16/32/12-frame ASIO/WASAPI quanta. A reversal starts from the last *applied* coefficient, not the most recent requested goal. No extra worker, event FIFO, heap, lock, division, or plugin re-instantiation in RT. The single native `M3DAtomicStudioBusFxChannelSessionRollback` CTest now checks actual ChannelId→wet PRE→MAIN and POST→MONITOR PCM with short callbacks, coalescing, revision rejection and null output at the terminal zero gain. The installed JUCE callback remains safely on accepted M4 while full vendor/Show migration remains pending; no fake GUI LIVE promotion. This removes a genuine small-buffer dezippering blocker for the final engine, not an extra audio engine. + +### M-U2 efficient GUI control ownership +`DynamicPreparedMixerBlock` reuses its compiler-built `ChannelId → dense lane` table after graph admission, so fader/PAN and PRE/POST SEND control commands do **not** linearly scan all channels per gesture. The table and CSR send adjacency are accessed on the control writer only; realtime callback reads packed atomic targets once per block, advances sample-continuous state, and does not hash, allocate, lock or invoke workers. Regression sends **4096 successive fader gestures**, tests latest-target-wins, unknown ChannelIds fail closed and exact PCM after 64 rendered samples. A lock-free atomic requirement is enforced at compile time for send target storage. The existing Windows job builds these tests via the established M3D test dependency; no new workflow or CI matrix. + +## ENGINE candidate for physical FAT (source-attested) +Canonical PR #266 alone is allowed to publish `ArSonMix-ENGINE-10CH4AUX-EXPERIMENTAL-Hardware-FAT-Windows-x64` after successful full Windows native CTest and independent SHA/PE/embedded-WebView verification. The retired M4 branch cannot publish a parallel ENGINE artifact. This is a **true native Windows JUCE GUI**, with `BUILD_PROVENANCE.json` and `HARDWARE_FAT_GUIDE.md`, suitable for cautious 0FX ASIO/WASAPI first-sound testing and crackle issue #15 evidence. Installed DSP is still M4 10CH/4AUX and the approved modern GUI #271 will require joined exact-SHA integration #270; do not promote universal capabilities merely because this ZIP exists. + +## M5-Live PCM control-plane convergence — 2026-11-03 +Installed M4 `PreparedMixerBlock` no longer reads four independent strip atomics during solo/fader traversal. Its `RealtimeStripControls` publishes one lock-free 64-bit snapshot containing *both* 31-bit fixed-point stereo gains (range 0..4) plus MUTE/SOLO flags, on the sole CONTROL writer; the AUDIO callback copies 10 snapshots once at the block boundary, then runs SOLO closure and PCM against the same consistent block view. Gains are quantized on CONTROL with precision comfortably finer than float, never on RT. The installed callback now reuses the SAME `RealtimeSlew64` type as future ChannelId for MUTE/PRE SEND and stereo fader/PAN—64 actual samples crossing variable hardware callback quanta, exact final endpoints and no divides in the hot sample loop. Zero additional audio thread, queue, allocation or VST3 refcount. An existing native CTest exercises 200,000 concurrent opposite pan/mute/solo GUI edits, rejected invalid ranges and coherent readback. Real M4 FX/physical route remains unchanged while accepted universal migration stays guarded. The published Hardware FAT SHA preceding this change remains a separate validated baseline; any new artifact requires exact SHA Windows CTest and a fresh PE/ZIP attestation. + +## M5-Live callback overlap fail-closed gate +The installed `LiveDryRoutingLab::process()` and prepared future `DynamicNativeSessionPublisher::render()` now use ONE reusable, allocation-free `RealtimeRenderPermit` helper. It acquires an atomic-flag once at entry and releases on all return paths (RAII). Concurrent unexpected host/backend invocations do **not** mix scratch, overwrite fade coefficients, or render a VST3 instance twice; the duplicate fails silent without locks, waiting, queueing, retrying, or instantiating anything. This adds no second production entry point and leaves JUCE's one selected PCM owner unchanged. An existing CTest stresses 20,000 rejected overlapping acquisitions followed by successful lease reuse. Native architecture gate requires both paths to use the same nonblocking permit. This is safety against invalid device callback overlap, not a claim that vendor plugins themselves are always realtime safe. + +## True GUI–ENGINE readback seam (M4, separate from universal) +`ConsoleLiveBridgeV6::snapshot` exposes **the exact accepted M4 10-strip route**, its physical source indices and separately namespaced `legacyM4.controlPlane=LEGACY_M4_ORDINAL` / `legacyM4.supportedOps` ONLY after the installed physical route is admitted, current device connected, and topology not faulted. M4 `SET_FADER/PAN/MUTE/SOLO/SOURCE/PROCESSING_FORMAT/PRIMARY_OUT` are native operations supported by its existing S1 `processProductionIntent`, with epoch and independent `legacyRoutingRevision` fence; conditional AUX/VST3/MONITOR operations require actual accepted resources. The universal `graph.channels`, `graph.capabilities.supportedOps`, `productionCallbackLive` stay EMPTY/FALSE. This is an intentional compatibility contract for GUI #271 and final integration #270, NOT a fake universal graph nor a duplicate mixer. GUI must distinguish M4 ordinals (1–10, AUX11–14) from permanent ChannelIds, never copy M4 controls into universal graph capabilities. A native CTest verifies accepted rows, bounded ops and fail-closed poisoned physical topology. + +## E2 native IN/OUT signal-flow truth — 2026-11-03 + +**Reference contracts (not browser DSP):** +- Adobe Audition multitrack: https://helpx.adobe.com/audition/desktop/mixing-multitrack-sessions/multitrack-routing-eq-controls.html — PRE send is independent of track fader; POST send follows it; MAIN/Mix is terminal hardware sink. +- Waves eMotion LV1 channels/groups/aux: https://www.waves.com/emotion-lv1-tutorial-4-2-mixer-channels-groups-aux — GROUP is real serial sum+inserts+fader, AUX/EFX is real parallel send+bus; monitor is independently routed. +- Waves eMotion LV1 tap options: https://www.waves.com/emotion-lv1-tutorial-4-9-mixer-window-aux-mode — distinguishes input, pre-fader, post-fader and post-panner taps. ArSonMix currently supports explicit PRE-fader-after-processing and POST-fader/post-pan edges, **not** all four LV1 taps. Never claim full LV1 tap parity. + +**Binding GUI → accepted native PCM:** IN accepts only verified physical callback ordinals and is NOT the channel processing width. A same-format live SOURCE change must be accepted via `setLivePhysicalSource(epoch,graphRevision,id,...)` before the operator sends another structural OUT/GROUP/FX Return command. Structural requests carrying a different same-format pin from the accepted canonical source now **NACK** with `invalidSource`; they cannot silently overlay the old pin and falsely ACK. Rebase GUI drafts from `acceptedPhysicalRequest()`. Unpatched→patched and genuine mono↔stereo source changes remain structural and require revalidation. + +**Two independent routing primitives:** `primaryOutput` is ONE unity-level, neutral-pan, POST-fader **serial OUT** (CH → Group → MAIN). Non-unity/PRE/panned primary descriptors are rejected. `SEND` remains a separately leveled/panned PRE/POST **parallel** edge into MONITOR, FX Return or another legal bus. DAG cycle and duplicate-edge rejection preserve the no-double-dry invariant. LINK FADERS is control-only; it must not be implemented as a Group bus. + +**Native regression:** `tests/console_native_integration_test.cpp` now exercises rejected malformed primary OUT, reject-before-ACK of both out-of-range and *valid but unaccepted* physical SOURCE, native live IN change with 64-sample crossfade, stale GUI route rejection, accepted rebased OUT revision, and real PCM through CH7→GROUP, CH2→MAIN, parallel wet return and independent MONITOR. `tests/dynamic_accepted_session_test.cpp` guards the same SOURCE transaction and unchanged prior sound. No callback-side allocation or new DSP owner is introduced. + +**Remaining STOP-SHIP:** Installed `LiveAudioEngine::audioDeviceIOCallbackWithContext` still runs native M4 10CH/4AUX. This is a portable ChannelId PCM/control integrity gate, **not physical E2 cutover**, Show parity or enabled GUI production capability. Real direct physical callback ownership, VST3/Orbit control and #271 accepted event bridge still require exact-joined-Windows and hardware FAT proof. + +## E2 physical PCM adoption — single original callback, guarded M4→ChannelId + +The installed `LiveAudioEngine::audioDeviceIOCallbackWithContext` still has exactly one JUCE callback, one native physical output gate and one `LiveDryRoutingLab::process()` invocation. Inside that existing verified DIRECT device process, a new CONTROL-admitted `UnifiedLegacyProductionAdmission` snapshot can replace M4 DSP with `DynamicNativeSessionPublisher::render()` **instead of** invoking `LiveChannelFxGraph::process()`. They are selected mutually exclusively once per callback. There is no additional PCM thread, no second VST host or double dry sum. + +**Physical adoption requirements and fallback:** only after operator APPLY has accepted real input/output masks (including sparse callback ordinals), all outputs are disarmed, and the special legacy CH1 external Orbit rack is EMPTY. The old M4 graph remains retained as a compatibility/fail-safe output; ChannelId admission rejects wrong epoch, invalid pins, uncompensated VST latency, resource budgets or untransferred CH1. These cases keep M4 audible, not a fake universal graph. Device stop, stale source, structural APPLY and CLEAR PATCH drop the ChannelId selector atomically. The PCM snapshot carries the exact original JUCE per-channel + AUX VST owner leases, and after successful admission the native callback renders them only once; plugin editor/Show state survives because owners are shared, not recreated. The existing MAIN/MONITOR/secondary output taps, master ramp, output MUTE and raw PCM capture fence are reused. + +**GUI control integrity:** the accepted M4 scalar controls (strip fader/pan/mute/solo, live same-format SOURCE, POST/PRE AUX level, AUX return fader, MONITOR gain) update both M4 safety fallback state and the native ChannelId atomic targets with the same device epoch. A rejected native scalar update immediately reselects M4. A structural edit rebuilds and re-admits only with output safely disarmed. The native graph now delivers independent post-fader L/R peak readings directly from its own PCM render for the existing M4 Console's ten channel LEDs and four AUX levels; no browser DSP/fake dual-stereo meter. + +**SCOPE BOUNDARY**: This is **physical callback ChannelId adoption for accepted fixed 10CH+4AUX routes only**, not full CH11/Group WIRE GUI cutover or automatic acceptance of occupied original CH1 Orbit. The M4 source/GUI editor paths still exist as bounded compatibility. `ConsoleLiveBridgeV6::productionCallbackLive=false` and universal capabilities remain false; they mean the **full universal operator console** is not ready, NOT that the lower-level ChannelId DSP can never be selected for M4-compatible hardware PCM. Keep PR #266 DRAFT. Next milestone is occupied CH1 Orbit+Show parity, native stable ChannelId GUI snapshot/ACK and direct CH11+Group/FX Return operator end-to-end cutover on this same callback. Physical hardware 0FX/1FX and issue #15 crackle remain NOT TESTED until manually checked against verified Windows artifact. + +## E2 native ORIGINAL CH1/Orbit vendor lease cutover — supersedes prior "CH1 EMPTY" gate (2026-11-03) + +**Critical source owner fix:** The original `LiveAudioEngine::Graph` now owns the CH1 bypass/de-click scratch AND an exact `shared_ptr` lifetime on CONTROL. The existing `LiveGraphHandoff` still publishes only `Graph*` on the one JUCE realtime callback. When the native ChannelId publisher admits the current M4 route, `currentOriginalCh1Lease()` supplies a `DynamicChannelFxLeaseBank::ExternalLease` with a strong reference to the **same original Graph object** and a raw (validated) process function. Its DSP function reuses the original plugin order, atomics, bypass envelope, real plugin instances, tail and editor/preset state; neither a VST clone nor an alternate audio thread is created. Original M4 FX and native ChannelId invoke **the same function**, selected mutually exclusively per callback. + +**No guessed ChannelId:** `UnifiedLegacyProductionAdmission` validates original owner identity `context==owner.get()` and binds an initially unspecified CH1 ID from the freshly compiled verified source roster. Explicit conflicting IDs NACK. A nonempty original vendor rack is only admitted when the acknowledged M4 CH1 rack has no conflicting native lane insert and the original rack is strictly zero-latency (no PDC yet). Original VST3 rack changes and Show recall revoke native ownership BEFORE the existing output-declicked graph handoff. The native CONTROL finalizer can re-admit the new exact original rack once handoff completes, **only if outputs are disarmed and device/mixer epoch is valid**. This preserves the original vendor editor, FX reorder, bypass, Show binary state and bank tail while native PCM is the one physical renderer. Graph and plugin reclamation happens on CONTROL after both the native publisher and handoff have retired their leases; no shared_ptr refcount/drop/heap on AUDIO. + +**Regression acceptance:** `verifyOccupiedExternalCh1Owner()` checks compiled CH1 binding without magic ID, rejects wrong/stale owner/context and spoofed ID, compares golden native/M4 vendor PCM, retains the exact original vendor when the M4 owner is destroyed, confirms one vendor invocation on callback, and checks final weak_ptr expiry only after native publisher + GUI owner control retirement. JS architecture gate enforces shared Graph ownership, exactly one installed JUCE callback, original bypass scratch, Show/ADD/REMOVE revocation and native external single-render dispatch. Windows exact-head native, GUI smoke and artifact checks are required before PASS can be claimed. + +**Remaining NOT DONE:** The real physical ASIO/WASAPI microphone/speaker execution, direct GUI universal CH11/serial GROUP/wet FX RETURN accepted snapshot/ACK, operator-visible external CH1 status and joined #270 executable. Native admission is a verified 10CH/4AUX compatibility cutover, **not** proof of every universal operator workflow; `productionCallbackLive` must stay FALSE until those operations really reach physical PCM. Show recall state needs end-to-end device FAT validation, not merely compiled source coverage. + +### E2 hardware renderer readback — V6 GUI bridge, without capability promotion + +`LiveDryRoutingLab::status()` reports `nativeChannelIdPcmActive` and `originalCh1GraphLeased` from the actual admitted device epoch and native FX owner. `ConsoleLiveBridgeV6::snapshot()` maps these ONLY into the accepted `legacyM4.pcmRenderer` (`CHANNEL_ID_10CH4AUX` or `M4_COMPAT`) and `legacyM4.originalCh1GraphLeased`, while preserving `controlPlane=LEGACY_M4_ORDINAL`, its exact routing revision and verified masks. An unready/no-device fixture receives no fabricated renderer label. Revocation immediately changes readback to `M4_COMPAT`; universal `productionCallbackLive`, stable ChannelIds and `graph.capabilities.supportedOps` remain strictly FALSE until the joined GUI #271/#270 physical integration genuinely controls CH11/Group/FX Return. The bridge's native snapshot regression checks both active and revoked provenance without changing the universal capability contract. diff --git a/docs/workstreams/GUI_FINAL_ENGINE_HANDOFF_20261102.md b/docs/workstreams/GUI_FINAL_ENGINE_HANDOFF_20261102.md new file mode 100644 index 000000000..68f997238 --- /dev/null +++ b/docs/workstreams/GUI_FINAL_ENGINE_HANDOFF_20261102.md @@ -0,0 +1,33 @@ +# ArSonMix — GUI-final engineering handoff (2 November 2026) + +**Product decision: operator UI WORKFLOW LOCKED for ENGINE #266, not audio-runtime certified.** GUI production owner: PR #271. User-approved interaction/geometry north star: PR #278 + published WIRE V36/V37 reference; hardware material V5 supersedes old BTN-180 art. FAT owner: PR #270. Single Console, one WebView2, one native JUCE callback. No JS graph/PCM engine and no imported demo rack/meters. + +## Fixed operator workflow +One dense mixer console shows **IN → M/ST → VST3 inserts → SEND/FX return → PAN/TRIM/CUE/MUTE/SOLO → FADER / genuine L/R meter → OUT**, with one-width pinned MAIN. The permanent section rail collapses I/O, FX and SEND for all strips without changing fader alignment. Source, destination, graph revision and route state must remain inspectable across banks. A WIRE source is a visual selection only; clicking outside releases it, hover affordance and enlarged IN hit target are requirements for the final patch renderer. Never display an imaginary long wire between off-screen banks. Reference WIRE model is NOT executable DSP. + +**Visual lock:** lightweight graphite #0B161E/#14232C/#20313B, approved V5 physical keys with tiny semantic backlight (MUTE red, SOLO amber, PFL cyan), single SVG text knockout, original channel palette/icons where *native metadata explicitly publishes them*; top and bottom use the same accepted color and icon; no CSS blur/hover glow. MAIN and each channel use EXACT shared width at 150/125/105 px for comfort/standard/compact. No CSS-render-driven audio changes. + +## One authoritative native socket +Contract remains `schemaVersion=6` in v8 orchestration. Subscribe `arMixConsoleSubscribe` → native `arMixConsoleSnapshot`, intents `arMixConsoleIntent` → native `arMixConsoleAck` → same-epoch/revision accepted snapshot. Every uint64 ID/revision is a canonical decimal **string**; requestId includes unique per-WebView nonce. GUI never replaces the accepted view with PENDING state or infers LIVE from clicks. Unknown operation, mismatched deviceEpoch/revision, missing hardware mask, unsupported source pin, callback not LIVE => disabled/rejected, original graph retained. The native producer must publish `device.{epoch,backend,captureDevice,playbackDevice,inputEndpoints,outputEndpoints,enabledInputs,enabledOutputs,sampleRate,bufferFrames,outputArmed}`, `graph.{revision,rosterRevision,channels,destinations,capabilities}`, and measured `telemetry`. + +| Final operator action | Intent operation | Existing GUI payload / expected ENGINE behavior | +|---|---|---| +| Select physical input IN | SET_SOURCE | `{portId}` verified enabled endpoint for exact ChannelId; no pseudo-stereo alias | +| Select primary OUT / serial Group | SET_PRIMARY_OUT | `{destinationId}` accepted bus/physical output by role; cycle/feedback rejected | +| MONO/STEREO processing | SET_PROCESSING_FORMAT | `{format}` independent of count of genuine physical pins | +| Add/select native VST3 | ADD_INSERT / PICK_INSERT_FILE | `{pluginId}` from native catalog or native picker; actual lease and CPU voice, never mock | +| Bypass/editor/reorder VST3 | SET_INSERT_BYPASS / OPEN_INSERT_EDITOR / MOVE_INSERT | `{insertId,bypassed}`, `{insertId}`, `{insertId,beforeInsertId}`; native lease preserved | +| SEND/FX-return | ADD_SEND / SET_SEND_TAP / SET_SEND_LEVEL | `{targetId,tap:'POST',levelDb:0}`, `{sendId,tap}`, `{sendId,levelDb}`; PRE/POST real PCM, no dry duplication | +| PAN / TRIM / FADER | SET_PAN / SET_TRIM / SET_FADER | `{value}`, `{valueDb}`, `{valueDb}`; RT smoothing, not graph rebuilt on drag | +| MUTE / SOLO / PFL (Cue) | SET_MUTE / SET_SOLO / SET_CUE | `{value:boolean}`; monitor semantics separate from MAIN summing | +| Link selected faders | SET_LINK_GROUP | `{channelIds,linked}`; controls only, NOT a Group DSP bus | +| Route selected to genuine Group | ROUTE_SELECTED_TO_GROUP | `{channelIds,destinationId}`; *serial exclusive* dry path without doubles | +| Rename / create native channel | RENAME_CHANNEL / CREATE_CHANNEL | `{name}` / `{role}`; native publishes stable ChannelId and rosterRevision | +| WIRE source/plug/replug/unplug, cross-bank navigator | **NOT INSTALLED AS LIVE OP** | Ref PR #278/V37 only. ENGINE+GUI+FAT must define corresponding accepted graph transactions in shared v8 contract BEFORE enabling. Do not simulate sound. | +| Device changes, Show recall/save, independent Monitor outputs | **ENGINE operation contract pending** | Native epoch/pins and full Show/plugin chunks must be published; fail closed until shared contract supports these operations. | + +### Channel identity schema extension: single-owner admission required +GUI now *reads optional* `graph.channels[].color` (#RRGGBB) and `graph.channels[].icon` (short glyph) ONLY from actual accepted native snapshots; missing data gives neutral grey and no icon, never palette-by-index. **ENGINE must add optional metadata and immutable accepted updates through issue #192 with fixture + validator + FAT tests**. Renaming keeps existing native ID; icon/color editing remains blocked until there are specific new supportedOps and ACK. Never advertise an editor that merely updates JS. + +### Release truth +Current PR #271 uses an illustrative Chromium native stub for S1/S2 controls, not real callback/ASIO PCM evidence. S0 producer unready C++ trace is preserved unchanged. Real full-fidelity callback promotion, actual 2-input/2-VST3/CH11/serial Group/wet Return/Monitor/Show, exact unified SHA Windows build and hardware crackle #15 remain mandatory; no public stable installer or user UAT claim before FAT #270. One combined FAT/Windows/Chromium gate, no repeated small CI promotions. diff --git a/docs/workstreams/GUI_WIRE_POT_V35_20261102.md b/docs/workstreams/GUI_WIRE_POT_V35_20261102.md new file mode 100644 index 000000000..8476c7b06 --- /dev/null +++ b/docs/workstreams/GUI_WIRE_POT_V35_20261102.md @@ -0,0 +1,17 @@ +# V35 — Native WIRE-pot SVG / Accepted Send Control + +Scope: GUI #271 (`work/operator-console-v6`) and authoritative SVG from #278 (same user-uploaded `knob-ICON.svg`). The GUI reference alone has **no real DSP**; only accepted native ChannelId sends may color the native knob. + +## Delivered +- Original uploaded SVG path is present at `web/assets/knob-ICON.svg`, with the same silhouette inlined as URL-encoded CSS mask for **offline standalone/WebView2 byte parity**. Old CSS radial knob and separate tick removed from native send control. +- **Dark grey `#4b535b`** whenever no accepted native send exists. A channel name selection, pointer hover, UI demo, or unaccepted pending request cannot light the knob. +- A row representing an accepted ChannelId `sends[]` link becomes `is-connected`. Its fill uses **native destination channel.color**; when native metadata is missing or invalid, grey is deliberately retained, never fabricated. +- Per-link 0.1dB SEND gain uses a pointer-captured, relative SVG encoder. Shift uses fine 14px/dB versus normal 3px/dB; wheel and keyboard remain native range controls, double click requests unity. No idle `pointermove` listener; active pointer handlers are installed on the captured input only and cleared after completion. +- During drag only local readout moves; **one native `SET_SEND_LEVEL` intent on accepted pointerup** with `requestId`, `deviceEpoch`, `baseGraphRevision`. On ACK rejection/timeout/cancel, accepted state remains unchanged, and the native accepted snapshot drives repaint. +- Core audio graph code, VST3 engine, stream callback, ASIO/PCM, UI channel ownership, visual reference PR278, and public Pages remain unaffected. + +## Verification and remaining release boundary +- `tests/operator_console_v6_smoke.py`: Chromium computed CSS mask/fill, idle state, accepted source→destination color, pointer drag one-intent + ACK-rejection rollback, pointercancel no intent, native keyboard step. +- `tests/mixer_shell_geometry_smoke.py`: original strip/meter/fader MAIN geometry; all existing UI tests, JS syntax, v8 fixture and offline embedding gated by `.github/workflows/ui-smoke.yml`. +- `node --check web/mixer-layout.js` and `python scripts/build_ui_css.py --check` required. +- **Stop ship remains:** PR271 is a draft GUI branch. Full WIRE OUT→IN routed audio, unrelated input-channel patch destinations, disconnect/replug and Show/SoF need corresponding accepted native operations from ENGINE #266; cannot be fabricated by changing JS. Commit must be integrated with ENGINE and FAT #270 with one exact-SHA Windows runtime/physical I/O test, and crackle issue #15 still unresolved. diff --git a/docs/workstreams/INTEGRATION_FAT_CONSOLE_V6.md b/docs/workstreams/INTEGRATION_FAT_CONSOLE_V6.md index ed0e998e2..ffeb513ef 100644 --- a/docs/workstreams/INTEGRATION_FAT_CONSOLE_V6.md +++ b/docs/workstreams/INTEGRATION_FAT_CONSOLE_V6.md @@ -28,3 +28,15 @@ Reconcile current `main`, engine #266 and GUI branch WITHOUT blind merges. Estab ## Coordination and CI discipline No owner edits under `engine/core/**` or `web/**` without first coordinating in #192. Create isolated integration tests rather than patching engine to satisfy a UI string assertion. CI stage only after meaningful combined checkpoints, no repetitive release upload before passing tests. Record one status row per exact SHA: Native | UI | Artifact | Physical FAT. Failing column prevents production label. Unattended thread/agent work is NOT implied by issues; separate agents must explicitly be started with these handoff docs. + +## Joined executable E3 — physical E2 native ChannelId + operator WebView2 + FAT (2026-11-03) + +Integration owner #270 has assembled one **exact-source-SHA candidate** from: +- main: latest approved Pages/visual preview and CSS tests, no visual regression or historical GUI reset +- ENGINE #266 @ `8d138b3959931bbc387c852ae3234e3a532cb1c2`: sole JUCE callback, hardware-verified fixed 10CH/4AUX ChannelId render, original CH1/Orbit/Show in-memory strong owner, true M4/ChannelId renderer readback, native stereo meters, structural and realtime source/FX controls +- GUI #271 @ `67ef6e7b0afab173840e611b7fdf6627a96e714a`: latest `web/` operator workflow with accepted legacyM4 controls, hardware key navigation and fader/pan UI, *not* false universal CH11/Group operations +- FAT #270 @ `6959a34f5acf76a0d60ab473301816f3899dc237`: native S0/Console v6 contract, exact-blob ZIP/PE/source checks and immutable read-only offline field FAT collector + +Collision policy: engine is authority for `src/`, `engine/`, `CMakeLists.txt` and PCM tests. GUI #271 is authority for the `web/` application JS and native UI assets; main is authority for `site/preview-v2/` and `AGENTS.md` visual lock. FAT #270 is authority for hardware collector/verification scripts. The two workflow files and two shared CI tests were reconciled explicitly, with one exact-head Windows executable+CTest+artifact producer. Native packaging now includes `web/hardware-keys.js` and the real fader and PAN PNG assets via JUCE BinaryData, with allowlisted offline asset URLs. All WebView2 operator JS including hardware keys, mixer-io and mixer-layout is SHA-verified INSIDE the packaged EXE rather than on disk only. + +**Acceptance boundary:** This is a single-source *joined integration candidate*, not full v8 universal product sign-off. GUI still uses fenced `legacyM4` for operator actions, even when the one callback PCM is native ChannelId. `productionCallbackLive=false` is correct for unsupported CH11/Group/FX Return universal CREATE/WIRE. Original CH1 vendor rack remains blocked from disk-native Show save/recall (no serialization yet). For release, first require exact-joined Windows CI PASS and artifact SHA, then physical 0FX/1FX ASIO/WASAPI long soak and crackle #15 root-cause, then full native ChannelId supportedOps/ACK and persistent Show. Do not set a false capability or promote a browser fixture as acoustic FAT. diff --git a/engine/core/ConsolePuzzleV8Wire.h b/engine/core/ConsolePuzzleV8Wire.h new file mode 100644 index 000000000..0a7484355 --- /dev/null +++ b/engine/core/ConsolePuzzleV8Wire.h @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include + +// One native wire serializer shared by JUCE control-thread producer and +// deterministic S0 fixture generator. NO DSP or callback ownership here. +// Physical ports and PCM measurements MUST come from actual native status. +namespace armix::console { +struct PuzzleV8Pin final { + int port=-1,callback=-1; + std::string label; + bool hasRawPeak=false; + double rawPeak=0.0; +}; +struct PuzzleV8Snapshot final { + std::string epoch="1",backend,captureDevice,playbackDevice; + std::string graphRevision="0",rosterRevision="0",legacyRoutingRevision="0"; + int sampleRate=0,bufferFrames=0; + bool outputArmed=false,rawCapturePresent=false; + bool mainPcmPresent=false,monitorPcmPresent=false; + double rawCapturePeak=0.0; + bool legacyActive=false,legacyRouteAccepted=false; + std::vector inputs,outputs; + // Installed M4 callback does NOT own a ChannelId graph yet. + bool productionCallbackLive=false; +}; +struct PuzzleV8Ack final { + std::string requestId,status="REJECTED",deviceEpoch="0"; + std::string graphRevision="0",rosterRevision="0"; + std::string errorCode="UNIVERSAL_CALLBACK_NOT_READY"; +}; +class PuzzleV8Wire final { + static std::string quote(const std::string& in) { + std::string out="\""; + static constexpr char hex[]="0123456789abcdef"; + for(const unsigned char c:in) { + switch(c) { + case '"':out+="\\\"";break; + case '\\':out+="\\\\";break; + case '\n':out+="\\n";break; + case '\r':out+="\\r";break; + case '\t':out+="\\t";break; + default: + if(c<32) {out+="\\u00";out+=hex[c>>4];out+=hex[c&15];} + else out+=static_cast(c); + } + } + return out+'"'; + } + static const char* bit(bool b) noexcept{return b?"true":"false";} + static std::string number(double n) { + if(!std::isfinite(n)||n<0.)return "null"; + char buffer[80]{}; + std::snprintf(buffer,sizeof(buffer),"%.9g",n); + return buffer; + } + static std::string pins(const std::vector& list,const char* kind) { + std::string s="["; + for(const auto& p:list) { + if(p.port<0||p.port>255||p.callback<0)continue; + if(s.size()>1)s+=','; + s+="{\"id\":"+quote(std::string(kind)+":"+std::to_string(p.port))+ + ",\"port\":"+std::to_string(p.port)+",\"callback\":"+ + std::to_string(p.callback)+",\"label\":"+ + quote(p.label.empty()?std::string(kind)+" "+std::to_string(p.port+1):p.label)+ + ",\"active\":true"; + if(p.hasRawPeak && std::isfinite(p.rawPeak) && p.rawPeak>=0.) { + s+=",\"rawPeak\":"+number(p.rawPeak)+ + ",\"rawPresent\":"+bit(p.rawPeak>0.0005); + } + s+='}'; + } + return s+"]"; + } + static std::string enabled(const std::vector& list) { + std::string s="["; + for(const auto& p:list){ + if(p.port<0||p.port>255||p.callback<0)continue; + if(s.size()>1)s+=','; + s+=std::to_string(p.port); + } + return s+"]"; + } +public: + static std::string snapshot(const PuzzleV8Snapshot& s) { + // Complete v8 mandatory wire even while callback is not universal. + // ChannelId and revisions are decimal strings; no JSON double. + return "{\"schemaVersion\":6,\"productionCallbackLive\":"+ + std::string(bit(s.productionCallbackLive))+ + ",\"device\":{\"epoch\":"+quote(s.epoch)+ + ",\"backend\":"+quote(s.backend)+ + ",\"captureDevice\":"+quote(s.captureDevice)+ + ",\"playbackDevice\":"+quote(s.playbackDevice)+ + ",\"inputEndpoints\":"+pins(s.inputs,"in")+ + ",\"outputEndpoints\":"+pins(s.outputs,"out")+ + ",\"enabledInputs\":"+enabled(s.inputs)+ + ",\"enabledOutputs\":"+enabled(s.outputs)+ + ",\"sampleRate\":"+(s.sampleRate>0?std::to_string(s.sampleRate):"null")+ + ",\"bufferFrames\":"+(s.bufferFrames>0?std::to_string(s.bufferFrames):"null")+ + ",\"outputArmed\":"+bit(s.outputArmed)+ + "},\"graph\":{\"revision\":"+quote(s.graphRevision)+ + ",\"rosterRevision\":"+quote(s.rosterRevision)+ + ",\"channels\":[],\"destinations\":[],\"capabilities\":{" + "\"callbackOwnsChannelIds\":false,\"fullVendorFxMigration\":false," + "\"showAndOutputParity\":false,\"physicalCaptureMapped\":false," + "\"dynamicChannels\":false,\"groups\":false,\"fxReturns\":false," + "\"monitor\":false,\"sendsOnFaders\":false,\"supportedOps\":[]}}," + "\"telemetry\":{\"rawCapturePresent\":"+bit(s.rawCapturePresent)+ + ",\"rawCapturePeak\":"+number(s.rawCapturePeak)+ + ",\"mainPcmPresent\":"+bit(s.mainPcmPresent)+ + ",\"monitorPcmPresent\":"+bit(s.monitorPcmPresent)+ + ",\"channelMeterRmsPeak\":[]},\"legacyM4\":{\"active\":"+ + bit(s.legacyActive)+",\"routeAccepted\":"+bit(s.legacyRouteAccepted)+ + ",\"routingRevision\":"+quote(s.legacyRoutingRevision)+"}}"; + } + static std::string ack(const PuzzleV8Ack& a) { + return "{\"requestId\":"+quote(a.requestId)+ + ",\"status\":"+quote(a.status)+ + ",\"deviceEpoch\":"+quote(a.deviceEpoch)+ + ",\"graphRevision\":"+quote(a.graphRevision)+ + ",\"rosterRevision\":"+quote(a.rosterRevision)+ + ",\"errorCode\":"+quote(a.errorCode)+"}"; + } + static std::string fixture(const PuzzleV8Snapshot& s,const PuzzleV8Ack& a) { + const auto state=snapshot(s); + const auto command="{\"requestId\":"+quote(a.requestId)+ + ",\"deviceEpoch\":"+quote(s.epoch)+ + ",\"baseGraphRevision\":"+quote(s.graphRevision)+ + ",\"baseRosterRevision\":"+quote(s.rosterRevision)+ + ",\"operation\":\"SET_SOURCE\",\"targetChannelId\":null,\"payload\":{}}"; + return "{\"events\":[{\"event\":\"arMixConsoleSnapshot\",\"payload\":"+ + state+"},{\"event\":\"arMixConsoleIntent\",\"payload\":"+command+ + "},{\"event\":\"arMixConsoleAck\",\"payload\":"+ack(a)+ + "},{\"event\":\"arMixConsoleSnapshot\",\"payload\":"+state+"}]}\n"; + } +}; +} // namespace armix::console diff --git a/engine/core/DynamicAcceptedSession.h b/engine/core/DynamicAcceptedSession.h index 4e841a4c5..64d9667d9 100644 --- a/engine/core/DynamicAcceptedSession.h +++ b/engine/core/DynamicAcceptedSession.h @@ -51,7 +51,8 @@ class DynamicAcceptedSession final { const DynamicGraphRequest& route, std::uint64_t expectedDeviceEpoch, std::uint64_t activeDeviceEpoch, - bool allOutputsDisarmed) { + bool allOutputsDisarmed, + DynamicNativeSessionPublisher::FxPlan fx={}) { Result result=preflight(expectedRosterRevision,expectedGraphRevision); if(!result.ok())return result; auto candidate=accepted_; // once per batch; ONLY CONTROL @@ -61,7 +62,7 @@ class DynamicAcceptedSession final { } return publish(std::move(candidate),route,expectedGraphRevision, expectedDeviceEpoch,activeDeviceEpoch,allOutputsDisarmed, - std::move(result)); + std::move(result),std::move(fx)); } // Studio Pro: one independent Bus ChannelId and automatic assignment of @@ -74,7 +75,8 @@ class DynamicAcceptedSession final { std::uint64_t expectedDeviceEpoch, std::uint64_t activeDeviceEpoch, bool allOutputsDisarmed, - float parallelGain=.25f) { + float parallelGain=.25f, + DynamicNativeSessionPublisher::FxPlan fx={}) { Result result=preflight(expectedRosterRevision,expectedGraphRevision); if(!result.ok())return result; auto candidate=accepted_; @@ -85,7 +87,7 @@ class DynamicAcceptedSession final { } return publish(std::move(candidate),route,expectedGraphRevision, expectedDeviceEpoch,activeDeviceEpoch,allOutputsDisarmed, - std::move(result)); + std::move(result),std::move(fx)); } // Add an empty GROUP or FX Channel, directly OUT -> MAIN, exactly as a @@ -96,7 +98,8 @@ class DynamicAcceptedSession final { const DynamicGraphRequest& route, std::uint64_t expectedDeviceEpoch, std::uint64_t activeDeviceEpoch, - bool allOutputsDisarmed) { + bool allOutputsDisarmed, + DynamicNativeSessionPublisher::FxPlan fx={}) { Result result=preflight(expectedRosterRevision,expectedGraphRevision); if(!result.ok())return result; auto candidate=accepted_; @@ -107,7 +110,7 @@ class DynamicAcceptedSession final { } return publish(std::move(candidate),route,expectedGraphRevision, expectedDeviceEpoch,activeDeviceEpoch,allOutputsDisarmed, - std::move(result)); + std::move(result),std::move(fx)); } // Delete an existing GROUP or FX return, atomically rerouting primary @@ -119,7 +122,8 @@ class DynamicAcceptedSession final { const DynamicGraphRequest& route, std::uint64_t expectedDeviceEpoch, std::uint64_t activeDeviceEpoch, - bool allOutputsDisarmed) { + bool allOutputsDisarmed, + DynamicNativeSessionPublisher::FxPlan fx={}) { Result result=preflight(expectedRosterRevision,expectedGraphRevision); if(!result.ok())return result; auto candidate=accepted_; @@ -130,7 +134,7 @@ class DynamicAcceptedSession final { } return publish(std::move(candidate),route,expectedGraphRevision, expectedDeviceEpoch,activeDeviceEpoch,allOutputsDisarmed, - std::move(result)); + std::move(result),std::move(fx)); } // Live routine controls change ONLY accepted edges/nodes. Persist values @@ -144,6 +148,31 @@ class DynamicAcceptedSession final { return false; return accepted_.rememberLiveMix(id,linear,pan); } + // The accepted physical patch is canonical too: subsequent Group/FX + // graph recompiles must preserve the most recently ACKed live SOURCE. + bool setLivePhysicalSource(std::uint64_t epoch,std::uint64_t graphRevision, + ChannelId id,int inputL,int inputR, + bool stereo) noexcept { + if(!accepted_.find(id))return false; + const auto it=std::find_if(acceptedRequest_.sources.begin(), + acceptedRequest_.sources.end(), + [id](const DynamicSourcePatch& p){return p.id==id;}); + if(it==acceptedRequest_.sources.end() || it->stereo!=stereo || + !publisher_.setPhysicalSource(epoch,graphRevision,id,inputL,inputR,stereo)) + return false; + it->inputL=inputL;it->inputR=inputR; + return true; + } + const DynamicGraphRequest& acceptedPhysicalRequest() const noexcept { + return acceptedRequest_; // CONTROL readback, not browser draft + } + bool setLiveMuteSolo(std::uint64_t epoch,std::uint64_t graphRevision, + ChannelId id,bool mute,bool solo) noexcept { + if(!accepted_.find(id)|| + !publisher_.setChannelMuteSolo(epoch,graphRevision,id,mute,solo)) + return false; + return accepted_.rememberLiveMuteSolo(id,mute,solo); + } bool setLiveParallelSend(std::uint64_t epoch,std::uint64_t graphRevision, ChannelId source,ChannelId destination, bool preFader,float linear) noexcept { @@ -172,7 +201,7 @@ class DynamicAcceptedSession final { return publisher_.render(epoch,inputs,inputCount,mainL,mainR,frames, muted,std::forward(fx),monitorL,monitorR); } - void unpublish() noexcept {publisher_.unpublish();} + void unpublish() noexcept {publisher_.unpublish();hasHostedFx_=false;} void pollRetirement() noexcept {publisher_.pollRetirement();} private: @@ -191,9 +220,54 @@ class DynamicAcceptedSession final { const DynamicGraphRequest& route, std::uint64_t previousGraphRevision, std::uint64_t requestedEpoch,std::uint64_t currentEpoch, - bool outputsDisarmed,Result&& result) { - result.native=publisher_.commit(candidate,route,previousGraphRevision, - requestedEpoch,currentEpoch,outputsDisarmed); + bool outputsDisarmed,Result&& result, + DynamicNativeSessionPublisher::FxPlan fx) { + // Existing SOURCE targets belong to the accepted native session. + // For already-patched ChannelIds with the same input format, ignore + // stale physical pin ordinals supplied by an old GUI draft during + // +GROUP/+FX Return. An explicit format change is structural. + // E2: once an accepted graph has hosted native VST, structural + // +GROUP/+FX Return/reorder must publish the same real instance + // leases at the next revision. Without this check, an omitted FxPlan + // silently drops processing on every already-audible channel. + // Reject while preserving old graph, vendor state and PCM. + if(hasHostedFx_ && !fx.owner) { + result.fault=Fault::graphRejected; + result.native.fault=DynamicNativeSessionPublisher::Fault::invalidCandidate; + result.native.revision=publisher_.acceptedRevision(); + result.edit.createdIds.clear(); + return result; + } + // A structural OUT/GROUP/Return edit does NOT implicitly change IN. + // The operator's same-format IN gesture is accepted first through + // setLivePhysicalSource(epoch,revision,...), which also updates the + // canonical acceptedRequest_. A stale GUI draft must rebase from that + // accepted SOURCE before asking for a structural ACK. Never silently + // restore old pins and claim the requested new route was accepted. + // Genuine format changes remain structural, with normal graph checks. + for(const auto& source:route.sources) { + const bool valid=DynamicPreparedMixerBlock::validPhysicalPatch( + route.physicalInputs,source.inputL,source.inputR,source.stereo); + const auto prior=std::find_if(acceptedRequest_.sources.begin(), + acceptedRequest_.sources.end(), + [&](const DynamicSourcePatch& p){return p.id==source.id;}); + const bool conflicting=prior!=acceptedRequest_.sources.end() && + source.stereo==prior->stereo && + (source.inputL!=prior->inputL || source.inputR!=prior->inputR); + if(!valid || conflicting) { + result.fault=Fault::graphRejected; + result.native.fault=DynamicNativeSessionPublisher::Fault::invalidGraph; + result.native.graphError={DynamicGraphFault::invalidSource,source.id}; + result.native.revision=publisher_.acceptedRevision(); + result.edit.createdIds.clear(); + return result; // old audible SOURCE and VST3 leases unchanged + } + } + auto effective=route; // CONTROL-only; preallocated before commit + const bool nextHasFx=static_cast(fx.owner); + result.native=publisher_.commit(candidate,effective,previousGraphRevision, + requestedEpoch,currentEpoch,outputsDisarmed, + std::move(fx)); if(!result.native.ok()) { result.fault=Fault::graphRejected; result.edit.createdIds.clear(); // NEVER advertise phantom Bus @@ -201,12 +275,16 @@ class DynamicAcceptedSession final { } static_assert(std::is_nothrow_move_assignable_v); accepted_=std::move(candidate); + acceptedRequest_=std::move(effective); + hasHostedFx_=nextHasFx; result.rosterRevision=accepted_.revision(); result.graphRevision=result.native.revision; return result; } DynamicChannelRoster accepted_; + DynamicGraphRequest acceptedRequest_{}; // CONTROL-only accepted physical SSOT DynamicNativeSessionPublisher publisher_; + bool hasHostedFx_=false; // CONTROL only; never an audio callback flag }; } // namespace armix::mixer diff --git a/engine/core/DynamicChannelFxLeaseBank.h b/engine/core/DynamicChannelFxLeaseBank.h new file mode 100644 index 000000000..68b44c7a6 --- /dev/null +++ b/engine/core/DynamicChannelFxLeaseBank.h @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "DynamicChannelRoster.h" +#include "LiveChannelFxGraph.h" +#include +#include +#include +#include +#include +#include +#include + +// M5 universal ChannelId/VST3 ownership bridge. +// +// Unlike the fixed ten-strip index, this immutable CONTROL-PREPARED table +// follows stable ChannelId across +CHANNEL, +GROUP, FX Return and reorder. +// It holds the exact M4 vendor FxInstance owner leases (binary state, +// parameters, bypass envelope, reverb tail). The audio callback traverses +// RAW pointers only: no shared_ptr refcount, heap, lock, VST instantiation, +// string compare or plugin lookup by catalog name. +// +// The bank must be owned by the SAME published/retired native graph snapshot +// as the PCM schedule. Do not discard it while a callback can render from it. +// Never render a former legacy graph concurrently with its migrated instances. +namespace armix::mixer { +class DynamicChannelFxLeaseBank final { +public: + using FxGraph=LiveChannelFxGraph; + using Lease=FxGraph::InstanceLease; + static constexpr int maxInserts=FxGraph::maxInsertsPerStrip; + + struct Assignment final { + ChannelId id{}; + ProcessingFormat format=ProcessingFormat::stereo; + std::vector inserts; // CONTROL only; no creation on callback + }; + + // Occupied CH1 vendor/Orbit owner remains alive with accepted PCM. + // A callback reads only a raw, prevalidated pointer; no refcount/heap. + struct ExternalLease final { + ChannelId id{}; + std::shared_ptr owner; + void* context=nullptr; + void (*render)(void*,float*,float*,int) noexcept=nullptr; + bool populated() const noexcept {return id.value||owner||context||render;} + bool valid() const noexcept { + return id.value && owner && context==owner.get() && render; + } + }; + enum class Fault : std::uint8_t { + none,invalidEpoch,emptyId,duplicateChannel,tooManyInserts, + emptyLease,duplicateInstance,invalidBusLayout,uncompensatedLatency, + missingLegacyIdentity,invalidExternalLease + }; + DynamicChannelFxLeaseBank()=default; + DynamicChannelFxLeaseBank(const DynamicChannelFxLeaseBank&)=delete; + DynamicChannelFxLeaseBank& operator=(const DynamicChannelFxLeaseBank&)=delete; + DynamicChannelFxLeaseBank(DynamicChannelFxLeaseBank&&)=default; + DynamicChannelFxLeaseBank& operator=(DynamicChannelFxLeaseBank&&)=default; + + // Used by message-thread M4->M5 migration. There is no fallback by + // slot position or catalog ID: an actual opaque M4 instance token is + // required, so a Show/reorder cannot accidentally acquire another plugin. + static bool captureLegacy(int lane,ChannelId nativeId, + ProcessingFormat format, + const FxGraph& prior, + Assignment& destination) { + if(lane<0||lane>=FxGraph::fxSlots||!nativeId.value)return false; + Assignment staged; + staged.id=nativeId;staged.format=format; + for(int slot=0;slotinstanceId!=token)return false; + staged.inserts.push_back(std::move(owner)); + } + destination=std::move(staged); + return true; + } + + static Fault prepare(std::uint64_t epoch,std::uint64_t revision, + std::span bindings, + DynamicChannelFxLeaseBank& destination) { + return prepare(epoch,revision,bindings,destination,ExternalLease{}); + } + static Fault prepare(std::uint64_t epoch,std::uint64_t revision, + std::span bindings, + DynamicChannelFxLeaseBank& destination, + ExternalLease external) { + if(external.populated() && !external.valid()) + return Fault::invalidExternalLease; + if(!epoch||!revision)return Fault::invalidEpoch; + DynamicChannelFxLeaseBank candidate; + candidate.epoch_=epoch;candidate.revision_=revision; + candidate.rows_.reserve(bindings.size()); + for(const auto& b:bindings) { + if(!b.id.value)return Fault::emptyId; + if(b.inserts.size()>static_cast(maxInserts)) + return Fault::tooManyInserts; + if(b.format!=ProcessingFormat::mono && + b.format!=ProcessingFormat::stereo)return Fault::invalidBusLayout; + Row row;row.id=b.id;row.format=b.format; + row.count=static_cast(b.inserts.size()); + for(std::size_t i=0;iprocessor)return Fault::emptyLease; + // M4's preparation verifies a stereo processor layout for + // both mono-as-dual and stereo strips. Other plugin layouts + // must be negotiated explicitly before a future PCM cutover. + if(owner->processor->getTotalNumInputChannels()!=2 || + owner->processor->getTotalNumOutputChannels()!=2) + return Fault::invalidBusLayout; + // Global live-mixer architecture (Waves LV1/Ableton): + // parallel PRE/POST paths with unequal VST latency require + // true graph-aware PDC. Until that engine exists, never + // admit a plugin that would produce misaligned MAIN/MONITOR, + // AUX/Group or parallel FX Return PCM. This is a CONTROL-only + // processor inspection, NEVER called from realtime. + if(owner->processor->getLatencySamples()!=0) + return Fault::uncompensatedLatency; + for(const auto& existing:candidate.rows_) + for(std::size_t k=0;kcount!=0)return Fault::invalidExternalLease; + candidate.external_=std::move(external); + } + destination=std::move(candidate); // atomic control-thread acceptance + return Fault::none; + } + + std::uint64_t epoch() const noexcept{return epoch_;} + std::uint64_t revision() const noexcept{return revision_;} + std::size_t lanes() const noexcept{return rows_.size();} + ChannelId externalChannel() const noexcept{return external_.id;} + std::size_t insertCount(ChannelId id) const noexcept { + const auto* p=find(id);return p?p->count:0; + } + const Lease* ownerForControl(ChannelId id,std::size_t slot) const noexcept { + const auto* p=find(id);return p&&slotcount?&p->owners[slot]:nullptr; + } + + // E2: stable ChannelId VST3 control plane. Requests are serialized by + // the native CONTROL writer, never the audio callback. A stale epoch, + // graph or opaque instance token cannot bypass somebody else's plugin. + // FxInstance owns the existing 8-ms realtime wet/dry envelope and vendor + // processBlock. No graph swap, device restart, VST creation or RT heap. + bool setInsertBypass(std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,ChannelId id, + std::size_t slot,const juce::String& instanceToken, + bool bypass) const noexcept { + if(expectedEpoch!=epoch_ || expectedRevision!=revision_ || + !id.value || instanceToken.isEmpty())return false; + const auto* owner=ownerForControl(id,slot); + if(!owner || !*owner || !(*owner)->processor || + (*owner)->instanceId!=instanceToken)return false; + (*owner)->bypassRequested.store(bypass,std::memory_order_release); + return true; + } + // The actual prepared vendor instance is also the native editor owner; + // never synthesize a WebView editor or use a catalog name as identity. + Lease leaseEditor(std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,ChannelId id, + std::size_t slot, + const juce::String& instanceToken) const noexcept { + if(expectedEpoch!=epoch_ || expectedRevision!=revision_ || + !id.value || instanceToken.isEmpty())return {}; + const auto* owner=ownerForControl(id,slot); + return owner && *owner && (*owner)->processor && + (*owner)->instanceId==instanceToken ? *owner : Lease{}; + } + + // CONTROL only: rebind all current vendor leases to a new graph revision. + // The same FxInstance keeps editor/state/tail and the audio callback only + // sees raw prepared pointers. No new plugin or audio pipeline is created. + static Fault reuseRevision(std::uint64_t epoch,std::uint64_t revision, + const DynamicChannelFxLeaseBank& prior, + DynamicChannelFxLeaseBank& destination) { + if(!epoch || epoch!=prior.epoch_ || + revision<=prior.revision_)return Fault::invalidEpoch; + std::vector retained; + retained.reserve(prior.rows_.size()); + for(const auto& row:prior.rows_) { + Assignment item; + item.id=row.id;item.format=row.format; + item.inserts.reserve(row.count); + for(std::size_t slot=0;slotcount;++i) + row->raw[i]->render(left,right,frames); + } + +private: + struct Row final { + ChannelId id{}; + ProcessingFormat format=ProcessingFormat::stereo; + std::uint8_t count=0; + std::array owners{}; + std::array raw{}; + }; + const Row* find(ChannelId id) const noexcept { + const auto it=std::lower_bound(rows_.begin(),rows_.end(),id.value, + [](const Row& row,std::uint64_t value){return row.id.valueid==id?&*it:nullptr; + } + std::vector rows_{}; + ExternalLease external_{}; // PCM snapshot retirement occurs off RT + std::uint64_t epoch_=0,revision_=0; +}; +} // namespace armix::mixer diff --git a/engine/core/DynamicChannelRoster.h b/engine/core/DynamicChannelRoster.h index a666b15a1..f05736a35 100644 --- a/engine/core/DynamicChannelRoster.h +++ b/engine/core/DynamicChannelRoster.h @@ -85,9 +85,8 @@ class DynamicChannelRoster final { std::size_t size() const noexcept {return channels_.size();} const std::vector& channels() const noexcept {return channels_;} const ChannelStripDefinition* find(ChannelId id) const noexcept { - const auto it=std::find_if(channels_.begin(),channels_.end(), - [id](const auto& c){return c.id==id;}); - return it==channels_.end()?nullptr:&*it; + const auto it=index_.find(id.value); + return it==index_.end()?nullptr:&channels_[it->second]; } // CONTROL THREAD ONLY. A realtime parameter target must survive the @@ -97,23 +96,30 @@ class DynamicChannelRoster final { bool rememberLiveMix(ChannelId id,float gain,float pan) noexcept { if(!id.value || !std::isfinite(gain) || gain<0.f || gain>4.f || !std::isfinite(pan) || pan< -1.f || pan>1.f)return false; - for(auto& row:channels_)if(row.id==id) { - row.faderLinear=gain;row.pan=pan;return true; - } - return false; + const auto it=index_.find(id.value); + if(it==index_.end())return false; + auto& row=channels_[it->second]; + row.faderLinear=gain;row.pan=pan; + return true; + } + bool rememberLiveMuteSolo(ChannelId id,bool mute,bool solo) noexcept { + const auto it=index_.find(id.value); + if(!id.value||it==index_.end())return false; + auto& row=channels_[it->second]; + row.mute=mute;row.solo=solo; + return true; } bool rememberLiveParallelSend(ChannelId id,ChannelId destination, bool preFader,float gain) noexcept { if(!id.value || !destination.value || !std::isfinite(gain) || gain<0.f || gain>4.f)return false; - for(auto& row:channels_)if(row.id==id){ - for(auto& link:row.sends) - if(link.destination==destination && - link.preFader==preFader && !link.primaryOutput) { - link.gain=gain;return true; - } - return false; - } + const auto it=index_.find(id.value); + if(it==index_.end())return false; + for(auto& link:channels_[it->second].sends) + if(link.destination==destination && + link.preFader==preFader && !link.primaryOutput) { + link.gain=gain;return true; + } return false; } @@ -220,7 +226,14 @@ class DynamicChannelRoster final { else it->insertCatalogIds.push_back(op.text); break; case ChannelEdit::Kind::addSendReference: - if(op.primaryOutput && std::any_of(it->sends.begin(),it->sends.end(), + // OUT is a single unity, POST-fader serial route. Its + // pan/fader live on the source strip; only SEND may own + // an independent PRE/POST tap, level or pan. Reject a + // malformed primary edge before it can reach PCM/GUI ACK. + if(op.primaryOutput && + (op.preFader || op.value!=1.f || op.sendPan!=0.f)) + result.fault=ChannelEditFault::invalidValue; + else if(op.primaryOutput && std::any_of(it->sends.begin(),it->sends.end(), [](const auto& s){return s.primaryOutput;})) result.fault=ChannelEditFault::invalidValue; else if(op.target.value==0 || op.target==op.id || seek(op.target)==candidate.end()) @@ -260,7 +273,12 @@ class DynamicChannelRoster final { } if(result.ok() && !withinBudget(candidate))result.fault=ChannelEditFault::budgetExceeded; if(!result.ok()) {result.createdIds.clear();return result;} + // Structural edits are infrequent and prepared entirely on CONTROL. + // Rebuild before acceptance: rejected/failed edits cannot leave the + // active stable-ID map pointing into an old reordered vector. + auto stagedIndex=buildIndex(candidate); channels_.swap(candidate); + index_.swap(stagedIndex); nextId_=next; result.revision=++revision_; return result; @@ -301,7 +319,12 @@ class DynamicChannelRoster final { if(!withinBudget(candidate)) { result.fault=ChannelEditFault::budgetExceeded;return result; } - channels_.swap(candidate);result.createdIds.push_back({nextId_++}); + // Structural edits are infrequent and prepared entirely on CONTROL. + // Rebuild before acceptance: rejected/failed edits cannot leave the + // active stable-ID map pointing into an old reordered vector. + auto stagedIndex=buildIndex(candidate); + channels_.swap(candidate); + index_.swap(stagedIndex);result.createdIds.push_back({nextId_++}); result.revision=++revision_;return result; } @@ -351,7 +374,12 @@ class DynamicChannelRoster final { if(!withinBudget(candidate)) { result.fault=ChannelEditFault::budgetExceeded;return result; } + // Structural edits are infrequent and prepared entirely on CONTROL. + // Rebuild before acceptance: rejected/failed edits cannot leave the + // active stable-ID map pointing into an old reordered vector. + auto stagedIndex=buildIndex(candidate); channels_.swap(candidate); + index_.swap(stagedIndex); result.revision=++revision_;return result; } @@ -426,13 +454,26 @@ class DynamicChannelRoster final { if(!withinBudget(candidate)) { result.fault=ChannelEditFault::budgetExceeded;return result; } + // Structural edits are infrequent and prepared entirely on CONTROL. + // Rebuild before acceptance: rejected/failed edits cannot leave the + // active stable-ID map pointing into an old reordered vector. + auto stagedIndex=buildIndex(candidate); channels_.swap(candidate); + index_.swap(stagedIndex); ++nextId_;result.revision=++revision_; result.createdIds.push_back(busId); return result; } private: + static std::unordered_map buildIndex( + const std::vector& rows) { + std::unordered_map index; + index.reserve(rows.size()); + for(std::size_t i=0;i channels_; + std::unordered_map index_; // CONTROL ONLY std::uint64_t revision_=0, nextId_=1; }; } // namespace armix::mixer diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index 65b315d8a..0574f9753 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -3,11 +3,13 @@ #include "DynamicPreparedMixerBlock.h" #include "DynamicConsoleRoutingView.h" #include "RealtimeRoutePublisher.h" +#include "RealtimeRenderPermit.h" #include #include #include #include #include +#include #include #include @@ -18,9 +20,25 @@ // Never run both renderers or sum their outputs. No browser-only LIVE status. namespace armix::mixer { class DynamicNativeSessionPublisher final { +public: + // Control-owned native FX lifetime travels IN the same accepted PCM + // snapshot. JUCE types stay outside this portable DSP publisher. + struct FxPlan final { + std::shared_ptr owner; // CONTROL-only copy/destruction + void* context=nullptr; // unchanged owner.get(), RT raw pointer + void (*render)(void*,ChannelId,float*,float*,int) noexcept=nullptr; + std::uint64_t deviceEpoch=0,graphRevision=0; + bool valid() const noexcept { + return (!owner&&!context&&!render&&!deviceEpoch&&!graphRevision) || + (owner&&context==owner.get()&&render&& + deviceEpoch>0&&graphRevision>0); + } + }; +private: struct Prepared final { DynamicPreparedMixerBlock graph; DynamicConsoleRoutingView routing; + FxPlan fx; // SAME lifetime and revision as native PCM graph int physicalInputs=0; bool monitor=false; }; @@ -49,8 +67,14 @@ class DynamicNativeSessionPublisher final { std::uint64_t expectedRevision, std::uint64_t proposedDeviceEpoch, std::uint64_t activeDeviceEpoch, - bool allOutputsDisarmed) { + bool allOutputsDisarmed, + FxPlan fx={}) { CommitResult report;report.revision=publisher_.lastRevision(); + if(!fx.valid() || + (fx.owner && (fx.deviceEpoch!=proposedDeviceEpoch || + fx.graphRevision!=expectedRevision+1))) { + report.fault=Fault::invalidCandidate;return report; + } if(proposedDeviceEpoch==0 || proposedDeviceEpoch!=activeDeviceEpoch) { report.fault=Fault::staleDevice;return report; @@ -76,6 +100,7 @@ class DynamicNativeSessionPublisher final { report.fault=Fault::invalidGraph;return report; } prepared->physicalInputs=request.physicalInputs; + prepared->fx=std::move(fx); // one accepted control-plane publication prepared->monitor=std::any_of(roster.channels().begin(), roster.channels().end(),[](const ChannelStripDefinition& row) { return row.role==ChannelRole::monitor; @@ -106,7 +131,9 @@ class DynamicNativeSessionPublisher final { bool render(std::uint64_t deviceEpoch,const float* const* physical, int physicalCount,float* mainL,float* mainR,int frames, bool outputMuted,Fx&& effect, - float* monitorL=nullptr,float* monitorR=nullptr) noexcept { + float* monitorL=nullptr,float* monitorR=nullptr, + std::span channelPeaksL={}, + std::span channelPeaksR={}) noexcept { static_assert(std::is_nothrow_invocable_v, "Realtime VST dispatch must be noexcept"); const auto clearOutputs=[&]() noexcept { @@ -140,13 +167,23 @@ class DynamicNativeSessionPublisher final { } // A single callback producer owns the prepared scratch. In case a // broken backend calls simultaneously, fail closed rather than race. - if(rendering_.test_and_set(std::memory_order_acquire)) { + armix::rt::RealtimeRenderPermit exclusive{rendering_}; + if(!exclusive) { clearOutputs();return false; } + // Prepared FX takes precedence over the legacy external callback. + // NEVER invoke both: that would double-compress or double-reverb. + // Snapshot ownership pins the M4 instance throughout this callback; + // only control-thread retirement releases the shared owner. + const auto dispatch=[&](ChannelId id,float* l,float* r,int n) noexcept { + const auto& acceptedFx=snap->prepared->fx; + if(acceptedFx.render) + acceptedFx.render(acceptedFx.context,id,l,r,n); + else effect(id,l,r,n); + }; const bool ok=snap->prepared->graph.process( physical,physicalCount,mainL,mainR,frames, - std::forward(effect),monitorL,monitorR); - rendering_.clear(std::memory_order_release); + dispatch,monitorL,monitorR,channelPeaksL,channelPeaksR); if(!ok)clearOutputs(); return ok; } @@ -163,6 +200,13 @@ class DynamicNativeSessionPublisher final { // M3C realtime parameters on the accepted ChannelId graph ONLY. // Caller must propagate the real device epoch and native ACK revision. // Rejected/stale edits leave the last accepted PCM unchanged. + bool setPhysicalSource(std::uint64_t epoch,std::uint64_t revision, + ChannelId id,int inputL,int inputR,bool stereo) noexcept { + return publisher_.updateActiveControl(epoch,revision, + [&](Prepared& active) noexcept { + return active.graph.setPhysicalSource(id,inputL,inputR,stereo); + }); + } bool setChannelMix(std::uint64_t epoch,std::uint64_t revision, ChannelId id,float gain,float pan) noexcept { return publisher_.updateActiveControl(epoch,revision, @@ -170,6 +214,13 @@ class DynamicNativeSessionPublisher final { return active.graph.setChannelMix(id,gain,pan); }); } + bool setChannelMuteSolo(std::uint64_t epoch,std::uint64_t revision, + ChannelId id,bool mute,bool solo) noexcept { + return publisher_.updateActiveControl(epoch,revision, + [&](Prepared& active) noexcept { + return active.graph.setChannelMuteSolo(id,mute,solo); + }); + } bool setParallelSendGain(std::uint64_t epoch,std::uint64_t revision, ChannelId source,ChannelId destination, bool preFader,float gain) noexcept { diff --git a/engine/core/DynamicPreparedMixerBlock.h b/engine/core/DynamicPreparedMixerBlock.h index 9f02c9834..cc6aa73be 100644 --- a/engine/core/DynamicPreparedMixerBlock.h +++ b/engine/core/DynamicPreparedMixerBlock.h @@ -1,9 +1,10 @@ // SPDX-License-Identifier: AGPL-3.0-only #pragma once #include "DynamicChannelRoster.h" +#include "RealtimeSlew64.h" +#include "RealtimeStereoControlWord.h" #include #include -#include #include #include #include @@ -58,6 +59,7 @@ class DynamicPreparedMixerBlock final { ChannelRole role=ChannelRole::input; int inputL=-1,inputR=-1; bool inputStereo=false,enabled=false; + bool monoPan=false; // mono source/processing, independent of VST rack width float gainL=1.f,gainR=1.f; std::size_t first=0,last=0,slot=0; }; @@ -67,26 +69,45 @@ class DynamicPreparedMixerBlock final { // between separate L and R loads. A torn stereo target can cause a // transient image/level jump even with sample ramps. 64-bit atomics are // required lock-free: callback must never invoke a hidden mutex. - struct StereoGainPair final { - float left=1.f,right=1.f; + using Word=armix::dsp::RealtimeStereoControlWord; + struct StereoGainPair final {float left=1.f,right=1.f;}; + // True microphone mono uses equal-power PAN even when a stereo VST rack + // processes its duplicated L/R PCM. A stereo physical source uses + // balance PAN unless explicitly folded to mono processing. Computing + // the coefficient is CONTROL-only; the callback reads one atomic pair. + static StereoGainPair coefficients(bool monoPan,float gain,float pan) noexcept { + if(monoPan) + return {gain*std::sqrt(.5f*(1.f-pan)), + gain*std::sqrt(.5f*(1.f+pan))}; + return {gain*(pan>0.f?1.f-pan:1.f), + gain*(pan<0.f?1.f+pan:1.f)}; + } + struct ChannelTarget final { + std::atomic state{Word::encode(1.f,1.f,false,false)}; + armix::dsp::RealtimeSlew64 appliedL{},appliedR{},gate{}; // AUDIO only }; - static constexpr std::uint64_t packGainPair(float left,float right) noexcept { - return (static_cast(std::bit_cast(right))<<32) | - std::bit_cast(left); + // CONTROL only packs already verified callback-ordinal physical pin pairs. + // 0xFFFF means missing right input for mono, never an active physical pin. + static constexpr std::uint32_t packPhysical(int left,int right) noexcept { + return static_cast(left) | + (static_cast(right<0?0xffff:right)<<16); } - static constexpr StereoGainPair unpackGainPair(std::uint64_t both) noexcept { - return {std::bit_cast(static_cast(both)), - std::bit_cast(static_cast(both>>32))}; + static constexpr int physicalLeft(std::uint32_t word) noexcept { + return static_cast(word&0xffffu); } - struct ChannelTarget final { - static_assert(std::atomic::is_always_lock_free, - "Realtime stereo mixer requires lock-free 64-bit atomic targets"); - std::atomic both{packGainPair(1.f,1.f)}; - float appliedL=1.f,appliedR=1.f; // audio thread only + static constexpr int physicalRight(std::uint32_t word) noexcept { + const auto right=static_cast((word>>16)&0xffffu); + return right==0xffff?-1:right; + } + struct SourceFade final { + std::uint32_t current=0,next=0; + int remaining=0; // AUDIO only; pending CONTROL target is one atomic }; struct SendTarget final { + static_assert(std::atomic::is_always_lock_free, + "Realtime SEND must never enter a hidden blocking atomic path"); std::atomic gain{1.f}; - float applied=1.f; + armix::dsp::RealtimeSlew64 applied{}; }; static constexpr std::size_t notScheduled=std::numeric_limits::max(); public: @@ -105,17 +126,58 @@ class DynamicPreparedMixerBlock final { bool setChannelMix(ChannelId id,float gain,float pan) noexcept { if(!id.value || !std::isfinite(gain) || gain<0.f || gain>4.f || !std::isfinite(pan) || pan< -1.f || pan>1.f)return false; - for(std::size_t i=0;i0.f?1.f-pan:1.f); - const float right=mono?gain*std::sqrt(.5f*(1.f+pan)): - gain*(pan<0.f?1.f+pan:1.f); - channelTargets_[i].both.store( - packGainPair(left,right),std::memory_order_release); - return true; - } - return false; + // Reuse the already-built ChannelId lookup; no O(N) scan on every + // rapid GUI fader tick, no callback hash lookup and no new allocation. + const auto found=controlIndex_.find(id.value); + if(found==controlIndex_.end())return false; + const auto i=found->second; + const auto gains=coefficients(lanes_[i].monoPan,gain,pan); + auto& target=channelTargets_[i]; + const auto old=Word::decode(target.state.load(std::memory_order_relaxed)); + // Serialized native CONTROL writer: keep mute/solo atomically paired + // with this fader/PAN target, never four separately loaded controls. + target.state.store(Word::encode(gains.left,gains.right,old.mute,old.solo), + std::memory_order_release); + return true; + } + // Canonical physical-pin validation shared by structural preflight and + // accepted realtime SOURCE changes. Never normalize an invalid draft + // into an apparently successful ACK by replacing it with old pins. + static bool validPhysicalPatch(int physicalInputs,int inputL,int inputR, + bool stereo) noexcept { + return physicalInputs>=0 && physicalInputs<=256 && + inputL>=0 && inputL=0 && inputRsecond]; + if(lane.role!=ChannelRole::input || lane.inputL<0 || + lane.inputStereo!=stereo)return false; // format requires APPLY + sourceTargets_[it->second].store(packPhysical(inputL,inputR), + std::memory_order_release); + return true; + } + bool setChannelMuteSolo(ChannelId id,bool mute,bool solo) noexcept { + if(!id.value)return false; + const auto it=controlIndex_.find(id.value); + if(it==controlIndex_.end())return false; + auto& target=channelTargets_[it->second]; + const auto old=Word::decode(target.state.load(std::memory_order_relaxed)); + target.state.store(Word::encode(old.left,old.right,mute,solo), + std::memory_order_release); + return true; } // Change gain ONLY on an existing parallel send (PRE or POST). // Exclusive primary OUT and source/destination edits stay structural. @@ -123,22 +185,24 @@ class DynamicPreparedMixerBlock final { bool preFader,float gain) noexcept { if(!source.value || !destination.value || !std::isfinite(gain) || gain<0.f || gain>4.f)return false; - for(const auto& lane:lanes_)if(lane.id==source) { - for(std::size_t e=lane.first;esecond]; + // Only that source's prepared CSR outgoing edges are examined. + // The public GUI can address arbitrary stable ChannelIds regardless + // of visual bank, strip position or hidden channels. + for(std::size_t e=lane.first;e byId; @@ -188,14 +253,8 @@ class DynamicPreparedMixerBlock final { } Lane lane; lane.id=row.id;lane.format=row.format;lane.role=row.role; - lane.enabled=!row.mute; - if(row.format==ProcessingFormat::mono) { - lane.gainL=row.faderLinear*std::sqrt(0.5f*(1.f-row.pan)); - lane.gainR=row.faderLinear*std::sqrt(0.5f*(1.f+row.pan)); - }else{ - lane.gainL=row.faderLinear*(row.pan>0.f?1.f-row.pan:1.f); - lane.gainR=row.faderLinear*(row.pan<0.f?1.f+row.pan:1.f); - } + lane.enabled=true; // keep prepared FX/tail alive across MUTE/SOLO + lane.monoPan=row.format==ProcessingFormat::mono; next.lanes_.push_back(lane); } if(main==notScheduled){error.fault=DynamicGraphFault::noMaster;return false;} @@ -207,14 +266,21 @@ class DynamicPreparedMixerBlock final { if(it==byId.end()){error={DynamicGraphFault::missingSource,patch.id};return false;} auto& lane=next.lanes_[it->second]; if(lane.role!=ChannelRole::input || lane.inputL!=-1 || - patch.inputL<0 || patch.inputL>=req.physicalInputs || - (patch.stereo && (patch.inputR<0 || - patch.inputR>=req.physicalInputs || patch.inputL==patch.inputR)) || - (!patch.stereo && patch.inputR!=-1)) { + !validPhysicalPatch(req.physicalInputs,patch.inputL, + patch.inputR,patch.stereo)) { error={DynamicGraphFault::invalidSource,patch.id};return false; } lane.inputL=patch.inputL;lane.inputR=patch.inputR; lane.inputStereo=patch.stereo; + // The channel SOURCE and the INSERT PROCESSING FORMAT are + // independent. Mono mic -> stereo VST still retains mono PAN. + if(!patch.stereo)lane.monoPan=true; + } + for(std::size_t i=0;i(solos[i]||forward[i]); } + next.initialAudible_.resize(rows.size()); for(std::size_t i=0;i( + !rows[i].mute && (!anySolo||solos[i]!=0)); + next.topologicalOrder_=order; // control-prepared, never RT sorted // One immutable render schedule serves BOTH logical output sinks. // Active monitor-only channels must not vanish merely because they @@ -352,20 +420,38 @@ class DynamicPreparedMixerBlock final { std::size_t slot=0; for(auto i:next.renderOrder_)next.lanes_[i].slot=slot++; next.scratch_.assign(active*2*frame,0.f); + next.sourceTargets_=std::make_unique[]>(rows.size()); + next.sourceFades_=std::make_unique(rows.size()); + for(std::size_t i=0;i(rows.size()); + next.blockTargets_.resize(rows.size()); + next.soloAncestors_.assign(rows.size(),0); + next.soloDescendants_.assign(rows.size(),0); for(std::size_t i=0;i(next.edges_.size()); for(std::size_t e=0;e bool process(const float* const* physical,int physicalCount, float* outputL,float* outputR,int frames,Fx&& processFx, - float* monitorL=nullptr,float* monitorR=nullptr) noexcept { + float* monitorL=nullptr,float* monitorR=nullptr, + std::span channelPeaksL={}, + std::span channelPeaksR={}) noexcept { if(frames<=0 || !outputL || !outputR)return false; + if(channelPeaksL.size()!=channelPeaksR.size() || + (!channelPeaksL.empty() && channelPeaksL.size()(capacity_); + // One canonical 64-bit target per logical channel, read once/block. + // Realtime SOLO closure reuses CONTROL-prepared order and CSR edges. + // No allocation, mutex, VST3 lease/reference, sorting or worker on RT. + bool anySolo=false; + for(std::size_t i=0;i(state.solo&&!state.mute); + soloAncestors_[i]=root;soloDescendants_[i]=root; + anySolo|=root!=0; + } + if(anySolo) { + for(auto it=topologicalOrder_.rbegin();it!=topologicalOrder_.rend();++it){ + const auto i=*it; + for(std::size_t e=lanes_[i].first;e=0 && physical && lane.inputL=0 && physical) { + auto& fade=sourceFades_[i]; + const auto desired=sourceTargets_[i].load(std::memory_order_acquire); + if(fade.remaining==0 && desired!=fade.current) { + fade.next=desired;fade.remaining=armix::dsp::RealtimeSlew64::samples; + } + // Resolve each verified physical pair ONCE per block; the + // inner sample loop only blends already-addressed PCM. + const auto resolve=[&](std::uint32_t pair,int side) noexcept + ->const float* { + const int a=physicalLeft(pair),b=physicalRight(pair); + if(a<0||a>=physicalCount||!physical[a])return nullptr; + if(lane.inputStereo){ + if(b<0||b>=physicalCount||!physical[b])return nullptr; + return side==0?physical[a]:physical[b]; + } + return physical[a]; + }; + const float* oldL=resolve(fade.current,0); + const float* oldR=resolve(fade.current,1); + const float* newL=fade.remaining?resolve(fade.next,0):oldL; + const float* newR=fade.remaining?resolve(fade.next,1):oldR; + if(fade.remaining==0) { + if(oldL&&oldR) + for(int f=0;f(fade.remaining-1)* + (1.f/static_cast(armix::dsp::RealtimeSlew64::samples)); + const float beforeL=oldL?oldL[f]:0.f; + const float beforeR=oldR?oldR[f]:0.f; + const float afterL=newL?newL[f]:0.f; + const float afterR=newR?newR[f]:0.f; + l[f]+=beforeL+(afterL-beforeL)*alpha; + r[f]+=beforeR+(afterR-beforeR)*alpha; + --fade.remaining; + if(fade.remaining==0){ + fade.current=fade.next; + // New CONTROL requests are consumed next block; + // never change the source mid-sample. + oldL=newL;oldR=newR; + for(int k=f+1;k(ramp); - float applied=target.applied; + // Coalesced, callback-continuous 64 SAMPLE slew. A 4-frame + // ASIO callback advances only 4/64 of the requested change. + target.applied.retarget(goal); for(int f=0;f(ramp); - const float stepR=(goalR-controls.appliedR)/static_cast(ramp); - float currentL=controls.appliedL,currentR=controls.appliedR; + // Left and right use ONE atomically read stereo goal. Ramp state + // survives variable hardware callback sizes and gesture reversals. + controls.appliedL.retarget(goalL); + controls.appliedR.retarget(goalR); + float observedL=0.f,observedR=0.f; for(int f=0;f(ramp); - float applied=target.applied; + // Coalesced, callback-continuous 64 SAMPLE slew. A 4-frame + // ASIO callback advances only 4/64 of the requested change. + target.applied.retarget(goal); for(int f=0;f lanes_; + std::unordered_map controlIndex_; // CONTROL only std::vector edges_; - std::vector renderOrder_; + std::vector renderOrder_,topologicalOrder_; + std::vector initialAudible_,soloAncestors_,soloDescendants_; + std::vector blockTargets_; // all allocated before RT std::vector scratch_; std::unique_ptr channelTargets_; + std::unique_ptr[]> sourceTargets_; + std::unique_ptr sourceFades_; std::unique_ptr sendTargets_; std::size_t main_=notScheduled,monitor_=notScheduled; bool mainMonoAfterFx_=false; - int capacity_=0; + int capacity_=0,physicalInputs_=0; }; } // namespace armix::mixer diff --git a/engine/core/LegacyLiveGraphMigration.h b/engine/core/LegacyLiveGraphMigration.h index 2358e6724..54a06c3cc 100644 --- a/engine/core/LegacyLiveGraphMigration.h +++ b/engine/core/LegacyLiveGraphMigration.h @@ -44,6 +44,9 @@ struct LegacyMigratedGraph final { 32u*1024u*1024u,8u,static_cast(maxChannelSends+maxAuxSends+2)}}; DynamicPreparedMixerBlock pcm{}; LegacyChannelIds ids{}; + // Exact verified physical SOURCE request, preserved for a single native + // admission. Never reconstruct callback port ordinals from a GUI draft. + DynamicGraphRequest request{}; std::uint64_t revision=0; }; @@ -187,6 +190,7 @@ class LegacyGraphMigration final { next.pcm,error.dynamic)){ error.fault=LegacyMigrationFault::invalidDynamicGraph;return false; } + next.request=std::move(request); next.revision=next.roster.revision(); destination=std::move(next); // publish only after caller's native MUTE/epoch ACK return true; diff --git a/engine/core/LiveChannelFxGraph.h b/engine/core/LiveChannelFxGraph.h index fff61df01..281b172f9 100644 --- a/engine/core/LiveChannelFxGraph.h +++ b/engine/core/LiveChannelFxGraph.h @@ -159,12 +159,24 @@ class LiveChannelFxGraph final { for(float v:gains)if(!std::isfinite(v)||v<0.f||v>1.f)return false; monitorLeft_=left;monitorRight_=right; monitorGains_=gains;monitorEnabled_=true; + for(int i=0;iprepareMonitorGains(gains); // unpublished graph/control only return true; } bool monitorEnabled() const noexcept{return monitorEnabled_;} int monitorOutputLeft() const noexcept{return monitorLeft_;} int monitorOutputRight() const noexcept{return monitorRight_;} const std::array& monitorGains() const noexcept{return monitorGains_;} + // Existing verified independent MONITOR source lane. Only the scalar + // changes; MAIN stays untouched, no graph rebuild or vendor lifecycle. + bool setMonitorSendGain(int lane,float gain) noexcept { + if(!monitorEnabled_||lane<0||lane>=fxSlots|| + !std::isfinite(gain)||gain<0.f||gain>1.f)return false; + monitorGainTargets_[lane].store(gain,std::memory_order_release); + monitorGains_[lane]=gain; // CONTROL-only Show/status readback + return true; + } bool switchPhysicalSource(int strip,SourceMode mode,int left,int right) noexcept { return block_&&block_->setPhysicalSource(strip,mode,left,right); } @@ -173,9 +185,11 @@ class LiveChannelFxGraph final { bool setAuxBusGain(int bus,float gain) noexcept { return block_&&block_->setAuxBusGain(bus,gain); } + bool setAuxSendGain(int source,int bus,SendTap tap,float gain) noexcept { + return block_ && block_->setAuxSendGain(source,bus,tap,gain); + } bool setAuxSendGain(int source,int bus,float gain) noexcept { - return block_ && block_->setAuxSendGain( - source,bus,SendTap::postFader,gain); + return setAuxSendGain(source,bus,SendTap::postFader,gain); } int activeInserts() const noexcept{return activeInserts_;} bool setStripControl(int channel,float gain,float pan, @@ -292,7 +306,8 @@ class LiveChannelFxGraph final { if(monitorEnabled_ && (!monitorL||!monitorR))return false; return block_->process(physical,inputs,left,right,frames,channelFx,levels, &controls_,monitorEnabled_?&monitorGains_:nullptr, - monitorL,monitorR); + monitorL,monitorR, + monitorEnabled_?&monitorGainTargets_:nullptr); } private: @@ -305,6 +320,7 @@ class LiveChannelFxGraph final { int mainOutputLeft_=0,mainOutputRight_=1; int monitorLeft_=-1,monitorRight_=-1; bool monitorEnabled_=false; - std::array monitorGains_{}; + std::array monitorGains_{}; // control-only accepted readback + std::array,fxSlots> monitorGainTargets_{}; // RT read }; } // namespace armix::mixer diff --git a/engine/core/NativeRenderAuthority.h b/engine/core/NativeRenderAuthority.h new file mode 100644 index 000000000..03d81b64b --- /dev/null +++ b/engine/core/NativeRenderAuthority.h @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include + +// Production render ownership, never an audio engine or a second callback. +// The approved GUI can project ONE native engine. Until the full ChannelId +// VST/editor/Show cutover is admitted, only the existing M4 route owns PCM. +// The legacy stereo path is diagnostic-only, never a hidden fallback. +namespace armix::mixer { +enum class NativeRenderOwner : std::uint8_t { + failSilentUnpatched, + acceptedM4Session, + isolatedDiagnostic +}; + +struct NativeRenderAuthority final { + static constexpr NativeRenderOwner select( + bool normalAudio, bool m4SessionActive) noexcept { + // A verified accepted M4 route always owns the callback: a diagnostic + // mode must never start processing a second stereo FX chain over it. + if(m4SessionActive)return NativeRenderOwner::acceptedM4Session; + if(normalAudio)return NativeRenderOwner::failSilentUnpatched; + return NativeRenderOwner::isolatedDiagnostic; + } + static constexpr bool isProduction(NativeRenderOwner owner) noexcept { + return owner==NativeRenderOwner::acceptedM4Session; + } + static constexpr bool mayRunDiagnostic(NativeRenderOwner owner) noexcept { + return owner==NativeRenderOwner::isolatedDiagnostic; + } +}; +static_assert(NativeRenderAuthority::select(true,false)== + NativeRenderOwner::failSilentUnpatched); +static_assert(NativeRenderAuthority::select(true,true)== + NativeRenderOwner::acceptedM4Session); +static_assert(NativeRenderAuthority::select(false,true)== + NativeRenderOwner::acceptedM4Session); +static_assert(NativeRenderAuthority::select(false,false)== + NativeRenderOwner::isolatedDiagnostic); +} // namespace armix::mixer diff --git a/engine/core/PreparedMixerBlock.h b/engine/core/PreparedMixerBlock.h index 7d58a411f..7f887810b 100644 --- a/engine/core/PreparedMixerBlock.h +++ b/engine/core/PreparedMixerBlock.h @@ -2,6 +2,8 @@ #pragma once #include "ChannelSendPlan.h" #include "AuxBusPlan.h" +#include "RealtimeSlew64.h" +#include "RealtimeStereoControlWord.h" #include #include #include @@ -124,12 +126,25 @@ struct PreparedRenderGraph final { // once per block and interpolates into fixed strip scratch buffers. The // immutable topology (DAG/physical ports/FX ownership) is never rebuilt for // ordinary fader, pan, MUTE, or SOLO changes. +// One packed uint64 captures both stereo coefficients AND MUTE/SOLO in one +// coherent block-boundary atomic load. A WebView gesture can never publish +// the left level from edit N and right/mute/solo from edit N+1. +// Two 31-bit fixed-point gains cover 0..4 with better-than-float readback +// precision and leave 2 bits for MUTE/SOLO. All quantization is CONTROL-only. class RealtimeStripControls final { public: - struct Target { - std::atomic left{1.f},right{1.f}; - std::atomic mute{false},solo{false}; - }; + using Word=armix::dsp::RealtimeStereoControlWord; + static constexpr std::uint64_t gainMask=Word::gainMask; + static constexpr std::uint64_t mutedBit=Word::mutedBit; + static constexpr std::uint64_t soloBit=Word::soloBit; + static constexpr std::uint64_t unity=Word::unity; + using Snapshot=Word::Snapshot; + struct Target final {std::atomic state{unity|(unity<<31)};}; + static std::uint64_t quantize(float v) noexcept {return Word::quantize(v);} + static std::uint64_t encode(float l,float r,bool mute,bool solo) noexcept { + return Word::encode(l,r,mute,solo); + } + static Snapshot decode(std::uint64_t v) noexcept {return Word::decode(v);} bool set(int strip,float gain,float pan,bool mono,bool mute,bool solo) noexcept { if(strip<0||strip>=stripCount||!std::isfinite(gain)||gain<0.f||gain>4.f|| !std::isfinite(pan)||pan< -1.f||pan>1.f)return false; @@ -137,18 +152,22 @@ class RealtimeStripControls final { gain*(pan>0.f?1.f-pan:1.f); const float right=mono?gain*std::sqrt(0.5f*(1.f+pan)): gain*(pan<0.f?1.f+pan:1.f); - auto& c=targets_[strip]; - c.left.store(left,std::memory_order_relaxed); - c.right.store(right,std::memory_order_relaxed); - c.mute.store(mute,std::memory_order_relaxed); - c.solo.store(solo,std::memory_order_relaxed); + targets_[strip].state.store(encode(left,right,mute,solo), + std::memory_order_release); return true; } + // Called on the unpublished graph's CONTROL constructor. Preserve flags + // for safe reuse, but ship a single coherent stereo snapshot. void setPreparedCoefficients(int strip,float left,float right) noexcept { - targets_[strip].left.store(left,std::memory_order_relaxed); - targets_[strip].right.store(right,std::memory_order_relaxed); + if(strip<0||strip>=stripCount)return; + const auto old=targets_[strip].state.load(std::memory_order_relaxed); + targets_[strip].state.store( + encode(left,right,(old&mutedBit)!=0,(old&soloBit)!=0), + std::memory_order_relaxed); + } + Snapshot read(int strip) const noexcept { + return decode(targets_[strip].state.load(std::memory_order_acquire)); } - const Target& at(int strip) const noexcept{return targets_[strip];} private: std::array targets_{}; }; @@ -190,11 +209,14 @@ class PreparedMixerBlock final { const float v=plan_.aux.edges[e].initialGain; auxTarget_[e].store(v,std::memory_order_relaxed); auxApplied_[e]=v; + auxGoal_[e]=v; + auxRampRemaining_[e]=0; } for(int b=0;b=stripCount||bus<0||bus>=auxBusCount|| - tap!=SendTap::postFader||!std::isfinite(gain)||gain<0.f||gain>1.f) + (tap!=SendTap::preFader&&tap!=SendTap::postFader)|| + !std::isfinite(gain)||gain<0.f||gain>1.f) return false; for(int e=plan_.aux.offset[source];e4.f)return false; auxBusTarget_[bus].store(gain,std::memory_order_release); + auxBusAutomationActive_.store(true,std::memory_order_release); return true; } float auxBusGain(int bus) const noexcept { @@ -271,6 +298,18 @@ class PreparedMixerBlock final { return -1.f; } + // CONTROL only, before publishing a MONITOR-enabled prepared graph. + // Initial send levels start at their approved values, not an audible + // ramp from zero when a device first arms its independent MONITOR bus. + void prepareMonitorGains( + const std::array& gains) noexcept { + for(int i=0;i* monitorGains=nullptr, - float* monitorL=nullptr,float* monitorR=nullptr) noexcept { + float* monitorL=nullptr,float* monitorR=nullptr, + const std::array,stripCount+auxBusCount>* + liveMonitorGains=nullptr) noexcept { static_assert(std::is_nothrow_invocable_v, "DSP hook must be noexcept and realtime bounded"); if (observed) *observed={}; @@ -302,6 +343,19 @@ class PreparedMixerBlock final { if(monitorR && monitorR!=monitorL)std::fill_n(monitorR,frames,0.f); return false; } + // Also support direct PreparedMixerBlock users (no JUCE FxGraph + // wrapper): the first real MONITOR render starts at its approved + // levels, never with a fake 64-frame fade from an unpatched zero. + if(monitorL && !monitorPrimed_) { + for(int i=0;i currentControls{}; bool anySolo=false; - if(live)for(int strip=0;stripat(strip).solo.load(std::memory_order_relaxed) && - !live->at(strip).mute.load(std::memory_order_relaxed); + if(live)for(int strip=0;stripread(strip); + anySolo |= state.solo && !state.mute; + } for(int k=0;kat(strip); - routeAudible=!target.mute.load(std::memory_order_relaxed); + const auto& target=currentControls[strip]; + routeAudible=!target.mute; if(routeAudible&&anySolo) { routeAudible=false; for(int j=0;jat(j); - if(s.solo.load(std::memory_order_relaxed) && - !s.mute.load(std::memory_order_relaxed) && + const auto& s=currentControls[j]; + if(s.solo && !s.mute && (j==strip||graph.sends.upstreamOf(strip,j)|| graph.sends.upstreamOf(j,strip))) { routeAudible=true;break; } } } - gl=target.left.load(std::memory_order_relaxed); - gr=target.right.load(std::memory_order_relaxed); + gl=target.left; + gr=target.right; // A MUTE or SOLO transition must also silence PRE sends. // Smooth the pre-send source gate over <=64 samples; it does // not create/restart FX, drivers, nodes or send topology. const float targetGate=routeAudible?1.f:0.f; if(!rampPrimed_[strip]) { - preGate_[strip]=targetGate; - lastGainL_[strip]=gl; - lastGainR_[strip]=gr; + preSlew_[strip].reset(targetGate); + gainSlewL_[strip].reset(gl); + gainSlewR_[strip].reset(gr); rampPrimed_[strip]=true; } - const int ramp=std::min(frames,64); - const float dGate=(targetGate-preGate_[strip])/ramp; - float gate=preGate_[strip]; + // Same canonical 64-SAMPLE slew as ChannelId. No division in + // the actual audio-sample loop, even at 4-frame ASIO quantum. + auto& gate=preSlew_[strip]; + gate.retarget(targetGate); for(int f=0;f0.f) { - monitorBusL[f]+=l[f]*monitorGain; - monitorBusR[f]+=r[f]*monitorGain; + l[f]*=slewL.next(); + r[f]*=slewR.next(); + if(monitorBusL) { + const float gain=nextMonitorGain(strip); + monitorBusL[f]+=l[f]*gain; + monitorBusR[f]+=r[f]*gain; } const float sampleL=std::abs(l[f]), sampleR=std::abs(r[f]); peakL=std::max(peakL,sampleL); @@ -453,13 +527,13 @@ class PreparedMixerBlock final { masterL_[f]+=l[f];masterR_[f]+=r[f]; } } - lastGainL_[strip]=gl;lastGainR_[strip]=gr; }else for(int f=0;f0.f) { - monitorBusL[f]+=l[f]*monitorGain; - monitorBusR[f]+=r[f]*monitorGain; + if(monitorBusL) { + const float gain=nextMonitorGain(strip); + monitorBusL[f]+=l[f]*gain; + monitorBusR[f]+=r[f]*gain; } const float sampleL=std::abs(l[f]), sampleR=std::abs(r[f]); peakL=std::max(peakL,sampleL); @@ -477,7 +551,13 @@ class PreparedMixerBlock final { } graph.sends.dispatch(strip,SendTap::postFader,l,r, left_.data(),right_.data(),frames); - if(live)dispatchLiveAux(strip,SendTap::postFader,l,r,frames); + // Before operator automation, preserve the original + // precompiled immutable AUX dispatch (fast path, no atomics). + // Once the message thread publishes a changed send target, + // the SAME callback switches to one live PRE/POST processor + // which follows 64-sample gains across varying block sizes. + if(auxAutomationActive_.load(std::memory_order_acquire)) + dispatchLiveAux(strip,SendTap::postFader,l,r,frames); else graph.aux.dispatch(strip,SendTap::postFader,l,r, auxLeft_.data(),auxRight_.data(),frames); } @@ -490,19 +570,46 @@ class PreparedMixerBlock final { float* const l=auxLeft_[b],* const r=auxRight_[b]; processFx(stripCount+b,l,r,frames); float peak=0.f; - const float monitorGain=monitorL?(*monitorGains)[stripCount+b]:0.f; - const float target=live + const int monitorLane=stripCount+b; + if(monitorBusL) { + const float next=liveMonitorGains + ?(*liveMonitorGains)[monitorLane].load(std::memory_order_acquire) + :(*monitorGains)[monitorLane]; + if(next!=monitorGoal_[monitorLane]) { + monitorGoal_[monitorLane]=next; + monitorRemaining_[monitorLane]=64; + } + } + // Original zero-automation fast path remains one scalar + // multiplication; only a real operator AUX fader edit enables + // the sample-continuous 64-frame de-zipper across 4/8/16-frame + // callbacks. The fader scales the return AFTER hosted AUX VST3 + // for both MAIN and independent MONITOR, not source dry PCM. + // AUX automation is independent of channel fader/MUTE control. + // A caller may automate AUX sends/returns without supplying a + // RealtimeStripControls bank; keep one canonical DSP target plane. + const bool automated=auxBusAutomationActive_.load( + std::memory_order_acquire); + const float target=automated ?auxBusTarget_[b].load(std::memory_order_acquire):bus.gain; - const float start=live?auxBusApplied_[b]:bus.gain; - const int ramp=std::min(frames,64); - const float step=(target-start)/static_cast(ramp); - float current=start; + if(automated && target!=auxBusGoal_[b]) { + auxBusGoal_[b]=target; + auxBusRemaining_[b]=64; + } + float current=automated?auxBusApplied_[b]:bus.gain; + int remaining=automated?auxBusRemaining_[b]:0; for(int f=0;f0) { + current+=(target-current)/static_cast(remaining); + --remaining; + } else current=target; const float vl=l[f]*current,vr=r[f]*current; - if(!bus.mute && monitorGain>0.f) { - monitorBusL[f]+=vl*monitorGain; - monitorBusR[f]+=vr*monitorGain; + if(monitorBusL) { + const float gain=nextMonitorGain(monitorLane); + if(!bus.mute) { + monitorBusL[f]+=vl*gain; + monitorBusR[f]+=vr*gain; + } } peak=std::max(peak,std::max(std::abs(vl),std::abs(vr))); if(bus.toMaster && !bus.mute){ @@ -510,7 +617,10 @@ class PreparedMixerBlock final { masterR_[f]+=vr; } } - if(live)auxBusApplied_[b]=target; + if(automated) { + auxBusApplied_[b]=remaining==0?target:current; + auxBusRemaining_[b]=remaining; + } if(observed)observed->auxPeak[b]=peak; } processFx(-1,masterL_,masterR_,frames); @@ -532,6 +642,18 @@ class PreparedMixerBlock final { return true; } private: + // Callback exclusive: monitor gain follows 64 sample steps regardless of + // 4/16/32/512-frame hardware buffers; no second effect render. + float nextMonitorGain(int lane) noexcept { + auto& applied=monitorApplied_[lane]; + auto& remaining=monitorRemaining_[lane]; + const float target=monitorGoal_[lane]; + if(remaining>0) { + applied+=(target-applied)/static_cast(remaining); + --remaining; + } else applied=target; + return applied; + } static constexpr std::uint32_t invalidSourcePair=0xffffffffu; static constexpr std::uint32_t packSourcePair(int left,int right) noexcept { return static_cast(left)| @@ -552,22 +674,31 @@ class PreparedMixerBlock final { if(edge.tap!=tap)continue; float* dl=auxLeft_[edge.bus],* dr=auxRight_[edge.bus]; if(!dl||!dr)continue; + // Preserve a 64-SAMPLE de-zipper across arbitrarily small / + // variable callbacks. PRE and POST use the same ramp; no + // frame-size-dependent jump, heap, lock, or graph recompilation. const float target=auxTarget_[e].load(std::memory_order_acquire); - const float start=auxApplied_[e]; - const int ramp=std::min(frames,64); - if(std::abs(target-start)<1.e-7f){ + if(target!=auxGoal_[e]) { + auxGoal_[e]=target; + auxRampRemaining_[e]=64; + } + float current=auxApplied_[e]; + int remaining=auxRampRemaining_[e]; + if(remaining==0) { const float gl=target*edge.leftPan,gr=target*edge.rightPan; for(int f=0;f(ramp); - float current=start; - for(int f=0;f0) { + current+=(target-current)/static_cast(remaining); + --remaining; + }else current=target; dl[f]+=l[f]*current*edge.leftPan; dr[f]+=r[f]*current*edge.rightPan; } } - auxApplied_[e]=target; + auxApplied_[e]=remaining==0?target:current; + auxRampRemaining_[e]=remaining; } } static bool validCapacity(int f) noexcept {return f>0 && f<=hardFrameLimit;} @@ -577,13 +708,24 @@ class PreparedMixerBlock final { std::array left_{}; std::array right_{}; std::array auxLeft_{},auxRight_{}; - std::array preGate_{},lastGainL_{},lastGainR_{}; + std::array preSlew_{}, + gainSlewL_{},gainSlewR_{}; // audio callback only, no heap std::array,stripCount> physicalTarget_{}; std::array physicalBlend_{}; + // OFF until any native SET_SEND_LEVEL. Audio callback reads only; + // control-thread publication is monotonic for this prepared graph. + std::atomic auxAutomationActive_{false}; std::array,maxAuxSends> auxTarget_{}; - std::array auxApplied_{}; // callback thread exclusive + std::array auxApplied_{},auxGoal_{}; // callback exclusive + std::array auxRampRemaining_{}; + std::array monitorApplied_{},monitorGoal_{}; + std::array monitorRemaining_{}; + bool monitorPrimed_=false; // sole audio producer except prepublish seeding std::array,auxBusCount> auxBusTarget_{}; - std::array auxBusApplied_{}; // callback thread exclusive + std::array auxBusApplied_{},auxBusGoal_{}; + std::array auxBusRemaining_{}; + std::atomic auxBusAutomationActive_{false}; + // State exclusively advanced in the single JUCE audio callback. std::array rampPrimed_{}; float* masterL_=nullptr; float* masterR_=nullptr; diff --git a/engine/core/RealtimeRenderPermit.h b/engine/core/RealtimeRenderPermit.h new file mode 100644 index 000000000..9eb141a1b --- /dev/null +++ b/engine/core/RealtimeRenderPermit.h @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include + +// One gate across the real installed M4 renderer and the future ChannelId +// publisher. If a misbehaving device/backend overlaps callbacks, do not +// concurrently write prepared scratch or process the same VST3 instance. +// Nonblocking: failed acquisition is SILENCE, never a spin, mutex or wait. +// RAII releases on every fail-closed return after entering the DSP block. +namespace armix::rt { +class RealtimeRenderPermit final { +public: + explicit RealtimeRenderPermit(std::atomic_flag& gate) noexcept + : gate_(gate), + entered_(!gate_.test_and_set(std::memory_order_acquire)) {} + RealtimeRenderPermit(const RealtimeRenderPermit&)=delete; + RealtimeRenderPermit& operator=(const RealtimeRenderPermit&)=delete; + ~RealtimeRenderPermit() noexcept { + if(entered_)gate_.clear(std::memory_order_release); + } + explicit operator bool() const noexcept {return entered_;} +private: + std::atomic_flag& gate_; + bool entered_; +}; +} // namespace armix::rt diff --git a/engine/core/RealtimeSlew64.h b/engine/core/RealtimeSlew64.h new file mode 100644 index 000000000..3e4e6fc2a --- /dev/null +++ b/engine/core/RealtimeSlew64.h @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +// One reusable fixed-duration DSP ramp for fader, pan and PRE/POST SEND. +// CONTROL coalesces to one latest atomic goal per callback; AUDIO owns +// current/remaining. No heap, lock, division or time API in the sample loop. +// A new gesture during a ramp starts at the *audibly applied* coefficient. +namespace armix::dsp { +struct RealtimeSlew64 final { + static constexpr int samples=64; + float current=1.f; + float goal=1.f; + float delta=0.f; + int remaining=0; + + void reset(float initial) noexcept { + current=goal=initial; + delta=0.f; + remaining=0; + } + void retarget(float requested) noexcept { + if(requested==goal)return; + goal=requested; + remaining=samples; + delta=(goal-current)*(1.f/static_cast(samples)); + } + float next() noexcept { + if(remaining>0) { + --remaining; + if(remaining==0)current=goal; // exact steady-state endpoint + else current+=delta; + } + return current; + } +}; +} // namespace armix::dsp diff --git a/engine/core/RealtimeStereoControlWord.h b/engine/core/RealtimeStereoControlWord.h new file mode 100644 index 000000000..a9b170166 --- /dev/null +++ b/engine/core/RealtimeStereoControlWord.h @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +// One canonical packed stereo gain / MUTE / SOLO word for M4 and ChannelId. +// Only serialized CONTROL encodes; AUDIO loads once/block. 31+31-bit gains +// and 2 bits of gating state; 64-bit lock-free atomics prevent torn decisions. +namespace armix::dsp { +struct RealtimeStereoControlWord final { + static constexpr std::uint64_t gainMask=(std::uint64_t{1}<<31)-1; + static constexpr std::uint64_t mutedBit=std::uint64_t{1}<<62; + static constexpr std::uint64_t soloBit=std::uint64_t{1}<<63; + static constexpr std::uint64_t unity=536870912ULL; + static_assert(std::atomic::is_always_lock_free, + "Realtime 64-bit control must never lock"); + struct Snapshot final { + float left=1.f,right=1.f; + bool mute=false,solo=false; + }; + static std::uint64_t quantize(float value) noexcept { + return static_cast( + static_cast(value)*(static_cast(gainMask)/4.)+.5); + } + static std::uint64_t encode(float left,float right,bool mute,bool solo) noexcept { + return quantize(left)|(quantize(right)<<31)| + (mute?mutedBit:0ULL)|(solo?soloBit:0ULL); + } + static Snapshot decode(std::uint64_t state) noexcept { + constexpr double scale=4./static_cast(gainMask); + return {static_cast(static_cast(state&gainMask)*scale), + static_cast(static_cast((state>>31)&gainMask)*scale), + (state&mutedBit)!=0,(state&soloBit)!=0}; + } +}; +} // namespace armix::dsp diff --git a/engine/core/UnifiedLegacyProductionAdmission.h b/engine/core/UnifiedLegacyProductionAdmission.h new file mode 100644 index 000000000..37d431806 --- /dev/null +++ b/engine/core/UnifiedLegacyProductionAdmission.h @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "LegacyLiveGraphMigration.h" +#include "DynamicChannelFxLeaseBank.h" +#include "DynamicNativeSessionPublisher.h" +#include +#include +#include +#include +#include +#include + +// M-U1: full M4 10CH + 4 AUX + MONITOR PCM and real VST leases are admitted +// as ONE identity-preserving dynamic session. No extra audio callback. +// This is CONTROL-only preparation; the physical callback cutover is a +// separate safety transaction and must select only ONE renderer. +// Occupied CH1 external/Orbit may be admitted ONLY with its original +// processor/editor owner and validated ChannelId; never silently drop VST. +namespace armix::mixer { +struct VerifiedNativeOutputs final { + int activeOutputChannels=0; // EXACT current enabled callback output count + int mainL=-1,mainR=-1,monitorL=-1,monitorR=-1; + bool monitorEnabled=false; + bool valid() const noexcept { + if(activeOutputChannels<2||activeOutputChannels>256 || + mainL<0||mainR<0||mainL>=activeOutputChannels|| + mainR>=activeOutputChannels||mainL==mainR)return false; + if(!monitorEnabled)return monitorL==-1&&monitorR==-1; + return monitorL>=0&&monitorR>=0&& + monitorL fxOwners{}; + VerifiedNativeOutputs hardware{}; + std::uint64_t deviceEpoch=0,pcmRevision=0; + + // E2 native GUI seam: bind a VST3 gesture to the CURRENT accepted PCM + // publisher, never just a retained old FX lease. Old editor handles may + // stay alive while a graph is retired, but stale controls cannot mutate + // a processor now referenced by a newer admitted graph. CONTROL only. + bool matches(const DynamicNativeSessionPublisher& publisher, + std::uint64_t epoch,std::uint64_t revision) const noexcept { + return epoch!=0 && revision!=0 && epoch==deviceEpoch && + revision==pcmRevision && fxOwners && + fxOwners->epoch()==epoch && fxOwners->revision()==revision && + publisher.acceptedRevision()==revision && + publisher.acceptedRouting(epoch,revision)!=nullptr; + } + bool setFxBypass(const DynamicNativeSessionPublisher& publisher, + std::uint64_t epoch,std::uint64_t revision, + ChannelId id,std::size_t slot, + const juce::String& instanceId,bool bypass) const noexcept { + return matches(publisher,epoch,revision) && + fxOwners->setInsertBypass(epoch,revision,id,slot, + instanceId,bypass); + } + DynamicChannelFxLeaseBank::Lease leaseFxEditor( + const DynamicNativeSessionPublisher& publisher, + std::uint64_t epoch,std::uint64_t revision,ChannelId id, + std::size_t slot,const juce::String& instanceId) const noexcept { + if(!matches(publisher,epoch,revision))return {}; + return fxOwners->leaseEditor(epoch,revision,id,slot,instanceId); + } +}; +class UnifiedLegacyProductionAdmission final { +public: + enum class Fault : std::uint8_t { + none,invalidOutputPins,staleHardware,outputArmed, + legacyCh1ExternalFx,staleFxGraph,legacyGraphInvalid, + fxLeaseInvalid,nativeRejected + }; + struct Report final { + Fault fault=Fault::none; + LegacyMigrationError migration{}; + DynamicChannelFxLeaseBank::Fault fx=DynamicChannelFxLeaseBank::Fault::none; + DynamicNativeSessionPublisher::CommitResult native{}; + bool ok() const noexcept {return fault==Fault::none;} + }; + + // Must be invoked on the SAME serialized M4 native control executor as + // hardware APPLY, Show capture and editor state. Prior accepted graph, + // leases and user outputs stay intact on any rejection. + static Report compileAndCommit( + const ChannelRoutingConfig& channels, + std::span callbackOrderedPhysicalPorts, + const SendRequest& sends,const AuxBusRequest& aux, + const std::array& monitorGains, + const LiveChannelFxGraph& acceptedM4Fx, + bool legacyExternalCh1FxActive, + const VerifiedNativeOutputs& hardware, + int maxFrames,std::size_t scratchBudget, + std::uint64_t expectedPcmRevision, + std::uint64_t deviceEpoch,std::uint64_t currentHardwareEpoch, + bool allOutputsDisarmed, + DynamicNativeSessionPublisher& publisher, + UnifiedLegacyAccepted& accepted, + DynamicChannelFxLeaseBank::ExternalLease externalCh1={}) { + Report result; + if(!hardware.valid() || + hardware.monitorEnabled!=acceptedM4Fx.monitorEnabled() || + hardware.mainL!=acceptedM4Fx.mainOutputLeft() || + hardware.mainR!=acceptedM4Fx.mainOutputRight() || + (hardware.monitorEnabled && + (hardware.monitorL!=acceptedM4Fx.monitorOutputLeft()|| + hardware.monitorR!=acceptedM4Fx.monitorOutputRight()))) { + result.fault=Fault::invalidOutputPins;return result; + } + if(!deviceEpoch || deviceEpoch!=currentHardwareEpoch) { + result.fault=Fault::staleHardware;return result; + } + if(!allOutputsDisarmed) { + result.fault=Fault::outputArmed;return result; + } + // A real legacy CH1 Graph owner may have no ChannelId until the + // accepted sparse-port topology has been compiled. Validate its + // lifetime/function now; bind its exact id from the compiled graph, + // not from a guessed strip index or WebView ordinal. + if(legacyExternalCh1FxActive!=externalCh1.populated() || + (legacyExternalCh1FxActive && + (!externalCh1.owner || externalCh1.context!=externalCh1.owner.get() || + !externalCh1.render))) { + result.fault=Fault::legacyCh1ExternalFx;return result; + } + // FxInstance owns one already-prepared stereo block. Do not let the + // dynamic callback deliver a larger quantum and silently bypass it. + if(maxFrames<1||maxFrames>acceptedM4Fx.capacity()|| + maxFrames>acceptedM4Fx.maxFramesPerPlugin()) { + result.fault=Fault::staleFxGraph;return result; + } + if(expectedPcmRevision!=publisher.acceptedRevision()) { + result.fault=Fault::nativeRejected; + result.native.fault=DynamicNativeSessionPublisher::Fault::staleRevision; + return result; + } + LegacyMigratedGraph candidate; + if(!LegacyGraphMigration::compile( + channels,callbackOrderedPhysicalPorts,sends,aux, + hardware.monitorEnabled,monitorGains,maxFrames,scratchBudget, + candidate,result.migration)) { + result.fault=Fault::legacyGraphInvalid;return result; + } + using Bank=DynamicChannelFxLeaseBank; + if(externalCh1.populated()) { + if((externalCh1.id.value && + externalCh1.id!=candidate.ids.inputs[0]) || + acceptedM4Fx.insertsOn(0)!=0) { + result.fault=Fault::legacyCh1ExternalFx;return result; + } + // The native compiler is the ONLY authority for stable ids. + // The original CH1 owner can never become an arbitrary bus. + externalCh1.id=candidate.ids.inputs[0]; + } + std::array lanes{}; + for(int i=0;iformat, + acceptedM4Fx,lanes[i])) { + result.fault=Fault::fxLeaseInvalid; + result.fx=Bank::Fault::missingLegacyIdentity; + return result; + } + } + Bank bank; + result.fx=Bank::prepare(deviceEpoch,expectedPcmRevision+1,lanes,bank, + std::move(externalCh1)); + if(result.fx!=Bank::Fault::none) { + result.fault=Fault::fxLeaseInvalid;return result; + } + auto owner=std::make_shared(std::move(bank)); + DynamicNativeSessionPublisher::FxPlan plan; + plan.owner=std::static_pointer_cast(owner); + plan.context=owner.get(); + plan.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(ctx))(id,l,r,n); + }; + plan.deviceEpoch=deviceEpoch;plan.graphRevision=expectedPcmRevision+1; + result.native=publisher.commit(candidate.roster,candidate.request, + expectedPcmRevision,deviceEpoch,currentHardwareEpoch, + allOutputsDisarmed,std::move(plan)); + if(!result.native.ok()) { + result.fault=Fault::nativeRejected;return result; + } + UnifiedLegacyAccepted next; + next.graph=std::move(candidate); + next.fxOwners=std::move(owner); + next.hardware=hardware; + next.deviceEpoch=deviceEpoch; + next.pcmRevision=result.native.revision; + accepted=std::move(next); + return result; + } +}; +} // namespace armix::mixer diff --git a/integration/ConsoleNativeContractV6.h b/integration/ConsoleNativeContractV6.h index 05fda42a3..7b40f3085 100644 --- a/integration/ConsoleNativeContractV6.h +++ b/integration/ConsoleNativeContractV6.h @@ -3,6 +3,9 @@ #include "../engine/core/DynamicAcceptedSession.h" #include #include +#include +#include +#include #include #include #include @@ -22,7 +25,7 @@ struct ConsoleIntentV6 final { patchInput, patchOutput, addChannel, groupSelected, addFxReturn, setInsert, setSend, setMix, recallShow }; - std::uint64_t requestId=0; // monotonic per live connection; never a strip index + std::string requestId; // Opaque per-WebView-session token, echoed exactly in ACK. std::uint64_t deviceEpoch=0,baseGraphRevision=0,baseRosterRevision=0; Operation operation=Operation::patchInput; ChannelId target{}; @@ -33,14 +36,27 @@ enum class IntentFaultV6 : std::uint8_t { staleGraph, staleRoster }; -// This is a preflight ONLY. The real JUCE control writer applies the native -// intent and returns ACK. lastCompletedId comes from that writer: do not -// mutate it here, or attempt to ACK a draft UI edit. +// The GUI sends an opaque string ('gui...:sequence'). Numeric <= comparison +// between different GUI incarnations is INVALID; an old editor reconnect can +// legally send a lower sequence. The existing native control writer owns a +// bounded recently-completed request-ID cache and supplies a VIEW of it here. +// This function does not retain IDs, emit ACK, create DSP or change the graph. +// Reject malformed IDs before they enter native diagnostic logs. +inline bool validConsoleRequestId(std::string_view id) noexcept { + if(id.empty() || id.size()>128)return false; + return std::all_of(id.begin(),id.end(),[](unsigned char ch) noexcept { + return ch>=0x21 && ch<=0x7e; + }); +} inline IntentFaultV6 validateConsoleIntent( const ConsoleIntentV6& intent,std::uint64_t actualDeviceEpoch, - std::uint64_t lastCompletedId,const DynamicAcceptedSession& accepted) noexcept { - if(!intent.requestId)return IntentFaultV6::invalidRequest; - if(intent.requestId<=lastCompletedId)return IntentFaultV6::duplicateOrOldRequest; + std::span completedRequestIds, + const DynamicAcceptedSession& accepted) noexcept { + if(!validConsoleRequestId(intent.requestId)) + return IntentFaultV6::invalidRequest; + if(std::find(completedRequestIds.begin(),completedRequestIds.end(), + std::string_view(intent.requestId))!=completedRequestIds.end()) + return IntentFaultV6::duplicateOrOldRequest; if(!actualDeviceEpoch || intent.deviceEpoch!=actualDeviceEpoch) return IntentFaultV6::staleDevice; if(intent.baseGraphRevision!=accepted.acceptedGraphRevision()) @@ -50,9 +66,29 @@ inline IntentFaultV6 validateConsoleIntent( return IntentFaultV6::none; } +// ChannelId is a native uint64 but a JSON string, *never* JavaScript Number. +// Reject malformed/overflowed/noncanonical identities instead of sending an +// intent to a guessed strip ordinal. Caller verifies this ID exists in the +// exact accepted native graph before authorizing a command. +inline bool parseNativeChannelId(std::string_view token,ChannelId& out) noexcept { + if(token.empty() || (token.size()>1 && token.front()=='0'))return false; + std::uint64_t value=0; + for(const char ch:token) { + if(ch<'0'||ch>'9')return false; + const auto digit=static_cast(ch-'0'); + if(value>(std::numeric_limits::max()-digit)/10u) + return false; + value=value*10u+digit; + } + if(value==0)return false; // Zero is the explicit unconnected OUT sentinel. + out=ChannelId{value};return true; +} + + struct ConsoleAckV6 final { enum class Status : std::uint8_t { acceptedGraph, rejected }; - std::uint64_t requestId=0,deviceEpoch=0,graphRevision=0,rosterRevision=0; + std::string requestId; // Must match user's opaque intent byte-for-byte. + std::uint64_t deviceEpoch=0,graphRevision=0,rosterRevision=0; Status status=Status::rejected; IntentFaultV6 preflight=IntentFaultV6::none; DynamicAcceptedSession::Fault nativeFault=DynamicAcceptedSession::Fault::none; @@ -65,7 +101,7 @@ struct ConsoleAckV6 final { inline ConsoleAckV6 consoleAckFromNative( const ConsoleIntentV6& intent,IntentFaultV6 preflight, const DynamicAcceptedSession& accepted, - const DynamicAcceptedSession::Result* nativeResult=nullptr) noexcept { + const DynamicAcceptedSession::Result* nativeResult=nullptr) { ConsoleAckV6 ack; ack.requestId=intent.requestId;ack.deviceEpoch=intent.deviceEpoch; ack.graphRevision=accepted.acceptedGraphRevision(); @@ -78,6 +114,10 @@ inline ConsoleAckV6 consoleAckFromNative( ack.status=ConsoleAckV6::Status::acceptedGraph; return ack; // Never claim productionCallbackLive here. } +inline std::string_view consoleWireAckStatus(const ConsoleAckV6& ack) noexcept { + return ack.status==ConsoleAckV6::Status::acceptedGraph + ?std::string_view{"ACCEPTED"}:std::string_view{"REJECTED"}; +} struct ConsoleSendV6 final { std::string destinationId; // Decimal string avoids JS Number precision loss. @@ -127,6 +167,7 @@ inline bool projectAcceptedConsoleV6( const DynamicAcceptedSession& native,std::uint64_t deviceEpoch, std::uint64_t exactGraphRevision, ConsoleAcceptedReadbackV6& destination) { + // GUI v6 uses canonical decimal-string uint64 revisions and BigInt. if(!deviceEpoch || !exactGraphRevision || native.acceptedGraphRevision()!=exactGraphRevision)return false; const auto* view=native.acceptedRouting(deviceEpoch,exactGraphRevision); @@ -157,4 +198,51 @@ inline bool projectAcceptedConsoleV6( destination=std::move(next); return true; } + +inline std::string_view consoleWireRole(ChannelRole role) noexcept { + switch(role) { + case ChannelRole::input: return "INPUT"; + case ChannelRole::group: return "GROUP"; + case ChannelRole::fxReturn: return "FX_RETURN"; + case ChannelRole::monitor: return "MONITOR"; + case ChannelRole::main: return "MAIN"; + } + return "UNKNOWN"; +} +struct ConsoleWireChannelV6 final { + std::string id,role,processingFormat,name,primaryOutId; + std::vector sends; + std::size_t primaryInputCount=0,parallelSendInputCount=0; + bool sourcePinVerified=false,actualPcmPresent=false; +}; +struct ConsoleWireReadbackV6 final { + std::uint32_t schemaVersion=6; + std::string deviceEpoch,graphRevision,rosterRevision,mainId,monitorId; + std::vector channels; + ProductionCapabilitiesV6 capabilities{}; + bool productionCallbackLive=false; +}; +// Control-only serialization model, NOT a device, JSON emitter or audio renderer. +inline ConsoleWireReadbackV6 toConsoleWireReadbackV6( + const ConsoleAcceptedReadbackV6& a) { + ConsoleWireReadbackV6 out; + out.deviceEpoch=std::to_string(a.deviceEpoch); + out.graphRevision=std::to_string(a.graphRevision); + out.rosterRevision=std::to_string(a.rosterRevision); + out.mainId=a.mainId;out.monitorId=a.monitorId; + out.capabilities=a.capabilities;out.productionCallbackLive=a.productionCallbackLive; + out.channels.reserve(a.channels.size()); + for(const auto& c:a.channels) { + ConsoleWireChannelV6 ch; + ch.id=c.id;ch.role=std::string(consoleWireRole(c.role)); + ch.processingFormat=c.format==ProcessingFormat::mono?"MONO":"STEREO"; + ch.name=c.name;ch.primaryOutId=c.primaryOutId;ch.sends=c.sends; + ch.primaryInputCount=c.primaryInputCount; + ch.parallelSendInputCount=c.parallelSendInputCount; + ch.sourcePinVerified=c.sourcePinVerified; + ch.actualPcmPresent=c.actualPcmPresent; + out.channels.push_back(std::move(ch)); + } + return out; +} } // namespace armix::integration diff --git a/scripts/build_ui_css.py b/scripts/build_ui_css.py index 86f81f5f2..0f3b79676 100644 --- a/scripts/build_ui_css.py +++ b/scripts/build_ui_css.py @@ -3,7 +3,7 @@ import argparse ROOT=Path(__file__).resolve().parents[1] SOURCE=ROOT/'web/styles-src' -MODULES=('00-font-and-assets.css','10-console-legacy.css','20-button-180.css','21-navigation-fx-power.css','30-selection-effects.css','40-rail-pan.css','41-mixer-performance.css','42-mixer-premium.css') +MODULES=('00-font-and-assets.css','10-console-legacy.css','20-button-180.css','21-navigation-fx-power.css','30-selection-effects.css','40-rail-pan.css','41-mixer-performance.css','42-mixer-premium.css','43-hardware-backlit.css') CSS=ROOT/'web/styles.css' HTML=ROOT/'AR-MIX-Live-FX-Host-Standalone-v0.3.html' def compile_css(): @@ -41,6 +41,7 @@ def embed_all(page,css): ('style','arsonmix-mixer-layout-css','web/mixer-layout.css'), ('script','arsonmix-mixer-io-js','web/mixer-io.js'), ('script','arsonmix-mixer-layout-js','web/mixer-layout.js'), + ('script','arsonmix-hardware-keys-js','web/hardware-keys.js'), ): built=embed_managed(built,tag,slot,(ROOT/path).read_text(encoding='utf-8')) return built diff --git a/scripts/check_console_puzzle.mjs b/scripts/check_console_puzzle.mjs index 8f137ffd4..cdd595f25 100644 --- a/scripts/check_console_puzzle.mjs +++ b/scripts/check_console_puzzle.mjs @@ -1,40 +1,172 @@ // SPDX-License-Identifier: AGPL-3.0-only -// Fail-closed source compatibility gate for the ONE integrated release branch. -// Contract self-tests can run on every PR. --release requires THREE owners' -// exact real-producer/consumer socket and refuses synthetic-only readiness. +// One shared v8 socket preflight (#279), maintained by FAT #270. +// OBSERVATION tiers are explicit. Source text can never attest actual PCM. +// No second schema; all JSON field validation lives in puzzle-seam.mjs. import {readFileSync} from 'node:fs'; +import {inspectCheckout as inspectApprovedConsole} from './check_pr278_console_authority.mjs'; +import {createHash} from 'node:crypto'; import {resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; import {execFileSync} from 'node:child_process'; -const files={ - native:'src/ConsoleLiveBridgeV6.h', - dispatcher:'src/Main.cpp', - gui:'web/mixer-layout.js', - guiTest:'tests/operator_console_v6_smoke.py', - fat:'scripts/console_v6_fat_gate.mjs', - fatTest:'tests/console_v6_fat_gate_test.mjs' -}; -const release=process.argv.includes('--release'); -const read=path=>{try{return readFileSync(resolve(path),'utf8')}catch{return ''}}; -const data=Object.fromEntries(Object.entries(files).map(([k,p])=>[k,read(p)])); -const checks=[ - ['ENGINE real device pin masks',/setProperty\("enabledInputs"/.test(data.native)&&/setProperty\("enabledOutputs"/.test(data.native),'ENGINE #266: publish enabledInputs and enabledOutputs from active device pin mask'], - ['ENGINE actual accepted stable ChannelId roster',!/graph->setProperty\("channels",juce::var\(juce::Array\{\}\)\)/.test(data.native)&&/setProperty\("channels"/.test(data.native),'ENGINE #266: serialize real accepted roster, not empty array'], - ['ENGINE universal processing admitted',!/setProperty\("productionCallbackLive",false\)/.test(data.native),'ENGINE #266: actual callback full fidelity must gate productionCallbackLive dynamically'], - ['ENGINE real ConsoleIntent dispatch',!/consoleBridge_\.rejectUnsupportedIntent\(args,snap\)/.test(data.dispatcher),'ENGINE #266: route valid intents to prepared accepted native graph, preserve rollback'], - ['GUI native ACK and snapshot listeners',/arMixConsoleAck/.test(data.gui)&&/arMixConsoleSnapshot/.test(data.gui),'GUI #271: consume real native ACK and snapshot'], - ['GUI fixture from one canonical source',/console-v6\/fixtures\.json/.test(data.guiTest),'GUI #271: use shared fixture file, remove standalone MAIN/BUS-FX fake ids'], - ['FAT checks native device endpoints and pin masks',/enabledInputs/.test(data.fat)&&/enabledOutputs/.test(data.fat),'FAT #270: validate native producer enabled pins, not hand-authored fantasy fields'], - ['FAT fixture from one canonical source',/console-v6\/fixtures\.json/.test(data.fatTest),'FAT #270: use the SAME shared fixture as GUI tests, not duplicate schema'], -]; -execFileSync(process.execPath,['--test','tests/console_v6_puzzle_seam_test.mjs'],{stdio:'inherit'}); -const blockers=checks.filter(x=>!x[1]); -for(const [name,pass,fix] of checks) - console.log((pass?'[MATCH] ':'[MISMATCH] ')+name+(pass?'':' -> '+fix)); -if(release){ - if(blockers.length){ - console.error('RELEASE PUZZLE GATE BLOCKED: '+blockers.length+' missing native/GUI/FAT sockets. No partial EXE/UAT.'); - process.exitCode=1; - }else console.log('RELEASE SOURCE SOCKET MATCH: static preflight only; native CTest, UI Playwright and independent physical FAT still required.'); -}else{ - console.log('G0 contract self-tests complete; --release will block until all three real owner branches match.'); + +export const SOCKET_PATHS=Object.freeze({ + native:'src/ConsoleLiveBridgeV6.h', + dispatcher:'src/Main.cpp', + gui:'web/mixer-layout.js', + guiTest:'tests/operator_console_v6_smoke.py', + fat:'scripts/console_v6_fat_gate.mjs', + fatTest:'tests/console_v6_fat_gate_test.mjs', + cxxFixture:'tests/console_puzzle_v8_fixture.cpp', + portableGolden:'tests/fixtures/console-v8-native-unready.json', + nativeRunner:'scripts/run_console_native_s0.mjs', + nativeProof:'scripts/verify_console_s0_native_fixture.mjs', + nativeSource:'src/LiveDryRoutingLab.h', + nativeTest:'tests/live_channel_fx_graph_test.cpp', + machine:'contracts/console-puzzle-v8.json' +}); +const c=(id,passes,owner,action)=>({id,pass:Boolean(passes),owner,action}); +// Pure source inspection ONLY; never return audioCertified or releaseReady=true. +export function inspectPuzzleSources(s,fixtureSha256=''){ + const native=s.native||'',dispatch=s.dispatcher||'',gui=s.gui||''; + const guiTest=s.guiTest||'',cpp=s.cxxFixture||'',fat=s.fat||''; + const fatTest=s.fatTest||'',runner=s.nativeRunner||''; + const proof=s.nativeProof||'',nativeSource=s.nativeSource||''; + const machine=s.machine||''; + const unready=/\bw\.productionCallbackLive\s*=\s*false\s*;/.test(native); + const strictLive=!unready&&/\bw\.productionCallbackLive\s*=/.test(native); + // A C++ entrypoint recognizing --emit-console-s0-json is NOT necessarily + // the actual JUCE producer. Historically the ENGINE test printed an offline + // PuzzleV8Wire::fixture(s,ack), which contains no engine.status PCM/pins. + // Restrict the check to the flag's actual branch, not a helper elsewhere. + const testCpp=s.nativeTest||''; + const flagAt=testCpp.indexOf('--emit-console-s0-json'); + let exportBranch=''; + if(flagAt>=0){ + const open=testCpp.indexOf('{',flagAt); + if(open>=0){ + let depth=1; + for(let i=open+1;i0 && + !/PuzzleV8Wire::fixture\s*\(/.test(exportBranch) && + /(?:LiveConsoleBridgeV6|Bridge)::snapshot\s*\(/.test(exportBranch) && + /\bengine\.status\s*\(/.test(exportBranch); + const acceptedRoster=/\bw\.channels\s*=|\.channels\.push_back|accepted.*ChannelId/.test(native) && + !/^\s*\/\/.*\bw\.channels\s*=/m.test(native); + const scopes=[ + c('V8_MACHINE_CONTRACT',machine.includes('"schemaVersion"')&& + machine.includes('"requiredSnapshotFields"')&&machine.includes('"intentRequired"')&& + machine.includes('"ackRequired"'), + 'SHARED #279','Restore machine-readable v8 schema/required-key inventory'), + c('S0_SINGLE_CPP_SERIALIZER', + native.includes('PuzzleV8Wire::snapshot(w)')&& + native.includes('PuzzleV8Wire::ack(ack)')&& + cpp.includes('PuzzleV8Wire::fixture(snapshot,ack)'), + 'ENGINE #266','C++ runtime + portable producer must use one PuzzleV8Wire serializer'), + c('S0_NATIVE_PIN_INVENTORY', + /\bw\.inputs\.push_back/.test(native)&&/\bw\.outputs\.push_back/.test(native), + 'ENGINE #266','Project native enabled input/output pin masks from actual JUCE status'), + c('S0_WEBVIEW_EVENTS', + dispatch.includes('arMixConsoleSnapshot')&&dispatch.includes('arMixConsoleIntent')&& + dispatch.includes('arMixConsoleAck')&&dispatch.includes('processProductionIntent'), + 'ENGINE #266','Dispatch real subscribe/intent/ACK/snapshot through active JUCE adapter'), + c('S0_EXPLICIT_JUCE_EXPORTER', + nativeEmitterSource && + runner.includes('assertExplicitS0Exporter') && + proof.includes('runActualNativeS0'), + 'ENGINE #266','Export exact JUCE LiveConsoleBridgeV6::snapshot(engine.status()) from native binary; PuzzleV8Wire::fixture(...) cannot qualify S0'), + c('S0_ONE_CPP_GUI_FIXTURE', + /^[a-f0-9]{64}$/.test(fixtureSha256)&& + guiTest.includes('console-v8-native-unready.json')&& + guiTest.includes(fixtureSha256)&& + proof.includes('actual.equals(expected)'), + 'GUI #271 + FAT #270','Same C++ byte-for-byte golden file and digest must be checked by both owners'), + c('GUI_NATIVE_ACK_SNAPSHOT', + gui.includes('arMixConsoleAck')&&gui.includes('arMixConsoleSnapshot')&& + gui.includes('arMixConsoleIntent')&& + gui.includes('baseGraphRevision')&&gui.includes('baseRosterRevision')&& + gui.includes('enabledInputs')&&gui.includes('enabledOutputs'), + 'GUI #271','No alternate GUI wire or missing pin masks; ACK requires exact accepted snapshot'), + c('FAT_SHARED_MACHINE_VALIDATION', + fat.includes('enabledInputs')&&fat.includes('enabledOutputs')&& + fatTest.includes('integration/console-v6/fixtures.json')&& + runner.includes('puzzle-seam.mjs')&& + machine.includes('"requiredSnapshotFields"'), + 'FAT #270','Use merged v8 machine socket and keep synthetic fixtures non-production'), + c('S1_INSTALLED_LEGACY_NATIVE_CONTROLS', + dispatch.includes('processProductionIntent')&& + native.includes('engine.switchDryRoutingLabSource(')&& + native.includes('engine.setDryRoutingLabParameter(')&& + nativeSource.includes('bool process('), + 'ENGINE #266','Verify actual callback IN1→CH07→MAIN PCM and native ACK on same source SHA'), + c('G2_FULL_UNIVERSAL_CALLBACK', + strictLive&&acceptedRoster&& + /supportedOps/.test(native)&& + /ChannelId/.test(native)&& + !/supportedOps\s*:\s*\[\s*\]/.test(native), + 'ENGINE #266','Install real full-fidelity ChannelId callback (VST/Show/CH11/Group/FX Return/Monitor); do not set LIVE in G0'), + c('G2_GUI_NATIVE_OPERATIONS', + gui.includes('productionCallbackLive===true')&& + gui.includes('supportedOps')&& + gui.includes('arMixConsoleIntent'), + 'GUI #271','Enable visible controls only for supported working native ops from accepted state') + ]; + const passes=id=>scopes.find(x=>x.id===id)?.pass===true; + const portableOnly=passes('S0_SINGLE_CPP_SERIALIZER')&& + passes('S0_ONE_CPP_GUI_FIXTURE'); + return { + stage:!passes('S0_EXPLICIT_JUCE_EXPORTER')?'S0_NATIVE_PRODUCER_BLOCKED': + !passes('G2_FULL_UNIVERSAL_CALLBACK')?'S1_OR_G0_ONLY_UNIVERSAL_BLOCKED': + 'SOURCE_CANDIDATE_ONLY_REQUIRES_NATIVE_PCM_CI_HARDWARE', + portableFixtureMatch:portableOnly, + actualNativeS0Verified:false, // source-only checker cannot execute native JUCE + actualCallbackPCMVerified:false, + hardwareFAT:'PENDING', + productCertified:false, + checks:scopes, + releaseSourceBlockers:scopes.filter(x=>!x.pass).map(x=>x.id) + }; +} +const here=resolve(fileURLToPath(new URL('..',import.meta.url))); +function filesOnDisk(){ + const files={}; + for(const [k,p] of Object.entries(SOCKET_PATHS)) + try{files[k]=readFileSync(resolve(here,p),'utf8')}catch{files[k]=''} + try{ + const bytes=readFileSync(resolve(here,SOCKET_PATHS.portableGolden)); + files.fixtureSha256=createHash('sha256').update(bytes).digest('hex'); + }catch{files.fixtureSha256=''} + return files; +} +if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){ + const release=process.argv.includes('--release'); + try{ + execFileSync(process.execPath,['--test','tests/console_v6_puzzle_seam_test.mjs'], + {cwd:here,stdio:'inherit'}); + const src=filesOnDisk(); + const result=inspectPuzzleSources(src,src.fixtureSha256); + for(const check of result.checks) + console.log((check.pass?'[MATCH] ':'[BLOCKED] ')+check.id+ + (check.pass?'':' -> '+check.owner+': '+check.action)); + console.log(JSON.stringify({stage:result.stage, + goldenSha256:src.fixtureSha256||'NOT_AVAILABLE', + actualNativeS0Verified:false,actualCallbackPCMVerified:false, + hardwareFAT:'PENDING',releaseSourceBlockers:result.releaseSourceBlockers},null,2)); + if(release){ + const design=inspectApprovedConsole(); + console.log('PR278 approved GUI source matches '+(design.checks.length-design.blocked.length)+'/'+design.checks.length); + for(const d of design.blocked)console.error('[PR278 GUI BLOCK] '+d.id+' -> GUI #271: '+d.action); + if(design.blocked.length)process.exitCode=1; + if(result.releaseSourceBlockers.length){ + console.error('RELEASE SOURCE GATE BLOCKED: '+result.releaseSourceBlockers.length+ + ' source discrepancies. Windows+Chromium/real callback PCM are independent mandatory checks.'); + process.exitCode=1; + }else console.log('SOURCE SOCKET CANDIDATE ONLY: not release/UAT; native PCM+EXE+physical review still required'); + } + }catch(e){console.error('SHARED PUZZLE PRECHECK FAILED: '+e.message);process.exitCode=1} } diff --git a/scripts/check_pr278_console_authority.mjs b/scripts/check_pr278_console_authority.mjs new file mode 100644 index 000000000..04f8c9109 --- /dev/null +++ b/scripts/check_pr278_console_authority.mjs @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// PR #278 approved visual contract; NEVER an audio/PCM certification. +import {readFileSync} from 'node:fs'; +import {resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; +export const DESIGN_REFERENCE={pr:278,sha:'eda57f931ae3cc2872579df29cdf4e1486592b64', + gitBlob:'1bbd9f50eefbb3c54d05d8e36e5afd3bd5e6d709'}; +function rule(css,key){const i=css.indexOf(key);if(i<0)return ''; + const a=css.indexOf('{',i),b=css.indexOf('}',a+1); + return a>=0&&b>=0?css.slice(a+1,b):'';} +export function inspectPr278(x={}){ + const js=x.js||'',css=x.css||'',ref=x.reference||'',old=x.legacy||'',test=x.test||''; + const hardware=x.hardware||'',hardwareCss=x.hardwareCss||''; + // Read the effective final native Console rules after the old fixed-width + // fallback. An early #app .arV6Strip{} declaration is NOT the winning rule + // after GUI-final shared-width/density and V5 skin were installed. + const strip=rule(css,'#app .arV6Console .arV6Strip,')||rule(css,'#app .arV6Strip{'); + const main=rule(css,'#app .arV6Console .arV6Main,')||rule(css,'#app .arV6Main{'); + const top=rule(css,'#app .arV6Console .arV6Top{')||rule(css,'#app .arV6Top{'); + const head=rule(css,'#app .arV6Console .arV6StripHead{')||rule(css,'#app .arV6StripHead{'); + const foot=rule(css,'#app .arV6Console .arV6StripStatus{')||rule(css,'#app .arV6StripStatus{'); + const checks=[]; + const add=(id,ok,action)=>checks.push({id,pass:!!ok,action}); + add('REFERENCE_278',ref.includes('id="tracks"')&&ref.includes('id="master"')&&ref.includes('id="pluginBrowser"'),'Include pinned #278 design study in integration source only'); + add('ONE_CONSOLE',js.includes("root.id='arV6Console'")&&js.includes("main.id='arV6Main'"),'Single approved Console, pinned MAIN'); + add('DIRECT_NATIVE_IO',js.includes("selectField('IN','SET_SOURCE'")&&js.includes("selectField('OUT','SET_PRIMARY_OUT'")&&js.includes('fxSection(ch)')&&js.includes('sendSection(ch)'),'Keep direct IN/OUT/FX/sends on each channel'); + add('NATIVE_ACK_NO_DEMO',js.includes('arMixConsoleAck')&&js.includes('arMixConsoleSnapshot')&&js.includes('supportedOps')&&js.includes('productionCallbackLive===true'),'Use actual native accepted snapshot and PCM only'); + const identityColor=js.includes("elStrip.style.setProperty('--ch'")||js.includes("elStrip.style.setProperty('--v6-strip-color'"); + const colorHead=head.includes('var(--ch')||head.includes('var(--v6-strip-color'); + const colorFoot=foot.includes('var(--ch')||foot.includes('var(--v6-strip-color'); + add('TOP_BOTTOM_COLOR_ICON',identityColor&&(js.includes('ch.icon')||js.includes('channelIcons'))&&colorHead&&colorFoot,'Port #278 exact channel name/color/icon at both top and bottom'); + const material=css.includes('--am-metal-panel:#14232C'); + const stripMetal=strip.includes('var(--am-metal-panel)')||strip.includes('var(--am-metal-base)'); + const topMetal=top.includes('var(--am-metal-panel)')||top.includes('var(--am-metal-raised)'); + add('ONE_GRAPHITE_CHASSIS',material&&stripMetal&&topMetal,'Use same #278 graphite metal material above and below fader'); + add('V5_HEADER_KEYS', + hardware.includes("['#app .arV6Console .arV6Top .arV6Button'")&& + hardware.includes("classList.add('mx-hw-key'")&& + hardwareCss.includes('#app button.mx-hw-key')&& + hardwareCss.includes('svg.mx-hw-face')&& + js.includes("const tools=h('div','arV6Tools')"), + 'Use owner-approved lightweight V5 cutout keys for native header actions; obsolete BTN-180 must not be restored'); + const stripWidth=strip.includes('var(--channel-w)')||strip.includes('var(--v6-channel-w)'); + const mainWidth=main.includes('var(--channel-w)')||main.includes('var(--v6-channel-w)'); + add('PINNED_MAIN_EQUAL_WIDTH',stripWidth&&mainWidth,'One shared computed width for source and MAIN strip at all viewports'); + add('PAN_CUE',js.includes('paintPan(')&&js.includes('--v6-pan-start')&&js.includes("'SET_CUE'"),'Center-detent pan and native-only Cue/PFL'); + add('LINK_VS_GROUP',js.includes("button('LINK FADERS'")&&js.includes("button('ROUTE TO GROUP BUS'"),'Separate fader-link control from serial Group DSP'); + add('MODELLESS_NATIVE_FX',js.includes('arV6PluginPanel')&&js.includes('arV6QuickPanel')&&js.includes('Search native scanned plugins'),'F8 modeless plugin manager must use actual VST3 inventory'); + add('OLD_PALETTE',old.includes('channelIcons=')&&old.includes('channelPalette='),'Preserve legacy 12 channel colors/icons'); + const nativeDensity=['comfort','standard','compact'].every(d=>js.toLowerCase().includes(d)) && + (js.includes('bankGeometry(')||js.includes('DENSITY_WIDTH')); + add('V8_DENSITY_AWARE_BANK',nativeDensity,'Use PR278 V8 Comfort150 / Standard125 / Compact105 minimum and reserved MAIN width'); + const realFold=css.includes('display:none')&&css.includes('.arV6Route')&& + css.includes('.arV6Fx')&&css.includes('.arV6Sends')&& + (css.includes('data-collapseroute')||css.includes('data-collapsefx')||css.includes('data-collapsesend')); + add('V8_TRUE_SECTION_COLLAPSE',realFold,'Hide collapsed Route/FX/Send children; no clipped 23px controls or rail mismatch'); + add('NATIVE_CONSUMER_TEST',test.includes('console-v8-native-unready.json')&&test.includes('arMixConsoleAck'),'Visual UI also requires native fixture/ACK regression'); + return {reference:DESIGN_REFERENCE,sourceOnly:true,audioCertified:false, + checks,blocked:checks.filter(c=>!c.pass)}; +} +const base=resolve(fileURLToPath(new URL('..',import.meta.url))); +const read=p=>{try{return readFileSync(resolve(base,p),'utf8')}catch{return ''}}; +export function inspectCheckout(){return inspectPr278({ + reference:read('design-references/audition-mixer-study/index.html'), + js:read('web/mixer-layout.js'),css:read('web/mixer-layout.css'), + legacy:read('web/app.js'),test:read('tests/operator_console_v6_smoke.py'), + hardware:read('web/hardware-keys.js'),hardwareCss:read('web/styles-src/43-hardware-backlit.css')});} +if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){ + const v=inspectCheckout(); + for(const c of v.checks)console.log((c.pass?'MATCH ':'BLOCK ')+c.id+(c.pass?'':' -> '+c.action)); + if(process.argv.includes('--release')&&v.blocked.length)process.exitCode=1; +} diff --git a/scripts/collect_hardware_fat_windows.ps1 b/scripts/collect_hardware_fat_windows.ps1 new file mode 100644 index 000000000..924bc5cd7 --- /dev/null +++ b/scripts/collect_hardware_fat_windows.ps1 @@ -0,0 +1,256 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Offline Windows field evidence recorder. NEVER controls audio devices, DSP, ARM or plugins. +param( + [ValidateSet('Verify','Start','Stop','Summary')][string]$Action='Verify', + [ValidateSet('OUTPUT_ONLY_TONE','CAPTURE_ONLY','DRY_THROUGH_0FX','LIVE_THROUGH_1FX')][string]$Mode='DRY_THROUGH_0FX', + [string]$Backend='', + [int]$SampleRate=0, + [int]$BufferFrames=0, + [string]$InputPins='', + [string]$OutputPins='', + [string]$CaptureEndpoint='', + [string]$RenderEndpoint='', + # MANUALLY read from the native VST3 rack; not a synthetic software probe. + # A 1FX run must identify exactly one active, non-bypassed vendor insert. + [ValidateRange(0,8)][int]$FxCount=0, + [string]$Vst3Name='', + [switch]$Wired, + [ValidateSet('CLEAR','CRACKLE','INCONCLUSIVE')][string]$Result='INCONCLUSIVE', + [string]$ReportPath='', + [string]$Witness='', + [string]$Notes='' +) +Set-StrictMode -Version Latest +$ErrorActionPreference='Stop' +$root=$PSScriptRoot +$manifestPath=Join-Path $root 'BUILD_PROVENANCE.json' +if (-not (Test-Path -LiteralPath $manifestPath -PathType Leaf)) { throw 'Missing BUILD_PROVENANCE.json: extract the complete verified Windows FAT ZIP first' } +$m=Get-Content -LiteralPath $manifestPath -Raw -Encoding UTF8 | ConvertFrom-Json +if ([string]$m.fatStatus -ne 'EXPERIMENTAL_NOT_HARDWARE_QUALIFIED') { throw 'Unexpected hardware qualification claim' } +if ([string]$m.sourceCommit -notmatch '^[a-f0-9]{40}$') { throw 'Invalid exact source SHA' } +if ([string]$m.fatCollectorSha256 -notmatch '^[a-f0-9]{64}$') { throw 'Missing FAT collector provenance' } +$selfHash=(Get-FileHash -LiteralPath $PSCommandPath -Algorithm SHA256).Hash.ToLowerInvariant() +if ($selfHash -ne [string]$m.fatCollectorSha256) { throw 'FAT collector was modified after packaging' } +$app=Join-Path $root ([string]$m.executable) +if (-not (Test-Path -LiteralPath $app -PathType Leaf)) { throw 'Missing packaged native GUI EXE' } +$exeHash=(Get-FileHash -LiteralPath $app -Algorithm SHA256).Hash.ToLowerInvariant() +if ($exeHash -ne [string]$m.exeSha256) { throw 'GUI EXE SHA-256 mismatch: do not test or label this artifact' } +$journalPath=Join-Path $root 'FAT_RUNS.json' +function Save-Journal($j) { + $j | ConvertTo-Json -Depth 12 | Set-Content -LiteralPath $journalPath -Encoding UTF8 +} +function Read-Journal { + if (Test-Path -LiteralPath $journalPath -PathType Leaf) { + $j=Get-Content -LiteralPath $journalPath -Raw -Encoding UTF8 | ConvertFrom-Json + if ($j.schema -ne 'arsonmix.hardware-fat-field-journal.v1' -or + $j.sourceSha -ne $m.sourceCommit -or $j.exeSha256 -ne $exeHash) { + throw 'FAT_RUNS.json belongs to a different or unsupported build' + } + return $j + } + return [pscustomobject]@{ + schema='arsonmix.hardware-fat-field-journal.v1' + sourceSha=[string]$m.sourceCommit + exeSha256=$exeHash + active=$null + sessions=@() + } +} +function Parse-Pins([string]$raw) { + if ([string]::IsNullOrWhiteSpace($raw)) { return @() } + $parsed=@() + foreach ($part in $raw.Split(',')) { + $pin=0 + if (-not [int]::TryParse($part.Trim(),[ref]$pin) -or $pin -lt 0 -or $pin -gt 255) { + throw 'Pin values must be physical callback ordinals 0..255 separated by commas, confirmed from native readback' + } + if ($parsed -contains $pin) { throw 'Duplicate physical pin in evidence' } + $parsed+= $pin + } + return $parsed +} +if ($Action -eq 'Verify') { + Write-Host ('FAT PACKAGE OK; build='+$m.sourceCommit+'; EXE SHA256='+$exeHash) + Write-Host 'UNQUALIFIED 10CH/4AUX candidate. No sound, device, latency or hardware result has been tested.' + exit 0 +} +$j=Read-Journal +if ($Action -eq 'Start') { + if ($null -ne $j.active) { throw 'A FAT mode is already active; Stop it before starting another' } + if (-not $Backend.Trim() -or $SampleRate -lt 8000 -or $SampleRate -gt 384000 -or + $BufferFrames -lt 16 -or $BufferFrames -gt 16384) { + throw 'Specify actual native readback -Backend, -SampleRate, -BufferFrames (not draft device values)' + } + $inputs=@(Parse-Pins $InputPins) + $outputs=@(Parse-Pins $OutputPins) + if ($Mode -eq 'OUTPUT_ONLY_TONE' -and ($inputs.Count -ne 0 -or $outputs.Count -lt 1)) { + throw 'OUTPUT_ONLY_TONE must have NO capture pins and a real render pin' + } + if ($Mode -eq 'CAPTURE_ONLY' -and ($outputs.Count -ne 0 -or $inputs.Count -lt 1)) { + throw 'CAPTURE_ONLY must have NO render pins and a real capture pin' + } + if ($Mode -in @('DRY_THROUGH_0FX','LIVE_THROUGH_1FX') -and + ($inputs.Count -lt 1 -or $outputs.Count -lt 1)) { + throw 'Live-through FAT requires actual capture and render pins' + } + # Prevent confusing a 0FX soak with a real active vendor effect. The + # operator enters verified-in-GUI details; collector cannot observe DSP. + if ($Mode -in @('DRY_THROUGH_0FX','LIVE_THROUGH_1FX') -and -not $Wired) { + throw 'Both matched 0FX/1FX tests require actual -Wired hardware routing' + } + if ($Mode -eq 'LIVE_THROUGH_1FX') { + if ($FxCount -ne 1 -or [string]::IsNullOrWhiteSpace($Vst3Name) -or + $Vst3Name.Length -gt 120) { + throw '1FX FAT requires -FxCount 1 and -Vst3Name copied from the active native VST3 rack' + } + # A user should not spend another 30 minutes on an incomparable setup. + # Compare against the most recent completed, witnessed 0FX baseline + # BEFORE the 1FX timer starts; never accept a guess about the device. + $baseline=@($j.sessions | Where-Object { $_.mode -eq 'DRY_THROUGH_0FX' } | Select-Object -Last 1) + if ($baseline.Count -ne 1 -or $baseline[0].elapsedSeconds -lt 1800 -or + -not $baseline[0].wired -or -not $baseline[0].reportSha256 -or + -not $baseline[0].witness -or + $baseline[0].operatorObservation -eq 'INCONCLUSIVE') { + throw 'Record a completed 30-minute wired 0FX baseline with witness and full report before 1FX' + } + $base=$baseline[0] + if ($base.backend -ne $Backend -or + $base.sampleRate -ne $SampleRate -or + $base.bufferFrames -ne $BufferFrames -or + ($base.capturePins -join ',') -ne ($inputs -join ',') -or + ($base.renderPins -join ',') -ne ($outputs -join ',') -or + $base.captureEndpoint -ne $CaptureEndpoint -or + $base.renderEndpoint -ne $RenderEndpoint) { + throw '1FX must use the identical ASIO/WASAPI device, clock, buffer and physical ports as the 0FX baseline' + } + } elseif ($FxCount -ne 0 -or -not [string]::IsNullOrWhiteSpace($Vst3Name)) { + throw 'Only LIVE_THROUGH_1FX accepts an active VST3 rack; other FAT modes require zero FX' + } + # The operator must select the mode in the running native app FIRST. + # Starting this timer does not change any endpoint or output ARM. + $j.active=[pscustomobject]@{ + mode=$Mode + startedUtc=[DateTime]::UtcNow.ToString('o') + backend=$Backend + sampleRate=$SampleRate + bufferFrames=$BufferFrames + capturePins=$inputs + renderPins=$outputs + captureEndpoint=$CaptureEndpoint + renderEndpoint=$RenderEndpoint + operatorReportedFxCount=$FxCount + operatorReportedVst3Name=$Vst3Name.Trim() + wired=[bool]$Wired + } + Save-Journal $j + Write-Host ('FAT TIMER STARTED '+$Mode+' at '+$j.active.startedUtc) + Write-Host 'Listen at LOW wired volume; use SIGNAL CHECK > MARK CRACKLE, COPY FULL REPORT. No audio or ARM controls were changed.' + exit 0 +} +if ($Action -eq 'Stop') { + if ($null -eq $j.active) { throw 'No active FAT session; use -Action Start after selecting actual native mode' } + $end=[DateTime]::UtcNow + $elapsed=[math]::Max(0,[math]::Floor(($end-([DateTime]::Parse($j.active.startedUtc).ToUniversalTime())).TotalSeconds)) + $reportFileName=$null + $reportHash=$null + if (-not [string]::IsNullOrWhiteSpace($ReportPath)) { + if (-not (Test-Path -LiteralPath $ReportPath -PathType Leaf)) { throw 'COPY FULL REPORT file not found' } + $reportFileName=('FAT_REPORT_'+$j.active.mode+'_'+$end.ToString('yyyyMMddTHHmmssZ')+'.txt') + $destination=Join-Path $root $reportFileName + Copy-Item -LiteralPath $ReportPath -Destination $destination -ErrorAction Stop + $reportHash=(Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash.ToLowerInvariant() + } + $session=[pscustomobject]@{ + mode=$j.active.mode + startedUtc=$j.active.startedUtc + endedUtc=$end.ToString('o') + elapsedSeconds=[int]$elapsed + backend=$j.active.backend + sampleRate=$j.active.sampleRate + bufferFrames=$j.active.bufferFrames + capturePins=$j.active.capturePins + renderPins=$j.active.renderPins + captureEndpoint=$j.active.captureEndpoint + renderEndpoint=$j.active.renderEndpoint + operatorReportedFxCount=$j.active.operatorReportedFxCount + operatorReportedVst3Name=$j.active.operatorReportedVst3Name + wired=$j.active.wired + operatorObservation=$Result + witness=$Witness + reportFile=$reportFileName + reportSha256=$reportHash + notes=$Notes + } + $j.sessions=@($j.sessions)+@($session) + $j.active=$null + Save-Journal $j + Write-Host ('FAT '+$session.mode+' ended: '+$elapsed+' seconds; observation='+$Result) + if ($null -eq $reportHash) { Write-Warning 'No full report supplied. Evidence will be incomplete.' } + if ($session.mode -in @('DRY_THROUGH_0FX','LIVE_THROUGH_1FX') -and $elapsed -lt 1800) { + Write-Warning 'Under 30 minutes; this does NOT satisfy the matched 0FX/1FX soak comparison.' + } + exit 0 +} +if ($Action -eq 'Summary') { + $missing=@() + $selected=@() + foreach ($required in @('OUTPUT_ONLY_TONE','CAPTURE_ONLY','DRY_THROUGH_0FX','LIVE_THROUGH_1FX')) { + $s=@($j.sessions | Where-Object { $_.mode -eq $required } | Select-Object -Last 1) + if ($s.Count -eq 0) { $missing+= $required; continue } + $selected+= $s[0] + if ($null -eq $s[0].reportSha256 -or $s[0].operatorObservation -eq 'INCONCLUSIVE' -or -not $s[0].witness) { + $missing+=($required+': report/observation/witness missing') + } + } + foreach ($mode in @('DRY_THROUGH_0FX','LIVE_THROUGH_1FX')) { + $matches=@($selected | Where-Object { $_.mode -eq $mode }) + if ($matches.Count -eq 1) { + $run=$matches[0] + if ($run.elapsedSeconds -lt 1800 -or -not $run.wired) { + $missing+=($mode+': 1800 seconds on wired route required') + } + if ($mode -eq 'LIVE_THROUGH_1FX' -and + ($run.operatorReportedFxCount -ne 1 -or + [string]::IsNullOrWhiteSpace($run.operatorReportedVst3Name))) { + $missing+='LIVE_THROUGH_1FX: native vendor insert identity missing' + } + } + } + # Compare like-for-like driver, clock, buffer, input/output pins before + # attributing any crackle difference to one vendor VST3. + $zero=@($selected | Where-Object { $_.mode -eq 'DRY_THROUGH_0FX' }) + $one=@($selected | Where-Object { $_.mode -eq 'LIVE_THROUGH_1FX' }) + if ($zero.Count -eq 1 -and $one.Count -eq 1) { + $base=$zero[0];$withFx=$one[0] + if ($base.backend -ne $withFx.backend -or + $base.sampleRate -ne $withFx.sampleRate -or + $base.bufferFrames -ne $withFx.bufferFrames -or + ($base.capturePins -join ',') -ne ($withFx.capturePins -join ',') -or + ($base.renderPins -join ',') -ne ($withFx.renderPins -join ',') -or + $base.captureEndpoint -ne $withFx.captureEndpoint -or + $base.renderEndpoint -ne $withFx.renderEndpoint) { + $missing+='0FX/1FX: backend, clock, buffer and physical routes must match for valid comparison' + } + } + if ($null -ne $j.active) { $missing+='An active session must be stopped first' } + $state=if ($missing.Count -eq 0) { 'EVIDENCE_READY_FOR_HUMAN_REVIEW' } else { 'EVIDENCE_INCOMPLETE' } + $resultJson=[ordered]@{ + schema='arsonmix.hardware-fat-summary.v1' + sourceSha=$m.sourceCommit + exeSha256=$exeHash + recordedAtUtc=[DateTime]::UtcNow.ToString('o') + status=$state + hardwareCertified=$false + physicalAudibilityVerifiedBySoftware=$false + fxComparisonSource='OPERATOR_REPORTED_ONLY' + unresolvedIssue=15 + sessions=$selected + blockers=$missing + caution='Observations and VST3 identity are human-entered, not hardware telemetry. Review real 0FX/1FX audio and exact clock/pins before attributing crackles. Capture flags are NOT render xruns.' + } + $outPath=Join-Path $root 'FAT_SUMMARY.json' + $resultJson | ConvertTo-Json -Depth 12 | Set-Content -LiteralPath $outPath -Encoding UTF8 + Write-Host ($state+'; wrote '+$outPath+'; certified=false') + Write-Warning 'Inspect FAT_RUNS.json and diagnostic files for sensitive device info before sharing. Issue #15 remains open.' + exit 0 +} \ No newline at end of file diff --git a/scripts/console_v6_fat_gate.mjs b/scripts/console_v6_fat_gate.mjs new file mode 100644 index 000000000..fcebd16b4 --- /dev/null +++ b/scripts/console_v6_fat_gate.mjs @@ -0,0 +1,304 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Evidence verifier; NOT a native PCM engine and NEVER a physical sound certificate. +import {readFileSync} from 'node:fs'; +import {createHash} from 'node:crypto'; +import {resolve,join} from 'node:path'; +import {pathToFileURL} from 'node:url'; +export const TRACE_SCHEMA='arsonmix.console-v6.acceptance-trace.v2'; +const fail=s=>{throw Error(s)}; +const must=(ok,s)=>{if(!ok)fail(s)}; +const json=p=>JSON.parse(readFileSync(p,'utf8')); +const hash=p=>createHash('sha256').update(readFileSync(p)).digest('hex'); +const is40=s=>/^[0-9a-f]{40}$/.test(s||''); +const is64=s=>/^[0-9a-f]{64}$/.test(s||''); +const sample=(v,label)=>{must(Array.isArray(v)&&v.length>=4&&v.length<=65536,label+': bounded PCM sample array required');must(v.every(x=>typeof x==='number'&&Number.isFinite(x)&&Math.abs(x)<=8),label+': nonfinite/invalid PCM');return v}; +const compare=(a,b,label)=>{must(a.length===b.length&&a.every((x,i)=>Math.abs(x-b[i])<=1e-5),label+': PCM mismatch')}; +const audible=(a,label)=>must(a.reduce((s,x)=>s+x*x,0)/a.length>1e-9,label+': silent PCM cannot prove routing'); +// G0 wire gate: actual WebView event envelopes, no parallel legacy trace shape. +// This validator checks claimed evidence structure, not producer authenticity. +const UINT64_MAX=18446744073709551615n; +function u64(v,where,positive=false){ + must(typeof v==='string'&&/^(0|[1-9][0-9]*)$/.test(v), + where+': canonical decimal-string uint64 required'); + const n=BigInt(v); + must(n<=UINT64_MAX&&(!positive||n>0n),where+': uint64 overflow/zero'); + return n; +} +function snapshot(s){ + must(s?.schemaVersion===6&&typeof s.productionCallbackLive==='boolean', + 'snapshot: schema v6 and explicit production callback state required'); + must(s.device&&s.graph&&s.telemetry,'snapshot: device/graph/telemetry required'); + u64(s.device.epoch,'device epoch',true); + u64(s.graph.revision,'graph revision'); + u64(s.graph.rosterRevision,'roster revision'); + must(typeof s.device.outputArmed==='boolean','snapshot: outputArmed required'); + for(const k of ['enabledInputs','enabledOutputs','inputEndpoints','outputEndpoints']) + must(Array.isArray(s.device[k]),'snapshot: native '+k+' inventory missing'); + for(const k of ['enabledInputs','enabledOutputs']){ + const a=s.device[k]; + must(a.every(x=>Number.isSafeInteger(x)&&x>=0&&x<=255)&& + new Set(a).size===a.length,'snapshot: invalid physical '+k); + } + const g=s.graph,c=g.capabilities; + must(Array.isArray(g.channels)&&Array.isArray(g.destinations)&&c&& + typeof c.callbackOwnsChannelIds==='boolean'&&Array.isArray(c.supportedOps), + 'snapshot: native channels/destinations/capability/supportedOps missing'); + must(c.supportedOps.every(x=>typeof x==='string')&& + new Set(c.supportedOps).size===c.supportedOps.length,'snapshot: invalid supportedOps'); + if(s.productionCallbackLive)must(c.callbackOwnsChannelIds===true, + 'snapshot: LIVE without installed native callback'); + // M4 can have ARMED physical outputs while universal ChannelId v6 is + // NOT admitted. Do not collapse the legacy output state into a fake LIVE flag. + // Separately, a v6 graph with productionCallbackLive=false is never audio proof. + const ids=new Set(); + for(const x of g.channels){ + u64(x?.id,'ChannelId',true); + must(!ids.has(x.id),'snapshot: duplicate ChannelId');ids.add(x.id); + must(['INPUT','MAIN','MONITOR','GROUP','FX_RETURN'].includes(x.role), + 'snapshot: invalid channel role'); + if(x.role==='GROUP')must(c.groups===true,'GROUP without native capability'); + if(x.role==='FX_RETURN')must(c.fxReturns===true,'FX Return without native capability'); + if(x.role==='MONITOR')must(c.monitor===true,'MONITOR without native capability'); + const pins=x.source?.physicalPins; + if(pins!==undefined){ + must(Array.isArray(pins)&&(pins.length===1||pins.length===2), + 'snapshot: invalid mono/stereo pin count'); + must(pins.every(p=>s.device.enabledInputs.includes(p)), + 'snapshot: source outside enabled native pins'); + if(pins.length===2)must(pins[0]!==pins[1], + 'snapshot: duplicate L/R physical stereo pin'); + } + } + return s; +} +export function checkTrace(t){ + must(t?.schema===TRACE_SCHEMA&&Array.isArray(t.events)&&t.events.length>=7, + 'trace v2 must use native WebView event envelopes'); + must(['SYNTHETIC','NATIVE_JUCE'].includes(t.provenance?.kind), + 'trace: synthetic/native provenance declaration required'); + if(t.provenance.kind==='NATIVE_JUCE')must(is40(t.provenance.sourceSha)&& + t.provenance.producer==='JUCE_WEBVIEW','native provenance requires exact SHA and producer'); + let state=null,pending=null,previousAck=null,accepted=0,rejected=0; + const ids=new Set(); + for(const [i,e] of t.events.entries()){ + const type=e?.event,p=e?.payload,where='event '+i; + must(['arMixConsoleSnapshot','arMixConsoleIntent','arMixConsoleAck'].includes(type)&& + p&&typeof p==='object',where+': unrecognized native WebView event'); + if(type==='arMixConsoleSnapshot'){ + snapshot(p); + if(!state){must(i===0,'first event must be accepted native snapshot');state=p;continue} + must(previousAck,where+': unsolicited snapshot'); + if(previousAck.status==='ACCEPTED'){ + must(p.device.epoch===state.device.epoch&& + p.graph.revision===previousAck.graphRevision&& + p.graph.rosterRevision===previousAck.rosterRevision, + where+': accepted ACK needs matching fresh snapshot'); + must(u64(p.graph.revision,'next graph')>=u64(state.graph.revision,'prior graph'), + where+': graph revision regressed'); + }else must(p.device.epoch===state.device.epoch&& + JSON.stringify(p.graph)===JSON.stringify(state.graph)&& + p.device.outputArmed===state.device.outputArmed, + where+': rejected intent mutated accepted graph or ARM'); + state=p;previousAck=null;continue; + } + must(state&&!previousAck,where+': fresh snapshot required after ACK'); + if(type==='arMixConsoleIntent'){ + must(!pending&&typeof p.requestId==='string'&& + p.requestId.length>=5&&p.requestId.length<=160&& + /^[\x21-\x7e]+$/.test(p.requestId)&&p.requestId.includes(':')&& + !ids.has(p.requestId), + where+': unique session-scoped opaque requestId required'); + u64(p.deviceEpoch,'intent deviceEpoch',true); + u64(p.baseGraphRevision,'intent baseGraphRevision'); + u64(p.baseRosterRevision,'intent baseRosterRevision'); + must(typeof p.operation==='string'&&p.operation.length>0, + where+': operation required'); + if(p.targetChannelId!=null)u64(p.targetChannelId,'targetChannelId',true); + must(p.payload&&typeof p.payload==='object'&&!Array.isArray(p.payload), + where+': payload object required'); + ids.add(p.requestId);pending=p;continue; + } + must(pending&&p.requestId===pending.requestId,where+': ACK requestId mismatch'); + must(['ACCEPTED','REJECTED','REQUIRES_DEVICE_CHANGE'].includes(p.status), + where+': unsupported native ACK status'); + const stale=pending.deviceEpoch!==state.device.epoch|| + pending.baseGraphRevision!==state.graph.revision|| + pending.baseRosterRevision!==state.graph.rosterRevision; + must(!stale||p.status!=='ACCEPTED',where+': stale epoch/graph/roster accepted'); + must(state.graph.capabilities.supportedOps.includes(pending.operation)|| + p.status!=='ACCEPTED',where+': unsupported native operation accepted'); + if(p.status==='ACCEPTED'){ + must(u64(p.graphRevision,'ACK graph revision')>=u64(state.graph.revision,'accepted graph')&& + u64(p.rosterRevision,'ACK roster revision')>=u64(state.graph.rosterRevision,'accepted roster'), + where+': ACK revision regressed');accepted++; + }else{ + must(typeof p.errorCode==='string'&&p.errorCode.length>0, + where+': rejected ACK missing errorCode'); + if(p.graphRevision!==undefined)must(p.graphRevision===state.graph.revision, + where+': rejected ACK changed graph revision'); + if(p.rosterRevision!==undefined)must(p.rosterRevision===state.graph.rosterRevision, + where+': rejected ACK changed roster revision');rejected++; + } + previousAck=p;pending=null; + } + must(!pending&&!previousAck,'trace truncated without ACK + full snapshot'); + must(accepted>0&&rejected>0,'trace needs accepted and rejected rollback'); + return {acceptedCommands:accepted,rejectedCommands:rejected, + finalGraphRevision:state.graph.revision,provenance:t.provenance.kind, + productionCallbackCertified:false,hardwareCertified:false}; +} +export function checkPcm(p){ + must(p?.schema==='arsonmix.console-v6.pcm-evidence.v1'&&Array.isArray(p.cases),'PCM schema missing'); + const required=['independent_inputs','group_fx_return','monitor_isolation','physical_mute'],seen=new Set(); + for(const c of p.cases){ + must(required.includes(c.kind)&&!seen.has(c.kind),'PCM duplicate/unrecognized case'); + seen.add(c.kind); + const s={}; + for(const [k,v] of Object.entries(c.samples||{}))s[k]=sample(v,c.kind+'.'+k); + const get=k=>{must(s[k],c.kind+': missing '+k);return s[k]}; + if(c.kind==='independent_inputs'){ + const a=get('input1'),b=get('input2'); + audible(a,'IN1');audible(b,'IN2'); + must(a.length===b.length&&a.some((x,i)=>Math.abs(x-b[i])>1e-3),'sources must be distinguishable'); + compare(get('ch7'),a,'IN1->CH7');compare(get('ch2'),b,'IN2->CH2'); + }else if(c.kind==='group_fx_return'){ + const dry=get('dry'),grp=get('group'),wet=get('wetReturn'); + must(typeof c.groupGain==='number'&&c.groupGain>0&&c.groupGain<1,'Group must measurably attenuate dry PCM'); + audible(dry,'GROUP dry');audible(wet,'FX RETURN wet'); + must(wet.length===dry.length&&wet.some((x,i)=>Math.abs(x-dry[i])>1e-3),'FX Return cannot duplicate dry PCM'); + compare(grp,dry.map(x=>x*c.groupGain),'serial GROUP'); + compare(get('main'),grp.map((x,i)=>x+wet[i]),'MAIN must contain GROUP+wet without double-dry'); + compare(get('groupMutedMain'),wet,'Group muted retains wet ONLY'); + compare(get('returnMutedMain'),grp,'FX Return muted retains Group dry'); + }else if(c.kind==='monitor_isolation'){ + must(typeof c.mainDestination==='string'&&typeof c.monitorDestination==='string'&&c.mainDestination!==c.monitorDestination,'MONITOR needs distinct destination'); + const main=get('main'),mon=get('monitor');audible(main,'MAIN');audible(mon,'MONITOR'); + compare(get('monitorMuted'),mon.map(()=>0),'MONITOR mute'); + compare(get('mainAfterMonitorMute'),main,'MONITOR mute cannot change MAIN'); + }else{ + const main=get('mainBeforeMute');audible(main,'pre-mute MAIN'); + compare(get('mainAfterMute'),main.map(()=>0),'MASTER mute'); + } + } + must(required.every(k=>seen.has(k)),'missing PCM cases: '+required.filter(k=>!seen.has(k)).join(',')); + return {pcmCases:seen.size,note:'numerical evidence only; synthetic fixtures are not live hardware proof'}; +} +// Gate G3: release evidence must be the ACTUAL files, not plausible-looking +// 64-character claims. Still cannot authenticate CI results or human hearing. +const bundleFile=(dist,name,label)=>{ + must(typeof name==='string'&&name.length>0&&name.length<=140&& + /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)&&!name.includes('..'), + label+': use one safe basename inside the distribution directory'); + return join(dist,name); +}; +const verifiedHash=(p,expected,label)=>{ + must(is64(expected),label+': SHA-256 digest required'); + must(hash(p)===expected,label+': actual file SHA-256 mismatch'); +}; +export function checkRelease(r,dist){ + must(is40(r?.sourceSha),'release: exact source SHA required'); + must(r.nativeCI?.sourceSha===r.sourceSha&&r.nativeCI?.conclusion==='success', + 'release: same-source Windows CI PASS required'); + must(r.chromiumCI?.sourceSha===r.sourceSha&&r.chromiumCI?.conclusion==='success', + 'release: same-source Chromium CI PASS required'); + for(const ci of [r.nativeCI,r.chromiumCI]) + must(/^https:\/\/github\.com\/masarray\/arsonmix\/actions\/runs\/[0-9]+$/.test(ci.url||''), + 'release: GitHub CI run URL required'); + must(r.nativeCTest==='PASS'&&r.chromiumPlaywright==='PASS'&& + r.windowsVerifier==='PASS', + 'release: CTest, Playwright and real Windows package verification required'); + const folder=resolve(dist); + const m=json(join(folder,'BUILD_PROVENANCE.json')); + must(m.sourceCommit===r.sourceSha,'release: packaged sourceCommit mismatches exact CI SHA'); + must(m.fatStatus==='EXPERIMENTAL_NOT_HARDWARE_QUALIFIED', + 'release: package cannot self-certify hardware'); + must(m.peMachine==='AMD64 (0x8664)'&&m.peSubsystem==='WINDOWS_GUI (2)'&& + m.webView2LoaderMode==='JUCE_WEBVIEW2_LOADER_STATIC_LINKED_V1', + 'release: Windows x64 GUI/WebView2 provenance missing'); + const exePath=bundleFile(folder,m.executable,'release exe path'); + must(is64(m.exeSha256),'release: manifest EXE SHA missing'); + verifiedHash(exePath,m.exeSha256,'release EXE'); + must(r.exeSha256===m.exeSha256,'release: EXE evidence digest mismatch'); + const artifacts=r.artifacts; + must(artifacts&&typeof artifacts==='object','release: actual evidence filenames required'); + const names=['zip','nativeTrace','nativePcm','hardwareReport']; + const namesSeen=new Set(); + const files={}; + for(const name of names){ + const file=artifacts[name]; + files[name]=bundleFile(folder,file,'release '+name); + must(!namesSeen.has(file)&&file!==m.executable&&file!=='BUILD_PROVENANCE.json', + 'release: distinct real evidence files required'); + namesSeen.add(file); + } + verifiedHash(files.zip,r.artifactSha256,'release ZIP'); + verifiedHash(files.nativeTrace,r.traceSha256,'release native ACK trace'); + verifiedHash(files.nativePcm,r.pcmSha256,'release native PCM samples'); + const zipBytes=readFileSync(files.zip); + must(zipBytes.length>=4&&zipBytes[0]===0x50&&zipBytes[1]===0x4b&& + zipBytes[2]===0x03&&zipBytes[3]===0x04, + 'release: artifact must be a ZIP; full contents verified by Windows PowerShell verifier'); + const trace=json(files.nativeTrace),pcm=json(files.nativePcm); + must(trace.provenance?.kind==='NATIVE_JUCE'&& + trace.provenance.sourceSha===r.sourceSha&& + trace.provenance.producer==='JUCE_WEBVIEW', + 'release: native WebView producer evidence required; SYNTHETIC not eligible'); + const verifiedTrace=checkTrace(trace); + must(verifiedTrace.provenance==='NATIVE_JUCE', + 'release: cannot qualify synthetic trace'); + must(pcm.provenance?.kind==='NATIVE_JUCE'&& + pcm.provenance.sourceSha===r.sourceSha&& + pcm.provenance.producer==='JUCE_CALLBACK', + 'release: actual JUCE callback PCM provenance required; SYNTHETIC not eligible'); + const verifiedPcm=checkPcm(pcm); + // Native graph admission gate: the final accepted runtime snapshot must + // expose the real universal roster, routes and live capabilities. + const finalEvent=trace.events[trace.events.length-1]; + must(finalEvent?.event==='arMixConsoleSnapshot', + 'release: no final accepted native snapshot'); + const s=finalEvent.payload,caps=s.graph.capabilities; + must(s.productionCallbackLive===true&& + caps.callbackOwnsChannelIds===true&& + caps.fullVendorFxMigration===true&&caps.showAndOutputParity===true&& + caps.physicalCaptureMapped===true&&caps.dynamicChannels===true&& + caps.groups===true&&caps.fxReturns===true&&caps.monitor===true, + 'release: full production ChannelId/VST/Show/physical output capabilities not LIVE'); + const roles=s.graph.channels.map(x=>x.role); + for(const role of ['GROUP','FX_RETURN','MONITOR','MAIN']) + must(roles.includes(role),'release: missing live '+role+' channel'); + must(roles.filter(x=>x==='INPUT').length>=11, + 'release: CH11 native callback not present'); + must(s.device.outputArmed===true&& + s.telemetry.rawCapturePresent===true&& + s.telemetry.mainPcmPresent===true&& + s.telemetry.monitorPcmPresent===true, + 'release: real raw/MAIN/MONITOR PCM and physical output arm required'); + const h=r.hardware; + must(h&&h.issue===15&&h.status==='PENDING_HUMAN_REVIEW', + 'release: hardware issue #15 must stay under human review'); + must(h.backend&&h.sampleRate>0&&h.bufferFrames>0&& + Array.isArray(h.inputPins)&&h.inputPins.length>0&& + Array.isArray(h.outputPins)&&h.outputPins.length>0&& + h.wired===true&&h.testDurationSeconds>=1800, + 'release: wired 0FX physical 30min evidence required'); + must(h.outputOnlyTone==='RECORDED'&&h.captureOnly==='RECORDED'&& + h.dry0Fx==='RECORDED'&&is64(h.fullReportSha256), + 'release: OUTPUT_ONLY_TONE, CAPTURE_ONLY, 0FX and full report required'); + verifiedHash(files.hardwareReport,h.fullReportSha256,'release hardware report'); + must(h.verifiedHumanWitness===true&& + typeof h.witnessId==='string'&&h.witnessId.length>=3, + 'release: independent human witness required'); + return {stage:'EVIDENCE_INTAKE_COMPLETE__ACOUSTIC_REVIEW_REQUIRED', + certified:false,sourceSha:r.sourceSha,exeSha256:m.exeSha256, + pcmCases:verifiedPcm.pcmCases,ackEvents:verifiedTrace.acceptedCommands+ + verifiedTrace.rejectedCommands, + evidenceFilesHashed:names.length}; +} +if(process.argv[1]&&import.meta.url===pathToFileURL(resolve(process.argv[1])).href){ + try{ + const [mode,evidence,dist]=process.argv.slice(2); + must(['trace','pcm','release'].includes(mode)&&evidence,'usage: node scripts/console_v6_fat_gate.mjs trace|pcm|release EVIDENCE.json [dist]'); + const result=mode==='trace'?checkTrace(json(evidence)):mode==='pcm'?checkPcm(json(evidence)):checkRelease(json(evidence),dist||'dist'); + console.log(JSON.stringify({ok:true,mode,...result},null,2)); + }catch(e){console.error('FAT GATE REJECT: '+e.message);process.exitCode=1} +} diff --git a/scripts/package_native_windows.ps1 b/scripts/package_native_windows.ps1 index 0b35cb7f8..158958ed5 100644 --- a/scripts/package_native_windows.ps1 +++ b/scripts/package_native_windows.ps1 @@ -69,6 +69,22 @@ if (-not (Test-Path -LiteralPath $fatGuide -PathType Leaf)) { } Copy-Item -LiteralPath $readme -Destination (Join-Path $OutputDir "README.md") Copy-Item -LiteralPath $fatGuide -Destination (Join-Path $OutputDir "HARDWARE_FAT_GUIDE.md") +# Include a safe offline field-evidence tool in the SAME verified FAT package. +# No audio device/ARM manipulation happens in this script. +$collectorSource="scripts/collect_hardware_fat_windows.ps1" +$collectorName="ArSonMix-Hardware-FAT.ps1" +if (-not (Test-Path -LiteralPath $collectorSource -PathType Leaf)) { throw "Missing FAT field collector" } +Copy-Item -LiteralPath $collectorSource -Destination (Join-Path $OutputDir $collectorName) -Force +Add-Content -LiteralPath (Join-Path $OutputDir "HARDWARE_FAT_GUIDE.md") -Encoding UTF8 -Value @' + +## Offline FAT field evidence recorder (bundled) +PowerShell in extracted ZIP: +- Verify: powershell -NoProfile -ExecutionPolicy Bypass -File .\ArSonMix-Hardware-FAT.ps1 -Action Verify +- For each mode, select the mode in native SIGNAL CHECK FIRST; use -Action Start with actual native -Backend, -SampleRate, -BufferFrames, -InputPins and -OutputPins (comma-separated physical callback ordinals), plus -Wired when appropriate. +- Use -Action Stop -Result CLEAR|CRACKLE|INCONCLUSIVE -Witness "operator ID" -ReportPath "path to COPY FULL REPORT text". This records wall-clock duration and hashes the copied diagnostic log. +- Run -Action Summary after OUTPUT_ONLY_TONE, CAPTURE_ONLY and DRY_THROUGH_0FX. It creates FAT_RUNS.json and FAT_SUMMARY.json next to the app, never arms output and never certifies acoustic quality. +- The ≥30-minute 0FX clean wired soak is reviewed manually against audio heard and diagnostic markers; inspect sensitive endpoint names in files before sharing. +'@ # Same executable, same features. Portable ZIP selects the adjacent Studio/ # data root; installed apps without this file continue using legacy AppData. "ARSONMIX_PORTABLE_WORKSPACE_V1" | @@ -93,6 +109,7 @@ $manifest = [ordered]@{ peFormat = "PE32+" peSubsystem = "WINDOWS_GUI (2)" exeSha256 = (Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash.ToLowerInvariant() + fatCollectorSha256 = (Get-FileHash -LiteralPath (Join-Path $OutputDir $collectorName) -Algorithm SHA256).Hash.ToLowerInvariant() indexHtmlSha256 = (Get-FileHash -LiteralPath "web/index.html" -Algorithm SHA256).Hash.ToLowerInvariant() appJsSha256 = (Get-FileHash -LiteralPath "web/app.js" -Algorithm SHA256).Hash.ToLowerInvariant() stylesCssSha256 = (Get-FileHash -LiteralPath "web/styles.css" -Algorithm SHA256).Hash.ToLowerInvariant() @@ -100,6 +117,9 @@ $manifest = [ordered]@{ pluginUiJsSha256 = (Get-FileHash -LiteralPath "web/plugin-ui.js" -Algorithm SHA256).Hash.ToLowerInvariant() bridgeJsSha256 = (Get-FileHash -LiteralPath "web/bridge.js" -Algorithm SHA256).Hash.ToLowerInvariant() monitorJsSha256 = (Get-FileHash -LiteralPath "web/monitor.js" -Algorithm SHA256).Hash.ToLowerInvariant() + mixerIoJsSha256 = (Get-FileHash -LiteralPath "web/mixer-io.js" -Algorithm SHA256).Hash.ToLowerInvariant() + mixerLayoutJsSha256 = (Get-FileHash -LiteralPath "web/mixer-layout.js" -Algorithm SHA256).Hash.ToLowerInvariant() + hardwareKeysJsSha256 = (Get-FileHash -LiteralPath "web/hardware-keys.js" -Algorithm SHA256).Hash.ToLowerInvariant() guiSource = "web/index.html + web/styles.css + web/plugin-ui.css + web/app.js + web/plugin-ui.js + web/bridge.js + web/monitor.js (JUCE BinaryData)" guiCalibration = "GAIN_10_TO_MINUS60_BLACK_DETENT_AT_38PX__VU_DBFS_INDEPENDENT_TICKS" fatStatus = "EXPERIMENTAL_NOT_HARDWARE_QUALIFIED" diff --git a/scripts/run_console_native_s0.mjs b/scripts/run_console_native_s0.mjs new file mode 100644 index 000000000..f806eaa56 --- /dev/null +++ b/scripts/run_console_native_s0.mjs @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// S0: only the actual C++ emitter may create the source fixture. +// The single canonical schema implementation is PR #279 puzzle-seam. +import {execFileSync} from 'node:child_process'; +import {createHash} from 'node:crypto'; +import {readFileSync,writeFileSync} from 'node:fs'; +import {resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {snapshot,intent,ack} from '../integration/console-v6/puzzle-seam.mjs'; +const block=s=>{throw Error('S0 BLOCKED: '+s)}; +const req=(x,s)=>{if(!x)block(s)}; +export function verifyNativeS0(events){ + req(Array.isArray(events)&&events.length===4,'C++ source must emit 4 events'); + const order=['arMixConsoleSnapshot','arMixConsoleIntent','arMixConsoleAck','arMixConsoleSnapshot']; + events.forEach((e,i)=>req(e?.event===order[i]&&e.payload, + 'native event '+i+' expected '+order[i])); + const [s,cmd,reject,next]=events.map(e=>e.payload); + snapshot(s);snapshot(next);intent(cmd);ack(reject,cmd,s,next); + req(!s.productionCallbackLive&&!next.productionCallbackLive&& + !s.graph.channels.length&&!s.graph.capabilities.supportedOps.length, + 'G0 cannot declare installed ChannelId callback'); + req(cmd.deviceEpoch===s.device.epoch&& + cmd.baseGraphRevision===s.graph.revision&& + cmd.baseRosterRevision===s.graph.rosterRevision, + 'operator request not based on native accepted state'); + req(reject.status==='REJECTED'&&reject.errorCode&& + reject.graphRevision===s.graph.revision&& + reject.rosterRevision===s.graph.rosterRevision,'native ACK must reject and preserve revision'); + req(JSON.stringify(s.graph)===JSON.stringify(next.graph)&& + s.device.epoch===next.device.epoch&& + JSON.stringify(s.device.enabledInputs)===JSON.stringify(next.device.enabledInputs)&& + JSON.stringify(s.device.enabledOutputs)===JSON.stringify(next.device.enabledOutputs)&& + JSON.stringify(s.device.inputEndpoints)===JSON.stringify(next.device.inputEndpoints)&& + JSON.stringify(s.device.outputEndpoints)===JSON.stringify(next.device.outputEndpoints)&& + s.device.outputArmed===next.device.outputArmed, + 'rejected native intent changed accepted graph/device/output ARM'); + return {gate:'S0_CXX_SOURCE_SOCKET',callbackPcmProven:false, + deviceEpoch:s.device.epoch,revision:s.graph.revision, + requestId:cmd.requestId}; +} +export function assertExplicitS0Exporter(generator,execute=execFileSync){ + req(typeof generator==='string'&&generator.length>0, + 'native JUCE exporter executable path required'); + // A crash (0xC0000409), missing binary, access error, or unrelated failing + // CTest is NOT proof that CLI argument parsing deliberately rejected a + // bogus flag. A clear stderr rejection marker is mandatory. + let deliberate=false; + try{ + execute(resolve(generator),['--arsonmix-s0-deliberately-unsupported-option'],{ + encoding:null,maxBuffer:1024*1024,timeout:15000,windowsHide:true, + stdio:['ignore','pipe','pipe'] + }); + }catch(e){ + const diagnostic=Buffer.isBuffer(e?.stderr)? + e.stderr.toString('utf8'):typeof e?.stderr==='string'?e.stderr:''; + deliberate=typeof e?.status==='number'&&e.status!==0&& + !e.signal&&diagnostic.includes('ARSONMIX_S0_UNSUPPORTED_ARGUMENT'); + if(!deliberate)throw new Error( + 'S0 BLOCKED: unknown-flag probe crashed, failed to execute, or lacked explicit rejection marker'); + } + req(deliberate, + 'C++ binary ignored unknown flag; portable fixture is NOT an actual JUCE exporter'); +} +export function generateS0({generator,output,sourceSha}){ + req(/^[a-f0-9]{40}$/.test(sourceSha||''),'full source SHA required'); + req(generator&&output,'C++ exporter and single output JSON required'); + const binary=resolve(generator); + // A portable C++ sample that silently ignores argv must NEVER be accepted + // as a callable JUCE native event exporter. Unknown command MUST fail. + assertExplicitS0Exporter(binary,execFileSync); + const buf=execFileSync(binary,['--emit-console-s0-json'], + {encoding:null,maxBuffer:8*1024*1024,timeout:15000,windowsHide:true}); + let data;try{data=JSON.parse(buf.toString('utf8'))} + catch{block('C++ stdout must contain a single JSON object')} + const status=verifyNativeS0(data.events); + writeFileSync(resolve(output),buf); + const sha=createHash('sha256').update(buf).digest('hex'); + req(createHash('sha256').update(readFileSync(resolve(output))).digest('hex')===sha, + 'native fixture bytes changed'); + return {...status,sourceSha,nativeFixtureSha256:sha, + path:resolve(output),cppGenerator:resolve(generator),uatReady:false}; +} +if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){ + const argv=process.argv.slice(2),a=x=>argv.includes(x)?argv[argv.indexOf(x)+1]:undefined; + try{ + const actual=execFileSync('git',['rev-parse','HEAD'],{encoding:'utf8'}).trim(); + req(a('--source-sha')===actual,'generator build source SHA must equal current git HEAD'); + console.log(JSON.stringify(generateS0({generator:a('--generator'), + output:a('--output'),sourceSha:actual}),null,2)); + }catch(e){console.error(e.message);process.exitCode=1} +} diff --git a/scripts/verify_console_s0_native_fixture.mjs b/scripts/verify_console_s0_native_fixture.mjs new file mode 100644 index 000000000..b343db2a7 --- /dev/null +++ b/scripts/verify_console_s0_native_fixture.mjs @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Puzzle v8 S0 independent byte-parity preflight on the ONE integrated tree. +// Actually compiles and executes the C++ ENGINE serializer in this checkout, +// compares emitted BYTES to GUI's checked-in native fixture, then uses the +// single #279 wire and optional Playwright GUI consumer on those same bytes. +// NEVER implies actual JUCE audio callback, physical output or hardware FAT. +import {execFileSync} from 'node:child_process'; +import {createHash} from 'node:crypto'; +import {mkdtempSync,readFileSync,rmSync,writeFileSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {resolve,join} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {generateS0} from './run_console_native_s0.mjs'; +const root=resolve(fileURLToPath(new URL('..',import.meta.url))); +const hash=x=>createHash('sha256').update(x).digest('hex'); +const fail=s=>{throw Error('S0 PRODUCER/GUI BYTE-PARITY BLOCKED: '+s)}; +const assert=(ok,s)=>{if(!ok)fail(s)}; +export function verifySourceBindings({read=readFileSync}={}){ + const producer=read(join(root,'tests/console_puzzle_v8_fixture.cpp'),'utf8'); + const native=read(join(root,'src/ConsoleLiveBridgeV6.h'),'utf8'); + const dispatcher=read(join(root,'src/Main.cpp'),'utf8'); + const gui=read(join(root,'tests/operator_console_v6_smoke.py'),'utf8'); + assert(producer.includes('PuzzleV8Wire::fixture(snapshot,ack)'), + 'ENGINE fixture must use the runtime shared serializer, not a separate JSON schema'); + assert(native.includes('PuzzleV8Wire::snapshot(w)')&& + native.includes('PuzzleV8Wire::ack(ack)'), + 'ENGINE native JUCE bridge not using identical C++ snapshot and ACK serializers'); + assert(dispatcher.includes('arMixConsoleSnapshot')&& + dispatcher.includes('arMixConsoleIntent')&& + dispatcher.includes('arMixConsoleAck'), + 'JUCE dispatcher missing one of the canonical native WebView event paths'); + assert(gui.includes('tests/fixtures/console-v8-native-unready.json')|| + gui.includes('console-v8-native-unready.json'), + 'GUI smoke must load the exact same native C++ golden fixture'); + return true; +} +// Real G0 S0 admission: the ENGINE-owned JUCE binary must explicitly +// implement --emit-console-s0-json (and reject unsupported flags). The +// same *actual* emitted bytes are passed to both shared FAT wire and GUI. +export function runActualNativeS0({generator,output,playwright=true}={}){ + assert(generator,'ENGINE JUCE exporter executable required for native S0'); + verifySourceBindings(); + const current=execFileSync('git',['rev-parse','HEAD'],{ + cwd:root,encoding:'utf8'}).trim(); + assert(/^[a-f0-9]{40}$/.test(current),'exact checkout SHA required'); + const dir=mkdtempSync(join(tmpdir(),'arsonmix-s0-juce-')); + const nativePath=output?resolve(output):join(dir,'juce-native-s0.json'); + try{ + const proof=generateS0({generator,output:nativePath,sourceSha:current}); + if(playwright)execFileSync(process.env.PYTHON||'python',[ + join(root,'tests/console_native_s0_playwright.py'),'--fixture',nativePath + ],{cwd:root,stdio:'inherit',timeout:120000}); + return {status:playwright?'S0_NATIVE_CONTROL_PLANE_GUI_MATCH': + 'S0_NATIVE_CONTROL_PLANE_ONLY', + ...proof,playwright:playwright?'PASS':'NOT_RUN', + nativeCallbackAudio:'NOT_PROVEN',fullMixerReady:false,hardwareFAT:'PENDING'}; + }finally{rmSync(dir,{recursive:true,force:true})} +} +export function run({output,playwright=false}={}){ + verifySourceBindings(); + const current=execFileSync('git',['rev-parse','HEAD'],{ + cwd:root,encoding:'utf8'}).trim(); + assert(/^[a-f0-9]{40}$/.test(current),'git HEAD cannot be resolved'); + const expectedPath=join(root,'tests/fixtures/console-v8-native-unready.json'); + const expected=readFileSync(expectedPath); + const expectedSha=hash(expected); + const gui=readFileSync(join(root,'tests/operator_console_v6_smoke.py'),'utf8'); + assert(gui.includes(expectedSha), + 'GUI locked fixture digest differs from C++-checked-in golden file bytes'); + const dir=mkdtempSync(join(tmpdir(),'arsonmix-s0-cxx-')); + const generated=output?resolve(output):join(dir,'cpp-produced.json'); + try{ + const cpp=join(root,'tests/console_puzzle_v8_fixture.cpp'); + const exe=join(dir,process.platform==='win32'?'s0-producer.exe':'s0-producer'); + // Ubuntu Chromium runner and Linux developer machines have a C++20 + // compiler; use CXX override for other POSIX toolchains. We do NOT mock + // compiler output. Native Windows MSVC is checked by CTest separately. + assert(process.platform!=='win32', + 'this portable S0 C++ compile gate runs on Chromium/Linux; Windows MSVC CTest is separate'); + const compiler=process.env.CXX||'c++'; + execFileSync(compiler,[ + '-std=c++20','-O2','-Wall','-Wextra','-Werror','-pedantic', + cpp,'-o',exe + ],{cwd:root,stdio:'pipe',timeout:120000}); + // Portable fixture: execute the compiled C++ main with NO argv. It is + // explicitly not the live JUCE exporter and cannot qualify S0 runtime. + const actual=execFileSync(exe,[],{cwd:root,encoding:null,timeout:15000, + maxBuffer:8*1024*1024}); + writeFileSync(generated,actual); + assert(actual.equals(expected), + 'ENGINE compiled stdout byte mismatch with checked-in GUI native JSON fixture'); + assert(hash(actual)===expectedSha, + 'portable C++ producer digest differs from one shared GUI golden SHA256'); + if(playwright){ + execFileSync(process.env.PYTHON||'python',[ + join(root,'tests/console_native_s0_playwright.py'), + '--fixture',generated + ],{cwd:root,stdio:'inherit',timeout:120000}); + } + return {status:'PORTABLE_CPP_SERIALIZER_PARITY_ONLY_NOT_S0', + sourceSha:current,sharedFixtureSha256:expectedSha, + events:4,sourceBindings:'STATIC_MATCH',nativeCallbackAudio:'NOT_PROVEN', + nativeEventExporter:'NOT_EXECUTED',nativeControlPlaneS0:'BLOCKED', + PlaywrightPortableGolden:playwright?'PASS':'NOT_RUN', + fullMixerReady:false,hardwareFAT:'PENDING'}; + }finally{rmSync(dir,{recursive:true,force:true})} +} +if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){ + try{ + const args=process.argv.slice(2),i=args.indexOf('--output'); + const output=i>=0?args[i+1]:undefined; + assert(i<0||output,'--output requires path'); + const nativeIndex=args.indexOf('--native-generator'); + const native=nativeIndex>=0?args[nativeIndex+1]:undefined; + assert(nativeIndex<0||native,'--native-generator requires built JUCE executable'); + const actual=native?runActualNativeS0({generator:native,output, + playwright:!args.includes('--skip-playwright')}): + run({output,playwright:args.includes('--playwright')}); + console.log(JSON.stringify(actual,null,2)); + }catch(e){console.error(e.stack||e.message);process.exitCode=1} +} diff --git a/scripts/verify_native_windows_artifact.ps1 b/scripts/verify_native_windows_artifact.ps1 index 2641426bb..1cd5a364e 100644 --- a/scripts/verify_native_windows_artifact.ps1 +++ b/scripts/verify_native_windows_artifact.ps1 @@ -10,6 +10,7 @@ $expected = @( "ArSonMix-GUI10CH-P012-Windows-x64.exe", "BUILD_PROVENANCE.json", "HARDWARE_FAT_GUIDE.md", + "ArSonMix-Hardware-FAT.ps1", "README.md", "portable_mode.txt" ) @@ -33,6 +34,13 @@ if (@(Compare-Object -ReferenceObject $expected -DifferenceObject $actual).Count } $manifest = Get-Content -LiteralPath (Join-Path $OutputDir "BUILD_PROVENANCE.json") -Raw -Encoding UTF8 | ConvertFrom-Json +# The exact executable and field recorder are both hash-bound to this source SHA. +$collectorPath=Join-Path $OutputDir "ArSonMix-Hardware-FAT.ps1" +$collectorHash=(Get-FileHash -LiteralPath $collectorPath -Algorithm SHA256).Hash.ToLowerInvariant() +$sourceCollectorHash=(Get-FileHash -LiteralPath "scripts/collect_hardware_fat_windows.ps1" -Algorithm SHA256).Hash.ToLowerInvariant() +if ($collectorHash -ne $sourceCollectorHash -or $collectorHash -ne $manifest.fatCollectorSha256) { + throw "FAT collector SHA mismatch in packaged distribution" +} # App-only ZIP does not ship an untracked dynamic WebView2Loader.dll. if ($manifest.webView2LoaderMode -ne "JUCE_WEBVIEW2_LOADER_STATIC_LINKED_V1" -or $manifest.guiStartupVerification -ne "WEBVIEW2_PREFLIGHT_AND_AR_MIX_GUI_READY_HANDSHAKE") { @@ -76,7 +84,10 @@ $resources = @( @{Path="web/plugin-ui.css"; Hash=$manifest.pluginUiCssSha256}, @{Path="web/plugin-ui.js"; Hash=$manifest.pluginUiJsSha256}, @{Path="web/bridge.js"; Hash=$manifest.bridgeJsSha256}, - @{Path="web/monitor.js"; Hash=$manifest.monitorJsSha256} + @{Path="web/monitor.js"; Hash=$manifest.monitorJsSha256}, + @{Path="web/mixer-io.js"; Hash=$manifest.mixerIoJsSha256}, + @{Path="web/mixer-layout.js"; Hash=$manifest.mixerLayoutJsSha256}, + @{Path="web/hardware-keys.js"; Hash=$manifest.hardwareKeysJsSha256} ) $embeddedText = [Text.Encoding]::UTF8.GetString($bytes) foreach ($item in $resources) { @@ -166,6 +177,17 @@ try { $stream.Dispose() } if ($inZipHash -ne $appHash) { throw "ZIP entry hash mismatch" } + $collectorEntry=$zip.GetEntry("ArSonMix-Hardware-FAT.ps1") + if ($null -eq $collectorEntry) { throw "Missing FAT collector inside ZIP" } + $collectorStream=$collectorEntry.Open() + $collectorHasher=[Security.Cryptography.SHA256]::Create() + try { + $inZipCollector=[BitConverter]::ToString($collectorHasher.ComputeHash($collectorStream)).Replace("-","").ToLowerInvariant() + } finally { + $collectorHasher.Dispose() + $collectorStream.Dispose() + } + if ($inZipCollector -ne $collectorHash) { throw "ZIP field collector SHA mismatch" } foreach ($rel in $factoryZipFiles) { $item = $zip.GetEntry($rel) if ($null -eq $item) { throw "FactoryFX file missing in ZIP: $rel" } diff --git a/src/ConsoleLiveBridgeV6.h b/src/ConsoleLiveBridgeV6.h new file mode 100644 index 000000000..4fafb349c --- /dev/null +++ b/src/ConsoleLiveBridgeV6.h @@ -0,0 +1,557 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include "../integration/ConsoleNativeContractV6.h" +#include "../engine/core/ConsolePuzzleV8Wire.h" +#include +#include +#include +#include +#include +#include +#include +#include + +// Native Console v6 adapter, exclusively on the JUCE MESSAGE/CONTROL thread. +// This projects the real M4 callback/device readback WITHOUT promoting its +// fixed strip indexes to fictitious ChannelIds. The production ChannelId +// migration must replace this deliberately fail-closed G0 capability gate. +// It never owns PCM, clones VST3, or calls the audio device from the browser. +namespace armix::console { +class LiveConsoleBridgeV6 final { +public: + static constexpr int schemaVersion=6; + + // Source: LiveAudioEngine::status() with its real JUCE callback telemetry, + // driver active masks and epoch. No browser invented physical pins. + static juce::var snapshot(const juce::var& live) { + // Single actual native producer for both JUCE WebView and S0 + // fixture. No JSON shape authored by the JS/GUI. + PuzzleV8Snapshot w; + const auto route=live.getProperty("dryRoutingLab",juce::var()); + // The control session has an epoch even before a driver is opened. + // 1 is the UNREADY session generation, NOT a fabricated physical + // source; any later verified device epoch supersedes this token. + auto actualEpoch=decimalFromNative(route.getProperty("epoch",juce::var())); + if(actualEpoch=="0")actualEpoch="1"; + w.epoch=actualEpoch.toStdString(); + w.legacyRoutingRevision=decimalFromNative( + route.getProperty("revision",juce::var())).toStdString(); + // The accepted fixed-M4 revision stays under legacyM4 only. + // A ChannelId revision is never copied from an ordinal M4 graph. + w.legacyActive=static_cast(route.getProperty("active",false)); + w.legacyRouteAccepted=static_cast(route.getProperty("ready",false)) && + static_cast(route.getProperty("hasAcceptedRoute",false)); + w.backend=live.getProperty("driver","").toString().toStdString(); + w.captureDevice=live.getProperty("inputDevice","").toString().toStdString(); + w.playbackDevice=live.getProperty("outputDevice","").toString().toStdString(); + const double rate=static_cast(live.getProperty("rate",0.)); + if(std::isfinite(rate) && rate>0. && rate<=384000.) + w.sampleRate=static_cast(rate); + const int frames=static_cast(live.getProperty("buffer",0)); + if(frames>0)w.bufferFrames=frames; + const bool connected=static_cast(live.getProperty("connected",false)); + w.outputArmed=connected && w.legacyRouteAccepted && + static_cast(live.getProperty("monitor",false)) && + static_cast(live.getProperty("directRouteAuthorized",false)); + const auto peak=static_cast(live.getProperty("inputPeak",0.)); + if(std::isfinite(peak) && peak>=0.)w.rawCapturePeak=peak; + w.rawCapturePresent=connected && + static_cast(live.getProperty("callbackCount",0.))>0. && + static_cast(live.getProperty("callbackInputChannels",0))>0 && + w.rawCapturePeak>0.0005; + w.mainPcmPresent=w.outputArmed && + static_cast(live.getProperty("peak",0.))>0.0002; + w.monitorPcmPresent=w.outputArmed && + static_cast(route.getProperty("monitorPeakL",0.))>0.0002; + const auto pins=route.getProperty("ports",juce::var()); + const auto peaks=live.getProperty("captureCallbackPeaks",juce::var()); + const auto* readings=peaks.getArray(); + if(const auto* physical=pins.getArray()) + for(const auto& p:*physical) { + const auto number=p.getProperty("port",juce::var()); + const auto ordinal=p.getProperty("callback",juce::var()); + if(!number.isInt()||!ordinal.isInt())continue; + PuzzleV8Pin pin; + pin.port=static_cast(number); + pin.callback=static_cast(ordinal); + if(pin.port<0 || pin.callback<0)continue; + pin.label=p.getProperty("label","").toString().toStdString(); + if(readings && pin.callbacksize()) { + const auto value=readings->getReference(pin.callback); + if(value.isInt()||value.isDouble()) { + const auto peakValue=static_cast(value); + if(std::isfinite(peakValue)&&peakValue>=0.) { + pin.hasRawPeak=true;pin.rawPeak=peakValue; + } + } + } + w.inputs.push_back(std::move(pin)); + } + const auto outputs=route.getProperty("outputPorts",juce::var()); + if(const auto* ports=outputs.getArray()) + for(int ordinal=0;ordinalsize();++ordinal) { + const auto value=ports->getReference(ordinal); + if(!value.isInt())continue; + const int physical=static_cast(value); + if(physical<0)continue; + w.outputs.push_back({physical,ordinal,{},{},0.}); + } + // The installed ABI is still M4 ordinals, but the single JUCE + // callback may now select the real native ChannelId PCM renderer + // with original CH1/Orbit lease after accepted admission. Neither + // physical mode implies universal CH11/GROUP/WIRE ownership. + w.productionCallbackLive=false; + const auto bytes=PuzzleV8Wire::snapshot(w); + auto actual=juce::JSON::parse(juce::String::fromUTF8(bytes.c_str())); + // Optional diagnosed M4 accepted controls are sourced from the + // installed JUCE control thread, not stale immutable routing faders. + // UNREADY fixture stays byte-identical; these are NOT ChannelIds. + const auto legacy=actual.getProperty("legacyM4",{}); + if(auto* object=legacy.getDynamicObject()) { + // Current native M4 (not a fake ChannelId roster): exactly the + // signal that is audible in this physical device callback. + const auto controls=route.getProperty("channelControls",juce::var()); + const auto peaksL=route.getProperty("channelPeaksL",juce::var()); + const auto peaksR=route.getProperty("channelPeaksR",juce::var()); + const auto inserts=route.getProperty("fxInstances",juce::var()); + if(controls.isArray())object->setProperty("channelControls",controls); + if(peaksL.isArray())object->setProperty("channelPeaksL",peaksL); + if(peaksR.isArray())object->setProperty("channelPeaksR",peaksR); + if(inserts.isArray())object->setProperty("fxInstances",inserts); + const auto topo=route.getProperty("acceptedRoute",juce::var()); + if(topo.isObject()) { + const auto sends=topo.getProperty("sends",juce::var()); + const auto returns=topo.getProperty("auxes",juce::var()); + if(sends.isArray())object->setProperty("acceptedSends",sends); + if(returns.isArray())object->setProperty("auxReturns",returns); + // Legacy M4 physical inputs/output membership are CONTROL + // readbacks from the actually admitted 10-strip route. Never + // infer them from presentation order or a UI draft. + const auto channels=topo.getProperty("channels",juce::var()); + if(connected && w.legacyActive && w.legacyRouteAccepted && + !static_cast(route.getProperty("topologyFault",false)) && + channels.isArray() && + channels.getArray()->size()==armix::mixer::stripCount) { + object->setProperty("acceptedChannels",channels); + object->setProperty("controlPlane","LEGACY_M4_ORDINAL"); + // Real accepted PCM provenance for FAT/GUI diagnostics. + // Read from LiveAudioEngine's installed callback, not + // guessed browser roles. This does NOT enable universal + // supportedOps, ChannelIds, or graph revision. + const bool native=static_cast(route.getProperty( + "nativeChannelIdPcmActive",false)); + object->setProperty("pcmRenderer",native + ?"CHANNEL_ID_10CH4AUX":"M4_COMPAT"); + object->setProperty("originalCh1GraphLeased", + native && static_cast(route.getProperty( + "originalCh1GraphLeased",false))); + // Separate namespace: these operations mutate the one + // INSTALLED M4 JUCE PCM graph. They are NEVER universal + // graph.capabilities.supportedOps or ChannelIds. + juce::Array allowed; + for(const char* op: {"SET_SOURCE","SET_PROCESSING_FORMAT", + "SET_PRIMARY_OUT","SET_FADER","SET_PAN","SET_MUTE","SET_SOLO"}) + allowed.add(juce::var(juce::String(op))); + if(returns.isArray())allowed.add(juce::var("SET_AUX_FADER")); + if(sends.isArray()&&!sends.getArray()->isEmpty()) + allowed.add(juce::var("SET_SEND_LEVEL")); + if(inserts.isArray()) { + bool hasNativeFx=false; + for(const auto& rack:*inserts.getArray()) + if(rack.isArray()&&!rack.getArray()->isEmpty()) { + hasNativeFx=true;break; + } + if(hasNativeFx) { + allowed.add(juce::var("SET_INSERT_BYPASS")); + allowed.add(juce::var("OPEN_INSERT_EDITOR")); + } + } + object->setProperty("supportedOps",juce::var(allowed)); + } + } + const auto monitorSends=route.getProperty("monitorSends",juce::var()); + if(monitorSends.isArray()) + object->setProperty("monitorSends",monitorSends); + const auto main=route.getProperty("mainOutputs",juce::var()); + if(main.isArray())object->setProperty("mainOutputs",main); + const auto monitor=route.getProperty("monitorOutputs",juce::var()); + if(monitor.isArray()) { + object->setProperty("monitorOutputs",monitor); + if(object->hasProperty("supportedOps") && + monitor.getArray()->size()==2) { + auto operations=object->getProperty("supportedOps"); + if(auto* list=operations.getArray()) { + list->add(juce::var("SET_MONITOR_LEVEL")); + object->setProperty("supportedOps",operations); + } + } + } + } + return actual; + } + + // Exact native wire: opaque, unique-per-editor requestId and uint64 + // canonical DECIMAL STRINGS, never a lossy double / JS Number cast. + // This G0 adapter has no supported mutating operation: an invalid/stale + // request or unsupported role must preserve the currently audible M4. + juce::var rejectUnsupportedIntent(const juce::var& intent, + const juce::var& acceptedSnapshot) { + const auto request=intent.getProperty("requestId",juce::var()); + const auto id=request.isString()?request.toString():juce::String{}; + const auto requestBytes=id.toStdString(); + const auto device=acceptedSnapshot.getProperty("device",{}); + const auto graph=acceptedSnapshot.getProperty("graph",{}); + const auto epoch=device.getProperty("epoch","0").toString(); + juce::String fault="UNIVERSAL_CALLBACK_NOT_READY"; + if(!armix::integration::validConsoleRequestId(requestBytes)) + fault="INVALID_REQUEST_ID"; + else if(completed_.find(requestBytes)!=completed_.end()) + fault="DUPLICATE_REQUEST_ID"; + else { + if(recentIds_.size()==maxRecentIds) { + completed_.erase(recentIds_.front()); + recentIds_.pop_front(); + } + recentIds_.push_back(requestBytes); + completed_.insert(requestBytes); + // G0 is fail closed by design. Distinguish malformed/stale wire + // from a legitimate mutation that requires the M4->M5 cutover. + std::uint64_t asked=0,baseGraph=0,baseRoster=0; + const bool wellFormed=decodeDecimal(intent.getProperty("deviceEpoch",{}),asked) && + decodeDecimal(intent.getProperty("baseGraphRevision",{}),baseGraph) && + decodeDecimal(intent.getProperty("baseRosterRevision",{}),baseRoster) && + intent.getProperty("operation",{}).isString(); + if(!wellFormed)fault="INVALID_DECIMAL_WIRE"; + else if(intent.getProperty("deviceEpoch",{}).toString()!=epoch) + fault="STALE_DEVICE_EPOCH"; + else if(intent.getProperty("baseGraphRevision",{}).toString()!= + graph.getProperty("revision","0").toString() || + intent.getProperty("baseRosterRevision",{}).toString()!= + graph.getProperty("rosterRevision","0").toString()) + fault="STALE_GRAPH_REVISION"; + else { + const auto target=intent.getProperty("targetChannelId",juce::var()); + armix::mixer::ChannelId channel{}; + if(!target.isVoid() && + (!target.isString() || + !armix::integration::parseNativeChannelId( + target.toString().toStdString(),channel))) + fault="INVALID_CHANNEL_ID"; + } + } + PuzzleV8Ack ack; + ack.requestId=requestBytes; + ack.status="REJECTED"; + ack.deviceEpoch=epoch.toStdString(); + ack.graphRevision=graph.getProperty("revision","0").toString().toStdString(); + ack.rosterRevision=graph.getProperty("rosterRevision","0").toString().toStdString(); + ack.errorCode=fault.toStdString(); + const auto bytes=PuzzleV8Wire::ack(ack); + return juce::JSON::parse(juce::String::fromUTF8(bytes.c_str())); + } + + + // S1 production bridge: operate the ACTUALLY INSTALLED M4 graph through + // LiveAudioEngine. A Legacy M4 lane is addressed by decimal "1".."10" + // only for this explicit internal migration transport. This does NOT + // claim that callbackOwnsChannelIds, CH11, GROUP or FX_RETURN exist. + // The same native audio owner, plugin editor and Show remain installed. + template + juce::var processProductionIntent(const juce::var& intent, + const juce::var& acceptedSnapshot, + Engine& engine,OpenEditor&& openEditor) { + const auto request=intent.getProperty("requestId",{}); + const auto requestId=request.isString()?request.toString():juce::String{}; + const auto bytes=requestId.toStdString(); + const auto device=acceptedSnapshot.getProperty("device",{}); + const auto graph=acceptedSnapshot.getProperty("graph",{}); + const auto epoch=device.getProperty("epoch","0").toString(); + const auto oldRev=graph.getProperty("revision","0").toString(); + const auto oldRoster=graph.getProperty("rosterRevision","0").toString(); + const auto legacyRev=acceptedSnapshot.getProperty("legacyM4",{}) + .getProperty("routingRevision","0").toString(); + juce::String error; + bool accepted=false; + if(!armix::integration::validConsoleRequestId(bytes))error="INVALID_REQUEST_ID"; + else if(completed_.find(bytes)!=completed_.end())error="DUPLICATE_REQUEST_ID"; + else { + if(recentIds_.size()==maxRecentIds) { + completed_.erase(recentIds_.front()); + recentIds_.pop_front(); + } + recentIds_.push_back(bytes); + completed_.insert(bytes); + std::uint64_t ep=0,rev=0,roster=0,channelId=0,m4Revision=0; + const auto target=intent.getProperty("targetChannelId",{}); + const auto payload=intent.getProperty("payload",{}); + const auto operation=intent.getProperty("operation",{}).toString(); + if(!decodeDecimal(intent.getProperty("deviceEpoch",{}),ep) || + !decodeDecimal(intent.getProperty("baseGraphRevision",{}),rev) || + !decodeDecimal(intent.getProperty("baseRosterRevision",{}),roster)) + error="INVALID_DECIMAL_WIRE"; + else if(intent.getProperty("deviceEpoch",{}).toString()!=epoch) + error="STALE_DEVICE_EPOCH"; + else if(intent.getProperty("baseGraphRevision",{}).toString()!=oldRev || + intent.getProperty("baseRosterRevision",{}).toString()!=oldRoster) + error="STALE_GRAPH_REVISION"; + // M4's presentation ordinals are NOT universal ChannelIds. + // A legacy-console intent requires an explicit independent + // revision fence. Without it, reject rather than silently + // alias the ChannelId graph's revision 0 to an M4 revision. + else if(!decodeDecimal(intent.getProperty("legacyRoutingRevision",{}), + m4Revision) || + intent.getProperty("legacyRoutingRevision","").toString()!=legacyRev) + error="STALE_LEGACY_ROUTING_REVISION"; + else if(!target.isString() || !decodeDecimal(target,channelId) || + channelId<1 || + (channelId>10 && + !((operation=="SET_MONITOR_LEVEL"|| + operation=="SET_AUX_FADER")&&channelId<=14))) + error="INVALID_LEGACY_CHANNEL_ID"; + // Never trust a guessed M4 ordinal or synthetic editor status. + // Native accepted hardware, actual route rows and the current + // topology-fault bit must have produced an explicit M4 authority + // envelope in this very same status snapshot. + else if(acceptedSnapshot.getProperty("legacyM4",{}) + .getProperty("controlPlane","").toString()!="LEGACY_M4_ORDINAL" || + !engine.dryRoutingLabActive() || + engine.dryRoutingLabEpoch()!=ep || + engine.dryRoutingLabRevision()!=m4Revision) + error="PRODUCTION_GRAPH_NOT_ADMITTED"; + else if(!payload.isObject())error="INVALID_PAYLOAD"; + else { + const int lane=static_cast(channelId-1); + if(operation=="SET_SOURCE") { + const auto id=payload.getProperty("portId",{}).toString(); + int left=-1; + if(parsePortId(id,"in:",left)) { + const auto rightId=payload.getProperty("rightPortId",{}).toString(); + int right=-1; + const auto format=payload.getProperty("sourceFormat","MONO").toString(); + if(format=="STEREO" && !parsePortId(rightId,"in:",right)) + error="INVALID_STEREO_RIGHT_PIN"; + else if(format!="MONO"&&format!="STEREO") + error="INVALID_SOURCE_FORMAT"; + else error=engine.switchDryRoutingLabSource( + lane,ep,m4Revision,format,left,right); + } else error="INVALID_PHYSICAL_INPUT_PORT"; + accepted=error.isEmpty(); + } else if(operation=="SET_FADER"||operation=="SET_PAN"|| + operation=="SET_MUTE"||operation=="SET_SOLO") { + const bool binary=operation=="SET_MUTE"||operation=="SET_SOLO"; + const auto value=payload.getProperty(binary?"value":"valueDb",{}); + juce::String key; + float control=0.f; + if(binary) { + const auto b=payload.getProperty("value",{}); + const auto on=payload.getProperty("enabled",b); + if(!on.isBool())error="INVALID_BOOLEAN_CONTROL"; + else control=static_cast(on)?1.f:0.f; + } else { + const auto number=payload.getProperty( + operation=="SET_FADER"?"valueDb":"value",{}); + if(!number.isInt()&&!number.isDouble()) + error="INVALID_NUMERIC_CONTROL"; + else { + const double v=static_cast(number); + if(!std::isfinite(v))error="NON_FINITE_CONTROL"; + else control=static_cast(v); + } + } + if(error.isEmpty()) { + if(operation=="SET_FADER")key="faderDb"; + else if(operation=="SET_PAN")key="pan"; + else if(operation=="SET_MUTE")key="mute"; + else key="solo"; + accepted=engine.setDryRoutingLabParameter( + lane,ep,m4Revision,key,control); + if(!accepted)error="NATIVE_CONTROL_REJECTED"; + } + } else if(operation=="CONNECT_AUX_SEND") { + const auto bus=payload.getProperty("auxIndex",{}); + const auto tapName=payload.getProperty("tap","POST").toString(); + const auto gain=payload.getProperty("value",{}); + const auto pan=payload.getProperty("pan",juce::var(0.0)); + if(!bus.isInt()||static_cast(bus)<0|| + static_cast(bus)>=armix::mixer::auxBusCount) + error="INVALID_AUX_RETURN"; + else if(tapName!="PRE"&&tapName!="POST") + error="INVALID_SEND_TAP"; + else if((!gain.isInt()&&!gain.isDouble())|| + (!pan.isInt()&&!pan.isDouble())) + error="INVALID_SEND_GAIN_OR_PAN"; + else { + const double level=static_cast(gain); + const double balance=static_cast(pan); + if(!std::isfinite(level)||level<0.||level>1.|| + !std::isfinite(balance)||balance< -1.||balance>1.) + error="INVALID_SEND_GAIN_OR_PAN"; + else { + error=engine.connectDryRoutingLabAuxSend( + lane,static_cast(bus),ep,m4Revision, + tapName=="PRE"?armix::mixer::SendTap::preFader: + armix::mixer::SendTap::postFader, + static_cast(level),static_cast(balance)); + accepted=error.isEmpty(); + } + } + } else if(operation=="SET_AUX_FADER") { + // Native AUX return fader AFTER its real VST3 rack. + // 11..14 are explicit legacy M4 auxiliary ordinals; + // never pretend these are stable universal ChannelIds. + if(channelId<11||channelId>14) + error="INVALID_LEGACY_AUX_CHANNEL"; + else { + const auto raw=payload.getProperty("value",{}); + if(!raw.isInt()&&!raw.isDouble()) + error="INVALID_AUX_FADER"; + else { + const double gain=static_cast(raw); + if(!std::isfinite(gain)||gain<0.||gain>4.) + error="INVALID_AUX_FADER"; + else { + accepted=engine.setDryRoutingLabAuxBusGain( + static_cast(channelId-11),ep, + m4Revision,static_cast(gain)); + if(!accepted)error="AUX_RETURN_NOT_ADMITTED"; + } + } + } + } else if(operation=="SET_MONITOR_LEVEL") { + const auto raw=payload.getProperty("value",{}); + if(!raw.isInt()&&!raw.isDouble()) + error="INVALID_MONITOR_LEVEL"; + else { + const double gain=static_cast(raw); + if(!std::isfinite(gain)||gain<0.||gain>1.) + error="INVALID_MONITOR_LEVEL"; + else { + accepted=engine.setDryRoutingLabMonitorSendGain( + lane,ep,m4Revision,static_cast(gain)); + if(!accepted)error="MONITOR_BUS_NOT_ADMITTED"; + } + } + } else if(operation=="SET_SEND_LEVEL") { + // A SEND level is native realtime PCM, NOT a new graph + // edge. Existing AUX1..4 are independent FX return buses. + const auto aux=payload.getProperty("auxIndex",{}); + const auto tapName=payload.getProperty("tap","POST").toString(); + const auto raw=payload.getProperty("value",{}); + if(!aux.isInt()||static_cast(aux)<0|| + static_cast(aux)>=armix::mixer::auxBusCount) + error="INVALID_AUX_RETURN"; + else if(tapName!="PRE"&&tapName!="POST") + error="INVALID_SEND_TAP"; + else if(!raw.isInt()&&!raw.isDouble()) + error="INVALID_SEND_LEVEL"; + else { + const double value=static_cast(raw); + if(!std::isfinite(value)||value<0.||value>1.) + error="INVALID_SEND_LEVEL"; + else { + const auto tap=tapName=="PRE"? + armix::mixer::SendTap::preFader: + armix::mixer::SendTap::postFader; + accepted=engine.setDryRoutingLabAuxSendGain( + lane,static_cast(aux),ep,m4Revision, + static_cast(value),tap); + if(!accepted)error="NATIVE_SEND_NOT_ADMITTED"; + } + } + } else if(operation=="SET_PROCESSING_FORMAT"|| + operation=="SET_PRIMARY_OUT") { + const auto nativeValue=payload.getProperty( + operation=="SET_PRIMARY_OUT"?"destinationId":"format",{}) + .toString(); + error=engine.repatchDryRoutingLabChannel( + lane,ep,m4Revision,operation,nativeValue); + accepted=error.isEmpty(); + } else if(operation=="SET_INSERT_BYPASS"|| + operation=="OPEN_INSERT_EDITOR") { + // The token must match an actually prepared vendor + // AudioPluginInstance in the current accepted M4 graph. + // Never invent a GUI insert, instantiate, clone or scan + // VST3 while changing BYPASS / opening an editor. + const auto token=payload.getProperty("insertId","").toString(); + const auto statuses=engine.status().getProperty("dryRoutingLab",{}); + const auto fx=statuses.getProperty("fxInstances",{}); + const auto* lanes=fx.getArray(); + int foundSlot=-1; + if(token.isNotEmpty() && lanes && lanesize()) { + const auto bank=lanes->getReference(lane); + if(const auto* slots=bank.getArray()) + for(int k=0;ksize();++k) + if(slots->getReference(k).getProperty("instanceId","") + .toString()==token) { + if(foundSlot>=0){foundSlot=-1;break;} + foundSlot=k; + } + } + if(foundSlot<0)error="UNKNOWN_NATIVE_INSERT_INSTANCE"; + else if(operation=="SET_INSERT_BYPASS") { + const auto value=payload.getProperty("bypassed",{}); + if(!value.isBool())error="INVALID_BYPASS_VALUE"; + else { + accepted=engine.setDryRoutingLabFxBypass( + lane,foundSlot,ep,m4Revision,token,static_cast(value)); + if(!accepted)error="NATIVE_INSERT_BYPASS_REJECTED"; + } + } else { + error=openEditor(lane,foundSlot,ep,m4Revision,token); + accepted=error.isEmpty(); + } + } else error="UNSUPPORTED_UNIVERSAL_OPERATION"; + } + } + const auto after=armix::console::LiveConsoleBridgeV6::snapshot(engine.status()); + const auto afterGraph=after.getProperty("graph",{}); + PuzzleV8Ack ack; + ack.requestId=bytes; + ack.status=accepted?"ACCEPTED":"REJECTED"; + ack.deviceEpoch=after.getProperty("device",{}).getProperty("epoch",epoch).toString().toStdString(); + ack.graphRevision=afterGraph.getProperty("revision",oldRev).toString().toStdString(); + ack.rosterRevision=afterGraph.getProperty("rosterRevision",oldRoster).toString().toStdString(); + ack.errorCode=error.toStdString(); + const auto json=PuzzleV8Wire::ack(ack); + return juce::JSON::parse(juce::String::fromUTF8(json.c_str())); + } + + static bool parsePortId(const juce::String& wire,const char* prefix,int& physical) { + if(!wire.startsWith(prefix))return false; + const auto text=wire.substring(static_cast(std::char_traits::length(prefix))); + std::uint64_t value=0; + if(!decodeDecimal(juce::var(text),value)||value>255)return false; + physical=static_cast(value); + return true; + } + + static bool decodeDecimal(const juce::var& raw,std::uint64_t& result) noexcept { + if(!raw.isString())return false; + const auto str=raw.toString(); + if(str.isEmpty()||str.length()>20 || + (str.length()>1 && str[0]=='0'))return false; + std::uint64_t n=0; + for(int i=0;i'9')return false; + const auto digit=static_cast(c-'0'); + if(n>(std::numeric_limits::max()-digit)/10)return false; + n=n*10+digit; + } + result=n;return true; + } + +private: + static juce::String decimalFromNative(const juce::var& value) { + if(!(value.isInt()||value.isInt64()))return "0"; + const auto n=static_cast(value); + return n>=0?juce::String(n):juce::String("0"); + } + static constexpr std::size_t maxRecentIds=256; + // Bounded completed IDs on the serialized message thread, never the + // native RT callback. Replayed old requests remain nonmutating in G0. + std::unordered_set completed_; + std::deque recentIds_; +}; +} // namespace armix::console diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index a80004bf0..07f8d1928 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -12,6 +12,7 @@ #include "../engine/device/JuceIndependentClockDevice.h" #include "../engine/device/LiveSecondaryOutputDevice.h" #include "../engine/core/LiveOutputRouteGate.h" +#include "../engine/core/NativeRenderAuthority.h" #include "../engine/device/AsioPriorityDeviceManager.h" #include "../engine/device/AsioRegistryIdentityProbe.h" #include "../engine/device/DirectRouteFence.h" @@ -69,6 +70,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback struct Graph { + // This same Graph owns the original CH1 vendor rack, its bypass + // envelopes and transition scratch, for BOTH M4 and the admitted + // ChannelId external lease. All memory is allocated on CONTROL; + // the audio callback only dereferences the leased Graph*. + Graph() { dryScratch.setSize(2,maxFrames,false,true,false); } + juce::AudioBuffer dryScratch; // Eight 4-bit physical slot indices in one x64 lock-free word. // Moving an insert publishes one complete order for the NEXT audio // block; the processor objects and their binary states never move. @@ -99,8 +106,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { formats_.addFormat (std::make_unique()); scratch_.setSize (2, maxFrames, false, true, false); - // One reusable preallocated stereo dry snapshot for transient FX bypass. - dryScratch_.setSize (2, maxFrames, false, true, false); + // CH1 bypass scratch now belongs to its shared Graph lifetime so + // a ChannelId PCM snapshot can retain the SAME original FX state. handoff_.initialize (graphOwned_.get()); } @@ -633,6 +640,18 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback totalLatency_.store(graphOwned_->latency,std::memory_order_release); handoff_.completeRetirement(); completedSwaps_.fetch_add (1, std::memory_order_relaxed); + // Only after the original host graph is the new accepted owner, + // safely migrate its exact original CH1 VSTs/Orbit and all M4 lanes. + // No plugin is recreated; retain M4 if the hardware is armed, + // stale or PDC disallows this graph. CONTROL/timer thread only. + if(allOutputsDisarmed() && dryRoutingLab_.hasExplicitRoute() && + directFence_.permitted() && !independent_.active()) { + if(auto* device=deviceManager_.getCurrentAudioDevice()) + (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count, + juce::jmax(32,device->getCurrentBufferSizeSamples()), + true,currentOriginalCh1Lease()); + } return true; } @@ -715,6 +734,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return false; prepareFxEditEnvelope(*next,device->getCurrentSampleRate()); stagedOwner_=std::move(next); + // CHANGE of original CH1 ownership must finish on the existing + // M4 buffer-boundary handoff first. Revoke the old native lease; + // once the staged Graph is accepted, re-admit its identical plugin + // state/editor/order into ChannelId without double processing. + dryRoutingLab_.revokeChannelIdPcm(); if(!handoff_.stage(stagedOwner_.get())) { stagedOwner_.reset(); @@ -920,6 +944,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback staged->slots[i].latency); if (!staged->slots[i].bypass) staged->latency += staged->slots[i].latency; } + // Show recall can replace original CH1 owner and all its binary + // plugin state. Revoke ChannelId PCM BEFORE staging the pointer: + // the original handoff then owns the next audible vendor graph. + dryRoutingLab_.revokeChannelIdPcm(); stagedOwner_ = std::move (staged); if (!handoff_.stage (stagedOwner_.get())) { @@ -1046,11 +1074,18 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback for(int i=0;icount;++i) if(graphOwned_->slots[i].latency!=0) return "CH1 rack contains a latent VST3: zero-latency settings are required for native multi-channel sends"; - return dryRoutingLab_.apply(command,directFence_.permitted(), - independent_.active(),graphOwned_->count,fx,formats_, - device->getCurrentSampleRate(), - juce::jmax(32,device->getCurrentBufferSizeSamples()), - true,restored); + const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + const auto result=dryRoutingLab_.apply( + command,directFence_.permitted(),independent_.active(), + graphOwned_->count,fx,formats_,device->getCurrentSampleRate(), + frames,true,restored); + // Same original PCM callback/hardware gate; a failed ChannelId + // admission retains the last accepted M4 with original Orbit/Show. + if(result.isEmpty()) + (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count,frames,allOutputsDisarmed(), + currentOriginalCh1Lease()); + return result; } void disableDryRoutingLab() noexcept { setOutputMuted(true); // never expose CH1 unexpectedly on STOP @@ -1058,14 +1093,68 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } juce::String switchDryRoutingLabSource(int strip,std::uint64_t epoch, std::uint64_t revision,const juce::String& mode, - int left,int right) noexcept { + int left,int right) { 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); + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device)return "SOURCE: active DIRECT audio device unavailable"; + // True first-input SOURCE selection is a control-prepared native graph + // transaction, not a browser-side APPLY or alternate callback. A + // single verified mono capture pin is a supported source. + try { + const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + const auto oldRevision=dryRoutingLab_.revision(); + const auto changed=dryRoutingLab_.repatchPhysicalSource( + strip,epoch,revision,mode,left,right, + directFence_.permitted(),independent_.active(), + graphOwned_->count,formats_,device->getCurrentSampleRate(),frames); + // Same-format SOURCE is an atomic live parameter on BOTH kernels: + // do not rebuild VST3/PCM or interrupt the 64-sample crossfade. + if(changed.isEmpty() && allOutputsDisarmed() && + oldRevision!=dryRoutingLab_.revision()) + (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count,frames,true, + currentOriginalCh1Lease()); + return changed; + } catch(const std::exception& ex) { + return "SOURCE: native prepare failed; prior audio kept: " + juce::String(ex.what()); + } catch(...) { + return "SOURCE: native prepare failed; prior audio kept"; + } + } + // Direct compact OUT / MONO-STEREO operator edits. One existing M4 + // prepared graph is republished; original VST3 instances/Orbit remain + // owned by the same native callback. Never touched on RT. + juce::String repatchDryRoutingLabChannel(int strip,std::uint64_t epoch, + std::uint64_t revision,const juce::String& operation, + const juce::String& value) { + 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 "CHANNEL PATCH: DIRECT device or VST3 handoff unavailable"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device)return "CHANNEL PATCH: no active native audio interface"; + try { + const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + const auto changed=dryRoutingLab_.repatchChannelStructure( + strip,epoch,revision,operation,value, + directFence_.permitted(),independent_.active(), + graphOwned_->count,formats_,device->getCurrentSampleRate(),frames); + if(changed.isEmpty() && allOutputsDisarmed()) + (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count,frames,true, + currentOriginalCh1Lease()); + return changed; + } catch(...) { + return "CHANNEL PATCH: native preparation failed; previous mix preserved"; + } } bool setDryRoutingLabParameter(int strip,std::uint64_t epoch, std::uint64_t revision,const juce::String& parameter, @@ -1082,13 +1171,49 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return dryRoutingLab_.setAuxBusGain(bus,epoch,revision,gain); } bool setDryRoutingLabAuxSendGain(int source,int bus,std::uint64_t epoch, + std::uint64_t revision,float gain, + armix::mixer::SendTap tap=armix::mixer::SendTap::postFader) noexcept { + if(independent_.active()||routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire) + !=armix::diagnostics::Route::normal|| + !directFence_.permitted()||savedDirectSetup_||savedLiveSetup_) + return false; + return dryRoutingLab_.setAuxSendGain(source,bus,epoch,revision,gain,tap); + } + juce::String connectDryRoutingLabAuxSend(int source,int bus, + std::uint64_t epoch,std::uint64_t revision, + armix::mixer::SendTap tap,float gain,float pan) { + 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 "AUX CONNECT: DIRECT device or VST graph handoff unavailable"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device)return "AUX CONNECT: no verified audio interface"; + try { + const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + const auto changed=dryRoutingLab_.connectPreparedAuxSend( + source,bus,epoch,revision,tap,gain,pan, + directFence_.permitted(),independent_.active(),graphOwned_->count, + formats_,device->getCurrentSampleRate(),frames); + if(changed.isEmpty() && allOutputsDisarmed()) + (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count,frames,true, + currentOriginalCh1Lease()); + return changed; + } catch(...) { + return "AUX CONNECT: failed native preparation; previous route retained"; + } + } + bool setDryRoutingLabMonitorSendGain(int source,std::uint64_t epoch, std::uint64_t revision,float gain) noexcept { if(independent_.active()||routeReconfiguring_.load(std::memory_order_acquire)|| diagnosticRoute_.load(std::memory_order_acquire) !=armix::diagnostics::Route::normal|| !directFence_.permitted()||savedDirectSetup_||savedLiveSetup_) return false; - return dryRoutingLab_.setAuxSendGain(source,bus,epoch,revision,gain); + return dryRoutingLab_.setMonitorSendGain(source,epoch,revision,gain); } bool setDryRoutingLabFxBypass(int lane,int slot,std::uint64_t epoch, std::uint64_t revision,const juce::String& instanceId, @@ -1436,8 +1561,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback armix::device::LiveSecondaryOutputDevice secondaryOutput_; std::optional savedDirectSetup_; juce::AudioPluginFormatManager formats_; - std::unique_ptr graphOwned_ {std::make_unique()}; - std::unique_ptr stagedOwner_; + // Strong ownership stays on CONTROL. The admitted native ChannelId + // snapshot may retain exactly this Graph while the vendor plugin, Show + // state and editor remain alive through an in-flight callback. + // Handoff still publishes Graph* atomically; no shared_ptr on AUDIO. + std::shared_ptr graphOwned_ {std::make_shared()}; + std::shared_ptr stagedOwner_; armix::rt::LiveGraphHandoff handoff_; // 0 idle, 1 fade-out, 2 fade-in. One controller producer, one RT reader. // No allocation, plugin re-instantiation or extra processing pass. @@ -1445,7 +1574,6 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback std::atomic fxMovePendingOrder_ {Graph::canonicalOrder}; bool attached_ = false; juce::AudioBuffer scratch_; - juce::AudioBuffer dryScratch_; armix::dsp::NativeMasterLoudness masterLoudness_; armix::diagnostics::DiagnosticTone diagnosticTone_; LiveDryRoutingLab dryRoutingLab_; @@ -1599,36 +1727,30 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback outputPeak_.store (0.f); } - // R0 bridge: existing CH1 multi-insert vendor state/Orbit stays owned by - // the live FX handoff. The audio callback holds its Cycle lease throughout - // this render pass, so an old plugin graph cannot retire in mid-block. - // This is a temporary ownership adapter until all inserts are represented - // by the same native multi-lane graph; not a second rendering engine. - struct LegacyChannelOneLease final { LiveAudioEngine* host; Graph* graph; }; - static void processLegacyChannelOne(void* token,int lane,float* left, - float* right,int frames) noexcept + // ONE original CH1 rack processor for M4 compatibility and the native + // ChannelId external lease. Graph lifetime is owned by CONTROL and the + // accepted publisher, never acquired or released inside audio callback. + static void renderOriginalChannelOneGraph(Graph& graph,float* left, + float* right,int frames) noexcept { - if(lane!=0 || !token || !left || !right || frames<=0 || frames>maxFrames)return; - const auto& lease=*static_cast(token); - auto* const host=lease.host; - auto* const graph=lease.graph; - if(!host || !graph || graph->count<=0)return; + if(!left||!right||left==right||frames<=0||frames>maxFrames|| + graph.count<=0)return; float* channels[]{left,right}; juce::AudioBuffer buffer(channels,2,frames); juce::MidiBuffer midi; - const auto order=graph->orderPacked.load(std::memory_order_acquire); - for(int logical=0;logicalcount;++logical) + const auto order=graph.orderPacked.load(std::memory_order_acquire); + for(int logical=0;logicalslots[physical]; + auto& slot=graph.slots[physical]; if(!slot.processor)continue; - auto& bypass=graph->bypassEnvelope[physical]; - bypass.request(graph->bypassFlags[physical].load(std::memory_order_acquire)); + auto& bypass=graph.bypassEnvelope[physical]; + bypass.request(graph.bypassFlags[physical].load(std::memory_order_acquire)); const bool blend=bypass.transitioning(); if(blend) { - juce::FloatVectorOperations::copy(host->dryScratch_.getWritePointer(0),left,frames); - juce::FloatVectorOperations::copy(host->dryScratch_.getWritePointer(1),right,frames); + juce::FloatVectorOperations::copy(graph.dryScratch.getWritePointer(0),left,frames); + juce::FloatVectorOperations::copy(graph.dryScratch.getWritePointer(1),right,frames); } if(bypass.shouldProcessWet()) { @@ -1642,8 +1764,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } if(blend) { - const float* dryL=host->dryScratch_.getReadPointer(0); - const float* dryR=host->dryScratch_.getReadPointer(1); + const float* dryL=graph.dryScratch.getReadPointer(0); + const float* dryR=graph.dryScratch.getReadPointer(1); for(int i=0;i(token)->graph; + if(graph)renderOriginalChannelOneGraph(*graph,left,right,frames); + } + + // Native external FX is a raw callback on the EXACT shared Graph owner + // bound by UnifiedLegacyProductionAdmission. The snapshot owns the + // strong reference and validates context==owner.get() off realtime. + static void processOwnedChannelOne(void* token,float* left, + float* right,int frames) noexcept + { + if(token)renderOriginalChannelOneGraph( + *static_cast(token),left,right,frames); + } + armix::mixer::DynamicChannelFxLeaseBank::ExternalLease + currentOriginalCh1Lease() const noexcept { + armix::mixer::DynamicChannelFxLeaseBank::ExternalLease fx; + if(!graphOwned_||graphOwned_->count<=0)return fx; + // Native PRE/POST/AUX cannot accept the original external rack + // with latent inserts until graph-wide PDC exists. A missing lease + // keeps the original M4 callback audible without false admission. + for(int i=0;icount;++i) + if(graphOwned_->slots[i].latency!=0)return fx; + fx.owner=std::static_pointer_cast(graphOwned_); // CONTROL + fx.context=graphOwned_.get(); + fx.render=&processOwnedChannelOne; + // id is bound from the compiled native ChannelId roster, NEVER a + // guessed display index/port; no native owner can be misdirected. + return fx; + } + void audioDeviceIOCallbackWithContext ( const float* const* inputs, int inputChannels, float* const* outputs, int outputChannels, int samples, const juce::AudioIODeviceCallbackContext&) override @@ -1680,6 +1839,13 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback std::memory_order_relaxed); return; } + // ONE explicit owner for the whole device callback. The GUI cannot + // select an experimental ChannelId renderer or revive stereo CH1. + // Cutover to universal will replace this authority transaction only + // after the full VST3/Show/epoch proof, never add a parallel callback. + const auto renderOwner=armix::mixer::NativeRenderAuthority::select( + activeDiagnosticRoute==armix::diagnostics::Route::normal, + dryRoutingLab_.active()); const auto cycle = handoff_.beginCycle(); // R0B B3: production NORMAL audio has a single native routing owner. // Until a device-epoch-validated 10CH/4AUX route is published, output @@ -1690,8 +1856,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Keep the existing FX graph handoff progressing even when unpatched: // a staged ADD/REMOVE must ACK and retire on the callback thread. // Only atomic reads and deterministic output writes; no RT heap or I/O. - if (activeDiagnosticRoute == armix::diagnostics::Route::normal - && !dryRoutingLab_.active()) + if (renderOwner == + armix::mixer::NativeRenderOwner::failSilentUnpatched) { // P0: SILENT output must not mean blind capture diagnostics. // A verified ASIO/WASAPI callback can carry PCM before any @@ -1746,7 +1912,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // action, with an immutable preallocated P1D graph. Its own zero-VST // callback path NEVER falls through to CH1 on stale/hotplug routes. // DirectFence was already checked above; no output to unknown device. - if (dryRoutingLab_.active()) + if (renderOwner == + armix::mixer::NativeRenderOwner::acceptedM4Session) { const auto outputGate=armix::mixer::LiveOutputRouteGate::evaluate( dryRoutingLab_.active(), @@ -1767,7 +1934,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Both native 10CH routing and the existing CH1 vendor FX chain // execute in ONE stereo output render pass. Never mix a parallel // CH1 output on top or copy vendor processors into another graph. - LegacyChannelOneLease ch1Lease{this,cycle.graph}; + LegacyChannelOneLease ch1Lease{cycle.graph}; std::array nativeMainPair{{-1,-1}}; std::array nativeMonitorPair{{-1,-1}}; const bool routed=dryRoutingLab_.process(inputs,inputChannels,outputs, @@ -1867,13 +2034,16 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::FloatVectorOperations::clear(outputs[channel],samples); return; } + // The only remaining stereo renderer is DIAGNOSTIC. It may emit + // a bounded test tone or test capture but never host channel VST3 + // or become a fallback production mixer. + jassert(armix::mixer::NativeRenderAuthority::mayRunDiagnostic( + renderOwner)); const bool enabled = monitor_.load (std::memory_order_relaxed) && !routeReconfiguring_.load (std::memory_order_acquire); const auto route = diagnosticRoute_.load (std::memory_order_relaxed); const bool toneTest = route == armix::diagnostics::Route::outputOnlyTone; const bool captureTest = route == armix::diagnostics::Route::captureOnly; - const bool dry = dryTest_.load (std::memory_order_relaxed) - || route != armix::diagnostics::Route::normal; if (toneTest && outputChannels > 0) testOutputFrames_.fetch_add (static_cast (samples), std::memory_order_relaxed); if (captureTest && inputChannels > 0) @@ -1903,10 +2073,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback { const int frames = juce::jmin (maxFrames, samples - offset); // Preallocated backing store: no resizing/capacity bookkeeping in RT. - // Two-channel AudioBuffer view refers to scratch_ without ownership. - // JUCE uses its inline channel pointer storage for two channels. - juce::AudioBuffer scratchView ( - scratch_.getArrayOfWritePointers(), 2, frames); + // Test-only stereo buffers are preallocated. There is no VST + // buffer view or plugin dispatch in the diagnostic-only path. if (toneTest) { auto* left = scratch_.getWritePointer (0); @@ -1930,55 +2098,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback for (int i = 0; i < frames; ++i) if (!toneTest) inPeak = juce::jmax (inPeak, std::abs (dst[i])); } - // MIDI capacity is empty unless the plugin itself changes it. - juce::MidiBuffer midi; - if (!dry) - { - // One atomic order snapshot per block: stable physical FX and bypass identity. - const auto order = cycle.graph->orderPacked.load (std::memory_order_acquire); - for (int fx = 0; fx < cycle.graph->count; ++fx) - { - const int physical = Graph::physicalAt (order, fx); - auto& slot = cycle.graph->slots[physical]; - if (!slot.processor) {midi.clear();continue;} - auto& bypass=cycle.graph->bypassEnvelope[physical]; - bypass.request(cycle.graph->bypassFlags[physical].load(std::memory_order_acquire)); - // Steady wet/dry requires no copy or extra arithmetic. - // A transition temporarily snapshots the exact input to - // this insert; a second full FX graph is never created. - const bool blend=bypass.transitioning(); - if (blend) - for(int ch=0;ch<2;++ch) - juce::FloatVectorOperations::copy( - dryScratch_.getWritePointer(ch), - scratch_.getReadPointer(ch),frames); - if (bypass.shouldProcessWet()) - { - const auto pluginBeginUs = clockMicros(); - slot.processor->processBlock (scratchView, midi); - const auto pluginUs = clockMicros() - pluginBeginUs; - lastPluginUsBySlot_[physical].store (pluginUs, std::memory_order_relaxed); - publishMax (worstPluginUsBySlot_[physical], pluginUs); - publishMax (worstPluginUs_, pluginUs); - if (static_cast (pluginUs) > periodUs * 0.75) - slowPlugins_.fetch_add (1, std::memory_order_relaxed); - } - if (blend) - { - float* wetL=scratch_.getWritePointer(0); - float* wetR=scratch_.getWritePointer(1); - const float* dryL=dryScratch_.getReadPointer(0); - const float* dryR=dryScratch_.getReadPointer(1); - for(int i=0;i #include @@ -61,6 +65,7 @@ class LiveDryRoutingLab final { // JUCE calls aboutToStart after configuring the input/output device. // One device session gets a new epoch; stored route cannot survive it. void prepareDevice (juce::AudioIODevice* device) noexcept { + channelIdPcmEpoch_.store(0,std::memory_order_release); const auto generation=deviceEpoch_.fetch_add(1,std::memory_order_acq_rel)+1; userPatched_.store(false,std::memory_order_release); registryValid_.store(false,std::memory_order_release); @@ -90,6 +95,7 @@ class LiveDryRoutingLab final { registryValid_.store(true,std::memory_order_release); } void deviceStopped() noexcept { + channelIdPcmEpoch_.store(0,std::memory_order_release); // A stale lab cannot silently resume legacy CH1 on device hotplug. userPatched_.store(false,std::memory_order_release); deviceEpoch_.fetch_add(1,std::memory_order_acq_rel); @@ -132,12 +138,19 @@ class LiveDryRoutingLab final { return "Clear the active input patch before creating an unpatched session"; if(active() && ready() && !hasExplicitRoute())return {}; auto request=std::make_unique(); + // New silent sessions use typed v2 from the first callback so the + // operator can choose MONO/STEREO processing BEFORE a physical IN. + // Old saved v1 Shows remain readable by NativeDryRouteCommand. + request->setProperty("schemaVersion",2); request->setProperty("deviceEpoch",static_cast(epoch())); request->setProperty("revision",static_cast(revision())); juce::Array channels; for(int i=0;i(); row->setProperty("mode","NONE"); + row->setProperty("sourceKind","NONE"); + row->setProperty("sourceFormat","NONE"); + row->setProperty("channelFormat","STEREO"); row->setProperty("left",-1); row->setProperty("right",-1); row->setProperty("gain",0.25); @@ -399,6 +412,9 @@ class LiveDryRoutingLab final { if(!registryValid_.load(std::memory_order_acquire) || epochAtPublish!=currentEpoch) return "Audio device changed before routing publication"; + // New M4 routing must not render against an older ChannelId graph. + // Output must remain disarmed throughout structural native APPLY. + channelIdPcmEpoch_.store(0,std::memory_order_release); const auto result=publisher_.publish(std::move(next),expectedRevision,epochAtPublish); switch(result) { case Publisher::Result::applied: @@ -411,6 +427,11 @@ class LiveDryRoutingLab final { // displays an acknowledged immutable copy; draft changes // never update this until graph publication succeeds. acceptedRoute_=explicitSelection?command:juce::var(); + // Retain the REAL prepared (possibly UNPATCHED/SILENT) M4 + // input topology so a single native SOURCE selection can + // compile the first mono route. No UI draft is authoritative. + sourceTemplate_=command; + acceptedFxSelections_=selections; // Release-store only AFTER a valid immutable graph publishes. // Even if OUTPUT is mistakenly armed, unpatched renders never // enter ANY channel/master vendor DSP or produce sound. @@ -479,6 +500,14 @@ class LiveDryRoutingLab final { return "SOURCE SWITCH: native graph rejected same-format input"; // This is the authoritative native parameter target, not an // unacknowledged browser draft. The callback fades PCM over 64 samples. + if(channelIdPhysicalPcmActive()) { + const auto id=nativeAccepted_.graph.ids.inputs[strip]; + if(!nativePublisher_.setPhysicalSource( + expectedEpoch,nativeAccepted_.pcmRevision,id, + callbackLeft,mode=="STEREO"?callbackRight:-1, + mode=="STEREO")) + channelIdPcmEpoch_.store(0,std::memory_order_release); + } if(auto* object=row.getDynamicObject()){ object->setProperty("left",physicalLeft); object->setProperty("right",mode=="STEREO"?physicalRight:-1); @@ -486,6 +515,207 @@ class LiveDryRoutingLab final { return {}; } + // A source changing from NONE to MONO/STEREO needs a new prepared + // topology. A source changing physical pin within the same format uses + // the existing zero-heap atomic source switch above. Both cases are + // handled through ONE native command and ONE ACK, not GUI APPLY wizard. + // All heavy preparation/reuse and deep cloning happen on message thread. + juce::String repatchPhysicalSource(int strip,std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,const juce::String& mode, + int physicalLeft,int physicalRight,bool directPermitted, + bool independentClock,int occupiedCh1Fx, + juce::AudioPluginFormatManager& formats,double sampleRate, + int deviceFrames) + { + if(!ready() || !registryValid_.load(std::memory_order_acquire) || + topologyFault_.load(std::memory_order_acquire) || + expectedEpoch!=epoch() || expectedRevision!=revision() || + !sourceTemplate_.isObject()) + return "SOURCE: native device, graph or accepted template stale"; + const auto sourceRows=sourceTemplate_.getProperty("channels",juce::var()); + const auto* rows=sourceRows.getArray(); + if(!rows || strip<0 || strip>=count || rows->size()!=count) + return "SOURCE: target channel unavailable"; + // Preserve the proven live-safe atomic path for an already scheduled + // channel. Never force a vendor graph rebuild for ordinary pin moves. + if(hasExplicitRoute() && + rows->getReference(strip).getProperty("mode",{}).toString()==mode) + return switchPhysicalSource(strip,expectedEpoch,expectedRevision, + mode,physicalLeft,physicalRight); + const int available=portCount_.load(std::memory_order_acquire); + if(available<=0||available>armix::device::LiveInputPortRegistry::limit) + return "SOURCE: driver did not verify active capture pins"; + std::array pins{}; + for(int i=0;i(available)}, + expectedEpoch,expectedRevision,staged); + if(error.isNotEmpty())return error; + return publishRevisedTopology(staged,expectedEpoch,expectedRevision, + directPermitted,independentClock,occupiedCh1Fx,formats, + sampleRate,deviceFrames); + } + + // One-click channel OUT and format: the existing native M4 routing/FX + // graph is the sole PCM owner. Prepare OUT/format on the JUCE control + // thread, then publish with exactly the same epoch/VST3 lease/Show + // rollback transaction as SOURCE. No device restart or UI-side routing. + juce::String repatchChannelStructure(int strip, + std::uint64_t expectedEpoch,std::uint64_t expectedRevision, + const juce::String& operation,const juce::String& requested, + bool directPermitted,bool independentClock,int occupiedCh1Fx, + juce::AudioPluginFormatManager& formats,double sampleRate, + int deviceFrames) { + if(!ready()||!registryValid_.load(std::memory_order_acquire)|| + topologyFault_.load(std::memory_order_acquire)|| + epoch()!=expectedEpoch||revision()!=expectedRevision|| + !sourceTemplate_.isObject()) + return "CHANNEL PATCH: native device or graph is stale"; + if(strip<0||strip>=count) + return "CHANNEL PATCH: invalid native channel"; + // This preserves all source pins, AUX taps, master and monitor + // destinations, original VST3 vendor state and all other channels. + auto staged=juce::JSON::parse(juce::JSON::toString(sourceTemplate_,false)); + if(!staged.isObject())return "CHANNEL PATCH: cannot clone accepted graph"; + auto rows=staged.getProperty("channels",juce::var()); + auto* list=rows.getArray(); + if(!list||list->size()!=count|| + !list->getReference(strip).isObject()) + return "CHANNEL PATCH: no accepted channel row"; + auto* row=list->getReference(strip).getDynamicObject(); + if(operation=="SET_PRIMARY_OUT") { + if(requested!="MAIN"&&requested!="NONE") + return "CHANNEL PATCH: only MAIN and NONE are installed M4 outputs"; + row->setProperty("main",requested=="MAIN"); + } else if(operation=="SET_PROCESSING_FORMAT") { + if(requested!="MONO"&&requested!="STEREO") + return "CHANNEL PATCH: processing format must be MONO or STEREO"; + const auto schema=staged.getProperty("schemaVersion",juce::var()); + if(!schema.isInt() || static_cast(schema)!=2) + return "CHANNEL PATCH: typed processing format requires native schema v2"; + row->setProperty("channelFormat",requested); + } else return "CHANNEL PATCH: unsupported graph operation"; + return publishRevisedTopology(staged,expectedEpoch,expectedRevision, + directPermitted,independentClock,occupiedCh1Fx,formats, + sampleRate,deviceFrames); + } + + // Operator one-action AUX send connection: prepare a real parallel + // edge in the SAME M4 graph that owns the channel VST3/AUX rack. + // The recipient must already own a genuine prepared effect. An empty + // AUX summed into MAIN doubles the dry path and is rejected. + juce::String connectPreparedAuxSend(int source,int bus, + std::uint64_t expectedEpoch,std::uint64_t expectedRevision, + armix::mixer::SendTap tap,float gain,float pan, + bool directPermitted,bool independentClock,int occupiedCh1Fx, + juce::AudioPluginFormatManager& formats,double sampleRate, + int deviceFrames) { + if(!hasExplicitRoute()||!ready()||!registryValid_.load(std::memory_order_acquire)|| + epoch()!=expectedEpoch||revision()!=expectedRevision|| + topologyFault_.load(std::memory_order_acquire)|| + source<0||source>=count||bus<0||bus>=auxCount|| + (tap!=armix::mixer::SendTap::preFader&& + tap!=armix::mixer::SendTap::postFader)|| + !std::isfinite(gain)||gain<0.f||gain>1.f|| + !std::isfinite(pan)||pan< -1.f||pan>1.f) + return "AUX CONNECT: invalid source, send or stale native graph"; + const auto* old=publisher_.controlPrepared(expectedEpoch,expectedRevision); + if(!old||old->insertsOn(count+bus)<=0) + return "AUX CONNECT: insert a real effect on AUX first; an empty return doubles dry MAIN"; + auto staged=juce::JSON::parse(juce::JSON::toString(sourceTemplate_,false)); + if(!staged.isObject())return "AUX CONNECT: accepted topology unavailable"; + const auto lanes=staged.getProperty("channels",juce::var()); + const auto* sources=lanes.getArray(); + if(!sources||sources->size()!=count|| + sources->getReference(source).getProperty("mode","NONE").toString()=="NONE") + return "AUX CONNECT: select a verified physical source first"; + auto aux=staged.getProperty("auxes",juce::var()); + if(aux.isVoid()) { + juce::Array defaults; + for(int b=0;b(); + row->setProperty("enabled",false); + row->setProperty("main",true); + row->setProperty("mute",false); + row->setProperty("gain",1.0); + defaults.add(juce::var(row.release())); + } + staged.getDynamicObject()->setProperty("auxes",juce::var(defaults)); + aux=staged.getProperty("auxes",juce::var()); + } + auto* auxes=aux.getArray(); + if(!auxes||auxes->size()!=auxCount)return "AUX CONNECT: corrupt return roster"; + auto* returnRow=auxes->getReference(bus).getDynamicObject(); + if(!returnRow)return "AUX CONNECT: invalid return"; + if(!static_cast(returnRow->getProperty("enabled"))) { + returnRow->setProperty("enabled",true); + returnRow->setProperty("main",true); // one-click parallel effect to MAIN + } + auto rawSends=staged.getProperty("sends",juce::var()); + if(rawSends.isVoid()) { + staged.getDynamicObject()->setProperty("sends", + juce::var(juce::Array{})); + rawSends=staged.getProperty("sends",juce::var()); + } + auto* sendRows=rawSends.getArray(); + if(!sendRows)return "AUX CONNECT: invalid accepted sends"; + juce::DynamicObject* existing=nullptr; + for(auto& item:*sendRows) { + if(static_cast(item.getProperty("from",-1))==source && + static_cast(item.getProperty("to",-1))==count+bus) { + existing=item.getDynamicObject(); + if(!existing)return "AUX CONNECT: invalid existing edge"; + break; + } + } + if(!existing) { + if(sendRows->size()>=armix::mixer::maxChannelSends) + return "AUX CONNECT: send capacity exhausted"; + auto row=std::make_unique(); + existing=row.get(); + sendRows->add(juce::var(row.release())); + } + existing->setProperty("from",source); + existing->setProperty("to",count+bus); + existing->setProperty("tap",tap==armix::mixer::SendTap::preFader?"PRE":"POST"); + existing->setProperty("gain",static_cast(gain)); + existing->setProperty("pan",static_cast(pan)); + return publishRevisedTopology(staged,expectedEpoch,expectedRevision, + directPermitted,independentClock,occupiedCh1Fx,formats, + sampleRate,deviceFrames); + } + + // Both SOURCE and channel structure edits share one graph compiler, + // VST3 lease policy and rollback path. Keep fast faders/pan/mute/solo + // on their separate atomic parameter path without any compilation. + juce::String publishRevisedTopology(juce::var& staged, + std::uint64_t expectedEpoch,std::uint64_t expectedRevision, + bool directPermitted,bool independentClock,int occupiedCh1Fx, + juce::AudioPluginFormatManager& formats,double sampleRate, + int deviceFrames) { + auto stagedRows=staged.getProperty("channels",juce::var()); + auto* editable=stagedRows.getArray(); + if(!editable||editable->size()!=count) + return "CHANNEL PATCH: malformed native topology"; + for(int i=0;igetReference(i).getDynamicObject(); + if(!row)return "CHANNEL PATCH: missing native channel"; + const auto& c=channelEdits_[i]; + row->setProperty("gain",static_cast(c.linear)); + row->setProperty("pan",static_cast(c.pan)); + row->setProperty("mute",c.mute); + row->setProperty("solo",c.solo); + } + if(expectedEpoch!=epoch()||expectedRevision!=revision()|| + !registryValid_.load(std::memory_order_acquire)) + return "CHANNEL PATCH: device changed; previous mix preserved"; + return apply(staged,directPermitted,independentClock,occupiedCh1Fx, + acceptedFxSelections_,formats,sampleRate,deviceFrames,true); + } + // 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 @@ -513,15 +743,30 @@ class LiveDryRoutingLab final { updated.mono,updated.mute,updated.solo); }))return false; channelEdits_[strip]=updated; + if(channelIdPhysicalPcmActive()) { + const auto id=nativeAccepted_.graph.ids.inputs[strip]; + const bool mirrored=(name=="mute"||name=="solo") + ?nativePublisher_.setChannelMuteSolo( + expectedEpoch,nativeAccepted_.pcmRevision, + id,updated.mute,updated.solo) + :nativePublisher_.setChannelMix( + expectedEpoch,nativeAccepted_.pcmRevision, + id,updated.linear,updated.pan); + if(!mirrored) + channelIdPcmEpoch_.store(0,std::memory_order_release); + } return true; } - // Operator M1: one POST gain is a realtime PARAMETER, never topology. - // The accepted send identity must exist and match THIS device epoch. + // Real AUX FX RETURN: one existing PRE or POST send has an independent + // realtime level. The tap/destination/edge identity are immutable here. + // A single render of source PCM, vendor VST, and AUX return remains + // authoritative on the installed JUCE callback. // The UI may adjust it while physical output is ARMED; no new plugin, // graph, callback or device restart occurs. bool setAuxSendGain(int source,int bus,std::uint64_t expectedEpoch, - std::uint64_t expectedRevision,float gain) noexcept { + std::uint64_t expectedRevision,float gain, + armix::mixer::SendTap tap=armix::mixer::SendTap::postFader) noexcept { if(source<0||source>=count||bus<0||bus>=auxCount|| !std::isfinite(gain)||gain<0.f||gain>1.f|| !ready()||!hasExplicitRoute()|| @@ -533,16 +778,24 @@ class LiveDryRoutingLab final { for(auto& item:*list) { if(static_cast(item.getProperty("from",-1))==source && static_cast(item.getProperty("to",-1))==count+bus && - item.getProperty("tap",{}).toString()=="POST") { + item.getProperty("tap",{}).toString()== + (tap==armix::mixer::SendTap::preFader?"PRE":"POST")) { accepted=&item;break; } } if(!accepted)return false; // No implicit creation of an AUX edge. if(!publisher_.updateActiveControl(expectedEpoch,expectedRevision, [&](FxGraph& fx) noexcept { - return fx.setAuxSendGain(source,bus,gain); + return fx.setAuxSendGain(source,bus,tap,gain); }))return false; accepted->getDynamicObject()->setProperty("gain",static_cast(gain)); + if(channelIdPhysicalPcmActive() && + !nativePublisher_.setParallelSendGain( + expectedEpoch,nativeAccepted_.pcmRevision, + nativeAccepted_.graph.ids.inputs[source], + nativeAccepted_.graph.ids.aux[bus], + tap==armix::mixer::SendTap::preFader,gain)) + channelIdPcmEpoch_.store(0,std::memory_order_release); return true; } @@ -563,6 +816,91 @@ class LiveDryRoutingLab final { return false; if(auto* obj=(*arr)[bus].getDynamicObject()) obj->setProperty("gain",static_cast(gain)); + if(channelIdPhysicalPcmActive() && + !nativePublisher_.setChannelMix( + expectedEpoch,nativeAccepted_.pcmRevision, + nativeAccepted_.graph.ids.aux[bus],gain,0.f)) + channelIdPcmEpoch_.store(0,std::memory_order_release); + return true; + } + + // Independent physical MONITOR/CUE bus: control only changes one + // existing send's target. PRE/POST AUX and MAIN VST PCM remain unchanged. + // If no verified distinct MONITOR output pair exists, reject. + bool setMonitorSendGain(int source,std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,float gain) noexcept { + if(source<0||source>=fxSlots||!std::isfinite(gain)|| + gain<0.f||gain>1.f||!hasExplicitRoute()|| + expectedEpoch!=epoch()||expectedRevision!=revision()) + return false; + auto gains=acceptedRoute_.getProperty("monitorSends",juce::var()); + auto* array=gains.getArray(); + const auto* current=publisher_.controlPrepared(expectedEpoch,expectedRevision); + if(!array||array->size()!=fxSlots||!current|| + !current->monitorEnabled())return false; + if(!publisher_.updateActiveControl(expectedEpoch,expectedRevision, + [&](FxGraph& fx) noexcept { + return fx.setMonitorSendGain(source,gain); + }))return false; + array->set(source,static_cast(gain)); // same accepted topology + if(channelIdPhysicalPcmActive() && + !nativePublisher_.setParallelSendGain( + expectedEpoch,nativeAccepted_.pcmRevision, + source laneIds, + armix::mixer::DynamicChannelFxLeaseBank& destination, + juce::String& error) const { + using Bank=armix::mixer::DynamicChannelFxLeaseBank; + if(laneIds.size()!=static_cast(fxSlots) || + !hasExplicitRoute() || !ready() || + expectedEpoch!=epoch() || expectedRevision!=revision()) { + error="M5: native epoch/revision or 10CH+4AUX FX roster stale"; + return false; + } + const FxGraph* current=publisher_.controlPrepared(expectedEpoch,expectedRevision); + if(!current) { + error="M5: no current M4 prepared vendor FX graph"; + return false; + } + std::vector staged; + staged.reserve(fxSlots); + for(int lane=0;lane(lane)], + format,*current,slot)) { + error="M5: failed to retain M4 VST3 token for lane "+ + juce::String(lane); + return false; + } + staged.push_back(std::move(slot)); + } + const auto fault=Bank::prepare(expectedEpoch,expectedRevision,staged, + destination); + if(fault!=Bank::Fault::none) { + error="M5: ChannelId VST lease migration rejected, fault "+ + juce::String(static_cast(fault)); + return false; + } + error.clear(); return true; } @@ -630,7 +968,100 @@ class LiveDryRoutingLab final { return {}; } + + // E2: ACTUAL hardware callback cutover for the admitted fixed 10CH+4AUX + // topology, retaining original per-lane JUCE VST3 leases and Show state. + // This CONTROL-only transaction uses real sparse driver port masks and + // the same physical destinations already validated by the M4 owner. + // Occupied original CH1/Orbit is leased as its existing shared Graph, + // including the exact atomic bypass, FX order, state, tail and editor. + // The published ChannelId snapshot retains this owner until RT retires. + bool admitChannelIdFromAcceptedM4(int occupiedExternalCh1Fx, + int deviceFrames,bool outputsDisarmed, + armix::mixer::DynamicChannelFxLeaseBank::ExternalLease externalCh1={}) { + channelIdPcmEpoch_.store(0,std::memory_order_release); + try { + if(!outputsDisarmed || occupiedExternalCh1Fx<0 || + (occupiedExternalCh1Fx>0)!=externalCh1.populated() || + !hasExplicitRoute()||!ready() || + topologyFault_.load(std::memory_order_acquire)) + return false; + const auto generation=epoch(),m4Revision=revision(); + const auto* old=publisher_.controlPrepared(generation,m4Revision); + if(!old || deviceFrames<=0) return false; + armix::mixer::NativeDryRouteCommand decoded; + juce::String problem; + if(!armix::mixer::NativeDryRouteCommand::decode( + acceptedRoute_,decoded,problem))return false; + // A native IN is a callback ordinal, not the numerical physical + // port label. Preserve original order including sparse ASIO pins. + const int inputs=portCount_.load(std::memory_order_acquire); + if(inputs<=0||inputs>armix::device::LiveInputPortRegistry::limit) + return false; + std::array ports{}; + for(int i=0;imainOutputLeft();hw.mainR=old->mainOutputRight(); + hw.monitorEnabled=old->monitorEnabled(); + if(hw.monitorEnabled) { + hw.monitorL=old->monitorOutputLeft(); + hw.monitorR=old->monitorOutputRight(); + } + std::array monitor{}; + if(hw.monitorEnabled) { + const auto gains=acceptedRoute_.getProperty("monitorSends",juce::var()); + const auto* list=gains.getArray(); + if(!list||list->size()!=fxSlots)return false; + for(int i=0;i( + static_cast(list->getReference(i))); + } + // The previous publisher belongs to another device generation. + // Retire it only on CONTROL, never from JUCE's device callback. + if(nativeAccepted_.deviceEpoch!=generation && + nativePublisher_.acceptedRevision()!=0) + nativePublisher_.unpublish(); + const int frames=juce::jmax(32,juce::jmin( + deviceFrames,old->maxFramesPerPlugin())); + auto applied=armix::mixer::UnifiedLegacyProductionAdmission::compileAndCommit( + decoded.channels,{ports.data(),static_cast(inputs)}, + decoded.sends,decoded.aux,monitor,*old, + occupiedExternalCh1Fx>0,hw, + frames,32u*1024u*1024u, + nativePublisher_.acceptedRevision(),generation,epoch(), + true,nativePublisher_,nativeAccepted_,std::move(externalCh1)); + if(!applied.ok() || generation!=epoch() || m4Revision!=revision()) + return false; // unchanged M4 PCM is the safe rollback + channelIdPcmEpoch_.store(generation,std::memory_order_release); + return true; + } catch(...) { + // Failure is on CONTROL; the original M4/Orbit graph remains + // valid and is the only callback PCM renderer selected. + return false; + } + } + void revokeChannelIdPcm() noexcept { + channelIdPcmEpoch_.store(0,std::memory_order_release); + } + bool channelIdPhysicalPcmActive() const noexcept { + const auto active=channelIdPcmEpoch_.load(std::memory_order_acquire); + return active!=0 && active==epoch() && ready(); + } + void disable() noexcept { + channelIdPcmEpoch_.store(0,std::memory_order_release); + nativePublisher_.unpublish(); // CONTROL-only; audio lease retires safely + nativeAccepted_=armix::mixer::UnifiedLegacyAccepted{}; userPatched_.store(false,std::memory_order_release); enabled_.store(false,std::memory_order_release); publishedEpoch_.store(0,std::memory_order_release); @@ -641,13 +1072,18 @@ class LiveDryRoutingLab final { fxCount_.store(0,std::memory_order_relaxed); fxReused_.store(0,std::memory_order_relaxed); acceptedRoute_=juce::var(); // control-thread STOP only + sourceTemplate_=juce::var(); + acceptedFxSelections_=FxSelections{}; for(auto& n:auxFxNames_)n.clear(); for(auto& p:channelPeaks_)p.store(0.f,std::memory_order_relaxed); for(auto& p:channelPeaksL_)p.store(0.f,std::memory_order_relaxed); for(auto& p:channelPeaksR_)p.store(0.f,std::memory_order_relaxed); for(auto& p:auxPeaks_)p.store(0.f,std::memory_order_relaxed); } - void poll() noexcept {publisher_.pollRetirement();} // message thread + void poll() noexcept { + publisher_.pollRetirement(); + nativePublisher_.pollRetirement(); + } // message thread only, reclaim both graph generations bool active() const noexcept {return enabled_.load(std::memory_order_acquire);} float peakLeft() const noexcept {return peakL_.load(std::memory_order_relaxed);} float peakRight() const noexcept {return peakR_.load(std::memory_order_relaxed);} @@ -679,6 +1115,17 @@ class LiveDryRoutingLab final { if(actualOutputPair)*actualOutputPair={{-1,-1}}; if(actualMonitorPair)*actualMonitorPair={{-1,-1}}; if(!active())return false; + // The real JUCE M4 callback owns one mutable DSP scratch/fade state. + // A broken backend overlapping two process() calls must never run + // two VST chains against the same prepared buffers. Fail SILENT, + // do not spin or take a lock on the host-owned realtime callback. + armix::rt::RealtimeRenderPermit exclusive{rendering_}; + if(!exclusive) { + if(outputs && frames>0 && frames<=Block::hardFrameLimit) + for(int c=0;c perChannelPeaks{}; std::array perChannelPeaksL{},perChannelPeaksR{}; @@ -798,11 +1248,35 @@ class LiveDryRoutingLab final { for(int c=0;cprepared->process(shifted.data(),inputCount, - mainL+offset,mainR+offset,n,&level, - externalContext,externalFx, - monitorL?monitorL+offset:nullptr, - monitorR?monitorR+offset:nullptr)) { + bool processed=false; + if(channelIdRender) { + // The current M4 import is at most 10+4+MAIN+MONITOR. + // Meter sources are the ACTUAL ChannelId PCM POST-fader + // lanes, not another mixer pass or reused M4 peak values. + std::array tapsL{},tapsR{}; + const auto noExtraFx=[](armix::mixer::ChannelId,float*,float*,int) noexcept {}; + processed=nativePublisher_.render( + generation,shifted.data(),inputCount, + mainL+offset,mainR+offset,n,false,noExtraFx, + monitorL?monitorL+offset:nullptr, + monitorR?monitorR+offset:nullptr,tapsL,tapsR); + if(processed) { + for(int ch=0;chprepared->process( + shifted.data(),inputCount,mainL+offset,mainR+offset,n, + &level,externalContext,externalFx, + monitorL?monitorL+offset:nullptr, + monitorR?monitorR+offset:nullptr); + } + if(!processed) { // A failed DSP pass must never leak partially rendered // MAIN/MONITOR PCM into an armed physical output. topologyFault_.store(true,std::memory_order_release); @@ -875,6 +1349,15 @@ class LiveDryRoutingLab final { out->setProperty("topologyFault",topologyFault_.load(std::memory_order_acquire)); out->setProperty("ready",ready()); out->setProperty("hasAcceptedRoute",hasExplicitRoute()); + const bool nativePcm=channelIdPhysicalPcmActive(); + out->setProperty("nativeChannelIdPcmActive",nativePcm); + // This exact original vendor Graph owner is retained by the native + // accepted snapshot, NOT merely a catalog name or M4 CH1 label. + // Message-thread diagnostic only; no false universal capabilities. + out->setProperty("originalCh1GraphLeased", + nativePcm && nativeAccepted_.fxOwners && + nativeAccepted_.fxOwners->externalChannel()== + nativeAccepted_.graph.ids.inputs[0]); out->setProperty("epoch",static_cast(epoch())); out->setProperty("revision",static_cast(revision())); out->setProperty("peakL",peakL_.load(std::memory_order_relaxed)); @@ -893,7 +1376,9 @@ class LiveDryRoutingLab final { out->setProperty("auxFxNames",juce::var(auxNames)); out->setProperty("auxPeaks",juce::var(auxPeaks)); out->setProperty("fxReused",fxReused_.load(std::memory_order_relaxed)); - // Only the message thread calls status(), never the audio callback. + // Control-thread snapshot; the existing channelControls property + // below is the single authoritative atomic-target readback, while + // acceptedRoute remains the immutable topology of the same revision. if(active() && ready())out->setProperty("acceptedRoute",acceptedRoute_); juce::Array liveFxInstances; const auto* prepared=hasExplicitRoute() @@ -991,7 +1476,11 @@ class LiveDryRoutingLab final { return juce::var(out.release()); } private: + std::atomic_flag rendering_=ATOMIC_FLAG_INIT; // one AUDIO producer Publisher publisher_; + armix::mixer::DynamicNativeSessionPublisher nativePublisher_; + armix::mixer::UnifiedLegacyAccepted nativeAccepted_; + std::atomic channelIdPcmEpoch_{0}; std::atomic monitorPeakL_{0.f},monitorPeakR_{0.f}; armix::dsp::MasterOutputMonoPolicy masterMonoPolicy_; // audio thread only std::array channelEdits_{}; // JUCE message thread only @@ -1000,6 +1489,8 @@ class LiveDryRoutingLab final { std::array,auxCount> auxPeaks_{}; std::atomic auxCountActive_{0},auxSendCount_{0}; juce::var acceptedRoute_; // native ACK only, no UI preview/localStorage truth + juce::var sourceTemplate_; // last prepared M4 template, including SILENT/NONE startup + FxSelections acceptedFxSelections_{}; // CONTROL ONLY: original VST3 identity for FX reuse // All data shared between JUCE device lifecycle and GUI/control reads // are atomic; the callback never enumerates masks or channel names. std::array,armix::device::LiveInputPortRegistry::limit> enabledPorts_{}; diff --git a/src/Main.cpp b/src/Main.cpp index c4258b25e..59a5bdb08 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -5,6 +5,7 @@ #include #include #include "LiveAudioEngine.h" +#include "ConsoleLiveBridgeV6.h" #include "ArSonMixStartupSplash.h" #include "VstOrbitController.h" #include "../engine/core/OrbitDistanceMapping.h" @@ -75,6 +76,40 @@ std::optional assetFor (const juce::String& { data = BinaryData::mixerlayout_js; size = BinaryData::mixerlayout_jsSize; mime = "text/javascript"; } else if (path == "/mixer-layout.css") { data = BinaryData::mixerlayout_css; size = BinaryData::mixerlayout_cssSize; mime = "text/css"; } + else if (path == "/hardware-keys.js") + { data = BinaryData::hardwarekeys_js; size = BinaryData::hardwarekeys_jsSize; mime = "text/javascript"; } + else if (path.startsWith("/assets/")) + { + // The standalone GUI references these physical fader/PAN images. + // Supply bytes only from embedded, SHA-bound JUCE BinaryData; an + // offline WebView cannot fetch adjacent disk files or the internet. + // This whitelist prevents WebView URL traversal into other resources. + static constexpr const char* allowed[] = { + "/assets/fader-silver2.png", + "/assets/faders/FADER-ARI-SILVER.png", + "/assets/faders/FADER-ARI-ROSEGOLD.png", + "/assets/faders/FADER-ARI-GOLD.png", + "/assets/pan/PAN-SLIDER.png", + "/assets/knob-ICON.svg" + }; + bool permitted = false; + for (auto* item : allowed) permitted |= path == item; + if (!permitted) return std::nullopt; + const auto basename=path.fromLastOccurrenceOf("/",false,false); + for (int i=0;ijuce::String { + if(nativeShowBusy_||studioBackupBusy_|| + engine_.isGraphSwitchPending()) + return "NATIVE_EDITOR_BUSY"; + const auto owner=engine_.leaseRoutedFxForEditor( + lane,slot,epoch,revision,token); + if(!owner || !owner->processor) + return "NATIVE_EDITOR_STALE_INSTANCE"; + try { + auto* editor=owner->processor->createEditorIfNeeded(); + if(!editor)return "NATIVE_PLUGIN_HAS_NO_EDITOR"; + closePluginEditor(); + routedEditorOwner_=owner; // original JUCE instance + routedEditorEpoch_=static_cast(epoch); + editorWindow_=std::make_unique( + owner->processor->getName(),editor); + return {}; + } catch(...) { + closePluginEditor(); + return "NATIVE_VENDOR_EDITOR_FAILED"; + } + }); + if (browser_.loaded) { + browser_.emitEventIfBrowserIsVisible("arMixConsoleAck",ack); + emitNativeConsoleSnapshot(engine_.status()); + } + }) .withResourceProvider (assetFor)) { settingsDirectory().createDirectory(); @@ -262,6 +342,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr private: LiveAudioEngine engine_; + armix::console::LiveConsoleBridgeV6 consoleBridge_; + bool consoleSubscribed_=false; VstOrbitController orbit_; juce::int64 fxGraphRevision_ = 1; // control-thread monotonic graph generation PluginCatalog catalog_; @@ -500,6 +582,13 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr browser_.emitEventIfBrowserIsVisible ("arMixNotice", juce::var (o.release())); } + void emitNativeConsoleSnapshot(const juce::var& engineStatus) + { + if(browser_.loaded && consoleSubscribed_) + browser_.emitEventIfBrowserIsVisible("arMixConsoleSnapshot", + armix::console::LiveConsoleBridgeV6::snapshot(engineStatus)); + } + void emitCatalog() { if (browser_.loaded) @@ -1353,6 +1442,39 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(error.isNotEmpty())emitNotice(error,true); return; } + // Operator-first native CHAN OUT / DSP FORMAT. This is the same + // installed M4 callback/FX publisher as routingSourceSwitch, not a + // synthetic universal ChannelId operation. GUI owner may wire a + // compact selector without navigating the large APPLY wizard. + if(action=="routingChannelStructure") { + const int requestId=static_cast(args.getProperty("requestId",0)); + const int channel=static_cast(args.getProperty("channel",-1)); + const auto operation=args.getProperty("operation","").toString(); + const auto selected=args.getProperty("selected","").toString(); + const auto ep=args.getProperty("deviceEpoch",juce::var()); + const auto rv=args.getProperty("revision",juce::var()); + const bool safe=requestId>0&&channel>=0&&channel(static_cast(ep)), + static_cast(static_cast(rv)), + operation,selected): + juce::String("CHANNEL PATCH: stale device or Show/FX edit busy"); + auto ack=std::make_unique(); + ack->setProperty("requestId",requestId); + ack->setProperty("channel",channel); + ack->setProperty("operation",operation); + ack->setProperty("ok",error.isEmpty()); + ack->setProperty("error",error); + ack->setProperty("state",engine_.status().getProperty("dryRoutingLab",{})); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixChannelStructureAck",juce::var(ack.release())); + if(error.isNotEmpty())emitNotice(error,true); + return; + } if (action == "routingDryApply") { LiveDryRoutingLab::FxSelections selected{}; @@ -1458,9 +1580,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr "arMixAuxBusGainAck",juce::var(ack.release())); return; } - // M1 operator realtime PARAM: existing AUX POST gain changes while - // audio is running. Structural sends remain guarded MUTE/APPLY. + // Existing PRE and POST sends are realtime parameters, including a + // live vocal SEND → AUX FX Return. Tap selection and NEW send edges + // remain separate structural transactions; this changes LEVEL only. if(action=="routingAuxSendGain") { + const auto tapName=args.getProperty("tap","POST").toString(); + const bool validTap=tapName=="PRE"||tapName=="POST"; + const auto tap=tapName=="PRE" + ?armix::mixer::SendTap::preFader + :armix::mixer::SendTap::postFader; const int source=static_cast(args.getProperty("from",-1)); const int bus=static_cast(args.getProperty("bus",-1)); const int requestId=static_cast(args.getProperty("requestId",0)); @@ -1469,24 +1597,89 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const bool number=value.isDouble()||value.isInt(); const float gain=number?static_cast(static_cast(value)):-1.f; const bool ok=!nativeShowBusy_&&!studioBackupBusy_&&!ep.isVoid()&&!rv.isVoid() && - number && requestId>0 && + number && validTap && requestId>0 && engine_.setDryRoutingLabAuxSendGain(source,bus, static_cast(static_cast(ep)), - static_cast(static_cast(rv)),gain); + static_cast(static_cast(rv)),gain,tap); auto ack=std::make_unique(); ack->setProperty("ok",ok); ack->setProperty("requestId",requestId); ack->setProperty("from",source); ack->setProperty("bus",bus); + ack->setProperty("tap",tapName); ack->setProperty("gain",static_cast(gain)); ack->setProperty("error",ok?juce::String(): - "Live AUX gain rejected: route revision/device changed or POST send missing"); + "Live AUX gain rejected: stale route, invalid tap or missing PRE/POST send"); ack->setProperty("state",engine_.status().getProperty("dryRoutingLab",{})); if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( "arMixAuxSendGainAck",juce::var(ack.release())); if(!ok)emitNotice("Live AUX send rejected; refresh accepted routing.",true); return; } + // One-click SEND -> existing real AUX VST3 RETURN. The structural + // graph transaction prepares/validates and retains the same processor + // owner; no unfiltered empty AUX can duplicate dry MAIN. + if(action=="routingAuxConnect") { + const int from=static_cast(args.getProperty("from",-1)); + const int bus=static_cast(args.getProperty("bus",-1)); + const int requestId=static_cast(args.getProperty("requestId",0)); + const auto ep=args.getProperty("deviceEpoch",juce::var()); + const auto rv=args.getProperty("revision",juce::var()); + const auto kind=args.getProperty("tap","POST").toString(); + const auto rawGain=args.getProperty("gain",juce::var()); + const auto rawPan=args.getProperty("pan",juce::var(0.0)); + const bool valid=requestId>0&&!nativeShowBusy_&&!studioBackupBusy_&& + (ep.isInt()||ep.isInt64())&&(rv.isInt()||rv.isInt64())&& + (rawGain.isInt()||rawGain.isDouble())&& + (rawPan.isInt()||rawPan.isDouble())&& + (kind=="PRE"||kind=="POST"); + const juce::String error=valid?engine_.connectDryRoutingLabAuxSend( + from,bus,static_cast(static_cast(ep)), + static_cast(static_cast(rv)), + kind=="PRE"?armix::mixer::SendTap::preFader: + armix::mixer::SendTap::postFader, + static_cast(static_cast(rawGain)), + static_cast(static_cast(rawPan))): + juce::String("AUX CONNECT: invalid or stale request"); + auto ack=std::make_unique(); + ack->setProperty("ok",error.isEmpty()); + ack->setProperty("requestId",requestId); + ack->setProperty("from",from); + ack->setProperty("bus",bus); + ack->setProperty("tap",kind); + ack->setProperty("error",error); + ack->setProperty("state",engine_.status().getProperty("dryRoutingLab",{})); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixAuxConnectAck",juce::var(ack.release())); + return; + } + // Same installed M4 callback owns independent MONITOR output pins. + // Move input or AUX return's own MONITOR SEND at audio rate without + // touching MAIN/FX or changing the physical port map. + if(action=="routingMonitorSendGain") { + const int source=static_cast(args.getProperty("from",-1)); + const int requestId=static_cast(args.getProperty("requestId",0)); + const auto ep=args.getProperty("deviceEpoch",juce::var()); + const auto rv=args.getProperty("revision",juce::var()); + const bool numeric=value.isInt()||value.isDouble(); + const float gain=numeric?static_cast(static_cast(value)):-1.f; + const bool ok=requestId>0&&!nativeShowBusy_&&!studioBackupBusy_&& + (ep.isInt()||ep.isInt64())&&(rv.isInt()||rv.isInt64())&&numeric&& + engine_.setDryRoutingLabMonitorSendGain( + source,static_cast(static_cast(ep)), + static_cast(static_cast(rv)),gain); + auto ack=std::make_unique(); + ack->setProperty("ok",ok); + ack->setProperty("requestId",requestId); + ack->setProperty("from",source); + ack->setProperty("gain",static_cast(gain)); + ack->setProperty("error",ok?juce::String(): + "MONITOR send rejected: no independent MONITOR bus, stale route or invalid gain"); + ack->setProperty("state",engine_.status().getProperty("dryRoutingLab",{})); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixMonitorSendGainAck",juce::var(ack.release())); + return; + } // G5C native per-instance BYPASS never recompiles the graph and // does not require muting the output. All identity gates must agree. if (action == "routingFxBypass") { @@ -2566,6 +2759,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (startupError_.isNotEmpty() && !bool (state.getProperty ("connected", false))) state.getDynamicObject()->setProperty ("error", startupError_); browser_.emitEventIfBrowserIsVisible ("arMixStatus", state); + // Four status readbacks/second on the control thread. No JUCE + // callback mutation, graph pointer lease or extra signal engine. + if(consoleSubscribed_ && timerTicks_%3==0) + emitNativeConsoleSnapshot(state); } }; diff --git a/src/NativeShowSaveWorker.h b/src/NativeShowSaveWorker.h index f44e1f23f..f568003d2 100644 --- a/src/NativeShowSaveWorker.h +++ b/src/NativeShowSaveWorker.h @@ -43,17 +43,19 @@ class NativeShowSaveWorker final : private juce::Thread { } bool launch(juce::File studio,SnapshotV2 snapshot, std::vector binaryStates,Completion completion) { - if(!reserve(Operation::save,std::move(studio),std::move(completion)) || - !detail::uuid(snapshot.id))return false; + // Reject invalid requests BEFORE reserving or retaining a potentially + // large vendor-state payload on this long-lived worker. + if(!detail::uuid(snapshot.id) || + !reserve(Operation::save,std::move(studio),std::move(completion))) + return false; snapshot_=std::move(snapshot); blobs_=std::move(binaryStates); - if(startThread())return true; - return false; + return startOrRelease(); } bool list(juce::File studio,Completion completion) { if(!reserve(Operation::list,std::move(studio),std::move(completion))) return false; - return startThread(); + return startOrRelease(); } bool read(juce::File studio,juce::String showId, juce::int64 epoch,juce::int64 revision,Completion completion) { @@ -62,9 +64,27 @@ class NativeShowSaveWorker final : private juce::Thread { return false; requestedId_=std::move(showId); requestEpoch_=epoch;requestRevision_=revision; - return startThread(); + return startOrRelease(); } private: + // Start failure must release captured Show snapshots, binary-state blobs + // and completion closures. The worker never transfers these to RT. + bool startOrRelease() { + if(startThread())return true; + releaseJob(); + return false; + } + // Exclusively invoked after the worker's IO is finished or before it + // started. No concurrent use with the caller/message thread. + void releaseJob() { + snapshot_=SnapshotV2{}; + blobs_.clear(); + blobs_.shrink_to_fit(); + requestedId_={}; + requestEpoch_=0;requestRevision_=0; + studio_={}; + finished_={}; + } bool reserve(Operation mode,juce::File studio,Completion completion) { if(isThreadRunning()||!completion)return false; operation_=mode;studio_=std::move(studio); @@ -86,10 +106,11 @@ class NativeShowSaveWorker final : private juce::Thread { } catch(...) { result.error="Unknown native Show IO exception; session unchanged"; } - blobs_.clear(); // release captured bytes on IO thread after commit - blobs_.shrink_to_fit(); + // Move the completion closure out: the worker must not retain a + // second copy of UI captures or a large Show snapshot between jobs. + auto done=std::move(finished_); + releaseJob(); // IO worker thread, never audio callback auto alive=alive_; - auto done=finished_; // A 128 MB vendor-blob result must not be copied by std::function // when JUCE queues an async callback on the message thread. auto delivered=std::make_shared(std::move(result)); diff --git a/src/NativeVerifiedSourcePatch.h b/src/NativeVerifiedSourcePatch.h new file mode 100644 index 000000000..ca9927d87 --- /dev/null +++ b/src/NativeVerifiedSourcePatch.h @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include + +// Message-thread SOURCE transaction: one verified input selection from an +// initially SILENT M4 session, without modifying the accepted Show or FX +// until the whole graph/epoch has compiled. Both MAIN and auxiliary outputs +// remain owned by the existing one JUCE production callback. +namespace armix::mixer { +struct NativeVerifiedSourcePatch final { + static juce::String prepare(const juce::var& accepted, + int channel,const juce::String& mode,int physicalLeft,int physicalRight, + std::span enabledPhysicalPorts, + std::uint64_t actualEpoch,std::uint64_t actualRevision, + juce::var& destination) + { + if(!actualEpoch || + actualEpoch>static_cast(std::numeric_limits::max()) || + 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()) + return "SOURCE: select an enabled physical capture pin"; + if(static_cast(accepted.getProperty("deviceEpoch",juce::var(-1))) != + static_cast(actualEpoch)) + return "SOURCE: device epoch changed; accepted patch preserved"; + bool validLeft=false,validRight=false; + for(const int port:enabledPhysicalPorts) { + if(port==physicalLeft)validLeft=true; + if(port==physicalRight)validRight=true; + } + if(!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 + // mutate the still-audible accepted routing snapshot. + auto copy=juce::JSON::parse(juce::JSON::toString(accepted,false)); + if(!copy.isObject()) + return "SOURCE: cannot clone accepted native patch"; + auto channels=copy.getProperty("channels",juce::var()); + auto* list=channels.getArray(); + if(!list || list->size()!=10 || !list->getReference(channel).isObject()) + return "SOURCE: accepted patch channel layout unavailable"; + auto* row=list->getReference(channel).getDynamicObject(); + // Native routing v2 separates SOURCE format from the processing + // channel width. A source is not audible if only the old "mode" + // field changes: NativeDryRouteCommand::decode will reject the stale + // sourceKind/sourceFormat. Keep selected channelFormat intact so a + // one-pin MONO microphone may feed STEREO processing without IN2. + const auto schema=copy.getProperty("schemaVersion",juce::var()); + if(!schema.isVoid() && (!schema.isInt() || + (static_cast(schema)!=1 && static_cast(schema)!=2))) + return "SOURCE: unsupported accepted native route version"; + if(schema.isInt() && static_cast(schema)==2) { + 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("sourceFormat",mode); + } + row->setProperty("mode",mode); + row->setProperty("left",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. + copy.getDynamicObject()->setProperty("deviceEpoch",static_cast(actualEpoch)); + copy.getDynamicObject()->setProperty("revision",static_cast(actualRevision)); + destination=std::move(copy); + return {}; + } +}; +} // namespace armix::mixer diff --git a/tests/button_asset_test.py b/tests/button_asset_test.py index 26d835420..7e34d1445 100644 --- a/tests/button_asset_test.py +++ b/tests/button_asset_test.py @@ -26,7 +26,9 @@ 'display:inline-flex', 'inset 5px 5px 2px -1px rgba(0,0,0,.18)' ): assert ''.join(rule.split()) in compact,rule -assert '--b180-off:#cbd1d1' in css +# PR#278 V6 owner-approved brighter OFF plastic; keep all original seven shadows. +assert '--b180-off:#E7EFF0' in css +assert '--b180-off:#E7EFF0' in (root/'web/styles-src/20-button-180.css').read_text(encoding='utf8') assert '--b180-edge:#747f7f' in css assert '--b180-off-ink:#172229' in css assert '--b180-ink:var(--b180-off-ink)' in css diff --git a/tests/ci_workflow_efficiency_test.mjs b/tests/ci_workflow_efficiency_test.mjs index 17241a1ad..e3b5c7833 100644 --- a/tests/ci_workflow_efficiency_test.mjs +++ b/tests/ci_workflow_efficiency_test.mjs @@ -15,8 +15,10 @@ test('only main and explicitly selected branch can produce a Windows FAT artifac assert.match(windows,/'web\/\*\*'/); assert.match(windows,/workflow_dispatch:/); assert.match(windows,/cancel-in-progress: true/); - assert.match(windows,/if: \$\{\{ github\.event_name != 'pull_request' \|\| github\.head_ref == 'milestone\/m4-unified-native-multichannel-fx-20261101' \}\}/); - assert.match(windows,/ArSonMix-M4-EXPERIMENTAL-Hardware-FAT-Windows-x64/); + assert.match(windows,/github\.head_ref == 'milestone\/m5-universal-channelid-vst3-lease-migration-20261101'/); + assert.match(windows,/github\.head_ref == 'work\/integration-fat-console-v6'/); + assert.match(windows,/ArSonMix-ENGINE-10CH4AUX-EXPERIMENTAL-Hardware-FAT-Windows-x64/); + assert.ok(!windows.includes("github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101'")); assert.ok(windows.indexOf('scripts/verify_native_windows_artifact.ps1') < windows.indexOf('uses: actions/upload-artifact@v4')); }); @@ -45,6 +47,16 @@ test('retain current native audio and dearVR CTests during CI optimization',()=> } assert.match(windows,/ctest --test-dir build -C Release --output-on-failure/); assert.match(windows,/'scripts\/build_ui_css\.py'/); - assert.match(windows,/if: \$\{\{ github\.event_name != 'pull_request' \|\| github\.head_ref == 'milestone\/m4-unified-native-multichannel-fx-20261101' \}\}/); - assert.match(windows,/ArSonMix-M4-EXPERIMENTAL-Hardware-FAT-Windows-x64/); + assert.match(windows,/github\.head_ref == 'milestone\/m5-universal-channelid-vst3-lease-migration-20261101'/); + assert.match(windows,/github\.head_ref == 'work\/integration-fat-console-v6'/); + assert.match(windows,/ArSonMix-ENGINE-10CH4AUX-EXPERIMENTAL-Hardware-FAT-Windows-x64/); +}); + +test('native FAT compiles the exact ENGINE PR HEAD and rejects transient merge refs',()=>{ + const shaRef="ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}"; + assert.ok(windows.includes(shaRef)); + assert.match(windows,/ENGINE_EXACT_SOURCE_SHA_VERIFIED/); + assert.match(windows,/git rev-parse HEAD/); + assert.ok(windows.indexOf('ENGINE_EXACT_SOURCE_SHA_VERIFIED')< + windows.indexOf('name: Build executable and native RT tests')); }); diff --git a/tests/console_native_integration_test.cpp b/tests/console_native_integration_test.cpp index b9c66d79b..3732e7bd9 100644 --- a/tests/console_native_integration_test.cpp +++ b/tests/console_native_integration_test.cpp @@ -7,6 +7,8 @@ #include #include #include +#include +#include #include using namespace armix::mixer; @@ -51,6 +53,22 @@ int main() { assert(first.ok() && first.edit.createdIds.size()==12); const auto ch7=first.edit.createdIds[6],ch2=first.edit.createdIds[1]; const auto main=first.edit.createdIds[10],monitor=first.edit.createdIds[11]; + // A serial OUT must always be POST fader, unity and neutral pan. + // PRE / independent send-level / send-pan belong only to parallel SEND. + ChannelEdit invalidOut;invalidOut.kind=ChannelEdit::Kind::addSendReference; + invalidOut.id=ch7;invalidOut.target=main; + invalidOut.value=1.f;invalidOut.preFader=true; + invalidOut.primaryOutput=true; + const auto tryOut=[&](const ChannelEdit& op) { + const std::array changes{op}; + return native.edit(1,1,changes,route,epoch,epoch,true); + }; + assert(!tryOut(invalidOut).ok()); + invalidOut.preFader=false;invalidOut.value=.5f; + assert(!tryOut(invalidOut).ok()); + invalidOut.value=1.f;invalidOut.sendPan=.2f; + assert(!tryOut(invalidOut).ok()); + assert(native.acceptedGraphRevision()==1); // Two IN pins are callback ordinals, not guessed adjacent physical DB labels. route.sources={{ch7,0,-1,false},{ch2,1,-1,false}}; std::array edges{linkOut(ch7,main),linkOut(ch2,main), @@ -70,20 +88,62 @@ int main() { assert(!snap.productionCallbackLive); assert(!snap.capabilities.universalLive()); assert(!snap.capabilities.group&&!snap.capabilities.fxReturn); + const auto firstWire=toConsoleWireReadbackV6(snap); + assert(firstWire.schemaVersion==6 && firstWire.deviceEpoch=="69"); + assert(firstWire.graphRevision=="2" && firstWire.rosterRevision=="2"); + assert(firstWire.channels[6].id==std::to_string(ch7.value)); + assert(firstWire.channels[6].role=="INPUT"); + assert(firstWire.channels[6].processingFormat=="MONO"); + assert(!firstWire.productionCallbackLive); + auto huge=snap; + huge.deviceEpoch=std::numeric_limits::max(); + huge.graphRevision=9007199254740993ULL; + const auto encoded=toConsoleWireReadbackV6(huge); + assert(encoded.deviceEpoch=="18446744073709551615"); + assert(encoded.graphRevision=="9007199254740993"); ConsoleIntentV6 intent; - intent.requestId=41;intent.deviceEpoch=epoch; + intent.requestId="gui-live:41";intent.deviceEpoch=epoch; intent.baseGraphRevision=2;intent.baseRosterRevision=2; intent.operation=ConsoleIntentV6::Operation::groupSelected; intent.target=ch7; - assert(validateConsoleIntent(intent,epoch,40,native)==IntentFaultV6::none); - assert(validateConsoleIntent(intent,epoch,41,native)==IntentFaultV6::duplicateOrOldRequest); - assert(validateConsoleIntent(intent,epoch+1,40,native)==IntentFaultV6::staleDevice); + // Multiple WebViews can coexist/reconnect. Dedup by opaque request ID, + // NOT by numeric sequence: 'gui-new:1' remains valid after 'gui-old:41'. + const std::array completedIds{ + "gui-old:41","gui-live:40"}; + const std::array completedIncluding{ + "gui-live:41","gui-old:41","gui-live:40"}; + assert(validateConsoleIntent(intent,epoch,completedIds,native)==IntentFaultV6::none); + assert(validateConsoleIntent(intent,epoch,completedIncluding,native) + ==IntentFaultV6::duplicateOrOldRequest); + assert(validateConsoleIntent(intent,epoch+1,completedIds,native) + ==IntentFaultV6::staleDevice); intent.baseGraphRevision=1; - assert(validateConsoleIntent(intent,epoch,40,native)==IntentFaultV6::staleGraph); + assert(validateConsoleIntent(intent,epoch,completedIds,native) + ==IntentFaultV6::staleGraph); intent.baseGraphRevision=2;intent.baseRosterRevision=1; - assert(validateConsoleIntent(intent,epoch,40,native)==IntentFaultV6::staleRoster); + assert(validateConsoleIntent(intent,epoch,completedIds,native) + ==IntentFaultV6::staleRoster); intent.baseRosterRevision=2; + intent.requestId="gui-new:1"; + assert(validateConsoleIntent(intent,epoch,completedIds,native)==IntentFaultV6::none); + intent.requestId="gui-live:41"; + assert(validConsoleRequestId(intent.requestId)); + intent.requestId="gui\nbad:42"; + assert(validateConsoleIntent(intent,epoch,completedIds,native) + ==IntentFaultV6::invalidRequest); + intent.requestId=std::string(129,'x'); + assert(validateConsoleIntent(intent,epoch,completedIds,native) + ==IntentFaultV6::invalidRequest); + intent.requestId="gui-live:41"; + ChannelId parsed{}; + assert(parseNativeChannelId("18446744073709551615",parsed) && + parsed.value==std::numeric_limits::max()); + assert(!parseNativeChannelId("18446744073709551616",parsed)); + assert(!parseNativeChannelId("ch-07",parsed)); + assert(!parseNativeChannelId("07",parsed)); + assert(!parseNativeChannelId("0",parsed)); + assert(parseNativeChannelId(std::to_string(ch7.value),parsed) && parsed==ch7); std::array a{},b{},left{},right{},ml{},mr{}; a.fill(.2f);b.fill(.4f); @@ -108,6 +168,8 @@ int main() { assert(!stale.ok()); auto nack=consoleAckFromNative(intent,IntentFaultV6::none,native,&stale); assert(nack.status==ConsoleAckV6::Status::rejected); + assert(nack.requestId==intent.requestId); + assert(consoleWireAckStatus(nack)=="REJECTED"); assert(nack.graphRevision==2 && !nack.productionCallbackLive); const auto prev=snap; assert(!projectAcceptedConsoleV6(native,epoch+1,2,snap)); @@ -121,11 +183,23 @@ int main() { group=added.edit.createdIds[0]; auto ack=consoleAckFromNative(intent,IntentFaultV6::none,native,&added); assert(ack.status==ConsoleAckV6::Status::acceptedGraph); + assert(ack.requestId=="gui-live:41"); + assert(consoleWireAckStatus(ack)=="ACCEPTED"); assert(ack.graphRevision==3 && !ack.productionCallbackLive); assert(projectAcceptedConsoleV6(native,epoch,3,snap)); assert(find(snap,ch7)->primaryOutId==std::to_string(group.value)); assert(find(snap,ch2)->primaryOutId==std::to_string(group.value)); assert(find(snap,group)->primaryInputCount==2); + const auto groupWire=toConsoleWireReadbackV6(snap); + // The accepted roster order is NOT the operator display order. Resolve + // the actual accepted ChannelId, never assume a newly added bus is last. + const auto groupWireIt=std::find_if(groupWire.channels.begin(), + groupWire.channels.end(),[&](const auto& c) { + return c.id==std::to_string(group.value); + }); + assert(groupWireIt!=groupWire.channels.end()); + assert(groupWireIt->role=="GROUP" && + groupWireIt->primaryInputCount==2); assert(render()&&approx(left[31],(.2f+.4f)*center*2.f)); assert(approx(ml[31],(.2f*.2f+.4f*.3f)*center)); @@ -139,6 +213,14 @@ int main() { assert(liveCh7 && liveCh7->primaryOutId==std::to_string(group.value)); assert(liveCh7->sends.size()==2); // MONITOR remains, wet SEND added assert(find(snap,wet)->parallelSendInputCount==1); + const auto returnWire=toConsoleWireReadbackV6(snap); + const auto returnWireIt=std::find_if(returnWire.channels.begin(), + returnWire.channels.end(),[&](const auto& c) { + return c.id==std::to_string(wet.value); + }); + assert(returnWireIt!=returnWire.channels.end()); + assert(returnWireIt->role=="FX_RETURN" && + returnWireIt->parallelSendInputCount==1); assert(render()); assert(approx(left[31],(.2f+.4f)*center*2.f+.2f*center*.25f*.5f)); assert(approx(ml[31],(.2f*.2f+.4f*.3f)*center)); @@ -148,11 +230,48 @@ int main() { const std::array editOne{linkOut(ch2,main)}; auto rejected=native.edit(4,4,editOne,route,epoch,epoch,true); assert(!rejected.ok()); + assert(rejected.fault==DynamicAcceptedSession::Fault::graphRejected); + assert(rejected.native.fault==DynamicNativeSessionPublisher::Fault::invalidGraph); + assert(rejected.native.graphError.fault==DynamicGraphFault::invalidSource); + assert(native.acceptedPhysicalRequest().sources[1].inputL==1); assert(native.acceptedGraphRevision()==4); assert(projectAcceptedConsoleV6(native,epoch,4,snap)); assert(snap.channels.size()==14 && !snap.productionCallbackLive); route.sources[1].inputL=1; assert(render()&&left[31]>0.f); + // A different but valid IN2 pin in an OUT structural edit MUST NACK. + // No old-source overlay and no false GUI acceptance. + route.sources[1].inputL=0; + auto wrongAck=native.edit(4,4,editOne,route,epoch,epoch,true); + assert(!wrongAck.ok() && + wrongAck.native.graphError.fault==DynamicGraphFault::invalidSource); + assert(wrongAck.native.graphError.id==ch2); + assert(native.acceptedGraphRevision()==4); + route.sources[1].inputL=1; + assert(render()); + assert(approx(left[31],(.2f+.4f)*center*2.f+ + .2f*center*.25f*.5f)); + // The real native same-format IN operation changes PCM and canonical + // readback without changing ChannelId, VST lane or graph revision. + assert(native.setLivePhysicalSource(epoch,4,ch2,0,-1,false)); + assert(native.acceptedPhysicalRequest().sources[1].inputL==0); + assert(render()&&render()); // 64-sample dezipper across two 32f blocks + assert(approx(left[31],(.2f+.2f)*center*2.f+ + .2f*center*.25f*.5f)); + assert(approx(ml[31],(.2f*.2f+.2f*.3f)*center)); + // A previous GUI draft is now stale. It must rebase from accepted + // native SOURCE before changing OUT; never receive a phantom ACK. + wrongAck=native.edit(4,4,editOne,route,epoch,epoch,true); + assert(!wrongAck.ok() && native.acceptedGraphRevision()==4); + route=native.acceptedPhysicalRequest(); + auto changedOut=native.edit(4,4,editOne,route,epoch,epoch,true); + assert(changedOut.ok() && native.acceptedGraphRevision()==5); + assert(native.acceptedPhysicalRequest().sources[1].inputL==0); + assert(render()); + // CH7 -> GROUP (serial + FX) while CH2 -> MAIN (direct), and + // CH7 -> wet FX Return in parallel: no double-dry contribution. + assert(approx(left[31],(.2f*2.f+.2f+.2f*.25f*.5f)*center)); + assert(approx(ml[31],(.2f*.2f+.2f*.3f)*center)); // OUTPUT MUTE must silence BOTH main and monitor and never invoke FX. assert(!native.render(epoch,pins,2,left.data(),right.data(), 32,true,fx,ml.data(),mr.data())); diff --git a/tests/console_native_s0_playwright.py b/tests/console_native_s0_playwright.py new file mode 100644 index 000000000..40e91d94b --- /dev/null +++ b/tests/console_native_s0_playwright.py @@ -0,0 +1,44 @@ +"""S0 Playwright consumer: SAME C++-generated native JSON used by FAT validator.""" +import argparse,asyncio,json +from pathlib import Path +from playwright.async_api import async_playwright +ROOT=Path(__file__).resolve().parents[1] +async def check(f): + ev=json.loads(Path(f).read_text(encoding='utf8'))['events'] + assert [e['event'] for e in ev]==['arMixConsoleSnapshot','arMixConsoleIntent','arMixConsoleAck','arMixConsoleSnapshot'] + s,cmd,ack,n=[e['payload'] for e in ev] + assert s==n and ack['status']=='REJECTED' and not s['productionCallbackLive'] + async with async_playwright() as p: + b=await p.chromium.launch(headless=True) + page=await b.new_page(viewport={'width':1366,'height':768}) + await page.add_init_script("""(() => { + const listeners={},out=[]; + window.__s0={out,publish:(e,p)=>(listeners[e]||[]).forEach(fn=>fn(p))}; + window.__JUCE__={backend:{emitEvent:(e,p)=>out.push({event:e,payload:p}), + addEventListener:(e,fn)=>(listeners[e]||=[]).push(fn)}}; + })()""") + await page.goto((ROOT/'web/index.html').as_uri()) + assert await page.evaluate("()=>window.__s0.out.some(x=>x.event==='arMixConsoleSubscribe')") + await page.evaluate("x=>window.__s0.publish('arMixConsoleSnapshot',x)",s) + state=await page.evaluate("()=>window.__arMixV6ReadOnly()") + assert state['nativePublisher'] is True and state['revision']==s['graph']['revision'] + assert state['visibleChannelIds']==[], 'GUI manufactured S0 ghost channels' + assert await page.locator('#arV6Console').is_hidden(), 'GUI promoted G0 as LIVE' + await page.evaluate("x=>window.__s0.publish('arMixConsoleAck',x)",ack) + await page.evaluate("x=>window.__s0.publish('arMixConsoleSnapshot',x)",n) + after=await page.evaluate("()=>window.__arMixV6ReadOnly()") + assert after['revision']==state['revision'] and after['pendingCount']==0 + malformed=json.loads(json.dumps(s)) + malformed['device'].pop('enabledInputs',None) + await page.evaluate("x=>window.__s0.publish('arMixConsoleSnapshot',x)",malformed) + rejected=await page.evaluate("()=>window.__arMixV6ReadOnly()") + assert rejected['revision']==state['revision'] + assert rejected['epoch']==state['epoch'] + assert rejected['visibleChannelIds']==[], 'invalid native pin inventory caused ghost channel' + await b.close() + print('S0_CPP_TO_GUI_SCHEMA_PASS_NOT_PCM') +if __name__=='__main__': + p=argparse.ArgumentParser() + p.add_argument('--fixture',required=True) + args=p.parse_args() + asyncio.run(check(args.fixture)) diff --git a/tests/console_puzzle_v8_fixture.cpp b/tests/console_puzzle_v8_fixture.cpp new file mode 100644 index 000000000..5ac77807e --- /dev/null +++ b/tests/console_puzzle_v8_fixture.cpp @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Portable C++ fixture generator, SAME serializer as runtime. +// g++ -std=c++20 -O2 -Wall -Wextra -Werror -pedantic -Iengine/core tests/console_puzzle_v8_fixture.cpp -o /tmp/arsonmix-v8-fixture +// /tmp/arsonmix-v8-fixture > tests/fixtures/console-v8-native-unready.json +#include "../engine/core/ConsolePuzzleV8Wire.h" +#include +#include +#include +int main(int argc,char** argv) { + using namespace armix::console; + PuzzleV8Snapshot snapshot; + // No audio driver exists in deterministic CI. UNREADY is the only + // truthful native state: zero invented physical pins or PCM and no fake + // ChannelIds from M4 presentation indices. + snapshot.epoch="1"; + PuzzleV8Ack ack; + ack.requestId="native-fixture-session:1"; + ack.deviceEpoch=snapshot.epoch; + const auto json=PuzzleV8Wire::fixture(snapshot,ack); + assert(json.find("\"enabledInputs\":[]")!=std::string::npos); + assert(json.find("\"productionCallbackLive\":false")!=std::string::npos); + assert(json.find("\"supportedOps\":[]")!=std::string::npos); + if(argc>1 && std::string(argv[1])=="--negative") { + snapshot.inputs.push_back({5,0,"Mic 1",true,0.125}); + snapshot.outputs.push_back({2,0,"OUT3",false,0.}); + const auto withPins=PuzzleV8Wire::snapshot(snapshot); + assert(withPins.find("\"enabledInputs\":[5]")!=std::string::npos); + assert(withPins.find("\"enabledOutputs\":[2]")!=std::string::npos); + assert(withPins.find("\"rawPeak\":0.125")!=std::string::npos); + assert(PuzzleV8Wire::ack(ack).find("native-fixture-session:1")!=std::string::npos); + return 0; + } + std::cout<structuredClone(x); +const snapshot=n=>({event:'arMixConsoleSnapshot',payload:{ + schemaVersion:6,productionCallbackLive:false, + device:{epoch:'69',outputArmed:false,enabledInputs:[0,1],enabledOutputs:[0,1], + inputEndpoints:[],outputEndpoints:[]}, + graph:{revision:String(n),rosterRevision:'5', + capabilities:{callbackOwnsChannelIds:false,groups:false,fxReturns:false, + monitor:true,supportedOps:['SET_FADER','SET_SOURCE']}, + channels:[{id:'7',role:'INPUT',source:{physicalPins:[0]}}, + {id:'2',role:'INPUT',source:{physicalPins:[1]}},{id:'100',role:'MAIN'}], + destinations:[]},telemetry:{rawCapturePresent:false}}}); +const evt=(event,payload)=>({event,payload}); +const trace=()=>({schema:TRACE_SCHEMA,provenance:{kind:'SYNTHETIC'},events:[ + snapshot(2), + evt('arMixConsoleIntent',{requestId:'webview-session:1',deviceEpoch:'69', + baseGraphRevision:'2',baseRosterRevision:'5',operation:'SET_FADER', + targetChannelId:'7',payload:{faderDb:-6}}), + evt('arMixConsoleAck',{requestId:'webview-session:1',status:'ACCEPTED', + graphRevision:'3',rosterRevision:'5'}),snapshot(3), + evt('arMixConsoleIntent',{requestId:'webview-session:2',deviceEpoch:'69', + baseGraphRevision:'2',baseRosterRevision:'5',operation:'SET_SOURCE', + targetChannelId:'7',payload:{portId:'IN1'}}), + evt('arMixConsoleAck',{requestId:'webview-session:2',status:'REJECTED', + graphRevision:'3',rosterRevision:'5',errorCode:'STALE_GRAPH'}),snapshot(3)]}); +const dry=[0.2,-0.1,0.4,-0.3],wet=[0.01,0.03,0.02,-0.01],grp=dry.map(x=>x*0.5),zero=a=>a.map(()=>0); +const pcm=()=>({schema:'arsonmix.console-v6.pcm-evidence.v1',cases:[ + {kind:'independent_inputs',samples:{input1:[0.1,-0.1,0.1,-0.1],input2:[0.05,0.15,-0.05,-0.15],ch7:[0.1,-0.1,0.1,-0.1],ch2:[0.05,0.15,-0.05,-0.15]}}, + {kind:'group_fx_return',groupGain:0.5,samples:{dry,group:grp,wetReturn:wet,main:grp.map((x,i)=>x+wet[i]),groupMutedMain:wet,returnMutedMain:grp}}, + {kind:'monitor_isolation',mainDestination:'hp0/1',monitorDestination:'hp2/3',samples:{main:dry,monitor:wet,monitorMuted:zero(wet),mainAfterMonitorMute:dry}}, + {kind:'physical_mute',samples:{mainBeforeMute:dry,mainAfterMute:zero(dry)}} +]}); +test('canonical native WebView trace has exact ACK/full snapshot and no fake live',()=>{ + assert.equal(checkTrace(trace()).provenance,'SYNTHETIC'); + const a=trace();a.events[3]=a.events[4]; + assert.throws(()=>checkTrace(a),/fresh snapshot required/); + const b=trace();b.events[6].payload.graph.channels[0].id='50'; + assert.throws(()=>checkTrace(b),/rejected intent mutated/); + const c=trace();c.events[1].payload.requestId='1'; + assert.throws(()=>checkTrace(c),/session-scoped opaque requestId/); + const armedM4=trace(); + for(const item of armedM4.events){ + if(item.event==='arMixConsoleSnapshot'){ + item.payload.device.outputArmed=true; + item.payload.legacyM4={routeAccepted:true,routingRevision:'17'}; + } + } + const legacyResult=checkTrace(armedM4); + assert.equal(legacyResult.hardwareCertified,false); + assert.equal(legacyResult.productionCallbackCertified,false); +}); +test('uint64 overflow, JS numeric revision, fake stereo pin and absent capability reject',()=>{ + const a=trace();a.events[0].payload.graph.channels[0].id='18446744073709551616'; + assert.throws(()=>checkTrace(a),/uint64 overflow/); + const b=trace();b.events[1].payload.baseGraphRevision=2; + assert.throws(()=>checkTrace(b),/decimal-string uint64/); + const c=trace();c.events[0].payload.graph.channels[0].source.physicalPins=[0,0]; + assert.throws(()=>checkTrace(c),/duplicate L\/R physical stereo/); + const d=trace();d.events[0].payload.graph.channels.push({id:'101',role:'GROUP'}); + assert.throws(()=>checkTrace(d),/GROUP without native capability/); +}); +test('duplicate/replayed request, stale device, graph and roster, unsupported op',()=>{ + const a=trace();a.events[4].payload.requestId='webview-session:1'; + a.events[5].payload.requestId='webview-session:1'; + assert.throws(()=>checkTrace(a),/session-scoped opaque requestId/); + const b=trace();b.events[1].payload.deviceEpoch='70'; + assert.throws(()=>checkTrace(b),/stale epoch\/graph\/roster/); + const c=trace();c.events[1].payload.baseRosterRevision='4'; + assert.throws(()=>checkTrace(c),/stale epoch\/graph\/roster/); + const d=trace();d.events[1].payload.operation='CREATE_CHANNEL'; + assert.throws(()=>checkTrace(d),/unsupported native operation/); + const e=trace();e.events[2].payload.rosterRevision='6'; + assert.throws(()=>checkTrace(e),/ACK needs matching fresh snapshot/); +}); +test('independent sparse native routing IN1->CH7 / IN2->CH2 and non-silent evidence',()=>{ + assert.equal(checkPcm(pcm()).pcmCases,4); + const a=pcm();a.cases[0].samples.ch7=a.cases[0].samples.input2;assert.throws(()=>checkPcm(a),/IN1->CH7/); + const b=pcm();b.cases[0].samples.input1=zero(b.cases[0].samples.input1);assert.throws(()=>checkPcm(b),/silent PCM/); +}); +test('Group serial, FX Return wet parallel, no doubled dry and return mute',()=>{ + const a=pcm();a.cases[1].samples.main=dry.map((x,i)=>x+grp[i]+wet[i]);assert.throws(()=>checkPcm(a),/double-dry/); + const b=pcm();b.cases[1].samples.wetReturn=dry;assert.throws(()=>checkPcm(b),/duplicate dry PCM/); + const c=pcm();c.cases[1].samples.returnMutedMain=zero(grp);assert.throws(()=>checkPcm(c),/FX Return muted retains/); +}); +test('MONITOR distinct device destination and independent mute; MASTER silence',()=>{ + const a=pcm();a.cases[2].monitorDestination='hp0/1';assert.throws(()=>checkPcm(a),/distinct destination/); + const b=pcm();b.cases[2].samples.mainAfterMonitorMute=zero(dry);assert.throws(()=>checkPcm(b),/cannot change MAIN/); + const c=pcm();c.cases[3].samples.mainAfterMute=dry;assert.throws(()=>checkPcm(c),/MASTER mute/); +}); +test('exact-source full native evidence rejects forged digest, mock PCM, missing live roles and 0FX report',()=>{ + const dir=mkdtempSync(join(tmpdir(),'arsonmix-fat-')); + try { + const sha='a'.repeat(40); + const hashBytes=data=>createHash('sha256').update(data).digest('hex'); + const persist=(file,data)=>{ + const bytes=Buffer.isBuffer(data)?data:Buffer.from(typeof data==='string'?data:JSON.stringify(data)); + writeFileSync(join(dir,file),bytes); + return hashBytes(bytes); + }; + const exeHash=persist('console.exe','EXE FIXTURE ONLY'); + persist('BUILD_PROVENANCE.json',{ + sourceCommit:sha,executable:'console.exe',exeSha256:exeHash, + fatStatus:'EXPERIMENTAL_NOT_HARDWARE_QUALIFIED', + peMachine:'AMD64 (0x8664)',peSubsystem:'WINDOWS_GUI (2)', + webView2LoaderMode:'JUCE_WEBVIEW2_LOADER_STATIC_LINKED_V1'}); + const traceFixture=trace(); + traceFixture.provenance={kind:'NATIVE_JUCE',sourceSha:sha,producer:'JUCE_WEBVIEW'}; + const liveCaps={ + callbackOwnsChannelIds:true,fullVendorFxMigration:true, + showAndOutputParity:true,physicalCaptureMapped:true,dynamicChannels:true, + groups:true,fxReturns:true,monitor:true, + supportedOps:['SET_FADER','SET_SOURCE']}; + const channels=Array.from({length:11},(_,i)=>({ + id:String(i+1),role:'INPUT',source:{physicalPins:[i%2]}})); + channels.push(...[ + {id:'50',role:'GROUP'}, {id:'51',role:'FX_RETURN'}, + {id:'52',role:'MONITOR'}, {id:'53',role:'MAIN'}]); + for(const item of traceFixture.events){ + if(item.event!=='arMixConsoleSnapshot')continue; + item.payload.productionCallbackLive=true; + item.payload.device.outputArmed=true; + item.payload.graph.capabilities=liveCaps; + item.payload.graph.channels=channels; + item.payload.telemetry={ + rawCapturePresent:true,mainPcmPresent:true,monitorPcmPresent:true}; + } + const pcmFixture=pcm(); + pcmFixture.provenance={kind:'NATIVE_JUCE',sourceSha:sha,producer:'JUCE_CALLBACK'}; + const archiveHash=persist('release.zip',Buffer.from('PK\x03\x04synthetic-zip-header-only')); + const traceHash=persist('trace.json',traceFixture); + const pcmHash=persist('pcm.json',pcmFixture); + const reportHash=persist('audio-report.txt','SYNTHETIC HARDWARE QA TEST FIXTURE — NOT AUDIO CERTIFICATION'); + const record={ + sourceSha:sha,exeSha256:exeHash, + nativeCI:{sourceSha:sha,conclusion:'success',url:'https://github.com/masarray/arsonmix/actions/runs/123'}, + chromiumCI:{sourceSha:sha,conclusion:'success',url:'https://github.com/masarray/arsonmix/actions/runs/124'}, + nativeCTest:'PASS',chromiumPlaywright:'PASS',windowsVerifier:'PASS', + artifactSha256:archiveHash,traceSha256:traceHash,pcmSha256:pcmHash, + artifacts:{zip:'release.zip',nativeTrace:'trace.json',nativePcm:'pcm.json', + hardwareReport:'audio-report.txt'}, + hardware:{issue:15,status:'PENDING_HUMAN_REVIEW',wired:true, + backend:'ASIO',sampleRate:48000,bufferFrames:480,inputPins:[0,1], + outputPins:[0,1],testDurationSeconds:1800,outputOnlyTone:'RECORDED', + captureOnly:'RECORDED',dry0Fx:'RECORDED', + fullReportSha256:reportHash,verifiedHumanWitness:true,witnessId:'qa1'} + }; + // Even a fully structural synthetic test fixture never sets certified=true. + const accepted=checkRelease(record,dir); + assert.equal(accepted.certified,false); + assert.equal(accepted.evidenceFilesHashed,4); + assert.equal(accepted.pcmCases,4); + const wrongSha=copy(record); + wrongSha.chromiumCI.sourceSha='b'.repeat(40); + assert.throws(()=>checkRelease(wrongSha,dir),/Chromium CI/); + const tampered=copy(record); + tampered.artifactSha256='f'.repeat(64); + assert.throws(()=>checkRelease(tampered,dir),/release ZIP: actual file SHA-256 mismatch/); + const tamperedHardware=copy(record); + tamperedHardware.hardware.fullReportSha256='f'.repeat(64); + assert.throws(()=>checkRelease(tamperedHardware,dir),/release hardware report: actual file SHA-256 mismatch/); + const syntheticTrace=copy(traceFixture); + syntheticTrace.provenance.kind='SYNTHETIC'; + const syntheticTraceHash=persist('trace.json',syntheticTrace); + const fromFake=copy(record); + fromFake.traceSha256=syntheticTraceHash; + assert.throws(()=>checkRelease(fromFake,dir),/native WebView producer evidence required/); + persist('trace.json',traceFixture); + const syntheticPcm=copy(pcmFixture); + syntheticPcm.provenance.kind='SYNTHETIC'; + const syntheticPcmHash=persist('pcm.json',syntheticPcm); + const fakePcm=copy(record); + fakePcm.pcmSha256=syntheticPcmHash; + assert.throws(()=>checkRelease(fakePcm,dir),/actual JUCE callback PCM provenance required/); + persist('pcm.json',pcmFixture); + const missingRole=copy(traceFixture); + for(const e of missingRole.events) + if(e.event==='arMixConsoleSnapshot') + e.payload.graph.channels=e.payload.graph.channels.filter(ch=>ch.role!=='FX_RETURN'); + const missingRoleHash=persist('trace.json',missingRole); + const noGroup=copy(record); + noGroup.traceSha256=missingRoleHash; + assert.throws(()=>checkRelease(noGroup,dir),/missing live FX_RETURN channel/); + persist('trace.json',traceFixture); + const shorter=copy(record); + shorter.hardware.testDurationSeconds=1799; + assert.throws(()=>checkRelease(shorter,dir),/30min/); + const missingWitness=copy(record); + missingWitness.hardware.verifiedHumanWitness=false; + assert.throws(()=>checkRelease(missingWitness,dir),/human witness/); + const pathTraversal=copy(record); + pathTraversal.artifacts.zip='../release.zip'; + assert.throws(()=>checkRelease(pathTraversal,dir),/safe basename/); + }finally {rmSync(dir,{recursive:true,force:true})} +}); + +// S0 unit fixture uses the ONE shared PR #279 synthetic file, never native evidence. +import {verifyNativeS0} from '../scripts/run_console_native_s0.mjs'; +test('S0 shared v8 contract rejects absent native pins, fake ACK and mutated graph',()=>{ + const f=JSON.parse(readFileSync('integration/console-v6/fixtures.json','utf8')); + assert.equal(f.provenance,'SYNTHETIC_CONTRACT_ONLY_NOT_HARDWARE'); + const s=copy(f.g0),i={...copy(f.intent),targetChannelId:null, + deviceEpoch:s.device.epoch,baseGraphRevision:s.graph.revision, + baseRosterRevision:s.graph.rosterRevision}; + const a={...copy(f.ack),requestId:i.requestId,deviceEpoch:s.device.epoch, + graphRevision:s.graph.revision,rosterRevision:s.graph.rosterRevision, + status:'REJECTED',errorCode:'UNIVERSAL_CALLBACK_NOT_READY'}; + const ev=[{event:'arMixConsoleSnapshot',payload:s}, + {event:'arMixConsoleIntent',payload:i}, + {event:'arMixConsoleAck',payload:a}, + {event:'arMixConsoleSnapshot',payload:copy(s)}]; + assert.equal(verifyNativeS0(ev).callbackPcmProven,false); + const bad=copy(ev);delete bad[0].payload.device.enabledInputs; + assert.throws(()=>verifyNativeS0(bad),/array required|enabledInputs/); + const fake=copy(ev);fake[2].payload.status='ACCEPTED'; + assert.throws(()=>verifyNativeS0(fake),/native ACK must reject/); + const rollback=copy(ev);rollback[3].payload.device.outputArmed=true; + assert.throws(()=>verifyNativeS0(rollback),/changed accepted graph/); +}); + +// S0 regression: a portable fixture binary that ignores argv must NEVER +// masquerade as JUCE's native WebView producer or grant product acceptance. +import {assertExplicitS0Exporter} from '../scripts/run_console_native_s0.mjs'; +test('native S0 exporter must deliberately reject unknown CLI, not crash/fail/ignore',()=>{ + assert.throws(()=>assertExplicitS0Exporter('/fake/fixture', + ()=>Buffer.from('{"events":[]}')), + /C\+\+ binary ignored unknown flag/); + let calls=0; + assert.doesNotThrow(()=>assertExplicitS0Exporter('/fake/native',()=>{ + calls++; + const e=new Error('unsupported CLI'); + e.status=64;e.stderr=Buffer.from('ARSONMIX_S0_UNSUPPORTED_ARGUMENT'); + throw e; + })); + assert.equal(calls,1); + for(const failure of [ + {status:3221226505,stderr:Buffer.from('Assertion failed')}, + {code:'ENOENT'}, + {status:2,stderr:Buffer.from('unrelated failed CTest')}, + {code:'ETIMEDOUT'} + ]){ + assert.throws(()=>assertExplicitS0Exporter('/fake/crash',()=>{ + const e=new Error('failed native process');Object.assign(e,failure);throw e; + }),/probe crashed, failed to execute, or lacked explicit rejection marker/); + } +}); + + + +// Source-only phase gate must NEVER call portable golden/live M4 a universal +// callback or a product. Not an alternative schema implementation. +import {inspectPuzzleSources} from '../scripts/check_console_puzzle.mjs'; +test('shared #279 release preflight blocks even a source with working M4 controls if universal callback remains UNREADY',()=>{ + const src={ + native:'PuzzleV8Wire::snapshot(w) PuzzleV8Wire::ack(ack) w.inputs.push_back(...) w.outputs.push_back(...) w.productionCallbackLive=false; engine.switchDryRoutingLabSource( engine.setDryRoutingLabParameter(', + dispatcher:'arMixConsoleSnapshot arMixConsoleIntent arMixConsoleAck processProductionIntent', + cxxFixture:'PuzzleV8Wire::fixture(snapshot,ack)', + gui:'arMixConsoleAck arMixConsoleSnapshot arMixConsoleIntent baseGraphRevision baseRosterRevision enabledInputs enabledOutputs productionCallbackLive===true supportedOps', + guiTest:'console-v8-native-unready.json '+ 'a'.repeat(64), + portableGolden:'fixture-only', + nativeRunner:'assertExplicitS0Exporter puzzle-seam.mjs', + nativeProof:'runActualNativeS0 actual.equals(expected)', + nativeSource:'bool process(', + fat:'enabledInputs enabledOutputs', + fatTest:'integration/console-v6/fixtures.json', + machine:'"schemaVersion" "requiredSnapshotFields" "intentRequired" "ackRequired"' + }; + const got=inspectPuzzleSources(src,'a'.repeat(64)); + assert.equal(got.portableFixtureMatch,true); + assert.equal(got.stage,'S0_NATIVE_PRODUCER_BLOCKED'); + assert.equal(got.productCertified,false); + assert.equal(got.actualCallbackPCMVerified,false); + assert.ok(got.releaseSourceBlockers.includes('S0_EXPLICIT_JUCE_EXPORTER')); + assert.ok(got.releaseSourceBlockers.includes('G2_FULL_UNIVERSAL_CALLBACK')); + const real=structuredClone(src); + real.nativeTest='if(argc==2 && std::string(argv[1])=="--emit-console-s0-json"){'+ + 'std::cout<{ + const reference='
'; + const js="root.id='arV6Console' main.id='arV6Main'"+ + "selectField('IN','SET_SOURCE' selectField('OUT','SET_PRIMARY_OUT' "+ + "fxSection(ch) sendSection(ch) arMixConsoleAck arMixConsoleSnapshot "+ + "supportedOps productionCallbackLive===true paintPan( --v6-pan-start 'SET_CUE' "+ + "button('LINK FADERS' button('ROUTE TO GROUP BUS' arV6PluginPanel "+ + "arV6QuickPanel Search native scanned plugins"; + const css='#app{--am-metal-panel:#14232C}#app .arV6Strip{background:#123}'+ + '#app .arV6Main{width:178px}#app .arV6Top{background:#456}'+ + '#app .arV6StripHead{color:white}#app .arV6StripStatus{color:white}'; + const r=inspectPr278({reference,js,css,legacy:'channelIcons= channelPalette=', + test:'console-v8-native-unready.json arMixConsoleAck'}); + for(const id of ['TOP_BOTTOM_COLOR_ICON','ONE_GRAPHITE_CHASSIS', + // V5 replaced the obsolete BTN180_HEADER predicate: require that the + // newer hardware key actually provides its JS owner AND native CSS skin. + 'V5_HEADER_KEYS','PINNED_MAIN_EQUAL_WIDTH','V8_DENSITY_AWARE_BANK','V8_TRUE_SECTION_COLLAPSE']) + assert.ok(r.blocked.some(c=>c.id===id),id+' must not pass'); + assert.equal(r.audioCertified,false); + for(const id of ['REFERENCE_278','DIRECT_NATIVE_IO','LINK_VS_GROUP','NATIVE_ACK_NO_DEMO']) + assert.ok(r.checks.some(c=>c.id===id&&c.pass),id+' valid path lost'); + assert.ok(inspectPr278({js,css}).blocked.some(c=>c.id==='REFERENCE_278')); +}); + +test('GUI-final source authority rejects obsolete BTN-180 and qualifies V5 native header only with full skin',()=>{ + const mock={js:"const tools=h('div','arV6Tools');",hardware: + "['#app .arV6Console .arV6Top .arV6Button'\nclassList.add('mx-hw-key'", + hardwareCss:'#app button.mx-hw-key { } svg.mx-hw-face { }'}; + const pick=x=>inspectPr278(x).checks.find(c=>c.id==='V5_HEADER_KEYS').pass; + assert.equal(pick(mock),true,'native header uses approved V5 renderer'); + assert.equal(pick({...mock,hardwareCss:''}),false,'missing skin must block release'); + assert.equal(pick({...mock,hardware:''}),false,'legacy header cannot pass without upgrade'); + const css=[ + '--am-metal-panel:#14232C', + '#app .arV6Console .arV6Strip,{background:var(--am-metal-panel);width:var(--v6-channel-w)}', + '#app .arV6Console .arV6Main,{width:var(--v6-channel-w)}', + '#app .arV6Console .arV6Top{background:var(--am-metal-panel)}', + '#app .arV6Console .arV6StripHead{border-color:var(--ch)}', + '#app .arV6Console .arV6StripStatus{border-color:var(--ch)}' + ].join('\n'); + const body=inspectPr278({...mock,css,js:mock.js+ + "elStrip.style.setProperty('--ch'; ch.icon; DENSITY_WIDTH comfort standard compact"}); + for(const name of ['ONE_GRAPHITE_CHASSIS','PINNED_MAIN_EQUAL_WIDTH','TOP_BOTTOM_COLOR_ICON']) + assert.equal(body.checks.find(x=>x.id===name).pass,true,name); +}); diff --git a/tests/dedicated_aux_bus_test.cpp b/tests/dedicated_aux_bus_test.cpp index c1f7899e3..309d080c5 100644 --- a/tests/dedicated_aux_bus_test.cpp +++ b/tests/dedicated_aux_bus_test.cpp @@ -75,6 +75,25 @@ int main(){ assert(near(meters.auxPeak[0],auxA)); // after bus gain 0.5 assert(near(meters.auxPeak[1],auxB)); assert(near(meters.channelPeak[9],.1f*std::sqrt(.5f))); + // This is real PRE/POST native PCM, never a JS send simulation. + // A 64-frame gain ramp must not collapse to an 8-frame hard step. + assert(block.setAuxSendGain(0,0,SendTap::preFader,0.f)); + assert(block.setAuxSendGain(9,1,SendTap::postFader,0.f)); + assert(!block.setAuxSendGain(9,0,SendTap::postFader,0.f)); // edge absent + const auto beforeSendAutomation=allocations.load(std::memory_order_relaxed); + for(int cycle=0;cycle<8;++cycle) + assert(block.process(input.data(),stripCount,outL.data(),outR.data(), + frames,effects,&meters)); + assert(allocations.load(std::memory_order_relaxed)==beforeSendAutomation); + assert(near(outL[7],direct)&&near(outR[7],direct)); + assert(near(block.auxSendGain(0,0,SendTap::preFader),0.f)); + assert(near(block.auxSendGain(9,1,SendTap::postFader),0.f)); + assert(block.setAuxSendGain(0,0,SendTap::preFader,.5f)); + assert(block.setAuxSendGain(9,1,SendTap::postFader,.25f)); + for(int cycle=0;cycle<8;++cycle) + assert(block.process(input.data(),stripCount,outL.data(),outR.data(), + frames,effects,&meters)); + assert(near(outL[7],direct+auxA+auxB)); // Shared stereo AUX receives an explicitly left-panned mono PRE send. // The right output must not inherit phantom mono power. @@ -208,6 +227,27 @@ int main(){ assert(near(monL[f],.4f*monoCenter*.75f)); assert(near(monR[f],.4f*monoCenter*.75f)); } + // Native MONITOR targets move independent of MAIN, and their ramp + // follows AUDIO samples across eight 8-frame callbacks. + std::array,stripCount+auxBusCount> liveMonitor{}; + for(int i=0;i #if defined(NDEBUG) #undef NDEBUG // Native Release CTest must actually run assertions. @@ -26,7 +27,116 @@ static ChannelEdit send(ChannelId from,ChannelId to,float gain,bool pre=false) { ChannelEdit e;e.kind=ChannelEdit::Kind::addSendReference; e.id=from;e.target=to;e.value=gain;e.preFader=pre;return e; } + +static void verifyRealtimeSlewAndNativeChannelIdContinuousControls() { + using armix::dsp::RealtimeSlew64; + // Sub-64 variable callbacks must not finish a 64-sample gesture in 4 + // frames. Coalescing multiple UI writes before a read keeps latest goal. + RealtimeSlew64 s; + s.reset(1.f); + s.retarget(.2f); + s.retarget(.5f); // replaces the old unrendered target; no queue buildup + for(int i=0;i<4;++i)s.next(); + assert(near(s.current,1.f-(.5f*4.f/64.f))); + for(int i=0;i<16;++i)s.next(); + assert(near(s.current,1.f-(.5f*20.f/64.f))); + for(int i=0;i<32;++i)s.next(); + assert(near(s.current,1.f-(.5f*52.f/64.f))); + for(int i=0;i<12;++i)s.next(); + assert(s.remaining==0 && s.current==.5f); + s.retarget(0.f); + for(int i=0;i<20;++i)s.next(); + const float applied=s.current; + s.retarget(.75f); // reverse while in flight; no jump on target update + assert(s.current==applied); + assert(s.next()>applied); + for(int i=1;i<64;++i)s.next(); + assert(s.current==.75f && s.remaining==0); + + // The approved GUI sends ChannelId-keyed realtime moves. Verify actual + // PCM through GROUP-compatible Main, PRE wet Return and POST Monitor, + // not a disconnected smoothing helper or browser-only fixture. + DynamicAcceptedSession session; + constexpr std::uint64_t epoch=9401; + DynamicGraphRequest route; + route.physicalInputs=1; + route.maxFrames=64; + std::array creates{ + add(0,ChannelRole::input,"VOICE"), + add(1,ChannelRole::fxReturn,"WET",ProcessingFormat::stereo), + add(2,ChannelRole::main,"MAIN",ProcessingFormat::stereo), + add(3,ChannelRole::monitor,"CUE",ProcessingFormat::stereo) + }; + auto a=session.edit(0,0,creates,route,epoch,epoch,true); + assert(a.ok()); + const auto voice=a.edit.createdIds[0]; + const auto wet=a.edit.createdIds[1]; + const auto main=a.edit.createdIds[2]; + const auto cue=a.edit.createdIds[3]; + std::array links{ + output(voice,main), + output(wet,main), + send(voice,wet,.5f,true), + send(voice,cue,.5f,false) + }; + route.sources={{voice,0,-1,false}}; + a=session.edit(1,1,links,route,epoch,epoch,true); + assert(a.ok()&&session.acceptedGraphRevision()==2); + std::array input{},outL{},outR{},cueL{},cueR{}; + input.fill(.5f); + const float* pins[]{input.data()}; + const auto fx=+[](ChannelId,float*,float*,int) noexcept {}; + const auto render=[&](int n) { + return session.render(epoch,pins,1,outL.data(),outR.data(),n, + false,fx,cueL.data(),cueR.data()); + }; + assert(render(64)); + const float initialMain=outL[63]; + const float initialCue=cueL[63]; + assert(initialMain>.1f && initialCue>.01f); + assert(session.setLiveMix(epoch,2,voice,0.f,0.f)); + assert(session.setLiveParallelSend(epoch,2,voice,wet,true,0.f)); + assert(session.setLiveParallelSend(epoch,2,voice,cue,false,0.f)); + // PRE send, POST send and channel fader must all advance across + // 4+16+32+12 (one complete ramp), not finish on the FIRST 4 samples. + assert(render(4)); + const float after4=outL[3],cue4=cueL[3]; + assert(after4>0.f && after40.f && cue40.f && after200.f && cue200.f); + assert(render(60)); + constexpr float center=.7071067811865475f; + assert(near(outL[59],.5f*.8f*center,0.0001f)); + assert(!session.setLiveMix(epoch,1,voice,1.f,0.f)); + assert(!session.setLiveParallelSend(epoch-1,2,voice,wet,true,1.f)); + assert(session.acceptedGraphRevision()==2); + session.unpublish(); + session.pollRetirement(); +} + int main() { + verifyRealtimeSlewAndNativeChannelIdContinuousControls(); constexpr std::uint64_t epoch=77; constexpr float center=.7071067811865475f; DynamicAcceptedSession session; @@ -56,13 +166,104 @@ int main() { const float gain=id==group?2.f:id==fx?.5f:1.f; for(int i=0;i(.2f+.4f)*center && l[3]<(.4f+.4f)*center); + assert(render(16)&&render(32)&&render(12)); + assert(near(l[11],(.4f+.4f)*center)); + assert(near(ml[11],(.4f*.2f+.4f*.25f)*center)); + // A last-target-wins reverse retains the same PCM and plugin graph. + assert(session.setLivePhysicalSource(epoch,2,micA,0,-1,false)); + assert(render()); + assert(near(l[63],(.2f+.4f)*center)); + assert(near(ml[63],(.2f*.2f+.4f*.25f)*center)); + assert(session.acceptedGraphRevision()==2); + // E1: structural draft pins are preflighted BEFORE accepted SOURCE + // reconciliation. Out-of-range or same-pin stereo must not be hidden by + // an earlier valid MONO source, falsely ACKed, or silence existing PCM. + ChannelEdit renameAttempt; + renameAttempt.kind=ChannelEdit::Kind::rename; + renameAttempt.id=micA; + renameAttempt.text="MUST_NOT_APPEAR_AFTER_REJECTION"; + const std::array structuralAttempt{renameAttempt}; + auto invalidSource=route; + invalidSource.sources[0].inputL=2; // exactly physicalInputs + auto deniedSource=session.edit(2,2,structuralAttempt,invalidSource,epoch,epoch,true); + assert(!deniedSource.ok()); + assert(deniedSource.fault==DynamicAcceptedSession::Fault::graphRejected); + assert(deniedSource.native.fault==DynamicNativeSessionPublisher::Fault::invalidGraph); + assert(deniedSource.native.graphError.fault==DynamicGraphFault::invalidSource); + assert(deniedSource.edit.createdIds.empty()); + assert(session.acceptedGraphRevision()==2); + assert(session.acceptedRosterRevision()==2); + assert(session.acceptedRoster().find(micA)->name=="LEAD"); + assert(session.acceptedPhysicalRequest().sources[0].inputL==0); + invalidSource=route; + invalidSource.sources[0].stereo=true; + invalidSource.sources[0].inputR=0; + deniedSource=session.edit(2,2,structuralAttempt,invalidSource,epoch,epoch,true); + assert(!deniedSource.ok() && + deniedSource.native.graphError.fault==DynamicGraphFault::invalidSource); + assert(render()&&near(l[63],(.2f+.4f)*center)); + // A physically valid but different pin is NOT an implicit IN request + // during RENAME/GROUP/OUT. Previously the old SOURCE was overlaid and + // an unfulfilled new pin was ACKed as successful (GUI/PCM disagreement). + auto validButUnacceptedSource=route; + validButUnacceptedSource.sources[0].inputL=1; + auto deniedValidSource=session.edit(2,2,structuralAttempt, + validButUnacceptedSource,epoch,epoch,true); + assert(!deniedValidSource.ok() && + deniedValidSource.fault==DynamicAcceptedSession::Fault::graphRejected); + assert(deniedValidSource.native.graphError.fault== + DynamicGraphFault::invalidSource); + assert(deniedValidSource.native.graphError.id==micA); + assert(session.acceptedGraphRevision()==2 && + session.acceptedPhysicalRequest().sources[0].inputL==0); + assert(session.acceptedRoster().find(micA)->name=="LEAD"); + assert(render()&&near(l[63],(.2f+.4f)*center)); + // One accepted ChannelId graph: realtime MUTE/SOLO and PRE/POST follow + // the same callback, not a recompilation or an extra FX instance. + assert(session.setLiveMuteSolo(epoch,2,micA,true,false)); + assert(session.acceptedRoster().find(micA)->mute); + assert(render(4)); + assert(l[3]>.4f*center && l[3]<.6f*center); + assert(render(16)&&render(32)&&render(12)); + assert(near(l[11],.4f*center)); + assert(near(ml[11],(.4f*.25f)*center)); + assert(session.setLiveMuteSolo(epoch,2,micA,false,true)); + assert(render()); + assert(near(l[63],.2f*center)); + assert(near(ml[63],(.2f*.2f)*center)); + assert(session.setLiveMuteSolo(epoch,2,main,true,false)); + assert(render()); + assert(near(l[63],0.f)&&near(r[63],0.f)); + assert(near(ml[63],(.2f*.2f)*center)); // independent MONITOR + assert(session.setLiveMuteSolo(epoch,2,main,false,false)); + assert(session.setLiveMuteSolo(epoch,2,micA,false,false)); + assert(render()); + assert(near(l[63],(.2f+.4f)*center)); + assert(near(ml[63],(.2f*.2f+.4f*.25f)*center)); + assert(!session.setLiveMuteSolo(epoch-1,2,micA,true,false)); + assert(!session.setLiveMuteSolo(epoch,1,micA,true,false)); + assert(!session.setLiveMuteSolo(epoch,2,ChannelId{987654},true,false)); + assert(!session.acceptedRoster().find(micA)->mute&& + !session.acceptedRoster().find(micA)->solo&& + session.acceptedGraphRevision()==2); // Control update is a real RT atomic, but is ALSO preserved by roster so // subsequent BUS compilation cannot silently reset fader/send gain. assert(session.setLiveMix(epoch,2,micA,.5f,0.f)); diff --git a/tests/engine_runtime_reconciliation_test.mjs b/tests/engine_runtime_reconciliation_test.mjs new file mode 100644 index 000000000..c251048d2 --- /dev/null +++ b/tests/engine_runtime_reconciliation_test.mjs @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Fast G0 architecture gate. Tests the INSTALLED owner (M4 compatibility) +// without pretending that the prepared ChannelId graph is live. +// When ChannelId cutover is actually approved, this gate MUST change in +// the same exact-SHA integration commit as the JUCE callback and native ACK. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; + +const read=p=>readFileSync(p,'utf8'); +const engine=read('src/LiveAudioEngine.h'); +const host=read('src/Main.cpp'); +const cmake=read('CMakeLists.txt'); +const authority=read('engine/core/NativeRenderAuthority.h'); +const bridge=read('src/ConsoleLiveBridgeV6.h'); +const wire=read('engine/core/ConsolePuzzleV8Wire.h'); +const schema=JSON.parse(read('contracts/console-puzzle-v8.json')); +const worker=read('src/NativeShowSaveWorker.h'); +const physical=read('src/LiveDryRoutingLab.h'); +const dynamic=read('engine/core/DynamicNativeSessionPublisher.h'); +const realtimePermit=read('engine/core/RealtimeRenderPermit.h'); +const start=engine.indexOf('void audioDeviceIOCallbackWithContext ('); +assert.ok(start>0,'missing ONE JUCE production callback'); +const callback=engine.slice(start); +const count=(s,pattern)=>[...s.matchAll(pattern)].length; + +test('exactly one production audio callback and one native PCM owner',()=>{ + assert.equal(count(engine,/void audioDeviceIOCallbackWithContext\s*\(/g),1); + assert.equal(count(host,/LiveAudioEngine engine_;/g),1); + assert.match(engine,/#include "\.\.\/engine\/core\/NativeRenderAuthority\.h"/); + assert.match(callback,/NativeRenderAuthority::select\(/); + assert.match(callback,/NativeRenderOwner::failSilentUnpatched/); + assert.match(callback,/NativeRenderOwner::acceptedM4Session/); + assert.equal(count(callback,/dryRoutingLab_\.process\(/g),1, + 'two native M4 PCM renders would double-sum or double-process vendor FX'); + assert.doesNotMatch(callback,/DynamicNativeSessionPublisher|DynamicAcceptedSession|\.publisher_\.render\(/, + 'unadmitted universal graph must never run alongside real M4 callback'); + assert.match(authority,/acceptedM4Session/); + assert.match(authority,/isolatedDiagnostic/); +}); + +test('unpatched is silent and diagnostic path cannot host a legacy second VST engine',()=>{ + const unpatched=callback.indexOf('NativeRenderOwner::failSilentUnpatched'); + const routed=callback.indexOf('NativeRenderOwner::acceptedM4Session'); + const isolated=callback.indexOf('// The only remaining stereo renderer is DIAGNOSTIC'); + const finish=callback.indexOf('const auto elapsedUs = clockMicros() - beginUs',isolated); + assert.ok(unpatched>=0&&routed>unpatched&&isolated>routed&&finish>isolated); + const first=callback.slice(unpatched,routed); + assert.match(first,/FloatVectorOperations::clear\(outputs\[c\], samples\)/); + assert.match(first,/handoff_\.endCycle\(cycle\)/, + 'plugin owner must still retire on the CONTROL thread when unpatched'); + const tail=callback.slice(isolated,finish); + assert.doesNotMatch(tail,/processor->processBlock|MidiBuffer midi|createPluginInstance|prepareToPlay/, + 'do not revive a hidden stereo plugin engine in diagnostic fallback'); + assert.match(tail,/diagnosticTone_\.next/); +}); + +test('original CH1 vendor FX/Orbit is leased exactly once in accepted M4 renderer',()=>{ + const old=engine.indexOf('static void renderOriginalChannelOneGraph('); + const end=engine.indexOf('void audioDeviceIOCallbackWithContext',old); + assert.ok(old>=0&&end>old); + const fx=engine.slice(old,end); + assert.match(fx,/slot\.processor->processBlock\(buffer,midi\)/); + assert.match(fx,/bypass\.request\(graph\.bypassFlags/); + assert.match(fx,/catch\(\.\.\.\)/); + assert.match(callback,/LegacyChannelOneLease ch1Lease\{cycle\.graph\}/); + assert.match(callback,/&processLegacyChannelOne/); + assert.doesNotMatch(callback,/std::make_unique<|std::make_shared<|createPluginInstance\(/, + 'no FX instantiation or graph allocation in device callback'); +}); + +test('occupied CH1 Orbit uses one strong Graph lease through native renderer and Show handoff',()=>{ + assert.match(engine,/std::shared_ptr graphOwned_\s*\{std::make_shared\(\)\}/); + assert.match(engine,/std::shared_ptr stagedOwner_/); + assert.match(engine,/fx\.owner=std::static_pointer_cast\(graphOwned_\)/); + assert.match(engine,/fx\.context=graphOwned_\.get\(\)/); + assert.match(engine,/fx\.render=&processOwnedChannelOne/); + assert.match(engine,/renderOriginalChannelOneGraph\(\s*\*static_cast\(token\)/); + assert.match(engine,/Graph\(\) \{ dryScratch\.setSize\(2,maxFrames,false,true,false\); \}/); + assert.match(engine,/graph\.dryScratch\.getWritePointer\(0\)/); + assert.match(engine,/graph\.orderPacked\.load\(std::memory_order_acquire\)/); + assert.match(engine,/dryRoutingLab_\.revokeChannelIdPcm\(\)/); + assert.equal(count(engine,/dryRoutingLab_\.revokeChannelIdPcm\(\)/g),2, + 'both Show recall and original CH1 ADD/REMOVE must revoke native renderer'); + assert.match(physical,/occupiedExternalCh1Fx>0,hw/); + assert.match(physical,/nativePublisher_,nativeAccepted_,std::move\(externalCh1\)/); + assert.match(physical,/channelIdPcmEpoch_\.store\(0,std::memory_order_release\)/); + assert.equal(count(engine,/void audioDeviceIOCallbackWithContext\s*\(/g),1); +}); + +test('shipping application does not compile a second test-only native mixer',()=>{ + const app=cmake.split(/\r?\n/).find(l=>l.startsWith('target_sources(ARMixConsole PRIVATE')); + assert.ok(app,'native JUCE application source list missing'); + assert.match(app,/src\/LiveAudioEngine\.h/); + assert.match(app,/engine\/core\/NativeRenderAuthority\.h/); + assert.doesNotMatch(app,/PreparedNativeMixerSession|DynamicNativeSessionPublisher|DynamicPreparedMixerBlock|UnifiedLegacyProductionAdmission|LegacyLiveGraphMigration/, + 'prepared graph may be compiled as tests/includes, not advertised as a second application entry point'); + assert.match(cmake,/target_sources\(ARMixNativeMixerSessionTests PRIVATE tests\/prepared_native_mixer_session_test\.cpp engine\/core\/PreparedNativeMixerSession\.h\)/); +}); + +test('GUI projection cannot falsely claim the prepared ChannelId engine is live',()=>{ + assert.equal(schema.schemaVersion,6); + assert.deepEqual(schema.wire.events, + ['arMixConsoleSubscribe','arMixConsoleSnapshot','arMixConsoleIntent','arMixConsoleAck']); + for(const item of ['deviceEpoch','baseGraphRevision','baseRosterRevision','requestId','targetChannelId']) + assert.ok(schema.intentRequired.includes(item)); + assert.ok(bridge.includes('w.productionCallbackLive=false')); + assert.match(bridge,/legacyM4/); + assert.match(wire,/callbackOwnsChannelIds\\":false/); + assert.match(wire,/fullVendorFxMigration\\":false/); + assert.ok(wire.includes('supportedOps')); + assert.match(bridge,/parseNativeChannelId/); + assert.match(bridge,/validConsoleRequestId/); +}); + +test('workers handle Show IO outside the audio callback, not as a second DSP engine',()=>{ + assert.match(worker,/class NativeShowSaveWorker final : private juce::Thread/); + assert.match(worker,/store\.commit\(show,\{snapshot_\},blobs_\)/); + assert.match(worker,/void releaseJob\(\)/); + assert.doesNotMatch(callback,/NativeShowStore|\.loadWithStates\(|\.commit\(show/); +}); + +test('E2 uses exactly one installed JUCE callback with admitted native ChannelId PCM and M4 fallback',()=>{ + assert.match(engine,/dryRoutingLab_\.admitChannelIdFromAcceptedM4\(/); + assert.match(physical,/UnifiedLegacyProductionAdmission::compileAndCommit\(/); + assert.match(physical,/channelIdPcmEpoch_\.store\(generation,std::memory_order_release\)/); + assert.match(physical,/const bool channelIdRender=/); + assert.match(physical,/if\(channelIdRender\)\s*\{/); + assert.match(physical,/nativePublisher_\.render\(/); + assert.match(physical,/else \{\s*processed=snapshot->prepared->process\(/); + assert.equal(count(callback,/dryRoutingLab_\.process\(/g),1); + assert.equal(count(callback,/DynamicNativeSessionPublisher::render\(/g),0, + 'a second JUCE native renderer may not be installed'); + assert.match(physical,/channelIdPcmEpoch_\.store\(0,std::memory_order_release\)/, + 'stale epoch and structural edits must turn off the native selector'); + assert.match(physical,/channelIdPhysicalPcmActive\(/, + 'live GUI scalar control must follow the admitted native renderer'); + assert.match(engine,/dryRoutingLab_\.revokeChannelIdPcm\(\)/, + 'original CH1 FX publication must first retire native PCM authority'); + assert.match(physical,/nativePublisher_\.pollRetirement\(\)/, + 'native VST owner generations must retire off audio callback'); +}); + +test('installed M4 and future ChannelId share one nonblocking render permit',()=>{ + assert.ok(physical.includes('RealtimeRenderPermit exclusive{rendering_}')); + assert.ok(dynamic.includes('RealtimeRenderPermit exclusive{rendering_}')); + assert.ok(realtimePermit.includes('test_and_set(std::memory_order_acquire)')); + assert.ok(realtimePermit.includes('clear(std::memory_order_release)')); + assert.ok(!realtimePermit.includes('std::mutex') && !realtimePermit.includes('condition_variable')); + assert.ok(physical.includes('if(!exclusive)')); + assert.ok(dynamic.includes('if(!exclusive)')); +}); + +test('legacy M4 operations are advertised separately, not as fake universal ChannelIds',()=>{ + assert.ok(bridge.includes('LEGACY_M4_ORDINAL')); + assert.ok(bridge.includes('acceptedChannels')); + assert.ok(bridge.includes('route.getProperty("topologyFault",false)')); + assert.ok(bridge.includes('object->setProperty("supportedOps",juce::var(allowed))')); + assert.ok(bridge.includes('w.productionCallbackLive=false')); + assert.ok(wire.includes('supportedOps')); +}); + +test('legacy M4 GUI commands require accepted physical authority, not just guessed ordinal',()=>{ + assert.ok(bridge.includes('.getProperty("controlPlane","").toString()!="LEGACY_M4_ORDINAL"')); + assert.ok(bridge.includes('PRODUCTION_GRAPH_NOT_ADMITTED')); + assert.ok(bridge.includes('legacyRoutingRevision')); +}); diff --git a/tests/fader_asset_test.py b/tests/fader_asset_test.py index a148146be..64978bd71 100644 --- a/tests/fader_asset_test.py +++ b/tests/fader_asset_test.py @@ -58,7 +58,8 @@ assert hashlib.sha256(rose).hexdigest()=="a1d0962a25336d88a062263761d22b65ceca85d4b356e7643f1234afd6573913" assert (int.from_bytes(rose[16:20],"big"),int.from_bytes(rose[20:24],"big"))==(36,77) finish=(root/"web/styles-src/42-mixer-premium.css").read_text(encoding="utf-8") -assert css.endswith(finish), "Premium CSS module not compiled last" +hardware=(root/"web/styles-src/43-hardware-backlit.css").read_text(encoding="utf-8") +assert css.endswith(finish+hardware), "Premium fader CSS must precede isolated V5 hardware-key override" marker='--ari-master-cap:url("data:image/png;base64,' assert css.count(marker)==2, "Rose MASTER must override old gold master once" embedded=css.rsplit(marker,1)[1].split('")',1)[0] diff --git a/tests/fixtures/console-v8-native-unready.json b/tests/fixtures/console-v8-native-unready.json new file mode 100644 index 000000000..c4b3d9549 --- /dev/null +++ b/tests/fixtures/console-v8-native-unready.json @@ -0,0 +1 @@ +{"events":[{"event":"arMixConsoleSnapshot","payload":{"schemaVersion":6,"productionCallbackLive":false,"device":{"epoch":"1","backend":"","captureDevice":"","playbackDevice":"","inputEndpoints":[],"outputEndpoints":[],"enabledInputs":[],"enabledOutputs":[],"sampleRate":null,"bufferFrames":null,"outputArmed":false},"graph":{"revision":"0","rosterRevision":"0","channels":[],"destinations":[],"capabilities":{"callbackOwnsChannelIds":false,"fullVendorFxMigration":false,"showAndOutputParity":false,"physicalCaptureMapped":false,"dynamicChannels":false,"groups":false,"fxReturns":false,"monitor":false,"sendsOnFaders":false,"supportedOps":[]}},"telemetry":{"rawCapturePresent":false,"rawCapturePeak":0,"mainPcmPresent":false,"monitorPcmPresent":false,"channelMeterRmsPeak":[]},"legacyM4":{"active":false,"routeAccepted":false,"routingRevision":"0"}}},{"event":"arMixConsoleIntent","payload":{"requestId":"native-fixture-session:1","deviceEpoch":"1","baseGraphRevision":"0","baseRosterRevision":"0","operation":"SET_SOURCE","targetChannelId":null,"payload":{}}},{"event":"arMixConsoleAck","payload":{"requestId":"native-fixture-session:1","status":"REJECTED","deviceEpoch":"1","graphRevision":"0","rosterRevision":"0","errorCode":"UNIVERSAL_CALLBACK_NOT_READY"}},{"event":"arMixConsoleSnapshot","payload":{"schemaVersion":6,"productionCallbackLive":false,"device":{"epoch":"1","backend":"","captureDevice":"","playbackDevice":"","inputEndpoints":[],"outputEndpoints":[],"enabledInputs":[],"enabledOutputs":[],"sampleRate":null,"bufferFrames":null,"outputArmed":false},"graph":{"revision":"0","rosterRevision":"0","channels":[],"destinations":[],"capabilities":{"callbackOwnsChannelIds":false,"fullVendorFxMigration":false,"showAndOutputParity":false,"physicalCaptureMapped":false,"dynamicChannels":false,"groups":false,"fxReturns":false,"monitor":false,"sendsOnFaders":false,"supportedOps":[]}},"telemetry":{"rawCapturePresent":false,"rawCapturePeak":0,"mainPcmPresent":false,"monitorPcmPresent":false,"channelMeterRmsPeak":[]},"legacyM4":{"active":false,"routeAccepted":false,"routingRevision":"0"}}}]} diff --git a/tests/gui_baseline_lock_test.py b/tests/gui_baseline_lock_test.py index 0d7c31983..b0b027bfe 100644 --- a/tests/gui_baseline_lock_test.py +++ b/tests/gui_baseline_lock_test.py @@ -12,8 +12,14 @@ lock=(root/'docs/GUI_BASELINE_LOCK_2026-10-25.md').read_text(encoding='utf8') assert '343692fc9b702661a8455cca30f0ffd108907324' in lock assert 'checkpoint/gui-v0.8-approved-20261025' in lock -assert 'docs/GUI_BASELINE_LOCK_2026-10-25.md' in readme -assert 'docs/GUI_BASELINE_LOCK_2026-10-25.md' in agents +# v6 is the live execution authority; the old GUI baseline remains historic. +# The base/main README now carries the newer PR278-v5.2 console authority; +# keep the old v6 pointer valid on historical branches, but do not reject +# the superseding owner-approved design / production / release handoff. +assert ('docs/EXECUTION_LOCK_UNIVERSAL_LIVE_CONSOLE_V6_20261101.md' in readme or + ('PRIMARY ARSONMIX GUI AUTHORITY' in readme and 'PR #278' in readme and + 'GUI #271' in readme and 'PRD' in readme)) +assert 'docs/EXECUTION_LOCK_UNIVERSAL_LIVE_CONSOLE_V6_20261101.md' in agents assert "ref: fix/fader-thumb-symmetry-polish" not in page assert "branches: [main]" in page and "head_sha" in page assert "branches: [main]" in ui and "pull_request:" in ui diff --git a/tests/gui_workflow_contract_test.mjs b/tests/gui_workflow_contract_test.mjs index b515c27ed..7d638cda7 100644 --- a/tests/gui_workflow_contract_test.mjs +++ b/tests/gui_workflow_contract_test.mjs @@ -88,3 +88,6 @@ test('native 12Hz status uses one capped shared visual meter scheduler',()=>{ import './audio_capture_triage_contract_test.mjs'; // P0 #132: deterministic transactional browser snapshot regression tests. import './ui_snapshot_transaction_test.mjs'; + +// Always run PR#278 V6 production material/identity/parity gate in the existing UI suite. +import './operator_visual_identity_v6_contract_test.mjs'; diff --git a/tests/hardware_key_v5_smoke.py b/tests/hardware_key_v5_smoke.py new file mode 100644 index 000000000..9bfd2f8d0 --- /dev/null +++ b/tests/hardware_key_v5_smoke.py @@ -0,0 +1,141 @@ +"""V5 mixer hardware keys: one masked legend, semantic LEDs, native parity. +Runs against the REAL web/index.html and GENERATED offline standalone. +No DSP/audio claims: this validates UI skin and existing button handlers only. +""" +import asyncio +from pathlib import Path +from playwright.async_api import async_playwright + +ROOT=Path(__file__).resolve().parents[1] + +async def audit(page): + await page.wait_for_function("""() => !!window.ArSonMixHardwareKeys && + !!document.querySelector('[data-mute="0"] svg.mx-hw-face')""") + keys=await page.evaluate("""() => { + const read=q=>{ + const b=document.querySelector(q),s=getComputedStyle(b),p=getComputedStyle(b,'::before'); + const face=b.querySelector('svg.mx-hw-face'); + const text=face?.querySelectorAll('mask text'); + return {className:b.className,pressed:b.getAttribute('aria-pressed'), + oldSkin:b.classList.contains('btn-180'),svg:!!face, + masks:face?.querySelectorAll('mask').length, + textCount:text?.length,visualText:face?.querySelectorAll(':scope > text').length, + led:s.getPropertyValue('--mx-hw-led').trim(),gap:p.opacity, + lamp:face?getComputedStyle(face.querySelector('.mx-hw-lamp')).opacity:null, + filter:s.filter,blur:s.backdropFilter,shadow:s.boxShadow}; + }; + return {mute:read('[data-mute="0"]'),solo:read('[data-solo="0"]'), + master:read('#masterMute'),phase:read('[data-pre="0"]'), + hpf:read('[data-hpf="0"]')}; + }""") + for name,item in keys.items(): + assert not item['oldSkin'],(name,item) + assert item['svg'] and item['masks']==1 and item['textCount']==1,(name,item) + assert item['visualText']==0,(name,item) + assert item['gap']=='0' and item['lamp']=='0',(name,item) + assert item['filter']=='none' and item['blur']=='none',(name,item) + assert keys['mute']['led']=='255,64,85',keys + assert keys['solo']['led']=='255,208,44',keys + assert keys['phase']['led']=='243,164,81',keys + assert keys['hpf']['led']=='87,211,189',keys + mute=page.locator('[data-mute="0"]') + solo=page.locator('[data-solo="0"]') + await mute.hover() + assert await mute.evaluate("(e)=>getComputedStyle(e).filter")=='none' + await mute.click() + await solo.click() + assert await mute.get_attribute('aria-pressed')=='true' + assert await solo.get_attribute('aria-pressed')=='true' + lit=await page.evaluate("""()=>[...document.querySelectorAll('[data-mute="0"],[data-solo="0"]')].map(b=>({ + gap:getComputedStyle(b,'::before').opacity, + lamp:getComputedStyle(b.querySelector('.mx-hw-lamp')).opacity + }))""") + assert lit==[{'gap':'1','lamp':'1'}]*2,lit + # Only native/app JS changes channel state: decorating cannot dispatch audio. + await mute.click() + assert await mute.get_attribute('aria-pressed')=='false' + assert await solo.get_attribute('aria-pressed')=='true' + await solo.click() + # Every MASTER control occupies the same 29px row as regular MUTE/SOLO. + dimensions=await page.evaluate("""()=>{ + const rect=q=>document.querySelector(q).getBoundingClientRect(); + const master=rect('#masterMute'),mono=rect('#masterMode'),channel=rect('[data-mute="0"]'); + return {masterH:master.height,modeH:mono.height,channelH:channel.height, + masterMid:master.top+master.height/2,modeMid:mono.top+mono.height/2, + channelMid:channel.top+channel.height/2}; + }""") + assert all(24<=dimensions[k]<=34 for k in ('masterH','modeH','channelH')),dimensions + assert max(dimensions[k] for k in ('masterH','modeH','channelH'))-min( + dimensions[k] for k in ('masterH','modeH','channelH'))<.3,dimensions + assert max(dimensions[k] for k in ('masterMid','modeMid','channelMid'))-min( + dimensions[k] for k in ('masterMid','modeMid','channelMid'))<1,dimensions + # SVG gradient LED stops are resolved colors, never unsupported CSS var syntax. + stops=await page.evaluate("""()=>[...document.querySelectorAll('[data-mute="0"],[data-solo="0"]')] + .map(b=>getComputedStyle(b.querySelector('.mx-hw-lamp').ownerSVGElement + .querySelector('linearGradient[id^="mx-hw-led"] stop')).stopColor)""") + assert stops==['rgb(255, 64, 85)','rgb(255, 208, 44)'],stops + # Master mode changes textContent; observer reinstalls ONE SVG legend. + mode=page.locator('#masterMode') + await mode.click() + await page.wait_for_function("""()=>document.querySelector('#masterMode') + ?.querySelector('svg.mx-hw-face mask text')?.textContent==='MONO'""") + assert await mode.get_attribute('aria-pressed')=='true' + await mode.click() + await page.wait_for_function("""()=>document.querySelector('#masterMode') + ?.querySelector('svg.mx-hw-face mask text')?.textContent==='STEREO'""") + # Channel redraw does not leave a raw/old BTN-180 switch behind. + await page.evaluate('renderMixer()') + await page.wait_for_function("""()=>[...document.querySelectorAll('#mixer .channel-actions button')] + .every(b=>!!b.querySelector('svg.mx-hw-face'))""") + assert await page.locator('#mixer .channel-actions button').count()==22 + # Added native controls get the SAME renderer without poll/per-meter observer. + await page.evaluate("""()=>{ + const node=document.createElement('section');node.className='arV6Console'; + node.id='v5-native-fixture'; + node.innerHTML='
'+ + ''+ + ''+ + ''+ + ''+ + ''; + document.querySelector('#app').appendChild(node); + }""") + await page.wait_for_function("""()=>document.querySelectorAll('#v5-native-fixture .mx-hw-face').length===6""") + native=await page.evaluate("""()=>[...document.querySelectorAll('#v5-native-fixture button')].map(b=>({ + led:getComputedStyle(b).getPropertyValue('--mx-hw-led').trim(), + lamp:getComputedStyle(b.querySelector('.mx-hw-lamp')).opacity, + gap:getComputedStyle(b,'::before').opacity + }))""") + assert [x['led'] for x in native]==[ + '210,225,234','255,64,85','255,208,44','90,200,231','87,211,189','90,200,231'],native + assert native[0]['lamp']=='0' and native[0]['gap']=='0',native + assert all(x['lamp']=='1' and x['gap']=='1' for x in native[1:]),native + await page.locator('#v5-native-fixture').evaluate('(el)=>el.remove()') + +async def main(): + async with async_playwright() as p: + browser=await p.chromium.launch(headless=True) + for width,height in [(1366,768),(1680,900)]: + page=await browser.new_page(viewport={'width':width,'height':height}) + errors=[] + page.on('pageerror',lambda e:errors.append(str(e))) + await page.goto((ROOT/'web/index.html').as_uri()) + await audit(page) + assert not errors,(width,errors) + if width==1680: + await page.screenshot(path='mixer-backlit-v5-native-1680.png') + await page.locator('[data-mute="0"]').click() + await page.locator('[data-solo="0"]').click() + await page.screenshot(path='mixer-backlit-v5-native-ON-1680.png') + assert await page.locator('[data-mute="0"]').get_attribute('aria-pressed')=='true' + assert await page.locator('[data-solo="0"]').get_attribute('aria-pressed')=='true' + await page.close() + page=await browser.new_page(viewport={'width':1366,'height':768}) + await page.set_content((ROOT/'AR-MIX-Live-FX-Host-Standalone-v0.3.html').read_text()) + await audit(page) + await page.close() + await browser.close() + print('PASS V5: single mask, asymmetric static light, semantic LEDs, native/legacy dynamic renderer, independent toggles, OFF/ON redraw & offline parity') + +if __name__=='__main__': + asyncio.run(main()) diff --git a/tests/live_channel_fx_graph_test.cpp b/tests/live_channel_fx_graph_test.cpp index 0dd136630..d9af5997a 100644 --- a/tests/live_channel_fx_graph_test.cpp +++ b/tests/live_channel_fx_graph_test.cpp @@ -1,7 +1,13 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/core/LiveChannelFxGraph.h" +#include "../engine/core/DynamicChannelFxLeaseBank.h" +#include "../engine/core/DynamicNativeSessionPublisher.h" +#include "../engine/core/UnifiedLegacyProductionAdmission.h" #include "../engine/core/NativeOutputPairTap.h" #include "../engine/core/RealtimeRoutePublisher.h" +#include "../src/ConsoleLiveBridgeV6.h" +#include "../src/NativeVerifiedSourcePatch.h" +#include "../engine/core/NativeDryRouteCommand.h" #if defined(NDEBUG) #undef NDEBUG #endif @@ -13,6 +19,10 @@ #include #include #include +#include +#include +#include +#include using namespace armix::mixer; static std::atomic heapCalls{0}; @@ -87,7 +97,1160 @@ static std::unique_ptr makeGraph(float firstFx,float returnF assert(graph->maxFramesPerPlugin()==32); // clamp minimum safe plugin quantum return graph; } -int main() { +// M5: real M4 JUCE plugin instances survive ChannelId graph migration. +// CH11 and FX Return are not borrowed legacy strips: they receive their own +// native processor leases and execute in the same prepared PCM schedule. +static void verifyUniversalChannelIdFxLeaseAndLivePcm() { + using Bank=DynamicChannelFxLeaseBank; + DynamicChannelRoster roster; + std::array adds{}; + for(int i=0;i<4;++i) { + auto& op=adds[static_cast(i)]; + op.kind=ChannelEdit::Kind::add; + op.position=static_cast(i); + op.role=i==2?ChannelRole::fxReturn:i==3?ChannelRole::main:ChannelRole::input; + op.format=i<2?ProcessingFormat::mono:ProcessingFormat::stereo; + op.text=i==0?"CH1":i==1?"CH11":i==2?"FX RETURN":"MAIN"; + } + const auto created=roster.edit(0,adds); + assert(created.ok()&&created.createdIds.size()==4); + const auto ch1=created.createdIds[0],ch11=created.createdIds[1]; + const auto ret=created.createdIds[2],main=created.createdIds[3]; + std::vector wire; + const auto link=[&](ChannelId src,ChannelId dst,bool primary, + float gain=1.f) { + ChannelEdit op;op.kind=ChannelEdit::Kind::addSendReference; + op.id=src;op.target=dst;op.value=gain;op.primaryOutput=primary; + wire.push_back(std::move(op)); + }; + link(ch1,main,true); + link(ch11,main,true); + link(ret,main,true); + link(ch11,ret,false,.5f); + ChannelEdit marker;marker.kind=ChannelEdit::Kind::addInsertReference; + marker.id=ret;marker.text="native-vst3-fx-return"; + wire.push_back(std::move(marker)); + assert(roster.edit(roster.revision(),wire).ok()); + const std::array selected{ch1,ch11}; + const auto group=roster.createBusForSelected( + roster.revision(),selected,"VOCAL GROUP",ChannelRole::group); + assert(group.ok()&&group.createdIds.size()==1); + const auto bus=group.createdIds[0]; + // The accepted routing view, not a UI draft, proves exclusive primary OUT. + + DynamicGraphRequest req; + req.physicalInputs=2;req.maxFrames=32; + req.sources={{ch1,0,-1,false},{ch11,1,-1,false}}; + DynamicNativeSessionPublisher native; + constexpr std::uint64_t epoch=991; + assert(native.commit(roster,req,0,epoch,epoch,true).ok()); + const auto* view=native.acceptedRouting(epoch,1); + assert(view&&view->find(ch11)&&view->find(bus)); + assert(view->find(ch11)->primaryOutput==bus); + assert(view->find(bus)->primaryOutput==main); + + auto original=makeGraph(2.f,3.f); + Bank::Assignment first,groupOwner; + assert(Bank::captureLegacy(0,ch1,ProcessingFormat::mono,*original,first)); + assert(Bank::captureLegacy(1,bus,ProcessingFormat::stereo,*original,groupOwner)); + // These are genuinely new CH11/FX Return native instances. The M4 + // vendor processor ownership class and binary state path are reused. + const auto newFx=[&](float g,const char* catalog)->Bank::Lease { + auto p=std::make_unique(g); + p->prepareToPlay(48000.0,64); + return std::make_shared( + std::move(p),juce::String(catalog),juce::String(catalog),64); + }; + Bank::Assignment eleven;eleven.id=ch11;eleven.format=ProcessingFormat::mono; + eleven.inserts.push_back(newFx(4.f,"ch11-gain")); + Bank::Assignment returnFx;returnFx.id=ret;returnFx.format=ProcessingFormat::stereo; + returnFx.inserts.push_back(newFx(2.f,"fx-return-gain")); + std::array assignments{first,eleven,groupOwner,returnFx}; + Bank bank; + // The accepted FX owner and native PCM must share the NEXT graph revision. + assert(Bank::prepare(epoch,native.acceptedRevision()+1,assignments,bank)== + Bank::Fault::none); + assert(bank.lanes()==4&&bank.insertCount(ch11)==1&& + bank.insertCount(bus)==1&&bank.insertCount(ret)==1); + assert(bank.ownerForControl(ch1,0)&& + (*bank.ownerForControl(ch1,0))->instanceId== + original->insertInstanceId(0,0)); + Bank blocked; + std::array alias{first,groupOwner}; + alias[1].id=ch11; + alias[1].inserts=first.inserts; // same native processor twice + assert(Bank::prepare(epoch,2,alias,blocked)==Bank::Fault::duplicateInstance); + assert(blocked.lanes()==0); + // Native PDC is not yet installed. A real JUCE AudioProcessor reporting + // 64 samples of plugin delay must be rejected BEFORE accepted PCM/lease + // publication; mixing uncompensated Return with MAIN is phase-unsafe. + auto latentProcessor=std::make_unique(1.5f); + latentProcessor->setLatencySamples(64); + latentProcessor->prepareToPlay(48000.0,64); + Bank::Assignment latent; + latent.id=ch11;latent.format=ProcessingFormat::mono; + latent.inserts.push_back(std::make_shared( + std::move(latentProcessor),"latent-vst","latency-64",64)); + const std::array latentScene{latent}; + assert(Bank::prepare(epoch,2,latentScene,blocked)== + Bank::Fault::uncompensatedLatency); + assert(blocked.lanes()==0); // failed admission cannot mutate previous bank + assert(Bank::prepare(epoch,2,assignments,blocked)==Bank::Fault::none); + const auto token=original->insertInstanceId(0,0); + auto migrated=*bank.ownerForControl(ch1,0); + assert(migrated->instanceId==token); + original.reset(); // vendor instances retained by bank, no new VST3 scan + assert(GainFx::living>=4); + auto acceptedOwner=std::make_shared(std::move(bank)); + DynamicNativeSessionPublisher::FxPlan ownerPlan; + ownerPlan.owner=std::static_pointer_cast(acceptedOwner); + ownerPlan.context=acceptedOwner.get(); + ownerPlan.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(ctx))(id,l,r,n); + }; + ownerPlan.deviceEpoch=epoch;ownerPlan.graphRevision=2; + assert(ownerPlan.valid()); + // A mismatched raw callback context cannot be published or overwrite a + // working hardware graph. This is not a UI flag or an unchecked pointer. + auto wrong=ownerPlan;wrong.context=nullptr; + assert(native.commit(roster,req,1,epoch,epoch,true,std::move(wrong)).fault== + DynamicNativeSessionPublisher::Fault::invalidCandidate); + assert(native.acceptedRevision()==1); + assert(native.commit(roster,req,1,epoch,epoch,true,ownerPlan).ok()); + assert(native.acceptedRevision()==2); + // Only the accepted snapshot retains the vendor bank; local control + // holders can retire without losing a live VST during callback. + acceptedOwner.reset(); + std::array mic{},music{},left{},right{}; + mic.fill(.2f);music.fill(.1f); + const float* pins[]{mic.data(),music.data()}; + int legacyFallbackCalls=0; + const auto legacyFx=[&](ChannelId,float*,float*,int) noexcept { + ++legacyFallbackCalls; + }; + const auto beforeHeap=heapCalls.load(std::memory_order_relaxed); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(legacyFallbackCalls==0); // never dual-render M4 + M5 + assert(heapCalls.load(std::memory_order_relaxed)==beforeHeap); + constexpr float center=.7071067811865475f; + // Main: (CH1 .2*2 + CH11 .1*4) * mono pan * GROUP FX3 + // + CH11 post-send .5 * FX Return VST2 (no extra dry source). + assert(near(left[31],((.2f*2.f+.1f*4.f)*3.f+ + (.1f*4.f)*.5f*2.f)*center)); + assert(near(left[31],right[31])); + // E2: bypass a REAL hosted JUCE VST in the SAME native ChannelId graph. + // Acknowledged plugin identity, epoch and revision must all agree. The + // bypass uses FxInstance's existing 8ms audio-thread envelope, not a + // second DSP path or a control-thread plugin restart. + auto* acceptedBank=static_cast(ownerPlan.context); + const auto ch11Id=(*acceptedBank->ownerForControl(ch11,0))->instanceId; + const int livingAtBypass=GainFx::living; + assert(!acceptedBank->setInsertBypass(epoch-1,2,ch11,0,ch11Id,true)); + assert(!acceptedBank->setInsertBypass(epoch,1,ch11,0,ch11Id,true)); + assert(!acceptedBank->setInsertBypass(epoch,2,ch11,0,"wrong-token",true)); + assert(!acceptedBank->setInsertBypass(epoch,2,ch11,1,ch11Id,true)); + { + auto editorLease=acceptedBank->leaseEditor(epoch,2,ch11,0,ch11Id); + assert(editorLease && editorLease->instanceId==ch11Id); + assert(!acceptedBank->leaseEditor(epoch,1,ch11,0,ch11Id)); + assert(!acceptedBank->leaseEditor(epoch,2,ch11,0,"wrong-token")); + } + assert(acceptedBank->setInsertBypass(epoch,2,ch11,0,ch11Id,true)); + for(int i=0;i<16;++i) + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(near(left[31],((.2f*2.f+.1f)*3.f+.1f*.5f*2.f)*center)); + assert(GainFx::living==livingAtBypass && legacyFallbackCalls==0); + assert(acceptedBank->setInsertBypass(epoch,2,ch11,0,ch11Id,false)); + for(int i=0;i<16;++i) + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(near(left[31],((.2f*2.f+.1f*4.f)*3.f+ + (.1f*4.f)*.5f*2.f)*center)); + assert(GainFx::living==livingAtBypass && legacyFallbackCalls==0); + // M5.3 physical SOURCE hot switch reuses the exact live JUCE VST + // instances; no catalog lookup, plugin restart, heap or extra renderer. + const auto heapAtSource=heapCalls.load(std::memory_order_relaxed); + const auto liveAtSource=GainFx::living; + assert(native.setPhysicalSource(epoch,2,ch11,0,-1,false)); + assert(!native.setPhysicalSource(epoch,2,ch11,2,-1,false)); + assert(!native.setPhysicalSource(epoch-1,2,ch11,0,-1,false)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==heapAtSource); + assert(GainFx::living==liveAtSource&&legacyFallbackCalls==0); + assert(near(left[31],((.2f*2.f+.2f*4.f)*3.f+ + (.2f*4.f)*.5f*2.f)*center)); + assert(native.setPhysicalSource(epoch,2,ch11,1,-1,false)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==heapAtSource); + assert(GainFx::living==liveAtSource&&legacyFallbackCalls==0); + assert(near(left[31],((.2f*2.f+.1f*4.f)*3.f+ + (.1f*4.f)*.5f*2.f)*center)); + // Real hosted JUCE VST instances remain leased exactly once while + // a muted GROUP silences serial dry PCM, not the parallel FX Return. + const auto livingBeforeMute=GainFx::living; + const auto heapBeforeMute=heapCalls.load(std::memory_order_relaxed); + assert(native.setChannelMuteSolo(epoch,2,bus,true,false)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==heapBeforeMute); + assert(GainFx::living==livingBeforeMute && legacyFallbackCalls==0); + assert(near(left[31],(.1f*4.f)*.5f*2.f*center)); + assert(native.setChannelMuteSolo(epoch,2,bus,false,false)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false,legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==heapBeforeMute); + assert(GainFx::living==livingBeforeMute && legacyFallbackCalls==0); + assert(near(left[31],((.2f*2.f+.1f*4.f)*3.f+ + (.1f*4.f)*.5f*2.f)*center)); + // M-U2: the canonical ChannelId fader is smoothed over 64 SAMPLES, + // not 64 frames-per-callback. A 32-frame backend callback must reach + // only the halfway coefficient; the next 32 reaches the exact goal. + // Neither render may allocate, reinstantiate or call the old M4 FX. + assert(native.setChannelMix(epoch,2,bus,.5f,0.f)); + const auto beforeHalfHeap=heapCalls.load(std::memory_order_relaxed); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeHalfHeap); + assert(legacyFallbackCalls==0); + assert(near(left[31],((.2f*2.f+.1f*4.f)*3.f*.75f+ + (.1f*4.f)*.5f*2.f)*center)); + const auto half=left[31]; + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeHalfHeap); + assert(legacyFallbackCalls==0); + assert(left[0](std::move(refreshed)); + auto refreshedPlan=ownerPlan; + refreshedPlan.owner=std::static_pointer_cast(refreshedOwner); + refreshedPlan.context=refreshedOwner.get(); + refreshedPlan.graphRevision=3; + const auto originalProcessors=GainFx::living; + assert(native.commit(roster,req,2,epoch,epoch,true,refreshedPlan).ok()); + assert(GainFx::living==originalProcessors); // reuse, never rebuild VST + assert(native.acceptedRevision()==3); + const auto heapBeforeReload=heapCalls.load(std::memory_order_relaxed); + assert(native.render(epoch,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(heapCalls.load(std::memory_order_relaxed)==heapBeforeReload); + assert(near(left[31],((.2f*2.f+.1f*4.f)*3.f*.5f+ + (.1f*4.f)*.5f*2.f)*center)); + assert(legacyFallbackCalls==0); + assert(!native.render(epoch+1,pins,2,left.data(),right.data(),32,false, + legacyFx)); + assert(left[31]==0.f&&right[31]==0.f); +} + +// M-U1 full-fidelity preparation: 10 CH + 4 AUX + M4 VST owners, +// sparse verified input ports, independent physical MAIN and MONITOR, +// PRE/POST and native Show/epoch rejection. Compare actual old M4 processor +// output with the same owners in ONE new atomic ChannelId publication. +static void verifyMU1LegacyM4FxFullMigrationAndMonitorPcm() { + constexpr std::array ports{3,0,4,7}; + ChannelRoutingConfig channels; + channels.stripsAndMaster.strips[0]={ + SourceMode::mono,3,-1,.5f,-.3f,false,false}; + channels.stripsAndMaster.strips[1]={ + SourceMode::stereo,4,7,.75f,.2f,false,false}; + channels.formats[2]=ChannelFormat::stereo; + channels.stripsAndMaster.master={1.1f,.1f,false,true}; + SendRequest sends; + sends.toMaster[0]=false;sends.count=1; + sends.sends[0]={0,2,SendTap::postFader,.3f,-.3f,true}; + AuxBusRequest aux; + aux.buses[0]={true,true,false,.8f}; + aux.count=1; + aux.sends[0]={1,0,SendTap::postFader,.25f,.1f,true}; + std::array monitorGains{}; + monitorGains[0]=.25f;monitorGains[stripCount]=.3f; + PreparedRenderGraph legacyGraph; + RenderError legacyError; + assert(PreparedRenderGraph::compile(channels,ports,sends, + legacyGraph,legacyError,aux)); + auto legacy=std::make_unique(legacyGraph,32,32); + assert(legacy->setMonitorOutputBus(2,3,4,monitorGains)); + auto ch1=std::make_unique(1.2f); + auto returnFx=std::make_unique(.9f); + ch1->prepareToPlay(48000,32); + returnFx->prepareToPlay(48000,32); + assert(legacy->install(0,std::move(ch1),"CH1 VST3","m4-ch1")); + assert(legacy->install(stripCount,std::move(returnFx),"AUX VST3","m4-aux")); + const auto oldCh1=legacy->insertInstanceId(0,0); + const auto oldAux=legacy->insertInstanceId(stripCount,0); + std::array mono{},unrelated{},stL{},stR{}; + for(int i=0;i<32;++i){ + mono[i]=.2f+.001f*i;unrelated[i]=.8f; + stL[i]=.15f+.002f*i;stR[i]=.35f-.001f*i; + } + const float* physical[]{mono.data(),unrelated.data(),stL.data(),stR.data()}; + std::array legacyL{},legacyR{},legacyML{},legacyMR{}; + assert(legacy->process(physical,4,legacyL.data(),legacyR.data(),32, + nullptr,nullptr,nullptr,legacyML.data(),legacyMR.data())); + DynamicNativeSessionPublisher publisher; + UnifiedLegacyAccepted accepted; + constexpr std::uint64_t epoch=565; + VerifiedNativeOutputs outputs{4,0,1,2,3,true}; + const auto good=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitorGains,*legacy,false,outputs, + 32,2u*1024u*1024u,0,epoch,epoch,true,publisher,accepted); + assert(good.ok()); + assert(publisher.acceptedRevision()==1); + assert(accepted.deviceEpoch==epoch&&accepted.pcmRevision==1); + assert(accepted.graph.roster.size()==stripCount+auxBusCount+2); + assert(accepted.graph.request.sources.size()==2); + assert(accepted.fxOwners->insertCount(accepted.graph.ids.inputs[0])==1); + assert(accepted.fxOwners->insertCount(accepted.graph.ids.aux[0])==1); + assert((*accepted.fxOwners->ownerForControl( + accepted.graph.ids.inputs[0],0))->instanceId==oldCh1); + assert((*accepted.fxOwners->ownerForControl( + accepted.graph.ids.aux[0],0))->instanceId==oldAux); + // Actual FX ownership survives the old M4 graph retirement. + legacy.reset(); + std::array dynamicL{},dynamicR{},dynamicML{},dynamicMR{}; + const auto mustNeverCall=[&](ChannelId,float*,float*,int) noexcept { + assert(false && "M4 processor may not render twice"); + }; + const auto before=heapCalls.load(std::memory_order_relaxed); + assert(publisher.render(epoch,physical,4,dynamicL.data(),dynamicR.data(), + 32,false,mustNeverCall, + dynamicML.data(),dynamicMR.data())); + assert(heapCalls.load(std::memory_order_relaxed)==before); + // E2 native physical path reads true per-ChannelId POST-fader left + // and right peaks from the SAME render (no stale M4 GUI meter). + std::array nativeMeterL{},nativeMeterR{}; + assert(publisher.render(epoch,physical,4,dynamicL.data(),dynamicR.data(), + 32,false,mustNeverCall, + dynamicML.data(),dynamicMR.data(), + nativeMeterL,nativeMeterR)); + assert(heapCalls.load(std::memory_order_relaxed)==before); + assert(nativeMeterL[0]>0.f&&nativeMeterR[0]>0.f); + assert(!near(nativeMeterL[0],nativeMeterR[0])); + assert(nativeMeterL[stripCount]>0.f&&nativeMeterR[stripCount]>0.f); + assert(nativeMeterL[stripCount+auxBusCount]>0.f); + assert(nativeMeterL[stripCount+auxBusCount+1]>0.f); + + for(int i=0;i<32;++i) { + assert(near(legacyL[i],dynamicL[i])); + assert(near(legacyR[i],dynamicR[i])); + assert(near(legacyML[i],dynamicML[i])); + assert(near(legacyMR[i],dynamicMR[i])); + } + // E2 native accepted-state FX seam: stale epoch/revision/token is + // rejected; a genuine VST bypass changes PCM through the SAME accepted + // ChannelId processor lease, not through old M4 or a mock plug-in. + const auto ch1Id=accepted.graph.ids.inputs[0]; + assert(!accepted.setFxBypass(publisher,epoch-1,1,ch1Id,0,oldCh1,true)); + assert(!accepted.setFxBypass(publisher,epoch,0,ch1Id,0,oldCh1,true)); + assert(!accepted.setFxBypass(publisher,epoch,1,ch1Id,0,"unowned",true)); + { + auto editor=accepted.leaseFxEditor(publisher,epoch,1,ch1Id,0,oldCh1); + assert(editor && editor->instanceId==oldCh1); + assert(!accepted.leaseFxEditor(publisher,epoch,1,ch1Id,0,"unowned")); + } + assert(accepted.setFxBypass(publisher,epoch,1,ch1Id,0,oldCh1,true)); + const auto heapAtFxControl=heapCalls.load(std::memory_order_relaxed); + for(int i=0;i<16;++i) + assert(publisher.render(epoch,physical,4,dynamicL.data(),dynamicR.data(), + 32,false,mustNeverCall, + dynamicML.data(),dynamicMR.data())); + assert(heapCalls.load(std::memory_order_relaxed)==heapAtFxControl); + assert(!near(legacyL[31],dynamicL[31])); + assert(accepted.setFxBypass(publisher,epoch,1,ch1Id,0,oldCh1,false)); + for(int i=0;i<16;++i) + assert(publisher.render(epoch,physical,4,dynamicL.data(),dynamicR.data(), + 32,false,mustNeverCall, + dynamicML.data(),dynamicMR.data())); + assert(near(legacyL[31],dynamicL[31])); + // Faults are non-destructive: no external CH1 Orbit state dropped, no + // wrong-speaker output, no stale hardware, no armed graph recreation. + LiveChannelFxGraph blockedLegacy(legacyGraph,32,32); + assert(blockedLegacy.setMonitorOutputBus(2,3,4,monitorGains)); + auto bad=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitorGains,blockedLegacy, + true,outputs,32,2u*1024u*1024u,1,epoch,epoch,true, + publisher,accepted); + assert(bad.fault==UnifiedLegacyProductionAdmission::Fault::legacyCh1ExternalFx); + auto wrongPins=outputs; + wrongPins.monitorR=0; // same physical output as MAIN + bad=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitorGains,blockedLegacy, + false,wrongPins,32,2u*1024u*1024u,1,epoch,epoch,true, + publisher,accepted); + assert(bad.fault==UnifiedLegacyProductionAdmission::Fault::invalidOutputPins); + bad=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitorGains,blockedLegacy, + false,outputs,32,2u*1024u*1024u,1,epoch,epoch+1,true, + publisher,accepted); + assert(bad.fault==UnifiedLegacyProductionAdmission::Fault::staleHardware); + bad=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitorGains,blockedLegacy, + false,outputs,32,2u*1024u*1024u,1,epoch,epoch,false, + publisher,accepted); + assert(bad.fault==UnifiedLegacyProductionAdmission::Fault::outputArmed); + assert(publisher.acceptedRevision()==1); + assert(accepted.fxOwners->insertCount(accepted.graph.ids.inputs[0])==1); + assert(publisher.render(epoch,physical,4,dynamicL.data(),dynamicR.data(), + 32,false,mustNeverCall, + dynamicML.data(),dynamicMR.data())); + for(int i=0;i<32;++i){ + assert(near(legacyL[i],dynamicL[i])); + assert(near(legacyMR[i],dynamicMR[i])); + } + assert(!publisher.render(epoch+1,physical,4,dynamicL.data(), + dynamicR.data(),32,false,mustNeverCall, + dynamicML.data(),dynamicMR.data())); + assert(dynamicL[31]==0.f&&dynamicR[31]==0.f); +} + +// M-U1: occupied legacy CH1 with original JUCE FX owner; PCM and fail-closed. +static void verifyOccupiedExternalCh1Owner() { + struct Owner { + GainFx fx{1.7f}; int calls=0; + Owner(){fx.prepareToPlay(48000,32);} + void process(float* l,float* r,int n) noexcept { + float* ptrs[]{l,r};juce::AudioBuffer block(ptrs,2,n); + juce::MidiBuffer midi;fx.processBlock(block,midi);++calls; + } + }; + ChannelRoutingConfig channels; + channels.stripsAndMaster.strips[0]={ + SourceMode::mono,3,-1,.8f,-.2f,false,false}; + SendRequest sends;AuxBusRequest aux; + constexpr std::array ports{3,0}; + PreparedRenderGraph route;RenderError err; + assert(PreparedRenderGraph::compile(channels,ports,sends,route,err,aux)); + auto old=std::make_unique(route,32,32); + auto vendor=std::make_shared();auto* raw=vendor.get(); + std::weak_ptr retiringOwner=vendor; + std::array src{},silent{},oldL{},oldR{},newL{},newR{}; + src.fill(.25f); + const float* pins[]{src.data(),silent.data()}; + const auto legacyFx=+[](void* c,int strip,float* l,float* r,int n) noexcept { + assert(strip==0);static_cast(c)->process(l,r,n); + }; + assert(old->process(pins,2,oldL.data(),oldR.data(),32, + nullptr,raw,legacyFx)); + DynamicNativeSessionPublisher publisher;UnifiedLegacyAccepted accepted; + std::array monitor{}; + VerifiedNativeOutputs outputs{2,0,1,-1,-1,false}; + constexpr std::uint64_t epoch=701; + auto status=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitor,*old,true,outputs, + 32,2u*1024u*1024u,0,epoch,epoch,true,publisher,accepted); + assert(status.fault==UnifiedLegacyProductionAdmission::Fault::legacyCh1ExternalFx); + assert(publisher.acceptedRevision()==0); + LegacyMigratedGraph migrated;LegacyMigrationError migrationError; + assert(LegacyGraphMigration::compile(channels,ports,sends,aux,false, + monitor,32,2u*1024u*1024u,migrated,migrationError)); + DynamicChannelFxLeaseBank::ExternalLease lease; + // The original JUCE Graph has no ChannelId. The native ADMISSION, + // not GUI strip ordinals, must bind the verified imported CH1 identity. + lease.id=ChannelId{}; + lease.owner=std::static_pointer_cast(vendor); + lease.context=raw; + lease.render=+[](void* c,float* l,float* r,int n) noexcept { + static_cast(c)->process(l,r,n); + }; + auto invalid=lease;invalid.context=nullptr; + status=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitor,*old,true,outputs, + 32,2u*1024u*1024u,0,epoch,epoch,true,publisher,accepted,invalid); + assert(status.fault==UnifiedLegacyProductionAdmission::Fault::legacyCh1ExternalFx); + // A supplied but WRONG nonzero ChannelId cannot hijack another lane. + invalid=lease;invalid.id=ChannelId{987654}; + status=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitor,*old,true,outputs, + 32,2u*1024u*1024u,0,epoch,epoch,true,publisher,accepted,invalid); + assert(status.fault==UnifiedLegacyProductionAdmission::Fault::legacyCh1ExternalFx); + assert(publisher.acceptedRevision()==0); + status=UnifiedLegacyProductionAdmission::compileAndCommit( + channels,ports,sends,aux,monitor,*old,true,outputs, + 32,2u*1024u*1024u,0,epoch,epoch,true,publisher,accepted,lease); + assert(status.ok()&&publisher.acceptedRevision()==1); + assert(accepted.fxOwners->externalChannel()==migrated.ids.inputs[0]); + // The publisher owns the exact vendor processBlock and GUI state, + // regardless of the former M4 route/control owner's retirement. + old.reset();vendor.reset(); + lease={};invalid={}; + assert(!retiringOwner.expired()); + const auto fallback=+[](ChannelId,float*,float*,int) noexcept { + assert(false && "occupied vendor FX must never disappear"); + }; + const auto before=heapCalls.load(std::memory_order_relaxed); + assert(publisher.render(epoch,pins,2,newL.data(),newR.data(), + 32,false,fallback)); + assert(heapCalls.load(std::memory_order_relaxed)==before); + assert(raw->calls==2); + for(int n=0;n<32;++n){ + assert(near(newL[n],oldL[n]));assert(near(newR[n],oldR[n])); + } + assert(!publisher.render(epoch+1,pins,2,newL.data(),newR.data(), + 32,false,fallback)); + assert(newL[31]==0.f&&newR[31]==0.f); + assert(publisher.acceptedRevision()==1); + // Once no callback may hold the accepted PCM snapshot, there is no + // hidden second FX owner. All vendor/plugin cleanup is off realtime. + publisher.unpublish(); + accepted=UnifiedLegacyAccepted{}; + publisher.pollRetirement(); + assert(retiringOwner.expired()); +} + +// M-U1 source/processing format independence: a mono microphone through a +// stereo native rack must retain the same equal-power PAN as M4. Conversely +// physical stereo folded to mono processing must not become stereo-balance. +// Compare exact physical L/R PCM for all four source/format combinations. +static void verifySourceFormatIndependentPanPcmParity() { + struct Case {bool sourceStereo,processStereo;float pan;}; + constexpr std::array cases{{ + {false,false,-.6f},{false,true,-.6f}, + {false,true,.6f},{true,false,.6f}, + {true,false,-.6f},{true,true,.6f} + }}; + constexpr std::array ports{3,7}; + std::array mic{},micR{}; + for(int i=0;i<32;++i){ + mic[i]=.15f+.001f*i; + micR[i]=.35f-.002f*i; + } + const float* physical[]{mic.data(),micR.data()}; + constexpr std::uint64_t epoch=800; + const auto noFx=+[](ChannelId,float*,float*,int) noexcept {}; + for(const auto& choice:cases) { + ChannelRoutingConfig cfg; + cfg.stripsAndMaster.strips[0]={ + choice.sourceStereo?SourceMode::stereo:SourceMode::mono, + 3,choice.sourceStereo?7:-1,.7f,choice.pan,false,false + }; + cfg.formats[0]=choice.processStereo? + ChannelFormat::stereo:ChannelFormat::mono; + SendRequest sends;AuxBusRequest aux; + PreparedRenderGraph oldRoute;RenderError legacyError; + assert(PreparedRenderGraph::compile( + cfg,ports,sends,oldRoute,legacyError,aux)); + auto old=std::make_unique(oldRoute,32,32); + assert(old->setStripControl(0,.7f,choice.pan, + !choice.sourceStereo||!choice.processStereo, + false,false)); + std::array oldL{},oldR{},nativeL{},nativeR{}; + assert(old->process(physical,2,oldL.data(),oldR.data(),32)); + DynamicNativeSessionPublisher native; + UnifiedLegacyAccepted accepted; + std::array monitor{}; + VerifiedNativeOutputs outs{2,0,1,-1,-1,false}; + auto admission=UnifiedLegacyProductionAdmission::compileAndCommit( + cfg,ports,sends,aux,monitor,*old,false,outs, + 32,2u*1024u*1024u,0,epoch,epoch,true,native,accepted); + assert(admission.ok()); + const auto before=heapCalls.load(std::memory_order_relaxed); + assert(native.render(epoch,physical,2,nativeL.data(), + nativeR.data(),32,false,noFx)); + assert(heapCalls.load(std::memory_order_relaxed)==before); + for(int i=0;i<32;++i){ + assert(near(nativeL[i],oldL[i])); + assert(near(nativeR[i],oldR[i])); + } + // A stale physical endpoint must fail silent and not change ACK. + assert(!native.render(epoch+1,physical,2,nativeL.data(), + nativeR.data(),32,false,noFx)); + assert(nativeL[31]==0.f&&nativeR[31]==0.f); + assert(native.acceptedRevision()==1); + } +} + +// G0: This is the real JUCE device/callback STATUS -> v6 Console wire, +// not a dry ChannelId graph or simulated universal engine. It must report +// measured M4 PCM while all unsupported ChannelId operations stay CLOSED. +static void verifyNativeConsoleWireRejectsUnsupportedM4AndPreservesEpoch() { + using Bridge=armix::console::LiveConsoleBridgeV6; + auto route=std::make_unique(); + constexpr juce::int64 epoch=9007199254740993LL; // beyond JS Number safety + route->setProperty("epoch",epoch); + route->setProperty("revision",juce::int64(77)); + route->setProperty("active",true); + route->setProperty("ready",true); + route->setProperty("hasAcceptedRoute",true); + // These booleans are device-loop truth, NOT permission to promote + // universal CH11, GROUP or WIRE operations in the GUI. + route->setProperty("nativeChannelIdPcmActive",true); + route->setProperty("originalCh1GraphLeased",true); + // Genuine admitted M4 rows, not fabricated universal ChannelIds. + juce::Array admittedRows; + for(int i=0;i(); + row->setProperty("mode",i==0?"MONO":"NONE"); + row->setProperty("left",i==0?2:-1); + row->setProperty("right",-1); + admittedRows.add(juce::var(row.release())); + } + auto admittedRoute=std::make_unique(); + admittedRoute->setProperty("channels",juce::var(admittedRows)); + route->setProperty("acceptedRoute",juce::var(admittedRoute.release())); + juce::Array ports; + auto port=std::make_unique(); + port->setProperty("port",2);port->setProperty("callback",0); + port->setProperty("label","ASIO Input 3"); + ports.add(juce::var(port.release())); + route->setProperty("ports",juce::var(ports)); + juce::Array outputs; + outputs.add(1);outputs.add(4); + route->setProperty("outputPorts",juce::var(outputs)); + juce::Array levels; + levels.add(.125);levels.add(0.0); + route->setProperty("channelPeaks",juce::var(levels)); + auto status=std::make_unique(); + status->setProperty("dryRoutingLab",juce::var(route.release())); + status->setProperty("driver","ASIO TEST"); + status->setProperty("inputDevice","TEST CAPTURE"); + status->setProperty("outputDevice","TEST RENDER"); + status->setProperty("connected",true); + status->setProperty("directRouteAuthorized",true); + status->setProperty("monitor",true); + status->setProperty("callbackCount",juce::int64(12)); + status->setProperty("callbackInputChannels",1); + status->setProperty("inputPeak",.25); + juce::Array perPort; + perPort.add(.25); + status->setProperty("captureCallbackPeaks",juce::var(perPort)); + status->setProperty("peak",.125); + status->setProperty("rate",48000); + status->setProperty("buffer",128); + const auto live=juce::var(status.release()); + auto snap=Bridge::snapshot(live); + auto device=snap.getProperty("device",{}); + auto graph=snap.getProperty("graph",{}); + auto measured=snap.getProperty("telemetry",{}); + assert(static_cast(snap.getProperty("schemaVersion",0))==6); + assert(!static_cast(snap.getProperty("productionCallbackLive",true))); + assert(device.getProperty("epoch","").toString()=="9007199254740993"); + assert(static_cast(device.getProperty("outputArmed",false))); + assert(static_cast(measured.getProperty("rawCapturePresent",false))); + assert(static_cast(measured.getProperty("mainPcmPresent",false))); + assert(graph.getProperty("revision","").toString()=="0"); + assert(graph.getProperty("rosterRevision","").toString()=="0"); + assert(graph.getProperty("channels",{}).getArray()->isEmpty()); + const auto caps=graph.getProperty("capabilities",{}); + assert(!static_cast(caps.getProperty("callbackOwnsChannelIds",true))); + assert(caps.getProperty("supportedOps",{}).getArray()->isEmpty()); + auto ins=device.getProperty("inputEndpoints",{}); + auto outs=device.getProperty("outputEndpoints",{}); + assert(ins.getArray()->size()==1 && outs.getArray()->size()==2); + const auto acceptedInputs=device.getProperty("enabledInputs",{}); + const auto acceptedOutputs=device.getProperty("enabledOutputs",{}); + assert(acceptedInputs.getArray() && acceptedInputs.getArray()->size()==1); + assert(acceptedOutputs.getArray() && acceptedOutputs.getArray()->size()==2); + assert(static_cast(acceptedInputs.getArray()->getReference(0))==2); + assert(static_cast(acceptedOutputs.getArray()->getReference(0))==1); + assert(static_cast(acceptedOutputs.getArray()->getReference(1))==4); + assert(static_cast(ins.getArray()->getReference(0).getProperty("port",0))==2); + assert(static_cast(ins.getArray()->getReference(0) + .getProperty("rawPeak",0.0))==.25); + assert(static_cast(ins.getArray()->getReference(0) + .getProperty("rawPresent",false))); + assert(static_cast(outs.getArray()->getReference(0).getProperty("port",0))==1); + assert(static_cast(outs.getArray()->getReference(1).getProperty("port",0))==4); + const auto diagnostic=snap.getProperty("legacyM4",{}); + assert(diagnostic.getProperty("routingRevision","").toString()=="77"); + assert(diagnostic.getProperty("controlPlane","").toString()=="LEGACY_M4_ORDINAL"); + assert(diagnostic.getProperty("pcmRenderer","").toString()=="CHANNEL_ID_10CH4AUX"); + assert(static_cast(diagnostic.getProperty("originalCh1GraphLeased",false))); + // A revoked native PCM mode must immediately report M4 fallback without + // inventing any universal ChannelId capabilities or stale FX identity. + auto pcmRouteReadback=live.getProperty("dryRoutingLab",{}); + pcmRouteReadback.getDynamicObject()->setProperty("nativeChannelIdPcmActive",false); + auto fallbackSnap=Bridge::snapshot(live); + const auto fallbackM4=fallbackSnap.getProperty("legacyM4",{}); + assert(fallbackM4.getProperty("pcmRenderer","").toString()=="M4_COMPAT"); + assert(!static_cast(fallbackM4.getProperty("originalCh1GraphLeased",true))); + assert(!static_cast(fallbackSnap.getProperty("productionCallbackLive",true))); + pcmRouteReadback.getDynamicObject()->setProperty("nativeChannelIdPcmActive",true); + const auto legacyRows=diagnostic.getProperty("acceptedChannels",{}); + assert(legacyRows.getArray()&& + legacyRows.getArray()->size()==armix::mixer::stripCount); + assert(legacyRows.getArray()->getReference(0).getProperty("mode","").toString()=="MONO"); + const auto nativeM4Ops=diagnostic.getProperty("supportedOps",{}); + assert(nativeM4Ops.getArray() && + nativeM4Ops.getArray()->contains(juce::var(juce::String("SET_FADER"))) && + nativeM4Ops.getArray()->contains(juce::var(juce::String("SET_MUTE"))) && + !nativeM4Ops.getArray()->contains(juce::var(juce::String("CREATE_CHANNEL")))); + // No false universal promotion even when the installed M4 branch can + // really mutate physical PCM through its own separately fenced transport. + assert(!static_cast(snap.getProperty("productionCallbackLive",true))); + assert(caps.getProperty("supportedOps",{}).getArray()->isEmpty()); + // Universal revisions cannot be borrowed from M4; this unready source + // must not permit GUI ChannelId operations even while M4 PCM is active. + assert(graph.getProperty("revision","").toString()=="0"); + Bridge bridge; + const auto intent=[&](const juce::String& req,const juce::String& ep, + const juce::String& rev="0") { + auto o=std::make_unique(); + o->setProperty("requestId",req); + o->setProperty("deviceEpoch",ep); + o->setProperty("baseGraphRevision",rev); + o->setProperty("baseRosterRevision","0"); + o->setProperty("operation","SET_SOURCE"); + o->setProperty("targetChannelId","18446744073709551615"); + return juce::var(o.release()); + }; + const auto pending=intent("editor:nonce:1","9007199254740993"); + auto ack=bridge.rejectUnsupportedIntent(pending,snap); + assert(ack.getProperty("requestId","").toString()=="editor:nonce:1"); + assert(ack.getProperty("status","").toString()=="REJECTED"); + assert(ack.getProperty("errorCode","").toString()=="UNIVERSAL_CALLBACK_NOT_READY"); + assert(ack.getProperty("graphRevision","").toString()=="0"); + assert(bridge.rejectUnsupportedIntent(pending,snap) + .getProperty("errorCode","").toString()=="DUPLICATE_REQUEST_ID"); + assert(bridge.rejectUnsupportedIntent(intent("editor:nonce:2","9007199254740992"),snap) + .getProperty("errorCode","").toString()=="STALE_DEVICE_EPOCH"); + assert(bridge.rejectUnsupportedIntent(intent("editor:nonce:3","9007199254740993","9"),snap) + .getProperty("errorCode","").toString()=="STALE_GRAPH_REVISION"); + std::uint64_t decoded=0; + assert(Bridge::decodeDecimal(juce::var("18446744073709551615"),decoded)); + assert(decoded==std::numeric_limits::max()); + assert(!Bridge::decodeDecimal(juce::var("18446744073709551616"),decoded)); + assert(!Bridge::decodeDecimal(juce::var("01"),decoded)); + assert(!Bridge::decodeDecimal(juce::var(9007199254740993.0),decoded)); + // Fail-closed device fault: do not advertise a compatibility actuator + // against a poisoned physical port topology or stale hardware session. + auto liveRoute=live.getProperty("dryRoutingLab",{}); + liveRoute.getDynamicObject()->setProperty("topologyFault",true); + const auto stale=Bridge::snapshot(live).getProperty("legacyM4",{}); + assert(stale.getProperty("supportedOps",{}).isVoid()); + assert(stale.getProperty("acceptedChannels",{}).isVoid()); + // No request above mutates the genuinely accepted M4 hardware route. + assert(static_cast(live.getProperty("dryRoutingLab",{}).getProperty("revision",0))==77); +} + +// G1 physical First Sound: one enabled callback pin becomes a MONO +// production source in ONE native mutation. No fabricated stereo IN1/IN1, +// no accidental modification of the last accepted M4 request on failure. +static void verifyFirstSoundOnePinNativeSourceDraft() { + using armix::mixer::NativeVerifiedSourcePatch; + auto command=std::make_unique(); + command->setProperty("deviceEpoch",juce::int64(17)); + command->setProperty("revision",juce::int64(8)); + juce::Array sources; + for(int c=0;c<10;++c) { + auto ch=std::make_unique(); + ch->setProperty("mode","NONE"); + ch->setProperty("left",-1); + ch->setProperty("right",-1); + ch->setProperty("gain",.25); + ch->setProperty("pan",0.0); + sources.add(juce::var(ch.release())); + } + command->setProperty("channels",juce::var(sources)); + const auto accepted=juce::var(command.release()); + const std::array physical{{5}}; + juce::var candidate; + assert(NativeVerifiedSourcePatch::prepare(accepted,6,"MONO",5,-1, + physical,17,9,candidate).isEmpty()); + const auto draftChannels=candidate.getProperty("channels",juce::var()); + const auto sourceBefore=accepted.getProperty("channels",juce::var()); + const auto* acceptedChannels=sourceBefore.getArray(); + const auto* changed=draftChannels.getArray(); + assert(changed && changed->size()==10 && acceptedChannels && + acceptedChannels->size()==10); + assert(changed->getReference(6).getProperty("mode","").toString()=="MONO"); + assert(static_cast(changed->getReference(6).getProperty("left",-1))==5); + assert(static_cast(changed->getReference(6).getProperty("right",0))==-1); + assert(acceptedChannels->getReference(6).getProperty("mode","").toString()=="NONE"); + assert(candidate.getProperty("revision",{}).toString()=="9"); + candidate=juce::var(); + assert(NativeVerifiedSourcePatch::prepare(accepted,6,"STEREO",5,5, + physical,17,9,candidate).isNotEmpty()); + assert(candidate.isVoid()); + assert(NativeVerifiedSourcePatch::prepare(accepted,6,"STEREO",5,7, + physical,17,9,candidate).isNotEmpty()); + assert(NativeVerifiedSourcePatch::prepare(accepted,6,"MONO",4,-1, + physical,17,9,candidate).isNotEmpty()); + assert(NativeVerifiedSourcePatch::prepare(accepted,6,"MONO",5,-1, + physical,18,9,candidate).isNotEmpty()); + assert(acceptedChannels->getReference(6).getProperty("mode","").toString()=="NONE"); + const std::array stereoPhysical{{5,7}}; + assert(NativeVerifiedSourcePatch::prepare(accepted,2,"STEREO",5,7, + stereoPhysical,17,9,candidate).isEmpty()); + const auto stereoRows=candidate.getProperty("channels",juce::var()); + assert(stereoRows.getArray()->getReference(2).getProperty("mode","").toString()=="STEREO"); + + // Real production route schema v2: distinguish physical SOURCE from + // channel PROCESSING width, and compile the accepted plan on the same + // NativeDryRouteCommand path used by LiveDryRoutingLab::apply(). + auto typed=juce::JSON::parse(juce::JSON::toString(accepted,false)); + typed.getDynamicObject()->setProperty("schemaVersion",2); + const auto typedSource=typed.getProperty("channels",{}); + for(auto& value:*typedSource.getArray()) { + auto* obj=value.getDynamicObject(); + assert(obj); + obj->setProperty("sourceKind","NONE"); + obj->setProperty("sourceFormat","NONE"); + obj->setProperty("channelFormat","STEREO"); + obj->setProperty("main",true); + obj->setProperty("mute",false); + obj->setProperty("solo",false); + } + juce::var typedNew; + assert(NativeVerifiedSourcePatch::prepare(typed,6,"MONO",5,-1, + physical,17,9,typedNew).isEmpty()); + const auto newRows=typedNew.getProperty("channels",{}); + const auto newCh=newRows.getArray()->getReference(6); + assert(newCh.getProperty("sourceKind","").toString()=="PHYSICAL"); + assert(newCh.getProperty("sourceFormat","").toString()=="MONO"); + assert(newCh.getProperty("channelFormat","").toString()=="STEREO"); + assert(static_cast(newCh.getProperty("right",0))==-1); + armix::mixer::NativeDryRouteCommand decoded; + juce::String error; + assert(armix::mixer::NativeDryRouteCommand::decode(typedNew,decoded,error)); + assert(decoded.channels.stripsAndMaster.strips[6].source== + armix::mixer::SourceMode::mono); + assert(decoded.channels.formats[6]==armix::mixer::ChannelFormat::stereo); + armix::mixer::ChannelRoutingPlan routed; + armix::mixer::LayoutError issue; + assert(armix::mixer::ChannelRoutingPlan::compile( + decoded.channels,physical,routed,issue)); + assert(routed.base.strips[6].inputA==0); + assert(routed.effectiveFormats[6]==armix::mixer::ChannelFormat::stereo); + const std::array mic{{.25f,.5f,.75f,1.f}}; + const float* nativePins[]{mic.data()}; + std::array routedL{},routedR{}; + assert(routed.base.extractSource(6,nativePins,1, + routedL.data(),routedR.data(),4)); + assert(routedL==mic && routedR==mic); + + // The *installed M4 native PCM renderer*, not DynamicPreparedMixerBlock: + // actual physical IN5 callback[0] -> independent CH07 -> stereo MAIN. + // Exercise the same LiveChannelFxGraph::process invoked by + // LiveDryRoutingLab::process from the sole JUCE hardware callback. + armix::mixer::PreparedRenderGraph prepared; + armix::mixer::RenderError renderError; + assert(armix::mixer::PreparedRenderGraph::compile( + decoded.channels,physical,decoded.sends,prepared,renderError,decoded.aux)); + armix::mixer::LiveChannelFxGraph production(prepared,64,64); + assert(production.setMainOutputPair(0,1,2)); + std::array mainL{},mainR{}; + armix::mixer::RenderLevels levels; + const auto beforeCallback=heapCalls.load(std::memory_order_relaxed); + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeCallback); + assert(mainL[0] > 0.f && mainR[0] > 0.f && + std::isfinite(mainL[0]) && std::isfinite(mainR[0])); + assert(near(mainL[0],mainR[0])); + assert(levels.channelPeak[6] > 0.f); + assert(levels.channelPeak[1] == 0.f); // CH02 unpatched, no fake PCM. + // The real strip deliberately de-clicks MUTE over up to 64 frames: + // a transition is NOT an immediate memset. Verify sample-by-sample + // monotonic fade and that steady muted blocks are truly silent. + assert(production.setStripControl(6,.25f,0.f,true,true,false)); + mainL.fill(1.f);mainR.fill(1.f); + const auto beforeMute=heapCalls.load(std::memory_order_relaxed); + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeMute); + assert(mainL[0]>0.f && mainR[0]>0.f); + // RAW physical microphone samples increase across the test block. + // Compare actual per-frame GAIN envelope after removing input amplitude, + // otherwise a correct fade is incorrectly rejected as nonmonotonic. + assert(mainL[0]/mic[0]>mainL[1]/mic[1] && + mainL[1]/mic[1]>mainL[2]/mic[2]); + assert(mainR[0]/mic[0]>mainR[1]/mic[1] && + mainR[1]/mic[1]>mainR[2]/mic[2]); + assert(mainL[3]>0.f && mainR[3]>0.f); // 4/64 frames, not a hard mute + // Sixteen small callback blocks complete EXACTLY the same 64-sample + // ramp as one 64-frame callback, without RT heap allocations. + float previousTail=mainL[3]/mic[3]; + for(int blockIndex=1;blockIndex<16;++blockIndex) { + const auto heapBefore=heapCalls.load(std::memory_order_relaxed); + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + assert(heapCalls.load(std::memory_order_relaxed)==heapBefore); + const float normalizedTail=mainL[3]/mic[3]; + assert(normalizedTail<=previousTail+1.e-5f); + previousTail=normalizedTail; + } + assert(near(mainL[3],0.f) && near(mainR[3],0.f)); + mainL.fill(1.f);mainR.fill(1.f); + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + for(int n=0;n<4;++n)assert(mainL[n]==0.f && mainR[n]==0.f); + assert(levels.channelPeak[6]==0.f); + assert(production.setStripControl(6,.25f,0.f,true,false,false)); + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + assert(mainL[0]>0.f&&mainR[0]>0.f); + assert(mainL[3]>mainL[0]); // unmute ramps, never spikes to unity + for(int k=1;k<16;++k) + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + assert(mainL[3]>0.f); + // A rapid re-MUTE in the middle of an unmute envelope does not + // interpolate from stale unity or introduce a discontinuity. + assert(production.setStripControl(6,.25f,0.f,true,true,false)); + assert(production.process(nativePins,1,mainL.data(),mainR.data(),4,&levels)); + assert(mainL[0]>0.f); + juce::var denied; + assert(NativeVerifiedSourcePatch::prepare(typed,6,"STEREO",5,5, + physical,17,9,denied).isNotEmpty()); + assert(denied.isVoid()); + assert(typedSource.getArray()->getReference(6) + .getProperty("sourceKind","").toString()=="NONE"); + + // SOURCE STEREO can be folded into MONO processing independently. + auto typedFold=juce::JSON::parse(juce::JSON::toString(typed,false)); + auto foldedRows=typedFold.getProperty("channels",{}); + foldedRows.getArray()->getReference(2).getDynamicObject() + ->setProperty("channelFormat","MONO"); + juce::var stereoFold; + assert(NativeVerifiedSourcePatch::prepare(typedFold,2,"STEREO",5,7, + stereoPhysical,17,9,stereoFold).isEmpty()); + assert(armix::mixer::NativeDryRouteCommand::decode( + stereoFold,decoded,error)); + assert(armix::mixer::ChannelRoutingPlan::compile( + decoded.channels,stereoPhysical,routed,issue)); + assert(routed.effectiveFormats[2]==armix::mixer::ChannelFormat::mono); + assert(routed.foldStereoToMono[2]); + + // SOURCE/VST3 lifecycle migration at production M4 graph granularity: + // both verified physical pins belong to one unchanged device epoch. + // Selecting another MONO pin must preserve the very SAME prepared + // JUCE processor (state/editor/tail identity), not silently rebuild it. + juce::var beforeSwap; + assert(NativeVerifiedSourcePatch::prepare( + typed,6,"MONO",5,-1,stereoPhysical,17,9,beforeSwap).isEmpty()); + armix::mixer::NativeDryRouteCommand oldCommand; + assert(armix::mixer::NativeDryRouteCommand::decode( + beforeSwap,oldCommand,error)); + armix::mixer::PreparedRenderGraph oldPlan; + assert(armix::mixer::PreparedRenderGraph::compile( + oldCommand.channels,stereoPhysical,oldCommand.sends,oldPlan, + renderError,oldCommand.aux)); + auto firstFxGraph=std::make_unique( + oldPlan,64,64); + auto nativeFx=std::make_unique(2.f); + nativeFx->prepareToPlay(48000,64); + assert(firstFxGraph->install(6,std::move(nativeFx), + "CH07 native vendor FX","ch07-stable-vendor-id")); + const auto* originalInstance=firstFxGraph->instanceProcessor(6); + assert(originalInstance!=nullptr); + const std::array secondPin{{.1f,.2f,.3f,.4f}}; + const float* twoNativeInputs[]{mic.data(),secondPin.data()}; + std::array oldMainL{},oldMainR{}; + const auto beforeOldRender=heapCalls.load(std::memory_order_relaxed); + assert(firstFxGraph->process(twoNativeInputs,2,oldMainL.data(), + oldMainR.data(),4)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeOldRender); + assert(oldMainL[0]>0.f && oldMainR[0]>0.f); + juce::var afterSwap; + assert(NativeVerifiedSourcePatch::prepare( + beforeSwap,6,"MONO",7,-1,stereoPhysical,17,10,afterSwap).isEmpty()); + armix::mixer::NativeDryRouteCommand switchedCommand; + assert(armix::mixer::NativeDryRouteCommand::decode( + afterSwap,switchedCommand,error)); + armix::mixer::PreparedRenderGraph switchedPlan; + assert(armix::mixer::PreparedRenderGraph::compile( + switchedCommand.channels,stereoPhysical,switchedCommand.sends, + switchedPlan,renderError,switchedCommand.aux)); + auto secondFxGraph=std::make_unique( + switchedPlan,64,64); + assert(secondFxGraph->reuseAt(6,0,*firstFxGraph,0,"ch07-stable-vendor-id")); + assert(secondFxGraph->instanceProcessor(6)==originalInstance); + firstFxGraph.reset(); // old control graph retired; vendor must stay alive + assert(secondFxGraph->instanceProcessor(6)==originalInstance); + std::array newMainL{},newMainR{}; + const auto beforeNewRender=heapCalls.load(std::memory_order_relaxed); + assert(secondFxGraph->process(twoNativeInputs,2,newMainL.data(), + newMainR.data(),4)); + assert(heapCalls.load(std::memory_order_relaxed)==beforeNewRender); + assert(newMainL[0]>0.f && newMainR[0]>0.f); + // Exactly one FX call and one real new source: 0.1 / 0.25 amplitude. + assert(near(newMainL[0]/oldMainL[0],.4f)); + assert(near(newMainR[0]/oldMainR[0],.4f)); + assert(typedSource.getArray()->getReference(6) + .getProperty("mode","").toString()=="NONE"); +} + +// V8 S0: a C++ fixture, built with the SAME header serializer installed in +// JUCE WebView, never hand-maintained by GUI/FAT. No real audio device exists +// for this UNREADY fixture and it intentionally has no dynamic capabilities. +static void verifyNativePuzzleV8FixtureAndWire() { + using namespace armix::console; + PuzzleV8Snapshot fixtureSource; + fixtureSource.epoch="1"; + PuzzleV8Ack rejected; + rejected.requestId="native-fixture-session:1"; + rejected.deviceEpoch=fixtureSource.epoch; + const auto expected=PuzzleV8Wire::fixture(fixtureSource,rejected); + const auto fixtureFile=std::filesystem::path(__FILE__).parent_path()/ + "fixtures"/"console-v8-native-unready.json"; + std::ifstream source(fixtureFile,std::ios::binary); + assert(source.is_open()); + const std::string checked((std::istreambuf_iterator(source)), + std::istreambuf_iterator()); + // Git on Windows can checkout a one-line JSON fixture with CRLF. + // The native stdout generator deliberately emits canonical LF; accept + // only the OS newline conversion, never changed JSON data. + std::string canonical=checked; + if(canonical.size()==expected.size()+1 && + canonical.size()>=2 && canonical.substr(canonical.size()-2)=="\r\n") + canonical.erase(canonical.size()-2,1); + assert(expected==canonical); + const auto parsed=juce::JSON::parse(juce::String::fromUTF8(expected.c_str())); + assert(parsed.isObject()); + const auto events=parsed.getProperty("events",{}); + assert(events.getArray()&&events.getArray()->size()==4); + const auto snap=events.getArray()->getReference(0).getProperty("payload",{}); + const auto device=snap.getProperty("device",{}); + const auto graph=snap.getProperty("graph",{}); + const auto telem=snap.getProperty("telemetry",{}); + const auto cmd=events.getArray()->getReference(1).getProperty("payload",{}); + const auto ack=events.getArray()->getReference(2).getProperty("payload",{}); + const auto repeated=events.getArray()->getReference(3).getProperty("payload",{}); + assert(cmd.getProperty("requestId","").toString()== + ack.getProperty("requestId","").toString()); + assert(cmd.getProperty("deviceEpoch","").toString()=="1"); + assert(juce::JSON::toString(snap)==juce::JSON::toString(repeated)); + // The same installed JUCE bridge must produce this UNREADY event state. + const auto native=armix::console::LiveConsoleBridgeV6::snapshot(juce::var()); + assert(juce::JSON::toString(snap)==juce::JSON::toString(native)); + armix::console::LiveConsoleBridgeV6 runtime; + const auto realAck=runtime.rejectUnsupportedIntent(cmd,native); + assert(juce::JSON::toString(ack)==juce::JSON::toString(realAck)); + assert(static_cast(snap.getProperty("schemaVersion",0))==6); + assert(!static_cast(snap.getProperty("productionCallbackLive",true))); + assert(device.getProperty("enabledInputs",{}).getArray()->isEmpty()); + assert(device.getProperty("epoch","").toString()=="1"); + assert(device.getProperty("enabledOutputs",{}).getArray()->isEmpty()); + assert(device.getProperty("inputEndpoints",{}).getArray()->isEmpty()); + assert(device.getProperty("outputEndpoints",{}).getArray()->isEmpty()); + assert(device.getProperty("sampleRate",{}).isVoid()); + assert(graph.getProperty("channels",{}).getArray()->isEmpty()); + assert(graph.getProperty("capabilities",{}) + .getProperty("supportedOps",{}).getArray()->isEmpty()); + assert(!static_cast(telem.getProperty("mainPcmPresent",true))); + assert(ack.getProperty("requestId","").toString()=="native-fixture-session:1"); + assert(ack.getProperty("status","").toString()=="REJECTED"); + PuzzleV8Snapshot withPins; + withPins.inputs.push_back({5,0,"Mic \"1\"\n",true,.25}); + withPins.outputs.push_back({7,0,"PHYS OUT8",false,0.}); + const auto physical=juce::JSON::parse(juce::String::fromUTF8( + PuzzleV8Wire::snapshot(withPins).c_str())); + const auto physicalDev=physical.getProperty("device",{}); + const auto inputMask=physicalDev.getProperty("enabledInputs",{}); + const auto outputMask=physicalDev.getProperty("enabledOutputs",{}); + assert(inputMask.getArray()->size()==1 && + static_cast(inputMask.getArray()->getReference(0))==5); + assert(outputMask.getArray()->size()==1 && + static_cast(outputMask.getArray()->getReference(0))==7); + const auto in=physicalDev.getProperty("inputEndpoints",{}); + assert(in.getArray()->getReference(0).getProperty("label","").toString()== + "Mic \"1\"\n"); + assert(in.getArray()->getReference(0).getProperty("id","").toString()=="in:5"); + assert(static_cast(in.getArray()->getReference(0).getProperty("active",false))); + assert(static_cast(in.getArray()->getReference(0) + .getProperty("rawPeak",0.))==.25); +} + +// E2: native JUCE VST3 stays audible through a serial GROUP edit; a missing +// successor FX owner rejects atomically rather than deleting hosted processing. +static void verifyChannelIdGroupPreservesHostedFx() { + using Bank=DynamicChannelFxLeaseBank; + using Pub=DynamicNativeSessionPublisher; + constexpr std::uint64_t epoch=1007; + constexpr float center=.7071067811865475f; + DynamicAcceptedSession live; + DynamicGraphRequest route;route.physicalInputs=1;route.maxFrames=32; + ChannelEdit micCreate;micCreate.kind=ChannelEdit::Kind::add; + micCreate.position=0;micCreate.role=ChannelRole::input; + micCreate.format=ProcessingFormat::mono;micCreate.text="VOICE"; + ChannelEdit mainCreate=micCreate;mainCreate.position=1; + mainCreate.role=ChannelRole::main; + mainCreate.format=ProcessingFormat::stereo;mainCreate.text="MAIN"; + const std::array creates{micCreate,mainCreate}; + const auto created=live.edit(0,0,creates,route,epoch,epoch,true); + assert(created.ok()&&created.edit.createdIds.size()==2); + const auto voice=created.edit.createdIds[0],main=created.edit.createdIds[1]; + route.sources={{voice,0,-1,false}}; + ChannelEdit link;link.kind=ChannelEdit::Kind::setPrimaryOutput; + link.id=voice;link.target=main; + const std::array routeEdit{link}; + auto gain=std::make_unique(2.f); + gain->prepareToPlay(48000.,32); + Bank::Assignment assignment;assignment.id=voice; + assignment.format=ProcessingFormat::mono; + assignment.inserts.push_back(std::make_shared( + std::move(gain),"voice-gain","voice-gain",32)); + const auto token=assignment.inserts[0]->instanceId; + const std::array assignments{assignment}; + auto bank=std::make_shared(); + assert(Bank::prepare(epoch,2,assignments,*bank)==Bank::Fault::none); + const auto plan=[&](std::shared_ptr owner,std::uint64_t rev) { + Pub::FxPlan fx;fx.owner=std::static_pointer_cast(owner); + fx.context=owner.get(); + fx.render=+[](void* p,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(p))(id,l,r,n); + }; + fx.deviceEpoch=epoch;fx.graphRevision=rev;return fx; + }; + assert(live.edit(1,1,routeEdit,route,epoch,epoch,true,plan(bank,2)).ok()); + std::array input{},l{},rr{};input.fill(.2f); + const float* pins[]{input.data()}; + int fallbackCalls=0; + const auto noFallback=[&](ChannelId,float*,float*,int) noexcept { + ++fallbackCalls; + }; + const auto render=[&]() { + return live.render(epoch,pins,1,l.data(),rr.data(),32,false,noFallback); + }; + auto heapBefore=heapCalls.load(std::memory_order_relaxed); + assert(render()&&near(l[31],.2f*2.f*center)); + assert(heapCalls.load(std::memory_order_relaxed)==heapBefore); + const std::array selected{voice}; + const auto denied=live.createBusForSelected(2,2,selected,"VOCALS", + ChannelRole::group,route,epoch,epoch,true); + assert(!denied.ok()&&denied.edit.createdIds.empty()); + assert(denied.native.fault==Pub::Fault::invalidCandidate); + assert(live.acceptedGraphRevision()==2); + assert(render()&&near(l[31],.2f*2.f*center)); + auto nextBank=std::make_shared(); + assert(Bank::reuseRevision(epoch,3,*bank,*nextBank)==Bank::Fault::none); + assert(Bank::reuseRevision(epoch,2,*bank,*nextBank)==Bank::Fault::invalidEpoch); + assert((*nextBank->ownerForControl(voice,0))->instanceId==token); + const int pluginCount=GainFx::living; + const auto group=live.createBusForSelected(2,2,selected,"VOCALS", + ChannelRole::group,route,epoch,epoch,true,.25f,plan(nextBank,3)); + assert(group.ok()&&group.edit.createdIds.size()==1); + assert(live.acceptedGraphRevision()==3); + assert(live.acceptedRouting(epoch,3)->find(voice)->primaryOutput== + group.edit.createdIds.front()); + heapBefore=heapCalls.load(std::memory_order_relaxed); + assert(render()&&near(l[31],.2f*2.f*center)); + assert(heapCalls.load(std::memory_order_relaxed)==heapBefore); + assert(GainFx::living==pluginCount&&fallbackCalls==0); + assert(!live.setLiveMix(epoch,2,voice,0.f,0.f)); + live.unpublish();live.pollRetirement(); +} + +int main(int argc,char** argv) { + if(argc==2 && std::string(argv[1])=="--emit-console-s0-json") { + verifyNativePuzzleV8FixtureAndWire(); + armix::console::PuzzleV8Snapshot s; + armix::console::PuzzleV8Ack ack; + ack.requestId="native-fixture-session:1"; + ack.deviceEpoch=s.epoch; + std::cout<.3f); } + // Run M5 AFTER the legacy suite: older M4 tests use absolute global + // GainFx::living/released counters as their own lifetime oracle. Running + // M5 before them changes those historical baseline counts, not DSP. + // M5 additionally asserts zero heap and valid vendor leases itself. + verifyUniversalChannelIdFxLeaseAndLivePcm(); + verifyMU1LegacyM4FxFullMigrationAndMonitorPcm(); + verifyOccupiedExternalCh1Owner(); + verifySourceFormatIndependentPanPcmParity(); + verifyNativeConsoleWireRejectsUnsupportedM4AndPreservesEpoch(); + verifyFirstSoundOnePinNativeSourceDraft(); + verifyNativePuzzleV8FixtureAndWire(); + verifyChannelIdGroupPreservesHostedFx(); // Tests above use a real JUCE AudioProcessor processing seam. Vendor // VST3 formats and sound quality require separate Windows hardware FAT. } diff --git a/tests/live_graph_contract_test.mjs b/tests/live_graph_contract_test.mjs index 594c641cf..6edcd12f1 100644 --- a/tests/live_graph_contract_test.mjs +++ b/tests/live_graph_contract_test.mjs @@ -28,6 +28,22 @@ test('preset UI reflects callback-acknowledged state not queued state',()=>{ assert.match(m,/arMixNativePresetLoaded/); assert.match(b,/RECALL LIVE/); }); +test('single engine production selection forbids old VST processing in diagnostic fallback',()=>{ + const authority=readFileSync(new URL('../engine/core/NativeRenderAuthority.h',import.meta.url),'utf8'); + assert.match(authority,/enum class NativeRenderOwner/); + assert.match(authority,/failSilentUnpatched/); + assert.match(authority,/acceptedM4Session/); + assert.match(authority,/isolatedDiagnostic/); + assert.match(e,/NativeRenderAuthority::select\(/); + assert.match(e,/NativeRenderOwner::acceptedM4Session/); + const start=e.indexOf('// The only remaining stereo renderer is DIAGNOSTIC'); + const end=e.indexOf('const auto elapsedUs = clockMicros() - beginUs',start); + assert.ok(start>0 && end>start,'explicit diagnostic-only tail must exist'); + const fallback=e.slice(start,end); + assert.doesNotMatch(fallback,/processor->processBlock|MidiBuffer midi|make_unique|make_shared/, + 'no second legacy stereo FX chain may be executed from diagnostics'); +}); + test('ADD/REMOVE remain guarded while MOVE publishes physical-slot order',()=>{ assert.match(e,/fxMovePhase_\.load/); assert.match(e,/FxOrderPlan::moved/); @@ -36,13 +52,26 @@ test('ADD/REMOVE remain guarded while MOVE publishes physical-slot order',()=>{ assert.doesNotMatch(move,/detach\(|attach\(/); }); -test('bypass is sample-smoothed on audio callback without control-thread CPU work',()=>{ +test('bypass is sample-smoothed by one original CH1 DSP owner for M4 and native ChannelId',()=>{ assert.match(e,/bypassEnvelope/); - assert.match(e,/bypass\.request\(cycle\.graph->bypassFlags/); - assert.match(e,/bypass\.transitioning\(\)/); - assert.match(e,/dryScratch_\.setSize \(2, maxFrames/); - assert.match(e,/bypass\.next\(\)/); - assert.match(e,/bypass\.shouldProcessWet\(\)/); + const start=e.indexOf('static void renderOriginalChannelOneGraph('); + const legacy=e.indexOf('static void processLegacyChannelOne(',start); + const native=e.indexOf('static void processOwnedChannelOne(',legacy); + const end=e.indexOf('void audioDeviceIOCallbackWithContext',native); + assert.ok(start>=0&&legacy>start&&native>legacy&&end>native, + 'native and M4 must share the original CH1 sample-accurate DSP owner'); + const originalDSP=e.slice(start,legacy); + const adapters=e.slice(legacy,end); + assert.match(originalDSP,/bypass\.request\(graph\.bypassFlags/); + assert.match(originalDSP,/slot\.processor->processBlock\(buffer,midi\)/); + assert.match(originalDSP,/bypass\.transitioning\(\)/); + assert.match(originalDSP,/graph\.dryScratch\.getWritePointer\(0\)/); + assert.match(originalDSP,/bypass\.next\(\)/); + assert.match(originalDSP,/bypass\.shouldProcessWet\(\)/); + assert.match(e,/Graph\(\) \{ dryScratch\.setSize\(2,maxFrames,false,true,false\); \}/); + assert.match(adapters,/renderOriginalChannelOneGraph\(\*graph,left,right,frames\)/); + assert.match(adapters,/renderOriginalChannelOneGraph\(\s*\*static_cast\(token\)/); + assert.match(adapters,/fx\.owner=std::static_pointer_cast\(graphOwned_\)/); assert.doesNotMatch(e.slice(e.indexOf('bool setBypass'),e.indexOf('bool removeAt')),/detach\(|prepareToPlay|releaseResources/); }); @@ -52,7 +81,7 @@ test('R0B CH1 MOVE inside routed 10CH graph uses the same callback-boundary de-c assert.match(move,/FxOrderPlan::moved/); assert.match(move,/fxMovePendingOrder_\.store/); assert.doesNotMatch(move,/detach\(|attach\(|prepareToPlay|releaseResources/); - const begin=e.indexOf('if (dryRoutingLab_.active())',e.indexOf('callbackCount_.fetch_add')); + const begin=e.indexOf('if (renderOwner ==',e.indexOf('callbackCount_.fetch_add')); const end=e.indexOf('const bool enabled = monitor_',begin); const routed=e.slice(begin,end); assert.match(routed,/FxMoveRamp::gain\(\s*routedFxMove,i,samples\)/); @@ -79,7 +108,7 @@ test('R0B major milestone: ADD and REMOVE are prepared control-thread transactio assert.match(e,/ownPlugin\s*\(/); assert.match(e,/old\.reset\(\); \/\/ Vendor cleanup only on final CONTROL-owned reference/); assert.match(e,/handoff_\.stage\(stagedOwner_\.get\(\)\)/); - const callback=e.slice(e.indexOf('if (dryRoutingLab_.active())',e.indexOf('callbackCount_.fetch_add')), + const callback=e.slice(e.indexOf('if (renderOwner ==',e.indexOf('callbackCount_.fetch_add')), e.indexOf('const bool enabled = monitor_',e.indexOf('callbackCount_.fetch_add'))); assert.match(callback,/handoff_\.endCycle\(cycle\)/); assert.match(callback,/cycle\.fadeOut/); @@ -103,13 +132,14 @@ test('R0B B3 NORMAL output is fail-silent while FX graph retirement still progre const beginning=e.indexOf('void audioDeviceIOCallbackWithContext'); const fence=e.indexOf('if (!independent_.active()',beginning); const lease=e.indexOf('const auto cycle = handoff_.beginCycle()',beginning); - const failSilent=e.indexOf('if (activeDiagnosticRoute == armix::diagnostics::Route::normal',beginning); + const failSilent=e.indexOf('if (renderOwner ==',lease); const callbackMetrics=e.indexOf('const std::uint64_t beginUs = clockMicros()',beginning); assert.ok(beginning>=0 && fence>beginning && lease>fence && failSilent>lease && callbackMetrics>failSilent, 'DIRECT fence first, then FX cycle lease, then fail-silent native gate'); const gate=e.slice(failSilent,callbackMetrics); - assert.match(gate,/!dryRoutingLab_\.active\(\)/); + assert.match(e,/NativeRenderAuthority::select\(/); + assert.match(gate,/NativeRenderOwner::failSilentUnpatched/); assert.match(gate,/FloatVectorOperations::clear\(outputs\[c\], samples\)/); assert.match(gate,/outputPeakL_\.store\(0\.f/); assert.match(gate,/handoff_\.endCycle\(cycle\)/, diff --git a/tests/live_routing_ui_contract_test.mjs b/tests/live_routing_ui_contract_test.mjs index 7e3f9ac05..454b8e8e9 100644 --- a/tests/live_routing_ui_contract_test.mjs +++ b/tests/live_routing_ui_contract_test.mjs @@ -46,7 +46,7 @@ test("GUI exposes only truthful dry device routes and acknowledged commit",()=>{ }); test("STOP-race is fail closed: all outputs are written to silence without CH1 fallback",()=>{ - const enter=engine.indexOf("if (dryRoutingLab_.active())",engine.indexOf("callbackCount_.fetch_add")); + const enter=engine.indexOf("if (renderOwner ==",engine.indexOf("callbackCount_.fetch_add")); // Bound the entire routed branch by the first statement of the legacy // fallback, not by an informational comment that can change at each R0B slice. const end=engine.indexOf("const bool enabled = monitor_",enter); diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index f019319ad..0ca5ded0a 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -26,8 +26,8 @@ test('MS3A MAIN physical output patch stages through existing muted native route assert.match(gui,/s\.outputPorts/); assert.match(gui,/__arMixStageMainOutputs/); assert.match(gui,/\.arIOMainOutput/); - assert.match(gui,/Only native-ACKed MAIN\/MONITOR pairs can carry sound/); - assert.match(gui,/internal stereo FX returns/); + assert.match(gui,/Selection is DRAFT until native APPLY\/ACK/); + assert.match(gui,/AUX1–4 are internal FX returns/); assert.match(monitor,/window\.__arMixStageMainOutputs/); assert.match(monitor,/mainOutputs:draftMainOutputs/); assert.match(monitor,/routingDryApply/); @@ -188,7 +188,7 @@ test('PATCH1 operator-first mono and nonadjacent stereo stage into ONE native tr assert.match(gui,/window\.__arMixOpenAudioIO=openIO/); assert.match(gui,/if\(b\.dataset\.mixPatch==='input'\)openIO\('inputs',channel\)/); assert.match(gui,/matrixPorts\(s,'inputs'\)/); - assert.match(gui,/SAME NATIVE ROUTING/); + assert.match(gui,/ADVANCED · MANUAL INPUT CROSSPOINTS/); assert.match(gui,/A separate Windows capture endpoints cannot be silently combined|Separate Windows capture endpoints cannot be silently combined/); assert.match(css,/\.arIOQuickPatch\{/); assert.match(css,/\.arIOQuickRow\[data-state="draft"\]/); @@ -575,3 +575,25 @@ test('hardware input CH1/CH2/CH10 selectable on the mixer itself without an IO m assert.match(css,/\.arChannelQuickInput\{/); assert.doesNotMatch(css,/backdrop-filter|filter:blur/); }); + +test('Audio Setup first-sound workflow keeps hardware and routing distinct',()=>{ + const css=read('web/mixer-io.css'); + assert.match(gui,/1 · DEVICE/); + assert.match(gui,/2 · INPUT → CHANNEL/); + assert.match(gui,/3 · MAIN OUT/); + assert.match(gui,/focusedInput=0/); + assert.match(gui,/row.hidden=i!==focusedInput/); + assert.match(gui,/pair\[0\]==='STEREO'&&verified.length<2/); + assert.match(gui,/r.left===r.right/); + assert.match(gui,/INVALID STEREO · SELECT DISTINCT L\/R/); + assert.match(gui,/stage.textContent='FIX AS MONO'/); + assert.match(gui,/button.dataset.ioQuickFix==='1'\?'MONO'/); + assert.match(gui,/function stageQuickInput\(button\)/); + assert.match(gui,/commitSourceInOneGesture\(/); + assert.match(gui,/arIOSimpleMain/); + assert.match(gui,/__arMixStageMainOutputs/); + assert.match(gui,/ADVANCED · HARDWARE PORT MATRIX \(OPTIONAL\)/); + assert.match(css,/\.arIOQuickRow\[hidden\]\{display:none!important\}/); + assert.match(css,/\.arIOAdvancedMatrix:not\(\[open\]\)/); + assert.doesNotMatch(gui,/new AudioContext|AudioWorklet|createPluginInstance|processBlock/); +}); diff --git a/tests/mixer_io_smoke.py b/tests/mixer_io_smoke.py index 6f47d8cdb..9e7bfa670 100644 --- a/tests/mixer_io_smoke.py +++ b/tests/mixer_io_smoke.py @@ -22,9 +22,35 @@ async def main(): await page.goto((root/"web/index.html").as_uri()) assert await page.locator("#mixer .rack").count()==10 assert await page.locator("#mixer .arChannelBank").count()==10 + # The REAL M4 host, not the future v6 demo, opens one console: + # actual native selectors, six VST3 slots and four AUX controls + # coexist in every input strip without FX/ROUTE/SENDS switching. + assert await page.locator('#mixer').get_attribute('data-io-mode')=='CONSOLE' + assert await page.locator('[data-mix-mode="CONSOLE"]').get_attribute('aria-pressed')=='true' + assert await page.locator('#mixer .arBankSource:visible').count()==10 + assert await page.locator('#mixer .arBankOutput:visible').count()==10 + assert await page.locator('#mixer .rack .insert-slot').count()==60 + assert await page.locator('#mixer .arSendBank:visible').count()==10 + await page.screenshot(path='mixer-m4-unified-1366.png') + # Main is visually pinned during navigation across the 10 real strips. + # Do not accept a CSS "sticky" label if its pixels are offscreen. + main_geom=await page.evaluate("""() => { + const mixer=document.querySelector('#mixer'); + const master=document.querySelector('#masterLeft'); + const start=master.getBoundingClientRect(); + const frame=mixer.getBoundingClientRect(); + mixer.scrollLeft=99999; + const end=master.getBoundingClientRect(); + mixer.scrollLeft=0; + return {left:start.left,right:start.right,endLeft:end.left,endRight:end.right, + frameRight:frame.right,frameLeft:frame.left}; + }""") + assert main_geom['right']<=main_geom['frameRight']+2,main_geom + assert main_geom['left']>=main_geom['frameLeft']-2,main_geom + assert abs(main_geom['right']-main_geom['endRight'])<2,main_geom assert await page.locator('.arChannelSignalFlow [data-focus-step]').count()==4 assert 'NO NATIVE ACK' in await page.locator('[data-focus-source]').inner_text() - assert await page.locator("[data-mix-mode]").count()==3 + assert await page.locator("[data-mix-mode]").count()==4 status=await page.evaluate("""() => { const ch=Array.from({length:10},()=>({mode:'NONE',left:-1,right:-1,gain:.25,pan:0,main:true,mute:false,solo:false,fxId:''})); const auxes=Array.from({length:4},()=>({enabled:false,gain:1,main:true,mute:false,fxId:''})); @@ -137,7 +163,7 @@ async def main(): await page.locator('#arIOAudioPath [data-io-signal-check]').click() assert await page.locator('#arSignalOverlay').evaluate("(e)=>e.classList.contains('open')") await page.locator('#arSignalClose').click() - assert "LIVE" in await page.locator('[data-strip="0"] .arBankStage').inner_text() + assert "ROUTE ACK" in await page.locator('[data-strip="0"] .arBankStage').inner_text() assert 'Microphone 1' in await page.locator('[data-focus-source]').inner_text() assert 'MAIN' in await page.locator('[data-focus-out]').inner_text() # M2 Studio-style BUS: one existing empty native lane, no phantom @@ -281,6 +307,19 @@ async def main(): assert await page.locator('.arIODeviceDriverButton').count()==2 assert await page.locator('.arIODeviceDriverButton[aria-pressed="true"]').inner_text()=='ASIO' assert await page.locator('.arIODevicePatchMatrix').is_visible() + assert not await page.locator('.arIODevicePatchMatrix').evaluate('(e)=>e.open') + # No large software-input / crosspoint DOM until explicitly requested. + assert await page.locator('.arIODevicePatchMatrix .arIOMatrixCell').count()==0 + assert await page.locator('.arIODevicePins').is_visible() + await page.locator('.arIODevicePatchMatrix > summary').click() + assert await page.locator('.arIODevicePatchMatrix').evaluate('(e)=>e.open') + # Details toggle is asynchronous; rendering the costly matrix only + # AFTER toggle is intentional, not a race to be hidden by time.sleep. + await page.locator('.arIODeviceDirectMatrix > summary').wait_for(state='visible') + # Matrix itself is an opt-in nested inspector; its individual cells + # must be visible only after expanding that native crosspoint layer. + await page.locator('.arIODeviceDirectMatrix > summary').click() + await page.locator('.arIODevicePatchMatrix .arIOMatrixCell').first.wait_for(state='visible') assert await page.locator('.arIODevicePatchMatrix .arIOMatrixCell').count()>0 # FAST3 source one-gesture has already completed an ARM ACK above. # This separate DEVICE APPLY must produce ONE new guarded arm, not @@ -362,6 +401,7 @@ async def main(): assert await page.locator('.arIODeviceDriverButton[aria-pressed="true"]').inner_text()=='ASIO' await page.locator('[data-io-tab="inputs"]').click() assert await page.locator('#arIOBody .arIOQuickRow').count()==10 + assert await page.locator('[data-io-quick-row]:visible').count()==1 # Operator-first mapper is visible; crosspoint is explicitly advanced. assert await page.locator('#arIOQuickPatch, .arIOQuickPatch').count()==1 assert await page.locator('[data-io-quick-row]').count()==10 @@ -381,6 +421,11 @@ async def main(): # Preserve the pre-test accepted route for later AUX negative tests. await page.evaluate('()=>window.__arMixRevertMixerDraft()') await page.locator('[data-io-tab="outputs"]').click() + assert await page.locator('.arIOSimpleMain').is_visible() + assert await page.locator('.arIOMainOutput').count()==2 + assert await page.locator('.arIOAdvancedMatrix').count()==1 + if not await page.locator('.arIOAdvancedMatrix').evaluate('(e)=>e.open'): + await page.locator('.arIOAdvancedMatrix > summary').click() outputs=await page.locator('#arIOBody').inner_text() assert "HW OUT 1" in outputs and "HW OUT 2" in outputs,outputs assert await page.locator('[data-io-matrix-kind="outputs"]').count()==4 @@ -391,7 +436,7 @@ async def main(): assert duplicate['ok'] is False and 'different' in duplicate['error'],duplicate assert (await page.evaluate('()=>window.__arMixRouteView().draftMainOutputs'))==[1,0] await page.evaluate('()=>window.__arMixRevertMixerDraft()') - assert "AUX1" in outputs and "not physical" in outputs,outputs + assert "AUX1–4 are internal FX returns, not hardware ports" in outputs,outputs await page.locator('[data-io-tab="device"]').click() await page.evaluate("""() => window.__armixTestEmit('arMixAudioDeviceInventory',{ types:[{name:'ASIO',active:true,inputs:['Mic 1','Mic 2'],outputs:['Out 1','Out 2']}] @@ -679,7 +724,7 @@ async def main(): window.__armixTestEmit('arMixStatus',status); return status; }""",status) - assert "LIVE" in await page.locator('[data-strip="1"] .arBankStage').inner_text() + assert "ROUTE ACK" in await page.locator('[data-strip="1"] .arBankStage').inner_text() # Accepted source automatically begins the final guarded hardware # ARM. Reject ARM deliberately for this G5 structural/FX fixture: # the new source route remains accepted, output remains safely @@ -810,8 +855,12 @@ async def main(): }""",status) await page.locator('[data-io-open]').click() await page.locator('[data-io-tab="outputs"]').click() - # Exercise actual sparse-pin OUTPUT crosspoints, not hidden fallback dropdowns. + assert await page.locator('.arIOSimpleMain').is_visible() assert await page.locator('.arIOMainOutput').count()==2 + # Crosspoint remains available, but is no longer the normal workflow. + if not await page.locator('.arIOAdvancedMatrix').evaluate('(e)=>e.open'): + await page.locator('.arIOAdvancedMatrix > summary').click() + # Exercise actual sparse-pin OUTPUT crosspoints, not hidden fallback dropdowns. await page.locator('[data-io-matrix-kind="outputs"][data-io-matrix-row="0"][data-io-matrix-pin="4"]').click() await page.locator('[data-io-matrix-kind="outputs"][data-io-matrix-row="1"][data-io-matrix-pin="5"]').click() assert await page.evaluate("""()=>window.__arMixRouteView().draftMainOutputs.join(',')""")=='4,5' @@ -864,6 +913,8 @@ async def main(): await page.locator('[data-io-tab="inputs"]').click() assert await page.locator('.arIOQuickPatch').is_visible() assert await page.locator('[data-io-quick-row]').count()==10 + await page.locator('[data-io-jump]').select_option('2') + assert await page.locator('[data-io-quick-row]:visible').count()==1 assert await page.locator('[data-io-quick-row="2"] [data-io-quick-pin="left"] option').count()==5 # R7: each USE INPUT commits the existing guarded native route # automatically, without a second STAGE/MUTE/APPLY button ritual. @@ -891,7 +942,7 @@ async def main(): window.__armixTestEmit('arMixRoutingLabAck',{ok:true,state:lab}); window.__armixTestEmit('arMixStatus',status);return status; }""",status) - assert 'LIVE' in await ch3.locator('.arIOQuickState').inner_text() + assert 'ROUTE ACK' in await ch3.locator('.arIOQuickState').inner_text() await page.evaluate("""status=>window.__armixTestEmit('arMixAudioArmAck',{ ok:false,armed:false,deviceEpoch:status.dryRoutingLab.epoch, error:'Output kept safely muted during multi-source setup' @@ -900,6 +951,9 @@ async def main(): # Sparse driver pins 5/8 -> CH6 stereo, independent of CH3's # accepted mono processing and with no fabricated adjacent R pin. ch6=page.locator('[data-io-quick-row="5"]') + await page.locator('[data-io-jump]').select_option('5') + assert await ch6.is_visible() + assert await page.locator('[data-io-quick-row]:visible').count()==1 await ch6.locator('[data-io-quick-mode]').select_option('STEREO') await ch6.locator('[data-io-quick-pin="left"]').select_option('4') await ch6.locator('[data-io-quick-pin="right"]').select_option('7') @@ -923,7 +977,7 @@ async def main(): window.__armixTestEmit('arMixRoutingLabAck',{ok:true,state:lab}); window.__armixTestEmit('arMixStatus',status);return status; }""",status) - assert 'LIVE' in await ch6.locator('.arIOQuickState').inner_text() + assert 'ROUTE ACK' in await ch6.locator('.arIOQuickState').inner_text() await page.evaluate("""status=>window.__armixTestEmit('arMixAudioArmAck',{ ok:false,armed:false,deviceEpoch:status.dryRoutingLab.epoch, error:'Output intentionally stays muted in this fixture' @@ -943,6 +997,11 @@ async def main(): # DEVICE4: name one logical stereo INPUT over sparse verified hardware, # then rename and remove it. Metadata must not emit routingDryApply. await page.locator('[data-io-tab="device"]').click() + if not await page.locator('.arIODevicePatchMatrix').evaluate('(e)=>e.open'): + await page.locator('.arIODevicePatchMatrix > summary').click() + # Demand-mounted logical-input matrix is appended on the details + # toggle; wait for real UI state instead of assuming synchronous DOM. + await page.locator('.arIOSoftwareGrid').wait_for(state='visible') assert await page.locator('.arIOSoftwareGrid').is_visible() count_before=await page.evaluate("""()=>window.__armixTestActions.filter(x=> x.name==='arMixAction'&&x.data.action==='routingDryApply').length""") @@ -1159,6 +1218,74 @@ async def main(): assert len(armed)==1 and armed[0]['data']['expectedEpoch']==31,armed assert armed[0]['data']['expectedRevision']==3,armed await qp.close() + + # Field screenshot regression: one enabled VB-Cable/recording pin may + # ONLY be selected as mono. Do not fabricate a second R endpoint. + one=await browser.new_page(viewport={"width":1366,"height":768}) + await one.add_init_script("""(() => { + const listeners={}; + window.__armixTestActions=[]; + window.__JUCE__={backend:{ + addEventListener(name,fn){(listeners[name]??=[]).push(fn)}, + emitEvent(name,data){window.__armixTestActions.push({name,data})} + }}; + window.__armixTestEmit=(name,datum)=>(listeners[name]||[]).forEach(fn=>fn(datum)); + })();""") + await one.goto((root/"web/index.html").as_uri()) + await one.evaluate("""() => { + const channels=Array.from({length:10},()=>({ + mode:'NONE',left:-1,right:-1,gain:.25,pan:0,main:true, + mute:false,solo:false,fxId:''})); + const auxes=Array.from({length:4},()=>({ + enabled:false,gain:1,main:true,mute:false,fxId:''})); + const lab={active:true,ready:true,epoch:51,revision:3, + ports:[{port:0,label:'CABLE Output capture pin 1'}], + outputPorts:[0,1], + acceptedRoute:{deviceEpoch:51,channels,auxes,sends:[]}}; + window.__armixTestEmit('arMixStatus',{ + connected:true,directRouteAuthorized:true,driver:'Windows Audio', + rate:48000,buffer:480,monitor:false,masterMute:false, + chainCount:0,dryRoutingLab:lab}); + window.__armixTestEmit('arMixAudioDeviceInventory',{ + currentType:'Windows Audio', + active:{backend:'Windows Audio', + captureDevice:'CABLE Output (VB-Audio Virtual Cable)', + playbackDevice:'Realtek HD Audio 2nd output',open:true, + authorized:true,deviceGeneration:51,enabledInputs:[0], + enabledOutputs:[0,1],inputNames:['CABLE recording'], + outputNames:['Speakers L','Speakers R']}, + types:[{name:'Windows Audio',active:true,separate:true, + inputs:['CABLE Output (VB-Audio Virtual Cable)'], + outputs:['Realtek HD Audio 2nd output']}]}); + }""") + await one.locator('#audioSetupBtn').click() + # Actual native Windows UI uses a compact right-side hardware drawer, + # not the old centered 920px blocking routing wizard. + drawer=await one.locator('#arIOOverlay .arIOWindow').bounding_box() + assert drawer and drawer['width']<=600,drawer + assert abs(drawer['x']+drawer['width']-1366)<2,drawer + assert await one.locator('.arIODevicePin').count()==3 + assert 'MONO ONLY' in await one.locator('.arIOPinHeading').inner_text() + assert not await one.locator('.arIODevicePatchMatrix').evaluate('(e)=>e.open') + await one.locator('[data-io-tab="inputs"]').click() + assert await one.locator('[data-io-quick-row]:visible').count()==1 + ch1=one.locator('[data-io-quick-row="0"]') + assert await ch1.locator('[data-io-quick-mode] option[value="STEREO"]').is_disabled() + await ch1.locator('[data-io-quick-mode]').select_option('MONO') + await ch1.locator('[data-io-quick-pin="left"]').select_option('0') + await ch1.locator('[data-io-quick-stage]').click() + sent=await one.evaluate("""() => window.__armixTestActions.filter( + x=>x.name==='arMixAction'&&x.data.action==='routingDryApply')""") + assert len(sent)==1,sent + assert sent[0]['data']['value']['channels'][0]['mode']=='MONO',sent + assert sent[0]['data']['value']['channels'][0]['left']==0,sent + assert sent[0]['data']['value']['channels'][0]['right']==-1,sent + # A pending routing command does not claim input PCM, MAIN sound, or + # output ARM. These require native acceptance and capture telemetry. + assert not await one.evaluate("""() => window.__armixTestActions.some( + x=>x.data?.action==='monitor'&&x.data.value===true)""") + await one.screenshot(path='audio-setup-one-pin-1366.png') + await one.close() await browser.close() print("PASS: G1/G2 + G3 real PRE/POST draft, AUX return, 0-gain bypass, native ACK/reject/revert, stable rack and 3 viewports") diff --git a/tests/mixer_routing_plan_test.cpp b/tests/mixer_routing_plan_test.cpp index 19517fb1c..248df8046 100644 --- a/tests/mixer_routing_plan_test.cpp +++ b/tests/mixer_routing_plan_test.cpp @@ -400,7 +400,7 @@ static void verifyDynamicPreparedPcm() { ChannelEdit solo;solo.kind=Kind::setSolo;solo.id=ids[10];solo.enabled=true; assert(bank.edit(bank.revision(),std::span(&solo,1)).ok()); assert(DynamicPreparedMixerBlock::compile(bank,request,renderer,error)); - assert(renderer.activeChannels()==2); // CH11 + MAIN only + assert(renderer.activeChannels()==6); // 5 sources retain VST tails; SOLO gates PCM assert(renderer.process(physical,2,l.data(),r.data(),32,fx)); assert(close(l[0],.4f*center)); solo.enabled=false; @@ -522,7 +522,7 @@ static void verifyDynamicDualBusPcm() { muteMain.enabled=true; assert(bank.edit(bank.revision(),std::span(&muteMain,1)).ok()); assert(DynamicPreparedMixerBlock::compile(bank,req,live,error)); - assert(live.activeChannels()==3); // CH1, CH32 and MONITOR + assert(live.activeChannels()==5); // MAIN mute retains tails; MONITOR stays independent assert(live.process(inputs,3,mainL.data(),mainR.data(),64,fx, monL.data(),monR.data())); assert(mainL[0]==0.f && mainR[0]==0.f); @@ -690,6 +690,50 @@ static void verifyLegacyToDynamicProductionPcmParity() { } + +static void verifyRealtimeFaderRampAcrossShortCallbacks() { + using namespace armix::mixer; + const std::array pins{0,1}; + ChannelRoutingConfig routing; + routing.stripsAndMaster.strips[0]= + {SourceMode::mono,0,-1,1.f,0.f,false,false}; + SendRequest sends; + sends.toMaster[0]=true; + PreparedRenderGraph graph; + RenderError error; + assert(PreparedRenderGraph::compile(routing,pins,sends,graph,error)); + PreparedMixerBlock block(graph,64); + RealtimeStripControls controls; + assert(controls.set(0,1.f,0.f,true,false,false)); + std::array mic{},unused{},left{},right{}; + mic.fill(.8f); + const float* sources[]={mic.data(),unused.data()}; + const auto noFx=[](int,float*,float*,int) noexcept {}; + const auto render=[&](int frames) { + left.fill(0.f);right.fill(0.f); + return block.process(sources,2,left.data(),right.data(),frames, + noFx,nullptr,&controls); + }; + assert(render(4)); + const float baseline=left[0]; + assert(baseline>.01f && close(right[3],baseline)); + assert(controls.set(0,0.f,0.f,true,false,false)); + assert(render(4)); + assert(close(left[3],baseline*60.f/64.f,3.e-5f)); + assert(render(16)); + assert(close(left[15],baseline*44.f/64.f,3.e-5f)); + assert(render(32)); + assert(close(left[31],baseline*12.f/64.f,3.e-5f)); + assert(render(12)); + assert(close(left[11],0.f,3.e-5f)); + // Mid-show fader reversal must not jump to the last requested target. + assert(controls.set(0,1.f,0.f,true,false,false)); + assert(render(4)); + assert(close(left[3],baseline*4.f/64.f,3.e-5f)); + assert(render(60)); + assert(close(left[59],baseline,3.e-5f)); +} + static void verifyRealtimeAuxPostGainWithoutGraphRebuild() { using namespace armix::mixer; const std::array pins{0,1}; @@ -798,8 +842,15 @@ static void verifyRealtimeAuxMasterPcmBothOutputs() { assert(!block.setAuxBusGain(0,std::numeric_limits::quiet_NaN())); assert(close(block.auxBusGain(0),0.f)); assert(close(block.plan().aux.buses[0].gain,1.f)); // topology immutable - // Legacy offline/no-live-control path still uses immutable compiled gain. + // Explicit AUX automation remains live even without a separate strip + // controls object. It MUST NOT silently fall back to stale compiled gain + // because older physical/native paths do not always pass that object. assert(block.process(inputs,2,left.data(),right.data(),64,noFx)); + assert(close(left[0],0.f)); + // A newly prepared graph starts at its own immutable initial gain: + // structural transaction/Show recall does not leak old AUX state. + PreparedMixerBlock freshlyPrepared(graph,64); + assert(freshlyPrepared.process(inputs,2,left.data(),right.data(),64,noFx)); assert(close(left[0],initial)); } @@ -969,6 +1020,7 @@ int main() { verifyDynamicChannelIdLiveControls(); verifyDynamicNativeSessionPublication(); verifyStudioConsoleBusBatchPcm(); + verifyRealtimeFaderRampAcrossShortCallbacks(); verifyRealtimeAuxMasterPcmBothOutputs(); verifyRealtimeAuxPostGainWithoutGraphRebuild(); verifyLegacyToDynamicProductionPcmParity(); diff --git a/tests/mixer_shell_geometry_smoke.py b/tests/mixer_shell_geometry_smoke.py index c6725308a..7b22302ad 100644 --- a/tests/mixer_shell_geometry_smoke.py +++ b/tests/mixer_shell_geometry_smoke.py @@ -14,7 +14,7 @@ async def main(): await page.locator('.left-rail [data-mix-mode="FX"]').wait_for() assert await page.locator('.toolbar-actions .nav [data-view]').count()==3 assert await page.locator('.toolbar-actions [data-native-action="audioSetup"]').count()==0 - assert await page.locator('.left-rail [data-mix-mode]').count()==3 + assert await page.locator('.left-rail [data-mix-mode]').count()==4 assert await page.locator('.left-rail [data-my-sounds]').count()==1 assert await page.locator('.left-rail [data-plugin-manager]').count()==1 assert await page.locator('.left-rail #audioSetupBtn').count()==1 @@ -22,6 +22,7 @@ async def main(): assert await page.locator('.workbench > .arMixerBankBar').count()==0 assert await page.locator('.arRailModeSection > .arMixerBankBar').count()==1 assert await page.locator('#mixer > .strip').count()==11 + assert await page.locator('#mixer').get_attribute('data-io-mode')=='CONSOLE' async def geometry(): return await page.evaluate("""() => { @@ -95,6 +96,50 @@ async def assert_linked(mode,width,height): await page.locator('.left-rail [data-mix-mode="FX"]').click() assert abs(await assert_linked('FX RESTORE',width,height)-heights['FX'])<1.1 + # Visual acceptance of the REAL Console (not the isolated #278 source): + # at desktop widths CH01..CH10 and pinned MAIN share a viewport; no + # wrapped identity, no invisible overlapping labels or repeated Add FX. + await page.locator('.left-rail [data-mix-mode="CONSOLE"]').click() + for width,height in [(1366,768),(1440,820),(1680,900),(1024,720)]: + await page.set_viewport_size({"width":width,"height":height}) + await page.evaluate("document.getElementById('mixer').scrollLeft=0") + verdict=await page.evaluate("""() => { + const m=document.querySelector('#mixer').getBoundingClientRect(); + const main=document.querySelector('#masterLeft').getBoundingClientRect(); + const strips=[...document.querySelectorAll('#mixer > .strip[data-strip]')]; + const heads=strips.map(s=>{ + const el=s.querySelector('.ch-id'),nr=el.querySelector('.arChannelNumber'), + btn=el.querySelector('.arChannelTopIdentity'), + mode=el.querySelector('.arFormatBadge'); + const h=el.getBoundingClientRect(),n=nr.getBoundingClientRect(), + b=btn.getBoundingClientRect(),f=mode.getBoundingClientRect(); + return {h:h.height,inside:n.left>=h.left-1&&f.right<=h.right+1&& + b.left>=n.right-2&&b.right<=f.left+2, + single:n.bottom<=h.bottom+1&&b.bottom<=h.bottom+1&&f.bottom<=h.bottom+1, + ellipsis:getComputedStyle(btn.querySelector('.arChannelTopName')).textOverflow}; + }); + return {width:window.innerWidth,mainVisible:main.left>=m.left-2&&main.right<=m.right+2, + lastVisible:strips[9].getBoundingClientRect().right<=main.left+2, + headProblems:heads.filter(x=>!x.inside||!x.single||x.h<27||x.ellipsis!=='ellipsis'), + visibleSources:strips.filter(s=>{const r=s.getBoundingClientRect(); + return r.left>=m.left-2&&r.right<=main.left+2}).length, + repeatedAdd:document.querySelectorAll('#mixer .strip[data-strip="0"] .rack .insert-slot:has(.insert.empty)') + .length, + displayedAdd:[...document.querySelectorAll('#mixer .strip[data-strip="0"] .rack .insert-slot:has(.insert.empty)')] + .filter(el=>getComputedStyle(el).display!=='none').length}; + }""") + assert verdict['mainVisible'],('MAIN obscured',verdict) + assert not verdict['headProblems'],('identity clip/overlap/wrap',verdict) + assert verdict['displayedAdd']<=1,('repeated ADD FX',verdict) + if width>=1366: + assert verdict['lastVisible'],('CH10 clipped by MAIN',verdict) + assert verdict['visibleSources']==10,('not ten visible strips',verdict) + if width in (1366,1440,1680): + await page.screenshot(path=('mixer-shell-compact-1366.png' if width==1366 else + 'mixer-design-review-1440.png' if width==1440 else 'mixer-g1-g2-1680.png')) + await page.set_viewport_size({"width":1024,"height":720}) + await page.locator('.left-rail [data-mix-mode="FX"]').click() + # Parent view changes still work; click rail mode from PATCH to return MIX. await page.locator('[data-view="SIGNAL FLOW"]').click() assert await page.locator('#mixer').evaluate("(e)=>e.classList.contains('hidden')") @@ -104,7 +149,7 @@ async def assert_linked(mode,width,height): # Full repaint must recreate only strip internals, not left-rail controls. await page.evaluate('renderMixer()') - assert await page.locator('.left-rail [data-mix-mode]').count()==3 + assert await page.locator('.left-rail [data-mix-mode]').count()==4 assert await page.locator('#mixer > .strip').count()==11 await assert_linked('RENDER',1024,720) assert not errors,errors @@ -112,4 +157,10 @@ async def assert_linked(mode,width,height): print("PASS: 11 shared fader tracks, 4 viewport sizes, 3 banks, rail navigation and repaint") if __name__=="__main__": - asyncio.run(main()) + # Execute the v8 native-producer fixture replay through real Chromium + # within this existing GUI smoke job; no second workflow/CI matrix. + from operator_console_v6_smoke import main as native_console_smoke + async def run_gui_suite(): + await main() + await native_console_smoke() + asyncio.run(run_gui_suite()) diff --git a/tests/native_artifact_packaging_contract_test.mjs b/tests/native_artifact_packaging_contract_test.mjs index 03adc7b02..ad366619e 100644 --- a/tests/native_artifact_packaging_contract_test.mjs +++ b/tests/native_artifact_packaging_contract_test.mjs @@ -134,3 +134,70 @@ test('FAT ZIP uses current single-APPLY physical first-sound guide',()=>{ for(const entry of ['10 input channels + 4 AUX','OUTPUT_ONLY_TONE','CAPTURE_ONLY','COPY FULL REPORT','30 minutes','no separate manual START AUDIO']) assert.ok(quick.includes(entry),entry); }); + +test('sole ENGINE #266 may upload an unqualified, exact-SHA physical FAT ZIP',()=>{ + const upload=workflow.split('uses: actions/upload-artifact@v4')[1]||''; + assert.ok(upload.includes('milestone/m5-universal-channelid-vst3-lease-migration-20261101')); + assert.ok(!upload.includes('milestone/m4-unified-native-multichannel-fx-20261101')); + assert.ok(upload.includes('ArSonMix-ENGINE-10CH4AUX-EXPERIMENTAL-Hardware-FAT-Windows-x64')); + assert.match(upload,/if-no-files-found: error/); + assert.ok(workflow.indexOf('ctest --test-dir build -C Release --output-on-failure')< + workflow.indexOf('uses: actions/upload-artifact@v4')); + assert.ok(workflow.indexOf('scripts/verify_native_windows_artifact.ps1')< + workflow.indexOf('uses: actions/upload-artifact@v4')); + const guide=read('docs/FIRST_SOUND_FAT_QUICKSTART_20261101.md'); + assert.match(guide,/single canonical ENGINE #266 branch/); + assert.match(guide,/10CH \+ 4AUX/); + assert.match(guide,/sourceCommit/); + assert.match(guide,/exeSha256/); +}); + +test('native sourceCommit attest matches GitHub PR head and exact compiled source',()=>{ + const shaRef="ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}"; + assert.ok(workflow.includes(shaRef)); + assert.match(workflow,/ENGINE SOURCE SHA MISMATCH/); + assert.match(packaging,/\$gitSha = \(\& git rev-parse HEAD\)\.Trim\(\)/); + assert.match(verify,/manifest\.sourceCommit/); +}); + +test('field FAT collector is packaged, checked against source + ZIP hash, never certifies audio',()=>{ + const collector=read('scripts/collect_hardware_fat_windows.ps1'); + for(const part of ['OUTPUT_ONLY_TONE','CAPTURE_ONLY','DRY_THROUGH_0FX','LIVE_THROUGH_1FX','FAT_RUNS.json', + 'FAT_SUMMARY.json','elapsedSeconds','reportSha256','hardwareCertified=$false', + 'Get-FileHash','sourceCommit','PSScriptRoot']) assert.ok(collector.includes(part),part); + assert.match(packaging,/fatCollectorSha256 = /); + assert.match(packaging,/ArSonMix-Hardware-FAT\.ps1/); + assert.match(verify,/manifest\.fatCollectorSha256/); + assert.match(verify,/ZIP field collector SHA mismatch/); + assert.match(verify,/Missing FAT collector inside ZIP/); + assert.doesNotMatch(collector,/AudioDeviceManager|setAudioDeviceSetup|startAudio|armOutput|backend\.emitEvent/i); + assert.match(workflow,/ParseFile\('scripts\/collect_hardware_fat_windows\.ps1'/); +}); + +test('joined FAT 1FX compares the same verified hardware as witnessed 0FX, never self-certifies',()=>{ + const script=read('scripts/collect_hardware_fat_windows.ps1'); + // The field collector is an *operator evidence journal*, not a fake VST3 + // host. Start must fail BEFORE a 30-minute soak on mismatched drivers. + for(const required of [ + "[ValidateRange(0,8)][int]$FxCount=0", + "[string]$Vst3Name=''", + "$Mode -eq 'LIVE_THROUGH_1FX'", + "$FxCount -ne 1", + "the active native VST3 rack", + "Record a completed 30-minute wired 0FX baseline", + "1FX must use the identical ASIO/WASAPI device", + "backend, clock, buffer and physical routes must match", + "operatorReportedFxCount=$FxCount", + "operatorReportedVst3Name=$Vst3Name.Trim()", + "fxComparisonSource='OPERATOR_REPORTED_ONLY'", + "hardwareCertified=$false", + "physicalAudibilityVerifiedBySoftware=$false" + ]) assert.ok(script.includes(required),required); + assert.match(script,/\$baseline\[0\]\.elapsedSeconds -lt 1800/); + assert.match(script,/\$base\.captureEndpoint -ne \$CaptureEndpoint/); + assert.match(script,/\$base\.renderEndpoint -ne \$RenderEndpoint/); + assert.match(script,/\$base\.capturePins -join ','/); + assert.match(script,/\$base\.renderPins -join ','/); + assert.match(script,/\$run\.elapsedSeconds -lt 1800/); + assert.doesNotMatch(script,/AudioDeviceManager|setAudioDeviceSetup|startAudio|armOutput|backend\.emitEvent/i); +}); diff --git a/tests/native_embedded_gui_assets_contract_test.mjs b/tests/native_embedded_gui_assets_contract_test.mjs new file mode 100644 index 000000000..4c02f8c29 --- /dev/null +++ b/tests/native_embedded_gui_assets_contract_test.mjs @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Integration FAT gate: the physical Windows JUCE executable must serve +// the exact GUI assets used by the joined operator console, OFFLINE. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync,existsSync} from 'node:fs'; +const read=p=>readFileSync(p,'utf8'); +const cmake=read('CMakeLists.txt'); +const host=read('src/Main.cpp'); +const html=read('web/index.html'); +const css=read('web/mixer-layout.css'); +const packageScript=read('scripts/package_native_windows.ps1'); +const verify=read('scripts/verify_native_windows_artifact.ps1'); +const images=[ + 'assets/fader-silver2.png', + 'assets/faders/FADER-ARI-SILVER.png', + 'assets/faders/FADER-ARI-ROSEGOLD.png', + 'assets/faders/FADER-ARI-GOLD.png', + 'assets/pan/PAN-SLIDER.png', + 'assets/knob-ICON.svg' +]; +test('joined native executable embeds actual operator hardware-control JS',()=>{ + assert.match(html,/')); +assert.ok(html.includes('')); +assert.ok(html.includes('')); +console.log('PASS: V6 native Console material, dual identity, guarded inline rename, bank arrows and standalone parity'); diff --git a/tests/p0_diagnostic_contract_test.mjs b/tests/p0_diagnostic_contract_test.mjs index 417ebd0a8..f44fd5a20 100644 --- a/tests/p0_diagnostic_contract_test.mjs +++ b/tests/p0_diagnostic_contract_test.mjs @@ -27,7 +27,12 @@ test('audio callback isolates low-amplitude oscillator from input and VST3',()=> assert.match(engine,/const bool captureTest = route == armix::diagnostics::Route::captureOnly/); assert.match(engine,/diagnosticTone_\.next \(audible\)/); assert.match(engine,/if \(!toneTest\)/); - assert.match(engine,/if \(!dry\)/); + const start=engine.indexOf('// The only remaining stereo renderer is DIAGNOSTIC'); + const end=engine.indexOf('const auto elapsedUs = clockMicros() - beginUs',start); + assert.ok(start>0&&end>start,'isolated diagnostics must have an explicit owner'); + assert.doesNotMatch(engine.slice(start,end), + /processor->processBlock|MidiBuffer midi/, + 'test tone and capture-only must never enter a legacy VST processor'); assert.match(osc,/0\.0316227766/); assert.doesNotMatch(osc,/new |malloc\(|std::vector|mutex|lock_guard|fwrite\(/); assert.match(build,/P0DiagnosticTone/); diff --git a/tests/realtime_control_test.cpp b/tests/realtime_control_test.cpp index 0cb920ab9..11d3b5ea0 100644 --- a/tests/realtime_control_test.cpp +++ b/tests/realtime_control_test.cpp @@ -1,5 +1,10 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/core/RealtimeControl.h" +#include "../engine/core/PreparedMixerBlock.h" +#include "../engine/core/RealtimeRenderPermit.h" +#include "../engine/core/RealtimeRoutePublisher.h" +#include "../engine/core/NativeRenderAuthority.h" +#include #include #ifdef NDEBUG #undef NDEBUG @@ -12,6 +17,90 @@ #include using namespace armix::rt; int main(){ + // Production cannot fall through to a second stereo/VST mixer. The + // only old stereo path is explicitly test/diagnostic and disconnected + // from an accepted native M4 route. + using Owner=armix::mixer::NativeRenderOwner; + using Authority=armix::mixer::NativeRenderAuthority; + assert(Authority::select(true,false)==Owner::failSilentUnpatched); + assert(Authority::select(true,true)==Owner::acceptedM4Session); + assert(Authority::select(false,true)==Owner::acceptedM4Session); + assert(Authority::select(false,false)==Owner::isolatedDiagnostic); + assert(!Authority::mayRunDiagnostic( + Authority::select(false,true))); + + // M5 LIVE (the installed M4 callback, not only prepared ChannelId): + // all 4 controls change in ONE atomic, while 2 threads run 200k + // opposing GUI gestures. RT must see either complete gesture A or B; + // no left from A with right/MUTE/SOLO from B. + using Controls=armix::mixer::RealtimeStripControls; + Controls atomicControls; + const auto u=atomicControls.read(2); + assert(std::fabs(u.left-1.f)<1e-6f && std::fabs(u.right-1.f)<1e-6f); + assert(!u.mute && !u.solo); + assert(atomicControls.set(2,.5f,-1.f,false,false,true)); + const auto a=atomicControls.read(2); + assert(std::fabs(a.left-.5f)<1e-6f && std::fabs(a.right)<1e-6f); + assert(!a.mute && a.solo); + assert(atomicControls.set(2,.8f,1.f,false,true,false)); + const auto b=atomicControls.read(2); + assert(std::fabs(b.left)<1e-6f && std::fabs(b.right-.8f)<1e-6f); + assert(b.mute && !b.solo); + std::atomic badMixed{false}; + constexpr int gestures=200000; + std::thread ctl([&]{ + for(int k=0;k gateHeld{false},releaseGate{false}; + std::thread activeRender([&] { + armix::rt::RealtimeRenderPermit permit(renderGate); + assert(static_cast(permit)); + gateHeld.store(true,std::memory_order_release); + while(!releaseGate.load(std::memory_order_acquire)) + std::this_thread::yield(); // TEST thread only; never real AUDIO + }); + while(!gateHeld.load(std::memory_order_acquire)) + std::this_thread::yield(); + for(int i=0;i<20000;++i) { + armix::rt::RealtimeRenderPermit rejected(renderGate); + assert(!static_cast(rejected)); // never wait, render twice, lock + } + releaseGate.store(true,std::memory_order_release); + activeRender.join(); + { + armix::rt::RealtimeRenderPermit reentered(renderGate); + assert(static_cast(reentered)); + } + std::cout<<"PASS: single M4/ChannelId RT renderer, 20000 duplicate callbacks fail closed\\n"; + SpscQueue q; int value=-1; assert(!q.tryPop(value)); @@ -51,6 +140,43 @@ int main(){ checkPan(0.f,0.f,1.f,0.f,1.f); checkPan(0.f,1.f,0.f,1.f,0.f); std::cout<<"PASS: native stereo pan centre, extremes, half-pan and unit-gain dual-mono\n"; + + // M1: retired FX/PCM snapshots remain owned until callbacks release + // their leases; a full bounded queue rejects instead of growing memory. + struct RetireProbe { + std::atomic* counter; + explicit RetireProbe(std::atomic& c):counter(&c){} + ~RetireProbe(){counter->fetch_add(1,std::memory_order_relaxed);} + }; + std::atomic destroyed{0}; + RealtimeRoutePublisher publisher; + const auto publish=[&](std::uint64_t revision) { + auto next=std::make_unique::Snapshot>(); + next->deviceEpoch=7;next->graphRevision=revision; + next->prepared=std::make_unique(destroyed); + return publisher.publish(std::move(next),revision-1,7); + }; + using Result=RealtimeRoutePublisher::Result; + assert(publish(1)==Result::applied); + { + auto lease=publisher.acquire(); + assert(lease.get(7)&&lease.get(7)->graphRevision==1); + assert(publish(2)==Result::applied); + assert(publish(3)==Result::applied); + assert(publisher.pendingRetirements()==2); + assert(publish(4)==Result::retirementFull); + assert(destroyed.load(std::memory_order_relaxed)==1); + assert(lease.get(7)->graphRevision==1); + } + assert(publisher.pollRetirement()); + assert(publisher.pendingRetirements()==0); + assert(destroyed.load(std::memory_order_relaxed)==3); + assert(publish(4)==Result::applied); + publisher.unpublish(); + assert(publisher.pollRetirement()); + // Three accepted snapshots + one rejected admission + final fourth + // accepted snapshot: all five owners are reclaimed (no leak/double free). + assert(destroyed.load(std::memory_order_relaxed)==5); // Runtime contract for the exact RT graph publication helper. struct FakeGraph { int id; }; FakeGraph old{1}, next{2}, third{3}; diff --git a/tests/realtime_ten_channel_controls_test.cpp b/tests/realtime_ten_channel_controls_test.cpp index 63d4fb1b8..0100c1b61 100644 --- a/tests/realtime_ten_channel_controls_test.cpp +++ b/tests/realtime_ten_channel_controls_test.cpp @@ -98,8 +98,11 @@ int main() { { auto lease=publisher.acquire(); assert(lease.get(4)&&lease.get(4)->prepared->identity==42); - assert(near(lease.get(4)->prepared->params.at(3).left.load(),.4f)); // stereo pan +20% reduces LEFT - assert(near(lease.get(4)->prepared->params.at(3).right.load(),.5f)); + // Read the complete accepted M4 GUI control once. Never recover + // independent left/right atomics (which can tear during pan drags). + const auto state=lease.get(4)->prepared->params.read(3); + assert(near(state.left,.4f)); // stereo pan +20% reduces LEFT + assert(near(state.right,.5f) && !state.mute && !state.solo); } publisher.unpublish(); assert(!publisher.updateActiveControl(4,1,update)); diff --git a/tests/reconciled_gui_engine_contract_test.mjs b/tests/reconciled_gui_engine_contract_test.mjs index d67b473fb..92b8f8535 100644 --- a/tests/reconciled_gui_engine_contract_test.mjs +++ b/tests/reconciled_gui_engine_contract_test.mjs @@ -61,7 +61,14 @@ test('JUCE native resources track the approved calibrated GUI without maintainin for (const resource of ['index_html','styles_css','pluginui_css','app_js','pluginui_js','bridge_js','monitor_js']) { assert.ok(cpp.includes('BinaryData::'+resource),resource+' missing from WebView provider'); } - assert.ok(css.endsWith(sourceCss), 'native CSS must end with its authoritative calibration module'); + // The approved V5 hardware-key overlay is intentionally appended AFTER + // the existing gain/meter calibration source. Exact calibration bytes, + // ordering and standalone parity remain checked: not a looser visual test. + const index=css.indexOf(sourceCss); + assert.ok(index>=0,'authoritative native fader/meter calibration CSS absent'); + assert.equal(css.indexOf(sourceCss,index+1),-1,'duplicate DSP scale calibration'); + assert.ok(css.slice(index+sourceCss.length).includes('mx-hw-key'), + 'post-calibration CSS must be the approved hardware-button overlay'); assert.ok(standalone.includes(''), 'Pages/standalone CSS drift'); assert.ok(standalone.includes(''), 'Pages/standalone JS drift'); for (const cls of ['gain-scale-travel','vu-scale-travel','meter-signal-area','fader-travel']) { diff --git a/tests/smart_audio_ard_contract_test.mjs b/tests/smart_audio_ard_contract_test.mjs index 424fcf8a7..188eb6a46 100644 --- a/tests/smart_audio_ard_contract_test.mjs +++ b/tests/smart_audio_ard_contract_test.mjs @@ -12,14 +12,35 @@ const ard = read('docs/ARD_SMART_AUDIO_ENGINE_V1_2026-10-25.md'); const impl = read('docs/SMART_AUDIO_ENGINE_IMPLEMENTATION_BLUEPRINT.md'); const issue = 'https://github.com/masarray/arsonmix/issues/15'; const visualLock = 'docs/GUI_BASELINE_LOCK_2026-10-25.md'; +const currentPrd = read('docs/PRD_ARSONMIX_OPERATOR_FIRST_LIVE_MIXER_V5_20261101.md'); +const currentArd = read('docs/ARD_ARSONMIX_UNIVERSAL_REALTIME_CONSOLE_V5_20261101.md'); +const executionLock = read('docs/EXECUTION_LOCK_UNIVERSAL_LIVE_CONSOLE_V6_20261101.md'); +const puzzleV8 = read('docs/PUZZLE_INTEGRATION_CONTRACT_V8_20261101.md'); -test('all entrypoints direct engineers to canonical ARD and implementation blueprint', () => { - for (const s of [agents, readme]) { - assert.match(s, /ARD_SMART_AUDIO_ENGINE_V1_2026-10-25\.md/); - assert.match(s, /SMART_AUDIO_ENGINE_IMPLEMENTATION_BLUEPRINT\.md/); - assert.ok(s.includes(issue)); - assert.ok(s.includes(visualLock)); +test('active entrypoints follow PRD/ARD v5.2 and Puzzle v8, while v6 is archived', () => { + for (const content of [agents, readme]) { + assert.match(content, /PRD_ARSONMIX_OPERATOR_FIRST_LIVE_MIXER_V5_20261101\.md/); + assert.match(content, /ARD_ARSONMIX_UNIVERSAL_REALTIME_CONSOLE_V5_20261101\.md/); + assert.match(content, /PUZZLE_INTEGRATION_CONTRACT_V8_20261101\.md/); + assert.ok(content.includes(issue), 'hardware crackle blocker must remain visible'); } + for (const [label, content] of [ + ['PRD v5', currentPrd], ['ARD v5', currentArd], + ['Puzzle socket v8', puzzleV8], ['Historical lock v6', executionLock] + ]) { + assert.ok(content.includes('ChannelId') || content.includes('channel'), + label + ' must describe real mixer channels'); + } + // The v8 socket supersedes the old v6/v7 sequencing; do not re-enable + // a second native renderer by making tests depend on historical plans. + assert.match(puzzleV8, /IConsoleRuntimeV8/); + assert.match(puzzleV8, /ChannelId/); + assert.match(executionLock, /one accepted PCM graph/i); + assert.match(executionLock, /CH11/); + assert.match(executionLock, /rollback/i); + // The old documents still exist as historical technical references. + // They are no longer the active instruction linked by repo entrypoints. + assert.ok(read(visualLock).length > 100); assert.match(old, /HISTORICAL 0\.3 DESIGN/); assert.match(old, /Current architecture \(overrides outdated v0\.3 proposals\)/); }); diff --git a/tests/ui_smoke.py b/tests/ui_smoke.py index 87934d184..37437307a 100644 --- a/tests/ui_smoke.py +++ b/tests/ui_smoke.py @@ -362,37 +362,39 @@ async def passive_hover_is_inert(selector): p=page.locator(f'[data-pan="{idx}"]') assert await p.get_attribute('aria-orientation')=='horizontal' assert await p.locator('.pan-thumb').count()==1 - # Button 180: SOLID base and exact layered shadow (never PNG/gradient). + # V5 approved physical key: one knockout mask, no duplicate text. for selector in ['[data-mute="0"]','[data-solo="0"]','[data-hpf="0"]']: v=await page.locator(selector).first.evaluate("""e=>{ - const s=getComputedStyle(e);return { - image:s.backgroundImage,shadow:s.boxShadow, - color:s.backgroundColor,transition:s.transitionDuration} + const s=getComputedStyle(e),face=e.querySelector('svg.mx-hw-face'); + return {skin:e.classList.contains('mx-hw-key'),old:e.classList.contains('btn-180'), + bg:s.backgroundImage,shadow:s.boxShadow,filter:s.filter, + masks:face?.querySelectorAll('mask').length, + texts:face?.querySelectorAll('mask text').length, + overlaid:face?.querySelectorAll(':scope > text').length, + gap:getComputedStyle(e,'::before').opacity}; }""") - assert v['image']=='none' and v['color'].startswith('rgb('), (selector,v) - assert v['shadow'].count('rgb')>=6,(selector,v) - assert v['transition'].split(', ')[0]=='0.045s',(selector,v) - style=await page.locator('[data-mute="0"]').evaluate("""e=>{ - const s=getComputedStyle(e);return {dur:s.transitionDuration,border:s.borderTopWidth, - radius:s.borderTopLeftRadius,shadow:s.boxShadow}; - }""") - assert style['border']=='1px' and style['radius']=='3px',style - # Inter is part of the app payload; no network font or fallback is allowed. + assert v['skin'] and not v['old'] and 'gradient' in v['bg'],(selector,v) + assert v['masks']==1 and v['texts']==1 and v['overlaid']==0,(selector,v) + assert v['gap']=='0' and v['filter']=='none',(selector,v) + # Inter remains embedded for unrelated app typography. assert await page.evaluate("""async()=>{ await document.fonts.load('600 12px "ArSonMix Inter"'); return document.fonts.check('600 12px "ArSonMix Inter"')&& getComputedStyle(document.querySelector('.strip-name')).fontFamily.includes('ArSonMix Inter'); }"""),'Embedded Inter font was not applied' - assert [round(float(v.rstrip('s')),3) for v in style['dur'].split(', ')]==[.045,.045,0,0],style - # Hover in production does not create a filter, while diagnostic - # baseline restores brightness to permit same-PC performance A/B. + # No passive GPU filter even under the old diagnostic baseline mode. utility=page.locator('[data-hpf="0"]') await utility.hover() assert await utility.evaluate("(e)=>getComputedStyle(e).filter")=='none' await page.evaluate("document.documentElement.dataset.mixperf='baseline'") - assert 'brightness(1.32)' in await utility.evaluate("(e)=>getComputedStyle(e).filter") - await page.evaluate("delete document.documentElement.dataset.mixperf") assert await utility.evaluate("(e)=>getComputedStyle(e).filter")=='none' + await page.evaluate("delete document.documentElement.dataset.mixperf") + # The unified M4 CONSOLE is tested in mixer_io_smoke.py, including + # a physically visible pinned MAIN, native IN/FX/SEND/OUT controls, + # horizontal banking and deliberately scrollable full 6-slot VST racks. + # This historical geometry test explicitly checks the retained FX-only + # engineering layer, where all six slots still fit without scroll. + await page.locator('[data-mix-mode="FX"]').click() # Visual-architecture regression: four intentionally different hardware # families, FX slots recessed rather than taking on button-cap artwork. # GUI target: MASTER is the 11th strip, not a floating right rail. @@ -446,8 +448,8 @@ async def passive_hover_is_inert(selector): assert await page.locator('.right-rail,.master-tabs,.head').count()==0 assert await page.locator('[data-master-output]').count()==0 assert await page.locator('.master-stereo-badge,.master-route-label,.fader-tools.master-tools').count()==0 - assert await page.locator('#masterMode.btn-180.is-stereo').count()==1 - assert await page.locator('#masterMode').inner_text()=='STEREO' + assert await page.locator('#masterMode.mx-hw-key.is-stereo').count()==1 + assert await page.locator('#masterMode svg.mx-hw-face mask text').text_content()=='STEREO' assert await page.locator('#masterMode').get_attribute('aria-pressed')=='false' # Streaming output panel has only two useful readouts. assert await page.locator('#masterLeft .master-analysis .master-info-row').count()==2 @@ -469,7 +471,7 @@ async def passive_hover_is_inert(selector): assert await page.locator('.left-rail [data-sof-toggle]').count()==1 assert await page.locator('.toolbar-actions .fx-nav,.left-rail .fx-nav').count()==0 assert await page.locator('.left-rail .pushable,.left-rail .front,.left-rail .edge,.left-rail .shadow').count()==0 - assert await page.locator('.left-rail [data-mix-mode]').count()==3 + assert await page.locator('.left-rail [data-mix-mode]').count()==4 assert await page.locator('.left-rail #audioSetupBtn').count()==1 assert await page.locator('.toolbar-actions #audioSetupBtn').count()==0 assert await page.locator('.left-rail [data-my-sounds],.left-rail [data-plugin-manager],.left-rail #arSignalOpen').count()==3 @@ -485,12 +487,14 @@ async def passive_hover_is_inert(selector): mute:grab('[data-mute="0"]'), utility:grab('[data-hpf="0"]')}; }""") - for key in ('rail','mute','utility'): - assert style[key]['face']=='rgb(203, 209, 209)',(key,style) + for key in ('rail',): + assert style[key]['face']=='rgb(231, 239, 240)',(key,style) assert style[key]['image']=='none',(key,style) assert style[key]['shadow'].count('rgb')==7,(key,style) assert style[key]['radius']=='3px',(key,style) - assert style['nav']['face']=='rgb(203, 209, 209)' and style['selected']['face']=='rgb(178, 232, 160)',style + for key in ('mute','utility'): + assert 'gradient' in style[key]['image'] and style[key]['radius']=='5px',(key,style) + assert style['nav']['face']=='rgb(231, 239, 240)' and style['selected']['face']=='rgb(178, 232, 160)',style assert style['railOn']['face']=='rgb(237, 184, 223)',style # Audio Device shares the physical BTN-180 toolbar face and dark ink. # The OFF state is truthful in UI-only preview. Explicitly force ON @@ -499,7 +503,7 @@ async def passive_hover_is_inert(selector): devOff=await device.evaluate("""e=>{const s=getComputedStyle(e),t=getComputedStyle(e.querySelector('#headerDriver')), r=e.getBoundingClientRect();return {face:s.backgroundColor,ink:t.color,shadow:s.boxShadow,rect:r.toJSON(), pressed:e.classList.contains('on'),backgroundImage:s.backgroundImage}}""") - assert devOff['face']==style['rail']['face']=='rgb(203, 209, 209)',devOff + assert devOff['face']==style['rail']['face']=='rgb(231, 239, 240)',devOff assert devOff['ink']=='rgb(23, 34, 41)' and devOff['backgroundImage']=='none',devOff assert not devOff['pressed'],devOff await device.evaluate("(e)=>e.classList.add('on')") @@ -511,10 +515,10 @@ async def passive_hover_is_inert(selector): assert all(abs(devOff['rect'][k]-devOn['rect'][k])<.2 for k in ('x','y','width','height')),(devOff,devOn) await page.screenshot(path=str(project/'device-green-on-palette-review.png'),full_page=True) await device.evaluate("(e)=>e.classList.remove('on')") - await page.wait_for_function("""()=>getComputedStyle(document.querySelector('.spec-device')).backgroundColor==='rgb(203, 209, 209)'""") + await page.wait_for_function("""()=>getComputedStyle(document.querySelector('.spec-device')).backgroundColor==='rgb(231, 239, 240)'""") assert all(style[key]['spanTransform']=='none' for key in ('nav','rail','selected')),style assert await page.locator('[data-hpf="0"]').evaluate( - "(e)=>getComputedStyle(e).boxShadow.includes('5px 5px 2px -1px')"),style + "(e)=>e.classList.contains('mx-hw-key')&&getComputedStyle(e).boxShadow.includes('inset')"),style # Real 1px tactile travel; no text scaling or width/height changes. preset=page.locator('[data-preset="Clean Vocal"]') pre=await preset.evaluate("(e)=>e.getBoundingClientRect().toJSON()") @@ -536,11 +540,14 @@ async def passive_hover_is_inert(selector): assert active['face']=='rgb(237, 184, 223)' and active['transform']=='matrix(1, 0, 0, 1, 0, 0)',active assert shared_shadow_shape(active['shadow'])==shared_shadow_shape(style['rail']['shadow']),active assert all(abs(active['rect'][k]-pre[k])<=.2 for k in ('x','y','width','height')),active - # Utility ON is soft cyan, not the old green/purple polarity palettes. + # HPF processing: teal lamp inside V5 knockout (not face-color repaint). await page.locator('[data-hpf="0"]').click() - await page.wait_for_timeout(190) - cyan=await page.locator('[data-hpf="0"]').evaluate("(e)=>getComputedStyle(e).backgroundColor") - assert cyan=='rgb(148, 232, 237)',cyan + hpf=await page.locator('[data-hpf="0"]').evaluate("""e=>({ + led:getComputedStyle(e).getPropertyValue('--mx-hw-led').trim(), + gap:getComputedStyle(e,'::before').opacity, + lamp:getComputedStyle(e.querySelector('.mx-hw-lamp')).opacity + })""") + assert hpf=={'led':'87,211,189','gap':'1','lamp':'1'},hpf await page.locator('[data-hpf="0"]').click() # Navigation remains mutually exclusive; selected is only a color latch. await page.locator('[data-view="FX RACK"]').click() @@ -549,7 +556,7 @@ async def passive_hover_is_inert(selector): const off=document.querySelector('[data-view="MIX"]'); return on.classList.contains('selected') && !off.classList.contains('selected') && getComputedStyle(on).backgroundColor==='rgb(178, 232, 160)' - && getComputedStyle(off).backgroundColor==='rgb(203, 209, 209)'; + && getComputedStyle(off).backgroundColor==='rgb(231, 239, 240)'; }""") nav=page.locator('[data-view="FX RACK"]') navBefore=await nav.evaluate("(e)=>e.getBoundingClientRect().toJSON()") @@ -598,18 +605,25 @@ async def passive_hover_is_inert(selector): assert not railGeometry['emptyControls'],railGeometry assert all(btn['width']>=40 and btn['height']>=25 for btn in railGeometry['buttons']),railGeometry await page.screenshot(path=str(project/'mixer-master-dual-metric-left-rail.png'),full_page=True) - off_mute=await page.locator('[data-mute="0"]').evaluate("(e)=>getComputedStyle(e).getPropertyValue('--b180-color').trim()") + off_mute=await page.locator('[data-mute="0"]').evaluate("(e)=>getComputedStyle(e,'::before').opacity") + assert off_mute=='0' await page.locator('[data-mute="0"]').click() - mute_on=await page.locator('[data-mute="0"]').evaluate("(e)=>getComputedStyle(e).getPropertyValue('--b180-color').trim()") - assert mute_on!=off_mute and await page.locator('[data-mute="0"]').get_attribute('aria-pressed')=='true' + mute_on=await page.locator('[data-mute="0"]').evaluate("""e=>({ + led:getComputedStyle(e).getPropertyValue('--mx-hw-led').trim(), + gap:getComputedStyle(e,'::before').opacity})""") + assert mute_on=={'led':'255,64,85','gap':'1'} + assert await page.locator('[data-mute="0"]').get_attribute('aria-pressed')=='true' await page.locator('[data-mute="0"]').click() await page.locator('[data-solo="0"]').click() - solo_on=await page.locator('[data-solo="0"]').evaluate("(e)=>getComputedStyle(e).getPropertyValue('--b180-color').trim()") - assert solo_on!=mute_on + solo_on=await page.locator('[data-solo="0"]').evaluate("""e=>({ + led:getComputedStyle(e).getPropertyValue('--mx-hw-led').trim(), + gap:getComputedStyle(e,'::before').opacity})""") + assert solo_on=={'led':'255,208,44','gap':'1'} await page.locator('[data-solo="0"]').click() await page.locator('[data-hpf="0"]').click() - hpf_on=await page.locator('[data-hpf="0"]').evaluate("(e)=>getComputedStyle(e).getPropertyValue('--b180-color').trim()") - assert hpf_on not in (mute_on,solo_on,off_mute) + hpf_on=await page.locator('[data-hpf="0"]').evaluate( + "(e)=>getComputedStyle(e).getPropertyValue('--mx-hw-led').trim()") + assert hpf_on=='87,211,189' await page.locator('[data-hpf="0"]').click() await page.screenshot(path=str(project/'mixer-crystal-candy-review.png'),full_page=True) await page.screenshot(path=str(project/'mixer-crystal-depth-glow-review.png'),full_page=True) @@ -657,7 +671,7 @@ async def passive_hover_is_inert(selector): selection:getComputedStyle(main,'::before').borderTopWidth, masterRows:[...master.children].map(x=>({cls:x.className,height:x.getBoundingClientRect().height}))}; }""") - assert architecture['small']=='none',architecture + assert 'gradient' in architecture['small'],architecture assert abs(architecture['mainFader']['height']-architecture['masterFader']['height'])<=2,architecture assert architecture['nav']=='none',architecture assert architecture['long']=='none',architecture @@ -691,38 +705,27 @@ async def passive_hover_is_inert(selector): assert smallRail['footerBottom']<=smallRail['bottom']+1,smallRail assert all(b['width']>35 for b in smallRail['buttons']),smallRail assert await page.locator('.strip').count()==11 - # The user's requirement: the SAME size/position before, during, and after toggle. - # OFF/ON use the exact same shadow-layer geometry, differing only in palette. + # V5 state changes only internal lamp and 1–2px occluded light. + # Physical key outer geometry is immutable: no old depressed BTN-180 layers. def switch_state(selector): return page.locator(selector).evaluate("""e=>{ - const s=getComputedStyle(e),r=e.getBoundingClientRect(); - return {t:s.transform,shadow:s.boxShadow,color:s.backgroundColor, - ink:s.color,left:r.left,top:r.top,width:r.width,height:r.height, - selected:e.classList.contains('active')||e.classList.contains('selected')}; + const s=getComputedStyle(e),r=e.getBoundingClientRect(),svg=e.querySelector('svg.mx-hw-face'); + return {t:s.transform,shadow:s.boxShadow,gap:getComputedStyle(e,'::before').opacity, + lamp:getComputedStyle(svg.querySelector('.mx-hw-lamp')).opacity, + left:r.left,top:r.top,width:r.width,height:r.height, + selected:e.classList.contains('active')}; }""") def same_rect(a,b): return all(abs(a[k]-b[k])<=.2 for k in ('left','top','width','height')) off=await switch_state('[data-mute="0"]') - assert off['t']=='matrix(1, 0, 0, 1, 0, 0)',off await page.locator('[data-mute="0"]').click() - await page.wait_for_function("""()=>{ - const e=document.querySelector('[data-mute="0"]'); - return e.classList.contains('active')&&getComputedStyle(e).boxShadow.includes('inset'); - }""",timeout=2500) - await page.wait_for_timeout(65) # 45ms palette, immediate pressed displacement on=await switch_state('[data-mute="0"]') - assert on['selected'] and shared_shadow_shape(on['shadow'])==shared_shadow_shape(off['shadow']),(off,on) - assert on['color']!=off['color'],(off,on) - assert on['t']==off['t'] and same_rect(off,on),(off,on) - assert off['color']=='rgb(203, 209, 209)' and off['ink']=='rgb(23, 34, 41)',(off,on) - assert on['ink']!=off['ink'],(off,on) - assert on['shadow'].startswith('rgba(0, 0, 0, 0.18)'),on + assert on['selected'] and off['gap']=='0' and on['gap']=='1',(off,on) + assert off['lamp']=='0' and on['lamp']=='1',(off,on) + assert off['shadow']==on['shadow'] and off['t']==on['t'] and same_rect(off,on),(off,on) await page.locator('[data-mute="0"]').click() - await page.mouse.move(1,1) # OFF after pointer leaves, not the intentional glossy hover state - await page.wait_for_timeout(190) back=await switch_state('[data-mute="0"]') - assert back['t']==off['t'] and same_rect(off,back),(off,back) - assert back['shadow']==off['shadow'],(off,back) + assert back['gap']=='0' and same_rect(off,back),(off,back) # Source A/B controls are gone; fader travel expands into their old space. assert await page.locator('[data-send]').count()==0 assert await page.locator('#mixer > .strip:not(.master-strip) .fader-tools').count()==0 @@ -756,51 +759,28 @@ def same_rect(a,b): and 'linear-gradient' in x['slitPaint'] and x['capWidth']==36 for x in fader_recess),fader_recess - # Both resting states share depth; while pointer is down only, cap sinks 1px - # with a stronger inner shadow and unchanged width/height/layout slot. + # Press travel applies only to the SVG keycap; housing stays stationary. btn=page.locator('[data-mute="0"]') - before=await btn.evaluate("""e=>({ - shadow:getComputedStyle(e).boxShadow, - before:getComputedStyle(e,'::before').content, - after:getComputedStyle(e,'::after').content})""") - assert before['before']=='none' and before['after']=='none',before press_before=await btn.evaluate("(e)=>e.getBoundingClientRect().toJSON()") await btn.hover() await page.mouse.down() - await page.wait_for_timeout(190) during=await btn.evaluate("""e=>({ - t:getComputedStyle(e).transform,rect:e.getBoundingClientRect().toJSON(), - shadow:getComputedStyle(e).boxShadow})""") - assert during['t']=='matrix(1, 0, 0, 1, 0, 1)',during - assert abs(during['rect']['y']-press_before['y']-1)<=.2,during - assert all(abs(during['rect'][k]-press_before[k])<=.2 for k in ('x','width','height')),during - assert during['shadow']!=before['shadow'] and '0.5' in during['shadow'],(before,during) + outer:getComputedStyle(e).transform, + face:getComputedStyle(e.querySelector('svg.mx-hw-face')).transform, + rect:e.getBoundingClientRect().toJSON() + })""") + assert during['outer'] in ('none','matrix(1, 0, 0, 1, 0, 0)'),during + assert during['face']=='matrix(1, 0, 0, 1, 0, 1)',during + assert abs(during['rect']['y']-press_before['y'])<=.2,during await page.mouse.up() - await page.wait_for_timeout(190) assert await btn.get_attribute('aria-pressed')=='true' - released_on=await btn.evaluate("""e=>({ - t:getComputedStyle(e).transform, shadow:getComputedStyle(e).boxShadow, - rect:e.getBoundingClientRect().toJSON() - })""") - assert released_on['t']=='matrix(1, 0, 0, 1, 0, 0)',released_on - assert abs(released_on['rect']['y']-press_before['y'])<=.2,released_on - assert shared_shadow_shape(released_on['shadow'])==shared_shadow_shape(before['shadow']),(before,released_on) - # Re-press while already ON; it must have the same 1px tactile travel. await btn.hover() await page.mouse.down() - await page.wait_for_timeout(120) - pressed_on=await btn.evaluate("""e=>({ - t:getComputedStyle(e).transform,shadow:getComputedStyle(e).boxShadow, - rect:e.getBoundingClientRect().toJSON() - })""") - assert pressed_on['t']=='matrix(1, 0, 0, 1, 0, 1)',pressed_on - assert abs(pressed_on['rect']['y']-press_before['y']-1)<=.2,pressed_on - assert all(abs(pressed_on['rect'][k]-press_before[k])<=.2 for k in ('x','width','height')),pressed_on - assert '0.5' in pressed_on['shadow'],pressed_on + pressed_on=await btn.evaluate( + "(e)=>getComputedStyle(e.querySelector('svg.mx-hw-face')).transform") + assert pressed_on=='matrix(1, 0, 0, 1, 0, 1)',pressed_on await page.mouse.up() - await page.wait_for_timeout(190) assert await btn.get_attribute('aria-pressed')=='false' - assert await btn.evaluate("(e)=>getComputedStyle(e).transform")=='matrix(1, 0, 0, 1, 0, 0)' released_off=await btn.evaluate("(e)=>e.getBoundingClientRect().toJSON()") assert abs(released_off['y']-press_before['y'])<=.2,released_off widths=await page.evaluate("""()=>{ @@ -867,23 +847,24 @@ def same_rect(a,b): await page.locator('[data-view="MIX"]').click() assert await page.locator('[data-fxpower="0:0"]').get_attribute('aria-pressed')=='true' assert await page.evaluate('durableSession().bypassed["0:0"]') is False - # A real two-state BTN-180 control: blue STEREO, red MONO, durable state. + # Master mode is also V5; MONO/STEREO replace only its SINGLE mask legend. mode=page.locator('#masterMode') - blue=await mode.evaluate("(e)=>getComputedStyle(e).getPropertyValue('--b180-color').trim()") - assert blue=='#9dd2f0',blue + assert await mode.evaluate("(e)=>e.classList.contains('mx-hw-key')") await mode.click() - red=await mode.evaluate("(e)=>getComputedStyle(e).getPropertyValue('--b180-color').trim()") - assert await mode.inner_text()=='MONO' and await mode.get_attribute('aria-pressed')=='true' - assert red=='#f99aa4' and red!=blue,red + await page.wait_for_function("""()=>document.querySelector('#masterMode') + .querySelector('svg.mx-hw-face mask text')?.textContent==='MONO'""") + assert await mode.get_attribute('aria-pressed')=='true' assert await page.evaluate('durableSession().masterMono') is True await mode.click() - assert await mode.inner_text()=='STEREO' and await mode.get_attribute('aria-pressed')=='false' + await page.wait_for_function("""()=>document.querySelector('#masterMode') + .querySelector('svg.mx-hw-face mask text')?.textContent==='STEREO'""") + assert await mode.get_attribute('aria-pressed')=='false' assert await page.evaluate('durableSession().masterMono') is False await page.locator('#masterMute').click() - assert await page.locator('#masterMute').inner_text()=='MUTE' assert await page.locator('#masterMute').get_attribute('aria-pressed')=='true' + assert await page.locator('#masterMute svg.mx-hw-face mask text').text_content()=='MUTE' await page.locator('#masterMute').click() - assert await page.locator('#masterMute').inner_text()=='MUTE' + assert await page.locator('#masterMute').get_attribute('aria-pressed')=='false' # Hover and active feedback stays visual and does not change native fader geometry. cap0=page.locator('[data-fader="0"] .cap') await cap0.hover() @@ -970,8 +951,14 @@ def same_rect(a,b): assert await page.evaluate('durableSession().masterBypassed["0"]') is True await page.locator('[data-master-power="0"]').click() assert await page.locator('[data-master-power="0"]').get_attribute('aria-pressed')=='true' - # Master insert selection can open an editor and replace the selected FX. + # PR #278 V5: clicking a real MASTER insert opens the compact + # contextual quick picker; F8 remains the separate full manager. await page.locator('[data-master-insert="0"]').click() + assert await page.locator('.arV5QuickFx').is_visible() + assert 'MAIN' in await page.locator('.arV5QuickHead').inner_text() + await page.locator('.arV5QuickFx [data-fast-close]').click() + assert await page.locator('.arV5QuickFx').is_hidden() + await page.keyboard.press('F8') assert await page.locator('#pluginModal').is_visible() await page.locator('#closeBrowser').click() assert await page.locator('#pluginModal').is_hidden() @@ -1124,11 +1111,14 @@ def same_rect(a,b): assert all(abs(v['unit']-14)<.3 and abs(v['meter']-14)<.3 and abs(v['fill']-10)<.6 and v['clip'] for v in vu_geometry),vu_geometry assert len(set(v['gradient'] for v in vu_geometry))==1, 'VU palette must match across all L/R/mono bars' await page.locator('#masterMode').click() - assert await page.locator('#masterMode').inner_text()=='MONO' - mono_text=await page.locator('#masterMode').evaluate('(e)=>({color:getComputedStyle(e).color,shadow:getComputedStyle(e).textShadow})') - assert mono_text['color']=='rgb(20, 16, 20)' and mono_text['shadow']=='none',mono_text + assert await page.locator('#masterMode svg.mx-hw-face mask text').text_content()=='MONO' + mono_text=await page.locator('#masterMode').evaluate("""e=>({ + led:getComputedStyle(e).getPropertyValue('--mx-hw-led').trim(), + glow:getComputedStyle(e.querySelector('.mx-hw-lamp')).opacity + })""") + assert mono_text=={'led':'210,225,234','glow':'1'},mono_text await page.locator('#masterMode').click() - assert await page.locator('#masterMode').inner_text()=='STEREO' + assert await page.locator('#masterMode svg.mx-hw-face mask text').text_content()=='STEREO' # Manual peak-hold reset must be deterministic: cancel the browser's # unrelated 25Hz demo producer before injecting explicit levels. Without # this, a live demo RAF can repopulate peakHold after RESET and make the @@ -1157,8 +1147,14 @@ def same_rect(a,b): await page.locator('#masterLeft .master-ch-id').click() assert await page.locator('#masterLeft').evaluate('(e)=>e.classList.contains("selected")') assert await page.locator('[data-strip="0"]').evaluate('(e)=>!e.classList.contains("selected")') - await page.locator('[data-strip="0"] .ch-id').click() + # CH number selects the strip; the adjacent name/icon deliberately opens editing. + await page.locator('[data-strip="0"] .arChannelNumber').click() assert await page.locator('#masterLeft').evaluate('(e)=>!e.classList.contains("selected")') + assert await page.locator('#channelIdentity').evaluate('(e)=>e.classList.contains("hidden")') + await page.locator('[data-strip="0"] .arChannelTopIdentity').click() + assert await page.locator('#channelIdentity').is_visible() + await page.locator('#identityCancel').click() + assert await page.locator('#channelIdentity').evaluate('(e)=>e.classList.contains("hidden")') pan=page.locator('[data-pan="0"]') await pan.focus() @@ -1188,28 +1184,24 @@ def same_rect(a,b): assert await pan.get_attribute('aria-valuenow')=='0' assert not await page.locator('#editor').is_visible(),'PAN double click opened editor' - # Same Button 180 construction, distinct solid color for each ON state. - async def image_for(selector): - return await page.locator(selector).first.evaluate( - '(b) => getComputedStyle(b).backgroundColor') - off_mute=await image_for('[data-mute="0"]') - assert off_mute.startswith('rgb(') - assert off_mute == await image_for('[data-solo="0"]') + # Same V5 material on all buttons, independent semantic LED and lamp. + async def led_state(selector): + return await page.locator(selector).first.evaluate("""b=>({ + led:getComputedStyle(b).getPropertyValue('--mx-hw-led').trim(), + gap:getComputedStyle(b,'::before').opacity, + lamp:getComputedStyle(b.querySelector('.mx-hw-lamp')).opacity + })""") + off_mute=await led_state('[data-mute="0"]') + off_solo=await led_state('[data-solo="0"]') + assert off_mute['gap']==off_solo['gap']=='0' await page.locator('[data-mute="0"]').click() - assert await page.locator('[data-mute="0"]').get_attribute('aria-pressed') == 'true' - # BTN-180 color transition is 45ms, while tactile press is immediate. - await page.wait_for_function("""()=>getComputedStyle(document.querySelector('[data-mute="0"]')).backgroundColor==='rgb(249, 154, 164)'""",timeout=2500) - assert await image_for('[data-mute="0"]') != await image_for('[data-solo="0"]'), await page.evaluate("""()=>{ - return [...document.querySelectorAll('[data-mute="0"],[data-solo="0"]')].map(e=>({ - cls:e.className,background:getComputedStyle(e).backgroundColor, - token:getComputedStyle(e).getPropertyValue('--b180-color'), - bgImage:getComputedStyle(e).backgroundImage - })) - }""") + assert await page.locator('[data-mute="0"]').get_attribute('aria-pressed')=='true' + mute_on=await led_state('[data-mute="0"]') + assert mute_on=={'led':'255,64,85','gap':'1','lamp':'1'},mute_on await page.locator('[data-solo="0"]').click() - assert await page.locator('[data-solo="0"]').get_attribute('aria-pressed') == 'true' - await page.wait_for_function("""()=>getComputedStyle(document.querySelector('[data-solo="0"]')).backgroundColor==='rgb(244, 212, 121)'""",timeout=2500) - assert await image_for('[data-solo="0"]') != await image_for('[data-mute="0"]') + assert await page.locator('[data-solo="0"]').get_attribute('aria-pressed')=='true' + solo_on=await led_state('[data-solo="0"]') + assert solo_on=={'led':'255,208,44','gap':'1','lamp':'1'},solo_on await page.locator('[data-mute="0"]').click() await page.locator('[data-solo="0"]').click() await page.locator('#masterMute').click() @@ -1543,7 +1535,7 @@ async def image_for(selector): assert 'KEEP IN STUDIO' in manager_hierarchy[0]['captions'],manager_hierarchy assert 'ArSonMix Inter' in ui_polish['font'],ui_polish - assert 'var(--b180-off' in ui_polish['resting'] or ui_polish['resting']=='#cbd1d1',ui_polish + assert 'var(--b180-off' in ui_polish['resting'] or ui_polish['resting']=='#E7EFF0',ui_polish await native.locator('#nativePluginManager [data-close-modal]').click() await native.locator('[data-strip="0"] .rack [data-plugin-picker="1"]').first.click() picker_equal=await native.evaluate("""()=>{ diff --git a/web/app.js b/web/app.js index dfc9ef649..54b9ce586 100644 --- a/web/app.js +++ b/web/app.js @@ -11,7 +11,7 @@ const raw=[ ['Backing','♫',['EQ','Reverb'],-3.6,-25], ['Guitar','♬',['EQ','Compressor','Delay'],-7.9,30], ['Keyboard','▥',['EQ','Reverb'],-14.2,0], - ['FX Return','◎',['Reverb'],-5.1,0] + ['Input 10','♩',['Reverb'],-5.1,0] ]; const channels=raw.map((a,i)=>({id:i+1,name:a[0],icon:a[1],color:colors[i],inserts:[...a[2]],fader:a[3],pan:a[4],trim:0,mute:false,solo:false,pre:false,hpf:i%4!==0,stereo:i>=6})); let currentChannel=0, masterSelected=false, view='MIX', sceneIdx=0, timer=0; @@ -266,19 +266,38 @@ function closeChannelIdentity(){ document.querySelectorAll('.strip.identity-editing').forEach(el=>el.classList.remove('identity-editing')); } function commitChannelIdentity(){ - if(editingChannel<0)return;const index=editingChannel; - const name=$('identityName').value.trim().replace(/\s+/g,' ').slice(0,26); + if(editingChannel<0)return; + const index=editingChannel, name=$('identityName').value.trim().replace(/\s+/g,' ').slice(0,26); if(!name){flash('Enter a channel name');$('identityName').focus();return} - channels[index].name=name;channels[index].icon=channelIcons.includes(editingIcon)?editingIcon:'♩'; - channels[index].color=channelPalette.includes(editingColor)?editingColor:colors[index]; - closeChannelIdentity();currentChannel=index;renderMixer(); + if(channels.some((c,i)=>i!==index&&c.name.trim().toLowerCase()===name.toLowerCase())){ + flash('Channel name already used');$('identityName').focus();return; + } + const ch=channels[index]; + ch.name=name;ch.icon=channelIcons.includes(editingIcon)?editingIcon:'♩'; + ch.color=channelPalette.includes(editingColor)?editingColor:colors[index]; + closeChannelIdentity();currentChannel=index; + // UI identity is not a native graph change. Do not remount any live FX/fader node. + const strip=document.querySelector('#mixer [data-strip="'+index+'"]'); + if(strip){ + strip.style.setProperty('--ch',ch.color); + for(const [sel,val] of [['.arChannelTopName',ch.name],['.arChannelTopIcon',ch.icon], + ['.strip-name .strip-caption',ch.name],['.strip-name .track-icon',ch.icon]]){ + const item=strip.querySelector(sel);if(item)item.textContent=val; + } + strip.querySelector('[data-identity-open]')?.setAttribute('aria-label','Edit '+ch.name+' name, icon and color'); + strip.querySelector('[data-editstrip]')?.setAttribute('aria-label','Double-click to edit '+ch.name+' name, icon and color'); + strip.querySelector('[data-fader]')?.setAttribute('aria-label',ch.name+' fader'); + const meter=strip.querySelector('.vu-bank'); + if(meter)meter.setAttribute('aria-label',ch.name+(ch.stereo?' stereo left and right meters':' mono meter')); + } + createSide(); if(view==='FX RACK')renderRackWorkspace(); - persistSession();flash('Channel identity updated'); + persistSession();flash('Channel label updated · native audio route unchanged'); } window.addEventListener('resize',positionChannelIdentity); $('mixer').addEventListener('scroll',positionChannelIdentity,{passive:true}); function makeStrip(ch,i){let inserts=ch.inserts.slice(0,6);while(inserts.length<6) inserts.push('');return `
-
${i+1}
${inserts.map((n,j)=>`
${n?``:''}
`).join('')}
+
CH ${String(i+1).padStart(2,'0')}
${inserts.map((n,j)=>`
${n?``:''}
`).join('')}
TRIM
dB
${fmt(ch.trim)}
${knobMarkup('trim',i,ch.trim,'Trim')}
${panMarkup(ch,i)}
${panText(ch.pan)}
${fmt(ch.fader)}
${ch.stereo?meterUnit(String(i)+'L','L')+meterUnit(String(i)+'R','R'):meterUnit(String(i),'')}${meterScaleMarkup()}
${faderScaleMarkup()}
@@ -305,7 +324,7 @@ function syncStripFormat(i,format){ window.__arMixSyncAcceptedChannelFormat=syncStripFormat; function renderMixer(){ const x=$('mixer'),scroll=x.scrollLeft; - x.innerHTML=channels.map(makeStrip).join('')+'
'; + x.innerHTML=channels.map(makeStrip).join('')+'
'; renderMaster();x.scrollLeft=scroll;createSide(); } let masterGain=-.1,masterPan=0,masterMute=false,masterMono=false,phones=-12,masterInserts=['Studio EQ','Brickwall Limiter'],masterBypassed={},pendingMasterSlot=null; @@ -327,7 +346,7 @@ const meterPercentToDbfs=p=>clamp(p,0,100)*.6-60; function meterUnit(key,label){return `
`} function renderMaster(){ const host=$('masterLeft');if(!host)return; - host.innerHTML=`
MASTER
+ host.innerHTML=`
MAIN
${masterFxRows()}
@@ -449,6 +468,11 @@ document.addEventListener('click',e=>{const b=e.target.closest('button,[data-cho if(b.dataset.pluginManager!==undefined){flash('Plugin Manager is available in the Windows desktop app');return} if(b.dataset.mySounds!==undefined){flash('Native VST3 presets are available in the Windows desktop app');return} if(b.dataset.choose!==undefined){chooseChannel(+b.dataset.choose);return} + if(b.dataset.identityOpen!==undefined){ + const index=Number(b.dataset.identityOpen); + if(Number.isInteger(index)&&index>=0&&index=channels.length)return; @@ -464,11 +488,11 @@ document.addEventListener('click',e=>{const b=e.target.closest('button,[data-cho if(b.dataset.mute!==undefined){toggleState(+b.dataset.mute,'mute');return}if(b.dataset.solo!==undefined){toggleState(+b.dataset.solo,'solo');return} if(b.dataset.pre!==undefined){let i=+b.dataset.pre;channels[i].pre=!channels[i].pre;b.classList.toggle('active');send('phase',channels[i].pre,i);return} if(b.dataset.hpf!==undefined){let i=+b.dataset.hpf;channels[i].hpf=!channels[i].hpf;b.classList.toggle('active');send('hpf',channels[i].hpf,i);return} - if(b.dataset.masterInsert!==undefined){pendingMasterSlot=+b.dataset.masterInsert;openPluginBrowser(currentChannel,true);return} + if(b.dataset.masterInsert!==undefined){pendingMasterSlot=+b.dataset.masterInsert;if(!window.__JUCE__?.backend?.emitEvent)openQuickFx(currentChannel,pendingMasterSlot,b,true);return} if(b.dataset.masterPower!==undefined){const slot=+b.dataset.masterPower;masterBypassed[slot]=!masterBypassed[slot];renderMaster();persistSession();send('masterFxBypass',{slot,bypass:masterBypassed[slot]},-1);return} if(b.dataset.clip!==undefined){resetClip(b.dataset.clip);return} if(b.dataset.fxpower!==undefined){const [i,j]=b.dataset.fxpower.split(':').map(Number);setFxBypass(i,j,!bypassed[fxKey(i,j)]);return} - if(b.dataset.insert){let [i,j]=b.dataset.insert.split(':').map(Number);currentChannel=i;pendingSlot=j;openPluginBrowser(i);return} + if(b.dataset.insert){let [i,j]=b.dataset.insert.split(':').map(Number);if(!window.__JUCE__?.backend?.emitEvent)openQuickFx(i,j,b);return} if(b.dataset.deleteScene!==undefined){deleteMixerSnapshot(b.dataset.deleteScene);return} if(b.dataset.scene!==undefined){loadSnapshotByIndex(+b.dataset.scene);return} if(b.dataset.preset){applyQuickPreset(b.dataset.preset);return} @@ -758,8 +782,74 @@ function renderSignalFlow(){ return; } $('rackWorkspace').innerHTML=`
NO TECHNICAL PATCHBAY REQUIRED

Signal Flow — See where your voice goes

A beginner-first view of the real-time audio path. Select your audio device in Setup.

01 · INPUTMicrophoneAudio Interface
ASIO or WASAPI
➜
02 · FX CHAINVST3 PluginsEQ · Dynamics
Reverb · Delay
➜
03 · MIXERMix & MonitorFader · Pan
Master · Meters
➜
04 · OUTPUTSpeakers / StreamAudio Device
Streaming bridge later
⚠ In this trial the audio flow is a visual concept; no microphone is captured and no audio is sent to a livestream.
`} + +// Adopt PR #278 V5 contextual quick-insert on the ORIGINAL mixer. +// Desktop native operations remain owned by bridge.js; this uses preview +// catalog ONLY when JUCE is absent, never as a fabricated VST3 instance. +const arV5Quick=document.createElement('section'); +arV5Quick.className='arV5QuickFx';arV5Quick.hidden=true; +arV5Quick.setAttribute('role','dialog'); +arV5Quick.setAttribute('aria-label','Quick add effect'); +arV5Quick.innerHTML='
ADD FX
'+ + ''+ + '
'+ + '
Enter: insert · Esc: close
'; +document.querySelector('#app .workbench')?.append(arV5Quick); +const arV5Search=arV5Quick.querySelector('.arV5QuickSearch'), + arV5Results=arV5Quick.querySelector('.arV5QuickResults'); +let arV5Anchor=null; +function closeQuickFx(focus=false){ + if(arV5Quick.hidden)return; + arV5Quick.hidden=true; + if(focus&&arV5Anchor?.isConnected)arV5Anchor.focus(); + arV5Anchor=null; +} +function renderQuickFx(){ + if(arV5Quick.hidden)return; + arV5Results.replaceChildren(); + const q=arV5Search.value.trim().toLocaleLowerCase(); + const found=pluginCatalog.filter(p=> + (p.name+' '+p.type+' '+(p.hint||'')).toLocaleLowerCase().includes(q)); + for(const fx of found.slice(0,64)){ + const b=document.createElement('button');b.type='button'; + b.className='arV5QuickResult';b.dataset.fastPlugin=fx.name; + const title=document.createElement('span');title.textContent=fx.name; + const kind=document.createElement('small');kind.textContent=fx.type; + b.append(title,kind);arV5Results.append(b); + } + if(!found.length){const p=document.createElement('p');p.textContent='No matching demo effects';arV5Results.append(p);} +} +function openQuickFx(channel,slot,anchor,isMaster=false){ + if(window.__JUCE__?.backend?.emitEvent)return false; + if(!isMaster){currentChannel=channel;pendingMasterSlot=null;pendingSlot=slot;} + else pendingMasterSlot=slot; + arV5Anchor=anchor; + arV5Quick.querySelector('.arV5QuickHead strong').textContent= + (isMaster?'MAIN':channels[channel]?.name||'CHANNEL')+' · FX '+(slot+1)+' · UI PREVIEW'; + const host=arV5Quick.parentElement,r=anchor?.getBoundingClientRect(),p=host?.getBoundingClientRect(); + if(r&&p){arV5Quick.style.left=Math.max(6,Math.min(r.left-p.left,p.width-320))+'px'; + arV5Quick.style.top=Math.max(6,Math.min(r.bottom-p.top+4,p.height-360))+'px';} + arV5Quick.hidden=false;arV5Search.value='';renderQuickFx();arV5Search.focus();return true; +} +arV5Search.addEventListener('input',renderQuickFx); +arV5Quick.addEventListener('click',e=>{ + if(e.target.closest('[data-fast-close]')){closeQuickFx(true);return;} + if(e.target.closest('[data-fast-manager]')){ + closeQuickFx();openPluginBrowser(currentChannel,pendingMasterSlot!==null);return;} + const b=e.target.closest('[data-fast-plugin]');if(!b)return; + if(!pluginCatalog.some(p=>p.name===b.dataset.fastPlugin))return; + closeQuickFx();insertPlugin(b.dataset.fastPlugin); +}); +arV5Quick.addEventListener('keydown',e=>{ + if(e.key==='Escape'){e.preventDefault();e.stopPropagation();closeQuickFx(true);} + if(e.key==='Enter'&&e.target===arV5Search){ + const first=arV5Results.querySelector('[data-fast-plugin]'); + if(first){e.preventDefault();first.click();} + } +}); + function openPluginBrowser(idx,isMaster=false){if(!isMaster){currentChannel=idx;pendingMasterSlot=null}activeCategory='All';$('pluginModal').classList.remove('hidden');$('pluginTarget').textContent=isMaster?'Adding to MASTER bus · demo FX catalog':'Adding to '+channels[idx].name+' · virtual effects catalog';$('pluginSearch').value='';renderPluginBrowser();$('pluginSearch').focus()} -function closePluginBrowser(){$('pluginModal').classList.add('hidden')} +function closePluginBrowser(){closeQuickFx();$('pluginModal').classList.add('hidden')} function renderPluginBrowser(){document.querySelectorAll('[data-category]').forEach(b=>b.classList.toggle('active',b.dataset.category===activeCategory));const q=$('pluginSearch').value.trim().toLowerCase();let pool=pluginCatalog.filter(p=>(activeCategory==='All'||p.type===activeCategory)&&`${p.name} ${p.type} ${p.hint}`.toLowerCase().includes(q));$('pluginResults').innerHTML=pool.map(p=>``).join('')||'

No matching demo effects.

'} function insertPlugin(name){ if(pendingMasterSlot!==null){ @@ -979,7 +1069,7 @@ document.addEventListener('input',e=>{const el=e.target;if(!el.dataset.fxparam)r $('pluginModal').addEventListener('click',e=>{if(e.target===$('pluginModal'))closePluginBrowser()}); $('channelIdentity').addEventListener('click',e=>{if(e.target===$('channelIdentity'))closeChannelIdentity()}); $('identityName').addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();commitChannelIdentity()}}); -document.addEventListener('keydown',e=>{if(e.key==='Escape'){closePluginBrowser();closeChannelIdentity()}if((e.key==='Enter'||e.key===' ')&&e.target.matches('[data-editstrip]')){e.preventDefault();openChannelIdentity(+e.target.dataset.editstrip)}}); +document.addEventListener('keydown',e=>{if(e.key==='F8'&&!e.repeat&&!document.documentElement.classList.contains('ar-v6-active')){e.preventDefault();if(window.__JUCE__?.backend?.emitEvent)document.querySelector('[data-plugin-manager]')?.click();else{closeQuickFx();openPluginBrowser(currentChannel,pendingMasterSlot!==null)}return;}if(e.key==='Escape'){closeQuickFx();closePluginBrowser();closeChannelIdentity()}if((e.key==='Enter'||e.key===' ')&&e.target.matches('[data-editstrip]')){e.preventDefault();openChannelIdentity(+e.target.dataset.editstrip)}}); document.addEventListener('change',e=>{if(e.target.id==='rackChannel')chooseChannel(+e.target.value)}); document.addEventListener('click',e=>{const id=e.target.closest('button')?.id;if(id==='saveFxFromRack')saveFxChainPreset();else if(id==='recallFxPreset')recallFxChain();else if(id==='openSetupFromFlow')$('audioSetupBtn')?.click();else if(id==='flowFxButton')setView('FX RACK');else if(id==='backMixer')setView('MIX')}); // The UI-only envelope remains one atomic storage transaction, never a 5s diff --git a/web/assets/knob-ICON.svg b/web/assets/knob-ICON.svg new file mode 100644 index 000000000..ef56513c6 --- /dev/null +++ b/web/assets/knob-ICON.svg @@ -0,0 +1,12 @@ + + + + + + + + + + diff --git a/web/bridge.js b/web/bridge.js index 2d376d804..f14ee87bc 100644 --- a/web/bridge.js +++ b/web/bridge.js @@ -832,8 +832,16 @@ ''+ ''; fxContext.hidden=false; - fxContext.style.left=Math.max(4,Math.min(x,window.innerWidth-fxContext.offsetWidth-4))+'px'; - fxContext.style.top=Math.max(4,Math.min(y,window.innerHeight-fxContext.offsetHeight-4))+'px'; + // The menu may never cover its own FX trigger: the user must be able + // to right-click a newly loaded vendor FX without closing another menu + // via a blind click. Use the adjacent side of the actual strip/slot. + const rect=anchor?.getBoundingClientRect?.(); + const width=fxContext.offsetWidth,height=fxContext.offsetHeight; + const after=rect?rect.right+7:x+7; + const before=rect?rect.left-width-7:x-width-7; + const left=after+width<=window.innerWidth-4?after:Math.max(4,before); + fxContext.style.left=Math.max(4,Math.min(left,window.innerWidth-width-4))+'px'; + fxContext.style.top=Math.max(4,Math.min(rect?rect.top:y,window.innerHeight-height-4))+'px'; fxContext.querySelector("button")?.focus({preventScroll:true}); } document.addEventListener("contextmenu",e=>{ diff --git a/web/hardware-keys.js b/web/hardware-keys.js new file mode 100644 index 000000000..4d8db8ac0 --- /dev/null +++ b/web/hardware-keys.js @@ -0,0 +1,178 @@ +/* ArSonMix hardware backlit keys — approved owner V5 geometry/occluded light. + UI-only decoration: existing data-*, click handlers and native ACK remain + the sole authority. No audio state is inferred or dispatched here. */ +(function(){ + 'use strict'; + const RULES=[ + ['#mixer .channel-actions [data-mute],#masterMute','mute','MUTE'], + ['#mixer .channel-actions [data-solo]','solo','SOLO'], + ['#mixer .utility-row [data-pre]','phase','Ø'], + ['#mixer .utility-row [data-hpf]','processing','HPF'], + ['#mixer [data-channel-format-toggle]','neutral',null], + ['#masterMode','neutral',null], + ['#mixer [data-fxpower],#masterLeft [data-master-power]','processing','FX'], + // Native top commands share the approved V5 key material; navigation + // chevrons retain their plain icon affordance. Decoration alone never + // dispatches or activates a native operation. + ['#app .arV6Console .arV6Top .arV6Button','neutral',null], + ['#app .arV6Console [data-op="SET_MUTE"]','mute','M'], + ['#app .arV6Console [data-op="SET_SOLO"]','solo','S'], + ['#app .arV6Console [data-op="SET_CUE"]','cue','C'], + ['#app .arV6Console [data-op="SET_INSERT_BYPASS"]','processing','FX'], + ['#app .arV6Console [data-op="SET_SEND_TAP"]','cue',null], + ['#app [data-sof-toggle]','cue','SEND'], + ['#app [data-chainbypass]','processing','FX'] + ]; + const PALETTE={ + mute:'255,64,85',solo:'255,208,44',cue:'90,200,231', + processing:'87,211,189',phase:'243,164,81', + link:'163,141,235',neutral:'210,225,234' + }; + const TARGET=RULES.map(rule=>rule[0]).join(','); + const instances=new WeakMap(); + let serial=0; + let observer=null; + const escapeXml=(value)=>String(value).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"').replace(/'/g,'''); + function source(button){ + for(const [selector,semantic,label] of RULES) { + if(button.matches(selector))return {semantic,label}; + } + return null; + } + function rawLabel(button){ + // Native accepted values can change PRE ↔ POST, MONO ↔ STEREO, etc. + return (button.textContent||'').trim().replace(/\s+/g,' '); + } + function classifyOn(button,legend){ + const pressed=button.getAttribute('aria-pressed'); + if(pressed!==null)return pressed==='true'; + if(button.dataset.op==='SET_SEND_TAP')return legend==='PRE'; + return button.classList.contains('active')||button.classList.contains('selected')|| + button.classList.contains('power-on')||button.classList.contains('on'); + } + function svgMarkup(legend,w,h,id,led){ + // V5: a SINGLE SVG mask text cut-out; never overlay duplicate text paints. + // ViewBox follows actual key size, preventing distorted glyphs in 28px strips. + const safe=escapeXml(legend); + const rx=Math.min(6,Math.max(2.5,h*.135)); + const fontSize=Math.max(8,Math.min(15,h*.46,(w-7)/(Math.max(1,legend.length)*.70))); + const x=w/2,y=h*.615,capW=Math.max(1,w-3),capH=Math.max(1,h-3); + const left=Math.max(3,w*.07),right=w-left,shineY=2.65; + const r=n=>Number(n.toFixed(2)); + return ''; + } + function render(button,force){ + if(!button.isConnected)return; + const record=instances.get(button); + if(!record)return; + const rect=button.getBoundingClientRect(); + const w=Math.max(16,rect.width-4),h=Math.max(16,rect.height-4); + const legend=button.dataset.mxHwLegend||record.legend; + const size=w.toFixed(1)+'x'+h.toFixed(1)+'/'+legend; + if(!force&&record.size===size&&button.querySelector(':scope > svg.mx-hw-face'))return; + record.size=size; + button.innerHTML=''+escapeXml(legend)+''+svgMarkup(legend,w,h,record.id,PALETTE[record.semantic]); + } + function upgrade(button){ + if(!(button instanceof HTMLButtonElement))return; + const rule=source(button); + if(!rule)return; + const existing=instances.get(button); + if(existing&&button.querySelector(':scope > svg.mx-hw-face')){resizer?.observe(button);return;} + const original=rawLabel(button); + let legend=rule.label||original||'ON'; + // A source text replacement (e.g. native PRE/POST) is authoritative. + if(existing&&original&&original!==existing.legend&&original!=='')legend=original; + if(!/^[\wØ/+\- ]{1,10}$/.test(legend))return; + if(!existing){ + // Drop the broken BTN-180 visual skin, retaining functionality/data hooks. + button.classList.remove('btn-180','candy'); + button.classList.add('mx-hw-key','mx-hw-'+rule.semantic); + if(!button.hasAttribute('aria-label'))button.setAttribute('aria-label',original||legend); + button.style.setProperty('--mx-hw-led',PALETTE[rule.semantic]); + instances.set(button,{id:++serial,legend,size:'',semantic:rule.semantic}); + if(resizer)resizer.observe(button); + }else{ + existing.legend=legend; + } + if(button.dataset.op==='SET_SEND_TAP')button.dataset.mxHwOn=String(classifyOn(button,legend)); + button.dataset.mxHwLegend=legend; + render(button,true); + } + function scan(root){ + if(!root||root.nodeType!==1)return; + if(root.matches('button.mx-hw-key')&&!root.querySelector('svg.mx-hw-face')){ + // An existing app handler replaced the button's textContent. + const prev=instances.get(root),changed=rawLabel(root); + if(prev&&changed&&changed!==prev.legend){ + root.dataset.mxHwLegend=changed; + prev.legend=changed; + } + upgrade(root); + }else if(root.matches(TARGET))upgrade(root); + for(const button of root.querySelectorAll(TARGET))upgrade(button); + } + const resizer=typeof ResizeObserver==='function'?new ResizeObserver(entries=>{ + for(const entry of entries)render(entry.target,false); + }):null; + const pending=new Set(); + let scheduled=false; + function flush(){ + scheduled=false; + for(const node of pending)scan(node); + pending.clear(); + } + function schedule(node){ + if(!node||node.nodeType!==1)return; + pending.add(node); + if(!scheduled){scheduled=true;queueMicrotask(flush)} + } + function install(){ + if(observer)return; + scan(document.body); + observer=new MutationObserver(records=>{ + for(const record of records){ + if(record.target instanceof HTMLButtonElement&&record.target.classList.contains('mx-hw-key') && + !record.target.querySelector('svg.mx-hw-face'))schedule(record.target); + for(const node of record.removedNodes)if(node.nodeType===1){ + if(node.matches?.('button.mx-hw-key')&&!node.isConnected)resizer?.unobserve(node); + for(const button of node.querySelectorAll?.('button.mx-hw-key')||[]) + if(!button.isConnected)resizer?.unobserve(button); + } + for(const node of record.addedNodes)if(node.nodeType===1&& + (node.matches?.(TARGET)||node.querySelector?.(TARGET)))schedule(node); + } + }); + // Watch DOM replacement only, not high-frequency meter/style attributes. + observer.observe(document.body,{childList:true,subtree:true}); + } + window.ArSonMixHardwareKeys=Object.freeze({install,upgrade,scan,PALETTE}); + if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',install,{once:true}); + else install(); +})(); \ No newline at end of file diff --git a/web/index.html b/web/index.html index 4b3852300..069ec9cf1 100644 --- a/web/index.html +++ b/web/index.html @@ -47,5 +47,5 @@
UI PREVIEW · Native audio engine is not connectedFader · PAN · VST3 FXPREVIEWArSonMix · Live VST3 Host
- + diff --git a/web/mixer-io.css b/web/mixer-io.css index d9565f2bd..982f1fe27 100644 --- a/web/mixer-io.css +++ b/web/mixer-io.css @@ -635,3 +635,167 @@ #app #mixer .arChannelQuickInput:disabled{color:#78949f;cursor:default} #app #mixer .arChannelQuickInput:focus-visible{outline:1px solid #7ad2e9;outline-offset:0} #app #mixer .arFormatBadge{top:0;height:15px;line-height:13px} + + +/* DEVICE/ROUTING 2026-11-01: one primary decision at a time. + Advanced crosspoints are never necessary for ordinary mono input routing. + No blur, glow filters, animated layout, large cards or second GUI router. */ +#arIOOverlay .arIOWindow{ + width:min(920px,calc(100vw - 28px)); + max-height:min(700px,calc(100dvh - 28px)); + border-radius:5px; + background:#15232d; +} +#arIOOverlay .arIOWindow>header{padding:8px 13px;min-height:42px} +#arIOOverlay .arIOWindow>header small{font-size:9px;letter-spacing:.6px} +#arIOOverlay .arIOWindow>header h2{font-size:15px;font-weight:500} +#arIOOverlay .arIOTop{padding:5px 13px;font-size:10px} +#arIOOverlay .arIOWindow nav{ + padding:6px 10px;gap:0;border-bottom:1px solid #3c5663;background:#172933; +} +#arIOOverlay .arIOWindow nav .btn-180{ + flex:1 1 0;min-width:0;height:30px;min-height:30px;border-radius:0; + font-size:10px;letter-spacing:.1px; +} +#arIOOverlay .arIOBody{padding:9px 12px;scrollbar-width:thin} +#arIOOverlay .arIOAudioPath{padding:5px 11px;gap:4px} +#arIOOverlay .arIOAudioPath>span{font-size:9px;padding:4px 6px} +#arIOOverlay .arIOAudioPath>small{font-size:10px} +#arIOOverlay .arIOWindow>footer{gap:6px;padding:7px 10px} +#arIOOverlay .arIOWindow>footer .btn-180{height:28px;min-height:28px;padding:0 9px} +#arIOOverlay .arIOWindow>footer [data-io-internal]{margin-left:0} +#arIOOverlay .arIODevicePatchMatrix{ + display:block;margin:9px 0 0;background:#162731;border:1px solid #355566; +} +#arIOOverlay .arIODevicePatchMatrix>.arIODeviceMatrixHeading{ + display:flex;list-style:none;cursor:pointer;min-height:32px;align-items:center; + padding:6px 10px;color:#adc7d3;font-weight:500; +} +#arIOOverlay .arIODevicePatchMatrix>.arIODeviceMatrixHeading::-webkit-details-marker{display:none} +#arIOOverlay .arIODevicePatchMatrix>.arIODeviceMatrixHeading:before{ + content:'▸';margin-right:8px;color:#80b5c9; +} +#arIOOverlay .arIODevicePatchMatrix[open]>.arIODeviceMatrixHeading:before{content:'▾'} +#arIOOverlay .arIODevicePatchMatrix:not([open])>:not(summary){display:none!important} +#arIOOverlay .arIOQuickPatch{max-width:100%;overflow:visible} +#arIOOverlay .arIOQuickColumns{display:none} +#arIOOverlay .arIOQuickHeader{min-height:47px;padding:7px 10px} +#arIOOverlay .arIOQuickGuide{ + padding:9px 10px;font-size:11px;color:#a7d3df;background:#1c303b; +} +#arIOOverlay .arIOQuickRow{ + grid-template-columns:minmax(100px,1fr) minmax(105px,1fr) minmax(135px,1.6fr) + minmax(135px,1.6fr) minmax(113px,1.2fr); + min-height:64px;padding:8px 11px;background:#172b36; + gap:8px;border-bottom:1px solid #3c5764; +} +#arIOOverlay .arIOQuickRow[hidden]{display:none!important} +#arIOOverlay .arIOQuickRow[data-state="invalid"]{ + box-shadow:inset 3px 0 #da9965;background:#302b27; +} +#arIOOverlay .arIOQuickRow[data-state="invalid"] .arIOQuickState{color:#ffcb9a} +#arIOOverlay .arIOQuickRow .arIOQuickState{font-size:10px;line-height:1.25} +#arIOOverlay .arIOQuickRow .arIOQuickStage{min-height:28px} +#arIOOverlay .arIOQuickFooter{ + background:#13242d;padding:9px 11px;margin:0;line-height:1.4; + font-size:10px;color:#9ec4d0; +} +#arIOOverlay .arIOJump{max-width:235px;width:235px} +#arIOOverlay .arIOSimpleMain{ + background:#162a35;border:1px solid #496675;padding:12px 13px;margin:0 0 9px; + color:#cfe3ec; +} +#arIOOverlay .arIOSimpleMain>strong{ + color:#d7edf5;font:600 12px/1.3 "Segoe UI",sans-serif; +} +#arIOOverlay .arIOSimpleMain p{ + margin:5px 0 11px;color:#9dbac9;line-height:1.35;font-size:10px; +} +#arIOOverlay .arIOSimpleMainRow{ + display:grid;grid-template-columns:1fr 1fr;gap:12px; +} +#arIOOverlay .arIOSimpleMainField{display:flex;flex-direction:column;gap:6px} +#arIOOverlay .arIOSimpleMainField>span{color:#84c8d8;font:600 10px/1.1 "Segoe UI",sans-serif} +#arIOOverlay .arIOSimpleMainField>select{ + width:100%;height:33px;min-width:0;padding:5px 8px; + background:#091c26;color:#deedf3;border:1px solid #548091;border-radius:3px; + font:11px/1.3 "Segoe UI",sans-serif; +} +#arIOOverlay .arIOSimpleMainField>select:disabled{opacity:.45} +#arIOOverlay .arIOAdvancedMatrix{margin:7px 0} +#arIOOverlay .arIOAdvancedMatrix>summary{ + cursor:pointer;color:#95b5c3;background:#172a35;border:1px solid #415a66; + padding:8px 10px;font-size:10px; +} +#arIOOverlay .arIOAdvancedMatrix:not([open])>*:not(summary){display:none!important} +@media(max-width:780px){ + #arIOOverlay .arIOWindow nav .btn-180{font-size:9px} + #arIOOverlay .arIOQuickRow{ + grid-template-columns:repeat(2,minmax(0,1fr));gap:7px; + } + #arIOOverlay .arIOQuickRow .arIOQuickAction{grid-column:span 2} + #arIOOverlay .arIOJump{width:180px;max-width:48%} +} +@media(max-height:700px){ + #arIOOverlay .arIOWindow{max-height:calc(100dvh - 12px)} + #arIOOverlay .arIOBody{padding:6px 10px} + #arIOOverlay .arIOAudioPath{grid-template-columns:repeat(4,minmax(0,1fr))} + #arIOOverlay .arIOAudioPath>button{grid-column:span 2} +} + + +/* v7 G1 operator hardware drawer. Unlike the former 920x700 blocking + wizard, device management is a narrow edge drawer; channel controls and + MAIN remain visible behind a light scrim, without new routing ownership. */ +#arIOOverlay{ + padding:0;justify-content:flex-end;align-items:stretch; + background:rgba(4,10,16,.48); +} +#arIOOverlay .arIOWindow{ + width:min(760px,100vw);height:100dvh;max-height:100dvh; + border:0;border-left:1px solid #5b7785;border-radius:0; + background:#13232c;box-shadow:-9px 0 22px #0005; +} +#arIOOverlay[data-active-tab="device"] .arIOWindow{ + width:min(594px,100vw); +} +#arIOOverlay .arIOWindow>header{ + min-height:43px;padding:7px 11px;gap:5px; +} +#arIOOverlay .arIOWindow>header h2{font-size:13px;font-weight:550;margin:0} +#arIOOverlay .arIOWindow>header small{font-size:9px} +#arIOOverlay .arIOTop{padding:5px 11px;font-size:10px} +#arIOOverlay .arIOWindow nav{ + padding:5px 8px;gap:0;background:#142934; +} +#arIOOverlay .arIOWindow nav .btn-180{ + flex:1 1 0;min-width:0;height:29px;min-height:29px; + padding:0 5px;font-size:9px;letter-spacing:0; +} +#arIOOverlay .arIOBody{ + padding:8px 10px;overflow-y:auto;min-height:0;overscroll-behavior:contain; +} +#arIOOverlay .arIOWindow>footer{padding:7px 10px;min-height:43px;gap:5px} +#arIOOverlay .arIOWindow>footer .btn-180{height:28px;min-height:28px} +.arIODevicePinGroup .arIODevicePinRow{ + min-height:27px; +} +.arIODevicePatchMatrix:not([open]) > :not(summary){ + display:none!important; +} +#app #mixer .arBankStage[data-state="invalid"]{ + color:#ffb38a!important; +} +#app #mixer .arBankStage[data-state="ack"]{ + color:#a5d0de!important; +} +@media(max-width:640px){ + #arIOOverlay .arIOWindow,#arIOOverlay[data-active-tab="device"] .arIOWindow{ + width:100vw; + } +} +@media(max-height:640px){ + #arIOOverlay .arIOBody{padding:6px 9px} + #arIOOverlay .arIOTop{padding:3px 9px} + #arIOOverlay .arIOWindow nav{padding:3px 8px} +} diff --git a/web/mixer-io.js b/web/mixer-io.js index bf34032b4..bf836fcf6 100644 --- a/web/mixer-io.js +++ b/web/mixer-io.js @@ -6,11 +6,11 @@ const mixer=document.getElementById('mixer'); const host=document.querySelector('.workbench'); if(!mixer||!host)return; - let mode='FX', lastStatus={}, deviceInventory=null, ioTab='device', lastSignature='', focusedInput=2; + let mode='CONSOLE', lastStatus={}, deviceInventory=null, ioTab='device', lastSignature='', focusedInput=0; let monitorSendsExpanded=false; // DEVICE1: staged selections are UI-only; only positive native ACK changes active hardware. let deviceDraft=null,deviceBusy=false,deviceNote='',deviceRequest='',deviceRequestSeq=0,lastDeviceRefresh=0,lastDeviceRescan=0,applyMutePending=false,applyAfterDevice=null,applyBaseEpoch=0; - let deviceMatrixView='inputs',deviceMatrixWaitEpoch=null; // Never display old hardware pins after an APPLY ACK. + let deviceMatrixView='inputs',deviceMatrixWaitEpoch=null,deviceMatrixOpen=false; // Never display old hardware pins after an APPLY ACK. // Pending SOURCE ACK is a UI projection only; monitor.js owns the native route. let quickSourcePending=null; const el=id=>document.getElementById(id); @@ -248,13 +248,19 @@ return section; } + // Only an ACKed physical MAIN pair is a MAIN route. Available output pins + // are merely inventory, never proof that a route has been selected. const outputLabel=s=>{ - const out=s.mainOutputs?.length===2?s.mainOutputs:s.outputPorts||[]; - return s.ready&&Number.isInteger(out[0])&&Number.isInteger(out[1])? - 'MAIN → HW '+(out[0]+1)+'/'+(out[1]+1):'MAIN → NO HW OUTPUT'; + const out=s.mainOutputs,enabled=new Set(s.outputPorts||[]); + if(!s.ready)return 'MAIN → NO DEVICE'; + if(!Array.isArray(out)||out.length!==2)return 'MAIN → UNPATCHED'; + if(!Number.isInteger(out[0])||!Number.isInteger(out[1])|| + out[0]===out[1]||!enabled.has(out[0])||!enabled.has(out[1])) + return 'MAIN → INVALID L/R'; + return 'MAIN → HW '+(out[0]+1)+'/'+(out[1]+1); }; const toolbar=node('div','arMixerBankBar'); - toolbar.innerHTML='
NO HARDWARE · PREVIEW
'; + toolbar.innerHTML='
NO HARDWARE · PREVIEW
'; host.insertBefore(toolbar,mixer); // One genuinely selected-channel journey, NOT another DSP or source registry. // Four compact steps show ACKNOWLEDGED state, never stage a hidden graph. @@ -453,7 +459,7 @@ sofControls.hidden=true;toolbar.appendChild(sofControls); const overlay=node('div','arIOOverlay'); overlay.id='arIOOverlay';overlay.hidden=true; - overlay.innerHTML=''; + overlay.innerHTML=''; document.body.appendChild(overlay); const audioPath=node('div','arIOAudioPath');audioPath.id='arIOAudioPath'; audioPath.innerHTML='CAPTURE · WAITROUTE · WAITMIXER · WAITOUTPUT · WAIT'; @@ -769,7 +775,7 @@ window.__arMixOpenAudioIO=openIO; function closeIO(){overlay.hidden=true;matrixDraft.clear();matrixSide.clear();matrixMessage='';} function setMode(next){ - if(!['FX','ROUTE','SENDS'].includes(next))return; + if(!['CONSOLE','FX','ROUTE','SENDS'].includes(next))return; if(next!=='SENDS'&&sofBus>=0)leaveSof(); mode=next;mixer.dataset.ioMode=mode; toolbar.querySelectorAll('[data-mix-mode]').forEach(b=>{const selected=b.dataset.mixMode===mode;b.classList.toggle('active',selected);b.setAttribute('aria-pressed',String(selected));}); @@ -788,7 +794,7 @@ } if(strip.querySelector('.arChannelBank'))continue; const bank=node('div','arChannelBank'); - bank.innerHTML='
INPUT SOURCE · NATIVEOUTPUT DESTINATIONMAIN · UNKNOWN
NATIVE PATCH REQUIRED
AUX SENDS · PRE / POST
'; + bank.innerHTML='
INPUT SOURCE · NATIVEOUTPUT DESTINATION
NATIVE PATCH REQUIRED
AUX SENDS · PRE / POST
'; strip.querySelector('.rack')?.insertAdjacentElement('afterend',bank); } } @@ -828,8 +834,22 @@ const dirty=current!==valueFor(accepted)||channelFormat(r)!==channelFormat(accepted); const stage=strip.querySelector('.arBankStage'); const sourcePending=quickSourcePending?.channel===i&&quickSourcePending.epoch===s.epoch; - stage.textContent=!s.ready?'NO LIVE DEVICE':sourcePending?'PENDING · NATIVE ACK':dirty?'DRAFT · NOT APPLIED':r.mode==='NONE'?'UNPATCHED · SILENT':'LIVE · NATIVE ACK'; - stage.dataset.state=!s.ready?'offline':sourcePending?'draft':dirty?'draft':r.mode==='NONE'?'offline':'live'; + const verified=new Set(portList(s).map(p=>p.port)); + const validInput=r.mode==='NONE'|| + (r.mode==='MONO'&&verified.has(r.left)&&r.right===-1)|| + (r.mode==='STEREO'&&r.left!==r.right&&verified.has(r.left)&&verified.has(r.right)); + const acceptedValid=!accepted||accepted.mode==='NONE'|| + (accepted.mode==='MONO'&&verified.has(accepted.left)&&accepted.right===-1)|| + (accepted.mode==='STEREO'&&accepted.left!==accepted.right&&verified.has(accepted.left)&&verified.has(accepted.right)); + // Source is real hardware, processing M/ST is independent. A restored + // invalid legacy alias is NEVER 'ACK/LIVE', even after a native route ACK. + stage.textContent=!s.ready?'NO VERIFIED DEVICE': + sourcePending?'PENDING · NATIVE ACK': + (!validInput||!acceptedValid)?'INVALID PHYSICAL INPUT · RE-PATCH': + dirty?'DRAFT · NOT APPLIED':r.mode==='NONE'?'UNPATCHED · NO INPUT': + 'ROUTE ACK · PCM UNVERIFIED'; + stage.dataset.state=!s.ready?'offline':sourcePending||dirty?'draft': + (!validInput||!acceptedValid)?'invalid':r.mode==='NONE'?'offline':'ack'; // Four native AUX destinations are always visible, even when empty. // Render only after a topology change, never on meter telemetry. const slots=Array.from({length:4},(_,bus)=>{ @@ -869,6 +889,28 @@ if(info.textContent!==caption)info.textContent=caption; toolbar.querySelector('[data-mix-apply]').disabled=!isNative()||!s.ready||!!s.pending||(!overlay.hidden&&matrixDraft.size>0); for(const strip of mixer.querySelectorAll('.strip[data-strip]'))refreshStrip(strip,s); + // Read-only pinned MAIN route. Reattach on master DOM regeneration but + // do not alter its fader, meters, FX, callback or native router. + const master=mixer.querySelector('#masterLeft'); + if(master){ + let summary=master.querySelector('.arMainOutSummary'); + if(!summary){ + summary=node('div','arMainOutSummary'); + summary.setAttribute('aria-label','Accepted physical MAIN routing'); + const heading=node('span','arMainOutHeading','MAIN OUT · NATIVE'); + const output=node('button','arMainOutAction'); + output.type='button';output.dataset.mixPatch='output'; + output.dataset.master='1';output.title='Configure physical MAIN L/R (native ACK)'; + summary.append(heading,output); + master.querySelector('.master-ch-id')?.insertAdjacentElement('afterend',summary); + } + const output=summary.querySelector('.arMainOutAction'); + if(output){ + const next=outputLabel(s); + if(output.textContent!==next)output.textContent=next; + output.disabled=!isNative()||!s.ready; + } + } if(!overlay.hidden)refreshIO(); if(!sendEditor.hidden)drawSendEditor(); sofRefresh(s); @@ -916,7 +958,7 @@ const title=node('header','arIOQuickHeader'); const words=node('div',''); words.append(node('strong','','1 · INTERFACE INPUT → MIXER CHANNEL'), - node('small','','Choose a channel, mono/stereo source and actual driver input(s). STAGE → MUTE → APPLY.')); + node('small','','Choose one channel and one or two distinct verified capture pins. USE INPUT commits through native ACK.')); const jump=node('select','arIOJump'); jump.dataset.ioJump='1';jump.setAttribute('aria-label','Find mixer channel'); for(let i=0;i<10;i++){ @@ -944,15 +986,20 @@ for(let i=0;i<10;i++){ const r=channelState(s,i),accepted=s.acceptedRoute?.channels?.[i]; const row=node('div','arIOQuickRow');row.dataset.ioQuickRow=String(i); + row.hidden=i!==focusedInput; row.dataset.state=!s.ready?'offline':valueFor(r)!==valueFor(accepted)?'draft': r.mode==='NONE'?'empty':'live'; const identity=node('div','arIOQuickIdentity'); identity.append(node('strong','','CH '+String(i+1).padStart(2,'0')),node('small','',matrixLogicalName(i))); const mode=node('select','arIOQuickMode');mode.dataset.ioQuickMode='1'; mode.setAttribute('aria-label','CH '+(i+1)+' physical input type'); - for(const pair of [['NONE','NO INPUT'],['MONO','MONO'],['STEREO','STEREO'], + for(const pair of [['NONE','NO INPUT'],['MONO','MONO'],['STEREO','STEREO · 2 PINS'], ...(r.mode==='BUS'?[['BUS','INTERNAL BUS']]:[])]){ - const option=node('option','',pair[1]);option.value=pair[0];option.selected=r.mode===pair[0];mode.appendChild(option); + const option=node('option','',pair[1]);option.value=pair[0];option.selected=r.mode===pair[0]; + // An accepted legacy invalid stereo route must remain inspectable, + // but new STEREO selection requires two distinct enabled driver pins. + if(pair[0]==='STEREO'&&verified.length<2&&r.mode!=='STEREO')option.disabled=true; + mode.appendChild(option); } const left=sourceSelect(i,'left',r.left),right=sourceSelect(i,'right',r.right); left.disabled=!hardwareReady(s)||r.mode==='NONE'||r.mode==='BUS'; @@ -962,12 +1009,23 @@ const stage=node('button','btn-180 arIOQuickStage','USE INPUT'); stage.dataset.ioQuickStage='1';stage.type='button'; stage.disabled=!hardwareReady(s)||r.mode==='BUS'; - action.append(stage,node('small','arIOQuickState',r.mode==='BUS'?'INTERNAL BUS': + const stereoInvalid=r.mode==='STEREO'&&(!verified.some(p=>p.port===r.left)|| + !verified.some(p=>p.port===r.right)||r.left===r.right); + if(stereoInvalid){ + row.dataset.state='invalid'; + // On a one-pin device, the accepted legacy stereo L=R route cannot + // be usable stereo. Offer ONE explicit native-safe MONO correction. + if(verified.length===1&&verified[0].port===r.left){ + stage.textContent='FIX AS MONO';stage.dataset.ioQuickFix='1'; + } + } + action.append(stage,node('small','arIOQuickState',stereoInvalid? + 'INVALID STEREO · SELECT DISTINCT L/R':r.mode==='BUS'?'INTERNAL BUS': !s.ready?'NO DEVICE':row.dataset.state==='draft'?'DRAFT · NOT LIVE': - row.dataset.state==='live'?'LIVE · ACK':'UNPATCHED')); + row.dataset.state==='live'?'ROUTE ACK · CHECK PCM':'UNPATCHED')); row.append(identity,mode,left,right,action);section.appendChild(row); } - section.appendChild(node('p','arIOQuickFooter','Select verified inputs, click USE INPUT. Native routing handles any required safe mute, ACK and re-arm automatically.')); + section.appendChild(node('p','arIOQuickFooter','ONE ACTION: USE INPUT → native safe route/ACK. No input PCM? Send playback into the selected recording endpoint, then check SIGNAL CHECK.')); return section; } function stageQuickInput(button){ @@ -975,7 +1033,8 @@ const s=route(),pins=new Set(matrixPorts(s,'inputs')); if(!row||!Number.isInteger(channel)||channel<0||channel>=10||!hardwareReady(s)) return matrixSay('Choose an active driver and wait for any previous APPLY.'); - const mode=row.querySelector('[data-io-quick-mode]').value, + const mode=button.dataset.ioQuickFix==='1'?'MONO': + row.querySelector('[data-io-quick-mode]').value, left=Number(row.querySelector('[data-io-quick-pin="left"]').value), right=Number(row.querySelector('[data-io-quick-pin="right"]').value); if(mode==='MONO'&&!pins.has(left))return matrixSay('CH '+(channel+1)+' · choose a valid mono input.'); @@ -1397,7 +1456,7 @@ hidden.value=d.backend;panel.appendChild(hidden); } const same=deviceSameEndpoint(d),advanced=node('details','arIODeviceAdvanced'); - advanced.appendChild(node('summary','','BUFFER / SAMPLE RATE / HARDWARE PIN ENABLE')); + advanced.appendChild(node('summary','','ADVANCED · BUFFER / SAMPLE RATE')); const fields=node('div','arIODeviceFields'); const rateOpts=[[0,'AUTO · driver default']],bufferOpts=[[0,'AUTO · driver default']]; if(same){ @@ -1412,6 +1471,12 @@ deviceSelect('arIODeviceBuffer',d.bufferSize,bufferOpts,deviceBusy||!isNative()))); advanced.appendChild(fields); const pins=node('div','arIODevicePins'); + const pinHeading=node('div','arIOPinHeading'); + const enabledCount=Array.isArray(d.enabledInputs)?d.enabledInputs.length:0; + pinHeading.append(node('strong','','HARDWARE PORTS · ENABLE INPUTS / OUTPUTS'), + node('span','',enabledCount+' capture pin(s) selected · '+(enabledCount<2? + 'MONO ONLY until a second distinct input is enabled':'MONO / STEREO PAIRS POSSIBLE'))); + panel.appendChild(pinHeading); for(const [direction,names,selectedPins] of [ ['INPUT',same?a.inputNames:[],d.enabledInputs], ['OUTPUT',same?a.outputNames:[],d.enabledOutputs]]){ @@ -1431,7 +1496,9 @@ }); pins.appendChild(side); } - advanced.appendChild(pins);panel.appendChild(advanced); + // Input/output pin enabling is a BASIC step, not an advanced matrix. + // The original native device draft/ACK path remains unchanged. + panel.appendChild(pins);panel.appendChild(advanced); } const actions=node('div','arIODeviceActions'); const refresh=node('button','btn-180 arIODeviceRefresh','REFRESH DEVICES'); @@ -1451,9 +1518,18 @@ devicePinNextStep())); panel.appendChild(actions);body.appendChild(panel); - const matrixSection=node('section','arIODevicePatchMatrix'); - const heading=node('div','arIODeviceMatrixHeading'); - heading.appendChild(node('strong','','AUDIO I/O · REAL PORT MATRIX')); + const matrixSection=node('details','arIODevicePatchMatrix'); + matrixSection.open=deviceMatrixOpen; + matrixSection.addEventListener('toggle',()=>{ + if(deviceMatrixOpen!==matrixSection.open){ + deviceMatrixOpen=matrixSection.open; + // Expensive crosspoints are constructed on demand, never just hidden + // behind CSS while a 12Hz native readback refreshes the device panel. + lastSignature='';refreshIO(); + } + }); + const heading=node('summary','arIODeviceMatrixHeading'); + heading.appendChild(node('strong','','ADVANCED · HARDWARE PORT MATRIX (OPTIONAL)')); const tabs=node('div','arIODeviceMatrixSwitch'); for(const [value,label] of [['inputs','INPUTS'],['outputs','OUTPUTS']]){ const b=node('button','arIODeviceMatrixTab',label);b.type='button'; @@ -1462,6 +1538,12 @@ tabs.appendChild(b); } heading.appendChild(tabs);matrixSection.appendChild(heading); + if(!deviceMatrixOpen){ + matrixSection.appendChild(node('p','arIODeviceMatrixEmpty', + 'Optional engineering crosspoints. Open only for advanced pin patching.')); + body.appendChild(matrixSection); + return; + } const live=!!d&&deviceSameEndpoint(d)&&a.authorized!==false; const s=route(); if(deviceMatrixWaitEpoch!==null&&s.epoch!==deviceMatrixWaitEpoch&&s.ready&&s.active) @@ -1502,7 +1584,10 @@ }); overlay.dataset.activeTab=ioTab; const matrixInDevice=ioTab==='device'&&deviceSameEndpoint(deviceDraft)&&hardwareReady(s); - overlay.querySelector('[data-mix-apply]').hidden=ioTab==='device'; + overlay.querySelector('[data-mix-apply]').hidden=ioTab==='device'|| + (ioTab==='inputs'&&!advancedMatrixOpen); + overlay.querySelector('[data-mix-apply]').textContent= + ioTab==='outputs'?'APPLY MAIN OUT':'APPLY ADVANCED'; overlay.querySelector('[data-io-revert]').hidden=ioTab==='device'&&!matrixInDevice; overlay.querySelector('[data-io-internal]').hidden=ioTab==='device'; overlay.querySelector('[data-io-device-apply]').hidden=ioTab!=='device'; @@ -1528,6 +1613,8 @@ if(previous)advancedMatrixOpen=previous.open; const previousDirect=body.querySelector('.arIODeviceDirectMatrix'); if(previousDirect)directMatrixOpen=previousDirect.open; + const previousHardware=body.querySelector('.arIODevicePatchMatrix'); + if(previousHardware)deviceMatrixOpen=previousHardware.open; body.replaceChildren(); if(ioTab!=='device'){ const identity=node('div','arIOHardwareHeader'); @@ -1543,10 +1630,43 @@ body.appendChild(makeQuickInputs(s)); const advanced=node('details','arIOAdvancedMatrix'); advanced.open=advancedMatrixOpen; - advanced.appendChild(node('summary','','ADVANCED M / L / R CROSSPOINT · SAME NATIVE ROUTING')); + advanced.addEventListener('toggle',()=>{ + advancedMatrixOpen=advanced.open; + overlay.querySelector('[data-mix-apply]').hidden=!advanced.open; + }); + advanced.appendChild(node('summary','','ADVANCED · MANUAL INPUT CROSSPOINTS')); advanced.appendChild(makeMatrix(s,ioTab)); body.appendChild(advanced); - }else body.appendChild(makeMatrix(s,ioTab)); + }else{ + // MAIN Left/Right must be visible before the engineering matrix. + // The same __arMixStageMainOutputs owns both paths. + const simple=node('section','arIOSimpleMain'); + simple.append(node('strong','','MAIN OUTPUT · STEREO PAIR'), + node('p','','Select two different enabled hardware outputs. APPLY OUTPUT publishes native routing; no browser sound is generated.')); + const outputPorts=matrixPorts(s,'outputs'); + const accepted=s.mainOutputs?.length===2?s.mainOutputs:[]; + const picked=s.draftMainOutputs?.length===2?s.draftMainOutputs:accepted; + const pickers=node('div','arIOSimpleMainRow'); + for(let side=0;side<2;side++){ + const label=node('label','arIOSimpleMainField'); + label.append(node('span','',side===0?'MAIN LEFT':'MAIN RIGHT')); + const select=node('select','arIOMainOutput');select.dataset.side=String(side); + const empty=node('option','','Choose verified output…');empty.value='-1';select.append(empty); + for(const port of outputPorts){ + const opt=node('option','','HW OUT '+(port+1));opt.value=String(port); + opt.selected=port===picked[side];select.appendChild(opt); + } + select.disabled=!hardwareReady(s)||s.pending||outputPorts.length<2; + label.append(select);pickers.append(label); + } + simple.append(pickers); + body.append(simple); + const advanced=node('details','arIOAdvancedMatrix'); + advanced.open=advancedMatrixOpen; + advanced.append(node('summary','','ADVANCED · OUTPUT CROSSPOINTS / MONITOR')); + advanced.append(makeMatrix(s,ioTab)); + body.append(advanced); + } } if(ioTab==='inputs'){ body.appendChild(node('p','arIOHint','MAONO PS22 virtual inputs appear here ONLY if its selected driver enumerates them as capture ports. Configure MAONO Routing Center and select the appropriate PS22 ASIO/recording endpoint in DEVICE / DRIVER. Separate Windows capture endpoints cannot be silently combined into one device. Processing MONO/STEREO is independent of physical source mode.')); @@ -1584,26 +1704,9 @@ body.appendChild(node('p','arIOHint','LIVE MONITOR: '+ (monitorLive.length===2?'HW '+(monitorLive[0]+1)+'/'+(monitorLive[1]+1):'DISABLED')+ ' · Independent POST-fader mix; all changes require MUTE → APPLY → ACK.')); - const details=node('details','arIOQuickMap'); - details.appendChild(node('summary','','QUICK OUTPUT SELECTION · ACCESSIBLE ALTERNATIVE')); - const accepted=s.mainOutputs?.length===2?s.mainOutputs:[]; - const draft=s.draftMainOutputs?.length===2?s.draftMainOutputs:accepted; - const ports=matrixPorts(s,'outputs'); - for(const [i,label] of ['MAIN LEFT','MAIN RIGHT'].entries()){ - const row=node('label','arIOOutputRow'); - const selector=node('select','arIOMainOutput'); - selector.dataset.side=String(i); - selector.setAttribute('aria-label',label+' destination'); - for(const p of ports){ - const option=node('option','','HW OUT '+(p+1)); - option.value=String(p);option.selected=p===draft[i];selector.appendChild(option); - } - selector.disabled=!hardwareReady(s)||ports.length<2; - row.append(node('strong','',label),selector);details.appendChild(row); - } - body.appendChild(details); - body.appendChild(node('p','arIOHint','LIVE MAIN: '+(accepted.length===2?'HW '+(accepted[0]+1)+'/'+(accepted[1]+1):'UNAVAILABLE')+ - ' · Only native-ACKed MAIN/MONITOR pairs can carry sound. AUX1–4 are internal stereo FX returns, not physical output sockets.')); + const acknowledged=s.mainOutputs?.length===2?s.mainOutputs:[]; + body.appendChild(node('p','arIOHint','NATIVE MAIN: '+(acknowledged.length===2?'HW '+(acknowledged[0]+1)+' / '+(acknowledged[1]+1):'UNAVAILABLE')+ + ' · Selection is DRAFT until native APPLY/ACK. AUX1–4 are internal FX returns, not hardware ports.')); }else{ renderCustomDevice(body); } @@ -1652,6 +1755,7 @@ } if(e.target.matches('[data-io-jump]')){ focusedInput=Number(e.target.value); + lastSignature='';refreshIO(); overlay.querySelector('[data-io-quick-row="'+focusedInput+'"]')?.scrollIntoView({block:'nearest'}); return; } @@ -1717,6 +1821,7 @@ if(!route().ready)openIO('device'); else openSourceChooser(index); } else if(step==='fx'){ + // The existing FX-only engineering layer remains an optional inspector. setMode('FX'); if(typeof chooseChannel==='function')chooseChannel(index); strip?.querySelector('.rack')?.scrollIntoView?.({block:'nearest',inline:'nearest'}); @@ -1890,6 +1995,7 @@ e.preventDefault();e.stopImmediatePropagation(); const strip=b.closest('[data-strip]'),channel=Number(strip?.dataset.strip)||0; if(b.dataset.mixPatch==='input')openIO('inputs',channel); + else if(b.dataset.mixPatch==='output')openIO('outputs',channel); else window.__arMixOpenChannelPatch?.(channel,b.dataset.mixPatch); return; } @@ -2077,5 +2183,6 @@ closeSendEditor(); } },true); - setMode('FX'); + // The ACTUAL M4 WebView2 mixer now opens as one integrated operator console. + setMode('CONSOLE'); })(); diff --git a/web/mixer-layout.css b/web/mixer-layout.css index 7a9ecf2b4..c9eac0d14 100644 --- a/web/mixer-layout.css +++ b/web/mixer-layout.css @@ -251,3 +251,1173 @@ @media(max-width:1366px){ #app .toolbar .project{max-width:130px;flex-basis:130px} } + + +/* ARSONMIX V6 PREMIUM LIVE CONSOLE — low-compositor-cost fixed strip grid. + Browser demo and native capability-gated shell share exactly the same DOM. */ +#app #arV6Console{display:none} +.ar-v6-active #app .left-rail{display:none!important} +.ar-v6-active #app .workbench{display:flex!important;flex:1 1 0;min-width:0;min-height:0;overflow:hidden} +.ar-v6-active #app #mixer, +.ar-v6-active #app #rackWorkspace{display:none!important} +.ar-v6-active #app .toolbar-actions.arSegmentedToolbar .nav, +.ar-v6-active #app .arMixerChannelPager{display:none!important} +#app .arV6Console, #app .arV6Console *{box-sizing:border-box} +.ar-v6-active #app #arV6Console{ + display:grid;grid-template-rows:51px auto minmax(0,1fr); + width:100%;height:100%;min-width:0;min-height:0;overflow:hidden; + background:linear-gradient(180deg,#23313a,#111b23 90px,#0c151c 100%); + color:#d3e0e6;font:11px/1.35 "ArSonMix Inter","Segoe UI",sans-serif; +} +#app .arV6Top{ + display:flex;justify-content:space-between;align-items:center; + gap:12px;padding:6px 13px;border-bottom:1px solid #435967; + background:linear-gradient(180deg,#33444e,#192833); + min-width:0; +} +#app .arV6Identification{display:flex;align-items:center;gap:11px;min-width:0;overflow:hidden} +#app .arV6Kicker{font:600 10px/1.2 "Segoe UI",sans-serif;letter-spacing:1.1px;white-space:nowrap;color:#d3e4ec} +#app .arV6Device{color:#92b3c1;font:10px/1.25 "Segoe UI",sans-serif;overflow:hidden;white-space:nowrap;text-overflow:ellipsis} +#app .arV6State{padding:4px 7px;border:1px solid #607782;border-radius:3px;white-space:nowrap;color:#e0dbad;font:600 9px/1 "Segoe UI",sans-serif} +#app .arV6Console[data-armed="true"] .arV6State{color:#a8e6cd;border-color:#396c62} +#app .arV6Tools{display:flex;align-items:center;gap:6px;flex:none} +#app .arV6Button,#app .arV6Select{ + font:500 10px/1.2 "Segoe UI",sans-serif; + color:#d5e5eb;background:linear-gradient(180deg,#354956,#1c303b); + border:1px solid #526e7a;border-radius:3px;min-height:25px; + padding:4px 7px;min-width:0; +} +#app .arV6Button{cursor:pointer} +#app .arV6Button:focus-visible,#app .arV6Select:focus-visible, +#app .arV6Fader:focus-visible,#app .arV6PanRange:focus-visible{ + outline:2px solid #62cce8;outline-offset:1px; +} +#app .arV6Button:disabled,#app .arV6Select:disabled, +#app .arV6Fader:disabled,#app .arV6PanRange:disabled{opacity:.48;cursor:not-allowed} +#app .arV6BankLabel{min-width:72px;text-align:center;color:#abc3cf;font:10px Consolas,monospace;white-space:nowrap} +#app .arV6SendMode{max-width:126px} +#app .arV6Message{ + font:10px/1.3 "Segoe UI",sans-serif; + padding:5px 12px;color:#e2caaa;background:#28333a; + border-bottom:1px solid #46535a;overflow:hidden;text-overflow:ellipsis;white-space:nowrap; +} +#app .arV6Message[hidden]{display:none} +#app .arV6Body{display:flex;min-width:0;min-height:0;overflow:hidden} +#app .arV6Lanes{ + display:flex;flex:1 1 0;min-width:0;min-height:0; + overflow-x:auto;overflow-y:hidden;scrollbar-width:thin; + scrollbar-color:#486171 #0e1b25;scroll-snap-type:x proximity; +} +#app .arV6Main{ + display:flex;flex:0 0 178px;max-width:178px;min-height:0; + border-left:2px solid #6b8993; + background:#22313c;z-index:1; +} +#app .arV6NoMaster{padding:15px;color:#e2ae97;font-size:11px} +#app .arV6Strip{ + --v6-strip-color:#5f9ab1; + display:grid;grid-template-rows:37px 235px 52px minmax(105px,1fr) 26px; + flex:0 0 167px;width:167px;min-height:0;height:100%; + padding:0 7px 5px;border-right:1px solid #354955; + background:linear-gradient(90deg,#1b2b35 0%,#263741 14%,#263741 87%,#15252e); + scroll-snap-align:start;overflow:hidden; +} +#app .arV6Strip.arV6Master{ + flex:1 0 0;width:100%; + background:linear-gradient(90deg,#2a414b,#283b47 88%,#172934); +} +#app .arV6StripHead{ + display:flex;flex-direction:column;justify-content:center;gap:3px; + min-width:0;border-bottom:1px solid #496473; +} +#app .arV6Role{font:600 9px/1 "Segoe UI",sans-serif;letter-spacing:.9px;color:#88adbc} +#app .arV6Name{font:600 12px/1.2 "Segoe UI",sans-serif;color:#ecf1f3; + white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +#app .arV6Upper{ + display:grid;grid-template-rows:31px 31px minmax(83px,1fr) minmax(54px,auto) 31px; + min-height:0;overflow:hidden;padding:6px 0 4px; + border-bottom:1px solid #3b4d57; +} +#app .arV6Field{display:flex;align-items:center;gap:5px;min-width:0} +#app .arV6FixedField{color:#91afbb;white-space:nowrap;font:9px Consolas,monospace} +#app .arV6FieldName{flex:0 0 27px;font:600 9px/1 "Segoe UI",sans-serif;color:#8faebc} +#app .arV6Field .arV6Select{flex:1 1 0;width:100%;max-width:116px;min-height:23px;padding:2px 3px} +#app .arV6Fx,#app .arV6Sends{ + min-height:0;overflow-x:hidden;overflow-y:auto;scrollbar-width:thin; + display:flex;flex-direction:column;gap:3px; + border-top:1px solid #354b57;padding-top:5px; +} +#app .arV6SectionTitle{font:600 9px/1.2 "Segoe UI",sans-serif;letter-spacing:.6px;color:#83aaba} +#app .arV6FxSlot,#app .arV6Send{display:flex;gap:3px;align-items:center;min-width:0} +#app .arV6FxSlot .arV6Button:first-child{ + flex:1 1 0;text-align:left;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; + background:#172b35;border-color:#476270;color:#c9dfe7; +} +#app .arV6FxSlot .arV6Button:last-child{flex:0 0 29px;width:29px;padding:3px 0;color:#9ee0bb} +#app .arV6FxSlot .arV6Button.isOff{color:#95a1a9} +#app .arV6AddFx{width:100%;min-height:23px!important;padding:3px!important;text-align:left;color:#90c9d8!important} +#app .arV6SendName{ + flex:1 1 0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#bfd2dc; + font:10px/1.1 "Segoe UI",sans-serif; +} +#app .arV6Send .arV6Button{min-height:20px;padding:2px 5px} +#app .arV6Controls{display:grid;grid-template-columns:minmax(0,1fr) 28px 28px;align-items:center; + gap:5px;border-bottom:1px solid #445863} +#app .arV6Controls .arV6Button{width:28px;min-height:28px;padding:0;font-size:11px} +#app .arV6Controls .arV6Button[aria-pressed="true"]{border-color:#bba35d;background:#61532b;color:#fff0ac} +#app .arV6Pan{display:flex;flex-direction:column;gap:2px;min-width:0;color:#86abb9;font-size:9px} +#app .arV6PanRange{ + width:100%;min-width:0;height:14px;margin:0;cursor:ew-resize; + appearance:none;-webkit-appearance:none;background:transparent; +} +/* Browser engines reject an entire selector list if either vendor + pseudo-element is unknown. Keep both tracks separate and identical. */ +#app .arV6PanRange::-webkit-slider-runnable-track{ + height:5px;border:1px solid #47616e;border-radius:1px; + background:linear-gradient(to right,#1c303a 0%,#1c303a var(--v6-pan-start,50%), + #55c0d5 var(--v6-pan-start,50%),#55c0d5 var(--v6-pan-end,50%), + #1c303a var(--v6-pan-end,50%),#1c303a 100%); +} +#app .arV6PanRange::-moz-range-track{ + height:5px;border:1px solid #47616e;border-radius:1px; + background:linear-gradient(to right,#1c303a 0%,#1c303a var(--v6-pan-start,50%), + #55c0d5 var(--v6-pan-start,50%),#55c0d5 var(--v6-pan-end,50%), + #1c303a var(--v6-pan-end,50%),#1c303a 100%); +} +#app .arV6PanRange::-webkit-slider-thumb{ + -webkit-appearance:none;appearance:none;width:10px;height:13px;margin-top:-5px; + border:1px solid #101c26;border-radius:2px;background:#abc5d0; +} +#app .arV6PanRange::-moz-range-thumb{ + width:10px;height:13px;border:1px solid #101c26;border-radius:2px;background:#abc5d0; +} +#app .arV6Lower{display:flex;gap:16px;align-items:center;justify-content:center; + padding:7px 5px 2px;min-height:0;position:relative} +#app .arV6Meter{ + display:flex;flex-direction:row;justify-content:center;gap:2px; + width:24px;height:100%;max-height:100%;min-height:70px;padding:2px; + border:1px solid #15242c;background:#02080d;box-shadow:inset 1px 0 #516673; +} +#app .arV6MeterLane{ + display:flex;flex:1 1 0;flex-direction:column-reverse; + justify-content:space-between;gap:1px;min-width:0;min-height:0; +} +#app .arV6Meter[data-format="MONO"] .arV6MeterLane[data-side="R"]{display:none} +#app .arV6Led{display:block;flex:1 1 0;min-height:2px;background:#172b30} +#app .arV6Led.lit{background:#29b277} +#app .arV6Led:nth-child(n+15).lit{background:#d8ac44} +#app .arV6Led:nth-child(n+20).lit{background:#dc6148} +#app .arV6Fader{ + writing-mode:vertical-lr;direction:rtl; + height:100%;min-height:75px;width:46px;min-width:46px;margin:0; + cursor:pointer;appearance:none;-webkit-appearance:none;background:transparent; +} +#app .arV6Fader::-webkit-slider-runnable-track{ + width:11px;min-height:100%;border:1px solid #02080d;border-radius:3px; + background:linear-gradient(90deg,#050a0f 0%,#182c36 45%,#061018 100%); + box-shadow:inset 1px 0 #58737d,inset -1px 0 #050b10; +} +#app .arV6Fader::-webkit-slider-thumb{ + -webkit-appearance:none;appearance:none; + width:44px;height:24px;border:0;border-radius:2px; + background:transparent url("assets/fader-silver2.png") center/contain no-repeat; +} +#app .arV6Fader::-moz-range-thumb{ + width:43px;height:23px;border:0;border-radius:2px; + background:transparent url("assets/fader-silver2.png") center/contain no-repeat; +} +#app .arV6Readout{ + position:absolute;bottom:3px;right:3px; + font:10px Consolas,monospace;color:#b7cbd5; +} +#app .arV6StripStatus{ + display:flex;align-items:center;min-width:0;overflow:hidden; + font:600 9px/1.2 "Segoe UI",sans-serif;letter-spacing:.15px; + color:#91b6c3;white-space:nowrap;text-overflow:ellipsis; +} +#app .arV6Console[data-demo="true"] .arV6StripStatus{color:#d9b98a} +#app .arV6Console[data-demo="true"] .arV6State{color:#e6bf8e;border-color:#986d46} +#app #arV6Return{min-height:29px;flex:0 0 auto} +#app #arV6Return[hidden]{display:none!important} +@media(max-width:1366px){ + #app .arV6Kicker{max-width:176px;overflow:hidden;text-overflow:ellipsis} + #app .arV6Strip{flex-basis:155px;width:155px;padding-left:6px;padding-right:6px} + #app .arV6Main{flex-basis:166px;max-width:166px} + #app .arV6Tools{gap:3px} +} +@media(max-width:1100px){ + #app .arV6Top{padding:5px 7px} + #app .arV6Kicker{display:none} + #app .arV6SendMode{max-width:105px} +} +@media(max-height:790px){ + #app .arV6Strip{grid-template-rows:32px 197px 45px minmax(85px,1fr) 22px} + #app .arV6Upper{grid-template-rows:27px 27px minmax(74px,1fr) minmax(43px,auto) 27px;padding-top:3px} + #app .arV6Top{min-height:44px} + #app .arV6Console .arV6Button{min-height:22px} +} +@media(max-height:690px){ + #app .arV6Strip{grid-template-rows:28px 160px 40px minmax(75px,1fr) 18px} + #app .arV6Upper{grid-template-rows:24px 24px minmax(54px,1fr) minmax(34px,auto) 24px} + #app .arV6SectionTitle{font-size:8px} + #app .arV6FxSlot .arV6Button{min-height:18px} + #app .arV6Device{font-size:9px} +} + +#app .arV6RoleSelect{width:78px;max-width:78px} +#app .arV6FxSlot[draggable="true"]{cursor:grab} +#app .arV6FxSlot[draggable="true"]:active{cursor:grabbing} +#app .arV6PluginChoice{width:100%;max-width:100%;min-height:23px} + + +/* ARSONMIX M4 UNIFIED OPERATOR CONSOLE — real WebView2 / JUCE path. + Single native-source view: IN -> M/ST -> FX -> AUX SEND -> MAIN -> FADER. + The existing mixer-io.js + monitor.js keep exclusive routing authority. + Zero CSS filter blur, large glow, transformed hover layers or extra canvas. */ +#app #mixer[data-io-mode="CONSOLE"]{ + align-items:stretch; + background:#0c1720; + scroll-snap-type:x proximity; +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip]{ + flex:0 0 146px;min-width:146px;max-width:146px; + display:flex;min-height:0;height:100%; + border-right:1px solid #334b58; + background:linear-gradient(90deg,#162631,#263741 8%,#22313c 88%,#152630); + box-shadow:inset 1px 0 #718a9938; + scroll-snap-align:start; +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip].selected{ + background:linear-gradient(90deg,#233e4b,#29424f 8%,#233845 88%,#152f3b); + box-shadow:inset 2px 0 #52d4ee; +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .ch-id{ + order:0;height:32px;min-height:32px;flex:0 0 32px; + font:600 13px/1 "Segoe UI",sans-serif; + justify-content:space-between;padding:0 9px; + background:linear-gradient(180deg,color-mix(in srgb,var(--ch) 34%,#2d404c),#172a35); + border-top:2px solid var(--ch);border-bottom:1px solid #3d5662; + text-shadow:none; +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] .arChannelQuickInput{ + display:none!important; +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .arChannelBank{ + order:1;display:flex!important;flex-direction:column; + flex:0 0 148px;height:148px;min-height:148px; + padding:5px 7px 4px;gap:4px; + background:linear-gradient(#142631,#152934); + border-bottom:1px solid #3b5460;overflow:hidden; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arRouteBank{ + display:grid!important;flex:0 0 79px;min-height:79px; + grid-template-columns:26px minmax(0,1fr); + grid-template-rows:24px 24px 24px; + gap:2px 4px;align-items:center;min-width:0; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arRouteBank > .arBankTitle{ + display:block;min-width:0;margin:0;line-height:1.1; + white-space:nowrap;overflow:hidden; + font:600 9px/1 "Segoe UI",sans-serif;color:#84b2c4; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arRouteBank > .arBankTitle:first-child{ + grid-column:1;grid-row:1;font-size:0; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arRouteBank > .arBankTitle:first-child::before{ + content:"IN";font:600 9px "Segoe UI",sans-serif; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arRouteBank > .arBankTitle:nth-of-type(2){ + grid-column:1;grid-row:2;font-size:0; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arRouteBank > .arBankTitle:nth-of-type(2)::before{ + content:"OUT";font:600 9px "Segoe UI",sans-serif; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arBankSource{ + grid-column:2;grid-row:1; + height:23px;min-height:23px;width:100%; + padding:2px 4px;font:10px/1.1 "Segoe UI",sans-serif; + border:1px solid #4e7282;border-radius:2px; + background:#091d28;color:#d0e6ef; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arBankOutput{ + grid-column:2;grid-row:2; + display:block;height:23px;min-height:23px;width:100%; + padding:3px 5px;text-align:left;white-space:nowrap;text-overflow:ellipsis; + border:1px solid #3c6271;border-radius:2px; + background:#142d39;color:#afd3df; + font:10px/1.1 "Segoe UI",sans-serif;cursor:pointer; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arBankOutput:hover{ + background:#1c3b4b; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arBankFormatRow{ + grid-column:1/-1;grid-row:3; + height:24px;min-height:24px;display:flex;align-items:center;gap:5px; + justify-content:space-between;overflow:hidden; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arBankChannelFormat{ + flex:0 0 60px;width:60px;max-width:60px;min-width:0; + min-height:21px;height:21px;padding:1px 3px; + background:#0c222e;border:1px solid #436777;color:#bcdbe5; + font:9px "Segoe UI",sans-serif; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arBankStage{ + display:block;min-width:0;flex:1 1 auto; + font:8px/1.1 "Segoe UI",sans-serif;white-space:nowrap; + text-align:right;overflow:hidden;text-overflow:ellipsis; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arRouteBank > .arBankPatch{ + display:none!important; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arSendBank{ + display:flex!important;flex:1 1 0;min-height:0; + flex-direction:column;gap:3px;overflow:hidden; + border-top:1px solid #355361;padding-top:4px; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arSendBank > .arBankTitle{ + flex:0 0 10px;display:block;font:600 9px/1 "Segoe UI",sans-serif; + color:#8ebccd; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arSendSummary{ + display:grid;grid-template-columns:repeat(2,minmax(0,1fr)); + grid-template-rows:repeat(2,20px);gap:2px;min-width:0;min-height:42px; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arSendChip{ + display:flex;align-items:center;gap:3px;min-width:0; + width:100%;height:20px;min-height:20px; + padding:2px 3px;border:1px solid #426474; + background:#152c37;border-radius:2px;font:9px/1 "Segoe UI",sans-serif; + overflow:hidden;text-overflow:ellipsis;white-space:nowrap; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arSendChip .arSendDest{ + font:600 8px/1 "Segoe UI",sans-serif;min-width:0;flex:none; +} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arSendBank > .arBankPatch{ + display:none!important; +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .rack{ + order:2;display:flex!important;flex:0 0 112px;height:112px;min-height:112px; + flex-direction:column;gap:3px;padding:6px 5px 4px; + overflow-x:hidden;overflow-y:auto;scrollbar-width:thin; + scrollbar-color:#456b7b #11242e; + border-bottom:1px solid #385460;background:#0f202b; +} +#app #mixer[data-io-mode="CONSOLE"] .rack .insert-slot{ + height:23px;min-height:23px;flex:0 0 23px; +} +#app #mixer[data-io-mode="CONSOLE"] .rack .insert{ + height:23px;min-height:23px; + font:10px/1 "Segoe UI",sans-serif; + border-color:#304b5b;box-shadow:none; + background:linear-gradient(#263c49,#122833); +} +#app #mixer[data-io-mode="CONSOLE"] .rack .insert.empty{ + border:1px dashed #315365;color:#70bdd1; +} +#app #mixer[data-io-mode="CONSOLE"] .rack .fx-power{ + width:23px;min-width:23px;height:23px;min-height:23px; + box-shadow:none;text-shadow:none;transition:none; +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .strip-controls{ + order:3;flex:0 0 78px;height:78px;min-height:78px; + padding:0;border-bottom:1px solid #324e5a; + background:#223440; +} +#app #mixer[data-io-mode="CONSOLE"] .strip-controls > .trim-row, +#app #mixer[data-io-mode="CONSOLE"] .strip-controls > .knob{ + display:none!important; +} +#app #mixer[data-io-mode="CONSOLE"] .strip-controls .pan-control{ + height:37px;min-height:37px;flex:0 0 37px; +} +#app #mixer[data-io-mode="CONSOLE"] .strip-controls .utility-row{ + height:31px;min-height:31px;flex:0 0 31px; + margin:0!important;padding:2px 6px; +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .channel-actions{ + order:4;height:35px;flex:0 0 35px;min-height:35px; + padding:3px 6px;gap:4px; +} +#app #mixer[data-io-mode="CONSOLE"] .channel-actions > button{ + height:27px!important;min-height:27px!important; +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .db-display{ + order:5;height:24px;flex:0 0 24px; + font:600 11px/1 Consolas,monospace;text-shadow:none; + color:#75cce4;background:#152934; +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .fader-zone{ + order:6;flex:1 1 auto;min-height:100px;overflow:hidden; +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .strip-name{ + order:7;height:44px;flex:0 0 44px;gap:3px; + font:600 11px/1 "Segoe UI",sans-serif;text-shadow:none; + background:linear-gradient(110deg,color-mix(in srgb,var(--ch) 45%,#101d26),#142936); +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .strip-name .track-icon{ + font-size:13px;line-height:14px; +} +#app #mixer[data-io-mode="CONSOLE"] > #masterLeft{ + flex:0 0 155px;min-width:155px;max-width:155px; + height:100%;position:sticky;right:0;z-index:3; + background:#293845;border-left:2px solid #a17f8b; + box-shadow:-5px 0 12px #06131a; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-ch-id{ + height:32px;flex:0 0 32px;min-height:32px; + font:600 12px "Segoe UI",sans-serif; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .arMainOutSummary{ + height:80px;min-height:80px;flex:0 0 80px; + display:flex;flex-direction:column;gap:8px;align-items:stretch; + padding:10px 8px;background:#19303c; + border-bottom:1px solid #3e6171; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .arMainOutHeading{ + font:600 9px/1 "Segoe UI",sans-serif;color:#a1c5d1; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .arMainOutAction{ + height:31px;min-height:31px;max-width:100%;overflow:hidden; + white-space:nowrap;text-overflow:ellipsis; + padding:3px 5px;border-radius:3px;border:1px solid #567583; + background:#203d4b;color:#e3ecf1; + font:10px/1.2 "Segoe UI",sans-serif;text-align:left; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .arMainOutAction:disabled{opacity:.48} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-fx-rack{ + flex:0 0 180px;height:180px;min-height:180px; + background:#152832; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-fx-slot{ + height:23px;min-height:23px;flex:0 0 23px; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-controls-zone{ + flex:0 0 78px;height:78px;min-height:78px; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-analysis{ + height:33px;min-height:33px;flex:0 0 33px;margin:2px 0; + overflow:hidden;padding:2px 5px; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-analysis .master-info-kicker{display:none} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-analysis .master-info-row{ + margin:0;font-size:8px;line-height:12px; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-pan-wrap{ + height:40px;min-height:40px;flex:0 0 40px; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-actions{ + height:35px;min-height:35px;flex:0 0 35px; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-db-display{ + height:24px;min-height:24px;flex:0 0 24px; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-fader-zone{ + flex:1 1 0;min-height:100px; +} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-strip-name{ + height:44px;min-height:44px;flex:0 0 44px; +} +#app .arRailModeSection .arMixerBankBar{ + height:auto;min-height:0;padding:5px;display:flex;flex-direction:column; + gap:5px;background:#14242d; +} +#app .arRailModeSection .arMixerBankModes{ + display:grid;grid-template-columns:1fr repeat(3,minmax(0,25px)); + width:100%;gap:2px; +} +#app .arRailModeSection .arMixerBankModes [data-mix-mode="CONSOLE"]{ + min-width:0;width:100%;background:#25495b;color:#d7eff7; + border-color:#547c8c;font-size:9px;padding:0 3px;letter-spacing:0; +} +#app .arRailModeSection .arMixerBankModes [data-mix-mode="CONSOLE"].active{ + background:#3b8695;color:#fff;border-color:#68b1bb; +} +#app .arRailModeSection .arMixerBankModes [data-mix-mode]:not([data-mix-mode="CONSOLE"]){ + width:25px;min-width:25px;padding:0; + font:600 8px "Segoe UI",sans-serif;letter-spacing:-.15px; +} +#app .arRailModeSection .arMixerBankBar .arMixApply{display:none} +#app .arRailModeSection .arMixerBankBar .arMixIoOpen{ + width:100%;height:30px;flex:none; +} +#app .arChannelSignalFlow{height:29px;min-height:29px;flex:0 0 29px} +#app .arChannelSignalFlow [data-focus-step]{ + font-size:9px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; +} +/* Four-layer engineering modes are retained for exact regression and + advanced work; the one-console mode is the M4 first-sound default. */ +@media(max-height:770px){ + #app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .arChannelBank{ + flex-basis:132px;height:132px;min-height:132px;padding-top:3px; + } + #app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arRouteBank{ + flex-basis:70px;min-height:70px;grid-template-rows:21px 21px 22px; + } + #app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arSendSummary{ + grid-template-rows:repeat(2,18px);min-height:38px; + } + #app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arSendChip{ + height:18px;min-height:18px; + } + #app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .rack{ + flex-basis:96px;height:96px;min-height:96px; + } + #app #mixer[data-io-mode="CONSOLE"] #masterLeft .arMainOutSummary{ + flex-basis:73px;height:73px;min-height:73px; + } + #app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-fx-rack{ + flex-basis:155px;height:155px;min-height:155px; + } +} +@media(max-width:1250px){ + #app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip]{ + flex-basis:136px;min-width:136px;max-width:136px; + } + #app #mixer[data-io-mode="CONSOLE"] > #masterLeft{ + flex-basis:148px;min-width:148px;max-width:148px; + } +} + + +/* Main dock geometry is measured by a ResizeObserver on the single mixer + viewport. Unlike position:sticky on the final flex child, this is always + visible at scrollLeft=0 and after any bank navigation. */ +#app #mixer[data-io-mode="CONSOLE"]{ + padding-right:155px; + scroll-padding-right:155px; +} +#app #mixer[data-io-mode="CONSOLE"] > #masterLeft{ + position:fixed!important; + right:auto!important; + left:var(--ar-main-dock-left,calc(100vw - 161px))!important; + top:var(--ar-main-dock-top,92px)!important; + height:var(--ar-main-dock-height,calc(100dvh - 122px))!important; + z-index:7; +} +@media(max-width:1250px){ + #app #mixer[data-io-mode="CONSOLE"]{padding-right:148px;scroll-padding-right:148px} +} + +/* Engineering bank parity: the extra accepted MAIN output line belongs to + unified CONSOLE only, so legacy FX/ROUTE/SENDS fader rows remain aligned. */ +#app #mixer:not([data-io-mode="CONSOLE"]) #masterLeft .arMainOutSummary{display:none!important} + +/* v5.2 operator-approved narrow console: UI-only banking, never a DSP switch. */ +#app .arV6Console[data-narrow="true"] .arV6Strip{ + flex:0 0 127px;width:127px;padding-left:4px;padding-right:4px; +} +#app .arV6Console[data-narrow="true"] .arV6Main{ + flex:0 0 143px;max-width:143px; +} +#app .arV6Console[data-narrow="true"] .arV6Strip.arV6Master{width:100%;flex:1 0 0} +#app .arV6Console[data-narrow="true"] .arV6Controls{ + grid-template-columns:minmax(0,1fr) 25px 25px;gap:2px; +} +#app .arV6Console[data-narrow="true"] .arV6Controls .arV6Button{width:25px} +@media(max-width:1100px){ + #app .arV6Tools{gap:2px} + #app .arV6Console .arV6Button,#app .arV6Console .arV6Select{padding-left:3px;padding-right:3px} +} + + +/* V5.2 PR#278 operator console: one shared row system for all strips and + section rail. Collapse changes only CSS, never DSP or accepted channel order. + FX/SEND inner scrolling cannot change neighboring fader alignment. */ +#app .arV6Console{ + --v6-head-h:37px;--v6-io-h:89px;--v6-fx-h:91px;--v6-send-h:55px; + --v6-pan-h:52px;--v6-status-h:26px; +} +#app .arV6Console[data-collapseio="true"]{--v6-io-h:24px} +#app .arV6Console[data-collapsefx="true"]{--v6-fx-h:23px} +#app .arV6Console[data-collapsesend="true"]{--v6-send-h:23px} +#app .arV6Console .arV6Strip{ + grid-template-rows:var(--v6-head-h) + calc(var(--v6-io-h) + var(--v6-fx-h) + var(--v6-send-h)) + var(--v6-pan-h) minmax(105px,1fr) var(--v6-status-h); +} +#app .arV6Console .arV6Upper{ + display:grid;grid-template-rows:var(--v6-io-h) var(--v6-fx-h) var(--v6-send-h); + padding:0;min-height:0;overflow:hidden; +} +#app .arV6Console .arV6Route{ + display:grid;grid-template-rows:repeat(3,minmax(0,1fr)); + gap:1px;min-height:0;overflow:hidden;padding:2px 0; + border-bottom:1px solid #405360; +} +#app .arV6Console .arV6Fx,#app .arV6Console .arV6Sends{ + overflow-y:auto;overflow-x:hidden;min-height:0;min-width:0; + padding:3px 0 2px;gap:2px;border-top:0;border-bottom:1px solid #3b4d59; +} +#app .arV6Console[data-collapseio="true"] .arV6Route>.arV6Field, +#app .arV6Console[data-collapsefx="true"] .arV6Fx>:not(.arV6SectionTitle), +#app .arV6Console[data-collapsesend="true"] .arV6Sends>:not(.arV6SectionTitle){display:none!important} +#app .arV6Console[data-collapseio="true"] .arV6Route::before{ + content:"IN / OUT";font:600 9px/18px "Segoe UI",sans-serif;color:#83aaba; +} +#app .arV6Console .arV6SectionRail{ + display:grid;flex:0 0 32px;width:32px;min-width:32px;min-height:0; + grid-template-rows:var(--v6-head-h) var(--v6-io-h) var(--v6-fx-h) + var(--v6-send-h) var(--v6-pan-h) minmax(105px,1fr) var(--v6-status-h); + background:#1c2931;border-right:1px solid #4a626f; +} +#app .arV6Console .arV6RailCell{ + min-width:0;min-height:0;display:flex;justify-content:center;align-items:flex-start; + padding:5px 1px 0;overflow:hidden; + border:0;border-bottom:1px solid #344a56;background:transparent; + color:#8fa9b6;font:600 9px/1.2 "Segoe UI",sans-serif; +} +#app .arV6Console .arV6RailToggle{ + width:100%;cursor:pointer;color:#add7e2;appearance:none; + border-radius:0;text-align:center; +} +#app .arV6Console .arV6RailToggle:hover, +#app .arV6Console .arV6RailToggle:focus-visible{ + background:#2c4552;outline:1px solid #6fc7df;outline-offset:-2px; +} +#app .arV6Console .arV6RailToggle.isCollapsed{color:#708b99;background:#26333c} +#app .arV6Console .arV6RailFader{align-items:center;padding:0;writing-mode:vertical-lr;letter-spacing:2px} +#app .arV6Console .arV6RailHeader{align-items:center;padding:0} +#app .arV6Console .arV6Strip[hidden]{display:none!important} +#app .arV6Console .arV6Filter{max-width:77px;width:77px} +@media(max-height:790px){ + #app .arV6Console{ + --v6-head-h:32px;--v6-io-h:76px;--v6-fx-h:74px;--v6-send-h:47px; + --v6-pan-h:45px;--v6-status-h:22px; + } + #app .arV6Console[data-collapseio="true"]{--v6-io-h:22px} + #app .arV6Console[data-collapsefx="true"]{--v6-fx-h:21px} + #app .arV6Console[data-collapsesend="true"]{--v6-send-h:21px} +} +@media(max-height:690px){ + #app .arV6Console{ + --v6-head-h:28px;--v6-io-h:67px;--v6-fx-h:57px;--v6-send-h:36px; + --v6-pan-h:40px;--v6-status-h:18px; + } + #app .arV6Console[data-collapseio="true"]{--v6-io-h:20px} + #app .arV6Console[data-collapsefx="true"]{--v6-fx-h:19px} + #app .arV6Console[data-collapsesend="true"]{--v6-send-h:19px} + #app .arV6Console .arV6RailCell{font-size:8px;padding-top:3px} +} + + +/* Native direct SEND gain in the same strip, not a separate FX workspace. + Two fixed rows per send preserve rail/fader geometry; inner scroll only. */ +#app .arV6Console .arV6Send{ + display:grid;grid-template-columns:minmax(0,1fr) 36px; + grid-template-rows:20px 18px;gap:0 3px; + flex:0 0 auto;min-height:38px;min-width:0;align-items:center; + border-bottom:1px solid #344c58; +} +#app .arV6Console .arV6SendName{ + grid-column:1;grid-row:1;min-width:0;overflow:hidden; + text-overflow:ellipsis;white-space:nowrap; +} +#app .arV6Console .arV6Send>.arV6Button{ + grid-column:2;grid-row:1;width:36px;min-width:0;max-width:36px; + height:18px;min-height:18px;padding:1px; +} +#app .arV6Console .arV6SendGain{ + display:flex;grid-column:1 / -1;grid-row:2; + align-items:center;gap:4px;min-width:0;min-height:18px; +} +#app .arV6Console .arV6SendLevel{ + min-width:0;flex:1 1 0;width:100%;height:13px;margin:0; + accent-color:#58b5ce;cursor:pointer; +} +#app .arV6Console .arV6SendLevel:disabled{opacity:.45;cursor:not-allowed} +#app .arV6Console .arV6SendDb{ + flex:0 0 39px;min-width:39px;color:#b6cbd5; + text-align:right;white-space:nowrap;font:9px/1 Consolas,monospace; +} +#app .arV6Console{--v6-fx-h:80px;--v6-send-h:82px} +@media(max-height:790px){ + #app .arV6Console{--v6-fx-h:70px;--v6-send-h:72px} +} +@media(max-height:690px){ + #app .arV6Console{--v6-fx-h:56px;--v6-send-h:55px} +} + + +/* User-approved PRD v5.2: native-only digital TRIM/CUE and lightweight + ChannelId-based multiselect. No RT animation or DSP graph duplication. */ +#app .arV6Console .arV6SelectionCount{ + flex:0 0 auto;white-space:nowrap;color:#9ebbc7;font:10px/1 Consolas,monospace; +} +#app .arV6Console .arV6StripHead{cursor:pointer} +#app .arV6Console .arV6Strip.isSelected{ + background:linear-gradient(90deg,#254454,#304958 14%,#304958 87%,#1a3441); + box-shadow:inset 0 0 0 1px #70b6d1; +} +#app .arV6Console .arV6Strip.isSelected .arV6StripHead{border-bottom-color:#79b9cb} +#app .arV6Console .arV6Controls{ + display:grid;grid-template-columns:minmax(0,1fr) repeat(3,26px); + grid-template-rows:minmax(0,1fr) 20px;gap:1px 3px; + padding:1px 0 2px;align-items:center; +} +#app .arV6Console .arV6Controls .arV6Pan{grid-row:1;grid-column:1} +#app .arV6Console .arV6Controls .arV6Button{ + min-height:24px;width:26px;padding:0;font-size:11px; +} +#app .arV6Console .arV6Trim{ + display:flex;grid-column:1/-1;grid-row:2;align-items:center; + gap:4px;min-width:0;height:19px;border-top:1px solid #324854; + color:#8cafc0;font:600 9px/1 "Segoe UI",sans-serif; +} +#app .arV6Console .arV6TrimLevel{ + min-width:0;flex:1 1 0;width:100%;margin:0;height:14px; + cursor:ew-resize;accent-color:#60b4ca; +} +#app .arV6Console .arV6TrimDb{ + min-width:28px;text-align:right;white-space:nowrap; + font:9px/1 Consolas,monospace;color:#bdd0d9; +} +#app .arV6Console .arV6TrimLevel:disabled{opacity:.45;cursor:not-allowed} +#app .arV6Console[data-narrow="true"] .arV6Controls{ + grid-template-columns:minmax(0,1fr) repeat(3,23px);gap:1px; +} +#app .arV6Console[data-narrow="true"] .arV6Controls .arV6Button{width:23px} +@media(max-height:690px){ + #app .arV6Console .arV6Controls{grid-template-rows:minmax(0,1fr) 17px;padding:0} + #app .arV6Console .arV6Controls .arV6Button{min-height:19px} + #app .arV6Console .arV6Trim{height:16px;font-size:8px;gap:2px} + #app .arV6Console .arV6TrimLevel{height:12px} +} + + +/* v5.2 one-Console DEVICE drawer: native hardware inventory only, no + fake setup wizard, no full-window modal and no fader DOM reflow. */ +#app .arV6Console{position:relative} +#app .arV6Console .arV6DevicePanel{ + position:absolute;z-index:20;top:52px;right:8px; + display:flex;flex-direction:column; + width:min(420px,calc(100% - 16px));max-height:min(72vh,530px); + overflow:hidden;background:#1a2a34;color:#d4e5eb; + border:1px solid #668693;border-radius:4px; + box-shadow:0 8px 25px #071019aa; +} +#app .arV6Console .arV6DevicePanel[hidden]{display:none!important} +#app .arV6Console .arV6DevicePanelHead{ + display:flex;justify-content:space-between;align-items:center; + gap:6px;min-height:35px;padding:5px 10px;background:#304651; + border-bottom:1px solid #456370; + font:600 10px/1.2 "Segoe UI",sans-serif; +} +#app .arV6Console .arV6DevicePanelHead .arV6Button{min-height:23px;min-width:26px;padding:2px} +#app .arV6Console .arV6DeviceRows{padding:5px 10px 10px;overflow-y:auto} +#app .arV6Console .arV6DeviceRow{ + display:grid;grid-template-columns:95px minmax(0,1fr);gap:8px; + padding:5px 0;border-bottom:1px solid #324954;font:10px/1.45 "Segoe UI",sans-serif; +} +#app .arV6Console .arV6DeviceRow span{color:#8fb5c4} +#app .arV6Console .arV6DeviceRow strong{font-weight:500;overflow-wrap:anywhere} +#app .arV6Console .arV6DeviceNote{margin:9px 0 2px;color:#c5ad86;font:10px/1.5 "Segoe UI",sans-serif} +@media(max-width:1100px){#app .arV6Console .arV6DevicePanel{top:45px}} + + +/* F8 native VST3 catalog: search-only until native ADD_INSERT capability + and a verified catalog are present. Floating inspector, zero fader reflow. */ +#app .arV6Console .arV6PluginPanel{ + position:absolute;z-index:21;top:52px;right:8px; + display:flex;flex-direction:column; + width:min(410px,calc(100% - 16px));max-height:min(72vh,540px); + overflow:hidden;background:#1a2a34;color:#d4e5eb; + border:1px solid #668693;border-radius:4px; + box-shadow:0 8px 25px #071019aa; +} +#app .arV6Console .arV6PluginPanel[hidden]{display:none!important} +#app .arV6Console .arV6PluginTarget{ + padding:7px 10px;color:#b4d2dc;font:10px/1.35 "Segoe UI",sans-serif; +} +#app .arV6Console .arV6PluginSearch{ + margin:0 10px 8px;min-height:30px;padding:6px 9px; + color:#e5eff4;background:#102633;border:1px solid #527a88; + border-radius:3px;font:11px "Segoe UI",sans-serif; +} +#app .arV6Console .arV6PluginResults{ + overflow:auto;display:flex;flex-direction:column; + min-height:65px;padding:0 9px 9px;gap:3px;scrollbar-width:thin; +} +#app .arV6Console .arV6PluginResult{ + text-align:left;min-height:28px;width:100%;padding:5px 8px; + background:#243d4a;color:#d6ebf0;border-color:#426879; +} +#app .arV6Console .arV6PluginResult:disabled{opacity:.46;cursor:not-allowed} +@media(max-width:1100px){#app .arV6Console .arV6PluginPanel{top:45px}} + + +/* PRD v5.2 operator milestone: one compact native multi-channel drawer, + separate relative LINK from serial GROUP BUS. No browser DSP or fake link. */ +#app .arV6Console .arV6SelectionCount{flex:0 0 auto;padding:3px 6px} +#app .arV6Console .arV6SelectionPanel{ + position:absolute;z-index:22;top:52px;right:8px; + width:min(350px,calc(100% - 16px));max-height:min(72vh,420px); + display:flex;flex-direction:column;gap:0;min-width:0; + background:#1a2a34;color:#d4e5eb;border:1px solid #668693; + border-radius:4px;box-shadow:0 8px 25px #071019aa; +} +#app .arV6Console .arV6SelectionPanel[hidden]{display:none!important} +#app .arV6Console .arV6SelectionSummary{ + padding:8px 10px;min-height:32px;max-height:78px;overflow-y:auto; + font:10px/1.5 "Segoe UI",sans-serif;color:#b9d1da; +} +#app .arV6Console .arV6SelectionActions{display:grid;gap:8px;padding:2px 10px 4px} +#app .arV6Console .arV6LinkActions{display:grid;grid-template-columns:1fr auto;gap:6px} +#app .arV6Console .arV6BusActions{display:grid;grid-template-columns:1fr auto;gap:6px} +#app .arV6Console .arV6GroupTarget{min-width:0;width:100%} +#app .arV6Console .arV6SelectionPanel .arV6DeviceNote{padding:0 10px 8px} +#app .arV6Console .arV6Rename{ + width:100%;min-height:23px;min-width:0;padding:2px 4px; + color:#eaf7f8;background:#16303d;border:1px solid #77b8c6; + font:500 12px/1.2 "Segoe UI",sans-serif; +} +@media(max-width:1100px){#app .arV6Console .arV6SelectionPanel{top:46px}} + + +/* PR #278 V5 contextual FX picker on existing old UI. Preserve all six + fixed-height native slots until engine/bridge support a variable rack; avoid + breaking the six-slot layout contract while keeping original BTN-180 art. */ + + +#app .workbench{position:relative} +#app .arV5QuickFx{ + position:absolute;z-index:46;top:80px;left:8px; + display:flex;flex-direction:column;width:min(316px,calc(100% - 16px)); + max-height:min(63vh,410px);background:#182b35;color:#dfedf2; + border:1px solid #628594;border-radius:4px;box-shadow:0 8px 23px #061018aa; +} +#app .arV5QuickFx[hidden]{display:none!important} +#app .arV5QuickHead{min-height:32px;display:flex;justify-content:space-between;align-items:center; + padding:5px 8px;border-bottom:1px solid #3e5964;font:500 11px/1.2 "Segoe UI",sans-serif} +#app .arV5QuickHead strong{font-weight:500;overflow:hidden;white-space:nowrap;text-overflow:ellipsis} +#app .arV5QuickHead button{background:transparent;border:0;color:#dceff4;font-size:18px;cursor:pointer} +#app .arV5QuickSearch{min-height:29px;margin:7px;padding:4px 7px; + background:#0d1c25;border:1px solid #506b7a;border-radius:2px;color:#e8f2f5} +#app .arV5QuickResults{display:flex;flex-direction:column;gap:2px;padding:2px 7px 8px; + overflow:auto;min-height:45px} +#app .arV5QuickResult{display:flex;justify-content:space-between;align-items:center;gap:6px; + min-height:28px;text-align:left;padding:5px 7px;color:#ddedf2;background:#25414d; + border:1px solid #3c5c69;border-radius:2px;cursor:pointer} +#app .arV5QuickResult:hover,#app .arV5QuickResult:focus-visible{background:#345967;border-color:#78afbe} +#app .arV5QuickResult span{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +#app .arV5QuickResult small{color:#aac4cd;white-space:nowrap} +#app .arV5QuickFoot{display:flex;justify-content:space-between;align-items:center;gap:5px; + padding:7px 8px;border-top:1px solid #3e5964;color:#9cb8c3;font-size:10px} +#app .arV5QuickFoot button{background:transparent;border:0;color:#88d0e6;cursor:pointer} + +/* V5 uses only the user's original ArSonMix material bitmaps: + 29x62 fader cap (aspect 36:77), ROSEGOLD MASTER, PAN-SLIDER 15:33. + Dark graphite well, never bright cyan above the fader cap. */ +#app .arV6Console .arV6Fader::-webkit-slider-thumb{ + background:transparent url("assets/faders/FADER-ARI-SILVER.png") center/29px 62px no-repeat; + width:29px;height:62px;border:0;border-radius:0;box-shadow:none; +} +#app .arV6Console .arV6Fader::-moz-range-thumb{ + background:transparent url("assets/faders/FADER-ARI-SILVER.png") center/29px 62px no-repeat; + width:29px;height:62px;border:0;border-radius:0;box-shadow:none; +} +#app .arV6Console #arV6Main .arV6Fader::-webkit-slider-thumb{ + background-image:url("assets/faders/FADER-ARI-ROSEGOLD.png"); +} +#app .arV6Console #arV6Main .arV6Fader::-moz-range-thumb{ + background-image:url("assets/faders/FADER-ARI-ROSEGOLD.png"); +} +#app .arV6Console .arV6PanRange::-webkit-slider-thumb{ + background:transparent url("assets/pan/PAN-SLIDER.png") center/15px 33px no-repeat; + width:15px;height:33px;border:0;border-radius:0;box-shadow:none; +} +#app .arV6Console .arV6PanRange::-moz-range-thumb{ + background:transparent url("assets/pan/PAN-SLIDER.png") center/15px 33px no-repeat; + width:15px;height:33px;border:0;border-radius:0;box-shadow:none; +} +#app .arV6Console .arV6Fader::-webkit-slider-runnable-track{ + background:linear-gradient(90deg,#020507,#142029 25%,#05090d 80%,#010406); + border-color:#050e14;box-shadow:inset 1px 0 #3c505c,inset -1px 0 #05090c; +} +/* Keep compact V5 popup separate from F8 floating Plugin Manager. */ +#app .arV6Console .arV6QuickPanel{ + display:flex;flex-direction:column;position:absolute;z-index:24; + width:min(310px,calc(100% - 14px));max-height:min(66vh,410px); + min-height:125px;overflow:hidden;background:#192b35;border:1px solid #678b96; + border-radius:4px;box-shadow:0 8px 23px #061018ab; +} +#app .arV6Console .arV6QuickPanel[hidden]{display:none!important} +#app .arV6Console .arV6QuickPanel .arV6PluginSearch{margin-top:7px} +#app .arV6Console .arV6QuickFoot{display:flex;align-items:center;justify-content:space-between; + gap:5px;border-top:1px solid #3e5964;padding:5px 8px;color:#a6bdc6;font-size:10px} +#app .arV6Console .arV6QuickFoot .arV6Button{ + min-height:23px;font-size:10px;color:#a9dce8} +#app .arV6Console .arV6CatalogFilters{display:grid;grid-template-columns:1fr 1fr; + gap:6px;padding:0 10px 8px} +#app .arV6Console .arV6CatalogRow{display:flex;align-items:center;gap:5px} +#app .arV6Console .arV6CatalogRow .arV6PluginResult{flex:1;min-width:0} +#app .arV6Console .arV6CatalogStar{flex:none;width:26px;min-width:26px; + min-height:26px;padding:0;font-size:16px;color:#e4ca8a} +@media(max-width:1100px){ + #app .arV6Console .arV6QuickPanel{max-height:62vh} + #app .arV6Console .arV6CatalogFilters{gap:3px} +} + + +/* PR#278 V6 theme authority ported to actual WebView M4. No native DSP changes. */ +#app{--am-metal-base:#0B161E;--am-metal-panel:#14232C;--am-metal-raised:#20313B; + --am-metal-edge:#334956;--am-metal-inset:#030A0F;--am-text-primary:#DAE9EF; + --am-text-muted:#94B1BD;--am-accent:#66CBDD;--am-crystal:#E7EFF0} +#app .toolbar{background:linear-gradient(#253741,#17252e)!important;border-bottom:1px solid var(--am-metal-edge)} +#app .toolbar-actions.arSegmentedToolbar .nav .btn-180, +#app .toolbar .spec-device,#app .arMixerChannelPager .btn-180{ + height:29px;min-height:29px;max-height:29px;display:inline-flex; + align-items:center;justify-content:center;line-height:1;text-align:center;box-sizing:border-box} +#app .arMixerChannelPager .btn-180{width:29px;min-width:29px;padding:0;--b180-ink:#1f1f1f} +#app .arMixerChannelPager svg{display:block;flex:none;width:24px;height:24px;fill:currentColor} +#app .left-rail{background:var(--am-metal-base)} +#app .left-rail :is(.arRailModeSection,.arRailUtilities){background:var(--am-metal-panel)} +#app .left-rail :is(.arRailHeading,.rail-section-title){background:var(--am-metal-raised);border-color:var(--am-metal-edge)} +#app #mixer[data-io-mode="CONSOLE"]{background:var(--am-metal-base)} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip]{ + background:linear-gradient(90deg,#0e1b23,var(--am-metal-panel) 8%,#172832 92%,#0e1b23); + border-right:1px solid var(--am-metal-edge);box-shadow:inset 1px 0 #aecbd012} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip].selected{ + background:linear-gradient(90deg,#172b35,var(--am-metal-raised) 9%,#1a303b 93%,#122630); + box-shadow:inset 2px 0 var(--am-accent)} +/* Both identity nameplates use the SAME stable --ch source (no second palette). */ +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > :is(.ch-id,.strip-name), +#app #mixer[data-io-mode="CONSOLE"] #masterLeft > :is(.master-ch-id,.master-strip-name){ + background:color-mix(in srgb,var(--ch) 43%,#101e27)!important; + color:#f0f7fa;border-top:2px solid var(--ch); + border-bottom:1px solid color-mix(in srgb,var(--ch) 49%,#0c1820);text-shadow:0 1px #02080a} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .ch-id{ + display:flex;align-items:center;gap:3px;padding:0 31px 0 5px; + font:500 10px/1.1 "Segoe UI",sans-serif} +#app #mixer[data-io-mode="CONSOLE"] .arChannelNumber{flex:0 0 30px;white-space:nowrap; + color:#e0edf1;font:600 9px/1 Consolas,monospace} +#app #mixer[data-io-mode="CONSOLE"] .arChannelTopIdentity{ + display:flex;align-items:center;gap:3px;flex:1;min-width:0;max-width:100%; + padding:3px 1px;margin:0;border:0;border-radius:2px;background:transparent; + font:500 10px/1.1 "Segoe UI",sans-serif;color:#f2f8fa;cursor:pointer;text-align:left} +#app #mixer[data-io-mode="CONSOLE"] .arChannelTopIdentity:focus-visible{ + outline:1px solid #d7f5f9;outline-offset:0} +#app #mixer[data-io-mode="CONSOLE"] .arChannelTopIcon{flex:none;font-size:13px;line-height:1} +#app #mixer[data-io-mode="CONSOLE"] .arChannelTopName{min-width:0;overflow:hidden; + white-space:nowrap;text-overflow:ellipsis} +#app #mixer[data-io-mode="CONSOLE"] .arFormatBadge{ + right:4px;top:6px;min-height:19px;height:19px; + background:var(--am-metal-inset);border-color:#638594;color:#e4f5f8} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .strip-name{ + display:flex;flex-direction:row;align-items:center;justify-content:center; + gap:5px;padding:3px 6px;overflow:hidden;font:500 10px/1.1 "Segoe UI",sans-serif} +#app #mixer[data-io-mode="CONSOLE"] .strip-name .strip-caption{ + min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +#app #mixer[data-io-mode="CONSOLE"] .strip-name .track-icon{flex:none;font-size:14px;line-height:1} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft > .master-ch-id{ + display:flex;justify-content:space-between;align-items:center;padding:0 8px; + color:#f9f0f3;font:500 11px/1 "Segoe UI",sans-serif} +#app #mixer[data-io-mode="CONSOLE"] .arMasterTopIdentity{ + display:inline-flex;align-items:center;gap:4px;font-size:10px} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .arChannelBank, +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .rack, +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-fx-rack, +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .arMainOutSummary, +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .strip-controls{ + background:var(--am-metal-panel);border-color:var(--am-metal-edge)} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank :is(.arBankSource,.arBankOutput,.arBankChannelFormat){ + background:var(--am-metal-inset);border:1px solid #425d6a; + color:var(--am-text-primary);box-shadow:inset 0 1px 2px #0006} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arSendBank{border-top-color:var(--am-metal-edge)} +#app #mixer[data-io-mode="CONSOLE"] .arChannelBank .arSendChip{ + background:var(--am-metal-raised);border-color:var(--am-metal-edge);color:var(--am-text-primary)} +#app #mixer[data-io-mode="CONSOLE"] .rack .insert, +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-insert{ + background:linear-gradient(#283b46,#192b35);border:1px solid #39515c;color:var(--am-text-primary)} +#app #mixer[data-io-mode="CONSOLE"] .rack .insert.empty{ + border:1px dashed #3c5967;color:#a3c8d2} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-controls-zone{ + background:var(--am-metal-panel);border-color:var(--am-metal-edge)} +#app #mixer[data-io-mode="CONSOLE"] .channel-actions{ + background:var(--am-metal-raised);border-color:var(--am-metal-edge)} +#app #mixer[data-io-mode="CONSOLE"] .db-display{ + background:var(--am-metal-panel);color:var(--am-accent)} +#app #mixer[data-io-mode="CONSOLE"] > #masterLeft{ + background:var(--am-metal-panel);border-left-color:#997888} +#app #mixer[data-io-mode="CONSOLE"] #masterLeft .arMainOutAction{ + background:var(--am-metal-inset);color:var(--am-text-primary);border-color:var(--am-metal-edge)} +/* Real fader PNG, RAIL3 well, meter geometry and seven-shadow BTN-180 preserved. */ + + +/* PR#278 visual correction G-V7: 10 source strips + MAIN at desktop widths. + Geometry is measured from the actual mixer viewport, not a separate mock + component. Narrow windows use adaptive banks; the fader travel remains owned + by existing native controls. */ +#app #mixer[data-io-mode="CONSOLE"]{ + --ar-visible-channels:10; + --ar-master-dock-width:128px; + padding-right:var(--ar-master-dock-width); + scroll-padding-right:var(--ar-master-dock-width); +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip]{ + flex:0 0 calc((100% - var(--ar-master-dock-width))/var(--ar-visible-channels)); + width:calc((100% - var(--ar-master-dock-width))/var(--ar-visible-channels)); + min-width:102px;max-width:none; +} +#app #mixer[data-io-mode="CONSOLE"] > #masterLeft{ + flex:0 0 128px;width:128px;min-width:128px;max-width:128px; + box-shadow:-2px 0 7px #02080c66; +} +/* No accidental 2-line CH number/name or wrap over FX on the real WebView. + 30px high, all three parts in a SINGLE bounded grid row. */ +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .ch-id{ + display:grid!important; + grid-template-columns:30px minmax(0,1fr) 22px!important; + grid-template-rows:minmax(0,1fr)!important; + gap:2px!important; + align-items:center!important;justify-content:normal!important; + padding:0 3px!important; + overflow:hidden!important; + white-space:nowrap!important; + line-height:1!important; +} +#app #mixer[data-io-mode="CONSOLE"] .ch-id .arChannelNumber{ + display:block!important;width:30px;min-width:0;max-width:30px; + white-space:nowrap!important; + overflow:hidden;text-overflow:clip; + font:600 9px/1 Consolas,monospace!important; +} +#app #mixer[data-io-mode="CONSOLE"] .ch-id .arChannelTopIdentity{ + display:flex!important;grid-column:2;grid-row:1; + align-items:center!important;justify-content:flex-start!important; + min-width:0!important;width:100%!important;height:28px!important; + max-width:100%;padding:0 1px!important;margin:0!important; + overflow:hidden!important;white-space:nowrap!important;flex-wrap:nowrap!important; + font:500 10px/1 "Segoe UI",sans-serif!important;text-align:left!important; +} +#app #mixer[data-io-mode="CONSOLE"] .ch-id .arChannelTopIcon{ + flex:none!important;white-space:nowrap!important;line-height:1!important; + font-size:12px!important; +} +#app #mixer[data-io-mode="CONSOLE"] .ch-id .arChannelTopName{ + display:block!important;flex:1 1 auto!important;min-width:0!important; + max-width:100%!important;overflow:hidden!important; + text-overflow:ellipsis!important;white-space:nowrap!important; + line-height:1.25!important; +} +#app #mixer[data-io-mode="CONSOLE"] .ch-id .arFormatBadge{ + position:static!important;grid-column:3;grid-row:1; + width:21px!important;min-width:21px!important;height:20px!important; + margin:0!important;padding:0!important; + font:500 9px/18px "Segoe UI",sans-serif!important; + text-align:center!important;white-space:nowrap!important; +} +#app #mixer[data-io-mode="CONSOLE"] > .strip[data-strip] > .strip-name{ + min-width:0!important;white-space:nowrap!important; + border-top-color:var(--ch); +} +/* PR278: exactly ONE Add FX affordance in each existing 6-slot rack. + All six native slot nodes remain mounted for bridge/ACK and VST state. */ +html:not(.native-engine) #app #mixer[data-io-mode="CONSOLE"] .rack .insert-slot:has(.insert.empty) ~ .insert-slot:has(.insert.empty){ + display:none!important; +} +html:not(.native-engine) #app #mixer[data-io-mode="CONSOLE"] #masterLeft .master-fx-slot:has(.master-insert.empty) ~ .master-fx-slot:has(.master-insert.empty){ + display:none!important; +} +@media(max-width:1339px){ + #app #mixer[data-io-mode="CONSOLE"]{--ar-visible-channels:8} +} +@media(max-width:1099px){ + #app #mixer[data-io-mode="CONSOLE"]{--ar-visible-channels:6} +} + + +/* Native WIRE-pot — byte-for-byte uploaded SVG silhouette, inline-masked so + portable standalone and installed WebView render identically offline. + Realtime meters never trigger CSS painting; mask is static and compositor-light. */ +#app .arV6Console .arV6WirePot{ + position:relative;display:inline-flex;align-items:center;justify-content:center; + flex:0 0 22px;width:22px;height:22px;min-width:22px;min-height:22px; + vertical-align:middle;background:none;border:0;box-shadow:none; + --v6-wire-fill:#4b535b;--v6-wire-deg:0deg; +} +#app .arV6Console .arV6WirePot::before{ + content:"";position:absolute;inset:1px;width:20px;height:20px; + background:var(--v6-wire-fill,#4b535b); + -webkit-mask-image:url("data:image/svg+xml,%3Csvg%20version%3D%221.2%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20800%22%20width%3D%22800%22%20height%3D%22800%22%3E%0A%09%3Cstyle%3E%0A%09%09.s0%20%7B%20fill%3A%20%23000000%20%7D%20%0A%09%3C%2Fstyle%3E%0A%09%3Cg%3E%0A%09%09%3Cg%3E%0A%09%09%09%3Cg%3E%0A%09%09%09%09%3Cpath%20class%3D%22s0%22%20d%3D%22m436.84%20436.84c-10.09%2010.09-23.34%2015.16-36.59%2015.16-13.25%200-26.49-5.07-36.59-15.16-20.23-20.24-20.23-52.94%200-73.18l253.11-253.11c-60.49-45.33-135.27-72.55-216.52-72.55-199.7%200-362.25%20162.5-362.25%20362.25%200%20199.75%20162.55%20362.25%20362.25%20362.25%20199.71%200%20362.25-162.5%20362.25-362.25%200-81.25-27.22-156.03-72.55-216.53z%22%2F%3E%0A%09%09%09%3C%2Fg%3E%0A%09%09%3C%2Fg%3E%0A%09%3C%2Fg%3E%0A%3C%2Fsvg%3E%0A"); + mask-image:url("data:image/svg+xml,%3Csvg%20version%3D%221.2%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20800%22%20width%3D%22800%22%20height%3D%22800%22%3E%0A%09%3Cstyle%3E%0A%09%09.s0%20%7B%20fill%3A%20%23000000%20%7D%20%0A%09%3C%2Fstyle%3E%0A%09%3Cg%3E%0A%09%09%3Cg%3E%0A%09%09%09%3Cg%3E%0A%09%09%09%09%3Cpath%20class%3D%22s0%22%20d%3D%22m436.84%20436.84c-10.09%2010.09-23.34%2015.16-36.59%2015.16-13.25%200-26.49-5.07-36.59-15.16-20.23-20.24-20.23-52.94%200-73.18l253.11-253.11c-60.49-45.33-135.27-72.55-216.52-72.55-199.7%200-362.25%20162.5-362.25%20362.25%200%20199.75%20162.55%20362.25%20362.25%20362.25%20199.71%200%20362.25-162.5%20362.25-362.25%200-81.25-27.22-156.03-72.55-216.53z%22%2F%3E%0A%09%09%09%3C%2Fg%3E%0A%09%09%3C%2Fg%3E%0A%09%3C%2Fg%3E%0A%3C%2Fsvg%3E%0A"); + -webkit-mask-repeat:no-repeat;mask-repeat:no-repeat; + -webkit-mask-position:center;mask-position:center; + -webkit-mask-size:contain;mask-size:contain; + transform:rotate(var(--v6-wire-deg,0deg)); + pointer-events:none; +} +#app .arV6Console .arV6WirePot.is-idle{opacity:1;pointer-events:none} +#app .arV6Console .arV6WirePot.is-connected:focus-within{outline:1px solid #70bed2;outline-offset:1px} +#app .arV6Console .arV6SendEmpty{ + grid-template-columns:minmax(0,1fr) 24px; + grid-template-rows:20px;min-height:21px; +} +#app .arV6Console .arV6SendEmpty .arV6SendName{color:#849ba6;font-size:9px} +#app .arV6Console .arV6SendEmpty .arV6WirePot{grid-column:2;grid-row:1} +#app .arV6Console .arV6SendGain{gap:8px;min-height:22px} +#app .arV6Console .arV6WirePot .arV6SendLevel{ + position:absolute;inset:0;width:100%;height:100%;margin:0; + opacity:0;cursor:ns-resize;touch-action:none;appearance:none; + -webkit-appearance:none; +} +#app .arV6Console .arV6WirePot .arV6SendLevel:disabled{cursor:not-allowed} +#app .arV6Console .arV6SendDb{flex:1 1 auto;min-width:43px;text-align:left} +@media(prefers-reduced-motion:reduce){ + #app .arV6Console .arV6WirePot::before{transition:none!important} +} + + +/* GUI FINAL -> ENGINE V8: 1 accepted identity, 1 channel width, 1 graphite + chassis. No new DSP, paint animation or browser-inferred LIVE controls. */ +#app #arV6Console{ + --v6-channel-w:150px; + --v6-status-h:34px; +} +#app .arV6Console .arV6Main, +#app .arV6Console[data-narrow="true"] .arV6Main{ + flex:0 0 var(--v6-channel-w);width:var(--v6-channel-w); + max-width:var(--v6-channel-w);min-width:var(--v6-channel-w); + border-left:0;box-shadow:-2px 0 0 #63808b; + background:var(--am-metal-panel); +} +#app .arV6Console .arV6Strip, +#app .arV6Console[data-narrow="true"] .arV6Strip{ + flex:0 0 var(--v6-channel-w);width:var(--v6-channel-w); + min-width:var(--v6-channel-w);max-width:var(--v6-channel-w); + background:var(--am-metal-panel); +} +#app .arV6Console .arV6Strip.arV6Master, +#app .arV6Console[data-narrow="true"] .arV6Strip.arV6Master{ + flex:0 0 var(--v6-channel-w);width:var(--v6-channel-w); + min-width:var(--v6-channel-w);max-width:var(--v6-channel-w); + background:var(--am-metal-panel); +} +#app .arV6Console .arV6Top{ + background:linear-gradient(180deg,var(--am-metal-raised),var(--am-metal-panel)); +} +#app .arV6Console .arV6StripHead{ + display:flex;flex-direction:row;align-items:center;gap:3px; + min-width:0;border-bottom:2px solid var(--ch,#5f9ab1); + background:color-mix(in srgb,var(--ch,#5f9ab1) 15%,var(--am-metal-panel)); +} +#app .arV6Console .arV6Role{flex:none;max-width:42%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:500 8px/1 "Segoe UI",sans-serif;letter-spacing:.15px} +#app .arV6Console .arV6IdentityIcon{flex:none;font-size:13px;line-height:1} +#app .arV6Console .arV6Name{flex:1;min-width:0;font-size:10px;font-weight:550} +#app .arV6Console .arV6StripStatus{ + display:flex;flex-direction:column;align-items:stretch;justify-content:center; + gap:1px;padding:2px 3px; + border-top:2px solid var(--ch,#5f9ab1); + background:color-mix(in srgb,var(--ch,#5f9ab1) 28%,var(--am-metal-panel)); + min-width:0; +} +#app .arV6Console .arV6FootIdentity{ + display:flex;gap:4px;align-items:center;min-width:0; + color:#ebf2f5;font:500 9px/1 "Segoe UI",sans-serif; +} +#app .arV6Console .arV6FootIcon{flex:none;font-size:11px;line-height:1} +#app .arV6Console .arV6FootName{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +#app .arV6Console .arV6PcmState{ + color:#b7c8ce;font:500 8px/1.05 "Segoe UI",sans-serif; + letter-spacing:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; +} +#app .arV6Console[data-demo="true"] .arV6PcmState{color:#e3bb82} diff --git a/web/mixer-layout.js b/web/mixer-layout.js index 9e1ac306b..b330783df 100644 --- a/web/mixer-layout.js +++ b/web/mixer-layout.js @@ -73,10 +73,10 @@ const mixer=document.getElementById('mixer'); if(mixer&&!document.getElementById('arMixChannelPager')){ const pager=document.createElement('div');pager.id='arMixChannelPager';pager.className='arMixerChannelPager'; - const prev=document.createElement('button');prev.type='button';prev.className='btn-180';prev.textContent='‹'; + const prev=document.createElement('button');prev.type='button';prev.className='btn-180';prev.innerHTML=''; prev.setAttribute('aria-label','Previous mixer channel bank'); const label=document.createElement('span');label.className='arMixerPagerLabel'; - const next=document.createElement('button');next.type='button';next.className='btn-180';next.textContent='›'; + const next=document.createElement('button');next.type='button';next.className='btn-180';next.innerHTML=''; next.setAttribute('aria-label','Next mixer channel bank'); pager.append(prev,label,next);nav.parentElement?.append(pager); const strips=()=>[...mixer.querySelectorAll('[data-strip]')]; @@ -103,6 +103,25 @@ if(typeof ResizeObserver==='function')new ResizeObserver(refresh).observe(mixer); refresh(); } + // MAIN lives in the original #mixer DOM (app.js still owns its native + // meter/FX/fader). In CONSOLE it is viewport-fixed, not a false sticky + // child at the end of a horizontally scrolling 10-strip flex track. + // Geometry is recomputed ONLY on resize, not on pointer/meter/scroll. + if(mixer){ + const syncMainDock=()=>{ + const rect=mixer.getBoundingClientRect(); + // Actual MASTER includes the original 2px rail edge and padding; + // do not assume its CSS flex-basis equals its rendered outer width. + const width=mixer.querySelector('#masterLeft')?.getBoundingClientRect().width|| + (window.innerWidth<=1250?148:155); + mixer.style.setProperty('--ar-main-dock-left',Math.round(rect.right-width)+'px'); + mixer.style.setProperty('--ar-main-dock-top',Math.round(rect.top)+'px'); + mixer.style.setProperty('--ar-main-dock-height',Math.round(rect.height)+'px'); + }; + if(typeof ResizeObserver==='function')new ResizeObserver(syncMainDock).observe(mixer); + window.addEventListener('resize',syncMainDock,{passive:true}); + syncMainDock(); + } // Studio-like channel selection and FX navigation are presentation-only. const channelList=rail.querySelector('#channelList'); channelList?.addEventListener('keydown',event=>{ @@ -142,3 +161,1542 @@ } document.documentElement.dataset.arMixerShell='rail-modes'; })(); + + +/* ARSONMIX V6 OPERATOR CONSOLE — native accepted projection only. + The legacy M4 console remains available until the native v6 publisher exists. + No WebAudio, DSP, routing solver, or fabricated ACK lives in this module. */ +(() => { + 'use strict'; + const mount=document.querySelector('#app .workbench'); + const backend=window.__JUCE__?.backend; + if(!mount||!document.getElementById('mixer')||document.getElementById('arV6Console'))return; + const native=!!(backend&&typeof backend.emitEvent==='function'&&typeof backend.addEventListener==='function'); + const h=(tag,cls,text)=>{ + const n=document.createElement(tag); + if(cls)n.className=cls; + if(text!==undefined)n.textContent=String(text); + return n; + }; + const button=(label,attrs={})=>{ + const n=h('button','arV6Button',label);n.type='button'; + for(const [key,value] of Object.entries(attrs))n.setAttribute(key,String(value)); + return n; + }; + const clamp=(n,a,b)=>Math.max(a,Math.min(b,n)); + function paintPan(slider,value){ + const n=clamp(Number(value)||0,-100,100),pos=(n+100)/2; + slider.style.setProperty('--v6-pan-start',Math.min(50,pos)+'%'); + slider.style.setProperty('--v6-pan-end',Math.max(50,pos)+'%'); + slider.setAttribute('aria-valuetext',n===0?'Center':n<0?'L '+Math.abs(n):'R '+n); + } + const clean=s=>String(s==null?'—':s); + const byId=new Map(); + // Selection is display state only, with immutable native ChannelId keys. + const selectedIds=new Set();let selectionAnchor=null; + const pending=new Map(); + const pendingTargets=new Set(); + const awaitingSnapshot=new Map(); + let snapshotSerial=0; + const operationCaps={ + SET_SOURCE:'SET_SOURCE',SET_PROCESSING_FORMAT:'SET_PROCESSING_FORMAT', + SET_PRIMARY_OUT:'SET_PRIMARY_OUT',ADD_INSERT:'ADD_INSERT', + PICK_INSERT_FILE:'PICK_INSERT_FILE',SET_INSERT_BYPASS:'SET_INSERT_BYPASS', + OPEN_INSERT_EDITOR:'OPEN_INSERT_EDITOR',MOVE_INSERT:'MOVE_INSERT', + ADD_SEND:'ADD_SEND',SET_SEND_TAP:'SET_SEND_TAP',SET_SEND_LEVEL:'SET_SEND_LEVEL', + SET_FADER:'SET_FADER',SET_PAN:'SET_PAN',SET_MUTE:'SET_MUTE', + SET_SOLO:'SET_SOLO',SET_TRIM:'SET_TRIM',SET_CUE:'SET_CUE', + SET_LINK_GROUP:'SET_LINK_GROUP',ROUTE_SELECTED_TO_GROUP:'ROUTE_SELECTED_TO_GROUP', + RENAME_CHANNEL:'RENAME_CHANNEL',CREATE_CHANNEL:'CREATE_CHANNEL' + }; + let accepted=null,acceptedNative=false,modeSend='',lastStructure='',requestSeq=0; + let lastControlProjection='',lastHeaderProjection=''; + // Stable indexed meters avoid re-querying every strip/LED on native PCM ticks. + const meterNodes=new Map(),statusNodes=new Map(); + const uiStats={structureRenders:0,controlRefreshes:0,telemetryFastFrames:0}; + let meterReadings=new Map(); + let draggingFx=null; + // Local pointer preview only. The accepted send stays native-owned until ACK. + let wirePotGesture=null; + const wirePotFill=id=>{ + const c=byId.get(id)?.color; + return typeof c==='string'&&/^#[0-9a-fA-F]{6}$/.test(c)?c:'#4b535b'; + }; + const wirePotAngle=db=>(-135+((clamp(db,-60,12)+60)/72)*270).toFixed(1)+'deg'; + function paintWirePot(pot,db){ + if(pot)pot.style.setProperty('--v6-wire-deg',wirePotAngle(db)); + } + function acceptedWireLevel(id,sendId){ + const channel=byId.get(id); + const send=channel?.sends?.find(s=>String(s.id)===sendId); + const db=send&&typeof send.levelDb==='number'?send.levelDb:NaN; + return Number.isFinite(db)?clamp(db,-60,12):null; + } + // Numeric decimal wire identifiers are required by integration/ConsoleNativeContractV6.h. + // Never downcast native 64-bit ChannelId, device epoch, or graph revision. + // Wire uint64 identities are canonical decimal STRINGS, not JS numbers. + // Reject overflow and noncanonical aliases before BigInt comparisons. + const decimal=v=>typeof v==='string'&&/^(0|[1-9][0-9]*)$/.test(v)&& + BigInt(v)<=18446744073709551615n?v:null; + const ge=(a,b)=>a!==null&&b!==null&&BigInt(a)>=BigInt(b); + // A reconnect must not replay the prior editor's request IDs. Retain a + // single session prefix for this WebView lifetime; each new WebView gets + // a cryptographically random prefix when secure randomness is available. + const instance=(()=>{ + const bytes=new Uint8Array(16); + try{ + window.crypto.getRandomValues(bytes); + return 'gui-'+Array.from(bytes,b=>b.toString(16).padStart(2,'0')).join(''); + }catch{ + return 'gui-'+Date.now().toString(36)+'-'+ + Math.random().toString(36).slice(2,14); + } + })(); + let feedback=''; + const root=h('section','arV6Console');root.id='arV6Console'; + root.setAttribute('aria-label','ArSonMix universal operator console'); + const top=h('div','arV6Top'); + const identification=h('div','arV6Identification'); + const kicker=h('span','arV6Kicker','ARSONMIX / UNIVERSAL LIVE CONSOLE'); + const deviceText=h('span','arV6Device','NO NATIVE CONSOLE SNAPSHOT'); + const modeBadge=h('span','arV6State','WAITING FOR NATIVE'); + identification.append(kicker,deviceText,modeBadge); + const tools=h('div','arV6Tools'); + const bankPrev=button('‹',{'aria-label':'Previous channel bank'}); + const bankLabel=h('span','arV6BankLabel','—'); + const bankNext=button('›',{'aria-label':'Next channel bank'}); + const sendMode=h('select','arV6Select arV6SendMode');sendMode.setAttribute('aria-label','Sends on faders target'); + const roleSelect=h('select','arV6Select arV6RoleSelect'); + roleSelect.setAttribute('aria-label','Native new channel type'); + for(const type of ['MONO','STEREO','GROUP','FX_RETURN','MONITOR']){ + const option=h('option','',type);option.value=type;roleSelect.append(option); + } + const add=button('+ CHANNEL',{'data-op':'CREATE_CHANNEL'}); + const deviceButton=button('DEVICE',{'aria-expanded':'false','aria-controls':'arV6DevicePanel', + 'aria-label':'Verified native audio device inventory'}); + const pluginsButton=button('VST3 F8',{'aria-expanded':'false', + 'aria-controls':'arV6PluginPanel','aria-label':'Native Plugin Manager F8'}); + const patch=button('PATCH',{'aria-label':'Open advanced patch'}); + const narrow=button('NARROW',{'aria-pressed':'false','aria-label':'Toggle narrow channel bank'}); + const roleFilter=h('select','arV6Select arV6Filter'); + roleFilter.setAttribute('aria-label','Filter visible mixer channels'); + const selectionCount=button('0 SEL',{'aria-label':'Selected channels and native group actions', + 'aria-controls':'arV6SelectionPanel','aria-expanded':'false'}); + selectionCount.classList.add('arV6SelectionCount'); + for(const [value,label] of [['ALL','ALL'],['INPUT','INPUT'],['GROUP','BUS'], + ['FX_RETURN','FX RTN'],['AUX','AUX'],['MONITOR','MON'],['SOLO','SOLO']]){ + const option=h('option','',label);option.value=value;roleFilter.append(option); + } + const back=button('V6 CONSOLE',{'aria-label':'Return to operator console'}); + back.id='arV6Return';back.hidden=true; + tools.append(bankPrev,bankLabel,bankNext,roleFilter,selectionCount, + sendMode,roleSelect,add,deviceButton,pluginsButton,narrow,patch); + top.append(identification,tools); + const message=h('div','arV6Message');message.setAttribute('role','status'); + const devicePanel=h('section','arV6DevicePanel'); + devicePanel.id='arV6DevicePanel';devicePanel.hidden=true; + devicePanel.setAttribute('aria-label','Read-only native audio device inventory'); + const deviceHead=h('div','arV6DevicePanelHead'); + const deviceClose=button('×',{'aria-label':'Close native device inventory'}); + deviceHead.append(h('span','','VERIFIED DEVICE · NATIVE READBACK'),deviceClose); + const deviceRows=h('div','arV6DeviceRows'); + devicePanel.append(deviceHead,deviceRows); + const pluginPanel=h('section','arV6PluginPanel'); + pluginPanel.id='arV6PluginPanel';pluginPanel.hidden=true; + pluginPanel.setAttribute('aria-label','Native scanned VST3 catalog'); + const pluginHead=h('div','arV6DevicePanelHead'); + const pluginClose=button('×',{'aria-label':'Close native Plugin Manager'}); + pluginHead.append(h('span','','NATIVE VST3 · PLUGIN MANAGER'),pluginClose); + const pluginTarget=h('div','arV6PluginTarget'); + const pluginSearch=h('input','arV6PluginSearch');pluginSearch.type='search'; + pluginSearch.placeholder='Search native scanned plugins...'; + pluginSearch.setAttribute('aria-label','Search native scanned VST3 catalog'); + const pluginResults=h('div','arV6PluginResults'); + const managerFilters=h('div','arV6CatalogFilters'); + const managerView=h('select','arV6Select'); + managerView.setAttribute('aria-label','Native plugin catalog filter'); + for(const [val,text] of [['ALL','All effects'],['FAVORITES','Favorites'],['RECENT','Recent']]){ + const opt=h('option','',text);opt.value=val;managerView.append(opt); + } + const managerCategory=h('select','arV6Select'); + managerCategory.setAttribute('aria-label','Native plugin category'); + managerFilters.append(managerView,managerCategory); + pluginPanel.append(pluginHead,pluginTarget,pluginSearch,managerFilters,pluginResults); + // Contextual V5 Add FX picker anchored to the exact strip, independent of F8. + const quickPanel=h('section','arV6QuickPanel'); + quickPanel.id='arV6QuickPanel';quickPanel.hidden=true; + quickPanel.setAttribute('role','dialog');quickPanel.setAttribute('aria-label','Quick native VST3 picker'); + const quickHead=h('div','arV6DevicePanelHead'); + const quickTitle=h('span','','QUICK ADD FX'); + const quickClose=button('×',{'aria-label':'Close quick native FX picker'}); + quickHead.append(quickTitle,quickClose); + const quickSearch=h('input','arV6PluginSearch');quickSearch.type='search'; + quickSearch.setAttribute('aria-label','Search quick native effects'); + quickSearch.placeholder='Search native VST3 effects…'; + const quickResults=h('div','arV6PluginResults'); + const quickManager=button('PLUGIN MANAGER · F8'); + quickManager.setAttribute('aria-label','Open full Plugin Manager from quick picker'); + const quickFoot=h('div','arV6QuickFoot'); + quickFoot.append(h('span','','Enter: load · Esc: close'),quickManager); + quickPanel.append(quickHead,quickSearch,quickResults,quickFoot); + // A small operator drawer differentiates relative fader links from actual + // serial Group-Bus summing. Both are SINGLE native graph transactions. + const selectionPanel=h('section','arV6SelectionPanel'); + selectionPanel.id='arV6SelectionPanel';selectionPanel.hidden=true; + selectionPanel.setAttribute('aria-label','Native multi-channel operator actions'); + const selectionHead=h('div','arV6DevicePanelHead'); + const selectionClose=button('×',{'aria-label':'Close selected channel actions'}); + selectionHead.append(h('span','','SELECTED · LIVE MIXING'),selectionClose); + const selectionSummary=h('div','arV6SelectionSummary'); + const selectionActions=h('div','arV6SelectionActions'); + const linkFaders=button('LINK FADERS',{'data-op':'SET_LINK_GROUP', + 'aria-label':'Link selected faders using native relative control group'}); + const unlinkFaders=button('UNLINK',{'data-op':'SET_LINK_GROUP', + 'aria-label':'Unlink selected faders using native relative control group'}); + const routeBus=h('select','arV6Select arV6GroupTarget'); + routeBus.setAttribute('aria-label','Select actual native summing Group Bus'); + const routeSelected=button('ROUTE TO GROUP BUS',{'data-op':'ROUTE_SELECTED_TO_GROUP', + 'aria-label':'Route selected channels to native summing Group Bus'}); + const linkRow=h('div','arV6LinkActions');linkRow.append(linkFaders,unlinkFaders); + const busRow=h('div','arV6BusActions');busRow.append(routeBus,routeSelected); + selectionActions.append(linkRow,busRow); + const selectionNote=h('p','arV6DeviceNote', + 'LINK FADERS moves controls relatively. GROUP BUS sums audio serially. These are different native operations; UI never mixes or reroutes PCM.'); + selectionPanel.append(selectionHead,selectionSummary,selectionActions,selectionNote); + const body=h('div','arV6Body'); + const sectionRail=h('aside','arV6SectionRail'); + sectionRail.setAttribute('aria-label','Synchronized mixer section collapse'); + sectionRail.append(h('span','arV6RailCell arV6RailHeader','▦')); + for(const [section,text,label] of [ + ['io','I/O','Collapse or expand native input and output rows'], + ['fx','FX','Collapse or expand VST3 insert section'], + ['send','SND','Collapse or expand send section']]){ + const control=button(text,{'data-section':section,'aria-expanded':'true','aria-label':label}); + control.classList.add('arV6RailCell','arV6RailToggle'); + sectionRail.append(control); + } + sectionRail.append(h('span','arV6RailCell arV6RailPan','PAN')); + sectionRail.append(h('span','arV6RailCell arV6RailFader','dB')); + sectionRail.append(h('span','arV6RailCell arV6RailStatus','•')); + const lanes=h('div','arV6Lanes');lanes.id='arV6Lanes';lanes.setAttribute('aria-label','Channel banks'); + const main=h('div','arV6Main');main.id='arV6Main';main.setAttribute('aria-label','Pinned main output'); + body.append(sectionRail,lanes,main); + root.append(top,message,devicePanel,pluginPanel,selectionPanel,quickPanel,body); + mount.append(root); + sectionRail.addEventListener('click',event=>{ + const control=event.target.closest('[data-section]'); + if(!control)return; + const key='collapse'+control.dataset.section; + const collapsed=root.dataset[key]!=='true'; + root.dataset[key]=String(collapsed); + control.setAttribute('aria-expanded',String(!collapsed)); + control.classList.toggle('isCollapsed',collapsed); + // Shared CSS variables resize every strip and rail atomically. + // No channel topology change and no fader/meter DOM remount. + refreshBanks(); + }); + roleFilter.addEventListener('change',()=>applyPresentation()); + selectionCount.addEventListener('click',()=>{ + selectionPanel.hidden=!selectionPanel.hidden; + selectionCount.setAttribute('aria-expanded',String(!selectionPanel.hidden)); + if(!selectionPanel.hidden)refreshSelectionActions(); + }); + selectionClose.addEventListener('click',()=>{ + selectionPanel.hidden=true;selectionCount.setAttribute('aria-expanded','false'); + }); + function selectedNativeIds(){ + return [...selectedIds].filter(id=>byId.has(id)&&byId.get(id).role!=='MAIN'); + } + function refreshSelectionActions(){ + const count=selectedIds.size; + selectionCount.textContent=count+' SEL'; + selectionCount.dataset.selectionCount=String(count); + selectionCount.setAttribute('aria-label', + count+' selected channels; native link and group controls'); + // Hardware keys convert button text into SVG. Repaint this dynamic + // count synchronously instead of waiting for a MutationObserver turn; + // no DSP/control operation is dispatched by this UI-only decoration. + window.ArSonMixHardwareKeys?.upgrade?.(selectionCount); + if(selectionPanel.hidden)return; + const ids=selectedNativeIds(),channels=ids.map(id=>byId.get(id)); + const names=channels.map(c=>c.name).join(' · '); + selectionSummary.textContent=names||'Select channel headers using Ctrl / Shift'; + const ready=ids.length>=2&&ids.length<=64&&!pendingTargets.has('@selection')&& + ids.every(id=>can('SET_LINK_GROUP',id)); + linkFaders.disabled=!ready||!can('SET_LINK_GROUP',null); + const current=channels[0]?.linkGroupId; + unlinkFaders.disabled=!ready||typeof current!=='string'||!current|| + !channels.every(c=>c.linkGroupId===current); + const buses=(accepted?.graph?.channels||[]).filter(ch=> + ch.role==='GROUP'&&!selectedIds.has(ch.id)&& + (accepted.graph.destinations||[]).some(dst=>dst.id===ch.id&& + dst.acceptsPrimary!==false)); + const signature=buses.map(ch=>ch.id+'|'+ch.name).join(','); + if(routeBus.dataset.signature!==signature){ + const value=routeBus.value; + routeBus.replaceChildren(); + const prompt=h('option','','SELECT NATIVE BUS');prompt.value='';routeBus.append(prompt); + for(const bus of buses){ + const option=h('option','',bus.name);option.value=bus.id;routeBus.append(option); + } + routeBus.value=buses.some(ch=>ch.id===value)?value:''; + routeBus.dataset.signature=signature; + } + const canRoute=ids.length>0&&ids.length<=64&& + (accepted?.graph?.capabilities?.groups===true)&& + channels.every(c=>['INPUT','AUX','FX_RETURN'].includes(c.role)&& + can('ROUTE_SELECTED_TO_GROUP',c.id))&& + can('ROUTE_SELECTED_TO_GROUP',null); + routeBus.disabled=!canRoute||!buses.length; + routeSelected.disabled=!canRoute||!buses.some(ch=>ch.id===routeBus.value); + } + routeBus.addEventListener('change',refreshSelectionActions); + const sendSelectionAction=linked=>{ + const ids=selectedNativeIds(); + if(ids.length<2||ids.length>64||linkFaders.disabled&&linked|| + unlinkFaders.disabled&&!linked)return; + sendIntent('SET_LINK_GROUP',null,{channelIds:ids,linked},ids); + }; + linkFaders.addEventListener('click',()=>sendSelectionAction(true)); + unlinkFaders.addEventListener('click',()=>sendSelectionAction(false)); + routeSelected.addEventListener('click',()=>{ + const ids=selectedNativeIds(),destinationId=routeBus.value; + if(routeSelected.disabled||!ids.length||ids.length>64|| + !byId.has(destinationId)||byId.get(destinationId).role!=='GROUP')return; + sendIntent('ROUTE_SELECTED_TO_GROUP',null, + {channelIds:ids,destinationId},ids); + }); + deviceButton.addEventListener('click',()=>{ + devicePanel.hidden=!devicePanel.hidden; + deviceButton.setAttribute('aria-expanded',String(!devicePanel.hidden)); + if(!devicePanel.hidden)refreshDevicePanel(); + }); + deviceClose.addEventListener('click',()=>{ + devicePanel.hidden=true;deviceButton.setAttribute('aria-expanded','false'); + }); + function closePluginManager(){ + pluginPanel.hidden=true;pluginsButton.setAttribute('aria-expanded','false'); + } + // UI-only preferences store stable native catalog IDs, never plugin state. + const pluginFavorites=new Set(),pluginRecent=[]; + try{ + const p=JSON.parse(localStorage.getItem('armix.v6.fx-ux.v5')||'{}'); + if(Array.isArray(p.favorites))for(const id of p.favorites.slice(0,300)) + if(typeof id==='string')pluginFavorites.add(id); + if(Array.isArray(p.recent))for(const id of p.recent.slice(0,20)) + if(typeof id==='string')pluginRecent.push(id); + }catch{} + function saveFxPrefs(){ + try{localStorage.setItem('armix.v6.fx-ux.v5',JSON.stringify({ + favorites:[...pluginFavorites].slice(0,300),recent:pluginRecent.slice(0,20)}));}catch{} + } + let quickTarget=null,quickAnchor=null; + const nativeCatalog=()=>acceptedNative&&Array.isArray(accepted?.catalog?.plugins)? + accepted.catalog.plugins.filter(p=>p&&typeof p.id==='string'&&p.id&& + typeof p.name==='string'&&p.name):[]; + function closeQuickFx(focus=false){ + quickPanel.hidden=true; + if(focus&&quickAnchor?.isConnected)quickAnchor.focus(); + quickAnchor=null; + } + function commitNativeFx(pluginId,id){ + if(!nativeCatalog().some(p=>p.id===pluginId)||!can('ADD_INSERT',id))return false; + if(!sendIntent('ADD_INSERT',id,{pluginId}))return false; + const n=pluginRecent.indexOf(pluginId);if(n!==-1)pluginRecent.splice(n,1); + pluginRecent.unshift(pluginId);if(pluginRecent.length>20)pluginRecent.length=20; + saveFxPrefs();return true; + } + function refreshQuickFx(){ + if(quickPanel.hidden)return; + quickResults.replaceChildren(); + const target=byId.get(quickTarget); + quickTitle.textContent=(target?.name||'CHANNEL')+' · ADD FX · NATIVE'; + const q=quickSearch.value.trim().toLocaleLowerCase(); + const results=nativeCatalog().filter(p=> + (p.name+' '+(p.vendor||'')+' '+(p.category||'')).toLocaleLowerCase().includes(q)) + .sort((a,b)=>Number(pluginFavorites.has(b.id))-Number(pluginFavorites.has(a.id))|| + a.name.localeCompare(b.name)); + if(!results.length)quickResults.append(h('p','arV6DeviceNote', + 'No verified VST3 catalog. Use Plugin Manager F8 after native scan.')); + for(const fx of results.slice(0,64)){ + const b=button((pluginFavorites.has(fx.id)?'★ ':'')+fx.name+' · '+(fx.category||'Effect'), + {'data-quick-fx':fx.id}); + b.classList.add('arV6PluginResult');b.disabled=!can('ADD_INSERT',quickTarget); + quickResults.append(b); + } + } + function openQuickFx(id,anchor){ + if(!byId.has(id))return; + quickTarget=id;quickAnchor=anchor||null; + closePluginManager(); + const area=root.getBoundingClientRect(),r=anchor?.getBoundingClientRect(); + if(r){ + quickPanel.style.left=Math.max(7,Math.min(r.left-area.left,area.width-320))+'px'; + quickPanel.style.top=Math.max(44,Math.min(r.bottom-area.top+3,area.height-340))+'px'; + } + quickPanel.hidden=false;quickSearch.value='';refreshQuickFx();quickSearch.focus(); + } + quickClose.addEventListener('click',()=>closeQuickFx(true)); + quickSearch.addEventListener('input',refreshQuickFx); + quickSearch.addEventListener('keydown',event=>{ + if(event.key==='Enter'){ + const first=quickResults.querySelector('button[data-quick-fx]:not([disabled])'); + if(first){event.preventDefault();first.click();} + } + }); + quickResults.addEventListener('click',event=>{ + const b=event.target.closest('button[data-quick-fx]'); + if(b&&!b.disabled&&commitNativeFx(b.dataset.quickFx,quickTarget))closeQuickFx(); + }); + quickManager.addEventListener('click',()=>{const id=quickTarget;closeQuickFx();openPluginManager(id)}); + managerView.addEventListener('change',refreshPluginCatalog); + managerCategory.addEventListener('change',refreshPluginCatalog); + function openPluginManager(id){ + if(id&&byId.has(id)&&byId.get(id).role!=='MAIN'){ + selectedIds.clear();selectedIds.add(id);selectionAnchor=id; + updateSelection(); + } + devicePanel.hidden=true;deviceButton.setAttribute('aria-expanded','false'); + closeQuickFx(); + pluginPanel.hidden=false;pluginsButton.setAttribute('aria-expanded','true'); + refreshPluginCatalog();pluginSearch.focus(); + } + pluginsButton.addEventListener('click',()=>{ + if(pluginPanel.hidden)openPluginManager(); + else closePluginManager(); + }); + pluginClose.addEventListener('click',closePluginManager); + pluginSearch.addEventListener('input',refreshPluginCatalog); + pluginResults.addEventListener('click',event=>{ + const fav=event.target.closest('button[data-fx-fav]'); + if(fav){ + const id=fav.dataset.fxFav; + if(!nativeCatalog().some(p=>p.id===id))return; + if(pluginFavorites.has(id))pluginFavorites.delete(id);else pluginFavorites.add(id); + saveFxPrefs();refreshPluginCatalog();refreshQuickFx();return; + } + const node=event.target.closest('button[data-plugin-id]'); + if(!node||node.disabled||selectedIds.size!==1)return; + if(commitNativeFx(node.dataset.pluginId,[...selectedIds][0]))closePluginManager(); + }); + document.addEventListener('keydown',event=>{ + if(!document.documentElement.classList.contains('ar-v6-active'))return; + if(event.key==='Escape'&&!quickPanel.hidden){ + event.preventDefault();closeQuickFx(true); + }else if(event.key==='Escape'&&!selectionPanel.hidden){ + event.preventDefault();selectionPanel.hidden=true; + selectionCount.setAttribute('aria-expanded','false'); + }else if(event.key==='Escape'&&!pluginPanel.hidden){ + event.preventDefault();closePluginManager(); + }else if(event.key==='F8'&&!event.repeat){ + event.preventDefault();openPluginManager(); + } + }); + narrow.addEventListener('click',()=>{ + const compact=root.dataset.narrow!=='true'; + root.dataset.narrow=String(compact); + narrow.setAttribute('aria-pressed',String(compact)); + narrow.textContent=compact?'WIDE':'NARROW'; + refreshBanks(); // Resize only; never create a native channel or remount faders. + }); + document.querySelector('.toolbar-actions')?.append(back); + const setVisible=v=>{ + document.documentElement.classList.toggle('ar-v6-active',!!v); + back.hidden=!!v; + }; + patch.addEventListener('click',()=>{ + setVisible(false); + document.querySelector('[data-view="SIGNAL FLOW"]')?.click(); + }); + back.addEventListener('click',()=>{ + document.querySelector('[data-view="MIX"]')?.click();setVisible(true); + }); + function refreshDevicePanel(){ + if(devicePanel.hidden)return; + deviceRows.replaceChildren(); + const d=acceptedNative?accepted?.device:null; + if(!d){deviceRows.append(h('p','','No verified native device published.'));return;} + const addRow=(label,value)=>{ + const row=h('div','arV6DeviceRow'); + row.append(h('span','',label),h('strong','',value));deviceRows.append(row); + }; + addRow('BACKEND',d.backend||'—'); + addRow('INPUT DEVICE',d.captureDevice||'NONE'); + addRow('OUTPUT DEVICE',d.playbackDevice||'NONE'); + addRow('CLOCK',Number.isFinite(d.sampleRate)?d.sampleRate+' Hz / '+ + d.bufferFrames+' frames':'UNVERIFIED'); + addRow('OUTPUT ARM',d.outputArmed?'ARMED · acoustics unverified':'DISARMED'); + for(const [label,ports,mask] of [ + ['INPUT PINS',d.inputEndpoints,d.enabledInputs], + ['OUTPUT PINS',d.outputEndpoints,d.enabledOutputs]]){ + const verified=ports.filter(p=>p.active===true&&mask.includes(p.port)); + addRow(label,verified.length?verified.map(p=>p.label+' (port '+p.port+ + ', callback '+p.callback+')').join(', '):'NO VERIFIED ACTIVE PIN'); + } + deviceRows.append(h('p','arV6DeviceNote', + 'Read-only: device changes require a genuine native SET_DEVICE transaction; no guessed hardware pin or automatic audio reroute.')); + } + function refreshPluginCatalog(){ + if(pluginPanel.hidden)return; + pluginResults.replaceChildren(); + const ids=[...selectedIds].filter(id=>byId.has(id)); + const id=ids.length===1?ids[0]:null; + pluginTarget.textContent=id? + 'TARGET · '+byId.get(id).name+' · '+(can('ADD_INSERT',id)? + 'NATIVE LOAD AVAILABLE':'NATIVE LOAD NOT AVAILABLE'): + 'Select exactly ONE channel header to load a VST3'; + const catalog=nativeCatalog(); + const categories=[...new Set(catalog.map(p=>p.category||'Effect'))].sort(); + const previous=managerCategory.value; + managerCategory.replaceChildren(); + const any=h('option','','All categories');any.value='ALL';managerCategory.append(any); + for(const category of categories){ + const opt=h('option','',category);opt.value=category;managerCategory.append(opt); + } + managerCategory.value=categories.includes(previous)?previous:'ALL'; + const q=pluginSearch.value.trim().toLocaleLowerCase(),mode=managerView.value; + const results=catalog.filter(p=> + (p.name+' '+(p.vendor||'')+' '+(p.category||'')).toLocaleLowerCase().includes(q)&& + (managerCategory.value==='ALL'||(p.category||'Effect')===managerCategory.value)&& + (mode!=='FAVORITES'||pluginFavorites.has(p.id))&& + (mode!=='RECENT'||pluginRecent.includes(p.id))) + .sort((a,b)=>mode==='RECENT'? + pluginRecent.indexOf(a.id)-pluginRecent.indexOf(b.id):a.name.localeCompare(b.name)); + if(!results.length)pluginResults.append(h('p','arV6DeviceNote', + catalog.length?'No native plugins match the filter': + 'Native catalog not published · no simulated plugins available.')); + for(const p of results.slice(0,100)){ + const row=h('div','arV6CatalogRow'); + const star=button(pluginFavorites.has(p.id)?'★':'☆', + {'data-fx-fav':p.id,'aria-label':'Toggle favorite '+p.name}); + star.classList.add('arV6CatalogStar'); + const add=button(p.name+' · '+(p.vendor||'VST3'),{'data-plugin-id':p.id}); + add.classList.add('arV6PluginResult');add.disabled=!id||!can('ADD_INSERT',id); + row.append(star,add);pluginResults.append(row); + } + } + function supported(op){ + const caps=accepted?.graph?.capabilities||{}; + // Absence of explicit native advertised operation support means disabled. + return acceptedNative && accepted?.productionCallbackLive===true && + Array.isArray(caps.supportedOps) && caps.supportedOps.includes(operationCaps[op]); + } + function can(op,id){ + if(!supported(op))return false; + if(op==='CREATE_CHANNEL')return !!accepted.graph.capabilities.dynamicChannels && !pendingTargets.has('@roster'); + if(op==='ADD_INSERT'&&!accepted?.catalog?.plugins?.length)return false; + if(!id)return !pendingTargets.has('@selection'); + const ch=byId.get(id); + return !!ch && !pendingTargets.has(id) && + (!Array.isArray(ch.allowedOps)||ch.allowedOps.includes(op)); + } + function showFeedback(text){ + feedback=clean(text);message.textContent=feedback; + message.hidden=!feedback; + } + function requestSnapshot(){ + if(native)backend.emitEvent('arMixConsoleSubscribe',{protocol:'v6',requester:instance}); + } + function sendIntent(op,id,payload,affectedIds=[]){ + if(!can(op,id)||affectedIds.length>64|| + affectedIds.some(channelId=>!can(op,channelId))){ + showFeedback('UNAVAILABLE · Native capability, selection lock or channel authorization missing'); + return false; + } + const requestId=instance+':'+String(++requestSeq); + const command={requestId,deviceEpoch:accepted.device.epoch, + baseGraphRevision:accepted.graph.revision, + baseRosterRevision:accepted.graph.rosterRevision, + operation:op,targetChannelId:id||null,payload:payload||{}}; + const targets=id?[id]:affectedIds.length?['@selection',...affectedIds]: + op==='CREATE_CHANNEL'?['@roster']:[]; + pending.set(requestId,{op,id,targets,baseRevision:command.baseGraphRevision, + baseRosterRevision:command.baseRosterRevision,epoch:command.deviceEpoch,snapshotSerial}); + for(const target of targets)pendingTargets.add(target); + showFeedback('PENDING · '+op+' · awaiting native ACK'); + refreshDisabled(); + backend.emitEvent('arMixConsoleIntent',command); + return true; + } + function receiveAck(data){ + const a=data?.ack||data; + if(!a||typeof a.requestId!=='string')return; + const task=pending.get(a.requestId);if(!task)return; + const epoch=decimal(a.deviceEpoch),rev=decimal(a.graphRevision),roster=decimal(a.rosterRevision); + if(!['ACCEPTED','REJECTED','REQUIRES_DEVICE_CHANGE'].includes(a.status)|| + epoch===null||rev===null||roster===null||epoch!==task.epoch|| + typeof a.errorCode!=='string'){ + showFeedback('INVALID NATIVE ACK · accepted route unchanged');return; + } + pending.delete(a.requestId); + const unlock=()=>{for(const target of task.targets||[])pendingTargets.delete(target)}; + if(a.status==='ACCEPTED'){ + if(BigInt(rev)wait.snapshotSerial&& + accepted?.device?.epoch===wait.epoch&& + accepted?.graph?.revision===wait.requiredRevision&& + accepted?.graph?.rosterRevision===wait.requiredRoster; + } + function validSnapshot(s){ + // Mirror the required v8 producer wire: never infer physical masks, + // capabilities, PCM or accepted ChannelIds from browser/M4 fallback. + if(!s||s.schemaVersion!==6||typeof s.productionCallbackLive!=='boolean'|| + !s.device||!s.graph||!s.telemetry)return false; + const d=s.device,g=s.graph,c=g.capabilities,t=s.telemetry; + if(decimal(d.epoch)===null||decimal(g.revision)===null|| + decimal(g.rosterRevision)===null||typeof d.backend!=='string'|| + typeof d.captureDevice!=='string'||typeof d.playbackDevice!=='string'|| + typeof d.outputArmed!=='boolean'||!Array.isArray(d.inputEndpoints)|| + !Array.isArray(d.outputEndpoints)||!Array.isArray(d.enabledInputs)|| + !Array.isArray(d.enabledOutputs)||!Array.isArray(g.channels)|| + !Array.isArray(g.destinations)||!c||!Array.isArray(c.supportedOps)) + return false; + const pins=a=>a.every(v=>Number.isSafeInteger(v)&&v>=0&&v<=255)&& + new Set(a).size===a.length; + if(!pins(d.enabledInputs)||!pins(d.enabledOutputs))return false; + for(const [type,endpoints,mask] of [['in',d.inputEndpoints,d.enabledInputs], + ['out',d.outputEndpoints,d.enabledOutputs]]){ + const ids=new Set(),cb=new Set(); + for(const e of endpoints){ + if(!e||!mask.includes(e.port)||e.id!==type+':'+e.port|| + !Number.isSafeInteger(e.callback)||e.callback<0|| + typeof e.label!=='string'||!e.label||typeof e.active!=='boolean'|| + ids.has(e.id)||cb.has(e.callback))return false; + ids.add(e.id);cb.add(e.callback); + } + } + for(const key of ['callbackOwnsChannelIds','fullVendorFxMigration','showAndOutputParity', + 'physicalCaptureMapped','dynamicChannels','groups','fxReturns','monitor','sendsOnFaders']) + if(typeof c[key]!=='boolean')return false; + if(c.supportedOps.some(op=>typeof op!=='string'||!/^[A-Z_]+$/.test(op))|| + new Set(c.supportedOps).size!==c.supportedOps.length)return false; + if(s.productionCallbackLive){ + if(d.epoch==='0'||!c.callbackOwnsChannelIds||!c.fullVendorFxMigration|| + !c.showAndOutputParity||!c.physicalCaptureMapped)return false; + }else if(g.channels.length||c.supportedOps.length)return false; + const ids=new Set(),roles=['INPUT','GROUP','FX_RETURN','MONITOR','MAIN','AUX']; + for(const ch of g.channels){ + if(!ch||decimal(ch.id)===null||ch.id==='0'||ids.has(ch.id)|| + !roles.includes(ch.role)||!['MONO','STEREO'].includes(ch.processingFormat)|| + typeof ch.name!=='string'||!Array.isArray(ch.inserts)||!Array.isArray(ch.sends))return false; + ids.add(ch.id); + } + for(const ch of g.channels){ + if(ch.primaryOutId!==undefined&&ch.primaryOutId!==null){ + const to=ch.primaryOutId; + const physical=d.outputEndpoints.some(p=>p.id===to&&p.active===true&& + d.enabledOutputs.includes(p.port)); + if(to===ch.id||!ids.has(to)&&!(physical&&['MAIN','MONITOR'].includes(ch.role))) + return false; + } + if(ch.source){ + const x=ch.source; + if(ch.role!=='INPUT'||typeof x.portId!=='string'|| + !Array.isArray(x.physicalPins)||!pins(x.physicalPins)|| + ![1,2].includes(x.physicalPins.length)|| + !x.physicalPins.every(p=>d.enabledInputs.includes(p)&& + d.inputEndpoints.some(e=>e.port===p&&e.active))|| + !d.inputEndpoints.some(p=>p.id===x.portId&&p.active&& + x.physicalPins.includes(p.port)))return false; + } + for(const send of ch.sends) + if(!ids.has(send.targetId)||send.targetId===ch.id|| + !['PRE','POST'].includes(send.tap))return false; + if(ch.role==='GROUP'&&!c.groups||ch.role==='FX_RETURN'&&!c.fxReturns|| + ch.role==='MONITOR'&&!c.monitor)return false; + } + if(s.productionCallbackLive&&g.channels.filter(ch=>ch.role==='MAIN').length!==1)return false; + // Reject source/primary bus cycles before allowing the operator to act. + const graphIds=new Map(g.channels.map(ch=>[ch.id,ch])); + for(const ch of g.channels){ + let current=ch,visited=new Set(); + while(current?.primaryOutId){ + if(visited.has(current.id))return false; + visited.add(current.id); + current=graphIds.get(current.primaryOutId); + } + } + if(g.destinations.some(dst=>!dst||!ids.has(dst.id)))return false; + if(typeof t.rawCapturePresent!=='boolean'||typeof t.mainPcmPresent!=='boolean'|| + typeof t.monitorPcmPresent!=='boolean'||typeof t.rawCapturePeak!=='number'|| + !Number.isFinite(t.rawCapturePeak)||t.rawCapturePeak<0)return false; + // Actual native meter fields are optional until the installed callback + // publishes them. When present, reject forged IDs/invalid PCM numbers. + // Keep peaks linear (values >1 indicate genuine clipping, not an error). + const raw=t.channelMeterRmsPeak; + if(raw!==undefined&&raw!==null){ + if(!Array.isArray(raw)&&(typeof raw!=='object'||Object.getPrototypeOf(raw)!==Object.prototype)) + return false; + const samples=Array.isArray(raw)?raw.map(x=>[x?.channelId,x]):Object.entries(raw); + const seen=new Set(); + for(const [key,m] of samples){ + if(!ids.has(key)||seen.has(key)||!m||typeof m!=='object')return false; + seen.add(key); + for(const prop of ['peak','peakLeft','peakRight','rmsLeft','rmsRight']){ + if(m[prop]!==undefined&&(typeof m[prop]!=='number'|| + !Number.isFinite(m[prop])||m[prop]<0))return false; + } + if(!['peak','peakLeft','peakRight','rmsLeft','rmsRight'] + .some(prop=>typeof m[prop]==='number'))return false; + } + } + return true; + } + function normalizeSnapshot(payload){ + const raw=payload?.snapshot||payload; + // Flat M4 readback is not the universal v8 device inventory. + return raw&&typeof raw==='object'&&raw.schemaVersion===6?raw:null; + } + function receiveSnapshot(data,fromNative){ + const s=normalizeSnapshot(data); + if(!validSnapshot(s)){ + if(fromNative)showFeedback('REJECTED SNAPSHOT · Invalid native epoch, revision or ChannelId'); + return false; + } + if(acceptedNative&&!fromNative)return false; + if(fromNative&&acceptedNative&&accepted&& + BigInt(s.device.epoch)JSON.stringify([d.backend,d.captureDevice,d.playbackDevice, + d.sampleRate,d.bufferFrames,d.inputEndpoints,d.outputEndpoints, + d.enabledInputs,d.enabledOutputs]); + if(hardware(s.device)!==hardware(accepted.device)){ + showFeedback('REJECTED DEVICE READBACK · epoch unchanged; retained verified pins'); + return false; + } + } + const priorEpoch=acceptedNative?accepted?.device?.epoch:null; + const structure=s.device.epoch+':'+s.graph.rosterRevision+':'+ + s.graph.channels.map(c=>[c.id,c.role,c.processingFormat,c.primaryOutId, + (c.inserts||[]).map(f=>f.id).join(','),(c.sends||[]).map(x=>x.id).join(',')].join(':')).join('|')+ + ':'+s.graph.capabilities.supportedOps.join('|'); + // Full snapshots remain authoritative; a telemetry-only message must + // still pass the same epoch/graph/roster validation and ACK fences. + const controlProjection=JSON.stringify([ + s.graph.channels,s.graph.destinations,s.graph.capabilities,s.catalog||null]); + const headerProjection=JSON.stringify([ + s.device.backend,s.device.sampleRate,s.device.bufferFrames, + s.device.outputArmed,s.device.epoch,s.graph.revision,s.productionCallbackLive,!!fromNative]); + accepted=s;acceptedNative=!!fromNative; + snapshotSerial++; + byId.clear(); + for(const c of s.graph.channels)byId.set(c.id,c); + if(fromNative&&priorEpoch!==null&&priorEpoch!==s.device.epoch){ + // Device replacement invalidates all old intents and controls; never + // replay them into an unrelated callback/port inventory. + pending.clear();pendingTargets.clear();awaitingSnapshot.clear(); + selectedIds.clear();selectionAnchor=null; + showFeedback('DEVICE CHANGED · native source and destination inventory refreshed'); + } + for(const [requestId,task] of awaitingSnapshot){ + if(ackMatches(task)){ + awaitingSnapshot.delete(requestId); + for(const target of task.targets||[])pendingTargets.delete(target); + } + } + const newStructure=structure!==lastStructure|| + root.dataset.demo!==String(!fromNative); + const newControls=controlProjection!==lastControlProjection; + const newHeader=headerProjection!==lastHeaderProjection; + lastStructure=structure; + lastControlProjection=controlProjection; + lastHeaderProjection=headerProjection; + if(newStructure){ + render(); + }else if(newControls){ + refreshAcceptedControls();refreshDisabled(); + }else{ + // High-frequency native meter snapshots only: no select.value writes, + // role filters, getBoundingClientRect, FX catalog DOM or fader remount. + uiStats.telemetryFastFrames++; + refreshMeters(); + } + if(newHeader&&!newStructure)updateHeader(); + root.dataset.demo=String(!fromNative); + if(newStructure||newControls){refreshDevicePanel();refreshPluginCatalog();refreshQuickFx();} + // Integration readback is intentionally not a production callback. + // It must never replace the working M4 console until callback cutover. + if(!fromNative||s.productionCallbackLive===true)setVisible(true); + return true; + } + const makeDemo=()=>{ + const names=['Lead Vocal','Guest Mic','Music L','Music R','Speech','Stream','Backing','Guitar','Keys','Talkback']; + const channels=names.map((name,i)=>({ + id:'DEMO:'+String(i+1),role:'INPUT',name,color:'#4e8ba4',processingFormat:i===2||i===3?'STEREO':'MONO', + source:null,primaryOut:null,inserts:[],sends:[],controls:{faderDb:0,pan:0,mute:false,solo:false} + })); + channels.push({id:'DEMO:MAIN',role:'MAIN',name:'MAIN',processingFormat:'STEREO', + inserts:[],sends:[],controls:{faderDb:0,pan:0,mute:false,solo:false}}); + return {schemaVersion:6,productionCallbackLive:false, + device:{epoch:'0',backend:'BROWSER DEMO',sampleRate:null,bufferFrames:null,outputArmed:false, + inputEndpoints:[],outputEndpoints:[]},graph:{revision:'0',rosterRevision:'0',channels,destinations:[], + capabilities:{dynamicChannels:false,groups:false,fxReturns:false,sendsOnFaders:false,supportedOps:[]}}, + telemetry:{rawCapturePresent:false,channelMeterRmsPeak:{}}}; + }; + function options(select,items,current,emptyLabel){ + select.replaceChildren(); + const zero=h('option','',emptyLabel);zero.value='';select.append(zero); + let found=!current; + for(const item of items){ + if(!item||typeof item.id!=='string'||!item.id)continue; + const opt=h('option','',item.name||item.label||item.id); + opt.value=item.id;opt.disabled=item.available===false||item.active===false; + if(current===item.id){opt.selected=true;found=true} + select.append(opt); + } + if(!found){ + const missing=h('option','','MISSING · '+current);missing.value=current; + missing.selected=true;missing.disabled=true;select.append(missing); + } + if(!current)select.value=''; + return select; + } + function legalOutputs(ch){ + const destinations=(accepted.graph.destinations||[]).filter(dst=>{ + const target=byId.get(dst.id); + return target&&target.id!==ch.id&&['MAIN','GROUP'].includes(target.role)&& + dst.acceptsPrimary!==false; + }); + // SOURCE channels may only route through native buses, not skip to a + // physical output. The MAIN/MONITOR roles can select verified render pins. + if(ch.role==='MAIN'||ch.role==='MONITOR') + return (accepted.device.outputEndpoints||[]).filter(p=> + p.active===true&&accepted.device.enabledOutputs.includes(p.port)); + return destinations; + } + function selectField(label,op,id,items,current,placeholder,extra){ + const row=h('label','arV6Field'); + row.append(h('span','arV6FieldName',label)); + const sel=options(h('select','arV6Select'),items,current,placeholder); + sel.dataset.op=op;sel.dataset.id=id; + if(extra)for(const [key,val] of Object.entries(extra))sel.dataset[key]=val; + sel.disabled=!can(op,id); + row.append(sel);return row; + } + function fxSection(ch){ + const section=h('div','arV6Fx'); + section.append(h('span','arV6SectionTitle','VST3 INSERTS')); + const list=Array.isArray(ch.inserts)?ch.inserts:[]; + for(const fx of list){ + const row=h('div','arV6FxSlot'); + row.dataset.fxId=clean(fx.id);row.dataset.id=ch.id; + row.draggable=can('MOVE_INSERT',ch.id); + row.append(button(fx.name||fx.pluginName||'VST3',{'data-op':'OPEN_INSERT_EDITOR', + 'data-id':ch.id,'data-native-insert-id':clean(fx.id)})); + const bypass=button(fx.bypassed?'OFF':'ON',{'data-op':'SET_INSERT_BYPASS', + 'data-id':ch.id,'data-native-insert-id':clean(fx.id),'aria-pressed':String(!fx.bypassed)}); + bypass.classList.toggle('isOff',!!fx.bypassed);row.append(bypass); + section.append(row); + } + const catalogReady=supported('ADD_INSERT')&&nativeCatalog().length>0; + const filePicker=supported('PICK_INSERT_FILE'); + const addFx=button(catalogReady?'+ ADD FX':filePicker?'+ OPEN VST3 FILE':'+ ADD FX', + catalogReady?{'data-ui':'OPEN_FX_QUICK','data-id':ch.id}: + filePicker?{'data-op':'PICK_INSERT_FILE','data-id':ch.id}: + {'data-ui':'OPEN_FX_QUICK','data-id':ch.id}); + addFx.classList.add('arV6AddFx');section.append(addFx); + return section; + } + function sendSection(ch){ + const section=h('div','arV6Sends'); + section.append(h('span','arV6SectionTitle','SEND · NATIVE')); + const sends=Array.isArray(ch.sends)?ch.sends:[]; + const targets=(accepted.graph.destinations||[]).filter(x=>x.acceptsSend===true); + // A silent dark knob has no keyboard/pointer action, cannot invent a route. + if(!sends.length){ + const zero=h('div','arV6Send arV6SendEmpty'); + zero.append(h('span','arV6SendName','NO PATCHED WIRE'), + h('span','arV6WirePot is-idle')); + section.append(zero); + } + for(const send of sends){ + const line=h('div','arV6Send');line.dataset.sendId=clean(send.id); + line.append(h('span','arV6SendName',clean(send.name||send.targetId))); + const toggle=button(send.tap==='PRE'?'PRE':'POST',{'data-op':'SET_SEND_TAP', + 'data-id':ch.id,'data-send':clean(send.id)}); + line.append(toggle); + const gain=h('label','arV6SendGain'); + const db=typeof send.levelDb==='number'?send.levelDb:NaN; + const verified=Number.isFinite(db); + const connected=acceptedNative&&accepted?.productionCallbackLive===true&& + !!byId.get(send.targetId)&&!!clean(send.id); + const knob=h('span','arV6WirePot '+(connected?'is-connected':'is-idle')); + knob.dataset.wireSourceId=ch.id;knob.dataset.sendId=clean(send.id); + // A missing native channel color stays neutral; never invent an identity. + knob.style.setProperty('--v6-wire-fill',connected?wirePotFill(send.targetId):'#4b535b'); + paintWirePot(knob,verified?db:0); + const slider=h('input','arV6SendLevel'); + slider.type='range';slider.min='-60';slider.max='12';slider.step='.1'; + slider.value=String(verified?clamp(db,-60,12):0); + slider.dataset.op='SET_SEND_LEVEL';slider.dataset.id=ch.id; + slider.dataset.send=clean(send.id); + slider.dataset.hasAcceptedLevel=String(verified); + slider.setAttribute('aria-label',(ch.name||ch.id)+' '+(send.name||send.targetId)+' native SEND gain dB'); + slider.disabled=!can('SET_SEND_LEVEL',ch.id)||!verified; + knob.append(slider); + const out=h('output','arV6SendDb',verified?db.toFixed(1)+' dB':'—'); + gain.append(knob,out); + line.append(gain);section.append(line); + } + const select=selectField('+ TO','ADD_SEND',ch.id,targets,'','NO NATIVE SEND BUS'); + section.append(select);return section; + } + // Metadata comes ONLY from the native accepted ChannelId roster. An + // unpublished/malformed identity gets a neutral non-role color, never + // a browser-assigned palette position or synthetic state. + const nativeIdentity=ch=>{ + const published=typeof ch.color==='string'&&/^#[0-9a-fA-F]{6}$/.test(ch.color); + const icon=typeof ch.icon==='string'&&Array.from(ch.icon).length<=4&& + Array.from(ch.icon).every(c=>c.codePointAt(0)>=32&&c.codePointAt(0)!==127)?ch.icon:''; + return {color:published?ch.color:'#5f9ab1',icon,published}; + }; + const roleLabel=ch=>clean(ch.role).toUpperCase()+ + (typeof ch.linkGroupId==='string'&&ch.linkGroupId? + ' · LINK '+ch.linkGroupId.slice(0,6):''); + function strip(ch,pinned=false){ + const role=clean(ch.role).toUpperCase(); + const elStrip=h('article','arV6Strip'+(pinned?' arV6Master':'')); + elStrip.dataset.channelId=ch.id; + const identity=nativeIdentity(ch); + elStrip.style.setProperty('--ch',identity.color); + elStrip.style.setProperty('--v6-strip-color',identity.color); + elStrip.dataset.identityPublished=String(identity.published); + const head=h('div','arV6StripHead'); + const roleName=h('span','arV6Role',roleLabel(ch)); + const name=h('strong','arV6Name',ch.name||ch.id);name.title=ch.id; + if(identity.icon)head.append(h('span','arV6IdentityIcon',identity.icon)); + head.append(roleName,name);elStrip.append(head); + elStrip.setAttribute('aria-selected',String(selectedIds.has(ch.id))); + const sourceSection=h('div','arV6Upper'); + const routeSection=h('div','arV6Route'); + const sources=(accepted.device.inputEndpoints||[]).filter(p=>p.active===true && accepted.device.enabledInputs.includes(p.port)); + if(role==='INPUT')routeSection.append(selectField('IN','SET_SOURCE',ch.id,sources, + ch.source?.portId||ch.source?.id||'','NO VERIFIED INPUT')); + else routeSection.append(h('div','arV6Field arV6FixedField','IN · '+role)); + const outs=legalOutputs(ch); + routeSection.append(selectField('OUT','SET_PRIMARY_OUT',ch.id,outs, + ch.primaryOutId||ch.primaryOut?.id||ch.primaryOut||'','NO VERIFIED OUT')); + const formats=['MONO','STEREO'].map(s=>({id:s,name:s})); + routeSection.append(selectField('M/ST','SET_PROCESSING_FORMAT',ch.id,formats, + ch.processingFormat||'','NATIVE FORMAT')); + sourceSection.append(routeSection,fxSection(ch),sendSection(ch)); + elStrip.append(sourceSection); + const controls=h('div','arV6Controls'); + const pan=h('label','arV6Pan');pan.append(h('span','','PAN')); + const panRange=h('input','arV6PanRange');panRange.type='range'; + panRange.min='-100';panRange.max='100';panRange.step='1'; + panRange.value=String(Number(ch.controls?.pan)||0); + paintPan(panRange,panRange.value); + panRange.dataset.op='SET_PAN';panRange.dataset.id=ch.id; + pan.append(panRange);controls.append(pan); + controls.append(button('M',{'data-op':'SET_MUTE','data-id':ch.id, + 'aria-pressed':String(!!ch.controls?.mute)})); + controls.append(button('S',{'data-op':'SET_SOLO','data-id':ch.id, + 'aria-pressed':String(!!ch.controls?.solo)})); + const cueKnown=typeof ch.controls?.cue==='boolean'&&role!=='MAIN'; + const cue=button('C',{'data-op':'SET_CUE','data-id':ch.id, + 'aria-pressed':String(ch.controls?.cue===true), + 'aria-label':(ch.name||ch.id)+' native monitor Cue/PFL'}); + cue.dataset.acceptedKnown=String(cueKnown);cue.disabled=!cueKnown||!can('SET_CUE',ch.id); + controls.append(cue); + const trimKnown=typeof ch.controls?.trimDb==='number'&&Number.isFinite(ch.controls.trimDb); + const trimRow=h('label','arV6Trim');trimRow.append(h('span','','TRIM')); + const trim=h('input','arV6TrimLevel');trim.type='range'; + trim.min='-24';trim.max='24';trim.step='.5'; + trim.value=String(trimKnown?clamp(ch.controls.trimDb,-24,24):0); + trim.dataset.op='SET_TRIM';trim.dataset.id=ch.id; + trim.dataset.acceptedKnown=String(trimKnown); + trim.setAttribute('aria-label',(ch.name||ch.id)+' digital input trim dB'); + trim.disabled=!trimKnown||!can('SET_TRIM',ch.id); + trimRow.append(trim,h('output','arV6TrimDb', + trimKnown?ch.controls.trimDb.toFixed(1):'—')); + controls.append(trimRow);elStrip.append(controls); + const lower=h('div','arV6Lower'); + const meter=h('div','arV6Meter');meter.dataset.meterId=ch.id; + meter.dataset.format=ch.processingFormat||'MONO'; + meter.setAttribute('aria-label','Native L/R PCM meter: '+(ch.name||ch.id)); + for(const side of ['L','R']){ + const lane=h('div','arV6MeterLane'); + lane.dataset.side=side; + for(let n=0;n<22;n++)lane.append(h('i','arV6Led')); + meter.append(lane); + } + const range=h('input','arV6Fader'); + range.type='range';range.min='-60';range.max='12';range.step='.1'; + const faderVal=Number(ch.controls?.faderDb); + range.value=String(Number.isFinite(faderVal)?clamp(faderVal,-60,12):0); + range.dataset.op='SET_FADER';range.dataset.id=ch.id; + range.setAttribute('aria-label',(ch.name||ch.id)+' fader dB'); + const lowerLabel=h('span','arV6Readout',(Number.isFinite(faderVal)?faderVal.toFixed(1):'—')+' dB'); + lower.append(meter,range,lowerLabel);elStrip.append(lower); + meterNodes.set(ch.id,{element:meter,lanes:[...meter.children]}); + const status=h('div','arV6StripStatus'); + status.dataset.statusId=ch.id; + const foot=h('div','arV6FootIdentity'); + if(identity.icon)foot.append(h('span','arV6FootIcon',identity.icon)); + foot.append(h('span','arV6FootName',ch.name||ch.id)); + const pcm=h('span','arV6PcmState',channelState(ch)); + status.append(foot,pcm); + statusNodes.set(ch.id,pcm);elStrip.append(status); + return elStrip; + } + function channelState(ch){ + if(!acceptedNative)return 'DEMO / NO AUDIO'; + if(accepted?.productionCallbackLive!==true)return 'NATIVE READBACK / NOT LIVE'; + if(ch.controls?.mute)return 'MUTED'; + const role=ch.role,t=accepted.telemetry||{}; + if(role==='INPUT'&&!ch.source)return 'SILENT / NO SOURCE'; + if(!accepted.device.outputArmed)return 'OUTPUT DISARMED'; + if(role==='MAIN')return t.mainPcmPresent===true? + 'MAIN PCM VERIFIED · ARMED':'MAIN PCM UNVERIFIED'; + if(role==='MONITOR')return t.monitorPcmPresent===true? + 'MONITOR PCM VERIFIED':'MONITOR PCM UNVERIFIED'; + if(role==='INPUT'&&t.rawCapturePresent!==true)return 'NO RAW CAPTURE PCM'; + const m=meterReadings.get(ch.id); + if(!m)return 'CHANNEL PCM UNVERIFIED'; + // An all-zero peak is silence/available measurement, not audible PCM. + const peaks=[m.peak,m.peakLeft,m.peakRight].filter(Number.isFinite); + const observed=peaks.some(p=>p>0); + if(!observed)return 'CHANNEL METER · SILENCE'; + return t.mainPcmPresent===true? + 'CHANNEL PCM MEASURED · MAIN OK':'CHANNEL PCM · MAIN UNVERIFIED'; + } + function updateHeader(){ + const d=accepted?.device||{},g=accepted?.graph||{}; + deviceText.textContent=(d.backend||'NO DEVICE')+' · '+ + (d.sampleRate?Math.round(d.sampleRate)+' Hz':'— Hz')+' / '+ + (d.bufferFrames||'—')+' frames · GRAPH '+(g.revision??'—'); + modeBadge.textContent=!acceptedNative?'DEMO · NOT CONNECTED': + accepted?.productionCallbackLive!==true?'NATIVE READBACK · NOT LIVE': + d.outputArmed?'NATIVE ACCEPTED · ARMED':'NATIVE ACCEPTED · OUTPUT DISARMED'; + root.dataset.demo=String(!acceptedNative); + root.dataset.armed=String(acceptedNative&&accepted?.productionCallbackLive===true&&!!d.outputArmed); + } + function updateSelection(){ + for(const strip of root.querySelectorAll('[data-channel-id]')){ + const selected=selectedIds.has(strip.dataset.channelId); + strip.classList.toggle('isSelected',selected); + strip.setAttribute('aria-selected',String(selected)); + } + refreshSelectionActions(); + refreshPluginCatalog(); + } + function selectChannel(id,event){ + const channel=byId.get(id); + if(!channel||channel.role==='MAIN')return; + const visible=[...lanes.querySelectorAll('.arV6Strip:not([hidden])')] + .map(strip=>strip.dataset.channelId); + if(!visible.includes(id))return; + if(event.shiftKey&&selectionAnchor&&visible.includes(selectionAnchor)){ + if(!event.ctrlKey&&!event.metaKey)selectedIds.clear(); + const a=visible.indexOf(selectionAnchor),b=visible.indexOf(id); + for(const x of visible.slice(Math.min(a,b),Math.max(a,b)+1))selectedIds.add(x); + }else if(event.ctrlKey||event.metaKey){ + if(selectedIds.has(id))selectedIds.delete(id);else selectedIds.add(id); + selectionAnchor=id; + }else{ + selectedIds.clear();selectedIds.add(id);selectionAnchor=id; + } + updateSelection(); // No DSP or ConsoleIntent involved. + } + function applyPresentation(){ + const value=roleFilter.value; + for(const strip of lanes.querySelectorAll('.arV6Strip')){ + const ch=byId.get(strip.dataset.channelId); + const match=ch&&(value==='ALL'||value==='SOLO'&&ch.controls?.solo===true|| + ch.role===value); + strip.hidden=!match; + } + // Presentational filters cannot alter native roster nor hide pinned MAIN. + if(lanes.querySelector('.arV6Strip:not([hidden])')===null)lanes.scrollLeft=0; + updateSelection();refreshBanks(); + } + function render(){ + if(!accepted)return; + uiStats.structureRenders++; + updateHeader(); + meterNodes.clear();statusNodes.clear();meterReadings.clear(); + lanes.replaceChildren();main.replaceChildren(); + const channels=accepted.graph.channels; + for(const id of selectedIds)if(!byId.has(id))selectedIds.delete(id); + if(selectionAnchor&&!byId.has(selectionAnchor))selectionAnchor=null; + for(const ch of channels){ + if(clean(ch.role).toUpperCase()==='MAIN')main.append(strip(ch,true)); + else lanes.append(strip(ch)); + } + if(!main.children.length){ + main.append(h('div','arV6NoMaster','MAIN NOT PUBLISHED BY NATIVE')); + } + const destinations=(accepted.graph.destinations||[]).filter(x=>x.acceptsSend===true); + options(sendMode,destinations,modeSend,'MAIN FADERS'); + const cap=accepted.graph.capabilities||{}; + sendMode.disabled=!acceptedNative||!cap.sendsOnFaders; + add.disabled=!can('CREATE_CHANNEL'); + refreshDisabled();syncFaderMode();refreshMeters();applyPresentation(); + } + function refreshDisabled(){ + if(!accepted)return; + for(const node of root.querySelectorAll('[data-op]')){ + const op=node.dataset.op,id=node.dataset.id||null; + node.disabled=!can(op,id)|| + (op==='SET_SEND_LEVEL'&&node.dataset.hasAcceptedLevel!=='true')|| + ((op==='SET_TRIM'||op==='SET_CUE')&&node.dataset.acceptedKnown!=='true'); + } + add.disabled=!can('CREATE_CHANNEL'); + refreshSelectionActions(); + const caps=accepted.graph.capabilities||{}; + roleSelect.disabled=!can('CREATE_CHANNEL'); + for(const option of roleSelect.options){ + option.disabled=(option.value==='GROUP'&&!caps.groups)|| + (option.value==='FX_RETURN'&&!caps.fxReturns)|| + (option.value==='MONITOR'&&!caps.monitor); + } + sendMode.disabled=!acceptedNative||!caps.sendsOnFaders; + for(const n of root.querySelectorAll('.arV6Fader')){ + if(modeSend){ + const ch=byId.get(n.dataset.id); + const hasSend=(ch?.sends||[]).some(s=>s.targetId===modeSend); + n.disabled=!hasSend||!can('SET_SEND_LEVEL',n.dataset.id); + } + } + } + function refreshAcceptedControls(){ + uiStats.controlRefreshes++; + for(const strip of root.querySelectorAll('[data-channel-id]')){ + const ch=byId.get(strip.dataset.channelId); + if(!ch)continue; + const identity=nativeIdentity(ch); + if(strip.style.getPropertyValue('--ch')!==identity.color){ + strip.style.setProperty('--ch',identity.color); + strip.style.setProperty('--v6-strip-color',identity.color); + } + strip.dataset.identityPublished=String(identity.published); + const nameNode=strip.querySelector('.arV6Name'); + if(nameNode&&nameNode.textContent!==ch.name)nameNode.textContent=ch.name; + const footName=strip.querySelector('.arV6FootName'); + if(footName&&footName.textContent!==ch.name)footName.textContent=ch.name; + for(const [container,selector] of [ + [strip.querySelector('.arV6StripHead'),'.arV6IdentityIcon'], + [strip.querySelector('.arV6FootIdentity'),'.arV6FootIcon']]){ + if(!container)continue; + let icon=container.querySelector(selector); + if(identity.icon){ + if(!icon){icon=h('span',selector.slice(1));container.prepend(icon);} + if(icon.textContent!==identity.icon)icon.textContent=identity.icon; + }else icon?.remove(); + } + const roleNode=strip.querySelector('.arV6Role'); + if(roleNode&&roleNode.textContent!==roleLabel(ch)) + roleNode.textContent=roleLabel(ch); + const choose=(op,value)=>{ + const field=strip.querySelector('select[data-op="'+op+'"]'); + if(!field)return; + const actual=typeof value==='string'?value:''; + if([...field.options].some(o=>o.value===actual))field.value=actual; + }; + choose('SET_SOURCE',ch.source?.portId||ch.source?.id||''); + choose('SET_PROCESSING_FORMAT',ch.processingFormat||''); + choose('SET_PRIMARY_OUT',ch.primaryOutId||ch.primaryOut?.id||(typeof ch.primaryOut==='string'?ch.primaryOut:'')); + choose('ADD_SEND',''); + const pan=strip.querySelector('[data-op="SET_PAN"]'); + if(pan){ + pan.value=String(Number(ch.controls?.pan)||0); + paintPan(pan,pan.value); + } + const meter=strip.querySelector('[data-meter-id]'); + if(meter)meter.dataset.format=ch.processingFormat||'MONO'; + for(const op of ['SET_MUTE','SET_SOLO','SET_CUE']){ + const n=strip.querySelector('button[data-op="'+op+'"]'); + if(n)n.setAttribute('aria-pressed',String(!!ch.controls?.[ + op==='SET_MUTE'?'mute':op==='SET_SOLO'?'solo':'cue'])); + if(n&&op==='SET_CUE')n.dataset.acceptedKnown=String( + typeof ch.controls?.cue==='boolean'&&ch.role!=='MAIN'); + } + const trim=strip.querySelector('[data-op="SET_TRIM"]'); + if(trim){ + const known=typeof ch.controls?.trimDb==='number'&&Number.isFinite(ch.controls.trimDb); + trim.dataset.acceptedKnown=String(known); + trim.value=String(known?clamp(ch.controls.trimDb,-24,24):0); + const readout=strip.querySelector('.arV6TrimDb'); + if(readout)readout.textContent=known?ch.controls.trimDb.toFixed(1):'—'; + } + for(const node of strip.querySelectorAll('.arV6FxSlot')){ + const fx=(ch.inserts||[]).find(x=>String(x.id)===node.dataset.fxId); + const power=node.querySelector('[data-op="SET_INSERT_BYPASS"]'); + if(fx&&power){ + power.textContent=fx.bypassed?'OFF':'ON'; + power.classList.toggle('isOff',!!fx.bypassed); + power.setAttribute('aria-pressed',String(!fx.bypassed)); + } + } + for(const node of strip.querySelectorAll('.arV6Send')){ + const send=(ch.sends||[]).find(x=>String(x.id)===node.dataset.sendId); + const tap=node.querySelector('[data-op="SET_SEND_TAP"]'); + if(send&&tap)tap.textContent=send.tap==='PRE'?'PRE':'POST'; + const gain=node.querySelector('.arV6SendLevel'); + if(gain){ + const db=Number(send?.levelDb),verified=!!send&&Number.isFinite(db); + gain.dataset.hasAcceptedLevel=String(verified); + gain.value=String(verified?clamp(db,-60,12):0); + const out=node.querySelector('.arV6SendDb'); + if(out)out.textContent=verified?db.toFixed(1)+' dB':'—'; + const knob=node.querySelector('.arV6WirePot'); + if(knob){ + const connected=acceptedNative&&accepted?.productionCallbackLive===true&& + !!byId.get(send?.targetId)&&!!clean(send?.id); + knob.classList.toggle('is-connected',connected); + knob.classList.toggle('is-idle',!connected); + knob.style.setProperty('--v6-wire-fill',connected?wirePotFill(send.targetId):'#4b535b'); + paintWirePot(knob,verified?db:0); + } + } + } + } + syncFaderMode();refreshMeters();applyPresentation(); + } + function syncFaderMode(){ + for(const range of root.querySelectorAll('.arV6Fader')){ + const ch=byId.get(range.dataset.id); + const send=modeSend?(ch?.sends||[]).find(s=>s.targetId===modeSend):null; + const db=Number(modeSend?send?.levelDb:ch?.controls?.faderDb); + range.value=String(Number.isFinite(db)?clamp(db,-60,12):0); + const text=range.parentElement?.querySelector('.arV6Readout'); + if(text)text.textContent=(Number.isFinite(db)?db.toFixed(1):'—')+' dB'; + } + } + function refreshMeters(){ + if(!accepted)return; + const incoming=acceptedNative?accepted.telemetry?.channelMeterRmsPeak:null; + meterReadings=Array.isArray(incoming)? + new Map(incoming.map(m=>[m.channelId,m])): + incoming&&typeof incoming==='object'?new Map(Object.entries(incoming)):new Map(); + const ledsForPeak=peak=>{ + if(typeof peak!=='number'||!Number.isFinite(peak)||peak<=0)return 0; + // Native linear PCM peak: fixed -60..0 dBFS 22-LED ladder; values >1 + // saturate red, never change the green/yellow/red reference positions. + return clamp(Math.ceil(22*(60+Math.max(-60,20*Math.log10(peak)))/60),0,22); + }; + for(const [id,view] of meterNodes){ + const ch=byId.get(id),m=meterReadings.get(id); + if(!ch)continue; + const mono=ch.processingFormat==='MONO'; + const expected=mono?'MONO':'STEREO'; + if(view.element.dataset.format!==expected)view.element.dataset.format=expected; + for(const lane of view.lanes){ + const side=lane.dataset.side; + // No invented stereo copy: an absent right peak stays dark. + const value=m?(side==='L'?(m.peakLeft??(mono?m.peak:0)):m.peakRight):0; + const lit=mono&&side==='R'?0:ledsForPeak(value); + if(lane.dataset.lit===String(lit))continue; + lane.dataset.lit=String(lit); + for(let i=0;i=total; + } + function jump(dir){ + const first=lanes.querySelector('.arV6Strip:not([hidden])'); + if(!first)return; + const perPage=Math.max(1,Math.floor(lanes.clientWidth/first.getBoundingClientRect().width)); + lanes.scrollBy({left:dir*perPage*first.getBoundingClientRect().width,behavior:'auto'}); + refreshBanks(); + } + bankPrev.addEventListener('click',()=>jump(-1)); + bankNext.addEventListener('click',()=>jump(1)); + lanes.addEventListener('scroll',refreshBanks,{passive:true}); + if(typeof ResizeObserver==='function')new ResizeObserver(refreshBanks).observe(lanes); + sendMode.addEventListener('change',()=>{modeSend=sendMode.value; + syncFaderMode();refreshDisabled(); + showFeedback(modeSend? + 'SENDS ON FADERS · native sends only · select MAIN FADERS to return':'MAIN FADERS · source gains unchanged'); + }); + // Reorder is one native structural intent; DOM/PCM order never changes on drop. + root.addEventListener('dragstart',event=>{ + const node=event.target.closest?.('.arV6FxSlot'); + if(!node||!node.draggable||!can('MOVE_INSERT',node.dataset.id)){ + event.preventDefault();return; + } + draggingFx={id:node.dataset.id,insertId:node.dataset.fxId}; + event.dataTransfer?.setData('text/plain',draggingFx.insertId); + if(event.dataTransfer)event.dataTransfer.effectAllowed='move'; + }); + root.addEventListener('dragover',event=>{ + const node=event.target.closest?.('.arV6FxSlot'); + if(draggingFx&&node&&draggingFx.id===node.dataset.id&& + draggingFx.insertId!==node.dataset.fxId)event.preventDefault(); + }); + root.addEventListener('drop',event=>{ + const node=event.target.closest?.('.arV6FxSlot'),source=draggingFx; + draggingFx=null; + if(!source||!node||source.id!==node.dataset.id|| + source.insertId===node.dataset.fxId)return; + event.preventDefault(); + sendIntent('MOVE_INSERT',source.id, + {insertId:source.insertId,beforeInsertId:node.dataset.fxId}); + }); + root.addEventListener('dragend',()=>{draggingFx=null}); + root.addEventListener('click',event=>{ + const n=event.target.closest('button[data-op]'); + if(!n||n.disabled)return; + const op=n.dataset.op,id=n.dataset.id||null,ch=byId.get(id); + if(op==='CREATE_CHANNEL'){ + // Native must allocate ChannelId; never append a fake strip on ACK. + const role=roleSelect.value; + const caps=accepted.graph.capabilities||{}; + if(!['MONO','STEREO','GROUP','FX_RETURN','MONITOR'].includes(role))return; + if(role==='GROUP'&&!caps.groups||role==='FX_RETURN'&&!caps.fxReturns|| + role==='MONITOR'&&!caps.monitor){showFeedback('UNAVAILABLE · Native role not accepted');return} + sendIntent(op,null,{role});return; + } + if(!ch)return; + if(op==='SET_MUTE')sendIntent(op,id,{value:!ch.controls?.mute}); + else if(op==='SET_SOLO')sendIntent(op,id,{value:!ch.controls?.solo}); + else if(op==='SET_CUE'&&typeof ch.controls?.cue==='boolean') + sendIntent(op,id,{value:!ch.controls.cue}); + else if(op==='SET_INSERT_BYPASS'){ + const fx=(ch.inserts||[]).find(x=>String(x.id)===n.dataset.nativeInsertId); + if(fx)sendIntent(op,id,{insertId:fx.id,bypassed:!fx.bypassed}); + } + else if(op==='OPEN_INSERT_EDITOR')sendIntent(op,id,{insertId:n.dataset.nativeInsertId}); + else if(op==='SET_SEND_TAP'){ + const send=(ch.sends||[]).find(x=>String(x.id)===n.dataset.send); + if(send)sendIntent(op,id,{sendId:send.id,tap:send.tap==='PRE'?'POST':'PRE'}); + } + else if(op==='PICK_INSERT_FILE')sendIntent(op,id,{}); + else if(op==='ADD_INSERT') + showFeedback('Native plugin selection requires the verified Plugin Manager'); + }); + root.addEventListener('click',event=>{ + const launcher=event.target.closest('button[data-ui="OPEN_PLUGIN_MANAGER"]'); + if(launcher){openPluginManager(launcher.dataset.id);return;} + const fast=event.target.closest('button[data-ui="OPEN_FX_QUICK"]'); + if(fast){openQuickFx(fast.dataset.id,fast);return;} + const strip=event.target.closest('.arV6Strip'); + if(!strip||event.target.closest('button,input,select,[draggable]'))return; + selectChannel(strip.dataset.channelId,event); + }); + // Inline rename never mutates accepted name. Only native ACK + matching + // snapshot changes the channel header; Escape/blur only cancels local input. + function beginRename(nameNode){ + const strip=nameNode?.closest('.arV6Strip'),id=strip?.dataset.channelId; + const ch=byId.get(id); + if(!ch||!can('RENAME_CHANNEL',id)){ + showFeedback('RENAME UNAVAILABLE · native RENAME_CHANNEL not installed');return; + } + if(strip.querySelector('.arV6Rename'))return; + const input=h('input','arV6Rename'); + input.type='text';input.maxLength=40;input.value=ch.name; + input.setAttribute('aria-label','Rename '+ch.name+' using native ChannelId'); + let finished=false; + const finish=commit=>{ + if(finished)return; + finished=true; // DOM replacement emits blur synchronously in WebView. + const newName=input.value.trim(); + const valid=commit&&newName&&newName.length<=40&&newName!==ch.name&& + !Array.from(newName).some(c=>c.charCodeAt(0)<32||c.charCodeAt(0)===127); + // Dispatch once while the editor is stable. Only native accepted + // snapshot may change the actual channel name. + if(valid)sendIntent('RENAME_CHANNEL',id,{name:newName}); + input.replaceWith(nameNode); + }; + input.addEventListener('keydown',event=>{ + if(event.key==='Enter'){event.preventDefault();finish(true)} + if(event.key==='Escape'){event.preventDefault();finish(false)} + }); + input.addEventListener('blur',()=>finish(false),{once:true}); + nameNode.replaceWith(input);input.focus();input.select(); + } + root.addEventListener('dblclick',event=>{ + const pot=event.target.closest('.arV6WirePot.is-connected'); + if(pot){ + const slider=pot.querySelector('.arV6SendLevel'); + if(slider&&!slider.disabled){ + const id=slider.dataset.id,sendId=slider.dataset.send; + const current=acceptedWireLevel(id,sendId); + if(current!==null&¤t!==0) + sendIntent('SET_SEND_LEVEL',id,{sendId,levelDb:0}); + refreshAcceptedControls();refreshDisabled(); + } + event.preventDefault();return; + } + const n=event.target.closest('.arV6PanRange'); + if(n&&!n.disabled){sendIntent('SET_PAN',n.dataset.id,{value:0});return;} + const name=event.target.closest('.arV6Name'); + if(name)beginRename(name); + }); + // Wire-pot is a compact SVG silhouette with full mouse-relative travel. + // During a drag only its local readout changes; exactly ONE native intent + // is submitted on pointerup. ACK + matching snapshot remain authoritative. + root.addEventListener('pointerdown',event=>{ + if(event.button!==0||wirePotGesture)return; + const knob=event.target.closest?.('.arV6WirePot.is-connected'); + const input=knob?.querySelector('.arV6SendLevel'); + if(!knob||!input||input.disabled||!can('SET_SEND_LEVEL',input.dataset.id))return; + const original=acceptedWireLevel(input.dataset.id,input.dataset.send); + if(original===null)return; + wirePotGesture={pointerId:event.pointerId,knob,input,original, + id:input.dataset.id,sendId:input.dataset.send, + x:event.clientX,y:event.clientY,preview:original}; + // Capture on the actual input: remains focused and keyboard accessible. + input.setPointerCapture?.(event.pointerId); + // ZERO idle pointermove listeners. Install a capture-local handler + // exclusively for the duration of this one edit. + input.onpointermove=moveWirePot; + event.preventDefault(); + }); + function moveWirePot(event){ + const g=wirePotGesture; + if(!g||event.pointerId!==g.pointerId)return; + const displacement=(event.clientX-g.x)-(event.clientY-g.y); + const db=Math.round(clamp(g.original+displacement/(event.shiftKey?14:3),-60,12)*10)/10; + if(db!==g.preview){ + g.preview=db;g.input.value=String(db); + paintWirePot(g.knob,db); + const label=g.knob.parentElement?.querySelector('.arV6SendDb'); + if(label)label.textContent=db.toFixed(1)+' dB'; + } + event.preventDefault(); + } + function finishWirePot(event,cancelled=false){ + const g=wirePotGesture; + if(!g||event.pointerId!==g.pointerId)return; + wirePotGesture=null; + g.input.onpointermove=null; + g.input.releasePointerCapture?.(event.pointerId); + const delta=g.preview!==g.original; + // Do not stage an edit when pointercancel/blur/Escape rejects the gesture. + if(!cancelled&&delta){ + sendIntent('SET_SEND_LEVEL',g.id,{sendId:g.sendId,levelDb:g.preview}); + } + if(cancelled)showFeedback('SEND CANCELLED · native accepted gain unchanged'); + refreshAcceptedControls();refreshDisabled(); + event.preventDefault(); + } + root.addEventListener('pointerup',event=>finishWirePot(event)); + root.addEventListener('pointercancel',event=>finishWirePot(event,true)); + root.addEventListener('keydown',event=>{ + if(event.key==='Escape'&&wirePotGesture){ + finishWirePot({pointerId:wirePotGesture.pointerId, + preventDefault:()=>{}},true); + event.preventDefault(); + } + }); + root.addEventListener('change',event=>{ + const n=event.target.closest('[data-op]'); + if(!n||n.disabled)return; + const id=n.dataset.id,op=n.dataset.op,ch=byId.get(id); + if(!ch)return; + if(op==='SET_SOURCE'&&n.value){ + const endpoint=(accepted.device.inputEndpoints||[]).find(e=>e.id===n.value&&e.available!==false&&e.active!==false); + if(endpoint)sendIntent(op,id,{portId:endpoint.id}); + }else if(op==='SET_PRIMARY_OUT'&&n.value){ + if(legalOutputs(ch).some(p=>p.id===n.value)) + sendIntent(op,id,{destinationId:n.value}); + } + else if(op==='SET_PROCESSING_FORMAT')sendIntent(op,id,{format:n.value}); + else if(op==='ADD_SEND'&&n.value)sendIntent(op,id,{targetId:n.value,tap:'POST',levelDb:0}); + else if(op==='SET_PAN'){ + const value=Number(n.value),snapped=Math.abs(value)<=4?0:value; + sendIntent(op,id,{value:snapped}); // ACK/snapshot, no optimistic PAN. + } + else if(op==='SET_TRIM'){ + const db=Number(n.value); + if(typeof ch.controls?.trimDb==='number'&&Number.isFinite(db)) + sendIntent(op,id,{valueDb:clamp(db,-24,24)}); + } + else if(op==='SET_SEND_LEVEL'){ + const send=(ch.sends||[]).find(s=>String(s.id)===n.dataset.send); + const value=Number(n.value); + if(send&&typeof send.levelDb==='number'&&Number.isFinite(send.levelDb)&&Number.isFinite(value)) + sendIntent('SET_SEND_LEVEL',id,{sendId:send.id, + levelDb:Math.round(clamp(value,-60,12)*10)/10}); + } + else if(op==='SET_FADER'){ + if(modeSend){ + const send=(ch.sends||[]).find(s=>s.targetId===modeSend); + if(send)sendIntent('SET_SEND_LEVEL',id,{sendId:send.id,levelDb:Number(n.value)}); + else showFeedback('UNAVAILABLE · No native send on this channel'); + }else sendIntent(op,id,{valueDb:Number(n.value)}); + } + // Restore only accepted controls without remounting meters or fader nodes. + if(accepted){refreshAcceptedControls();refreshDisabled();} + }); + if(native){ + backend.addEventListener('arMixConsoleSnapshot',s=>receiveSnapshot(s,true)); + backend.addEventListener('arMixConsoleAck',receiveAck); + requestSnapshot(); + }else if(new URLSearchParams(location.search).get('console')==='v6'){ + // The opt-in browser preview is visibly DEMO with every mutation disabled. + // Existing baseline preview without ?console=v6 remains backward compatible. + receiveSnapshot(makeDemo(),false); + showFeedback('BROWSER DEMO · UI layout only · no PCM, hardware, installed VST3 or LIVE routes'); + } + // Host/browser acceptance harness: dispatch a native envelope explicitly; + // no public function may forge a native acceptance in a real JUCE session. + if(!native){ + window.addEventListener('arMixV6Fixture',e=>receiveSnapshot(e.detail?.snapshot||e.detail,false)); + } + window.__arMixV6ReadOnly=()=>({ + nativePublisher:acceptedNative,revision:accepted?.graph?.revision??null, + epoch:accepted?.device?.epoch??null,visibleChannelIds:[...byId.keys()], + pendingCount:pending.size,selectedChannelIds:[...selectedIds],feedback, + uiStats:{...uiStats} + }); +})(); diff --git a/web/styles-src/20-button-180.css b/web/styles-src/20-button-180.css index c217cfe70..a82dd60a3 100644 --- a/web/styles-src/20-button-180.css +++ b/web/styles-src/20-button-180.css @@ -3,7 +3,7 @@ Semantic colors alone define the latched state; only the transient :active pointer press moves the cap inward by 1px without changing its layout slot. */ :root{ - --b180-off:#cbd1d1;--b180-edge:#747f7f;--b180-off-ink:#172229; + --b180-off:#E7EFF0;--b180-edge:#747f7f;--b180-off-ink:#172229; --b180-color:var(--b180-off);--b180-border:var(--b180-edge); --b180-ink:var(--b180-off-ink); --b180-on-cyan:#94e8ed;--b180-on-green:#91edac; diff --git a/web/styles-src/43-hardware-backlit.css b/web/styles-src/43-hardware-backlit.css new file mode 100644 index 000000000..72d741113 --- /dev/null +++ b/web/styles-src/43-hardware-backlit.css @@ -0,0 +1,157 @@ +/* Owner-approved V5 graphite hardware keys, production native/legacy console. + ONE SVG cutout legend, ONE white edge shine, asymmetric occluded leakage. + No hover repaint, SVG filters, blur, infinite animation, or fake audio state. + This module is LAST in the deterministic CSS build, replacing BTN-180 only + on opt-in tactile mixer buttons. Navigation, routing pins, meters, faders, + editor launchers, dropdowns and ordinary dialog actions are NOT backlit. */ +#app button.mx-hw-key { + --mx-hw-led:210,225,234; + position:relative!important; + display:inline-block!important; + box-sizing:border-box!important; + min-width:0!important; + padding:2px!important; + overflow:hidden!important; + isolation:isolate!important; + border:1px solid #0c151b!important; + border-radius:5px!important; + background:linear-gradient(180deg,#0b141b,#25343d)!important; + box-shadow:inset 0 2px 4px #03080db5!important; + color:transparent!important; + text-shadow:none!important; + letter-spacing:0!important; + line-height:normal!important; + filter:none!important; + backdrop-filter:none!important; + -webkit-backdrop-filter:none!important; + transform:none!important; + transition:none!important; + text-align:center!important; + cursor:pointer; + touch-action:manipulation; +} +#app button.mx-hw-key.mx-hw-mute {--mx-hw-led:255,64,85} +#app button.mx-hw-key.mx-hw-solo {--mx-hw-led:255,208,44} +#app button.mx-hw-key.mx-hw-cue {--mx-hw-led:90,200,231} +#app button.mx-hw-key.mx-hw-processing {--mx-hw-led:87,211,189} +#app button.mx-hw-key.mx-hw-phase {--mx-hw-led:243,164,81} +#app button.mx-hw-key.mx-hw-link {--mx-hw-led:163,141,235} +#app button.mx-hw-key.mx-hw-neutral {--mx-hw-led:210,225,234} +/* V5 leakage strategy: four tiny STATIC gradients only in the closest + 1–2px gap, unequal sides, lower-center stronger; top almost occluded. */ +#app button.mx-hw-key::before { + content:""!important; + display:block!important; + position:absolute!important; + inset:1px!important; + border:0!important; + border-radius:4px!important; + width:auto!important;height:auto!important; + transform:none!important; + pointer-events:none!important; + z-index:2!important; + opacity:0!important; + box-shadow:none!important; + background: + linear-gradient(90deg,transparent 0%,rgba(var(--mx-hw-led),.035) 18%, + rgba(var(--mx-hw-led),.16) 33%,rgba(var(--mx-hw-led),.46) 49%, + rgba(var(--mx-hw-led),.27) 63%,rgba(var(--mx-hw-led),.07) 80%,transparent 100%) + center bottom / calc(100% - 12px) 2px no-repeat, + linear-gradient(180deg,transparent 0%,transparent 30%, + rgba(var(--mx-hw-led),.045) 50%,rgba(var(--mx-hw-led),.21) 75%, + rgba(var(--mx-hw-led),.1) 88%,transparent 100%) + left bottom / 2px 100% no-repeat, + linear-gradient(180deg,transparent 0%,transparent 44%, + rgba(var(--mx-hw-led),.075) 65%,rgba(var(--mx-hw-led),.17) 85%, + transparent 100%) + right bottom / 2px 100% no-repeat, + linear-gradient(90deg,transparent 0%,transparent 34%, + rgba(var(--mx-hw-led),.055) 50%,transparent 67%,transparent 100%) + center top / calc(100% - 18px) 1px no-repeat!important; +} +#app button.mx-hw-key::after{content:none!important;display:none!important} +#app button.mx-hw-key[aria-pressed="true"]::before, +#app button.mx-hw-key.active::before, +#app button.mx-hw-key.selected::before, +#app button.mx-hw-key.power-on::before, +#app button.mx-hw-key[data-mx-hw-on="true"]::before {opacity:1!important} +#app button.mx-hw-key > svg.mx-hw-face { + position:absolute!important; + z-index:1!important; + top:2px!important;right:2px!important;bottom:2px!important;left:2px!important; + width:calc(100% - 4px)!important; + height:calc(100% - 4px)!important; + display:block!important; + min-height:0!important; + overflow:hidden!important; + pointer-events:none!important; + transform:translateY(0)!important; + transition:none!important; + filter:none!important; +} +#app button.mx-hw-key svg .mx-hw-lamp {opacity:0!important} +#app button.mx-hw-key[aria-pressed="true"] svg .mx-hw-lamp, +#app button.mx-hw-key.active svg .mx-hw-lamp, +#app button.mx-hw-key.selected svg .mx-hw-lamp, +#app button.mx-hw-key.power-on svg .mx-hw-lamp, +#app button.mx-hw-key[data-mx-hw-on="true"] svg .mx-hw-lamp {opacity:1!important} +#app button.mx-hw-key[aria-pressed="true"] > svg.mx-hw-face, +#app button.mx-hw-key.active > svg.mx-hw-face, +#app button.mx-hw-key[data-mx-hw-on="true"] > svg.mx-hw-face { + transform:translateY(1px)!important; +} +#app button.mx-hw-key > .mx-hw-screen-reader{ + position:absolute!important; + width:1px!important;height:1px!important; + margin:-1px!important;padding:0!important; + border:0!important;overflow:hidden!important; + clip-path:inset(50%)!important; + white-space:nowrap!important; +} +#app button.mx-hw-key:hover:not(:disabled){ + filter:none!important; + background:linear-gradient(180deg,#0b141b,#25343d)!important; + box-shadow:inset 0 2px 4px #03080db5!important; +} +#app button.mx-hw-key:active:not(:disabled){ + transform:none!important; + background:linear-gradient(180deg,#0b141b,#25343d)!important; + box-shadow:inset 0 2px 4px #03080db5!important; +} +#app button.mx-hw-key:active:not(:disabled) > svg.mx-hw-face{ + transform:translateY(1px)!important; +} +#app button.mx-hw-key:focus-visible{ + outline:2px solid #9bbecd!important; + outline-offset:2px!important; +} +#app button.mx-hw-key:disabled { + cursor:not-allowed!important; + opacity:.47!important; + filter:none!important; +} +#app button.mx-hw-key:disabled::before{opacity:0!important} +#app button.mx-hw-key:disabled svg .mx-hw-lamp{opacity:0!important} +/* Keep target strip geometry intact, bypassing the legacy BTN-180 face. */ +#app #mixer .channel-actions button.mx-hw-key, +#app #mixer .utility-row button.mx-hw-key { + flex:1 1 0; +} +/* The legacy MASTER MUTE was sized only by .candy. Own its 29px geometry + explicitly after replacing that obsolete class, matching every strip. */ +#app #masterLeft .master-actions button.mx-hw-key, +#app #masterMute.mx-hw-key{ + height:29px!important; + min-height:29px!important; + max-height:29px!important; + align-self:center!important; +} +#app #mixer [data-channel-format-toggle].mx-hw-key{ + min-width:20px!important; +} +#app .arV6Controls button.mx-hw-key{width:28px!important;height:28px!important;padding:2px!important} +#app .arV6FxSlot button.mx-hw-key{min-width:27px!important;min-height:22px!important;padding:2px!important} +#app .arV6Send button.mx-hw-key{min-width:34px!important;min-height:20px!important;padding:2px!important} +@media(prefers-reduced-motion:reduce){ + #app button.mx-hw-key,#app button.mx-hw-key > svg.mx-hw-face{transition:none!important} +} diff --git a/web/styles.css b/web/styles.css index 74a63fe13..eb5955b00 100644 --- a/web/styles.css +++ b/web/styles.css @@ -611,7 +611,7 @@ html[data-mixperf="baseline"] .toolbar .spec-device:hover{border-color:#3586a2} Semantic colors alone define the latched state; only the transient :active pointer press moves the cap inward by 1px without changing its layout slot. */ :root{ - --b180-off:#cbd1d1;--b180-edge:#747f7f;--b180-off-ink:#172229; + --b180-off:#E7EFF0;--b180-edge:#747f7f;--b180-off-ink:#172229; --b180-color:var(--b180-off);--b180-border:var(--b180-edge); --b180-ink:var(--b180-off-ink); --b180-on-cyan:#94e8ed;--b180-on-green:#91edac; @@ -1447,3 +1447,160 @@ html:not([data-mixperf="baseline"]):not([data-mixperf="layers-off"]):not([data-m background-clip:content-box;border:0;box-shadow:none; } #app #mixer .meter .clip-led.latched{box-shadow:none!important} +/* Owner-approved V5 graphite hardware keys, production native/legacy console. + ONE SVG cutout legend, ONE white edge shine, asymmetric occluded leakage. + No hover repaint, SVG filters, blur, infinite animation, or fake audio state. + This module is LAST in the deterministic CSS build, replacing BTN-180 only + on opt-in tactile mixer buttons. Navigation, routing pins, meters, faders, + editor launchers, dropdowns and ordinary dialog actions are NOT backlit. */ +#app button.mx-hw-key { + --mx-hw-led:210,225,234; + position:relative!important; + display:inline-block!important; + box-sizing:border-box!important; + min-width:0!important; + padding:2px!important; + overflow:hidden!important; + isolation:isolate!important; + border:1px solid #0c151b!important; + border-radius:5px!important; + background:linear-gradient(180deg,#0b141b,#25343d)!important; + box-shadow:inset 0 2px 4px #03080db5!important; + color:transparent!important; + text-shadow:none!important; + letter-spacing:0!important; + line-height:normal!important; + filter:none!important; + backdrop-filter:none!important; + -webkit-backdrop-filter:none!important; + transform:none!important; + transition:none!important; + text-align:center!important; + cursor:pointer; + touch-action:manipulation; +} +#app button.mx-hw-key.mx-hw-mute {--mx-hw-led:255,64,85} +#app button.mx-hw-key.mx-hw-solo {--mx-hw-led:255,208,44} +#app button.mx-hw-key.mx-hw-cue {--mx-hw-led:90,200,231} +#app button.mx-hw-key.mx-hw-processing {--mx-hw-led:87,211,189} +#app button.mx-hw-key.mx-hw-phase {--mx-hw-led:243,164,81} +#app button.mx-hw-key.mx-hw-link {--mx-hw-led:163,141,235} +#app button.mx-hw-key.mx-hw-neutral {--mx-hw-led:210,225,234} +/* V5 leakage strategy: four tiny STATIC gradients only in the closest + 1–2px gap, unequal sides, lower-center stronger; top almost occluded. */ +#app button.mx-hw-key::before { + content:""!important; + display:block!important; + position:absolute!important; + inset:1px!important; + border:0!important; + border-radius:4px!important; + width:auto!important;height:auto!important; + transform:none!important; + pointer-events:none!important; + z-index:2!important; + opacity:0!important; + box-shadow:none!important; + background: + linear-gradient(90deg,transparent 0%,rgba(var(--mx-hw-led),.035) 18%, + rgba(var(--mx-hw-led),.16) 33%,rgba(var(--mx-hw-led),.46) 49%, + rgba(var(--mx-hw-led),.27) 63%,rgba(var(--mx-hw-led),.07) 80%,transparent 100%) + center bottom / calc(100% - 12px) 2px no-repeat, + linear-gradient(180deg,transparent 0%,transparent 30%, + rgba(var(--mx-hw-led),.045) 50%,rgba(var(--mx-hw-led),.21) 75%, + rgba(var(--mx-hw-led),.1) 88%,transparent 100%) + left bottom / 2px 100% no-repeat, + linear-gradient(180deg,transparent 0%,transparent 44%, + rgba(var(--mx-hw-led),.075) 65%,rgba(var(--mx-hw-led),.17) 85%, + transparent 100%) + right bottom / 2px 100% no-repeat, + linear-gradient(90deg,transparent 0%,transparent 34%, + rgba(var(--mx-hw-led),.055) 50%,transparent 67%,transparent 100%) + center top / calc(100% - 18px) 1px no-repeat!important; +} +#app button.mx-hw-key::after{content:none!important;display:none!important} +#app button.mx-hw-key[aria-pressed="true"]::before, +#app button.mx-hw-key.active::before, +#app button.mx-hw-key.selected::before, +#app button.mx-hw-key.power-on::before, +#app button.mx-hw-key[data-mx-hw-on="true"]::before {opacity:1!important} +#app button.mx-hw-key > svg.mx-hw-face { + position:absolute!important; + z-index:1!important; + top:2px!important;right:2px!important;bottom:2px!important;left:2px!important; + width:calc(100% - 4px)!important; + height:calc(100% - 4px)!important; + display:block!important; + min-height:0!important; + overflow:hidden!important; + pointer-events:none!important; + transform:translateY(0)!important; + transition:none!important; + filter:none!important; +} +#app button.mx-hw-key svg .mx-hw-lamp {opacity:0!important} +#app button.mx-hw-key[aria-pressed="true"] svg .mx-hw-lamp, +#app button.mx-hw-key.active svg .mx-hw-lamp, +#app button.mx-hw-key.selected svg .mx-hw-lamp, +#app button.mx-hw-key.power-on svg .mx-hw-lamp, +#app button.mx-hw-key[data-mx-hw-on="true"] svg .mx-hw-lamp {opacity:1!important} +#app button.mx-hw-key[aria-pressed="true"] > svg.mx-hw-face, +#app button.mx-hw-key.active > svg.mx-hw-face, +#app button.mx-hw-key[data-mx-hw-on="true"] > svg.mx-hw-face { + transform:translateY(1px)!important; +} +#app button.mx-hw-key > .mx-hw-screen-reader{ + position:absolute!important; + width:1px!important;height:1px!important; + margin:-1px!important;padding:0!important; + border:0!important;overflow:hidden!important; + clip-path:inset(50%)!important; + white-space:nowrap!important; +} +#app button.mx-hw-key:hover:not(:disabled){ + filter:none!important; + background:linear-gradient(180deg,#0b141b,#25343d)!important; + box-shadow:inset 0 2px 4px #03080db5!important; +} +#app button.mx-hw-key:active:not(:disabled){ + transform:none!important; + background:linear-gradient(180deg,#0b141b,#25343d)!important; + box-shadow:inset 0 2px 4px #03080db5!important; +} +#app button.mx-hw-key:active:not(:disabled) > svg.mx-hw-face{ + transform:translateY(1px)!important; +} +#app button.mx-hw-key:focus-visible{ + outline:2px solid #9bbecd!important; + outline-offset:2px!important; +} +#app button.mx-hw-key:disabled { + cursor:not-allowed!important; + opacity:.47!important; + filter:none!important; +} +#app button.mx-hw-key:disabled::before{opacity:0!important} +#app button.mx-hw-key:disabled svg .mx-hw-lamp{opacity:0!important} +/* Keep target strip geometry intact, bypassing the legacy BTN-180 face. */ +#app #mixer .channel-actions button.mx-hw-key, +#app #mixer .utility-row button.mx-hw-key { + flex:1 1 0; +} +/* The legacy MASTER MUTE was sized only by .candy. Own its 29px geometry + explicitly after replacing that obsolete class, matching every strip. */ +#app #masterLeft .master-actions button.mx-hw-key, +#app #masterMute.mx-hw-key{ + height:29px!important; + min-height:29px!important; + max-height:29px!important; + align-self:center!important; +} +#app #mixer [data-channel-format-toggle].mx-hw-key{ + min-width:20px!important; +} +#app .arV6Controls button.mx-hw-key{width:28px!important;height:28px!important;padding:2px!important} +#app .arV6FxSlot button.mx-hw-key{min-width:27px!important;min-height:22px!important;padding:2px!important} +#app .arV6Send button.mx-hw-key{min-width:34px!important;min-height:20px!important;padding:2px!important} +@media(prefers-reduced-motion:reduce){ + #app button.mx-hw-key,#app button.mx-hw-key > svg.mx-hw-face{transition:none!important} +}