From 65e46f34d367aa9d5303bd8ccfab6ebcc4302b99 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 11 Nov 2026 03:32:48 +0700 Subject: [PATCH 1/4] refactor(device): isolate serialized Apply preflight, pin validation, verified rollback --- CMakeLists.txt | 9 + docs/architecture/README.md | 1 + src/Main.cpp | 178 +++++--------- src/NativeDeviceApplyCoordinator.h | 220 ++++++++++++++++++ .../native_device_apply_coordinator_test.cpp | 132 +++++++++++ 5 files changed, 426 insertions(+), 114 deletions(-) create mode 100644 src/NativeDeviceApplyCoordinator.h create mode 100644 tests/native_device_apply_coordinator_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0b77c943f..ab6f1cd81 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -263,6 +263,15 @@ if(BUILD_TESTING) add_executable(ARMixDeviceSessionTransitionTests tests/device_session_transition_policy_test.cpp engine/device/DeviceSessionTransitionPolicy.h) target_compile_features(ARMixDeviceSessionTransitionTests PRIVATE cxx_std_20) add_test(NAME NonDestructiveAudioSetupRetainsMixerDocument COMMAND ARMixDeviceSessionTransitionTests) + # M2 control-thread device Apply owner: UI preflight, exact pin identity, + # nested modal reentry, accepted readback and fail-closed rollback. + juce_add_console_app(ARMixDeviceApplyCoordinatorTests PRODUCT_NAME "ArSonMix Device Apply Coordinator Tests") + target_sources(ARMixDeviceApplyCoordinatorTests PRIVATE + tests/native_device_apply_coordinator_test.cpp src/NativeDeviceApplyCoordinator.h) + target_link_libraries(ARMixDeviceApplyCoordinatorTests PRIVATE + juce::juce_audio_devices juce::juce_recommended_config_flags) + target_compile_features(ARMixDeviceApplyCoordinatorTests PRIVATE cxx_std_20) + add_test(NAME NativeDeviceApplyPinValidationAndRollbackEvidence COMMAND ARMixDeviceApplyCoordinatorTests) add_executable(ARMixLiveRoutingEpochTests tests/live_port_epoch_publisher_test.cpp) target_compile_features(ARMixLiveRoutingEpochTests PRIVATE cxx_std_20) add_test(NAME P1ELivePortGenerationRevisionAndRealtimeRetirement COMMAND ARMixLiveRoutingEpochTests) diff --git a/docs/architecture/README.md b/docs/architecture/README.md index c92317521..a47cce96f 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -36,6 +36,7 @@ Assembled /preview/ DOM (presentation only) | Session persistence | src/NativeMixerSessionStore.h; src/NativeMixerSessionSaveWorker.h; src/NativeMixerSessionFxRestore.h | .smix durable state, rollback, vendor-state retention and explicit schema migration | | Native graph publisher & PCM | engine/core/DynamicNativeSessionPublisher.h; engine/core/RealtimeRoutePublisher.h; engine/core/DynamicPreparedMixerBlock.h | Validated immutable prepared graph, atomic publication, safe retirement, callback render state | | Audio device policy | src/LiveAudioEngine.h; engine/device/**; src/Main.cpp currently applies device | Verified driver/pins, epochs, reopen/rebind, explicit physical output safety; independent from logical session document | +| Audio device apply preflight (M2a) | src/NativeDeviceApplyCoordinator.h; src/Main.cpp (remaining orchestration) | Single message-thread transaction guard, JUCE open boundary, typed request/pin checks, accepted readback and fail-closed rollback. Next: extract full apply/rebind orchestration without duplicating DeviceManager | | Production audio compatibility | src/LiveDryRoutingLab.h; engine/core/UnifiedLegacyProductionAdmission.h | Retain only proven required M4/FAT migration semantics; never create another render authority | | Built-in DSP and VST lifecycle | engine/builtin_fx/**; src/NativeBuiltInFx.h; src/FactoryFxRegistry.h; src/PluginCatalog.h; engine/core/DynamicChannelFxLeaseBank.h; src/LiveAudioEngine.h | Per-processor DSP; one built-in registration for live insert, offline prepare, restore and native picker. Specialized editors and vendor lease remain with their existing owners. | | Player | engine/player/**; src/Main.cpp dispatch | Worker decode / buffered PCM, one native graph virtual input, no independent hardware output callback | diff --git a/src/Main.cpp b/src/Main.cpp index 8c24164bf..ebbb1d217 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -38,6 +38,7 @@ #include "NativeChannelAppearanceStore.h" #include "NativeMixerSessionSaveWorker.h" #include "NativeLogicalMixerControl.h" +#include "NativeDeviceApplyCoordinator.h" #include #include #include @@ -1206,7 +1207,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(safe->browser_.loaded)safe->browser_.emitEventIfBrowserIsVisible(event,juce::var(ack.release())); }; if(!queued || logicalMixer_.readOnly() || mixerSessionWorker_.busy() || - audioDeviceApplyActive_ || nativeShowBusy_ || studioBackupBusy_) + deviceApply_.busy() || nativeShowBusy_ || studioBackupBusy_) return reply("Offline FX settings could not be changed"); // This isolated processor has no publisher or audio consumer. Drain // its typed settings packet on CONTROL without rendering PCM. @@ -1223,7 +1224,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void handleLogicalMixerIntent(const juce::var& request) { const auto snapshot=approvedNativeSnapshot(); logicalMixer_.handleIntent(request,{ - audioDeviceApplyActive_ || nativeShowBusy_ || studioBackupBusy_ || + deviceApply_.busy() || nativeShowBusy_ || studioBackupBusy_ || engine_.isGraphSwitchPending(), snapshot.getProperty("logicalMixer",{}).isObject(), logicalVendorEditor_.has_value() @@ -1320,7 +1321,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // ENGINE callback. This code executes on the JUCE message thread, not RT. void handleApprovedNativeControl(const juce::var& request) { - if(audioDeviceApplyActive_) { + if(deviceApply_.busy()) { auto ack=std::make_unique(); ack->setProperty("requestId",request.getProperty("requestId",{})); ack->setProperty("status","REJECTED"); @@ -1596,38 +1597,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } using MixerBindingMode=armix::session::MixerDeviceBindingPolicy::Mode; - bool audioDeviceApplyActive_=false; // JUCE message thread, including nested driver dispatch + armix::device::NativeDeviceApplyCoordinator deviceApply_; // one CONTROL-thread transaction owner juce::String openSelectedAudioDevice(const juce::String& backend, const juce::AudioDeviceManager::AudioDeviceSetup& setup,bool resetDefaults=false) { - auto& manager=engine_.devices(); - if(manager.getCurrentAudioDeviceType()==backend && !resetDefaults) { - if(auto* device=manager.getCurrentAudioDevice();device && !device->isOpen()) - manager.closeAudioDevice(); - return manager.setAudioDeviceSetup(setup,true); - } - - // JUCE's setCurrentAudioDeviceType opens its remembered/default - // device first and sleeps on the message thread. Initialise the - // exact named backend and requested masks in one open instead. - auto xml=manager.createStateXml(); - if(!xml)xml=std::make_unique("DEVICESETUP"); - xml->setAttribute("deviceType",backend); - xml->removeAttribute("audioDeviceName"); - xml->setAttribute("audioInputDeviceName",setup.inputDeviceName); - xml->setAttribute("audioOutputDeviceName",setup.outputDeviceName); - xml->setAttribute("audioDeviceRate",setup.sampleRate); - xml->setAttribute("audioDeviceBufferSize",setup.bufferSize); - const auto setMask=[&](const char* key,bool useDefault,const juce::BigInteger& mask) { - if(useDefault)xml->removeAttribute(key); - else xml->setAttribute(key,mask.toString(2)); - }; - setMask("audioDeviceInChans",setup.useDefaultInputChannels,setup.inputChannels); - setMask("audioDeviceOutChans",setup.useDefaultOutputChannels,setup.outputChannels); - diagnostics_.record("CUSTOM_AUDIO_PHASE","CLOSE_PREVIOUS | "+manager.getCurrentAudioDeviceType()); - manager.closeAudioDevice(); - diagnostics_.record("CUSTOM_AUDIO_PHASE","OPEN_SELECTED | "+backend); - return manager.initialise(2,2,xml.get(),false); + return armix::device::NativeDeviceApplyCoordinator::openSelected( + engine_.devices(),backend,setup,resetDefaults, + [this](const juce::String& phase) { + diagnostics_.record("CUSTOM_AUDIO_PHASE",phase); + }); } void applyCustomAudioDevice(const juce::var& args) @@ -1635,7 +1613,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // JUCE device lifecycle runs on the message thread, including ASIO's // modal callbacks. Serialize transactions across nested dispatch. const auto id=args.getProperty("requestId",{}).toString().substring(0,64); - if(audioDeviceApplyActive_) { + if(deviceApply_.busy()) { auto ack=std::make_unique(); ack->setProperty("requestId",id); ack->setProperty("ok",false); @@ -1644,7 +1622,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr browser_.emitEventIfBrowserIsVisible("arMixAudioDeviceApplyAck",juce::var(ack.release())); return; } - const juce::ScopedValueSetter applying(audioDeviceApplyActive_,true); + auto applying=deviceApply_.tryBegin(); + if(!applying)return; // busy ACK already emitted above const auto oldGeneration=engine_.status().getProperty("deviceGeneration",0); auto send=[&](bool ok,const juce::String& state,const juce::String& error, bool canReusePins=false) @@ -1677,41 +1656,25 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return send(false,"REJECTED", "Stop STREAM and 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()||playback.isEmpty()|| - typeName.length()>160||capture.length()>250||playback.length()>250) - return send(false,"REJECTED","Choose an actual playback device"); + const auto parsed=armix::device::NativeDeviceApplyCoordinator::parse(config); + if(!parsed)return send(false,"REJECTED",parsed.error); + const auto& requested=parsed.value; + const auto& typeName=requested.backend; + const auto& capture=requested.capture; + const auto& playback=requested.playback; + const double rate=requested.rate,block=requested.block; 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); - // A separate-input/output backend can legitimately open a render - // endpoint WITHOUT capture hardware. Empty capture is a deliberate - // operator choice, never an inferred name or a fake input port. - // ASIO/non-separate drivers retain exact duplex device identity; - // they may still expose zero enabled capture *pins*. const bool separate=selectedType->hasSeparateInputsAndOutputs(); const bool outputOnly=separate&&capture.isEmpty(); - if((!outputOnly&&!namesIn.contains(capture))||!namesOut.contains(playback)|| - (!separate&&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 auto namesError=armix::device::NativeDeviceApplyCoordinator::validateNames( + requested,selectedType->getDeviceNames(true), + selectedType->getDeviceNames(false),separate); + if(namesError.isNotEmpty())return send(false,"REJECTED",namesError); const bool unchangedDevice=manager.getCurrentAudioDeviceType()==typeName; juce::AudioDeviceManager::AudioDeviceSetup before; manager.getAudioDeviceSetup(before); @@ -1722,14 +1685,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const bool previousWasOpen=previousDevice!=nullptr&&previousDevice->isOpen(); const bool previousMixerBound=engine_.hasBoundMixerRoute(); const bool previousMonitor=engine_.isMonitorEnabled(); - const auto assignMain=config.getProperty("assignSelectedPlaybackPinsToMain",false); - if(!assignMain.isBool()) - return send(false,"REJECTED","Invalid MAIN playback pin selection"); - const bool explicitMain=static_cast(assignMain); - const auto confirm=config.getProperty("confirmRetainedPinMapping",false); - if(!confirm.isBool()) - return send(false,"REJECTED","Invalid retained mixer mapping confirmation"); - if(static_cast(confirm)) { + const bool explicitMain=requested.assignMain; + if(requested.confirmRetainedPinMapping) { // The first Apply must open and verify the selected device. // Confirmation binds only that exact, still-open generation; // draft rate, buffer and pin changes use the normal Apply path. @@ -1770,23 +1727,13 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr pinOutput.getArray()->size()!=2)) return send(false,"REJECTED","Select exactly two inspected playback pins for MAIN."); if(recovery.reuseActivePins) { - const auto inCount=juce::jmin(64,previousDevice->getInputChannelNames().size()); - const auto outCount=juce::jmin(64,previousDevice->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)|| - (outputOnly&&!inMask.isZero())||outMask.countNumberOfSetBits()<2) - return send(false,"REJECTED","Select real input pins (or none) and >=2 verified playback pins"); + if(!armix::device::NativeDeviceApplyCoordinator::parsePinMasks( + pinInput,pinOutput,previousDevice->getInputChannelNames().size(), + previousDevice->getOutputChannelNames().size(),outputOnly, + inMask,outMask)) + return send(false,"REJECTED", + "Select real input pins (or none) and >=2 verified playback pins"); candidate.useDefaultInputChannels=false; candidate.useDefaultOutputChannels=false; candidate.inputChannels=inMask; @@ -1870,19 +1817,21 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // A transient ASIO4ALL pin inventory can settle on the next tick. if(changedAsioPinLayout) error="ASIO pin layout changed. Output remains muted; review the new playback pins."; - 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)|| - opened->getActiveInputChannels()!=actual.inputChannels|| - opened->getActiveOutputChannels()!=actual.outputChannels|| - opened->getActiveOutputChannels().countNumberOfSetBits()<2|| - std::abs(opened->getCurrentSampleRate()-actual.sampleRate)>1.0|| - opened->getCurrentBufferSizeSamples()!=actual.bufferSize)) - error="Driver readback mismatch; device setting was not accepted"; + if(error.isEmpty()) { + armix::device::NativeDeviceApplyCoordinator::AppliedReadback observed; + observed.actual=actual; + observed.backend=manager.getCurrentAudioDeviceType(); + observed.open=opened!=nullptr&&opened->isOpen(); + if(observed.open) { + observed.activeInputs=opened->getActiveInputChannels(); + observed.activeOutputs=opened->getActiveOutputChannels(); + observed.deviceRate=opened->getCurrentSampleRate(); + observed.deviceBuffer=opened->getCurrentBufferSizeSamples(); + } + if(!armix::device::NativeDeviceApplyCoordinator::matchesApplied( + requested,candidate,observed)) + error="Driver readback mismatch; device setting was not accepted"; + } if(error.isEmpty())diagnostics_.record("CUSTOM_AUDIO_PHASE","BIND_MIXER | "+typeName); const auto bindingMode=explicitPairStillIdentified?MixerBindingMode::verifiedMainPinApply: MixerBindingMode::verifiedDeviceApply; @@ -1927,18 +1876,18 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr manager.getCurrentAudioDeviceType()==previousType; juce::AudioDeviceManager::AudioDeviceSetup checked; manager.getAudioDeviceSetup(checked); + armix::device::NativeDeviceApplyCoordinator::RollbackReadback rollback; + rollback.actual=checked; + rollback.backend=manager.getCurrentAudioDeviceType(); + auto* recovered=manager.getCurrentAudioDevice(); + rollback.open=recovered!=nullptr&&recovered->isOpen(); + if(rollback.open) { + rollback.inputNames=recovered->getInputChannelNames(); + rollback.outputNames=recovered->getOutputChannelNames(); + } const bool verified=restored&& - checked.inputDeviceName==before.inputDeviceName&& - checked.outputDeviceName==before.outputDeviceName&& - checked.inputChannels==before.inputChannels&& - checked.outputChannels==before.outputChannels&& - checked.sampleRate==before.sampleRate&& - checked.bufferSize==before.bufferSize&& - manager.getCurrentAudioDevice()!=nullptr&& - manager.getCurrentAudioDevice()->isOpen()&& - (previousType!="ASIO"|| - (manager.getCurrentAudioDevice()->getInputChannelNames()==originalInputNames&& - manager.getCurrentAudioDevice()->getOutputChannelNames()==originalOutputNames))&& + armix::device::NativeDeviceApplyCoordinator::matchesRollback( + before,previousType,originalInputNames,originalOutputNames,rollback)&& finishAudioSetupAndRecoverMixer(); if(verified)asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); diagnostics_.record("CUSTOM_AUDIO_APPLY_FAIL",error+" | rollback="+ @@ -3323,7 +3272,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void onAction (const juce::var& args) { auto action = args.getProperty ("action", {}).toString(); - if(audioDeviceApplyActive_ && action!="audioDeviceApply")return; + if(deviceApply_.busy() && action!="audioDeviceApply")return; const auto value = args.getProperty ("value", {}); const int slot = static_cast (args.getProperty ("slot", -1)); if(action=="playerChooseOutput") { @@ -5771,7 +5720,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const bool silent=!mixerSessionRecoveryPending_ && engine_.hasPristineSilentMixerAwaitingAsio(); if(epoch==asioRecoveryEpoch_ || (!retained && !silent) || - audioDeviceApplyActive_ || (audioSetupWindow_ && audioSetupWindow_->isVisible()) || + deviceApply_.busy() || (audioSetupWindow_ && audioSetupWindow_->isVisible()) || nativeShowBusy_ || studioBackupBusy_ || mixerSessionWorker_.busy() || catalog_.busy() || engine_.isGraphSwitchPending() || engine_.independentClockActive() || engine_.diagnosticRoute()!=armix::diagnostics::Route::normal)return; @@ -5787,7 +5736,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto now=monotonicMilliseconds(); asioRecoveryGate_.observeEpoch(epoch,now); if(!asioRecoveryGate_.due(now))return; // let ASIO4ALL WDM pin inventory settle - const juce::ScopedValueSetter applying(audioDeviceApplyActive_,true); + auto applying=deviceApply_.tryBegin(); + if(!applying)return; if(!device || !device->isOpen() || device->getActiveOutputChannels().countNumberOfSetBits()<2) { // A missing, closed or output-less ASIO device requires a vendor call. @@ -5892,7 +5842,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void changeListenerCallback (juce::ChangeBroadcaster*) override { - if(audioDeviceApplyActive_)return; // synchronous transaction owns recovery + if(deviceApply_.busy())return; // synchronous transaction owns recovery // Save device state only after a real change, not on every 3-second tick. deviceSettingsDirty_ = true; // The retention gate closes only on an actual epoch/owner change. @@ -5908,7 +5858,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void timerCallback() override { - if(audioDeviceApplyActive_)return; // a vendor modal loop may re-enter JUCE + if(deviceApply_.busy())return; // a vendor modal loop may re-enter JUCE // Always disabled unless the user explicitly starts a bounded trace. const bool timing = guiPerf_.active; const double tickStart = timing ? juce::Time::getMillisecondCounterHiRes() : 0.0; diff --git a/src/NativeDeviceApplyCoordinator.h b/src/NativeDeviceApplyCoordinator.h new file mode 100644 index 000000000..118b54ecf --- /dev/null +++ b/src/NativeDeviceApplyCoordinator.h @@ -0,0 +1,220 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include +#include + +namespace armix::device { +// JUCE MESSAGE/CONTROL thread only. One serialized device transaction owner. +// This class owns request/pin/readback validation and the narrow driver-open +// boundary, NOT a second AudioDeviceManager, mixer document or PCM callback. +// The host still owns physical output permission and session rebind/rollback. +class NativeDeviceApplyCoordinator final { +public: + class Lease final { + public: + Lease() noexcept = default; + Lease(const Lease&)=delete; + Lease& operator=(const Lease&)=delete; + Lease(Lease&& other) noexcept : owner_(std::exchange(other.owner_,nullptr)) {} + Lease& operator=(Lease&&)=delete; + ~Lease() {if(owner_)owner_->busy_=false;} + explicit operator bool() const noexcept {return owner_!=nullptr;} + private: + friend class NativeDeviceApplyCoordinator; + explicit Lease(NativeDeviceApplyCoordinator* owner) noexcept : owner_(owner) {} + NativeDeviceApplyCoordinator* owner_=nullptr; + }; + + bool busy() const noexcept {return busy_;} + [[nodiscard]] Lease tryBegin() noexcept { + if(busy_)return {}; + busy_=true; + return Lease(this); + } + + struct Request { + juce::String backend,capture,playback; + double rate=0.,block=0.; + bool assignMain=false,confirmRetainedPinMapping=false; + }; + struct Parsed { + Request value{}; + juce::String error; + explicit operator bool() const noexcept {return error.isEmpty();} + }; + static Parsed parse(const juce::var& config) { + Parsed out; + if(!config.isObject()) { + out.error="Missing device configuration"; + return out; + } + auto& r=out.value; + r.backend=config.getProperty("backend",{}).toString(); + r.capture=config.getProperty("captureDevice",{}).toString(); + r.playback=config.getProperty("playbackDevice",{}).toString(); + if(r.backend.isEmpty()||r.playback.isEmpty()|| + r.backend.length()>160||r.capture.length()>250||r.playback.length()>250) { + out.error="Choose an actual playback device"; + return out; + } + const auto sample=config.getProperty("sampleRate",{}), + period=config.getProperty("bufferSize",{}); + if(!(sample.isInt()||sample.isInt64()||sample.isDouble())|| + !(period.isInt()||period.isInt64()||period.isDouble())) { + out.error="Rate and buffer must be numeric or AUTO (0)"; + return out; + } + r.rate=static_cast(sample); + r.block=static_cast(period); + if(!std::isfinite(r.rate)||!std::isfinite(r.block)|| + (r.rate!=0.&&(r.rate<8000.||r.rate>384000.))|| + (r.block!=0.&&(r.block<16.||r.block>8192.|| + std::floor(r.block)!=r.block))) { + out.error="Invalid device sample rate or buffer size"; + return out; + } + const auto assign=config.getProperty("assignSelectedPlaybackPinsToMain",false); + if(!assign.isBool()) { + out.error="Invalid MAIN playback pin selection"; + return out; + } + const auto confirm=config.getProperty("confirmRetainedPinMapping",false); + if(!confirm.isBool()) { + out.error="Invalid retained mixer mapping confirmation"; + return out; + } + r.assignMain=static_cast(assign); + r.confirmRetainedPinMapping=static_cast(confirm); + return out; + } + + static juce::String validateNames(const Request& r, + const juce::StringArray& inputs,const juce::StringArray& outputs, + bool separate) { + const bool outputOnly=separate&&r.capture.isEmpty(); + if((!outputOnly&&!inputs.contains(r.capture))|| + !outputs.contains(r.playback)|| + (!separate&&r.capture!=r.playback)) + return "Device names or duplex pairing are not reported by JUCE"; + return {}; + } + + // Do not narrow untrusted 64-bit UI values to int before testing bounds: + // a forged 2^32+N pin could otherwise alias an existing physical jack. + static bool parsePins(const juce::var& values,int limit,juce::BigInteger& mask) { + const auto* list=values.getArray(); + if(!list||list->size()>64||limit<0||limit>64)return false; + juce::BigInteger candidate; + for(const auto& value:*list) { + if(!(value.isInt()||value.isInt64()))return false; + const auto raw=static_cast(value); + if(raw<0||raw>=limit||candidate[static_cast(raw)])return false; + candidate.setBit(static_cast(raw)); + } + mask=candidate; + return true; + } + + static bool parsePinMasks(const juce::var& inputs,const juce::var& outputs, + int inputCount,int outputCount,bool outputOnly, + juce::BigInteger& inputMask,juce::BigInteger& outputMask) { + juce::BigInteger in,out; + if(!parsePins(inputs,juce::jmin(64,inputCount),in)|| + !parsePins(outputs,juce::jmin(64,outputCount),out)|| + (outputOnly&&!in.isZero())||out.countNumberOfSetBits()<2)return false; + inputMask=in;outputMask=out; + return true; + } + + struct AppliedReadback { + juce::AudioDeviceManager::AudioDeviceSetup actual; + juce::String backend; + bool open=false; + juce::BigInteger activeInputs,activeOutputs; + double deviceRate=0.; + int deviceBuffer=0; + }; + // The acknowledgement is not permission to output sound: it proves only + // that JUCE accepted the selected backend, names, masks, rate and period. + static bool matchesApplied(const Request& requested, + const juce::AudioDeviceManager::AudioDeviceSetup& candidate, + const AppliedReadback& live) noexcept { + const auto& a=live.actual; + return live.open&&live.backend==requested.backend&& + a.inputDeviceName==requested.capture&& + a.outputDeviceName==requested.playback&& + (requested.rate<=0.||std::abs(a.sampleRate-requested.rate)<=1.)&& + (requested.block<=0.||a.bufferSize==static_cast(requested.block))&& + (candidate.useDefaultInputChannels||a.inputChannels==candidate.inputChannels)&& + (candidate.useDefaultOutputChannels||a.outputChannels==candidate.outputChannels)&& + live.activeInputs==a.inputChannels&&live.activeOutputs==a.outputChannels&& + live.activeOutputs.countNumberOfSetBits()>=2&& + std::abs(live.deviceRate-a.sampleRate)<=1.&& + live.deviceBuffer==a.bufferSize; + } + + struct RollbackReadback { + juce::AudioDeviceManager::AudioDeviceSetup actual; + juce::String backend; + bool open=false; + juce::StringArray inputNames,outputNames; + }; + // Previously CLOSED driver is never a valid rollback target. For ASIO, + // even a numerically equal mask is unsafe after pin names are reordered. + static bool matchesRollback( + const juce::AudioDeviceManager::AudioDeviceSetup& before, + const juce::String& previousBackend, + const juce::StringArray& previousInputs, + const juce::StringArray& previousOutputs, + const RollbackReadback& live) noexcept { + const auto& a=live.actual; + return live.open&&live.backend==previousBackend&& + a.inputDeviceName==before.inputDeviceName&& + a.outputDeviceName==before.outputDeviceName&& + a.inputChannels==before.inputChannels&& + a.outputChannels==before.outputChannels&& + a.sampleRate==before.sampleRate&&a.bufferSize==before.bufferSize&& + (previousBackend!="ASIO"|| + (live.inputNames==previousInputs&&live.outputNames==previousOutputs)); + } + + using RecordPhase=std::function; + static juce::String openSelected(juce::AudioDeviceManager& manager, + const juce::String& backend, + const juce::AudioDeviceManager::AudioDeviceSetup& setup, + bool resetDefaults,const RecordPhase& record) { + if(manager.getCurrentAudioDeviceType()==backend&&!resetDefaults) { + if(auto* device=manager.getCurrentAudioDevice();device&&!device->isOpen()) + manager.closeAudioDevice(); + return manager.setAudioDeviceSetup(setup,true); + } + // setCurrentAudioDeviceType can open an unrelated remembered endpoint; + // initialise directly with the explicit backend and physical names. + auto xml=manager.createStateXml(); + if(!xml)xml=std::make_unique("DEVICESETUP"); + xml->setAttribute("deviceType",backend); + xml->removeAttribute("audioDeviceName"); + xml->setAttribute("audioInputDeviceName",setup.inputDeviceName); + xml->setAttribute("audioOutputDeviceName",setup.outputDeviceName); + xml->setAttribute("audioDeviceRate",setup.sampleRate); + xml->setAttribute("audioDeviceBufferSize",setup.bufferSize); + const auto setMask=[&](const char* key,bool defaults,const juce::BigInteger& mask) { + if(defaults)xml->removeAttribute(key); + else xml->setAttribute(key,mask.toString(2)); + }; + setMask("audioDeviceInChans",setup.useDefaultInputChannels,setup.inputChannels); + setMask("audioDeviceOutChans",setup.useDefaultOutputChannels,setup.outputChannels); + if(record)record("CLOSE_PREVIOUS | "+manager.getCurrentAudioDeviceType()); + manager.closeAudioDevice(); + if(record)record("OPEN_SELECTED | "+backend); + return manager.initialise(2,2,xml.get(),false); + } + +private: + bool busy_=false; // JUCE message thread, including nested ASIO modal dispatch +}; +} // namespace armix::device diff --git a/tests/native_device_apply_coordinator_test.cpp b/tests/native_device_apply_coordinator_test.cpp new file mode 100644 index 000000000..040f39b6d --- /dev/null +++ b/tests/native_device_apply_coordinator_test.cpp @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#ifdef NDEBUG +#undef NDEBUG +#endif +#include "../src/NativeDeviceApplyCoordinator.h" +#include +#include +#include + +using Coordinator=armix::device::NativeDeviceApplyCoordinator; +using Setup=juce::AudioDeviceManager::AudioDeviceSetup; + +static juce::var config(const juce::String& json) { + auto v=juce::JSON::parse(json); + assert(v.isObject()); + return v; +} + +int main() { + // Nested JUCE driver modal loops must reject another concurrent APPLY + // and release exactly once, including moved lease ownership. + Coordinator owner; + assert(!owner.busy()); + { + auto outer=owner.tryBegin(); + assert(outer && owner.busy()); + assert(!owner.tryBegin()); + auto moved=std::move(outer); + assert(!outer && moved); + assert(!owner.tryBegin()); + } + assert(!owner.busy()); + auto reacquired=owner.tryBegin(); + assert(reacquired && owner.busy()); + + const auto valid=config(R"({"backend":"ASIO","captureDevice":"ASIO Test", + "playbackDevice":"ASIO Test","sampleRate":48000,"bufferSize":256, + "assignSelectedPlaybackPinsToMain":true, + "confirmRetainedPinMapping":false})"); + const auto parsed=Coordinator::parse(valid); + assert(parsed); + const auto& request=parsed.value; + assert(request.backend=="ASIO" && request.rate==48000. && + request.block==256. && request.assignMain); + assert(Coordinator::validateNames(request,{"ASIO Test"},{"ASIO Test"},false).isEmpty()); + assert(Coordinator::validateNames(request,{"ASIO Test"},{"Other"},false).isNotEmpty()); + assert(Coordinator::validateNames(request,{"Different"},{"ASIO Test"},false).isNotEmpty()); + auto outputOnly=config(R"({"backend":"Windows Audio", + "captureDevice":"","playbackDevice":"Speakers", + "sampleRate":0,"bufferSize":0})"); + auto output=Coordinator::parse(outputOnly); + assert(output && output.value.rate==0. && output.value.block==0.); + assert(Coordinator::validateNames(output.value,{},{"Speakers"},true).isEmpty()); + assert(Coordinator::validateNames(output.value,{},{"Speakers"},false).isNotEmpty()); + for(const auto& invalid : { + "{}", R"({"backend":"ASIO","playbackDevice":"X","sampleRate":"48000","bufferSize":256})", + R"({"backend":"ASIO","playbackDevice":"X","sampleRate":4000,"bufferSize":256})", + R"({"backend":"ASIO","playbackDevice":"X","sampleRate":48000,"bufferSize":1.5})", + R"({"backend":"ASIO","playbackDevice":"X","sampleRate":48000,"bufferSize":8193})", + R"({"backend":"ASIO","playbackDevice":"X","sampleRate":48000,"bufferSize":256,"assignSelectedPlaybackPinsToMain":"yes"})", + R"({"backend":"ASIO","playbackDevice":"X","sampleRate":48000,"bufferSize":256,"confirmRetainedPinMapping":1})" + }) { + assert(!Coordinator::parse(juce::JSON::parse(juce::String(invalid)))); + } + + auto input=juce::JSON::parse("[0,2]"); + auto outputs=juce::JSON::parse("[1,3]"); + juce::BigInteger inMask,outMask; + assert(Coordinator::parsePinMasks(input,outputs,4,4,false,inMask,outMask)); + assert(inMask[0] && inMask[2] && outMask[1] && outMask[3]); + assert(!Coordinator::parsePinMasks(input,outputs,4,4,true,inMask,outMask)); + assert(Coordinator::parsePinMasks(juce::JSON::parse("[]"),outputs,4,4,true,inMask,outMask)); + assert(inMask.isZero()); + assert(!Coordinator::parsePinMasks(input,juce::JSON::parse("[0]"),4,4,false,inMask,outMask)); + assert(!Coordinator::parsePinMasks(input,juce::JSON::parse("[3,3]"),4,4,false,inMask,outMask)); + assert(!Coordinator::parsePinMasks(input,juce::JSON::parse("[1,-1]"),4,4,false,inMask,outMask)); + assert(!Coordinator::parsePinMasks(input,juce::JSON::parse("[0,5]"),4,4,false,inMask,outMask)); + juce::Array huge; + huge.add(juce::var(static_cast(1ull<<33))); + huge.add(juce::var(1)); + assert(!Coordinator::parsePinMasks(input,juce::var(huge),4,4,false,inMask,outMask)); + // An invalid request never partially overwrites the previous masks. + assert(inMask.isZero() && outMask[1] && outMask[3]); + + Setup candidate; + candidate.inputDeviceName="ASIO Test"; + candidate.outputDeviceName="ASIO Test"; + candidate.sampleRate=48000; + candidate.bufferSize=256; + candidate.useDefaultInputChannels=false; + candidate.useDefaultOutputChannels=false; + candidate.inputChannels.setBit(0); + candidate.outputChannels.setBit(0); + candidate.outputChannels.setBit(1); + Coordinator::AppliedReadback observed; + observed.backend="ASIO"; + observed.actual=candidate; + observed.open=true; + observed.activeInputs=candidate.inputChannels; + observed.activeOutputs=candidate.outputChannels; + observed.deviceRate=48000.; + observed.deviceBuffer=256; + assert(Coordinator::matchesApplied(request,candidate,observed)); + observed.actual.outputChannels.clearBit(1); + assert(!Coordinator::matchesApplied(request,candidate,observed)); + observed.actual=candidate; + observed.deviceBuffer=128; + assert(!Coordinator::matchesApplied(request,candidate,observed)); + observed.deviceBuffer=256; + observed.backend="Windows Audio"; + assert(!Coordinator::matchesApplied(request,candidate,observed)); + observed.backend="ASIO"; + observed.open=false; + assert(!Coordinator::matchesApplied(request,candidate,observed)); + + Coordinator::RollbackReadback rollback; + rollback.open=true; + rollback.backend="ASIO"; + rollback.actual=candidate; + rollback.inputNames={"Mic 1","Mic 2"}; + rollback.outputNames={"Monitor L","Monitor R"}; + assert(Coordinator::matchesRollback(candidate,"ASIO",rollback.inputNames, + rollback.outputNames,rollback)); + rollback.outputNames={"Monitor R","Monitor L"}; + assert(!Coordinator::matchesRollback(candidate,"ASIO", + {"Mic 1","Mic 2"},{"Monitor L","Monitor R"},rollback)); + rollback.outputNames={"Monitor L","Monitor R"}; + rollback.open=false; + assert(!Coordinator::matchesRollback(candidate,"ASIO", + rollback.inputNames,rollback.outputNames,rollback)); + std::cout<<"Native device Apply preflight/rollback: PASS\n"; +} From 51da4e9d21d1ead8f6d859d92f4f0a853c69e21d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 11 Nov 2026 03:34:29 +0700 Subject: [PATCH 2/4] test(device): assert output-only pin validation at new coordinator seam --- tests/approved_native_m2_contract.test.cjs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 245391ffa..952b44938 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1293,10 +1293,13 @@ test("P0 built-in EQ/Compressor/Harmony load independent of slow external VST3 c }); test("P0 output-only Audio I/O is a real native configuration, never blocked by missing capture",()=>{ const cpp=read("src/Main.cpp"),bridge=read("web/approved-native-bridge.js"); + const apply=read("src/NativeDeviceApplyCoordinator.h"); assert.match(cpp,/const bool outputOnly=separate&&capture\.isEmpty\(\)/); assert.match(cpp,/candidate\.useDefaultInputChannels=!outputOnly/); assert.match(cpp,/if\(outputOnly\)candidate\.inputChannels\.clear\(\)/); - assert.match(cpp,/\(outputOnly&&!inMask\.isZero\(\)\)/); + assert.match(cpp,/NativeDeviceApplyCoordinator::parsePinMasks/); + assert.match(apply,/\(outputOnly&&!in\.isZero\(\)\)/); + assert.match(apply,/out\.countNumberOfSetBits\(\)<2/); assert.doesNotMatch(cpp,/opened->getActiveInputChannels\(\)\.countNumberOfSetBits\(\)<1/); assert.match(bridge,/No hardware input \(Player \/ FX\)/); assert.match(bridge,/t\?\.separate\?\["",\.\.\.\(t\.inputs\|\|\[\]\)\]/); From 6f4ff82b5c56fbab055cb89b2ab03d42276d1264 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 11 Nov 2026 03:35:38 +0700 Subject: [PATCH 3/4] test(device): keep JUCE open and rollback invariants at extracted owner --- tests/mixer_io_operator_contract_test.mjs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index e6601d109..04a355a82 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -204,12 +204,14 @@ test('DEVICE1 existing matrix drives real JUCE manager with gated native readbac assert.match(native,/action == "audioDeviceApply"/); const open=native.slice(native.indexOf('juce::String openSelectedAudioDevice('), native.indexOf('void applyCustomAudioDevice(')); + const coordinator=read('src/NativeDeviceApplyCoordinator.h'); + assert.match(open,/NativeDeviceApplyCoordinator::openSelected/); assert.match(native,/openSelectedAudioDevice\(typeName,candidate\)/); assert.match(native,/openSelectedAudioDevice\(previousType,before\)/); - assert.match(open,/setAudioDeviceSetup\(setup,true\)/); - assert.match(open,/manager\.initialise\(2,2,xml\.get\(\),false\)/); - assert.match(open,/manager\.closeAudioDevice\(\);[\s\S]*manager\.initialise/); - assert.doesNotMatch(open,/manager\.setCurrentAudioDeviceType\(/); + assert.match(coordinator,/setAudioDeviceSetup\(setup,true\)/); + assert.match(coordinator,/manager\.initialise\(2,2,xml\.get\(\),false\)/); + assert.match(coordinator,/manager\.closeAudioDevice\(\);[\s\S]*manager\.initialise/); + assert.doesNotMatch(coordinator,/manager\.setCurrentAudioDeviceType\(/); assert.match(native,/beginManualAudioSetup\(\)/); assert.match(native,/finishManualAudioSetup\(bindingMode!=MixerBindingMode::verifiedMainPinApply\)/); assert.match(native,/RESTORED_MUTED/); From 02b7c2d25af47b874e5734984f0edf6917397b31 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 11 Nov 2026 03:36:41 +0700 Subject: [PATCH 4/4] test(device): verify moved hardware readback gates at native coordinator --- tests/mixer_io_operator_contract_test.mjs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index 04a355a82..58e725d5e 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -306,6 +306,7 @@ test('P0 FIRST SOUND raw capture has per-pin native callback truth BEFORE route test('P0 MAONO: one APPLY MUTE-ACKs before switching and native ARM',()=>{ const js=read('web/mixer-io.js'); const main=read('src/Main.cpp'); + const applyOwner=read('src/NativeDeviceApplyCoordinator.h'); const engine=read('src/LiveAudioEngine.h'); const start=js.indexOf('const deviceSwitchBlocker=s=>'); const end=js.indexOf('function deviceApply()',start); @@ -322,8 +323,10 @@ test('P0 MAONO: one APPLY MUTE-ACKs before switching and native ARM',()=>{ assert.match(js,/disabled=!!deviceBlocker\|\|deviceBusy\|\|applyMutePending/); assert.match(js,/deviceNote=ack\?\.ok\?'DEVICE ACCEPTED · OUTPUT MUTED · '\+devicePinNextStep\(\)/); assert.match(main,/!engine_\.allOutputsDisarmed\(\)/); - assert.match(main,/opened->getActiveInputChannels\(\)!=actual\.inputChannels/); - assert.match(main,/opened->getCurrentSampleRate\(\)-actual\.sampleRate/); + assert.match(main,/NativeDeviceApplyCoordinator::matchesApplied/); + assert.match(main,/observed\.activeInputs=opened->getActiveInputChannels\(\)/); + assert.match(applyOwner,/live\.activeInputs==a\.inputChannels/); + assert.match(applyOwner,/std::abs\(live\.deviceRate-a\.sampleRate\)/); assert.match(engine,/return isOutputMuted\(\) && !secondaryOutput_\.armed\(\)/); const standalone=read('AR-MIX-Live-FX-Host-Standalone-v0.3.html'); const jsTag='