From ac75bd20c2951e4e8bc93aaaa0f674f3a9df6ea6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 31 Oct 2026 09:44:50 +0700 Subject: [PATCH 01/13] feat(audio): JUCE native custom device inventory, guarded apply, readback and muted rollback --- src/Main.cpp | 252 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 230 insertions(+), 22 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 253425ace..e23768b06 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -745,6 +745,214 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr browser_.emitEventIfBrowserIsVisible ("arMixScanProgress", catalog_.progress()); } + + // DEVICE1: the WebView2 matrix is the operator GUI; JUCE remains the + // single device owner. No hardware calls ever run from the audio callback. + juce::var currentDeviceSnapshot() const + { + // This readback is used for UI and ACK, never to claim that a staged + // select value is already open/playing on hardware. + auto o=std::make_unique(); + auto& manager=const_cast(engine_).devices(); + juce::AudioDeviceManager::AudioDeviceSetup setup; + manager.getAudioDeviceSetup(setup); + auto* device=manager.getCurrentAudioDevice(); + o->setProperty("backend",manager.getCurrentAudioDeviceType()); + o->setProperty("captureDevice",setup.inputDeviceName); + o->setProperty("playbackDevice",setup.outputDeviceName); + o->setProperty("rate",device!=nullptr&&device->isOpen()?device->getCurrentSampleRate():0.0); + o->setProperty("buffer",device!=nullptr&&device->isOpen()?device->getCurrentBufferSizeSamples():0); + o->setProperty("open",device!=nullptr&&device->isOpen()); + o->setProperty("outputMuted",engine_.isOutputMuted()); + o->setProperty("deviceGeneration",engine_.status().getProperty("deviceGeneration",0)); + juce::Array inputNames,outputNames,inputPins,outputPins,rates,buffers; + if(device!=nullptr&&device->isOpen()) { + const auto inputs=device->getInputChannelNames(); + const auto outputs=device->getOutputChannelNames(); + const auto inputMask=device->getActiveInputChannels(); + const auto outputMask=device->getActiveOutputChannels(); + for(int i=0;igetAvailableSampleRates()) rates.add(value); + for(const auto value:device->getAvailableBufferSizes()) buffers.add(value); + o->setProperty("hasControlPanel",device->hasControlPanel()); + }else o->setProperty("hasControlPanel",false); + o->setProperty("inputNames",juce::var(inputNames)); + o->setProperty("outputNames",juce::var(outputNames)); + o->setProperty("enabledInputs",juce::var(inputPins)); + o->setProperty("enabledOutputs",juce::var(outputPins)); + o->setProperty("rates",juce::var(rates)); + o->setProperty("buffers",juce::var(buffers)); + return juce::var(o.release()); + } + + void applyCustomAudioDevice(const juce::var& args) + { + // Synchronous manager operations stay on JUCE's established message + // thread. A vendor driver may block; never pretend JS async fixes it. + const auto id=args.getProperty("requestId",{}).toString().substring(0,64); + const auto oldGeneration=engine_.status().getProperty("deviceGeneration",0); + auto send=[&](bool ok,const juce::String& state,const juce::String& error) + { + auto ack=std::make_unique(); + ack->setProperty("requestId",id); + ack->setProperty("ok",ok); + ack->setProperty("state",state); + ack->setProperty("error",error); + ack->setProperty("active",currentDeviceSnapshot()); + ack->setProperty("outputMuted",engine_.isOutputMuted()); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible("arMixAudioDeviceApplyAck",juce::var(ack.release())); + }; + if(id.isEmpty()||id.length()>64||!(args.getProperty("expectedDeviceGeneration",{}).isDouble()|| + args.getProperty("expectedDeviceGeneration",{}).isInt()|| + args.getProperty("expectedDeviceGeneration",{}).isInt64())|| + static_cast(args.getProperty("expectedDeviceGeneration",{})) != + static_cast(oldGeneration)) + return send(false,"REJECTED","Stale device generation; refresh DEVICE / DRIVER"); + if(nativeShowBusy_||studioBackupBusy_||engine_.isGraphSwitchPending()|| + engine_.independentClockActive()||engine_.hasTemporaryDiagnosticDevice()|| + !engine_.allOutputsDisarmed()) + return send(false,"REJECTED", + "MUTE MAIN and secondary output; finish Show/FX/diagnostic/clock transition first"); + const auto config=args.getProperty("config",{}); + if(!config.isObject())return send(false,"REJECTED","Missing device configuration"); + const auto typeName=config.getProperty("backend",{}).toString(); + const auto capture=config.getProperty("captureDevice",{}).toString(); + const auto playback=config.getProperty("playbackDevice",{}).toString(); + if(typeName.isEmpty()||capture.isEmpty()||playback.isEmpty()|| + typeName.length()>160||capture.length()>250||playback.length()>250) + return send(false,"REJECTED","Choose actual capture and playback devices"); + auto& manager=engine_.devices(); + juce::AudioIODeviceType* selectedType=nullptr; + for(auto* type:manager.getAvailableDeviceTypes()) + if(type!=nullptr&&type->getTypeName()==typeName)selectedType=type; + if(selectedType==nullptr)return send(false,"REJECTED","Audio backend is not installed"); + // Do not let JS submit arbitrary names or combine unmatched ASIO devices. + const auto namesIn=selectedType->getDeviceNames(true); + const auto namesOut=selectedType->getDeviceNames(false); + if(!namesIn.contains(capture)||!namesOut.contains(playback)|| + (!selectedType->hasSeparateInputsAndOutputs()&&capture!=playback)) + return send(false,"REJECTED","Device names or duplex pairing are not reported by JUCE"); + auto sample=config.getProperty("sampleRate",{}), period=config.getProperty("bufferSize",{}); + if(!(sample.isInt()||sample.isDouble()||sample.isInt64())|| + !(period.isInt()||period.isDouble()||period.isInt64())) + return send(false,"REJECTED","Rate and buffer must be numeric or AUTO (0)"); + const double rate=static_cast(sample); + const double block=static_cast(period); + if(!std::isfinite(rate)||!std::isfinite(block)|| + (rate!=0&&(rate<8000||rate>384000))|| + (block!=0&&(block<16||block>8192||std::floor(block)!=block))) + return send(false,"REJECTED","Invalid device sample rate or buffer size"); + const bool unchangedDevice=manager.getCurrentAudioDeviceType()==typeName; + juce::AudioDeviceManager::AudioDeviceSetup before; + manager.getAudioDeviceSetup(before); + const auto previousType=manager.getCurrentAudioDeviceType(); + const bool sameEndpoint=unchangedDevice&&before.inputDeviceName==capture + &&before.outputDeviceName==playback; + juce::AudioDeviceManager::AudioDeviceSetup candidate=before; + candidate.inputDeviceName=capture; + candidate.outputDeviceName=playback; + candidate.sampleRate=rate; + candidate.bufferSize=static_cast(block); + // Pins are explicit only when candidate is the CURRENT active device. + // Other device pin labels do not exist until JUCE actually opens it. + // Its first APPLY uses safe defaults; then users refine real pin masks. + const auto pinInput=config.getProperty("enabledInputs",{}); + const auto pinOutput=config.getProperty("enabledOutputs",{}); + if(sameEndpoint && pinInput.isArray() && pinOutput.isArray()) { + const auto* active=manager.getCurrentAudioDevice(); + if(active==nullptr||!active->isOpen()) + return send(false,"REJECTED","Current device is not open; refresh"); + const auto inCount=juce::jmin(64,active->getInputChannelNames().size()); + const auto outCount=juce::jmin(64,active->getOutputChannelNames().size()); + auto parsePins=[](const juce::var& values,int limit,juce::BigInteger& mask)->bool { + const auto* array=values.getArray(); + if(array==nullptr||array->size()>64)return false; + for(const auto& p:*array) { + if(!(p.isInt()||p.isInt64()))return false; + const int index=static_cast(p); + if(index<0||index>=limit||mask[index])return false; + mask.setBit(index); + } + return true; + }; + juce::BigInteger inMask,outMask; + if(!parsePins(pinInput,inCount,inMask)||!parsePins(pinOutput,outCount,outMask)|| + inMask.countNumberOfSetBits()<1||outMask.countNumberOfSetBits()<2) + return send(false,"REJECTED","Choose >=1 verified capture and >=2 playback pins"); + candidate.useDefaultInputChannels=false; + candidate.useDefaultOutputChannels=false; + candidate.inputChannels=inMask; + candidate.outputChannels=outMask; + }else { + candidate.useDefaultInputChannels=true; + candidate.useDefaultOutputChannels=true; + } + const auto* active=manager.getCurrentAudioDevice(); + if(sameEndpoint && active!=nullptr && active->isOpen()) { + if(rate>0&&!active->getAvailableSampleRates().contains(rate)) + return send(false,"REJECTED","Requested sample rate not reported by selected device"); + if(block>0&&!active->getAvailableBufferSizes().contains(static_cast(block))) + return send(false,"REJECTED","Requested buffer size not reported by selected device"); + } + + // Full device transaction: never enable audio during an intermediate + // backend auto-open, and never persist an unverified partial selection. + const auto start=monotonicMilliseconds(); + engine_.beginManualAudioSetup(); + if(!unchangedDevice)manager.setCurrentAudioDeviceType(typeName,false); + auto error=manager.getCurrentAudioDeviceType()==typeName + ?manager.setAudioDeviceSetup(candidate,true) + :juce::String("Selected audio backend could not be opened"); + juce::AudioDeviceManager::AudioDeviceSetup actual; + manager.getAudioDeviceSetup(actual); + auto* opened=manager.getCurrentAudioDevice(); + if(error.isEmpty()&&(opened==nullptr||!opened->isOpen()|| + manager.getCurrentAudioDeviceType()!=typeName|| + actual.inputDeviceName!=capture||actual.outputDeviceName!=playback|| + (rate>0&&std::abs(actual.sampleRate-rate)>1.0)|| + (block>0&&actual.bufferSize!=static_cast(block))|| + (!candidate.useDefaultInputChannels&&actual.inputChannels!=candidate.inputChannels)|| + (!candidate.useDefaultOutputChannels&&actual.outputChannels!=candidate.outputChannels))) + error="Driver readback mismatch; device setting was not accepted"; + if(error.isEmpty()&&!engine_.finishManualAudioSetup()) + error="Device opened but direct safe production session was rejected"; + if(error.isEmpty()) { + deviceSettingsDirty_=true; + directRestore_.cancel(); + diagnostics_.record("CUSTOM_AUDIO_APPLY_OK", + typeName+" | "+juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); + return send(true,"ACCEPTED_MUTED",{}); + } + // One rollback, never blind default endpoint fallback, no auto-unmute. + engine_.beginManualAudioSetup(); + if(manager.getCurrentAudioDeviceType()!=previousType&&previousType.isNotEmpty()) + manager.setCurrentAudioDeviceType(previousType,false); + const auto restored=previousType.isNotEmpty()&& + manager.getCurrentAudioDeviceType()==previousType&& + manager.setAudioDeviceSetup(before,true).isEmpty(); + juce::AudioDeviceManager::AudioDeviceSetup checked; + manager.getAudioDeviceSetup(checked); + const bool verified=restored&& + checked.inputDeviceName==before.inputDeviceName&& + checked.outputDeviceName==before.outputDeviceName&& + checked.inputChannels==before.inputChannels&& + checked.outputChannels==before.outputChannels&& + manager.getCurrentAudioDevice()!=nullptr&& + manager.getCurrentAudioDevice()->isOpen()&&engine_.finishManualAudioSetup(); + diagnostics_.record("CUSTOM_AUDIO_APPLY_FAIL",error+" | rollback="+ + (verified?"RESTORED":"RECOVERY_REQUIRED")+" | "+ + juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); + send(false,verified?"RESTORED_MUTED":"RECOVERY_REQUIRED",error); + } + void showDeviceSetup() { diagnostics_.record ("SETUP", "Open audio device setup"); @@ -1603,34 +1811,34 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } else if (action == "audioDeviceInventory") { - // Enumeration only on explicit user request, on the JUCE message thread. - // Never reopen an audio endpoint or change the routing epoch here. + // Explicit inventory request: no device re-open, no output arm. auto inventory=std::make_unique(); juce::Array types; auto& manager=engine_.devices(); - for (auto* type : manager.getAvailableDeviceTypes()) - { - if (type == nullptr) continue; - // Explicit user-triggered enumeration on the JUCE message - // thread. Inactive WASAPI/DirectSound/ASIO types may not - // have been scanned yet; listing getDeviceNames alone can - // misleadingly show NO devices. Never scan in audio RT. + for(auto* type:manager.getAvailableDeviceTypes()) { + if(type==nullptr)continue; type->scanForDevices(); auto item=std::make_unique(); - item->setProperty ("name", type->getTypeName()); - item->setProperty ("active", type->getTypeName() == manager.getCurrentAudioDeviceType()); - juce::Array inputs, outputs; - for (const auto& label : type->getDeviceNames (true)) inputs.add (label); - for (const auto& label : type->getDeviceNames (false)) outputs.add (label); - item->setProperty ("inputs", juce::var (inputs)); - item->setProperty ("outputs", juce::var (outputs)); - types.add (juce::var (item.release())); + item->setProperty("name",type->getTypeName()); + item->setProperty("active",type->getTypeName()==manager.getCurrentAudioDeviceType()); + item->setProperty("separate",type->hasSeparateInputsAndOutputs()); + juce::Array inputs,outputs; + for(const auto& n:type->getDeviceNames(true))inputs.add(n); + for(const auto& n:type->getDeviceNames(false))outputs.add(n); + item->setProperty("inputs",juce::var(inputs)); + item->setProperty("outputs",juce::var(outputs)); + types.add(juce::var(item.release())); } - inventory->setProperty ("types", juce::var (types)); - inventory->setProperty ("currentType", manager.getCurrentAudioDeviceType()); - if (browser_.loaded) - browser_.emitEventIfBrowserIsVisible ("arMixAudioDeviceInventory", - juce::var (inventory.release())); + inventory->setProperty("types",juce::var(types)); + inventory->setProperty("currentType",manager.getCurrentAudioDeviceType()); + inventory->setProperty("active",currentDeviceSnapshot()); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible("arMixAudioDeviceInventory", + juce::var(inventory.release())); + } + else if (action == "audioDeviceApply") + { + applyCustomAudioDevice(args); } else if (action == "audioSetup") { From a43bac4e1e68aa7780a99e06d09016df9cfc3f51 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 31 Oct 2026 09:46:00 +0700 Subject: [PATCH 02/13] feat(audio): custom device driver, endpoint, sample and pin controls in existing IO matrix --- web/mixer-io.js | 265 +++++++++++++++++++++++++++++++++++++----------- 1 file changed, 203 insertions(+), 62 deletions(-) diff --git a/web/mixer-io.js b/web/mixer-io.js index 3144341ff..6bacb2483 100644 --- a/web/mixer-io.js +++ b/web/mixer-io.js @@ -8,6 +8,8 @@ if(!mixer||!host)return; let mode='FX', lastStatus={}, deviceInventory=null, ioTab='device', lastSignature='', focusedInput=2; let monitorSendsExpanded=false; + // DEVICE1: staged selections are UI-only; only positive native ACK changes active hardware. + let deviceDraft=null,deviceBusy=false,deviceNote='',deviceRequest='',deviceRequestSeq=0,lastDeviceRefresh=0; // Pending SOURCE ACK is a UI projection only; monitor.js owns the native route. let quickSourcePending=null; const el=id=>document.getElementById(id); @@ -41,7 +43,7 @@ sofControls.hidden=true;toolbar.appendChild(sofControls); const overlay=node('div','arIOOverlay'); overlay.id='arIOOverlay';overlay.hidden=true; - overlay.innerHTML=''; + overlay.innerHTML=''; document.body.appendChild(overlay); // G3: ONE floating inspector follows the selected source/AUX, no new // DSP graph, no heavyweight matrix, no layout shifts in the MIX strips. @@ -276,7 +278,7 @@ if(Number.isInteger(channel)&&channel>=0&&channel<10)focusedInput=channel; if(overlay.hidden)advancedMatrixOpen=false; overlay.hidden=false;lastSignature='';refreshIO(); - if(isNative())backend.emitEvent('arMixAction',{action:'audioDeviceInventory'}); + if(isNative())deviceRefresh(); if(Number.isInteger(channel))overlay.querySelector('[data-io-quick-row="'+channel+'"]')?.scrollIntoView({block:'nearest'}); } window.__arMixOpenAudioIO=openIO; @@ -660,6 +662,145 @@ 'MONITOR needs two verified unused output pins.'); lastSignature='';refresh(); } + + const deviceType=name=>(deviceInventory?.types||[]).find(t=>t.name===name); + const deviceSameEndpoint=d=>!!d&&!!deviceInventory?.active?.open&& + deviceInventory.active.backend===d.backend&& + deviceInventory.active.captureDevice===d.captureDevice&& + deviceInventory.active.playbackDevice===d.playbackDevice; + function makeDeviceDraft(){ + const a=deviceInventory?.active||{},types=deviceInventory?.types||[]; + const backend=types.some(t=>t.name===a.backend)?a.backend:types[0]?.name||''; + const t=deviceType(backend); + const playback=t?.outputs?.includes(a.playbackDevice)?a.playbackDevice:t?.outputs?.[0]||''; + const capture=t?.inputs?.includes(a.captureDevice)?a.captureDevice: + t?.separate?t?.inputs?.[0]||'':playback; + const same=backend===a.backend&&playback===a.playbackDevice&&capture===a.captureDevice; + return {backend,captureDevice:capture,playbackDevice:playback, + sampleRate:same&&a.rate?Number(a.rate):0, + bufferSize:same&&a.buffer?Number(a.buffer):0, + enabledInputs:same?[...(a.enabledInputs||[])]:null, + enabledOutputs:same?[...(a.enabledOutputs||[])]:null}; + } + const pinsEqual=(a,b)=>Array.isArray(a)&&Array.isArray(b)&& + a.length===b.length&&a.every((v,i)=>v===b[i]); + function deviceDirty(){ + const d=deviceDraft,a=deviceInventory?.active; + return !!d&&(!a?.open||d.backend!==a.backend||d.captureDevice!==a.captureDevice|| + d.playbackDevice!==a.playbackDevice|| + (d.sampleRate>0&&d.sampleRate!==Number(a.rate))|| + (d.bufferSize>0&&d.bufferSize!==Number(a.buffer))|| + (deviceSameEndpoint(d)&& + (!pinsEqual(d.enabledInputs,a.enabledInputs)||!pinsEqual(d.enabledOutputs,a.enabledOutputs)))); + } + function deviceRefresh(){ + if(!isNative()||deviceBusy)return; + const now=Date.now();if(now-lastDeviceRefresh<1000)return; + lastDeviceRefresh=now;backend.emitEvent('arMixAction',{action:'audioDeviceInventory'}); + } + function deviceApply(){ + if(!isNative()||deviceBusy||!deviceDraft||!deviceInventory?.active)return; + const d=deviceDraft,a=deviceInventory.active; + if(route().monitor||lastStatus.monitor||lastStatus.secondaryOutputArmed) { + deviceNote='MUTE MAIN and secondary output in SIGNAL CHECK before APPLY DEVICE'; + lastSignature='';refreshIO();return; + } + if(!d.backend||!d.captureDevice||!d.playbackDevice||!deviceDirty())return; + // Changing hardware is a structural transaction, not a fader parameter. + deviceRequest='device-'+Date.now()+'-'+(++deviceRequestSeq); + deviceBusy=true;deviceNote='APPLYING · OUTPUT MUTED · waiting for native readback'; + backend.emitEvent('arMixAction',{action:'audioDeviceApply',requestId:deviceRequest, + expectedDeviceGeneration:Number(a.deviceGeneration)||0, + config:{backend:d.backend,captureDevice:d.captureDevice, + playbackDevice:d.playbackDevice,sampleRate:d.sampleRate,bufferSize:d.bufferSize, + enabledInputs:Array.isArray(d.enabledInputs)?d.enabledInputs:[], + enabledOutputs:Array.isArray(d.enabledOutputs)?d.enabledOutputs:[]}}); + lastSignature='';refreshIO(); + } + function deviceField(label,control){ + const group=node('label','arIODeviceField'); + group.append(node('span','',label),control);return group; + } + function deviceSelect(cls,value,options,disabled=false){ + const field=node('select',cls); + for(const [v,label] of options){ + const opt=node('option','',label);opt.value=String(v);field.appendChild(opt); + } + if(options.some(([v])=>String(v)===String(value)))field.value=String(value); + field.disabled=disabled||!options.length; + return field; + } + function renderCustomDevice(body){ + const a=deviceInventory?.active||{},types=deviceInventory?.types||[]; + if(!deviceDraft&&types.length)deviceDraft=makeDeviceDraft(); + const d=deviceDraft; + const panel=node('section','arIORealDeviceSetup arIODeviceControl'); + panel.appendChild(node('p','arIODeviceSummary', + !isNative()?'WEB PREVIEW · connect the Windows application to configure real hardware': + a.open?'ACTIVE · '+a.backend+' · '+a.captureDevice+' → '+a.playbackDevice+ + ' · '+a.rate+' Hz / '+a.buffer+' samples': + 'NO VERIFIED DEVICE · select a reported interface and APPLY DEVICE')); + if(!types.length){ + panel.appendChild(node('p','arIODeviceEmpty', + isNative()?'Scanning actual Windows drivers. Use REFRESH DEVICE LIST if needed.': + 'Hardware cannot be changed in a browser-only preview.')); + } else if(d){ + const t=deviceType(d.backend),separate=!!t?.separate; + const fields=node('div','arIODeviceFields'); + fields.appendChild(deviceField('DRIVER / BACKEND',deviceSelect('arIODeviceBackend', + d.backend,types.map(t=>[t.name,t.name]),deviceBusy||!isNative()))); + fields.appendChild(deviceField(separate?'CAPTURE DEVICE':'AUDIO INTERFACE', + deviceSelect('arIODeviceCapture',d.captureDevice,(t?.inputs||[]).map(n=>[n,n]), + deviceBusy||!isNative()||!separate))); + fields.appendChild(deviceField('PLAYBACK DEVICE',deviceSelect('arIODevicePlayback', + d.playbackDevice,(t?.outputs||[]).map(n=>[n,n]),deviceBusy||!isNative()))); + const same=deviceSameEndpoint(d); + const rateOpts=[[0,'AUTO · driver default']]; + const bufferOpts=[[0,'AUTO · driver default']]; + if(same){ + const rates=[...new Set([...(a.rates||[]),a.rate].filter(v=>Number(v)>0))]; + const periods=[...new Set([...(a.buffers||[]),a.buffer].filter(v=>Number(v)>0))]; + for(const v of rates)rateOpts.push([Number(v),Number(v)/1000+' kHz']); + for(const v of periods)bufferOpts.push([Number(v),v+' samples']); + } + fields.appendChild(deviceField('SAMPLE RATE',deviceSelect('arIODeviceRate', + d.sampleRate,rateOpts,deviceBusy||!isNative()))); + fields.appendChild(deviceField('BUFFER / PERIOD',deviceSelect('arIODeviceBuffer', + d.bufferSize,bufferOpts,deviceBusy||!isNative()))); + panel.appendChild(fields); + panel.appendChild(node('p','arIODeviceNote',same? + 'These rates, buffers and channel pins are reported by the OPEN JUCE device.': + 'New interface: rate/buffer AUTO and default pin masks on first APPLY. Edit verified pins after it opens. No guessed capabilities.')); + const pins=node('div','arIODevicePins'); + for(const [direction,names,selected] of [ + ['INPUT',same?a.inputNames:[],d.enabledInputs], + ['OUTPUT',same?a.outputNames:[],d.enabledOutputs]]){ + const side=node('div','arIODevicePinGroup'); + side.appendChild(node('strong','',direction+' HARDWARE PINS'+(same?' · DRIVER REPORTED':' · AFTER APPLY'))); + if(!same||!names?.length){ + side.appendChild(node('small','',same?'No reported pins':'Select and APPLY this interface first')); + }else{ + names.forEach((name,index)=>{ + const lbl=node('label','arIODevicePinRow'); + const cb=node('input','arIODevicePin');cb.type='checkbox'; + cb.dataset.devicePinDirection=direction;cb.value=String(index); + cb.checked=Array.isArray(selected)&&selected.includes(index); + cb.disabled=deviceBusy||!isNative(); + lbl.append(cb,node('span','',String(index+1).padStart(2,'0')+' · '+name)); + side.appendChild(lbl); + }); + } + pins.appendChild(side); + } + panel.appendChild(pins); + } + const row=node('div','arIODeviceActions'); + const refresh=node('button','btn-180 arIODeviceRefresh','REFRESH DEVICE LIST'); + refresh.type='button';refresh.dataset.ioRefreshDevice='1';refresh.disabled=deviceBusy||!isNative(); + row.appendChild(refresh);panel.appendChild(row); + body.appendChild(panel); + } + function refreshIO(){ const s=route(),id=el('arIOIdentity'),body=el('arIOBody'); matrixResetIfDeviceChanged(s); @@ -670,10 +811,18 @@ b.setAttribute('aria-selected',String(active)); }); overlay.dataset.activeTab=ioTab; + overlay.querySelector('[data-mix-apply]').hidden=ioTab==='device'; + overlay.querySelector('[data-io-revert]').hidden=ioTab==='device'; + overlay.querySelector('[data-io-internal]').hidden=ioTab==='device'; + overlay.querySelector('[data-io-device-apply]').hidden=ioTab!=='device'; + overlay.querySelector('[data-io-device-revert]').hidden=ioTab!=='device'; + overlay.querySelector('[data-io-device-apply]').disabled=!isNative()||deviceBusy||!deviceDirty()|| + !!s.pending||s.monitor||!!lastStatus.secondaryOutputArmed; + overlay.querySelector('[data-io-device-revert]').disabled=deviceBusy||!deviceDirty(); overlay.querySelector('[data-mix-apply]').disabled=!hardwareReady(s)||!!matrixDraft.size||s.monitor; overlay.querySelector('[data-io-revert]').disabled=!isNative()||s.pending; const signature=ioTab+'|'+JSON.stringify([s.epoch,s.revision,s.pending,s.draftRoutes, - s.outputPorts,s.mainOutputs,s.draftMainOutputs,s.monitorOutputs,s.draftMonitorOutputs,s.monitorSends,s.draftMonitorSends,s.ports,deviceInventory,matrixPage[ioTab],monitorSendsExpanded, + s.outputPorts,s.mainOutputs,s.draftMainOutputs,s.monitorOutputs,s.draftMonitorOutputs,s.monitorSends,s.draftMonitorSends,s.ports,deviceInventory,deviceDraft,deviceBusy,deviceNote,matrixPage[ioTab],monitorSendsExpanded, [...matrixDraft],[...matrixSide]]); if(lastSignature===signature)return; lastSignature=signature; @@ -758,62 +907,12 @@ body.appendChild(node('p','arIOHint','LIVE MAIN: '+(accepted.length===2?'HW '+(accepted[0]+1)+'/'+(accepted[1]+1):'UNAVAILABLE')+ ' · Only native-ACKed MAIN/MONITOR pairs can carry sound. AUX1–4 are internal stereo FX returns, not physical output sockets.')); }else{ - // Present the REAL JUCE device inventory, not a mock backend selector. - // Backend/device/rate/buffer changes happen only inside the existing - // safe native AudioDeviceSelectorComponent (no second device manager). - const setup=node('section','arIORealDeviceSetup'); - setup.setAttribute('aria-label','Select an actual Windows audio device'); - const summary=node('div','arIORealDeviceSummary'); - summary.append(node('strong','','1 · AUDIO DRIVER & DEVICE'), - node('small','',!isNative()?'WEB PREVIEW · Windows audio devices cannot be listed here': - 'Native JUCE device selector · changing hardware requires route review')); - const chooser=node('button','btn-180 arIODeviceChoose','SELECT AUDIO DRIVER / DEVICE…'); - chooser.type='button';chooser.dataset.ioAdvanced='1'; - chooser.disabled=!isNative(); - const refresh=node('button','btn-180 arIODeviceRefresh','REFRESH DEVICE LIST'); - refresh.type='button';refresh.dataset.ioRefreshDevice='1';refresh.disabled=!isNative(); - const actions=node('div','arIODeviceActions');actions.append(chooser,refresh); - setup.append(summary,actions); - setup.appendChild(node('p','arIODeviceNote', - 'The Windows selector provides driver type, capture/playback device, enabled input/output channels, sample rate and buffer. Selecting a different driver never auto-unmutes output.')); - const backends=node('div','arIOBackendStatus'); - const types=Array.isArray(deviceInventory?.types)?deviceInventory.types:[]; - const backendType=(kind)=>types.find(t=>kind==='WASAPI' - ?String(t.name).startsWith('Windows Audio') - :kind==='ASIO'?t.name==='ASIO':t.name==='DirectSound'); - for(const [kind,title] of [['ASIO','ASIO'],['WASAPI','WASAPI · Windows Audio'],['DirectSound','DirectSound · legacy']]){ - const item=backendType(kind); - const tag=node('span','arIOBackendBadge',kind+' · '+(item?'DETECTED':'NOT REPORTED')); - tag.dataset.available=item?'yes':'no'; - tag.title=item?'Driver enumerated by JUCE': - isNative()?'Not reported by this running native JUCE backend':'Native inventory unavailable in web preview'; - backends.appendChild(tag); - } - setup.appendChild(backends); - const inventory=node('section','arIODeviceInventory'); - inventory.setAttribute('aria-label','Driver-reported ASIO WASAPI DirectSound capture and playback devices'); - if(!types.length){ - inventory.appendChild(node('p','arIODeviceEmpty', - isNative()?'Reading available Windows audio backends… press REFRESH if empty.': - 'PREVIEW ONLY · Open the Windows EXE to detect installed drivers, ASIO interfaces, WASAPI or DirectSound devices.')); - }else{ - for(const type of types){ - const card=node('div','arIODeviceType'); - card.dataset.active=type.active?'true':'false'; - const backendName=String(type.name).startsWith('Windows Audio') - ?type.name+' · WASAPI':String(type.name); - const title=node('strong','',backendName+(type.active?' · CURRENT':'')); - const input=node('span','','CAPTURE · '+(type.inputs?.length?type.inputs.join(' · '):'NONE REPORTED')); - const output=node('span','','PLAYBACK · '+(type.outputs?.length?type.outputs.join(' · '):'NONE REPORTED')); - card.append(title,input,output);inventory.appendChild(card); - } - } - setup.appendChild(inventory);body.appendChild(setup); + renderCustomDevice(body); } const hint=!isNative()?'PREVIEW ONLY · no native hardware': s.monitor?'MUTE OUTPUT BEFORE APPLY':s.pending?'WAITING FOR NATIVE ACK': s.ready?'E'+s.epoch+' · Native APPLY required for input edits':'CHOOSE A VERIFIED DIRECT DEVICE'; - el('arIOFeedback').textContent=matrixMessage||hint; + el('arIOFeedback').textContent=(ioTab==='device'?deviceNote:matrixMessage)||hint; } function changeSource(select){ const channel=Number(select.dataset.channel); @@ -946,14 +1045,15 @@ if(b.dataset.ioClose!==undefined){e.preventDefault();e.stopImmediatePropagation();closeIO();return;} if(b.dataset.ioTab){e.preventDefault();e.stopImmediatePropagation();ioTab=b.dataset.ioTab;matrixMessage='';lastSignature='';refreshIO();return;} if(b.dataset.ioRefreshDevice!==undefined){ - e.preventDefault();e.stopImmediatePropagation(); - if(isNative())backend.emitEvent('arMixAction',{action:'audioDeviceInventory'}); - return; + e.preventDefault();e.stopImmediatePropagation();deviceRefresh();return; + } + if(b.dataset.ioDeviceApply!==undefined){ + e.preventDefault();e.stopImmediatePropagation();deviceApply();return; } - if(b.dataset.ioAdvanced!==undefined){ + if(b.dataset.ioDeviceRevert!==undefined){ e.preventDefault();e.stopImmediatePropagation(); - if(!isNative())return; - closeIO();backend.emitEvent('arMixAction',{action:'audioSetup'});return; + if(!deviceBusy){deviceDraft=makeDeviceDraft();deviceNote='DEVICE DRAFT REVERTED';lastSignature='';refreshIO();} + return; } if(b.dataset.mixPatch){ e.preventDefault();e.stopImmediatePropagation(); @@ -964,6 +1064,32 @@ } if(b.dataset.mixApply!==undefined){e.preventDefault();e.stopImmediatePropagation();const response=window.__arMixApplyMixerDraft?.();if(response&&!response.ok)el('arIOFeedback').textContent=response.error;refresh();return;} },true); + document.addEventListener('change',e=>{ + const target=e.target; + if(overlay.hidden||ioTab!=='device'||deviceBusy||!deviceDraft)return; + if(target.matches('.arIODeviceBackend')){ + const t=deviceType(target.value); + const playback=t?.outputs?.[0]||'',capture=t?.separate?t?.inputs?.[0]||'':playback; + deviceDraft={backend:target.value,captureDevice:capture,playbackDevice:playback, + sampleRate:0,bufferSize:0,enabledInputs:null,enabledOutputs:null}; + }else if(target.matches('.arIODevicePlayback')){ + deviceDraft.playbackDevice=target.value; + if(!deviceType(deviceDraft.backend)?.separate)deviceDraft.captureDevice=target.value; + }else if(target.matches('.arIODeviceCapture')){ + deviceDraft.captureDevice=target.value; + }else if(target.matches('.arIODeviceRate')){ + deviceDraft.sampleRate=Number(target.value)||0; + }else if(target.matches('.arIODeviceBuffer')){ + deviceDraft.bufferSize=Number(target.value)||0; + }else if(target.matches('.arIODevicePin')){ + const key=target.dataset.devicePinDirection==='INPUT'?'enabledInputs':'enabledOutputs'; + const set=new Set(deviceDraft[key]||[]),pin=Number(target.value); + if(target.checked)set.add(pin);else set.delete(pin); + deviceDraft[key]=[...set].sort((a,b)=>a-b); + }else return; + deviceNote='DEVICE DRAFT · changes are not live until native APPLY'; + lastSignature='';refreshIO(); + },true); document.addEventListener('change',e=>{ if(sendEditor.hidden||!sendFocus||!sendEditor.contains(e.target))return; const input=e.target; @@ -995,7 +1121,22 @@ if(window.__armixIoStatusKey!==key){window.__armixIoStatusKey=key;lastSignature='';refresh();} if(!overlay.hidden){const identity=(d.driver||'')+'/'+(d.rate||0)+'/'+(d.buffer||0);if(overlay.dataset.deviceIdentity!==identity){overlay.dataset.deviceIdentity=identity;refreshIO();}} }); - backend?.addEventListener?.('arMixAudioDeviceInventory',d=>{deviceInventory=d;lastSignature='';if(!overlay.hidden)refreshIO();}); + backend?.addEventListener?.('arMixAudioDeviceInventory',d=>{ + const hadDraft=deviceDirty(); + deviceInventory=d; + if(!hadDraft&&!deviceBusy)deviceDraft=makeDeviceDraft(); + lastSignature='';if(!overlay.hidden)refreshIO(); + }); + backend?.addEventListener?.('arMixAudioDeviceApplyAck',ack=>{ + if(!deviceBusy||ack?.requestId!==deviceRequest)return; + deviceBusy=false;deviceRequest=''; + if(deviceInventory&&ack?.active)deviceInventory.active=ack.active; + deviceDraft=makeDeviceDraft(); + deviceNote=ack?.ok?'ACCEPTED · NATIVE DEVICE VERIFIED · OUTPUT MUTED': + (ack?.state||'REJECTED')+' · '+(ack?.error||'Check driver and retry'); + // Same real routing controller sees the new device epoch via normal status. + lastSignature='';if(!overlay.hidden)refreshIO(); + }); backend?.addEventListener?.('arMixRoutingLabAck',ack=>{ if(quickSourcePending){ const requested=quickSourcePending; From 11d13334df68014b7fb97a4ce72ec6c477ab0f38 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 31 Oct 2026 09:46:07 +0700 Subject: [PATCH 03/13] feat(audio): synchronize standalone device setup UI with native web source --- AR-MIX-Live-FX-Host-Standalone-v0.3.html | 266 +++++++++++++++++------ 1 file changed, 204 insertions(+), 62 deletions(-) diff --git a/AR-MIX-Live-FX-Host-Standalone-v0.3.html b/AR-MIX-Live-FX-Host-Standalone-v0.3.html index fa3f9769e..6369748c3 100644 --- a/AR-MIX-Live-FX-Host-Standalone-v0.3.html +++ b/AR-MIX-Live-FX-Host-Standalone-v0.3.html @@ -3164,6 +3164,8 @@ if(!mixer||!host)return; let mode='FX', lastStatus={}, deviceInventory=null, ioTab='device', lastSignature='', focusedInput=2; let monitorSendsExpanded=false; + // DEVICE1: staged selections are UI-only; only positive native ACK changes active hardware. + let deviceDraft=null,deviceBusy=false,deviceNote='',deviceRequest='',deviceRequestSeq=0,lastDeviceRefresh=0; // Pending SOURCE ACK is a UI projection only; monitor.js owns the native route. let quickSourcePending=null; const el=id=>document.getElementById(id); @@ -3197,7 +3199,7 @@ sofControls.hidden=true;toolbar.appendChild(sofControls); const overlay=node('div','arIOOverlay'); overlay.id='arIOOverlay';overlay.hidden=true; - overlay.innerHTML=''; + overlay.innerHTML=''; document.body.appendChild(overlay); // G3: ONE floating inspector follows the selected source/AUX, no new // DSP graph, no heavyweight matrix, no layout shifts in the MIX strips. @@ -3432,7 +3434,7 @@ if(Number.isInteger(channel)&&channel>=0&&channel<10)focusedInput=channel; if(overlay.hidden)advancedMatrixOpen=false; overlay.hidden=false;lastSignature='';refreshIO(); - if(isNative())backend.emitEvent('arMixAction',{action:'audioDeviceInventory'}); + if(isNative())deviceRefresh(); if(Number.isInteger(channel))overlay.querySelector('[data-io-quick-row="'+channel+'"]')?.scrollIntoView({block:'nearest'}); } window.__arMixOpenAudioIO=openIO; @@ -3816,6 +3818,145 @@ 'MONITOR needs two verified unused output pins.'); lastSignature='';refresh(); } + + const deviceType=name=>(deviceInventory?.types||[]).find(t=>t.name===name); + const deviceSameEndpoint=d=>!!d&&!!deviceInventory?.active?.open&& + deviceInventory.active.backend===d.backend&& + deviceInventory.active.captureDevice===d.captureDevice&& + deviceInventory.active.playbackDevice===d.playbackDevice; + function makeDeviceDraft(){ + const a=deviceInventory?.active||{},types=deviceInventory?.types||[]; + const backend=types.some(t=>t.name===a.backend)?a.backend:types[0]?.name||''; + const t=deviceType(backend); + const playback=t?.outputs?.includes(a.playbackDevice)?a.playbackDevice:t?.outputs?.[0]||''; + const capture=t?.inputs?.includes(a.captureDevice)?a.captureDevice: + t?.separate?t?.inputs?.[0]||'':playback; + const same=backend===a.backend&&playback===a.playbackDevice&&capture===a.captureDevice; + return {backend,captureDevice:capture,playbackDevice:playback, + sampleRate:same&&a.rate?Number(a.rate):0, + bufferSize:same&&a.buffer?Number(a.buffer):0, + enabledInputs:same?[...(a.enabledInputs||[])]:null, + enabledOutputs:same?[...(a.enabledOutputs||[])]:null}; + } + const pinsEqual=(a,b)=>Array.isArray(a)&&Array.isArray(b)&& + a.length===b.length&&a.every((v,i)=>v===b[i]); + function deviceDirty(){ + const d=deviceDraft,a=deviceInventory?.active; + return !!d&&(!a?.open||d.backend!==a.backend||d.captureDevice!==a.captureDevice|| + d.playbackDevice!==a.playbackDevice|| + (d.sampleRate>0&&d.sampleRate!==Number(a.rate))|| + (d.bufferSize>0&&d.bufferSize!==Number(a.buffer))|| + (deviceSameEndpoint(d)&& + (!pinsEqual(d.enabledInputs,a.enabledInputs)||!pinsEqual(d.enabledOutputs,a.enabledOutputs)))); + } + function deviceRefresh(){ + if(!isNative()||deviceBusy)return; + const now=Date.now();if(now-lastDeviceRefresh<1000)return; + lastDeviceRefresh=now;backend.emitEvent('arMixAction',{action:'audioDeviceInventory'}); + } + function deviceApply(){ + if(!isNative()||deviceBusy||!deviceDraft||!deviceInventory?.active)return; + const d=deviceDraft,a=deviceInventory.active; + if(route().monitor||lastStatus.monitor||lastStatus.secondaryOutputArmed) { + deviceNote='MUTE MAIN and secondary output in SIGNAL CHECK before APPLY DEVICE'; + lastSignature='';refreshIO();return; + } + if(!d.backend||!d.captureDevice||!d.playbackDevice||!deviceDirty())return; + // Changing hardware is a structural transaction, not a fader parameter. + deviceRequest='device-'+Date.now()+'-'+(++deviceRequestSeq); + deviceBusy=true;deviceNote='APPLYING · OUTPUT MUTED · waiting for native readback'; + backend.emitEvent('arMixAction',{action:'audioDeviceApply',requestId:deviceRequest, + expectedDeviceGeneration:Number(a.deviceGeneration)||0, + config:{backend:d.backend,captureDevice:d.captureDevice, + playbackDevice:d.playbackDevice,sampleRate:d.sampleRate,bufferSize:d.bufferSize, + enabledInputs:Array.isArray(d.enabledInputs)?d.enabledInputs:[], + enabledOutputs:Array.isArray(d.enabledOutputs)?d.enabledOutputs:[]}}); + lastSignature='';refreshIO(); + } + function deviceField(label,control){ + const group=node('label','arIODeviceField'); + group.append(node('span','',label),control);return group; + } + function deviceSelect(cls,value,options,disabled=false){ + const field=node('select',cls); + for(const [v,label] of options){ + const opt=node('option','',label);opt.value=String(v);field.appendChild(opt); + } + if(options.some(([v])=>String(v)===String(value)))field.value=String(value); + field.disabled=disabled||!options.length; + return field; + } + function renderCustomDevice(body){ + const a=deviceInventory?.active||{},types=deviceInventory?.types||[]; + if(!deviceDraft&&types.length)deviceDraft=makeDeviceDraft(); + const d=deviceDraft; + const panel=node('section','arIORealDeviceSetup arIODeviceControl'); + panel.appendChild(node('p','arIODeviceSummary', + !isNative()?'WEB PREVIEW · connect the Windows application to configure real hardware': + a.open?'ACTIVE · '+a.backend+' · '+a.captureDevice+' → '+a.playbackDevice+ + ' · '+a.rate+' Hz / '+a.buffer+' samples': + 'NO VERIFIED DEVICE · select a reported interface and APPLY DEVICE')); + if(!types.length){ + panel.appendChild(node('p','arIODeviceEmpty', + isNative()?'Scanning actual Windows drivers. Use REFRESH DEVICE LIST if needed.': + 'Hardware cannot be changed in a browser-only preview.')); + } else if(d){ + const t=deviceType(d.backend),separate=!!t?.separate; + const fields=node('div','arIODeviceFields'); + fields.appendChild(deviceField('DRIVER / BACKEND',deviceSelect('arIODeviceBackend', + d.backend,types.map(t=>[t.name,t.name]),deviceBusy||!isNative()))); + fields.appendChild(deviceField(separate?'CAPTURE DEVICE':'AUDIO INTERFACE', + deviceSelect('arIODeviceCapture',d.captureDevice,(t?.inputs||[]).map(n=>[n,n]), + deviceBusy||!isNative()||!separate))); + fields.appendChild(deviceField('PLAYBACK DEVICE',deviceSelect('arIODevicePlayback', + d.playbackDevice,(t?.outputs||[]).map(n=>[n,n]),deviceBusy||!isNative()))); + const same=deviceSameEndpoint(d); + const rateOpts=[[0,'AUTO · driver default']]; + const bufferOpts=[[0,'AUTO · driver default']]; + if(same){ + const rates=[...new Set([...(a.rates||[]),a.rate].filter(v=>Number(v)>0))]; + const periods=[...new Set([...(a.buffers||[]),a.buffer].filter(v=>Number(v)>0))]; + for(const v of rates)rateOpts.push([Number(v),Number(v)/1000+' kHz']); + for(const v of periods)bufferOpts.push([Number(v),v+' samples']); + } + fields.appendChild(deviceField('SAMPLE RATE',deviceSelect('arIODeviceRate', + d.sampleRate,rateOpts,deviceBusy||!isNative()))); + fields.appendChild(deviceField('BUFFER / PERIOD',deviceSelect('arIODeviceBuffer', + d.bufferSize,bufferOpts,deviceBusy||!isNative()))); + panel.appendChild(fields); + panel.appendChild(node('p','arIODeviceNote',same? + 'These rates, buffers and channel pins are reported by the OPEN JUCE device.': + 'New interface: rate/buffer AUTO and default pin masks on first APPLY. Edit verified pins after it opens. No guessed capabilities.')); + const pins=node('div','arIODevicePins'); + for(const [direction,names,selected] of [ + ['INPUT',same?a.inputNames:[],d.enabledInputs], + ['OUTPUT',same?a.outputNames:[],d.enabledOutputs]]){ + const side=node('div','arIODevicePinGroup'); + side.appendChild(node('strong','',direction+' HARDWARE PINS'+(same?' · DRIVER REPORTED':' · AFTER APPLY'))); + if(!same||!names?.length){ + side.appendChild(node('small','',same?'No reported pins':'Select and APPLY this interface first')); + }else{ + names.forEach((name,index)=>{ + const lbl=node('label','arIODevicePinRow'); + const cb=node('input','arIODevicePin');cb.type='checkbox'; + cb.dataset.devicePinDirection=direction;cb.value=String(index); + cb.checked=Array.isArray(selected)&&selected.includes(index); + cb.disabled=deviceBusy||!isNative(); + lbl.append(cb,node('span','',String(index+1).padStart(2,'0')+' · '+name)); + side.appendChild(lbl); + }); + } + pins.appendChild(side); + } + panel.appendChild(pins); + } + const row=node('div','arIODeviceActions'); + const refresh=node('button','btn-180 arIODeviceRefresh','REFRESH DEVICE LIST'); + refresh.type='button';refresh.dataset.ioRefreshDevice='1';refresh.disabled=deviceBusy||!isNative(); + row.appendChild(refresh);panel.appendChild(row); + body.appendChild(panel); + } + function refreshIO(){ const s=route(),id=el('arIOIdentity'),body=el('arIOBody'); matrixResetIfDeviceChanged(s); @@ -3826,10 +3967,18 @@ b.setAttribute('aria-selected',String(active)); }); overlay.dataset.activeTab=ioTab; + overlay.querySelector('[data-mix-apply]').hidden=ioTab==='device'; + overlay.querySelector('[data-io-revert]').hidden=ioTab==='device'; + overlay.querySelector('[data-io-internal]').hidden=ioTab==='device'; + overlay.querySelector('[data-io-device-apply]').hidden=ioTab!=='device'; + overlay.querySelector('[data-io-device-revert]').hidden=ioTab!=='device'; + overlay.querySelector('[data-io-device-apply]').disabled=!isNative()||deviceBusy||!deviceDirty()|| + !!s.pending||s.monitor||!!lastStatus.secondaryOutputArmed; + overlay.querySelector('[data-io-device-revert]').disabled=deviceBusy||!deviceDirty(); overlay.querySelector('[data-mix-apply]').disabled=!hardwareReady(s)||!!matrixDraft.size||s.monitor; overlay.querySelector('[data-io-revert]').disabled=!isNative()||s.pending; const signature=ioTab+'|'+JSON.stringify([s.epoch,s.revision,s.pending,s.draftRoutes, - s.outputPorts,s.mainOutputs,s.draftMainOutputs,s.monitorOutputs,s.draftMonitorOutputs,s.monitorSends,s.draftMonitorSends,s.ports,deviceInventory,matrixPage[ioTab],monitorSendsExpanded, + s.outputPorts,s.mainOutputs,s.draftMainOutputs,s.monitorOutputs,s.draftMonitorOutputs,s.monitorSends,s.draftMonitorSends,s.ports,deviceInventory,deviceDraft,deviceBusy,deviceNote,matrixPage[ioTab],monitorSendsExpanded, [...matrixDraft],[...matrixSide]]); if(lastSignature===signature)return; lastSignature=signature; @@ -3914,62 +4063,12 @@ body.appendChild(node('p','arIOHint','LIVE MAIN: '+(accepted.length===2?'HW '+(accepted[0]+1)+'/'+(accepted[1]+1):'UNAVAILABLE')+ ' · Only native-ACKed MAIN/MONITOR pairs can carry sound. AUX1–4 are internal stereo FX returns, not physical output sockets.')); }else{ - // Present the REAL JUCE device inventory, not a mock backend selector. - // Backend/device/rate/buffer changes happen only inside the existing - // safe native AudioDeviceSelectorComponent (no second device manager). - const setup=node('section','arIORealDeviceSetup'); - setup.setAttribute('aria-label','Select an actual Windows audio device'); - const summary=node('div','arIORealDeviceSummary'); - summary.append(node('strong','','1 · AUDIO DRIVER & DEVICE'), - node('small','',!isNative()?'WEB PREVIEW · Windows audio devices cannot be listed here': - 'Native JUCE device selector · changing hardware requires route review')); - const chooser=node('button','btn-180 arIODeviceChoose','SELECT AUDIO DRIVER / DEVICE…'); - chooser.type='button';chooser.dataset.ioAdvanced='1'; - chooser.disabled=!isNative(); - const refresh=node('button','btn-180 arIODeviceRefresh','REFRESH DEVICE LIST'); - refresh.type='button';refresh.dataset.ioRefreshDevice='1';refresh.disabled=!isNative(); - const actions=node('div','arIODeviceActions');actions.append(chooser,refresh); - setup.append(summary,actions); - setup.appendChild(node('p','arIODeviceNote', - 'The Windows selector provides driver type, capture/playback device, enabled input/output channels, sample rate and buffer. Selecting a different driver never auto-unmutes output.')); - const backends=node('div','arIOBackendStatus'); - const types=Array.isArray(deviceInventory?.types)?deviceInventory.types:[]; - const backendType=(kind)=>types.find(t=>kind==='WASAPI' - ?String(t.name).startsWith('Windows Audio') - :kind==='ASIO'?t.name==='ASIO':t.name==='DirectSound'); - for(const [kind,title] of [['ASIO','ASIO'],['WASAPI','WASAPI · Windows Audio'],['DirectSound','DirectSound · legacy']]){ - const item=backendType(kind); - const tag=node('span','arIOBackendBadge',kind+' · '+(item?'DETECTED':'NOT REPORTED')); - tag.dataset.available=item?'yes':'no'; - tag.title=item?'Driver enumerated by JUCE': - isNative()?'Not reported by this running native JUCE backend':'Native inventory unavailable in web preview'; - backends.appendChild(tag); - } - setup.appendChild(backends); - const inventory=node('section','arIODeviceInventory'); - inventory.setAttribute('aria-label','Driver-reported ASIO WASAPI DirectSound capture and playback devices'); - if(!types.length){ - inventory.appendChild(node('p','arIODeviceEmpty', - isNative()?'Reading available Windows audio backends… press REFRESH if empty.': - 'PREVIEW ONLY · Open the Windows EXE to detect installed drivers, ASIO interfaces, WASAPI or DirectSound devices.')); - }else{ - for(const type of types){ - const card=node('div','arIODeviceType'); - card.dataset.active=type.active?'true':'false'; - const backendName=String(type.name).startsWith('Windows Audio') - ?type.name+' · WASAPI':String(type.name); - const title=node('strong','',backendName+(type.active?' · CURRENT':'')); - const input=node('span','','CAPTURE · '+(type.inputs?.length?type.inputs.join(' · '):'NONE REPORTED')); - const output=node('span','','PLAYBACK · '+(type.outputs?.length?type.outputs.join(' · '):'NONE REPORTED')); - card.append(title,input,output);inventory.appendChild(card); - } - } - setup.appendChild(inventory);body.appendChild(setup); + renderCustomDevice(body); } const hint=!isNative()?'PREVIEW ONLY · no native hardware': s.monitor?'MUTE OUTPUT BEFORE APPLY':s.pending?'WAITING FOR NATIVE ACK': s.ready?'E'+s.epoch+' · Native APPLY required for input edits':'CHOOSE A VERIFIED DIRECT DEVICE'; - el('arIOFeedback').textContent=matrixMessage||hint; + el('arIOFeedback').textContent=(ioTab==='device'?deviceNote:matrixMessage)||hint; } function changeSource(select){ const channel=Number(select.dataset.channel); @@ -4102,14 +4201,15 @@ if(b.dataset.ioClose!==undefined){e.preventDefault();e.stopImmediatePropagation();closeIO();return;} if(b.dataset.ioTab){e.preventDefault();e.stopImmediatePropagation();ioTab=b.dataset.ioTab;matrixMessage='';lastSignature='';refreshIO();return;} if(b.dataset.ioRefreshDevice!==undefined){ - e.preventDefault();e.stopImmediatePropagation(); - if(isNative())backend.emitEvent('arMixAction',{action:'audioDeviceInventory'}); - return; + e.preventDefault();e.stopImmediatePropagation();deviceRefresh();return; } - if(b.dataset.ioAdvanced!==undefined){ + if(b.dataset.ioDeviceApply!==undefined){ + e.preventDefault();e.stopImmediatePropagation();deviceApply();return; + } + if(b.dataset.ioDeviceRevert!==undefined){ e.preventDefault();e.stopImmediatePropagation(); - if(!isNative())return; - closeIO();backend.emitEvent('arMixAction',{action:'audioSetup'});return; + if(!deviceBusy){deviceDraft=makeDeviceDraft();deviceNote='DEVICE DRAFT REVERTED';lastSignature='';refreshIO();} + return; } if(b.dataset.mixPatch){ e.preventDefault();e.stopImmediatePropagation(); @@ -4120,6 +4220,32 @@ } if(b.dataset.mixApply!==undefined){e.preventDefault();e.stopImmediatePropagation();const response=window.__arMixApplyMixerDraft?.();if(response&&!response.ok)el('arIOFeedback').textContent=response.error;refresh();return;} },true); + document.addEventListener('change',e=>{ + const target=e.target; + if(overlay.hidden||ioTab!=='device'||deviceBusy||!deviceDraft)return; + if(target.matches('.arIODeviceBackend')){ + const t=deviceType(target.value); + const playback=t?.outputs?.[0]||'',capture=t?.separate?t?.inputs?.[0]||'':playback; + deviceDraft={backend:target.value,captureDevice:capture,playbackDevice:playback, + sampleRate:0,bufferSize:0,enabledInputs:null,enabledOutputs:null}; + }else if(target.matches('.arIODevicePlayback')){ + deviceDraft.playbackDevice=target.value; + if(!deviceType(deviceDraft.backend)?.separate)deviceDraft.captureDevice=target.value; + }else if(target.matches('.arIODeviceCapture')){ + deviceDraft.captureDevice=target.value; + }else if(target.matches('.arIODeviceRate')){ + deviceDraft.sampleRate=Number(target.value)||0; + }else if(target.matches('.arIODeviceBuffer')){ + deviceDraft.bufferSize=Number(target.value)||0; + }else if(target.matches('.arIODevicePin')){ + const key=target.dataset.devicePinDirection==='INPUT'?'enabledInputs':'enabledOutputs'; + const set=new Set(deviceDraft[key]||[]),pin=Number(target.value); + if(target.checked)set.add(pin);else set.delete(pin); + deviceDraft[key]=[...set].sort((a,b)=>a-b); + }else return; + deviceNote='DEVICE DRAFT · changes are not live until native APPLY'; + lastSignature='';refreshIO(); + },true); document.addEventListener('change',e=>{ if(sendEditor.hidden||!sendFocus||!sendEditor.contains(e.target))return; const input=e.target; @@ -4151,7 +4277,22 @@ if(window.__armixIoStatusKey!==key){window.__armixIoStatusKey=key;lastSignature='';refresh();} if(!overlay.hidden){const identity=(d.driver||'')+'/'+(d.rate||0)+'/'+(d.buffer||0);if(overlay.dataset.deviceIdentity!==identity){overlay.dataset.deviceIdentity=identity;refreshIO();}} }); - backend?.addEventListener?.('arMixAudioDeviceInventory',d=>{deviceInventory=d;lastSignature='';if(!overlay.hidden)refreshIO();}); + backend?.addEventListener?.('arMixAudioDeviceInventory',d=>{ + const hadDraft=deviceDirty(); + deviceInventory=d; + if(!hadDraft&&!deviceBusy)deviceDraft=makeDeviceDraft(); + lastSignature='';if(!overlay.hidden)refreshIO(); + }); + backend?.addEventListener?.('arMixAudioDeviceApplyAck',ack=>{ + if(!deviceBusy||ack?.requestId!==deviceRequest)return; + deviceBusy=false;deviceRequest=''; + if(deviceInventory&&ack?.active)deviceInventory.active=ack.active; + deviceDraft=makeDeviceDraft(); + deviceNote=ack?.ok?'ACCEPTED · NATIVE DEVICE VERIFIED · OUTPUT MUTED': + (ack?.state||'REJECTED')+' · '+(ack?.error||'Check driver and retry'); + // Same real routing controller sees the new device epoch via normal status. + lastSignature='';if(!overlay.hidden)refreshIO(); + }); backend?.addEventListener?.('arMixRoutingLabAck',ack=>{ if(quickSourcePending){ const requested=quickSourcePending; @@ -4184,6 +4325,7 @@ },true); setMode('FX'); })(); +