From 3a047ce5451a3f36dbb92911dfb3e570b1a60c8a Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 28 Oct 2026 06:32:44 +0700 Subject: [PATCH] feat(mixer): integrate tested 10-channel mono/stereo, pre-post sends, FX return and master DSP into current main baseline --- .github/workflows/p1-windows.yml | 2 +- CMakeLists.txt | 14 +- docs/P1A_REAL_MIXER_ROUTING_CORE_20261028.md | 32 +++ .../P1B_MONO_STEREO_PORT_CONTRACT_20261028.md | 56 ++++ docs/P1C_INTERNAL_SENDS_DAG_20261028.md | 50 ++++ ...P1D_INTEGRATED_TEN_CHANNEL_DSP_20261028.md | 30 +++ engine/core/ChannelRoutingContract.h | 177 +++++++++++++ engine/core/ChannelSendPlan.h | 176 +++++++++++++ engine/core/MixerRoutingPlan.h | 168 ++++++++++++ engine/core/PreparedMixerBlock.h | 240 ++++++++++++++++++ tests/channel_routing_contract_test.cpp | 114 +++++++++ tests/channel_send_plan_test.cpp | 112 ++++++++ tests/mixer_routing_plan_test.cpp | 100 ++++++++ tests/prepared_mixer_block_test.cpp | 150 +++++++++++ 14 files changed, 1419 insertions(+), 2 deletions(-) create mode 100644 docs/P1A_REAL_MIXER_ROUTING_CORE_20261028.md create mode 100644 docs/P1B_MONO_STEREO_PORT_CONTRACT_20261028.md create mode 100644 docs/P1C_INTERNAL_SENDS_DAG_20261028.md create mode 100644 docs/P1D_INTEGRATED_TEN_CHANNEL_DSP_20261028.md create mode 100644 engine/core/ChannelRoutingContract.h create mode 100644 engine/core/ChannelSendPlan.h create mode 100644 engine/core/MixerRoutingPlan.h create mode 100644 engine/core/PreparedMixerBlock.h create mode 100644 tests/channel_routing_contract_test.cpp create mode 100644 tests/channel_send_plan_test.cpp create mode 100644 tests/mixer_routing_plan_test.cpp create mode 100644 tests/prepared_mixer_block_test.cpp diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 8a6a85a3b..d9e615c8d 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -63,7 +63,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 ARMixWorkspaceTests ARMixVaultTests 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 ARMixWorkspaceTests ARMixVaultTests 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 5982b680c..298af93ce 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/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/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/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/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 @@ -47,6 +47,18 @@ target_link_libraries(ARMixConsole PRIVATE include(CTest) if(BUILD_TESTING) + add_executable(ARMixMixerRoutingTests tests/mixer_routing_plan_test.cpp) + target_compile_features(ARMixMixerRoutingTests PRIVATE cxx_std_20) + add_test(NAME TenStripStaticRoutingAndMaster COMMAND ARMixMixerRoutingTests) + add_executable(ARMixChannelRoutingContractTests tests/channel_routing_contract_test.cpp) + target_compile_features(ARMixChannelRoutingContractTests PRIVATE cxx_std_20) + add_test(NAME MonoStereoSparsePhysicalPortRouting COMMAND ARMixChannelRoutingContractTests) + add_executable(ARMixChannelSendTests tests/channel_send_plan_test.cpp) + target_compile_features(ARMixChannelSendTests PRIVATE cxx_std_20) + add_test(NAME TenChannelAcyclicPrePostSends COMMAND ARMixChannelSendTests) + 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(ARMixOrbitPhaseTests tests/orbit_phase_test.cpp) target_compile_features(ARMixOrbitPhaseTests PRIVATE cxx_std_20) add_test(NAME VstAzimuthOrbitRamp COMMAND ARMixOrbitPhaseTests) diff --git a/docs/P1A_REAL_MIXER_ROUTING_CORE_20261028.md b/docs/P1A_REAL_MIXER_ROUTING_CORE_20261028.md new file mode 100644 index 000000000..7d5baf688 --- /dev/null +++ b/docs/P1A_REAL_MIXER_ROUTING_CORE_20261028.md @@ -0,0 +1,32 @@ +# ArSonMix P1A — verified foundation for real 10-channel routing + MASTER (2026-10-28) + +Baseline: `main@de683b001a5a1e5e050bc20ddb52d32b22fa58d1`. Scope: **pure DSP core plus deterministic C++ tests, no live activation**. Superseded/stale UI-DSP PRs must not be bulk merged. Owner's global priority remains stable ultra-low-latency Windows audio and the approved v0.8 GUI; this is not a release or a hardware certification. + +## Why this milestone exists + +The current JUCE native callback (`src/LiveAudioEngine.h`) processes one stereo input source through one VST3 chain to the master; `src/Main.cpp` currently consumes channel fader/pan/mute only for Channel 1. Its ten other GUI channel/MASTER insert surfaces cannot be called native live FX until a real input/bus topology exists. Issue #15 **0-FX hardware crackle** remains a release gate, and the Smart Audio Engine ARD explicitly prohibits activating P2.6 live multi-channel DSP until that hardware gate passes. + +## Implemented: device-independent, offline-prepared routing contract + +`engine/core/MixerRoutingPlan.h`: + +- Exactly 10 source strips + one MASTER. Every source starts **disconnected** (never invented or assigned to an arbitrary device pin). Physical input indexes are explicit; mono/stereo slots do not infer a nonexistent stereo device. +- The control thread validates *all* channel mappings, valid numeric parameters, stereo channel separation, source mode and physically negotiated input count. It compiles a temporary plan and atomically **as a unit at the API boundary** replaces the output Plan only on complete success. The caller must still publish the Plan across threads safely; **this implementation does not yet provide a graph swap or cross-thread publication**. +- Precomputed equal-power mono pan and stereo-balance coefficients; logical SOLO/MUTE arbitration; fader level, MASTER gain/PAN/mute/mono. No per-sample trig, heap, logging, scans or device operations. +- `extract(strip,...)` reads true physical channel input into preallocated stereo scratch, preserving stereo. `accumulate(strip,...)` sums post-FX stereo scratch into the MASTER mix. `finishMaster(...)` applies MASTER controls after the future master FX chain. +- Unassigned or unavailable physical input returns silence and `false` from `extract`; it never masquerades as a live VST3 or fabricates VU levels. + +## Engineering invariants / tests + +`tests/mixer_routing_plan_test.cpp` covers 10 independent mono sources, separate left/right physical inputs, stereo identity, mono centered -3 dB law, panic/mute/solo correctness, M/S output summing, invalid physical input and duplicate L/R index, non-finite pan, gain bounds, unknown source modes, recompile rollback and null/insufficient input availability. Existing Windows CTest builds `ARMixMixerRoutingTests` as part of the established workflow (no extra workflow or redundant matrix). + +## Next integration gates (deliberately not marked complete) + +1. Issue #15 must be physically gated for **0 FX** (OUTPUT_ONLY_TONE, CAPTURE_ONLY, DRY_THROUGH; negotiated driver rate/period and capture/renderer evidence). A CTest pass is not a substitute. +2. Create `SourceRegistry` populated from *actual* ASIO/WASAPI/virtual input endpoints, mapping by explicit per-channel source ID, not hard-coded GUI label or default fake input. Preserve robust DirectFence/independent clocks. +3. Allocate fixed scratch/master buffers ahead of callback; each source: `extract → channel VST chain → fader/pan/mute/solo accumulate`, then `MASTER FX → finishMaster → actual output`. Avoid feedback paths for FX Return. Handle mono/stereo VST bus layout and channel-local plugin/editor/Orbit identity. +4. Publish immutable source/routing snapshots at audio block boundary using the existing `LiveGraphHandoff` epoch/quiescent retirement pattern. No graph destruction, initialization, allocations, locks or device restarts on callback. Support transaction rollback, ACK and source availability status. +5. Verify per-source meters against true post-FX levels; add callback budget profiling, cross-channel isolation, device hotplug, recall, latency/PDC and minimum-buffer soak tests. No guaranteed click-free VST order change until measured on the real device. +6. Only then enable `ADD FX` for CH2–10 and MASTER in native GUI. An unrouted channel must show a truthful disabled/unassigned status until activation. + +No installer/runtime changes are included in this milestone. Public/private binary feature parity and the portable VST Vault rules remain unchanged. diff --git a/docs/P1B_MONO_STEREO_PORT_CONTRACT_20261028.md b/docs/P1B_MONO_STEREO_PORT_CONTRACT_20261028.md new file mode 100644 index 000000000..983986b95 --- /dev/null +++ b/docs/P1B_MONO_STEREO_PORT_CONTRACT_20261028.md @@ -0,0 +1,56 @@ +# P1B — Independent mono/stereo strips and sparse physical-port contract + +**Date:** 2026-10-28 +**Parent:** [P1A real 10-strip routing PR #108](https://github.com/masarray/arsonmix/pull/108) +**Product authority:** [Routing and mono/stereo ARD #109](https://github.com/masarray/arsonmix/issues/109) +**Safety boundaries:** [P0 0-VST crackle #15](https://github.com/masarray/arsonmix/issues/15), [FX reorder #102](https://github.com/masarray/arsonmix/pull/102), [portable performance #85](https://github.com/masarray/arsonmix/issues/85) + +## Scope, not promotional claims + +P1B extends the **control-thread-compiled, device-independent P1A DSP primitive**. It does **not** open ASIO/WASAPI, replace `LiveAudioEngine.h`, enable audio inputs for CH2–10, change the native WebView2 GUI, make sends live, or perform runtime VST3 mono/stereo layout negotiation. No Windows hardware FAT or live crackle guarantee is claimed. + +The new `engine/core/ChannelRoutingContract.h` adds: + +1. **Three independent channel-format choices:** `followSource` (default compatibility), `mono`, and `stereo`. A source can independently be `disconnected/mono/stereo`. These typed selections avoid the common error of treating source width and channel processing width as the same property. +2. **Device callback port mapping:** an explicitly provided list of actual enabled *physical ports in callback-pointer order*. `InputPortMap` verifies every port index is within the implementation boundary 0–255, has no duplicates, and maps physical port ID to dense callback pointer index. **This list must come from the opened device, not inferred from channel labels.** JUCE callback pointer ordering and each device's active bitsets need implementation/proof in the forthcoming adapter. +3. **Sparse/nonadjacent input choices:** physically numbered port 2 may be callback[1], and stereo L=5, R=7 may be callback[0] and callback[2]. Any unavailable physical port fails closed; existing routing plan is retained. The same hardware input may feed several independent mixer strips. +4. **Format conversion:** stereo → mono input folds down `0.5*(L+R)` before channel FX scratch; mono → stereo is explicitly dual mono, with the existing equal-power mono pan law (-3 dB center, unity at hard left/right). The stereo→mono path uses a mono equal-power panner and the ordinary stereo→stereo path retains L/R balance. +5. **Prepared-only parameters:** format-dependent pan coefficients and physical mapping are compiled before audio RT. `extract` and `accumulate` are fixed-size, allocation-free operations on caller-owned preallocated buffers. No cache lookup, lock, device query, resize, VST construction, event emit, or thread spawning in callback. + +## Important DSP rules for integration + +- This P1B implementation models **channel format before FX**, not the plugin bus layout. Stereo reverb on a mono track may legitimately turn a mono-input DSP channel into a stereo-output FX path. Do not downmix the post-FX wet signal without explicit routing/policy. The actual negotiated plugin input/output bus layout (mono, stereo, mono-in/stereo-out) belongs to the next FX adapter gate. +- A mono source duplicated to stereo is *dual mono*, not claimed stereophonic width. A regular stereo source is not accidentally collapsed. The chosen -3 dB center mapping is a deliberate compatibility law, **not** a universal acoustical loudness guarantee when stereo plugins introduce decorrelated components. +- The simple `0.5*(L+R)` downmix can cancel anti-phase material. Show a phase/correlation warning in the eventual UI when appropriate; do not add a hidden signal-level maximizer. +- Legacy P1A `Plan` is composed, not rewritten or forked. Existing P1A default settings retain their behavior. There is no duplicate audio engine. +- The existing caller must publish validated routing plans via an explicit RT-safe ownership/epoch protocol. **P1B's all-or-nothing compile does not itself implement a cross-thread graph swap.** Device generation, graph generation, UI request/ACK and no stale update are next-stage requirements. +- Raw device-scoped physical indices are not portable stable identities. Workspace restore must check endpoint identity + per-port identity/label against the current driver, present missing/unmapped status and require user confirmation before live activation. Never silently reassign CH1 mic or monitor speaker. +- If the requested input port is outside the driver's current **active mask**, enabling it may need explicit Audio Setup and a device restart. Switching between already enabled ports can be compiled without reopening, once safe graph publication exists. Do not claim universally click-free switching. + +## Tests in existing Windows CTest + +`tests/channel_routing_contract_test.cpp` checks: sparse callback pointer order, nonadjacent stereo L/R, independent mono/stereo output coefficients, stereo-to-mono fold, center pan level continuity, invalid/missing ports, duplicate enabled port, invalid format, rejection without partial mutation, cross-strip input fanout, and corrupt NaN parameters. + +Both `channel_routing_contract_test.cpp` and the inherited `mixer_routing_plan_test.cpp` explicitly restore assertions if `NDEBUG` is defined. This is important: native Windows Release CI otherwise compiles `assert()` away, accidentally reporting a test PASS without executing assertions. + +New CTest target: `MonoStereoSparsePhysicalPortRouting`. No separate CI workflow. Local GCC 20 optimization with AddressSanitizer/UndefinedBehaviorSanitizer passed on the new contract; Microsoft MSVC/Windows CI and real hardware must be checked separately. + +## Approved GUI plan (not yet enabled) + +**Preserve the existing user-approved 10-strip + MASTER console**, faders, meters, FX inserts and current compact visual language. + +- Main strip displays compact `SOURCE` (e.g. `IN 3`, `IN 5/7`, `CH 1`) and clearly distinct `MONO/ST` format indicator, not a misleading `M` icon confused with MUTE. +- Click SOURCE to open a lightweight anchored chooser of current valid hardware mono/stereo L/R pairs and internal sends. An inspector provides L and R independent selectors, source width/processing format, output bus, send pre/post fader, and input status. Only route kinds actually supported by native engine are enabled. +- Advanced Patchbay matrix visualizes all channels and ports without ten giant popovers. No blur/glow filters, no heavyweight hover shaders, no per-channel animation timers or fake meters. Use existing shared visual scheduler and byte-identical CSS/build assets. +- UI changes are **request → pending → native ACK/reject**, never optimistic localStorage authority for audio. Failure keeps the prior DSP route. Missing hardware is named, not silently reassigned. +- Preview mode uses a clearly labelled simulated topology and cannot be mistaken for real native audio. + +## Next gates, strictly ordered + +1. Review this P1B stacked PR against #108; Windows CTest + native build must PASS before integrating. Never merge the stacked PR directly into main without its parent P1A. +2. Native `DevicePortRegistry`: enumerate actual negotiated device channel masks and map physical ports to callback pointers, then verify on ASIO 4+/8+ channel hardware and WASAPI variants. No hidden channel re-open. +3. Implement per-strip prepared DSP state and mono/stereo plugin bus negotiation, then controlled graph publication with device epoch, ACK, smooth mute/ramp, and deferred destruction. Reuse existing LiveGraphHandoff patterns; do not co-own one VST processor in two concurrent execution graphs. +4. Add true SOURCE/MONO/ST controls and advanced Patchbay only when live native engine can execute them. Complete native sends, output mapping and latency compensation, plus portable state persistence. +5. Prove no-VST baseline #15 and perform multi-channel physical FAT, hotplug recovery, callback deadlines, audio isolation, clicks and real VST3 vendor states. Hardware test is the release gate. + +**Definition of P1B completion:** checked-in pure routing code + passing deterministic release-mode assertions, not a new user-ready EXE. diff --git a/docs/P1C_INTERNAL_SENDS_DAG_20261028.md b/docs/P1C_INTERNAL_SENDS_DAG_20261028.md new file mode 100644 index 000000000..4a25de65c --- /dev/null +++ b/docs/P1C_INTERNAL_SENDS_DAG_20261028.md @@ -0,0 +1,50 @@ +# ArSonMix P1C — Acyclic per-channel sends and internal bus routing core + +**Date:** 2026-10-28 +**Base:** P1B stacked PR #110 (which depends on P1A PR #108) +**Status:** Prepared DSP core + deterministic native C++ tests. **NOT wired to live JUCE audio device or VST3.** +**Related:** #109 track routing, #95 channel FX, #15 hardware 0-FX crackles, #85 portable workspaces. + +## Native audio topology contract + +One physical input may fan out to multiple strips by explicit selection. Each strip independently processes its input FX, post-FX/pre-fader signal, its gain/mute/pan stage, and sends to another strip. P1C compiles **up to 32 sends** between ten strips (bounded, deterministic). No arbitrary 32-channel hardware restriction is implied: 32 is the temporary explicit capacity for *send edges*, not devices or input channels. + +`engine/core/ChannelSendPlan.h` provides: + +- One `SendDefinition`: source strip, destination strip, pre/post-fader tap, linear send gain, stereo balance and enabled flag. +- `SendRequest::toMaster[channel]`: independent default main-out control (true by default). A sends-only channel can turn off its direct MASTER path, avoiding unwanted double-feed. +- **Cycle detector:** reject CH1→CH2→CH1 and longer loops and self-feedback before activation. A deterministic Kahn topological sort prepares the actual processing order. Enabling a rejected edge leaves the previous plan unchanged. +- **Signal correctness:** pre-fader send comes from the *post-FX pre-fader* source buffer; post-fader send comes from *post-fader/post-mute* source buffer, provided by the future host integration. Different tap choices are not silently interchanged. Pre-fader sends intentionally do not follow fader attenuation; final policy for how solo/mute affects pre sends must be explicit in the native mixer host. +- **No implicit feedback or implicit master sends:** MASTER remains downstream of all strips. A MASTER-to-channel return requires a separate latency/feedback-safe graph contract and is deliberately unavailable at P1C. +- Direct send routing is additive to the channel's main output; `toMaster=false` is the way to construct an explicit sends-only source. The actual output stage must respect this flag before the feature is enabled. +- Sends support per-edge stereo balance; they do not currently perform an automatic stereo-to-mono conversion. The independent format contract of P1B must select channel DSP width, and insert-plugin layout negotiation remains a separate requirement. + +## Realtime performance model + +All validation, float finite checks, duplicate checks, cycle sorting, output offsets and send gain/pan coefficients are computed **off realtime** by `ChannelSendPlan::compile`. Plan publication is **not** implemented yet. `dispatch` loops only over the active source's outgoing edges and the host-provided fixed sample count, accumulating into preallocated, already-cleared destination buffers. No heap, locks, sample-loop trigonometry, topology scans, telemetry string allocations, graph destruction or plugin creation in this primitive. + +The future RT integration must provide correctly scoped scratch buffers: +1. At the start of **each audio block**, clear **every** per-strip destination/incoming-send accumulator exactly once; also prepare each strip's physical input scratch. Use `ChannelRoutingPlan::extract` **before** any internal-send dispatch, because `extract` overwrites scratch. Never clear the destination after an upstream send has already written to it. +2. Walk `topologicalOrder` once, combining that strip's prepared physical input and previously accumulated upstream sends into its *own* preallocated input buffer, then run its VST3 chain exactly once. Capture its post-FX/pre-fader tap. +3. Apply fader/mute/solo/pan to a distinct scratch output, capture its post-fader tap, and dispatch each configured pre/post tap only from the correct buffer. Do not reuse a destination accumulator as a source. +4. `receivesInternalAudio(strip)` is true for any bus-return recipient, **even if its hardware SourceMode is disconnected**. The future host must not skip a return merely because P1A/P1B's physical-only `Strip::active` is false. The return's effective gain/mute/solo state must be applied separately, without processing an invented physical input. +5. Mix only `toMaster=true` strips to MASTER; run MASTER FX and final output controls once, then send to the selected driver output. `toMaster=false` prevents duplicate dry+send output. +6. The routing plan, channel VST instances, plugin editors, Orbit references and negotiated device source identity must be changed through a single safe graph epoch/handoff/ACK protocol. Never process the same VST3 instance concurrently in old/new graphs. + +Input device masks, hotplug and callback port indices are owned by P1B + forthcoming device registry. P1C cannot prove stable hardware timing and must not be enabled on top of a failing zero-VST hardware FAT (#15). + +## Tests / boundaries + +`tests/channel_send_plan_test.cpp` verifies: zero-send defaults, deterministic 10-strip order, pre vs post taps, send pan and gain, fan-out, fan-in, main-out disable, cycle/self-loop rejection, duplicate edge prevention, invalid indices, gain, pan and tap, disabled edges, over-capacity, transaction rollback and invalid buffer guard, plus audio-return activity with no physical port. Windows Release `assert` is kept enabled even under `NDEBUG` so CTest is meaningful. No redundant GitHub Action matrix. + +The planned GUI should offer a compact SOURCE chooser and channel Sends inspector. Only show a real send selection when both source and destination are native connected buses; all routed requests use native ACK/reject. No full DOM redraw on pointer movements and no fake meter. + +## Delivery sequencing + +1. P1A #108 exact-head green, then merge it after verifying current `main` and unrelated PR ownership. +2. P1B #110 exact-head green, retarget after parent merge; merge with no conflict and no regression. +3. P1C this stacked PR exact-head green; retarget after P1B merge. +4. Real device registry (stable endpoint/port IDs), immutable graph/device epoch lifetime, and true per-channel plugin bus negotiation. +5. Only after issue #15 clean 0-FX physical FAT: staged live 2-channel, 4-channel, then 10-channel hardware acceptance with sends, recall, Orbit, all FX operations, and measured xrun/callback deadlines. + +**No claim of full live 10-channel FX, click-free sends or hardware performance certification is made by this milestone.** diff --git a/docs/P1D_INTEGRATED_TEN_CHANNEL_DSP_20261028.md b/docs/P1D_INTEGRATED_TEN_CHANNEL_DSP_20261028.md new file mode 100644 index 000000000..eff03fa08 --- /dev/null +++ b/docs/P1D_INTEGRATED_TEN_CHANNEL_DSP_20261028.md @@ -0,0 +1,30 @@ +# P1D — INTEGRATED TEN-CHANNEL DSP MILESTONE (2026-10-28) + +**Source-of-truth:** this integration branch is forked directly from current main at `c0d7c794a27fcdc7adbe77c6166a2e97b848b82c`. The narrow CMake and Windows workflow edits preserve P0 sample-accurate FX bypass and all device/Orbit protections on main. It consolidates P1A #108, P1B #110, P1C #111 and adds a genuine **single-pass 10-strip audio block executor**. It does **not** silently merge old UI branches. + +## Shipped in this integration milestone (native C++, device independent) +- `MixerRoutingPlan.h`: 10-channel gain/pan/mute/solo/master DSP primitives. +- `ChannelRoutingContract.h`: independent MONO/STEREO channel format and explicitly enabled (potentially sparse/noncontiguous) physical input port-to-callback buffer translation. Precompiled mono-to-stereo dual-mono and stereo-to-mono fold policy. +- `ChannelSendPlan.h`: validated max 32 pre/post-fader routes, deterministic DAG order, no feedback/self sends, no accidental duplicate sends, control-thread compile/rollback. +- `PreparedMixerBlock.h`: allocates a bounded planar buffer arena once before realtime. One `process()` actually mixes physical inputs and internal receives, processes channel FX hook, dispatches pre-fader taps, applies independent gains/pan/solo/mute, dispatches post-fader taps, supports returns with NO physical input, sums to stereo master, runs master FX hook and applies master controls. RT path is bounded, no heap/mutex/UI/driver calls; FIXED order and buffer. No one-thread-per-strip. +- Four executable C++ acceptance tests, with asserts enabled in `-DNDEBUG` Windows Release; new `TenChannelEndToEndPreparedAudioRender` test exercises actual audio sample vectors through the full graph, master peaks, post-fader and pre-fader bypass behavior, fanout, returns, SOLO graph closure, invalid routing rollback, no-RT-allocation tracking and 1000 repeated blocks. Older P1A/B/C tests remain. +- Registered in existing `p1-windows.yml` CMake native build + CTest, no duplicate workflow. P0, GUI and plugin files untouched. + +## Correctly limited scope +- This graph is an **executable DSP integration**, not merely a planning document, and not an actual live Windows-device implementation. It does NOT replace `src/LiveAudioEngine.h` callback, change physical ASIO capture masks, instantiate VST3, wire new per-strip UI or create an artifact that proves CH2-10 on hardware. +- `Fx` hook is a `noexcept` caller-supplied native function object; **mono-only / mono-in-stereo-out VST3 bus negotiation and plugin instance lifetime are not yet implemented**. The hook is a testable seam, not a plugin adapter. +- The default exact 10-strip / max32 sends / max8192-frame limits are current bounded implementation sizes, NOT a whitelist on the user's VST library or an audio-interface input limit. +- Live production graph changes require atomic block-boundary plan publication, device/graph generation fences, safe de-click ramp/crossfade, non-RT retirement and UI ACK. This milestone intentionally does not bypass those gates. +- Physical device `portId` needs stable identity over session/workspace, driver channel-mask actual mapping, and explicit user action if an inactive pin requires a device restart. Do not silently bind hardware to another port. +- At a live use case with physical upstream AND internal input on same channel, samples sum deliberately. Meter provenance, overload and phase warning need qualification. +- Solo semantics: SOLO strip's upstream ancestors and downstream descendants stay audible; unrelated sends into a downstream return do not leak. MUTE kills all sends in this initial policy; pre-fader sends ignore fader but obey MUTE. FX tails when strips become unassigned need explicit future lifecycle/hold policy. +- Audio stability issue #15 (0-FX crackle) is not solved by this graph; **Windows live hardware FAT is still blocking production activation**. + +## Follow-on hardware integration: not marked completed +1. Finish #15 0-FX connected-audio proof for single-clock ASIO, virtual input, WASAPI/BT and real render underrun provenance. +2. Implement device-port registry/control thread; negotiate active channel masks and map exact JUCE callback pointer order for enabled ports. +3. Create channel-specific VST instance/bus layouts and a graph publisher with revision+epoch+ACK and RT-safe retirement. Reuse validated plugin instances without concurrent process in old/new graphs. +4. Enable CH1–10 native routing in production only after hardware/device identity guards and telemetry; then render truthful native meters and compact SOURCE + MONO/ST inspector with no heavy blur / animation. +5. Complete AUX outputs/sends/multi-output patchbay, PDC and portable performance restore, with measured hardware validation. + +**No fabricated claim:** CI success only confirms software contracts and Windows compilation, never sound quality, hardware routing, or low-latency audio. diff --git a/engine/core/ChannelRoutingContract.h b/engine/core/ChannelRoutingContract.h new file mode 100644 index 000000000..1eb5e8d33 --- /dev/null +++ b/engine/core/ChannelRoutingContract.h @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "MixerRoutingPlan.h" +#include +#include +#include +#include +#include + +// P1B: device-independent, offline-compiled MONO/STEREO channel contract. +// An enabled physical port is NOT a callback pointer ordinal: sparse ASIO +// masks must be translated by the backend at device setup, never on audio RT. +// This unit deliberately does not activate any JUCE device, FX or mixer GUI. +namespace armix::mixer { + +constexpr int maxPhysicalPorts = 256; + +enum class ChannelFormat : std::uint8_t { followSource, mono, stereo }; +enum class LayoutFault : std::uint8_t { + none, invalidPhysicalPort, duplicateEnabledPort, unavailableSourcePort, + invalidChannelFormat, basePlanRejected +}; +struct LayoutError final { + LayoutFault fault = LayoutFault::none; + int strip = -1; + int physicalPort = -1; + Error baseError {}; +}; + +// Backend-owned control code MUST supply ports in the exact callback pointer +// order negotiated with the driver. Enumerated labels alone are insufficient. +// The physical-port index is device-scoped; portability requires endpoint-ID +// and port-ID validation when restoring a saved Performance on a new PC. +struct InputPortMap final { + std::array callbackIndex {}; + int enabledCount = 0; + + static bool prepare(std::span callbackOrderedPhysicalPorts, + InputPortMap& out, LayoutError& error) noexcept { + error = {}; + if (callbackOrderedPhysicalPorts.size() > maxPhysicalPorts) { + error.fault = LayoutFault::invalidPhysicalPort; + return false; + } + InputPortMap candidate; + candidate.callbackIndex.fill(-1); + for (std::size_t i = 0; i < callbackOrderedPhysicalPorts.size(); ++i) { + const int port = callbackOrderedPhysicalPorts[i]; + if (port < 0 || port >= maxPhysicalPorts) { + error.fault = LayoutFault::invalidPhysicalPort; + error.physicalPort = port; + return false; + } + if (candidate.callbackIndex[port] != -1) { + error.fault = LayoutFault::duplicateEnabledPort; + error.physicalPort = port; + return false; + } + candidate.callbackIndex[port] = static_cast(i); + } + candidate.enabledCount = static_cast(callbackOrderedPhysicalPorts.size()); + out = candidate; + return true; + } + int callbackFor(int physicalPort) const noexcept { + return physicalPort >= 0 && physicalPort < maxPhysicalPorts + ? callbackIndex[physicalPort] : -1; + } +}; + +struct ChannelRoutingConfig final { + Configuration stripsAndMaster {}; + std::array formats {}; // all followSource by default +}; + +struct ChannelRoutingPlan final { + // Existing P1A Plan remains authoritative for mixing/solo/master controls. + Plan base {}; + std::array effectiveFormats {}; + std::array foldStereoToMono {}; + InputPortMap inputPorts {}; + + // Compile/reject on the control thread. Destination is only updated after + // every source, physical pin, mode, gain, pan and master rule passes. + static bool compile(const ChannelRoutingConfig& requested, + std::span callbackOrderedPhysicalPorts, + ChannelRoutingPlan& destination, + LayoutError& error) noexcept { + error = {}; + InputPortMap ports; + if (!InputPortMap::prepare(callbackOrderedPhysicalPorts, ports, error)) + return false; + + Configuration mapped = requested.stripsAndMaster; + std::array effective {}; + std::array folded {}; + for (int i=0; i +#include +#include +#include +#include + +// P1C: bounded, allocation-free compile-only bus/send scheduler. +// This is NOT installed on the live JUCE audio thread. Publishing a Plan +// later requires device/graph epoch validation and a quiescent handoff. +// In a future callback, process channels in topologicalOrder, take POST-FX +// buffers for preFader sends, and take POST-FADER/POST-MUTE buffers for +// postFader sends. Pre-fader send mute/solo policy belongs to caller. +namespace armix::mixer { + +constexpr int maxChannelSends = 32; + +enum class SendTap : std::uint8_t { preFader, postFader }; +struct SendDefinition final { + int source = -1; + int destination = -1; + SendTap tap = SendTap::postFader; + float gain = 1.f; + float pan = 0.f; // stereo BALANCE, not mono equal-power panning + bool enabled = true; +}; +struct SendRequest final { + std::array toMaster {}; + std::array sends {}; + int count = 0; + SendRequest() noexcept { toMaster.fill(true); } +}; +enum class SendFault : std::uint8_t { + none, tooManySends, invalidCount, invalidStrip, selfFeedback, + invalidTap, invalidGain, invalidPan, duplicateSend, cycleDetected +}; +struct SendError final { + SendFault fault = SendFault::none; + int sendIndex = -1; + int strip = -1; +}; + +// Entire plan is immutable once published to a callback. No heap or +// dynamically sized vectors. All floating-point coefficient calculation, +// validation, and Kahn topological sorting occur on control thread ONLY. +struct ChannelSendPlan final { + struct Edge { + int destination = -1; + SendTap tap = SendTap::postFader; + float leftGain = 0.f, rightGain = 0.f; + }; + std::array orderedEdges {}; + std::array outgoingOffset {}; + std::array topologicalOrder {}; + std::array orderRank {}; + std::array toMaster {}; + // A strip can be a BUS RETURN even without any physical input; do not + // gate these strips on ChannelRoutingPlan::Strip::active (physical only). + std::array receivesInternal {}; + int edgeCount = 0; + + static bool compile(const SendRequest& requested, + ChannelSendPlan& destination, + SendError& error) noexcept { + error = {}; + if (requested.count < 0) { + error.fault = SendFault::invalidCount; return false; + } + if (requested.count > maxChannelSends) { + error.fault = SendFault::tooManySends; return false; + } + ChannelSendPlan candidate; + candidate.toMaster = requested.toMaster; + std::array outgoingCount {}; + std::array indegree {}; + for (int i=0;i=stripCount || + s.destination<0 || s.destination>=stripCount) { + error={SendFault::invalidStrip,i,s.source};return false; + } + if (s.source==s.destination) { + error={SendFault::selfFeedback,i,s.source};return false; + } + if (s.tap!=SendTap::preFader && s.tap!=SendTap::postFader) { + error={SendFault::invalidTap,i,s.source};return false; + } + if (!std::isfinite(s.gain)||s.gain<0.f||s.gain>4.f) { + error={SendFault::invalidGain,i,s.source};return false; + } + if (!std::isfinite(s.pan)||s.pan< -1.f||s.pan>1.f) { + error={SendFault::invalidPan,i,s.source};return false; + } + // One edge per source/destination/tap. Different tap types may + // coexist, but identical duplicates would double the signal. + for (int j=0;j0.f?1.f-s.pan:1.f); + e.rightGain=s.gain*(s.pan<0.f?1.f+s.pan:1.f); + } + // Kahn's algorithm; deterministic ascending tie-break between strips. + std::array emitted {}; + for (int k=0;k=stripCount||frames<=0||!sourceLeft||!sourceRight|| + !inputLeft||!inputRight)return; + for(int e=outgoingOffset[source];e=0&&strip=0&&strip=0&&source=0&& + destination +#include +#include +#include + +// Phase P1: prepared, device-independent 10-strip + MASTER routing primitive. +// NO connection to the live audio callback yet. All topology changes must be +// compiled on the control thread and published using a quiescent/epoch handoff. +// Only read/accumulate/master belong in the realtime callback. +namespace armix::mixer { + +constexpr int stripCount = 10; + +enum class SourceMode { disconnected, mono, stereo }; + +struct StripConfig final { + SourceMode source = SourceMode::disconnected; + int inputA = -1, inputB = -1; // physical input indices, never GUI labels + float faderLinear = 1.0f; // UI dB conversion happens on control thread + float pan = 0.0f; // -1 = left, 0 = center, +1 = right + bool mute = false, solo = false; +}; +struct MasterConfig final { + float gainLinear = 1.0f; + float pan = 0.0f; + bool mute = false, mono = false; +}; +struct Configuration final { + std::array strips {}; + MasterConfig master {}; +}; +enum class Fault { none, invalidInputCount, inputOutOfRange, duplicateStereoInput, + invalidSourceMode, invalidGain, invalidPan }; +struct Error final { + Fault code = Fault::none; + int strip = -1; // -1 denotes master/device rather than a source strip +}; + +struct CompiledStrip final { + int inputA = -1, inputB = -1; + SourceMode mode = SourceMode::disconnected; + bool active = false; // muted, disconnected and solo-excluded are never routed + float leftGain = 0.f, rightGain = 0.f; +}; + +struct Plan final { + std::array strips {}; + int physicalInputs = 0; + float masterGain = 1.f, masterLeftBalance = 1.f, masterRightBalance = 1.f; + bool masterMono = false; + int activeStrips = 0; + + // Control thread ONLY. Rejection leaves previous plan untouched. + // Unassigned strips are legal and always silent, never fake VST buses. + static bool compile(const Configuration& cfg, int inputCount, Plan& destination, + Error& error) noexcept { + error = {}; + if (inputCount < 0 || inputCount > 256) { + error = {Fault::invalidInputCount,-1}; + return false; + } + if (!validGain(cfg.master.gainLinear)) { + error = {Fault::invalidGain,-1}; return false; + } + if (!validPan(cfg.master.pan)) { + error = {Fault::invalidPan,-1}; return false; + } + bool anySolo = false; + for (int i=0;i=inputCount || + (c.source==SourceMode::stereo && (c.inputB<0 || c.inputB>=inputCount))) { + error={Fault::inputOutOfRange,i};return false; + } + if (c.source==SourceMode::stereo && c.inputA==c.inputB) { + error={Fault::duplicateStereoInput,i};return false; + } + if (c.solo && !c.mute) anySolo = true; + } + Plan candidate; + candidate.physicalInputs = inputCount; + candidate.masterGain = cfg.master.mute?0.f:cfg.master.gainLinear; + candidate.masterMono = cfg.master.mono; + candidate.masterLeftBalance = cfg.master.pan>0.f?1.f-cfg.master.pan:1.f; + candidate.masterRightBalance = cfg.master.pan<0.f?1.f+cfg.master.pan:1.f; + for (int i=0;i0.f; + if (!p.active) continue; + ++candidate.activeStrips; + if (c.source==SourceMode::mono) { + // Equal-power mono panning, computed exactly once per topology edit. + p.leftGain=c.faderLinear*std::sqrt(0.5f*(1.f-c.pan)); + p.rightGain=c.faderLinear*std::sqrt(0.5f*(1.f+c.pan)); + } else { + // Stereo BALANCE, not an accidental crossfeed or stereo collapse. + p.leftGain=c.faderLinear*(c.pan>0.f?1.f-c.pan:1.f); + p.rightGain=c.faderLinear*(c.pan<0.f?1.f+c.pan:1.f); + } + } + destination=candidate; + return true; + } + + // RT: read one physical input source into preallocated stereo FX scratch. + // Stereo processors can consume both channels before accumulate(). + bool extract(int strip,const float* const* inputs,int availableInputs, + float* left,float* right,int frames) const noexcept { + if (!left || !right || frames<=0 || strip<0 || strip>=stripCount) return false; + const auto& route=strips[strip]; + const bool valid=route.active && inputs && + route.inputA>=0 && route.inputA=0 && route.inputB=stripCount || frames<=0 || + !left || !right || !masterL || !masterR) return; + const auto& p=strips[strip]; + if (!p.active) return; + for(int i=0;i=0.f&&v<=4.f; } + static bool validPan(float v) noexcept { return std::isfinite(v)&&v>=-1.f&&v<=1.f; } +}; +} // namespace armix::mixer diff --git a/engine/core/PreparedMixerBlock.h b/engine/core/PreparedMixerBlock.h new file mode 100644 index 000000000..127978f37 --- /dev/null +++ b/engine/core/PreparedMixerBlock.h @@ -0,0 +1,240 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "ChannelSendPlan.h" +#include +#include +#include +#include +#include +#include +#include +#include + +// P1D: one real, deterministic, *device-independent* block execution of +// physical inputs -> ten native strip lanes -> pre/post sends -> returns -> +// stereo master. Not connected to JUCE, ASIO, VST3 or live GUI yet. +// Construct/compile/reclaim on CONTROL thread; process() on ONE audio thread. +// A prepared instance must never be mutated or destroyed while processing. +namespace armix::mixer { + +enum class RenderFault : unsigned char { + none, invalidChannelRouting, invalidSendRouting +}; +struct RenderError final { + RenderFault fault = RenderFault::none; + LayoutError channel {}; + SendError sends {}; +}; + +struct PreparedRenderGraph final { + ChannelRoutingPlan channels {}; + ChannelSendPlan sends {}; + std::array audible {}; + std::array scheduled {}; + std::array leftGain {}; + std::array rightGain {}; + + // Pure control-thread compile: full rollback if any source or send is bad. + // SOLO closure: include direct ancestors and direct descendants (transitive + // within each direction) of soloed strips; do not inadvertently include + // unrelated sources connected to a soloed strip's downstream FX return. + static bool compile(const ChannelRoutingConfig& routing, + std::span callbackOrderedPhysicalPorts, + const SendRequest& sendsRequest, + PreparedRenderGraph& destination, + RenderError& error) noexcept { + error = {}; + PreparedRenderGraph candidate; + if (!ChannelRoutingPlan::compile(routing, callbackOrderedPhysicalPorts, + candidate.channels, error.channel)) { + error.fault = RenderFault::invalidChannelRouting; + return false; + } + if (!ChannelSendPlan::compile(sendsRequest, candidate.sends, error.sends)) { + error.fault = RenderFault::invalidSendRouting; + return false; + } + + const auto& configs = routing.stripsAndMaster.strips; + std::array ancestors {}; + std::array descendants {}; + bool anySolo = false; + for(int i=0;i=0;--k) { + const int source=candidate.sends.topologicalOrder[k]; + for(int e=candidate.sends.outgoingOffset[source]; + e0.f?1.f-c.pan:1.f); + candidate.rightGain[i]=c.faderLinear*(c.pan<0.f?1.f+c.pan:1.f); + } + } + destination=candidate; + return true; + } +}; + +struct RenderLevels final { + std::array channelPeak {}; + float masterPeakL = 0.f, masterPeakR = 0.f; +}; + +// Isolates buffer lifetime and prepared plan from device callback, FX +// instance lifetime and GUI. Build a replacement off RT; swap a POINTER +// only through the host's proven callback-boundary epoch/ack ownership. +class PreparedMixerBlock final { +public: + // The maximum is an implementation bound, NOT an OS device promise. + // Allocations are constructor-only; 20 strip lanes + 2 master lanes. + static constexpr int hardFrameLimit = 8192; + PreparedMixerBlock(const PreparedRenderGraph& plan, int maxFrames) + : plan_(plan), capacity_(maxFrames), + backing_(validCapacity(maxFrames) + ? static_cast(stripCount*2+2)*maxFrames + : 0u, 0.f) { + if (!validCapacity(maxFrames)) + capacity_=0; + if(!capacity_)return; + for(int i=0;i(2*i)*capacity_; + right_[i]=left_[i]+capacity_; + } + masterL_=backing_.data()+static_cast(stripCount*2)*capacity_; + masterR_=masterL_+capacity_; + } + PreparedMixerBlock(const PreparedMixerBlock&)=delete; + PreparedMixerBlock& operator=(const PreparedMixerBlock&)=delete; + PreparedMixerBlock(PreparedMixerBlock&&)=delete; + PreparedMixerBlock& operator=(PreparedMixerBlock&&)=delete; + + int capacity() const noexcept { return capacity_; } + const PreparedRenderGraph& plan() const noexcept {return plan_;} + + // FX callback signature: void(int stripId, float* L, float* R, int frames) + // noexcept, with stripId=-1 for the master FX chain. This interface is + // explicitly stereo scratch, NOT a claim that mono VST bus negotiation is + // solved. The native FX adapter must negotiate sidechain/mono/stereo off RT. + template + bool process(const float* const* physical, int callbackInputCount, + float* outputL, float* outputR, int frames, Fx&& processFx, + RenderLevels* observed=nullptr) noexcept { + static_assert(std::is_nothrow_invocable_v, + "DSP hook must be noexcept and realtime bounded"); + if (observed) *observed={}; + if (frames<=0 || !outputL || !outputR)return false; + std::fill_n(outputL,frames,0.f); + std::fill_n(outputR,frames,0.f); + if (capacity_==0 || frames>capacity_ || callbackInputCount<0) + return false; + for(int i=0;i=0 && + source.inputA=0 && source.inputBchannelPeak[strip]=peak; + graph.sends.dispatch(strip,SendTap::postFader,l,r, + left_.data(),right_.data(),frames); + } + processFx(-1,masterL_,masterR_,frames); + graph.channels.base.finishMaster(masterL_,masterR_,frames); + float peakL=0.f,peakR=0.f; + for(int f=0;fmasterPeakL=peakL; observed->masterPeakR=peakR;} + return true; + } +private: + static bool validCapacity(int f) noexcept {return f>0 && f<=hardFrameLimit;} + const PreparedRenderGraph plan_; + int capacity_=0; + std::vector backing_; // ALLOCATED BEFORE callback, never resized + std::array left_{}; + std::array right_{}; + float* masterL_=nullptr; + float* masterR_=nullptr; +}; +} // namespace armix::mixer diff --git a/tests/channel_routing_contract_test.cpp b/tests/channel_routing_contract_test.cpp new file mode 100644 index 000000000..5098ad068 --- /dev/null +++ b/tests/channel_routing_contract_test.cpp @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/core/ChannelRoutingContract.h" +#include +#if defined(NDEBUG) +#undef NDEBUG // Assertions are test execution, even in Windows Release. +#endif +#include +#include +#include +#include +using namespace armix::mixer; +static bool approx(float a, float b) { return std::abs(a-b) <= 0.00001f; } +int main() { + // Sparse physical ports ordered as the callback really delivers them. + // callback[0] = physical 5, callback[1] = physical 2, + // callback[2] = physical 7. Do not assume ordinal == hardware port. + constexpr std::array enabled={5,2,7}; + ChannelRoutingConfig cfg; + cfg.stripsAndMaster.strips[0]={SourceMode::mono,2,-1,1.f,0.f,false,false}; + cfg.stripsAndMaster.strips[1]={SourceMode::stereo,5,7,1.f,0.f,false,false}; + ChannelRoutingPlan plan; LayoutError error; + assert(ChannelRoutingPlan::compile(cfg,enabled,plan,error)); + assert(plan.inputPorts.callbackFor(2)==1); + assert(plan.inputPorts.callbackFor(5)==0); + assert(plan.inputPorts.callbackFor(7)==2); + assert(plan.inputPorts.callbackFor(0)==-1); + std::array p5={0.8f,-0.8f,0.2f}; + std::array p2={0.2f,0.4f,0.6f}; + std::array p7={0.4f,-0.4f,0.6f}; + const float* callback[]={p5.data(),p2.data(),p7.data()}; + std::array l{},r{},ml{},mr{}; + assert(plan.extract(0,callback,3,l.data(),r.data(),3)); + assert(approx(l[0],0.2f)&&approx(r[0],0.2f)); + plan.accumulate(0,l.data(),r.data(),ml.data(),mr.data(),3); + assert(approx(ml[0],.2f*.70710678f)&&approx(mr[0],.2f*.70710678f)); + assert(plan.extract(1,callback,3,l.data(),r.data(),3)); + assert(approx(l[0],.8f)&&approx(r[0],.4f)); + plan.accumulate(1,l.data(),r.data(),ml.data(),mr.data(),3); + assert(approx(ml[0],.8f+.2f*.70710678f)&&approx(mr[0],.4f+.2f*.70710678f)); + + // Source stereo -> channel MONO: pre-FX calibrated 0.5(L+R), + // then equal-power center pan. Side cancellation is deterministic. + cfg.formats[1]=ChannelFormat::mono; + assert(ChannelRoutingPlan::compile(cfg,enabled,plan,error)); + assert(plan.effectiveFormats[1]==ChannelFormat::mono); + assert(plan.foldStereoToMono[1]); + assert(plan.extract(1,callback,3,l.data(),r.data(),3)); + assert(approx(l[0],.6f)&&approx(r[0],.6f)); + assert(approx(l[1],-.6f)&&approx(r[1],-.6f)); + Plan::clearMaster(ml.data(),mr.data(),3); + plan.accumulate(1,l.data(),r.data(),ml.data(),mr.data(),3); + assert(approx(ml[0],.6f*.70710678f)&&approx(mr[0],ml[0])); + + // Source MONO -> channel STEREO: dual mono, no invented width and + // no +3dB jump compared with original equal-power mono center. + cfg.formats[0]=ChannelFormat::stereo; + assert(ChannelRoutingPlan::compile(cfg,enabled,plan,error)); + assert(plan.extract(0,callback,3,l.data(),r.data(),3)); + Plan::clearMaster(ml.data(),mr.data(),3); + plan.accumulate(0,l.data(),r.data(),ml.data(),mr.data(),3); + assert(approx(ml[0],.2f*.70710678f)&&approx(mr[0],.2f*.70710678f)); + + // Mono source keeps equal-power pan even with STEREO channel format. + // At hard right, level is unity and never unintentionally -3dB. + cfg.stripsAndMaster.strips[0].pan=1.f; + assert(ChannelRoutingPlan::compile(cfg,enabled,plan,error)); + Plan::clearMaster(ml.data(),mr.data(),3); + assert(plan.extract(0,callback,3,l.data(),r.data(),3)); + plan.accumulate(0,l.data(),r.data(),ml.data(),mr.data(),3); + assert(approx(ml[0],0.f)&&approx(mr[0],.2f)); + cfg.stripsAndMaster.strips[0].pan=0.f; + assert(ChannelRoutingPlan::compile(cfg,enabled,plan,error)); + + // Physical mapping rejected transactionally: plan stays bit-exact. + const auto old=plan; + cfg.stripsAndMaster.strips[0].inputA=6; + assert(!ChannelRoutingPlan::compile(cfg,enabled,plan,error)); + assert(error.fault==LayoutFault::unavailableSourcePort && error.strip==0 && error.physicalPort==6); + assert(plan.base.strips[0].inputA==old.base.strips[0].inputA); + cfg.stripsAndMaster.strips[0].inputA=2; + cfg.formats[0]=static_cast(99); + assert(!ChannelRoutingPlan::compile(cfg,enabled,plan,error)); + assert(error.fault==LayoutFault::invalidChannelFormat && error.strip==0); + cfg.formats[0]=ChannelFormat::stereo; + constexpr std::array duplicates={5,2,5}; + assert(!ChannelRoutingPlan::compile(cfg,duplicates,plan,error)); + assert(error.fault==LayoutFault::duplicateEnabledPort && error.physicalPort==5); + constexpr std::array outside={5,256,7}; + assert(!ChannelRoutingPlan::compile(cfg,outside,plan,error)); + assert(error.fault==LayoutFault::invalidPhysicalPort && error.physicalPort==256); + assert(plan.base.strips[0].inputA==old.base.strips[0].inputA); + + // Stereo L and R may be nonadjacent in *physical* space, but + // L/R self alias is invalid (fail-closed, not dual-mono by accident). + cfg.stripsAndMaster.strips[1].inputB=5; + assert(!ChannelRoutingPlan::compile(cfg,enabled,plan,error)); + assert(error.fault==LayoutFault::basePlanRejected); + assert(error.baseError.code==Fault::duplicateStereoInput); + cfg.stripsAndMaster.strips[1].inputB=7; + + // 10 channels share 1 input safely: fanout but no extra device pin. + cfg={}; + for(auto& s:cfg.stripsAndMaster.strips) s={SourceMode::mono,2,-1,1.f,0.f,false,false}; + assert(ChannelRoutingPlan::compile(cfg,enabled,plan,error)); + assert(plan.base.activeStrips==10); + for(int i=0;i::quiet_NaN(); + assert(!ChannelRoutingPlan::compile(cfg,enabled,plan,error)); + assert(error.fault==LayoutFault::basePlanRejected && error.baseError.strip==9); +} diff --git a/tests/channel_send_plan_test.cpp b/tests/channel_send_plan_test.cpp new file mode 100644 index 000000000..5c4b46a37 --- /dev/null +++ b/tests/channel_send_plan_test.cpp @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/core/ChannelSendPlan.h" +#if defined(NDEBUG) +#undef NDEBUG // Windows Release must execute every acceptance assertion. +#endif +#include +#include +#include +#include +using namespace armix::mixer; +static bool close(float x,float y) { return std::abs(x-y)<1.e-6f; } + +int main() { + ChannelSendPlan plan; + SendRequest cfg; + SendError err; + assert(ChannelSendPlan::compile(cfg,plan,err)); + assert(plan.edgeCount==0); + assert(!plan.receivesInternalAudio(3)); + for(int i=0;i CH2 pre-fader, CH1 -> CH4 post-fader, + // CH2 -> CH4 post-fader, CH3 -> CH4 pre-fader. + cfg.toMaster[0]=false; // sends-only source avoids accidental dry duplication + cfg.sends[0]={0,1,SendTap::preFader,.5f,0.f,true}; + cfg.sends[1]={0,3,SendTap::postFader,.4f,1.f,true}; + cfg.sends[2]={1,3,SendTap::postFader,1.f,0.f,true}; + cfg.sends[3]={2,3,SendTap::preFader,1.f,0.f,true}; + cfg.count=4; + assert(ChannelSendPlan::compile(cfg,plan,err)); + assert(plan.edgeCount==4); + // CH4 may be a pure FX Return with no hardware port, but it is active + // as an internal-bus recipient. Physical input availability is separate. + assert(plan.receivesInternalAudio(1)); + assert(plan.receivesInternalAudio(3)); + assert(!plan.receivesInternalAudio(0)); + assert(!plan.receivesInternalAudio(-1)); + assert(!plan.masterEnabled(0)&&plan.masterEnabled(1)); + assert(plan.upstreamOf(0,1)); + assert(plan.upstreamOf(1,3)); + assert(plan.upstreamOf(2,3)); + const std::array one {1.f,-.25f,.75f}; + const std::array two {.5f,.25f,-.5f}; + std::array,stripCount> l{},r{}; + std::array lp{},rp{}; + for(int i=0;i(77); + assert(!ChannelSendPlan::compile(cfg,plan,err)&&err.fault==SendFault::invalidTap); + cfg.sends[4].tap=SendTap::postFader; + cfg.sends[4].gain=std::numeric_limits::infinity(); + assert(!ChannelSendPlan::compile(cfg,plan,err)&&err.fault==SendFault::invalidGain); + cfg.sends[4].gain=.5f; + cfg.sends[4].pan=std::numeric_limits::quiet_NaN(); + assert(!ChannelSendPlan::compile(cfg,plan,err)&&err.fault==SendFault::invalidPan); + cfg.sends[4].pan=0.f; + cfg.sends[4].destination=stripCount; + assert(!ChannelSendPlan::compile(cfg,plan,err)&&err.fault==SendFault::invalidStrip); + cfg.sends[4].destination=1; + cfg.sends[4].enabled=false; + assert(ChannelSendPlan::compile(cfg,plan,err)); + assert(plan.edgeCount==4); // disabled edge never processed + assert(plan.receivesInternalAudio(3)); + cfg.count=maxChannelSends+1; + assert(!ChannelSendPlan::compile(cfg,plan,err)&&err.fault==SendFault::tooManySends); + cfg.count=-1; + assert(!ChannelSendPlan::compile(cfg,plan,err)&&err.fault==SendFault::invalidCount); + // Fails closed on missing input/output pointers and invalid channel id. + std::array sampleLeft {3.f,3.f,3.f},sampleRight {2.f,2.f,2.f}; + plan.dispatch(-1,SendTap::postFader,sampleLeft.data(),sampleRight.data(),lp.data(),rp.data(),3); + plan.dispatch(99,SendTap::postFader,sampleLeft.data(),sampleRight.data(),lp.data(),rp.data(),3); + plan.dispatch(0,SendTap::preFader,nullptr,sampleRight.data(),lp.data(),rp.data(),3); + + // Full 10-strip forward sends graph; source is processed before target. + cfg=SendRequest{}; + cfg.count=stripCount-1; + for(int i=0;i +#if defined(NDEBUG) +#undef NDEBUG // Never skip P1A assertions in Release native CTest. +#endif +#include +#include +#include + +using namespace armix::mixer; +static bool close(float a,float b,float tol=1.e-5f){return std::abs(a-b) a={1.f,2.f,3.f,4.f}; + const std::array b={.25f,.5f,.75f,1.f}; + const std::array c={-1.f,-2.f,-3.f,-4.f}; + const float* input[]={a.data(),b.data(),c.data()}; + std::array l{},r{},ml{},mr{}; + assert(!plan.extract(0,input,3,l.data(),r.data(),4)); + for(int i=0;i<4;++i)assert(l[i]==0.f&&r[i]==0.f); + cfg.strips[0]={SourceMode::stereo,0,1,1.f,0.f,false,false}; + cfg.strips[1]={SourceMode::mono,2,-1,1.f,0.f,false,false}; + assert(Plan::compile(cfg,3,plan,err)&&plan.activeStrips==2); + assert(plan.extract(0,input,3,l.data(),r.data(),4)); + Plan::clearMaster(ml.data(),mr.data(),4); + plan.accumulate(0,l.data(),r.data(),ml.data(),mr.data(),4); + assert(close(ml[0],1.f)&&close(mr[0],.25f)); // stereo transparency + assert(plan.extract(1,input,3,l.data(),r.data(),4)); + plan.accumulate(1,l.data(),r.data(),ml.data(),mr.data(),4); + constexpr float center=.7071067811865475f; + assert(close(ml[0],1.f-center)&&close(mr[0],.25f-center)); + plan.finishMaster(ml.data(),mr.data(),4); + // Muting other bus must be independent, never change strip 0. + cfg.strips[1].mute=true; + assert(Plan::compile(cfg,3,plan,err)&&plan.activeStrips==1); + Plan::clearMaster(ml.data(),mr.data(),4); + assert(!plan.extract(1,input,3,l.data(),r.data(),4)); + assert(plan.extract(0,input,3,l.data(),r.data(),4)); + plan.accumulate(0,l.data(),r.data(),ml.data(),mr.data(),4); + assert(close(ml[3],4.f)&&close(mr[3],1.f)); + // Solo arbitration is determined off RT, and mute wins over solo. + cfg.strips[1].mute=false;cfg.strips[1].solo=true; + assert(Plan::compile(cfg,3,plan,err)&&plan.activeStrips==1); + assert(!plan.extract(0,input,3,l.data(),r.data(),4)); + assert(plan.extract(1,input,3,l.data(),r.data(),4)); + cfg.strips[1].mute=true; + assert(Plan::compile(cfg,3,plan,err)&&plan.activeStrips==1); + assert(plan.extract(0,input,3,l.data(),r.data(),4)); + // Stereo balance and true mono master happen after summing. + cfg.strips[1]={}; + cfg.master={2.f,1.f,false,true}; + assert(Plan::compile(cfg,3,plan,err)); + Plan::clearMaster(ml.data(),mr.data(),4); + assert(plan.extract(0,input,3,l.data(),r.data(),4)); + plan.accumulate(0,l.data(),r.data(),ml.data(),mr.data(),4); + plan.finishMaster(ml.data(),mr.data(),4); + assert(close(ml[0],.25f)&&close(mr[0],.25f)); // right-only, doubled, mono + // Reject illegal hardware routes, NaNs and stereo self-alias; NO partial commit. + const auto old=plan; + cfg.strips[2]={SourceMode::stereo,1,9,1.f,0.f,false,false}; + assert(!Plan::compile(cfg,3,plan,err)&&err.code==Fault::inputOutOfRange&&err.strip==2); + assert(plan.activeStrips==old.activeStrips&&plan.masterMono==old.masterMono); + cfg.strips[2].inputB=1; + assert(!Plan::compile(cfg,3,plan,err)&&err.code==Fault::duplicateStereoInput); + cfg.strips[2]={}; + cfg.strips[0].pan=std::numeric_limits::quiet_NaN(); + assert(!Plan::compile(cfg,3,plan,err)&&err.code==Fault::invalidPan&&err.strip==0); + cfg.strips[0].pan=0.f; + cfg.strips[3].source=static_cast(255); + assert(!Plan::compile(cfg,3,plan,err)&&err.code==Fault::invalidSourceMode&&err.strip==3); + cfg.strips[3]={}; + cfg.master.gainLinear=10.f; + assert(!Plan::compile(cfg,3,plan,err)&&err.code==Fault::invalidGain&&err.strip==-1); + cfg.master.gainLinear=1.f; + assert(!Plan::compile(cfg,-1,plan,err)&&err.code==Fault::invalidInputCount); + // 10 independent mono strips, no fixed 2-channel or 1-channel shortcut. + cfg=Configuration{}; + std::array,stripCount> sources{}; + std::array pointers{}; + for(int i=0;i(i+1); + pointers[i]=sources[i].data(); + cfg.strips[i]={SourceMode::mono,i,-1,1.f,-1.f,false,false}; + } + assert(Plan::compile(cfg,stripCount,plan,err)&&plan.activeStrips==stripCount); + float sumL=0.f,sumR=0.f,cl=0.f,cr=0.f; + for(int i=0;i +#include +#include +#include +#include +#include +#include +#include +#include +using namespace armix::mixer; + +static std::atomic allocations {0}; +// Count realtime allocations, including foreign DSP hooks if accidentally added. +void* operator new(std::size_t n) { + allocations.fetch_add(1,std::memory_order_relaxed); + if(void* p=std::malloc(n==0?1:n))return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept {std::free(p);} +void operator delete(void* p,std::size_t) noexcept {std::free(p);} + +static bool near(float a,float b,float d=0.00002f){return std::abs(a-b) mono {.4f,.4f,.4f,.4f}; + const std::array unrelated {.7f,.7f,.7f,.7f}; + const std::array musicL {.2f,.2f,.2f,.2f}; + const std::array musicR {.6f,.6f,.6f,.6f}; + const float* audio[]={mono.data(),unrelated.data(),musicL.data(),musicR.data()}; + std::array outputL{}, outputR{}; + RenderLevels levels; + int chainCalls=0; std::array visited{}; + auto fx = [&](int strip,float* l,float* r,int frames) noexcept { + visited[chainCalls++]=strip; + if(strip==0) {for(int i=0;i