From 0bd69fe6ee45136762b78af59de5bff6ac0e273d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 12 Nov 2026 21:01:39 +0700 Subject: [PATCH 001/140] feat(gui): reconcile contextual Gain/SOF workflow with approved Harmonice v9 and safe EdgeId tests --- .github/workflows/ui-smoke.yml | 2 + .../assets/mixer-control-keys.css | 25 ++++ .../assets/mixer-section-controls.css | 87 +++++++++++++ site/preview-v2/index.html | 113 ++++++++++++++--- ...pproved_css_stage_d_single_bundle_smoke.py | 2 +- ...s_png_buttons_wire_reconciliation_smoke.py | 4 +- tests/sof_contextual_console_smoke.py | 116 ++++++++++++++++++ web/approved-native-bridge.js | 1 + 8 files changed, 328 insertions(+), 22 deletions(-) create mode 100644 tests/sof_contextual_console_smoke.py diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 74b6a40fd..a98adbb74 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -359,6 +359,8 @@ jobs: run: python tests/approved_native_wire_gain_smoke.py - name: Stage D one runtime CSSOM and actual stylesheet network count run: python tests/approved_css_stage_d_single_bundle_smoke.py + - name: Contextual GAIN/FX and Sends-on-Faders browser workflow + run: python tests/sof_contextual_console_smoke.py - name: Stage C rendered CSS parity (original vs compiled, three viewports + hover) run: python tests/approved_css_stage_c_computed_parity_smoke.py - name: WIRE A main edge and safe graph integration in real Chromium DOM diff --git a/site/preview-buttons/assets/mixer-control-keys.css b/site/preview-buttons/assets/mixer-control-keys.css index 6996d2e17..8f1a67279 100644 --- a/site/preview-buttons/assets/mixer-control-keys.css +++ b/site/preview-buttons/assets/mixer-control-keys.css @@ -113,3 +113,28 @@ @media(prefers-reduced-motion:reduce){ .app .console-body .strip .mx-hw-row>button.mx-hw-key{transition:none!important} } + +/* SAME approved Harmonice v9 sprite in contextual SOF FX cell. + No new generated button artwork, CSS approximation or alternate state. */ +.app .console-body .strip .mx-sof-tap-key{ + position:relative;display:block;flex:0 0 55px;width:55px;height:29px; + margin:0;padding:0;border:0;background:transparent;overflow:visible; + isolation:isolate;cursor:pointer;color:transparent;font-size:0;line-height:0; +} +.app .console-body .strip .mx-sof-tap-key::before{ + content:"";position:absolute;inset:0;display:block;pointer-events:none; + background-image:url("harmonice-thin-flat-v9-approved-off-shadow-57x30.png"); + background-repeat:no-repeat;background-size:400% 300%; + background-position:var(--mx-native-x,33.333333%) 0%; +} +.app .console-body .strip .mx-sof-tap-key[data-tap-visual="pre"]{--mx-native-x:0%} +.app .console-body .strip .mx-sof-tap-key[data-tap-visual="idle"]{--mx-native-x:33.333333%} +.app .console-body .strip .mx-sof-tap-key[data-tap-visual="post"]{--mx-native-x:66.666667%} +.app .console-body .strip .mx-sof-tap-key[data-tap-visual="mixed"]{--mx-native-x:100%} +.app .console-body .strip .mx-sof-tap-key:disabled{opacity:.72;cursor:default} +.app .console-body .strip .mx-sof-tap-key:focus-visible{outline:2px solid #9eddec;outline-offset:2px} + +/* Same approved v9 physical OFF shadow as the source strip. */ +.app .console-body .strip .mx-sof-tap-key[data-tap-visual="pre"]::before{ + filter:drop-shadow(0 .8px 1.15px rgba(0,0,0,.42)) drop-shadow(0 1.7px 2.1px rgba(0,0,0,.32)); +} diff --git a/site/preview-v2/assets/mixer-section-controls.css b/site/preview-v2/assets/mixer-section-controls.css index 9131ee6e4..e3a3f9b0e 100644 --- a/site/preview-v2/assets/mixer-section-controls.css +++ b/site/preview-v2/assets/mixer-section-controls.css @@ -78,3 +78,90 @@ @media(max-width:900px){.command-bar{padding:0 5px;gap:4px}.command-bar .toolbar-label{display:none}.command-bar .tool{padding:4px 6px}.command-bar .toolbar-select{max-width:86px}.command-bar .sep{margin:0 1px}} + + +/* Contextual console views. One existing FX cell, no extra strip height. + All expensive effects/graph state stays mounted on the native side. */ +.command-bar .strip-view-switch{ + display:inline-flex;align-items:center;flex:none;border:1px solid #53656c; + border-radius:3px;overflow:hidden;background:#172833;height:28px; +} +.command-bar .strip-view-switch .tool{ + min-height:26px;height:26px;padding:3px 9px;border:0;border-radius:0; + font-size:10px;letter-spacing:.015em;background:transparent;color:#b9ced6; +} +.command-bar .strip-view-switch .tool+.tool{border-left:1px solid #4a5b65} +.command-bar .strip-view-switch .tool[aria-pressed="true"]{ + color:#eff9fa;background:#365765;box-shadow:inset 0 -2px #7ec5d4; +} +.command-bar .strip-view-switch .tool:disabled{opacity:.65;cursor:default} +.mixer-title .mix-context{ + display:inline-flex;align-items:center;min-width:0;margin-left:9px; + padding:2px 7px;border:1px solid #435c69;border-radius:2px; + color:#9acbd9;background:#182c37;font-size:10px;font-weight:500; + letter-spacing:.03em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; +} +.command-bar:has(#sofToggle[aria-pressed="true"]) #sofToggle{ + color:#e7f6f5;background:#2b5760;border-color:#6a9aa6; +} +.console-body .strip .fx-section.is-gain-view, +.console-body .strip .fx-section.is-sof-view{ + display:flex;flex-direction:column;min-height:0;overflow:hidden; + background:linear-gradient(180deg,#21343d,#172832); +} +.console-body .strip .gain-view-body{ + min-height:0;flex:1;display:flex;flex-direction:column; + justify-content:center;align-items:center;gap:2px;padding:2px 2px 4px; +} +.console-body .strip .gain-dial{ + position:relative;display:block;flex:0 0 39px;width:39px;height:39px; + border-radius:50%;cursor:ns-resize; +} +.console-body .strip .gain-dial-face{ + display:block;position:absolute;inset:2px;border:2px solid #5c747f; + border-radius:50%;background:radial-gradient(circle at 38% 31%,#617480,#273842 65%,#15242b); + box-shadow:inset 0 1px #9aafb844,0 2px 3px #0007; +} +.console-body .strip .gain-dial-face::after{ + content:"";position:absolute;left:50%;top:4px;width:2px;height:10px; + border-radius:2px;background:#d2ecf3;box-shadow:0 0 1px #fff8; + transform-origin:1px 12px;transform:translateX(-50%) rotate(var(--gain-rotation,0deg)); +} +.console-body .strip .gain-dial input{ + position:absolute;inset:0;width:100%;height:100%;margin:0;opacity:0; + cursor:ns-resize;writing-mode:vertical-lr;direction:rtl; +} +.console-body .strip .gain-dial:focus-within{outline:2px solid #7ebccf;outline-offset:1px} +.console-body .strip .gain-readout{ + display:block;text-align:center;font-size:10px;line-height:15px; + min-width:65px;max-width:100%;padding:0 4px;border-radius:2px; + background:#102530;border:1px solid #3c606e;color:#b9e8f3; + font-variant-numeric:tabular-nums;font-weight:500;white-space:nowrap; +} +.console-body .strip .sof-view-body{ + flex:1;display:flex;align-items:center;justify-content:space-between; + min-height:0;gap:4px;padding:4px 4px 5px; +} +.console-body .strip .sof-info{display:flex;flex-direction:column;min-width:0;gap:3px} +.console-body .strip .sof-badge{ + color:#c1e5ed;font-size:9px;font-weight:500;white-space:nowrap; + overflow:hidden;text-overflow:ellipsis; +} +.console-body .strip .sof-info small{ + font-size:9px;color:#91b3c0;max-width:100%;white-space:nowrap; + overflow:hidden;text-overflow:ellipsis; +} +.console-body.sends-mode .strip.audio .fader-head{ + background:#173844;border-bottom:1px solid #507481; +} +.console-body.sends-mode .strip.audio .fader-readout{color:#b3e6ef} +.console-body.sends-mode .strip.audio .fader:disabled{opacity:.42;cursor:not-allowed} +@media(max-width:900px){ + .command-bar .strip-view-switch .tool{padding:3px 5px;font-size:9px} + .mixer-title .mix-context{padding:2px 4px} +} +@media(max-height:610px){ + .console-body .strip .gain-dial{flex-basis:28px;width:28px;height:28px} + .console-body .strip .gain-dial-face::after{height:7px;transform-origin:1px 9px} + .console-body .strip .sof-info small{display:none} +} diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index 4df87e2ae..313b8f07a 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -42,6 +42,12 @@ + STRIP +
+ + +
+ @@ -76,7 +82,7 @@
-
Live Mixer10 audio tracks · 1 bus · master
+
Live MixerMAIN MIX10 audio tracks · 1 bus · master
', '
VISUAL PREVIEWNo browser audio
' ].join(""); @@ -107,7 +110,7 @@ function render(){ for(const c of [bg,dot]){c.setAttribute("cx",x.toFixed(2));c.setAttribute("cy",y.toFixed(2));} // Keep source captions readable, including directly behind the head. label.setAttribute("x",x.toFixed(2)); - label.setAttribute("y",(y<95?y+28:y-22).toFixed(2)); + label.setAttribute("y",(y+3.5).toFixed(2)); g.setAttribute("aria-valuenow",String(Math.round(deg>180?deg-360:deg))); } $("skMode").textContent=native()?(context()?"NATIVE HRTF":"NATIVE UNAVAILABLE"):"VISUAL ONLY · NO AUDIO"; diff --git a/tests/approved_native_sonku_smoke.py b/tests/approved_native_sonku_smoke.py index afe6f4910..0e65bd313 100644 --- a/tests/approved_native_sonku_smoke.py +++ b/tests/approved_native_sonku_smoke.py @@ -103,6 +103,7 @@ def exercise(browser,out,width,height): })"""), "Listener PNG did not load" labels=editor.locator("#skMap .sk-direction").all_inner_texts() assert labels==["REAR","FRONT","RIGHT","LEFT"],labels + assert editor.locator("#skListenerArt").get_attribute("pointer-events")=="none" assert editor.locator("#skMotion").inner_text()=="ORBIT" assert editor.locator("#skDirection").inner_text()=="CLOCKWISE" assert editor.locator("#skMode").inner_text()=="NATIVE HRTF" @@ -150,7 +151,30 @@ def pose(degrees): x,y=pose(90);assert x<90 and abs(y-165)<1,("RIGHT",x,y) x,y=pose(180);assert abs(x-200)<1 and y<60,("REAR",x,y) x,y=pose(-90);assert x>310 and abs(y-165)<1,("LEFT",x,y) - pose(0) + # Actual pointer drag uses physical stage coordinates: screen bottom + # means 0° FRONT, not a mirrored/right-facing listener. No simulated + # DSP authority: the browser must emit a native settings request. + pose(-90) + svg=editor.locator("#skMap").bounding_box() + assert svg + def screen(x,y): + return (svg["x"]+x*svg["width"]/400, + svg["y"]+y*svg["height"]/330) + sx,sy=screen(320,165) + ex,ey=screen(200,285) + page.mouse.move(sx,sy) + page.mouse.down() + page.mouse.move(ex,ey,steps=9) + page.mouse.up() + dragAction=last_action(page,"nativeSonKuSet") + assert dragAction["settings"]["moving"] is False + assert abs(dragAction["settings"]["startAzimuthDegrees"])<5,dragAction + # Never confuse successful pointer motion with audio-applied ACK. + emit(page,"arMixBuiltinSonKuAck",{ + "requestId":dragAction["requestId"],"status":"APPLIED"}) + accepted_snapshot(page,state,{**SETTINGS,"moving":False, + "stereoSpreadDegrees":0.0,"startAzimuthDegrees":0.0}, + applied=dragAction["requestId"]) bounds=editor.bounding_box() assert bounds and bounds["width"]>260 and bounds["width"] Date: Fri, 13 Nov 2026 07:38:11 +0700 Subject: [PATCH 040/140] test(sonku): read SVG direction labels as textContent and assert visual anchors --- tests/approved_native_sonku_smoke.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/approved_native_sonku_smoke.py b/tests/approved_native_sonku_smoke.py index 0e65bd313..5d267d635 100644 --- a/tests/approved_native_sonku_smoke.py +++ b/tests/approved_native_sonku_smoke.py @@ -101,8 +101,15 @@ def exercise(browser,out,width,height): image.onerror=()=>resolve(false); image.src='assets/sonku-listener-top.png'; })"""), "Listener PNG did not load" - labels=editor.locator("#skMap .sk-direction").all_inner_texts() - assert labels==["REAR","FRONT","RIGHT","LEFT"],labels + # SVG is not HTML text: Chromium 158 no longer exposes usable + # HTMLElement.innerText for these nodes. Read SVG textContent and verify + # the actual anchors, so front/rear cannot silently flip in the GUI. + direction=editor.locator("#skMap .sk-direction") + labels=direction.evaluate_all( + "(nodes)=>nodes.map(n=>({text:n.textContent.trim(),x:Number(n.getAttribute('x')),y:Number(n.getAttribute('y'))}))") + assert [x["text"] for x in labels]==["REAR","FRONT","RIGHT","LEFT"],labels + assert labels[0]["y"]<60 and labels[1]["y"]>290,labels + assert labels[2]["x"]<50 and labels[3]["x"]>300,labels assert editor.locator("#skListenerArt").get_attribute("pointer-events")=="none" assert editor.locator("#skMotion").inner_text()=="ORBIT" assert editor.locator("#skDirection").inner_text()=="CLOCKWISE" From e36397c3f8283dff1411a91a1c4c5a54f428f95f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 08:03:23 +0700 Subject: [PATCH 041/140] fix(gui): selected SOF target by stable strip ID, no ambiguous PRE bulk action --- site/preview-v2/index.html | 57 +++++++++++++++++++++++++------------- 1 file changed, 38 insertions(+), 19 deletions(-) diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index 8f9f50489..8f243c62c 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -208,7 +208,7 @@ }));}catch(error){/* Manager still works without browser storage. */} } const tracksEl=document.getElementById('tracks'),masterEl=document.getElementById('master'),info=document.getElementById('info'); -let nextId=1,nextGroup=1,tracks=[],master,preview=false,meterFrame=0,lastTick=0,clipboard=null,scenes=[],stripView="fx",sofEnabled=false,sofTarget="Bus A",wireSourceId=1,wireEdges=[],nextWireId=1,selectedWireEdgeId=null,wireMode='send',wireAnchorId=null,wireHoverId=null,wireGesture=null,wireSuppressClick=false,pendingBusRoute=null,wireView='focus',wireSourcePinned=false,wireIntent=false; +let nextId=1,nextGroup=1,tracks=[],master,preview=false,meterFrame=0,lastTick=0,clipboard=null,scenes=[],stripView="fx",sofEnabled=false,sofTarget="Bus A",sofTargetId=null,wireSourceId=1,wireEdges=[],nextWireId=1,selectedWireEdgeId=null,wireMode='send',wireAnchorId=null,wireHoverId=null,wireGesture=null,wireSuppressClick=false,pendingBusRoute=null,wireView='focus',wireSourcePinned=false,wireIntent=false; const clone=x=>JSON.parse(JSON.stringify(x)); const selection=()=>tracks.concat(master).filter(t=>t.selected); const make=(name,kind,color)=>{ @@ -343,8 +343,7 @@ /* SOF is a contextual UI view of an explicit existing EdgeId, not a new graph. */ function sectionSof(t){ // SOF is a view of ONE selected target WIRE, not a parallel audio graph. - const options=tracks.filter(x=>x.name===sofTarget&&(x.kind==='bus'||x.kind==='fx')); - const dest=options.length===1?options[0]:null; + const dest=selectedSofDestination(); const edge=dest?wireFor(t.id,dest.id):null; const send=edge&&edge.kind==='send'?edge:null; const native=!!window.__JUCE__?.backend; @@ -358,7 +357,7 @@ !send?'Not an independent SEND':'LEVEL '+wireDbText(send.levelDb); const editable=!!send&&(!native||t.nativeTapAvailable===true); const onEditable=!!send&&(!native||t.nativeSendAvailable===true); - const enabled=send?.sendEnabled!==false; + const enabled=!!send&&send.sendEnabled!==false; return '
'+ '
↗SEND TO '+escapeHtml(sofTarget||'—')+'
'+ '
'+badge+''+ @@ -762,19 +761,22 @@ // Four dedicated PNG frames avoid CSS-faked lighting: PRE, POST idle, POST // routed, MIX (several outgoing SEND edges with different tap positions). const tapVisual=nativeTapUnavailable?'idle': - parallelSends.length===0?(tapMode==='split'?'pre':'idle'): + parallelSends.length===0?'idle': tapMode==='mixed'?'mixed':tapMode==='split'?'pre':'post'; const tapText=tapVisual==='mixed'?'MIX':tapVisual==='pre'?'PRE':'POST'; + const tapTarget=parallelSends.find(edge=>edge.id===selectedWireEdgeId)|| + (parallelSends.length===1?parallelSends[0]:null); + const tapEditable=!nativeTapUnavailable&&(parallelSends.length===0||!!tapTarget); const tapTitle=nativeTapUnavailable?'PRE/POST unavailable until native WIRE tap ACK; routing unchanged': !parallelSends.length?'No parallel sends · '+(tapMode==='split'?'PRE':'POST')+ ' is only the future WIRE default; primary MAIN unchanged': - tapMode==='mixed'?'Mixed PRE and POST parallel WIRE sends · click to set all POST': + tapMode==='mixed'?'Mixed PRE and POST parallel WIRE sends · select one WIRE before editing': (tapMode==='send'?'POST follows channel fader':'PRE independent before FX')+ ' · '+parallelSends.length+' outgoing parallel SEND(s), primary MAIN unchanged'; code+='
' +'' +''; - if(t.kind!=='master'&&!sofEnabled)code+=''; + if(t.kind!=='master'&&!sofEnabled)code+=''; code+='
'; code+=sectionFader(t); code+='
'+(sofEnabled&&t.kind==='audio'?'S ': '')+formatDb(sofEnabled&&t.kind==='audio'?getSofLevel(t):t.level)+'
'; @@ -819,8 +821,8 @@ if(tracksEl.style?.setProperty)tracksEl.style.setProperty('--bank-columns',String(capacity)); // Release observers for detached bank DOM; never accumulate orphan lanes. meterObserver?.disconnect();meterGeometry=new WeakMap(); + updateSofTargets(); // Resolve selected EdgeId destination before painting strips. tracksEl.innerHTML=bankTracks.map(strip).join(''); - updateSofTargets(); const gainBtn=document.getElementById('gainView'),fxBtn=document.getElementById('fxView'); for(const [button,value] of [[gainBtn,'gain'],[fxBtn,'fx']]){ button.disabled=sofEnabled; @@ -866,23 +868,33 @@ btn.classList.toggle('active',compact);btn.setAttribute('aria-pressed',String(compact)); return density; } +function selectedSofDestination(){ + // A stable local display ID, never an audio-graph identity or a bus name. + // Native ChannelId stays a precise decimal string in the bridge. + return tracks.find(t=>t.id===sofTargetId&&(t.kind==='bus'||t.kind==='fx'))||null; +} function updateSofTargets(){ - const el=document.getElementById('sofTarget'),choices=tracks.filter(t=>t.kind==='bus'||t.kind==='fx').map(t=>t.name); - const target=choices.includes(sofTarget)?sofTarget:choices[0]||''; - sofTarget=target; - const html=choices.map(name=>'').join(''); - if(el.innerHTML!==html)el.innerHTML=html;el.value=sofTarget; + const el=document.getElementById('sofTarget'); + const choices=tracks.filter(t=>t.kind==='bus'||t.kind==='fx'); + let target=selectedSofDestination(); + if(!target){ + const named=choices.filter(t=>t.name===sofTarget); + target=named.length===1?named[0]:choices[0]||null; + } + sofTargetId=target?.id??null;sofTarget=target?.name||''; + const html=choices.map(t=>'').join(''); + if(el.innerHTML!==html)el.innerHTML=html; + el.value=target?String(target.id):''; } function getSofIndex(t){return t.sendSlots.findIndex((slot,i)=>(i===t.activeSend?t.send:slot.send)===sofTarget);} function getSofEdge(t){ - const options=tracks.filter(x=>x.name===sofTarget&&(x.kind==='bus'||x.kind==='fx')); - const dest=options.length===1?options[0]:null; + const dest=selectedSofDestination(); const edge=dest&&wireFor(t.id,dest.id); return edge&&edge.kind==='send'?edge:null; } function getSofLevel(t){const edge=getSofEdge(t);return edge?edge.levelDb:-60;} function setSofLevel(t,newLevel){ - const dest=tracks.find(x=>x.name===sofTarget&&x.id!==t.id); + const dest=selectedSofDestination(); if(!dest||t.kind==='master')return false; const level=Math.round(Math.max(-60,Math.min(6,newLevel))*10)/10; const edge=getSofEdge(t); @@ -892,7 +904,8 @@ } function toggleSof(force){ sofEnabled=typeof force==='boolean'?force:!sofEnabled; - if(sofEnabled&&!sofTarget){sofEnabled=false;say('Create a Bus or FX Return to use Sends on Faders');return;} + updateSofTargets(); + if(sofEnabled&&!selectedSofDestination()){sofEnabled=false;say('Create a Bus or FX Return to use Sends on Faders');return;} const btn=document.getElementById('sofToggle');btn.classList.toggle('active',sofEnabled); btn.setAttribute('aria-pressed',String(sofEnabled));document.querySelector('.console-body').classList.toggle('sends-mode',sofEnabled); render();say(sofEnabled?'SENDS ON FADERS: adjusting '+sofTarget+' send levels · main faders protected':'MAIN MIX: faders control primary channel level'); @@ -2651,7 +2664,13 @@ }); } document.getElementById('sofToggle').addEventListener('click',()=>toggleSof()); -document.getElementById('sofTarget').addEventListener('change',()=>{sofTarget=document.getElementById('sofTarget').value;render();say('Sends target: '+sofTarget);}); +document.getElementById('sofTarget').addEventListener('change',()=>{ + const id=Number(document.getElementById('sofTarget').value); + const target=tracks.find(t=>t.id===id&&(t.kind==='bus'||t.kind==='fx')); + if(!target){updateSofTargets();say('Invalid SEND target · selection unchanged');return;} + sofTargetId=target.id;sofTarget=target.name; + render();say('SEND MIX → '+sofTarget+' · MAIN faders protected'); +}); document.getElementById('addTrack').addEventListener('click',()=>{ const n=tracks.filter(t=>t.kind==='audio').length+1,t=make('Track '+n,'audio',COLORS[(n-1)%COLORS.length]);const firstBus=tracks.findIndex(x=>x.kind==='bus');tracks.splice(firstBus<0?tracks.length:firstBus,0,t); if(!wireGraphCommit([{type:'CONNECT',sourceId:t.id,destId:master.id}],{record:false})){tracks=tracks.filter(x=>x.id!==t.id);return;}revealTrack(t);say('Added '+t.name+' → MAIN · reference only'); @@ -2713,7 +2732,7 @@ if(x.send===old)x.send=name; x.sendSlots.forEach(slot=>{if(slot.send===old)slot.send=name;}); }); - if(sofTarget===old)sofTarget=name; + if(sofTargetId===t.id)sofTarget=name; closeChannelIdentity();render();say('Channel identity updated · '+name+' · routing references preserved'); } document.getElementById('identityClose').addEventListener('click',closeChannelIdentity); From f150aa0e55520d9d2282c521fe9f80ae5af9291d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 08:03:49 +0700 Subject: [PATCH 042/140] fix(native-ui): keep selected SOF destination bound to UI ID not mutable name --- web/approved-native-bridge.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 9b9ca7698..4669ac829 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -407,7 +407,7 @@ function selectedNativeSofEdge(t) { if(!scope?.sofEnabled||!t||t.kind!=="audio")return null; const current=controller?.state()?.current,source=nativeIdFor(t); - const matches=scope?.tracks?.filter(x=>x.name===scope.sofTarget&& + const matches=scope?.tracks?.filter(x=>x.id===scope.sofTargetId&& (x.kind==="bus"||x.kind==="fx"))||[]; if(!current?.admitted||!source||matches.length!==1)return null; const dest=nativeIdFor(matches[0]); @@ -635,7 +635,7 @@ const t=scope?.tracks?.find(x=>x.id===tId); if(t&&scope?.sofEnabled)scope.refreshStrip?.(t); } - if(scope?.sofEnabled && local.destId===scope?.tracks?.find(x=>x.name===scope.sofTarget)?.id){ + if(scope?.sofEnabled && local.destId===scope?.sofTargetId){ const t=scope?.tracks?.find(x=>x.id===tId); const slider=document.querySelector('.strip[data-id="'+tId+'"] input.fader'); if(t&&slider&&document.activeElement!==slider){ From 20715ea8a86945d38a64f1962e8751f9a57e4266 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 08:03:52 +0700 Subject: [PATCH 043/140] fix(native-ui): keep selected SOF destination bound to UI ID not mutable name --- scripts/build_approved_native_gui.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 3f07eb305..a7ce3583f 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -214,7 +214,7 @@ def accepted_pages_html() -> str: "window.__ARMIX_NATIVE_SCOPE__=Object.freeze({\n" " get tracks(){return tracks;},get master(){return master;},\n" " get wireEdges(){return wireEdges;}, // native read-only UI edge identity\n" - " get sofEnabled(){return sofEnabled;},get sofTarget(){return sofTarget;},toggleSof,\n" + " get sofEnabled(){return sofEnabled;},get sofTarget(){return sofTarget;},\n"\n " get sofTargetId(){return sofTargetId;},toggleSof,\n" " get selectedWireEdgeId(){return selectedWireEdgeId;},\n" " get wireGainDragging(){return !!sendKnobDrag;},paintWireKnob,\n" " syncNativeWireGains(rows){\n" From fa51fe2061a5c9ed157469e5e679819dccca95f2 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 08:04:43 +0700 Subject: [PATCH 044/140] feat(sonku): true depth-layered ellipse, dual speaker monitors at 0 spread, tactile rotary VST editor --- site/preview-v2/assets/mixer-fx-rack.css | 118 +++++++++++++ site/preview-v2/assets/mixer-native-sonku.js | 174 ++++++++++++++----- 2 files changed, 250 insertions(+), 42 deletions(-) diff --git a/site/preview-v2/assets/mixer-fx-rack.css b/site/preview-v2/assets/mixer-fx-rack.css index 953d263eb..999f30358 100644 --- a/site/preview-v2/assets/mixer-fx-rack.css +++ b/site/preview-v2/assets/mixer-fx-rack.css @@ -1228,3 +1228,121 @@ .mx-sonku .sk-stage .sk-source-label{fill:#e1faff;font-size:11px;font-weight:600;letter-spacing:0;pointer-events:none} .mx-sonku .sk-stage .sk-right .sk-source-label{fill:#ffe4f6} .mx-sonku .sk-stage .sk-front{fill:#81e0ed;font-weight:600} + +/* 8D-SonKu P1 studio hardware skin; component scoped, 18 CSS owners intact. + The far dashed rail is behind listener PNG; near elliptical rail is in front. + Source monitor separation is render-only; never changes native HRIR angles. */ +.mx-sonku{width:min(758px,calc(100vw - 28px));top:8%;background:#0f1d29; + border:1px solid #435b68;border-top-color:#708997;border-bottom-color:#253a45; + box-shadow:0 23px 54px rgba(0,0,0,.74),inset 0 1px rgba(233,251,255,.11); + font-family:Inter,"Segoe UI",Arial,sans-serif;font-size:11px;letter-spacing:.04px} +.mx-sonku .sk-head{background:linear-gradient(180deg,#2c4150,#152833); + border-bottom:1px solid #071721;box-shadow:inset 0 1px rgba(231,248,255,.15); + min-height:40px;padding:8px 14px} +.mx-sonku .sk-brand{font-weight:650;letter-spacing:.1px;font-size:15px; + text-shadow:0 1px 1px #000} +.mx-sonku .sk-headnote{letter-spacing:1.3px;color:#93b6c6;font-size:9px} +.mx-sonku .sk-content{grid-template-columns:minmax(0,1.48fr) minmax(220px,1fr); + gap:0;padding:0;align-items:stretch} +.mx-sonku .sk-stage{padding:11px 10px 6px 12px; + background:linear-gradient(155deg,#162936,#0c1b28); + border-right:1px solid #395565} +.mx-sonku .sk-stage svg{border:1px solid #3f5f70;border-top-color:#233f4f; + border-radius:7px;box-shadow:inset 0 2px 8px #010c15;aspect-ratio:400/330} +.mx-sonku .sk-stage text{paint-order:stroke fill} +.mx-sonku .sk-orbit-rear{stroke-linecap:round} +.mx-sonku .sk-orbit-front{stroke-linecap:round;filter:drop-shadow(0 0 3px rgba(104,202,224,.27))} +.mx-sonku .sk-listener-art{pointer-events:none;opacity:.97; + filter:drop-shadow(0 5px 9px rgba(37,183,230,.17))} +.mx-sonku .sk-stage .sk-direction{font-size:9px;letter-spacing:1.25px;fill:#98bcc9; + font-weight:550} +.mx-sonku .sk-stage .sk-front{fill:#81e6ee;font-size:10px} +.mx-sonku .sk-src{cursor:grab;touch-action:none;outline:none; + filter:drop-shadow(0 2px 4px rgba(0,0,0,.62))} +.mx-sonku .sk-src:active{cursor:grabbing} +.mx-sonku .sk-speaker-shell{fill:#203745;stroke:#7cbdcc;stroke-width:1.4} +.mx-sonku .sk-speaker-inner{fill:#0c202c;stroke:#325665;stroke-width:.8} +.mx-sonku .sk-speaker-tweeter{fill:#8bcbd7;stroke:#365c6b;stroke-width:1} +.mx-sonku .sk-speaker-woofer{fill:#355f70;stroke:#91cfda;stroke-width:1.15} +.mx-sonku .sk-speaker-cone{fill:#162e3a;stroke:#78acba;stroke-width:.9} +.mx-sonku .sk-right .sk-speaker-shell{stroke:#e3accf;fill:#4a3545} +.mx-sonku .sk-right .sk-speaker-inner{fill:#251e2b;stroke:#7a526d} +.mx-sonku .sk-right .sk-speaker-tweeter{fill:#edc5df;stroke:#885d7b} +.mx-sonku .sk-right .sk-speaker-woofer{fill:#8b5d7c;stroke:#e8b6d5} +.mx-sonku .sk-right .sk-speaker-cone{fill:#3c293e;stroke:#d3a5c4} +.mx-sonku .sk-stage .sk-speaker-label{fill:#e9fbff;font-size:12px; + font-weight:650;letter-spacing:.5px;pointer-events:none; + stroke:rgba(3,20,30,.8);stroke-width:2.1px} +.mx-sonku .sk-right .sk-speaker-label{fill:#ffe7f8} +.mx-sonku .sk-src:focus-visible .sk-speaker-shell{stroke-width:2.8} +.mx-sonku .sk-tether{pointer-events:none} +.mx-sonku .sk-stage-caption{font-size:8px;letter-spacing:.9px;margin:5px 0 1px;color:#86aebc} +.mx-sonku .sk-controls{padding:13px 14px 9px;gap:9px; + background:linear-gradient(135deg,#233542 0,#182b38 22%,#142430 85%,#10212d 100%); + box-shadow:inset 1px 0 rgba(255,255,255,.07)} +.mx-sonku .sk-control-title{display:flex;align-items:center;justify-content:space-between; + font-size:10px;letter-spacing:1.4px;font-weight:600;color:#bedbe5;padding:2px 0} +.mx-sonku .sk-engine-led{display:inline-flex;align-items:center;gap:5px; + font-size:8px;letter-spacing:.65px;color:#83acb7;font-weight:500} +.mx-sonku .sk-engine-led::before{content:"";width:5px;height:5px;border-radius:50%; + background:#72d6ce;box-shadow:0 0 6px #65ceb8} +.mx-sonku .sk-buttons{gap:7px} +.mx-sonku .sk-buttons button{min-height:31px;padding:6px 4px;font-weight:600; + letter-spacing:.75px;font-size:9px;color:#b6d1dd; + border:1px solid #425e6f;border-top-color:#6d8b98;border-bottom-color:#223c4b; + background:linear-gradient(#304a59,#1d3342); + box-shadow:inset 0 1px rgba(255,255,255,.11),0 2px 3px rgba(0,0,0,.35)} +.mx-sonku .sk-buttons button[aria-pressed="true"]{ + background:linear-gradient(#2c6a7b,#19485b);border-color:#73baca; + color:#e5fbff;box-shadow:inset 0 1px rgba(255,255,255,.2),0 0 6px rgba(75,193,219,.17)} +.mx-sonku .sk-rotary-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr)); + row-gap:9px;column-gap:9px;align-items:center;justify-items:center; + flex:1;min-height:240px} +.mx-sonku .sk-rotary{display:flex!important;flex-direction:column;align-items:center; + justify-content:center;gap:4px;min-width:0;width:100%; + padding:5px 1px!important;border:0;letter-spacing:.7px} +.mx-sonku .sk-param-name{font-size:9px;color:#b9d3df; + letter-spacing:.8px;font-weight:600;white-space:nowrap;text-align:center} +.mx-sonku .sk-dial{--sk-sweep:135deg;--sk-needle:0deg; + display:block;position:relative;width:62px;height:62px;flex:none; + cursor:ns-resize;touch-action:none;user-select:none;outline:none} +.mx-sonku .sk-dial-track{position:absolute;inset:0;border-radius:50%; + background:conic-gradient(from 225deg,#65cadd 0deg,#65cadd var(--sk-sweep), + #344d5d var(--sk-sweep),#344d5d 270deg,transparent 270deg 360deg); + mask:radial-gradient(circle,transparent 0 53%,black 55% 62%,transparent 64%); + filter:drop-shadow(0 0 2px rgba(95,199,221,.27))} +.mx-sonku .sk-dial-cap{position:absolute;inset:9px;border-radius:50%; + border:1px solid #758a94;border-bottom-color:#142530;border-right-color:#263f4b; + background:radial-gradient(circle at 38% 28%,#5e7481 0%,#3c5462 24%,#233d4b 55%,#142b39 84%); + box-shadow:0 3px 6px #081521,inset 0 1px 2px rgba(240,251,255,.4), + inset 0 -3px 7px rgba(0,0,0,.35);pointer-events:none} +.mx-sonku .sk-dial-needle{position:absolute;inset:0;transform:rotate(var(--sk-needle)); + transition:transform 60ms linear;pointer-events:none} +.mx-sonku .sk-dial-needle::before{content:"";display:block;position:absolute; + width:3px;height:10px;left:calc(50% - 1.5px);top:3px;border-radius:2px; + background:#d6faff;box-shadow:0 0 3px rgba(155,241,255,.56)} +.mx-sonku .sk-controls .sk-rotary .sk-dial input{ + position:absolute;inset:0;width:100%;height:100%;margin:0!important;grid-column:auto; + opacity:0;cursor:ns-resize;pointer-events:none;accent-color:transparent} +.mx-sonku .sk-rotary:focus-within .sk-dial-cap{outline:1px solid #87d5e6;outline-offset:2px} +.mx-sonku .sk-rotary output{font-size:11px;font-weight:600;letter-spacing:.2px; + font-variant-numeric:tabular-nums;color:#dcf3f7} +.mx-sonku .sk-guide{font-size:9px;line-height:1.42;color:#91b2c2; + border-top:1px solid rgba(113,157,173,.24);padding-top:9px;letter-spacing:.1px} +.mx-sonku .sk-status{background:linear-gradient(#142836,#0c1a27); + border-top:1px solid #415d6d;padding:7px 13px;letter-spacing:.55px; + color:#99bac8} +@media(max-width:550px){ + .mx-sonku{top:8px;max-height:calc(100vh - 16px)} + .mx-sonku .sk-content{grid-template-columns:1fr} + .mx-sonku .sk-stage{border-right:0;border-bottom:1px solid #344d5d} + .mx-sonku .sk-stage svg{max-height:37vh} + .mx-sonku .sk-controls{gap:8px} + .mx-sonku .sk-rotary-grid{grid-template-columns:repeat(4,minmax(0,1fr)); + row-gap:0;min-height:auto;gap:1px} + .mx-sonku .sk-dial{width:48px;height:48px} + .mx-sonku .sk-dial-cap{inset:8px} + .mx-sonku .sk-param-name{font-size:8px} + .mx-sonku .sk-rotary{padding:3px 0!important} + .mx-sonku .sk-guide{font-size:9px} +} diff --git a/site/preview-v2/assets/mixer-native-sonku.js b/site/preview-v2/assets/mixer-native-sonku.js index e7afb90b3..e5f4508a8 100644 --- a/site/preview-v2/assets/mixer-native-sonku.js +++ b/site/preview-v2/assets/mixer-native-sonku.js @@ -20,12 +20,34 @@ const angle=(v)=>((v%360)+360)%360; // Listener faces the BOTTOM of this top-down stage. // Acoustic coordinates stay fixed: FRONT=0°, RIGHT=+90°, REAR=180°, // LEFT=-90°. When facing down, anatomical RIGHT appears screen-left. -const stagePoint=(azimuthDegrees,radius=120)=>{ +// Perspective projection is presentation-only. Never remap the HRTF azimuth: +// 0° FRONT (screen bottom), +90° listener RIGHT (screen left). +// All emitters lie on one physically plausible horizontal ellipse; + // its rear half is occluded by the head and near half overlays the bust. +const STAGE=Object.freeze({x:200,y:174,rx:148,ry:83}); +const stagePoint=(azimuthDegrees)=>{ const rad=angle(azimuthDegrees)*Math.PI/180; - return {x:200-radius*Math.sin(rad),y:165+radius*Math.cos(rad)}; + return {x:STAGE.x-STAGE.rx*Math.sin(rad), + y:STAGE.y+STAGE.ry*Math.cos(rad)}; }; const stageAzimuth=(screenX,screenY)=> - Math.atan2(200-screenX,screenY-165)*180/Math.PI; + Math.atan2((STAGE.x-screenX)/STAGE.rx, + (screenY-STAGE.y)/STAGE.ry)*180/Math.PI; +// At SPREAD=0 the two actual HRIR directions coincide. Separate the +// drawings (not their acoustic coordinates) tangentially, with tiny tethers +// identifying the shared acoustic point. L and R remain independently draggable. +const displayPair=(azimuths)=>{ + const anchors=azimuths.map(stagePoint); + const distance=Math.hypot(anchors[0].x-anchors[1].x,anchors[0].y-anchors[1].y); + const mid=(azimuths[0]+azimuths[1])*0.5*Math.PI/180; + const tangent={x:STAGE.rx*Math.cos(mid),y:STAGE.ry*Math.sin(mid)}; + const n=Math.hypot(tangent.x,tangent.y)||1; + const offset=Math.max(0,(46-distance)*0.5); + return anchors.map((anchor,i)=>({ + anchor,visible:{x:anchor.x+(i===0?1:-1)*offset*tangent.x/n, + y:anchor.y+(i===0?1:-1)*offset*tangent.y/n} + })); +}; const root=document.createElement("section"); root.id="mxNativeSonKu";root.className="mx-sonku";root.hidden=true; root.setAttribute("role","dialog");root.setAttribute("aria-modal","false"); @@ -37,36 +59,52 @@ root.innerHTML=[ '', '
', '', - '', - '', - '', - '', - '', - '', - '', - '', - 'REAR', - 'FRONT', - 'RIGHTLEFT', - '', - // Measured top-down blue bust PNG. The visible face points toward bottom FRONT. - // SVG image stays passive and cannot steal pointer capture from source dots. - '', - '', + '', + '', + '', + '', + '', + '', + // Far orbit belongs BEHIND the listener; true perspective elliptical rail. + '', + '', + 'REAR', + 'FRONT', + 'RIGHTLEFT', + // Image stays a single 128px transparent original: never canvas-generated DSP. + '', + '', + // Near orbit overlays lower bust, forming ONE plausible 3D spatial ring. + '', + '', + '', + // No circle markers: each emitter is a small raised studio monitor. + // Offsets at coincident directions are display-only; native azimuth stays equal. '', - '', - 'L', + '', + '', + '', + '', + '', + '', + 'L', '', - '', - 'R', + '', + '', + '', + '', + '', + '', + 'R', '
HEADPHONES · HRIR 0° ELEVATION · 44.1 / 48 kHz
', - '
', '
VISUAL PREVIEWNo browser audio
' ].join(""); @@ -74,7 +112,7 @@ const $=id=>root.querySelector("#"+id); const mount=()=>{if(!root.isConnected)document.body.append(root)}; if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",mount,{once:true});else mount(); let current=null,accepted=defaults(),draft=defaults(),pending=null,latest=null, - readId="",readSentAt=0,seq=1,clock=null,observed=0,observedAt=0,drag=null; + readId="",readSentAt=0,seq=1,clock=null,observed=0,observedAt=0,drag=null,dialDrag=null; const context=()=>{ if(!current||!native())return null; const s=snapshot(),id=window.__ARMIX_NATIVE_M2__?.nativeIdFor?.(current.track); @@ -96,22 +134,37 @@ function render(){ ["skSpread",s.stereoSpreadDegrees,"skSpreadValue",Math.round(s.stereoSpreadDegrees)+"°"], ["skMix",s.spatialMix*100,"skMixValue",Math.round(s.spatialMix*100)+"%"], ["skTrim",s.outputTrim*100,"skTrimValue",Math.round(s.outputTrim*100)+"%"]]; - for(const [input,value,out,label] of vals){$(input).value=String(value);$(out).textContent=label;} + for(const [input,value,out,label] of vals){ + const el=$(input);el.value=String(value);$(out).textContent=label; + const min=Number(el.min),max=Number(el.max); + const p=Math.max(0,Math.min(1,(value-min)/(max-min))); + const dial=el.closest(".sk-dial"); + dial.style.setProperty("--sk-sweep",(p*270).toFixed(2)+"deg"); + dial.style.setProperty("--sk-needle",(-135+p*270).toFixed(2)+"deg"); + } const liveMotion=s.moving&¤t&&!pending?observed: s.startAzimuthDegrees; const phase=native()&&s.moving&¤t&&!pending&&observedAt? liveMotion+(performance.now()-observedAt)*.001* (s.clockwise?1:-1)*360/s.revolutionSeconds:liveMotion; - for(let source=0;source<2;++source){ - const deg=angle(phase+(source?1:-1)*s.stereoSpreadDegrees/2); - const {x,y}=stagePoint(deg); + const angles=[phase-s.stereoSpreadDegrees/2,phase+s.stereoSpreadDegrees/2]; + const pair=displayPair(angles); + for(let source=0;source<2;++source) { + const deg=angle(angles[source]); + const {anchor,visible}=pair[source]; const g=root.querySelector('.sk-src[data-index="'+source+'"]'); - const bg=g.querySelector(".sk-source-bg"),dot=g.querySelector(".sk-source-core"),label=g.querySelector(".sk-source-label"); - for(const c of [bg,dot]){c.setAttribute("cx",x.toFixed(2));c.setAttribute("cy",y.toFixed(2));} - // Keep source captions readable, including directly behind the head. - label.setAttribute("x",x.toFixed(2)); - label.setAttribute("y",(y+3.5).toFixed(2)); + g.setAttribute("transform","translate("+visible.x.toFixed(2)+","+visible.y.toFixed(2)+")"); + g.dataset.acousticX=anchor.x.toFixed(2); + g.dataset.acousticY=anchor.y.toFixed(2); + g.dataset.visualX=visible.x.toFixed(2); + g.dataset.visualY=visible.y.toFixed(2); + const deltaX=anchor.x-visible.x,deltaY=anchor.y-visible.y; + const leader=g.querySelector(".sk-tether"); + leader.setAttribute("d","M0 0 L"+deltaX.toFixed(2)+" "+deltaY.toFixed(2)); + leader.style.opacity=Math.hypot(deltaX,deltaY)>4?".65":"0"; g.setAttribute("aria-valuenow",String(Math.round(deg>180?deg-360:deg))); + const direction=deg<45||deg>=315?"FRONT":deg<135?"RIGHT":deg<225?"REAR":"LEFT"; + g.setAttribute("aria-valuetext",direction+" "+Math.round(deg)+"°"); } $("skMode").textContent=native()?(context()?"NATIVE HRTF":"NATIVE UNAVAILABLE"):"VISUAL ONLY · NO AUDIO"; } @@ -163,7 +216,7 @@ backend()?.addEventListener?.("arMixBuiltinSonKuSnapshot",r=>{ return; } accepted={...r.settings};pending=null;hint("DSP APPLIED · ACCEPTED");flushLatest(); - }else if(!drag){ + }else if(!drag&&!dialDrag){ accepted={...r.settings};draft={...r.settings}; } if(Number.isFinite(r.observedAzimuthDegrees)){ @@ -172,7 +225,7 @@ backend()?.addEventListener?.("arMixBuiltinSonKuSnapshot",r=>{ render(); }); $("skClose").addEventListener("click",()=>{root.hidden=true;current=null; - pending=null;latest=null;readId="";readSentAt=0; + pending=null;latest=null;readId="";readSentAt=0;dialDrag=null; if(clock!==null){clearInterval(clock);clock=null;}}); $("skMotion").addEventListener("click",()=>send({...draft,moving:!draft.moving})); $("skDirection").addEventListener("click",()=>send({...draft,clockwise:!draft.clockwise})); @@ -186,6 +239,43 @@ for(const [id,key,convert] of [ if(!Number.isFinite(v))return;draft={...draft,[key]:convert(v)};render();}); input.addEventListener("change",()=>send({...draft,[key]:convert(Number(input.value))})); } +// Control-surface tactile dials. Retain native as the +// accessible focus/keyboard source; direct pointer motion is vertical and +// commits exactly once on release (never streams speculative host DSP values). +for(const [id,initial] of [["skSpeed",12],["skSpread",60],["skMix",100],["skTrim",75]]){ + const input=$(id),dial=input.closest(".sk-dial"); + const min=Number(input.min),max=Number(input.max),step=Number(input.step)||1; + dial.addEventListener("pointerdown",e=>{ + if(e.button!==0)return; + e.preventDefault();input.focus({preventScroll:true}); + dialDrag={id,pointer:e.pointerId,startY:e.clientY,origin:Number(input.value),moved:false}; + dial.setPointerCapture(e.pointerId); + }); + dial.addEventListener("pointermove",e=>{ + if(!dialDrag||dialDrag.id!==id||dialDrag.pointer!==e.pointerId)return; + const delta=dialDrag.startY-e.clientY; + if(Math.abs(delta)>2)dialDrag.moved=true; + if(!dialDrag.moved)return; + const raw=dialDrag.origin+delta*(max-min)/135; + const bounded=Math.min(max,Math.max(min,raw)); + const next=Math.min(max,Math.max(min,min+Math.round((bounded-min)/step)*step)); + if(Number(input.value)!==next){input.value=String(next);input.dispatchEvent(new Event("input",{bubbles:true}));} + }); + const finish=e=>{ + if(!dialDrag||dialDrag.id!==id||dialDrag.pointer!==e.pointerId)return; + const moved=dialDrag.moved; + dialDrag=null; + if(dial.hasPointerCapture(e.pointerId))dial.releasePointerCapture(e.pointerId); + if(moved)input.dispatchEvent(new Event("change",{bubbles:true})); + }; + dial.addEventListener("pointerup",finish); + dial.addEventListener("pointercancel",e=>{if(dialDrag?.id===id)dialDrag=null;}); + dial.addEventListener("dblclick",e=>{ + e.preventDefault();input.value=String(initial); + input.dispatchEvent(new Event("input",{bubbles:true})); + input.dispatchEvent(new Event("change",{bubbles:true})); + }); +} const map=$("skMap"); function toAzimuth(e) { const rect=map.getBoundingClientRect(); @@ -225,7 +315,7 @@ const api={ id:ID, insert(target){return Boolean(window.__ARMIX_NATIVE_M2__?.insertPlugin?.(ID,target));}, open(track,slot){ - pending=null;latest=null;readId="";readSentAt=0; + pending=null;latest=null;readId="";readSentAt=0;dialDrag=null; observedAt=0;accepted=defaults();draft=defaults(); current={track,slot,instanceId:null}; const s=snapshot(),id=window.__ARMIX_NATIVE_M2__?.nativeIdFor?.(track); From 3fbce7c6d39183b7cc91619d663be3580f8de04a Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 08:05:23 +0700 Subject: [PATCH 045/140] refine(gui): PRE edits one selected send; show saved-off level and honest no-send state --- site/preview-v2/index.html | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index 8f243c62c..6f24b1906 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -335,7 +335,7 @@ const nativeUnavailable=!!window.__JUCE__?.backend&&!t.nativeGainAvailable; return '
'+ 'GINPUT GAIN
'+ - '
'; @@ -353,8 +353,10 @@ const visual=!send?'idle':tap==='preFader'||tap==='preFx'?'pre':'post'; const badge=!edge?'NO SEND':edge.kind!=='send'?'PRIMARY OUT': tap==='preFader'?'PRE-FADER':tap==='preFx'?'PRE-FX':'POST-FADER'; - const status=!dest?'Select one unique BUS/FX':!edge?'Patch with WIRE': - !send?'Not an independent SEND':'LEVEL '+wireDbText(send.levelDb); + const status=!dest?'Select a BUS/FX':!edge?'Patch with WIRE': + !send?'PRIMARY ROUTE · no send level': + send.sendEnabled===false?'OFF · saved '+wireDbText(send.levelDb): + 'LEVEL '+wireDbText(send.levelDb); const editable=!!send&&(!native||t.nativeTapAvailable===true); const onEditable=!!send&&(!native||t.nativeSendAvailable===true); const enabled=!!send&&send.sendEnabled!==false; @@ -755,7 +757,10 @@ const parallelSends=wireEdges.filter(e=>e.enabled&&e.sourceId===t.id&&e.kind==='send'&&e.destId!==master.id); const allSendPost=parallelSends.length>0&¶llelSends.every(e=>e.mode==='send'); const allSendPre=parallelSends.length>0&¶llelSends.every(e=>e.mode==='split'); - const tapMode=allSendPost?'send':allSendPre?'split':parallelSends.length?'mixed':t.wireTapMode==='split'?'split':'send'; + const tapTarget=parallelSends.find(edge=>edge.id===selectedWireEdgeId)|| + (parallelSends.length===1?parallelSends[0]:null); + const tapMode=tapTarget?tapTarget.mode:allSendPost?'send':allSendPre?'split': + parallelSends.length?'mixed':'idle'; const nativeTapUnavailable=!!window.__JUCE__?.backend&&!t.nativeTapAvailable; // An unpatched channel has a future WIRE default, not an illuminated send. // Four dedicated PNG frames avoid CSS-faked lighting: PRE, POST idle, POST @@ -764,15 +769,12 @@ parallelSends.length===0?'idle': tapMode==='mixed'?'mixed':tapMode==='split'?'pre':'post'; const tapText=tapVisual==='mixed'?'MIX':tapVisual==='pre'?'PRE':'POST'; - const tapTarget=parallelSends.find(edge=>edge.id===selectedWireEdgeId)|| - (parallelSends.length===1?parallelSends[0]:null); - const tapEditable=!nativeTapUnavailable&&(parallelSends.length===0||!!tapTarget); + const tapEditable=!nativeTapUnavailable&&!!tapTarget; const tapTitle=nativeTapUnavailable?'PRE/POST unavailable until native WIRE tap ACK; routing unchanged': - !parallelSends.length?'No parallel sends · '+(tapMode==='split'?'PRE':'POST')+ - ' is only the future WIRE default; primary MAIN unchanged': + !parallelSends.length?'NO SEND · connect and select an independent WIRE first': tapMode==='mixed'?'Mixed PRE and POST parallel WIRE sends · select one WIRE before editing': (tapMode==='send'?'POST follows channel fader':'PRE independent before FX')+ - ' · '+parallelSends.length+' outgoing parallel SEND(s), primary MAIN unchanged'; + ' · selected EdgeId '+(tapTarget?.id||'none')+' of '+parallelSends.length+' parallel SEND(s)'; code+='
' +'' +''; @@ -2150,14 +2152,13 @@ // MIX status is not permission to rewrite all parallel connections. const selected=sends.find(edge=>edge.id===selectedWireEdgeId)||(sends.length===1?sends[0]:null); if(sends.length>1&&!selected){say('Select a specific WIRE before changing its tap');return;} - const next=selected?(selected.mode==='send'?'split':'send'):(t.wireTapMode==='split'?'send':'split'); - if(selected&&!wireGraphCommit([{type:'MODE',sourceId:t.id,edgeId:selected.id,mode:next}]))return; - t.wireTapMode=next; - if(wireSourceId===t.id){wireMode=next;document.getElementById('wireMode').value=next;} + if(!selected){say('NO SEND · patch and select one WIRE before changing its tap');return;} + const next=selected.mode==='send'?'split':'send'; + if(!wireGraphCommit([{type:'MODE',sourceId:t.id,edgeId:selected.id,mode:next}]))return; refreshStrip(t);selectTrack(t); - say(t.name+' '+(next==='split'?'PRE (independent pre-FX)':'POST (follow fader)')+ - ' · outgoing parallel WIRE sends '+(sends.length?'updated':'default selected')+ - ' · primary MAIN unchanged · GUI reference only'); + say(t.name+' → '+(tracks.find(x=>x.id===selected.destId)?.name||'BUS')+ + ' '+(next==='split'?'PRE-FX':'POST-FADER')+ + ' · one EdgeId only · primary MAIN unchanged · GUI reference'); return; } if(a==='eq')t.eq=!t.eq; From 4652a744ab4ae01b1ceca58bb6c3d7e372eb420a Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 08:06:19 +0700 Subject: [PATCH 046/140] test(sonku): prove ellipse occlusion, two visible speakers at zero spread and rotary DSP edit --- tests/approved_native_sonku_smoke.py | 79 ++++++++++++++++++++++------ 1 file changed, 63 insertions(+), 16 deletions(-) diff --git a/tests/approved_native_sonku_smoke.py b/tests/approved_native_sonku_smoke.py index 5d267d635..c70c0592e 100644 --- a/tests/approved_native_sonku_smoke.py +++ b/tests/approved_native_sonku_smoke.py @@ -92,6 +92,24 @@ def exercise(browser,out,width,height): editor=page.locator("#mxNativeSonKu") editor.wait_for(state="visible",timeout=5000) assert editor.locator("#skMap .sk-src").count()==2 + assert editor.locator("#skMap .sk-speaker-shell").count()==2 + assert editor.locator("#skMap #skRearArc").count()==1 + assert editor.locator("#skMap #skFrontArc").count()==1 + # Painter's ordering is 3D: far rail -> head PNG -> near rail. + assert page.evaluate("""() => { + const map=document.querySelector('#skMap'); + const rear=map.querySelector('#skRearArc'); + const art=map.querySelector('#skListenerArt'); + const front=map.querySelector('#skFrontArc'); + return Boolean((rear.compareDocumentPosition(art) & Node.DOCUMENT_POSITION_FOLLOWING) && + (art.compareDocumentPosition(front) & Node.DOCUMENT_POSITION_FOLLOWING)); + }"""), "Front/back ring painter layering incorrect" + # Every rotation input remains an accessible native range, wrapped in + # a tactile rotary shell: no browser PCM, no fake processed state. + assert editor.locator(".sk-rotary-grid .sk-dial").count()==4 + for knob in ("skSpeed","skSpread","skMix","skTrim"): + assert editor.locator("#"+knob).get_attribute("type")=="range" + assert editor.locator("#"+knob).evaluate("(n)=>n.closest('.sk-dial')!==null") art=editor.locator("#skListenerArt") assert art.count()==1 and art.get_attribute("href")=="assets/sonku-listener-top.png" # Image is actually available inside the assembled native GUI bundle. @@ -150,38 +168,67 @@ def pose(degrees): settings={**SETTINGS,"moving":False,"stereoSpreadDegrees":0.0, "startAzimuthDegrees":float(degrees)} accepted_snapshot(page,state,settings) - return ( - float(editor.locator('.sk-src[data-index="0"] .sk-source-bg').get_attribute("cx")), - float(editor.locator('.sk-src[data-index="0"] .sk-source-bg').get_attribute("cy")) - ) - x,y=pose(0);assert abs(x-200)<1 and y>270,("FRONT",x,y) - x,y=pose(90);assert x<90 and abs(y-165)<1,("RIGHT",x,y) - x,y=pose(180);assert abs(x-200)<1 and y<60,("REAR",x,y) - x,y=pose(-90);assert x>310 and abs(y-165)<1,("LEFT",x,y) - # Actual pointer drag uses physical stage coordinates: screen bottom - # means 0° FRONT, not a mirrored/right-facing listener. No simulated - # DSP authority: the browser must emit a native settings request. - pose(-90) + # Acoustic anchor is distinct from the readable icon's display offset. + # The offset NEVER alters native azimuth when both sources coincide. + nodes=editor.locator('#skMap .sk-src') + data=nodes.evaluate_all("""els=>els.map(n=>({ + ax:Number(n.dataset.acousticX),ay:Number(n.dataset.acousticY), + vx:Number(n.dataset.visualX),vy:Number(n.dataset.visualY), + value:Number(n.getAttribute('aria-valuenow'))}))""") + assert len(data)==2 and data[0]["value"]==data[1]["value"]==degrees,data + assert abs(data[0]["ax"]-data[1]["ax"])<.01,data + assert abs(data[0]["ay"]-data[1]["ay"])<.01,data + separation=((data[0]["vx"]-data[1]["vx"])**2+ + (data[0]["vy"]-data[1]["vy"])**2)**.5 + assert separation>=44,("Two studio speakers overlap at zero spread",data) + return data[0]["ax"],data[0]["ay"] + x,y=pose(0);assert abs(x-200)<1 and y>245,("FRONT",x,y) + x,y=pose(90);assert x<60 and abs(y-174)<1,("RIGHT",x,y) + x,y=pose(180);assert abs(x-200)<1 and y<100,("REAR",x,y) + x,y=pose(-90);assert x>335 and abs(y-174)<1,("LEFT",x,y) + # Actual pointer drag is taken from the VISIBLE L speaker at -90, + # toward the physical near-ellipse FRONT, not the hidden anchor. svg=editor.locator("#skMap").bounding_box() assert svg def screen(x,y): return (svg["x"]+x*svg["width"]/400, svg["y"]+y*svg["height"]/330) - sx,sy=screen(320,165) - ex,ey=screen(200,285) + source=editor.locator('.sk-src[data-index="0"]') + sx,sy=screen(float(source.get_attribute("data-visual-x")), + float(source.get_attribute("data-visual-y"))) + ex,ey=screen(200,257) page.mouse.move(sx,sy) page.mouse.down() - page.mouse.move(ex,ey,steps=9) + page.mouse.move(ex,ey,steps=10) page.mouse.up() dragAction=last_action(page,"nativeSonKuSet") assert dragAction["settings"]["moving"] is False assert abs(dragAction["settings"]["startAzimuthDegrees"])<5,dragAction - # Never confuse successful pointer motion with audio-applied ACK. emit(page,"arMixBuiltinSonKuAck",{ "requestId":dragAction["requestId"],"status":"APPLIED"}) accepted_snapshot(page,state,{**SETTINGS,"moving":False, "stereoSpreadDegrees":0.0,"startAzimuthDegrees":0.0}, applied=dragAction["requestId"]) + # Vertical knob drag must update one typed value and commit once on + # pointer release. Pure browser drawing cannot claim DSP APPLIED. + knob=editor.locator("#skSpeed").locator("..") + box=knob.bounding_box();assert box + x=box["x"]+box["width"]*.5;y=box["y"]+box["height"]*.5 + before=page.evaluate( + "()=>window.__actions.filter(a=>a.action==='nativeSonKuSet').length") + page.mouse.move(x,y);page.mouse.down() + page.mouse.move(x,y-17,steps=6);page.mouse.up() + newactions=page.evaluate( + "()=>window.__actions.filter(a=>a.action==='nativeSonKuSet')") + assert len(newactions)==before+1,("Rotary did not commit once",newactions) + dialAction=newactions[-1] + assert dialAction["settings"]["revolutionSeconds"]>12,dialAction + emit(page,"arMixBuiltinSonKuAck",{ + "requestId":dialAction["requestId"],"status":"APPLIED"}) + accepted_snapshot(page,state,{**SETTINGS,"moving":False, + "stereoSpreadDegrees":0.0,"startAzimuthDegrees":0.0, + "revolutionSeconds":dialAction["settings"]["revolutionSeconds"]}, + applied=dialAction["requestId"]) bounds=editor.bounding_box() assert bounds and bounds["width"]>260 and bounds["width"] Date: Fri, 13 Nov 2026 08:06:25 +0700 Subject: [PATCH 047/140] test(ui): SOF target stays on exact BUS ID across rename and view switch --- tests/sof_contextual_console_smoke.py | 28 ++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/tests/sof_contextual_console_smoke.py b/tests/sof_contextual_console_smoke.py index a50a0417f..2728c9036 100644 --- a/tests/sof_contextual_console_smoke.py +++ b/tests/sof_contextual_console_smoke.py @@ -88,12 +88,38 @@ def run() -> None: assert "harmonice-thin-flat-v9-approved-off-shadow-57x30.png" in sprite, sprite assert tap.is_disabled() - # Keep FX slots/trim values when returning from SENDS. + # SOF target is a stable strip ID, never a BUS display name. + target_select = page.locator("#sofTarget") + initial_id = target_select.input_value() + assert initial_id.isdigit(), (width, initial_id) + expected_name = target_select.locator("option:checked").inner_text() + assert page.locator("#mixContext").inner_text() == "SEND MIX → " + expected_name + assert first.locator(".mx-sof-on-key").get_attribute("aria-pressed") == "false", ( + "An absent SEND is not secretly ON") + + # Returning to MAIN must keep FX/GAIN selection and actual fader mix. page.locator("#sofToggle").click() assert page.locator("#mixContext").inner_text() == "MAIN MIX" gain.click() assert "+6.5 dB" in first.locator(".gain-readout").inner_text() + # Rename the selected BUS in the native-style identity card. + # SOF selection must follow its ID, not jump back to Bus A. + page.locator("#viewFilter").select_option("bus") + selected_bus = page.locator('#tracks .strip[data-id="' + initial_id + '"]') + assert selected_bus.count() == 1, (width, initial_id) + selected_bus.locator(".strip-identity-top").dblclick() + page.locator("#identityName").fill("STAGE MONITOR A") + page.locator("#identitySave").click() + assert target_select.input_value() == initial_id + assert target_select.locator("option:checked").inner_text() == "STAGE MONITOR A" + page.locator("#viewFilter").select_option("all") + page.locator("#sofToggle").click() + assert page.locator("#mixContext").inner_text() == "SEND MIX → STAGE MONITOR A" + assert first.locator(".is-sof-view").get_attribute("data-sof-target") == initial_id + page.locator("#sofToggle").click() + gain.click() + # Every visible cell remains in its strip bounds. geometry = first.locator(".gain-view-body").evaluate("""el => { const a=el.getBoundingClientRect(), From 62528d5abf5bfa5c85def2560d1c6243b4142e38 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 08:10:08 +0700 Subject: [PATCH 048/140] fix(build): restore Python string concatenation in native SOF scope export --- scripts/build_approved_native_gui.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index a7ce3583f..990ca2516 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -214,7 +214,8 @@ def accepted_pages_html() -> str: "window.__ARMIX_NATIVE_SCOPE__=Object.freeze({\n" " get tracks(){return tracks;},get master(){return master;},\n" " get wireEdges(){return wireEdges;}, // native read-only UI edge identity\n" - " get sofEnabled(){return sofEnabled;},get sofTarget(){return sofTarget;},\n"\n " get sofTargetId(){return sofTargetId;},toggleSof,\n" + " get sofEnabled(){return sofEnabled;},get sofTarget(){return sofTarget;},\n" + " get sofTargetId(){return sofTargetId;},toggleSof,\n" " get selectedWireEdgeId(){return selectedWireEdgeId;},\n" " get wireGainDragging(){return !!sendKnobDrag;},paintWireKnob,\n" " syncNativeWireGains(rows){\n" From cc6f71d6e1a237a4f04cf431baa3a31666d642d9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 08:11:36 +0700 Subject: [PATCH 049/140] docs(sonku): lock perspective ellipse, source disambiguation and studio rotary UX contract --- docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md | 13 ++++++++++++- docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md | 9 +++++++++ docs/RESEARCH_8D_SONKU_SPATIAL_AUDIO_20261112.md | 7 +++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md b/docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md index 3f243960d..56332e885 100644 --- a/docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md +++ b/docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md @@ -139,4 +139,15 @@ One coherent M1 PR should add: minimal pure `SonKuMotion`, real prepared directi See [PRD](PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md), [research](RESEARCH_8D_SONKU_SPATIAL_AUDIO_20261112.md). ## Top-down visual orientation (2026-11-13 owner-approved) -The new photographed/illustrated blue listener-bust image is viewed from above with the person's face pointing to the BOTTOM of the SVG stage. Do **not** change DSP azimuth signs to match screen coordinates. Visual screen coordinates are X right, Y down, and projection is `screenX = centerX - radius * sin(azimuth)`, `screenY = centerY + radius * cos(azimuth)`. Acoustic FRONT=0° appears bottom, REAR=180° appears top, RIGHT=+90° appears screen-left, LEFT=-90° appears screen-right (anatomical right/left looking over the listener, not screen-side shorthand). Pointer inverse is `atan2(centerX - x, y - centerY)` and all changes still flow through the installed native FX ACK/readback; asset is only one passive GUI raster. The source PNG is `site/preview-v2/assets/sonku-listener-top.png` and is copied unchanged into the **one approved compiled /preview/** and native JUCE binary resource bundle. The asset is a preoptimized transparent 128px indexed PNG (8162 bytes; copy verbatim, no runtime SVG filters beyond the scoped drop-shadow). No DSP, HRTF dataset, routing, or extra HTML renderer changes. +The new photographed/illustrated blue listener-bust image is viewed from above with the person's face pointing to the BOTTOM of the SVG stage. Do **not** change DSP azimuth signs to match screen coordinates. Visual screen coordinates are X right, Y down, and **perspective-ellipse (presentation-only)** projection is `screenX = centerX - rx * sin(azimuth)`, `screenY = centerY + ry * cos(azimuth)`, with current stage `centerX=200`, `centerY=174`, `rx=148`, `ry=83`. Acoustic FRONT=0° appears bottom, REAR=180° appears top, RIGHT=+90° appears screen-left, LEFT=-90° appears screen-right (anatomical right/left looking over the listener, not screen-side shorthand). Pointer inverse is `atan2((centerX - x)/rx, (y - centerY)/ry)` and all changes still flow through the installed native FX ACK/readback; asset is only one passive GUI raster. The source PNG is `site/preview-v2/assets/sonku-listener-top.png` and is copied unchanged into the **one approved compiled /preview/** and native JUCE binary resource bundle. The asset is a preoptimized transparent 128px indexed PNG (8162 bytes; copy verbatim, no runtime SVG filters beyond the scoped drop-shadow). No DSP, HRTF dataset, routing, or extra HTML renderer changes. + +## 2026-11-13 — locked premium spatial editor geometry and control contract (M4 UX) +This record supersedes the earlier **round/circular stage UI** and radial 2D marker presentation. It does **not** alter audio parameter semantics, HRTF filter response, or stereo PCM channel assignment. + +- **Unified perspective**: one perspective-flattened elliptical orbit is split into far (REAR) and near (FRONT) SVG paths. The far dashed arc must be painted **before** the passive blue listener PNG, and the near highlighted arc **after** the PNG, making the ring appear to pass in front of the lower bust. This is painter occlusion, not 3D ray tracing. Original source image remains `site/preview-v2/assets/sonku-listener-top.png`; no copyrighted product asset cloning. +- **True acoustic coordinates**: 0° front, +90° listener right / screen left, 180° rear, -90° listener left / screen right. The ellipse is a **visual projection only**. The native HRIR and `SonKuSpatialCore` use the same, unchanged angle. Do not apply the ellipse's `rx/ry` ratio inside audio convolution. +- **Two visible independent source monitors**: at zero (or near-zero) stereo spread, both emitters share the same true acoustic anchor. The GUI draws *two studio monitor glyphs* with a symmetric, continuous tangential offset sufficient to remain separately clickable and links them to the true anchor with subtle tethers. Store actual anchor separately from displayed coordinates, and always pass the actual azimuth to native SPSC settings. On spread >0 markers return smoothly toward true positions; **never silently alter native spread** just to separate SVG icons. +- **Control surface**: dark satin/brushed plugin-editor finish; compact metal-look four rotary controls REVOLUTION/SPREAD/SPATIAL MIX/OUTPUT TRIM. Keep native HTML range inputs for keyboard and assistive access. UI pointer vertical drag updates only draft value; exactly ONE native edit request is sent on release, ACK/readback authority unchanged. Double click returns to the documented default. Never let the pointer-only visual dial claim applied DSP. +- **No extra renderer or CSS owner**: add to existing one /preview/ editor and existing `mixer-fx-rack.css`, maintaining exactly 18 CSS owner links. No WebAudio, DSP JS clone, extra callback or CPU-intensive continuous 3D scene. +- **Verification evidence**: Chromium assembled native GUI two viewport screenshots, actual FX picker insertion and ACK/readback, four acoustic directions, front/rear painter order, both monitors visible at 0° spread, real mouse drag to FRONT, rotary drag with one typed native request. Exact SHA `4652a744ab4ae01b1ceca58bb6c3d7e372eb420a`, [UI run](https://github.com/masarray/arsonmix/actions/runs/43342451656), [two screenshots](https://github.com/masarray/arsonmix/actions/runs/43342451656/artifacts/13999089726). +- **Release gate**: browser FAT uses simulated JUCE events. It is not physical binaural localization or installed Windows/ASIO FAT, and the PR must be reconciled with advancing `main` before any public release. diff --git a/docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md b/docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md index b2a38be39..aacb08d2d 100644 --- a/docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md +++ b/docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md @@ -91,3 +91,12 @@ No dearVR binary/source/reverb preset copying, unlicensed HRTF dataset distribut 5. **No "3D verified" badge until blind headphone front/rear listening succeeds.** See: [ARD](ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md), [research evidence](RESEARCH_8D_SONKU_SPATIAL_AUDIO_20261112.md), and existing [feature playbook](architecture/FEATURE_EXTENSION_PLAYBOOK.md). + +## 2026-11-13 — verified spatial UX acceptance refinements +For the owner's approved top-side-head PNG, the plugin shall present an **elliptical 3D-implied orbital plane** rather than a 2D circle. The rear orbit must visually pass **behind** the head, and the foreground orbit must pass **in front of** the lower bust. This is a UI projection, **not** an audio-path or 8-channel expansion. + +Both L and R studio monitor speakers must remain separately visible and individually interactive even when **Stereo Spread = 0°**. If acoustic positions coincide, graphical disambiguation must be clearly presentation-only; their identical native azimuths and original channel routing remain unchanged. FRONT remains the bottom of the stage; anatomical RIGHT is screen-left, anatomical LEFT screen-right. + +The editor must feel like a compact hardware-grade audio plugin, with tactile rotary controls and clear numeric readouts, not large web-style cards or anonymous browser sliders. Rotary pointer gestures must be bounded and single-commit; keyboard focus, range semantics and double-click default restoration remain accessible. Do not imitate or redistribute commercial plugin skins. + +Acceptance evidence on the real compiled native HTML bundle must cover correct Z-order, actual PNG load, two separately visible monitors at 0° spread, correct four-direction mapping, mouse drag to FRONT, knob edit single native queue/ACK and desktop/narrow screenshots. Do not translate GUI PASS into a claim of verified binaural headphone localization. diff --git a/docs/RESEARCH_8D_SONKU_SPATIAL_AUDIO_20261112.md b/docs/RESEARCH_8D_SONKU_SPATIAL_AUDIO_20261112.md index 13dd8d657..4c454c128 100644 --- a/docs/RESEARCH_8D_SONKU_SPATIAL_AUDIO_20261112.md +++ b/docs/RESEARCH_8D_SONKU_SPATIAL_AUDIO_20261112.md @@ -53,3 +53,10 @@ Date: 2026-11-12. Status: desktop research, not first-hand FFT/CPU/ASIO/listener ## Design recommendation R0: publish PRD and ARD (this branch). M1: implement true 4-direction native HRTF core with one stable insert identity, PCM tests and safe bypass. M2: add sample-driven orbit. M3: real room. M4: premium path editor, calibration. Gate perfection claims on measured listening evidence. + +## UI references audited 2026-11-13 (form principles only) +- [Waves Nx Virtual Mix Room user guide](https://assets.wavescdn.com/pdf/plugins/nx.pdf): a human-head-centric visual with speaker icons makes orientation and left/right scene intent recognizable. Adapt **human + monitors**, not Waves' copyrighted artwork or skin. +- [Sound Particles Energy Panner 2](https://soundparticles.com/products/energypanner/overview/): the moving-source visualization is the main interaction canvas; source paths, controls and stereo distribution are visually connected. Adapt **one central spatial display** and visible source markers. +- [dearVR PRO 2](https://spaes.org/dearVR-PRO-2): direct graphical XYZ positioning illustrates why direction should be interactive rather than a hidden numerical parameter. 8D-SonKu M1 stays horizontal 0° elevation; do not advertise full XYZ elevation or personalized distance room simulation absent DSP. + +The adapted user experience is **not** based on reverse-engineering any proprietary plugin GUI. Use the already-owner-approved blue bust asset, original SVG perspective ellipse, original mini studio-monitor vector controls and native JUCE/HTML range inputs. Preserve acoustic coordinate signs and distinguish display separation from true source azimuth. See the M4 contract in the ARD and PRD. From 0112649e328e54138f75866deec3c0193614954b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 08:11:44 +0700 Subject: [PATCH 050/140] fix(gui): admit native GAIN view only after per-ChannelId gain capability ACK --- site/preview-v2/index.html | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index 6f24b1906..fb5de119f 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -2659,9 +2659,15 @@ for(const [id,value] of [['gainView','gain'],['fxView','fx']]){ document.getElementById(id).addEventListener('click',()=>{ if(sofEnabled)return; - if(value==='gain'&&window.__JUCE__?.backend){say('Native input gain requires accepted DSP control');return;} + if(value==='gain'&&window.__JUCE__?.backend&& + !tracks.some(t=>t.kind==='audio'&&t.nativeGainAvailable===true)){ + say('INPUT GAIN unavailable · no channel has an acknowledged native gain stage'); + return; + } + // View selection is presentation-only; the DSP insert chain stays resident. stripView=value;render(); - say(value==='gain'?'Digital INPUT GAIN view · preview trim only':'FX RACK view · existing inserts preserved'); + say(value==='gain'?'Digital INPUT GAIN · each knob follows accepted channel readback': + 'FX RACK · existing inserts preserved'); }); } document.getElementById('sofToggle').addEventListener('click',()=>toggleSof()); From 8826f0e105f90ee2493487734433fc12825ee62f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 08:14:18 +0700 Subject: [PATCH 051/140] fix(gui): fader double-click respects SOF EdgeId; GAIN double-click resets through native intent --- site/preview-v2/index.html | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index fb5de119f..9e3568770 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -2178,7 +2178,28 @@ if(e.target.closest?.('.wire-gain,.wire-pot')){ const el=e.target.closest('.wire-pot')?.querySelector('.wire-gain')||e.target.closest('.wire-gain');el.value='0';handleField({target:el,type:'change'});return; } - if(e.target.classList.contains('fader')){t.level=0;refreshStrip(t);say(t.name+' fader reset to 0.0 dB');} + const dial=e.target.closest?.('.gain-dial'); + if(dial){ + const gain=dial.querySelector('[data-field="trim"]'); + if(!gain||gain.disabled)return; + // Same field path as a knob gesture: native ACK, no UI-only gain mutation. + gain.value='0';gain.dispatchEvent(new Event('input',{bubbles:true})); + gain.dispatchEvent(new Event('change',{bubbles:true})); + if(!window.__JUCE__?.backend)say(t.name+' digital input gain → unity (0.0 dB)'); + return; + } + if(e.target.classList.contains('fader')){ + const send=sofEnabled&&t.kind==='audio'; + if(send&&!getSofEdge(t)){say('NO SEND · patch one WIRE first');return;} + // Never mutate t.level directly: in SOF the physical fader belongs to + // the selected EdgeId, not MAIN. Native bridge owns the accepted write. + const fader=e.target; + if(fader.disabled)return; + fader.value='0';fader.dispatchEvent(new Event('input',{bubbles:true})); + fader.dispatchEvent(new Event('change',{bubbles:true})); + if(!window.__JUCE__?.backend)say(t.name+(send?' SEND':' MAIN')+' fader → 0.0 dB'); + return; + } if(e.target.classList.contains('center-pan')){t.pan=0;refreshStrip(t);say(t.name+' pan centered');} if(e.target.closest('.footer-label,.strip-identity-top'))openChannelIdentity(t,e.target); }); From dfccaafc3c54f90f816e56615e4dc3e5fa1413c4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 08:14:47 +0700 Subject: [PATCH 052/140] test(gui): GAIN unity double-click, SOF reset guard and accepted native gain entry --- tests/sof_contextual_console_smoke.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/sof_contextual_console_smoke.py b/tests/sof_contextual_console_smoke.py index 2728c9036..39eadb05e 100644 --- a/tests/sof_contextual_console_smoke.py +++ b/tests/sof_contextual_console_smoke.py @@ -34,6 +34,10 @@ def run() -> None: assert 'id="gainView"' in source and 'id="fxView"' in source assert 'id="mixContext"' in source assert "Never auto-patch or remove a WIRE at minimum send level." in source + assert "const send=sofEnabled&&t.kind==='audio';" in source, ( + "Fader reset must inspect active SEND context instead of overwriting MAIN") + assert "nativeGainAvailable===true" in source, ( + "Native input gain should be available only with installed capability") with sync_playwright() as p: browser = p.chromium.launch(headless=True) try: @@ -62,6 +66,14 @@ def run() -> None: }""") assert "+6.5 dB" in first.locator(".gain-readout").inner_text() assert "6.5" in knob.get_attribute("value") or knob.input_value() == "6.5" + # Double-click must use the same gain parameter path and restore unity. + first.locator(".gain-dial").dblclick() + assert "+0.0 dB" in first.locator(".gain-readout").inner_text() + assert knob.input_value() == "0" + knob.evaluate("""el => { + el.value = '6.5'; + el.dispatchEvent(new Event('input', {bubbles:true})); + }""") fx.click() assert first.locator(".is-gain-view").count() == 0 From 6d034882982f0e0c0c0347b9ddac938b4bd5c442 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 08:16:27 +0700 Subject: [PATCH 053/140] fix(native-ui): doubleclick SOF controls EdgeId send, not MAIN; GAIN reset uses installed intent --- web/approved-native-bridge.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 4669ac829..43a9e68fc 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -3839,12 +3839,27 @@ }, consumeDoubleClick(event,t) { if (!connected)return false; + // Reset the parameter the fader CURRENTLY owns. A SOF reset must not + // write the main channel's SET_FADER or M4 faderDb by accident. if (event.target.classList.contains("fader")){ + if(scope?.sofEnabled&&t?.kind==="audio"){ + const edge=selectedNativeSofEdge(t),id=edge&&uiByWireId.get(edge.edgeId); + if(!edge||id===undefined|| + !requestWireGain({sourceId:t.id,edgeId:id,levelDb:0})) + status("SOF unity reset unavailable · select one admitted SEND"); + return true; + } if((m4ControlIsOwner()&&m4Verified()) || (t?.kind==="master"&&(m4Verified()||nativeMasterReady()))) sendM4Control(t?.kind==="master"?"masterGain":"faderDb",t,0); else intent("SET_FADER",t,{valueDb:0}); } + else if(event.target.closest?.(".gain-dial")){ + if(t?.kind!=="audio"||t.nativeGainAvailable!==true) + status("INPUT GAIN unity reset requires native PCM admission"); + else intent("SET_INPUT_GAIN",t,{valueDb:0}); + return true; + } else if(event.target.classList.contains("center-pan")){ if(m4ControlIsOwner()&&m4Verified())sendM4Control("pan",t,0); else intent("SET_PAN",t,{value:0}); From 25fa8c022f4efbf8ff123523286ba1a5fe52b9c6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 08:17:06 +0700 Subject: [PATCH 054/140] test(native-ui): protect MAIN from SOF double-click and verify Gain unity intent --- tests/approved_native_m2_contract.test.cjs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index a4f66f437..1d0d3f331 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1981,3 +1981,24 @@ test("O3 OUTPUTS stays in one existing Audio I/O with safe, read-only DOM",()=>{ assert.match(bridge,/owner\.textContent=patch\.role/); assert.doesNotMatch(bridge,/owner\.innerHTML=patch/); }); + +test("SOF double-click and target selection never commandeer MAIN fader",()=>{ + const html=read("site/preview-v2/index.html"); + const bridge=read("web/approved-native-bridge.js"); + const bundle=read("scripts/build_approved_native_gui.py"); + assert.match(html,/function selectedSofDestination\(\)/); + assert.match(html,/sofTargetId=target\?\.id\?\?null/); + assert.match(html,/const send=sofEnabled&&t\.kind==='audio'/); + assert.match(html,/fader\.dispatchEvent\(new Event\('change'/); + assert.match(bundle,/get sofTargetId\(\)\{return sofTargetId;\}/); + assert.match(bridge,/x\.id===scope\.sofTargetId/); + const start=bridge.indexOf("consumeDoubleClick(event,t)"); + const end=bridge.indexOf("applyIdentity:",start); + assert.ok(start>0&&end>start,"native delegate must own double-click"); + const handler=bridge.slice(start,end); + assert.ok(handler.indexOf("scope?.sofEnabled") < + handler.indexOf('sendM4Control'), + "SOF must intercept fader reset BEFORE M4/Main fader ownership"); + assert.match(handler,/requestWireGain\(\{sourceId:t\.id,edgeId:id,levelDb:0\}\)/); + assert.match(handler,/intent\("SET_INPUT_GAIN",t,\{valueDb:0\}\)/); +}); From efe883a370e5bcd764bb9049cac0de0eb3cee4c7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 09:15:41 +0700 Subject: [PATCH 055/140] feat(sonku): sample-continuous HRTF direction and wet/trim transitions with PCM regression --- engine/builtin_fx/sonku/SonKuSpatialCore.h | 40 +++++++++++++++----- tests/sonku_spatial_core_test.cpp | 43 ++++++++++++++++++++++ 2 files changed, 74 insertions(+), 9 deletions(-) diff --git a/engine/builtin_fx/sonku/SonKuSpatialCore.h b/engine/builtin_fx/sonku/SonKuSpatialCore.h index 7ae0b7f68..d8990d89f 100644 --- a/engine/builtin_fx/sonku/SonKuSpatialCore.h +++ b/engine/builtin_fx/sonku/SonKuSpatialCore.h @@ -44,6 +44,10 @@ class SonKuSpatialCore final { std::abs(rate-48000.)>.1))return false; sampleRate_=rate; bank_=(std::abs(rate-44100.)<.1)?hrir::normal44100:hrir::normal48000; + // Prepared control-side: continuous coefficient and gain smoothing + // without trigonometric/exponential work in the audio callback. + filterSlew_=static_cast(1.-std::exp(-1./(rate*0.006))); + levelSlew_=static_cast(1.-std::exp(-1./(rate*0.008))); reset(); ready_=true; return true; @@ -51,6 +55,9 @@ class SonKuSpatialCore final { void reset() noexcept { for(auto& channel:history_)channel.fill(0.f); for(auto& source:kernels_)for(auto& ear:source)ear.fill(0.f); + for(auto& source:targets_)for(auto& ear:source)ear.fill(0.f); + smoothedMix_=settings_.spatialMix; + smoothedTrim_=settings_.outputTrim; write_=0; remaining_=0; degrees_=wrapDegrees(settings_.startAzimuthDegrees); @@ -76,10 +83,11 @@ class SonKuSpatialCore final { if(!ready_ || !left || !right || samples<=0)return; const double step=(settings_.moving ? (settings_.clockwise?1.:-1.)*360./(sampleRate_*settings_.revolutionSeconds) : 0.); - const float wetLevel=0.5f*settings_.outputTrim; - const float dryLevel=1.f-settings_.spatialMix; - const float binauralLevel=settings_.spatialMix*wetLevel; for(int i=0;i(bank_[lo][measuredEar][k])*(1.f-u) + static_cast(bank_[hi][measuredEar][k])*u); - // Small bounded coefficient smoothing prevents abrupt filter - // switches on motion/edits. No interpolating filter ownership. - auto& current=kernels_[source][ear][k]; - current=haveKernel_?(current*0.65f+next*0.35f):next; + // Recompute target every 16 samples, interpolate per sample. + targets_[source][ear][k]=next; } } } void updateKernels() noexcept { interpolate(0,degrees_-static_cast(settings_.stereoSpreadDegrees)*0.5); interpolate(1,degrees_+static_cast(settings_.stereoSpreadDegrees)*0.5); + // First prepared sample is a valid full-level measured HRIR; only + // subsequent direction edits slew, avoiding initial audio dropout. + if(!haveKernel_)kernels_=targets_; haveKernel_=true; } using Bank=const std::int16_t (*)[2][taps]; Bank bank_=nullptr; std::array,2> history_{}; std::array,2>,2> kernels_{}; + std::array,2>,2> targets_{}; Settings settings_{}; + float smoothedMix_=1.f,smoothedTrim_=0.75f; + float filterSlew_=0.f,levelSlew_=0.f; double sampleRate_=0.; double degrees_=0.; int write_=0; diff --git a/tests/sonku_spatial_core_test.cpp b/tests/sonku_spatial_core_test.cpp index 31c9ad70c..31951d15a 100644 --- a/tests/sonku_spatial_core_test.cpp +++ b/tests/sonku_spatial_core_test.cpp @@ -78,6 +78,49 @@ int main() { assert(std::abs(oneR[i]-chunkR[i])<1.e-6f); } assert(std::abs(whole.azimuthDegrees()-chunked.azimuthDegrees())<1.e-10); + // A hard FRONT->REAR teleport must not replace 560 FIR coefficients + // at the next 16-sample boundary. Compare the identical dry/PCM + // history before and immediately after reposition. + SonKuSpatialCore teleport,stationary; + assert(teleport.prepare(rate)&&stationary.prepare(rate)); + Settings front=s;front.startAzimuthDegrees=0.f; + assert(teleport.setSettings(front)&&stationary.setSettings(front)); + std::array preL{},preR{},sameL{},sameR{}; + preL.fill(.12f);preR.fill(-.10f);sameL=preL;sameR=preR; + teleport.process(preL.data(),preR.data(),512); + stationary.process(sameL.data(),sameR.data(),512); + Settings rear=front;rear.startAzimuthDegrees=180.f; + assert(teleport.setSettings(rear)); + std::array stepL{},stepR{},refL{},refR{}; + stepL.fill(.12f);stepR.fill(-.10f);refL=stepL;refR=stepR; + teleport.process(stepL.data(),stepR.data(),1024); + stationary.process(refL.data(),refR.data(),1024); + assert(std::abs(stepL[0]-refL[0])<.008f); + assert(std::abs(stepR[0]-refR[0])<.008f); + double changed=0.; + for(int i=750;i<1024;++i) + changed+=std::abs(stepL[i]-refL[i])+std::abs(stepR[i]-refR[i]); + assert(changed>.005); + // MIX/trim changes are smoothed on the same audio clock. + SonKuSpatialCore mixCore; + assert(mixCore.prepare(rate)); + Settings dry=front;dry.spatialMix=0.f; + assert(mixCore.setSettings(dry)); + std::array warmL{},warmR{}; + warmL.fill(.19f);warmR.fill(-.13f); + mixCore.process(warmL.data(),warmR.data(),2048); + Settings wet=dry;wet.spatialMix=1.f;wet.outputTrim=.5f; + assert(mixCore.setSettings(wet)); + std::array fadeL{},fadeR{}; + fadeL.fill(.19f);fadeR.fill(-.13f); + mixCore.process(fadeL.data(),fadeR.data(),1024); + assert(std::abs(fadeL[0]-.19f)<.01f); + assert(std::abs(fadeR[0]+.13f)<.01f); + for(int i=1;i<1024;++i) { + assert(std::isfinite(fadeL[i])&&std::isfinite(fadeR[i])); + assert(std::abs(fadeL[i]-fadeL[i-1])<.04f); + assert(std::abs(fadeR[i]-fadeR[i-1])<.04f); + } moving.spatialMix=0.f; assert(chunked.setSettings(moving)); std::array dryL{},dryR{};dryL.fill(.17f);dryR.fill(-.29f); chunked.process(dryL.data(),dryR.data(),32); From 96482b385d5557cae47c7315a707e306108a8b24 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 09:23:30 +0700 Subject: [PATCH 056/140] test(sonku): resolve static pose fixture name collision in fast C++20 gate --- tests/sonku_spatial_core_test.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/sonku_spatial_core_test.cpp b/tests/sonku_spatial_core_test.cpp index 31951d15a..9b9f7a5d9 100644 --- a/tests/sonku_spatial_core_test.cpp +++ b/tests/sonku_spatial_core_test.cpp @@ -83,14 +83,14 @@ int main() { // history before and immediately after reposition. SonKuSpatialCore teleport,stationary; assert(teleport.prepare(rate)&&stationary.prepare(rate)); - Settings front=s;front.startAzimuthDegrees=0.f; - assert(teleport.setSettings(front)&&stationary.setSettings(front)); + Settings frontPose=s;frontPose.startAzimuthDegrees=0.f; + assert(teleport.setSettings(frontPose)&&stationary.setSettings(frontPose)); std::array preL{},preR{},sameL{},sameR{}; preL.fill(.12f);preR.fill(-.10f);sameL=preL;sameR=preR; teleport.process(preL.data(),preR.data(),512); stationary.process(sameL.data(),sameR.data(),512); - Settings rear=front;rear.startAzimuthDegrees=180.f; - assert(teleport.setSettings(rear)); + Settings rearPose=frontPose;rearPose.startAzimuthDegrees=180.f; + assert(teleport.setSettings(rearPose)); std::array stepL{},stepR{},refL{},refR{}; stepL.fill(.12f);stepR.fill(-.10f);refL=stepL;refR=stepR; teleport.process(stepL.data(),stepR.data(),1024); @@ -104,7 +104,7 @@ int main() { // MIX/trim changes are smoothed on the same audio clock. SonKuSpatialCore mixCore; assert(mixCore.prepare(rate)); - Settings dry=front;dry.spatialMix=0.f; + Settings dry=frontPose;dry.spatialMix=0.f; assert(mixCore.setSettings(dry)); std::array warmL{},warmR{}; warmL.fill(.19f);warmR.fill(-.13f); From fdf484a03be88b5c0ddaae5a7ce249e50d446b2d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 09:25:43 +0700 Subject: [PATCH 057/140] fix(sonku): settle exactly to dry after clickless wet/dry ramp, assert both phases --- engine/builtin_fx/sonku/SonKuSpatialCore.h | 7 +++++++ tests/sonku_spatial_core_test.cpp | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/engine/builtin_fx/sonku/SonKuSpatialCore.h b/engine/builtin_fx/sonku/SonKuSpatialCore.h index d8990d89f..5e4484694 100644 --- a/engine/builtin_fx/sonku/SonKuSpatialCore.h +++ b/engine/builtin_fx/sonku/SonKuSpatialCore.h @@ -86,6 +86,13 @@ class SonKuSpatialCore final { for(int i=0;i settleL{},settleR{}; + for(int block=0;block<80;++block) { + settleL.fill(0.f);settleR.fill(0.f); + chunked.process(settleL.data(),settleR.data(),128); + } std::array dryL{},dryR{};dryL.fill(.17f);dryR.fill(-.29f); chunked.process(dryL.data(),dryR.data(),32); for(int i=0;i<32;++i){assert(std::abs(dryL[i]-.17f)<1.e-6f);assert(std::abs(dryR[i]+.29f)<1.e-6f);} From 75ba1988ba697ec2855972c36ed9c4e8d98fa51e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 09:33:08 +0700 Subject: [PATCH 058/140] feat(sonku): exact native HRTF headphone listening and blind direction qualification WAVs --- .github/workflows/ui-smoke.yml | 13 ++ tests/sonku_offline_demo_contract.py | 38 ++++++ tools/sonku_offline_listening.cpp | 170 +++++++++++++++++++++++++++ 3 files changed, 221 insertions(+) create mode 100644 tests/sonku_offline_demo_contract.py create mode 100644 tools/sonku_offline_listening.cpp diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index aa95c445c..f4cb2d561 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -209,6 +209,19 @@ jobs: python -m playwright install --with-deps chromium - name: Actual native picker insert, ACK/readback, editor open, UI controls run: python tests/approved_native_sonku_smoke.py + - name: Render original 8D-SonKu headphone candidate through exact native HRTF + run: | + g++ -std=c++20 -O2 -Wall -Wextra -pedantic tools/sonku_offline_listening.cpp -o /tmp/sonku-listening + /tmp/sonku-listening sonku-listening + python tests/sonku_offline_demo_contract.py sonku-listening + - name: Publish 8D-SonKu reproducible listening WAVs and blind answer key + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ArSonMix-SonKu-Headphone-Audio-${{ github.run_id }} + path: sonku-listening/* + if-no-files-found: ignore + retention-days: 14 - name: Keep verified 8D-SonKu editor screenshots if: ${{ always() }} uses: actions/upload-artifact@v4 diff --git a/tests/sonku_offline_demo_contract.py b/tests/sonku_offline_demo_contract.py new file mode 100644 index 000000000..d8fb941d1 --- /dev/null +++ b/tests/sonku_offline_demo_contract.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Offline listening WAV contract: format, finite energy, direction and no clipping.""" +from pathlib import Path +import array +import sys +import wave + +root = Path(sys.argv[1] if len(sys.argv)>1 else "sonku-listening") +def read(name, frames): + path=root/name + assert path.exists() and path.stat().st_size>10000,path + with wave.open(str(path),"rb") as w: + assert w.getnchannels()==2 + assert w.getsampwidth()==2 + assert w.getframerate()==48000 + assert w.getnframes()==frames,(name,w.getnframes(),frames) + pcm=array.array("h",w.readframes(frames)) + if sys.byteorder!="little":pcm.byteswap() + assert len(pcm)==2*frames + peak=max(map(abs,pcm)) + assert 250100000,(name,"unexpected silence") + return pcm +single=read("sonku-reference-four.wav",4*120000) +blind=read("sonku-blind-eight.wav",8*120000) +orbit=read("sonku-orbit-cw.wav",480000) +# +90° (second reference segment) has a distinct binaural response. +section=single[120000*2:120000*4] +left=sum(abs(section[i]) for i in range(0,len(section),2)) +right=sum(abs(section[i]) for i in range(1,len(section),2)) +assert right>left*1.2,("RIGHT HRTF channel swapped",left,right) +# No false silence between orbit buffer boundaries; source is continuous. +assert sum(abs(x) for x in orbit[220000:230000])>1000 +assert (root/"LISTENING-GUIDE.txt").exists() +key=(root/"BLIND-ANSWER-KEY.txt").read_text() +assert key.count("Trial ")==8 and key.count("FRONT")==2 and key.count("REAR")==2 +print("PASS 8D-SonKu actual C++ offline WAV: four directions, balanced blind", + "set, clockwise orbit, 48kHz stereo PCM, no clipping.") diff --git a/tools/sonku_offline_listening.cpp b/tools/sonku_offline_listening.cpp new file mode 100644 index 000000000..807ca3141 --- /dev/null +++ b/tools/sonku_offline_listening.cpp @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Deterministic offline headphone evidence from the EXACT shipped native +// 8D-SonKu measured HRTF core. No external music, WebAudio or second engine. +// Generates lossless stereo WAVs for listening and blind front/rear evaluation. +// Audio is NONPERSONALIZED MIT KEMAR, so perceptual externalization is UNPROVEN. +#include "../engine/builtin_fx/sonku/SonKuSpatialCore.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr std::uint32_t rate=48000; +constexpr int framesPerBlock=128; +constexpr int activeFrames=rate*2; +constexpr int silenceFrames=rate/2; +constexpr int rampFrames=rate/50; // 20ms, no clicks between labeled probes +using armix::sonku::Settings; +using armix::sonku::SonKuSpatialCore; +struct Noise { + std::uint32_t x=0x9a762b41u; + float low=0.f,body=0.f; + float sample() noexcept { + x^=x<<13;x^=x>>17;x^=x<<5; + const float white=(static_cast(x&0xffffffu)/8388608.f)-1.f; + low+=.085f*(white-low); + body+=.013f*(white-body); + return .16f*(.44f*white+.37f*low+.19f*body); + } +}; +void appendSample(std::vector& bytes,float x){ + if(!std::isfinite(x))throw std::runtime_error("Nonfinite SonKu PCM"); + if(std::abs(x)>.95f)throw std::runtime_error("SonKu clipping: reduce offline source"); + const auto sample=static_cast(std::lround(x*32767.f)); + const auto bits=static_cast(sample); + bytes.push_back(static_cast(bits&255u)); + bytes.push_back(static_cast((bits>>8)&255u)); +} +void appendStereo(std::vector& bytes,float l,float r){ + appendSample(bytes,l);appendSample(bytes,r); +} +void le(std::ostream& out,std::uint32_t x,int width){ + for(int i=0;i((x>>(8*i))&255u)); +} +void writeWav(const std::filesystem::path& path,const std::vector& pcm){ + if(pcm.size()>0xFFFFFF00u||pcm.size()%4)throw std::runtime_error("Invalid PCM length"); + std::ofstream out(path,std::ios::binary); + if(!out)throw std::runtime_error("Cannot open "+path.string()); + out.write("RIFF",4);le(out,static_cast(pcm.size()+36),4); + out.write("WAVEfmt ",8);le(out,16,4);le(out,1,2);le(out,2,2); + le(out,rate,4);le(out,rate*4,4);le(out,4,2);le(out,16,2); + out.write("data",4);le(out,static_cast(pcm.size()),4); + out.write(reinterpret_cast(pcm.data()), + static_cast(pcm.size())); + if(!out)throw std::runtime_error("Failed writing "+path.string()); +} +Settings fixed(float azimuth){ + Settings s{}; + s.moving=false;s.startAzimuthDegrees=azimuth; + s.stereoSpreadDegrees=0.f;s.spatialMix=1.f;s.outputTrim=.72f; + return s; +} +std::vector staticProbes(const std::vector& azimuths) { + SonKuSpatialCore dsp;Noise noise; + if(!dsp.prepare(rate))throw std::runtime_error("No 48k HRTF"); + std::vector result; + result.reserve(static_cast(azimuths.size())* + (activeFrames+silenceFrames)*4); + for(const int azimuth:azimuths){ + dsp.reset();if(!dsp.setSettings(fixed(static_cast(azimuth)))) + throw std::runtime_error("Invalid static direction"); + for(int base=0;base l{},r{}; + for(int i=0;i(rampFrames), + 0.f,1.f); + v=noise.sample()*gain; + } + l[static_cast(i)]=v; + r[static_cast(i)]=v; + } + dsp.process(l.data(),r.data(),n); + for(int i=0;i orbit(){ + SonKuSpatialCore dsp;Noise noise; + if(!dsp.prepare(rate))throw std::runtime_error("No 48k HRTF"); + Settings s=fixed(0.f);s.moving=true;s.clockwise=true;s.revolutionSeconds=10.f; + dsp.reset();if(!dsp.setSettings(s))throw std::runtime_error("No 360 orbit"); + const int frames=rate*10; + std::vector result; + result.reserve(static_cast(frames)*4); + for(int base=0;base l{},r{}; + for(int i=0;i(rampFrames),0.f,1.f); + const float v=noise.sample()*gain; + l[static_cast(i)]=v; + r[static_cast(i)]=v; + } + dsp.process(l.data(),r.data(),n); + for(int i=0;i& blind) { + std::ofstream f(directory/"LISTENING-GUIDE.txt"); + if(!f)throw std::runtime_error("Cannot create guide"); + f<<"8D-SonKu measured-HRTF headphone listening qualification\n" + <<"SOURCE: EXACT engine/builtin_fx/sonku/SonKuSpatialCore.h in this SHA.\n" + <<"Audio: 48kHz, 16-bit stereo PCM, nonpersonalized MIT KEMAR, 0deg elevation.\n" + <<"Generated original broadband test noise; NO licensed music or speech.\n\n" + <<"HEADPHONES ONLY. Disable OS spatializer/enhancement, avoid speakers.\n" + <<"Start at LOW volume. Do not treat this as a certified perceptual pass.\n\n" + <<"sonku-reference-four.wav: 4 x 2.5 seconds; each position has 2s noise\n" + <<"then 0.5s quiet. Order: FRONT, RIGHT, REAR, LEFT.\n" + <<"sonku-blind-eight.wav: 8 x 2.5 seconds, balanced two times each.\n" + <<"Write down FRONT/RIGHT/REAR/LEFT for trials 1..8 before opening KEY.\n" + <<"sonku-orbit-cw.wav: 10s one continuous 360deg clockwise orbit,\n" + <<"starting at FRONT, acoustic RIGHT on listener's right headphone.\n\n" + <<"If front/rear is ambiguous or internalized, note headphones and listener.\n" + <<"These are not room reflections, personalized HRTFs or VST3 binaries.\n"; + std::ofstream key(directory/"BLIND-ANSWER-KEY.txt"); + if(!key)throw std::runtime_error("Cannot write blind answer key"); + key<<"OPEN ONLY AFTER LISTENING. Exact 2.5-second trial windows:\n"; + for(std::size_t i=0;i reference{0,90,180,-90}; + const std::vector blind{180,0,-90,90,90,180,0,-90}; + writeWav(dir/"sonku-reference-four.wav", + staticProbes({reference.begin(),reference.end()})); + writeWav(dir/"sonku-blind-eight.wav",staticProbes(blind)); + writeWav(dir/"sonku-orbit-cw.wav",orbit()); + notes(dir,blind); + std::cout<<"SonKu listening package PASS: measured native HRTF, " + <<"4 labeled + 8 blind directions + one 360 orbit\n"; + }catch(const std::exception& error){ + std::cerr<<"SonKu offline render FAILED: "< Date: Fri, 13 Nov 2026 09:36:19 +0700 Subject: [PATCH 059/140] feat(sof): edit exact parallel EdgeId ON/OFF and PRE/POST without touching primary OUT --- engine/core/DynamicChannelRoster.h | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/engine/core/DynamicChannelRoster.h b/engine/core/DynamicChannelRoster.h index 98079fd96..fb11276ff 100644 --- a/engine/core/DynamicChannelRoster.h +++ b/engine/core/DynamicChannelRoster.h @@ -67,7 +67,7 @@ struct ChannelEdit final { // Control-document metadata (rack/slot bypass) changes revision // without changing a fader, audio descriptor or live PCM topology. touchDocumentRevision, - setInputGain + setInputGain, setSendEnabled, setSendTap } kind=Kind::add; ChannelId id{}; // existing channel (except add) ChannelId target{}; // send destination @@ -81,6 +81,7 @@ struct ChannelEdit final { bool primaryOutput=false; // exclusive OUT edge, independent of parallel SEND bool connectMainOnCreate=false; // WIRE-first native creation; legacy imports unchanged float sendPan=0.f; // independent send PAN, never channel fader PAN + std::uint64_t sendEdgeId=0; // exact existing parallel EdgeId std::string text; }; struct ChannelEditResult final { @@ -268,6 +269,19 @@ class DynamicChannelRoster final { case ChannelEdit::Kind::setSolo: it->solo=op.enabled; break; + case ChannelEdit::Kind::setSendEnabled: + case ChannelEdit::Kind::setSendTap: { + const auto edge=std::find_if(it->sends.begin(),it->sends.end(), + [&](const auto& send){return send.edgeId==op.sendEdgeId;}); + if(!op.sendEdgeId || edge==it->sends.end()) + result.fault=ChannelEditFault::missingEdge; + else if(edge->primaryOutput) + result.fault=ChannelEditFault::invalidAction; + else if(op.kind==ChannelEdit::Kind::setSendEnabled) + edge->enabled=op.enabled; + else edge->preFader=op.preFader; // post-FX PRE, not PRE_FX + break; + } case ChannelEdit::Kind::touchDocumentRevision: // Exact stable ChannelId is validated above. Bump the // document revision without fabricating a DSP parameter From b00fdc9ad7e730de0ee07fb657c5ea9c6b7c0ba0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 09:36:40 +0700 Subject: [PATCH 060/140] feat(sof): expose real accepted-session input trim and EdgeId gate after PCM ACK --- engine/core/DynamicAcceptedSession.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/engine/core/DynamicAcceptedSession.h b/engine/core/DynamicAcceptedSession.h index dd4486f23..ca11e76da 100644 --- a/engine/core/DynamicAcceptedSession.h +++ b/engine/core/DynamicAcceptedSession.h @@ -306,6 +306,14 @@ class DynamicAcceptedSession final { return false; return accepted_.rememberLiveMix(id,linear,pan); } + // Pre-insert, pre-fader digital input gain; a real ChannelId PCM target. + bool setLiveInputGain(std::uint64_t epoch,std::uint64_t graphRevision, + ChannelId id,float linear) noexcept { + const auto* row=accepted_.find(id); + if(!row || row->role!=ChannelRole::input || + !publisher_.setChannelInputGain(epoch,graphRevision,id,linear))return false; + return accepted_.rememberLiveInputGain(id,linear); + } // 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, @@ -350,6 +358,20 @@ class DynamicAcceptedSession final { source,destination,preFader,linear); } + // The exact existing parallel EdgeId is toggled without deleting its + // connection, changing the source's primary OUT, or recompiling the graph. + bool setLiveSendEnabled(std::uint64_t epoch,std::uint64_t graphRevision, + ChannelId source,std::uint64_t edgeId,bool enabled) noexcept { + const auto* row=accepted_.find(source); + if(!row || !edgeId)return false; + for(const auto& edge:row->sends) + if(edge.edgeId==edgeId && !edge.primaryOutput){ + if(!publisher_.setWireEnabled(epoch,graphRevision,source,edgeId,enabled)) + return false; + return accepted_.rememberLiveSendEnabled(source,edgeId,enabled); + } + return false; + } bool setLiveWireGain(std::uint64_t epoch,std::uint64_t revision, ChannelId source,std::uint64_t edgeId,float gain) noexcept { const auto* row=accepted_.find(source); From 7c475c8c9212e88cae52a028772f56592666b19e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 09:37:02 +0700 Subject: [PATCH 061/140] feat(sof): expose offline EdgeId SEND ON and PRE/POST with truthful wire presence --- src/NativeLogicalMixerWorkspace.h | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/NativeLogicalMixerWorkspace.h b/src/NativeLogicalMixerWorkspace.h index bed3d2b90..53058bb54 100644 --- a/src/NativeLogicalMixerWorkspace.h +++ b/src/NativeLogicalMixerWorkspace.h @@ -188,6 +188,29 @@ class NativeLogicalMixerWorkspace final { edit.value=static_cast(n); } result=editor_.edit(expected,std::span{&edit,1}); + } else if(operation=="SET_SEND_TAP") { + const auto raw=payload.getProperty("edgeId",{}); + std::uint64_t edgeId=0; + if(!armix::session::parseDecimal(raw,edgeId)||!edgeId) + return bad("INVALID_SEND_TAP_EDGE"); + const auto tap=payload.getProperty("tap","").toString(); + if(tap!="PRE_FADER" && tap!="POST_FADER") + return bad("INVALID_SEND_TAP_STAGE"); + edit.kind=ChannelEdit::Kind::setSendTap; + edit.sendEdgeId=edgeId; + edit.preFader=tap=="PRE_FADER"; + result=editor_.edit(expected,std::span{&edit,1}); + } else if(operation=="SET_SEND_ENABLED") { + // Document-only operation: never impersonate installed ASIO PCM. + const auto raw=payload.getProperty("edgeId",{}); + const auto enabled=payload.getProperty("enabled",{}); + std::uint64_t edgeId=0; + if(!armix::session::parseDecimal(raw,edgeId)||!edgeId|| + !enabled.isBool())return bad("INVALID_SEND_ENABLED"); + edit.kind=ChannelEdit::Kind::setSendEnabled; + edit.sendEdgeId=edgeId; + edit.enabled=static_cast(enabled); + result=editor_.edit(expected,std::span{&edit,1}); } else if(operation=="SET_MUTE" || operation=="SET_SOLO") { if(!number.isBool())return bad("INVALID_BOOLEAN_CONTROL"); edit.kind=operation=="SET_MUTE"? @@ -351,6 +374,7 @@ class NativeLogicalMixerWorkspace final { for(const char* op:{"CREATE_CHANNEL","DELETE_CHANNEL","CREATE_GROUP", "REMOVE_BUS","RENAME_CHANNEL","SET_FADER","SET_INPUT_GAIN","SET_PAN","SET_MUTE", "SET_SOLO","SET_PROCESSING_FORMAT","WIRE_TRANSACTION", + "SET_SEND_ENABLED","SET_SEND_TAP", "ADD_FX_REFERENCE","REMOVE_FX_REFERENCE", "SET_FX_SLOT_BYPASS","SET_FX_RACK_BYPASS"})operations.add(juce::String(op)); set(cap,"supportedOps",juce::var(operations)); @@ -406,9 +430,13 @@ class NativeLogicalMixerWorkspace final { set(edge,"from",str(row.id.value)); set(edge,"to",str(send.destination.value)); set(edge,"signalKind","AUDIO");set(edge,"enabled",true); + // The wire remains present; SEND ON is an independent audio gate. + set(edge,"sendEnabled",send.enabled); set(edge,"gainLinear",static_cast(send.gain)); set(edge,"primaryOutput",send.primaryOutput); set(edge,"tap",send.preFader?"SPLIT_PRE":"POST_FADER"); + // Never confuse the modern post-FX PRE_FADER tap with PRE_FX. + set(edge,"tapStage",send.preFader?"PRE_FADER":"POST_FADER"); edges.add(edge); sends.add(edge); if(send.primaryOutput)set(channel,"primaryOutId",str(send.destination.value)); From 8fa3ca45558cbdbbbedd2f53e9f5ac842be31156 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 09:37:19 +0700 Subject: [PATCH 062/140] test(sof): exact EdgeId primary rejection, preserved OFF level and logical gain restore --- .../device_independent_mixer_session_test.cpp | 41 ++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/tests/device_independent_mixer_session_test.cpp b/tests/device_independent_mixer_session_test.cpp index 780c76216..af1ccdfc8 100644 --- a/tests/device_independent_mixer_session_test.cpp +++ b/tests/device_independent_mixer_session_test.cpp @@ -80,6 +80,41 @@ int main() { valid(track->sends.back().destination==stableMain && !track->sends.back().primaryOutput); + // SEND ON/OFF is a state of the exact parallel EdgeId, NOT removal. + // Primary OUT and a different edge may not be touched accidentally. + const auto sendEdge=track->sends.back().edgeId; + ChannelEdit off;off.kind=ChannelEdit::Kind::setSendEnabled; + off.id=backing;off.sendEdgeId=sendEdge;off.enabled=false; + auto toggled=logical.edit(logical.revision(), + std::span{&off,1}); + valid(toggled.accepted()); + track=logical.roster().find(backing); + valid(track->sends.size()==2 && !track->sends.back().enabled && + track->sends.back().gain==.25f && + track->sends.back().edgeId==sendEdge && + track->sends.front().primaryOutput && track->sends.front().enabled); + const auto revisionAfterOff=logical.revision(); + valid(!logical.edit(revisionAfterOff-1, + std::span{&off,1}).accepted()); + ChannelEdit wrong=off;wrong.sendEdgeId=serialEdge; + valid(!logical.edit(logical.revision(), + std::span{&wrong,1}).accepted()); + wrong.sendEdgeId=99999999; + valid(!logical.edit(logical.revision(), + std::span{&wrong,1}).accepted()); + valid(!logical.roster().find(backing)->sends.back().enabled); + // Restore retains disabled SEND identity and parameters without hardware. + DeviceIndependentMixerSession switched; + valid(switched.restore(logical.roster())); + const auto* swapped=switched.roster().find(backing); + valid(swapped && !swapped->sends.back().enabled && + swapped->sends.back().gain==.25f && swapped->sends.back().edgeId==sendEdge); + ChannelEdit on=off;on.enabled=true; + valid(logical.edit(logical.revision(), + std::span{&on,1}).accepted()); + valid(logical.roster().find(backing)->sends.back().enabled && + logical.roster().find(backing)->sends.back().edgeId==sendEdge); + // 4) SOURCE ONLY removes primary MAIN but leaves the strip and // its explicit parallel SEND. Removing the last send keeps the channel. ChannelEdit sourceOnly; @@ -124,6 +159,9 @@ int main() { ChannelEdit gain;gain.kind=ChannelEdit::Kind::setFader; gain.id=backing;gain.value=.5f; settings.push_back(gain); + ChannelEdit trim;trim.kind=ChannelEdit::Kind::setInputGain; + trim.id=backing;trim.value=2.f; + settings.push_back(trim); ChannelEdit pan;pan.kind=ChannelEdit::Kind::setPan; pan.id=backing;pan.value=-.2f; settings.push_back(pan); @@ -157,7 +195,8 @@ int main() { const auto* row=restored.roster().find(backing); valid(row && row->format==ProcessingFormat::mono && std::abs(row->faderLinear-.5f)<1.e-6f && - std::abs(row->pan+.2f)<1.e-6f && row->mute && row->solo && + std::abs(row->pan+.2f)<1.e-6f && row->inputGainLinear==2.f && + row->mute && row->solo && row->insertCatalogIds.size()==1 && row->insertCatalogIds.front()=="armix.builtin.channel-compressor.v1"); From 09bc887c37c4b9f967afb957825a39f507868ff2 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 09:37:34 +0700 Subject: [PATCH 063/140] test(pcm): verify exact-EdgeId SEND ramp and nonlinear pre-FX gain with accepted revisions --- tests/dynamic_accepted_session_test.cpp | 167 ++++++++++++++++++++++++ 1 file changed, 167 insertions(+) diff --git a/tests/dynamic_accepted_session_test.cpp b/tests/dynamic_accepted_session_test.cpp index de60b7740..ccba0566d 100644 --- a/tests/dynamic_accepted_session_test.cpp +++ b/tests/dynamic_accepted_session_test.cpp @@ -29,6 +29,171 @@ static ChannelEdit send(ChannelId from,ChannelId to,float gain,bool pre=false) { e.id=from;e.target=to;e.value=gain;e.preFader=pre;return e; } +// Real PCM SEND ON/OFF: mute one parallel edge without deleting the cable, +// changing its gain/tap, or affecting the source channel's MAIN contribution. +static void verifyPerEdgeSendEnablePcm() { + constexpr std::uint64_t epoch=9422; + DynamicAcceptedSession session; + DynamicGraphRequest req;req.physicalInputs=1;req.maxFrames=64; + const std::array channels{ + add(0,ChannelRole::input,"VOICE"), + add(1,ChannelRole::fxReturn,"WET",ProcessingFormat::stereo), + add(2,ChannelRole::main,"MAIN",ProcessingFormat::stereo) + }; + auto a=session.edit(0,0,channels,req,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 std::array links{ + output(voice,main),output(wet,main),send(voice,wet,.5f,true) + }; + req.sources={{voice,0,-1,false}}; + a=session.edit(1,1,links,req,epoch,epoch,true); + assert(a.ok()); + const auto* row=session.acceptedRoster().find(voice); + assert(row && row->sends.size()==2); + const auto edge=std::find_if(row->sends.begin(),row->sends.end(), + [&](const auto& e){return e.destination==wet && !e.primaryOutput;}); + assert(edge!=row->sends.end() && edge->enabled); + const auto edgeId=edge->edgeId; + std::array input{},l{},r{};input.fill(.5f); + const float* pins[]{input.data()}; + const auto fx=+[](ChannelId,float*,float*,int) noexcept {}; + const auto render=[&](int frames=64){ + return session.render(epoch,pins,1,l.data(),r.data(),frames,false,fx); + }; + assert(render()); + const float withSend=l[63]; + assert(withSend>.35f); + ChannelEdit off;off.kind=ChannelEdit::Kind::setSendEnabled; + off.id=voice;off.sendEdgeId=edgeId;off.enabled=false; + const std::array disable{off}; + a=session.edit(2,2,disable,req,epoch,epoch,true); + assert(a.ok() && a.graphRevision==3); + row=session.acceptedRoster().find(voice); + const auto offEdge=std::find_if(row->sends.begin(),row->sends.end(), + [&](const auto& e){return e.edgeId==edgeId;}); + assert(offEdge!=row->sends.end() && !offEdge->enabled && + offEdge->gain==.5f && offEdge->preFader); + // Disabled SEND stores its prior gain; no accidental auto-enable. + assert(session.acceptedRoster().find(voice)->sends.back().gain==.5f); + assert(render()); + const float withoutSend=l[63]; + assert(withoutSend>.1f && withoutSend enable{on}; + a=session.edit(3,3,enable,req,epoch,epoch,true); + assert(a.ok() && a.graphRevision==4); + row=session.acceptedRoster().find(voice); + const auto onEdge=std::find_if(row->sends.begin(),row->sends.end(), + [&](const auto& e){return e.edgeId==edgeId;}); + assert(onEdge!=row->sends.end() && onEdge->enabled && + onEdge->gain==.5f && onEdge->preFader); + assert(render() && near(l[63],withSend,1e-4f)); + // Toggle the same EdgeId LIVE without a graph revision or WIRE removal. + assert(!session.setLiveSendEnabled(epoch-1,4,voice,edgeId,false)); + assert(!session.setLiveSendEnabled(epoch,3,voice,edgeId,false)); + assert(session.setLiveSendEnabled(epoch,4,voice,edgeId,false)); + assert(session.acceptedGraphRevision()==4); + assert(!session.acceptedRoster().find(voice)->sends.back().enabled); + const auto* accepted=session.acceptedRouting(epoch,4); + assert(accepted); + const auto routingEdge=std::find_if(accepted->edges.begin(),accepted->edges.end(), + [&](const auto& e){return e.edgeId==edgeId;}); + assert(routingEdge!=accepted->edges.end() && !routingEdge->enabled); + // Disabled SEND stores its prior gain; no accidental auto-enable. + assert(session.acceptedRoster().find(voice)->sends.back().gain==.5f); + assert(render(4)); + const float liveOff=l[3]; + assert(liveOff>withoutSend && liveOffsends.back().enabled); + assert(render(4) && l[3]>withoutSend && l[3].01f && truePre post{retap}; + a=session.edit(4,4,post,req,epoch,epoch,true); + assert(a.ok() && a.graphRevision==5); + row=session.acceptedRoster().find(voice); + const auto moved=std::find_if(row->sends.begin(),row->sends.end(), + [&](const auto& e){return e.edgeId==edgeId;}); + assert(moved!=row->sends.end() && !moved->preFader && + moved->enabled && moved->gain==.5f); + assert(render() && near(l[63],0.f,1e-5f)); + // Reject primary tap edits and keep the accepted revision/audio intact. + const auto primary=std::find_if(row->sends.begin(),row->sends.end(), + [&](const auto& e){return e.primaryOutput;}); + assert(primary!=row->sends.end()); + retap.sendEdgeId=primary->edgeId;retap.preFader=true; + const std::array illegal{retap}; + a=session.edit(5,5,illegal,req,epoch,epoch,true); + assert(!a.ok() && session.acceptedGraphRevision()==5); + assert(render() && near(l[63],0.f,1e-5f)); + session.unpublish();session.pollRetirement(); +} + +// Digital input trim must precede nonlinear FX, with callback-continuous +// sample smoothing and a stable ChannelId during live parameter changes. +static void verifyDigitalInputGainBeforeFxPcm() { + constexpr std::uint64_t epoch=9442; + DynamicAcceptedSession session; + DynamicGraphRequest req;req.physicalInputs=1;req.maxFrames=64; + const std::array setup{ + add(0,ChannelRole::input,"MIC"), + add(1,ChannelRole::main,"MAIN",ProcessingFormat::stereo) + }; + auto a=session.edit(0,0,setup,req,epoch,epoch,true); + assert(a.ok()); + const auto mic=a.edit.createdIds[0]; + const auto main=a.edit.createdIds[1]; + const std::array link{output(mic,main)}; + req.sources={{mic,0,-1,false}}; + a=session.edit(1,1,link,req,epoch,epoch,true); + assert(a.ok()); + std::array input{},l{},r{};input.fill(.25f); + const float* pins[]{input.data()}; + const auto square=[&](ChannelId ch,float* left,float* right,int n) noexcept { + if(ch!=mic)return; + for(int i=0;iinputGainLinear==2.f); + assert(render(4)); + assert(l[3]>original && l[3] change{rename}; + a=session.edit(2,2,change,req,epoch,epoch,true); + assert(a.ok() && session.acceptedRoster().find(mic)->inputGainLinear==2.f); + assert(render(64)); + assert(near(l[63],original*4.f,1e-4f)); + session.unpublish();session.pollRetirement(); +} + static void verifyRealtimeSlewAndNativeChannelIdContinuousControls() { using armix::dsp::RealtimeSlew64; // Sub-64 variable callbacks must not finish a 64-sample gesture in 4 @@ -919,6 +1084,8 @@ int main() { verifyConsoleWirePrimaryOutputPcm(); verifyRealtimeSlewAndNativeChannelIdContinuousControls(); + verifyPerEdgeSendEnablePcm(); + verifyDigitalInputGainBeforeFxPcm(); constexpr std::uint64_t epoch=77; constexpr float center=.7071067811865475f; DynamicAcceptedSession session; From c349388e0f3ba8625dc914460eb52e1a67eac581 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 09:37:45 +0700 Subject: [PATCH 064/140] ci(sof): compile and execute deterministic native PCM regressions in fast Linux job --- .github/workflows/logical-mixer-fast.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.github/workflows/logical-mixer-fast.yml b/.github/workflows/logical-mixer-fast.yml index d0621622d..0313dc7cf 100644 --- a/.github/workflows/logical-mixer-fast.yml +++ b/.github/workflows/logical-mixer-fast.yml @@ -4,6 +4,10 @@ on: paths: - 'engine/core/DeviceIndependentMixerSession.h' - 'engine/core/DynamicChannelRoster.h' + - 'engine/core/DynamicPreparedMixerBlock.h' + - 'engine/core/DynamicAcceptedSession.h' + - 'engine/core/DynamicNativeSessionPublisher.h' + - 'tests/dynamic_accepted_session_test.cpp' - 'tests/device_independent_mixer_session_test.cpp' - '.github/workflows/logical-mixer-fast.yml' workflow_dispatch: @@ -19,3 +23,9 @@ jobs: tests/device_independent_mixer_session_test.cpp \ -o /tmp/arsonmix-logical-test /tmp/arsonmix-logical-test + - name: Compile and run native PCM gain, PRE/POST and SEND regressions (no JUCE) + run: | + c++ -std=c++20 -O1 -Wall -Wextra -Werror -I. \ + tests/dynamic_accepted_session_test.cpp \ + -o /tmp/arsonmix-dynamic-pcm-test + /tmp/arsonmix-dynamic-pcm-test From e3b27962e65cd0b1c98ec4285b40e7365b7d831c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:06:56 +0700 Subject: [PATCH 065/140] fix(sof): one native EdgeId SET_TAP path for WIRE inspector and SOF; disambiguate PRE_FX --- web/approved-native-bridge.js | 49 ++++++++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 7 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index ed554e3d8..ab7831212 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -404,6 +404,29 @@ else window.setTimeout(()=>controller?.expire(result.requestId),8000); return result.ok; }; + // One accepted EdgeId/tap command shared by SOF and the WIRE inspector. + // A typed SET_TAP recompiles the existing PCM graph; neither GUI may + // repaint PRE/POST until the subsequent independent accepted readback. + function requestNativeTap(source,edgeId,tap){ + const state=controller?.state(),current=state?.current; + if(!current?.admitted||current.retained||state.pending|| + !current.graph.capabilities.supportedOps.includes("APPLY_WIRE_TRANSACTION")|| + !source||!edgeId||!["PRE_FADER","POST_FADER"].includes(tap)){ + status("PRE/POST unavailable · wait for an admitted native WIRE");return false; + } + const matches=current.graph.edges.filter(e=>e.enabled&&e.edgeId===edgeId&& + e.from===source&&e.primaryOutput===false); + if(matches.length!==1||!["PRE_FADER","POST_FADER"].includes(matches[0].tap)){ + status("PRE/POST unavailable · selected send identity changed");return false; + } + if(matches[0].tap===tap)return true; + const result=controller.intent("APPLY_WIRE_TRANSACTION",source,{changes:[{ + op:"SET_TAP",from:source,edgeId,tap + }]}); + if(!result.ok){status("PRE/POST unchanged · "+result.error);return false;} + window.setTimeout(()=>controller?.expire(result.requestId),8000); + return true; + } function selectedNativeSofEdge(t) { if(!scope?.sofEnabled||!t||t.kind!=="audio")return null; const current=controller?.state()?.current,source=nativeIdFor(t); @@ -514,10 +537,13 @@ const isMain=edge.to===accepted.mainChannelId; const isPrimary=source?.primaryOutId===edge.to; // An independent SEND to MAIN is not the source's primary OUT. - const kind=isPrimary?"primary":edge.tap==="SPLIT_PRE"||edge.tap==="SPLIT_POST"?"split":"send"; + // Explicit native tapStage disambiguates legacy PRE_FX SPLIT_PRE from + // real post-FX PRE_FADER. The reference 'split' mode means PRE_FX only. + const tap=["PRE_FADER","POST_FADER"].includes(edge.tapStage)?edge.tapStage:edge.tap; + const legacySplit=tap==="SPLIT_PRE"||tap==="SPLIT_POST"; + const kind=isPrimary?"primary":legacySplit?"split":"send"; const mode=isMain?(isPrimary?"postFader":"send"):kind==="primary"?"routeOnly": - kind==="split"?(edge.tap==="SPLIT_PRE"?"splitPre":"splitPost"): - edge.tap==="PRE_FADER"?"split":"send"; + legacySplit?(tap==="SPLIT_PRE"?"splitPre":"splitPost"):"send"; if (isPrimary && edge.gainLinear!==1) return false; const gainDb=isPrimary?0:Math.round(Math.max(-60,Math.min(6, edge.gainLinear>0?20*Math.log10(edge.gainLinear):-60))*10)/10; @@ -526,7 +552,7 @@ newWireByUi.set(uiId,edge.edgeId); newUiByWire.set(edge.edgeId,uiId); edges.push({id:uiId,sourceId:src,destId:dst,kind,mode, - nativeTap:edge.tap,sendEnabled:edge.sendEnabled!==false, + nativeTap:tap,sendEnabled:edge.sendEnabled!==false, enabled:true,levelDb:gainDb}); } if (!scope.wireGraph.validateCandidateGraph(nextTracks,nextMaster.id,edges).ok) return false; @@ -3477,9 +3503,7 @@ return true; } const next=target.tap==="PRE_FADER"?"POST_FADER":"PRE_FADER"; - intent("APPLY_WIRE_TRANSACTION",t,{changes:[{ - op:"SET_TAP",from:id,edgeId:target.edgeId,tap:next - }]}); + requestNativeTap(id,target.edgeId,next); return true; } if(action==="sofOn"){ @@ -3648,6 +3672,17 @@ nativeToast("WIRE not saved · previous routing retained"); return true; } + // The inspector's legacy MODE gesture is only a presentation gesture. + // Map it to one real installed PRE_FADER/POST_FADER EdgeId transaction; + // never queue/replay it as a startup wire or mutate a demo graph. + if(Array.isArray(ops)&&ops.length===1&&ops[0].type==="MODE"){ + const op=ops[0]; + const source=nativeByUiId.get(op.sourceId),edgeId=wireByUiId.get(op.edgeId); + const tap=op.mode==="split"?"PRE_FADER": + op.mode==="send"?"POST_FADER":null; + requestNativeTap(source,edgeId,tap); + return true; + } const state=controller?.state(); // A first drag may arrive before SOURCE's later accepted snapshot. // Preserve that one operator intent; resolve only against fresh native From 0aa950a1d6eb91e21546c0c5e0fae34b6d21f7e2 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:07:48 +0700 Subject: [PATCH 066/140] fix(gui): real PRE-FADER in WIRE inspector with fail-closed native tap admission --- site/preview-v2/index.html | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index 41607dc3d..2a1058a83 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -652,7 +652,12 @@ let label='',status=''; if(isSource){label='SOURCE';status='⇢ '+wireOutgoingCount(t.id)+' OUT';} else if(t.kind==='master'){label='MAIN';status=source&&wireFor(source.id,master.id)?'DIRECT ON':'DIRECT OFF';} - else if(edge){label='IN ← CH'+String(source.id).padStart(2,'0');status=edge.mode==='split'?'PRE FX':'POST FADER';} + else if(edge){ + label='IN ← CH'+String(source.id).padStart(2,'0'); + status=edge.nativeTap==='PRE_FADER'?'PRE FADER': + edge.nativeTap==='POST_FADER'?'POST FADER': + edge.mode==='split'?'PRE FX':'POST FADER'; + } else if(legacy){label='LEGACY';status='SEND ACTIVE';} else if(t.kind==='bus')label='BUS'; else if(t.kind==='fx')label='FX RETURN'; @@ -1267,14 +1272,23 @@ const src=tracks.find(t=>t.id===p.src),dst=tracks.concat(master).find(t=>t.id===p.dst); if(!src||!dst){panel.hidden=true;return;} const edge=info.edge,key=p.src+':'+p.dst; + const native=!!window.__JUCE__?.backend; + const tapValue=edge?.nativeTap==='PRE_FADER'?'split': + edge?.nativeTap==='POST_FADER'?'send':edge?.mode; + const tapEditable=!native||(src.nativeTapAvailable===true&& + edge?.kind==='send'&&['PRE_FADER','POST_FADER'].includes(edge.nativeTap)); const controls=edge? - '
'+ + '
'+ ''+ ''+edge.levelDb+' dB'+ ''+ - ''+ + ''+ '
': '
Managed by existing '+escapeHtml(info.kind.toUpperCase())+' routing. No duplicate WIRE edge.
'; panel.innerHTML=''+escapeHtml(wireWsLabel(p.src))+' → '+escapeHtml(wireWsLabel(p.dst))+''+ From aa92c4420d7b121c0dc72d2573d918ca6bb4e769 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:09:05 +0700 Subject: [PATCH 067/140] test(sof): native inspector PRE/POST intent, ACK/readback, and rejected tap rollback --- tests/approved_native_m2_contract.test.cjs | 59 ++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 875119210..f459d364c 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -27,6 +27,46 @@ function acceptedFixture(){ tap:"POST",gainLinear:1,enabled:true,signalKind:"AUDIO"}]; return s; } +test("native PRE_FADER WIRE inspector uses one exact SET_TAP PCM intent and accepted readback",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const preview=read("site/preview-v2/index.html"); + assert.match(bridge,/function requestNativeTap\(source,edgeId,tap\)/); + assert.match(bridge,/ops\[0\]\.type==="MODE"/); + assert.match(bridge,/op:"SET_TAP",from:source,edgeId,tap/); + assert.match(bridge,/const tap=\["PRE_FADER","POST_FADER"\]\.includes\(edge\.tapStage\)/); + assert.match(preview,/edge\.nativeTap==='PRE_FADER'\?'PRE FADER'/); + assert.match(preview,/edge\.nativeTap==='PRE_FADER'\?'split'/); + assert.match(preview,/native\?'PRE FADER':'Pre FX'/); + const s=acceptedFixture(),source=s.graph.channels[0].id; + const bus={id:"9007199254740999",role:"GROUP",name:"BUS B",processingFormat:"STEREO", + controls:{faderDb:0,pan:0,mute:false,solo:false},inserts:[],sends:[]}; + s.graph.channels.splice(1,0,bus); + s.graph.destinations.push({id:bus.id,role:"GROUP"}); + delete s.graph.channels[0].primaryOutId; + s.graph.edges[0]={edgeId:"9223372036854775808",from:source,to:bus.id, + tap:"POST_FADER",gainLinear:.5,enabled:true,sendEnabled:true, + primaryOutput:false,signalKind:"AUDIO"}; + const sent=[],c=protocol.createController({emit:(event,payload)=>sent.push({event,payload})}); + assert.equal(c.onSnapshot(clone(s)),true); + const change={op:"SET_TAP",from:source,edgeId:s.graph.edges[0].edgeId,tap:"PRE_FADER"}; + const t=c.intent("APPLY_WIRE_TRANSACTION",source,{changes:[change]}); + assert.equal(t.ok,true); + assert.deepEqual(sent.at(-1).payload.payload.changes,[change]); + assert.equal(c.state().current.graph.edges[0].tap,"POST_FADER"); + assert.equal(c.onAck({requestId:t.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:s.device.epoch,graphRevision:"6",rosterRevision:"8"}),true); + assert.equal(c.state().current.graph.edges[0].tap,"POST_FADER", + "ACK alone cannot repaint a PRE_FADER send"); + const next=clone(s);next.graph.revision="6";next.graph.rosterRevision="8"; + next.graph.edges[0].tap="PRE_FADER"; + assert.equal(c.onSnapshot(next),true); + assert.equal(c.state().pending,null); + assert.equal(c.state().current.graph.edges[0].tap,"PRE_FADER"); + assert.equal(c.state().current.graph.edges[0].edgeId,change.edgeId); + assert.equal(c.state().current.graph.edges[0].gainLinear,.5); + assert.equal(c.state().current.graph.edges[0].sendEnabled,true); +}); + test("native input Gain is a separate ChannelId scalar proven only by ACK plus inputGain readback",()=>{ const s=acceptedFixture(),id=s.graph.channels[0].id; s.graph.capabilities.supportedOps.push("SET_INPUT_GAIN"); @@ -1233,6 +1273,25 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a listeners.get("arMixConsoleSnapshot")(gained); assert.equal(scope.edges[0].levelDb,-12); assert.equal(paints,paintBeforeGain); + // WIRE inspector MODE is a legacy visual gesture. It MUST become one + // exact native SET_TAP EdgeId transaction; rejection leaves the PCM tap intact. + const tapUi=scope.edges[0].id; + assert.equal(window.__ARMIX_NATIVE_M2__.consumeWire([{ + type:"MODE",sourceId:sourceUi,edgeId:tapUi,mode:"split" + }]),true); + const tapRequest=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; + assert.equal(tapRequest.operation,"APPLY_WIRE_TRANSACTION"); + assert.deepEqual(tapRequest.payload.changes,[{ + op:"SET_TAP",from:routed.graph.channels[0].id, + edgeId:"9223372036854775810",tap:"PRE_FADER" + }]); + assert.equal(scope.edges[0].nativeTap,"POST_FADER"); + listeners.get("arMixConsoleAck")({requestId:tapRequest.requestId,status:"REJECTED", + errorCode:"NATIVE_WIRE_TRANSACTION_REJECTED",deviceEpoch:gained.device.epoch, + graphRevision:"8",rosterRevision:"8"}); + assert.equal(window.__ARMIX_NATIVE_M2__.state().pending,null); + assert.equal(scope.edges[0].nativeTap,"POST_FADER", + "rejected native tap must restore the last accepted PCM stage"); // OUT uses the same actual INPUT destination as WIRE, not a name-only // GROUP lookup. An exclusive route promotes the existing native edge. const hooks=window.__ARMIX_NATIVE_M2__,sourceTrack=scope.tracks[0]; From 95febc608b570c0a6d05d84fa68e957e768e9bc7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:10:45 +0700 Subject: [PATCH 068/140] test(sof): compare cross-VM native intents as JSON and match optional-chain tap field --- tests/approved_native_m2_contract.test.cjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index f459d364c..fc5bdb022 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -35,7 +35,7 @@ test("native PRE_FADER WIRE inspector uses one exact SET_TAP PCM intent and acce assert.match(bridge,/op:"SET_TAP",from:source,edgeId,tap/); assert.match(bridge,/const tap=\["PRE_FADER","POST_FADER"\]\.includes\(edge\.tapStage\)/); assert.match(preview,/edge\.nativeTap==='PRE_FADER'\?'PRE FADER'/); - assert.match(preview,/edge\.nativeTap==='PRE_FADER'\?'split'/); + assert.match(preview,/edge\?\.nativeTap==='PRE_FADER'\?'split'/); assert.match(preview,/native\?'PRE FADER':'Pre FX'/); const s=acceptedFixture(),source=s.graph.channels[0].id; const bus={id:"9007199254740999",role:"GROUP",name:"BUS B",processingFormat:"STEREO", @@ -1281,7 +1281,7 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a }]),true); const tapRequest=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; assert.equal(tapRequest.operation,"APPLY_WIRE_TRANSACTION"); - assert.deepEqual(tapRequest.payload.changes,[{ + assert.deepEqual(JSON.parse(JSON.stringify(tapRequest.payload.changes)),[{ op:"SET_TAP",from:routed.graph.channels[0].id, edgeId:"9223372036854775810",tap:"PRE_FADER" }]); From ce7c65863fbe50062575d6157d290228236f536a Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:15:31 +0700 Subject: [PATCH 069/140] feat(sonku-v2): fixed-memory directional image-source early reflections A/B seam --- .../builtin_fx/sonku/SonKuEarlyReflections.h | 156 ++++++++++++++++++ engine/builtin_fx/sonku/SonKuSpatialCore.h | 16 +- 2 files changed, 170 insertions(+), 2 deletions(-) create mode 100644 engine/builtin_fx/sonku/SonKuEarlyReflections.h diff --git a/engine/builtin_fx/sonku/SonKuEarlyReflections.h b/engine/builtin_fx/sonku/SonKuEarlyReflections.h new file mode 100644 index 000000000..73db9ebdb --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuEarlyReflections.h @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include + +// Bounded, first-order image-source room for headphone externalization trials. +// Reflection image geometry follows Allen & Berkley (JASA, 1979), not +// randomized stereo delays. The ears use lightweight ITD/ILD approximation; +// this is NOT an HRTF-convolved reflection / arbitrary geometry simulation. +// No allocation, locks, worker, I/O, FFT or second device callback. +namespace armix::sonku { +class SonKuEarlyReflections final { +public: + struct Ears {float left=0.f,right=0.f;}; + static constexpr int wallCount=4; + static constexpr int sourceCount=2; + static constexpr int ringFrames=8192; + static constexpr int geometryInterval=64; + bool prepare(double rate) noexcept { + ready_=false; + if(!std::isfinite(rate) || (std::abs(rate-44100.)>.1 && + std::abs(rate-48000.)>.1))return false; + rate_=static_cast(rate); + delaySlew_=static_cast(1.-std::exp(-1./(rate*0.024))); + gainSlew_=static_cast(1.-std::exp(-1./(rate*0.012))); + amountSlew_=static_cast(1.-std::exp(-1./(rate*0.010))); + reset(); + ready_=true; + return true; + } + void reset() noexcept { + for(auto& h:history_)h.fill(0.f); + lowpass_.fill(0.f); + for(auto& paths:tap_)for(auto& p:paths)p=Tap{}; + write_=0;untilGeometry_=0;primed_=false; + amount_=0.f; + } + // Deliberately experimental and OFF by default. Legacy 8/8 direction + // baseline stays bit-identical. A/B is set on an unpublished/offline core + // until headphone, CPU and device gates approve native publication. + bool setAmount(float value) noexcept { + if(!std::isfinite(value)||value<0.f||value>1.f)return false; + if(amountTarget_==0.f&&amount_==0.f&&value>0.f)reset(); + amountTarget_=value; + return true; + } + bool active() const noexcept {return ready_&&(amount_>0.f||amountTarget_>0.f);} + float targetAmount() const noexcept {return amountTarget_;} + Ears process(float left,float right,double azimuth,float spread) noexcept { + if(!active())return {}; + constexpr std::array dummy{}; (void)dummy; + if(untilGeometry_==0){ + updateGeometry(azimuth,spread); + untilGeometry_=geometryInterval; + } + const float x[2]{std::isfinite(left)?left:0.f, + std::isfinite(right)?right:0.f}; + for(int s=0;s(ringFrames-3)); + const int integer=static_cast(bounded); + const float fract=bounded-static_cast(integer); + const int i0=(write_-integer)&(ringFrames-1); + const int i1=(i0-1)&(ringFrames-1); + return history_[source][i0]*(1.f-fract)+history_[source][i1]*fract; + } + void updateGeometry(double azimuth,float spread) noexcept { + constexpr float pi=3.14159265358979323846f; + constexpr float sourceDistance=1.60f; // meters + constexpr float halfWidth=3.20f,halfDepth=4.00f; + constexpr float speedOfSound=343.f; + constexpr float earHalfTime=.00031f; // max +/-0.31ms + constexpr std::array walls{.74f,.74f,.67f,.67f}; + for(int source=0;source(azimuth) + +(source==0?-.5f:.5f)*spread; + const float rad=degrees*(pi/180.f); + const float sx=sourceDistance*std::sin(rad); + const float sy=sourceDistance*std::cos(rad); + const std::array,wallCount> images{{ + {{-2.f*halfWidth-sx,sy}},{{2.f*halfWidth-sx,sy}}, + {{sx,2.f*halfDepth-sy}},{{sx,-2.f*halfDepth-sy}} + }}; + for(int wall=0;wall(ringFrames-3)); + tap.targetDelayR=std::clamp(common-earDelta,1.f, + static_cast(ringFrames-3)); + tap.targetGainL=level*(1.f-.13f*directionX); + tap.targetGainR=level*(1.f+.13f*directionX); + if(!primed_){ + tap.delayL=tap.targetDelayL; + tap.delayR=tap.targetDelayR; + tap.gainL=tap.targetGainL; + tap.gainR=tap.targetGainR; + } + } + } + primed_=true; + } + static_assert((ringFrames&(ringFrames-1))==0); + std::array,sourceCount> history_{}; + std::array,sourceCount> tap_{}; + std::array lowpass_{}; + float rate_=0.f,delaySlew_=0.f,gainSlew_=0.f,amountSlew_=0.f; + float amount_=0.f,amountTarget_=0.f; + int write_=0,untilGeometry_=0; + bool ready_=false,primed_=false; +}; +} // namespace armix::sonku diff --git a/engine/builtin_fx/sonku/SonKuSpatialCore.h b/engine/builtin_fx/sonku/SonKuSpatialCore.h index 5e4484694..a99a0c5d0 100644 --- a/engine/builtin_fx/sonku/SonKuSpatialCore.h +++ b/engine/builtin_fx/sonku/SonKuSpatialCore.h @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only #pragma once #include "SonKuMeasuredHrir.h" +#include "SonKuEarlyReflections.h" #include #include #include @@ -48,6 +49,7 @@ class SonKuSpatialCore final { // without trigonometric/exponential work in the audio callback. filterSlew_=static_cast(1.-std::exp(-1./(rate*0.006))); levelSlew_=static_cast(1.-std::exp(-1./(rate*0.008))); + if(!room_.prepare(rate))return false; reset(); ready_=true; return true; @@ -62,6 +64,7 @@ class SonKuSpatialCore final { remaining_=0; degrees_=wrapDegrees(settings_.startAzimuthDegrees); haveKernel_=false; + room_.reset(); } bool setSettings(const Settings& s) noexcept { if(!valid(s))return false; @@ -75,6 +78,11 @@ class SonKuSpatialCore final { return true; } Settings settings() const noexcept {return settings_;} + // A/B-only control pending room's headphone/device qualification. + // Legacy live insert remains room-free until product evidence is accepted. + bool setEarlyReflectionsAmount(float amount) noexcept { + return room_.setAmount(amount); + } bool ready() const noexcept {return ready_;} double azimuthDegrees() const noexcept {return degrees_;} // In-place stereo; caller owns valid, non-overlapping L/R PCM pointers. @@ -121,8 +129,11 @@ class SonKuSpatialCore final { ears[0]+=v0*l0+v1*l1; ears[1]+=v0*r0+v1*r1; } - left[i]=dryLevel*x0+binauralLevel*ears[0]; - right[i]=dryLevel*x1+binauralLevel*ears[1]; + const auto reflection=room_.active() + ?room_.process(x0,x1,degrees_,settings_.stereoSpreadDegrees) + :SonKuEarlyReflections::Ears{}; + left[i]=dryLevel*x0+binauralLevel*(ears[0]+reflection.left); + right[i]=dryLevel*x1+binauralLevel*(ears[1]+reflection.right); if(++write_==taps)write_=0; if(step!=0.) { degrees_+=step; @@ -168,6 +179,7 @@ class SonKuSpatialCore final { std::array,2>,2> kernels_{}; std::array,2>,2> targets_{}; Settings settings_{}; + SonKuEarlyReflections room_{}; float smoothedMix_=1.f,smoothedTrim_=0.75f; float filterSlew_=0.f,levelSlew_=0.f; double sampleRate_=0.; From b6df9a08977aa6c31e280b45928917b363d8ec70 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:17:49 +0700 Subject: [PATCH 070/140] test(sonku-v2): A/B identical-source WAVs, PCM parity and exact-causality room gates --- .github/workflows/ui-smoke.yml | 2 + .../builtin_fx/sonku/SonKuEarlyReflections.h | 1 - tests/sonku_early_reflections_test.cpp | 48 +++++++++++++++++++ tests/sonku_offline_demo_contract.py | 10 ++++ tests/sonku_spatial_core_test.cpp | 32 +++++++++++++ tools/sonku_offline_listening.cpp | 23 +++++++-- 6 files changed, 112 insertions(+), 4 deletions(-) create mode 100644 tests/sonku_early_reflections_test.cpp diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index f4cb2d561..c5cba742f 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -213,6 +213,8 @@ jobs: run: | g++ -std=c++20 -O2 -Wall -Wextra -pedantic tools/sonku_offline_listening.cpp -o /tmp/sonku-listening /tmp/sonku-listening sonku-listening + g++ -std=c++20 -O2 -Wall -Wextra -pedantic tests/sonku_early_reflections_test.cpp -o /tmp/sonku-room-test + /tmp/sonku-room-test python tests/sonku_offline_demo_contract.py sonku-listening - name: Publish 8D-SonKu reproducible listening WAVs and blind answer key if: ${{ always() }} diff --git a/engine/builtin_fx/sonku/SonKuEarlyReflections.h b/engine/builtin_fx/sonku/SonKuEarlyReflections.h index 73db9ebdb..8bdc3172a 100644 --- a/engine/builtin_fx/sonku/SonKuEarlyReflections.h +++ b/engine/builtin_fx/sonku/SonKuEarlyReflections.h @@ -50,7 +50,6 @@ class SonKuEarlyReflections final { float targetAmount() const noexcept {return amountTarget_;} Ears process(float left,float right,double azimuth,float spread) noexcept { if(!active())return {}; - constexpr std::array dummy{}; (void)dummy; if(untilGeometry_==0){ updateGeometry(azimuth,spread); untilGeometry_=geometryInterval; diff --git a/tests/sonku_early_reflections_test.cpp b/tests/sonku_early_reflections_test.cpp new file mode 100644 index 000000000..5edd9b7f9 --- /dev/null +++ b/tests/sonku_early_reflections_test.cpp @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#if defined(NDEBUG) +#undef NDEBUG +#endif +#include "../engine/builtin_fx/sonku/SonKuEarlyReflections.h" +#include +#include +#include +#include +int main(){ + using armix::sonku::SonKuEarlyReflections; + SonKuEarlyReflections invalid; + assert(!invalid.prepare(96000.)); + assert(!invalid.prepare(std::numeric_limits::quiet_NaN())); + for(double rate:{44100.,48000.}){ + SonKuEarlyReflections a,b; + assert(a.prepare(rate)&&b.prepare(rate)); + assert(!a.active()); + assert(!a.setAmount(-.01f)); + assert(!a.setAmount(std::numeric_limits::infinity())); + assert(a.setAmount(.55f)&&b.setAmount(.55f)); + double echo=0.,earDifference=0.; + constexpr int count=4096; + for(int i=0;i180){ + echo+=std::abs(x.left)+std::abs(x.right); + earDifference+=std::abs(x.left-x.right); + } + } + assert(echo>.004 && earDifference>.001); + // Switching the optional room off must settle to bit-exact silence; + // the dry measured HRTF never borrows anything from stale room state. + assert(a.setAmount(0.f)); + for(int i=0;i<6000;++i){ + auto tail=a.process(0.f,0.f,180.,0.f); + if(i>5000)assert(tail.left==0.f&&tail.right==0.f); + } + assert(!a.active()); + } + return 0; +} diff --git a/tests/sonku_offline_demo_contract.py b/tests/sonku_offline_demo_contract.py index d8fb941d1..07ad8f4e1 100644 --- a/tests/sonku_offline_demo_contract.py +++ b/tests/sonku_offline_demo_contract.py @@ -24,6 +24,16 @@ def read(name, frames): single=read("sonku-reference-four.wav",4*120000) blind=read("sonku-blind-eight.wav",8*120000) orbit=read("sonku-orbit-cw.wav",480000) +v2four=read("sonku-v2-room-four.wav",4*120000) +v2orbit=read("sonku-v2-room-orbit-cw.wav",480000) +# Baseline V1 and candidate V2 are deliberately non-identical on same noise. +# Room must affect later samples, not fake position on the direct sound. +difference=sum(abs(int(a)-int(b)) for a,b in + zip(v2four[70000:200000],single[70000:200000])) +assert difference>1500,("V2 room candidate did not affect PCM",difference) +orbitDelta=sum(abs(int(a)-int(b)) for a,b in + zip(v2orbit[70000:200000],orbit[70000:200000])) +assert orbitDelta>1500,("V2 moving room candidate did not affect PCM",orbitDelta) # +90° (second reference segment) has a distinct binaural response. section=single[120000*2:120000*4] left=sum(abs(section[i]) for i in range(0,len(section),2)) diff --git a/tests/sonku_spatial_core_test.cpp b/tests/sonku_spatial_core_test.cpp index 57df5208c..d70ff4988 100644 --- a/tests/sonku_spatial_core_test.cpp +++ b/tests/sonku_spatial_core_test.cpp @@ -78,6 +78,38 @@ int main() { assert(std::abs(oneR[i]-chunkR[i])<1.e-6f); } assert(std::abs(whole.azimuthDegrees()-chunked.azimuthDegrees())<1.e-10); + // V2 A/B: room OFF is the verified original renderer; room ON + // produces only delayed acoustic energy, without modifying first + // arrival, direction signs or host buffer partition behavior. + constexpr int roomFrames=4096; + std::array noL{},noR{},wetL{},wetR{},partL{},partR{}; + noL[0]=wetL[0]=partL[0]=.5f; + noR[0]=wetR[0]=partR[0]=.5f; + SonKuSpatialCore noRoom,withRoom,partRoom; + assert(noRoom.prepare(rate)&&withRoom.prepare(rate)&&partRoom.prepare(rate)); + Settings roomSettings=s;roomSettings.startAzimuthDegrees=0.f; + assert(noRoom.setSettings(roomSettings)&&withRoom.setSettings(roomSettings) + &&partRoom.setSettings(roomSettings)); + assert(withRoom.setEarlyReflectionsAmount(.55f)); + assert(partRoom.setEarlyReflectionsAmount(.55f)); + noRoom.process(noL.data(),noR.data(),roomFrames); + withRoom.process(wetL.data(),wetR.data(),roomFrames); + partRoom.process(partL.data(),partR.data(),128); + partRoom.process(partL.data()+128,partR.data()+128,384); + partRoom.process(partL.data()+512,partR.data()+512,roomFrames-512); + double roomDifference=0.; + for(int i=0;i180)roomDifference+=std::abs(wetL[i]-noL[i])+ + std::abs(wetR[i]-noR[i]); + } + assert(roomDifference>.001); // A hard FRONT->REAR teleport must not replace 560 FIR coefficients // at the next 16-sample boundary. Compare the identical dry/PCM // history before and immediately after reposition. diff --git a/tools/sonku_offline_listening.cpp b/tools/sonku_offline_listening.cpp index 807ca3141..4524af5cf 100644 --- a/tools/sonku_offline_listening.cpp +++ b/tools/sonku_offline_listening.cpp @@ -66,9 +66,11 @@ Settings fixed(float azimuth){ s.stereoSpreadDegrees=0.f;s.spatialMix=1.f;s.outputTrim=.72f; return s; } -std::vector staticProbes(const std::vector& azimuths) { +std::vector staticProbes(const std::vector& azimuths,float roomAmount=0.f) { SonKuSpatialCore dsp;Noise noise; if(!dsp.prepare(rate))throw std::runtime_error("No 48k HRTF"); + if(!dsp.setEarlyReflectionsAmount(roomAmount)) + throw std::runtime_error("Invalid early room amount"); std::vector result; result.reserve(static_cast(azimuths.size())* (activeFrames+silenceFrames)*4); @@ -96,9 +98,11 @@ std::vector staticProbes(const std::vector& azimuths) { } return result; } -std::vector orbit(){ +std::vector orbit(float roomAmount=0.f){ SonKuSpatialCore dsp;Noise noise; if(!dsp.prepare(rate))throw std::runtime_error("No 48k HRTF"); + if(!dsp.setEarlyReflectionsAmount(roomAmount)) + throw std::runtime_error("Invalid orbit room amount"); Settings s=fixed(0.f);s.moving=true;s.clockwise=true;s.revolutionSeconds=10.f; dsp.reset();if(!dsp.setSettings(s))throw std::runtime_error("No 360 orbit"); const int frames=rate*10; @@ -141,7 +145,14 @@ void notes(const std::filesystem::path& directory, <<"sonku-orbit-cw.wav: 10s one continuous 360deg clockwise orbit,\n" <<"starting at FRONT, acoustic RIGHT on listener's right headphone.\n\n" <<"If front/rear is ambiguous or internalized, note headphones and listener.\n" - <<"These are not room reflections, personalized HRTFs or VST3 binaries.\n"; + <<"Baseline SonKu files have no room reflections (V1).\n" + <<"V2 room candidate adds four 1st-order image-source reflections\n" + <<"per emitter (6.4x8m fixed room) with bounded ear delays and level.\n" + <<"sonku-v2-room-four.wav = A/B against sonku-reference-four.wav.\n" + <<"sonku-v2-room-orbit-cw.wav = A/B against sonku-orbit-cw.wav.\n" + <<"Both comparisons reuse exactly the same source noise and direct HRIR.\n" + <<"Do blind-level and externalization evaluation before enabling V2 live.\n" + <<"This is NOT full HRIR-convolved reflections, FDN or personalized HRTF.\n"; std::ofstream key(directory/"BLIND-ANSWER-KEY.txt"); if(!key)throw std::runtime_error("Cannot write blind answer key"); key<<"OPEN ONLY AFTER LISTENING. Exact 2.5-second trial windows:\n"; @@ -160,6 +171,12 @@ int main(int argc,char** argv){ staticProbes({reference.begin(),reference.end()})); writeWav(dir/"sonku-blind-eight.wav",staticProbes(blind)); writeWav(dir/"sonku-orbit-cw.wav",orbit()); + // Only the bounded early-reflection stage changes between paired + // files. Source, directions, KEMAR HRIR, loudness trim and clock are + // identical. Blind front/back listening is the decision gate. + writeWav(dir/"sonku-v2-room-four.wav", + staticProbes({reference.begin(),reference.end()},.55f)); + writeWav(dir/"sonku-v2-room-orbit-cw.wav",orbit(.55f)); notes(dir,blind); std::cout<<"SonKu listening package PASS: measured native HRTF, " <<"4 labeled + 8 blind directions + one 360 orbit\n"; From 2dfc5d4d47b3a7d6c1978c29a92276d1977a3946 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:20:43 +0700 Subject: [PATCH 071/140] docs(sonku-v2): externalization image-source model and gated A/B design --- docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md | 4 +++ docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md | 4 +++ ...KU_V2_EXTERNALIZATION_DECISION_20261113.md | 34 +++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md diff --git a/docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md b/docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md index 56332e885..fc17bc3c1 100644 --- a/docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md +++ b/docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md @@ -151,3 +151,7 @@ This record supersedes the earlier **round/circular stage UI** and radial 2D mar - **No extra renderer or CSS owner**: add to existing one /preview/ editor and existing `mixer-fx-rack.css`, maintaining exactly 18 CSS owner links. No WebAudio, DSP JS clone, extra callback or CPU-intensive continuous 3D scene. - **Verification evidence**: Chromium assembled native GUI two viewport screenshots, actual FX picker insertion and ACK/readback, four acoustic directions, front/rear painter order, both monitors visible at 0° spread, real mouse drag to FRONT, rotary drag with one typed native request. Exact SHA `4652a744ab4ae01b1ceca58bb6c3d7e372eb420a`, [UI run](https://github.com/masarray/arsonmix/actions/runs/43342451656), [two screenshots](https://github.com/masarray/arsonmix/actions/runs/43342451656/artifacts/13999089726). - **Release gate**: browser FAT uses simulated JUCE events. It is not physical binaural localization or installed Windows/ASIO FAT, and the PR must be reconciled with advancing `main` before any public release. + + +## 2026-11-13 — V2 spatial externalization architecture +See docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md. Experimental room processing is opt-in and OFF in native JUCE until qualified with headphone A/B. Fixed bounded image-source early reflections retain the same single PCM authority; future ITD-aligned HRIR implementation is a separate stage. diff --git a/docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md b/docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md index aacb08d2d..c69633c38 100644 --- a/docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md +++ b/docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md @@ -100,3 +100,7 @@ Both L and R studio monitor speakers must remain separately visible and individu The editor must feel like a compact hardware-grade audio plugin, with tactile rotary controls and clear numeric readouts, not large web-style cards or anonymous browser sliders. Rotary pointer gestures must be bounded and single-commit; keyboard focus, range semantics and double-click default restoration remain accessible. Do not imitate or redistribute commercial plugin skins. Acceptance evidence on the real compiled native HTML bundle must cover correct Z-order, actual PNG load, two separately visible monitors at 0° spread, correct four-direction mapping, mouse drag to FRONT, knob edit single native queue/ACK and desktop/narrow screenshots. Do not translate GUI PASS into a claim of verified binaural headphone localization. + + +## 2026-11-13 — perceptual acceptance and UX guardrails +User reports correct 8/8 blind positions and 4/4 known, but insufficient FRONT/REAR distance and uneven perceived motion. Preserve the correct azimuth signs and build same-input, level-checked original-vs-V2 headphone WAVs first. No extra controls or labels before sound is validated. A future SPACE knob must be compact, discoverable and backed by native typed ACK/readback and compatible session migration; default must remain user-test-proven rather than arbitrary reverb. diff --git a/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md new file mode 100644 index 000000000..d7b8375a6 --- /dev/null +++ b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md @@ -0,0 +1,34 @@ +# 8D-SonKu V2 — Externalization & Natural Orbit Architecture +2026-11-13 | Experimental stage M1 | Based on PR #606 baseline + +## Confirmed user observations +- Headphone listener reports correct directions, 4/4 known and 8/8 blind. +- FRONT/REAR are too thin/near-head and motion through both median-plane axes lacks realistic depth. +- This is a perceptual report, NOT a measured distance, CPU benchmark or proof of identical HRTF fit for all listeners. + +## Technical research and prior art (no code or skin copying) +- Allen & Berkley (1979), Image Method for Efficiently Simulating Small-Room Acoustics, JASA 65(4), DOI 10.1121/1.382599 — geometrical mirror-image first-order acoustic paths and time-of-flight. +- Steam Audio core guide: https://github.com/ValveSoftware/steam-audio/blob/master/core/doc/guide.rst — direct binaural HRTF, room reflections and distance effects are separate, testable stages. +- 3D Tune-In Audio Toolkit: https://github.com/3DTune-In/3dti_AudioToolkit — ITD-independent HRIR interpolation and acoustic parallax are mature solutions, *research for later M2*, not implemented here. +- Frontal externalization BRIR study: https://pmc.ncbi.nlm.nih.gov/articles/PMC13451706/ — altered early reflections and direct/reflected ratio can improve front externalization for some listeners, not a guaranteed result on all headphones. + +## Current implementation decision: split M1 from the other acoustic stages +Keep SonKuSpatialCore and native JUCE/PCM graph as one authoritative processor; no new DSP engine, new device callback, JS audio path, thread, blocking call, file access or dynamic callback allocation. Add SonKuEarlyReflections as a fixed-memory, first-order image-source *experimental* room stage. Amount=0 by default and guarantees identical previously qualified native PCM. Amount=.55 generates *offline-only* A/B comparison WAVs using the exact original source samples and direct KEMAR HRIR. Do not publish this as a new default until blind headphone tests support it. + +### Bounded acoustic model (M1) +- Room width 6.4m, depth 8.0m, listener centered, 2 sources at 1.6m rotating on the horizontal ring. +- Four first-order wall images per source (left, right, front, rear), hence eight reflected paths. +- Delay in samples = (distance from image - direct source distance) / 343m/s × sample rate, plus a small symmetric ear baseline to create directional ITD; gains = wall reflectivity × directDistance/pathDistance × fixed safety factor. +- Mild source low-pass, ear-directional ITD/ILD approximation; NOT HRTF-convolved reflected signals or FDN reverb. +- Fixed 8192-frame power-of-two ring for each source (~64KiB total) and fractional-delay interpolation; geometry updates every 64 frames while delay and gains smoothly follow per-sample. +- Works at 44.1/48k; conservative fixed delay bounds; original direct HRTF FIR, stereo dry, spatialMix, outputTrim, ASIO and native ACK/readback remain untouched. +- One C++ unit gate, one exact-core integration parity test, two A/B WAV comparisons and a bounded CPU comparison before Windows FAT. + +## Staged next steps (NOT yet delivered) +M2: ITD/time-aligned measured HRIR preprocessing + fractional ear delay, grid-point identity and phase/ILD regression; no generic "phase aligned" switch without proving source accuracy. +M3: if needed, prepared HRTF-filtered reflections with bounded convolution and room distance parameter. +M4: only after successful listening trials, a compact SPACE control with native typed lease, accepted ACK/readback, versioned session schema and a calibrated default. No extra user-facing page. +M5: optional low-cost FDN late reverb, several HRTF profiles / calibration and head tracking after measured CPU and perceptual evidence. + +## Listening gate +Compare the legacy source-accurate 4-direction WAV and 10s orbit with two V2 files rendered from EXACT same input samples. Match perceived level, listen on headphones with OS virtualization off. Measure 8-direction mapping, front/rear distance, orbit continuity, colorations, metallic echoes and time-varying flutter. If room worsens direction or sound quality, keep amount=0. CI PCM PASS alone does not prove spatial externalization. From 2fe3df69e5fc5d7fdafca32ec6a32adb472769e8 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:23:37 +0700 Subject: [PATCH 072/140] fix(sonku-v2): finite room shutdown and exact zero bypass after slew --- engine/builtin_fx/sonku/SonKuEarlyReflections.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/engine/builtin_fx/sonku/SonKuEarlyReflections.h b/engine/builtin_fx/sonku/SonKuEarlyReflections.h index 8bdc3172a..240fe516c 100644 --- a/engine/builtin_fx/sonku/SonKuEarlyReflections.h +++ b/engine/builtin_fx/sonku/SonKuEarlyReflections.h @@ -63,7 +63,9 @@ class SonKuEarlyReflections final { history_[s][write_]=.70f*x[s]+.30f*lowpass_[s]; } amount_+=amountSlew_*(amountTarget_-amount_); - if(std::abs(amount_-amountTarget_)<1.e-6f)amount_=amountTarget_; + // Bound shutdown to a finite 10-12 time-constant fade, then + // restore strict bit-exact OFF/zero CPU on the next callback. + if(std::abs(amount_-amountTarget_)<1.e-5f)amount_=amountTarget_; Ears output{}; for(int s=0;s Date: Fri, 13 Nov 2026 10:25:26 +0700 Subject: [PATCH 073/140] fix(sof): expose exact accepted parallel EdgeId admission to native WIRE inspector --- web/approved-native-bridge.js | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index ab7831212..3aa78e0d6 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -372,14 +372,25 @@ return; // next coalesced target follows ACK + independent readback } } - function requestWireGain(op){ + // Every editable WIRE scalar must resolve an exact native ChannelId + + // EdgeId, not a destination kind, strip label, or reference graph index. + // A PARALLEL_SEND can legally point to MAIN; a PRIMARY_OUT can point to BUS. + function admittedParallelWire(uiSourceId,uiEdgeId,operation){ const current=controller?.state()?.current; - const edgeId=wireByUiId.get(op.edgeId),source=nativeByUiId.get(op.sourceId); + const source=nativeByUiId.get(uiSourceId),edgeId=wireByUiId.get(uiEdgeId); + if(!flags.acceptedGraphConnected||!current?.admitted||current.retained|| + !source||!edgeId||!current.graph.capabilities.supportedOps.includes(operation)) + return null; + const matches=current.graph.edges.filter(e=>e.enabled&& + e.edgeId===edgeId&&e.from===source&&e.primaryOutput===false); + return matches.length===1?matches[0]:null; + } + function requestWireGain(op){ const db=Number(op.levelDb); - if(!current?.admitted||!current.graph.capabilities.supportedOps.includes("SET_WIRE_GAIN")|| - !Number.isFinite(db)||db< -60||db>6)return false; - const edge=current.graph.edges.find(e=>e.enabled&&e.edgeId===edgeId&&e.from===source); - if(!edge||edge.primaryOutput!==false)return false; + if(!Number.isFinite(db)||db< -60||db>6|| + !admittedParallelWire(op.sourceId,op.edgeId,"SET_WIRE_GAIN"))return false; + const current=controller.state().current; + const edgeId=wireByUiId.get(op.edgeId),source=nativeByUiId.get(op.sourceId); // A physical SEND fader floor is -infinity (zero PCM), NOT -60 dB linear. pendingWireGains.set(edgeId,{source,gain:db<=-60?0:Math.pow(10,db/20),identity:current.identity}); queueWireGainFlush();return true; @@ -3643,6 +3654,14 @@ } status("NATIVE: "+action+" is not an accepted ChannelId operation");return true; }, + canWireGain(uiEdgeId,uiSourceId){ + return !!admittedParallelWire(uiSourceId,uiEdgeId,"SET_WIRE_GAIN"); + }, + canWireTap(uiEdgeId,uiSourceId){ + const edge=admittedParallelWire(uiSourceId,uiEdgeId,"APPLY_WIRE_TRANSACTION"); + return !!edge&&["PRE_FADER","POST_FADER"].includes(edge.tap)&& + !controller?.state()?.pending; + }, consumeWire(ops,retries=0) { if (!connected)return false; if(logicalView) { From 272b1981c879364c843ed189a7101c3c45fd01b0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:26:41 +0700 Subject: [PATCH 074/140] perf(sonku-v2): same-runner V1 vs early-reflection CPU comparison at 44.1/48k --- .github/workflows/ui-smoke.yml | 4 ++ tools/sonku_rt_benchmark.cpp | 74 ++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 tools/sonku_rt_benchmark.cpp diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index c5cba742f..03fc36a4f 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -215,6 +215,10 @@ jobs: /tmp/sonku-listening sonku-listening g++ -std=c++20 -O2 -Wall -Wextra -pedantic tests/sonku_early_reflections_test.cpp -o /tmp/sonku-room-test /tmp/sonku-room-test + - name: SonKu same-runner realtime CPU comparison (informational, not a release pass) + run: | + g++ -std=c++20 -O2 -Wall -Wextra -pedantic tools/sonku_rt_benchmark.cpp -o /tmp/sonku-rt-bench + /tmp/sonku-rt-bench python tests/sonku_offline_demo_contract.py sonku-listening - name: Publish 8D-SonKu reproducible listening WAVs and blind answer key if: ${{ always() }} diff --git a/tools/sonku_rt_benchmark.cpp b/tools/sonku_rt_benchmark.cpp new file mode 100644 index 000000000..9b3a0f9fd --- /dev/null +++ b/tools/sonku_rt_benchmark.cpp @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Scoped, runner-local reference measurement: never a hard/flaky CI threshold. +// Same 8D-SonKu core, same input blocks, same sample clock for V1 and V2. +// No wall-clock queries or I/O INSIDE the realtime processing function. +#include "../engine/builtin_fx/sonku/SonKuSpatialCore.h" +#include +#include +#include +#include +#include +#include + +namespace { +struct Result {double milliseconds=0.,checksum=0.,audios=0.;}; +template +Result measure(double rate,float amount){ + using namespace armix::sonku; + SonKuSpatialCore dsp; + if(!dsp.prepare(rate))throw std::runtime_error("unsupported sample rate"); + Settings s{};s.moving=true;s.revolutionSeconds=10.f; + s.spatialMix=1.f;s.stereoSpreadDegrees=60.f; + if(!dsp.setSettings(s)||!dsp.setEarlyReflectionsAmount(amount)) + throw std::runtime_error("invalid DSP setup"); + std::array inputL{},inputR{}; + for(std::size_t n=0;n(rate)*3; // three virtual seconds + auto start=std::chrono::steady_clock::now(); + double checksum=0.; + int done=0; + while(done(static_cast(block),frames-done); + auto l=inputL,r=inputR; + dsp.process(l.data(),r.data(),take); + for(int i=0;i( + std::chrono::steady_clock::now()-start).count(); + if(!(elapsed>0.)||!(checksum>1.))throw std::runtime_error("empty benchmark"); + return {elapsed,checksum,static_cast(frames)/rate}; +} +template +void report(double rate){ + const auto baseline=measure(rate,0.f); + const auto room=measure(rate,.55f); + std::cout<(rate); + report<512>(rate); + } + }catch(const std::exception& e){ + std::cerr<<"SONKU CPU BENCH FAIL: "< Date: Fri, 13 Nov 2026 10:26:47 +0700 Subject: [PATCH 075/140] fix(gui): WIRE inspector distinguishes PRIMARY unity from parallel sends incl MAIN; native edits await PCM readback --- site/preview-v2/index.html | 51 ++++++++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 5 deletions(-) diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index 2a1058a83..338448c87 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -1275,12 +1275,20 @@ const native=!!window.__JUCE__?.backend; const tapValue=edge?.nativeTap==='PRE_FADER'?'split': edge?.nativeTap==='POST_FADER'?'send':edge?.mode; - const tapEditable=!native||(src.nativeTapAvailable===true&& - edge?.kind==='send'&&['PRE_FADER','POST_FADER'].includes(edge.nativeTap)); + // A PRIMARY_OUT is fixed unity even when its destination is a BUS. + // An independently admitted PARALLEL_SEND remains editable even to MAIN. + // Only the connected native bridge can grant PCM control capability. + const gainEditable=edge&&(!native?edge.kind!=='primary': + window.__ARMIX_NATIVE_M2__?.canWireGain?.(edge.id,edge.sourceId)===true); + const tapEditable=edge&&(!native?edge.kind!=='primary': + window.__ARMIX_NATIVE_M2__?.canWireTap?.(edge.id,edge.sourceId)===true); const controls=edge? '
'+ - ''+ - ''+edge.levelDb+' dB'+ + ''+ + ''+(edge.kind==='primary'?'PRIMARY · UNITY': + edge.levelDb+' dB')+''+ ''+ ''+ - ''+(edge.kind==='primary'?'PRIMARY · UNITY': - edge.levelDb+' dB')+''+ + ''+ + ''+edge.levelDb+' dB'+ ''+ ''+\n ''+edge.levelDb+' dB'+\n ''+\n ''+\n '
':\n '
Managed by existing '+escapeHtml(info.kind.toUpperCase())+' routing. No duplicate WIRE edge.
';\n", + " const controls=edge?\n '
'+\n ''+\n ''+(edge.kind==='primary'?'PRIMARY · UNITY':\n edge.levelDb+' dB')+''+\n ''+\n ''+\n '
':\n '
Managed by existing '+escapeHtml(info.kind.toUpperCase())+' routing. No duplicate WIRE edge.
';\n"), + ("document.getElementById('wireWsInspector').addEventListener('input',e=>{\n const gain=e.target.closest?.('[data-ws-gain]');\n if(!gain)return;\n const edge=wireEdges.find(x=>x.id===Number(gain.dataset.wsGain)&&x.enabled);\n if(!edge||edge.destId===master.id)return;\n const amount=Math.max(-60,Math.min(6,Math.round(Number(gain.value)||0)));\n if(!wireGraphCommit([{type:'GAIN',sourceId:edge.sourceId,edgeId:edge.id,\n levelDb:amount}],{record:false}))return;\n document.getElementById('wireWsGainText').textContent=amount+' dB';\n});\ndocument.getElementById('wireWsInspector').addEventListener('change',e=>{\n const gain=e.target.closest?.('[data-ws-gain]'),tap=e.target.closest?.('[data-ws-tap]');\n if(tap){\n const edge=wireEdges.find(x=>x.id===Number(tap.dataset.wsTap)&&x.enabled);\n if(!edge||!wireGraphCommit([{type:'MODE',sourceId:edge.sourceId,edgeId:edge.id,\n mode:tap.value==='split'?'split':'send'}],{record:false}))return;\n const owner=wireSourceTrack(edge.sourceId);if(owner)owner.wireTapMode=tap.value==='split'?'split':'send';\n }\n if(gain||tap){\n wireWsRecord(wireWsEditBefore);wireWsEditBefore=null;render();renderWireWorkspace();\n say('WIRE inspector accepted · reference graph only');\n }\n});\n\n", + "document.getElementById('wireWsInspector').addEventListener('input',e=>{\n const gain=e.target.closest?.('[data-ws-gain]');\n if(!gain)return;\n const edge=wireEdges.find(x=>x.id===Number(gain.dataset.wsGain)&&x.enabled);\n if(!edge||edge.kind==='primary')return;\n const amount=Math.max(-60,Math.min(6,Math.round(Number(gain.value)||0)));\n if(window.__JUCE__?.backend){\n if(window.__ARMIX_NATIVE_M2__?.canWireGain?.(edge.id,edge.sourceId)!==true)return;\n // Coalesce rapid gestures in the existing native control queue. This LCD\n // shows a pending operation, NEVER a speculative accepted PCM level.\n window.__ARMIX_NATIVE_M2__?.consumeWire?.([{type:'GAIN',\n sourceId:edge.sourceId,edgeId:edge.id,levelDb:amount}]);\n const readout=document.getElementById('wireWsGainText');\n if(readout)readout.textContent='PENDING · '+amount+' dB';\n return;\n }\n if(!wireGraphCommit([{type:'GAIN',sourceId:edge.sourceId,edgeId:edge.id,\n levelDb:amount}],{record:false}))return;\n document.getElementById('wireWsGainText').textContent=amount+' dB';\n});\ndocument.getElementById('wireWsInspector').addEventListener('change',e=>{\n const gain=e.target.closest?.('[data-ws-gain]'),tap=e.target.closest?.('[data-ws-tap]');\n if(window.__JUCE__?.backend){\n if(gain){\n const edge=wireEdges.find(x=>x.id===Number(gain.dataset.wsGain)&&x.enabled);\n if(edge?.kind!=='primary'&&window.__ARMIX_NATIVE_M2__?.canWireGain?.(edge.id,edge.sourceId)===true){\n // Keyboard-only range change may not have emitted 'input'.\n window.__ARMIX_NATIVE_M2__?.consumeWire?.([{type:'GAIN',sourceId:edge.sourceId,\n edgeId:edge.id,levelDb:Math.max(-60,Math.min(6,Math.round(Number(gain.value)||0)))}]);\n }\n }\n if(tap){\n const edge=wireEdges.find(x=>x.id===Number(tap.dataset.wsTap)&&x.enabled);\n const requested=tap.value==='split'?'split':'send';\n // Restore the accepted selector position immediately. An independent\n // structural readback will move it after the engine actually publishes.\n tap.value=edge?.nativeTap==='PRE_FADER'?'split':'send';\n if(edge&&window.__ARMIX_NATIVE_M2__?.canWireTap?.(edge.id,edge.sourceId)===true){\n window.__ARMIX_NATIVE_M2__?.consumeWire?.([{type:'MODE',sourceId:edge.sourceId,\n edgeId:edge.id,mode:requested}]);\n say('WIRE tap requested · awaiting accepted native PCM readback');\n }else say('WIRE tap unavailable · native graph or EdgeId changed');\n }\n wireWsEditBefore=null;return; // native owns state; no demo undo or full repaint\n }\n if(tap){\n const edge=wireEdges.find(x=>x.id===Number(tap.dataset.wsTap)&&x.enabled);\n if(!edge||!wireGraphCommit([{type:'MODE',sourceId:edge.sourceId,edgeId:edge.id,\n mode:tap.value==='split'?'split':'send'}],{record:false}))return;\n const owner=wireSourceTrack(edge.sourceId);if(owner)owner.wireTapMode=tap.value==='split'?'split':'send';\n }\n if(gain||tap){\n wireWsRecord(wireWsEditBefore);wireWsEditBefore=null;render();renderWireWorkspace();\n say('WIRE inspector accepted · reference graph only');\n }\n});\n\n"), +) + + + def native_html(approved: str | None = None) -> str: original = accepted_pages_html() if approved is None else approved newline = "\r\n" if "\r\n" in original else "\n" From ba7c712ec73ea08d5b96b3a973ea7f14c77fcd06 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:32:17 +0700 Subject: [PATCH 080/140] test(native-gui): execute assembled native-only WIRE inspector and assert public Pages untouched --- tests/approved_native_m2_contract.test.cjs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index d67e03b0c..f5ea8b916 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -28,7 +28,13 @@ function acceptedFixture(){ return s; } test("WIRE inspector controls PRIMARY BUS and PARALLEL MAIN by actual EdgeId, with native readback only",()=>{ - const vm=require("node:vm"),html=read("site/preview-v2/index.html"); + const vm=require("node:vm"),{execFileSync}=require("node:child_process"); + const publicHtml=read("site/preview-v2/index.html"); + assert.doesNotMatch(publicHtml,/__ARMIX_NATIVE_M2__/, + "public approved /preview/ must never own native control authority"); + const html=execFileSync("python3",["-c", + "from scripts.build_approved_native_gui import native_html; from pathlib import Path; print(native_html(Path('site/preview-v2/index.html').read_text(encoding='utf-8')))" + ],{encoding:"utf8",maxBuffer:10*1024*1024}); const bridge=read("web/approved-native-bridge.js"); const builder=read("scripts/build_approved_native_gui.py"); assert.match(bridge,/function admittedParallelWire\(uiSourceId,uiEdgeId,operation\)/); From 5e86f45c05b248420127ac665cc510bd57ef83a6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:33:17 +0700 Subject: [PATCH 081/140] fix(native-gui): include exact gainEditable admission in reversible WIRE inspector hook --- scripts/build_approved_native_gui.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index a451cc7d9..3dbc667a7 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -300,7 +300,7 @@ def accepted_pages_html() -> str: # are never accepted by the browser mock before installed PCM readback. NATIVE_EVENT_HOOKS += ( (" const tapEditable=!native||(src.nativeTapAvailable===true&&\n edge?.kind==='send'&&['PRE_FADER','POST_FADER'].includes(edge.nativeTap));\n", - " const tapEditable=edge&&(!native?edge.kind!=='primary':\n window.__ARMIX_NATIVE_M2__?.canWireTap?.(edge.id,edge.sourceId)===true);\n"), + " const gainEditable=edge&&(!native?edge.kind!=='primary':\n window.__ARMIX_NATIVE_M2__?.canWireGain?.(edge.id,edge.sourceId)===true);\n const tapEditable=edge&&(!native?edge.kind!=='primary':\n window.__ARMIX_NATIVE_M2__?.canWireTap?.(edge.id,edge.sourceId)===true);\n"), (" const controls=edge?\n '
'+\n ''+\n ''+edge.levelDb+' dB'+\n ''+\n ''+\n '
':\n '
Managed by existing '+escapeHtml(info.kind.toUpperCase())+' routing. No duplicate WIRE edge.
';\n", " const controls=edge?\n '
'+\n ''+\n ''+(edge.kind==='primary'?'PRIMARY · UNITY':\n edge.levelDb+' dB')+''+\n ''+\n ''+\n '
':\n '
Managed by existing '+escapeHtml(info.kind.toUpperCase())+' routing. No duplicate WIRE edge.
';\n"), ("document.getElementById('wireWsInspector').addEventListener('input',e=>{\n const gain=e.target.closest?.('[data-ws-gain]');\n if(!gain)return;\n const edge=wireEdges.find(x=>x.id===Number(gain.dataset.wsGain)&&x.enabled);\n if(!edge||edge.destId===master.id)return;\n const amount=Math.max(-60,Math.min(6,Math.round(Number(gain.value)||0)));\n if(!wireGraphCommit([{type:'GAIN',sourceId:edge.sourceId,edgeId:edge.id,\n levelDb:amount}],{record:false}))return;\n document.getElementById('wireWsGainText').textContent=amount+' dB';\n});\ndocument.getElementById('wireWsInspector').addEventListener('change',e=>{\n const gain=e.target.closest?.('[data-ws-gain]'),tap=e.target.closest?.('[data-ws-tap]');\n if(tap){\n const edge=wireEdges.find(x=>x.id===Number(tap.dataset.wsTap)&&x.enabled);\n if(!edge||!wireGraphCommit([{type:'MODE',sourceId:edge.sourceId,edgeId:edge.id,\n mode:tap.value==='split'?'split':'send'}],{record:false}))return;\n const owner=wireSourceTrack(edge.sourceId);if(owner)owner.wireTapMode=tap.value==='split'?'split':'send';\n }\n if(gain||tap){\n wireWsRecord(wireWsEditBefore);wireWsEditBefore=null;render();renderWireWorkspace();\n say('WIRE inspector accepted · reference graph only');\n }\n});\n\n", From 59f18b1f868dac432fb383b9e0f162020df3f2d0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:39:25 +0700 Subject: [PATCH 082/140] feat(sonku-v2): render uninterrupted two-turn 20s orbit with seam and phase gates --- ...KU_V2_EXTERNALIZATION_DECISION_20261113.md | 5 ++++ tests/sonku_offline_demo_contract.py | 16 ++++++++++--- tools/sonku_offline_listening.cpp | 23 +++++++++++++------ 3 files changed, 34 insertions(+), 10 deletions(-) diff --git a/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md index d7b8375a6..6105b9427 100644 --- a/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md +++ b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md @@ -32,3 +32,8 @@ M5: optional low-cost FDN late reverb, several HRTF profiles / calibration and h ## Listening gate Compare the legacy source-accurate 4-direction WAV and 10s orbit with two V2 files rendered from EXACT same input samples. Match perceived level, listen on headphones with OS virtualization off. Measure 8-direction mapping, front/rear distance, orbit continuity, colorations, metallic echoes and time-varying flutter. If room worsens direction or sound quality, keep amount=0. CI PCM PASS alone does not prove spatial externalization. + +## 2026-11-13 listener feedback and two-turn orbit gate +Listener recognizes direction but describes a noncircular perceived orbit: RIGHT → FRONT is pleasing, yet FRONT/RIGHT/REAR continuity feels incomplete and FRONT subjectively nearer. The room is **rectangular 6.4 × 8 m**, so reflected image distances and directional/temporal profiles vary across axes. This is one plausible contributor, not a proven cause; non-individual HRTF and ITD-inconsistent HRIR interpolation remain other hypotheses. + +The offline evaluation now renders a **single uninterrupted 20-second, 2 × 360° clockwise trajectory** (10 seconds/turn) for both legacy direct HRTF and rectangular-room A/B. Only fade in at time 0 and fade out at 20 seconds; no fade/reset/offset at the 10-second boundary. Landmarks: FRONT 0/10/20s; RIGHT 2.5/12.5; REAR 5/15; LEFT 7.5/17.5. PCM tests verify 960,000 frames, non-silent seam, fixed rate and output sign, and C++ end-of-two-turn phase closure. Do not market a verified circular perceptual effect until headphone evaluation. diff --git a/tests/sonku_offline_demo_contract.py b/tests/sonku_offline_demo_contract.py index 07ad8f4e1..c7a5d1b1c 100644 --- a/tests/sonku_offline_demo_contract.py +++ b/tests/sonku_offline_demo_contract.py @@ -23,9 +23,9 @@ def read(name, frames): return pcm single=read("sonku-reference-four.wav",4*120000) blind=read("sonku-blind-eight.wav",8*120000) -orbit=read("sonku-orbit-cw.wav",480000) +orbit=read("sonku-orbit-cw-2x.wav",960000) v2four=read("sonku-v2-room-four.wav",4*120000) -v2orbit=read("sonku-v2-room-orbit-cw.wav",480000) +v2orbit=read("sonku-v2-room-orbit-cw-2x.wav",960000) # Baseline V1 and candidate V2 are deliberately non-identical on same noise. # Room must affect later samples, not fake position on the direct sound. difference=sum(abs(int(a)-int(b)) for a,b in @@ -41,8 +41,18 @@ def read(name, frames): assert right>left*1.2,("RIGHT HRTF channel swapped",left,right) # No false silence between orbit buffer boundaries; source is continuous. assert sum(abs(x) for x in orbit[220000:230000])>1000 +# Verify there is no mute, edit or source reset at the 10s handoff. +# Stereo interleaved: 48000 samples = 1 second, 2 PCM ints per frame. +for audio in (orbit,v2orbit): + for second in (9,10,11,19): + begin=(second*48000+4000)*2 + assert sum(abs(x) for x in audio[begin:begin+9600])>2000,( + "silent loop seam",second) +assert "20s" in (root/"LISTENING-GUIDE.txt").read_text() +assert not (root/"sonku-orbit-cw.wav").exists(),( + "stale 10s artifact must not appear alongside 2x master") assert (root/"LISTENING-GUIDE.txt").exists() key=(root/"BLIND-ANSWER-KEY.txt").read_text() assert key.count("Trial ")==8 and key.count("FRONT")==2 and key.count("REAR")==2 print("PASS 8D-SonKu actual C++ offline WAV: four directions, balanced blind", - "set, clockwise orbit, 48kHz stereo PCM, no clipping.") + "set, two continuous 360deg turns (20s), 48kHz stereo PCM, no clipping.") diff --git a/tools/sonku_offline_listening.cpp b/tools/sonku_offline_listening.cpp index 4524af5cf..67ae2f79c 100644 --- a/tools/sonku_offline_listening.cpp +++ b/tools/sonku_offline_listening.cpp @@ -21,6 +21,10 @@ constexpr int framesPerBlock=128; constexpr int activeFrames=rate*2; constexpr int silenceFrames=rate/2; constexpr int rampFrames=rate/50; // 20ms, no clicks between labeled probes +constexpr int orbitSecondsPerTurn=10; +constexpr int orbitTurns=2; +constexpr int orbitFrames=rate*orbitSecondsPerTurn*orbitTurns; +static_assert(orbitFrames==960000); using armix::sonku::Settings; using armix::sonku::SonKuSpatialCore; struct Noise { @@ -105,7 +109,7 @@ std::vector orbit(float roomAmount=0.f){ throw std::runtime_error("Invalid orbit room amount"); Settings s=fixed(0.f);s.moving=true;s.clockwise=true;s.revolutionSeconds=10.f; dsp.reset();if(!dsp.setSettings(s))throw std::runtime_error("No 360 orbit"); - const int frames=rate*10; + const int frames=orbitFrames; // two complete turns on ONE continuous audio clock std::vector result; result.reserve(static_cast(frames)*4); for(int base=0;base orbit(float roomAmount=0.f){ dsp.process(l.data(),r.data(),n); for(int i=0;i.01) + throw std::runtime_error("Two turns do not close acoustic orbit"); return result; } const char* direction(int deg) { @@ -142,14 +149,16 @@ void notes(const std::filesystem::path& directory, <<"then 0.5s quiet. Order: FRONT, RIGHT, REAR, LEFT.\n" <<"sonku-blind-eight.wav: 8 x 2.5 seconds, balanced two times each.\n" <<"Write down FRONT/RIGHT/REAR/LEFT for trials 1..8 before opening KEY.\n" - <<"sonku-orbit-cw.wav: 10s one continuous 360deg clockwise orbit,\n" - <<"starting at FRONT, acoustic RIGHT on listener's right headphone.\n\n" + <<"sonku-orbit-cw-2x.wav: 20s TWO seamless continuous 360deg\n" + <<"clockwise turns, 10s each, FRONT at 0/10/20s. No pause at 10s.\n" + <<"At 2.5/12.5s RIGHT, 5/15s REAR, 7.5/17.5s LEFT.\n" + <<"Acoustic RIGHT is on listener's right headphone.\n\n" <<"If front/rear is ambiguous or internalized, note headphones and listener.\n" <<"Baseline SonKu files have no room reflections (V1).\n" <<"V2 room candidate adds four 1st-order image-source reflections\n" <<"per emitter (6.4x8m fixed room) with bounded ear delays and level.\n" <<"sonku-v2-room-four.wav = A/B against sonku-reference-four.wav.\n" - <<"sonku-v2-room-orbit-cw.wav = A/B against sonku-orbit-cw.wav.\n" + <<"sonku-v2-room-orbit-cw-2x.wav = A/B against sonku-orbit-cw-2x.wav.\n" <<"Both comparisons reuse exactly the same source noise and direct HRIR.\n" <<"Do blind-level and externalization evaluation before enabling V2 live.\n" <<"This is NOT full HRIR-convolved reflections, FDN or personalized HRTF.\n"; @@ -170,16 +179,16 @@ int main(int argc,char** argv){ writeWav(dir/"sonku-reference-four.wav", staticProbes({reference.begin(),reference.end()})); writeWav(dir/"sonku-blind-eight.wav",staticProbes(blind)); - writeWav(dir/"sonku-orbit-cw.wav",orbit()); + writeWav(dir/"sonku-orbit-cw-2x.wav",orbit()); // Only the bounded early-reflection stage changes between paired // files. Source, directions, KEMAR HRIR, loudness trim and clock are // identical. Blind front/back listening is the decision gate. writeWav(dir/"sonku-v2-room-four.wav", staticProbes({reference.begin(),reference.end()},.55f)); - writeWav(dir/"sonku-v2-room-orbit-cw.wav",orbit(.55f)); + writeWav(dir/"sonku-v2-room-orbit-cw-2x.wav",orbit(.55f)); notes(dir,blind); std::cout<<"SonKu listening package PASS: measured native HRTF, " - <<"4 labeled + 8 blind directions + one 360 orbit\n"; + <<"4 labeled + 8 blind directions + two uninterrupted 360 turns\n"; }catch(const std::exception& error){ std::cerr<<"SonKu offline render FAILED: "< Date: Fri, 13 Nov 2026 10:42:47 +0700 Subject: [PATCH 083/140] feat(sonku-v2): 20s square-room diagnostic orbit and mirrored reflection tests --- ...KU_V2_EXTERNALIZATION_DECISION_20261113.md | 3 +++ .../builtin_fx/sonku/SonKuEarlyReflections.h | 23 +++++++++++++++++-- engine/builtin_fx/sonku/SonKuSpatialCore.h | 4 ++++ tests/sonku_early_reflections_test.cpp | 16 +++++++++++++ tests/sonku_offline_demo_contract.py | 6 ++++- tools/sonku_offline_listening.cpp | 15 ++++++++---- 6 files changed, 60 insertions(+), 7 deletions(-) diff --git a/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md index 6105b9427..45f3f7381 100644 --- a/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md +++ b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md @@ -37,3 +37,6 @@ Compare the legacy source-accurate 4-direction WAV and 10s orbit with two V2 fil Listener recognizes direction but describes a noncircular perceived orbit: RIGHT → FRONT is pleasing, yet FRONT/RIGHT/REAR continuity feels incomplete and FRONT subjectively nearer. The room is **rectangular 6.4 × 8 m**, so reflected image distances and directional/temporal profiles vary across axes. This is one plausible contributor, not a proven cause; non-individual HRTF and ITD-inconsistent HRIR interpolation remain other hypotheses. The offline evaluation now renders a **single uninterrupted 20-second, 2 × 360° clockwise trajectory** (10 seconds/turn) for both legacy direct HRTF and rectangular-room A/B. Only fade in at time 0 and fade out at 20 seconds; no fade/reset/offset at the 10-second boundary. Landmarks: FRONT 0/10/20s; RIGHT 2.5/12.5; REAR 5/15; LEFT 7.5/17.5. PCM tests verify 960,000 frames, non-silent seam, fixed rate and output sign, and C++ end-of-two-turn phase closure. Do not market a verified circular perceptual effect until headphone evaluation. + +## 2026-11-13 — rectangular vs symmetric-room controlled comparison +The report of an elliptical/unequal-distance orbit does NOT prove a room-model bug. Alongside V1 direct HRTF and the existing rectangular 6.4×8m image-source room, a third A/B WAV uses a square 7.2×7.2m room with all wall reflectivities identical. The emitted direct HRTF, sample clock, source waveform and 2×360° motion remain identical. The square wall layout has fourfold rotational geometry and tests whether wall distance contributes to perceived asymmetry; it is NOT a circular room or a promised perceptual cure. C++ tests check left/right mirror of the reflected impulse. A/B only, original native default remains OFF. diff --git a/engine/builtin_fx/sonku/SonKuEarlyReflections.h b/engine/builtin_fx/sonku/SonKuEarlyReflections.h index 240fe516c..501cccfca 100644 --- a/engine/builtin_fx/sonku/SonKuEarlyReflections.h +++ b/engine/builtin_fx/sonku/SonKuEarlyReflections.h @@ -4,6 +4,7 @@ #include #include #include +#include // Bounded, first-order image-source room for headphone externalization trials. // Reflection image geometry follows Allen & Berkley (JASA, 1979), not @@ -11,6 +12,7 @@ // this is NOT an HRTF-convolved reflection / arbitrary geometry simulation. // No allocation, locks, worker, I/O, FFT or second device callback. namespace armix::sonku { +enum class SonKuRoomShape : std::uint8_t { Rectangular=0, Square=1 }; class SonKuEarlyReflections final { public: struct Ears {float left=0.f,right=0.f;}; @@ -46,6 +48,17 @@ class SonKuEarlyReflections final { amountTarget_=value; return true; } + // Offline experiment only. Reject shape edits while effect is active. + bool setShape(SonKuRoomShape shape) noexcept { + if(shape!=SonKuRoomShape::Rectangular && shape!=SonKuRoomShape::Square) + return false; + if(active())return false; + shape_=shape; + untilGeometry_=0; + primed_=false; + return true; + } + SonKuRoomShape shape() const noexcept {return shape_;} bool active() const noexcept {return ready_&&(amount_>0.f||amountTarget_>0.f);} float targetAmount() const noexcept {return amountTarget_;} Ears process(float left,float right,double azimuth,float spread) noexcept { @@ -104,10 +117,15 @@ class SonKuEarlyReflections final { void updateGeometry(double azimuth,float spread) noexcept { constexpr float pi=3.14159265358979323846f; constexpr float sourceDistance=1.60f; // meters - constexpr float halfWidth=3.20f,halfDepth=4.00f; + // The square profile tests rotationally symmetric wall geometry; + // it is not a simulated circular room or guaranteed psychoacoustics. + const float halfWidth=(shape_==SonKuRoomShape::Square)?3.60f:3.20f; + const float halfDepth=(shape_==SonKuRoomShape::Square)?3.60f:4.00f; constexpr float speedOfSound=343.f; constexpr float earHalfTime=.00031f; // max +/-0.31ms - constexpr std::array walls{.74f,.74f,.67f,.67f}; + constexpr std::array rectangular{.74f,.74f,.67f,.67f}; + constexpr std::array square{.70f,.70f,.70f,.70f}; + const auto& walls=(shape_==SonKuRoomShape::Square)?square:rectangular; for(int source=0;source(azimuth) +(source==0?-.5f:.5f)*spread; @@ -152,6 +170,7 @@ class SonKuEarlyReflections final { float rate_=0.f,delaySlew_=0.f,gainSlew_=0.f,amountSlew_=0.f; float amount_=0.f,amountTarget_=0.f; int write_=0,untilGeometry_=0; + SonKuRoomShape shape_=SonKuRoomShape::Rectangular; bool ready_=false,primed_=false; }; } // namespace armix::sonku diff --git a/engine/builtin_fx/sonku/SonKuSpatialCore.h b/engine/builtin_fx/sonku/SonKuSpatialCore.h index a99a0c5d0..7ba5d1237 100644 --- a/engine/builtin_fx/sonku/SonKuSpatialCore.h +++ b/engine/builtin_fx/sonku/SonKuSpatialCore.h @@ -83,6 +83,10 @@ class SonKuSpatialCore final { bool setEarlyReflectionsAmount(float amount) noexcept { return room_.setAmount(amount); } + // Explicit A/B-only shape selection; never persisted or host-exposed. + bool setEarlyReflectionsShape(SonKuRoomShape shape) noexcept { + return room_.setShape(shape); + } bool ready() const noexcept {return ready_;} double azimuthDegrees() const noexcept {return degrees_;} // In-place stereo; caller owns valid, non-overlapping L/R PCM pointers. diff --git a/tests/sonku_early_reflections_test.cpp b/tests/sonku_early_reflections_test.cpp index 5edd9b7f9..e6fd7b392 100644 --- a/tests/sonku_early_reflections_test.cpp +++ b/tests/sonku_early_reflections_test.cpp @@ -13,6 +13,22 @@ int main(){ assert(!invalid.prepare(96000.)); assert(!invalid.prepare(std::numeric_limits::quiet_NaN())); for(double rate:{44100.,48000.}){ + SonKuEarlyReflections squareRight,squareLeft; + assert(squareRight.prepare(rate)&&squareLeft.prepare(rate)); + assert(squareRight.setShape(SonKuRoomShape::Square)); + assert(squareLeft.setShape(SonKuRoomShape::Square)); + assert(squareRight.setAmount(.55f)&&squareLeft.setAmount(.55f)); + double mirrorError=0.,soundEnergy=0.; + for(int i=0;i<4096;++i){ + const float v=i==0?1.f:0.f; + const auto right=squareRight.process(v,0.f,90.,0.f); + const auto left=squareLeft.process(v,0.f,-90.,0.f); + mirrorError+=std::abs(right.left-left.right)+ + std::abs(right.right-left.left); + soundEnergy+=std::abs(right.left)+std::abs(right.right); + } + assert(soundEnergy>.004); + assert(mirrorError<1.e-4); SonKuEarlyReflections a,b; assert(a.prepare(rate)&&b.prepare(rate)); assert(!a.active()); diff --git a/tests/sonku_offline_demo_contract.py b/tests/sonku_offline_demo_contract.py index c7a5d1b1c..2ce96cba0 100644 --- a/tests/sonku_offline_demo_contract.py +++ b/tests/sonku_offline_demo_contract.py @@ -26,6 +26,7 @@ def read(name, frames): orbit=read("sonku-orbit-cw-2x.wav",960000) v2four=read("sonku-v2-room-four.wav",4*120000) v2orbit=read("sonku-v2-room-orbit-cw-2x.wav",960000) +squareOrbit=read("sonku-v2-square-orbit-cw-2x.wav",960000) # Baseline V1 and candidate V2 are deliberately non-identical on same noise. # Room must affect later samples, not fake position on the direct sound. difference=sum(abs(int(a)-int(b)) for a,b in @@ -34,6 +35,9 @@ def read(name, frames): orbitDelta=sum(abs(int(a)-int(b)) for a,b in zip(v2orbit[70000:200000],orbit[70000:200000])) assert orbitDelta>1500,("V2 moving room candidate did not affect PCM",orbitDelta) +shapeDelta=sum(abs(int(a)-int(b)) for a,b in + zip(squareOrbit[70000:200000],v2orbit[70000:200000])) +assert shapeDelta>1500,("Square and rectangle rendered the same",shapeDelta) # +90° (second reference segment) has a distinct binaural response. section=single[120000*2:120000*4] left=sum(abs(section[i]) for i in range(0,len(section),2)) @@ -43,7 +47,7 @@ def read(name, frames): assert sum(abs(x) for x in orbit[220000:230000])>1000 # Verify there is no mute, edit or source reset at the 10s handoff. # Stereo interleaved: 48000 samples = 1 second, 2 PCM ints per frame. -for audio in (orbit,v2orbit): +for audio in (orbit,v2orbit,squareOrbit): for second in (9,10,11,19): begin=(second*48000+4000)*2 assert sum(abs(x) for x in audio[begin:begin+9600])>2000,( diff --git a/tools/sonku_offline_listening.cpp b/tools/sonku_offline_listening.cpp index 67ae2f79c..18424964d 100644 --- a/tools/sonku_offline_listening.cpp +++ b/tools/sonku_offline_listening.cpp @@ -102,11 +102,13 @@ std::vector staticProbes(const std::vector& azimuths,float ro } return result; } -std::vector orbit(float roomAmount=0.f){ +std::vector orbit(float roomAmount=0.f, + armix::sonku::SonKuRoomShape shape=armix::sonku::SonKuRoomShape::Rectangular){ SonKuSpatialCore dsp;Noise noise; if(!dsp.prepare(rate))throw std::runtime_error("No 48k HRTF"); - if(!dsp.setEarlyReflectionsAmount(roomAmount)) - throw std::runtime_error("Invalid orbit room amount"); + if(!dsp.setEarlyReflectionsShape(shape)|| + !dsp.setEarlyReflectionsAmount(roomAmount)) + throw std::runtime_error("Invalid orbit room configuration"); Settings s=fixed(0.f);s.moving=true;s.clockwise=true;s.revolutionSeconds=10.f; dsp.reset();if(!dsp.setSettings(s))throw std::runtime_error("No 360 orbit"); const int frames=orbitFrames; // two complete turns on ONE continuous audio clock @@ -158,7 +160,10 @@ void notes(const std::filesystem::path& directory, <<"V2 room candidate adds four 1st-order image-source reflections\n" <<"per emitter (6.4x8m fixed room) with bounded ear delays and level.\n" <<"sonku-v2-room-four.wav = A/B against sonku-reference-four.wav.\n" - <<"sonku-v2-room-orbit-cw-2x.wav = A/B against sonku-orbit-cw-2x.wav.\n" + <<"sonku-v2-room-orbit-cw-2x.wav = 6.4 x 8m rectangular room.\n" + <<"sonku-v2-square-orbit-cw-2x.wav = 7.2 x 7.2m symmetric room.\n" + <<"Both candidates reuse the SAME direct HRTF/noise and 20s clock.\n" + <<"Square geometry is not a guarantee of circular perception.\n" <<"Both comparisons reuse exactly the same source noise and direct HRIR.\n" <<"Do blind-level and externalization evaluation before enabling V2 live.\n" <<"This is NOT full HRIR-convolved reflections, FDN or personalized HRTF.\n"; @@ -186,6 +191,8 @@ int main(int argc,char** argv){ writeWav(dir/"sonku-v2-room-four.wav", staticProbes({reference.begin(),reference.end()},.55f)); writeWav(dir/"sonku-v2-room-orbit-cw-2x.wav",orbit(.55f)); + writeWav(dir/"sonku-v2-square-orbit-cw-2x.wav", + orbit(.55f,armix::sonku::SonKuRoomShape::Square)); notes(dir,blind); std::cout<<"SonKu listening package PASS: measured native HRTF, " <<"4 labeled + 8 blind directions + two uninterrupted 360 turns\n"; From 409ed5d175345204048aa6a64a9ac229a475f062 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:44:32 +0700 Subject: [PATCH 084/140] feat(sonku-v2): two-turn clockwise and counterclockwise binaural A/B set --- docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md | 3 +++ tests/sonku_offline_demo_contract.py | 9 ++++++++- tools/sonku_offline_listening.cpp | 13 +++++++++++-- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md index 45f3f7381..b7acf194f 100644 --- a/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md +++ b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md @@ -40,3 +40,6 @@ The offline evaluation now renders a **single uninterrupted 20-second, 2 × 360 ## 2026-11-13 — rectangular vs symmetric-room controlled comparison The report of an elliptical/unequal-distance orbit does NOT prove a room-model bug. Alongside V1 direct HRTF and the existing rectangular 6.4×8m image-source room, a third A/B WAV uses a square 7.2×7.2m room with all wall reflectivities identical. The emitted direct HRTF, sample clock, source waveform and 2×360° motion remain identical. The square wall layout has fourfold rotational geometry and tests whether wall distance contributes to perceived asymmetry; it is NOT a circular room or a promised perceptual cure. C++ tests check left/right mirror of the reflected impulse. A/B only, original native default remains OFF. + +## 2026-11-13 — independent reversed-motion listening probes +In response to asymmetrical perceived naturalness of RIGHT→FRONT vs FRONT→RIGHT, add three CCW two-turn WAVs alongside the three clockwise versions. All six are 20 seconds, use the exact same deterministic original noise, same native HRTF and DSP sample clock, and have no loop seam. Clockwise: FRONT → RIGHT → REAR → LEFT → FRONT. Counterclockwise: FRONT → LEFT → REAR → RIGHT → FRONT. This allows listening comparison of RIGHT→FRONT (CCW at 7.5–10 and 17.5–20 seconds) with FRONT→RIGHT (CW at 0–2.5 and 10–12.5 seconds), and tests whether perceptual asymmetry reverses with source rotation direction. No additional live motion modes, no UI changes, no assertion of physically circular perception. diff --git a/tests/sonku_offline_demo_contract.py b/tests/sonku_offline_demo_contract.py index 2ce96cba0..1cfba47c2 100644 --- a/tests/sonku_offline_demo_contract.py +++ b/tests/sonku_offline_demo_contract.py @@ -27,6 +27,9 @@ def read(name, frames): v2four=read("sonku-v2-room-four.wav",4*120000) v2orbit=read("sonku-v2-room-orbit-cw-2x.wav",960000) squareOrbit=read("sonku-v2-square-orbit-cw-2x.wav",960000) +reverse=read("sonku-orbit-ccw-2x.wav",960000) +reverseRoom=read("sonku-v2-room-orbit-ccw-2x.wav",960000) +reverseSquare=read("sonku-v2-square-orbit-ccw-2x.wav",960000) # Baseline V1 and candidate V2 are deliberately non-identical on same noise. # Room must affect later samples, not fake position on the direct sound. difference=sum(abs(int(a)-int(b)) for a,b in @@ -38,6 +41,10 @@ def read(name, frames): shapeDelta=sum(abs(int(a)-int(b)) for a,b in zip(squareOrbit[70000:200000],v2orbit[70000:200000])) assert shapeDelta>1500,("Square and rectangle rendered the same",shapeDelta) +# Reverse motion must change the binaural path (not merely rename a WAV). +reverseDelta=sum(abs(int(a)-int(b)) for a,b in + zip(reverse[350000:500000],orbit[350000:500000])) +assert reverseDelta>1500,("CW/CCW unexpectedly identical",reverseDelta) # +90° (second reference segment) has a distinct binaural response. section=single[120000*2:120000*4] left=sum(abs(section[i]) for i in range(0,len(section),2)) @@ -47,7 +54,7 @@ def read(name, frames): assert sum(abs(x) for x in orbit[220000:230000])>1000 # Verify there is no mute, edit or source reset at the 10s handoff. # Stereo interleaved: 48000 samples = 1 second, 2 PCM ints per frame. -for audio in (orbit,v2orbit,squareOrbit): +for audio in (orbit,v2orbit,squareOrbit,reverse,reverseRoom,reverseSquare): for second in (9,10,11,19): begin=(second*48000+4000)*2 assert sum(abs(x) for x in audio[begin:begin+9600])>2000,( diff --git a/tools/sonku_offline_listening.cpp b/tools/sonku_offline_listening.cpp index 18424964d..1d0126c19 100644 --- a/tools/sonku_offline_listening.cpp +++ b/tools/sonku_offline_listening.cpp @@ -103,13 +103,14 @@ std::vector staticProbes(const std::vector& azimuths,float ro return result; } std::vector orbit(float roomAmount=0.f, - armix::sonku::SonKuRoomShape shape=armix::sonku::SonKuRoomShape::Rectangular){ + armix::sonku::SonKuRoomShape shape=armix::sonku::SonKuRoomShape::Rectangular, + bool clockwise=true){ SonKuSpatialCore dsp;Noise noise; if(!dsp.prepare(rate))throw std::runtime_error("No 48k HRTF"); if(!dsp.setEarlyReflectionsShape(shape)|| !dsp.setEarlyReflectionsAmount(roomAmount)) throw std::runtime_error("Invalid orbit room configuration"); - Settings s=fixed(0.f);s.moving=true;s.clockwise=true;s.revolutionSeconds=10.f; + Settings s=fixed(0.f);s.moving=true;s.clockwise=clockwise;s.revolutionSeconds=10.f; dsp.reset();if(!dsp.setSettings(s))throw std::runtime_error("No 360 orbit"); const int frames=orbitFrames; // two complete turns on ONE continuous audio clock std::vector result; @@ -164,6 +165,8 @@ void notes(const std::filesystem::path& directory, <<"sonku-v2-square-orbit-cw-2x.wav = 7.2 x 7.2m symmetric room.\n" <<"Both candidates reuse the SAME direct HRTF/noise and 20s clock.\n" <<"Square geometry is not a guarantee of circular perception.\n" + <<"CCW versions contain FRONT>LEFT>REAR>RIGHT>FRONT each 10s.\n" + <<"Compare direction-reversed tracks to isolate turn-order effects.\n" <<"Both comparisons reuse exactly the same source noise and direct HRIR.\n" <<"Do blind-level and externalization evaluation before enabling V2 live.\n" <<"This is NOT full HRIR-convolved reflections, FDN or personalized HRTF.\n"; @@ -193,6 +196,12 @@ int main(int argc,char** argv){ writeWav(dir/"sonku-v2-room-orbit-cw-2x.wav",orbit(.55f)); writeWav(dir/"sonku-v2-square-orbit-cw-2x.wav", orbit(.55f,armix::sonku::SonKuRoomShape::Square)); + writeWav(dir/"sonku-orbit-ccw-2x.wav", + orbit(0.f,armix::sonku::SonKuRoomShape::Rectangular,false)); + writeWav(dir/"sonku-v2-room-orbit-ccw-2x.wav", + orbit(.55f,armix::sonku::SonKuRoomShape::Rectangular,false)); + writeWav(dir/"sonku-v2-square-orbit-ccw-2x.wav", + orbit(.55f,armix::sonku::SonKuRoomShape::Square,false)); notes(dir,blind); std::cout<<"SonKu listening package PASS: measured native HRTF, " <<"4 labeled + 8 blind directions + two uninterrupted 360 turns\n"; From 3a74b0273c7a7e13d5d2614183d19995eb12ad57 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:47:22 +0700 Subject: [PATCH 085/140] test(sonku-v2): import room-shape enum in mirror symmetry fixture --- tests/sonku_early_reflections_test.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/sonku_early_reflections_test.cpp b/tests/sonku_early_reflections_test.cpp index e6fd7b392..9d5787030 100644 --- a/tests/sonku_early_reflections_test.cpp +++ b/tests/sonku_early_reflections_test.cpp @@ -9,6 +9,7 @@ #include int main(){ using armix::sonku::SonKuEarlyReflections; + using armix::sonku::SonKuRoomShape; SonKuEarlyReflections invalid; assert(!invalid.prepare(96000.)); assert(!invalid.prepare(std::numeric_limits::quiet_NaN())); From 90d5a9e89636e397915a8fa366ecd45a4c0d8bd7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:49:58 +0700 Subject: [PATCH 086/140] ci: fast Linux preflight compiles full ChannelId routing CTest before expensive Windows --- .github/workflows/p1-windows.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 3bbd6f57a..4187198c3 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -182,6 +182,12 @@ jobs: node --test tests/rc_operator_workflow_contract.test.mjs tests/workstream_coordination_contract.test.mjs tests/ci_workflow_efficiency_test.mjs tests/chat_ci_dispatch_contract.test.mjs tests/approved_native_m2_contract.test.cjs tests/native_artifact_packaging_contract.test.mjs tests/windows_installer_contract_test.mjs tests/live_graph_contract_test.mjs tests/native_caption_wire_geometry_contract.test.cjs python -m unittest discover -s tests -p approved_native_gui_bundle_test.py -v python -m unittest discover -s scripts/tests -p test_factoryfx_release_bundle.py -v + # Portable ChannelId PCM routing MUST be checked in under a minute, + # before allocating a Windows JUCE/MSVC runner (93-CTest suite). + - name: Native ChannelId pre/post and fader PCM golden (Linux no JUCE) + run: | + g++ -std=c++20 -O2 -Wall -Wextra -Werror tests/mixer_routing_plan_test.cpp -o "$RUNNER_TEMP/armix-native-routing-pcm" + "$RUNNER_TEMP/armix-native-routing-pcm" - name: WaveShell JUCE 8 class-index regression (source-aware) shell: bash run: | From b79093bcc0f2cce7d05fc2372a1c2dd6555ef6a4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:50:01 +0700 Subject: [PATCH 087/140] test: expose exact PRE_FADER PCM mismatch and preserved roster values on failure --- tests/mixer_routing_plan_test.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/mixer_routing_plan_test.cpp b/tests/mixer_routing_plan_test.cpp index d8cbb7798..cb84679a8 100644 --- a/tests/mixer_routing_plan_test.cpp +++ b/tests/mixer_routing_plan_test.cpp @@ -10,6 +10,7 @@ #endif #include #include +#include #include using namespace armix::mixer; @@ -1124,7 +1125,14 @@ static void verifyNativePrePostAndSendEnablePcm() { assert(roster.find(mic)->sends[0].edgeId==edgeId); assert(roster.find(mic)->sends[0].gain==.5f); assert(host.commit(roster,req,1,874,874,true).ok()); - assert(render()&&close(left[63],.25f*2.f*mono*.5f,1.e-4f)); + const bool preRendered=render(); + const float expectedPre=.25f*2.f*mono*.5f; + if(!preRendered || !close(left[63],expectedPre,1.e-4f)) + std::fprintf(stderr,"PRE_POST_DIAG pre_render=%d L0=%.9g L63=%.9g R63=%.9g expected=%.9g gain=%.9g edge_pre=%d edge_gain=%.9g\n", + static_cast(preRendered),left[0],left[63],right[63],expectedPre, + roster.find(mic)->faderLinear,static_cast(roster.find(mic)->sends[0].preFader), + roster.find(mic)->sends[0].gain); + assert(preRendered&&close(left[63],expectedPre,1.e-4f)); assert(fxCalls==3); // one nonlinear FX pass per callback, no parallel duplicate assert(host.setWireEnabled(874,2,mic,edgeId,false)); assert(roster.rememberLiveSendEnabled(mic,edgeId,false)); From 27c8009a1d4c9acd5b8f5172cec68d23058d6092 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:52:36 +0700 Subject: [PATCH 088/140] fix(test-pcm): declare stereo FX RETURN and MAIN for accurate pre/post mono source golden levels --- tests/mixer_routing_plan_test.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/tests/mixer_routing_plan_test.cpp b/tests/mixer_routing_plan_test.cpp index cb84679a8..230b44cd2 100644 --- a/tests/mixer_routing_plan_test.cpp +++ b/tests/mixer_routing_plan_test.cpp @@ -1087,6 +1087,11 @@ static void verifyNativePrePostAndSendEnablePcm() { for(int i=0;i<3;++i){ add[i].kind=Kind::add;add[i].position=static_cast(i); add[i].role=i==0?ChannelRole::input:i==1?ChannelRole::fxReturn:ChannelRole::main; + // Deliberate mono microphone into stereo FX RETURN and stereo MAIN. + // Without explicit formats, ChannelEdit defaults ALL THREE to mono: + // wet and MAIN each apply an additional equal-power -3 dB pan. The + // golden .25*2*mono*.5 assumes only the input's mono-pan stage. + add[i].format=i==0?ProcessingFormat::mono:ProcessingFormat::stereo; add[i].text=i==0?"Mic":i==1?"Wet":"MAIN"; } const auto created=roster.edit(0,add); @@ -1115,7 +1120,17 @@ static void verifyNativePrePostAndSendEnablePcm() { const auto render=[&](){return host.render(874,physical,1, left.data(),right.data(),64,false,fx);}; constexpr float mono=.7071067811865475f; - assert(render()&&close(left[63],.25f*2.f*mono*.5f,1.e-4f)); + // Keep a real PCM assertion in Release and print both values when it + // fails: do not accept a DSP regression just to make Windows CI green. + const bool postRendered=render(); + const float expectedPost=.25f*2.f*mono*.5f; + if(!postRendered||!close(left[63],expectedPost,1.e-4f)) + std::fprintf(stderr,"PRE_POST_DIAG initial_post=%d L0=%.9g L63=%.9g R63=%.9g expected=%.9g source_format=%d wet_format=%d main_format=%d\\n", + static_cast(postRendered),left[0],left[63],right[63],expectedPost, + static_cast(roster.find(mic)->format), + static_cast(roster.find(wet)->format), + static_cast(roster.find(main)->format)); + assert(postRendered&&close(left[63],expectedPost,1.e-4f)); assert(host.setChannelMix(874,1,mic,0.f,0.f)); assert(roster.rememberLiveMix(mic,0.f,0.f)); assert(render()&&close(left[63],0.f)); From 200be5f9320718dc9beaaea8156c4b889d5d1fc0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 10:53:50 +0700 Subject: [PATCH 089/140] fix(test-pcm): explicit stereo MAIN for input gain before FX routing golden --- tests/mixer_routing_plan_test.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/mixer_routing_plan_test.cpp b/tests/mixer_routing_plan_test.cpp index 230b44cd2..888108e35 100644 --- a/tests/mixer_routing_plan_test.cpp +++ b/tests/mixer_routing_plan_test.cpp @@ -1025,7 +1025,10 @@ static void verifyNativeInputGainBeforeFx() { create[0].kind=Kind::add;create[0].position=0; create[0].role=ChannelRole::input;create[0].text="Mic"; create[1].kind=Kind::add;create[1].position=1; - create[1].role=ChannelRole::main;create[1].text="MAIN"; + create[1].role=ChannelRole::main;create[1].format=ProcessingFormat::stereo; + create[1].text="MAIN"; + // Preserve the golden microphone equal-power PAN without adding an + // unrelated second mono-pan attenuation on the MAIN sink. const auto added=roster.edit(0,create); assert(added.ok()); const auto mic=added.createdIds[0],main=added.createdIds[1]; From 115f4376786a2cede6609e584803344b4423e494 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 11:00:31 +0700 Subject: [PATCH 090/140] fix(test): encode native Unicode Python subprocess output as UTF-8 on Windows CP1252 --- tests/approved_native_m2_contract.test.cjs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index f5ea8b916..8a6451d17 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -34,7 +34,14 @@ test("WIRE inspector controls PRIMARY BUS and PARALLEL MAIN by actual EdgeId, wi "public approved /preview/ must never own native control authority"); const html=execFileSync("python3",["-c", "from scripts.build_approved_native_gui import native_html; from pathlib import Path; print(native_html(Path('site/preview-v2/index.html').read_text(encoding='utf-8')))" - ],{encoding:"utf8",maxBuffer:10*1024*1024}); + ],{ + encoding:"utf8",maxBuffer:10*1024*1024, + // Windows runner's default Python stdout is often CP1252. The approved + // GUI includes Unicode symbols (e.g. ◉), so explicitly encode THIS child + // stream as UTF-8 rather than relying on host code page or a global CI knob. + env:{...process.env,PYTHONIOENCODING:"utf-8"} + }); + assert.ok(html.includes("◉"),"native assembled Unicode survives Python stdout on Windows"); const bridge=read("web/approved-native-bridge.js"); const builder=read("scripts/build_approved_native_gui.py"); assert.match(bridge,/function admittedParallelWire\(uiSourceId,uiEdgeId,operation\)/); From 118dab7b34d84ed03a2a253eeaf07d9f86f2cc91 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 11:00:34 +0700 Subject: [PATCH 091/140] ci: emulate Windows CP1252 in cheap preflight before MSVC compilation --- .github/workflows/p1-windows.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 4187198c3..fe05f6e43 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -180,6 +180,9 @@ jobs: "$RUNNER_TEMP/armix-first-run-policy" node --test tests/native_first_run_bootstrap_contract.test.mjs node --test tests/rc_operator_workflow_contract.test.mjs tests/workstream_coordination_contract.test.mjs tests/ci_workflow_efficiency_test.mjs tests/chat_ci_dispatch_contract.test.mjs tests/approved_native_m2_contract.test.cjs tests/native_artifact_packaging_contract.test.mjs tests/windows_installer_contract_test.mjs tests/live_graph_contract_test.mjs tests/native_caption_wire_geometry_contract.test.cjs + # Simulate Windows CP1252 before allocating MSVC: the native + # inspector Python child must explicitly select UTF-8. + PYTHONIOENCODING=cp1252 node --test --test-name-pattern="WIRE inspector controls PRIMARY BUS" tests/approved_native_m2_contract.test.cjs python -m unittest discover -s tests -p approved_native_gui_bundle_test.py -v python -m unittest discover -s scripts/tests -p test_factoryfx_release_bundle.py -v # Portable ChannelId PCM routing MUST be checked in under a minute, From 3aca1833f40a47341cbf5c999e33582b09a988b5 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 11:13:14 +0700 Subject: [PATCH 092/140] feat(sonku): bounded eight-line stereo FDN late ambience with prepared RT60 presets --- engine/builtin_fx/sonku/SonKuMusicalReverb.h | 134 +++++++++++++++++++ engine/builtin_fx/sonku/SonKuSpatialCore.h | 20 ++- 2 files changed, 151 insertions(+), 3 deletions(-) create mode 100644 engine/builtin_fx/sonku/SonKuMusicalReverb.h diff --git a/engine/builtin_fx/sonku/SonKuMusicalReverb.h b/engine/builtin_fx/sonku/SonKuMusicalReverb.h new file mode 100644 index 000000000..f9775aad6 --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuMusicalReverb.h @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include + +// Compact eight-line stereo FDN for musical late ambience. The 8x8 Hadamard +// feedback matrix is orthogonal (unit-energy): stability depends solely on +// prepared per-line RT60 gains and damping. No heap/locks/FFT/trig/I/O in process. +// A small, diffuse late field complements the already-approved square early +// reflections; no source-following stereo pan is imposed on the reverb tail. +// These listening-test presets are OFF in the shipping JUCE editor. +namespace armix::sonku { +enum class SonKuReverbPreset : std::uint8_t { StudioGlue=0, AiryChamber=1 }; + +class SonKuMusicalReverb final { +public: + struct Ears {float left=0.f,right=0.f;}; + static constexpr int lineCount=8; + static constexpr int ringFrames=4096; + bool prepare(double rate) noexcept { + ready_=false; + if(!std::isfinite(rate) || (std::abs(rate-44100.)>.1 && + std::abs(rate-48000.)>.1))return false; + sampleRate_=static_cast(rate); + slew_=static_cast(1.-std::exp(-1./(rate*.012))); + amountTarget_=0.f; + preset_=SonKuReverbPreset::StudioGlue; + configure(); + reset(); + ready_=true; + return true; + } + void reset() noexcept { + for(auto& line:memory_)line.fill(0.f); + lowpass_.fill(0.f); + write_=0;amount_=0.f; + // The target amount is a CONTROL-side setting and survives resetting + // host transport/processor so the same program can restart cleanly. + } + bool setAmount(float amount) noexcept { + if(!std::isfinite(amount) || amount<0.f || amount>1.f)return false; + if(amount_==0.f && amountTarget_==0.f && amount>0.f)reset(); + amountTarget_=amount; + return true; + } + bool setPreset(SonKuReverbPreset value) noexcept { + if(value!=SonKuReverbPreset::StudioGlue && + value!=SonKuReverbPreset::AiryChamber)return false; + // Preset updates calculate RT60 coefficients. Never use this setter + // on an active realtime callback; native host doesn't expose it yet. + if(active())return false; + preset_=value; + configure(); + return true; + } + SonKuReverbPreset preset() const noexcept {return preset_;} + bool active() const noexcept {return ready_&&(amount_>0.f||amountTarget_>0.f);} + float targetAmount() const noexcept {return amountTarget_;} + Ears process(float left,float right) noexcept { + if(!active())return {}; + const float a=std::isfinite(left)?left:0.f; + const float b=std::isfinite(right)?right:0.f; + const float mid=.5f*(a+b); + const float side=.5f*(a-b); + std::array y{},mix{}; + for(int i=0;i inMid{1,1,-1,1,1,-1,-1,1}; + constexpr std::array inSide{1,-1,1,-1,1,-1,1,-1}; + constexpr std::array outL{1,-1,1,1,-1,1,-1,1}; + constexpr std::array outR{-1,1,1,-1,1,1,-1,1}; + float wetLeft=0.f,wetRight=0.f; + for(int i=0;i lengths{ + 2111,2339,2579,2803,3079,3319,3593,3929}; + const float rt60=preset_==SonKuReverbPreset::StudioGlue?.78f:1.28f; + const float cutoff=preset_==SonKuReverbPreset::StudioGlue?5900.f:7000.f; + constexpr float pi=3.14159265358979323846f; + dampCoeff_=1.f-std::exp(-2.f*pi*cutoff/sampleRate_); + for(int i=0;i(std::lround( + lengths[i]*sampleRate_/48000.f)),1,ringFrames-2); + gain_[i]=std::exp(-6.9077553f* + static_cast(delay_[i])/(sampleRate_*rt60)); + } + } + static_assert((ringFrames&(ringFrames-1))==0); + std::array,lineCount> memory_{}; + std::array lowpass_{}; + std::array gain_{}; + std::array delay_{}; + float sampleRate_=48000.f,dampCoeff_=0.f,slew_=0.f; + float amount_=0.f,amountTarget_=0.f; + int write_=0; + SonKuReverbPreset preset_=SonKuReverbPreset::StudioGlue; + bool ready_=false; +}; +} // namespace armix::sonku diff --git a/engine/builtin_fx/sonku/SonKuSpatialCore.h b/engine/builtin_fx/sonku/SonKuSpatialCore.h index 7ba5d1237..557c0d1ef 100644 --- a/engine/builtin_fx/sonku/SonKuSpatialCore.h +++ b/engine/builtin_fx/sonku/SonKuSpatialCore.h @@ -2,6 +2,7 @@ #pragma once #include "SonKuMeasuredHrir.h" #include "SonKuEarlyReflections.h" +#include "SonKuMusicalReverb.h" #include #include #include @@ -49,7 +50,7 @@ class SonKuSpatialCore final { // without trigonometric/exponential work in the audio callback. filterSlew_=static_cast(1.-std::exp(-1./(rate*0.006))); levelSlew_=static_cast(1.-std::exp(-1./(rate*0.008))); - if(!room_.prepare(rate))return false; + if(!room_.prepare(rate)||!reverb_.prepare(rate))return false; reset(); ready_=true; return true; @@ -65,6 +66,7 @@ class SonKuSpatialCore final { degrees_=wrapDegrees(settings_.startAzimuthDegrees); haveKernel_=false; room_.reset(); + reverb_.reset(); } bool setSettings(const Settings& s) noexcept { if(!valid(s))return false; @@ -87,6 +89,14 @@ class SonKuSpatialCore final { bool setEarlyReflectionsShape(SonKuRoomShape shape) noexcept { return room_.setShape(shape); } + // Experimental wet-only late room, OFF unless explicitly enabled by + // controlled offline A/B. The native parameter contract is unchanged. + bool setMusicalReverbAmount(float amount) noexcept { + return reverb_.setAmount(amount); + } + bool setMusicalReverbPreset(SonKuReverbPreset preset) noexcept { + return reverb_.setPreset(preset); + } bool ready() const noexcept {return ready_;} double azimuthDegrees() const noexcept {return degrees_;} // In-place stereo; caller owns valid, non-overlapping L/R PCM pointers. @@ -136,8 +146,11 @@ class SonKuSpatialCore final { const auto reflection=room_.active() ?room_.process(x0,x1,degrees_,settings_.stereoSpreadDegrees) :SonKuEarlyReflections::Ears{}; - left[i]=dryLevel*x0+binauralLevel*(ears[0]+reflection.left); - right[i]=dryLevel*x1+binauralLevel*(ears[1]+reflection.right); + const auto late=reverb_.active() + ?reverb_.process(x0,x1) + :SonKuMusicalReverb::Ears{}; + left[i]=dryLevel*x0+binauralLevel*(ears[0]+reflection.left+late.left); + right[i]=dryLevel*x1+binauralLevel*(ears[1]+reflection.right+late.right); if(++write_==taps)write_=0; if(step!=0.) { degrees_+=step; @@ -184,6 +197,7 @@ class SonKuSpatialCore final { std::array,2>,2> targets_{}; Settings settings_{}; SonKuEarlyReflections room_{}; + SonKuMusicalReverb reverb_{}; float smoothedMix_=1.f,smoothedTrim_=0.75f; float filterSlew_=0.f,levelSlew_=0.f; double sampleRate_=0.; From 30a75efc424f6d98efb9132b016ac9e23984a7a8 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 11:15:20 +0700 Subject: [PATCH 093/140] test(sonku): musical FDN impulse/PCM/CPU gates and 2x orbit A-B listening renders --- .github/workflows/ui-smoke.yml | 2 + ...KU_V2_EXTERNALIZATION_DECISION_20261113.md | 5 ++ tests/sonku_musical_reverb_test.cpp | 62 +++++++++++++++++++ tests/sonku_offline_demo_contract.py | 10 ++- tests/sonku_spatial_core_test.cpp | 31 ++++++++++ tools/sonku_offline_listening.cpp | 23 ++++++- tools/sonku_rt_benchmark.cpp | 9 ++- 7 files changed, 136 insertions(+), 6 deletions(-) create mode 100644 tests/sonku_musical_reverb_test.cpp diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 03fc36a4f..2b0cdc9e2 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -215,6 +215,8 @@ jobs: /tmp/sonku-listening sonku-listening g++ -std=c++20 -O2 -Wall -Wextra -pedantic tests/sonku_early_reflections_test.cpp -o /tmp/sonku-room-test /tmp/sonku-room-test + g++ -std=c++20 -O2 -Wall -Wextra -pedantic tests/sonku_musical_reverb_test.cpp -o /tmp/sonku-fdn-test + /tmp/sonku-fdn-test - name: SonKu same-runner realtime CPU comparison (informational, not a release pass) run: | g++ -std=c++20 -O2 -Wall -Wextra -pedantic tools/sonku_rt_benchmark.cpp -o /tmp/sonku-rt-bench diff --git a/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md index b7acf194f..d746285c0 100644 --- a/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md +++ b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md @@ -43,3 +43,8 @@ The report of an elliptical/unequal-distance orbit does NOT prove a room-model b ## 2026-11-13 — independent reversed-motion listening probes In response to asymmetrical perceived naturalness of RIGHT→FRONT vs FRONT→RIGHT, add three CCW two-turn WAVs alongside the three clockwise versions. All six are 20 seconds, use the exact same deterministic original noise, same native HRTF and DSP sample clock, and have no loop seam. Clockwise: FRONT → RIGHT → REAR → LEFT → FRONT. Counterclockwise: FRONT → LEFT → REAR → RIGHT → FRONT. This allows listening comparison of RIGHT→FRONT (CCW at 7.5–10 and 17.5–20 seconds) with FRONT→RIGHT (CW at 0–2.5 and 10–12.5 seconds), and tests whether perceptual asymmetry reverses with source rotation direction. No additional live motion modes, no UI changes, no assertion of physically circular perception. + +## 2026-11-13 — listener-approved Square Orbit checkpoint and musical late reverb M2 +The owner has listened to and approved the **square-room orbit as perceptually circular**. Its exact base code is pinned at `checkpoint/8d-sonku-square-orbit-approved-20261113` (`3a74b0273c7a7e13d5d2614183d19995eb12ad57`); this immutable evaluation milestone must not be overwritten by reverb experiments. There already are eight bounded 1st-order wall-reflection paths (four per source), but **there was no late reverb**. + +New *opt-in offline candidate*, original `SonKuMusicalReverb.h`: 8 noncommensurate delays with a normalized Hadamard orthogonal feedback matrix, per-line RT60 feedback gains prepared for 44.1/48k, damping low-pass in the loop, stereo decorrelated output, 12ms wet ramp, and at least 43ms to first late energy. Max delay ring 8×4096 floats (~128KiB) with no dynamic PCM buffer, FFT, allpass resonator cascade, or per-sample trigonometry/exp. Two listening-only presets: Studio Glue (RT60 ~0.78s; 5.9kHz damping) and Airy Chamber (RT60 ~1.28s; 7kHz). Wet amount .42 for controlled A/B is intentionally modest and **OFF in the native plugin**. Square early reflections remain exactly as approved, with no room-size or HRTF clock modification. Compare baseline square with Studio Glue and Airy Chamber 20s 2-turn WAVs, using same source, latency, level trim, azimuth and direct HRIR. C++ tests validate stable impulse energy, late onset, stereo width, RT60 decay, byte-exact disabled state and PCM partition parity. No GUI knob, session upgrade or public release until listener feedback and physical Windows audio qualification. FDN theory: Stautner/Puckette (1982), Jot/Chaigne (1991), and practical low-metallic density guidance from Valhalla DSP; original GPL-compatible implementation, no copied commercial source. diff --git a/tests/sonku_musical_reverb_test.cpp b/tests/sonku_musical_reverb_test.cpp new file mode 100644 index 000000000..3a099734a --- /dev/null +++ b/tests/sonku_musical_reverb_test.cpp @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#if defined(NDEBUG) +#undef NDEBUG +#endif +#include "../engine/builtin_fx/sonku/SonKuMusicalReverb.h" +#include +#include +#include +#include + +int main(){ + using armix::sonku::SonKuMusicalReverb; + using armix::sonku::SonKuReverbPreset; + SonKuMusicalReverb invalid; + assert(!invalid.prepare(96000.)); + assert(!invalid.prepare(std::numeric_limits::quiet_NaN())); + for(double rate:{44100.,48000.}){ + SonKuMusicalReverb fx,copy; + assert(fx.prepare(rate)&©.prepare(rate)); + assert(!fx.active()); + assert(!fx.setAmount(-.1f)); + assert(!fx.setAmount(std::numeric_limits::infinity())); + assert(!fx.setPreset(static_cast(99))); + assert(fx.setPreset(SonKuReverbPreset::StudioGlue)); + assert(copy.setPreset(SonKuReverbPreset::StudioGlue)); + assert(fx.setAmount(.40f)&©.setAmount(.40f)); + assert(!fx.setPreset(SonKuReverbPreset::AiryChamber)); + const int count=static_cast(rate*2.0); + double energy=0.,width=0.,early=0.,late=0.; + for(int i=0;i2000)energy+=magnitude; + if(i>2000&&irate*1.5)late+=magnitude; + } + assert(early==0.); // direct + early stays untouched + assert(energy>.005 && width>.002); // diffuse stereo field, not mono + assert(late(rate);++i){ + const auto output=fx.process(i==0?.4f:0.f,i==0?.4f:0.f); + airy+=std::abs(output.left)+std::abs(output.right); + } + assert(airy>.005); + } + return 0; +} diff --git a/tests/sonku_offline_demo_contract.py b/tests/sonku_offline_demo_contract.py index 1cfba47c2..42524b649 100644 --- a/tests/sonku_offline_demo_contract.py +++ b/tests/sonku_offline_demo_contract.py @@ -30,6 +30,8 @@ def read(name, frames): reverse=read("sonku-orbit-ccw-2x.wav",960000) reverseRoom=read("sonku-v2-room-orbit-ccw-2x.wav",960000) reverseSquare=read("sonku-v2-square-orbit-ccw-2x.wav",960000) +glue=read("sonku-v3-square-glue-cw-2x.wav",960000) +airy=read("sonku-v3-square-airy-cw-2x.wav",960000) # Baseline V1 and candidate V2 are deliberately non-identical on same noise. # Room must affect later samples, not fake position on the direct sound. difference=sum(abs(int(a)-int(b)) for a,b in @@ -45,6 +47,12 @@ def read(name, frames): reverseDelta=sum(abs(int(a)-int(b)) for a,b in zip(reverse[350000:500000],orbit[350000:500000])) assert reverseDelta>1500,("CW/CCW unexpectedly identical",reverseDelta) +for name,candidate in (("glue",glue),("airy",airy)): + fdnDelta=sum(abs(int(a)-int(b)) for a,b in + zip(candidate[400000:550000],squareOrbit[400000:550000])) + assert fdnDelta>1500,("FDN stage produced identical PCM",name,fdnDelta) +distinct=sum(abs(int(a)-int(b)) for a,b in zip(glue[400000:550000],airy[400000:550000])) +assert distinct>1500,("FDN Studio Glue and Airy Chamber matched exactly",distinct) # +90° (second reference segment) has a distinct binaural response. section=single[120000*2:120000*4] left=sum(abs(section[i]) for i in range(0,len(section),2)) @@ -54,7 +62,7 @@ def read(name, frames): assert sum(abs(x) for x in orbit[220000:230000])>1000 # Verify there is no mute, edit or source reset at the 10s handoff. # Stereo interleaved: 48000 samples = 1 second, 2 PCM ints per frame. -for audio in (orbit,v2orbit,squareOrbit,reverse,reverseRoom,reverseSquare): +for audio in (orbit,v2orbit,squareOrbit,reverse,reverseRoom,reverseSquare,glue,airy): for second in (9,10,11,19): begin=(second*48000+4000)*2 assert sum(abs(x) for x in audio[begin:begin+9600])>2000,( diff --git a/tests/sonku_spatial_core_test.cpp b/tests/sonku_spatial_core_test.cpp index d70ff4988..6324e8b84 100644 --- a/tests/sonku_spatial_core_test.cpp +++ b/tests/sonku_spatial_core_test.cpp @@ -110,6 +110,37 @@ int main() { std::abs(wetR[i]-noR[i]); } assert(roomDifference>.001); + // V3 late room is strictly opt-in, delayed and sample-partition + // deterministic. The approved direct-HRTF + square ER is untouched + // before the first late echo. + SonKuSpatialCore glow,glowChunks; + assert(glow.prepare(rate)&&glowChunks.prepare(rate)); + assert(glow.setEarlyReflectionsShape(SonKuRoomShape::Square)); + assert(glowChunks.setEarlyReflectionsShape(SonKuRoomShape::Square)); + assert(glow.setSettings(roomSettings)&&glowChunks.setSettings(roomSettings)); + assert(glow.setEarlyReflectionsAmount(.55f)&&glowChunks.setEarlyReflectionsAmount(.55f)); + assert(glow.setMusicalReverbAmount(.42f)&&glowChunks.setMusicalReverbAmount(.42f)); + std::array tailL{},tailR{},splitL{},splitR{}; + tailL[0]=splitL[0]=.5f;tailR[0]=splitR[0]=.5f; + glow.process(tailL.data(),tailR.data(),roomFrames); + glowChunks.process(splitL.data(),splitR.data(),128); + glowChunks.process(splitL.data()+128,splitR.data()+128,384); + glowChunks.process(splitL.data()+512,splitR.data()+512,roomFrames-512); + double diff=0.; + for(int i=0;i2200)diff+=std::abs(tailL[i]-wetL[i])+ + std::abs(tailR[i]-wetR[i]); + } + assert(diff>.001); // A hard FRONT->REAR teleport must not replace 560 FIR coefficients // at the next 16-sample boundary. Compare the identical dry/PCM // history before and immediately after reposition. diff --git a/tools/sonku_offline_listening.cpp b/tools/sonku_offline_listening.cpp index 1d0126c19..12c511e32 100644 --- a/tools/sonku_offline_listening.cpp +++ b/tools/sonku_offline_listening.cpp @@ -104,12 +104,16 @@ std::vector staticProbes(const std::vector& azimuths,float ro } std::vector orbit(float roomAmount=0.f, armix::sonku::SonKuRoomShape shape=armix::sonku::SonKuRoomShape::Rectangular, - bool clockwise=true){ + bool clockwise=true,float lateAmount=0.f, + armix::sonku::SonKuReverbPreset latePreset= + armix::sonku::SonKuReverbPreset::StudioGlue){ SonKuSpatialCore dsp;Noise noise; if(!dsp.prepare(rate))throw std::runtime_error("No 48k HRTF"); if(!dsp.setEarlyReflectionsShape(shape)|| - !dsp.setEarlyReflectionsAmount(roomAmount)) - throw std::runtime_error("Invalid orbit room configuration"); + !dsp.setMusicalReverbPreset(latePreset)|| + !dsp.setEarlyReflectionsAmount(roomAmount)|| + !dsp.setMusicalReverbAmount(lateAmount)) + throw std::runtime_error("Invalid orbit acoustic configuration"); Settings s=fixed(0.f);s.moving=true;s.clockwise=clockwise;s.revolutionSeconds=10.f; dsp.reset();if(!dsp.setSettings(s))throw std::runtime_error("No 360 orbit"); const int frames=orbitFrames; // two complete turns on ONE continuous audio clock @@ -167,6 +171,13 @@ void notes(const std::filesystem::path& directory, <<"Square geometry is not a guarantee of circular perception.\n" <<"CCW versions contain FRONT>LEFT>REAR>RIGHT>FRONT each 10s.\n" <<"Compare direction-reversed tracks to isolate turn-order effects.\n" + <<"sonku-v3-square-glue-cw-2x.wav = approved square ROOM plus\n" + <<" subdued stereo 8-line FDN, Studio Glue RT60 ~0.78s.\n" + <<"sonku-v3-square-airy-cw-2x.wav = same square ROOM with\n" + <<" more spacious FDN Airy Chamber RT60 ~1.28s.\n" + <<"V2 square and V3 candidates share the exact 20s original source,\n" + <<"HRTF, four-wall ER, angle clock and output trim.\n" + <<"FDN candidate is wet-only and OFF in native plugin by default.\n" <<"Both comparisons reuse exactly the same source noise and direct HRIR.\n" <<"Do blind-level and externalization evaluation before enabling V2 live.\n" <<"This is NOT full HRIR-convolved reflections, FDN or personalized HRTF.\n"; @@ -202,6 +213,12 @@ int main(int argc,char** argv){ orbit(.55f,armix::sonku::SonKuRoomShape::Rectangular,false)); writeWav(dir/"sonku-v2-square-orbit-ccw-2x.wav", orbit(.55f,armix::sonku::SonKuRoomShape::Square,false)); + writeWav(dir/"sonku-v3-square-glue-cw-2x.wav", + orbit(.55f,armix::sonku::SonKuRoomShape::Square,true,.42f, + armix::sonku::SonKuReverbPreset::StudioGlue)); + writeWav(dir/"sonku-v3-square-airy-cw-2x.wav", + orbit(.55f,armix::sonku::SonKuRoomShape::Square,true,.42f, + armix::sonku::SonKuReverbPreset::AiryChamber)); notes(dir,blind); std::cout<<"SonKu listening package PASS: measured native HRTF, " <<"4 labeled + 8 blind directions + two uninterrupted 360 turns\n"; diff --git a/tools/sonku_rt_benchmark.cpp b/tools/sonku_rt_benchmark.cpp index 9b3a0f9fd..3336e5749 100644 --- a/tools/sonku_rt_benchmark.cpp +++ b/tools/sonku_rt_benchmark.cpp @@ -13,13 +13,14 @@ namespace { struct Result {double milliseconds=0.,checksum=0.,audios=0.;}; template -Result measure(double rate,float amount){ +Result measure(double rate,float amount,float late=0.f){ using namespace armix::sonku; SonKuSpatialCore dsp; if(!dsp.prepare(rate))throw std::runtime_error("unsupported sample rate"); Settings s{};s.moving=true;s.revolutionSeconds=10.f; s.spatialMix=1.f;s.stereoSpreadDegrees=60.f; - if(!dsp.setSettings(s)||!dsp.setEarlyReflectionsAmount(amount)) + if(!dsp.setSettings(s)||!dsp.setEarlyReflectionsAmount(amount)|| + !dsp.setMusicalReverbAmount(late)) throw std::runtime_error("invalid DSP setup"); std::array inputL{},inputR{}; for(std::size_t n=0;n void report(double rate){ const auto baseline=measure(rate,0.f); const auto room=measure(rate,.55f); + const auto musical=measure(rate,.55f,.42f); std::cout< Date: Fri, 13 Nov 2026 11:19:42 +0700 Subject: [PATCH 094/140] feat(sonku): original plucked-tone musical A/B on approved square orbit --- ...KU_V2_EXTERNALIZATION_DECISION_20261113.md | 3 + tests/sonku_offline_demo_contract.py | 10 +++ tools/sonku_offline_listening.cpp | 66 +++++++++++++++++++ 3 files changed, 79 insertions(+) diff --git a/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md index d746285c0..d61993276 100644 --- a/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md +++ b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md @@ -48,3 +48,6 @@ In response to asymmetrical perceived naturalness of RIGHT→FRONT vs FRONT→RI The owner has listened to and approved the **square-room orbit as perceptually circular**. Its exact base code is pinned at `checkpoint/8d-sonku-square-orbit-approved-20261113` (`3a74b0273c7a7e13d5d2614183d19995eb12ad57`); this immutable evaluation milestone must not be overwritten by reverb experiments. There already are eight bounded 1st-order wall-reflection paths (four per source), but **there was no late reverb**. New *opt-in offline candidate*, original `SonKuMusicalReverb.h`: 8 noncommensurate delays with a normalized Hadamard orthogonal feedback matrix, per-line RT60 feedback gains prepared for 44.1/48k, damping low-pass in the loop, stereo decorrelated output, 12ms wet ramp, and at least 43ms to first late energy. Max delay ring 8×4096 floats (~128KiB) with no dynamic PCM buffer, FFT, allpass resonator cascade, or per-sample trigonometry/exp. Two listening-only presets: Studio Glue (RT60 ~0.78s; 5.9kHz damping) and Airy Chamber (RT60 ~1.28s; 7kHz). Wet amount .42 for controlled A/B is intentionally modest and **OFF in the native plugin**. Square early reflections remain exactly as approved, with no room-size or HRTF clock modification. Compare baseline square with Studio Glue and Airy Chamber 20s 2-turn WAVs, using same source, latency, level trim, azimuth and direct HRIR. C++ tests validate stable impulse energy, late onset, stereo width, RT60 decay, byte-exact disabled state and PCM partition parity. No GUI knob, session upgrade or public release until listener feedback and physical Windows audio qualification. FDN theory: Stautner/Puckette (1982), Jot/Chaigne (1991), and practical low-metallic density guidance from Valhalla DSP; original GPL-compatible implementation, no copied commercial source. + +## 2026-11-13 — original musical-content A/B +Because broadband noise cannot reveal whether a late reverb is pleasing on music, the exact core offline renderer now also creates a deterministic 20-second synthetic plucked-tone motif, repeated identically once per 360° orbit, under the same Square ER. Three WAVs: baseline late OFF; Studio Glue RT60≈0.78s; Airy Chamber RT60≈1.28s. The melody is originally generated test material, with no copyrighted recordings. Envelope fades within each note to avoid spurious onset clicks. C++ and Python gates verify correct WAV format, PCM non-identity between presets and no clipping. This remains a **perceptual candidate**, not an assertion of musical quality. diff --git a/tests/sonku_offline_demo_contract.py b/tests/sonku_offline_demo_contract.py index 42524b649..dde0b43f6 100644 --- a/tests/sonku_offline_demo_contract.py +++ b/tests/sonku_offline_demo_contract.py @@ -32,6 +32,9 @@ def read(name, frames): reverseSquare=read("sonku-v2-square-orbit-ccw-2x.wav",960000) glue=read("sonku-v3-square-glue-cw-2x.wav",960000) airy=read("sonku-v3-square-airy-cw-2x.wav",960000) +musicBase=read("sonku-musical-square-base-2x.wav",960000) +musicGlue=read("sonku-musical-square-glue-2x.wav",960000) +musicAiry=read("sonku-musical-square-airy-2x.wav",960000) # Baseline V1 and candidate V2 are deliberately non-identical on same noise. # Room must affect later samples, not fake position on the direct sound. difference=sum(abs(int(a)-int(b)) for a,b in @@ -53,6 +56,13 @@ def read(name, frames): assert fdnDelta>1500,("FDN stage produced identical PCM",name,fdnDelta) distinct=sum(abs(int(a)-int(b)) for a,b in zip(glue[400000:550000],airy[400000:550000])) assert distinct>1500,("FDN Studio Glue and Airy Chamber matched exactly",distinct) +for name,variant in (("glue",musicGlue),("airy",musicAiry)): + delta=sum(abs(int(a)-int(b)) for a,b in + zip(variant[300000:540000],musicBase[300000:540000])) + assert delta>1000,("Musical FDN did not alter original tones",name,delta) +musicDistinct=sum(abs(int(a)-int(b)) for a,b in + zip(musicGlue[300000:540000],musicAiry[300000:540000])) +assert musicDistinct>1000,("Musical presets sound identical",musicDistinct) # +90° (second reference segment) has a distinct binaural response. section=single[120000*2:120000*4] left=sum(abs(section[i]) for i in range(0,len(section),2)) diff --git a/tools/sonku_offline_listening.cpp b/tools/sonku_offline_listening.cpp index 12c511e32..548ceeb1b 100644 --- a/tools/sonku_offline_listening.cpp +++ b/tools/sonku_offline_listening.cpp @@ -138,6 +138,60 @@ std::vector orbit(float roomAmount=0.f, throw std::runtime_error("Two turns do not close acoustic orbit"); return result; } +// Original 20-second plucked-tone motif (20 half-second events, repeated on +// both revolutions). Synthesized here rather than using protected recordings. +// This deliberately exposes metallic late-tail coloration hidden by noise tests. +// It uses the EXACT same SonKuSpatialCore and accepted square early room. +std::vector musicalOrbit(float lateAmount, + armix::sonku::SonKuReverbPreset preset){ + SonKuSpatialCore dsp; + if(!dsp.prepare(rate)|| + !dsp.setEarlyReflectionsShape(armix::sonku::SonKuRoomShape::Square)|| + !dsp.setMusicalReverbPreset(preset)|| + !dsp.setEarlyReflectionsAmount(.55f)|| + !dsp.setMusicalReverbAmount(lateAmount)) + throw std::runtime_error("Invalid original musical test configuration"); + Settings s=fixed(0.f);s.moving=true;s.clockwise=true;s.revolutionSeconds=10.f; + dsp.reset();if(!dsp.setSettings(s))throw std::runtime_error("Invalid musical orbit"); + constexpr std::array notes{ + 57,64,60,69,62,65,69,60,64,67, + 71,67,65,72,69,64,60,67,64,62}; + std::array frequencies{}; + for(std::size_t i=0;i bytes; + bytes.reserve(static_cast(orbitFrames)*4); + for(int base=0;base l{},r{}; + for(int i=0;i(notes.size()); + const int position=at%noteFrames; + const float t=static_cast(position)/noteFrames; + const float attack=std::clamp(position/(rate*.009f),0.f,1.f); + const float release=std::clamp( + (noteFrames-1-position)/(rate*.030f),0.f,1.f); + const float envelope=attack*release*std::exp(-3.2f*t); + const double theta=2.*pi*frequencies[static_cast(note)]* + static_cast(position)/rate; + const float tonal=static_cast( + std::sin(theta)+.27*std::sin(2.*theta)+ + .31*std::sin(theta*1.5)); + const float sample=.115f*envelope*tonal; + l[static_cast(i)]=sample; + r[static_cast(i)]=sample; + } + dsp.process(l.data(),r.data(),n); + for(int i=0;i.01) + throw std::runtime_error("Musical double orbit did not close"); + return bytes; +} const char* direction(int deg) { switch(deg){case 0:return "FRONT";case 90:return "RIGHT";case 180:return "REAR"; case -90:return "LEFT";default:return "INVALID";} @@ -178,6 +232,12 @@ void notes(const std::filesystem::path& directory, <<"V2 square and V3 candidates share the exact 20s original source,\n" <<"HRTF, four-wall ER, angle clock and output trim.\n" <<"FDN candidate is wet-only and OFF in native plugin by default.\n" + <<"sonku-musical-square-base-2x.wav = original synthetic plucks,\n" + <<" approved square ER with NO late reverb.\n" + <<"sonku-musical-square-glue-2x.wav = identical plucks with Studio Glue.\n" + <<"sonku-musical-square-airy-2x.wav = identical plucks with Airy Chamber.\n" + <<"The plucks are ORIGINAL test tones (no copyrighted composition).\n" + <<"Use them to judge vocal-like reverb coloration/tail musicality.\n" <<"Both comparisons reuse exactly the same source noise and direct HRIR.\n" <<"Do blind-level and externalization evaluation before enabling V2 live.\n" <<"This is NOT full HRIR-convolved reflections, FDN or personalized HRTF.\n"; @@ -219,6 +279,12 @@ int main(int argc,char** argv){ writeWav(dir/"sonku-v3-square-airy-cw-2x.wav", orbit(.55f,armix::sonku::SonKuRoomShape::Square,true,.42f, armix::sonku::SonKuReverbPreset::AiryChamber)); + writeWav(dir/"sonku-musical-square-base-2x.wav", + musicalOrbit(0.f,armix::sonku::SonKuReverbPreset::StudioGlue)); + writeWav(dir/"sonku-musical-square-glue-2x.wav", + musicalOrbit(.42f,armix::sonku::SonKuReverbPreset::StudioGlue)); + writeWav(dir/"sonku-musical-square-airy-2x.wav", + musicalOrbit(.42f,armix::sonku::SonKuReverbPreset::AiryChamber)); notes(dir,blind); std::cout<<"SonKu listening package PASS: measured native HRTF, " <<"4 labeled + 8 blind directions + two uninterrupted 360 turns\n"; From 63a85fbb010d6e5590ed7bfe1673eb5bed50af1f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 12:54:00 +0700 Subject: [PATCH 095/140] test(sonku): compare late FDN against exact approved square PCM baseline --- tests/sonku_spatial_core_test.cpp | 41 ++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/tests/sonku_spatial_core_test.cpp b/tests/sonku_spatial_core_test.cpp index 6324e8b84..12689ec53 100644 --- a/tests/sonku_spatial_core_test.cpp +++ b/tests/sonku_spatial_core_test.cpp @@ -4,6 +4,7 @@ #endif #include "../engine/builtin_fx/sonku/SonKuSpatialCore.h" #include +#include #include #include #include @@ -113,34 +114,46 @@ int main() { // V3 late room is strictly opt-in, delayed and sample-partition // deterministic. The approved direct-HRTF + square ER is untouched // before the first late echo. + // IMPORTANT: the accepted reference is SQUARE, not the earlier + // rectangular V2 room. A rectangle-vs-square comparison cannot + // establish that adding the FDN leaves the approved orbit intact. + // Allocate this extra test processor off-stack (each core owns + // fixed ~192 KiB acoustic rings; Windows test stacks are bounded). + auto approvedSquare=std::make_unique(); SonKuSpatialCore glow,glowChunks; - assert(glow.prepare(rate)&&glowChunks.prepare(rate)); + assert(approvedSquare->prepare(rate)&&glow.prepare(rate)&&glowChunks.prepare(rate)); + assert(approvedSquare->setEarlyReflectionsShape(SonKuRoomShape::Square)); assert(glow.setEarlyReflectionsShape(SonKuRoomShape::Square)); assert(glowChunks.setEarlyReflectionsShape(SonKuRoomShape::Square)); - assert(glow.setSettings(roomSettings)&&glowChunks.setSettings(roomSettings)); - assert(glow.setEarlyReflectionsAmount(.55f)&&glowChunks.setEarlyReflectionsAmount(.55f)); + assert(approvedSquare->setSettings(roomSettings)&& + glow.setSettings(roomSettings)&&glowChunks.setSettings(roomSettings)); + assert(approvedSquare->setEarlyReflectionsAmount(.55f)&& + glow.setEarlyReflectionsAmount(.55f)&& + glowChunks.setEarlyReflectionsAmount(.55f)); assert(glow.setMusicalReverbAmount(.42f)&&glowChunks.setMusicalReverbAmount(.42f)); - std::array tailL{},tailR{},splitL{},splitR{}; - tailL[0]=splitL[0]=.5f;tailR[0]=splitR[0]=.5f; + std::array squareL{},squareR{},tailL{},tailR{},splitL{},splitR{}; + squareL[0]=squareR[0]=tailL[0]=tailR[0]=splitL[0]=splitR[0]=.5f; + approvedSquare->process(squareL.data(),squareR.data(),roomFrames); glow.process(tailL.data(),tailR.data(),roomFrames); glowChunks.process(splitL.data(),splitR.data(),128); glowChunks.process(splitL.data()+128,splitR.data()+128,384); glowChunks.process(splitL.data()+512,splitR.data()+512,roomFrames-512); - double diff=0.; + double lateDifference=0.; for(int i=0;i43 ms at both qualified rates. + // This proves exact sample identity in the approved square + // direct+ER path before late ambience arrives. + if(i<1800){ + assert(tailL[i]==squareL[i]); + assert(tailR[i]==squareR[i]); } - if(i>2200)diff+=std::abs(tailL[i]-wetL[i])+ - std::abs(tailR[i]-wetR[i]); + if(i>2200)lateDifference+=std::abs(tailL[i]-squareL[i])+ + std::abs(tailR[i]-squareR[i]); } - assert(diff>.001); + assert(lateDifference>.001); // A hard FRONT->REAR teleport must not replace 560 FIR coefficients // at the next 16-sample boundary. Compare the identical dry/PCM // history before and immediately after reposition. From 28153ec20a0db014f512ef7244a65caa6b56d0c0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:00:53 +0700 Subject: [PATCH 096/140] test(sof): real native Chromium EdgeId gain, tap, SEND ON, ACK/readback and MAIN protection --- tests/approved_native_sof_chromium_smoke.py | 203 ++++++++++++++++++++ 1 file changed, 203 insertions(+) create mode 100644 tests/approved_native_sof_chromium_smoke.py diff --git a/tests/approved_native_sof_chromium_smoke.py b/tests/approved_native_sof_chromium_smoke.py new file mode 100644 index 000000000..760732ed8 --- /dev/null +++ b/tests/approved_native_sof_chromium_smoke.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Actual compiled native Sends-on-Faders GUI: EdgeId intents -> ACK -> readback. + +Uses the SAME native-only assembled /preview/ as the Windows WebView2 host. +Playwright emulates the JUCE transport, never PCM or a second audio engine. +PCM PRE/POST, gain slew and enable gates are independently verified in CTest. +No private mixer mutators, reference reducer, or fake browser audio are used. +""" +from __future__ import annotations + +import copy +import importlib.util +from pathlib import Path +import tempfile + +from playwright.sync_api import sync_playwright +from approved_native_wire_gain_smoke import MAIN, RECEIVER, SEND, SOURCE, ack, emit, snapshot + +ROOT = Path(__file__).resolve().parents[1] + + +def admitted_session(): + state = snapshot() + graph = state["graph"] + graph["capabilities"]["supportedOps"] = [ + "SET_FADER", "SET_WIRE_GAIN", "SET_SEND_ENABLED", "APPLY_WIRE_TRANSACTION" + ] + graph["channels"][0]["controls"]["faderDb"] = -7.5 + graph["channels"][1]["role"] = "GROUP" + graph["channels"][1]["name"] = "STAGE BUS" + graph["edges"][1]["sendEnabled"] = True + graph["destinations"] = [ + {k: channel[k] for k in ("id", "role", "name")} + for channel in graph["channels"] + ] + state["mixerSession"]["channels"] = copy.deepcopy(graph["channels"]) + state["productionCallbackLive"] = True + return state + + +def intent_list(page, operation): + return page.evaluate( + "operation=>window.__nativeIntents.filter(x=>x.operation===operation)", + operation, + ) + + +def wait_for_intents(page, operation, count): + page.wait_for_function( + """([operation,count])=> + window.__nativeIntents.filter(x=>x.operation===operation).length>=count""", + arg=[operation, count], timeout=6000, + ) + values = intent_list(page, operation) + assert len(values) == count, (operation, values) + return values[-1] + + +def exercise(browser, out, width, height): + page = browser.new_page(viewport={"width":width, "height":height}) + errors = [] + page.on("pageerror", lambda error: errors.append(str(error))) + page.add_init_script("""window.__nativeListeners=new Map();window.__nativeIntents=[]; + window.__JUCE__={backend:{ + emitEvent(name,payload){ + if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload); + }, + addEventListener(name,callback){window.__nativeListeners.set(name,callback);} + }};""") + page.goto((out/"index.html").as_uri()) + page.wait_for_function("()=>window.__ARMIX_NATIVE_M2__?.enabled", timeout=15000) + state = admitted_session() + emit(page, "arMixConsoleSnapshot", state) + source = page.locator('#tracks .strip[data-id="1"]') + source.wait_for(state="attached",timeout=15000) + target = page.locator("#sofTarget") + toggle = page.locator("#sofToggle") + assert toggle.is_visible() and toggle.is_enabled(), ( + "A current native PCM graph with all three SEND capabilities must admit SOF") + options = target.locator("option").all_text_contents() + assert any("STAGE BUS" in label for label in options), options + target.select_option(label=next(label for label in options if "STAGE BUS" in label)) + toggle.click() + assert page.locator("#mixContext").inner_text() == "SEND MIX → STAGE BUS" + on = source.locator('[data-action="sofOn"]') + tap = source.locator('[data-action="sofTap"]') + assert on.is_enabled() and tap.is_enabled() + assert on.get_attribute("aria-pressed") == "true" + assert "POST-FADER" in source.locator(".sof-badge").inner_text() + assert not source.locator(".fader").is_disabled(), "Admitted send must own SOF fader" + + # SEND OFF is a scalar against the EXACT existing EdgeId, not topology. + on.click() + off = wait_for_intents(page, "SET_SEND_ENABLED", 1) + assert off["channelId"] == SOURCE and off["payload"] == { + "edgeId":SEND,"enabled":False + }, off + assert on.get_attribute("aria-pressed") == "true", ( + "An unacknowledged intent must not visibly turn off the accepted send") + ack(page, state, off) + assert on.get_attribute("aria-pressed") == "true", "ACK alone is not PCM readback" + state["graph"]["edges"][1]["sendEnabled"] = False + emit(page, "arMixConsoleSnapshot", state) + page.wait_for_function("""()=>document.querySelector( + '#tracks .strip[data-id="1"] [data-action="sofOn"]')?.getAttribute('aria-pressed')==='false'""") + assert source.locator(".sof-badge").inner_text() == "POST-FADER" + assert "OFF" in source.locator(".sof-info small").inner_text() + assert len(state["graph"]["edges"]) == 3 + assert state["graph"]["edges"][1]["gainLinear"] == .5 + + on = source.locator('[data-action="sofOn"]') + on.click() + enabled = wait_for_intents(page, "SET_SEND_ENABLED", 2) + assert enabled["payload"] == {"edgeId":SEND,"enabled":True} + ack(page, state, enabled) + state["graph"]["edges"][1]["sendEnabled"] = True + emit(page, "arMixConsoleSnapshot", state) + page.wait_for_function("""()=>document.querySelector( + '#tracks .strip[data-id="1"] [data-action="sofOn"]')?.getAttribute('aria-pressed')==='true'""") + + # A PRE-FADER tap changes the installed graph revision; no DOM optimism. + source.locator('[data-action="sofTap"]').click() + structural = wait_for_intents(page, "APPLY_WIRE_TRANSACTION", 1) + changes = structural["payload"]["changes"] + assert len(changes)==1 and changes[0] == { + "op":"SET_TAP","from":SOURCE,"edgeId":SEND,"tap":"PRE_FADER" + }, structural + assert "POST-FADER" in source.locator(".sof-badge").inner_text() + state["graph"].update(revision="3",rosterRevision="3") + state["mixerSession"].update(routeRevision="3",rosterRevision="3") + state["graph"]["edges"][1]["tap"] = "PRE_FADER" + ack(page, state, structural) + assert "POST-FADER" in source.locator(".sof-badge").inner_text(), ( + "A control ACK alone cannot announce a newly installed PRE tap") + emit(page, "arMixConsoleSnapshot", state) + page.wait_for_function("""()=>document.querySelector( + '#tracks .strip[data-id="1"] .sof-badge')?.textContent==='PRE-FADER'""") + assert source.locator('[data-action="sofTap"]').get_attribute("data-tap-visual")=="pre" + + # The physical SOF fader controls SEND GAIN only. The accepted main fader + # remains -7.5 dB and no SET_FADER intent may be generated by a send move. + fader = source.locator(".fader") + assert fader.is_enabled() + fader.evaluate("""el=>{ + el.value='-12'; + el.dispatchEvent(new Event('input',{bubbles:true})); + el.dispatchEvent(new Event('change',{bubbles:true})); + }""") + level = wait_for_intents(page,"SET_WIRE_GAIN",1) + assert level["channelId"]==SOURCE + assert level["payload"]["edgeId"]==SEND + assert abs(level["payload"]["gainLinear"]-10**(-12/20))<1e-8 + assert intent_list(page,"SET_FADER")==[] + assert state["graph"]["channels"][0]["controls"]["faderDb"]==-7.5 + ack(page,state,level) + state["graph"]["edges"][1]["gainLinear"] = level["payload"]["gainLinear"] + emit(page,"arMixConsoleSnapshot",state) + fader.blur() + emit(page,"arMixConsoleSnapshot",state) + assert state["graph"]["channels"][0]["controls"]["faderDb"]==-7.5 + assert intent_list(page,"SET_FADER")==[] + page.screenshot(path=f"arsonmix-native-sof-{width}.png") + + # The absence of an admitted EdgeId must never trigger an automatic + # patch, a ghost send, nor an unintended MAIN fader write. + state["graph"].update(revision="4",rosterRevision="4") + state["mixerSession"].update(routeRevision="4",rosterRevision="4") + state["graph"]["edges"].pop(1) + emit(page,"arMixConsoleSnapshot",state) + assert "NO SEND" in source.locator(".sof-badge").inner_text() + assert source.locator('[data-action="sofOn"]').is_disabled() + assert source.locator('[data-action="sofTap"]').is_disabled() + before=len(page.evaluate("()=>window.__nativeIntents")) + assert source.locator(".fader").is_disabled() + assert len(page.evaluate("()=>window.__nativeIntents"))==before + + toggle.click() + assert page.locator("#mixContext").inner_text()=="MAIN MIX" + assert abs(float(source.locator(".fader").input_value())-(-7.5))<.01 + assert not errors, errors + page.close() + + +def main(): + spec=importlib.util.spec_from_file_location( + "native_bundle",ROOT/"scripts/build_approved_native_gui.py") + bundle=importlib.util.module_from_spec(spec) + spec.loader.exec_module(bundle) + with tempfile.TemporaryDirectory(prefix="armix-native-sof-") as directory: + out=Path(directory) + bundle.stage(out) + with sync_playwright() as pw: + browser=pw.chromium.launch(headless=True) + try: + for width,height in ((1366,900),(1024,768)): + exercise(browser,out,width,height) + finally: + browser.close() + print("PASS native SOF actual Chromium: exact EdgeId ON/OFF, PRE tap, gain, ACK/readback, no ghost patch or MAIN fader write; two viewports") + + +if __name__=="__main__": + main() From 261b2473182a0636f429d97d9606304c0c63dada Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:01:21 +0700 Subject: [PATCH 097/140] ci(sof): reuse SonKu Chromium runner for real native SOF ACK/readback and two screenshot artifacts --- .github/workflows/ui-smoke.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index f4cb2d561..5a06c3af5 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -209,6 +209,11 @@ jobs: python -m playwright install --with-deps chromium - name: Actual native picker insert, ACK/readback, editor open, UI controls run: python tests/approved_native_sonku_smoke.py + # Same Chromium installation and same native-only GUI assembler. + # Fast scoped SOF qualification runs on the existing SonKu integration + # job (zero additional browser runners and zero Windows recompiles). + - name: Native SOF PRE/POST, SEND ON, EdgeId gain and ACK/readback Chromium + run: python tests/approved_native_sof_chromium_smoke.py - name: Render original 8D-SonKu headphone candidate through exact native HRTF run: | g++ -std=c++20 -O2 -Wall -Wextra -pedantic tools/sonku_offline_listening.cpp -o /tmp/sonku-listening @@ -230,6 +235,14 @@ jobs: path: arsonmix-sonku-editor-*.png if-no-files-found: ignore retention-days: 7 + - name: Keep native SOF accepted-state desktop and narrow screenshots + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ArSonMix-SOF-PCM-Bridge-${{ github.run_id }} + path: arsonmix-native-sof-*.png + if-no-files-found: ignore + retention-days: 7 vocal-throw-preview: name: Vocal Throw native editor desktop/mobile Chromium FAT From 8a97611731d45332f522b2e0e3ee040bc96a7f3a Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:02:40 +0700 Subject: [PATCH 098/140] test(sof): blur physical SOF slider with cross-version Playwright-safe DOM operation --- tests/approved_native_sof_chromium_smoke.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/approved_native_sof_chromium_smoke.py b/tests/approved_native_sof_chromium_smoke.py index 760732ed8..0997e897d 100644 --- a/tests/approved_native_sof_chromium_smoke.py +++ b/tests/approved_native_sof_chromium_smoke.py @@ -155,7 +155,7 @@ def exercise(browser, out, width, height): ack(page,state,level) state["graph"]["edges"][1]["gainLinear"] = level["payload"]["gainLinear"] emit(page,"arMixConsoleSnapshot",state) - fader.blur() + fader.evaluate("el=>el.blur()") emit(page,"arMixConsoleSnapshot",state) assert state["graph"]["channels"][0]["controls"]["faderDb"]==-7.5 assert intent_list(page,"SET_FADER")==[] From 6d8780c60708f27a12fa91221430dd0ffb53ffde Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:03:02 +0700 Subject: [PATCH 099/140] ci(sof): qualify scoped native-owner test PR on existing SonKu Chromium runner before integration --- .github/workflows/ui-smoke.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 5a06c3af5..75231ddc6 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -193,7 +193,9 @@ jobs: sonku-preview: name: 8D-SonKu native insert/editor Chromium FAT (desktop and narrow) needs: quick - if: ${{ (github.event_name == 'pull_request' && startsWith(github.head_ref, 'feat/8d-sonku-')) || (github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/heads/feat/8d-sonku-') && inputs.expected_sha != '') }} + # Both 8D-SonKu and SOF native-owner PRs share ONE actual Chromium runner. + # Preserve fast-only checks for unrelated GUI and engine branches. + if: ${{ (github.event_name == 'pull_request' && (startsWith(github.head_ref, 'feat/8d-sonku-') || startsWith(github.head_ref, 'test/sof-native-'))) || (github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/heads/feat/8d-sonku-') && inputs.expected_sha != '') }} runs-on: ubuntu-latest timeout-minutes: 12 steps: From e6d73ce7cff584565241d7578c94fb7f337b2091 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:05:20 +0700 Subject: [PATCH 100/140] test(sof): assert actual native intent targetChannelId transport schema, not fictional channelId --- tests/approved_native_sof_chromium_smoke.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/approved_native_sof_chromium_smoke.py b/tests/approved_native_sof_chromium_smoke.py index 0997e897d..254de70a3 100644 --- a/tests/approved_native_sof_chromium_smoke.py +++ b/tests/approved_native_sof_chromium_smoke.py @@ -92,7 +92,7 @@ def exercise(browser, out, width, height): # SEND OFF is a scalar against the EXACT existing EdgeId, not topology. on.click() off = wait_for_intents(page, "SET_SEND_ENABLED", 1) - assert off["channelId"] == SOURCE and off["payload"] == { + assert off["targetChannelId"] == SOURCE and off["payload"] == { "edgeId":SEND,"enabled":False }, off assert on.get_attribute("aria-pressed") == "true", ( @@ -147,7 +147,7 @@ def exercise(browser, out, width, height): el.dispatchEvent(new Event('change',{bubbles:true})); }""") level = wait_for_intents(page,"SET_WIRE_GAIN",1) - assert level["channelId"]==SOURCE + assert level["targetChannelId"]==SOURCE assert level["payload"]["edgeId"]==SEND assert abs(level["payload"]["gainLinear"]-10**(-12/20))<1e-8 assert intent_list(page,"SET_FADER")==[] From f74e981fd9f8092c56f9c064d064706f4080bc08 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:11:33 +0700 Subject: [PATCH 101/140] feat(sonku): offline bounded room geometry and inverse-distance binaural cues --- .../builtin_fx/sonku/SonKuEarlyReflections.h | 56 ++++++++++++++++--- 1 file changed, 49 insertions(+), 7 deletions(-) diff --git a/engine/builtin_fx/sonku/SonKuEarlyReflections.h b/engine/builtin_fx/sonku/SonKuEarlyReflections.h index 501cccfca..25c40be4f 100644 --- a/engine/builtin_fx/sonku/SonKuEarlyReflections.h +++ b/engine/builtin_fx/sonku/SonKuEarlyReflections.h @@ -13,6 +13,12 @@ // No allocation, locks, worker, I/O, FFT or second device callback. namespace armix::sonku { enum class SonKuRoomShape : std::uint8_t { Rectangular=0, Square=1 }; +// Offline-only center-listener geometry. Width/depth are full room spans; +// the source moves on a horizontal ring at distanceMeters from the listener. +// No realtime mutation or native state schema is published by this experiment. +struct SonKuRoomGeometry { + float widthMeters=7.2f,depthMeters=7.2f,distanceMeters=1.6f; +}; class SonKuEarlyReflections final { public: struct Ears {float left=0.f,right=0.f;}; @@ -54,10 +60,39 @@ class SonKuEarlyReflections final { return false; if(active())return false; shape_=shape; + custom_=false; // restores the exact legacy square/rectangle semantics + untilGeometry_=0; + primed_=false; + return true; + } + // Evaluated on an unpublished, inactive DSP instance only. Width up to + // 40m is safely contained in the existing 8192-frame delay rings at 48k. + static bool validGeometry(const SonKuRoomGeometry& g) noexcept { + if(!std::isfinite(g.widthMeters)||!std::isfinite(g.depthMeters)|| + !std::isfinite(g.distanceMeters))return false; + if(g.widthMeters<5.f||g.depthMeters<5.f|| + g.widthMeters>40.f||g.depthMeters>40.f|| + g.distanceMeters<1.6f||g.distanceMeters>10.f|| + 2.f*(g.distanceMeters+.5f)>std::min(g.widthMeters,g.depthMeters)) + return false; + const float longest=std::max(g.widthMeters,g.depthMeters)+g.distanceMeters; + const float largestPath=std::sqrt(longest*longest+ + g.distanceMeters*g.distanceMeters); + return (largestPath-g.distanceMeters)*48000.f/343.f+32.f < + static_cast(ringFrames-3); + } + bool setGeometry(const SonKuRoomGeometry& g) noexcept { + if(active()||!validGeometry(g))return false; + geometry_=g; + custom_=true; + shape_=SonKuRoomShape::Square; // consistent 0.70 walls, not rectangle untilGeometry_=0; primed_=false; return true; } + float relativeDistanceGain() const noexcept { + return custom_?1.6f/geometry_.distanceMeters:1.f; + } SonKuRoomShape shape() const noexcept {return shape_;} bool active() const noexcept {return ready_&&(amount_>0.f||amountTarget_>0.f);} float targetAmount() const noexcept {return amountTarget_;} @@ -116,11 +151,13 @@ class SonKuEarlyReflections final { } void updateGeometry(double azimuth,float spread) noexcept { constexpr float pi=3.14159265358979323846f; - constexpr float sourceDistance=1.60f; // meters - // The square profile tests rotationally symmetric wall geometry; - // it is not a simulated circular room or guaranteed psychoacoustics. - const float halfWidth=(shape_==SonKuRoomShape::Square)?3.60f:3.20f; - const float halfDepth=(shape_==SonKuRoomShape::Square)?3.60f:4.00f; + const float sourceDistance=custom_?geometry_.distanceMeters:1.60f; + // Preserve the approved 7.2m/1.6m path exactly when custom_ is false. + // A wider room changes physical image paths, not KEMAR azimuth signs. + const float halfWidth=custom_?geometry_.widthMeters*.5f: + ((shape_==SonKuRoomShape::Square)?3.60f:3.20f); + const float halfDepth=custom_?geometry_.depthMeters*.5f: + ((shape_==SonKuRoomShape::Square)?3.60f:4.00f); constexpr float speedOfSound=343.f; constexpr float earHalfTime=.00031f; // max +/-0.31ms constexpr std::array rectangular{.74f,.74f,.67f,.67f}; @@ -145,7 +182,11 @@ class SonKuEarlyReflections final { // symmetric while keeping every reflection causal. const float common=extra+earHalfTime*rate_; const float earDelta=directionX*earHalfTime*rate_; - const float level=.28f*walls[wall]*(sourceDistance/path); + // New distance studies use fixed 1.6m acoustic reference: + // pressure at a reflected path falls with 1/path. Legacy + // calculations are untouched at the accepted radius. + const float level=.28f*walls[wall]* + ((custom_?1.6f:sourceDistance)/path); auto& tap=tap_[source][wall]; tap.targetDelayL=std::clamp(common+earDelta,1.f, static_cast(ringFrames-3)); @@ -171,6 +212,7 @@ class SonKuEarlyReflections final { float amount_=0.f,amountTarget_=0.f; int write_=0,untilGeometry_=0; SonKuRoomShape shape_=SonKuRoomShape::Rectangular; - bool ready_=false,primed_=false; + SonKuRoomGeometry geometry_{}; + bool custom_=false,ready_=false,primed_=false; }; } // namespace armix::sonku From 76e086af8624a8ed15b4929fadea8f22fe7688d1 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:11:35 +0700 Subject: [PATCH 102/140] feat(sonku): offline bounded room geometry and inverse-distance binaural cues --- engine/builtin_fx/sonku/SonKuSpatialCore.h | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/engine/builtin_fx/sonku/SonKuSpatialCore.h b/engine/builtin_fx/sonku/SonKuSpatialCore.h index 557c0d1ef..6f0073ac0 100644 --- a/engine/builtin_fx/sonku/SonKuSpatialCore.h +++ b/engine/builtin_fx/sonku/SonKuSpatialCore.h @@ -89,6 +89,10 @@ class SonKuSpatialCore final { bool setEarlyReflectionsShape(SonKuRoomShape shape) noexcept { return room_.setShape(shape); } + // Offline M3 distance/large-room acoustic trial. Not a GUI/native ABI. + bool setAcousticRoomGeometry(const SonKuRoomGeometry& geometry) noexcept { + return room_.setGeometry(geometry); + } // Experimental wet-only late room, OFF unless explicitly enabled by // controlled offline A/B. The native parameter contract is unchanged. bool setMusicalReverbAmount(float amount) noexcept { @@ -105,6 +109,7 @@ class SonKuSpatialCore final { if(!ready_ || !left || !right || samples<=0)return; const double step=(settings_.moving ? (settings_.clockwise?1.:-1.)*360./(sampleRate_*settings_.revolutionSeconds) : 0.); + const float distanceGain=room_.relativeDistanceGain(); for(int i=0;i Date: Fri, 13 Nov 2026 13:11:38 +0700 Subject: [PATCH 103/140] test(sonku): protect approved square and validate room/distance PCM --- tests/sonku_early_reflections_test.cpp | 41 ++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/tests/sonku_early_reflections_test.cpp b/tests/sonku_early_reflections_test.cpp index 9d5787030..a540ca5eb 100644 --- a/tests/sonku_early_reflections_test.cpp +++ b/tests/sonku_early_reflections_test.cpp @@ -10,6 +10,7 @@ int main(){ using armix::sonku::SonKuEarlyReflections; using armix::sonku::SonKuRoomShape; + using armix::sonku::SonKuRoomGeometry; SonKuEarlyReflections invalid; assert(!invalid.prepare(96000.)); assert(!invalid.prepare(std::numeric_limits::quiet_NaN())); @@ -30,6 +31,46 @@ int main(){ } assert(soundEnergy>.004); assert(mirrorError<1.e-4); + // The published user's approved square impulse must remain byte-exact + // when the same geometry is expressed explicitly. + { + SonKuEarlyReflections approved,explicitSquare; + assert(approved.prepare(rate)&&explicitSquare.prepare(rate)); + assert(approved.setShape(SonKuRoomShape::Square)); + assert(explicitSquare.setGeometry({7.2f,7.2f,1.6f})); + assert(approved.setAmount(.55f)&&explicitSquare.setAmount(.55f)); + assert(!explicitSquare.setGeometry({14.4f,14.4f,5.f})); + for(int i=0;i<8192;++i) { + const float v=i==0?.75f:0.f; + const auto a0=approved.process(v,v,37.,45.f); + const auto b0=explicitSquare.process(v,v,37.,45.f); + assert(a0.left==b0.left&&a0.right==b0.right); + } + } + assert(!SonKuEarlyReflections::validGeometry({7.2f,7.2f,5.f})); + assert(!SonKuEarlyReflections::validGeometry({40.1f,40.f,1.6f})); + assert(!SonKuEarlyReflections::validGeometry({ + std::numeric_limits::quiet_NaN(),14.f,2.f})); + assert(SonKuEarlyReflections::validGeometry({14.4f,14.4f,5.f})); + assert(SonKuEarlyReflections::validGeometry({28.8f,28.8f,8.f})); + // Larger boundaries delay the FIRST reflected arrival. No longer + // room is faked by increasing a single reverb decay number. + { + SonKuEarlyReflections nearRoom,largeRoom; + assert(nearRoom.prepare(rate)&&largeRoom.prepare(rate)); + assert(nearRoom.setShape(SonKuRoomShape::Square)); + assert(largeRoom.setGeometry({28.8f,28.8f,1.6f})); + assert(nearRoom.setAmount(.55f)&&largeRoom.setAmount(.55f)); + int nearFirst=-1,largeFirst=-1; + for(int i=0;i<8000;++i) { + const float v=i==0?1.f:0.f; + const auto a0=nearRoom.process(v,v,0.,0.f); + const auto b0=largeRoom.process(v,v,0.,0.f); + if(nearFirst<0 && (a0.left!=0.f||a0.right!=0.f))nearFirst=i; + if(largeFirst<0 && (b0.left!=0.f||b0.right!=0.f))largeFirst=i; + } + assert(nearFirst>100 && largeFirst>nearFirst+800); + } SonKuEarlyReflections a,b; assert(a.prepare(rate)&&b.prepare(rate)); assert(!a.active()); From 336afbba2107388cd4cea2ea6be7408209d0a653 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:11:40 +0700 Subject: [PATCH 104/140] test(sonku): protect approved square and validate room/distance PCM --- tests/sonku_spatial_core_test.cpp | 39 +++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/sonku_spatial_core_test.cpp b/tests/sonku_spatial_core_test.cpp index 12689ec53..b48a83257 100644 --- a/tests/sonku_spatial_core_test.cpp +++ b/tests/sonku_spatial_core_test.cpp @@ -154,6 +154,45 @@ int main() { std::abs(tailR[i]-squareR[i]); } assert(lateDifference>.001); + // Explicit approved square parameters remain PCM-identical. Radius + // attenuation works even with early reflections disabled, so SPACE + // and DISTANCE remain independent, not one misleading "big hall" knob. + { + auto approved=std::make_unique(); + auto same=std::make_unique(); + auto distant=std::make_unique(); + assert(approved->prepare(rate)&&same->prepare(rate)&& + distant->prepare(rate)); + Settings pose=s;pose.moving=false;pose.startAzimuthDegrees=0.f; + assert(approved->setSettings(pose)&&same->setSettings(pose)&& + distant->setSettings(pose)); + assert(approved->setEarlyReflectionsShape(SonKuRoomShape::Square)); + assert(same->setAcousticRoomGeometry({7.2f,7.2f,1.6f})); + assert(distant->setAcousticRoomGeometry({28.8f,28.8f,8.f})); + assert(approved->setEarlyReflectionsAmount(.55f)); + assert(same->setEarlyReflectionsAmount(.55f)); + std::array aa{},ab{},ba{},bb{}; + aa[0]=ab[0]=ba[0]=bb[0]=.6f; + approved->process(aa.data(),ab.data(),4096); + same->process(ba.data(),bb.data(),4096); + for(int i=0;i<4096;++i) { + assert(aa[i]==ba[i]&&ab[i]==bb[i]); + } + std::array nearL{},nearR{},farL{},farR{}; + nearL[0]=nearR[0]=farL[0]=farR[0]=.6f; + // Compare separate fresh reference to distant field (ER OFF). + auto dryNear=std::make_unique(); + assert(dryNear->prepare(rate)&&dryNear->setSettings(pose)); + dryNear->process(nearL.data(),nearR.data(),1024); + distant->process(farL.data(),farR.data(),1024); + double nearEnergy=0.,farEnergy=0.; + for(int i=0;i<1024;++i) { + nearEnergy+=std::abs(nearL[i])+std::abs(nearR[i]); + farEnergy+=std::abs(farL[i])+std::abs(farR[i]); + } + assert(nearEnergy>.01); + assert(std::abs(farEnergy/nearEnergy-.2)<1.e-5); + } // A hard FRONT->REAR teleport must not replace 560 FIR coefficients // at the next 16-sample boundary. Compare the identical dry/PCM // history before and immediately after reposition. From a020baf80aba3800053e31562a1c7d876e845369 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:13:04 +0700 Subject: [PATCH 105/140] feat(sonku): deterministic larger room and distant-source listening WAVs --- tools/sonku_offline_listening.cpp | 44 ++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/tools/sonku_offline_listening.cpp b/tools/sonku_offline_listening.cpp index 548ceeb1b..08b579f96 100644 --- a/tools/sonku_offline_listening.cpp +++ b/tools/sonku_offline_listening.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -106,10 +107,12 @@ std::vector orbit(float roomAmount=0.f, armix::sonku::SonKuRoomShape shape=armix::sonku::SonKuRoomShape::Rectangular, bool clockwise=true,float lateAmount=0.f, armix::sonku::SonKuReverbPreset latePreset= - armix::sonku::SonKuReverbPreset::StudioGlue){ + armix::sonku::SonKuReverbPreset::StudioGlue, + std::optional geometry=std::nullopt){ SonKuSpatialCore dsp;Noise noise; if(!dsp.prepare(rate))throw std::runtime_error("No 48k HRTF"); if(!dsp.setEarlyReflectionsShape(shape)|| + (geometry && !dsp.setAcousticRoomGeometry(*geometry))|| !dsp.setMusicalReverbPreset(latePreset)|| !dsp.setEarlyReflectionsAmount(roomAmount)|| !dsp.setMusicalReverbAmount(lateAmount)) @@ -239,8 +242,22 @@ void notes(const std::filesystem::path& directory, <<"The plucks are ORIGINAL test tones (no copyrighted composition).\n" <<"Use them to judge vocal-like reverb coloration/tail musicality.\n" <<"Both comparisons reuse exactly the same source noise and direct HRIR.\n" - <<"Do blind-level and externalization evaluation before enabling V2 live.\n" - <<"This is NOT full HRIR-convolved reflections, FDN or personalized HRTF.\n"; + <<"V4: DISTANCE and ROOM SIZE are separate acoustic parameters.\n" + <<"sonku-v4-spacious-near-orbit-cw-2x.wav = 14.4x14.4m at 1.6m.\n" + <<"sonku-v4-spacious-far-orbit-cw-2x.wav = 14.4x14.4m at 5.0m.\n" + <<"sonku-v4-large-near-orbit-cw-2x.wav = 28.8x28.8m at 1.6m.\n" + <<"sonku-v4-large-far-orbit-cw-2x.wav = 28.8x28.8m at 8.0m.\n" + <<"All V4 tracks use the SAME 20s source and orbital motion as Square.\n" + <<"Larger room = later/weaker true 1st-order image echoes.\n" + <<"More distant source = quieter 1/r DIRECT KEMAR and weaker echoes.\n" + <<"These WAVs are NOT peak-normalized: turn down before near tracks.\n" + <<"Use matched perceived playback loudness for judgments of spatial\n" + <<"distance, and separately judge actual level reduction as a cue.\n" + <<"V4 room tests disable FDN deliberately: the existing 0.78/1.28s\n" + <<"tail is not calibrated for large halls (no pretend big-hall RT60).\n" + <<"Not simulated: air absorption, floor/ceiling, personalized HRTF,\n" + <<"direct path time-of-flight, or higher-order wall reflections.\n" + <<"Offline candidates only, NO native GUI/session/product release.\n"; std::ofstream key(directory/"BLIND-ANSWER-KEY.txt"); if(!key)throw std::runtime_error("Cannot write blind answer key"); key<<"OPEN ONLY AFTER LISTENING. Exact 2.5-second trial windows:\n"; @@ -285,6 +302,27 @@ int main(int argc,char** argv){ musicalOrbit(.42f,armix::sonku::SonKuReverbPreset::StudioGlue)); writeWav(dir/"sonku-musical-square-airy-2x.wav", musicalOrbit(.42f,armix::sonku::SonKuReverbPreset::AiryChamber)); + // V4 independent distance/room dimensions, not synthetic reverb EQ. + // Original approved Square WAV and all V1-V3 audio are unchanged. + using armix::sonku::SonKuRoomShape; + using armix::sonku::SonKuRoomGeometry; + using armix::sonku::SonKuReverbPreset; + writeWav(dir/"sonku-v4-spacious-near-orbit-cw-2x.wav", + orbit(.55f,SonKuRoomShape::Square,true,0.f, + SonKuReverbPreset::StudioGlue, + SonKuRoomGeometry{14.4f,14.4f,1.6f})); + writeWav(dir/"sonku-v4-spacious-far-orbit-cw-2x.wav", + orbit(.55f,SonKuRoomShape::Square,true,0.f, + SonKuReverbPreset::StudioGlue, + SonKuRoomGeometry{14.4f,14.4f,5.f})); + writeWav(dir/"sonku-v4-large-near-orbit-cw-2x.wav", + orbit(.55f,SonKuRoomShape::Square,true,0.f, + SonKuReverbPreset::StudioGlue, + SonKuRoomGeometry{28.8f,28.8f,1.6f})); + writeWav(dir/"sonku-v4-large-far-orbit-cw-2x.wav", + orbit(.55f,SonKuRoomShape::Square,true,0.f, + SonKuReverbPreset::StudioGlue, + SonKuRoomGeometry{28.8f,28.8f,8.f})); notes(dir,blind); std::cout<<"SonKu listening package PASS: measured native HRTF, " <<"4 labeled + 8 blind directions + two uninterrupted 360 turns\n"; From f8b7320bd3fc8e0f4f1e9df7cf81b5f9cad40bd4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:13:06 +0700 Subject: [PATCH 106/140] test(sonku): verify distance and room dimensions in WAV contracts --- tests/sonku_offline_demo_contract.py | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/tests/sonku_offline_demo_contract.py b/tests/sonku_offline_demo_contract.py index dde0b43f6..7a9bb4842 100644 --- a/tests/sonku_offline_demo_contract.py +++ b/tests/sonku_offline_demo_contract.py @@ -6,7 +6,7 @@ import wave root = Path(sys.argv[1] if len(sys.argv)>1 else "sonku-listening") -def read(name, frames): +def read(name, frames, minimum_peak=250, minimum_energy=100000): path=root/name assert path.exists() and path.stat().st_size>10000,path with wave.open(str(path),"rb") as w: @@ -18,8 +18,8 @@ def read(name, frames): if sys.byteorder!="little":pcm.byteswap() assert len(pcm)==2*frames peak=max(map(abs,pcm)) - assert 250100000,(name,"unexpected silence") + assert minimum_peakminimum_energy,(name,"unexpected silence") return pcm single=read("sonku-reference-four.wav",4*120000) blind=read("sonku-blind-eight.wav",8*120000) @@ -35,6 +35,22 @@ def read(name, frames): musicBase=read("sonku-musical-square-base-2x.wav",960000) musicGlue=read("sonku-musical-square-glue-2x.wav",960000) musicAiry=read("sonku-musical-square-airy-2x.wav",960000) +spaciousNear=read("sonku-v4-spacious-near-orbit-cw-2x.wav",960000) +spaciousFar=read("sonku-v4-spacious-far-orbit-cw-2x.wav",960000,60,10000) +largeNear=read("sonku-v4-large-near-orbit-cw-2x.wav",960000) +largeFar=read("sonku-v4-large-far-orbit-cw-2x.wav",960000,40,8000) +# Same source and identical 20s orbital clock: room width only changes +# path delay/level; source distance only changes geometric pressure. +def pcm_delta(a,b): + return sum(abs(int(x)-int(y)) for x,y in zip(a[300000:440000],b[300000:440000])) +assert pcm_delta(spaciousNear,squareOrbit)>1500,"Spacious room is identical to approved square" +assert pcm_delta(largeNear,spaciousNear)>1500,"Large and spacious room are identical" +assert pcm_delta(spaciousFar,spaciousNear)>1500,"5m source ignored" +assert pcm_delta(largeFar,largeNear)>1500,"8m source ignored" +def energy(a): + return sum(abs(int(x)) for x in a[300000:440000]) +assert .081000 # Verify there is no mute, edit or source reset at the 10s handoff. # Stereo interleaved: 48000 samples = 1 second, 2 PCM ints per frame. -for audio in (orbit,v2orbit,squareOrbit,reverse,reverseRoom,reverseSquare,glue,airy): +for audio in (orbit,v2orbit,squareOrbit,reverse,reverseRoom,reverseSquare, + glue,airy,spaciousNear,spaciousFar,largeNear,largeFar): for second in (9,10,11,19): begin=(second*48000+4000)*2 - assert sum(abs(x) for x in audio[begin:begin+9600])>2000,( + assert sum(abs(x) for x in audio[begin:begin+9600])>400,( "silent loop seam",second) assert "20s" in (root/"LISTENING-GUIDE.txt").read_text() assert not (root/"sonku-orbit-cw.wav").exists(),( From 64c8357f67c98f1aff1896a80182a6b3261c3ec8 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:13:09 +0700 Subject: [PATCH 107/140] feat(sonku): deterministic larger room and distant-source listening WAVs --- tools/sonku_rt_benchmark.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tools/sonku_rt_benchmark.cpp b/tools/sonku_rt_benchmark.cpp index 3336e5749..b3e359e49 100644 --- a/tools/sonku_rt_benchmark.cpp +++ b/tools/sonku_rt_benchmark.cpp @@ -13,13 +13,16 @@ namespace { struct Result {double milliseconds=0.,checksum=0.,audios=0.;}; template -Result measure(double rate,float amount,float late=0.f){ +Result measure(double rate,float amount,float late=0.f, + const armix::sonku::SonKuRoomGeometry* geometry=nullptr){ using namespace armix::sonku; SonKuSpatialCore dsp; if(!dsp.prepare(rate))throw std::runtime_error("unsupported sample rate"); Settings s{};s.moving=true;s.revolutionSeconds=10.f; s.spatialMix=1.f;s.stereoSpreadDegrees=60.f; - if(!dsp.setSettings(s)||!dsp.setEarlyReflectionsAmount(amount)|| + if(!dsp.setSettings(s)|| + (geometry && !dsp.setAcousticRoomGeometry(*geometry))|| + !dsp.setEarlyReflectionsAmount(amount)|| !dsp.setMusicalReverbAmount(late)) throw std::runtime_error("invalid DSP setup"); std::array inputL{},inputR{}; @@ -52,11 +55,14 @@ void report(double rate){ const auto baseline=measure(rate,0.f); const auto room=measure(rate,.55f); const auto musical=measure(rate,.55f,.42f); + const armix::sonku::SonKuRoomGeometry large{28.8f,28.8f,8.f}; + const auto space=measure(rate,.55f,0.f,&large); std::cout<0.5 m wall clearance and worst image + path within the existing 8192-frame circular delay ring at 48 kHz. +- First-order image-source paths still use 2 emitters × 4 walls, 64-frame + geometry cadence, fractional-delay taps, smoothed delays and gains. No ray + tracing, FFT, new thread, host callback, heap or IO in `process()`. +- `SonKuSpatialCore` applies reference-distance gain ONLY to direct measured + HRTF when an experimental non-reference geometry is configured; reflections + use absolute reflected path pressure and the existing FDN stage is unchanged. +- This is NOT a full physical BRIR: no floor/ceiling, higher-order reflections, + occlusion, calibrated high-frequency air absorption, direct time-of-flight, + personalized pinna model, dynamic head tracking or release-qualified tail. +- No GUI/bridge/lease/session edits; ALL production instances remain legacy + geometry with direct gain=1 and the approved PCM arithmetic unchanged. + +## Matched-source audition matrix (two 10-second 360° revolutions) +The existing `sonku-v2-square-orbit-cw-2x.wav` remains the reference. + +| WAV stem | Width × depth | Emission radius | Late reverb | Intended comparison | +| --- | --- | --- | --- | --- | +| v2-square | 7.2 × 7.2 m | 1.6 m | OFF | Owner-approved | +| v4-spacious-near | 14.4 × 14.4 m | 1.6 m | OFF | Room dimension only | +| v4-spacious-far | 14.4 × 14.4 m | 5.0 m | OFF | Distance only vs spacious-near | +| v4-large-near | 28.8 × 28.8 m | 1.6 m | OFF | Larger room without moving source | +| v4-large-far | 28.8 × 28.8 m | 8.0 m | OFF | Distance only vs large-near | + +All render the same deterministic noise, source stereo, azimuth path, +KEMAR HRIR, wet setting and trim. Files are NOT normalized: distant samples +are truly quieter. For localization evaluation match perceived monitoring +loudness safely and separately evaluate the physical level change. +Headphones only; disable OS spatial enhancement. + +## Gates +1. Legacy default Square vs explicit identical geometry: byte-exact early + reflection and full native-core PCM under both 44.1/48k. +2. Larger room first-echo onset must move later, beyond the reference. +3. Distant direct field must approximate 1.6/r with ER OFF; reject invalid, + nonfinite, too-small, out-of-wall geometry and active edits. +4. Complete WAV formats, continuous 2-turn seam, non-silent tails, + direction signs, parity, amplitude safety and same-runner CPU telemetry. +5. Listener A/B judgment and Windows ASIO hardware tests are separate, + necessary release gates. No native GUI control or installer promotion yet. + +## Research +- Allen and Berkley, JASA 65(4), 943–950 (1979), DOI 10.1121/1.382599: + first-order image-source paths for rectangular rooms. +- Valve Steam Audio core guide, direct distance attenuation and reflection + model as separate signal-processing stages: + https://github.com/ValveSoftware/steam-audio/blob/master/core/doc/guide.rst + +No external code or proprietary impulse responses copied. From 34e1112fbc349003ae33f0fc72836e4a08c1f60d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:16:19 +0700 Subject: [PATCH 109/140] ci(integration): share one Chromium runner for V65 WIRE + native SOF/SonKu cross-branch visual FAT --- .github/workflows/ui-smoke.yml | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 75231ddc6..d833184cb 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -195,7 +195,7 @@ jobs: needs: quick # Both 8D-SonKu and SOF native-owner PRs share ONE actual Chromium runner. # Preserve fast-only checks for unrelated GUI and engine branches. - if: ${{ (github.event_name == 'pull_request' && (startsWith(github.head_ref, 'feat/8d-sonku-') || startsWith(github.head_ref, 'test/sof-native-'))) || (github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/heads/feat/8d-sonku-') && inputs.expected_sha != '') }} + if: ${{ (github.event_name == 'pull_request' && (startsWith(github.head_ref, 'feat/8d-sonku-') || startsWith(github.head_ref, 'test/sof-native-') || startsWith(github.head_ref, 'integration/sof-sonku-main-'))) || (github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/heads/feat/8d-sonku-') && inputs.expected_sha != '') }} runs-on: ubuntu-latest timeout-minutes: 12 steps: @@ -216,6 +216,12 @@ jobs: # job (zero additional browser runners and zero Windows recompiles). - name: Native SOF PRE/POST, SEND ON, EdgeId gain and ACK/readback Chromium run: python tests/approved_native_sof_chromium_smoke.py + - name: Integrated V65 WIRE motion, SOF and actual native WIRE regression + if: ${{ github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/sof-sonku-main-') }} + run: | + python tests/pages_v60_fader_wire_tactile_smoke.py + python tests/approved_native_wire_gain_smoke.py + python tests/sof_contextual_console_smoke.py - name: Render original 8D-SonKu headphone candidate through exact native HRTF run: | g++ -std=c++20 -O2 -Wall -Wextra -pedantic tools/sonku_offline_listening.cpp -o /tmp/sonku-listening @@ -242,7 +248,10 @@ jobs: uses: actions/upload-artifact@v4 with: name: ArSonMix-SOF-PCM-Bridge-${{ github.run_id }} - path: arsonmix-native-sof-*.png + path: | + arsonmix-native-sof-*.png + arsonmix-v60-*.png + native-wire-gain-*.png if-no-files-found: ignore retention-days: 7 From a424dbc5039d940a5569fd297621165c1fbddaec Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:18:46 +0700 Subject: [PATCH 110/140] test(wire): correct bottom-detent -infinity PCM golden to linear zero without disconnect --- tests/approved_native_wire_gain_smoke.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_wire_gain_smoke.py b/tests/approved_native_wire_gain_smoke.py index 3bd2071bb..40fb13200 100644 --- a/tests/approved_native_wire_gain_smoke.py +++ b/tests/approved_native_wire_gain_smoke.py @@ -287,7 +287,12 @@ def main(): page.wait_for_function("()=>window.__nativeIntents.length===2") assert page.evaluate("()=>window.__heldWireInput===document.querySelector('#tracks .strip[data-id=\"2\"] .wire-gain')"), "ACK detached held gain control" latest = page.evaluate("()=>window.__nativeIntents.at(-1)") - assert abs(latest["payload"]["gainLinear"] - .001) < 1e-8 + # Native SOF/WIRE policy defines the bottom -60 dB + # detent as -infinity/silence (linear zero), not 0.001. + # The exact SEND EdgeId is retained; this is a scalar + # mute-level gain, NEVER a graph REMOVE/disconnect. + assert latest["payload"]["gainLinear"] == 0, latest + assert latest["payload"]["edgeId"] == SEND, latest state["graph"]["edges"][1]["gainLinear"] = latest["payload"]["gainLinear"] ack(page, state, latest) emit(page, "arMixConsoleSnapshot", state) From eb2dd57265fc8ad3edf94779d89b56557b908f58 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:21:46 +0700 Subject: [PATCH 111/140] test(sof): unity digital gain readout follows approved 0.0 dB formatting --- tests/sof_contextual_console_smoke.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/sof_contextual_console_smoke.py b/tests/sof_contextual_console_smoke.py index 39eadb05e..7195620d6 100644 --- a/tests/sof_contextual_console_smoke.py +++ b/tests/sof_contextual_console_smoke.py @@ -68,7 +68,9 @@ def run() -> None: assert "6.5" in knob.get_attribute("value") or knob.input_value() == "6.5" # Double-click must use the same gain parameter path and restore unity. first.locator(".gain-dial").dblclick() - assert "+0.0 dB" in first.locator(".gain-readout").inner_text() + # The public formatter reserves '+' for strictly + # positive values; gain unity is displayed as 0.0 dB. + assert first.locator(".gain-readout").inner_text().strip() == "0.0 dB" assert knob.input_value() == "0" knob.evaluate("""el => { el.value = '6.5'; From 7403f8a0703c4d6ae4283b33ee669ea6d25e6119 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 13:27:12 +0700 Subject: [PATCH 112/140] test(sof): navigate real More menu before filtering BUS and restoring All in Chromium --- tests/sof_contextual_console_smoke.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/tests/sof_contextual_console_smoke.py b/tests/sof_contextual_console_smoke.py index 7195620d6..0b248ec65 100644 --- a/tests/sof_contextual_console_smoke.py +++ b/tests/sof_contextual_console_smoke.py @@ -119,7 +119,20 @@ def run() -> None: # Rename the selected BUS in the native-style identity card. # SOF selection must follow its ID, not jump back to Bus A. - page.locator("#viewFilter").select_option("bus") + # VIEW & SELECTION was deliberately moved under the + # compact More menu. Exercise its visible operator path; + # do not force a hidden 60°', '', '', - '
Drag the two monitors on the orbit · knobs: vertical drag, double-click to reset
', + '
', + '
SPACEDIRECT ONLY
', + '
', + '', + '', + '', + '
', + '', + '', + '
Reflections + musical room tail · OFF keeps original HRTF
', + '
Drag monitors to position · rotary knobs: vertical drag, double-click to reset
', '
', '
VISUAL PREVIEWNo browser audio
' ].join(""); @@ -142,6 +162,21 @@ function render(){ dial.style.setProperty("--sk-sweep",(p*270).toFixed(2)+"deg"); dial.style.setProperty("--sk-needle",(-135+p*270).toFixed(2)+"deg"); } + // ROOM is one typed native scene, never a browser audio simulator. + root.querySelectorAll("[data-sk-room]").forEach(el=>{ + el.setAttribute("aria-pressed", + String(Number(el.dataset.skRoom)===s.spacePreset)); + }); + const sizeLabels=["DIRECT ONLY","7.2 × 7.2 m","14.4 × 14.4 m","28.8 × 28.8 m"]; + $("skSpaceText").textContent=sizeLabels[s.spacePreset]; + const distance=$("skDistance"),max=roomMaxDistance[s.spacePreset]; + distance.max=String(max); + distance.disabled=s.spacePreset===0; + distance.value=String(Math.min(max,s.sourceDistanceMeters)); + $("skDistanceValue").textContent=s.sourceDistanceMeters.toFixed(1)+" m"; + $("skAmbience").value=String(Math.round(s.ambience*100)); + $("skAmbience").disabled=s.spacePreset===0; + $("skAmbienceValue").textContent=Math.round(s.ambience*100)+"%"; const liveMotion=s.moving&¤t&&!pending?observed: s.startAzimuthDegrees; const phase=native()&&s.moving&¤t&&!pending&&observedAt? @@ -208,16 +243,17 @@ backend()?.addEventListener?.("arMixBuiltinSonKuSnapshot",r=>{ if(r?.requestId!==readId||!current)return; const c=context();if(!c||r.status!=="ACCEPTED"|| r.channelId!==c.channelId||r.instanceId!==c.instanceId)return; - if(!valid(r.settings))return; + const incoming=normalizeSettings(r.settings); + if(!valid(incoming))return; readId="";readSentAt=0; if(pending) { if(!pending.ack || r.appliedRequestId!==pending.requestId){ if(pending.ack)requestSnapshot(); return; } - accepted={...r.settings};pending=null;hint("DSP APPLIED · ACCEPTED");flushLatest(); + accepted={...incoming};pending=null;hint("DSP APPLIED · ACCEPTED");flushLatest(); }else if(!drag&&!dialDrag){ - accepted={...r.settings};draft={...r.settings}; + accepted={...incoming};draft={...incoming}; } if(Number.isFinite(r.observedAzimuthDegrees)){ observed=r.observedAzimuthDegrees;observedAt=performance.now(); @@ -229,6 +265,27 @@ $("skClose").addEventListener("click",()=>{root.hidden=true;current=null; if(clock!==null){clearInterval(clock);clock=null;}}); $("skMotion").addEventListener("click",()=>send({...draft,moving:!draft.moving})); $("skDirection").addEventListener("click",()=>send({...draft,clockwise:!draft.clockwise})); +root.querySelectorAll("[data-sk-room]").forEach(btn=>btn.addEventListener("click",()=>{ + const preset=Number(btn.dataset.skRoom),max=roomMaxDistance[preset]; + send({...draft,spacePreset:preset, + sourceDistanceMeters:preset===0?draft.sourceDistanceMeters: + Math.min(draft.sourceDistanceMeters,max)}); +})); +for(const [id,key,convert] of [ + ["skDistance","sourceDistanceMeters",v=>v], + ["skAmbience","ambience",v=>v/100]]) { + const slider=$(id); + slider.addEventListener("input",()=>{ + if(slider.disabled)return; + const value=Number(slider.value); + if(!Number.isFinite(value))return; + draft={...draft,[key]:convert(value)};render(); + }); + slider.addEventListener("change",()=>{ + if(slider.disabled)return; + send({...draft,[key]:convert(Number(slider.value))}); + }); +} for(const [id,key,convert] of [ ["skSpeed","revolutionSeconds",v=>v], ["skSpread","stereoSpreadDegrees",v=>v], From be2e4fba1e61af78118f6eecb584945f16840b35 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:03:59 +0700 Subject: [PATCH 120/140] style(sonku): compact responsive SPACE instrument controls in existing FX owner --- site/preview-v2/assets/mixer-fx-rack.css | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/site/preview-v2/assets/mixer-fx-rack.css b/site/preview-v2/assets/mixer-fx-rack.css index 999f30358..58dff3d82 100644 --- a/site/preview-v2/assets/mixer-fx-rack.css +++ b/site/preview-v2/assets/mixer-fx-rack.css @@ -1346,3 +1346,31 @@ .mx-sonku .sk-rotary{padding:3px 0!important} .mx-sonku .sk-guide{font-size:9px} } + +/* SonKu M4 native SPACE controls — same existing FX-rack CSS owner. + Small instrument-row treatment, not another card or a 19th CSS bundle. */ +.mx-sonku .sk-space-panel{display:grid;gap:7px;padding:9px 8px 8px; + border-top:1px solid #446171;border-bottom:1px solid #203a4a; + background:rgba(5,20,30,.27);border-radius:6px} +.mx-sonku .sk-space-head{display:flex;align-items:center;justify-content:space-between; + font-size:9px;letter-spacing:.85px;color:#afcfdd;font-weight:550} +.mx-sonku .sk-space-head output{color:#8ed3e0;font-size:9px;letter-spacing:.2px; + font-variant-numeric:tabular-nums} +.mx-sonku .sk-space-options{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:4px} +.mx-sonku .sk-space-options button{min-width:0;min-height:26px;padding:4px 2px; + border:1px solid #45616c;border-radius:4px;background:#1d3543; + font-size:8px;letter-spacing:.2px;font-weight:500;color:#bad2dc} +.mx-sonku .sk-space-options button[aria-pressed="true"]{color:#e8fbff; + border-color:#6fc6d7;background:#24556a;box-shadow:inset 0 1px #ffffff19} +.mx-sonku .sk-space-options button:focus-visible{outline:2px solid #9bdae8;outline-offset:1px} +.mx-sonku .sk-controls .sk-space-slider{display:grid!important; + grid-template-columns:1fr auto;gap:3px!important;align-items:center; + font-size:9px;letter-spacing:.4px;color:#a6c5d1;margin:0} +.mx-sonku .sk-controls .sk-space-slider output{font-size:9px; + color:#daf2f7;font-variant-numeric:tabular-nums} +.mx-sonku .sk-controls .sk-space-slider input{grid-column:1/-1; + width:100%;height:13px;margin:0!important;accent-color:#67c4d7} +.mx-sonku .sk-space-slider input:disabled{opacity:.32;cursor:not-allowed} +.mx-sonku .sk-space-hint{font-size:8px;line-height:1.35;color:#87aebb} +@media(max-width:550px){.mx-sonku .sk-space-panel{gap:6px;padding:8px} + .mx-sonku .sk-space-options button{min-height:29px;font-size:9px}} From 98f6ec1b5d48e257d600b4b7a10f8efeccb0bf7e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:05:07 +0700 Subject: [PATCH 121/140] test(sonku): native scene PCM partition parity and live transition regression --- tests/sonku_spatial_core_test.cpp | 56 +++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/tests/sonku_spatial_core_test.cpp b/tests/sonku_spatial_core_test.cpp index b48a83257..cb72627e9 100644 --- a/tests/sonku_spatial_core_test.cpp +++ b/tests/sonku_spatial_core_test.cpp @@ -193,6 +193,62 @@ int main() { assert(nearEnergy>.01); assert(std::abs(farEnergy/nearEnergy-.2)<1.e-5); } + // M4: real native scene settings must affect the exact PCM core, not + // just a visual mock. Old 1.6m/Square HRTF remains the same baseline. + { + auto reference=std::make_unique(); + auto scene=std::make_unique(); + auto partition=std::make_unique(); + assert(reference->prepare(rate)&&scene->prepare(rate)&& + partition->prepare(rate)); + Settings live=s;live.moving=false;live.startAzimuthDegrees=0.f; + live.spacePreset=2;live.sourceDistanceMeters=5.f; + live.roomAmount=.55f;live.ambience=.32f; + assert(valid(live)); + Settings bad=live;bad.spacePreset=1; + assert(!valid(bad)); // 5m cannot fit inside 7.2m square + bad=live;bad.ambience=std::numeric_limits::quiet_NaN(); + assert(!valid(bad)); + bad=live;bad.spacePreset=4;assert(!valid(bad)); + assert(reference->setSettings(s)); + assert(scene->setSettings(live)&&partition->setSettings(live)); + constexpr int n=4096; + std::array refL{},refR{},a{},b{},chunkL{},chunkR{}; + for(int i=0;i(i)*.07f); + refL[i]=refR[i]=a[i]=b[i]=chunkL[i]=chunkR[i]=sample; + } + reference->process(refL.data(),refR.data(),n); + scene->process(a.data(),b.data(),n); + for(int i=0;iprocess(chunkL.data()+i,chunkR.data()+i,128); + double delta=0.; + for(int i=0;i.1); // actual accepted-space DSP, not GUI-only + // Changing room size in-flight is permitted: all geometry and + // FDN coefficients are already bounded, no memory allocation. + live.spacePreset=3;live.sourceDistanceMeters=8.f; + assert(valid(live)&&scene->setSettings(live)); + std::array transitionL{},transitionR{}; + transitionL.fill(.13f);transitionR.fill(.13f); + scene->process(transitionL.data(),transitionR.data(),128); + for(int i=0;i<128;++i) + assert(std::isfinite(transitionL[i])&& + std::isfinite(transitionR[i])&& + std::abs(transitionL[i])<1.f&& + std::abs(transitionR[i])<1.f); + // Turning SPACE off removes all room+FDN work after smoothing. + live.spacePreset=0;assert(scene->setSettings(live)); + for(int i=0;i<90;++i){ + transitionL.fill(0.f);transitionR.fill(0.f); + scene->process(transitionL.data(),transitionR.data(),128); + } + } // A hard FRONT->REAR teleport must not replace 560 FIR coefficients // at the next 16-sample boundary. Compare the identical dry/PCM // history before and immediately after reposition. From 3199b39d752eeafb7ab4db617604269a73b14315 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:05:26 +0700 Subject: [PATCH 122/140] test(sonku): prepared FDN live preset switching and stale-tail suppression --- tests/sonku_musical_reverb_test.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/sonku_musical_reverb_test.cpp b/tests/sonku_musical_reverb_test.cpp index 3a099734a..d958ec743 100644 --- a/tests/sonku_musical_reverb_test.cpp +++ b/tests/sonku_musical_reverb_test.cpp @@ -57,6 +57,30 @@ int main(){ airy+=std::abs(output.left)+std::abs(output.right); } assert(airy>.005); + // Native M4 can change room decay in the callback with prepared + // coefficients and no tail-ring clear, even while active. + SonKuMusicalReverb live; + assert(live.prepare(rate)); + assert(live.setRealtimeProgram(SonKuReverbPreset::StudioGlue,.38f)); + assert(!live.setRealtimeProgram(SonKuReverbPreset::LargeRoom,1.1f)); + for(int i=0;i(rate);++i) { + const auto out=live.process(i==0?.4f:0.f,i==0?.4f:0.f); + assert(std::isfinite(out.left)&&std::isfinite(out.right)); + } + assert(live.setRealtimeProgram(SonKuReverbPreset::LargeRoom,.38f)); + for(int i=0;i<8192;++i) { + const auto out=live.process(0.f,0.f); + assert(std::isfinite(out.left)&&std::isfinite(out.right)); + } + assert(live.setRealtimeProgram(SonKuReverbPreset::LargeRoom,0.f)); + for(int i=0;i<11000;++i)live.process(0.f,0.f); + assert(!live.active()); + // Reactivation may not expose delay contents from the last run. + assert(live.setRealtimeProgram(SonKuReverbPreset::AiryChamber,.38f)); + for(int i=0;i<1800;++i){ + const auto out=live.process(0.f,0.f); + assert(out.left==0.f&&out.right==0.f); + } } return 0; } From 2f8a17013a218e1d230498bdf416adcae0482d58 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:06:18 +0700 Subject: [PATCH 123/140] test(sonku): real Chromium SPACE size/distance ACK/readback and fail-closed OFF --- tests/approved_native_sonku_smoke.py | 58 +++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_sonku_smoke.py b/tests/approved_native_sonku_smoke.py index c70c0592e..3e9c19519 100644 --- a/tests/approved_native_sonku_smoke.py +++ b/tests/approved_native_sonku_smoke.py @@ -21,6 +21,10 @@ "outputTrim":0.75, "moving":True, "clockwise":True, + "spacePreset":0, + "sourceDistanceMeters":1.6, + "roomAmount":0.55, + "ambience":0.30, } def last_action(page,name): @@ -32,7 +36,7 @@ def last_action(page,name): def accepted_snapshot(page,state,settings,applied=None): read=last_action(page,"nativeSonKuSnapshot") payload={ - "requestId":read["requestId"],"status":"ACCEPTED","schemaVersion":1, + "requestId":read["requestId"],"status":"ACCEPTED","schemaVersion":2, "channelId":SOURCE,"slot":0,"instanceId":INSTANCE, "deviceEpoch":state["device"]["epoch"], "graphRevision":state["graph"]["revision"], @@ -229,6 +233,58 @@ def screen(x,y): "stereoSpreadDegrees":0.0,"startAzimuthDegrees":0.0, "revolutionSeconds":dialAction["settings"]["revolutionSeconds"]}, applied=dialAction["requestId"]) + # M4: native SPACE must be an actual typed ACK/readback edit. + # No browser-only audio, no visual success before PCM applied. + assert editor.locator(".sk-space-options button").count()==4 + assert editor.locator("#skDistance").is_disabled() + assert editor.locator("#skAmbience").is_disabled() + editor.locator('[data-sk-room="2"]').click() + scene=last_action(page,"nativeSonKuSet") + assert scene["settings"]["spacePreset"]==2,scene + assert scene["settings"]["sourceDistanceMeters"]==1.6,scene + assert scene["settings"]["roomAmount"]==0.55,scene + assert scene["settings"]["ambience"]==0.30,scene + assert "ACCEPTED" not in editor.locator("#skHint").inner_text() + emit(page,"arMixBuiltinSonKuAck",{ + "requestId":scene["requestId"],"status":"APPLIED"}) + sceneState={**SETTINGS,"moving":False,"startAzimuthDegrees":0.0, + "stereoSpreadDegrees":0.0, + "revolutionSeconds":dialAction["settings"]["revolutionSeconds"], + "spacePreset":2} + accepted_snapshot(page,state,sceneState,applied=scene["requestId"]) + assert editor.locator('[data-sk-room="2"]').get_attribute("aria-pressed")=="true" + assert editor.locator("#skDistance").is_enabled() + assert editor.locator("#skAmbience").is_enabled() + # Programmatic range edit emits real DOM input+change events, just as + # an operator gesture does; assertions inspect outgoing native packets. + editor.locator("#skDistance").evaluate("""n=>{ + n.value='5.0';n.dispatchEvent(new Event('input',{bubbles:true})); + n.dispatchEvent(new Event('change',{bubbles:true}));}""") + distance=last_action(page,"nativeSonKuSet") + assert distance["settings"]["spacePreset"]==2,distance + assert abs(distance["settings"]["sourceDistanceMeters"]-5.0)<.01,distance + emit(page,"arMixBuiltinSonKuAck",{ + "requestId":distance["requestId"],"status":"APPLIED"}) + sceneState={**sceneState,"sourceDistanceMeters":5.0} + accepted_snapshot(page,state,sceneState,applied=distance["requestId"]) + editor.locator('[data-sk-room="1"]').click() + clamped=last_action(page,"nativeSonKuSet") + assert clamped["settings"]["spacePreset"]==1,clamped + assert clamped["settings"]["sourceDistanceMeters"]<=3.1,clamped + emit(page,"arMixBuiltinSonKuAck",{ + "requestId":clamped["requestId"],"status":"APPLIED"}) + sceneState={**sceneState,"spacePreset":1, + "sourceDistanceMeters":clamped["settings"]["sourceDistanceMeters"]} + accepted_snapshot(page,state,sceneState,applied=clamped["requestId"]) + editor.locator('[data-sk-room="0"]').click() + off=last_action(page,"nativeSonKuSet") + assert off["settings"]["spacePreset"]==0,off + emit(page,"arMixBuiltinSonKuAck",{ + "requestId":off["requestId"],"status":"APPLIED"}) + accepted_snapshot(page,state,{**sceneState,"spacePreset":0}, + applied=off["requestId"]) + assert editor.locator("#skDistance").is_disabled() + assert editor.locator("#skAmbience").is_disabled() bounds=editor.bounding_box() assert bounds and bounds["width"]>260 and bounds["width"] Date: Fri, 13 Nov 2026 14:06:37 +0700 Subject: [PATCH 124/140] fix(wire): native-only inspector rollback to accepted EdgeId readback after rejected gain/timeout --- scripts/build_approved_native_gui.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 3dbc667a7..fc3f502dd 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -239,6 +239,21 @@ def accepted_pages_html() -> str: " }\n" " }\n" " },\n" + " rollbackNativeWireInspector(rows){\n" + " const gain=document.getElementById('wireWsGain');\n" + " const text=document.getElementById('wireWsGainText');\n" + " // Rejection/expiry has no new PCM snapshot. Restore the last admitted\n" + " // readback in-place rather than leaving a forever-PENDING inspector.\n" + " if(!gain||!text?.textContent?.startsWith('PENDING · '))return false;\n" + " const id=Number(gain.dataset.wsGain);\n" + " const edge=wireEdges.find(e=>e.id===id&&e.kind!=='primary'&&e.enabled);\n" + " const row=Array.isArray(rows)?rows.find(r=>r.id===id&&Number.isFinite(r.levelDb)):null;\n" + " if(!edge||!row){gain.disabled=true;text.textContent='SEND UNAVAILABLE';return true;}\n" + " edge.levelDb=row.levelDb;\n" + " gain.value=String(row.levelDb); // same focused input, no DOM replacement\n" + " text.textContent='UNCHANGED · '+row.levelDb+' dB';\n" + " return true;\n" + " },\n" " syncVerifiedM4Wires(rows,ids){\n" " if(!Array.isArray(rows)||rows.length!==10||!Array.isArray(ids)||ids.length!==10)\n" " return false;\n" From 8925f9be07705b4ab4ab2603d3888bb336df8cef Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:07:02 +0700 Subject: [PATCH 125/140] fix(bridge): rollback pending inspector LCD on native rejection using last accepted EdgeId snapshot --- web/approved-native-bridge.js | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 3aa78e0d6..6108b3226 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -643,6 +643,14 @@ } return true; } + // One authoritative EdgeId gain projection for normal readback AND failure + // rollback. No duplicate DSP math or synthetic accepted control state. + function nativeWireGainReadback(next){ + return (next?.graph?.edges||[]).filter(e=>e.enabled&&e.primaryOutput===false) + .map(e=>({id:uiByWireId.get(e.edgeId),pending:pendingWireGains.has(e.edgeId), + levelDb:Math.round(Math.max(-60,Math.min(6, + e.gainLinear>0?20*Math.log10(e.gainLinear):-60))*10)/10})); + } function projectNativeGraphWithoutFocusLoss(next) { // Only identity, order, processing width, source and edges are structural. // Rack/slot bypass is applied in-place from independent readback below. @@ -658,9 +666,7 @@ lastNativeTopologySignature=structure; return true; } - scope?.syncNativeWireGains?.(next.graph.edges.filter(e=>e.enabled&&e.primaryOutput===false) - .map(e=>({id:uiByWireId.get(e.edgeId),pending:pendingWireGains.has(e.edgeId),levelDb:Math.round(Math.max(-60,Math.min(6, - e.gainLinear>0?20*Math.log10(e.gainLinear):-60))*10)/10}))); + scope?.syncNativeWireGains?.(nativeWireGainReadback(next)); // A SEND OFF is a scalar, NOT a disconnected WIRE. Update just the // affected selected SOF strip; preserve fader focus and all plugin state. for(const edge of next.graph.edges.filter(e=>e.enabled&&e.primaryOutput===false)){ @@ -2954,6 +2960,11 @@ state.current?.device?.epoch===wire.epoch&&deferStartupWire(wire.ops,1))return; startupWire=null; pendingWireGains.clear(); + // The controller deliberately freezes current on a rejected ACK. + // Repaint only an inspector that still says PENDING from that + // admitted PCM readback, without a new intent, timer or graph edit. + if(state.current) + scope?.rollbackNativeWireInspector?.(nativeWireGainReadback(state.current)); if(pendingFxInsert?.authority==="CHANNEL_ID"){ pendingFxInsert=null; nativeToast("VST3 insert rejected · "+state.lastError); @@ -2966,7 +2977,7 @@ // Never destroy an active pointer capture. Once the user releases, // restore only the last independently accepted native controls. if(flags.acceptedGraphConnected && (scope.activeFaderId??-1)<0){ - if(!scope.wireGainDragging && !document.activeElement?.matches?.(".strip select,.wire-gain")) + if(!scope.wireGainDragging && !document.activeElement?.matches?.(".strip select,.wire-gain,#wireWsGain")) scope.render?.(); controller.subscribe(); if(state.current)paintNativeMeters(state.current); From 28bf141e15fa5afa549173bba392fcdd6ecdc82b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:07:10 +0700 Subject: [PATCH 126/140] test(sonku): source-level native v2 DSP ACK and session persistence contract --- tests/native_peq_assembly_test.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/native_peq_assembly_test.py b/tests/native_peq_assembly_test.py index b72e67958..cdf1bc117 100644 --- a/tests/native_peq_assembly_test.py +++ b/tests/native_peq_assembly_test.py @@ -80,6 +80,31 @@ def test_single_style_owner(self): self.assertIn("armix-floating-close",throw) self.assertNotIn("new AudioContext",throw) + def test_sonku_native_space_v2_owned_by_single_pcm_graph(self): + main=(ROOT/"src/Main.cpp").read_text("utf-8") + processor=(ROOT/"engine/builtin_fx/SonKuSpatialProcessor.h").read_text("utf-8") + core=(ROOT/"engine/builtin_fx/sonku/SonKuSpatialCore.h").read_text("utf-8") + js=(ROOT/"site/preview-v2/assets/mixer-native-sonku.js").read_text("utf-8") + snapshot=main.split("void emitNativeSonKuSnapshot(",1)[1].split( + "void servicePendingNativeSonKu()",1)[0] + for field in ("spacePreset","sourceDistanceMeters","roomAmount","ambience"): + self.assertIn('values->setProperty("'+field+'"',snapshot) + if field=="spacePreset": + self.assertIn('values.getProperty("spacePreset"',main) + else: + self.assertIn('optionalNumber("'+field+'"',main) + self.assertIn(field,js) + self.assertIn(field,core) + self.assertIn('reply->setProperty("schemaVersion",2)',snapshot) + self.assertIn("queueSettings(settings,numeric)",main) + self.assertIn("complete_.push(",processor) + self.assertIn("out.writeInt(2)",processor) + self.assertIn("version==1&&size!=30",processor) + self.assertIn("version==2&&size!=46",processor) + self.assertNotIn("new AudioContext",js) + self.assertIn("[data-sk-room]",js) + self.assertIn('arMixBuiltinSonKuAck',js) + def test_native_tempo_readback_belongs_to_vocal_throw_not_eq(self): # The real C++ dispatcher must populate the exact VocalThrow # snapshot, not an unrelated EQ response. Browser-only mocks cannot From 361f6eb6d6453ec2f3a913f8945018927e67838e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:07:33 +0700 Subject: [PATCH 127/140] test(wire): execute native compiled inspector rollback with exact EdgeId rejection, focus and stale-route guards --- tests/approved_native_m2_contract.test.cjs | 23 ++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 8a6451d17..1209bc567 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -56,6 +56,7 @@ test("WIRE inspector controls PRIMARY BUS and PARALLEL MAIN by actual EdgeId, wi const parallel={id:42,sourceId:1,destId:3,kind:"send",mode:"send", nativeTap:"POST_FADER",levelDb:-6,enabled:true}; const panel={hidden:false,innerHTML:""},readout={textContent:"-6 dB"}; + const inspectorGain={value:"-12",dataset:{wsGain:"42"},disabled:false}; const observed=[]; const gain=input=>input?.dataset?.wsGain!==undefined?input:null; const tap=input=>input?.dataset?.wsTap!==undefined?input:null; @@ -66,6 +67,7 @@ test("WIRE inspector controls PRIMARY BUS and PARALLEL MAIN by actual EdgeId, wi get hidden(){return panel.hidden},set hidden(v){panel.hidden=v}, get innerHTML(){return panel.innerHTML},set innerHTML(v){panel.innerHTML=v}}; if(id==="wireWsGainText")return readout; + if(id==="wireWsGain")return inspectorGain; return null; }}, window:{__JUCE__:{backend:{}},__ARMIX_NATIVE_M2__:{ @@ -119,6 +121,27 @@ test("WIRE inspector controls PRIMARY BUS and PARALLEL MAIN by actual EdgeId, wi assert.match(observed[2],/awaiting accepted native PCM readback/); assert.equal(primary.levelDb,0); assert.equal(parallel.levelDb,-6,"reference WIRE graph never becomes native routing owner"); + // Execute the native compiled rollback method rather than a mock. It must + // repair the same focused DOM control from the latest accepted PCM readback. + // Rejection has no new snapshot: the original level remains -6, not -12. + const rollbackStart=html.indexOf(" rollbackNativeWireInspector(rows){"); + const rollbackEnd=html.indexOf(" syncVerifiedM4Wires(rows,ids){",rollbackStart); + assert.ok(rollbackStart>0&&rollbackEnd>rollbackStart,"native rollback method installed exactly once"); + const method=html.slice(rollbackStart,rollbackEnd).trim().replace(/,\\s*$/,""); + const rollback=vm.runInNewContext("({"+method+"})",scope); + assert.equal(rollback.rollbackNativeWireInspector([{id:42,levelDb:-6}]),true); + assert.equal(inspectorGain.value,"-6","failed native intent restores accepted gain without replacing the focused input"); + assert.equal(readout.textContent,"UNCHANGED · -6 dB","LCD cannot remain PENDING after a rejected gain"); + assert.equal(parallel.levelDb,-6,"no browser graph edit or optimistic audio state"); + assert.equal(rollback.rollbackNativeWireInspector([{id:42,levelDb:-6}]),false, + "idempotent failure reconciliation must not repaint a settled LCD"); + // A stale EdgeId cannot silently roll back or write a different route. + inspectorGain.dataset.wsGain="41";readout.textContent="PENDING · -8 dB"; + assert.equal(rollback.rollbackNativeWireInspector([{id:42,levelDb:-6}]),true); + assert.equal(inspectorGain.disabled,true); + assert.equal(readout.textContent,"SEND UNAVAILABLE"); + assert.match(bridge,/rollbackNativeWireInspector\\?\\.\\(nativeWireGainReadback\\(state.current\\)\\)/, + "native control failure must invoke the same compiled inspector rollback"); }); test("native PRE_FADER WIRE inspector uses one exact SET_TAP PCM intent and accepted readback",()=>{ From f337ae0c781fff60be5b41846fea8aa0e5f99b05 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:07:50 +0700 Subject: [PATCH 128/140] docs(sonku): native SPACE vertical slice architecture and release gates --- ...NATIVE_SPACE_RELEASE_CANDIDATE_20261113.md | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 docs/SONKU_M4_NATIVE_SPACE_RELEASE_CANDIDATE_20261113.md diff --git a/docs/SONKU_M4_NATIVE_SPACE_RELEASE_CANDIDATE_20261113.md b/docs/SONKU_M4_NATIVE_SPACE_RELEASE_CANDIDATE_20261113.md new file mode 100644 index 000000000..30812dd94 --- /dev/null +++ b/docs/SONKU_M4_NATIVE_SPACE_RELEASE_CANDIDATE_20261113.md @@ -0,0 +1,71 @@ +# SonKu M4 — Native SPACE / musical ambience release candidate +2026-11-13 | Draft stacked on #643 → #629 → #606 | NOT public release + +## Why this is a vertical product slice +Operator opens **8D-SonKu** from the real FX rack and selects OFF / SQUARE / +CHAMBER / LARGE. Two small sliders control source distance and musical +AMBIENCE. A single `nativeSonKuSet` message flows through the existing +device-epoch, graph-revision, exact ChannelId, instance lease, native queue, +JUCE processing callback and completion. The GUI only displays APPLIED after +matching callback ACK and accepted DSP readback. No WebAudio, browser PCM, +fake owner or duplicated audio callback. + +Room map: +- OFF: original direct KEMAR HRIR; no ER or late FDN work, v1-compatible. +- SQUARE: 7.2 × 7.2 m, max radius 3.1 m, short Studio Glue decay ~0.78 s. +- CHAMBER: 14.4 × 14.4 m, max radius 6.7 m, Airy decay ~1.28 s. +- LARGE: 28.8 × 28.8 m, max radius 10 m, restrained decay ~2.05 s. +RoomAmount is fixed to the previously tested 0.55 when user first enables +a scene. For each scene, the direct path uses 1.6 / sourceDistance pressure, +the eight first-order wall paths use 1.6 / reflectedPath pressure, and the +diffuse tail is wet-only. The exact approved HRIR azimuth and orbit geometry +are unchanged. + +## Realtime invariants +- All 8× per-line FDN feedback gains and damping coefficients for these + presets are computed on `prepare()` and selected without exp(), new/delete, + locks, device restart, or blocking calls in the callback. +- Coefficients and wet levels slew on the sample clock; existing ER fractional + delays and gains slew too, with geometry recalculated only every 64 samples. +- Reenable after disabled room uses a validity horizon on the existing fixed + 8192-sample ER rings; reenable on FDN uses a horizon on the existing 4096- + frame rings. No ~64/128 KiB buffer clears in a live edit. +- FX graph owns bypass/retire/reorder/routing; SonKu never installs its own + audio device or hidden monitoring gate. +- Multiple instances have independent fixed memory; no static mutable DSP. + +## Persistence and backward compatibility +`SonKuSpatialProcessor` serializes SONK version 2, exactly 46 bytes with +old 30-byte v1 restore supported. New state carries `spacePreset`, +`sourceDistanceMeters`, `roomAmount`, `ambience`. Legacy v1 restores as +room OFF; malformed v2 is rejected atomically; the last accepted edit is +only persisted after audio-applied completion. Accepted snapshot schema=2 +returns exactly the stored state. Existing GUI transport v1 fields may omit +new controls and default OFF. + +## What still blocks public release +1. CI: source contract, native no-JUCE PCM, Chromium actual WebView2-assembled + controls, exact-SHA Windows MSVC/CTest, multi-instance restore and restart. +2. Confirm no clicks/glitches on OFF→LARGE→SQUARE, rapid slider changes, rack + bypass, graph remove, save/open .smix, device swap, and stereo-only policy. +3. Human headphone A/B: compare approved Square reference, Studio Glue, Airy + and M4 scene presets with music + voice (front/rear distance, flutter, + metallic coloration, decay masking); adjust only after evidence. +4. Reconcile parent #606 (latest main) → #629 → #643 → this M4 without + dropping independent WIRE, GUI, updater and FX progress. Do not promote + public release based on Linux offline/Chromium mocks alone. + +## Explicit physical limits +2D first-order 4-wall image model; no height/floor/ceiling, personalized +HRTF, frequency-calibrated air absorption, true measured BRIR, later +higher-order bounces or physically fitted RT60. LARGE is a musical scene +preset, not a certified geometry-based hall reverb. Accurate propagation +delay of the direct path is not modeled, for low latency. + +## References (concepts only) +- Allen–Berkley image-source method: JASA 65(4), 1979, DOI 10.1121/1.382599 +- Valve Steam Audio core guide: direct distance and room reflections are + separate stages; no vendor code copied. + https://github.com/ValveSoftware/steam-audio/blob/master/core/doc/guide.rst +- JUCE AudioProcessor: processBlock realtime cautions and bypass semantics. + https://docs.juce.com/master/classjuce_1_1AudioProcessor.html From a8d9267eb437b7c44620b791b8e0c2374fba8a9f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:08:20 +0700 Subject: [PATCH 129/140] test(wire): correct JS RegExp escapes in executable compiled rollback regression --- tests/approved_native_m2_contract.test.cjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 1209bc567..327d67991 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -127,7 +127,7 @@ test("WIRE inspector controls PRIMARY BUS and PARALLEL MAIN by actual EdgeId, wi const rollbackStart=html.indexOf(" rollbackNativeWireInspector(rows){"); const rollbackEnd=html.indexOf(" syncVerifiedM4Wires(rows,ids){",rollbackStart); assert.ok(rollbackStart>0&&rollbackEnd>rollbackStart,"native rollback method installed exactly once"); - const method=html.slice(rollbackStart,rollbackEnd).trim().replace(/,\\s*$/,""); + const method=html.slice(rollbackStart,rollbackEnd).trim().replace(/,\s*$/,""); const rollback=vm.runInNewContext("({"+method+"})",scope); assert.equal(rollback.rollbackNativeWireInspector([{id:42,levelDb:-6}]),true); assert.equal(inspectorGain.value,"-6","failed native intent restores accepted gain without replacing the focused input"); @@ -140,7 +140,7 @@ test("WIRE inspector controls PRIMARY BUS and PARALLEL MAIN by actual EdgeId, wi assert.equal(rollback.rollbackNativeWireInspector([{id:42,levelDb:-6}]),true); assert.equal(inspectorGain.disabled,true); assert.equal(readout.textContent,"SEND UNAVAILABLE"); - assert.match(bridge,/rollbackNativeWireInspector\\?\\.\\(nativeWireGainReadback\\(state.current\\)\\)/, + assert.match(bridge,/rollbackNativeWireInspector\?\.\(nativeWireGainReadback\(state.current\)\)/, "native control failure must invoke the same compiled inspector rollback"); }); From a597ae93b7c4ef1b36af9760e8f756ca19644ecd Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:10:40 +0700 Subject: [PATCH 130/140] fix(sonku): make first native ROOM selection audible while preserving legacy OFF PCM --- engine/builtin_fx/sonku/SonKuSpatialCore.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/engine/builtin_fx/sonku/SonKuSpatialCore.h b/engine/builtin_fx/sonku/SonKuSpatialCore.h index 4ff690330..27d3226d8 100644 --- a/engine/builtin_fx/sonku/SonKuSpatialCore.h +++ b/engine/builtin_fx/sonku/SonKuSpatialCore.h @@ -25,8 +25,11 @@ struct Settings { // HRTF-only. All other scenes are optional and OFF unless selected. int spacePreset = 0; // 0=OFF, 1=Square 7.2, 2=Chamber 14.4, 3=Large 28.8 float sourceDistanceMeters = 1.6f; - float roomAmount = 0.f; - float ambience = 0.f; + // Stored while OFF so the first selected scene is immediately audible + // and turning ROOM off/on remembers the previous wet preference. + // spacePreset=0 still guarantees identical legacy HRTF-only PCM. + float roomAmount = .55f; + float ambience = .30f; }; inline bool valid(const Settings& s) noexcept { return std::isfinite(s.startAzimuthDegrees) && From 318b2c22f0f6503db1600bfc5f06284fabb7ba14 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:11:20 +0700 Subject: [PATCH 131/140] test(chromium): real WIRE Inspector rejected ACK restores focused gain and LCD without later snapshot --- tests/approved_native_wire_gain_smoke.py | 62 ++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/tests/approved_native_wire_gain_smoke.py b/tests/approved_native_wire_gain_smoke.py index 40fb13200..967280cda 100644 --- a/tests/approved_native_wire_gain_smoke.py +++ b/tests/approved_native_wire_gain_smoke.py @@ -143,6 +143,65 @@ def drag(): + +def verify_inspector_rejected_gain(page, out): + """Real compiled native GUI: rejected ACK with NO new snapshot must not + strand PENDING or detach the inspector slider held in keyboard focus.""" + page.add_init_script("""window.__nativeListeners=new Map();window.__nativeIntents=[]; + window.__JUCE__={backend:{ + emitEvent(name,payload){ + if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload); + }, + addEventListener(name,callback){window.__nativeListeners.set(name,callback);} + }};""") + errors=[] + page.on("pageerror",lambda exc:errors.append(str(exc))) + page.goto((out/"index.html").as_uri()) + page.wait_for_function("()=>window.__ARMIX_NATIVE_M2__?.enabled") + state=snapshot() + emit(page,"arMixConsoleSnapshot",state) + page.locator("#wireMatrixToggle").click() + route=page.locator('[data-ws-inspect="1:2"]') + route.wait_for(state="visible") + route.click() + slider=page.locator("#wireWsGain") + slider.wait_for(state="visible") + assert slider.is_enabled(),"Selected parallel SEND must allow native gain" + assert "PRIMARY" not in page.locator("#wireWsGainText").inner_text() + assert abs(float(slider.input_value())-(-6.0))<.11 + page.evaluate("()=>window.__heldInspectorGain=document.getElementById('wireWsGain')") + slider.focus() + slider.evaluate("""el=>{ + el.value='-12'; + el.dispatchEvent(new Event('input',{bubbles:true})); + }""") + assert page.locator("#wireWsGainText").inner_text()=="PENDING · -12 dB" + page.wait_for_function( + "()=>window.__nativeIntents.filter(x=>x.operation==='SET_WIRE_GAIN').length===1") + request=page.evaluate( + "()=>window.__nativeIntents.find(x=>x.operation==='SET_WIRE_GAIN')") + assert request["targetChannelId"]==SOURCE,request + assert request["payload"]["edgeId"]==SEND,request + assert abs(request["payload"]["gainLinear"]-10**(-12/20))<1e-8,request + emit(page,"arMixConsoleAck",{ + "requestId":request["requestId"],"status":"REJECTED", + "errorCode":"TEST_REJECTION","deviceEpoch":state["device"]["epoch"], + "graphRevision":state["graph"]["revision"], + "rosterRevision":state["graph"]["rosterRevision"]}) + # NO independent later snapshot is intentionally emitted. + # A rejected request cannot wait for one to repaint its LCD. + assert page.locator("#wireWsGainText").inner_text()=="UNCHANGED · -6 dB" + assert abs(float(slider.input_value())-(-6))<.11 + assert page.evaluate( + "()=>document.getElementById('wireWsGain')===window.__heldInspectorGain") + assert slider.evaluate("el=>document.activeElement===el"), ( + "Rejection must not drop keyboard focus on the original range input") + assert len(page.evaluate( + "()=>window.__nativeIntents.filter(x=>x.operation==='SET_WIRE_GAIN')"))==1 + assert abs(float(page.evaluate( + "()=>window.__ARMIX_NATIVE_SCOPE__.wireEdges.find(e=>e.id===2)?.levelDb"))-(-6))<.11 + assert not errors,errors + def verify_external_output(page, out): """Actual /preview/ native WebView: select -> native ACK -> callback readback. @@ -250,6 +309,9 @@ def main(): impact = browser.new_page(viewport={"width": 1366, "height": 768}) verify_socket_impact(impact, out) impact.close() + inspector_page = browser.new_page(viewport={"width":1366,"height":900}) + verify_inspector_rejected_gain(inspector_page,out) + inspector_page.close() output_page = browser.new_page(viewport={"width":1366,"height":900}) verify_external_output(output_page,out) output_page.close() From 484f46b6e85692111ed2d1e73644f5a5697653c1 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:11:55 +0700 Subject: [PATCH 132/140] ci(wire): reuse existing scoped Chromium runner for rejected inspector ACK regression --- .github/workflows/ui-smoke.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index d833184cb..414d85d68 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -195,7 +195,7 @@ jobs: needs: quick # Both 8D-SonKu and SOF native-owner PRs share ONE actual Chromium runner. # Preserve fast-only checks for unrelated GUI and engine branches. - if: ${{ (github.event_name == 'pull_request' && (startsWith(github.head_ref, 'feat/8d-sonku-') || startsWith(github.head_ref, 'test/sof-native-') || startsWith(github.head_ref, 'integration/sof-sonku-main-'))) || (github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/heads/feat/8d-sonku-') && inputs.expected_sha != '') }} + if: ${{ (github.event_name == 'pull_request' && (startsWith(github.head_ref, 'feat/8d-sonku-') || startsWith(github.head_ref, 'test/sof-native-') || startsWith(github.head_ref, 'integration/sof-sonku-main-') || startsWith(github.head_ref, 'fix/native-wire-inspector-'))) || (github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/heads/feat/8d-sonku-') && inputs.expected_sha != '') }} runs-on: ubuntu-latest timeout-minutes: 12 steps: @@ -216,6 +216,8 @@ jobs: # job (zero additional browser runners and zero Windows recompiles). - name: Native SOF PRE/POST, SEND ON, EdgeId gain and ACK/readback Chromium run: python tests/approved_native_sof_chromium_smoke.py + - name: Native WIRE Inspector rejected gain and exact EdgeId ACK rollback (real Chromium) + run: python tests/approved_native_wire_gain_smoke.py - name: Integrated V65 WIRE motion, SOF and actual native WIRE regression if: ${{ github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/sof-sonku-main-') }} run: | From 2900ffbe7c882d01f8dd20ab7d5a7ce611065051 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:12:28 +0700 Subject: [PATCH 133/140] feat(sonku): render five M4 musical scene WAVs through exact ACKed DSP core --- tools/sonku_offline_listening.cpp | 38 ++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/tools/sonku_offline_listening.cpp b/tools/sonku_offline_listening.cpp index 08b579f96..ae2697103 100644 --- a/tools/sonku_offline_listening.cpp +++ b/tools/sonku_offline_listening.cpp @@ -146,15 +146,18 @@ std::vector orbit(float roomAmount=0.f, // This deliberately exposes metallic late-tail coloration hidden by noise tests. // It uses the EXACT same SonKuSpatialCore and accepted square early room. std::vector musicalOrbit(float lateAmount, - armix::sonku::SonKuReverbPreset preset){ + armix::sonku::SonKuReverbPreset preset, + std::optional nativeScene=std::nullopt){ SonKuSpatialCore dsp; if(!dsp.prepare(rate)|| - !dsp.setEarlyReflectionsShape(armix::sonku::SonKuRoomShape::Square)|| - !dsp.setMusicalReverbPreset(preset)|| - !dsp.setEarlyReflectionsAmount(.55f)|| - !dsp.setMusicalReverbAmount(lateAmount)) + (!nativeScene && + (!dsp.setEarlyReflectionsShape(armix::sonku::SonKuRoomShape::Square)|| + !dsp.setMusicalReverbPreset(preset)|| + !dsp.setEarlyReflectionsAmount(.55f)|| + !dsp.setMusicalReverbAmount(lateAmount)))) throw std::runtime_error("Invalid original musical test configuration"); - Settings s=fixed(0.f);s.moving=true;s.clockwise=true;s.revolutionSeconds=10.f; + Settings s=nativeScene.value_or(fixed(0.f)); + s.moving=true;s.clockwise=true;s.revolutionSeconds=10.f; dsp.reset();if(!dsp.setSettings(s))throw std::runtime_error("Invalid musical orbit"); constexpr std::array notes{ 57,64,60,69,62,65,69,60,64,67, @@ -255,6 +258,14 @@ void notes(const std::filesystem::path& directory, <<"distance, and separately judge actual level reduction as a cue.\n" <<"V4 room tests disable FDN deliberately: the existing 0.78/1.28s\n" <<"tail is not calibrated for large halls (no pretend big-hall RT60).\n" + <<"M4 musical candidate WAVs use the EXACT native SonKu settings v2:\n" + <<"sonku-m4-musical-square-near-2x.wav = 7.2m, 1.6m, 0.30 ambience.\n" + <<"sonku-m4-musical-chamber-near-2x.wav = 14.4m, 1.6m.\n" + <<"sonku-m4-musical-chamber-far-2x.wav = 14.4m, 5m.\n" + <<"sonku-m4-musical-large-near-2x.wav = 28.8m, 1.6m.\n" + <<"sonku-m4-musical-large-far-2x.wav = 28.8m, 8m.\n" + <<"Same original plucked motif + KEMAR HRTF, same 20s clock;\n" + <<"decay programs = 0.78 / 1.28 / 2.05 s. NOT volume-normalized.\n" <<"Not simulated: air absorption, floor/ceiling, personalized HRTF,\n" <<"direct path time-of-flight, or higher-order wall reflections.\n" <<"Offline candidates only, NO native GUI/session/product release.\n"; @@ -323,6 +334,21 @@ int main(int argc,char** argv){ orbit(.55f,SonKuRoomShape::Square,true,0.f, SonKuReverbPreset::StudioGlue, SonKuRoomGeometry{28.8f,28.8f,8.f})); + // Native scene v2 listening evidence. These use the exact core API + // that receives ACKed FX editor settings (no separate reverb engine). + auto emitScene=[&](const char* file,int preset,float distance){ + Settings settings=fixed(0.f); + settings.spacePreset=preset; + settings.sourceDistanceMeters=distance; + settings.roomAmount=.55f; + settings.ambience=.30f; + writeWav(dir/file,musicalOrbit(0.f,SonKuReverbPreset::StudioGlue,settings)); + }; + emitScene("sonku-m4-musical-square-near-2x.wav",1,1.6f); + emitScene("sonku-m4-musical-chamber-near-2x.wav",2,1.6f); + emitScene("sonku-m4-musical-chamber-far-2x.wav",2,5.f); + emitScene("sonku-m4-musical-large-near-2x.wav",3,1.6f); + emitScene("sonku-m4-musical-large-far-2x.wav",3,8.f); notes(dir,blind); std::cout<<"SonKu listening package PASS: measured native HRTF, " <<"4 labeled + 8 blind directions + two uninterrupted 360 turns\n"; From 29e671bf1e0cf49a302dd842a058fcfd0070991f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:13:04 +0700 Subject: [PATCH 134/140] test(sonku): real M4 musical scene PCM differences and distance falloff --- tests/sonku_offline_demo_contract.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/sonku_offline_demo_contract.py b/tests/sonku_offline_demo_contract.py index 7a9bb4842..7faa70b27 100644 --- a/tests/sonku_offline_demo_contract.py +++ b/tests/sonku_offline_demo_contract.py @@ -51,6 +51,24 @@ def energy(a): return sum(abs(int(x)) for x in a[300000:440000]) assert .081000,"M4 square ambience is silent" +assert music_delta(m4Chamber,m4Square)>1000,"Chamber settings ignored" +assert music_delta(m4Large,m4Chamber)>1000,"Large room reverb ignored" +assert music_delta(m4Chamber,m4ChamberFar)>1000,"Chamber distance ignored" +assert music_delta(m4Large,m4LargeFar)>1000,"Large room distance ignored" +def musical_energy(a): + return sum(abs(int(x)) for x in a[280000:450000]) +assert musical_energy(m4ChamberFar) Date: Fri, 13 Nov 2026 14:14:11 +0700 Subject: [PATCH 135/140] test(chromium): resolve exact projected WIRE EdgeId instead of assuming allocator index 2 --- tests/approved_native_wire_gain_smoke.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/approved_native_wire_gain_smoke.py b/tests/approved_native_wire_gain_smoke.py index 967280cda..aae8e9611 100644 --- a/tests/approved_native_wire_gain_smoke.py +++ b/tests/approved_native_wire_gain_smoke.py @@ -198,8 +198,11 @@ def verify_inspector_rejected_gain(page, out): "Rejection must not drop keyboard focus on the original range input") assert len(page.evaluate( "()=>window.__nativeIntents.filter(x=>x.operation==='SET_WIRE_GAIN')"))==1 - assert abs(float(page.evaluate( - "()=>window.__ARMIX_NATIVE_SCOPE__.wireEdges.find(e=>e.id===2)?.levelDb"))-(-6))<.11 + assert abs(float(page.evaluate("""()=>{ + // EdgeId is allocated by the native graph projector; never assume 2. + const id=Number(document.getElementById('wireWsGain').dataset.wsGain); + return window.__ARMIX_NATIVE_SCOPE__.wireEdges.find(e=>e.id===id)?.levelDb; + }"""))-(-6))<.11 assert not errors,errors def verify_external_output(page, out): From 6996e9ebc530397f0163531cac3e223cde33af19 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:17:53 +0700 Subject: [PATCH 136/140] fix(wire): settle exact gain no-op and stale deferred EdgeId without spurious ACK wait --- web/approved-native-bridge.js | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 6108b3226..609089742 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -362,10 +362,23 @@ if(state?.pending||!current?.admitted)return; for(const [edgeId,edit] of pendingWireGains){ pendingWireGains.delete(edgeId); - if(current.identity!==edit.identity)continue; // never replay into a new graph/device + if(current.identity!==edit.identity){ + // A changed device/graph invalidates a deferred edit, but must not + // strand its LCD while waiting for a nonexistent ACK. + scope?.rollbackNativeWireInspector?.(nativeWireGainReadback(current)); + continue; // never replay into a new graph/device + } const edge=current.graph.edges.find(e=>e.enabled&&e.edgeId===edgeId&&e.from===edit.source); - if(!edge||edge.primaryOutput!==false)continue; - if(Math.abs(edge.gainLinear-edit.gain)<.00001)continue; + if(!edge||edge.primaryOutput!==false){ + scope?.rollbackNativeWireInspector?.(nativeWireGainReadback(current)); + continue; + } + if(Math.abs(edge.gainLinear-edit.gain)<.00001){ + // The accepted PCM gain already equals the requested scalar. Do not + // emit a redundant native intent, but DO settle the pending display. + scope?.syncNativeWireGains?.(nativeWireGainReadback(current)); + continue; + } const result=controller.intent("SET_WIRE_GAIN",edit.source,{edgeId,gainLinear:edit.gain}); if(result.ok)window.setTimeout(()=>controller?.expire(result.requestId),8000); else status("WIRE gain rejected · "+result.error); From 06b1bfebf256142f67a4dcf46090eb0068df6857 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:18:34 +0700 Subject: [PATCH 137/140] test(chromium): exact accepted -6 dB WIRE no-op settles LCD without any ACK or extra PCM intent --- tests/approved_native_wire_gain_smoke.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/approved_native_wire_gain_smoke.py b/tests/approved_native_wire_gain_smoke.py index aae8e9611..ec461bdee 100644 --- a/tests/approved_native_wire_gain_smoke.py +++ b/tests/approved_native_wire_gain_smoke.py @@ -159,6 +159,9 @@ def verify_inspector_rejected_gain(page, out): page.goto((out/"index.html").as_uri()) page.wait_for_function("()=>window.__ARMIX_NATIVE_M2__?.enabled") state=snapshot() + # Use an exactly representable accepted -6 dB gain to prove the + # native coalescer's equality/no-op path emits no redundant intent. + state["graph"]["edges"][1]["gainLinear"]=10**(-6/20) emit(page,"arMixConsoleSnapshot",state) page.locator("#wireMatrixToggle").click() route=page.locator('[data-ws-inspect="1:2"]') @@ -203,6 +206,21 @@ def verify_inspector_rejected_gain(page, out): const id=Number(document.getElementById('wireWsGain').dataset.wsGain); return window.__ARMIX_NATIVE_SCOPE__.wireEdges.find(e=>e.id===id)?.levelDb; }"""))-(-6))<.11 + # Requesting the exact same accepted -6 dB is a no-op: native must + # suppress redundant PCM writes AND settle the pending LCD by itself. + # No ACK, new snapshot or hidden user recovery action is available. + slider.evaluate("""el=>{ + el.value='-6'; + el.dispatchEvent(new Event('input',{bubbles:true})); + }""") + assert page.locator("#wireWsGainText").inner_text()=="PENDING · -6 dB" + page.wait_for_function("""()=>{ + return document.getElementById('wireWsGainText')?.textContent==='-6 dB'; + }""",timeout=5000) + assert len(page.evaluate( + "()=>window.__nativeIntents.filter(x=>x.operation==='SET_WIRE_GAIN')"))==1, ( + "Exact accepted gain no-op must not resend a native PCM command") + assert slider.evaluate("el=>document.activeElement===el") assert not errors,errors def verify_external_output(page, out): From 0bcb695fd7f72a9d39110fd1c146ed8db7ab6b0d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:28:45 +0700 Subject: [PATCH 138/140] test(sonku): exact JUCE native v1/v2 state migration and PCM-applied ACK --- CMakeLists.txt | 8 ++++ tests/sonku_native_state_test.cpp | 76 +++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 tests/sonku_native_state_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 697e2a77c..e7d2b95dd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -202,6 +202,14 @@ if(BUILD_TESTING) add_executable(ARMixSonKuCoreTests tests/sonku_spatial_core_test.cpp) target_compile_features(ARMixSonKuCoreTests PRIVATE cxx_std_20) add_test(NAME NativeSonKuMeasuredBinauralDirectionalAndChunkParity COMMAND ARMixSonKuCoreTests) + # Real JUCE processor: audio-applied ACK, v1/v2 state, corruption fences. + juce_add_console_app(ARMixSonKuNativeStateTests PRODUCT_NAME "ArSonMix SonKu Native State Tests") + target_sources(ARMixSonKuNativeStateTests PRIVATE tests/sonku_native_state_test.cpp) + target_link_libraries(ARMixSonKuNativeStateTests PRIVATE + juce::juce_audio_processors juce::juce_recommended_config_flags) + target_compile_features(ARMixSonKuNativeStateTests PRIVATE cxx_std_20) + add_test(NAME NativeSonKuSessionV1V2AndAudioAppliedAck + COMMAND ARMixSonKuNativeStateTests) # Pure control-plane first-run routing selection: no JUCE, drivers, # WASAPI activation or callback dependencies. Full Windows CTest gate. add_executable(ARMixFirstRunEndpointPolicyTests diff --git a/tests/sonku_native_state_test.cpp b/tests/sonku_native_state_test.cpp new file mode 100644 index 000000000..ad2927dff --- /dev/null +++ b/tests/sonku_native_state_test.cpp @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Real JUCE SonKu adapter: authoritative audio ACK, v1/v2 persistence, +// corrupt-state rejection and real 2-channel PCM after restore. +#if defined(NDEBUG) +#undef NDEBUG +#endif +#include "../engine/builtin_fx/SonKuSpatialProcessor.h" +#include +#include +#include +int main(){ + using armix::builtin_fx::SonKuSpatialProcessor; + SonKuSpatialProcessor live; + live.prepareToPlay(48000.,128); + assert(live.isReady()); + auto scene=live.acceptedSettings(); + assert(scene.spacePreset==0); // legacy samples always load with ROOM OFF + scene.spacePreset=2;scene.sourceDistanceMeters=5.f; + scene.roomAmount=.55f;scene.ambience=.30f; + assert(armix::sonku::valid(scene)); + assert(live.queueSettings(scene,42)); + // Queued does NOT mean accepted; only the actual PCM callback may apply. + assert(live.acceptedSettings().spacePreset==0); + juce::AudioBuffer audio(2,128); + juce::MidiBuffer midi; + audio.clear(); + audio.getWritePointer(0)[0]=.1f; + audio.getWritePointer(1)[0]=.1f; + live.processBlock(audio,midi); + SonKuSpatialProcessor::Completion ack{}; + assert(live.pollCompletion(ack) && ack.applied && ack.requestId==42); + assert(live.acceptedSettings().spacePreset==2); + assert(live.acceptedSettings().sourceDistanceMeters==5.f); + for(int c=0;c<2;++c) + for(int i=0;i<128;++i)assert(std::isfinite(audio.getSample(c,i))); + juce::MemoryBlock bytes; + live.getStateInformation(bytes); + assert(bytes.getSize()==46); + SonKuSpatialProcessor restored; + restored.prepareToPlay(48000.,128); + assert(restored.restoreUnpublishedState(bytes.getData(), + static_cast(bytes.getSize()))); + const auto got=restored.acceptedSettings(); + assert(got.spacePreset==2&&got.sourceDistanceMeters==5.f); + assert(got.roomAmount==.55f&&got.ambience==.30f); + assert(restored.getTailLengthSeconds()>=2.); + audio.clear();audio.getWritePointer(0)[0]=.1f; + restored.processBlock(audio,midi); + for(int c=0;c<2;++c) + for(int i=0;i<128;++i)assert(std::isfinite(audio.getSample(c,i))); + // Strict v1 binary payload: SONK, v1, five floats and two bool bytes. + juce::MemoryBlock legacy; + {juce::MemoryOutputStream out(legacy,false); + out.writeInt(0x534F4E4B);out.writeInt(1); + out.writeFloat(0.f);out.writeFloat(12.f);out.writeFloat(60.f); + out.writeFloat(1.f);out.writeFloat(.75f); + out.writeByte(1);out.writeByte(1);} + assert(legacy.getSize()==30); + SonKuSpatialProcessor older; + older.prepareToPlay(48000.,128); + assert(older.restoreUnpublishedState(legacy.getData(),30)); + assert(older.acceptedSettings().spacePreset==0); + assert(!older.restoreUnpublishedState(legacy.getData(),29)); + juce::MemoryBlock invalid=bytes; + auto* data=static_cast(invalid.getData()); + // Space preset starts at byte offset 30: reject out-of-range v2 schema. + data[30]=99;data[31]=data[32]=data[33]=0; + SonKuSpatialProcessor bad; + bad.prepareToPlay(48000.,128); + assert(!bad.restoreUnpublishedState(invalid.getData(),46)); + assert(bad.acceptedSettings().spacePreset==0); + // Stale/completed active buffers may not be used as a published restore. + restored.sealForRealtime(); + assert(!restored.restoreUnpublishedState(bytes.getData(),46)); + return 0; +} From 22e76e46565973a5a1587dde05703078f28653d9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 14:37:50 +0700 Subject: [PATCH 139/140] ci(sonku): run existing scoped native Chromium FAT on SonKu M4+WIRE reconciliation PR --- .github/workflows/ui-smoke.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index b0047ee99..4d0eb70ae 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -195,7 +195,7 @@ jobs: needs: quick # Both 8D-SonKu and SOF native-owner PRs share ONE actual Chromium runner. # Preserve fast-only checks for unrelated GUI and engine branches. - if: ${{ (github.event_name == 'pull_request' && (startsWith(github.head_ref, 'feat/8d-sonku-') || startsWith(github.head_ref, 'test/sof-native-') || startsWith(github.head_ref, 'integration/sof-sonku-main-') || startsWith(github.head_ref, 'fix/native-wire-inspector-'))) || (github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/heads/feat/8d-sonku-') && inputs.expected_sha != '') }} + if: ${{ (github.event_name == 'pull_request' && (startsWith(github.head_ref, 'feat/8d-sonku-') || startsWith(github.head_ref, 'test/sof-native-') || startsWith(github.head_ref, 'integration/sof-sonku-main-') || startsWith(github.head_ref, 'fix/native-wire-inspector-') || startsWith(github.head_ref, 'integration/sonku-m4-wire-'))) || (github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/heads/feat/8d-sonku-') && inputs.expected_sha != '') }} runs-on: ubuntu-latest timeout-minutes: 12 steps: From 1d8b5b3319349efea1b55087323491ef355755a4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 13 Nov 2026 15:02:14 +0700 Subject: [PATCH 140/140] ci(integration): qualify combined SonKu M4, Guitar FX and WIRE V67 on existing scoped Chromium runner --- .github/workflows/ui-smoke.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 4d0eb70ae..7962776fd 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -195,7 +195,7 @@ jobs: needs: quick # Both 8D-SonKu and SOF native-owner PRs share ONE actual Chromium runner. # Preserve fast-only checks for unrelated GUI and engine branches. - if: ${{ (github.event_name == 'pull_request' && (startsWith(github.head_ref, 'feat/8d-sonku-') || startsWith(github.head_ref, 'test/sof-native-') || startsWith(github.head_ref, 'integration/sof-sonku-main-') || startsWith(github.head_ref, 'fix/native-wire-inspector-') || startsWith(github.head_ref, 'integration/sonku-m4-wire-'))) || (github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/heads/feat/8d-sonku-') && inputs.expected_sha != '') }} + if: ${{ (github.event_name == 'pull_request' && (startsWith(github.head_ref, 'feat/8d-sonku-') || startsWith(github.head_ref, 'test/sof-native-') || startsWith(github.head_ref, 'integration/sof-sonku-main-') || startsWith(github.head_ref, 'fix/native-wire-inspector-') || startsWith(github.head_ref, 'integration/sonku-m4-wire-') || startsWith(github.head_ref, 'integration/sonku-m4-guitar-'))) || (github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/heads/feat/8d-sonku-') && inputs.expected_sha != '') }} runs-on: ubuntu-latest timeout-minutes: 12 steps: