From ea239b8c7f6c6b4d7dada1dbdeeb39d4b15a40b2 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 13:10:09 +0700 Subject: [PATCH 1/2] integrate(native): preserve main GUI v0.8 UX and add tested P2.5 JUCE VST3 engine, truthful meters, native bridge and CI --- .github/workflows/p1-windows.yml | 69 ++ AR-MIX-Live-FX-Host-Standalone-v0.3.html | 2 + CMakeLists.txt | 34 +- README.md | 64 +- docs/HISTORICAL_README_PRE_RECONCILIATION.md | 104 +++ docs/P1_FIRST_SOUND.md | 36 + docs/P25_LIVE_GRAPH_HANDOFF.md | 32 + docs/P2_DAW_WORKFLOW.md | 34 + docs/P2_FABFILTER_FX_COMPATIBILITY.md | 23 + docs/P2_LIVE_METER_PAN_FX_BYPASS.md | 22 + docs/P2_NATIVE_FX_RACK.md | 37 + docs/P2_NATIVE_PRESETS.md | 27 + docs/P2_REALTIME_RELIABILITY.md | 43 ++ docs/PROGRESS_RECONCILIATION_2026-10-25.md | 55 ++ src/DiagnosticsRecorder.h | 99 +++ src/LiveAudioEngine.h | 669 ++++++++++++++++++ src/LiveGraphHandoff.h | 85 +++ src/Main.cpp | 572 +++++++++++++-- src/NativePresetArchive.h | 222 ++++++ src/PluginCatalog.h | 305 ++++++++ src/StereoPan.h | 28 + src/VstBusLayout.h | 64 ++ tests/fx_add_contract_test.mjs | 30 + tests/live_graph_contract_test.mjs | 34 + tests/main_v08_native_integration_test.mjs | 36 + tests/native_preset_contract_test.mjs | 33 + tests/native_preset_roundtrip_test.cpp | 70 ++ tests/native_ui_contract_test.mjs | 39 + tests/realtime_control_test.cpp | 78 ++ tests/reconciled_gui_engine_contract_test.mjs | 42 ++ web/app.js | 2 + web/bridge.js | 621 ++++++++++++++++ web/index.html | 2 +- web/monitor.js | 110 +++ web/native-bridge.js | 74 ++ 35 files changed, 3695 insertions(+), 102 deletions(-) create mode 100644 .github/workflows/p1-windows.yml create mode 100644 docs/HISTORICAL_README_PRE_RECONCILIATION.md create mode 100644 docs/P1_FIRST_SOUND.md create mode 100644 docs/P25_LIVE_GRAPH_HANDOFF.md create mode 100644 docs/P2_DAW_WORKFLOW.md create mode 100644 docs/P2_FABFILTER_FX_COMPATIBILITY.md create mode 100644 docs/P2_LIVE_METER_PAN_FX_BYPASS.md create mode 100644 docs/P2_NATIVE_FX_RACK.md create mode 100644 docs/P2_NATIVE_PRESETS.md create mode 100644 docs/P2_REALTIME_RELIABILITY.md create mode 100644 docs/PROGRESS_RECONCILIATION_2026-10-25.md create mode 100644 src/DiagnosticsRecorder.h create mode 100644 src/LiveAudioEngine.h create mode 100644 src/LiveGraphHandoff.h create mode 100644 src/NativePresetArchive.h create mode 100644 src/PluginCatalog.h create mode 100644 src/StereoPan.h create mode 100644 src/VstBusLayout.h create mode 100644 tests/fx_add_contract_test.mjs create mode 100644 tests/live_graph_contract_test.mjs create mode 100644 tests/main_v08_native_integration_test.mjs create mode 100644 tests/native_preset_contract_test.mjs create mode 100644 tests/native_preset_roundtrip_test.cpp create mode 100644 tests/native_ui_contract_test.mjs create mode 100644 tests/reconciled_gui_engine_contract_test.mjs create mode 100644 web/bridge.js create mode 100644 web/monitor.js create mode 100644 web/native-bridge.js diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml new file mode 100644 index 000000000..d88697341 --- /dev/null +++ b/.github/workflows/p1-windows.yml @@ -0,0 +1,69 @@ +name: Windows Native VST3 Host +on: + push: + branches: [ main, feature/p1-first-sound-windows, feature/p2-native-vst-catalog-fx-rack, feature/p2-daw-workflow-progress, fix/p2-native-output-monitor-diagnostics, fix/p2-realtime-glitch-telemetry-latest-gui, fix/p2-truthful-meter-pan-fx-toggle, feature/p2-native-state-presets, fix/p2-fabfilter-add-workflow, feature/p25-live-preset-graph-swap, integration/p25-gui-engine-reconciled, integration/main-v08-gui-p25-native ] + pull_request: + workflow_dispatch: + +concurrency: + group: windows-vst3-${{ github.head_ref || github.ref_name }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + windows-build: + runs-on: windows-2022 + timeout-minutes: 50 + steps: + - uses: actions/checkout@v4 + - name: Checkout JUCE 8 pinned + uses: actions/checkout@v4 + with: + repository: juce-framework/JUCE + ref: 8.0.15 + path: third_party/JUCE + - name: Install WebView2 SDK for JUCE + shell: pwsh + run: nuget install Microsoft.Web.WebView2 -Version 1.0.3485.44 -OutputDirectory .deps -NonInteractive + - name: Validate native UI JavaScript + shell: pwsh + run: | + node --check web/bridge.js + node --check web/monitor.js + node --check web/app.js + node --test tests/native_ui_contract_test.mjs + node --test tests/native_preset_contract_test.mjs + node --test tests/fx_add_contract_test.mjs + node --test tests/live_graph_contract_test.mjs + node --test tests/reconciled_gui_engine_contract_test.mjs + - name: Configure Windows x64 + shell: pwsh + run: > + cmake -S . -B build -G "Visual Studio 17 2022" -A x64 + -DJUCE_ROOT="${{ github.workspace }}/third_party/JUCE" + -DBUILD_TESTING=ON + -DJUCE_WEBVIEW2_PACKAGE_LOCATION="${{ github.workspace }}/.deps" + - name: Build executable and native RT tests + run: cmake --build build --config Release --target ARMixConsole ARMixRTTests ARMixPresetTests --parallel 2 + - name: Test realtime control primitives + run: ctest --test-dir build -C Release --output-on-failure + - name: Package native executable + shell: pwsh + run: | + New-Item -ItemType Directory -Force -Path dist | Out-Null + $exe = Get-ChildItem -Path build -Filter "*.exe" -Recurse | + Where-Object { $_.Name -like "*AR*Mix*" -and $_.FullName -match 'Release' } | + Select-Object -First 1 + if (-not $exe) { throw "ARMixConsole EXE not found" } + Copy-Item $exe.FullName "dist/ArSonMix-P2.5-GUI-v0.8-Native-Windows.exe" + Copy-Item README.md "dist/README.md" + "P2 experimental: audio routes automatically; use headphones at low level. Only Channel 1 is native. Other strips are inactive previews." | + Out-File -FilePath dist/FIRST_SOUND_README.txt -Encoding utf8 + - uses: actions/upload-artifact@v4 + with: + name: ArSonMix-P2.5-GUI-v0.8-Native-Windows-x64 + path: dist/ + if-no-files-found: error + retention-days: 14 diff --git a/AR-MIX-Live-FX-Host-Standalone-v0.3.html b/AR-MIX-Live-FX-Host-Standalone-v0.3.html index 32fed83db..e5941ee2f 100644 --- a/AR-MIX-Live-FX-Host-Standalone-v0.3.html +++ b/AR-MIX-Live-FX-Host-Standalone-v0.3.html @@ -982,6 +982,8 @@ }); document.addEventListener('keydown',e=>{if(e.ctrlKey&&e.key.toLowerCase()==='s'){e.preventDefault();if(persistSession())flash('UI state saved locally');else flash('Browser storage unavailable')}}); let lastMeterFrame=0;function meters(t){ + // JUCE desktop reads actual audio meters; browser demo only animates a preview. + if(window.__JUCE__?.backend?.emitEvent)return; requestAnimationFrame(meters);if(t-lastMeterFrame<33||document.hidden)return;lastMeterFrame=t; channels.forEach((ch,i)=>{const wave=(Math.sin(t*.0022+i*1.92)+Math.sin(t*.0043+i*.6))*.5; let v=clamp(45+wave*24+ch.fader*.48,4,98);if(ch.mute)v=2;updateMeterVisual(String(i),v,t)}); diff --git a/CMakeLists.txt b/CMakeLists.txt index 66c128819..6a19462de 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,44 +1,52 @@ cmake_minimum_required(VERSION 3.22) -project(ARMixConsole VERSION 0.3.0 LANGUAGES CXX) +project(ARMixConsole VERSION 0.5.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) -# Set JUCE_ROOT to the path of a local JUCE checkout. No downloads occur at runtime. if (NOT DEFINED JUCE_ROOT) - message(FATAL_ERROR "Pass -DJUCE_ROOT=C:/path/to/JUCE (JUCE 8/9 checkout)") + message(FATAL_ERROR "Pass -DJUCE_ROOT=C:/path/to/JUCE (8.0.15+ required)") endif() add_subdirectory("${JUCE_ROOT}" "${CMAKE_BINARY_DIR}/juce") juce_add_gui_app(ARMixConsole - PRODUCT_NAME "AR MIX Console" + PRODUCT_NAME "AR MIX Studio" COMPANY_NAME "AR MIX Open Source" + BUNDLE_ID "org.armix.studio" NEEDS_WEB_BROWSER TRUE NEEDS_WEBVIEW2 TRUE NEEDS_CURL FALSE) -juce_add_binary_data(ARMixAssets - SOURCES - web/index.html - web/styles.css - web/app.js) +juce_add_binary_data(ARMixAssets SOURCES + web/index.html web/styles.css web/app.js web/bridge.js web/monitor.js) -target_sources(ARMixConsole PRIVATE src/Main.cpp) +target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/PluginCatalog.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/VstBusLayout.h src/LiveGraphHandoff.h) target_compile_definitions(ARMixConsole PRIVATE JUCE_WEB_BROWSER=1 JUCE_USE_WIN_WEBVIEW2=1 JUCE_USE_CURL=0 - JUCE_APPLICATION_NAME_STRING="AR MIX Console" - JUCE_APPLICATION_VERSION_STRING="0.3.0") + JUCE_ASIO=1 + JUCE_PLUGINHOST_VST3=1 + JUCE_APPLICATION_NAME_STRING="AR MIX Studio" + JUCE_APPLICATION_VERSION_STRING="0.5.0-p2") target_link_libraries(ARMixConsole PRIVATE ARMixAssets juce::juce_gui_extra + juce::juce_audio_utils + juce::juce_audio_processors + juce::juce_cryptography + juce::juce_audio_devices juce::juce_recommended_config_flags juce::juce_recommended_warning_flags) -# Independent of JUCE; tests lock-free event and coalesced scalar contracts. include(CTest) if(BUILD_TESTING) add_executable(ARMixRTTests tests/realtime_control_test.cpp) target_compile_features(ARMixRTTests PRIVATE cxx_std_20) add_test(NAME RealtimeControlPrimitives COMMAND ARMixRTTests) + juce_add_console_app(ARMixPresetTests PRODUCT_NAME "ArSonMix Native Preset Tests") + target_sources(ARMixPresetTests PRIVATE tests/native_preset_roundtrip_test.cpp src/NativePresetArchive.h) + target_link_libraries(ARMixPresetTests PRIVATE juce::juce_core juce::juce_cryptography + juce::juce_recommended_config_flags) + target_compile_features(ARMixPresetTests PRIVATE cxx_std_20) + add_test(NAME NativePresetZipRoundTrip COMMAND ARMixPresetTests) endif() diff --git a/README.md b/README.md index c44b857b5..b900dfa06 100644 --- a/README.md +++ b/README.md @@ -1,56 +1,54 @@ -# AR MIX Studio — Open-Source Live FX Host (v0.3 UI & Architecture) +# ArSonMix -**Status: interactive UI prototype + C++ real-time messaging primitives. No audio engine yet.** +**Open-source live VST3 host with a premium v0.8 virtual digital mixer interface.** Built for Windows live vocal, karaoke and streaming workflows, with a JUCE C++20 audio engine and a WebView2 console UI. -AR MIX Studio targets live vocal processing for karaoke performers and livestream creators. It is VST3-first: the principal activity is building a beautiful, low-friction FX chain with a digital-console look. The core engine is planned as C++20/JUCE with Windows ASIO/WASAPI; the frontend is a self-contained HTML/CSS/SVG UI embedded in JUCE WebView2. +[Premium browser GUI preview](site/preview/index.html) · [Experimental Windows EXE builds](https://github.com/masarray/arsonmix/actions/workflows/p1-windows.yml?query=branch%3Aintegration%2Fp25-gui-engine-reconciled) · [Progress & release status](docs/PROGRESS_RECONCILIATION_2026-10-25.md) · [ARD](docs/ARD_AR_MIX_LIVE_FX_HOST_v0.3.md) -## Public website and interactive GUI preview +## Current development baseline · 25 October 2026 -- **Landing website:** https://masarray.github.io/arsonmix/ -- **Review the actual mixer GUI:** https://masarray.github.io/arsonmix/preview/ -- **Open mixer full-screen:** https://masarray.github.io/arsonmix/preview/mixer.html +| Area | Working development scope | Important limit | +|---|---|---| +| GUI & UX | Latest tactile/metallic v0.5 PC console design, channel identity editor (name/icon/color), PAN snapping, red Master fader, peak-hold & clip LEDs | Browser-only UI controls are not proof of audio DSP functionality | +| Audio | JUCE native callback, Windows ASIO/WASAPI device selection, auto output routing, real meters, PAN, channel/master faders and MUTE | Real processing currently uses **Channel 1 stereo**; input strips 2–12 are previews | +| VST3 | Scan/import/catalog, insert/editor, atomic bypass and diagnostic messages | FabFilter and iZotope RX were confirmed loading on prior P2.4.1 hardware; retest integrated build | +| Presets | Native `.armix` ZIP + vendor binary plugin state, FX order/bypass, Channel 1/master gain and PAN | Save requires muted output; presets depend on locally installed VST3 files | +| Live recall | Experimental P2.5 prepared graph, callback-boundary de-click fade, deferred plugin retirement | Not seamless dual-graph crossfade. FX ADD/REMOVE/REORDER still detach callback | +| Master | Real Master level/MUTE plus independent L/R meters | Master FX inserts, master PAN, LUFS-I and dBTP **not native**; visual previews/placeholder fields | +| Routing | Functional Channel 1 to selected hardware output | No true independent 12-channel, streaming/record buses or automatic loopback setup yet | -GitHub Pages publishes the current **GUI development branch** through [the main-branch Pages workflow](.github/workflows/pages-publish.yml), after UI smoke tests pass. This preview is intentionally separate from the stable `main` code and from the native audio engine work. It is a **browser GUI prototype with simulated meters**, not a functioning VST audio host. +The canonical reconciliation source is **`integration/main-v08-gui-p25-native`**, preserving both the best [GUI branch](https://github.com/masarray/arsonmix/tree/main) and the advanced [P2.5 engine branch](https://github.com/masarray/arsonmix/tree/feature/p25-live-preset-graph-swap). Current `main` already contains approved GUI v0.8 (PR #2). This integration layers the native P2.5 engine on that exact v0.8 base without rolling back visual changes. Previous engineering PRs remain preserved until post-merge verification. -## Try the current prototype now +## Try it -Open `AR-MIX-Live-FX-Host-Standalone-v0.3.html` in a current Chrome or Edge browser. No installation or internet access is required. The meters are intentionally **simulated**. Clicking `FX RACK` opens a chain editor: add a *demo* plugin, bypass/reorder/remove it; `MIX` offers faders, pan and MUTE/SOLO; `SIGNAL FLOW` describes the path; `SETUP` previews the driver wizard; `EASY VIEW` toggles Pro controls. Save a local FX chain preset or Mixer Snapshot, and export/import a JSON session file. +**Visual preview:** open `AR-MIX-Live-FX-Host-Standalone-v0.3.html` directly in a current browser, or use the `site/preview` UI. Browser preview uses animated demonstration meters and dummy FX. It cannot process your microphone. -**Important:** catalog entries are visual demo effects, not installed VST3 binaries. Nothing will process live audio or activate your mic in this version. The Windows JUCE shell is source-only and has not been compiled/validated on Windows in this environment. +**Actual Windows audio:** from the linked Windows Actions workflow, open the latest **successful integration-branch run** and download its EXE artifact. Use wired headphones at a low level; configure ASIO/WASAPI; open `MIX → ADD FX` to scan/select your own installed VST3, then edit and bypass it in the rack. The source does **not** redistribute FabFilter, iZotope, or other proprietary plugins. -## Build JUCE WebView2 shell (Windows) +For native sound presets, create a sound, mute output and choose `MY SOUNDS → SAVE`. Re-enable output before using experimental `RECALL LIVE`. Check `SIGNAL CHECK` and `audio-diagnostics.log` after a test. Avoid changing audio devices during graph transitions. -Prerequisites: Visual Studio 2022 with C++, CMake >=3.22, a local compatible JUCE 8/9 source checkout, and WebView2 runtime. See licenses before distribution. +This is an **engineering preview**, not qualified for an unattended livestream. Do not equate passing CI with verified dropout-free ASIO/WASAPI or all-plugin compatibility. -```powershell -.\build_windows.ps1 -JuceRoot C:\dev\JUCE -``` +## Building the Windows native app -CMake example: +Requires Visual Studio 2022 C++, CMake 3.22+, compatible JUCE 8, WebView2 and the appropriate ASIO SDK/licensing components. ```powershell cmake -S . -B build -G "Visual Studio 17 2022" -A x64 -DJUCE_ROOT="C:/dev/JUCE" cmake --build build --config Release +ctest --test-dir build -C Release --output-on-failure ``` -The shell embeds the same UI through JUCE BinaryData and uses `WebBrowserComponent::withResourceProvider`. `withEventListener("arMixParameter")` only logs events on the **JUCE message thread**. Implement the typed control dispatcher + RT backend before making it process audio. `JUCE_ASIO=1` is **not yet enabled** in this shell; check GPLv3 ASIO SDK compatibility and driver setup as specified in the ARD. +The source tree separates `src/` (JUCE native engine, VST3 host, diagnostics and state), `web/` (premium console and native bridge), `engine/core/` (reusable realtime controls), `tests/` (native and visual regressions), `docs/` (ARD and phase guides) and `site/` (browser-only landing/preview). GitHub CI tests both Windows MSVC and Chromium layout independently. -## C++20 realtime primitives test - -```bash -g++ -std=c++20 -O2 -Wall -Wextra -pedantic -pthread tests/realtime_control_test.cpp -o rt_tests -./rt_tests -``` +## Planned progression -## Files +1. **P2.5.2** — safe live ADD/REMOVE/REORDER, preparation worker, plugin/device lifecycle and measured crossfade/latency tradeoffs. +2. **P2.6** — actual multichannel input mixer, per-channel VST racks, routing and independent output buses. +3. **P2.7** — complete native session/snapshot persistence, autosave recovery, sound library and beginner-focused flow. +4. Hardware validation and stability gates with common VST3 plugins, including FabFilter/RX, before promoting a qualified release. -- `docs/ARD_AR_MIX_LIVE_FX_HOST_v0.3.md` — full product/technical architecture, RT rules, UX flows, benchmarks, roadmap and risk register. -- `docs/UI_AUDIT_AND_QA_v0.3.md` — source UI audit, fixes and executed smoke test. -- `web/{index.html,styles.css,app.js}` — maintainable UI frontend. -- `AR-MIX-Live-FX-Host-Standalone-v0.3.html` — complete single-file offline trial. -- `src/Main.cpp`, `CMakeLists.txt`, `build_windows.ps1` — native UI host scaffold. -- `engine/core/RealtimeControl.h`, `tests/realtime_control_test.cpp` — tested sample real-time control patterns, not complete DSP. +For the lineage of all parallel threads and outstanding tests, read [the reconciliation ledger](docs/PROGRESS_RECONCILIATION_2026-10-25.md). Previous README content remains preserved in [historical notes](docs/HISTORICAL_README_PRE_RECONCILIATION.md). -## Licensing +## License -Code in this trial is authored for the project and provided under AGPL-3.0-only to align with JUCE open-source licensing. JUCE, ASIO SDK and VST3 SDK have their own notices and obligations; check exact version and dependency licensing before publishing binaries. No third-party VST binaries or proprietary mixer UI graphics are included. +Project code is published under AGPL-3.0-only. JUCE, ASIO, VST3 SDK, third-party artwork and plugin licenses are independent and must be reviewed before redistribution; commercial VST binaries are not included. diff --git a/docs/HISTORICAL_README_PRE_RECONCILIATION.md b/docs/HISTORICAL_README_PRE_RECONCILIATION.md new file mode 100644 index 000000000..789261919 --- /dev/null +++ b/docs/HISTORICAL_README_PRE_RECONCILIATION.md @@ -0,0 +1,104 @@ +# ArSonMix — Live VST3 Host + +**Current integration candidate (25 October 2026): P2.5 live preset graph + latest v0.5 premium mixer GUI.** Desktop Windows x64 / JUCE 8 / ASIO-WASAPI / VST3. The integrated branch is `integration/p25-gui-engine-reconciled`; **the default `main` is older** and must not be treated as the latest native implementation. Code is experimental until Windows hardware tests pass. + +- [Integrated Windows builds](https://github.com/masarray/arsonmix/actions/workflows/p1-windows.yml?query=branch%3Aintegration%2Fp25-gui-engine-reconciled) — download EXE artifact from a successful run. +- [Integration PR](https://github.com/masarray/arsonmix/pulls) and [progress reconciliation ledger](docs/PROGRESS_RECONCILIATION_2026-10-25.md). +- [Premium GUI reference branch](https://github.com/masarray/arsonmix/tree/fix/fader-thumb-symmetry-polish) is archived by branch and imported to the integration source; static browser demo is not a VST host. +- [Latest native engine reference](https://github.com/masarray/arsonmix/tree/feature/p25-live-preset-graph-swap), including real FabFilter/RX compatibility and experimental buffer-boundary preset graph handoff. + +**Actual native status:** Channel 1 stereo path, native VST3 rack/catalog/scan/import, FabFilter and iZotope RX were confirmed to INSERT on user hardware, native VU and PAN, FX bypass, native `.armix` snapshots, experimental Live Recall. **Not yet native:** Channels 2–12, master inserts, master PAN, routing to independent streaming/recording buses, LUFS/true peak. Browser-only session controls are not native persistence. SAVE is muted-only and structure ADD/REMOVE/REORDER still detaches callback. + +## Historical roadmap and previous implementation notes + +The text below documents the development progression. Historical "source-only" or v0.3 statements are superseded by the above current status, not a description of this integration branch. + +--- +# AR MIX Studio — Open-Source Live FX Host (v0.3 UI & Architecture) + +**Status: P1 experimental native Windows first-sound implementation (pending CI/hardware verification) + v0.3 UI demo.** + +AR MIX Studio targets live vocal processing for karaoke performers and livestream creators. It is VST3-first: the principal activity is building a beautiful, low-friction FX chain with a digital-console look. The core engine is planned as C++20/JUCE with Windows ASIO/WASAPI; the frontend is a self-contained HTML/CSS/SVG UI embedded in JUCE WebView2. + +## Try the current prototype now + +Open `AR-MIX-Live-FX-Host-Standalone-v0.3.html` in a current Chrome or Edge browser. No installation or internet access is required. The meters are intentionally **simulated**. Clicking `FX RACK` opens a chain editor: add a *demo* plugin, bypass/reorder/remove it; `MIX` offers faders, pan and MUTE/SOLO; `SIGNAL FLOW` describes the path; `SETUP` previews the driver wizard; `EASY VIEW` toggles Pro controls. Save a local FX chain preset or Mixer Snapshot, and export/import a JSON session file. + +**Important:** catalog entries are visual demo effects, not installed VST3 binaries. Nothing will process live audio or activate your mic in this version. The Windows JUCE shell is source-only and has not been compiled/validated on Windows in this environment. + +## Build JUCE WebView2 shell (Windows) + +Prerequisites: Visual Studio 2022 with C++, CMake >=3.22, a local compatible JUCE 8/9 source checkout, and WebView2 runtime. See licenses before distribution. + +```powershell +.\build_windows.ps1 -JuceRoot C:\dev\JUCE +``` + +CMake example: + +```powershell +cmake -S . -B build -G "Visual Studio 17 2022" -A x64 -DJUCE_ROOT="C:/dev/JUCE" +cmake --build build --config Release +``` + +The shell embeds the same UI through JUCE BinaryData and uses `WebBrowserComponent::withResourceProvider`. `withEventListener("arMixParameter")` only logs events on the **JUCE message thread**. Implement the typed control dispatcher + RT backend before making it process audio. `JUCE_ASIO=1` is **not yet enabled** in this shell; check GPLv3 ASIO SDK compatibility and driver setup as specified in the ARD. + +## C++20 realtime primitives test + +```bash +g++ -std=c++20 -O2 -Wall -Wextra -pedantic -pthread tests/realtime_control_test.cpp -o rt_tests +./rt_tests +``` + +## Files + +- `docs/ARD_AR_MIX_LIVE_FX_HOST_v0.3.md` — full product/technical architecture, RT rules, UX flows, benchmarks, roadmap and risk register. +- `docs/UI_AUDIT_AND_QA_v0.3.md` — source UI audit, fixes and executed smoke test. +- `web/{index.html,styles.css,app.js}` — maintainable UI frontend. +- `AR-MIX-Live-FX-Host-Standalone-v0.3.html` — complete single-file offline trial. +- `src/Main.cpp`, `CMakeLists.txt`, `build_windows.ps1` — native UI host scaffold. +- `engine/core/RealtimeControl.h`, `tests/realtime_control_test.cpp` — tested sample real-time control patterns, not complete DSP. + +## Licensing + +Code in this trial is authored for the project and provided under AGPL-3.0-only to align with JUCE open-source licensing. JUCE, ASIO SDK and VST3 SDK have their own notices and obligations; check exact version and dependency licensing before publishing binaries. No third-party VST binaries or proprietary mixer UI graphics are included. + +## P1 Windows native First Sound + +The new P1 native EXE provides actual microphone passthrough through one VST3 effect, ASIO/WASAPI device selector, bypass, monitor arm/mute, master gain and real callback meter. The old FX rack and channels 2–12 are **still UI previews** (do not confuse demo plugin inserts with native VST3). Output starts muted for hearing/feedback safety. See [P1 trial instructions](docs/P1_FIRST_SOUND.md). + +GitHub Actions: [Windows First Sound builds](https://github.com/masarray/arsonmix/actions/workflows/p1-windows.yml). Download the artifact only after the run is GREEN. JUCE 8.0.15 is pinned by CI and includes GPLv3 ASIO SDK sources; this repository uses AGPLv3. Plugin compatibility and low latency must still be verified with real hardware. + +## P2 Native VST3 Catalog and FX Rack + +The native Windows host supports **Scan VST3**, **Add Plugin Folder**, **Import VST3** and a persistent plugin catalog in user app-data. The FX Rack inside WebView2 now controls the **one native stereo audio path** with up to 8 real VST3 effects: add, bypass, reorder, remove and open plugin UI. The Windows audio setup dialog is also native, with saved device configuration. + +All remaining UI preview channels and factory vocal presets are still visual; do not infer that they are running live audio. Legacy VST2 `.dll` is **not** supported or automatically treated as VST3. Plugin scanning uses a worker, but not yet a crash-isolated subprocess; avoid unknown plugins during a livestream. Read [P2 Hardware Trial](docs/P2_NATIVE_FX_RACK.md). + +## P2 DAW UX improvement + +Use MIX → Channel 1 ADD FX to select a real indexed VST3; PLUGINS opens Plugin Manager for scan/import only. Audio Setup now reports loading status and reuses the native selector window. Scan uses real candidate counters and indeterminate discovery stage. See [P2 DAW workflow guide](docs/P2_DAW_WORKFLOW.md). + +## P2.2 Realtime Reliability + latest ArSonMix GUI + +- The live signal is routed automatically on a valid JUCE device; no extra enable gate. Emergency output mute stays in SIGNAL CHECK. +- Real-time health counters: callback processing time, worst processing time, callbacks over 80% or 100% of buffer period, timing gaps, and worst VST3 processing time. +- Persistent bounded rotating log in user app data `AR-MIX-Studio/diagnostics/audio-diagnostics.log`, using a dedicated logger worker (never audio callback). +- Device XML saved upon device change, **not** on a repeating 3-second UI timer. +- Uses current `fix/fader-thumb-symmetry-polish` GUI (ArSonMix, metal controls, horizontal PAN sliders). Audio host code stays isolated. +- Press SIGNAL CHECK → OPEN DIAGNOSTIC LOG to inspect or share diagnostic evidence after reproducing audio stutter. +- Read [P2.2 reliability guide](docs/P2_REALTIME_RELIABILITY.md). + +## P2.3 — Real Live VU + PAN + Instant FX Bypass + +- In the native JUCE host, v0.3 sine-wave demonstration meter generator is completely disabled. Only real Channel 1 input and real master output move; other preview channels have no fake audio activity. +- Channel 1 horizontal PAN is connected to the actual stereo output matrix after VST3, with a transparent centre and correlated-stereo-safe extremes. +- Each VST3 insert in the MIX view has a small ⏻ toggle with clear ON/OFF state. Bypass updates the atomic realtime control without rebuilding the plugin graph or leaving the MIX screen. +- Diagnostic health JSON no longer truncates every record at 511 characters; the bounded queue slot is now 4096 bytes, with a truncation counter. +- Windows CI validates the native UI contract and real DSP pan coefficient tests. Hardware verification remains necessary. + +## P2.5.1 — Live preset prepared graph + +- Pre-stage plugin binary state before live recall, publish graph at audio callback boundary, retire old graph only after callback acknowledges; de-click buffer fades. +- Does not require MUTE OUTPUT for recall; SAVE still muted-only. Old ADD/REMOVE/REORDER remains callback-detach and should not be used during performance. +- See [P2.5 live recall notes](docs/P25_LIVE_GRAPH_HANDOFF.md). This is not a full seamless dual-DSP crossfade. diff --git a/docs/P1_FIRST_SOUND.md b/docs/P1_FIRST_SOUND.md new file mode 100644 index 000000000..071ed2ac7 --- /dev/null +++ b/docs/P1_FIRST_SOUND.md @@ -0,0 +1,36 @@ +# P1 FIRST SOUND — Windows VST3 host +**Status:** Experimental source implementation. Windows physical I/O and VST3 compatibility must be confirmed by CI and hardware testing. + +## Hardware trial +1. Download the build artifact **AR-MIX-Studio-P1-Windows-x64** from the P1 GitHub Actions run. +2. Extract the ZIP. Install the Microsoft WebView2 Runtime if not already present. +3. Connect an audio interface and use wired headphones; reduce headphone/output volume. +4. Launch the EXE. Output starts **MUTED** deliberately to prevent feedback. +5. Click **AUDIO SETUP** at the bottom status area. Select ASIO when supported, otherwise Windows Audio/WASAPI. Set microphone input, headphone output, 48 kHz, and begin at 128/256 frames. +6. Click **LOAD REAL VST3** and choose one compatible installed stereo `.vst3`. The visual FX rack is still a DEMO: only the actual path chosen in the native strip is loaded. +7. Click **MONITOR ON**. Speak into the microphone and check headphone audio; test bypass. Lower physical gain if clipping or feedback occurs. +8. Open the native audio setup to try 64 frames *after* confirming clean audio at 128/256. Log pops/dropouts and real device latency. + +## Scope +- Native JUCE AudioDeviceManager (ASIO and Windows Audio/WASAPI), live input->output, one effect VST3, device dialog, monitor arm/disarm, bypass, master gain, basic callback-driven meter. +- No per-channel DSP beyond the first live stereo path. Track 2–12 and mock FX rack still simulate UI data, visually dimmed native meter. +- No plugin editor, multichain, host automation, plugin sandbox, latency compensation, snapshot state restore, streaming loopback, or crash isolation yet. +- Plugin insert/removal momentarily detaches audio callbacks. This is safe for ownership but **not glitch-free**. Do not change plugin on air. +- JUCE WebView2 UI does not process real-time audio. The audio callback avoids host-side heap allocations, locks, logging, file I/O and WebView access. Third-party VST3 code may violate RT safety and cannot be trusted. +- Host buffer period in ms is **not** actual input-to-output round-trip latency. Measure hardware loopback separately. + +## Known P1 risks +- Third-party VST3 discovery/creation runs on the message thread and may block or crash with badly-behaved plugins. P2 must isolate scanning and implement verified safe graph transitions. +- The current stereo-only effect restriction intentionally rejects mono-to-stereo and instrument-only plugins. +- ASIO and WASAPI hardware availability varies. Select a single full-duplex interface whenever possible. +- Monitor through **headphones**, not speakers, to avoid acoustic feedback. +- Verify plugin licensing and JUCE/ASIO GPLv3/AGPLv3 obligations before distribution. + +## Acceptance test (not inferred from successful compilation) +- Windows CI green and packaged executable downloads. +- Native output stays silent before user enables monitoring. +- 48 kHz mic -> headphone dry passthrough works. +- Known stereo VST3 changes audible signal; bypass restores dry signal. +- Real device name/rate/buffer/plugin latency reported, meter responds only to real output. +- Startup/shutdown repeat 20x without crash, test 30 min voice monitoring. +- Test ASIO and WASAPI separately, log latency and glitches. This P1 implementation does **not** yet count x-runs. diff --git a/docs/P25_LIVE_GRAPH_HANDOFF.md b/docs/P25_LIVE_GRAPH_HANDOFF.md new file mode 100644 index 000000000..28c41cf5a --- /dev/null +++ b/docs/P25_LIVE_GRAPH_HANDOFF.md @@ -0,0 +1,32 @@ +# P2.5.1 — Live Preset Graph Handoff (ARD P2 safe-recall foundation) + +## Product goal +Previous P2.4 recall required MUTE OUTPUT and called JUCE removeAudioCallback/addAudioCallback around graph changes. This interrupted the hardware path. + +## Implemented +- The existing Add FX FabFilter/RX compatibility and P2.4 .armix ZIP format remain unchanged. +- Preset recall validates every archive entry, recreates all VST3 processor instances, restores each vendor binary state, and prepares DSP outside the realtime callback while the old graph continues to process audio. +- A bounded **one-slot publication** object exposes an immutable prepared Graph pointer at a buffer boundary. RT thread does no plugin creation, graph copying, mutex locking, dynamic allocation, or third-party destruction during handoff. +- In the last old callback the output gain ramps downward over one buffer; new graph is activated at callback boundary. In the first new callback output ramps upward. No double-DSP old/new crossfade occurs: avoids worst-case CPU doubling with expensive RX/FabFilter processors. +- Audio callback publishes the retired pointer. JUCE message timer takes acknowledgment and destroys old plugin instances only after old callback is finished, then announces successful recall to UI and updates Channel 1/FX Rack controls. +- Snapshot fader/PAN/mute/master settings and VST3 latency are updated at graph transition. Hardware input/output device is untouched. +- New stress test executes 12,000 cross-thread graph handoffs and validates no early reclamation, no second pending graph and expected fade endpoints. +- Counters `completedGraphSwaps` and `graphSwitchPending` are added to status and 1-Hz diagnostics. + +## Precisely what is NOT complete +- This is **buffer-boundary declick switching** with a roughly two-buffer gain dip, not genuinely seamless dual-run or delay-compensated crossfade. Effect tails do not persist through graph replacement. +- Add/Remove/Reorder FX still detach the callback and can cause a brief glitch; graph structural edits need separate migration. +- Plugin preparation and ZIP reading remain synchronous on the message thread, so UI may freeze temporarily although audio callback remains independent. Next phase must stage on background worker, coordinate JUCE plugin threading requirements and deal with plugin state APIs that require message-thread affinity. +- Simultaneous audio device change while a graph is pending should be avoided until device-lifecycle cancellation is implemented. +- Plugin compatibility and xrun telemetry must be verified with real FabFilter, iZotope RX and ASIO hardware before declaring live-ready. + +## Windows physical acceptance +1. Load FabFilter (e.g., Pro-Q) and iZotope RX, confirm both work; save as `Chain A` (P2.4 save still requires output muted). Repeat with a second preset `Chain B` containing a different sound. +2. Unmute output and play continuous signal. Open MY SOUNDS and RECALL LIVE alternating presets while listening on headphones. +3. Check graph count increases in SIGNAL CHECK diagnostic status; ensure the audio device never restarts, current and new plugin editors open correctly, and saved vendor states restore. +4. Compare interrupted signal length and xrun timing with old P2.4 and review AUDIO_HEALTH after 2 minutes. Avoid device changes during recall. +5. On any stuck load or stream loss, share `audio-diagnostics.log` and stop using the experimental release for a real broadcast. + +## Release gates +- Windows x64 MSVC, JS contract, CTest stress all green. +- Physical 30+ minute soak and plugin-specific AB listening (FabFilter, RX, ArSonKuPik) still required. Draft PR only. diff --git a/docs/P2_DAW_WORKFLOW.md b/docs/P2_DAW_WORKFLOW.md new file mode 100644 index 000000000..19bcd142e --- /dev/null +++ b/docs/P2_DAW_WORKFLOW.md @@ -0,0 +1,34 @@ +# P2 DAW Workflow & Progress UX — Windows Trial + +## What changed + +- **Mixer-first add:** click **ADD FX** directly on channel 1. The FX selector opens an indexed VST3 catalog with search and categories. Click **+ ADD** to insert into the real native chain; existing mixer insert buttons open plugin editors. Do not confuse the other 11 visual channel strips with native I/O. +- **Plugin Manager:** **PLUGINS** in the toolbar opens plugin administration. System scan, custom folder scan and individual `.vst3` import exist exclusively here, not inside the effects picker. +- **Real scanning progress:** while finding `.vst3` candidates the total is unknown (animated indeterminate bar). Once the scanner has enumerated candidate modules, the bar becomes determinate using **processed candidate count / total candidates**. It shows current module and effects found; no invented percentages. +- **Audio Setup progress:** opening from toolbar or SETUP immediately shows a busy dialog while JUCE initializes the selector. First-open ASIO driver enumeration may still take time. The app reports actual setup construction time in milliseconds; the native audio setup window is reused for later opens. +- **Background:** VST3 scan runs on a dedicated worker. Metadata discovery can still run untrusted third-party plugin code; there is no crash isolation in this version. +- **Monitor safety:** scanning and chain structural changes require MONITOR OFF. Live bypass uses atomic flags in the native engine. + +## Quick trial + +1. Download and unzip **AR-MIX-Studio-P2-DAW-Workflow-Windows-x64** from a successful GitHub Actions run. +2. Launch the EXE and click **AUDIO SETUP**. Observe a graphical progress indicator; configure your ASIO or WASAPI input/output. Close settings, then reopen to verify faster cached window reuse. +3. Click **PLUGINS** and **SCAN STANDARD FOLDERS**. Watch the scan change from discovery (indeterminate) to candidate inspection (% with real totals). Import a single .vst3 with **IMPORT INDIVIDUAL .VST3** or add a folder if needed. +4. Return to **MIX**, click **ADD FX** on Channel 1, search the catalog, and choose **+ ADD**. The effect should appear in the real channel rack. Click the inserted plugin to open its native editor. +5. With monitoring off, build your chain. Enable monitoring only after you have wired headphones at low volume and have a stable driver setup. + +## Known limits + +- First ASIO driver enumeration may still be slow or blocked by an external driver. Reporting an indeterminate busy state is honest; claiming a fake numeric percentage is not. Timing data supports the next performance audit. +- Scanner currently loads third-party plugin metadata in the application process. Crashes/hangs remain possible. +- The catalog indexes VST3 only. VST2 *.dll loading is unsupported. +- P2 is one native Channel 1 input path with up to eight serial stereo VST3 effects, not a complete 12-channel live mixer. +- GUI and scanner features compile in Windows CI but hardware scan/audio/editor behavior must be validated on a physical Windows PC. + +## Acceptance + +- Windows CI GREEN including `node --check web/bridge.js`, C++ Release build and RT tests. +- Opening Audio Setup displays busy feedback immediately; subsequent opens use the cached native window. +- Plugin Manager displays real progress with total after discovery. +- ADD FX on mixer opens selector without navigation to manager. +- No fake scan percentages, no plugin scan operations accidentally triggered from FX selection. diff --git a/docs/P2_FABFILTER_FX_COMPATIBILITY.md b/docs/P2_FABFILTER_FX_COMPATIBILITY.md new file mode 100644 index 000000000..97336438d --- /dev/null +++ b/docs/P2_FABFILTER_FX_COMPATIBILITY.md @@ -0,0 +1,23 @@ +# P2.4.1 — VST3 Add FX compatibility and failure diagnostics + +Hardware report: FabFilter plugins appear in installed VST3 catalog, but pressing ADD has no visible effect. + +## Source audit and fixes +- Confirmed UX defect: Native engine previously emits loading errors as a toast obscured by the Add VST3 modal; a failed insert looks like no response. +- Confirmed compatibility restriction: the host always called `setBusesLayout` with exactly one stereo input and one stereo output, potentially rejecting VST3s with an auxiliary sidechain bus or already valid default layout. Now it preserves the plugin's existing compatible main stereo bus layout, or negotiates stereo main with optional auxiliary buses disabled. +- Plugin creation still runs synchronously in the UI message thread; an indeterminate "Loading…" indicator is painted before calling JUCE, but long/blocked third-party VST creation remains possible. +- New native result event `arMixAddResult` sends result/error, elapsed time, request ID and chain size. Failures stay visible **inside** the Add FX dialog, with a diagnostic log event `FX_LOAD_FAIL`. +- Both adding a plugin and restoring a native preset apply the same bus negotiation. + +## Trial +1. Use the new Windows artifact in PR; open **MIX → ADD FX**, search FAB. +2. Choose FabFilter Pro-C 2, Pro-Q or Pro-DS. Observe Loading… status, then insert success or visible exact error. +3. On success, the plugin appears in Channel 1 live rack; click its name to open native UI; toggle power to bypass. Test with headphones at low volume. +4. On failure, copy the full text of the red FX NOT LOADED message and open **SIGNAL CHECK → OPEN DIAGNOSTIC LOG**. Attach log for class/bus/plugin-specific diagnosis. +5. Test at least one previously working ArSonKuPik and native preset Save/Recall to prevent regression. + +## Remaining risks +- No real FabFilter VST3 binary and license is available to CI. Windows build GREEN does **not** prove vendor-specific runtime compatibility. +- Creating VSTs remains synchronous on the host message thread, so slow initialization may stall even with a Loading state. True off-thread staging plus graph swap is subsequent ARD work. +- Scanner is a worker thread, not a separate crash-isolated process. +- Host processes exactly one native stereo Channel 1 path; other mixer strips remain previews. diff --git a/docs/P2_LIVE_METER_PAN_FX_BYPASS.md b/docs/P2_LIVE_METER_PAN_FX_BYPASS.md new file mode 100644 index 000000000..d2819d1e0 --- /dev/null +++ b/docs/P2_LIVE_METER_PAN_FX_BYPASS.md @@ -0,0 +1,22 @@ +# P2.3 — True VU meters, real PAN and fast VST3 bypass + +## Changes +- **Native VU meters**: removed the conflicting sine-wave demo meter requestAnimationFrame path in the native WebView. Only Channel 1 input and real master output are driven from JUCE status samples. Other 11 channels remain explicitly inactive visual previews, with meter lamps disabled. +- **Meter appearance**: UI-only peak attack with a small falling-ballistic smoothing on incoming native input and master peak readings (12 Hz status cadence). No fabricated noise or sine animation. +- **Native PAN**: Channel 1 pan slider -100..100 now controls an atomic normalized stereo pan matrix applied *after* actual VST3 processing, before master gain. At centre, stereo passes unchanged. At a hard side, both stereo channels fold into the target channel at 0.5 each; dual-mono does not double its amplitude. Stereo balance is not a full multichannel spatial panner. +- **Fast Studio One-style insert enable**: Every native FX insert on the MIX channel strip now includes a dedicated ON/OFF power toggle. Clicking the plugin body still opens the VST3 editor. Power updates the existing atomic bypass flag, without callback detachment or FX Rack navigation. The FX Rack includes the same on/off state. +- **Logger repaired**: Uploaded 08:48–08:54 diagnostic log contained 364 AUDIO_HEALTH lines with exactly 511 bytes of text each, so time counters and VST slot details were truncated. Queue slot increased from 512 to 4096 bytes and truncation counts are exposed for verification. This does *not* retroactively recover the missing metrics. +- **Latest GUI**: adopted the current style sheet from the metallic PAN/fader GUI branch. No redesign of accepted user artwork. + +## Acceptance tests +1. Run the new native EXE and confirm only Channel 1 input and master output react to actual input. All other strip meters remain dormant, even after changing tabs and moving faders. +2. Move Channel 1 PAN to hard left, centre and hard right with stereo headphones. A dual-mono vocal should move to the chosen ear and return to both at centre. +3. Add ArSonKuPik to MIX Channel 1, click the small ⏻ button on its insert (not the editor name). Sound must alternate FX processed/bypassed without an audio device restart. Watch ON/OFF immediately reflect native chain state. +4. Click the plugin name to open the native VST3 editor. +5. Open SIGNAL CHECK and OPEN DIAGNOSTIC LOG, reproduce for 1–2 minutes, confirm AUDIO_HEALTH JSON records are no longer clipped at 511 characters and the callback/plugin timings can be parsed. +6. Verify monitoring still flows automatically and no sonic dropout is introduced. + +## Boundaries +- Only Channel 1 is native. The other channels and their mock inserts are visual previews. +- A successful CI build does not prove audio quality or round-trip stability on specific Windows hardware. +- Real ASIO/WASAPI channel assignment for 12 native channels, presets and streaming output is still out of scope. diff --git a/docs/P2_NATIVE_FX_RACK.md b/docs/P2_NATIVE_FX_RACK.md new file mode 100644 index 000000000..e98956311 --- /dev/null +++ b/docs/P2_NATIVE_FX_RACK.md @@ -0,0 +1,37 @@ +# AR MIX Studio P2 — Native VST3 Catalog and FX Rack (Experimental) + +## Try on Windows +1. Open the GitHub Actions build artifact `AR-MIX-Studio-P2-Windows-x64` from the successful workflow. +2. Unzip, open `AR-MIX-Studio-P2.exe`. Audio monitoring is OFF at startup. +3. In **SETUP**, choose **OPEN ASIO / WASAPI DEVICE SETTINGS**, select an input+output interface, 48 kHz, and 128/256 samples to start. +4. In **FX RACK**, click **RESCAN VST3** to search system VST3 locations, **ADD PLUGIN FOLDER** for an additional installation directory, or **IMPORT VST3 FILE** for an individual `.vst3` file/bundle. +5. Results appear in the persistent native catalog. Search by plugin name or vendor. Click **+ ADD** to insert the plugin into the actual audio chain. Repeat up to 8 plugins. +6. **EDIT** opens the plugin's native UI; **ON/OFF** bypasses; arrows change order; **×** removes. Changes pause the callback briefly, so do not perform them on-air. +7. With headphones and low hardware volume, click **MONITOR ON**. Confirm audible change between plugin ON/OFF and watch real input/master meters. + +## What P2 actually implements +- Windows ASIO/WASAPI using JUCE AudioDeviceManager and native selector. +- Settings persisted to user app-data `AR-MIX-Studio/audio-devices.xml`. +- Native VST3 catalog persisted to `AR-MIX-Studio/plugin-catalog.json`. +- Recursive scan of default/custom folders, direct import of one `.vst3` file/bundle, cached display between sessions. +- Single live microphone/stereo audio path with maximum eight native VST3 inserts, native plugin UI, order, bypass, removal. +- Low-allocation host callback. UI and scanning are outside the callback. + +## Explicit exclusions / safety +- **VST2 DLL** is not a VST3 module; raw DLL import is intentionally rejected. VST2 would require a separate, vetted SDK/licensing strategy. +- **Scanning is on a worker thread, not a crash-isolated subprocess**. Broken plugins may still crash or hang the host. This is experimental. +- The other 11 mixer channels and their visual presets are still a concept. Native FX chain applies only to channel 1. +- Real plugin state preset/save/restore, sidechain routing, bridge to OBS and round-trip measurement are not finished. +- VST3 processBlock code belongs to third-party plugins. Host-side callback design alone cannot guarantee zero allocations, x-runs or crashes. +- Plugins that do not support stereo effect layout may be rejected. Missing/invalid libraries are reported to the user. +- Do not infer audio reliability from successful GitHub Actions compilation. Validate with ASIO and WASAPI on physical hardware. + +## Acceptance +- GitHub Actions release x64 build GREEN and artifact uploaded. +- Scan actual VST3 installation, catalog populated and survives restart. +- Add/remove/bypass/edit/reorder two real plugins and verify audible routing. +- Save/restart audio device settings and verify the same device is selected. +- Test repeatedly with headphones, 48 kHz / 128 samples then 64 only after stable result. + +## Live-safe P2 operations +Bypass toggles are atomic and do not detach the audio callback. Scanning plugins and add/remove/reorder are refused when monitoring is enabled, so the singer cannot accidentally force an audio callback restart while live. Turn MONITOR OFF to edit chain structure, then arm monitoring again. The VST3 code itself is third-party; test carefully. diff --git a/docs/P2_NATIVE_PRESETS.md b/docs/P2_NATIVE_PRESETS.md new file mode 100644 index 000000000..0423b0778 --- /dev/null +++ b/docs/P2_NATIVE_PRESETS.md @@ -0,0 +1,27 @@ +# P2.4 — Native My Sounds · VST3 binary preset ZIP + +**Source of requirements:** `docs/ARD_AR_MIX_LIVE_FX_HOST_v0.3.md`, sections 2, 7, 8, 8.1, 13. This phase closes the fundamental persistence gap. This is NOT yet complete session/snapshot support or live-safe hot-swap. + +## Completed milestone +- A native `MY SOUNDS` button is available beside Live FX Rack and in the FX Rack toolbar. +- Save `*.armix` files to the native app-data `AR-MIX-Studio/presets/` directory. +- ZIP contains `manifest.json` and `state/00.bin` through `state/07.bin`, captured with JUCE `AudioPluginInstance::getStateInformation` and restored with `setStateInformation` (full vendor-controlled binary state, unlike browser dummy knobs). +- Manifest includes schema/version, Channel 1 input gain/PAN/mute, master gain/mute, ordered stable plugin file/UID/catalog identity, bypass and SHA-256 per plugin-state blob. Output device/driver routing is **not** stored or switched. +- Input validates 8-plugin maximum, 8 MiB per plugin state, ZIP file 72 MiB, 256 KiB manifest, fixed entry names/entry count, finite numeric settings, plugin identity and SHA-256. It never extracts archive entries to arbitrary filesystem paths. +- Recall stages a full new chain and restores each VST3 state before detaching the existing audio callback. If plugin validation/creation/state restoration fails, active chain is left intact. Old processors are retired on the message thread after callback is detached. +- Audio output **must be muted before save or recall** because vendor plugin binary state calls and current graph detach are not guaranteed glitch-free. Output remains muted after recall. The UI explains why instead of silently interrupting a live broadcast. + +## Physical trial on Windows +1. Select input/output in AUDIO SETUP and add ArSonKuPik or another known working VST3. Make an audible adjustment inside the plugin editor. +2. Open SIGNAL CHECK and click MUTE OUTPUT. Open MY SOUNDS, enter `Vocal Test 1`, SAVE SOUND. +3. Edit the plugin parameters to something clearly different or remove the plugin while muted. +4. Open MY SOUNDS and RECALL the saved sound. Check plugin editor state, bypass and processing, fader/PAN/master settings, and insert order. Unmute output manually. +5. Close/restart the EXE and repeat recall. Native presets should persist. Confirm there is no unexpected audio-device switch. +6. Test corrupted archives and missing plugins. The current chain must be retained when validation fails. + +## Deferred ARD work / phase gate +- Smooth live graph switching with a prepared immutable graph + epoch-ack and bounded crossfade, so snapshot changes can be auditioned without output mute. +- Full mixer snapshots including every native channel and sends, A/B preview, durable sessions and autosave journal. +- Dedicated storage worker and out-of-process plugin scanner. ZIP save/restore I/O and vendor plugin preparation currently run on the non-real-time message thread *while output is muted*. +- Multiple independent physical/virtual inputs and real routing/stream output, rather than demo strips. +- Plugin compatibility test matrix / actual Windows xrun & 60-minute soak gates. diff --git a/docs/P2_REALTIME_RELIABILITY.md b/docs/P2_REALTIME_RELIABILITY.md new file mode 100644 index 000000000..cfe18d820 --- /dev/null +++ b/docs/P2_REALTIME_RELIABILITY.md @@ -0,0 +1,43 @@ +# ArSonMix P2.2 — Investigating recurring audio dropouts + +**Status:** Experimental Windows diagnostic build. Performance counters are evidence, not a concluded root cause. + +## Current evidence from the user's PC +- VST3 host produces audio when output is enabled, thus at least one valid input→VST→master→Windows Audio output path exists. +- Displayed device: Windows Audio, 48 kHz, 480-sample buffer = 10 ms nominal buffer period. +- The VST3 chain advertised 960 samples processing latency = 20 ms at 48 kHz. This is plugin latency **not** measured system round-trip latency. +- Reported audio pauses every few seconds. Source inspection found an old 3-second synchronous device XML state poll on the message thread. That was unnecessary and is now removed, but it is a candidate cause, **not a proven diagnosis**. +- Other candidates include WASAPI scheduling irregularity, slow VST3 processBlock, input/output endpoint contention, and device stop/restart events. + +## Implemented changes +1. **Auto-routing:** with a valid duplex device selected, the output is active without an extra arm button. A user-accessible emergency MUTE OUTPUT in SIGNAL CHECK remains available; use headphones at low volume to prevent feedback. +2. **Event-driven settings:** AudioDeviceManager ChangeListener marks device XML dirty. It is no longer repeatedly serialized and written on a 36-tick / 3-second timer. +3. **Realtime measurements:** atomic counters are updated inside the audio callback, with no file I/O, locks, heap allocations in host callback logic, or GUI calls. Measures callback duration, worst duration, processing beyond 80% of available callback period, over-budget callbacks, long callback scheduling gaps and slow plugin time. +4. **Background diagnostics:** a bounded 128-record SPSC UI→worker queue writes 1 Hz health snapshots and event markers to a rotating 2 MB log (plus previous). The plugin/audio callback only publishes numeric counters, not file records. +5. **Visual diagnostics:** SIGNAL CHECK shows live input/post-FX/output meters plus deadline timing; OPEN DIAGNOSTIC LOG reveals the local file. +6. **Current GUI:** imported current source (ArSonMix brand, metallic faders, horizontal PAN slider, tactile buttons) from GUI branch `fix/fader-thumb-symmetry-polish`. Maintains working native VST3 plugin picker/catalog. +7. **Live FX structural operations:** add/remove/reorder may still briefly detach callbacks. Do not perform them during a performance until graph hot swap is engineered. + +## Reproduction / engineering triage + +1. Choose the same selected input and headphone output. Start with 48 kHz / 480 samples to reproduce reported problem, keep output/headphone volume low. +2. In SIGNAL CHECK, note worst callback duration, over-budget count, callback-gap count and plugin time. Keep recording for at least 2–3 minutes through the intermittent symptom. +3. First test with **DRY TEST ON** (all VST3 skipped, same audio device). Observe and record if dropout remains. Then turn DRY TEST OFF and test each plugin in isolation. +4. Try ASIO on one full-duplex interface, initially 128–256 samples if supported; separately compare Windows Audio/WASAPI. Driver and endpoint selection must be changed through Audio Setup. +5. Use OPEN DIAGNOSTIC LOG. Copy the latest log around the timestamps of audible stutters, with device and plugin names sanitized if sharing publicly. +6. Interpret cautiously: + - Slow callback/over-budget jumps near a dropout suggest a DSP deadline miss (plugin processing or callback). + - Slow plugin increments suggest one or more VST3 calls are consuming most of the deadline. This release logs each VST3 slot's last and worst processing time to help identify a slow insert. Compare slot timings and use DRY TEST to confirm causality. + - A callback scheduling gap jump with low process time suggests driver/OS scheduling or device discontinuity. + - Flat counters despite audible loss suggest an endpoint, physical device, external virtual cable, or a discontinuity not captured by this timing probe. +7. Success criterion: sustained uninterrupted mic→dry→master output and then mic→VST3→master output; no observed dropout on the actual physical interface. + +## Engineering limits / follow-up +- These are **timing indicators, not driver-confirmed xrun counts**. Device-specific ASIO/WASAPI dropout callback telemetry is still missing. +- Third-party VST3 plugin code may allocate or block; the host cannot enforce its RT safety. +- No complete plugin crash sandbox or seamless FX graph swap yet. +- Real output to streaming apps is separate from the output endpoint in the JUCE device selector. UI “Record/Streaming” output buttons remain previews until real routing is implemented. +- The log may contain local device/plugin names; treat it as diagnostic user data. + +## Additional telemetry +Audio-device start and stop callback counts are recorded, together with per-VST3 slot last/worst process duration (microseconds). A rise in device stop/start around stutters indicates a device lifecycle event; a rise in one slot's processing duration indicates a potentially expensive effect. Time counters alone do not prove that a device underrun occurred. diff --git a/docs/PROGRESS_RECONCILIATION_2026-10-25.md b/docs/PROGRESS_RECONCILIATION_2026-10-25.md new file mode 100644 index 000000000..4c0bd0f85 --- /dev/null +++ b/docs/PROGRESS_RECONCILIATION_2026-10-25.md @@ -0,0 +1,55 @@ +# Main v0.8 + P2.5 native reconciliation — merge candidate + +- **Non-negotiable GUI source:** `main` at `aff95a7c811a3817edf61303e1f24ef31e53d11d` (merged GUI v0.8 PR #2). +- **Native engine parent:** `feature/p25-live-preset-graph-swap` checkpoint `7a769105595aeaa2f8d8e3a549143426fdba5eae`; the MSVC CI green integration checkpoint is `351eb79bd8df775aadb4810c1cf53f7410cea411`. +- Merge strategy: retain `main` v0.8 `web/app.js` semantics, `web/styles.css`, `web/index.html` layout, `site/` and visual tests; add native C++ engine, backend bridge, tester, docs, and only the fake-meter guard / bridge script references. Native output is intentionally limited to Channel 1 and Master L/R for truthful behavior. +- This is **a development merge**. No physical hardware soak; do not call the release stable. +- Both `main` and upstream GUI + engine checkpoint remain independently available and recoverable. + +--- + +# ArSonMix — Cross-thread reconciliation ledger (2026-10-25) + +This is the authoritative **development baseline** for the integration candidate, not evidence of hardware qualification. + +## Canonical integration +- Branch: `integration/main-v08-gui-p25-native`. +- **Engine ancestor**: `feature/p25-live-preset-graph-swap` @ `7a769105595aeaa2f8d8e3a549143426fdba5eae`, Windows CI GREEN run [40164992415](https://github.com/masarray/arsonmix/actions/runs/40164992415). +- **GUI visual source**: `fix/fader-thumb-symmetry-polish` @ `7d4892036caadd97c79e03321e8f11de5d3d3dcf`. Restored latest channel identity editor, dedicated master strip inside the mixer, tactile hardware PNGs, clip/peak and refined PAN/faders, premium dark metal controls. +- **UI-to-engine adapter**: `web/bridge.js` inherited from P2.5 and adapted to current GUI DOM. ONLY real Channel 1/real Master measurements control the native meters. No sinusoidal demo meters run in JUCE. +- **No destructive cherry-pick**: neither GUI branch nor historic PRs were overwritten. All original branches/PRs remain readable. The integration source incorporates visual code on top of native engine with contract tests. + +## Proven / supported vs incomplete +| Capability | Current integrated claim | Evidence/limit | +|---|---|---| +| GUI premium | Latest GUI branch imported into Windows host | Browser visual QA required on integration PR | +| Channel identity (name/icon/color) | Interactive UI, saved as GUI/session state | Not authoritative for audio routing | +| VU native | Ch1 input and independent Master L/R sourced from DSP | Channel 2–12 fake activity disabled | +| VST3 FabFilter/iZotope RX insert | Confirmed by user on previous P2.4.1 Windows EXE | Retest integrated EXE | +| VST3 catalog, add/open/editor/bypass | C++ native Channel 1 | Others GUI placeholders | +| `.armix` real plugin state | Native ZIP binary-state, validation and restore | Runtime vendor round-trip needs hardware test | +| P2.5 recall during output active | Prepared graph, callback-boundary fade and deferred retirement | No dual-graph crossfade; audio dips around transition; not qualified for performance | +| ADD/REMOVE/REORDER FX | Real Channel 1; callback may detach and briefly stop | Not yet live-safe | +| MASTER FX and master PAN | Attractive GUI **preview only**; controls disabled in native shell | Master fader/MUTE and true L/R meter remain native | +| Full mixer/streaming/record routing | Not implemented | Next phase P2.6 | +| 30–60 minute soak/xrun/third-party crash sandbox | Not completed | Release blocker | + +## Branch and PR ancestry (DO NOT DELETE) +The following PR stack retains all historical engineering changes, and **must not be blindly merged in arbitrary order**: +1. [PR #1](https://github.com/masarray/arsonmix/pull/1) P1 native first sound +2. [PR #3](https://github.com/masarray/arsonmix/pull/3) P2 VST3 catalog and native FX +3. [PR #4](https://github.com/masarray/arsonmix/pull/4) DAW selection/scan progress +4. [PR #5](https://github.com/masarray/arsonmix/pull/5) output/diagnostics +5. [PR #6](https://github.com/masarray/arsonmix/pull/6) realtime telemetry/auto route +6. [PR #7](https://github.com/masarray/arsonmix/pull/7) true VU, PAN, bypass +7. [PR #8](https://github.com/masarray/arsonmix/pull/8) My Sounds native binary state +8. [PR #9](https://github.com/masarray/arsonmix/pull/9) FabFilter/RX VST3 bus compatibility +9. [PR #10](https://github.com/masarray/arsonmix/pull/10) live graph handoff. +GUI [PR #2](https://github.com/masarray/arsonmix/pull/2) is an **independent visual branch**, incorporated selectively here. +Original developer source, assets, standalone preview, docs and QA tests remain in their originating branches. + +## Safety and release policy +- Keep `main` unchanged until **both** Windows native CI and Chromium visual smoke are GREEN, plus real hardware trial has confirmed VST3 insert/edit/bypass and preset recall. +- Experimental release is not "stable", no IEC/audio standards certification, no guaranteed glitch-free audio. +- One canonical artifact per promoted revision; no duplicate unverified EXE claiming latest stable. +- Next milestone after reconciled acceptance: P2.5.2 live-safe ADD/REMOVE/REORDER, worker preparation and safe device lifecycle; then P2.6 real multichannel routing, then P2.7 full mixer sessions. diff --git a/src/DiagnosticsRecorder.h b/src/DiagnosticsRecorder.h new file mode 100644 index 000000000..f7973a5a0 --- /dev/null +++ b/src/DiagnosticsRecorder.h @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include + +// Bounded UI-thread -> file-thread telemetry queue (SPSC). +// Audio callback NEVER interacts with this class. The UI samples atomics +// at 1 Hz and enqueues a compact record; file I/O occurs only on worker. +class DiagnosticsRecorder final : private juce::Thread +{ +public: + explicit DiagnosticsRecorder (const juce::File& directory) + : juce::Thread ("AR MIX Diagnostic Writer"), + folder_ (directory), logfile_ (directory.getChildFile ("audio-diagnostics.log")) + { + folder_.createDirectory(); + startThread(); + record ("SESSION", "started"); + } + + ~DiagnosticsRecorder() override + { + record ("SESSION", "closing"); + signalThreadShouldExit(); + notify(); + stopThread (5000); + } + + // Producer: JUCE message thread only; may allocate, never RT. + void record (const juce::String& kind, const juce::String& details) + { + const auto head = producer_.load (std::memory_order_relaxed); + const auto next = (head + 1) % capacity; + if (next == consumer_.load (std::memory_order_acquire)) + { + lost_.fetch_add (1, std::memory_order_relaxed); + return; + } + const auto timestamp = juce::Time::getCurrentTime().toISO8601 (true); + juce::String message = timestamp + " | " + kind + " | " + + details.replaceCharacters ("\r\n", " "); + const auto utf8 = message.toRawUTF8(); + auto& slot = queue_[head]; + const auto inputLength = std::strlen (utf8); + const auto count = juce::jmin (static_cast (sizeof (slot.data) - 1), + inputLength); + if (inputLength > count) + truncated_.fetch_add (1, std::memory_order_relaxed); + std::memcpy (slot.data, utf8, count); + slot.data[count] = 0; + producer_.store (next, std::memory_order_release); + notify(); + } + + juce::File getLogFile() const { return logfile_; } + std::uint64_t lostRecords() const noexcept { return lost_.load(); } + std::uint64_t truncatedRecords() const noexcept { return truncated_.load(); } + +private: + static constexpr unsigned capacity = 128; + struct Record { char data[4096] {}; }; + std::array queue_ {}; + std::atomic producer_ { 0 }, consumer_ { 0 }; + std::atomic lost_ { 0 }, truncated_ { 0 }; + juce::File folder_, logfile_; + + void run() override + { + // One write per drain batch, never from the UI or audio callback. + for (;;) + { + juce::String batch; + unsigned tail = consumer_.load (std::memory_order_relaxed); + const auto head = producer_.load (std::memory_order_acquire); + while (tail != head) + { + batch += juce::String::fromUTF8 (queue_[tail].data); + batch += "\n"; + tail = (tail + 1) % capacity; + } + consumer_.store (tail, std::memory_order_release); + if (batch.isNotEmpty()) + { + if (logfile_.getSize() > 2 * 1024 * 1024) + { + auto rotated = folder_.getChildFile ("audio-diagnostics.previous.log"); + rotated.deleteFile(); + logfile_.moveFileTo (rotated); + } + logfile_.appendText (batch, false, false, "\n"); + } + if (threadShouldExit() && tail == producer_.load (std::memory_order_acquire)) + break; + wait (350); + } + } +}; diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h new file mode 100644 index 000000000..95c437d55 --- /dev/null +++ b/src/LiveAudioEngine.h @@ -0,0 +1,669 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include "StereoPan.h" +#include "NativePresetArchive.h" +#include "VstBusLayout.h" +#include "LiveGraphHandoff.h" +#include +#include +#include +#include +#include +#include + +// One live stereo input path and up to 8 actual VST3 processors. +// The audio callback never scans files, creates plugins, mutates the chain, +// enters UI code, locks host mutexes, logs, or changes device settings. +// P2.5 recall pre-stages a graph and transitions at callback boundaries. +// Legacy Add/Remove/Move still detach; seamless structural editing is deferred. +class LiveAudioEngine final : private juce::AudioIODeviceCallback +{ +public: + static constexpr int maxFx = 8; + + struct Slot + { + std::unique_ptr processor; + juce::String name, catalogId, path; + int uid = 0; + bool bypass = false; + int latency = 0; + }; + + struct Graph + { + std::array slots {}; + std::array, maxFx> bypassFlags {}; + int count = 0; + int latency = 0; + bool hasRecallState = false; + float channelDb = 0.f, masterDb = 0.f, pan = 0.f; + float channelLinear = 1.f, masterLinear = 1.f; + bool channelMute = false, masterMute = false; + }; + + LiveAudioEngine() + { + formats_.addFormat (std::make_unique()); + scratch_.setSize (2, maxFrames, false, true, false); + handoff_.initialize (graphOwned_.get()); + } + + ~LiveAudioEngine() override { stop(); } + + juce::AudioDeviceManager& devices() noexcept { return deviceManager_; } + + juce::String start (const juce::XmlElement* savedSettings = nullptr) + { + // A mixer behaves like a signal path: ready I/O flows automatically. + // The former MONITOR enable gate caused silent master/output confusion. + // Panic OUTPUT MUTE remains available at all times. + monitor_.store (true); + const auto error = deviceManager_.initialise (1, 2, savedSettings, true); + if (error.isNotEmpty()) return error; + deviceManager_.addAudioCallback (this); + attached_ = true; + return {}; + } + + void stop() + { + detach(); + handoff_.resetAfterStop (graphOwned_.get()); + stagedOwner_.reset(); + for (int i = 0; i < graphOwned_->count; ++i) + { + if (graphOwned_->slots[i].processor) graphOwned_->slots[i].processor->releaseResources(); + graphOwned_->slots[i] = Slot {}; + } + graphOwned_->count = 0; + deviceManager_.closeAudioDevice(); + } + + void setMonitorEnabled (bool value) noexcept { monitor_.store (value); } + bool isMonitorEnabled() const noexcept { return monitor_.load(); } + // Emergency output mute, not a prerequisite for receiving audio. + void setOutputMuted (bool mute) noexcept { monitor_.store (!mute, std::memory_order_release); } + bool isOutputMuted() const noexcept { return !monitor_.load (std::memory_order_acquire); } + void setDryTestEnabled (bool value) noexcept { dryTest_.store (value); } + bool isDryTestEnabled() const noexcept { return dryTest_.load(); } + void setMasterGainDb (float value) noexcept + { + if (std::isfinite (value)) masterGain_.store (juce::Decibels::decibelsToGain (juce::jlimit (-60.f, 10.f, value))); + } + void setChannelGainDb (float value) noexcept + { + if (std::isfinite (value)) channelGain_.store (juce::Decibels::decibelsToGain (juce::jlimit (-60.f, 10.f, value))); + } + // True stereo-to-stereo pan: centre preserves stereo; extremes fold + // both stereo input channels to the chosen side at unity for dual-mono. + // Parameter is normalized on the UI thread; callback only loads atomic. + void setChannelPan (float value) noexcept + { + if (std::isfinite (value)) + channelPan_.store (juce::jlimit (-1.f, 1.f, value), std::memory_order_relaxed); + } + void setChannelMuted (bool value) noexcept { channelMute_.store (value); } + void setMasterMuted (bool value) noexcept { masterMute_.store (value); } + + int chainSize() const noexcept { return graphOwned_->count; } + bool isGraphSwitchPending() const noexcept { return handoff_.busy(); } + // Invoke from the JUCE message thread, at most once per timer tick. + // Retire only after the callback has acknowledged and left the old graph. + bool finalizeGraphSwitch() + { + auto* retired = handoff_.takeRetired(); + if (!retired) return false; + jassert (retired == graphOwned_.get()); + if (retired != graphOwned_.get() || !stagedOwner_) return false; + auto old = std::move (graphOwned_); + graphOwned_ = std::move (stagedOwner_); + for (int i = 0; i < old->count; ++i) + if (old->slots[i].processor) old->slots[i].processor->releaseResources(); + old.reset(); // Third-party destruction exclusively on message thread. + handoff_.completeRetirement(); + completedSwaps_.fetch_add (1, std::memory_order_relaxed); + return true; + } + + juce::AudioPluginInstance* pluginAt (int index) noexcept + { + return index >= 0 && index < graphOwned_->count ? graphOwned_->slots[index].processor.get() : nullptr; + } + + juce::var chainState() const + { + juce::Array nodes; + for (int i = 0; i < graphOwned_->count; ++i) + { + auto node = std::make_unique(); + node->setProperty ("index", i); + node->setProperty ("name", graphOwned_->slots[i].name); + node->setProperty ("id", graphOwned_->slots[i].catalogId); + node->setProperty ("bypass", graphOwned_->slots[i].bypass); + node->setProperty ("latency", graphOwned_->slots[i].latency); + nodes.add (juce::var (node.release())); + } + return juce::var (nodes); + } + + juce::String addVst3 (const juce::String& filename, int uid, + const juce::String& catalogId) + { + if (handoff_.busy()) return "FX graph transition in progress; retry shortly"; + if (graphOwned_->count >= maxFx) return "FX Rack is full (maximum 8 VST3 effects)"; + auto* device = deviceManager_.getCurrentAudioDevice(); + if (device == nullptr) return "Configure a working audio input/output device first"; + auto* fmt = formats_.getFormat (0); + if (fmt == nullptr || ! fmt->fileMightContainThisPluginType (filename)) + return "VST3 module not found: " + filename; + + juce::OwnedArray descs; + fmt->findAllTypesForFile (descs, filename); + juce::PluginDescription* chosen = nullptr; + for (auto* d : descs) + if (d != nullptr && d->uniqueId == uid && !d->isInstrument) + { + chosen = d; + break; + } + if (chosen == nullptr) + return "Effect not found inside VST3 module. Rescan the catalog."; + + juce::String error; + auto instance = formats_.createPluginInstance ( + *chosen, device->getCurrentSampleRate(), + juce::jmax (32, device->getCurrentBufferSizeSamples()), error); + if (! instance) + return "Failed to instantiate VST3: " + error; + + const auto busError = armix::vst::prepareStereoEffectLayout (*instance); + if (busError.isNotEmpty()) + return chosen->name + ": " + busError; + + detach(); + Slot node; + node.name = chosen->name; + node.catalogId = catalogId; + node.path = filename; + node.uid = uid; + node.processor = std::move (instance); + graphOwned_->slots[graphOwned_->count] = std::move (node); + graphOwned_->bypassFlags[graphOwned_->count].store (false, std::memory_order_release); + ++graphOwned_->count; + attach(); + return {}; + } + + // Capture VST3 vendor binary state, not the legacy WebView2 mock settings. + // Must only run when output is muted (caller enforces): callback is detached + // exactly once, no plugin state methods ever execute on the audio thread. + juce::String captureSnapshot (armix::storage::Snapshot& snapshot) + { + if (!isOutputMuted()) return "Mute hardware output before saving a native preset"; + if (handoff_.busy()) return "Finish pending FX graph transition before saving"; + snapshot.effects.clear(); + snapshot.channelDb = juce::Decibels::gainToDecibels ( + channelGain_.load (std::memory_order_relaxed), -60.f); + snapshot.masterDb = juce::Decibels::gainToDecibels ( + masterGain_.load (std::memory_order_relaxed), -60.f); + snapshot.pan = channelPan_.load (std::memory_order_relaxed); + snapshot.channelMute = channelMute_.load (std::memory_order_relaxed); + snapshot.masterMute = masterMute_.load (std::memory_order_relaxed); + detach(); + juce::String error; + try + { + for (int i = 0; i < graphOwned_->count; ++i) + { + const auto& slot = graphOwned_->slots[i]; + if (!slot.processor) { error = "Invalid active FX slot"; break; } + armix::storage::FxState state; + state.path = slot.path; + state.name = slot.name; + state.catalogId = slot.catalogId; + state.uid = slot.uid; + state.bypass = graphOwned_->bypassFlags[i].load (std::memory_order_acquire); + slot.processor->getStateInformation (state.binary); + if (state.binary.getSize() > armix::storage::NativePresetArchive::maxStateBytes) + { + error = "Plugin state exceeds 8 MB: " + slot.name; + break; + } + snapshot.effects.push_back (std::move (state)); + } + } + catch (...) + { + error = "Plugin threw while saving its state"; + } + attach(); + if (error.isNotEmpty()) snapshot.effects.clear(); + return error; + } + + // Stage all VST3 binary states before publication; callback never owns + // or destroys a plugin. No manual output mute is required for recall. + juce::String restoreSnapshot (const armix::storage::Snapshot& snapshot) + { + if (handoff_.busy()) + return "A live FX graph transition is already in progress"; + if (snapshot.effects.size() > maxFx) return "Too many plugins in preset"; + auto* device = deviceManager_.getCurrentAudioDevice(); + if (!device) return "No active audio device"; + auto* fmt = formats_.getFormat (0); + if (!fmt) return "No VST3 format available"; + const auto rate = device->getCurrentSampleRate(); + const auto buffer = juce::jmax (32, device->getCurrentBufferSizeSamples()); + const auto deviceEpoch = deviceStartCount_.load (std::memory_order_acquire); + + std::array stagedSlots; + for (int i = 0; i < static_cast (snapshot.effects.size()); ++i) + { + const auto& fx = snapshot.effects[static_cast (i)]; + if (fx.binary.getSize() > armix::storage::NativePresetArchive::maxStateBytes || + !juce::File (fx.path).exists() || !fx.path.endsWithIgnoreCase (".vst3")) + return "Plugin is missing or invalid: " + fx.name; + juce::OwnedArray descriptions; + fmt->findAllTypesForFile (descriptions, fx.path); + juce::PluginDescription* match = nullptr; + for (auto* candidate : descriptions) + if (candidate != nullptr && candidate->uniqueId == fx.uid && + !candidate->isInstrument) + { match = candidate; break; } + if (!match) return "VST3 plugin identity missing: " + fx.name; + + juce::String error; + auto processor = formats_.createPluginInstance (*match, rate, buffer, error); + if (!processor) return "Cannot open preset plugin " + fx.name + ": " + error; + const auto busError = armix::vst::prepareStereoEffectLayout (*processor); + if (busError.isNotEmpty()) + return "Unsupported VST3 bus layout for " + fx.name + ": " + busError; + try + { + // State is restored before insertion; live audio still uses the + // old plan until every new instance has finished construction. + processor->prepareToPlay (rate, buffer); + if (fx.binary.getSize() > 0) + processor->setStateInformation ( + fx.binary.getData(), static_cast (fx.binary.getSize())); + } + catch (...) + { + return "Plugin failed to restore its binary state: " + fx.name; + } + Slot slot; + slot.name = match->name; + slot.catalogId = fx.catalogId; + slot.path = fx.path; + slot.uid = fx.uid; + slot.bypass = fx.bypass; + slot.processor = std::move (processor); + stagedSlots[static_cast (i)] = std::move (slot); + } + + // Reject a graph prepared against stale rate/buffer. + if (deviceEpoch != deviceStartCount_.load (std::memory_order_acquire) || + device != deviceManager_.getCurrentAudioDevice() || + rate != device->getCurrentSampleRate() || + buffer != juce::jmax (32, device->getCurrentBufferSizeSamples())) + return "Audio device changed during preset preparation. Retry recall."; + + // Ownership stays with the control thread. The audio thread switches + // only an immutable pointer at a callback boundary (never detach). + auto staged = std::make_unique(); + staged->slots = std::move (stagedSlots); + staged->count = static_cast (snapshot.effects.size()); + staged->hasRecallState = true; + staged->channelDb = snapshot.channelDb; + staged->masterDb = snapshot.masterDb; + staged->channelLinear = juce::Decibels::decibelsToGain (snapshot.channelDb); + staged->masterLinear = juce::Decibels::decibelsToGain (snapshot.masterDb); + staged->pan = snapshot.pan; + staged->channelMute = snapshot.channelMute; + staged->masterMute = snapshot.masterMute; + for (int i = 0; i < staged->count; ++i) + { + staged->bypassFlags[i].store (staged->slots[i].bypass, std::memory_order_relaxed); + staged->slots[i].latency = staged->slots[i].processor->getLatencySamples(); + if (!staged->slots[i].bypass) staged->latency += staged->slots[i].latency; + } + stagedOwner_ = std::move (staged); + if (!handoff_.stage (stagedOwner_.get())) + { + stagedOwner_.reset(); + return "Cannot schedule live FX graph swap"; + } + return {}; + } + + bool setBypass (int index, bool value) + { + if (handoff_.busy()) return false; + if (index < 0 || index >= graphOwned_->count) return false; + // Message-thread metadata and an atomic value consumed by the audio thread. + graphOwned_->slots[index].bypass = value; + graphOwned_->bypassFlags[index].store (value, std::memory_order_release); + return true; + } + + bool removeAt (int index) + { + if (handoff_.busy()) return false; + if (index < 0 || index >= graphOwned_->count) return false; + detach(); + if (graphOwned_->slots[index].processor) + graphOwned_->slots[index].processor->releaseResources(); + for (int i = index; i + 1 < graphOwned_->count; ++i) + graphOwned_->slots[i] = std::move (graphOwned_->slots[i + 1]); + graphOwned_->slots[--graphOwned_->count] = Slot {}; + for (int i = 0; i < graphOwned_->count; ++i) + graphOwned_->bypassFlags[i].store (graphOwned_->slots[i].bypass, std::memory_order_release); + attach(); + return true; + } + + bool moveSlot (int from, int to) + { + if (handoff_.busy()) return false; + if (from < 0 || from >= graphOwned_->count || to < 0 || to >= graphOwned_->count || from == to) + return false; + detach(); + auto moved = std::move (graphOwned_->slots[from]); + if (from < to) + for (int i = from; i < to; ++i) graphOwned_->slots[i] = std::move (graphOwned_->slots[i + 1]); + else + for (int i = from; i > to; --i) graphOwned_->slots[i] = std::move (graphOwned_->slots[i - 1]); + graphOwned_->slots[to] = std::move (moved); + for (int i = 0; i < graphOwned_->count; ++i) + graphOwned_->bypassFlags[i].store (graphOwned_->slots[i].bypass, std::memory_order_release); + attach(); + return true; + } + + juce::var status() + { + auto o = std::make_unique(); + auto* d = deviceManager_.getCurrentAudioDevice(); + o->setProperty ("connected", d != nullptr); + o->setProperty ("driver", deviceManager_.getCurrentAudioDeviceType()); + o->setProperty ("device", d ? d->getName() : "No device"); + o->setProperty ("rate", d ? d->getCurrentSampleRate() : 0.0); + o->setProperty ("buffer", d ? d->getCurrentBufferSizeSamples() : 0); + o->setProperty ("monitor", monitor_.load()); + o->setProperty ("masterMute", masterMute_.load()); + o->setProperty ("channelMute", channelMute_.load()); + o->setProperty ("channelPan", channelPan_.load()); + o->setProperty ("dryTest", dryTest_.load()); + juce::AudioDeviceManager::AudioDeviceSetup setup; + deviceManager_.getAudioDeviceSetup (setup); + o->setProperty ("inputDevice", setup.inputDeviceName); + o->setProperty ("outputDevice", setup.outputDeviceName); + o->setProperty ("deviceInputChannels", d ? d->getActiveInputChannels().countNumberOfSetBits() : 0); + o->setProperty ("deviceOutputChannels", d ? d->getActiveOutputChannels().countNumberOfSetBits() : 0); + o->setProperty ("callbackInputChannels", callbackInputs_.load()); + o->setProperty ("callbackOutputChannels", callbackOutputs_.load()); + o->setProperty ("callbackCount", static_cast (callbackCount_.load())); + o->setProperty ("callbackDurationUs", static_cast (lastCallbackUs_.load())); + o->setProperty ("worstCallbackUs", static_cast (worstCallbackUs_.load())); + o->setProperty ("slowCallbackCount", static_cast (slowCallbacks_.load())); + o->setProperty ("overBudgetCount", static_cast (overBudgetCallbacks_.load())); + o->setProperty ("callbackGapCount", static_cast (callbackGaps_.load())); + o->setProperty ("worstCallbackGapUs", static_cast (worstCallbackGapUs_.load())); + o->setProperty ("worstPluginUs", static_cast (worstPluginUs_.load())); + o->setProperty ("deviceStartCount", static_cast (deviceStartCount_.load())); + o->setProperty ("deviceStopCount", static_cast (deviceStopCount_.load())); + juce::Array pluginTimings; + for (int i = 0; i < graphOwned_->count; ++i) + { + auto item = std::make_unique(); + item->setProperty ("slot", i + 1); + item->setProperty ("name", graphOwned_->slots[i].name); + item->setProperty ("lastUs", static_cast (lastPluginUsBySlot_[i].load())); + item->setProperty ("worstUs", static_cast (worstPluginUsBySlot_[i].load())); + pluginTimings.add (juce::var (item.release())); + } + o->setProperty ("pluginTimings", juce::var (pluginTimings)); + o->setProperty ("slowPluginCount", static_cast (slowPlugins_.load())); + o->setProperty ("periodUs", d && d->getCurrentSampleRate() > 0 + ? 1000000.0 * d->getCurrentBufferSizeSamples() / d->getCurrentSampleRate() : 0.0); + o->setProperty ("performanceNote", "Over-budget and callback-gap counts are timing indicators, not driver-confirmed xruns."); + o->setProperty ("inputPeak", inputPeak_.load()); + o->setProperty ("postFxPeak", postFxPeak_.load()); + o->setProperty ("peak", outputPeak_.load()); + o->setProperty ("peakLeft", outputPeakL_.load()); + o->setProperty ("peakRight", outputPeakR_.load()); + o->setProperty ("latencySamples", totalLatency_.load()); + o->setProperty ("chainCount", graphOwned_->count); + o->setProperty ("graphSwitchPending", handoff_.busy()); + o->setProperty ("completedGraphSwaps", static_cast (completedSwaps_.load())); + return juce::var (o.release()); + } + +private: + static constexpr int maxFrames = 8192; + juce::AudioDeviceManager deviceManager_; + juce::AudioPluginFormatManager formats_; + std::unique_ptr graphOwned_ {std::make_unique()}; + std::unique_ptr stagedOwner_; + armix::rt::LiveGraphHandoff handoff_; + bool attached_ = false; + juce::AudioBuffer scratch_; + // Indexed atomic bypass flags: instant RT-safe toggles, no graph detachment. + std::atomic monitor_ { false }, channelMute_ { false }, masterMute_ { false }, dryTest_ { false }; + std::atomic masterGain_ { 1.f }, channelGain_ { 1.f }, channelPan_ { 0.f }; + std::atomic inputPeak_ { 0.f }, postFxPeak_ { 0.f }, outputPeak_ { 0.f }; + std::atomic outputPeakL_ { 0.f }, outputPeakR_ { 0.f }; + std::atomic callbackInputs_ { 0 }, callbackOutputs_ { 0 }; + std::atomic callbackCount_ { 0 }; + // Audio-thread-only timestamp and cheap atomically published counters. + // No log writes, allocations, locks or WebView interactions in callback. + std::atomic lastCallbackUs_ {0}, worstCallbackUs_ {0}; + std::atomic slowCallbacks_ {0}, overBudgetCallbacks_ {0}; + std::atomic callbackGaps_ {0}, worstCallbackGapUs_ {0}; + std::atomic worstPluginUs_ {0}, slowPlugins_ {0}; + std::atomic deviceStartCount_ {0}, deviceStopCount_ {0}; + std::array, maxFx> lastPluginUsBySlot_ {}; + std::array, maxFx> worstPluginUsBySlot_ {}; + std::uint64_t previousCallbackStartUs_ = 0; + double sampleRateHz_ = 48000.0; + + static std::uint64_t clockMicros() noexcept + { + return static_cast ( + std::chrono::duration_cast ( + std::chrono::steady_clock::now().time_since_epoch()).count()); + } + + static void publishMax (std::atomic& dst, std::uint64_t value) noexcept + { + auto old = dst.load (std::memory_order_relaxed); + while (old < value && !dst.compare_exchange_weak ( + old, value, std::memory_order_relaxed)) {} + } + std::atomic totalLatency_ { 0 }; + std::atomic completedSwaps_ {0}; + + void detach() + { + if (attached_) + { + deviceManager_.removeAudioCallback (this); + attached_ = false; + } + } + void attach() + { + if (! attached_ && deviceManager_.getCurrentAudioDevice() != nullptr) + { + deviceManager_.addAudioCallback (this); + attached_ = true; + } + } + + void audioDeviceAboutToStart (juce::AudioIODevice* d) override + { + deviceStartCount_.fetch_add (1, std::memory_order_relaxed); + sampleRateHz_ = juce::jmax (1.0, d->getCurrentSampleRate()); + for (int i = 0; i < maxFx; ++i) + { + lastPluginUsBySlot_[i].store (0, std::memory_order_relaxed); + worstPluginUsBySlot_[i].store (0, std::memory_order_relaxed); + } + previousCallbackStartUs_ = 0; + int latency = 0; + for (int i = 0; i < graphOwned_->count; ++i) + { + auto& slot = graphOwned_->slots[i]; + if (slot.processor) + { + slot.processor->releaseResources(); + slot.processor->prepareToPlay (d->getCurrentSampleRate(), + juce::jmax (32, d->getCurrentBufferSizeSamples())); + slot.latency = slot.processor->getLatencySamples(); + if (!graphOwned_->bypassFlags[i].load (std::memory_order_relaxed)) latency += slot.latency; + } + } + totalLatency_.store (latency); + inputPeak_.store (0.f); + postFxPeak_.store (0.f); + outputPeak_.store (0.f); + } + + void audioDeviceStopped() override + { + deviceStopCount_.fetch_add (1, std::memory_order_relaxed); + inputPeak_.store (0.f); + outputPeak_.store (0.f); + } + + void audioDeviceIOCallbackWithContext ( + const float* const* inputs, int inputChannels, float* const* outputs, + int outputChannels, int samples, const juce::AudioIODeviceCallbackContext&) override + { + const auto cycle = handoff_.beginCycle(); + const std::uint64_t beginUs = clockMicros(); + const double periodUs = 1000000.0 * static_cast (samples) / sampleRateHz_; + // Scheduling gaps only suggest instability: pause/suspend and WASAPI + // callback scheduling can create false positives. Never label xruns. + if (previousCallbackStartUs_ != 0 && periodUs > 0) + { + const auto gap = beginUs - previousCallbackStartUs_; + publishMax (worstCallbackGapUs_, gap); + if (static_cast (gap) > periodUs * 2.3) + callbackGaps_.fetch_add (1, std::memory_order_relaxed); + } + previousCallbackStartUs_ = beginUs; + callbackInputs_.store (inputChannels, std::memory_order_relaxed); + callbackOutputs_.store (outputChannels, std::memory_order_relaxed); + callbackCount_.fetch_add (1, std::memory_order_relaxed); + const bool enabled = monitor_.load (std::memory_order_relaxed); + const bool dry = dryTest_.load (std::memory_order_relaxed); + const bool muted = channelMute_.load (std::memory_order_relaxed) + || masterMute_.load (std::memory_order_relaxed); + const float gain = masterGain_.load (std::memory_order_relaxed) + * channelGain_.load (std::memory_order_relaxed); + const float pan = channelPan_.load (std::memory_order_relaxed); + // Precomputed stereo pan matrix; no trigonometry, locks or allocations + // in the realtime sample loop. 0 = transparent identity matrix. + const auto matrix = armix::dsp::StereoPanMatrix::fromNormalized (pan); + const float rampStep = samples > 1 ? 1.f / static_cast (samples - 1) : 0.f; + float inPeak = 0.f, postFxPeak = 0.f, outPeak = 0.f; + float outPeakL = 0.f, outPeakR = 0.f; + for (int offset = 0; offset < samples; offset += maxFrames) + { + const int frames = juce::jmin (maxFrames, samples - offset); + scratch_.setSize (2, frames, false, false, true); + for (int c = 0; c < 2; ++c) + { + float* dst = scratch_.getWritePointer (c); + const float* src = inputChannels > c ? inputs[c] + : inputChannels > 0 ? inputs[0] : nullptr; + if (src) + juce::FloatVectorOperations::copy (dst, src + offset, frames); + else + juce::FloatVectorOperations::clear (dst, frames); + for (int i = 0; i < frames; ++i) + inPeak = juce::jmax (inPeak, std::abs (dst[i])); + } + // MIDI capacity is empty unless the plugin itself changes it. + juce::MidiBuffer midi; + if (!dry) + { + for (int fx = 0; fx < cycle.graph->count; ++fx) + { + auto& slot = cycle.graph->slots[fx]; + if (slot.processor && ! cycle.graph->bypassFlags[fx].load (std::memory_order_relaxed)) + { + const auto pluginBeginUs = clockMicros(); + slot.processor->processBlock (scratch_, midi); + const auto pluginUs = clockMicros() - pluginBeginUs; + lastPluginUsBySlot_[fx].store (pluginUs, std::memory_order_relaxed); + publishMax (worstPluginUsBySlot_[fx], pluginUs); + publishMax (worstPluginUs_, pluginUs); + if (static_cast (pluginUs) > periodUs * 0.75) + slowPlugins_.fetch_add (1, std::memory_order_relaxed); + } + midi.clear(); + } + } + for (int ch = 0; ch < 2; ++ch) + { + const float* processed = scratch_.getReadPointer (ch); + for (int i = 0; i < frames; ++i) + postFxPeak = juce::jmax (postFxPeak, std::abs (processed[i])); + } + for (int c = 0; c < outputChannels; ++c) + { + if (!outputs[c]) continue; + const float* left = scratch_.getReadPointer (0); + const float* right = scratch_.getReadPointer (1); + float* dst = outputs[c] + offset; + float channelPeak = 0.f; + for (int i = 0; i < frames; ++i) + { + const float mapped = c == 0 ? matrix.ll * left[i] + matrix.lr * right[i] + : matrix.rl * left[i] + matrix.rr * right[i]; + const auto phase = (offset + i) * rampStep; + const float ramp = cycle.fadeOut ? 1.f - phase + : cycle.fadeIn ? phase : 1.f; + const float value = (enabled && !muted) ? mapped * gain * ramp : 0.f; + dst[i] = value; + channelPeak = juce::jmax (channelPeak, std::abs (value)); + } + outPeak = juce::jmax (outPeak, channelPeak); + if (c == 0) outPeakL = juce::jmax (outPeakL, channelPeak); + if (c == 1) outPeakR = juce::jmax (outPeakR, channelPeak); + } + } + inputPeak_.store (juce::jmin (1.f, inPeak), std::memory_order_relaxed); + postFxPeak_.store (juce::jmin (1.f, postFxPeak), std::memory_order_relaxed); + outputPeak_.store (juce::jmin (1.f, outPeak), std::memory_order_relaxed); + outputPeakL_.store (juce::jmin (1.f, outPeakL), std::memory_order_relaxed); + outputPeakR_.store (juce::jmin (1.f, outPeakR), std::memory_order_relaxed); + if (cycle.fadeOut) + { + // Ownership remains with stagedOwner_ until message thread ack. + handoff_.endCycle (cycle); + const auto* switched = handoff_.current(); + if (switched && switched->hasRecallState) + { + channelGain_.store (switched->channelLinear, std::memory_order_relaxed); + masterGain_.store (switched->masterLinear, std::memory_order_relaxed); + setChannelPan (switched->pan); + setChannelMuted (switched->channelMute); + setMasterMuted (switched->masterMute); + totalLatency_.store (switched->latency, std::memory_order_relaxed); + } + } + const auto elapsedUs = clockMicros() - beginUs; + lastCallbackUs_.store (elapsedUs, std::memory_order_relaxed); + publishMax (worstCallbackUs_, elapsedUs); + if (static_cast (elapsedUs) > periodUs * 0.80) + slowCallbacks_.fetch_add (1, std::memory_order_relaxed); + if (static_cast (elapsedUs) > periodUs) + overBudgetCallbacks_.fetch_add (1, std::memory_order_relaxed); + } +}; diff --git a/src/LiveGraphHandoff.h b/src/LiveGraphHandoff.h new file mode 100644 index 000000000..e1f6f654a --- /dev/null +++ b/src/LiveGraphHandoff.h @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include + +// P2.5.1 SPSC RT graph handoff. Message thread OWNS all graphs and retires +// only after the audio callback acknowledges a buffer-boundary transition. +// The callback never copies ownership, frees memory, locks, or waits. +namespace armix::rt +{ +template +class LiveGraphHandoff final +{ +public: + struct Cycle { Graph* graph=nullptr; bool fadeOut=false; bool fadeIn=false; }; + void initialize (Graph* graph) noexcept + { + active_.store (graph, std::memory_order_release); + pending_.store (nullptr, std::memory_order_release); + retired_.store (nullptr, std::memory_order_release); + phase_.store (0, std::memory_order_release); + fadeInNext_ = false; + } + bool stage (Graph* candidate) noexcept + { + if (!candidate) return false; + int idle = 0; + if (!phase_.compare_exchange_strong (idle, 1, std::memory_order_acq_rel)) + return false; + pending_.store (candidate, std::memory_order_release); + return true; + } + bool busy() const noexcept + { + return phase_.load (std::memory_order_acquire) != 0; + } + Cycle beginCycle() noexcept + { + Cycle cycle; + cycle.graph = active_.load (std::memory_order_acquire); + cycle.fadeOut = pending_.load (std::memory_order_acquire) != nullptr; + cycle.fadeIn = fadeInNext_; + fadeInNext_ = false; + return cycle; + } + void endCycle (const Cycle& cycle) noexcept + { + if (!cycle.fadeOut) return; + // Control thread never cancels a published graph before acknowledgement. + auto* newGraph = pending_.exchange (nullptr, std::memory_order_acq_rel); + if (!newGraph) return; + active_.store (newGraph, std::memory_order_release); + phase_.store (2, std::memory_order_release); + retired_.store (cycle.graph, std::memory_order_release); + fadeInNext_ = true; + } + Graph* takeRetired() noexcept + { + return retired_.exchange (nullptr, std::memory_order_acq_rel); + } + // Called AFTER the message thread safely releases the retired graph. + void completeRetirement() noexcept + { + phase_.store (0, std::memory_order_release); + } + Graph* current() const noexcept { return active_.load (std::memory_order_acquire); } + // Caller must already have synchronously stopped/detached audio callbacks. + void resetAfterStop (Graph* graph) noexcept { initialize (graph); } +private: + std::atomic active_ {nullptr}; + std::atomic pending_ {nullptr}; + std::atomic retired_ {nullptr}; + // 0=idle, 1=queued, 2=acknowledged; closes the pending/ack gap. + std::atomic phase_ {0}; + bool fadeInNext_ = false; // audio thread exclusive +}; + +inline float linearBufferRamp (int sample, int total, bool fadeOut, bool fadeIn) noexcept +{ + if (total <= 1) return fadeOut ? 0.f : 1.f; + const auto unit = static_cast (sample) / static_cast (total-1); + if (fadeOut) return 1.f-unit; + if (fadeIn) return unit; + return 1.f; +} +} // namespace armix::rt diff --git a/src/Main.cpp b/src/Main.cpp index 22666e162..c2830f83e 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1,85 +1,547 @@ // SPDX-License-Identifier: AGPL-3.0-only -// AR MIX Studio UI integration prototype. No sound processing is implemented. +// Native VST3 FX catalog, plugin rack and audio-device bridge. +// Audio runs exclusively in JUCE AudioIODeviceCallback; WebView is control only. #include -#include +#include #include +#include "LiveAudioEngine.h" +#include "DiagnosticsRecorder.h" +#include "PluginCatalog.h" #include +#include +#include namespace { -std::optional assetFor(const juce::String& path) +juce::File settingsDirectory() +{ + return juce::File::getSpecialLocation ( + juce::File::userApplicationDataDirectory).getChildFile ("AR-MIX-Studio"); +} + +std::optional assetFor (const juce::String& path) { - int size = 0; const char* data = nullptr; + int size = 0; juce::String mime; if (path == "/" || path == "/index.html") - { - data = BinaryData::index_html; size = BinaryData::index_htmlSize; mime = "text/html"; - } + { data = BinaryData::index_html; size = BinaryData::index_htmlSize; mime = "text/html"; } else if (path == "/styles.css") - { - data = BinaryData::styles_css; size = BinaryData::styles_cssSize; mime = "text/css"; - } + { data = BinaryData::styles_css; size = BinaryData::styles_cssSize; mime = "text/css"; } else if (path == "/app.js") - { - data = BinaryData::app_js; size = BinaryData::app_jsSize; mime = "text/javascript"; - } + { data = BinaryData::app_js; size = BinaryData::app_jsSize; mime = "text/javascript"; } + else if (path == "/bridge.js") + { data = BinaryData::bridge_js; size = BinaryData::bridge_jsSize; mime = "text/javascript"; } + else if (path == "/monitor.js") + { data = BinaryData::monitor_js; size = BinaryData::monitor_jsSize; mime = "text/javascript"; } else return std::nullopt; - juce::WebBrowserComponent::Resource result; - result.data.resize(static_cast(size)); - std::memcpy(result.data.data(), data, static_cast(size)); - result.mimeType = mime; - return result; + juce::WebBrowserComponent::Resource resource; + resource.data.resize (static_cast (size)); + std::memcpy (resource.data.data(), data, static_cast (size)); + resource.mimeType = mime; + return resource; } -class ConsoleWindow final : public juce::DocumentWindow +class Browser final : public juce::WebBrowserComponent +{ +public: + explicit Browser (Options options) : WebBrowserComponent (std::move (options)) {} + bool loaded = false; + void pageFinishedLoading (const juce::String&) override { loaded = true; } +}; + +class PluginEditorWindow final : public juce::DocumentWindow +{ +public: + PluginEditorWindow (const juce::String& title, juce::AudioProcessorEditor* editor) + : DocumentWindow (title, juce::Colour (0xff14212a), allButtons) + { + setUsingNativeTitleBar (true); + setContentOwned (editor, true); + setResizable (true, true); + centreWithSize (juce::jmax (380, editor->getWidth()), juce::jmax (300, editor->getHeight())); + setVisible (true); + } + void closeButtonPressed() override { setVisible (false); } +}; + +class AudioSetupWindow final : public juce::DocumentWindow +{ +public: + explicit AudioSetupWindow (juce::AudioDeviceManager& manager) + : juce::DocumentWindow ("AR MIX — ASIO / WASAPI Setup", + juce::Colour (0xff14212a), allButtons) + { + setUsingNativeTitleBar (true); + setResizable (true, true); + setResizeLimits (580, 430, 1300, 1000); + auto* selector = new juce::AudioDeviceSelectorComponent ( + manager, 1, 2, 1, 2, false, false, false, false); + setContentOwned (selector, true); + centreWithSize (740, 590); + } + void closeButtonPressed() override { setVisible (false); } +}; + +class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, private juce::ChangeListener { public: ConsoleWindow() - : juce::DocumentWindow("AR MIX Studio — FX Host UI prototype", - juce::Colour(0xff101921), - juce::DocumentWindow::allButtons), - browser(juce::WebBrowserComponent::Options{} - .withBackend(juce::WebBrowserComponent::Options::Backend::webview2) - .withWinWebView2Options( - juce::WebBrowserComponent::Options::WinWebView2{} - .withUserDataFolder(juce::File::getSpecialLocation( - juce::File::userApplicationDataDirectory) - .getChildFile("AR-MIX-Studio-WebView2"))) - .withNativeIntegrationEnabled() - .withEventListener("arMixParameter", [](juce::var args) - { - // This is the JUCE message thread, NOT the audio callback. - // Forward validated state changes through a lock-free queue - // when a real audio engine is added. - DBG("AR MIX UI event: " + juce::JSON::toString(args)); - }) - .withResourceProvider(assetFor)) - { - setUsingNativeTitleBar(true); - setResizable(true, true); - setResizeLimits(1100, 650, 3840, 2160); - setContentNonOwned(&browser, false); - centreWithSize(1650, 930); - setVisible(true); - browser.goToURL(juce::WebBrowserComponent::getResourceProviderRoot()); + : DocumentWindow ("AR MIX Studio — Native VST3 FX Host", + juce::Colour (0xff101921), allButtons), + catalog_ (settingsDirectory()), + diagnostics_ (settingsDirectory().getChildFile ("diagnostics")), + presets_ (settingsDirectory().getChildFile ("presets")), + browser_ (juce::WebBrowserComponent::Options{} + .withBackend (juce::WebBrowserComponent::Options::Backend::webview2) + .withWinWebView2Options ( + juce::WebBrowserComponent::Options::WinWebView2{} + .withUserDataFolder ( + juce::File::getSpecialLocation ( + juce::File::userApplicationDataDirectory) + .getChildFile ("AR-MIX-Studio-WebView2"))) + .withNativeIntegrationEnabled() + .withEventListener ("arMixParameter", [this] (juce::var args) { onParameter (args); }) + .withEventListener ("arMixAction", [this] (juce::var args) { onAction (args); }) + .withResourceProvider (assetFor)) + { + settingsDirectory().createDirectory(); + catalog_.onChanged = [this] { emitCatalog(); emitScanProgress(); }; + setUsingNativeTitleBar (true); + setResizable (true, true); + setResizeLimits (1100, 650, 3840, 2160); + setContentNonOwned (&browser_, false); + centreWithSize (1650, 930); + setVisible (true); + + auto saved = juce::XmlDocument::parse (settingsDirectory().getChildFile ("audio-devices.xml")); + startupError_ = engine_.start (saved.get()); + engine_.devices().addChangeListener (this); + diagnostics_.record ("STARTUP", startupError_.isEmpty() ? "Audio device initialized" : startupError_); + browser_.goToURL (juce::WebBrowserComponent::getResourceProviderRoot()); + startTimerHz (12); + // Defer initial scan until explicitly requested in Plugin Manager. + // Startup must not spend seconds enumerating third-party VST3 modules. + } + + ~ConsoleWindow() override + { + stopTimer(); + catalog_.onChanged = nullptr; + editorWindow_.reset(); + audioSetupWindow_.reset(); + engine_.devices().removeChangeListener (this); + engine_.stop(); + browser_.setVisible (false); } + void closeButtonPressed() override { juce::JUCEApplication::getInstance()->systemRequestedQuit(); } + private: - juce::WebBrowserComponent browser; - JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ConsoleWindow) + LiveAudioEngine engine_; + PluginCatalog catalog_; + DiagnosticsRecorder diagnostics_; + armix::storage::NativePresetArchive presets_; + Browser browser_; + std::unique_ptr chooser_; + std::unique_ptr editorWindow_; + std::unique_ptr audioSetupWindow_; + juce::String startupError_, lastAudioXml_; + bool initialStateSent_ = false; + bool setupLaunching_ = false; + unsigned int timerTicks_ = 0; + bool deviceSettingsDirty_ = false; + juce::var pendingPresetUI_; + juce::String pendingPresetName_; + + void emitNotice (const juce::String& message, bool error = false) + { + auto o = std::make_unique(); + o->setProperty ("text", message); + o->setProperty ("error", error); + if (browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixNotice", juce::var (o.release())); + } + + void emitCatalog() + { + if (browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixCatalog", catalog_.snapshot()); + } + + // Every plugin insert request gets a structured result. A toast behind + // a modal is not an actionable failure report for live performers. + void emitFxAddResult (int requestId, const juce::String& name, + const juce::String& error, unsigned int elapsedMs) + { + auto response = std::make_unique(); + response->setProperty ("requestId", requestId); + response->setProperty ("name", name); + response->setProperty ("ok", error.isEmpty()); + response->setProperty ("error", error); + response->setProperty ("elapsedMs", static_cast (elapsedMs)); + response->setProperty ("chainSize", engine_.chainSize()); + if (browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixAddResult", juce::var (response.release())); + } + + void emitPresets() + { + if (browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixPresets", presets_.list()); + } + + void emitChain() + { + if (browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixChain", engine_.chainState()); + } + + void onParameter (const juce::var& args) + { + const auto name = args.getProperty ("parameter", {}).toString(); + const int channel = static_cast (args.getProperty ("channel", -2)); + const auto value = args.getProperty ("value", {}); + const auto valueNumber = static_cast (static_cast (value)); + if (name == "masterGain" && (value.isDouble() || value.isInt())) + engine_.setMasterGainDb (valueNumber); + // The app.js bridge converts strip index 0 to channel ID 1. + else if (name == "faderDb" && channel == 1 && (value.isDouble() || value.isInt())) + engine_.setChannelGainDb (valueNumber); + else if (name == "pan" && channel == 1 && (value.isDouble() || value.isInt())) + engine_.setChannelPan (valueNumber * 0.01f); + else if (name == "mute" && channel == 1 && value.isBool()) + engine_.setChannelMuted (bool (value)); + else if (name == "masterMute" && value.isBool()) + engine_.setMasterMuted (bool (value)); + } + + void emitSetupPhase (const juce::String& phase, int elapsedMs = 0) + { + auto o = std::make_unique(); + o->setProperty ("phase", phase); + o->setProperty ("elapsedMs", elapsedMs); + if (browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixSetupProgress", juce::var (o.release())); + } + + void emitScanProgress() + { + if (browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixScanProgress", catalog_.progress()); + } + + void showDeviceSetup() + { + diagnostics_.record ("SETUP", "Open audio device setup"); + if (setupLaunching_) return; + + // The native JUCE device list is cached after first construction: + // reopening the settings window avoids repeating full widget setup. + if (audioSetupWindow_ != nullptr) + { + audioSetupWindow_->setVisible (true); + audioSetupWindow_->toFront (true); + emitSetupPhase ("opened", 0); + return; + } + + setupLaunching_ = true; + emitSetupPhase ("preparing"); + const auto begin = juce::Time::getMillisecondCounter(); + juce::Timer::callAfterDelay (150, + [safe = juce::Component::SafePointer (this), begin] + { + if (safe == nullptr) return; + safe->emitSetupPhase ("enumerating"); + safe->audioSetupWindow_ = + std::make_unique (safe->engine_.devices()); + safe->audioSetupWindow_->setVisible (true); + safe->audioSetupWindow_->toFront (true); + safe->setupLaunching_ = false; + safe->emitSetupPhase ("opened", + static_cast (juce::Time::getMillisecondCounter() - begin)); + }); + } + + void chooseImport() + { + chooser_ = std::make_unique ( + "Import an individual VST3 module or bundle", juce::File{}, "*", true); + chooser_->launchAsync ( + juce::FileBrowserComponent::openMode | + juce::FileBrowserComponent::canSelectFiles | + juce::FileBrowserComponent::canSelectDirectories, + [this] (const juce::FileChooser& f) + { + const auto file = f.getResult(); + if (file == juce::File{}) return; + if (file.hasFileExtension (".dll")) + { + emitNotice ("Legacy VST2 DLL cannot be imported as VST3. Select a .vst3 module.", true); + return; + } + catalog_.importVst3 (file); + emitCatalog(); + }); + } + + void chooseFolder() + { + chooser_ = std::make_unique ( + "Add a VST3 plugin folder to your catalog", juce::File{}, "*", true); + chooser_->launchAsync ( + juce::FileBrowserComponent::openMode | + juce::FileBrowserComponent::canSelectDirectories, + [this] (const juce::FileChooser& f) + { + const auto folder = f.getResult(); + if (folder != juce::File{}) + catalog_.addDirectory (folder); + }); + } + + void onAction (const juce::var& args) + { + const auto action = args.getProperty ("action", {}).toString(); + const auto value = args.getProperty ("value", {}); + const int slot = static_cast (args.getProperty ("slot", -1)); + + if (action == "audioSetup") showDeviceSetup(); + else if (action == "presetList") + emitPresets(); + else if (action == "presetSave") + { + const auto name = armix::storage::NativePresetArchive::cleanName ( + args.getProperty ("name", {}).toString()); + if (name.isEmpty()) + return emitNotice ("Choose a valid preset name", true); + if (!engine_.isOutputMuted()) + return emitNotice ("Mute output in SIGNAL CHECK before saving a native sound preset. This avoids interrupting your live performance.", true); + editorWindow_.reset(); + armix::storage::Snapshot snapshot; + snapshot.name = name; + auto error = engine_.captureSnapshot (snapshot); + if (error.isEmpty()) error = presets_.save (snapshot); + if (error.isNotEmpty()) + { + diagnostics_.record ("PRESET_SAVE_FAIL", name + ": " + error); + emitNotice (error, true); + } + else + { + diagnostics_.record ("PRESET_SAVED", name + " (" + juce::String (snapshot.effects.size()) + " VST3)"); + emitPresets(); + emitNotice ("Native VST3 preset saved: " + name); + } + } + else if (action == "presetLoad") + { + const auto name = args.getProperty ("name", {}).toString(); + if (engine_.isGraphSwitchPending()) + return emitNotice ("FX recall is already transitioning; retry shortly.", true); + editorWindow_.reset(); + armix::storage::Snapshot snapshot; + auto error = presets_.load (name, snapshot); + if (error.isEmpty()) error = engine_.restoreSnapshot (snapshot); + if (error.isNotEmpty()) + { + diagnostics_.record ("PRESET_LOAD_FAIL", name + ": " + error); + emitNotice ("Preset unchanged: " + error, true); + } + else + { + // UI reflects state only AFTER the audio thread acknowledges + // the staged plan; avoid claiming active while it is still old. + auto updated = std::make_unique(); + updated->setProperty ("name", name); + updated->setProperty ("channelDb", snapshot.channelDb); + updated->setProperty ("masterDb", snapshot.masterDb); + updated->setProperty ("pan", snapshot.pan * 100.f); + updated->setProperty ("channelMute", snapshot.channelMute); + updated->setProperty ("masterMute", snapshot.masterMute); + pendingPresetUI_ = juce::var (updated.release()); + pendingPresetName_ = name; + diagnostics_.record ("PRESET_GRAPH_QUEUED", name + " (" + + juce::String (snapshot.effects.size()) + " VST3)"); + emitNotice ("Preparing live transition to sound: " + name); + } + } + else if (action == "openDiagnostics") + { + const auto file = diagnostics_.getLogFile(); + if (file.existsAsFile()) file.revealToUser(); + else file.getParentDirectory().revealToUser(); + } + else if (action == "scanVst3") + { + diagnostics_.record ("PLUGIN_SCAN", "Scan standard VST3 folders"); + catalog_.scanDefaults(); + } + else if (action == "addScanFolder") + { + chooseFolder(); + } + else if (action == "importVst3") + { + chooseImport(); + } + else if (action == "addCatalog") + { + const auto requestId = static_cast (args.getProperty ("requestId", 0)); + const auto requestedId = args.getProperty ("id", {}).toString(); + const auto* plugin = catalog_.find (requestedId); + const auto name = plugin != nullptr ? plugin->name : juce::String ("Unknown VST3"); + const auto started = juce::Time::getMillisecondCounter(); + juce::String error; + + if (plugin == nullptr) + error = "Plugin is no longer in the catalog. Rescan in PLUGINS and try again."; + else + { + diagnostics_.record ("FX_ADD_REQUEST", name + " | " + plugin->path); + editorWindow_.reset(); + try + { + error = engine_.addVst3 (plugin->path, plugin->uid, plugin->key()); + } + catch (const std::exception& ex) + { + error = "VST3 instantiation threw an exception: " + juce::String (ex.what()); + } + catch (...) + { + error = "VST3 instantiation failed with an unknown exception"; + } + } + const auto elapsed = juce::Time::getMillisecondCounter() - started; + emitFxAddResult (requestId, name, error, elapsed); + if (error.isNotEmpty()) + { + diagnostics_.record ("FX_LOAD_FAIL", name + " | " + error + + " | elapsedMs=" + juce::String (elapsed)); + emitNotice (name + ": " + error, true); + } + else + { + diagnostics_.record ("FX_LOAD", name + " | elapsedMs=" + juce::String (elapsed)); + emitChain(); + emitNotice (name + " inserted into Channel 1 FX Rack."); + } + } + else if (action == "fxRemove") + { + editorWindow_.reset(); + if (engine_.removeAt (slot)) { diagnostics_.record ("FX_REMOVE", juce::String (slot)); emitChain(); } + } + else if (action == "fxMove") + { + editorWindow_.reset(); + if (engine_.moveSlot (slot, slot + static_cast (value))) { diagnostics_.record ("FX_MOVE", juce::String (slot)); emitChain(); } + } + else if (action == "fxBypass") + { + if (value.isBool() && engine_.setBypass (slot, bool (value))) { diagnostics_.record ("FX_BYPASS", juce::String (slot) + (bool (value) ? " ON" : " OFF")); emitChain(); } + } + else if (action == "fxEditor") + { + editorWindow_.reset(); + if (auto* processor = engine_.pluginAt (slot)) + { + if (auto* editor = processor->createEditorIfNeeded()) + editorWindow_ = std::make_unique ( + processor->getName(), editor); + else + emitNotice ("This VST3 does not expose a graphical editor.", true); + } + } + else if (action == "monitor" && value.isBool()) + { + engine_.setMonitorEnabled (bool (value)); + diagnostics_.record ("OUTPUT_MUTE", bool (value) ? "OFF" : "ON"); + } + else if (action == "dryTest" && value.isBool()) + { + engine_.setDryTestEnabled (bool (value)); + diagnostics_.record ("DRY_TEST", bool (value) ? "ON" : "OFF"); + } + else if (action == "refreshState") + { + emitCatalog(); + emitChain(); + } + } + + void changeListenerCallback (juce::ChangeBroadcaster*) override + { + // Save device state only after a real change, not on every 3-second tick. + deviceSettingsDirty_ = true; + diagnostics_.record ("DEVICE_CHANGE", "Device manager event"); + } + + void timerCallback() override + { + ++timerTicks_; + if (engine_.finalizeGraphSwitch()) + { + diagnostics_.record ("GRAPH_SWAP_ACK", pendingPresetName_); + emitChain(); + if (pendingPresetUI_.isObject() && browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixNativePresetLoaded", pendingPresetUI_); + if (pendingPresetName_.isNotEmpty()) + emitNotice ("Live sound recalled: " + pendingPresetName_); + pendingPresetUI_ = juce::var(); + pendingPresetName_.clear(); + } + if (timerTicks_ % 12 == 0) + diagnostics_.record ("AUDIO_HEALTH", juce::JSON::toString (engine_.status(), false)); + + if (deviceSettingsDirty_) + { + deviceSettingsDirty_ = false; + if (auto xml = engine_.devices().createStateXml()) + { + const auto text = xml->toString(); + if (text != lastAudioXml_) + { + lastAudioXml_ = text; + if (!settingsDirectory().getChildFile ("audio-devices.xml").replaceWithText (text)) + diagnostics_.record ("DEVICE_SAVE_FAIL", "Unable to persist device settings"); + } + } + } + if (!browser_.loaded) return; + if (!initialStateSent_) + { + initialStateSent_ = true; + emitCatalog(); + emitScanProgress(); + emitChain(); + emitPresets(); + } + if (catalog_.busy() && timerTicks_ % 3 == 0) + emitScanProgress(); + auto state = engine_.status(); + state.getDynamicObject()->setProperty ("diagnosticsDropped", + static_cast (diagnostics_.lostRecords())); + state.getDynamicObject()->setProperty ("diagnosticsTruncated", + static_cast (diagnostics_.truncatedRecords())); + if (startupError_.isNotEmpty() && !bool (state.getProperty ("connected", false))) + state.getDynamicObject()->setProperty ("error", startupError_); + browser_.emitEventIfBrowserIsVisible ("arMixStatus", state); + } }; class ConsoleApp final : public juce::JUCEApplication { public: - const juce::String getApplicationName() override { return "AR MIX Console"; } - const juce::String getApplicationVersion() override { return "0.3.0"; } - void initialise(const juce::String&) override { window = std::make_unique(); } - void shutdown() override { window.reset(); } + const juce::String getApplicationName() override { return "ArSonMix"; } + const juce::String getApplicationVersion() override { return "0.5.0-native-catalog"; } + void initialise (const juce::String&) override { window_ = std::make_unique(); } + void shutdown() override { window_.reset(); } private: - std::unique_ptr window; + std::unique_ptr window_; }; -} // namespace -START_JUCE_APPLICATION(ConsoleApp) +} +START_JUCE_APPLICATION (ConsoleApp) diff --git a/src/NativePresetArchive.h b/src/NativePresetArchive.h new file mode 100644 index 000000000..08b007914 --- /dev/null +++ b/src/NativePresetArchive.h @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include + +// P2.4 native VST3-state container. Archive never extracts paths to disk. +// All calls are CONTROL/IO thread only, never made by AudioIODeviceCallback. +namespace armix::storage +{ +struct FxState +{ + juce::String name, path, catalogId; + int uid = 0; + bool bypass = false; + juce::MemoryBlock binary; +}; + +struct Snapshot +{ + juce::String name; + float channelDb = 0.f, pan = 0.f, masterDb = 0.f; + bool channelMute = false, masterMute = false; + std::vector effects; +}; + +class NativePresetArchive final +{ +public: + static constexpr int maxEffects = 8; + static constexpr size_t maxStateBytes = 8 * 1024 * 1024; + static constexpr juce::int64 maxArchiveBytes = 72 * 1024 * 1024; + + explicit NativePresetArchive (juce::File directory) : folder_ (std::move (directory)) + { + folder_.createDirectory(); + } + + static juce::String cleanName (juce::String input) + { + return input.trim().substring (0, 56) + .retainCharacters ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -_"); + } + + juce::File fileFor (const juce::String& name) const + { + return folder_.getChildFile (cleanName (name) + ".armix"); + } + + juce::var list() const + { + juce::Array values; + auto files = folder_.findChildFiles (juce::File::findFiles, false, "*.armix"); + for (const auto& file : files) + { + if (values.size() >= 120) break; + values.add (file.getFileNameWithoutExtension()); + } + return juce::var (values); + } + + // This ZIP is the ARD-specified portable container, not a list of GUI knob labels. + juce::String save (const Snapshot& state) + { + if (state.effects.size() > maxEffects) return "Too many effects in snapshot"; + const auto safe = cleanName (state.name); + if (safe.isEmpty()) return "Use a preset name containing letters or numbers"; + if (!folder_.isDirectory() && folder_.createDirectory().failed()) + return "Preset directory cannot be created"; + + juce::ZipFile::Builder builder; + auto manifest = std::make_unique(); + manifest->setProperty ("format", "arsonmix.native.fx-snapshot"); + manifest->setProperty ("schemaVersion", 1); + manifest->setProperty ("name", safe); + manifest->setProperty ("channelId", "ch-001"); + manifest->setProperty ("channelDb", static_cast (state.channelDb)); + manifest->setProperty ("channelPan", static_cast (state.pan)); + manifest->setProperty ("masterDb", static_cast (state.masterDb)); + manifest->setProperty ("channelMute", state.channelMute); + manifest->setProperty ("masterMute", state.masterMute); + // Hardware output endpoints are intentionally NOT saved or switched. + juce::Array items; + for (int index = 0; index < static_cast (state.effects.size()); ++index) + { + const auto& fx = state.effects[static_cast (index)]; + if (! fx.path.endsWithIgnoreCase (".vst3") || fx.path.length() > 1024 || + fx.binary.getSize() > maxStateBytes || fx.path.isEmpty()) + return "Invalid plugin path or oversized VST3 state in slot " + juce::String (index + 1); + const auto path = "state/" + juce::String (index).paddedLeft ('0', 2) + ".bin"; + auto obj = std::make_unique(); + obj->setProperty ("name", fx.name); + obj->setProperty ("path", fx.path); + obj->setProperty ("catalogId", fx.catalogId); + obj->setProperty ("uid", fx.uid); + obj->setProperty ("bypass", fx.bypass); + obj->setProperty ("statePath", path); + obj->setProperty ("stateBytes", static_cast (fx.binary.getSize())); + obj->setProperty ("sha256", juce::SHA256 (fx.binary).toHexString()); + items.add (juce::var (obj.release())); + builder.addEntry ( + std::make_unique (fx.binary.getData(), fx.binary.getSize(), true), + 0, path, juce::Time::getCurrentTime()); + } + manifest->setProperty ("pluginInstances", juce::var (items)); + const auto json = juce::JSON::toString (juce::var (manifest.release()), true); + if (json.getNumBytesAsUTF8() > 256 * 1024) return "Manifest too large"; + builder.addEntry ( + std::make_unique (json.toRawUTF8(), + static_cast (json.getNumBytesAsUTF8()), true), + 6, "manifest.json", juce::Time::getCurrentTime()); + + juce::TemporaryFile temp (fileFor (safe)); + auto stream = temp.getFile().createOutputStream(); + if (! stream) return "Unable to open temporary preset file"; + if (! builder.writeToStream (*stream, nullptr)) + return "Preset ZIP write failed; original preset untouched"; + stream->flush(); + if (stream->getStatus().failed()) + return "Failed to flush preset to disk"; + stream.reset(); + if (temp.getFile().getSize() > maxArchiveBytes) + return "Preset archive exceeds safety limit"; + if (! temp.overwriteTargetFileWithTemporary()) + return "Could not commit preset file atomically"; + return {}; + } + + juce::String load (const juce::String& requestedName, Snapshot& output) const + { + const auto safe = cleanName (requestedName); + if (safe.isEmpty() || safe != requestedName) return "Invalid preset name"; + const auto file = fileFor (safe); + if (! file.existsAsFile() || file.getSize() > maxArchiveBytes) + return "Preset file missing or above safety limit"; + juce::ZipFile zip (file); + if (zip.getNumEntries() < 1 || zip.getNumEntries() > maxEffects + 1) + return "Invalid preset archive entry count"; + const int manifestIndex = zip.getIndexOfFileName ("manifest.json"); + if (manifestIndex < 0 || !zip.getEntry (manifestIndex) || + zip.getEntry (manifestIndex)->uncompressedSize > 256 * 1024) + return "Preset manifest missing or exceeds 256 KB"; + const auto manifestStream = std::unique_ptr ( + zip.createStreamForEntry (manifestIndex)); + if (!manifestStream) return "Cannot open preset manifest"; + const auto data = manifestStream->readEntireStreamAsString(); + if (data.getNumBytesAsUTF8() > 256 * 1024) return "Manifest exceeds limit"; + const auto manifest = juce::JSON::parse (data); + if (!manifest.isObject() || + manifest.getProperty ("format", {}).toString() != "arsonmix.native.fx-snapshot" || + static_cast (manifest.getProperty ("schemaVersion", 0)) != 1 || + !manifest.getProperty ("pluginInstances", {}).isArray()) + return "Unsupported native preset format"; + auto temp = Snapshot {}; + temp.name = safe; + auto readDb = [&manifest] (const char* key, double minimum, double maximum, float& result) + { + const auto v = manifest.getProperty (key, {}); + if (!v.isDouble() && !v.isInt()) return false; + const auto number = static_cast (v); + if (!std::isfinite (number) || number < minimum || number > maximum) return false; + result = static_cast (number); + return true; + }; + if (!readDb ("channelDb", -60, 10, temp.channelDb) || + !readDb ("masterDb", -60, 10, temp.masterDb) || + !readDb ("channelPan", -1, 1, temp.pan)) + return "Unsafe mixer values in preset"; + const auto m1 = manifest.getProperty ("channelMute", {}); + const auto m2 = manifest.getProperty ("masterMute", {}); + if (!m1.isBool() || !m2.isBool()) return "Invalid mute flags"; + temp.channelMute = static_cast (m1); + temp.masterMute = static_cast (m2); + + const auto entries = manifest.getProperty ("pluginInstances", {}); + const auto* list = entries.getArray(); + if (!list || list->size() > maxEffects || zip.getNumEntries() != list->size() + 1) + return "Preset plugin count mismatch"; + + for (int i = 0; i < list->size(); ++i) + { + const auto& entry = list->getReference (i); + if (!entry.isObject()) return "Invalid preset plugin record"; + auto fx = FxState {}; + fx.name = entry.getProperty ("name", {}).toString(); + fx.path = entry.getProperty ("path", {}).toString(); + fx.catalogId = entry.getProperty ("catalogId", {}).toString(); + const auto vUid = entry.getProperty ("uid", {}); + const auto vBypass = entry.getProperty ("bypass", {}); + if (!vUid.isInt() || !vBypass.isBool() || + !fx.path.endsWithIgnoreCase (".vst3") || fx.path.length() > 1024) + return "Invalid VST3 identity"; + fx.uid = static_cast (vUid); + fx.bypass = static_cast (vBypass); + const auto statePath = "state/" + juce::String (i).paddedLeft ('0', 2) + ".bin"; + if (entry.getProperty ("statePath", {}).toString() != statePath) + return "Unexpected archive state path"; + const int zipIndex = zip.getIndexOfFileName (statePath); + const auto* zipEntry = zipIndex >= 0 ? zip.getEntry (zipIndex) : nullptr; + if (!zipEntry || zipEntry->uncompressedSize < 0 || + zipEntry->uncompressedSize > static_cast (maxStateBytes) || + static_cast (entry.getProperty ("stateBytes", -1)) != zipEntry->uncompressedSize) + return "VST3 state is missing or exceeds safety limit"; + auto input = std::unique_ptr (zip.createStreamForEntry (zipIndex)); + if (!input) return "Unable to read VST3 state"; + input->readIntoMemoryBlock (fx.binary, static_cast (maxStateBytes + 1)); + if (fx.binary.getSize() != static_cast (zipEntry->uncompressedSize) || + !juce::SHA256 (fx.binary).toHexString().equalsIgnoreCase ( + entry.getProperty ("sha256", {}).toString())) + return "VST3 state integrity check failed"; + temp.effects.push_back (std::move (fx)); + } + output = std::move (temp); // transactional: caller sees only validated state + return {}; + } + +private: + juce::File folder_; +}; +} // namespace armix::storage diff --git a/src/PluginCatalog.h b/src/PluginCatalog.h new file mode 100644 index 000000000..d3be9b56c --- /dev/null +++ b/src/PluginCatalog.h @@ -0,0 +1,305 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#if JUCE_WINDOWS + #include +#endif +#include +#include +#include + +// All callbacks run on JUCE's message thread. The scanner performs filesystem +// enumeration and plugin metadata discovery on a dedicated non-audio thread. +struct CatalogEntry +{ + juce::String path, name, vendor, category; + int uid = 0; + int variant = 0; + + juce::String key() const { return path + "|" + juce::String (uid) + "|" + juce::String (variant); } + + juce::var toVar() const + { + auto o = std::make_unique(); + o->setProperty ("id", key()); + o->setProperty ("path", path); + o->setProperty ("name", name); + o->setProperty ("vendor", vendor); + o->setProperty ("category", category); + o->setProperty ("uid", uid); + o->setProperty ("variant", variant); + return juce::var (o.release()); + } + + static CatalogEntry fromVar (const juce::var& v) + { + CatalogEntry e; + e.path = v.getProperty ("path", {}).toString(); + e.name = v.getProperty ("name", {}).toString(); + e.vendor = v.getProperty ("vendor", {}).toString(); + e.category = v.getProperty ("category", {}).toString(); + e.uid = static_cast (v.getProperty ("uid", 0)); + e.variant = static_cast (v.getProperty ("variant", 0)); + return e; + } +}; + +class PluginCatalog final +{ +public: + using Callback = std::function; + explicit PluginCatalog (juce::File dataFolder) + : dataFolder_ (std::move (dataFolder)), worker_ (*this) + { + dataFolder_.createDirectory(); + load(); + } + + ~PluginCatalog() + { + alive_.store (false); + lifetime_->store (false); + worker_.signalThreadShouldExit(); + // Scanning cannot be forcibly cancelled inside a third-party scanner. + // Never detach a worker that still references this object. + worker_.stopThread (-1); + } + + const std::vector& entries() const noexcept { return entries_; } + bool busy() const noexcept { return scanning_.load(); } + juce::String scanMessage() const { return scanMessage_; } + // Real scan counters. Enumeration has no known denominator; only report + // a percentage after candidate discovery has finished. + juce::var progress() const + { + auto result = std::make_unique(); + const auto phase = phase_.load (std::memory_order_acquire); + const auto total = total_.load (std::memory_order_relaxed); + result->setProperty ("active", busy()); + result->setProperty ("phase", phase == 1 ? "discovering" : + phase == 2 ? "inspecting" : "done"); + result->setProperty ("done", completed_.load (std::memory_order_relaxed)); + result->setProperty ("total", total); + result->setProperty ("found", found_.load (std::memory_order_relaxed)); + { + const juce::ScopedLock lock (progressLock_); + result->setProperty ("current", current_); + } + return juce::var (result.release()); + } + Callback onChanged; + + void addDirectory (const juce::File& folder) + { + if (! folder.isDirectory() || busy()) + return; + const auto p = folder.getFullPathName(); + if (! customFolders_.contains (p)) + { + customFolders_.add (p); + save(); + } + scan ({ p }); + } + + void scanDefaults() + { + juce::VST3PluginFormat format; + juce::StringArray paths; + const auto defaults = format.getDefaultLocationsToSearch(); + for (int i = 0; i < defaults.getNumPaths(); ++i) + paths.addIfNotAlreadyThere (defaults[i].getFullPathName()); + for (const auto& p : customFolders_) + paths.addIfNotAlreadyThere (p); + scan (paths); + } + + // Direct VST3 file/bundle import (no forced recursive system scan). + // Native .dll is legacy VST2 and is deliberately not mislabeled as VST3. + void importVst3 (const juce::File& file) + { + if (busy()) return; + if (! file.exists() || ! file.hasFileExtension (".vst3")) + { + scanMessage_ = "Choose a .vst3 file or bundle. Legacy VST2 .dll is not supported."; + if (onChanged) onChanged(); + return; + } + scan (juce::StringArray { file.getFullPathName() }); + } + + const CatalogEntry* find (const juce::String& id) const + { + for (const auto& entry : entries_) + if (entry.key() == id) + return &entry; + return nullptr; + } + + juce::var snapshot() const + { + auto o = std::make_unique(); + juce::Array list; + for (const auto& entry : entries_) + list.add (entry.toVar()); + o->setProperty ("items", juce::var (list)); + o->setProperty ("scanning", busy()); + o->setProperty ("message", scanMessage_); + o->setProperty ("count", static_cast (entries_.size())); + return juce::var (o.release()); + } + +private: + struct Scanner final : juce::Thread + { + explicit Scanner (PluginCatalog& owner) : juce::Thread ("AR MIX VST3 Scanner"), owner_ (owner) {} + PluginCatalog& owner_; + juce::StringArray requested_; + + void run() override + { + #if JUCE_WINDOWS + const auto hr = CoInitializeEx (nullptr, COINIT_APARTMENTTHREADED); + #endif + std::vector found; + juce::VST3PluginFormat format; + juce::StringArray allCandidates; + // 1. Enumerate candidates. Total cannot be estimated here. + owner_.phase_.store (1, std::memory_order_release); + for (const auto& requested : requested_) + { + if (threadShouldExit()) break; + const juce::File file (requested); + juce::StringArray candidates; + if (file.isDirectory() && ! file.hasFileExtension (".vst3")) + { + juce::FileSearchPath search; + search.add (file); + candidates = format.searchPathsForPlugins (search, true, false); + } + else if (file.hasFileExtension (".vst3")) + candidates.add (requested); + for (const auto& path : candidates) + allCandidates.addIfNotAlreadyThere (path); + } + + // 2. Inspect actual plugins; progress denominator is now real. + owner_.total_.store (allCandidates.size(), std::memory_order_relaxed); + owner_.phase_.store (2, std::memory_order_release); + for (int n = 0; n < allCandidates.size(); ++n) + { + if (threadShouldExit()) break; + const auto path = allCandidates[n]; + { + const juce::ScopedLock lock (owner_.progressLock_); + owner_.current_ = juce::File (path).getFileName(); + } + if (format.fileMightContainThisPluginType (path)) + { + juce::OwnedArray descriptions; + format.findAllTypesForFile (descriptions, path); + for (int i = 0; i < descriptions.size(); ++i) + { + const auto* desc = descriptions[i]; + if (desc == nullptr || desc->isInstrument) continue; + found.push_back ({ desc->fileOrIdentifier, desc->name, + desc->manufacturerName, desc->category, + desc->uniqueId, i }); + } + } + owner_.found_.store (static_cast (found.size()), std::memory_order_relaxed); + owner_.completed_.store (n + 1, std::memory_order_release); + } + { + const juce::ScopedLock lock (owner_.progressLock_); + owner_.current_.clear(); + } + #if JUCE_WINDOWS + if (SUCCEEDED (hr)) CoUninitialize(); + #endif + // Completion is delivered by a SafePointer owned by the UI host, + // so destruction cannot dereference the window after shutdown. + auto lifetime = owner_.lifetime_; + juce::MessageManager::callAsync ([&owner = owner_, lifetime, results = std::move (found)]() mutable + { + if (! lifetime->load()) return; + for (const auto& e : results) + { + const auto iter = std::find_if (owner.entries_.begin(), owner.entries_.end(), + [&e] (const CatalogEntry& old) { return old.key() == e.key(); }); + if (iter == owner.entries_.end()) + owner.entries_.push_back (e); + else + *iter = e; + } + std::sort (owner.entries_.begin(), owner.entries_.end(), + [] (const CatalogEntry& a, const CatalogEntry& b) + { return a.name.compareIgnoreCase (b.name) < 0; }); + owner.scanMessage_ = "Scan complete: " + juce::String (results.size()) + " plugin variants inspected"; + owner.phase_.store (0, std::memory_order_release); + owner.scanning_.store (false); + owner.save(); + if (owner.onChanged) owner.onChanged(); + }); + } + }; + + void scan (const juce::StringArray& paths) + { + if (busy()) return; + completed_.store (0); + total_.store (0); + found_.store (0); + phase_.store (1); + { const juce::ScopedLock lock (progressLock_); current_.clear(); } + scanning_.store (true); + scanMessage_ = "Scanning VST3 metadata (background)..."; + if (onChanged) onChanged(); + worker_.requested_ = paths; + worker_.startThread(); + } + + void load() + { + auto json = juce::JSON::parse (dataFolder_.getChildFile ("plugin-catalog.json")); + const auto storedItems = json.getProperty ("items", {}); + if (auto* items = storedItems.getArray()) + for (const auto& item : *items) + { + auto entry = CatalogEntry::fromVar (item); + if (entry.path.isNotEmpty()) + entries_.push_back (std::move (entry)); + } + const auto storedFolders = json.getProperty ("folders", {}); + if (auto* folders = storedFolders.getArray()) + for (const auto& folder : *folders) + customFolders_.addIfNotAlreadyThere (folder.toString()); + scanMessage_ = "Ready - " + juce::String (entries_.size()) + " cached VST3 effects"; + } + + void save() + { + auto o = std::make_unique(); + juce::Array list, folders; + for (const auto& entry : entries_) list.add (entry.toVar()); + for (const auto& folder : customFolders_) folders.add (folder); + o->setProperty ("schemaVersion", 1); + o->setProperty ("items", juce::var (list)); + o->setProperty ("folders", juce::var (folders)); + dataFolder_.getChildFile ("plugin-catalog.json") + .replaceWithText (juce::JSON::toString (juce::var (o.release()), true)); + } + + juce::File dataFolder_; + std::vector entries_; + juce::StringArray customFolders_; + std::atomic alive_ { true }, scanning_ { false }; + std::shared_ptr> lifetime_ = std::make_shared> (true); + mutable juce::CriticalSection progressLock_; + juce::String current_; + std::atomic phase_ { 0 }, total_ { 0 }, completed_ { 0 }, found_ { 0 }; + juce::String scanMessage_ = "Ready"; + Scanner worker_; +}; diff --git a/src/StereoPan.h b/src/StereoPan.h new file mode 100644 index 000000000..4d205a88f --- /dev/null +++ b/src/StereoPan.h @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include + +namespace armix::dsp +{ +// Branch selection occurs once per buffer, not inside the sample loop. +// Center: transparent stereo identity. +// Extremes: both channels fold into the selected output with 0.5 weights, +// so dual-mono input stays at unity instead of gaining +6 dB. +struct StereoPanMatrix final +{ + float ll = 1.f, lr = 0.f, rl = 0.f, rr = 1.f; + + static StereoPanMatrix fromNormalized (float p) noexcept + { + if (!std::isfinite (p)) p = 0.f; + p = std::clamp (p, -1.f, 1.f); + return { + p > 0.f ? 1.f - p : 1.f + .5f * p, + p < 0.f ? -.5f * p : 0.f, + p > 0.f ? .5f * p : 0.f, + p < 0.f ? 1.f + p : 1.f - .5f * p + }; + } +}; +} // namespace armix::dsp diff --git a/src/VstBusLayout.h b/src/VstBusLayout.h new file mode 100644 index 000000000..07b7cb55e --- /dev/null +++ b/src/VstBusLayout.h @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include + +// Non-RT only. The host processes a 2-channel scratch block. Keep the +// plugin's already-compatible main stereo buses unchanged, rather than +// unconditionally forcing a new layout (which can fail for VST3s with +// optional sidechain/auxiliary buses). +namespace armix::vst +{ +inline juce::String describeBuses (const juce::AudioProcessor::BusesLayout& layout) +{ + juce::String text; + const auto describe = [] (const juce::Array& buses) + { + juce::StringArray names; + for (const auto& bus : buses) + names.add (juce::String (bus.size()) + "ch"); + return names.joinIntoString (","); + }; + return "inputs [" + describe (layout.inputBuses) + "], outputs [" + + describe (layout.outputBuses) + "]"; +} + +inline juce::String prepareStereoEffectLayout (juce::AudioProcessor& processor) +{ + if (processor.getBusCount (true) < 1 || processor.getBusCount (false) < 1) + return "VST3 has no main input or output bus"; + + auto original = processor.getBusesLayout(); + if (original.inputBuses.isEmpty() || original.outputBuses.isEmpty()) + return "VST3 reports missing main bus layout"; + const auto stereo = juce::AudioChannelSet::stereo(); + const auto disabled = juce::AudioChannelSet::disabled(); + const auto compatible = [&stereo, &disabled] (const juce::AudioProcessor::BusesLayout& l) + { + if (l.inputBuses.isEmpty() || l.outputBuses.isEmpty() || + l.inputBuses[0] != stereo || l.outputBuses[0] != stereo) return false; + for (int i = 1; i < l.inputBuses.size(); ++i) + if (l.inputBuses[i] != disabled) return false; + for (int i = 1; i < l.outputBuses.size(); ++i) + if (l.outputBuses[i] != disabled) return false; + return true; + }; + + // Working defaults (common in FabFilter and other commercial VST3s) + // must not be reset just because the host wants stereo. + if (compatible (original)) return {}; + + auto requested = original; + requested.inputBuses.set (0, stereo); + requested.outputBuses.set (0, stereo); + for (int i = 1; i < requested.inputBuses.size(); ++i) + requested.inputBuses.set (i, disabled); + for (int i = 1; i < requested.outputBuses.size(); ++i) + requested.outputBuses.set (i, disabled); + + if (processor.setBusesLayout (requested) && + compatible (processor.getBusesLayout())) return {}; + + return "Stereo main bus could not be negotiated (existing " + + describeBuses (original) + "). This host requires stereo in/out with optional sidechains disabled."; +} +} // namespace armix::vst diff --git a/tests/fx_add_contract_test.mjs b/tests/fx_add_contract_test.mjs new file mode 100644 index 000000000..0e640a20c --- /dev/null +++ b/tests/fx_add_contract_test.mjs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Regression guard for nonresponsive ADD FX clicks and VST3 stereo/sidechain. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +const js=readFileSync('web/bridge.js','utf8'); +const host=readFileSync('src/Main.cpp','utf8'); +const dsp=readFileSync('src/LiveAudioEngine.h','utf8'); +const layout=readFileSync('src/VstBusLayout.h','utf8'); + +test('every ADD click identifies request and reports result inside the open selector',()=>{ + assert.match(js,/send\("addCatalog",\{id,requestId\}\)/); + assert.match(js,/backend\.addEventListener\("arMixAddResult"/); + assert.match(js,/nativeAddFeedback/); + assert.match(js,/FX NOT LOADED:/); + assert.match(js,/if\(result\.ok\)hideDialog\("nativeFxSelector"\)/); + assert.match(host,/emitFxAddResult \(requestId, name, error, elapsed\)/); + assert.match(host,/FX_LOAD_FAIL/); +}); +test('plugin load and preset restore both negotiate existing VST3 bus layouts',()=>{ + assert.equal((dsp.match(/prepareStereoEffectLayout/g)||[]).length,2); + assert.match(layout,/if \(compatible \(original\)\) return \{\};/); + assert.match(layout,/requested\.inputBuses\.set \(i, disabled\)/); + assert.match(layout,/processor\.setBusesLayout \(requested\)/); +}); +test('GUI paints actual indeterminate feedback before synchronous plugin instantiate',()=>{ + assert.match(js,/requestAnimationFrame\(\(\)=>requestAnimationFrame\(\(\)=>send\("addCatalog"/); + assert.match(js,/aria-live="polite"/); + assert.match(js,/state\.adding=true/); +}); diff --git a/tests/live_graph_contract_test.mjs b/tests/live_graph_contract_test.mjs new file mode 100644 index 000000000..86ce65738 --- /dev/null +++ b/tests/live_graph_contract_test.mjs @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Static wiring contracts supplement the 12k native handoff stress cycles. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +const e=readFileSync('src/LiveAudioEngine.h','utf8'); +const h=readFileSync('src/LiveGraphHandoff.h','utf8'); +const m=readFileSync('src/Main.cpp','utf8'); +const b=readFileSync('web/bridge.js','utf8'); +test('live recall stages complete VST state before pointer publication',()=>{ + const restore=e.slice(e.indexOf('juce::String restoreSnapshot'), e.indexOf('bool setBypass')); + assert.match(restore,/prepareToPlay \(rate, buffer\)/); + assert.match(restore,/setStateInformation/); + assert.match(restore,/handoff_\.stage \(stagedOwner_\.get\(\)\)/); + assert.doesNotMatch(restore,/\bdetach\s*\(/); +}); +test('RT callback owns pointer switch and message thread owns third party destruction',()=>{ + assert.match(e,/handoff_\.beginCycle\(\)/); + assert.match(e,/handoff_\.endCycle \(cycle\)/); + assert.match(e,/handoff_\.takeRetired\(\)/); + assert.match(e,/handoff_\.completeRetirement\(\)/); + assert.match(h,/std::atomic active_/); + assert.match(h,/std::atomic phase_/); +}); +test('preset UI reflects callback-acknowledged state not queued state',()=>{ + assert.match(m,/if \(engine_\.finalizeGraphSwitch\(\)\)/); + assert.match(m,/pendingPresetUI_/); + assert.match(m,/arMixNativePresetLoaded/); + assert.match(b,/RECALL LIVE/); +}); +test('old structural operations remain guarded and declared as unfinished',()=>{ + assert.match(e,/if \(handoff_\.busy\(\)\) return false/); + assert.match(e,/Legacy Add\/Remove\/Move still detach/); +}); diff --git a/tests/main_v08_native_integration_test.mjs b/tests/main_v08_native_integration_test.mjs new file mode 100644 index 000000000..e109ea9ce --- /dev/null +++ b/tests/main_v08_native_integration_test.mjs @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +const read=p=>readFileSync(p,'utf8'); +const app=read('web/app.js'), css=read('web/styles.css'), html=read('web/index.html'); +const bridge=read('web/bridge.js'), src=read('src/LiveAudioEngine.h'), offline=read('AR-MIX-Live-FX-Host-Standalone-v0.3.html'); +test('GUI v0.8 remains the canonical host, not an older v0.5 reset',()=>{ + assert.match(app,/function openChannelIdentity\(/); + assert.match(app,/function masterFxRows\(/); + assert.match(app,/class="master-analysis"/); + assert.match(app,/LUFS-I/); + assert.match(app,/dBTP/); + assert.match(html,/id="channelIdentity"/); + assert.match(css,/rail-input-footer/); + assert.match(css,/master-analysis/); + assert.match(html,/src="bridge\.js"/); + assert.match(html,/src="monitor\.js"/); +}); +test('offline standalone is the byte-matched MAIN v0.8 demo',()=>{ + assert.ok(offline.includes('')); + assert.ok(offline.includes('')); +}); +test('no fake oscillating VUs inside native JUCE',()=>{ + const a=app.indexOf('function meters(t)'),guard=app.indexOf('if(window.__JUCE__?.backend?.emitEvent)return;',a),raf=app.indexOf('requestAnimationFrame(meters)',a); + assert.ok(a>=0&&guard>a&&guard{ + assert.match(src,/handoff_\.beginCycle\(/); + assert.match(src,/handoff_\.stage\(/); + assert.match(bridge,/arMixNativePresetLoaded/); + assert.match(bridge,/Master PAN DSP not yet implemented/); + assert.match(bridge,/data-fxpower/); +}); diff --git a/tests/native_preset_contract_test.mjs b/tests/native_preset_contract_test.mjs new file mode 100644 index 000000000..a3e914803 --- /dev/null +++ b/tests/native_preset_contract_test.mjs @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Static guard: the native preset path must never silently fall back to demo +// localStorage or authorize an unmuted VST3 graph mutation. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +const get=p=>readFileSync(p,'utf8'); +const main=get('src/Main.cpp'), engine=get('src/LiveAudioEngine.h'); +const io=get('src/NativePresetArchive.h'), bridge=get('web/bridge.js'); +test('full vendor state is captured/restored by the native host',()=>{ + assert.match(engine,/getStateInformation \(state\.binary\)/); + assert.match(engine,/setStateInformation \(/); + assert.match(engine,/snapshot\.effects\.push_back/); + assert.match(engine,/auto retired = std::move \(slots_\)/); +}); +test('ZIP archive does not extract untrusted paths to disk',()=>{ + assert.match(io,/juce::ZipFile::Builder/); + assert.match(io,/manifest\.json/); + assert.match(io,/juce::SHA256/); + assert.match(io,/maxStateBytes = 8 \* 1024 \* 1024/); + assert.doesNotMatch(io,/uncompressTo|uncompressEntry/); +}); +test('muted-only safety and transactional read',()=>{ + assert.match(main,/!engine_\.isOutputMuted\(\)/); + assert.match(engine,/if \(!isOutputMuted\(\)\)/); + assert.match(io,/output = std::move \(temp\)/); +}); +test('separate native My Sounds not browser-only preset',()=>{ + assert.match(bridge,/data-my-sounds/); + assert.match(bridge,/send\("presetSave",\{name\}\)/); + assert.match(bridge,/send\("presetLoad",\{name\}\)/); + assert.match(bridge,/arMixNativePresetLoaded/); +}); diff --git a/tests/native_preset_roundtrip_test.cpp b/tests/native_preset_roundtrip_test.cpp new file mode 100644 index 000000000..7f77567f0 --- /dev/null +++ b/tests/native_preset_roundtrip_test.cpp @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Runtime test for the actual .armix ZIP implementation, not static text. +#ifdef NDEBUG + #undef NDEBUG +#endif +#include +#include +#include +#include "../src/NativePresetArchive.h" + +int main() +{ + auto folder = juce::File::getSpecialLocation (juce::File::tempDirectory) + .getNonexistentChildFile ("ArSonMixPresetUnit", "", false); + assert (folder.createDirectory().wasOk()); + armix::storage::NativePresetArchive archive (folder); + + armix::storage::Snapshot original; + original.name = "Vocal Session 01"; + original.channelDb = -7.25f; + original.masterDb = -3.5f; + original.pan = .42f; + original.channelMute = true; + original.masterMute = false; + armix::storage::FxState plugin; + plugin.name = "Test FX"; + plugin.path = "C:/Nonexistent/Test FX.vst3"; + plugin.uid = 982314; + plugin.catalogId = "test-fx-982314"; + plugin.bypass = true; + const char bytes[] = { '\x01', '\x00', '\x02', '\x7f', '\x01', '\x12' }; + plugin.binary.append (bytes, sizeof (bytes)); + original.effects.push_back (std::move (plugin)); + const auto error = archive.save (original); + if (error.isNotEmpty()) std::cerr << "SAVE: " << error << "\n"; + assert (error.isEmpty()); + + armix::storage::Snapshot loaded; + const auto loadError = archive.load (original.name, loaded); + if (loadError.isNotEmpty()) std::cerr << "LOAD: " << loadError << "\n"; + assert (loadError.isEmpty()); + assert (loaded.name == original.name); + assert (std::abs (loaded.channelDb - original.channelDb) < 1e-4f); + assert (std::abs (loaded.masterDb - original.masterDb) < 1e-4f); + assert (std::abs (loaded.pan - original.pan) < 1e-4f); + assert (loaded.channelMute && !loaded.masterMute); + assert (loaded.effects.size() == 1); + assert (loaded.effects[0].path == original.effects[0].path); + assert (loaded.effects[0].uid == original.effects[0].uid); + assert (loaded.effects[0].catalogId == original.effects[0].catalogId); + assert (loaded.effects[0].bypass); + assert (loaded.effects[0].binary == original.effects[0].binary); + + // Malformed ZIP must not replace previously validated snapshot state. + const auto existingName = loaded.name; + { + juce::FileOutputStream out (archive.fileFor (original.name)); + assert (out.openedOk()); + assert (out.setPosition (0)); + assert (out.writeByte ('?')); + out.flush(); + } + auto failure = archive.load (original.name, loaded); + assert (failure.isNotEmpty()); + assert (loaded.name == existingName && loaded.effects.size() == 1); + + folder.deleteRecursively(); + std::cout << "PASS: native ZIP round-trip, binary VST state, mixer values, corruption refusal\n"; + return 0; +} diff --git a/tests/native_ui_contract_test.mjs b/tests/native_ui_contract_test.mjs new file mode 100644 index 000000000..4172aa07c --- /dev/null +++ b/tests/native_ui_contract_test.mjs @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// No dependencies; catches regressions between the legacy v0.3 GUI and native host. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +const app=readFileSync('web/app.js','utf8'); +const bridge=readFileSync('web/bridge.js','utf8'); +const engine=readFileSync('src/LiveAudioEngine.h','utf8'); +const main=readFileSync('src/Main.cpp','utf8'); +const recorder=readFileSync('src/DiagnosticsRecorder.h','utf8'); +test('native app never runs demo sine meters',()=>{ + const fn=app.indexOf('function meters(t)'); + const nativeExit=app.indexOf('if(window.__JUCE__?.backend?.emitEvent)return;',fn); + const demoLoop=app.indexOf('requestAnimationFrame(meters)',fn); + assert.ok(fn>=0 && nativeExit>fn && nativeExit{ + assert.match(bridge,/inputLevel=percent\(d\.inputPeak\)/); + assert.match(bridge,/outputLevel=percent\(d\.peak\)/); + assert.ok(bridge.includes('["masterL",liveOutputLeft]')); + assert.ok(bridge.includes('["masterR",liveOutputRight]')); + assert.match(bridge,/track\.dataset\.preview="1"/); + assert.ok(bridge.includes("meter-fill{opacity:0!important}")); +}); +test('quick FX bypass is wired to native slot instead of demo mock',()=>{ + assert.match(bridge,/data-native-fx="bypass" data-slot="\$\{i\}"/); + assert.match(bridge,/aria-pressed="\$\{!p\.bypass\}"/); + assert.match(bridge,/send\("fxBypass",\{slot,value:!state\.chain\[slot\]\?\.bypass\}\)/); + assert.match(engine,/graphOwned_->bypassFlags\[index\]\.store/); +}); +test('GUI pan event reaches actual callback pan matrix',()=>{ + assert.match(app,/send\(master\?'masterPan':'pan',c\.pan,master\?-1:idx\)/); + assert.match(main,/name == "pan" && channel == 1/); + assert.match(engine,/StereoPanMatrix::fromNormalized/); +}); +test('health logger has room for complete JSON snapshots',()=>{ + assert.match(recorder,/char data\[4096\]/); + assert.match(recorder,/truncatedRecords\(\)/); +}); diff --git a/tests/realtime_control_test.cpp b/tests/realtime_control_test.cpp index 8d18885e2..0cb920ab9 100644 --- a/tests/realtime_control_test.cpp +++ b/tests/realtime_control_test.cpp @@ -1,7 +1,12 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/core/RealtimeControl.h" #include +#ifdef NDEBUG + #undef NDEBUG +#endif #include +#include "../src/StereoPan.h" +#include "../src/LiveGraphHandoff.h" #include #include #include @@ -29,5 +34,78 @@ int main(){ std::thread producer([&]{for(std::uint32_t i=0;i handoff; + handoff.initialize (&old); + assert(!handoff.busy() && handoff.current()==&old); + assert(handoff.stage(&next) && !handoff.stage(&third)); + auto first=handoff.beginCycle(); + assert(first.graph==&old && first.fadeOut && !first.fadeIn); + assert(armix::rt::linearBufferRamp(0,128,true,false)==1.f); + assert(armix::rt::linearBufferRamp(127,128,true,false)==0.f); + handoff.endCycle(first); + assert(handoff.current()==&next && handoff.busy()); + assert(!handoff.stage(&third)); + assert(handoff.takeRetired()==&old); + // Retirement acknowledgement stays pending until old owners are actually + // destroyed by control; no premature second stage in the handoff gap. + assert(!handoff.stage(&third)); + handoff.completeRetirement(); + assert(handoff.stage(&third)); + auto second=handoff.beginCycle(); + assert(second.graph==&next && second.fadeOut && second.fadeIn); + handoff.endCycle(second); + assert(handoff.takeRetired()==&next); + handoff.completeRetirement(); + assert(handoff.current()==&third); + auto last=handoff.beginCycle(); + assert(!last.fadeOut && last.fadeIn); + assert(armix::rt::linearBufferRamp(0,128,false,true)==0.f); + assert(armix::rt::linearBufferRamp(127,128,false,true)==1.f); + handoff.endCycle(last); + // Repeat thousands of publications on another callback thread and + // consume the acknowledgement only from the control thread. + armix::rt::LiveGraphHandoff threaded; + threaded.initialize (&old); + constexpr int rounds=12000; + std::atomic ended{false}; + std::thread audio([&] { + while(!ended.load(std::memory_order_acquire)) { + auto cycle=threaded.beginCycle(); + if(cycle.fadeOut)threaded.endCycle(cycle); + else std::this_thread::yield(); + } + }); + for(int i=0;ireadFileSync(p,'utf8'); +const html=read('web/index.html'),app=read('web/app.js'),css=read('web/styles.css'); +const bridge=read('web/bridge.js'),engine=read('src/LiveAudioEngine.h'); +test('latest desktop GUI is present and actually loads native bridge',()=>{ + assert.match(app,/function openChannelIdentity\(/); + assert.match(app,/id="masterLeft"/); + assert.match(app,/class="fx-power/); + assert.match(app,/data-meter="\$\{key\}"/); + assert.match(html,/id="channelIdentity"/); + assert.match(html,/src="bridge\.js"/); + assert.match(html,/src="monitor\.js"/); + assert.match(css,/master-fx-rack/); +}); +test('native desktop does not run any visual-only sine meter loop',()=>{ + const fn=app.indexOf('function meters(t)'); + assert.ok(fn>0); + const early=app.indexOf('if(window.__JUCE__?.backend?.emitEvent)return;',fn); + const osc=app.indexOf('requestAnimationFrame(meters)',fn); + assert.ok(early>fn&&early{ + assert.match(bridge,/data-master-insert/); + assert.match(bridge,/data-master-power/); + assert.match(bridge,/Master PAN DSP not yet implemented/); + assert.match(bridge,/Only Channel 1|Channel 1/); +}); +test('full engine capabilities preserved',()=>{ + assert.match(engine,/prepareStereoEffectLayout/); + assert.match(engine,/NativePresetArchive/); + assert.match(engine,/handoff_\.stage/); + assert.match(engine,/handoff_\.beginCycle/); + assert.match(bridge,/arMixAddResult/); + assert.match(bridge,/arMixNativePresetLoaded/); +}); diff --git a/web/app.js b/web/app.js index 18935803c..40e1fcfce 100644 --- a/web/app.js +++ b/web/app.js @@ -272,6 +272,8 @@ document.addEventListener('keydown',e=>{const pan=e.target.closest('[data-pan]') }); document.addEventListener('keydown',e=>{if(e.ctrlKey&&e.key.toLowerCase()==='s'){e.preventDefault();if(persistSession())flash('UI state saved locally');else flash('Browser storage unavailable')}}); let lastMeterFrame=0;function meters(t){ + // JUCE desktop reads actual audio meters; browser demo only animates a preview. + if(window.__JUCE__?.backend?.emitEvent)return; requestAnimationFrame(meters);if(t-lastMeterFrame<33||document.hidden)return;lastMeterFrame=t; channels.forEach((ch,i)=>{const wave=(Math.sin(t*.0022+i*1.92)+Math.sin(t*.0043+i*.6))*.5; let v=clamp(45+wave*24+ch.fader*.48,4,98);if(ch.mute)v=2;updateMeterVisual(String(i),v,t)}); diff --git a/web/bridge.js b/web/bridge.js new file mode 100644 index 000000000..8f429a3a5 --- /dev/null +++ b/web/bridge.js @@ -0,0 +1,621 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Actual JUCE native bridge. This script is loaded only inside the desktop host. +// Never claims the other 11 concept tracks or mock presets are live channels. +(() => { + const backend = window.__JUCE__?.backend; + if (!backend?.emitEvent || !backend?.addEventListener) return; + document.documentElement.classList.add("native-engine"); + // Clear preview levels before first device callback/status reaches WebView. + document.querySelectorAll("[data-meter],#masterMeterL,#masterMeterR,#masterMeterAux") + .forEach(el=>el.style.setProperty("--level","0%")); + + const send = (action, more = {}) => backend.emitEvent("arMixAction", {action, ...more}); + const state = {catalog: [], chain: [], scanning: false, message: "Connecting to native host...", + device: {}, presets: [], addRequestId:0, addError:"", pendingPlugin:"", filter: "", selectedCategory: "All", monitor: false, error: "", progress: {active:false,phase:"done",done:0,total:0,found:0,current:""}, adding:false}; + + const escapeHtml = text => String(text ?? "").replace(/[&<>"']/g, c => ( + {"&":"&","<":"<",">":">",'"':""","'":"'"}[c])); + const percent = peak => Math.max(1,Math.min(100,(20*Math.log10(Math.max(1e-6,Number(peak)||0))+60)*100/60)); + const toStatus = text => { + const e = document.querySelector("#nativeDeviceStatus"); + if(e) e.textContent = text; + const footer = document.querySelector("#audioStatus"); + if(footer) footer.textContent = text; + }; + + // The v0.3 cosmetic demo catalog and FX editor are replaced with the REAL + // catalog/chain when running in JUCE. Keep HTML trial standalone unchanged. + const css = document.createElement("style"); + css.textContent = ` + .native-toolbar{display:flex;flex-wrap:wrap;gap:7px;align-items:center} + .native-btn{font:inherit;color:#d6e9ef;padding:8px 12px;border:1px solid #48677a;border-radius:6px; + background:linear-gradient(180deg,#405c70 0%,#243846 47%,#0d1e29 100%);cursor:pointer; + box-shadow:inset 0 1px 1px #93badc70,0 2px 3px #0008} + .native-btn:hover{border-color:#62b8dc} + .native-add-feedback{margin:9px 0 11px;padding:10px 12px;border-radius:5px;font-size:12px; + line-height:1.55;border:1px solid #4e7789;background:#153545;color:#b9eaff} + .native-add-feedback.error{background:#39252a;border-color:#b76b68;color:#ffe0d4} + .native-add-feedback.waiting{background:#203849;border-color:#669abc;color:#c4ecff} + .native-add-feedback strong{font-weight:600} + .native-add-feedback .native-busy{display:inline-block;width:10px;height:10px; + margin-right:7px;border:2px solid #477a97;border-top-color:#80eaff; + border-radius:100%;animation:nativeBusySpin 1s linear infinite} + @keyframes nativeBusySpin{to{transform:rotate(360deg)}} + .native-btn.primary{border-color:#2dbee9;background:linear-gradient(180deg,#4cddff 0%,#0f9fd1 42%,#08688c 100%);color:#042231} + .native-btn.warn{color:#ffd0c9;border-color:#915552} + .native-btn.on{border-color:#4ae3fd;color:#9ceaff;background:linear-gradient(#165b79,#123142)} + .native-panel{padding:16px 18px;max-width:1160px;margin:0 auto;color:#dcecf2;box-sizing:border-box} + .native-hdr{display:flex;justify-content:space-between;gap:15px;align-items:start;padding:6px 0 16px} + .native-hdr h2{font-size:19px;font-weight:500;margin:5px 0} + .native-sub{font-size:12px;color:#8da9b9;line-height:1.6} + .native-grid{display:grid;grid-template-columns:minmax(300px,1fr) minmax(280px,.95fr);gap:14px} + .native-card{background:linear-gradient(160deg,#1e303c,#13222c 75%);border:1px solid #3b5361;border-radius:9px;padding:12px; + box-shadow:inset 0 1px #7fb0ca27,0 7px 18px #0004;min-height:180px} + .native-card h3{font-size:13px;font-weight:550;color:#7fe4fb;margin:2px 0 12px} + .native-nodes{display:flex;flex-direction:column;gap:7px} + .native-node{display:flex;align-items:center;gap:7px;padding:7px 8px;border:1px solid #405a69;border-radius:6px;background:#101e28} + .native-node .node-index{color:#52c9ea;font:12px monospace;width:22px} + .native-node .node-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px} + .native-node .node-text small{display:block;color:#7196a8;font-size:10px;margin-top:3px} + .native-node.is-bypassed{opacity:.55} + .native-node button{padding:5px 7px;font-size:10px;min-width:28px} + .native-search{box-sizing:border-box;display:block;width:100%;font:12px inherit;outline:0;color:#dcecf2; + border:1px solid #4b6b79;background:#0b1923;border-radius:5px;padding:10px;margin-bottom:9px} + .native-category{display:flex;gap:4px;flex-wrap:wrap;margin:7px 0} + .native-category button{padding:5px 10px;font-size:11px} + .native-scroll{max-height:400px;overflow:auto;display:flex;flex-direction:column;gap:6px} + .native-item{display:flex;gap:8px;align-items:center;border:1px solid #324d5a;padding:8px 9px;background:#10232d;border-radius:6px} + .native-item div{min-width:0;flex:1} + .native-item b{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;font-weight:500} + .native-item small{color:#749aab;font-size:10px} + .native-tag{font-size:9px;border:1px solid #3f7a90;padding:3px 5px;border-radius:3px;color:#8ad6ed} + .native-empty{border:1px dashed #3b5361;padding:18px;color:#8fafbc;text-align:center;border-radius:5px;font-size:12px} + .native-status{padding:8px 10px;background:#10212c;border:1px solid #36546b;border-radius:5px;font-size:11px;color:#97bac8} + #nativeP2{display:flex;gap:5px;align-items:center;font-size:10px;white-space:nowrap} + #nativeP2 button{padding:4px 8px;font-size:10px} + #nativeDeviceStatus{color:#a8c4d0;max-width:360px;overflow:hidden;text-overflow:ellipsis} + .status-help{flex:1;min-width:0} + @media(max-width:1150px){.native-grid{grid-template-columns:1fr}.native-hdr{flex-direction:column}} + `; + css.textContent += "\n .native-modal{position:fixed;inset:0;z-index:700;display:flex;align-items:center;justify-content:center;\n background:rgba(3,11,18,.78);backdrop-filter:blur(5px);padding:22px;box-sizing:border-box}\n .native-modal[hidden]{display:none}\n .native-dialog{width:min(860px,96vw);max-height:min(840px,92vh);overflow:hidden;\n display:flex;flex-direction:column;background:linear-gradient(145deg,#243945 0%,#101e29 62%,#0c1821);\n border:1px solid #638293;border-radius:11px;box-shadow:0 18px 80px #000c,inset 0 1px #b2d9e449}\n .native-dialog-header{display:flex;align-items:center;justify-content:space-between;gap:15px;\n border-bottom:1px solid #3c5360;padding:14px 17px}\n .native-dialog-header h2{font-size:18px;font-weight:500;color:#e4f4f9;margin:4px 0}\n .native-dialog-body{padding:14px 17px;overflow:auto;min-height:60px}\n .native-dialog-footer{border-top:1px solid #334b58;padding:9px 17px;color:#91abb8;font-size:11px}\n .native-dialog.small{max-width:520px}\n .native-bar{height:12px;border:1px solid #527282;background:#0a1621;border-radius:7px;overflow:hidden;position:relative;\n box-shadow:inset 0 2px 5px #000c}\n .native-bar-fill{height:100%;width:0%;background:linear-gradient(180deg,#8ef6ff,#17a8da 43%,#08688e);\n box-shadow:0 0 8px #1ed5fcbb;border-right:1px solid #ddffff}\n .native-bar.unknown .native-bar-fill{width:34%;position:absolute;animation:native-indeterminate 1.65s ease-in-out infinite}\n @keyframes native-indeterminate{0%{left:-36%}50%{left:58%}100%{left:105%}}\n .native-progress-info{font:11px monospace;color:#a5d5e2;margin:8px 0;display:flex;justify-content:space-between;gap:9px}\n .native-progress-info strong{font-weight:500;color:#d8f9ff}\n #nativeScanHud{position:fixed;left:50%;transform:translateX(-50%);bottom:37px;z-index:550;\n background:#152c3b;border:1px solid #537588;border-radius:8px;box-shadow:0 6px 20px #000a;\n padding:9px 13px;width:min(470px,90vw)}\n #nativeScanHud[hidden]{display:none}\n .native-result{display:flex;align-items:center;gap:7px;background:#10222c;border:1px solid #314d5c;\n border-radius:6px;padding:9px 11px;margin:5px 0}\n .native-result span{flex:1;min-width:0}\n .native-result b{display:block;font-weight:500;color:#d6edf7;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n .native-result small{display:block;color:#88aaba;font-size:10px;margin-top:4px}\n .native-search{font-family:inherit!important}\n"; + css.textContent += "\n .native-insert-row{display:flex;align-items:center;gap:2px;width:100%;min-width:0}\n .native-insert-row>.insert{flex:1;min-width:0;text-align:left;overflow:hidden;\n text-overflow:ellipsis;white-space:nowrap;padding-left:4px;padding-right:1px}\n .native-insert-row>.native-power{flex:0 0 21px;width:21px;height:21px;\n font-size:14px;line-height:18px;text-align:center;border-radius:3px;\n border:1px solid #3b6973;color:#8becb3;cursor:pointer;padding:0;\n background:linear-gradient(#385e65,#102c30);box-shadow:inset 0 1px #91e8bd44}\n .native-insert-row>.native-power.is-off{color:#8b9ca5;border-color:#53616a;\n background:linear-gradient(#39414a,#171e27);box-shadow:none}\n .native-insert-row>.native-power:focus-visible{outline:2px solid #4dd7ff}\n .native-insert-row.is-bypassed>.insert{opacity:.54;filter:saturate(.55)}\n .native-engine .strip[data-preview=\"1\"] .meter-fill{opacity:0!important}\n .native-engine .strip[data-preview=\"1\"] .meter{opacity:.36}\n .native-engine .meter-fill{transition:height 90ms linear}\n "; + document.head.appendChild(css); + const footer = document.querySelector(".status-help"); + if(footer) footer.innerHTML = `
+ + + + LIVE AUDIO AUTO-ROUTED + Starting native audio... +
`; + + const workspace = document.querySelector("#rackWorkspace"); + const mixer = document.querySelector("#mixer"); + const currentTab = () => document.querySelector(".nav button.selected")?.dataset.view; + const fxCategories = ["All","Dynamics","EQ","Delay","Reverb","Other"]; + const classFor = item => { + const s = (item.category+" "+item.name).toLowerCase(); + if(/compress|limit|gate|dynam|de.?ess/.test(s)) return "Dynamics"; + if(/eq|equal|filter/.test(s)) return "EQ"; + if(/delay|echo/.test(s)) return "Delay"; + if(/verb|room|hall/.test(s)) return "Reverb"; + return "Other"; + }; + function cardHeader(title,subtitle) { + return `
AR MIX · NATIVE VST3 ENGINE +

${escapeHtml(title)}

${escapeHtml(subtitle)}
`; + } + function renderRack(){ + if(!workspace || currentTab()!=="FX RACK") return; + workspace.innerHTML=`
+ ${cardHeader("Live FX Chain · Vocal Input","Arrange your real VST3 effects here. Use + ADD FX to choose from your installed catalog.")} +
+ + + + ${state.chain.length}/8 live effects · Real-time processor chain (Channel 1) +
+
+

MIC INPUT → PROCESSING → MAIN OUTPUT

+
+
INPUT 1 / MICROPHONE
+ ${state.chain.map((p,i)=>`
+ ${String(i+1).padStart(2,"0")} + ${escapeHtml(p.name)}${p.latency||0} samples processing latency + + + + + +
`).join("")} + ${state.chain.length===0?'
No FX loaded yet · Click + ADD FX to insert a real VST3.
':""} + +
MASTER OUTPUT / STREAM
+
+
+

Bypass can change without stopping the audio callback. Live chain edits briefly restart processing; avoid editing FX while performing. Bypass is real-time safe.

+
`; +} + function createDialog(id,title,small=false){ + let overlay=document.getElementById(id); + if(overlay)return overlay; + overlay=document.createElement("div");overlay.id=id;overlay.className="native-modal";overlay.hidden=true; + overlay.innerHTML=``; + document.body.appendChild(overlay); + return overlay; +} + function showDialog(id){const d=document.getElementById(id);if(d){d.hidden=false;d.querySelector("input")?.focus()}} + function hideDialog(id){const d=document.getElementById(id);if(d)d.hidden=true} + function pluginRows(items,limit=180){ + return items.length?items.slice(0,limit).map(p=>`
+ ${escapeHtml(p.name)} + ${escapeHtml(p.vendor||"Unknown vendor")} · ${escapeHtml(p.category||"Audio effect")} + VST3 +
`).join("") + :'
No matching installed VST3 effects. Open Plugin Manager to scan your folders.
'; +} + function filterPlugins(){ + return state.catalog.filter(p=>state.selectedCategory==="All"||classFor(p)===state.selectedCategory) + .filter(p=>(p.name+" "+p.vendor+" "+p.category).toLowerCase().includes(state.filter.toLowerCase())); +} + function renderPicker(){ + const dlg=document.getElementById("nativeFxSelector"); + if(!dlg)return; + dlg.querySelector(".native-dialog-body").innerHTML=` +
SELECT EFFECT → INSERT INTO LIVE VOCAL FX RACK
+ +
${fxCategories.map(c=>``).join("")}
+
+ ${state.adding?`Loading ${escapeHtml(state.pendingPlugin)}… + Initializing VST3; this may take a moment.`: + state.addError?`FX NOT LOADED: ${escapeHtml(state.addError)} +
Open PLUGINS to rescan or SIGNAL CHECK for diagnostic logs.
`:""} +
+
${pluginRows(filterPlugins())}
`; + dlg.querySelector(".native-dialog-footer").innerHTML=`${state.catalog.length} available plugins · OPEN PLUGIN MANAGER for scanning and import`; +} + function openPicker(){renderPicker();showDialog("nativeFxSelector")} + function scanProgressHtml(){ + const p=state.progress||{}; + const count=p.done||0,total=p.total||0,found=p.found||0; + const known=p.phase==="inspecting"&&total>0; + const percentage=known?Math.round(count/total*100):null; + return `
${p.phase==="discovering"?"Discovering plugin files": + p.phase==="inspecting"?"Inspecting VST3 metadata":"Scan completed"} + ${known?`${count} / ${total} · ${percentage}%`:"Working…"}
+
+
${escapeHtml(p.current||"")}${found} effects found
`; +} + function renderManager(){ + const dlg=document.getElementById("nativePluginManager"); + if(!dlg)return; + dlg.querySelector(".native-dialog-body").innerHTML=` +
MANAGE INSTALLED VST3 PLUGINS · SCANNING RUNS OFF THE AUDIO CALLBACK
+
+ + + +
+
+

${state.scanning?"SCANNING PLUGINS":"PLUGIN SCANNER"}

+
${state.scanning?scanProgressHtml(): + `
${escapeHtml(state.message)} · ${state.catalog.length} cached effects
`}
+
+
Plugin catalog (${state.catalog.length}) — stored between launches
+
${state.catalog.length? + state.catalog.slice(0,120).map(p=>`
${escapeHtml(p.name)} + ${escapeHtml(p.vendor||"Unknown")} · ${escapeHtml(p.path)}
`).join("") + :'
No plugins indexed yet. Scan your standard folders or import a .vst3 file.
'}
`; + dlg.querySelector(".native-dialog-footer").textContent= + "VST2 DLL is not VST3. Scanning third-party binaries is not yet crash-isolated."; +} + function updateProgress(){ + const p=state.progress||{}; + const hud=document.getElementById("nativeScanHud"); + hud.hidden=!p.active; + if(p.active)hud.innerHTML=`
VST3 SCANNING · ${state.catalog.length} cached effects
${scanProgressHtml()}`; + const mgr=document.getElementById("nativePluginManager"); + if(mgr&&!mgr.hidden){ + const host=mgr.querySelector("#nativeManagerProgress"); + if(host)host.innerHTML=p.active?scanProgressHtml():`
${escapeHtml(state.message)}
`; + } +} + function addPluginManagerToolbar(){ + const nav=document.querySelector(".nav"); + if(nav&&!nav.querySelector("[data-plugin-manager]")){ + const b=document.createElement("button"); + b.dataset.pluginManager="1"; + b.textContent="PLUGINS"; + b.title="Plugin Manager · VST3 scan and catalog administration"; + nav.appendChild(b); + } + } + function renderMySounds(){ + const dlg=document.getElementById("nativeMySounds"); + if(!dlg)return; + const muted=!state.monitor; + dlg.querySelector(".native-dialog-body").innerHTML=` +
+ Native .armix presets save the REAL VST3 binary settings, insert order, + bypass, Channel 1 fader/PAN/mute and master. Other demo channels are NOT included. + Devices and output routing are never changed by recall. +
+
+ ${muted?"OUTPUT MUTED · Save and recall available." + :"LIVE OUTPUT ACTIVE · Recall uses a short de-click fade. Mute before SAVE."} + ${muted?"":''} +
+
+ + +
+
SAVED NATIVE SOUNDS · ${state.presets.length}
+
${state.presets.length? + state.presets.map(n=>`
+ ${escapeHtml(n)}.armix · full vendor VST3 state + +
`).join("") : + '
No native sounds saved. Mute output, then save the current live FX chain.
'} +
`; + dlg.querySelector(".native-dialog-footer").textContent= + "Live recall: prepared VST3 chain switches at a callback boundary with a brief fade-down/up (not dual-graph seamless). SAVE requires mute. Output routing is unchanged."; + } + function openMySounds(){ + renderMySounds(); + showDialog("nativeMySounds"); + send("presetList"); + } + function initModals(){ + createDialog("nativeFxSelector","Add VST3 Effect"); + createDialog("nativeMySounds","My Sounds · Native Presets",true); + createDialog("nativePluginManager","Plugin Manager"); + createDialog("nativeAudioSetup","Opening Audio Setup",true); + const setup=document.getElementById("nativeAudioSetup"); + setup.querySelector(".native-dialog-body").innerHTML=`

Preparing ASIO/WASAPI driver configuration…

+
+

Third-party ASIO drivers may require additional enumeration time.

`; + setup.querySelector(".native-dialog-footer").textContent="Audio processing remains independent of this window."; + const hud=document.createElement("div");hud.id="nativeScanHud";hud.hidden=true;document.body.appendChild(hud); +} + function renderSetup() { + if(!workspace||currentTab()!=="SETUP") return; + workspace.dataset.nativeSetup="1"; + const d=state.device; + workspace.innerHTML = `
+ ${cardHeader("Windows Audio Setup","Select your ASIO or WASAPI input and output using the native JUCE device selector. Settings are retained after restart.")} +
+

ACTIVE AUDIO DEVICE

+

Driver: ${escapeHtml(d.driver||"Not connected")}
Device: ${escapeHtml(d.device||"Not selected")}
Sample rate: ${Number(d.rate||0).toLocaleString()} Hz · Buffer: ${d.buffer||0} samples

+
+ + +
+

For first test: wired headphones, 48 kHz and 128/256 samples. Start MONITOR OFF. ASIO and WASAPI are not interchangeable with virtual streaming outputs; loopback routing is a separate feature.

+
+
`; + } + function patchMixer(){ + if(!mixer)return; + const tracks=mixer.querySelectorAll(".strip"); + tracks.forEach((track,i)=>{ + const rack=track.querySelector(".rack"); + if(!rack)return; + if(track.classList.contains("master-strip")){ + track.dataset.preview="1"; + track.title="Master FX and master PAN are visual previews; Master fader and meters are native"; + track.querySelectorAll("[data-master-insert],[data-master-power]").forEach(x=>{ + x.disabled=true;x.title="Preview only — Master FX DSP not yet implemented"; + }); + const pan=track.querySelector('[data-pan="master"]'); + if(pan){pan.removeAttribute("tabindex");pan.style.pointerEvents="none";pan.title="Master PAN DSP not yet implemented";} + const marker=track.querySelector(".master-info-kicker span"); + if(marker)marker.textContent="NATIVE PEAKS"; + return; + } + if(i!==0){ + rack.dataset.preview="1"; + track.dataset.preview="1"; + track.querySelectorAll(".meter-peak").forEach(x=>x.style.display="none"); + track.title=`${track.querySelector(".strip-name")?.textContent?.trim()||"Channel"} — visual preview only; native I/O not wired`; + return; + } + const signature=state.chain.map(p=>p.id+"|"+p.bypass).join(","); + if(rack.dataset.nativeSig===signature)return; + rack.dataset.nativeSig=signature; + rack.innerHTML=state.chain.slice(0,5).map((p,i)=> + `
+ + +
`).join("")+ + `
`; + }); +} + let renderPending = false; + function syncView(){ + if(renderPending) return; + renderPending=true; + queueMicrotask(()=>{ + renderPending=false; + if(currentTab()==="FX RACK"){ + if(workspace.firstElementChild?.dataset.liveNative!=="1")renderRack(); + } else if(currentTab()==="SETUP"){ + if(workspace.firstElementChild?.dataset.nativeSetup!=="1")renderSetup(); + } + patchMixer(); + }); + } + new MutationObserver(()=>syncView()).observe(workspace,{childList:true}); + new MutationObserver(()=>syncView()).observe(mixer,{childList:true}); + const repaint=()=>{ + if(currentTab()==="FX RACK") renderRack(); + if(currentTab()==="SETUP") renderSetup(); + patchMixer(); + }; + + // Capture native controls before the legacy v0.3 demo handlers. + document.addEventListener("click", function(e){ + const el=e.target.closest("[data-native-action],[data-native-add],[data-native-fx],[data-fxpower],[data-master-insert],[data-master-power],[data-native-category],[data-go-native-rack],[data-insert],[data-plugin-picker],[data-plugin-manager],[data-my-sounds],[data-preset-mute],[data-preset-save],[data-preset-load],[data-close-modal]"); + if(!el)return; + e.preventDefault();e.stopImmediatePropagation(); + + if(el.dataset.closeModal){hideDialog(el.dataset.closeModal);return;} + if(el.hasAttribute("data-master-insert")||el.hasAttribute("data-master-power")){ + toStatus("Master FX is a visual preview; real processing is Channel 1.");return; + } + if(el.hasAttribute("data-fxpower")){ + const [channel,slot]=el.dataset.fxpower.split(":").map(Number); + if(channel===0)send("fxBypass",{slot,value:!state.chain[slot]?.bypass}); + else toStatus("Visual preview only. Native FX available on Channel 1."); + return; + } + if(el.hasAttribute("data-my-sounds")){openMySounds();return;} + if(el.hasAttribute("data-preset-mute")){ + send("monitor",{value:false});state.monitor=false;renderMySounds();return; + } + if(el.hasAttribute("data-preset-save")){ + const input=document.getElementById("nativePresetName"); + const name=(input?.value||"").trim(); + if(!name)return; + input.disabled=true; + requestAnimationFrame(()=>requestAnimationFrame(()=>{ + send("presetSave",{name}); + input.disabled=false; + })); + return; + } + if(el.hasAttribute("data-preset-load")){ + const name=el.dataset.presetLoad; + if(!name)return; + if(!confirm('Recall native sound "'+name+'"? The mixer will use a short de-click fade when switching FX chains.'))return; + const notice=document.querySelector("#nativeMySounds .native-status"); + if(notice)notice.textContent="Preparing new VST3 instances and binary states. Live audio remains on the current graph until the new plan is ready…"; + requestAnimationFrame(()=>requestAnimationFrame(()=>send("presetLoad",{name}))); + return; + } + if(el.hasAttribute("data-plugin-manager")){ + renderManager();showDialog("nativePluginManager");return; + } + if(el.hasAttribute("data-plugin-picker")){ + openPicker();return; + } + if(el.hasAttribute("data-insert")){ + const article=el.closest(".strip"); + const idx=Number(article?.dataset.strip??0); + if(idx!==0){ + const toast=document.querySelector("#toast"); + if(toast){toast.textContent="Native VST3 is currently available on Channel 1 only.";toast.classList.add("show"); + setTimeout(()=>toast.classList.remove("show"),2200);} + return; + } + openPicker();return; + } + if(el.hasAttribute("data-go-native-rack")){ + document.querySelector('.nav button[data-view="FX RACK"]')?.click();return; + } + const action=el.dataset.nativeAction; + if(action){ + if(action==="monitor"){send("monitor",{value:!state.monitor});return;} + if(action==="audioSetup"){ + const overlay=document.getElementById("nativeAudioSetup"); + if(overlay){ + overlay.querySelector(".native-dialog-body").innerHTML= + `

Preparing ASIO/WASAPI device selection…

+
+

Loading device options. Third-party driver enumeration may be slow.

`; + showDialog("nativeAudioSetup"); + } + // Allow WebView to paint before synchronous JUCE/ASIO enumeration begins. + requestAnimationFrame(()=>requestAnimationFrame(()=>send("audioSetup"))); + return; + } + send(action);return; + } + if(el.dataset.nativeAdd){ + if(state.adding)return; + const id=el.dataset.nativeAdd; + const chosen=state.catalog.find(p=>p.id===id); + state.adding=true; + state.addError=""; + state.pendingPlugin=chosen?.name||"selected effect"; + const requestId=++state.addRequestId; + const progress=document.getElementById("nativeAddFeedback"); + if(progress){ + progress.style.display=""; + progress.className="native-add-feedback waiting"; + progress.textContent="Loading "+state.pendingPlugin+"… Initializing VST3."; + progress.setAttribute("aria-busy","true"); + } + document.querySelectorAll("#nativeFxSelector [data-native-add]") + .forEach(b=>b.disabled=true); + // Let the WebView paint before the synchronous plugin factory call. + requestAnimationFrame(()=>requestAnimationFrame(()=>send("addCatalog",{id,requestId}))); + return; + } + if(el.dataset.nativeCategory){ + state.selectedCategory=el.dataset.nativeCategory; + renderPicker();return; + } + const fx=el.dataset.nativeFx,slot=Number(el.dataset.slot); + if(fx==="editor")send("fxEditor",{slot}); + if(fx==="remove")send("fxRemove",{slot}); + if(fx==="bypass")send("fxBypass",{slot,value:!state.chain[slot]?.bypass}); + if(fx==="up"||fx==="down")send("fxMove",{slot,value:fx==="up"?-1:1}); +},true); + document.addEventListener("input", function(e){ + if(e.target.id!=="nativeVstSearch")return; + state.filter=e.target.value; + const pos=e.target.selectionStart; + renderPicker(); + const input=document.querySelector("#nativeVstSearch"); + input?.focus(); + input?.setSelectionRange(pos,pos); +},true); + + backend.addEventListener("arMixPresets",items=>{ + state.presets=Array.isArray(items)?items:[]; + const dialog=document.getElementById("nativeMySounds"); + if(dialog&&!dialog.hidden){ + const previous=dialog.querySelector("#nativePresetName")?.value||""; + renderMySounds(); + const input=dialog.querySelector("#nativePresetName"); + if(input)input.value=previous; + } + }); + backend.addEventListener("arMixNativePresetLoaded",d=>{ + // Synchronize the real mixer controls. Do not apply the legacy localStorage + // demo presets as an authoritative source for DSP. + if(typeof channels!=="undefined" && channels[0]){ + channels[0].fader=Number(d.channelDb)||0; + channels[0].pan=Math.round(Number(d.pan)||0); + channels[0].mute=!!d.channelMute; + if(typeof masterGain!=="undefined")masterGain=Number(d.masterDb)||0; + if(typeof masterMute!=="undefined")masterMute=!!d.masterMute; + if(typeof renderMixer==="function")renderMixer(); + if(typeof renderMaster==="function")renderMaster(); + patchMixer(); + } + hideDialog("nativeMySounds"); + }); + backend.addEventListener("arMixCatalog",data=>{ + state.catalog=Array.isArray(data.items)?data.items:[]; + state.scanning=!!data.scanning; + state.message=data.message||"Ready"; + repaint(); + const dialog=document.getElementById("nativePluginManager"); + if(dialog&&!dialog.hidden)renderManager(); + const picker=document.getElementById("nativeFxSelector"); + if(picker&&!picker.hidden)renderPicker(); + updateProgress(); + }); + backend.addEventListener("arMixChain",nodes=>{ + state.chain=Array.isArray(nodes)?nodes:[]; + repaint(); + const picker=document.getElementById("nativeFxSelector"); + if(picker&&!picker.hidden)renderPicker(); + }); + backend.addEventListener("arMixAddResult",result=>{ + if(Number(result.requestId)!==state.addRequestId)return; + state.adding=false; + state.pendingPlugin=""; + state.addError=result.ok?"":String(result.error||"Unknown VST3 loading failure"); + if(result.ok)hideDialog("nativeFxSelector"); + else{ + // Keep error in the open modal; toast behind backdrop is insufficient. + renderPicker(); + document.getElementById("nativeAddFeedback")?.setAttribute("aria-busy","false"); + } + }); + backend.addEventListener("arMixNotice",data=>{ + const text=data.text||""; + const toast=document.querySelector("#toast"); + if(toast){ + toast.textContent=text; + toast.classList.add("show"); + setTimeout(()=>toast.classList.remove("show"),3500); + } + if(data.error)console.warn("AR MIX native:",text); + }); + let liveInputLevel=0, liveOutputLevel=0, liveOutputLeft=0, liveOutputRight=0; + let lastSetupSignature=""; + backend.addEventListener("arMixStatus",d=>{ + state.device=d; + state.monitor=!!d.monitor; + const b=document.querySelector('[data-native-action="monitor"]'); + if(b){b.textContent=state.monitor?"MUTE OUTPUT":"UNMUTE OUTPUT";b.classList.toggle("on",!state.monitor);} + const text=d.error?"AUDIO ERROR: "+d.error: + d.connected?`${d.driver} · ${Math.round(d.rate)} Hz / ${d.buffer} · ${state.chain.length} LIVE VST3 · ${d.latencySamples||0} samples FX latency` + :"NO AUDIO DEVICE · SELECT AUDIO SETUP"; + toStatus(text); + // Only CH1 and master are sourced from a real native audio callback. + const inputLevel=percent(d.inputPeak), outputLevel=percent(d.peak); + // Real left/right peaks reflect PAN. Fast attack, capped 12-Hz UI release. + liveInputLevel=Math.max(inputLevel,liveInputLevel-5); + liveOutputLevel=Math.max(outputLevel,liveOutputLevel-5); + liveOutputLeft=Math.max(percent(d.peakLeft),liveOutputLeft-5); + liveOutputRight=Math.max(percent(d.peakRight),liveOutputRight-5); + const meter=document.querySelector('[data-meter="0"]'); + if(meter)meter.style.setProperty("--level",liveInputLevel+"%"); + for(const [key,level] of [["masterL",liveOutputLeft],["masterR",liveOutputRight]]){ + const target=document.querySelector('[data-meter="'+key+'"]')|| + document.getElementById(key==="masterL"?"masterMeterL":"masterMeterR"); + if(target)target.style.setProperty("--level",level+"%"); + } + const aux=document.getElementById("masterMeterAux"); + if(aux)aux.style.setProperty("--level",liveOutputLevel+"%"); + // Design-only LUFS/true-peak fields have no native measurement yet. + const lufs=document.getElementById("masterLufs"),tp=document.getElementById("masterDbtp"); + if(lufs)lufs.textContent="—"; + if(tp)tp.textContent="—"; + // v0.8 Master stream LUFS-I/dBTP remains unimplemented; values stay + // em dashes rather than falsely claiming measured loudness. + const pk=document.getElementById("masterPeakDb"); + if(pk)pk.textContent=Number(d.peak)>0 + ?(20*Math.log10(Math.max(1e-8,Number(d.peak)))).toFixed(1)+" dBFS":"−∞"; + const cpu=document.querySelector(".cpu strong"); + if(cpu)cpu.textContent="NATIVE"; + const statusSetup=document.querySelector("[data-native-setup]"); + const setupSignature=[d.connected,d.driver,d.device,d.rate,d.buffer,d.error||""].join("|"); + if(statusSetup && setupSignature!==lastSetupSignature && !document.activeElement?.matches("input")){ + lastSetupSignature=setupSignature; + renderSetup(); + } + }); + backend.addEventListener("arMixScanProgress",p=>{ + state.progress=p; + updateProgress(); + }); + backend.addEventListener("arMixSetupProgress",p=>{ + const dlg=document.getElementById("nativeAudioSetup"); + if(!dlg)return; + if(p.phase==="opened"){ + const body=dlg.querySelector(".native-dialog-body"); + body.innerHTML=`

Audio Device Settings opened in a separate window.

Setup initialization: ${Number(p.elapsedMs)||0} ms.

`; + setTimeout(()=>hideDialog("nativeAudioSetup"),700); + }else{ + const info=dlg.querySelector(".native-dialog-body p"); + if(info) info.textContent=p.phase==="enumerating"?"Enumerating ASIO/WASAPI devices and drivers…":"Preparing audio device selector…"; + } + }); + // Create real dialogs and synchronize cached state after WebView startup. + initModals(); + addPluginManagerToolbar(); + send("refreshState"); + syncView(); +})(); diff --git a/web/index.html b/web/index.html index c07866cf2..41137defd 100644 --- a/web/index.html +++ b/web/index.html @@ -39,5 +39,5 @@
UI STUDY · Audio engine disconnected · Simulated metersDrag faders and PAN sliders • Click FX insert to open plugin browser • Ctrl+S saves sessionArSonMix | FX HOST UI PROTOTYPE
- + diff --git a/web/monitor.js b/web/monitor.js new file mode 100644 index 000000000..4b24205ca --- /dev/null +++ b/web/monitor.js @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Native output diagnostics: JS control only, never audio callback work. +(() => { + const api = window.__JUCE__?.backend; + if (!api?.emitEvent || !api?.addEventListener) return; + let state = {}; + const css = document.createElement("style"); + css.textContent = "#arSignalOverlay{display:none;position:fixed;inset:0;z-index:990;background:#020a10d9;align-items:center;justify-content:center}" + + "#arSignalOverlay.open{display:flex}.arSignalPanel{width:min(710px,93vw);padding:16px;background:linear-gradient(#263d4b,#10212c 80%);border:1px solid #6a92a5;border-radius:9px;color:#d9eaf3;box-shadow:0 15px 55px #000c}" + + ".arSignalHeader{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px}.arSignalHeader h2{font-size:18px;font-weight:500;margin:0}" + + ".arSignalGrid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:9px}.arSignalStage{padding:10px;background:#0d202b;border:1px solid #365565;border-radius:6px;min-width:0}" + + ".arSignalStage small{display:block;color:#80d4e8;font-size:10px}.arSignalStage b{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;font-size:11px;margin:10px 0}" + + ".arSignalMeter{background:#041019;height:9px;border:1px solid #37576a;border-radius:4px;overflow:hidden}.arSignalMeter i{display:block;width:1%;height:100%;background:linear-gradient(90deg,#14bbaa,#b6d851,#edac38)}" + + "#arSignalReason{font-size:12px;line-height:1.6;padding:12px;background:#1c3645;border:1px solid #4d7284;border-radius:5px;margin:13px 0}" + + ".arSignalActions{display:flex;flex-wrap:wrap;gap:8px}.arSignalActions button,.arSignalHeader button{color:#e0f5ff;padding:8px 12px;border:1px solid #57849a;border-radius:4px;background:linear-gradient(#395b70,#143447);cursor:pointer}" + + "#arSignalFooter{margin-top:12px;font-size:11px;color:#9bbbbf;line-height:1.6}#arSignalBadge{color:#edbf7d;font-size:10px;margin-left:6px;white-space:nowrap}" + + "#arSignalOpen{padding:4px 7px;font-size:10px}"; + document.head.appendChild(css); + const footer = document.querySelector("#nativeP2"); + if (footer) footer.insertAdjacentHTML("beforeend", + 'OUTPUT DISARMED'); + const overlay = document.createElement("div"); + overlay.id = "arSignalOverlay"; + overlay.innerHTML = ''; + document.body.appendChild(overlay); + const el = id => document.getElementById(id); + const percent = v => Math.max(1,Math.min(100,(20*Math.log10(Math.max(1e-6,Number(v)||0))+60)*100/60)); + function diagnosis(d) { + if (d.error) return "Audio driver error: "+d.error; + if (!d.connected) return "No audio device connected. Open AUDIO SETUP."; + if (!d.deviceOutputChannels) return "No active output channels. Select a headphone/speaker output in AUDIO SETUP."; + if (!d.monitor) return "OUTPUT MUTED by user. Audio routes automatically after a working input/output device is selected."; + if (d.masterMute) return "MASTER MUTED: switch off the master MUTE button."; + if (d.channelMute) return "CHANNEL 1 MUTED: switch off Lead Vocal MUTE."; + if ((d.inputPeak||0)>.006 && (d.postFxPeak||0)<.0002) return "Mic input is detected but VST3 output is silent. Enable DRY TEST to bypass all plugins."; + if ((d.postFxPeak||0)>.003 && (d.peak||0)<.0002) return "Post-FX audio exists, but hardware output is silent. Check faders, mutes and output settings."; + if ((d.peak||0)>.003) return "Samples reach the output buffer. If you cannot hear them, check your interface mixer, physical output selection and headphone volume."; + if ((d.inputPeak||0)<.0005) return "Microphone signal is low/absent. Check the selected ASIO/WASAPI input and gain."; + return "Output armed. Speak into the microphone and inspect all three meters."; + } + function repaint(d) { + el("arSignalBadge").textContent = !d.monitor ? "OUTPUT MUTED" : d.masterMute ? "MASTER MUTED" : d.channelMute ? "CH1 MUTED" : "OUTPUT ARMED"; + el("arSignalBadge").style.color = d.monitor && !d.masterMute && !d.channelMute ? "#71e9cc" : "#e9be7c"; + const monitorButton=document.querySelector('[data-native-action="monitor"]'); + if (monitorButton) monitorButton.textContent=d.monitor?"MUTE OUTPUT":"UNMUTE OUTPUT"; + // The original UI shell had fixed 48 kHz / 64-sample demo badges. Show + // the REAL negotiated driver parameters instead of misleading the user. + const rateLabel=document.querySelector('.spec:not(.spec-device):not(.bpm) strong'); + if(rateLabel)rateLabel.textContent=d.rate?String(Math.round(d.rate/1000)):"—"; + const bufferLabel=document.querySelector('.spec.bpm strong'); + if(bufferLabel)bufferLabel.textContent=d.buffer?String(d.buffer):"—"; + const driverLabel=document.querySelector('.spec-device strong'); + if(driverLabel)driverLabel.textContent=d.driver||"NO DRIVER"; + const liveLabel=document.querySelector('.status > span:first-child > b'); + if(liveLabel)liveLabel.textContent="NATIVE CH1"; + const edition=document.querySelector('.status > span:last-child'); + if(edition)edition.textContent="AR MIX P2 · CH1 NATIVE + UI PREVIEW"; + if (!overlay.classList.contains("open")) return; + el("arInputName").textContent=d.inputDevice||"Input device"; + el("arFxName").textContent=d.dryTest?"DRY BYPASS":"VST3 Chain"; + el("arOutputName").textContent=d.outputDevice||"Output device"; + el("arInputBar").style.width=percent(d.inputPeak)+"%"; + el("arFxBar").style.width=percent(d.postFxPeak)+"%"; + el("arOutputBar").style.width=percent(d.peak)+"%"; + el("arSignalReason").textContent=diagnosis(d); + el("arSignalMonitor").textContent=d.monitor?"MUTE OUTPUT":"UNMUTE OUTPUT"; + el("arSignalDry").textContent=d.dryTest?"DRY TEST ON":"DRY TEST OFF"; + el("arHealthPanel").textContent="CALLBACK "+(d.callbackDurationUs||0)+" µs / period "+ + Math.round(d.periodUs||0)+" µs | Worst "+(d.worstCallbackUs||0)+ + " µs | Over-budget "+(d.overBudgetCount||0)+ + " | Long gaps "+(d.callbackGapCount||0)+ + " | Worst VST "+(d.worstPluginUs||0)+" µs"+ + " | device starts/stops "+(d.deviceStartCount||0)+"/"+(d.deviceStopCount||0)+ + " (timing indicators, NOT confirmed driver xruns)"; + const timing=Array.isArray(d.pluginTimings)?d.pluginTimings:[]; + const fxInfo=timing.map(x=>x.slot+". "+x.name+": "+x.lastUs+" µs now, worst "+x.worstUs+" µs").join(" | "); + if(fxInfo)el("arHealthPanel").textContent+=" | FX: "+fxInfo; + el("arSignalFooter").textContent=(d.driver||"Audio")+" · "+(d.rate||0)+" Hz / "+(d.buffer||0)+ + " samples · "+(d.deviceInputChannels||0)+" active input / "+(d.deviceOutputChannels||0)+" active output channels · "+ + (d.latencySamples||0)+" samples plugin latency. Choose hardware output using AUDIO SETUP; Main L/R and Streaming are UI previews."; + } + api.addEventListener("arMixStatus",d=>{state=d;repaint(d);}); + el("arSignalOpen")?.addEventListener("click",()=>{overlay.classList.add("open");repaint(state);}); + el("arSignalClose").addEventListener("click",()=>overlay.classList.remove("open")); + el("arSignalMonitor").addEventListener("click",()=>api.emitEvent("arMixAction",{action:"monitor",value:!state.monitor})); + el("arSignalDry").addEventListener("click",()=>api.emitEvent("arMixAction",{action:"dryTest",value:!state.dryTest})); + el("arSignalLogs").addEventListener("click",()=>api.emitEvent("arMixAction",{action:"openDiagnostics"})); + el("arSignalSetup").addEventListener("click",()=>{ + overlay.classList.remove("open"); + document.querySelector('[data-native-action="audioSetup"]')?.click(); + }); + overlay.addEventListener("click",e=>{if(e.target===overlay)overlay.classList.remove("open");}); + document.addEventListener("click",e=>{ + if(!e.target.closest("[data-output],#monitorSource"))return; + e.preventDefault();e.stopImmediatePropagation(); + overlay.classList.add("open");repaint(state); + },true); +})(); diff --git a/web/native-bridge.js b/web/native-bridge.js new file mode 100644 index 000000000..c78ca3bad --- /dev/null +++ b/web/native-bridge.js @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// The standalone HTML still works as a demo. This runs only inside JUCE WebView2. +(() => { + const backend = window.__JUCE__?.backend; + if (!backend?.emitEvent || !backend?.addEventListener) return; + const send = (action, value) => backend.emitEvent("arMixAction", { action, value }); + const target = document.querySelector(".status-help"); + if (!target) return; + const strip = document.createElement("div"); + strip.id = "nativeP1"; + strip.innerHTML = 'Starting audio...'; + target.replaceChildren(strip); + const style = document.createElement("style"); + style.textContent = ` + #nativeP1{display:flex;align-items:center;gap:5px;white-space:nowrap;font-size:10px;max-width:100%;overflow:auto} + #nativeP1 button{font:inherit;color:#cde5ed;border:1px solid #426273;border-radius:4px;padding:4px 7px; + background:linear-gradient(175deg,#42596b 0%,#233745 42%,#101e29 100%);cursor:pointer} + #nativeP1 button[aria-pressed=true]{background:linear-gradient(#24aadd,#10617d 58%,#063247); + border-color:#71d8f2;color:#fff} + #nativeP1 [data-p1-status]{color:#95b9c6;min-width:110px;overflow:hidden;text-overflow:ellipsis} + .status-help{min-width:0;flex:1} + `; + document.head.appendChild(style); + let monitor = false, bypass = false, warned = false; + strip.addEventListener("click", (e) => { + const b = e.target.closest("button[data-p1]"); + if (!b) return; + if (b.dataset.p1 === "setup") send("audioSetup"); + if (b.dataset.p1 === "load") send("chooseVst3"); + if (b.dataset.p1 === "unload") send("unloadVst3"); + if (b.dataset.p1 === "monitor") send("monitor", !monitor); + if (b.dataset.p1 === "bypass") send("bypass", !bypass); + }); + + // Actual output level from the native callback. Remaining mock channels + // are forced dark to avoid implying the P1 host has 12 live audio inputs. + function level(peak) { + const db = 20 * Math.log10(Math.max(1e-6, Number(peak) || 0)); + return Math.max(1, Math.min(100, (db + 60) * 100 / 60)); + } + backend.addEventListener("arMixStatus", (s) => { + monitor = !!s.monitor; + bypass = !!s.bypass; + const mon = strip.querySelector('[data-p1="monitor"]'); + const by = strip.querySelector('[data-p1="bypass"]'); + mon.textContent = monitor ? "MONITOR ON" : "MONITOR OFF"; + mon.setAttribute("aria-pressed", String(monitor)); + by.textContent = bypass ? "BYPASS ON" : "BYPASS OFF"; + by.setAttribute("aria-pressed", String(bypass)); + strip.querySelector("[data-p1-status]").textContent = + s.error ? "ERROR: " + s.error : + (s.connected ? s.driver + " · " + Math.round(s.rate) + "Hz / " + s.buffer + " · " + + (s.plugin || "Dry mic") + " · +" + (s.pluginLatencySamples || 0) + " samples plugin latency" : + "NO AUDIO DEVICE"); + const status = document.getElementById("audioStatus"); + if (status) status.textContent = s.connected + ? "P1 NATIVE · " + (monitor ? "MONITOR ARMED" : "MONITOR MUTED (safe)") + + " · Live VST3: " + (s.plugin || "none") + : "P1 NATIVE · No audio device"; + const p = level(s.peak); + document.querySelectorAll("[data-meter]").forEach((meter) => + meter.style.setProperty("--level", meter.dataset.meter === "0" ? p + "%" : "1%")); + ["masterMeterL","masterMeterR","masterMeterAux"].forEach((id) => { + const el = document.getElementById(id); + if (el) el.style.setProperty("--level", p + "%"); + }); + const cpu = document.querySelector(".cpu strong"); + if (cpu) cpu.textContent = "P1 LIVE"; + if (!warned && s.error) { + warned = true; + console.warn("AR MIX native audio:", s.error); + } + }); +})(); From d3ad468f30d9937ac8577b306774f0b23046bf7b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sun, 25 Oct 2026 13:18:55 +0700 Subject: [PATCH 2/2] test(p25): update stale native contract assertions for prepared graph retirement and callback handoff --- tests/main_v08_native_integration_test.mjs | 2 +- tests/native_preset_contract_test.mjs | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/main_v08_native_integration_test.mjs b/tests/main_v08_native_integration_test.mjs index e109ea9ce..c6755ec8c 100644 --- a/tests/main_v08_native_integration_test.mjs +++ b/tests/main_v08_native_integration_test.mjs @@ -29,7 +29,7 @@ test('no fake oscillating VUs inside native JUCE',()=>{ }); test('native plugin state and graph preserved',()=>{ assert.match(src,/handoff_\.beginCycle\(/); - assert.match(src,/handoff_\.stage\(/); + assert.match(src,/handoff_\.stage \(/); assert.match(bridge,/arMixNativePresetLoaded/); assert.match(bridge,/Master PAN DSP not yet implemented/); assert.match(bridge,/data-fxpower/); diff --git a/tests/native_preset_contract_test.mjs b/tests/native_preset_contract_test.mjs index a3e914803..273aa9a68 100644 --- a/tests/native_preset_contract_test.mjs +++ b/tests/native_preset_contract_test.mjs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-only -// Static guard: the native preset path must never silently fall back to demo -// localStorage or authorize an unmuted VST3 graph mutation. +// Static guard: vendor state comes from native VST3, never browser demo. +// SAVE requires mute; live RECALL uses a staged graph handoff at callback boundaries. import test from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; @@ -11,7 +11,10 @@ test('full vendor state is captured/restored by the native host',()=>{ assert.match(engine,/getStateInformation \(state\.binary\)/); assert.match(engine,/setStateInformation \(/); assert.match(engine,/snapshot\.effects\.push_back/); - assert.match(engine,/auto retired = std::move \(slots_\)/); + assert.match(engine,/stagedOwner_ = std::move \(staged\)/); + assert.match(engine,/handoff_\.stage \(stagedOwner_\.get\(\)\)/); + assert.match(engine,/handoff_\.takeRetired\(\)/); + assert.match(engine,/handoff_\.completeRetirement\(\)/); }); test('ZIP archive does not extract untrusted paths to disk',()=>{ assert.match(io,/juce::ZipFile::Builder/);