diff --git a/.github/workflows/dsp.yml b/.github/workflows/dsp.yml new file mode 100644 index 0000000..a3a7da6 --- /dev/null +++ b/.github/workflows/dsp.yml @@ -0,0 +1,50 @@ +name: Fast headless DSP checks +on: + pull_request: + paths: + - "Source/DSP/**" + - "WebUI/**" + - "tests/**" + - "CMakeLists.txt" + - ".github/workflows/dsp.yml" + workflow_dispatch: +permissions: + contents: read +concurrency: + group: dsp-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + dsp-linux: + runs-on: ubuntu-latest + timeout-minutes: 8 + steps: + - uses: actions/checkout@v4 + - name: Configure native core (no JUCE download) + run: cmake -S . -B build -DARSONEQ_BUILD_PLUGIN=OFF -DARSONEQ_BUILD_TESTS=ON -DCMAKE_BUILD_TYPE=Release + - name: Compile native tests + run: cmake --build build --config Release --parallel 2 + - name: Test DSP, transitions, analyzer queue + run: ctest --test-dir build -C Release --output-on-failure + - name: JS syntax + offline UI bridge smoke (no npm needed) + run: | + node --check WebUI/app.js + node WebUI/smoke.test.cjs + - name: Capture 900x535 editor visual QA (no JUCE build) + shell: bash + run: | + node WebUI/visual-qa.cjs + CHROME=$(command -v google-chrome || command -v chromium || true) + if [[ -z "$CHROME" ]]; then + echo "Chromium unavailable; skipping image snapshot" + exit 0 + fi + mkdir -p visual-qa + "$CHROME" --headless --no-sandbox --disable-gpu --hide-scrollbars --virtual-time-budget=1200 --window-size=900,535 --screenshot="$PWD/visual-qa/ArSonEQ-M3-1-900x535.png" "file://$PWD/WebUI/visual-qa.generated.html" + test -s visual-qa/ArSonEQ-M3-1-900x535.png + - name: Publish actual browser rendering for UI review + uses: actions/upload-artifact@v4 + with: + name: ArSonEQ-M3-1-GUI-Visual-QA + path: visual-qa/ArSonEQ-M3-1-900x535.png + if-no-files-found: warn + retention-days: 7 diff --git a/.github/workflows/sc220-vst3-export.yml b/.github/workflows/sc220-vst3-export.yml new file mode 100644 index 0000000..9f1ffb1 --- /dev/null +++ b/.github/workflows/sc220-vst3-export.yml @@ -0,0 +1,74 @@ +name: SC220 integration VST3 reproducible binary export +on: + push: + branches: ['feat/initial-vst3-eq-architecture'] + paths: ['.github/workflows/sc220-vst3-export.yml'] + workflow_dispatch: + +permissions: + actions: read + contents: write + +concurrency: + group: sc220-arsoneq-export + cancel-in-progress: false + +jobs: + export-reproducible-vst3: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Pin previous successful Windows CI artifact + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + run_status=$(gh api repos/masarray/arson-eq/actions/runs/40983590331 --jq '.conclusion') + run_sha=$(gh api repos/masarray/arson-eq/actions/runs/40983590331 --jq '.head_sha') + [[ "$run_status" == "success" ]] || { echo "Original VST3 build was not successful"; exit 1; } + [[ "$run_sha" == "1f9513d75faea306e06bafd7b68119d4b8bef276" ]] || { echo "Source changed; rebuild required"; exit 1; } + gh run download 40983590331 --repo masarray/arson-eq --name 'ArSonEQ-M3-1-Windows-x64-VST3-Standalone-TEST' --dir from-audited-ci + - name: Verify actual VST3 module, package exact binary and AGPL notice + shell: bash + run: | + set -euo pipefail + bundle='from-audited-ci/VST3/ArSonEQ.vst3' + test -d "$bundle" + module=$(find "$bundle" -type f -iname '*.vst3' -print -quit) + test -n "$module" + test "$(stat -c '%s' "$module")" -gt 100000 + mkdir -p stage + cp -a "$bundle" 'stage/ArSonEQ.vst3' + cp LICENSE 'stage/AGPL-3.0-LICENSE.txt' + cat > stage/PROVENANCE.txt < SHA256SUMS.txt + test -s 'ArSonEQ-v0.1.0-M3.1-Windows-x64-VST3.zip' + unzip -tq 'ArSonEQ-v0.1.0-M3.1-Windows-x64-VST3.zip' + - name: Publish version-pinned public engineering VST3 binary without mutating stable tags + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + if gh release view 'v0.1.0-m3.1-sc220-test' --repo 'masarray/arson-eq' >/dev/null 2>&1; then + echo "Immutable integration release exists; refusing to replace binaries." + exit 1 + fi + gh release create 'v0.1.0-m3.1-sc220-test' 'ArSonEQ-v0.1.0-M3.1-Windows-x64-VST3.zip' SHA256SUMS.txt \ + --repo 'masarray/arson-eq' --target '1f9513d75faea306e06bafd7b68119d4b8bef276' --prerelease \ + --title 'ArSonEQ - SC220 Integration VST3 (M3.1 engineering)' \ + --notes 'Independently licensed AGPL-3.0 Windows x64 VST3 exported from an already-passing Windows build. Includes source/run provenance, corresponding GitHub source commit, licence and checksums. Intended as an engineering test asset, not a claim of SC220+ASIO hardware approval.' diff --git a/.github/workflows/vst3-windows.yml b/.github/workflows/vst3-windows.yml new file mode 100644 index 0000000..7f1e0ad --- /dev/null +++ b/.github/workflows/vst3-windows.yml @@ -0,0 +1,76 @@ +name: Windows VST3 + Standalone Release +on: + pull_request: + paths: + - "Source/**" + - "WebUI/index.html" + - "WebUI/style.css" + - "WebUI/app.js" + - "tests/**" + - "CMakeLists.txt" + - ".github/workflows/vst3-windows.yml" + workflow_dispatch: +permissions: + contents: read +concurrency: + group: windows-dual-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + windows-dual: + runs-on: windows-latest + timeout-minutes: 35 + steps: + - uses: actions/checkout@v4 + - name: Cache pinned WebView2 SDK + uses: actions/cache@v4 + id: webview2 + with: + path: ${{ runner.temp }}/arsoneq-nuget + key: webview2-sdk-1.0.3485.44 + - name: Install WebView2 SDK (build-time only) + if: steps.webview2.outputs.cache-hit != 'true' + shell: pwsh + run: nuget install Microsoft.Web.WebView2 -Version 1.0.3485.44 -OutputDirectory "$env:RUNNER_TEMP/arsoneq-nuget" -NonInteractive + - name: Configure pinned JUCE 9.0.4 and all tests + shell: pwsh + run: cmake -S . -B build-vst -DARSONEQ_BUILD_PLUGIN=ON -DARSONEQ_BUILD_TESTS=ON "-DJUCE_WEBVIEW2_PACKAGE_LOCATION=$env:RUNNER_TEMP/arsoneq-nuget" + - name: Build BOTH Windows Release formats + native tests + run: cmake --build build-vst --config Release --target ArSonEQ_VST3 ArSonEQ_Standalone arson_eq_core_tests arson_eq_rt_tests arson_eq_analyzer_tests --parallel 2 + - name: Run 3 native DSP suites + run: ctest --test-dir build-vst -C Release --output-on-failure + - name: Package verified VST3 and Standalone EXE together + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $root = "build-vst/ArSonEQ_artefacts/Release" + $vst = Join-Path $root "VST3/ArSonEQ.vst3" + $standaloneDir = Join-Path $root "Standalone" + if (!(Test-Path $vst -PathType Container)) { throw "Missing VST3 bundle: $vst" } + $exe = Get-ChildItem $standaloneDir -Filter "ArSonEQ.exe" -File -ErrorAction Stop | Select-Object -First 1 + if ($null -eq $exe) { throw "Missing Standalone EXE in $standaloneDir" } + if ($exe.Length -lt 100000) { throw "Unexpectedly small Standalone EXE" } + $dll = Get-ChildItem $vst -Recurse -File -Filter "*.vst3" | Select-Object -First 1 + if ($null -eq $dll -or $dll.Length -lt 100000) { throw "Missing compiled VST3 module" } + $out = "dist/ArSonEQ-M3-1-Windows-x64" + New-Item -ItemType Directory -Force "$out/VST3","$out/Standalone" | Out-Null + Copy-Item -Path $vst -Destination "$out/VST3/" -Recurse -Force + Copy-Item -Path $exe.FullName -Destination "$out/Standalone/ArSonEQ.exe" -Force + Copy-Item -Path "packaging/README_WINDOWS_TEST.txt" -Destination "$out/README_WINDOWS_TEST.txt" -Force + Set-Content -Path "$out/BUILD.txt" -Value @( + "Project: ArSonEQ M3 native stereo FFT + quick editor engineering test" + "Commit: ${{ github.sha }}" + "Windows: x64 / Release" + "Targets: VST3 + Standalone" + "JUCE: 9.0.4; GUI: bundled offline WebView2" + "VST3 module bytes: $($dll.Length)" + "Standalone exe bytes: $($exe.Length)" + "Both produced by a single CI run." + ) -Encoding utf8 + Get-ChildItem $out -Recurse | Select-Object FullName,Length + - name: Upload combined VST3 + Standalone test package + uses: actions/upload-artifact@v4 + with: + name: ArSonEQ-M3-1-Windows-x64-VST3-Standalone-TEST + path: dist/ArSonEQ-M3-1-Windows-x64/ + if-no-files-found: error + retention-days: 14 diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..d66ddc9 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,83 @@ +cmake_minimum_required(VERSION 3.24) +project(ArSonEQ VERSION 0.1.0 LANGUAGES C CXX) + +option(ARSONEQ_BUILD_PLUGIN "Build JUCE VST3 plugin and native Standalone application" OFF) +option(ARSONEQ_BUILD_TESTS "Build standalone DSP unit tests" ON) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +add_library(arson_eq_dsp INTERFACE) +target_include_directories(arson_eq_dsp INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/Source") +target_compile_features(arson_eq_dsp INTERFACE cxx_std_17) + +if(ARSONEQ_BUILD_TESTS) + enable_testing() + add_executable(arson_eq_core_tests tests/eq_core_tests.cpp) + target_link_libraries(arson_eq_core_tests PRIVATE arson_eq_dsp) + if(MSVC) + target_compile_options(arson_eq_core_tests PRIVATE /W4) + else() + target_compile_options(arson_eq_core_tests PRIVATE -Wall -Wextra -Wpedantic) + endif() + add_test(NAME arson_eq_core COMMAND arson_eq_core_tests) + add_executable(arson_eq_rt_tests tests/eq_rt_tests.cpp) + target_link_libraries(arson_eq_rt_tests PRIVATE arson_eq_dsp) + add_test(NAME arson_eq_rt COMMAND arson_eq_rt_tests) + find_package(Threads REQUIRED) + add_executable(arson_eq_analyzer_tests tests/eq_analyzer_tests.cpp) + target_link_libraries(arson_eq_analyzer_tests PRIVATE arson_eq_dsp Threads::Threads) + add_test(NAME arson_eq_analyzer COMMAND arson_eq_analyzer_tests) +endif() + +if(ARSONEQ_BUILD_PLUGIN) + # Local JUCE checkout for offline builds; otherwise fetch a pinned release. + if(DEFINED JUCE_SOURCE_DIR AND EXISTS "${JUCE_SOURCE_DIR}/CMakeLists.txt") + add_subdirectory("${JUCE_SOURCE_DIR}" "${CMAKE_BINARY_DIR}/juce") + else() + include(FetchContent) + FetchContent_Declare(juce + GIT_REPOSITORY https://github.com/juce-framework/JUCE.git + GIT_TAG 9.0.4 + GIT_SHALLOW TRUE) + FetchContent_MakeAvailable(juce) + endif() + + juce_add_plugin(ArSonEQ + COMPANY_NAME "ArSon Audio" + BUNDLE_ID "com.arsonaudio.arsoneq" + PLUGIN_MANUFACTURER_CODE ArsN + PLUGIN_CODE ArEQ + # One shared processor/editor implementation for both deliverables. + # Standalone is a native Windows executable, NOT a web page. + FORMATS VST3 Standalone + VST3_CATEGORIES Fx EQ + IS_SYNTH FALSE + NEEDS_MIDI_INPUT FALSE + NEEDS_MIDI_OUTPUT FALSE + IS_MIDI_EFFECT FALSE + COPY_PLUGIN_AFTER_BUILD FALSE + PRODUCT_NAME "ArSonEQ" + NEEDS_WEBVIEW2 TRUE) + target_sources(ArSonEQ PRIVATE + Source/PluginProcessor.cpp + Source/PluginEditor.cpp) + if(WIN32) + # Browser UI is plain static HTML/CSS/JS embedded in BOTH formats. + # No Node/React/vite/npm at runtime and no local web server. + juce_add_binary_data(ArSonEQWebAssets SOURCES + WebUI/index.html WebUI/style.css WebUI/app.js) + target_sources(ArSonEQ PRIVATE Source/WebEditor.cpp) + target_link_libraries(ArSonEQ PRIVATE ArSonEQWebAssets) + endif() + target_link_libraries(ArSonEQ PRIVATE arson_eq_dsp + juce::juce_audio_utils juce::juce_gui_extra juce::juce_dsp + juce::juce_recommended_config_flags + juce::juce_recommended_warning_flags + juce::juce_recommended_lto_flags) + target_compile_definitions(ArSonEQ PRIVATE + JUCE_WEB_BROWSER=1 JUCE_USE_CURL=0 JUCE_VST3_CAN_REPLACE_VST2=0) + if(WIN32) + target_compile_definitions(ArSonEQ PRIVATE JUCE_USE_WIN_WEBVIEW2=1) + endif() +endif() diff --git a/README.md b/README.md new file mode 100644 index 0000000..b324b3c --- /dev/null +++ b/README.md @@ -0,0 +1,114 @@ +# ArSonEQ + +ArSonEQ is an original, open-source, professional parametric equalizer plug-in project. The goal is a fast, transparent, refined workflow comparable in capability to leading commercial EQs, **not** a clone of another product's source code, branding, or artwork. + +**Status: M0 foundation, under active development. Not yet a release-quality replacement for Pro-Q 3.** + +## Source and architecture + +The initial reference is [MaSonKuPik](https://github.com/masarray/masonkupik), another project owned by the maintainer. Its Web Audio/TypeScript EQ interaction model and Butterworth filter settings inform ArSonEQ, but the browser graph is **not** a native VST engine. Native DSP is independently implemented in portable C++17, and JUCE 9 supplies the plug-in wrapper and UI. No compressor, limiter, exciter, or web runtime is bundled into the EQ. + +- [Product requirements](docs/PRD.md) +- [Architecture and real-time design](docs/ARD.md) +- [Migration audit and provenance](docs/MIGRATION.md) +- [Implementation milestones and acceptance gates](docs/ROADMAP.md) + +## Build direction + +- Initial target: Windows x64 VST3; macOS VST3/AU subsequently. +- CMake 3.24+, C++17, JUCE **9.0.4 pinned** (no floating HEAD). An installed local JUCE checkout can be selected with `JUCE_SOURCE_DIR`. +- Headless C++ DSP tests build without downloading JUCE. +- Configure: `cmake -S . -B build -DARSONEQ_BUILD_PLUGIN=OFF -DARSONEQ_BUILD_TESTS=ON` +- Test: `cmake --build build --config Release && ctest --test-dir build --output-on-failure -C Release` +- Plug-in: `cmake -S . -B build-vst -DARSONEQ_BUILD_PLUGIN=ON -DARSONEQ_BUILD_TESTS=ON`; then `cmake --build build-vst --config Release`. +- If no local JUCE source is supplied, the plug-in configuration fetches pinned JUCE from GitHub. A connection is necessary only at configure time, not when running the plug-in. + +## License and dependencies + +This repository already uses **AGPL-3.0** (see LICENSE). JUCE 9 modules are offered under AGPLv3 or separate commercial terms. This project uses the AGPL path for the open-source edition. **A commercial JUCE licence may be required** for a future proprietary/closed-source edition. Steinberg VST 3 SDK 3.8+ is MIT-licensed; trademark requirements are separate. Verify all third-party dependencies and source provenance before redistribution. + +FabFilter and Pro-Q are trademarks of their respective owner, which is not affiliated with ArSonEQ. There is no FabFilter intellectual property or GUI artwork in this repository. + + +## Native DSP / analyzer milestone + +The M1.5 upgrade uses preallocated dual-path crossfades for discrete filter topology, route and enabled changes. Continuous gain/frequency/Q movements use coefficient smoothing. A zero-latency minimum-phase DSP path remains the only implemented phase mode. A single-producer/single-consumer telemetry queue feeds two 4,096-point FFTs (input and output) on the editor thread, without FFT execution in the audio callback. UI transfer curves reflect L/R/M/S routing via a matrix calculation and are cached until parameters or geometry change. + +New headless checks include dynamic transitions, algebraic-vs-measured response, heap-allocation checks in DSP processing, and SPSC thread safety. This is **not** certification of click-free behavior on every host or of low-CPU targets: host testing, CPU profiles, pluginval and independent DAW testing remain necessary before release. + + +## M2 Windows web GUI (MaSonKuPik-inspired) + +On Windows, the editor prefers a **premium dark HTML/CSS/Canvas 2D UI** hosted by JUCE 9 WebView2. Assets are embedded into the VST3; no installer web server, external network, React runtime, or npm package install. WebView2 must be available on the user's machine. If unsupported, the native JUCE editor is retained. The DSP continues to run independently of either editor. + +Control map: double-click empty canvas to create a bell filter, double-click an existing node to remove; drag for frequency/gain; wheel over a node for Q or cut slope; click for inspector; route filters to Stereo/L/R/Mid/Side; edit numeric frequency/gain/Q in the right inspector; Delete removes selected band. Native APVTS parameter IDs are not changed. The response curve is computed in the C++ DSP, and a bounded 25Hz FFT stream from the editor's native queue drives the input/output spectrum behind the curve. + +Source `WebUI/` is deliberately tiny and zero-dependency. Run `node --check WebUI/app.js && node WebUI/smoke.test.cjs` for an offline bridge wiring smoke check. This is NOT a substitute for actual DAW/WebView2 UI testing, host recall validation or CPU/memory profiling. + +### Windows fallback + +Set environment variable `ARSONEQ_USE_NATIVE_GUI=1` before launching your DAW to force the original JUCE native editor if WebView2 is unsupported or fails in the host. Restart the host to make it take effect. The embedded JS is not an audio dependency; DSP processing remains available without any GUI. + + +## M2.1 — Compact premium editor + +Based on user-provided screenshots comparing Pro-Q 3, ArSonMix and ArSonEQ, the first WebView2 UI was redesigned around a **full-width EQ graph**. Initial WebView2 editor size is **900 × 535** (host title bar excluded), resizable from 760 × 455. Selected nodes open a small movable-by-anchor floating filter popup rather than occupying a permanent empty 294px sidebar. The top/bottom rails are compact, frequencies and dB labels remain visible in the graph, and the active-band list is available from the BANDS button. The materials follow ArSonMix's dark glass workspace / aluminum control / turquoise status language without copying third-party graphical assets. A no-network, no-React JavaScript/Canvas editor is still bundled into the VST3. + +Controls: single-click a node to select and open floating controls; click empty canvas to dismiss; double-click to add/delete; drag Hz/dB; wheel to change Q/slope; click BANDS for other active bands, ? for concise help. The existing native fallback and DAW automation parameters are preserved. Native host visual QA, memory/CPU data and pluginval remain necessary before calling the GUI production-ready. + + +### Compact editor controls (M2.1) +The primary 900×535 Windows WebView2 GUI uses a single edge-to-edge frequency graph and a contextual floating inspector. Click a node to open filter type, frequency/gain/Q rotary and numeric edits, slope, stereo/Mid/Side route, bypass and delete; close the inspector for a fully unobstructed graph. Rotate a control by dragging vertically or use precise numeric inputs. The ANALYZER switch disables the native audio telemetry and UI FFT work when OFF. For debugging fallback: launch the DAW with `ARSONEQ_USE_NATIVE_GUI=1`. + + +## M2.2 — TWO Windows deliverables: VST3 + Standalone EXE + +The Windows Release job **builds both** `ArSonEQ_VST3` and `ArSonEQ_Standalone` from the same JUCE AudioProcessor, 24-band C++ DSP, WebView2 GUI and 168 stable host parameter IDs. These are different binary formats, not two GUIs or a separate browser website. + +- **VST3**: `ArSonEQ.vst3` bundle; copy its complete folder to `C:\Program Files\Common Files\VST3\`; restart/rescan ArSonMix, REAPER, or another VST3 host. +- **Standalone EXE**: `ArSonEQ.exe`; launch directly on Windows x64. It does **not** load other VSTs; it is a standalone EQ audio application. Select the desired input/output audio devices using the standard JUCE standalone audio settings. For processing a microphone or external audio feed, configure a real input source and output monitor; simply starting the EXE does not route system-wide playback through the EQ. +- **Both**: use the same offline-embedded WebView2 interface and require Microsoft Edge WebView2 Runtime. To force the simpler native fallback UI, set `ARSONEQ_USE_NATIVE_GUI=1` in the environment *before* launching the EXE or DAW. + +A combined **Windows x64 engineering test ZIP** contains `VST3/`, `Standalone/`, `BUILD.txt` and `README_WINDOWS_TEST.txt`. Both formats compile in **one shared CI job** (pinned JUCE and WebView2 SDK, one CMake configure and native DSP tests). A build PASS does not prove soundcard support or host runtime behavior: physical ASIO/WASAPI audio checks, DAW recall, pluginval, GUI screenshot and CPU profiling remain separate release gates. + + +## M2.3 GUI fix: unobstructed equalizer graph + +Based on real VSTHost side-by-side screenshots, the EQ's old floating editor was found to cover critical frequency response data. The band editor is now a compact, dedicated *bottom control deck*, physically outside the graph DOM. It cannot overlay the response curve at any band frequency/level. Selecting empty plot dismisses the controls and restores full graph height; selecting a filter displays its type/rotaries/numeric fields/slope/route/bypass. The plot features a warm-gold native EQ response with green boost shading, individual colored nodes, separate analyzer rail and automatically expanded dB range when needed. Both packaged formats (VST3 and native Standalone) use exactly the same assets; no C++ DSP/host parameter contract changed. + +The Linux fast CI job also generates a deterministic **browser screenshot** at 900×535 with a synthetic host fixture for visual layout inspection; this preview fixture is *not embedded* into end-user builds and must not be confused with the actual C++ audio response. Real VSTHost and ArSonMix comparison/DAW validation remains necessary. + + +**M2.3.1 visual audit:** A CI-created 900×535 browser screenshot is reviewed for panel occlusion, axis collisions and control sizing. When dragging a not-yet-selected node, the dock now opens on *pointer release* to avoid graph-height changes during audio parameter gestures; double-click deletion retains a small first-hit tolerance. Both compiled formats use this same GUI. The browser preview's example curves are synthesized for **visual QA only**, not audio engine output. + + +## Competitive gap audit (2026-10-30) + +After a user-provided side-by-side screenshot comparison of ArSonEQ Standalone and FabFilter Pro-Q 3 in VSTHost, the latest engineering priorities are documented in [the Pro-Q 3 gap audit and M2.4 milestone plan](docs/PROQ3_GAP_AUDIT_AND_M24_PLAN_20261030.md). The important uncovered issue is not a superficial gradient: ArSonEQ's analyzer currently averages stereo samples before FFT, losing fully anti-phase stereo signals, and maps nearest FFT bins to a coarse log spectrum without Pro-Q-style speed/tilt/resolution options. The planned fix preserves actual stereo spectral energy, correct measurement units and real-time safety. GUI density and VST3/Standalone quality gates follow this correctness milestone. Do not interpret the published M2.3 engineering builds as equal in sound/features/performance to Pro-Q 3. + + +## M2.4 — native stereo spectrum and professional compact graph (engineering candidate) + +The user-reportable Pro-Q 3 comparison motivated replacing the coarse mono spectrum (which cancelled antiphase L/R) with **real pre/post L/R PCM telemetry**, independent FFTs and power-domain stereo aggregation. GUI-side Hann FFT is 1024–8192 selectable, 384 logarithmic points with time-based smoothing; FFT tilt defaults to 4.5 dB/oct and affects the **visualization only**, not audio. Pre/Post/Freeze and display range are selectable; right meter shows sample peaks (not true peaks). A 70px selected-band quick strip keeps at least 390px graph height at 900×535; click MORE for full controls. No new VST3 host parameters, no audio callback allocation/FFT, no online UI libraries. + +**Release status: engineering candidate.** Native/GUI automatic tests and a dual-format Windows build are prerequisites; real hardware and VSTHost/ArSonMix testing remain necessary before declaring Pro-Q 3 feature parity. + + +## M2.5 — floating band inspector + professional editing (engineering candidate) + +M2.4's bottom flex dock caused a *real* click/release viewport jump. M2.5 relocates the band inspector **into the graph as an absolutely positioned overlay**, so clicking, closing and opening MORE cannot modify the graph dimensions. The card is placed relative to the selected node while preserving pointer coordinates. Ctrl/Meta-click selects multiple bands, group drag moves frequencies in log space with coherent relative frequency and dB offsets, Shift-drag gives precision, Ctrl+Z/Ctrl+Y and toolbar arrows provide bounded 64-level undo/redo of **local edits**, and right click opens actionable EQ band controls. Group movements use bounded native bridge transactions and properly paired host gestures. Native FFT and DSP audio path unchanged. NOTE: DAW global undo and full Pro-Q 3 features are separate future milestones, as is real VSTHost/ArSonMix hardware QA. + + +## M3 integrated milestone — native presets / filter-shapes / dynamic EQ + +**Presets**: Top-center chooser is now connected to native JUCE presets (8 original factory recipes plus 8 persistent User slots). Pick `USER 01–08` in the SAVE destination and press SAVE. User data stored under `%APPDATA%/ArSon Audio/ArSonEQ/Presets/`; host DAW project recall still uses APVTS. + +**Filter types**: Bell, Low Shelf, High Shelf, Low Cut (HPF), High Cut (LPF), Notch, Band Pass, Tilt Shelf, Flat Tilt. Shape buttons in MORE are real host parameters; existing indexes 0..5 unchanged. + +**Native Dynamic EQ**: On Bell/Low/High Shelf, MORE exposes Dynamic Range ±12dB and manual Threshold -60..0 dBFS, with band-limited energy detection and smoothed dynamic EQ filtering. Dynamic Range=0 returns to pure static EQ. No DSP in the browser. + +**Maturity**: This is an engineering candidate only; it does **not** include Pro-Q 3 analog matching, Natural/Linear Phase, external sidechain, automatic threshold, EQ Match or a release-grade preset importer. See docs/ROADMAP.md for M2–M5 ledger and outstanding tests. + + +### M3.1 dynamic feedback / compact controls +Dynamic bands now show **live DSP-activity-driven** gain motion and composite response, sampled from the native detector via fixed-size telemetry. The advanced floating card shrinks to 484×142; selecting FILTER TYPE opens an **app-owned dark 9-filter menu** so no white system menu appears, while presets have a text-only chevron-free dark popup. This does not mean Pro-Q3/iZotope engine parity: computed dynamic curve is an instantaneous approximation; auto threshold, sidechain and program-dependent ballistics are still missing. diff --git a/Source/DSP/AnalyzerQueue.h b/Source/DSP/AnalyzerQueue.h new file mode 100644 index 0000000..87ef91f --- /dev/null +++ b/Source/DSP/AnalyzerQueue.h @@ -0,0 +1,39 @@ +// Lock-free SPSC PCM telemetry. Exactly one audio producer, one UI consumer. +// No allocation/FFT/locks in the audio callback; dropped visual frames never block audio. +#pragma once +#include +#include +#include + +namespace arson::eq { +struct MeterFrame { float preL=0.f,preR=0.f,postL=0.f,postR=0.f; }; +class AnalyzerQueue { +public: + static constexpr uint32_t capacity=16384; + void setEnabled(bool value) noexcept { enabled_.store(value,std::memory_order_release); } + bool isEnabled() const noexcept { return enabled_.load(std::memory_order_acquire); } + bool push(float preL,float preR,float postL,float postR) noexcept { + const auto w=write_.load(std::memory_order_relaxed); + if(w-read_.load(std::memory_order_acquire)>=capacity) return false; + frames_[w&(capacity-1)]={preL,preR,postL,postR}; + write_.store(w+1,std::memory_order_release); + return true; + } + // Compatibility: mono input is represented as dual mono telemetry. + bool push(float before,float after) noexcept { + return push(before,before,after,after); + } + bool pop(MeterFrame& out) noexcept { + const auto r=read_.load(std::memory_order_relaxed); + if(r==write_.load(std::memory_order_acquire))return false; + out=frames_[r&(capacity-1)]; + read_.store(r+1,std::memory_order_release); + return true; + } +private: + static_assert((capacity&(capacity-1))==0,"ring size power of two"); + std::array frames_{}; + std::atomic write_{0},read_{0}; + std::atomic enabled_{false}; +}; +} diff --git a/Source/DSP/ParametricEQ.h b/Source/DSP/ParametricEQ.h new file mode 100644 index 0000000..b655915 --- /dev/null +++ b/Source/DSP/ParametricEQ.h @@ -0,0 +1,466 @@ +// ArSonEQ native DSP core: C++17, no JUCE, allocations, or locks on the audio path. +// New implementation informed by standard RBJ Audio EQ Cookbook biquads and +// MaSonKuPik's 12-48 dB/oct Butterworth Q-stage selections. +#pragma once +#include +#include +#include +#include +#include +#include + +namespace arson::eq { +constexpr int kMaxBands = 24; +constexpr int kMaxStages = 4; +constexpr double kPi = 3.1415926535897932384626433832795; + +enum class Type : int { Bell, LowShelf, HighShelf, LowCut, HighCut, Notch, BandPass, TiltShelf, FlatTilt }; +enum class Route : int { Stereo, Left, Right, Mid, Side }; + +struct Band { + bool enabled = false; + Type type = Type::Bell; + Route route = Route::Stereo; + double frequency = 1000.0; + double gainDb = 0.0; + double q = 1.0; + int slope = 12; + double dynamicRangeDb = 0.0; // signed additional gain, -12..+12 + double thresholdDb = -24.0; // band-limited trigger dBFS, -60..0 +}; +inline bool same(const Band& a, const Band& b) noexcept { + return a.enabled == b.enabled && a.type == b.type && a.route == b.route + && a.frequency == b.frequency && a.gainDb == b.gainDb + && a.q == b.q && a.slope == b.slope + && a.dynamicRangeDb == b.dynamicRangeDb && a.thresholdDb == b.thresholdDb; +} +inline double finiteClamp(double x, double fallback, double low, double high) noexcept { + return std::clamp(std::isfinite(x) ? x : fallback, low, high); +} +struct Coeff { + double b0=1.0, b1=0.0, b2=0.0, a1=0.0, a2=0.0; +}; +inline Coeff identity() noexcept { return {}; } +inline Coeff coefficients(Type type, double freq, double gainDb, double q, double sr) noexcept { + freq = finiteClamp(freq, 1000.0, 20.0, 0.45 * sr); + gainDb = finiteClamp(gainDb, 0.0, -24.0, 24.0); + q = finiteClamp(q, 1.0, 0.1, 24.0); + const auto w = 2.0 * kPi * freq / sr; + const auto s = std::sin(w), c = std::cos(w); + const auto A = std::pow(10.0, gainDb / 40.0); + const auto alpha = s / (2.0 * q); + // RBJ shelving slope S is bounded independently of bell Q to avoid + // unstable/extremely resonant shelves. + const auto S = std::clamp(q, 0.25, 1.0); + const auto shelfAlpha = 0.5 * s * std::sqrt((A + 1.0 / A) * (1.0 / S - 1.0) + 2.0); + const auto root = 2.0 * std::sqrt(A) * shelfAlpha; + double b0=1,b1=0,b2=0,a0=1,a1=0,a2=0; + switch (type) { + case Type::Bell: + b0=1+alpha*A; b1=-2*c; b2=1-alpha*A; + a0=1+alpha/A; a1=-2*c; a2=1-alpha/A; break; + case Type::BandPass: + // RBJ constant 0 dB peak bandpass, numerator = alpha. + b0=alpha; b1=0; b2=-alpha; + a0=1+alpha; a1=-2*c; a2=1-alpha; break; + case Type::TiltShelf: + case Type::FlatTilt: + // These are assembled as two shelves in makeStages(). + return identity(); + case Type::Notch: + b0=1; b1=-2*c; b2=1; + a0=1+alpha; a1=-2*c; a2=1-alpha; break; + case Type::LowCut: + b0=(1+c)/2; b1=-(1+c); b2=(1+c)/2; + a0=1+alpha; a1=-2*c; a2=1-alpha; break; + case Type::HighCut: + b0=(1-c)/2; b1=1-c; b2=(1-c)/2; + a0=1+alpha; a1=-2*c; a2=1-alpha; break; + case Type::LowShelf: + b0=A*((A+1)-(A-1)*c+root); + b1=2*A*((A-1)-(A+1)*c); + b2=A*((A+1)-(A-1)*c-root); + a0=(A+1)+(A-1)*c+root; + a1=-2*((A-1)+(A+1)*c); + a2=(A+1)+(A-1)*c-root; break; + case Type::HighShelf: + b0=A*((A+1)+(A-1)*c+root); + b1=-2*A*((A-1)+(A+1)*c); + b2=A*((A+1)+(A-1)*c-root); + a0=(A+1)-(A-1)*c+root; + a1=2*((A-1)-(A+1)*c); + a2=(A+1)-(A-1)*c-root; break; + } + if (!std::isfinite(a0) || std::abs(a0) < 1e-15) return identity(); + const double inv = 1.0 / a0; + Coeff result{b0*inv,b1*inv,b2*inv,a1*inv,a2*inv}; + if (!std::isfinite(result.b0) || !std::isfinite(result.a1) + || !std::isfinite(result.a2)) return identity(); + return result; +} +inline int stageCount(int slope) noexcept { + return slope >= 48 ? 4 : slope >= 36 ? 3 : slope >= 24 ? 2 : 1; +} +inline double butterworthQ(int stages, int index) noexcept { + constexpr double qs[4][4] = { + {0.7071067811865476, 0, 0, 0}, + {0.541196100146197, 1.306562964876377, 0, 0}, + {0.517638090205041, 0.707106781186548, 1.931851652578137, 0}, + {0.509795579104159, 0.601344886935045, 0.899976223136416, 2.562915447741506} + }; + return qs[std::clamp(stages,1,4)-1][std::clamp(index,0,3)]; +} +inline std::array makeStages(Band band, double sr) noexcept { + std::array result{}; + if (!band.enabled) return result; + const bool cut = band.type == Type::LowCut || band.type == Type::HighCut; + const bool tilt = band.type == Type::TiltShelf || band.type == Type::FlatTilt; + const int count = cut ? stageCount(band.slope) : tilt ? 2 : 1; + for (int i=0;i(i)] = coefficients( + lo?Type::LowShelf:Type::HighShelf,band.frequency, + lo?-0.5*band.gainDb:0.5*band.gainDb,tiltQ,sr); + } else result[static_cast(i)] = coefficients(band.type,band.frequency,band.gainDb,q,sr); + } + return result; +} +inline double magnitudeDb(const Coeff& c, double freq, double sr) noexcept { + const auto theta = 2.0*kPi*freq/sr; + const auto z = std::polar(1.0,-theta), z2=z*z; + const auto num = c.b0 + c.b1*z + c.b2*z2; + const auto den = 1.0 + c.a1*z + c.a2*z2; + return 20.0*std::log10(std::max(std::abs(num)/std::max(std::abs(den),1e-20),1e-20)); +} + + +struct StereoMatrix { + std::complex ll{1.0,0.0}, lr{0.0,0.0}; + std::complex rl{0.0,0.0}, rr{1.0,0.0}; +}; + +class Engine { +public: + void prepare(double rate) noexcept { + sampleRate_ = finiteClamp(rate, 48000.0, 8000.0, 384000.0); + for (auto& s : slots_) { + s.primary = makePath(s.requested); + s.secondary = {}; + s.fadeRemaining = 0; + s.fadeLength = 0; + } + } + double sampleRate() const noexcept { return sampleRate_; } + // Audio-thread-owned current detector activity; publish once per block + // via separate relaxed atomics in the processor, never read Engine cross-thread. + float dynamicActivity(int index) const noexcept { + if(!valid(index))return 0.f; + const auto& slot=slots_[static_cast(index)]; + const auto activity=[](const Path& p) noexcept { + return p.dynamicEnabled?std::max(p.activity[0],p.activity[1]):0.; + }; + return static_cast(std::clamp(std::max(activity(slot.primary), + slot.fadeRemaining?activity(slot.secondary):0.),0.,1.)); + } + Band band(int index) const noexcept { + return valid(index) ? slots_[static_cast(index)].requested : Band{}; + } + bool setBand(int index, Band value) noexcept { + if (!valid(index)) return false; + value.frequency = finiteClamp(value.frequency, 1000.0, 20.0, 0.45 * sampleRate_); + value.gainDb = finiteClamp(value.gainDb, 0.0, -24.0, 24.0); + value.q = finiteClamp(value.q, 1.0, 0.1, 24.0); + value.slope = stageCount(value.slope) * 12; + value.dynamicRangeDb=finiteClamp(value.dynamicRangeDb,0.,-12.,12.); + value.thresholdDb=finiteClamp(value.thresholdDb,-24.,-60.,0.); + if (static_cast(value.type) < 0 || static_cast(value.type) > 8) + value.type = Type::Bell; + if (static_cast(value.route) < 0 || static_cast(value.route) > 4) + value.route = Route::Stereo; + auto& s = slots_[static_cast(index)]; + if (same(s.requested, value)) return false; + s.requested = value; + // During a topology crossfade, keep BOTH live branches untouched. + // Only the latest request is queued; the next change starts after fade. + // Restarting fades midway creates sharp discontinuities on automation. + if (s.fadeRemaining == 0) apply(s, value); + return true; + } + void reset() noexcept { prepare(sampleRate_); } + void process(double& left, double& right) noexcept { + for (auto& s : slots_) { + if (s.fadeRemaining == 0) { + if (!s.primary.band.enabled) continue; + processStereoPath(s.primary, left, right); + } else { + const double inL=left,inR=right; + double oldL=inL,oldR=inR,newL=inL,newR=inR; + if (s.primary.band.enabled) processStereoPath(s.primary,oldL,oldR); + if (s.secondary.band.enabled) processStereoPath(s.secondary,newL,newR); + const double t=1.0-static_cast(s.fadeRemaining-1)/s.fadeLength; + const double smooth=t*t*(3.0-2.0*t); + left=oldL+(newL-oldL)*smooth; + right=oldR+(newR-oldR)*smooth; + finishFade(s); + } + } + } + void processMono(double& sample) noexcept { + for (auto& s : slots_) { + if (s.fadeRemaining == 0) { + if (s.primary.band.enabled) processMonoPath(s.primary,sample); + } else { + double oldValue=sample,newValue=sample; + if (s.primary.band.enabled) processMonoPath(s.primary,oldValue); + if (s.secondary.band.enabled) processMonoPath(s.secondary,newValue); + const double t=1.0-static_cast(s.fadeRemaining-1)/s.fadeLength; + const double smooth=t*t*(3.0-2.0*t); + sample=oldValue+(newValue-oldValue)*smooth; + finishFade(s); + } + } + } + double bandResponseDb(int index, double frequency) const noexcept { + if (!valid(index)) return 0.0; + const Band b=slots_[static_cast(index)].requested; + if (!b.enabled) return 0.0; + const auto coeff=makeStages(b,sampleRate_); + const auto count=stageCountFor(b); + double db=0.0; + for (int i=0;i(i)],frequency,sampleRate_); + return db; + } + // The actual steady-state 2x2 matrix includes crossfeed from M/S. + // A graph showing only stereo-routed bands would conceal active filters. + StereoMatrix matrixResponse(double frequency, + const std::array* dynamicActivity=nullptr) const noexcept { + StereoMatrix total; + if (!std::isfinite(frequency) || frequency<=0.0 || frequency>=sampleRate_*0.5) + return total; + for(int slotIndex=0;slotIndex(slotIndex)]; + const Band b=slot.requested; + if (!b.enabled) continue; + std::complex h{1.0,0.0}; + const auto stages=makeStages(b,sampleRate_); + const auto z=std::polar(1.0,-2.0*kPi*frequency/sampleRate_); + const auto z2=z*z; + for(int k=0;k(k)]; + const auto numerator=c.b0+c.b1*z+c.b2*z2; + const auto denominator=1.0+c.a1*z+c.a2*z2; + h*=numerator/denominator; + } + if(dynamicActivity!=nullptr && std::abs(b.dynamicRangeDb)>0.0001 && + (b.type==Type::Bell||b.type==Type::LowShelf||b.type==Type::HighShelf)) { + const double wet=std::clamp(double((*dynamicActivity)[static_cast(slotIndex)]),0.,1.); + if(wet>0.0001) { + const auto c=coefficients(b.type,b.frequency,b.dynamicRangeDb,b.q,sampleRate_); + const auto dynH=(c.b0+c.b1*z+c.b2*z2)/(1.0+c.a1*z+c.a2*z2); + h*=1.0+wet*(dynH-1.0); + } + } + StereoMatrix f; + const auto one=std::complex(1.0,0.0); + switch (b.route) { + case Route::Stereo: f.ll=h; f.rr=h; break; + case Route::Left: f.ll=h; break; + case Route::Right: f.rr=h; break; + case Route::Mid: + f.ll=(h+one)*0.5;f.rr=f.ll; + f.lr=(h-one)*0.5;f.rl=f.lr;break; + case Route::Side: + f.ll=(h+one)*0.5;f.rr=f.ll; + f.lr=(one-h)*0.5;f.rl=f.lr;break; + } + StereoMatrix next; + next.ll=f.ll*total.ll+f.lr*total.rl; + next.lr=f.ll*total.lr+f.lr*total.rr; + next.rl=f.rl*total.ll+f.rr*total.rl; + next.rr=f.rl*total.lr+f.rr*total.rr; + total=next; + } + return total; + } + // Graph target: diagonal feed responses L->L and R->R. + // Nonzero lr/rl should be visualised separately as stereo crossfeed. + std::array channelResponseDb(double frequency) const noexcept { + const auto m=matrixResponse(frequency); + const auto toDb=[](const std::complex& z) noexcept { + return 20.0*std::log10(std::max(std::abs(z),1e-20)); + }; + return {toDb(m.ll),toDb(m.rr)}; + } + double stereoResponseDb(double frequency) const noexcept { + const auto r=channelResponseDb(frequency); + return (r[0]+r[1])*0.5; + } +private: + struct State { double z1=0.0,z2=0.0; }; + struct Path { + Band band{}; + std::array coefficients{}; + std::array target{}; + std::array,2> state{}; + int stages=0; + int morphRemaining=0; + Coeff detector{}, dynamicFilter{}; + std::array detectorState{}, dynamicState{}; + std::array envelope{}; + std::array activity{}; + double thresholdLinear=0.0630957; + double attack=0.,release=0.; + bool dynamicEnabled=false; + }; + struct Slot { + Band requested{}; + Path primary{},secondary{}; + int fadeRemaining=0,fadeLength=0; + }; + static bool valid(int index) noexcept { return index>=0 && index0.0001 && + (b.type==Type::Bell || b.type==Type::LowShelf || b.type==Type::HighShelf); + if(p.dynamicEnabled) { + p.detector=coefficients(Type::BandPass,b.frequency,0.0, + std::clamp(b.q,0.3,12.0),sampleRate_); + p.dynamicFilter=coefficients(b.type,b.frequency,b.dynamicRangeDb,b.q,sampleRate_); + p.thresholdLinear=std::pow(10.,b.thresholdDb/20.); + p.attack=std::exp(-1./(0.012*sampleRate_)); + p.release=std::exp(-1./(0.100*sampleRate_)); + } + return p; + } + void apply(Slot& s,const Band& value) noexcept { + if (sameTopology(s.primary.band,value)) { + s.primary.band=value; + if (value.enabled) { + s.primary.target=makeStages(value,sampleRate_); + s.primary.morphRemaining=std::max(1,static_cast(sampleRate_*0.012)); + } + return; + } + // Only topology changes run two paths. This also smooths bypass, + // hard cut-slope switches and L/R/M/S routing changes. + s.secondary=makePath(value); + s.fadeLength=std::max(1,static_cast(sampleRate_*0.010)); + s.fadeRemaining=s.fadeLength; + } + void finishFade(Slot& s) noexcept { + if (--s.fadeRemaining!=0) return; + s.primary=s.secondary; + s.secondary={}; + if (!same(s.requested,s.primary.band)) + apply(s,s.requested); + } + static void advance(Path& p) noexcept { + if(p.morphRemaining==0) return; + const double remain=static_cast(p.morphRemaining); + for(int i=0;i(i)]; + const auto& t=p.target[static_cast(i)]; + c.b0+=(t.b0-c.b0)/remain;c.b1+=(t.b1-c.b1)/remain; + c.b2+=(t.b2-c.b2)/remain;c.a1+=(t.a1-c.a1)/remain; + c.a2+=(t.a2-c.a2)/remain; + } + --p.morphRemaining; + } + static double runBiquad(const Coeff& c, State& z, double x) noexcept { + const double y=c.b0*x+z.z1; + const double z1=c.b1*x-c.a1*y+z.z2; + const double z2=c.b2*x-c.a2*y; + if(!std::isfinite(y)||!std::isfinite(z1)||!std::isfinite(z2)){z={};return 0.;} + z.z1=std::abs(z1)<1.e-24?0.:z1; + z.z2=std::abs(z2)<1.e-24?0.:z2; + return y; + } + static double runDynamic(Path& p,double pre,double post,int lane) noexcept { + if(!p.dynamicEnabled)return post; + const auto k=static_cast(lane); + const double trigger=runBiquad(p.detector,p.detectorState[k],pre); + const double sq=trigger*trigger; + // Energy-following envelope: level is root mean squared per lane. + const double c=sq>p.envelope[k]?p.attack:p.release; + p.envelope[k]=c*p.envelope[k]+(1.-c)*sq; + const double rms=std::sqrt(std::max(0.,p.envelope[k])); + const double threshold=std::max(p.thresholdLinear,1.e-5); + // Soft onset: starts 6dB below threshold, reaches full at +6dB. + const double wet=std::clamp((rms/threshold-0.5)/1.5,0.,1.); + p.activity[k]=wet; + const double filtered=runBiquad(p.dynamicFilter,p.dynamicState[k],post); + return post+(filtered-post)*wet; + } + static double filter(Path& p,double sample,int lane) noexcept { + double x=sample; + for(int i=0;i(i)]; + auto& z=p.state[static_cast(lane)][static_cast(i)]; + const double y=c.b0*x+z.z1; + const double z1=c.b1*x-c.a1*y+z.z2; + const double z2=c.b2*x-c.a2*y; + if(!std::isfinite(y)||!std::isfinite(z1)||!std::isfinite(z2)) { + z={};x=0.0; + } else { + z.z1=std::abs(z1)<1e-24?0.0:z1; + z.z2=std::abs(z2)<1e-24?0.0:z2; + x=y; + } + } + return x; + } + static void processStereoPath(Path& p,double& l,double& r) noexcept { + advance(p); + switch(p.band.route) { + case Route::Stereo: { + const double a=l,b=r; + l=runDynamic(p,a,filter(p,l,0),0); + r=runDynamic(p,b,filter(p,r,1),1);break; + } + case Route::Left: {const double a=l;l=runDynamic(p,a,filter(p,l,0),0);break;} + case Route::Right: {const double a=r;r=runDynamic(p,a,filter(p,r,1),1);break;} + case Route::Mid: { + const auto mid=(l+r)*0.5; + const auto delta=runDynamic(p,mid,filter(p,mid,0),0)-mid; + l+=delta;r+=delta;break; + } + case Route::Side: { + const auto side=(l-r)*0.5; + const auto delta=runDynamic(p,side,filter(p,side,0),0)-side; + l+=delta;r-=delta;break; + } + } + } + static void processMonoPath(Path& p,double& x) noexcept { + advance(p); + if(p.band.route!=Route::Right && p.band.route!=Route::Side) { + const double pre=x;x=runDynamic(p,pre,filter(p,x,0),0); + } + } + double sampleRate_=48000.0; + std::array slots_{}; +}; +} // namespace arson::eq diff --git a/Source/DSP/SpectrumDisplay.h b/Source/DSP/SpectrumDisplay.h new file mode 100644 index 0000000..d60c466 --- /dev/null +++ b/Source/DSP/SpectrumDisplay.h @@ -0,0 +1,48 @@ +// Original, JUCE-free spectral display mathematics. Analysis uses power, +// never time-domain L+R downmix. Tilt and smoothing are display-only. +#pragma once +#include +#include +#include +#include +namespace arson::eq { +struct SpectrumDisplay { + static constexpr int points=384, maxFft=8192; + static constexpr double loHz=20.,hiHz=20000.; + static constexpr float floorDb=-120.f; + static double power(float magnitudeL,float magnitudeR,float coherentAmplitude) noexcept { + const double scale=std::max(1.e-12,double(coherentAmplitude)); + const double l=double(magnitudeL)/scale, r=double(magnitudeR)/scale; + return 0.5*(l*l+r*r); + } + static float db(double linearPower) noexcept { + return float(std::clamp(10.*std::log10(std::max(linearPower,1.e-12)), + -120.,24.)); + } + static double frequency(int index) noexcept { + return loHz*std::pow(hiHz/loHz,double(index)/(points-1)); + } + static float tilt(float value,double frequencyHz,float dbPerOctave) noexcept { + return value+dbPerOctave*float(std::log2(std::max(1.,frequencyHz)/1000.)); + } + static float smooth(float previous,float next,double elapsedSec,bool fast=false) noexcept { + const double seconds=next>previous?(fast?0.025:0.060):(fast?0.14:0.35); + const double k=std::exp(-std::clamp(elapsedSec,0.,1.)/seconds); + return float(std::clamp(k*previous+(1.-k)*next,-120.,24.)); + } + // Interpolate spectral *power* across adjacent FFT bins to avoid nearest-bin + // stair-stepping, while staying faithful to the physical FFT resolution. + template + static double samplePower(const Magnitudes& left,const Magnitudes& right, + int fftSize,double sampleRate,double hz) noexcept { + const double fractional=std::clamp(hz*fftSize/std::max(1.,sampleRate), + 1.,double(fftSize/2)); + const int lower=int(fractional),upper=std::min(lower+1,fftSize/2); + const double mix=fractional-lower; + // Caller supplies coherent amplitude normalization (Hann sum/2). + const double a=0.5*(left[lower]*left[lower]+right[lower]*right[lower]); + const double b=0.5*(left[upper]*left[upper]+right[upper]*right[upper]); + return a+(b-a)*mix; + } +}; +} diff --git a/Source/PluginEditor.cpp b/Source/PluginEditor.cpp new file mode 100644 index 0000000..f072472 --- /dev/null +++ b/Source/PluginEditor.cpp @@ -0,0 +1,368 @@ +#include "PluginEditor.h" +#include "DSP/SpectrumDisplay.h" +#include +#include + +namespace { +const juce::Colour bg(0xff11151c), grid(0xff252d37), ink(0xffc9d3e0); +const juce::Colour accent(0xff52c9df), selectedColor(0xfff2bf79); +constexpr double minHz=20.0,maxHz=20000.0,dbRange=18.0; +constexpr const char* typeNames[]{"Bell","Low Sh","High Sh","Low Cut","High Cut","Notch", + "Band Pass","Tilt Sh","Flat Tilt"}; +constexpr const char* routeNames[]{"Stereo","L","R","Mid","Side"}; +} +ArSonEQEditor::ArSonEQEditor(ArSonEQAudioProcessor& owner) + : juce::AudioProcessorEditor(owner),processor_(owner),fft_(fftOrder_) { + setResizable(true,true); + setResizeLimits(680,420,1440,900); + graphEngine_.prepare(processor_.configuredSampleRate()); + for(int i=0;i(i)] = 0.5f*(1.0f-std::cos( + 2.0f*juce::MathConstants::pi*i/(fftSize_-1))); + levelsPre_.fill(-108.0f); + levelsPost_.fill(-108.0f); + setSize(930,570); + setWantsKeyboardFocus(true); + processor_.analyzer().setEnabled(true); + startTimerHz(30); + timerCallback(); +} +ArSonEQEditor::~ArSonEQEditor() { + stopTimer(); + processor_.analyzer().setEnabled(false); +} +void ArSonEQEditor::resized() { + rebuildResponseCurves(); +} +juce::Rectangle ArSonEQEditor::graph() const { + return juce::Rectangle(48.f,73.f, + static_cast(getWidth())-76.f,static_cast(getHeight())-215.f); +} +float ArSonEQEditor::xForHz(double freq) const { + const auto r=graph(); + return r.getX()+static_cast(std::log(std::clamp(freq,minHz,maxHz)/minHz) + /std::log(maxHz/minHz))*r.getWidth(); +} +float ArSonEQEditor::yForDb(double db) const { + const auto r=graph(); + return r.getCentreY()-static_cast(std::clamp(db,-dbRange,dbRange)/dbRange) + *r.getHeight()*0.5f; +} +double ArSonEQEditor::hzForX(float x) const { + const auto r=graph(); + return minHz*std::pow(maxHz/minHz,std::clamp( + static_cast((x-r.getX())/r.getWidth()),0.0,1.0)); +} +double ArSonEQEditor::dbForY(float y) const { + const auto r=graph(); + return std::clamp(static_cast((r.getCentreY()-y)*2/r.getHeight())*dbRange, + -dbRange,dbRange); +} +void ArSonEQEditor::timerCallback() { + bool changed=false; + const auto sr=processor_.configuredSampleRate(); + if (graphEngine_.sampleRate()!=sr) { graphEngine_.prepare(sr);changed=true; } + for(int i=0;i(i)],b)) { + cached_[static_cast(i)]=b; + graphEngine_.setBand(i,b); + changed=true; + } + } + if(changed) rebuildResponseCurves(); + updateSpectrum(); + if(changed || spectrumReady_) repaint(); +} +void ArSonEQEditor::rebuildResponseCurves() { + curveLeft_.clear(); + curveRight_.clear(); + curveCrossfeed_.clear(); + const auto r=graph(); + if(r.getWidth()<=0.0f || r.getHeight()<=0.0f) return; + const int points=std::min(420,std::max(120,static_cast(r.getWidth()/2))); + for(int i=0;i<=points;++i) { + const auto x=r.getX()+r.getWidth()*static_cast(i)/points; + const auto matrix=graphEngine_.matrixResponse(hzForX(x)); + const auto db=[](const std::complex& v) { + return 20.0*std::log10(std::max(std::abs(v),1e-20)); + }; + const auto yL=yForDb(db(matrix.ll)); + const auto yR=yForDb(db(matrix.rr)); + const auto cross=yForDb(db(matrix.lr)); + if(i==0) { + curveLeft_.startNewSubPath(x,yL); + curveRight_.startNewSubPath(x,yR); + curveCrossfeed_.startNewSubPath(x,cross); + } else { + curveLeft_.lineTo(x,yL); + curveRight_.lineTo(x,yR); + curveCrossfeed_.lineTo(x,cross); + } + } +} +void ArSonEQEditor::updateSpectrum() { + arson::eq::MeterFrame frame; + bool got=false; + int drained=0; + while(drained(i))&(fftSize_-1); + const size_t idx=static_cast(i); + fftPre_[idx]=preHistory_[pos]*window_[idx]; + fftPost_[idx]=postHistory_[pos]*window_[idx]; + } + fft_.performFrequencyOnlyForwardTransform(fftPre_.data()); + fft_.performFrequencyOnlyForwardTransform(fftPost_.data()); + for(int i=0;i<=fftSize_/2;++i) { + const size_t k=static_cast(i); + prePower_[k]=fftPre_[k]*fftPre_[k]; + postPower_[k]=fftPost_[k]*fftPost_[k]; + } + // Reuse FFT scratch buffers to analyze RIGHT channel independently. + // Power is combined after FFT; anti-phase L/R no longer cancels. + for(int i=0;i(i))&(fftSize_-1); + const size_t k=static_cast(i); + fftPre_[k]=preRightHistory_[pos]*window_[k]; + fftPost_[k]=postRightHistory_[pos]*window_[k]; + } + fft_.performFrequencyOnlyForwardTransform(fftPre_.data()); + fft_.performFrequencyOnlyForwardTransform(fftPost_.data()); + // Hann coherent amplitude normalization (sum of window / 2). + constexpr double coherentAmplitude=(fftSize_-1)*0.25; + for(int i=0;i<=fftSize_/2;++i) { + const size_t k=static_cast(i); + const double prePower=0.5*(double(prePower_[k])+double(fftPre_[k])*fftPre_[k])/ + (coherentAmplitude*coherentAmplitude); + const double postPower=0.5*(double(postPower_[k])+double(fftPost_[k])*fftPost_[k])/ + (coherentAmplitude*coherentAmplitude); + const float a=arson::eq::SpectrumDisplay::db(prePower); + const float b=arson::eq::SpectrumDisplay::db(postPower); + levelsPre_[k]=0.75f*levelsPre_[k]+0.25f*std::clamp(a,-108.f,12.f); + levelsPost_[k]=0.75f*levelsPost_[k]+0.25f*std::clamp(b,-108.f,12.f); + } + spectrumReady_=true; +} +void ArSonEQEditor::drawSpectrum(juce::Graphics& g,juce::Rectangle r) { + if(!spectrumReady_) return; + const double sr=processor_.configuredSampleRate(); + juce::Path pre,post; + constexpr int points=320; + for(int i=0;i<=points;++i) { + const auto x=r.getX()+r.getWidth()*static_cast(i)/points; + const auto f=hzForX(x); + const auto bin=std::clamp(static_cast(std::lround(f*fftSize_/sr)),1,fftSize_/2); + const auto yForLevel=[&](float level) { + return r.getBottom() - std::clamp((level+108.0f)/96.0f,0.0f,1.0f) + *r.getHeight(); + }; + const auto a=yForLevel(levelsPre_[static_cast(bin)]); + const auto b=yForLevel(levelsPost_[static_cast(bin)]); + if(i==0){ pre.startNewSubPath(x,a);post.startNewSubPath(x,b); } + else { pre.lineTo(x,a);post.lineTo(x,b); } + } + g.setColour(juce::Colour(0xff708092).withAlpha(0.42f)); + g.strokePath(pre,juce::PathStrokeType(1.0f)); + g.setColour(juce::Colour(0xff5db8b2).withAlpha(0.55f)); + g.strokePath(post,juce::PathStrokeType(1.15f)); +} +void ArSonEQEditor::paint(juce::Graphics& g) { + g.fillAll(bg); + g.setColour(ink); + g.setFont(juce::Font(juce::FontOptions(17.0f).withStyle("Plain"))); + g.drawText("ARSON EQ",juce::Rectangle(23,15,190,32),juce::Justification::centredLeft); + g.setColour(juce::Colour(0xff748391));g.setFont(11.f); + g.drawText("PARAMETRIC / ZERO LATENCY",juce::Rectangle(205,20,280,22), + juce::Justification::centredLeft); + const auto r=graph(); + g.setColour(juce::Colour(0xff161c24)); + g.fillRoundedRectangle(r,6.f); + const double ticks[]{20,50,100,200,500,1000,2000,5000,10000,20000}; + for(const auto f:ticks) { + const auto x=xForHz(f); + g.setColour(grid);g.drawVerticalLine(juce::roundToInt(x),r.getY(),r.getBottom()); + g.setColour(juce::Colour(0xff8b98a8));g.setFont(10.f); + g.drawText(f>=1000?juce::String(f/1000.0, f==2000||f==5000||f==10000||f==20000?0:1)+"k" + :juce::String(static_cast(f)), + juce::Rectangle(x-19,r.getBottom()+4,38,15),juce::Justification::centred); + } + for(int db=-18;db<=18;db+=6) { + const auto y=yForDb(db); + g.setColour(db==0?juce::Colour(0xff596879):grid); + g.drawHorizontalLine(juce::roundToInt(y),r.getX(),r.getRight()); + g.setColour(juce::Colour(0xff8b98a8));g.setFont(10.f); + g.drawText((db>0?"+":"")+juce::String(db), + juce::Rectangle(7,y-7,32,15),juce::Justification::centredRight); + } + // Analyzer is purely visual and drains on the message thread. + // Curves are cached and rebuilt only after parameter/geometry changes. + drawSpectrum(g,r); + g.setColour(accent.withAlpha(0.95f)); + g.strokePath(curveLeft_,juce::PathStrokeType(2.f)); + g.setColour(selectedColor.withAlpha(0.82f)); + g.strokePath(curveRight_,juce::PathStrokeType(1.1f)); + g.setColour(juce::Colour(0xff8a9ba8).withAlpha(0.45f)); + g.strokePath(curveCrossfeed_,juce::PathStrokeType(0.65f)); + for(int i=0;i(i)]; + if(!b.enabled) continue; + const auto x=xForHz(b.frequency); + const auto y=yForDb(b.type==arson::eq::Type::LowCut + ||b.type==arson::eq::Type::HighCut?0.0:b.gainDb); + g.setColour(i==selected_?selectedColor:accent.withAlpha(0.78f)); + g.fillEllipse(x-5,y-5,10,10); + if(i==selected_) { g.setColour(ink);g.drawEllipse(x-8,y-8,16,16,1.f); } + } + g.setColour(juce::Colour(0xff7e91a0));g.setFont(11.f); + g.drawText("FFT: grey input / teal output · EQ: cyan L→L / gold R→R · Drag: Hz + dB", + juce::Rectangle(48,getHeight()-116,getWidth()-96,22), + juce::Justification::centredLeft); + drawModeButtons(g); +} +void ArSonEQEditor::drawModeButtons(juce::Graphics& g) { + const int y=getHeight()-81; + g.setColour(juce::Colour(0xff7e91a0));g.setFont(11.f); + if(selected_<0) { + g.drawText("Select an EQ node to edit its shape and channel.", + juce::Rectangle(48,y,getWidth()-60,48),juce::Justification::centredLeft); + return; + } + const auto& b=cached_[static_cast(selected_)]; + g.drawText("B"+juce::String(selected_+1)+" "+juce::String(b.frequency,1)+" Hz " + +juce::String(b.gainDb,1)+" dB Q "+juce::String(b.q,2), + juce::Rectangle(48,y-30,getWidth()-60,25),juce::Justification::centredLeft); + for(int i=0;i<6;++i) { + const juce::Rectangle box(48.f+i*84.f,static_cast(y),80.f,27.f); + const bool active=static_cast(b.type)==i; + g.setColour(active?juce::Colour(0xff255060):juce::Colour(0xff202832)); + g.fillRoundedRectangle(box,4.f); + g.setColour(active?accent:ink);g.setFont(11.f); + g.drawText(typeNames[i],box,juce::Justification::centred); + } + for(int i=0;i<5;++i) { + const juce::Rectangle box(48.f+i*67.f,static_cast(y+32),63.f,25.f); + const bool active=static_cast(b.route)==i; + g.setColour(active?juce::Colour(0xff255060):juce::Colour(0xff202832)); + g.fillRoundedRectangle(box,4.f); + g.setColour(active?accent:ink);g.setFont(11.f); + g.drawText(routeNames[i],box,juce::Justification::centred); + } + g.setColour(juce::Colour(0xff738799));g.setFont(10.f); + g.drawText("Cut slope: wheel on node",juce::Rectangle( + 410,y+33,getWidth()-450,22),juce::Justification::centredRight); +} +bool ArSonEQEditor::modeClick(juce::Point pos) { + if(selected_<0) return false; + const int y=getHeight()-81; + for(int i=0;i<6;++i) + if(juce::Rectangle(48.f+i*84.f,static_cast(y),80.f,27.f).contains(pos)) { + setField(selected_,"type",static_cast(i));return true; + } + for(int i=0;i<5;++i) + if(juce::Rectangle(48.f+i*67.f,static_cast(y+32),63.f,25.f).contains(pos)) { + setField(selected_,"route",static_cast(i));return true; + } + return false; +} +int ArSonEQEditor::hitBand(juce::Point pos) const { + for(int i=arson::eq::kMaxBands-1;i>=0;--i) { + const auto& b=cached_[static_cast(i)]; + if(!b.enabled) continue; + const auto x=xForHz(b.frequency), y=yForDb( + b.type==arson::eq::Type::LowCut||b.type==arson::eq::Type::HighCut?0:b.gainDb); + if(std::hypot(pos.x-x,pos.y-y)<13.f) return i; + } + return -1; +} +void ArSonEQEditor::setField(int slot,const char* field,float value,bool gesture) { + if(slot<0) return; + if(auto* p=processor_.parameters.getParameter(ArSonEQAudioProcessor::parameterId(slot,field))) { + if(gesture) p->beginChangeGesture(); + p->setValueNotifyingHost(p->convertTo0to1(value)); + if(gesture) p->endChangeGesture(); + } + timerCallback(); +} +void ArSonEQEditor::beginDrag() { + if(dragging_<0||gestureOpen_) return; + for(const char* field:{"freq","gain"}) + if(auto* p=processor_.parameters.getParameter( + ArSonEQAudioProcessor::parameterId(dragging_,field))) p->beginChangeGesture(); + gestureOpen_=true; +} +void ArSonEQEditor::endDrag() { + if(!gestureOpen_) return; + for(const char* field:{"freq","gain"}) + if(auto* p=processor_.parameters.getParameter( + ArSonEQAudioProcessor::parameterId(dragging_,field))) p->endChangeGesture(); + gestureOpen_=false; +} +void ArSonEQEditor::mouseDown(const juce::MouseEvent& e) { + const auto pos=e.position; + if(modeClick(pos)) return; + selected_=hitBand(pos);dragging_=selected_; + if(dragging_>=0) beginDrag(); + repaint(); +} +void ArSonEQEditor::mouseDrag(const juce::MouseEvent& e) { + if(dragging_<0 || !gestureOpen_) return; + setField(dragging_,"freq",static_cast(hzForX(e.position.x)),false); + const auto t=cached_[static_cast(dragging_)].type; + if(t!=arson::eq::Type::LowCut&&t!=arson::eq::Type::HighCut) + setField(dragging_,"gain",static_cast(dbForY(e.position.y)),false); +} +void ArSonEQEditor::mouseUp(const juce::MouseEvent&) { + endDrag(); dragging_=-1; +} +void ArSonEQEditor::mouseDoubleClick(const juce::MouseEvent& e) { + if(!graph().contains(e.position)) return; + const auto hit=hitBand(e.position); + if(hit>=0) { + setField(hit,"enabled",0.f);if(selected_==hit) selected_=-1; + } else { + for(int i=0;i(i)].enabled) continue; + setField(i,"type",0.f); + setField(i,"freq",static_cast(hzForX(e.position.x))); + setField(i,"gain",static_cast(dbForY(e.position.y))); + setField(i,"q",1.f); + setField(i,"route",0.f); + setField(i,"enabled",1.f); + selected_=i;break; + } + } + repaint(); +} +bool ArSonEQEditor::keyPressed(const juce::KeyPress& k) { + if(selected_<0) return false; + if(k==juce::KeyPress::deleteKey||k==juce::KeyPress::backspaceKey) { + setField(selected_,"enabled",0.f);selected_=-1;return true; + } + return false; +} +void ArSonEQEditor::mouseWheelMove(const juce::MouseEvent& e, + const juce::MouseWheelDetails& wheel) { + const auto hit=hitBand(e.position); + const int slot=hit>=0?hit:selected_; + if(slot<0) return; + const auto& b=cached_[static_cast(slot)]; + if(b.type==arson::eq::Type::LowCut||b.type==arson::eq::Type::HighCut) { + const int slope=std::clamp((b.slope/12-1)+(wheel.deltaY>0?1:-1),0,3); + setField(slot,"slope",static_cast(slope)); + } else { + setField(slot,"q",static_cast( + std::clamp(b.q*(wheel.deltaY>0?1.15:1/1.15),0.1,24.0))); + } +} diff --git a/Source/PluginEditor.h b/Source/PluginEditor.h new file mode 100644 index 0000000..139dc0a --- /dev/null +++ b/Source/PluginEditor.h @@ -0,0 +1,53 @@ +#pragma once +#include +#include +#include +#include "PluginProcessor.h" + +class ArSonEQEditor final : public juce::AudioProcessorEditor, private juce::Timer { +public: + explicit ArSonEQEditor(ArSonEQAudioProcessor&); + ~ArSonEQEditor() override; + void paint(juce::Graphics&) override; + void resized() override; + void mouseDown(const juce::MouseEvent&) override; + void mouseDrag(const juce::MouseEvent&) override; + void mouseUp(const juce::MouseEvent&) override; + void mouseDoubleClick(const juce::MouseEvent&) override; + bool keyPressed(const juce::KeyPress&) override; + void mouseWheelMove(const juce::MouseEvent&,const juce::MouseWheelDetails&) override; +private: + void timerCallback() override; + void updateSpectrum(); + void drawSpectrum(juce::Graphics&,juce::Rectangle); + void rebuildResponseCurves(); + juce::Rectangle graph() const; + int hitBand(juce::Point) const; + float xForHz(double) const; + float yForDb(double) const; + double hzForX(float) const; + double dbForY(float) const; + void setField(int slot,const char* field,float value,bool withGesture=true); + void beginDrag(); + void endDrag(); + void drawModeButtons(juce::Graphics&); + bool modeClick(juce::Point); + ArSonEQAudioProcessor& processor_; + arson::eq::Engine graphEngine_; + std::array cached_{}; + static constexpr int fftOrder_=12; + static constexpr int fftSize_=1< preHistory_{},postHistory_{},preRightHistory_{}, + postRightHistory_{},window_{}; + std::array prePower_{},postPower_{}; + std::array fftPre_{},fftPost_{}; + std::array levelsPre_{},levelsPost_{}; + size_t historyPosition_=0; + uint64_t framesSeen_=0; + bool spectrumReady_=false; + juce::Path curveLeft_,curveRight_,curveCrossfeed_; + int selected_=-1,dragging_=-1; + bool gestureOpen_=false; + JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ArSonEQEditor) +}; diff --git a/Source/PluginProcessor.cpp b/Source/PluginProcessor.cpp new file mode 100644 index 0000000..ffdbdea --- /dev/null +++ b/Source/PluginProcessor.cpp @@ -0,0 +1,245 @@ +#include "PluginProcessor.h" +#include "PluginEditor.h" +#if JUCE_WINDOWS +#include "WebEditor.h" +#endif +#include + +juce::String ArSonEQAudioProcessor::parameterId(int band, const char* field) { + return "b" + juce::String(band).paddedLeft('0', 2) + "_" + field; +} + +juce::AudioProcessorValueTreeState::ParameterLayout ArSonEQAudioProcessor::makeLayout() { + juce::AudioProcessorValueTreeState::ParameterLayout layout; + const juce::StringArray types{"Bell","Low Shelf","High Shelf","Low Cut","High Cut","Notch", + "Band Pass","Tilt Shelf","Flat Tilt"}; + const juce::StringArray routes{"Stereo","Left","Right","Mid","Side"}; + const juce::StringArray slopes{"12 dB/oct","24 dB/oct","36 dB/oct","48 dB/oct"}; + juce::NormalisableRange freq(20.0f, 20000.0f); + freq.setSkewForCentre(1000.0f); + for (int i=0; i(id("enabled"),name+"Enabled",false)); + layout.add(std::make_unique(id("type"),name+"Type",types,0)); + layout.add(std::make_unique(id("route"),name+"Route",routes,0)); + layout.add(std::make_unique(id("freq"),name+"Frequency",freq,1000.0f)); + layout.add(std::make_unique(id("gain"),name+"Gain", + juce::NormalisableRange(-24.0f,24.0f,0.01f),0.0f)); + layout.add(std::make_unique(id("q"),name+"Q", + juce::NormalisableRange(0.1f,24.0f,0.0f,0.35f),1.0f)); + layout.add(std::make_unique(id("slope"),name+"Cut Slope",slopes,0)); + // Append new IDs; never renumber legacy b00..b23 filter controls. + layout.add(std::make_unique(id("dynRange"),name+"Dynamic Range", + juce::NormalisableRange(-12.0f,12.0f,0.01f),0.f)); + layout.add(std::make_unique(id("dynThreshold"),name+"Dynamic Threshold", + juce::NormalisableRange(-60.f,0.f,0.1f),-24.f)); + } + return layout; +} + +ArSonEQAudioProcessor::ArSonEQAudioProcessor() +: AudioProcessor(BusesProperties() + .withInput("Input",juce::AudioChannelSet::stereo(),true) + .withOutput("Output",juce::AudioChannelSet::stereo(),true)), + parameters(*this,nullptr,"PARAMETERS",makeLayout()) { + for (int i=0;i(i)]; + p.enabled=parameters.getRawParameterValue(parameterId(i,"enabled")); + p.type=parameters.getRawParameterValue(parameterId(i,"type")); + p.route=parameters.getRawParameterValue(parameterId(i,"route")); + p.freq=parameters.getRawParameterValue(parameterId(i,"freq")); + p.gain=parameters.getRawParameterValue(parameterId(i,"gain")); + p.q=parameters.getRawParameterValue(parameterId(i,"q")); + p.slope=parameters.getRawParameterValue(parameterId(i,"slope")); + p.dynRange=parameters.getRawParameterValue(parameterId(i,"dynRange")); + p.dynThreshold=parameters.getRawParameterValue(parameterId(i,"dynThreshold")); + jassert(p.enabled && p.type && p.route && p.freq && p.gain && p.q && p.slope + && p.dynRange && p.dynThreshold); + } + engine_.prepare(48000.0); +} +bool ArSonEQAudioProcessor::isBusesLayoutSupported(const BusesLayout& layout) const { + const auto in=layout.getMainInputChannelSet(); + return (in==juce::AudioChannelSet::mono() || in==juce::AudioChannelSet::stereo()) + && layout.getMainOutputChannelSet()==in; +} +void ArSonEQAudioProcessor::prepareToPlay(double rate,int) { + preparedRate_.store(rate,std::memory_order_relaxed); + engine_.prepare(rate); + syncBands(); + engine_.reset(); // initial state takes effect without fade-in +} +arson::eq::Band ArSonEQAudioProcessor::readBand(int i) const noexcept { + arson::eq::Band b; + if (i<0 || i>=arson::eq::kMaxBands) return b; + const auto& p=raw_[static_cast(i)]; + b.enabled=p.enabled->load(std::memory_order_relaxed)>0.5f; + b.type=static_cast(static_cast(std::lround(p.type->load(std::memory_order_relaxed)))); + b.route=static_cast(static_cast(std::lround(p.route->load(std::memory_order_relaxed)))); + b.frequency=p.freq->load(std::memory_order_relaxed); + b.gainDb=p.gain->load(std::memory_order_relaxed); + b.q=p.q->load(std::memory_order_relaxed); + b.slope=12*(1+static_cast(std::lround(p.slope->load(std::memory_order_relaxed)))); + b.dynamicRangeDb=p.dynRange->load(std::memory_order_relaxed); + b.thresholdDb=p.dynThreshold->load(std::memory_order_relaxed); + return b; +} +void ArSonEQAudioProcessor::syncBands() noexcept { + for (int i=0;i +void ArSonEQAudioProcessor::processAudio(juce::AudioBuffer& audio) { + juce::ScopedNoDenormals noDenormals; + syncBands(); + const int channels=audio.getNumChannels(),frames=audio.getNumSamples(); + if (channels<1) return; + const bool tap=analyzer_.isEnabled(); + auto* left=audio.getWritePointer(0); + if (channels==1) { + for (int s=0;s(x); + engine_.processMono(x);left[s]=static_cast(x); + if (tap) analyzer_.push(before,static_cast(x)); + } + } else { + auto* right=audio.getWritePointer(1); + for (int s=0;s(l):0.f; + const float preR=tap?static_cast(r):0.f; + engine_.process(l,r); + left[s]=static_cast(l);right[s]=static_cast(r); + if (tap) analyzer_.push(preL,preR,static_cast(l),static_cast(r)); + } + for (int ch=2;ch(band)].store(engine_.dynamicActivity(band), + std::memory_order_relaxed); +} +void ArSonEQAudioProcessor::processBlock(juce::AudioBuffer& b,juce::MidiBuffer&) { processAudio(b); } +void ArSonEQAudioProcessor::processBlock(juce::AudioBuffer& b,juce::MidiBuffer&) { processAudio(b); } +void ArSonEQAudioProcessor::getStateInformation(juce::MemoryBlock& destination) { + auto state=parameters.copyState(); + state.setProperty("arsoneq_schema",2,nullptr); + if (auto xml=state.createXml()) copyXmlToBinary(*xml,destination); +} +void ArSonEQAudioProcessor::setStateInformation(const void* data,int size) { + if (auto xml=getXmlFromBinary(data,size)) { + if (xml->hasTagName(parameters.state.getType().toString())) { + parameters.replaceState(juce::ValueTree::fromXml(*xml)); + currentPreset_=-1; + } + } +} +juce::AudioProcessorEditor* ArSonEQAudioProcessor::createEditor() { +#if JUCE_WINDOWS + // Prefer MaSonKuPik-inspired zero-framework WebView2 GUI. Never force + // Internet Explorer as a fallback; retain the proven JUCE native editor. + if (ArSonEQWebEditor::supported()) + return new ArSonEQWebEditor(*this); +#endif + return new ArSonEQEditor(*this); +} + +namespace { +struct FactoryBand { + int slot; int type; double hz,gain,q; int route=0; double dyn=0,thr=-24; +}; +void applyValue(juce::AudioProcessorValueTreeState& state,int slot, + const char* field,float value) { + auto* p=state.getParameter(ArSonEQAudioProcessor::parameterId(slot,field)); + if(!p)return; + p->beginChangeGesture(); + p->setValueNotifyingHost(p->convertTo0to1(value)); + p->endChangeGesture(); +} +} // namespace + +juce::String ArSonEQAudioProcessor::presetName(int index) { + static const char* labels[]{ + "Init / Flat","Clean Vocal","Vocal Presence","Warm Vocal", + "De-Esser Dynamic","Tight Kick","Balanced Master","Air & Sparkle", + "User 01","User 02","User 03","User 04", + "User 05","User 06","User 07","User 08" + }; + return index>=0&&index=presetCount)return false; + const auto file=userPresetFile(index); + if(file.getParentDirectory().createDirectory().failed())return false; + auto state=parameters.copyState(); + state.setProperty("arsoneq_schema",2,nullptr); + auto xml=state.createXml(); + if(xml==nullptr)return false; + const bool ok=xml->writeTo(file); + if(ok)currentPreset_=index; + return ok; +} +bool ArSonEQAudioProcessor::loadPreset(int index) { + if(index<0||index>=presetCount)return false; + if(index>=factoryPresetCount) { + const auto file=userPresetFile(index); + if(!file.existsAsFile()||file.getSize()>256*1024)return false; + const auto xml=juce::XmlDocument::parse(file); + if(xml==nullptr||!xml->hasTagName(parameters.state.getType().toString()))return false; + const auto tree=juce::ValueTree::fromXml(*xml); + if(!tree.isValid())return false; + parameters.replaceState(tree); + currentPreset_=index; + return true; + } + // Reset to a neutral, deterministic set before applying selected recipe. + // All changes are on the message thread; audio callback only reads atomics. + for(int i=0;i(b.type)); + applyValue(parameters,b.slot,"freq",static_cast(b.hz)); + applyValue(parameters,b.slot,"gain",static_cast(b.gain)); + applyValue(parameters,b.slot,"q",static_cast(b.q)); + applyValue(parameters,b.slot,"route",static_cast(b.route)); + applyValue(parameters,b.slot,"dynRange",static_cast(b.dyn)); + applyValue(parameters,b.slot,"dynThreshold",static_cast(b.thr)); + }; + switch(index) { + case 0: break; // flat + case 1: add({0,3,75,0,0.707});add({1,0,260,-2.2,1.1});add({2,0,3400,1.7,.9});break; + case 2: add({0,3,85,0,.707});add({1,0,310,-2.5,1.2}); + add({2,0,2800,2.5,.95});add({3,2,11000,1.5,.65});break; + case 3: add({0,1,140,2.2,.7});add({1,0,320,-1.8,1.15}); + add({2,2,9600,1.2,.65});break; + case 4: add({0,3,90,0,.707});add({1,0,6800,0,3.0,0,-7,-34}); + add({2,0,3100,1.,.9});break; + case 5: add({0,3,30,0,.707});add({1,0,65,2.5,1.2}); + add({2,0,290,-3.0,1.3});add({3,0,3600,1.5,.9});break; + case 6: add({0,1,80,1.0,.7});add({1,0,260,-1.1,1.0}); + add({2,0,2700,0.8,.85});add({3,2,13500,1.3,.7});break; + case 7: add({0,3,75,0,.707});add({1,2,14000,2.8,.7}); + add({2,0,4900,1.4,.8});break; + default:break; + } + currentPreset_=index; + return true; +} + +juce::AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new ArSonEQAudioProcessor(); } diff --git a/Source/PluginProcessor.h b/Source/PluginProcessor.h new file mode 100644 index 0000000..ec02617 --- /dev/null +++ b/Source/PluginProcessor.h @@ -0,0 +1,76 @@ +#pragma once +#include +#include +#include +#include "DSP/ParametricEQ.h" +#include "DSP/AnalyzerQueue.h" + +class ArSonEQAudioProcessor final : public juce::AudioProcessor { +public: + ArSonEQAudioProcessor(); + ~ArSonEQAudioProcessor() override = default; + const juce::String getName() const override { return "ArSonEQ"; } + void prepareToPlay(double sampleRate, int samplesPerBlock) override; + void releaseResources() override {} + void processBlock(juce::AudioBuffer&, juce::MidiBuffer&) override; + void processBlock(juce::AudioBuffer&, juce::MidiBuffer&) override; + bool supportsDoublePrecisionProcessing() const override { return true; } + bool isBusesLayoutSupported(const BusesLayout& layouts) const override; + juce::AudioProcessorEditor* createEditor() override; + bool hasEditor() const override { return true; } + double getTailLengthSeconds() const override { return 0; } + bool acceptsMidi() const override { return false; } + bool producesMidi() const override { return false; } + bool isMidiEffect() const override { return false; } + int getNumPrograms() override { return 1; } + int getCurrentProgram() override { return 0; } + void setCurrentProgram(int) override {} + const juce::String getProgramName(int) override { return {}; } + void changeProgramName(int, const juce::String&) override {} + void getStateInformation(juce::MemoryBlock&) override; + void setStateInformation(const void*, int) override; + + static juce::String parameterId(int band, const char* field); + arson::eq::Band readBand(int index) const noexcept; + // Presets owned by native JUCE, never by volatile WebView localStorage. + static constexpr int factoryPresetCount=8, userPresetCount=8; + static constexpr int presetCount=factoryPresetCount+userPresetCount; + static juce::String presetName(int index); + bool loadPreset(int index); // GUI/message thread only + bool saveUserPreset(int index); // 8..15 only, never audio thread + int currentPreset() const noexcept { return currentPreset_; } + void setPresetModified() noexcept { currentPreset_=-1; } + double configuredSampleRate() const noexcept { return preparedRate_.load(std::memory_order_relaxed); } + juce::AudioProcessorValueTreeState parameters; + arson::eq::AnalyzerQueue& analyzer() noexcept { return analyzer_; } + // GUI-only telemetry: block-latched native dynamic wet values, never UI timers/FFT + // inside processBlock. Relaxed atomic read/write is sufficient for meters. + float dynamicActivity(int band) const noexcept { + return band>=0&&band(band)].load(std::memory_order_relaxed):0.f; + } + +private: + struct ParamRefs { + std::atomic* enabled = nullptr; + std::atomic* type = nullptr; + std::atomic* route = nullptr; + std::atomic* freq = nullptr; + std::atomic* gain = nullptr; + std::atomic* q = nullptr; + std::atomic* slope = nullptr; + std::atomic* dynRange = nullptr; + std::atomic* dynThreshold = nullptr; + }; + static juce::AudioProcessorValueTreeState::ParameterLayout makeLayout(); + void syncBands() noexcept; + template void processAudio(juce::AudioBuffer&); + std::array raw_{}; + arson::eq::Engine engine_; + arson::eq::AnalyzerQueue analyzer_; + std::atomic preparedRate_{48000.0}; + std::array,arson::eq::kMaxBands> dynamics_{}; + int currentPreset_=-1; + juce::File userPresetFile(int slot) const; + JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ArSonEQAudioProcessor) +}; diff --git a/Source/WebEditor.cpp b/Source/WebEditor.cpp new file mode 100644 index 0000000..7fa72f8 --- /dev/null +++ b/Source/WebEditor.cpp @@ -0,0 +1,467 @@ +#include "WebEditor.h" +#include +#include +#include + +namespace { +constexpr int graphPoints=256; +constexpr int spectrumPoints=arson::eq::SpectrumDisplay::points; +constexpr double lowest=20.0,highest=20000.0; + +juce::var makeObject() { return juce::var(new juce::DynamicObject()); } +void property(juce::var& object,const char* key,juce::var value) { + object.getDynamicObject()->setProperty(juce::Identifier(key),std::move(value)); +} +juce::WebBrowserComponent::Options browserOptions( + std::function command, + std::function(const juce::String&)> resource) { + using Web=juce::WebBrowserComponent; + const auto cache=juce::File::getSpecialLocation(juce::File::tempDirectory) + .getChildFile("ArSonEQ-WebView2"); + return Web::Options{} + .withBackend(Web::Options::Backend::webview2) + .withWinWebView2Options(Web::Options::WinWebView2{} + .withUserDataFolder(cache) + .withStatusBarDisabled() + .withBackgroundColour(juce::Colour(0xff0b0f16))) + .withNativeIntegrationEnabled() + .withEventListener("eq-command",[command=std::move(command)](juce::var message) { + command(message); + }) + .withResourceProvider(std::move(resource)); +} +} // namespace + +bool ArSonEQWebEditor::supported() { + // Do not silently fall back to legacy Internet Explorer: it can't run this + // modern Canvas UI and would expose a blank / broken editor. + using Web=juce::WebBrowserComponent; + if(juce::SystemStats::getEnvironmentVariable( + "ARSONEQ_USE_NATIVE_GUI","")=="1") + return false; + return Web::areOptionsSupported(Web::Options{} + .withBackend(Web::Options::Backend::webview2)); +} + +std::optional +ArSonEQWebEditor::resource(const juce::String& url) { + const char* ptr=nullptr; + int length=0; + juce::String mime; + if(url=="/"||url=="/index.html") { + ptr=BinaryData::index_html;length=BinaryData::index_htmlSize;mime="text/html; charset=utf-8"; + } else if(url=="/style.css") { + ptr=BinaryData::style_css;length=BinaryData::style_cssSize;mime="text/css; charset=utf-8"; + } else if(url=="/app.js") { + ptr=BinaryData::app_js;length=BinaryData::app_jsSize;mime="text/javascript; charset=utf-8"; + } else return std::nullopt; + if(ptr==nullptr || length<=0) return std::nullopt; + juce::WebBrowserComponent::Resource result; + result.data.resize(static_cast(length)); + std::memcpy(result.data.data(),ptr,static_cast(length)); + result.mimeType=mime; + return result; +} +ArSonEQWebEditor::ArSonEQWebEditor(ArSonEQAudioProcessor& p) + : AudioProcessorEditor(p),processor_(p), + browser_(browserOptions( + [this](const juce::var& message){ onCommand(message); }, + [](const juce::String& url){ return resource(url); })) { + setOpaque(true); + browser_.onLoaded=[this] { + pageLoaded_=true; + if(ready_)sendState(true); + }; + addAndMakeVisible(browser_); + setResizable(true,true); + // Full-canvas EQ fits a normal DAW floating plugin window (~Pro-Q aspect). + setResizeLimits(760,455,1360,850); + graphEngine_.prepare(p.configuredSampleRate()); + levelsPre_.fill(-120.f); + levelsPost_.fill(-120.f); + prepareWindow(); + lastAnalysisTick_=juce::Time::getMillisecondCounter(); + setSize(900,535); + processor_.analyzer().setEnabled(true); + browser_.goToURL(juce::WebBrowserComponent::getResourceProviderRoot()); + startTimerHz(25); +} +ArSonEQWebEditor::~ArSonEQWebEditor() { + stopTimer(); + processor_.analyzer().setEnabled(false); + for(int i=0;i(i)][static_cast(j)]) + if(auto* param=processor_.parameters.getParameter( + ArSonEQAudioProcessor::parameterId(i,j==0?"freq":j==1?"gain":"q"))) + param->endChangeGesture(); +} +void ArSonEQWebEditor::resized() { browser_.setBounds(getLocalBounds()); } + +void ArSonEQWebEditor::setField(int id,const char* field,float value) { + if(id<0||id>=arson::eq::kMaxBands||!std::isfinite(value))return; + if(auto* param=processor_.parameters.getParameter( + ArSonEQAudioProcessor::parameterId(id,field))) { + const float normal=param->convertTo0to1(value); + param->beginChangeGesture(); + param->setValueNotifyingHost(normal); + param->endChangeGesture(); + } +} +void ArSonEQWebEditor::edit(int id,const juce::String& field,float value,bool useGesture) { + if(id<0||id>=arson::eq::kMaxBands||!std::isfinite(value))return; + const char* key=nullptr; + if(field=="freq") {key="freq";value=juce::jlimit(20.f,20000.f,value);} + else if(field=="gain") {key="gain";value=juce::jlimit(-24.f,24.f,value);} + else if(field=="q") {key="q";value=juce::jlimit(.1f,24.f,value);} + else if(field=="type") {key="type";value=std::round(juce::jlimit(0.f,8.f,value));} + else if(field=="dynRange") {key="dynRange";value=juce::jlimit(-12.f,12.f,value);} + else if(field=="dynThreshold") {key="dynThreshold";value=juce::jlimit(-60.f,0.f,value);} + else if(field=="route") {key="route";value=std::round(juce::jlimit(0.f,4.f,value));} + else if(field=="slope") {key="slope";value=std::round(juce::jlimit(0.f,3.f,value));} + else if(field=="enabled") {key="enabled";value=value>.5f?1.f:0.f;} + if(!key)return; // strict field allow-list, no arbitrary host parameter access + if(auto* param=processor_.parameters.getParameter( + ArSonEQAudioProcessor::parameterId(id,key))) { + processor_.setPresetModified(); + if(useGesture)param->beginChangeGesture(); + param->setValueNotifyingHost(param->convertTo0to1(value)); + if(useGesture)param->endChangeGesture(); + } +} +void ArSonEQWebEditor::gesture(int id,const juce::var& fields,bool begin) { + if(id<0||id>=arson::eq::kMaxBands||!fields.isArray())return; + for(const auto& item:*fields.getArray()) { + const auto field=item.toString(); + const int n=field=="freq"?0:field=="gain"?1:field=="q"?2:-1; + if(n<0)continue; + auto& current=gestures_[static_cast(id)][static_cast(n)]; + if(current==begin)continue; + if(auto* param=processor_.parameters.getParameter( + ArSonEQAudioProcessor::parameterId(id,n==0?"freq":n==1?"gain":"q"))) { + if(begin)param->beginChangeGesture(); + else param->endChangeGesture(); + current=begin; + } + } +} +void ArSonEQWebEditor::onCommand(const juce::var& message) { + if(!message.isObject())return; + const auto kind=message.getProperty("kind",{}).toString(); + if(kind=="ready") { + ready_=true; + if(pageLoaded_)sendState(true); + return; + } + if(kind=="presetLoad" || kind=="presetSave") { + const int index=static_cast(message.getProperty("index",-1)); + const bool ok=kind=="presetLoad"? + processor_.loadPreset(index):processor_.saveUserPreset(index); + auto reply=makeObject(); + property(reply,"ok",ok); + property(reply,"operation",kind); + property(reply,"index",index); + property(reply,"name",ArSonEQAudioProcessor::presetName(index)); + browser_.emitEventIfBrowserIsVisible("eq-preset-result",reply); + if(ok) { selected_=-1;sendState(true); } + return; + } + if(kind=="spectrum") { + analyzerVisible_=static_cast(message.getProperty("enabled",true)); + processor_.analyzer().setEnabled(analyzerVisible_); + if(!analyzerVisible_) { + arson::eq::MeterFrame old; + while(processor_.analyzer().pop(old)) {} + framesSeen_=0;framesSinceFFT_=0; + } + return; + } + if(kind=="analyzerSettings") { + const auto field=message.getProperty("field",{}).toString(); + const auto value=message.getProperty("value",0); + const int v=static_cast(value); + if(field=="fft" && v>=10 && v<=13) { + fftOrder_=v;prepareWindow();framesSinceFFT_=0; + levelsPre_.fill(-120.f);levelsPost_.fill(-120.f); + } else if(field=="speed" && v>=0 && v<=2) speed_=v; + else if(field=="range" && (v==60||v==90||v==120)) range_=v; + else if(field=="tilt" && (static_cast(value)==0. || + static_cast(value)==3. || + static_cast(value)==4.5 || + static_cast(value)==6.)) + tilt_=static_cast(static_cast(value)); + else if(field=="freeze")freeze_=static_cast(value); + else if(field=="pre")showPre_=static_cast(value); + else if(field=="post")showPost_=static_cast(value); + return; + } + // Bounded message-thread transactions: one IPC command for an entire + // multi-band frame, never any work on the real-time audio callback. + if(kind=="bulkEdit") { + const auto values=message.getProperty("entries",{}); + if(!values.isArray()||values.getArray()->size()>168)return; + const bool useGesture=static_cast(message.getProperty("gesture",true)); + for(const auto& item:*values.getArray()) { + if(!item.isObject())continue; + const int slot=static_cast(item.getProperty("id",-1)); + const auto field=item.getProperty("field",{}).toString(); + const float value=static_cast(static_cast(item.getProperty("value",0.))); + edit(slot,field,value,useGesture); + } + return; + } + if(kind=="gestureMany") { + const auto values=message.getProperty("items",{}); + if(!values.isArray()||values.getArray()->size()>arson::eq::kMaxBands)return; + const bool begin=static_cast(message.getProperty("begin",false)); + for(const auto& item:*values.getArray()) { + if(!item.isObject())continue; + const int slot=static_cast(item.getProperty("id",-1)); + gesture(slot,item.getProperty("fields",{}),begin); + } + return; + } + const int id=static_cast(message.getProperty("id",-1)); + if(kind=="select") { + selected_=id>=0&&id( + static_cast(message.getProperty("value",0.0))); + edit(id,message.getProperty("field",{}).toString(),value, + static_cast(message.getProperty("gesture",true))); + } else if(kind=="add") { + const float freq=static_cast(static_cast(message.getProperty("freq",1000.0))); + const float gain=static_cast(static_cast(message.getProperty("gain",0.0))); + if(id<0||id>=arson::eq::kMaxBands)return; + setField(id,"type",0.f);setField(id,"route",0.f); + setField(id,"q",1.f);setField(id,"slope",0.f); + edit(id,"freq",freq,true);edit(id,"gain",gain,true); + edit(id,"dynRange",0.f,true);edit(id,"dynThreshold",-24.f,true); + edit(id,"enabled",1.f,true); + selected_=id; + sendState(true); + } +} +void ArSonEQWebEditor::sendState(bool response) { + if(!ready_||!pageLoaded_)return; + auto value=makeObject(); + property(value,"rate",processor_.configuredSampleRate()); + juce::Array bands; + for(int i=0;i(b.type)); + property(item,"route",static_cast(b.route)); + property(item,"freq",b.frequency); + property(item,"gain",b.gainDb); + property(item,"q",b.q); + property(item,"slope",arson::eq::stageCount(b.slope)-1); + property(item,"dynRange",b.dynamicRangeDb); + property(item,"dynThreshold",b.thresholdDb); + bands.add(std::move(item)); + } + property(value,"bands",std::move(bands)); + property(value,"presetIndex",processor_.currentPreset()); + juce::Array presets; + for(int i=0;i l,r,c,b; + for(int i=0;i(i)/(graphPoints-1)); + const auto matrix=graphEngine_.matrixResponse(hz); + const auto db=[](const std::complex& v) { + return juce::jlimit(-120.0,40.0,20.0*std::log10( + std::max(1.0e-20,std::abs(v)))); + }; + l.add(db(matrix.ll));r.add(db(matrix.rr)); + c.add(db(matrix.lr)); + b.add(selected_>=0?graphEngine_.bandResponseDb(selected_,hz):0.0); + } + property(curves,"l",std::move(l)); + property(curves,"r",std::move(r)); + property(curves,"cross",std::move(c)); + property(curves,"band",std::move(b)); + property(value,"curve",std::move(curves)); + } + browser_.emitEventIfBrowserIsVisible("eq-state",value); +} +void ArSonEQWebEditor::prepareWindow() { + // Window construction is a one-shot editor/configuration operation, not + // 4 * FFT-size trigonometry on every 25 Hz paint/update. + const int N=1<::pi*i/(N-1))); + window_[static_cast(i)]=w; + sum+=w; + } + coherentAmplitude_=std::max(1.,sum*0.5); +} +void ArSonEQWebEditor::sendSpectrum() { + arson::eq::MeterFrame f; + int drained=0; + float peakLeft=0.f,peakRight=0.f; + while(drained(arson::eq::AnalyzerQueue::capacity) && + processor_.analyzer().pop(f)) { + samples_[0][head_]=f.preL; + samples_[1][head_]=f.preR; + samples_[2][head_]=f.postL; + samples_[3][head_]=f.postR; + peakLeft=std::max(peakLeft,std::abs(f.postL)); + peakRight=std::max(peakRight,std::abs(f.postR)); + head_=(head_+1)&(maxSize_-1); + ++framesSeen_;++framesSinceFFT_;++drained; + } + // Sample peaks are from real native output, not synthetic UI levels. + peakL_=std::max(peakLeft,peakL_*0.82f); + peakR_=std::max(peakRight,peakR_*0.82f); + if(!ready_||!pageLoaded_||framesSeen_(1<(N)+static_cast(i))&(maxSize_-1); + fftScratch_[static_cast(i)]= + samples_[static_cast(channel)][pos]*window_[static_cast(i)]; + } + fft.performFrequencyOnlyForwardTransform(fftScratch_.data()); + std::copy_n(fftScratch_.data(),N/2+1,magnitudes_[static_cast(channel)].data()); + } + const auto sr=processor_.configuredSampleRate(); + const bool fast=speed_==0; + const auto smoothTime=elapsed*(speed_==2?0.46:1.0); + for(int i=0;i(i)]=arson::eq::SpectrumDisplay::smooth( + levelsPre_[static_cast(i)],targetPre,smoothTime,fast); + levelsPost_[static_cast(i)]=arson::eq::SpectrumDisplay::smooth( + levelsPost_[static_cast(i)],targetPost,smoothTime,fast); + } + } + juce::Array before,after; + for(int i=0;i(arson::eq::SpectrumDisplay::tilt( + levelsPre_[static_cast(i)],hz,tilt_))); + after.add(static_cast(arson::eq::SpectrumDisplay::tilt( + levelsPost_[static_cast(i)],hz,tilt_))); + } + auto snapshot=makeObject(); + property(snapshot,"pre",std::move(before)); + property(snapshot,"post",std::move(after)); + property(snapshot,"peakL",static_cast(peakL_)); + property(snapshot,"peakR",static_cast(peakR_)); + property(snapshot,"range",range_); + property(snapshot,"tilt",static_cast(tilt_)); + property(snapshot,"preVisible",showPre_); + property(snapshot,"postVisible",showPost_); + property(snapshot,"frozen",freeze_); + browser_.emitEventIfBrowserIsVisible("eq-spectrum",snapshot); +} + + +void ArSonEQWebEditor::sendDynamics(bool force) { + if(!ready_||!pageLoaded_)return; + const auto tick=juce::Time::getMillisecondCounter(); + // Prefer active streaming at <=20Hz; don't recompute a 256-point curve + // during every 25Hz UI message tick or when dynamics are unused. + if(!force && tick-lastDynamicsTick_<50)return; + lastDynamicsTick_=tick; + std::array wet{}; + bool any=false,changed=force; + juce::Array gains,activity; + const double sr=processor_.configuredSampleRate(); + for(int i=0;i(i)]; + const bool active=b.enabled && std::abs(b.dynamicRangeDb)>0.0001 && + (b.type==arson::eq::Type::Bell || + b.type==arson::eq::Type::LowShelf || + b.type==arson::eq::Type::HighShelf); + const auto v=active?juce::jlimit(0.f,1.f,processor_.dynamicActivity(i)):0.f; + wet[static_cast(i)]=v; + any|=active; + changed|=std::abs(v-lastDynamicActivity_[static_cast(i)])>0.006f; + activity.add(v); + double deltaDb=0.; + if(active&&v>0.0001f) { + // True complex response of the interpolated dynamic filter at + // this band's own frequency (not a fabricated animated meter). + const auto c=arson::eq::coefficients(b.type,b.frequency,b.dynamicRangeDb,b.q,sr); + const auto z=std::polar(1.,-2.*arson::eq::kPi*b.frequency/sr); + const auto z2=z*z; + const auto dynH=(c.b0+c.b1*z+c.b2*z2)/(1.+c.a1*z+c.a2*z2); + deltaDb=20.*std::log10(std::max(1.e-20,std::abs(1.+double(v)*(dynH-1.)))); + } + gains.add(deltaDb); + } + if(!any&&!hadDynamicBands_)return; + changed|=(any!=hadDynamicBands_); + if(!changed)return; + hadDynamicBands_=any; + lastDynamicActivity_=wet; + auto payload=makeObject(); + property(payload,"active",any); + property(payload,"activity",std::move(activity)); + property(payload,"gainDb",std::move(gains)); + if(any) { + juce::Array l,r; + for(int i=0;i& c) { + return juce::jlimit(-120.,40.,20.*std::log10(std::max(1.e-20,std::abs(c)))); + }; + l.add(db(matrix.ll)); + r.add(db(matrix.rr)); + } + property(payload,"l",std::move(l)); + property(payload,"r",std::move(r)); + } + browser_.emitEventIfBrowserIsVisible("eq-dynamics",payload); +} + +void ArSonEQWebEditor::timerCallback() { + bool changed=false; + const auto rate=processor_.configuredSampleRate(); + if(graphEngine_.sampleRate()!=rate) { + graphEngine_.prepare(rate);changed=true; + } + for(int i=0;i(i)],b)) { + cache_[static_cast(i)]=b; + graphEngine_.setBand(i,b); + changed=true; + } + } + if(changed)sendState(true); + // Dynamic curve must animate even when analyzer FFT is switched OFF. + sendDynamics(changed); + if(analyzerVisible_)sendSpectrum(); +} diff --git a/Source/WebEditor.h b/Source/WebEditor.h new file mode 100644 index 0000000..84f1423 --- /dev/null +++ b/Source/WebEditor.h @@ -0,0 +1,70 @@ +#pragma once +#include "PluginProcessor.h" +#include +#include +#include +#include "DSP/SpectrumDisplay.h" +#include + +// Local-only WebView2/C++ bridge. Audio remains completely native and unaware +// of its editor. No HTTP requests, Web Audio DSP, React, or JS in processBlock. +class ArSonEQWebEditor final : public juce::AudioProcessorEditor, + private juce::Timer { +public: + explicit ArSonEQWebEditor(ArSonEQAudioProcessor&); + ~ArSonEQWebEditor() override; + void resized() override; + static bool supported(); +private: + class LocalBrowser final : public juce::WebBrowserComponent { + public: + std::function onLoaded; + void pageFinishedLoading(const juce::String&) override { + if(onLoaded)onLoaded(); + } + explicit LocalBrowser(const juce::WebBrowserComponent::Options& options) + : juce::WebBrowserComponent(options) {} + bool pageAboutToLoad(const juce::String& url) override { + return url.startsWith(getResourceProviderRoot()); + } + }; + static std::optional resource(const juce::String&); + void onCommand(const juce::var&); + void edit(int, const juce::String&, float, bool gesture); + void gesture(int, const juce::var&, bool begin); + void setField(int, const char*, float); + void sendState(bool response); + void sendSpectrum(); + void sendDynamics(bool force=false); + void prepareWindow(); + void timerCallback() override; + static constexpr int maxSize_=8192; + static constexpr int points_=arson::eq::SpectrumDisplay::points; + ArSonEQAudioProcessor& processor_; + LocalBrowser browser_; + arson::eq::Engine graphEngine_; + std::array cache_{}; + std::array,arson::eq::kMaxBands> gestures_{}; + juce::dsp::FFT fft10_{10},fft11_{11},fft12_{12},fft13_{13}; + // Fixed native UI-side storage, 4 real channels: PreL, PreR, PostL, PostR. + std::array,4> samples_{}; + std::array window_{}; + double coherentAmplitude_=1.; + std::array fftScratch_{}; + std::array,4> magnitudes_{}; + std::array levelsPre_{},levelsPost_{}; + size_t head_=0; + uint64_t framesSeen_=0; + int framesSinceFFT_=0,fftOrder_=12,speed_=1,range_=90; + float tilt_=4.5f,peakL_=0.f,peakR_=0.f; + bool freeze_=false,showPre_=true,showPost_=true; + juce::uint32 lastAnalysisTick_=0; + std::array lastDynamicActivity_{}; + bool hadDynamicBands_=false; + juce::uint32 lastDynamicsTick_=0; + int selected_=-1; + bool analyzerVisible_=true; + bool ready_=false; + bool pageLoaded_=false; + JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ArSonEQWebEditor) +}; \ No newline at end of file diff --git a/WebUI/app.js b/WebUI/app.js new file mode 100644 index 0000000..d5b5c5a --- /dev/null +++ b/WebUI/app.js @@ -0,0 +1,799 @@ +/* ArSonEQ Studio web canvas. Adapted interaction vocabulary from user's MaSonKuPik EQ. + * WebView contains NO audio DSP, no Web Audio, no libraries, no network requests. + * Backend owns authoritative host parameters and transfer functions. + */ +(() => { +"use strict"; +const $=id=>document.getElementById(id); +const canvas=$("eqCanvas"), wrap=$("graphWrap"), ctx=canvas.getContext("2d",{alpha:false}); +const TYPES=["Bell","Low Shelf","High Shelf","Low Cut","High Cut","Notch","Band Pass","Tilt Shelf","Flat Tilt"]; +const COLORS=["#ff9473","#e5b855","#a99aff","#77d5a4","#53ccd2","#b58eea","#eb87a9","#78b6e9"]; +const F0=20,F1=20000,MAX=24,RIGHT_RAIL=63; +let rangeDb=12; +const plotWidth=width=>Math.max(1,width-RIGHT_RAIL); +const clamp=(x,a,b)=>Math.max(a,Math.min(b,x)); +const hzX=(f,width)=>Math.log(clamp(f,F0,F1)/F0)/Math.log(F1/F0)*plotWidth(width); +const xHz=(x,width)=>F0*Math.pow(F1/F0,clamp(x/plotWidth(width),0,1)); +const dbY=(v,h)=>h*0.5-clamp(v,-rangeDb,rangeDb)/rangeDb*h*0.5; +const yDb=(y,h)=>clamp((h*0.5-y)/(h*0.5)*rangeDb,-rangeDb,rangeDb); +const isCut=t=>t===3||t===4; +const hasGain=t=>!isCut(t)&&t!==5&&t!==6; +const isFiniteNumber=n=>typeof n==="number"&&Number.isFinite(n); +const noteFor=hz=>{if(!isFiniteNumber(hz)||hz<=0)return "—";const midi=Math.round(69+12*Math.log2(hz/440));return ["C","C♯","D","D♯","E","F","F♯","G","G♯","A","A♯","B"][(midi+1200)%12]+(Math.floor(midi/12)-1);}; +const backend=window.__JUCE__?.backend; +let bands=Array.from({length:MAX},(_,i)=>({id:i,enabled:false,type:0,route:0,freq:1000,gain:0,q:1,slope:0,dynRange:0,dynThreshold:-24})); +let presetNames=[],activePreset=-1,presetBusy=false; +let dynamicState={active:false,l:[],r:[],activity:Array(24).fill(0),gainDb:Array(24).fill(0)}; +let curves={l:[],r:[],cross:[],band:[]},spec={pre:[],post:[],range:90,peakL:0,peakR:0,preVisible:true,postVisible:true},samplerate=48000; +let selected=-1,hovered=-1,showSpectrum=true,dragging=null,pendingDrag=null,lastValidPick=null; +const selection=new Set(),history=[],redoHistory=[]; +const FIELDS=["enabled","type","route","freq","gain","q","slope","dynRange","dynThreshold"]; +let editSnapshot=null,historyReplay=false; +const snapshot=()=>bands.map(b=>FIELDS.map(f=>b[f])); +const refreshUndo=()=>{$("undoBtn").disabled=!history.length;$("redoBtn").disabled=!redoHistory.length;}; +const beginEdit=()=>{if(!editSnapshot&&!historyReplay)editSnapshot=snapshot();}; +const finishEdit=()=>{ + if(!editSnapshot)return; + const after=snapshot(),before=editSnapshot;editSnapshot=null; + if(after.some((v,i)=>v.some((x,j)=>x!==before[i][j]))){ + history.push({before,after});if(history.length>64)history.shift(); + redoHistory.length=0; + } + refreshUndo(); +}; +const undoRedo=undo=>{ + if(dragging||editSnapshot)return; + const src=undo?history:redoHistory,dst=undo?redoHistory:history; + const entry=src.pop();if(!entry)return; + const values=undo?entry.before:entry.after,changes=[]; + historyReplay=true; + values.forEach((row,id)=>row.forEach((value,k)=>{ + const field=FIELDS[k]; + if(bands[id][field]!==value){bands[id][field]=value;changes.push({id,field,value});} + })); + historyReplay=false; + if(changes.length)emit({kind:"bulkEdit",entries:changes,gesture:true}); + dst.push(entry);refreshUndo();renderInspector();renderRail();placeInspector();changed(); +}; +let w=1,h=1,dpr=1,dirty=false,connected=false,hasSpectrum=false; +const emit=payload=>{if(backend?.emitEvent)backend.emitEvent("eq-command",payload);}; +const changed=()=>{if(!dirty){dirty=true;requestAnimationFrame(()=>{dirty=false;draw();});}}; +const col=i=>COLORS[i%COLORS.length]; +const active=()=>bands.map((b,i)=>b.enabled?i:-1).filter(i=>i>=0); +const updateBandLocal=(id,field,value)=>{ + if(id<0||id>=MAX||!Number.isFinite(value))return; + bands[id][field]=value; + renderInspector();changed(); +}; +const setParam=(id,field,value,gesture=true)=>{ + if(!Number.isFinite(value)||id<0||id>=MAX||!FIELDS.includes(field))return; + if(bands[id][field]===value)return; + if(gesture)beginEdit(); + updateBandLocal(id,field,value); + if(activePreset>=0){activePreset=-1;$("presetSelect").value="-1";} + emit({kind:"edit",id,field,value,gesture}); + if(gesture)finishEdit(); +}; +const placeInspector=()=>{ + const card=$("inspector"); + if(card.hidden||selected<0)return; + const height=card.classList.contains("expanded")?Math.min(142,h-40):70; + const width=Math.min(484,Math.max(270,plotWidth(w)-28)); + const b=bands[selected],x=hzX(b.freq,w),y=dbY(isCut(b.type)?0:b.gain,h); + let left=clamp(x-width*.5,12,Math.max(12,plotWidth(w)-width-12)); + let top=h-height-13; + if(y>=top-20){ + if(y-height-27>=35)top=y-height-27; + else if(y+height+27{ + const id=(i>=0&&i=0){ + if(selection.has(id))selection.delete(id);else selection.add(id); + selected=selection.size?[...selection].at(-1):-1; + }else{selected=id;selection.clear();if(id>=0)selection.add(id);} + $("bandList").hidden=true;$("quickHelp").hidden=true; + emit({kind:"select",id:selected}); + renderInspector();renderRail();placeInspector();changed(); +}; +const addBand=(x,y)=>{ + const idx=bands.findIndex(b=>!b.enabled); + if(idx<0)return; + beginEdit(); + const freq=xHz(x,w),gain=yDb(y,h); + bands[idx]={...bands[idx],enabled:true,type:0,route:0,freq,gain,q:1,slope:0,dynRange:0,dynThreshold:-24}; + emit({kind:"add",id:idx,freq,gain}); + select(idx);finishEdit(); +}; +const removeSelected=()=>{ + if(selected<0)return; + beginEdit(); + const entries=[...selection].filter(id=>bands[id]?.enabled).map(id=>({id,field:"enabled",value:0})); + for(const e of entries)bands[e.id].enabled=false; + if(entries.length)emit({kind:"bulkEdit",entries,gesture:true}); + select(-1);finishEdit(); +}; +const bandHit=(x,y)=>{ + let choice=-1,best=16*16; + for(let i=0;if>=1000?(f/1000).toFixed(f%1000===0?0:1)+"k":Math.round(f)+""; +const number=n=>Number.isFinite(n)?n.toFixed(1):"—"; +const renderRail=()=>{ + const list=active(); + $("bandCount").textContent=list.length+" / 24"; + const rail=$("bandRail");rail.replaceChildren(); + for(const i of list){ + const chip=document.createElement("button"); + chip.type="button";chip.className="band-chip on"+(selected===i?" selected":""); + chip.style.setProperty("--chip",col(i)); + chip.textContent=(selection.has(i)?"◆ ":"")+String(i+1).padStart(2,"0")+" · "+formatHz(bands[i].freq); + chip.onclick=e=>select(i,!!(e.ctrlKey||e.metaKey));rail.appendChild(chip); + } +}; +const renderInspector=()=>{ + const b=selected>=0?bands[selected]:null; + $("inspector").hidden=!b; + $("emptyInspector").hidden=true; + $("bandInspector").hidden=!b; + if(!b)return; + $("activeLabel").textContent=["STEREO","LEFT","RIGHT","MID","SIDE"][b.route]||"STEREO"; + $("bandTitle").textContent=(selection.size>1?selection.size+" BANDS · ":"BAND ")+ + String(selected+1).padStart(2,"0"); + $("bandDot").style.background=col(selected); + $("enableBtn").textContent=b.enabled?"● ON":"○ OFF"; + $("enableBtn").classList.toggle("off",!b.enabled); + $("typeSelect").value=String(b.type); + $("typeButton").textContent=TYPES[b.type]||"Bell"; + $("slopeSelect").value=String(b.slope); + const setValue=(id,v)=>{const input=$(id);if(document.activeElement!==input)input.value=String(v);}; + setValue("freqInput",Math.round(b.freq*10)/10); + setValue("gainInput",Math.round(b.gain*100)/100); + setValue("qInput",Math.round(b.q*100)/100); + $("gainInput").disabled=!hasGain(b.type); + $("gainKnob").style.opacity=$("gainInput").disabled?".35":"1"; + $("slopeSelect").disabled=!isCut(b.type); + $("noteLabel").textContent=noteFor(b.freq); + $("typeGlyph").textContent=["⌒","◡","◠","╱","╲","⌄","◇","⇅","↕"][b.type]||"⌒"; + $("shapePicker").querySelectorAll("button").forEach(btn=> + btn.classList.toggle("active",Number(btn.dataset.shape)===b.type)); + const dynamicOK=b.type===0||b.type===1||b.type===2; + $("dynRangeInput").disabled=!dynamicOK; + $("dynThresholdInput").disabled=!dynamicOK; + setValue("dynRangeInput",Math.round((b.dynRange||0)*10)/10); + setValue("dynThresholdInput",Math.round((b.dynThreshold??-24)*10)/10); + updateDynamicMeter(); + const knobAngle=(v,min,max,log=false)=>{ + const t=log?(Math.log(v/min)/Math.log(max/min)):(v-min)/(max-min); + return (-140+280*clamp(t,0,1)).toFixed(1)+"deg"; + }; + $("freqKnob").style.setProperty("--angle",knobAngle(b.freq,20,20000,true)); + $("gainKnob").style.setProperty("--angle",knobAngle(b.gain,-24,24)); + $("qKnob").style.setProperty("--angle",knobAngle(b.q,.1,24,true)); + $("routeGroup").querySelectorAll("button").forEach(btn=> + btn.classList.toggle("active",Number(btn.dataset.route)===b.route)); + // Inspector is a fixed-geometry compositor overlay, not a flex child. +}; +const updateDynamicMeter=()=>{ + const b=selected>=0?bands[selected]:null; + if(!b)return; + const eligible=(b.type===0||b.type===1||b.type===2)&&Math.abs(b.dynRange)>0.01; + const gain=eligible?(dynamicState.gainDb?.[selected]||0):0; + const activity=eligible?(dynamicState.activity?.[selected]||0):0; + $("dynStatus").textContent=eligible?(gain>0?"+":"")+gain.toFixed(1)+" dB":"OFF"; + $("dynStatus").classList.toggle("active",eligible&&activity>0.015); + $("dynMeterFill").style.width=(100*clamp(activity,0,1)).toFixed(1)+"%"; +}; +const mapLocal=e=>{const r=canvas.getBoundingClientRect();return{x:clamp(e.clientX-r.left,0,plotWidth(r.width)),y:clamp(e.clientY-r.top,0,r.height)};}; +// Canvas renderer: only native DSP response data are graphed. No JS biquads. +const responsePath=arr=>{ + const pathWidth=plotWidth(w); + if(!arr||arr.length<2)return false; + ctx.beginPath(); + for(let i=0;i{ + const staticCurve=curves.l; + if(!staticCurve?.length||staticCurve.length<2)return; + const live=dynamicState.active && dynamicState.l?.length===staticCurve.length; + const arr=live?dynamicState.l:staticCurve; + const baseline=h*.5,pw=plotWidth(w); + // Boost and attenuation each get an independently clipped fill. + // The underlying music spectrum remains visible through both layers. + const fillHalf=(upper)=>{ + ctx.save(); + ctx.beginPath(); + if(upper){ctx.moveTo(0,0);ctx.lineTo(pw,0);ctx.lineTo(pw,baseline);ctx.lineTo(0,baseline);} + else {ctx.moveTo(0,baseline);ctx.lineTo(pw,baseline);ctx.lineTo(pw,h);ctx.lineTo(0,h);} + ctx.closePath();ctx.clip(); + if(responsePath(arr)){ + ctx.lineTo(pw,baseline);ctx.lineTo(0,baseline);ctx.closePath(); + const grad=ctx.createLinearGradient(0,upper?0:baseline,0,upper?baseline:h); + if(upper){ + grad.addColorStop(0,"rgba(102,218,123,.24)"); + grad.addColorStop(1,"rgba(64,185,103,.06)"); + }else{ + grad.addColorStop(0,"rgba(171,120,59,.13)"); + grad.addColorStop(1,"rgba(160,79,79,.23)"); + } + ctx.fillStyle=grad;ctx.fill(); + } + ctx.restore(); + }; + fillHalf(true);fillHalf(false); + if(live){ + // Static reference is deliberately subdued; live effective IIR response + // comes from native DSP activity (no fake sound-reactive animation). + if(responsePath(staticCurve)){ + ctx.strokeStyle="#c2a4788f";ctx.lineWidth=1.05;ctx.stroke(); + } + const pw=plotWidth(w); + ctx.beginPath(); + arr.forEach((v,i)=>{const x=i*pw/(arr.length-1),y=dbY(v,h); + if(!i)ctx.moveTo(x,y);else ctx.lineTo(x,y);}); + for(let i=staticCurve.length-1;i>=0;--i){ + ctx.lineTo(i*pw/(staticCurve.length-1),dbY(staticCurve[i],h)); + } + ctx.closePath();ctx.fillStyle="rgba(161,90,202,.27)";ctx.fill(); + } + ctx.lineWidth=2.1;ctx.strokeStyle=live?"#f4d57d":"#f0cc6b";ctx.lineJoin="round"; + ctx.shadowBlur=3;ctx.shadowColor="#ecb84f69"; + if(responsePath(arr))ctx.stroke(); + ctx.shadowBlur=0; + const rightCurve=live?dynamicState.r:curves.r; + const differ=arr?.length===rightCurve?.length && + arr.some((v,i)=>Math.abs(v-rightCurve[i])>.15); + if(differ){ + ctx.strokeStyle="#75d7d7";ctx.lineWidth=1.2; + if(responsePath(rightCurve))ctx.stroke(); + } +}; +const drawSelectedBand=()=>{ + if(selected<0||!bands[selected]?.enabled||!curves.band?.length)return; + if(responsePath(curves.band)){ + ctx.strokeStyle=col(selected);ctx.globalAlpha=.78; + ctx.lineWidth=1.2;ctx.stroke();ctx.globalAlpha=1; + } +}; +// Spectrum values are real C++ FFT dBFS with visualization-only tilt. +const spectrumY=value=>{ + const range=spec.range===60||spec.range===120?spec.range:90; + return h*(1-clamp(value/range+1,0,1)); +}; +const spectrumPath=values=>{ + if(!values?.length)return false; + ctx.beginPath(); + const pw=plotWidth(w); + for(let i=0;i{ + if(!spectrumPath(values))return; + const pw=plotWidth(w); + if(fill){ + ctx.lineTo(pw,h);ctx.lineTo(0,h);ctx.closePath(); + const grad=ctx.createLinearGradient(0,0,0,h); + grad.addColorStop(0,"rgba(200,200,211,.28)"); + grad.addColorStop(.52,"rgba(158,160,171,.20)"); + grad.addColorStop(1,"rgba(88,92,106,.11)"); + ctx.fillStyle=grad;ctx.fill(); + } + if(spectrumPath(values)){ + ctx.strokeStyle=fill?"#c3c4cc88":"#959dad9c"; + ctx.lineWidth=fill?1.25:.9;ctx.stroke(); + } +}; +const drawMeters=()=>{ + const right=plotWidth(w),x=right+9,trackH=h-38,yTop=12,barW=9; + const peak=[spec.peakL||0,spec.peakR||0]; + for(let channel=0;channel<2;++channel){ + const bx=x+channel*12; + ctx.fillStyle="#101822";ctx.fillRect(bx,yTop,barW,trackH); + const level=clamp((20*Math.log10(Math.max(peak[channel],1.e-8))+90)/90,0,1); + const height=trackH*level; + const grad=ctx.createLinearGradient(0,yTop+trackH,0,yTop); + grad.addColorStop(0,"#4acfa3");grad.addColorStop(.80,"#dfca61");grad.addColorStop(1,"#e66664"); + ctx.fillStyle=grad;ctx.fillRect(bx,yTop+trackH-height,barW,height); + ctx.fillStyle="#a5b4c0";ctx.font="9px Consolas,monospace";ctx.textAlign="center"; + ctx.fillText(channel===0?"L":"R",bx+barW/2,h-7); + } +}; +const draw=()=>{ + if(w<2||h<2)return; + const pw=plotWidth(w); + ctx.save();ctx.setTransform(dpr,0,0,dpr,0,0); + ctx.fillStyle="#17151c";ctx.fillRect(0,0,w,h); + const ground=ctx.createLinearGradient(0,0,0,h); + ground.addColorStop(0,"#211d27");ground.addColorStop(.55,"#1d1b22");ground.addColorStop(1,"#151a24"); + ctx.fillStyle=ground;ctx.fillRect(0,0,pw,h); + ctx.fillStyle="#0f141c";ctx.fillRect(pw,0,w-pw,h); + ctx.font="10px Consolas,monospace"; + for(const hz of [20,30,40,50,70,100,200,300,500,700,1000,2000,3000,5000,7000,10000,20000]){ + const x=hzX(hz,w); + const major=[20,100,1000,10000].includes(hz); + ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,h); + ctx.lineWidth=major?.9:.5;ctx.strokeStyle=major?"#403a46":"#302d36";ctx.stroke(); + if([30,50,100,200,500,1000,2000,5000,10000,20000].includes(hz)){ + ctx.textAlign="center";ctx.fillStyle="#98919e"; + ctx.fillText(formatHz(hz),clamp(x,18,pw-35),h-8); + } + } + const tickStep=rangeDb<=15?3:6; + for(let db=-rangeDb;db<=rangeDb;db+=tickStep){ + const y=dbY(db,h); + ctx.beginPath();ctx.moveTo(0,y);ctx.lineTo(pw,y); + ctx.lineWidth=db===0?1.25:.65; + ctx.strokeStyle=db===0?"#987b4b":"#37313b";ctx.stroke(); + ctx.textAlign="right";ctx.font="10px Consolas,monospace"; + ctx.fillStyle=db===0?"#f0c86d":"#a9a0a8"; + ctx.fillText((db>0?"+":"")+db,pw-6,clamp(y+3,13,h-17)); + } + // Right meter and analyzer level reference, physically separate from EQ dB gain axis. + const range=spec.range===60||spec.range===120?spec.range:90; + ctx.beginPath();ctx.moveTo(pw+.5,0);ctx.lineTo(pw+.5,h); + ctx.strokeStyle="#4a444d";ctx.stroke(); + ctx.textAlign="right";ctx.font="9px Consolas,monospace"; + for(let level=0;level>=-range;level-=20){ + const y=h*(-level)/range; + ctx.fillStyle="#838c98";ctx.fillText(String(level),w-5,clamp(y+5,13,h-22)); + } + if(showSpectrum){ + if(spec.postVisible!==false){ctx.globalAlpha=.89;drawSpectrum(spec.post,true);} + if(spec.preVisible!==false){ctx.globalAlpha=.72;drawSpectrum(spec.pre,false);} + ctx.globalAlpha=1; + } + drawMeters(); + drawSelectedBand(); + drawResponse(); + for(let i=0;i0.01? + (dynamicState.gainDb?.[i]||0):0; + const focus=selection.has(i)||hovered===i; + ctx.save(); + // Animated dynamic marker is separate from the STATIC draggable handle, + // so clicking it never moves the band or changes graph coordinates. + if(Math.abs(dynamicDelta)>0.08){ + const activeY=dbY(b.gain+dynamicDelta,h); + ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(x,activeY); + ctx.strokeStyle=col(i);ctx.lineWidth=2.0;ctx.globalAlpha=.8;ctx.stroke(); + ctx.beginPath();ctx.arc(x,activeY,3.3+wet*1.4,0,Math.PI*2); + ctx.fillStyle="#f8d77e";ctx.fill();ctx.globalAlpha=1; + } + ctx.shadowBlur=focus?9:3;ctx.shadowColor=col(i); + ctx.beginPath();ctx.arc(x,y,focus?6.2:5.4,0,Math.PI*2); + ctx.fillStyle=col(i);ctx.fill(); + ctx.shadowBlur=0;ctx.lineWidth=focus?2:1.5; + ctx.strokeStyle="#e7e3df";ctx.stroke(); + ctx.beginPath();ctx.arc(x,y,focus?8.8:7.3,0,Math.PI*2); + ctx.strokeStyle=focus?"#e9e6df91":"#ffffff20";ctx.lineWidth=.9;ctx.stroke(); + if(focus){ + ctx.textAlign="center";ctx.font="10px Consolas,monospace"; + ctx.fillStyle="#f0ece8";ctx.fillText(String(i+1),x,Math.max(19,y-16)); + } + ctx.restore(); + } + ctx.restore(); +}; +const resize=()=>{ + const r=wrap.getBoundingClientRect(),oldW=w,oldH=h; + w=Math.max(1,r.width);h=Math.max(1,r.height); + dpr=Math.min(2,window.devicePixelRatio||1); + const cw=Math.max(1,Math.round(w*dpr)),ch=Math.max(1,Math.round(h*dpr)); + if(canvas.width!==cw||canvas.height!==ch){canvas.width=cw;canvas.height=ch;} + if(oldW!==w||oldH!==h){placeInspector();changed();} +}; +new ResizeObserver(resize).observe(wrap); +window.addEventListener("resize",resize); +const updatePresetMenu=()=>{ + const menu=$("presetMenu"); + if(!menu||menu.children.length===presetNames.length+1){ + if(menu)for(let i=0;i{ + const index=pos-1,button=document.createElement("button"); + button.type="button";button.dataset.index=String(index); + button.textContent=name; + button.classList.toggle("selected",index===activePreset); + button.onclick=()=>{ + hidePresetMenu(); + if(index>=0)presets.load(index); + }; + menu.appendChild(button); + }); +}; +const hidePresetMenu=()=>{ + $("presetMenu").hidden=true; + $("presetButton").setAttribute("aria-expanded","false"); +}; +const hideTypeMenu=()=>{ + $("typeMenu").hidden=true; + $("typeButton").setAttribute("aria-expanded","false"); +}; +const hideExtraMenus=()=>{hidePresetMenu();hideTypeMenu();}; +function applyHostState(data){ + if(!data||!Array.isArray(data.bands)||data.bands.length!==MAX)return; + connected=true;samplerate=isFiniteNumber(data.rate)?data.rate:samplerate; + bands=data.bands.map((b,i)=>({ + id:i,enabled:!!b.enabled,type:clamp(b.type|0,0,8),route:clamp(b.route|0,0,4), + freq:clamp(Number(b.freq)||1000,20,20000),gain:clamp(Number(b.gain)||0,-24,24), + q:clamp(Number(b.q)||1,.1,24),slope:clamp(b.slope|0,0,3), + dynRange:clamp(Number(b.dynRange)||0,-12,12), + dynThreshold:clamp(Number(b.dynThreshold??-24),-60,0) + })); + if(dragging)for(const [id,v] of dragging.values){ + if(bands[id]){bands[id].freq=v.freq;bands[id].gain=v.gain;} + } + if(data.curve)curves=data.curve; + // Invalidates stale live response while C++ detector/filter topology changes. + dynamicState={...dynamicState,active:false,l:[],r:[]}; + // Match Pro-EQ style 12 dB default range, but expand if actual host gain + // exceeds 12 dB so handles/response are never silently clipped. + const peak=Math.max(0,...bands.filter(b=>b.enabled).map(b=>Math.abs(b.gain)), + ...(curves.l||[]).map(Math.abs),...(curves.r||[]).map(Math.abs)); + rangeDb=clamp(Math.ceil((peak+1)/3)*3,12,24); + $("stateInfo").textContent="24 BANDS / "+(samplerate/1000).toFixed(1)+" kHz / ZERO LATENCY"; + $("bridgeStatus").textContent="NATIVE DSP CONNECTED"; + if(Array.isArray(data.presets)&&data.presets.length){ + presetNames=data.presets.map(String); + if($("presetSelect").options.length!==presetNames.length+1){ + $("presetSelect").replaceChildren(); + const custom=document.createElement("option");custom.value="-1";custom.textContent="Custom / Init"; + $("presetSelect").appendChild(custom); + presetNames.forEach((name,index)=>{ + const option=document.createElement("option"); + option.value=String(index);option.textContent=name; + $("presetSelect").appendChild(option); + }); + } + } + activePreset=Number.isInteger(data.presetIndex)?data.presetIndex:-1; + $("presetSelect").value=String(activePreset); + $("presetButton").textContent=activePreset>=0?(presetNames[activePreset]||"Custom / Init"):"Custom / Init"; + updatePresetMenu(); + renderInspector();renderRail();if(!dragging)placeInspector();changed(); +} +function applyDynamics(data){ + if(!data||!Array.isArray(data.activity)||data.activity.length!==MAX)return; + if(data.active && (!Array.isArray(data.l)||!Array.isArray(data.r)))return; + dynamicState={active:!!data.active, + l: data.active?data.l:[],r:data.active?data.r:[], + activity:data.activity.map(v=>clamp(Number(v)||0,0,1)), + gainDb:Array.isArray(data.gainDb)?data.gainDb.map(v=>Number(v)||0):Array(MAX).fill(0)}; + updateDynamicMeter();changed(); +} +function applySpectrum(data){ + if(!data||!Array.isArray(data.pre)||!Array.isArray(data.post))return; + spec=data;hasSpectrum=true;if(showSpectrum)changed(); +} +if(backend?.addEventListener){ + backend.addEventListener("eq-state",applyHostState); + backend.addEventListener("eq-spectrum",applySpectrum); + backend.addEventListener("eq-dynamics",applyDynamics); + emit({kind:"ready"}); +}else{ + $("bridgeStatus").textContent="WEB PREVIEW MODE — NO AUDIO ENGINE"; + curves.l=Array(256).fill(0);curves.r=Array(256).fill(0); +} +// Native-style right click: actions operate on real host parameters. +const hideContext=()=>{$("bandContextMenu").hidden=true;}; +canvas.addEventListener("contextmenu",e=>{ + e.preventDefault(); + const p=mapLocal(e),id=bandHit(p.x,p.y); + if(id>=0&&!selection.has(id))select(id); + const menu=$("bandContextMenu"); + const rect={width:184,height:185}; + menu.style.left=clamp(p.x,8,Math.max(8,plotWidth(w)-rect.width-8))+"px"; + menu.style.top=clamp(p.y,28,Math.max(28,h-rect.height-8))+"px"; + menu.dataset.x=String(p.x);menu.dataset.y=String(p.y); + menu.querySelectorAll("button").forEach(btn=>{ + if(btn.dataset.eqMenu==="add")btn.hidden=id>=0; + else if(["edit","toggle","remove"].includes(btn.dataset.eqMenu))btn.hidden=id<0; + }); + menu.hidden=false; +}); +$("bandContextMenu").addEventListener("click",e=>{ + const action=e.target.closest("[data-eq-menu]")?.dataset.eqMenu; + if(!action)return; + const menu=$("bandContextMenu"); + if(action==="edit"&&selected>=0){renderInspector();placeInspector();} + else if(action==="dynamic"&&selected>=0){ + const b=bands[selected]; + if(b.type===0||b.type===1||b.type===2){ + setParam(selected,"dynRange",Math.abs(b.dynRange)>0.01?0:-6); + $("inspector").classList.add("expanded"); + $("advancedBtn").textContent="LESS ▴";placeInspector(); + } + } + else if(action==="toggle"&&selected>=0){ + beginEdit(); + const entries=[...selection].map(id=>({id,field:"enabled",value:bands[id].enabled?0:1})); + for(const change of entries)bands[change.id].enabled=!!change.value; + emit({kind:"bulkEdit",entries,gesture:true}); + finishEdit();renderInspector();changed(); + }else if(action==="remove")removeSelected(); + else if(action==="add")addBand(Number(menu.dataset.x),Number(menu.dataset.y)); + else if(action==="all"){ + selection.clear();for(const id of active())selection.add(id); + selected=selection.size?[...selection].at(-1):-1; + emit({kind:"select",id:selected});renderInspector();renderRail();placeInspector();changed(); + } + hideContext(); +}); +canvas.addEventListener("pointerdown",e=>{ + hideContext();hideExtraMenus(); + if(e.button!==0)return; + const p=mapLocal(e),id=bandHit(p.x,p.y); + if(id<0){select(-1);return;} + lastValidPick={id,x:p.x,y:p.y,at:Date.now()}; + if(e.ctrlKey||e.metaKey){select(id,true);return;} + if(!selection.has(id))select(id); + else if(selected!==id){selected=id;emit({kind:"select",id});renderInspector();placeInspector();} + beginEdit(); + const ids=selection.has(id)?[...selection]:[id]; + const start=new Map(ids.map(i=>[i,{freq:bands[i].freq,gain:bands[i].gain}])); + const fields=ids.map(i=>({id:i,fields:["freq",...(hasGain(bands[i].type)?["gain"]:[])]})); + dragging={id,pointer:e.pointerId,x:p.x,y:p.y,start,values:new Map(start), + fields,group:ids.length>1,precision:!!e.shiftKey}; + canvas.setPointerCapture(e.pointerId); + if(ids.length===1)emit({kind:"begin",id,fields:fields[0].fields}); + else emit({kind:"gestureMany",begin:true,items:fields}); +}); +canvas.addEventListener("pointermove",e=>{ + const p=mapLocal(e); + $("hoverReadout").textContent=formatHz(xHz(p.x,w))+" Hz • "+noteFor(xHz(p.x,w))+" • "+number(yDb(p.y,h))+" dB"; + if(dragging&&dragging.pointer===e.pointerId){ + const d=dragging,precision=e.shiftKey||d.precision?0.17:1; + const dx=(p.x-d.x)*precision,dy=(p.y-d.y)*precision; + const ratio=Math.exp(dx/plotWidth(w)*Math.log(F1/F0)),delta=-dy/(h*.5)*rangeDb; + const entries=[]; + for(const [id,v] of d.start){ + const freq=clamp(v.freq*ratio,F0,F1); + const gain=!hasGain(bands[id].type)?v.gain:clamp(v.gain+delta,-24,24); + d.values.set(id,{freq,gain}); + bands[id].freq=freq;bands[id].gain=gain; + entries.push({id,field:"freq",value:freq}); + if(hasGain(bands[id].type))entries.push({id,field:"gain",value:gain}); + } + pendingDrag=entries; + if(!canvas.dataset.dragRaf){canvas.dataset.dragRaf="1";requestAnimationFrame(flushDrag);} + renderInspector();changed();return; + } + const hit=bandHit(p.x,p.y); + if(hit!==hovered){hovered=hit;changed();} + const tooltip=$("graphTooltip"); + if(hit>=0){ + const band=bands[hit]; + tooltip.textContent="B"+(hit+1)+" "+formatHz(band.freq)+" Hz "+number(band.gain)+" dB · Q "+number(band.q); + tooltip.style.left=clamp(p.x+14,10,w-190)+"px"; + tooltip.style.top=clamp(p.y-50,8,h-45)+"px";tooltip.hidden=false; + }else tooltip.hidden=true; +}); +const flushDrag=()=>{ + canvas.dataset.dragRaf=""; + if(!pendingDrag)return; + const entries=pendingDrag;pendingDrag=null; + if(dragging&&!dragging.group){ + for(const e of entries)emit({kind:"edit",...e,gesture:false}); + }else emit({kind:"bulkEdit",entries,gesture:false}); + renderRail(); +}; +const finishDrag=e=>{ + if(!dragging||dragging.pointer!==e.pointerId)return; + flushDrag(); + const d=dragging;dragging=null; + if(d.group)emit({kind:"gestureMany",begin:false,items:d.fields}); + else emit({kind:"end",id:d.id,fields:d.fields[0].fields}); + finishEdit();placeInspector();changed(); +}; +canvas.addEventListener("pointerup",finishDrag); +canvas.addEventListener("pointercancel",finishDrag); +canvas.addEventListener("pointerleave",()=>{hovered=-1;$("graphTooltip").hidden=true;changed();}); +canvas.addEventListener("dblclick",e=>{ + const p=mapLocal(e); + let id=bandHit(p.x,p.y); + // Coordinates remain stable; narrow fallback for double click hit testing. + if(id<0 && lastValidPick && Date.now()-lastValidPick.at<550 && + Math.hypot(p.x-lastValidPick.x,p.y-lastValidPick.y)<20) + id=lastValidPick.id; + lastValidPick=null; + if(id>=0){select(id);removeSelected();} + else addBand(p.x,p.y); +}); +canvas.addEventListener("wheel",e=>{ + const p=mapLocal(e),id=bandHit(p.x,p.y); + if(id<0)return; + e.preventDefault(); + const b=bands[id],direction=e.deltaY<0?1:-1; + if(isCut(b.type))setParam(id,"slope",clamp(b.slope+direction,0,3)); + else setParam(id,"q",clamp(b.q*Math.pow(1.14,direction),.1,24)); + if(!selection.has(id))select(id); +},{passive:false}); +const ctrl=(id,field,converter=Number)=>{ + $(id).addEventListener("change",()=>{ + if(selected<0)return;const v=converter($(id).value); + if(Number.isFinite(v))setParam(selected,field,v); + }); +}; +ctrl("typeSelect","type",Number);ctrl("slopeSelect","slope",Number); +ctrl("dynRangeInput","dynRange",v=>clamp(Number(v),-12,12)); +ctrl("dynThresholdInput","dynThreshold",v=>clamp(Number(v),-60,0)); +ctrl("freqInput","freq",v=>clamp(Number(v),20,20000)); +ctrl("gainInput","gain",v=>clamp(Number(v),-24,24)); +ctrl("qInput","q",v=>clamp(Number(v),.1,24)); +$("enableBtn").onclick=()=>{if(selected>=0)setParam(selected,"enabled",bands[selected].enabled?0:1);}; +$("removeBtn").onclick=removeSelected; +$("routeGroup").addEventListener("click",e=>{ + const btn=e.target.closest("[data-route]"); + if(selected>=0&&btn)setParam(selected,"route",Number(btn.dataset.route)); +}); +// A dark, original app-owned popup avoids WebView2's white native + + + + + +
+ +
+
+ + +
+ PARAMETRIC EQ + Double-click to add a band +
+
dB
+ + + + + + +
+
+
+ + + +
+ \ No newline at end of file diff --git a/WebUI/smoke.test.cjs b/WebUI/smoke.test.cjs new file mode 100644 index 0000000..f0e61a1 --- /dev/null +++ b/WebUI/smoke.test.cjs @@ -0,0 +1,186 @@ +// Zero-dependency smoke test of bundled WebUI startup and host-command bridge. +// Runs in Node using a minimal fake DOM/canvas. Catches regressions in real JS +// interaction wiring without building JUCE or opening a DAW. +const fs=require("node:fs"),vm=require("node:vm"),assert=require("node:assert/strict"); +const calls=[],handlers={},nodes={},windowEvents={}; +function element(id) { + if(nodes[id])return nodes[id]; + const events={},classes=new Set(); + const node={ + id,value:"",style:{setProperty(){}},className:"",textContent:"",hidden:false, + get options(){return this.children;}, + dataset:{},width:800,height:400,disabled:false,children:[], + classList:{ + toggle(name){if(classes.has(name)){classes.delete(name);return false;}classes.add(name);return true;}, + add(name){classes.add(name);},remove(name){classes.delete(name);}, + contains(name){return classes.has(name);} + }, + addEventListener(name,callback){events[name]=callback;}, + dispatch(name,payload){assert.ok(events[name],id+" has "+name);events[name](payload||{});}, + setAttribute(){}, + appendChild(child){this.children.push(child);return child;}, + replaceChildren(){this.children=[];}, + querySelectorAll(){return [0,1,2,3,4].map(i=>({ + dataset:{route:String(i)},classList:{toggle(){}} + }));}, + getBoundingClientRect(){return{left:0,top:0,width:800,height:400};}, + setPointerCapture(){}, + scrollIntoView(){}, + getContext(){return ctx;} + }; + return nodes[id]=node; +} +const ctx={ + fillRect(){},beginPath(){},moveTo(){},lineTo(){},stroke(){},fill(){}, + arc(){},closePath(){},clip(){},save(){},restore(){},fillText(){},setTransform(){}, + createLinearGradient(){return{addColorStop(){}};} +}; +const document={activeElement:null, + getElementById:element, + createElement:()=>element("created-"+Object.keys(nodes).length) +}; +const backend={ + addEventListener(name,fn){handlers[name]=fn;}, + emitEvent(name,data){calls.push({name,data});} +}; +const window={ + __JUCE__:{backend},devicePixelRatio:1, + addEventListener(name,fn){windowEvents[name]=fn;}, + requestAnimationFrame(fn){fn();} +}; +const sandbox={ + document,window,ResizeObserver:class{constructor(fn){this.fn=fn;}observe(){this.fn();}}, + requestAnimationFrame:fn=>fn(),console,Math,Array,Number,JSON,Set +}; +vm.runInNewContext(fs.readFileSync("WebUI/app.js","utf8"),sandbox,{timeout:2000,filename:"app.js"}); +const find=k=>calls.filter(x=>x.data.kind===k).map(x=>x.data); +assert.ok(find("ready").length,"JS announces ready to native engine"); +assert.equal(typeof handlers["eq-state"],"function"); +assert.equal(typeof handlers["eq-spectrum"],"function"); +const bands=Array.from({length:24},(_,i)=>({ + enabled:i<2,type:0,route:0,freq:i===0?1000:5000,gain:i===0?6:2,q:1,slope:0, + dynRange:0,dynThreshold:-24 +})); +const curve=Array(256).fill(0); +handlers["eq-state"]({bands,rate:48000,curve:{l:curve,r:curve,cross:curve,band:curve}, + presets:["Init / Flat","Clean Vocal","Vocal Presence","Warm Vocal","De-Esser Dynamic", + "Tight Kick","Balanced Master","Air & Sparkle","User 01","User 02","User 03", + "User 04","User 05","User 06","User 07","User 08"],presetIndex:-1}); +assert.ok(element("bridgeStatus").textContent.includes("CONNECTED"),"UI becomes connected"); +assert.ok(element("bandCount").textContent.includes("2 / 24"),"host band snapshot reflected"); +handlers["eq-spectrum"]({pre:Array(384).fill(-80),post:Array(384).fill(-75),range:90,peakL:0.2,peakR:0.15}); +element("eqCanvas").dispatch("pointerdown",{button:0,pointerId:1,clientX:431,clientY:100}); +assert.ok(find("begin").length,"host gesture starts on drag"); +assert.equal(element("inspector").hidden,false,"floating card opens on pointerdown without reflow"); +assert.ok(Number.parseFloat(element("inspector").style.left)>=0,"card is positioned inside the graph"); +assert.ok(element("inspector").style.top.endsWith("px"),"card uses absolute coordinates, no flex sizing"); +element("eqCanvas").dispatch("pointermove",{pointerId:1,clientX:500,clientY:170}); +element("eqCanvas").dispatch("pointerup",{pointerId:1}); +assert.ok(find("end").length,"host gesture ends after drag"); +assert.equal(element("inspector").hidden,false,"floating card remains visible after drag"); +const cardTop=element("inspector").style.top; +assert.ok(cardTop.endsWith("px"),"floating card has stable compositor position"); +assert.ok(find("edit").some(x=>x.field==="freq"),"drag automates frequency"); +element("qKnob").dispatch("pointerdown",{button:0,pointerId:25,clientY:120,preventDefault(){}}); +element("qKnob").dispatch("pointermove",{pointerId:25,clientY:98}); +element("qKnob").dispatch("pointerup",{pointerId:25}); +assert.ok(find("begin").some(x=>x.fields.includes("q")),"Q knob opens host automation gesture"); +assert.ok(find("edit").some(x=>x.field==="q"),"Q knob has actual editing behavior"); +assert.ok(find("end").some(x=>x.fields.includes("q")),"Q knob closes host automation gesture"); +// M3 native preset browser + filter discovery + real dynamic host params. +assert.equal(element("presetSelect").options.length,17,"native factory+user preset list visible"); +element("presetSelect").value="4";element("presetSelect").dispatch("change"); +assert.ok(find("presetLoad").some(x=>x.index===4),"factory preset triggers native load"); +element("saveSlot").value="9";element("savePreset").onclick(); +assert.ok(find("presetSave").some(x=>x.index===9),"user preset saves to chosen native slot"); +element("shapePicker").dispatch("click",{target:{closest(){return{dataset:{shape:"6"}};}}}); +assert.ok(find("edit").some(x=>x.field==="type"&&x.value===6),"Band Pass becomes real host parameter"); +element("shapePicker").dispatch("click",{target:{closest(){return{dataset:{shape:"0"}};}}}); +element("dynRangeInput").value="-6";element("dynRangeInput").dispatch("change"); +element("dynThresholdInput").value="-36";element("dynThresholdInput").dispatch("change"); +assert.ok(find("edit").some(x=>x.field==="dynRange"&&x.value===-6),"native dynamic range"); +assert.ok(find("edit").some(x=>x.field==="dynThreshold"&&x.value===-36),"native dynamic threshold"); +assert.equal(typeof handlers["eq-dynamics"],"function","native dynamic telemetry handler is registered"); +element("presetMenu").hidden=true; +element("presetButton").onclick(); +assert.equal(element("presetMenu").hidden,false,"preset list uses app-owned dark popover"); +assert.equal(element("presetMenu").children.length,17,"dark preset menu has all factory/user options"); +assert.ok(element("presetMenu").children[2].textContent.includes("Clean Vocal"),"real preset labels"); +element("presetButton").onclick(); +element("typeMenu").hidden=true; +element("typeButton").onclick(); +assert.equal(element("typeMenu").hidden,false,"filter shape uses app-owned dark popover"); +assert.equal(element("typeMenu").children.length,9,"dark EQ type menu includes all nine native shapes"); +element("typeMenu").children[1].onclick(); +assert.ok(find("edit").some(x=>x.field==="type"&&x.value===1),"custom filter menu controls native filter type"); +element("typeMenu").children[0].onclick(); +const activity=Array(24).fill(0);activity[0]=0.82; +const dynGain=Array(24).fill(0);dynGain[0]=-4.8; +handlers["eq-dynamics"]({active:true,activity,gainDb:dynGain, + l:Array(256).fill(-3.2),r:Array(256).fill(-3.2)}); +assert.equal(element("dynMeterFill").style.width,"82.0%","meter driven by real host activity"); +assert.ok(element("dynStatus").textContent.includes("-4.8"),"meter gain dB from host"); +handlers["eq-dynamics"]({active:false,activity:Array(24).fill(0),gainDb:Array(24).fill(0)}); +assert.equal(element("dynMeterFill").style.width,"0.0%","meter clears when dynamics are off"); + +element("analyzerMenu").hidden=true; +element("analyzerMenuBtn").onclick(); +assert.equal(element("analyzerMenu").hidden,false,"analyzer FFT options available"); +element("fftSelect").value="13";element("fftSelect").dispatch("change"); +assert.ok(find("analyzerSettings").some(x=>x.field==="fft"&&x.value===13),"native FFT resolution changes"); +element("freezeSpectrum").checked=true;element("freezeSpectrum").dispatch("change"); +assert.ok(find("analyzerSettings").some(x=>x.field==="freeze"&&x.value===true),"native analyzer freeze"); +element("advancedBtn").onclick(); +assert.ok(element("inspector").classList.contains("expanded"),"advanced controls are overlay, not layout"); +assert.ok(find("ready").length,"advanced editor toggle does not restart browser"); +element("advancedBtn").onclick(); +assert.ok(!element("inspector").classList.contains("expanded"),"quick panel closes without graph reflow"); +// Ctrl-select second band, then move both in a single bounded IPC frame. +element("eqCanvas").dispatch("pointerdown",{button:0,pointerId:3,clientX:589,clientY:167,ctrlKey:true}); +element("eqCanvas").dispatch("pointerdown",{button:0,pointerId:4,clientX:589,clientY:167}); +element("eqCanvas").dispatch("pointermove",{pointerId:4,clientX:609,clientY:154}); +element("eqCanvas").dispatch("pointerup",{pointerId:4}); +assert.ok(find("gestureMany").some(x=>x.begin===true),"group begins host gestures"); +assert.ok(find("gestureMany").some(x=>x.begin===false),"group closes host gestures"); +assert.ok(find("bulkEdit").some(x=>x.entries?.some(e=>e.id===0)&&x.entries?.some(e=>e.id===1)),"group edit batches multiple bands in one IPC event"); +assert.equal(element("inspector").hidden,false,"group edit keeps stable card visible"); +windowEvents.keydown({target:{matches(){return false;}},key:"z",ctrlKey:true,preventDefault(){}}); +assert.ok(find("bulkEdit").some(x=>x.gesture===true),"Ctrl+Z restores native host parameters with gesture"); +windowEvents.keydown({target:{matches(){return false;}},key:"y",ctrlKey:true,preventDefault(){}}); +assert.equal(element("redoBtn").disabled,true,"redo stack consumed"); +// Right-click is contextual, not a layout-sized modal. +element("eqCanvas").dispatch("contextmenu",{clientX:589,clientY:167,preventDefault(){}}); +assert.equal(element("bandContextMenu").hidden,false,"right-click menu is visible"); +assert.ok(element("bandContextMenu").style.top.endsWith("px"),"context menu is graph anchored"); +element("eqCanvas").dispatch("pointerdown",{button:0,pointerId:8,clientX:589,clientY:167,ctrlKey:true}); +assert.equal(element("bandContextMenu").hidden,true,"normal canvas interaction dismisses context menu"); + + +element("viewBtn").onclick(); +assert.ok(find("spectrum").some(x=>x.enabled===false),"spectrum switch gates native telemetry"); +element("viewBtn").onclick(); +assert.ok(find("spectrum").some(x=>x.enabled===true),"spectrum gate resumes native telemetry"); +element("eqCanvas").dispatch("dblclick",{clientX:100,clientY:300}); +assert.ok(find("add").length,"double click empty graph creates band"); +element("closeInspector").onclick(); +assert.equal(element("inspector").hidden,true,"close inspector frees entire graph"); +element("bandsBtn").onclick(); +assert.equal(element("bandList").hidden,false,"band list opens only when asked"); +element("helpBtn").onclick(); +assert.equal(element("bandList").hidden,true,"help and band menus are mutually exclusive"); +assert.equal(element("quickHelp").hidden,false,"help popover opens on demand"); +const markup=fs.readFileSync("WebUI/index.html","utf8"); +const style=fs.readFileSync("WebUI/style.css","utf8"); +assert.ok(markup.includes('class="graph-wrap"'),"graph wraps the canvas and card"); +assert.ok(markup.indexOf('id="inspector"')>markup.indexOf('id="quickHelp"'),"card comes after menus"); +assert.ok(markup.indexOf('id="inspector"')\n'),"card nested inside graphWrap, not in flex flow"); +assert.ok(style.includes(".inspector{position:absolute"),"card uses absolute overlay, no layout reflow"); +assert.ok(style.includes(".inspector.expanded{flex:none"),"expanded card stays outside flex layout"); +assert.ok(!style.includes("filter:brightness"),"no global hover GPU brightness filters"); +handlers["eq-state"]({bands,rate:48000,curve:{l:curve,r:curve,cross:curve,band:curve}}); +// Check host-originated gain beyond 12 dB no longer silently clips nodes. +const elevated=bands.map(x=>({...x})); +elevated[0].gain=18; +handlers["eq-state"]({bands:elevated,rate:48000,curve:{l:curve,r:curve,cross:curve,band:curve}}); +assert.ok(element("inspector").hidden,"host snapshots do not force the floating card open"); +console.log("ArSonEQ M2.5 smoke PASS: stable overlay, precision/group gestures, undo/redo, right-click, analyzer"); diff --git a/WebUI/style.css b/WebUI/style.css new file mode 100644 index 0000000..e332eb1 --- /dev/null +++ b/WebUI/style.css @@ -0,0 +1,291 @@ +/* ArSonEQ M2.3 - compact non-obscuring instrument deck. + Visual language: ArSonMix metal/glass; interaction language: professional + logarithmic EQ. No transitions, backdrop-filter, React or remote assets. */ +:root{color-scheme:dark;--glass:#151923;--graph:#19171f;--line:#37333f;--ink:#e7e9ec; + --sub:#98a0ad;--soft:#728092;--gold:#eac66f;--cyan:#64d8e8;--green:#6fd7a0; + --metal1:#78828d;--metal2:#333b46;--metal3:#141d27} +*{box-sizing:border-box} +html,body{width:100%;height:100%;margin:0;overflow:hidden;background:#0d1118;color:var(--ink); + font:11px "Segoe UI",Arial,sans-serif;user-select:none;-webkit-user-select:none} +button,select,input{font:inherit}button{cursor:pointer} +button:focus-visible,select:focus-visible,input:focus-visible{outline:1px solid #79d8e9;outline-offset:1px} +button:disabled,input:disabled,select:disabled{opacity:.43;cursor:default} +button:hover:not(:disabled){border-color:#91a4b5} +[hidden]{display:none!important} +#app{display:flex;flex-direction:column;width:100%;height:100%;min-width:700px;min-height:420px;background:#12151e} + +/* Short anodized-aluminum header. The user's music remains the hero. */ +.top{height:42px;flex:0 0 42px;display:flex;align-items:center;gap:10px;padding:0 12px; + background:linear-gradient(180deg,#363c47,#242a34 52%,#1b222d 53%,#202935); + border-bottom:1px solid #515463;box-shadow:inset 0 1px #626b78,0 2px 6px #0008;z-index:5} +.brand{display:flex;align-items:center;gap:6px;min-width:190px;white-space:nowrap} +.brand-glyph{font-size:20px;line-height:22px;font-weight:800;letter-spacing:-3px;color:#f5faff} +.brand-glyph span{color:#62dbed;font-size:9px;margin-left:2px} +.brand-name{font-size:19px;font-weight:760;letter-spacing:-1.3px;color:#f4f5f9} +.brand-name span{color:var(--cyan);font-weight:400} +.brand-separator{width:1px;height:18px;background:#58616c;margin:0 2px} +.brand-caption{font-size:8px;letter-spacing:1.2px;color:#a1a7b0} +.preset-center{min-width:160px;max-width:300px;flex:1;height:24px;display:flex; + align-items:center;justify-content:space-between;gap:8px;padding:0 8px; + border:1px solid #414b5a;border-radius:4px;background:linear-gradient(#151b27,#202736); + color:#b7c0cc;font-size:9px;letter-spacing:.5px;box-shadow:inset 0 1px 4px #0006} +#stateInfo{overflow:hidden;white-space:nowrap;text-overflow:ellipsis} +.preset-arrows{font-size:16px;color:#8c98a4} +.top-actions{margin-left:auto;display:flex;align-items:center;gap:6px} +.bar-button,.help-button{height:25px;border:1px solid #626d79;border-radius:4px; + background:linear-gradient(#c9d1d4,#9eacb4 48%,#71838c 49%,#aebdc3); + box-shadow:inset 0 1px #fff9,0 1px 2px #0006;color:#1b3443;font-size:9px; + font-weight:730;letter-spacing:.3px;padding:0 9px} +.bar-button b{color:#295469;font-weight:700;margin-left:3px} +.bar-button.active #spectrumStatus{color:#075f4b;font-weight:850} +.help-button{width:25px;padding:0;font-size:12px} + +/* The graph and dock are SIBLINGS. No editing control may cover a graph pixel. */ +.workspace{flex:1;min-height:0;display:flex;flex-direction:column;align-items:stretch;overflow:hidden; + background:radial-gradient(ellipse at 50% -10%,#2b2a35,#171c26 70%,#111823)} +.graph-wrap{width:100%;flex:1;min-height:0;position:relative;overflow:hidden;touch-action:none; + background:var(--graph);border-bottom:1px solid #41404b} +.graph-wrap canvas{display:block;width:100%;height:100%;cursor:crosshair} +.graph-hud{position:absolute;top:8px;left:13px;right:105px;display:flex; + align-items:center;justify-content:space-between;gap:12px;pointer-events:none} +.graph-mode{font-size:9px;letter-spacing:1.2px;font-weight:700;color:#a7a5ad} +.graph-cyan{display:inline-block;width:5px;height:5px;border-radius:50%;margin-left:6px; + background:var(--cyan)} +.graph-info{font:10px Consolas,monospace;color:#93949f;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.axis-hint{position:absolute;right:8px;top:24px;color:#a0a0b1;font:9px Consolas,monospace} +.graph-overlay{position:absolute;pointer-events:none;z-index:3;padding:6px 8px; + border:1px solid #60616f;border-radius:4px;background:#282731f0; + box-shadow:0 4px 12px #000a;font:10px Consolas,monospace;white-space:nowrap;color:#f1f0ee} + +/* Compact editable control island BELOW the graph: no position:absolute. + Its height is fixed so window resize never pushes controls out of frame. */ +.inspector{position:relative;flex:0 0 148px;min-height:148px; + align-self:center;width:min(570px,calc(100% - 26px));margin:0 auto 7px;padding:0 12px 7px; + border:1px solid #515663;border-radius:10px;color:#dfe5ec; + background:linear-gradient(160deg,#34333b 0%,#292b35 30%,#212a35 75%,#182430 100%); + box-shadow:inset 0 1px #777580,0 1px 0 #121720,0 6px 16px #0009} +.inspector::before{content:"";position:absolute;inset:1px;border:1px solid #33384290; + border-radius:9px;pointer-events:none} +.inspector-top{height:26px;display:flex;align-items:center;justify-content:space-between; + border-bottom:1px solid #5c606a72} +.identity,.inspector-actions{display:flex;align-items:center;gap:7px;white-space:nowrap} +.identity{font-size:10px;font-weight:750;letter-spacing:.5px} +.identity i{width:9px;height:9px;border-radius:50%;background:var(--cyan);box-shadow:0 0 7px #a8acb766} +.channel-badge{font-size:8px;font-weight:500;letter-spacing:.5px;color:#b9c5d1; + background:#242b35;border:1px solid #4b5562;border-radius:3px;padding:2px 5px} +.inspector-actions button{height:21px;min-width:24px;padding:0 6px;color:#d5dbe1; + border:1px solid #666a72;border-radius:3px;background:linear-gradient(#59616b,#343d48)} +.inspector-actions #enableBtn{color:#86efc3;border-color:#48766d;font-weight:800} +.inspector-actions #enableBtn.off{color:#c7b8ad;border-color:#71635e} +.inspector-actions #removeBtn{font-size:14px;color:#e6abb0} +.inspector-actions #closeInspector{font-size:13px} +.band-inspector{padding-top:5px} +.parameter-row{display:grid;grid-template-columns:1.24fr 1fr 1fr .85fr;gap:10px;align-items:start} +.parameter{display:block;position:relative;min-width:0;color:#a6a6ae;font-size:8px; + font-weight:700;letter-spacing:1px;text-align:center} +.parameter select,.number{margin-top:3px;height:23px;width:100%;min-width:0;border:1px solid #5b6773;border-radius:4px; + background:linear-gradient(#141d29,#2a3440);color:#f4f5fa;box-shadow:inset 0 1px 2px #0007} +.parameter select{padding:0 7px;font-size:10px;letter-spacing:0;cursor:pointer} +.shape-glyph{display:grid;place-items:center;height:28px;margin:1px auto;color:#88dbd5; + font-size:24px;line-height:28px} +.knob-face{display:block;position:relative;width:34px;height:34px;margin:2px auto 0; + border:2px solid #586676;border-radius:50%;cursor:ns-resize;touch-action:none; + background:radial-gradient(circle at 35% 25%,#87929e,#465361 40%,#1b2632 71%,#090f17); + box-shadow:inset 0 1px 2px #e7edf099,inset 0 -2px 4px #030810,0 2px 2px #000b} +.knob-face::before{content:"";position:absolute;inset:-4px;border-radius:50%;border:1px solid #485464} +.knob-face::after{content:"";position:absolute;left:50%;top:50%;height:7px;width:3px;border-radius:3px; + background:#67e4e8;transform:translate(-50%,-50%) rotate(var(--angle,-140deg)) translateY(-13px); + box-shadow:0 0 5px #57d5dc} +.knob-face.gain::after{background:var(--gold);box-shadow:0 0 6px #e7ba5c} +.knob-face.q::after{background:#d1e1ee} +.knob-face:hover{border-color:#85cad7} +.number{display:flex;align-items:center;gap:3px;padding:0 6px} +.number input{min-width:0;width:100%;border:0;outline:0;background:transparent;text-align:center; + color:#f0f2f6;font-weight:700;font-size:11px} +.number span{font:9px Consolas,monospace;color:#9daabb} +.number input::-webkit-inner-spin-button{-webkit-appearance:none} +.number:focus-within{border-color:#75d6e2} +.inspector-bottom{display:flex;justify-content:space-between;align-items:end;gap:10px; + margin-top:6px;padding-top:5px;border-top:1px solid #545c6970} +.channel-wrap>span,.slope-wrap,.note-info>span{display:block;color:#a2a9b4; + font-size:8px;letter-spacing:.8px;font-weight:700} +.channel-wrap{min-width:180px} +.route-group{display:flex;gap:3px;margin-top:3px} +.route-group button{min-width:28px;height:20px;padding:0 5px;font-size:9px; + border:1px solid #5b6775;border-radius:3px;color:#b5bfcc;background:linear-gradient(#3c4a58,#222e3a)} +.route-group button.active{border-color:#54adc4;color:#effcff;background:linear-gradient(#2c7c93,#12516b)} +.slope-wrap{min-width:72px}.slope-wrap select{display:block;width:100%;height:20px;margin-top:3px; + border:1px solid #566475;border-radius:3px;background:#23313f;color:#d2dce6;font-size:9px} +.note-info{min-width:42px;text-align:right}.note-info b{display:block;margin-top:5px; + font:12px Consolas,monospace;color:var(--gold)} + +/* Drop-down overlays only for optional band navigation/help; never the EQ edit panel. */ +.band-list,.quick-help{position:absolute;z-index:8;right:12px;top:8px;border-radius:5px; + border:1px solid #5c6b7a;background:linear-gradient(#2b3a49,#1b2835); + box-shadow:0 8px 22px #000a} +.band-list{width:260px;padding:10px;max-height:80%} +.popup-head{display:flex;justify-content:space-between;gap:6px;font-size:10px; + padding-bottom:7px;border-bottom:1px solid #526071;font-weight:700} +.popup-head span{font-size:8px;color:#91a1b0} +.band-rail{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:4px; + max-height:230px;overflow:auto;padding-top:8px} +.band-chip{height:26px;border:1px solid #536e7b;border-radius:3px; + background:#253f4f;color:#d2e4ee;font:10px Consolas,monospace} +.band-chip.selected{border-color:#d2dce1} +.quick-help{width:246px;padding:12px} +.quick-help b{color:#80dfe8;letter-spacing:1px} +.quick-help p{font-size:10px;margin:9px 0;color:#c1d0d9} + +/* Low visual noise; does not compete with a 0 dB axis. */ +.bottom-bar{flex:0 0 25px;height:25px;display:flex;align-items:center;justify-content:space-between; + gap:10px;padding:0 11px;border-top:1px solid #4b5360; + background:linear-gradient(#303945,#1a2531);box-shadow:inset 0 1px #485664; + color:#a7b5c3;font:9px "Segoe UI",Arial,sans-serif} +.footer-left,.footer-center,.footer-right{display:flex;align-items:center;gap:8px;white-space:nowrap} +.signal-flag{font-weight:700;letter-spacing:.3px;color:#d0d9e3} +.signal-flag i{display:inline-block;width:5px;height:5px;margin-right:4px;border-radius:50%;background:#6ce4ab} +.footer-divider{width:1px;height:10px;background:#5a6877} +#bridgeStatus{max-width:170px;overflow:hidden;text-overflow:ellipsis;color:#95aabc} +.footer-center{font-size:8px;letter-spacing:.5px} +.legend-mark{display:inline-block;width:5px;height:5px;border-radius:50%} +.legend-mark.pre{background:#8c91a6}.legend-mark.post{background:#71dca6} +.legend-mark.curve{background:#f5c873} +.footer-right{color:#b4bac5}.footer-right b{font-size:8px;letter-spacing:1px;color:#72cbda} +@media(max-width:840px){.brand{min-width:150px}.brand-caption{display:none} + .preset-center{min-width:120px}.bar-button{padding:0 6px}.footer-center{display:none}} +@media(max-height:510px){.inspector{flex-basis:138px;min-height:138px;margin-bottom:3px} + .inspector-bottom{margin-top:3px;padding-top:3px}.knob-face{height:27px;width:27px}} + + +/* M2.4: main EQ plot remains dominant (~390-410px at 535px editor). + Advanced controls use reserved height, never overlay any EQ node. */ +.inspector{flex:0 0 70px;min-height:70px;margin-bottom:3px;padding:0 11px 4px;width:min(630px,calc(100% - 22px))} +.inspector-top{height:21px} +.band-inspector{padding-top:3px} +.parameter-row{grid-template-columns:1.3fr 1fr 1fr .85fr;gap:8px} +.parameter{font-size:8px;text-align:left;letter-spacing:.65px} +.parameter select,.number{height:25px;margin-top:2px} +.shape-glyph,.knob-face,.inspector-bottom{display:none} +.inspector.expanded{flex:0 0 151px;min-height:151px;padding-bottom:7px;margin-bottom:6px} +.inspector.expanded .knob-face{display:block} +.inspector.expanded .shape-glyph{display:grid} +.inspector.expanded .inspector-bottom{display:flex} +.inspector.expanded .parameter{text-align:center} +.inspector.expanded .band-inspector{padding-top:5px} +.inspector-actions #advancedBtn{font-size:9px;min-width:50px;color:#b9dbeb} +.analyzer-menu{position:absolute;z-index:9;top:34px;right:70px;width:315px; + background:linear-gradient(#2b313b,#161d27);border:1px solid #5a6471; + padding:12px;border-radius:6px;box-shadow:0 9px 24px #000a} +.analyzer-title{display:flex;justify-content:space-between;align-items:center;color:#e5e9ef; + font-size:10px;font-weight:750;letter-spacing:.7px;margin-bottom:12px} +.analyzer-title span{font-size:9px;color:#8fa5b5;font-weight:400;letter-spacing:0} +.analyzer-options{display:grid;grid-template-columns:1fr 1fr;gap:10px} +.analyzer-options label{font-size:9px;color:#adbdca;font-weight:700} +.analyzer-options select{display:block;width:100%;height:28px;margin-top:4px; + color:#e5f2f7;background:#223543;border:1px solid #5c6e7b;border-radius:4px} +.analyzer-switches{display:flex;justify-content:space-between;margin:12px 0 9px;color:#c8deeb; + border-top:1px solid #40525e;padding-top:10px} +.analyzer-switches label{cursor:pointer} +.analyzer-switches input{accent-color:#6bd2c1;vertical-align:middle} +.analyzer-menu small{font-size:9px;color:#8b9eab} +@media(max-height:510px){.inspector{flex-basis:70px;min-height:70px} + .inspector.expanded{flex-basis:140px;min-height:140px}} + +/* M2.5 composited Band Inspector: zero flex reflow, static EQ coordinates. */ +.workspace{display:flex;flex-direction:column;position:relative} +.graph-wrap{flex:1 1 auto;min-height:0;isolation:isolate} +.inspector{position:absolute;z-index:7;top:auto;bottom:13px;left:13px; + flex:none;min-height:0;height:70px;width:min(630px,calc(100% - 26px)); + margin:0;padding:0 11px 4px;align-self:auto;max-width:none; + box-shadow:inset 0 1px #777580,0 1px 0 #121720,0 9px 25px #000b; + transform:translateZ(0);will-change:auto} +.inspector.expanded{flex:none;min-height:0;height:151px;padding-bottom:7px;margin:0} +.history-button{min-width:31px!important;font-size:17px!important;padding:0 4px!important} +.history-button:disabled{opacity:.42} +.inspector .identity{letter-spacing:.4px} +.inspector .parameter-row{gap:8px} +@media(max-height:510px){.inspector{height:70px}.inspector.expanded{height:140px}} +.band-context{position:absolute;z-index:12;width:166px;padding:5px; + border-radius:5px;border:1px solid #6b7683; + background:linear-gradient(#303843,#192633);box-shadow:0 10px 28px #000b} +.band-context button{display:block;width:100%;min-height:28px;border:0; + border-bottom:1px solid #3c4b584d;background:transparent; + padding:5px 8px;text-align:left;font-size:10px;color:#d9e6ec; + font-weight:650;letter-spacing:.25px} +.band-context button:last-child{border-bottom:0} +.band-context button:hover{background:#3c6473;color:#fff} + +/* M3 integrated presets, discoverable filter types, real dynamic controls. + Presets do not crowd the plot: all widgets are inside the original chrome. */ +.preset-center{flex:1 1 250px;min-width:195px;max-width:330px;gap:4px;padding:0 4px} +#presetSelect{min-width:0;flex:1 1 auto;height:22px;border:0; + background:transparent;color:#dce8f4;font-size:10px;font-weight:650;text-align:center} +#presetSelect option{background:#1d2a37;color:#e6eef5} +.preset-nav{border:0;background:transparent;color:#bdd1df;min-width:20px; + height:22px;font-size:18px;line-height:16px;font-weight:650} +.preset-save{height:21px;padding:0 7px;border:1px solid #577889;border-radius:3px; + background:linear-gradient(#334f60,#1b3341);color:#d1eef9;font-size:9px;font-weight:800} +#saveSlot{height:21px;max-width:68px;flex:0 0 68px;font-size:9px; + border:1px solid #405967;color:#d5e5ee;background:#233744;border-radius:3px} +.preset-nav:hover,.preset-save:hover{background:#496b79;color:white} +.inspector.expanded{height:231px} +@media(max-height:510px){.inspector.expanded{height:231px}} +.shape-picker,.dyn-controls{display:none} +.inspector.expanded .shape-picker{display:grid;grid-template-columns:repeat(9,minmax(0,1fr)); + gap:3px;padding:7px 1px 5px} +.shape-picker button{height:22px;min-width:0;border:1px solid #576675;background:#202f3c; + color:#a8c4d2;border-radius:3px;font-size:8px;letter-spacing:0;font-weight:700;cursor:pointer} +.shape-picker button.active{border-color:#8dd7e5;background:#376273;color:white} +.inspector.expanded .dyn-controls{display:flex;align-items:center;gap:8px; + min-height:34px;padding:3px 4px;background:#152430a6;border:1px solid #3d5464;border-radius:4px} +.dyn-controls b{font-size:9px;letter-spacing:.4px;color:#65cfe5;white-space:nowrap} +.dyn-controls label{display:flex;align-items:center;gap:4px;min-width:0;white-space:nowrap; + font-size:8px;color:#b7c5d2} +.dyn-controls input{width:54px;height:24px;background:#233947;color:#f4faff; + border:1px solid #516d7c;border-radius:3px;padding:0 3px;text-align:center} +#dynStatus{font-size:8px;color:#85e4b6;margin-left:auto} +.inspector.expanded .inspector-bottom{padding-top:7px} + +/* M3.1 responsive instrument UI: dark menus rendered by our own DOM, not + platform-native select popups (Windows white theme cannot bleed through). */ +.preset-center{position:relative;overflow:visible;max-width:337px;flex:1 1 260px} +.preset-picker-button{flex:1 1 auto;min-width:65px;height:22px;border:0; + background:transparent;color:#e7eaf0;text-align:center;font-weight:700; + font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; + letter-spacing:.04em} +.preset-picker-button:hover{background:#2e4959} +.dark-menu{position:absolute;z-index:90;padding:6px;border:1px solid #596a7e; + border-radius:5px;background:#1b2937;color:#e4eef8; + box-shadow:0 14px 30px #000d;max-height:300px;overflow-y:auto;scrollbar-color:#496478 #182736} +.dark-menu button{display:block;width:100%;background:transparent; + border:1px solid transparent;border-radius:3px;padding:7px 9px; + min-height:28px;white-space:nowrap;text-align:left; + font-size:10px;font-weight:600;color:#cbdce9} +.dark-menu button:hover,.dark-menu button.selected{background:#345b70;color:#fff; + border-color:#6b9aad} +.preset-options{top:31px;left:16px;width:230px;max-height:305px} +.inspector{width:min(484px,calc(100% - 26px));height:70px} +.inspector.expanded{height:142px} +@media(max-height:510px){.inspector.expanded{height:142px}} +.parameter.shape{position:relative} +.type-picker-button{display:block;margin-top:4px;height:25px;width:100%; + border:1px solid #5b6d7c;border-radius:3px;background:#1b2d3a; + color:#edf4fa;text-align:left;padding:0 9px;font-size:10px;font-weight:700} +.type-picker-button:hover{background:#36586a;border-color:#9bd9ea} +.type-options{z-index:100;position:absolute;bottom:32px;left:-4px; + width:250px;max-height:none;display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:3px} +.type-options button{text-align:center;font-size:9px;white-space:normal; + padding:5px 2px;line-height:12px;min-height:34px} +.inspector.expanded .shape-picker{display:none!important} +.inspector.expanded .dyn-controls{display:flex;min-height:35px;height:35px;gap:7px; + padding:4px 5px;margin-top:6px} +.inspector.expanded .inspector-bottom{padding-top:6px} +.dyn-controls b{font-size:9px} +.dyn-controls label{font-size:8px} +#dynStatus{min-width:40px;text-align:right;font-size:10px;color:#90a9b7; + font-variant-numeric:tabular-nums} +#dynStatus.active{color:#e7b5f4} +.dyn-meter{width:38px;min-width:38px;height:6px;background:#243543; + border-radius:4px;border:1px solid #486071;overflow:hidden} +.dyn-meter i{display:block;height:100%;width:0;background:linear-gradient(90deg,#4eb8d6,#bd76e6); + border-radius:4px} diff --git a/WebUI/visual-qa.cjs b/WebUI/visual-qa.cjs new file mode 100644 index 0000000..bc7c043 --- /dev/null +++ b/WebUI/visual-qa.cjs @@ -0,0 +1,9 @@ +// CI-only visual QA. Never bundled in the production plugin. +const fs=require("node:fs"),path=require("node:path"); +const base=__dirname; +const html=fs.readFileSync(path.join(base,"index.html"),"utf8"); +const hook=''; +if(!html.includes(hook))throw Error("Missing app.js"); +const injected=""; +fs.writeFileSync(path.join(base,"visual-qa.generated.html"),html.replace(hook,injected+hook),"utf8"); +console.log("Created offline EQ visual QA fixture"); diff --git a/docs/ARD.md b/docs/ARD.md new file mode 100644 index 0000000..6baacf1 --- /dev/null +++ b/docs/ARD.md @@ -0,0 +1,241 @@ +# ARD — ArSonEQ Architecture & Design Rules + +Version 0.1 · 2026-10-29 · Status: approved direction, implementation evolving + +## Design decisions + +**A1 — Native engine, not Web Audio:** Reimplement an independent C++17 DSP core with deterministic biquad coefficients. MaSonKuPik is a functional/UX reference, not a source tree to copy indiscriminately. + +**A2 — JUCE 9.0.4 for VST3 and native editor:** Use JUCE only for plug-in host integration, parameters, state and rendering. DSP owns no JUCE types. Pin external dependency version. The repo and the JUCE AGPL distribution path are compatible; commercial distribution requires a separate licence decision. + +**A3 — 24 fixed band slots, no dynamic audio allocations:** Each slot has type, frequency, gain, Q, cut slope, channel mode and enabled state. Keep parameter IDs stable even after a slot is removed in UI. Fixed max 4 stages for P0 cut filters. + +**A4 — Hard isolation of audio and UI:** Audio callback does no malloc/free, locks, network IO, console IO, GPU interaction, or file access. Parameter snapshots are read as atomics, and coefficients update only on changed values. UI can cache graph responses and throttle analyzer repainting independently. + +**A5 — Stereo M/S routing:** For each band transform L/R to M=(L+R)/2, S=(L-R)/2 only if that band's placement needs M/S; apply independent filter state to the selected route; reconstruct L=M+S, R=M-S. Never apply per-band M/S as a global widening effect. Mono input uses mono processing and disables meaningless Left/Right/Side routes as necessary. + +**A6 — Separate transfer functions from UI graphs:** Expose analytical magnitude response from the exact DSP coefficient generator. UI graph must use actual sample rate and its current processing mode, not a fabricated 48kHz Web Audio offline context. + +**A7 — Explicit progression of phase modes:** P0 direct causal minimum-phase biquad, zero algorithmic delay. P2 separate measured natural-phase alternative and latency-accounted linear-phase FIR. Do not claim a direct analog-copy of FabFilter algorithms. + +## Architecture + +```text +DAW host + ├── VST3 wrapper (JUCE): buses, latency, automation, state, host lifetime + ├── ParameterAdapter: stable IDs, normalized ranges, bounded snapshots + ├── AudioProcessor (real-time): input → 24 fixed-band EQ → output + │ ├── biquad coefficient generator (RBJ topology + Butterworth stages) + │ ├── per-band L/R/M/S state, sanitized numerical limits + │ └── smoothing / topology transition policy + └── Editor (message thread): graph, nodes, inspector, cached response + └── optional RT-safe metering/FFT telemetry queue (future) +``` + +Portable DSP must be independently tested with a simple C++ test harness. It must not include Web Audio, JUCE, UI, JSON, or licensing code. + +## Signal flow / control + +1. Host writes normalized parameter values into APVTS atomics. On each block, processor reads a coherent-enough bounded snapshot per slot; each changed slot updates its target coefficients. A later revision may use immutable whole-bank snapshots for simultaneous multi-parameter changes. +2. Each sample flows through enabled slots in stable numerical order, with independent state for L/R or M/S. All stereo transforms are per slot; no summing of nonidentical latency paths. +3. Gain in dB converts to amplitude; cut filters are Butterworth cascades using the MaSonKuPik Q-stage array: 12 [0.70710678], 24 [0.5411961,1.30656296], 36 [0.51763809,0.70710678,1.93185165], 48 [0.50979558,0.60134489,0.89997622,2.56291545]. +4. For bell/shelf/notch calculate normalized biquad from RBJ Audio EQ Cookbook. Frequency/Q are bounded; every intermediate is finite; target coefficients computed at configuration changes, **never per sample**. +5. Retune uses interpolation or a fully verified dual-pipeline crossfade to avoid zippering and instability. Shape/slope change needs separate discontinuity tests. A simple block-step rebuild is **not** a release-quality solution. +6. Bypass is unity and preserves host state; transitions require crossfade/ramps, and full bypass must neither alter latency nor create clicks. +7. On sample-rate changes, update all coefficients and reset/transition filter state predictably; on silence avoid denormal stalls. + +## Parameter contract + +For slot N, IDs are immutable `bNN_enabled`, `bNN_type`, `bNN_freq`, `bNN_gain`, `bNN_q`, `bNN_slope`, `bNN_route`. Type order: Bell, LowShelf, HighShelf, LowCut, HighCut, Notch. Route: Stereo, Left, Right, Mid, Side. Slope: 12,24,36,48. Safe defaults: disabled, bell, 1000 Hz, 0 dB, Q=1, slope=12, Stereo. Numbering and enum order are persistence APIs; do not reorder. + +Band ranges: 20 Hz–20 kHz (clamp to 45% SR), -24 to +24 dB, Q 0.1–24; visual options may expose more restricted zoom. Actual cutoff and response are sample-rate limited. + +Schema migration: a versioned host state tree will preserve current slot identity when changing GUI, FFT or dynamic features. Any later incompatible addition must be additive or migratable, never rename existing host parameter IDs. + +## Lifecycle and threading + +- Construction: allocate fixed states once. Prepare: set sample rate, initialize states. Process: no allocation and no throwing. +- UI: repaints only on observed change; optional analyzer target 20–30 FPS. No unbounded `repaint()` loop or heavyweight effects; when editor closes, analysis stops. +- For P1 FFT, use preallocated SPSC sample/tap queue and worker/UI drain; drop visual frames rather than block the audio callback. Ensure lock-free queue semantics and ownership with tests. +- Offline render and host-initiated parameter automation must use the same DSP equations; no dependence on frame rate or wall clock. + +## Precision and verification + +For reference response test: compare analytical `H(e^{jw})` with measured sine sweep at 44.1/48/96/192 kHz and check normalized Biquad stability; verify 24 stages × two channels with random input finite. Test M/S symmetry, mono, disabled-band unity, impulse tail, repeatability, gain at band center, coefficient edge cases, and rapid-automation stress. Track max absolute error by mode. + +Before shipping: run Steinberg validator, JUCE pluginval, REAPER, and a second DAW; run Windows Defender scan on artifacts. Include licenses in binary distribution. + +## Design risk register + +| Risk | Mitigation | +|---|---| +| Browser DSP copy is not VST-ready | Port feature contract and verified math only | +| Automation zipper/crackle | Per-sample coefficient smoothing and topology-specific crossfade QA | +| GUI hover/FFT slowing real-time audio | Cached CPU draw, no GPU dependency for sound, throttled analyzer | +| JUCE AGPL/commercial licensing | Publish source under AGPL, review commercial edition separately | +| Nonzero-phase behavior misrepresented | Name only implemented modes, measure before enabling | +| Parallel thread drift | PRD/ARD and CHANGELOG are canonical; small PRs with tests, no speculative rewrites | + +## Stage gates + +M0: repo structure, standalone DSP, unit tests, CMake; M1: VST3 adapter, host params, graph interaction and save state; M2: audited transitions, spectrum analyzer, host validation; M3: dynamic EQ; M4: phase variants/surround/other formats. Consult [ROADMAP.md](ROADMAP.md) for binary acceptance. Avoid costly CI on unneeded toolchains until the host wrapper exists. + + +## M1.5 / early M2 engineering reconciliation (2026-10-29) + +After auditing the initial native implementation, naive coefficient interpolation was replaced for **discrete topology changes**: enabled/bypass, filter shape, route and number of stages now use two fixed preallocated processing paths, a 10ms smoothstep crossfade and bounded last-request-wins pending transitions. This avoids changing the same path's topology/state instantly or restarting an unfinished transition. Topology crossfades cost extra CPU **only while a change is in progress**, and never introduce latency. Frequency/Q/gain updates retain stable-coefficient interpolation over 12ms on the active path. All work is performed with fixed storage and no heap operations on the callback. + +**Limitations:** exact pop/click-free behavior still requires listening and more stringent amplitude-difference stress tests with external hosts; high-rate topology automation can defer the most recent request by the remaining crossfade duration. For 24 automated bands all changing simultaneously, two-path execution increases CPU temporarily. This must be benchmarked at small buffers; it is not yet a measured CPU guarantee. + +The analyzer uses a fixed 16,384-frame SPSC ring of {pre-mono, post-mono} samples, with release/acquire indexed ownership. The audio thread only pushes when an editor is open; on overflow telemetry frames are dropped rather than delaying audio. The editor consumes on a 30Hz timer, computes Hann-windowed 4,096-point pre/post FFTs on the message thread, and draws both behind the EQ curve. FFT size limits low-frequency resolution (~11.7Hz per bin at 48kHz); future analyzer iterations can use lower-frequency multiresolution windows if CPU budget permits. The audio path does **not** invoke the FFT. + +The graph caches a 2x2 complex transfer matrix for the full cascade, including L/R/M/S and crossfeed. UI plots diagonal L<-L and R<-R responses and a subdued crossfeed line, recomputing only when EQ parameters, sample rate or editor geometry changes. This is a more accurate representation than the initial stereo-only approximate graph. It does not claim to equal a measured music-spectrum FFT or FabFilter's proprietary phase algorithms. + +The fixed APVTS parameter IDs remain unchanged. The project now tests single-thread finite/RT stress, measured sine gain against the analytic curve, switch continuity, no heap allocations during process, ring buffer overflow and concurrent producer-consumer integrity. + +CI efficiency: one small Linux headless job and one Windows VST3 job that also runs the headless tests; avoid a duplicate Windows headless matrix. CI begins only after a coherent multi-file milestone commit, not after each individual edit. + + +## M2 GUI Architecture — native DSP + bundled JUCE WebView2 shell + +**Decision**: User explicitly requested porting MaSonKuPik EQ presentation, with an optimized web GUI. On Windows the editor uses JUCE 9.0.4 WebBrowserComponent with the WebView2 backend. Assets are three embedded local-only files: `WebUI/index.html`, `style.css`, `app.js`. There are **no npm runtime dependencies**, React, Tailwind, live web requests, localhost server, remote fonts, Web Audio DSP, or online CDNs. Windows native JUCE editor remains as a fallback if WebView2 options are unsupported; the DSP and VST3 parameters are unchanged. + +**Bridge and ownership**: +- C++ reads the authoritative 168 APVTS host parameters (24 slots x 7) on the editor message thread at 25Hz. Browser can only submit allow-listed `enabled/type/route/freq/gain/q/slope` commands via one `eq-command` listener. Numeric values and indices are bounded. Gestures (`begin` / `edit` / `end`) use `beginChangeGesture`, `setValueNotifyingHost`, `endChangeGesture` to preserve host automation. +- UI response curves are computed from the **same native DSP transfer matrix**, including stereo L/R and M/S; transmitted only on changed bands, sample rate, or selected band (256 log-spaced points). No offline Web Audio simulation or JS filter coefficients. +- Pre/post audio telemetry enters existing fixed-size SPSC queue; the message thread performs FFT and sends 224 log bins via a bounded 25Hz event. The WebView does **not** call native audio processing, use Web Audio, or access the audio callback. +- Canvas 2D retains MaSonKuPik interaction logic (double-click to add/remove, pointer drag, wheel Q/slope, notes and inspector), but uses a new self-contained DOM/Canvas implementation to avoid shipping its entire mastering app and dependency graph. Rendering is event-driven: only repaint after changed state or spectrum and maintain a 2x maximum device pixel ratio. +- Embedded resource provider only serves exact static resource paths; page navigation is limited to local resource root; CSP denies all external origins. Avoid security expansion by never loading third-party pages in a native-integrated WebView. +- WebView2 is a Chromium runtime and may use more baseline memory than JUCE's native editor. A tiny JS bundle is not the same as a zero-cost WebView2 process. Measure resident memory, first-open time, CPU and multi-instance behavior on Windows before calling the UI "ultra-lightweight". + +**CI**: Javascript syntax + no-dependency mock-DOM smoke on Linux; Windows build checks pinned WebView2 SDK headers/loader and embeds the assets into the VST3 artifact. Use a cached pinned NuGet SDK and retain native DSP test suites. Real DAW/WebView2 runtime inspection remains a gate. + +**Compatibility**: Never change existing host parameter IDs, plug-in ID, manufacturer ID, plugin binary format, state schema or audio process methods just to support GUI redesign. Native editor must remain available as a recovery path. If runtime initialization fails after CMake-supported capability probe, report failure and improve fallback rather than claiming success. + + +## M2.1 Visual hierarchy correction — reference images and ArSonMix design system (2026-10-29) +User supplied side-by-side screenshots: Pro-Q 3 (902×572), ArSonMix mixer (1652×962), old ArSonEQ (1112×712). Audit shows wasted right inspector column, 1110×680 editor default, chart truncated by minimum CSS geometry, redundant header/footer text, and overlarge always-on panels. + +**Canonical UX**: The graph is the main work area (full width); only a narrow 43px top chrome and 29px bottom status bar remain. Selected bands summon a 466px floating inspector adjacent to the selected node; the box prefers below if space permits, otherwise above, clamped inside graph bounds. No inspector exists when selection is empty. All 24 active bands remain available through the graph or optional BANDS popover. A fixed 900×535 JUCE initial editor size fits ordinary floating host windows. User may resize from 760×455 to 1360×850, and the floating inspector stays within graph bounds. + +**Visual tokens**: Derive from ArSonMix's documented `design-references/brushed-metal-v1.0/reference.json`: metallic/aluminum controls, blue-black glass in the FX workspace, turquoise status and contextual channel colors. Retain high contrast, compact controls with 1px beveled borders and no high-cost hover filters, blur or animation. Use Pro-Q's high-level placement concept only, not FabFilter artwork/trademarks/assets. + +**Rendering**: Always draw full graph, subtle log-frequency grid, warm 0dB baseline, restrained 2px curve, thin R line only when different from L, per-band colored draggable nodes and optional FFT layer. No React runtime and no constant idle redraw. Canvas changes remain event/telemetry driven and are capped at device DPR=2. No changes to the audio callback, native DSP or stable host parameters. WebView2 is still a browser process; memory/idle-paint tests remain required. + +**Acceptance**: JavaScript smoke checks selected inspector visibility, floating position, no sidebar, menus and native gestures; Windows JUCE/WebView2 VST3 release build required; actual DAW screenshot/re-open/multi-instance test and CPU/RAM profiling remain release gates. + + +### M2.1 finishing integration — rotary automation and spectrum cost gate +The floating inspector includes three tactile rotary controls for frequency, gain and Q; each supports vertical pointer drag, mapped logarithmically for Hz/Q and linearly for dB. Each pointer begins one APVTS gesture, sends bounded parameter edits during movement, and ends the gesture on pointer release/cancel/lost capture. The native bridge's fixed gesture array grows from 2 to 3 fields. Numeric inputs remain for precise editing. This only extends the *GUI bridge*; the engine, 168 parameter IDs, and persisted state schema are unchanged. + +The ANALYZER switch sends a native `spectrum` command. When off, `AnalyzerQueue::setEnabled(false)` atomically shuts off audio telemetry production, and the message-thread FFT/send loop is skipped; when on, telemetry resumes. Closing the editor still disables the queue. This prevents unnecessary audio-to-UI data and expensive FFT work when the user wants a still EQ curve. This is a source-level optimization and must be validated with actual Windows WebView2 CPU measurements. + +Smoke coverage checks knob Q gesture, native UI event paths, spectrum ON/OFF command, full-width graph, no permanent sidebar, popup placement, and popup/menu lifecycle. CI workflow paths include UI assets (build) and all WebUI test changes (headless), without rebuilding JUCE for a test-file-only edit. + + +## M2.2 — Dual-target native Windows delivery + +The exact same `juce_add_plugin(ArSonEQ ... FORMATS VST3 Standalone)` shared source set produces (1) a real VST3 plugin bundle for third-party hosts, and (2) a true native Windows `ArSonEQ.exe` using JUCE's official Standalone plugin wrapper and audio-device lifecycle. This avoids creating a second competing processor/GUI code path, avoids a wrapper webserver or Electron process, and prevents hardcoding Windows device APIs. Windows audio I/O belongs to JUCE Standalone: device selection and permissions follow the runtime/OS. Browser assets are binary resources embedded into each target; no localhost server or external assets. + +The CI compiles both targets under ONE configured JUCE build graph, runs the same three native DSP suites, verifies nontrivial EXE and VST3 module outputs, and uploads **one combined test bundle** with a commit SHA manifest. Only native DSP C++ source and plugin client wrapper differ at link time. Test audio-device initialization, system-exclusive modes, auto/manual input selection, actual ASIO/WASAPI drivers, and persistence on Windows real hardware before advertising the Standalone app as production ready. The VST3 and Standalone executables should not be mixed or installed into each other's folders. + + +## M2.3 GUI audit: VSTHost screenshot differential and non-occluding editing architecture + +**User-supplied evidence:** A VSTHost screenshot shows an active ArSonEQ band at 78.4Hz/+12.25dB and a 466px editing card obscuring much of the actual response and lower plot. A comparison VSTHost screenshot shows Pro-Q 3 displaying its dominant frequency response in an uncluttered upper graph with small, clearly grouped musical controls near the bottom. Our previous M2.1 approach (an absolutely positioned inspector based on selected node X/Y) fundamentally allowed graph occlusion; CSS repositioning alone was not a credible solution. + +**Fix architecture:** The `inspector` node is a *sibling following* `graph-wrap` inside a vertical-flex `workspace`. When selected, the bottom context deck has exactly 143px of dedicated layout height plus a 7px edge gap; when selection is absent the deck disappears and plot expands. **No band control exists inside graph-wrap and no band controls are positioned absolutely over the plot.** This makes graph occlusion mathematically impossible in the DOM structure, including at extrema of frequency, gain, host resize and all 24 slots. No animation/reflow loops, no hovering tooltip stealing pointer events. + +**Visual pass:** Carbon/charcoal graph rather than navy dashboard; premium dark ArSonMix workspace with restrained metallic control surfaces; response line in warm gold; translucent green area for positive boost and subtle warm attenuation fill; per-band colored handles; selected-band isolated response; independent right-side FFT dB rail, thin frequency grid, more restrained typography. Original gold/green scheme is a design pattern, not use of FabFilter's proprietary art. Default 12dB display range automatically expands to 15/18/21/24dB in response to actual parameter magnitudes; graph displays the authoritative C++ calculated transfer matrix rather than a synthetic JavaScript frequency response. + +**Performance:** Right rail costs 40 CSS pixels, leaving a dedicated graph viewport width for logarithmic X mapping. Canvas render is event-/FFT-telemetry driven; no permanent animation loop, React, network requests, blur effects or global hover filters. FFT still runs only in editor thread and is fully gated OFF when disabled. The inspector is compact and uses existing host APVTS gesture semantics and parameter IDs. Both Windows Standalone and VST3 compile from exactly the same HTML/CSS/JS embedded bytes. + +**QA / evidence:** Headless browser synthetic host fixture (CI only) provides deterministic initial bands and a synthetic Gaussian-like visual response to expose layout issues in a 900×535 screenshot. This *visual mock response is never compiled or embedded into the plugin*: only `index.html`, `style.css` and `app.js` are embedded. The fixture does not validate native DSP accuracy, Windows WebView2, ArSonMix/VSTHost focus handling, or real audio latency. The Linux quick job renders a screenshot with existing Chromium and publishes it as a separate tiny artifact; no extra JUCE build. Automated JS smoke asserts dock sibling DOM, bounded layout structure, native host gestures, analyzer off gating, 12dB+ high-gain state, and popover behavior. + +**Release gates:** Inspect headless pixel rendering for any clipping/collisions and run both Windows binaries in actual VSTHost and ArSonMix at 100%/150% DPI. Profile multiple instances and input device support separately. FabFilter Pro-Q 3 feature/visual parity is an aspiration, not currently certified or claimed. + + +### M2.3.1 visual QA findings — axis collision and pointer-frame invariant + +The 900x535 Chromium screenshot was reviewed, not merely generated. The geometry correctly shows an isolated bottom edit deck and four unobstructed EQ nodes, but the top-right +12/+9 dB labels collided because both were clamped to y >= 28px. Fix axis text placement to `clamp(y+3,13,h-17)`, which preserves separation at both positive and negative range extremes; move the 20kHz frequency label inward to prevent collision with the rightmost -12dB label. Enlarge static metallic knobs from 30px to 34px with a correspondingly bounded 148px dock. + +**Interaction invariant:** The graph height changes when opening/closing the dock. Previously `pointerdown` synchronously selected a node and opened the dock before a drag, remapping the Canvas coordinate system between pointerdown and pointermove. Now a first pointerdown captures the node and begins a host gesture **without selecting/opening the dock**. The dock appears only on pointer release after ending the host gesture, so the first drag uses one stable graph coordinate system throughout. A recent first-hit cache is used narrowly for double-click deletion when the second click lands a few pixels away after layout reflow. The fake-host test validates that the dock stays closed until release, then opens with correct host gesture lifecycle. Editing an already-selected node retains a fixed dock height. This is especially important for VSTHost and other small floating editors. + +These are GUI-only fixes; C++ DSP, latency, APVTS IDs, standalone/VST3 sources remain unchanged. + + +## M2.4 architecture decision — Pro-Q 3 gap audit, 2026-10-30 + +**Authoritative baseline:** `docs/PROQ3_GAP_AUDIT_AND_M24_PLAN_20261030.md` compares user VSTHost/Standalone screenshots and the original Pro-Q 3 50-page manual against the real native C++/JUCE source. It supersedes earlier speculative UI descriptions; do not start any more style-only changes without addressing analyzer correctness. + +**P0 failure in source:** the current processor computes `(L+R)*0.5` before queuing a spectrum PCM stream; anti-phase L/R cancels to zero even with audible energy. The current 4096 FFT maps 224 logarithmic UI frequencies to their nearest FFT bin; duplicate bins share temporal smoothing state and get updated multiple times per frame. These are the concrete engineering causes of weak/stair-stepped analyzer behavior. A WebUI CSS gradient is not a solution. + +**Approved direction:** preserve 100% native C++ DSP, a single lock-free PCM producer, and UI/editor FFT. Extend the SPSC payload to preserve L/R before and after EQ and compute power spectra independently. Merge in the power domain. Calibrate window/magnitude, implement per-display-frequency smoothing once per frame, and apply 4.5dB/oct visualization-only tilt by default. Offer 1024–8192 FFT, speed, range, Pre/Post/Freeze and sample-peak L/R meter with actual audio telemetry. No audio-thread FFT, lock, alloc or WebView. + +**UI density correction:** at 900×535, default selected-band deck <=70px so plot remains >=390px tall. Advanced controls are user-expanded, not permanently visible. The current ~148px deck cannot reach Pro-Q 3 graph dominance even after styling. The selected band and the gain curve must remain unobscured. Use ArSonMix visual tokens with original assets and shared CSS; do not copy FabFilter's proprietary art. + +**Compatibility:** 24 slots and the existing 168 APVTS parameter IDs remain unchanged through M2.4. Analyzer settings use versioned non-host-parameter settings until their automation requirements are decided; no retroactive parameter-ID remapping. Keep VST3 and Standalone generated in one Windows Release job. Proof gates cover 44.1/48/96k, 32/64/128 buffers, 50Hz–10k calibrated response, anti-phase stereo source, DPI 100/150%, VSTHost, ArSonMix and multi-instance resource use. Manual references: https://www.fabfilter.com/downloads/pdf/help/ffproq3-manual.pdf printed pp. 9–11 and 25–26. + + +### M2.4 implementation (2026-10-30, candidate before host QA) +The SPSC `MeterFrame` is upgraded from premixed mono input/output to four channel snapshots `preL,preR,postL,postR`; mono uses dual-mono. Sample energy is combined **after** native FFT in the power domain, preventing anti-phase cancellation in Mid/Side material. `Source/DSP/SpectrumDisplay.h` defines testable pure C++ log-frequency interpolation, power/dB normalization, tilt and time-constant-based smoothing; this never touches the audible DSP coefficients. + +The editor owns four preallocated 8192-sample circular time-domain buffers, a reusable JUCE FFT scratch buffer, and four magnitude tables. GUI-side FFT dispatch is selectable 1024/2048/4096/8192, using a Hann window and coherent-amplitude normalization (sum(Hann)/2), followed by power-domain stereo combination into 384 log-spaced visual frequencies. EMA attack/release uses elapsed UI time, not a fixed smoothing-per-bin mutation. The FFT only executes on the JUCE message thread while GUI and analyzer are enabled. Resolution, speed, tilt (0/3/4.5/6 dB per octave), 60/90/120 dB display range, Pre/Post and Freeze are editor settings, **not new VST3 host parameters**. The right-side L/R meter shows the highest observed output samples from editor telemetry, with display release; not true peak and not guaranteed sample-complete if the SPSC telemetry ring overflows. + +Default active-band dock is 70px with explicit MORE expansion to 151px for knob/route/slope/note detail; graphical controls are always outside `graph-wrap`. The graph gets approximately 398px height at 900×535, exceeding the >=390px design contract. Renderer is original Canvas2D, no React/Web Audio, no GPU blur or permanent animation loop. There are still only the original 168 host band params, all preserved. + +**Validation discipline:** native analyzer test asserts fully anti-phase L/R power, -6dB power conversion, 4.5dB/oct tilt and concurrent FIFO. UI smoke tests FFT option event, freeze and 70px dock. These are unit/smoke checks, **not** a complete Hann-window signal calibration / VSTHost cross-DAW / pluginval certification. Actual sine sweep and stereo music comparison remains a release gate. + + +**M2.4 native fallback QA / FFT optimization:** Windows first compilation identified native JUCE fallback's old `MeterFrame::before/after` field names. Its analyzer now captures independent L/R histories and combines their **FFT powers**, so anti-phase and right-only signals are visible even when WebView2 is unavailable. Four-channel WebView analyzer computes Hann coefficients and window coherent gain once at editor construction or FFT resolution changes, not with expensive trig for each FFT/channel at 25 Hz. Both changes preserve real-time safe core audio. The first CI failure is an integration regression, not evidence of validated Windows audio; recheck on a fresh dual-format CI run. + + +## M2.5 — professional direct manipulation and immutable graph viewport (2026-10-30) + +The user-reported screenshot regression in M2.4 is a real layout bug: the 70px inspector is a flex sibling of the plot, and selection, deselection or MORE expansion changes the canvas height. This shifts log-frequency and dB coordinates mid gesture. M2.5 moves `#inspector` **inside** `#graphWrap` and composites it with absolute positioning. It never consumes flex height. An algorithm computes an initial card position from the selected handle, preferring below the plot line; if the handle is too near the bottom, it places the card above the handle. Card position is updated on selection, resize, and MORE toggle, **not on every drag frame**. Canvas width/height and FFT/meter geometry are unchanged by selection. Right-click context menu uses the same graph coordinate system. + +Native + WebView command contract: +- Existing single-band `begin`/`edit`/`end` unchanged. +- M2.5 adds `gestureMany {begin:boolean, items:[{id,fields:["freq","gain"]}]}` with max 24 entries, and `bulkEdit {entries:[{id,field,value}],gesture:boolean}` with max 168 entries; the native bridge validates each id and field through existing editor methods. One WebView IPC frame can update all 24 bands. No audio-thread work. +- Ctrl/Meta click toggles band membership; Ctrl/Meta+A selects all enabled; selected set remains independent of native `selected_` primary band. Group drag applies **frequency ratio** from shared log-x displacement and **gain dB offset** to each eligible bell/shelf; cuts and notches preserve gain. Host gestures are opened for each band and closed on pointer release/cancel, including on destructor failure cleanup. +- Shift drag scales pointer movement to ~17% of full-range for precision; frequency clipping and gain clipping remain within 20–20000 Hz / ±24dB, no parameter-ID migration. +- Undo/Redo uses bounded 64-entry per-editor snapshots of all 24×7 band controls. The UI records one edit transaction per drag or knob gesture and sends one bounded `bulkEdit` transaction when undoing/redoing. Ctrl+Z/Y and toolbar buttons target **UI-local** history; external DAW undo/redo, automated host control, session-persisted undo stacks remain out-of-scope. The actual VST3 parameters are authoritative and changed with `setValueNotifyingHost` via JUCE. History is not a new persisted state parameter. +- Context menu: right-click handle for edit/bypass/delete, right-click empty plot for add band, select all from menu. All actions are connected to actual band parameters, not inactive mock controls. + +Validation: JavaScript fake-host smoke now verifies floating nesting and compositor CSS contract, drag gestures, grouped `bulkEdit`, undo/redo, right-click and analyzer actions; Chromium visual snapshot of selected band on a fixed canvas. Real VSTHost/ArSonMix 100%/150% DPI, host automation and drag-click feedback remain mandatory before merge. Keep PR draft. + +**Limits:** Group selection currently supports aggregate drag/delete/bypass, not true Pro-Q 3 per-band solo, range editing, spectrum grab or fully integrated DAW undo. Do not claim those implemented. Advanced card may cover background spectrum but selected band nodes are protected by initial placement; it is not a reflowing bottom dock. + + +## M3 — native Dynamic EQ + 9 filter shapes + persistent preset architecture (2026-10-30) + +### DSP decisions +- The original six `Type` values (0–5) remain **numerically unchanged**. Types 6=BandPass, 7=TiltShelf, 8=FlatTilt extend the JUCE host choice list; `BandPass` is the RBJ constant-peak bandpass; TiltShelf/FlatTilt use two opposite low/high shelves, realized as a two-stage path. Neither new shape is a claim of FabFilter analog matching. +- Existing 24×7 (168) APVTS IDs retain their names; add `bXX_dynRange` and `bXX_dynThreshold` per band, **48 added host parameters** (216 total). Dynamic range default zero (legacy project behavior unchanged), manual threshold default -24 dBFS. Save-state schema 2; old state XML loads via APVTS's compatible parameter mapping. +- Dynamic audio processing on native Engine::process()/processMono(): only Bell/LowShelf/HighShelf supports dynamics; each active dynamic band has preallocated per-lane RBJ band-pass detector state, energy follower with ~12ms attack/~100ms release, 6dB-soft-onset threshold, and a separate fixed dynamic EQ filter branch blended continuously in proportion to detector. Range is signed ±12 dB. Controls are updated at audio-block boundary via atomic APVTS references and topology-safe 10ms path crossfade, with no FFT/alloc/locks in sample processing. **This is a functional manual-threshold dynamic EQ foundation**, not FabFilter's program-dependent auto threshold or analog matched design. The display shows the static curve; a dynamic activity/ghost response visual remains pending. +- Active Dynamic EQ adds a detector/filter pair only for enabled dynamic bands. Default range=0 bypasses them. Validate transfer at 48/96k, extremes Q, clipping, M/S routing, rapid automation, and multiple instances on hardware. + +### Native presets +- Native C++/JUCE factory presets: Init/Flat, Clean Vocal, Vocal Presence, Warm Vocal, De-Esser Dynamic, Tight Kick, Balanced Master, Air & Sparkle. All are original, light-duty examples, not "FabFilter" or third-party settings. +- User presets 01–08 persisted as full JUCE ValueTree XML under `%APPDATA%/ArSon Audio/ArSonEQ/Presets/`, with fixed filenames and no user-supplied path traversal. `User 01..08` are selected for saving via a separate dedicated slot selector and **SAVE**; loading is via top-center preset picker/prev/next. Factory and User settings are shared across VST3 and Standalone on the same Windows profile. Host session save/recall continues through APVTS. +- All user-file read/writes happen only on GUI/message thread, never inside audio callbacks. 256KiB load-size limit. Factory changes are applied as host-notified parameter writes, user XML through JUCE APVTS state replace. Missing user files must show a failure, not pretend to load. +- The center toolbar is now a real user control, with rate/band status relocated to footer; advanced filter shape chips and dynamic range/threshold are inside the M2.5 floating inspector, preserving canvas geometry. The 9 filter types also remain in the accessible dropdown. + +### Compatibility and truthful status +- "M2.5" (flicker-free floating inspector) is user-confirmed; "M3 integrated candidate" is **NOT** validated on real hardware until new CI, VSTHost/ArSonMix, preset reload across application restart, and audio output profile. +- Distinct from Pro-Q 3: no program-dependent dynamic auto mode, external sidechain, custom detector range, Natural/Linear Phase, brickwall, 6–96dB/oct filters, EQ Match, surround, multi-instance comparison. Those are M4/M5 and must never be represented by relabeling this code. + + +## M3.1 — Live native dynamic transfer + compact instrument UI (2026-10-30) + +**Reference behavior:** FabFilter Pro-Q 3 [official 2018 announcement](https://www.fabfilter.com/news/1543478400/fabfilter-releases-fabfilter-pro-q-3-equalizer-plug-in-with-dynamic-eq) describes per-band dynamic range, band-limited trigger, automatic/manual threshold and program-dependent timing. iZotope [Neutron EQ documentation](https://s3.amazonaws.com/izotopedownloads/docs/neutron4/en/equalizer/index.html) describes current-band threshold/reduction meters, dynamic node movement and response curves. These are studied behavioral references, NOT copied assets or proprietary algorithms. + +**Correctness fix:** In M3, changes to dynamic Bell/Shelf frequency/Q modified the static filters but did not refresh the dynamic detector/dynamic-filter coefficients. In the original C++ `Engine::sameTopology`, changes to frequency/Q on active dynamic bands now force the existing 10ms dual-path crossfade, preventing stale detector frequency. `Path::activity[0..1]` is set from the **actual audio-driven, smoothed RMS detector wet factor** in `runDynamic`. The processor publishes `Engine::dynamicActivity(i)` into 24 relaxed atomics at the **end of each audio callback**, never inside a per-sample IPC/heap/FFT/lock operation. + +**Graph telemetry:** Every ~50ms on the JUCE editor/message thread (only when wet changes by >0.006, topology changes, or dynamics are disabled), `WebEditor::sendDynamics` obtains actual per-band activity via the atomics. The UI computes **a quasi-static instantaneous transfer estimate** with the exact existing biquad coefficients: `H_effective = H_static × (1 - wet + wet × H_dyn)`. Per-band left/right/mid/side matrix routing is respected in the graph's `Engine::matrixResponse(freq,&wet)`. Native emits `eq-dynamics` carrying 256 frequency-point effective L/R response arrays, 24 wet values and 24 center-frequency response dB differences. The browser draws a moving gold composite response against a subdued static reference, a purple tinted region between curves, a mobile fine indicator per dynamic node (while keeping the draggable node at a static coordinate), and a numeric reduction/addition meter. + +**Limits:** The displayed curve is a DSP-derived *instantaneous stationary approximation*. It is NOT a precise transfer measurement for time-varying IIR coefficients, nor a recorded true level meter. Do not fake motion with generated values when running live. Browser CI fixture's synthetic demonstration must always be labeled synthetic, not native proof. Pro-Q 3's analog matching, automated threshold, program-dependent ballistics, Natural/Linear Phase, iZotope external sidechain remain unimplemented. + +**Visual regression fixes:** The native `