From 2d426a91f17cb51ce9ef7609ba733e48c9d6f496 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 11 Nov 2026 04:07:16 +0700 Subject: [PATCH] refactor(device): serialize native modal setup with Apply and ASIO recovery --- docs/architecture/README.md | 1 + src/Main.cpp | 38 +++++++++++++++---- src/NativeDeviceApplyCoordinator.h | 17 ++++++--- tests/mixer_io_operator_contract_test.mjs | 18 +++++++++ .../native_device_apply_coordinator_test.cpp | 30 +++++++++++++++ 5 files changed, 91 insertions(+), 13 deletions(-) diff --git a/docs/architecture/README.md b/docs/architecture/README.md index a47cce96f..402569d05 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -37,6 +37,7 @@ Assembled /preview/ DOM (presentation only) | 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 | +| Modal setup transaction (M2b) | src/Main.cpp::showDeviceSetup; NativeDeviceApplyCoordinator.h | Persistent one-owner lease across visible JUCE selector, explicit Apply and automatic ASIO restart; repeated Setup clicks never re-mute; selector close completes readback/rebind before releasing lease | | 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 ebbb1d217..5e1218e3b 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -353,6 +353,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr orbit_.stop(); catalog_.onChanged = nullptr; closePluginEditor(); + // Tear down the modal transaction first. A closing window must not + // re-enter device rebind while ConsoleWindow is being destroyed. + audioSetupLease_.reset(); audioSetupWindow_.reset(); engine_.devices().removeChangeListener (this); // Drain any earlier file work before the final muted checkpoint. @@ -471,6 +474,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr armix::mixer::NativeMusicTempoMonitor::State lastMusicTempo_{}; std::unique_ptr editorWindow_; std::unique_ptr audioSetupWindow_; + // Persistent modal lease: blocks an Apply/ASIO restart while JUCE's + // device selector is open, not merely during the initial show() call. + std::optional audioSetupLease_; juce::String startupError_, lastAudioXml_; bool initialStateSent_ = false; bool consoleSubscribed_ = false; // Real snapshot subscription; not FAT certification @@ -1622,7 +1628,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr browser_.emitEventIfBrowserIsVisible("arMixAudioDeviceApplyAck",juce::var(ack.release())); return; } - auto applying=deviceApply_.tryBegin(); + auto applying=deviceApply_.tryBegin( + armix::device::NativeDeviceApplyCoordinator::Purpose::explicitApply); 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, @@ -1903,13 +1910,25 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr { diagnostics_.record ("SETUP", "Open audio device setup"); if (setupLaunching_) return; - // Suspend physical output but retain ALL authored mixer state while - // the real JUCE device selector is visible (including no-change close). + // Repeated clicks must not re-suspend output or discard a pending + // preserve-monitor intention. The selector itself is already active. + if (audioSetupWindow_ && audioSetupWindow_->isVisible()) { + audioSetupWindow_->toFront(true); + return; + } + auto modalLease=deviceApply_.tryBegin( + armix::device::NativeDeviceApplyCoordinator::Purpose::setupDialog); + if(!modalLease) { + emitNotice("Finish the active audio device change first.",true); + return; + } + audioSetupLease_.emplace(std::move(modalLease)); + // Hold a lease for the WHOLE modal selection, including ASIO's + // nested dispatcher and the final accepted mixer rebind. autoMainEpoch_=0; engine_.beginManualAudioSetup(true); - // The native JUCE device list is cached after first construction: - // reopening the settings window avoids repeating full widget setup. + // Reuse cached JUCE selector without creating another DeviceManager. if (audioSetupWindow_ != nullptr) { audioSetupWindow_->setVisible (true); @@ -1926,7 +1945,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr std::make_unique (safe->engine_.devices(), [safe] { - if (safe == nullptr) return; + if (safe == nullptr || !safe->audioSetupLease_) return; + // Keep the transaction reserved until the selector + // close has completed rebind, native readback and ACK. + auto closingLease=std::move(*safe->audioSetupLease_); + safe->audioSetupLease_.reset(); if (safe->finishAudioSetupAndRecoverMixer()) { safe->requestAutomaticMain(!safe->engine_.takeAsioResetMonitorIntent()); @@ -5736,7 +5759,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 - auto applying=deviceApply_.tryBegin(); + auto applying=deviceApply_.tryBegin( + armix::device::NativeDeviceApplyCoordinator::Purpose::asioRecovery); if(!applying)return; if(!device || !device->isOpen() || device->getActiveOutputChannels().countNumberOfSetBits()<2) { diff --git a/src/NativeDeviceApplyCoordinator.h b/src/NativeDeviceApplyCoordinator.h index 118b54ecf..9948652eb 100644 --- a/src/NativeDeviceApplyCoordinator.h +++ b/src/NativeDeviceApplyCoordinator.h @@ -14,6 +14,10 @@ namespace armix::device { // The host still owns physical output permission and session rebind/rollback. class NativeDeviceApplyCoordinator final { public: + // Every possible JUCE driver mutation uses the same control-thread gate: + // explicit UI Apply, native modal selector, and bounded ASIO recovery. + enum class Purpose : std::uint8_t { none, explicitApply, setupDialog, asioRecovery }; + class Lease final { public: Lease() noexcept = default; @@ -21,7 +25,7 @@ class NativeDeviceApplyCoordinator final { 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;} + ~Lease() {if(owner_)owner_->purpose_=Purpose::none;} explicit operator bool() const noexcept {return owner_!=nullptr;} private: friend class NativeDeviceApplyCoordinator; @@ -29,10 +33,11 @@ class NativeDeviceApplyCoordinator final { NativeDeviceApplyCoordinator* owner_=nullptr; }; - bool busy() const noexcept {return busy_;} - [[nodiscard]] Lease tryBegin() noexcept { - if(busy_)return {}; - busy_=true; + bool busy() const noexcept {return purpose_!=Purpose::none;} + Purpose activePurpose() const noexcept {return purpose_;} + [[nodiscard]] Lease tryBegin(Purpose purpose=Purpose::explicitApply) noexcept { + if(purpose==Purpose::none || busy())return {}; + purpose_=purpose; return Lease(this); } @@ -215,6 +220,6 @@ class NativeDeviceApplyCoordinator final { } private: - bool busy_=false; // JUCE message thread, including nested ASIO modal dispatch + Purpose purpose_=Purpose::none; // JUCE message thread; one driver transaction }; } // namespace armix::device diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index 58e725d5e..418eb54d8 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -683,3 +683,21 @@ test('offline checkpoints stay protected until verified native restore',()=>{ assert.match(control,/workspace_=std::move\(\*candidate\);[\s\S]*?checkpointSaved_\(workspace_.document\(\).id\)/); assert.match(save,/if\(automatic&&mixerSessionRecoveryPending_\)[\s\S]*?return "[^"]+";[\s\S]*?captureNativeMixerSession/); }); + +// Exact control-thread serialization source contract for nested JUCE modal loops. +test('M2b native AUDIO SETUP holds one lease through visible selection and rebind',()=>{ + const cpp=read('src/Main.cpp'); + const owner=read('src/NativeDeviceApplyCoordinator.h'); + const setup=cpp.slice(cpp.indexOf('void showDeviceSetup()'), + cpp.indexOf('// A Windows native Explorer picker',cpp.indexOf('void showDeviceSetup()'))); + assert.match(setup,/audioSetupWindow_ && audioSetupWindow_->isVisible\(\)/); + assert.match(setup,/deviceApply_\.tryBegin\([\s\S]*?Purpose::setupDialog/); + assert.match(setup,/audioSetupLease_\.emplace\(std::move\(modalLease\)\)/); + assert.match(setup,/engine_\.beginManualAudioSetup\(true\)/); + assert.match(setup,/auto closingLease=std::move\(\*safe->audioSetupLease_\)/); + assert.match(setup,/safe->finishAudioSetupAndRecoverMixer\(\)/); + assert.match(owner,/enum class Purpose : std::uint8_t/); + assert.match(cpp,/Purpose::asioRecovery/); + assert.match(cpp,/Purpose::explicitApply/); + assert.doesNotMatch(setup,/\.closeAudioDevice\(/); +}); diff --git a/tests/native_device_apply_coordinator_test.cpp b/tests/native_device_apply_coordinator_test.cpp index 040f39b6d..6be22a992 100644 --- a/tests/native_device_apply_coordinator_test.cpp +++ b/tests/native_device_apply_coordinator_test.cpp @@ -6,6 +6,7 @@ #include #include #include +#include using Coordinator=armix::device::NativeDeviceApplyCoordinator; using Setup=juce::AudioDeviceManager::AudioDeviceSetup; @@ -32,6 +33,35 @@ int main() { assert(!owner.busy()); auto reacquired=owner.tryBegin(); assert(reacquired && owner.busy()); + assert(owner.activePurpose()==Coordinator::Purpose::explicitApply); + // A JUCE modal dialog must reserve the SAME coordinator for its entire + // visible lifecycle, not just the showDeviceSetup call stack. + Coordinator modalOwner; + std::optional visibleSetup; + auto lease=modalOwner.tryBegin(Coordinator::Purpose::setupDialog); + assert(lease); + visibleSetup.emplace(std::move(lease)); + assert(modalOwner.busy() && + modalOwner.activePurpose()==Coordinator::Purpose::setupDialog); + assert(!modalOwner.tryBegin(Coordinator::Purpose::explicitApply)); + assert(!modalOwner.tryBegin(Coordinator::Purpose::asioRecovery)); + assert(!modalOwner.tryBegin(Coordinator::Purpose::setupDialog)); + // During the close callback move out the lease. New actions must remain + // rejected until the final hardware readback/rebind finishes. + { + auto closing=std::move(*visibleSetup); + visibleSetup.reset(); + assert(modalOwner.busy()); + assert(!modalOwner.tryBegin(Coordinator::Purpose::explicitApply)); + } + assert(!modalOwner.busy() && + modalOwner.activePurpose()==Coordinator::Purpose::none); + assert(!modalOwner.tryBegin(Coordinator::Purpose::none)); + { + auto restart=modalOwner.tryBegin(Coordinator::Purpose::asioRecovery); + assert(restart && !modalOwner.tryBegin(Coordinator::Purpose::setupDialog)); + } + assert(!modalOwner.busy()); const auto valid=config(R"({"backend":"ASIO","captureDevice":"ASIO Test", "playbackDevice":"ASIO Test","sampleRate":48000,"bufferSize":256,