diff --git a/.github/workflows/dlms-fast.yml b/.github/workflows/dlms-fast.yml new file mode 100644 index 000000000..097d62c95 --- /dev/null +++ b/.github/workflows/dlms-fast.yml @@ -0,0 +1,51 @@ +name: DLMS speaker processor (focused C++ and UX) +on: + pull_request: + types: [opened, reopened, synchronize] + paths: + - 'engine/lms/**' + - 'engine/core/DynamicNativeSessionPublisher.h' + - 'src/NativeLmsWebIntent.h' + - 'src/NativeMixerSessionDocument.h' + - 'src/LiveDryRoutingLab.h' + - 'tests/lms_*' + - 'site/preview-v2/assets/lms-*.js' + - 'site/preview-v2/assets/lms-*.css' + - '.github/workflows/dlms-fast.yml' + - '.github/workflows/harmony-fast-dsp.yml' + - 'CMakeLists.txt' + workflow_dispatch: +permissions: + contents: read +concurrency: + group: dlms-fast-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + dlms: + name: DLMS only — native speaker PCM, safety and 5-page model + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + - name: One matrix of speaker-ONLY portable C++ tests (no JUCE, no hardware) + shell: bash + run: | + set -euo pipefail + for name in lms_prepared_speaker_pcm_test lms_synthetic_realtime_budget_test \ + lms_native_output_reservation_test lms_native_postfx_main_witness_test \ + lms_native_draft_ack_readback_test lms_verified_device_binder_test \ + lms_offline_session_draft_test; do + printf 'DLMS C++ %s\\n' "$name" + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror \ + "tests/${name}.cpp" -o "$RUNNER_TEMP/${name}" + "$RUNNER_TEMP/${name}" + done + - name: DLMS design UX, matrix, explicit port matching and native bridge + run: | + node --check site/preview-v2/assets/lms-system-model.js + node --check site/preview-v2/assets/lms-workspace.js + node --test tests/lms_system_model.test.cjs tests/lms_native_bridge.test.cjs + - name: DLMS scope contract (no vocal-harmony tests in this gate) + run: node --test tests/dlms_ci_scope_contract.test.cjs diff --git a/.github/workflows/harmony-fast-dsp.yml b/.github/workflows/harmony-fast-dsp.yml index a0c4e1168..dc00befd1 100644 --- a/.github/workflows/harmony-fast-dsp.yml +++ b/.github/workflows/harmony-fast-dsp.yml @@ -6,7 +6,8 @@ on: - 'engine/builtin_fx/Harmony*.h' - 'tests/harmony*.cpp' - 'tools/harmony_offline_ab.cpp' - - 'CMakeLists.txt' + # Shared CMake edits for DLMS or the mixer are NOT Harmonice DSP edits. + # Full native CTest qualifies shared build integration separately. - '.github/workflows/harmony-fast-dsp.yml' permissions: contents: read @@ -15,6 +16,10 @@ concurrency: cancel-in-progress: true jobs: harmony-cpp: + # The LMS long-running PR contains historical shared Harmony commits. + # Revalidate dedicated Harmonice changes in its OWN vocal FX PR; the + # speaker-only PR is qualified by DLMS PCM + general native integration. + if: ${{ !startsWith(github.head_ref, 'feat/lms-') && !startsWith(github.head_ref, 'feat/dlms-') }} name: Native DSP compile and PCM regression (Linux, no JUCE) runs-on: ubuntu-latest timeout-minutes: 7 diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 37f343179..19341f8ff 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -196,6 +196,34 @@ jobs: run: | g++ -std=c++20 -O2 -Wall -Wextra -Werror tests/mixer_routing_plan_test.cpp -o "$RUNNER_TEMP/armix-native-routing-pcm" "$RUNNER_TEMP/armix-native-routing-pcm" + # LMS has a portable JUCE-free DSP kernel. Catch an actual PCM or + # allocation regression in seconds before paying for Windows MSVC. + - name: LMS prepared crossover / EQ / speaker matrix PCM preflight + if: ${{ github.event_name == 'pull_request' && startsWith(github.head_ref, 'feat/lms-') }} + run: | + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror tests/lms_prepared_speaker_pcm_test.cpp -o "$RUNNER_TEMP/armix-lms-pcm" + "$RUNNER_TEMP/armix-lms-pcm" + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror tests/lms_synthetic_realtime_budget_test.cpp -o "$RUNNER_TEMP/armix-lms-rt" + "$RUNNER_TEMP/armix-lms-rt" + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror tests/lms_native_output_reservation_test.cpp -o "$RUNNER_TEMP/armix-lms-port-guard" + "$RUNNER_TEMP/armix-lms-port-guard" + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror tests/lms_native_postfx_main_witness_test.cpp -o "$RUNNER_TEMP/armix-lms-post-main" + "$RUNNER_TEMP/armix-lms-post-main" + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror tests/lms_native_draft_ack_readback_test.cpp -o "$RUNNER_TEMP/armix-lms-ack" + "$RUNNER_TEMP/armix-lms-ack" + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror tests/lms_verified_device_binder_test.cpp -o "$RUNNER_TEMP/armix-lms-device" + "$RUNNER_TEMP/armix-lms-device" + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror tests/lms_offline_session_draft_test.cpp -o "$RUNNER_TEMP/armix-lms-session" + "$RUNNER_TEMP/armix-lms-session" + # Windows MSVC CTest previously SIGSEGV'd before executing SonKu + # asserts: multiple ~192 KiB automatic DSP fixtures exhausted the + # bounded Windows test-thread stack. Run its REAL non-JUCE PCM + # fixture with a 1 MiB Linux stack limit before reserving MSVC. + - name: SonKu PCM parity with Windows-sized stack (LMS integration) + if: ${{ github.event_name == 'pull_request' && startsWith(github.head_ref, 'feat/lms-') }} + run: | + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror tests/sonku_spatial_core_test.cpp -o "$RUNNER_TEMP/armix-sonku-stack" + (ulimit -s 1024; "$RUNNER_TEMP/armix-sonku-stack") - name: WaveShell JUCE 8 class-index regression (source-aware) shell: bash run: | diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 6c81d2313..37d1f266e 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -129,6 +129,7 @@ jobs: node --test tests/floating_window_workspace_contract.test.mjs node --test tests/rc_operator_workflow_contract.test.mjs node --test tests/workstream_coordination_contract.test.mjs tests/chat_ci_dispatch_contract.test.mjs tests/gui_workflow_contract_test.mjs tests/plugin_ui_contract_test.mjs tests/ci_workflow_efficiency_test.mjs tests/fx_drag_reorder_contract_test.mjs tests/mixer_io_operator_contract_test.mjs tests/mixer_shell_contract_test.mjs tests/approved_native_m2_contract.test.cjs + if [ -f tests/lms_native_bridge.test.cjs ]; then node --test tests/lms_system_model.test.cjs tests/lms_native_bridge.test.cjs; fi node tests/wire_graph_canonical_model.test.cjs node tests/wire_main_native_handoff_contract.test.cjs - name: Verify single published /preview/ source offline @@ -423,6 +424,11 @@ jobs: python -m pip install --upgrade pip python -m pip install playwright python -m playwright install --with-deps chromium + # LMS Browser FAT is additive only when this feature exists in the + # exact checked-out source. Never test a separate or prototype renderer. + - name: LMS five-workspace crossover / matrix / EQ / geometry Chromium + if: ${{ hashFiles('tests/pages_lms_five_workspaces_smoke.py') != '' }} + run: python tests/pages_lms_five_workspaces_smoke.py - name: Verify opt-in actual /preview/ GUI profiling, default OFF run: python tests/approved_gui_perf_stage_a_smoke.py - name: Validate Stage B native meter dirty-write / authoritative Pages parity @@ -742,6 +748,7 @@ jobs: name: arsonmix-gui-current-smoke path: | pages-wire-main-*.png + pages-lms-*.png pages-v53-fx-rail-*.png pages-v51-portrait-meter-*.png pages-fader-rollback-*.png diff --git a/CMakeLists.txt b/CMakeLists.txt index e2f1cb58d..5313b098e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -218,6 +218,62 @@ target_link_libraries(ARMixConsole PRIVATE include(CTest) if(BUILD_TESTING) + # LMS M2: portable native DSP kernel, prepared off-RT and exercised with + # actual PCM blocks. This is NOT a second mixer callback or device graph. + add_executable(ARMixSpeakerPcmTests tests/lms_prepared_speaker_pcm_test.cpp + engine/lms/PreparedSpeakerSystem.h) + target_compile_features(ARMixSpeakerPcmTests PRIVATE cxx_std_20) + add_test(NAME LMSNativeLR4MultisectionVerifiedOutputsAndDelay + COMMAND ARMixSpeakerPcmTests) + add_executable(ARMixSpeakerDeviceBinderTests + tests/lms_verified_device_binder_test.cpp + engine/lms/NativeSpeakerDeviceBinder.h) + target_compile_features(ARMixSpeakerDeviceBinderTests PRIVATE cxx_std_20) + add_test(NAME LMSNativeExactJuceOutputInventoryDiscardBrowserOrdinals + COMMAND ARMixSpeakerDeviceBinderTests) + add_executable(ARMixSpeakerDraftAckReadbackTests + tests/lms_native_draft_ack_readback_test.cpp + engine/core/DynamicNativeSessionPublisher.h + engine/lms/NativeSpeakerOutputReservation.h) + target_compile_features(ARMixSpeakerDraftAckReadbackTests PRIVATE cxx_std_20) + add_test(NAME LMSNativeSameGraphDesignAckReadbackAndStaleRevocation + COMMAND ARMixSpeakerDraftAckReadbackTests) + add_executable(ARMixSpeakerPostFxMainWitnessTests + tests/lms_native_postfx_main_witness_test.cpp + engine/lms/PreparedSpeakerSystem.h + engine/core/DynamicNativeSessionPublisher.h) + target_compile_features(ARMixSpeakerPostFxMainWitnessTests PRIVATE cxx_std_20) + add_test(NAME LMSOneAcceptedNativeMainFxToEightWayShadowPcm + COMMAND ARMixSpeakerPostFxMainWitnessTests) + add_executable(ARMixSpeakerOutputReservationTests + tests/lms_native_output_reservation_test.cpp + engine/lms/NativeSpeakerOutputReservation.h + engine/lms/PreparedSpeakerSystem.h) + target_compile_features(ARMixSpeakerOutputReservationTests PRIVATE cxx_std_20) + add_test(NAME LMSNativeAcceptedChannelIdExclusiveAsioOutputGuard + COMMAND ARMixSpeakerOutputReservationTests) + add_executable(ARMixSpeakerRealtimeTests tests/lms_synthetic_realtime_budget_test.cpp + engine/lms/PreparedSpeakerSystem.h) + target_compile_features(ARMixSpeakerRealtimeTests PRIVATE cxx_std_20) + add_test(NAME LMSNativeFourWayStereoZeroCallbackHeap + COMMAND ARMixSpeakerRealtimeTests) + # LMS M11 detached session draft: portable cold-open safety policy. + add_executable(ARMixSpeakerOfflineDraftTests + tests/lms_offline_session_draft_test.cpp + engine/lms/LmsOfflineDraft.h) + target_compile_features(ARMixSpeakerOfflineDraftTests PRIVATE cxx_std_20) + add_test(NAME LMSOfflineSmixDraftAlwaysUnassignedDisarmed + COMMAND ARMixSpeakerOfflineDraftTests) + # LMS M6 JUCE WebView control ABI tests: native schema only, no ASIO + # endpoint/driver opened, no second audio callback or render. + juce_add_console_app(ARMixSpeakerWebIntentTests PRODUCT_NAME "ArSonMix LMS Offline WebView Native Contract") + target_sources(ARMixSpeakerWebIntentTests PRIVATE tests/lms_juce_web_intent_test.cpp + src/NativeLmsWebIntent.h) + target_compile_features(ARMixSpeakerWebIntentTests PRIVATE cxx_std_20) + target_link_libraries(ARMixSpeakerWebIntentTests PRIVATE + juce::juce_core juce::juce_recommended_config_flags) + add_test(NAME LMSNativeJuceIntentSchemaAndDisconnectedReadback + COMMAND ARMixSpeakerWebIntentTests) juce_add_console_app(ARMixFactoryFxRegistryTests PRODUCT_NAME "ArSonMix Factory FX Integrity Tests") target_sources(ARMixFactoryFxRegistryTests PRIVATE tests/factory_fx_registry_test.cpp src/FactoryFxRegistry.h) target_link_libraries(ARMixFactoryFxRegistryTests PRIVATE juce::juce_core juce::juce_cryptography juce::juce_recommended_config_flags) diff --git a/docs/DLMS_PRO_WORKFLOW_SAFETY_M12_20261114.md b/docs/DLMS_PRO_WORKFLOW_SAFETY_M12_20261114.md new file mode 100644 index 000000000..a8cebc33e --- /dev/null +++ b/docs/DLMS_PRO_WORKFLOW_SAFETY_M12_20261114.md @@ -0,0 +1,74 @@ +# DLMS Professional Workflow & Safety Contract — M12 (2026-11-14) + +**Product**: ArSonMix — Digital Loudspeaker Management System (DLMS) workspace. +**Unrelated**: Harmonice is the built-in vocal-harmony audio FX in the channel FX Rack. Its DSP test does not qualify DLMS. + +## Verified competitive patterns and what is actually adopted + +| Professional reference | Verified published workflow | ArSonMix DLMS decision | +| --- | --- | --- | +| d&b R1 | Offline design without attached amplifiers, separate device and group views, device system check | Keep an always-visible *DESIGN ONLY* identity and five purposeful pages; never imitate hardware telemetry | +| Xilica Designer | Project is authored offline, then explicitly mapped to physical device identity, reviewed and deployed separately | Require operator-selected exact ASIO port identity; device epoch and graph changes invalidate pending review | +| Lake Controller | Recall Compare detects differences between saved and active configuration; bulk recall has a distinct high-impact confirmation | Preserve the previous DSP design until explicit mapping is accepted; do not silently map ordinal 1 to a different amplifier | +| Powersoft ArmoníaPlus | Device-aware speaker-way routing, per-way crossover/EQ/delay/gain/polarity, RMS and peak protection | Separate logical crossover sections from output DSP and physical port inventory; prioritize measured electrical calibration | +| Q-SYS | Loudspeaker protection requires manufacturer-derived RMS/peak voltages and high-pass constraints | Digital dBFS ceiling and a 'limiter on' checkbox never constitute safe speaker hardware authorization | + +Reference links: +- https://www.dbaudio.com/global/en/products/software/r1/ +- https://support.xilica.com/en/articles/3955586 +- https://mediadl.musictribe.com/media/PLM/data/docs/Lake-Controller/Lake%20Controller%20Operation%20Manual_1.7.0.pdf +- https://www.powersoft.com/en/technologies/dsp-technology +- https://help.qsys.com/Content/Schematic_Library/lua_speaker.htm + +## Owner and signal path: one native authority + +``` +ArSonMix native accepted MAIN (post FX and post master processing) + -> CONTROL prepared speaker DSP (HPF/LPF crossover, PEQ, delay, polarity, gain) + -> isolated offline diagnostic PCM and atomic readback + -> speaker output port intents (MUTED, not physical) + -> NATIVE binder checks actual JUCE/ASIO inventory + same device epoch + -> accepted speaker draft ACK + exact graph readback (hardwareApplied=false) + -X-> physical loudspeaker output [NOT AUTHORIZED] +``` + +No WebView JSON may declare trusted actual ASIO callback ordinals, DAC full-scale voltage, amplifier gain, or physical output authorization. The single existing native JUCE callback remains the future sole physical writer. The M10 diagnostic is bounded and isolated, not a parallel live sound path. + +## Current M12 interaction rules (code implemented in branch) + +1. **Design**: System → Crossover → Matrix → Processing → Alignment. Start offline, no auto-patched output. +2. **Inspect**: Obtain actual port identities from the native JUCE output inventory; MAIN/MONITOR/EXTERNAL occupied ports are not selectable as speaker destination. +3. **Option A — New hardware layout**: *Use verified ports* intentionally clears all prior routing/DSP and requires confirmation. +4. **Option B — Keep sound-system design**: *Reassign + keep DSP* opens a compact per-output review. Every connected/tuned/positioned old output requires an explicit unique new port. Unmapped untouched placeholders may be dropped. PEQ, delay, crossover, gain, polarity, limiter intent and geometry are preserved **only for selected ports**; every result is **MUTED**. No guessed ordinal, partial commit, or hidden auto-patch. +5. **Validate**: Reassignment invalidates old accepted design revision and needs a separate user-initiated native Validate; native ACK must be followed by a subsequent readback of every DSP field. Device epoch/graph or occupancy changes cancel pending mapping review. +6. **Save / Open**: The existing `.smix` codec stores a versioned, disconnected LMS draft with DSP values only. It strips port identity, graph epoch, hardware unmute, and claimed calibrated voltage values. Opening it cannot auto-arm a speaker. **Important limitation:** The GUI's direct restored-DLMS-editor presentation is not yet wired to the session import event; native session storage and offline model tests are separate completed contracts. + +## Status taxonomy — never claim a capability that is not present + +| Label | Allowed meaning | +| --- | --- | +| DESIGN ONLY | Editable offline data; no port authorization or acoustic measurement | +| INSPECTION REQUIRED | Port inventory absent/stale | +| REVIEW REQUIRED | Saved design needs explicit operator port mapping | +| ACK PENDING READBACK | CONTROL accepted a typed draft, but state not yet reconciled | +| VALIDATED DRAFT | Exact same epoch/graph/revision and DSP fields verified; hardwareApplied **false** | +| CALIBRATION UNVERIFIED | Actual DAC/amp/driver limit evidence missing; **no speaker LIVE** | +| LIVE | **Forbidden for this milestone**; requires independent FAT and typed native arm transaction | + +### Tests and CI boundaries + +- **DLMS focused** `.github/workflows/dlms-fast.yml`: seven portable C++20 tests for crossover/PCM, callback allocation, output reservation, post-MAIN witness, native ACK and stale revocation, real ASIO binder and disconnected session draft; two JS suites for the five pages, review transaction, stale inspection, and model math; job scope contract. +- **Shared integration**: native Windows MSVC/CTest tests JUCE session persistence, host/build ABI, and no regressions; full product Chromium ensures the rest of the mixer survives. A shared PAN test failure is **not** a failure of speaker DSP, but it must be resolved before full-product release. +- **Harmonice**: vocal harmony fast tests do not run for the DLMS feature branch. They remain in a distinct vocal-effect workflow and cannot be reported as DLMS PASS. + +### Remaining gates for a physically usable professional DLMS + +1. Read-only GUI session-recovery presentation with explicit `NEEDS_REMAP` and comparison to native device inventory; no automatic rematch by ordinal. +2. Separate **trusted measurement provenance**: DAC Vrms measured at a known gain setting, amplifier gain and voltage limits from a documented manufacturer profile, power handling/HPF, reviewable measurement date and instrument identity. Valid numeric fields alone are **not** proof. +3. Typed physical speaker admission lease, exclusive MAIN/MONITOR/EXTERNAL pin ownership, atomic device-change revocation, rollback, measured limiter readback and emergency mute through the **single** PCM callback. Avoid a second output engine. +4. Actual multichannel ASIO/amplifier/dummy-load FAT: calibration tolerance, silence on exception/stale epoch, crossover spectral analysis, latency, xrun/device restart, driver disconnect, channel polarity and physical pin labeling. +5. Only after these and full product qualification may production operator workflow expose LIVE. No estimate or simulated meter is a substitute for field evidence. + +## Next implementation focus + +Keep UI compact and operational, not a massive wizard: display `DESIGN`, `INSPECT`, `REVIEW`, `VALIDATED` as explicit states; one output map with selected source way, exact port label, mute and short status. A/B/compare changes before admission. No fake color-coded 'safe' LED, no optimism after stale ACK, and no redundant FX-specific CI gate. diff --git a/docs/LMS_OUTPUT_PROTECTION_FAT_GATE_20261114.md b/docs/LMS_OUTPUT_PROTECTION_FAT_GATE_20261114.md new file mode 100644 index 000000000..04b54cd91 --- /dev/null +++ b/docs/LMS_OUTPUT_PROTECTION_FAT_GATE_20261114.md @@ -0,0 +1,46 @@ +# ArSonMix LMS — M10 speaker-protection qualification and independent hardware FAT + +**Engineering state (2026-11-14): DRAFT / PHYSICAL OUTPUT DISCONNECTED.** +This decision record is for **ArSonMix** Loudspeaker Management. **Harmonice** is only the built-in vocal harmony FX, not the product name. +Track PR #635 and issue #636. No code in M2–M10 provides a physical loudspeaker LIVE/ARM capability. + +## Verified professional workflow references + +- [Allen & Heath AHM Channels: zone ways, individual output limiter, threshold/attack/release and gain-reduction meter](https://support.allen-heath.com/hc/en-gb/articles/40185199750161-Channels) +- [Allen & Heath AHM Configure: output patching after selecting crossover ways and structural interruption warning](https://support.allen-heath.com/hc/en-gb/articles/40185032073873-Configure) +- [Q-SYS Loudspeaker block: request manufacturer RMS/peak voltage and detector timings](https://help.qsys.com/Content/Schematic_Library/lua_speaker.htm) +- [Q-SYS Gain Structure: measured amplifier calibration, limiter downstream of processing](https://support.qsys.com/en_US/how-to-%7C-set-proper-gain-structure-in-q-sys) + +These sources inform workflow and safety **principles**, not permission to use a vendor's proprietary DSP implementation or infer unknown speaker parameters. + +## Actual native invariants + +1. The accepted **ChannelId** post-master PCM renderer is the sole authority: Hardware IN / PLAYER -> channel FX -> fader/pan/mute -> WIRE/BUS -> MAIN -> master gain/mute/mono. There is no second physical callback, competing mixer or GUI-owned routing graph. +2. Speaker designs are revision- and device-epoch-fenced **muted drafts**. ASIO hardware pins remain disarmed; topology or device changes revoke prior acceptance. +3. CONTROL prepares crossover, EQ, delay, polarity, voltage-model coefficients and private scratch. AUDIO is bounded, no lock, no allocation, no device enumeration or settings computation. +4. M9 measured-voltage model requires DAC full-scale RMS, *linear voltage gain* for amplifier and driver manufacturer peak/continuous voltage data. It rejects invalid/nonfinite bounds. Optional safety high-pass is a prepared LR4. These are **declared test inputs**, not verified independent calibration. +5. M9 peak attenuation is **sample peak only**, not 4x/8x oversampled intersample true peak. Its RMS detector is exponentially weighted input power, not validated thermal, excursion or amplifier-headroom protection. Even a unit-passing digital limiter **must not** be advertised as safe speaker protection. +6. M10 diagnostic is solely an isolated memory-only output array. A new accepted muted draft may run at most **two device-rate seconds** of post-master PCM diagnostics (plus one callback quantum). Atomic CONTROL readback marks capturedFrames, captureFrameLimit, captureComplete and last measured per-way gain reduction / RMS / peak. Expired diagnostics do **not** keep consuming crossover CPU on every show callback. Readback says hardwareApplied=false. +7. GUI `/preview/` is the only approved design surface. Typed browser intent cannot set manufacturer calibration or ARM. Native exact DSP/threshold/pin readback must match draft before a *VALIDATED DRAFT* caption; it never says LIVE. + +## Next P0 release sequence (independent gates) + +### M11 — trusted field calibration + resilient session +- CONTROL-only source of manufacturer data and instrument-verified DAC voltage/amplifier voltage gain, with provenance, units, device identity and sample rate. Test calibrated model boundaries independently at the actual device. A UI checkbox or a pasted dBFS threshold can **never** turn an output on. +- Persist LMS draft in versioned `.smix`, including only stable logical section IDs, explicit device-identity bindings and disconnected state. Reopen, device reconnect, sample-rate/quantum change or unknown profile MUST reset to DISARMED with no auto patch. + +### M12 — sole-authority hardware activation +- A separate, authenticated native physical output transaction must require current independently approved calibration, matching real ASIO callback pins, unoccupied driver output ordinals, exact accepted graph revision/device epoch, watchdog, runtime limiter state and explicit operator action. Every stale/missing condition fails silent. +- No second PCM engine: published output scratch and interleaving must be completed in the existing audio callback, with physical pin writer **exclusive ownership**. Never OR into MAIN/MONITOR or permit a source-only fallback to CH1. +- Produce actual callback ACK for each output pin; differentiate REQUESTED, ACCEPTED, APPLIED, MUTED, REVOKED. GUI may render LIVE **only after** matching native readback and independent hardware proof. + +### M13 — physical FAT; required before enabling live speakers +- Test independent ASIO multi-output devices with dummy loads first (2/4/6/8 output ways, mono/stereo); test 44.1/48/96kHz, variable 32–512 frame callback quanta, graph retarget/remove, master mute and global fail-silent. +- Capture actual voltmeter/scope peak and RMS versus software modeled outputs. Sweep, limiter threshold/attack/release, hard clipping/inter-sample peaks, crossover phase, and per-way HPF using verified equipment. Independently verify external amplifier gain/clipping, driver thermal/peak limits, and polarity. +- Test late hot-plug, ASIO4ALL port reshuffle, sample-rate restart, stale epoch and buffer pointer invalidation. Any failure must revoke all speaker output rights immediately. +- Keep PR #635 draft and **no public speaker LIVE** until M11–M13 have signed hardware evidence; generic MSVC/CTest green is software-only, not a substitute. + +## Efficient qualification +- Cheap native C++/Node and 1 MiB stack SonKu PCM preflight per relevant PR edit. Preserve `-Werror`, measured data and negative tests. +- Dispatch **one exact-SHA Windows native milestone** after cheap gates are green; add one full Chromium gate when UI/contract changes warrant it. Do not dispatch redundant FAT/installer on device/DSP-only drafts. +- Maintain one approved `/preview/` and no GUI rollback from parallel SonKu, Guitar FX, gain/SOF or Vocal Throw threads. diff --git a/engine/builtin_fx/HarmonyPitchSynchronous.h b/engine/builtin_fx/HarmonyPitchSynchronous.h index 011198ef6..672d1b54e 100644 --- a/engine/builtin_fx/HarmonyPitchSynchronous.h +++ b/engine/builtin_fx/HarmonyPitchSynchronous.h @@ -92,6 +92,10 @@ class PitchSynchronousVoice final { if(state.nextCenter+width(time)) state.nextCenter=static_cast(time)+width; float sumL=0.f,sumR=0.f,weight=0.f; + // True mono source windows must stay bit-exact across compilers. + // Only reuse a normalized ear when every contributing sample is + // equal. Real stereo signals always retain independent accumulators. + bool identicalSourceWindows=true; for(auto& grain:state.grains) { if(!grain.active)continue; const double offset=static_cast(time)-grain.center; @@ -100,13 +104,27 @@ class PitchSynchronousVoice final { if(u<=-1.)continue; // Raised compact zero-slope window, avoiding per-sample trig. const float w=static_cast((1.-u*u)*(1.-u*u)); - sumL+=readAt(left,time,writeIndex,grain.source+offset)*w; - if constexpr(Stereo) - sumR+=readAt(right,time,writeIndex,grain.source+offset)*w; + const float leftSample=readAt( + left,time,writeIndex,grain.source+offset); + sumL+=leftSample*w; + if constexpr(Stereo) { + const float rightSample=readAt( + right,time,writeIndex,grain.source+offset); + identicalSourceWindows &= leftSample==rightSample; + sumR+=rightSample*w; + } weight+=w; } if(weight<.05f)return {}; - return {sumL/weight,sumR/weight,true}; + const float normalizedLeft=sumL/weight; + if constexpr(Stereo) { + // GCC 15 may round equal independent float accumulations + // differently by one ULP. Never manufacture a stereo side + // channel from demonstrably identical mono grain samples. + return {normalizedLeft, + identicalSourceWindows?normalizedLeft:sumR/weight,true}; + } + return {normalizedLeft,0.f,true}; } struct Grain {double center=0.,source=0.,width=1.;bool active=false;}; struct State { diff --git a/engine/core/DynamicChannelRoster.h b/engine/core/DynamicChannelRoster.h index fb11276ff..33b63e994 100644 --- a/engine/core/DynamicChannelRoster.h +++ b/engine/core/DynamicChannelRoster.h @@ -792,7 +792,7 @@ class DynamicChannelRoster final { bool restoreExact(std::uint64_t restoredRevision, std::span entries) { if(restoredRevision==0 || entries.empty() || - !withinBudget(std::vector(entries.begin(),entries.end()))) + !withinBudget(entries)) return false; std::unordered_set ids,edges; std::uint64_t maxId=0,maxEdge=0; @@ -878,7 +878,11 @@ class DynamicChannelRoster final { return !s.empty() && s.size()<=96 && std::none_of(s.begin(),s.end(),[](unsigned char c){return c<32;}); } - bool withinBudget(const std::vector& rows) const noexcept { + // All CONTROL budget validation consumes a read-only view. A temporary + // vector copy in restoreExact() added heap churn and triggered GCC 15's + // -Wfree-nonheap-object in the temporary destructor. Validate the + // original immutable span before allocating the accepted candidate. + bool withinBudget(std::span rows) const noexcept { std::size_t remaining=budget_.definitionBytes; for(const auto& row:rows) { const auto debit=[&remaining](std::size_t bytes){ diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index 08df7899e..b376bb62f 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -6,12 +6,15 @@ #include "NativeBeatFrameContext.h" #include "RealtimeRoutePublisher.h" #include "RealtimeRenderPermit.h" +#include "../lms/NativeSpeakerOutputReservation.h" #include #include #include #include #include #include +#include +#include #include #include @@ -25,6 +28,60 @@ class DynamicNativeSessionPublisher final { public: // Control-owned native FX lifetime travels IN the same accepted PCM // snapshot. JUCE types stay outside this portable DSP publisher. + // Optional one-pass observer of the already-accepted MAIN PCM after + // ChannelId routing and rack FX. No new renderer, separate mixing pass, + // hardware pin ownership, or data lifetime beyond this callback. + // Observers MUST be no-throw, allocation-free and MUST NOT mutate MAIN. + // This is pre-master-output gain; the physical post-gain path remains the + // authority for future speaker activation and must be gated separately. + struct MainPcmObserver final { + void* context=nullptr; + void (*observe)(void*,const float*,const float*,int) noexcept=nullptr; + }; + // M5: CONTROL-only, immutable readback of a VERIFIED but DISCONNECTED + // speaker design. Never exposed to the realtime callback. In particular, + // `validatedDraft` must NOT be presented as physically APPLIED/LIVE. + enum class SpeakerDraftFault : std::uint8_t { + none,staleDeviceOrGraph,staleDraft,invalidSource, + invalidReservation,invalidDsp,preparationFailed + }; + struct SpeakerDraftAck final { + SpeakerDraftFault fault=SpeakerDraftFault::none; + armix::lms::SpeakerReservationFault reservationFault= + armix::lms::SpeakerReservationFault::none; + armix::lms::SpeakerPlanFault planFault=armix::lms::SpeakerPlanFault::none; + std::uint64_t deviceEpoch=0,graphRevision=0,designRevision=0; + std::size_t preparedScratchBytes=0; + bool validatedDraft=false,hardwareApplied=false; + [[nodiscard]] bool ok() const noexcept { + return fault==SpeakerDraftFault::none && validatedDraft && + !hardwareApplied; + } + }; + struct SpeakerDiagnosticProtection final { + int callbackOrdinal=-1; + bool voltageModelPrepared=false; // NOT proof of verified calibration + float gainReductionDb=0.f,preLimitRmsDigital=0.f,outputPeakDigital=0.f; + }; + struct SpeakerDiagnosticReadback final { + bool available=false,hardwareApplied=false; + std::uint64_t deviceEpoch=0,graphRevision=0,designRevision=0; + std::uint64_t completedBlocks=0; + std::uint64_t capturedFrames=0,captureFrameLimit=0; + bool captureComplete=false; // last measured peak is historical + float postMasterPeakL=0.f,postMasterPeakR=0.f; + std::vector> isolatedOutputPeaks; + std::vector outputProtection; + }; + struct SpeakerDraftReadback final { + std::uint64_t deviceEpoch=0,graphRevision=0,designRevision=0; + ChannelId mainSource{}; + std::string deviceIdentity; + armix::lms::SpeakerSystemRequest design; + std::vector reservedOutputOrdinals; + std::size_t preparedScratchBytes=0; + bool validatedDraft=true,hardwareApplied=false; + }; struct FxPlan final { std::shared_ptr owner; // CONTROL-only copy/destruction void* context=nullptr; // unchanged owner.get(), RT raw pointer @@ -45,6 +102,27 @@ class DynamicNativeSessionPublisher final { int physicalInputs=0; bool monitor=false; }; + // The ONLY speaker output publication is an isolated, in-memory diagnostic + // sink. It consumes the actual post-master PCM from the existing callback; + // it has no device output pointers or physical authorization API. + // A separate RT lease protects its DSP state from CONTROL retirement. + struct SpeakerDiagnosticPrepared final { + std::unique_ptr dsp; + std::uint64_t pcmRevision=0,designRevision=0; + int physicalCount=0; + std::vector scratch; + std::vector pins; + std::vector ownedOrdinals; + std::array,256> lastPeaks{}; + std::atomic inputPeakL{0.f},inputPeakR{0.f}; + std::atomic completedBlocks{0}; + std::atomic capturedFrames{0}; + std::uint64_t captureFrameLimit=0; // CONTROL-prepared fixed 2 s window + }; + using DiagnosticPublisher=armix::rt::RealtimeRoutePublisher; + std::unique_ptr speakerDraft_; // CONTROL readback + std::unique_ptr speakerPrepared_; // validated CONTROL DSP + DiagnosticPublisher speakerDiagnostics_; // ONLY diagnostic memory; never ASIO using Publisher=armix::rt::RealtimeRoutePublisher; public: enum class Fault : std::uint8_t { @@ -127,6 +205,9 @@ class DynamicNativeSessionPublisher final { expectedRevision,activeDeviceEpoch); switch(status) { case Publisher::Result::applied: { + // Every accepted structural PCM revision revokes old speaker + // pin identity and DSP; a UI draft cannot survive by accident. + revokeSpeakerDraft(); const auto source=musicTempo_.selectedSource(); if(source.value) { const auto* published=publisher_.controlPrepared( @@ -155,6 +236,238 @@ class DynamicNativeSessionPublisher final { return report; } + // M5: same-publisher CONTROL transaction. Required caller-side proof: + // inventory was constructed from the ACTUAL active JUCE device's + // enabled output mask, never from browser-stored ordinal labels. + // No side effects on existing ChannelId PCM or hardware pin ownership. + // ALL speaker output DSP remains permanently DISCONNECTED at M5. + SpeakerDraftAck acceptSpeakerDraft( + const armix::lms::SpeakerSystemRequest& request, + const armix::lms::NativePcmOutputInventory& inventory, + ChannelId mainSource,std::uint64_t expectedDesignRevision) { + SpeakerDraftAck ack; + ack.deviceEpoch=request.deviceEpoch; + ack.graphRevision=request.graphRevision; + ack.designRevision=speakerDraft_?speakerDraft_->designRevision:0; + const auto* accepted=publisher_.controlPrepared( + request.deviceEpoch,request.graphRevision); + if(!accepted || !request.deviceEpoch || !request.graphRevision || + !inventory.acceptedChannelIdPcm || + !inventory.deviceEpoch || !inventory.acceptedGraphRevision || + inventory.deviceEpoch!=request.deviceEpoch || + inventory.acceptedGraphRevision!=request.graphRevision) { + ack.fault=SpeakerDraftFault::staleDeviceOrGraph;return ack; + } + if(expectedDesignRevision!=ack.designRevision || + expectedDesignRevision==std::numeric_limits::max()){ + ack.fault=SpeakerDraftFault::staleDraft;return ack; + } + if(!mainSource.value || accepted->routing.main!=mainSource || + inventory.mainChannelId!=mainSource.value){ + ack.fault=SpeakerDraftFault::invalidSource;return ack; + } + if(request.maxFrames!=accepted->graph.capacity()) { + ack.fault=SpeakerDraftFault::invalidDsp; + ack.planFault=armix::lms::SpeakerPlanFault::invalidFormat; + return ack; + } + try { + const auto reserved=armix::lms::NativeSpeakerOutputReservation:: + preflight(request,inventory,mainSource.value); + if(!reserved.ok() || reserved.mayWritePhysicalAudio){ + ack.fault=SpeakerDraftFault::invalidReservation; + ack.reservationFault=reserved.fault;return ack; + } + std::unique_ptr dsp; + const auto candidate=armix::lms::PreparedSpeakerSystem:: + prepare(request,dsp); + if(!candidate.ok() || !dsp){ + ack.fault=SpeakerDraftFault::invalidDsp; + ack.planFault=candidate.fault;return ack; + } + // Everything above is speculative. Build a complete readback + // BEFORE publishing either pointer: an exception leaves the last + // accepted draft and PCM untouched (transactional rollback). + auto snapshot=std::make_unique(); + snapshot->deviceEpoch=request.deviceEpoch; + snapshot->graphRevision=request.graphRevision; + snapshot->designRevision=expectedDesignRevision+1; + snapshot->mainSource=mainSource; + snapshot->deviceIdentity=inventory.deviceIdentity; + snapshot->design=request; + snapshot->reservedOutputOrdinals=reserved.reservedCallbackOrdinals; + snapshot->preparedScratchBytes=candidate.scratchBytes; + // Prepare the same real DSP kernel for an *isolated* post-master + // sink. Only its internal scratch is unmuted to measure the filter + // response. It is NEVER passed a physical ASIO pointer. The + // accepted design and all real outputs remain muted/disarmed. + auto diagnosticRequest=request; + for(auto& patch:diagnosticRequest.outputs) { + patch.mute=false; + patch.limiterEnabled=true; // bounded digital test ceiling only + patch.confirmedSpeakerProfile=true; // diagnostics only; NOT calibration + } + std::unique_ptr diagnosticDsp; + const auto diagPlan=armix::lms::PreparedSpeakerSystem::prepare( + diagnosticRequest,diagnosticDsp); + if(!diagPlan.ok()||!diagnosticDsp) { + ack.fault=SpeakerDraftFault::invalidDsp; + ack.planFault=diagPlan.fault;return ack; + } + const auto outputs=request.outputs.size(); + const auto frames=static_cast(request.maxFrames); + // Count the validated CONTROL DSP, the diagnostic DSP and + // isolated output buffers together; no hidden 2x allocation. + if(outputs>request.scratchBudgetBytes/sizeof(float)/frames || + diagPlan.scratchBytes>request.scratchBudgetBytes- + outputs*frames*sizeof(float) || + candidate.scratchBytes>request.scratchBudgetBytes- + outputs*frames*sizeof(float)-diagPlan.scratchBytes) { + ack.fault=SpeakerDraftFault::invalidDsp; + ack.planFault=armix::lms::SpeakerPlanFault::scratchBudget; + return ack; + } + auto diagnostic=std::make_unique(); + diagnostic->dsp=std::move(diagnosticDsp); + diagnostic->pcmRevision=request.graphRevision; + diagnostic->designRevision=snapshot->designRevision; + diagnostic->physicalCount=request.activeOutputChannels; + // The diagnostic doubles section processing only for a bounded + // two-second verification window. On a running show it MUST + // expire automatically; physical outputs remain disconnected. + // CONTROL uses trusted native sampleRate, not GUI milliseconds. + diagnostic->captureFrameLimit=static_cast( + std::ceil(request.sampleRate*2.)); + diagnostic->scratch.resize(outputs*frames,0.f); + diagnostic->pins.resize(static_cast(request.activeOutputChannels), + nullptr); + diagnostic->ownedOrdinals=reserved.reservedCallbackOrdinals; + for(std::size_t i=0;iownedOrdinals.size();++i) + diagnostic->pins[static_cast( + diagnostic->ownedOrdinals[i])]=diagnostic->scratch.data()+i*frames; + auto diagSnapshot=std::make_unique(); + diagSnapshot->deviceEpoch=request.deviceEpoch; + diagSnapshot->graphRevision=snapshot->designRevision; + diagSnapshot->prepared=std::move(diagnostic); + // The separate diagnostic publication is CONTROL-only, revision + // fenced and RT-retired. Failed publication retains old readback. + if(speakerDiagnostics_.publish(std::move(diagSnapshot), + expectedDesignRevision,request.deviceEpoch)!= + DiagnosticPublisher::Result::applied) { + ack.fault=SpeakerDraftFault::preparationFailed;return ack; + } + speakerPrepared_=std::move(dsp); + speakerDraft_=std::move(snapshot); + ack.designRevision=speakerDraft_->designRevision; + ack.preparedScratchBytes=candidate.scratchBytes; + ack.validatedDraft=true; + // No hardware output ACL exists in this transaction. + ack.hardwareApplied=false; + return ack; + } catch(...) { + ack.fault=SpeakerDraftFault::preparationFailed; + return ack; + } + } + + // Copy the returned values on CONTROL before modifying the accepted PCM. + // Any graph/device change makes old draft readback unavailable. + [[nodiscard]] const SpeakerDraftReadback* speakerDraftReadback( + std::uint64_t epoch,std::uint64_t graphRevision) const noexcept { + if(!speakerDraft_ || speakerDraft_->deviceEpoch!=epoch || + speakerDraft_->graphRevision!=graphRevision || + !publisher_.controlPrepared(epoch,graphRevision))return nullptr; + return speakerDraft_.get(); + } + + // Closing a session, disconnecting device, or clearing a physical patch + // must invalidate readback before another control request arrives. + void revokeSpeakerDraft() noexcept { + speakerDiagnostics_.unpublish(); + speakerDraft_.reset(); + speakerPrepared_.reset(); + } + + // AUDIO: a post-master sidecar on the SAME accepted callback. All speaker + // destinations are privately preallocated on CONTROL. This method has + // NO hardware output parameter and NEVER changes MAIN/MONITOR/EXTERNAL. + // The caller must pass the revision returned by the actual PCM render. + bool processSpeakerDiagnostic(std::uint64_t epoch,std::uint64_t pcmRevision, + const float* postMasterL, + const float* postMasterR,int frames) noexcept { + auto lease=speakerDiagnostics_.acquire(); + const auto* snap=lease.get(epoch); + if(!snap||!snap->prepared||!pcmRevision||!postMasterL|| + !postMasterR||frames<1)return false; + auto& diag=*snap->prepared; + if(diag.pcmRevision!=pcmRevision || !diag.dsp || + diag.designRevision!=snap->graphRevision)return false; + const auto used=diag.capturedFrames.load(std::memory_order_relaxed); + if(used>=diag.captureFrameLimit)return false; + const bool done=diag.dsp->process(epoch,pcmRevision, + postMasterL,postMasterR,diag.pins.data(),diag.physicalCount, + frames,true); // authorization is for PRIVATE scratch, not ASIO + if(!done)return false; + float left=0.f,right=0.f; + for(int i=0;i(pin)]; + float peak=0.f; + for(int i=0;i(pin)].store( + peak,std::memory_order_release); + } + diag.completedBlocks.fetch_add(1,std::memory_order_release); + // SINGLE audio-callback writer, no CAS or heap. A final accepted + // quantum can cross the frame limit by at most maxFrames-1 samples. + diag.capturedFrames.store(used+static_cast(frames), + std::memory_order_release); + return true; + } + // CONTROL only. Never infer hardware LIVE from these isolated PCM meters. + [[nodiscard]] SpeakerDiagnosticReadback speakerDiagnosticReadback( + std::uint64_t epoch,std::uint64_t pcmRevision) const { + SpeakerDiagnosticReadback result; + if(!speakerDraft_||speakerDraft_->deviceEpoch!=epoch || + speakerDraft_->graphRevision!=pcmRevision)return result; + const auto* diag=speakerDiagnostics_.controlPrepared( + epoch,speakerDraft_->designRevision); + if(!diag || diag->pcmRevision!=pcmRevision)return result; + result.available=true; + result.deviceEpoch=epoch; + result.graphRevision=pcmRevision; + result.designRevision=diag->designRevision; + result.completedBlocks=diag->completedBlocks.load(std::memory_order_acquire); + result.capturedFrames=diag->capturedFrames.load(std::memory_order_acquire); + result.captureFrameLimit=diag->captureFrameLimit; + result.captureComplete=result.capturedFrames>=result.captureFrameLimit; + result.postMasterPeakL=diag->inputPeakL.load(std::memory_order_acquire); + result.postMasterPeakR=diag->inputPeakR.load(std::memory_order_acquire); + for(std::size_t j=0;jownedOrdinals.size();++j) { + const int ordinal=diag->ownedOrdinals[j]; + result.isolatedOutputPeaks.emplace_back( + ordinal,diag->lastPeaks[static_cast(ordinal)] + .load(std::memory_order_acquire)); + armix::lms::PreparedSpeakerSystem::OutputProtectionReadback sample; + // Same native DSP instance as the PCM sink; atomic readback only. + if(diag->dsp && diag->dsp->outputProtectionReadback(j,sample)) + result.outputProtection.push_back({ + ordinal,sample.voltageModelPrepared,sample.gainReductionDb, + sample.preLimitRmsDigital,sample.outputPeakDigital}); + } + return result; + } + // Sole AUDIO CALLBACK path when connected by DYN1 live migration: // no alloc, mutex, wait, refcount, graph sorting or VST creation. // Caller-supplied FX owns its native ChannelId-keyed VST instance lease. @@ -168,7 +481,10 @@ class DynamicNativeSessionPublisher final { std::span channelPeaksR={}, std::span playerPcm={}, float* const* hardwareOutputs=nullptr, - int hardwareOutputCount=0) noexcept { + int hardwareOutputCount=0, + MainPcmObserver observer={}, + std::uint64_t* renderedGraphRevision=nullptr) noexcept { + if(renderedGraphRevision)*renderedGraphRevision=0; static_assert(std::is_nothrow_invocable_v, "Realtime VST dispatch must be noexcept"); const auto clearOutputs=[&]() noexcept { @@ -241,6 +557,10 @@ class DynamicNativeSessionPublisher final { physical,physicalCount,mainL,mainR,frames, dispatch,monitorL,monitorR,channelPeaksL,channelPeaksR,playerPcm, hardwareOutputs,hardwareOutputCount); + if(ok && renderedGraphRevision) + *renderedGraphRevision=snap->graphRevision; + if(ok && observer.observe) + observer.observe(observer.context,mainL,mainR,frames); if(!ok) { // A rejected physical callback (including aliased independent // amplifier buffers) emits silence, not a stale LIVE snapshot. @@ -284,10 +604,12 @@ class DynamicNativeSessionPublisher final { // Caller validates actual driver pins and MAIN/MONITOR collision first. bool setExternalOutput(std::uint64_t epoch,std::uint64_t revision, ChannelId id,int left,int right,int outputCount) noexcept { - return publisher_.updateActiveControl(epoch,revision, + const bool updated=publisher_.updateActiveControl(epoch,revision, [&](Prepared& active) noexcept { return active.graph.setExternalOutput(id,left,right,outputCount); }); + if(updated)revokeSpeakerDraft(); // physical pin inventory changed + return updated; } std::pair externalOutput(std::uint64_t epoch, std::uint64_t revision,ChannelId id) const noexcept { @@ -409,8 +731,11 @@ class DynamicNativeSessionPublisher final { const auto* p=publisher_.controlPrepared(epoch,revision); return p?p->graph.latencySamples():0; } - void unpublish() noexcept {publisher_.unpublish();} - void pollRetirement() noexcept {publisher_.pollRetirement();} + void unpublish() noexcept {revokeSpeakerDraft();publisher_.unpublish();} + void pollRetirement() noexcept { + publisher_.pollRetirement(); + speakerDiagnostics_.pollRetirement(); + } std::uint64_t acceptedRevision() const noexcept { return publisher_.lastRevision(); // CONTROL only } diff --git a/engine/lms/LmsOfflineDraft.h b/engine/lms/LmsOfflineDraft.h new file mode 100644 index 000000000..fc68346fb --- /dev/null +++ b/engine/lms/LmsOfflineDraft.h @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +// ArSonMix LMS M11: versioned, DEVICE-INDEPENDENT offline speaker design. +// This is exclusively session/CONTROL data. There is intentionally no +// callback ordinal, ASIO writer, calibration authority or ARM capability. +#include "PreparedSpeakerSystem.h" +#include +#include +#include +#include +#include +#include +#include + +namespace armix::lms { +struct OfflineSpeakerDraft final { + static constexpr int formatVersion=1; + int version=formatVersion; + double designRateHz=48000.; // reference for cutoff/EQ validity, never rebinds device + int ways=2; + bool stereo=true; + std::vector crossoverHz; + // OutputPatch reused only as a familiar *unassigned* DSP data carrier: + // portIdentity MUST be blank, all outputs muted and voltageModel empty. + std::vector outputs; +}; +class OfflineSpeakerDraftPolicy final { + static bool token(const std::string& s,std::size_t max) noexcept { + return !s.empty()&&s.size()<=max&& + std::any_of(s.begin(),s.end(),[](unsigned char c){return c!=32;})&& + std::all_of(s.begin(),s.end(), + [](unsigned char c){return c>=32&&c<=126;}); + } +public: + [[nodiscard]] static bool valid(const OfflineSpeakerDraft& d) { + if(d.version!=OfflineSpeakerDraft::formatVersion|| + !std::isfinite(d.designRateHz)||d.designRateHz<8000.|| + d.designRateHz>384000.||d.ways<1||d.ways>16|| + d.crossoverHz.size()!=static_cast(d.ways-1)|| + d.outputs.size()>256)return false; + double previous=15.; + for(const auto hz:d.crossoverHz) { + if(!std::isfinite(hz)||hz<20.||hz<=previous*1.01|| + hz>=d.designRateHz*.45)return false; + previous=hz; + } + std::unordered_set seen; + for(const auto& p:d.outputs) { + if(!token(p.outputId,256)||!seen.insert(p.outputId).second|| + !p.portIdentity.empty()||!p.mute|| + p.confirmedSpeakerProfile||p.voltageModel.has_value()|| + p.sourceSide<0||p.sourceSide>(d.stereo?1:0)|| + p.section<0||p.section>=d.ways|| + !std::isfinite(p.gainDb)||p.gainDb< -60.||p.gainDb>6.|| + !std::isfinite(p.delayMs)||p.delayMs<0.||p.delayMs>500.|| + !std::isfinite(p.ceilingDbfs)||p.ceilingDbfs< -60.|| + p.ceilingDbfs>0.||p.peq.size()>8)return false; + for(const auto& b:p.peq) { + if(!std::isfinite(b.frequencyHz)||b.frequencyHz<20.|| + b.frequencyHz>=d.designRateHz*.45|| + !std::isfinite(b.q)||b.q<.1||b.q>18.|| + !std::isfinite(b.gainDb)||b.gainDb< -18.|| + b.gainDb>18.)return false; + } + } + return true; + } + + // The accepted native draft is the source of parameters. Never serialize + // its device epoch, graph revision, output pins or claimed calibration: + // opening .smix always yields an unassigned and fully muted snapshot. + static bool detach(const SpeakerSystemRequest& source, + OfflineSpeakerDraft& destination) { + if(!source.deviceEpoch||!source.graphRevision)return false; + OfflineSpeakerDraft next; + next.designRateHz=source.sampleRate; + next.ways=source.ways;next.stereo=source.stereo; + next.crossoverHz=source.crossoverHz; + next.outputs=source.outputs; + for(std::size_t i=0;i +#include +#include +#include +#include +#include +#include + +namespace armix::lms { +struct TrustedSpeakerDeviceView final { + // ONLY constructed from a captured, active JUCE device mask and the + // accepted native ChannelId routing snapshot, never from WebView JSON. + std::uint64_t deviceEpoch=0,graphRevision=0,mainChannelId=0; + std::string backend,deviceIdentity; + double sampleRate=0.; + int callbackOutputs=0,maxFrames=0; + int mainL=-1,mainR=-1,monitorL=-1,monitorR=-1; + bool acceptedPcm=false,exactDeviceMask=false,allOutputsDisarmed=false; + std::vector actualEnabledPorts; + std::vector otherOccupiedOrdinals; +}; +enum class SpeakerBindFault : std::uint8_t { + none,unverifiedDevice,staleDevice,staleGraph,invalidSource, + changedFormat,invalidPhysicalPin,invalidLoudspeakerDraft +}; +struct SpeakerBoundDraft final { + SpeakerSystemRequest verifiedRequest; + NativePcmOutputInventory verifiedInventory; + std::uint64_t sourceChannelId=0; +}; +struct SpeakerBindResult final { + SpeakerBindFault fault=SpeakerBindFault::none; + [[nodiscard]] bool ok() const noexcept {return fault==SpeakerBindFault::none;} +}; +class NativeSpeakerDeviceBinder final { +public: + // Validate first, then atomically stage a complete CONTROL-only result. + // A rejected candidate never changes prior verified input or caller state. + static SpeakerBindResult bind(const SpeakerSystemRequest& proposed, + const TrustedSpeakerDeviceView& device, + std::uint64_t sourceChannelId,SpeakerBoundDraft& output) { + const auto fail=[](SpeakerBindFault f){return SpeakerBindResult{f};}; + if(!device.exactDeviceMask||!device.acceptedPcm|| + !device.allOutputsDisarmed||device.backend!="ASIO"|| + device.deviceIdentity.empty()||device.actualEnabledPorts.empty()) + return fail(SpeakerBindFault::unverifiedDevice); + if(!device.deviceEpoch||proposed.deviceEpoch!=device.deviceEpoch) + return fail(SpeakerBindFault::staleDevice); + if(!device.graphRevision||proposed.graphRevision!=device.graphRevision) + return fail(SpeakerBindFault::staleGraph); + if(!sourceChannelId||sourceChannelId!=device.mainChannelId) + return fail(SpeakerBindFault::invalidSource); + if(!std::isfinite(device.sampleRate)||device.sampleRate<8000.|| + proposed.sampleRate!=device.sampleRate|| + proposed.activeOutputChannels!=device.callbackOutputs|| + device.callbackOutputs<2||device.callbackOutputs>256) + return fail(SpeakerBindFault::changedFormat); + std::unordered_set actualIds; + std::unordered_set callbackOrdinals; + for(const auto& p:device.actualEnabledPorts){ + if(p.identity.empty()||p.identity.starts_with("DEMO-")|| + p.callbackOrdinal<0||p.callbackOrdinal>=device.callbackOutputs|| + !actualIds.insert(p.identity).second|| + !callbackOrdinals.insert(p.callbackOrdinal).second) + return fail(SpeakerBindFault::invalidPhysicalPin); + } + if(static_cast(callbackOrdinals.size())!=device.callbackOutputs) + return fail(SpeakerBindFault::invalidPhysicalPin); + for(const auto& p:proposed.outputs){ + if(!actualIds.contains(p.portIdentity)||p.portIdentity.starts_with("DEMO-")) + return fail(SpeakerBindFault::invalidPhysicalPin); + // The user can inspect an output draft but cannot pre-authorize + // a physical loudspeaker by checking limiter/protection in UI. + if(!p.mute)return fail(SpeakerBindFault::invalidLoudspeakerDraft); + } + SpeakerBoundDraft staged; + staged.verifiedRequest=proposed; + // UI pin ordinals are completely discarded, including forged + // "verifiedPorts" that happen to use an actual display label. + staged.verifiedRequest.verifiedPorts=device.actualEnabledPorts; + staged.verifiedInventory.deviceEpoch=device.deviceEpoch; + staged.verifiedInventory.acceptedGraphRevision=device.graphRevision; + staged.verifiedInventory.mainChannelId=device.mainChannelId; + staged.verifiedInventory.deviceIdentity=device.deviceIdentity; + staged.verifiedInventory.sampleRate=device.sampleRate; + staged.verifiedInventory.callbackOutputs=device.callbackOutputs; + staged.verifiedInventory.mainL=device.mainL; + staged.verifiedInventory.mainR=device.mainR; + staged.verifiedInventory.monitorL=device.monitorL; + staged.verifiedInventory.monitorR=device.monitorR; + staged.verifiedInventory.acceptedChannelIdPcm=device.acceptedPcm; + staged.verifiedInventory.allOutputsDisarmed=device.allOutputsDisarmed; + staged.verifiedInventory.enabledOutputPorts=device.actualEnabledPorts; + staged.verifiedInventory.otherOccupiedOutputOrdinals=device.otherOccupiedOrdinals; + staged.sourceChannelId=sourceChannelId; + // The existing M3 output-owner guard is the single authority for + // MAIN/MONITOR/EXTERNAL and duplicate-output collision checks. + if(!NativeSpeakerOutputReservation::preflight( + staged.verifiedRequest,staged.verifiedInventory, + staged.sourceChannelId).ok()) + return fail(SpeakerBindFault::invalidPhysicalPin); + output=std::move(staged); + return {}; + } +}; +} // namespace armix::lms diff --git a/engine/lms/NativeSpeakerOutputReservation.h b/engine/lms/NativeSpeakerOutputReservation.h new file mode 100644 index 000000000..939c2afa7 --- /dev/null +++ b/engine/lms/NativeSpeakerOutputReservation.h @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +// LMS M3 CONTROL-side output ownership fence. The JUCE callback remains +// the ONLY hardware writer. This policy is an admission prerequisite, +// NOT a second routing engine and NOT proof of loudspeaker protection. +#include "PreparedSpeakerSystem.h" +#include +#include +#include +#include +#include +#include +#include + +namespace armix::lms { +struct NativePcmOutputInventory final { + // Obtained from the accepted ChannelId PCM graph + current device snapshot, + // NEVER from GUI labels or ordinal assumptions. + std::uint64_t deviceEpoch=0,acceptedGraphRevision=0,mainChannelId=0; + std::string deviceIdentity; + double sampleRate=0.; + int callbackOutputs=0; + int mainL=-1,mainR=-1,monitorL=-1,monitorR=-1; + bool acceptedChannelIdPcm=false,allOutputsDisarmed=false; + std::vector otherOccupiedOutputOrdinals; // e.g. EXTERNAL or BUS direct + std::vector enabledOutputPorts; +}; +enum class SpeakerReservationFault : std::uint8_t { + none,notAcceptedPcm,staleDevice,staleGraph,invalidSource, + deviceLayoutMismatch,occupiedOutput,unknownPort,unprotectedOutput +}; +struct SpeakerReservationResult final { + SpeakerReservationFault fault=SpeakerReservationFault::none; + std::vector reservedCallbackOrdinals; // CONTROL: explicit exclusive pins + std::uint64_t acceptedDeviceEpoch=0,acceptedGraphRevision=0; + bool mayWritePhysicalAudio=false; // M3 always FALSE: no calibrated limiter. + [[nodiscard]] bool ok() const noexcept{return fault==SpeakerReservationFault::none;} +}; +class NativeSpeakerOutputReservation final { +public: + // NO allocation in the realtime callback; only invoke from CONTROL with + // current device readback and accepted native ChannelId graph. + // Even an "unmuted" browser design cannot arm real loudspeakers using a + // Boolean acknowledgement or a digital hard clip masquerading as a limiter. + static SpeakerReservationResult preflight( + const SpeakerSystemRequest& request, + const NativePcmOutputInventory& accepted, + std::uint64_t requestedSourceChannelId) { + SpeakerReservationResult report{}; + auto reject=[&](SpeakerReservationFault reason) { + report.fault=reason; + report.reservedCallbackOrdinals.clear(); + return report; + }; + if(!accepted.acceptedChannelIdPcm||!accepted.allOutputsDisarmed|| + accepted.deviceIdentity.empty()||accepted.deviceEpoch==0|| + accepted.acceptedGraphRevision==0) + return reject(SpeakerReservationFault::notAcceptedPcm); + if(request.deviceEpoch!=accepted.deviceEpoch) + return reject(SpeakerReservationFault::staleDevice); + if(request.graphRevision!=accepted.acceptedGraphRevision) + return reject(SpeakerReservationFault::staleGraph); + if(!requestedSourceChannelId||requestedSourceChannelId!=accepted.mainChannelId) + return reject(SpeakerReservationFault::invalidSource); + if(request.activeOutputChannels!=accepted.callbackOutputs|| + accepted.callbackOutputs<2||accepted.callbackOutputs>256|| + !std::isfinite(accepted.sampleRate)|| + accepted.sampleRate!=request.sampleRate|| + accepted.mainL<0||accepted.mainR<0|| + accepted.mainL==accepted.mainR|| + accepted.mainL>=accepted.callbackOutputs|| + accepted.mainR>=accepted.callbackOutputs) + return reject(SpeakerReservationFault::deviceLayoutMismatch); + auto owned=accepted.otherOccupiedOutputOrdinals; + owned.push_back(accepted.mainL);owned.push_back(accepted.mainR); + if(accepted.monitorL>=0||accepted.monitorR>=0) { + if(accepted.monitorL<0||accepted.monitorR<0|| + accepted.monitorL==accepted.monitorR|| + accepted.monitorL>=accepted.callbackOutputs|| + accepted.monitorR>=accepted.callbackOutputs) + return reject(SpeakerReservationFault::deviceLayoutMismatch); + owned.push_back(accepted.monitorL);owned.push_back(accepted.monitorR); + } + std::unordered_set used; + for(const auto pin:owned) + if(pin<0||pin>=accepted.callbackOutputs||!used.insert(pin).second) + return reject(SpeakerReservationFault::deviceLayoutMismatch); + for(const auto& selected:request.outputs) { + const auto verified=std::find_if(accepted.enabledOutputPorts.begin(), + accepted.enabledOutputPorts.end(),[&](const VerifiedOutputPort& p){ + return p.identity==selected.portIdentity; + }); + const auto draft=std::find_if(request.verifiedPorts.begin(), + request.verifiedPorts.end(),[&](const VerifiedOutputPort& p){ + return p.identity==selected.portIdentity; + }); + if(verified==accepted.enabledOutputPorts.end()|| + draft==request.verifiedPorts.end()|| + verified->callbackOrdinal!=draft->callbackOrdinal) + return reject(SpeakerReservationFault::unknownPort); + const int ordinal=verified->callbackOrdinal; + if(ordinal<0||ordinal>=accepted.callbackOutputs) + return reject(SpeakerReservationFault::unknownPort); + if(!used.insert(ordinal).second) + return reject(SpeakerReservationFault::occupiedOutput); + report.reservedCallbackOrdinals.push_back(ordinal); + // The M2 "limiter" is currently a HARD DIGITAL CEILING, not a + // calibrated voltage/RMS/peak speaker safety DSP. No live output + // authorization is legal merely because a user enabled it. + if(!selected.mute) + return reject(SpeakerReservationFault::unprotectedOutput); + } + report.acceptedDeviceEpoch=accepted.deviceEpoch; + report.acceptedGraphRevision=accepted.acceptedGraphRevision; + // Result describes only a safely disconnected mapping draft. + // A later true native limiter + verified profile must introduce a + // distinct typed hardware publication transaction. + return report; + } +}; +} // namespace armix::lms diff --git a/engine/lms/PreparedSpeakerSystem.h b/engine/lms/PreparedSpeakerSystem.h new file mode 100644 index 000000000..92e46097f --- /dev/null +++ b/engine/lms/PreparedSpeakerSystem.h @@ -0,0 +1,466 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +// LMS M2 native PCM kernel. Not a second callback, mixer, or device manager. +// CONTROL: validate/compile/allocate. AUDIO: bounded process only. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace armix::lms { +struct VerifiedOutputPort final { + std::string identity; // exact verified device-native pin, not DEMO/GUI ordinal + int callbackOrdinal=-1; +}; +struct ParametricBand final { + double frequencyHz=1000.,q=0.70710678118,gainDb=0.; + bool enabled=true; // same bypass semantics as LMS Output EQ editor +}; +// CONTROL-origin voltage model. Values are REQUIRED measured/manufacturer data, +// NOT defaults and NOT a browser checkbox. A validated value set is not proof +// of hardware calibration and NEVER grants permission to ARM an ASIO pin. +struct DriverVoltageModel final { + std::string profileId; // external driver/manufacturer reference + double dacFullScaleVrms=0.; // measured DAC sine RMS at digital 0dBFS + double amplifierVoltageGain=0.; // measured volts-out / volts-in (linear) + double continuousDriverVrms=0.; // manufacturer-derived electrical limit + double driverPeakVolts=0.; // manufacturer-derived instantaneous limit + double minimumHighpassHz=0.; // 0 only when no safety HPF is specified + double rmsWindowMs=500.; // thermal-oriented detector time constant + double releaseMs=150.; // attenuation release, immediate peak attack +}; +struct OutputPatch final { + std::string outputId,portIdentity; + int sourceSide=0,section=0; // section [0,ways); side 0=L/mono, 1=R + double delayMs=0.,gainDb=0.; + std::vector peq; // max 8 fully prepared peaking bands + bool mute=true,limiterEnabled=false,polarityInverted=false; + double ceilingDbfs=-6.; + // A host-owned, explicit operator acknowledgement, NOT proof of physical protection. + bool confirmedSpeakerProfile=false; + std::optional voltageModel; // host CONTROL only +}; +struct SpeakerSystemRequest final { + std::uint64_t deviceEpoch=0,graphRevision=0; + double sampleRate=0.; + int maxFrames=0,activeOutputChannels=0,ways=2; // 1..16, budget constrained + bool stereo=true; + std::vector crossoverHz; // ascending, ways-1 + std::vector verifiedPorts; + std::vector outputs; + std::size_t scratchBudgetBytes=16U*1024U*1024U; +}; +enum class SpeakerPlanFault : std::uint8_t { + none,invalidEpoch,invalidFormat,invalidCrossover,invalidPort, + duplicatePort,invalidRoute,invalidOutputDsp,unconfirmedSpeaker, + scratchBudget,preparationFailed,invalidVoltageModel +}; +struct SpeakerPrepareResult final { + SpeakerPlanFault fault=SpeakerPlanFault::none; + std::size_t scratchBytes=0; + [[nodiscard]] bool ok() const noexcept {return fault==SpeakerPlanFault::none;} +}; + +// 2 x 2nd-order Butterworth = LR4, 24 dB/oct, in-phase complementary pair. +struct Biquad final { + double b0=1.,b1=0.,b2=0.,a1=0.,a2=0.,z1=0.,z2=0.; + [[nodiscard]] float process(float in) noexcept { + const double x=static_cast(in),y=b0*x+z1; + z1=b1*x-a1*y+z2;z2=b2*x-a2*y; + if(std::abs(z1)<1.e-28)z1=0.; + if(std::abs(z2)<1.e-28)z2=0.; + return static_cast(y); + } + static Biquad make(double sr,double hz,bool high) noexcept { + constexpr double q=0.7071067811865475244; + constexpr double pi=3.14159265358979323846; + const double w=2.*pi*hz/sr,c=std::cos(w),a=std::sin(w)/(2.*q); + const double scale=1./(1.+a); + Biquad b; + b.b0=((high?(1.+c):(1.-c))*.5)*scale; + b.b1=(high?-(1.+c):(1.-c))*scale; + b.b2=b.b0;b.a1=-2.*c*scale;b.a2=(1.-a)*scale; + return b; + } + static Biquad peak(double sr,double hz,double q,double gainDb) noexcept { + constexpr double pi=3.14159265358979323846; + const double w=2.*pi*hz/sr,c=std::cos(w),alpha=std::sin(w)/(2.*q); + const double A=std::pow(10.,gainDb/40.),scale=1./(1.+alpha/A); + Biquad b; + b.b0=(1.+alpha*A)*scale; + b.b1=-2.*c*scale; + b.b2=(1.-alpha*A)*scale; + b.a1=b.b1; + b.a2=(1.-alpha/A)*scale; + return b; + } +}; + +class PreparedSpeakerSystem final { +public: + struct OutputProtectionReadback final { + bool voltageModelPrepared=false; // calibration has NOT been proven + float gainReductionDb=0.f; + float preLimitRmsDigital=0.f; + float outputPeakDigital=0.f; + }; +private: + struct Section final { + int side=0,way=0; + std::array hp{},lp{}; + bool hasHigh=false,hasLow=false; + }; + struct Destination final { + int source=0,physical=0; + float gain=1.f,ceiling=1.f,polarity=1.f; + bool mute=true,limit=false,voltageMode=false,safetyHpf=false; + float voltagePeakDigital=1.f,voltageRmsDigital=1.f; + float attenuation=1.f; + double rmsPower=0.,rmsCoefficient=0.,releaseCoefficient=0.; + double delaySamples=0.; + std::array safetyHp{}; + std::vector eq; + std::vector ring; + std::size_t write=0; + [[nodiscard]] float delay(float sample) noexcept { + if(delaySamples<=0.)return sample; + ring[write]=sample; + double read=static_cast(write)-delaySamples; + if(read<0.)read+=static_cast(ring.size()); + const auto index=static_cast(read); + const auto other=(index+1)%ring.size(); + const float frac=static_cast(read-static_cast(index)); + const float result=ring[index]+(ring[other]-ring[index])*frac; + if(++write==ring.size())write=0; + return result; + } + }; + std::uint64_t epoch_=0,revision_=0; + int capacity_=0,physicalCount_=0,ways_=0; + bool stereo_=false; + std::vector
sections_; + std::vector destinations_; + std::vector scratch_; + // Separate lock-free telemetry storage; all writes are AUDIO, CONTROL + // only samples atomic values. No vectors/heap or locking in process(). + std::unique_ptr[]> lastGrDb_,lastRms_,lastPeak_; + std::size_t usedBytes_=0; +public: + PreparedSpeakerSystem()=default; + PreparedSpeakerSystem(const PreparedSpeakerSystem&)=delete; + PreparedSpeakerSystem& operator=(const PreparedSpeakerSystem&)=delete; + PreparedSpeakerSystem(PreparedSpeakerSystem&&)=default; + PreparedSpeakerSystem& operator=(PreparedSpeakerSystem&&)=default; + [[nodiscard]] std::size_t scratchBytes() const noexcept{return usedBytes_;} + [[nodiscard]] std::size_t sectionCount() const noexcept{return sections_.size();} + [[nodiscard]] std::size_t destinationCount() const noexcept{return destinations_.size();} + [[nodiscard]] std::uint64_t epoch() const noexcept{return epoch_;} + [[nodiscard]] std::uint64_t revision() const noexcept{return revision_;} + [[nodiscard]] bool outputProtectionReadback(std::size_t index, + OutputProtectionReadback& out) const noexcept { + if(index>=destinations_.size()||!lastGrDb_||!lastRms_||!lastPeak_) + return false; + out.voltageModelPrepared=destinations_[index].voltageMode; + out.gainReductionDb=lastGrDb_[index].load(std::memory_order_acquire); + out.preLimitRmsDigital=lastRms_[index].load(std::memory_order_acquire); + out.outputPeakDigital=lastPeak_[index].load(std::memory_order_acquire); + return true; + } + + // A rejected candidate NEVER changes the prior accepted snapshot. + static SpeakerPrepareResult prepare(const SpeakerSystemRequest& req, + std::unique_ptr& accepted) { + SpeakerPrepareResult result; + try { + if(!req.deviceEpoch||!req.graphRevision){ + result.fault=SpeakerPlanFault::invalidEpoch;return result; + } + if(!(req.sampleRate>=8000.&&req.sampleRate<=384000.)|| + !std::isfinite(req.sampleRate)||req.maxFrames<1||req.maxFrames>8192|| + req.ways<1||req.ways>16||req.activeOutputChannels<1|| + req.activeOutputChannels>256){ + result.fault=SpeakerPlanFault::invalidFormat;return result; + } + if(req.crossoverHz.size()!=static_cast(req.ways-1)){ + result.fault=SpeakerPlanFault::invalidCrossover;return result; + } + double prev=15.; + for(const auto hz:req.crossoverHz){ + if(!std::isfinite(hz)||hz<20.||hz<=prev*1.01|| + hz>=req.sampleRate*.45){ + result.fault=SpeakerPlanFault::invalidCrossover;return result; + } + prev=hz; + } + std::unordered_set names; + std::unordered_set ordinals; + if(req.verifiedPorts.empty()||req.verifiedPorts.size()>256){ + result.fault=SpeakerPlanFault::invalidPort;return result; + } + for(const auto& p:req.verifiedPorts) { + if(p.identity.empty()||p.identity.starts_with("DEMO-")|| + p.callbackOrdinal<0||p.callbackOrdinal>=req.activeOutputChannels|| + !names.insert(p.identity).second|| + !ordinals.insert(p.callbackOrdinal).second){ + result.fault=SpeakerPlanFault::invalidPort;return result; + } + } + if(req.outputs.size()>req.verifiedPorts.size()){ + result.fault=SpeakerPlanFault::invalidPort;return result; + } + std::unordered_set logical; + std::unordered_set physical; + std::size_t totalRing=0,totalEq=0; + for(const auto& p:req.outputs){ + if(p.outputId.empty()||p.portIdentity.empty()|| + !logical.insert(p.outputId).second|| + !physical.insert(p.portIdentity).second){ + result.fault=SpeakerPlanFault::duplicatePort;return result; + } + if((p.sourceSide!=0&&p.sourceSide!=1)|| + (!req.stereo&&p.sourceSide!=0)|| + p.section<0||p.section>=req.ways){ + result.fault=SpeakerPlanFault::invalidRoute;return result; + } + if(!std::any_of(req.verifiedPorts.begin(),req.verifiedPorts.end(), + [&](const auto& x){return x.identity==p.portIdentity;})){ + result.fault=SpeakerPlanFault::invalidPort;return result; + } + if(!std::isfinite(p.gainDb)||p.gainDb< -60.||p.gainDb>6.|| + !std::isfinite(p.delayMs)||p.delayMs<0.||p.delayMs>500.|| + !std::isfinite(p.ceilingDbfs)||p.ceilingDbfs< -60.||p.ceilingDbfs>0.){ + result.fault=SpeakerPlanFault::invalidOutputDsp;return result; + } + if(p.peq.size()>8){ + result.fault=SpeakerPlanFault::invalidOutputDsp;return result; + } + for(const auto& band:p.peq) + if(!std::isfinite(band.frequencyHz)||band.frequencyHz<20.|| + band.frequencyHz>=req.sampleRate*.45|| + !std::isfinite(band.q)||band.q<.1||band.q>18.|| + !std::isfinite(band.gainDb)||band.gainDb< -18.|| + band.gainDb>18.){ + result.fault=SpeakerPlanFault::invalidOutputDsp;return result; + } + totalEq+=p.peq.size(); + if(p.voltageModel) { + const auto& m=*p.voltageModel; + const auto safe=[](double v,double lo,double hi) noexcept { + return std::isfinite(v)&&v>=lo&&v<=hi; + }; + // A full measured-voltage model is all-or-nothing. A + // partial/malformed profile cannot be treated as calibrated. + if(m.profileId.empty()||m.profileId.size()>128|| + !safe(m.dacFullScaleVrms,.1,50.)|| + !safe(m.amplifierVoltageGain,1.,1000.)|| + !safe(m.continuousDriverVrms,.01,10000.)|| + !safe(m.driverPeakVolts,.01,20000.)|| + !safe(m.minimumHighpassHz,0.,req.sampleRate*.45)|| + (m.minimumHighpassHz!=0. && m.minimumHighpassHz<20.)|| + !safe(m.rmsWindowMs,10.,30000.)|| + !safe(m.releaseMs,5.,10000.)) { + result.fault=SpeakerPlanFault::invalidVoltageModel;return result; + } + const double normalization=std::sqrt(2.)* + m.dacFullScaleVrms*m.amplifierVoltageGain; + const double peak=m.driverPeakVolts/normalization; + const double rms=m.continuousDriverVrms/normalization; + if(!safe(peak,1.e-7,1.)||!safe(rms,1.e-7,1.)|| + m.driverPeakVolts=static_cast( + std::numeric_limits::max()/sizeof(float)-4)){ + result.fault=SpeakerPlanFault::scratchBudget;return result; + } + totalRing+=static_cast(samples)+3; + } + const auto sections=static_cast(req.ways)*(req.stereo?2U:1U); + const auto maxFloats=req.scratchBudgetBytes/sizeof(float); + const auto totalSamples=sections*static_cast(req.maxFrames); + const auto floatBytes=(totalRing+totalSamples)*sizeof(float); + const auto telemetryBytes=req.outputs.size()*3U*sizeof(std::atomic); + if(sections>maxFloats/static_cast(req.maxFrames)|| + totalRing>maxFloats-totalSamples|| + floatBytes>req.scratchBudgetBytes|| + telemetryBytes>req.scratchBudgetBytes-floatBytes|| + totalEq*sizeof(Biquad)>req.scratchBudgetBytes-floatBytes-telemetryBytes){ + result.fault=SpeakerPlanFault::scratchBudget;return result; + } + auto next=std::make_unique(); + next->epoch_=req.deviceEpoch;next->revision_=req.graphRevision; + next->capacity_=req.maxFrames;next->physicalCount_=req.activeOutputChannels; + next->ways_=req.ways;next->stereo_=req.stereo; + next->scratch_.resize(sections*static_cast(req.maxFrames)); + next->sections_.reserve(sections); + for(int side=0;side<(req.stereo?2:1);++side) + for(int way=0;way0){ + s.hasHigh=true; + s.hp[0]=s.hp[1]=Biquad::make(req.sampleRate,req.crossoverHz[way-1],true); + } + if(waysections_.push_back(s); + } + next->destinations_.reserve(req.outputs.size()); + if(!req.outputs.empty()) { + next->lastGrDb_=std::make_unique[]>(req.outputs.size()); + next->lastRms_=std::make_unique[]>(req.outputs.size()); + next->lastPeak_=std::make_unique[]>(req.outputs.size()); + for(std::size_t i=0;ilastGrDb_[i].store(0.f,std::memory_order_relaxed); + next->lastRms_[i].store(0.f,std::memory_order_relaxed); + next->lastPeak_[i].store(0.f,std::memory_order_relaxed); + } + } + for(const auto& p:req.outputs){ + Destination d; + const auto pin=std::find_if(req.verifiedPorts.begin(),req.verifiedPorts.end(), + [&](const auto& x){return x.identity==p.portIdentity;}); + d.physical=pin->callbackOrdinal; + d.source=p.sourceSide*req.ways+p.section; + d.gain=static_cast(std::pow(10.,p.gainDb/20.)); + d.mute=p.mute;d.limit=p.limiterEnabled; + d.polarity=p.polarityInverted?-1.f:1.f; + d.ceiling=static_cast(std::pow(10.,p.ceilingDbfs/20.)); + if(p.voltageModel) { + const auto& m=*p.voltageModel; + const double norm=std::sqrt(2.)*m.dacFullScaleVrms* + m.amplifierVoltageGain; + d.voltageMode=true; + d.voltagePeakDigital=static_cast(m.driverPeakVolts/norm); + d.voltageRmsDigital=static_cast(m.continuousDriverVrms/norm); + d.rmsCoefficient=std::exp(-1000./(m.rmsWindowMs*req.sampleRate)); + d.releaseCoefficient=std::exp(-1000./(m.releaseMs*req.sampleRate)); + if(m.minimumHighpassHz>0.) { + d.safetyHpf=true; + d.safetyHp[0]=d.safetyHp[1]=Biquad::make( + req.sampleRate,m.minimumHighpassHz,true); + } + } + d.delaySamples=p.delayMs*req.sampleRate/1000.; + d.eq.reserve(p.peq.size()); + for(const auto& band:p.peq) + if(band.enabled) + d.eq.push_back(Biquad::peak(req.sampleRate,band.frequencyHz, + band.q,band.gainDb)); + if(d.delaySamples>0.) + d.ring.resize(static_cast(std::ceil(d.delaySamples))+3); + next->destinations_.push_back(std::move(d)); + } + next->usedBytes_=next->scratch_.size()*sizeof(float); + for(const auto& d:next->destinations_) + next->usedBytes_+=d.ring.size()*sizeof(float)+d.eq.size()*sizeof(Biquad); + next->usedBytes_+=req.outputs.size()*3U*sizeof(std::atomic); + result.scratchBytes=next->usedBytes_; + accepted=std::move(next); + return result; + }catch(...){ + result.fault=SpeakerPlanFault::preparationFailed;return result; + } + } + // AUDIO only. All source planes are copied into prepared section buffers + // BEFORE output writes, so input aliasing physical MAIN is supported. + // On stale epoch/revision, bad frame count, or absent pin: zero writes. + [[nodiscard]] bool process(std::uint64_t currentDeviceEpoch, + std::uint64_t acceptedGraphRevision,const float* mainL, + const float* mainR,float* const* output,int physicalCount, + int frames,bool nativeOutputAuthorized) noexcept { + if(!nativeOutputAuthorized||currentDeviceEpoch!=epoch_|| + acceptedGraphRevision!=revision_||physicalCount!=physicalCount_|| + frames<1||frames>capacity_||!mainL||(stereo_&&!mainR)||!output) + return false; + for(const auto& d:destinations_) + if(d.physical<0||d.physical>=physicalCount||!output[d.physical]) + return false; + if(destinations_.empty())return true; // no active physical pins + for(std::size_t idx=0;idx(capacity_); + for(int i=0;i(d.source)*capacity_; + if(d.mute){ + std::fill_n(out,frames,0.f); + lastGrDb_[destIndex].store(0.f,std::memory_order_release); + lastRms_[destIndex].store(0.f,std::memory_order_release); + lastPeak_[destIndex].store(0.f,std::memory_order_release); + continue; + } + float worstAttenuation=1.f,outputPeak=0.f; + for(int i=0;i(x)*x; + d.rmsPower=d.rmsCoefficient*d.rmsPower+ + (1.-d.rmsCoefficient)*power; + const float rms=static_cast(std::sqrt(std::max(0.,d.rmsPower))); + float wanted=1.f; + const float ax=std::abs(x); + if(ax>d.voltagePeakDigital) + wanted=std::min(wanted,d.voltagePeakDigital/ax); + if(rms>d.voltageRmsDigital) + wanted=std::min(wanted,d.voltageRmsDigital/rms); + // Immediate reduction protects a known sample peak; + // exponential recovery avoids gain-pumping on release. + if(wanted( + d.releaseCoefficient*d.attenuation+ + (1.-d.releaseCoefficient)*wanted); + x*=d.attenuation; + worstAttenuation=std::min(worstAttenuation,d.attenuation); + // Last-resort SAMPLE-peak fence; intersample peaks and + // thermal/excursion limits are NOT certified here. + x=std::clamp(x,-d.voltagePeakDigital,d.voltagePeakDigital); + } + // Legacy dBFS ceiling remains only a digital fallback. + if(d.limit)x=std::clamp(x,-d.ceiling,d.ceiling); + out[i]=x; + outputPeak=std::max(outputPeak,std::abs(x)); + } + const float gr=worstAttenuation<1.f? + -20.f*std::log10(std::max(worstAttenuation,1.e-9f)):0.f; + lastGrDb_[destIndex].store(gr,std::memory_order_release); + lastRms_[destIndex].store(d.voltageMode? + static_cast(std::sqrt(std::max(0.,d.rmsPower))):0.f, + std::memory_order_release); + lastPeak_[destIndex].store(outputPeak,std::memory_order_release); + } + return true; + } +}; +} // namespace armix::lms diff --git a/scripts/build_pages.py b/scripts/build_pages.py index 61b4c03d1..4c7d6fd73 100644 --- a/scripts/build_pages.py +++ b/scripts/build_pages.py @@ -7,6 +7,7 @@ from approved_fx_rack_interaction import apply_fx_rack_interaction from compose_native_peq import apply_native_peq from compose_operator_ux import apply_operator_ux +from compose_lms import apply_lms ROOT=Path(__file__).resolve().parents[1] p=argparse.ArgumentParser() p.add_argument('--out',default='dist-pages') @@ -92,6 +93,7 @@ canonical_html=apply_fx_rack_interaction(canonical_html,buttons_dest/'assets') canonical_html=apply_native_peq(canonical_html) canonical_html=apply_operator_ux(canonical_html,buttons_dest/'assets') +canonical_html=apply_lms(canonical_html,buttons_dest/'assets') # The shipped UI is composed from inline JS as well as owner assets. Check all # inline code BEFORE packaging or deployment: a single unterminated string # otherwise leaves an empty mixer despite green source/PNG contract tests. diff --git a/scripts/compose_lms.py b/scripts/compose_lms.py new file mode 100644 index 000000000..498edc6ab --- /dev/null +++ b/scripts/compose_lms.py @@ -0,0 +1,53 @@ +"""Integrate LMS in the SINGLE approved /preview/ assembler, never a second page. + +LMS is an offline logical DESIGN workspace only. Native PCM is neither +created nor touched; production hardware must implement ACK/readback separately. +""" +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +LMS_STYLE = ROOT / "site" / "preview-v2" / "assets" / "lms-workspace.css" +LMS_SCRIPTS = ("lms-system-model.js", "lms-workspace.js") + + +def _once(source: str, target: str, replacement: str, label: str) -> str: + if source.count(target) != 1: + raise ValueError("LMS approved /preview/ anchor drift: " + label) + return source.replace(target, replacement, 1) + + +def apply_lms(html: str, assets: Path) -> str: + """Compose one scoped workspace beside the mixer, not over its PCM state.""" + button = ('') + html = _once( + html, button, + button + '\n ', + "primary toolbar button") + html = _once( + html, '
', + ' \n' + '
', + "single in-app workspace") + scripts = "".join('\n' + for name in LMS_SCRIPTS) + for name in LMS_SCRIPTS: + if not (ROOT / "site" / "preview-v2" / "assets" / name).is_file(): + raise FileNotFoundError("LMS asset missing: " + name) + html = _once(html, '', scripts + '', "script order") + + chrome = assets / "mixer-chrome-material.css" + current = chrome.read_text(encoding="utf-8") + scoped = LMS_STYLE.read_text(encoding="utf-8") + if ".lms-workspace{" in current or "\n.console-pane{" in scoped: + raise ValueError("LMS CSS ownership collision") + if not scoped.startswith("/* ArSonMix LMS:"): + raise ValueError("Unexpected LMS CSS source") + chrome.write_text(current.rstrip() + "\n" + scoped.rstrip() + "\n", + encoding="utf-8") + return html diff --git a/site/preview-v2/assets/lms-system-model.js b/site/preview-v2/assets/lms-system-model.js new file mode 100644 index 000000000..6382da9f4 --- /dev/null +++ b/site/preview-v2/assets/lms-system-model.js @@ -0,0 +1,344 @@ +/* ArSonMix LMS logical DESIGN model. No PCM, no device writes, no fake ACK. + * Portable CommonJS/browser API. Hardware mapping belongs to native control. + */ +(function (root, factory) { + const api = factory(); + if (typeof module === "object" && module.exports) module.exports = api; + else root.ArSonMixLmsModel = api; +})(typeof globalThis !== "undefined" ? globalThis : this, function () { + "use strict"; + const MIN_HZ = 20, MAX_HZ = 20000, SPEED_M_S = 343; + const SIDES = Object.freeze(["L", "R"]); + const MAX_WAYS = 16; + const MAX_DEMO_PORTS = 32; + const requireNumber = (v, lo, hi, label) => { + if (typeof v !== "number" || !Number.isFinite(v) || v < lo || v > hi) + throw new RangeError(label); + return v; + }; + const requireInteger = (v, lo, hi, label) => { + requireNumber(v, lo, hi, label); + if (!Number.isInteger(v)) throw new RangeError(label); + return v; + }; + const suffixes = n => { + if (n === 1) return ["FULL"]; + if (n === 2) return ["LOW", "HIGH"]; + if (n === 3) return ["LOW", "MID", "HIGH"]; + if (n === 4) return ["SUB", "LOW", "MID", "HIGH"]; + return Array.from({length:n}, (_,i) => "WAY " + String(i+1).padStart(2,"0")); + }; + function sectionsFor(ways, stereo) { + requireInteger(ways, 1, MAX_WAYS, "ways"); + const names = suffixes(ways); + return (stereo ? SIDES : ["M"]).flatMap(side => + names.map((band,i) => Object.freeze({ + id: side + ":" + (i+1), + name: band + (side === "M" ? "" : " " + side), + band, side, index:i + })) + ); + } + function defaultCutoffs(ways) { + if (ways === 1) return []; + if (ways === 2) return [1600]; + if (ways === 3) return [120,2400]; + if (ways === 4) return [80,250,2400]; + return Array.from({length:ways-1}, (_,i) => + Math.round(40 * Math.pow(12000/40,(i+1)/ways))); + } + function validateCutoffs(cutoffs, ways) { + if (!Array.isArray(cutoffs) || cutoffs.length !== ways-1) + throw new RangeError("crossover boundary count"); + let previous = MIN_HZ; + for (const value of cutoffs) { + requireNumber(value, MIN_HZ, MAX_HZ, "crossover frequency"); + if (value <= previous*1.01 || value >= MAX_HZ) + throw new RangeError("crossover bands must remain strictly ordered"); + previous = value; + } + return true; + } + function demoPorts(n) { + requireInteger(n, 1, MAX_DEMO_PORTS, "demo port count"); + return Array.from({length:n}, (_,i) => "DEMO-" + String(i+1).padStart(2,"0")); + } + const defaultDsp = () => ({ + gainDb:0, delayMs:0, polarity:"normal", peq:[], + muted:true, limiterEnabled:false, limiterThresholdDb:null + }); + const defaultPosition = i => ({x:(i%2===0?-4.5:4.5), y:3+2*Math.floor(i/2)}); + function createSystem({ways=3,stereo=true,ports=[]}={}) { + if (typeof stereo!=="boolean") throw new TypeError("stereo"); + requireInteger(ways,1,MAX_WAYS,"ways"); + if (!Array.isArray(ports) || ports.length>64 || ports.some(p=>typeof p!=="string" || !p.trim())) + throw new TypeError("ports"); + if (new Set(ports).size !== ports.length) throw new Error("duplicate port identity"); + return { + schema:"arsonmix.lms.draft.v1", revision:0, name:"Main PA", + ways, stereo, cutoffsHz:defaultCutoffs(ways), + sections:sectionsFor(ways,stereo), ports:ports.slice(), + // Empty crosspoints are intentional: NEVER auto-connect to an unknown speaker. + routes:{}, dsp:Object.fromEntries(ports.map(p=>[p,defaultDsp()])), + positions:Object.fromEntries(ports.map((p,i)=>[p,defaultPosition(i)])), + listener:{x:0,y:15}, applied:false + }; + } + function validateSystem(s) { + if (!s || s.schema!=="arsonmix.lms.draft.v1" || s.applied!==false) + throw new Error("not an offline LMS draft"); + requireInteger(s.ways,1,MAX_WAYS,"ways"); + validateCutoffs(s.cutoffsHz,s.ways); + if (!Array.isArray(s.ports) || new Set(s.ports).size!==s.ports.length) + throw new Error("invalid port list"); + const expected = sectionsFor(s.ways,s.stereo).map(x=>x.id); + if (JSON.stringify(expected)!==JSON.stringify(s.sections.map(x=>x.id))) + throw new Error("section identities inconsistent"); + for (const [port,section] of Object.entries(s.routes)) { + if (!s.ports.includes(port)||!expected.includes(section)) + throw new Error("orphan output mapping"); + } + return true; + } + function withWays(s,ways) { + validateSystem(s); + requireInteger(ways,1,MAX_WAYS,"ways"); + if (ways===s.ways) return s; + // Section ordinal meaning changes: clearing ALL crosspoints is intentional. + // Old acoustic protection settings must never silently migrate to a new driver. + return {...s, revision:s.revision+1, ways, + cutoffsHz:defaultCutoffs(ways), sections:sectionsFor(ways,s.stereo), + routes:{}, dsp:Object.fromEntries(s.ports.map(p=>[p,defaultDsp()])) + }; + } + function withStereo(s,stereo) { + validateSystem(s); + if (typeof stereo!=="boolean") throw new TypeError("stereo"); + if (s.stereo===stereo) return s; + return {...s, revision:s.revision+1, stereo, + sections:sectionsFor(s.ways,stereo), routes:{}, + dsp:Object.fromEntries(s.ports.map(p=>[p,defaultDsp()]))}; + } + function withCutoff(s,index,hz) { + validateSystem(s); + requireInteger(index,0,s.ways-2,"cutoff index"); + const next=s.cutoffsHz.slice(); + next[index]=requireNumber(hz,MIN_HZ,MAX_HZ,"crossover frequency"); + validateCutoffs(next,s.ways); + return {...s, revision:s.revision+1, cutoffsHz:next}; + } + function withPorts(s,ports) { + validateSystem(s); + if (!Array.isArray(ports) || ports.some(p=>typeof p!=="string" || !p.trim()) + || new Set(ports).size!==ports.length || ports.length>64) + throw new TypeError("ports must have distinct stable identities"); + if (JSON.stringify(ports)===JSON.stringify(s.ports)) return s; + // Device identity changed: any previous patch is now unsafe, even if + // a previous ordinal happens to have the same visible number. + return {...s, revision:s.revision+1, ports:ports.slice(), routes:{}, + dsp:Object.fromEntries(ports.map(p=>[p,defaultDsp()])), + positions:Object.fromEntries(ports.map((p,i)=>[p,s.positions[p]||defaultPosition(i)])) + }; + } + + // Explicit old logical output => inspected physical identity. Never guess + // ASIO ordinals. A non-selected tuned/connected output rejects atomically. + function reassignVerifiedPorts(s,ports,assignments) { + validateSystem(s); + if(!Array.isArray(ports)||ports.length<1||ports.length>64|| + ports.some(p=>typeof p!=="string"||!p.trim()||p.startsWith("DEMO-"))|| + new Set(ports).size!==ports.length) + throw new TypeError("verified port inventory required"); + if(!assignments||typeof assignments!=="object"||Array.isArray(assignments)|| + !Object.keys(assignments).length) + throw new Error("Choose at least one explicit output assignment"); + const used=new Set(),routes={},defaults=defaultDsp(); + const dsp=Object.fromEntries(ports.map(p=>[p,defaultDsp()])); + const positions=Object.fromEntries(ports.map((p,i)=>[p,defaultPosition(i)])); + for(const [source,target] of Object.entries(assignments)){ + if(!s.ports.includes(source)||!ports.includes(target)) + throw new Error("Unknown output in remap"); + if(used.has(target))throw new Error("Duplicate physical port assignment"); + used.add(target); + dsp[target]={...s.dsp[source],peq:(s.dsp[source].peq||[]).map(b=>({...b})), + muted:true}; + positions[target]={...s.positions[source]}; + if(s.routes[source])routes[target]=s.routes[source]; + } + for(const source of s.ports){ + const p=s.dsp[source],index=s.ports.indexOf(source); + const custom=Object.keys(defaults).some(k=> + JSON.stringify(p[k])!==JSON.stringify(defaults[k]))|| + JSON.stringify(s.positions[source])!==JSON.stringify(defaultPosition(index)); + if((s.routes[source]||custom)&& + !Object.prototype.hasOwnProperty.call(assignments,source)) + throw new Error("Assign "+source+" to preserve its routing, DSP or alignment"); + } + const next={...s,revision:s.revision+1,applied:false, + ports:ports.slice(),routes,dsp,positions}; + validateSystem(next); + return next; + } + function withRoute(s,port,section) { + validateSystem(s); + if (!s.ports.includes(port)) throw new RangeError("unknown output port"); + if (section!==null && !s.sections.some(x=>x.id===section)) + throw new RangeError("unknown crossover section"); + const routes={...s.routes}; + if (section===null || routes[port]===section) delete routes[port]; + else routes[port]=section; // one feed per physical output; fanout is allowed + return {...s, revision:s.revision+1, routes}; + } + function withDsp(s,port,patch) { + validateSystem(s); + if (!s.ports.includes(port) || !patch || typeof patch!=="object") + throw new RangeError("unknown output DSP target"); + const allowed=new Set(["gainDb","delayMs","polarity","muted", + "limiterEnabled","limiterThresholdDb"]); + for (const key of Object.keys(patch)) if (!allowed.has(key)) + throw new Error("unknown DSP property: "+key); + const p={...s.dsp[port],...patch}; + requireNumber(p.gainDb,-60,6,"gainDb"); + requireNumber(p.delayMs,0,500,"delayMs"); + if (!["normal","invert"].includes(p.polarity)) throw new RangeError("polarity"); + if (typeof p.muted!=="boolean" || typeof p.limiterEnabled!=="boolean") + throw new TypeError("DSP switches"); + if (p.limiterThresholdDb!==null) + requireNumber(p.limiterThresholdDb,-60,0,"limiterThresholdDb"); + // No hardware safety claims: this offline draft NEVER authorizes output. + return {...s, revision:s.revision+1, dsp:{...s.dsp,[port]:p}}; + } + // Output DSP band editor. The browser never runs audio; parameters stay + // in a typed disconnected draft pending native rate/port verification. + function validateBand(b) { + if (!b || typeof b !== "object" || typeof b.enabled !== "boolean") + throw new TypeError("PEQ band identity"); + requireNumber(b.frequencyHz,20,20000,"PEQ frequency"); + requireNumber(b.q,0.1,18,"PEQ Q"); + requireNumber(b.gainDb,-18,18,"PEQ gain"); + return true; + } + function withPeqBand(s,port,index,patch) { + validateSystem(s); + if (!s.ports.includes(port)) throw new RangeError("unknown output DSP target"); + if (!Number.isInteger(index)||index<0||index>=8)throw new RangeError("PEQ band index"); + const before=s.dsp[port].peq; + if (!Array.isArray(before)||index>before.length)throw new RangeError("PEQ gap"); + const allowed=["frequencyHz","q","gainDb","enabled"]; + if (!patch || Object.keys(patch).some(key=>!allowed.includes(key))) + throw new Error("unknown PEQ property"); + const next=before.map(p=>({...p})); + next[index]={frequencyHz:1000,q:0.70710678118,gainDb:0,enabled:true, + ...next[index],...patch}; + validateBand(next[index]); + return {...s,revision:s.revision+1,dsp:{ + ...s.dsp,[port]:{...s.dsp[port],peq:next} + }}; + } + function withoutPeqBand(s,port,index) { + validateSystem(s); + if(!s.ports.includes(port))throw new RangeError("unknown output DSP target"); + const before=s.dsp[port].peq; + requireInteger(index,0,before.length-1,"PEQ band index"); + return {...s,revision:s.revision+1,dsp:{ + ...s.dsp,[port]:{...s.dsp[port],peq:before.filter((_,i)=>i!==index)} + }}; + } + // C++ PreparedSpeakerSystem::Biquad::make is the authority. Mirror its + // 2 x Butterworth LR4 magnitude here, not made-up rectangular "curves". + // Preview always labels its ASSUMED 48kHz sample rate; not a measurement. + function biquadMagnitude(hz,cutoff,high,sampleRate) { + requireNumber(hz,20,sampleRate*.5-.01,"preview Hz"); + const omega=2*Math.PI*cutoff/sampleRate,c=Math.cos(omega); + const alpha=Math.sin(omega)/(2*Math.SQRT1_2); + const scale=1/(1+alpha); + const b0=((high?1+c:1-c)*.5)*scale; + const b1=(high?-(1+c):1-c)*scale,b2=b0; + const a1=-2*c*scale,a2=(1-alpha)*scale; + const theta=2*Math.PI*hz/sampleRate; + const cos=Math.cos(theta),sin=Math.sin(theta); + const real=b0+b1*cos+b2*Math.cos(2*theta); + const imag=-b1*sin-b2*Math.sin(2*theta); + const denR=1+a1*cos+a2*Math.cos(2*theta); + const denI=-a1*sin-a2*Math.sin(2*theta); + return Math.sqrt((real*real+imag*imag)/ + Math.max(1e-28,denR*denR+denI*denI)); + } + function crossoverMagnitude(cutoffs,way,hz,sampleRate=48000) { + if(!Array.isArray(cutoffs)||!Number.isInteger(way)|| + way<0||way>cutoffs.length||sampleRate<44100||sampleRate>192000|| + !Number.isFinite(hz)||hz<20||hz>=sampleRate*.5) + throw new RangeError("crossover plot request"); + let magnitude=1; + if(way>0){ + const one=biquadMagnitude(hz,cutoffs[way-1],true,sampleRate); + magnitude*=one*one; + } + if(way192000|| + !Number.isFinite(hz)||hz<20||hz>=sampleRate*.5) + throw new RangeError("PEQ plot request"); + let mag=1; + for(const b of bands) { + validateBand(b); + if(!b.enabled)continue; + if(b.frequencyHz>=sampleRate*.45)continue; // visual marker; native rejects + const w=2*Math.PI*b.frequencyHz/sampleRate,c=Math.cos(w); + const alpha=Math.sin(w)/(2*b.q),A=Math.pow(10,b.gainDb/40); + const scale=1/(1+alpha/A),th=2*Math.PI*hz/sampleRate; + const b0=(1+alpha*A)*scale,b1=-2*c*scale,b2=(1-alpha*A)*scale; + const a1=b1,a2=(1-alpha/A)*scale; + const cos=Math.cos(th),sin=Math.sin(th); + const nr=b0+b1*cos+b2*Math.cos(2*th),ni=-b1*sin-b2*Math.sin(2*th); + const dr=1+a1*cos+a2*Math.cos(2*th),di=-a1*sin-a2*Math.sin(2*th); + mag*=Math.sqrt((nr*nr+ni*ni)/Math.max(1e-28,dr*dr+di*di)); + } + return 20*Math.log10(Math.max(1e-10,mag)); + } + function withSuggestedDelays(s) { + validateSystem(s); + const estimates=alignment(s); + if(estimates.some(x=>x.additionalMs>500))throw new RangeError("alignment delay budget"); + const dsp={...s.dsp}; + for(const x of estimates) + dsp[x.port]={...dsp[x.port],delayMs:Math.round(x.additionalMs*100)/100}; + return {...s,revision:s.revision+1,dsp}; + } + function withPosition(s,port,x,y) { + validateSystem(s); + if (!s.ports.includes(port)) throw new RangeError("unknown speaker"); + requireNumber(x,-1000,1000,"speaker x"); + requireNumber(y,-1000,1000,"speaker y"); + return {...s, revision:s.revision+1, + positions:{...s.positions,[port]:{x,y}}}; + } + function withListener(s,x,y) { + validateSystem(s); + requireNumber(x,-1000,1000,"listener x"); + requireNumber(y,-1000,1000,"listener y"); + return {...s, revision:s.revision+1,listener:{x,y}}; + } + function alignment(s,{speed=SPEED_M_S}={}) { + validateSystem(s); + requireNumber(speed,300,360,"sound speed"); + const distances=s.ports.map(p=>{ + const v=s.positions[p], dx=v.x-s.listener.x,dy=v.y-s.listener.y; + return {port:p,distanceM:Math.hypot(dx,dy)}; + }); + const farthest=Math.max(0,...distances.map(d=>d.distanceM)); + return distances.map(d=>({...d,additionalMs:(farthest-d.distanceM)/speed*1000})); + } + return Object.freeze({ + MAX_WAYS,MAX_DEMO_PORTS,sectionsFor,defaultCutoffs,validateCutoffs, + demoPorts,createSystem,validateSystem,withWays,withStereo,withCutoff, + withPorts,reassignVerifiedPorts,withRoute,withDsp,withPeqBand,withoutPeqBand, + crossoverMagnitude,peqMagnitude,withSuggestedDelays, + withPosition,withListener,alignment + }); +}); diff --git a/site/preview-v2/assets/lms-workspace.css b/site/preview-v2/assets/lms-workspace.css new file mode 100644 index 000000000..aadecaf1d --- /dev/null +++ b/site/preview-v2/assets/lms-workspace.css @@ -0,0 +1,136 @@ +/* ArSonMix LMS: one scoped workspace in the approved /preview/ console. + Compiled into existing mixer-chrome-material CSS owner, no extra runtime sheet. + Independent of source mixer/fader/WIRE styling and all native PCM controls. */ +.app.lms-active .console-pane{display:none!important} +.app.lms-active .command-bar>:not(#lmsOpen){display:none!important} +.command-bar #lmsOpen[aria-pressed="true"]{border-color:#58bbce;background:#183944;color:#c8eff5} +.lms-workspace[hidden]{display:none!important} +.lms-workspace{ + --lms-bg:#0c151c;--lms-surface:#13202a;--lms-border:#30434e; + --lms-ink:#d8e6eb;--lms-secondary:#92aeb9;--lms-accent:#5bc5d1; + flex:1;min-height:0;min-width:0;display:flex;overflow:hidden; + background:var(--lms-bg);color:var(--lms-ink); + font:400 12px/1.4 "Segoe UI",Arial,sans-serif;letter-spacing:0 +} +.lms-workspace *{box-sizing:border-box} +.lms-workspace button,.lms-workspace input,.lms-workspace select{ + font:inherit;color:inherit +} +.lms-workspace button{cursor:pointer} +.lms-workspace button:focus-visible,.lms-workspace input:focus-visible, +.lms-workspace select:focus-visible{outline:2px solid var(--lms-accent);outline-offset:2px} +.lms-sidebar{width:164px;flex:none;border-right:1px solid var(--lms-border); + background:linear-gradient(180deg,#172630,#101b24);padding:14px 8px;overflow-y:auto} +.lms-sidebar .lms-name{font-size:12px;font-weight:620;letter-spacing:.03em; + color:#e8f4f6;margin:3px 10px 16px} +.lms-nav{display:flex;flex-direction:column;gap:3px} +.lms-nav button{display:flex;align-items:center;gap:10px;width:100%;text-align:left; + border:1px solid transparent;background:transparent;padding:10px 11px; + border-radius:5px;color:#a9c0c9} +.lms-nav button.active{background:#22424c;color:#e8fcff;border-color:#477985} +.lms-nav button:hover:not(.active){background:#1d303b} +.lms-nav .lms-index{opacity:.65;font:500 10px/1.2 monospace} +.lms-sidebar-foot{border-top:1px solid #30434e;color:#93abb5;margin-top:22px; + padding:14px 10px;font-size:10px;line-height:1.5} +.lms-stage{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:hidden} +.lms-heading{display:flex;justify-content:space-between;align-items:center;gap:10px; + padding:11px 18px;border-bottom:1px solid var(--lms-border);min-height:53px;flex:none} +.lms-heading h2{font-size:16px;font-weight:580;margin:0} +.lms-heading small{font-size:10px;color:var(--lms-secondary)} +.lms-offline{font-size:10px;border:1px solid #6e6141;padding:4px 8px;color:#e5c996; + border-radius:4px;white-space:nowrap;background:#332e22} +.lms-content{overflow:auto;flex:1;min-height:0;padding:16px 18px 24px} +.lms-grid{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(240px,.8fr);gap:14px} +.lms-panel{border:1px solid var(--lms-border);background:var(--lms-surface); + border-radius:6px;padding:14px;min-width:0;overflow:hidden} +.lms-panel h3{font-size:12px;font-weight:590;margin:0 0 13px;color:#e3eff3} +.lms-panel h3 span{float:right;font-weight:400;font-size:10px;color:var(--lms-secondary)} +.lms-label{display:block;font-size:10px;color:var(--lms-secondary);margin-bottom:6px} +.lms-muted{color:var(--lms-secondary)} +.lms-caption{font-size:10px;color:#94afb8;line-height:1.45} +.lms-line{border-top:1px solid #334651;margin:12px 0} +.lms-control-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap} +.lms-btn,.lms-select,.lms-number{border:1px solid #3c5664;background:#192b35; + border-radius:4px;padding:7px 10px;min-height:30px} +.lms-btn:hover{background:#26414c;border-color:#5da0b2} +.lms-btn.active{background:#174753;border-color:#5ac3d1;color:#c7f6ff} +.lms-btn:disabled{cursor:not-allowed;opacity:.45} +.lms-select{max-width:100%;min-width:100px} +.lms-number{width:92px;text-align:right;font-variant-numeric:tabular-nums} +.lms-number:disabled{opacity:.5} +.lms-summary{display:flex;gap:10px;flex-wrap:wrap} +.lms-stat{padding:10px 14px;border:1px solid #364e59;background:#142733; + min-width:95px;border-radius:4px} +.lms-stat b{font-size:19px;font-weight:500;display:block} +.lms-stat span{font-size:10px;color:var(--lms-secondary)} +.lms-steps{display:flex;gap:6px;align-items:center;flex-wrap:wrap;margin:12px 0} +.lms-step{padding:9px 11px;border:1px solid #375463;background:#1a2b37;border-radius:4px} +.lms-step strong{display:block;font-weight:500;font-size:11px} +.lms-step small{font-size:9px;color:#a4b9c1} +.lms-arrow{color:#6c939f;font-size:16px} +.lms-speaker-map{height:226px;position:relative; + border:1px solid #36505e;border-radius:5px; + background:repeating-linear-gradient(0deg,transparent,transparent 34px,#29404b40 35px), + repeating-linear-gradient(90deg,transparent,transparent 34px,#29404b40 35px),#0e1d26} +.lms-speaker-map .stage{position:absolute;top:8px;left:30%;right:30%; + padding:7px;text-align:center;background:#334651;border-radius:4px;font-size:10px} +.lms-map-spk{position:absolute;border:1px solid #689cac;border-radius:5px; + background:#1e414d;padding:6px 10px;color:#dcf8fd;font-size:10px} +.lms-listener{position:absolute;bottom:21px;left:50%;transform:translateX(-50%); + border:1px solid #6a92a1;border-radius:20px;padding:7px;background:#213442} +.lms-frequency{width:100%;max-height:250px;display:block;border:1px solid #334855;border-radius:4px} +.lms-band-row{display:flex;gap:8px;align-items:center;border-bottom:1px solid #2d414e; + padding:9px 2px;font-size:11px} +.lms-band-row:last-child{border-bottom:0} +.lms-band-mark{width:9px;height:9px;border-radius:2px;display:inline-block;flex:none} +.lms-band-row .lms-band-name{flex:1} +.lms-split-row{display:flex;align-items:center;gap:12px;padding:8px 0;border-bottom:1px solid #2d414e} +.lms-split-row:last-child{border:0} +.lms-split-row label{flex:1} +.lms-table-scroll{max-width:100%;overflow:auto;border:1px solid #354c57;border-radius:4px} +.lms-matrix{border-collapse:separate;border-spacing:0;width:max-content;min-width:100%;font-size:11px} +.lms-matrix th,.lms-matrix td{padding:7px 8px;border-right:1px solid #2b404d; + border-bottom:1px solid #293e48;text-align:center;white-space:nowrap} +.lms-matrix th:first-child,.lms-matrix td:first-child{position:sticky;left:0; + background:#1a2c37;text-align:left;z-index:2;min-width:95px} +.lms-matrix th{background:#1c2d38;font-weight:500;font-size:10px;color:#b3ccd4;position:sticky;top:0;z-index:1} +.lms-cross{min-width:26px;min-height:26px;border:1px solid #405765;border-radius:4px; + background:#10212b;color:#90abb4;padding:0} +.lms-cross.active{background:#177989;color:#fff;border-color:#5ed1de} +.lms-cross:hover{border-color:#85dbe5} +.lms-output-list{display:flex;flex-direction:column;gap:5px} +.lms-output{display:flex;align-items:center;gap:10px;border:1px solid #334956; + background:#152731;padding:9px 10px;border-radius:4px;text-align:left;width:100%} +.lms-output.active{border-color:#5cbdca;background:#1a3945} +.lms-output strong{font-size:11px;font-weight:570;flex:1} +.lms-output small{font-size:10px;color:#99b4be} +.lms-form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px} +.lms-field label{display:block;color:#9bb6bf;font-size:10px;margin-bottom:6px} +.lms-field input,.lms-field select{width:100%;max-width:100%} +.lms-native-bar{display:flex;align-items:center;justify-content:space-between; + flex-wrap:wrap;gap:8px;padding:7px 10px;margin-bottom:10px; + border:1px solid #334b57;border-radius:4px;background:#132630; + color:#b9d5de;font-size:10px} +.lms-native-bar strong{font-weight:600;color:#d3edf2;letter-spacing:.03em} +.lms-native-bar small{font-size:9px;color:#91acb6} +.lms-native-bar .lms-control-row{margin:0;gap:6px} +.lms-native-bar .lms-btn{min-height:24px;font-size:10px;padding:4px 9px} +.lms-native-bar .lms-btn:disabled{opacity:.4;cursor:not-allowed} +.lms-tip{border-left:2px solid #82b7c0;color:#a8c6cd;padding:5px 10px; + font-size:10px;margin:12px 0} +.lms-warn{border-left:2px solid #c3a06d;color:#e4c9a1;padding:5px 10px;font-size:10px} +.lms-room{width:100%;max-height:450px;display:block;background:#101e27;border-radius:5px; + border:1px solid #3c5360;touch-action:none} +.lms-room .spk{cursor:grab} +.lms-room .ref{cursor:move} +.lms-room text{pointer-events:none;font:10px "Segoe UI",sans-serif} +.lms-mini-table{width:100%;border-collapse:collapse;font-size:11px} +.lms-mini-table th{text-align:left;font-size:10px;font-weight:500;color:#99b5be} +.lms-mini-table td,.lms-mini-table th{padding:8px;border-bottom:1px solid #324752} +.lms-mini-table tr.current{background:#23404b} +@media(max-width:960px){.lms-grid{grid-template-columns:1fr}.lms-sidebar{width:138px}.lms-content{padding:12px}} +@media(max-width:640px){.lms-sidebar{width:55px;padding:10px 4px}.lms-sidebar .lms-name{font-size:0} + .lms-nav button{justify-content:center;padding:10px 0;font-size:0} + .lms-nav .lms-index{font-size:12px}.lms-sidebar-foot{display:none} + .lms-heading{padding:10px}.lms-heading h2{font-size:13px}.lms-content{padding:8px} + .lms-form-grid{grid-template-columns:1fr}} diff --git a/site/preview-v2/assets/lms-workspace.js b/site/preview-v2/assets/lms-workspace.js new file mode 100644 index 000000000..8814ea3d7 --- /dev/null +++ b/site/preview-v2/assets/lms-workspace.js @@ -0,0 +1,645 @@ +/* ArSonMix LMS: five focused pages; native offline design inspection/ACK + * only. One JUCE engine owns device identity and accepted PCM; this view + * NEVER writes audio or turns a draft into a speaker hardware Apply. + */ +(function () { +"use strict"; +const M=window.ArSonMixLmsModel, root=document.getElementById("lmsWorkspace"); +const app=document.querySelector(".app"), launch=document.getElementById("lmsOpen"); +if (!M||!root||!app||!launch||root.dataset.ready) return; +root.dataset.ready="1"; +let state=M.createSystem({ways:3,stereo:true,ports:M.demoPorts(6)}); +let page="system",selectedPort=state.ports[0],pending=null,message=""; +let dspTab="eq",selectedBand=0; +let dragging=null; +// Browser preview has NO native bridge, demo ports or pretend live ACK. +// Desktop requests actual ASIO port inventory from the sole JUCE engine. +const backend=window.__JUCE__?.backend; +const nativeConnected=!!(backend?.emitEvent&&backend?.addEventListener); +let nativeInventory=null,nativeStatus="Inspection required"; +let nativeInspectRequest="",nativeSerial=0,nativePending=null; +let validatedForRevision=-1,validatedGraph="",validatedDevice=""; +function nativeBound() { + return !!(nativeInventory?.ready && Array.isArray(nativeInventory.ports) && + state.ports.length && + state.ports.every(p=>nativeInventory.ports.some(x=>x.identity===p&&!x.occupied))); +} +function nativeAvailable() { + return nativeInventory?.ready?nativeInventory.ports.filter(x=>!x.occupied):[]; +} +function portLabel(id) { + const actual=nativeInventory?.ports?.find(x=>x.identity===id); + return actual?"OUT "+(Number(actual.callbackOrdinal)+1): + id.replace("DEMO-","D"); +} +function inspectNative() { + if(!nativeConnected)return; + nativeInspectRequest="lms-inspect-"+(++nativeSerial); + backend.emitEvent("arMixLmsInspect",{requestId:nativeInspectRequest}); +} +function proposedOutputs() { + return state.ports.filter(p=>state.routes[p]).map(port=>{ + const section=state.sections.find(s=>s.id===state.routes[port]); + const dsp=state.dsp[port]; + if(!section||!dsp)throw new Error("Incomplete speaker output draft"); + return { + outputId:port,portIdentity:port, + sourceSide:section.side==="R"?1:0,section:section.index, + gainDb:dsp.gainDb,delayMs:dsp.delayMs, + muted:dsp.muted,polarityInverted:dsp.polarity==="invert", + limiterEnabled:dsp.limiterEnabled, + limiterThresholdDb:dsp.limiterThresholdDb, + peq:(dsp.peq||[]).map(b=>({ + frequencyHz:b.frequencyHz,q:b.q,gainDb:b.gainDb,enabled:b.enabled + })) + }; + }); +} +function validateNativeDraft() { + if(!nativeConnected||!nativeBound()||!nativeInventory.outputDisarmed || + nativePending||!Object.keys(state.routes).length)return; + try { + M.validateSystem(state); + const outputs=proposedOutputs(); + const id="lms-validate-"+(++nativeSerial); + const document={ + schema:state.schema,applied:false,ways:state.ways, + stereo:state.stereo,cutoffsHz:state.cutoffsHz.slice(),outputs + }; + nativePending={requestId:id,uiRevision:state.revision, + deviceEpoch:nativeInventory.deviceEpoch,graphRevision:nativeInventory.graphRevision, + outputs,cutoffsHz:document.cutoffsHz,ackedRevision:null}; + nativeStatus="Validating muted design against native ASIO graph"; + backend.emitEvent("arMixLmsValidate",{ + schema:"arsonmix.lms.native-design-intent.v1",requestId:id, + deviceEpoch:nativeInventory.deviceEpoch, + graphRevision:nativeInventory.graphRevision, + expectedDesignRevision:nativeInventory.designRevision, + sampleRate:nativeInventory.sampleRate, + maxFrames:nativeInventory.maxFrames, + activeOutputChannels:nativeInventory.activeOutputChannels, + design:document + }); + render(); + }catch(error){nativeStatus="Rejected: "+error.message;nativePending=null;render();} +} +function sameNativeReadback(snapshot,pending) { + const actual=snapshot.validatedDesign; + if(!actual || snapshot.hardwareApplied!==false || + snapshot.deviceEpoch!==pending.deviceEpoch || + snapshot.graphRevision!==pending.graphRevision || + snapshot.designRevision!==pending.ackedRevision || + actual.ways!==state.ways || actual.stereo!==state.stereo || + JSON.stringify(actual.cutoffsHz)!==JSON.stringify(pending.cutoffsHz)) + return false; + if(!Array.isArray(actual.outputs)||actual.outputs.length!==pending.outputs.length) + return false; + // Complete native readback parity is mandatory. Reading only route/mute + // permits an old EQ/delay/polarity to be falsely advertised as validated. + // All values are bounded and numerically decoded by the JUCE intent parser. + if(snapshot.outputDisarmed!==true)return false; + const bandEqual=(x,p)=>x&&p&& + x.frequencyHz===p.frequencyHz&&x.q===p.q&& + x.gainDb===p.gainDb&&x.enabled===p.enabled; + return pending.outputs.every(p=>actual.outputs.some(x=> + x.outputId===p.outputId&&x.portIdentity===p.portIdentity&& + x.sourceSide===p.sourceSide&&x.section===p.section&&x.muted===p.muted&& + x.gainDb===p.gainDb&&x.delayMs===p.delayMs&& + x.polarityInverted===p.polarityInverted&& + x.limiterEnabled===p.limiterEnabled&& + x.limiterThresholdDb===(p.limiterThresholdDb===null?-6:p.limiterThresholdDb)&& + x.voltageModelPresent===false&& + Array.isArray(x.peq)&&x.peq.length===p.peq.length&& + p.peq.every((band,i)=>bandEqual(x.peq[i],band)))); +} +if(nativeConnected){ + backend.addEventListener("arMixLmsInspection",response=>{ + if(!response||response.schema!=="arsonmix.lms.native-inspection.v1"|| + response.requestId!==nativeInspectRequest)return; + if(!response.ready){ + if(pending?.kind==="reassign")pending=null; + nativeInventory=null; + nativeStatus="Native ASIO graph unavailable · output disconnected"; + validatedForRevision=-1; + nativePending=null; + render();return; + } + if(!Array.isArray(response.ports) || + response.ports.some(x=>typeof x.identity!=="string"|| + !Number.isInteger(x.callbackOrdinal)||typeof x.occupied!=="boolean") || + typeof response.deviceEpoch!=="string" || + typeof response.graphRevision!=="string" || + typeof response.designRevision!=="string" || + !Number.isFinite(response.sampleRate) || + !Number.isInteger(response.maxFrames)){ + nativeInventory=null;nativePending=null; + nativeStatus="Invalid native port readback";render();return; + } + if(pending?.kind==="reassign" && + (pending.deviceEpoch!==response.deviceEpoch || + pending.graphRevision!==response.graphRevision))pending=null; + nativeInventory=response; + if(nativePending?.ackedRevision!==null&&nativePending && + state.revision===nativePending.uiRevision && + sameNativeReadback(response,nativePending)){ + validatedForRevision=state.revision; + validatedGraph=response.graphRevision; + validatedDevice=response.deviceEpoch; + nativeStatus="Native validated draft · hardware NOT applied"; + nativePending=null; + }else if(nativePending?.ackedRevision!==null&&nativePending){ + nativeStatus="Native readback mismatch · draft NOT validated"; + nativePending=null; + validatedForRevision=-1; + }else if(validatedForRevision!==state.revision || + validatedGraph!==response.graphRevision || + validatedDevice!==response.deviceEpoch){ + validatedForRevision=-1; + nativeStatus=response.outputDisarmed? + "Verified ASIO ports · select and validate a muted design": + "Verified ASIO ports · mute ALL outputs before validation"; + } + render(); + }); + backend.addEventListener("arMixLmsDesignAck",ack=>{ + if(!nativePending || !ack || + ack.schema!=="arsonmix.lms.native-design-ack.v1" || + ack.requestId!==nativePending.requestId)return; + if(ack.status!=="VALIDATED_PENDING_READBACK" || ack.hardwareApplied!==false){ + nativeStatus="Native REJECTED: "+String(ack.errorCode||"INVALID_DESIGN"); + validatedForRevision=-1; + nativePending=null; + inspectNative(); + render();return; + } + nativePending.ackedRevision=ack.designRevision; + nativeStatus="Native ACK received · checking subsequent readback"; + inspectNative();render(); + }); +} +function nativeBar() { + if(!nativeConnected)return ""; + const ports=nativeAvailable(); + const canBind=nativeInventory?.ready && ports.length>0&&ports.length<=64; + const ready=nativeBound()&&nativeInventory.outputDisarmed && + Object.keys(state.routes).length>0&&!nativePending; + const verified=nativeInventory?.ready===true&& + nativeInventory.outputDisarmed===true&&nativeInventory.hardwareApplied===false&& + nativeBound()&&validatedForRevision===state.revision&& + validatedGraph===nativeInventory?.graphRevision&& + validatedDevice===nativeInventory?.deviceEpoch; + return '
'+ + ''+safe(verified?'VALIDATED DRAFT':'NATIVE INSPECTION')+ + ' · '+safe(nativeStatus)+ + ' · '+ports.length+' free ASIO pins · No speaker output authorization'+ + '
'+ + btn("Inspect ASIO","nativeInspect")+ + (canBind?btn("Use verified ports","nativePorts"):'')+ + (canBind&&Object.keys(state.routes).length? + btn("Reassign + keep DSP","nativeReassign"):'')+ + (nativeBound()?'':'')+ + '
'; +} + +const pageNames={system:"System",crossover:"Crossover",matrix:"Matrix", + processing:"Processing",alignment:"Alignment"}; +const pages=Object.keys(pageNames); +const safe=x=>String(x).replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[c])); +const number=x=>Number(x).toFixed(1); +const unit=x=>Number(x).toFixed(2); +const color=i=>["#59bfd0","#8cb7dd","#d9b77e","#88c6ae","#b5a8dc","#cb9fab"][i%6]; +function selectOptions(items,value) { + return items.map(o=>'').join(""); +} +function btn(label,act,active=false) { + return ''; +} +function stats() { + return '
'+state.ways+'Ways / source
'+ + '
'+state.sections.length+'Section signals
'+ + '
'+Object.keys(state.routes).length+'Draft patches
'+ + '
'+state.ports.length+''+(nativeBound()?"Verified ASIO ports":"Demo output ports")+'
'; +} +function overviewMap() { + return '
'+ + '
STAGE / MAIN PA
'+ + 'LEFT '+state.ways+'-WAY'+ + 'RIGHT '+state.ways+'-WAY'+ + 'LISTENER
'; +} +function systemPage() { + return '
'+ + '

Speaker system Signal flow

'+ + '
MAIN / BUSLogical source›'+ + ''+state.ways+'-Way XOVER'+state.sections.length+' sections›'+ + 'MATRIXExplicit patch›'+ + 'OUTPUT DSPPer hardware pin
'+ + '
'+stats()+ + '

Choose the number of ways in Crossover first, then route sections to outputs in Matrix. All changes remain offline drafts.

'+ + '
'+btn("Edit Crossover","go:crossover")+ + btn("Open Matrix","go:matrix")+'
'+ + '

Speaker placement Top view

'+ + overviewMap()+'
'+ + btn("Visual alignment","go:alignment")+'No measured acoustic data
'; +} +function freqX(hz) {return 24+(Math.log10(hz)-Math.log10(20))/(Math.log10(20000)-Math.log10(20))*650;} +function frequencyPage() { + // Numeric response is the exact same two cascaded Butterworth magnitude + // model as the native PreparedSpeakerSystem LR4 kernel, at assumed 48 kHz. + const freqPoints=Array.from({length:116},(_,i)=>20*Math.pow(1000,i/115)); + const dbToY=db=>Math.max(30,Math.min(196,30+(3-db)*3.75)); + const guides=[0,-6,-12,-24,-36].map(db=> + ''+ + ''+db+'').join(""); + let curves="",rows=""; + for(let i=0;i{ + const mag=M.crossoverMagnitude(state.cutoffsHz,i,hz,48000); + const db=20*Math.log10(Math.max(1e-7,mag)); + return (j?"L":"M")+freqX(hz).toFixed(2)+" "+dbToY(db).toFixed(2); + }).join(" "); + const shade=color(i); + curves+=''; + const edges=[20].concat(state.cutoffsHz,[20000]); + rows+='
'+ + ''+safe(state.sections[i].band)+''+ + safe(Math.round(edges[i])+'–'+Math.round(edges[i+1])+' Hz')+'
'; + } + const crossoverMarks=state.cutoffsHz.map(hz=> + '').join(""); + const ticks=[20,100,1000,10000,20000].map(hz=> + ''+ + (hz===20000?"20k":hz===10000?"10k":hz===1000?"1k":hz)+'').join(""); + const splits=state.cutoffsHz.map((v,i)=> + '
'+ + 'Hz
').join(""); + return '
'+ + '

Crossover frequency response LR4 · 24 dB/oct · calculated at 48 kHz

'+ + ''+ + ''+guides+ + [50,100,500,1000,5000,10000].map(hz=>'').join("")+ + crossoverMarks+curves+ticks+''+ + '

Calculated electrical LR4 magnitude. No microphone measurement, speaker response, acoustic summation or phase correction. Output remains disconnected.

'+ + '
'+ + ''+ + ''+ + ''+ + '
'+ + '

A structural change clears every matrix patch and output protection draft. Never reconnect an HF speaker automatically.

'+ + '
'+ + '

Section boundaries Linked '+(state.stereo?"L/R":"mono")+' design

'+ + rows+'
'+splits+ + '

Start with section count, then patch sections to destinations in Matrix. Split frequencies must be checked against speaker specifications and actual device sample rate.

'+ + '
'+btn("Route sections → Matrix","go:matrix")+'
'+ + '
'; +} +function matrixPage() { + const headers=state.ports.map(p=>''+safe(portLabel(p))+'').join(""); + const rows=state.sections.map(s=>''+safe(s.name)+''+ + state.ports.map(p=>'').join("")+'').join(""); + return '

Section → Output Matrix Exclusive destination · source fan-out allowed

'+ + '
'+(nativeBound()? + 'Verified native ASIO roster · output pins remain DISCONNECTED': + ''+ + 'Hardware pin identity will come from ASIO discovery; these IDs are placeholders.')+'
'+ + '
'+ + headers+''+rows+'
CROSSOVER
'+ + '

Click a crosspoint to assign/unassign that section. A destination can have only one section; several destinations may share a source. A different hardware device must be explicitly mapped later.

'+ + '
'; +} +function outputList() { + return '
'+state.ports.map(p=> + '').join("")+'
'; +} +function dspPage() { + const p=state.dsp[selectedPort]||{},section=state.sections.find(s=>s.id===state.routes[selectedPort]); + const bands=p.peq||[]; + const selector='
'+ + ["eq","level","protection"].map(id=> + '').join("")+'
'; + let editor=""; + if(dspTab==="eq"){ + const pointX=i=>24+650*i/95,yDb=db=>30+(18-Math.max(-18,Math.min(18,db)))*4.5; + const pth=Array.from({length:96},(_,i)=>{ + const hz=20*Math.pow(1000,i/95); + const db=M.peqMagnitude(bands,hz); + return (i?'L':'M')+pointX(i).toFixed(2)+' '+yDb(db).toFixed(2); + }).join(' '); + const eqRows=bands.map((b,i)=> + '').join(""); + const current=bands[selectedBand]; + editor='

Parametric EQ 8-band capacity · design only

'+ + ''+ + ''+ + [-18,-9,0,9,18].map(db=>''+ + (db>0?'+':'')+db+'').join('')+ + ''+ + [20,100,1000,10000,20000].map(hz=>''+ + (hz===20000?'20k':hz===10000?'10k':hz===1000?'1k':hz)+'').join('')+ + '

Calculated peaking EQ response at 48 kHz. No acoustic measurement or output PCM.

'+ + '
'+eqRows+'
'+ + '
'+ + ''+ + (current?btn("Remove selected","removePeq"):'')+'
'+ + (current?'
'+ + '
'+ + '
'+ + '
'+ + '
': + '

No EQ bands. Add a band to start shaping this output.

'); + }else if(dspTab==="level"){ + editor='

Gain / polarity / delay Selected destination only

'+ + '
'+ + '
'+ + '
'+ + '
'+ + '
'+ + '
'+ + '
'+ + '

Need distance-based timing? Use Alignment and copy its calculated offsets to output delay drafts.

'+ + btn("Open visual alignment","go:alignment"); + }else{ + editor='

Speaker protection NOT CALIBRATED

'+ + '
'+ + '
'+ + '
'+ + '
'+ + '

Digital dBFS is not speaker power or excursion. Native sample-peak/RMS voltage modelling runs only in isolated diagnostics; measured DAC, amplifier and driver calibration plus physical FAT are still required. This page cannot arm loudspeakers.

'; + } + return '
'+ + '

Section destinations Hardware port unavailable

'+ + outputList()+'
'+ + '

'+safe(selectedPort||"No output")+ + ' '+safe(section?.name||"Not patched")+'

'+ + selector+'
'+editor+'
'; +} +function alignPage() { + const all=M.alignment(state); + const result=all.find(r=>r.port===selectedPort); + const xSvg=x=>320+x*12,ySvg=y=>70+y*10; + const lines=all.map(r=>{ + const s=state.positions[r.port],x=xSvg(s.x),y=ySvg(s.y); + const refX=xSvg(state.listener.x),refY=ySvg(state.listener.y); + const midX=(x+refX)/2,midY=(y+refY)/2; + return ''+ + ''+unit(r.distanceM)+' m'+ + ''+ + ''+safe(r.port.replace("DEMO-","D"))+''; + }).join(""); + const sx=state.positions[selectedPort]?.x??0,sy=state.positions[selectedPort]?.y??0; + const table=all.map(r=>''+ + ''+safe(r.port)+''+unit(r.distanceM)+' m'+unit(r.additionalMs)+' ms'+ + ''+unit(state.dsp[r.port]?.delayMs??0)+' ms').join(""); + return '
'+ + '

Distance alignment Top view · metres

'+ + ''+ + ''+ + 'STAGE'+ + [100,160,220,280,340].map(y=>'').join('')+ + lines+''+ + 'REFERENCE'+ + '

Drag speakers or the reference marker. This calculates direct-path distances and arrival-time offsets, NOT phase or measured acoustic alignment.

'+ + '
'+ + ''+ + ''+table+'
OutputDistanceSuggestedDraft
'+ + '

Geometry inspector Not applied to audio

'+ + ''+ + ''+ + '
'+ + '
'+ + '
'+ + '
'+ + '
'+ + '
'+unit(result?.additionalMs||0)+' ms'+ + 'Suggested offset for '+safe(selectedPort)+'
'+ + '

Farthest speaker receives zero relative delay. Nearer speakers receive an additional delay (343 m/s assumption).

'+ + '
'+btn("Copy offsets into delay drafts","planDelay")+ + '

No geometry-only estimate compensates crossover phase, horn depth, temperature, device latency or measured impulse response. Draft changes never arm hardware or modify the JUCE callback.

'+ + '
'; +} +function reviewBox() { + if (!pending) return ""; + if(pending.kind==="reassign") { + const rows=state.ports.map(source=>'
'+ + ''+ + '
').join(""); + return '
'+ + 'Review explicit output reassignment'+ + '

'+safe(pending.description)+'

'+ + '
'+rows+'
'+ + '

Every routed, tuned or positioned output needs a unique verified port. All reassigned outputs become MUTED. Only the offline design changes; fresh native ACK and subsequent readback are still required.

'+ + '
'+btn("Confirm muted reassignment","confirmReassign")+ + btn("Cancel","cancel")+'
'; + } + return '
'+ + 'Review structural change

'+safe(pending.description)+ + '

'+btn("Confirm, clear routes","confirm")+ + btn("Cancel","cancel")+'
'; +} +function render() { + const open=!root.hidden; + if (!open) return; + root.innerHTML=''+ + '

'+pageNames[page]+ + '

'+safe(state.name)+' · '+(state.stereo?"Stereo":"Mono")+ + ' · '+state.ways+' Way · revision '+state.revision+'
'+ + '
DESIGN ONLY · OUTPUT DISCONNECTED
'+ + '
'+nativeBar()+reviewBox()+ + (message?'':'')+ + ({system:systemPage,crossover:frequencyPage,matrix:matrixPage, + processing:dspPage,alignment:alignPage}[page]())+'
'; +} +function update(next,status="Draft edited · native validation required") {state=next;message="";pending=null;validatedForRevision=-1;nativeStatus=nativeConnected?status:nativeStatus;if(!state.ports.includes(selectedPort)){selectedPort=state.ports[0]||null;selectedBand=0;}render();} +function openLms(open) { + root.hidden=!open;app.classList.toggle("lms-active",open); + launch.setAttribute("aria-pressed",String(open)); + launch.textContent=open?"Back to Mixer":"Speakers"; + if (open){render();inspectNative();} +} +launch.addEventListener("click",()=>openLms(root.hidden)); +root.addEventListener("click",event=>{ + const t=event.target.closest("button");if(!t)return; + const id=t.dataset.page; + if(id){page=id;pending=null;message="";render();return;} + const act=t.dataset.action; + if(act?.startsWith("go:")){page=act.slice(3);pending=null;render();return;} + if(act==="cancel"){pending=null;render();return;} + if(act==="nativeInspect"){inspectNative();return;} + if(act==="nativePorts"){ + const actual=nativeAvailable().map(p=>p.identity); + if(!actual.length||actual.length>64)return; + pending={description:"Replace DEMO ports with the CURRENT verified ASIO output mask? This intentionally clears all patches and DSP settings; it does NOT route or arm speakers.", + run:()=>M.withPorts(state,actual)}; + render();return; + } + if(act==="nativeValidate"){validateNativeDraft();return;} + if(act==="nativeReassign"){ + if(!nativeInventory?.ready||!nativeInventory.outputDisarmed|| + nativePending||!Object.keys(state.routes).length)return; + const ports=nativeAvailable().map(p=>p.identity); + if(!ports.length||ports.length>64)return; + pending={kind:"reassign",revision:state.revision,ports, + deviceEpoch:nativeInventory.deviceEpoch, + graphRevision:nativeInventory.graphRevision,assignments:{}, + description:"Choose exact ASIO destinations. No automatic ordinal mapping. Routing, DSP and alignment are preserved only for explicitly selected outputs."}; + message="";render();return; + } + if(act==="confirmReassign"){ + if(pending?.kind!=="reassign"||pending.revision!==state.revision|| + !nativeInventory?.ready||!nativeInventory.outputDisarmed|| + nativeInventory.deviceEpoch!==pending.deviceEpoch|| + nativeInventory.graphRevision!==pending.graphRevision|| + JSON.stringify(nativeAvailable().map(p=>p.identity))!== + JSON.stringify(pending.ports)){ + pending=null;message="ASIO device inventory changed · inspect again"; + validatedForRevision=-1;render();return; + } + try{ + const next=M.reassignVerifiedPorts(state,pending.ports,pending.assignments); + update(next,"Explicit ASIO reassignment saved as MUTED draft · native validation required"); + }catch(e){message=e.message;render();} + return; + } + if(act==="planDelay"){ + pending={description:"Copy calculated geometric delays to all output DSP DRAFTS. No audio, device, native PCM ACK, or hardware output will be changed.", + run:()=>M.withSuggestedDelays(state)}; + render();return; + } + if(act==="addPeq"){ + try{selectedBand=state.dsp[selectedPort].peq.length; + update(M.withPeqBand(state,selectedPort,selectedBand,{}));} + catch(e){message=e.message;render();} + return; + } + if(act==="removePeq"){ + try{const next=M.withoutPeqBand(state,selectedPort,selectedBand); + selectedBand=Math.max(0,selectedBand-1);update(next);} + catch(e){message=e.message;render();} + return; + } + if(t.dataset.dspTab){dspTab=t.dataset.dspTab;render();return;} + if(t.dataset.selectBand!==undefined){selectedBand=Number(t.dataset.selectBand);render();return;} + + if(act==="confirm"&&pending){const p=pending;update(p.run());return;} + if(t.dataset.routePort){ + try{update(M.withRoute(state,t.dataset.routePort,t.dataset.routeSection));} + catch(e){message=e.message;render();} + return; + } + if(t.dataset.selectPort){selectedPort=t.dataset.selectPort;selectedBand=0;render();} +}); +root.addEventListener("change",event=>{ + const t=event.target; + try { + if(t.dataset.rebindSource!==undefined){ + if(pending?.kind!=="reassign")return; + const source=t.dataset.rebindSource; + if(!state.ports.includes(source))return; + if(t.value)pending.assignments[source]=t.value; + else delete pending.assignments[source]; + message="";render();return; + } + if(t.dataset.ways!==undefined){ + const ways=Number(t.value); + if(ways!==state.ways) pending={description:"Changing the number of ways clears ALL crosspoints and resets output DSP drafts. The current mixer/audio remains untouched.",run:()=>M.withWays(state,ways)}; + render();return; + } + if(t.dataset.stereo!==undefined){ + const stereo=t.value==="1"; + if(stereo!==state.stereo)pending={description:"Changing mono/stereo layout clears ALL patches and resets output DSP drafts.",run:()=>M.withStereo(state,stereo)}; + render();return; + } + if(t.dataset.ports!==undefined){ + const n=Number(t.value); + if(n!==state.ports.length)pending={description:"Changing the demo port roster clears ALL patches. Real ASIO pins are never guessed.",run:()=>M.withPorts(state,M.demoPorts(n))}; + render();return; + } + if(t.dataset.cutoff!==undefined){update(M.withCutoff(state,Number(t.dataset.cutoff),Number(t.value)));return;} + if(t.dataset.selectPort!==undefined||t.dataset.alignPort!==undefined){selectedPort=t.value;selectedBand=0;render();return;} + if(t.dataset.peqField!==undefined){ + const field=t.dataset.peqField; + const value=field==="enabled"?t.value==="1":Number(t.value); + update(M.withPeqBand(state,selectedPort,selectedBand,{[field]:value})); + return; + } + if(t.dataset.dsp!==undefined){ + const field=t.dataset.dsp; + const v=["muted","limiterEnabled"].includes(field)?t.value==="1": + field==="limiterThresholdDb"?(t.value===""?null:Number(t.value)): + ["delayMs","gainDb"].includes(field)?Number(t.value):t.value; + update(M.withDsp(state,selectedPort,{[field]:v}));return; + } + if(t.dataset.position!==undefined){ + const pos=state.positions[selectedPort]; + update(M.withPosition(state,selectedPort, + t.dataset.position==="x"?Number(t.value):pos.x, + t.dataset.position==="y"?Number(t.value):pos.y));return; + } + if(t.dataset.listener!==undefined){ + update(M.withListener(state, + t.dataset.listener==="x"?Number(t.value):state.listener.x, + t.dataset.listener==="y"?Number(t.value):state.listener.y));return; + } + }catch(e){message=e.message;render();} +}); +function point(svg,e) { + const r=svg.getBoundingClientRect(); + return {x:(e.clientX-r.left)*640/r.width,y:(e.clientY-r.top)*380/r.height}; +} +root.addEventListener("pointerdown",e=>{ + const t=e.target.closest("[data-speaker],[data-listener-point]"); + if(!t||e.button!==0)return; + const svg=t.closest("svg");if(!svg)return; + dragging={svg,id:e.pointerId,port:t.dataset.speaker||null}; + svg.setPointerCapture(e.pointerId); + e.preventDefault(); +}); +root.addEventListener("pointerup",e=>{ + if(!dragging||dragging.id!==e.pointerId)return; + const drag=dragging;dragging=null; + const q=point(drag.svg,e),x=Math.round(((q.x-320)/12)*10)/10, + y=Math.round(((q.y-70)/10)*10)/10; + try{ + if(drag.port){selectedPort=drag.port;update(M.withPosition(state,drag.port,x,y));} + else update(M.withListener(state,x,y)); + }catch(err){message=err.message;render();} +}); +root.addEventListener("pointercancel",()=>{dragging=null;}); +window.addEventListener("keydown",e=>{ + if(e.key==="Escape"&&!root.hidden&& + !e.target.closest("input,select,textarea"))openLms(false); +}); +launch.setAttribute("aria-pressed","false"); +})(); diff --git a/site/preview-v2/assets/mixer-control-keys.css b/site/preview-v2/assets/mixer-control-keys.css index 8dd084432..72e39d90d 100644 --- a/site/preview-v2/assets/mixer-control-keys.css +++ b/site/preview-v2/assets/mixer-control-keys.css @@ -212,7 +212,7 @@ } .app .console-body .strip .mx-hw-row>button.mx-hw-key[data-hw-kind="mute"]{--mx-hw-led:255,78,90} .app .console-body .strip .mx-hw-row>button.mx-hw-key[data-hw-kind="solo"]{--mx-hw-led:255,207,68} -.app .console-body .strip .mx-hw-row>button.mx-hw-key[data-hw-kind="cue"]{--mx-hw-led:101,210,236} +.app .console-body .strip .mx-hw-row>button.mx-hw-key[data-hw-kind="pfl"]{--mx-hw-led:101,210,236} /* Occluded light escape: partial bottom + weak short sides, no neon perimeter. */ .app .console-body .strip .mx-hw-row>button.mx-hw-key::before{ content:""; diff --git a/site/preview-v2/assets/mixer-control-keys.js b/site/preview-v2/assets/mixer-control-keys.js index 4db54dfeb..50a1e5651 100644 --- a/site/preview-v2/assets/mixer-control-keys.js +++ b/site/preview-v2/assets/mixer-control-keys.js @@ -5,7 +5,7 @@ 'use strict'; const SELECTOR='.console-body .mx-hw-row>button.mx-hw-key'; const COLORS=Object.freeze({ - mute:'255,78,90',solo:'255,207,68',cue:'101,210,236' + mute:'255,78,90',solo:'255,207,68',pfl:'101,210,236' }); const records=new WeakMap(); const escapeXml=value=>String(value).replace(/[&<>"']/g,ch=>({ @@ -78,7 +78,7 @@ if(records.has(button)){if(button.dataset.hwKind!=='mute')render(button);return;} const semantic=button.dataset.hwKind; if(!Object.hasOwn(COLORS,semantic))return; - const legend=({mute:'MUTE',solo:'SOLO',cue:'PFL'})[semantic]; + const legend=({mute:'MUTE',solo:'SOLO',pfl:'PFL'})[semantic]; if(!button.hasAttribute('aria-label'))button.setAttribute('aria-label',legend); // MUTE uses lightweight DOM + CSS; no SVG, image asset, or resize redraw. if(semantic==='mute'){ diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 65baae3d3..5fd230ecc 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1474,6 +1474,85 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return "SOURCE: native prepare failed; prior audio kept"; } } + // Read-only CONTROL inspection. Rendering this inventory in WebView + // neither authorizes loudspeakers nor grants browser access to driver + // callback ordinal selection. + bool inspectLmsDeviceOffline( + armix::lms::TrustedSpeakerDeviceView& out) const { + if(independent_.active() || !attached_ || !directFence_.permitted() || + handoff_.busy() || + routeReconfiguring_.load(std::memory_order_acquire) || + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal || + deviceManager_.getCurrentAudioDeviceType()!="ASIO") + return false; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device || !device->isOpen())return false; + armix::device::JuceActivePortSnapshot pins; + armix::device::JuceActivePortSnapshot::Fault reason{}; + const auto generation=dryRoutingLab_.epoch(); + if(!armix::device::JuceActivePortSnapshot::capture( + device,generation,pins,reason))return false; + const auto rate=device->getCurrentSampleRate(); + if(!dryRoutingLab_.inspectNativeSpeakerDevice( + pins,rate,allOutputsDisarmed(),out))return false; + return deviceManager_.getCurrentAudioDevice()==device && + device->isOpen() && + rate==device->getCurrentSampleRate() && + dryRoutingLab_.matchesSessionDevice(pins); + } + + // Returns only a CONTROL-owned, already validated/disconnected draft. + // Null is the correct answer after a device or PCM revision change. + const armix::mixer::DynamicNativeSessionPublisher::SpeakerDraftReadback* + lmsDraftReadback(std::uint64_t epoch,std::uint64_t graph) const noexcept { + return dryRoutingLab_.nativeSpeakerDraftReadback(epoch,graph); + } + + // M6 CONTROL only. The outer DEVICE authority, not the WebView, proves + // that the present ASIO registration, callback mask, and ALL physical + // playback paths are disarmed before validating a loudspeaker draft. + // This is NOT hardware Apply and NEVER enables amplifier outputs. + LiveDryRoutingLab::SpeakerDraftControlResult validateLmsDesignOffline( + const armix::lms::SpeakerSystemRequest& proposed, + std::uint64_t expectedDesignRevision) { + using AckFault=armix::mixer::DynamicNativeSessionPublisher::SpeakerDraftFault; + LiveDryRoutingLab::SpeakerDraftControlResult rejected; + rejected.ack.fault=AckFault::staleDeviceOrGraph; + if(independent_.active() || !attached_ || !directFence_.permitted() || + !allOutputsDisarmed() || handoff_.busy() || + routeReconfiguring_.load(std::memory_order_acquire) || + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal || + deviceManager_.getCurrentAudioDeviceType()!="ASIO") + return rejected; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device || !device->isOpen())return rejected; + armix::device::JuceActivePortSnapshot pins; + armix::device::JuceActivePortSnapshot::Fault fault{}; + if(!armix::device::JuceActivePortSnapshot::capture( + device,proposed.deviceEpoch,pins,fault) || + !dryRoutingLab_.matchesSessionDevice(pins)) + return rejected; + const auto rate=device->getCurrentSampleRate(); + if(proposed.sampleRate!=rate || + proposed.activeOutputChannels!=pins.outputCount)return rejected; + auto result=dryRoutingLab_.acceptNativeSpeakerDraft( + proposed,pins,rate,true,expectedDesignRevision); + // Never retain a draft accepted against a transient driver setup. + if(deviceManager_.getCurrentAudioDevice()!=device || + !device->isOpen() || + rate!=device->getCurrentSampleRate() || + !allOutputsDisarmed() || + !dryRoutingLab_.matchesSessionDevice(pins)){ + dryRoutingLab_.revokeNativeSpeakerDraft(); + result.ack.validatedDraft=false; + result.ack.hardwareApplied=false; + result.ack.fault=AckFault::staleDeviceOrGraph; + } + return result; + } + // O1 physical External OUT: solely CONTROL, on the already-approved // single ASIO/ChannelId PCM callback. Hardware pin masks and labels // are read atomically with the current device lifecycle generation. diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index cc6587749..60dd77a27 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -15,6 +15,8 @@ #include "NativeTopologyEditSafety.h" #include "NativeMixerSessionDocument.h" #include "../engine/device/JuceActivePortSnapshot.h" +#include "../engine/lms/NativeSpeakerDeviceBinder.h" +#include "../engine/lms/LmsOfflineDraft.h" #include "../engine/core/RealtimeRoutePublisher.h" #include "../engine/core/RealtimeRenderPermit.h" #include "../engine/core/ProductionRenderAudit.h" @@ -2306,6 +2308,12 @@ class LiveDryRoutingLab final { draft.request=nativeAccepted_.graph.request; draft.waitingAsioInputs=waitingAsioInputs_; draft.externalOutputs=externalOutputAssignments_; + // M11: only the separately detached, muted and unassigned + // speaker DSP draft belongs in .smix, never live ASIO pins. + if(offlineSpeakerDraft_ && + !armix::lms::OfflineSpeakerDraftPolicy::valid(*offlineSpeakerDraft_)) + return "Saved LMS offline draft has invalid state"; + draft.lmsDraft=offlineSpeakerDraft_; std::vector staged; std::set hashes; juce::int64 total=0; @@ -2347,6 +2355,119 @@ class LiveDryRoutingLab final { } catch(...) {return "Native graph/VST3 state capture failed";} } + // M6 CONTROL ONLY: a browser draft NEVER supplies the trusted hardware + // mask. Build it here from a fresh JUCE snapshot and the SAME accepted + // ChannelId PCM publisher. This method does not arm any speaker. + struct SpeakerDraftControlResult final { + armix::mixer::DynamicNativeSessionPublisher::SpeakerDraftAck ack{}; + armix::lms::SpeakerBindFault bindFault=armix::lms::SpeakerBindFault::none; + }; + static std::string speakerNativePortIdentity( + const armix::device::JuceActivePortSnapshot& pins,int ordinal) { + const int physical=pins.outputPhysicalPort(ordinal); + if(physical<0||physical>=pins.outputNames.size() || + pins.outputNames[physical].isEmpty())return {}; + return pins.typeName.toStdString()+"/"+ + pins.deviceName.toStdString()+"/"+std::to_string(physical)+"/"+ + pins.outputNames[physical].toStdString(); + } + bool inspectNativeSpeakerDevice( + const armix::device::JuceActivePortSnapshot& pins, + double currentSampleRate,bool outputsDisarmed, + armix::lms::TrustedSpeakerDeviceView& out) const { + if(!channelIdPhysicalPcmActive() || !ready() || + !matchesSessionDevice(pins) || pins.typeName!="ASIO" || + pins.deviceName.isEmpty() || + !std::isfinite(currentSampleRate) || currentSampleRate<=0.) + return false; + const auto revision=nativeAccepted_.pcmRevision; + if(!nativeAccepted_.matches(nativePublisher_,pins.epoch,revision)) + return false; + const auto* accepted=nativePublisher_.acceptedRouting(pins.epoch,revision); + if(!accepted || !accepted->main.value)return false; + armix::lms::TrustedSpeakerDeviceView candidate; + candidate.deviceEpoch=pins.epoch; + candidate.graphRevision=revision; + candidate.mainChannelId=accepted->main.value; + candidate.backend=pins.typeName.toStdString(); + candidate.deviceIdentity=pins.typeName.toStdString()+"/"+ + pins.deviceName.toStdString(); + candidate.sampleRate=currentSampleRate; + candidate.callbackOutputs=pins.outputCount; + candidate.maxFrames=nativeAccepted_.graph.request.maxFrames; + const auto& hw=nativeAccepted_.hardware; + candidate.mainL=hw.mainL;candidate.mainR=hw.mainR; + candidate.monitorL=hw.monitorEnabled?hw.monitorL:-1; + candidate.monitorR=hw.monitorEnabled?hw.monitorR:-1; + candidate.acceptedPcm=true; + candidate.exactDeviceMask=true; // matchesSessionDevice above + candidate.allOutputsDisarmed=outputsDisarmed; + for(int ordinal=0;ordinalchannels){ + const auto [left,right]=nativePublisher_.externalOutput( + pins.epoch,revision,channel.id); + if(left>=0)candidate.otherOccupiedOrdinals.push_back(left); + if(right>=0)candidate.otherOccupiedOrdinals.push_back(right); + } + out=std::move(candidate); + return true; + } + SpeakerDraftControlResult acceptNativeSpeakerDraft( + const armix::lms::SpeakerSystemRequest& draft, + const armix::device::JuceActivePortSnapshot& pins, + double currentSampleRate,bool verifiedOutputsDisarmed, + std::uint64_t expectedDesignRevision) { + SpeakerDraftControlResult reply; + using Fault=armix::mixer::DynamicNativeSessionPublisher::SpeakerDraftFault; + reply.ack.fault=Fault::staleDeviceOrGraph; + armix::lms::TrustedSpeakerDeviceView actual; + if(!verifiedOutputsDisarmed || + !inspectNativeSpeakerDevice(pins,currentSampleRate, + verifiedOutputsDisarmed,actual) || + actual.graphRevision!=draft.graphRevision || + actual.deviceEpoch!=draft.deviceEpoch || + actual.sampleRate!=draft.sampleRate) + return reply; + armix::lms::SpeakerBoundDraft bound; + const auto boundResult=armix::lms::NativeSpeakerDeviceBinder::bind( + draft,actual,actual.mainChannelId,bound); + reply.bindFault=boundResult.fault; + if(!boundResult.ok()){ + reply.ack.fault=Fault::invalidReservation; + return reply; + } + // Preflight session detachment BEFORE native ACK: a design that + // cannot safely survive cold-open must not report a full acceptance. + armix::lms::OfflineSpeakerDraft detached; + if(!armix::lms::OfflineSpeakerDraftPolicy::detach( + bound.verifiedRequest,detached)) { + reply.ack.fault=Fault::invalidDsp; + return reply; + } + reply.ack=nativePublisher_.acceptSpeakerDraft( + bound.verifiedRequest,bound.verifiedInventory, + armix::mixer::ChannelId{actual.mainChannelId}, + expectedDesignRevision); + if(reply.ack.ok())offlineSpeakerDraft_=std::move(detached); + return reply; + } + const armix::mixer::DynamicNativeSessionPublisher::SpeakerDraftReadback* + nativeSpeakerDraftReadback(std::uint64_t deviceEpoch, + std::uint64_t graphRevision) const noexcept { + if(!channelIdPhysicalPcmActive() || + nativeAccepted_.pcmRevision!=graphRevision || + deviceEpoch!=epoch())return nullptr; + return nativePublisher_.speakerDraftReadback(deviceEpoch,graphRevision); + } + + void revokeNativeSpeakerDraft() noexcept { + nativePublisher_.revokeSpeakerDraft(); + } + // O1 CONTROL: true ASIO physical pin identity -> packed callback ordinal. // No OUT reconfiguration is allowed to steal MAIN or MONITOR. Every edit // preserves the existing internal WIRE graph and FX lease. @@ -2508,6 +2629,11 @@ class LiveDryRoutingLab final { using namespace armix::mixer; if(!outputsDisarmed || (!replaceActive && channelIdPhysicalPcmActive()) || !bank) return "Restore requires a muted device"; + // Even direct native callers cannot smuggle a physical speaker + // binding into the session restoration path. + if(document.lmsDraft && + !armix::lms::OfflineSpeakerDraftPolicy::valid(*document.lmsDraft)) + return "Invalid disconnected LMS draft"; const auto generation=pins.epoch; if(!matchesSessionDevice(pins) || bank->epoch()!=generation || document.request.physicalInputs!=pins.inputs.enabledCount || @@ -2562,6 +2688,9 @@ class LiveDryRoutingLab final { if(!externalOutputVerified_.empty()) externalOutputEpoch_=generation; } + // After the graph is accepted this stays only on CONTROL. + // No speaker DSP or hardware patch is published from .smix. + offlineSpeakerDraft_=std::move(document.lmsDraft); nativeAccepted_.fxOwners=std::move(bank); nativeAccepted_.deviceEpoch=generation; nativeAccepted_.pcmRevision=published.revision; @@ -3135,6 +3264,7 @@ class LiveDryRoutingLab final { outputSlices[c]=outputs[c]?outputs[c]+offset:nullptr; armix::mixer::RenderLevels level; bool processed=false; + std::uint64_t renderedPcmRevision=0; if(channelIdRender) { // The current M4 import is at most 10+4+MAIN+MONITOR. // Meter sources are the ACTUAL ChannelId PCM POST-fader @@ -3162,7 +3292,7 @@ class LiveDryRoutingLab final { std::span( slice.data(),playerPcm.size()), meterOnly?nullptr:outputSlices.data(), - meterOnly?0:outputCount); + meterOnly?0:outputCount,{},&renderedPcmRevision); if(processed) { for(std::size_t ch=0;ch waitingAsioInputs_; std::vector externalOutputAssignments_; + std::optional offlineSpeakerDraft_; // CONTROL only; no ASIO ACL std::vector externalOutputVerified_; // per amplifier, CONTROL only std::uint64_t externalOutputEpoch_=0; // CONTROL only, never callback state // Four 9-bit callback indices (0 means absent) and the prepared quantum. diff --git a/src/Main.cpp b/src/Main.cpp index 1d1c5c6ab..7ae7c8919 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -9,6 +9,7 @@ #include "../integration/ApprovedNativeRuntimeSnapshot.h" #include "../integration/ApprovedNativeControlIntent.h" #include "LiveAudioEngine.h" +#include "NativeLmsWebIntent.h" #include "NativeSessionToken.h" #include "ArSonMixStartupSplash.h" #include "ArSonWindowChrome.h" @@ -304,6 +305,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr .withEventListener ("arMixFxParameterHotkeyInspect", [this] (juce::var args) { inspectFxParameterHotkey(args); }) + .withEventListener ("arMixLmsInspect", [this] (juce::var args) { + handleNativeLmsInspect(args); + }) + .withEventListener ("arMixLmsValidate", [this] (juce::var args) { + handleNativeLmsValidate(args); + }) .withEventListener ("arMixConsoleSubscribe", [this] (juce::var) { // G0 real-device native producer, NEVER a synthetic ChannelId callback. consoleSubscribed_ = true; @@ -1774,6 +1781,75 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr "arMixConsoleSnapshot", approvedNativeSnapshot()); } + // M6 CONTROL-only LMS bridge: the GUI may INSPECT an actual ASIO mask, + // but it can never claim ASIO ownership or produce PCM from JavaScript. + void handleNativeLmsInspect(const juce::var& args) { + const auto requestId=args.getProperty("requestId","").toString(); + if(requestId.isEmpty()||requestId.length()>120)return; + armix::lms::TrustedSpeakerDeviceView inspected; + const bool ready=engine_.inspectLmsDeviceOffline(inspected); + juce::var response; + if(ready) { + const auto* read=engine_.lmsDraftReadback( + inspected.deviceEpoch,inspected.graphRevision); + response=armix::lms::web::inspection(inspected,read); + } else { + auto rejected=std::make_unique(); + rejected->setProperty("schema","arsonmix.lms.native-inspection.v1"); + rejected->setProperty("ready",false); + rejected->setProperty("hardwareApplied",false); + rejected->setProperty("errorCode","NEEDS_VERIFIED_ASIO_CHANNEL_ID"); + response=juce::var(rejected.release()); + } + if(auto* obj=response.getDynamicObject()) + obj->setProperty("requestId",requestId); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible( + "arMixLmsInspection",std::move(response)); + } + + void handleNativeLmsValidate(const juce::var& args) { + const auto id=args.getProperty("requestId","").toString(); + if(id.isEmpty()||id.length()>120)return; + auto reply=std::make_unique(); + reply->setProperty("schema","arsonmix.lms.native-design-ack.v1"); + reply->setProperty("requestId",id); + reply->setProperty("status","REJECTED"); + reply->setProperty("hardwareApplied",false); + reply->setProperty("validatedDraft",false); + reply->setProperty("errorCode","INVALID_OFFLINE_LMS_INTENT"); + armix::lms::web::OfflineIntent intent; + if(armix::lms::web::decode(args,intent)) { + // Only the real engine may collect device masks, physical MAIN + // identity and all-output disarm proof. No fake inspection + // object supplied by the browser is passed to this method. + const auto result=engine_.validateLmsDesignOffline( + intent.proposed,intent.expectedDesignRevision); + const auto& ack=result.ack; + reply->setProperty("deviceEpoch", + juce::String(std::to_string(ack.deviceEpoch))); + reply->setProperty("graphRevision", + juce::String(std::to_string(ack.graphRevision))); + reply->setProperty("designRevision", + juce::String(std::to_string(ack.designRevision))); + reply->setProperty("scratchBytes", + static_cast(ack.preparedScratchBytes)); + reply->setProperty("status", + ack.ok()?"VALIDATED_PENDING_READBACK":"REJECTED"); + const auto error=juce::String("NATIVE_LMS_")+ + juce::String(static_cast(ack.fault))+ + "_PIN_"+juce::String(static_cast(result.bindFault))+ + "_RES_"+juce::String(static_cast(ack.reservationFault))+ + "_DSP_"+juce::String(static_cast(ack.planFault)); + reply->setProperty("errorCode",ack.ok()?juce::String("NONE"):error); + } + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible( + "arMixLmsDesignAck",juce::var(reply.release())); + // No speculative snapshot: the GUI must request a later native + // inspection and compare designRevision + accepted graph identity. + } + // UI-only native transaction. No PCM mutation; never arm an output. void handleNativeChannelIdentitySet(const juce::var& request) { diff --git a/src/NativeLmsWebIntent.h b/src/NativeLmsWebIntent.h new file mode 100644 index 000000000..39fbe5674 --- /dev/null +++ b/src/NativeLmsWebIntent.h @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +// Browser -> CONTROL only. Translate a bounded offline speaker DESIGN, +// never device identity, PCM ownership, hardware arm, or protection authority. +#include "../engine/lms/NativeSpeakerDeviceBinder.h" +#include "../engine/core/DynamicNativeSessionPublisher.h" +#include +#include +#include +#include +#include +#include +#include + +namespace armix::lms::web { +struct OfflineIntent final { + std::string requestId; + std::uint64_t expectedDesignRevision=0; + SpeakerSystemRequest proposed; +}; +inline bool uint64Token(const juce::var& token,std::uint64_t& result, + bool allowZero=true) noexcept { + if(!token.isString())return false; + const auto str=token.toString(); + if(str.isEmpty()||str.length()>20||(str.length()>1&&str[0]=='0')) + return false; + std::uint64_t value=0; + for(int i=0;i'9')return false; + const auto digit=static_cast(ch-'0'); + if(value>(std::numeric_limits::max()-digit)/10) + return false; + value=value*10+digit; + } + if(!allowZero&&!value)return false; + result=value; + return true; +} +inline bool finiteNumber(const juce::var& value,double& out) noexcept { + if(!value.isInt() && !value.isInt64() && !value.isDouble())return false; + out=static_cast(value); + return std::isfinite(out); +} +inline bool integerNumber(const juce::var& value,int& out) noexcept { + double amount=0.; + if(!finiteNumber(value,amount)|| + amount::min() || + amount>std::numeric_limits::max() || + std::trunc(amount)!=amount)return false; + out=static_cast(amount);return true; +} +inline bool boolean(const juce::var& source,bool& value) noexcept { + if(!source.isBool())return false; + value=static_cast(source);return true; +} +inline bool decode(const juce::var& args,OfflineIntent& out) { + if(!args.isObject() || + args.getProperty("schema","").toString()!="arsonmix.lms.native-design-intent.v1") + return false; + const auto requestId=args.getProperty("requestId",{}); + if(!requestId.isString() || requestId.toString().isEmpty() || + requestId.toString().length()>120)return false; + // Log-safe fixed-size request token (no whitespace, markup or control). + const auto token=requestId.toString(); + for(int i=0;i0x7e)return false; + } + OfflineIntent candidate; + candidate.requestId=requestId.toString().toStdString(); + if(!uint64Token(args.getProperty("deviceEpoch",{}), + candidate.proposed.deviceEpoch,false) || + !uint64Token(args.getProperty("graphRevision",{}), + candidate.proposed.graphRevision,false) || + !uint64Token(args.getProperty("expectedDesignRevision",{}), + candidate.expectedDesignRevision,true)) + return false; + const auto p=args.getProperty("design",{}); + if(!p.isObject()||p.getProperty("schema","").toString()!="arsonmix.lms.draft.v1" || + p.getProperty("applied",{})!=juce::var(false) || + !integerNumber(p.getProperty("ways",{}),candidate.proposed.ways) || + candidate.proposed.ways<1||candidate.proposed.ways>16 || + !boolean(p.getProperty("stereo",{}),candidate.proposed.stereo) || + !finiteNumber(args.getProperty("sampleRate",{}), + candidate.proposed.sampleRate) || + !integerNumber(args.getProperty("maxFrames",{}), + candidate.proposed.maxFrames) || + !integerNumber(args.getProperty("activeOutputChannels",{}), + candidate.proposed.activeOutputChannels)) + return false; + if(candidate.proposed.maxFrames<1||candidate.proposed.maxFrames>8192 || + candidate.proposed.activeOutputChannels<2|| + candidate.proposed.activeOutputChannels>256)return false; + const auto cutoffVar=p.getProperty("cutoffsHz",{}); + const auto* cutoffs=cutoffVar.getArray(); + if(!cutoffs || cutoffs->size()!=candidate.proposed.ways-1)return false; + for(const auto& c:*cutoffs){ + double value=0.; + if(!finiteNumber(c,value))return false; + candidate.proposed.crossoverHz.push_back(value); + } + const auto outputs=p.getProperty("outputs",{}); + const auto* rows=outputs.getArray(); + if(!rows||rows->size()>64)return false; + std::unordered_set seenIds,seenPorts; + for(const auto& raw:*rows) { + if(!raw.isObject())return false; + OutputPatch row; + const auto id=raw.getProperty("outputId",{}); + const auto pin=raw.getProperty("portIdentity",{}); + if(!id.isString()||!pin.isString()|| + id.toString().isEmpty()||pin.toString().isEmpty()|| + id.toString().length()>128||pin.toString().length()>1024) + return false; + row.outputId=id.toString().toStdString(); + row.portIdentity=pin.toString().toStdString(); + if(!seenIds.insert(row.outputId).second|| + !seenPorts.insert(row.portIdentity).second)return false; + if(!integerNumber(raw.getProperty("sourceSide",{}),row.sourceSide) || + !integerNumber(raw.getProperty("section",{}),row.section) || + !finiteNumber(raw.getProperty("gainDb",{}),row.gainDb) || + !finiteNumber(raw.getProperty("delayMs",{}),row.delayMs) || + !boolean(raw.getProperty("muted",{}),row.mute) || + !boolean(raw.getProperty("polarityInverted",{}),row.polarityInverted)) + return false; + // These UI booleans are inert design observations only. They are + // NEVER interpreted as calibrated speaker protection authorization. + bool intendsLimiter=false; + if(!boolean(raw.getProperty("limiterEnabled",{}),intendsLimiter)) + return false; + row.limiterEnabled=intendsLimiter; + row.confirmedSpeakerProfile=false; + // Optional electronic-only DIGITAL ceiling is a fully revisioned + // draft value, never proof of voltage / RMS / transducer protection. + // Null means the explicit -6 dBFS default, not an inferred profile. + const auto ceiling=raw.getProperty("limiterThresholdDb",{}); + if(ceiling.isVoid())row.ceilingDbfs=-6.; + else if(!finiteNumber(ceiling,row.ceilingDbfs) || + row.ceilingDbfs< -60. || row.ceilingDbfs>0.)return false; + // A browser cannot furnish trusted manufacturer/measurement models. + if(raw.getDynamicObject()->hasProperty(juce::Identifier("voltageModel"))) + return false; + const auto eq=raw.getProperty("peq",{}); + const auto* bands=eq.getArray(); + if(!bands||bands->size()>8)return false; + for(const auto& v:*bands){ + if(!v.isObject())return false; + ParametricBand band; + if(!finiteNumber(v.getProperty("frequencyHz",{}),band.frequencyHz) || + !finiteNumber(v.getProperty("q",{}),band.q) || + !finiteNumber(v.getProperty("gainDb",{}),band.gainDb) || + !boolean(v.getProperty("enabled",{}),band.enabled)) + return false; + row.peq.push_back(band); + } + candidate.proposed.outputs.push_back(std::move(row)); + } + out=std::move(candidate); + return true; +} +inline juce::var inspection(const TrustedSpeakerDeviceView& device, + const armix::mixer::DynamicNativeSessionPublisher:: + SpeakerDraftReadback* readback) { + auto root=std::make_unique(); + root->setProperty("schema","arsonmix.lms.native-inspection.v1"); + root->setProperty("ready",true); + root->setProperty("deviceEpoch",juce::String(std::to_string(device.deviceEpoch))); + root->setProperty("graphRevision",juce::String(std::to_string(device.graphRevision))); + root->setProperty("mainChannelId",juce::String(std::to_string(device.mainChannelId))); + root->setProperty("sampleRate",device.sampleRate); + root->setProperty("maxFrames",device.maxFrames); + root->setProperty("activeOutputChannels",device.callbackOutputs); + root->setProperty("outputDisarmed",device.allOutputsDisarmed); + root->setProperty("hardwareApplied",false); + root->setProperty("designRevision",juce::String(std::to_string( + readback?readback->designRevision:0))); + juce::Array ports; + for(const auto& pin:device.actualEnabledPorts) { + auto row=std::make_unique(); + row->setProperty("identity",juce::String::fromUTF8(pin.identity.c_str())); + row->setProperty("callbackOrdinal",pin.callbackOrdinal); + const bool occupied=pin.callbackOrdinal==device.mainL || + pin.callbackOrdinal==device.mainR || + pin.callbackOrdinal==device.monitorL || + pin.callbackOrdinal==device.monitorR || + std::find(device.otherOccupiedOrdinals.begin(), + device.otherOccupiedOrdinals.end(), + pin.callbackOrdinal)!=device.otherOccupiedOrdinals.end(); + row->setProperty("occupied",occupied); + ports.add(juce::var(row.release())); + } + root->setProperty("ports",juce::var(ports)); + if(readback){ + auto design=std::make_unique(); + design->setProperty("ways",readback->design.ways); + design->setProperty("stereo",readback->design.stereo); + juce::Array cuts; + for(double hz:readback->design.crossoverHz)cuts.add(hz); + design->setProperty("cutoffsHz",juce::var(cuts)); + juce::Array routes; + for(const auto& p:readback->design.outputs){ + auto route=std::make_unique(); + route->setProperty("outputId",juce::String::fromUTF8(p.outputId.c_str())); + route->setProperty("portIdentity",juce::String::fromUTF8(p.portIdentity.c_str())); + route->setProperty("sourceSide",p.sourceSide); + route->setProperty("section",p.section); + route->setProperty("muted",p.mute); + route->setProperty("gainDb",p.gainDb); + route->setProperty("delayMs",p.delayMs); + route->setProperty("polarityInverted",p.polarityInverted); + route->setProperty("limiterEnabled",p.limiterEnabled); + route->setProperty("limiterThresholdDb",p.ceilingDbfs); + route->setProperty("voltageModelPresent",p.voltageModel.has_value()); + // Return exactly the bounded parameter values that were prepared + // by native DSP. The UI verifies these BEFORE claiming VALIDATED. + juce::Array bands; + for(const auto& b:p.peq){ + auto band=std::make_unique(); + band->setProperty("frequencyHz",b.frequencyHz); + band->setProperty("q",b.q); + band->setProperty("gainDb",b.gainDb); + band->setProperty("enabled",b.enabled); + bands.add(juce::var(band.release())); + } + route->setProperty("peq",juce::var(bands)); + routes.add(juce::var(route.release())); + } + design->setProperty("outputs",juce::var(routes)); + root->setProperty("validatedDesign",juce::var(design.release())); + } + return juce::var(root.release()); +} +} // namespace armix::lms::web diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index dd3492675..963e515c6 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -2,6 +2,7 @@ #pragma once #include #include +#include "../engine/lms/LmsOfflineDraft.h" #include "../engine/core/UnifiedLegacyProductionAdmission.h" #include "NativeShowStore.h" #include "NativeHotkeyRegistry.h" @@ -72,6 +73,9 @@ struct MixerSessionDocument final { // Logical-only per-slot bypass intentions; no fabricated FX processor // state or fake vendor SHA. Physical sessions keep existing inserts. std::vector plannedSlotBypassed; + // Device-INDEPENDENT LMS DSP design, optional legacy-v1 extension. + // NO ASIO pin, device epoch, calibration authority or ARM bit is stored. + std::optional lmsDraft; // Session-specific global shortcuts; app-wide keys live in native settings. std::vector hotkeys; float masterGain=1.f; @@ -461,13 +465,125 @@ class Codec final { return parseDecimal(get(v,"main"),ids.main.value) && parseDecimal(get(v,"monitor"),ids.monitor.value,true); } + + // LMS-only strict whitelist. Unlike unknown ordinary v1 session fields, + // a speaker-related key cannot silently become physical authority during + // a future migration or typo'd session-import workflow. + static bool strictKeys(const juce::var& item, + std::initializer_list allowed) { + const auto* object=item.getDynamicObject(); + if(!object)return false; + const auto& properties=object->getProperties(); + for(int i=0;i cutoffs,outputs; + for(const auto hz:d.crossoverHz)cutoffs.add(hz); + set(root,"crossoverHz",juce::var(cutoffs)); + for(const auto& p:d.outputs) { + auto out=object(); + set(out,"outputId",juce::String::fromUTF8(p.outputId.c_str())); + set(out,"sourceSide",p.sourceSide); + set(out,"section",p.section); + set(out,"gainDb",p.gainDb); + set(out,"delayMs",p.delayMs); + set(out,"polarityInverted",p.polarityInverted); + set(out,"limiterEnabled",p.limiterEnabled); + set(out,"ceilingDbfs",p.ceilingDbfs); + juce::Array bands; + for(const auto& eq:p.peq) { + auto band=object(); + set(band,"frequencyHz",eq.frequencyHz); + set(band,"q",eq.q); + set(band,"gainDb",eq.gainDb); + set(band,"enabled",eq.enabled); + bands.add(band); + } + set(out,"peq",juce::var(bands)); + outputs.add(out); + } + set(root,"outputs",juce::var(outputs)); + return root; + } + static bool readOfflineSpeaker(const juce::var& v, + armix::lms::OfflineSpeakerDraft& accepted) { + using armix::lms::OfflineSpeakerDraft; + using armix::lms::OfflineSpeakerDraftPolicy; + if(!strictKeys(v,{"schema","version","designRateHz","ways", + "stereo","crossoverHz","outputs"})|| + get(v,"schema").toString()!="arsonmix.lms.offline-draft.v1") + return false; + OfflineSpeakerDraft next; + if(!integral(get(v,"version"),next.version,1,1)|| + !real(get(v,"designRateHz"),next.designRateHz,8000.,384000.)|| + !integral(get(v,"ways"),next.ways,1,16)|| + !strictBool(get(v,"stereo"),next.stereo))return false; + const auto cutoffs=get(v,"crossoverHz"),outputs=get(v,"outputs"); + const auto* hz=cutoffs.getArray(),*list=outputs.getArray(); + if(!hz||!list||hz->size()!=next.ways-1||list->size()>256)return false; + for(const auto& item:*hz) { + double value=0.; + if(!real(item,value,20.,384000.))return false; + next.crossoverHz.push_back(value); + } + for(const auto& item:*list) { + if(!strictKeys(item,{"outputId","sourceSide","section", + "gainDb","delayMs","polarityInverted","limiterEnabled", + "ceilingDbfs","peq"}))return false; + armix::lms::OutputPatch p; + juce::String outputId; + if(!textField(get(item,"outputId"),outputId,96)|| + !integral(get(item,"sourceSide"),p.sourceSide,0,1)|| + !integral(get(item,"section"),p.section,0,15)|| + !real(get(item,"gainDb"),p.gainDb,-60.,6.)|| + !real(get(item,"delayMs"),p.delayMs,0.,500.)|| + !real(get(item,"ceilingDbfs"),p.ceilingDbfs,-60.,0.)|| + !strictBool(get(item,"polarityInverted"),p.polarityInverted)|| + !strictBool(get(item,"limiterEnabled"),p.limiterEnabled)) + return false; + p.outputId=outputId.toStdString(); + const auto eq=get(item,"peq"); + const auto* bands=eq.getArray(); + if(!bands||bands->size()>8)return false; + for(const auto& b:*bands) { + if(!strictKeys(b,{"frequencyHz","q","gainDb","enabled"})) + return false; + armix::lms::ParametricBand row; + if(!real(get(b,"frequencyHz"),row.frequencyHz,20.,384000.)|| + !real(get(b,"q"),row.q,.1,18.)|| + !real(get(b,"gainDb"),row.gainDb,-18.,18.)|| + !strictBool(get(b,"enabled"),row.enabled))return false; + p.peq.push_back(row); + } + // Patch ctor defaults to mute=true with portIdentity blank. + // No saved hardware data is ever accepted by this decoder. + next.outputs.push_back(std::move(p)); + } + if(!OfflineSpeakerDraftPolicy::valid(next))return false; + accepted=std::move(next); + return true; + } public: static juce::String encode(const MixerSessionDocument& d) { + if(d.lmsDraft && !armix::lms::OfflineSpeakerDraftPolicy::valid(*d.lmsDraft)) + return {}; auto root=object(); set(root,"schema","arsonmix.mixer-session.v1"); if(d.logicalOnly)set(root,"logicalOnly",true); set(root,"id",d.id); set(root,"acceptedRevision",decimal(d.acceptedRevision)); + if(d.lmsDraft)set(root,"lmsDraft",offlineSpeaker(*d.lmsDraft)); set(root,"savedMs",decimal(static_cast(d.savedMs))); if(d.resumeMain.has_value())set(root,"resumeMain",*d.resumeMain); set(root,"legacyIds",ids(d.legacyIds)); @@ -621,6 +737,11 @@ class Codec final { if(!parseDecimal(get(root,"savedMs"),ms)||ms>static_cast( std::numeric_limits::max()))return false; doc.savedMs=static_cast(ms); + if(root.getDynamicObject()->hasProperty("lmsDraft")) { + armix::lms::OfflineSpeakerDraft offline; + if(!readOfflineSpeaker(get(root,"lmsDraft"),offline))return false; + doc.lmsDraft=std::move(offline); + } const auto binding=get(root,"binding"); if(!textField(get(binding,"backend"),doc.binding.backend,128,doc.logicalOnly)|| !textField(get(binding,"capture"),doc.binding.capture,256,true)|| diff --git a/tests/approved_css_original_bundle_fixture.py b/tests/approved_css_original_bundle_fixture.py index 783bf09d2..de2a35f09 100644 --- a/tests/approved_css_original_bundle_fixture.py +++ b/tests/approved_css_original_bundle_fixture.py @@ -15,6 +15,7 @@ sys.path.insert(0, str(ROOT / "scripts")) from compile_approved_css import LINK from compose_operator_ux import apply_operator_ux +from compose_lms import apply_lms from approved_fx_rack_interaction import apply_fx_rack_interaction ORIGINAL_LINK = re.compile( r'' @@ -44,5 +45,6 @@ def restore_original_css_bundle(bundle: Path) -> None: shutil.copyfile(ROOT / "site" / owner / "assets" / name, assets / name) # The shipped DOM already contains the same composition. Reapply it # only to reconstruct the CSS owner bytes, using its original HTML input. - apply_operator_ux(apply_fx_rack_interaction(source_html, assets), assets) + composed=apply_operator_ux(apply_fx_rack_interaction(source_html, assets), assets) + apply_lms(composed, assets) # same new owner bytes before CSS optimization index.write_text(original_html, encoding="utf-8") diff --git a/tests/css_v26_restore.py b/tests/css_v26_restore.py index 539542fef..c29ea89ab 100644 --- a/tests/css_v26_restore.py +++ b/tests/css_v26_restore.py @@ -32,7 +32,26 @@ def inline_css(text): assert len(blocks)==3 and blocks[0].group(1)==blocks[1].group(1)=="" return blocks[-1].group(1) +def historical_v26_owner(modern,record): + """Reconstruct the immutable V26 owner after the one audited PFL fix. + + The shipping hardware key has data-hw-kind="pfl"; V26's historic owner + used "cue" for the LED selector. Keep the V26 ledger byte-exact rather + than silently rewriting an old milestone fingerprint or allowing arbitrary + CSS changes. Only this single selector substitution is admissible. + """ + if meta(modern)==record["current"]: + return modern + live='.app .console-body .strip .mx-hw-row>button.mx-hw-key[data-hw-kind="pfl"]{--mx-hw-led:101,210,236}' + historical=live.replace('data-hw-kind="pfl"','data-hw-kind="cue"') + if modern.count(live)!=1 or modern.count(historical)!=0: + raise AssertionError("V26 owner source changed unexpectedly") + original=modern.replace(live,historical,1) + assert meta(original)==record["current"],"Unapproved CSS drift outside exact PFL selector" + return original + def restore_owner(modern,record): + modern=historical_v26_owner(modern,record) assert meta(modern)==record["current"],"V26 owner source changed unexpectedly" old=modern for edit in sorted(record["edits"],key=lambda e:e["offset"]): diff --git a/tests/dlms_ci_scope_contract.test.cjs b/tests/dlms_ci_scope_contract.test.cjs new file mode 100644 index 000000000..1715348a0 --- /dev/null +++ b/tests/dlms_ci_scope_contract.test.cjs @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: AGPL-3.0-only +"use strict"; +const test=require("node:test"); +const assert=require("node:assert/strict"); +const fs=require("node:fs"); +const path=require("node:path"); +const root=path.resolve(__dirname,".."); +const read=p=>fs.readFileSync(path.join(root,p),"utf8"); +test("DLMS speaker fast CI compiles only speaker DSP and runs only speaker UX",()=>{ + const yaml=read(".github/workflows/dlms-fast.yml"); + const cxx=[...yaml.matchAll(/lms_[a-z_]+_test/g)].map(x=>x[0]); + assert.ok(cxx.length>=7); + assert.match(yaml,/engine\/lms\/\*\*/); + assert.match(yaml,/lms_system_model\.test\.cjs/); + assert.match(yaml,/lms_native_bridge\.test\.cjs/); + assert.match(yaml,/g\+\+ -std=c\+\+20.*-Werror/); + assert.doesNotMatch(yaml,/harmony_dsp_test|harmony_pitch_synchronous_test|sonku_spatial_core_test|VocalThrowProcessor/); + assert.doesNotMatch(yaml,/setup-python|playwright install|cmake --build/); +}); +test("vocal-harmony DSP gate no longer runs for generic CMake or DLMS changes",()=>{ + const yaml=read(".github/workflows/harmony-fast-dsp.yml"); + assert.doesNotMatch(yaml,/^\s+- 'CMakeLists\.txt'\s*$/m); + assert.match(yaml,/engine\/builtin_fx\/Harmony\*\.h/); + assert.match(yaml,/tests\/harmony\*\.cpp/); +}); diff --git a/tests/harmony_dsp_test.cpp b/tests/harmony_dsp_test.cpp index ee6a1ddae..88ec366bd 100644 --- a/tests/harmony_dsp_test.cpp +++ b/tests/harmony_dsp_test.cpp @@ -99,6 +99,18 @@ static void testLeadTune(){ auto mono=leadFixture(rate,220.,-35.f,0.f); mono.right=mono.left; const auto on=tune(mono,rate,true); + if(on.left!=on.right){ + std::size_t different=0,first=on.left.size(); + float maximum=0.f; + for(std::size_t i=0;i0.f){++different;first=std::min(first,i); + maximum=std::max(maximum,delta);} + } + std::cerr<<"mono-lead PCM mismatch rate="< +#include +#include +using namespace armix::lms; +using namespace armix::lms::web; +int main(){ + const auto valid=juce::JSON::parse(R"JSON({ + "schema":"arsonmix.lms.native-design-intent.v1", + "requestId":"lms-validate-4", + "deviceEpoch":"21","graphRevision":"42", + "expectedDesignRevision":"0", + "sampleRate":48000,"maxFrames":256,"activeOutputChannels":8, + "design":{"schema":"arsonmix.lms.draft.v1","applied":false, + "ways":2,"stereo":true,"cutoffsHz":[1400], + "outputs":[{"outputId":"HF-L","portIdentity":"ASIO/driver/4/OUT 5", + "sourceSide":0,"section":1,"gainDb":-5.5,"delayMs":0.34, + "muted":true,"polarityInverted":true,"limiterEnabled":false, + "peq":[{"frequencyHz":1000,"q":1.5,"gainDb":2.3,"enabled":true}]}]}} + )JSON"); + OfflineIntent accepted; + assert(decode(valid,accepted)); + assert(accepted.requestId=="lms-validate-4"); + assert(accepted.proposed.deviceEpoch==21); + assert(accepted.proposed.graphRevision==42); + assert(accepted.proposed.activeOutputChannels==8); + assert(accepted.proposed.outputs.size()==1); + assert(accepted.proposed.outputs[0].polarityInverted); + assert(accepted.proposed.outputs[0].mute); + assert(accepted.proposed.outputs[0].ceilingDbfs==-6.); + assert(!accepted.proposed.outputs[0].voltageModel.has_value()); + assert(!accepted.proposed.outputs[0].confirmedSpeakerProfile); + assert(accepted.proposed.outputs[0].peq.size()==1); + assert(accepted.proposed.outputs[0].peq[0].enabled); + auto withCeiling=juce::JSON::parse(juce::JSON::toString(valid)); + auto ceilingDesign=withCeiling.getProperty("design",{}); + auto ceilingRows=ceilingDesign.getProperty("outputs",{}); + auto& ceilingRow=ceilingRows.getArray()->getReference(0); + ceilingRow.getDynamicObject()->setProperty("limiterThresholdDb",-12.5); + OfflineIntent ceilingIntent; + assert(decode(withCeiling,ceilingIntent)); + assert(ceilingIntent.proposed.outputs[0].ceilingDbfs==-12.5); + ceilingRow.getDynamicObject()->setProperty("limiterThresholdDb",-61.); + assert(!decode(withCeiling,ceilingIntent)); + ceilingRow.getDynamicObject()->setProperty("limiterThresholdDb","-12"); + assert(!decode(withCeiling,ceilingIntent)); + ceilingRow.getDynamicObject()->setProperty("limiterThresholdDb",-12.5); + ceilingRow.getDynamicObject()->setProperty("voltageModel",true); + assert(!decode(withCeiling,ceilingIntent)); + auto reject=[&](const char* key,juce::var value){ + auto changed=juce::JSON::parse(juce::JSON::toString(valid)); + changed.getDynamicObject()->setProperty(key,value); + OfflineIntent other; + assert(!decode(changed,other)); + }; + reject("deviceEpoch","0"); + reject("deviceEpoch","021"); + reject("deviceEpoch","18446744073709551616"); + reject("graphRevision","4e2"); + reject("expectedDesignRevision","-1"); + reject("requestId","multi line\nbad"); + auto invalid=juce::JSON::parse(juce::JSON::toString(valid)); + invalid.getProperty("design",{}).getDynamicObject()-> + setProperty("applied",true); + OfflineIntent unchanged; + assert(!decode(invalid,unchanged)); + assert(accepted.proposed.deviceEpoch==21); + TrustedSpeakerDeviceView inspected; + inspected.deviceEpoch=21;inspected.graphRevision=42; + inspected.mainChannelId=999;inspected.backend="ASIO"; + inspected.deviceIdentity="ASIO/driver";inspected.sampleRate=48000; + inspected.maxFrames=256;inspected.callbackOutputs=8; + inspected.mainL=0;inspected.mainR=1; + inspected.monitorL=2;inspected.monitorR=3; + inspected.allOutputsDisarmed=true; + for(int i=0;i<8;++i) + inspected.actualEnabledPorts.push_back({"ASIO/driver/"+std::to_string(i),i}); + const auto snapshot=inspection(inspected,nullptr); + assert(snapshot.getProperty("ready",{})==juce::var(true)); + assert(snapshot.getProperty("hardwareApplied",{})==juce::var(false)); + assert(snapshot.getProperty("designRevision","")=="0"); + const auto ports=snapshot.getProperty("ports",{}).getArray(); + assert(ports&&ports->size()==8); + assert(ports->getReference(0).getProperty("occupied",{})==juce::var(true)); + assert(ports->getReference(4).getProperty("occupied",{})==juce::var(false)); + armix::mixer::DynamicNativeSessionPublisher::SpeakerDraftReadback read; + read.deviceEpoch=21;read.graphRevision=42;read.designRevision=3; + read.mainSource=armix::mixer::ChannelId{999}; + read.design=accepted.proposed; + const auto roundTrip=inspection(inspected,&read); + const auto verified=roundTrip.getProperty("validatedDesign",{}); + const auto outRows=verified.getProperty("outputs",{}).getArray(); + assert(outRows&&outRows->size()==1); + const auto& row=outRows->getReference(0); + assert(row.getProperty("gainDb",{})==juce::var(-5.5)); + assert(row.getProperty("delayMs",{})==juce::var(0.34)); + assert(row.getProperty("polarityInverted",{})==juce::var(true)); + assert(row.getProperty("limiterEnabled",{})==juce::var(false)); + assert(row.getProperty("limiterThresholdDb",{})==juce::var(-6.)); + assert(row.getProperty("voltageModelPresent",{})==juce::var(false)); + const auto peq=row.getProperty("peq",{}).getArray(); + assert(peq&&peq->size()==1); + const auto& eq=peq->getReference(0); + assert(eq.getProperty("frequencyHz",{})==juce::var(1000.)); + assert(eq.getProperty("q",{})==juce::var(1.5)); + assert(eq.getProperty("gainDb",{})==juce::var(2.3)); + assert(eq.getProperty("enabled",{})==juce::var(true)); + assert(roundTrip.getProperty("hardwareApplied",{})==juce::var(false)); + std::puts("PASS LMS: strict JUCE message-thread schema, no fake hardware ACK, bounded device readback"); +} diff --git a/tests/lms_native_bridge.test.cjs b/tests/lms_native_bridge.test.cjs new file mode 100644 index 000000000..d440e9f43 --- /dev/null +++ b/tests/lms_native_bridge.test.cjs @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: AGPL-3.0-only +const test=require("node:test"); +const assert=require("node:assert/strict"); +const fs=require("node:fs"); +const path=require("node:path"); +const M=require("../site/preview-v2/assets/lms-system-model.js"); +const source=fs.readFileSync(path.join(__dirname, + "../site/preview-v2/assets/lms-workspace.js"),"utf8"); + +function fixture(withBackend){ + const handlers={},events=[],dom={}; + const backend=withBackend?{ + addEventListener(type,fn){handlers[type]=fn}, + emitEvent(type,data){events.push({type,data})} + }:null; + const launch={textContent:"",addEventListener(type,fn){dom["launch:"+type]=fn}, + setAttribute(key,value){this[key]=value}}; + const root={hidden:true,dataset:{},innerHTML:"", + addEventListener(type,fn){dom[type]=fn}}; + const app={classList:{toggle(){}}}; + const document={ + getElementById(id){return id==="lmsOpen"?launch: + id==="lmsWorkspace"?root:null}, + querySelector(q){return q===".app"?app:null} + }; + const window={ArSonMixLmsModel:M,addEventListener(){}, + ...(backend?{__JUCE__:{backend}}:{})}; + new Function("window","document",source)(window,document); + const click=dataset=>dom.click({target:{closest:()=>({dataset})}}); + const change=(dataset,value)=>dom.change({target:{dataset,value}}); + const consume=(type)=>{const found=events.filter(e=>e.type===type);assert.ok(found.length,"expected "+type);return found.at(-1).data}; + return {backend,handlers,events,dom,launch,root,click,change,consume, + open(){dom["launch:click"]()}}; +} +function nativeProjection(design) { + return {...design,outputs:design.outputs.map(x=>({ + ...x,limiterThresholdDb:x.limiterThresholdDb===null?-6:x.limiterThresholdDb, + voltageModelPresent:false + }))}; +} +function inspection(id,{ready=true,outputDisarmed=true,revision="0", + design=null,epoch="21",graph="42"}={}){ + return {schema:"arsonmix.lms.native-inspection.v1",requestId:id, + ready,hardwareApplied:false,deviceEpoch:epoch,graphRevision:graph, + designRevision:revision,sampleRate:48000,maxFrames:256, + activeOutputChannels:8,outputDisarmed,validatedDesign:design, + ports:Array.from({length:8},(_,i)=>({ + identity:"ASIO-EXACT-DEVICE/PIN-"+i,callbackOrdinal:i,occupied:i<4 + }))}; +} +test("public /preview/ remains an offline design without native event claims",()=>{ + const app=fixture(false);app.open(); + assert.ok(app.root.innerHTML.includes("DESIGN ONLY · OUTPUT DISCONNECTED")); + assert.ok(!app.root.innerHTML.includes("NATIVE INSPECTION")); + assert.equal(app.events.length,0); + app.click({page:"crossover"}); + assert.ok(app.root.innerHTML.includes("calculated at 48 kHz")); +}); +test("native validation requires inspected physical pins, disarmed outputs and later readback",()=>{ + const app=fixture(true);app.open(); + const first=app.consume("arMixLmsInspect"); + assert.ok(!app.root.innerHTML.includes("Validate design")); + app.handlers.arMixLmsInspection(inspection(first.requestId,{ready:false})); + assert.ok(app.root.innerHTML.includes("unavailable")); + const invalid=app.consume("arMixLmsInspect"); + assert.equal(invalid.requestId,first.requestId); + app.click({action:"nativeInspect"}); + const current=app.consume("arMixLmsInspect"); + app.handlers.arMixLmsInspection(inspection(current.requestId)); + assert.ok(app.root.innerHTML.includes("4 free ASIO pins")); + app.click({action:"nativePorts"}); + assert.ok(app.root.innerHTML.includes("Review structural change")); + app.click({action:"confirm"}); + assert.ok(app.root.innerHTML.includes("Verified ASIO ports")); + app.click({page:"matrix"}); + const port="ASIO-EXACT-DEVICE/PIN-4"; + app.click({routePort:port,routeSection:"L:1"}); + assert.ok(app.root.innerHTML.includes("Native validation")); + app.click({action:"nativeValidate"}); + const sent=app.consume("arMixLmsValidate"); + assert.equal(sent.schema,"arsonmix.lms.native-design-intent.v1"); + assert.equal(sent.design.schema,"arsonmix.lms.draft.v1"); + assert.equal(sent.design.outputs.length,1); + assert.equal(sent.design.outputs[0].portIdentity,port); + assert.equal(sent.design.outputs[0].sourceSide,0); + assert.equal(sent.design.outputs[0].muted,true); + assert.equal(sent.design.outputs[0].limiterThresholdDb,null); + assert.equal(sent.expectedDesignRevision,"0"); + assert.equal(sent.deviceEpoch,"21"); + assert.equal(sent.graphRevision,"42"); + assert.equal(sent.design.applied,false); + assert.ok(!app.root.innerHTML.includes("VALIDATED DRAFT")); + app.handlers.arMixLmsDesignAck({ + schema:"arsonmix.lms.native-design-ack.v1", + requestId:sent.requestId,status:"VALIDATED_PENDING_READBACK", + hardwareApplied:false,designRevision:"1",errorCode:"NONE"}); + assert.ok(!app.root.innerHTML.includes("VALIDATED DRAFT")); + const refresh=app.consume("arMixLmsInspect"); + app.handlers.arMixLmsInspection(inspection(refresh.requestId,{ + revision:"1", + design:{ways:sent.design.ways,stereo:sent.design.stereo, + cutoffsHz:sent.design.cutoffsHz,outputs:nativeProjection(sent.design).outputs} + })); + assert.ok(app.root.innerHTML.includes("VALIDATED DRAFT")); + assert.ok(app.root.innerHTML.includes("hardware NOT applied")); + app.click({page:"crossover"}); + app.change({cutoff:"0"},"200"); + assert.ok(!app.root.innerHTML.includes("VALIDATED DRAFT")); + assert.ok(app.root.innerHTML.includes("native validation required")); +}); + +test("native readback must match EVERY output DSP field before VALIDATED",()=>{ + const mutations=[ + ["gain",x=>{x.gainDb=-13;}], + ["delay",x=>{x.delayMs=48.25;}], + ["polarity",x=>{x.polarityInverted=true;}], + ["limiter",x=>{x.limiterEnabled=true;}], + ["digital ceiling",x=>{x.limiterThresholdDb=-17.25;}], + ["missing digital ceiling",x=>{delete x.limiterThresholdDb;}], + ["unacknowledged voltage profile",x=>{x.voltageModelPresent=true;}], + ["eq insertion",x=>{x.peq=[{frequencyHz:1000,q:1,gainDb:6,enabled:true}];}], + ["missing eq",x=>{delete x.peq;}], + ["missing delay",x=>{delete x.delayMs;}], + ["unmute",x=>{x.muted=false;}], + ]; + for(const [name,mutate] of mutations){ + const app=fixture(true);app.open(); + const first=app.consume("arMixLmsInspect"); + app.handlers.arMixLmsInspection(inspection(first.requestId)); + app.click({action:"nativePorts"});app.click({action:"confirm"}); + app.click({routePort:"ASIO-EXACT-DEVICE/PIN-4",routeSection:"L:1"}); + app.click({action:"nativeValidate"}); + const sent=app.consume("arMixLmsValidate"); + app.handlers.arMixLmsDesignAck({ + schema:"arsonmix.lms.native-design-ack.v1",requestId:sent.requestId, + status:"VALIDATED_PENDING_READBACK",hardwareApplied:false, + designRevision:"1",errorCode:"NONE" + }); + const checked=app.consume("arMixLmsInspect"); + const actual=nativeProjection(structuredClone(sent.design)); + mutate(actual.outputs[0]); + app.handlers.arMixLmsInspection(inspection(checked.requestId,{ + revision:"1",design:actual + })); + assert.ok(!app.root.innerHTML.includes("VALIDATED DRAFT"),name); + assert.ok(app.root.innerHTML.includes("readback mismatch"),name); + } +}); +test("guided DLMS ASIO reassign retains DSP, requires manual pin mapping and readback",()=>{ + const app=fixture(true);app.open(); + const id=app.consume("arMixLmsInspect").requestId; + app.handlers.arMixLmsInspection(inspection(id)); + app.click({routePort:"DEMO-01",routeSection:"L:1"}); + app.click({selectPort:"DEMO-01"}); + app.change({dsp:"gainDb"},"-7"); + app.change({dsp:"muted"},"0"); + assert.ok(app.root.innerHTML.includes("Reassign + keep DSP")); + app.click({action:"nativeReassign"}); + assert.ok(app.root.innerHTML.includes("Review explicit output reassignment")); + app.click({action:"confirmReassign"}); + assert.ok(app.root.innerHTML.includes("Choose at least one explicit")); + assert.equal(app.events.filter(e=>e.type==="arMixLmsValidate").length,0); + app.change({rebindSource:"DEMO-01"},"ASIO-EXACT-DEVICE/PIN-4"); + app.click({action:"confirmReassign"}); + assert.ok(app.root.innerHTML.includes("saved as MUTED draft"), + "Reassignment status: "+app.root.innerHTML.slice(0,3800)); + assert.ok(!app.root.innerHTML.includes("Review explicit output reassignment")); + assert.equal(app.events.filter(e=>e.type==="arMixLmsValidate").length,0); + app.click({action:"nativeValidate"}); + const sent=app.consume("arMixLmsValidate"); + assert.equal(sent.design.outputs.length,1); + assert.equal(sent.design.outputs[0].portIdentity,"ASIO-EXACT-DEVICE/PIN-4"); + assert.equal(sent.design.outputs[0].gainDb,-7); + assert.equal(sent.design.outputs[0].muted,true); + assert.equal(sent.design.applied,false); +}); +test("DLMS mapping review aborts if a fresh inspection changes device epoch",()=>{ + const app=fixture(true);app.open(); + const id=app.consume("arMixLmsInspect").requestId; + app.handlers.arMixLmsInspection(inspection(id)); + app.click({routePort:"DEMO-01",routeSection:"L:1"}); + app.click({action:"nativeReassign"}); + assert.ok(app.root.innerHTML.includes("Review explicit output reassignment")); + app.click({action:"nativeInspect"}); + const refresh=app.consume("arMixLmsInspect"); + app.handlers.arMixLmsInspection(inspection(refresh.requestId,{epoch:"999"})); + assert.ok(!app.root.innerHTML.includes("Review explicit output reassignment")); + assert.equal(app.events.filter(e=>e.type==="arMixLmsValidate").length,0); +}); + +test("native readback cannot validate when hardware is armed",()=>{ + const app=fixture(true);app.open(); + const first=app.consume("arMixLmsInspect"); + app.handlers.arMixLmsInspection(inspection(first.requestId)); + app.click({action:"nativePorts"});app.click({action:"confirm"}); + app.click({routePort:"ASIO-EXACT-DEVICE/PIN-4",routeSection:"L:1"}); + app.click({action:"nativeValidate"}); + const sent=app.consume("arMixLmsValidate"); + app.handlers.arMixLmsDesignAck({ + schema:"arsonmix.lms.native-design-ack.v1",requestId:sent.requestId, + status:"VALIDATED_PENDING_READBACK",hardwareApplied:false, + designRevision:"1",errorCode:"NONE" + }); + const checked=app.consume("arMixLmsInspect"); + app.handlers.arMixLmsInspection(inspection(checked.requestId,{ + revision:"1",design:nativeProjection(sent.design),outputDisarmed:false + })); + assert.ok(!app.root.innerHTML.includes("VALIDATED DRAFT")); +}); +test("native rejection and armed-device snapshot never invent APPLIED",()=>{ + const app=fixture(true);app.open(); + let req=app.consume("arMixLmsInspect"); + app.handlers.arMixLmsInspection(inspection(req.requestId,{outputDisarmed:false})); + app.click({action:"nativePorts"});app.click({action:"confirm"}); + const port="ASIO-EXACT-DEVICE/PIN-4"; + app.click({routePort:port,routeSection:"L:1"}); + assert.ok(app.root.innerHTML.includes("disabled")); + app.click({action:"nativeValidate"}); + assert.equal(app.events.filter(e=>e.type==="arMixLmsValidate").length,0); + app.click({action:"nativeInspect"}); + req=app.consume("arMixLmsInspect"); + app.handlers.arMixLmsInspection(inspection(req.requestId)); + app.click({action:"nativeValidate"}); + const sent=app.consume("arMixLmsValidate"); + app.handlers.arMixLmsDesignAck({ + schema:"arsonmix.lms.native-design-ack.v1", + requestId:sent.requestId,status:"REJECTED", + hardwareApplied:false,errorCode:"NATIVE_LMS_STALE_GRAPH"}); + assert.ok(app.root.innerHTML.includes("REJECTED")); + assert.ok(!app.root.innerHTML.includes("VALIDATED DRAFT")); +}); diff --git a/tests/lms_native_draft_ack_readback_test.cpp b/tests/lms_native_draft_ack_readback_test.cpp new file mode 100644 index 000000000..7e7135cf1 --- /dev/null +++ b/tests/lms_native_draft_ack_readback_test.cpp @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// One accepted native ChannelId PCM graph owns the speaker design admission. +// This test never opens, borrows, or writes an ASIO hardware output buffer. +#include "../engine/core/DynamicNativeSessionPublisher.h" +#if defined(NDEBUG) +#undef NDEBUG // Release/CTest must execute every safety assertion. +#endif +#include +#include +#include +#include +#include +using namespace armix::mixer; +using namespace armix::lms; + +static ChannelEdit create(int at,ChannelRole role,const char* name){ + ChannelEdit e; + e.kind=ChannelEdit::Kind::add;e.position=static_cast(at); + e.role=role;e.format=ProcessingFormat::stereo;e.text=name;return e; +} +static SpeakerSystemRequest design(std::uint64_t epoch,std::uint64_t graph){ + SpeakerSystemRequest s; + s.deviceEpoch=epoch;s.graphRevision=graph; + s.sampleRate=48000.;s.maxFrames=256; + s.activeOutputChannels=8;s.ways=2;s.stereo=true; + s.crossoverHz={1400.}; + for(int i=0;i<8;++i)s.verifiedPorts.push_back( + {"ASIO-DEVICE-IDENTITY:PIN-"+std::to_string(i),i}); + OutputPatch a,b; + a.outputId="HF-L";a.portIdentity=s.verifiedPorts[4].identity; + a.sourceSide=0;a.section=1;a.mute=true; + b.outputId="HF-R";b.portIdentity=s.verifiedPorts[6].identity; + b.sourceSide=1;b.section=1;b.mute=true; + s.outputs={a,b}; + return s; +} +static NativePcmOutputInventory actual(const SpeakerSystemRequest& s, + ChannelId main){ + NativePcmOutputInventory p; + p.deviceEpoch=s.deviceEpoch; + p.acceptedGraphRevision=s.graphRevision; + p.mainChannelId=main.value; + p.deviceIdentity="ASIO-DEVICE-IDENTITY"; + p.sampleRate=s.sampleRate; + p.callbackOutputs=s.activeOutputChannels; + p.mainL=0;p.mainR=1;p.monitorL=2;p.monitorR=3; + p.allOutputsDisarmed=true;p.acceptedChannelIdPcm=true; + p.enabledOutputPorts=s.verifiedPorts; + return p; +} +int main() { + constexpr std::uint64_t epoch=9876; + DynamicChannelRoster roster; + const std::array add{ + create(0,ChannelRole::input,"VOICE"), + create(1,ChannelRole::main,"MAIN") + }; + const auto made=roster.edit(0,add); + assert(made.ok()&&made.createdIds.size()==2); + const auto voice=made.createdIds[0],main=made.createdIds[1]; + ChannelEdit wire; + wire.kind=ChannelEdit::Kind::setPrimaryOutput;wire.id=voice;wire.target=main; + assert(roster.edit(roster.revision(),std::span(&wire,1)).ok()); + DynamicGraphRequest request; + request.physicalInputs=2;request.maxFrames=256; + request.sources={{voice,0,1,true}}; + DynamicNativeSessionPublisher native; + assert(native.commit(roster,request,0,epoch,epoch,true).ok()); + auto s=design(epoch,1); + auto p=actual(s,main); + auto accepted=native.acceptSpeakerDraft(s,p,main,0); + assert(accepted.ok()&&accepted.designRevision==1); + assert(!accepted.hardwareApplied&&accepted.preparedScratchBytes>0); + auto* read=native.speakerDraftReadback(epoch,1); + assert(read&&read->validatedDraft&&!read->hardwareApplied); + assert(read->designRevision==1&&read->graphRevision==1); + assert(read->deviceEpoch==epoch&&read->mainSource==main); + assert(read->reservedOutputOrdinals.size()==2); + assert(read->reservedOutputOrdinals[0]==4&&read->reservedOutputOrdinals[1]==6); + assert(read->design.crossoverHz==s.crossoverHz); + assert(read->design.outputs[0].portIdentity==s.outputs[0].portIdentity); + // Replay of stale browser revision cannot stomp the first acceptance. + const auto stale=native.acceptSpeakerDraft(s,p,main,0); + assert(stale.fault==DynamicNativeSessionPublisher::SpeakerDraftFault::staleDraft); + assert(stale.designRevision==1&&!stale.validatedDraft); + assert(native.speakerDraftReadback(epoch,1)->designRevision==1); + // Native source authority belongs to MAIN, never an arbitrary sender. + const auto notMain=native.acceptSpeakerDraft(s,p,voice,1); + assert(notMain.fault==DynamicNativeSessionPublisher::SpeakerDraftFault::invalidSource); + assert(native.speakerDraftReadback(epoch,1)->designRevision==1); + // Unsafe user unmute + checkbox limiter is not an approved protection. + s.outputs[0].mute=false; + s.outputs[0].limiterEnabled=true; + s.outputs[0].confirmedSpeakerProfile=true; + const auto unsafe=native.acceptSpeakerDraft(s,p,main,1); + assert(unsafe.fault==DynamicNativeSessionPublisher::SpeakerDraftFault::invalidReservation); + assert(unsafe.reservationFault==SpeakerReservationFault::unprotectedOutput); + assert(!unsafe.hardwareApplied); + assert(native.speakerDraftReadback(epoch,1)->designRevision==1); + s.outputs[0].mute=true; + // A physically occupied MAIN or MONITOR socket is not a speaker target. + s.outputs[0].portIdentity=s.verifiedPorts[0].identity; + const auto collision=native.acceptSpeakerDraft(s,p,main,1); + assert(collision.reservationFault==SpeakerReservationFault::occupiedOutput); + s.outputs[0].portIdentity=s.verifiedPorts[4].identity; + // Rejected DSP parameters cannot corrupt the accepted draft. + s.crossoverHz={30000.}; + const auto badFilter=native.acceptSpeakerDraft(s,p,main,1); + assert(badFilter.fault==DynamicNativeSessionPublisher::SpeakerDraftFault::invalidDsp); + assert(badFilter.planFault==SpeakerPlanFault::invalidCrossover); + s.crossoverHz={1800.}; + s.maxFrames=128; + const auto badQuantum=native.acceptSpeakerDraft(s,p,main,1); + assert(badQuantum.fault==DynamicNativeSessionPublisher::SpeakerDraftFault::invalidDsp); + s.maxFrames=256; + // A CONTROL-supplied manufacturer/measurement voltage model can be + // prepared and revisioned, but it NEVER grants ASIO activation. + DriverVoltageModel voltage; + voltage.profileId="TEST-ONLY"; + voltage.dacFullScaleVrms=2.; + voltage.amplifierVoltageGain=25.; + voltage.continuousDriverVrms=12.; + voltage.driverPeakVolts=21.; + voltage.minimumHighpassHz=80.; + s.outputs[0].voltageModel=voltage; + // Operator design revision advances ONLY after full validation and prep. + const auto updated=native.acceptSpeakerDraft(s,p,main,1); + assert(updated.ok()&&updated.designRevision==2); + assert(native.speakerDraftReadback(epoch,1)->design.crossoverHz[0]==1800.); + const auto* calibratedDraft=native.speakerDraftReadback(epoch,1); + assert(calibratedDraft->design.outputs[0].voltageModel.has_value()); + assert(calibratedDraft->design.outputs[0].voltageModel->profileId=="TEST-ONLY"); + const auto diagnostic=native.speakerDiagnosticReadback(epoch,1); + assert(diagnostic.available && !diagnostic.hardwareApplied && + diagnostic.designRevision==2); + s.outputs[0].mute=false; + const auto stillNotArmed=native.acceptSpeakerDraft(s,p,main,2); + assert(stillNotArmed.fault==DynamicNativeSessionPublisher::SpeakerDraftFault::invalidReservation); + assert(stillNotArmed.reservationFault==SpeakerReservationFault::unprotectedOutput); + assert(native.speakerDraftReadback(epoch,1)->designRevision==2); + s.outputs[0].mute=true; + assert(!native.speakerDraftReadback(epoch+1,1)); + assert(!native.speakerDraftReadback(epoch,2)); + // Accepted structural PCM revision invalidates ALL previously prepared + // speaker state; even if driver output ordinals happen to be identical. + const auto nextGraph=native.commit(roster,request,1,epoch,epoch,true); + assert(nextGraph.ok()&&nextGraph.revision==2); + assert(!native.speakerDraftReadback(epoch,1)); + assert(!native.speakerDraftReadback(epoch,2)); + s.graphRevision=2;p.acceptedGraphRevision=2; + const auto fresh=native.acceptSpeakerDraft(s,p,main,0); + assert(fresh.ok()&&fresh.designRevision==1); + native.unpublish(); + assert(!native.speakerDraftReadback(epoch,2)); + std::puts("PASS LMS M5: same-native-PCM draft ACK/readback, revision rollback, pin safety, structural revoke, hardware disabled"); +} diff --git a/tests/lms_native_output_reservation_test.cpp b/tests/lms_native_output_reservation_test.cpp new file mode 100644 index 000000000..8b8437f87 --- /dev/null +++ b/tests/lms_native_output_reservation_test.cpp @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/lms/NativeSpeakerOutputReservation.h" +#if defined(NDEBUG) +#undef NDEBUG +#endif +#include +#include +using namespace armix::lms; +static SpeakerSystemRequest speaker() { + SpeakerSystemRequest s; + s.deviceEpoch=13;s.graphRevision=28;s.sampleRate=48000.; + s.maxFrames=256;s.activeOutputChannels=8;s.ways=2;s.stereo=true; + s.crossoverHz={1200.}; + s.verifiedPorts={{"ASIO#EXACT/1",0},{"ASIO#EXACT/2",1}, + {"ASIO#EXACT/3",2},{"ASIO#EXACT/4",3}, + {"ASIO#EXACT/5",4},{"ASIO#EXACT/6",5}, + {"ASIO#EXACT/7",6},{"ASIO#EXACT/8",7}}; + OutputPatch p;p.outputId="LOW-L";p.portIdentity="ASIO#EXACT/5"; + p.sourceSide=0;p.section=0;p.mute=true; + s.outputs.push_back(p); + p.outputId="LOW-R";p.portIdentity="ASIO#EXACT/7";p.sourceSide=1; + s.outputs.push_back(p); + return s; +} +static NativePcmOutputInventory current() { + NativePcmOutputInventory i; + i.deviceEpoch=13;i.acceptedGraphRevision=28;i.mainChannelId=101; + i.deviceIdentity="DRIVER#EXACT";i.sampleRate=48000.; + i.callbackOutputs=8;i.mainL=0;i.mainR=1; + i.monitorL=2;i.monitorR=3;i.acceptedChannelIdPcm=true; + i.allOutputsDisarmed=true; + i.enabledOutputPorts=speaker().verifiedPorts; + return i; +} +static void gate() { + auto s=speaker();auto i=current(); + const auto ok=NativeSpeakerOutputReservation::preflight(s,i,101); + assert(ok.ok() && !ok.mayWritePhysicalAudio); + assert((ok.reservedCallbackOrdinals==std::vector{4,6})); + auto rejected=[&](SpeakerReservationFault fault) { + const auto r=NativeSpeakerOutputReservation::preflight(s,i,101); + assert(!r.ok()&&r.fault==fault&&!r.mayWritePhysicalAudio); + assert(r.reservedCallbackOrdinals.empty()); + }; + i.allOutputsDisarmed=false;rejected(SpeakerReservationFault::notAcceptedPcm); + i.allOutputsDisarmed=true; + i.acceptedChannelIdPcm=false;rejected(SpeakerReservationFault::notAcceptedPcm); + i.acceptedChannelIdPcm=true; + s.deviceEpoch=12;rejected(SpeakerReservationFault::staleDevice); + s.deviceEpoch=13; + s.graphRevision=27;rejected(SpeakerReservationFault::staleGraph); + s.graphRevision=28; + i.mainChannelId=999;rejected(SpeakerReservationFault::invalidSource); + i.mainChannelId=101; + s.sampleRate=96000.;rejected(SpeakerReservationFault::deviceLayoutMismatch); + s.sampleRate=48000.; + i.enabledOutputPorts[4].callbackOrdinal=5; + rejected(SpeakerReservationFault::unknownPort); + i.enabledOutputPorts[4].callbackOrdinal=4; + i.otherOccupiedOutputOrdinals={4}; + rejected(SpeakerReservationFault::occupiedOutput); + i.otherOccupiedOutputOrdinals.clear(); + s.outputs[0].portIdentity="ASIO#EXACT/3"; // MONITOR 2 + rejected(SpeakerReservationFault::occupiedOutput); + s.outputs[0].portIdentity="ASIO#EXACT/1"; // MAIN 0 + rejected(SpeakerReservationFault::occupiedOutput); + s.outputs[0].portIdentity="ASIO#EXACT/5"; + s.outputs[1].portIdentity="ASIO#EXACT/5"; // same pin twice + rejected(SpeakerReservationFault::occupiedOutput); + s.outputs[1].portIdentity="ASIO#EXACT/7"; + s.outputs[1].mute=false; + s.outputs[1].confirmedSpeakerProfile=true;s.outputs[1].limiterEnabled=true; + rejected(SpeakerReservationFault::unprotectedOutput); // hard clip is NOT speaker protection + s.outputs[1].mute=true; + const auto final=NativeSpeakerOutputReservation::preflight(s,i,101); + assert(final.ok()&&!final.mayWritePhysicalAudio); +} +int main() { + gate(); + std::puts("PASS LMS M3: exact native ChannelId/epoch/ASIO pin reservation, no hardware output authority"); +} diff --git a/tests/lms_native_postfx_main_witness_test.cpp b/tests/lms_native_postfx_main_witness_test.cpp new file mode 100644 index 000000000..e3b1e10f3 --- /dev/null +++ b/tests/lms_native_postfx_main_witness_test.cpp @@ -0,0 +1,305 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// M4: End-to-end portable ChannelId post-FX MAIN -> real LMS DSP PCM witness. +// The 12 buffers below are isolated DIAGNOSTIC buffers, NOT ASIO output pins; +// the accepted native publisher performs the ONE graph render / VST dispatch. +#include "../engine/core/DynamicNativeSessionPublisher.h" +#include "../engine/lms/PreparedSpeakerSystem.h" +#include "../engine/lms/NativeSpeakerOutputReservation.h" +#if defined(NDEBUG) +#undef NDEBUG +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace armix::mixer; +using namespace armix::lms; + +static std::atomic allocations{0}; +void* operator new(std::size_t n) { + allocations.fetch_add(1,std::memory_order_relaxed); + if(void* p=std::malloc(n?n:1)) return p; + throw std::bad_alloc(); +} +void* operator new[](std::size_t n) { + allocations.fetch_add(1,std::memory_order_relaxed); + if(void* p=std::malloc(n?n:1)) return p; + throw std::bad_alloc(); +} +// Keep the replacement deallocator opaque to GCC's unrelated vector-copy +// inliner; it falsely diagnoses custom malloc/new pairs as mismatched while +// the allocation counter still covers ALL global new/new[] calls. +#if defined(_MSC_VER) +__declspec(noinline) +#elif defined(__GNUC__) +__attribute__((noinline)) +#endif +static void releaseTracked(void* p) noexcept {std::free(p);} +void operator delete(void* p) noexcept {releaseTracked(p);} +void operator delete(void* p,std::size_t) noexcept {releaseTracked(p);} +void operator delete[](void* p) noexcept {releaseTracked(p);} +void operator delete[](void* p,std::size_t) noexcept {releaseTracked(p);} + +static ChannelEdit add(int index,ChannelRole role,const char* name) { + ChannelEdit e; + e.kind=ChannelEdit::Kind::add;e.position=static_cast(index); + e.role=role;e.format=ProcessingFormat::stereo;e.text=name;return e; +} +static ChannelEdit output(ChannelId from,ChannelId to) { + ChannelEdit e;e.kind=ChannelEdit::Kind::setPrimaryOutput; + e.id=from;e.target=to;return e; +} + +struct Witness { + static constexpr int maxFrames=256,activePins=12; + PreparedSpeakerSystem* speaker=nullptr; + std::uint64_t epoch=750,revision=1; + std::array,activePins> diagnostic{}; + std::array diagnosticPointers{}; + int observations=0; + bool processed=false; + Witness() { + for(int i=0;i(ctx); + ++self.observations; + self.processed=self.speaker->process(self.epoch,self.revision,left,right, + self.diagnosticPointers.data(),activePins,frames,true); + } +}; + +int main() { + constexpr auto epoch=750ULL; + DynamicNativeSessionPublisher native; + DynamicChannelRoster roster; + const std::array creates{ + add(0,ChannelRole::input,"VOICE"), + add(1,ChannelRole::main,"MAIN") + }; + const auto created=roster.edit(0,creates); + assert(created.ok() && created.createdIds.size()==2); + const auto voice=created.createdIds[0],main=created.createdIds[1]; + const ChannelEdit mainWire=output(voice,main); + assert(roster.edit(roster.revision(),std::span(&mainWire,1)).ok()); + DynamicGraphRequest request; + request.physicalInputs=2;request.maxFrames=Witness::maxFrames; + request.sources={{voice,0,1,true}}; + const auto accepted=native.commit(roster,request,0,epoch,epoch,true); + assert(accepted.ok() && accepted.revision==1); + assert(native.acceptedRouting(epoch,1)->find(voice)->primaryOutput==main); + + SpeakerSystemRequest settings; + settings.deviceEpoch=epoch;settings.graphRevision=1; + settings.sampleRate=48000.;settings.maxFrames=Witness::maxFrames; + settings.activeOutputChannels=Witness::activePins; + settings.stereo=true;settings.ways=4; + settings.crossoverHz={100.,1000.,6000.}; + for(int i=0;i dsp; + assert(PreparedSpeakerSystem::prepare(settings,dsp).ok()); + Witness witness;witness.speaker=dsp.get(); + DynamicNativeSessionPublisher::MainPcmObserver observer{ + &witness,&Witness::capture + }; + std::array inL{},inR{},mainL{},mainR{}; + std::array inputs{inL.data(),inR.data()}; + inL.fill(.2f);inR.fill(.05f); + // Physical pins supplied by an ASIO callback must NEVER be modified in + // M4 diagnostic witnessing (including MAIN, MONITOR and other BUS). + std::array,Witness::activePins> driver{}; + for(auto& pin:driver)pin.fill(.8125f); + int voiceFxCalls=0,mainFxCalls=0; + auto fx=[&](ChannelId id,float* l,float* r,int n) noexcept { + if(id==voice) { + ++voiceFxCalls; + for(int i=0;i.055f); + assert(diag.isolatedOutputPeaks[0].second<.09f); // measured RMS-driven GR + assert(diag.outputProtection.size()==8); + assert(diag.outputProtection[0].callbackOrdinal==4); + assert(diag.outputProtection[0].voltageModelPrepared); + assert(diag.outputProtection[0].gainReductionDb>6.f); + assert(diag.outputProtection[0].preLimitRmsDigital>.15f); + assert(diag.outputProtection[0].outputPeakDigital<.09f); + assert(diag.outputProtection[1].callbackOrdinal==5); + assert(!diag.outputProtection[1].voltageModelPrepared); + assert(diag.outputProtection[1].gainReductionDb==0.f); + assert(diag.isolatedOutputPeaks[4].first==8); + assert(diag.isolatedOutputPeaks[4].second>.035f); + assert(diag.isolatedOutputPeaks[3].second<.02f); + assert(diag.isolatedOutputPeaks[7].second<.02f); + for(const auto& pin:driver) + for(float v:pin)assert(v==.8125f); // NO touched ASIO pin + const auto beforeStale=diag.completedBlocks; + assert(!native.processSpeakerDiagnostic(epoch,2, + mainL.data(),mainR.data(),Witness::maxFrames)); + assert(!native.processSpeakerDiagnostic(epoch+1,1, + mainL.data(),mainR.data(),Witness::maxFrames)); + assert(native.speakerDiagnosticReadback(epoch,1).completedBlocks==beforeStale); + // Runtime master mute enters as zero PCM, never a stale full-range signal. + mainL.fill(0.f);mainR.fill(0.f); + assert(native.processSpeakerDiagnostic(epoch,1, + mainL.data(),mainR.data(),Witness::maxFrames)); + diag=native.speakerDiagnosticReadback(epoch,1); + assert(diag.postMasterPeakL==0.f && diag.postMasterPeakR==0.f); + // M10 CPU budget: even with an accepted design and continuous MAIN + // source, expensive 8-way diagnostics automatically expire. A speaker + // draft never activates a permanently running second DSP workload. + const auto capturedAllocations=allocations.load(std::memory_order_relaxed); + int acceptedRemaining=0; + for(int i=0;i<800;++i) { + if(!native.processSpeakerDiagnostic(epoch,1, + mainL.data(),mainR.data(),Witness::maxFrames))break; + ++acceptedRemaining; + } + assert(acceptedRemaining>100 && acceptedRemaining<300); + // AUDIO-only heap fence: CONTROL readback is explicitly allowed to + // allocate result vectors and must not contaminate this accounting. + assert(allocations.load(std::memory_order_relaxed)==capturedAllocations); + auto finalCapture=native.speakerDiagnosticReadback(epoch,1); + assert(finalCapture.available && !finalCapture.hardwareApplied); + assert(finalCapture.captureComplete); + assert(finalCapture.capturedFrames>=finalCapture.captureFrameLimit); + assert(finalCapture.completedBlocks==220+1+ + static_cast(acceptedRemaining)); + const auto afterControlReadback=allocations.load(std::memory_order_relaxed); + for(int repeat=0;repeat<12;++repeat) + assert(!native.processSpeakerDiagnostic(epoch,1, + mainL.data(),mainR.data(),Witness::maxFrames)); + assert(allocations.load(std::memory_order_relaxed)==afterControlReadback); + assert(native.speakerDiagnosticReadback(epoch,1).completedBlocks== + finalCapture.completedBlocks); + for(const auto& pin:driver) + for(float v:pin)assert(v==.8125f); + native.revokeSpeakerDraft(); + assert(!native.speakerDiagnosticReadback(epoch,1).available); + assert(!native.processSpeakerDiagnostic(epoch,1, + mainL.data(),mainR.data(),Witness::maxFrames)); + native.unpublish();native.pollRetirement(); + std::puts("PASS LMS: one accepted ChannelId MAIN FX render -> 8 isolated crossover outputs, zero callback heap, no physical write"); +} diff --git a/tests/lms_offline_session_draft_test.cpp b/tests/lms_offline_session_draft_test.cpp new file mode 100644 index 000000000..fb191187c --- /dev/null +++ b/tests/lms_offline_session_draft_test.cpp @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#if defined(NDEBUG) +#undef NDEBUG +#endif +#include "../engine/lms/LmsOfflineDraft.h" +#include +#include +#include +#include +#include +using namespace armix::lms; +int main() { + SpeakerSystemRequest bound; + bound.deviceEpoch=71;bound.graphRevision=34; + bound.sampleRate=48000.;bound.maxFrames=256; + bound.activeOutputChannels=8;bound.ways=2;bound.stereo=true; + bound.crossoverHz={1800.}; + bound.verifiedPorts={{"ASIO:PIN-4",4},{"ASIO:PIN-6",6}}; + OutputPatch lo,hi; + lo.outputId="LOW-L";lo.portIdentity="ASIO:PIN-4"; + lo.section=0;lo.sourceSide=0;lo.mute=true;lo.gainDb=-3.; + lo.delayMs=1.75;lo.ceilingDbfs=-9.;lo.limiterEnabled=true; + lo.peq={{110.,.8,-1.5,true}}; + lo.confirmedSpeakerProfile=true; + lo.voltageModel=DriverVoltageModel{"TEST-PROFILE",2.,22.,8.,18.,40.,500.,150.}; + hi.outputId="HIGH-R";hi.portIdentity="ASIO:PIN-6"; + hi.section=1;hi.sourceSide=1;hi.mute=false; + hi.gainDb=-8.;hi.polarityInverted=true; + bound.outputs={lo,hi}; + OfflineSpeakerDraft saved; + assert(OfflineSpeakerDraftPolicy::detach(bound,saved)); + assert(OfflineSpeakerDraftPolicy::valid(saved)); + assert(saved.outputs.size()==2 && saved.outputs[0].peq.size()==1); + assert(saved.outputs[0].outputId=="LOW-L" && + saved.outputs[1].outputId=="HIGH-R"); + assert(saved.outputs[0].portIdentity.empty() && + saved.outputs[1].portIdentity.empty()); + // A GUI-owned outputId that was identical to a physical port string + // must be severed from that hardware identity on cold save. + auto portNamed=bound; + portNamed.outputs[0].outputId=portNamed.outputs[0].portIdentity; + portNamed.outputs[1].outputId=portNamed.outputs[1].portIdentity; + OfflineSpeakerDraft aliased; + assert(OfflineSpeakerDraftPolicy::detach(portNamed,aliased)); + assert(aliased.outputs[0].outputId=="OUT-1" && + aliased.outputs[1].outputId=="OUT-2"); + assert(saved.outputs[0].mute && saved.outputs[1].mute); + assert(!saved.outputs[0].confirmedSpeakerProfile && + !saved.outputs[0].voltageModel); + assert(saved.outputs[0].ceilingDbfs==-9.); + SpeakerSystemRequest restored; + assert(OfflineSpeakerDraftPolicy::restoreDisconnected(saved,restored)); + assert(restored.deviceEpoch==0 && restored.graphRevision==0 && + restored.activeOutputChannels==0 && restored.verifiedPorts.empty()); + assert(restored.outputs[0].portIdentity.empty() && + restored.outputs[1].portIdentity.empty()); + std::unique_ptr dsp; + const auto preparation=PreparedSpeakerSystem::prepare(restored,dsp); + assert(!preparation.ok() && !dsp); // NEVER auto-publish after cold open + auto previous=restored; + auto bad=saved;bad.version=2; + assert(!OfflineSpeakerDraftPolicy::restoreDisconnected(bad,restored)); + assert(restored.deviceEpoch==previous.deviceEpoch && + restored.outputs.size()==previous.outputs.size()); + bad=saved;bad.outputs[0].portIdentity="ASIO:PIN-4"; + assert(!OfflineSpeakerDraftPolicy::valid(bad)); + bad=saved;bad.outputs[0].mute=false; + assert(!OfflineSpeakerDraftPolicy::valid(bad)); + bad=saved;bad.outputs[0].confirmedSpeakerProfile=true; + assert(!OfflineSpeakerDraftPolicy::valid(bad)); + bad=saved;bad.outputs[0].voltageModel=lo.voltageModel; + assert(!OfflineSpeakerDraftPolicy::valid(bad)); + bad=saved;bad.crossoverHz={std::numeric_limits::quiet_NaN()}; + assert(!OfflineSpeakerDraftPolicy::valid(bad)); + bad=saved;bad.outputs[0].peq[0].q=std::numeric_limits::infinity(); + assert(!OfflineSpeakerDraftPolicy::valid(bad)); + bad=saved;bad.outputs[1].outputId="LOW-L"; + assert(!OfflineSpeakerDraftPolicy::valid(bad)); + bad=saved;bad.outputs[1].section=2; + assert(!OfflineSpeakerDraftPolicy::valid(bad)); + bad=saved;bad.stereo=false; + assert(!OfflineSpeakerDraftPolicy::valid(bad)); // stale right-side route + bad=saved;bad.outputs[0].outputId=" "; + assert(!OfflineSpeakerDraftPolicy::valid(bad)); + auto untouched=saved; + bound.graphRevision=0; + assert(!OfflineSpeakerDraftPolicy::detach(bound,saved)); + assert(saved.outputs[0].gainDb==untouched.outputs[0].gainDb); + std::puts("PASS LMS M11: persisted-design detaches physical pins/calibration, cold-open unassigned, strict rollback"); +} diff --git a/tests/lms_prepared_speaker_pcm_test.cpp b/tests/lms_prepared_speaker_pcm_test.cpp new file mode 100644 index 000000000..9602ae9d9 --- /dev/null +++ b/tests/lms_prepared_speaker_pcm_test.cpp @@ -0,0 +1,350 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/lms/PreparedSpeakerSystem.h" +#include +#ifdef NDEBUG +#undef NDEBUG // Always execute PCM assertions, even in release CTest. +#endif +#include +#include +#include +#include +#include +#include +using namespace armix::lms; +constexpr double pi=3.14159265358979323846; +SpeakerSystemRequest base(int ways=2,bool stereo=true) { + SpeakerSystemRequest r; + r.deviceEpoch=71;r.graphRevision=14; + r.sampleRate=48000.;r.maxFrames=256;r.activeOutputChannels=8; + r.ways=ways;r.stereo=stereo; + if(ways==2)r.crossoverHz={1000.}; + if(ways==3)r.crossoverHz={150.,2000.}; + if(ways==4)r.crossoverHz={80.,300.,2500.}; + r.verifiedPorts={{"ASIO#37/OUT-1",0},{"ASIO#37/OUT-3",2}, + {"ASIO#37/OUT-4",3},{"ASIO#37/OUT-6",5}, + {"ASIO#37/OUT-8",7}}; + return r; +} +OutputPatch patch(std::string id,std::string pin,int side,int way,double delay=0.) { + OutputPatch p; + p.outputId=std::move(id);p.portIdentity=std::move(pin); + p.sourceSide=side;p.section=way;p.delayMs=delay; + p.mute=false;p.limiterEnabled=true;p.ceilingDbfs=0.; + p.confirmedSpeakerProfile=true;return p; +} +std::unique_ptr prepared(const SpeakerSystemRequest& r) { + std::unique_ptr out; + const auto result=PreparedSpeakerSystem::prepare(r,out); + if(!result.ok()) { + std::cerr<<"prepare fault="<(result.fault)<<"\n"; + throw std::runtime_error("prepare failed"); + } + assert(out&&out->epoch()==r.deviceEpoch&&out->revision()==r.graphRevision); + assert(out->sectionCount()==static_cast(r.ways*(r.stereo?2:1))); + assert(out->destinationCount()==r.outputs.size()); + assert(out->scratchBytes()==result.scratchBytes); + return out; +} +struct Outputs { + std::vector> data; + std::vector raw; + explicit Outputs(int n):data(n,std::vector(256,0.f)){ + for(auto& d:data)raw.push_back(d.data()); + } +}; +void validate() { + auto r=base(); + auto kept=prepared(r); + auto reject=[&](SpeakerPlanFault fault){ + auto report=PreparedSpeakerSystem::prepare(r,kept); + assert(report.fault==fault); + assert(kept&&kept->revision()==14); + }; + r.deviceEpoch=0;reject(SpeakerPlanFault::invalidEpoch);r.deviceEpoch=71; + r.crossoverHz={30000.};reject(SpeakerPlanFault::invalidCrossover);r.crossoverHz={1000.}; + r.verifiedPorts[0].identity="DEMO-01";reject(SpeakerPlanFault::invalidPort); + r.verifiedPorts[0].identity="ASIO#37/OUT-1"; + r.outputs={patch("low","invalid",0,0)};reject(SpeakerPlanFault::invalidPort); + r.outputs={patch("low","ASIO#37/OUT-1",0,5)};reject(SpeakerPlanFault::invalidRoute); + r.outputs={patch("low","ASIO#37/OUT-1",0,0),patch("low2","ASIO#37/OUT-1",0,0)}; + reject(SpeakerPlanFault::duplicatePort); + r.outputs={patch("low","ASIO#37/OUT-1",0,0)}; + r.outputs[0].limiterEnabled=false;reject(SpeakerPlanFault::unconfirmedSpeaker); + r.outputs[0].mute=true;r.outputs[0].confirmedSpeakerProfile=false; + assert(prepared(r)->sectionCount()==4); + r.outputs[0].delayMs=600.;reject(SpeakerPlanFault::invalidOutputDsp); + r.outputs[0].delayMs=500.;r.scratchBudgetBytes=512; + reject(SpeakerPlanFault::scratchBudget); + r=base();r.verifiedPorts[1].callbackOrdinal=0; + reject(SpeakerPlanFault::invalidPort); +} +void frequency(double hz,double low,double high) { + auto r=base(); + r.outputs={patch("low L","ASIO#37/OUT-1",0,0), + patch("high L","ASIO#37/OUT-3",0,1), + patch("low R","ASIO#37/OUT-4",1,0), + patch("high R","ASIO#37/OUT-6",1,1)}; + auto system=prepared(r); + std::array left{},right{}; + Outputs output(8); + double sumLo=0.,sumHi=0.,sumInput=0.,sumCombined=0.; + for(int block=0;block<400;++block){ + for(int i=0;i<256;++i){ + const double t=static_cast(block*256+i)/r.sampleRate; + left[i]=static_cast(.25*std::sin(2*pi*hz*t)); + right[i]=left[i]*.5f; + } + assert(system->process(71,14,left.data(),right.data(),output.raw.data(),8,256,true)); + if(block<15)continue; + for(int i=0;i<256;++i){ + const double lo=output.data[0][i],hi=output.data[2][i]; + sumLo+=lo*lo;sumHi+=hi*hi;sumInput+=left[i]*left[i]; + sumCombined+=(lo+hi)*(lo+hi); + assert(std::abs(output.data[3][i]-lo*.5)<.00001); + assert(std::abs(output.data[5][i]-hi*.5)<.00001); + } + } + const auto measuredLow=std::sqrt(sumLo/sumInput); + const auto measuredHigh=std::sqrt(sumHi/sumInput); + const auto summed=std::sqrt(sumCombined/sumInput); + std::cout<<"LR4 "< source{};source.fill(.25f); + assert(!system->process(72,14,source.data(),nullptr,out.raw.data(),8,256,true)); + assert(!system->process(71,15,source.data(),nullptr,out.raw.data(),8,256,true)); + assert(!system->process(71,14,source.data(),nullptr,out.raw.data(),8,257,true)); + assert(!system->process(71,14,source.data(),nullptr,out.raw.data(),8,256,false)); + for(const auto sample:out.data[0])assert(sample==0.f); + std::fill(out.data[0].begin(),out.data[0].end(),.25f); + assert(system->process(71,14,out.raw[0],nullptr,out.raw.data(),8,256,true)); + assert(std::abs(out.data[2][100])<.2f); + for(const auto& lane:out.data)for(const auto sample:lane)assert(std::isfinite(sample)); +} +void delay_fanout_and_mute() { + auto r=base(1,false); + r.outputs={patch("dry","ASIO#37/OUT-1",0,0), + patch("delayed","ASIO#37/OUT-3",0,0,1.5/48.)}; + auto system=prepared(r); + Outputs out(8); + std::array impulse{};impulse[0]=.5f; + assert(system->process(71,14,impulse.data(),nullptr,out.raw.data(),8,256,true)); + assert(std::abs(out.data[0][0]-.5f)<1e-6f); + assert(std::abs(out.data[2][0])<1e-6f); + assert(std::abs(out.data[2][1]-.25f)<1e-6f); + assert(std::abs(out.data[2][2]-.25f)<1e-6f); + r.outputs[0].mute=true;r.outputs[0].limiterEnabled=false; + auto muted=prepared(r); + std::fill(out.data[0].begin(),out.data[0].end(),9.f); + assert(muted->process(71,14,impulse.data(),nullptr,out.raw.data(),8,256,true)); + for(const auto sample:out.data[0])assert(sample==0.f); +} +void digital_ceiling() { + auto r=base(1,false); + r.outputs={patch("full","ASIO#37/OUT-1",0,0)}; + r.outputs[0].gainDb=6.;r.outputs[0].ceilingDbfs=-12.; + auto system=prepared(r); + Outputs out(8); + std::array in{};in.fill(1.f); + assert(system->process(71,14,in.data(),nullptr,out.raw.data(),8,256,true)); + const float ceiling=static_cast(std::pow(10.,-12./20.)); + for(const float sample:out.data[0])assert(sample<=ceiling+1.e-6f); +} +void per_output_peq() { + auto r=base(1,false); + r.outputs={patch("peq","ASIO#37/OUT-1",0,0)}; + r.outputs[0].peq.push_back({1000.,1.,6.}); + auto system=prepared(r); + Outputs out(8); + std::array in{}; + double inPower=0.,outPower=0.; + for(int block=0;block<200;++block){ + for(int i=0;i<256;++i){ + const double time=(block*256+i)/48000.; + in[i]=static_cast(.1*std::sin(2*pi*1000.*time)); + } + assert(system->process(71,14,in.data(),nullptr,out.raw.data(),8,256,true)); + if(block<10)continue; + for(int i=0;i<256;++i){ + inPower+=in[i]*in[i]; + outPower+=out.data[0][i]*out.data[0][i]; + } + } + const auto gain=std::sqrt(outPower/inPower); + assert(gain>1.93&&gain<2.07); // 6 dB peaking EQ, true PCM + r.outputs[0].peq[0].q=0.; + std::unique_ptr rejected=std::move(system); + const auto bad=PreparedSpeakerSystem::prepare(r,rejected); + assert(bad.fault==SpeakerPlanFault::invalidOutputDsp); + assert(rejected&&rejected->destinationCount()==1); // rollback +} + +void polarity_and_eq_band_bypass() { + auto req=base(1,false); + req.outputs={patch("polarity","ASIO#37/OUT-1",0,0), + patch("eq-bypass","ASIO#37/OUT-3",0,0)}; + req.outputs[0].polarityInverted=true; + req.outputs[1].peq.push_back({1000.,1.,6.,false}); + auto system=prepared(req); + Outputs out(8); + std::array input{}; + input.fill(.2f); + assert(system->process(71,14,input.data(),nullptr,out.raw.data(),8,256,true)); + for(int i=0;i<256;++i) { + assert(std::abs(out.data[0][i]+.2f)<.00001f); + assert(std::abs(out.data[2][i]-.2f)<.00001f); + } + assert(out.data[0][255]<0.f&&out.data[2][255]>0.f); + // A bypassed 6 dB EQ must not retain DSP state or affect any channel. + // Verify enabled band peak is about +6 dB after the biquad settles. + req.outputs[0].peq.clear(); + req.outputs[1].peq[0].enabled=true; + system=prepared(req); + double energyIn=0.,energyOut=0.; + for(int block=0;block<100;++block) { + for(int i=0;i<256;++i) { + const double time=static_cast(block*256+i)/req.sampleRate; + input[i]=static_cast(.05*std::sin(2*pi*1000.*time)); + } + assert(system->process(71,14,input.data(),nullptr,out.raw.data(),8,256,true)); + if(block>10)for(int i=0;i<256;++i) { + energyIn+=input[i]*input[i]; + energyOut+=out.data[2][i]*out.data[2][i]; + } + } + const auto measured=std::sqrt(energyOut/energyIn); + assert(measured>1.93&&measured<2.07); +} + +DriverVoltageModel measuredExample() { + DriverVoltageModel m; + m.profileId="TEST-ONLY-NOT-A-CERTIFIED-SPEAKER"; + m.dacFullScaleVrms=2.;m.amplifierVoltageGain=30.; + m.continuousDriverVrms=10.;m.driverPeakVolts=18.; + m.rmsWindowMs=80.;m.releaseMs=40.; + return m; +} +void voltage_model_profile_validation_and_rollback() { + auto request=base(1,false); + request.outputs={patch("tested","ASIO#37/OUT-1",0,0)}; + request.outputs[0].voltageModel=measuredExample(); + auto kept=prepared(request); + auto reject=[&](DriverVoltageModel candidate) { + request.outputs[0].voltageModel=std::move(candidate); + const auto bad=PreparedSpeakerSystem::prepare(request,kept); + assert(bad.fault==SpeakerPlanFault::invalidVoltageModel); + assert(kept&&kept->destinationCount()==1); // prior graph intact + }; + auto model=measuredExample(); + model.dacFullScaleVrms=0.;reject(model); + model=measuredExample();model.amplifierVoltageGain=-1.;reject(model); + model=measuredExample();model.driverPeakVolts=2.;reject(model); + model=measuredExample();model.minimumHighpassHz=23000.;reject(model); + model=measuredExample();model.rmsWindowMs=0.;reject(model); + model=measuredExample();model.releaseMs=std::nan("");reject(model); + model=measuredExample();model.profileId.clear();reject(model); + request.outputs[0].voltageModel=measuredExample(); + request.scratchBudgetBytes=250; + const auto budget=PreparedSpeakerSystem::prepare(request,kept); + assert(budget.fault==SpeakerPlanFault::scratchBudget); + PreparedSpeakerSystem::OutputProtectionReadback reading{}; + assert(kept->outputProtectionReadback(0,reading)&& + reading.voltageModelPrepared); + assert(!kept->outputProtectionReadback(1,reading)); +} +void voltage_peak_rms_recovery_and_channel_isolation() { + auto req=base(1,false); + req.outputs={patch("modelled","ASIO#37/OUT-1",0,0), + patch("legacy","ASIO#37/OUT-3",0,0)}; + req.outputs[0].voltageModel=measuredExample(); + req.outputs[1].ceilingDbfs=0.; + auto system=prepared(req); + Outputs out(8); + std::array in{}; + in.fill(.8f); + // Real repeated float PCM; not a unit test of source string existence. + for(int block=0;block<500;++block) { + assert(system->process(71,14,in.data(),nullptr,out.raw.data(),8,256,true)); + for(int i=0;i<256;++i) { + assert(std::isfinite(out.data[0][i])); + assert(std::abs(out.data[0][i])<.213f); // modelled peak voltage + assert(std::abs(out.data[2][i]-.8f)<1.e-5f); // independent output + } + } + PreparedSpeakerSystem::OutputProtectionReadback status{}; + assert(system->outputProtectionReadback(0,status)); + assert(status.voltageModelPrepared); + assert(status.gainReductionDb>12.f); // thermal-oriented detector actually active + assert(status.preLimitRmsDigital>.7f); + assert(status.outputPeakDigital<.125f); + assert(system->outputProtectionReadback(1,status)); + assert(!status.voltageModelPrepared&&status.gainReductionDb==0.f); + assert(std::abs(status.outputPeakDigital-.8f)<1.e-5f); + // Recover smoothly toward unity with a low level input. + in.fill(.02f); + const float firstBefore=out.data[0][255]; + assert(system->process(71,14,in.data(),nullptr,out.raw.data(),8,256,true)); + const float shortlyAfter=out.data[0][255]; + assert(shortlyAfter<.02f&&shortlyAfterprocess(71,14,in.data(),nullptr,out.raw.data(),8,256,true)); + assert(out.data[0][255]>.019f&&out.data[0][255]<=.020001f); + assert(system->outputProtectionReadback(0,status)&&status.gainReductionDb<.1f); + // Stale callback cannot write to the isolated destination. + out.data[0][0]=.123f; + assert(!system->process(72,14,in.data(),nullptr,out.raw.data(),8,256,true)); + assert(out.data[0][0]==.123f); +} +void voltage_profile_safety_hpf_frequency() { + auto req=base(1,false); + req.outputs={patch("hp","ASIO#37/OUT-1",0,0)}; + auto model=measuredExample(); + model.minimumHighpassHz=120.; + req.outputs[0].voltageModel=model; + auto measure=[&](double hz) { + auto graph=prepared(req); + Outputs out(8); + std::array sine{}; + double inputPower=0.,outputPower=0.; + for(int block=0;block<180;++block) { + for(int i=0;i<256;++i) { + const auto t=static_cast(block*256+i)/req.sampleRate; + sine[i]=static_cast(.04*std::sin(2*pi*hz*t)); + } + assert(graph->process(71,14,sine.data(),nullptr, + out.raw.data(),8,256,true)); + if(block<30)continue; + for(int i=0;i<256;++i) { + inputPower+=sine[i]*sine[i]; + outputPower+=out.data[0][i]*out.data[0][i]; + } + } + return std::sqrt(outputPower/inputPower); + }; + const auto low=measure(30.),high=measure(1200.); + assert(low<.01); // genuine LR4 24dB/oct safety HPF + assert(high>.97&&high<1.03); +} + +int main(){ + validate(); + frequency(100.,1.,0.); + frequency(1000.,.5,.5); + frequency(10000.,0.,1.); + hardware_guard_and_alias();delay_fanout_and_mute();digital_ceiling();per_output_peq();polarity_and_eq_band_bypass(); + voltage_model_profile_validation_and_rollback(); + voltage_peak_rms_recovery_and_channel_isolation(); + voltage_profile_safety_hpf_frequency(); + for(int ways=1;ways<=4;++ways) + assert(prepared(base(ways))->sectionCount()==static_cast(2*ways)); + std::cout<<"PASS LMS prepared PCM: LR4, routing, epoch, DSP and delay\n"; +} diff --git a/tests/lms_synthetic_realtime_budget_test.cpp b/tests/lms_synthetic_realtime_budget_test.cpp new file mode 100644 index 000000000..d44111a69 --- /dev/null +++ b/tests/lms_synthetic_realtime_budget_test.cpp @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Synthetic audio-thread allocation/performance fixture; never ASIO FAT proof. +#include "../engine/lms/PreparedSpeakerSystem.h" +#include +#include +#ifdef NDEBUG +#undef NDEBUG // Always execute PCM assertions, even in release CTest. +#endif +#include +#include +#include +#include +#include +#include +#include +static std::atomic allocations{0}; +void* operator new(std::size_t n){ + ++allocations; + if(void* p=std::malloc(n))return p; + throw std::bad_alloc(); +} +void* operator new[](std::size_t n){ + ++allocations; + if(void* p=std::malloc(n))return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept{std::free(p);} +void operator delete[](void* p) noexcept{std::free(p);} +void operator delete(void* p,std::size_t) noexcept{std::free(p);} +void operator delete[](void* p,std::size_t) noexcept{std::free(p);} +int main(){ + using namespace armix::lms; + SpeakerSystemRequest r; + r.deviceEpoch=1;r.graphRevision=1;r.sampleRate=48000.; + r.maxFrames=256;r.activeOutputChannels=16;r.ways=4;r.stereo=true; + r.crossoverHz={80.,300.,2500.}; + for(int i=0;i<8;++i){ + const auto pin="DRIVER#A/"+std::to_string(i); + r.verifiedPorts.push_back({pin,i}); + OutputPatch o; + o.outputId="speaker-"+std::to_string(i);o.portIdentity=pin; + o.sourceSide=i/4;o.section=i%4;o.delayMs=i*2.; + o.mute=false;o.limiterEnabled=true; + o.confirmedSpeakerProfile=true;o.ceilingDbfs=-3.; + o.peq={{120.,1.1,2.},{800.,.75,-3.},{3500.,1.2,1.5}}; + r.outputs.push_back(o); + } + std::unique_ptr graph; + assert(PreparedSpeakerSystem::prepare(r,graph).ok()); + std::array sourceL{},sourceR{}; + std::vector> output(16,std::vector(256)); + std::array pointers{}; + for(int i=0;i<16;++i)pointers[i]=output[i].data(); + for(int i=0;i<256;++i){ + sourceL[i]=std::sin(static_cast(i)*.05f)*.3f; + sourceR[i]=std::cos(static_cast(i)*.07f)*.3f; + } + assert(graph->process(1,1,sourceL.data(),sourceR.data(),pointers.data(),16,256,true)); + const auto before=allocations.load(); + const auto started=std::chrono::steady_clock::now(); + for(int block=0;block<1500;++block) + assert(graph->process(1,1,sourceL.data(),sourceR.data(),pointers.data(),16,256,true)); + const auto micros=std::chrono::duration_cast( + std::chrono::steady_clock::now()-started).count(); + assert(allocations.load()==before); + for(int c=0;c<8;++c)for(float sample:output[c]) + assert(std::isfinite(sample)&&std::abs(sample)<1.001f); + std::cout<<"PASS LMS: 8 output, stereo 4-way, 1500 x 256 PCM frames, " + <<"no realtime heap, synthetic duration "<{ + const s=M.createSystem({ways:3,ports:M.demoPorts(6)}); + assert.deepEqual(s.sections.map(x=>x.name),[ + "LOW L","MID L","HIGH L","LOW R","MID R","HIGH R"]); + assert.deepEqual(s.routes,{}); + assert.equal(s.applied,false); + for(const p of s.ports){ + assert.equal(s.dsp[p].muted,true); + assert.equal(s.dsp[p].limiterEnabled,false); + assert.equal(s.dsp[p].limiterThresholdDb,null); + } + assert.equal(M.validateSystem(s),true); +}); + +test("crossover ways are flexible and structural change clears ALL patch/output safety drafts",()=>{ + const s=M.createSystem({ways:2,ports:M.demoPorts(4)}); + const mapped=M.withRoute(s,s.ports[0],"L:1"); + const edited=M.withDsp(mapped,s.ports[0],{gainDb:-6,muted:false}); + const next=M.withWays(edited,3); + assert.equal(next.sections.length,6); + assert.equal(next.ports.length,4); + assert.deepEqual(next.routes,{}); + assert.equal(next.dsp[s.ports[0]].gainDb,0); + assert.equal(next.dsp[s.ports[0]].muted,true); + assert.equal(next.applied,false); + assert.equal(edited.ways,2); // immutable transaction, old accepted draft intact + assert.equal(edited.routes[s.ports[0]],"L:1"); + const sixteen=M.withWays(next,16); + assert.equal(sixteen.sections.length,32); + assert.equal(sixteen.cutoffsHz.length,15); + assert.equal(M.validateSystem(sixteen),true); +}); + +test("routing one output is exclusive; one source may fan out to multiple destinations",()=>{ + let s=M.createSystem({ways:3,ports:M.demoPorts(6)}); + s=M.withRoute(s,"DEMO-01","L:1"); + s=M.withRoute(s,"DEMO-02","L:1"); + assert.equal(s.routes["DEMO-02"],"L:1"); + s=M.withRoute(s,"DEMO-01","L:2"); + assert.equal(s.routes["DEMO-01"],"L:2"); + assert.equal(Object.keys(s.routes).length,2); + s=M.withRoute(s,"DEMO-01","L:2"); // clicking active crosspoint disconnects + assert.equal(s.routes["DEMO-01"],undefined); + assert.throws(()=>M.withRoute(s,"DEMO-01","L:55"),/unknown crossover/); + assert.throws(()=>M.withRoute(s,"ASIO 1","L:1"),/unknown output/); +}); + +test("port discovery changes never silently reuse ordinal pin assignments",()=>{ + let s=M.createSystem({ways:2,ports:["device-A#1","device-A#2"]}); + s=M.withRoute(s,"device-A#1","L:1"); + s=M.withPorts(s,["device-B#1","device-B#2"]); + assert.deepEqual(s.routes,{}); + assert.equal(s.dsp["device-B#1"].muted,true); + assert.equal(s.ports[0],"device-B#1"); + assert.equal(s.applied,false); + assert.throws(()=>M.createSystem({ports:["same","same"]}),/duplicate/); +}); + +test("DLMS explicit ASIO reassignment retains tuning, never auto-maps or auto-unmutes",()=>{ + let s=M.createSystem({ways:2,ports:["DEMO-01","DEMO-02","DEMO-03"]}); + s=M.withRoute(s,"DEMO-01","L:1"); + s=M.withDsp(s,"DEMO-01",{gainDb:-8,delayMs:23.5, + limiterEnabled:true,limiterThresholdDb:-14,muted:false,polarity:"invert"}); + s=M.withPeqBand(s,"DEMO-01",0,{frequencyHz:110,q:.9,gainDb:-2}); + s=M.withPosition(s,"DEMO-01",-5,12); + const ports=["ASIO/verified1","ASIO/verified2"]; + assert.throws(()=>M.reassignVerifiedPorts(s,ports,{}),/Choose at least one/); + assert.throws(()=>M.reassignVerifiedPorts(s,ports,{"DEMO-02":ports[0]}),/Assign DEMO-01/); + assert.throws(()=>M.reassignVerifiedPorts(s,ports,{"DEMO-01":ports[0],"DEMO-02":ports[0]}),/Duplicate physical/); + assert.throws(()=>M.reassignVerifiedPorts(s,ports,{"DEMO-01":"untrusted"}),/Unknown output/); + assert.throws(()=>M.reassignVerifiedPorts(s,["DEMO-01"],{"DEMO-01":"DEMO-01"}),/verified port/); + const next=M.reassignVerifiedPorts(s,ports,{"DEMO-01":ports[1]}); + assert.equal(s.routes["DEMO-01"],"L:1"); + assert.equal(s.dsp["DEMO-01"].muted,false); + assert.deepEqual(next.routes,{[ports[1]]:"L:1"}); + assert.equal(next.dsp[ports[1]].muted,true); + assert.equal(next.dsp[ports[1]].gainDb,-8); + assert.equal(next.dsp[ports[1]].delayMs,23.5); + assert.equal(next.dsp[ports[1]].polarity,"invert"); + assert.equal(next.dsp[ports[1]].limiterThresholdDb,-14); + assert.equal(next.dsp[ports[1]].peq[0].gainDb,-2); + assert.equal(next.positions[ports[1]].y,12); + assert.deepEqual(next.dsp[ports[0]].peq,[]); + assert.equal(next.revision,s.revision+1); + assert.equal(next.applied,false); + assert.equal(M.validateSystem(next),true); +}); + +test("boundaries must be ordered and physically plausible; invalid edit rolls back",()=>{ + const s=M.createSystem({ways:3}); + assert.deepEqual(s.cutoffsHz,[120,2400]); + const edited=M.withCutoff(s,1,3000); + assert.deepEqual(edited.cutoffsHz,[120,3000]); + assert.deepEqual(s.cutoffsHz,[120,2400]); + assert.throws(()=>M.withCutoff(s,0,3000),/strictly ordered/); + assert.throws(()=>M.withCutoff(s,0,Infinity),/crossover frequency/); + assert.throws(()=>M.withCutoff(s,0,0),/crossover frequency/); +}); + +test("visual distance alignment returns additional geometric delay for nearer speaker",()=>{ + let s=M.createSystem({ways:1,ports:["far","near"]}); + s=M.withListener(s,0,0); + s=M.withPosition(s,"far",0,20); + s=M.withPosition(s,"near",0,10); + const values=M.alignment(s); + assert.equal(values[0].additionalMs,0); + assert.ok(Math.abs(values[1].additionalMs-10000/343)<1e-8); + assert.equal(values[1].distanceM,10); + assert.equal(s.dsp.near.delayMs,0); // cannot silently write acoustic estimate + assert.throws(()=>M.withPosition(s,"near",NaN,0),/speaker x/); +}); + +test("output DSP is bounded, muted by default and never grants hardware authority",()=>{ + const s=M.createSystem({ports:["out1"]}); + const next=M.withDsp(s,"out1",{gainDb:-3,limiterThresholdDb:-12}); + assert.equal(next.dsp.out1.limiterEnabled,false); + assert.equal(next.applied,false); + assert.throws(()=>M.withDsp(s,"out1",{gainDb:30}),/gainDb/); + assert.throws(()=>M.withDsp(s,"out1",{limiterThresholdDb:3}),/limiterThresholdDb/); + assert.throws(()=>M.withDsp(s,"out1",{unsafeHardwareEnable:true}),/unknown DSP/); +}); + + +test("native-calculated LR4 amplitude response is complementary at split",()=>{ + const low=M.crossoverMagnitude([1000],0,1000); + const high=M.crossoverMagnitude([1000],1,1000); + assert.ok(Math.abs(low-.5)<.002,(low).toString()); + assert.ok(Math.abs(high-.5)<.002,(high).toString()); + assert.ok(M.crossoverMagnitude([1000],0,100)>.99); + assert.ok(M.crossoverMagnitude([1000],1,100)<.01); + assert.throws(()=>M.crossoverMagnitude([1000],0,25000),/plot request/); +}); + +test("EQ band state and graph match native RBJ peak filter math",()=>{ + const original=M.createSystem({ways:2,ports:["port"]}); + const edited=M.withPeqBand(original,"port",0, + {frequencyHz:1000,q:1,gainDb:6,enabled:true}); + assert.equal(original.dsp.port.peq.length,0); + assert.equal(edited.dsp.port.peq[0].gainDb,6); + const atPeak=M.peqMagnitude(edited.dsp.port.peq,1000); + assert.ok(Math.abs(atPeak-6)<.01,atPeak.toString()); + assert.equal(M.peqMagnitude([{...edited.dsp.port.peq[0],enabled:false}],1000),0); + assert.throws(()=>M.withPeqBand(edited,"port",1,{q:0}),/PEQ Q/); + assert.throws(()=>M.withPeqBand(edited,"port",2,{}),/PEQ gap/); + assert.throws(()=>M.withPeqBand(edited,"port",1,{notAllowed:1}),/unknown PEQ/); + const removed=M.withoutPeqBand(edited,"port",0); + assert.deepEqual(removed.dsp.port.peq,[]); + assert.equal(removed.applied,false); +}); + +test("visual alignment explicitly copies geometric offsets to disconnected drafts",()=>{ + let s=M.createSystem({ways:2,ports:["far","near"]}); + s=M.withListener(s,0,0); + s=M.withPosition(s,"far",0,30); + s=M.withPosition(s,"near",0,10); + const prior=s; + const planned=M.withSuggestedDelays(s); + assert.equal(prior.dsp.near.delayMs,0); + assert.equal(planned.dsp.far.delayMs,0); + assert.ok(Math.abs(planned.dsp.near.delayMs-58.31)<.015); + assert.equal(planned.applied,false); + assert.deepEqual(planned.routes,{}); + assert.equal(planned.dsp.near.muted,true); + const waysChanged=M.withWays(planned,3); + assert.equal(waysChanged.dsp.near.delayMs,0); +}); + +test("real five-workspace interactions show curves, PEQ and review rather than applying",()=>{ + const fs=require("node:fs"); + const ui=fs.readFileSync(require.resolve("../site/preview-v2/assets/lms-workspace.js"),"utf8"); + const callbacks={root:{},launcher:{}}; + const root={dataset:{},hidden:true,innerHTML:"", + addEventListener(type,fn){callbacks.root[type]=fn}}; + const launcher={addEventListener(type,fn){callbacks.launcher[type]=fn}, + setAttribute(k,v){this[k]=v},textContent:""}; + const app={classList:{toggle(){}}}; + const document={getElementById(id){return id==="lmsWorkspace"?root: + id==="lmsOpen"?launcher:null}, + querySelector(q){return q===".app"?app:null}}; + const window={ArSonMixLmsModel:M,addEventListener(){}}; + new Function("window","document",ui)(window,document); + const click=dataset=>callbacks.root.click({target:{closest:()=>({dataset})}}); + callbacks.launcher.click(); + assert.ok(root.innerHTML.includes("Speaker system")); + click({page:"crossover"}); + assert.ok(root.innerHTML.includes("LR4 · 24 dB/oct")); + assert.ok(root.innerHTML.includes("Calculated electrical LR4")); + click({page:"processing"}); + assert.ok(root.innerHTML.includes("Parametric EQ")); + click({action:"addPeq"}); + assert.ok(root.innerHTML.includes("EQ 1")); + callbacks.root.change({target:{dataset:{peqField:"gainDb"},value:"6"}}); + assert.ok(root.innerHTML.includes("6.0 dB")); + click({dspTab:"protection"}); + assert.ok(root.innerHTML.includes("NOT CALIBRATED")); + click({page:"alignment"}); + assert.ok(root.innerHTML.includes("Suggested")); + click({action:"planDelay"}); + assert.ok(root.innerHTML.includes("Review structural change")); + click({action:"cancel"}); + assert.ok(!root.innerHTML.includes("Review structural change")); + click({action:"planDelay"}); + click({action:"confirm"}); + assert.ok(root.innerHTML.includes("revision ")); + assert.ok(root.innerHTML.includes("Not applied to audio")); + assert.equal(launcher["aria-pressed"],"true"); +}); diff --git a/tests/lms_verified_device_binder_test.cpp b/tests/lms_verified_device_binder_test.cpp new file mode 100644 index 000000000..ab1d55c4f --- /dev/null +++ b/tests/lms_verified_device_binder_test.cpp @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/lms/NativeSpeakerDeviceBinder.h" +#ifdef NDEBUG +#undef NDEBUG +#endif +#include +#include +using namespace armix::lms; +static TrustedSpeakerDeviceView device(){ + TrustedSpeakerDeviceView d; + d.deviceEpoch=13;d.graphRevision=7;d.mainChannelId=99; + d.backend="ASIO";d.deviceIdentity="ASIO:driver-GUID-OR-PIN-PROVENANCE"; + d.sampleRate=48000.;d.callbackOutputs=8; + d.mainL=0;d.mainR=1;d.monitorL=2;d.monitorR=3; + d.acceptedPcm=d.exactDeviceMask=d.allOutputsDisarmed=true; + for(int i=0;i<8;++i) + d.actualEnabledPorts.push_back({"ASIO:pin-physical-"+std::to_string(i*2),i}); + return d; +} +static SpeakerSystemRequest proposal(const TrustedSpeakerDeviceView& d){ + SpeakerSystemRequest p; + p.deviceEpoch=d.deviceEpoch;p.graphRevision=d.graphRevision; + p.sampleRate=d.sampleRate;p.activeOutputChannels=d.callbackOutputs; + p.maxFrames=256;p.ways=2;p.stereo=true;p.crossoverHz={1400.}; + // Browser forges a DIFFERENT callback ordinal for the genuine identity: + p.verifiedPorts={{d.actualEnabledPorts[4].identity,0}}; + OutputPatch a; + a.outputId="LOW L";a.portIdentity=d.actualEnabledPorts[4].identity; + a.sourceSide=0;a.section=0;a.mute=true; + p.outputs.push_back(a); + return p; +} +int main(){ + auto d=device();auto p=proposal(d); + SpeakerBoundDraft out; + const auto accepted=NativeSpeakerDeviceBinder::bind(p,d,99,out); + assert(accepted.ok()); + assert(out.verifiedInventory.enabledOutputPorts.size()==8); + assert(out.verifiedRequest.verifiedPorts.size()==8); + assert(out.verifiedRequest.verifiedPorts[4].callbackOrdinal==4); + assert(p.verifiedPorts[0].callbackOrdinal==0); + assert(out.verifiedInventory.mainL==0 && out.verifiedInventory.allOutputsDisarmed); + const auto original=out.verifiedRequest.outputs[0].portIdentity; + auto reject=[&](SpeakerBindFault wanted){ + const auto res=NativeSpeakerDeviceBinder::bind(p,d,99,out); + assert(!res.ok()&&res.fault==wanted); + assert(out.verifiedRequest.outputs[0].portIdentity==original); + assert(out.verifiedInventory.enabledOutputPorts[4].callbackOrdinal==4); + }; + d.exactDeviceMask=false;reject(SpeakerBindFault::unverifiedDevice);d.exactDeviceMask=true; + d.allOutputsDisarmed=false;reject(SpeakerBindFault::unverifiedDevice);d.allOutputsDisarmed=true; + d.backend="Windows Audio";reject(SpeakerBindFault::unverifiedDevice);d.backend="ASIO"; + p.deviceEpoch=12;reject(SpeakerBindFault::staleDevice);p.deviceEpoch=13; + p.graphRevision=6;reject(SpeakerBindFault::staleGraph);p.graphRevision=7; + d.mainChannelId=98;reject(SpeakerBindFault::invalidSource);d.mainChannelId=99; + p.sampleRate=44100.;reject(SpeakerBindFault::changedFormat);p.sampleRate=48000.; + p.outputs[0].mute=false;p.outputs[0].limiterEnabled=true; + p.outputs[0].confirmedSpeakerProfile=true; + reject(SpeakerBindFault::invalidLoudspeakerDraft); + p.outputs[0].mute=true; + p.outputs[0].portIdentity="DEMO-04"; + reject(SpeakerBindFault::invalidPhysicalPin); + p.outputs[0].portIdentity=d.actualEnabledPorts[0].identity; + reject(SpeakerBindFault::invalidPhysicalPin); // MAIN collision + p.outputs[0].portIdentity=d.actualEnabledPorts[4].identity; + d.otherOccupiedOrdinals={4};reject(SpeakerBindFault::invalidPhysicalPin); + d.otherOccupiedOrdinals.clear(); + d.actualEnabledPorts[5].callbackOrdinal=4; + reject(SpeakerBindFault::invalidPhysicalPin); + d.actualEnabledPorts[5].callbackOrdinal=5; + assert(NativeSpeakerDeviceBinder::bind(p,d,99,out).ok()); + assert(!NativeSpeakerOutputReservation::preflight( + out.verifiedRequest,out.verifiedInventory,99).mayWritePhysicalAudio); + std::puts("PASS LMS M6 verified device binder: browser ordinals discarded, actual ASIO pins fenced, rollback, physical writes forbidden"); +} diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index a756dd34c..636365cde 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -1310,7 +1310,87 @@ static void verifyChannelInputGainSessionRoundtrip() { assert(!Codec::decode(juce::JSON::toString(invalid,false),restored)); } + +static void verifyLmsOfflineSmixRoundtrip() { + using namespace armix::lms; + auto document=makeSession(); + SpeakerSystemRequest accepted; + accepted.deviceEpoch=54;accepted.graphRevision=89; + accepted.sampleRate=48000.;accepted.ways=2;accepted.stereo=true; + accepted.crossoverHz={1200.}; + OutputPatch way; + way.outputId="HF-L";way.portIdentity="ASIO-DRIVER:PORT-7"; + way.section=1;way.sourceSide=0;way.mute=false; + way.gainDb=-6.;way.ceilingDbfs=-12.; + way.peq={{3200.,.7,-2.,true}}; + way.confirmedSpeakerProfile=true; + way.voltageModel=DriverVoltageModel{"NOT-CALIBRATED",2.,20.,15.,24.,100.,600.,160.}; + accepted.outputs={way}; + OfflineSpeakerDraft saved; + assert(OfflineSpeakerDraftPolicy::detach(accepted,saved)); + document.lmsDraft=saved; + const auto text=Codec::encode(document); + assert(text.isNotEmpty() && text.contains("arsonmix.lms.offline-draft.v1")); + // Hard guarantee: the SESSION extension cannot contain any ASIO binding + // or voltage model, including after a file save / reopen. + const auto raw=juce::JSON::parse(text).getProperty("lmsDraft",{}); + assert(raw.isObject()); + assert(raw.getProperty("deviceEpoch",{}).isVoid()); + assert(raw.getProperty("hardwareApplied",{}).isVoid()); + const auto storedOutputs=raw.getProperty("outputs",{}); + const auto* outputs=storedOutputs.getArray(); + assert(outputs && outputs->size()==1); + assert(outputs->getReference(0).getProperty("portIdentity",{}).isVoid()); + assert(outputs->getReference(0).getProperty("voltageModel",{}).isVoid()); + MixerSessionDocument reopened; + assert(Codec::decode(text,reopened)); + assert(reopened.lmsDraft && reopened.lmsDraft->outputs.size()==1); + SpeakerSystemRequest disconnected; + assert(OfflineSpeakerDraftPolicy::restoreDisconnected(*reopened.lmsDraft,disconnected)); + assert(disconnected.deviceEpoch==0 && disconnected.graphRevision==0); + assert(disconnected.verifiedPorts.empty()); + assert(disconnected.outputs[0].mute && disconnected.outputs[0].portIdentity.empty()); + assert(disconnected.outputs[0].peq.size()==1); + // Old v1 .smix has no LMS extension; it must still decode identically. + auto legacy=makeSession();legacy.lmsDraft.reset(); + MixerSessionDocument old; + assert(Codec::decode(Codec::encode(legacy),old)&&!old.lmsDraft); + + const auto checkTamper=[&](const char* key,const juce::var& value, + bool nested) { + auto test=juce::JSON::parse(text); + auto draft=test.getProperty("lmsDraft",{}); + if(nested) { + const auto storedOutputs=draft.getProperty("outputs",{}); + auto* out=storedOutputs.getArray(); + assert(out && out->size()==1); + out->getReference(0).getDynamicObject()->setProperty(key,value); + } else draft.getDynamicObject()->setProperty(key,value); + MixerSessionDocument rejected=old; + assert(!Codec::decode(juce::JSON::toString(test,false),rejected)); + assert(!rejected.lmsDraft.has_value()); + }; + checkTamper("hardwareApplied",true,false); + checkTamper("deviceEpoch","54",false); + checkTamper("portIdentity","ASIO-DRIVER:PORT-7",true); + checkTamper("mute",false,true); + checkTamper("confirmedSpeakerProfile",true,true); + checkTamper("version",2,false); + checkTamper("ceilingDbfs",-99.0,true); + // Native file store uses the SAME codec and staged hash validation. + const auto file=juce::File::getSpecialLocation(juce::File::tempDirectory) + .getChildFile("arsonmix-lms-m11-"+juce::Uuid().toDashedString()+".smix"); + assert(NativeMixerSessionStore::writeFile(file,document,{}).isEmpty()); + MixerSessionDocument onDisk; + std::vector states; + assert(NativeMixerSessionStore::readFile(file,onDisk,states).isEmpty()); + assert(onDisk.lmsDraft && onDisk.lmsDraft->outputs[0].outputId=="HF-L"); + assert(onDisk.lmsDraft->outputs[0].portIdentity.empty()); + assert(file.deleteFile()); +} + int main(){ + verifyLmsOfflineSmixRoundtrip(); verifyChannelInputGainSessionRoundtrip(); verifyDurableNativeFxPowerIdentity(); verifyHotkeyDocumentIdentityAndMigration(); diff --git a/tests/pages_controls_v6_smoke.py b/tests/pages_controls_v6_smoke.py index e9b824cb6..4dcf69a55 100644 --- a/tests/pages_controls_v6_smoke.py +++ b/tests/pages_controls_v6_smoke.py @@ -38,13 +38,16 @@ def assert_ownership(): # Restore only the immutable CSS owner; the live page may legitimately # evolve after V26 (WIRE/FX) without changing hardware key source bytes. # Still verifies every V26 owner fingerprint and V25 migrated material. - from css_v26_restore import restore_owner,manifest as v26_manifest + from css_v26_restore import restore_owner,historical_v26_owner,manifest as v26_manifest from css_v25_restore import manifest as v25_manifest original_v25_key=restore_owner(css,v26_manifest()["sources"]["mixer-control-keys.css"]) v30=v25_manifest()["movedCss"] assert original_v25_key.startswith(v30) modern_v6=original_v25_key[len(v30):] - assert css.endswith(modern_v6),"V6 modern MUTE/SOLO/PFL CSS changed" + # Historical V26 source is byte-exact after the *one* verified PFL + # runtime correction. No other CSS edit may pass the owner fingerprint. + assert 'data-hw-kind="pfl"]{--mx-hw-led:101,210,236}' in css + assert historical_v26_owner(css,v26_manifest()["sources"]["mixer-control-keys.css"]).endswith(modern_v6),"V6 modern MUTE/SOLO/PFL CSS changed" assert css.count("!important")-modern_v6.count("!important")==83 assert modern_v6.count("!important")<=14, "V6 key owner priority budget regressed" @@ -79,7 +82,10 @@ async def assert_mixer(page, width): background:s.backgroundImage,focus:e.getAttribute('aria-label') }; })""") - assert [d["kind"] for d in details]==["mute","solo","cue"],details + # HTML hardware kind is the operator-facing PFL key, while its + # existing native action remains 'cue' for the monitoring contract. + # Never normalize the visual PFL back to cue or blindly alter the GUI. + assert [d["kind"] for d in details]==["mute","solo","pfl"],details assert [d["action"] for d in details]==["mute","solo","cue"],details assert [d["label"] for d in details]==["MUTE","SOLO","PFL"],details assert [d["led"] for d in details]==["255,78,90","255,207,68","101,210,236"],details diff --git a/tests/pages_inter_utility_v7_smoke.py b/tests/pages_inter_utility_v7_smoke.py index 14762750b..42cf1a699 100644 --- a/tests/pages_inter_utility_v7_smoke.py +++ b/tests/pages_inter_utility_v7_smoke.py @@ -117,14 +117,25 @@ async def visual(page,width): if width==1680: await page.screenshot(path='pages-v7-embedded-inter-utility-1680.png') # MUTE is an independent CSS/HTML caption; SOLO/PFL retain SVG masks. - for k in ('mute','solo','cue'): + # The accepted hardware key identity is 'pfl'; its action is 'cue'. + # Never confuse data-hw-kind with the internal click-handler action. + for k in ('mute','solo','pfl'): key=row.locator(f'.mx-hw-row button[data-hw-kind="{k}"]') + # FX/FORMAT toggles asynchronously re-render this strip; wait for the + # post-render DOM instead of sampling a transient detached key. + await key.wait_for(state="attached",timeout=6000) assert await key.count()==1 if k=='mute': assert await key.locator('.mx-mute-face .mx-mute-legend').inner_text()=='MUTE' assert await key.locator('svg,img').count()==0 else: - assert await key.locator('svg.mx-hw-face mask text').count()==1 + # The SVG is inserted by the one authoritative resize-aware hardware + # renderer after the button enters the DOM. Assert the real mask and + # embossed legend, not merely the presence of an inert button. + legend=key.locator('svg.mx-hw-face mask text') + await legend.wait_for(state="attached",timeout=6000) + assert await legend.count()==1 + assert (await legend.text_content())==('PFL' if k=='pfl' else 'SOLO') async def main(): source_contract() diff --git a/tests/pages_lms_five_workspaces_smoke.py b/tests/pages_lms_five_workspaces_smoke.py new file mode 100644 index 000000000..ad16054a4 --- /dev/null +++ b/tests/pages_lms_five_workspaces_smoke.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Real Chromium UX FAT for the ONE canonical ArSonMix /preview/ LMS workspace. +No fake ASIO, audio, protection, or hardware ACK claims. +""" +from pathlib import Path +import subprocess,sys,tempfile +from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console + +ROOT=Path(__file__).resolve().parents[1] + +def main(): + with tempfile.TemporaryDirectory(prefix="arsonmix-lms-ui-") as name: + target=Path(name)/"dist" + subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), + "--out",str(target),"--sha","lms-ui-exact-source", + "--branch","lms"],cwd=ROOT,check=True,capture_output=True,text=True) + public=published_console(target) + with sync_playwright() as pw: + browser=pw.chromium.launch(headless=True) + for width in (1366,1680): + page=browser.new_page(viewport={"width":width,"height":900}) + errors=[] + page.on("pageerror",lambda e:errors.append(str(e))) + page.goto(public.as_uri()) + speaker=page.locator("#lmsOpen") + assert speaker.count()==1,"one LMS entrypoint inside approved mixer" + speaker.click() + body=page.locator("#lmsWorkspace") + assert body.is_visible() and page.locator(".app.lms-active").count()==1 + assert body.locator(".lms-nav button").count()==5 + assert "DESIGN ONLY" in body.inner_text() + assert "OUTPUT DISCONNECTED" in body.inner_text() + assert page.locator(".console-pane").is_hidden() + assert not body.evaluate("(el)=>!!el.querySelector('audio,video,iframe')"), \ + "LMS cannot instantiate any competing audio graph or renderer" + + body.locator('button[data-page="crossover"]').click() + assert body.locator(".lms-frequency path").count()==3 + before=body.locator(".lms-frequency path").first.get_attribute("d") + body.locator("#lms-x0").fill("180") + body.locator("#lms-x0").press("Tab") + after=body.locator(".lms-frequency path").first.get_attribute("d") + assert before!=after,"Crossover must plot recalculated LR4, not static rectangles" + assert "48 kHz" in body.inner_text() + if width==1680: + page.screenshot(path="pages-lms-crossover-1680.png",full_page=False) + body.locator("#lms-way").select_option("4") + assert "Review structural change" in body.inner_text() + body.locator('[data-action="confirm"]').click() + assert body.locator(".lms-frequency path").count()==4 + + body.locator('button[data-page="matrix"]').click() + matrix=body.locator(".lms-matrix") + assert matrix.locator("tbody tr").count()==8 + first=matrix.locator('[data-route-port="DEMO-01"][data-route-section="L:1"]') + first.click() + assert matrix.locator('[data-route-port="DEMO-01"][data-route-section="L:1"]').get_attribute("aria-pressed")=="true" + another=matrix.locator('[data-route-port="DEMO-01"][data-route-section="L:2"]') + another.click() + assert matrix.locator('[data-route-port="DEMO-01"][data-route-section="L:2"]').get_attribute("aria-pressed")=="true" + assert matrix.locator('[data-route-port="DEMO-01"][data-route-section="L:1"]').get_attribute("aria-pressed")=="false", \ + "one physical destination cannot silently sum two crossover sections" + body.locator('button[data-page="processing"]').click() + assert "Parametric EQ" in body.inner_text() + body.locator('[data-action="addPeq"]').click() + assert body.locator('[data-select-band="0"]').count()==1 + before=body.locator(".lms-frequency path").first.get_attribute("d") + body.locator('[data-peq-field="gainDb"]').fill("6") + body.locator('[data-peq-field="gainDb"]').press("Tab") + after=body.locator(".lms-frequency path").first.get_attribute("d") + assert before!=after,"EQ must plot real biquad response" + if width==1680: + page.screenshot(path="pages-lms-eq-1680.png",full_page=False) + body.locator('[data-dsp-tab="protection"]').click() + assert "NOT CALIBRATED" in body.inner_text() + + body.locator('button[data-page="alignment"]').click() + assert body.locator("#lms-room-svg").count()==1 + assert "Suggested" in body.inner_text() + body.locator("#lms-align-port").select_option("DEMO-06") + assert "ms" in body.inner_text() + body.locator('[data-action="planDelay"]').click() + assert "Review structural change" in body.inner_text() + body.locator('[data-action="cancel"]').click() + body.locator('[data-action="planDelay"]').click() + body.locator('[data-action="confirm"]').click() + if width==1680: + page.screenshot(path="pages-lms-alignment-1680.png",full_page=False) + body.locator('button[data-page="processing"]').click() + body.locator('[data-dsp-tab="level"]').click() + delay=float(body.locator("#lms-delay").input_value()) + assert delay>0,"Nearer speaker requires positive extra delay draft" + assert "DESIGN ONLY" in body.inner_text() + assert not errors,(width,errors) + speaker.click() + assert body.is_hidden() and page.locator(".app.lms-active").count()==0 + assert page.locator(".console-pane").is_visible() + page.close() + browser.close() + print("PASS LMS canonical /preview/: 5 pages, calculated LR4/PEQ curves, exclusive patch," + " draft geometry, fail-closed no native ACK; 2 viewport Chromium UX") + +if __name__=="__main__": + main() diff --git a/tests/preview_v2_v7_visual_smoke.py b/tests/preview_v2_v7_visual_smoke.py index 9f9f4d10e..46dd7c2f3 100644 --- a/tests/preview_v2_v7_visual_smoke.py +++ b/tests/preview_v2_v7_visual_smoke.py @@ -41,9 +41,18 @@ def audit_geometry(page, title): const b=getComputedStyle(bottom).borderBottomColor; if(a!==b)problems.push('top/bottom channel color mismatch '+tag); } + // MASTER deliberately has MUTE+SOLO only: PFL needs a separate + // monitor bus and must never pretend to audition a loudspeaker + // or create a feedback path back into MAIN. Non-master strips + // (audio, bus, FX return) retain all three physical keys. const controls=[...t.querySelectorAll('.switch-section.mx-hw-row > button.mx-hw-key')]; - if(controls.length!==3)problems.push('MUTE/SOLO/PFL count !=3 '+tag); - else { + const expected=t.classList.contains('master')? + ['mute','solo']:['mute','solo','pfl']; + const kinds=controls.map(c=>c.dataset.hwKind); + if(kinds.join(',')!==expected.join(',')) + problems.push('MUTE/SOLO/PFL kind/count mismatch '+tag+ + ' expected '+expected.join(',')+' actual '+kinds.join(',')); + if(controls.length===expected.length) { if(Math.max(...controls.map(c=>r(c).width))-Math.min(...controls.map(c=>r(c).width))>1.8) problems.push('inconsistent V6 button widths '+tag); if(Math.max(...controls.map(c=>r(c).top))-Math.min(...controls.map(c=>r(c).top))>1) diff --git a/tests/single_preview_publication_contract_test.py b/tests/single_preview_publication_contract_test.py index c9e51060c..1510a1a82 100644 --- a/tests/single_preview_publication_contract_test.py +++ b/tests/single_preview_publication_contract_test.py @@ -1,12 +1,13 @@ """Fail closed: GitHub Pages must expose ONE approved ArSonMix GUI at /preview/.""" from pathlib import Path -import json, re, sys, hashlib, shutil, tempfile +import json, re, sys, hashlib, shutil, tempfile, subprocess sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts')) from compile_approved_css import LINK, optimize_css, compile_runtime_bundle, link_runtime_bundle, RUNTIME_CSS from approved_fx_rack_power import apply_authoritative_fx_power from approved_fx_rack_interaction import apply_fx_rack_interaction from compose_native_peq import apply_native_peq from compose_operator_ux import apply_operator_ux +from compose_lms import apply_lms ROOT=Path(__file__).resolve().parents[1] DST=Path(sys.argv[1]).resolve() if len(sys.argv)>1 else ROOT/'dist-pages' gui=DST/'preview' @@ -55,6 +56,7 @@ def require(ok,why): # then run the existing operator composer. Historic V28 assets stay locked. apply_fx_rack_interaction((ROOT/"site/preview-v2/index.html").read_text(encoding="utf-8"),owned) expected=apply_operator_ux(expected,owned) + expected=apply_lms(expected,owned) composed_css={name:(owned/name).read_text(encoding="utf-8") for name in owners} # Stage C: the source HTML remains byte-exact, but the 18 deployed CSS files # contain only proven cascade winners. Verify every *generated* byte and query @@ -104,6 +106,18 @@ def css_rewrite(match): require(len(shipped)==1 and shipped[0].group(2)==RUNTIME_CSS, 'Only the single compiled runtime CSS is allowed to load') require(html==expected,'rendered /preview/ DOM differs from source + approved buttons + one runtime CSS + nonvisual profiler') +# LMS is a sibling workspace in the SAME renderer; never a second /preview/ page. +require(html.count('id="lmsOpen"')==1 and html.count('id="lmsWorkspace"')==1, + 'LMS button or workspace absent/duplicated') +for asset in ('lms-workspace.js','lms-system-model.js','lms-workspace.css'): + require((gui/'assets'/asset).read_bytes()== + (ROOT/'site/preview-v2/assets'/asset).read_bytes(), + 'LMS composed asset drift: '+asset) +require('ArSonMixLmsModel' in (gui/'assets/lms-workspace.js').read_text(encoding='utf-8'), + 'LMS logical model not used by workspace') +subprocess.run(['node','--test',str(ROOT/'tests/lms_system_model.test.cjs')], + cwd=ROOT,check=True) + for name in ('mixer-wire-dots.css','knob-ICON.svg'): require((gui/'assets'/name).read_bytes()==(ROOT/'site/preview-v2/assets'/name).read_bytes(),'WIRE source drift: '+name) require((gui/'assets/mixer-keys-thin-flat-v9-approved-off-shadow-57x30.png').read_bytes()==(ROOT/'site/preview-buttons/assets/mixer-keys-thin-flat-v9-approved-off-shadow-57x30.png').read_bytes(),'approved PNG sprite mismatch') diff --git a/tests/sonku_spatial_core_test.cpp b/tests/sonku_spatial_core_test.cpp index 0258e2201..c3d440614 100644 --- a/tests/sonku_spatial_core_test.cpp +++ b/tests/sonku_spatial_core_test.cpp @@ -12,12 +12,21 @@ int main() { using namespace armix::sonku; - SonKuSpatialCore rejected; + // Windows default test-thread stack is commonly 1 MiB. Each SonKu + // instance owns ~192 KiB of fixed reverb/reflection delay state; + // multiple automatic instances can overflow the stack before an + // assertion executes, even though the standalone DSP is correct. + // This fixture creates processors on the CONTROL/test heap only. + // Production prepare/process and realtime zero-allocation semantics + // are not changed by this test-lifetime correction. + auto rejectedStorage=std::make_unique(); + auto& rejected=*rejectedStorage; assert(!rejected.prepare(96000.)); assert(!rejected.prepare(std::numeric_limits::infinity())); assert(!rejected.ready()); for(double rate:{44100.,48000.}) { - SonKuSpatialCore core; + auto coreStorage=std::make_unique(); + auto& core=*coreStorage; assert(core.prepare(rate)); Settings s{}; s.moving=false; s.stereoSpreadDegrees=0.f; s.spatialMix=1.f; @@ -67,7 +76,10 @@ int main() { oneL[i]=chunkL[i]=std::sin(i*0.07f)*0.2f; oneR[i]=chunkR[i]=std::cos(i*0.09f)*0.2f; } - SonKuSpatialCore whole,chunked; + auto wholeStorage=std::make_unique(); + auto chunkedStorage=std::make_unique(); + auto& whole=*wholeStorage; + auto& chunked=*chunkedStorage; assert(whole.prepare(rate)&&chunked.prepare(rate)); assert(whole.setSettings(moving)&&chunked.setSettings(moving)); whole.process(oneL.data(),oneR.data(),longFrames); @@ -87,7 +99,12 @@ int main() { std::array noL{},noR{},wetL{},wetR{},partL{},partR{}; noL[0]=wetL[0]=partL[0]=.5f; noR[0]=wetR[0]=partR[0]=.5f; - SonKuSpatialCore noRoom,withRoom,partRoom; + auto noRoomStorage=std::make_unique(); + auto withRoomStorage=std::make_unique(); + auto partRoomStorage=std::make_unique(); + auto& noRoom=*noRoomStorage; + auto& withRoom=*withRoomStorage; + auto& partRoom=*partRoomStorage; assert(noRoom.prepare(rate)&&withRoom.prepare(rate)&&partRoom.prepare(rate)); Settings roomSettings=s;roomSettings.startAzimuthDegrees=0.f; assert(noRoom.setSettings(roomSettings)&&withRoom.setSettings(roomSettings) @@ -121,7 +138,10 @@ int main() { // Allocate this extra test processor off-stack (each core owns // fixed ~192 KiB acoustic rings; Windows test stacks are bounded). auto approvedSquare=std::make_unique(); - SonKuSpatialCore glow,glowChunks; + auto glowStorage=std::make_unique(); + auto glowChunksStorage=std::make_unique(); + auto& glow=*glowStorage; + auto& glowChunks=*glowChunksStorage; assert(approvedSquare->prepare(rate)&&glow.prepare(rate)&&glowChunks.prepare(rate)); assert(approvedSquare->setEarlyReflectionsShape(SonKuRoomShape::Square)); assert(glow.setEarlyReflectionsShape(SonKuRoomShape::Square)); @@ -415,7 +435,10 @@ int main() { // A hard FRONT->REAR teleport must not replace 560 FIR coefficients // at the next 16-sample boundary. Compare the identical dry/PCM // history before and immediately after reposition. - SonKuSpatialCore teleport,stationary; + auto teleportStorage=std::make_unique(); + auto stationaryStorage=std::make_unique(); + auto& teleport=*teleportStorage; + auto& stationary=*stationaryStorage; assert(teleport.prepare(rate)&&stationary.prepare(rate)); Settings frontPose=s;frontPose.startAzimuthDegrees=0.f; assert(teleport.setSettings(frontPose)&&stationary.setSettings(frontPose)); @@ -436,7 +459,8 @@ int main() { changed+=std::abs(stepL[i]-refL[i])+std::abs(stepR[i]-refR[i]); assert(changed>.005); // MIX/trim changes are smoothed on the same audio clock. - SonKuSpatialCore mixCore; + auto mixCoreStorage=std::make_unique(); + auto& mixCore=*mixCoreStorage; assert(mixCore.prepare(rate)); Settings dry=frontPose;dry.spatialMix=0.f; assert(mixCore.setSettings(dry));