diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 0aaf424c8..97cebf1da 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -89,7 +89,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 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..a37722ee6 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/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,17 @@ target_link_libraries(ARMixConsole PRIVATE include(CTest) if(BUILD_TESTING) + # P1A/P1B/P1C: compiled and tested now; intentionally NOT connected + # to the JUCE audio callback until control-plane/epoch/hardware FAT exists. + 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(ARMixOrbitPhaseTests tests/orbit_phase_test.cpp) target_compile_features(ARMixOrbitPhaseTests PRIVATE cxx_std_20) add_test(NAME VstAzimuthOrbitRamp COMMAND ARMixOrbitPhaseTests) diff --git a/docs/P1ABC_MAIN_RECONCILIATION_20261028.md b/docs/P1ABC_MAIN_RECONCILIATION_20261028.md new file mode 100644 index 000000000..1783aa27d --- /dev/null +++ b/docs/P1ABC_MAIN_RECONCILIATION_20261028.md @@ -0,0 +1,33 @@ +# P1A/P1B/P1C reconciliation — compiled routing foundations only (2026-10-28) + +## Current main and dependency decision +Integration base: `main@c0d7c794a27fcdc7adbe77c6166a2e97b848b82c`, which includes #106 visually smoothed native LED meters and #107 sample-accurate FX bypass de-click. Existing stacked drafts #108 (P1A), #110 (P1B) and #111 (P1C) were developed against older bases. Original #108 is **merge-dirty** against main after #107 changed the same Windows CMake test/build line. Do **not** force-merge the stale branches or accept replacement of the de-click/Orbit tests. + +This integration takes the reviewed source implementations from head #111, which contains exact ancestry #108 → #110 → #111, then fixes a cross-module pre-fader extraction issue identified during integration review. `extractSource` now makes raw physical capture independent of fader gain, mute and solo, while `extract` retains post-fader MASTER behavior. A new Release regression verifies zero-fader pre-fader sends, muted source taps, and stereo-to-mono raw fold. Only CMake `target_sources`, CTest registration, Windows build target list and this handoff were integrated additively from latest main. No new CI workflows; no base file reset; existing `ARMixFxBypassEnvelopeTests` and `ARMixDearVrPolarPolicyTests` must remain built. All three C++ routing test files have `#undef NDEBUG` *before* `#include ` to keep Release test assertions executing. Previous P1A alone did not have this, so do not revive its raw 2026-10-27 test blob. + +## P1A: deterministic source routing (10 input strips + MASTER) +`engine/core/MixerRoutingPlan.h` compiles mono/stereo input maps, gains, panning, mute/solo, and master mono/gain/balance offline. Fails closed for invalid routes and nonfinite gains/pans. RT extract/accumulate/finish use caller-owned preallocated arrays. See `docs/P1A_REAL_MIXER_ROUTING_CORE_20261028.md`. + +## P1B: source format is separate from callback index +`engine/core/ChannelRoutingContract.h` supports independent `followSource/mono/stereo` formats, a validated callback-index lookup derived from sparse **physical port identities**, and mono fold / dual mono. It does NOT assign live device indices or drive native GUI dropdowns. See `docs/P1B_MONO_STEREO_PORT_CONTRACT_20261028.md`. + +## P1C: static cycle-safe sends +`engine/core/ChannelSendPlan.h` prepares a bounded 32-edge acyclic send graph, deterministic ordering, pre/post-fader taps, send balance, bus-return semantics and `toMaster` flags. No per-pointer-move send commands, no native stage activation. The live-processing caller will be responsible for correct pre/post tap buffers, solo/mute policy and graph-epoch handoff. See `docs/P1C_INTERNAL_SENDS_DAG_20261028.md`. + +## Frozen production boundaries +Current live native chain remains CH1 + MASTER. **CH2–10 and MASTER FX are not yet native multi-bus processing.** Source mapping/FX routing GUI controls must remain disabled/truthful until: (1) physical endpoint ID and callback mask are verified; (2) graph compiled and published with epoch/revision ACK outside RT; (3) deterministic no-heap callback and per-plugin PDC verified; (4) #15 zero-plugin hardware crackle qualification; (5) real-device mono/stereo/multi-input and sends FAT. FX reorder #102 remains separately owned and draft; CI optimization #101 is independent and must not replace native test gates. + +## Verification +- P1A test: `TenStripStaticRoutingAndMaster` +- P1B test: `MonoStereoSparsePhysicalPortRouting` +- P1C test: `TenChannelAcyclicPrePostSends` +- Full existing native CTest and single Windows GUI artifact workflow on exact integration SHA. +- Chromium/Firefox GUI smoke includes the real MASTER L/R LED regression and latest Orbit. +- Validate newest main HEAD, PR review and complete CI prior to merge. Postmerge main CI and Pages must be green. +- This is a **compile-only engineering milestone**, not a functioning 10-channel DAW. Neither FPS on owner's Windows server nor native multi-I/O hardware audio has been qualified. + +## Late reconciliation with PR #101 (2026-10-28) +While integration PR #112 was being validated, another thread merged PR #101 at `main@66989fa46f004aa852207f1159bf3e1b8e9506c1`: path-filtered native PR gates, current-main-only verified Windows FAT artifact, and stale-safe Pages publisher. Its three workflow changes and policy Node tests are now authoritative. PR #112 was reconciled by a two-parent merge commit (no overwriting `main` workflows). Only three native test targets were inserted into **PR #101's** new Windows build list. `tests/ci_workflow_efficiency_test.mjs`, concurrent Pages policy, Chromium/Firefox gate scheduling, mandatory de-click/Orbit CTests, and main-only artifact upload are preserved unchanged. Main CI and full on-head Windows MSVC CTest must re-pass following this integration. + +## Send connectivity correctness gate +The integration audit also corrected `ChannelSendPlan::upstreamOf()`: comparing topological rank alone falsely reported a connection between unrelated strips. The compiled plan now stores a bounded per-source 10-bit descendant mask computed in reverse topological order once during off-RT preparation. Query is O(1); Release CTest proves multihop reachability, disconnected-but-ordered channels, self and reverse negatives. No new runtime graph traversal or heap allocation. 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..d20a966d2 --- /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. Reverse-order propagation then compiles a 10-bit transitive reachability mask for each source. `upstreamOf(a,b)` tests real directed connectivity in O(1), **not** just whether a happens to precede b in an unrelated topological 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::extractSource` **before** any internal-send dispatch, because raw extraction overwrites scratch. This input must not be gated by fader zero or MASTER mute; use `extract` only for the legacy post-fader/solo-controlled path. A pre-fader send must still receive its source at fader -∞, with explicit native mute/solo policy applied later. 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. The integration regression also compiles a real one-port `ChannelRoutingPlan` with source fader zero, proves `extractSource` remains nonzero while master accumulation is silent, and routes a live pre-fader send (plus stereo-to-mono fold and muted-source source read). 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/engine/core/ChannelRoutingContract.h b/engine/core/ChannelRoutingContract.h new file mode 100644 index 000000000..d3ed215be --- /dev/null +++ b/engine/core/ChannelRoutingContract.h @@ -0,0 +1,187 @@ +// 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 mono fold before the plugin. + bool extractSource(int strip, const float* const* input, int availableCallbackInputs, + float* left, float* right, int frames) const noexcept { + if (!base.extractSource(strip,input,availableCallbackInputs,left,right,frames)) + return false; + foldIfMono(strip,left,right,frames); + return true; + } + // Post-fader/master compatibility path (inactive strips remain silent). + bool extract(int strip, const float* const* input, int availableCallbackInputs, + float* left, float* right, int frames) const noexcept { + if (!base.extract(strip,input,availableCallbackInputs,left,right,frames)) + return false; + foldIfMono(strip,left,right,frames); + return true; + } + void accumulate(int strip, const float* left, const float* right, + float* masterL, float* masterR, int frames) const noexcept { + base.accumulate(strip, left, right, masterL, masterR, frames); + } +private: + void foldIfMono(int strip,float* left,float* right,int frames) const noexcept { + if (!foldStereoToMono[strip]) return; + 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 {}; + // True graph reachability, not mere topological rank. Bounded ten-bit + // descendants per source, computed only during non-RT plan compilation. + std::array downstreamMask {}; + 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=0;--k) { + const int source=candidate.topologicalOrder[k]; + std::uint16_t reachable=0; + for(int e=candidate.outgoingOffset[source]; + e( + reachable | (std::uint16_t{1} << child) | + candidate.downstreamMask[child]); + } + candidate.downstreamMask[source]=reachable; + } + destination=candidate; + return true; + } + + // Called by a future callback with caller-owned, nonaliasing buffers. + // Destination scratch MUST be allocated and cleared before processing. + // RT complexity O(outgoingEdges[source] * frames), no dynamic work. + void dispatch(int source,SendTap tap, + const float* sourceLeft,const float* sourceRight, + float* const* inputLeft,float* const* inputRight, + int frames) const noexcept { + if(source<0||source>=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: raw physical extraction for PRE-FADER sends / pre-FX processing. + // Hardware ownership is independent of current fader/mute/solo: at -inf dB + // a pre-fader send can still receive real input. The future caller owns + // explicit pre-send mute/solo policy. No DSP graph is activated here. + bool extractSource(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.mode!=SourceMode::disconnected && inputs && + route.inputA>=0 && route.inputA=0 && route.inputB=stripCount) return false; + if (!strips[strip].active) { + std::fill_n(left,frames,0.f);std::fill_n(right,frames,0.f); + return false; + } + return extractSource(strip,inputs,availableInputs,left,right,frames); + } + + // RT: mix one channel's POST-FX scratch onto the master accumulator. + void accumulate(int strip,const float* left,const float* right, + float* masterL,float* masterR,int frames) const noexcept { + if (strip<0 || strip>=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/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..32cfc24b5 --- /dev/null +++ b/tests/channel_send_plan_test.cpp @@ -0,0 +1,174 @@ +// 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)); + assert(plan.upstreamOf(0,3)); // transitive 0 -> 1 -> 3 + assert(!plan.upstreamOf(0,2)); // topological order != graph edge + assert(!plan.upstreamOf(1,2)); + assert(!plan.upstreamOf(3,0)); + assert(!plan.upstreamOf(0,0)); + assert(!plan.upstreamOf(-1,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 enabledPort{0}; + assert(ChannelRoutingPlan::compile(physical,enabledPort,sourcePlan,layoutError)); + assert(!sourcePlan.base.strips[0].active); + const std::array mic {.8f,-.4f}; + const float* capture[]={mic.data()}; + std::array rawL{},rawR{},postL{},postR{},mixL{},mixR{}; + assert(sourcePlan.extractSource(0,capture,1,rawL.data(),rawR.data(),2)); + assert(close(rawL[0],.8f)&&close(rawR[0],.8f)); + assert(!sourcePlan.extract(0,capture,1,postL.data(),postR.data(),2)); + assert(close(postL[0],0.f)&&close(postR[0],0.f)); + sourcePlan.accumulate(0,rawL.data(),rawR.data(),mixL.data(),mixR.data(),2); + assert(close(mixL[0],0.f)&&close(mixR[0],0.f)); + + SendRequest preOnly; + preOnly.count=1; + preOnly.toMaster[0]=false; + preOnly.sends[0]={0,1,SendTap::preFader,1.f,0.f,true}; + ChannelSendPlan prePlan; + assert(ChannelSendPlan::compile(preOnly,prePlan,err)); + std::array,stripCount> recvL{},recvR{}; + std::array recvLp{},recvRp{}; + for(int i=0;i stereoPorts{0,1}; + physical.stripsAndMaster.strips[0]={SourceMode::stereo,0,1,0.f,0.f,false,false}; + physical.formats[0]=ChannelFormat::mono; + assert(ChannelRoutingPlan::compile(physical,stereoPorts,sourcePlan,layoutError)); + const std::array side {-.2f,.4f}; + const float* stereoCapture[]={mic.data(),side.data()}; + assert(sourcePlan.extractSource(0,stereoCapture,2,rawL.data(),rawR.data(),2)); + assert(close(rawL[0],.3f)&&close(rawR[0],.3f)); + assert(!sourcePlan.extract(0,stereoCapture,2,postL.data(),postR.data(),2)); +} diff --git a/tests/mixer_routing_plan_test.cpp b/tests/mixer_routing_plan_test.cpp new file mode 100644 index 000000000..3b3565b5f --- /dev/null +++ b/tests/mixer_routing_plan_test.cpp @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/core/MixerRoutingPlan.h" +#include +#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