From 33f4c8d9609f839f93db95fb846b7dd86a12bdb7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 08:23:07 +0700 Subject: [PATCH 1/2] feat(audio): reconcile opt-in ten-channel DRY routing lab onto current main --- .github/workflows/p1-windows.yml | 3 +- CMakeLists.txt | 5 +- ...1E_CURRENT_MAIN_RECONCILIATION_20261028.md | 16 + docs/P1E_NATIVE_DRY_LAB_FAT_20261028.md | 36 +++ engine/core/RealtimeRoutePublisher.h | 136 ++++++++ engine/device/LiveInputPortRegistry.h | 63 ++++ src/LiveAudioEngine.h | 71 ++++ src/LiveDryRoutingLab.h | 306 ++++++++++++++++++ src/Main.cpp | 30 ++ tests/live_port_epoch_publisher_test.cpp | 124 +++++++ tests/live_routing_ui_contract_test.mjs | 46 +++ web/monitor.js | 133 +++++++- 12 files changed, 961 insertions(+), 8 deletions(-) create mode 100644 docs/ARD_P1E_CURRENT_MAIN_RECONCILIATION_20261028.md create mode 100644 docs/P1E_NATIVE_DRY_LAB_FAT_20261028.md create mode 100644 engine/core/RealtimeRoutePublisher.h create mode 100644 engine/device/LiveInputPortRegistry.h create mode 100644 src/LiveDryRoutingLab.h create mode 100644 tests/live_port_epoch_publisher_test.cpp create mode 100644 tests/live_routing_ui_contract_test.mjs diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index b37d88b6f..7ec8dae79 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -78,6 +78,7 @@ jobs: 'tests/native_artifact_packaging_contract_test.mjs' 'tests/portable_workspace_contract_test.mjs' 'tests/plugin_vault_contract_test.mjs' + 'tests/live_routing_ui_contract_test.mjs' 'tests/studio_backup_contract_test.mjs' ) node --test $contracts @@ -90,7 +91,7 @@ jobs: -DBUILD_TESTING=ON -DJUCE_WEBVIEW2_PACKAGE_LOCATION="${{ github.workspace }}/.deps" - name: Build executable and native RT tests - run: cmake --build build --config Release --target ARMixConsole ARMixMixerRoutingTests ARMixChannelRoutingContractTests ARMixChannelSendTests ARMixPreparedMixerBlockTests ARMixWorkspaceTests ARMixVaultTests ARMixBackupTests ARMixOrbitPhaseTests ARMixOrbitControlTests ARMixOrbitMotionTests ARMixOrbitDistanceTests ARMixFxBypassEnvelopeTests ARMixDearVrPolarPolicyTests ARMixRTTests ARMixPresetTests ARMixDiagnosticTests ARMixClockBridgeTests ARMixVirtualClockSoakTests ARMixCadenceTests ARMixCrackleWindowTests ARMixHealthTests ARMixPolicyTests ARMixPeriodEvidenceTests ARMixLifecycleTests ARMixWasapiProbeTests ARMixDualJuceTests ARMixClockSizingTests ARMixIndependentFormatTests ARMixRecoveryTests ARMixStreamWatchdogTests ARMixBridgeContinuityTests ARMixEndpointPolicyTests ARMixEndpointGuardTests ARMixAsioPolicyTests ARMixAsioBackendTests ARMixAsioRegistryIdentityTests ARMixDirectFenceTests --parallel 2 + run: cmake --build build --config Release --target ARMixConsole ARMixMixerRoutingTests ARMixChannelRoutingContractTests ARMixChannelSendTests ARMixPreparedMixerBlockTests ARMixLiveRoutingEpochTests ARMixWorkspaceTests ARMixVaultTests ARMixBackupTests ARMixOrbitPhaseTests ARMixOrbitControlTests ARMixOrbitMotionTests ARMixOrbitDistanceTests ARMixFxBypassEnvelopeTests ARMixDearVrPolarPolicyTests ARMixRTTests ARMixPresetTests ARMixDiagnosticTests ARMixClockBridgeTests ARMixVirtualClockSoakTests ARMixCadenceTests ARMixCrackleWindowTests ARMixHealthTests ARMixPolicyTests ARMixPeriodEvidenceTests ARMixLifecycleTests ARMixWasapiProbeTests ARMixDualJuceTests ARMixClockSizingTests ARMixIndependentFormatTests ARMixRecoveryTests ARMixStreamWatchdogTests ARMixBridgeContinuityTests ARMixEndpointPolicyTests ARMixEndpointGuardTests ARMixAsioPolicyTests ARMixAsioBackendTests ARMixAsioRegistryIdentityTests ARMixDirectFenceTests --parallel 2 - name: Test realtime control primitives run: ctest --test-dir build -C Release --output-on-failure - name: Package verified JUCE GUI for hardware FAT diff --git a/CMakeLists.txt b/CMakeLists.txt index f5831b624..d4a775b17 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,7 +19,7 @@ juce_add_gui_app(ARMixConsole juce_add_binary_data(ARMixAssets SOURCES web/index.html web/styles.css web/app.js web/bridge.js web/monitor.js) -target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/VstOrbitController.h engine/core/MixerRoutingPlan.h engine/core/ChannelRoutingContract.h engine/core/ChannelSendPlan.h engine/core/PreparedMixerBlock.h engine/core/OrbitPhase.h engine/core/OrbitControlPolicy.h engine/core/OrbitMotion.h engine/core/OrbitDistanceMapping.h engine/core/DearVrPolarPolicy.h src/PluginCatalog.h src/PluginVault.h src/PortableWorkspace.h src/StudioBackup.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/core/CallbackCadenceEvidence.h engine/diagnostics/CrackleEvidenceWindow.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h engine/device/PeriodCapabilityEvidence.h engine/device/SessionLifecycle.h engine/device/WasapiCapabilityProbe.h engine/device/JuceIndependentClockDevice.h engine/device/ClockBridgeSizing.h engine/device/IndependentStreamFormatFence.h engine/device/DirectRestoreBackoff.h engine/device/IndependentStreamWatchdog.h engine/device/BridgeContinuityGate.h engine/device/EndpointIdentityPolicy.h engine/device/WasapiEndpointIdentityGuard.h engine/device/AsioStartupPolicy.h engine/device/AsioPriorityDeviceManager.h engine/device/AsioRegistrationPolicy.h engine/device/AsioRegistryIdentityProbe.h engine/device/DirectRouteFence.h) +target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/VstOrbitController.h engine/core/MixerRoutingPlan.h engine/core/ChannelRoutingContract.h engine/core/ChannelSendPlan.h engine/core/PreparedMixerBlock.h engine/core/RealtimeRoutePublisher.h engine/device/LiveInputPortRegistry.h src/LiveDryRoutingLab.h engine/core/OrbitPhase.h engine/core/OrbitControlPolicy.h engine/core/OrbitMotion.h engine/core/OrbitDistanceMapping.h engine/core/DearVrPolarPolicy.h src/PluginCatalog.h src/PluginVault.h src/PortableWorkspace.h src/StudioBackup.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/core/CallbackCadenceEvidence.h engine/diagnostics/CrackleEvidenceWindow.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h engine/device/PeriodCapabilityEvidence.h engine/device/SessionLifecycle.h engine/device/WasapiCapabilityProbe.h engine/device/JuceIndependentClockDevice.h engine/device/ClockBridgeSizing.h engine/device/IndependentStreamFormatFence.h engine/device/DirectRestoreBackoff.h engine/device/IndependentStreamWatchdog.h engine/device/BridgeContinuityGate.h engine/device/EndpointIdentityPolicy.h engine/device/WasapiEndpointIdentityGuard.h engine/device/AsioStartupPolicy.h engine/device/AsioPriorityDeviceManager.h engine/device/AsioRegistrationPolicy.h engine/device/AsioRegistryIdentityProbe.h engine/device/DirectRouteFence.h) target_compile_definitions(ARMixConsole PRIVATE JUCE_WEB_BROWSER=1 JUCE_USE_WIN_WEBVIEW2=1 @@ -59,6 +59,9 @@ if(BUILD_TESTING) add_executable(ARMixPreparedMixerBlockTests tests/prepared_mixer_block_test.cpp) target_compile_features(ARMixPreparedMixerBlockTests PRIVATE cxx_std_20) add_test(NAME TenChannelEndToEndPreparedAudioRender COMMAND ARMixPreparedMixerBlockTests) + add_executable(ARMixLiveRoutingEpochTests tests/live_port_epoch_publisher_test.cpp) + target_compile_features(ARMixLiveRoutingEpochTests PRIVATE cxx_std_20) + add_test(NAME P1ELivePortGenerationRevisionAndRealtimeRetirement COMMAND ARMixLiveRoutingEpochTests) add_executable(ARMixOrbitPhaseTests tests/orbit_phase_test.cpp) target_compile_features(ARMixOrbitPhaseTests PRIVATE cxx_std_20) add_test(NAME VstAzimuthOrbitRamp COMMAND ARMixOrbitPhaseTests) diff --git a/docs/ARD_P1E_CURRENT_MAIN_RECONCILIATION_20261028.md b/docs/ARD_P1E_CURRENT_MAIN_RECONCILIATION_20261028.md new file mode 100644 index 000000000..97150cf3a --- /dev/null +++ b/docs/ARD_P1E_CURRENT_MAIN_RECONCILIATION_20261028.md @@ -0,0 +1,16 @@ +# P1E integration reconciliation — 2026-10-28 + +## Source of truth and reasons for a fresh branch +Base: `main@61b2971e2be276c7b4e7fa034b64640ae1ef848e`, including folded-metal fader #120, fast-fall/ease-out meter #106, independent MASTER L/R, latest Orbit/capture #105, de-click #107, backup #116, P1D #114, pre-fader hardening #118, lean native CI #101. + +The original P1E PR #119 had Windows native CI PASS [40608546403](https://github.com/masarray/arsonmix/actions/runs/40608546403) but browser UI smoke FAIL [40608546037](https://github.com/masarray/arsonmix/actions/runs/40608546037). Its `tests/ui_smoke.py` was stale and failed at a preexisting peakHold assertion (`Boolean(peakHold.masterL) is False`); #119 has no UI smoke file diff. Its source branch was built atop earlier `main@4951f3b`, before later main fader changes. + +We compared the blob SHA at that base and the newest main for **every P1E-modified existing file**: `.github/workflows/p1-windows.yml`, `CMakeLists.txt`, `src/Main.cpp`, `src/LiveAudioEngine.h`, `web/monitor.js`. All five were byte-identical on latest main and old base. Thus their exact P1E candidate blobs can be safely reused; the other six files are additive P1E-only. This integration intentionally retains **all remaining file blobs from latest main**, especially the validated `tests/ui_smoke.py`, `web/app.js`, `web/bridge.js`, `web/styles.css`, fader CSS, and Orbit assets. No merge of old PR branch history or old test baseline. + +## Actual scope +The opt-in **SIGNAL CHECK → DRY ROUTING LAB** provides real physical ASIO/WASAPI enabled input-channel mapping into independent 10-strip dry DSP through the preallocated P1D `PreparedMixerBlock`. Operator mute, zero loaded VST3, DIRECT route, no independent clock, native epoch and graph revision/ACK, stale-device fail-closed behavior are required. C++ route publisher uses a single atomic writer/read reservation gate and off-RT reclamation. Native callback path remains ordinary CH1 VST3 when LAB is off, and no unsupported GUI multi-VST3 claims are added. Failure, unconnected input or stale port mapping must produce silence, not fake VU activity. + +## Tests and risk gates +The exact newly integrated head must run the **same** full Chromium/Firefox/Orbit GUI smoke currently green on main, native Node route contract, Windows MSVC/CTest and real executable packaging. Verify output against latest original main tree for unrelated visual source blobs. No additional CI matrices or jobs. + +Do **not** claim full production 10-channel VST3, 2-AUX runtime processing, plugin graph live swap, or #15 zero-VST crackle hardware pass. P1E is operator-controlled DRY hardware FAT only. Physical Windows ASIO/WASAPI inputs, buffer dropouts, latency, mute transition and routing status must be tested on owner's actual interface. Avoid arbitrarily modifying old PR #102 FX drag engine, source fader image or Orbit; use current main as owner. diff --git a/docs/P1E_NATIVE_DRY_LAB_FAT_20261028.md b/docs/P1E_NATIVE_DRY_LAB_FAT_20261028.md new file mode 100644 index 000000000..97c7d714a --- /dev/null +++ b/docs/P1E_NATIVE_DRY_LAB_FAT_20261028.md @@ -0,0 +1,36 @@ +# P1E — REAL 10-CHANNEL DRY ASIO/WASAPI FAT LAB (2026-10-28) + +**Native code, not just another offline graph.** The owner-approved ten-strip P1D `PreparedMixerBlock` is now callable from the live JUCE audio callback in a **separate, explicit, fail-closed DRY ROUTING LAB**. This milestone exists to prove **actual physical input channel separation, mono/stereo hardware patching, routing graph activation and Windows device continuity**, while preserving the current VST3 CH1 production path whenever the lab is OFF. + +**The lab is not a finished performance mixer.** It deliberately has NO VST3 inserts, AUX sends, independent channel fader binding, automatic portable device map restore, multi-output patchbay, PDC or FX Tail guarantees. CH2–CH10 rack buttons remain truthful preview. Never advertise ten live VST3 chains or approved #15 zero-FX crackle status based on this PR alone. + +## Open it on real Windows hardware + +1. Build Windows artifact from **the passing P1E PR head**, do NOT use a stale previously downloaded build. Set headphone volume physically LOW. +2. In **AUDIO SETUP**, choose and verify the actual ASIO/WASAPI DIRECT interface and enable the needed physical input channels in its active input mask. Do not expect `initialise(1,2)` to activate all channels automatically. +3. If a VST3 was loaded in CH1, save/stop it and remove it from the chain before the dry test. Disable Smart Clock / independent capture/render, set SIGNAL CHECK to NORMAL, and leave the verified DIRECT route selected. +4. Open **SIGNAL CHECK**, click **MUTE OUTPUT**, then **ROUTING LAB · 10 CH**. Only channels reported from the **actual opened device's enabled input-channel bitmask** appear in the selectors. If the port you need does not appear, enable it in AUDIO SETUP, which may restart the device; do not lie with phantom dropdown ports. +5. Example with an active 8-input interface: set CH1 **MONO** input 3; CH2 **STEREO** input 5(L) / 6(R); CH3 **MONO** input 1. All other CH4–CH10 **NONE**. Choose a low initial per-strip level, e.g. −18 or −12 dB. Press **APPLY TO NATIVE AUDIO**; wait for explicit native ACK, never infer audio commit from UI selection alone. +6. Close the routing lab, go back to SIGNAL CHECK, and deliberately **UNMUTE OUTPUT**. Stimulate each physical input separately and confirm that only the corresponding path is heard. Then try nonadjacent L/R mappings, duplicate input fanout and a muted/None channel. +7. MUTE OUTPUT and press **STOP LAB**. STOP also forces output mute before returning to the original CH1 VST3 engine; unmute only after selecting/validating the wanted signal path. + +### Safety and determinism + +- The lab has a separate exact input registry: `juce::BigInteger activeInputChannels` is enumerated **off callback**, mapping actual hardware ID to JUCE's packed callback pointer index. Callback channel count is checked against the prepared map for every buffer. Max 256 enabled pins accepted; larger counts fail closed. +- A monotonic **device epoch** invalidates prepared routes on device stop/restart. An active lab with a stale device does NOT fall through to old CH1 audio; it outputs silence until the operator explicitly reapplies or stops the lab. UI shows **DRY LAB STALE — SILENT**. +- Graphs compile on the message/control thread; a single atomic pointer is published with `expectedRevision` and `deviceEpoch`. Callback obtains a no-heap lease before accessing the prepared graph. Old buffers are retired only when all callback readers leave. Excess rapid edits receive a specific retry response instead of freeing audio-owned memory. +- Channel processing is bounded, uses P1D's preallocated fixed workspace, has no VST instantiation or lock in the audio callback. Variable callback quanta are chunked into the prepared hard-frame limit. On invalid buffer or stale epoch, output must be silence. +- An initial 256-sample bounded de-click fade on a new route revision starts at the previously emitted output sample. This is a topology-switch mitigation, **not yet proof of click-free behavior at any buffer rate/driver**. +- MUTE OUTPUT is a *required precondition* of every APPLY; there is never an automatic audible route to an unknown speaker. STOP forces output mute. FX add/remove, preset recall, Smart Clock mode and other diagnostic modes are blocked while LAB is active. +- The lab sends dry output to actual render callback channels 1 and 2 (0-based indices 0/1); additional output channels are cleared. No hidden ASRC/split-clock buffering is introduced on a direct ASIO path. +- If the selected input is no longer available, no plugin can synthesize signal from a dummy channel and callback output remains silent. No route is persisted to a future machine until endpoint/physical-port identities have been verified by a portable-source migration workflow. + +## Engineering validation + +`ARMixLiveRoutingEpochTests` includes sparse 5/2/9 input mapping, duplicate/invalid masks, generation mismatch, revisions, ABA-safe reader-held graph lifetime, full retirement queue and explicit STOP fail-closed, 8,000 sequential publications and 1,000 concurrent read/publish cycles, with all C++ assertions enabled even in Release. + +`tests/live_routing_ui_contract_test.mjs` asserts the opt-in event, status/ACK, mute requirements, user port selector and preservation of the original non-native VST3-preview strips. Existing Windows native build compiles the P1E JUCE header and all previous native realtime/Orbit/FX tests; Node checks validate monitor.js. + +**Real-device acceptance checklist (NOT YET PASSED):** ASIO 2/4/8 inputs; non-contiguous enabled active mask; mono→both speakers and stereo L/R isolation; unplug/replug and driver re-selection silences until remap; rapid edits/STOP while audio runs, no heap/click, 0 VST case compared with issue #15; 48/96 kHz, short buffers and controlled low-volume headphones; compare DIRECT to independent-clock diagnostics only outside LAB. Preserve logs for genuine device/render errors. + +**Merge gate:** exact-head Windows Native CTest + Chromium smoke, inspect binary artifact/provenance from Actions, reconcile all parallel PRs against latest `main` before merge. **Native GUI faders for CH2–CH10 and channel-VST3 processing are not delivered in this PR.** Follow-on P1F must implement per-strip plugin instance ownership, negotiated mono/stereo bus layouts and authentic mixer fader/FX bindings after the 0-VST3 hardware signal-path FAT is clean. diff --git a/engine/core/RealtimeRoutePublisher.h b/engine/core/RealtimeRoutePublisher.h new file mode 100644 index 000000000..2e2c7cc4f --- /dev/null +++ b/engine/core/RealtimeRoutePublisher.h @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include +#include + +// One control-thread writer and any number of bounded RT readers. +// IMPORTANT: Separate "reader count" and "active pointer" atomics DO NOT +// protect reclamation; a reader can enter after a zero-count observation +// and acquire a pointer which is being freed. Gate reader reservation and +// writer publication with ONE sequentially-consistent atomic state. +// +// State bit 0: writer publishing/unpublishing (RT fails closed, NO SPIN). +// High bits: +2 per active reader. Any reader registered before writer +// publication retains old lifetime until it releases the lease. +// In contrast, readers registering after the gate clears see only NEW active. +// Retired memory is reclaimed only on control thread, and only when there +// are no preexisting readers. No heap/lock/device call on RT read path. +namespace armix::rt { +template +class RealtimeRoutePublisher final { + static_assert(RetiredCapacity>=2); + static constexpr std::uint32_t writerFlag=1U, readerUnit=2U; +public: + struct Snapshot final { + std::uint64_t deviceEpoch=0; + std::uint64_t graphRevision=0; + std::unique_ptr prepared; + }; + enum class Result : std::uint8_t { + applied, invalidCandidate, staleDevice, staleRevision, retirementFull + }; + class ReadLease final { + public: + explicit ReadLease (RealtimeRoutePublisher& owner) noexcept : owner_(&owner) { + auto activity=owner_->activity_.load(std::memory_order_seq_cst); + // Do not spin/wait inside the audio callback. One silent block is + // preferable to scheduling jitter while control thread publishes. + if((activity&writerFlag)!=0 || activity>UINT32_MAX-readerUnit) + return; + if(!owner_->activity_.compare_exchange_strong( + activity,activity+readerUnit, + std::memory_order_seq_cst,std::memory_order_seq_cst)) + return; + registered_=true; + item_=owner_->active_.load(std::memory_order_seq_cst); + } + ReadLease(const ReadLease&)=delete; + ReadLease& operator=(const ReadLease&)=delete; + ReadLease(ReadLease&&)=delete; + ReadLease& operator=(ReadLease&&)=delete; + ~ReadLease() noexcept { + if(registered_) + owner_->activity_.fetch_sub(readerUnit,std::memory_order_seq_cst); + } + const Snapshot* get(std::uint64_t currentEpoch) const noexcept { + return item_ && item_->deviceEpoch==currentEpoch + ? item_ : nullptr; + } + private: + RealtimeRoutePublisher* owner_; + const Snapshot* item_=nullptr; + bool registered_=false; + }; + + RealtimeRoutePublisher()=default; + RealtimeRoutePublisher(const RealtimeRoutePublisher&)=delete; + RealtimeRoutePublisher& operator=(const RealtimeRoutePublisher&)=delete; + + // CONTROL thread only. Expected revision is last acknowledged revision; + // candidate is fully preallocated and validated before any RT publication. + Result publish(std::unique_ptr next, + std::uint64_t expectedRevision, + std::uint64_t deviceEpochNow) noexcept { + if(!next || !next->prepared || next->deviceEpoch==0 || + next->graphRevision==0 || next->graphRevision<=expectedRevision) + return Result::invalidCandidate; + if(next->deviceEpoch!=deviceEpochNow) + return Result::staleDevice; + if(expectedRevision!=revision_) + return Result::staleRevision; + pollRetirement(); + if(owned_ && retiredCount_>=RetiredCapacity) + return Result::retirementFull; + // Single writer. Publish/retire happens only with the low-bit gate set. + activity_.fetch_or(writerFlag,std::memory_order_seq_cst); + if(owned_)retired_[retiredCount_++]=std::move(owned_); + owned_=std::move(next); + active_.store(owned_.get(),std::memory_order_seq_cst); + activity_.fetch_and(~writerFlag,std::memory_order_seq_cst); + revision_=owned_->graphRevision; + return Result::applied; + } + + // Immediately gate the last route to silence. Do NOT delete a graph + // while the audio callback could own a ReadLease to its snapshot. + void unpublish() noexcept { + activity_.fetch_or(writerFlag,std::memory_order_seq_cst); + active_.store(nullptr,std::memory_order_seq_cst); + activity_.fetch_and(~writerFlag,std::memory_order_seq_cst); + revision_=0; + pollRetirement(); + if(!owned_)return; + if(retiredCount_ active_{nullptr}; + std::atomic activity_{0}; + std::unique_ptr owned_; + std::array,RetiredCapacity> retired_{}; + std::size_t retiredCount_=0; + std::uint64_t revision_=0; +}; +} // namespace armix::rt diff --git a/engine/device/LiveInputPortRegistry.h b/engine/device/LiveInputPortRegistry.h new file mode 100644 index 000000000..96e01f148 --- /dev/null +++ b/engine/device/LiveInputPortRegistry.h @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include + +// P1E — CONTROL-thread-only preparation from the *opened driver's active* +// channel mask. Physical channel IDs are zero-based; callback pointers are +// packed into [0..enabledCount) in the driver's enabled-channel order. +// Device names/ports must be verified by caller against the same session. +// This header deliberately has no JUCE dependency and does no callback work. +namespace armix::device { +struct LiveInputPortRegistry final { + static constexpr int limit = 256; + enum class Fault : std::uint8_t { + none, invalidEpoch, invalidPort, duplicatePort, overflow + }; + std::array callbackByPhysical {}; + std::array physicalByCallback {}; + std::uint64_t epoch = 0; + int enabledCount = 0; + + static bool prepare (std::uint64_t generation, + std::span physicalEnabledInCallbackOrder, + LiveInputPortRegistry& destination, + Fault& fault) noexcept { + fault=Fault::none; + if(generation==0) { fault=Fault::invalidEpoch; return false; } + if(physicalEnabledInCallbackOrder.size()>limit) { + fault=Fault::overflow;return false; + } + LiveInputPortRegistry next; + next.callbackByPhysical.fill(-1); + next.physicalByCallback.fill(-1); + for(std::size_t n=0;n=limit) { + fault=Fault::invalidPort;return false; + } + if(next.callbackByPhysical[id]!=-1) { + fault=Fault::duplicatePort;return false; + } + next.callbackByPhysical[id]=static_cast(n); + next.physicalByCallback[n]=id; + } + next.epoch=generation; + next.enabledCount=static_cast(physicalEnabledInCallbackOrder.size()); + destination=next; + return true; + } + int callbackIndex(int port) const noexcept { + return port>=0 && port=0 && callbackcount = 0; deviceManager_.closeAudioDevice(); + dryRoutingLab_.poll(); } void setMonitorEnabled (bool value) noexcept { monitor_.store (value); } @@ -261,6 +264,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String setIndependentClockEnabled (bool wanted) { + if (dryRoutingLab_.active()) return "Stop DRY ROUTING LAB before changing the device clock"; if (handoff_.busy()) return "Finish pending VST3 graph switch before changing audio backend"; if (wanted == independent_.active() && !(savedDirectSetup_ && !wanted)) return {}; if (wanted && savedDirectSetup_) return "Restore old device backend before another transition"; @@ -344,6 +348,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // user setup is restored on exit; temporary routes must not be persisted. juce::String setDiagnosticRoute (armix::diagnostics::Route wanted) { + if (dryRoutingLab_.active()) return "Stop DRY ROUTING LAB before changing SIGNAL CHECK"; using Route = armix::diagnostics::Route; if (handoff_.busy()) return "Finish the pending FX graph transition first"; if (independent_.active()) return "Disable independent clock mode before endpoint isolation tests"; @@ -508,6 +513,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String addVst3 (const juce::String& filename, int uid, const juce::String& catalogId) { + if (dryRoutingLab_.active()) return "Stop DRY ROUTING LAB before editing VST3"; if (handoff_.busy()) return "FX graph transition in progress; retry shortly"; if (graphOwned_->count >= maxFx) return "FX Rack is full (maximum 8 VST3 effects)"; auto* device = deviceManager_.getCurrentAudioDevice(); @@ -558,6 +564,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // exactly once, no plugin state methods ever execute on the audio thread. juce::String captureSnapshot (armix::storage::Snapshot& snapshot) { + if (dryRoutingLab_.active()) return "Stop DRY ROUTING LAB before saving native FX state"; if (!isOutputMuted()) return "Mute hardware output before saving a native preset"; if (handoff_.busy()) return "Finish pending FX graph transition before saving"; snapshot.effects.clear(); @@ -604,6 +611,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // or destroys a plugin. No manual output mute is required for recall. juce::String restoreSnapshot (const armix::storage::Snapshot& snapshot) { + if (dryRoutingLab_.active()) return "Stop DRY ROUTING LAB before preset recall"; if (handoff_.busy()) return "A live FX graph transition is already in progress"; if (snapshot.effects.size() > maxFx) return "Too many plugins in preset"; @@ -716,6 +724,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool removeAt (int index) { + if (dryRoutingLab_.active()) return false; if (handoff_.busy()) return false; if (index < 0 || index >= graphOwned_->count) return false; detach(); @@ -732,6 +741,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool moveSlot (int from, int to) { + if (dryRoutingLab_.active()) return false; if (handoff_.busy()) return false; if (from < 0 || from >= graphOwned_->count || to < 0 || to >= graphOwned_->count || from == to) return false; @@ -748,13 +758,36 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return true; } + // Explicit message-thread transaction. NO VST is processed in this LAB. + juce::String applyDryRoutingLab (const juce::var& command) { + if (!isOutputMuted()) return "MUTE OUTPUT before applying physical DRY LAB routing"; + if (handoff_.busy()) return "A VST3 graph handoff is in progress"; + if (routeReconfiguring_.load(std::memory_order_acquire)) + return "Audio device is changing; retry when stable"; + if (diagnosticRoute_.load(std::memory_order_acquire) + != armix::diagnostics::Route::normal) + return "Return SIGNAL CHECK to NORMAL before routing LAB"; + if (savedDirectSetup_ || savedLiveSetup_) + return "Restore the full DIRECT audio device before routing LAB"; + return dryRoutingLab_.apply(command,directFence_.permitted(), + independent_.active(),graphOwned_->count); + } + void disableDryRoutingLab() noexcept { + setOutputMuted(true); // never expose CH1 unexpectedly on STOP + dryRoutingLab_.disable(); + } + bool dryRoutingLabActive() const noexcept {return dryRoutingLab_.active();} + void pollDryRoutingLab() noexcept {dryRoutingLab_.poll();} + juce::var status() { + dryRoutingLab_.poll(); // off-RT reclaim after callback quiescence auto o = std::make_unique(); const bool dual = independent_.active(); auto* d = dual ? independent_.renderDevice() : deviceManager_.getCurrentAudioDevice(); auto* capture = dual ? independent_.captureDevice() : d; + o->setProperty ("dryRoutingLab",dryRoutingLab_.status(capture)); o->setProperty ("connected", d != nullptr && capture != nullptr); o->setProperty ("adaptiveClockActive", dual); o->setProperty ("adaptiveClockFaulted", dual && independent_.faulted()); @@ -1013,6 +1046,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::AudioBuffer scratch_; juce::AudioBuffer dryScratch_; armix::diagnostics::DiagnosticTone diagnosticTone_; + LiveDryRoutingLab dryRoutingLab_; std::atomic diagnosticRoute_ {armix::diagnostics::Route::normal}; std::atomic routeReconfiguring_ {false}; std::optional savedLiveSetup_; @@ -1096,6 +1130,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void audioDeviceAboutToStart (juce::AudioIODevice* d) override { + dryRoutingLab_.prepareDevice(d); // exact active mask, before callback if (!independent_.active()) { const auto backend=d->getTypeName(); @@ -1138,6 +1173,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void audioDeviceStopped() override { + dryRoutingLab_.deviceStopped(); deviceStopCount_.fetch_add (1, std::memory_order_relaxed); inputPeak_.store (0.f); outputPeak_.store (0.f); @@ -1194,6 +1230,41 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback callbackInputs_.store (inputChannels, std::memory_order_relaxed); callbackOutputs_.store (outputChannels, std::memory_order_relaxed); callbackCount_.fetch_add (1, std::memory_order_relaxed); + // P1E: the LIVE dry-routed 10-strip path is an explicit operator + // action, with an immutable preallocated P1D graph. Its own zero-VST + // callback path NEVER falls through to CH1 on stale/hotplug routes. + // DirectFence was already checked above; no output to unknown device. + if (dryRoutingLab_.active()) + { + const bool outputPermitted = monitor_.load(std::memory_order_relaxed) + && !routeReconfiguring_.load(std::memory_order_acquire) + && !masterMute_.load(std::memory_order_relaxed) + && activeDiagnosticRoute == armix::diagnostics::Route::normal + && !independent_.active(); + (void) dryRoutingLab_.process(inputs,inputChannels,outputs, + outputChannels,samples, + masterGain_.load(std::memory_order_relaxed), + !outputPermitted); + // Only measured output levels, not fake VST or other-strip meters. + const float left=dryRoutingLab_.peakLeft(); + const float right=dryRoutingLab_.peakRight(); + inputPeak_.store(0.f,std::memory_order_relaxed); + postFxPeak_.store(juce::jmin(1.f,juce::jmax(left,right)),std::memory_order_relaxed); + outputPeakL_.store(juce::jmin(1.f,left),std::memory_order_relaxed); + outputPeakR_.store(juce::jmin(1.f,right),std::memory_order_relaxed); + outputPeak_.store(juce::jmin(1.f,juce::jmax(left,right)),std::memory_order_relaxed); + // Existing FX graph is excluded at enable time. A structural + // edit during LAB is rejected on the control thread. + const auto elapsed=clockMicros()-beginUs; + lastCallbackUs_.store(elapsed,std::memory_order_relaxed); + publishMax(worstCallbackUs_,elapsed); + realtimeHistogram_.observe(elapsed,periodUs); + if(static_cast(elapsed)>periodUs*0.80) + slowCallbacks_.fetch_add(1,std::memory_order_relaxed); + if(static_cast(elapsed)>periodUs) + overBudgetCallbacks_.fetch_add(1,std::memory_order_relaxed); + return; + } const bool enabled = monitor_.load (std::memory_order_relaxed) && !routeReconfiguring_.load (std::memory_order_acquire); const auto route = diagnosticRoute_.load (std::memory_order_relaxed); diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h new file mode 100644 index 000000000..d6ce44719 --- /dev/null +++ b/src/LiveDryRoutingLab.h @@ -0,0 +1,306 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "../engine/core/PreparedMixerBlock.h" +#include "../engine/core/RealtimeRoutePublisher.h" +#include "../engine/device/LiveInputPortRegistry.h" +#include +#include +#include +#include +#include +#include +#include +#include + +// P1E — user-opt-in, *DRY / NO VST3* physical multichannel routing laboratory. +// Uses the P1D core already on main, not a competing mixer/DSP engine. +// Hardware rate/port identity and DIRECT route authorization are owned by +// LiveAudioEngine. No disk I/O, heap allocation, plugin or device operation +// on process() callback. This is a FAT diagnostic, NOT performance mode. +class LiveDryRoutingLab final { +public: + using Plan=armix::mixer::PreparedRenderGraph; + using Block=armix::mixer::PreparedMixerBlock; + using Publisher=armix::rt::RealtimeRoutePublisher; + static constexpr int count=armix::mixer::stripCount; + + // JUCE calls aboutToStart after configuring the input/output device. + // One device session gets a new epoch; stored route cannot survive it. + void prepareDevice (juce::AudioIODevice* device) noexcept { + // The new epoch invalidates old DSP immediately. Publish the new + // active mask using ATOMIC port slots: JUCE can restart the driver + // while its message thread is generating a routing/status snapshot. + const auto generation=deviceEpoch_.fetch_add(1,std::memory_order_acq_rel)+1; + registryValid_.store(false,std::memory_order_release); + portCount_.store(0,std::memory_order_release); + callbackInputCount_.store(-1,std::memory_order_release); + if(!device)return; + std::array candidate{}; + int count=0; + const auto mask=device->getActiveInputChannels(); + for(int bit=mask.findNextSetBit(0);bit>=0; + bit=mask.findNextSetBit(bit+1)) { + if(count>=armix::device::LiveInputPortRegistry::limit) + return; // never truncate/alias active device ports + candidate[count++]=bit; + } + armix::device::LiveInputPortRegistry prepared; + armix::device::LiveInputPortRegistry::Fault fault; + if(!armix::device::LiveInputPortRegistry::prepare( + generation,{candidate.data(),static_cast(count)}, + prepared,fault))return; + for(int i=0;i0) + return "Disable/remove Channel 1 VST3 before DRY Routing LAB (no plugin state is touched)"; + if(!command.isObject()) return "Invalid Dry Routing configuration"; + const auto currentEpoch=deviceEpoch_.load(std::memory_order_acquire); + if(!registryValid_.load(std::memory_order_acquire)) + return "Audio device has no validated active capture ports"; + const int countNow=portCount_.load(std::memory_order_acquire); + if(countNow<=0 || countNow>armix::device::LiveInputPortRegistry::limit) + return "Invalid active device input channel mask"; + std::array physicalPorts{}; + for(int i=0;i( + static_cast(command.getProperty("deviceEpoch",juce::var(0)))); + const auto expectedRevision=static_cast( + static_cast(command.getProperty("revision",juce::var(0)))); + if(currentEpoch==0 || expectedEpoch!=currentEpoch) + return "Audio device changed: reopen ROUTING to remap physical ports"; + const auto values=command.getProperty("channels",{}); + auto* assignments=values.getArray(); + if(!assignments || assignments->size()!=count) + return "Supply exactly 10 explicit channel assignments"; + armix::mixer::ChannelRoutingConfig cfg; + for(int i=0;igetReference(i); + if(!item.isObject())return "Invalid channel assignment"; + const auto mode=item.getProperty("mode",{}).toString(); + const auto left=item.getProperty("left",-1); + const auto right=item.getProperty("right",-1); + const auto gain=item.getProperty("gain",0.25); + if(!left.isInt()||!right.isInt()||!(gain.isDouble()||gain.isInt())) + return "Invalid input port number or channel level"; + const float level=static_cast(static_cast(gain)); + if(!std::isfinite(level)||level<0.f||level>1.f) + return "Channel level must be 0..1"; + auto& c=cfg.stripsAndMaster.strips[i]; + c.faderLinear=level; + c.pan=0.f; + if(mode=="NONE") { + c.source=armix::mixer::SourceMode::disconnected; + continue; + } + if(mode=="MONO") { + c.source=armix::mixer::SourceMode::mono; + c.inputA=static_cast(left); + cfg.formats[i]=armix::mixer::ChannelFormat::mono; + } else if(mode=="STEREO") { + c.source=armix::mixer::SourceMode::stereo; + c.inputA=static_cast(left); + c.inputB=static_cast(right); + cfg.formats[i]=armix::mixer::ChannelFormat::stereo; + } else return "Channel format must be NONE, MONO or STEREO"; + } + armix::mixer::SendRequest sends; // hardware dry FAT, no FX/send fabric yet + Plan plan; + armix::mixer::RenderError error; + if(!Plan::compile(cfg, + {physicalPorts.data(),static_cast(countNow)}, + sends,plan,error)) + return "Invalid physical routing (inactive port, format or mapping)"; + const auto revision=expectedRevision+1; + if(revision==0) return "Routing revision overflow"; + auto next=std::make_unique(); + next->deviceEpoch=currentEpoch; + next->graphRevision=revision; + next->prepared=std::make_unique(plan,Block::hardFrameLimit); + if(!next->prepared || next->prepared->capacity()==0) + return "Cannot allocate routing workspace"; + const auto epochAtPublish=deviceEpoch_.load(std::memory_order_acquire); + if(!registryValid_.load(std::memory_order_acquire) || + epochAtPublish!=currentEpoch) + return "Audio device changed before routing publication"; + const auto result=publisher_.publish(std::move(next),expectedRevision,epochAtPublish); + switch(result) { + case Publisher::Result::applied: + publishedEpoch_.store(currentEpoch,std::memory_order_release); + enabled_.store(true,std::memory_order_release); + return {}; + case Publisher::Result::staleDevice: + return "Device epoch changed during preparation"; + case Publisher::Result::staleRevision: + return "Routing changed elsewhere: refresh before applying"; + case Publisher::Result::retirementFull: + return "Routing edits are too fast; retry after callback retirement"; + default: + return "Invalid prepared route"; + } + } + + void disable() noexcept { + enabled_.store(false,std::memory_order_release); + publishedEpoch_.store(0,std::memory_order_release); + publisher_.unpublish(); // control thread only + peakL_.store(0.f,std::memory_order_relaxed); + peakR_.store(0.f,std::memory_order_relaxed); + } + void poll() noexcept {publisher_.pollRetirement();} // message thread + bool active() const noexcept {return enabled_.load(std::memory_order_acquire);} + float peakLeft() const noexcept {return peakL_.load(std::memory_order_relaxed);} + float peakRight() const noexcept {return peakR_.load(std::memory_order_relaxed);} + bool ready() const noexcept { + return active() && publishedEpoch_.load(std::memory_order_acquire)==epoch(); + } + std::uint64_t epoch() const noexcept { + return deviceEpoch_.load(std::memory_order_acquire); + } + std::uint64_t revision() const noexcept {return publisher_.lastRevision();} // control only + + // JUCE render callback, with a verified single-clock device. Routing + // publishes at the BLOCK boundary. Missing/stale ports output SILENCE. + // A failed run never falls through to an unrelated microphone/plugin path. + bool process(const float* const* inputs,int inputCount, + float* const* outputs,int outputCount,int frames, + float masterGain,bool masterMuted) noexcept { + if(!active())return false; + // Stale meters must never survive a failed device/epoch mapping. + peakL_.store(0.f,std::memory_order_relaxed); + peakR_.store(0.f,std::memory_order_relaxed); + if(frames<=0)return true; + for(int c=0;carmix::device::LiveInputPortRegistry::limit) + return true; + const auto generation=epoch(); + auto lease=publisher_.acquire(); + const auto* snapshot=lease.get(generation); + if(!snapshot||!snapshot->prepared || + inputCount!=callbackInputCount_.load(std::memory_order_acquire)) { + fadeRemaining_=0; + lastOutputL_=lastOutputR_=0.f; + return true; + } + if(snapshot->graphRevision!=audioRevision_ || generation!=audioEpoch_) { + audioRevision_=snapshot->graphRevision; + audioEpoch_=generation; + fadeRemaining_=rampFrames; + fadeFromL_=lastOutputL_; + fadeFromR_=lastOutputR_; + } + // Large/variable JUCE quantum is chunked using stack pointer views; + // no heap allocation or new processing object inside callback. + std::array shifted{}; + constexpr int max=Block::hardFrameLimit; + const auto noFx=[](int,float*,float*,int) noexcept {}; + float peakL=0.f,peakR=0.f; + for(int offset=0;offsetprepared->process(shifted.data(),inputCount, + outputs[0]+offset,outputs[1]+offset,n,noFx,&level)) + return true; + const float g=masterMuted?0.f:std::clamp(masterGain,0.f,2.f); + for(int i=0;i0) { + const float t=1.f-static_cast(fadeRemaining_-1)/ + static_cast(rampFrames); + l=fadeFromL_+(l-fadeFromL_)*t; + r=fadeFromR_+(r-fadeFromR_)*t; + --fadeRemaining_; + } + outputs[0][offset+i]=l; + outputs[1][offset+i]=r; + lastOutputL_=l; + lastOutputR_=r; + peakL=std::max(peakL,std::abs(l)); + peakR=std::max(peakR,std::abs(r)); + } + } + peakL_.store(peakL,std::memory_order_relaxed); + peakR_.store(peakR,std::memory_order_relaxed); + return true; + } + + juce::var status(juce::AudioIODevice* device) const { + auto out=std::make_unique(); + out->setProperty("active",active()); + out->setProperty("ready",ready()); + out->setProperty("epoch",static_cast(epoch())); + out->setProperty("revision",static_cast(revision())); + out->setProperty("peakL",peakL_.load(std::memory_order_relaxed)); + out->setProperty("peakR",peakR_.load(std::memory_order_relaxed)); + juce::Array ports; + if(device && registryValid_.load(std::memory_order_acquire)) { + const auto generation=epoch(); + const int countNow=portCount_.load(std::memory_order_acquire); + const auto names=device->getInputChannelNames(); + for(int i=0;i(); + p->setProperty("port",physical); + p->setProperty("callback",i); + p->setProperty("label",physicalsetProperty("ports",juce::var(ports)); + out->setProperty("note","EXPLICIT DRY HARDWARE FAT ONLY: no channel VST3, no sends, no portable route persistence"); + return juce::var(out.release()); + } +private: + Publisher publisher_; + // All data shared between JUCE device lifecycle and GUI/control reads + // are atomic; the callback never enumerates masks or channel names. + std::array,armix::device::LiveInputPortRegistry::limit> enabledPorts_{}; + std::atomic portCount_{0}; + std::atomic registryValid_{false}; + std::atomic deviceEpoch_{0}; + std::atomic publishedEpoch_{0}; + std::atomic callbackInputCount_{-1}; + std::atomic enabled_{false}; + std::atomic peakL_{0.f},peakR_{0.f}; + // Exclusive render-producer state. Bounded fade starts from the exact + // previously output sample, preventing a topology switch discontinuity. + static constexpr int rampFrames=256; + int fadeRemaining_=0; + std::uint64_t audioRevision_=0,audioEpoch_=0; + float fadeFromL_=0.f,fadeFromR_=0.f; + float lastOutputL_=0.f,lastOutputR_=0.f; +}; diff --git a/src/Main.cpp b/src/Main.cpp index 39f7336ae..091c249dc 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -906,6 +906,36 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr action == "presetLoad" || action == "presetSave")) return emitNotice ("Return to DIRECT mode before editing VST3 graph (live-safe graph edits are a later gate).", true); + // A user-controlled hardware dry routing FAT, not a change to the + // existing 1-channel VST3 production chain. Explicit Apply/Stop. + if (action == "routingDryApply") + { + const auto error=engine_.applyDryRoutingLab(value); + auto reply=std::make_unique(); + reply->setProperty("ok",error.isEmpty()); + reply->setProperty("error",error); + const auto status=engine_.status().getProperty("dryRoutingLab",{}); + reply->setProperty("state",status); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible( + "arMixRoutingLabAck",juce::var(reply.release())); + if(error.isNotEmpty())return emitNotice(error,true); + diagnostics_.record("LIVE_DRY_ROUTING_LAB_APPLIED", + "No VST3 | actual enabled hardware mask and epoch verified"); + return emitNotice( + "DRY ROUTING LAB active: 10 native input strips, NO FX. " + "Use low headphone volume. Stop LAB before loading VST3."); + } + if (action == "routingDryStop") + { + engine_.disableDryRoutingLab(); + diagnostics_.record("LIVE_DRY_ROUTING_LAB_STOP","Restored native CH1 production path"); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible( + "arMixRoutingLabAck",engine_.status().getProperty("dryRoutingLab",{})); + return emitNotice("DRY ROUTING LAB stopped. Native CH1 path restored."); + } + if (action == "smartClock") { if (!value.isBool()) return emitNotice ("Invalid smart clock command", true); diff --git a/tests/live_port_epoch_publisher_test.cpp b/tests/live_port_epoch_publisher_test.cpp new file mode 100644 index 000000000..cdd09ecd3 --- /dev/null +++ b/tests/live_port_epoch_publisher_test.cpp @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/core/RealtimeRoutePublisher.h" +#include "../engine/device/LiveInputPortRegistry.h" +#if defined(NDEBUG) +#undef NDEBUG +#endif +#include +#include +#include +#include +#include +#include +using namespace armix; +struct SpyGraph { + static inline std::atomic alive{0}; + int value=0; + explicit SpyGraph(int v) noexcept :value(v) {alive.fetch_add(1);} + ~SpyGraph() noexcept {alive.fetch_sub(1);} +}; +using Publisher=rt::RealtimeRoutePublisher; +static std::unique_ptr makeGraph(std::uint64_t epoch,std::uint64_t revision,int tag) { + auto x=std::make_unique(); + x->deviceEpoch=epoch;x->graphRevision=revision; + x->prepared=std::make_unique(tag); + return x; +} +int main() { + device::LiveInputPortRegistry ports;device::LiveInputPortRegistry::Fault fault; + constexpr std::array order{5,2,9}; + assert(device::LiveInputPortRegistry::prepare(7,order,ports,fault)); + assert(ports.epoch==7&&ports.enabledCount==3); + assert(ports.callbackIndex(5)==0&&ports.callbackIndex(2)==1); + assert(ports.callbackIndex(9)==2&&ports.callbackIndex(0)==-1); + assert(ports.physicalIndex(1)==2&&ports.physicalIndex(3)==-1); + assert(ports.matches(7,3)&&!ports.matches(7,4)&&!ports.matches(8,3)); + const auto old=ports; + constexpr std::array duplicates{5,2,5}; + assert(!device::LiveInputPortRegistry::prepare(7,duplicates,ports,fault)); + assert(fault==device::LiveInputPortRegistry::Fault::duplicatePort); + assert(ports.epoch==old.epoch&&ports.callbackIndex(9)==2); + constexpr std::array invalid{-1,0}; + assert(!device::LiveInputPortRegistry::prepare(7,invalid,ports,fault)); + assert(fault==device::LiveInputPortRegistry::Fault::invalidPort); + assert(!device::LiveInputPortRegistry::prepare(0,order,ports,fault)); + assert(fault==device::LiveInputPortRegistry::Fault::invalidEpoch); + + Publisher p; + assert(p.publish(makeGraph(1,1,101),0,2)==Publisher::Result::staleDevice); + assert(p.lastRevision()==0); + assert(p.publish(makeGraph(1,1,101),0,1)==Publisher::Result::applied); + assert(p.lastRevision()==1); + { + auto lease=p.acquire(); + assert(lease.get(1) && lease.get(1)->prepared->value==101); + assert(!lease.get(2)); // epoch mismatch never exposes stale audio + assert(p.publish(makeGraph(1,2,102),0,1)==Publisher::Result::staleRevision); + assert(p.publish(makeGraph(1,2,102),1,1)==Publisher::Result::applied); + assert(lease.get(1) && lease.get(1)->prepared->value==101); + assert(p.pendingRetirements()==1); + assert(!p.pollRetirement()); + assert(SpyGraph::alive==2); + assert(p.publish(makeGraph(1,3,103),2,1)==Publisher::Result::applied); + assert(p.publish(makeGraph(1,4,104),3,1)==Publisher::Result::applied); + assert(p.pendingRetirements()==3); + assert(p.publish(makeGraph(1,5,105),4,1)==Publisher::Result::retirementFull); + { + auto newer=p.acquire(); + assert(newer.get(1)&&newer.get(1)->prepared->value==104); + } + // Emergency unpublish CANNOT wait for the first active lease; but + // subsequent callbacks MUST see no valid graph immediately. + p.unpublish(); + assert(p.lastRevision()==0); + auto silenced=p.acquire(); + assert(!silenced.get(1)); + } + assert(p.pollRetirement()); + // The last unpublished owner was held until the callback could retire. + assert(SpyGraph::alive==1); + assert(p.publish(makeGraph(8,1,201),0,8)==Publisher::Result::applied); + { auto v=p.acquire();assert(v.get(8)->prepared->value==201); } + p.unpublish(); + assert(p.pollRetirement()); + assert(SpyGraph::alive==0); + + // A burst of consecutive reconfigurations does not leak retired plans + // or allocate anything in the read lease (the callback API). + for(int i=0;i<8000;++i) { + auto next=makeGraph(9,static_cast(i+1),i); + assert(p.publish(std::move(next),static_cast(i),9)==Publisher::Result::applied); + auto lease=p.acquire(); + assert(lease.get(9)&&lease.get(9)->prepared->value==i); + } + p.unpublish(); + assert(p.pollRetirement()); + assert(SpyGraph::alive==0); + + // Concurrent RT reader repeatedly observes either a whole published + // snapshot or nullptr; no old graph can be destroyed while leased. + std::atomic running{true};std::atomic observed{0}; + std::thread audio([&]{ + while(running.load(std::memory_order_relaxed)){ + auto lease=p.acquire(); + if(const auto* s=lease.get(10)){ + assert(s->deviceEpoch==10); + assert(s->prepared->value>=0); + observed.fetch_add(1,std::memory_order_relaxed); + } + } + }); + std::uint64_t ack=0; + for(int i=0;i<1000;++i) { + auto state=makeGraph(10,ack+1,i); + const auto ret=p.publish(std::move(state),ack,10); + if(ret==Publisher::Result::applied) ++ack; + else assert(ret==Publisher::Result::retirementFull); + p.pollRetirement(); + } + running.store(false,std::memory_order_release); + audio.join(); + p.unpublish(); + assert(p.pollRetirement()); + assert(SpyGraph::alive==0); +} diff --git a/tests/live_routing_ui_contract_test.mjs b/tests/live_routing_ui_contract_test.mjs new file mode 100644 index 000000000..f22446a9c --- /dev/null +++ b/tests/live_routing_ui_contract_test.mjs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Native/GUI contract: P1E exposes REAL channel routing only under explicit +// muted-output operator action and never falsely marks CH2-10 VST inserts live. +import { readFileSync } from "node:fs"; +import assert from "node:assert/strict"; +import test from "node:test"; + +const engine=readFileSync(new URL("../src/LiveAudioEngine.h",import.meta.url),"utf8"); +const lab=readFileSync(new URL("../src/LiveDryRoutingLab.h",import.meta.url),"utf8"); +const main=readFileSync(new URL("../src/Main.cpp",import.meta.url),"utf8"); +const ui=readFileSync(new URL("../web/monitor.js",import.meta.url),"utf8"); +const bridge=readFileSync(new URL("../web/bridge.js",import.meta.url),"utf8"); + +test("P1E is opt-in; all native VST3/clock/diagnostic paths protected",()=>{ + assert.match(engine,/dryRoutingLab_\.active\(\)/); + assert.match(engine,/!isOutputMuted\(\).*MUTE OUTPUT/); + assert.match(engine,/setOutputMuted\(true\); \/\/ never expose CH1 unexpectedly/); + assert.match(engine,/dryRoutingLab_\.prepareDevice\(d\)/); + assert.match(engine,/dryRoutingLab_\.deviceStopped\(\)/); + assert.match(engine,/dryRoutingLab_\.process\(inputs,inputChannels,outputs/); + assert.match(engine,/if \(dryRoutingLab_\.active\(\)\) return "Stop DRY ROUTING LAB before editing VST3"/); + assert.match(engine,/if \(dryRoutingLab_\.active\(\)\) return "Stop DRY ROUTING LAB before preset recall"/); + assert.match(lab,/publisher_\.publish/); + assert.match(lab,/deviceEpoch_/); + assert.match(lab,/Block::hardFrameLimit/); + assert.match(lab,/rampFrames=256/); + assert.match(lab,/publishedEpoch_\.load/); + assert.match(lab,/std::array/); +}); +test("GUI exposes only truthful dry device routes and acknowledged commit",()=>{ + assert.match(ui,/ROUTING LAB · 10 CH/); + assert.match(ui,/routingDryApply/); + assert.match(ui,/routingDryStop/); + assert.match(ui,/arMixRoutingLabAck/); + assert.match(ui,/data-route-left/); + assert.match(ui,/data-route-right/); + assert.match(ui,/status|DRY LAB STALE/); + assert.match(ui,/No VST3|no VST3|no channel VST3|no VST3/i); + assert.match(main,/action == "routingDryApply"/); + assert.match(main,/action == "routingDryStop"/); + assert.match(main,/arMixRoutingLabAck/); + // Default 10 fake preview strips are intentionally not made into VST3 + // controls by the dry hardware test. + assert.match(bridge,/if\(i!==0\)/); + assert.match(bridge,/track\.dataset\.preview="1"/); +}); diff --git a/web/monitor.js b/web/monitor.js index a84f80e2a..4e91a531f 100644 --- a/web/monitor.js +++ b/web/monitor.js @@ -21,6 +21,17 @@ "#arDiagnosticCopy{color:#e1f7f4;background:#166052;border:1px solid #34c8ac;border-radius:4px;padding:7px 12px;cursor:pointer}" + "#arDiagnosticCopyStatus{color:#8cdec9;font-size:10px}" + "#arSmartClockToggle{color:#f5eadb;background:#284961;border:1px solid #9bb2c5;border-radius:4px;padding:7px 12px;cursor:pointer}"; + // No blur, no animated shaders or per-strip timer. Routing draws only + // on explicit user edit; existing native health polling stays at 12 Hz. + css.textContent += + "#arRoutingLabOverlay{display:none;position:fixed;inset:0;z-index:995;background:#08121be8;align-items:center;justify-content:center}" + + "#arRoutingLabOverlay.open{display:flex}#arRoutingLabPanel{width:min(760px,94vw);max-height:86vh;overflow:auto;box-sizing:border-box;padding:16px;background:#172834;border:1px solid #637e8a;border-radius:8px;color:#dcecf3}" + + "#arRoutingLabPanel h2{font-size:17px;font-weight:600;margin:0 0 6px}#arRoutingLabPanel p{font-size:11px;line-height:1.6;color:#9cc5d4;margin:6px 0 13px}" + + ".arRouteRow{display:grid;grid-template-columns:60px 105px 1fr 1fr 110px;gap:6px;align-items:center;padding:5px 0;border-bottom:1px solid #2d4653}" + + ".arRouteRow label{font-size:11px;font-weight:600}.arRouteRow select{width:100%;min-width:0;padding:6px;background:#0d202b;border:1px solid #4d6879;border-radius:4px;color:#e1eef5;font-size:11px}" + + ".arRouteFoot{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end;margin-top:12px}.arRouteFoot button,.arRouteClose{color:#f0f7fa;background:#24475a;border:1px solid #587f91;border-radius:4px;padding:8px 12px;cursor:pointer}" + + "#arRouteApply{background:#237566;border-color:#4ba48d}#arRouteStop{background:#50343c;border-color:#a8717c}" + + "#arRouteFeedback{font-size:11px;min-height:18px;color:#8bdec1;margin-top:10px}"; document.head.appendChild(css); // Signal Check is declared in the permanent toolbar; footer holds status only. const overlay = document.createElement("div"); @@ -34,7 +45,7 @@ '
Reading native audio state...
' + '
' + '' + - '
' + + '' + '
' + ''+ + ['NONE','MONO','STEREO'].map(m=>'').join('')+''+ + ''+ + ''+ + '
'; + }).join(''); + rows.querySelectorAll('[data-route-row]').forEach(row=>{ + const model=draftRoutes[Number(row.dataset.routeRow)]; + row.querySelector('[data-route-mode]').addEventListener('change',e=>{model.mode=e.target.value;refreshMode(row);}); + row.querySelector('[data-route-left]').addEventListener('change',e=>{model.left=Number(e.target.value);}); + row.querySelector('[data-route-right]').addEventListener('change',e=>{model.right=Number(e.target.value);}); + row.querySelector('[data-route-gain]').addEventListener('change',e=>{model.gain=Number(e.target.value);}); + refreshMode(row); + }); + updateRouteLabIdentity(); + } + function refreshMode(row){ + const type=row.querySelector('[data-route-mode]').value; + row.querySelector('[data-route-left]').disabled=type==="NONE"; + row.querySelector('[data-route-right]').disabled=type!=="STEREO"; + } + function updateRouteLabIdentity(){ + const d=state.dryRoutingLab||{}; + const label=document.getElementById("arRouteIdentity"); + if(!label)return; + setTextIfChanged(label,(d.active ? (d.ready?"DRY LAB ACTIVE":"DRY LAB STALE — SILENT, REAPPLY"):"DRY LAB OFF")+ + " · device epoch "+(d.epoch||0)+" · rev "+(d.revision||0)+ + " · "+(d.ports?.length||0)+" enabled physical inputs"); + } + document.getElementById("arOpenRoutingLab").addEventListener("click",()=>{ + drawRoutes(); + routeOverlay.classList.add("open"); + overlay.classList.remove("open"); + }); + document.getElementById("arRouteClose").addEventListener("click",()=>routeOverlay.classList.remove("open")); + routeOverlay.addEventListener("click",e=>{if(e.target===routeOverlay)routeOverlay.classList.remove("open");}); + document.getElementById("arRouteApply").addEventListener("click",()=>{ + const d=state.dryRoutingLab||{}; + if(!draftEpoch || draftEpoch!==Number(d.epoch)){ + document.getElementById("arRouteFeedback").textContent= + "DEVICE CHANGED · old channel assignments discarded. Re-select the actual physical inputs."; + drawRoutes(); + return; // must never submit old ports with a newly observed epoch + } + if(!Array.isArray(d.ports)||!d.ports.length){ + document.getElementById("arRouteFeedback").textContent="Select a real ASIO/WASAPI audio input in AUDIO SETUP first.";return; + } + document.getElementById("arRouteFeedback").textContent="Applying native route (output must be MUTED)..."; + api.emitEvent("arMixAction",{action:"routingDryApply",value:{ + deviceEpoch:draftEpoch,revision:Number(d.revision)||0, + channels:draftRoutes.map(c=>({...c})) + }}); + }); + document.getElementById("arRouteStop").addEventListener("click",()=>api.emitEvent("arMixAction",{action:"routingDryStop"})); + api.addEventListener("arMixRoutingLabAck",reply=>{ + const result=reply?.state||reply||{}; + if(result && typeof result==="object" && "epoch" in result)state.dryRoutingLab=result; + document.getElementById("arRouteFeedback").textContent= + reply?.ok===false?("REJECTED · "+(reply.error||"Invalid route")): + result.active?"NATIVE ACK: DRY LAB ENABLED · zero VST3 · UNMUTE OUTPUT in SIGNAL CHECK":"NATIVE ACK: STOPPED · output remains MUTED for safety"; + updateRouteLabIdentity(); + }); + const el = id => document.getElementById(id); // 12Hz native telemetry must not replace unchanged text nodes or cause // needless main-thread paint/layout invalidations on static header labels. @@ -64,6 +174,9 @@ Number(d?.backendXrunCount)>=3 && Number(d?.overBudgetCount)===0; function diagnosis(d) { + if(d.dryRoutingLab?.active) return d.dryRoutingLab.ready? + "Live 10-channel DRY ROUTING LAB: actual native inputs → dry master. No VST3, AUX or snapshot routing. Use low headphone volume.": + "Routing LAB device generation changed. Output is SILENT until you remap the real device and APPLY again."; if(d.diagnosticRoute==="OUTPUT_ONLY_TONE") return "Output-only test: capture endpoint is disconnected. Listen for tone at low headphone volume and click MARK CRACKLE when audible."; if(d.diagnosticRoute==="CAPTURE_ONLY") return "Capture-only test: hardware render endpoint is disconnected. Observe capture input and backend discontinuity count; you should hear no audio."; if(d.diagnosticRoute==="DRY_THROUGH") return "Dry-through test: microphone to output with all VST3 bypassed. MARK CRACKLE at audible glitches."; @@ -85,6 +198,13 @@ return "Output armed. Speak into the microphone and inspect all three meters."; } function repaint(d) { + if(routeOverlay.classList.contains("open")){ + if(draftEpoch!==(Number(d.dryRoutingLab?.epoch)||0)) { + drawRoutes(); // fresh port names; reset stale user assignments + document.getElementById("arRouteFeedback").textContent= + "AUDIO DEVICE CHANGED · all input assignments reset. Select ports again."; + } else updateRouteLabIdentity(); + } setTextIfChanged(el("arSignalBadge"),!d.monitor ? "OUTPUT MUTED" : d.masterMute ? "MASTER MUTED" : d.channelMute ? "CH1 MUTED" : "OUTPUT ARMED"); el("arSignalBadge").style.color = d.monitor && !d.masterMute && !d.channelMute ? "#71e9cc" : "#e9be7c"; const monitorButton=document.querySelector('[data-native-action="monitor"]'); @@ -98,14 +218,15 @@ const driverLabel=document.querySelector('.spec-device strong'); setTextIfChanged(driverLabel,d.driver||"NO DRIVER"); const liveLabel=document.querySelector('.status > span:first-child > b'); - setTextIfChanged(liveLabel,"NATIVE CH1"); + setTextIfChanged(liveLabel,d.dryRoutingLab?.active?"NATIVE DRY 10CH LAB":"NATIVE CH1"); const edition=document.querySelector('.status > span:last-child'); - setTextIfChanged(edition,"AR MIX P2 · CH1 NATIVE + UI PREVIEW"); + setTextIfChanged(edition,d.dryRoutingLab?.active? + "AR MIX P1E · REAL DRY ROUTES / FX DISABLED":"AR MIX P2 · CH1 NATIVE + UI PREVIEW"); if (!overlay.classList.contains("open")) return; - el("arInputName").textContent=d.diagnosticRoute==="OUTPUT_ONLY_TONE"?"INTERNAL TEST TONE":d.inputDevice||"Input device"; - el("arFxName").textContent=d.diagnosticRoute==="OUTPUT_ONLY_TONE"?"NO INPUT / NO FX":d.diagnosticRoute!=="NORMAL"?"NO FX":d.dryTest?"DRY BYPASS":"VST3 Chain"; + el("arInputName").textContent=d.dryRoutingLab?.active?"NATIVE 10 CH INPUTS":d.diagnosticRoute==="OUTPUT_ONLY_TONE"?"INTERNAL TEST TONE":d.inputDevice||"Input device"; + el("arFxName").textContent=d.dryRoutingLab?.active?"DRY · ZERO VST3":d.diagnosticRoute==="OUTPUT_ONLY_TONE"?"NO INPUT / NO FX":d.diagnosticRoute!=="NORMAL"?"NO FX":d.dryTest?"DRY BYPASS":"VST3 Chain"; el("arOutputName").textContent=d.outputDevice||"Output device"; - el("arInputBar").style.width=percent(d.inputPeak)+"%"; + el("arInputBar").style.width=percent(d.dryRoutingLab?.active?Math.max(d.dryRoutingLab.peakL||0,d.dryRoutingLab.peakR||0):d.inputPeak)+"%"; el("arFxBar").style.width=percent(d.postFxPeak)+"%"; el("arOutputBar").style.width=percent(d.peak)+"%"; el("arSignalReason").textContent=diagnosis(d); From 5c5f9e8536bf612eb0d51d2d65ac6201361d9db0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 08:34:45 +0700 Subject: [PATCH 2/2] fix(audio): mute-before-render and zero all outputs on LAB STOP race --- ...1E_CURRENT_MAIN_RECONCILIATION_20261028.md | 7 ++++++ src/LiveAudioEngine.h | 15 ++++++++---- src/LiveDryRoutingLab.h | 12 +++++++++- tests/live_routing_ui_contract_test.mjs | 24 +++++++++++++++++++ 4 files changed, 53 insertions(+), 5 deletions(-) diff --git a/docs/ARD_P1E_CURRENT_MAIN_RECONCILIATION_20261028.md b/docs/ARD_P1E_CURRENT_MAIN_RECONCILIATION_20261028.md index 97150cf3a..85377c5ff 100644 --- a/docs/ARD_P1E_CURRENT_MAIN_RECONCILIATION_20261028.md +++ b/docs/ARD_P1E_CURRENT_MAIN_RECONCILIATION_20261028.md @@ -14,3 +14,10 @@ The opt-in **SIGNAL CHECK → DRY ROUTING LAB** provides real physical ASIO/WASA The exact newly integrated head must run the **same** full Chromium/Firefox/Orbit GUI smoke currently green on main, native Node route contract, Windows MSVC/CTest and real executable packaging. Verify output against latest original main tree for unrelated visual source blobs. No additional CI matrices or jobs. Do **not** claim full production 10-channel VST3, 2-AUX runtime processing, plugin graph live swap, or #15 zero-VST crackle hardware pass. P1E is operator-controlled DRY hardware FAT only. Physical Windows ASIO/WASAPI inputs, buffer dropouts, latency, mute transition and routing status must be tested on owner's actual interface. Avoid arbitrarily modifying old PR #102 FX drag engine, source fader image or Orbit; use current main as owner. + +## Postreview fail-closed audio safety (P2 fixes before merge) +Two valid review comments on the first PR head required corrections: +1. A concurrent **STOP LAB** can change `active()` after the audio callback's outer check but before entering `process()`. The caller now checks the return value and explicitly zeros *all* output buffers plus all displayed output levels on a false return. Never fall through to the CH1 production renderer. No allocation or OS call on callback. +2. With mute engaged during a topology switch, interpolating old `lastOutput` after applying `masterMuted?0` output gain could leak previously audible samples into hardware output. The lab now returns early with already-cleared outputs when muted, resets all residual fade/output history and primes a 256-sample **from-zero** transition on first unmute. It also skips muted dry DSP processing to conserve CPU. + +The existing Windows CTest runs unchanged; native UI Node contract now requires explicit STOP output-clear and mute-before-DSP guards. Both fail-closed safety paths are engineering corrections, not proof of hardware crackle immunity. diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index a3771e3cb..808e06715 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1241,13 +1241,20 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback && !masterMute_.load(std::memory_order_relaxed) && activeDiagnosticRoute == armix::diagnostics::Route::normal && !independent_.active(); - (void) dryRoutingLab_.process(inputs,inputChannels,outputs, + const bool routed=dryRoutingLab_.process(inputs,inputChannels,outputs, outputChannels,samples, masterGain_.load(std::memory_order_relaxed), !outputPermitted); - // Only measured output levels, not fake VST or other-strip meters. - const float left=dryRoutingLab_.peakLeft(); - const float right=dryRoutingLab_.peakRight(); + // STOP can race after the outer active() check. Never leave a + // callback's output untouched, and NEVER fall through into CH1. + if(!routed) { + for(int c=0;c shifted{}; @@ -228,7 +238,7 @@ class LiveDryRoutingLab final { if(!snapshot->prepared->process(shifted.data(),inputCount, outputs[0]+offset,outputs[1]+offset,n,noFx,&level)) return true; - const float g=masterMuted?0.f:std::clamp(masterGain,0.f,2.f); + const float g=std::clamp(masterGain,0.f,2.f); for(int i=0;i{ assert.match(bridge,/if\(i!==0\)/); assert.match(bridge,/track\.dataset\.preview="1"/); }); + +test("STOP-race is fail closed: all outputs are written to silence without CH1 fallback",()=>{ + const enter=engine.indexOf("if (dryRoutingLab_.active())",engine.indexOf("callbackCount_.fetch_add")); + const end=engine.indexOf("// Existing FX graph is excluded",enter); + assert.ok(enter>=0&&end>enter, "live audio callback LAB branch must exist"); + const branch=engine.slice(enter,end); + assert.match(branch,/const bool routed=dryRoutingLab_\.process\(/); + assert.match(branch,/if\(!routed\)\s*\{\s*for\(int c=0;c{ + const start=lab.indexOf("if(snapshot->graphRevision!=audioRevision_"); + const beforeRender=lab.indexOf("snapshot->prepared->process(",start); + const silent=lab.indexOf("if(masterMuted) {",start); + assert.ok(start>=0&&silent>start&&beforeRender>silent); + const gate=lab.slice(silent,beforeRender); + assert.match(gate,/fadeRemaining_=rampFrames/); + assert.match(gate,/fadeFromL_=fadeFromR_=0\.f/); + assert.match(gate,/lastOutputL_=lastOutputR_=0\.f/); + assert.match(gate,/return true/); + assert.ok(!lab.includes("masterMuted?0.f:std::clamp(masterGain"), "don't mute before fade and then reintroduce old samples"); +});