diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py
index e93910d68..9b161d488 100644
--- a/scripts/build_approved_native_gui.py
+++ b/scripts/build_approved_native_gui.py
@@ -21,7 +21,8 @@
ROOT = Path(__file__).resolve().parents[1]
CANONICAL = ROOT / "site" / "preview-v2"
NATIVE_ADAPTER = ROOT / "web" / "approved-native-bridge.js"
-ADAPTER_MARKER = ('\n'
+ADAPTER_MARKER = ('\n'
+ '\n'
'')
SCHEMA = "arsonmix.approved-native-pages-bundle.v2"
@@ -57,6 +58,11 @@ def accepted_pages_html() -> str:
# HTML at native build time. Every anchor must occur exactly once: no silent
# breakage if Pages GUI source evolves. No extra layout or simulated PCM.
NATIVE_EVENT_HOOKS = (
+ # The approved Pages HTML stays byte-for-byte unchanged; these two
+ # reversible native-only hooks expose verified mixer hardware choices.
+ ("const option=(values,selected)=>values.map(x=>'').join('');\n", "const option=(values,selected)=>values.map(x=>{const value=Array.isArray(x)?x[0]:x,label=Array.isArray(x)?x[1]:x;return '';}).join('');\n"),
+ ("const channelOptions=(t,type)=>{\n",
+ "const channelOptions=(t,type)=>{\n if(window.__JUCE__?.backend){\n const native=window.__ARMIX_NATIVE_M2__?.channelOptions?.(t,type);\n if(native)return native;\n return type==='input'?[['None','Choose audio device…']]:type==='output'?[[t.output||'Master','MAIN']]:['None'];\n }\n"),
("function wireGraphCommit(ops,{record=true}={}){\n",
"function wireGraphCommit(ops,{record=true}={}){\n"
" if(window.__JUCE__?.backend){window.__ARMIX_NATIVE_M2__?.consumeWire?.(ops);return false;}\n"),
@@ -186,6 +192,8 @@ def stage(out: Path) -> dict:
out.mkdir(parents=True)
shutil.copytree(pages / "assets", out / "assets")
shutil.copy2(NATIVE_ADAPTER, out / "assets" / "approved-native-bridge.js")
+ shutil.copy2(ROOT / "web" / "approved-native-io.css",
+ out / "assets" / "approved-native-io.css")
shutil.copy2(ROOT / "web" / "approved-native-contract.js",
out / "assets" / "approved-native-contract.js")
native = native_html(approved.decode("utf-8")).encode("utf-8")
diff --git a/src/Main.cpp b/src/Main.cpp
index f410bce6b..6fde37f5f 100644
--- a/src/Main.cpp
+++ b/src/Main.cpp
@@ -783,17 +783,31 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr
if(engine_.dryRoutingLabActive() && channel>=1 &&
channel<=LiveDryRoutingLab::count &&
(name=="faderDb"||name=="pan"||name=="mute"||name=="solo")) {
+ // Audition-style live mixer control: all ten strip faders/pans/
+ // mute/solo target their REAL native PCM owner, never the Pages
+ // demo model or hardcoded legacy CH1. No UI-thread graph rebuild.
const auto ep=args.getProperty("routeEpoch",juce::var());
const auto rev=args.getProperty("routeRevision",juce::var());
+ bool accepted=false;
if(!ep.isVoid()&&!rev.isVoid() &&
((name=="mute"||name=="solo")?value.isBool():
(value.isDouble()||value.isInt()))) {
const auto epoch=static_cast(static_cast(ep));
const auto revision=static_cast(static_cast(rev));
const float liveValue=value.isBool()?(bool(value)?1.f:0.f):valueNumber;
- (void)engine_.setDryRoutingLabParameter(channel-1,epoch,revision,
+ accepted=engine_.setDryRoutingLabParameter(channel-1,epoch,revision,
name,liveValue);
}
+ auto ack=std::make_unique();
+ ack->setProperty("channel",channel);
+ ack->setProperty("parameter",name);
+ ack->setProperty("ok",accepted);
+ ack->setProperty("routeEpoch",
+ static_cast(engine_.dryRoutingLabEpoch()));
+ ack->setProperty("routeRevision",
+ static_cast(engine_.dryRoutingLabRevision()));
+ if(browser_.loaded)
+ browser_.emitEventIfBrowserIsVisible("arMixM4ControlAck",juce::var(ack.release()));
return;
}
if (name == "masterGain" && (value.isDouble() || value.isInt()))
diff --git a/src/NativeVerifiedSourcePatch.h b/src/NativeVerifiedSourcePatch.h
index ca9927d87..677be1000 100644
--- a/src/NativeVerifiedSourcePatch.h
+++ b/src/NativeVerifiedSourcePatch.h
@@ -23,9 +23,11 @@ struct NativeVerifiedSourcePatch final {
actualRevision>static_cast(std::numeric_limits::max()) ||
!accepted.isObject() || channel<0 || channel>=10)
return "SOURCE: stale device epoch or invalid native channel";
- if(mode!="MONO"&&mode!="STEREO")
- return "SOURCE: MONO or STEREO mode required";
- if(physicalLeft<0 || enabledPhysicalPorts.empty())
+ if(mode!="NONE"&&mode!="MONO"&&mode!="STEREO")
+ return "SOURCE: NONE, MONO or STEREO mode required";
+ if(mode=="NONE" && (physicalLeft!=-1||physicalRight!=-1))
+ return "SOURCE: clear input requires no physical capture pins";
+ if(mode!="NONE"&&(physicalLeft<0||enabledPhysicalPorts.empty()))
return "SOURCE: select an enabled physical capture pin";
if(static_cast(accepted.getProperty("deviceEpoch",juce::var(-1))) !=
static_cast(actualEpoch))
@@ -35,8 +37,8 @@ struct NativeVerifiedSourcePatch final {
if(port==physicalLeft)validLeft=true;
if(port==physicalRight)validRight=true;
}
- if(!validLeft || (mode=="STEREO" &&
- (!validRight || physicalLeft==physicalRight)))
+ if(mode!="NONE"&&(!validLeft || (mode=="STEREO" &&
+ (!validRight || physicalLeft==physicalRight))))
return "SOURCE: STEREO requires two distinct active physical pins; MONO accepts one";
// JUCE var assignment shares the underlying DynamicObject. Deep
// clone before touching a row, or failed prepare would silently
@@ -62,11 +64,11 @@ struct NativeVerifiedSourcePatch final {
const auto width=row->getProperty("channelFormat").toString();
if(width!="MONO" && width!="STEREO")
return "SOURCE: native processing format missing or invalid";
- row->setProperty("sourceKind","PHYSICAL");
+ row->setProperty("sourceKind",mode=="NONE"?"NONE":"PHYSICAL");
row->setProperty("sourceFormat",mode);
}
row->setProperty("mode",mode);
- row->setProperty("left",physicalLeft);
+ row->setProperty("left",mode=="NONE"?-1:physicalLeft);
row->setProperty("right",mode=="STEREO"?physicalRight:-1);
// The existing M4 producer handles revision/epoch publication and
// fails back to its prior accepted graph on any bad plugin/routing.
diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs
index 2b584dd09..f84e50e36 100644
--- a/tests/approved_native_m2_contract.test.cjs
+++ b/tests/approved_native_m2_contract.test.cjs
@@ -416,6 +416,85 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a
assert.equal(scope.edges.length,0,"accepted snapshot replaces reference wire");
});
+test("verified Windows CH10 selects sparse hardware IN3 then native ACK starts MAIN; M4 fader targets CH10",()=>{
+ const vm=require("node:vm"),events=[],listeners=new Map();
+ const tracks=Array.from({length:10},(_,i)=>({
+ id:30+i,name:"CH"+(i+1),kind:"audio",input:"None",output:"Master",
+ level:-12,pan:0,mute:false,solo:false
+ }));
+ const scope={tracks,master:{id:90,name:"MAIN",level:0,mute:false},
+ render(){},stopDemo(){},findTrack(el){return el.track;},
+ displayMeterDbfs(){}};
+ const backend={
+ emitEvent(name,payload){events.push({name,payload});},
+ addEventListener(name,cb){listeners.set(name,cb);}
+ };
+ const preview={disabled:false};
+ const document={
+ readyState:"complete",documentElement:{dataset:{}},
+ getElementById:id=>id==="info"?{textContent:""}:id==="preview"?preview:null,
+ querySelector(){return null;},addEventListener(){}
+ };
+ const window={__JUCE__:{backend},ArSonApprovedNativeContract:protocol,
+ __ARMIX_NATIVE_SCOPE__:scope,setTimeout(){return 0;}};
+ vm.runInNewContext(read("web/approved-native-bridge.js"),
+ {window,document,performance:{now:()=>0},console},{timeout:1500});
+ const g0=clone(fixtures.g0);
+ g0.device.enabledInputs=[0,2];
+ g0.device.inputEndpoints=[
+ {id:"in:0",port:0,callback:0,label:"Mic 1",active:true},
+ {id:"in:2",port:2,callback:1,label:"Mic 3",active:true}
+ ];
+ g0.legacyM4={active:true,routeAccepted:false,routingRevision:"12"};
+ listeners.get("arMixConsoleSnapshot")(g0);
+ listeners.get("arMixStatus")({
+ connected:true,directRouteAuthorized:true,adaptiveClockActive:false,
+ monitor:false,dryRoutingLab:{active:true,ready:true,topologyFault:false,
+ hasAcceptedRoute:false,epoch:69,revision:12}
+ });
+ const choices=window.__ARMIX_NATIVE_M2__.channelOptions(tracks[9],"input");
+ assert.ok(choices.some(x=>x[0]==="MONO:2"),"sparse physical input is real");
+ assert.ok(!choices.some(x=>/CABLE Output L\/R \(Stereo\)/.test(x[0])),
+ "fake Pages CABLE list must not be selectable as hardware");
+ const picker={dataset:{field:"input"},value:"MONO:2",track:tracks[9]};
+ assert.equal(window.__ARMIX_NATIVE_M2__.consumeField({target:picker,type:"change"}),true);
+ const req=events.findLast(x=>x.payload?.action==="routingSourceSwitch");
+ assert.ok(req);
+ assert.equal(req.payload.channel,9,"CH10 routes its OWN hardware input");
+ assert.equal(req.payload.left,2);
+ assert.equal(req.payload.mode,"MONO");
+ assert.equal(req.payload.deviceEpoch,69);
+ assert.equal(req.payload.revision,12);
+ const rows=Array.from({length:10},(_,i)=>i===9?
+ {mode:"MONO",left:2,right:-1,main:true}:
+ {mode:"NONE",left:-1,right:-1,main:true});
+ listeners.get("arMixSourceSwitchAck")({
+ ok:true,requestId:req.payload.requestId,channel:9,
+ state:{active:true,ready:true,topologyFault:false,
+ hasAcceptedRoute:true,epoch:69,revision:13,
+ acceptedRoute:{channels:rows}}
+ });
+ const monitor=events.findLast(x=>x.payload?.action==="monitor");
+ assert.ok(monitor);
+ assert.equal(monitor.payload.value,true);
+ assert.equal(monitor.payload.expectedRevision,13);
+ assert.equal(tracks[9].input,"MONO:2");
+ listeners.get("arMixAudioArmAck")({ok:true,armed:true,deviceEpoch:69});
+ const armed=clone(g0);
+ armed.legacyM4={active:true,routeAccepted:true,routingRevision:"13"};
+ armed.device.outputArmed=true;
+ listeners.get("arMixConsoleSnapshot")(armed);
+ const fader={dataset:{field:"level"},value:"-18",track:tracks[9]};
+ window.__ARMIX_NATIVE_M2__.consumeField({target:fader,type:"change"});
+ const param=events.findLast(x=>x.name==="arMixParameter");
+ assert.ok(param,"M4 CH10 fader reaches real native parameter transport");
+ assert.equal(param.payload.channel,10);
+ assert.equal(param.payload.parameter,"faderDb");
+ assert.equal(param.payload.routeEpoch,69);
+ assert.equal(param.payload.routeRevision,13);
+ assert.equal(param.payload.value,-18);
+});
+
test("M3 Windows bundle owns pointerup fader gesture and fences native FX keyboard reorder",()=>{
const builder=read("scripts/build_approved_native_gui.py");
const bridge=read("web/approved-native-bridge.js");
@@ -428,29 +507,51 @@ test("M3 Windows bundle owns pointerup fader gesture and fences native FX keyboa
assert.ok(!bridge.includes('window.addEventListener("pointerup"'));
});
-test("native Windows operator can explicitly patch first physical input, arm and mute",()=>{
+test("Windows mixer uses Audition-style native IN on any channel, no hidden CH1 arm wizard",()=>{
const js=read("web/approved-native-bridge.js");
const main=read("src/Main.cpp");
const engine=read("src/LiveAudioEngine.h");
- assert.match(js,/REAL AUDIO · FIRST SOUND/);
- assert.match(js,/action:"audioSetup"/);
- assert.match(js,/d\.inputEndpoints\.filter\(p=>/);
- assert.match(js,/d\.enabledInputs\.includes\(p\.port\)/);
- assert.match(js,/action:"routingSourceSwitch",requestId:pendingSourceId/);
- assert.match(js,/channel:0,mode:"MONO",left:pin,right:-1/);
- assert.match(js,/action:"monitor",value:true/);
+ const page=read("site/preview-v2/index.html");
+ const builder=read("scripts/build_approved_native_gui.py");
+ assert.match(js,/channelOptions:nativeChannelOptions/);
+ assert.match(js,/const chooseNativePhysicalInput=\(track,value\)=>/);
+ assert.match(js,/const channel=inputAt\(track\)/);
+ assert.match(js,/action:"routingSourceSwitch",requestId:p.id,channel:p.channel/);
+ assert.match(js,/inputAt\(track\)/);
+ assert.match(js,/nativeSourcePending\.phase="mute"/);
assert.match(js,/action:"monitor",value:false/);
- assert.match(js,/expectedEpoch:epoch,expectedRevision:revision/);
+ assert.match(js,/action:"monitor",value:true/);
assert.match(js,/arMixSourceSwitchAck/);
assert.match(js,/arMixAudioArmAck/);
- assert.match(js,/if\(ack\.ok===true\)/);
- assert.match(js,/NATIVE PATCH REJECTED:/);
- assert.match(js,/NO VERIFIED AUDIO DEVICE/);
- assert.match(js,/NATIVE PCM · HARDWARE FAT PENDING/);
- assert.match(js,/MAIN ARMED · PCM NOT YET ADMITTED/);
+ assert.match(js,/deviceEpoch:p.epoch,revision:p.revision/);
+ assert.match(js,/arMixAudioDeviceApplyAck/);
+ assert.match(js,/arMixAudioDeviceInventory/);
+ assert.match(js,/Audio I\/O Settings/);
+ assert.match(js,/Driver Recovery…/);
+ assert.doesNotMatch(js,/Patch CH1|Arm output/);
+ assert.doesNotMatch(page,/__ARMIX_NATIVE_M2__/,"public approved Pages must remain byte-identical");
+ assert.match(builder,/const channelOptions=\(t,type\)=>/);
+ assert.match(builder,/Array\.isArray\(x\)\?x\[0\]:x/);
+ assert.match(builder,/approved-native-io\.css/);
assert.match(main,/action=="routingSourceSwitch"/);
assert.match(main,/engine_\.liveOutputArmFault\(\)/);
- assert.match(main,/safe->emitApprovedNativeSnapshot\(\)/);
assert.match(engine,/juce::String switchDryRoutingLabSource\(/);
assert.match(engine,/setOutputMuted\(true\)/);
});
+test("G0 M4 real mixer fader/pan/mute/solo work before universal ChannelId admission",()=>{
+ const js=read("web/approved-native-bridge.js");
+ const main=read("src/Main.cpp");
+ const dry=read("src/LiveDryRoutingLab.h");
+ assert.match(js,/verifiedM4\(\)/);
+ assert.match(js,/m4Parameter\(t,"faderDb",numeric\)/);
+ assert.match(js,/m4Parameter\(t,"pan",pan\)/);
+ assert.match(js,/m4Parameter\(t,action,!t\[action\]\)/);
+ assert.match(js,/channel:channel\+1,value,routeEpoch:epoch,routeRevision:revision/);
+ assert.match(js,/renderMeasuredM4\(live\)/);
+ assert.match(js,/channelPeaksL/);
+ assert.match(js,/channelPeaksR/);
+ assert.match(main,/accepted=engine_\.setDryRoutingLabParameter\(channel-1/);
+ assert.match(main,/arMixM4ControlAck/);
+ assert.match(dry,/publisher_\.updateActiveControl\(expectedEpoch,expectedRevision/);
+});
+
diff --git a/tests/native_dry_route_command_test.cpp b/tests/native_dry_route_command_test.cpp
index 4b8d3239f..b8700c410 100644
--- a/tests/native_dry_route_command_test.cpp
+++ b/tests/native_dry_route_command_test.cpp
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
#include "../engine/core/NativeDryRouteCommand.h"
#include "../engine/core/PreparedMixerBlock.h"
+#include "../src/NativeVerifiedSourcePatch.h"
#if defined(NDEBUG)
#undef NDEBUG
#endif
@@ -139,6 +140,35 @@ int main(){
assert(near(l[0],0.5f*0.70710678118f));
assert(near(r[0],0.5f*0.70710678118f));
+ // Audition-style IN=None on ANY previously routed native channel is a
+ // complete typed source patch, not an invalid physical input/guessed pin.
+ // The accepted reference stays unchanged until the graph is republished.
+ auto sourceTemplate=juce::JSON::parse(juce::JSON::toString(typed,false));
+ sourceTemplate.getDynamicObject()->setProperty("deviceEpoch",juce::int64(91));
+ sourceTemplate.getDynamicObject()->setProperty("revision",juce::int64(7));
+ sourceTemplate.getDynamicObject()->setProperty("sends",
+ juce::var(juce::Array{}));
+ juce::var noSource,invalidClear;
+ assert(NativeVerifiedSourcePatch::prepare(sourceTemplate,0,"NONE",-1,-1,
+ ports,91,7,noSource).isEmpty());
+ const auto cleared=noSource.getProperty("channels",{}).getArray()->getReference(0);
+ assert(cleared.getProperty("mode",{}).toString()=="NONE");
+ assert(cleared.getProperty("sourceKind",{}).toString()=="NONE");
+ assert(cleared.getProperty("sourceFormat",{}).toString()=="NONE");
+ assert(static_cast(cleared.getProperty("left",0))==-1);
+ assert(static_cast(cleared.getProperty("right",0))==-1);
+ assert(sourceTemplate.getProperty("channels",{}).getArray()
+ ->getReference(0).getProperty("mode",{}).toString()=="MONO");
+ assert(NativeVerifiedSourcePatch::prepare(sourceTemplate,0,"NONE",2,-1,
+ ports,91,7,invalidClear).isNotEmpty());
+ assert(invalidClear.isVoid());
+ assert(NativeVerifiedSourcePatch::prepare(sourceTemplate,0,"NONE",-1,-1,
+ ports,92,7,invalidClear).isNotEmpty()); // wrong driver epoch
+ NativeDryRouteCommand clearedPlan;
+ assert(NativeDryRouteCommand::decode(noSource,clearedPlan,error));
+ assert(clearedPlan.channels.stripsAndMaster.strips[0].source==SourceMode::disconnected);
+ assert(clearedPlan.channels.formats[0]==ChannelFormat::stereo);
+
// Fail-closed: one type mismatch, old decoded plan unchanged.
const auto before=v2;
auto* ch0=typed.getProperty("channels",juce::var())
diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js
index 7e548a6e3..fa31b966b 100644
--- a/web/approved-native-bridge.js
+++ b/web/approved-native-bridge.js
@@ -145,137 +145,498 @@
}
}
- // Native-only operator controls in the EXISTING approved More menu:
- // user selects REAL JUCE active pin -> explicitly patches CH1 -> arms output.
- // No auto-arm, demo PCM, guessed physical port or second GUI.
- let hardware=null, inputSelect=null, routeBtn=null, armBtn=null, muteBtn=null;
- let hardwareNote=null, pendingSourceId=0, sourceSerial=100;
- const safeNativeCounter=x=>{
- if(typeof x!=="string" || !/^[1-9]\d*$/.test(x))return null;
- const number=Number(x);
- return Number.isSafeInteger(number)&&number>0?number:null;
- };
+ // Exactly one device configuration flow: reuse the existing custom
+ // Audio I/O panel, not a second large JUCE AudioDeviceSelectorComponent.
+ // It remains available as an Advanced driver-recovery tool in native host.
+ let hardware=null, hardwareNote=null, lastDryReadback=null;
const legacy=()=>hardware?.raw?.legacyM4;
const deviceReady=()=>!!(hardware?.device?.backend &&
hardware.device.sampleRate>0 &&
hardware.device.enabledInputs.length>0 &&
hardware.device.enabledOutputs.length>=2 && legacy()?.active===true);
+ const verifiedM4=()=>{
+ const d=lastDryReadback;
+ return deviceReady() && legacy()?.routeAccepted===true &&
+ d?.ready===true && d?.hasAcceptedRoute===true && !d?.topologyFault &&
+ String(d.epoch)===hardware.device.epoch &&
+ String(d.revision)===legacy().routingRevision;
+ };
function updateHardwarePanel(next) {
- hardware=next || null;
+ hardware=next||null;
const d=next?.device;
const deviceOpen=Boolean(d?.backend && d.sampleRate>0 &&
d.enabledOutputs.length>=2);
const label=document.getElementById("transport");
- if(label)label.textContent=!deviceOpen?"Device not ready":
- d.outputArmed?"Output armed":"Output muted";
+ if(label)label.textContent=!deviceOpen?"Choose audio device":
+ d.outputArmed?"MAIN monitoring on":"MAIN monitoring off";
+
const warning=document.querySelector?.(".status-bar .warning");
- if(warning)warning.textContent=!deviceOpen?"NO VERIFIED AUDIO DEVICE":
+ if(warning)warning.textContent=!deviceOpen?"CHOOSE AUDIO OUTPUT":
d.outputArmed?(next.admitted?"NATIVE PCM · HARDWARE FAT PENDING":
- "MAIN ARMED · PCM NOT YET ADMITTED"):
- legacy()?.routeAccepted?"INPUT PATCHED · OUTPUT MUTED":
- "NO AUDIBLE OUTPUT · PATCH INPUT + ARM";
- if(!inputSelect)return;
- const pins=deviceOpen?d.inputEndpoints.filter(p=>
- p.active===true && d.enabledInputs.includes(p.port)):[];
- const key=pins.map(p=>p.id+"|"+p.label).join(";");
- if(inputSelect.dataset.pins!==key) {
- const before=inputSelect.value;
- inputSelect.dataset.pins=key;
- inputSelect.replaceChildren();
- const option=document.createElement("option");
- option.value="";option.textContent="Physical input for CH1";
- inputSelect.appendChild(option);
- for(const pin of pins){
- const item=document.createElement("option");
- item.value=String(pin.port);
- item.textContent=pin.label+" · IN "+(pin.port+1);
- inputSelect.appendChild(item);
- }
- if(pins.some(p=>String(p.port)===before))inputSelect.value=before;
- }
- inputSelect.disabled=!deviceReady();
- if(routeBtn)routeBtn.disabled=!deviceReady() ||
- inputSelect.value==="" || pendingSourceId!==0;
- if(armBtn)armBtn.disabled=!deviceReady() ||
- legacy()?.routeAccepted!==true || d.outputArmed;
- if(muteBtn)muteBtn.disabled=!deviceOpen || !d.outputArmed;
+ "MAIN MONITOR ON · VERIFY SOUND"):
+ "CHOOSE CHANNEL IN · THEN MONITOR";
if(hardwareNote) {
- const evidence=protocol.diagnoseFirstSound?.(next,inputSelect.value);
- // Human-readable PCM stages from the ORIGINAL native callback only.
- // These values are NOT evidence that the DAC or speaker is audible.
- hardwareNote.textContent=evidence?
- evidence.readout+" · "+evidence.nextAction:
- "No verified hardware PCM readback available.";
+ const observed=protocol.diagnoseFirstSound?.(next,null);
+ hardwareNote.textContent=!deviceOpen?
+ "Audio I/O: choose the hardware input and actual listening/output device.":
+ (observed?observed.readout+" · ":"")+
+ "Choose IN on any mixer channel. Routing and monitoring use native readback.";
}
}
function installFirstSoundMenu() {
const menu=document.querySelector?.("#moreTools .more-tools-panel");
if(!menu || typeof document.createElement!=="function")return;
- const item=(tag,cls,label)=>{
- const el=document.createElement(tag);
- el.className=cls;el.textContent=label;
- if(tag==="button")el.type="button";
- return el;
- };
- const caption=item("span","more-tools-caption","REAL AUDIO · FIRST SOUND");
- const setup=item("button","tool","Audio Setup");
+ const caption=document.createElement("span");
+ caption.className="more-tools-caption";
+ caption.textContent="AUDIO · DEVICE SETTINGS";
+ const setup=document.createElement("button");
+ setup.className="tool";setup.type="button";setup.textContent="Audio I/O Settings";
+ setup.dataset.nativeAction="audioSetup";
setup.addEventListener("click",()=>{
- backend.emitEvent("arMixAction",{action:"audioSetup"});
- status("NATIVE: select actual ASIO/WASAPI input + output in Audio Setup.");
+ // Event may be intercepted by the existing mixer-io.js capture handler.
+ // When handled there, do not emit the old JUCE setup command.
+ if(window.__arMixOpenAudioIO){
+ window.__arMixOpenAudioIO("device");
+ status("Choose actual capture and playback devices in Audio I/O.");
+ }else status("Audio I/O panel unavailable; do not open a second setup wizard.");
});
- inputSelect=item("select","toolbar-select","");
- inputSelect.setAttribute("aria-label","JUCE physical input for CH1");
- inputSelect.addEventListener("change",()=>updateHardwarePanel(hardware));
- routeBtn=item("button","tool","Patch CH1");
- routeBtn.addEventListener("click",()=>{
- const d=hardware?.device,l=legacy();
- const epoch=safeNativeCounter(d?.epoch);
- const revision=safeNativeCounter(l?.routingRevision);
- const pin=Number(inputSelect?.value);
- if(!deviceReady()||inputSelect.value==="" ||
- epoch===null||revision===null||
- !Number.isInteger(pin)||!d.enabledInputs.includes(pin)){
- status("NATIVE: invalid input pin, epoch or route revision.");return;
- }
- pendingSourceId=++sourceSerial;
- routeBtn.disabled=true;
- backend.emitEvent("arMixAction",{
- action:"routingSourceSwitch",requestId:pendingSourceId,
- channel:0,mode:"MONO",left:pin,right:-1,
- deviceEpoch:epoch,revision
- });
- status("NATIVE: CH1 physical input patch pending real ACK.");
+ hardwareNote=document.createElement("span");
+ hardwareNote.className="more-tools-caption";
+ hardwareNote.style.whiteSpace="normal";
+ menu.append(caption,setup,hardwareNote);
+ updateHardwarePanel(hardware);
+ }
+ // Compact Audio I/O is native-only. The EXISTING JUCE AudioDeviceManager
+ // remains the single owner, via its already-tested inventory/Apply APIs.
+ // No AudioDeviceSelectorComponent popup or additional device callback in the
+ // normal workflow; the stock JUCE selector remains Advanced recovery.
+ let ioRoot=null,ioDraft=null,ioInventory=null,ioBusy=false,
+ ioMutePending=false,ioRequest="",ioCounter=0,ioMessage="";
+ const ioElement=(tag,cls,label)=>{
+ const n=document.createElement(tag);
+ if(cls)n.className=cls;if(label!==undefined)n.textContent=label;
+ if(tag==="button")n.type="button";
+ return n;
+ };
+ const ioType=()=>ioInventory?.types?.find(t=>t.name===ioDraft?.backend);
+ const ioField=(parent,id,label)=>{
+ const row=ioElement("div","ar-native-io-field");
+ const text=ioElement("label","",label);text.htmlFor=id;
+ const select=ioElement("select");select.id=id;row.append(text,select);
+ parent.appendChild(row);return select;
+ };
+ const ioPopulate=(select,items,current)=>{
+ const key=JSON.stringify(items);
+ if(select.dataset.options!==key){
+ select.dataset.options=key;
+ select.replaceChildren(...items.map(([value,label])=>new Option(label,value)));
+ }
+ if(items.some(x=>x[0]===current))select.value=current;
+ else select.value=items[0]?.[0]??"";
+ };
+ const actualIo=()=>ioInventory?.active||{};
+ const setIoDraftFromActual=()=>{
+ const a=actualIo(),types=ioInventory?.types||[];
+ const name=a.backend||types.find(t=>/ASIO/i.test(t.name))?.name||
+ types[0]?.name||"";
+ const selected=types.find(t=>t.name===name);
+ const capture=a.open&&a.backend===name?a.captureDevice:
+ selected?.inputs?.[0]||selected?.outputs?.[0]||"";
+ const playback=a.open&&a.backend===name?a.playbackDevice:
+ selected?.outputs?.[0]||"";
+ ioDraft={backend:name,captureDevice:capture,playbackDevice:playback,
+ sampleRate:a.open&&a.backend===name?Number(a.rate)||0:0,
+ bufferSize:a.open&&a.backend===name?Number(a.buffer)||0:0};
+ };
+ const ioSameDevice=()=>{
+ const a=actualIo(),d=ioDraft;
+ return !!(a?.open&&d&&a.backend===d.backend&&
+ a.captureDevice===d.captureDevice&&a.playbackDevice===d.playbackDevice);
+ };
+ const ioVirtualOutput=name=>/virtual|vb-audio|cable input|loopback|obs/i.test(name||"");
+ // A single VB-Cable's capture endpoint fed to its own playback endpoint
+ // is a self-loop, not a speaker monitor. Do not auto-arm this configuration.
+ const ioFeedbackLoop=(capture,playback)=>
+ /^cable output\b/i.test(capture||"") &&
+ /^cable input\b/i.test(playback||"") &&
+ /vb-audio virtual cable/i.test(capture||"") &&
+ /vb-audio virtual cable/i.test(playback||"");
+ function renderNativeIo(){
+ if(!ioRoot)return;
+ const a=actualIo(),d=ioDraft||{},types=ioInventory?.types||[],type=ioType();
+ const backendSelect=ioRoot.querySelector("#arNativeBackend");
+ const capture=ioRoot.querySelector("#arNativeCapture");
+ const playback=ioRoot.querySelector("#arNativePlayback");
+ const rate=ioRoot.querySelector("#arNativeRate");
+ const buffer=ioRoot.querySelector("#arNativeBuffer");
+ ioPopulate(backendSelect,types.map(t=>[t.name,t.name]),d.backend);
+ const inputs=type?.inputs||[],outputs=type?.outputs||[];
+ ioPopulate(capture,inputs.map(x=>[x,x]),d.captureDevice);
+ ioPopulate(playback,outputs.map(x=>[x,x]),d.playbackDevice);
+ capture.disabled=!!ioBusy||!type?.separate;
+ if(!type?.separate && outputs.length){
+ ioDraft.captureDevice=ioDraft.playbackDevice;
+ ioPopulate(capture,[[ioDraft.captureDevice,ioDraft.captureDevice]],ioDraft.captureDevice);
+ }
+ const same=ioSameDevice();
+ ioPopulate(rate,[["0","Auto / driver default"],
+ ...(same?(a.rates||[]).map(x=>[String(x),Number(x).toLocaleString()+" Hz"]):[])],
+ String(same?d.sampleRate:0));
+ ioPopulate(buffer,[["0","Auto / driver default"],
+ ...(same?(a.buffers||[]).map(x=>[String(x),x+" samples"]):[])],
+ String(same?d.bufferSize:0));
+ for(const select of [backendSelect,playback,rate,buffer])
+ select.disabled=!!ioBusy||!select.options.length;
+ const status=ioRoot.querySelector("#arNativeIoActual");
+ status.textContent=a.open?
+ "ACTIVE · "+a.backend+" · "+a.captureDevice+" → "+a.playbackDevice+
+ " · "+Math.round(Number(a.rate)||0)+" Hz / "+(a.buffer||0)+" samples"+
+ (a.outputMuted?" · MAIN muted":" · MAIN monitoring"):
+ "NO VERIFIED AUDIO DEVICE · choose driver, input and output";
+ const virtual=ioRoot.querySelector("#arNativeIoVirtual");
+ virtual.textContent=ioFeedbackLoop(d.captureDevice,d.playbackDevice)?
+ "LOOPBACK RISK: VB-Cable CABLE Output capture → CABLE Input playback returns to the SAME virtual cable. Select a different monitoring output before listening.":
+ ioVirtualOutput(d.playbackDevice)?
+ "Virtual playback endpoint: this may feed another app, not your headphones. Choose a physical speaker/headphone output to listen directly.":"";
+ const note=ioRoot.querySelector("#arNativeIoNote");
+ note.textContent=ioMessage||"Apply hardware once. Then select IN on any mixer channel.";
+ ioRoot.querySelector("#arNativeIoApply").disabled=ioBusy||
+ !d.backend||!d.captureDevice||!d.playbackDevice||!a||
+ !ioInventory?.types?.length;
+ ioRoot.querySelector("#arNativeIoApply").textContent=ioBusy?"Verifying…":"Apply Device";
+ }
+ function installNativeIoPanel(){
+ if(ioRoot)return;
+ ioRoot=ioElement("div","ar-native-io");ioRoot.id="arNativeAudioIo";
+ ioRoot.hidden=true;ioRoot.setAttribute("role","dialog");
+ ioRoot.setAttribute("aria-label","Audio hardware setup");
+ ioRoot.setAttribute("aria-modal","true");
+ const panel=ioElement("section","ar-native-io-panel");
+ const head=ioElement("header","ar-native-io-header");
+ head.append(ioElement("strong","","Audio I/O · Driver & Monitoring"));
+ const close=ioElement("button","ar-native-io-close","×");
+ close.setAttribute("aria-label","Close audio settings");
+ close.addEventListener("click",()=>{ioRoot.hidden=true;});
+ head.append(close);panel.append(head);
+ const body=ioElement("div","ar-native-io-body");
+ const readback=ioElement("div","ar-native-io-readback");readback.id="arNativeIoActual";
+ body.append(readback);
+ const backendSelect=ioField(body,"arNativeBackend","Audio driver");
+ const capture=ioField(body,"arNativeCapture","Capture / input");
+ const playback=ioField(body,"arNativePlayback","Playback / output");
+ backendSelect.addEventListener("change",()=>{
+ const type=(ioInventory?.types||[]).find(t=>t.name===backendSelect.value);
+ ioDraft={backend:backendSelect.value,
+ captureDevice:type?.separate?(type.inputs?.[0]||""):(type?.outputs?.[0]||""),
+ playbackDevice:type?.outputs?.[0]||"",sampleRate:0,bufferSize:0};
+ ioMessage="Device selection is a draft until Apply Device succeeds.";
+ renderNativeIo();
});
- armBtn=item("button","tool","Arm output");
- armBtn.addEventListener("click",()=>{
- if(!deviceReady()||legacy()?.routeAccepted!==true)return;
- const epoch=safeNativeCounter(hardware.device.epoch);
- const revision=safeNativeCounter(legacy().routingRevision);
- if(epoch===null||revision===null)return;
- backend.emitEvent("arMixAction",{action:"monitor",value:true,
- expectedEpoch:epoch,expectedRevision:revision});
- status("NATIVE: output ARM requested; awaiting JUCE ACK.");
+ capture.addEventListener("change",()=>{ioDraft.captureDevice=capture.value;renderNativeIo();});
+ playback.addEventListener("change",()=>{
+ ioDraft.playbackDevice=playback.value;
+ if(!ioType()?.separate)ioDraft.captureDevice=playback.value;
+ renderNativeIo();
+ });
+ const warning=ioElement("div","ar-native-io-notice");warning.id="arNativeIoVirtual";
+ body.append(warning);
+ const advanced=ioElement("details","");
+ const summary=ioElement("summary","","Advanced · sample rate & buffer");
+ advanced.append(summary);
+ const fields=ioElement("div","ar-native-io-body");
+ const rate=ioField(fields,"arNativeRate","Sample rate");
+ const buffer=ioField(fields,"arNativeBuffer","Buffer");
+ rate.addEventListener("change",()=>{ioDraft.sampleRate=Number(rate.value);});
+ buffer.addEventListener("change",()=>{ioDraft.bufferSize=Number(buffer.value);});
+ advanced.append(fields);body.append(advanced);
+ const actions=ioElement("div","ar-native-io-controls");
+ const apply=ioElement("button","primary","Apply Device");apply.id="arNativeIoApply";
+ apply.addEventListener("click",applyNativeAudioIO);
+ const recover=ioElement("button","","Driver Recovery…");
+ recover.title="Advanced JUCE selector — only for driver troubleshooting";
+ recover.addEventListener("click",()=>{
+ ioRoot.hidden=true;
+ backend.emitEvent("arMixAction",{action:"audioSetup"});
});
- muteBtn=item("button","tool","Mute output");
- muteBtn.addEventListener("click",()=>{
+ actions.append(apply,recover);body.append(actions);
+ const note=ioElement("div","ar-native-io-busy");note.id="arNativeIoNote";
+ body.append(note);panel.append(body);ioRoot.append(panel);
+ ioRoot.addEventListener("click",e=>{if(e.target===ioRoot)ioRoot.hidden=true;});
+ document.body.appendChild(ioRoot);
+ }
+ function openNativeAudioIO(){
+ installNativeIoPanel();
+ ioRoot.hidden=false;
+ ioMessage="Reading verified driver inventory…";
+ renderNativeIo();
+ backend.emitEvent("arMixAction",{action:"audioDeviceInventory"});
+ }
+ function applyNativeAudioIO(){
+ if(ioBusy||!ioDraft||!ioInventory)return;
+ const d=ioDraft;
+ if(!d.backend||!d.captureDevice||!d.playbackDevice){
+ ioMessage="Choose a valid input and playback device.";renderNativeIo();return;
+ }
+ ioBusy=true;
+ ioMessage="Applying driver selection · verify hardware ACK before using audio.";
+ if(hardware?.device?.outputArmed){
+ ioMutePending=true;
backend.emitEvent("arMixAction",{action:"monitor",value:false});
- status("NATIVE: output MUTE requested; awaiting JUCE ACK.");
+ }else submitDeviceApply();
+ renderNativeIo();
+ }
+ function submitDeviceApply(){
+ const d=ioDraft,a=actualIo(),same=ioSameDevice();
+ ioRequest="io-"+(++ioCounter);
+ backend.emitEvent("arMixAction",{action:"audioDeviceApply",
+ requestId:ioRequest,expectedDeviceGeneration:Number(a.deviceGeneration)||0,
+ config:{backend:d.backend,captureDevice:d.captureDevice,
+ playbackDevice:d.playbackDevice,
+ sampleRate:same?Number(d.sampleRate)||0:0,
+ bufferSize:same?Number(d.bufferSize)||0:0,
+ enabledInputs:same?a.enabledInputs:null,
+ enabledOutputs:same?a.enabledOutputs:null}});
+ }
+ // Same operator contract as Adobe/FL: every processing strip selects
+ // its own VERIFIED hardware input; output initially targets MAIN. No
+ // forced CH1, no draft graph, no separate Start or Arm button.
+ const inputAt=track=>{
+ const index=scope?.tracks?.indexOf(track)??-1;
+ return index>=0&&index<10?index:-1;
+ };
+ const routeRow=index=>(lastDryReadback?.acceptedRoute?.channels||
+ lastDryReadback?.preparedM4Route?.channels||[])[index];
+ const routeValue=r=>r?.mode==="MONO"?"MONO:"+r.left:
+ r?.mode==="STEREO"?"STEREO:"+r.left+":"+r.right:"None";
+ const hardwareInputs=()=>{
+ const d=hardware?.device;
+ if(!deviceReady()||!Array.isArray(d?.inputEndpoints))return [];
+ const enabled=new Set(d.enabledInputs);
+ return d.inputEndpoints.filter(p=>p?.active===true &&
+ Number.isInteger(p.port)&&enabled.has(p.port) && p.port>=0&&p.port<64);
+ };
+ let nativeSourcePending=null,nativeSourceSerial=1500000;
+ const signalSourceResult=message=>{status(message);};
+ const stopSource=error=>{
+ const p=nativeSourcePending;
+ nativeSourcePending=null;
+ const alreadyPatched=!!p?.accepted;
+ signalSourceResult((alreadyPatched?"INPUT CONNECTED · MONITOR OFF · ":"INPUT NEEDS VERIFICATION · ")+
+ error+". Inspect Audio I/O and native readback before trying again.");
+ controller?.subscribe(); // lost ACK or hotplug: never trust optimistic UI
+ };
+ const submitSource=()=>{
+ const p=nativeSourcePending,d=lastDryReadback||{};
+ if(!p||!deviceReady()||!d.ready||d.topologyFault||
+ String(d.epoch)!==String(p.epoch)||Number(d.revision)!==p.revision){
+ stopSource("device or route became stale");return;
+ }
+ p.phase="source";
+ backend.emitEvent("arMixAction",{
+ action:"routingSourceSwitch",requestId:p.id,channel:p.channel,
+ mode:p.mode,left:p.left,right:p.right,
+ deviceEpoch:p.epoch,revision:p.revision
});
- hardwareNote=item("span","more-tools-caption","Device not initialized");
- hardwareNote.style.whiteSpace="normal";
- menu.append(caption,setup,inputSelect,routeBtn,armBtn,muteBtn,hardwareNote);
- updateHardwarePanel(hardware);
+ signalSourceResult("CH "+(p.channel+1)+" · connecting verified hardware source…");
+ };
+ const monitorAfterSource=()=>{
+ const p=nativeSourcePending,d=p?.accepted;
+ if(!p||!d?.ready||!d.hasAcceptedRoute||d.topologyFault||
+ String(d.epoch)!==String(p.epoch)){
+ stopSource("output cannot be monitored until route is verified");return;
+ }
+ if(ioFeedbackLoop(hardware?.device?.captureDevice,hardware?.device?.playbackDevice)){
+ const channel=p.channel;
+ nativeSourcePending=null;
+ signalSourceResult("CH "+(channel+1)+" routed; MAIN monitoring stays OFF: input and output loop back through the same VB-Cable. Choose a physical output in Audio I/O.");
+ return;
+ }
+ if(!p.wasMonitoring){
+ const channel=p.channel;
+ nativeSourcePending=null;
+ signalSourceResult("CH "+(channel+1)+" → MAIN · input connected, output remains MUTED. Use the existing MAIN MUTE button to monitor.");
+ return;
+ }
+ p.phase="monitor";p.revision=Number(d.revision);
+ backend.emitEvent("arMixAction",{action:"monitor",value:true,
+ expectedEpoch:p.epoch,expectedRevision:p.revision});
+ signalSourceResult("CH "+(p.channel+1)+" · enabling MAIN monitoring…");
+ };
+ const chooseNativePhysicalInput=(track,value)=>{
+ const channel=inputAt(track),d=lastDryReadback||{};
+ if(channel<0)return false;
+ if(value==="__IO__"){openNativeAudioIO();return true;}
+ if(nativeSourcePending) {signalSourceResult("Previous input is still being verified.");return true;}
+ if(!deviceReady()||!d.ready||d.topologyFault||!d.active||
+ String(d.epoch)!==hardware.device.epoch){
+ signalSourceResult("Choose Audio I/O and a valid input/output device first.");
+ return true;
+ }
+ const mode=value==="None"?"NONE":value.startsWith("MONO:")?"MONO":
+ value.startsWith("STEREO:")?"STEREO":"INVALID";
+ if(mode==="INVALID"){signalSourceResult("Input unavailable on this hardware.");return true;}
+ const pins=hardwareInputs(),set=new Set(pins.map(p=>p.port));
+ const parts=value.split(":"),left=mode==="NONE"?-1:Number(parts[1]),
+ right=mode==="STEREO"?Number(parts[2]):-1;
+ if(mode==="MONO"&&(!set.has(left)||parts.length!==2) ||
+ mode==="STEREO"&&(!set.has(left)||!set.has(right)||left===right||parts.length!==3)){
+ signalSourceResult("This input is not enabled by the selected audio driver.");return true;
+ }
+ const before=routeRow(channel);
+ const unchanged=routeValue(before)===value;
+ if(unchanged)return true; // never change monitoring consent on no-op
+ const epoch=Number(d.epoch),revision=Number(d.revision);
+ if(!Number.isSafeInteger(epoch)||epoch<=0||!Number.isSafeInteger(revision)||revision<1){
+ signalSourceResult("Native route revision is not ready.");return true;
+ }
+ nativeSourcePending={id:++nativeSourceSerial,channel,mode,left,right,
+ epoch,revision,phase:"source",wasMonitoring:hardware.device.outputArmed===true};
+ const ticket=nativeSourcePending.id;
+ // One bounded operator-request timeout, never a realtime callback timer.
+ // Driver/ACK can be lost: force a new authoritative snapshot and unblock IN.
+ window.setTimeout(()=>{
+ if(nativeSourcePending?.id===ticket)
+ stopSource("native source/monitor ACK did not arrive");
+ },8000);
+ // Native M4 applies SAME-FORMAT source changes in 64-sample crossfade.
+ // Structural changes while monitored mute on the existing control thread
+ // before preparing the immutable graph, then resume only after real ACK.
+ if(hardware.device.outputArmed && !unchanged&&before?.mode!==mode){
+ nativeSourcePending.phase="mute";
+ backend.emitEvent("arMixAction",{action:"monitor",value:false,
+ expectedEpoch:epoch,expectedRevision:revision});
+ }else if(unchanged){
+ nativeSourcePending.accepted=d;
+ monitorAfterSource();
+ }else submitSource();
+ return true;
+ };
+ function nativeChannelOptions(track,type){
+ if(type==="input"){
+ if(inputAt(track)<0)return [["None","No input"]];
+ const pins=hardwareInputs(),list=[["None","No input"]];
+ for(const pin of pins)
+ list.push(["MONO:"+pin.port,"Mono · IN "+(pin.port+1)+" · "+(pin.label||"Input")]);
+ for(let i=0;i+1{
+ if(!verifiedM4()){
+ status("Select IN on a verified channel before adjusting the live mix.");
+ return false;
+ }
+ const channel=scope?.tracks?.indexOf(track)??-1;
+ if(channel<0||channel>=10){
+ status("No native ten-channel identity for this control.");
+ return false;
+ }
+ const epoch=Number(lastDryReadback.epoch),revision=Number(lastDryReadback.revision);
+ if(!Number.isSafeInteger(epoch)||epoch<=0||
+ !Number.isSafeInteger(revision)||revision<=0)return false;
+ backend.emitEvent("arMixParameter",{
+ parameter,channel:channel+1,value,routeEpoch:epoch,routeRevision:revision
+ });
+ return true; // request sent; not ACK or altered GUI model
+ };
+ const renderMeasuredM4=(live)=>{
+ if(flags.acceptedGraphConnected||!scope?.tracks)return;
+ const d=live?.dryRoutingLab||{};
+ lastDryReadback=d;
+ let changed=false;
+ // MAIN's approved MUTE is a real hardware output gate in native G0.
+ // Boot muted means MUTE lit; deliberately clicking it enables monitor.
+ const main=scope.master;
+ if(main&&typeof hardware?.device?.outputArmed==="boolean"){
+ const mute=!hardware.device.outputArmed || live.masterMute===true;
+ if(main.mute!==mute){main.mute=mute;changed=true;}
+ }
+ // Source identity must follow native accepted/prepared routes after ANY
+ // hotplug, restart or external patch: never leave old demo input names.
+ const rows=d.acceptedRoute?.channels||d.preparedM4Route?.channels||[];
+ if(d.ready && Array.isArray(rows)&&rows.length>=10)for(let i=0;i<10;++i){
+ const t=scope.tracks[i],r=rows[i];
+ if(!t||!r)continue;
+ const source=routeValue(r);
+ const output=r.main?"Master":"SOURCE ONLY (No Main)";
+ if(t.input!==source){t.input=source;changed=true;}
+ if(t.output!==output){t.output=output;changed=true;}
+ }
+ if(!verifiedM4()){
+ if(changed)scope.render?.();
+ return;
+ }
+ const controls=d.channelControls,peaksL=d.channelPeaksL,peaksR=d.channelPeaksR;
+ if(!Array.isArray(controls)||controls.length!==10)return;
+ for(let i=0;i<10;++i){
+ const t=scope.tracks[i],c=controls[i];
+ if(!t||!c)continue;
+ const f=Number(c.db),p=Number(c.pan);
+ if(Number.isFinite(f)&&Math.abs(t.level-f)>0.02){t.level=f;changed=true;}
+ if(Number.isFinite(p)&&Math.abs(t.pan-p)>0.02){t.pan=p;changed=true;}
+ if(typeof c.mute==="boolean"&&t.mute!==c.mute){t.mute=c.mute;changed=true;}
+ if(typeof c.solo==="boolean"&&t.solo!==c.solo){t.solo=c.solo;changed=true;}
+ }
+ const master=scope.master;
+ const masterDb=Number(live?.masterDb);
+ if(master&&Number.isFinite(masterDb)&&masterDb>=-90&&masterDb<=12&&
+ Math.abs(master.level-masterDb)>0.02){master.level=masterDb;changed=true;}
+ if(master&&typeof live?.masterMute==="boolean"&&
+ master.mute!==live.masterMute){master.mute=live.masterMute;changed=true;}
+ // Render only on ACCEPTED control state changes, never at 12Hz. The
+ // WebView compositor is not a part of the realtime audio callback.
+ if(changed)scope.render?.();
+ const timestamp=performance.now();
+ const paint=(track,left,right)=>{
+ const root=document.querySelector('.strip[data-id="'+track?.id+'"]');
+ if(!root)return;
+ for(const [side,peak] of [["left",left],["right",right]]){
+ const fill=root.querySelector('.meter-fill.'+side);
+ if(!fill||!Number.isFinite(peak)||peak<0)continue;
+ const db=peak===0?-90:20*Math.log10(peak);
+ scope.displayMeterDbfs?.(fill,Math.max(-90,Math.min(6,db)),timestamp,
+ "m4:"+track.id+":"+side);
+ }
+ };
+ if(Array.isArray(peaksL)&&Array.isArray(peaksR)&&peaksL.length===10&&peaksR.length===10)
+ for(let i=0;i<10;++i)paint(scope.tracks[i],Number(peaksL[i]),Number(peaksR[i]));
+ paint(master,Number(d.peakL),Number(d.peakR));
+ };
function onNativeReadback(next) {
+ const oldPortSignature=hardware?.device?
+ JSON.stringify([hardware.device.epoch,hardware.device.inputEndpoints,hardware.device.playbackDevice]):"";
updateHardwarePanel(next);
+ if(nativeSourcePending && next?.device?.epoch!==String(nativeSourcePending.epoch))
+ stopSource("audio interface changed during selection");
+ const newPortSignature=next?.device?
+ JSON.stringify([next.device.epoch,next.device.inputEndpoints,next.device.playbackDevice]):"";
+ // Only re-render the full mixer when real hardware inventory changes,
+ // never on each 12Hz meter or transport update.
+ if(oldPortSignature!==newPortSignature && !nativeSourcePending)
+ scope?.render?.();
const caps=next?.graph?.capabilities;
const nativeAdmitted=next.admitted && caps?.callbackOwnsChannelIds===true;
if (!nativeAdmitted) {
flags.productionCallbackLive=false;flags.acceptedGraphConnected=false;
lastPaintedSignature="";
stopDemo();
- status("NATIVE G0 · PATCH CH1/ARM tersedia pada device terverifikasi; kontrol ChannelId/WIRE menunggu PCM native.");
+ status("NATIVE MIXER · pilih IN pada channel mana saja; level/pan/mute/solo menggunakan engine audio.");
return;
}
// Control readback may change at the SAME structural graph revision.
@@ -317,37 +678,114 @@
}
}
});
+ backend.addEventListener("arMixAudioDeviceInventory",data=>{
+ if(!data||!Array.isArray(data.types))return;
+ ioInventory=data;
+ if(!ioDraft||!ioBusy)setIoDraftFromActual();
+ if(ioRoot)renderNativeIo();
+ });
+ backend.addEventListener("arMixAudioDeviceApplyAck",ack=>{
+ if(!ioBusy||ack?.requestId!==ioRequest)return;
+ ioBusy=false;ioMutePending=false;ioRequest="";
+ if(ioInventory&&ack?.active)ioInventory.active=ack.active;
+ if(ack?.ok===true){
+ setIoDraftFromActual();
+ ioMessage="Device verified. Select IN on any channel; monitoring is handled automatically.";
+ controller?.subscribe();
+ }else ioMessage="Device rejected · "+String(ack?.error||"Check audio driver and retry");
+ renderNativeIo();
+ });
+ backend.addEventListener("arMixAudioArmAck",ack=>{
+ if(!ioMutePending)return;
+ ioMutePending=false;
+ if(ack?.ok===true&&ack.armed===false)submitDeviceApply();
+ else {ioBusy=false;ioMessage="Cannot safely switch device while output is active.";renderNativeIo();}
+ });
backend.addEventListener("arMixConsoleSnapshot", snapshot=>controller.onSnapshot(snapshot));
backend.addEventListener("arMixConsoleAck", ack=>controller.onAck(ack));
- backend.addEventListener("arMixSourceSwitchAck", ack=>{
- if(!pendingSourceId||ack?.requestId!==pendingSourceId)return;
- pendingSourceId=0;
- if(ack.ok===true) {
- status("NATIVE: CH1 PATCH accepted by JUCE; validating later readback.");
- controller.subscribe();
- }else status("NATIVE PATCH REJECTED: "+(ack?.error||"stale physical route"));
- updateHardwarePanel(hardware);
+ backend.addEventListener("arMixStatus",live=>renderMeasuredM4(live));
+ backend.addEventListener("arMixM4ControlAck",ack=>{
+ if(ack?.ok!==true)
+ status("Control rejected: hardware/route changed; original mix retained.");
});
- backend.addEventListener("arMixAudioArmAck", ack=>{
- if(ack?.ok===true){
- status(ack.armed?"NATIVE: user ARM accepted; checking real PCM.":
- "NATIVE: output muted.");
- controller.subscribe();
- }else status("NATIVE ARM REJECTED: "+(ack?.error||"device not ready"));
+ backend.addEventListener("arMixSourceSwitchAck",ack=>{
+ const p=nativeSourcePending;
+ if(!p||p.phase!=="source"||Number(ack?.requestId)!==p.id||
+ Number(ack?.channel)!==p.channel)return;
+ const next=ack?.state||{},row=next.acceptedRoute?.channels?.[p.channel];
+ if(ack.ok!==true||!next.ready||next.topologyFault||
+ String(next.epoch)!==String(p.epoch)||
+ routeValue(row)!==(p.mode==="NONE"?"None":
+ p.mode+":"+p.left+(p.mode==="STEREO"?":"+p.right:""))){
+ stopSource(String(ack?.error||"Native patch ACK/readback mismatch"));return;
+ }
+ lastDryReadback=next;
+ p.accepted=next;
+ if(scope?.tracks?.[p.channel]){
+ scope.tracks[p.channel].input=routeValue(row);
+ scope.render?.();
+ }
+ const hasInput=(next.acceptedRoute?.channels||[])
+ .some(r=>r.mode==="MONO"||r.mode==="STEREO");
+ if(!hasInput && p.mode==="NONE"){
+ nativeSourcePending=null;
+ signalSourceResult("No input selected · MAIN remains safe.");
+ }else if(p.wasMonitoring&&hardware?.device?.outputArmed){
+ nativeSourcePending=null;
+ signalSourceResult("CH "+(p.channel+1)+" · live source switched.");
+ }else monitorAfterSource();
+ });
+ backend.addEventListener("arMixAudioArmAck",ack=>{
+ const p=nativeSourcePending;
+ if(!p||!(p.phase==="mute"||p.phase==="monitor"))return;
+ const valid=ack?.ok===true&&Number(ack.deviceEpoch)===p.epoch&&
+ (p.phase==="mute"?ack.armed===false:ack.armed===true);
+ if(!valid){stopSource(String(ack?.error||"Monitor gate rejected"));return;}
+ if(hardware?.device)hardware.device.outputArmed=!!ack.armed;
+ if(p.phase==="mute")submitSource();
+ else {
+ nativeSourcePending=null;
+ signalSourceResult("CH "+(p.channel+1)+
+ " → MAIN · monitoring active. Verify audible output on the selected device.");
+ }
});
}
const nativeHooks=Object.freeze({
enabled:connected,
+ channelOptions:nativeChannelOptions,
consumeField(event) {
if (!connected)return false;
const el=event.target,field=el?.dataset?.field;
if (!field)return false;
const t=scope?.findTrack?.(el) || null;
if (!t)return true;
+ if (!flags.acceptedGraphConnected && field==="input") {
+ chooseNativePhysicalInput(t,el.value);
+ return true;
+ }
+ if (!flags.acceptedGraphConnected && field==="output") {
+ if(t===scope?.master || el.value==="__IO__")openNativeAudioIO();
+ else status("Internal output routing requires a verified native MAIN path.");
+ return true;
+ }
if (!flags.acceptedGraphConnected) {
- if (field==="level")el.value=String(t.level);
- else if (field==="pan")el.value=String(t.pan);
- status("NATIVE: ChannelId PCM not admitted; control unchanged");
+ // Drag may move only the physical fader thumb. On release, send one
+ // real native M4 parameter with exact epoch/revision; the next real
+ // engine readback owns the displayed value.
+ const numeric=Number(el.value);
+ const pan=el.dataset.panKeyboard==="true"||el.dataset.panAltPointer==="true"||
+ Math.abs(numeric)>12?numeric:0;
+ if(event.type==="change"&&t===scope.master){
+ if(field==="level"&&Number.isFinite(numeric))
+ backend.emitEvent("arMixParameter",{parameter:"masterGain",value:numeric,channel:-1});
+ }else if(event.type==="change"&&field==="level"&&Number.isFinite(numeric))
+ m4Parameter(t,"faderDb",numeric);
+ else if(event.type==="change"&&field==="pan"&&Number.isFinite(pan))
+ m4Parameter(t,"pan",pan);
+ if(!verifiedM4()&&t!==scope.master){
+ if(field==="level")el.value=String(t.level);
+ else if(field==="pan")el.value=String(t.pan);
+ }
return true;
}
// During a native pointer drag move the approved fader *cap* only.
@@ -387,6 +825,29 @@
if (["wireExpand","wireSource","wireRoute","editIdentity","rename"].includes(action))
return !["wireExpand","wireSource","wireRoute"].includes(action);
if (action==="mute"||action==="solo") {
+ if(!flags.acceptedGraphConnected) {
+ if(t===scope?.master&&action==="mute"){
+ const armed=hardware?.device?.outputArmed===true;
+ if(!armed&&!verifiedM4()){
+ status("Connect a verified IN on any channel before enabling MAIN.");
+ return true;
+ }
+ if(!armed&&ioFeedbackLoop(hardware?.device?.captureDevice,
+ hardware?.device?.playbackDevice)){
+ status("MAIN monitoring refused: VB-Cable capture/playback form a feedback loop.");
+ return true;
+ }
+ // MAIN mute is the EXISTING visible physical monitor gate.
+ // One operator gesture, no new ARM/START UI or hidden auto-arm.
+ backend.emitEvent("arMixAction",{action:"monitor",value:!armed,
+ ...(armed?{}:{
+ expectedEpoch:Number(lastDryReadback.epoch),
+ expectedRevision:Number(lastDryReadback.revision)
+ })});
+ return true;
+ }
+ m4Parameter(t,action,!t[action]);return true;
+ }
const key=action==="mute"?"SET_MUTE":"SET_SOLO";
intent(key,t,{value:!t[action],enabled:!t[action]});return true;
}
@@ -439,8 +900,15 @@
consumeUndo() {if (!connected)return false;status("NATIVE: WIRE undo requires accepted native transaction");return true;},
consumeDoubleClick(event,t) {
if (!connected)return false;
- if (event.target.classList.contains("fader"))intent("SET_FADER",t,{valueDb:0});
- else if(event.target.classList.contains("center-pan"))intent("SET_PAN",t,{value:0});
+ if (event.target.classList.contains("fader")) {
+ if(flags.acceptedGraphConnected)intent("SET_FADER",t,{valueDb:0});
+ else if(t===scope?.master)
+ backend.emitEvent("arMixParameter",{parameter:"masterGain",value:0,channel:-1});
+ else m4Parameter(t,"faderDb",0);
+ } else if(event.target.classList.contains("center-pan")) {
+ if(flags.acceptedGraphConnected)intent("SET_PAN",t,{value:0});
+ else m4Parameter(t,"pan",0);
+ }
else status("NATIVE: identity editor unavailable until native ACK contract");
return true;
},
@@ -460,13 +928,13 @@
value:descriptor,configurable:false,writable:false
});
if (!connected)return;
- // Disable physical control gestures while G0 has no accepted ChannelId graph.
- // Presentation-only bank/selection remains available.
+ // G0 with a VERIFIED M4 native route is a real mixer: never block its
+ // fader just because universal ChannelId migration is not yet admitted.
document.addEventListener("pointerdown",event=>{
- if (flags.acceptedGraphConnected) return;
- if (!event.target.closest?.(".fader-box,.center-pan")) return;
+ if(flags.acceptedGraphConnected||verifiedM4())return;
+ if(!event.target.closest?.(".fader-box,.center-pan"))return;
event.preventDefault();event.stopImmediatePropagation();
- status("NATIVE G0: physical gain/pan unavailable until engine graph admission");
+ status("Choose a verified hardware IN before adjusting the mixer.");
},true);
// Reference-only buttons outside strips must not mutate fake Show/FX state.
document.addEventListener("click",event=>{
@@ -480,6 +948,10 @@
// finishFaderPointer via build_approved_native_gui.py hook. A later
// window.pointerup listener would run after that handler clears the gesture.
const ready=()=>{
+ // Contract/protocol tests deliberately use a minimal DOM without
+ // createElement. Production WebView always provides it; publishing the
+ // native transport must not depend on constructing the settings overlay.
+ if(typeof document.createElement==="function")installNativeIoPanel();
installFirstSoundMenu();
updateHardwarePanel(null);
stopDemo();
diff --git a/web/approved-native-io.css b/web/approved-native-io.css
new file mode 100644
index 000000000..48d5e44ad
--- /dev/null
+++ b/web/approved-native-io.css
@@ -0,0 +1,26 @@
+/* SPDX-License-Identifier: AGPL-3.0-only
+ Native-only Audio I/O controls. ONE approved /preview/ mixer skin is retained.
+ The panel runs entirely on the JUCE message thread; no DSP/JS WebAudio. */
+.ar-native-io-open{min-width:75px;white-space:nowrap}
+.ar-native-monitor{min-width:92px;white-space:nowrap}
+.ar-native-monitor[data-on="true"]{color:#a3e8ca;border-color:#4a8f78}
+.ar-native-io[hidden]{display:none!important}
+.ar-native-io{position:fixed;inset:0;z-index:999;display:flex;align-items:flex-start;justify-content:center;padding:clamp(25px,9vh,98px) 16px 16px;background:rgba(1,8,12,.67)}
+.ar-native-io-panel{width:min(550px,100%);max-height:min(690px,86vh);overflow:auto;color:#d4e6e9;background:#122630;border:1px solid #436574;border-radius:9px;box-shadow:0 18px 50px #0008;font:12px 'Inter','Segoe UI',Arial,sans-serif}
+.ar-native-io-header{display:flex;align-items:center;justify-content:space-between;padding:12px 15px;border-bottom:1px solid #31515c}
+.ar-native-io-header strong{font-size:13px;font-weight:600;letter-spacing:.02em}
+.ar-native-io-close{border:1px solid #42616c;border-radius:5px;color:inherit;background:#213940;min-width:28px;height:27px;cursor:pointer}
+.ar-native-io-body{padding:14px 16px;display:grid;gap:10px}
+.ar-native-io-field{display:grid;grid-template-columns:114px minmax(0,1fr);align-items:center;gap:10px}
+.ar-native-io-field label{color:#99b6c1;font-size:11px}
+.ar-native-io-field select{width:100%;height:32px;min-width:0;border:1px solid #416878;border-radius:5px;padding:0 8px;color:#e6f5f6;background:#1a3440;font:inherit}
+.ar-native-io-readback{padding:9px 11px;border:1px solid #345663;background:#10232c;border-radius:5px;line-height:1.55;color:#bcd1d9}
+.ar-native-io-notice{color:#edc78d;line-height:1.5;font-size:11px}
+.ar-native-io-controls{display:flex;align-items:center;flex-wrap:wrap;gap:9px;margin-top:4px}
+.ar-native-io-controls button{border:1px solid #557884;border-radius:5px;color:#e5f6f5;background:#24424c;padding:8px 12px;font:inherit;cursor:pointer}
+.ar-native-io-controls button.primary{background:#257d91;border-color:#4b9bac;color:white}
+.ar-native-io-controls button:disabled{opacity:.45;cursor:not-allowed}
+.ar-native-io-busy{color:#a6c6cf;flex:1;line-height:1.4;font-size:11px}
+.ar-native-io summary{cursor:pointer;color:#a8cbd7}
+@media(max-height:650px){.ar-native-io{padding:12px}.ar-native-io-panel{max-height:calc(100vh - 24px)}}
+@media(max-width:500px){.ar-native-io-field{grid-template-columns:1fr;gap:3px}}