diff --git a/.github/workflows/native-builtin-fx.yml b/.github/workflows/native-builtin-fx.yml new file mode 100644 index 000000000..590676e9f --- /dev/null +++ b/.github/workflows/native-builtin-fx.yml @@ -0,0 +1,32 @@ +name: Native Built-in FX DSP +on: + pull_request: + paths: + - 'site/preview-v2/assets/mixer-builtin-eq.*' + - 'tests/builtin_eq_gui_contract_test.mjs' + - 'engine/builtin_fx/**' + - 'tests/builtin_channel_eq_test.cpp' + - '.github/workflows/native-builtin-fx.yml' + workflow_dispatch: +permissions: + contents: read +concurrency: + group: native-builtinfx-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + standalone-dsp: + # Fast Linux DSP; canonical Windows MSVC only on full milestone review. + runs-on: ubuntu-latest + timeout-minutes: 8 + steps: + - uses: actions/checkout@v4 + - name: Console EQ GUI syntax and ownership contract + run: | + node --check site/preview-v2/assets/mixer-builtin-eq.js + node tests/builtin_eq_gui_contract_test.mjs + - name: Configure no-JUCE native built-in FX + run: cmake -S engine/builtin_fx -B build-builtin-fx -DCMAKE_BUILD_TYPE=Release + - name: Compile native DSP test + run: cmake --build build-builtin-fx --config Release --parallel 2 + - name: Verify native DSP + zero heap test + run: ctest --test-dir build-builtin-fx -C Release --output-on-failure diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 0ce438f6c..4b60d6190 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -129,7 +129,7 @@ jobs: needs: quick # Draft commits never reserve expensive Windows runners. Non-draft PR # synchronizations re-test latest HEAD. Main push and manual always run. - if: ${{ github.event_name != 'pull_request' }} + if: ${{ github.event_name != 'pull_request' || github.event.pull_request.draft == false }} runs-on: windows-2022 timeout-minutes: 50 steps: diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 13afdba0f..92522e5cb 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -54,10 +54,20 @@ on: workflow_dispatch: inputs: expected_sha: - description: "Immutable source SHA for ChatGPT milestone" + description: "Immutable source SHA for ChatGPT Chromium milestone" type: string required: false default: "" + historical_full: + description: "Explicitly rerun pinned V10-V28 CSS migration/historical parity" + type: boolean + required: false + default: false + firefox_perf: + description: "Optional Firefox compositor/performance cross-browser qualification" + type: boolean + required: false + default: false # New PR commits supersede old UI checks. The production Pages dispatcher # only reacts to a completed successful main push, never cancelled checks. @@ -95,6 +105,7 @@ jobs: - name: Check native UI contracts, workflow policy, and WIRE without Chromium run: | 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 + node tests/builtin_eq_gui_contract_test.mjs node tests/wire_graph_canonical_model.test.cjs node tests/wire_main_native_handoff_contract.test.cjs - name: Verify single published /preview/ source offline @@ -106,9 +117,11 @@ jobs: run: node scripts/check_console_puzzle.mjs --release frontend: name: Full Chromium /preview/ visual and interaction qualification - # Draft edits are cheap; ChatGPT milestone comments dispatch this full suite. + # Draft iteration receives only quick checks; promotion to Ready-for-review + # or an explicit manual dispatch runs this full browser suite. A non-draft + # PR synchronize always requalifies the latest commit, never stale HEAD. needs: quick - if: ${{ github.event_name != 'pull_request' }} + if: ${{ github.event_name != 'pull_request' || github.event.pull_request.draft == false }} runs-on: ubuntu-latest timeout-minutes: 20 steps: @@ -168,6 +181,10 @@ jobs: run: python tests/approved_stage_c_css_visual_parity_smoke.py - name: Check real mobile /preview/ touch toolbar, popup and stray chevrons run: python tests/approved_preview_mobile_navigation_smoke.py + - name: FX rack master bypass preserves each insert state (real Chromium) + run: python tests/approved_fx_rack_master_power_smoke.py + - name: Parametric EQ picker to rack and draggable editor (real Chromium) + run: python tests/approved_builtin_peq_picker_smoke.py - name: Stage D one runtime CSSOM and actual stylesheet network count run: python tests/approved_css_stage_d_single_bundle_smoke.py - name: Stage C rendered CSS parity (original vs compiled, three viewports + hover) @@ -212,7 +229,7 @@ jobs: # pretending the intentional V50 layout/stylesheet changes are V22. # Restore PR files before ALL current GUI/function/geometry smoke tests. - name: Mount pinned V24 historical CSS fixture (reversible, no CI rebaseline) - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} shell: bash run: | set -euo pipefail @@ -225,58 +242,58 @@ jobs: git show "$baseline:$path" > "$path" done - name: Verify V8 FX rack and Plugin Manager CSS ownership - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_ownership_v8_smoke.py - name: Verify V9 PAN/fader/meter CSS ownership and geometry - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_ownership_v9_smoke.py - name: Verify V10 cascade ownership and rendered console geometry - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v10_smoke.py - name: Validate V11 section ownership, cascade and computed visual styles - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v11_smoke.py - name: Verify V12 removed shadow declarations and old/new visual + control parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v12_smoke.py - name: Verify V13 owned CSS conflicts and physical control visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v13_smoke.py - name: Verify V14 canonical 45 material tokens and V13 browser parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v14_smoke.py - name: Verify V15 clean cross-owner CSS and actual interactive visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v15_smoke.py - name: Verify V16 WIRE single CSS owner, 241-rule exact source and visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v16_smoke.py - name: Verify V17 Plugin Manager and Fast FX Picker single CSS owner - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v17_smoke.py - name: Verify V18 physical Chrome ownership and four cascade conflict removals - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v18_smoke.py - name: Verify V19 shared operator key ownership and six shadowed declarations - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v19_smoke.py - name: Verify V20 elimination of 53 shadowed declarations and Chromium state parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v20_smoke.py - name: Verify V21 physical console chassis geometry owner and visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v21_smoke.py - name: Verify V22 legacy key material migration and M3 visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v22_smoke.py - name: Verify V23 exact cascade deletions and browser parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v23_smoke.py - name: Verify V24 Fader/Meter/FX cascade pruning and browser parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v24_smoke.py - name: Restore and verify exact V50 PR assets before current UI smoke - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} shell: bash run: | set -euo pipefail @@ -289,7 +306,7 @@ jobs: # The V25 historical test is an immutable exact-byte migration gate. # Do not rebaseline it after deliberate V26 dead-rule removals. - name: Mount pinned V25 original CSS before historical V25 migration test - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} shell: bash run: | set -euo pipefail @@ -302,10 +319,10 @@ jobs: git show "$baseline:$path" > "$path" done - name: Verify V25 exact V51 physical-key owner migration and zero visual regression - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v25_smoke.py - name: Restore and verify current V26 source before latest GUI tests - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} shell: bash run: | set -euo pipefail @@ -317,7 +334,7 @@ jobs: git diff --exit-code -- site/preview-v2/index.html site/preview-v2/assets/mixer-control-keys.css site/preview-v2/assets/mixer-chrome-material.css site/preview-v2/assets/mixer-plugin-browser.css site/preview-v2/assets/mixer-pan-controls.css site/preview-v2/assets/mixer-fader-assembly.css site/preview-v2/assets/mixer-meter-display.css site/preview-v2/assets/mixer-utility-controls.css # Byte-exact V26 historical CSS check is pinned, not rebaselined. - name: Mount V26 approved source before historical regression - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} shell: bash run: | set -euo pipefail @@ -330,10 +347,10 @@ jobs: git show "$baseline:$path" > "$path" done - name: Verify V26 retired socket dead rules and exact V25 visual/control parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v26_smoke.py - name: Restore P0 current WIRE source after historical V26 regression - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} shell: bash run: | set -euo pipefail @@ -346,7 +363,7 @@ jobs: # V27 is a byte-exact historical CSS migration proof; it must run # against its original qualified GUI, never rebaseline a newer FX/rail. - name: Mount pinned V27 GUI and CSS owners for immutable parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} shell: bash run: | set -euo pipefail @@ -359,10 +376,10 @@ jobs: git show "$baseline:$path" > "$path" done - name: Verify V27 scoped material and 37 owned loser declarations with Chromium parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/pages_css_architecture_v27_smoke.py - name: Restore and verify exact V53 current sources after historical V27 - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} shell: bash run: | set -euo pipefail @@ -373,7 +390,7 @@ jobs: done git diff --exit-code -- site/preview-v2/index.html site/preview-v2/assets/mixer-chrome-material.css site/preview-v2/assets/mixer-plugin-browser.css site/preview-v2/assets/mixer-pan-controls.css site/preview-v2/assets/mixer-fader-assembly.css site/preview-v2/assets/mixer-meter-display.css site/preview-v2/assets/mixer-utility-controls.css - name: Verify V28 exact approved /preview/ source and interactive browser parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && (startsWith(github.head_ref, 'css/v28-') || startsWith(github.head_ref, 'integration/product-'))) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.historical_full == true) || (github.event_name == 'pull_request' && (startsWith(github.head_ref, 'css/v28-') || startsWith(github.head_ref, 'integration/product-'))) }} run: python tests/pages_css_architecture_v28_smoke.py - name: Verify embedded Inter font and contextual V7 micro-controls if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} @@ -428,13 +445,13 @@ jobs: - name: Verify MIX and FX RACK Auto Orbit workflow if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/native_orbit_ui_smoke.py - # Firefox perf is deliberate: main release verification or manual opt-in. - # Do not download/run a second browser for every iterative GUI PR. + # Firefox is an explicit cross-browser/performance opt-in. Ordinary + # exact-SHA Chromium milestones stay Chromium-only and runner-efficient. - name: Install Firefox for compositor functional regression - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.firefox_perf == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python -m playwright install firefox - name: Run Firefox opt-in performance diagnostics smoke - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.firefox_perf == true) || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/ui_firefox_perf_smoke.py - name: Attach current WIRE / FX / meter / fader screenshots (small, PR-friendly) if: always() @@ -451,5 +468,7 @@ jobs: pages-v55-*.png pages-v28-physical-console-owner-v59-*.png pages-mobile-*.png + parametric-eq-mixer-*.png + parametric-eq-editor-*.png if-no-files-found: ignore retention-days: 3 diff --git a/engine/builtin_fx/BuiltInFxCatalog.h b/engine/builtin_fx/BuiltInFxCatalog.h new file mode 100644 index 000000000..23e39acbc --- /dev/null +++ b/engine/builtin_fx/BuiltInFxCatalog.h @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include + +// This is a compile-time catalog of NATIVE effects, not a VST3/FactoryFX manifest. +// Never advertise these as usable in the operator picker until the native PCM +// owner and ACK/snapshot adapter have actually been integrated. +namespace armix::builtin_fx { +inline constexpr std::string_view channelEqId = "armix.builtin.channel-eq.v1"; + +enum class FilterKind : std::uint8_t { highPass, lowShelf, bell, highShelf, lowPass }; +enum class Slope : std::uint8_t { db12 = 12, db24 = 24 }; +struct SlotSpec { + std::string_view id; + FilterKind kind; + float defaultHz; +}; +inline constexpr std::array channelEqSlots{{ + {"hpf", FilterKind::highPass, 80.0f}, + {"low-shelf", FilterKind::lowShelf, 160.0f}, + {"peq-1", FilterKind::bell, 250.0f}, + {"peq-2", FilterKind::bell, 500.0f}, + {"peq-3", FilterKind::bell, 1500.0f}, + {"peq-4", FilterKind::bell, 4500.0f}, + {"high-shelf",FilterKind::highShelf, 9500.0f}, + {"lpf", FilterKind::lowPass, 18000.0f} +}}; +static_assert(channelEqSlots.size() == 8); +} // namespace armix::builtin_fx diff --git a/engine/builtin_fx/CMakeLists.txt b/engine/builtin_fx/CMakeLists.txt new file mode 100644 index 000000000..558812cc0 --- /dev/null +++ b/engine/builtin_fx/CMakeLists.txt @@ -0,0 +1,24 @@ +# Optional JUCE-independent developer/CI gate for the built-in DSP module. +# cmake -S engine/builtin_fx -B build/builtin_fx +# cmake --build build/builtin_fx --config Release +# ctest --test-dir build/builtin_fx -C Release --output-on-failure +cmake_minimum_required(VERSION 3.22) +project(ArSonMixBuiltInFX LANGUAGES CXX) +enable_testing() +add_executable(ArSonMixBuiltInEQTests ../../tests/builtin_channel_eq_test.cpp) +target_compile_features(ArSonMixBuiltInEQTests PRIVATE cxx_std_20) +if(MSVC) + target_compile_options(ArSonMixBuiltInEQTests PRIVATE /W4) +else() + target_compile_options(ArSonMixBuiltInEQTests PRIVATE -Wall -Wextra -Wpedantic) +endif() +add_test(NAME BuiltInChannelEqIndependentRealtimeDSP COMMAND ArSonMixBuiltInEQTests) + +add_executable(ArSonMixBuiltInEQBankTests ../../tests/builtin_channel_eq_bank_test.cpp) +target_compile_features(ArSonMixBuiltInEQBankTests PRIVATE cxx_std_20) +if(MSVC) + target_compile_options(ArSonMixBuiltInEQBankTests PRIVATE /W4) +else() + target_compile_options(ArSonMixBuiltInEQBankTests PRIVATE -Wall -Wextra -Wpedantic) +endif() +add_test(NAME BuiltInChannelEqFourteenChannelAudioOwnerAndAck COMMAND ArSonMixBuiltInEQBankTests) diff --git a/engine/builtin_fx/ChannelEq.h b/engine/builtin_fx/ChannelEq.h new file mode 100644 index 000000000..a900304d8 --- /dev/null +++ b/engine/builtin_fx/ChannelEq.h @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "BuiltInFxCatalog.h" +#include +#include +#include +#include +#include +#include +#include + +// Channel strip EQ for the main native mixer ONLY. Deliberately no JUCE, +// VST3, ArSonEQ, FFT, WebView2, heap allocation or audio callback ownership. +// prepare()/setBand() operate on UNPUBLISHED instances (or in offline tests). +// For live edits, prepareBandEdit() performs all trig on CONTROL; applyPreparedBand() +// performs only bounded copies on the exclusive audio owner at a block boundary. +// No state mutation may race process(), and no UI thread reads live histories. +namespace armix::builtin_fx { +struct Band { + bool enabled = false; + float frequencyHz = 1000.0f; + float gainDb = 0.0f; + float q = 0.70710678f; + Slope slope = Slope::db12; // HPF/LPF only; other types ignore it. +}; + +class ChannelEq final { +public: + static constexpr std::size_t bandCount = channelEqSlots.size(); + static constexpr float maxGainDb = 18.0f; + static constexpr float minQ = 0.2f; + static constexpr float maxQ = 12.0f; + + ChannelEq() noexcept { + for (std::size_t i = 0; i < bandCount; ++i) { + current_.settings[i].frequencyHz = channelEqSlots[i].defaultHz; + current_.settings[i].q = channelEqSlots[i].kind == FilterKind::bell ? 1.0f : 0.70710678f; + } + } + + // CONTROL creates a precomputed change without accessing a live EQ. + // A bounded queue/immutable handoff outside this module transports it to + // the audio owner. sampleRate acts as a device-epoch-independent fence; + // the mixer adapter must ALSO validate ChannelId, epoch, and revision. + struct PreparedBandEdit final { + Band band{}; + std::size_t index=bandCount; + double sampleRate=0.0; + std::array,2> coefficients{}; // b0,b1,b2,a1,a2 + std::uint8_t sections=0; + bool valid=false; + }; + + static bool prepareBandEdit(std::size_t index, const Band& band, + double sampleRate, PreparedBandEdit& output) noexcept { + if (!std::isfinite(sampleRate) || sampleRate < 8000.0 || + sampleRate > 384000.0 || + !validBand(index,band,static_cast(std::min(20000.0,sampleRate*0.45)))) + return false; + Slot compiled{}; + if (band.enabled && !makeSlot(channelEqSlots[index].kind,band,sampleRate,compiled)) + return false; + PreparedBandEdit candidate{}; + candidate.band=band; + candidate.index=index; + candidate.sampleRate=sampleRate; + candidate.sections=compiled.count; + for (std::uint8_t i=0;i=bandCount || + edit.sampleRate!=sampleRate_ || + !validBand(edit.index,edit.band,maxFrequencyHz())) return false; + const auto kind=channelEqSlots[edit.index].kind; + const bool cut=kind==FilterKind::highPass||kind==FilterKind::lowPass; + const std::uint8_t expected=edit.band.enabled ? + static_cast(cut && edit.band.slope==Slope::db24 ? 2 : 1) : 0; + if (edit.sections!=expected) return false; + Slot newSlot{}; + newSlot.count=expected; + for(std::uint8_t i=0;i(i); + previous_=current_; + current_=next; + fadeRemaining_=fadeLength_; + return true; + } + + // Prepares without allocating. Enabled filters above the new Nyquist guard + // cause rejection (caller must explicitly choose a safe setting). + bool prepare(double sampleRate) noexcept { + if (!std::isfinite(sampleRate) || sampleRate < 8000.0 || sampleRate > 384000.0) + return false; + const float maxHz = static_cast(std::min(20000.0, sampleRate * 0.45)); + Bank next = current_; + for (std::size_t i = 0; i < bandCount; ++i) { + auto& band = next.settings[i]; + if (!band.enabled) band.frequencyHz = std::min(band.frequencyHz, maxHz); + if (!validBand(i, band, maxHz)) return false; + } + next.activeCount = 0; + for (std::size_t i = 0; i < bandCount; ++i) { + next.slots[i] = Slot{}; + if (next.settings[i].enabled) { + if (!makeSlot(channelEqSlots[i].kind, next.settings[i], sampleRate, next.slots[i])) + return false; + next.active[next.activeCount++] = static_cast(i); + } + } + sampleRate_ = sampleRate; + current_ = next; + previous_ = Bank{}; + fadeLength_ = std::max(1, static_cast(std::round(sampleRate * 0.005))); + fadeRemaining_ = 0; + prepared_ = true; + return true; + } + + // Offline/unpublished convenience, NOT for the live audio callback: + // this computes trigonometric coefficients. Use prepareBandEdit() on the + // CONTROL thread and applyPreparedBand() on AUDIO for live automation. + bool setBand(std::size_t index, const Band& band) noexcept { + if(!prepared_)return false; + PreparedBandEdit edit{}; + return prepareBandEdit(index,band,sampleRate_,edit) && applyPreparedBand(edit); + } + + bool resetToFlat() noexcept { + if (!prepared_) return false; + if (current_.activeCount == 0) return true; + previous_ = current_; + for (std::size_t i = 0; i < bandCount; ++i) { + current_.settings[i].enabled = false; + current_.slots[i] = Slot{}; + } + current_.activeCount = 0; + fadeRemaining_ = fadeLength_; + return true; + } + + [[nodiscard]] Band band(std::size_t index) const noexcept { + return index < bandCount ? current_.settings[index] : Band{}; + } + [[nodiscard]] bool isPrepared() const noexcept { return prepared_; } + [[nodiscard]] double sampleRate() const noexcept { return sampleRate_; } + [[nodiscard]] float maxFrequencyHz() const noexcept { + return static_cast(std::min(20000.0, sampleRate_ * 0.45)); + } + [[nodiscard]] std::size_t activeBands() const noexcept { return current_.activeCount; } + [[nodiscard]] int addedLatencySamples() const noexcept { return 0; } + [[nodiscard]] bool transitioning() const noexcept { + return fadeRemaining_>0 || externalFadeRemaining_>0; + } + // AUDIO-owner-only smooth gate, preserving individual band settings. + void setExternalBypass(bool bypass) noexcept { + const float target=bypass?0.0f:1.0f; + if(target==externalTarget_)return; + externalTarget_=target; + if(current_.activeCount==0 && fadeRemaining_==0) { + externalWet_=target;externalFadeRemaining_=0; + } else externalFadeRemaining_=fadeLength_; + } + + // Processing and all biquad histories are audio-owner exclusive. + // left==right is explicitly one mono buffer, never double processed. + void processStereo(float* left, float* right, std::size_t frames) noexcept { + if (!prepared_ || !left || !right || frames == 0) return; + if (left == right) { processMono(left, frames); return; } + if (current_.activeCount==0 && fadeRemaining_==0) { + externalWet_=externalTarget_;externalFadeRemaining_=0; + return; // exact bitwise bypass + } + + for (std::size_t i = 0; i < frames; ++i) { + const float dryL = left[i], dryR = right[i]; + const float wetL = render(current_, 0, dryL), wetR = render(current_, 1, dryR); + if (fadeRemaining_ > 0) { + const float oldL = render(previous_, 0, dryL); + const float oldR = render(previous_, 1, dryR); + const float mix = 1.0f - static_cast(fadeRemaining_ - 1) / + static_cast(fadeLength_); + const float processedL=oldL+(wetL-oldL)*mix; + const float processedR=oldR+(wetR-oldR)*mix; + const float gate=nextExternalMix(); + left[i]=dryL+(processedL-dryL)*gate; + right[i]=dryR+(processedR-dryR)*gate; + --fadeRemaining_; + } else { + const float gate=nextExternalMix(); + left[i]=dryL+(wetL-dryL)*gate; + right[i]=dryR+(wetR-dryR)*gate; + } + } + clearTiny(current_); + if (fadeRemaining_ != 0) clearTiny(previous_); + } + + void processMono(float* samples, std::size_t frames) noexcept { + if(!prepared_||!samples||frames==0)return; + if(current_.activeCount==0 && fadeRemaining_==0) { + externalWet_=externalTarget_;externalFadeRemaining_=0;return; + } + + for (std::size_t i = 0; i < frames; ++i) { + const float dry = samples[i]; + const float wet = render(current_, 0, dry); + if (fadeRemaining_ > 0) { + const float old = render(previous_, 0, dry); + const float mix = 1.0f - static_cast(fadeRemaining_ - 1) / + static_cast(fadeLength_); + const float processed=old+(wet-old)*mix; + const float gate=nextExternalMix(); + samples[i]=dry+(processed-dry)*gate; + --fadeRemaining_; + } else { + const float gate=nextExternalMix(); + samples[i]=dry+(wet-dry)*gate; + } + } + clearTiny(current_); + if (fadeRemaining_ != 0) clearTiny(previous_); + } + + // Control-side visualization only. Never call while an audio callback is + // mutating this instance. Host should snapshot coefficients off callback. + [[nodiscard]] double responseDb(double frequencyHz) const noexcept { + if (!prepared_ || !std::isfinite(frequencyHz) || frequencyHz <= 0.0 || + frequencyHz >= sampleRate_ * 0.5) return 0.0; + const double w = twoPi * frequencyHz / sampleRate_; + const std::complex z1 = std::polar(1.0, -w); + const auto z2 = z1 * z1; + double result = 0.0; + for (std::uint8_t k = 0; k < current_.activeCount; ++k) { + const auto& s = current_.slots[current_.active[k]]; + for (std::uint8_t j = 0; j < s.count; ++j) { + const auto& c = s.section[j]; + const auto numerator = c.b0 + c.b1 * z1 + c.b2 * z2; + const auto denominator = 1.0 + c.a1 * z1 + c.a2 * z2; + const double mag = std::abs(numerator / denominator); + result += 20.0 * std::log10(std::max(1.0e-12, mag)); + } + } + return std::clamp(result, -160.0, 80.0); + } + +private: + static constexpr double twoPi = 6.283185307179586476925286766559; + struct Section { + double b0=1, b1=0, b2=0, a1=0, a2=0; + double z1[2]{}, z2[2]{}; + float process(int channel, float input) noexcept { + const double x = static_cast(input); + const double out = b0 * x + z1[channel]; + z1[channel] = b1 * x - a1 * out + z2[channel]; + z2[channel] = b2 * x - a2 * out; + return static_cast(out); + } + void denormalGuard() noexcept { + for (int i = 0; i < 2; ++i) { + if (std::abs(z1[i]) < 1.0e-24) z1[i] = 0; + if (std::abs(z2[i]) < 1.0e-24) z2[i] = 0; + } + } + }; + struct Slot { std::array section{}; std::uint8_t count=0; }; + struct Bank { + std::array settings{}; + std::array slots{}; + std::array active{}; + std::uint8_t activeCount=0; + }; + Bank current_{}, previous_{}; + double sampleRate_ = 0.0; + int fadeLength_ = 1, fadeRemaining_ = 0; + float externalWet_=1.0f,externalTarget_=1.0f; + int externalFadeRemaining_=0; + bool prepared_ = false; + float nextExternalMix() noexcept { + if(externalFadeRemaining_>0) { + externalWet_+=(externalTarget_-externalWet_)/ + static_cast(externalFadeRemaining_); + if(--externalFadeRemaining_==0)externalWet_=externalTarget_; + } + return externalWet_; + } + + static bool validBand(std::size_t i, const Band& b, float maxHz) noexcept { + if (i >= bandCount || !std::isfinite(b.frequencyHz) || + !std::isfinite(b.gainDb) || !std::isfinite(b.q) || + b.frequencyHz < 20.0f || b.frequencyHz > maxHz || + b.gainDb < -maxGainDb || b.gainDb > maxGainDb || + b.q < minQ || b.q > maxQ) return false; + return b.slope == Slope::db12 || b.slope == Slope::db24; + } + static bool normalized(Section& s, double b0, double b1, double b2, + double a0, double a1, double a2) noexcept { + if (!std::isfinite(a0) || std::abs(a0) < 1.0e-12) return false; + s.b0 = b0 / a0; s.b1 = b1 / a0; s.b2 = b2 / a0; + s.a1 = a1 / a0; s.a2 = a2 / a0; + return std::isfinite(s.b0) && std::isfinite(s.b1) && std::isfinite(s.b2) && + std::isfinite(s.a1) && std::isfinite(s.a2); + } + static bool makeBiquad(FilterKind kind, const Band& b, double sampleRate, + double q, Section& out) noexcept { + const double omega = twoPi * b.frequencyHz / sampleRate; + const double c = std::cos(omega), s = std::sin(omega); + const double a = std::pow(10.0, static_cast(b.gainDb) / 40.0); + const double alpha = s / (2.0 * q); + switch (kind) { + case FilterKind::bell: + return normalized(out, 1.0+alpha*a, -2.0*c, 1.0-alpha*a, + 1.0+alpha/a, -2.0*c, 1.0-alpha/a); + case FilterKind::highPass: + return normalized(out, (1+c)*0.5, -(1+c), (1+c)*0.5, + 1+alpha, -2*c, 1-alpha); + case FilterKind::lowPass: + return normalized(out, (1-c)*0.5, 1-c, (1-c)*0.5, + 1+alpha, -2*c, 1-alpha); + case FilterKind::lowShelf: { + const double edge = s * std::sqrt(a) * std::sqrt(2.0); + return normalized(out, + a*((a+1)-(a-1)*c+edge), 2*a*((a-1)-(a+1)*c), + a*((a+1)-(a-1)*c-edge), + (a+1)+(a-1)*c+edge, -2*((a-1)+(a+1)*c), + (a+1)+(a-1)*c-edge); + } + case FilterKind::highShelf: { + const double edge = s * std::sqrt(a) * std::sqrt(2.0); + return normalized(out, + a*((a+1)+(a-1)*c+edge), -2*a*((a-1)+(a+1)*c), + a*((a+1)+(a-1)*c-edge), + (a+1)-(a-1)*c+edge, 2*((a-1)-(a+1)*c), + (a+1)-(a-1)*c-edge); + } + } + return false; + } + static bool makeSlot(FilterKind kind, const Band& b, double rate, Slot& result) noexcept { + const bool cut = kind == FilterKind::highPass || kind == FilterKind::lowPass; + result.count = static_cast(cut && b.slope == Slope::db24 ? 2 : 1); + if (result.count == 2) { + return makeBiquad(kind, b, rate, 0.541196100146197, result.section[0]) && + makeBiquad(kind, b, rate, 1.306562964876377, result.section[1]); + } + return makeBiquad(kind, b, rate, cut ? 0.7071067811865476 : b.q, + result.section[0]); + } + static float render(Bank& bank, int channel, float sample) noexcept { + for (std::uint8_t i = 0; i < bank.activeCount; ++i) { + auto& slot = bank.slots[bank.active[i]]; + for (std::uint8_t j = 0; j < slot.count; ++j) + sample = slot.section[j].process(channel, sample); + } + return sample; + } + static void clearTiny(Bank& bank) noexcept { + for (std::uint8_t i = 0; i < bank.activeCount; ++i) { + auto& slot = bank.slots[bank.active[i]]; + for (std::uint8_t j = 0; j < slot.count; ++j) + slot.section[j].denormalGuard(); + } + } +}; +} // namespace armix::builtin_fx diff --git a/engine/builtin_fx/ChannelEqBank.h b/engine/builtin_fx/ChannelEqBank.h new file mode 100644 index 000000000..2745ded2a --- /dev/null +++ b/engine/builtin_fx/ChannelEqBank.h @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "ChannelEq.h" +#include +#include +#include +#include +#include + +// Real-time bridge between one JUCE control-thread owner and the ONLY native +// audio callback. The DSP is native; this is NOT a VST3 loader or second engine. +namespace armix::builtin_fx { +namespace detail { +template class SpscRing final { + static_assert(Capacity > 1 && Capacity < 65536); +public: + // Exactly ONE producer and ONE consumer; serial control events only. + bool push(const T& value) noexcept { + const auto write = write_.load(std::memory_order_relaxed); + if (write - read_.load(std::memory_order_acquire) >= Capacity) return false; + storage_[write % Capacity] = value; + write_.store(write + 1, std::memory_order_release); + return true; + } + bool pop(T& value) noexcept { + const auto read = read_.load(std::memory_order_relaxed); + if (read == write_.load(std::memory_order_acquire)) return false; + value = storage_[read % Capacity]; + read_.store(read + 1, std::memory_order_release); + return true; + } + [[nodiscard]] bool canPush() const noexcept { + return write_.load(std::memory_order_relaxed) - + read_.load(std::memory_order_acquire) < Capacity; + } +private: + alignas(64) std::atomic write_{0}; + alignas(64) std::atomic read_{0}; + std::array storage_{}; +}; +} // namespace detail + +class ChannelEqBank final { +public: + static constexpr std::size_t laneCount = 14; // 10 physical CH + 4 AUX; no fake MASTER + static constexpr std::size_t maxPendingPerLane = 32; + struct Ack final { + std::uint64_t requestId = 0; + std::uint64_t deviceEpoch = 0; + std::uint64_t graphRevision = 0; + std::uint8_t lane = 0; + std::uint8_t slot = 0; + Band accepted{}; + bool applied = false; + bool gate=false,installed=false,bypassed=false; + }; + ChannelEqBank() = default; + ChannelEqBank(const ChannelEqBank&) = delete; + ChannelEqBank& operator=(const ChannelEqBank&) = delete; + + // Call BEFORE publishing a graph to the audio callback. Never prepare a + // published graph; its state is exclusively advanced by the audio owner. + bool prepare(double sampleRate) noexcept { + if (ready_) return false; + if (!std::isfinite(sampleRate) || sampleRate < 8000.0 || sampleRate > 384000.0) + return false; + for(std::size_t lane=0;lane= laneCount || slot >= ChannelEq::bandCount || + requestId == 0 || deviceEpoch == 0 || graphRevision == 0) + return false; + ChannelEq::PreparedBandEdit prepared{}; + if (!ChannelEq::prepareBandEdit(slot, band, sampleRate_, prepared)) return false; + Command c{};c.requestId=requestId;c.deviceEpoch=deviceEpoch; + c.graphRevision=graphRevision;c.lane=static_cast(lane); + c.slot=static_cast(slot);c.edit=prepared; + return pending_[lane].push(c); + } + bool queueGateEdit(std::size_t lane,bool installed,bool bypassed, + std::uint64_t requestId,std::uint64_t deviceEpoch, + std::uint64_t graphRevision) noexcept { + if(!ready_||lane>=laneCount||!requestId||!deviceEpoch|| + !graphRevision||(!installed&&bypassed))return false; + Command c{};c.requestId=requestId;c.deviceEpoch=deviceEpoch; + c.graphRevision=graphRevision;c.lane=static_cast(lane); + c.slot=255;c.gate=true;c.installed=installed;c.bypassed=bypassed; + return pending_[lane].push(c); + } + // CONTROL->AUDIO atomic rack override. User's own EQ bypass is retained. + bool setRackBypass(std::size_t lane,bool bypass) noexcept { + if(lane>=laneCount)return false; + rackBypassed_[lane].store(bypass,std::memory_order_release); + return true; + } + [[nodiscard]] bool rackBypassed(std::size_t lane) const noexcept { + return lane=laneCount||(!installed&&bypassed))return false; + insertBypassed_[lane]=!installed||bypassed; + eqs_[lane].setExternalBypass(insertBypassed_[lane]||rackBypassed(lane)); + return true; + } + // AUDIO OWNER ONLY. At most one filter change per strip per block, and + // never start another 5ms topology fade before the previous one ends. + // A full acknowledgement ring BACKPRESSURES the request queue; it must + // never silently apply a command whose ACK was lost. + void render(std::size_t lane, float* left, float* right, + std::size_t frames, + std::uint64_t activeEpoch=0, + std::uint64_t activeRevision=0) noexcept { + if (!ready_ || lane >= laneCount || !left || !right || frames == 0) return; + auto& eq = eqs_[lane]; + const bool rackOff=rackBypassed_[lane].load(std::memory_order_acquire); + eq.setExternalBypass(insertBypassed_[lane]||rackOff); + if (!eq.transitioning() && acknowledgements_[lane].canPush()) { + Command command{}; + if (pending_[lane].pop(command)) { + // Structural re-publication may inherit this bank. Do not + // apply a queued edit from a superseded epoch/revision. + const bool sessionMatches = (activeEpoch==0 && activeRevision==0) || + (command.deviceEpoch==activeEpoch && + command.graphRevision==activeRevision); + bool applied=false; + if(sessionMatches) { + if(command.gate) { + applied=command.installed||eq.resetToFlat(); + if(applied) { + insertBypassed_[lane]=!command.installed||command.bypassed; + eq.setExternalBypass(insertBypassed_[lane]||rackOff); + } + } else applied=eq.applyPreparedBand(command.edit); + } + Ack ack{command.requestId,command.deviceEpoch,command.graphRevision, + command.lane,command.slot,command.edit.band,applied, + command.gate,command.installed,command.bypassed}; + // Can only fail if another thread illegally writes the same + // SPSC consumer ACK ring. The producer cannot fill it. + (void)acknowledgements_[lane].push(ack); + } + } + eq.processStereo(left,right,frames); + } + // Control thread: drain after audio block; validate the ACK's graph epoch + // and revision AGAIN before changing the public accepted UI state. + bool pollAck(std::size_t lane, Ack& result) noexcept { + return lane < laneCount && acknowledgements_[lane].pop(result); + } + // Tests and UNPUBLISHED topology authoring only; querying while render() + // runs is a data race. Live readbacks MUST use the ACK value. + [[nodiscard]] Band offlineBand(std::size_t lane, std::size_t slot) const noexcept { + return lane < laneCount ? eqs_[lane].band(slot) : Band{}; + } +private: + struct Command final { + std::uint64_t requestId=0,deviceEpoch=0,graphRevision=0; + std::uint8_t lane=0,slot=0; + bool gate=false,installed=false,bypassed=false; + ChannelEq::PreparedBandEdit edit{}; + }; + std::array eqs_{}; + std::array insertBypassed_{}; // AUDIO or unpublished CONTROL + std::array,laneCount> rackBypassed_{}; // CONTROL->AUDIO + std::array,laneCount> pending_{}; + std::array,laneCount> acknowledgements_{}; + double sampleRate_=0.0; + bool ready_=false; +}; +} // namespace armix::builtin_fx diff --git a/engine/builtin_fx/README.md b/engine/builtin_fx/README.md new file mode 100644 index 000000000..332e8c5bc --- /dev/null +++ b/engine/builtin_fx/README.md @@ -0,0 +1,117 @@ +# ArSonMix native built-in FX (not FactoryFX/VST3) + +This folder is owned by `masarray/arsonmix`. **It does not depend on or modify +ArSonEQ**, whose advanced 24-band/dynamic/M-S/FabFilter-class development remains +independent. `FactoryFX/` elsewhere means separately packaged user/factory +**VST3 plugins**, not native mixer effects. Do not put this source into VST3 +scan/packaging flows. + +## Initial native DSP module + +- `BuiltInFxCatalog.h`: compile-time identity `armix.builtin.channel-eq.v1` + and stable 8-slot IDs: HPF / low shelf / PEQ 1–4 / high shelf / LPF. +- `ChannelEq.h`: minimal portable C++20, eight fixed slots, max ten IIR biquad + sections, active-slot fast path, 12/24 dB/oct HPF/LPF, +/-18 dB PEQ/shelves, + frequency/Q validation, per-instance stereo filter memories, 5ms old/new + bank crossfade. Live `prepareBandEdit()` computes coefficients on CONTROL; + `applyPreparedBand()` applies them on AUDIO without trigonometry. No analyzer, + dynamic EQ, M/S, oversampling, WebView, JUCE, VST3 loader, heap allocations, + mutexes, FFT or additional sample buffering. +- `CMakeLists.txt`: self-contained standalone headless native CTest using the + same `tests/builtin_channel_eq_test.cpp` as the main project; no JUCE needed. + +## Safe integration contract (not implemented by this folder-only candidate) + +One `ChannelEq` per **accepted ChannelId** and audio epoch, initialized at the +actual device sample rate. The existing **single** native audio callback owns +`processMono/processStereo` in-place on its existing prepared channel PCM. An +accepted control command is first compiled using +`ChannelEq::prepareBandEdit()` **off callback**. Its small immutable packet is +handed to the existing bounded control queue and then +`applyPreparedBand()` is invoked on the exclusive audio owner **at a block +boundary**. `setBand()` is an offline / unpublished-graph convenience only, +never invoke it in the live callback (it computes trig). The audio owner can +also call the cheap `resetToFlat()` at a safe block boundary. **Never mutate +the live instance from the WebView/UI/control thread while processing**. DSP has no independent callback or +worker and cannot obtain an audio input device. + +Typical chain is verified hardware IN -> trim -> channel EQ -> existing vendor +FX rack -> fader -> PRE/POST sends -> MAIN, but binding this point requires +review of the current single-owner native graph. Default disabled EQ must be +bitwise-transparent. The rack-wide FX bypass is separate from the channel EQ +and must preserve individual insert states. UI is added to the **one approved** +`/preview/` component system only when native snapshot/ACK and Show recall +are implemented; a browser illustration must never claim live audio. + +Control packet must carry validated decimal-string ChannelId, device epoch and +base graph revision. After native accept, browser still needs a matching +snapshot with all 8 band settings and computed response. Readback and response +must be prepared from the exclusive owner or an immutable copy off callback; +never sample live biquad histories on another thread. Show save/restore owns +logical settings, not a plugin binary, and must preserve applied revision. +Rapid automation during an unfinished 5ms transition needs explicit owner +queue/coalescing validation before host integration; this candidate does not +claim click-free arbitrary multiwriter automation. + +## Validation and release status + +This is a **real native DSP and tests**, but **not yet wired to ArSonMix audio +PCM or UI**. No new buttons, routes or VST3 scan are installed by this code. +This is intentionally separate from ongoing P0 mixer recovery and native FX +rack/WIRE PRs. Run standalone CTest; Windows final host build, actual CPU +benchmarks, physical ASIO/driver FAT and accepted GUI integration are separate +release gates. `addedLatencySamples()==0` means no DSP buffering/lookahead; +minimum-phase IIR still has frequency-dependent group delay, and hardware +roundtrip latency is not zero. + +## Live PCM seam (P1 integration on the PR branch only) + +The existing `LiveChannelFxGraph` is the ONLY native audio owner. The graph +prepares a `ChannelEqBank` using the ACTUAL negotiated sample rate on its +control thread, then calls `render(strip,L,R,frames)` immediately before the +existing vendor FX racks in the SAME `PreparedMixerBlock::process` channel +callback. All 14 lanes are flat and bitwise transparent on first launch. +A new SPSC control-to-audio queue accepts precomputed immutable edits and +an independent bounded ACK ring communicates actual applied settings back +to the message thread, with request ID + original device epoch + graph +revision. When a previous 5ms fade is running, the next edit waits for the +next block; queue saturation rejects without mutating DSP. Never treat a +QUEUED command as applied, or ACK from an old epoch as a new accepted state. + +The isolated graph seam is **not an operator feature** until a host command +adapter, stable ChannelId lookup, state preservation across topology changes, +Show recall and the sole approved `/preview/` control with matching accepted +ACK/snapshot have been proven. This PR must not be merged as a finished EQ +plugin or released as an audible operator feature before those gates pass. +See `tests/builtin_channel_eq_bank_test.cpp` for bounded queue / ACK fixtures. + +Reference mathematics: W3C Audio EQ Cookbook (RBJ), 2021, +https://www.w3.org/TR/audio-eq-cookbook/ . Interaction inspiration: FL Studio +Fruity Parametric EQ, **not a copy of its source code, icons, or artwork**. + +## Built-in EQ native product adapter — PR #423 + +The DSP is owned by this ArSonMix repository; no code, build product, CI or plugin identity in `masarray/arson-eq` is modified. It is **not a VST3 module** and does not appear in the user-owned plugin scanner or FactoryFX. + +The 8 fixed slots (HPF/LOW/PEQ1–4/HIGH/LPF) are processed in-place before vendor inserts on the original M4 10CH+4AUX graph and the admitted ChannelId native graph. M4→ChannelId and structural native revisions retain one shared EQ bank and correct stable input/aux ChannelIds. Extra dynamic channels, MAIN and MONITOR are **not** mapped to the 14 legacy EQ lanes; the controls fail closed rather than borrowing a strip's EQ. Structural changes inherit the bank only for the same hardware clock; stale revisions are rejected at the actual DSP apply boundary. Never insert a second callback, FFT, latency buffer or ArSonEQ 24-band engine. + +### Operator UI + +The approved `/preview/` mixer has a small **EQ** button beside each supported channel FX rack header; the separate compact EQ overlay is implemented in `site/preview-v2/assets/mixer-builtin-eq.{js,css}` as an INTERNAL source of the approved deterministic Pages/JUCE renderer. The `/preview/` page marks controls as **UI DEMO / NO AUDIO**. The native JUCE bridge resolves the actual accepted decimal-string `ChannelId`, current epoch and PCM graph revision; no browser-inferred lane or active VST insert. A control command is `builtinEqSetBand` through the existing `arMixAction` bridge, returning QUEUED (not applied). Only the audio callback ACK plus a subsequent native parameter snapshot updates the browser's accepted EQ state. A failed/stale/busy/unsupported edit leaves accepted parameters unchanged, and hardware routing is never activated by opening the EQ editor. + +### Remaining release qualification + +Native Windows exact-SHA executable, CTest, visual equivalence against the user-approved deployed `/preview/`, no-allocation xrun stress, device reconnect, scenario/Show restoration, and real ASIO hardware ears-on FAT must all be independently verified. These gates are **not** inferred from native DSP unit success or from a static browser rendering. Draft PR is not a production release; no merge without accepting multi-PR conflict with the active product integration owner. + +### Channel EQ lifecycle and plotting regression (2026-11-06) + +Native control readback clamps disabled default cutoff frequencies to the exact +DSP preparation limit min(20 kHz, 45% negotiated device rate), including 8/16/32 +kHz devices. The editor uses the actual native sample rate for the complete +display response computation, preparing filter coefficients once per redraw +instead of once per frequency pixel. Touch/mouse pointer drags display a dashed, +**not yet applied** response; user release sends only one bounded control +intent. Graph/device hotplug, migration or channel disappearance invalidates +the editor until a new authoritative native snapshot is requested. A matching +epoch, PCM revision and exact native ChannelId are required before the editor +accepts a parameter snapshot. No visual gesture starts a new callback. diff --git a/engine/core/DynamicChannelFxLeaseBank.h b/engine/core/DynamicChannelFxLeaseBank.h index 46c29f4f8..697d1fdf1 100644 --- a/engine/core/DynamicChannelFxLeaseBank.h +++ b/engine/core/DynamicChannelFxLeaseBank.h @@ -6,6 +6,8 @@ #include #include #include +#include +#include #include #include #include @@ -33,6 +35,9 @@ class DynamicChannelFxLeaseBank final { ChannelId id{}; ProcessingFormat format=ProcessingFormat::stereo; std::vector inserts; // CONTROL only; no creation on callback + // Reused over revision changes. This flag overrides the effective + // output without changing the individual FxInstance bypass flags. + std::shared_ptr> rackBypassed; }; // Occupied CH1 vendor/Orbit owner remains alive with accepted PCM. @@ -68,6 +73,9 @@ class DynamicChannelFxLeaseBank final { if(lane<0||lane>=FxGraph::fxSlots||!nativeId.value)return false; Assignment staged; staged.id=nativeId;staged.format=format; + // Preserve master OFF across M4->ChannelId, even with EQ-only rack. + staged.rackBypassed=std::make_shared>( + prior.rackBypassed(lane)); for(int slot=0;slot>(false); // CONTROL allocation row.count=static_cast(b.inserts.size()); for(std::size_t i=0;ibypassRequested.store(bypass,std::memory_order_release); return true; } + bool setRackBypass(std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,ChannelId id, + bool bypass) const noexcept { + if(expectedEpoch!=epoch_||expectedRevision!=revision_||!id.value) + return false; + const auto* row=find(id); + if(!row||!row->rackBypassed)return false; + row->rackBypassed->store(bypass,std::memory_order_release); + return true; + } + bool rackBypassed(ChannelId id) const noexcept { + const auto* row=find(id); + return row&&row->rackBypassed && + row->rackBypassed->load(std::memory_order_acquire); + } // The actual prepared vendor instance is also the native editor owner; // never synthesize a WebView editor or use a catalog name as identity. Lease leaseEditor(std::uint64_t expectedEpoch, @@ -199,7 +224,7 @@ class DynamicChannelFxLeaseBank final { retained.reserve(prior.rows_.size()); for(const auto& row:prior.rows_) { Assignment item; - item.id=row.id;item.format=row.format; + item.id=row.id;item.format=row.format;item.rackBypassed=row.rackBypassed; item.inserts.reserve(row.count); for(std::size_t slot=0;slotrackBypassed && + row->rackBypassed->load(std::memory_order_acquire); for(std::size_t i=0;icount;++i) - row->raw[i]->render(left,right,frames); + row->raw[i]->render(left,right,frames,rackOff); } private: @@ -262,6 +290,7 @@ class DynamicChannelFxLeaseBank final { ChannelId id{}; ProcessingFormat format=ProcessingFormat::stereo; std::uint8_t count=0; + std::shared_ptr> rackBypassed; // persists across revisions std::array owners{}; std::array raw{}; }; diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index c767600af..178d356d9 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -4,6 +4,8 @@ #include "DynamicConsoleRoutingView.h" #include "RealtimeRoutePublisher.h" #include "RealtimeRenderPermit.h" +#include "../builtin_fx/ChannelEqBank.h" +#include #include #include #include @@ -28,6 +30,10 @@ class DynamicNativeSessionPublisher final { void* context=nullptr; // unchanged owner.get(), RT raw pointer void (*render)(void*,ChannelId,float*,float*,int) noexcept=nullptr; std::uint64_t deviceEpoch=0,graphRevision=0; + // Built-in native EQ is independent of the vendor VST3 plan. + // Populated on initial M4→ChannelId admission, never on callback. + std::shared_ptr builtInEq; + std::array builtInEqIds{}; bool valid() const noexcept { return (!owner&&!context&&!render&&!deviceEpoch&&!graphRevision) || (owner&&context==owner.get()&&render&& @@ -39,6 +45,8 @@ class DynamicNativeSessionPublisher final { DynamicPreparedMixerBlock graph; DynamicConsoleRoutingView routing; FxPlan fx; // SAME lifetime and revision as native PCM graph + std::shared_ptr builtInEq; + std::array builtInEqIds{}; int physicalInputs=0; bool monitor=false; }; @@ -102,6 +110,19 @@ class DynamicNativeSessionPublisher final { report.fault=Fault::invalidGraph;return report; } prepared->physicalInputs=request.physicalInputs; + // An explicitly supplied EQ bank is authoritative (notably Show V5 + // recall). Structural edits that do not supply one retain the single + // prior RT-owned bank and its histories. Sharing/copying is CONTROL + // only; the callback always sees exactly one bank per graph snapshot. + // Never silently replace a fresh, restored Show with prior PCM state. + const auto* prior=publisher_.controlPrepared(proposedDeviceEpoch,expectedRevision); + if(fx.builtInEq) { + prepared->builtInEq=fx.builtInEq; + prepared->builtInEqIds=fx.builtInEqIds; + } else if(prior && prior->builtInEq) { + prepared->builtInEq=prior->builtInEq; + prepared->builtInEqIds=prior->builtInEqIds; + } prepared->fx=std::move(fx); // one accepted control-plane publication prepared->monitor=std::any_of(roster.channels().begin(), roster.channels().end(),[](const ChannelStripDefinition& row) { @@ -178,6 +199,18 @@ class DynamicNativeSessionPublisher final { // Snapshot ownership pins the M4 instance throughout this callback; // only control-thread retirement releases the shared owner. const auto dispatch=[&](ChannelId id,float* l,float* r,int n) noexcept { + // Independent minimum-phase EQ BEFORE vendor inserts, exactly + // once per native ChannelId strip. Unmapped extra native buses + // pass through flat; never guess their identity by strip index. + if(auto* eq=snap->prepared->builtInEq.get()) { + for(std::size_t lane=0;laneprepared->builtInEqIds.size();++lane) { + if(snap->prepared->builtInEqIds[lane]==id) { + eq->render(lane,l,r,static_cast(n), + snap->deviceEpoch,snap->graphRevision); + break; + } + } + } const auto& acceptedFx=snap->prepared->fx; if(acceptedFx.render) acceptedFx.render(acceptedFx.context,id,l,r,n); @@ -199,7 +232,63 @@ class DynamicNativeSessionPublisher final { return current?¤t->routing:nullptr; } - // M3C realtime parameters on the accepted ChannelId graph ONLY. + // CONTROL APIs: actual native ChannelId identity, no ordinal fallback. + // success = queued only; ACK is generated exclusively by AUDIO render. + bool queueBuiltInEqEdit(std::uint64_t epoch,std::uint64_t revision,ChannelId id, + std::size_t slot,const armix::builtin_fx::Band& band, + std::uint64_t requestId) noexcept { + if(!requestId||!id.value)return false; + return publisher_.updateActiveControl(epoch,revision, + [&](Prepared& p) noexcept { + if(!p.builtInEq)return false; + for(std::size_t lane=0;lanequeueBandEdit(lane,slot,band, + requestId,epoch,revision); + return false; + }); + } + bool queueBuiltInEqGate(std::uint64_t epoch,std::uint64_t revision,ChannelId id, + bool installed,bool bypassed,std::uint64_t requestId) noexcept { + if(!requestId||!id.value)return false; + return publisher_.updateActiveControl(epoch,revision, + [&](Prepared& p) noexcept { + if(!p.builtInEq)return false; + for(std::size_t lane=0;lanequeueGateEdit(lane,installed,bypassed, + requestId,epoch,revision); + return false; + }); + } + // Header bypass of one accepted ChannelId EQ owner, without touching + // the remembered individual EQ gate or its eight filter bands. + bool setBuiltInEqRackBypass(std::uint64_t epoch,std::uint64_t revision, + ChannelId id,bool bypass) noexcept { + if(!id.value)return false; + return publisher_.updateActiveControl(epoch,revision, + [&](Prepared& p) noexcept { + if(!p.builtInEq)return false; + for(std::size_t lane=0;lanesetRackBypass(lane,bypass); + return false; + }); + } + bool pollBuiltInEqAck(std::uint64_t epoch,std::uint64_t revision,ChannelId id, + armix::builtin_fx::ChannelEqBank::Ack& ack) noexcept { + if(!id.value)return false; + return publisher_.updateActiveControl(epoch,revision, + [&](Prepared& p) noexcept { + if(!p.builtInEq)return false; + for(std::size_t lane=0;lanepollAck(lane,ack); + return false; + }) && ack.deviceEpoch==epoch && ack.graphRevision==revision; + } + + // M3C realtime parameters on the accepted ChannelId graph ONLY. // Caller must propagate the real device epoch and native ACK revision. // Rejected/stale edits leave the last accepted PCM unchanged. bool setPhysicalSource(std::uint64_t epoch,std::uint64_t revision, diff --git a/engine/core/LiveChannelFxGraph.h b/engine/core/LiveChannelFxGraph.h index 281b172f9..393e9f852 100644 --- a/engine/core/LiveChannelFxGraph.h +++ b/engine/core/LiveChannelFxGraph.h @@ -2,6 +2,7 @@ #pragma once #include "PreparedMixerBlock.h" #include "FxBypassEnvelope.h" +#include "../builtin_fx/ChannelEqBank.h" #include #include #include @@ -79,7 +80,7 @@ class LiveChannelFxGraph final { processing.clear(std::memory_order_release); return ok; } - void render(float* left,float* right,int samples) noexcept { + void render(float* left,float* right,int samples,bool rackBypassed=false) noexcept { if(processing.test_and_set(std::memory_order_acquire)) { contention.fetch_add(1,std::memory_order_relaxed); juce::FloatVectorOperations::clear(left,samples); @@ -87,7 +88,8 @@ class LiveChannelFxGraph final { return; } // G5C: atomic request from control; fade and scratch RT-owned. - bypassFade.request(bypassRequested.load(std::memory_order_relaxed)); + // Master rack bypass affects the WET/DRY envelope, never the remembered insert preference. + bypassFade.request(rackBypassed || bypassRequested.load(std::memory_order_relaxed)); if(bypassFade.fullyBypassed()) { processing.clear(std::memory_order_release); return; @@ -191,6 +193,49 @@ class LiveChannelFxGraph final { bool setAuxSendGain(int source,int bus,float gain) noexcept { return setAuxSendGain(source,bus,SendTap::postFader,gain); } + using BuiltInEqAck=armix::builtin_fx::ChannelEqBank::Ack; + bool prepareBuiltInEq(double rate) noexcept {return builtinEq_ && builtinEq_->prepare(rate);} + // CONTROL-only lease for migration to the accepted native ChannelId + // renderer. Lifetime pinned by BOTH graph publishers, not the GUI. + std::shared_ptr + builtInEqLease() const noexcept {return builtinEq_;} + // CONTROL on an UNPUBLISHED candidate only. Share the same RT histories + // across same-rate routing revisions, not an independent EQ sound. + void inheritBuiltInEqFrom(const LiveChannelFxGraph& prior) noexcept { + if(builtinEq_ && prior.builtinEq_ && + builtinEq_->sampleRate()==prior.builtinEq_->sampleRate()) { + builtinEq_=prior.builtinEq_; + for(int lane=0;lane=0&&lanesetBandOffline(static_cast(lane),slot,b); + } + bool setBuiltInEqGateOffline(int lane,bool installed,bool bypassed) noexcept { + return lane>=0&&lanesetGateOffline(static_cast(lane), + installed,bypassed); + } + bool queueBuiltInEqEdit(int lane,std::size_t slot,const armix::builtin_fx::Band& b, + std::uint64_t req,std::uint64_t epoch,std::uint64_t rev) noexcept { + return lane>=0&&lanequeueBandEdit( + static_cast(lane),slot,b,req,epoch,rev); + } // producer on control; success = queued, not applied + bool queueBuiltInEqGate(int lane,bool installed,bool bypassed, + std::uint64_t req,std::uint64_t ep,std::uint64_t rev) noexcept { + return lane>=0&&lanequeueGateEdit( + static_cast(lane),installed,bypassed,req,ep,rev); + } + bool pollBuiltInEqAck(int lane,BuiltInEqAck& ack) noexcept { + return lane>=0&&lanepollAck(static_cast(lane),ack); + } // control-only, validate epoch/rev before UI use int activeInserts() const noexcept{return activeInserts_;} bool setStripControl(int channel,float gain,float pan, bool mono,bool mute,bool solo) noexcept { @@ -227,6 +272,21 @@ class LiveChannelFxGraph final { fx->bypassRequested.store(bypass,std::memory_order_release); return true; } + // One atomic rack override per channel. Individual slot bypass flags stay + // unchanged; ON restores the previous enabled/disabled combination. + bool setRackBypass(int strip,bool bypass) noexcept { + if(strip<0||strip>=fxSlots||!builtinEq_ || + !builtinEq_->setRackBypass(static_cast(strip),bypass)) + return false; + // Same rack override for native EQ + VST3, preserving each slot's + // own bypass preference; both envelopes smooth on AUDIO. + rackBypassed_[strip].store(bypass,std::memory_order_release); + return true; + } + bool rackBypassed(int strip) const noexcept { + return strip>=0&&stripcatalogId!=catalogId)return false; for(int i=0;i=fxSlots)return; + // In-place channel EQ before existing vendor VST3 inserts/PRE sends. + // Default OFF is bitwise-transparent; no second callback. + builtinEq_->render(static_cast(strip),l,r, + static_cast(samples), + builtinEqEpoch_,builtinEqRevision_); + const bool rackOff=rackBypassed_[strip].load(std::memory_order_acquire); const int count=counts_[strip]; // immutable, prepared OFF RT if(count>0) { for(int slot=0;slotrender(l,r,samples); // no shared_ptr copies or RT heap use + instance->render(l,r,samples,rackOff); // one RT owner, no heap use } } else if(strip==0 && externalFx) externalFx(externalContext,strip,l,r,samples); @@ -311,10 +381,14 @@ class LiveChannelFxGraph final { } private: + std::shared_ptr builtinEq_{ + std::make_shared()}; + std::uint64_t builtinEqEpoch_=0,builtinEqRevision_=0; // set BEFORE publishing std::unique_ptr block_; RealtimeStripControls controls_ {}; FxBank processors_ {}; std::array counts_ {}; + std::array,fxSlots> rackBypassed_{}; // CONTROL write; one RT read per lane int activeInserts_=0; int pluginQuantum_=512; int mainOutputLeft_=0,mainOutputRight_=1; diff --git a/engine/core/UnifiedLegacyProductionAdmission.h b/engine/core/UnifiedLegacyProductionAdmission.h index 37d431806..f3a98d2cd 100644 --- a/engine/core/UnifiedLegacyProductionAdmission.h +++ b/engine/core/UnifiedLegacyProductionAdmission.h @@ -59,6 +59,12 @@ struct UnifiedLegacyAccepted final { fxOwners->setInsertBypass(epoch,revision,id,slot, instanceId,bypass); } + bool setFxRackBypass(const DynamicNativeSessionPublisher& publisher, + std::uint64_t epoch,std::uint64_t revision, + ChannelId id,bool bypass) const noexcept { + return matches(publisher,epoch,revision) && + fxOwners->setRackBypass(epoch,revision,id,bypass); + } DynamicChannelFxLeaseBank::Lease leaseFxEditor( const DynamicNativeSessionPublisher& publisher, std::uint64_t epoch,std::uint64_t revision,ChannelId id, @@ -181,6 +187,13 @@ class UnifiedLegacyProductionAdmission final { (*static_cast(ctx))(id,l,r,n); }; plan.deviceEpoch=deviceEpoch;plan.graphRevision=expectedPcmRevision+1; + // One shared lightweight native DSP owner across M4→ChannelId + // cutover. Do NOT instantiate ArSonEQ/VST3 or reset user curves. + plan.builtInEq=acceptedM4Fx.builtInEqLease(); + for(int i=0;i(i)]=candidate.ids.inputs[i]; + for(int b=0;b(stripCount+b)]=candidate.ids.aux[b]; result.native=publisher.commit(candidate.roster,candidate.request, expectedPcmRevision,deviceEpoch,currentHardwareEpoch, allOutputsDisarmed,std::move(plan)); diff --git a/scripts/approved_fx_rack_power.py b/scripts/approved_fx_rack_power.py new file mode 100644 index 000000000..fd91331ca --- /dev/null +++ b/scripts/approved_fx_rack_power.py @@ -0,0 +1,32 @@ +"""Approved single-GUI FX rack power semantics, injected at the ONE Pages build. + +The historical V28 source HTML is immutable. Apply exactly FOUR audited +semantic substitutions to its JavaScript when assembling both public /preview/ +and native JUCE WebView2. No additional stylesheet, second state store, or +private fork of the mixer. t.fxOn is rack authority, slotBypass[] is the +preserved per-insert preference. Effective = fxOn && !slotBypass[i]. +""" +def apply_authoritative_fx_power(html: str) -> str: + substitutions = [ + ( + "name==='None'?'is-empty':t.slotBypass[i]?'is-bypassed':'is-active'", + "name==='None'?'is-empty':(!t.fxOn||t.slotBypass[i])?'is-bypassed':'is-active'", + ), + ( + 'aria-pressed="\'+Boolean(!t.slotBypass[i])+\'">', + 'aria-pressed="\'+Boolean(t.fxOn&&!t.slotBypass[i])+\'">', + ), + ( + "title=\"'+(t.slotBypass[i]?'Enable':'Bypass')+' only insert", + "title=\"'+(!t.fxOn?'Rack bypassed, saved '+(t.slotBypass[i]?'OFF':'ON'):t.slotBypass[i]?'Enable':'Bypass')+' only insert", + ), + ( + "aria-label=\"'+(t.slotBypass[i]?'Enable':'Bypass')+' only FX insert", + "aria-label=\"'+(!t.fxOn?'Rack bypassed, saved '+(t.slotBypass[i]?'OFF':'ON'):t.slotBypass[i]?'Enable':'Bypass')+' only FX insert", + ), + ] + for before, after in substitutions: + if html.count(before) != 1: + raise ValueError("FX master semantics anchor missing or ambiguous: " + before[:90]) + html=html.replace(before,after,1) + return html diff --git a/scripts/build_pages.py b/scripts/build_pages.py index e0e92b0c3..388a88f4e 100644 --- a/scripts/build_pages.py +++ b/scripts/build_pages.py @@ -2,6 +2,8 @@ from pathlib import Path import argparse,os,json,shutil,subprocess,sys from compile_approved_css import optimize_assets +from compose_builtin_eq import compose_builtin_eq +from approved_fx_rack_power import apply_authoritative_fx_power ROOT=Path(__file__).resolve().parents[1] p=argparse.ArgumentParser() p.add_argument('--out',default='dist-pages') @@ -26,6 +28,12 @@ # are source inputs only; this output has ONE HTML, ONE CSS/JS/asset set. (buttons_dest/'assets').mkdir(parents=True) canonical_html=(canonical/'index.html').read_text(encoding='utf-8') +# Compose the OPTIONAL built-in EQ operator control into the approved assembled +# /preview/ only. Preserve historical internal seed HTML byte-for-byte: V28 +# baseline recovery must remain possible. Both public Pages and the JUCE native +# binary use this SAME deterministic assembled output; no second mixer UI. +canonical_html=compose_builtin_eq(canonical_html) + special=('mixer-control-keys.css','mixer-control-keys.js') sprite='mute-solo-pfl-56x37.png' for src in sorted((canonical/'assets').iterdir()): @@ -59,6 +67,7 @@ if canonical_html.count('')!=1 or probe_tag in canonical_html: raise SystemExit('Approved Pages profiler injection must have exactly one body') canonical_html=canonical_html.replace('',probe_tag+'\n',1) +canonical_html=apply_authoritative_fx_power(canonical_html) # Stage C: compile only DEPLOYED copies, never modify locked V28 source # owners or approved PNG artwork. No new CSS/override or second renderer. canonical_html,css_compilation=optimize_assets(canonical_html,buttons_dest/'assets',runtime_bundle=True) diff --git a/scripts/compose_builtin_eq.py b/scripts/compose_builtin_eq.py new file mode 100644 index 000000000..ecad683d1 --- /dev/null +++ b/scripts/compose_builtin_eq.py @@ -0,0 +1,69 @@ +"""Deterministic additive Built-in EQ in the ONE approved ArSonMix /preview/. + +Never mutate frozen V28 HTML, VST3 catalog, or create another renderer. +This P0 adapter composes the fixed PRE-VST3 native EQ into the existing rack. +""" +SCRIPT = '' +CLICK_BEFORE = " if(a==='openPlugin'){openFastPicker(t,Number(btn.dataset.slot),btn);return;}" +CLICK_AFTER = """ if(a==='openBuiltinEq'){window.ArSonMixBuiltinEq?.open(t);return;} + if(a==='builtinEqPower'){window.ArSonMixBuiltinEq?.power(t);return;} + if(a==='builtinEqRemove'){window.ArSonMixBuiltinEq?.remove(t);return;}""" +RACK_START = 'function sectionFx(t){' +RACK_HOOK = """window.__ARMIX_BUILTIN_EQ_REFRESH__=function(uiId){ + const t=tracks.concat(master).find(x=>x.id===Number(uiId)); + if(t)refreshStrip(t); +}; +window.__ARMIX_BUILTIN_EQ_NOTIFY__=message=>say(message); +window.__ARMIX_BUILTIN_EQ_FIND_CHANNEL__=function(nativeChannelId){ + return tracks.concat(master).find(t=> + window.__ARMIX_BUILTIN_EQ_CHANNEL__?.resolve?.(t.id)===nativeChannelId + )||null; +}; +function sectionFx(t){""" +RACK_ROWS = " for(const {name,i} of rows){" +RACK_ROWS_HOOK = """ out+=window.ArSonMixBuiltinEq?.slotMarkup?.(t,materialIcon)||''; + for(const {name,i} of rows){""" +PICKER_START = " plugEl('fastResults').innerHTML=list.length?list.map(p=>" +PICKER_HELPER_START = 'function renderFastPicker(){' +PICKER_HELPER = """function insertChosenBuiltinEq(){ + const track=tracks.concat(master).find(x=>x.id===activeFxTarget?.channelId); + if(!track||track.kind==='master'||!window.ArSonMixBuiltinEq?.insert(track)){ + say('Parametric EQ insert rejected · no accepted channel or already installed'); + return false; + } + setFastPicker(false); + say(track.name+' · Parametric EQ requested for FX Rack · click rack row to edit'); + return true; +} +function renderFastPicker(){""" +RACK_COUNT = "FX '+used.length+'" +RACK_COUNT_HOOK = "FX '+(used.length+(window.ArSonMixBuiltinEq?.installed?.(t)?1:0))+'" +PICKER_HOOK = """ const builtin=(!q||['parametric eq','peq','channel eq','built-in fx'].some(name=>name.includes(q)))? + '
BUILT-IN FX
':''; + plugEl('fastResults').innerHTML=builtin+'
VST3 PLUGINS
'+(list.length?list.map(p=>""" +PICKER_END = """).join(''):'
No matching effects
';""" +PICKER_END_HOOK = """).join(''):'
No matching effects
');""" +PICKER_CLICK = " const btn=e.target.closest('[data-fast-id]');if(btn)insertCatalogPlugin(btn.dataset.fastId);" +PICKER_CLICK_HOOK = """ const eq=e.target.closest('[data-fast-builtin-eq]'); + if(eq){insertChosenBuiltinEq();return;} + const btn=e.target.closest('[data-fast-id]');if(btn)insertCatalogPlugin(btn.dataset.fastId);""" +PICKER_ENTER = "if(b){e.preventDefault();insertCatalogPlugin(b.dataset.fastId);}" +PICKER_ENTER_HOOK = "if(b){e.preventDefault();if(b.hasAttribute('data-fast-builtin-eq'))insertChosenBuiltinEq();else insertCatalogPlugin(b.dataset.fastId);}" + +def compose_builtin_eq(source: str) -> str: + anchors=(CLICK_BEFORE,RACK_START,RACK_ROWS,RACK_COUNT,PICKER_HELPER_START, + PICKER_START,PICKER_END,PICKER_CLICK,PICKER_ENTER) + if source.count('')!=1 or SCRIPT in source or 'openBuiltinEq' in source: + raise ValueError('Built-in EQ expects pristine approved HTML seed') + if any(source.count(a)!=1 for a in anchors): + raise ValueError('Built-in EQ requires exactly one canonical rack/picker owner') + return (source.replace('',SCRIPT+'\n',1) + .replace(RACK_START,RACK_HOOK,1) + .replace(RACK_ROWS,RACK_ROWS_HOOK,1) + .replace(RACK_COUNT,RACK_COUNT_HOOK,1) + .replace(PICKER_HELPER_START,PICKER_HELPER,1) + .replace(PICKER_START,PICKER_HOOK,1) + .replace(PICKER_END,PICKER_END_HOOK,1) + .replace(PICKER_CLICK,PICKER_CLICK_HOOK,1) + .replace(PICKER_ENTER,PICKER_ENTER_HOOK,1) + .replace(CLICK_BEFORE,CLICK_AFTER+'\n'+CLICK_BEFORE,1)) diff --git a/site/preview-v2/assets/mixer-builtin-eq.js b/site/preview-v2/assets/mixer-builtin-eq.js new file mode 100644 index 000000000..245d6927b --- /dev/null +++ b/site/preview-v2/assets/mixer-builtin-eq.js @@ -0,0 +1,348 @@ +/* ArSonMix Built-in Parametric EQ: small operator overlay in the ONLY /preview/. + * Browser renders RESPONSE FROM ACCEPTED PARAMETERS, never audio/FFT/WebAudio. + * Static Pages is explicitly a visual DESIGN DEMO. Native uses ACK + LATER + * authoritative snapshot; browser drafts never enter the mixer graph. */ +(()=>{ + 'use strict'; + const LABELS=['HPF','LOW','P1','P2','P3','P4','HIGH','LPF']; + const TYPES=['hp','ls','bell','bell','bell','bell','hs','lp']; + const DEFAULT=[80,160,250,500,1500,4500,9500,18000]; + const COLORS=['#9dc7ff','#eabb80','#e0a5db','#8eace8','#86d4ac','#e0b67c','#d99da8','#86cfe4']; + const empty=()=>DEFAULT.map((f,i)=>({enabled:false,frequencyHz:f,gainDb:0,q:i>=2&&i<=5?1:.70710678,slope:12})); + const clamp=(v,lo,hi)=>Math.max(lo,Math.min(hi,v)); + const maxHz=()=>Math.min(20000,Math.floor(sampleRate*.45)); + const hzToX=(hz,w)=>28+Math.log(clamp(hz,20,20000)/20)/Math.log(1000)*(w-58); + const xToHz=(x,w)=>20*Math.pow(1000,clamp((x-28)/(w-58),0,1)); + const dbToY=(db,h)=>h/2-clamp(db,-18,18)*(h-39)/36; + const yToDb=(y,h)=>clamp((h/2-y)*36/(h-39),-18,18); + const isCut=i=>i===0||i===7; + const gainEnabled=i=>i!==0&&i!==7; + const mk=(tag,cl,text)=>{const el=document.createElement(tag);if(cl)el.className=cl;if(text!==undefined)el.textContent=text;return el;}; + const root=mk('section');root.id='mxBuiltinEq';root.hidden=true;root.setAttribute('role','dialog');root.setAttribute('aria-modal','false');root.setAttribute('aria-label','Built-in parametric equalizer'); + const head=mk('header','mx-eq-top'),mark=mk('i','mx-eq-mark'),brand=mk('strong','', 'ArSonMix · Parametric EQ'); + const channelLabel=mk('span','mx-eq-channel'),spacer=mk('span','mx-eq-spacer'),mode=mk('span','mx-eq-mode'); + const close=mk('button','mx-eq-close','×');close.type='button';close.title='Close channel EQ';head.append(mark,brand,channelLabel,spacer,mode,close); + const workspace=mk('div','mx-eq-workspace'); + const graph=mk('div','mx-eq-chart'),canvas=mk('canvas'),hint=mk('div','mx-eq-hint','LOG FREQUENCY · RESPONSE (NOT SPECTRUM)'),legend=mk('div','mx-eq-legend','±18 dB');canvas.setAttribute('aria-label','Parametric EQ frequency response graph');graph.append(canvas,hint,legend); + const rail=mk('div','mx-eq-rail'),buttons=[];LABELS.forEach((title,i)=>{const b=mk('button','mx-eq-band',title);b.type='button';b.dataset.slot=String(i);b.style.setProperty('--eq-band',COLORS[i]);const led=mk('i');b.prepend(led);rail.append(b);buttons.push(b);}); + const controls=mk('div','mx-eq-controls'); + const powerCol=mk('div','mx-eq-vertical');const power=mk('button','mx-eq-switch','ENABLE');power.type='button';power.setAttribute('aria-pressed','false');const flat=mk('button','mx-eq-reset','FLAT BAND');flat.type='button';powerCol.append(power,flat); + const field=(label,type,min,max,step)=>{const wrap=mk('label','',label),v=mk(type==='slope'?'select':'input');v.setAttribute('aria-label',label);if(type==='slope'){[12,24].forEach(n=>{const o=mk('option','',`${n} dB/oct`);o.value=String(n);v.append(o);});}else{v.type='number';v.min=String(min);v.max=String(max);v.step=String(step);}wrap.append(v);return {wrap,v};}; + const freq=field('FREQUENCY · Hz','frequency',20,20000,1),gain=field('GAIN · dB','gain',-18,18,.1),q=field('Q · WIDTH','q',.2,12,.01),slope=field('CUT SLOPE','slope'); + const resetCol=mk('div','mx-eq-vertical');const typeName=mk('div','mx-eq-channel','BAND');resetCol.append(typeName); + controls.append(powerCol,freq.wrap,gain.wrap,q.wrap,slope.wrap,resetCol); + const footer=mk('footer','mx-eq-footer'),status=mk('span','mx-eq-status'),footerNote=mk('span','mx-eq-footnote','IIR · NO LOOKAHEAD · NO FFT');footer.append(status,footerNote); + workspace.append(graph,rail,controls,footer);root.append(head,workspace); + const attach=()=>{if(!root.isConnected)document.body.append(root);}; + if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',attach,{once:true});else attach(); + // Real modeless title-bar dragging, isolated from frequency-node gestures. + let windowGesture=null; + const stopDrag=e=>{ + if(!windowGesture||windowGesture.id!==e.pointerId)return; + windowGesture=null;head.releasePointerCapture?.(e.pointerId); + }; + head.addEventListener('pointerdown',e=>{ + if(e.button!==0||e.target.closest?.('button'))return; + const r=root.getBoundingClientRect(); + windowGesture={id:e.pointerId,offsetX:e.clientX-r.left,offsetY:e.clientY-r.top}; + head.setPointerCapture?.(e.pointerId);e.preventDefault(); + }); + head.addEventListener('pointermove',e=>{ + if(!windowGesture||e.pointerId!==windowGesture.id)return; + const r=root.getBoundingClientRect(); + root.style.left=clamp(e.clientX-windowGesture.offsetX,0,Math.max(0,(window.innerWidth||1024)-r.width))+'px'; + root.style.top=clamp(e.clientY-windowGesture.offsetY,0,Math.max(0,(window.innerHeight||768)-r.height))+'px'; + root.style.transform='none';e.preventDefault(); + }); + head.addEventListener('pointerup',stopDrag); + head.addEventListener('pointercancel',stopDrag); + const ctx=canvas.getContext('2d',{alpha:false}); + let current=null,channelId=null,epoch=null,revision=null,bands=empty(),slot=2,sampleRate=48000; + let pending=null,waitingAck=false,snapshotReady=false,reqSeq=1,activeGesture=null, + demonstration=!Boolean(window.__JUCE__?.backend); // native readback works even before editor opened + const nativeBackend=()=>window.__JUCE__?.backend; + const nativeRoute=()=>window.__ARMIX_BUILTIN_EQ_CHANNEL__; + const demoStates=new Map(),nativeStates=new Map(); + let lastGraphEqSweep=''; + const sameGraph=(v,n)=>v&&n&&v.epoch===n.device?.epoch&&v.revision===n.graph?.revision; + const stateFor=t=>{ + if(!t||t.kind==='master')return null; + if(!nativeBackend())return demoStates.get(t.id)||null; + const id=nativeRoute()?.resolve?.(t.id),n=nativeRoute()?.state?.(); + const accepted=nativeStates.get(id);return sameGraph(accepted,n)?accepted:null; + }; + const refresh=t=>window.__ARMIX_BUILTIN_EQ_REFRESH__?.(t?.id); + const notify=message=>window.__ARMIX_BUILTIN_EQ_NOTIFY__?.(message); + const safeName=t=>String(t?.name||'Channel').replace(/[&<>"']/g,c=>({ + '&':'&','<':'<','>':'>','"':'"',"'":''' + })[c]); + const nextRequestId=()=> (BigInt(Date.now())*10000n+BigInt(reqSeq++%10000)).toString(); + const setStatus=(message,kind='')=>{status.textContent=message;status.className='mx-eq-status '+kind;}; + const isOpen=()=>!root.hidden; + const isEditable=()=>demonstration||Boolean(channelId&&snapshotReady&&!pending&& + current&&stateFor(current)?.installed); + const resetNative=()=>{channelId=null;epoch=null;revision=null;pending=null;waitingAck=false;snapshotReady=false;bands=empty();setStatus('NATIVE: WAITING FOR ACCEPTED CHANNEL', 'warn');render();}; + const updateInputs=()=>{ + const b=bands[slot]; + buttons.forEach((node,i)=>{node.classList.toggle('selected',slot===i);node.classList.toggle('on',bands[i].enabled);node.setAttribute('aria-pressed',String(bands[i].enabled));}); + power.setAttribute('aria-pressed',String(b.enabled));power.textContent=b.enabled?'BAND ON':'BAND OFF'; + freq.v.value=String(Math.round(b.frequencyHz));gain.v.value=b.gainDb.toFixed(1);q.v.value=b.q.toFixed(2);slope.v.value=String(b.slope); + typeName.textContent=LABELS[slot];gain.v.disabled=isCut(slot)||!isEditable();q.v.disabled=isCut(slot)||slot===1||slot===6||!isEditable(); + slope.v.disabled=!isCut(slot)||!isEditable();freq.v.disabled=!isEditable();power.disabled=!isEditable();flat.disabled=!isEditable(); + buttons.forEach(x=>{x.disabled=false;}); + }; + const num=(x,d)=>Number.isFinite(Number(x))?Number(x):d; + const validBand=(i,b)=>Boolean(b)&&typeof b.enabled==='boolean'&&Number.isFinite(b.frequencyHz)&&b.frequencyHz>=20&&b.frequencyHz<=(b.enabled?maxHz():20000)&&Number.isFinite(b.gainDb)&&Math.abs(b.gainDb)<=18&&Number.isFinite(b.q)&&b.q>=.2&&b.q<=12&&(b.slope===12||b.slope===24); + const coeff=(type,b,sr,q)=>{ + const w=2*Math.PI*b.frequencyHz/sr,c=Math.cos(w),sin=Math.sin(w),a=Math.pow(10,b.gainDb/40),al=sin/(2*q),edge=sin*Math.sqrt(a)*Math.SQRT2; + let v; + if(type==='bell')v=[1+al*a,-2*c,1-al*a,1+al/a,-2*c,1-al/a]; + else if(type==='hp')v=[(1+c)/2,-(1+c),(1+c)/2,1+al,-2*c,1-al]; + else if(type==='lp')v=[(1-c)/2,1-c,(1-c)/2,1+al,-2*c,1-al]; + else if(type==='ls')v=[a*((a+1)-(a-1)*c+edge),2*a*((a-1)-(a+1)*c),a*((a+1)-(a-1)*c-edge),(a+1)+(a-1)*c+edge,-2*((a-1)+(a+1)*c),(a+1)+(a-1)*c-edge]; + else v=[a*((a+1)+(a-1)*c+edge),-2*a*((a-1)+(a+1)*c),a*((a+1)+(a-1)*c-edge),(a+1)-(a-1)*c+edge,2*((a-1)-(a+1)*c),(a+1)-(a-1)*c-edge]; + const a0=v[3];return [v[0]/a0,v[1]/a0,v[2]/a0,1,v[4]/a0,v[5]/a0]; + }; + // Coefficients depend on settings and sample rate, NOT on graph X pixels. + // Build once per animation frame; no 8x redundant trig/pow coefficient work. + const compiledSections=src=>{ + const sections=[]; + for(let i=0;i{ + if(!sections.length)return 0; + const w=2*Math.PI*hz/sampleRate,cos=Math.cos(w),sin=Math.sin(w); + const cos2=Math.cos(2*w),sin2=Math.sin(2*w); + let result=0; + for(const c of sections){ + const nr=c[0]+c[1]*cos+c[2]*cos2,ni=-(c[1]*sin+c[2]*sin2); + const dr=1+c[4]*cos+c[5]*cos2,di=-(c[4]*sin+c[5]*sin2); + result+=10*Math.log10(Math.max(1e-24,(nr*nr+ni*ni)/Math.max(1e-24,dr*dr+di*di))); + }return result; + }; + const draw=()=>{ + if(root.hidden||!ctx)return; + const r=canvas.getBoundingClientRect();if(r.width<100||r.height<80)return; + const dpr=Math.min(window.devicePixelRatio||1,2),w=r.width,h=r.height; + canvas.width=Math.round(w*dpr);canvas.height=Math.round(h*dpr);ctx.setTransform(dpr,0,0,dpr,0,0); + ctx.fillStyle='#15212a';ctx.fillRect(0,0,w,h);const y0=dbToY(0,h); + ctx.font='9px Consolas,monospace';ctx.textBaseline='top'; + for(const f of [20,50,100,200,500,1000,2000,5000,10000,20000]){ + const x=hzToX(f,w);ctx.strokeStyle=f===1000?'#334c57':'#273a45';ctx.lineWidth=.75;ctx.beginPath();ctx.moveTo(x,17);ctx.lineTo(x,h-20);ctx.stroke();ctx.fillStyle='#78919f';ctx.fillText(f>=1000?`${f/1000}k`:String(f),x-8,h-15); + } + for(const db of [-18,-12,-6,0,6,12,18]){ + const y=dbToY(db,h);ctx.strokeStyle=db===0?'#587581':'#2b3b45';ctx.lineWidth=db===0?1.2:.7;ctx.beginPath();ctx.moveTo(23,y);ctx.lineTo(w-28,y);ctx.stroke();ctx.fillStyle='#8ca5b3';ctx.fillText(db>0?'+'+db:String(db),3,y-5); + } + const displayBands=activeGesture?.draft ? + bands.map((band,i)=>i===activeGesture.slot?activeGesture.draft:band):bands; + const sections=compiledSections(displayBands); + const steps=Math.max(80,Math.floor(w-58)),points=[]; + for(let i=0;i<=steps;i++){const f=xToHz(28+(w-58)*i/steps,w);points.push([hzToX(f,w),dbToY(responseDb(f,sections),h)]);} + ctx.beginPath();points.forEach(([x,y],i)=>i?ctx.lineTo(x,y):ctx.moveTo(x,y));ctx.lineTo(w-28,y0);ctx.lineTo(28,y0);ctx.closePath();ctx.fillStyle='rgba(79,174,207,.09)';ctx.fill(); + ctx.beginPath();points.forEach(([x,y],i)=>i?ctx.lineTo(x,y):ctx.moveTo(x,y));ctx.strokeStyle=activeGesture?.draft?'#9ae9f3':'#67d3e5'; + ctx.lineWidth=2;ctx.setLineDash(activeGesture?.draft?[5,3]:[]);ctx.stroke();ctx.setLineDash([]); + for(let i=0;i{updateInputs();if(frame)cancelAnimationFrame(frame);frame=requestAnimationFrame(()=>{frame=0;draw();});}; + const apply=(candidate)=>{ + if(!isEditable()||!validBand(slot,candidate))return; + if(demonstration){ + bands[slot]={...candidate}; + if(current)demoStates.set(current.id,{ + ...(demoStates.get(current.id)||{installed:false,bypassed:false}), + bands:bands.map(b=>({...b}))}); + setStatus('DESIGN DEMO · VISUAL ONLY · NO AUDIO','warn');render();return; + } + if(!nativeBackend()?.emitEvent||!channelId||!epoch||!revision)return; + const id=nextRequestId(),command={action:'builtinEqSetBand',channelId,deviceEpoch:epoch,graphRevision:revision,requestId:id,slot,band:candidate}; + pending={id,channelId,epoch,revision,slot};waitingAck=false; + setStatus('NATIVE: REQUEST SENT · WAITING FOR AUDIO CALLBACK','warn');render();nativeBackend().emitEvent('arMixAction',command); + }; + const selected=()=>bands[slot]; + const update=(patch)=>apply({...selected(),...patch}); + power.addEventListener('click',()=>update({enabled:!selected().enabled,frequencyHz:Math.min(selected().frequencyHz,maxHz())})); + flat.addEventListener('click',()=>update({...empty()[slot]})); + freq.v.addEventListener('change',()=>update({frequencyHz:clamp(num(freq.v.value,selected().frequencyHz),20,maxHz())})); + gain.v.addEventListener('change',()=>update({gainDb:clamp(num(gain.v.value,selected().gainDb),-18,18)})); + q.v.addEventListener('change',()=>update({q:clamp(num(q.v.value,selected().q),.2,12)})); + slope.v.addEventListener('change',()=>update({slope:num(slope.v.value,12)===24?24:12})); + rail.addEventListener('click',e=>{const btn=e.target.closest('[data-slot]');if(!btn)return;slot=Number(btn.dataset.slot);render();}); + const locate=e=>{const r=canvas.getBoundingClientRect();return {x:e.clientX-r.left,y:e.clientY-r.top,w:r.width,h:r.height};}; + const pick=(p)=>{let index=-1,d=17*17;bands.forEach((b,i)=>{const x=hzToX(b.frequencyHz,p.w),y=dbToY(isCut(i)?0:b.gainDb,p.h),dist=(x-p.x)**2+(y-p.y)**2;if(dist{ + if(e.button!==0||!isEditable())return; + const p=locate(e),i=pick(p);if(i<0)return; + slot=i;activeGesture={id:e.pointerId,slot:i,draft:null}; + canvas.setPointerCapture?.(e.pointerId);render(); + }); + canvas.addEventListener('pointermove',e=>{ + const g=activeGesture;if(!g||g.id!==e.pointerId||!isEditable())return; + const p=locate(e),selectedBand=bands[g.slot]; + g.draft={...selectedBand,enabled:true, + frequencyHz:clamp(Math.round(xToHz(p.x,p.w)),20,maxHz()), + gainDb:isCut(g.slot)?0:Math.round(yToDb(p.y,p.h)*10)/10}; + setStatus('DRAG PREVIEW · RELEASE TO REQUEST AUDIO CHANGE','warn'); + render(); // dashed preview only; the accepted band stays unchanged + }); + canvas.addEventListener('pointerup',e=>{ + const g=activeGesture;if(!g||g.id!==e.pointerId)return; + activeGesture=null;slot=g.slot; + const p=locate(e),old=bands[g.slot]; + const candidate=g.draft||{...old,enabled:true, + frequencyHz:clamp(Math.round(xToHz(p.x,p.w)),20,maxHz()), + gainDb:isCut(g.slot)?0:Math.round(yToDb(p.y,p.h)*10)/10}; + if(isEditable())apply(candidate); + else render(); + }); + canvas.addEventListener('pointercancel',()=>{activeGesture=null;render();}); + canvas.addEventListener('wheel',e=>{const p=locate(e),i=pick(p);if(i<0||!isEditable())return;e.preventDefault();slot=i;const b=bands[i];if(isCut(i))update({slope:b.slope===12?24:12,enabled:true});else update({q:clamp(Math.round((b.q+(e.deltaY<0?.08:-.08))*100)/100,.2,12),enabled:true});},{passive:false}); + close.addEventListener('click',()=>{root.hidden=true;activeGesture=null;}); + root.addEventListener('keydown',e=>{if(e.key==='Escape'){e.stopPropagation();root.hidden=true;}}); + if(typeof ResizeObserver!=='undefined'){new ResizeObserver(()=>{if(isOpen())render();}).observe(graph);}else window.addEventListener('resize',()=>{if(isOpen())render();},{passive:true}); + const validateSnap=s=>s?.schemaVersion===1&&s.channelId===channelId&& + s.deviceEpoch===epoch&&s.graphRevision===revision&& + typeof s.installed==='boolean'&&typeof s.bypassed==='boolean'&& + /^\d+$/.test(String(s.deviceEpoch||''))&&/^\d+$/.test(String(s.graphRevision||''))&& + Array.isArray(s.bands)&&s.bands.length===8&&s.bands.every((b,i)=>validBand(i,b)); + const backend=nativeBackend(); + if(backend?.addEventListener){ + // A historical EQ snapshot must never stay editable after hotplug, + // device restart, graph replacement or channel removal. + backend.addEventListener('arMixConsoleSnapshot',s=>{ + // The approved native graph projection may install strips after this + // listener in the same browser turn. Request each actual ChannelId once + // per admitted epoch/revision, after its projection has settled. + const requery=()=>{ + const n=nativeRoute()?.state?.(); + if(!n?.admitted||!s?.admitted|| + s.device?.epoch!==n.device?.epoch|| + s.graph?.revision!==n.graph?.revision|| + !Array.isArray(n.graph?.channels))return; + const key=String(n.device.epoch)+'/'+String(n.graph.revision); + if(key===lastGraphEqSweep)return; + lastGraphEqSweep=key; + for(const ch of n.graph.channels) { + const t=window.__ARMIX_BUILTIN_EQ_FIND_CHANNEL__?.(ch.id); + if(t&&t.kind!=='master') + backend.emitEvent('arMixAction',{action:'builtinEqSnapshot', + channelId:ch.id}); + } + }; + if(typeof window.setTimeout==='function')window.setTimeout(requery,0); + else requery(); + if(!isOpen()||demonstration||!channelId)return; + const accepted=s?.admitted===true&&s.device?.epoch===epoch&& + s.graph?.revision===revision&&Array.isArray(s.graph.channels)&& + s.graph.channels.some(ch=>ch.id===channelId); + if(!accepted){mode.textContent='NATIVE · ROUTE CHANGED';resetNative();} + }); + backend.addEventListener('arMixBuiltinEqQueue',r=>{if(!pending||r?.requestId!==pending.id||r.channelId!==channelId)return;if(r.status==='REJECTED'){const t=current;pending=null;setStatus('NATIVE: EQ REJECTED; STATE UNCHANGED','warn');notify('Parametric EQ insert/edit rejected by native engine');refresh(t);render();}else setStatus('QUEUED · WAITING FOR DSP APPLY ACK','warn');}); + backend.addEventListener('arMixBuiltinEqAck',r=>{if(!pending||r?.requestId!==pending.id||r.channelId!==channelId)return;if(r.status==='APPLIED'&&r.deviceEpoch===pending.epoch&&r.graphRevision===pending.revision){waitingAck=true;setStatus('DSP APPLIED · AWAITING ACCEPTED READBACK','warn');}else {const t=current;pending=null;waitingAck=false;setStatus('NATIVE: NOT APPLIED; STATE UNCHANGED','warn');notify('Parametric EQ change not applied');refresh(t);render();}}); + backend.addEventListener('arMixBuiltinEqSnapshot',s=>{ + const n=nativeRoute()?.state?.(); + const validIdentity=s?.schemaVersion===1&& + typeof s.channelId==='string'&&typeof s.installed==='boolean'&& + typeof s.bypassed==='boolean'&&s.deviceEpoch===n?.device?.epoch&& + s.graphRevision===n?.graph?.revision; + const otherTrack=validIdentity? + window.__ARMIX_BUILTIN_EQ_FIND_CHANNEL__?.(s.channelId):null; + const hasUnconfirmedCurrent=pending&&pending.channelId===s?.channelId&& + (!waitingAck||s.appliedRequestId!==pending.id); + if(otherTrack&&!hasUnconfirmedCurrent) { + const prior=nativeStates.get(s.channelId); + nativeStates.set(s.channelId,{installed:s.installed,bypassed:s.bypassed, + epoch:s.deviceEpoch,revision:s.graphRevision}); + if(!prior||prior.installed!==s.installed||prior.bypassed!==s.bypassed|| + prior.revision!==s.graphRevision||prior.epoch!==s.deviceEpoch) + refresh(otherTrack); + } + if(demonstration||!validateSnap(s))return; + if(pending&&(!waitingAck||s.appliedRequestId!==pending.id))return; + bands=s.bands.map(b=>({...b}));epoch=s.deviceEpoch;revision=s.graphRevision; + sampleRate=Number(s.sampleRate)||48000;pending=null;waitingAck=false;snapshotReady=true; + nativeStates.set(channelId,{installed:s.installed,bypassed:s.bypassed, + epoch:s.deviceEpoch,revision:s.graphRevision}); + setStatus(s.installed?'NATIVE · DSP ACCEPTED · LIVE PCM': + 'NATIVE · NOT INSERTED · CHOOSE FROM FX LIST',s.installed?'good':'warn'); + refresh(current);render(); + }); + } + const setGate=(track,installed,bypassed)=>{ + if(!track||track.kind==='master'||pending)return false; + if(!nativeBackend()){ + const previous=demoStates.get(track.id)||{bands:empty()}; + demoStates.set(track.id,{...previous,installed,bypassed:installed&&bypassed, + bands:installed?previous.bands:empty()}); + if(current?.id===track.id)bands=demoStates.get(track.id).bands.map(b=>({...b})); + setStatus('DESIGN DEMO · NO AUDIO SIGNAL','warn');refresh(track);render();return true; + } + demonstration=false; + const id=nativeRoute()?.resolve?.(track.id),n=nativeRoute()?.state?.(); + if(!id||!n?.admitted||!n?.device?.epoch||!n?.graph?.revision)return false; + if(current?.id!==track.id&&isOpen())root.hidden=true; + current=track;channelId=id;epoch=n.device.epoch;revision=n.graph.revision; + snapshotReady=false; + const requestId=nextRequestId(); + pending={id:requestId,channelId:id,epoch,revision,slot:-1,kind:'gate',trackId:track.id,installRequested:installed}; + waitingAck=false; + setStatus('NATIVE · GATE QUEUED · WAITING FOR AUDIO ACK','warn'); + nativeBackend().emitEvent('arMixAction',{action:'builtinEqSetGate',channelId:id, + deviceEpoch:epoch,graphRevision:revision,requestId,installed,bypassed}); + refresh(track);render();return true; + }; + window.ArSonMixBuiltinEq=Object.freeze({ + installed(track){return Boolean(stateFor(track)?.installed||(pending?.kind==='gate'&&pending.installRequested&&pending.trackId===track?.id));}, + slotMarkup(track,materialIcon){ + const st=stateFor(track); + const installing=!st?.installed&&pending?.kind==='gate'&&pending.installRequested&&pending.trackId===track?.id; + if(!st?.installed&&!installing)return ''; + if(installing)return '
Parametric EQ · APPLYING…
'; + const enabled=track.fxOn!==false&&!st.bypassed; + const power=materialIcon?.('power_settings_new')||'⏻'; + const remove=materialIcon?.('delete_forever')||'×'; + const label=safeName(track); + return '
'+ + ''+ + ''+ + '
'; + }, + insert(track){ + if(!track||track.kind==='master'||this.installed(track))return false; + // Selecting in the picker ONLY inserts. Clicking the accepted rack row + // is the sole editor-opening action (DAW-style modeless FX workflow). + const accepted=setGate(track,true,false); + if(!accepted)notify('Parametric EQ insert rejected · channel unchanged'); + return accepted; + }, + power(track){const st=stateFor(track);if(st?.installed)setGate(track,true,!st.bypassed);}, + remove(track){const st=stateFor(track);if(st?.installed)setGate(track,false,false);}, + open(track){ + if(!track||track.kind==='master')return; + current=track;channelLabel.textContent=String(track.name||'Channel');root.hidden=false;slot=2;pending=null;waitingAck=false; + const host=nativeRoute(),resolved=host?.resolve?.(track.id),s=host?.state?.(); + demonstration=!nativeBackend(); + if(demonstration){channelId=null;snapshotReady=false; + bands=demoStates.get(track.id)?.bands?.map(b=>({...b}))||empty(); + sampleRate=48000;mode.textContent='UI DEMO · NO AUDIO'; + setStatus('DESIGN DEMO · NO AUDIO SIGNAL','warn');} + else if(resolved&&s?.admitted){channelId=resolved;epoch=s.device?.epoch;revision=s.graph?.revision;bands=empty();pending=null;snapshotReady=false; + // Control disabled until real native snapshot arrives; never pretend + // that a screenshot/browser fixture is already loaded as channel state. + mode.textContent='NATIVE · CHANNEL ID '+channelId;setStatus('NATIVE · LOADING ACCEPTED PARAMETERS','warn');nativeBackend()?.emitEvent('arMixAction',{action:'builtinEqSnapshot',channelId}); + }else{mode.textContent='NATIVE · UNAVAILABLE';resetNative();} + render();root.querySelector('.mx-eq-close')?.focus(); + },close(){root.hidden=true;}}); +})(); diff --git a/site/preview-v2/assets/mixer-fx-rack.css b/site/preview-v2/assets/mixer-fx-rack.css index afc444a1a..c2cb4cd5f 100644 --- a/site/preview-v2/assets/mixer-fx-rack.css +++ b/site/preview-v2/assets/mixer-fx-rack.css @@ -166,3 +166,45 @@ color:#849ca7!important; } .console-body .strip .fx-section.is-chain-bypassed>.subhead [data-util-kind="fx-main"]{opacity:.65} + +/* Native built-in Channel EQ is an FX component, NOT an extra stylesheet owner. + All selectors are new and scoped; historical material and VST rack geometry + remain unchanged. The Stage B CSS non-stacking gate must remain enabled. */ +/* ArSonMix: one optional BUILT-IN CHANNEL EQ overlay, never a second mixer. + * Material palette is scoped and derived from the approved /preview/ hardware + * chassis and FX glass. All sizes are compact, no blur/spectrum GPU loop. */ +#mxBuiltinEq[hidden]{display:none!important} +#mxBuiltinEq{--eq-cyan:#60c8df;--eq-ink:#d9e7ed;--eq-mute:#93a5af;position:fixed;z-index:120;left:50%;top:50%;transform:translate(-50%,-50%);width:min(770px,calc(100vw - 18px));height:min(465px,calc(100dvh - 18px));min-width:0;min-height:325px;display:flex;flex-direction:column;overflow:hidden;box-sizing:border-box;border:1px solid #566a78;border-radius:6px;background:#18232c;color:var(--eq-ink);box-shadow:0 14px 40px #000c,0 0 0 1px #0a151a,inset 0 1px #73838e;font:11px/1.25 "Segoe UI",Arial,sans-serif} +#mxBuiltinEq button,#mxBuiltinEq input,#mxBuiltinEq select{font:inherit}#mxBuiltinEq button{cursor:pointer}#mxBuiltinEq button:disabled,#mxBuiltinEq input:disabled,#mxBuiltinEq select:disabled{opacity:.55;cursor:default} +#mxBuiltinEq button:focus-visible,#mxBuiltinEq input:focus-visible,#mxBuiltinEq select:focus-visible{outline:2px solid #85d1e6;outline-offset:1px} +.mx-eq-top{cursor:move;touch-action:none;user-select:none;height:30px;flex:0 0 30px;display:flex;align-items:center;gap:10px;padding:0 10px;background:linear-gradient(#575d62,#393f46 54%,#292f35 54%,#333c44);border-bottom:1px solid #101820;box-shadow:inset 0 1px #92999d} +.mx-eq-top .mx-eq-mark{width:4px;height:14px;background:#5fc6da}.mx-eq-top strong{font-size:12px;font-weight:600;letter-spacing:.3px;color:#eff4f6}.mx-eq-top .mx-eq-channel{color:#b9c9d0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10px} +.mx-eq-top .mx-eq-spacer{flex:1}.mx-eq-top .mx-eq-mode{font:9px/1 Consolas,monospace;color:#aad3df;white-space:nowrap}.mx-eq-close{border:1px solid #1a3039;border-radius:2px;background:linear-gradient(#64737e,#394c58);color:#f3f8fa;height:22px;width:25px;font:16px/19px Arial!important;padding:0} +.mx-eq-workspace{flex:1;min-height:0;display:flex;flex-direction:column;background:#101a22} +.mx-eq-chart{position:relative;flex:1;min-height:116px;box-sizing:border-box;background:radial-gradient(ellipse at 45% 20%,#21333c 0%,#17242e 50%,#101c25 100%);overflow:hidden;border-bottom:1px solid #445560} +.mx-eq-chart canvas{display:block;width:100%;height:100%;touch-action:none;cursor:crosshair} +.mx-eq-hint{pointer-events:none;position:absolute;left:10px;top:8px;font:9px/1.1 Consolas,monospace;color:#8da6b4}.mx-eq-legend{pointer-events:none;position:absolute;right:11px;top:8px;font:9px/1.2 Consolas,monospace;color:#95b8c4} +.mx-eq-rail{flex:0 0 31px;display:grid;grid-template-columns:repeat(8,minmax(0,1fr));gap:3px;padding:4px 8px;background:linear-gradient(#222e38,#18232c);border-bottom:1px solid #46505a} +.mx-eq-band{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:flex;align-items:center;justify-content:center;gap:5px;border:1px solid #3c515e;border-radius:2px;color:#94a8b6;background:#202c36;font:9px/1 "Segoe UI",Arial,sans-serif!important} +.mx-eq-band i{display:inline-block;height:6px;width:6px;flex:0 0 6px;border-radius:50%;background:var(--eq-band,#69c9dd);opacity:.35} +.mx-eq-band.on{color:#e2f3f7;background:#293f4e;border-color:#527c8c}.mx-eq-band.on i{opacity:1}.mx-eq-band.selected{outline:1px solid #a0d8e5;outline-offset:-2px;color:#f4feff} +.mx-eq-controls{flex:0 0 83px;min-height:83px;display:grid;grid-template-columns:88px repeat(4,minmax(0,1fr)) 66px;gap:10px;align-items:center;padding:7px 12px;background:linear-gradient(165deg,#394954,#273943 45%,#1d2d37);box-shadow:inset 0 1px #657a85} +.mx-eq-controls label{min-width:0;display:block;color:#9db7c2;font:9px/1.3 "Segoe UI",Arial,sans-serif;letter-spacing:.55px}.mx-eq-controls input,.mx-eq-controls select{box-sizing:border-box;margin-top:5px;min-width:0;width:100%;height:29px;padding:0 6px;border:1px solid #536674;border-radius:3px;background:linear-gradient(#0f1c26,#243542);box-shadow:inset 0 1px 3px #0008;color:#eaf3f7;font:12px/1 Consolas,monospace!important;text-align:center} +.mx-eq-controls input::-webkit-inner-spin-button{-webkit-appearance:none}.mx-eq-controls .mx-eq-switch,.mx-eq-controls .mx-eq-reset{width:100%;height:29px;border:1px solid #5b7480;border-radius:3px;color:#b4c7d0;background:linear-gradient(#3d5561,#263d48);font:10px/1 "Segoe UI",Arial,sans-serif!important} +.mx-eq-controls .mx-eq-switch[aria-pressed="true"]{background:linear-gradient(#275b59,#19413c);border-color:#4d947d;color:#adf5ce}.mx-eq-controls .mx-eq-reset{margin-top:4px;height:24px;font-size:9px!important} +.mx-eq-controls .mx-eq-vertical{display:flex;flex-direction:column;justify-content:center;align-items:stretch;gap:2px} +.mx-eq-footer{flex:0 0 24px;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:0 10px;background:linear-gradient(#303f49,#1e2c37);border-top:1px solid #586572;color:#9bb2bf;font:9px/1 Consolas,monospace;white-space:nowrap} +.mx-eq-footer .mx-eq-status{min-width:0;overflow:hidden;text-overflow:ellipsis}.mx-eq-footer .mx-eq-status.good{color:#8de0bb}.mx-eq-footer .mx-eq-status.warn{color:#f2c28a}.mx-eq-footer .mx-eq-footnote{color:#829ba8} +@media(max-width:760px){html #mxBuiltinEq{width:calc(100vw - 12px);height:min(440px,calc(100dvh - 12px))}html .mx-eq-controls{gap:5px;padding:6px;grid-template-columns:66px repeat(4,minmax(0,1fr)) 51px}html .mx-eq-rail{padding:3px;gap:2px}html .mx-eq-band{gap:2px;font-size:8px!important}html .mx-eq-controls input,html .mx-eq-controls select{font-size:10px!important;padding:0 2px}html .mx-eq-controls label{font-size:8px}html .mx-eq-footer .mx-eq-footnote{display:none}} +@media(max-height:440px){html .mx-eq-top{height:25px;flex-basis:25px}html .mx-eq-controls{flex-basis:68px;min-height:68px}html .mx-eq-rail{flex-basis:27px}html .mx-eq-footer{flex-basis:20px}} +@media(prefers-reduced-motion:reduce){html #mxBuiltinEq *{transition:none!important;animation:none!important}} + + +/* Built-in native PRE insert: follow the existing FX rack visual owner. */ +.fast-fx-category{padding:6px 10px 3px;color:#8bbbc8;font:9px/1.2 "Segoe UI",Arial,sans-serif;letter-spacing:.8px;border-top:1px solid #334651} +.fast-fx-category:first-child{border-top:0} +.fxslot-row.is-builtin{border-left:2px solid #6ac4d2;background:linear-gradient(90deg,#28424b40,#25353c18)} +.fxslot-row.is-builtin .fx-pick{color:#c3ecf1} +.fxslot-row.is-builtin .fx-pick small{font:8px/1 Consolas,monospace;letter-spacing:.25px;color:#86a7b4;margin-left:5px} +.fxslot-row.is-builtin.is-bypassed .fx-pick{color:#8b9aa3} +.fxslot-row.is-builtin.is-pending .fx-pick{color:#b7a67f;cursor:progress;font-size:10px} diff --git a/src/ApprovedNativeV8Projection.h b/src/ApprovedNativeV8Projection.h index ab95387fd..b5f4b4cc5 100644 --- a/src/ApprovedNativeV8Projection.h +++ b/src/ApprovedNativeV8Projection.h @@ -82,6 +82,11 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus) { fx.add(juce::var(insert.release())); } ch->setProperty("inserts",juce::var(fx)); + const auto rackBypassed=row.getProperty("fxRackBypassed",{}); + if(!rackBypassed.isVoid()) { + if(!rackBypassed.isBool())return false; + ch->setProperty("fxRackBypassed",rackBypassed); + } ch->setProperty("sends",juce::var(juce::Array{})); if(role!="INPUT"){ auto dst=std::make_unique(); diff --git a/src/ConsoleLiveBridgeV6.h b/src/ConsoleLiveBridgeV6.h index a30991611..8db86ac42 100644 --- a/src/ConsoleLiveBridgeV6.h +++ b/src/ConsoleLiveBridgeV6.h @@ -150,6 +150,8 @@ class LiveConsoleBridgeV6 final { if(peaksL.isArray())object->setProperty("channelPeaksL",peaksL); if(peaksR.isArray())object->setProperty("channelPeaksR",peaksR); if(inserts.isArray())object->setProperty("fxInstances",inserts); + const auto rackPower=route.getProperty("fxRackBypassed",juce::var()); + if(rackPower.isArray())object->setProperty("fxRackBypassed",rackPower); // The prepared/unpatched native M4 graph is a real silent route. // It allows direct IN gesture to activate the FIRST source. // This does not set productionCallbackLive or fake PCM. diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 20bc4039e..752e8ab4b 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -91,6 +91,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } std::array slots {}; std::array, maxFx> bypassFlags {}; + std::atomic rackBypassed{false}; // does not overwrite per-slot flags // Owned and advanced exclusively by the realtime render callback. // Physical-slot identity survives an atomic logical reorder (PR #102). std::array bypassEnvelope {}; @@ -1059,7 +1060,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String applyDryRoutingLab ( const juce::var& command, const LiveDryRoutingLab::FxSelections& fx, - const LiveDryRoutingLab::FxRestores* restored=nullptr) { + const LiveDryRoutingLab::FxRestores* restored=nullptr, + const LiveDryRoutingLab::EqRestores* restoredEq=nullptr) { if (dryRoutingLab_.nativeBusTopologyLive()) return "REMOVE native GROUP/FX RETURN buses before applying an M4 route"; if (!allOutputsDisarmed()) return "MUTE hardware output and DISARM STREAM before APPLY routing"; @@ -1084,7 +1086,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const auto result=dryRoutingLab_.apply( command,directFence_.permitted(),independent_.active(), graphOwned_->count,fx,formats_,device->getCurrentSampleRate(), - frames,true,restored); + frames,true,restored,restoredEq); // Same original PCM callback/hardware gate; a failed ChannelId // admission retains the last accepted M4 with original Orbit/Show. if(result.isEmpty()) @@ -1229,6 +1231,16 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback !=armix::diagnostics::Route::normal)return false; return dryRoutingLab_.setFxBypass(lane,slot,epoch,revision,instanceId,bypass); } + bool setDryRoutingLabFxRackBypass(int lane,std::uint64_t epoch, + std::uint64_t revision,bool bypass) noexcept { + if(routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + if(!dryRoutingLab_.setFxRackBypass(lane,epoch,revision,bypass))return false; + if(lane==0 && graphOwned_) + graphOwned_->rackBypassed.store(bypass,std::memory_order_release); + return true; + } armix::mixer::LiveChannelFxGraph::InstanceLease leaseRoutedFxForEditor( int lane,int slot,std::uint64_t epoch,std::uint64_t revision, const juce::String& instanceId) const noexcept { @@ -1333,6 +1345,18 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return dryRoutingLab_.bypassNativeInsert(epoch,revision,id,slot, token,bypass); } + bool bypassNativeFxRack(std::uint64_t epoch,std::uint64_t revision, + armix::mixer::ChannelId id,bool bypass) noexcept { + if(routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + if(!dryRoutingLab_.bypassNativeRack(epoch,revision,id,bypass))return false; + // The original CH1 VST3 instance can be external-leased into the + // native ChannelId publisher. Its own crossfade gate must agree. + if(graphOwned_ && dryRoutingLab_.nativeChannelIsOriginalCh1(id)) + graphOwned_->rackBypassed.store(bypass,std::memory_order_release); + return true; + } armix::mixer::LiveChannelFxGraph::InstanceLease leaseNativeVst3Editor( std::uint64_t epoch,std::uint64_t revision, armix::mixer::ChannelId id,std::size_t slot, @@ -1433,6 +1457,39 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback armix::diagnostics::Route::normal)return false; return dryRoutingLab_.setNativeBusMix(epoch,revision,id,gain,pan); } + using BuiltInEqAck=LiveDryRoutingLab::BuiltInEqAck; + bool builtInEqIdentity(armix::mixer::ChannelId id,int& lane, + std::uint64_t& ep,std::uint64_t& rev) const noexcept { + if(independent_.active()||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.builtInEqIdentity(id,lane,ep,rev); + } + bool queueBuiltInEqEdit(int lane,std::size_t slot, + const armix::builtin_fx::Band& b, + std::uint64_t requestId,std::uint64_t ep, + std::uint64_t rev) noexcept { + if(independent_.active()||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.queueBuiltInEqEdit(lane,slot,b,requestId,ep,rev); + } + bool queueBuiltInEqGate(int lane,bool installed,bool bypassed, + std::uint64_t requestId,std::uint64_t ep, + std::uint64_t rev) noexcept { + if(independent_.active()||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.queueBuiltInEqGate(lane,installed,bypassed, + requestId,ep,rev); + } + bool pollBuiltInEqAck(int lane,std::uint64_t ep, + std::uint64_t rev,BuiltInEqAck& ack) noexcept { + return dryRoutingLab_.pollBuiltInEqAck(lane,ep,rev,ack); + } bool dryRoutingLabActive() const noexcept {return dryRoutingLab_.active();} void pollDryRoutingLab() noexcept {dryRoutingLab_.poll();} @@ -1935,7 +1992,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback auto& slot=graph.slots[physical]; if(!slot.processor)continue; auto& bypass=graph.bypassEnvelope[physical]; - bypass.request(graph.bypassFlags[physical].load(std::memory_order_acquire)); + bypass.request(graph.rackBypassed.load(std::memory_order_acquire) || + graph.bypassFlags[physical].load(std::memory_order_acquire)); const bool blend=bypass.transitioning(); if(blend) { diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 82f5ea88b..5586249a5 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -57,6 +57,11 @@ class LiveDryRoutingLab final { const juce::MemoryBlock* binary=nullptr; }; using FxRestores=std::array,fxSlots>; + struct EqRestore final { + bool installed=false,bypassed=false; + std::array bands{}; + }; + using EqRestores=std::array; struct ChannelEdit { float linear=1.f, pan=0.f; bool mute=false, solo=false, mono=false; @@ -174,7 +179,8 @@ class LiveDryRoutingLab final { const FxSelections& selections, juce::AudioPluginFormatManager& formats, double sampleRate,int deviceFrames,bool explicitSelection=true, - const FxRestores* restores=nullptr) { + const FxRestores* restores=nullptr, + const EqRestores* eqRestores=nullptr) { // E5: the M4 compiler cannot encode an admitted native GROUP/FX RETURN. // An M4 APPLY, Show recall or structural SOURCE/AUX edit must not // erase native BUS PCM while its ChannelId graph owns the callback. @@ -308,6 +314,10 @@ class LiveDryRoutingLab final { juce::jlimit(32,Block::hardFrameLimit,deviceFrames)); if(!next->prepared || next->prepared->capacity()==0) return "Cannot allocate routing workspace"; + // Must use verified active hardware rate, never assume 48k. + if(!next->prepared->prepareBuiltInEq(sampleRate)) + return "Invalid native channel EQ device sample rate"; + next->prepared->setBuiltInEqSession(currentEpoch,revision); if(!next->prepared->setMainOutputPair( mainLeft,mainRight,callbackOutputCount_.load(std::memory_order_acquire))) return "MAIN output patch references invalid callback channels"; @@ -337,6 +347,30 @@ class LiveDryRoutingLab final { // and FxInstance has an atomic try-enter to guard against overlap. // Never reuse across a device epoch or changed device quantum. const auto* prior=publisher_.controlPrepared(currentEpoch,expectedRevision); + // Show recall must publish ONE fresh, fully prepared DSP bank. + // Never edit a prior LIVE EQ owner or borrow its histories for recall. + if(eqRestores) { + for(int lane=0;lane(lane)]; + if(!saved.installed && saved.bypassed) + return "Invalid Show EQ: bypass without insert"; + for(std::size_t slot=0;slot( + std::min(20000.0,sampleRate*.45))); + if((!saved.installed&&band.enabled)|| + !next->prepared->setBuiltInEqOffline(lane,slot,band)) + return "Show EQ filter not valid for current audio device rate"; + } + if(!next->prepared->setBuiltInEqGateOffline(lane, + saved.installed,saved.bypassed)) + return "Cannot prepare native Show EQ gate"; + } + } else if(prior)next->prepared->inheritBuiltInEqFrom(*prior); int insertCount=0,reusedCount=0; for(int lane=0;lane=fxSlots||!hasExplicitRoute()|| + expectedEpoch!=epoch()||expectedRevision!=revision())return false; + return publisher_.updateActiveControl(expectedEpoch,expectedRevision, + [&](FxGraph& fx) noexcept {return fx.setRackBypass(lane,bypass);}); + } + // Quiescent message-thread identity lease for the vendor's native GUI. // Shared lifetime is independent of route reorder, but not authority: // an editor request MUST match the current accepted route. @@ -1197,6 +1241,23 @@ class LiveDryRoutingLab final { return nativeAccepted_.setFxBypass(nativePublisher_,epochAtEdit, pcmRevision,target,slot,token,bypass); } + bool nativeChannelIsOriginalCh1(armix::mixer::ChannelId target) const noexcept { + return nativeAccepted_.fxOwners && + nativeAccepted_.fxOwners->externalChannel()==target && + target==nativeAccepted_.graph.ids.inputs[0]; + } + bool bypassNativeRack(std::uint64_t epochAtEdit,std::uint64_t pcmRevision, + armix::mixer::ChannelId target,bool bypass) noexcept { + if(!nativeAccepted_.setFxRackBypass(nativePublisher_,epochAtEdit, + pcmRevision,target,bypass)) + return false; + // 10 CH + 4 AUX share the actual EQ bank; extra native buses + // without EQ retain their native VST-only master override. + if(nativeAccepted_.graph.ids.legacyFxIndex(target)>=0) + return nativePublisher_.setBuiltInEqRackBypass( + epochAtEdit,pcmRevision,target,bypass); + return true; + } armix::mixer::DynamicChannelFxLeaseBank::Lease leaseNativeInsertEditor( std::uint64_t epochAtEdit,std::uint64_t pcmRevision, armix::mixer::ChannelId target,std::size_t slot, @@ -1720,6 +1781,8 @@ class LiveDryRoutingLab final { liveInserts.add(juce::var(item.release())); } row->setProperty("inserts",juce::var(liveInserts)); + row->setProperty("fxRackBypassed", + nativeAccepted_.fxOwners->rackBypassed(ch.id)); if(pcmMeterValid && meterIndexsetProperty("peakL",static_cast( nativeMeterPeaksL_[meterIndex].load(std::memory_order_relaxed))); @@ -1842,7 +1905,71 @@ class LiveDryRoutingLab final { } // Status / control thread only. An empty prepared graph is ready, but // cannot be advertised as a LIVE patched route or a savable Show. - bool hasExplicitRoute() const noexcept { + using BuiltInEqAck=FxGraph::BuiltInEqAck; + // Native ChannelId to the 14 original hardware/aux EQ owners only. + bool builtInEqIdentity(armix::mixer::ChannelId id,int& lane, + std::uint64_t& ep,std::uint64_t& rev) const noexcept { + if(!id.value||!ready()||!channelIdPhysicalPcmActive()|| + nativeAccepted_.deviceEpoch!=epoch())return false; + const auto index=nativeAccepted_.graph.ids.legacyFxIndex(id); + if(index<0||index>=fxSlots)return false; + lane=index;ep=epoch();rev=nativeAccepted_.pcmRevision;return true; + } + // CONTROL enqueue via the existing published graph lease, never change + // live coefficients from UI; one SPSC producer and one audio consumer. + bool queueBuiltInEqEdit(int lane,std::size_t slot, + const armix::builtin_fx::Band& band, + std::uint64_t requestId,std::uint64_t expectedEpoch, + std::uint64_t expectedRevision) noexcept { + if(!ready()||!hasExplicitRoute()||requestId==0||lane<0||lane>=fxSlots|| + expectedEpoch!=epoch())return false; + if(channelIdPhysicalPcmActive()) { + if(expectedRevision!=nativeAccepted_.pcmRevision)return false; + const auto id=lane(lane)] + :nativeAccepted_.graph.ids.aux[static_cast(lane-count)]; + return nativePublisher_.queueBuiltInEqEdit(expectedEpoch,expectedRevision, + id,slot,band,requestId); + } + if(expectedRevision!=revision())return false; + return publisher_.updateActiveControl(expectedEpoch,expectedRevision, + [&](FxGraph& graph) noexcept {return graph.queueBuiltInEqEdit( + lane,slot,band,requestId,expectedEpoch,expectedRevision);}); + } + bool queueBuiltInEqGate(int lane,bool installed,bool bypassed, + std::uint64_t req,std::uint64_t ep,std::uint64_t rev) noexcept { + if(!ready()||!hasExplicitRoute()||!req||lane<0||lane>=fxSlots||ep!=epoch()) + return false; + if(channelIdPhysicalPcmActive()) { + if(rev!=nativeAccepted_.pcmRevision)return false; + const auto id=lane(lane)] + :nativeAccepted_.graph.ids.aux[static_cast(lane-count)]; + return nativePublisher_.queueBuiltInEqGate(ep,rev,id,installed,bypassed,req); + } + if(rev!=revision())return false; + return publisher_.updateActiveControl(ep,rev, + [&](FxGraph& graph) noexcept { + return graph.queueBuiltInEqGate(lane,installed,bypassed,req,ep,rev); + }); + } + bool pollBuiltInEqAck(int lane,std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,BuiltInEqAck& ack) noexcept { + if(!ready()||lane<0||lane>=fxSlots|| + expectedEpoch!=epoch())return false; + if(channelIdPhysicalPcmActive()) { + if(expectedRevision!=nativeAccepted_.pcmRevision)return false; + const auto id=lane(lane)] + :nativeAccepted_.graph.ids.aux[static_cast(lane-count)]; + return nativePublisher_.pollBuiltInEqAck(expectedEpoch,expectedRevision,id,ack); + } + if(expectedRevision!=revision())return false; + return publisher_.updateActiveControl(expectedEpoch,expectedRevision, + [&](FxGraph& graph) noexcept {return graph.pollBuiltInEqAck(lane,ack);}) && + ack.deviceEpoch==expectedEpoch&&ack.graphRevision==expectedRevision; + } + bool hasExplicitRoute() const noexcept { return ready() && acceptedRoute_.isObject(); } std::uint64_t epoch() const noexcept { @@ -2169,6 +2296,10 @@ class LiveDryRoutingLab final { liveFxInstances.add(juce::var(slots)); } out->setProperty("fxInstances",juce::var(liveFxInstances)); + juce::Array rackFlags; + for(int lane=0;lanerackBypassed(lane):false); + out->setProperty("fxRackBypassed",juce::var(rackFlags)); juce::Array controls,fxNames; for(int i=0;i eqPending_{}; + std::array eqSnapshotDue_{}; + std::array eqLastApplied_{}; + std::array,14> eqAccepted_{}; + std::array eqInstalled_{},eqBypassed_{}; + std::uint64_t eqCacheEpoch_=0; + // Never serialize an unacknowledged command, even if output is muted. + bool unsettledBuiltInEq() const noexcept { + return std::any_of(eqPending_.begin(),eqPending_.end(), + [](const EqPending& p){return p.active;}); + } + void captureAcceptedEq(armix::shows::SnapshotV2& show) const noexcept { + for(std::size_t lane=0;lane(std::min( + 20000.0,device->getCurrentSampleRate()*.45)); + for(auto& band:eqAccepted_[lane]) + if(!band.enabled)band.frequencyHz=std::min( + band.frequencyHz,safeHz); + } + // No fabricated DSP acknowledgement; the new graph contains + // accepted offline state and UI requests a fresh native snapshot. + } + } + void syncEqEpoch(std::uint64_t ep) { + if(eqCacheEpoch_==ep)return; + eqCacheEpoch_=ep;eqSnapshotDue_.fill(false);eqLastApplied_.fill(0); + eqInstalled_.fill(false);eqBypassed_.fill(false); + for(auto& pending:eqPending_)pending={}; + auto* hardware=engine_.devices().getCurrentAudioDevice(); + const float safeHz=hardware? + static_cast(std::min(20000.0,hardware->getCurrentSampleRate()*.45)): + 20000.f; + for(auto& lane:eqAccepted_) + for(std::size_t i=0;i20)return false; + std::uint64_t n=0; + for(int i=0;i'9')return false; + const auto digit=static_cast(c-'0'); + if(n>(UINT64_MAX-digit)/10u)return false; + n=n*10u+digit; + } + result=n;return n>0; + } + static bool eqFloat(const juce::var& v,float& out) noexcept { + if(!(v.isInt()||v.isInt64()||v.isDouble()))return false; + const auto n=static_cast(v); + if(!std::isfinite(n)||std::abs(n)>1000000.)return false; + out=static_cast(n);return true; + } + void emitEqSnapshot(armix::mixer::ChannelId id) { + int lane=-1;std::uint64_t ep=0,rev=0; + if(!browser_.loaded || !engine_.builtInEqIdentity(id,lane,ep,rev))return; + syncEqEpoch(ep); + auto out=std::make_unique(); + out->setProperty("schemaVersion",1); + out->setProperty("channelId",juce::String(std::to_string(id.value))); + out->setProperty("deviceEpoch",juce::String(std::to_string(ep))); + out->setProperty("graphRevision",juce::String(std::to_string(rev))); + out->setProperty("appliedRequestId",juce::String( + std::to_string(eqLastApplied_[static_cast(lane)]))); + if(auto* device=engine_.devices().getCurrentAudioDevice()) + out->setProperty("sampleRate",device->getCurrentSampleRate()); + juce::Array bands; + for(const auto& band:eqAccepted_[static_cast(lane)]) { + auto row=std::make_unique(); + row->setProperty("enabled",band.enabled); + row->setProperty("frequencyHz",band.frequencyHz); + row->setProperty("gainDb",band.gainDb); + row->setProperty("q",band.q); + row->setProperty("slope",static_cast(band.slope)); + bands.add(juce::var(row.release())); + } + out->setProperty("bands",juce::var(bands)); + out->setProperty("installed",eqInstalled_[static_cast(lane)]); + out->setProperty("bypassed",eqBypassed_[static_cast(lane)]); + browser_.emitEventIfBrowserIsVisible("arMixBuiltinEqSnapshot", + juce::var(out.release())); + } + void onEqAction(const juce::var& a) { + std::uint64_t number=0,ep=0,rev=0,req=0; + const auto hasId=eqUInt(a.getProperty("channelId",{}),number); + const armix::mixer::ChannelId ch{number}; + int lane=-1;std::uint64_t liveEp=0,liveRev=0; + const bool available=hasId&&engine_.builtInEqIdentity(ch,lane,liveEp,liveRev); + const bool gateAction=a.getProperty("action",{}).toString()=="builtinEqSetGate"; + if(a.getProperty("action",{}).toString()=="builtinEqSnapshot") { + if(available)emitEqSnapshot(ch); + return; + } + bool queued=false; + if(available&&eqUInt(a.getProperty("deviceEpoch",{}),ep)&& + eqUInt(a.getProperty("graphRevision",{}),rev)&& + eqUInt(a.getProperty("requestId",{}),req)&& + ep==liveEp&&rev==liveRev&&!studioBackupBusy_&&!nativeShowBusy_ && + (gateAction||a.getProperty("slot",{}).isInt()|| + a.getProperty("slot",{}).isInt64())) { + syncEqEpoch(ep); + const auto slot=static_cast(a.getProperty("slot",-1)); + const auto b=a.getProperty("band",{}); + const auto enabled=b.getProperty("enabled",{}); + float freq=0,gain=0,q=0,slope=0; + auto& pending=eqPending_[static_cast(lane)]; + if(!pending.active&&gateAction&& + a.getProperty("installed",{}).isBool()&& + a.getProperty("bypassed",{}).isBool()) { + const bool install=static_cast(a.getProperty("installed",{})); + const bool bypass=static_cast(a.getProperty("bypassed",{})); + queued=engine_.queueBuiltInEqGate(lane,install,bypass,req,ep,rev); + if(queued)pending={ch,req,ep,rev,-1,true}; + } else if(!pending.active&&!gateAction&& + eqInstalled_[static_cast(lane)]&& + slot>=0&&slot<8&&b.isObject()&&enabled.isBool()&& + eqFloat(b.getProperty("frequencyHz",{}),freq)&& + eqFloat(b.getProperty("gainDb",{}),gain)&& + eqFloat(b.getProperty("q",{}),q)&& + eqFloat(b.getProperty("slope",{}),slope)&& + (slope==12.f||slope==24.f)) { + armix::builtin_fx::Band band{}; + band.enabled=static_cast(enabled); + band.frequencyHz=freq;band.gainDb=gain;band.q=q; + band.slope=slope==24.f?armix::builtin_fx::Slope::db24: + armix::builtin_fx::Slope::db12; + queued=engine_.queueBuiltInEqEdit(lane,static_cast(slot), + band,req,ep,rev); + if(queued) pending={ch,req,ep,rev,slot,true}; + } + } + auto reply=std::make_unique(); + reply->setProperty("schemaVersion",1); + reply->setProperty("requestId",juce::String(std::to_string(req))); + reply->setProperty("channelId",juce::String(std::to_string(number))); + reply->setProperty("status",queued?"QUEUED":"REJECTED"); + browser_.emitEventIfBrowserIsVisible("arMixBuiltinEqQueue", + juce::var(reply.release())); + } + void serviceEqAck() { + if(!browser_.loaded)return; + for(int lane=0;lane<14;++lane)if(eqSnapshotDue_[static_cast(lane)]) { + eqSnapshotDue_[static_cast(lane)]=false; + emitEqSnapshot(eqPending_[static_cast(lane)].channel); + } + for(int lane=0;lane<14;++lane) { + auto& pending=eqPending_[static_cast(lane)]; + if(!pending.active)continue; + // A graph rebuild or device reconnect invalidates the old EQ + // authority. Such a command cannot be ACKed by the new graph: + // the bank rejects its old revision at the next callback. Do + // not let it indefinitely block Show SAVE/RECALL. + int currentLane=-1; + std::uint64_t currentEpoch=0,currentRevision=0; + const bool sameSession=engine_.builtInEqIdentity( + pending.channel,currentLane,currentEpoch,currentRevision) && + currentLane==lane && currentEpoch==pending.epoch && + currentRevision==pending.revision; + LiveAudioEngine::BuiltInEqAck ack{}; + const bool got=sameSession && + engine_.pollBuiltInEqAck(lane,pending.epoch,pending.revision,ack); + // No audio callback while muted is NOT a rejected command. + // Only real AUDIO ACK or invalidated graph authority settles it. + if(sameSession&&!got)continue; + const bool ok=got&&ack.applied&&ack.requestId==pending.request && + ack.lane==lane&& + ((pending.slot<0&&ack.gate)|| + (pending.slot>=0&&!ack.gate&&ack.slot==pending.slot)); + auto reply=std::make_unique(); + reply->setProperty("schemaVersion",1); + reply->setProperty("requestId",juce::String(std::to_string(pending.request))); + reply->setProperty("channelId",juce::String(std::to_string(pending.channel.value))); + reply->setProperty("deviceEpoch",juce::String(std::to_string(pending.epoch))); + reply->setProperty("graphRevision",juce::String(std::to_string(pending.revision))); + reply->setProperty("status",ok?"APPLIED":"REJECTED"); + if(ok) { + const auto index=static_cast(lane); + if(pending.slot<0) { + eqInstalled_[index]=ack.installed; + eqBypassed_[index]=ack.bypassed; + if(!ack.installed) { + auto* device=engine_.devices().getCurrentAudioDevice(); + const float safeHz=device?static_cast( + std::min(20000.0,device->getCurrentSampleRate()*.45)):20000.f; + for(std::size_t i=0;i(pending.slot)]=ack.accepted; + eqLastApplied_[index]=pending.request; + eqSnapshotDue_[static_cast(lane)]=true; + } + browser_.emitEventIfBrowserIsVisible("arMixBuiltinEqAck", + juce::var(reply.release())); + pending.active=false; + } + } + bool webViewPeerWarmed_ = false; bool webViewStartupNoticeSent_ = false; juce::uint32 webViewStartupTick_ = 0; @@ -1404,6 +1638,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void onAction (const juce::var& args) { const auto action = args.getProperty ("action", {}).toString(); + if(action=="builtinEqSetBand"||action=="builtinEqSetGate"|| + action=="builtinEqSnapshot") { + onEqAction(args);return; + } const auto value = args.getProperty ("value", {}); const int slot = static_cast (args.getProperty ("slot", -1)); // User may adjust live levels, but cannot alter the persisted VST @@ -1412,7 +1650,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr action.startsWith ("import") || action.startsWith ("fx") || action == "addCatalog" || action == "addScanFolder" || action == "scanVst3" || action == "routingDryApply" || - action == "routingFxBypass")) + action == "routingFxBypass" || + action == "routingNativeFxRackBypass" || + action == "routingNativeFxInsertBypass")) { const auto reason=juce::String( "Studio backup in progress. Finish backup before editing saved FX or VST library."); @@ -1430,6 +1670,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr action=="routingDryApply"?"arMixRoutingLabAck":"arMixRoutingFxBypassAck", juce::var(ack.release())); } + if((action=="routingNativeFxRackBypass" || + action=="routingNativeFxInsertBypass") && browser_.loaded) { + auto ack=std::make_unique(); + ack->setProperty("requestId",args.getProperty("requestId",{})); + ack->setProperty("ok",false); + ack->setProperty("error",reason); + browser_.emitEventIfBrowserIsVisible( + "arMixNativeFxPowerAck",juce::var(ack.release())); + } return emitNotice(reason,true); } @@ -1614,6 +1863,65 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(!ok)emitNotice("Live AUX send rejected; refresh accepted routing.",true); return; } + // Accepted ChannelId FX power. A rack master is an additive gate, + // not a rewrite of the eight saved individual bypass preferences. + // Both gestures are fenced to the actual device epoch + PCM revision + // and reply with an ACK; the WebView re-reads the producer snapshot. + if(action=="routingNativeFxRackBypass" || + action=="routingNativeFxInsertBypass") { + const auto request=args.getProperty("requestId",{}).toString(); + const auto rawId=args.getProperty("channelId",{}); + const auto rawEpoch=args.getProperty("deviceEpoch",{}); + const auto rawRevision=args.getProperty("revision",{}); + const auto parse=[](const juce::var& wire,std::uint64_t& out) -> bool { + if(!wire.isString())return false; + const auto text=wire.toString().toStdString(); + if(text.empty()||text.size()>20|| + text[0]=='0'||text.find_first_not_of("0123456789")!=std::string::npos) + return false; + try { + const auto decoded=std::stoull(text); + if(!decoded||std::to_string(decoded)!=text)return false; + out=decoded;return true; + } catch(...) {return false;} + }; + std::uint64_t channel=0,ep=0,rev=0; + const bool valid=request.isNotEmpty()&&request.length()<=128 && + parse(rawId,channel)&&parse(rawEpoch,ep)&& + parse(rawRevision,rev)&&value.isBool() && + !studioBackupBusy_&&!nativeShowBusy_&& + !engine_.independentClockActive(); + bool applied=false; + if(valid && !acceptedControlRequests_.contains(request)) { + acceptedControlRequests_.add(request); + if(acceptedControlRequests_.size()>512) + acceptedControlRequests_.remove(0); + const armix::mixer::ChannelId id{channel}; + if(action=="routingNativeFxRackBypass") + applied=engine_.bypassNativeFxRack(ep,rev,id,static_cast(value)); + else { + const auto token=args.getProperty("insertId",{}).toString(); + applied=slot>=0&&slot(slot),token,static_cast(value)); + } + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("ok",applied); + ack->setProperty("channelId",rawId); + ack->setProperty("bypassed",value); + ack->setProperty("error",applied?juce::String(): + "Native FX power rejected: stale device/revision, Show busy or instance mismatch"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixNativeFxPowerAck",juce::var(ack.release())); + if(applied)diagnostics_.record("NATIVE_FX_POWER", + rawId.toString()+(action=="routingNativeFxRackBypass"?" rack":" insert")+ + (static_cast(value)?" BYPASS":" ENABLE")); + return; + } + // G5C native per-instance BYPASS never recompiles the graph and // does not require muting the output. All identity gates must agree. if (action == "routingFxBypass") { @@ -1696,6 +2004,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (nativeShowBusy_ || studioBackupBusy_ || catalog_.busy() || engine_.isGraphSwitchPending() || engine_.hasTemporaryDiagnosticDevice()) return reject("Finish the current Studio task before capturing a native Show."); + if(unsettledBuiltInEq()) + return reject("Wait for the pending native EQ AUDIO ACK before Show SAVE."); // Never save the unacknowledged JS draft. Message-thread capture // reads the accepted LIVE graph, updated faders and exact device epoch. // VST3 is fail-closed until a quiescent vendor state capture gate exists. @@ -1709,6 +2019,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr static_cast(lab.getProperty("revision",juce::var(0)))); auto error=armix::shows::NativeLiveShowCapture::captureDry( nativeStatus,name,captured,true); + if(error.isEmpty()) { + syncEqEpoch(epoch); + if(unsettledBuiltInEq())error="Native EQ changed during Show capture"; + else captureAcceptedEq(captured); // exact ACK-accepted 10 CH + 4 AUX + } std::vector blobs; if(error.isEmpty()) { // Do not read vendor parameters while an editor is open. @@ -1750,7 +2065,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } } if(error.isEmpty()) { - captured.sourceBuild="G5E_NATIVE_FX_SHOW_CAPTURE"; + captured.sourceBuild="BUILTIN_EQ_V5_PLUS_G5E_VST3_SHOW_CAPTURE"; armix::shows::SnapshotV2 verified; if(!armix::shows::Codec::decode( armix::shows::Codec::encode(captured),verified)) @@ -1847,6 +2162,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr }; if(!armix::shows::detail::uuid(id)) return reject("Select a native Show UUID from the saved list."); + if(unsettledBuiltInEq()) + return reject("Wait for pending native EQ AUDIO ACK before Show RECALL."); if(nativeShowBusy_ || studioBackupBusy_ || catalog_.busy() || engine_.isGraphSwitchPending() || !engine_.allOutputsDisarmed()) return reject("Mute native output and finish ongoing Studio work."); @@ -1884,6 +2201,17 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr try { LiveDryRoutingLab::FxSelections selections{}; LiveDryRoutingLab::FxRestores restores{}; + LiveDryRoutingLab::EqRestores eqRestores{}; + for(int lane=0;lane(lane)].eq + :result.loaded.aux[static_cast( + lane-LiveDryRoutingLab::count)].eq; + auto& eq=eqRestores[static_cast(lane)]; + eq.installed=eqSaved.installed; + eq.bypassed=eqSaved.bypassed; + eq.bands=eqSaved.bands; + } const auto attach=[&](int lane, const std::vector& refs) ->juce::String { @@ -1926,7 +2254,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(error.isEmpty()) { safe->closePluginEditor(); error=safe->engine_.applyDryRoutingLab( - command,selections,&restores); + command,selections,&restores,&eqRestores); + if(error.isEmpty()) { + // Only after all VST3 AND built-in EQ + // state is accepted in one new native graph. + const auto epochNow=static_cast( + static_cast( + lab.getProperty("epoch",juce::var(0)))); + safe->acceptedEqFromShow(result.loaded,epochNow); + } } } catch(const std::exception& ex) { error="Native VST3 Show preflight exception: "+ @@ -2668,6 +3004,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } } if (!browser_.loaded) return; + serviceEqAck(); // exact DSP-apply ACK, deferred readback, no new poll thread if (!initialStateSent_) { initialStateSent_ = true; diff --git a/src/NativeShowSchema.h b/src/NativeShowSchema.h index e0abff646..44c7b47af 100644 --- a/src/NativeShowSchema.h +++ b/src/NativeShowSchema.h @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only #pragma once #include +#include "../engine/builtin_fx/ChannelEq.h" #include #include #include @@ -24,6 +25,19 @@ struct FxRef final { juce::String stateSha256; // external, separately verified immutable blob bool bypass = false; }; +// v5: Compact CONTROL-only 8-band EQ record per fixed channel/AUX. +// Never stores a vendor plugin, UI ordinal, device pointer or PCM state. +struct EqState final { + bool installed=false,bypassed=false; + std::array bands{}; + EqState() noexcept { + for(std::size_t i=0;i fx; + EqState eq; std::vector sends; }; // AUX is an extra, one-way stereo FX return, not INPUT CH9/10 or hardware I/O. @@ -47,6 +62,7 @@ struct AuxReturn final { bool enabled = false, toMaster = true, mute = false; double gain = 1.0; std::vector fx; + EqState eq; }; struct AuxSend final { int source = -1; // physical logical INPUT 0..9 @@ -165,9 +181,9 @@ class Codec final { static juce::String encode(const SnapshotV2& s) { auto v=detail::object(); detail::commonWrite(v,s.id,s.name,s.createdMs,s.modifiedMs); - // V4 records the independent channel processing width; V3 lacked - // this field and V2 also lacked AUX returns. Old readers fail closed. - detail::put(v,"schemaVersion",4); + // V5 adds real native Channel EQ with an exact 8-band record per + // original CH/AUX; V2-V4 remain readable only as EQ-not-installed. + detail::put(v,"schemaVersion",5); detail::put(v,"format","arsonmix.native.snapshot"); detail::put(v,"sourceBuild",s.sourceBuild); auto master=detail::object(); @@ -197,6 +213,7 @@ class Codec final { sends.add(p); } detail::put(c,"fx",juce::var(fx));detail::put(c,"sends",juce::var(sends)); + detail::put(c,"builtinEq",encodeEq(ch.eq)); strips.add(c); } detail::put(v,"strips",juce::var(strips)); @@ -210,6 +227,7 @@ class Codec final { detail::put(rec,"mute",bus.mute); detail::put(rec,"gain",bus.gain); detail::put(rec,"fx",juce::var(encodeFx(bus.fx))); + detail::put(rec,"builtinEq",encodeEq(bus.eq)); aux.add(rec); } for(const auto& send:s.auxSends) { @@ -241,9 +259,9 @@ class Codec final { static bool decode(const juce::String& json,SnapshotV2& out) { if(json.getNumBytesAsUTF8()>maxJsonBytes) return false; const auto v=juce::JSON::parse(json); - if(!detail::header(v,"arsonmix.native.snapshot",2,4)) return false; + if(!detail::header(v,"arsonmix.native.snapshot",2,5)) return false; int version=0; - if(!detail::integer(detail::get(v,"schemaVersion"),version,2,4)) + if(!detail::integer(detail::get(v,"schemaVersion"),version,2,5)) return false; SnapshotV2 next; if(!detail::common(v,next.id,next.name,next.createdMs,next.modifiedMs) || @@ -284,7 +302,7 @@ class Codec final { // V2/V3 migration infers exactly the original native v1 format. // Never silently discard a new typed width from a downgraded file. const auto width=detail::get(rec,"channelFormat"); - if(version==4){ + if(version>=4){ if(!detail::integer(width,ch.channelFormat,1,2))return false; } else { if(!width.isVoid())return false; @@ -294,6 +312,10 @@ class Codec final { (ch.source==1 && (ch.inputA<0||ch.inputB!=-1)) || (ch.source==2 && (ch.inputA<0||ch.inputB<0||ch.inputA==ch.inputB))) return false; + const auto eqRecord=detail::get(rec,"builtinEq"); + if(version>=5) { + if(!decodeEq(eqRecord,ch.eq)) return false; + } else if(!eqRecord.isVoid()) return false; // no silent EQ downgrade const auto fxv=detail::get(rec,"fx"), sv=detail::get(rec,"sends"); const auto* sends=sv.getArray(); if(!sends || (totalSends+=sends->size())>maxSendsPerSnapshot || @@ -334,6 +356,10 @@ class Codec final { !detail::flag(detail::get(rec,"mute"),bus.mute) || !detail::real(detail::get(rec,"gain"),bus.gain,0.0,4.0) || !decodeFx(detail::get(rec,"fx"),bus.fx)) return false; + const auto eqRecord=detail::get(rec,"builtinEq"); + if(version>=5) { + if(!decodeEq(eqRecord,bus.eq))return false; + } else if(!eqRecord.isVoid())return false; } for(const auto& rec:*sends) { AuxSend send; @@ -353,6 +379,53 @@ class Codec final { out=std::move(next); return true; } private: + static juce::var encodeEq(const EqState& state) { + auto rec=detail::object(); + detail::put(rec,"installed",state.installed); + detail::put(rec,"bypassed",state.bypassed); + juce::Array rows; + for(const auto& band:state.bands) { + auto b=detail::object(); + detail::put(b,"enabled",band.enabled); + detail::put(b,"frequencyHz",static_cast(band.frequencyHz)); + detail::put(b,"gainDb",static_cast(band.gainDb)); + detail::put(b,"q",static_cast(band.q)); + detail::put(b,"slope",static_cast(band.slope)); + rows.add(b); + } + detail::put(rec,"bands",juce::var(rows)); + return rec; + } + static bool decodeEq(const juce::var& rec,EqState& result) { + if(!rec.isObject())return false; + EqState next; + if(!detail::flag(detail::get(rec,"installed"),next.installed)|| + !detail::flag(detail::get(rec,"bypassed"),next.bypassed)|| + (!next.installed&&next.bypassed))return false; + const auto bandsValue=detail::get(rec,"bands"); + const auto* rows=bandsValue.getArray(); + if(!rows||rows->size()!=static_cast(next.bands.size()))return false; + for(std::size_t i=0;igetReference(static_cast(i)); + auto& band=next.bands[i]; + int slope=0; + double freq=0,gain=0,q=0; + if(!b.isObject()|| + !detail::flag(detail::get(b,"enabled"),band.enabled)|| + !detail::real(detail::get(b,"frequencyHz"),freq,20.,20000.)|| + !detail::real(detail::get(b,"gainDb"),gain,-18.,18.)|| + !detail::real(detail::get(b,"q"),q,.2,12.)|| + !detail::integer(detail::get(b,"slope"),slope,12,24)|| + (slope!=12&&slope!=24)|| + (!next.installed&&band.enabled))return false; + band.frequencyHz=static_cast(freq); + band.gainDb=static_cast(gain); + band.q=static_cast(q); + band.slope=static_cast(slope); + } + result=next; + return true; + } static juce::Array encodeFx(const std::vector& fx) { juce::Array encoded; for(const auto& f:fx) { diff --git a/tests/approved_builtin_peq_picker_smoke.py b/tests/approved_builtin_peq_picker_smoke.py new file mode 100644 index 000000000..708a94165 --- /dev/null +++ b/tests/approved_builtin_peq_picker_smoke.py @@ -0,0 +1,85 @@ +"""Real pointer/keyboard contract for single approved /preview/ FX picker and Parametric EQ. +Browser-only visual demo is not audible PCM or hardware FAT. +""" +from pathlib import Path +from playwright.sync_api import sync_playwright + +PAGE=Path(__file__).resolve().parents[1]/"dist-pages/preview/index.html" + +def main(): + assert PAGE.is_file(), "Build approved /preview/ first" + with sync_playwright() as pw: + browser=pw.chromium.launch(headless=True) + try: + for width,height in [(390,844),(1366,768),(1680,900)]: + page=browser.new_page(viewport={"width":width,"height":height}) + errors=[] + page.on("pageerror", lambda e: errors.append(str(e))) + page.goto(PAGE.as_uri()) + strip=page.locator('#tracks .strip[data-id="1"]') + strip.wait_for() + assert page.locator('#mxBuiltinEq').is_hidden() + strip.locator('.fx-pick.empty').click() + picker=page.locator('#fastPicker') + assert picker.is_visible() + choice=page.locator('#fastResults [data-fast-builtin-eq]') + assert choice.count()==1 and "Parametric EQ" in choice.inner_text() + choice.click() + assert picker.is_hidden() + editor=page.locator('#mxBuiltinEq') + assert editor.is_hidden(), "Selecting a plugin cannot auto-open the editor" + row=strip.locator('.fxslot-row.is-builtin') + assert row.count()==1 and "Parametric EQ" in row.inner_text() + assert row.get_attribute('data-fx-effective')=="true" + assert "FX 2" in strip.locator('.fx-section .hint').inner_text() + row.locator('[data-action="openBuiltinEq"]').click() + assert editor.is_visible() + assert editor.locator('.mx-eq-mode').inner_text()=="UI DEMO · NO AUDIO" + title=editor.locator('.mx-eq-top') + rect=editor.bounding_box() + bar=title.bounding_box() + assert rect and bar + x=bar["x"]+min(110,bar["width"]/3) + y=bar["y"]+bar["height"]/2 + page.mouse.move(x,y) + page.mouse.down() + page.mouse.move(x+37,y+23,steps=5) + page.mouse.up() + moved=editor.bounding_box() + assert moved and moved["x"]>=rect["x"]+(3 if width < 760 else 23) and moved["y"]>=rect["y"]+13,(rect,moved) + band=editor.locator('.mx-eq-band[data-slot="3"]') + band.click() + assert "selected" in band.get_attribute("class") + editor.locator('.mx-eq-switch').click() + assert editor.locator('.mx-eq-switch').get_attribute('aria-pressed')=="true" + freq=editor.get_by_label('FREQUENCY · Hz') + freq.fill("735") + freq.press("Tab") + assert freq.input_value()=="735" + gain=editor.get_by_label('GAIN · dB') + gain.fill("4.0") + gain.press("Tab") + assert gain.input_value()=="4.0" + # Capture the EXACT approved GUI actually rendered by Chromium. + # These are screenshots of an interactive UI DEMO, NOT audio PCM. + page.screenshot(path=f"parametric-eq-mixer-{width}x{height}.png",animations="disabled") + editor.screenshot(path=f"parametric-eq-editor-{width}x{height}.png",animations="disabled") + editor.locator('.mx-eq-close').click() + assert editor.is_hidden() + row.locator('[data-action="openBuiltinEq"]').click() + assert editor.is_visible() + # Editor starts on P1 each time; recall the previously edited P2. + editor.locator('.mx-eq-band[data-slot="3"]').click() + assert editor.get_by_label('FREQUENCY · Hz').input_value()=="735" + assert editor.get_by_label('GAIN · dB').input_value()=="4.0" + editor.locator('.mx-eq-close').click() + row.locator('[data-action="builtinEqRemove"]').click() + assert strip.locator('.fxslot-row.is-builtin').count()==0 + assert not errors, errors + print("PASS Parametric EQ pick/insert/open/drag/edit/reopen/remove",width,height) + page.close() + finally: + browser.close() + +if __name__=="__main__": + main() diff --git a/tests/approved_fx_rack_master_power_smoke.py b/tests/approved_fx_rack_master_power_smoke.py new file mode 100644 index 000000000..25eb5dd9e --- /dev/null +++ b/tests/approved_fx_rack_master_power_smoke.py @@ -0,0 +1,89 @@ +"""P0 FX rack: header bypass overrides effective power, never saved slots. + +Chromium exercises ONE actual built /preview/ GUI (also used by native JUCE). +Public Pages only demonstrates the control state; real DSP is checked in +native engine contracts/Windows CTest and physical hardware FAT separately. +""" +from pathlib import Path +from playwright.sync_api import sync_playwright + +PAGE=Path(__file__).resolve().parents[1]/"dist-pages/preview/index.html" + + +def snapshot(page, channel=1): + root=page.locator(f'#tracks .strip[data-id="{channel}"] .fx-section') + return root.evaluate("""el=>({ + rack:el.dataset.fxChainEnabled, + header:el.querySelector('[data-action="fxOn"]').getAttribute('aria-pressed'), + slots:[...el.querySelectorAll('.fxslot-row:not(.is-empty)')].map(row=>({ + id:row.dataset.insertId, + individual:row.dataset.fxSlotEnabled, + effective:row.dataset.fxEffective, + power:row.querySelector('[data-action="slotPower"]') + ?.getAttribute('aria-pressed'), + bypassed:row.classList.contains('is-bypassed') + })) + })""") + + +def main(): + assert PAGE.is_file(), "build official /preview/ first" + with sync_playwright() as pw: + browser=pw.chromium.launch(headless=True) + try: + for width,height in [(390,844),(1366,768),(1680,900)]: + page=browser.new_page(viewport={"width":width,"height":height}) + errors=[] + page.on("pageerror",lambda e:errors.append(str(e))) + page.goto(PAGE.as_uri()) + page.locator("#tracks .strip[data-id='1']").wait_for() + root=page.locator('#tracks .strip[data-id="1"]') + initial=snapshot(page) + assert len(initial["slots"])==1 and initial["slots"][0]["power"]=="true",initial + # Load the second effect using the actual UI picker. + root.locator('.fx-pick.empty').click() + page.locator('#fastResults [data-fast-id]').first.click() + both=snapshot(page) + assert len(both["slots"])==2 and all( + x["power"]=="true" for x in both["slots"]),both + # Individual OFF is a stored preference, never overwritten. + root.locator('[data-action="slotPower"][data-slot="0"]').click() + individual=snapshot(page) + assert individual["slots"][0]["individual"]=="false",individual + assert individual["slots"][1]["individual"]=="true",individual + # On phones the official console banks one channel at a + # time; inspect CH2 via its real bank selector, not a hidden DOM. + if width < 500: + page.locator("#bankSelect").select_option("1") + other=snapshot(page,2) + if width < 500: + page.locator("#bankSelect").select_option("0") + root.locator('[data-action="fxOn"]').click() + off=snapshot(page) + assert off["header"]==off["rack"]=="false",off + assert all(row["power"]=="false" and + row["effective"]=="false" and row["bypassed"] + for row in off["slots"]),off + assert [r["individual"] for r in off["slots"]]==["false","true"],off + assert [r["id"] for r in off["slots"]]==[r["id"] for r in individual["slots"]],off + if width < 500: + page.locator("#bankSelect").select_option("1") + assert snapshot(page,2)==other,"Rack power leaked into other channel" + if width < 500: + page.locator("#bankSelect").select_option("0") + root.locator('[data-action="fxOn"]').click() + restored=snapshot(page) + assert restored["header"]==restored["rack"]=="true",restored + assert [r["power"] for r in restored["slots"]]==["false","true"],restored + assert [r["effective"] for r in restored["slots"]]==["false","true"],restored + assert [r["individual"] for r in restored["slots"]]==["false","true"],restored + assert [r["id"] for r in restored["slots"]]==[r["id"] for r in individual["slots"]],restored + assert not errors,errors + print("PASS FX rack master power + saved individual state",width,height) + page.close() + finally: + browser.close() + + +if __name__=="__main__": + main() diff --git a/tests/builtin_channel_eq_bank_test.cpp b/tests/builtin_channel_eq_bank_test.cpp new file mode 100644 index 000000000..0d00bd83e --- /dev/null +++ b/tests/builtin_channel_eq_bank_test.cpp @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/builtin_fx/ChannelEqBank.h" +#include +#include + +#include +#include +#include +#include +static std::atomic denyHeap{false}; +void* operator new(std::size_t n) {if(denyHeap.load()) std::abort();if(void* p=std::malloc(n?n:1))return p;throw std::bad_alloc();} +void* operator new[](std::size_t n) {if(denyHeap.load())std::abort();if(void* p=std::malloc(n?n:1))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);} +static void require(bool v, const char* expression, int line) {if(!v){std::fprintf(stderr,"FAIL at %d: %s\n",line,expression);std::abort();}} +#define CHECK(e) require(bool(e),#e,__LINE__) +using namespace armix::builtin_fx; +int main() { + ChannelEqBank bank; + CHECK(!bank.ready());CHECK(!bank.queueBandEdit(0,2,Band{},1,1,1)); + CHECK(bank.prepare(48000));CHECK(!bank.prepare(44100)); + CHECK(bank.addedLatencySamples()==0); + std::array l{},r{}; + for(std::size_t i=0;i reference{},out{},silent{}; + double dryEnergy=0,wetEnergy=0; + for(int block=0;block<64;++block) { + for(int i=0;i<128;++i) + reference[static_cast(i)]= + static_cast(.1*std::sin(6.283185307179586* + 1000.0*(block*128+i)/48000.0)); + out=reference; + restored.render(3,out.data(),silent.data(),128); + CHECK(out==reference); // restored bypass must be bitwise dry + } + CHECK(restored.setGateOffline(3,true,false)); // offline only, new candidate + for(int block=0;block<64;++block) { + for(int i=0;i<128;++i) + reference[static_cast(i)]= + static_cast(.1*std::sin(6.283185307179586* + 1000.0*(block*128+i)/48000.0)); + out=reference; + restored.render(3,out.data(),silent.data(),128); + if(block>=48)for(int i=0;i<128;++i) { + dryEnergy+=reference[static_cast(i)]* + reference[static_cast(i)]; + wetEnergy+=out[static_cast(i)]* + out[static_cast(i)]; + } + } + CHECK(dryEnergy>0.001&&wetEnergy>dryEnergy*4); + CHECK(!restored.setGateOffline(14,true,false)); + // Rack OFF: exact dry PCM once the 5ms fade completes, while the EQ's + // own ON preference and eight bands remain unchanged. + CHECK(restored.setRackBypass(3,true)); + for(int block=0;block<10;++block){ + for(int i=0;i<128;++i) + reference[static_cast(i)]= + static_cast(.1*std::sin(6.283185307179586* + 1000.0*(block*128+i)/48000.0)); + out=reference; + restored.render(3,out.data(),silent.data(),128); + if(block>=6)CHECK(out==reference); + } + CHECK(restored.rackBypassed(3)); + CHECK(restored.setRackBypass(3,false)); + double resumedEnergy=0,dryResumed=0; + for(int block=0;block<64;++block){ + for(int i=0;i<128;++i) + reference[static_cast(i)]= + static_cast(.1*std::sin(6.283185307179586* + 1000.0*(block*128+i)/48000.0)); + out=reference; + restored.render(3,out.data(),silent.data(),128); + if(block>=48)for(int i=0;i<128;++i){ + resumedEnergy+=out[static_cast(i)]* + out[static_cast(i)]; + dryResumed+=reference[static_cast(i)]* + reference[static_cast(i)]; + } + } + CHECK(resumedEnergy>dryResumed*4); + CHECK(!restored.rackBypassed(3)&&!restored.setRackBypass(14,true)); + std::puts("PASS: 14-lane EQ, Show V5 offline restore/bypass PCM, SPSC ACK, no RT heap"); +} diff --git a/tests/builtin_channel_eq_test.cpp b/tests/builtin_channel_eq_test.cpp new file mode 100644 index 000000000..bd6c280d4 --- /dev/null +++ b/tests/builtin_channel_eq_test.cpp @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/builtin_fx/ChannelEq.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +std::atomic noHeap{false}; +[[noreturn]] void fail(const char* test) noexcept { + std::fprintf(stderr, "FAIL: %s\n", test); + std::abort(); +} +void check(bool ok, const char* test) noexcept { if (!ok) fail(test); } +bool near(double actual, double expected, double tolerance) noexcept { + return std::abs(actual-expected) <= tolerance; +} +} // namespace + +// Optional hard tripwire: processing/configuration must never request heap. +void* operator new(std::size_t n) { + if (noHeap.load(std::memory_order_relaxed)) fail("heap allocation in built-in DSP"); + if (auto* p=std::malloc(n?n:1)) return p; + throw std::bad_alloc(); +} +void* operator new[](std::size_t n) { + if (noHeap.load(std::memory_order_relaxed)) fail("heap allocation in built-in DSP[]"); + if (auto* p=std::malloc(n?n:1)) 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); } + +using namespace armix::builtin_fx; +static Band onBand(ChannelEq& eq, std::size_t slot, float freq, float gain=0.0f, + float q=1.0f, Slope slope=Slope::db12) { + Band b=eq.band(slot); + b.enabled=true; b.frequencyHz=freq; b.gainDb=gain; b.q=q; b.slope=slope; + check(eq.setBand(slot,b),"set band accepted"); + return b; +} +static void runUntilSettled(ChannelEq& eq) { + std::array l{},r{}; + while(eq.transitioning())eq.processStereo(l.data(),r.data(),l.size()); +} +static void testCatalogAndDefault() { + check(channelEqId=="armix.builtin.channel-eq.v1","stable built-in ID"); + check(ChannelEq::bandCount==8,"eight slots exactly"); + check(channelEqSlots[0].kind==FilterKind::highPass,"fixed HPF slot"); + check(channelEqSlots[7].kind==FilterKind::lowPass,"fixed LPF slot"); + for(int rate : {44100,48000,96000}) { + ChannelEq eq; + check(eq.prepare(rate),"prepare sample rate"); + check(eq.activeBands()==0,"all filters off on first launch"); + check(eq.addedLatencySamples()==0,"no buffering/lookahead"); + std::array l{},r{}; + for (std::size_t i=0;i(i)*0.001f - 0.05f; + r[i]=1.0f-l[i]; + } + const auto unchangedL=l,unchangedR=r; + eq.processStereo(l.data(),r.data(),l.size()); + check(l==unchangedL&&r==unchangedR,"exact transparent disabled stereo"); + eq.processMono(l.data(),l.size()); + check(l==unchangedL,"exact transparent disabled mono"); + eq.processStereo(nullptr,nullptr,128); + eq.processMono(nullptr,128); + } + ChannelEq lowSample; + check(lowSample.prepare(8000),"8k rate supported"); + check(lowSample.band(7).frequencyHz<=3600.f,"disabled default clamps below Nyquist"); + check(!lowSample.prepare(0)&&!lowSample.prepare(std::numeric_limits::infinity()),"invalid sample rate rejected"); +} +static void testResponse() { + ChannelEq eq; + check(eq.prepare(48000),"prepare"); + check(near(eq.responseDb(1000),0,1e-10),"off response flat"); + onBand(eq,2,1000,6,1); + check(near(eq.responseDb(1000),6,0.07),"PEQ +6 dB center"); + check(std::abs(eq.responseDb(30))<1,"bell does not affect DC region much"); + onBand(eq,1,160,5,1); + check(eq.responseDb(30)>4,"low shelf +5dB low frequency"); + onBand(eq,6,8000,-5,1); + check(eq.responseDb(15000)<-3,"high shelf attenuates high frequencies"); + ChannelEq cuts; + check(cuts.prepare(48000),"prepare cuts"); + onBand(cuts,0,100,0,.707f,Slope::db12); + const double hpf12=cuts.responseDb(25); + check(hpf12<-22 && hpf12>-29,"HPF 12 dB/oct falloff"); + onBand(cuts,0,100,0,.707f,Slope::db24); + check(cuts.responseDb(25)::infinity(), + std::numeric_limits::quiet_NaN()}) { + auto b=base;b.enabled=true;b.frequencyHz=invalid; + check(!eq.setBand(3,b),"invalid frequency rejected"); + } + auto b=base;b.enabled=true;b.gainDb=21.f; + check(!eq.setBand(3,b),"invalid gain rejected"); + b=base;b.enabled=true;b.q=0.0f; + check(!eq.setBand(3,b),"invalid q rejected"); + b=base;b.enabled=true;b.slope=static_cast(99); + check(!eq.setBand(3,b),"invalid slope rejected"); + check(!eq.setBand(8,base),"invalid slot rejected"); + check(eq.activeBands()==0,"failed writes leave existing state unchanged"); + onBand(eq,2,1000,9); + runUntilSettled(eq); + const auto before=eq.band(2); + auto wrong=before;wrong.frequencyHz=30000; + check(!eq.setBand(2,wrong),"failed update leaves active filter untouched"); + check(eq.band(2).frequencyHz==before.frequencyHz,"readback unchanged on rejected edit"); + check(eq.resetToFlat(),"reset all in one transition"); + runUntilSettled(eq); + check(eq.activeBands()==0 && near(eq.responseDb(1000),0,0.0001),"flat reset"); + check(!eq.transitioning(),"reset fade completed"); +} +static void testAudibleProcessingAndIndependence() { + ChannelEq eq; + check(eq.prepare(48000),"prepare"); + onBand(eq,2,1000,12,0.7f); + runUntilSettled(eq); + constexpr int n=128; + std::array left{}, right{}; + left[0]=1.0f; + eq.processStereo(left.data(),right.data(),left.size()); + check(left[0]>0.0f,"first sample delivered, no initial buffer/latency"); + check(std::all_of(right.begin(),right.end(),[](float v){return v==0.f;}),"no L->R leakage"); + ChannelEq mono; + check(mono.prepare(48000),"mono prepare"); + onBand(mono,2,1000,12,0.7f); + runUntilSettled(mono); + std::array x{};x[0]=1; + mono.processStereo(x.data(),x.data(),x.size()); // alias -> once only + check(near(x[0],left[0],1e-6),"alias-safe stereo uses mono path once"); + + ChannelEq gate; + check(gate.prepare(48000),"gate prepare"); + onBand(gate,1,160,6,1); + runUntilSettled(gate); + std::array held{};held.fill(1.f); + for(int i=0;i<16;++i) { held.fill(1.f); gate.processMono(held.data(),held.size()); } + check(held.back()>1.7,"actual LF shelf modifies PCM"); + const float previousWet = held.back(); + check(gate.resetToFlat(),"bypass request"); + held.fill(1.f); + gate.processMono(held.data(),held.size()); + check(std::abs(held[0]-previousWet)<0.1f,"start bypass transition follows last wet output"); + check(near(held.back(),1.0,1e-6),"finished bypass returns exact dry PCM"); + check(!gate.transitioning(),"bypass ramp completed"); +} +static void testFourteenIndependentChannels() { + // 10 CH + 4 AUX. Test per-channel filter/history isolation, not 14 EQs + // accidentally chained into a single PCM buffer. + std::array lanes{}; + for(auto& eq:lanes)check(eq.prepare(48000),"14 independent preparations"); + onBand(lanes[0],2,1000,9,0.7f); + runUntilSettled(lanes[0]); + onBand(lanes[13],0,120,0,0.707f,Slope::db24); + runUntilSettled(lanes[13]); + std::array,14> left{},right{}; + std::array reference1000{},reference60{}; + for(unsigned repeat=0;repeat<64;++repeat) { + for(std::size_t i=0;i(repeat*reference1000.size()+i)/48000.0; + reference1000[i]=0.1f*std::sin(6.283185307179586*t*1000.0); + reference60[i]=0.1f*std::sin(6.283185307179586*t*60.0); + } + for(std::size_t lane=0;lane(reference1000[i])*reference1000[i]; + boost1000+=static_cast(left[0][i])*left[0][i]; + dry60+=static_cast(reference60[i])*reference60[i]; + cut60+=static_cast(left[13][i])*left[13][i]; + } + check(boost1000>dry1000*4,"CH01 independent PEQ boost is audible PCM"); + check(cut60 l{},r{}; + l[0]=1.f; + noHeap.store(true,std::memory_order_release); + const bool accepted=eq.applyPreparedBand(packet); + if(accepted)eq.processStereo(l.data(),r.data(),l.size()); + noHeap.store(false,std::memory_order_release); + check(accepted,"audio owner applies precomputed packet"); + check(eq.activeBands()==1&&eq.band(4).gainDb==7.0f,"accepted DSP readback"); + check(l[0]>0.0f,"precomputed audio sample delivered"); + + ChannelEq changedRate; + check(changedRate.prepare(44100),"changed rate instance"); + check(!changedRate.applyPreparedBand(packet),"stale sample rate packet rejected"); + check(changedRate.activeBands()==0,"stale packet no partial application"); + ChannelEq::PreparedBandEdit invalidPacket=packet; + invalidPacket.sections=99; + check(!eq.applyPreparedBand(invalidPacket),"untrusted section count rejected"); + invalidPacket=packet; + invalidPacket.coefficients[0][0]=std::numeric_limits::quiet_NaN(); + // Force meaningful change so duplicate same-state shortcut cannot conceal + // a malformed coefficient payload. + invalidPacket.band.gainDb=8.0f; + check(!eq.applyPreparedBand(invalidPacket),"malformed filter coefficient rejected"); + check(eq.band(4).gainDb==7.0f,"rejected packet does not replace DSP state"); +} +static void testNoHeapAndVariableQuantum() { + ChannelEq eq; + check(eq.prepare(48000),"prepare"); + std::array l{},r{}; + for (auto count : {32u,64u,128u,512u}) { + l.fill(0.12f);r.fill(-0.07f); + auto hp=eq.band(0);hp.enabled=true;hp.frequencyHz=90+static_cast(count)/10.f; + hp.slope=Slope::db24; + ChannelEq::PreparedBandEdit prepared{}; + check(ChannelEq::prepareBandEdit(0,hp,48000,prepared),"control precomputes HPF"); + noHeap.store(true,std::memory_order_release); + const bool ok=eq.applyPreparedBand(prepared); + if(ok)eq.processStereo(l.data(),r.data(),count); + noHeap.store(false,std::memory_order_release); + check(ok,"parameter writes without allocation"); + check(std::isfinite(l[0])&&std::isfinite(l[count-1])&& + std::isfinite(r[count-1]),"variable quantum finite stereo"); + } +} +int main() { + testCatalogAndDefault(); + testResponse(); + testValidationAndReset(); + testAudibleProcessingAndIndependence(); + testPrecomputedControlToAudioBoundary(); + testNoHeapAndVariableQuantum(); + testFourteenIndependentChannels(); + std::puts("PASS: ArSonMix built-in 8-slot native Channel EQ; no ArSonEQ/VST3 dependency"); +} diff --git a/tests/builtin_eq_gui_contract_test.mjs b/tests/builtin_eq_gui_contract_test.mjs new file mode 100644 index 000000000..bcad698fe --- /dev/null +++ b/tests/builtin_eq_gui_contract_test.mjs @@ -0,0 +1,67 @@ +// The built-in EQ editor is an independent component inside the ONE +// approved ArSonMix /preview/ renderer. No duplicate audio or route UI. +import fs from 'node:fs'; +import assert from 'node:assert/strict'; +const html=fs.readFileSync('site/preview-v2/index.html','utf8'); +const assembler=fs.readFileSync('scripts/build_pages.py','utf8'); +const component=fs.readFileSync('scripts/compose_builtin_eq.py','utf8'); +const js=fs.readFileSync('site/preview-v2/assets/mixer-builtin-eq.js','utf8'); +const css=fs.readFileSync('site/preview-v2/assets/mixer-fx-rack.css','utf8'); +const native=fs.readFileSync('web/approved-native-bridge.js','utf8'); +assert.ok(assembler.includes('compose_builtin_eq(canonical_html)')); +assert.ok(component.includes('assets/mixer-builtin-eq.js')); +assert.ok(!html.includes('assets/mixer-builtin-eq.js'), 'V28 source HTML stays byte-frozen'); +assert.ok(js.includes('data-action="openBuiltinEq"'), 'Only the rack insert opens editor'); +assert.ok(!component.includes('mx-eq-open'), 'No redundant header EQ popup launcher'); +assert.ok(component.includes('insertChosenBuiltinEq') && + component.includes('PICKER_ENTER_HOOK'), 'Picker click and Enter use same insert workflow'); +assert.ok(component.includes('BUILT-IN FX')&&component.includes('VST3 PLUGINS')); +assert.ok(component.includes('RACK_ROWS_HOOK')&&component.includes('PICKER_CLICK_HOOK')); +assert.ok(js.includes('slotMarkup(track')&&js.includes('builtinEqSetGate')); +assert.ok(js.includes('lastGraphEqSweep')&&js.includes('otherTrack'), + 'Reproject actual native ChannelId EQ state after structural graph revision'); +const main=fs.readFileSync('src/Main.cpp','utf8'); +const publisher=fs.readFileSync('engine/core/DynamicNativeSessionPublisher.h','utf8'); +assert.ok(publisher.includes('if(fx.builtInEq) {') && + publisher.indexOf('if(fx.builtInEq) {') < + publisher.indexOf('else if(prior && prior->builtInEq)'), + 'Show V5 supplied EQ must win over a prior native ChannelId graph'); +assert.ok(main.includes('if(sameSession&&!got)continue;') && + main.includes('currentRevision==pending.revision') && + !main.includes('now-pending.started<4000u'), + 'Never report a false timeout; invalidate outstanding EQ only on structural session loss'); +assert.ok(main.includes('captureAcceptedEq(')&& + main.includes('acceptedEqFromShow(')&& + main.includes('unsettledBuiltInEq()')&& + main.includes('EqRestores eqRestores'), + 'Show V5 must save accepted EQ, build fresh DSP on recall and fence pending ACK'); +const showSchema=fs.readFileSync('src/NativeShowSchema.h','utf8'); +assert.ok(showSchema.includes('schemaVersion",5')&& + showSchema.includes('encodeEq(')&&showSchema.includes('decodeEq('), + 'Native Show V5 must preserve all 8 bands; old V2-V4 decode to default off'); +assert.ok(component.includes('window.ArSonMixBuiltinEq?.open(t)')); +assert.match(native,/__ARMIX_BUILTIN_EQ_CHANNEL__/); +assert.match(js,/arMixBuiltinEqAck/); +assert.match(js,/arMixBuiltinEqSnapshot/); +assert.match(js,/DESIGN DEMO · NO AUDIO/); +assert.match(js,/snapshotReady/); +assert.ok(!['AudioContext','webkitAudioContext','createScriptProcessor','new Worker('].some(s=>js.includes(s)), 'Browser EQ must not own audio callback'); +assert.ok(css.includes('#mxBuiltinEq[hidden]')); +const eqBank=fs.readFileSync('engine/builtin_fx/ChannelEqBank.h','utf8'); +assert.ok(eqBank.includes('rackBypassed_[lane].load')&& + eqBank.includes('insertBypassed_[lane]||rackOff'), + 'FX header OFF must override native EQ PCM without losing insert preference'); +console.log('Built-in Parametric EQ DAW GUI contract: PASS (isolated from VST3 and alt mixer)'); + +assert.ok(!html.includes('assets/mixer-builtin-eq.css'), 'No second CSS cascade owner'); + +assert.ok(!js.includes('hz/48000'), 'Spectrum display must use accepted device sample rate'); +assert.ok(js.includes('compiledSections(displayBands)'), 'Coefficient design once per paint, not each frequency pixel'); +assert.ok(js.includes('arMixConsoleSnapshot'), 'Device/graph invalidation listener required'); +assert.ok(js.includes('s.deviceEpoch===epoch&&s.graphRevision===revision'), + 'Reject stale samples and stale graph revisions'); +assert.ok(js.includes('RELEASE TO REQUEST AUDIO CHANGE'), 'Drag must be preview-only until release'); +assert.ok(js.includes('BigInt(Date.now())'), 'Request IDs must survive a WebView restart without accidental replay'); + +// Verify real editor JS behavior, not just substring presence. +await import('./builtin_eq_interaction_test.mjs'); diff --git a/tests/builtin_eq_interaction_test.mjs b/tests/builtin_eq_interaction_test.mjs new file mode 100644 index 000000000..8d5db559f --- /dev/null +++ b/tests/builtin_eq_interaction_test.mjs @@ -0,0 +1,217 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Run the shipped browser EQ against a deterministic DOM/native event source. +// This checks control ACK behavior, NOT a physical sound-card FAT. +import assert from 'node:assert/strict'; +import vm from 'node:vm'; +import fs from 'node:fs'; +const source=fs.readFileSync('site/preview-v2/assets/mixer-builtin-eq.js','utf8'); +class Node { + constructor(tag) { + this.tagName=tag;this.children=[];this.dataset={};this.attributes={}; + this.className='';this.style={setProperty(){}};this.textContent=''; + this.listeners=new Map();this.hidden=false;this.disabled=false; + this.value='';this.isConnected=false; + this.classList={toggle:(name,on)=>{ + const parts=new Set(this.className.split(/\s+/).filter(Boolean)); + if(on)parts.add(name);else parts.delete(name); + this.className=[...parts].join(' '); + }}; + } + append(...nodes){for(const node of nodes)node.isConnected=true;this.children.push(...nodes);} + prepend(...nodes){for(const node of nodes)node.isConnected=true;this.children.unshift(...nodes);} + setAttribute(name,value){this.attributes[name]=String(value);} + getAttribute(name){return this.attributes[name];} + addEventListener(name,fn){ + const callbacks=this.listeners.get(name)||[]; + callbacks.push(fn);this.listeners.set(name,callbacks); + } + fire(name,props={}) { + const evt={target:this,button:0,pointerId:1,clientX:0,clientY:0, + preventDefault(){},stopPropagation(){},...props}; + for(const fn of this.listeners.get(name)||[])fn(evt); + } + querySelector(sel){ + const q=[...this.children]; + while(q.length){ + const n=q.shift(); + if(sel.startsWith('.')?n.className.split(/\s+/).includes(sel.slice(1)): + n.tagName===sel)return n; + q.unshift(...n.children); + } + return null; + } + closest(sel){return sel==='[data-slot]'&&this.dataset.slot!==undefined?this:null;} + getBoundingClientRect(){return {left:0,top:0,width:520,height:240};} + getContext(){ + const noop=()=>{}; + return Object.fromEntries(['setTransform','fillRect','beginPath','moveTo','lineTo', + 'stroke','fillText','closePath','fill','arc','setLineDash'].map(k=>[k,noop])); + } + setPointerCapture(){} + focus(){} +} +const defaults=()=>[80,160,250,500,1500,4500,9500,18000].map((hz,i)=>({ + enabled:false,frequencyHz:hz,gainDb:0,q:i>=2&&i<=5?1:0.70710678,slope:12 +})); +const snapshot=(epoch='9',revision='3',id='0',bands=defaults(),installed=true,bypassed=false)=>({ + schemaVersion:1,channelId:'101',deviceEpoch:epoch,graphRevision:revision, + sampleRate:44100,appliedRequestId:id,bands,installed,bypassed +}); +function start(native) { + const listeners=new Map(),sent=[]; + const backend={ + emitEvent(name,payload){sent.push({name,payload});}, + addEventListener(name,fn){ + const all=listeners.get(name)||[]; + all.push(fn);listeners.set(name,all); + } + }; + let epoch='9',revision='3'; + const window={devicePixelRatio:1,addEventListener(){}}; + if(native) { + window.__JUCE__={backend}; + window.__ARMIX_BUILTIN_EQ_CHANNEL__={ + resolve:ui=>ui===42?'101':null, + state:()=>({admitted:true,device:{epoch},graph:{revision,channels:[{id:'101'}]}}) + }; + } + const document={readyState:'complete',body:new Node('body'), + createElement:t=>new Node(t)}; + vm.runInNewContext(source,{window,document,Math,Number,String,BigInt,Date, + requestAnimationFrame:fn=>{fn();return 0;},cancelAnimationFrame(){}}, + {filename:'mixer-builtin-eq.js',timeout:1500}); + const dialog=document.body.querySelector('section'); + assert.ok(dialog); + const find=sel=>{ + const found=dialog.querySelector(sel); + assert.ok(found,'Missing editor element '+sel); + return found; + }; + return {window,backend,sent,dialog,find,fire(name,data){ + for(const fn of listeners.get(name)||[])fn(data); + },session(ep,rev){epoch=ep;revision=rev;}}; +} +const lastAction=h=>h.sent.filter(x=>x.name==='arMixAction').at(-1)?.payload; +{ + const h=start(false); + h.window.ArSonMixBuiltinEq.open({id:42,name:'Vocal',kind:'audio'}); + h.find('.mx-eq-switch').fire('click'); + const title=h.find('.mx-eq-top'); + title.fire('pointerdown',{pointerId:11,clientX:250,clientY:160}); + title.fire('pointermove',{pointerId:11,clientX:290,clientY:195}); + title.fire('pointerup',{pointerId:11}); + assert.equal(h.dialog.style.transform,'none'); + assert.equal(h.dialog.style.left,'40px'); + assert.equal(h.dialog.style.top,'35px'); + assert.equal(h.sent.length,0,'Static Pages EQ must never issue a PCM command'); + assert.match(h.find('.mx-eq-status').textContent,/NO AUDIO/); +} +{ + const h=start(true),editor=h.window.ArSonMixBuiltinEq; + editor.open({id:42,name:'Mic 1',kind:'audio'}); + assert.equal(lastAction(h).action,'builtinEqSnapshot'); + assert.equal(lastAction(h).channelId,'101'); + const power=h.find('.mx-eq-switch'); + assert.equal(power.disabled,true,'Wait for authoritative native EQ readback'); + h.fire('arMixBuiltinEqSnapshot',snapshot()); + assert.equal(power.disabled,false); + h.sent.length=0; + power.fire('click'); + const command=lastAction(h); + assert.equal(command.action,'builtinEqSetBand'); + assert.equal(command.channelId,'101'); + assert.equal(command.deviceEpoch,'9'); + assert.equal(command.graphRevision,'3'); + assert.equal(command.slot,2); + assert.equal(command.band.enabled,true); + assert.match(command.requestId,/^[0-9]+$/); + assert.equal(power.getAttribute('aria-pressed'),'false','QUEUED is not applied'); + h.fire('arMixBuiltinEqQueue',{requestId:command.requestId,channelId:'101',status:'QUEUED'}); + h.fire('arMixBuiltinEqAck',{requestId:command.requestId,channelId:'101', + deviceEpoch:'9',graphRevision:'3',status:'APPLIED'}); + assert.equal(power.getAttribute('aria-pressed'),'false','ACK alone is not readback'); + h.fire('arMixBuiltinEqSnapshot',snapshot('9','3','0')); + assert.equal(power.getAttribute('aria-pressed'),'false','Old readback must not win'); + const applied=defaults();applied[2].enabled=true; + h.fire('arMixBuiltinEqSnapshot',snapshot('9','3',command.requestId,applied)); + assert.equal(power.getAttribute('aria-pressed'),'true','Only accepted PCM readback paints ON'); + h.fire('arMixBuiltinEqSnapshot',snapshot('9','2','123',defaults())); + assert.equal(power.getAttribute('aria-pressed'),'true','Stale graph cannot mutate UI'); + h.fire('arMixConsoleSnapshot',{admitted:true,device:{epoch:'10'}, + graph:{revision:'3',channels:[{id:'101'}]}}); + assert.equal(power.disabled,true,'Hotplug must revoke old EQ control'); + h.session('10','4'); + editor.open({id:42,name:'Mic 1',kind:'audio'}); + h.fire('arMixBuiltinEqSnapshot',snapshot('10','4')); + const canvas=h.find('canvas'); + const x=28+Math.log(250/20)/Math.log(1000)*(520-58); + h.sent.length=0; + canvas.fire('pointerdown',{pointerId:8,clientX:x,clientY:120}); + canvas.fire('pointermove',{pointerId:8,clientX:x+50,clientY:91}); + assert.equal(h.sent.length,0,'Pointer motion is a PREVIEW, not new DSP state'); + canvas.fire('pointerup',{pointerId:8,clientX:x+50,clientY:91}); + const drag=lastAction(h); + assert.equal(h.sent.length,1,'Release issues exactly one intent'); + assert.equal(drag.band.enabled,true); + assert.ok(drag.band.frequencyHz>250); + assert.equal(power.getAttribute('aria-pressed'),'false','Drag UI stays accepted-only'); +} +{ + const h=start(true),t={id:42,name:'Mic 1',kind:'audio'}; + const installed=h.window.ArSonMixBuiltinEq.insert(t); + assert.equal(installed,true); + assert.equal(h.dialog.hidden,true,'Picker insert does not open a blocking editor'); + assert.match(h.window.ArSonMixBuiltinEq.slotMarkup(t,()=>''),/APPLYING/); + const add=lastAction(h); + assert.equal(add.action,'builtinEqSetGate'); + assert.equal(add.installed,true); + assert.match(h.window.ArSonMixBuiltinEq.slotMarkup(t,()=>''),/data-builtin-eq="pending"/, + 'Provisional label only, never claim accepted native FX before AUDIO ACK'); + h.fire('arMixBuiltinEqQueue',{requestId:add.requestId,channelId:'101',status:'QUEUED'}); + h.fire('arMixBuiltinEqAck',{requestId:add.requestId,channelId:'101', + deviceEpoch:'9',graphRevision:'3',status:'APPLIED'}); + assert.match(h.window.ArSonMixBuiltinEq.slotMarkup(t,()=>''),/data-builtin-eq="pending"/, + 'AUDIO ACK alone must retain provisional row until producer snapshot'); + h.fire('arMixBuiltinEqSnapshot',snapshot('9','3',add.requestId)); + assert.match(h.window.ArSonMixBuiltinEq.slotMarkup(t,()=>''),/Parametric EQ/); + h.window.ArSonMixBuiltinEq.open(t); + assert.equal(h.dialog.hidden,false,'Clicking accepted rack row opens editor'); + h.window.ArSonMixBuiltinEq.power(t); + const bypass=lastAction(h); + assert.equal(bypass.action,'builtinEqSetGate');assert.equal(bypass.bypassed,true); + h.fire('arMixBuiltinEqAck',{requestId:bypass.requestId,channelId:'101', + deviceEpoch:'9',graphRevision:'3',status:'APPLIED'}); + h.fire('arMixBuiltinEqSnapshot',snapshot('9','3',bypass.requestId,defaults(),true,true)); + assert.match(h.window.ArSonMixBuiltinEq.slotMarkup(t,()=>''),/is-bypassed/); + h.window.ArSonMixBuiltinEq.remove(t); + const del=lastAction(h); + assert.equal(del.installed,false); + h.fire('arMixBuiltinEqAck',{requestId:del.requestId,channelId:'101', + deviceEpoch:'9',graphRevision:'3',status:'APPLIED'}); + h.fire('arMixBuiltinEqSnapshot',snapshot('9','3',del.requestId,defaults(),false,false)); + assert.equal(h.window.ArSonMixBuiltinEq.slotMarkup(t,()=>''),''); +} +{ + const h=start(true),track={id:42,name:'Vocal',kind:'audio',fxOn:true}; + let paints=0; + h.window.__ARMIX_BUILTIN_EQ_FIND_CHANNEL__=id=>id==='101'?track:null; + h.window.__ARMIX_BUILTIN_EQ_REFRESH__=()=>{paints++;}; + h.fire('arMixConsoleSnapshot',{admitted:true,device:{epoch:'9'}, + graph:{revision:'3',channels:[{id:'101'}]}}); + assert.equal(lastAction(h)?.action,'builtinEqSnapshot', + 'Accepted graph must requery exact ChannelId EQ readback'); + h.fire('arMixBuiltinEqSnapshot',snapshot('9','3','0',defaults(),true,false)); + assert.match(h.window.ArSonMixBuiltinEq.slotMarkup(track,()=>''),/Parametric EQ/, + 'Unopened editor still restores authoritative rack presence'); + assert.ok(paints>0); + h.session('10','4'); + assert.equal(h.window.ArSonMixBuiltinEq.slotMarkup(track,()=>''),'', + 'Device/graph change revokes stale EQ rack state'); + h.fire('arMixConsoleSnapshot',{admitted:true,device:{epoch:'10'}, + graph:{revision:'4',channels:[{id:'101'}]}}); + assert.equal(lastAction(h)?.action,'builtinEqSnapshot'); + h.fire('arMixBuiltinEqSnapshot',snapshot('10','4','0',defaults(),false,false)); + assert.equal(h.window.ArSonMixBuiltinEq.slotMarkup(track,()=>''),'', + 'New session flat EQ does not borrow prior device state'); +} +console.log('PASS: Built-in EQ insert/bypass/remove after native ACK + readback; no fake PCM'); \ No newline at end of file diff --git a/tests/live_channel_fx_graph_test.cpp b/tests/live_channel_fx_graph_test.cpp index 515c7481c..3aef071fd 100644 --- a/tests/live_channel_fx_graph_test.cpp +++ b/tests/live_channel_fx_graph_test.cpp @@ -178,7 +178,18 @@ static void verifyUniversalChannelIdFxLeaseAndLivePcm() { auto second=newFx(1.25f,"ch11-second-vst3"); assert(Bank::appendOwned(epoch,3,bank,ch11,ProcessingFormat::mono, second,expanded)==Bank::Fault::none); + // Rack OFF applies to the new plugin too; old per-plugin OFF remains + // untouched and native append carries the same authoritative override. + assert(bank.setRackBypass(epoch,2,ch11,true)); + assert(bank.rackBypassed(ch11)); assert(expanded.insertCount(ch11)==2); + // expanded was already created before the OFF gesture. Its revision + // holds the same shared rack gate, so it observes the control live. + assert(expanded.rackBypassed(ch11)); + assert(!expanded.setRackBypass(epoch,2,ch11,false)); // stale version + assert(expanded.setRackBypass(epoch,3,ch11,false)); + assert(!bank.rackBypassed(ch11)); + assert(!expanded.rackBypassed(ch11)); assert(expanded.insertCount(ch1)==bank.insertCount(ch1)); assert((*expanded.ownerForControl(ch11,0))->instanceId== (*bank.ownerForControl(ch11,0))->instanceId); @@ -1874,6 +1885,152 @@ static void verifyChannelIdGroupPreservesHostedFx() { live.unpublish();live.pollRetirement(); } + +static void verifyBuiltInEqRealPcmHook() { + constexpr std::array physicalPorts{2,5}; + ChannelRoutingConfig config; + config.stripsAndMaster.strips[0]={SourceMode::mono,2,-1,1.f,0.f,false,false}; + SendRequest sends; + PreparedRenderGraph plan;RenderError error; + assert(PreparedRenderGraph::compile(config,physicalPorts,sends,plan,error)); + auto wet=std::make_unique(plan,128,128); + auto dry=std::make_unique(plan,128,128); + assert(wet->prepareBuiltInEq(48000)&&dry->prepareBuiltInEq(48000)); + armix::builtin_fx::Band b{}; + b.enabled=true;b.frequencyHz=1000;b.gainDb=9;b.q=1; + assert(!wet->queueBuiltInEqEdit(0,2,b,0,7,2)); + assert(wet->queueBuiltInEqEdit(0,2,b,101,7,2)); + // Insertion is a separate ACK-backed AUDIO command, not implicit in edits. + assert(wet->queueBuiltInEqGate(0,true,false,102,7,2)); + std::array pcm{},silent{},wl{},wr{},dl{},dr{}; + const float* pins[]{pcm.data(),silent.data()}; + double dryPower=0,wetPower=0; + for(int block=0;block<64;++block) { + for(int i=0;i<128;++i) { + pcm[static_cast(i)]=static_cast( + .1*std::sin(6.283185307179586*1000*(block*128+i)/48000.0)); + } + const auto before=heapCalls.load(std::memory_order_relaxed); + assert(wet->process(pins,2,wl.data(),wr.data(),128)); + assert(dry->process(pins,2,dl.data(),dr.data(),128)); + assert(heapCalls.load(std::memory_order_relaxed)==before); + if(block==0) { + LiveChannelFxGraph::BuiltInEqAck ack{}; + assert(wet->pollBuiltInEqAck(0,ack)); + assert(ack.applied&&ack.requestId==101&&ack.deviceEpoch==7&& + ack.graphRevision==2&&ack.slot==2&&!ack.gate); + } + if(block==4) { + LiveChannelFxGraph::BuiltInEqAck ack{}; + assert(wet->pollBuiltInEqAck(0,ack)); + assert(ack.applied&&ack.gate&&ack.installed&&!ack.bypassed&& + ack.requestId==102&&ack.deviceEpoch==7&&ack.graphRevision==2); + } + if(block>=48)for(int i=0;i<128;++i) { + dryPower+=dl[static_cast(i)]*dl[static_cast(i)]; + wetPower+=wl[static_cast(i)]*wl[static_cast(i)]; + } + } + assert(dryPower>0.001&&wetPower>dryPower*4); +} + + +static void verifyBuiltInEqNativeChannelIdAndRevisionFence() { + DynamicChannelRoster roster; + std::array adds{}; + adds[0].kind=ChannelEdit::Kind::add;adds[0].role=ChannelRole::input; + adds[0].position=0;adds[0].format=ProcessingFormat::mono; + adds[1].kind=ChannelEdit::Kind::add;adds[1].role=ChannelRole::main; + adds[1].position=1;adds[1].format=ProcessingFormat::stereo; + const auto made=roster.edit(0,adds); + assert(made.ok() && made.createdIds.size()==2); + const auto ch=made.createdIds[0],main=made.createdIds[1]; + ChannelEdit link; + link.kind=ChannelEdit::Kind::addSendReference; + link.id=ch;link.target=main;link.value=1.f;link.primaryOutput=true; + assert(roster.edit(roster.revision(),std::span(&link,1)).ok()); + DynamicGraphRequest req; + req.physicalInputs=1;req.maxFrames=128;req.sources={{ch,0,-1,false}}; + auto eq=std::make_shared(); + assert(eq->prepare(48000)); + DynamicNativeSessionPublisher::FxPlan plan; + plan.builtInEq=eq;plan.builtInEqIds[0]=ch; + DynamicNativeSessionPublisher native; + assert(native.commit(roster,req,0,9,9,true,plan).ok()); + armix::builtin_fx::Band b{}; + b.enabled=true;b.frequencyHz=1000;b.gainDb=9;b.q=1.f; + assert(!native.queueBuiltInEqEdit(9,1,main,2,b,101)); + assert(native.queueBuiltInEqEdit(9,1,ch,2,b,101)); + assert(!native.queueBuiltInEqGate(9,1,main,true,false,102)); // wrong ChannelId + assert(native.queueBuiltInEqGate(9,1,ch,true,false,102)); + std::array pcm{},left{},right{}; + const float* pins[]{pcm.data()}; + auto noFx=[](ChannelId,float*,float*,int) noexcept {}; + double power=0; + for(int block=0;block<64;++block) { + for(int i=0;i<128;++i) + pcm[static_cast(i)]=static_cast( + .1*std::sin(6.283185307179586*1000*(block*128+i)/48000.0)); + const auto before=heapCalls.load(std::memory_order_relaxed); + assert(native.render(9,pins,1,left.data(),right.data(),128,false,noFx)); + assert(heapCalls.load(std::memory_order_relaxed)==before); + if(block==0) { + armix::builtin_fx::ChannelEqBank::Ack ack{}; + assert(native.pollBuiltInEqAck(9,1,ch,ack)); + assert(ack.applied&&ack.requestId==101&&ack.slot==2&&!ack.gate); + } + if(block==4) { + armix::builtin_fx::ChannelEqBank::Ack ack{}; + assert(native.pollBuiltInEqAck(9,1,ch,ack)); + assert(ack.applied&&ack.gate&&ack.installed&&ack.requestId==102); + } + if(block>=48)for(float y:left)power+=y*y; + } + // Mono input uses equal-power route; 9 dB bell must boost 1 kHz + // regardless of whether a native VST owner is present. + assert(power>1.0); + // Native publisher revision swaps retain the ONE EQ owner and history. + assert(native.commit(roster,req,1,9,9,true).ok()); + assert(native.queueBuiltInEqEdit(9,2,ch,2,b,103)); + assert(native.render(9,pins,1,left.data(),right.data(),128,false,noFx)); + armix::builtin_fx::ChannelEqBank::Ack ack{}; + assert(native.pollBuiltInEqAck(9,2,ch,ack)&&ack.applied&&ack.requestId==103); + + // Show V5 recall replaces the DSP bank even when the same ChannelId and + // epoch already have an admitted native graph. The old wet bank must NOT + // overwrite fresh offline-restored bands during the revision-3 commit. + auto restored=std::make_shared(); + assert(restored->prepare(48000)); + auto cut=b;cut.gainDb=-9.f; + assert(restored->setBandOffline(0,2,cut)); + assert(restored->setGateOffline(0,true,false)); + DynamicNativeSessionPublisher::FxPlan showPlan; + showPlan.builtInEq=restored;showPlan.builtInEqIds[0]=ch; + assert(native.commit(roster,req,2,9,9,true,showPlan).ok()); + assert(!native.queueBuiltInEqEdit(9,2,ch,2,b,104)); // superseded graph + double recalledPower=0; + for(int block=0;block<64;++block) { + for(int i=0;i<128;++i) + pcm[static_cast(i)]=static_cast( + .1*std::sin(6.283185307179586*1000*(block*128+i)/48000.0)); + const auto before=heapCalls.load(std::memory_order_relaxed); + assert(native.render(9,pins,1,left.data(),right.data(),128,false,noFx)); + assert(heapCalls.load(std::memory_order_relaxed)==before); + if(block>=48)for(float y:left)recalledPower+=y*y; + } + // 9 dB boost before recall must become a 9 dB CUT after recall, + // proving sound and accepted Show state can no longer diverge. + assert(recalledPower>0.001&&recalledPowerrackBypassed(0)); + assert(!native.setBuiltInEqRackBypass(9,2,ch,false)); // stale revision + assert(native.setBuiltInEqRackBypass(9,3,ch,false)); + assert(!restored->rackBypassed(0)); +} + int main(int argc,char** argv) { if(argc==2 && std::string(argv[1])=="--emit-console-s0-json") { verifyNativePuzzleV8FixtureAndWire(); @@ -2246,10 +2403,39 @@ int main(int argc,char** argv) { assert(heapCalls.load(std::memory_order_relaxed)==beforeNextProcess); assert(left[0]>.3f); } + // FX RACK POWER: one atomic master overrides effective processing, + // without destroying the ON/OFF preferences of individual inserts. + { + auto graph=makeGraph(2.f,3.f); + const auto token=graph->insertInstanceId(0); + assert(!graph->rackBypassed(0)); + assert(graph->setInsertBypass(0,0,token,true)); // individual OFF + assert(graph->insertBypassed(0,0)); + assert(graph->setRackBypass(0,true)); // master OFF + assert(graph->rackBypassed(0)&&graph->insertBypassed(0,0)); + assert(graph->setRackBypass(0,false)); // master ON + assert(!graph->rackBypassed(0)); + assert(graph->insertBypassed(0,0)); // stays OFF + assert(graph->setInsertBypass(0,0,token,false)); + assert(graph->setRackBypass(0,true)); + assert(graph->setRackBypass(0,false)); + assert(!graph->insertBypassed(0,0)); // returns to ON + assert(!graph->setRackBypass(-1,true)); + assert(!graph->setRackBypass(LiveChannelFxGraph::fxSlots,true)); + auto moved=makeGraph(1.f,1.f,false); + assert(graph->setRackBypass(0,true)); + assert(moved->reuse(0,*graph,"vst3-ch1-id")); + assert(moved->rackBypassed(0)); // graph retirement retains gate + assert(moved->insertBypassed(0,0)==graph->insertBypassed(0,0)); + assert(moved->setRackBypass(0,false)); + assert(!moved->insertBypassed(0,0)); // saved ON restored + } // Run M5 AFTER the legacy suite: older M4 tests use absolute global // GainFx::living/released counters as their own lifetime oracle. Running // M5 before them changes those historical baseline counts, not DSP. // M5 additionally asserts zero heap and valid vendor leases itself. + verifyBuiltInEqRealPcmHook(); + verifyBuiltInEqNativeChannelIdAndRevisionFence(); verifyUniversalChannelIdFxLeaseAndLivePcm(); verifyMU1LegacyM4FxFullMigrationAndMonitorPcm(); verifyOccupiedExternalCh1Owner(); diff --git a/tests/live_graph_contract_test.mjs b/tests/live_graph_contract_test.mjs index 6edcd12f1..b33a201fd 100644 --- a/tests/live_graph_contract_test.mjs +++ b/tests/live_graph_contract_test.mjs @@ -62,7 +62,10 @@ test('bypass is sample-smoothed by one original CH1 DSP owner for M4 and native 'native and M4 must share the original CH1 sample-accurate DSP owner'); const originalDSP=e.slice(start,legacy); const adapters=e.slice(legacy,end); - assert.match(originalDSP,/bypass\.request\(graph\.bypassFlags/); + assert.match(originalDSP,/bypass\.request\(graph\.rackBypassed\.load/); + assert.match(originalDSP,/graph\.bypassFlags\[physical\]\.load/); + assert.match(originalDSP,/\|\|/, "rack override must OR with individual insert bypass"); + assert.match(originalDSP,/slot\.processor->processBlock\(buffer,midi\)/); assert.match(originalDSP,/bypass\.transitioning\(\)/); assert.match(originalDSP,/graph\.dryScratch\.getWritePointer\(0\)/); diff --git a/tests/live_routing_ui_contract_test.mjs b/tests/live_routing_ui_contract_test.mjs index 454b8e8e9..a6224516d 100644 --- a/tests/live_routing_ui_contract_test.mjs +++ b/tests/live_routing_ui_contract_test.mjs @@ -295,7 +295,10 @@ test("G5E native Shows browse and hash-verified FX recall are worker-backed and assert.match(main,/nativeShowWorker_\.read\(/); assert.match(main,/result\.requestEpoch/); assert.match(main,/result\.requestRevision/); - assert.match(main,/applyDryRoutingLab\(\s*command,selections,&restores\)/); + assert.match(main,/applyDryRoutingLab\(\s*command,selections,&restores,&eqRestores\)/); + assert.match(main,/acceptedEqFromShow\(result.loaded,epochNow\)/); + assert.match(lab,/if\(eqRestores\)/); + assert.match(lab,/setBuiltInEqOffline\(lane,slot,band\)/); assert.match(main,/result\.loadedStates/); assert.match(main,/entry->uid!=ref\.uid/); assert.match(main,/safe->closePluginEditor\(\)/); diff --git a/tests/native_live_show_capture_test.cpp b/tests/native_live_show_capture_test.cpp index 7e2a250f4..51adffcb2 100644 --- a/tests/native_live_show_capture_test.cpp +++ b/tests/native_live_show_capture_test.cpp @@ -273,14 +273,14 @@ int main() { typedCaptured.strips[1].channelFormat==1); assert(typedCaptured.strips[2].busReturn && typedCaptured.strips[2].channelFormat==1); - const auto savedV4=Codec::encode(typedCaptured); - auto rawV4=juce::JSON::parse(savedV4); - assert(static_cast(rawV4.getProperty("schemaVersion",{}))==4); - SnapshotV2 restoredV4; - assert(Codec::decode(savedV4,restoredV4)); - assert(Codec::encode(restoredV4)==savedV4); + const auto savedV5=Codec::encode(typedCaptured); + auto rawV5=juce::JSON::parse(savedV5); + assert(static_cast(rawV5.getProperty("schemaVersion",{}))==5); + SnapshotV2 restoredV5; + assert(Codec::decode(savedV5,restoredV5)); + assert(Codec::encode(restoredV5)==savedV5); juce::var appliedV2; - const auto prepareTyped=NativeDryShowRecall::prepare(restoredV4, + const auto prepareTyped=NativeDryShowRecall::prepare(restoredV5, typedStatus,appliedV2); if(prepareTyped.isNotEmpty())std::cerr<<"MS1 typed recall failure: "< noPorts; set(disconnectedLab,"ports",juce::var(noPorts)); - assert(NativeDryShowRecall::prepare(restoredV4,disconnected, + assert(NativeDryShowRecall::prepare(restoredV5,disconnected, appliedV2).isNotEmpty()); assert(juce::JSON::toString(appliedV2,false)==originalV2); diff --git a/tests/native_show_schema_test.cpp b/tests/native_show_schema_test.cpp index ea22e74c1..678d4bbfb 100644 --- a/tests/native_show_schema_test.cpp +++ b/tests/native_show_schema_test.cpp @@ -50,6 +50,11 @@ int main() { snap.strips[0].inputA=3;snap.strips[0].inputB=5; // sparse physical pins snap.strips[0].pan=-0.32;snap.strips[0].fader=0.75; snap.strips[0].mute=true; + snap.strips[0].eq.installed=true; + snap.strips[0].eq.bands[2].enabled=true; + snap.strips[0].eq.bands[2].frequencyHz=1050.f; + snap.strips[0].eq.bands[2].gainDb=4.5f; + snap.strips[0].eq.bands[2].q=1.1f; snap.strips[0].fx.push_back({ "vault:test|987",987,juce::String::repeatedString("a",64),true }); @@ -58,6 +63,11 @@ int main() { // Four AUX return lanes exist IN ADDITION to all ten input strips. snap.aux[0].enabled=true;snap.aux[0].gain=0.82; snap.aux[0].fx.push_back({"vault:aux-reverb",1234,juce::String::repeatedString("b",64),false}); + snap.aux[0].eq.installed=true; + snap.aux[0].eq.bypassed=true; // bypass does NOT destroy EQ curves + snap.aux[0].eq.bands[0].enabled=true; + snap.aux[0].eq.bands[0].frequencyHz=110.f; + snap.aux[0].eq.bands[0].slope=armix::builtin_fx::Slope::db24; snap.aux[3].enabled=true;snap.aux[3].mute=true; snap.auxSends.push_back({0,0,true,0.25,-0.2}); snap.auxSends.push_back({6,3,false,0.75,0.3}); @@ -70,6 +80,30 @@ int main() { assert(loaded.strips[0].channelFormat==1 && loaded.strips[1].channelFormat==2); assert(loaded.strips[2].busReturn && loaded.strips[2].channelFormat==1); assert(loaded.strips[0].fx[0].stateSha256==juce::String::repeatedString("a",64)); + // V5 EQ is mandatory and fixed-width: never accept a partial 7-band + // preset that could silently change the realtime DSP routing. + auto missingEq=juce::JSON::parse(encoded); + auto* eqRows=missingEq.getProperty("strips",{}).getArray(); + eqRows->getReference(0).getDynamicObject()->removeProperty("builtinEq"); + SnapshotV2 invalidEq{}; + assert(!Codec::decode(juce::JSON::toString(missingEq),invalidEq)); + auto shortEq=juce::JSON::parse(encoded); + auto* eqStrips=shortEq.getProperty("strips",{}).getArray(); + auto* eqBands=eqStrips->getReference(0).getProperty( + "builtinEq",{}).getProperty("bands",{}).getArray(); + assert(eqBands&&eqBands->size()==8); + eqBands->removeLast(); + assert(!Codec::decode(juce::JSON::toString(shortEq),invalidEq)); + auto missingAuxEq=juce::JSON::parse(encoded); + auto* eqAux=missingAuxEq.getProperty("auxReturns",{}).getArray(); + eqAux->getReference(0).getDynamicObject()->removeProperty("builtinEq"); + assert(!Codec::decode(juce::JSON::toString(missingAuxEq),invalidEq)); + + assert(loaded.strips[0].eq.installed&&!loaded.strips[0].eq.bypassed); + assert(loaded.strips[0].eq.bands[2].enabled&& + loaded.strips[0].eq.bands[2].gainDb==4.5f); + assert(loaded.aux[0].eq.installed&&loaded.aux[0].eq.bypassed&& + loaded.aux[0].eq.bands[0].slope==armix::builtin_fx::Slope::db24); assert(loaded.strips[0].sends[0].preFader); assert(loaded.strips[6].solo&&!loaded.strips[6].toMaster); assert(loaded.masterMono); @@ -85,6 +119,17 @@ int main() { assert(loaded.strips[0].inputB==5); // failure leaves last good record broken=snap;broken.strips[0].inputB=3; assert(!Codec::decode(Codec::encode(broken),loaded)); + broken=snap;broken.strips[0].eq.bands[2].gainDb=21.f; + assert(!Codec::decode(Codec::encode(broken),loaded)); + broken=snap;broken.strips[0].eq.bands[2].q=0.f; + assert(!Codec::decode(Codec::encode(broken),loaded)); + broken=snap;broken.strips[0].eq.bands[0].slope= + static_cast(13); + assert(!Codec::decode(Codec::encode(broken),loaded)); + broken=snap;broken.aux[0].eq.installed=false; + assert(!Codec::decode(Codec::encode(broken),loaded)); + broken=snap;broken.strips[0].eq.installed=false; + assert(!Codec::decode(Codec::encode(broken),loaded)); broken=snap;broken.strips[0].pan=1.01; assert(!Codec::decode(Codec::encode(broken),loaded)); broken=snap;broken.strips[0].sends[0].destination=0; @@ -114,10 +159,29 @@ int main() { assert(!Codec::decode(juce::JSON::toString(invalidFormat),loaded)); assert(loaded.strips[0].channelFormat==1); + // V4 had the typed processing width and AUX, but NO native EQ record. + auto legacyV4=juce::JSON::parse(encoded); + auto* v4Rows=legacyV4.getProperty("strips",{}).getArray(); + auto* v4Aux=legacyV4.getProperty("auxReturns",{}).getArray(); + for(auto& row:*v4Rows)row.getDynamicObject()->removeProperty("builtinEq"); + for(auto& row:*v4Aux)row.getDynamicObject()->removeProperty("builtinEq"); + legacyV4.getDynamicObject()->setProperty("schemaVersion",4); + assert(Codec::decode(juce::JSON::toString(legacyV4),loaded)); + assert(!loaded.strips[0].eq.installed&&!loaded.aux[0].eq.installed); + // A false v4 marker must NOT silently discard enabled V5 EQ. + auto forgedV4=juce::JSON::parse(encoded); + forgedV4.getDynamicObject()->setProperty("schemaVersion",4); + assert(!Codec::decode(juce::JSON::toString(forgedV4),loaded)); + // Older V3 AUX-aware snapshots did not have processing format. auto legacyV3=juce::JSON::parse(encoded); auto* oldRows=legacyV3.getProperty("strips",{}).getArray(); - for(auto& row:*oldRows)row.getDynamicObject()->removeProperty("channelFormat"); + for(auto& row:*oldRows) { + row.getDynamicObject()->removeProperty("channelFormat"); + row.getDynamicObject()->removeProperty("builtinEq"); + } + auto* oldAuxV3=legacyV3.getProperty("auxReturns",{}).getArray(); + for(auto& row:*oldAuxV3)row.getDynamicObject()->removeProperty("builtinEq"); legacyV3.getDynamicObject()->setProperty("schemaVersion",3); assert(Codec::decode(juce::JSON::toString(legacyV3),loaded)); assert(loaded.strips[0].channelFormat==2); // native v1 physical stereo @@ -131,7 +195,10 @@ int main() { // no implicit BUS mono processing or hidden loss of a real V4 field. auto legacy=juce::JSON::parse(encoded); auto* oldRowsV2=legacy.getProperty("strips",{}).getArray(); - for(auto& row:*oldRowsV2)row.getDynamicObject()->removeProperty("channelFormat"); + for(auto& row:*oldRowsV2){ + row.getDynamicObject()->removeProperty("channelFormat"); + row.getDynamicObject()->removeProperty("builtinEq"); + } legacy.getDynamicObject()->removeProperty("auxReturns"); legacy.getDynamicObject()->removeProperty("auxSends"); legacy.getDynamicObject()->setProperty("schemaVersion",2); @@ -149,6 +216,6 @@ int main() { assert(!loaded.aux[0].enabled && loaded.auxSends.empty()); assert(loaded.name=="Soundcheck 01"); - std::cout << "PASS: bounded ShowV2/SnapshotV2 JSON round-trips, 10 INPUT + 4 AUX, PRE/POST, FX hashes, legacy V2 decode, rollback\n"; + std::cout << "PASS: Show snapshot V5 native EQ (10 CH + 4 AUX), legacy V2-V4 decode, VST3 hashes and rollback\n"; return 0; } diff --git a/tests/native_show_store_test.cpp b/tests/native_show_store_test.cpp index a591ad592..c0de04a5f 100644 --- a/tests/native_show_store_test.cpp +++ b/tests/native_show_store_test.cpp @@ -32,6 +32,11 @@ int main() { snap.createdMs=show.createdMs;snap.modifiedMs=show.modifiedMs; snap.strips[0].source=2; snap.strips[0].inputA=2;snap.strips[0].inputB=5; + snap.strips[0].eq.installed=true; + snap.strips[0].eq.bands[2].enabled=true; + snap.strips[0].eq.bands[2].frequencyHz=1000.f; + snap.strips[0].eq.bands[2].gainDb=6.f; + snap.strips[0].eq.bands[2].q=.9f; BinaryState blob; const char bytes[]={'a','r','m','i','x',0,1,2,'\0'}; blob.bytes.append(bytes,sizeof(bytes)); @@ -43,6 +48,10 @@ int main() { auxBlob.bytes.append(auxBytes,sizeof(auxBytes)); auxBlob.sha256=juce::SHA256(auxBlob.bytes).toHexString(); snap.aux[0].enabled=true;snap.aux[0].gain=0.6; + snap.aux[0].eq.installed=true;snap.aux[0].eq.bypassed=true; + snap.aux[0].eq.bands[0].enabled=true; + snap.aux[0].eq.bands[0].frequencyHz=120.f; + snap.aux[0].eq.bands[0].slope=armix::builtin_fx::Slope::db24; snap.aux[0].fx.push_back({"AuxReverb|202",202,auxBlob.sha256,false}); snap.auxSends.push_back({0,0,true,0.35,0.0}); std::vector snapshots={snap}; @@ -58,6 +67,13 @@ int main() { assert(loaded.channelSafes[3]); assert(retrieved.size()==1 && retrieved[0].strips[0].inputB==5); assert(retrieved[0].strips[0].fx[0].stateSha256==blob.sha256); + assert(retrieved[0].strips[0].eq.installed&& + retrieved[0].strips[0].eq.bands[2].enabled&& + retrieved[0].strips[0].eq.bands[2].gainDb==6.f); + assert(retrieved[0].aux[0].eq.installed&&retrieved[0].aux[0].eq.bypassed&& + retrieved[0].aux[0].eq.bands[0].frequencyHz==120.f&& + retrieved[0].aux[0].eq.bands[0].slope== + armix::builtin_fx::Slope::db24); // G5E2: the same immutable generation must deliver the exact vendor // binary bytes to the CONTROL thread before any candidate graph exists. ShowV2 fxShow;std::vector fxSnaps; diff --git a/tests/pages_contextual_buttons_smoke.py b/tests/pages_contextual_buttons_smoke.py index 6f93f27c8..f8f366799 100644 --- a/tests/pages_contextual_buttons_smoke.py +++ b/tests/pages_contextual_buttons_smoke.py @@ -96,7 +96,7 @@ def check_page(browser,path,label): assert page.locator('#tracks .strip[data-id="1"] .wire-node-out').count()==1 assert page.locator('#tracks .strip[data-id="1"] .wire-node-in').count()==1 assert not errors,(label,'page errors',errors) - if label=='png': + if label=='public': page.screenshot(path='pages-v6-contextual-buttons-1440.png') page.close() @@ -113,24 +113,24 @@ def main(): subprocess.run([sys.executable,str(ROOT/'scripts/build_pages.py'), '--out',str(dist),'--sha','v6-ci','--branch','main'], cwd=ROOT,check=True,capture_output=True,text=True) - for target in ('preview','preview-v2','preview-buttons'): - assets=dist/target/'assets' - assert (assets/OWNER).read_bytes()==(ROOT/'site/preview-v2/assets'/OWNER).read_bytes(),target - assert (assets/SCRIPT).read_bytes()==(ROOT/'site/preview-v2/assets'/SCRIPT).read_bytes(),target + # The one canonical Pages/JUCE output is /preview/. Historical + # source seeds are fixtures, NOT additional public HTML routes. + assets=dist/'preview/assets' + assert (assets/OWNER).read_bytes()==(ROOT/'site/preview-v2/assets'/OWNER).read_bytes() + assert (assets/SCRIPT).read_bytes()==(ROOT/'site/preview-v2/assets'/SCRIPT).read_bytes() png_src=ROOT/'site/preview-buttons/assets' - png_pub=dist/'preview-buttons/assets' + png_pub=assets for file in ('mixer-control-keys.css','mixer-control-keys.js','mute-solo-pfl-56x37.png'): assert (png_pub/file).read_bytes()==(png_src/file).read_bytes(),file with sync_playwright() as p: browser=p.chromium.launch(headless=True) for file,label in ( (CANON,'canonical'), - (dist/'preview/mixer.html','public'), - (dist/'preview-buttons/index.html','png') + (dist/'preview/index.html','public') ): check_page(browser,file,label) browser.close() - print('PASS V6 OTHER buttons: 3 routes, PNG protected, action release, native latches,') + print('PASS V6 OTHER buttons: approved /preview/ and source fixture, PNG protected,') print('micro geometry, fixed MAIN size, no pointer-focus or layout scroll') diff --git a/tests/pages_contextual_contrast_smoke.py b/tests/pages_contextual_contrast_smoke.py index d1bc627a1..bcf16681f 100644 --- a/tests/pages_contextual_contrast_smoke.py +++ b/tests/pages_contextual_contrast_smoke.py @@ -98,7 +98,7 @@ def verify(page,label,path): assert contrast("#f5f8ff","#405b7f")>=5.5 # The bank-changing arrow has already been exercised; CH 01 need not # remain rendered after moving to the next bank. - if label=="approved-png": + if label=="public": page.locator(".command-bar").screenshot(path="pages-v6-arrow-contrast-1680.png") def main(): @@ -115,15 +115,15 @@ def main(): check=True,cwd=ROOT,stdout=subprocess.PIPE,stderr=subprocess.PIPE) with sync_playwright() as p: browser=p.chromium.launch(headless=True) + # One actual public mixer; historical preview URLs redirect only. for path,label in ((PAGE,"canonical"), - (dst/"preview/mixer.html","published-mixer"), - (dst/"preview-buttons/index.html","approved-png")): + (dst/"preview/index.html","public")): page=browser.new_page(viewport={"width":1680,"height":900}) verify(page,label,path) page.close() browser.close() print("PASS arrow OFF/ON icon contrast, unchanged geometry, Route to Bus dark microcopy,") - print("WIRE linked/legacy semantic contrast, and PNG reference route 3/3") + print("WIRE linked/legacy semantic contrast, source and one public PNG route") if __name__=="__main__": diff --git a/tests/pages_m1_meter_gain_calibration_smoke.py b/tests/pages_m1_meter_gain_calibration_smoke.py index a34c63b23..560caec49 100644 --- a/tests/pages_m1_meter_gain_calibration_smoke.py +++ b/tests/pages_m1_meter_gain_calibration_smoke.py @@ -4,6 +4,8 @@ Use the real generated public /preview/ and canonical sources, never a mock. Check unit math, computed geometry, visual label rhythm, and click-to-preview. """ +import hashlib +import json import math import subprocess import sys @@ -199,25 +201,37 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), "--out",str(dist),"--sha","m1-calibrated","--branch","m1"], cwd=ROOT,check=True,capture_output=True,text=True) - published=dist/"preview/mixer.html" - assert published.read_bytes()==CANON.read_bytes(),"Published mixer source drift" - expected_ruler_keys={ - "mixer-fader-assembly.css":"css-owner-v27-fader-rollback-pre-v52-tail", - "mixer-meter-display.css":"css-owner-v27-meter-pruned", - } - for name,key in expected_ruler_keys.items(): - assert f"assets/{name}?v={key}" in published.read_text("utf-8"),( - "stale ruler cache URL",name,key) + published=dist/"preview/index.html" + # Stage D has one runtime CSSOM. The canonical source remains + # byte-immutable but the product intentionally composes PNG controls, + # built-in Channel EQ and other approved native UI additions. Verify + # every fader/meter source owner is carried by the content-addressed + # runtime instead of demanding obsolete individual link URLs. + meta=json.loads((dist/"preview/build.json").read_text("utf-8")) + cssmeta=meta["css_compilation"] + runtime=(dist/"preview/assets/arsonmix-approved-runtime.css").read_bytes() + digest=hashlib.sha256(runtime).hexdigest()[:16] + assert cssmeta["runtimeBundleCssSHA256"]==digest + assert cssmeta["runtimeStylesheetCount"]==1 + assert published.read_text("utf-8").count( + "assets/arsonmix-approved-runtime.css?sha="+digest)==1 for name in ("mixer-fader-assembly.css","mixer-meter-display.css"): - assert (dist/"preview/assets"/name).read_bytes()==(ASSETS/name).read_bytes(),name + assert ("BEGIN approved owner "+name).encode() in runtime,name + data=(dist/"preview/assets"/name).read_bytes() + assert cssmeta["shaByCssOwner"][name]==hashlib.sha256(data).hexdigest()[:16],name + assert (dist/"preview/assets/mixer-control-keys.css").read_bytes()==( + ROOT/"site/preview-buttons/assets/mixer-control-keys.css").read_bytes() + assert (dist/"preview/assets/mixer-wire-dots.css").read_bytes()==( + ASSETS/"mixer-wire-dots.css").read_bytes() with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) for html,label,width,height in ( (CANON,"canonical",1366,768), (CANON,"canonical",1680,900), (CANON,"canonical",1920,1080), + (published,"pages",1366,768), (published,"pages",1680,900), - (dist/"preview-buttons/index.html","png",1366,768)): + (published,"pages",1920,1080)): page=browser.new_page(viewport={"width":width,"height":height}) errors=[] page.on("pageerror",lambda exc:errors.append(str(exc))) @@ -233,7 +247,7 @@ def main(): page.close() browser.close() print("PASS M1: dBFS meter and gain rulers calibrated to physical travel; " - "preview demo displays real dBFS percentages, 3 densities × 3 sizes × 3 Pages routes") + "preview demo displays real dBFS percentages, 3 densities × 3 sizes × 1 public route") if __name__=="__main__": main() diff --git a/tests/pages_micro_fader_visual_v18_smoke.py b/tests/pages_micro_fader_visual_v18_smoke.py index cb7446100..08038e96f 100644 --- a/tests/pages_micro_fader_visual_v18_smoke.py +++ b/tests/pages_micro_fader_visual_v18_smoke.py @@ -88,7 +88,7 @@ def check(page,path,label): label,density,"printed scale numbers collide",tick) assert tick["value"]=="0",(label,density,"fader numeric value changed",tick) assert abs(tick["panHeight"]-40)<.6,(label,density,"PAN input hitbox moved",tick["panHeight"]) - if density=="comfort" and label=="png": + if density=="comfort" and label=="public": page.locator(channel+" .fader-section").screenshot(path="pages-v18-fader-scale-1680.png") page.locator(channel+" .fx-section").screenshot(path="pages-v18-fx-micro-1680.png") assert not errors,(label,errors) @@ -110,14 +110,15 @@ def main(): cwd=ROOT,check=True,capture_output=True,text=True) with sync_playwright() as playwright: browser=playwright.chromium.launch(headless=True) + # The approved PNG surface is /preview/index.html. The two + # legacy paths are redirects, not independent mixer renderers. for path,label in ((SOURCE,"canonical"), - (dist/"preview/mixer.html","public"), - (dist/"preview-buttons/index.html","png")): + (dist/"preview/index.html","public")): page=browser.new_page(viewport={"width":1680,"height":900},device_scale_factor=1) check(page,path,label) browser.close() print("PASS V18: Material delete+phase, 17px square buttons, calibrated rulers,") - print("no label overlaps across densities, PNG preserved, 3 real preview routes") + print("no label overlaps across densities, approved PNG in one public preview") if __name__=="__main__": main() diff --git a/tests/pages_png_buttons_wire_reconciliation_smoke.py b/tests/pages_png_buttons_wire_reconciliation_smoke.py index 036003f62..e0c449abf 100644 --- a/tests/pages_png_buttons_wire_reconciliation_smoke.py +++ b/tests/pages_png_buttons_wire_reconciliation_smoke.py @@ -37,27 +37,49 @@ def verify_bundle(dist): assert "url=../preview/" in (dist/"preview-buttons/index.html").read_text(encoding="utf-8") assert 'http-equiv="refresh"' in (dist/"preview/mixer.html").read_text(encoding="utf-8") - # Strip only the two deliberate fingerprinted CSS/JS URLs. Everything - # else, including the V46+ WIRE model and channel events, must be 1:1. - stripped=html + # The current approved assembler adds native EQ/Fx controls and Stage D + # combines 18 source-owned CSS stylesheets into one content-addressed + # runtime stylesheet. A removed per-owner CSS URL is intentional, NOT a + # missing hardware key. Verify source bytes, digest, and the exact owner + # inside the runtime CSS rather than restoring obsolete HTML parity. + revisions=meta["button_css_js_revisions"] for name in SPECIAL: - path="assets/"+name - original_url=re.search(re.escape(path)+r'(?:\?[^"\s>]+)?',original) - current_url=re.search(re.escape(path)+r'\?rev=([0-9a-f]{16})',stripped) - assert original_url and current_url,(name,"missing cache-safe URL") expected=hashlib.sha256((OWNER/name).read_bytes()).hexdigest()[:16] - assert current_url.group(1)==expected,(name,"wrong asset revision") - stripped=stripped[:current_url.start()]+original_url.group(0)+stripped[current_url.end():] + assert revisions.get(name)==expected,(name,"wrong button asset digest") assert (generated/"assets"/name).read_bytes()==(OWNER/name).read_bytes(),name - assert stripped==original,"User-approved button variant modified the real WIRE mixer" + assert f'assets/{SPECIAL[1]}?rev={revisions[SPECIAL[1]]}' in html, ( + "approved PNG control JS not versioned") + runtime="arsonmix-approved-runtime.css" + cssmeta=meta["css_compilation"] + csssha=cssmeta["runtimeBundleCssSHA256"] + assert re.fullmatch(r"[0-9a-f]{16}",csssha) + assert html.count(f'assets/{runtime}?sha={csssha}')==1, ( + "single compiled CSS owner not loaded exactly once") + compiled=(generated/"assets"/runtime).read_bytes() + assert hashlib.sha256(compiled).hexdigest()[:16]==csssha, ( + "compiled CSS runtime digest drift") + assert b"BEGIN approved owner mixer-control-keys.css" in compiled + assert b"BEGIN approved owner mixer-wire-dots.css" in compiled + assert cssmeta["runtimeStylesheetCount"]==1 + assert cssmeta["removedStylesheetRequests"]==17 - # Removing old snapshots makes every extra asset a current-source - # dependency, never a cloned V45 file frozen across future WIRE updates. + # Never publish a cloned mixer or extra asset. Only the generated runtime + # CSS is added; CSS source owners remain available for provenance. Stage C + # legitimately compiles ordinary CSS declarations, so demand byte parity + # of non-CSS assets and separately verify the two locked CSS owners. canonical={f.name for f in (REFERENCE/"assets").iterdir() if f.is_file()} published={f.name for f in (generated/"assets").iterdir() if f.is_file()} - assert published==canonical|{SPRITE},("asset set drift",published^canonical) + assert published==canonical|{SPRITE,runtime},("asset set drift",published^canonical) for name in canonical-set(SPECIAL): - assert (generated/"assets"/name).read_bytes()==(REFERENCE/"assets"/name).read_bytes(),name + if not name.endswith(".css"): + assert (generated/"assets"/name).read_bytes()==(REFERENCE/"assets"/name).read_bytes(),name + assert (generated/"assets/mixer-wire-dots.css").read_bytes()==( + REFERENCE/"assets/mixer-wire-dots.css").read_bytes() + assert (generated/"assets/mixer-control-keys.css").read_bytes()==( + OWNER/"mixer-control-keys.css").read_bytes() + # The independent single-preview publication contract checks the entire + # generated DOM and all 18 compiled CSS owners byte-for-byte. This test + # additionally exercises real browser control, geometry and WIRE state. png=(generated/"assets"/SPRITE).read_bytes() assert png==(ROOT/"site/preview-v34/assets"/SPRITE).read_bytes() @@ -150,7 +172,7 @@ def main(): cwd=ROOT,check=True,capture_output=True,text=True) verify_bundle(dist) verify_browser(dist) - print("PASS: approved PNG buttons track latest canonical WIRE, asset byte parity, 3 viewports, ON/OFF stable") + print("PASS: one Stage D runtime CSS, locked PNG/WIRE assets, 3 Chromium viewports, ON/OFF stable") if __name__=="__main__": main() diff --git a/tests/pages_wire_incoming_v43_smoke.py b/tests/pages_wire_incoming_v43_smoke.py index 8c6b3f33f..b5aa95574 100644 --- a/tests/pages_wire_incoming_v43_smoke.py +++ b/tests/pages_wire_incoming_v43_smoke.py @@ -1,13 +1,42 @@ #!/usr/bin/env python3 """V43: generated public /preview/ parity, persistent incoming cables, and physical socket impact.""" from pathlib import Path -import math,re,subprocess,sys,tempfile +import hashlib,json,math,re,subprocess,sys,tempfile from playwright.sync_api import sync_playwright ROOT=Path(__file__).resolve().parents[1] CANONICAL=ROOT/"site/preview-v2/index.html" WIRE_CSS=ROOT/"site/preview-v2/assets/mixer-wire-dots.css" + +def verify_approved_wire_bundle(dist, *, extra_owners=()): + """Prove one public /preview/ with the approved WIRE owners. + + The assembler legitimately adds EQ, PNG keys, rack controls, a profiler, + and one Stage D runtime CSS. Internal historical HTML is not public HTML. + The separate single-preview contract checks complete source-derived bytes. + """ + public=dist/"preview/index.html" + html=public.read_text("utf-8") + meta=json.loads((dist/"preview/build.json").read_text("utf-8")) + assert meta["kind"]=="APPROVED_SINGLE_GUI" and meta["live_audio"] is False + assert meta["wire_source_sha256"]==hashlib.sha256( + (ROOT/"site/preview-v2/index.html").read_bytes()).hexdigest() + assert "0 and r["height"]>0,r @@ -55,9 +84,21 @@ def main(): cwd=ROOT,capture_output=True,text=True) public=dst/"preview/index.html" shared=dst/"preview/assets/mixer-wire-dots.css" - assert "mixer-control-keys.css?rev=" in public.read_text("utf-8"),"Published /preview/ lost approved PNG hardware keys" + # Stage D deliberately replaces 18 CSS links with one content-addressed + # runtime stylesheet. Verify that the two locked physical component owners + # remain present and byte-exact, rather than requiring obsolete link URLs. + manifest=json.loads((dst/"preview/build.json").read_text("utf-8")) + assert re.fullmatch(r"[0-9a-f]{16}", + manifest["button_css_js_revisions"]["mixer-control-keys.css"]) + keys=dst/"preview/assets/mixer-control-keys.css" + assert keys.read_bytes()==(ROOT/"site/preview-buttons/assets/mixer-control-keys.css").read_bytes() assert shared.read_bytes()==WIRE_CSS.read_bytes(),"Approved /preview/ did not publish the effective WIRE CSS" - assert 'assets/mixer-wire-dots.css?v=v59-selected-wire-quiet' in public.read_text("utf-8") + published=public.read_text("utf-8") + runtime=dst/"preview/assets/arsonmix-approved-runtime.css" + assert 'href="assets/arsonmix-approved-runtime.css?sha=' in published + bundled=runtime.read_text("utf-8") + assert "BEGIN approved owner mixer-control-keys.css" in bundled + assert "BEGIN approved owner mixer-wire-dots.css" in bundled with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) for width in (1366,1680): diff --git a/tests/pages_wire_v44_finish_smoke.py b/tests/pages_wire_v44_finish_smoke.py index b06887855..d6314faa6 100644 --- a/tests/pages_wire_v44_finish_smoke.py +++ b/tests/pages_wire_v44_finish_smoke.py @@ -3,7 +3,7 @@ from pathlib import Path import subprocess,sys,tempfile from playwright.sync_api import sync_playwright -from pages_wire_incoming_v43_smoke import center, impact_peak +from pages_wire_incoming_v43_smoke import center, impact_peak, verify_approved_wire_bundle ROOT=Path(__file__).resolve().parents[1] SRC=ROOT/"site/preview-v2/index.html" @@ -20,10 +20,7 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), "--out",str(dst),"--sha","v44-ui-smoke","--branch","gui-v44"], cwd=ROOT,capture_output=True,text=True,check=True) - public=dst/"preview/mixer.html" - assert public.read_bytes()==SRC.read_bytes(),"published /preview/ differs from canonical GUI" - assert (dst/"preview/assets/mixer-wire-dots.css").read_bytes()==CSS.read_bytes(),"published WIRE style missing" - assert 'assets/mixer-wire-dots.css?v=v59-selected-wire-quiet' in public.read_text("utf-8") + public=verify_approved_wire_bundle(dst) with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) for width in (1366,1680): diff --git a/tests/pages_wire_v45_socket_layout_smoke.py b/tests/pages_wire_v45_socket_layout_smoke.py index 9c5f2773c..9ad666e11 100644 --- a/tests/pages_wire_v45_socket_layout_smoke.py +++ b/tests/pages_wire_v45_socket_layout_smoke.py @@ -6,7 +6,7 @@ from pathlib import Path import subprocess,sys,tempfile from playwright.sync_api import sync_playwright -from pages_wire_incoming_v43_smoke import center +from pages_wire_incoming_v43_smoke import center, verify_approved_wire_bundle ROOT=Path(__file__).resolve().parents[1] HTML=ROOT/"site/preview-v2/index.html" @@ -61,10 +61,7 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), "--out",str(dist),"--sha","v45-browser","--branch","v45"], cwd=ROOT,capture_output=True,text=True,check=True) - public=dist/"preview/mixer.html" - assert public.read_bytes()==HTML.read_bytes(),"Pages did not publish canonical V45 console" - assert (dist/"preview/assets/mixer-wire-dots.css").read_bytes()==STYLE.read_bytes(),"Pages lost WIRE CSS" - assert "assets/mixer-wire-dots.css?v=v59-selected-wire-quiet" in public.read_text("utf-8") + public=verify_approved_wire_bundle(dist) with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) for width in (1366,1680,1920): diff --git a/tests/pages_wire_v46_precision_smoke.py b/tests/pages_wire_v46_precision_smoke.py index 95a8f1e0d..3415e80b1 100644 --- a/tests/pages_wire_v46_precision_smoke.py +++ b/tests/pages_wire_v46_precision_smoke.py @@ -10,6 +10,7 @@ from pathlib import Path from playwright.sync_api import sync_playwright +from pages_wire_incoming_v43_smoke import verify_approved_wire_bundle ROOT=Path(__file__).resolve().parents[1] HTML=ROOT/"site/preview-v2/index.html" @@ -49,12 +50,10 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), "--out",str(dist),"--sha","v46-dot-anchors","--branch","v46"], cwd=ROOT,capture_output=True,text=True,check=True) - public=dist/"preview/mixer.html" - assert public.read_bytes()==HTML.read_bytes(),"published /preview/ HTML is stale" - assert (dist/"preview/assets/mixer-wire-dots.css").read_bytes()==CSS.read_bytes(),"public WIRE CSS differs" - assert "assets/mixer-wire-dots.css?v=v59-selected-wire-quiet" in public.read_text("utf-8") - assert (dist/"preview/assets/mixer-wire-out-align-v48.css").read_bytes()==(ROOT/"site/preview-v2/assets/mixer-wire-out-align-v48.css").read_bytes(), "V48 alignment stylesheet missing from /preview/" - assert "assets/mixer-wire-out-align-v48.css?v=out-center-v48" in public.read_text("utf-8") + # Stage C can prune redundant alignment declarations. Verify the compiled + # alignment owner and runtime digest, then exercise actual dot geometry. + public=verify_approved_wire_bundle( + dist,extra_owners=("mixer-wire-out-align-v48.css",)) with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) diff --git a/tests/preview_v2_v7_visual_smoke.py b/tests/preview_v2_v7_visual_smoke.py index 09f095a73..47c33ebfb 100644 --- a/tests/preview_v2_v7_visual_smoke.py +++ b/tests/preview_v2_v7_visual_smoke.py @@ -7,7 +7,7 @@ """ from __future__ import annotations from pathlib import Path -import subprocess, sys, re +import hashlib, json, subprocess, sys, re from playwright.sync_api import sync_playwright ROOT = Path(__file__).resolve().parents[1] @@ -298,13 +298,29 @@ def main(): assert PAGE.exists() and PUBLIC.exists(), (PAGE, PUBLIC) assembled=PUBLIC.read_text(encoding="utf-8") raw=PAGE.read_text(encoding="utf-8") + meta=json.loads((PUBLIC.parent/"build.json").read_text(encoding="utf-8")) + assert meta["kind"]=="APPROVED_SINGLE_GUI" + assert meta["wire_source_sha256"]==hashlib.sha256(raw.encode()).hexdigest() + # The approved assembler composes Channel EQ, a guarded rack header, + # an opt-in profiler and exactly ONE Stage D runtime CSS; this is no + # longer byte-identical to the raw internal historical source page. + cssmeta=meta["css_compilation"] + runtime=(PUBLIC.parent/"assets/arsonmix-approved-runtime.css").read_bytes() + digest=hashlib.sha256(runtime).hexdigest()[:16] + assert cssmeta["runtimeBundleCssSHA256"]==digest + assert cssmeta["runtimeStylesheetCount"]==1 + assert assembled.count("assets/arsonmix-approved-runtime.css?sha="+digest)==1 + assert b"BEGIN approved owner mixer-wire-dots.css" in runtime for asset in ("mixer-control-keys.css","mixer-control-keys.js"): - token="assets/"+asset - source_link=re.search(re.escape(token)+r'(?:\?[^"\s>]+)?',raw) - assert source_link,(asset,"source link missing") - assembled=re.sub(re.escape(token)+r'\?rev=[0-9a-f]{16}', - lambda _: source_link.group(0),assembled) - assert assembled==raw, "Public /preview/ must preserve every GUI interaction and differ only in approved PNG key URLs" + expected=hashlib.sha256( + (ROOT/"site/preview-buttons/assets"/asset).read_bytes()).hexdigest()[:16] + assert meta["button_css_js_revisions"][asset]==expected,asset + assert (PUBLIC.parent/"assets"/asset).read_bytes()==( + ROOT/"site/preview-buttons/assets"/asset).read_bytes(),asset + assert "arsonmix-approved-runtime.css" in assembled + # Independent single_preview_publication_contract_test.py already + # proves the entire assembled HTML, 18 compiled CSS owners and PNG + # bytes. This test retains real visual/workflow browser acceptance. assert 'http-equiv="refresh"' in (PUBLIC.parent/"mixer.html").read_text(encoding="utf-8") count = 0 with sync_playwright() as playwright: diff --git a/tests/single_preview_publication_contract_test.py b/tests/single_preview_publication_contract_test.py index ea2397a95..8630926fb 100644 --- a/tests/single_preview_publication_contract_test.py +++ b/tests/single_preview_publication_contract_test.py @@ -3,6 +3,8 @@ import json, re, sys, hashlib 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 compose_builtin_eq import compose_builtin_eq, SCRIPT, CLICK_AFTER +from approved_fx_rack_power import apply_authoritative_fx_power ROOT=Path(__file__).resolve().parents[1] DST=Path(sys.argv[1]).resolve() if len(sys.argv)>1 else ROOT/'dist-pages' gui=DST/'preview' @@ -17,7 +19,11 @@ def require(ok,why): require('console-body' in html and RUNTIME_CSS in html and 'mixer-control-keys.js' in html,'not the actual approved console') # The only compiled DOM changes are two hashed approved PNG links and the dormant profiling script. revisions=build.get('button_css_js_revisions',{}) -expected=source +expected=compose_builtin_eq(source) +require(expected.count(SCRIPT)==1 and expected.count(CLICK_AFTER)==1, + 'one builtin EQ editor, one accepted FX header action') +require(source.count('openBuiltinEq')==0, + 'historical internal source must remain frozen and EQ assembled only once') for name in ('mixer-control-keys.css','mixer-control-keys.js'): require(name in revisions and re.fullmatch('[0-9a-f]{16}',revisions[name]) is not None,'missing versioned approved key') token='assets/'+name @@ -36,6 +42,7 @@ def require(ok,why): require((gui/'assets/gui-perf-probe.js').read_bytes()== (ROOT/'site/preview-v2/assets/gui-perf-probe.js').read_bytes(), 'opt-in performance probe was not copied byte-for-byte') +expected=apply_authoritative_fx_power(expected) # 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 # hash; never approve an extra stylesheet, different owner or PNG mutation. @@ -82,7 +89,7 @@ def css_rewrite(match): shipped=list(LINK.finditer(html)) 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') +require(html==expected,'rendered /preview/ DOM differs from approved single-owner assembler + built-in EQ + PNG buttons + runtime CSS + profiler') 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/mute-solo-pfl-56x37.png').read_bytes()==(ROOT/'site/preview-buttons/assets/mute-solo-pfl-56x37.png').read_bytes(),'approved PNG sprite mismatch') diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 212cd2d9f..a47081009 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -20,6 +20,7 @@ // B-stage: attached-node-only meter caches; a structural render invalidates // them atomically. Never retain detached WebView2 strips or stale channel IDs. const meterElements = new Map(); + let nativeFxPowerSerial=0, pendingNativeFxPower=null; let controller = null; const status = message => { lastNativeError = message; @@ -82,6 +83,8 @@ t.mute=ch.controls.mute; t.solo=ch.controls.solo; t.selected=previous.get(t.id)?.selected || false; + if(typeof ch.fxRackBypassed==="boolean") + t.fxOn=!ch.fxRackBypassed; // ONLY actual native rack readback if (Array.isArray(ch.inserts)) { t.fx=Array.from({length:8},(_,i)=>ch.inserts[i]?.name||"None"); t.slotBypass=Array.from({length:8},(_,i)=>Boolean(ch.inserts[i]?.bypassed)); @@ -304,7 +307,7 @@ // Control readback may change at the SAME structural graph revision. // Compare the actual accepted controls/edges, never skip native fader updates. const signature=next.identity+"|"+JSON.stringify(next.graph.channels.map(ch=>[ - ch.id,ch.controls,ch.inserts,ch.primaryOutId]))+"|"+JSON.stringify(next.graph.edges); + ch.id,ch.controls,ch.inserts,ch.fxRackBypassed,ch.primaryOutId]))+"|"+JSON.stringify(next.graph.edges); if (signature===lastPaintedSignature) { // Telemetry often advances without a structural graph revision. paintNativeMeters(next); @@ -317,6 +320,16 @@ } flags.productionCallbackLive=next.productLive;flags.acceptedGraphConnected=true; lastPaintedSignature=signature;stopDemo();paintNativeMeters(next); + if(pendingNativeFxPower?.acked) { + const pending=pendingNativeFxPower; + const nativeCh=next.graph.channels.find(ch=>ch.id===pending.channelId); + const actual=pending.kind==="rack"?nativeCh?.fxRackBypassed: + nativeCh?.inserts?.find(i=>i.id===pending.insertId)?.bypassed; + if(actual===pending.bypassed) { + pendingNativeFxPower=null; + status("NATIVE FX "+pending.kind+" power verified from actual PCM readback"); + } + } status((next.productLive?"NATIVE PRODUCT LIVE":"NATIVE PCM GRAPH ACCEPTED · FAT PENDING")+ " · device "+next.device.epoch+ " · graph "+next.graph.revision+" · roster "+next.graph.rosterRevision); @@ -349,6 +362,17 @@ finally{profiler.sample("nativeSnapshotJsMs",performance.now()-started);} }); backend.addEventListener("arMixConsoleAck", ack=>controller.onAck(ack)); + backend.addEventListener("arMixNativeFxPowerAck", ack=>{ + if(!pendingNativeFxPower||ack?.requestId!==pendingNativeFxPower.requestId)return; + if(ack.ok!==true){ + pendingNativeFxPower=null; + status("NATIVE FX REJECTED: "+(ack?.error||"stale engine authority")); + controller.subscribe(); // restore authoritative state + return; + } + pendingNativeFxPower.acked=true; + controller.subscribe(); // ACK is not state; await independent PCM readback + }); backend.addEventListener("arMixSourceSwitchAck", ack=>{ if(!pendingSourceId||ack?.requestId!==pendingSourceId)return; pendingSourceId=0; @@ -420,6 +444,43 @@ const key=action==="mute"?"SET_MUTE":"SET_SOLO"; intent(key,t,{value:!t[action],enabled:!t[action]});return true; } + if(action==="fxOn" || action==="slotPower") { + const current=controller?.state()?.current; + const id=nativeIdFor(t); + const ch=current?.graph?.channels?.find(x=>x.id===id); + if(!current?.admitted||!id||!ch||pendingNativeFxPower){ + status("NATIVE FX: wait for accepted graph/readback or pending ACK"); + return true; + } + const rack=action==="fxOn"; + const slot=Number(btn?.dataset?.slot); + const insert=!rack&&Number.isInteger(slot)&&slot>=0&&slot<8? + ch.inserts?.[slot]:null; + if((rack&&typeof ch.fxRackBypassed!=="boolean")|| + (!rack&&(!insert||typeof insert.bypassed!=="boolean"|| + typeof insert.id!=="string"||!insert.id))){ + status("NATIVE FX: rack/insert is not admitted on this ChannelId"); + return true; + } + const requestId="fx-"+(++nativeFxPowerSerial)+"-"+Date.now().toString(36); + const bypassed=rack?!ch.fxRackBypassed:!insert.bypassed; + pendingNativeFxPower={requestId,channelId:id,kind:rack?"rack":"insert", + insertId:insert?.id,bypassed,acked:false}; + backend.emitEvent("arMixAction",{ + action:rack?"routingNativeFxRackBypass":"routingNativeFxInsertBypass", + requestId,channelId:id,deviceEpoch:current.device.epoch, + revision:current.graph.revision,value:bypassed, + ...(rack?{}:{slot,insertId:insert.id}) + }); + status("NATIVE FX "+(rack?"RACK":"INSERT")+" pending ACK + PCM readback"); + window.setTimeout(()=>{ + if(pendingNativeFxPower?.requestId===requestId){ + pendingNativeFxPower=null;controller?.subscribe(); + status("NATIVE FX ACK/readback timeout; control unchanged until producer confirms"); + } + },8000); + return true; + } status("NATIVE: "+action+" is not an accepted ChannelId operation");return true; }, consumeWire(ops) { @@ -477,6 +538,17 @@ state:()=>controller?.state() || null }); window.__ARMIX_NATIVE_M2__ = nativeHooks; + // Narrow, read-only adapter: the EQ editor must never guess the native + // ChannelId from a UI strip ordinal. The accepted console projection + // supplies exact identity; this adapter does NOT publish audio data. + Object.defineProperty(window,"__ARMIX_BUILTIN_EQ_CHANNEL__",{ + configurable:false,writable:false, + value:Object.freeze({ + resolve(uiId){return connected&&flags.acceptedGraphConnected? + nativeByUiId.get(Number(uiId))||null:null;}, + state(){return connected?controller?.state().current||null:null;} + }) + }); const descriptor = Object.freeze({ source:"site/preview-v2 + site/preview-buttons", pagesRoute:"/preview/",