Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions docs/architecture/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
178 changes: 64 additions & 114 deletions src/Main.cpp

Large diffs are not rendered by default.

220 changes: 220 additions & 0 deletions src/NativeDeviceApplyCoordinator.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
// SPDX-License-Identifier: AGPL-3.0-only
#pragma once
#include <juce_audio_devices/juce_audio_devices.h>
#include <cmath>
#include <cstdint>
#include <functional>
#include <memory>
#include <utility>

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<double>(sample);
r.block=static_cast<double>(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<bool>(assign);
r.confirmRetainedPinMapping=static_cast<bool>(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<std::int64_t>(value);
if(raw<0||raw>=limit||candidate[static_cast<int>(raw)])return false;
candidate.setBit(static_cast<int>(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<int>(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<void(const juce::String&)>;
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<juce::XmlElement>("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
5 changes: 4 additions & 1 deletion tests/approved_native_m2_contract.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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\|\|\[\]\)\]/);
Expand Down
28 changes: 19 additions & 9 deletions tests/mixer_io_operator_contract_test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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/);
Expand Down Expand Up @@ -304,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);
Expand All @@ -320,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='<script id="arsonmix-mixer-io-js">';
Expand All @@ -337,6 +342,7 @@ test('P0 MAONO: one APPLY MUTE-ACKs before switching and native ARM',()=>{

test('DEVICE2 native device list is cached on overlay open; explicit scan is fail-closed',()=>{
const native=read('src/Main.cpp'),gui=read('web/mixer-io.js');
const applyOwner=read('src/NativeDeviceApplyCoordinator.h');
const section=native.slice(native.indexOf('else if (action == "audioDeviceInventory")'),
native.indexOf('else if (action == "audioDeviceApply")'));
assert.match(section,/emitDeviceInventory\(false\)/);
Expand All @@ -353,9 +359,13 @@ test('DEVICE2 native device list is cached on overlay open; explicit scan is fai
assert.match(gui,/SCAN_ERROR|BLOCKED_ARMED/);
const apply=native.slice(native.indexOf('void applyCustomAudioDevice('),
native.indexOf('void showDeviceSetup()',native.indexOf('void applyCustomAudioDevice(')));
assert.match(apply,/opened->getActiveInputChannels\(\)!=actual\.inputChannels/);
assert.match(apply,/opened->getActiveOutputChannels\(\)!=actual\.outputChannels/);
assert.match(apply,/opened->getCurrentBufferSizeSamples\(\)!=actual\.bufferSize/);
assert.match(apply,/NativeDeviceApplyCoordinator::matchesApplied/);
assert.match(apply,/observed\.activeInputs=opened->getActiveInputChannels\(\)/);
assert.match(apply,/observed\.activeOutputs=opened->getActiveOutputChannels\(\)/);
assert.match(apply,/observed\.deviceBuffer=opened->getCurrentBufferSizeSamples\(\)/);
assert.match(applyOwner,/live\.activeInputs==a\.inputChannels/);
assert.match(applyOwner,/live\.activeOutputs==a\.outputChannels/);
assert.match(applyOwner,/live\.deviceBuffer==a\.bufferSize/);
});

test('SOURCE2 selected-channel popover selects verified physical ports without a second router',()=>{
Expand Down
Loading
Loading