diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 0ce438f6c..0c8aa9410 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -26,6 +26,9 @@ on: - 'web/monitor.js' - 'tests/*.cpp' - 'scripts/package_native_windows.ps1' + - 'scripts/build_verify_windows_installer.ps1' + - 'installer/**' + - 'tests/windows_installer_contract_test.mjs' - 'scripts/verify_native_windows_artifact.ps1' - 'scripts/collect_hardware_fat_windows.ps1' - 'scripts/console_v6_fat_gate.mjs' @@ -64,6 +67,9 @@ on: - 'web/monitor.js' - 'tests/*.cpp' - 'scripts/package_native_windows.ps1' + - 'scripts/build_verify_windows_installer.ps1' + - 'installer/**' + - 'tests/windows_installer_contract_test.mjs' - 'scripts/verify_native_windows_artifact.ps1' - 'scripts/collect_hardware_fat_windows.ps1' - 'scripts/console_v6_fat_gate.mjs' @@ -121,7 +127,7 @@ jobs: node scripts/check_console_puzzle.mjs node --check web/approved-native-bridge.js node --check web/approved-native-contract.js - node --test tests/workstream_coordination_contract.test.mjs tests/ci_workflow_efficiency_test.mjs tests/chat_ci_dispatch_contract.test.mjs tests/approved_native_m2_contract.test.cjs tests/native_artifact_packaging_contract_test.mjs tests/live_graph_contract_test.mjs + node --test tests/workstream_coordination_contract.test.mjs tests/ci_workflow_efficiency_test.mjs tests/chat_ci_dispatch_contract.test.mjs tests/approved_native_m2_contract.test.cjs tests/native_artifact_packaging_contract_test.mjs tests/windows_installer_contract_test.mjs tests/live_graph_contract_test.mjs python -m unittest discover -s tests -p approved_native_gui_bundle_test.py -v python -m unittest discover -s scripts/tests -p test_factoryfx_release_bundle.py -v windows-build: @@ -197,6 +203,7 @@ jobs: 'tests/independent_clock_adapter_contract_test.mjs' 'tests/direct_restore_recovery_contract_test.mjs' 'tests/native_artifact_packaging_contract_test.mjs' + 'tests/windows_installer_contract_test.mjs' 'tests/portable_workspace_contract_test.mjs' 'tests/plugin_vault_contract_test.mjs' 'tests/plugin_ui_contract_test.mjs' @@ -217,7 +224,8 @@ jobs: - name: Verify exact ONE approved /preview/ GUI CMake bundle run: node scripts/check_approved_native_gui_release.mjs --source-only --bundle build/approved_gui - name: Build executable and native RT tests - run: cmake --build build --config Release --target ARMixConsole ARMixFactoryFxRegistryTests ARMixFxOrderTests ARMixFxStructuralHandoffTests ARMixMixerRoutingTests ARMixChannelRoutingContractTests ARMixChannelSendTests ARMixPreparedMixerBlockTests ARMixLiveRoutingEpochTests ARMixJucePortMaskTests ARMixNativeMixerSessionTests ARMixNativeDrySendTests ARMixLiveChannelFxTests ARMixDedicatedAuxBusTests ARMixTenChannelLiveControlTests ARMixWorkspaceTests ARMixVaultTests ARMixBackupTests ARMixOrbitPhaseTests ARMixOrbitControlTests ARMixOrbitMotionTests ARMixOrbitDistanceTests ARMixFxBypassEnvelopeTests ARMixDearVrPolarPolicyTests ARMixRTTests ARMixPresetTests ARMixShowSchemaTests ARMixShowStoreTests ARMixLiveShowCaptureTests ARMixNativeMasterLoudnessTests ARMixDiagnosticTests ARMixClockBridgeTests ARMixVirtualClockSoakTests ARMixCadenceTests ARMixCaptureBoundaryTests ARMixCrackleWindowTests ARMixHealthTests ARMixPolicyTests ARMixPeriodEvidenceTests ARMixLifecycleTests ARMixWasapiProbeTests ARMixDualJuceTests ARMixClockSizingTests ARMixIndependentFormatTests ARMixRecoveryTests ARMixStreamWatchdogTests ARMixBridgeContinuityTests ARMixEndpointPolicyTests ARMixEndpointGuardTests ARMixAsioPolicyTests ARMixAsioBackendTests ARMixAsioRegistryIdentityTests ARMixDirectFenceTests --parallel 2 + # Build the default CMake graph so every registered CTest executable is built. + run: cmake --build build --config Release --parallel 2 - name: Test realtime control primitives run: ctest --test-dir build -C Release --output-on-failure - name: Package verified JUCE GUI for hardware FAT @@ -238,6 +246,28 @@ jobs: run: | & ./scripts/verify_native_windows_artifact.ps1 -OutputDir dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Install Inno Setup 6 compiler if missing + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + shell: pwsh + run: | + if (-not (Get-Command ISCC.exe -ErrorAction SilentlyContinue) -and + -not (Test-Path -LiteralPath 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe')) { + choco install innosetup --yes --no-progress --limit-output + if ($LASTEXITCODE -ne 0) { throw 'Inno Setup compiler installation failed' } + } + - name: Compile and validate per-user Windows RC installer from exact FAT PE + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + shell: pwsh + run: | + & ./scripts/build_verify_windows_installer.ps1 -OutputDir dist -InstallerOutput installer-output + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - uses: actions/upload-artifact@v4 + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + with: + name: ArSonMix-Windows-Installer-UNQUALIFIED-${{ github.run_id }} + path: installer-output/ + if-no-files-found: error + retention-days: 14 # Optional manual FAT only: never churn experimental ZIPs per commit. # The unqualified artifact is NOT a stable release or physical audio proof. - uses: actions/upload-artifact@v4 diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 74cd6c9c0..aa5f290eb 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -49,10 +49,15 @@ on: - 'scripts/chat_ci_dispatch.mjs' - 'tests/chat_ci_dispatch_contract.test.mjs' - '.github/workflows/chat-ci-milestone.yml' - # Manually run full Chromium (including immutable historical tests) on a - # specific development branch whenever a milestone needs visual qualification. + # Exact-SHA product qualification covers the CURRENT shipped console. + # Immutable historical migrations are an independent maintenance opt-in. workflow_dispatch: inputs: + historical_css: + description: "Also run archived V8-V27 migration fixtures (CSS maintenance only)" + type: boolean + required: false + default: false expected_sha: description: "Immutable source SHA for ChatGPT milestone" type: string @@ -90,12 +95,14 @@ jobs: node --check web/approved-native-bridge.js node --check web/approved-native-contract.js node --check site/preview-v2/assets/gui-perf-probe.js + node --check site/preview-v2/assets/mixer-native-peq.js + python tests/native_peq_assembly_test.py + python tests/approved_operator_ux_smoke.py python scripts/build_ui_css.py --check python tests/gui_baseline_lock_test.py python tests/brand_icon_contract_test.py python tests/brand_package_files_test.py python tests/css_v28_restore.py - python -m unittest discover -s tests -p approved_operator_ux_smoke.py -v - name: Check native UI contracts, workflow policy, and WIRE without Chromium run: | node --test tests/workstream_coordination_contract.test.mjs tests/chat_ci_dispatch_contract.test.mjs tests/gui_workflow_contract_test.mjs tests/plugin_ui_contract_test.mjs tests/ci_workflow_efficiency_test.mjs tests/fx_drag_reorder_contract_test.mjs tests/mixer_io_operator_contract_test.mjs tests/mixer_shell_contract_test.mjs tests/approved_native_m2_contract.test.cjs @@ -108,6 +115,34 @@ jobs: - name: Block incomplete product release only when preparing product review if: ${{ github.event_name == 'pull_request' && !github.event.pull_request.draft && startsWith(github.head_ref, 'integration/product-') }} run: node scripts/check_console_puzzle.mjs --release + operator-ux-fat: + name: Operator UX real Chromium / native-assembled GUI (5 viewports) + needs: quick + if: ${{ github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Install Chromium for UX FAT + run: | + python -m pip install playwright + python -m playwright install --with-deps chromium + - name: Measure actual layout, close keys, floating move and small-screen scaling + run: | + python tests/approved_operator_ux_chromium_fat.py + python tests/approved_operator_ux_native_identity_smoke.py + - name: Retain rendered evidence across viewport sizes + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ArSonMix-Operator-UX-5-viewports-${{ github.run_id }} + path: operator-ux-*.png + if-no-files-found: ignore + retention-days: 7 + frontend: name: Full Chromium /preview/ visual and interaction qualification # Draft edits are cheap; ChatGPT milestone comments dispatch this full suite. @@ -170,8 +205,22 @@ jobs: run: python tests/approved_native_meter_dirty_stage_b_smoke.py - name: Verify Stage C shipped CSS versus original-source computed and screenshot parity run: python tests/approved_stage_c_css_visual_parity_smoke.py + - name: V29 operator WebView - five geometry sizes, floating controls, and native channel identity + run: | + python tests/approved_operator_ux_chromium_fat.py + python tests/approved_operator_ux_native_identity_smoke.py - name: Check real mobile /preview/ touch toolbar, popup and stray chevrons run: python tests/approved_preview_mobile_navigation_smoke.py + - name: FX rack master bypass preserves each insert state (real Chromium) + run: python tests/approved_fx_rack_master_power_smoke.py + - name: Native FX pointer transfer, delete and editor identity + run: python tests/approved_native_fx_edit_smoke.py + - name: Native EQ real Chromium SVG gestures, ACK, graph and responsive editor + run: python tests/approved_native_peq_smoke.py + - name: Cold start first WIRE and original-channel VST3 picker editor + run: python tests/approved_native_cold_start_smoke.py + - name: Native WIRE gain and OUT share accepted PCM identity (real Chromium) + run: python tests/approved_native_wire_gain_smoke.py - name: Stage D one runtime CSSOM and actual stylesheet network count run: python tests/approved_css_stage_d_single_bundle_smoke.py - name: Stage C rendered CSS parity (original vs compiled, three viewports + hover) @@ -183,7 +232,7 @@ jobs: - name: Verify V53 handle-free FX row drag, keyboard and rack reorder run: python tests/pages_fx_rail_v53_smoke.py - name: Qualify public /preview/ floating Channel Editor with zero mixer reflow (five real Chromium viewports) - run: python tests/approved_operator_ux_chromium_fat.py + run: python tests/approved_operator_ux_chromium_fat.py --public - name: Check public FX rack master bypass preserves individual slot states run: python tests/approved_fx_rack_master_power_smoke.py - name: Verify V54 context-aware WIRE and independent FX chain/slot bypass @@ -215,12 +264,12 @@ jobs: - name: Verify V15 real pointer OUT-to-IN wire and exclusive Bus routing if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/preview_v15_drag_wire_smoke.py - # V10–V24 are exact historical migration/restoration tests. They compare - # original versioned bytes, so run them on immutable V24 rather than - # pretending the intentional V50 layout/stylesheet changes are V22. - # Restore PR files before ALL current GUI/function/geometry smoke tests. + # Archived CSS migrations compare historical bytes, not the current + # shipped mixer. Keep them available for explicit CSS maintenance; do + # not mount old skins during an ordinary live-audio product milestone. + # If requested, restore sources before ALL current product regressions. - name: Mount pinned V24 historical CSS fixture (reversible, no CI rebaseline) - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -233,58 +282,58 @@ jobs: git show "$baseline:$path" > "$path" done - name: Verify V8 FX rack and Plugin Manager CSS ownership - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_ownership_v8_smoke.py - name: Verify V9 PAN/fader/meter CSS ownership and geometry - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_ownership_v9_smoke.py - name: Verify V10 cascade ownership and rendered console geometry - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v10_smoke.py - name: Validate V11 section ownership, cascade and computed visual styles - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v11_smoke.py - name: Verify V12 removed shadow declarations and old/new visual + control parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v12_smoke.py - name: Verify V13 owned CSS conflicts and physical control visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v13_smoke.py - name: Verify V14 canonical 45 material tokens and V13 browser parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v14_smoke.py - name: Verify V15 clean cross-owner CSS and actual interactive visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v15_smoke.py - name: Verify V16 WIRE single CSS owner, 241-rule exact source and visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v16_smoke.py - name: Verify V17 Plugin Manager and Fast FX Picker single CSS owner - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v17_smoke.py - name: Verify V18 physical Chrome ownership and four cascade conflict removals - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v18_smoke.py - name: Verify V19 shared operator key ownership and six shadowed declarations - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v19_smoke.py - name: Verify V20 elimination of 53 shadowed declarations and Chromium state parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v20_smoke.py - name: Verify V21 physical console chassis geometry owner and visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v21_smoke.py - name: Verify V22 legacy key material migration and M3 visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v22_smoke.py - name: Verify V23 exact cascade deletions and browser parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v23_smoke.py - name: Verify V24 Fader/Meter/FX cascade pruning and browser parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v24_smoke.py - name: Restore and verify exact V50 PR assets before current UI smoke - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -297,7 +346,7 @@ jobs: # The V25 historical test is an immutable exact-byte migration gate. # Do not rebaseline it after deliberate V26 dead-rule removals. - name: Mount pinned V25 original CSS before historical V25 migration test - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -310,10 +359,10 @@ jobs: git show "$baseline:$path" > "$path" done - name: Verify V25 exact V51 physical-key owner migration and zero visual regression - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v25_smoke.py - name: Restore and verify current V26 source before latest GUI tests - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -325,7 +374,7 @@ jobs: git diff --exit-code -- site/preview-v2/index.html site/preview-v2/assets/mixer-control-keys.css site/preview-v2/assets/mixer-chrome-material.css site/preview-v2/assets/mixer-plugin-browser.css site/preview-v2/assets/mixer-pan-controls.css site/preview-v2/assets/mixer-fader-assembly.css site/preview-v2/assets/mixer-meter-display.css site/preview-v2/assets/mixer-utility-controls.css # Byte-exact V26 historical CSS check is pinned, not rebaselined. - name: Mount V26 approved source before historical regression - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -338,10 +387,10 @@ jobs: git show "$baseline:$path" > "$path" done - name: Verify V26 retired socket dead rules and exact V25 visual/control parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v26_smoke.py - name: Restore P0 current WIRE source after historical V26 regression - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -354,7 +403,7 @@ jobs: # V27 is a byte-exact historical CSS migration proof; it must run # against its original qualified GUI, never rebaseline a newer FX/rail. - name: Mount pinned V27 GUI and CSS owners for immutable parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -367,10 +416,10 @@ jobs: git show "$baseline:$path" > "$path" done - name: Verify V27 scoped material and 37 owned loser declarations with Chromium parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v27_smoke.py - name: Restore and verify exact V53 current sources after historical V27 - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -458,6 +507,12 @@ jobs: pages-v54-*.png pages-v55-*.png pages-v28-physical-console-owner-v59-*.png + operator-identity-*.png + operator-ux-*.png pages-mobile-*.png + native-wire-gain-*.png + native-cold-start-*.png + native-fx-edit-*.png + native-peq-*.png if-no-files-found: ignore retention-days: 3 diff --git a/AGENTS.md b/AGENTS.md index 94d2458db..b28b6129f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,7 +131,7 @@ with pending physical FAT. Full procedure and edge cases: ## Native architecture and user behavior - Bundle exactly the SAME generated GUI shown at `/preview/` into native WebView2 using a deterministic current-main source/asset provenance; do not hand-copy old mock HTML or duplicate CSS ownership. Thin native adapter may change **data and event authority only**, not GUI appearance or physical interaction. - v8 schemaVersion=6 `arMixConsoleSubscribe`, `Snapshot`, `Intent`, `Ack`; canonical uint64 decimal-string ChannelId/EdgeId/device epochs/graph revisions. Intent accepted only after matching ACK and later accepted same-revision native snapshot. PENDING/REJECTED/STALE/unsupported != LIVE. -- Default CH→MAIN is real graph edge. Display WIRE only for the selected channel; focused MAIN fragments only expanded; collapsed wire quiet; OUT lit only for **custom non-MAIN** outgoing edges. Wire, OUT, IN, Matrix, Navigator, Scene/Undo, FX, fader, PAN, meter derive from native accepted graph/control state. Physical device pin mapping only actual verified ASIO/WASAPI ports; no fake meter/audio/FX in Pages. +- Default CH→MAIN is real graph edge. Display WIRE only for the selected channel; decorative source/master MAIN cable fragments are hidden by owner correction (2026-11-07), while actual MAIN edges and jack controls remain; collapsed wire quiet; OUT lit only for **custom non-MAIN** outgoing edges. Wire, OUT, IN, Matrix, Navigator, Scene/Undo, FX, fader, PAN, meter derive from native accepted graph/control state. Physical device pin mapping only actual verified ASIO/WASAPI ports; no fake meter/audio/FX in Pages. - Structural graph off callback, atomic immutable publication; zero callback locks/heap/UI/VST scanning/disk. Preserve CH1 vendor VST3/Orbit, original 10CH+4AUX, Show/device paths during migration. Never create duplicate routing PCM or special fake CH1; no JS/WebAudio audio engine. - One meaningful vertical milestone: actual compiled Windows EXE displays exact /preview/ skin (including its approved buttons), then real native input→channel→MAIN, meter/fader, VST3 and WIRE intent/ACK/snapshot, then full FAT. Verify 1366×768, 1680×900, 1920×1080 and bank/density/fold states. - `node scripts/check_console_puzzle.mjs --release` must fail on any alternate GUI. No user UAT until a coherent native product; physical rig absent => FAT PENDING, not product ready. @@ -146,3 +146,7 @@ The archival `docs/GUI_BASELINE_LOCK_2026-10-25.md` remains available only for r - [Smart Audio Engine Implementation Blueprint](docs/SMART_AUDIO_ENGINE_IMPLEMENTATION_BLUEPRINT.md) - [Dry physical crackle #15](https://github.com/masarray/arsonmix/issues/15) These remain for device-clock, render-discontinuity and hardware FAT engineering only. Their old GUI v0.8 descriptions do not override the sole **/preview/** GUI. + +## Owner correction: native FX editing (2026-11-07) + +Continue the working #418 ChannelId PCM integration. Vendor editor lifetime follows the actual active processor lease across reorder/transfer; never validate it against inactive M4 slots. FX remove/reorder/cross-channel MOVE must preserve exact instance identity, state and bypass and publish through native ACK/readback. A row-sized pointer ghost is presentation only. The owner explicitly authorized reconciliation and merge of this verified milestone to main; stable-release/physical-FAT claims remain separate. See [P3 evidence](docs/P3_NATIVE_FX_RACK_EDIT_20261107.md). diff --git a/CMakeLists.txt b/CMakeLists.txt index 5f29c3c81..93b73cc51 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9,6 +9,10 @@ endif() add_subdirectory("${JUCE_ROOT}" "${CMAKE_BINARY_DIR}/juce") find_package(Python3 REQUIRED COMPONENTS Interpreter) +# The independent exact-byte verifier must use the SAME Python interpreter +# selected by CMake to generate compressed favicon/PNG resources (Windows +# runners can have several Python versions with different zlib builds). +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/approved-gui-python.txt" "${Python3_EXECUTABLE}\n") set(ARMIX_BRAND_DIR "${CMAKE_CURRENT_BINARY_DIR}/brand_icons") execute_process( COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/generate_brand_icons.py" @@ -33,14 +37,15 @@ juce_add_gui_app(ARMixConsole # The approved operator GUI is generated from the EXACT Pages sources at # configure time. Never compile legacy web/index.html or console-native.html. # User-approved /preview/ iframe uses preview-v2 DOM + PNG-button variant. -find_package(Python3 REQUIRED COMPONENTS Interpreter) set(ARMIX_APPROVED_GUI_DIR "${CMAKE_CURRENT_BINARY_DIR}/approved_gui") file(GLOB_RECURSE ARMIX_APPROVED_GUI_SOURCE_INPUTS CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/site/preview-v2/*" "${CMAKE_CURRENT_SOURCE_DIR}/site/preview-buttons/assets/*") list(APPEND ARMIX_APPROVED_GUI_SOURCE_INPUTS "${CMAKE_CURRENT_SOURCE_DIR}/web/approved-native-bridge.js" - "${CMAKE_CURRENT_SOURCE_DIR}/scripts/build_approved_native_gui.py") + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/build_approved_native_gui.py" + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/build_pages.py" + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/compose_native_peq.py") set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${ARMIX_APPROVED_GUI_SOURCE_INPUTS}) execute_process( COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/build_approved_native_gui.py" @@ -62,6 +67,12 @@ juce_add_binary_data(ARMixAssets SOURCES target_include_directories(ARMixConsole PRIVATE "${ARMIX_APPROVED_GUI_DIR}") target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h src/VstOrbitController.h engine/core/MixerRoutingPlan.h engine/core/ChannelRoutingContract.h engine/core/ChannelSendPlan.h engine/core/AuxBusPlan.h engine/core/PreparedMixerBlock.h engine/core/MasterOutputMonoPolicy.h engine/core/LiveChannelFxGraph.h engine/core/PreparedNativeMixerSession.h engine/core/NativeDryRouteCommand.h engine/core/RealtimeRoutePublisher.h engine/device/LiveInputPortRegistry.h src/LiveDryRoutingLab.h engine/core/OrbitPhase.h engine/core/OrbitControlPolicy.h engine/core/OrbitMotion.h engine/core/OrbitDistanceMapping.h engine/core/DearVrPolarPolicy.h src/PluginCatalog.h src/FactoryFxRegistry.h src/PluginVault.h src/PortableWorkspace.h src/StudioBackup.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/NativeShowSchema.h src/NativeDryShowRecall.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/core/CallbackCadenceEvidence.h engine/diagnostics/CrackleEvidenceWindow.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h engine/device/PeriodCapabilityEvidence.h engine/device/SessionLifecycle.h engine/device/WasapiCapabilityProbe.h engine/device/JuceIndependentClockDevice.h engine/device/LiveSecondaryOutputDevice.h engine/core/LiveOutputRouteGate.h engine/device/ClockBridgeSizing.h engine/device/IndependentStreamFormatFence.h engine/device/DirectRestoreBackoff.h engine/device/IndependentStreamWatchdog.h engine/device/BridgeContinuityGate.h engine/device/EndpointIdentityPolicy.h engine/device/WasapiEndpointIdentityGuard.h engine/device/AsioStartupPolicy.h engine/device/AsioPriorityDeviceManager.h engine/device/JuceActivePortSnapshot.h engine/device/AsioRegistrationPolicy.h engine/device/AsioRegistryIdentityProbe.h engine/device/DirectRouteFence.h) +# Explicit UTF-8 source decoding: native channel icons are Unicode, and +# MSVC's machine-specific ANSI source charset corrupts emoji literals. +# Limit the flag to C++ (not Windows .rc/resource compilation). +if(MSVC) + target_compile_options(ARMixConsole PRIVATE "$<$:/utf-8>") +endif() target_compile_definitions(ARMixConsole PRIVATE JUCE_WEB_BROWSER=1 JUCE_USE_WIN_WEBVIEW2=1 @@ -127,6 +138,16 @@ if(BUILD_TESTING) target_compile_features(ARMixNativeV8ProjectionTests PRIVATE cxx_std_20) add_test(NAME M3BNativeV8StableIdReadbackAndFailClosedProjection COMMAND ARMixNativeV8ProjectionTests) add_dependencies(ARMixMixerRoutingTests ARMixNativeV8ProjectionTests) + juce_add_console_app(ARMixApprovedRoutingPcmTests PRODUCT_NAME "ArSonMix Approved WIRE PCM Tests") + target_sources(ARMixApprovedRoutingPcmTests PRIVATE tests/approved_native_routing_pcm_test.cpp) + target_link_libraries(ARMixApprovedRoutingPcmTests PRIVATE juce::juce_core juce::juce_recommended_config_flags) + target_compile_features(ARMixApprovedRoutingPcmTests PRIVATE cxx_std_20) + add_test(NAME P0ApprovedDecoderChannelToChannelAndSourceOnlyPCM COMMAND ARMixApprovedRoutingPcmTests) + add_dependencies(ARMixMixerRoutingTests ARMixApprovedRoutingPcmTests) + add_executable(ARMixLatencyCompensationTests tests/dynamic_latency_compensation_test.cpp) + target_compile_features(ARMixLatencyCompensationTests PRIVATE cxx_std_20) + add_test(NAME NativeGraphLatencyAlignedFanInAndHardwarePCM COMMAND ARMixLatencyCompensationTests) + add_dependencies(ARMixMixerRoutingTests ARMixLatencyCompensationTests) add_executable(ARMixChannelRoutingContractTests tests/channel_routing_contract_test.cpp) target_compile_features(ARMixChannelRoutingContractTests PRIVATE cxx_std_20) add_test(NAME MonoStereoSparsePhysicalPortRouting COMMAND ARMixChannelRoutingContractTests) @@ -162,6 +183,10 @@ if(BUILD_TESTING) target_link_libraries(ARMixNativeDrySendTests PRIVATE juce::juce_core juce::juce_recommended_config_flags) target_compile_features(ARMixNativeDrySendTests PRIVATE cxx_std_20) add_test(NAME LiveNativePrePostSendAndBusContract COMMAND ARMixNativeDrySendTests) + # Device reopen must not silently replace an authored ChannelId mixer. + add_executable(ARMixDeviceSessionTransitionTests tests/device_session_transition_policy_test.cpp engine/device/DeviceSessionTransitionPolicy.h) + target_compile_features(ARMixDeviceSessionTransitionTests PRIVATE cxx_std_20) + add_test(NAME NonDestructiveAudioSetupRetainsMixerDocument COMMAND ARMixDeviceSessionTransitionTests) add_executable(ARMixLiveRoutingEpochTests tests/live_port_epoch_publisher_test.cpp) target_compile_features(ARMixLiveRoutingEpochTests PRIVATE cxx_std_20) add_test(NAME P1ELivePortGenerationRevisionAndRealtimeRetirement COMMAND ARMixLiveRoutingEpochTests) @@ -313,6 +338,33 @@ if(BUILD_TESTING) target_link_libraries(ARMixShowStoreTests PRIVATE juce::juce_core juce::juce_cryptography juce::juce_recommended_config_flags) target_compile_features(ARMixShowStoreTests PRIVATE cxx_std_20) add_test(NAME P4ImmutableNativeShowsAndVendorStateRoundTrip COMMAND ARMixShowStoreTests) + # Full-size stable ChannelId MixerSession document (never the fixed ShowV2). + juce_add_console_app(ARMixDurableMixerSessionTests PRODUCT_NAME "ArSonMix Durable Dynamic Mixer Session Tests") + target_sources(ARMixDurableMixerSessionTests PRIVATE tests/native_mixer_session_store_test.cpp + src/NativeMixerSessionDocument.h src/NativeMixerSessionStore.h) + target_link_libraries(ARMixDurableMixerSessionTests PRIVATE + juce::juce_audio_devices juce::juce_audio_processors juce::juce_cryptography juce::juce_recommended_config_flags) + target_compile_features(ARMixDurableMixerSessionTests PRIVATE cxx_std_20) + add_test(NAME P0DynamicMixerSessionDocumentAndCrashSafeRecovery COMMAND ARMixDurableMixerSessionTests) + # Presentation-only native identity; no audio-thread access. + juce_add_console_app(ARMixChannelAppearanceTests PRODUCT_NAME "ArSonMix Channel Appearance Tests") + target_sources(ARMixChannelAppearanceTests PRIVATE + tests/native_channel_appearance_store_test.cpp src/NativeChannelAppearanceStore.h) + target_link_libraries(ARMixChannelAppearanceTests PRIVATE + juce::juce_core juce::juce_recommended_config_flags) + target_compile_features(ARMixChannelAppearanceTests PRIVATE cxx_std_20) + if(MSVC) + target_compile_options(ARMixChannelAppearanceTests PRIVATE "$<$:/utf-8>") + endif() + add_test(NAME NativeChannelIdentityDiskAckAndExactId COMMAND ARMixChannelAppearanceTests) + + # Eight-band native PEQ: deterministic sweep, stereo isolation, RT no-heap, + # smoothing and Nyquist guards. Built with the existing Windows native lane. + add_executable(ARMixNativeChannelEqTests tests/builtin_channel_eq_test.cpp + engine/builtin_fx/BuiltInFxCatalog.h engine/builtin_fx/ChannelEq.h) + target_compile_features(ARMixNativeChannelEqTests PRIVATE cxx_std_20) + add_test(NAME NativePEQEightBandsRTAndFrequencyResponse COMMAND ARMixNativeChannelEqTests) + add_dependencies(ARMixMixerRoutingTests ARMixNativeChannelEqTests) add_executable(ARMixNativeMasterLoudnessTests tests/native_master_loudness_test.cpp engine/dsp/NativeMasterLoudness.h) target_compile_features(ARMixNativeMasterLoudnessTests PRIVATE cxx_std_20) diff --git a/docs/ADR_DEVICE_INDEPENDENT_MIXER_SESSION_20261107.md b/docs/ADR_DEVICE_INDEPENDENT_MIXER_SESSION_20261107.md new file mode 100644 index 000000000..1b16f5229 --- /dev/null +++ b/docs/ADR_DEVICE_INDEPENDENT_MIXER_SESSION_20261107.md @@ -0,0 +1,147 @@ +# ADR — ArSonMix Device-Independent Mixer Session & Crash-Safe Resume +**Status: IMPLEMENTATION DESIGN / NOT YET IMPLEMENTED** +**Date:** 2026-11-07 +**Canonical integration:** PR #418, preserve ONE JUCE audio callback, native ChannelId PCM ownership, and the single assembled `/preview/` GUI. +**Driver incident:** Operator confirms WASAPI works; ASIO4ALL was reconfigured from existing WDM inputs to VB-Cable capture + Realtek playback and the host showed `Current device is not open; refresh`. Software replay is not physical qualification. + +## 0. Non-negotiable user outcomes + +1. Device selection, driver sample-rate/buffer, pin setup, and driver loss **NEVER erase mixer content**: channel IDs/order/names, channel format, faders/PAN/MUTE/SOLO, EQ and builtin effects, VST3 chains/slot identities/params/bypass/order and available saved binary states, groups/AUX/MON/MATRIX/CUE that are actually supported, sends, WIRE edges/gains, bus/master settings, routing intents, and GUI user workflow. Maintain EXACT values, not defaults. +2. Opening an Audio I/O window without committing hardware change MUST NOT mutate, discard, re-create, or reset the accepted mixer graph. +3. A different hardware device can invalidate PHYSICAL endpoint bindings only. Keep every mixer control and internal edge intact. Mark unresolved physical IN and OUT as **NEEDS REMAP**. Do not infer that "ASIO4ALL v2" on both selectors proves VB-Cable IN or Realtek OUT; require current driver port readback and identity evidence. +4. On restart, reopen the **last verified mixer document** immediately, even if no device can open; the mixer looks as previously used, but all hardware outputs remain DISARMED until a fresh verified device, routing and explicit user ARM. +5. Named user snapshots/Shows and "Latest Session" auto recovery are distinct features: users can save immutable presets and return to them, while autosave is an unobtrusive crash-safe last-known-good working state. +6. No extra callback, JS/WebAudio DSP, audio-thread disk I/O, graph rebuild on GUI navigation, optimistic ACK, automatic output routing or auto-unmute. Preserve existing `/preview/` geometry and approved icon. + +## 1. Audit findings, current source (PR #418 at design time) + +- `src/LiveAudioEngine.h::beginManualAudioSetup()` calls `dryRoutingLab_.disable()`; `finishManualAudioSetup()` invokes `startUnpatchedProductionSession()`. `LiveDryRoutingLab::startUnpatchedSession()` explicitly creates ten NONE sources, gains 0.25, neutral pans and zero sends: a real native mixer reset. +- `src/Main.cpp::showDeviceSetup()` invokes `beginManualAudioSetup()` **on opening the native JUCE settings window**, and calls `finishManualAudioSetup()` when closed; `applyCustomAudioDevice()` uses the same reset machinery. Both entrypoints must be transactionally unified. Merely closing a settings window must not replace a session. +- `LiveDryRoutingLab::prepareDevice/deviceStopped` increment a *transient* device epoch and revoke valid hardware masks. This is correct for hardware safety, but NOT evidence that the user-authored mixer document should be thrown away. +- `web/approved-native-bridge.js::refreshRealM4Inputs()` may reset presented input to None when native authoritative state is unpatched; UI must preserve document draft and display `NEEDS REMAP` without falsely claiming active PCM. +- `NativeLiveShowCapture`/`NativeDryShowRecall`/`NativeShowSchema` and `NativeShowStore` already offer useful transactional snapshot, checksum and immutable HEAD primitives. Their current fixed 10 CH + 4 AUX schema does NOT losslessly represent today's dynamic ChannelId GROUP/FX RETURN/WIRE graph. Do not repurpose this restricted format as full-session autosave or silently drop extra buses. +- `StudioBackup` is a user-directed whole-Studio export with integrity manifest. It is NOT startup autosave. +- Windows FAT run 42318730495: MSVC builds, CTest **58/58 PASS**, package fails due to a different `favicon.ico` hash during `scripts/package_native_windows.ps1` regeneration. CMake-selected Python is recorded in `build/approved-gui-python.txt`, while the packager independently invoked PATH `python`; the optional final verification script made the same mistake. Preserve SHA guard and use the exact CMake interpreter at BOTH boundaries. The generated current branding cannot be considered delivered until ZIP + embedded PE icon checks pass. + +## 2. Architecture — two lifetimes, one native authority + +```text + UI /preview/ — draft gestures and commands only + | + Native CONTROL owner + | + MixerSessionStore / SessionDocument + stable ChannelId / BusId / EdgeId / FxSlotId / revision + / | \ + Live immutable PCM DeviceBinding Persistence I/O + graph + FX leases (runtime epoch) .stage + HEAD + LKG + one JUCE callback masks / ports snapshots + autosave + \ / + DeviceApplyCoordinator (one serialized transaction) + | + ONE JUCE AudioDeviceManager +``` + +- **MixerSessionDocument (durable)**: stable logical identity + channels, buses, WIRE edges, matrix/group sends, source *intent*, FX chain references and bypass, channel controls, EQ states, master controls, UI workspace hints, named scenes. Does not embed a driver object, device epoch, callback pointers, realtime counters, screen DOM state or "output armed" permission. +- **AudioDeviceProfile (durable but independent)**: chosen backend and registered driver identity, separate endpoint identity where actually available, preferred sample rate and period, preferred physical pin roles, optional compatible hardware profile. The profile is a *preference*, not proof an output is safe or connected. +- **DeviceBinding (ephemeral)**: current JUCE device instance, verified sparse physical pin masks/labels, actual rate/period, callback generation/epoch, authorization, active mappings, failure causes and monitoring armed state. It may become unbound without modifying the mixer document. +- **PreparedRealtimeGraph (ephemeral/rebuildable)**: prepared render graph, channel buffers, plugin runtime instances/leases and PDC for current device format. Re-preparation on rate/buffer/port change is permitted, but the serialized user mixer state remains immutable and can rebuild exactly on a compatible device. +- **SessionStore** owns accepted model. All UI readbacks and effect commands derive from accepted native state. A device ACK does not declare restored routing LIVE; a later native graph generation/readback is required. Control, device and document revisions are separately monotonic; do not copy temporary device epochs into serialized IDs. + +## 3. DeviceApplyCoordinator — two-phase, idempotent, silence-safe + +**Before any mutation:** +- Gate one transaction by requestId, expected document revision, device generation and pending FX/Show work. Capture/pin an immutable **accepted MixerSessionDocument** and references to existing native VST3 leases; do not stop or erase logical routing. A device chooser opening should display current values without entering this state. +- Preflight current output state. Require explicit user review and disarm before hardware reassignment. Keep the single direct output safety fence; disarm secondary stream. Never secretly switch from ASIO to WASAPI, another speaker, or an arbitrary first enumerated port. +- Capture a non-RT complete safe checkpoint. For VST3 states that cannot be captured safely while live, retain the last verified state blob and mark it **DIRTY / SAVE PENDING**; never claim a lossless vendor snapshot. Do not block the callback for disk/JSON/plugin serialization. + +**Apply**: +```text +IDLE -> STAGE_DOCUMENT -> QUIESCE_OUTPUT -> OPEN_NEW_DEVICE + -> VERIFY_IDENTITY + PIN_ROLES + RATE/BUFFER -> PREPARE_NEW_GRAPH + -> VALIDATE_DOCUMENT + BIND_HARDWARE -> ATOMIC_GRAPH_SWAP + -> READBACK -> ACCEPTED_MUTED (or NEEDS_REMAP_MUTED) + +failure: OLD_DOCUMENT_INTACT -> attempt verified old-device restore once + -> RESTORED_MUTED or RECOVERY_REQUIRED (old document still intact) +``` + +- Hold complete logical graph and channel controls in the session model throughout the device change. For unchanged hardware port identity, compatible remapping is eligible; for swapped/disappeared/ambiguous ASIO4ALL WDM pins, preserve the routing *intent*, but mark unresolved bindings DISCONNECTED / NEEDS_REMAP and stay muted. +- If rate/block changes, call correct JUCE/VST3 preparation on control-supported threads; vendor processing tails may reset and audible interruption is unavoidable. User values, FX order and available serialized plugin state must survive. No guarantee of seamless hot-switch between clocks. +- A rejected driver open, partial readback, post-open identity mismatch or plugin prepare failure may never publish a default mixer as the accepted document. An unavailable plugin becomes a visible offline/missing placeholder with its stored state retained; it cannot cause accidental bypass of every other chain. +- Publish new graph and document binding together only when identities and routes are valid, with bounded RT-safe handoff; report route acceptance separately from device openness. No per-callback locks, allocations, logging, disk I/O or vendor GUI work. +- After success the mixer should **LOOK THE SAME**. Physical device-bound badges alone may change to NEEDS REMAP. Explicit user ARM after checking a real input and real output is still required. + +## 4. Persistence & recovery, on user's actual Studio workspace + +Use the existing `PortableWorkspace::dataRoot()` and current Studio backup conventions. Do not create a competing config root or store project truth in browser localStorage. + +**Versioned schema** `arsonmix.mixer-session.v1`, with build ID, schema version, stable document UUID, document revision, graph IDs, typed processing topology, logical routing, source intent, FX slot IDs/canonical catalog IDs, VST/plugin state SHA references, EQ parameters, snapshot metadata, UI view state and external hardware profile reference. Enforce total size, per-effect state caps, node/edge limits, unique IDs, acyclic graph and supplied plugin hash checks. Migrations must not coerce unsupported dynamic buses into 10+4 or silently discard WIRE. + +**Store layout (proposed):** +```text +Studio/Sessions// + HEAD # small atomic generation pointer + versions// + session.json # complete validated mixer document + blobs/.bin # content-addressed vendor state + manifest.json # per-file SHA, schema, length, source revision + recovery/ # bounded last-known-good / failed draft metadata +Studio/DeviceProfiles/.json # independent hardware preferences +Studio/Shows/ # existing user-named Shows untouched +``` + +Write **stage -> validate -> readback hash -> atomic commit/pointer swap**. Preserve at least two last-known-good generations, never overwrite a valid HEAD with a partial write. Include bounded orphan cleanup only off RT and only after successful commits. Support crash between any two filesystem operations and corrupt or read-only folders; load last-good and give an actionable read-only/recovery status rather than resetting to defaults. Verify portable/installed data roots use identical semantics. + +**Autosave policy:** +- Save only native **accepted** changes (not pending GUI gestures) and only when the accepted document revision advances. Debounce normal scalar changes, coalesce fader movement and persist a compact document generation; a single fader drag is one accepted gesture, not 60 writes per second. For structural edits, write a checkpoint at acceptance and avoid unrelated repeat snapshots. +- Vendor state can require different safe thread-affinity/quiescence: separate its checkpoint from high-rate fader saves. Never call arbitrary VST3 `getStateInformation` from realtime callback or while device teardown is in progress. Publish “Latest saved / Pending plugin state” truthfully. +- Manual **Save Snapshot** creates an immutable named revision; **Recall Snapshot** preflights and atomically prepares, with a one-step undo checkpoint. **Latest Session** is not a snapshot scene, and **Save Show** is not startup autosave. Preserve existing Shows/Studio Backup and introduce explicit user-level session import/export separately. +- On normal application exit, attempt a bounded final commit on the correct non-RT owner. After crash, prefer last verified fully committed generation; never trust a partial last gesture or partial plugin blob. + +**Cold startup**: +1. Verify last-good session on disk (schema, checksums, stable IDs). Render saved mixer workspace even with hardware disconnected; show clearly which device/profile is missing. +2. Discover hardware without choosing an unsafe substitute. Match exact physical port roles only with sufficient identity evidence. Unresolved physical routing gets NEEDS REMAP, all outputs DISARMED and a non-destructive device selector. +3. Prepare graph after device has been explicitly verified; publish native acceptance/ACK, then offer user-controlled ARM. Do not start loud audio from persisted "MONITOR ON" or saved meter levels. + +## 5. UI acceptance on the ONE approved /preview/ + +Keep current compact premium console; no new bulky wizard. A small existing status area displays e.g. `Latest session saved`, `Saving…`, `FX state pending`, `Output muted · verify mapping` or `3 inputs need remap`. A single **Snapshots** drop-down offers named Save, Recall, Rename/Remove and Restore Last Good. Device change does not trigger a full track list re-creation; reconcile by stable ChannelId and only update physical pin choices/status. Never render `None` over a saved but temporarily unresolved physical source *intent*. Never claim the old input is currently LIVE without driver readback. + +## 6. Provenance: approved latest icon is a release contract + +Brand reference = current approved `assets/icon/brand-source-128.png` and committed `assets/icon/arsonmix-app.ico`, `site/favicon.ico`, `site/favicon-16x16.png`, `site/favicon-32x32.png` on latest reconciled `main`. Current `CMakeLists.txt` uses `ICON_BIG/ICON_SMALL` from generated PNG; `src/Main.cpp` calls `setIcon(approvedAppIcon())` for windows; `build_pages.py` includes favicons in public preview. All are **source wiring**, not proof of installed EXE. +- Fix the exact packaging verifier interpreter mismatch without disabling the SHA test. +- Verify source hash + committed icon bytes, run consistent generation, assert EXE PE icon group rendered pixels match approved PNG at supported sizes; check native window/titlebar and WebView2 favicon after build. Validate actual artifact exe and ZIP SHA + embedded sourceCommit. Do not claim the icon is delivered while the ZIP lane is red. +- Prefer eventually shipping byte-exact pre-approved sealed icon resources across build machines (no Python/zlib-dependent compressed-byte drift); retain an independent derived-pixel verifier. + +## 7. Deterministic qualification matrix + +**Pure native session/control tests**: +- 10CH+4AUX and dynamic GROUP/FX RETURN/ChannelId/WIRE multiple edges: capture doc -> change device -> same IDs and exact fader/EQ/FX/bypass/latency/graph controls -> reconnect (including ASIO4ALL reorder). +- Device dialog open/cancel, same-device APPLY with unchanged pins, sample rate/buffer only, ASIO closed reopen, changed Realtek/VB-Cable pins, device busy/rejected, rollback success and failure. In ALL cases: original document stays complete; no auto monitor ARM. +- Disconnect/reconnect while current source identity absent, invalid sparse pin indices and ambiguous ASIO4ALL names; never silently wire channel A to device B. +- Vendor VST3 state success/failure/stale lease, editor open, missing plugin, plugin changed sample rate, save/recall mid-graph change. Exact acknowledged prior generation retained. +- Persistence fault injection: crash after stage/manifest/rename/HEAD, corrupt JSON/hash, low disk, read-only portable path, malformed graph, duplicate IDs, oversized FX blob, migration from ShowV2; no truncated/excessive memory or write in RT. + +**UI/Windows/physical gates**: +- Full Chromium captures identical MIXER/FX/ROUTE visual positions at 1366/1680/1920 and bank mode. Device-change ACK must preserve every on-screen accepted control and stable wire ID while only hardware-unsupported port states become NEEDS REMAP. +- Exact-SHA Windows MSVC + native CTest + independently verified FAT ZIP. Pin/branding PE evidence and clean reinstall/portable second-run last-session recall. +- Physical WASAPI and ASIO4ALL with VB-Cable capture and Realtek render: compare same mix/FX order before/after reconfiguration and relaunch, no phantom output to speakers, measure crackle/latency/clock drift. Software PASS != hardware PASS. + +## 8. Milestones (one meaningful integration PR, avoid naive patch stacking) + +| Phase | Product deliverable | Exit criterion | +|---|---|---| +| P0 release integrity | Fix packaging Python provenance, source/PE branding checks | Same-SHA FAT ZIP produced, independently verified, not claimed physical pass | +| P1 state ownership | Document/DeviceBinding separation; no mixer destructive mutation when opening/changing Audio Setup | All supported mixer controls preserved across ASIO/WASAPI/same-device APPLY and driver failure; native regression matrix | +| P2 persistent work | Versioned full ChannelId SessionStore, fast accepted-revision autosave, named snapshot & crash recovery | Complete dynamic graph and available FX state round-trip after cold restart, corruption rollback; no RT cost | +| P3 hardware recovery UX | Identity-safe physical port profile/remap, missing VST placeholder and explicit re-arm | VB-Cable→Realtek ASIO4ALL and WASAPI test; no silent misrouting/reset; readable diagnostics | +| P4 release qualification | Whole workflow, UI parity, exact SHA ZIP and actual hardware FAT | Repeatable soak/clock/latency/crackle evidence; staged PR review then merge main when qualified | + +**Conservative launch scope:** do not silently migrate legacy Show storage into complete SessionStore. Full session serializer must first round-trip native ChannelId state including extra buses and WIRE before making autosave the default. Do not use blind `startUnpatchedProductionSession()` as a recovery step once a user-authored document exists. + +## Handoff and safety + +- Current main at audit: `f96c09ec33da36c723aff3ae73b9b42d7db3fa7e`. Current draft integration PR #418 at audit: `9de9756c8303a081918bc9fd23195186e1e68128`. Both must be rechecked before implementation and merge. +- The architecture above is a **design**. Only the packaging interpreter fix is small implementation work in this checkpoint. No claim of implemented session retention, autosave, plugin state preservation across hardware restart, or physical ASIO4ALL PASS yet. diff --git a/docs/P0_LIVE_ROUTING_RECOVERY_20261106.md b/docs/P0_LIVE_ROUTING_RECOVERY_20261106.md new file mode 100644 index 000000000..02bb48043 --- /dev/null +++ b/docs/P0_LIVE_ROUTING_RECOVERY_20261106.md @@ -0,0 +1,76 @@ +# P0 live routing recovery — CH03 → CH04 and SOURCE ONLY + +Continue PR #418 on `integration/daw-direct-hardware-input-20261105`. +The approved assembled `/preview/` appearance and sole JUCE callback remain. + +## Root causes and changes + +1. `integration/ApprovedNativeControlIntent.h`, the decoder actually included + by `Main.cpp`, rejected INPUT destinations. The PCM compiler already + supports channel-to-channel routing. Admit an INPUT only when both the + accepted public and native inventories identify that exact ChannelId with + the same role. Retain epoch, graph, roster, edge, feedback and source guards. +2. `DynamicPreparedMixerBlock` culled every lane with no path to MAIN or + MONITOR. SOURCE ONLY therefore lost its DSP and local meter. Schedule + physical/insert signal roots and their descendants independently of output + reachability. Empty, unpatched descriptors still use no audio scratch. +3. Publish INPUT channels in the accepted destination inventory. Preserve + detailed native WIRE rejection reasons through the existing IPC executor + and ACK, including feedback cycle, duplicate route and stale edge. + +## Defined audio behavior + +- Physical capture and incoming WIRE PCM **sum before** the receiver's mono + fold, inserts, fader, PAN, MUTE/SOLO and post-fader meter. A hardware selector + set to None leaves incoming WIRE audio intact. +- CONNECT adds a deliberate parallel post-fader send; it can produce a second + audible path when the source still has a primary MAIN route. ROUTE ONLY + replaces the primary destination and preserves deliberate parallel sends. + Promotion of an existing send retains its EdgeId and does not double dry PCM. +- SOURCE ONLY removes the primary edge; source capture, inserts, meter and + deliberate parallel sends remain active. Removing an EdgeId affects only + that edge. Feedback cycles reject the complete candidate atomically. + +## Regression evidence + +`P0ApprovedDecoderChannelToChannelAndSourceOnlyPCM` is pulled into the existing +Windows build through `ARMixMixerRoutingTests`, then executed by CTest. +It crosses the approved production decoder/executor, accepted session, +publisher, compiler and renderer, asserting actual sample values and meters: + +- CH03 stereo hardware → MAIN; CH07 mono remains independently audible. +- CH03 → CH04 with no hardware on CH04; receiver FX gain and fader affect PCM. +- Parallel send, promotion to exclusive primary with stable EdgeId, unplug, + reconnect, retarget and CH03 → CH04 → BUS → MAIN. +- SOURCE ONLY at source or receiver retains local DSP and meters. +- Live receiver fader/PAN, FX seam bypass, MUTE/SOLO; hardware plus WIRE summing. +- Cycle rollback, stale graph/epoch and forged native destination role reject. +- Zero C++ heap allocations during every tested render block. + +The new regression fails with the old decoder and, separately, with the old +render scheduling. Existing routing/dynamic PCM tests, approved native v8 +tests, 127 fast native contracts, and deterministic approved GUI provenance +checks also pass locally. The Chromium/Windows result and exact checkpoint +SHA are recorded in PR #418; do not infer those results from this document. +The test FX seam is deterministic DSP, not a third-party VST3 hardware test. + +## Short physical FAT + +1. Use the checkpoint's **UNQUALIFIED** Windows ZIP. Choose a real ASIO/WASAPI + capture/playback pair. Set CH03 IN to stereo 1+2, CH04 IN to None, both + faders to 0 dB; no MUTE/SOLO. Verify CH03 and MAIN activity first. +2. Connect CH03 OUT → CH04 IN in normal post-fader send mode. CH04 meter must + move. Remove CH03's direct MAIN edge for a serial listening test; otherwise + the retained parallel MAIN route deliberately adds another dry contribution. +3. With CH04 → MAIN, move CH04's fader and bypass/enable a real VST3 insert. + Its output must affect MAIN. Test MONO/STEREO and MUTE/SOLO. +4. Remove CH04 → MAIN: CH03 and CH04 meters must keep moving; their contribution + to MAIN stops. Reconnect without changing hardware IN or restarting audio. +5. Set CH03 to SOURCE ONLY with no other sends: CH03's meter remains active, + CH04 no longer receives it. Reconnect and test BUS/MAIN plus device reopen. + +On failure, immediately choose **More → Copy Audio Report** and paste the +report with the exact ZIP/source SHA and routing steps. Physical listening, +vendor VST3 behavior, ASIO timing, hotplug and crackle soak remain **PENDING** +until observed on the user's hardware. This checkpoint does not authorize +merging main or promoting a stable release. diff --git a/docs/P1_NATIVE_WIRE_GAIN_20261106.md b/docs/P1_NATIVE_WIRE_GAIN_20261106.md new file mode 100644 index 000000000..86e0a39e5 --- /dev/null +++ b/docs/P1_NATIVE_WIRE_GAIN_20261106.md @@ -0,0 +1,37 @@ +# Native WIRE gain and channel OUT + +Continues PR #418's real channel-to-channel PCM and source-only recovery. +The approved `/preview/` layout and single JUCE audio callback remain the +product owners. + +## Behavior + +- WIRE send gain and Sends on Faders target an accepted native EdgeId. + Drag updates coalesce while one intent waits for ACK and independent + accepted readback. No optimistic audio state is presented as accepted. +- Gain is a scalar update: graph/roster revisions and strip DOM stay stable. + The existing preallocated DSP gain slew spans 64 samples. No graph compile, + allocation or new callback is introduced by a gain edit. +- Primary OUT stays at unity; use channel/destination faders for its level. +- OUT choices include INPUT, GROUP and FX_RETURN, resolved by ChannelId. + Duplicate and reserved names get an identity suffix. OUT uses the same + exclusive ROUTE_ONLY transaction as WIRE, including cycle validation. +- Source-only/dormant sends remember accepted gain. A subsequent hardware + source preparation must restore that gain instead of reverting to unity. +- Device, graph or roster changes discard queued old-identity edits. + +## Verification + +`approved_native_routing_pcm_test.cpp` exercises public decoder/executor, +accepted session/publisher and actual rendered samples. It checks level, +64-sample smoothing, accepted readback, unchanged revisions, invalid/primary +edge rejection, dormant gain restoration and zero render allocations. + +`approved_native_m2_contract.test.cjs` covers latest-value coalescing, +ACK/readback proof, destination/tap identity and ambiguous OUT names. +`approved_native_wire_gain_smoke.py` uses real compiled native HTML and +Chromium keyboard input at 1366x768, 1680x900 and 1920x1080. Its backend is +emulated for UI isolation; it is not physical audio evidence. + +Physical ASIO/WASAPI, third-party VST3 listening and live stability remain +PENDING until measured on a real rig. No stable qualification is implied. diff --git a/docs/P1_NONDESTRUCTIVE_DEVICE_SESSION_20261107.md b/docs/P1_NONDESTRUCTIVE_DEVICE_SESSION_20261107.md new file mode 100644 index 000000000..fdec29220 --- /dev/null +++ b/docs/P1_NONDESTRUCTIVE_DEVICE_SESSION_20261107.md @@ -0,0 +1,30 @@ +# P1-A — Non-destructive Audio I/O session protection + +**Integration owner:** PR #418 on `integration/daw-direct-hardware-input-20261105`. **Status: partial protection, NOT full device rebind or restart resume.** + +## Causal correction + +The prior `beginManualAudioSetup()` invoked `dryRoutingLab_.disable()`, releasing the accepted M4/ChannelId publishers, FX leases, WIRE graph and live controls on **dialog open**. `finishManualAudioSetup()` then created a fresh unpatched 10CH/4AUX graph even if the operator closed the selector without changing hardware. + +The P1-A changes retain that accepted graph on setup entry, keep both outputs disarmed while device selection happens, and bypass default graph recreation when the accepted routing is still ready for the current hardware epoch. A driver change/failure preserves authored state **in process** but stops short of falsely claiming live PCM: the session remains unbound and muted until a future complete, verified rebind transaction is implemented. Other diagnostic/independent-clock paths now refuse to discard authored graph state without that transaction. This is containment, not full recovery. + +## Explicit limitations / next critical engineering work + +- The existing JUCE selector applies edits immediately; it is not a staged Cancel/Apply UX. A no-change close preserves the graph but leaves output muted for safety. Hardware changes require real identity, mask, sample-rate, buffer, FX preparation, graph publication and ACK validation. +- On an actual epoch change, the in-memory accepted logical graph and plugin lease data are **retained but not yet rebound or guaranteed to be fully visible**. Do not clear the mixer, fake a success ACK, use default endpoints, arm output, or call an M4-only Show recall to repair it. Restart does not yet restore this retained session. +- Before P1 can be marked complete, implement canonical MixerSessionDocument with durable stable IDs and complete FX state, safe DeviceApplyCoordinator, full dynamic graph rebind and GUI NEEDS REMAP projection. +- P2 crash-safe last-good generation, snapshots, plugin state blobs and restart resume remain pending. +- P3 timed VST3 catalog/cache and editor restore, P4 Inno Setup, P5 signed-update verification and installer qualification remain pending. +- Physical WASAPI/ASIO4ALL hardware FAT remains PENDING; green CTest cannot establish audible latency, sample-clock stability or sound quality. + +## Regression evidence + +The new C++ policy suite exercises all 8 verified/bound/authored combinations, asserting **createFirstSilentMixer** is legal only when no authored content exists. The policy is invoked directly by native `finishManualAudioSetup()`. A native MSVC build/CTest is required before any merge or qualification. This checkpoint does not claim full application acceptance. + +## Next milestone: real two-phase rebind + +1. Capture accepted immutable ChannelId model and original plugin/VST3 state on CONTROL (not inside callback). +2. Prepare a verified driver profile, compare physical input/output identities and explicitly mark changed ports NEEDS REMAP. +3. Rebuild graph with all authored stable IDs, buses, WIREs, original processing parameters, FX order/bypass and safe plugin state at the new sample rate/buffer. +4. Publish atomically, ensure accepted native readback and user-visible document projection. Keep output disarmed until an explicit ARM. +5. Rejected device or plugin preparation must not mutate the accepted document. Test no-change, active graph, ASIO4ALL WDM pin reorder, lost device, failed driver, rate/buffer changes, and concurrent editor/FX work. diff --git a/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md b/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md new file mode 100644 index 000000000..7d86ca6d1 --- /dev/null +++ b/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md @@ -0,0 +1,75 @@ +# Cold WIRE and native VST3 recovery + +Continues #418 at `16fe8c42`. The supplied Windows screenshots show two +different FX failures: stale routing publication and a blanket plugin-latency +rejection. The reported first-WIRE toast was not captured in those images; +cold admission is covered explicitly below rather than inferred from a +previously working OUT-dropdown transaction. + +## Audited faults + +1. The picker chose M4 for original CH1–10 while ChannelId already owned PCM, + unless an unrelated WIRE edit had set `nativeBusStructural`. PCM authority + now selects native insertion for all admitted INPUT/GROUP/FX_RETURN/MAIN + channels. An occupied external CH1 vendor chain keeps its ownership guard. +2. The legacy compatibility insertion cloned `sourceTemplate_` with its old + APPLY revision. It now stamps the validated current epoch/revision, and + APPLY rejects stale revisions before expensive vendor preparation. +3. Native plugin admission compared a routing epoch to a device-start count. + Reopening a device can make those counters differ. Admission now compares + the actual routing epoch, consistently with accepted native readback. +4. Clicking an admitted native insert still queried M4's FX array. Editor + acquisition now uses exact ChannelId, native PCM revision, slot and opaque + instance token. The existing JUCE editor window retains the real owner. +5. Catalog refresh called the M4 FX painter even while ChannelId owned PCM. + Its stale/empty FX array could erase an installed native rack in the GUI, + and equal-revision telemetry would not rebuild it. The M4 painter now + refuses to paint over native authority; a catalog-refresh regression + verifies the accepted name/token survives. +6. A first drag could reach the bridge while SOURCE admission or another + native intent was pending. One bounded latest CONNECT/ROUTE_ONLY gesture + is retained, requests independent readback and dispatches only after native + projection is ready. Epoch changes, changed mapped endpoint identities, + failure and timeout discard it. No automatic OUT rewrite, output arm or + optimistic wire is introduced. A new CONNECT rejected solely for a stale + native revision receives at most one rebase after independent readback; + removals/retargets, changed epochs and feedback rejection are never retried. + +## Fixed-latency VST3 support + +The native graph now computes latency along the same prepared DAG. Each +fan-in aligns incoming edges and its own hardware source before processing. +PRE-fader edges in this kernel are post-insert, so they include that source's +FX latency. MAIN and MONITOR terminal timing is aligned as well. A bypassed +insert/rack retains its declared latency through an aligned dry delay, so +scalar bypass does not change compensation or rebuild the graph. + +All delay storage is prepared on CONTROL, bounded by the graph scratch +budget and 131072 samples per path. Callback processing uses preallocated +stereo rings, with no heap/lock/device operation. The host reports actual +native plugin delay in snapshots/audio status. Excessive latency rejects +the candidate and retains the old graph. + +A plugin changing its latency after preparation is conservatively rendered +as aligned dry with `latencyChanged` readback until reloaded. Automatic live +latency reconfiguration is not claimed. Legacy external CH1 paths retain +their existing restrictions; this is not a license to remove their guards. + +## Regression evidence + +- `approved_native_cold_start_smoke.py`: compiled native DOM, real mouse drag + from G0 before admission, no OUT priming, native picker insert on an original + channel with structural=false and unrelated M4 revision, then editor token. + Three desktop sizes. Its backend is emulated for UI isolation. +- `dynamic_latency_compensation_test.cpp`: actual sample impulses through + source latency, serial/parallel PRE/POST sends, receiver hardware fan-in, + MAIN/MONITOR, varying callback sizes, zero render allocations and rejection + rollback on budget overflow. +- `live_channel_fx_graph_test.cpp`: real JUCE AudioProcessor sample delay, + wet/individual/rack bypass timing, zero render allocations, latency-change + fallback and existing vendor-instance migration/ownership regressions. +- Existing decoder/channel-to-channel/source-only PCM and approved GUI bundle + provenance checks remain required. + +Physical user-rig ASIO/WASAPI/VST3 listening and soak remain PENDING. Software +tests do not prove that a third-party vendor plugin or a public rig is safe. diff --git a/docs/P3_NATIVE_FX_RACK_EDIT_20261107.md b/docs/P3_NATIVE_FX_RACK_EDIT_20261107.md new file mode 100644 index 000000000..f7e3a41ce --- /dev/null +++ b/docs/P3_NATIVE_FX_RACK_EDIT_20261107.md @@ -0,0 +1,62 @@ +# Native FX editor lifetime and rack editing + +Continues the owner-tested working candidate `2b1ef483` in #418. The owner +explicitly requested these fixes, visual removal of MAIN cable fragments, +reconciliation and merge to main. Physical routing/FX processing was reported +working; full ASIO/device/long-session qualification remains separate. + +## Editor flash root causes + +The 12 Hz retention check searched inactive M4 `fxInstances` even when native +ChannelId owned the plugin. It therefore closed the newly opened native +editor. Retention now queries the current processor lease by pointer and device +epoch. It survives reorder and channel transfer, and closes on actual removal +or device invalidation. Generic device-manager notifications no longer close +an otherwise valid editor. Reopening also destroys the old window before +asking JUCE for an editor pointer, avoiding a dangling returned editor. + +## One native FX edit transaction + +REMOVE_INSERT and MOVE_INSERT require current device/PCM/roster revisions, +exact source ChannelId, slot and opaque instance token. Destination ChannelId, +role and insertion position are validated independently against public/native +inventories. Both roster catalog order and actual processor lease order prepare +off callback and publish once. Cross-channel MOVE transfers the existing +processor and saved bypass/state; it does not rescan, clone or prepare a VST. +PDC is rebuilt from the new placement; no new callback or JS DSP exists. + +ACK alone does not move/delete GUI rows. Later accepted readback must prove +the exact new ordered token inventories and global absence/uniqueness of the +removed/moved instance. Stale tokens, full racks, invalid positions and an +occupied external CH1 owner reject without replacing the audible graph. + +## Shared approved GUI + +The historical HTML seed is preserved. The sole Pages assembler adds shared +FX interaction semantics, used identically by public `/preview/` and native +WebView2. A row-sized ghost follows pointer motion with an insertion marker; +dragging up/down or into another visible channel rack dispatches one native +edit. Escape, invalid release and pointer cancellation discard presentation. +Keyboard Alt+arrow reorder uses the same native authority. Public reference +transfers retain identity and compact slots, without claiming audio. + +MAIN's decorative source-down/master-down cable fragments are no longer +rendered. Actual MAIN edges, jack identity, OUT controls, disconnect/Undo and +custom channel-to-channel cables remain available. + +## Verification and merge + +- Native JUCE tests: noncommutative gain/offset PCM verifies initial order, + reorder, cross-channel transfer and delete; exact owner/editor retention, + no processor re-prepare, stale rejection and zero render allocations. +- Transport tests: exact ordered ACK/readback, no token copy masquerading as + transfer, deletion absence, stale instance rejection and editor guard source. +- Browser tests: compiled native pointer ghost movement, insertion marker, + reorder/transfer/delete, editor token after transfer, and quiet MAIN while + the audio edge remains, at three desktop sizes. Backend isolation is emulated. +- Existing approved-GUI provenance and current browser/PCM suites remain required. + +Reconcile main's one documentation-only commit `ac85039a` as a parent of the +candidate before exact-SHA qualification. Merge only the qualified source under +the owner's explicit instruction; do not label main merge as a stable release +or invent completion of physical FAT for the newly added interactions. diff --git a/docs/SMART_CI_RUNNER_WORKFLOW.md b/docs/SMART_CI_RUNNER_WORKFLOW.md index 83ca918fb..660873a21 100644 --- a/docs/SMART_CI_RUNNER_WORKFLOW.md +++ b/docs/SMART_CI_RUNNER_WORKFLOW.md @@ -156,3 +156,7 @@ Physical audio FAT: Unresolved risk and next significant milestone: ``` + +## Historical CSS migrations + +Full current-product UI qualification keeps archived V8–V27 migration tests disabled unless `historical_css: true` is explicitly requested. Current approved GUI, native interaction, browser and provenance checks remain mandatory. diff --git a/engine/builtin_fx/BuiltInFxCatalog.h b/engine/builtin_fx/BuiltInFxCatalog.h new file mode 100644 index 000000000..23e39acbc --- /dev/null +++ b/engine/builtin_fx/BuiltInFxCatalog.h @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include + +// This is a compile-time catalog of NATIVE effects, not a VST3/FactoryFX manifest. +// Never advertise these as usable in the operator picker until the native PCM +// owner and ACK/snapshot adapter have actually been integrated. +namespace armix::builtin_fx { +inline constexpr std::string_view channelEqId = "armix.builtin.channel-eq.v1"; + +enum class FilterKind : std::uint8_t { highPass, lowShelf, bell, highShelf, lowPass }; +enum class Slope : std::uint8_t { db12 = 12, db24 = 24 }; +struct SlotSpec { + std::string_view id; + FilterKind kind; + float defaultHz; +}; +inline constexpr std::array channelEqSlots{{ + {"hpf", FilterKind::highPass, 80.0f}, + {"low-shelf", FilterKind::lowShelf, 160.0f}, + {"peq-1", FilterKind::bell, 250.0f}, + {"peq-2", FilterKind::bell, 500.0f}, + {"peq-3", FilterKind::bell, 1500.0f}, + {"peq-4", FilterKind::bell, 4500.0f}, + {"high-shelf",FilterKind::highShelf, 9500.0f}, + {"lpf", FilterKind::lowPass, 18000.0f} +}}; +static_assert(channelEqSlots.size() == 8); +} // namespace armix::builtin_fx diff --git a/engine/builtin_fx/ChannelEq.h b/engine/builtin_fx/ChannelEq.h new file mode 100644 index 000000000..a900304d8 --- /dev/null +++ b/engine/builtin_fx/ChannelEq.h @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "BuiltInFxCatalog.h" +#include +#include +#include +#include +#include +#include +#include + +// Channel strip EQ for the main native mixer ONLY. Deliberately no JUCE, +// VST3, ArSonEQ, FFT, WebView2, heap allocation or audio callback ownership. +// prepare()/setBand() operate on UNPUBLISHED instances (or in offline tests). +// For live edits, prepareBandEdit() performs all trig on CONTROL; applyPreparedBand() +// performs only bounded copies on the exclusive audio owner at a block boundary. +// No state mutation may race process(), and no UI thread reads live histories. +namespace armix::builtin_fx { +struct Band { + bool enabled = false; + float frequencyHz = 1000.0f; + float gainDb = 0.0f; + float q = 0.70710678f; + Slope slope = Slope::db12; // HPF/LPF only; other types ignore it. +}; + +class ChannelEq final { +public: + static constexpr std::size_t bandCount = channelEqSlots.size(); + static constexpr float maxGainDb = 18.0f; + static constexpr float minQ = 0.2f; + static constexpr float maxQ = 12.0f; + + ChannelEq() noexcept { + for (std::size_t i = 0; i < bandCount; ++i) { + current_.settings[i].frequencyHz = channelEqSlots[i].defaultHz; + current_.settings[i].q = channelEqSlots[i].kind == FilterKind::bell ? 1.0f : 0.70710678f; + } + } + + // CONTROL creates a precomputed change without accessing a live EQ. + // A bounded queue/immutable handoff outside this module transports it to + // the audio owner. sampleRate acts as a device-epoch-independent fence; + // the mixer adapter must ALSO validate ChannelId, epoch, and revision. + struct PreparedBandEdit final { + Band band{}; + std::size_t index=bandCount; + double sampleRate=0.0; + std::array,2> coefficients{}; // b0,b1,b2,a1,a2 + std::uint8_t sections=0; + bool valid=false; + }; + + static bool prepareBandEdit(std::size_t index, const Band& band, + double sampleRate, PreparedBandEdit& output) noexcept { + if (!std::isfinite(sampleRate) || sampleRate < 8000.0 || + sampleRate > 384000.0 || + !validBand(index,band,static_cast(std::min(20000.0,sampleRate*0.45)))) + return false; + Slot compiled{}; + if (band.enabled && !makeSlot(channelEqSlots[index].kind,band,sampleRate,compiled)) + return false; + PreparedBandEdit candidate{}; + candidate.band=band; + candidate.index=index; + candidate.sampleRate=sampleRate; + candidate.sections=compiled.count; + for (std::uint8_t i=0;i=bandCount || + edit.sampleRate!=sampleRate_ || + !validBand(edit.index,edit.band,maxFrequencyHz())) return false; + const auto kind=channelEqSlots[edit.index].kind; + const bool cut=kind==FilterKind::highPass||kind==FilterKind::lowPass; + const std::uint8_t expected=edit.band.enabled ? + static_cast(cut && edit.band.slope==Slope::db24 ? 2 : 1) : 0; + if (edit.sections!=expected) return false; + Slot newSlot{}; + newSlot.count=expected; + for(std::uint8_t i=0;i(i); + previous_=current_; + current_=next; + fadeRemaining_=fadeLength_; + return true; + } + + // Prepares without allocating. Enabled filters above the new Nyquist guard + // cause rejection (caller must explicitly choose a safe setting). + bool prepare(double sampleRate) noexcept { + if (!std::isfinite(sampleRate) || sampleRate < 8000.0 || sampleRate > 384000.0) + return false; + const float maxHz = static_cast(std::min(20000.0, sampleRate * 0.45)); + Bank next = current_; + for (std::size_t i = 0; i < bandCount; ++i) { + auto& band = next.settings[i]; + if (!band.enabled) band.frequencyHz = std::min(band.frequencyHz, maxHz); + if (!validBand(i, band, maxHz)) return false; + } + next.activeCount = 0; + for (std::size_t i = 0; i < bandCount; ++i) { + next.slots[i] = Slot{}; + if (next.settings[i].enabled) { + if (!makeSlot(channelEqSlots[i].kind, next.settings[i], sampleRate, next.slots[i])) + return false; + next.active[next.activeCount++] = static_cast(i); + } + } + sampleRate_ = sampleRate; + current_ = next; + previous_ = Bank{}; + fadeLength_ = std::max(1, static_cast(std::round(sampleRate * 0.005))); + fadeRemaining_ = 0; + prepared_ = true; + return true; + } + + // Offline/unpublished convenience, NOT for the live audio callback: + // this computes trigonometric coefficients. Use prepareBandEdit() on the + // CONTROL thread and applyPreparedBand() on AUDIO for live automation. + bool setBand(std::size_t index, const Band& band) noexcept { + if(!prepared_)return false; + PreparedBandEdit edit{}; + return prepareBandEdit(index,band,sampleRate_,edit) && applyPreparedBand(edit); + } + + bool resetToFlat() noexcept { + if (!prepared_) return false; + if (current_.activeCount == 0) return true; + previous_ = current_; + for (std::size_t i = 0; i < bandCount; ++i) { + current_.settings[i].enabled = false; + current_.slots[i] = Slot{}; + } + current_.activeCount = 0; + fadeRemaining_ = fadeLength_; + return true; + } + + [[nodiscard]] Band band(std::size_t index) const noexcept { + return index < bandCount ? current_.settings[index] : Band{}; + } + [[nodiscard]] bool isPrepared() const noexcept { return prepared_; } + [[nodiscard]] double sampleRate() const noexcept { return sampleRate_; } + [[nodiscard]] float maxFrequencyHz() const noexcept { + return static_cast(std::min(20000.0, sampleRate_ * 0.45)); + } + [[nodiscard]] std::size_t activeBands() const noexcept { return current_.activeCount; } + [[nodiscard]] int addedLatencySamples() const noexcept { return 0; } + [[nodiscard]] bool transitioning() const noexcept { + return fadeRemaining_>0 || externalFadeRemaining_>0; + } + // AUDIO-owner-only smooth gate, preserving individual band settings. + void setExternalBypass(bool bypass) noexcept { + const float target=bypass?0.0f:1.0f; + if(target==externalTarget_)return; + externalTarget_=target; + if(current_.activeCount==0 && fadeRemaining_==0) { + externalWet_=target;externalFadeRemaining_=0; + } else externalFadeRemaining_=fadeLength_; + } + + // Processing and all biquad histories are audio-owner exclusive. + // left==right is explicitly one mono buffer, never double processed. + void processStereo(float* left, float* right, std::size_t frames) noexcept { + if (!prepared_ || !left || !right || frames == 0) return; + if (left == right) { processMono(left, frames); return; } + if (current_.activeCount==0 && fadeRemaining_==0) { + externalWet_=externalTarget_;externalFadeRemaining_=0; + return; // exact bitwise bypass + } + + for (std::size_t i = 0; i < frames; ++i) { + const float dryL = left[i], dryR = right[i]; + const float wetL = render(current_, 0, dryL), wetR = render(current_, 1, dryR); + if (fadeRemaining_ > 0) { + const float oldL = render(previous_, 0, dryL); + const float oldR = render(previous_, 1, dryR); + const float mix = 1.0f - static_cast(fadeRemaining_ - 1) / + static_cast(fadeLength_); + const float processedL=oldL+(wetL-oldL)*mix; + const float processedR=oldR+(wetR-oldR)*mix; + const float gate=nextExternalMix(); + left[i]=dryL+(processedL-dryL)*gate; + right[i]=dryR+(processedR-dryR)*gate; + --fadeRemaining_; + } else { + const float gate=nextExternalMix(); + left[i]=dryL+(wetL-dryL)*gate; + right[i]=dryR+(wetR-dryR)*gate; + } + } + clearTiny(current_); + if (fadeRemaining_ != 0) clearTiny(previous_); + } + + void processMono(float* samples, std::size_t frames) noexcept { + if(!prepared_||!samples||frames==0)return; + if(current_.activeCount==0 && fadeRemaining_==0) { + externalWet_=externalTarget_;externalFadeRemaining_=0;return; + } + + for (std::size_t i = 0; i < frames; ++i) { + const float dry = samples[i]; + const float wet = render(current_, 0, dry); + if (fadeRemaining_ > 0) { + const float old = render(previous_, 0, dry); + const float mix = 1.0f - static_cast(fadeRemaining_ - 1) / + static_cast(fadeLength_); + const float processed=old+(wet-old)*mix; + const float gate=nextExternalMix(); + samples[i]=dry+(processed-dry)*gate; + --fadeRemaining_; + } else { + const float gate=nextExternalMix(); + samples[i]=dry+(wet-dry)*gate; + } + } + clearTiny(current_); + if (fadeRemaining_ != 0) clearTiny(previous_); + } + + // Control-side visualization only. Never call while an audio callback is + // mutating this instance. Host should snapshot coefficients off callback. + [[nodiscard]] double responseDb(double frequencyHz) const noexcept { + if (!prepared_ || !std::isfinite(frequencyHz) || frequencyHz <= 0.0 || + frequencyHz >= sampleRate_ * 0.5) return 0.0; + const double w = twoPi * frequencyHz / sampleRate_; + const std::complex z1 = std::polar(1.0, -w); + const auto z2 = z1 * z1; + double result = 0.0; + for (std::uint8_t k = 0; k < current_.activeCount; ++k) { + const auto& s = current_.slots[current_.active[k]]; + for (std::uint8_t j = 0; j < s.count; ++j) { + const auto& c = s.section[j]; + const auto numerator = c.b0 + c.b1 * z1 + c.b2 * z2; + const auto denominator = 1.0 + c.a1 * z1 + c.a2 * z2; + const double mag = std::abs(numerator / denominator); + result += 20.0 * std::log10(std::max(1.0e-12, mag)); + } + } + return std::clamp(result, -160.0, 80.0); + } + +private: + static constexpr double twoPi = 6.283185307179586476925286766559; + struct Section { + double b0=1, b1=0, b2=0, a1=0, a2=0; + double z1[2]{}, z2[2]{}; + float process(int channel, float input) noexcept { + const double x = static_cast(input); + const double out = b0 * x + z1[channel]; + z1[channel] = b1 * x - a1 * out + z2[channel]; + z2[channel] = b2 * x - a2 * out; + return static_cast(out); + } + void denormalGuard() noexcept { + for (int i = 0; i < 2; ++i) { + if (std::abs(z1[i]) < 1.0e-24) z1[i] = 0; + if (std::abs(z2[i]) < 1.0e-24) z2[i] = 0; + } + } + }; + struct Slot { std::array section{}; std::uint8_t count=0; }; + struct Bank { + std::array settings{}; + std::array slots{}; + std::array active{}; + std::uint8_t activeCount=0; + }; + Bank current_{}, previous_{}; + double sampleRate_ = 0.0; + int fadeLength_ = 1, fadeRemaining_ = 0; + float externalWet_=1.0f,externalTarget_=1.0f; + int externalFadeRemaining_=0; + bool prepared_ = false; + float nextExternalMix() noexcept { + if(externalFadeRemaining_>0) { + externalWet_+=(externalTarget_-externalWet_)/ + static_cast(externalFadeRemaining_); + if(--externalFadeRemaining_==0)externalWet_=externalTarget_; + } + return externalWet_; + } + + static bool validBand(std::size_t i, const Band& b, float maxHz) noexcept { + if (i >= bandCount || !std::isfinite(b.frequencyHz) || + !std::isfinite(b.gainDb) || !std::isfinite(b.q) || + b.frequencyHz < 20.0f || b.frequencyHz > maxHz || + b.gainDb < -maxGainDb || b.gainDb > maxGainDb || + b.q < minQ || b.q > maxQ) return false; + return b.slope == Slope::db12 || b.slope == Slope::db24; + } + static bool normalized(Section& s, double b0, double b1, double b2, + double a0, double a1, double a2) noexcept { + if (!std::isfinite(a0) || std::abs(a0) < 1.0e-12) return false; + s.b0 = b0 / a0; s.b1 = b1 / a0; s.b2 = b2 / a0; + s.a1 = a1 / a0; s.a2 = a2 / a0; + return std::isfinite(s.b0) && std::isfinite(s.b1) && std::isfinite(s.b2) && + std::isfinite(s.a1) && std::isfinite(s.a2); + } + static bool makeBiquad(FilterKind kind, const Band& b, double sampleRate, + double q, Section& out) noexcept { + const double omega = twoPi * b.frequencyHz / sampleRate; + const double c = std::cos(omega), s = std::sin(omega); + const double a = std::pow(10.0, static_cast(b.gainDb) / 40.0); + const double alpha = s / (2.0 * q); + switch (kind) { + case FilterKind::bell: + return normalized(out, 1.0+alpha*a, -2.0*c, 1.0-alpha*a, + 1.0+alpha/a, -2.0*c, 1.0-alpha/a); + case FilterKind::highPass: + return normalized(out, (1+c)*0.5, -(1+c), (1+c)*0.5, + 1+alpha, -2*c, 1-alpha); + case FilterKind::lowPass: + return normalized(out, (1-c)*0.5, 1-c, (1-c)*0.5, + 1+alpha, -2*c, 1-alpha); + case FilterKind::lowShelf: { + const double edge = s * std::sqrt(a) * std::sqrt(2.0); + return normalized(out, + a*((a+1)-(a-1)*c+edge), 2*a*((a-1)-(a+1)*c), + a*((a+1)-(a-1)*c-edge), + (a+1)+(a-1)*c+edge, -2*((a-1)+(a+1)*c), + (a+1)+(a-1)*c-edge); + } + case FilterKind::highShelf: { + const double edge = s * std::sqrt(a) * std::sqrt(2.0); + return normalized(out, + a*((a+1)+(a-1)*c+edge), -2*a*((a-1)+(a+1)*c), + a*((a+1)+(a-1)*c-edge), + (a+1)-(a-1)*c+edge, 2*((a-1)-(a+1)*c), + (a+1)-(a-1)*c-edge); + } + } + return false; + } + static bool makeSlot(FilterKind kind, const Band& b, double rate, Slot& result) noexcept { + const bool cut = kind == FilterKind::highPass || kind == FilterKind::lowPass; + result.count = static_cast(cut && b.slope == Slope::db24 ? 2 : 1); + if (result.count == 2) { + return makeBiquad(kind, b, rate, 0.541196100146197, result.section[0]) && + makeBiquad(kind, b, rate, 1.306562964876377, result.section[1]); + } + return makeBiquad(kind, b, rate, cut ? 0.7071067811865476 : b.q, + result.section[0]); + } + static float render(Bank& bank, int channel, float sample) noexcept { + for (std::uint8_t i = 0; i < bank.activeCount; ++i) { + auto& slot = bank.slots[bank.active[i]]; + for (std::uint8_t j = 0; j < slot.count; ++j) + sample = slot.section[j].process(channel, sample); + } + return sample; + } + static void clearTiny(Bank& bank) noexcept { + for (std::uint8_t i = 0; i < bank.activeCount; ++i) { + auto& slot = bank.slots[bank.active[i]]; + for (std::uint8_t j = 0; j < slot.count; ++j) + slot.section[j].denormalGuard(); + } + } +}; +} // namespace armix::builtin_fx diff --git a/engine/builtin_fx/ChannelEqProcessor.h b/engine/builtin_fx/ChannelEqProcessor.h new file mode 100644 index 000000000..8a44e371e --- /dev/null +++ b/engine/builtin_fx/ChannelEqProcessor.h @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "ChannelEq.h" +#include "../core/RealtimeNativeFxControl.h" +#include +#include +#include +#include +#include +#include + +// One ordinary stereo FX processor in the EXISTING ordered ChannelId rack. +// The established FxInstance owns this processor, per-slot identity, bypass, +// graph latency and retirement. No second callback and no fixed pre-VST bank. +// Single message-thread producer; single audio callback consumer. +namespace armix::builtin_fx { +template class EqSpsc final { +public: + bool push(const T& value) noexcept { + const auto w=write_.load(std::memory_order_relaxed); + if(w-read_.load(std::memory_order_acquire)>=Capacity)return false; + data_[w%Capacity]=value; + write_.store(w+1,std::memory_order_release); + return true; + } + bool pop(T& value) noexcept { + const auto r=read_.load(std::memory_order_relaxed); + if(r==write_.load(std::memory_order_acquire))return false; + value=data_[r%Capacity]; + read_.store(r+1,std::memory_order_release); + return true; + } + bool canPush() const noexcept { + return write_.load(std::memory_order_relaxed)- + read_.load(std::memory_order_acquire) write_{0}; + alignas(64) std::atomic read_{0}; + std::array data_{}; +}; + +class ChannelEqProcessor final : public juce::AudioProcessor, + public armix::mixer::RealtimeNativeFxControl { +public: + static constexpr const char* catalogIdentity="armix.builtin.channel-eq.v1"; + struct Completion { + std::uint64_t requestId=0; + std::uint8_t bandIndex=0; + Band band{}; + bool applied=false; + }; + + ChannelEqProcessor() + : juce::AudioProcessor(BusesProperties() + .withInput("Input",juce::AudioChannelSet::stereo(),true) + .withOutput("Output",juce::AudioChannelSet::stereo(),true)) { + // All 8 defaults are owned by the same DSP definition as the graph. + for(std::size_t i=0;i& pcm,juce::MidiBuffer&) override { + juce::ScopedNoDenormals noDenormals; + if(!ready_||pcm.getNumChannels()<2||pcm.getNumSamples()<=0)return; + consumeRealtimeEdits(); + eq_.processStereo(pcm.getWritePointer(0),pcm.getWritePointer(1), + static_cast(pcm.getNumSamples())); + } + void processBlock(juce::AudioBuffer&,juce::MidiBuffer&) override {} + + // AUDIO thread: bounded one control packet per block. The host calls + // this also when fully bypassed; there is no second callback or worker. + void consumeRealtimeEdits() noexcept override { + Edit next; + if(!ready_||!completion_.canPush()||!queued_.pop(next))return; + const bool ok=eq_.applyPreparedBand(next.prepared); + completion_.push({next.requestId, + static_cast(next.prepared.index),next.prepared.band,ok}); + } + + // Control-thread only. Compiles coefficients off realtime, then publishes + // one bounded block-boundary command. Queued is NOT DSP-applied. + bool queueBand(std::size_t index,const Band& band,std::uint64_t id) noexcept { + if(!ready_||!id||index>=ChannelEq::bandCount)return false; + Edit e;e.requestId=id; + if(!ChannelEq::prepareBandEdit(index,band,rate_,e.prepared)) + return false; + return queued_.push(e); + } + // Control-thread only, after a callback completion: accepted_ is never + // accessed by processBlock, so Show/GUI reads cannot race DSP histories. + bool pollCompletion(Completion& result) noexcept { + if(!completion_.pop(result))return false; + if(result.applied&&result.bandIndex acceptedBands() const noexcept { + return accepted_; // CONTROL thread ONLY + } + double acceptedSampleRate() const noexcept {return rate_;} + bool isReady() const noexcept {return ready_;} + void sealForRealtime() noexcept override {published_=true;} + bool stateSnapshotQuiescent() const noexcept override { + // CONTROL only; the caller owns FxInstance's non-blocking capture + // gate, so it cannot race the consumer inside processBlock. + return queued_.empty()&&completion_.empty(); + } + + // The native Show's vendor-state lease already serializes state on the + // control thread. Built-in DSP uses that same per-insert lease and schema, + // not a second fixed channel EQ snapshot. + void getStateInformation(juce::MemoryBlock& destination) override { + juce::MemoryOutputStream output(destination,false); + output.writeInt(0x41504551); // "APEQ" + output.writeInt(1); + for(const auto& b:accepted_) { + output.writeByte(b.enabled?1:0); + output.writeFloat(b.frequencyHz); + output.writeFloat(b.gainDb); + output.writeFloat(b.q); + output.writeByte(static_cast(b.slope)); + } + } + // Only a NEW, unpublished processor is permitted to receive a binary + // Show restore. Mutating a live published DSP would race its callback. + // The Show builder may call this before OR after prepareToPlay; both + // restore the complete bank, and the next audio block starts settled. + // For future ChannelId Show preflight, use the bool-returning method + // rather than JUCE's legacy void setter so errors are not hidden. + bool restoreUnpublishedState(const void* data,int size) { + if(published_||!data|| + size!=8+static_cast(ChannelEq::bandCount)*14 || + !queued_.empty()||!completion_.empty())return false; + juce::MemoryInputStream input(data,static_cast(size),false); + if(input.readInt()!=0x41504551||input.readInt()!=1)return false; + std::array next{}; + for(auto& b:next) { + const int enabled=input.readByte(); + if(enabled!=0&&enabled!=1)return false; + b.enabled=enabled!=0; + b.frequencyHz=input.readFloat(); + b.gainDb=input.readFloat(); + b.q=input.readFloat(); + const int slope=input.readByte(); + if(slope!=12&&slope!=24)return false; + b.slope=slope==24?Slope::db24:Slope::db12; + } + if(!input.isExhausted())return false; + const double validationRate=ready_?rate_:48000.; + const float maxHz=static_cast( + std::min(20000.0,validationRate*0.45)); + for(std::size_t i=0;i20000.f) + return false; + if(!next[i].enabled) + next[i].frequencyHz=std::min(next[i].frequencyHz,maxHz); + ChannelEq::PreparedBandEdit prepared{}; + if(!ChannelEq::prepareBandEdit(i,next[i],validationRate,prepared)) + return false; // all-or-nothing preflight + } + if(ready_) { + for(std::size_t i=0;i queued_{}; + EqSpsc completion_{}; + std::array accepted_{}; + double rate_=0.; // control-owned immutable after prepare + bool ready_=false; // prepared before graph publication + bool published_=false; // CONTROL-only, sealed by FxInstance off callback +}; +} // namespace armix::builtin_fx diff --git a/engine/core/DynamicAcceptedSession.h b/engine/core/DynamicAcceptedSession.h index ec901f2d3..343852940 100644 --- a/engine/core/DynamicAcceptedSession.h +++ b/engine/core/DynamicAcceptedSession.h @@ -246,15 +246,27 @@ class DynamicAcceptedSession final { source,destination,preFader,linear); } + bool setLiveWireGain(std::uint64_t epoch,std::uint64_t revision, + ChannelId source,std::uint64_t edgeId,float gain) noexcept { + const auto* row=accepted_.find(source); + if(!row||!edgeId)return false; + for(const auto& edge:row->sends) + if(edge.edgeId==edgeId&&!edge.primaryOutput) + return setLiveParallelSend(epoch,revision,source,edge.destination,edge.preFader,gain); + return false; + } // This is a callback-ready DELEGATE, not an additional audio renderer. // M3D does not attach it to the production JUCE device until VST/Show // ownership and native output-port parity have been migrated. template bool render(std::uint64_t epoch,const float* const* inputs,int inputCount, float* mainL,float* mainR,int frames,bool muted,Fx&& fx, - float* monitorL=nullptr,float* monitorR=nullptr) noexcept { + float* monitorL=nullptr,float* monitorR=nullptr, + std::span channelPeaksL={}, + std::span channelPeaksR={}) noexcept { return publisher_.render(epoch,inputs,inputCount,mainL,mainR,frames, - muted,std::forward(fx),monitorL,monitorR); + muted,std::forward(fx),monitorL,monitorR, + channelPeaksL,channelPeaksR); } void unpublish() noexcept {publisher_.unpublish();hasHostedFx_=false;} void pollRetirement() noexcept {publisher_.pollRetirement();} diff --git a/engine/core/DynamicChannelFxLeaseBank.h b/engine/core/DynamicChannelFxLeaseBank.h index 46c29f4f8..6547882fa 100644 --- a/engine/core/DynamicChannelFxLeaseBank.h +++ b/engine/core/DynamicChannelFxLeaseBank.h @@ -6,6 +6,8 @@ #include #include #include +#include +#include #include #include #include @@ -33,6 +35,9 @@ class DynamicChannelFxLeaseBank final { ChannelId id{}; ProcessingFormat format=ProcessingFormat::stereo; std::vector inserts; // CONTROL only; no creation on callback + // Reused over revision changes. This flag overrides the effective + // output without changing the individual FxInstance bypass flags. + std::shared_ptr> rackBypassed; }; // Occupied CH1 vendor/Orbit owner remains alive with accepted PCM. @@ -50,7 +55,7 @@ class DynamicChannelFxLeaseBank final { enum class Fault : std::uint8_t { none,invalidEpoch,emptyId,duplicateChannel,tooManyInserts, emptyLease,duplicateInstance,invalidBusLayout,uncompensatedLatency, - missingLegacyIdentity,invalidExternalLease + missingLegacyIdentity,invalidExternalLease,invalidInsertPosition,staleInstance }; DynamicChannelFxLeaseBank()=default; DynamicChannelFxLeaseBank(const DynamicChannelFxLeaseBank&)=delete; @@ -101,6 +106,8 @@ class DynamicChannelFxLeaseBank final { if(b.format!=ProcessingFormat::mono && b.format!=ProcessingFormat::stereo)return Fault::invalidBusLayout; Row row;row.id=b.id;row.format=b.format; + row.rackBypassed=b.rackBypassed?b.rackBypassed: + std::make_shared>(false); // CONTROL allocation row.count=static_cast(b.inserts.size()); for(std::size_t i=0;iprocessor->getTotalNumInputChannels()!=2 || owner->processor->getTotalNumOutputChannels()!=2) return Fault::invalidBusLayout; - // Global live-mixer architecture (Waves LV1/Ableton): - // parallel PRE/POST paths with unequal VST latency require - // true graph-aware PDC. Until that engine exists, never - // admit a plugin that would produce misaligned MAIN/MONITOR, - // AUX/Group or parallel FX Return PCM. This is a CONTROL-only - // processor inspection, NEVER called from realtime. - if(owner->processor->getLatencySamples()!=0) + // Latency is captured once at prepared instance creation. + // The publisher builds graph-aware fan-in delay from it. + if(owner->latencySamples<0 || + owner->latencySamples>armix::dsp::StereoLatencyDelay::maximumSamples || + owner->latencyChanged.load(std::memory_order_acquire)) return Fault::uncompensatedLatency; for(const auto& existing:candidate.rows_) for(std::size_t k=0;kcount;++i) { + const int n=row->raw[i]->latencySamples; + if(n>armix::dsp::StereoLatencyDelay::maximumSamples-total)return -1; + total+=n; + } + return total; + } std::uint64_t epoch() const noexcept{return epoch_;} std::uint64_t revision() const noexcept{return revision_;} std::size_t lanes() const noexcept{return rows_.size();} @@ -174,6 +188,21 @@ class DynamicChannelFxLeaseBank final { (*owner)->bypassRequested.store(bypass,std::memory_order_release); return true; } + bool setRackBypass(std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,ChannelId id, + bool bypass) const noexcept { + if(expectedEpoch!=epoch_||expectedRevision!=revision_||!id.value) + return false; + const auto* row=find(id); + if(!row||!row->rackBypassed)return false; + row->rackBypassed->store(bypass,std::memory_order_release); + return true; + } + bool rackBypassed(ChannelId id) const noexcept { + const auto* row=find(id); + return row&&row->rackBypassed && + row->rackBypassed->load(std::memory_order_acquire); + } // The actual prepared vendor instance is also the native editor owner; // never synthesize a WebView editor or use a catalog name as identity. Lease leaseEditor(std::uint64_t expectedEpoch, @@ -188,6 +217,44 @@ class DynamicChannelFxLeaseBank final { } // CONTROL only: rebind all current vendor leases to a new graph revision. + bool retainsEditor(const Lease& owner) const noexcept { + if(!owner)return false; + for(const auto& row:rows_) + for(std::size_t i=0;iinstanceId!=token)return Fault::staleInstance; + std::vector list; + for(const auto& row:prior.rows_) { + Assignment a;a.id=row.id;a.format=row.format;a.rackBypassed=row.rackBypassed; + for(std::size_t i=0;ifound->inserts.size()||found->inserts.size()>=maxInserts) + return Fault::invalidInsertPosition; + found->inserts.insert(found->inserts.begin()+position,*lease); + } + return prepare(epoch,revision,list,destination,prior.external_); + } + // The same FxInstance keeps editor/state/tail and the audio callback only // sees raw prepared pointers. No new plugin or audio pipeline is created. static Fault reuseRevision(std::uint64_t epoch,std::uint64_t revision, @@ -195,16 +262,72 @@ class DynamicChannelFxLeaseBank final { DynamicChannelFxLeaseBank& destination) { if(!epoch || epoch!=prior.epoch_ || revision<=prior.revision_)return Fault::invalidEpoch; + return reusePreparedOwners(epoch,revision,prior,destination); + } + + // Caller has independently verified identical negotiated audio format. + static Fault rebindSameFormat(std::uint64_t epoch,std::uint64_t revision, + const DynamicChannelFxLeaseBank& prior, + DynamicChannelFxLeaseBank& destination) { + if(epoch<=prior.epoch_ || revision<=prior.revision_) + return Fault::invalidEpoch; + return reusePreparedOwners(epoch,revision,prior,destination); + } + +private: + static Fault reusePreparedOwners(std::uint64_t epoch,std::uint64_t revision, + const DynamicChannelFxLeaseBank& prior, + DynamicChannelFxLeaseBank& destination) { + std::vector retained; + retained.reserve(prior.rows_.size()); + for(const auto& row:prior.rows_) { + Assignment item; + item.id=row.id;item.format=row.format;item.rackBypassed=row.rackBypassed; + item.inserts.reserve(row.count); + for(std::size_t slot=0;slot retained; retained.reserve(prior.rows_.size()); + bool found=false; for(const auto& row:prior.rows_) { Assignment item; - item.id=row.id;item.format=row.format; + item.id=row.id; + item.format=row.id==target?format:row.format; + item.rackBypassed=row.rackBypassed; item.inserts.reserve(row.count); for(std::size_t slot=0;slotrackBypassed && + row->rackBypassed->load(std::memory_order_acquire); for(std::size_t i=0;icount;++i) - row->raw[i]->render(left,right,frames); + row->raw[i]->render(left,right,frames,rackOff); } private: @@ -262,6 +388,7 @@ class DynamicChannelFxLeaseBank final { ChannelId id{}; ProcessingFormat format=ProcessingFormat::stereo; std::uint8_t count=0; + std::shared_ptr> rackBypassed; // persists across revisions std::array owners{}; std::array raw{}; }; diff --git a/engine/core/DynamicChannelRoster.h b/engine/core/DynamicChannelRoster.h index 3b435432d..70113e091 100644 --- a/engine/core/DynamicChannelRoster.h +++ b/engine/core/DynamicChannelRoster.h @@ -58,11 +58,13 @@ enum class ChannelEditFault : std::uint8_t { struct ChannelEdit final { enum class Kind : std::uint8_t { add, duplicate, remove, move, rename, setFormat, setFader, setPan, - setMute, setSolo, addInsertReference, addSendReference, setPrimaryOutput + setMute, setSolo, addInsertReference, addSendReference, setPrimaryOutput, + removeInsertReference, moveInsertReference } kind=Kind::add; ChannelId id{}; // existing channel (except add) ChannelId target{}; // send destination std::size_t position=0; + std::size_t insertPosition=0; // final destination position after removal ChannelRole role=ChannelRole::input; ProcessingFormat format=ProcessingFormat::mono; float value=0.f; @@ -242,6 +244,23 @@ class DynamicChannelRoster final { result.fault=ChannelEditFault::budgetExceeded; else it->insertCatalogIds.push_back(op.text); break; + case ChannelEdit::Kind::removeInsertReference: + case ChannelEdit::Kind::moveInsertReference: { + auto& slots=it->insertCatalogIds; + if(op.position>=slots.size()) {result.fault=ChannelEditFault::invalidPosition;break;} + if(op.kind==ChannelEdit::Kind::removeInsertReference) { + slots.erase(slots.begin()+op.position);break; + } + auto target=seek(op.target); + if(target==candidate.end() || target->role==ChannelRole::monitor || + (target!=it && target->insertCatalogIds.size()>=budget_.maximumInsertSlotsPerChannel) || + op.insertPosition>target->insertCatalogIds.size()-(target==it?1:0)) { + result.fault=ChannelEditFault::invalidPosition;break; + } + auto catalog=slots[op.position];slots.erase(slots.begin()+op.position); + target->insertCatalogIds.insert(target->insertCatalogIds.begin()+op.insertPosition,std::move(catalog)); + break; + } case ChannelEdit::Kind::addSendReference: // OUT is a single unity, POST-fader serial route. Its // pan/fader live on the source strip; only SEND may own @@ -355,7 +374,6 @@ class DynamicChannelRoster final { const auto main=std::find_if(candidate.begin(),candidate.end(), [](const auto& ch){return ch.role==ChannelRole::main;}); if(main==candidate.end()){result.fault=ChannelEditFault::invalidAction;return result;} - const ChannelId mainId=main->id; std::uint64_t stagedNextEdge=nextEdgeId_; if(!assignMissingEdgeIds(candidate,stagedNextEdge)){ result.fault=ChannelEditFault::idExhausted;return result; @@ -390,27 +408,40 @@ class DynamicChannelRoster final { } if(!op.to.value || op.to==op.from || !std::isfinite(op.gain) || op.gain<0.f || op.gain>4.f || - (op.kind==WireChange::Kind::routeOnly && op.to==mainId)){ + (op.kind==WireChange::Kind::routeOnly && op.gain!=1.f)){ result.fault=ChannelEditFault::invalidValue;break; } - const bool already=std::any_of(sends.begin(),sends.end(), + const auto existing=std::find_if(sends.begin(),sends.end(), [&](const auto& s){return s.destination==op.to;}); - if(already && op.kind==WireChange::Kind::connect){ + if(existing!=sends.end() && op.kind==WireChange::Kind::connect){ result.fault=ChannelEditFault::duplicateSend;break; } if(op.kind==WireChange::Kind::routeOnly){ + // ROUTE_ONLY is an exclusive primary OUT choice, including + // MAIN. Replace the previous primary destination (MAIN or + // GROUP), but preserve other deliberate parallel SENDs. sends.erase(std::remove_if(sends.begin(),sends.end(), - [&](const auto& s){return s.destination==mainId;}), + [&](const auto& s){return s.primaryOutput && + s.destination!=op.to;}), sends.end()); - if(already)continue; // retain original edgeId/gain + const auto target=std::find_if(sends.begin(),sends.end(), + [&](const auto& s){return s.destination==op.to;}); + if(target!=sends.end()){ + // Promote the EXACT existing EdgeId to primary instead + // of doubling a parallel SEND in the accepted PCM. + target->primaryOutput=true; + target->gain=1.f;target->preFader=false;target->pan=0.f; + continue; + } } if(sends.size()>=budget_.maximumSendsPerChannel){ result.fault=ChannelEditFault::budgetExceeded;break; } - const bool hasPrimary=std::any_of(sends.begin(),sends.end(), - [](const auto& s){return s.primaryOutput;}); - const bool primary=!hasPrimary && - (op.to==mainId || op.kind==WireChange::Kind::routeOnly); + // CONNECT means a deliberate parallel POST-fader send, even to + // MAIN and even when primary OUT is NONE. Only ROUTE_ONLY may + // establish a primary. This prevents silent promotion of a send + // into an exclusive route and preserves SOURCE ONLY readback. + const bool primary=op.kind==WireChange::Kind::routeOnly; sends.push_back({op.to,op.gain,false,0.f,primary,0}); } if(result.ok()){ @@ -651,6 +682,56 @@ class DynamicChannelRoster final { return result; } + // Restore stable native ChannelIds and EdgeIds without replaying CREATE, + // which would invent new identities, reorder wires and break external FX. + // CONTROL ONLY; no audio is ever published by this operation. + bool restoreExact(std::uint64_t restoredRevision, + std::span entries) { + if(restoredRevision==0 || entries.empty() || + !withinBudget(std::vector(entries.begin(),entries.end()))) + return false; + std::unordered_set ids,edges; + std::uint64_t maxId=0,maxEdge=0; + int mains=0,monitors=0; + for(const auto& ch:entries) { + if(!ch.id.value || ch.id.value==std::numeric_limits::max() || + !ids.insert(ch.id.value).second || + !std::isfinite(ch.faderLinear) || ch.faderLinear<0.f || + ch.faderLinear>4.f || !std::isfinite(ch.pan) || + ch.pan< -1.f || ch.pan>1.f)return false; + maxId=std::max(maxId,ch.id.value); + mains+=ch.role==ChannelRole::main; + monitors+=ch.role==ChannelRole::monitor; + int primary=0; + for(const auto& send:ch.sends) { + if(!send.edgeId || + send.edgeId==std::numeric_limits::max() || + !send.destination.value || send.destination==ch.id || + !edges.insert(send.edgeId).second || + !std::isfinite(send.gain)||send.gain<0.f||send.gain>4.f || + !std::isfinite(send.pan)||send.pan< -1.f||send.pan>1.f) + return false; + primary+=send.primaryOutput; + maxEdge=std::max(maxEdge,send.edgeId); + } + if(primary>1 || (ch.role==ChannelRole::main && !ch.sends.empty()) || + (ch.role==ChannelRole::monitor && !ch.sends.empty()))return false; + } + if(mains!=1||monitors>1)return false; + for(const auto& ch:entries) + for(const auto& send:ch.sends) + if(ids.count(send.destination.value)==0)return false; + auto candidate=std::vector(entries.begin(),entries.end()); + auto index=buildIndex(candidate); + if(index.size()!=candidate.size())return false; + channels_.swap(candidate); + index_.swap(index); + revision_=restoredRevision; + nextId_=maxId+1; + nextEdgeId_=maxEdge+1; + return true; + } + private: static bool assignMissingEdgeIds( std::vector& rows,std::uint64_t& next) { diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index c767600af..a4f3d6ac8 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -28,8 +28,9 @@ class DynamicNativeSessionPublisher final { void* context=nullptr; // unchanged owner.get(), RT raw pointer void (*render)(void*,ChannelId,float*,float*,int) noexcept=nullptr; std::uint64_t deviceEpoch=0,graphRevision=0; + int (*latency)(void*,ChannelId) noexcept=nullptr; bool valid() const noexcept { - return (!owner&&!context&&!render&&!deviceEpoch&&!graphRevision) || + return (!owner&&!context&&!render&&!deviceEpoch&&!graphRevision&&!latency) || (owner&&context==owner.get()&&render&& deviceEpoch>0&&graphRevision>0); } @@ -68,7 +69,8 @@ class DynamicNativeSessionPublisher final { std::uint64_t proposedDeviceEpoch, std::uint64_t activeDeviceEpoch, bool allOutputsDisarmed, - FxPlan fx={},bool verifiedInternalWireOnly=false) { + FxPlan fx={nullptr,nullptr,nullptr,0,0,nullptr},bool verifiedInternalWireOnly=false, + bool verifiedInternalFxOnly=false) { CommitResult report;report.revision=publisher_.lastRevision(); if(!fx.valid() || (fx.owner && (fx.deviceEpoch!=proposedDeviceEpoch || @@ -83,9 +85,15 @@ class DynamicNativeSessionPublisher final { expectedRevision==std::numeric_limits::max()) { report.fault=Fault::staleRevision;return report; } - // Only the canonical native WIRE owner may attest unchanged - // physical patch / device epoch. Other structural edits disarm. - if(!allOutputsDisarmed && !verifiedInternalWireOnly) { + // A latency-budgeted vendor FX lease can be prepared off-RT and + // published on the SAME physical device/patch as the existing + // ChannelId graph. Neither WIRE nor this in-place FX edit can + // change physical pins. Other structural edits still disarm. + if(verifiedInternalFxOnly && !fx.owner) { + report.fault=Fault::invalidCandidate;return report; + } + if(!allOutputsDisarmed && !verifiedInternalWireOnly && + !verifiedInternalFxOnly) { report.fault=Fault::outputArmed;return report; } auto next=std::make_unique(); @@ -96,6 +104,11 @@ class DynamicNativeSessionPublisher final { roster,request,prepared->graph,report.graphError)) { report.fault=Fault::invalidGraph;return report; } + if(!prepared->graph.prepareLatency([&](ChannelId id) noexcept { + return fx.latency?fx.latency(fx.context,id):0; + },request.maxScratchBytes,report.graphError)) { + report.fault=Fault::invalidGraph;return report; + } // The Console data and PCM schedule must originate from one and the // same accepted roster. No browser-side inferred BUS assignments. if(!DynamicConsoleRoutingView::build(roster,prepared->routing)) { @@ -228,12 +241,44 @@ class DynamicNativeSessionPublisher final { bool preFader,float gain) noexcept { return publisher_.updateActiveControl(epoch,revision, [&](Prepared& active) noexcept { - return active.graph.setParallelSendGain( - source,destination,preFader,gain); + if(!std::isfinite(gain)||gain<0.f||gain>4.f)return false; + const bool admitted=std::any_of(active.routing.edges.begin(),active.routing.edges.end(), + [&](const auto& edge){return edge.from==source&&edge.to==destination&& + edge.preFader==preFader&&!edge.primaryOutput;}); + if(!admitted)return false; + if(active.graph.channelScheduled(source)&&!active.graph.setParallelSendGain( + source,destination,preFader,gain))return false; + // A dormant send has no scratch/atomic DSP edge yet. Its + // accepted gain is still editable and seeds the next source + // preparation through the authoritative remembered roster. + // Routing readback is CONTROL-only; AUDIO reads only the + // graph's atomic gain target and preallocated 64-sample slew. + for(auto& edge:active.routing.edges) + if(edge.from==source&&edge.to==destination&& + edge.preFader==preFader&&!edge.primaryOutput) + edge.gainLinear=gain; + for(auto& row:active.routing.channels)if(row.id==source) + for(auto& edge:row.parallelSends) + if(edge.destination==destination&&edge.preFader==preFader) + edge.gain=gain; + return true; }); } + bool setWireGain(std::uint64_t epoch,std::uint64_t revision, + ChannelId source,std::uint64_t edgeId,float gain) noexcept { + const auto* routing=acceptedRouting(epoch,revision); + if(!routing||!edgeId)return false; + for(const auto& edge:routing->edges) + if(edge.edgeId==edgeId&&edge.from==source&&!edge.primaryOutput) + return setParallelSendGain(epoch,revision,source,edge.to,edge.preFader,gain); + return false; + } // CONTROL ONLY; never destroy the last live graph in a callback. + int latencySamples(std::uint64_t epoch,std::uint64_t revision) const noexcept { + const auto* p=publisher_.controlPrepared(epoch,revision); + return p?p->graph.latencySamples():0; + } void unpublish() noexcept {publisher_.unpublish();} void pollRetirement() noexcept {publisher_.pollRetirement();} std::uint64_t acceptedRevision() const noexcept { diff --git a/engine/core/DynamicPreparedMixerBlock.h b/engine/core/DynamicPreparedMixerBlock.h index e9365f83a..196cb1788 100644 --- a/engine/core/DynamicPreparedMixerBlock.h +++ b/engine/core/DynamicPreparedMixerBlock.h @@ -2,6 +2,7 @@ #pragma once #include "DynamicChannelRoster.h" #include "RealtimeSlew64.h" +#include "StereoLatencyDelay.h" #include "RealtimeStereoControlWord.h" #include #include @@ -204,6 +205,61 @@ class DynamicPreparedMixerBlock final { bool contains(ChannelId id) const noexcept { return controlIndex_.find(id.value)!=controlIndex_.end(); } + // CONTROL only. Empty unpatched lanes deliberately have no PCM scratch. + bool channelScheduled(ChannelId id) const noexcept { + const auto found=controlIndex_.find(id.value); + return found!=controlIndex_.end()&& + std::find(renderOrder_.begin(),renderOrder_.end(),found->second)!=renderOrder_.end(); + } + + // CONTROL-only DAG PDC. Every fan-in receives sample-aligned PCM, + // including a destination's own hardware capture and PRE-fader sends. + // A failure discards the unpublished candidate; the old graph stays live. + template + bool prepareLatency(Latency&& latency,std::size_t budget,DynamicGraphError& error) { + std::vector arrival(lanes_.size(),0),output(lanes_.size(),0); + std::size_t bytes=scratch_.size()*sizeof(float); + edgeDelays_.resize(edges_.size());physicalDelays_.resize(lanes_.size()); + sinkDelays_.resize(lanes_.size()); + const auto allocate=[&](armix::dsp::StereoLatencyDelay& delay,int samples) { + if(samples<0||samples>armix::dsp::StereoLatencyDelay::maximumSamples)return false; + const auto need=static_cast(samples)*2*sizeof(float); + if(bytes>budget||need>budget-bytes)return false; + bytes+=need;return delay.prepare(samples); + }; + for(const auto i:renderOrder_) { + const int own=latency(lanes_[i].id); + if(own<0||own>armix::dsp::StereoLatencyDelay::maximumSamples|| + arrival[i]>armix::dsp::StereoLatencyDelay::maximumSamples-own) { + error={DynamicGraphFault::overflow,lanes_[i].id};return false; + } + const auto dryBytes=static_cast(own)*2*sizeof(float); + if(bytes>budget||dryBytes>budget-bytes) { + error={DynamicGraphFault::scratchBudget,lanes_[i].id};return false; + } + bytes+=dryBytes; // prepared VST bypass delay is part of PDC budget + output[i]=arrival[i]+own; + for(std::size_t e=lanes_[i].first;e=0&&!allocate(physicalDelays_[i],arrival[i])) { + error={DynamicGraphFault::scratchBudget,lane.id};return false; + } + for(std::size_t e=lane.first;e reachesOutput(rows.size(),0); - if(next.lanes_[main].enabled)reachesOutput[main]=1; - if(monitor!=notScheduled && next.lanes_[monitor].enabled) - reachesOutput[monitor]=1; - for(auto k=order.rbegin();k!=order.rend();++k) - if(next.lanes_[*k].enabled) - for(const auto& edge:outgoing[*k]) - if(next.lanes_[edge.destination].enabled && - reachesOutput[edge.destination]) - reachesOutput[*k]=1; - // Reverse reachability alone would schedule 128 silent lanes with - // sends to MAIN. Include only actual capture sources, explicit FX - // generator lanes, and descendants; preserve empty MAIN for mute. + // Capture/FX lifetime is independent of output routing. SOURCE ONLY + // must still run inserts and publish its local post-fader meters. + // Schedule signal roots and descendants even with NO path to a sink; + // unpatched empty descriptors remain scratch-free. Keep empty sinks + // so MAIN/MONITOR silence is always rendered deterministically. std::vector hasSignal(rows.size(),0); for(std::size_t i=0;i( @@ -395,7 +440,7 @@ class DynamicPreparedMixerBlock final { hasSignal[edge.destination]=1; } for(const auto i:order) - if(reachesOutput[i] && (hasSignal[i] || i==main || i==monitor)) + if(hasSignal[i] || i==main || i==monitor) next.renderOrder_.push_back(i); // Edges must only target retained scratch lanes. This is distinct // from "reachable from MAIN": a silent incoming lane has no slot. @@ -407,7 +452,7 @@ class DynamicPreparedMixerBlock final { if(frame>0 && active>req.maxScratchBytes/(2*sizeof(float)*frame)) { error.fault=DynamicGraphFault::scratchBudget;return false; } - // One immutable CSR adjacency; only main-reachable edges retained. + // One immutable CSR adjacency over the retained processing lanes. for(std::size_t i=0;i(fade.remaining-1)* - (1.f/static_cast(armix::dsp::RealtimeSlew64::samples)); - const float beforeL=oldL?oldL[f]:0.f; - const float beforeR=oldR?oldR[f]:0.f; - const float afterL=newL?newL[f]:0.f; - const float afterR=newR?newR[f]:0.f; - l[f]+=beforeL+(afterL-beforeL)*alpha; - r[f]+=beforeR+(afterR-beforeR)*alpha; - --fade.remaining; - if(fade.remaining==0){ - fade.current=fade.next; - // New CONTROL requests are consumed next block; - // never change the source mid-sample. - oldL=newL;oldR=newR; - for(int k=f+1;k0) { + const float alpha=1.f-static_cast(fade.remaining-1)/ + static_cast(armix::dsp::RealtimeSlew64::samples); + vl+=((newL?newL[f]:0.f)-vl)*alpha; + vr+=((newR?newR[f]:0.f)-vr)*alpha; + if(--fade.remaining==0){fade.current=fade.next;oldL=newL;oldR=newR;} } + if(!physicalDelays_.empty())physicalDelays_[i].process(vl,vr); + l[f]+=vl;r[f]+=vr; } } if(lane.format==ProcessingFormat::mono) @@ -610,8 +641,9 @@ class DynamicPreparedMixerBlock final { target.applied.retarget(goal); for(int f=0;f initialAudible_,soloAncestors_,soloDescendants_; std::vector blockTargets_; // all allocated before RT std::vector scratch_; + std::vector edgeDelays_,physicalDelays_,sinkDelays_; + int latencySamples_=0; std::unique_ptr channelTargets_; std::unique_ptr[]> sourceTargets_; std::unique_ptr sourceFades_; diff --git a/engine/core/LiveChannelFxGraph.h b/engine/core/LiveChannelFxGraph.h index 281b172f9..769bc927a 100644 --- a/engine/core/LiveChannelFxGraph.h +++ b/engine/core/LiveChannelFxGraph.h @@ -2,6 +2,9 @@ #pragma once #include "PreparedMixerBlock.h" #include "FxBypassEnvelope.h" +#include "StereoLatencyDelay.h" +#include "RealtimeNativeFxControl.h" +#include #include #include #include @@ -27,12 +30,16 @@ class LiveChannelFxGraph final { static constexpr int maxInsertsPerStrip=8; // fixed capacity, no RT allocation using Processor=juce::AudioProcessor; - struct FxInstance final { + struct FxInstance final : juce::AudioProcessorListener { std::unique_ptr processor; + RealtimeNativeFxControl* nativeControl=nullptr; // bound once OFF realtime juce::MidiBuffer midi; const juce::String catalogId; const juce::String name; const juce::String instanceId; // stable through MOVE; never a slot index + const int latencySamples; + std::atomic latencyChanged{false}; + armix::dsp::StereoLatencyDelay dryDelay; std::atomic bypassRequested{false}; armix::dsp::FxBypassEnvelope bypassFade; // RT exclusive state std::vector dryLeft,dryRight; // CONTROL allocation @@ -46,10 +53,17 @@ class LiveChannelFxGraph final { : processor(std::move(p)),catalogId(std::move(id)),name(std::move(label)), instanceId("g5c-"+juce::String(static_cast( nextId.fetch_add(1,std::memory_order_relaxed)))), + latencySamples(processor?processor->getLatencySamples():0), dryLeft(static_cast(maxSamples)), dryRight(static_cast(maxSamples)) { + if(!dryDelay.prepare(latencySamples))throw std::invalid_argument("VST3 latency exceeds prepared delay budget"); midi.ensureSize(1024); bypassFade.prepare(false,processor?processor->getSampleRate():48000.0,0); + if(processor){ + nativeControl=dynamic_cast(processor.get()); + if(nativeControl)nativeControl->sealForRealtime(); + processor->addListener(this); + } } FxInstance(const FxInstance&)=delete; FxInstance& operator=(const FxInstance&)=delete; @@ -57,10 +71,17 @@ class LiveChannelFxGraph final { // Shared by old/new immutable snapshots; last owner drops ONLY on // control-thread retirement after the final RT reader exits. if(processor) { + processor->removeListener(this); try { processor->releaseResources(); } catch(...) { /* vendor cleanup cannot unwind graph retirement */ } } } + void audioProcessorParameterChanged(juce::AudioProcessor*,int,float) override {} + void audioProcessorChanged(juce::AudioProcessor* p, + const juce::AudioProcessorListener::ChangeDetails& details) override { + if(details.latencyChanged && p && p->getLatencySamples()!=latencySamples) + latencyChanged.store(true,std::memory_order_release); + } // G5E: vendor binary state capture is CONTROL only. This is the same // fail-closed gate used by realtime processBlock. While control owns // the gate, a racing muted callback returns silence without waiting. @@ -69,6 +90,13 @@ class LiveChannelFxGraph final { return false; bool ok=false; try { + // Even under the exclusive processor gate, async EQ edits + // can still be QUEUED or have an unconsumed completion. + // Never serialize a stale binary state into a native Show. + if(nativeControl && !nativeControl->stateSnapshotQuiescent()) { + processing.clear(std::memory_order_release); + return false; + } juce::MemoryBlock candidate; processor->getStateInformation(candidate); if(candidate.getSize()<=8U*1024U*1024U) { @@ -79,7 +107,7 @@ class LiveChannelFxGraph final { processing.clear(std::memory_order_release); return ok; } - void render(float* left,float* right,int samples) noexcept { + void render(float* left,float* right,int samples,bool rackBypassed=false) noexcept { if(processing.test_and_set(std::memory_order_acquire)) { contention.fetch_add(1,std::memory_order_relaxed); juce::FloatVectorOperations::clear(left,samples); @@ -87,22 +115,32 @@ class LiveChannelFxGraph final { return; } // G5C: atomic request from control; fade and scratch RT-owned. - bypassFade.request(bypassRequested.load(std::memory_order_relaxed)); - if(bypassFade.fullyBypassed()) { - processing.clear(std::memory_order_release); - return; - } + // Master rack bypass affects the WET/DRY envelope, never the remembered insert preference. + bypassFade.request(rackBypassed || bypassRequested.load(std::memory_order_relaxed)); if(samples<=0 || static_cast(samples)>dryLeft.size()) { juce::FloatVectorOperations::clear(left,std::max(0,samples)); juce::FloatVectorOperations::clear(right,std::max(0,samples)); processing.clear(std::memory_order_release); return; } - const bool fading=bypassFade.transitioning(); - if(fading) { - juce::FloatVectorOperations::copy(dryLeft.data(),left,samples); - juce::FloatVectorOperations::copy(dryRight.data(),right,samples); + // Drain at most one native EQ control edit even while bypassed. + // Fully bypassed plugins otherwise never call processBlock, which + // would strand pending GUI commands until users turned them ON. + if(nativeControl && bypassFade.fullyBypassed()) + nativeControl->consumeRealtimeEdits(); + // Keep bypass at the SAME declared latency as wet, including + // rack bypass and disabled slots. PDC never changes on a scalar. + for(int i=0;i(i)]=l; + dryRight[static_cast(i)]=r; + } + if(bypassFade.fullyBypassed()||latencyChanged.load(std::memory_order_acquire)) { + juce::FloatVectorOperations::copy(left,dryLeft.data(),samples); + juce::FloatVectorOperations::copy(right,dryRight.data(),samples); + processing.clear(std::memory_order_release);return; } + const bool fading=bypassFade.transitioning(); try { float* planar[]{left,right}; juce::AudioBuffer buffer(planar,2,samples); @@ -227,6 +265,17 @@ class LiveChannelFxGraph final { fx->bypassRequested.store(bypass,std::memory_order_release); return true; } + // One atomic rack override per channel. Individual slot bypass flags stay + // unchanged; ON restores the previous enabled/disabled combination. + bool setRackBypass(int strip,bool bypass) noexcept { + if(strip<0||strip>=fxSlots)return false; + rackBypassed_[strip].store(bypass,std::memory_order_release); + return true; + } + bool rackBypassed(int strip) const noexcept { + return strip>=0&&stripcatalogId!=catalogId)return false; for(int i=0;i=fxSlots)return; const int count=counts_[strip]; // immutable, prepared OFF RT + const bool rackOff=rackBypassed_[strip].load(std::memory_order_acquire); if(count>0) { for(int slot=0;slotrender(l,r,samples); // no shared_ptr copies or RT heap use + instance->render(l,r,samples,rackOff); // existing 8ms fade; no RT allocation } } else if(strip==0 && externalFx) + // The legacy CH1 callback owns its own per-slot smooth rack + // bypass. Never skip it abruptly or strip out its FX tail. externalFx(externalContext,strip,l,r,samples); }; if(monitorEnabled_ && (!monitorL||!monitorR))return false; @@ -315,6 +371,7 @@ class LiveChannelFxGraph final { RealtimeStripControls controls_ {}; FxBank processors_ {}; std::array counts_ {}; + std::array,fxSlots> rackBypassed_{}; // CONTROL write; one RT read per lane int activeInserts_=0; int pluginQuantum_=512; int mainOutputLeft_=0,mainOutputRight_=1; diff --git a/engine/core/NativeFxRackTransaction.h b/engine/core/NativeFxRackTransaction.h new file mode 100644 index 000000000..30a8261b2 --- /dev/null +++ b/engine/core/NativeFxRackTransaction.h @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "DynamicChannelFxLeaseBank.h" +namespace armix::mixer { +// CONTROL-only preparation. Roster and actual processor inventory move +// together; a failed candidate never mutates the currently audible graph. +inline bool prepareNativeFxRackEdit(std::uint64_t epoch,std::uint64_t graphRevision, + std::uint64_t rosterRevision,const DynamicChannelRoster& prior, + const DynamicChannelFxLeaseBank& bank,ChannelId source,std::size_t slot, + const juce::String& token,ChannelId target,std::size_t position, + DynamicChannelRoster& next,DynamicChannelFxLeaseBank& nextBank) { + if(bank.epoch()!=epoch||bank.revision()!=graphRevision||prior.revision()!=rosterRevision) + return false; + const auto* from=prior.find(source); + const auto* to=target.value?prior.find(target):nullptr; + const auto* lease=bank.ownerForControl(source,slot); + if(!from||!lease||!*lease||(*lease)->instanceId!=token|| + from->insertCatalogIds.size()!=bank.insertCount(source)|| + slot>=from->insertCatalogIds.size()|| + from->insertCatalogIds[slot]!=(*lease)->catalogId.toStdString()|| + (target.value&&(!to||to->role==ChannelRole::monitor|| + to->insertCatalogIds.size()!=bank.insertCount(target))))return false; + DynamicChannelFxLeaseBank prepared; + if(DynamicChannelFxLeaseBank::editOwned(epoch,graphRevision+1,bank,source,slot, + token,target,position,to?to->format:from->format,prepared)!= + DynamicChannelFxLeaseBank::Fault::none)return false; + auto roster=prior; + ChannelEdit edit;edit.kind=target.value?ChannelEdit::Kind::moveInsertReference: + ChannelEdit::Kind::removeInsertReference; + edit.id=source;edit.position=slot;edit.target=target;edit.insertPosition=position; + if(!roster.edit(rosterRevision,std::span(&edit,1)).ok())return false; + next=std::move(roster);nextBank=std::move(prepared);return true; +} +} diff --git a/engine/core/RealtimeNativeFxControl.h b/engine/core/RealtimeNativeFxControl.h new file mode 100644 index 000000000..b15eab95d --- /dev/null +++ b/engine/core/RealtimeNativeFxControl.h @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +// Optional native FX control mailbox hook. The existing FxInstance invokes +// this on the SAME audio callback before its bypass fast path; the callback +// may drain one bounded edit even when an insert is fully bypassed. +// No allocation, lock, dynamic cast, UI or second renderer in this interface. +namespace armix::mixer { +struct RealtimeNativeFxControl { + virtual ~RealtimeNativeFxControl() = default; + virtual void consumeRealtimeEdits() noexcept = 0; + // CONTROL-only lifecycle: after FxInstance accepts this processor, a + // vendor-state restore must not mutate published audio-owned filters. + virtual void sealForRealtime() noexcept {} + // CONTROL-only Show capture guard: pending DSP edits must first be + // consumed AND acknowledged, otherwise a saved state could be stale. + virtual bool stateSnapshotQuiescent() const noexcept {return true;} +}; +} // namespace armix::mixer diff --git a/engine/core/RealtimeRoutePublisher.h b/engine/core/RealtimeRoutePublisher.h index 5c2452392..1e72f59c3 100644 --- a/engine/core/RealtimeRoutePublisher.h +++ b/engine/core/RealtimeRoutePublisher.h @@ -35,7 +35,8 @@ class RealtimeRoutePublisher final { }; class ReadLease final { public: - explicit ReadLease (RealtimeRoutePublisher& owner) noexcept : owner_(&owner) { + explicit ReadLease (RealtimeRoutePublisher& owner,bool skip=false) noexcept : owner_(&owner) { + if(skip)return; auto activity=owner_->activity_.load(std::memory_order_seq_cst); // Do not spin/wait inside the audio callback. One silent block is // preferable to scheduling jitter while control thread publishes. @@ -95,6 +96,25 @@ class RealtimeRoutePublisher final { return Result::applied; } + // CONTROL only, after proving identical hardware layout and format. + // Keep the prepared compatibility plan and its revision. Run the paired + // publication while no reader can observe or acquire this snapshot. + template + bool rebindQuiescent(std::uint64_t from,std::uint64_t to, + Commit&& commit) noexcept { + static_assert(noexcept(commit())); + if(!owned_ || active_.load(std::memory_order_seq_cst)!=owned_.get() || + owned_->deviceEpoch!=from || !from || to<=from)return false; + std::uint32_t idle=0; + if(!activity_.compare_exchange_strong(idle,writerFlag, + std::memory_order_seq_cst)) + return false; + const bool accepted=commit(); + if(accepted)owned_->deviceEpoch=to; + activity_.store(0,std::memory_order_seq_cst); + return accepted; + } + // Immediately gate the last route to silence. Do NOT delete a graph // while the audio callback could own a ReadLease to its snapshot. void unpublish() noexcept { @@ -140,7 +160,7 @@ class RealtimeRoutePublisher final { owned_->graphRevision==expectedRevision ?owned_->prepared.get():nullptr; } - [[nodiscard]] ReadLease acquire() noexcept {return ReadLease(*this);} + [[nodiscard]] ReadLease acquire(bool skip=false) noexcept {return ReadLease(*this,skip);} std::uint64_t lastRevision() const noexcept {return revision_;} // CONTROL std::size_t pendingRetirements() const noexcept {return retiredCount_;} // CONTROL bool readersPresent() const noexcept { diff --git a/engine/core/StereoLatencyDelay.h b/engine/core/StereoLatencyDelay.h new file mode 100644 index 000000000..804530e16 --- /dev/null +++ b/engine/core/StereoLatencyDelay.h @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include + +namespace armix::dsp { +// CONTROL prepares storage; AUDIO owns the cursor. Zero delay is a true +// passthrough. No allocation, interpolation, lock or modulo in the sample path. +class StereoLatencyDelay final { +public: + static constexpr int maximumSamples=131072; + bool prepare(int samples) { + if(samples<0 || samples>maximumSamples)return false; + data_.assign(static_cast(samples)*2,0.f);cursor_=0; + return true; + } + void process(float& left,float& right) noexcept { + if(data_.empty())return; + const float l=data_[cursor_],r=data_[cursor_+1]; + data_[cursor_]=left;data_[cursor_+1]=right; + left=l;right=r;cursor_+=2; + if(cursor_==data_.size())cursor_=0; + } +private: + std::vector data_; + std::size_t cursor_=0; +}; +} diff --git a/engine/core/UnifiedLegacyProductionAdmission.h b/engine/core/UnifiedLegacyProductionAdmission.h index 37d431806..ba55ee45a 100644 --- a/engine/core/UnifiedLegacyProductionAdmission.h +++ b/engine/core/UnifiedLegacyProductionAdmission.h @@ -59,6 +59,12 @@ struct UnifiedLegacyAccepted final { fxOwners->setInsertBypass(epoch,revision,id,slot, instanceId,bypass); } + bool setFxRackBypass(const DynamicNativeSessionPublisher& publisher, + std::uint64_t epoch,std::uint64_t revision, + ChannelId id,bool bypass) const noexcept { + return matches(publisher,epoch,revision) && + fxOwners->setRackBypass(epoch,revision,id,bypass); + } DynamicChannelFxLeaseBank::Lease leaseFxEditor( const DynamicNativeSessionPublisher& publisher, std::uint64_t epoch,std::uint64_t revision,ChannelId id, @@ -180,6 +186,9 @@ class UnifiedLegacyProductionAdmission final { plan.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { (*static_cast(ctx))(id,l,r,n); }; + plan.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; plan.deviceEpoch=deviceEpoch;plan.graphRevision=expectedPcmRevision+1; result.native=publisher.commit(candidate.roster,candidate.request, expectedPcmRevision,deviceEpoch,currentHardwareEpoch, diff --git a/engine/device/AudioSetupRecoveryPolicy.h b/engine/device/AudioSetupRecoveryPolicy.h new file mode 100644 index 000000000..a67a52db7 --- /dev/null +++ b/engine/device/AudioSetupRecoveryPolicy.h @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +namespace armix::device { +// A pure CONTROL-thread decision: the selected ASIO driver may keep the same +// JUCE name while its ASIO4ALL/WDM pins were reconfigured externally. +// Never reuse the old live pin mask when the device is no longer open. +// A closed prior device is not a valid rollback target. +struct AudioSetupRecoveryPolicy final { + struct Plan final { + bool reuseActivePins; + bool recreateDevice; + bool priorKnownOpen; + bool verifyAsioPinIdentity; + }; + static constexpr Plan select(bool sameEndpoint, bool priorOpen, + bool isAsio, bool completePinSelection) noexcept { + return { + sameEndpoint && priorOpen && completePinSelection, + sameEndpoint && (!priorOpen || isAsio), + priorOpen, + sameEndpoint && priorOpen && isAsio && completePinSelection + }; + } +}; +} // namespace armix::device diff --git a/engine/device/DeviceSessionTransitionPolicy.h b/engine/device/DeviceSessionTransitionPolicy.h new file mode 100644 index 000000000..5eab14f16 --- /dev/null +++ b/engine/device/DeviceSessionTransitionPolicy.h @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include + +namespace armix::device { + +// The mixer document is not a hardware binding. An epoch change invalidates +// PCM admission, NOT the operator's authored controls, WIREs or VST3 leases. +// All decisions happen on the JUCE message/control thread; no audio callback +// may read or mutate the retained document. +enum class DeviceSessionDecision : std::uint8_t { + rejectedDevice, + retainBoundMixer, + createFirstSilentMixer, + retainUnboundMixer +}; + +[[nodiscard]] constexpr DeviceSessionDecision decideDeviceSession( + bool verifiedDevice, bool mixerReadyForCurrentEpoch, + bool hasAuthoredMixerContent) noexcept +{ + if (!verifiedDevice) return DeviceSessionDecision::rejectedDevice; + if (mixerReadyForCurrentEpoch) return DeviceSessionDecision::retainBoundMixer; + return hasAuthoredMixerContent ? DeviceSessionDecision::retainUnboundMixer + : DeviceSessionDecision::createFirstSilentMixer; +} + +// Retained processors stay on their prepared rate. A changed buffer is +// safe when every callback chunk fits both the old graph and the new device. +[[nodiscard]] constexpr int retainedMixerQuantum( + int preparedFrames,int currentFrames,int maximumFrames, + bool rateChanged,bool hasPreparedEffects) noexcept +{ + if(preparedFrames<=0 || currentFrames<=0 || + preparedFrames>maximumFrames || currentFrames>maximumFrames || + (rateChanged && hasPreparedEffects))return 0; + return std::min(preparedFrames,currentFrames); +} + +} // namespace armix::device diff --git a/engine/diagnostics/CrackleEvidenceWindow.h b/engine/diagnostics/CrackleEvidenceWindow.h index e6d1b23b2..2d8941cc9 100644 --- a/engine/diagnostics/CrackleEvidenceWindow.h +++ b/engine/diagnostics/CrackleEvidenceWindow.h @@ -37,12 +37,26 @@ class CrackleEvidenceWindow final std::uint64_t count = 0; bool available = false; }; + // OS memory measurements are sampled ONLY by the message thread. + // "Page faults" includes soft/minor faults; NOT a hard-fault / disk + // paging counter and never proof of a missed hardware callback. + struct MemoryPressure + { + std::uint32_t systemLoadPercent = 0; + std::uint64_t availablePhysicalMiB = 0; + std::uint64_t processWorkingSetMiB = 0; + std::uint64_t processPrivateCommitMiB = 0; + std::uint64_t processPageFaults = 0; + bool systemAvailable = false; + bool processAvailable = false; + }; struct Sample { std::uint64_t atMs = 0; std::uint64_t deviceGeneration = 0; std::string routeScope; // stable backend, endpoints, mode and output gates std::array counters {}; + MemoryPressure memory {}; bool connected = false; }; struct Delta @@ -60,6 +74,10 @@ class CrackleEvidenceWindow final Reason reason = Reason::insufficientHistory; std::uint64_t elapsedMs = 0; std::array changes {}; + MemoryPressure memoryBefore {}, memoryAtMark {}; + std::uint32_t peakLoadPercent = 0; + bool loadComparable = false; + Delta processPageFaults {}; bool ready() const noexcept { return reason == Reason::ready; } }; @@ -129,6 +147,34 @@ class CrackleEvidenceWindow final } result.reason = Reason::ready; result.elapsedMs = now.atMs - baseline->atMs; + result.memoryBefore = baseline->memory; + result.memoryAtMark = now.memory; + // Pressure and page-fault samples share the exact same validated + // route/generation/time window as the audio timing counters. + if(baseline->memory.systemAvailable && now.memory.systemAvailable) + { + result.loadComparable = true; + result.peakLoadPercent = now.memory.systemLoadPercent; + for(std::size_t i=0; iatMs || + candidate.atMs > now.atMs)continue; + if(!candidate.memory.systemAvailable) { + result.loadComparable=false;break; + } + if(candidate.memory.systemLoadPercent>result.peakLoadPercent) + result.peakLoadPercent=candidate.memory.systemLoadPercent; + } + } + if(baseline->memory.processAvailable && + now.memory.processAvailable && + now.memory.processPageFaults >= baseline->memory.processPageFaults) + result.processPageFaults = { + now.memory.processPageFaults-baseline->memory.processPageFaults, + true + }; for (std::size_t i=0; icounters[i]; diff --git a/installer/ArSonMix.iss b/installer/ArSonMix.iss new file mode 100644 index 000000000..ed7999f29 --- /dev/null +++ b/installer/ArSonMix.iss @@ -0,0 +1,38 @@ +; ArSonMix x64 RC from exact independently verified FAT app, no new DSP or GUI. +#ifndef SourceRoot + #error "Supply /DSourceRoot with SHA-verified staging directory" +#endif +#ifndef OutputRoot + #error "Supply /DOutputRoot with destination directory" +#endif +[Setup] +AppId=ArSonMix.LiveStudio +AppName=ArSonMix +AppVersion=0.1.0-rc.1 +AppVerName=ArSonMix RC (hardware FAT pending) +AppPublisher=ArSonMix +AppPublisherURL=https://masarray.github.io/arsonmix/ +DefaultDirName={localappdata}\Programs\ArSonMix +PrivilegesRequired=lowest +DisableProgramGroupPage=yes +ArchitecturesAllowed=x64compatible +ArchitecturesInstallIn64BitMode=x64compatible +MinVersion=10.0.17763 +WizardStyle=modern +OutputDir={#OutputRoot} +OutputBaseFilename=ArSonMix-Windows-x64-Setup-UNQUALIFIED +SetupIconFile={#SourceRoot}\arsonmix-app.ico +UninstallDisplayIcon={app}\ArSonMix.exe +Compression=lzma2 +SolidCompression=yes +CloseApplications=no +RestartApplications=no +[Files] +Source: "{#SourceRoot}\verified-gui.exe"; DestDir: "{app}"; DestName: "ArSonMix.exe"; Flags: ignoreversion +Source: "{#SourceRoot}\BUILD_PROVENANCE.json"; DestDir: "{app}"; Flags: ignoreversion +Source: "{#SourceRoot}\README.md"; DestDir: "{app}"; Flags: ignoreversion +Source: "{#SourceRoot}\FactoryFX\*"; DestDir: "{app}\FactoryFX"; Flags: ignoreversion recursesubdirs createallsubdirs skipifsourcedoesntexist +[Icons] +Name: "{autoprograms}\ArSonMix"; Filename: "{app}\ArSonMix.exe"; WorkingDir: "{app}" +; No Run or UninstallDelete: do not auto-activate live audio or erase +; AppData Studio. Do not install portable_mode.txt. diff --git a/integration/ApprovedNativeControlIntent.h b/integration/ApprovedNativeControlIntent.h index e5062b9a3..50434f74d 100644 --- a/integration/ApprovedNativeControlIntent.h +++ b/integration/ApprovedNativeControlIntent.h @@ -9,6 +9,8 @@ #include #include #include +#include +#include // INTEGRATOR M3-B: bridge the approved /preview/ control ABI to the ONE // native ChannelId PCM owner from ENGINE #266. Translation is CONTROL-thread @@ -68,6 +70,269 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( return reject("STALE_NATIVE_CONTROL_REVISION"); if(!request.isString() || request.toString().isEmpty() || request.toString().length()>128)return reject("INVALID_REQUEST_ID"); + // A true ChannelId processing M/ST edit is structural PCM, never an + // M4 ordinal patch. Check both independent producer and public contracts + // before passing device/graph/roster-fenced native identities. + if(op=="SET_PROCESSING_FORMAT") { + if(!approvedHasOperation(caps.getProperty("supportedOps",{}), + "SET_PROCESSING_FORMAT") || + !approvedHasOperation(installedBus.getProperty("supportedOps",{}), + "NATIVE_SET_PROCESSING_FORMAT")) + return reject("NATIVE_PROCESSING_FORMAT_NOT_ADMITTED"); + juce::var owner,producer; + for(const auto& row:*rows.getArray()) + if(row.getProperty("id","").toString()==ids.toString())owner=row; + for(const auto& row:*nativeRows.getArray()) + if(row.getProperty("id","").toString()==ids.toString())producer=row; + if(!owner.isObject()||!producer.isObject()|| + owner.getProperty("role","").toString()!="INPUT" || + producer.getProperty("role","").toString()!="INPUT" || + owner.getProperty("processingFormat","").toString()!= + producer.getProperty("format","").toString()) + return reject("PROCESSING_FORMAT_SOURCE_NOT_ADMITTED"); + const auto payload=publicIntent.getProperty("payload",{}); + const auto fmt=payload.getProperty("format",{}); + if(!payload.isObject()||!fmt.isString()|| + (fmt.toString()!="MONO"&&fmt.toString()!="STEREO")|| + fmt.toString()==producer.getProperty("format","").toString()) + return reject("INVALID_NATIVE_PROCESSING_FORMAT"); + auto checked=std::make_unique(); + checked->setProperty("format",fmt); + auto converted=std::make_unique(); + converted->setProperty("requestId",request); + converted->setProperty("deviceEpoch",epoch); + converted->setProperty("baseGraphRevision",revision); + converted->setProperty("baseRosterRevision",roster); + converted->setProperty("targetChannelId",ids); + converted->setProperty("operation","NATIVE_SET_PROCESSING_FORMAT"); + converted->setProperty("payload",juce::var(checked.release())); + return {juce::var(converted.release()),{}}; + } + if(op=="SET_WIRE_GAIN") { + if(!approvedHasOperation(caps.getProperty("supportedOps",{}),"SET_WIRE_GAIN")|| + !approvedHasOperation(installedBus.getProperty("supportedOps",{}),"NATIVE_SET_WIRE_GAIN")) + return reject("NATIVE_WIRE_GAIN_NOT_ADMITTED"); + const auto payload=publicIntent.getProperty("payload",{}); + const auto edgeId=payload.getProperty("edgeId",{}); + double gain=0.; + if(!nativeV8Decimal(edgeId)||!nativeV8Number(payload.getProperty("gainLinear",{}),gain)|| + gain<0.||gain>4.)return reject("INVALID_NATIVE_WIRE_GAIN"); + juce::var publicEdge,nativeEdge; + const auto pub=graph.getProperty("edges",{}),native=installedBus.getProperty("edges",{}); + if(!pub.isArray()||!native.isArray())return reject("WIRE_EDGE_INVENTORY_UNAVAILABLE"); + for(const auto& e:*pub.getArray()) + if(e.getProperty("edgeId",{})==edgeId&&e.getProperty("from",{})==ids)publicEdge=e; + for(const auto& e:*native.getArray()) + if(e.getProperty("edgeId",{})==edgeId&&e.getProperty("from",{})==ids)nativeEdge=e; + if(!publicEdge.isObject()||!nativeEdge.isObject())return reject("WIRE_STALE_EDGE"); + const auto primary=publicEdge.getProperty("primaryOutput",{}); + const auto nativePrimary=nativeEdge.getProperty("primaryOutput",{}); + if(!primary.isBool()||!nativePrimary.isBool()||static_cast(primary)|| + static_cast(nativePrimary))return reject("WIRE_PRIMARY_GAIN_FIXED"); + if(publicEdge.getProperty("enabled",{})!=juce::var(true)|| + publicEdge.getProperty("to",{})!=nativeEdge.getProperty("to",{})|| + publicEdge.getProperty("tap",{})!=nativeEdge.getProperty("tap",{})) + return reject("WIRE_EDGE_IDENTITY_MISMATCH"); + auto checked=std::make_unique(); + checked->setProperty("edgeId",edgeId);checked->setProperty("gainLinear",gain); + auto converted=std::make_unique(); + converted->setProperty("requestId",request);converted->setProperty("deviceEpoch",epoch); + converted->setProperty("baseGraphRevision",revision); + converted->setProperty("baseRosterRevision",roster);converted->setProperty("targetChannelId",ids); + converted->setProperty("operation","NATIVE_SET_WIRE_GAIN"); + converted->setProperty("payload",juce::var(checked.release())); + return {juce::var(converted.release()),{}}; + } + // P1 WIRE: the previous GUI emitted APPLY_WIRE_TRANSACTION, but this + // translator accepted only fader/pan/mute/solo and silently left native + // BUS routing unavailable. Validate the exact accepted ChannelId/EdgeId + // inventory and public+native capabilities BEFORE compiling any changes. + if(op=="APPLY_WIRE_TRANSACTION") { + if(!approvedHasOperation(caps.getProperty("supportedOps",{}), + "APPLY_WIRE_TRANSACTION") || + !approvedHasOperation(installedBus.getProperty("supportedOps",{}), + "NATIVE_APPLY_WIRE_TRANSACTION")) + return reject("NATIVE_WIRE_NOT_ADMITTED"); + juce::var owner,producer; + for(const auto& row:*rows.getArray()) + if(row.getProperty("id","").toString()==ids.toString())owner=row; + for(const auto& row:*nativeRows.getArray()) + if(row.getProperty("id","").toString()==ids.toString())producer=row; + if(!owner.isObject()||!producer.isObject()|| + owner.getProperty("role","").toString()!= + producer.getProperty("role","").toString()) + return reject("WIRE_SOURCE_NOT_ADMITTED"); + const auto sourceRole=owner.getProperty("role","").toString(); + if(sourceRole!="INPUT"&&sourceRole!="GROUP"&&sourceRole!="FX_RETURN") + return reject("WIRE_INVALID_SOURCE_ROLE"); + const auto sourcePayload=publicIntent.getProperty("payload",{}); + const auto rawChanges=sourcePayload.getProperty("changes",{}); + const auto* changes=rawChanges.getArray(); + if(!changes||changes->isEmpty()||changes->size()>64) + return reject("WIRE_INVALID_BATCH"); + const auto pubEdges=graph.getProperty("edges",{}); + const auto nativeEdges=installedBus.getProperty("edges",{}); + if(!pubEdges.isArray()||!nativeEdges.isArray()) + return reject("WIRE_EDGE_INVENTORY_UNAVAILABLE"); + juce::Array verified; + for(const auto& edit:*changes) { + if(!edit.isObject())return reject("WIRE_INVALID_EDIT"); + const auto kind=edit.getProperty("op","").toString(); + const auto from=edit.getProperty("from",{}); + if(from.toString()!=ids.toString()|| + (kind!="CONNECT" && kind!="REMOVE" && + kind!="RETARGET" && kind!="ROUTE_ONLY")) + return reject("WIRE_SOURCE_OR_OPERATION_INVALID"); + auto item=std::make_unique(); + item->setProperty("op",kind); + item->setProperty("from",ids); + if(kind=="REMOVE" || kind=="RETARGET") { + const auto edgeId=edit.getProperty("edgeId",{}); + if(!nativeV8Decimal(edgeId))return reject("WIRE_EDGE_ID_INVALID"); + bool pubFound=false,nativeFound=false; + for(const auto& e:*pubEdges.getArray()) + if(e.getProperty("edgeId","").toString()==edgeId.toString() && + e.getProperty("from","").toString()==ids.toString()) + pubFound=true; + for(const auto& e:*nativeEdges.getArray()) + if(e.getProperty("edgeId","").toString()==edgeId.toString() && + e.getProperty("from","").toString()==ids.toString()) + nativeFound=true; + if(!pubFound||!nativeFound)return reject("WIRE_STALE_EDGE"); + item->setProperty("edgeId",edgeId); + } + if(kind=="CONNECT" || kind=="RETARGET" || kind=="ROUTE_ONLY") { + const auto to=edit.getProperty("to",{}); + if(!nativeV8Decimal(to) || to.toString()==ids.toString()) + return reject("WIRE_INVALID_DESTINATION"); + juce::String role; + juce::String nativeRole; + for(const auto& row:*rows.getArray()) + if(row.getProperty("id","").toString()==to.toString()) + role=row.getProperty("role","").toString(); + for(const auto& row:*nativeRows.getArray()) + if(row.getProperty("id","").toString()==to.toString()) + nativeRole=row.getProperty("role","").toString(); + // INPUT describes a channel's hardware-source capability, + // not an exclusive source selector. The same channel also + // receives internal PCM, summed before its inserts/fader. + // Require matching native roles, not a GUI-only destination. + if(nativeRole!=role || + (role!="INPUT"&&role!="GROUP"&&role!="FX_RETURN"&&role!="MAIN")) + return reject("WIRE_UNSUPPORTED_DESTINATION"); + // MAIN is a supported ROUTE_ONLY target: the roster makes + // exactly one serial unity-gain primary edge, no double dry. + + item->setProperty("to",to); + } + if(kind=="CONNECT" || kind=="ROUTE_ONLY") { + double gain=0.; + if(edit.getProperty("tap","").toString()!="POST_FADER" || + !nativeV8Number(edit.getProperty("gainLinear",{}),gain) || + gain<0.||gain>4.|| + (kind=="ROUTE_ONLY"&&gain!=1.)) + return reject("WIRE_UNSUPPORTED_TAP_OR_GAIN"); + item->setProperty("gainLinear",gain); + } + verified.add(juce::var(item.release())); + } + auto payload=std::make_unique(); + payload->setProperty("changes",juce::var(verified)); + auto converted=std::make_unique(); + converted->setProperty("requestId",request); + converted->setProperty("deviceEpoch",epoch); + converted->setProperty("baseGraphRevision",revision); + converted->setProperty("baseRosterRevision",roster); + converted->setProperty("targetChannelId",ids); + converted->setProperty("operation","NATIVE_APPLY_WIRE_TRANSACTION"); + converted->setProperty("payload",juce::var(payload.release())); + return {juce::var(converted.release()),{}}; + } + if(op=="REMOVE_INSERT"||op=="MOVE_INSERT") { + const bool moving=op=="MOVE_INSERT"; + if(!approvedHasOperation(caps.getProperty("supportedOps",{}),moving?"MOVE_INSERT":"REMOVE_INSERT")|| + !approvedHasOperation(installedBus.getProperty("supportedOps",{}),moving?"NATIVE_MOVE_INSERT":"NATIVE_REMOVE_INSERT")) + return reject("NATIVE_FX_RACK_NOT_ADMITTED"); + const auto payload=publicIntent.getProperty("payload",{}); + const auto slot=payload.getProperty("slot",{}),token=payload.getProperty("instanceId",{}); + if(!slot.isInt()||static_cast(slot)<0||static_cast(slot)>=8|| + !token.isString()||token.toString().isEmpty())return reject("INVALID_FX_INSTANCE"); + const int index=static_cast(slot);juce::var from,nativeFrom; + for(const auto& row:*rows.getArray())if(row.getProperty("id",{})==ids)from=row; + for(const auto& row:*nativeRows.getArray())if(row.getProperty("id",{})==ids)nativeFrom=row; + const auto pub=from.getProperty("inserts",{}),actual=nativeFrom.getProperty("inserts",{}); + if(!pub.isArray()||!actual.isArray()||pub.size()!=actual.size()||index>=pub.size()|| + pub[index].getProperty("id",{})!=token||actual[index].getProperty("instanceId",{})!=token) + return reject("STALE_FX_INSTANCE"); + auto args=std::make_unique();args->setProperty("slot",slot); + args->setProperty("instanceId",token); + if(moving) { + const auto target=payload.getProperty("toChannelId",{}),position=payload.getProperty("toSlot",{}); + if(!nativeV8Decimal(target)||!position.isInt()||static_cast(position)<0) + return reject("INVALID_FX_DESTINATION"); + juce::var to,nativeTo; + for(const auto& row:*rows.getArray())if(row.getProperty("id",{})==target)to=row; + for(const auto& row:*nativeRows.getArray())if(row.getProperty("id",{})==target)nativeTo=row; + const auto fx=to.getProperty("inserts",{}),nfx=nativeTo.getProperty("inserts",{}); + const auto role=to.getProperty("role",{}).toString(); + const int count=fx.isArray()?fx.size():-1; + if(!to.isObject()||!nativeTo.isObject()||role!=nativeTo.getProperty("role",{}).toString()|| + (role!="INPUT"&&role!="GROUP"&&role!="FX_RETURN"&&role!="MAIN")|| + !fx.isArray()||!nfx.isArray()||fx.size()!=nfx.size()|| + count-(target==ids?1:0)>=8||static_cast(position)>count-(target==ids?1:0)) + return reject("INVALID_FX_DESTINATION"); + args->setProperty("toChannelId",target);args->setProperty("toSlot",position); + } + auto converted=std::make_unique(); + converted->setProperty("requestId",request);converted->setProperty("deviceEpoch",epoch); + converted->setProperty("baseGraphRevision",revision);converted->setProperty("baseRosterRevision",roster); + converted->setProperty("targetChannelId",ids);converted->setProperty("operation",moving?"NATIVE_MOVE_INSERT":"NATIVE_REMOVE_INSERT"); + converted->setProperty("payload",juce::var(args.release()));return {juce::var(converted.release()),{}}; + } + if(op=="LOAD_INSERT") { + // Native-accepted ChannelId + catalog identity + exact next slot. + // Device/graph/roster were already independently compared above. + if(!approvedHasOperation(caps.getProperty("supportedOps",{}),"LOAD_INSERT") || + !approvedHasOperation(installedBus.getProperty("supportedOps",{}), + "NATIVE_LOAD_INSERT")) + return reject("NATIVE_VST3_NOT_ADMITTED"); + juce::var ch,nativeCh; + for(const auto& row:*rows.getArray()) + if(row.getProperty("id","").toString()==ids.toString())ch=row; + for(const auto& row:*nativeRows.getArray()) + if(row.getProperty("id","").toString()==ids.toString())nativeCh=row; + const auto role=ch.getProperty("role","").toString(); + if(!ch.isObject()||!nativeCh.isObject()|| + role!=nativeCh.getProperty("role","").toString()|| + (role!="INPUT"&&role!="GROUP"&&role!="FX_RETURN"&&role!="MAIN")) + return reject("NATIVE_VST3_TARGET_NOT_ADMITTED"); + const auto payload=publicIntent.getProperty("payload",{}); + const auto catalog=payload.getProperty("catalogId",{}); + const auto slot=payload.getProperty("slot",{}); + const auto publicFx=ch.getProperty("inserts",{}); + const auto nativeFx=nativeCh.getProperty("inserts",{}); + if(!payload.isObject()||!catalog.isString()|| + catalog.toString().isEmpty()|| + catalog.toString().getNumBytesAsUTF8()>256|| + !slot.isInt()||static_cast(slot)<0|| + static_cast(slot)>=8|| + !publicFx.isArray()||!nativeFx.isArray()|| + publicFx.getArray()->size()!=static_cast(slot)|| + nativeFx.getArray()->size()!=static_cast(slot)) + return reject("NATIVE_VST3_SLOT_OR_CATALOG_INVALID"); + auto args=std::make_unique(); + args->setProperty("catalogId",catalog); + args->setProperty("slot",slot); + auto converted=std::make_unique(); + converted->setProperty("requestId",request); + converted->setProperty("deviceEpoch",epoch); + converted->setProperty("baseGraphRevision",revision); + converted->setProperty("baseRosterRevision",roster); + converted->setProperty("targetChannelId",ids); + converted->setProperty("operation","NATIVE_LOAD_INSERT"); + converted->setProperty("payload",juce::var(args.release())); + return {juce::var(converted.release()),{}}; + } if(op!="SET_FADER" && op!="SET_PAN" && op!="SET_MUTE" && op!="SET_SOLO")return reject("UNSUPPORTED_APPROVED_CONTROL"); // Both native *and* GUI-side capabilities must be explicitly advertised @@ -95,8 +360,8 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( const bool input=role=="INPUT"; const bool bus=role=="GROUP" || role=="FX_RETURN"; if(!input && !bus)return reject("CHANNEL_ROLE_NOT_MUTABLE"); - if(bus && (op=="SET_MUTE" || op=="SET_SOLO")) - return reject("BUS_MUTE_SOLO_NOT_ADMITTED"); + // A native GROUP has exactly the same ChannelId mute/solo atomics as + // an INPUT. Keep the legacy AUX distinction in the engine role gate. const auto controls=channel.getProperty("controls",{}); if(!controls.isObject())return reject("INVALID_NATIVE_CONTROLS"); const auto fader=controls.getProperty("faderDb",{}); @@ -155,7 +420,8 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( translatedPayload->setProperty("pan",acceptedPan); } else { if(!value.isBool())return reject("INVALID_MUTE_SOLO_VALUE"); - nativeOperation="NATIVE_SET_CHANNEL_MUTE_SOLO"; + nativeOperation=bus?"NATIVE_SET_BUS_MUTE_SOLO": + "NATIVE_SET_CHANNEL_MUTE_SOLO"; translatedPayload->setProperty("mute",op=="SET_MUTE"?value:mute); translatedPayload->setProperty("solo",op=="SET_SOLO"?value:solo); } @@ -191,7 +457,8 @@ inline bool approvedNativeId(const juce::var& value,std::uint64_t& result) { // No fallback to ordinal-only M4 or synthetic JS/DSP is permitted. template inline bool executeApprovedNativeControl(Engine& engine, - const juce::var& translated) { + const juce::var& translated, + juce::String* nativeError=nullptr) { if(!translated.isObject())return false; std::uint64_t epoch=0,revision=0,roster=0,id=0; if(!approvedNativeId(translated.getProperty("deviceEpoch",{}),epoch) || @@ -203,6 +470,105 @@ inline bool executeApprovedNativeControl(Engine& engine, if(!payload.isObject())return false; const auto operation=translated.getProperty("operation","").toString(); const auto channel=armix::mixer::ChannelId{id}; + if(operation=="NATIVE_SET_PROCESSING_FORMAT") { + const auto format=payload.getProperty("format",{}); + if(!format.isString()|| + (format.toString()!="MONO"&&format.toString()!="STEREO")) + return false; + const auto mode=format.toString()=="MONO"? + armix::mixer::ProcessingFormat::mono: + armix::mixer::ProcessingFormat::stereo; + if constexpr(requires(Engine& e,armix::mixer::ProcessingFormat width) { + e.editNativeProcessingFormat(epoch,revision,roster,channel,width); + }) { + const auto changed=engine.editNativeProcessingFormat( + epoch,revision,roster,channel,mode); + return changed.accepted && changed.error!=nullptr && + changed.error[0]==0; + } else return false; + } + if(operation=="NATIVE_MOVE_INSERT"||operation=="NATIVE_REMOVE_INSERT") { + const auto slot=payload.getProperty("slot",{}),token=payload.getProperty("instanceId",{}); + if(!slot.isInt()||static_cast(slot)<0||static_cast(slot)>=8||!token.isString())return false; + std::uint64_t target=0;int position=0; + if(operation=="NATIVE_MOVE_INSERT") { + const auto pos=payload.getProperty("toSlot",{}); + if(!approvedNativeId(payload.getProperty("toChannelId",{}),target)||!pos.isInt())return false; + position=static_cast(pos);if(position<0||position>=8)return false; + } + if constexpr(requires(Engine& e){e.editNativeFxRack(epoch,revision,roster,channel, + std::size_t{},juce::String{},armix::mixer::ChannelId{},std::size_t{});}) { + const auto result=engine.editNativeFxRack(epoch,revision,roster,channel, + static_cast(static_cast(slot)),token.toString(), + armix::mixer::ChannelId{target},static_cast(position)); + if(nativeError&&!result.accepted)*nativeError=result.error; + return result.accepted&&result.error&&result.error[0]==0; + }else return false; + } + if(operation=="NATIVE_SET_WIRE_GAIN") { + std::uint64_t edge=0;double gain=0.; + if(!approvedNativeId(payload.getProperty("edgeId",{}),edge)|| + !nativeV8Number(payload.getProperty("gainLinear",{}),gain)||gain<0.||gain>4.)return false; + if constexpr(requires(Engine& e){e.setNativeWireGain(epoch,revision,roster,channel,edge,0.f);}) + return engine.setNativeWireGain(epoch,revision,roster,channel,edge,static_cast(gain)); + return false; + } + if(operation=="NATIVE_APPLY_WIRE_TRANSACTION") { + const auto raw=payload.getProperty("changes",{}); + const auto* edits=raw.getArray(); + if(!edits||edits->isEmpty()||edits->size()>64)return false; + std::vector changes; + changes.reserve(static_cast(edits->size())); + for(const auto& edit:*edits) { + if(!edit.isObject())return false; + const auto op=edit.getProperty("op","").toString(); + std::uint64_t from=0,to=0,edgeId=0; + if(!approvedNativeId(edit.getProperty("from",{}),from) || from!=id) + return false; + armix::mixer::WireChange change; + change.from=armix::mixer::ChannelId{from}; + if(op=="CONNECT")change.kind=armix::mixer::WireChange::Kind::connect; + else if(op=="REMOVE")change.kind=armix::mixer::WireChange::Kind::remove; + else if(op=="RETARGET")change.kind=armix::mixer::WireChange::Kind::retarget; + else if(op=="ROUTE_ONLY")change.kind=armix::mixer::WireChange::Kind::routeOnly; + else return false; + if(op=="CONNECT"||op=="RETARGET"||op=="ROUTE_ONLY") { + if(!approvedNativeId(edit.getProperty("to",{}),to)||to==from) + return false; + change.to=armix::mixer::ChannelId{to}; + } + if(op=="REMOVE"||op=="RETARGET") { + if(!approvedNativeId(edit.getProperty("edgeId",{}),edgeId)) + return false; + change.edgeId=edgeId; + } + if(op=="CONNECT"||op=="ROUTE_ONLY") { + double gain=0.; + if(!nativeV8Number(edit.getProperty("gainLinear",{}),gain) || + gain<0.||gain>4.|| + (op=="ROUTE_ONLY"&&gain!=1.)) + return false; + change.gain=static_cast(gain); + } + changes.push_back(change); + } + // The real engine may still reject while monitoring/output is armed. + // Never auto-mute, fabricate a JS graph, or bypass its safety fence. + if constexpr(requires(Engine& e, std::span values) { + e.applyNativeWireTransaction(epoch,revision,roster,values); + }) { + const auto applied=engine.applyNativeWireTransaction( + epoch,revision,roster, + std::span(changes)); + if(!applied.accepted && nativeError && applied.error) + *nativeError=applied.error; + // NativeBusResult.error is const char*, not juce::String. + // The compiler and regression probe must share the exact native + // error ABI. Never claim ACK for a contradictory accepted/error pair. + return applied.accepted && applied.error != nullptr && + applied.error[0] == '\0'; + } else return false; + } if(operation=="NATIVE_SET_CHANNEL_MIX" || operation=="NATIVE_SET_BUS_MIX") { const auto rawGain=payload.getProperty("gain",{}); @@ -218,13 +584,22 @@ inline bool executeApprovedNativeControl(Engine& engine, return engine.setNativeBusMix(epoch,revision,channel, static_cast(gain),static_cast(pan)); } - if(operation=="NATIVE_SET_CHANNEL_MUTE_SOLO") { + if(operation=="NATIVE_SET_CHANNEL_MUTE_SOLO" || + operation=="NATIVE_SET_BUS_MUTE_SOLO") { const auto mute=payload.getProperty("mute",{}); const auto solo=payload.getProperty("solo",{}); if(!mute.isBool()||!solo.isBool())return false; - return engine.setNativeInputMuteSolo(epoch,revision,channel, - static_cast(mute), - static_cast(solo)); + if(operation=="NATIVE_SET_CHANNEL_MUTE_SOLO") + return engine.setNativeInputMuteSolo(epoch,revision,channel, + static_cast(mute), + static_cast(solo)); + if constexpr(requires(Engine& e){ + e.setNativeBusMuteSolo(epoch,revision,channel,true,false); + }) + return engine.setNativeBusMuteSolo(epoch,revision,channel, + static_cast(mute), + static_cast(solo)); + return false; } return false; } diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index eaafd93b0..544c500e7 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -82,11 +82,155 @@ inline bool publishVerifiedFirstSoundState(juce::var& snapshot, boolIs(route,"hasAcceptedRoute",true)); firstSound->setProperty("routingRevision",physicalReady ?juce::String(static_cast(revision)):juce::String("0")); + // Exactly ten hardware INPUT readbacks from the existing accepted M4 + // compiler, not the public Pages demo. A new unpatched session reports + // an empty array: we must not fabricate a default CH1 microphone. + juce::Array verifiedChannels; + if(physicalReady && boolIs(route,"hasAcceptedRoute",true)) { + const auto accepted=route.getProperty("acceptedRoute",{}); + const auto channels=accepted.getProperty("channels",{}); + if(auto* list=channels.getArray();list!=nullptr && + list->size()==10) { + bool valid=true; + for(const auto& item:*list) { + if(!item.isObject()) {valid=false;break;} + const auto mode=item.getProperty("mode",{}).toString(); + const auto left=item.getProperty("left",juce::var()); + const auto right=item.getProperty("right",juce::var()); + const auto main=item.getProperty("main",{}); + // BUS is a real accepted, internally-fed M4 lane. Discarding + // all 10 readbacks because ONE lane is BUS would hide live + // physical microphone inputs on otherwise verified channels. + // Preserve BUS identity without claiming a hardware pin. + if((mode!="NONE" && mode!="MONO" && + mode!="STEREO" && mode!="BUS") || + !(left.isInt()||left.isInt64()) || + !(right.isInt()||right.isInt64()) || !main.isBool()) { + valid=false;break; + } + const int l=static_cast(left),r=static_cast(right); + if(((mode=="NONE"||mode=="BUS")&&(l!=-1||r!=-1)) || + (mode=="MONO"&&(r!=-1||l<0)) || + (mode=="STEREO"&&(l<0||r<0||l==r))) { + valid=false;break; + } + if((mode=="MONO"||mode=="STEREO")&& + (!inputs.getArray()->contains(l)|| + (mode=="STEREO"&&!inputs.getArray()->contains(r)))) { + valid=false;break; + } + auto verified=std::make_unique(); + verified->setProperty("mode",mode); + verified->setProperty("left",l); + verified->setProperty("right",r); + verified->setProperty("main",main); + const auto format=item.getProperty("channelFormat",{}).toString(); + if(format=="MONO"||format=="STEREO") + verified->setProperty("channelFormat",format); + verifiedChannels.add(juce::var(verified.release())); + } + if(!valid)verifiedChannels.clear(); + } + } + firstSound->setProperty("channels",juce::var(verifiedChannels)); + // Native M4 remains the real 10-channel callback before ChannelId + // admission, including a stable source patch under armed monitoring. + // Publish only verified PCM controls and measured per-channel peaks. + // Never infer controls from the Pages reference model. + if(physicalReady && boolIs(route,"hasAcceptedRoute",true) && + !boolIs(route,"nativeBusStructural",true) && + verifiedChannels.size()==10) { + const auto controls=route.getProperty("channelControls",{}); + const auto levelsL=route.getProperty("channelPeaksL",{}); + const auto levelsR=route.getProperty("channelPeaksR",{}); + const auto* ctl=controls.getArray(); + const auto* l=levelsL.getArray(); + const auto* r=levelsR.getArray(); + bool valid=ctl && l && r && ctl->size()==10 && + l->size()==10 && r->size()==10; + for(int i=0;valid && i<10;++i) { + const auto row=ctl->getReference(i); + double db=0.,pan=0.,peakL=0.,peakR=0.; + valid=row.isObject() && + nativeV8Number(row.getProperty("db",{}),db) && + nativeV8Number(row.getProperty("pan",{}),pan) && + nativeV8Number(l->getReference(i),peakL) && + nativeV8Number(r->getReference(i),peakR) && + db>=-60.01 && db<=10.01 && + pan>=-100.01 && pan<=100.01 && + peakL>=0. && peakR>=0. && + row.getProperty("mute",{}).isBool() && + row.getProperty("solo",{}).isBool(); + } + if(valid) { + firstSound->setProperty("channelControls",controls); + firstSound->setProperty("channelPeaksL",levelsL); + firstSound->setProperty("channelPeaksR",levelsR); + double masterDb=0.; + if(nativeV8Number(live.getProperty("masterDb",{}),masterDb) && + masterDb>=-60.01 && masterDb<=10.01) + firstSound->setProperty("masterDb",masterDb); + const auto masterMute=live.getProperty("masterMute",{}); + if(masterMute.isBool())firstSound->setProperty("masterMute",masterMute); + } + } + // Real routed FX instance IDs and catalog keys are read only from the + // installed publisher. A browser cannot insert forged plugin identities. + if(physicalReady && boolIs(route,"hasAcceptedRoute",true)) { + const auto fx=route.getProperty("fxInstances",{}); + if(auto* rows=fx.getArray();rows && rows->size()==14) + firstSound->setProperty("fxInstances",fx); + } + firstSound->setProperty("nativeBusStructural", + route.getProperty("nativeBusStructural",false)); // Do not write the route to the graph or change native capability flags. snapshot.getDynamicObject()->setProperty("legacyM4",juce::var(firstSound.release())); return physicalReady; } +inline void publishNativeMasterControls(juce::var& snapshot,const juce::var& live) +{ + // The physical MAIN gain/mute is + // applied by the single LiveAudioEngine host after that render. The + // generic ChannelId roster's default MAIN fader is not this physical + // gain. Publish the real host readback, or the visible master will + // snap back to 0 dB after every accepted native scalar snapshot. + double physicalMasterDb=0.; + const auto physicalMasterMute=live.getProperty("masterMute",{}); + if(nativeV8Number(live.getProperty("masterDb",{}),physicalMasterDb) && + physicalMasterDb>=-60.01 && physicalMasterDb<=10.01 && + physicalMasterMute.isBool()) { + const auto installedGraph=snapshot.getProperty("graph",{}); + const auto channels=installedGraph.getProperty("channels",{}); + if(auto* rows=channels.getArray()) + for(auto& row:*rows) + if(row.getProperty("role",{}).toString()=="MAIN") { + const auto controls=row.getProperty("controls",{}); + if(auto* obj=controls.getDynamicObject()) { + obj->setProperty("faderDb",physicalMasterDb); + obj->setProperty("mute",physicalMasterMute); + } + } + } +} + +inline bool projectRetainedNativeChannelIdGraph(juce::var& snapshot,const juce::var& live) +{ + const auto route=live.getProperty("dryRoutingLab",{}); + const auto retained=route.getProperty("retainedNativeBus",{}); + const auto pcm=route.getProperty("nativeChannelIdPcmActive",{}); + const auto device=snapshot.getProperty("device",{}); + const auto armed=device.getProperty("outputArmed",{}); + if(!retained.isObject() || !pcm.isBool() || static_cast(pcm) || + !armed.isBool() || static_cast(armed) || + !projectNativeGraph(snapshot,retained,NativeGraphProjection::retained)) + return false; + snapshot.getProperty("graph",{}).getDynamicObject() + ->setProperty("bindingState","NEEDS_REMAP"); + publishNativeMasterControls(snapshot,live); + return true; +} + inline bool projectInstalledNativeChannelIdGraph( juce::var& snapshot, const juce::var& live) { @@ -135,11 +279,12 @@ inline bool projectInstalledNativeChannelIdGraph( // comes from the verified installed ENGINE status above, not the caller. if (!projectApprovedNativeV8(snapshot,bus,true)) return false; + publishNativeMasterControls(snapshot,live); // Advertise only controls provided by the currently installed and // positively admitted native callback (never inferred from a JSON shape // or the browser). Both the native and public capability are required by - // the stateless control translator. WIRE remains explicitly disabled - // until the native structural dispatcher is independently admitted. + // the stateless control translator. Never invent a WIRE capability; it + // is enabled only by positive native ChannelId PCM readback. juce::Array available; const auto nativeOps=bus.getProperty("supportedOps",{}); const auto* actual=nativeOps.getArray(); @@ -154,6 +299,21 @@ inline bool projectInstalledNativeChannelIdGraph( available.add(juce::String("SET_MUTE")); available.add(juce::String("SET_SOLO")); } + // The installed native publisher already supported WIRE, but the host + // projection discarded it. The GUI then rejected every real BUS/WIRE + // gesture as NOT_ADMITTED. Admit only the actual installed operation. + if(has("NATIVE_APPLY_WIRE_TRANSACTION")) + available.add(juce::String("APPLY_WIRE_TRANSACTION")); + if(has("NATIVE_SET_WIRE_GAIN")) + available.add(juce::String("SET_WIRE_GAIN")); + if(has("NATIVE_SET_PROCESSING_FORMAT")) + available.add(juce::String("SET_PROCESSING_FORMAT")); + if(has("NATIVE_REMOVE_INSERT"))available.add(juce::String("REMOVE_INSERT")); + if(has("NATIVE_MOVE_INSERT"))available.add(juce::String("MOVE_INSERT")); + if(has("NATIVE_LOAD_INSERT")) + available.add(juce::String("LOAD_INSERT")); + if(has("NATIVE_CREATE_GROUP_SELECTED")) + available.add(juce::String("CREATE_GROUP")); const auto graph=snapshot.getProperty("graph",{}); const auto caps=graph.getProperty("capabilities",{}); if (auto* props=caps.getDynamicObject()) @@ -161,4 +321,116 @@ inline bool projectInstalledNativeChannelIdGraph( // Product LIVE stays false until independent vendor/Show/hardware FAT. return true; } + +/** + * Milestone A: one authoritative control-thread SessionSnapshot projection. + * The native callback remains the only PCM producer. Legacy M4 may be an + * implementation detail but NEVER independently competes with ChannelId. + * There is no UI, file I/O, VST preparation or RT mutation in this routine. + */ +inline void publishAuthoritativeMixerSession(juce::var& snapshot) +{ + if(!snapshot.isObject())return; + const auto device=snapshot.getProperty("device",{}); + const auto graph=snapshot.getProperty("graph",{}); + const auto caps=graph.getProperty("capabilities",{}); + const auto m4=snapshot.getProperty("legacyM4",{}); + const auto epoch=device.getProperty("epoch","0").toString(); + const auto graphRows=graph.getProperty("channels",{}); + const bool channelIdReady=caps.isObject() && + static_cast(caps.getProperty("callbackOwnsChannelIds",false)) && + nativeV8Decimal(epoch) && epoch!="0" && + nativeV8Decimal(graph.getProperty("revision",{})) && + graphRows.isArray() && graphRows.getArray()->size()>0; + const bool channelIdRetained=!channelIdReady && + graph.getProperty("bindingState",{}).toString()=="NEEDS_REMAP"; + const bool hasChannelId=channelIdReady || channelIdRetained; + const auto sources=m4.getProperty("channels",{}); + const auto controls=m4.getProperty("channelControls",{}); + const auto peakL=m4.getProperty("channelPeaksL",{}); + const auto peakR=m4.getProperty("channelPeaksR",{}); + const auto rackFlags=m4.getProperty("fxRackBypassed",{}); + const bool preparedM4=!hasChannelId && m4.isObject() && + static_cast(m4.getProperty("active",false)) && + static_cast(m4.getProperty("routeAccepted",false)) && + !static_cast(m4.getProperty("nativeBusStructural",true)) && + nativeV8Decimal(epoch) && epoch!="0" && + nativeV8Decimal(m4.getProperty("routingRevision",{})) && + sources.isArray() && controls.isArray() && peakL.isArray() && peakR.isArray() && + sources.getArray()->size()==10 && controls.getArray()->size()==10 && + peakL.getArray()->size()==10 && peakR.getArray()->size()==10; + juce::Array rows; + bool validM4=preparedM4; + if(preparedM4) { + for(int i=0;i<10;++i) { + const auto src=sources[i],ctl=controls[i]; + double db=0.,pan=0.,l=0.,r=0.; + if(!src.isObject() || !ctl.isObject() || + !nativeV8Number(ctl.getProperty("db",{}),db) || + !nativeV8Number(ctl.getProperty("pan",{}),pan) || + !nativeV8Number(peakL[i],l) || + !nativeV8Number(peakR[i],r) || + !ctl.getProperty("mute",{}).isBool() || + !ctl.getProperty("solo",{}).isBool() || + !src.getProperty("main",{}).isBool() || + db< -60.01 || db>10.01 || pan< -100.01 || pan>100.01 || + l<0. || r<0.) {validM4=false;break;} + auto c=std::make_unique(); + c->setProperty("faderDb",db); + c->setProperty("pan",pan/100.); + c->setProperty("mute",ctl.getProperty("mute",{})); + c->setProperty("solo",ctl.getProperty("solo",{})); + auto row=std::make_unique(); + // M4 IDs are deliberately NOT uint64 native ChannelIds. + row->setProperty("id","m4:"+juce::String(i+1).paddedLeft('0',2)); + row->setProperty("ordinal",i); + row->setProperty("role","INPUT"); + row->setProperty("source",src); + row->setProperty("controls",juce::var(c.release())); + row->setProperty("primaryOut",static_cast( + src.getProperty("main",false))?"MAIN":"NONE"); + row->setProperty("peakL",l); + row->setProperty("peakR",r); + if(rackFlags.isArray() && rackFlags.getArray()->size()>i && rackFlags[i].isBool()) + row->setProperty("fxRackBypassed",rackFlags[i]); + rows.add(juce::var(row.release())); + } + if(!validM4)rows.clear(); + } + auto session=std::make_unique(); + const auto authority=hasChannelId?"CHANNEL_ID":validM4?"M4":"NONE"; + if(channelIdRetained)session->setProperty("bindingState","NEEDS_REMAP"); + session->setProperty("authority",authority); + session->setProperty("deviceEpoch",epoch); + session->setProperty("routeRevision",hasChannelId? + graph.getProperty("revision","0"):validM4? + m4.getProperty("routingRevision","0"):juce::var("0")); + session->setProperty("rosterRevision",hasChannelId? + graph.getProperty("rosterRevision","0"):juce::var("0")); + session->setProperty("channels",hasChannelId?graphRows:juce::var(rows)); + session->setProperty("supportedOps",channelIdReady? + caps.getProperty("supportedOps",juce::var(juce::Array{})): + juce::var(juce::Array{})); + // Actual physical post-mixer MAIN is not a second audio graph. + auto master=std::make_unique(); + if(hasChannelId) { + for(const auto& ch:*graphRows.getArray()) + if(ch.getProperty("role","").toString()=="MAIN") { + const auto c=ch.getProperty("controls",{}); + if(c.isObject()) { + master->setProperty("db",c.getProperty("faderDb",{})); + master->setProperty("mute",c.getProperty("mute",{})); + } + break; + } + }else if(validM4) { + master->setProperty("db",m4.getProperty("masterDb",{})); + master->setProperty("mute",m4.getProperty("masterMute",{})); + } + master->setProperty("outputArmed",device.getProperty("outputArmed",false)); + session->setProperty("main",juce::var(master.release())); + snapshot.getDynamicObject()->setProperty("mixerSession", + juce::var(session.release())); +} + } // namespace armix::console diff --git a/integration/ApprovedNativeV8Projection.h b/integration/ApprovedNativeV8Projection.h index a2f6b3ee1..8319b7759 100644 --- a/integration/ApprovedNativeV8Projection.h +++ b/integration/ApprovedNativeV8Projection.h @@ -33,9 +33,11 @@ inline bool nativeV8Number(const juce::var& value,double& n) { // A structurally correct bus is NOT proof that its IDs own the installed // JUCE callback. The real PCM owner must explicitly admit the producer. // G0 must pass false and keep the accepted GUI graph unmodified. -inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, - bool installedChannelIdCallbackAdmitted) { - if(!installedChannelIdCallbackAdmitted)return false; +enum class NativeGraphProjection { installed, retained }; + +inline bool projectNativeGraph(juce::var& snapshot,const juce::var& bus, + NativeGraphProjection mode) { + const bool installed=mode==NativeGraphProjection::installed; const auto device=snapshot.getProperty("device",{}); if(!nativeV8Decimal(device.getProperty("epoch",{})))return false; const auto rawRows=bus.getProperty("channels",{}),rawEdges=bus.getProperty("edges",{}); @@ -81,24 +83,42 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, ch->setProperty("controls",juce::var(controls.release())); juce::Array fx; for(const auto& item:*inserts.getArray()){ + // This integration/ header is the one included by the live native + // runtime snapshot. The src/ counterpart is NOT its replacement. + // id is the installed processor token; catalogId is the vendor + // identity used for the command and subsequent ACK/readback. const auto token=item.getProperty("instanceId",{}),label=item.getProperty("name",{}); + const auto catalog=item.getProperty("id",{}); const auto bypass=item.getProperty("bypassed",{}); - if(!token.isString()||!label.isString()||!bypass.isBool())return false; + if(!token.isString()||token.toString().isEmpty()|| + !catalog.isString()||catalog.toString().isEmpty()|| + catalog.toString().getNumBytesAsUTF8()>256|| + !label.isString()||!bypass.isBool())return false; auto insert=std::make_unique(); - insert->setProperty("id",token);insert->setProperty("name",label); + insert->setProperty("id",token);insert->setProperty("catalogId",catalog); + insert->setProperty("name",label); insert->setProperty("bypassed",bypass); + const auto latency=item.getProperty("latencySamples",{}); + if(latency.isInt())insert->setProperty("latencySamples",latency); + const auto changed=item.getProperty("latencyChanged",{}); + if(changed.isBool())insert->setProperty("latencyChanged",changed); fx.add(juce::var(insert.release())); } ch->setProperty("inserts",juce::var(fx)); + const auto rackBypassed=row.getProperty("fxRackBypassed",{}); + if(!rackBypassed.isVoid()) { + if(!rackBypassed.isBool())return false; + ch->setProperty("fxRackBypassed",rackBypassed); + } ch->setProperty("sends",juce::var(juce::Array{})); - if(role!="INPUT"){ + { // INPUT channels can receive WIRE PCM as well as physical capture. auto dst=std::make_unique(); dst->setProperty("id",id);dst->setProperty("name",name); dst->setProperty("role",role); destinations.add(juce::var(dst.release())); } double left=0.,right=0.; - if(nativeV8Number(row.getProperty("peakL",{}),left) && + if(installed && nativeV8Number(row.getProperty("peakL",{}),left) && nativeV8Number(row.getProperty("peakR",{}),right) && left>=0.&&right>=0.){ auto peak=std::make_unique(); @@ -148,17 +168,28 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, if(!g||!t||!graph.getProperty("capabilities",{}).isObject())return false; // All validation completed before anything becomes authoritative. g->setProperty("revision",rev);g->setProperty("rosterRevision",roster); + const auto latency=bus.getProperty("latencySamples",{}); + if(latency.isInt())g->setProperty("latencySamples",latency); g->setProperty("mainChannelId",mainId); g->setProperty("channels",juce::var(channels)); g->setProperty("destinations",juce::var(destinations)); g->setProperty("edges",juce::var(wires)); if(auto* caps=graph.getProperty("capabilities",{}).getDynamicObject()){ - caps->setProperty("callbackOwnsChannelIds",true); - juce::Array ops;ops.add("APPLY_WIRE_TRANSACTION"); + caps->setProperty("callbackOwnsChannelIds",installed); + juce::Array ops; + if(installed)ops.add("APPLY_WIRE_TRANSACTION"); + const auto actual=installed?bus.getProperty("supportedOps",{}):juce::var{}; + if(const auto* list=actual.getArray()) + if(list->contains(juce::var("NATIVE_SET_WIRE_GAIN")))ops.add("SET_WIRE_GAIN"); caps->setProperty("supportedOps",juce::var(ops)); } t->setProperty("channelMeterRmsPeak",juce::var(meters.release())); // productionCallbackLive deliberately stays FALSE until full FAT. return true; } +inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, + bool installedChannelIdCallbackAdmitted) { + return installedChannelIdCallbackAdmitted && + projectNativeGraph(snapshot,bus,NativeGraphProjection::installed); +} } // namespace armix::console diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 0aa79f524..7f707daef 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -57,6 +57,40 @@ def accepted_pages_html() -> str: # HTML at native build time. Every anchor must occur exactly once: no silent # breakage if Pages GUI source evolves. No extra layout or simulated PCM. NATIVE_EVENT_HOOKS = ( + # The published /preview/ HTML and its V28 checkpoint are immutable. + # Change ONLY the compiled native WebView's operator fader travel law. + # The DSP gain remains exact dB -> 10^(dB/20), and the mapping is + # invertible at every tick; no new JS audio engine or controller. + ("function faderPercent(value,isSend){return rangePct(value,-60,isSend?6:10);}\n", + "const FADER_TAPER=Object.freeze([[-60,0],[-48,15],[-36,27],[-24,39],[-12,54],[-6,65],[0,77],[6,92],[10,100]]);\n" + "function faderPercent(value,isSend){\n" + " if(isSend)return rangePct(value,-60,6);\n" + " const db=Math.max(-60,Math.min(10,Number(value)));\n" + " for(let i=1;i{\n", + "const channelOptions=(t,type)=>{\n" + " if(type==='input'&&window.__JUCE__?.backend)\n" + " return window.__ARMIX_NATIVE_M2__?.inputChoices?.(t)||['None'];\n" + " if(type==='output'&&window.__JUCE__?.backend)\n" + " return window.__ARMIX_NATIVE_M2__?.outputChoices?.(t)||[t.output];\n"), ("function wireGraphCommit(ops,{record=true}={}){\n", "function wireGraphCommit(ops,{record=true}={}){\n" " if(window.__JUCE__?.backend){window.__ARMIX_NATIVE_M2__?.consumeWire?.(ops);return false;}\n"), @@ -66,6 +100,15 @@ def accepted_pages_html() -> str: ("function handleField(event){\n", "function handleField(event){\n" " if(window.__JUCE__?.backend){window.__ARMIX_NATIVE_M2__?.consumeField?.(event);return;}\n"), + # Native-only: the SAME original quick picker/manager owns the UI. + # Only insertion leaves the demo reducer and goes to JUCE's actual VST3 + # graph; never mark a browser insert as loaded. + ("function applyChannelIdentity(){\n", + "function applyChannelIdentity(){\n" + " if(window.__JUCE__?.backend&&!window.__ARMIX_NATIVE_M2__?.applyIdentity?.())return;\n"), + ("function insertCatalogPlugin(id){\n", + "function insertCatalogPlugin(id){\n" + " if(window.__JUCE__?.backend){window.__ARMIX_NATIVE_M2__?.insertPlugin?.(id,activeFxTarget);return;}\n"), (" if(a==='wireExpand'){document.querySelector('.section-rail", " if(window.__JUCE__?.backend&&!window.__ARMIX_NATIVE_M2__?.enabled)return;\n" " if(window.__ARMIX_NATIVE_M2__?.consumeAction?.(t,a,btn))return;\n" @@ -132,10 +175,66 @@ def accepted_pages_html() -> str: # Native WebView2 only: expose the original Pages IIFE model to the thin # bridge. No second renderer/state reducer, no change to public /preview/. ("restorePluginPreferences();init();\n})();", + "let verifiedM4WireSignature='',verifiedM4WireDirty=false;\n" "window.__ARMIX_NATIVE_SCOPE__=Object.freeze({\n" " get tracks(){return tracks;},get master(){return master;},\n" + " get wireEdges(){return wireEdges;}, // native read-only UI edge identity\n" + " get wireGainDragging(){return !!sendKnobDrag;},paintWireKnob,\n" + " syncNativeWireGains(rows){\n" + " for(const row of rows){\n" + " const edge=wireEdges.find(e=>e.id===row.id&&e.kind!=='primary');\n" + " if(!edge||!Number.isFinite(row.levelDb))continue;\n" + " edge.levelDb=row.levelDb;\n" + " const input=document.querySelector('.wire-gain[data-wire-id=\"'+edge.id+'\"]');\n" + " if(input&&input!==sendKnobDrag?.input&&!row.pending){\n" + " input.value=String(row.levelDb);paintWireKnob(input,row.levelDb);\n" + " }\n" + " }\n" + " },\n" + " syncVerifiedM4Wires(rows,ids){\n" + " if(!Array.isArray(rows)||rows.length!==10||!Array.isArray(ids)||ids.length!==10)\n" + " return false;\n" + " const tracksById=new Map(tracks.filter(t=>t.kind==='audio').map(t=>[t.id,t]));\n" + " if(new Set(ids).size!==10||ids.some(id=>!tracksById.has(id))||\n" + " rows.some(r=>!r||typeof r.main!=='boolean'))return false;\n" + " const next=[];\n" + " for(let i=0;i<10;i++)if(rows[i].main){\n" + " const prior=wireEdges.find(e=>e.enabled&&e.kind==='primary'&&\n" + " e.sourceId===ids[i]&&e.destId===master.id);\n" + " next.push(prior||{id:nextWireId++,sourceId:ids[i],destId:master.id,\n" + " kind:'primary',mode:'postFader',enabled:true,levelDb:0});\n" + " }\n" + " const sig=rows.map((r,i)=>r.main?String(ids[i]):'').join('|');\n" + " if(sig!==verifiedM4WireSignature || wireEdges.length!==next.length ||\n" + " next.some((e,i)=>wireEdges[i]!==e)){\n" + " wireEdges=next;verifiedM4WireSignature=sig;verifiedM4WireDirty=true;\n" + " if(selectedWireEdgeId!==null&&!wireEdges.some(e=>e.id===selectedWireEdgeId))\n" + " selectedWireEdgeId=null;\n" + " syncWireOutputProjection();\n" + " }\n" + " if(verifiedM4WireDirty&&!wireGesture&&!faderGesture&&\n" + " !document.activeElement?.matches?.('.strip select')){\n" + " verifiedM4WireDirty=false;refreshWireRoutingNodes();\n" + " }\n" + " return true;\n" + " },\n" " make,render,findTrack,displayMeterDbfs,\n" - " colors:COLORS,wireGraph:ArSonWireGraph,\n" + " openChannelIdentity,closeChannelIdentity,\n" + " get identityTrackId(){return identityTrackId;},\n" + " get identityColor(){return identityColor;},get identityIcon(){return identityIcon;},\n" + " refreshStrip,syncFaderVisual,openFastPicker,openPluginBrowser,\n" + " get activeFaderId(){return faderGesture?Number(faderGesture.input.closest('.strip')?.dataset.id):-1;},\n" + " setNativeCatalog(rows){\n" + " pluginCatalog=rows.filter(x=>x&&typeof x.id==='string'&&typeof x.name==='string').map(x=>({\n" + " id:x.id,name:x.name,vendor:x.vendor||'Unknown',category:x.category||'Utility',\n" + " format:'VST3',status:'ready',latencySamples:null,\n" + " favorite:!!x.favorite,hidden:false}));\n" + " const label=document.querySelector('.plugin-disclaimer');\n" + " if(label)label.textContent='NATIVE JUCE VST3 · only verified scanned catalog entries are insertable';\n" + " renderPluginCatalog();renderFastPicker();return pluginCatalog.length;\n" + " },\n" + " closeNativePicker(){setFastPicker(false);},\n" + " colors:COLORS,channelIcons:CHANNEL_ICONS,wireGraph:ArSonWireGraph,\n" " allocateWireId(){return nextWireId++;},\n" " installGraph(channels,main,edges){\n" " tracks=channels;master=main;wireEdges=edges;\n" @@ -264,7 +363,25 @@ def verify(out: Path) -> dict: expected_out = Path(tmp) / "bundle" expected = stage(expected_out) if existing != expected: - raise ValueError("STALE OR WRONG APPROVED GUI BUNDLE: source/manifest changed") + # Diagnose the exact differing byte source. Never weaken the gate, + # and never hide a Python/zlib or asset generation mismatch behind + # an unhelpful generic manifest error. + mismatches = [] + for key in sorted(set(existing) | set(expected)): + old, new = existing.get(key), expected.get(key) + if old == new: + continue + if key == "files" and isinstance(old, list) and isinstance(new, list): + old_files = {x["path"]: x["sha256"] for x in old} + new_files = {x["path"]: x["sha256"] for x in new} + for path in sorted(old_files.keys() | new_files.keys()): + if old_files.get(path) != new_files.get(path): + mismatches.append( + f"resource={path} existing={old_files.get(path)} regenerated={new_files.get(path)}") + else: + mismatches.append(f"field={key} existing={old!r} regenerated={new!r}") + raise ValueError("STALE OR WRONG APPROVED GUI BUNDLE: " + + "; ".join(mismatches[:4])) paths = {"index.html", "ApprovedGuiResources.h", "approved-gui-manifest.json"} paths.update(p["path"] for p in expected["files"]) for path in sorted(paths): diff --git a/scripts/build_verify_windows_installer.ps1 b/scripts/build_verify_windows_installer.ps1 new file mode 100644 index 000000000..6cfab9f11 --- /dev/null +++ b/scripts/build_verify_windows_installer.ps1 @@ -0,0 +1,76 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Independent FAT-only GUI installer build AND real per-user install/uninstall. +param([string]$OutputDir="dist",[string]$InstallerOutput="installer-output") +Set-StrictMode -Version Latest +$ErrorActionPreference="Stop" +$dist=(Resolve-Path -LiteralPath $OutputDir).Path +$sha=(& git rev-parse HEAD).Trim() +$manifest=Get-Content -LiteralPath (Join-Path $dist "BUILD_PROVENANCE.json") -Raw -Encoding UTF8 | ConvertFrom-Json +$exe=Join-Path $dist "ArSonMix-GUI10CH-P012-Windows-x64.exe" +$appHash=(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant() +if($LASTEXITCODE -ne 0 -or $manifest.sourceCommit -ne $sha -or + $manifest.exeSha256 -ne $appHash -or $manifest.fatStatus -ne "EXPERIMENTAL_NOT_HARDWARE_QUALIFIED" -or + (Get-Item -LiteralPath $exe).Length -ne $manifest.guiExeBytes -or + (Test-Path -LiteralPath (Join-Path $dist "Studio"))) { + throw "Installer requires the exact already verified and hardware-unqualified FAT PE" +} +$which=Get-Command ISCC.exe -ErrorAction SilentlyContinue +$iscc=if($which){$which.Source}else{"C:\Program Files (x86)\Inno Setup 6\ISCC.exe"} +if(-not (Test-Path -LiteralPath $iscc -PathType Leaf)){throw "Inno Setup 6 compiler missing"} +$root=(Resolve-Path .).Path +$out=Join-Path $root $InstallerOutput +New-Item -ItemType Directory -Force -Path $out | Out-Null +$stage=Join-Path $env:RUNNER_TEMP ("arsonmix-install-stage-"+[guid]::NewGuid().ToString("N")) +$install=Join-Path $env:RUNNER_TEMP ("arsonmix-install-test-"+[guid]::NewGuid().ToString("N")) +$studio=Join-Path $env:APPDATA "AR-MIX-Studio" +New-Item -ItemType Directory -Force -Path $studio | Out-Null +$sentinel=Join-Path $studio ("installer-test-"+[guid]::NewGuid().ToString("N")+".keep") +"persistent-private-data" | Set-Content -LiteralPath $sentinel +try { + New-Item -ItemType Directory -Force -Path $stage | Out-Null + Copy-Item -LiteralPath $exe -Destination (Join-Path $stage "verified-gui.exe") + foreach($item in @("BUILD_PROVENANCE.json","README.md")){ + Copy-Item -LiteralPath (Join-Path $dist $item) -Destination (Join-Path $stage $item) + } + Copy-Item -LiteralPath "assets/icon/arsonmix-app.ico" -Destination (Join-Path $stage "arsonmix-app.ico") + $factory=Join-Path $dist "FactoryFX" + if(Test-Path -LiteralPath $factory -PathType Container){ + Copy-Item -LiteralPath $factory -Destination (Join-Path $stage "FactoryFX") -Recurse + } + & $iscc "/Qp" "/DSourceRoot=$stage" "/DOutputRoot=$out" "installer/ArSonMix.iss" + $setup=Join-Path $out "ArSonMix-Windows-x64-Setup-UNQUALIFIED.exe" + if($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $setup -PathType Leaf) -or + (Get-Item -LiteralPath $setup).Length -lt 2MB){throw "ISCC failed to build installer RC"} + $start=Start-Process -FilePath $setup -ArgumentList @( + "/VERYSILENT","/SUPPRESSMSGBOXES","/NORESTART","/CURRENTUSER","/DIR=$install" + ) -Wait -PassThru + if($start.ExitCode -ne 0){throw "Actual Windows installation failed"} + $installedExe=Join-Path $install "ArSonMix.exe" + if(-not (Test-Path -LiteralPath $installedExe -PathType Leaf) -or + (Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash.ToLowerInvariant() -ne $appHash -or + (Test-Path -LiteralPath (Join-Path $install "portable_mode.txt"))){ + throw "Installed EXE hash or storage mode differs from source" + } + $installedManifest=Get-Content -LiteralPath (Join-Path $install "BUILD_PROVENANCE.json") -Raw -Encoding UTF8 | ConvertFrom-Json + if($installedManifest.sourceCommit -ne $sha){throw "Wrong installed provenance"} + $uninstall=Join-Path $install "unins000.exe" + if(-not (Test-Path -LiteralPath $uninstall -PathType Leaf)){throw "Uninstaller missing"} + $stop=Start-Process -FilePath $uninstall -ArgumentList @( + "/VERYSILENT","/SUPPRESSMSGBOXES","/NORESTART" + ) -Wait -PassThru + if($stop.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $sentinel)){ + throw "Uninstaller failed or erased user Studio data" + } + [ordered]@{ + sourceCommit=$sha;guiSha256=$appHash + installerSha256=(Get-FileHash -LiteralPath $setup -Algorithm SHA256).Hash.ToLowerInvariant() + certification="UNSIGNED_HARDWARE_FAT_PENDING";mode="PER_USER_NO_AUTOARM" + } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $out "INSTALLER_PROVENANCE.json") -Encoding UTF8 + Write-Host "INSTALLER_RC_VERIFIED: SHA-matched PE, install/uninstall, private Studio intact" + Write-Host "PHYSICAL_FAT_PENDING" +} +finally { + if(Test-Path -LiteralPath $sentinel){Remove-Item -LiteralPath $sentinel -Force} + if(Test-Path -LiteralPath $stage){Remove-Item -LiteralPath $stage -Recurse -Force} + if(Test-Path -LiteralPath $install){Remove-Item -LiteralPath $install -Recurse -Force -ErrorAction SilentlyContinue} +} diff --git a/scripts/check_approved_native_gui_release.mjs b/scripts/check_approved_native_gui_release.mjs index 1e6398f7c..88ebef1c7 100644 --- a/scripts/check_approved_native_gui_release.mjs +++ b/scripts/check_approved_native_gui_release.mjs @@ -64,7 +64,13 @@ try { if(/juce_add_binary_data\(ARMixAssets SOURCES\s*web\//.test(cmake) || host.includes('BinaryData::consolenative_html')) block('Forbidden alternative GUI compiled in Windows executable'); - const py=process.env.PYTHON || 'python'; + // CMake's FindPython3 may pick a different interpreter than PATH's + // `python` on Windows. PNG/favicon bytes can differ across zlib versions. + // Reproduce the GUI with the exact Python that made the CMake bundle. + const interpreterNote=join(bundle,'..','approved-gui-python.txt'); + const cmakePython=existsSync(interpreterNote) + ? read(interpreterNote).toString('utf8').trim() : ''; + const py=cmakePython || process.env.PYTHON || 'python'; const result=spawnSync(py,['scripts/build_approved_native_gui.py', '--out',bundle,'--verify'],{cwd:root,encoding:'utf8',timeout:60000}); if(result.error || result.status!==0) diff --git a/scripts/ci_select_changed_paths.mjs b/scripts/ci_select_changed_paths.mjs new file mode 100644 index 000000000..51a16b457 --- /dev/null +++ b/scripts/ci_select_changed_paths.mjs @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Only select real test suites. No PR owner, labels, collision or GitHub API. +import {execFileSync} from 'node:child_process'; +import {appendFileSync} from 'node:fs'; +import {requiresUiSmoke,requiresNativeQualification} from './check_workstream_coordination.mjs'; +const base=process.argv[2]; +if(!base || !/^[a-f0-9]{40}$/.test(base)) + throw Error('Expected exact Git base SHA'); +const changed=execFileSync('git', + ['diff','--name-only','--diff-filter=ACMRT',base,'HEAD'], + {encoding:'utf8',maxBuffer:8*1024*1024}) + .split(/\r?\n/).filter(Boolean); +const ui=requiresUiSmoke(changed),native=requiresNativeQualification(changed); +if(process.env.GITHUB_OUTPUT) + appendFileSync(process.env.GITHUB_OUTPUT, + 'run_ui='+(ui?'true':'false')+'\n'+ + 'run_native='+(native?'true':'false')+'\n'); +console.log('Changed '+changed.length+' paths: Chromium '+ui+', Windows CTest '+native); diff --git a/scripts/package_native_windows.ps1 b/scripts/package_native_windows.ps1 index a1881b24c..1e6390bdc 100644 --- a/scripts/package_native_windows.ps1 +++ b/scripts/package_native_windows.ps1 @@ -61,7 +61,13 @@ if ($LASTEXITCODE -ne 0 -or $gitSha -notmatch '^[0-9a-f]{40}$') { # Refuse a valid PE/CTest artifact which embeds the WRONG browser renderer. # This is the source/asset attestation for the exact approved Pages GUI. $approvedGuiDir = Join-Path $BuildDir "approved_gui" -& python scripts/build_approved_native_gui.py --out $approvedGuiDir --verify +. (Join-Path $PSScriptRoot "resolve_approved_gui_python.ps1") +$approvedGuiPython = Resolve-ArSonMixApprovedGuiPython -BuildDir $BuildDir +# Validate the ACTUAL compiled Windows taskbar/EXE icon against the approved +# committed PNG, not merely CMake resource names or an unverified .ico. +& $approvedGuiPython scripts/verify_windows_pe_brand_icon.py --exe $app --approved assets/icon/arsonmix-256.png +if ($LASTEXITCODE -ne 0) { throw "WINDOWS BRAND PE ICON MISMATCH: compiled app icon differs from approved ArSonMix" } +& $approvedGuiPython scripts/build_approved_native_gui.py --out $approvedGuiDir --verify if ($LASTEXITCODE -ne 0) { throw "APPROVED GUI PROVENANCE MISMATCH: generated bundle differs from Pages" } $approvedGuiManifestPath = Join-Path $approvedGuiDir "approved-gui-manifest.json" $approvedGui = Get-Content -LiteralPath $approvedGuiManifestPath -Raw -Encoding UTF8 | ConvertFrom-Json diff --git a/scripts/resolve_approved_gui_python.ps1 b/scripts/resolve_approved_gui_python.ps1 new file mode 100644 index 000000000..8d3e18b5b --- /dev/null +++ b/scripts/resolve_approved_gui_python.ps1 @@ -0,0 +1,17 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Exact byte-for-byte /preview/ verifier must run under the interpreter +# selected by CMake for its generated favicon/PNG resources. A different +# Python/zlib from PATH may emit different PNG/ICO compressed bytes. +function Resolve-ArSonMixApprovedGuiPython { + param([Parameter(Mandatory=$true)][string] $BuildDir) + $note = Join-Path $BuildDir "approved-gui-python.txt" + if (-not (Test-Path -LiteralPath $note -PathType Leaf)) { + throw "CMake Python provenance missing: $note" + } + $selected = (Get-Content -LiteralPath $note -Raw -Encoding UTF8).Trim() + if ([string]::IsNullOrWhiteSpace($selected) -or + -not (Test-Path -LiteralPath $selected -PathType Leaf)) { + throw "CMake-selected Python unavailable; refusing unverified GUI regeneration" + } + return (Resolve-Path -LiteralPath $selected).Path +} diff --git a/scripts/verify_native_windows_artifact.ps1 b/scripts/verify_native_windows_artifact.ps1 index f11114569..8f20d7c3b 100644 --- a/scripts/verify_native_windows_artifact.ps1 +++ b/scripts/verify_native_windows_artifact.ps1 @@ -98,7 +98,12 @@ if ($LASTEXITCODE -ne 0 -or $sha -ne $manifest.sourceCommit) { # Release gate must verify the EXACT GUI shown by /preview/, not a # self-consistent but WRONG legacy web/index.html or console-native renderer. $approvedGuiDir = Join-Path "build" "approved_gui" -& python scripts/build_approved_native_gui.py --out $approvedGuiDir --verify +. (Join-Path $PSScriptRoot "resolve_approved_gui_python.ps1") +$approvedGuiPython = Resolve-ArSonMixApprovedGuiPython -BuildDir "build" +# Independent post-package check of the EXE that will go INSIDE the ZIP. +& $approvedGuiPython scripts/verify_windows_pe_brand_icon.py --exe $exePath --approved assets/icon/arsonmix-256.png +if ($LASTEXITCODE -ne 0) { throw "REJECT: distributed Windows PE icon does not match current approved brand" } +& $approvedGuiPython scripts/build_approved_native_gui.py --out $approvedGuiDir --verify if ($LASTEXITCODE -ne 0) { throw "REJECT: native GUI is not built from current approved Pages" } $approvedPath = Join-Path $approvedGuiDir "approved-gui-manifest.json" $approved = Get-Content -LiteralPath $approvedPath -Raw -Encoding UTF8 | ConvertFrom-Json diff --git a/scripts/verify_windows_pe_brand_icon.py b/scripts/verify_windows_pe_brand_icon.py new file mode 100644 index 000000000..a9942030b --- /dev/null +++ b/scripts/verify_windows_pe_brand_icon.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Attest actual Windows PE RT_GROUP_ICON pixels against the approved source. + +Stdlib only: parse x64 PE resources and compare 256px icon RGBA to the +committed brand. JUCE/Windows premultiplied RGB conversions may round a +visible component by 1-2; alpha must match exactly, RGB <=3 composite units. +""" +import argparse +from pathlib import Path +import struct +import sys +from generate_brand_icons import read_png + + +def check(data: bytes, expected: Path): + def bounds(offset, size): + if offset < 0 or size < 0 or offset + size > len(data): + raise ValueError("Corrupt PE resource bounds") + def u16(offset): + bounds(offset, 2) + return struct.unpack_from(" 1024: + raise ValueError("Excessive PE resource entries") + bounds(pos+16, count*8) + result=[] + for i in range(count): + ident, offset = struct.unpack_from(" 255: + raise ValueError("Invalid resource group name") + bounds(name_offset+2, nchars*2) + ident = data[name_offset+2:name_offset+2+nchars*2].decode("utf-16le") + else: + ident &= 0x7fffffff + result.append((ident, offset)) + return result + resources={} + for resource_type, type_node in entries(0): + if resource_type not in (3, 14): + continue + if not type_node & 0x80000000: + raise ValueError("Malformed icon resource type") + parts={} + for name, lang_node in entries(type_node & 0x7fffffff): + if not lang_node & 0x80000000: + raise ValueError("Missing icon language tree") + for _, leaf in entries(lang_node & 0x7fffffff): + if leaf & 0x80000000: + raise ValueError("Nested icon data") + pos = root+(leaf & 0x7fffffff) + bounds(pos, 16) + rva, size, _, _ = struct.unpack_from(" 1024*1024: + raise ValueError("Oversized icon resource") + off=file_offset(rva, size) + parts.setdefault(name, data[off:off+size]) + resources[resource_type]=parts + images=resources.get(3,{}) + groups=resources.get(14,{}) + if not groups or not images: + raise ValueError("Windows EXE is missing RT_GROUP_ICON/RT_ICON") + size, expected_rows = read_png(expected) + if size != 256: + raise ValueError("Committed approved brand icon is not 256px") + checked=0 + required={16,32,48,256} + for name, group in groups.items(): + if len(group)<6: + raise ValueError("Truncated icon group") + reserved,kind,count=struct.unpack_from("3*255: + raise ValueError(f"Icon differs from approved brand x={pos//4} y={y}") + checked+=1 + if required-found: + raise ValueError(f"Windows icon {name} missing sizes {sorted(required-found)}") + if checked!=len(groups): + raise ValueError("Every PE icon group must match approved ArSonMix pixels") + return checked + + +def main(): + parser=argparse.ArgumentParser() + parser.add_argument("--exe",required=True,type=Path) + parser.add_argument("--approved",required=True,type=Path) + args=parser.parse_args() + try: + n=check(args.exe.read_bytes(),args.approved) + except (ValueError,OSError,struct.error,IndexError) as exc: + print("PE_BRAND_ICON_REJECTED: "+str(exc),file=sys.stderr) + return 1 + print(f"PE_BRAND_ICON_VERIFIED: {n} Windows icon groups, 16/32/48/256px, approved alpha and visible RGB") + return 0 + + +if __name__=="__main__": + sys.exit(main()) diff --git a/site/preview-v2/assets/mixer-open.svg b/site/preview-v2/assets/mixer-open.svg new file mode 100644 index 000000000..95600b59e --- /dev/null +++ b/site/preview-v2/assets/mixer-open.svg @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/site/preview-v2/assets/mixer-save.svg b/site/preview-v2/assets/mixer-save.svg new file mode 100644 index 000000000..19479ee06 --- /dev/null +++ b/site/preview-v2/assets/mixer-save.svg @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/src/ApprovedNativeV8Projection.h b/src/ApprovedNativeV8Projection.h index ab95387fd..792d5e291 100644 --- a/src/ApprovedNativeV8Projection.h +++ b/src/ApprovedNativeV8Projection.h @@ -73,17 +73,34 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus) { ch->setProperty("controls",juce::var(controls.release())); juce::Array fx; for(const auto& item:*inserts.getArray()){ + // Catalog identity selects the vendor binary; instance identity + // addresses the live DSP processor and per-slot bypass/editor. + // They must NEVER be compared as if they were interchangeable. const auto token=item.getProperty("instanceId",{}),label=item.getProperty("name",{}); + const auto catalog=item.getProperty("id",{}); const auto bypass=item.getProperty("bypassed",{}); - if(!token.isString()||!label.isString()||!bypass.isBool())return false; + if(!token.isString()||token.toString().isEmpty()|| + !catalog.isString()||catalog.toString().isEmpty()|| + catalog.toString().getNumBytesAsUTF8()>256|| + !label.isString()||!bypass.isBool())return false; auto insert=std::make_unique(); - insert->setProperty("id",token);insert->setProperty("name",label); + insert->setProperty("id",token);insert->setProperty("catalogId",catalog); + insert->setProperty("name",label); insert->setProperty("bypassed",bypass); + const auto latency=item.getProperty("latencySamples",{}); + if(latency.isInt())insert->setProperty("latencySamples",latency); + const auto changed=item.getProperty("latencyChanged",{}); + if(changed.isBool())insert->setProperty("latencyChanged",changed); fx.add(juce::var(insert.release())); } ch->setProperty("inserts",juce::var(fx)); + const auto rackBypassed=row.getProperty("fxRackBypassed",{}); + if(!rackBypassed.isVoid()) { + if(!rackBypassed.isBool())return false; + ch->setProperty("fxRackBypassed",rackBypassed); + } ch->setProperty("sends",juce::var(juce::Array{})); - if(role!="INPUT"){ + { // INPUT channels can receive WIRE PCM as well as physical capture. auto dst=std::make_unique(); dst->setProperty("id",id);dst->setProperty("name",name); dst->setProperty("role",role); @@ -140,6 +157,8 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus) { if(!g||!t)return false; // All validation completed before anything becomes authoritative. g->setProperty("revision",rev);g->setProperty("rosterRevision",roster); + const auto latency=bus.getProperty("latencySamples",{}); + if(latency.isInt())g->setProperty("latencySamples",latency); g->setProperty("mainChannelId",mainId); g->setProperty("channels",juce::var(channels)); g->setProperty("destinations",juce::var(destinations)); @@ -147,6 +166,9 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus) { if(auto* caps=graph.getProperty("capabilities",{}).getDynamicObject()){ caps->setProperty("callbackOwnsChannelIds",true); juce::Array ops;ops.add("APPLY_WIRE_TRANSACTION"); + const auto actual=bus.getProperty("supportedOps",{}); + if(const auto* list=actual.getArray()) + if(list->contains(juce::var("NATIVE_SET_WIRE_GAIN")))ops.add("SET_WIRE_GAIN"); caps->setProperty("supportedOps",juce::var(ops)); } t->setProperty("channelMeterRmsPeak",juce::var(meters.release())); diff --git a/src/ConsoleLiveBridgeV6.h b/src/ConsoleLiveBridgeV6.h index a30991611..8db86ac42 100644 --- a/src/ConsoleLiveBridgeV6.h +++ b/src/ConsoleLiveBridgeV6.h @@ -150,6 +150,8 @@ class LiveConsoleBridgeV6 final { if(peaksL.isArray())object->setProperty("channelPeaksL",peaksL); if(peaksR.isArray())object->setProperty("channelPeaksR",peaksR); if(inserts.isArray())object->setProperty("fxInstances",inserts); + const auto rackPower=route.getProperty("fxRackBypassed",juce::var()); + if(rackPower.isArray())object->setProperty("fxRackBypassed",rackPower); // The prepared/unpatched native M4 graph is a real silent route. // It allows direct IN gesture to activate the FIRST source. // This does not set productionCallbackLive or fake PCM. diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 20bc4039e..5bceac060 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -7,7 +7,10 @@ #include "VstBusLayout.h" #include "LiveGraphHandoff.h" #include "LiveDryRoutingLab.h" +#include "NativeMixerSessionFxRestore.h" +#include "NativeTopologyEditSafety.h" #include "../engine/dsp/NativeMasterLoudness.h" +#include "../engine/builtin_fx/ChannelEqProcessor.h" #include "DiagnosticTone.h" #include "../engine/device/JuceIndependentClockDevice.h" #include "../engine/device/LiveSecondaryOutputDevice.h" @@ -16,6 +19,7 @@ #include "../engine/device/AsioPriorityDeviceManager.h" #include "../engine/device/AsioRegistryIdentityProbe.h" #include "../engine/device/DirectRouteFence.h" +#include "../engine/device/DeviceSessionTransitionPolicy.h" #include "../engine/device/WasapiEndpointIdentityGuard.h" #include "../engine/core/FxOrderPlan.h" #include "../engine/core/FxMoveRamp.h" @@ -91,6 +95,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } std::array slots {}; std::array, maxFx> bypassFlags {}; + std::atomic rackBypassed{false}; // does not overwrite per-slot flags // Owned and advanced exclusively by the realtime render callback. // Physical-slot identity survives an atomic logical reorder (PR #102). std::array bypassEnvelope {}; @@ -180,7 +185,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } // Saved explicit device choice MUST NOT be silently replaced by // JUCE's selectDefaultDeviceOnFailure path (e.g. ASIO -> WASAPI). - auto error = deviceManager_.initialise (1, 2, savedSettings, !savedRoute); + // Prefer both input pins on a verified stereo endpoint; saved explicit + // channel masks still take precedence. Outputs remain DISARMED. + auto error = deviceManager_.initialise (2, 2, savedSettings, !savedRoute); if (error.isNotEmpty() && !savedRoute && deviceManager_.singleAsioPreferred()) { // This was only an automatic FIRST-RUN ASIO preference, not the @@ -295,18 +302,49 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // FAST1: control-thread output arm preflight; physical MUTE always works. // No auto-arm on device reopen, no RT allocation or driver reconfiguration. - juce::String liveOutputArmFault() + // Names are only an extra conservative policy for one identifiable + // VB-Cable *self loop*. Never guess that an arbitrary virtual endpoint + // equals another physical card; the native output gate remains primary. + static bool knownVirtualCableFeedbackPair(const juce::String& capture, + const juce::String& playback) noexcept + { + const auto in=capture.toLowerCase(),out=playback.toLowerCase(); + return (in.contains("vb-audio") || out.contains("vb-audio")) && + in.contains("cable output") && out.contains("cable input"); + } + + // First-time output authorization requires a verified capture source. + // Restoring an ALREADY-ARMED MAIN after a structural input edit instead + // verifies the existing destination/route even when every source is NONE: + // silence is safe and the user must not have to re-press MONITOR after + // NONE -> STEREO on the same device. Epoch/feedback/STREAM fences remain. + // Manual MONITOR arming always requires a verified source. An already + // authorized MAIN may remain safely armed while an input is temporarily + // NONE; this overload NEVER relaxes the explicit arm safety contract. + juce::String liveOutputArmFault() { return liveOutputArmFault(true); } + juce::String liveOutputArmFault(bool requirePhysicalSource) { auto* device=deviceManager_.getCurrentAudioDevice(); if (!device || !device->isOpen() || !directFence_.permitted() || independent_.active()) return "Select a verified DIRECT ASIO/Windows Audio device first."; + // Do not turn on a known VB-Cable -> same VB-Cable feedback loop, + // even if JS or an external host sends a monitor request. CONTROL + // thread only; no DSP callback cost, no implicit hardware redirect. + juce::AudioDeviceManager::AudioDeviceSetup currentSetup; + deviceManager_.getAudioDeviceSetup(currentSetup); + if (knownVirtualCableFeedbackPair(currentSetup.inputDeviceName, + currentSetup.outputDeviceName)) + return "MONITOR OFF: VB-Cable capture/playback self-loop. Choose a physical output or separate virtual cable."; if (routeReconfiguring_.load(std::memory_order_acquire) || handoff_.busy() || !dryRoutingLab_.active() || !dryRoutingLab_.ready() || !dryRoutingLab_.hasExplicitRoute()) return "Apply a real INPUT PATCH and wait for native routing ACK."; if (device->getActiveOutputChannels().countNumberOfSetBits()<2) return "MAIN needs two verified hardware output pins."; + if(dryRoutingLab_.channelIdPhysicalPcmActive()) + return !requirePhysicalSource || dryRoutingLab_.hasVerifiedNativeSources() + ?juce::String{}:juce::String("No physical input assigned. Select a channel IN first."); const auto readback=dryRoutingLab_.status(device); const auto accepted=readback.getProperty("acceptedRoute",juce::var()); const auto channels=accepted.getProperty("channels",juce::var()); @@ -317,7 +355,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if(row.getProperty("mode",juce::var()).toString()=="MONO" || row.getProperty("mode",juce::var()).toString()=="STEREO") {physicalSource=true;break;} - if (!physicalSource)return "No physical input assigned. Connect CH1/CH2 first."; + if (!physicalSource && requirePhysicalSource) + return "No physical input assigned. Connect CH1/CH2 first."; return {}; } void setMonitorEnabled (bool value) noexcept { monitor_.store (value); } @@ -337,13 +376,60 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Suppress any live output while selecting/changing a device, even if JUCE // starts its new callback before the selector window is closed. void beginManualAudioSetup() noexcept { + offeredWasapiBinding_.reset(); setOutputMuted(true); + secondaryOutput_.disarm(); directFence_.suspend(); - dryRoutingLab_.disable(); // explicit control-thread reset; not RT + // Do NOT disable the accepted ChannelId graph. Audio Setup is a + // device-binding operation, not an implicit CLEAR MIXER command. + // The JUCE selector may change the driver before its window closes. } bool finishManualAudioSetup() { if(!approveDirectRoute())return false; - return startUnpatchedProductionSession().isEmpty(); + using Decision=armix::device::DeviceSessionDecision; + switch(armix::device::decideDeviceSession( + true,dryRoutingLab_.ready(), + dryRoutingLab_.hasAuthoredMixerContent())) { + case Decision::retainBoundMixer: + return true; // no-op dialog: keep the exact FX/WIRE/PCM graph + case Decision::createFirstSilentMixer: + return startUnpatchedProductionSession().isEmpty(); + case Decision::retainUnboundMixer: + return rebindRetainedWasapiSession(); + case Decision::rejectedDevice: + return false; + } + return false; + } + // Explicit operator consent can bind matching numbered pins on another + // uniquely identified WASAPI endpoint pair. It never authorizes output. + bool stageRetainedWasapiPortMapping() { + offeredWasapiBinding_.reset(); + if(!hasRetainedUnboundMixer() || !acceptedWasapiBinding_)return false; + try { + auto current=inspectWasapiBinding(); + if(!current || !acceptedWasapiBinding_->samePinLayout(*current) || + acceptedWasapiBinding_->sameEndpoints(*current) || + acceptedWasapiBinding_->rate!=current->rate) + return false; + offeredWasapiBinding_=std::move(current); + return true; + } catch(...) {return false;} + } + bool confirmRetainedWasapiPortMapping() { + auto offered=std::move(offeredWasapiBinding_); + offeredWasapiBinding_.reset(); + return offered && hasRetainedUnboundMixer() && directFence_.permitted() && + rebindRetainedWasapiSession(&*offered); + } + bool recoverSameWasapiMixer() { + return hasRetainedUnboundMixer() && rebindRetainedWasapiSession(); + } + bool hasRetainedNativeSession() const noexcept { + return dryRoutingLab_.hasRetainedNativeSession(); + } + bool hasRetainedUnboundMixer() const noexcept { + return dryRoutingLab_.hasAuthoredMixerContent() && !dryRoutingLab_.ready(); } // Device changes are exclusively CONTROL-THREAD transactions. @@ -379,8 +465,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String setIndependentClockEnabled (bool wanted) { - if (dryRoutingLab_.hasExplicitRoute()) - return "CLEAR PATCH and MUTE OUTPUT before changing the device clock"; + if (dryRoutingLab_.hasAuthoredMixerContent()) + return "Preserve the authored mixer first: changing the device clock requires a full non-destructive session rebind"; if (handoff_.busy()) return "Finish pending VST3 graph switch before changing audio backend"; if (wanted == independent_.active() && !(savedDirectSetup_ && !wanted)) return {}; if (wanted && savedDirectSetup_) return "Restore old device backend before another transition"; @@ -475,8 +561,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // user setup is restored on exit; temporary routes must not be persisted. juce::String setDiagnosticRoute (armix::diagnostics::Route wanted) { - if (dryRoutingLab_.hasExplicitRoute()) - return "CLEAR PATCH and MUTE OUTPUT before changing SIGNAL CHECK"; + if (dryRoutingLab_.hasAuthoredMixerContent()) + return "An authored mixer cannot enter endpoint isolation until a safe session rebind is available"; using Route = armix::diagnostics::Route; if (handoff_.busy()) return "Finish the pending FX graph transition first"; if (independent_.active()) return "Disable independent clock mode before endpoint isolation tests"; @@ -1037,13 +1123,22 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String startUnpatchedProductionSession() { setOutputMuted(true); secondaryOutput_.disarm(); // never carry LIVE STREAM into a new unpatched graph + if(hasRetainedUnboundMixer()) + return "Mixer session preserved, but device changed: full ChannelId graph and plugin-state rebind required (output stays muted)"; auto* device=deviceManager_.getCurrentAudioDevice(); if(!device || !directFence_.permitted() || independent_.active()) return "No verified DIRECT full-duplex device"; - return dryRoutingLab_.startUnpatchedSession( + const auto epoch=dryRoutingLab_.epoch(); + auto profile=inspectWasapiBinding(); + const auto error=dryRoutingLab_.startUnpatchedSession( directFence_.permitted(),independent_.active(),graphOwned_->count, formats_,device->getCurrentSampleRate(), juce::jmax(32,device->getCurrentBufferSizeSamples())); + if(error.isEmpty() && dryRoutingLab_.epoch()==epoch) { + acceptedMixerBinding_=readMixerBinding(*device); + acceptedWasapiBinding_=std::move(profile); + } + return error; } // Historical STOP command retained as a safe CLEAR PATCH alias. @@ -1097,6 +1192,63 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback setOutputMuted(true); // never expose CH1 unexpectedly on STOP dryRoutingLab_.disable(); } + // One structural graph transaction for SOURCE, OUT, M/ST and FX inserts: + // keep the last accepted PCM audible while the CONTROL thread validates, + // clones, and prepares the candidate. Disarm MAIN only at the atomic + // publication boundary, then re-admit ChannelId before restoring it. + // Rejected preparation must never cause a hardware mute or a fake GUI ACK. + // STREAM forbids structural editing and fast scalar controls stay atomic. + template + juce::String applyGuardedDryTopology(std::uint64_t expectedEpoch, + int frames,Edit&& edit) { + if(secondaryOutput_.armed()) + return "STOP STREAM before a structural INPUT/OUT change"; + const bool wasMonitoring=isMonitorEnabled(); + bool enteredPublication=false; + juce::String error; + try { + error=edit([&] { + enteredPublication=true; + // A topology publication is NOT an operator MONITOR OFF. + // Preserve the authorized MAIN decision across NONE -> STEREO. + // Only gate the physical render for this short commit window. + if(wasMonitoring) + topologyPublicationMute_.store(true,std::memory_order_release); + }); + } + catch(const std::exception& ex) { + error="NATIVE TOPOLOGY: preparation failed: "+juce::String(ex.what()); + } + catch(...) { error="NATIVE TOPOLOGY: preparation failed"; } + // A syntactically valid request can still reject before publication: + // retain the previous monitor, graph and ChannelId authority. + if(!enteredPublication)return error; + return finishGuardedDryTopology( + expectedEpoch,frames,wasMonitoring,std::move(error)); + } + // One post-publication authority handoff/restoration policy for all + // structural controls. Never confuse muted hardware with detached DSP. + juce::String finishGuardedDryTopology(std::uint64_t expectedEpoch, + int frames,bool wasMonitoring,juce::String error) { + if(error.isEmpty() && expectedEpoch==dryRoutingLab_.epoch() && + dryRoutingLab_.hasExplicitRoute()) + (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count,frames,true,currentOriginalCh1Lease()); + const bool sameEpoch=expectedEpoch==dryRoutingLab_.epoch(); + const bool safeToResume=wasMonitoring && sameEpoch && + armix::mixer::NativeTopologyEditSafety::mayRestoreMonitor( + // An accepted NONE source is silent, but never removes the + // user's previously authorized output destination. + wasMonitoring,sameEpoch,liveOutputArmFault(false).isEmpty(), + secondaryOutput_.armed()); + // When a device/handoff/output fence fails, revoke authorization + // instead of accidentally reopening a changed or unsafe endpoint. + // For a safe same-device edit, do NOT rewrite the user's MONITOR bit: + // the temporary publication gate is a separate realtime control. + if(wasMonitoring && !safeToResume)setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); + return error; + } juce::String switchDryRoutingLabSource(int strip,std::uint64_t epoch, std::uint64_t revision,const juce::String& mode, int left,int right) { @@ -1108,24 +1260,26 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return "SOURCE SWITCH: live DIRECT device or graph unavailable"; auto* device=deviceManager_.getCurrentAudioDevice(); if(!device)return "SOURCE: active DIRECT audio device unavailable"; - // True first-input SOURCE selection is a control-prepared native graph - // transaction, not a browser-side APPLY or alternate callback. A - // single verified mono capture pin is a supported source. try { const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); - const auto oldRevision=dryRoutingLab_.revision(); - const auto changed=dryRoutingLab_.repatchPhysicalSource( - strip,epoch,revision,mode,left,right, - directFence_.permitted(),independent_.active(), - graphOwned_->count,formats_,device->getCurrentSampleRate(),frames); - // Same-format SOURCE is an atomic live parameter on BOTH kernels: - // do not rebuild VST3/PCM or interrupt the 64-sample crossfade. - if(changed.isEmpty() && allOutputsDisarmed() && - oldRevision!=dryRoutingLab_.revision()) - (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( - graphOwned_->count,frames,true, - currentOriginalCh1Lease()); - return changed; + const bool structural=dryRoutingLab_.sourceNeedsPreparedGraph(strip,mode); + if(!armix::mixer::NativeTopologyEditSafety::mayEdit( + structural,secondaryOutput_.armed())) + return "SOURCE: STOP STREAM before changing source format"; + // Existing same-format physical pin changes remain live, atomic + // and 64-sample crossfaded; no unnecessary mute or recompile. + if(!structural) + return dryRoutingLab_.repatchPhysicalSource( + strip,epoch,revision,mode,left,right, + directFence_.permitted(),independent_.active(), + graphOwned_->count,formats_,device->getCurrentSampleRate(),frames); + return applyGuardedDryTopology(epoch,frames,[&](const auto& beforePublish){ + return dryRoutingLab_.repatchPhysicalSource( + strip,epoch,revision,mode,left,right, + directFence_.permitted(),independent_.active(), + graphOwned_->count,formats_,device->getCurrentSampleRate(), + frames,beforePublish); + }); } catch(const std::exception& ex) { return "SOURCE: native prepare failed; prior audio kept: " + juce::String(ex.what()); } catch(...) { @@ -1149,19 +1303,52 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if(!device)return "CHANNEL PATCH: no active native audio interface"; try { const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); - const auto changed=dryRoutingLab_.repatchChannelStructure( - strip,epoch,revision,operation,value, - directFence_.permitted(),independent_.active(), - graphOwned_->count,formats_,device->getCurrentSampleRate(),frames); - if(changed.isEmpty() && allOutputsDisarmed()) - (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( - graphOwned_->count,frames,true, - currentOriginalCh1Lease()); - return changed; + return applyGuardedDryTopology(epoch,frames,[&](const auto& beforePublish) { + return dryRoutingLab_.repatchChannelStructure( + strip,epoch,revision,operation,value, + directFence_.permitted(),independent_.active(), + graphOwned_->count,formats_,device->getCurrentSampleRate(), + frames,beforePublish); + }); } catch(...) { return "CHANNEL PATCH: native preparation failed; previous mix preserved"; } } + + // Existing single-callback native FX rack. Internally mute for a + // structural vendor prepare, then restore monitoring only on verified + // same-device/safe routing. The operator never needs an Arm/Patch wizard. + juce::String insertDryRoutingLabFx(int lane,int slot, + std::uint64_t epoch,std::uint64_t revision, + const LiveDryRoutingLab::FxSelection& chosen) { + if(independent_.active()||handoff_.busy()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + !directFence_.permitted()||savedDirectSetup_||savedLiveSetup_|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal) + return "FX INSERT: native direct graph or device unavailable"; + if(secondaryOutput_.armed()) + return "FX INSERT: stop the secondary stream before changing VST topology"; + for(int i=0;icount;++i) + if(graphOwned_->slots[i].latency!=0) + return "FX INSERT: CH1 latent VST3 needs PDC before routed inserts"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device)return "FX INSERT: select an actual audio device"; + const auto preflight=dryRoutingLab_.fxInsertPreflight( + lane,slot,epoch,revision,chosen); + if(preflight.isNotEmpty())return preflight; + auto* pluginFormat=formats_.getFormat(0); + if(!pluginFormat || + !pluginFormat->fileMightContainThisPluginType(chosen.path)) + return "FX INSERT: VST3 bundle unavailable or invalid; rescan catalog"; + const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + return applyGuardedDryTopology(epoch,frames,[&](const auto& beforePublish) { + return dryRoutingLab_.insertCatalogFx(lane,slot,epoch,revision, + chosen,directFence_.permitted(),independent_.active(), + graphOwned_->count,formats_,device->getCurrentSampleRate(), + frames,beforePublish); + }); + } bool setDryRoutingLabParameter(int strip,std::uint64_t epoch, std::uint64_t revision,const juce::String& parameter, float value) noexcept { @@ -1229,6 +1416,16 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback !=armix::diagnostics::Route::normal)return false; return dryRoutingLab_.setFxBypass(lane,slot,epoch,revision,instanceId,bypass); } + bool setDryRoutingLabFxRackBypass(int lane,std::uint64_t epoch, + std::uint64_t revision,bool bypass) noexcept { + if(routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + if(!dryRoutingLab_.setFxRackBypass(lane,epoch,revision,bypass))return false; + if(lane==0 && graphOwned_) + graphOwned_->rackBypassed.store(bypass,std::memory_order_release); + return true; + } armix::mixer::LiveChannelFxGraph::InstanceLease leaseRoutedFxForEditor( int lane,int slot,std::uint64_t epoch,std::uint64_t revision, const juce::String& instanceId) const noexcept { @@ -1247,8 +1444,137 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return "MUTE OUTPUT and use verified DIRECT before FX state capture"; return dryRoutingLab_.captureRoutedFxStates(epoch,revision,states); } + + // Native session serialization is CONTROL-owned; all vendor binary reads + // require MUTED MAIN/STREAM, with zero I/O in the physical audio callback. + juce::String captureNativeMixerSession( + armix::session::MixerSessionDocument& document, + std::vector& states,bool retained=false) { + if(!allOutputsDisarmed()||independent_.active()|| + !directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0) + return "MUTE MAIN/STREAM and finish FX handoff before session save"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device||!device->isOpen())return "Audio device unavailable for session capture"; + if(retained && !acceptedMixerBinding_) + return "Retained mixer device identity unavailable"; + auto error=dryRoutingLab_.captureNativeMixerSession(document,states,retained); + if(error.isNotEmpty())return error; + document.binding=retained?*acceptedMixerBinding_:readMixerBinding(*device); + document.masterGain=masterGain_.load(std::memory_order_acquire); + document.masterMute=masterMute_.load(std::memory_order_acquire); + document.masterMono=masterMono_.load(std::memory_order_acquire); + return {}; + } + + struct MixerBindingInspection final { + armix::session::HardwareBinding live; + armix::mixer::VerifiedNativeOutputs outputs{}; + armix::device::JuceActivePortSnapshot pins; + int callbackInputs=0; + std::uint64_t epoch=0; + }; + // Read-only control-thread verification of the currently opened pins. + juce::String inspectNativeMixerSessionBinding( + const armix::session::MixerSessionDocument& saved, + MixerBindingInspection& out) { + if(independent_.active()||!attached_|| + !directFence_.permitted()||handoff_.busy()|| + fxMovePhase_.load(std::memory_order_acquire)!=0|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal|| + routeReconfiguring_.load(std::memory_order_acquire)) + return "Verify DIRECT before device inspection"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device||!device->isOpen()) + return "NEEDS_REMAP: current audio device unavailable"; + MixerBindingInspection candidate; + juce::AudioDeviceManager::AudioDeviceSetup setup; + deviceManager_.getAudioDeviceSetup(setup); + const auto inputMask=device->getActiveInputChannels(); + const auto outputMask=device->getActiveOutputChannels(); + const auto rate=device->getCurrentSampleRate(); + const auto frames=device->getCurrentBufferSizeSamples(); + candidate.epoch=dryRoutingLab_.epoch(); + armix::device::JuceActivePortSnapshot::Fault pinFault{}; + if(inputMask!=setup.inputChannels || outputMask!=setup.outputChannels || + rate!=setup.sampleRate || frames!=setup.bufferSize || + !armix::device::JuceActivePortSnapshot::fromMasks( + candidate.epoch,inputMask,outputMask,candidate.pins,pinFault) || + !dryRoutingLab_.matchesSessionDevice(candidate.pins)) + return "NEEDS_REMAP: audio device pin readback does not match callback"; + candidate.live={ + deviceManager_.getCurrentAudioDeviceType(), + setup.inputDeviceName,setup.outputDeviceName, + inputMask.toString(16),outputMask.toString(16),rate,frames}; + candidate.callbackInputs=candidate.pins.inputs.enabledCount; + candidate.outputs=armix::session::MixerDeviceBindingPolicy::proposedOutputs( + saved,candidate.live,candidate.pins.outputCount); + if(candidate.epoch!=dryRoutingLab_.epoch()) + return "NEEDS_REMAP: device changed during inspection"; + out=std::move(candidate); + return {}; + } + + // Prepare fresh vendor processors before publishing the replacement. + // A successful publication leaves MAIN disarmed for caller verification. + juce::String restoreNativeMixerSession( + armix::session::MixerSessionDocument document, + const std::vector& states, + bool replaceActive=false,bool* sameLiveOutputs=nullptr) { + if((replaceActive?secondaryOutput_.armed():!allOutputsDisarmed())|| + independent_.active()||!attached_|| + !directFence_.permitted()||handoff_.busy()|| + fxMovePhase_.load(std::memory_order_acquire)!=0|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal|| + routeReconfiguring_.load(std::memory_order_acquire)) + return "MUTE output and verify DIRECT before restoring mixer"; + MixerBindingInspection inspected; + auto bindingError=inspectNativeMixerSessionBinding(document,inspected); + if(bindingError.isNotEmpty())return bindingError; + using BindingPolicy=armix::session::MixerDeviceBindingPolicy; + if(sameLiveOutputs) + *sameLiveOutputs=dryRoutingLab_.matchesNativeMixerOutputs(inspected.outputs); + bindingError=BindingPolicy::apply(document,inspected.live,inspected.outputs, + inspected.callbackInputs,false); + if(bindingError.isNotEmpty())return bindingError; + const auto ep=inspected.epoch; + const auto next=dryRoutingLab_.nativeGraphRevisionForRestore(); + if(!next || !dryRoutingLab_.matchesSessionDevice(inspected.pins)) + return "NEEDS_REMAP: device epoch changed before FX preparation"; + document.request.maxFrames=juce::jmax(32,inspected.live.frames); + std::shared_ptr bank; + const auto error=armix::session::NativeMixerSessionFxRestore::prepare( + document,states,formats_,inspected.live.rate,document.request.maxFrames,ep,next,bank); + if(error.isNotEmpty())return "FX_PREPARE_FAILED: "+error; + if(!directFence_.permitted()) + return "NEEDS_REMAP: DIRECT authorization changed during FX preparation"; + auto profile=inspectWasapiBinding(); + const auto gain=document.masterGain; + const auto mute=document.masterMute; + const auto mono=document.masterMono; + const bool monitoring=isMonitorEnabled(); + if(monitoring)setMonitorEnabled(false); + const auto applied=dryRoutingLab_.restoreNativeMixerSession( + std::move(document),std::move(bank),inspected.pins, + allOutputsDisarmed(),replaceActive); + if(applied.isNotEmpty()) { + if(monitoring&&ep==dryRoutingLab_.epoch()&&liveOutputArmFault(false).isEmpty()) + setMonitorEnabled(true); + return applied; + } + acceptedWasapiBinding_=std::move(profile); + acceptedMixerBinding_=std::move(inspected.live); + setMasterGainLinear(gain); + setMasterMuted(mute);setMasterMono(mono); + return {}; + } + std::uint64_t dryRoutingLabEpoch() const noexcept {return dryRoutingLab_.epoch();} std::uint64_t dryRoutingLabRevision() const noexcept {return dryRoutingLab_.revision();} + std::uint64_t outputArmRevision() const noexcept {return dryRoutingLab_.controlRevision();} // One native ChannelId bus transaction on the installed DIRECT device. // The GUI only obtains accepted state after successful native publisher // commit; no speculative UI role or second audio engine. @@ -1260,19 +1586,133 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const std::string& name,float gain, armix::mixer::ChannelId remove={}) { LiveDryRoutingLab::NativeBusResult rejected; - rejected.error="HARDWARE_NOT_DISARMED"; - if(independent_.active() || !attached_ || + rejected.error="NATIVE_BUS_DEVICE_UNAVAILABLE"; + if(independent_.active() || !attached_ || secondaryOutput_.armed() || !directFence_.permitted() || routeReconfiguring_.load(std::memory_order_acquire) || diagnosticRoute_.load(std::memory_order_acquire)!= armix::diagnostics::Route::normal || - !allOutputsDisarmed() || handoff_.busy() || - fxMovePhase_.load(std::memory_order_acquire)!=0) + handoff_.busy() || fxMovePhase_.load(std::memory_order_acquire)!=0) + return rejected; + const bool wasMonitoring=isMonitorEnabled(); + bool publishing=false; + try { + const auto result=dryRoutingLab_.editNativeBus( + epoch,pcmRevision,rosterRevision,role,selected, + name,gain,remove,true,[&] { + publishing=true; + // User must not have to toggle MONITOR for an ordinary + // Add BUS. A late output gate covers only publication. + if(wasMonitoring)topologyPublicationMute_.store( + true,std::memory_order_release); + }); + if(publishing) { + if(wasMonitoring && + !armix::mixer::NativeTopologyEditSafety::mayRestoreMonitor( + wasMonitoring,epoch==dryRoutingLab_.epoch(), + liveOutputArmFault(false).isEmpty(), + secondaryOutput_.armed())) + setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); + } + return result; + } catch(...) { + if(publishing) { + setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); + } + rejected.error="NATIVE_BUS_PUBLICATION_EXCEPTION"; + return rejected; + } + } + // Processing M/ST is an accepted ChannelId PCM topology transaction. + // The host gates physical output only at publication, then preserves + // the operator's original MONITOR decision on the same verified device. + LiveDryRoutingLab::NativeBusResult editNativeProcessingFormat( + std::uint64_t epoch,std::uint64_t pcmRevision, + std::uint64_t rosterRevision,armix::mixer::ChannelId id, + armix::mixer::ProcessingFormat format) { + LiveDryRoutingLab::NativeBusResult rejected{}; + rejected.error="NATIVE_PROCESSING_DEVICE_UNAVAILABLE"; + if(independent_.active()||!attached_||secondaryOutput_.armed()|| + !directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal|| + handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0) + return rejected; + const bool wasMonitoring=isMonitorEnabled(); + bool publishing=false; + try { + const auto result=dryRoutingLab_.editNativeProcessingFormat( + epoch,pcmRevision,rosterRevision,id,format,true,[&] { + publishing=true; + if(wasMonitoring)topologyPublicationMute_.store( + true,std::memory_order_release); + }); + if(publishing) { + if(wasMonitoring && + !armix::mixer::NativeTopologyEditSafety::mayRestoreMonitor( + wasMonitoring,epoch==dryRoutingLab_.epoch(), + liveOutputArmFault(false).isEmpty(), + secondaryOutput_.armed())) + setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); + } + return result; + } catch(...) { + if(publishing) { + setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); + } + rejected.error="NATIVE_PROCESSING_PUBLICATION_EXCEPTION"; return rejected; - return dryRoutingLab_.editNativeBus( - epoch,pcmRevision,rosterRevision,role,selected, - name,gain,remove,true); + } + } + // Native built-in EQ travels through EXACTLY the same ordered FxInstance + // lease, ChannelId graph revision, bypass envelope, and PDC as VST3. + // It is not the legacy fixed pre-VST EQ bank. + LiveDryRoutingLab::NativeBusResult installNativeBuiltInEq( + std::uint64_t ep,std::uint64_t pcmRevision, + std::uint64_t rosterRevision,armix::mixer::ChannelId id) { + LiveDryRoutingLab::NativeBusResult fail{}; + fail.error="NATIVE_EQ_HOST_UNAVAILABLE"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(independent_.active()||!attached_||!device|| + !directFence_.permitted()||secondaryOutput_.armed()|| + handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return fail; + if(ep!=dryRoutingLab_.epoch()){ + fail.error="NATIVE_EQ_DEVICE_CHANGED";return fail; + } + const auto rate=device->getCurrentSampleRate(); + const int frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + if(!(rate>=8000. && rate<=384000.)|| + frames>LiveDryRoutingLab::Block::hardFrameLimit) { + fail.error="NATIVE_EQ_UNSUPPORTED_AUDIO_FORMAT";return fail; + } + try { + auto processor=std::make_unique(); + processor->prepareToPlay(rate,frames); + if(!processor->isReady()){ + fail.error="NATIVE_EQ_PREPARE_REJECTED";return fail; + } + auto lease=std::make_shared< + armix::mixer::LiveChannelFxGraph::FxInstance>( + std::move(processor), + juce::String(armix::builtin_fx::ChannelEqProcessor::catalogIdentity), + "Parametric EQ",LiveDryRoutingLab::Block::hardFrameLimit); + return dryRoutingLab_.attachNativeInsert(ep,pcmRevision, + rosterRevision,id, + armix::builtin_fx::ChannelEqProcessor::catalogIdentity, + std::move(lease),true); + } catch(...) { + fail.error="NATIVE_EQ_PREPARE_EXCEPTION";return fail; + } } + // User-owned VST3 on a true dynamic ChannelId. Instantiation/scan/layout // work is CONTROL only; the callback receives an immutable fx lease. LiveDryRoutingLab::NativeBusResult installNativeVst3( @@ -1283,12 +1723,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback fail.error="NATIVE_VST3_HOST_UNAVAILABLE"; auto* device=deviceManager_.getCurrentAudioDevice(); if(independent_.active()||!attached_||!device|| - !directFence_.permitted()||!allOutputsDisarmed()|| + !directFence_.permitted()||secondaryOutput_.armed()|| handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0|| routeReconfiguring_.load(std::memory_order_acquire)|| diagnosticRoute_.load(std::memory_order_acquire)!= armix::diagnostics::Route::normal)return fail; - if(ep!=deviceStartCount_.load(std::memory_order_acquire)) + if(ep!=dryRoutingLab_.epoch()) {fail.error="NATIVE_VST3_DEVICE_CHANGED";return fail;} const auto rate=device->getCurrentSampleRate(); const int frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); @@ -1314,8 +1754,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback fail.error="NATIVE_VST3_INCOMPATIBLE_STEREO_LAYOUT";return fail; } instance->prepareToPlay(rate,frames); - if(instance->getLatencySamples()!=0) { - fail.error="NATIVE_VST3_REQUIRES_PDC";return fail; + if(instance->getLatencySamples()<0 || + instance->getLatencySamples()>armix::dsp::StereoLatencyDelay::maximumSamples) { + fail.error="NATIVE_VST3_LATENCY_EXCEEDS_BUDGET";return fail; } auto lease=std::make_shared< armix::mixer::LiveChannelFxGraph::FxInstance>( @@ -1327,12 +1768,39 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback fail.error="NATIVE_VST3_VENDOR_PREPARE_FAILED";return fail; } } + LiveDryRoutingLab::NativeBusResult editNativeFxRack(std::uint64_t ep, + std::uint64_t revision,std::uint64_t roster,armix::mixer::ChannelId source, + std::size_t slot,const juce::String& token,armix::mixer::ChannelId target,std::size_t position) { + LiveDryRoutingLab::NativeBusResult fail;fail.error="NATIVE_FX_RACK_HOST_BUSY"; + if(independent_.active()||!attached_||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)||handoff_.busy()|| + fxMovePhase_.load(std::memory_order_acquire)!=0|| + diagnosticRoute_.load(std::memory_order_acquire)!=armix::diagnostics::Route::normal) + return fail; + return dryRoutingLab_.editNativeFxRack(ep,revision,roster,source,slot,token,target,position); + } + bool retainsRoutedFxEditor(std::uint64_t epoch, + const armix::mixer::LiveChannelFxGraph::InstanceLease& owner) const noexcept { + return dryRoutingLab_.retainsFxEditor(epoch,owner); + } bool bypassNativeVst3(std::uint64_t epoch,std::uint64_t revision, armix::mixer::ChannelId id,std::size_t slot, const juce::String& token,bool bypass) noexcept { return dryRoutingLab_.bypassNativeInsert(epoch,revision,id,slot, token,bypass); } + bool bypassNativeFxRack(std::uint64_t epoch,std::uint64_t revision, + armix::mixer::ChannelId id,bool bypass) noexcept { + if(routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + if(!dryRoutingLab_.bypassNativeRack(epoch,revision,id,bypass))return false; + // The original CH1 VST3 instance can be external-leased into the + // native ChannelId publisher. Its own crossfade gate must agree. + if(graphOwned_ && dryRoutingLab_.nativeChannelIsOriginalCh1(id)) + graphOwned_->rackBypassed.store(bypass,std::memory_order_release); + return true; + } armix::mixer::LiveChannelFxGraph::InstanceLease leaseNativeVst3Editor( std::uint64_t epoch,std::uint64_t revision, armix::mixer::ChannelId id,std::size_t slot, @@ -1362,16 +1830,42 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback std::uint64_t rosterRevision,armix::mixer::ChannelId channel, int left,int right,bool stereo) { LiveDryRoutingLab::NativeBusResult fail; - fail.error="HARDWARE_NOT_DISARMED"; + fail.error="NATIVE_SOURCE_DEVICE_UNAVAILABLE"; if(independent_.active()||!attached_||!directFence_.permitted()|| + secondaryOutput_.armed()|| routeReconfiguring_.load(std::memory_order_acquire)|| diagnosticRoute_.load(std::memory_order_acquire)!= armix::diagnostics::Route::normal || - !allOutputsDisarmed()||handoff_.busy()|| - fxMovePhase_.load(std::memory_order_acquire)!=0) + handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0) + return fail; + const bool wasMonitoring=isMonitorEnabled(); + bool publishing=false; + try{ + const auto result=dryRoutingLab_.patchNativeInputSource( + epoch,pcmRevision,rosterRevision,channel,left,right,stereo, + true,[&]{ + publishing=true; + if(wasMonitoring)topologyPublicationMute_.store( + true,std::memory_order_release); + }); + if(publishing){ + if(wasMonitoring && + !armix::mixer::NativeTopologyEditSafety::mayRestoreMonitor( + wasMonitoring,epoch==dryRoutingLab_.epoch(), + liveOutputArmFault(false).isEmpty(), + secondaryOutput_.armed())) + setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); + } + return result; + }catch(...){ + if(publishing){ + setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); + } + fail.error="NATIVE_SOURCE_PUBLICATION_EXCEPTION"; return fail; - return dryRoutingLab_.patchNativeInputSource( - epoch,pcmRevision,rosterRevision,channel,left,right,stereo,true); + } } LiveDryRoutingLab::NativeBusResult setNativePrimaryOutput( std::uint64_t ep,std::uint64_t pcmRev,std::uint64_t rosterRev, @@ -1405,6 +1899,15 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return dryRoutingLab_.applyNativeWireTransaction( ep,pcmRev,rosterRev,changes); } + bool setNativeWireGain(std::uint64_t epoch,std::uint64_t rev, + std::uint64_t roster,armix::mixer::ChannelId source, + std::uint64_t edge,float gain) noexcept { + if(independent_.active()||!attached_||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.setNativeWireGain(epoch,rev,roster,source,edge,gain); + } bool setNativeInputMix(std::uint64_t epoch,std::uint64_t rev, armix::mixer::ChannelId id,float gain,float pan) noexcept { if(independent_.active()||!directFence_.permitted()|| @@ -1421,6 +1924,15 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback armix::diagnostics::Route::normal)return false; return dryRoutingLab_.setNativeInputMuteSolo(epoch,rev,id,mute,solo); } + bool setNativeBusMuteSolo(std::uint64_t epoch,std::uint64_t rev, + armix::mixer::ChannelId id, + bool mute,bool solo) noexcept { + if(independent_.active()||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.setNativeBusMuteSolo(epoch,rev,id,mute,solo); + } bool nativeBusTopologyLive() const noexcept { return dryRoutingLab_.nativeBusTopologyLive(); } @@ -1434,6 +1946,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return dryRoutingLab_.setNativeBusMix(epoch,revision,id,gain,pan); } bool dryRoutingLabActive() const noexcept {return dryRoutingLab_.active();} + bool hasBoundMixerRoute() const noexcept {return dryRoutingLab_.hasExplicitRoute();} void pollDryRoutingLab() noexcept {dryRoutingLab_.poll();} juce::var status() @@ -1624,7 +2137,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("masterLufs", loudness.integratedLufs); if (measuredDirect && loudness.truePeakValid) o->setProperty ("masterDbtp", loudness.dbtp); - o->setProperty ("latencySamples", totalLatency_.load()); + o->setProperty ("latencySamples", dryRoutingLab_.channelIdPhysicalPcmActive()? + dryRoutingLab_.nativePcmLatencySamples():totalLatency_.load()); o->setProperty ("chainCount", graphOwned_->count); o->setProperty ("graphSwitchPending", handoff_.busy()); o->setProperty ("completedGraphSwaps", static_cast (completedSwaps_.load())); @@ -1672,6 +2186,100 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } private: + armix::session::HardwareBinding readMixerBinding(juce::AudioIODevice& device) { + juce::AudioDeviceManager::AudioDeviceSetup setup; + deviceManager_.getAudioDeviceSetup(setup); + return {deviceManager_.getCurrentAudioDeviceType(),setup.inputDeviceName, + setup.outputDeviceName,device.getActiveInputChannels().toString(16), + device.getActiveOutputChannels().toString(16),device.getCurrentSampleRate(), + device.getCurrentBufferSizeSamples()}; + } + struct WasapiBinding { + armix::device::EndpointIdentityPolicy::Selection endpoints; + juce::String backend; + juce::BigInteger inputs,outputs; + juce::StringArray inputLabels,outputLabels; + double rate=0.0; + int frames=0; + std::uint64_t epoch=0; + + bool samePinLayout(const WasapiBinding& other) const { + return backend==other.backend && inputs==other.inputs && outputs==other.outputs && + inputLabels==other.inputLabels && outputLabels==other.outputLabels; + } + bool sameEndpoints(const WasapiBinding& other) const noexcept { + return armix::device::EndpointIdentityPolicy::sameIdentity(endpoints,other.endpoints); + } + }; + + std::optional inspectWasapiBinding() { + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device || !device->isOpen() || independent_.active() || + !directFence_.permitted() || !device->getTypeName().startsWith("Windows Audio")) + return {}; + const auto epoch=dryRoutingLab_.epoch(); + juce::AudioDeviceManager::AudioDeviceSetup setup; + deviceManager_.getAudioDeviceSetup(setup); + const auto endpoints=armix::device::WasapiEndpointIdentityGuard::resolve( + setup.inputDeviceName,setup.outputDeviceName); + if(!endpoints.ok())return {}; + const auto inputs=device->getActiveInputChannels(); + const auto outputs=device->getActiveOutputChannels(); + const auto rate=device->getCurrentSampleRate(); + const auto frames=device->getCurrentBufferSizeSamples(); + if(inputs!=setup.inputChannels || outputs!=setup.outputChannels || + inputs.isZero() || outputs.countNumberOfSetBits()<2 || + !std::isfinite(rate) || rate<8000.0 || rate!=setup.sampleRate || + frames<16 || frames>LiveDryRoutingLab::Block::hardFrameLimit || + frames!=setup.bufferSize)return {}; + const auto inLabels=device->getInputChannelNames(); + const auto outLabels=device->getOutputChannelNames(); + const auto uniqueActiveLabels=[](const juce::BigInteger& mask,const juce::StringArray& labels) { + juce::StringArray seen; + for(int pin=mask.findNextSetBit(0);pin>=0;pin=mask.findNextSetBit(pin+1)) { + if(pin>=labels.size() || labels[pin].isEmpty() || seen.contains(labels[pin])) + return false; + seen.add(labels[pin]); + } + return true; + }; + if(!uniqueActiveLabels(inputs,inLabels) || !uniqueActiveLabels(outputs,outLabels) || + dryRoutingLab_.epoch()!=epoch || !directFence_.permitted())return {}; + return WasapiBinding{endpoints.selection,device->getTypeName(),inputs,outputs, + inLabels,outLabels,rate,frames,epoch}; + } + + bool rebindRetainedWasapiSession(const WasapiBinding* offered=nullptr) { + if(!acceptedWasapiBinding_ || !allOutputsDisarmed() || !attached_ || + routeReconfiguring_.load(std::memory_order_acquire) || handoff_.busy() || + fxMovePhase_.load(std::memory_order_acquire)!=0 || + diagnosticRoute_.load(std::memory_order_acquire)!=armix::diagnostics::Route::normal) + return false; + try { + auto current=inspectWasapiBinding(); + if(!current || !acceptedWasapiBinding_->samePinLayout(*current)) + return false; + if(offered) { + if(offered->epoch!=current->epoch || offered->rate!=current->rate || + offered->frames!=current->frames || !offered->sameEndpoints(*current) || + !offered->samePinLayout(*current)) + return false; + } else if(!acceptedWasapiBinding_->sameEndpoints(*current))return false; + const bool rateChanged=acceptedWasapiBinding_->rate!=current->rate; + // The external CH1/Orbit rack is prepared by the device callback + // rather than the retained ChannelId lease bank. Keep the same + // policy for it as for other authored effects. + if((rateChanged && graphOwned_->count>0) || + !dryRoutingLab_.rebindVerifiedDevice(acceptedWasapiBinding_->epoch, + current->epoch,current->frames,rateChanged)) + return false; + if(auto* device=deviceManager_.getCurrentAudioDevice()) + acceptedMixerBinding_=readMixerBinding(*device); + acceptedWasapiBinding_=std::move(current); + return true; + } catch(...) {return false;} + } + bool approveDirectRoute ( const armix::device::AsioRegistrationPolicy::Identity* expectedAsio = nullptr) { @@ -1741,6 +2349,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback static constexpr int maxFrames = 8192; armix::device::AsioPriorityDeviceManager deviceManager_; armix::device::DirectRouteFence directFence_; + std::optional acceptedMixerBinding_; + std::optional acceptedWasapiBinding_; // CONTROL only + std::optional offeredWasapiBinding_; // one explicit remap // Control-thread only; retain full class identity for exact comparison, // publish correlation HASH only. Never read registry in audio callback. armix::device::AsioRegistrationPolicy::Identity asioPinnedRegistration_; @@ -1771,6 +2382,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback std::atomic routeReconfiguring_ {false}; std::optional savedLiveSetup_; // Indexed atomic bypass flags: instant RT-safe toggles, no graph detachment. + // Temporary publication silence never changes operator MONITOR or MAIN MUTE. + // The DIRECT device fence and physical-output verification remain separate. + std::atomic topologyPublicationMute_ { false }; std::atomic monitor_ { false }, channelMute_ { false }, masterMute_ { false }, masterMono_ { 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 }; @@ -1853,6 +2467,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void audioDeviceAboutToStart (juce::AudioIODevice* d) override { + setOutputMuted(true); secondaryOutput_.invalidateSource(); // source clock may have changed dryRoutingLab_.prepareDevice(d); // exact active mask, before callback if (!independent_.active()) @@ -1904,6 +2519,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void audioDeviceStopped() override { + setOutputMuted(true); secondaryOutput_.invalidateSource(); // explicit reconnect required after device stop masterLoudness_.prepare (0.0); // clear validity across device epoch dryRoutingLab_.deviceStopped(); @@ -1935,7 +2551,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback auto& slot=graph.slots[physical]; if(!slot.processor)continue; auto& bypass=graph.bypassEnvelope[physical]; - bypass.request(graph.bypassFlags[physical].load(std::memory_order_acquire)); + bypass.request(graph.rackBypassed.load(std::memory_order_acquire) || + graph.bypassFlags[physical].load(std::memory_order_acquire)); const bool blend=bypass.transitioning(); if(blend) { @@ -2111,7 +2728,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback activeDiagnosticRoute == armix::diagnostics::Route::normal, !routeReconfiguring_.load(std::memory_order_acquire), !masterMute_.load(std::memory_order_relaxed), - monitor_.load(std::memory_order_relaxed), + monitor_.load(std::memory_order_relaxed) && + !topologyPublicationMute_.load(std::memory_order_acquire), secondaryOutput_.armed()); const bool outputPermitted=outputGate.renderMain; // Native input PCM must remain observable even with safe output MUTE. @@ -2132,7 +2750,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback masterGain_.load(std::memory_order_relaxed), !outputPermitted,&ch1Lease,&processLegacyChannelOne, masterMono_.load(std::memory_order_relaxed), - &nativeMainPair,&nativeMonitorPair); + &nativeMainPair,&nativeMonitorPair, + activeDiagnosticRoute==armix::diagnostics::Route::normal && + !routeReconfiguring_.load(std::memory_order_acquire) && + !topologyPublicationMute_.load(std::memory_order_acquire)); // Constant-time, callback-local physical PCM tap. Nothing is // reconfigured or acquired from another graph generation. const auto nativeMain=armix::mixer::NativeOutputPairTap::select( @@ -2230,6 +2851,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback jassert(armix::mixer::NativeRenderAuthority::mayRunDiagnostic( renderOwner)); const bool enabled = monitor_.load (std::memory_order_relaxed) + && !topologyPublicationMute_.load (std::memory_order_acquire) && !routeReconfiguring_.load (std::memory_order_acquire); const auto route = diagnosticRoute_.load (std::memory_order_relaxed); const bool toneTest = route == armix::diagnostics::Route::outputOnlyTone; diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 82f5ea88b..052949ff9 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -4,10 +4,14 @@ #include "../engine/core/MasterOutputMonoPolicy.h" #include "../engine/core/LiveChannelFxGraph.h" #include "../engine/core/DynamicChannelFxLeaseBank.h" +#include "../engine/device/DeviceSessionTransitionPolicy.h" +#include "../engine/core/NativeFxRackTransaction.h" #include "../engine/core/UnifiedLegacyProductionAdmission.h" #include "VstBusLayout.h" #include "../engine/core/NativeDryRouteCommand.h" #include "NativeVerifiedSourcePatch.h" +#include "NativeTopologyEditSafety.h" +#include "NativeMixerSessionDocument.h" #include "../engine/device/JuceActivePortSnapshot.h" #include "../engine/core/RealtimeRoutePublisher.h" #include "../engine/core/RealtimeRenderPermit.h" @@ -19,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -62,10 +67,16 @@ class LiveDryRoutingLab final { bool mute=false, solo=false, mono=false; }; + // Device callbacks only invalidate admission. CONTROL can later rebind + // the previously active graph after independent hardware verification. + void invalidateDeviceAdmission() noexcept { + channelIdPcmEpoch_.store(0,std::memory_order_release); + } + // JUCE calls aboutToStart after configuring the input/output device. // One device session gets a new epoch; stored route cannot survive it. void prepareDevice (juce::AudioIODevice* device) noexcept { - channelIdPcmEpoch_.store(0,std::memory_order_release); + invalidateDeviceAdmission(); const auto generation=deviceEpoch_.fetch_add(1,std::memory_order_acq_rel)+1; userPatched_.store(false,std::memory_order_release); registryValid_.store(false,std::memory_order_release); @@ -95,7 +106,7 @@ class LiveDryRoutingLab final { registryValid_.store(true,std::memory_order_release); } void deviceStopped() noexcept { - channelIdPcmEpoch_.store(0,std::memory_order_release); + invalidateDeviceAdmission(); // A stale lab cannot silently resume legacy CH1 on device hotplug. userPatched_.store(false,std::memory_order_release); deviceEpoch_.fetch_add(1,std::memory_order_acq_rel); @@ -174,7 +185,8 @@ class LiveDryRoutingLab final { const FxSelections& selections, juce::AudioPluginFormatManager& formats, double sampleRate,int deviceFrames,bool explicitSelection=true, - const FxRestores* restores=nullptr) { + const FxRestores* restores=nullptr, + const std::function& beforePublish={}) { // E5: the M4 compiler cannot encode an admitted native GROUP/FX RETURN. // An M4 APPLY, Show recall or structural SOURCE/AUX edit must not // erase native BUS PCM while its ChannelId graph owns the callback. @@ -279,6 +291,8 @@ class LiveDryRoutingLab final { static_cast(command.getProperty("revision",juce::var(0)))); if(currentEpoch==0 || expectedEpoch!=currentEpoch) return "Audio device changed: reopen ROUTING to remap physical ports"; + if(expectedRevision!=revision()) + return "Routing revision changed before preparation; refresh accepted state"; armix::mixer::NativeDryRouteCommand decoded; juce::String validationError; if(!armix::mixer::NativeDryRouteCommand::decode( @@ -418,12 +432,27 @@ class LiveDryRoutingLab final { if(!registryValid_.load(std::memory_order_acquire) || epochAtPublish!=currentEpoch) return "Audio device changed before routing publication"; + // The old accepted graph continues to render while a new vendor + // instance is scanned, constructed and prepared on CONTROL. Only + // after ALL fallible preparation and the last device-epoch check + // may the caller briefly close the physical output at commit. + // Never call the gate on a failed plugin admission. + if(beforePublish)beforePublish(); // New M4 routing must not render against an older ChannelId graph. - // Output must remain disarmed throughout structural native APPLY. - channelIdPcmEpoch_.store(0,std::memory_order_release); + // The output must be disarmed by the caller at the publication edge. + const auto previousPcmEpoch=channelIdPcmEpoch_.exchange( + 0,std::memory_order_acq_rel); const auto result=publisher_.publish(std::move(next),expectedRevision,epochAtPublish); + // A rejected publication did NOT replace the callback graph. Keep + // the previous admitted native PCM authority rather than silently + // falling back to potentially stale M4 controls on this device. + if(result!=Publisher::Result::applied && + previousPcmEpoch==epochAtPublish && + deviceEpoch_.load(std::memory_order_acquire)==epochAtPublish) + channelIdPcmEpoch_.store(previousPcmEpoch,std::memory_order_release); switch(result) { case Publisher::Result::applied: + reboundQuantum_.store(Block::hardFrameLimit,std::memory_order_release); publishedEpoch_.store(currentEpoch,std::memory_order_release); enabled_.store(true,std::memory_order_release); sendCount_.store(sends.count,std::memory_order_relaxed); @@ -443,6 +472,12 @@ class LiveDryRoutingLab final { // enter ANY channel/master vendor DSP or produce sound. userPatched_.store(explicitSelection,std::memory_order_release); channelEdits_=proposed; // control thread SSOT for this route revision + // The freshly accepted M4 graph now owns these exact controls. + // Dirty native-only gestures have been captured into the new + // graph or superseded by a deliberate explicit APPLY. + // Otherwise re-admission would reject forever after one fader + // gesture and disable all fallback live controls. + nativeControlDirty_=false; for(int i=0;i=fxSlots||slot<0||slot>=maxFxPerLane|| + chosen.id.isEmpty()||chosen.path.isEmpty()||chosen.name.isEmpty()|| + !ready()||!hasExplicitRoute()||nativeStructureLive_|| + topologyFault_.load(std::memory_order_acquire)|| + !registryValid_.load(std::memory_order_acquire)|| + expectedEpoch!=epoch()||expectedRevision!=revision()|| + !sourceTemplate_.isObject()) + return "FX INSERT: stale routing/ChannelId authority or invalid catalog slot"; + if(acceptedFxSelections_[lane][slot].id.isNotEmpty()) + return "FX INSERT: this slot already has a native VST3"; + if(slot>0&&acceptedFxSelections_[lane][slot-1].id.isEmpty()) + return "FX INSERT: choose the first empty insert position"; + return {}; + } + + // SINGLE CONTROL-thread control-state inheritance used by BOTH SOURCE/ + // OUT edits and vendor VST3 insertion. An FX add must not recompile an + // earlier APPLY's fader/PAN/MUTE/SOLO into the already-audible PCM. + // This copies authoritative M4 controls, or the actual ChannelId roster + // while ChannelId owns PCM; it never borrows a browser/demo state. + juce::String inheritLiveControlsForRecompile(juce::var& staged, + std::uint64_t expectedEpoch) const { + auto stagedRows=staged.getProperty("channels",juce::var()); + auto* editable=stagedRows.getArray(); + if(!editable||editable->size()!=count) + return "malformed accepted native channel topology"; + const bool nativeControls=channelIdPhysicalPcmActive(); + if(nativeControls && (nativeStructureLive_ || + nativeAccepted_.deviceEpoch!=expectedEpoch)) + return "incompatible ChannelId roster or stale device epoch"; + for(int i=0;igetReference(i).getDynamicObject(); + if(!row)return "missing accepted native channel"; + const auto& c=channelEdits_[i]; + const auto* accepted=nativeControls + ?nativeAccepted_.graph.roster.find(nativeAccepted_.graph.ids.inputs[i]) + :nullptr; + if(nativeControls && (!accepted || + accepted->role!=armix::mixer::ChannelRole::input)) + return "admitted input channel roster is stale"; + const armix::mixer::NativeTopologyEditSafety::MixSnapshot legacy{ + c.linear,c.pan,c.mute,c.solo}; + const armix::mixer::NativeTopologyEditSafety::MixSnapshot native{ + accepted?accepted->faderLinear:c.linear, + accepted?accepted->pan:c.pan, + accepted?accepted->mute:c.mute, + accepted?accepted->solo:c.solo}; + const auto kept=armix::mixer::NativeTopologyEditSafety::preserveAcceptedMix( + legacy,native,nativeControls); + row->setProperty("gain",static_cast(kept.linear)); + row->setProperty("pan",static_cast(kept.pan)); + row->setProperty("mute",kept.mute); + row->setProperty("solo",kept.solo); + } + return {}; + } + + // Native /preview/ FX picker: append one catalog-verified stereo VST3 to + // the SAME accepted ten-channel/4AUX renderer. This is a prepared graph + // transaction on JUCE CONTROL, never a JS plugin or RT instantiation. + juce::String insertCatalogFx(int lane,int slot, + std::uint64_t expectedEpoch,std::uint64_t expectedRevision, + const FxSelection& chosen,bool directPermitted, + bool independentClock,int occupiedCh1Fx, + juce::AudioPluginFormatManager& formats,double sampleRate, + int deviceFrames, + const std::function& beforePublish={}) { + const auto preflight=fxInsertPreflight( + lane,slot,expectedEpoch,expectedRevision,chosen); + if(preflight.isNotEmpty())return preflight; + auto command=juce::JSON::parse( + juce::JSON::toString(sourceTemplate_,false)); + if(!command.isObject()) + return "FX INSERT: accepted source template cannot be cloned"; + command.getDynamicObject()->setProperty("deviceEpoch",static_cast(expectedEpoch)); + command.getDynamicObject()->setProperty("revision",static_cast(expectedRevision)); + // A vendor plugin prepare happens AFTER live native fader/PAN edits. + // Recompile from the last accepted operator controls, not the stale + // pre-fader sourceTemplate_ values. Rejection keeps the old PCM live. + const auto inherited=inheritLiveControlsForRecompile( + command,expectedEpoch); + if(inherited.isNotEmpty())return "FX INSERT: "+inherited; + auto next=acceptedFxSelections_; + next[lane][slot]=chosen; + return apply(command,directPermitted,independentClock,occupiedCh1Fx, + next,formats,sampleRate,deviceFrames,true,nullptr, + beforePublish); + } + // M1 direct-source parameter: only same-format physical→physical // input on an ALREADY scheduled channel. Route DAG, VST3 lease, FX // identity and hardware output ownership are immutable. Epoch/revision @@ -511,8 +643,10 @@ class LiveDryRoutingLab final { if(!nativePublisher_.setPhysicalSource( expectedEpoch,nativeAccepted_.pcmRevision,id, callbackLeft,mode=="STEREO"?callbackRight:-1, - mode=="STEREO"))rejectedNativeMirror(); - else { + mode=="STEREO")) { + rejectedNativeMirror(); + return "SOURCE SWITCH: native PCM rejected mirror; refresh/recover routing"; + } else { // Physical SOURCE changes are LIVE atomic controls. Persist // the actual callback ordinals for the NEXT Group/FX Return // structural compile rather than reusing stale APPLY pins. @@ -532,6 +666,17 @@ class LiveDryRoutingLab final { return {}; } + // CONTROL-only classification for the operator's direct IN dropdown. + // Fail conservatively to the guarded path for an absent/invalid template. + bool sourceNeedsPreparedGraph(int strip,const juce::String& mode) const { + if(!sourceTemplate_.isObject() || !hasExplicitRoute())return true; + const auto channels=sourceTemplate_.getProperty("channels",juce::var()); + const auto* rows=channels.getArray(); + if(!rows||rows->size()!=count||strip<0||strip>=count)return true; + return armix::mixer::NativeTopologyEditSafety::structuralSource( + true,rows->getReference(strip).getProperty("mode",{}).toString()==mode); + } + // A source changing from NONE to MONO/STEREO needs a new prepared // topology. A source changing physical pin within the same format uses // the existing zero-heap atomic source switch above. Both cases are @@ -542,7 +687,8 @@ class LiveDryRoutingLab final { int physicalLeft,int physicalRight,bool directPermitted, bool independentClock,int occupiedCh1Fx, juce::AudioPluginFormatManager& formats,double sampleRate, - int deviceFrames) + int deviceFrames, + const std::function& beforePublish={}) { if(!ready() || !registryValid_.load(std::memory_order_acquire) || topologyFault_.load(std::memory_order_acquire) || @@ -573,7 +719,7 @@ class LiveDryRoutingLab final { if(error.isNotEmpty())return error; return publishRevisedTopology(staged,expectedEpoch,expectedRevision, directPermitted,independentClock,occupiedCh1Fx,formats, - sampleRate,deviceFrames); + sampleRate,deviceFrames,beforePublish); } // One-click channel OUT and format: the existing native M4 routing/FX @@ -585,7 +731,8 @@ class LiveDryRoutingLab final { const juce::String& operation,const juce::String& requested, bool directPermitted,bool independentClock,int occupiedCh1Fx, juce::AudioPluginFormatManager& formats,double sampleRate, - int deviceFrames) { + int deviceFrames, + const std::function& beforePublish={}) { if(!ready()||!registryValid_.load(std::memory_order_acquire)|| topologyFault_.load(std::memory_order_acquire)|| epoch()!=expectedEpoch||revision()!=expectedRevision|| @@ -617,7 +764,7 @@ class LiveDryRoutingLab final { } else return "CHANNEL PATCH: unsupported graph operation"; return publishRevisedTopology(staged,expectedEpoch,expectedRevision, directPermitted,independentClock,occupiedCh1Fx,formats, - sampleRate,deviceFrames); + sampleRate,deviceFrames,beforePublish); } // Operator one-action AUX send connection: prepare a real parallel @@ -712,25 +859,17 @@ class LiveDryRoutingLab final { std::uint64_t expectedEpoch,std::uint64_t expectedRevision, bool directPermitted,bool independentClock,int occupiedCh1Fx, juce::AudioPluginFormatManager& formats,double sampleRate, - int deviceFrames) { - auto stagedRows=staged.getProperty("channels",juce::var()); - auto* editable=stagedRows.getArray(); - if(!editable||editable->size()!=count) - return "CHANNEL PATCH: malformed native topology"; - for(int i=0;igetReference(i).getDynamicObject(); - if(!row)return "CHANNEL PATCH: missing native channel"; - const auto& c=channelEdits_[i]; - row->setProperty("gain",static_cast(c.linear)); - row->setProperty("pan",static_cast(c.pan)); - row->setProperty("mute",c.mute); - row->setProperty("solo",c.solo); - } + int deviceFrames, + const std::function& beforePublish={}) { + const auto inherited=inheritLiveControlsForRecompile( + staged,expectedEpoch); + if(inherited.isNotEmpty())return "CHANNEL PATCH: "+inherited; if(expectedEpoch!=epoch()||expectedRevision!=revision()|| !registryValid_.load(std::memory_order_acquire)) return "CHANNEL PATCH: device changed; previous mix preserved"; return apply(staged,directPermitted,independentClock,occupiedCh1Fx, - acceptedFxSelections_,formats,sampleRate,deviceFrames,true); + acceptedFxSelections_,formats,sampleRate,deviceFrames,true, + nullptr,beforePublish); } // Native live control path. Only the JUCE message thread writes. No @@ -946,6 +1085,16 @@ class LiveDryRoutingLab final { }); } + // Master rack gate is a single RT-visible atomic per lane; never overwrite + // stored individual insert bypass flags. Safe under current epoch/revision. + bool setFxRackBypass(int lane,std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,bool bypass) noexcept { + if(lane<0||lane>=fxSlots||!hasExplicitRoute()|| + expectedEpoch!=epoch()||expectedRevision!=revision())return false; + return publisher_.updateActiveControl(expectedEpoch,expectedRevision, + [&](FxGraph& fx) noexcept {return fx.setRackBypass(lane,bypass);}); + } + // Quiescent message-thread identity lease for the vendor's native GUI. // Shared lifetime is independent of route reorder, but not authority: // an editor request MUST match the current accepted route. @@ -1081,7 +1230,8 @@ class LiveDryRoutingLab final { if(!applied.ok() || generation!=epoch() || m4Revision!=revision()) return false; // selected M4 PCM owns the safe fallback nativeControlDirty_=false; // fresh accepted legacy/native control baseline - channelIdPcmEpoch_.store(generation,std::memory_order_release); + installNativeHardware(generation,nativeAccepted_.hardware, + nativeAccepted_.graph.request.maxFrames); return true; } catch(...) { // Failure is on CONTROL; the original M4/Orbit graph remains @@ -1116,7 +1266,7 @@ class LiveDryRoutingLab final { std::uint64_t expectedRosterRevision,armix::mixer::ChannelId target, const juce::String& catalogId, armix::mixer::DynamicChannelFxLeaseBank::Lease processor, - bool outputsDisarmed=false) { + bool verifiedPreparedLiveInsert=false) { using namespace armix::mixer; NativeBusResult out{}; out.pcmRevision=nativeAccepted_.pcmRevision; @@ -1127,18 +1277,17 @@ class LiveDryRoutingLab final { expectedPcmRevision!=nativeAccepted_.pcmRevision|| expectedRosterRevision!=nativeAccepted_.graph.roster.revision()) return out; - if(!outputsDisarmed) {out.error="OUTPUT_MUST_BE_DISARMED";return out;} + if(!verifiedPreparedLiveInsert) { + out.error="NATIVE_INSERT_REQUIRES_PREPARED_INTERNAL_FX";return out; + } const auto* current=nativeAccepted_.graph.roster.find(target); - if(!current || (current->role!=ChannelRole::input && - current->role!=ChannelRole::group)) { + if(!current || current->role==ChannelRole::monitor) { out.error="NATIVE_INSERT_TARGET_UNAVAILABLE";return out; } - // The fixed 10 CH/4 AUX rack remains owned by M4/Show while migrating. - // Never replace or double-render one of its vendor instances. - for(const auto id:nativeAccepted_.graph.ids.inputs) - if(id==target){out.error="M4_INSERT_USE_EXISTING_RACK";return out;} - if(originalM4Aux(target)){ - out.error="M4_INSERT_USE_EXISTING_RACK";return out; + // PCM authority, not historical strip ordinal, owns every new FX. + // An occupied external CH1 chain still needs a combined lease contract. + if(nativeAccepted_.fxOwners->externalChannel()==target) { + out.error="EXTERNAL_CH1_INSERT_CHAIN_ALREADY_OWNED";return out; } if(catalogId.isEmpty()||catalogId.getNumBytesAsUTF8()>256) { out.error="INVALID_VST3_CATALOG_ID";return out; @@ -1169,11 +1318,14 @@ class LiveDryRoutingLab final { fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept{ (*static_cast(ctx))(id,l,r,n); }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; fx.deviceEpoch=expectedEpoch; fx.graphRevision=expectedPcmRevision+1; const auto published=nativePublisher_.commit( next,nativeAccepted_.graph.request,expectedPcmRevision, - expectedEpoch,epoch(),true,std::move(fx)); + expectedEpoch,epoch(),false,std::move(fx),false,true); if(!published.ok()) { out.error="NATIVE_VST3_PCM_COMMIT_REJECTED";return out; } @@ -1191,12 +1343,66 @@ class LiveDryRoutingLab final { out.error="NATIVE_VST3_ADMISSION_FAILED";return out; } } + NativeBusResult editNativeFxRack(std::uint64_t ep,std::uint64_t revision, + std::uint64_t rosterRevision,armix::mixer::ChannelId source,std::size_t slot, + const juce::String& token,armix::mixer::ChannelId target,std::size_t position) { + using namespace armix::mixer; + NativeBusResult reply;reply.error="STALE_NATIVE_FX_RACK"; + if(!channelIdPhysicalPcmActive()||!ready()||ep!=epoch()|| + nativeAccepted_.deviceEpoch!=ep||nativeAccepted_.pcmRevision!=revision|| + !nativeAccepted_.fxOwners)return reply; + try { + DynamicChannelRoster roster;DynamicChannelFxLeaseBank prepared; + if(!prepareNativeFxRackEdit(ep,revision,rosterRevision, + nativeAccepted_.graph.roster,*nativeAccepted_.fxOwners,source, + slot,token,target,position,roster,prepared)) { + reply.error="NATIVE_FX_RACK_IDENTITY_OR_POSITION_REJECTED";return reply; + } + auto owner=std::make_shared(std::move(prepared)); + DynamicNativeSessionPublisher::FxPlan fx; + fx.owner=owner;fx.context=owner.get();fx.deviceEpoch=ep;fx.graphRevision=revision+1; + fx.render=+[](void* p,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(p))(id,l,r,n); + }; + fx.latency=+[](void* p,ChannelId id) noexcept { + return static_cast(p)->latencySamples(id); + }; + const auto committed=nativePublisher_.commit(roster,nativeAccepted_.graph.request, + revision,ep,epoch(),false,std::move(fx),false,true); + if(!committed.ok()){reply.error="NATIVE_FX_RACK_PCM_COMMIT_REJECTED";return reply;} + nativeAccepted_.graph.roster=std::move(roster);nativeAccepted_.fxOwners=std::move(owner); + nativeAccepted_.pcmRevision=committed.revision;nativeStructureLive_=true; + nativeMeterEpoch_.store(0,std::memory_order_release); + reply.accepted=true;reply.error="";reply.pcmRevision=committed.revision; + reply.rosterRevision=nativeAccepted_.graph.roster.revision();return reply; + }catch(...){reply.error="NATIVE_FX_RACK_PREPARE_FAILED";return reply;} + } + bool retainsFxEditor(std::uint64_t ep,const FxGraph::InstanceLease& owner) const noexcept { + if(!owner||ep!=epoch()||!ready())return false; + if(channelIdPhysicalPcmActive())return nativeAccepted_.fxOwners&& + nativeAccepted_.fxOwners->retainsEditor(owner); + const auto* prepared=publisher_.controlPrepared(ep,revision()); + if(prepared)for(int lane=0;laneinsertsOn(lane);++slot) + if(prepared->insertInstanceId(lane,slot)==owner->instanceId)return true; + return false; + } bool bypassNativeInsert(std::uint64_t epochAtEdit,std::uint64_t pcmRevision, armix::mixer::ChannelId target,std::size_t slot, const juce::String& token,bool bypass) noexcept { return nativeAccepted_.setFxBypass(nativePublisher_,epochAtEdit, pcmRevision,target,slot,token,bypass); } + bool nativeChannelIsOriginalCh1(armix::mixer::ChannelId target) const noexcept { + return nativeAccepted_.fxOwners && + nativeAccepted_.fxOwners->externalChannel()==target && + target==nativeAccepted_.graph.ids.inputs[0]; + } + bool bypassNativeRack(std::uint64_t epochAtEdit,std::uint64_t pcmRevision, + armix::mixer::ChannelId target,bool bypass) noexcept { + return nativeAccepted_.setFxRackBypass(nativePublisher_,epochAtEdit, + pcmRevision,target,bypass); + } armix::mixer::DynamicChannelFxLeaseBank::Lease leaseNativeInsertEditor( std::uint64_t epochAtEdit,std::uint64_t pcmRevision, armix::mixer::ChannelId target,std::size_t slot, @@ -1212,7 +1418,8 @@ class LiveDryRoutingLab final { std::span selection, const std::string& name,float sendGain, armix::mixer::ChannelId remove={}, - bool outputsDisarmed=false) { + bool outputsDisarmed=false, + const std::function& beforePublish={}) { using namespace armix::mixer; NativeBusResult reply{}; reply.pcmRevision=nativeAccepted_.pcmRevision; @@ -1272,8 +1479,14 @@ class LiveDryRoutingLab final { fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { (*static_cast(ctx))(id,l,r,n); }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; fx.deviceEpoch=expectedEpoch; fx.graphRevision=expectedPcmRevision+1; + // Keep old PCM running throughout candidate validation/FX lease + // reuse, and briefly gate hardware only at native publication. + if(beforePublish)beforePublish(); const auto published=nativePublisher_.commit( next,nativeAccepted_.graph.request,expectedPcmRevision, expectedEpoch,epoch(),true,std::move(fx)); @@ -1300,6 +1513,93 @@ class LiveDryRoutingLab final { } } + // User-facing M/ST toggle after ChannelId takes over. This changes + // processing width and pan semantics, NOT physical source pins, OUT + // routing or the operator's MONITOR state. Reuse vendor leases and + // publish the complete accepted PCM DAG atomically from CONTROL. + NativeBusResult editNativeProcessingFormat( + std::uint64_t expectedEpoch,std::uint64_t expectedPcmRevision, + std::uint64_t expectedRosterRevision,armix::mixer::ChannelId channel, + armix::mixer::ProcessingFormat format,bool outputsDisarmed=false, + const std::function& beforePublish={}) { + using namespace armix::mixer; + NativeBusResult reply{}; + reply.pcmRevision=nativeAccepted_.pcmRevision; + reply.rosterRevision=nativeAccepted_.graph.roster.revision(); + if(!outputsDisarmed){ + reply.error="PROCESSING_FORMAT_REQUIRES_PUBLICATION_GATE";return reply; + } + if(!channelIdPhysicalPcmActive()||!ready()|| + expectedEpoch!=epoch()||nativeAccepted_.deviceEpoch!=expectedEpoch|| + !nativeAccepted_.fxOwners|| + expectedPcmRevision!=nativeAccepted_.pcmRevision|| + expectedRosterRevision!=nativeAccepted_.graph.roster.revision()) { + reply.error="STALE_NATIVE_PROCESSING_GRAPH";return reply; + } + const auto* current=nativeAccepted_.graph.roster.find(channel); + if(!current || current->role!=ChannelRole::input || + (format!=ProcessingFormat::mono && format!=ProcessingFormat::stereo) || + current->format==format) { + reply.error="INVALID_NATIVE_PROCESSING_FORMAT";return reply; + } + // CH1 may have an externally leased vendor graph. Its width needs + // an explicit combined VST contract; do not reassign that owner here. + if(nativeAccepted_.fxOwners->externalChannel()==channel) { + reply.error="EXTERNAL_VST_LAYOUT_NOT_ADMITTED";return reply; + } + try { + auto roster=nativeAccepted_.graph.roster; + // LiveDryRoutingLab has an unrelated legacy M4 ChannelEdit. + // Select the ChannelId roster's native edit ABI explicitly. + armix::mixer::ChannelEdit edit; + edit.kind=armix::mixer::ChannelEdit::Kind::setFormat; + edit.id=channel; + edit.format=format; + const std::array edits{edit}; + if(!roster.edit(expectedRosterRevision,edits).ok()) { + reply.error="NATIVE_PROCESSING_ROSTER_REJECTED";return reply; + } + DynamicChannelFxLeaseBank bank; + if(DynamicChannelFxLeaseBank::reuseWithProcessingFormat( + expectedEpoch,expectedPcmRevision+1, + *nativeAccepted_.fxOwners,channel,format,bank)!= + DynamicChannelFxLeaseBank::Fault::none) { + reply.error="NATIVE_PROCESSING_FX_REBIND_REJECTED";return reply; + } + auto owner=std::make_shared( + std::move(bank)); + DynamicNativeSessionPublisher::FxPlan fx; + fx.owner=std::static_pointer_cast(owner); + fx.context=owner.get(); + fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(ctx))(id,l,r,n); + }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; + fx.deviceEpoch=expectedEpoch; + fx.graphRevision=expectedPcmRevision+1; + if(beforePublish)beforePublish(); // no hardware mute during prepare + const auto published=nativePublisher_.commit( + roster,nativeAccepted_.graph.request,expectedPcmRevision, + expectedEpoch,epoch(),true,std::move(fx)); + if(!published.ok()) { + reply.error="NATIVE_PROCESSING_PCM_COMMIT_REJECTED";return reply; + } + nativeAccepted_.graph.roster=std::move(roster); + nativeAccepted_.fxOwners=std::move(owner); + nativeAccepted_.pcmRevision=published.revision; + nativeStructureLive_=true; // never restore stale M4 width + nativeMeterEpoch_.store(0,std::memory_order_release); + reply.accepted=true;reply.error=""; + reply.pcmRevision=published.revision; + reply.rosterRevision=nativeAccepted_.graph.roster.revision(); + return reply; + } catch(...) { + reply.error="NATIVE_PROCESSING_PREPARE_FAILED";return reply; + } + } + // Product Console: a NEW stable ChannelId input, not a fixed M4 ordinal // or an unowned JS strip. Starts unpatched and silent. Structural graph, // old vendor FX leases and MAIN routing publish as ONE control transaction. @@ -1356,6 +1656,9 @@ class LiveDryRoutingLab final { fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { (*static_cast(ctx))(id,l,r,n); }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; fx.deviceEpoch=expectedEpoch; fx.graphRevision=expectedPcmRevision+1; const auto published=nativePublisher_.commit( @@ -1385,7 +1688,8 @@ class LiveDryRoutingLab final { NativeBusResult patchNativeInputSource(std::uint64_t expectedEpoch, std::uint64_t expectedPcmRevision,std::uint64_t expectedRosterRevision, armix::mixer::ChannelId channel,int physicalLeft, - int physicalRight,bool stereo,bool outputsDisarmed=false) { + int physicalRight,bool stereo,bool outputsDisarmed=false, + const std::function& beforePublish={}) { using namespace armix::mixer; NativeBusResult reply{}; reply.pcmRevision=nativeAccepted_.pcmRevision; @@ -1398,28 +1702,32 @@ class LiveDryRoutingLab final { expectedRosterRevision!=nativeAccepted_.graph.roster.revision()) return reply; const auto* target=nativeAccepted_.graph.roster.find(channel); - if(!target||target->role!=ChannelRole::input||!nativeStructureLive_) { - reply.error="NOT_DYNAMIC_INPUT";return reply; + if(!target||target->role!=ChannelRole::input){ + reply.error="NATIVE_INPUT_ID_UNAVAILABLE";return reply; } - for(const auto id:nativeAccepted_.graph.ids.inputs) - if(channel==id) {reply.error="M4_INPUT_NOT_DYNAMIC";return reply;} + const bool disconnect=!stereo&&physicalLeft==-1&&physicalRight==-1; int l=-1,r=-1; - for(int i=0;i(ctx))(id,left,right,n); }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; fx.deviceEpoch=expectedEpoch;fx.graphRevision=expectedPcmRevision+1; + if(beforePublish)beforePublish(); // late PCM publication gate const auto published=nativePublisher_.commit( nativeAccepted_.graph.roster,request,expectedPcmRevision, expectedEpoch,epoch(),true,std::move(fx)); @@ -1444,6 +1756,8 @@ class LiveDryRoutingLab final { nativeAccepted_.graph.request=std::move(request); nativeAccepted_.fxOwners=std::move(owner); nativeAccepted_.pcmRevision=published.revision; + nativeStructureLive_=true; // M4 source roster no longer authoritative + nativeMeterEpoch_.store(0,std::memory_order_release); reply.accepted=true;reply.error=""; reply.pcmRevision=published.revision; reply.rosterRevision=nativeAccepted_.graph.roster.revision(); @@ -1501,6 +1815,9 @@ class LiveDryRoutingLab final { fx.render=+[](void* ctx,ChannelId id,float* l,float* rr,int n) noexcept{ (*static_cast(ctx))(id,l,rr,n); }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; fx.deviceEpoch=ep;fx.graphRevision=expectedPcmRev+1; const auto published=nativePublisher_.commit( roster,nativeAccepted_.graph.request,expectedPcmRev, @@ -1550,7 +1867,11 @@ class LiveDryRoutingLab final { auto roster=nativeAccepted_.graph.roster; const auto changed=roster.wireTransaction(expectedRosterRev,changes); if(!changed.ok()){ - r.error="NATIVE_WIRE_TRANSACTION_REJECTED";return r; + r.error=changed.fault==ChannelEditFault::missingEdge + ?"NATIVE_WIRE_STALE_EDGE": + changed.fault==ChannelEditFault::duplicateSend + ?"NATIVE_WIRE_DUPLICATE_ROUTE":"NATIVE_WIRE_TRANSACTION_REJECTED"; + return r; } DynamicChannelFxLeaseBank bank; if(DynamicChannelFxLeaseBank::reuseRevision( @@ -1565,13 +1886,18 @@ class LiveDryRoutingLab final { fx.render=+[](void* ctx,ChannelId id,float* l,float* rr,int n) noexcept { (*static_cast(ctx))(id,l,rr,n); }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; fx.deviceEpoch=ep; fx.graphRevision=expectedPcmRev+1; const auto published=nativePublisher_.commit( roster,nativeAccepted_.graph.request,expectedPcmRev, ep,epoch(),false,std::move(fx),true); if(!published.ok()){ - r.error="NATIVE_WIRE_PCM_GRAPH_REJECTED";return r; + r.error=published.graphError.fault==DynamicGraphFault::cycle + ?"NATIVE_WIRE_FEEDBACK_CYCLE":"NATIVE_WIRE_PCM_GRAPH_REJECTED"; + return r; } nativeAccepted_.graph.roster=std::move(roster); nativeAccepted_.fxOwners=std::move(owner); @@ -1647,12 +1973,219 @@ class LiveDryRoutingLab final { return nativeAccepted_.graph.roster.rememberLiveMix(id,gain,pan); } + // Realtime GROUP/FX_RETURN mute and solo have the same verified + // ChannelId PCM target as INPUT, but NEVER mutate an original M4 AUX. + bool setNativeBusMuteSolo(std::uint64_t epochAtEdit, + std::uint64_t expectedPcmRevision, + armix::mixer::ChannelId id, + bool mute,bool solo) noexcept { + if(!channelIdPhysicalPcmActive()||epochAtEdit!=epoch()|| + expectedPcmRevision!=nativeAccepted_.pcmRevision)return false; + const auto* channel=nativeAccepted_.graph.roster.find(id); + if(!channel || (channel->role!=armix::mixer::ChannelRole::group && + channel->role!=armix::mixer::ChannelRole::fxReturn) || + originalM4Aux(id))return false; + if(!nativePublisher_.setChannelMuteSolo( + epochAtEdit,expectedPcmRevision,id,mute,solo))return false; + if(!nativeAccepted_.graph.roster.rememberLiveMuteSolo(id,mute,solo)) { + topologyFault_.store(true,std::memory_order_release); + return false; + } + nativeControlDirty_=true; + return true; + } + + // EdgeId-keyed live SEND level: no graph compile, VST recreation or + // callback handoff. Primary outputs retain their unity-gain contract. + bool setNativeWireGain(std::uint64_t ep,std::uint64_t graphRev, + std::uint64_t rosterRev,armix::mixer::ChannelId source, + std::uint64_t edgeId,float gain) noexcept { + if(!channelIdPhysicalPcmActive()||!ready()||ep!=epoch()|| + graphRev!=nativeAccepted_.pcmRevision|| + rosterRev!=nativeAccepted_.graph.roster.revision()|| + !std::isfinite(gain)||gain<0.f||gain>4.f)return false; + const auto* row=nativeAccepted_.graph.roster.find(source); + if(!row||!edgeId)return false; + for(const auto& edge:row->sends) + if(edge.edgeId==edgeId&&!edge.primaryOutput) { + if(!nativePublisher_.setWireGain(ep,graphRev,source,edgeId,gain))return false; + if(!nativeAccepted_.graph.roster.rememberLiveParallelSend( + source,edge.destination,edge.preFader,gain))return false; + nativeControlDirty_=true; + return true; + } + return false; + } + int nativePcmLatencySamples() const noexcept { + return channelIdPhysicalPcmActive()? + nativePublisher_.latencySamples(epoch(),nativeAccepted_.pcmRevision):0; + } // CONTROL snapshot: genuine stable ChannelIds from the SAME publisher // as physical PCM. No guessed IDs, synthetic UI routes or JS DSP. - juce::var nativeBusStatus() const { - if(!channelIdPhysicalPcmActive() || !nativeAccepted_.fxOwners)return {}; + + // CONTROL-only capture of the currently INSTALLED ChannelId PCM graph. + // Fail closed if any vendor cannot supply a quiescent binary state. + juce::String captureNativeMixerSession( + armix::session::MixerSessionDocument& document, + std::vector& blobs, + bool retained=false) noexcept { + using namespace armix::mixer; + const auto observedEpoch=epoch(); + const auto documentEpoch=retained?nativeAccepted_.deviceEpoch:observedEpoch; + if((!retained && !channelIdPhysicalPcmActive()) || + (retained && channelIdPhysicalPcmActive()) || + !nativeAccepted_.matches(nativePublisher_,documentEpoch,nativeAccepted_.pcmRevision)) + return "No authoritative native ChannelId graph"; + if(nativeAccepted_.fxOwners->externalChannel().value) + return "External CH1 FX owner cannot yet be serialized independently"; + // MAIN and STREAM are muted by the caller. Wait briefly for the + // current callback to leave the vendor processors before capturing. + std::optional renderPermit; + for(int attempt=0;attempt<50;++attempt) { + renderPermit.emplace(rendering_); + if(*renderPermit)break; + juce::Thread::sleep(1); + } + if(!*renderPermit)return "Audio callback did not quiesce for mixer capture"; + try { + armix::session::MixerSessionDocument draft; + draft.roster=nativeAccepted_.graph.roster; + draft.acceptedRevision=draft.roster.revision(); + draft.legacyIds=nativeAccepted_.graph.ids; + draft.outputs=nativeAccepted_.hardware; + draft.request=nativeAccepted_.graph.request; + std::vector staged; + std::set hashes; + juce::int64 total=0; + for(const auto& channel:draft.roster.channels()) { + const auto count=nativeAccepted_.fxOwners->insertCount(channel.id); + if(count>static_cast(FxGraph::maxInsertsPerStrip)) + return "Native FX count exceeded per-channel rack"; + if(nativeAccepted_.fxOwners->rackBypassed(channel.id)) + draft.rackBypassed.push_back(channel.id); + for(std::size_t slot=0;slotownerForControl(channel.id,slot); + if(!owner||!*owner||!(*owner)->processor|| + (*owner)->catalogId.isEmpty()) + return "Native FX lease missing during capture"; + juce::MemoryBlock bytes; + if(!(*owner)->tryCaptureState(bytes)) + return "VST3 state not quiescent: "+(*owner)->catalogId; + total+=static_cast(bytes.getSize()); + if(total>128LL*1024LL*1024LL) + return "Native mixer vendor-state budget exceeded"; + const auto hash=juce::SHA256(bytes).toHexString(); + draft.inserts.push_back({channel.id,slot,(*owner)->catalogId, + {},hash,(*owner)->name,0, + (*owner)->bypassRequested.load(std::memory_order_acquire)}); + if(hashes.insert(hash).second) { + armix::shows::BinaryState entry; + entry.sha256=hash;entry.bytes=std::move(bytes); + staged.push_back(std::move(entry)); + } + } + } + if(epoch()!=observedEpoch || + !nativeAccepted_.matches(nativePublisher_,documentEpoch,nativeAccepted_.pcmRevision)) + return "Native graph changed during FX snapshot"; + document=std::move(draft); + blobs=std::move(staged); + return {}; + } catch(...) {return "Native graph/VST3 state capture failed";} + } + + // Match CONTROL's live device readback to the masks registered for the + // actual callback epoch. Neither a saved document nor an M4 graph + // attests which physical pins the current callback can address. + bool matchesSessionDevice(const armix::device::JuceActivePortSnapshot& pins) const noexcept { + if(!registryValid_.load(std::memory_order_acquire) || + topologyFault_.load(std::memory_order_acquire) || + !pins.matchesCallback(epoch(),callbackInputCount_.load(std::memory_order_acquire), + callbackOutputCount_.load(std::memory_order_acquire))) + return false; + for(int i=0;i bank, + const armix::device::JuceActivePortSnapshot& pins, + bool outputsDisarmed,bool replaceActive=false) { + using namespace armix::mixer; + if(!outputsDisarmed || (!replaceActive && channelIdPhysicalPcmActive()) || !bank) + return "Restore requires a muted device"; + const auto generation=pins.epoch; + if(!matchesSessionDevice(pins) || bank->epoch()!=generation || + document.request.physicalInputs!=pins.inputs.enabledCount || + document.outputs.activeOutputChannels!=pins.outputCount || + !document.outputs.valid()) + return "NEEDS_REMAP: verified callback layout changed"; + if(document.request.maxFrames<32 || document.request.maxFrames>Block::hardFrameLimit) + return "Invalid native mixer quantum"; + try { + document.request.maxScratchBytes=32U*1024U*1024U; + const auto previous=nativePublisher_.acceptedRevision(); + DynamicNativeSessionPublisher::FxPlan fx; + fx.owner=std::static_pointer_cast(bank); + fx.context=bank.get(); + fx.deviceEpoch=generation;fx.graphRevision=previous+1; + fx.render=+[](void* p,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(p))(id,l,r,n); + }; + fx.latency=+[](void* p,ChannelId id) noexcept { + return static_cast(p)->latencySamples(id); + }; + const auto published=nativePublisher_.commit( + document.roster,document.request,previous,generation,epoch(), + true,std::move(fx)); + if(!published.ok()) + return "Native ChannelId PCM rejected persisted topology: "+ + juce::String(static_cast(published.fault)); + nativeAccepted_.graph.roster=std::move(document.roster); + nativeAccepted_.graph.request=std::move(document.request); + nativeAccepted_.graph.ids=document.legacyIds; + nativeAccepted_.graph.revision=nativeAccepted_.graph.roster.revision(); + nativeAccepted_.hardware=document.outputs; + nativeAccepted_.fxOwners=std::move(bank); + nativeAccepted_.deviceEpoch=generation; + nativeAccepted_.pcmRevision=published.revision; + nativeStructureLive_=true; + nativeControlDirty_=true; + publishedEpoch_.store(0,std::memory_order_release); + publisher_.unpublish(); + nativeMeterEpoch_.store(0,std::memory_order_release); + // Only the logical source patch is restored. Physical OUT remains + // disarmed until the user independently enables monitoring. + installNativeHardware(generation,nativeAccepted_.hardware, + nativeAccepted_.graph.request.maxFrames); + return channelIdPhysicalPcmActive()?juce::String{}: + juce::String("NEEDS_REMAP: device changed during native publication"); + }catch(...) {return "Native session restore exception";} + } + + bool matchesNativeMixerOutputs(const armix::mixer::VerifiedNativeOutputs& outputs) const noexcept { + return channelIdPhysicalPcmActive() && + armix::session::MixerDeviceBindingPolicy::sameOutputs(nativeAccepted_.hardware,outputs); + } + + std::uint64_t nativeGraphRevisionForRestore() const noexcept { + const auto current=nativePublisher_.acceptedRevision(); + return current==std::numeric_limits::max()?0:current+1; + } + + juce::var nativeBusStatus(bool retained=false) const { + if(!nativeAccepted_.fxOwners || + (!retained && !channelIdPhysicalPcmActive()))return {}; const auto* routing=nativePublisher_.acceptedRouting( - epoch(),nativeAccepted_.pcmRevision); + nativeAccepted_.deviceEpoch,nativeAccepted_.pcmRevision); if(!routing)return {}; auto state=std::make_unique(); state->setProperty("graphRevision",juce::String( @@ -1660,25 +2193,33 @@ class LiveDryRoutingLab final { state->setProperty("rosterRevision",juce::String( std::to_string(routing->rosterRevision))); state->setProperty("structural",nativeStructureLive_); + if(!retained) + state->setProperty("latencySamples",nativePublisher_.latencySamples(epoch(),nativeAccepted_.pcmRevision)); juce::Array allowed; // Only expose operations backed by a real DSP lease. Dynamic // FX_RETURN insertion is not available until a native VST3 owner // can be prepared for its new ChannelId; do not advertise it. - for(const char* op: {"NATIVE_CREATE_GROUP_SELECTED", + if(!retained) + for(const char* op: {"NATIVE_CREATE_GROUP_SELECTED", "NATIVE_REMOVE_BUS","NATIVE_SET_BUS_MIX", "NATIVE_CREATE_CHANNEL","NATIVE_PATCH_CHANNEL", "NATIVE_SET_PRIMARY_OUT", "NATIVE_APPLY_WIRE_TRANSACTION", + "NATIVE_SET_WIRE_GAIN", + "NATIVE_SET_PROCESSING_FORMAT", "NATIVE_SET_CHANNEL_MIX", "NATIVE_SET_CHANNEL_MUTE_SOLO", - "NATIVE_LOAD_INSERT","NATIVE_SET_INSERT_BYPASS", + "NATIVE_SET_BUS_MUTE_SOLO", + "NATIVE_LOAD_INSERT","NATIVE_REMOVE_INSERT","NATIVE_MOVE_INSERT", + "NATIVE_SET_INSERT_BYPASS", "NATIVE_OPEN_INSERT_EDITOR"}) allowed.add(juce::var(juce::String(op))); state->setProperty("supportedOps",juce::var(allowed)); juce::Array rows; // Meter taps come from the SAME realtime ChannelId renderer, in // accepted roster order. No JS guesses or second DSP render. - const bool pcmMeterValid=nativeMeterEpoch_.load(std::memory_order_acquire)==epoch(); + const bool pcmMeterValid=!retained && + nativeMeterEpoch_.load(std::memory_order_acquire)==epoch(); std::size_t meterIndex=0; for(const auto& ch:routing->channels) { auto row=std::make_unique(); @@ -1715,11 +2256,15 @@ class LiveDryRoutingLab final { item->setProperty("instanceId",(*lease)->instanceId); item->setProperty("id",(*lease)->catalogId); item->setProperty("name",(*lease)->name); + item->setProperty("latencySamples",(*lease)->latencySamples); + item->setProperty("latencyChanged",(*lease)->latencyChanged.load(std::memory_order_acquire)); item->setProperty("bypassed",(*lease)->bypassRequested.load( std::memory_order_relaxed)); liveInserts.add(juce::var(item.release())); } row->setProperty("inserts",juce::var(liveInserts)); + row->setProperty("fxRackBypassed", + nativeAccepted_.fxOwners->rackBypassed(ch.id)); if(pcmMeterValid && meterIndexsetProperty("peakL",static_cast( nativeMeterPeaksL_[meterIndex].load(std::memory_order_relaxed))); @@ -1735,13 +2280,15 @@ class LiveDryRoutingLab final { for(const auto& source:nativeAccepted_.graph.request.sources) { if(source.id!=ch.id)continue; auto physical=std::make_unique(); - if(source.inputL>=0&&source.inputLsetProperty("bindingState","NEEDS_REMAP"); + if(!retained && source.inputL>=0 && + source.inputLsetProperty("portId","in:"+juce::String(pin)); } // Preserve BOTH actual physical pins on native readback, not // just the left pin. The GUI may not invent the right channel. - if(source.stereo && source.inputR>=0 && + if(!retained && source.stereo && source.inputR>=0 && source.inputRsetProperty("portIdRight","in:"+juce::String(right)); @@ -1798,9 +2345,16 @@ class LiveDryRoutingLab final { topologyFault_.store(true,std::memory_order_release); else channelIdPcmEpoch_.store(0,std::memory_order_release); } + std::uint64_t controlRevision() const noexcept { + return channelIdPhysicalPcmActive() && nativeStructureLive_ + ?nativeAccepted_.pcmRevision:revision(); + } + bool hasVerifiedNativeSources() const noexcept { + return channelIdPhysicalPcmActive() && !nativeAccepted_.graph.request.sources.empty(); + } bool channelIdPhysicalPcmActive() const noexcept { const auto active=channelIdPcmEpoch_.load(std::memory_order_acquire); - return active!=0 && active==epoch() && ready() && + return active!=0 && active==epoch() && registryValid_.load(std::memory_order_acquire) && !topologyFault_.load(std::memory_order_acquire); } @@ -1836,14 +2390,99 @@ class LiveDryRoutingLab final { bool active() const noexcept {return enabled_.load(std::memory_order_acquire);} float peakLeft() const noexcept {return peakL_.load(std::memory_order_relaxed);} float peakRight() const noexcept {return peakR_.load(std::memory_order_relaxed);} + // CONTROL ONLY: hardware loss makes ready() false but does not erase + // authored values, FX identity, GROUP/FX_RETURN buses or accepted WIREs. + // Never downgrade this dynamic document to the fixed 10CH/4AUX schema. + bool hasRetainedNativeSession() const noexcept { + return !channelIdPhysicalPcmActive() && nativeAccepted_.fxOwners && hasAuthoredMixerContent(); + } + bool hasAuthoredMixerContent() const noexcept { + if(acceptedRoute_.isObject() || nativeStructureLive_ || nativeControlDirty_) + return true; + for(const auto& lane:acceptedFxSelections_) + for(const auto& fx:lane) + if(fx.id.isNotEmpty())return true; + if(nativeAccepted_.fxOwners) + for(const auto& channel:nativeAccepted_.graph.roster.channels()) + if(nativeAccepted_.fxOwners->insertCount(channel.id)>0) + return true; + return false; + } + // CONTROL only. The verified profile proves identical port ordinals. + // Rebuild DSP scratch/PDC while retaining the accepted document and + // compatible processors. Never re-use a processor at a different rate. + bool rebindVerifiedDevice(std::uint64_t priorEpoch,std::uint64_t newEpoch, + int deviceFrames,bool rateChanged) { + using namespace armix::mixer; + if(!priorEpoch || newEpoch<=priorEpoch || newEpoch!=epoch() || + !active() || !registryValid_.load(std::memory_order_acquire) || + topologyFault_.load(std::memory_order_acquire))return false; + if(nativeAccepted_.matches(nativePublisher_,priorEpoch,nativeAccepted_.pcmRevision)) { + const auto revision=nativeAccepted_.pcmRevision; + const auto& hardware=nativeAccepted_.hardware; + if(nativeAccepted_.graph.request.physicalInputs!= + callbackInputCount_.load(std::memory_order_acquire) || + hardware.activeOutputChannels!=callbackOutputCount_.load(std::memory_order_acquire)) + return false; + bool hasEffects=nativeAccepted_.fxOwners->externalChannel().value!=0; + for(const auto& row:nativeAccepted_.graph.roster.channels()) + if(nativeAccepted_.fxOwners->insertCount(row.id)>0){hasEffects=true;break;} + auto request=nativeAccepted_.graph.request; + request.maxFrames=armix::device::retainedMixerQuantum( + request.maxFrames,deviceFrames,Block::hardFrameLimit,rateChanged,hasEffects); + if(request.maxFrames==0)return false; + auto owner=std::make_shared(); + if(DynamicChannelFxLeaseBank::rebindSameFormat( + newEpoch,revision+1,*nativeAccepted_.fxOwners,*owner)!= + DynamicChannelFxLeaseBank::Fault::none)return false; + DynamicNativeSessionPublisher::FxPlan fx; + fx.owner=owner;fx.context=owner.get(); + fx.deviceEpoch=newEpoch;fx.graphRevision=revision+1; + fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(ctx))(id,l,r,n); + }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; + const auto applied=nativePublisher_.commit(nativeAccepted_.graph.roster,request, + revision,newEpoch,epoch(),true,std::move(fx)); + if(!applied.ok())return false; + nativeAccepted_.graph.request=std::move(request); + nativeAccepted_.deviceEpoch=newEpoch; + nativeAccepted_.pcmRevision=applied.revision; + nativeAccepted_.fxOwners=std::move(owner); + nativeControlDirty_=true; + installNativeHardware(newEpoch,hardware,nativeAccepted_.graph.request.maxFrames); + return channelIdPhysicalPcmActive(); + } + if(nativeStructureLive_ || nativeControlDirty_ || publishedEpoch_.load( + std::memory_order_acquire)!=priorEpoch || !acceptedRoute_.isObject())return false; + const auto* compatibility=publisher_.controlPrepared(priorEpoch,revision()); + if(!compatibility)return false; + bool hasEffects=false; + if(rateChanged) + for(int lane=0;laneinsertsOn(lane)>0; + const int quantum=armix::device::retainedMixerQuantum( + std::min(compatibility->maxFramesPerPlugin(),reboundQuantum_.load(std::memory_order_acquire)), + deviceFrames,Block::hardFrameLimit,rateChanged,hasEffects); + if(!quantum || !publisher_.rebindQuiescent(priorEpoch,newEpoch,[&]() noexcept { + return newEpoch==epoch(); + }))return false; + reboundQuantum_.store(quantum,std::memory_order_release); + publishedEpoch_.store(newEpoch,std::memory_order_release); + userPatched_.store(true,std::memory_order_release); + return newEpoch==epoch() && ready(); + } bool ready() const noexcept { return active() && !topologyFault_.load(std::memory_order_acquire) - && publishedEpoch_.load(std::memory_order_acquire)==epoch(); + && (channelIdPhysicalPcmActive() || + publishedEpoch_.load(std::memory_order_acquire)==epoch()); } // Status / control thread only. An empty prepared graph is ready, but // cannot be advertised as a LIVE patched route or a savable Show. bool hasExplicitRoute() const noexcept { - return ready() && acceptedRoute_.isObject(); + return channelIdPhysicalPcmActive() || (ready() && acceptedRoute_.isObject()); } std::uint64_t epoch() const noexcept { return deviceEpoch_.load(std::memory_order_acquire); @@ -1860,7 +2499,8 @@ class LiveDryRoutingLab final { FxGraph::ExternalStripFx externalFx=nullptr, bool masterMono=false, std::array* actualOutputPair=nullptr, - std::array* actualMonitorPair=nullptr) noexcept { + std::array* actualMonitorPair=nullptr, + bool allowMutedMetering=false) noexcept { if(actualOutputPair)*actualOutputPair={{-1,-1}}; if(actualMonitorPair)*actualMonitorPair={{-1,-1}}; if(!active())return false; @@ -1920,20 +2560,23 @@ class LiveDryRoutingLab final { silence();return true; } const auto generation=epoch(); - auto lease=publisher_.acquire(); + const bool channelIdRender=generation!=0 && + channelIdPcmEpoch_.load(std::memory_order_acquire)==generation; + // Native hardware destinations are published before native admission. + // The compatibility lease is only required by its own render path. + auto lease=publisher_.acquire(channelIdRender); const auto* snapshot=lease.get(generation); - if(!snapshot||!snapshot->prepared || - inputCount!=callbackInputCount_.load(std::memory_order_acquire)) { - if(inputCount!=callbackInputCount_.load(std::memory_order_acquire)) - topologyFault_.store(true,std::memory_order_release); - fadeRemaining_=0; - lastOutputL_=lastOutputR_=0.f; + if(!channelIdRender && (!snapshot || !snapshot->prepared)) { + silence();return true; + } + const auto native=channelIdRender? + nativeHardware_.load(std::memory_order_acquire):0; + const int outLeft=channelIdRender?nativePin(native,0):snapshot->prepared->mainOutputLeft(); + const int outRight=channelIdRender?nativePin(native,1):snapshot->prepared->mainOutputRight(); + if(epoch()!=generation || (channelIdRender && + channelIdPcmEpoch_.load(std::memory_order_acquire)!=generation)) { silence();return true; } - // Callback destinations come only from the leased immutable graph. - // If a driver restarts or changes topology, silence all outputs. - const int outLeft=snapshot->prepared->mainOutputLeft(); - const int outRight=snapshot->prepared->mainOutputRight(); if(outLeft<0||outRight<0||outLeft==outRight|| outLeft>=outputCount||outRight>=outputCount|| !outputs[outLeft]||!outputs[outRight]){ @@ -1944,9 +2587,11 @@ class LiveDryRoutingLab final { float* const mainR=outputs[outRight]; float* monitorL=nullptr; float* monitorR=nullptr; - if(snapshot->prepared->monitorEnabled()) { - const int l=snapshot->prepared->monitorOutputLeft(); - const int r=snapshot->prepared->monitorOutputRight(); + const int monitorLeft=channelIdRender?nativePin(native,2): + snapshot->prepared->monitorOutputLeft(); + if(channelIdRender?monitorLeft>=0:snapshot->prepared->monitorEnabled()) { + const int l=monitorLeft; + const int r=channelIdRender?nativePin(native,3):snapshot->prepared->monitorOutputRight(); if(l<0||r<0||l>=outputCount||r>=outputCount|| l==r||l==outLeft||l==outRight||r==outLeft||r==outRight|| !outputs[l]||!outputs[r]) { @@ -1959,36 +2604,36 @@ class LiveDryRoutingLab final { // Return the callback indices from THIS leased prepared graph. // The post-render FX transition and meters must not re-read a // potentially newer route or assume hardware channels 0/1. - if(actualOutputPair)*actualOutputPair={{outLeft,outRight}}; - if(snapshot->graphRevision!=audioRevision_ || generation!=audioEpoch_) { - audioRevision_=snapshot->graphRevision; + if(actualOutputPair && !masterMuted)*actualOutputPair={{outLeft,outRight}}; + if(masterMuted && actualMonitorPair)*actualMonitorPair={{-1,-1}}; + const auto renderRevision=channelIdRender?0:snapshot->graphRevision; + if(renderRevision!=audioRevision_ || generation!=audioEpoch_) { + audioRevision_=renderRevision; audioEpoch_=generation; fadeRemaining_=rampFrames; fadeFromL_=lastOutputL_; fadeFromR_=lastOutputR_; } - // Strict output mute wins over every topology fade. Output buffers - // are cleared by the fail-silent gate, so skip all muted DSP work. - // Prime a 256-sample fade FROM ZERO for the first unmuted block. - // Never interpolate any previously audible sample while muted. + // Muted native metering uses scratch and keeps the output ramp at zero. + const bool meterOnly=masterMuted && allowMutedMetering && channelIdRender; if(masterMuted) { masterMonoPolicy_.primeWhileMuted(masterMono); fadeRemaining_=rampFrames; fadeFromL_=fadeFromR_=0.f; lastOutputL_=lastOutputR_=0.f; - silence();return true; + if(!meterOnly){silence();return true;} } // Large/variable JUCE quantum is chunked using stack pointer views; // no heap allocation or new processing object inside callback. std::array shifted{}; - const int max=snapshot->prepared->maxFramesPerPlugin(); + int max=channelIdRender?static_cast(native>>36): + std::min(snapshot->prepared->maxFramesPerPlugin(), + reboundQuantum_.load(std::memory_order_acquire)); + if(meterOnly)max=std::min(max,mutedMeterFrames); if(max<=0) { topologyFault_.store(true,std::memory_order_release); silence();return true; } - const bool channelIdRender= - channelIdPcmEpoch_.load(std::memory_order_acquire)==generation && - generation!=0; float peakL=0.f,peakR=0.f,monitorPeakL=0.f,monitorPeakR=0.f; std::array perChannelPeaks{}; std::array perChannelPeaksL{},perChannelPeaksR{}; @@ -2010,9 +2655,11 @@ class LiveDryRoutingLab final { const auto noExtraFx=[](armix::mixer::ChannelId,float*,float*,int) noexcept {}; processed=nativePublisher_.render( generation,shifted.data(),inputCount, - mainL+offset,mainR+offset,n,false,noExtraFx, - monitorL?monitorL+offset:nullptr, - monitorR?monitorR+offset:nullptr,tapsL,tapsR); + meterOnly?mutedMain_[0].data():mainL+offset, + meterOnly?mutedMain_[1].data():mainR+offset,n,false,noExtraFx, + monitorL?(meterOnly?mutedMonitor_[0].data():monitorL+offset):nullptr, + monitorR?(meterOnly?mutedMonitor_[1].data():monitorR+offset):nullptr, + tapsL,tapsR); if(processed) { for(std::size_t ch=0;chsetProperty("nativeBusStructural",nativeStructureLive_); if(nativePcm)out->setProperty("nativeBus",nativeBusStatus()); + else if(hasAuthoredMixerContent()) { + auto retained=nativeBusStatus(true); + if(retained.isObject()) + out->setProperty("retainedNativeBus",std::move(retained)); + } // This exact original vendor Graph owner is retained by the native // accepted snapshot, NOT merely a catalog name or M4 CH1 label. // Message-thread diagnostic only; no false universal capabilities. @@ -2128,7 +2783,7 @@ class LiveDryRoutingLab final { nativeAccepted_.fxOwners->externalChannel()== nativeAccepted_.graph.ids.inputs[0]); out->setProperty("epoch",static_cast(epoch())); - out->setProperty("revision",static_cast(revision())); + out->setProperty("revision",static_cast(controlRevision())); out->setProperty("peakL",peakL_.load(std::memory_order_relaxed)); out->setProperty("peakR",peakR_.load(std::memory_order_relaxed)); out->setProperty("monitorPeakL",monitorPeakL_.load(std::memory_order_relaxed)); @@ -2169,6 +2824,10 @@ class LiveDryRoutingLab final { liveFxInstances.add(juce::var(slots)); } out->setProperty("fxInstances",juce::var(liveFxInstances)); + juce::Array rackFlags; + for(int lane=0;lanerackBypassed(lane):false); + out->setProperty("fxRackBypassed",juce::var(rackFlags)); juce::Array controls,fxNames; for(int i=0;isetProperty("outputPorts",juce::var(outputPorts)); - juce::Array liveMain; + juce::Array liveMain,liveMonitor,liveMonitorSends; const auto* mainGraph=publisher_.controlPrepared(epoch(),revision()); - if(mainGraph&&ready()&®istryValid_.load(std::memory_order_acquire)){ - const int l=mainGraph->mainOutputLeft(),r=mainGraph->mainOutputRight(); + const auto addPair=[&](juce::Array& pair,int left,int right) { const int n=callbackOutputCount_.load(std::memory_order_acquire); - if(l>=0&&r>=0&&l=n || right>=n)return; + pair.add(enabledOutputPorts_[left].load(std::memory_order_relaxed)); + pair.add(enabledOutputPorts_[right].load(std::memory_order_relaxed)); + }; + if(nativePcm) { + const auto& hw=nativeAccepted_.hardware; + addPair(liveMain,hw.mainL,hw.mainR); + if(hw.monitorEnabled)addPair(liveMonitor,hw.monitorL,hw.monitorR); + } else if(mainGraph && ready() && registryValid_.load(std::memory_order_acquire)) { + addPair(liveMain,mainGraph->mainOutputLeft(),mainGraph->mainOutputRight()); + if(mainGraph->monitorEnabled()) + addPair(liveMonitor,mainGraph->monitorOutputLeft(),mainGraph->monitorOutputRight()); + } + if(mainGraph && !liveMonitor.isEmpty()) + for(float gain:mainGraph->monitorGains())liveMonitorSends.add(gain); out->setProperty("mainOutputs",juce::var(liveMain)); - juce::Array liveMonitor,liveMonitorSends; - if(mainGraph && mainGraph->monitorEnabled() && - ready() && registryValid_.load(std::memory_order_acquire)) { - const int l=mainGraph->monitorOutputLeft(); - const int r=mainGraph->monitorOutputRight(); - const int n=callbackOutputCount_.load(std::memory_order_acquire); - if(l>=0&&r>=0&&lmonitorGains())liveMonitorSends.add(gain); - } - } out->setProperty("monitorOutputs",juce::var(liveMonitor)); out->setProperty("monitorSends",juce::var(liveMonitorSends)); out->setProperty("note","Native 10CH+4AUX production mixer; unpatched startup is SILENT. Explicit input assignment/ACK required. Hardware FAT unqualified."); return juce::var(out.release()); } private: + // Four 9-bit callback indices (0 means absent) and the prepared quantum. + // One atomic read gives AUDIO a coherent destination/quantum contract. + std::atomic nativeHardware_{0}; + static int nativePin(std::uint64_t hardware,int index) noexcept { + return static_cast((hardware>>(index*9))&511U)-1; + } + void installNativeHardware(std::uint64_t generation, + const armix::mixer::VerifiedNativeOutputs& hw,int frames) noexcept { + nativeHardware_.store((static_cast(frames)<<36) | + (static_cast(hw.monitorR+1)<<27) | + (static_cast(hw.monitorL+1)<<18) | + (static_cast(hw.mainR+1)<<9) | + static_cast(hw.mainL+1),std::memory_order_release); + enabled_.store(true,std::memory_order_release); + nativeMeterEpoch_.store(0,std::memory_order_release); + channelIdPcmEpoch_.store(generation,std::memory_order_release); + userPatched_.store(true,std::memory_order_release); + } + static constexpr int mutedMeterFrames=512; + std::array,2> mutedMain_{},mutedMonitor_{}; std::atomic_flag rendering_=ATOMIC_FLAG_INIT; // one AUDIO producer Publisher publisher_; armix::mixer::DynamicNativeSessionPublisher nativePublisher_; @@ -2276,6 +2952,7 @@ class LiveDryRoutingLab final { std::atomic topologyFault_{false}; std::atomic deviceEpoch_{0}; std::atomic publishedEpoch_{0}; + std::atomic reboundQuantum_{Block::hardFrameLimit}; std::atomic callbackInputCount_{-1}; std::atomic callbackOutputCount_{-1}; std::atomic enabled_{false}; diff --git a/src/Main.cpp b/src/Main.cpp index 6fc8336b8..c31dcdf05 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -9,16 +9,23 @@ #include "../integration/ApprovedNativeRuntimeSnapshot.h" #include "../integration/ApprovedNativeControlIntent.h" #include "LiveAudioEngine.h" +#include "NativeSessionToken.h" #include "ArSonMixStartupSplash.h" #include "VstOrbitController.h" #include "../engine/core/OrbitDistanceMapping.h" #include "../engine/core/DearVrPolarPolicy.h" #include "DiagnosticsRecorder.h" #include "../engine/device/DirectRestoreBackoff.h" +#include "../engine/device/AudioSetupRecoveryPolicy.h" #include "../engine/device/PeriodCapabilityEvidence.h" #include "../engine/diagnostics/CrackleEvidenceWindow.h" #if defined(_WIN32) #include "../engine/device/WasapiCapabilityProbe.h" +#include +#include +#if defined(_MSC_VER) +#pragma comment(lib, "Psapi.lib") +#endif #endif #include "PluginCatalog.h" #include "PortableWorkspace.h" @@ -26,6 +33,8 @@ #include "NativeLiveShowCapture.h" #include "NativeDryShowRecall.h" #include "NativeShowSaveWorker.h" +#include "NativeChannelAppearanceStore.h" +#include "NativeMixerSessionSaveWorker.h" #include #include #include @@ -198,13 +207,36 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr onStartupStage_ (std::move (onStartupStage)), browser_ (webViewOptions() .withNativeIntegrationEnabled() - .withEventListener ("arMixGuiReady", [this] (juce::var) + .withEventListener ("arMixGuiReady", [this] (juce::var ready) { browser_.loaded = true; guiReadyTick_ = juce::Time::getMillisecondCounter(); + // WebView2 may finish its first navigation while this + // DocumentWindow is still hidden behind the splash. On + // 125%/150% DPI its child controller can keep that *old* + // bounds even though JUCE has already resized the content. + // Reapply actual browser bounds on the message thread, + // once after the native peer is visible: NO audio work. + const int cssWidth = static_cast (ready.getProperty ("viewportWidth", 0)); + const int cssHeight = static_cast (ready.getProperty ("viewportHeight", 0)); + if ((cssWidth > 0 && std::abs (cssWidth - browser_.getWidth()) > 2) || + (cssHeight > 0 && std::abs (cssHeight - browser_.getHeight()) > 2)) + diagnostics_.record ("WEBVIEW2_INITIAL_BOUNDS", + juce::String (cssWidth) + "x" + juce::String (cssHeight) + + " host=" + juce::String (browser_.getWidth()) + "x" + + juce::String (browser_.getHeight())); + juce::MessageManager::callAsync ( + [safe = juce::Component::SafePointer (this)] + { + if (safe && safe->browser_.isShowing()) + safe->browser_.resized(); + }); browser_.repaint(); if (onStartupStage_) onStartupStage_ (1); }) + .withEventListener ("arMixChannelIdentitySet", [this] (juce::var args) { + handleNativeChannelIdentitySet(args); + }) .withEventListener ("arMixConsoleSubscribe", [this] (juce::var) { // G0 real-device native producer, NEVER a synthetic ChannelId callback. consoleSubscribed_ = true; @@ -234,7 +266,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr setResizable (true, true); setResizeLimits (1100, 650, 3840, 2160); setContentNonOwned (&browser_, false); - centreWithSize (1650, 930); + // A fixed 1650x930 initial HWND exceeds the *logical* Windows work + // area on high-DPI laptops. Clamp BEFORE WebView2 first navigation, + // instead of letting Windows resize the outer peer without matching + // the child compositor during its hidden first-frame startup. + const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay(); + const auto available = display != nullptr + ? display->userArea : juce::Rectangle (0, 0, 1650, 930); + centreWithSize (juce::jlimit (1100, 1650, available.getWidth() - 24), + juce::jlimit (650, 930, available.getHeight() - 24)); // Keep native main window hidden during its expensive initial WebView2 // construction. The opaque always-on-top splash owns first paint. // After one control tick, reveal the PEER behind splash if WebView2 @@ -252,6 +292,16 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Startup must not spend seconds enumerating third-party VST3 modules. } + // Rebind the embedded WebView2 controller whenever its JUCE content + // window is resized. This catches the hidden-peer/show path, DPI moves + // and normal operator window drags without a per-frame polling timer. + void resized() override + { + juce::DocumentWindow::resized(); + if (getContentComponent() == &browser_ && browser_.isShowing()) + browser_.resized(); + } + ~ConsoleWindow() override { stopTimer(); @@ -260,6 +310,18 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr closePluginEditor(); audioSetupWindow_.reset(); engine_.devices().removeChangeListener (this); + // Drain any earlier file work before the final muted checkpoint. + // Remember MAIN before the shutdown mute changes the hardware state. + const bool resumeMain=engine_.isMonitorEnabled(); + engine_.setOutputMuted(true); + engine_.disconnectSecondaryOutput(); + mixerSessionWorker_.finishForShutdown(); + const auto lab=engine_.status().getProperty("dryRoutingLab",{}); + if(static_cast(lab.getProperty("nativeChannelIdPcmActive",false))) { + const auto error=saveMixerSession(resumeMain); + if(error.isNotEmpty()) + diagnostics_.record("DYNAMIC_MIXER_EXIT_SAVE_REJECTED",error); + } engine_.stop(); browser_.setVisible (false); } @@ -272,11 +334,20 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr juce::int64 fxGraphRevision_ = 1; // control-thread monotonic graph generation PluginCatalog catalog_; DiagnosticsRecorder diagnostics_; + armix::appearance::Store channelAppearance_{settingsDirectory()}; armix::storage::NativePresetArchive presets_; std::function onStartupStage_; Browser browser_; armix::storage::StudioBackup::Worker studioBackupWorker_; armix::shows::NativeShowSaveWorker nativeShowWorker_; + armix::session::NativeMixerSessionSaveWorker mixerSessionWorker_; + juce::String mixerSessionId_,mixerSessionStatus_="NO_SAVED_SESSION"; + juce::String mixerSessionError_,lastMixerSessionFingerprint_; + bool mixerSessionStartupInspected_=false; + bool mixerSessionRecoveryPending_=false; + std::unique_ptr mixerFileChooser_; + bool mixerFileDialogOpen_=false; + juce::File lastMixerFile_; bool nativeShowBusy_ = false; bool studioBackupBusy_ = false; std::unique_ptr chooser_; @@ -284,13 +355,22 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Destruction order: editorWindow_ releases its JUCE GUI BEFORE the // retained vendor processor lease. No vendor destructor runs on RT. armix::mixer::LiveChannelFxGraph::InstanceLease routedEditorOwner_; - juce::int64 routedEditorEpoch_=0; + std::uint64_t routedEditorEpoch_=0; + struct PendingNativeEq { + armix::mixer::LiveChannelFxGraph::InstanceLease owner; + juce::String request,channelId,deviceEpoch,revision,instanceId; + int slot=-1; + juce::uint32 started=0; + } pendingNativeEq_; + juce::String lastNativeEqRequest_,lastNativeEqInstance_; + juce::String lastNativeEqEpoch_,lastNativeEqRevision_; std::unique_ptr editorWindow_; std::unique_ptr audioSetupWindow_; juce::String startupError_, lastAudioXml_; bool initialStateSent_ = false; bool consoleSubscribed_ = false; // Real snapshot subscription; not FAT certification juce::StringArray acceptedControlRequests_; // bounded request replay fence + juce::StringArray acceptedAppearanceRequests_; // identity request replay fence bool webViewPeerWarmed_ = false; bool webViewStartupNoticeSent_ = false; juce::uint32 webViewStartupTick_ = 0; @@ -381,12 +461,45 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return {static_cast(amount), true}; } + // O(1) Windows OS counters at the existing 1 Hz AUDIO_HEALTH poll + // (and explicit Mark Crackle); never inside audioDeviceIOCallback. + // GlobalMemoryStatusEx load is whole-system RAM pressure, NOT process + // usage. PROCESS_MEMORY_COUNTERS_EX PageFaultCount includes SOFT faults; + // a Windows ETW hard-fault trace is needed to prove disk paging. + static armix::diagnostics::CrackleEvidenceWindow::MemoryPressure + readMemoryPressure() noexcept + { + using Memory = armix::diagnostics::CrackleEvidenceWindow::MemoryPressure; + Memory out; +#if defined(_WIN32) + MEMORYSTATUSEX system {}; + system.dwLength = sizeof(system); + if(::GlobalMemoryStatusEx(&system) != FALSE) + { + out.systemAvailable = true; + out.systemLoadPercent = system.dwMemoryLoad; + out.availablePhysicalMiB = system.ullAvailPhys/(1024ull*1024ull); + } + PROCESS_MEMORY_COUNTERS_EX process {}; + if(::GetProcessMemoryInfo(::GetCurrentProcess(), + reinterpret_cast(&process), + static_cast(sizeof(process))) != FALSE) + { + out.processAvailable = true; + out.processWorkingSetMiB = process.WorkingSetSize/(1024ull*1024ull); + out.processPrivateCommitMiB = process.PrivateUsage/(1024ull*1024ull); + out.processPageFaults = process.PageFaultCount; + } +#endif + return out; + } static armix::diagnostics::CrackleEvidenceWindow::Sample makeEvidenceSample ( const juce::var& state) { using Window = armix::diagnostics::CrackleEvidenceWindow; Window::Sample out; out.atMs = monotonicMilliseconds(); + out.memory = readMemoryPressure(); out.connected = bool(state.getProperty("connected", false)); const auto epoch = evidenceCounter(state.getProperty("deviceGeneration", {})); if (!epoch.available) out.connected = false; @@ -430,10 +543,38 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return out; } - juce::String crackleWindowReport (const juce::var& status) const + static juce::String compactMemoryWindowReport ( + const armix::diagnostics::CrackleEvidenceWindow::Window& window) + { + const auto& before=window.memoryBefore; + const auto& at=window.memoryAtMark; + const auto fmt=[](std::uint64_t value,bool valid) { + return valid ? juce::String(static_cast(value)) + : juce::String("N/A"); + }; + juce::String result="RAM_LOAD_START_PCT="; + result+=fmt(before.systemLoadPercent,window.ready()&&before.systemAvailable); + result+=" | RAM_LOAD_MARK_PCT="; + result+=fmt(at.systemLoadPercent,window.ready()&&at.systemAvailable); + result+=" | RAM_LOAD_PREMARK_PEAK_PCT="; + result+=fmt(window.peakLoadPercent,window.loadComparable); + result+=" | FREE_PHYSICAL_MIB="; + result+=fmt(at.availablePhysicalMiB,window.ready()&&at.systemAvailable); + result+=" | PROCESS_WORKING_SET_MIB="; + result+=fmt(at.processWorkingSetMiB,window.ready()&&at.processAvailable); + result+=" | PROCESS_PRIVATE_COMMIT_MIB="; + result+=fmt(at.processPrivateCommitMiB,window.ready()&&at.processAvailable); + result+=" | ALL_PAGE_FAULTS_DELTA="; + result+=fmt(window.processPageFaults.value, + window.processPageFaults.comparable); + result+=" | HARD_FAULTS=UNAVAILABLE | NOT_CAUSAL_PROOF"; + return result; + } + + juce::String crackleWindowReport ( + const armix::diagnostics::CrackleEvidenceWindow::Window& window) const { using Window = armix::diagnostics::CrackleEvidenceWindow; - const auto window = crackleEvidence_.mark (makeEvidenceSample(status)); juce::String report = "PRE_MARK_EVIDENCE_5S="; report += Window::reasonName(window.reason); report += " | elapsedMs=" + juce::String(static_cast(window.elapsedMs)); @@ -449,6 +590,34 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr ? juce::String(static_cast(delta.value)) : juce::String("N/A"); } + const auto& before = window.memoryBefore; + const auto& marked = window.memoryAtMark; + report += " | SYSTEM_RAM_LOAD_BEFORE_PCT="; + report += window.ready() && before.systemAvailable + ? juce::String(before.systemLoadPercent):juce::String("N/A"); + report += " | SYSTEM_RAM_LOAD_AT_MARK_PCT="; + report += window.ready() && marked.systemAvailable + ? juce::String(marked.systemLoadPercent):juce::String("N/A"); + report += " | SYSTEM_RAM_LOAD_WINDOW_PEAK_PCT="; + report += window.loadComparable + ? juce::String(window.peakLoadPercent):juce::String("N/A"); + report += " | SYSTEM_AVAILABLE_PHYSICAL_MIB_AT_MARK="; + report += window.ready() && marked.systemAvailable + ? juce::String(static_cast(marked.availablePhysicalMiB)) + : juce::String("N/A"); + report += " | ARSONMIX_WORKING_SET_MIB_AT_MARK="; + report += window.ready() && marked.processAvailable + ? juce::String(static_cast(marked.processWorkingSetMiB)) + : juce::String("N/A"); + report += " | ARSONMIX_PRIVATE_COMMIT_MIB_AT_MARK="; + report += window.ready() && marked.processAvailable + ? juce::String(static_cast(marked.processPrivateCommitMiB)) + : juce::String("N/A"); + report += " | PROCESS_ALL_PAGE_FAULTS_SOFT_OR_HARD_DELTA="; + report += window.processPageFaults.comparable + ? juce::String(static_cast(window.processPageFaults.value)) + : juce::String("N/A"); + report += " | OS_HARD_PAGE_FAULTS=UNAVAILABLE_REQUIRES_ETW"; report += " | CORRELATION_ONLY_NOT_CAUSAL_PROOF"; return report; } @@ -765,8 +934,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Actual prepared M4 epoch/revision enables the native First Sound // hardware PATCH/ARM workflow before full ChannelId admission. (void) armix::console::publishVerifiedFirstSoundState (accepted, live); - (void) armix::console::projectInstalledNativeChannelIdGraph ( - accepted, live); + if (!armix::console::projectInstalledNativeChannelIdGraph (accepted, live)) + (void) armix::console::projectRetainedNativeChannelIdGraph (accepted, live); + // Sole control-thread SessionSnapshot from the installed PCM publisher. + armix::console::publishAuthoritativeMixerSession(accepted); + if(auto* obj=accepted.getDynamicObject()) + obj->setProperty("channelAppearance",channelAppearance_.snapshot(accepted.getProperty("graph",{}))); return accepted; } @@ -782,6 +955,35 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr "arMixConsoleSnapshot", approvedNativeSnapshot()); } + // UI-only native transaction. No PCM mutation; never arm an output. + void handleNativeChannelIdentitySet(const juce::var& request) + { + const auto v=request.getProperty("requestId",{}); + const auto id=v.isString()?v.toString():juce::String{}; + juce::String error; + if(id.isEmpty()||id.length()>120) + error="INVALID_CHANNEL_APPEARANCE_REQUEST_ID"; + else if(acceptedAppearanceRequests_.contains(id)) + error="DUPLICATE_CHANNEL_APPEARANCE_REQUEST_ID"; + else { + acceptedAppearanceRequests_.add(id); + if(acceptedAppearanceRequests_.size()>256) + acceptedAppearanceRequests_.remove(0); + error=channelAppearance_.apply(request,approvedNativeSnapshot()); + } + auto ack=std::make_unique(); + ack->setProperty("requestId",id); + ack->setProperty("ok",error.isEmpty()); + ack->setProperty("error",error); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible("arMixChannelIdentityAck",juce::var(ack.release())); + if(error.isEmpty()) { + diagnostics_.record("NATIVE_CHANNEL_APPEARANCE_SAVED", + request.getProperty("channelId","").toString()); + emitApprovedNativeSnapshot(); + } else diagnostics_.record("NATIVE_CHANNEL_APPEARANCE_REJECTED",error); + } + // One native dispatcher; the source of truth is the already installed // ENGINE callback. This code executes on the JUCE message thread, not RT. void handleApprovedNativeControl(const juce::var& request) @@ -802,8 +1004,47 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } const auto translated=armix::console::translateApprovedNativeControl( request,before,installedBus); - const bool applied=!replay&&translated.ok()&& - armix::console::executeApprovedNativeControl(engine_,translated.translated); + bool applied=false; + juce::String nativeError; + if(!replay&&translated.ok()) { + const auto command=translated.translated; + if(command.getProperty("operation","").toString()=="NATIVE_LOAD_INSERT") { + // Exactly one catalog-resolved vendor processor from the + // installed native library. No browser path, ordinal M4 + // fallback, secondary DSP or user-visible MONITOR ritual. + const auto args=command.getProperty("payload",{}); + const auto catalogId=args.getProperty("catalogId","").toString(); + const bool builtInEq=catalogId== + armix::builtin_fx::ChannelEqProcessor::catalogIdentity; + const auto* plugin=builtInEq?nullptr:catalog_.find(catalogId); + std::uint64_t ep=0,rev=0,roster=0,target=0; + if((!builtInEq&&!plugin)||catalog_.busy()||nativeShowBusy_|| + studioBackupBusy_||engine_.isGraphSwitchPending()) { + nativeError="NATIVE_VST3_CATALOG_OR_HOST_BUSY"; + } else if(!armix::console::approvedNativeId( + command.getProperty("deviceEpoch",{}),ep) || + !armix::console::approvedNativeId( + command.getProperty("baseGraphRevision",{}),rev) || + !armix::console::approvedNativeId( + command.getProperty("baseRosterRevision",{}),roster) || + !armix::console::approvedNativeId( + command.getProperty("targetChannelId",{}),target)) { + nativeError="NATIVE_VST3_INVALID_SESSION_ID"; + } else { + const auto result=builtInEq? + engine_.installNativeBuiltInEq( + ep,rev,roster,armix::mixer::ChannelId{target}): + engine_.installNativeVst3( + ep,rev,roster,armix::mixer::ChannelId{target}, + plugin->path,plugin->uid,plugin->key()); + applied=result.accepted && result.error && + result.error[0]==0; + if(!applied)nativeError=result.error; + } + } else { + applied=armix::console::executeApprovedNativeControl(engine_,command,&nativeError); + } + } // An engine setter ACK is not independent PCM evidence. Re-read the // same physical callback authority after mutation before claiming it // was accepted; browser then explicitly requests LATER readback. @@ -821,6 +1062,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr ack->setProperty("errorCode",nativeStillAdmitted?"NONE": replay?"DUPLICATE_REQUEST_ID": translated.error.isNotEmpty()?translated.error: + nativeError.isNotEmpty()?nativeError: applied?"NATIVE_CALLBACK_LOST":"NATIVE_PCM_MUTATION_REJECTED"); ack->setProperty("deviceEpoch",device.getProperty("epoch","0")); ack->setProperty("graphRevision",graph.getProperty("revision","0")); @@ -982,7 +1224,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // thread. A vendor driver may block; never pretend JS async fixes it. const auto id=args.getProperty("requestId",{}).toString().substring(0,64); const auto oldGeneration=engine_.status().getProperty("deviceGeneration",0); - auto send=[&](bool ok,const juce::String& state,const juce::String& error) + auto send=[&](bool ok,const juce::String& state,const juce::String& error, + bool canReusePins=false) { auto ack=std::make_unique(); ack->setProperty("requestId",id); @@ -991,6 +1234,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr ack->setProperty("error",error); ack->setProperty("active",currentDeviceSnapshot()); ack->setProperty("outputMuted",engine_.isOutputMuted()); + ack->setProperty("mixerBound",engine_.hasBoundMixerRoute()); + ack->setProperty("canReusePins",canReusePins); if(browser_.loaded) browser_.emitEventIfBrowserIsVisible("arMixAudioDeviceApplyAck",juce::var(ack.release())); }; @@ -1042,6 +1287,31 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto previousType=manager.getCurrentAudioDeviceType(); const bool sameEndpoint=unchangedDevice&&before.inputDeviceName==capture &&before.outputDeviceName==playback; + auto* previousDevice=manager.getCurrentAudioDevice(); + const bool previousWasOpen=previousDevice!=nullptr&&previousDevice->isOpen(); + const auto confirm=config.getProperty("confirmRetainedPinMapping",false); + if(!confirm.isBool()) + return send(false,"REJECTED","Invalid retained mixer mapping confirmation"); + if(static_cast(confirm)) { + // The first Apply must open and verify the selected device. + // Confirmation binds only that exact, still-open generation; + // draft rate, buffer and pin changes use the normal Apply path. + if(!sameEndpoint || !previousWasOpen || rate!=before.sampleRate || + block!=before.bufferSize || + !engine_.confirmRetainedWasapiPortMapping()) + return send(false,"NEEDS_REMAP", + "Cannot reuse mixer pins. Endpoint, pin layout or FX format is incompatible."); + deviceSettingsDirty_=true; + directRestore_.cancel(); + diagnostics_.record("CUSTOM_AUDIO_REMAP_ACCEPTED",typeName); + send(true,"ACCEPTED_MUTED",{}); + emitApprovedNativeSnapshot(); + return; + } + const auto originalInputNames=previousWasOpen + ?previousDevice->getInputChannelNames():juce::StringArray{}; + const auto originalOutputNames=previousWasOpen + ?previousDevice->getOutputChannelNames():juce::StringArray{}; juce::AudioDeviceManager::AudioDeviceSetup candidate=before; candidate.inputDeviceName=capture; candidate.outputDeviceName=playback; @@ -1052,12 +1322,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Its first APPLY uses safe defaults; then users refine real pin masks. const auto pinInput=config.getProperty("enabledInputs",{}); const auto pinOutput=config.getProperty("enabledOutputs",{}); - if(sameEndpoint && pinInput.isArray() && pinOutput.isArray()) { - auto* active=manager.getCurrentAudioDevice(); - if(active==nullptr||!active->isOpen()) - return send(false,"REJECTED","Current device is not open; refresh"); - const auto inCount=juce::jmin(64,active->getInputChannelNames().size()); - const auto outCount=juce::jmin(64,active->getOutputChannelNames().size()); + // External ASIO4ALL changes can leave the same endpoint name in JUCE + // with a closed object. Reopen with safe default masks first; the + // previous (possibly reordered) physical pin indices are not valid. + const auto recovery=armix::device::AudioSetupRecoveryPolicy::select( + sameEndpoint,previousWasOpen,typeName=="ASIO", + pinInput.isArray()&&pinOutput.isArray()); + if(recovery.reuseActivePins) { + const auto inCount=juce::jmin(64,previousDevice->getInputChannelNames().size()); + const auto outCount=juce::jmin(64,previousDevice->getOutputChannelNames().size()); auto parsePins=[](const juce::var& values,int limit,juce::BigInteger& mask)->bool { const auto* array=values.getArray(); if(array==nullptr||array->size()>64)return false; @@ -1100,12 +1373,29 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto start=monotonicMilliseconds(); engine_.beginManualAudioSetup(); if(!unchangedDevice)manager.setCurrentAudioDeviceType(typeName,false); + // JUCE setAudioDeviceSetup() can return success without reopening when + // setup == currentSetup and currentAudioDevice != nullptr, even when + // that driver object has stopped. closeAudioDevice() deletes it but + // keeps the setup for an explicit, fresh driver instance on APPLY. + // For ASIO this also observes changed ASIO4ALL aggregate WDM pins. + // Only the operator initiates this; never auto-reopen/arm on a timer. + if(recovery.recreateDevice && manager.getCurrentAudioDeviceType()==typeName) { + diagnostics_.record("CUSTOM_AUDIO_RECREATE", + typeName+" | "+(previousWasOpen?"REFRESH_ASIO_PINS":"CLOSED_DEVICE_RECOVERY")); + manager.closeAudioDevice(); + } auto error=manager.getCurrentAudioDeviceType()==typeName ?manager.setAudioDeviceSetup(candidate,true) :juce::String("Selected audio backend could not be opened"); juce::AudioDeviceManager::AudioDeviceSetup actual; manager.getAudioDeviceSetup(actual); auto* opened=manager.getCurrentAudioDevice(); + const bool changedAsioPinLayout=error.isEmpty()&&recovery.verifyAsioPinIdentity&& + opened!=nullptr&&opened->isOpen()&& + (opened->getInputChannelNames()!=originalInputNames|| + opened->getOutputChannelNames()!=originalOutputNames); + if(changedAsioPinLayout) + error="ASIO pin layout changed. Output remains muted; review the NEW capture and playback pins and Apply again"; if(error.isEmpty()&&(opened==nullptr||!opened->isOpen()|| manager.getCurrentAudioDeviceType()!=typeName|| actual.inputDeviceName!=capture||actual.outputDeviceName!=playback|| @@ -1120,20 +1410,39 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr std::abs(opened->getCurrentSampleRate()-actual.sampleRate)>1.0|| opened->getCurrentBufferSizeSamples()!=actual.bufferSize)) error="Driver readback mismatch; device setting was not accepted"; - if(error.isEmpty()&&!engine_.finishManualAudioSetup()) + if(error.isEmpty()&&!finishAudioSetupAndRecoverMixer()) { + if(engine_.directRouteAuthorized() && + (engine_.hasRetainedUnboundMixer() || mixerSessionRecoveryPending_)) { + const juce::String needsRemap="Device opened. Mixer retained and muted; its port mapping or FX processing format needs review"; + diagnostics_.record("CUSTOM_AUDIO_NEEDS_REMAP",needsRemap); + send(false,"NEEDS_REMAP",needsRemap,engine_.stageRetainedWasapiPortMapping()); + emitApprovedNativeSnapshot(); + return; + } error="Device opened but direct safe production session was rejected"; + } if(error.isEmpty()) { deviceSettingsDirty_=true; directRestore_.cancel(); diagnostics_.record("CUSTOM_AUDIO_APPLY_OK", typeName+" | "+juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); - return send(true,"ACCEPTED_MUTED",{}); + send(true,"ACCEPTED_MUTED",{}); + emitApprovedNativeSnapshot(); + return; + } + // A changed ASIO layout cannot be 'restored' by replaying indices + // that now refer to different WDM pins. Keep the fresh device MUTED, + // unauthorised, and show its new pin names for deliberate remapping. + if(changedAsioPinLayout) { + diagnostics_.record("CUSTOM_AUDIO_ASIO_TOPOLOGY_CHANGED",error); + return send(false,"RECOVERY_REQUIRED",error); } // One rollback, never blind default endpoint fallback, no auto-unmute. + // A previously CLOSED device was never a verified rollback target. engine_.beginManualAudioSetup(); - if(manager.getCurrentAudioDeviceType()!=previousType&&previousType.isNotEmpty()) + if(recovery.priorKnownOpen&&manager.getCurrentAudioDeviceType()!=previousType&&previousType.isNotEmpty()) manager.setCurrentAudioDeviceType(previousType,false); - const auto restored=previousType.isNotEmpty()&& + const auto restored=recovery.priorKnownOpen&&previousType.isNotEmpty()&& manager.getCurrentAudioDeviceType()==previousType&& manager.setAudioDeviceSetup(before,true).isEmpty(); juce::AudioDeviceManager::AudioDeviceSetup checked; @@ -1143,18 +1452,27 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr checked.outputDeviceName==before.outputDeviceName&& checked.inputChannels==before.inputChannels&& checked.outputChannels==before.outputChannels&& + checked.sampleRate==before.sampleRate&& + checked.bufferSize==before.bufferSize&& manager.getCurrentAudioDevice()!=nullptr&& - manager.getCurrentAudioDevice()->isOpen()&&engine_.finishManualAudioSetup(); + manager.getCurrentAudioDevice()->isOpen()&& + (previousType!="ASIO"|| + (manager.getCurrentAudioDevice()->getInputChannelNames()==originalInputNames&& + manager.getCurrentAudioDevice()->getOutputChannelNames()==originalOutputNames))&& + engine_.finishManualAudioSetup(); diagnostics_.record("CUSTOM_AUDIO_APPLY_FAIL",error+" | rollback="+ (verified?"RESTORED":"RECOVERY_REQUIRED")+" | "+ juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); send(false,verified?"RESTORED_MUTED":"RECOVERY_REQUIRED",error); + emitApprovedNativeSnapshot(); } void showDeviceSetup() { diagnostics_.record ("SETUP", "Open audio device setup"); if (setupLaunching_) return; + // Suspend physical output but retain ALL authored mixer state while + // the real JUCE device selector is visible (including no-change close). engine_.beginManualAudioSetup(); // The native JUCE device list is cached after first construction: @@ -1176,7 +1494,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr [safe] { if (safe == nullptr) return; - if (safe->engine_.finishManualAudioSetup()) + if (safe->finishAudioSetupAndRecoverMixer()) { safe->deviceSettingsDirty_ = true; safe->startupError_.clear(); @@ -1190,7 +1508,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr { safe->diagnostics_.record ("DIRECT_ROUTE_REJECTED", "No valid full-duplex device; audio remains gated"); - safe->emitNotice ("Choose a working capture and render device. Audio remains muted.", true); + safe->emitNotice ( + safe->engine_.hasRetainedUnboundMixer() + ? "Mixer and plugin state retained. Device binding changed; output stays muted until a verified full-session rebind." + : "Choose a working capture and render device. Audio remains muted.", true); + safe->emitApprovedNativeSnapshot(); } }); safe->audioSetupWindow_->setVisible (true); @@ -1330,6 +1652,24 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr result << "Logical cores: " << juce::SystemStats::getNumCpus() << " | RAM: " << juce::SystemStats::getMemorySizeInMegabytes() << " MiB\n"; result << "Telemetry: true hardware render underruns UNAVAILABLE; callback time/gap are proxies only.\n"; + const auto memory=readMemoryPressure(); + result << "=== WINDOWS MEMORY PRESSURE (MESSAGE THREAD ONLY) ===\n"; + if(memory.systemAvailable) + result << "System RAM load: " << memory.systemLoadPercent + << "% | Physically available: " + << static_cast(memory.availablePhysicalMiB) + << " MiB\n"; + else result << "System RAM pressure: UNAVAILABLE\n"; + if(memory.processAvailable) + result << "ArSonMix resident working set: " + << static_cast(memory.processWorkingSetMiB) + << " MiB | Private commit: " + << static_cast(memory.processPrivateCommitMiB) + << " MiB | All process page faults (SOFT+HARD): " + << static_cast(memory.processPageFaults) << "\n"; + else result << "ArSonMix process counters: UNAVAILABLE\n"; + result << "70% is NOT an OS or ASIO glitch threshold. These are correlation" + " indicators, not disk hard-fault evidence or a fix for lost audio.\n"; result << "CALLBACK CADENCE: START-to-START estimates use PREVIOUS callback frame count; " "normal variable block sizes are not driver xruns. 1.5x/2.3x flags " "are scheduling heuristics only, not WASAPI/ASIO underrun evidence.\n"; @@ -1410,6 +1750,325 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return result; } + // One message-thread owner for native EQ commands/readback. The only + // parameter writer is the existing JUCE callback via ChannelEqProcessor's + // bounded SPSC mailbox. ACK is emitted only AFTER audio consumed the edit. + void emitNativeEqSnapshot(const juce::String& request, + const juce::String& channelId,const juce::String& epoch, + const juce::String& revision,int slot,const juce::String& instanceId, + armix::builtin_fx::ChannelEqProcessor* processor) { + auto reply=std::make_unique(); + reply->setProperty("requestId",request); + reply->setProperty("channelId",channelId); + reply->setProperty("deviceEpoch",epoch); + reply->setProperty("graphRevision",revision); + reply->setProperty("slot",slot); + reply->setProperty("instanceId",instanceId); + reply->setProperty("schemaVersion",1); + reply->setProperty("status",processor?"ACCEPTED":"REJECTED"); + if(processor) { + reply->setProperty("sampleRate",processor->acceptedSampleRate()); + juce::Array bands; + for(const auto& band:processor->acceptedBands()){ + auto item=std::make_unique(); + item->setProperty("enabled",band.enabled); + item->setProperty("frequencyHz",static_cast(band.frequencyHz)); + item->setProperty("gainDb",static_cast(band.gainDb)); + item->setProperty("q",static_cast(band.q)); + item->setProperty("slope",static_cast(band.slope)); + bands.add(juce::var(item.release())); + } + reply->setProperty("bands",juce::var(bands)); + if(instanceId==lastNativeEqInstance_ && + epoch==lastNativeEqEpoch_ && revision==lastNativeEqRevision_) + reply->setProperty("appliedRequestId",lastNativeEqRequest_); + } else reply->setProperty("error","NATIVE_EQ_INSTANCE_OR_REVISION_UNAVAILABLE"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixBuiltinEqSnapshot",juce::var(reply.release())); + } + + void servicePendingNativeEq() { + if(!pendingNativeEq_.owner)return; + auto* processor=dynamic_cast( + pendingNativeEq_.owner->processor.get()); + if(!processor){pendingNativeEq_={};return;} + armix::builtin_fx::ChannelEqProcessor::Completion completion; + if(!processor->pollCompletion(completion)){ + if(juce::Time::getMillisecondCounter()-pendingNativeEq_.started<3000u) + return; + } + const auto request=pendingNativeEq_.request; + bool applied=completion.applied && completion.requestId && + request=="eq-"+juce::String(std::to_string(completion.requestId)); + // Reject stale graph/device ACKs even if DSP consumed the old command. + const auto snap=approvedNativeSnapshot(); + const auto device=snap.getProperty("device",{}); + const auto graph=snap.getProperty("graph",{}); + applied=applied && pendingNativeEq_.deviceEpoch== + device.getProperty("epoch","").toString() && + pendingNativeEq_.revision== + graph.getProperty("revision","").toString(); + if(applied){ + lastNativeEqRequest_=request; + lastNativeEqInstance_=pendingNativeEq_.instanceId; + lastNativeEqEpoch_=pendingNativeEq_.deviceEpoch; + lastNativeEqRevision_=pendingNativeEq_.revision; + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("channelId",pendingNativeEq_.channelId); + ack->setProperty("deviceEpoch",pendingNativeEq_.deviceEpoch); + ack->setProperty("graphRevision",pendingNativeEq_.revision); + ack->setProperty("instanceId",pendingNativeEq_.instanceId); + ack->setProperty("status",applied?"APPLIED":"REJECTED"); + ack->setProperty("errorCode",applied?"NONE":"DSP_EDIT_NOT_APPLIED_OR_STALE"); + pendingNativeEq_={}; + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixBuiltinEqAck",juce::var(ack.release())); + } + + + // Never confuse durable logical ChannelId state with a physical device + // authorization. This message-thread report is status only, not PCM. + void emitMixerSessionAck(const juce::String& operation, + const juce::String& error={}) { + auto ack=std::make_unique(); + ack->setProperty("operation",operation); + ack->setProperty("ok",error.isEmpty()); + ack->setProperty("error",error); + ack->setProperty("state",mixerSessionStatus_); + ack->setProperty("saved",mixerSessionId_.isNotEmpty()); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible("arMixNativeSessionAck", + juce::var(ack.release())); + } + + juce::String resolveMixerSessionCatalog(armix::session::MixerSessionDocument& doc, + bool captureIdentity) { + for(auto& insert:doc.inserts) { + if(insert.catalogId==armix::builtin_fx::ChannelEqProcessor::catalogIdentity) { + if(insert.path.isNotEmpty() || insert.uid!=0) + return "Saved built-in EQ identity was modified"; + continue; + } + const auto* registered=catalog_.find(insert.catalogId); + if(!registered || registered->key()!=insert.catalogId || + (!captureIdentity && (registered->uid!=insert.uid || registered->path!=insert.path))) + return "Saved external VST3 identity unavailable: "+insert.catalogId; + if(captureIdentity) { + insert.path=registered->path; + insert.uid=registered->uid; + insert.name=registered->name; + } + } + return {}; + } + + juce::String readMixerSessionForRecovery(armix::session::MixerSessionDocument& doc, + std::vector& blobs) { + if(engine_.hasRetainedNativeSession()) { + const auto error=engine_.captureNativeMixerSession(doc,blobs,true); + if(error.isNotEmpty())return error; + doc.id=mixerSessionId_; + return resolveMixerSessionCatalog(doc,true); + } + return armix::session::NativeMixerSessionStore(settingsDirectory()).load(doc,blobs); + } + + juce::String restoreSavedMixerSession(bool startupOnSavedDevice=false) { + if(!engine_.allOutputsDisarmed() || mixerSessionWorker_.busy() || + nativeShowBusy_ || studioBackupBusy_ || engine_.isGraphSwitchPending()) + return "MUTE output and finish Studio IO before restoring mixer"; + armix::session::NativeMixerSessionStore store(settingsDirectory()); + if(!engine_.hasRetainedNativeSession() && !store.exists()) { + mixerSessionStatus_="NO_SAVED_SESSION"; + return "No saved dynamic mixer session"; + } + armix::session::MixerSessionDocument doc; + std::vector states; + const bool retained=engine_.hasRetainedNativeSession(); + auto error=readMixerSessionForRecovery(doc,states); + bool usedPrevious=false; + if(error.isNotEmpty()&&!retained&&store.recoverPrevious().isEmpty()) { + error=store.load(doc,states); + usedPrevious=error.isEmpty(); + } + if(error.isNotEmpty()) { + mixerSessionStatus_=retained?"RETAINED_SESSION_UNAVAILABLE":"DAMAGED_SESSION"; + mixerSessionError_=error; + diagnostics_.record("DYNAMIC_MIXER_READ_REJECTED",error); + return error; + } + mixerSessionId_=doc.id; + // A disk SHA is NOT permission to instantiate executable code. + // Every external VST3 must still match today's verified catalog + // identity, exact UID and registered path. A moved or tampered + // binary needs an explicit catalog remap, never a blind load. + error=resolveMixerSessionCatalog(doc,false); + if(error.isNotEmpty()) { + mixerSessionStatus_="NEEDS_VST3_REMAP"; + mixerSessionError_=error; + diagnostics_.record("DYNAMIC_MIXER_VST3_REMAP_REQUIRED",error); + return error; + } + const bool resume=startupOnSavedDevice && !usedPrevious && !retained && + doc.resumeMain.value_or(true); + const auto live=engine_.status().getProperty("dryRoutingLab",{}); + if(static_cast(live.getProperty("nativeChannelIdPcmActive",false))) { + mixerSessionStatus_="LIVE_MIXER_UNCHANGED"; + return "Live native mixer already active; refusing to replace it"; + } + error=engine_.restoreNativeMixerSession(std::move(doc),states); + if(error.isNotEmpty()) { + mixerSessionStatus_=error.contains("NEEDS_REMAP") + ?"NEEDS_REMAP":"RESTORE_REJECTED"; + mixerSessionError_=error; + diagnostics_.record("DYNAMIC_MIXER_RESTORE_REJECTED",error); + return error; + } + mixerSessionRecoveryPending_=false; + if(resume && engine_.liveOutputArmFault(false).isEmpty()) + engine_.setMonitorEnabled(true); + mixerSessionStatus_=engine_.isMonitorEnabled()?"RESTORED_MONITORING":"RESTORED_MUTED"; + mixerSessionError_.clear(); + diagnostics_.record("DYNAMIC_MIXER_RESTORED",mixerSessionStatus_); + if(usedPrevious)emitNotice("Last verified mixer checkpoint restored with MAIN muted.",true); + emitApprovedNativeSnapshot(); + return {}; + } + + juce::String saveMixerSession(bool resumeMain, const juce::File& exportFile={}) { + const bool automatic=exportFile==juce::File{}; + if(automatic&&mixerSessionRecoveryPending_) + return "The retained mixer checkpoint is awaiting a verified device"; + if(mixerSessionWorker_.busy()||nativeShowBusy_||studioBackupBusy_|| + catalog_.busy()||engine_.isGraphSwitchPending()) + return "Mixer is busy. Try again after the current operation."; + const bool monitoring=engine_.isMonitorEnabled(); + if(engine_.secondaryArmed())return "Stop STREAM before saving the mixer"; + const auto epoch=engine_.dryRoutingLabEpoch(); + if(monitoring)engine_.setMonitorEnabled(false); + armix::session::MixerSessionDocument doc; + std::vector states; + auto error=engine_.captureNativeMixerSession(doc,states); + if(monitoring && epoch==engine_.dryRoutingLabEpoch() && + engine_.liveOutputArmFault(false).isEmpty()) + engine_.setMonitorEnabled(true); + if(error.isNotEmpty())return error; + if(automatic)doc.resumeMain=resumeMain; + doc.id=mixerSessionId_.isNotEmpty()?mixerSessionId_: + juce::Uuid().toDashedString().toLowerCase(); + // Use the verified installed vendor identity; never load using a + // browser-provided plugin name or relocate an arbitrary VST3 path. + error=resolveMixerSessionCatalog(doc,true); + if(error.isNotEmpty())return error; + doc.savedMs=1; // signature excludes wall time; includes FX state hashes + const auto canonical=armix::session::Codec::encode(doc); + armix::session::MixerSessionDocument verified; + if(!armix::session::Codec::decode(canonical,verified)) + return "Mixer session document validation rejected"; + const auto fingerprint=juce::SHA256(canonical.toRawUTF8(), + canonical.getNumBytesAsUTF8()).toHexString(); + if(automatic&&fingerprint==lastMixerSessionFingerprint_) + return {}; + doc.savedMs=juce::Time::currentTimeMillis(); + const auto pendingId=doc.id; + auto safe=juce::Component::SafePointer(this); + if(!mixerSessionWorker_.save(settingsDirectory(),std::move(doc), + std::move(states), + [safe,pendingId,fingerprint,automatic](juce::String failure){ + if(safe==nullptr)return; + if(!automatic) { + safe->emitMixerSessionAck("SAVE",failure); + return; + } + if(failure.isEmpty()) { + safe->mixerSessionId_=pendingId; + safe->lastMixerSessionFingerprint_=fingerprint; + safe->mixerSessionStatus_="SAVED_VERIFIED_MUTED"; + safe->mixerSessionError_.clear(); + safe->diagnostics_.record("DYNAMIC_MIXER_SAVED", + "AUTO_CHECKPOINT"); + }else{ + safe->mixerSessionStatus_="SAVE_REJECTED"; + safe->mixerSessionError_=failure; + safe->diagnostics_.record("DYNAMIC_MIXER_SAVE_REJECTED",failure); + } + },exportFile))return "Mixer session IO worker unavailable"; + if(automatic)mixerSessionStatus_="SAVING"; + return {}; + } + + void openMixerFile(const juce::File& file) { + const auto chosenEpoch=engine_.dryRoutingLabEpoch(); + auto safe=juce::Component::SafePointer(this); + if(!mixerSessionWorker_.load(file,[safe,chosenEpoch,file](juce::String error, + armix::session::MixerSessionDocument doc, + std::vector states) { + if(safe==nullptr)return; + auto& engine=safe->engine_; + if(error.isEmpty() && (safe->nativeShowBusy_||safe->studioBackupBusy_|| + safe->catalog_.busy()||engine.isGraphSwitchPending()|| + chosenEpoch!=engine.dryRoutingLabEpoch())) + error="Mixer or audio device changed while opening the file"; + if(error.isEmpty()&&engine.secondaryArmed()) + error="Stop STREAM before opening a mixer"; + if(error.isEmpty())error=safe->resolveMixerSessionCatalog(doc,false); + if(error.isEmpty()) { + const auto id=doc.id; + bool sameOutputs=false; + const bool monitoring=engine.isMonitorEnabled(); + error=engine.restoreNativeMixerSession(std::move(doc),states,true,&sameOutputs); + if(monitoring&&sameOutputs&&error.isEmpty()&& + chosenEpoch==engine.dryRoutingLabEpoch()&&engine.liveOutputArmFault(false).isEmpty()) + engine.setMonitorEnabled(true); + if(error.isEmpty()) { + safe->closePluginEditor(); + safe->stopOrbit(); + safe->mixerSessionId_=id; + safe->mixerSessionRecoveryPending_=false; + safe->lastMixerSessionFingerprint_.clear(); + safe->mixerSessionStatus_=engine.isMonitorEnabled()?"RESTORED_MONITORING":"RESTORED_MUTED"; + safe->mixerSessionError_.clear(); + safe->lastMixerFile_=file; + safe->emitApprovedNativeSnapshot(); + } + } + safe->emitMixerSessionAck("OPEN",error); + }))emitMixerSessionAck("OPEN","Mixer file operation already in progress"); + } + + void chooseMixerFile(bool save) { + if(mixerFileDialogOpen_)return; + const auto operation=save?"SAVE":"OPEN"; + if(mixerSessionWorker_.busy()||nativeShowBusy_||studioBackupBusy_) + return emitMixerSessionAck(operation,"Mixer file operation already in progress"); + auto start=lastMixerFile_; + if(start==juce::File{}) { + start=juce::File::getSpecialLocation(juce::File::userDocumentsDirectory); + if(save)start=start.getChildFile("Mixer.smix"); + } + mixerFileDialogOpen_=true; + mixerFileChooser_=std::make_unique( + save?"Save mixer":"Open mixer",start,"*.smix",true); + using BrowserFlags=juce::FileBrowserComponent; + mixerFileChooser_->launchAsync(BrowserFlags::canSelectFiles | + (save?(BrowserFlags::saveMode|BrowserFlags::warnAboutOverwriting):BrowserFlags::openMode), + [safe=juce::Component::SafePointer(this),save,operation] + (const juce::FileChooser& picker) { + if(safe==nullptr)return; + safe->mixerFileDialogOpen_=false; + auto file=picker.getResult(); + if(file==juce::File{})return; + if(!save)return safe->openMixerFile(file); + if(!file.hasFileExtension(".smix")) + return safe->emitMixerSessionAck(operation,"Use the .smix file extension"); + safe->lastMixerFile_=file; + const auto error=safe->saveMixerSession(false,file); + if(error.isNotEmpty())safe->emitMixerSessionAck(operation,error); + }); + } + void onAction (const juce::var& args) { const auto action = args.getProperty ("action", {}).toString(); @@ -1421,7 +2080,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr action.startsWith ("import") || action.startsWith ("fx") || action == "addCatalog" || action == "addScanFolder" || action == "scanVst3" || action == "routingDryApply" || - action == "routingFxBypass")) + action == "routingFxBypass" || + action == "routingNativeFxRackBypass" || + action == "routingNativeFxInsertBypass" || + action == "routingFxRackBypass" || + action == "nativeEqSetBand")) { const auto reason=juce::String( "Studio backup in progress. Finish backup before editing saved FX or VST library."); @@ -1439,6 +2102,24 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr action=="routingDryApply"?"arMixRoutingLabAck":"arMixRoutingFxBypassAck", juce::var(ack.release())); } + if(action=="routingFxRackBypass" && browser_.loaded){ + auto ack=std::make_unique(); + ack->setProperty("requestId",args.getProperty("requestId",{})); + ack->setProperty("channel",args.getProperty("channel",-1)); + ack->setProperty("ok",false); + ack->setProperty("error",reason); + browser_.emitEventIfBrowserIsVisible( + "arMixRoutingFxRackAck",juce::var(ack.release())); + } + if((action=="routingNativeFxRackBypass" || + action=="routingNativeFxInsertBypass") && browser_.loaded) { + auto ack=std::make_unique(); + ack->setProperty("requestId",args.getProperty("requestId",{})); + ack->setProperty("ok",false); + ack->setProperty("error",reason); + browser_.emitEventIfBrowserIsVisible( + "arMixNativeFxPowerAck",juce::var(ack.release())); + } return emitNotice(reason,true); } @@ -1463,6 +2144,280 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // M1 RT source switch on an existing physical channel. Unlike // structural routingDryApply, it does not unpatch outputs, rebuild // VST3s, or restart the device; input PCM fades inside one graph. + // F0: independently acknowledged existing M4 PCM controls during + // G0, before ChannelId admission. Do not send GUI demo parameters + // or mutate a second DSP. One control-thread atomic update only. + + // Real built-in rack node, not a GUI-only pre-VST channel EQ. + // All identity fields are validated by the accepted native lease. + if(action=="nativeEqSnapshot"||action=="nativeEqSetBand") { + const auto rawChannel=args.getProperty("channelId",{}); + const auto rawEpoch=args.getProperty("deviceEpoch",{}); + const auto rawRevision=args.getProperty("graphRevision",{}); + const auto rawInstance=args.getProperty("instanceId",{}); + const auto request=args.getProperty("requestId",{}).toString(); + const int eqSlot=static_cast(args.getProperty("slot",-1)); + std::uint64_t ch=0,ep=0,rev=0; + const bool valid=armix::console::approvedNativeId(rawChannel,ch)&& + armix::console::approvedNativeId(rawEpoch,ep)&& + armix::console::approvedNativeId(rawRevision,rev)&& + rawInstance.isString()&&rawInstance.toString().isNotEmpty()&& + eqSlot>=0&&eqSlot(eqSlot), + rawInstance.toString()): + armix::mixer::LiveChannelFxGraph::InstanceLease{}; + auto* processor=owner?dynamic_cast( + owner->processor.get()):nullptr; + if(action=="nativeEqSnapshot") { + emitNativeEqSnapshot(request,rawChannel.toString(), + rawEpoch.toString(),rawRevision.toString(), + eqSlot,rawInstance.toString(),processor); + return; + } + const auto bandData=args.getProperty("band",{}); + const int index=static_cast(args.getProperty("bandIndex",-1)); + const auto enabled=bandData.getProperty("enabled",{}); + const auto frequency=bandData.getProperty("frequencyHz",{}); + const auto gain=bandData.getProperty("gainDb",{}); + const auto q=bandData.getProperty("q",{}); + const auto slope=bandData.getProperty("slope",{}); + double f=0.,g=0.,quality=0.; + auto validNumber=[](const juce::var& v,double& d) { + if(!v.isDouble()&&!v.isInt())return false; + d=static_cast(v);return std::isfinite(d); + }; + bool queued=false; + if(processor&&!pendingNativeEq_.owner&&!nativeShowBusy_&&!studioBackupBusy_ && + !engine_.independentClockActive() && index>=0&&index<8 && + enabled.isBool()&&slope.isInt() && + (static_cast(slope)==12||static_cast(slope)==24) && + validNumber(frequency,f)&&validNumber(gain,g)&& + validNumber(q,quality) && request.startsWith("eq-")) { + armix::builtin_fx::Band b; + b.enabled=static_cast(enabled); + b.frequencyHz=static_cast(f); + b.gainDb=static_cast(g); + b.q=static_cast(quality); + b.slope=static_cast(slope)==24? + armix::builtin_fx::Slope::db24:armix::builtin_fx::Slope::db12; + // Id strings are decimal after "eq-", unlike canonical + // ChannelIds; never convert 64-bit ChannelId to JS Number. + const auto wire=request.substring(3).toStdString(); + std::uint64_t numeric=0; + if(!wire.empty()&&wire.size()<=19&& + wire.find_first_not_of("0123456789")==std::string::npos) { + try{numeric=std::stoull(wire);}catch(...){numeric=0;} + } + queued=numeric>0&&processor->queueBand( + static_cast(index),b,numeric); + if(queued) { + pendingNativeEq_.owner=owner; + pendingNativeEq_.request=request; + pendingNativeEq_.channelId=rawChannel.toString(); + pendingNativeEq_.deviceEpoch=rawEpoch.toString(); + pendingNativeEq_.revision=rawRevision.toString(); + pendingNativeEq_.instanceId=rawInstance.toString(); + pendingNativeEq_.slot=eqSlot; + pendingNativeEq_.started=juce::Time::getMillisecondCounter(); + } + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("channelId",rawChannel); + ack->setProperty("instanceId",rawInstance); + ack->setProperty("status",queued?"QUEUED":"REJECTED"); + ack->setProperty("errorCode",queued?"NONE": + pendingNativeEq_.owner?"EQ_CONTROL_BUSY":"INVALID_OR_STALE_NATIVE_EQ"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixBuiltinEqQueue",juce::var(ack.release())); + return; + } + + // Route the approved channel FX picker to the SAME prepared M4 + // graph as physical IN/OUT. ID resolves exclusively in the JUCE + // catalog; browser paths/names are never trusted as plugin identity. + if(action=="routingFxInsert"){ + const auto requestId=args.getProperty("requestId",{}).toString(); + const int lane=static_cast(args.getProperty("channel",-1)); + const int position=static_cast(args.getProperty("slot",-1)); + const auto id=args.getProperty("id",{}).toString(); + const auto ep=args.getProperty("deviceEpoch",{}); + const auto rv=args.getProperty("revision",{}); + const auto status=engine_.status().getProperty("dryRoutingLab",{}); + const auto actualEp=status.getProperty("epoch",{}); + const auto actualRev=status.getProperty("revision",{}); + const auto* plugin=catalog_.find(id); + juce::String error="FX INSERT: invalid/stale device, channel, slot or catalog"; + const bool tokens= + armix::console::nativeSessionTokenMatches(ep,actualEp) && + armix::console::nativeSessionTokenMatches(rv,actualRev); + if(requestId.startsWith("fx-")&&requestId.length()<=48 && + tokens && lane>=0&&lane=0&&position(status.getProperty("hasAcceptedRoute",false))) { + const LiveDryRoutingLab::FxSelection selection{ + plugin->key(),plugin->path,plugin->name,plugin->uid}; + error=engine_.insertDryRoutingLabFx(lane,position, + static_cast(static_cast(ep)), + static_cast(static_cast(rv)), + selection); + } + auto reply=std::make_unique(); + reply->setProperty("requestId",requestId); + reply->setProperty("ok",error.isEmpty()); + reply->setProperty("error",error); + reply->setProperty("channel",lane); + reply->setProperty("slot",position); + reply->setProperty("state",engine_.status().getProperty("dryRoutingLab",{})); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixRoutingFxInsertAck",juce::var(reply.release())); + if(error.isNotEmpty())emitNotice(error,true); + else diagnostics_.record("NATIVE_ROUTED_FX_INSERT", + "CH "+juce::String(lane+1)+" slot "+juce::String(position+1)); + return; + } + // M4 is internal PCM compatibility, not an independent GUI state. + // One native rack gate overrides FX wet/dry, preserving slot bypasses. + if(action=="routingFxRackBypass"){ + const auto requestId=args.getProperty("requestId",{}).toString(); + const int lane=static_cast(args.getProperty("channel",-1)); + const auto ep=args.getProperty("deviceEpoch",juce::var()); + const auto rv=args.getProperty("revision",juce::var()); + const auto route=engine_.status().getProperty("dryRoutingLab",{}); + const auto currentEp=route.getProperty("epoch",juce::var()); + const auto currentRv=route.getProperty("revision",juce::var()); + const bool tokens= + armix::console::nativeSessionTokenMatches(ep,currentEp) && + armix::console::nativeSessionTokenMatches(rv,currentRv); + const bool replay=acceptedControlRequests_.contains(requestId); + const bool valid=tokens&&value.isBool()&& + requestId.startsWith("rack-m4-")&&requestId.length()<=48 && + lane>=0&&lane(route.getProperty("hasAcceptedRoute",false)) && + !static_cast(route.getProperty("nativeChannelIdPcmActive",false)) && + !static_cast(route.getProperty("nativeBusStructural",false)) && + !static_cast(route.getProperty("topologyFault",true)) && + engine_.directRouteAuthorized()&&!engine_.independentClockActive(); + if(!replay && requestId.startsWith("rack-m4-") && requestId.length()<=48){ + acceptedControlRequests_.add(requestId); + if(acceptedControlRequests_.size()>512)acceptedControlRequests_.remove(0); + } + const bool applied=valid&&engine_.setDryRoutingLabFxRackBypass( + lane,static_cast(static_cast(ep)), + static_cast(static_cast(rv)), + static_cast(value)); + auto ack=std::make_unique(); + ack->setProperty("requestId",requestId); + ack->setProperty("ok",applied); + ack->setProperty("deviceEpoch",currentEp); + ack->setProperty("routingRevision",currentRv); + ack->setProperty("channel",lane); + ack->setProperty("bypassed",value); + ack->setProperty("error",applied?juce::String(): + "Native rack bypass rejected: stale epoch, revision or PCM authority"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixRoutingFxRackAck",juce::var(ack.release())); + return; + } + if(action=="routingM4Control"){ + const auto requestId=args.getProperty("requestId",juce::var()).toString(); + const int channel=static_cast(args.getProperty("channel",-1)); + const auto name=args.getProperty("parameter",juce::var()).toString(); + const auto val=args.getProperty("controlValue",juce::var()); + const auto ep=args.getProperty("deviceEpoch",juce::var()); + const auto rv=args.getProperty("revision",juce::var()); + const auto state=engine_.status(); + const auto route=state.getProperty("dryRoutingLab",{}); + const auto currentEp=route.getProperty("epoch",juce::var()); + const auto currentRv=route.getProperty("revision",juce::var()); + const bool tokenOk= + armix::console::nativeSessionTokenMatches(ep,currentEp) && + armix::console::nativeSessionTokenMatches(rv,currentRv); + const bool ready=tokenOk && requestId.startsWith("m4-") && + requestId.length()<=48 && + !nativeShowBusy_ && !studioBackupBusy_ && + static_cast(route.getProperty("hasAcceptedRoute",false)) && + // Native ChannelId may own CH1..10 while the physical host + // still owns post-mixer MAIN gain/mute. Admit only MAIN in that case. + (channel==-1 || + !static_cast(route.getProperty("nativeBusStructural",false))) && + !static_cast(route.getProperty("topologyFault",true)) && + engine_.directRouteAuthorized() && !engine_.independentClockActive(); + const bool boolean=(name=="mute"||name=="solo"||name=="masterMute"); + const double numeric=boolean?0.:static_cast(val); + const bool typeOk=boolean?val.isBool():(val.isDouble()||val.isInt()); + const bool master=(channel==-1 && + (name=="masterGain"||name=="masterMute")); + const bool lane=(channel>=0 && channel=-100.&&numeric<=100.): + (numeric>=-60.&&numeric<=10.)); + bool applied=ready && typeOk && (master||lane) && + (boolean||std::isfinite(numeric)) && range; + if(applied && lane) + applied=engine_.setDryRoutingLabParameter(channel, + static_cast(static_cast(ep)), + static_cast(static_cast(rv)), + name,val.isBool()?(bool(val)?1.f:0.f): + static_cast(numeric)); + else if(applied && name=="masterGain") + engine_.setMasterGainDb(static_cast(numeric)); + else if(applied && name=="masterMute") + engine_.setMasterMuted(bool(val)); + auto ack=std::make_unique(); + ack->setProperty("requestId",requestId); + ack->setProperty("ok",applied); + ack->setProperty("deviceEpoch",currentEp); + ack->setProperty("routingRevision",currentRv); + ack->setProperty("channel",channel); + ack->setProperty("parameter",name); + ack->setProperty("error",applied?juce::String(): + juce::String("Stale G0 route, invalid parameter or PCM authority changed")); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible("arMixM4ControlAck", + juce::var(ack.release())); + // ACK is not PCM proof; the bridge requires a LATER snapshot. + return; + } + // A visible /preview/ channel OUT changes this same installed M4 + // topology. Only actual MAIN / NONE semantics are supported here. + if(action=="routingChannelPatch"){ + const int requestId=static_cast(args.getProperty("requestId",0)); + const int channel=static_cast(args.getProperty("channel",-1)); + const auto target=args.getProperty("target",juce::var()).toString(); + const auto operation=args.getProperty("operation","SET_PRIMARY_OUT").toString(); + const auto ep=args.getProperty("deviceEpoch",juce::var()); + const auto rv=args.getProperty("revision",juce::var()); + juce::String error="CHANNEL PATCH: stale identity, unsupported format/output or busy Show"; + const bool allowed=(operation=="SET_PRIMARY_OUT" && + (target=="MAIN"||target=="NONE")) || + (operation=="SET_PROCESSING_FORMAT" && + (target=="MONO"||target=="STEREO")); + if(requestId>0 && channel>=0 && channel(static_cast(ep)), + static_cast(static_cast(rv)), + operation,target); + auto ack=std::make_unique(); + ack->setProperty("requestId",requestId); + ack->setProperty("channel",channel); + ack->setProperty("ok",error.isEmpty()); + ack->setProperty("error",error); + ack->setProperty("state",engine_.status().getProperty("dryRoutingLab",{})); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixChannelPatchAck",juce::var(ack.release())); + if(error.isNotEmpty())emitNotice(error,true); + return; + } if(action=="routingSourceSwitch"){ const int requestId=static_cast(args.getProperty("requestId",0)); const int channel=static_cast(args.getProperty("channel",-1)); @@ -1471,13 +2426,24 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto rv=args.getProperty("revision",juce::var()); const int left=static_cast(args.getProperty("left",-1)); const int right=static_cast(args.getProperty("right",-1)); - const juce::String error=requestId>0&&!ep.isVoid()&&!rv.isVoid()&& + // SOURCE uses the SAME exact native session authority as FX, + // OUT and M4. A JUCE JSON double may be an exact integer, but + // fractional/NaN/rounded or stale tokens must never be cast to + // a valid active epoch/revision before changing physical PCM. + const auto nativeRoute=engine_.status().getProperty("dryRoutingLab",{}); + const bool tokens= + armix::console::nativeSessionTokenMatches( + ep,nativeRoute.getProperty("epoch",{})) && + armix::console::nativeSessionTokenMatches( + rv,nativeRoute.getProperty("revision",{})); + const juce::String error=requestId>0 && + channel>=0&&channel(static_cast(ep)), - static_cast(static_cast(rv)), + armix::console::nativeSessionTokenValue(ep), + armix::console::nativeSessionTokenValue(rv), mode,left,right): - juce::String("SOURCE SWITCH: stale request or Show/backup busy"); + juce::String("SOURCE SWITCH: stale native epoch/revision, channel or Show/backup busy"); auto ack=std::make_unique(); ack->setProperty("requestId",requestId); ack->setProperty("channel",channel); @@ -1623,6 +2589,186 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(!ok)emitNotice("Live AUX send rejected; refresh accepted routing.",true); return; } + // Accepted ChannelId FX power. A rack master is an additive gate, + // not a rewrite of the eight saved individual bypass preferences. + // Both gestures are fenced to the actual device epoch + PCM revision + // and reply with an ACK; the WebView re-reads the producer snapshot. + if(action=="routingNativeFxRackBypass" || + action=="routingNativeFxInsertBypass") { + const auto request=args.getProperty("requestId",{}).toString(); + const auto rawId=args.getProperty("channelId",{}); + const auto rawEpoch=args.getProperty("deviceEpoch",{}); + const auto rawRevision=args.getProperty("revision",{}); + const auto parse=[](const juce::var& wire,std::uint64_t& out) -> bool { + if(!wire.isString())return false; + const auto text=wire.toString().toStdString(); + if(text.empty()||text.size()>20|| + text[0]=='0'||text.find_first_not_of("0123456789")!=std::string::npos) + return false; + try { + const auto decoded=std::stoull(text); + if(!decoded||std::to_string(decoded)!=text)return false; + out=decoded;return true; + } catch(...) {return false;} + }; + std::uint64_t channel=0,ep=0,rev=0; + const bool valid=request.isNotEmpty()&&request.length()<=128 && + parse(rawId,channel)&&parse(rawEpoch,ep)&& + parse(rawRevision,rev)&&value.isBool() && + !studioBackupBusy_&&!nativeShowBusy_&& + !engine_.independentClockActive(); + bool applied=false; + if(valid && !acceptedControlRequests_.contains(request)) { + acceptedControlRequests_.add(request); + if(acceptedControlRequests_.size()>512) + acceptedControlRequests_.remove(0); + const armix::mixer::ChannelId id{channel}; + if(action=="routingNativeFxRackBypass") + applied=engine_.bypassNativeFxRack(ep,rev,id,static_cast(value)); + else { + const auto token=args.getProperty("insertId",{}).toString(); + applied=slot>=0&&slot(slot),token,static_cast(value)); + } + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("ok",applied); + ack->setProperty("channelId",rawId); + ack->setProperty("bypassed",value); + ack->setProperty("error",applied?juce::String(): + "Native FX power rejected: stale device/revision, Show busy or instance mismatch"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixNativeFxPowerAck",juce::var(ack.release())); + if(applied)diagnostics_.record("NATIVE_FX_POWER", + rawId.toString()+(action=="routingNativeFxRackBypass"?" rack":" insert")+ + (static_cast(value)?" BYPASS":" ENABLE")); + return; + } + + // Real DAW + BUS from the approved Windows GUI. The engine creates + // and publishes a stereo GROUP directly in its sole ChannelId PCM + // owner; no browser-only track or legacy M4 shadow is created. + // Normal GUI physical IN remains available after a native BUS/WIRE + // publication. The ChannelId producer, not stale M4, owns the patch. + if(action=="routingNativeSourcePatch"){ + const auto request=args.getProperty("requestId",{}).toString(); + const auto rawId=args.getProperty("channelId",{}); + const auto rawEp=args.getProperty("deviceEpoch",{}); + const auto rawRev=args.getProperty("graphRevision",{}); + const auto rawRoster=args.getProperty("rosterRevision",{}); + const auto mode=args.getProperty("mode",{}).toString(); + const int left=static_cast(args.getProperty("left",-1)); + const int right=static_cast(args.getProperty("right",-1)); + std::uint64_t id=0,ep=0,rev=0,roster=0; + const auto snap=approvedNativeSnapshot(); + const auto graph=snap.getProperty("graph",{}); + bool input=false; + const auto channels=graph.getProperty("channels",{}); + if(const auto* rows=channels.getArray()) + for(const auto& row:*rows) + if(row.getProperty("id","").toString()==rawId.toString()&& + row.getProperty("role","").toString()=="INPUT") + input=true; + const bool valid=request.startsWith("source-native-")&& + request.length()<=64&&!acceptedControlRequests_.contains(request)&& + armix::console::approvedNativeId(rawId,id)&& + armix::console::approvedNativeId(rawEp,ep)&& + armix::console::approvedNativeId(rawRev,rev)&& + armix::console::approvedNativeId(rawRoster,roster)&& + (mode=="NONE"||mode=="MONO"||mode=="STEREO")&& + (mode!="NONE"||(left==-1&&right==-1))&& + (mode!="MONO"||right==-1)&&input&& + snap.getProperty("device",{}).getProperty("epoch","").toString()==rawEp.toString()&& + graph.getProperty("revision","").toString()==rawRev.toString()&& + graph.getProperty("rosterRevision","").toString()==rawRoster.toString()&& + !nativeShowBusy_&&!studioBackupBusy_; + LiveDryRoutingLab::NativeBusResult result; + result.error="NATIVE_SOURCE_NOT_ADMITTED_OR_STALE"; + if(valid){ + acceptedControlRequests_.add(request); + if(acceptedControlRequests_.size()>512) + acceptedControlRequests_.remove(0); + result=engine_.patchNativeInputSource(ep,rev,roster, + armix::mixer::ChannelId{id},left,right,mode=="STEREO"); + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("channelId",rawId); + ack->setProperty("ok",valid&&result.accepted); + ack->setProperty("error",result.error?result.error:"NATIVE_SOURCE_UNKNOWN"); + ack->setProperty("graphRevision", + juce::String(std::to_string(result.pcmRevision))); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixNativeSourceAck",juce::var(ack.release())); + if(valid&&result.accepted) + diagnostics_.record("DAW_NATIVE_SOURCE", + "ChannelId "+rawId.toString()+" → "+mode); + else emitNotice("Channel IN rejected: "+ + juce::String(result.error?result.error:"native error"),true); + return; + } + if(action=="routingNativeBusCreate") { + const auto request=args.getProperty("requestId",{}).toString(); + const auto rawEp=args.getProperty("deviceEpoch",{}); + const auto rawRev=args.getProperty("graphRevision",{}); + const auto rawRoster=args.getProperty("rosterRevision",{}); + std::uint64_t ep=0,rev=0,roster=0; + const auto live=engine_.status(); + const auto lab=live.getProperty("dryRoutingLab",{}); + const auto native=lab.getProperty("nativeBus",{}); + const auto before=approvedNativeSnapshot(live); + const auto caps=before.getProperty("graph",{}) + .getProperty("capabilities",{}).getProperty("supportedOps",{}); + const bool admitted=caps.isArray()&& + caps.getArray()->contains("CREATE_GROUP"); + const bool valid=request.startsWith("bus-")&& + request.length()<=64 && + !acceptedControlRequests_.contains(request)&& + armix::console::approvedNativeId(rawEp,ep)&& + armix::console::approvedNativeId(rawRev,rev)&& + armix::console::approvedNativeId(rawRoster,roster)&& + ep==engine_.dryRoutingLabEpoch() && + native.getProperty("graphRevision","").toString()==rawRev.toString() && + native.getProperty("rosterRevision","").toString()==rawRoster.toString() && + admitted && !nativeShowBusy_ && !studioBackupBusy_; + LiveDryRoutingLab::NativeBusResult result; + result.error="NATIVE_BUS_NOT_ADMITTED_OR_STALE"; + if(valid) { + acceptedControlRequests_.add(request); + if(acceptedControlRequests_.size()>512) + acceptedControlRequests_.remove(0); + int count=0; + const auto channels=native.getProperty("channels",{}); + if(const auto* rows=channels.getArray()) + for(const auto& row:*rows) + if(row.getProperty("role","").toString()=="GROUP")++count; + const std::string name="Bus "+std::to_string(count+1); + result=engine_.editNativeBus(ep,rev,roster, + armix::mixer::ChannelRole::group, + std::span{},name,1.f); + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("ok",valid&&result.accepted); + ack->setProperty("error",result.error?result.error:"NATIVE_BUS_UNKNOWN"); + ack->setProperty("createdId",result.accepted? + juce::String(std::to_string(result.created.value)):juce::String()); + ack->setProperty("graphRevision", + juce::String(std::to_string(result.pcmRevision))); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible( + "arMixNativeBusAck",juce::var(ack.release())); + if(valid&&result.accepted) + diagnostics_.record("NATIVE_DAW_BUS", + "Created real ChannelId GROUP with MAIN output"); + else emitNotice("Add BUS rejected: "+ + juce::String(result.error?result.error:"native error"),true); + return; + } + // G5C native per-instance BYPASS never recompiles the graph and // does not require muting the output. All identity gates must agree. if (action == "routingFxBypass") { @@ -1636,6 +2782,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr lane,slot,epoch,revision,token,static_cast(value)); auto ack=std::make_unique(); ack->setProperty("ok",ok); + ack->setProperty("requestId",args.getProperty("requestId",juce::var())); + ack->setProperty("channel",lane); + ack->setProperty("slot",slot); ack->setProperty("error",ok?juce::String(): "FX bypass rejected: route revision, instance or device changed"); ack->setProperty("state",engine_.status().getProperty("dryRoutingLab",{})); @@ -1657,14 +2806,26 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr bool opened=false; juce::String error="FX editor unavailable: device, revision or instance changed"; if(!nativeShowBusy_&&!studioBackupBusy_&&!engine_.isGraphSwitchPending()) { - const auto owner=engine_.leaseRoutedFxForEditor( - lane,slot,epoch,revision,token); + armix::mixer::LiveChannelFxGraph::InstanceLease owner; + std::uint64_t retainedEpoch=epoch; + const auto nativeId=args.getProperty("channelId",{}); + if(!nativeId.isVoid()) { + std::uint64_t id=0,ep=0,rev=0; + if(armix::console::approvedNativeId(nativeId,id)&& + armix::console::approvedNativeId(args.getProperty("deviceEpoch",{}),ep)&& + armix::console::approvedNativeId(args.getProperty("revision",{}),rev)&& + slot>=0&&slot(slot),token); + retainedEpoch=ep; + } + } else owner=engine_.leaseRoutedFxForEditor(lane,slot,epoch,revision,token); if(owner && owner->processor) { try { + closePluginEditor(); if(auto* editor=owner->processor->createEditorIfNeeded()) { - closePluginEditor(); routedEditorOwner_=owner; - routedEditorEpoch_=static_cast(epoch); + routedEditorEpoch_=retainedEpoch; editorWindow_=std::make_unique( owner->processor->getName(),editor); opened=true; @@ -1690,8 +2851,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr else emitNotice(error,true); return; } + + if(action=="nativeMixerFileSave"||action=="nativeMixerFileOpen") { + chooseMixerFile(action=="nativeMixerFileSave"); + return; + } if (action == "routingDryShowSave") { + const auto updateShowId=value.isString()?value.toString():juce::String(); const auto reject=[this](const juce::String& reason) { if(browser_.loaded) { auto ack=std::make_unique(); @@ -1702,6 +2869,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } emitNotice("Show not saved: "+reason,true); }; + if(updateShowId.isNotEmpty()&&!armix::shows::detail::uuid(updateShowId)) + return reject("Invalid Show identity for version update."); if (nativeShowBusy_ || studioBackupBusy_ || catalog_.busy() || engine_.isGraphSwitchPending() || engine_.hasTemporaryDiagnosticDevice()) return reject("Finish the current Studio task before capturing a native Show."); @@ -1796,7 +2965,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr safe->browser_.emitEventIfBrowserIsVisible("arMixNativeShowSaveAck", juce::var(ack.release())); } - }); + },updateShowId); if(!started)return reject("Native Show worker is busy. No session was modified."); nativeShowBusy_=true; return emitNotice("Saving ACK-verified routing and binary VST3 state on the Show IO worker."); @@ -1828,6 +2997,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr auto row=std::make_unique(); row->setProperty("id",item.id); row->setProperty("name",item.name); + row->setProperty("needsRecovery",item.needsRecovery); + row->setProperty("hasPrevious",item.hasPrevious); items.add(juce::var(row.release())); } ack->setProperty("items",juce::var(items)); @@ -1841,6 +3012,51 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr nativeShowBusy_=true; return; } + // Explicit recovery repairs only a damaged disk HEAD, never auto- + // recalls/arms audio and never overwrites a verified current Show. + if (action == "routingDryShowRecover") + { + const auto id=value.toString(); + const auto reject=[this](const juce::String& error) { + if(browser_.loaded) { + auto ack=std::make_unique(); + ack->setProperty("ok",false); + ack->setProperty("error",error); + browser_.emitEventIfBrowserIsVisible( + "arMixNativeShowRecoverAck",juce::var(ack.release())); + } + emitNotice("Show recovery unchanged: "+error,true); + }; + if(!armix::shows::detail::uuid(id)) + return reject("Select a valid saved Show identity."); + if(nativeShowBusy_||studioBackupBusy_||catalog_.busy()|| + engine_.isGraphSwitchPending()||!engine_.allOutputsDisarmed()) + return reject("MUTE both outputs and finish all Studio tasks before recovery."); + auto safe=juce::Component::SafePointer(this); + const bool started=nativeShowWorker_.recover(settingsDirectory(),id, + [safe](armix::shows::NativeShowSaveWorker::Result result) { + if(safe==nullptr)return; + safe->nativeShowBusy_=false; + if(result.ok()) + safe->diagnostics_.record("NATIVE_SHOW_LKG_RECOVERED",result.showId); + else safe->diagnostics_.record("NATIVE_SHOW_LKG_REJECTED",result.error); + if(safe->browser_.loaded) { + auto ack=std::make_unique(); + ack->setProperty("ok",result.ok()); + ack->setProperty("error",result.error); + ack->setProperty("showId",result.showId); + safe->browser_.emitEventIfBrowserIsVisible( + "arMixNativeShowRecoverAck",juce::var(ack.release())); + } + if(result.ok()) + safe->emitNotice("Last verified Show restored on disk. OUTPUT stays MUTED; review and RECALL explicitly."); + else + safe->emitNotice("Last-good Show recovery rejected: "+result.error,true); + }); + if(!started)return reject("Cannot start Show recovery IO worker."); + nativeShowBusy_=true; + return; + } if (action == "routingDryShowRecall") { const auto id=value.toString(); @@ -2149,8 +3365,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr else if (action == "diagnosticMark") { const auto status = engine_.status(); + const auto window=crackleEvidence_.mark(makeEvidenceSample(status)); diagnostics_.record ("AUDIO_GLITCH_MARK", juce::JSON::toString (status, false)); - diagnostics_.record ("AUDIO_GLITCH_WINDOW", crackleWindowReport (status)); + // The recent/important history intentionally caps each entry + // at 950 characters. Keep MEMORY as a separate compact event + // so a long XRun/cadence report never truncates RAM evidence. + diagnostics_.record ("AUDIO_GLITCH_MEMORY", + compactMemoryWindowReport(window)); + diagnostics_.record ("AUDIO_GLITCH_WINDOW", + crackleWindowReport(window)); emitNotice ("Crackle marker saved with source-labeled pre-mark evidence (up to 5 s)."); } else if (action == "backupStudio") @@ -2483,7 +3706,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr fault="Audio device changed during START AUDIO; recheck routing."; if (arm && fault.isEmpty() && !expectedRevision.isVoid() && static_cast(static_cast(expectedRevision)) - !=engine_.dryRoutingLabRevision()) + !=engine_.outputArmRevision()) fault="Native route revision changed; review hardware patch."; // Isolated output-tone testing remains supported in SIGNAL CHECK. if (arm && fault.isEmpty() && @@ -2497,6 +3720,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr auto ack=std::make_unique(); ack->setProperty("ok",fault.isEmpty()); ack->setProperty("armed",engine_.isMonitorEnabled()); + // Optional request identity for safe, ordered device changes. + // No new audio-thread state and backward-compatible with MUTE. + ack->setProperty("requestId", + args.getProperty("requestId",juce::var())); ack->setProperty("error",fault); ack->setProperty("deviceEpoch", static_cast(engine_.dryRoutingLabEpoch())); @@ -2517,12 +3744,36 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } } + bool finishAudioSetupAndRecoverMixer() { + const bool bound=engine_.finishManualAudioSetup(); + if(!engine_.directRouteAuthorized())return false; + const auto lab=engine_.status().getProperty("dryRoutingLab",{}); + if(static_cast(lab.getProperty("nativeChannelIdPcmActive",false)))return true; + if(engine_.hasRetainedNativeSession() || + armix::session::NativeMixerSessionStore(settingsDirectory()).exists()) { + const auto error=restoreSavedMixerSession(); + if(error.isNotEmpty()) { + emitNotice("Mixer retained; "+error,true); + return false; + } + return true; + } + return bound; + } + void changeListenerCallback (juce::ChangeBroadcaster*) override { // Save device state only after a real change, not on every 3-second tick. deviceSettingsDirty_ = true; - if(routedEditorOwner_)closePluginEditor(); + // The retention gate closes only on an actual epoch/owner change. diagnostics_.record ("DEVICE_CHANGE", "Device manager event"); + if((audioSetupWindow_==nullptr || !audioSetupWindow_->isVisible()) && + engine_.recoverSameWasapiMixer()) { + mixerSessionStatus_="RESTORED_MUTED"; + mixerSessionError_.clear(); + diagnostics_.record("DYNAMIC_MIXER_REATTACHED","Verified WASAPI callback epoch; outputs DISARMED"); + emitApprovedNativeSnapshot(); + } } void timerCallback() override @@ -2538,6 +3789,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr guiPerf_.prevTickMs = tickStart; } ++timerTicks_; + servicePendingNativeEq(); // A hidden JUCE/WebView2 peer may defer first navigation. Expose the // compositor behind the opaque startup splash after the first tick; // the user sees the completed mixer only after the ready handshake. @@ -2546,6 +3798,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr webViewPeerWarmed_ = true; setVisible (true); toBack(); + browser_.resized(); // first visible HWND, not its pre-splash size } // Existing message-thread 12 Hz timer: no extra worker or DSP work. // Never allow a hidden broken GUI to continue unattended audio. @@ -2574,6 +3827,17 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr engine_.devices().addChangeListener (this); diagnostics_.record ("STARTUP", startupError_.isEmpty() ? "Audio device initialized" : startupError_); + if(!mixerSessionStartupInspected_) { + mixerSessionStartupInspected_=true; + if(armix::session::NativeMixerSessionStore(settingsDirectory()).exists()){ + mixerSessionRecoveryPending_=true; + const auto error=restoreSavedMixerSession(startupError_.isEmpty()); + if(error.isNotEmpty()) + emitNotice("Saved mixer retained; "+error,true); + else if(saved==nullptr) + deviceSettingsDirty_=true; + } + } if (onStartupStage_) onStartupStage_ (2); } // ONE actionable notice per unexpected DIRECT reroute. The audio @@ -2595,6 +3859,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Audio thread publishes only fault flags. A bounded message-thread // restore transaction handles device failures without hot-plug spin. serviceDirectRestore(); + // Autosave only while ALL outputs are muted. Vendor-state reads + // happen on CONTROL; disk commits run on ONE serialized IO worker. + // A performance with armed speakers/stream is never interrupted for + // snapshot capture. One bounded attempt per 60 seconds of idle UI. + if(audioEngineStarted_ && timerTicks_%720==0 && + engine_.allOutputsDisarmed() && !mixerSessionWorker_.busy() && + !nativeShowBusy_ && !studioBackupBusy_ && !catalog_.busy() && + !engine_.isGraphSwitchPending() && !engine_.hasTemporaryDiagnosticDevice()) + (void)saveMixerSession(false); if (engine_.finalizeGraphSwitch()) { ++fxGraphRevision_; @@ -2652,7 +3925,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // DeviceManager signals even when a temporary capture-only / // output-only route is selected. Never persist that test route. if (!engine_.hasTemporaryDiagnosticDevice() && !engine_.independentClockActive() && - engine_.directRouteAuthorized() && + engine_.directRouteAuthorized() && !engine_.hasRetainedUnboundMixer() && (audioSetupWindow_ == nullptr || !audioSetupWindow_->isVisible()) && engine_.devices().getCurrentAudioDevice() != nullptr) if (auto xml = engine_.devices().createStateXml()) @@ -2703,26 +3976,13 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr crackleEvidence_.push (makeEvidenceSample (state)); diagnostics_.record ("AUDIO_HEALTH", juce::JSON::toString (state, false)); } - if(routedEditorOwner_) { - // Unplug/reopen may bypass normal GUI actions. Never keep a - // vendor editor on an invalid device epoch or removed instance. - const auto route=state.getProperty("dryRoutingLab",{}); - bool retained=false; - if(static_cast(route.getProperty("ready",false)) && - static_cast(route.getProperty("epoch",juce::var(0))) - ==routedEditorEpoch_) { - const auto rows=route.getProperty("fxInstances",juce::var()); - if(const auto* lanes=rows.getArray()) - for(const auto& lane:*lanes) - if(const auto* slots=lane.getArray()) - for(const auto& slot:*slots) - if(slot.getProperty("instanceId",{}).toString() - ==routedEditorOwner_->instanceId) - retained=true; - } - if(!retained)closePluginEditor(); - } + if(routedEditorOwner_ && + !engine_.retainsRoutedFxEditor(routedEditorEpoch_,routedEditorOwner_)) + closePluginEditor(); annotateRecovery (state); + state.getDynamicObject()->setProperty("mixerSessionStatus",mixerSessionStatus_); + if(mixerSessionError_.isNotEmpty()) + state.getDynamicObject()->setProperty("mixerSessionError",mixerSessionError_); state.getDynamicObject()->setProperty ("diagnosticsDropped", static_cast (diagnostics_.lostRecords())); state.getDynamicObject()->setProperty ("diagnosticsTruncated", diff --git a/src/NativeChannelAppearanceStore.h b/src/NativeChannelAppearanceStore.h new file mode 100644 index 000000000..68dd2227b --- /dev/null +++ b/src/NativeChannelAppearanceStore.h @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +// Durable UI identity, not DSP topology. The accepted native ChannelId is the +// address; rename/color/icon never rebuild PCM or touch a realtime callback. +// Disk IO is only performed on the JUCE message thread, never on the audio +// thread. Fail closed on an invalid existing document (no silent overwrite). +namespace armix::appearance { +class Store final { +public: + explicit Store(juce::File directory) + : file_(directory.getChildFile("channel-appearance.v1.json")) + { load(); } + + struct Entry final {juce::String name,color,icon;}; + juce::String error() const {return loadError_;} + static bool decimal(const juce::var& input,std::uint64_t& value,bool zero=false) { + if(!input.isString())return false; + const auto text=input.toString().toStdString(); + if(text.empty()||text.size()>20||(text.size()>1&&text[0]=='0'))return false; + std::uint64_t next=0; + auto [end,err]=std::from_chars(text.data(),text.data()+text.size(),next); + if(err!=std::errc{}||end!=text.data()+text.size()||(!zero&&!next))return false; + value=next;return true; + } + static bool validName(const juce::String& name) { + const auto utf8=name.toStdString(); + if(name.isEmpty()||name!=name.trim()||name.length()>30||utf8.size()>96)return false; + for(auto ch:utf8)if(static_cast(ch)<32||ch==127)return false; + return true; + } + static bool validColor(const juce::String& color) { + if(color.length()!=7||color[0]!='#')return false; + for(int i=1;i<7;++i){ + auto c=color[i]; + if(!((c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F')))return false; + } + return true; + } + static bool validIcon(const juce::String& icon) { + // Compiler-source codepages and JUCE's const-char* overloads differ on + // Windows. Decode the canonical wire UTF-8 bytes explicitly; no + // emoji literals or locale-sensitive constructors in native identity. + static const std::array allowed { + juce::String::fromUTF8("\xE2\x99\xA9"), + juce::String::fromUTF8("\xE2\x99\xAB"), + juce::String::fromUTF8("\xE2\x99\xAC"), + juce::String::fromUTF8("\xF0\x9F\x8E\x99"), + juce::String::fromUTF8("\xF0\x9F\x8E\xB8"), + juce::String::fromUTF8("\xF0\x9F\x8E\xB9"), + juce::String::fromUTF8("\xF0\x9F\xA5\x81"), + juce::String::fromUTF8("\xF0\x9F\x8E\xA7"), + juce::String::fromUTF8("\xE2\x96\xA5"), + juce::String::fromUTF8("\xE2\x97\x89"), + juce::String::fromUTF8("\xE2\x97\x8E"), + juce::String::fromUTF8("\xE2\x8A\x9E") + }; + return std::find(allowed.begin(),allowed.end(),icon)!=allowed.end(); + } + + // Only the accepted control-thread graph may authorize a ChannelId edit. + // No ChannelId JS Number, no ordinal alias and no stale hardware epoch. + juce::String apply(const juce::var& request,const juce::var& accepted) { + if(loadError_.isNotEmpty())return loadError_; + const auto graph=accepted.getProperty("graph",{}); + const auto device=accepted.getProperty("device",{}); + const auto channels=graph.getProperty("channels",{}); + if(!channels.isArray())return "NO_NATIVE_CHANNEL_GRAPH"; + const auto caps=graph.getProperty("capabilities",{}); + const auto session=accepted.getProperty("mixerSession",{}); + if(session.getProperty("authority","").toString()!="CHANNEL_ID"|| + !(static_cast(caps.getProperty("callbackOwnsChannelIds",false))|| + graph.getProperty("bindingState","").toString()=="NEEDS_REMAP")) + return "NATIVE_CHANNEL_GRAPH_NOT_ACCEPTED"; + std::uint64_t channel=0,epoch=0,rev=0,roster=0,appearanceRev=0; + const auto id=request.getProperty("channelId",{}); + if(!decimal(id,channel)|| + !decimal(request.getProperty("deviceEpoch",{}),epoch,true)|| + !decimal(request.getProperty("graphRevision",{}),rev,true)|| + !decimal(request.getProperty("rosterRevision",{}),roster,true)|| + !decimal(request.getProperty("appearanceRevision",{}),appearanceRev,true)|| + epoch==0||rev==0||roster==0|| + device.getProperty("epoch","").toString()!=juce::String(std::to_string(epoch))|| + graph.getProperty("revision","").toString()!=juce::String(std::to_string(rev))|| + graph.getProperty("rosterRevision","").toString()!=juce::String(std::to_string(roster))) + return "STALE_CHANNEL_IDENTITY_OR_GRAPH"; + if(appearanceRev!=revision_)return "STALE_CHANNEL_APPEARANCE_REVISION"; + const auto nameVar=request.getProperty("name",{}); + const auto colorVar=request.getProperty("color",{}); + const auto iconVar=request.getProperty("icon",{}); + if(!nameVar.isString()||!colorVar.isString()||!iconVar.isString()) + return "INVALID_CHANNEL_APPEARANCE_FIELDS"; + const Entry next{nameVar.toString(),colorVar.toString(),iconVar.toString()}; + if(!validName(next.name)||!validColor(next.color)||!validIcon(next.icon)) + return "INVALID_CHANNEL_NAME_COLOR_OR_ICON"; + bool found=false; + const auto idText=id.toString(); + for(const auto& row:*channels.getArray()) { + const auto rowId=row.getProperty("id",{}); + if(!rowId.isString())return "INVALID_NATIVE_ROSTER"; + if(rowId.toString()==idText){found=true;continue;} + const auto it=entries_.find(rowId.toString().toStdString()); + const auto other=it==entries_.end()?row.getProperty("name","").toString():it->second.name; + if(next.name.equalsIgnoreCase(other)) + return "CHANNEL_NAME_ALREADY_IN_USE"; + } + if(!found)return "CHANNEL_NOT_IN_NATIVE_ROSTER"; + const auto key=idText.toStdString(); + const auto existing=entries_.find(key); + if(existing!=entries_.end() && existing->second.name==next.name && + existing->second.color==next.color && existing->second.icon==next.icon) + return {}; // idempotent; no flash, no unnecessary disk IO + if(entries_.size()>=512&&existing==entries_.end()) + return "CHANNEL_APPEARANCE_LIMIT"; + if(revision_==std::numeric_limits::max()) + return "CHANNEL_APPEARANCE_REVISION_EXHAUSTED"; + auto candidate=entries_;candidate[key]=next; + const auto writeError=commit(candidate,revision_+1); + if(writeError.isNotEmpty())return writeError; + entries_.swap(candidate);++revision_; + return {}; + } + + juce::var snapshot(const juce::var& graph) const { + auto root=std::make_unique(); + root->setProperty("schema","arsonmix.native.channel-appearance.v1"); + root->setProperty("revision",juce::String(std::to_string(revision_))); + root->setProperty("readOnly",loadError_.isNotEmpty()); + juce::Array rows; + const auto channels=graph.getProperty("channels",{}); + if(const auto* live=channels.getArray()){ + for(const auto& ch:*live){ + const auto id=ch.getProperty("id",{}).toString(); + const auto found=entries_.find(id.toStdString()); + if(found==entries_.end())continue; + auto row=std::make_unique(); + row->setProperty("id",id); + row->setProperty("name",found->second.name); + row->setProperty("color",found->second.color); + row->setProperty("icon",found->second.icon); + rows.add(juce::var(row.release())); + } + } + root->setProperty("entries",juce::var(rows)); + return juce::var(root.release()); + } + +private: + juce::File file_; + std::map entries_; + std::uint64_t revision_=0; + juce::String loadError_; + + static juce::var encode(const std::map& entries, + std::uint64_t revision) { + auto root=std::make_unique(); + root->setProperty("schema","arsonmix.native.channel-appearance.v1"); + root->setProperty("revision",juce::String(std::to_string(revision))); + juce::Array rows; + for(const auto& [key,entry]:entries) { + auto item=std::make_unique(); + item->setProperty("id",juce::String(key)); + item->setProperty("name",entry.name); + item->setProperty("color",entry.color); + item->setProperty("icon",entry.icon); + rows.add(juce::var(item.release())); + } + root->setProperty("entries",juce::var(rows)); + return juce::var(root.release()); + } + juce::String commit(const std::map& candidate, + std::uint64_t revision) const { + const auto directory=file_.getParentDirectory(); + if(!directory.isDirectory()&&directory.createDirectory().failed()) + return "CANNOT_CREATE_CHANNEL_APPEARANCE_DIRECTORY"; + const auto json=juce::JSON::toString(encode(candidate,revision),false); + if(json.getNumBytesAsUTF8()>128*1024) + return "CHANNEL_APPEARANCE_DOCUMENT_TOO_LARGE"; + juce::TemporaryFile temp(file_); + auto output=temp.getFile().createOutputStream(); + if(!output||!output->writeText(json,false,false,"\n")) + return "CANNOT_STAGE_CHANNEL_APPEARANCE"; + output->flush(); + if(output->getStatus().failed())return "CANNOT_FLUSH_CHANNEL_APPEARANCE"; + output.reset(); + if(!temp.overwriteTargetFileWithTemporary()) + return "CANNOT_ATOMICALLY_COMMIT_CHANNEL_APPEARANCE"; + return {}; + } + void load() { + if(!file_.exists())return; + if(!file_.existsAsFile()||file_.getSize()<1||file_.getSize()>128*1024){ + loadError_="CHANNEL_APPEARANCE_FILE_INVALID";return; + } + const auto root=juce::JSON::parse(file_.loadFileAsString()); + if(!root.isObject()||root.getProperty("schema","").toString()!="arsonmix.native.channel-appearance.v1"){ + loadError_="CHANNEL_APPEARANCE_SCHEMA_INVALID";return; + } + const auto data=root.getProperty("entries",{}); + std::uint64_t revision=0; + if(!decimal(root.getProperty("revision",{}),revision,true)||!data.isArray()|| + data.getArray()->size()>512){ + loadError_="CHANNEL_APPEARANCE_CONTENT_INVALID";return; + } + std::map candidate; + for(const auto& item:*data.getArray()) { + const auto id=item.getProperty("id",{}); + const auto name=item.getProperty("name",{}); + const auto color=item.getProperty("color",{}); + const auto icon=item.getProperty("icon",{}); + std::uint64_t n=0; + if(!decimal(id,n)||!name.isString()||!color.isString()||!icon.isString()|| + !validName(name.toString())||!validColor(color.toString())|| + !validIcon(icon.toString())|| + !candidate.emplace(id.toString().toStdString(), + Entry{name.toString(),color.toString(),icon.toString()}).second) { + loadError_="CHANNEL_APPEARANCE_ENTRY_INVALID";return; + } + } + entries_.swap(candidate);revision_=revision; + } +}; +} // namespace armix::appearance diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h new file mode 100644 index 000000000..a38f02a94 --- /dev/null +++ b/src/NativeMixerSessionDocument.h @@ -0,0 +1,472 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include "../engine/core/UnifiedLegacyProductionAdmission.h" +#include "NativeShowStore.h" +#include +#include +#include +#include +#include +#include + +// The logical session and its hardware binding are deliberately separate. +// This is a DOCUMENT, not another graph, DSP engine or audio callback. +// All validation/conversion occurs on the JUCE CONTROL / I/O threads. +namespace armix::session { +using namespace armix::mixer; + +struct HardwareBinding final { + juce::String backend,capture,playback,inputMask,outputMask; + double rate=0.; + int frames=0; +}; +struct StoredInsert final { + ChannelId channel{}; + std::size_t slot=0; + juce::String catalogId,path,sha256,name; + int uid=0; + bool bypass=false; +}; +struct MixerSessionDocument final { + juce::String id; + DynamicChannelRoster roster{ChannelRosterBudget{ + 32u*1024u*1024u,8u,static_cast(maxChannelSends+maxAuxSends+2)}}; + DynamicGraphRequest request{}; + LegacyChannelIds legacyIds{}; + VerifiedNativeOutputs outputs{}; + HardwareBinding binding{}; + std::vector inserts; + std::vector rackBypassed; + float masterGain=1.f; + bool masterMute=false,masterMono=false; + // Internal checkpoint preference, distinct from the hardware monitor pair. + std::optional resumeMain; + std::uint64_t acceptedRevision=0; + juce::int64 savedMs=0; +}; +// Logical topology never authorizes a different physical endpoint. An +// operator-confirmed rebind changes only verified hardware metadata; it +// cannot change the ChannelId graph, vendor state, or ARM an output. +struct MixerDeviceBindingPolicy final { + static bool sameBinding(const HardwareBinding& a,const HardwareBinding& b) { + return a.backend==b.backend && a.capture==b.capture && + a.playback==b.playback && a.inputMask==b.inputMask && + a.outputMask==b.outputMask && a.rate==b.rate; + } + static bool sameOutputs(const VerifiedNativeOutputs& a, + const VerifiedNativeOutputs& b) { + return a.activeOutputChannels==b.activeOutputChannels && + a.mainL==b.mainL && a.mainR==b.mainR && + a.monitorEnabled==b.monitorEnabled && + (!a.monitorEnabled || + (a.monitorL==b.monitorL && a.monitorR==b.monitorR)); + } + // Preserve the selected physical pairs when they still exist. A new + // pair is only proposed here; apply() requires operator confirmation. + static VerifiedNativeOutputs proposedOutputs(const MixerSessionDocument& document, + const HardwareBinding& live,int count) { + auto outputs=document.outputs; + outputs.activeOutputChannels=count; + if(document.binding.outputMask!=live.outputMask) { + const auto saved=mask(document.binding.outputMask); + const auto current=mask(live.outputMask); + outputs.mainL=remapPin(saved,current,outputs.mainL); + outputs.mainR=remapPin(saved,current,outputs.mainR); + if(outputs.monitorEnabled) { + outputs.monitorL=remapPin(saved,current,outputs.monitorL); + outputs.monitorR=remapPin(saved,current,outputs.monitorR); + } + } + if(!outputs.valid()) + outputs={count,0,1,outputs.monitorEnabled?2:-1, + outputs.monitorEnabled?3:-1,outputs.monitorEnabled}; + return outputs; + } + static juce::String apply(MixerSessionDocument& document, + const HardwareBinding& live, + const VerifiedNativeOutputs& outputs, + int callbackInputs,bool operatorApproved) { + if(!outputs.valid() || callbackInputs<1 || callbackInputs>256 || + live.backend.isEmpty() || live.capture.isEmpty() || + live.playback.isEmpty() || live.inputMask.isEmpty() || + live.outputMask.isEmpty() || !std::isfinite(live.rate) || + live.rate<8000. || live.rate>384000. || + live.frames<16 || live.frames>8192) + return "NEEDS_REMAP: live device verification incomplete"; + const auto oldPins=mask(document.binding.inputMask); + const auto newPins=mask(live.inputMask); + if(oldPins.countNumberOfSetBits()!=document.request.physicalInputs || + newPins.countNumberOfSetBits()!=callbackInputs || + mask(live.outputMask).countNumberOfSetBits()!=outputs.activeOutputChannels) + return "NEEDS_REMAP: callback pin inventory does not match device masks"; + if(sameBinding(document.binding,live) && sameOutputs(document.outputs,outputs)) + return {}; + if(!operatorApproved) + return "NEEDS_REMAP: select the saved audio device and pin layout in Audio I/O"; + + if(oldPins!=newPins) { + auto& sources=document.request.sources; + if(document.binding.backend!=live.backend || document.binding.capture!=live.capture) { + // Different endpoint AND different layout: numerical overlap + // cannot establish the identity of a capture pin. + sources.clear(); + } else { + std::vector mapped; + mapped.reserve(sources.size()); + for(auto source:sources) { + source.inputL=remapPin(oldPins,newPins,source.inputL); + if(source.stereo)source.inputR=remapPin(oldPins,newPins,source.inputR); + if(source.inputL>=0 && (!source.stereo || source.inputR>=0)) + mapped.push_back(source); + } + sources=std::move(mapped); + } + } + document.request.physicalInputs=callbackInputs; + document.binding=live; + document.outputs=outputs; + return {}; + } +private: + static juce::BigInteger mask(const juce::String& text) { + juce::BigInteger bits; + bits.parseString(text,16); + return bits; + } + static int remapPin(const juce::BigInteger& saved,const juce::BigInteger& current,int ordinal) { + if(ordinal<0)return -1; + int physical=saved.findNextSetBit(0); + for(int i=0;i=0;++i) + physical=saved.findNextSetBit(physical+1); + if(physical<0 || !current[physical])return -1; + int index=0; + for(int pin=current.findNextSetBit(0);pin20||(s[0]=='0'&&s.size()!=1))return false; + std::uint64_t n=0; + auto [end,err]=std::from_chars(s.data(),s.data()+s.size(),n); + if(err!=std::errc{}||end!=s.data()+s.size()||(!allowZero&&!n))return false; + result=n;return true; +} +inline bool real(const juce::var& v,double& n,double lo,double hi) { + if(!(v.isDouble()||v.isInt()||v.isInt64()))return false; + n=static_cast(v); + return std::isfinite(n)&&n>=lo&&n<=hi; +} +inline bool integral(const juce::var& v,int& n,int lo,int hi) { + if(!v.isInt())return false; + n=static_cast(v); + return n>=lo&&n<=hi; +} +inline juce::var get(const juce::var& v,const char* key) { + return v.isObject()?v.getProperty(key,juce::var()):juce::var(); +} +inline bool strictBool(const juce::var& v,bool& out) { + if(!v.isBool())return false; + out=static_cast(v);return true; +} +inline bool textField(const juce::var& v,juce::String& out,int max,bool empty=false) { + if(!v.isString()||v.toString().getNumBytesAsUTF8()>max|| + (!empty&&v.toString().isEmpty()))return false; + out=v.toString();return true; +} +class Codec final { + static juce::var object(){return juce::var(new juce::DynamicObject());} + static void set(juce::var& obj,const char* k,const juce::var& v) { + obj.getDynamicObject()->setProperty(k,v); + } + static juce::var ids(const LegacyChannelIds& ids) { + auto v=object(); + juce::Array in,aux; + for(auto id:ids.inputs)in.add(decimal(id.value)); + for(auto id:ids.aux)aux.add(decimal(id.value)); + set(v,"inputs",juce::var(in));set(v,"aux",juce::var(aux)); + set(v,"main",decimal(ids.main.value)); + set(v,"monitor",decimal(ids.monitor.value)); + return v; + } + static bool readIds(const juce::var& v,LegacyChannelIds& ids) { + const auto inputVar=get(v,"inputs"),auxVar=get(v,"aux"); + const auto* in=inputVar.getArray(),*aux=auxVar.getArray(); + if(!in||!aux||in->size()!=stripCount||aux->size()!=auxBusCount) + return false; + for(int i=0;igetReference(i),ids.inputs[i].value))return false; + for(int i=0;igetReference(i),ids.aux[i].value))return false; + return parseDecimal(get(v,"main"),ids.main.value) && + parseDecimal(get(v,"monitor"),ids.monitor.value,true); + } +public: + static juce::String encode(const MixerSessionDocument& d) { + auto root=object(); + set(root,"schema","arsonmix.mixer-session.v1"); + set(root,"id",d.id); + set(root,"acceptedRevision",decimal(d.acceptedRevision)); + set(root,"savedMs",decimal(static_cast(d.savedMs))); + if(d.resumeMain.has_value())set(root,"resumeMain",*d.resumeMain); + set(root,"legacyIds",ids(d.legacyIds)); + auto bind=object(); + set(bind,"backend",d.binding.backend); + set(bind,"capture",d.binding.capture); + set(bind,"playback",d.binding.playback); + set(bind,"inputMask",d.binding.inputMask); + set(bind,"outputMask",d.binding.outputMask); + set(bind,"rate",d.binding.rate); + set(bind,"frames",d.binding.frames); + set(root,"binding",bind); + auto output=object(); + set(output,"active",d.outputs.activeOutputChannels); + set(output,"mainL",d.outputs.mainL);set(output,"mainR",d.outputs.mainR); + set(output,"monitorL",d.outputs.monitorL); + set(output,"monitorR",d.outputs.monitorR); + set(output,"monitorEnabled",d.outputs.monitorEnabled); + set(root,"outputs",output); + auto master=object(); + set(master,"gain",d.masterGain);set(master,"mute",d.masterMute); + set(master,"mono",d.masterMono);set(root,"master",master); + juce::Array channels; + for(const auto& row:d.roster.channels()) { + auto ch=object(); + set(ch,"id",decimal(row.id.value)); + set(ch,"role",static_cast(row.role)); + set(ch,"format",static_cast(row.format)); + set(ch,"name",juce::String::fromUTF8(row.name.c_str())); + set(ch,"gain",row.faderLinear); + set(ch,"pan",row.pan);set(ch,"mute",row.mute);set(ch,"solo",row.solo); + juce::Array catalogs,sends; + for(const auto& c:row.insertCatalogIds) + catalogs.add(juce::String::fromUTF8(c.c_str())); + for(const auto& s:row.sends){ + auto e=object(); + set(e,"edgeId",decimal(s.edgeId)); + set(e,"to",decimal(s.destination.value)); + set(e,"gain",s.gain);set(e,"pan",s.pan); + set(e,"pre",s.preFader);set(e,"primary",s.primaryOutput); + sends.add(e); + } + set(ch,"catalogs",juce::var(catalogs)); + set(ch,"sends",juce::var(sends)); + channels.add(ch); + } + set(root,"channels",juce::var(channels)); + auto request=object(); + set(request,"physicalInputs",d.request.physicalInputs); + set(request,"maxFrames",d.request.maxFrames); + set(request,"mainMonoAfterFx",d.request.mainMonoAfterFx); + juce::Array sources; + for(const auto& p:d.request.sources) { + auto source=object(); + set(source,"id",decimal(p.id.value)); + set(source,"left",p.inputL); + set(source,"right",p.inputR); + set(source,"stereo",p.stereo); + sources.add(source); + } + set(request,"sources",juce::var(sources)); + set(root,"request",request); + juce::Array inserts,racks; + for(const auto& f:d.inserts) { + auto fx=object(); + set(fx,"channel",decimal(f.channel.value)); + set(fx,"slot",static_cast(f.slot)); + set(fx,"catalogId",f.catalogId);set(fx,"path",f.path); + set(fx,"uid",f.uid);set(fx,"name",f.name); + set(fx,"sha256",f.sha256);set(fx,"bypass",f.bypass); + inserts.add(fx); + } + for(auto id:d.rackBypassed)racks.add(decimal(id.value)); + set(root,"inserts",juce::var(inserts));set(root,"rackBypassed",juce::var(racks)); + return juce::JSON::toString(root,false); + } + static bool decode(const juce::String& json,MixerSessionDocument& output) { + if(json.getNumBytesAsUTF8()>4U*1024U*1024U)return false; + auto root=juce::JSON::parse(json); + if(!root.isObject()||get(root,"schema").toString()!="arsonmix.mixer-session.v1") + return false; + MixerSessionDocument doc; + if(root.getDynamicObject()->hasProperty("resumeMain")) { + bool resume=false; + if(!strictBool(get(root,"resumeMain"),resume))return false; + doc.resumeMain=resume; + } + if(!textField(get(root,"id"),doc.id,48)|| + !armix::shows::detail::uuid(doc.id)|| + !parseDecimal(get(root,"acceptedRevision"),doc.acceptedRevision)|| + !readIds(get(root,"legacyIds"),doc.legacyIds)) + return false; + std::uint64_t ms=0; + if(!parseDecimal(get(root,"savedMs"),ms)||ms>static_cast( + std::numeric_limits::max()))return false; + doc.savedMs=static_cast(ms); + const auto binding=get(root,"binding"); + if(!textField(get(binding,"backend"),doc.binding.backend,128)|| + !textField(get(binding,"capture"),doc.binding.capture,256)|| + !textField(get(binding,"playback"),doc.binding.playback,256)|| + !textField(get(binding,"inputMask"),doc.binding.inputMask,256)|| + !textField(get(binding,"outputMask"),doc.binding.outputMask,256)) + return false; + double n=0.; + if(!real(get(binding,"rate"),n,8000.,384000.))return false; + doc.binding.rate=n; + if(!integral(get(binding,"frames"),doc.binding.frames,16,8192)) + return false; + auto outputs=get(root,"outputs"); + if(!integral(get(outputs,"active"),doc.outputs.activeOutputChannels,2,256)|| + !integral(get(outputs,"mainL"),doc.outputs.mainL,0,255)|| + !integral(get(outputs,"mainR"),doc.outputs.mainR,0,255)|| + !integral(get(outputs,"monitorL"),doc.outputs.monitorL,-1,255)|| + !integral(get(outputs,"monitorR"),doc.outputs.monitorR,-1,255)|| + !strictBool(get(outputs,"monitorEnabled"),doc.outputs.monitorEnabled)|| + !doc.outputs.valid())return false; + auto master=get(root,"master"); + if(!real(get(master,"gain"),n,0.,4.))return false; + doc.masterGain=static_cast(n); + if(!strictBool(get(master,"mute"),doc.masterMute)|| + !strictBool(get(master,"mono"),doc.masterMono))return false; + const auto channelsVar=get(root,"channels"); + const auto* channels=channelsVar.getArray(); + if(!channels||channels->size()<15||channels->size()>2048)return false; + std::vector entries; + entries.reserve(static_cast(channels->size())); + for(const auto& ch:*channels) { + ChannelStripDefinition row; + int role=0,format=0; + if(!parseDecimal(get(ch,"id"),row.id.value)|| + !integral(get(ch,"role"),role,0,4)|| + !integral(get(ch,"format"),format,0,1))return false; + row.role=static_cast(role); + row.format=static_cast(format); + juce::String name; + if(!textField(get(ch,"name"),name,96)|| + !real(get(ch,"gain"),n,0.,4.))return false; + row.name=name.toStdString();row.faderLinear=static_cast(n); + if(!real(get(ch,"pan"),n,-1.,1.))return false; + row.pan=static_cast(n); + if(!strictBool(get(ch,"mute"),row.mute)|| + !strictBool(get(ch,"solo"),row.solo))return false; + const auto catalogsVar=get(ch,"catalogs"),sendsVar=get(ch,"sends"); + const auto* catalogs=catalogsVar.getArray(); + const auto* sends=sendsVar.getArray(); + if(!catalogs||!sends||catalogs->size()>8||sends->size()>128) + return false; + for(const auto& catalog:*catalogs) { + juce::String value; + if(!textField(catalog,value,256))return false; + row.insertCatalogIds.push_back(value.toStdString()); + } + for(const auto& send:*sends) { + ChannelSendRef edge; + if(!parseDecimal(get(send,"edgeId"),edge.edgeId)|| + !parseDecimal(get(send,"to"),edge.destination.value)|| + !real(get(send,"gain"),n,0.,4.))return false; + edge.gain=static_cast(n); + if(!real(get(send,"pan"),n,-1.,1.))return false; + edge.pan=static_cast(n); + if(!strictBool(get(send,"pre"),edge.preFader)|| + !strictBool(get(send,"primary"),edge.primaryOutput))return false; + row.sends.push_back(edge); + } + entries.push_back(std::move(row)); + } + if(!doc.roster.restoreExact(doc.acceptedRevision,entries))return false; + const auto seek=[&doc](ChannelId id,ChannelRole role){ + const auto* row=doc.roster.find(id); + return row && row->role==role; + }; + for(auto id:doc.legacyIds.inputs)if(!seek(id,ChannelRole::input))return false; + for(auto id:doc.legacyIds.aux)if(!seek(id,ChannelRole::fxReturn))return false; + if(!seek(doc.legacyIds.main,ChannelRole::main) || + (doc.legacyIds.monitor.value&&!seek(doc.legacyIds.monitor,ChannelRole::monitor))) + return false; + auto req=get(root,"request"); + if(!integral(get(req,"physicalInputs"),doc.request.physicalInputs,1,256)|| + !integral(get(req,"maxFrames"),doc.request.maxFrames,16,8192)|| + !strictBool(get(req,"mainMonoAfterFx"),doc.request.mainMonoAfterFx)) + return false; + const auto sourcesVar=get(req,"sources"); + const auto* sources=sourcesVar.getArray(); + if(!sources||sources->size()>channels->size())return false; + std::set seenSources; + for(const auto& src:*sources) { + DynamicSourcePatch p; + if(!parseDecimal(get(src,"id"),p.id.value)|| + !seenSources.insert(p.id.value).second || + !seek(p.id,ChannelRole::input) || + !integral(get(src,"left"),p.inputL,0,doc.request.physicalInputs-1)|| + !integral(get(src,"right"),p.inputR,-1,doc.request.physicalInputs-1)|| + !strictBool(get(src,"stereo"),p.stereo)|| + (p.stereo && (p.inputR<0||p.inputR==p.inputL))|| + (!p.stereo&&p.inputR>=0)) + return false; + doc.request.sources.push_back(p); + } + const auto fxVar=get(root,"inserts"),racksVar=get(root,"rackBypassed"); + const auto* fx=fxVar.getArray(); + const auto* racks=racksVar.getArray(); + if(!fx||!racks||fx->size()>16384||racks->size()>channels->size())return false; + std::set> seenFx; + for(const auto& item:*fx) { + StoredInsert p;int slot=0; + if(!parseDecimal(get(item,"channel"),p.channel.value)|| + !doc.roster.find(p.channel)|| + !integral(get(item,"slot"),slot,0,7))return false; + p.slot=static_cast(slot); + if(!seenFx.emplace(p.channel.value,p.slot).second|| + !textField(get(item,"catalogId"),p.catalogId,256)|| + !textField(get(item,"path"),p.path,2048,true)|| + !textField(get(item,"name"),p.name,256,true)|| + !integral(get(item,"uid"),p.uid,std::numeric_limits::min(), + std::numeric_limits::max())|| + !textField(get(item,"sha256"),p.sha256,64)|| + p.sha256.length()!=64 || + !p.sha256.containsOnly("0123456789abcdef")|| + !strictBool(get(item,"bypass"),p.bypass))return false; + doc.inserts.push_back(std::move(p)); + } + for(const auto& item:*racks) { + ChannelId id; + if(!parseDecimal(item,id.value)||!doc.roster.find(id)|| + std::find(doc.rackBypassed.begin(),doc.rackBypassed.end(),id)!= + doc.rackBypassed.end())return false; + doc.rackBypassed.push_back(id); + } + // Encode always emits in ChannelId/slot order. A manually shuffled or + // duplicated slot manifest is rejected; its vendor states must never + // attach to a different processor or channel. + for(const auto& ch:doc.roster.channels()) { + std::size_t slot=0; + const bool legacyMarker=ch.insertCatalogIds.size()==1 && + ch.insertCatalogIds[0]=="legacy:aux-rack"; + for(const auto& fxRow:doc.inserts) + if(fxRow.channel==ch.id) { + if(fxRow.slot!=slot++)return false; + // A malformed, otherwise SHA-correct document can claim + // more FX slots than the accepted roster's catalog. + // Bound-check BEFORE indexing: never allow UB on restore. + if(!legacyMarker && + (fxRow.slot>=ch.insertCatalogIds.size() || + ch.insertCatalogIds[fxRow.slot]!=fxRow.catalogId.toStdString())) + return false; + } + // The old four AUX are declared as legacy:aux-rack placeholders + // even when no plugin is installed. They are NOT vendor leases. + // No orphan leases, and no phantom roster FX. In particular an + // empty catalog cannot authorize an installed vendor processor. + if(!legacyMarker&&slot!=ch.insertCatalogIds.size())return false; + } + output=std::move(doc); + return true; + } +}; +} // namespace armix::session diff --git a/src/NativeMixerSessionFxRestore.h b/src/NativeMixerSessionFxRestore.h new file mode 100644 index 000000000..7bab6ca48 --- /dev/null +++ b/src/NativeMixerSessionFxRestore.h @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "NativeMixerSessionDocument.h" +#include "VstBusLayout.h" +#include "../engine/builtin_fx/ChannelEqProcessor.h" +#include +#include +#include +#include +#include +#include +#include + +// Prepare ALL owned VST3 processors on CONTROL before the one ChannelId PCM +// publisher commit. Never re-use a previous device epoch's processor. +namespace armix::session { +class NativeMixerSessionFxRestore final { +public: + using Bank=armix::mixer::DynamicChannelFxLeaseBank; + using Lease=armix::mixer::LiveChannelFxGraph::InstanceLease; + static juce::String prepare(const MixerSessionDocument& doc, + const std::vector& states, + juce::AudioPluginFormatManager& formats,double sampleRate, + int frames,std::uint64_t epoch,std::uint64_t pcmRevision, + std::shared_ptr& result) { + if(!(sampleRate>=8000.&&sampleRate<=384000.)||frames<32|| + frames>armix::mixer::PreparedMixerBlock::hardFrameLimit|| + epoch==0||pcmRevision==0) + return "Invalid driver/epoch for VST3 restoration"; + auto* format=formats.getFormat(0); + std::vector assignments; + assignments.reserve(doc.roster.size()); + // Index ONCE. A large dynamic mixer must not rescan every channel + // against all VST3 inserts and binary states at every restart. + // Manifest validity is established by Codec; preserve slot order. + std::unordered_map> byChannel; + std::unordered_map byHash; + byChannel.reserve(doc.roster.size()); + byHash.reserve(states.size()); + for(const auto& insert:doc.inserts) + byChannel[insert.channel.value].push_back(&insert); + for(const auto& state:states) + if(!byHash.emplace(state.sha256.toStdString(),&state).second) + return "Duplicate mixer vendor-state blob identity"; + try { + for(const auto& ch:doc.roster.channels()) { + Bank::Assignment lane; + lane.id=ch.id;lane.format=ch.format; + if(std::find(doc.rackBypassed.begin(),doc.rackBypassed.end(),ch.id) + !=doc.rackBypassed.end()) + lane.rackBypassed=std::make_shared>(true); + const auto laneIt=byChannel.find(ch.id.value); + if(laneIt!=byChannel.end()) + for(const StoredInsert* stored:laneIt->second) { + const auto& insert=*stored; + if(insert.slot!=lane.inserts.size()) + return "Saved FX slots are not contiguous"; + const auto found=byHash.find(insert.sha256.toStdString()); + if(found==byHash.end()) + return "Missing saved VST3 state"; + const auto& state=*found->second; + if(state.bytes.getSize()>8U*1024U*1024U|| + juce::SHA256(state.bytes).toHexString()!=insert.sha256) + return "Missing or corrupt saved VST3 state"; + std::unique_ptr processor; + if(insert.catalogId== + armix::builtin_fx::ChannelEqProcessor::catalogIdentity) { + auto eq=std::make_unique(); + eq->prepareToPlay(sampleRate,frames); + if(!eq->isReady()|| + !eq->restoreUnpublishedState( + state.bytes.getData(), + static_cast(state.bytes.getSize()))) + return "Saved native EQ state rejected; graph unchanged"; + processor=std::move(eq); + } else { + if(!format|| + !format->fileMightContainThisPluginType(insert.path)) + return "Saved VST3 unavailable: "+insert.catalogId; + juce::OwnedArray descriptions; + format->findAllTypesForFile(descriptions,insert.path); + juce::PluginDescription* chosen=nullptr; + for(auto* d:descriptions) + if(d&&d->uniqueId==insert.uid&&!d->isInstrument) + {chosen=d;break;} + if(!chosen)return "Saved VST3 identity not found: "+insert.catalogId; + juce::String pluginError; + processor=formats.createPluginInstance(*chosen,sampleRate,frames,pluginError); + if(!processor) + return "VST3 instance unavailable: "+pluginError; + const auto layout=armix::vst::prepareStereoEffectLayout(*processor); + if(layout.isNotEmpty()) + return "Saved VST3 stereo layout rejected: "+layout; + processor->prepareToPlay(sampleRate,frames); + } + if(insert.catalogId!= + armix::builtin_fx::ChannelEqProcessor::catalogIdentity) + processor->setStateInformation(state.bytes.getData(), + static_cast(state.bytes.getSize())); + const int latency=processor->getLatencySamples(); + if(latency<0|| + latency>armix::dsp::StereoLatencyDelay::maximumSamples) + return "Saved FX latency exceeds graph PDC budget"; + auto owner=std::make_shared( + std::move(processor),insert.catalogId,insert.name, + armix::mixer::PreparedMixerBlock::hardFrameLimit); + owner->bypassRequested.store(insert.bypass,std::memory_order_release); + lane.inserts.push_back(std::move(owner)); + } + assignments.push_back(std::move(lane)); + } + Bank prepared; + const auto fault=Bank::prepare(epoch,pcmRevision,assignments,prepared); + if(fault!=Bank::Fault::none) + return "Saved native FX lease rejected: "+ + juce::String(static_cast(fault)); + result=std::make_shared(std::move(prepared)); + return {}; + }catch(const std::exception& ex) { + return "VST3 restore rejected: "+juce::String(ex.what()); + }catch(...) {return "VST3 restore aborted without PCM mutation";} + } +}; +} // namespace armix::session diff --git a/src/NativeMixerSessionSaveWorker.h b/src/NativeMixerSessionSaveWorker.h new file mode 100644 index 000000000..6e39dd5e0 --- /dev/null +++ b/src/NativeMixerSessionSaveWorker.h @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "NativeMixerSessionStore.h" +#include +#include +#include +#include +#include +#include + +// Snapshot ownership moves from JUCE CONTROL to this single IO thread. +// No file IO or SHA-256 in the realtime callback. An immutable generation is +// promoted only after all bytes verify, with a message-thread completion. +namespace armix::session { +class NativeMixerSessionSaveWorker final : private juce::Thread { +public: + using Completion=std::function; + using ReadCompletion=std::function)>; + NativeMixerSessionSaveWorker():juce::Thread("ArSonMix MixerSession IO"){} + ~NativeMixerSessionSaveWorker() override { + alive_->store(false,std::memory_order_release); + signalThreadShouldExit(); + stopThread(-1); + } + bool busy() const noexcept {return busy_.load(std::memory_order_acquire);} + void finishForShutdown() { + waitForThreadToExit(-1); + busy_.store(false,std::memory_order_release); + done_={};readDone_={};states_.clear(); + } + bool save(juce::File studio,MixerSessionDocument document, + std::vector binary, + Completion completion,juce::File exportFile={}) { + if(busy_.exchange(true,std::memory_order_acq_rel))return false; + studio_=std::move(studio); + exportFile_=std::move(exportFile); + doc_=std::move(document); + states_=std::move(binary); + done_=std::move(completion); + return start(); + } + bool load(juce::File file,ReadCompletion completion) { + if(busy_.exchange(true,std::memory_order_acq_rel))return false; + exportFile_=std::move(file); + readDone_=std::move(completion); + return start(); + } +private: + bool start() { + ++serial_; + if(!startThread()){ + busy_.store(false,std::memory_order_release); + done_={};readDone_={};states_.clear(); + return false; + } + return true; + } + void run() override { + juce::String error; + try { + NativeMixerSessionStore store(studio_); + if(readDone_)error=NativeMixerSessionStore::readFile(exportFile_,doc_,states_); + else error=exportFile_==juce::File{}?store.commit(doc_,states_): + NativeMixerSessionStore::writeFile(exportFile_,doc_,states_); + }catch(...) {error="Mixer session IO worker exception";} + // Release potentially large VST3 binary buffers before callback. + if(!readDone_)states_.clear(); + auto alive=alive_; + const auto serial=serial_; + juce::MessageManager::callAsync([this,alive,error,serial]() mutable { + if(!alive->load(std::memory_order_acquire)||serial!=serial_)return; + busy_.store(false,std::memory_order_release); + auto callback=std::move(done_); + done_={}; + auto readCallback=std::move(readDone_); + readDone_={}; + if(readCallback)readCallback(std::move(error),std::move(doc_),std::move(states_)); + else if(callback)callback(std::move(error)); + }); + } + juce::File studio_,exportFile_; + MixerSessionDocument doc_; + std::vector states_; + Completion done_; + ReadCompletion readDone_; + unsigned serial_=0; + std::atomic busy_{false}; + std::shared_ptr> alive_= + std::make_shared>(true); +}; +} // namespace armix::session diff --git a/src/NativeMixerSessionStore.h b/src/NativeMixerSessionStore.h new file mode 100644 index 000000000..da614918e --- /dev/null +++ b/src/NativeMixerSessionStore.h @@ -0,0 +1,261 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "NativeMixerSessionDocument.h" +#include +#include +#include +#include +#include + +// One durable device-independent MixerSessionDocument per Studio workspace. +// No audio thread access. Generations are immutable. A single atomic HEAD +// pointer is the commit boundary, and PREVIOUS remains explicit recovery only. +namespace armix::session { +class NativeMixerSessionStore final { +public: + explicit NativeMixerSessionStore(juce::File studio) + : root_(studio.getChildFile("MixerSession")) {} + static constexpr juce::int64 maxJson=4*1024*1024; + static constexpr juce::int64 maxState=8*1024*1024; + static constexpr juce::int64 maxTotal=128*1024*1024; + static constexpr std::size_t maxStates=16384; + + juce::String commit(const MixerSessionDocument& doc, + const std::vector& states) const { + if(!armix::shows::detail::uuid(doc.id)||states.size()>maxStates) + return "Mixer session ID/state count invalid"; + const auto json=Codec::encode(doc); + if(json.getNumBytesAsUTF8()>maxJson)return "Mixer session document exceeds 4 MB"; + MixerSessionDocument verified; + if(!Codec::decode(json,verified))return "Mixer session graph cannot be serialized safely"; + std::set hashes,referenced; + juce::int64 total=json.getNumBytesAsUTF8(); + for(const auto& fx:doc.inserts)referenced.insert(fx.sha256.toLowerCase()); + for(const auto& state:states) { + if(!safeHash(state.sha256)||!hashes.insert(state.sha256.toLowerCase()).second|| + state.bytes.getSize()>static_cast(maxState)|| + juce::SHA256(state.bytes).toHexString()!=state.sha256.toLowerCase()) + return "Mixer vendor state duplicate, oversized or wrong SHA"; + total+=static_cast(state.bytes.getSize()); + if(total>maxTotal)return "Mixer session exceeds 128 MB budget"; + } + if(hashes!=referenced)return "Mixer vendor state manifest is incomplete"; + if(!root_.isDirectory()&&root_.createDirectory().failed()) + return "MixerSession directory is not writable"; + const auto versions=root_.getChildFile("versions"); + if(!versions.isDirectory()&&versions.createDirectory().failed()) + return "MixerSession versions directory unavailable"; + const auto id=juce::Uuid().toDashedString().toLowerCase(); + if(!armix::shows::detail::uuid(id))return "Cannot allocate generation"; + const auto stage=root_.getChildFile(".staging-"+id); + if(stage.exists()||stage.createDirectory().failed()) + return "Cannot create mixer staging directory"; + struct Clean final { + juce::File dir; + ~Clean(){if(dir.exists())dir.deleteRecursively();} + } cleanup{stage}; + const auto payload=stage.getChildFile("blobs"); + if(payload.createDirectory().failed())return "Cannot create vendor state directory"; + const auto checksum=juce::SHA256(json.toRawUTF8(),json.getNumBytesAsUTF8()).toHexString(); + if(!stage.getChildFile("mixer.json").replaceWithText(json)|| + !stage.getChildFile("mixer.sha256").replaceWithText(checksum)) + return "Cannot write mixer document or checksum"; + for(const auto& state:states) { + const auto path=payload.getChildFile(state.sha256.toLowerCase()+".bin"); + if(!path.replaceWithData(state.bytes.getData(),state.bytes.getSize())|| + path.getSize()!=static_cast(state.bytes.getSize())|| + !juce::SHA256(path).toHexString().equalsIgnoreCase(state.sha256)) + return "Cannot durably stage verified vendor state"; + } + MixerSessionDocument reread; + std::vector copies; + if(readGeneration(stage,reread,copies).isNotEmpty()|| + Codec::encode(reread)!=json)return "Staged session readback changed"; + const auto committed=versions.getChildFile(id); + if(committed.exists()||!stage.moveFileTo(committed)) + return "Cannot publish immutable mixer generation"; + const auto head=root_.getChildFile("HEAD"); + if(head.existsAsFile()) { + const auto previous=readPointer(head); + if(previous.isEmpty())return "Current mixer HEAD invalid; recover explicitly"; + MixerSessionDocument older; + std::vector oldStates; + const auto error=readGeneration(versions.getChildFile(previous),older,oldStates); + if(error.isNotEmpty()) + return "Current mixer generation invalid; preserve it for recovery: "+error; + const auto backupError=writePointer(root_.getChildFile("PREVIOUS"),previous); + if(backupError.isNotEmpty())return backupError; + } + return writePointer(head,id); + } + + // A single portable JSON file, with content-addressed plug-in state. + static juce::String writeFile(const juce::File& file,MixerSessionDocument doc, + const std::vector& states) { + doc.resumeMain.reset(); + const auto json=Codec::encode(doc); + MixerSessionDocument verified; + if(!Codec::decode(json,verified))return "Cannot encode mixer file"; + auto root=juce::JSON::parse(json); + auto blobs=juce::var(new juce::DynamicObject()); + std::set hashes,referenced; + for(const auto& insert:doc.inserts)referenced.insert(insert.sha256); + juce::int64 total=0; + for(const auto& state:states) { + const auto size=static_cast(state.bytes.getSize()); + total+=size; + if(!safeHash(state.sha256)||!hashes.insert(state.sha256).second|| + size>maxState||total>maxTotal|| + juce::SHA256(state.bytes).toHexString()!=state.sha256) + return "Invalid mixer plug-in state"; + blobs.getDynamicObject()->setProperty(state.sha256, + juce::Base64::toBase64(state.bytes.getData(),state.bytes.getSize())); + } + if(hashes!=referenced||hashes.size()>maxStates) + return "Incomplete mixer plug-in state"; + root.getDynamicObject()->setProperty("pluginState",blobs); + juce::TemporaryFile staging(file); + if(!staging.getFile().replaceWithText(juce::JSON::toString(root,false)) || + !staging.overwriteTargetFileWithTemporary()) + return "Could not write mixer file"; + return {}; + } + + static juce::String readFile(const juce::File& file,MixerSessionDocument& out, + std::vector& states) { + constexpr auto maxFile=maxJson+(maxTotal*4/3)+maxStates*80; + const auto size=file.getSize(); + if(!file.hasFileExtension(".smix")||!file.existsAsFile()||size<1||size>maxFile) + return "Mixer file is missing, invalid or too large"; + juce::FileInputStream input(file); + juce::MemoryBlock contents; + if(!input.openedOk()||input.readIntoMemoryBlock(contents,maxFile+1)>maxFile) + return "Could not read mixer file"; + auto root=juce::JSON::parse(contents.toString()); + if(!root.isObject())return "Invalid mixer JSON"; + const auto blobs=root.getProperty("pluginState",{}); + if(!blobs.isObject())return "Mixer plug-in state is missing"; + root.getDynamicObject()->removeProperty("pluginState"); + root.getDynamicObject()->removeProperty("resumeMain"); + MixerSessionDocument doc; + if(!Codec::decode(juce::JSON::toString(root,false),doc)) + return "Invalid mixer session"; + std::set referenced; + for(const auto& insert:doc.inserts)referenced.insert(insert.sha256); + const auto& properties=blobs.getDynamicObject()->getProperties(); + if(referenced.size()>maxStates||static_cast(referenced.size())!=properties.size()) + return "Incomplete mixer plug-in state"; + std::vector verified; + juce::int64 total=0; + for(const auto& hash:referenced) { + const auto state=blobs.getProperty(hash,{}); + if(!safeHash(hash)||!state.isString()||state.toString().length()>((maxState+2)/3)*4) + return "Invalid mixer plug-in state"; + juce::MemoryOutputStream decoded; + if(!juce::Base64::convertFromBase64(decoded,state.toString())) + return "Invalid mixer plug-in state encoding"; + const auto bytes=static_cast(decoded.getDataSize()); + total+=bytes; + if(bytes>maxState||total>maxTotal||juce::SHA256(decoded.getMemoryBlock()).toHexString()!=hash) + return "Mixer plug-in state failed verification"; + verified.push_back({hash,decoded.getMemoryBlock()}); + } + out=std::move(doc); + states=std::move(verified); + return {}; + } + + // Read normal HEAD only: no silent fallback to an older performance. + juce::String load(MixerSessionDocument& out, + std::vector& states) const { + const auto pointer=readPointer(root_.getChildFile("HEAD")); + if(pointer.isEmpty())return "Mixer session HEAD missing or invalid"; + MixerSessionDocument doc; + std::vector binary; + const auto error=readGeneration(root_.getChildFile("versions").getChildFile(pointer), + doc,binary); + if(error.isNotEmpty())return error; + if(readPointer(root_.getChildFile("HEAD"))!=pointer) + return "Mixer HEAD changed during read"; + out=std::move(doc);states=std::move(binary); + return {}; + } + bool exists() const noexcept {return root_.getChildFile("HEAD").existsAsFile();} + // Recovery does NOT arm output or publish a graph. Valid HEAD wins. + juce::String recoverPrevious() const { + MixerSessionDocument current; + std::vector currentStates; + if(load(current,currentStates).isEmpty()) + return "Saved mixer generation is already verified"; + const auto pointer=readPointer(root_.getChildFile("PREVIOUS")); + if(pointer.isEmpty())return "Last-good mixer pointer missing"; + MixerSessionDocument verified; + std::vector binary; + const auto error=readGeneration(root_.getChildFile("versions").getChildFile(pointer), + verified,binary); + if(error.isNotEmpty())return "Previous mixer generation invalid: "+error; + return writePointer(root_.getChildFile("HEAD"),pointer); + } +private: + juce::File root_; + static bool safeHash(const juce::String& hash) { + return hash.length()==64 && hash.containsOnly("0123456789abcdef"); + } + static juce::String readPointer(const juce::File& file) { + if(!file.existsAsFile()||file.getSize()<1||file.getSize()>128)return {}; + const auto name=file.loadFileAsString().trim(); + return armix::shows::detail::uuid(name)?name:juce::String{}; + } + static juce::String writePointer(const juce::File& file,const juce::String& id) { + if(!armix::shows::detail::uuid(id))return "Invalid mixer generation pointer"; + juce::TemporaryFile staging(file); + auto output=staging.getFile().createOutputStream(); + if(!output||!output->writeText(id+"\n",false,false,"\n")) + return "Cannot stage mixer HEAD"; + output->flush(); + if(output->getStatus().failed())return "Cannot flush mixer HEAD"; + output.reset(); + return staging.overwriteTargetFileWithTemporary() + ?juce::String{}:juce::String("Cannot atomically publish mixer HEAD"); + } + static juce::String readGeneration(const juce::File& generation, + MixerSessionDocument& out, + std::vector& states) { + const auto jsonFile=generation.getChildFile("mixer.json"); + const auto sumFile=generation.getChildFile("mixer.sha256"); + if(!generation.isDirectory()||!jsonFile.existsAsFile()|| + jsonFile.getSize()<1||jsonFile.getSize()>maxJson|| + !sumFile.existsAsFile()||sumFile.getSize()!=64) + return "Mixer JSON generation missing/oversized"; + const auto text=jsonFile.loadFileAsString(); + const auto expected=sumFile.loadFileAsString().trim(); + if(!safeHash(expected)|| + juce::SHA256(text.toRawUTF8(),text.getNumBytesAsUTF8()).toHexString()!=expected) + return "Mixer document SHA mismatch"; + MixerSessionDocument doc; + if(!Codec::decode(text,doc)) + return "Mixer session semantic validation rejected"; + std::set hashes; + for(const auto& insert:doc.inserts)hashes.insert(insert.sha256); + if(hashes.size()>maxStates)return "Mixer vendor state reference count exceeded"; + std::vector binaries; + juce::int64 total=0; + for(const auto& hash:hashes) { + if(!safeHash(hash))return "Unsafe mixer state hash"; + const auto file=generation.getChildFile("blobs").getChildFile(hash+".bin"); + if(!file.existsAsFile()||file.getSize()<0||file.getSize()>maxState) + return "Mixer VST3 state missing or oversized"; + total+=file.getSize(); + if(total>maxTotal)return "Mixer vendor state budget exceeded"; + armix::shows::BinaryState blob; + blob.sha256=hash; + if(!file.loadFileAsData(blob.bytes)|| + juce::SHA256(blob.bytes).toHexString()!=hash) + return "Mixer vendor state changed on disk"; + binaries.push_back(std::move(blob)); + } + out=std::move(doc);states=std::move(binaries); + return {}; + } +}; +} // namespace armix::session diff --git a/src/NativeSessionToken.h b/src/NativeSessionToken.h new file mode 100644 index 000000000..0b5399739 --- /dev/null +++ b/src/NativeSessionToken.h @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include + +namespace armix::console { +// The WebView JSON bridge may encode an integral Number as JUCE double. +// Never reinterpret a fractional/NaN/oversized JavaScript value as a +// different device epoch or graph revision. This is CONTROL thread only. +inline std::uint64_t nativeSessionTokenValue(const juce::var& value) noexcept { + if(value.isInt() || value.isInt64()) { + const auto n=static_cast(value); + return n>0 ? static_cast(n) : 0; + } + if(value.isDouble()) { + const auto n=static_cast(value); + constexpr double maxExact=9007199254740991.0; // 2^53 - 1 + if(std::isfinite(n) && n>0. && n<=maxExact && + std::floor(n)==n) + return static_cast(n); + } + return 0; +} +inline bool nativeSessionTokenValid(const juce::var& supplied) noexcept { + return nativeSessionTokenValue(supplied)!=0; +} +inline bool nativeSessionTokenMatches(const juce::var& supplied, + const juce::var& producer) noexcept { + const auto accepted=nativeSessionTokenValue(producer); + return accepted!=0 && nativeSessionTokenValue(supplied)==accepted; +} +} // namespace armix::console diff --git a/src/NativeShowSaveWorker.h b/src/NativeShowSaveWorker.h index f568003d2..4465c5823 100644 --- a/src/NativeShowSaveWorker.h +++ b/src/NativeShowSaveWorker.h @@ -16,10 +16,11 @@ namespace armix::shows { class NativeShowSaveWorker final : private juce::Thread { public: - enum class Operation { save, list, read }; + enum class Operation { save, list, read, recover }; struct Summary { juce::String id,name; juce::int64 modifiedMs=0; + bool needsRecovery=false,hasPrevious=false; }; struct Result { Operation operation=Operation::save; @@ -42,14 +43,17 @@ class NativeShowSaveWorker final : private juce::Thread { std::move(completion)); } bool launch(juce::File studio,SnapshotV2 snapshot, - std::vector binaryStates,Completion completion) { + std::vector binaryStates,Completion completion, + juce::String updateShowId={}) { // Reject invalid requests BEFORE reserving or retaining a potentially // large vendor-state payload on this long-lived worker. if(!detail::uuid(snapshot.id) || + (updateShowId.isNotEmpty()&&!detail::uuid(updateShowId)) || !reserve(Operation::save,std::move(studio),std::move(completion))) return false; snapshot_=std::move(snapshot); blobs_=std::move(binaryStates); + updateShowId_=std::move(updateShowId); return startOrRelease(); } bool list(juce::File studio,Completion completion) { @@ -57,6 +61,14 @@ class NativeShowSaveWorker final : private juce::Thread { return false; return startOrRelease(); } + // Explicit recovery runs only on this serialized storage worker. + bool recover(juce::File studio,juce::String showId,Completion completion) { + if(!detail::uuid(showId)|| + !reserve(Operation::recover,std::move(studio),std::move(completion))) + return false; + requestedId_=std::move(showId); + return startOrRelease(); + } bool read(juce::File studio,juce::String showId, juce::int64 epoch,juce::int64 revision,Completion completion) { if(!detail::uuid(showId)||epoch<=0||revision<=0 || @@ -81,6 +93,7 @@ class NativeShowSaveWorker final : private juce::Thread { blobs_.clear(); blobs_.shrink_to_fit(); requestedId_={}; + updateShowId_={}; requestEpoch_=0;requestRevision_=0; studio_={}; finished_={}; @@ -99,7 +112,8 @@ class NativeShowSaveWorker final : private juce::Thread { try { NativeShowStore store(studio_); if(operation_==Operation::save)save(store,result); - else if(operation_==Operation::list)listShows(result); + else if(operation_==Operation::list)listShows(store,result); + else if(operation_==Operation::recover)recoverShow(store,result); else readShow(store,result); } catch(const std::exception& e) { result.error="Native Show IO exception: "+juce::String(e.what()); @@ -122,15 +136,27 @@ class NativeShowSaveWorker final : private juce::Thread { } void save(NativeShowStore& store,Result& result) { result.snapshotId=snapshot_.id; - result.name=snapshot_.name; ShowV2 show; - show.id=juce::Uuid().toDashedString().toLowerCase(); - show.name=snapshot_.name; - show.createdMs=snapshot_.createdMs; - show.modifiedMs=snapshot_.modifiedMs; + if(updateShowId_.isNotEmpty()) { + // Verify every byte of the existing Show before introducing a + // replacement generation. Never overwrite damaged or stale work. + std::vector verifiedOld; + result.error=store.load(updateShowId_,show,verifiedOld); + if(result.error.isNotEmpty())return; + // The old snapshot remains immutable in PREVIOUS; only the + // current head gets the new accepted performance snapshot. + show.snapshotOrder.clear(); + show.modifiedMs=juce::jmax(show.modifiedMs+1,snapshot_.modifiedMs); + } else { + show.id=juce::Uuid().toDashedString().toLowerCase(); + show.name=snapshot_.name; + show.createdMs=snapshot_.createdMs; + show.modifiedMs=snapshot_.modifiedMs; + } show.currentSnapshotId=snapshot_.id; show.snapshotOrder.push_back(snapshot_.id); result.showId=show.id; + result.name=show.name; result.error=store.commit(show,{snapshot_},blobs_); if(result.error.isNotEmpty())return; ShowV2 verified; @@ -144,7 +170,7 @@ class NativeShowSaveWorker final : private juce::Thread { } // Lightweight bounded metadata listing. Full data+SHA verification is // performed again by NativeShowStore::load before any recall can apply. - void listShows(Result& result) { + void listShows(NativeShowStore& store,Result& result) { const auto root=studio_.getChildFile("Shows"); if(!root.isDirectory())return; juce::DirectoryIterator iter(root,false,"*",juce::File::findDirectories); @@ -157,17 +183,26 @@ class NativeShowSaveWorker final : private juce::Thread { const auto folder=iter.getFile(); const auto id=folder.getFileName(); if(!detail::uuid(id))continue; + const bool hasPrevious=folder.getChildFile("PREVIOUS").existsAsFile(); const auto head=folder.getChildFile("HEAD"); - if(!head.existsAsFile()||head.getSize()>128)continue; - const auto version=head.loadFileAsString().trim(); - if(!detail::uuid(version))continue; - const auto meta=folder.getChildFile("versions") - .getChildFile(version).getChildFile("show.json"); - if(!meta.existsAsFile()||meta.getSize()>maxJsonBytes)continue; + juce::String version; + if(head.existsAsFile()&&head.getSize()>0&&head.getSize()<=128) + version=head.loadFileAsString().trim(); + const auto meta=detail::uuid(version) + ?folder.getChildFile("versions").getChildFile(version).getChildFile("show.json") + :juce::File{}; ShowV2 show; - if(!Codec::decode(meta.loadFileAsString(),show) || - !show.id.equalsIgnoreCase(id)||show.snapshotOrder.empty())continue; - result.items.push_back({show.id,show.name,show.modifiedMs}); + if(meta.existsAsFile()&&meta.getSize()>0&&meta.getSize()<=maxJsonBytes&& + Codec::decode(meta.loadFileAsString(),show)&& + show.id.equalsIgnoreCase(id)&&!show.snapshotOrder.empty()) { + result.items.push_back({show.id,show.name,show.modifiedMs,false,hasPrevious}); + } else if(hasPrevious) { + // A damaged HEAD must not make a verified prior Show invisible. + std::vector verified; + if(store.loadPrevious(id,show,verified).isEmpty() && + !show.snapshotOrder.empty()) + result.items.push_back({show.id,show.name,show.modifiedMs,true,true}); + } } std::sort(result.items.begin(),result.items.end(), [](const Summary& a,const Summary& b) { @@ -176,6 +211,15 @@ class NativeShowSaveWorker final : private juce::Thread { }); if(result.items.size()>64)result.items.resize(64); } + void recoverShow(NativeShowStore& store,Result& result) { + result.showId=requestedId_; + result.error=store.recoverPrevious(requestedId_); + if(result.error.isNotEmpty())return; + ShowV2 verified; + std::vector checked; + result.error=store.load(requestedId_,verified,checked); + if(result.error.isEmpty())result.name=verified.name; + } void readShow(NativeShowStore& store,Result& result) { result.showId=requestedId_; ShowV2 show; @@ -200,6 +244,7 @@ class NativeShowSaveWorker final : private juce::Thread { SnapshotV2 snapshot_; std::vector blobs_; // captured on CONTROL, hashed/written on IO worker juce::String requestedId_; + juce::String updateShowId_; // target of an EXPLICIT user version save juce::int64 requestEpoch_=0,requestRevision_=0; Completion finished_; std::shared_ptr> alive_= diff --git a/src/NativeShowStore.h b/src/NativeShowStore.h index 626069892..494d1dd39 100644 --- a/src/NativeShowStore.h +++ b/src/NativeShowStore.h @@ -112,21 +112,80 @@ class NativeShowStore final { const auto committed=versions.getChildFile(generation); if(committed.exists()||!stage.moveFileTo(committed)) return "Unable to publish immutable generation directory"; + // Promote the former verified HEAD into a separate durable recovery + // pointer BEFORE replacing HEAD. If power is lost at any boundary, + // the old HEAD still works or an explicit recovery candidate survives. + // PREVIOUS never changes the active Show automatically. + const auto head=showRoot.getChildFile("HEAD"); + if(head.existsAsFile()) { + if(head.getSize()<1 || head.getSize()>128) + return "Existing Show HEAD invalid: refuse to discard recovery history"; + const auto previousId=head.loadFileAsString().trim(); + if(!detail::uuid(previousId)) + return "Existing Show HEAD invalid: refuse to discard recovery history"; + ShowV2 priorShow; + std::vector priorSnapshots; + const auto priorError=readFolder( + versions.getChildFile(previousId),priorShow,priorSnapshots); + if(priorError.isNotEmpty() || !priorShow.id.equalsIgnoreCase(show.id)) + return "Existing Show generation invalid: recover explicitly before overwrite"; + const auto backupError=writePointer(showRoot.getChildFile("PREVIOUS"),previousId); + if(backupError.isNotEmpty())return "Cannot preserve prior Show HEAD: "+backupError; + } // A failed HEAD write leaves previous generation intact; a new version // may remain orphaned but will never be loaded without its HEAD. - juce::TemporaryFile temp(showRoot.getChildFile("HEAD")); - auto stream=temp.getFile().createOutputStream(); - if(!stream) return "Cannot open temporary Show pointer"; - if(!stream->writeText(generation+"\n",false,false,"\n")) - return "Cannot write temporary Show pointer"; - stream->flush(); - if(stream->getStatus().failed())return "Failed to flush Show pointer"; - stream.reset(); - if(!temp.overwriteTargetFileWithTemporary()) - return "Cannot atomically commit Show pointer"; + return writePointer(head,generation); + } + + // Read-only last-known-good inspection. Verify the complete previous + // generation, including each vendor blob, before exposing its metadata. + // A corrupt HEAD must never force recovery or change the accepted graph. + juce::String loadPrevious(const juce::String& requestedId,ShowV2& show, + std::vector& snapshots, + juce::String* generation=nullptr) const { + if(!detail::uuid(requestedId))return "Invalid Show ID"; + const auto dir=root_.getChildFile(requestedId.toLowerCase()); + const auto pointer=dir.getChildFile("PREVIOUS"); + if(!pointer.existsAsFile()||pointer.getSize()<1||pointer.getSize()>128) + return "Previous Show generation missing"; + const auto id=pointer.loadFileAsString().trim(); + if(!detail::uuid(id))return "Unsafe previous Show pointer"; + ShowV2 candidate; + std::vector items; + const auto error=readFolder(dir.getChildFile("versions").getChildFile(id), + candidate,items); + if(error.isNotEmpty())return "Previous Show cannot be verified: "+error; + if(!candidate.id.equalsIgnoreCase(requestedId)) + return "Previous Show identity mismatch"; + show=std::move(candidate); + snapshots=std::move(items); + if(generation)*generation=id; return {}; } + // Explicit operator-directed disaster recovery. NEVER silently substitute + // PREVIOUS on normal load: that would turn a corrupted latest performance + // into an apparently successful, but stale, recalled Show. + // Verify the entire old generation including FX hashes BEFORE switching. + // After success, existing loadWithStates() can restore every verified blob. + juce::String recoverPrevious(const juce::String& requestedId) const { + if(!detail::uuid(requestedId))return "Invalid Show ID"; + // A valid current performance must never be overwritten with an + // older one merely because a recovery pointer exists. + ShowV2 current; + std::vector currentSnapshots; + if(load(requestedId,current,currentSnapshots).isEmpty()) + return "Current Show is verified: refusing to overwrite working performance"; + juce::String priorId; + ShowV2 recovered; + std::vector snapshots; + const auto error=loadPrevious(requestedId,recovered,snapshots,&priorId); + if(error.isNotEmpty())return error; + // Pointer repair is an explicit IO transaction, never PCM publication. + return writePointer(root_.getChildFile(requestedId.toLowerCase()) + .getChildFile("HEAD"),priorId); + } + // Read-and-verify entire generation before changing either output value. juce::String load(const juce::String& requestedId,ShowV2& show, std::vector& snapshots) const { @@ -198,6 +257,20 @@ class NativeShowStore final { } private: juce::File root_; + static juce::String writePointer(const juce::File& target,const juce::String& id) { + if(!detail::uuid(id))return "Unsafe Show generation pointer"; + juce::TemporaryFile temp(target); + auto output=temp.getFile().createOutputStream(); + if(!output)return "Cannot open temporary Show pointer"; + if(!output->writeText(id+"\n",false,false,"\n")) + return "Cannot write temporary Show pointer"; + output->flush(); + if(output->getStatus().failed())return "Failed to flush Show pointer"; + output.reset(); + if(!temp.overwriteTargetFileWithTemporary()) + return "Cannot atomically replace Show pointer"; + return {}; + } static bool validHash(const juce::String& s) { if(s.length()!=64) return false; for(const auto ch:s.toStdString()) diff --git a/src/NativeTopologyEditSafety.h b/src/NativeTopologyEditSafety.h new file mode 100644 index 000000000..3e0acfaee --- /dev/null +++ b/src/NativeTopologyEditSafety.h @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +// P0 First Sound: CONTROL-thread source/OUT transaction policy. +// No realtime callback, locks, dynamic allocation or new DSP ownership. +namespace armix::mixer { +struct NativeTopologyEditSafety final { + struct MixSnapshot final { + float linear=1.f, pan=0.f; + bool mute=false, solo=false; + }; + // Before replacing an admitted ChannelId graph, copy its ACTUAL live + // fader/pan/mute/solo into the next M4 topology. A native gesture must + // never silently revert to an earlier fallback mixer value. + static constexpr MixSnapshot preserveAcceptedMix( + MixSnapshot legacy,MixSnapshot native,bool channelIdOwnsPcm) noexcept { + return channelIdOwnsPcm?native:legacy; + } + static constexpr bool structuralSource(bool hasAcceptedRoute, + bool sameFormat) noexcept { + return !hasAcceptedRoute || !sameFormat; + } + static constexpr bool mayEdit(bool structural, bool streamArmed) noexcept { + // An atomic physical pin switch does not replace a PCM graph. + return !structural || !streamArmed; + } + static constexpr bool mayRestoreMonitor(bool previouslyArmed, + bool sameDeviceEpoch, + bool outputArmSafe, + bool streamArmed) noexcept { + return previouslyArmed && sameDeviceEpoch && outputArmSafe && !streamArmed; + } +}; +} // namespace armix::mixer diff --git a/src/NativeVerifiedSourcePatch.h b/src/NativeVerifiedSourcePatch.h index ca9927d87..b92bd5c80 100644 --- a/src/NativeVerifiedSourcePatch.h +++ b/src/NativeVerifiedSourcePatch.h @@ -23,9 +23,12 @@ struct NativeVerifiedSourcePatch final { actualRevision>static_cast(std::numeric_limits::max()) || !accepted.isObject() || channel<0 || channel>=10) return "SOURCE: stale device epoch or invalid native channel"; - if(mode!="MONO"&&mode!="STEREO") - return "SOURCE: MONO or STEREO mode required"; - if(physicalLeft<0 || enabledPhysicalPorts.empty()) + if(mode!="NONE"&&mode!="MONO"&&mode!="STEREO") + return "SOURCE: NONE, MONO or STEREO mode required"; + const bool clearing=mode=="NONE"; + if(clearing && (physicalLeft!=-1||physicalRight!=-1)) + return "SOURCE: clearing input cannot supply physical pins"; + if(!clearing && (physicalLeft<0 || enabledPhysicalPorts.empty())) return "SOURCE: select an enabled physical capture pin"; if(static_cast(accepted.getProperty("deviceEpoch",juce::var(-1))) != static_cast(actualEpoch)) @@ -35,8 +38,8 @@ struct NativeVerifiedSourcePatch final { if(port==physicalLeft)validLeft=true; if(port==physicalRight)validRight=true; } - if(!validLeft || (mode=="STEREO" && - (!validRight || physicalLeft==physicalRight))) + if(!clearing && (!validLeft || (mode=="STEREO" && + (!validRight || physicalLeft==physicalRight)))) return "SOURCE: STEREO requires two distinct active physical pins; MONO accepts one"; // JUCE var assignment shares the underlying DynamicObject. Deep // clone before touching a row, or failed prepare would silently @@ -62,11 +65,11 @@ struct NativeVerifiedSourcePatch final { const auto width=row->getProperty("channelFormat").toString(); if(width!="MONO" && width!="STEREO") return "SOURCE: native processing format missing or invalid"; - row->setProperty("sourceKind","PHYSICAL"); + row->setProperty("sourceKind",clearing?"NONE":"PHYSICAL"); row->setProperty("sourceFormat",mode); } row->setProperty("mode",mode); - row->setProperty("left",physicalLeft); + row->setProperty("left",clearing?-1:physicalLeft); row->setProperty("right",mode=="STEREO"?physicalRight:-1); // The existing M4 producer handles revision/epoch publication and // fails back to its prior accepted graph on any bad plugin/routing. diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py new file mode 100644 index 000000000..1c02fbcbb --- /dev/null +++ b/tests/approved_native_cold_start_smoke.py @@ -0,0 +1,269 @@ +"""Real compiled DOM from G0: first drag without OUT priming, first native +FX picker insert on original CH with structural=false, then vendor editor. +Backend isolation is emulated; actual latency/sample evidence is CTest. +""" +import copy +import importlib.util +import json +from pathlib import Path +import tempfile +from playwright.sync_api import sync_playwright +from approved_native_wire_gain_smoke import snapshot, emit, ack, SOURCE, RECEIVER + +ROOT = Path(__file__).resolve().parents[1] + + +def drag(page, source, destination): + a = page.locator(f'#tracks .strip[data-id="{source}"] .wire-node-out').bounding_box() + b = page.locator(f'#tracks .strip[data-id="{destination}"] .wire-node-in').bounding_box() + assert a and b + page.mouse.move(a['x'] + a['width']/2, a['y'] + a['height']/2) + page.mouse.down() + page.mouse.move(b['x'] + b['width']/2, b['y'] + b['height']/2, steps=12) + page.mouse.up() + + +def main(): + spec = importlib.util.spec_from_file_location('bundle', ROOT/'scripts/build_approved_native_gui.py') + bundle = importlib.util.module_from_spec(spec) + spec.loader.exec_module(bundle) + with tempfile.TemporaryDirectory() as directory, sync_playwright() as p: + out = Path(directory) + bundle.stage(out) + browser = p.chromium.launch() + for width, height in [(1366,768),(1680,900),(1920,1080)]: + page = browser.new_page(viewport={'width':width,'height':height}) + errors=[] + page.on('pageerror', lambda e:errors.append(str(e))) + page.add_init_script("""window.__nativeListeners=new Map();window.__events=[];window.__nativeIntents=[]; + window.__JUCE__={backend:{emitEvent(name,payload){window.__events.push({name,payload}); + if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload);}, + addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") + page.goto((out/'index.html').as_uri()) + page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__?.enabled') + g0=json.loads((ROOT/'integration/console-v6/fixtures.json').read_text())['g0'] + g0['mixerSession']={'authority':'NONE','deviceEpoch':g0['device']['epoch'],'channels':[]} + g0['legacyM4']={'active':True,'routeAccepted':False,'routingRevision':'1'} + emit(page,'arMixConsoleSnapshot',g0) + # Native-only Studio controls must use real JUCE Show I/O; the + # public Pages scene model must never acknowledge a persisted Show. + show_panel = "#moreTools .more-tools-panel" + show_id = "11111111-2222-4333-8444-555555555555" + corrupt_id = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee" + def show_click(text): + page.evaluate("""([selector,text])=>{ + const buttons=[...document.querySelectorAll(selector+' button')]; + const button=buttons.find(b=>b.textContent===text); + if(!button)throw Error('Missing native Show button: '+text); + button.click(); + }""",[show_panel,text]) + def show_select(value): + return page.evaluate("""([selector,value])=>{ + const node=document.querySelector(selector+' select[aria-label="Saved native Show"]'); + if(!node)throw Error('Native Show selector absent'); + node.value=value;node.dispatchEvent(new Event('change')); + const buttons=[...document.querySelectorAll(selector+' button')]; + const available=name=>buttons.find(b=>b.textContent===name)?.disabled===false; + return {recall:available('Recall Show'),recover:available('Recover Last Good')}; + }""",[show_panel,value]) + toolbar=page.locator(".command-bar") + for caption,icon in [("Save","mixer-save.svg"),("Open","mixer-open.svg")]: + button=toolbar.get_by_role("button",name=caption,exact=True) + assert button.locator("img").get_attribute("src")=="assets/"+icon + assert button.locator("img").evaluate("el=>el.complete && el.naturalWidth>0") + button.click() + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="nativeMixerFile"+caption + for name in ["Save Mixer Session","Restore Saved Mixer", + "Rebind Current Device…","Recover Previous Mixer"]: + assert page.get_by_role("button",name=name,exact=True).count()==0 + emit(page,"arMixNativeSessionAck",{"operation":"OPEN","ok":False,"error":"Invalid mixer JSON"}) + assert page.get_by_text("Invalid mixer JSON",exact=True).count()>=1 + assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='monitor')") + show_click("Browse Shows") + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" + emit(page,"arMixNativeShowListAck",{"ok":True,"items":[ + {"id":show_id,"name":"Valid Performance","hasPrevious":True,"needsRecovery":False}, + {"id":corrupt_id,"name":"Damaged HEAD","hasPrevious":True,"needsRecovery":True}]}) + assert show_select(show_id)=={"recall":True,"recover":True} + assert show_select(corrupt_id)=={"recall":False,"recover":True} + show_click("Recover Last Good") + recovery=page.evaluate("()=>window.__events.at(-1).payload") + assert recovery=={"action":"routingDryShowRecover","value":corrupt_id} + assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='monitor')") + emit(page,"arMixNativeShowRecoverAck",{"ok":True,"showId":corrupt_id}) + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" + emit(page,"arMixNativeShowListAck",{"ok":True,"items":[ + {"id":corrupt_id,"name":"Recovered Performance","hasPrevious":True,"needsRecovery":False}]}) + assert show_select(corrupt_id)["recall"] is True + show_click("Recall Show") + recalled=page.evaluate("()=>window.__events.at(-1).payload") + assert recalled=={"action":"routingDryShowRecall","value":corrupt_id} + emit(page,"arMixNativeShowRecallAck",{"ok":False,"error":"DEVICE_REBIND_REQUIRED"}) + assert "DEVICE_REBIND_REQUIRED" in page.locator(show_panel).text_content() + show_click("Save New Version") + assert page.evaluate("()=>window.__events.at(-1).payload")=={ + "action":"routingDryShowSave","value":corrupt_id} + emit(page,"arMixNativeShowSaveAck",{"ok":True,"showId":corrupt_id}) + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" + emit(page,"arMixNativeShowListAck",{"ok":True,"items":[ + {"id":corrupt_id,"name":"Recovered Performance","hasPrevious":True,"needsRecovery":False}]}) + show_click("Save Show") + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowSave" + emit(page,"arMixNativeShowSaveAck",{"ok":True,"showId":show_id}) + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" + emit(page,"arMixNativeShowListAck",{"ok":True,"items":[]}) + assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='monitor')") + if 'collapsed-send' in (page.locator('.console-body').get_attribute('class') or ''): + page.locator('.section-rail [data-section="send"]').click() + # Release before bootstrap SOURCE's later native readback arrives. + drag(page,1,2) + assert not page.evaluate('()=>window.__nativeIntents.length') + state=snapshot() + state['graph']['edges'].pop(1) # genuinely no existing channel send + state['graph']['capabilities']['supportedOps'] += ['LOAD_INSERT'] + for ident, role, name in [('101','GROUP','Vocal Group'), + ('102','FX_RETURN','Reverb Return')]: + state['graph']['channels'].insert(-1, { + 'id':ident,'role':role,'name':name,'processingFormat':'STEREO', + 'controls':{'faderDb':-5,'pan':0,'mute':False,'solo':False}, + 'inserts':[],'sends':[]}) + state['graph']['destinations'].append({'id':ident,'role':role,'name':name}) + state['legacyM4']={'active':True,'routeAccepted':True,'routingRevision':'77', + 'nativeBusStructural':False,'fxInstances':[[] for _ in range(14)]} + emit(page,'arMixConsoleSnapshot',state) + page.wait_for_function('()=>window.__nativeIntents.length===1') + route=page.evaluate('()=>window.__nativeIntents[0]') + assert route['operation']=='APPLY_WIRE_TRANSACTION' + assert route['payload']['changes'][0]['from']==SOURCE + assert route['payload']['changes'][0]['to']==RECEIVER + assert route['payload']['changes'][0]['op']=='CONNECT' + # Source admission can advance after the GUI's last readback. + # Reject once as stale, independently refresh, then rebase only + # the same explicit connection with a new request ID. + emit(page,'arMixConsoleAck',{'requestId':route['requestId'],'status':'REJECTED', + 'errorCode':'STALE_NATIVE_CONTROL_REVISION','deviceEpoch':state['device']['epoch'], + 'graphRevision':'3','rosterRevision':'3'}) + state['graph'].update(revision='3',rosterRevision='3') + emit(page,'arMixConsoleSnapshot',state) + page.wait_for_function('()=>window.__nativeIntents.length===2') + retry=page.evaluate('()=>window.__nativeIntents.at(-1)') + assert retry['baseGraphRevision']=='3' and retry['requestId']!=route['requestId'] + assert retry['payload']==route['payload'] + route=retry + state['graph'].update(revision='4',rosterRevision='4') + state['graph']['edges'].append({'edgeId':'9223372036854775810','from':SOURCE,'to':RECEIVER, + 'primaryOutput':False,'enabled':True,'gainLinear':1,'tap':'POST_FADER','signalKind':'AUDIO'}) + state['mixerSession'].update(routeRevision='4',rosterRevision='4',channels=copy.deepcopy(state['graph']['channels'])) + ack(page,state,route) + emit(page,'arMixConsoleSnapshot',state) + page.wait_for_function('()=>!window.__ARMIX_NATIVE_M2__.state().pending') + # First FX on original CH: native authority even when the legacy + # structural marker is false and its independent revision is 77. + emit(page,'arMixCatalog',{'items':[{'id':'test-vst-64','name':'Latency VST','vendor':'Fixture', + 'category':'EQ','favorite':True}],'scanning':False}) + page.locator('#tracks .strip[data-id="1"] .fx-section [data-action="openPlugin"]').first.click() + page.locator('#fastPicker [data-fast-id="test-vst-64"]').click() + page.wait_for_function('()=>window.__nativeIntents.length===3') + fx=page.evaluate('()=>window.__nativeIntents.at(-1)') + assert fx['operation']=='LOAD_INSERT' and fx['baseGraphRevision']=='4' + assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='routingFxInsert')") + state['graph'].update(revision='5',rosterRevision='5') + state['graph']['channels'][0]['inserts']=[{'id':'g5c-actual','catalogId':'test-vst-64', + 'name':'Latency VST','bypassed':False,'latencySamples':64}] + state['mixerSession'].update(routeRevision='5',rosterRevision='5',channels=copy.deepcopy(state['graph']['channels'])) + ack(page,state,fx) + emit(page,'arMixConsoleSnapshot',state) + page.wait_for_function("()=>document.getElementById('fastPicker').hidden") + emit(page,'arMixCatalog',{'items':[{'id':'test-vst-64','name':'Latency VST','vendor':'Fixture', + 'category':'EQ','favorite':True}],'scanning':False}) + assert page.locator('#tracks .strip[data-id="1"] .fx-section [data-action="openPlugin"]').first.inner_text()=='Latency VST', 'catalog refresh overwrote the accepted native rack' + + page.locator('#tracks .strip[data-id="1"] .fx-section [data-action="openPlugin"]').first.click() + editor=page.evaluate("()=>window.__events.filter(e=>e.payload?.action==='routingFxEditor').at(-1)?.payload") + assert editor and editor['channelId']==SOURCE and editor['instanceId']=='g5c-actual' + assert editor['revision']=='5' and 'channel' not in editor + # A new device epoch publishes the same document without a + # callback, port assignment, meter evidence or write capability. + retained=copy.deepcopy(state) + retained['device'].update(epoch='92',outputArmed=False,sampleRate=0, + bufferFrames=0,inputEndpoints=[],outputEndpoints=[], + enabledInputs=[],enabledOutputs=[]) + retained['graph']['bindingState']='NEEDS_REMAP' + retained['graph']['capabilities'].update(callbackOwnsChannelIds=False,supportedOps=[]) + retained['graph']['channels'][0]['source']={ + 'bindingState':'NEEDS_REMAP','sourceFormat':'MONO'} + retained['telemetry']['channelMeterRmsPeak']={} + retained['legacyM4']={'active':False,'routeAccepted':False,'routingRevision':'0'} + retained['mixerSession'].update(deviceEpoch='92',bindingState='NEEDS_REMAP', + channels=copy.deepcopy(retained['graph']['channels'])) + emit(page,'arMixConsoleSnapshot',retained) + page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__.state().current?.retained') + assert page.locator('.status-bar .warning').inner_text().startswith('NEEDS REMAP') + assert page.locator('[data-native-monitor]').is_disabled() + assert page.locator('#tracks .strip').count()==4 + assert 'OUT NEEDS REMAP' in page.locator('#transport').inner_text() + page.locator('#tracks .strip[data-id="1"] .wire-node-out').click() + emit(page,'arMixConsoleSnapshot',retained) + assert page.locator('#tracks .strip[data-id="2"] .wire-gain').is_disabled() + strip=page.locator('#tracks .strip[data-id="1"]') + assert strip.locator('select[data-field="input"]').input_value()=='NEEDS REMAP' + assert strip.locator('.fx-section [data-action="openPlugin"]').first.inner_text()=='Latency VST' + before=page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="routingFxEditor").length') + strip.locator('.fx-section [data-action="openPlugin"]').first.click() + assert page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="routingFxEditor").length')==before + assert page.evaluate('()=>window.__nativeIntents.length')==3 + # Late readback from the disconnected epoch cannot re-admit audio. + emit(page,'arMixConsoleSnapshot',state) + assert page.evaluate('()=>window.__ARMIX_NATIVE_M2__.state().current.retained') + # A new WASAPI pair is inspected before exposing a separate, + # explicit confirmation for the retained numbered pin mapping. + page.locator('[data-native-io]').click() + backend='Windows Audio' + active={'backend':backend,'captureDevice':'New Capture','playbackDevice':'New Playback', + 'open':True,'authorized':True,'deviceGeneration':12,'rate':48000,'buffer':256, + 'inputNames':['Input 1'],'outputNames':['Output 1','Output 2'], + 'enabledInputs':[0],'enabledOutputs':[0,1],'rates':[48000],'buffers':[256]} + emit(page,'arMixAudioDeviceInventory',{'active':active,'types':[ + {'name':backend,'inputs':['New Capture'],'outputs':['New Playback'],'separate':True}]}) + remap=page.locator('[data-audio-remap]') + assert remap.is_hidden() + page.locator('[data-audio-apply]').click() + read_apply='()=>window.__events.filter(e=>e.payload?.action==="audioDeviceApply").at(-1).payload' + opened=page.evaluate(read_apply) + assert 'confirmRetainedPinMapping' not in opened['config'] + emit(page,'arMixAudioDeviceApplyAck',{'requestId':'old','state':'NEEDS_REMAP', + 'active':active,'canReusePins':True}) + assert remap.is_hidden() + emit(page,'arMixAudioDeviceApplyAck',{'requestId':opened['requestId'],'state':'NEEDS_REMAP', + 'active':active,'canReusePins':True}) + remap.click() + binding=page.evaluate(read_apply) + assert binding['config']['confirmRetainedPinMapping'] is True + assert binding['expectedDeviceGeneration']==12 + assert binding['config']['captureDevice']=='New Capture' + assert binding['config']['playbackDevice']=='New Playback' + assert binding['config']['sampleRate']==48000 and binding['config']['bufferSize']==256 + emit(page,'arMixAudioDeviceApplyAck',{'requestId':binding['requestId'],'ok':True, + 'state':'ACCEPTED_MUTED','active':active,'mixerBound':True}) + assert page.locator('.armix-audio-shade').is_hidden() + rebound=copy.deepcopy(state) + rebound['device'].update(epoch='93',outputArmed=False) + rebound['graph']['revision']='6' + rebound['mixerSession'].update(deviceEpoch='93',routeRevision='6') + monitor_events=page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="monitor").length') + emit(page,'arMixConsoleSnapshot',rebound) + page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__.state().current?.admitted') + assert page.locator('[data-native-monitor]').is_enabled() + assert page.locator('[data-native-monitor]').get_attribute('data-armed')=='false' + assert page.locator('#tracks .strip').count()==4 + assert strip.locator('.fx-section [data-action="openPlugin"]').first.inner_text()=='Latency VST' + assert page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="monitor").length')==monitor_events + assert not errors, errors + page.screenshot(path=f'native-cold-start-{width}.png') + page.close() + browser.close() + print('PASS G0 first drag without OUT priming; original-channel FX/editor; retained GROUP/FX/WIRE and disarm; 3 sizes (UI isolation)') + + +if __name__=='__main__': + main() diff --git a/tests/approved_native_fx_edit_smoke.py b/tests/approved_native_fx_edit_smoke.py new file mode 100644 index 000000000..ebe470efd --- /dev/null +++ b/tests/approved_native_fx_edit_smoke.py @@ -0,0 +1,101 @@ +"""Compiled native pointer ghost -> MOVE/REMOVE intent -> ACK/readback. +Real PCM/order/lease lifetime are covered separately by native CTest. +""" +import copy +import importlib.util +from pathlib import Path +import tempfile +from playwright.sync_api import sync_playwright +from approved_native_wire_gain_smoke import snapshot,emit,ack,SOURCE,RECEIVER +ROOT=Path(__file__).resolve().parents[1] + +def main(): + spec=importlib.util.spec_from_file_location('bundle',ROOT/'scripts/build_approved_native_gui.py') + bundle=importlib.util.module_from_spec(spec);spec.loader.exec_module(bundle) + with tempfile.TemporaryDirectory() as directory,sync_playwright() as p: + out=Path(directory);bundle.stage(out);browser=p.chromium.launch() + for width,height in [(1366,768),(1680,900),(1920,1080)]: + page=browser.new_page(viewport={'width':width,'height':height});errors=[] + page.on('pageerror',lambda e:errors.append(str(e))) + page.add_init_script("""window.__nativeListeners=new Map();window.__nativeIntents=[];window.__actions=[]; + window.__JUCE__={backend:{emitEvent(name,payload){ + if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload); + if(name==='arMixAction')window.__actions.push(payload);}, + addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") + page.goto((out/'index.html').as_uri());page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__?.enabled') + state=snapshot();state['graph']['capabilities']['supportedOps']+=['MOVE_INSERT','REMOVE_INSERT'] + state['graph']['channels'][0]['inserts']=[ + {'id':'actual-a','catalogId':'a','name':'ArSonEQ','bypassed':False}, + {'id':'actual-b','catalogId':'b','name':'ArSonKuPik','bypassed':True}] + emit(page,'arMixConsoleSnapshot',state) + def row(channel,slot):return page.locator(f'#tracks .strip[data-id="{channel}"] .fxslot-row[data-slot="{slot}"]') + def move(source,slot,destination,target_slot,after=False): + surface=row(source,slot).locator('.fx-pick').bounding_box();target=row(destination,target_slot).bounding_box() + assert surface and target + page.mouse.move(surface['x']+surface['width']/2,surface['y']+surface['height']/2);page.mouse.down() + x=target['x']+target['width']/2;y=target['y']+target['height']*(.8 if after else .2) + page.mouse.move(x,y,steps=10);page.wait_for_timeout(60) + ghost=page.locator('.fx-drag-ghost');assert ghost.count()==1 + bounds=ghost.bounding_box();assert bounds and abs(bounds['x']-x)<220 + page.mouse.move(x+18,y+2,steps=3);page.wait_for_timeout(30) + moved=ghost.bounding_box();assert moved and abs(moved['x']-bounds['x']-18)<2 + assert page.locator('.fx-drop-marker:visible').count()==1 + page.mouse.move(x,y);page.mouse.up();assert ghost.count()==0 + return page.evaluate('()=>window.__nativeIntents.at(-1)') + def accept(request): + n=str(int(state['graph']['revision'])+1) + state['graph'].update(revision=n,rosterRevision=n) + state['mixerSession'].update(routeRevision=n,rosterRevision=n,channels=copy.deepcopy(state['graph']['channels'])) + ack(page,state,request);emit(page,'arMixConsoleSnapshot',state) + page.wait_for_function('()=>!window.__ARMIX_NATIVE_M2__.state().pending') + # Escape cancels presentation without committing an audio edit. + assert page.locator('.fx-grip').count()==0,'retired handle must never appear' + surface=row(1,0).locator('.fx-pick').bounding_box();assert surface + page.mouse.move(surface['x']+5,surface['y']+5);page.mouse.down();page.mouse.move(450,50,steps=10) + page.wait_for_timeout(40);assert page.locator('.fx-drag-ghost').count()==1 + page.keyboard.press('Escape');page.mouse.up() + assert page.locator('.fx-drag-ghost').count()==0 + assert page.evaluate('()=>window.__nativeIntents.length')==0 + # POWER/DELETE remain dedicated click targets, not drag origins. + for action in ("slotPower","removeFx"): + rect=row(1,0).locator(f'[data-action="{action}"]').bounding_box() + assert rect + page.mouse.move(rect['x']+rect['width']/2,rect['y']+rect['height']/2) + page.mouse.down();page.mouse.move(450,50,steps=6) + assert page.locator('.fx-drag-ghost').count()==0,action + page.mouse.up() + assert page.evaluate('()=>window.__nativeIntents.length')==0,action + # A short click on the name still opens the real native editor. + row(1,0).locator('.fx-pick').click() + assert page.evaluate("()=>window.__actions.at(-1)?.action")=="routingFxEditor" + assert page.evaluate('()=>window.__nativeIntents.length')==0 + # Drag lower within the same rack: exact plugin follows pointer. + request=move(1,0,1,1,True) + assert request['operation']=='MOVE_INSERT' and request['payload']['toSlot']==1 + assert row(1,0).get_attribute('data-insert-id')=='actual-a','optimistic reorder' + state['graph']['channels'][0]['inserts'].reverse();accept(request) + assert row(1,0).get_attribute('data-insert-id')=='actual-b' + # Cross-channel MOVE, not a new plugin load or name-only copy. + request=move(1,1,2,0) + assert request['operation']=='MOVE_INSERT' and request['payload']['toChannelId']==RECEIVER + assert request['payload']['instanceId']=='actual-a' + state['graph']['channels'][1]['inserts'].append(state['graph']['channels'][0]['inserts'].pop(1));accept(request) + assert row(2,0).get_attribute('data-insert-id')=='actual-a' + row(2,0).locator('[data-action="openPlugin"]').click() + editor=page.evaluate('()=>window.__actions.at(-1)') + assert editor['action']=='routingFxEditor' and editor['channelId']==RECEIVER and editor['instanceId']=='actual-a' + row(1,0).locator('[data-action="removeFx"]').click() + request=page.evaluate('()=>window.__nativeIntents.at(-1)') + assert request['operation']=='REMOVE_INSERT' and request['payload']['instanceId']=='actual-b' + assert row(1,0).get_attribute('data-insert-id')=='actual-b','optimistic delete' + state['graph']['channels'][0]['inserts'].clear();accept(request) + assert page.locator('#tracks .strip[data-id="1"] .fxslot-row:not(.is-empty)').count()==0 + assert row(2,0).get_attribute('data-insert-id')=='actual-a' + assert page.locator('.wire-main-fragment').count()==0 + assert any(e['to']==state['graph']['mainChannelId'] for e in state['graph']['edges']) + assert not errors,errors + page.screenshot(path=f'native-fx-edit-{width}.png');page.close() + browser.close() + print('PASS native handle-free FX pointer ghost, reorder, cross-channel move, delete, editor token and quiet MAIN; 3 sizes') + +if __name__=='__main__':main() diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 2b584dd09..c02f20fbf 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -114,6 +114,547 @@ test("native signal evidence is produced from measured engine fields, never JS s assert.doesNotMatch(transport,/setProperty \("rawCapturePeak", 0\.0\)/); assert.match(bridge,/protocol\.diagnoseFirstSound/); }); +test("P0 DAW approved Windows GUI directly binds every IN to current JUCE ports, never Pages demo",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const producer=read("integration/ApprovedNativeRuntimeSnapshot.h"); + const builder=read("scripts/build_approved_native_gui.py"); + const nativeMain=read("src/Main.cpp"); + assert.match(builder,/type==='input'&&window\.__JUCE__\?\.backend/); + assert.match(builder,/__ARMIX_NATIVE_M2__\?\.inputChoices/); + assert.match(bridge,/inputChoices\(t\)/); + assert.match(bridge,/hardware\.device\.enabledInputs\.includes\(p\.port\)/); + assert.match(bridge,/field==="input"/); + // Reordering /preview/ strips must NOT change the real hardware lane. + assert.match(bridge,/const channel=m4Index\(t\)/); + assert.match(bridge,/const m4TrackIds=Array\.isArray\(scope\?\.tracks\)/); + assert.match(bridge,/const savedId = uiByNativeId\.get\(ch\.id\) \?\? m4Id/); + assert.match(bridge,/action:"routingSourceSwitch"/); + assert.match(bridge,/row\?\.left===p\.choice\.left/); + assert.match(bridge,/expectedEpoch:p\.epoch,expectedRevision:Number\(next\.revision\)/); + assert.match(bridge,/inputSelect\.hidden=true;routeBtn\.hidden=true;armBtn\.hidden=true/); + assert.match(bridge,/openNativeAudioIO\(\)/); + assert.match(bridge,/\.armix-audio-shade\[hidden\]\{display:none\}/); + assert.match(producer,/firstSound->setProperty\("channels",juce::var\(verifiedChannels\)\)/); + assert.match(producer,/publishAuthoritativeMixerSession/); + assert.match(nativeMain,/publishAuthoritativeMixerSession\(accepted\)/); + assert.match(bridge,/session\.authority==="CHANNEL_ID"/); + assert.match(bridge,/m4ControlIsOwner\(\)/); + assert.match(producer,/list->size\(\)==10/); + assert.match(nativeMain,/engine_\.switchDryRoutingLabSource\(channel,/); + assert.match(nativeMain,/engine_\.liveOutputArmFault\(\)/); + // Public Pages still has its simulation, but NONE of those fake inputs + // can be submitted by the native bridge. Only the native injected source. + assert.doesNotMatch(bridge,/channelOptions\(t,'input'\)/); +}); +test("DAW G0 native M4 controls, source clear, OUT & monitoring are real",()=>{ + const producer=read("integration/ApprovedNativeRuntimeSnapshot.h"); + const bridge=read("web/approved-native-bridge.js"); + const native=read("src/Main.cpp"); + const source=read("src/NativeVerifiedSourcePatch.h"); + const builder=read("scripts/build_approved_native_gui.py"); + assert.match(producer,/firstSound->setProperty\("channelControls",controls\)/); + assert.match(producer,/firstSound->setProperty\("channelPeaksL",levelsL\)/); + assert.match(bridge,/function paintM4Fallback\(next\)/); + assert.match(bridge,/function sendM4Control\(parameter,t,value\)/); + assert.match(bridge,/action:"routingM4Control"/); + assert.match(bridge,/action:"routingChannelPatch"/); + assert.match(bridge,/const channel=m4Index\(t\)/); + assert.match(bridge,/data-native-monitor/); + assert.match(bridge,/const firstListen=p.autoListen/); + assert.match(bridge,/next\.nativeChannelIdPcmActive===true \|\|/); + assert.match(native,/if\(action=="routingM4Control"\)/); + assert.match(native,/engine_\.setDryRoutingLabParameter\(channel,/); + assert.match(native,/if\(action=="routingChannelPatch"\)/); + assert.match(native,/engine_\.repatchDryRoutingLabChannel\(channel,/); + assert.match(source,/if\(mode!="NONE"&&mode!="MONO"&&mode!="STEREO"\)/); + assert.match(source,/row->setProperty\("sourceKind",clearing\?"NONE":"PHYSICAL"\)/); + assert.match(builder,/type==='output'/); + assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); +}); +test("P0 physical SOURCE switching rejects fractional and stale native session tokens before PCM",()=>{ + const main=read("src/Main.cpp"); + const tokens=read("src/NativeSessionToken.h"); + const start=main.indexOf('if(action=="routingSourceSwitch")'); + const end=main.indexOf('if (action == "routingDryApply")',start); + assert.ok(start>=0&&end>start); + const source=main.slice(start,end); + assert.match(source,/nativeSessionTokenMatches\(/); + assert.match(source,/nativeSessionTokenValue\(ep\)/); + assert.match(source,/nativeSessionTokenValue\(rv\)/); + assert.match(source,/channel>=0&&channel\(ep\)/); + assert.match(tokens,/std::isfinite\(n\)/); + assert.match(tokens,/std::floor\(n\)==n/); +}); +test("Native FX GUI routes through ChannelId PCM with no operator MONITOR ritual",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const main=read("src/Main.cpp"); + const engine=read("src/LiveAudioEngine.h"); + const pub=read("engine/core/DynamicNativeSessionPublisher.h"); + const lab=read("src/LiveDryRoutingLab.h"); + const contract=read("web/approved-native-contract.js"); + const translate=read("integration/ApprovedNativeControlIntent.h"); + const snapshot=read("integration/ApprovedNativeRuntimeSnapshot.h"); + const activeProjection=read("integration/ApprovedNativeV8Projection.h"); + assert.match(activeProjection,/insert->setProperty\("catalogId",catalog\)/); + assert.match(activeProjection,/ch->setProperty\("fxRackBypassed",rackBypassed\)/); + assert.match(bridge,/controller\.intent\("LOAD_INSERT",nativeId,/); + assert.match(bridge,/if\(accepted\?\.admitted && nativeCh\)/); + assert.match(lab,/nativeAccepted_\.fxOwners->externalChannel\(\)==target/); + assert.match(bridge,/pendingFxInsert=\{authority:"CHANNEL_ID"/); + assert.match(bridge,/inserted\?\.catalogId===p\.id/); + assert.match(translate,/if\(op=="LOAD_INSERT"\)/); + assert.match(snapshot,/available\.add\(juce::String\("LOAD_INSERT"\)\)/); + assert.match(main,/engine_\.installNativeVst3\(/); + assert.match(contract,/if \(operation === "LOAD_INSERT"\)/); + assert.match(contract,/ch\.inserts\[payload\.slot\]\?\.catalogId===payload\.catalogId/); + assert.match(lab,/epoch\(\),false,std::move\(fx\),false,true\)/); + assert.match(pub,/verifiedInternalFxOnly/); + const install=engine.slice(engine.indexOf("installNativeVst3("), + engine.indexOf("bool bypassNativeVst3(",engine.indexOf("installNativeVst3("))); + assert.doesNotMatch(install,/!allOutputsDisarmed\(\)/); + assert.match(install,/secondaryOutput_\.armed\(\)/); + assert.match(install,/getLatencySamples\(\)>armix::dsp::StereoLatencyDelay::maximumSamples/); +}); +test("Native VST3 insert ACK + readback distinguishes vendor catalog key from live instance token",()=>{ + const base=acceptedFixture(); + base.graph.capabilities.supportedOps.push("LOAD_INSERT"); + const sent=[],accepted=[]; + const controller=protocol.createController({emit:(name,payload)=>sent.push({name,payload}), + onAccepted:s=>accepted.push(s)}); + assert.equal(controller.onSnapshot(base),true); + const source=base.graph.channels[0].id; + const cmd=controller.intent("LOAD_INSERT",source,{catalogId:"vendor.eq.catalog",slot:0}); + assert.equal(cmd.ok,true); + const after=clone(base); + after.graph.revision="6";after.graph.rosterRevision="8"; + after.graph.channels[0].inserts=[{id:"vst3-instance-unique-7", + catalogId:"vendor.eq.catalog",name:"Vendor EQ",bypassed:false}]; + const next=protocol.normalizeSnapshot(after); + const pending={operation:"LOAD_INSERT",targetChannelId:source, + payload:{catalogId:"vendor.eq.catalog",slot:0}, + baseGraphRevision:"5",baseRosterRevision:"7"}; + assert.ok(next?.admitted); + assert.equal(protocol.readbackProvesIntent(next,pending),true, + "live instance token differs from catalog ID but effect is verified"); + for(const spoof of [ + {id:"vst3-instance-unique-7",name:"Vendor EQ",bypassed:false}, + {id:"vst3-instance-unique-7",catalogId:"different.plugin",name:"Vendor EQ",bypassed:false}, + {id:"",catalogId:"vendor.eq.catalog",name:"Vendor EQ",bypassed:false} + ]){ + const bad=clone(after);bad.graph.channels[0].inserts=[spoof]; + assert.equal(protocol.readbackProvesIntent(protocol.normalizeSnapshot(bad),pending),false); + } + assert.equal(controller.onAck({requestId:cmd.requestId,status:"ACCEPTED", + deviceEpoch:base.device.epoch,graphRevision:"6",rosterRevision:"8",errorCode:"NONE"}),true); + assert.equal(controller.state().lastError,"PENDING_ACCEPTED_SNAPSHOT"); + assert.equal(controller.onSnapshot(after),true); + assert.equal(controller.state().lastError,"ACCEPTED_READBACK"); + assert.equal(accepted.at(-1).graph.channels[0].inserts[0].id,"vst3-instance-unique-7"); + assert.ok(sent.some(evt=>evt.name==="arMixConsoleSubscribe")); +}); +test("WIRE ROUTE ONLY to BUS preserves explicit MAIN parallel send after native ACK and readback",()=>{ + const before=acceptedFixture(); + const source=before.graph.channels[0], main=before.graph.mainChannelId; + const oldBus="9007199254740994",newBus="9007199254740995"; + const group=id=>({id,role:"GROUP",name:id===oldBus?"BUS A":"BUS B", + processingFormat:"STEREO",primaryOutId:main, + controls:{faderDb:0,pan:0,mute:false,solo:false},inserts:[],sends:[]}); + before.graph.channels.splice(1,0,group(oldBus),group(newBus)); + before.graph.destinations=[{id:oldBus},{id:newBus},{id:main}]; + source.primaryOutId=oldBus; + source.source={sourceFormat:"MONO",portId:"in:0"}; + const mkEdge=(id,from,to,primary)=>({edgeId:id,from,to, + tap:"POST_FADER",gainLinear:1,enabled:true,signalKind:"AUDIO", + primaryOutput:primary}); + before.graph.edges=[ + mkEdge("9223372036854775808",source.id,oldBus,true), + mkEdge("9223372036854775809",source.id,main,false), + mkEdge("9223372036854775810",oldBus,main,true), + mkEdge("9223372036854775811",newBus,main,true) + ]; + const events=[],controller=protocol.createController({ + emit:(name,payload)=>events.push({name,payload})}); + assert.equal(controller.onSnapshot(before),true); + assert.equal(controller.state().current.admitted,true); + const change={op:"ROUTE_ONLY",from:source.id,to:newBus, + tap:"POST_FADER",gainLinear:1}; + const submitted=controller.intent("APPLY_WIRE_TRANSACTION",source.id, + {changes:[change]}); + assert.equal(submitted.ok,true); + const after=clone(before); + after.graph.revision="6";after.graph.rosterRevision="8"; + after.graph.channels[0].primaryOutId=newBus; + after.graph.edges[0].to=newBus; // exact native EdgeId promoted/retargeted + assert.equal(controller.onAck({requestId:submitted.requestId,status:"ACCEPTED", + deviceEpoch:before.device.epoch,graphRevision:"6",rosterRevision:"8", + errorCode:"NONE"}),true); + assert.equal(controller.state().lastError,"PENDING_ACCEPTED_SNAPSHOT"); + assert.equal(controller.onSnapshot(after),true); + assert.equal(controller.state().lastError,"ACCEPTED_READBACK", + "verified ROUTE_ONLY must not reject intentionally preserved parallel MAIN"); + assert.equal(controller.state().current.graph.channels[0].primaryOutId,newBus); + assert.equal(controller.state().current.graph.edges.find(e=> + e.edgeId==="9223372036854775809").primaryOutput,false); + assert.ok(events.some(e=>e.name==="arMixConsoleSubscribe")); + const invalid=clone(after); + invalid.graph.edges[1].primaryOutput=true; + const pending={operation:"APPLY_WIRE_TRANSACTION",targetChannelId:source.id, + baseGraphRevision:"5",baseRosterRevision:"7", + originalPrimaryOutId:oldBus,payload:{changes:[change]}}; + assert.equal(protocol.readbackProvesIntent(protocol.normalizeSnapshot(invalid),pending),false, + "a second MAIN primary must still fail closed"); + invalid.graph.edges[1].primaryOutput=false; + invalid.graph.edges[0].to=oldBus; + assert.equal(protocol.readbackProvesIntent(protocol.normalizeSnapshot(invalid),pending),false, + "old primary may not survive as an independent cable"); +}); +test("WIRE SOURCE ONLY readback retains physical input but removes primary MAIN",()=>{ + const before=acceptedFixture(); + const source=before.graph.channels[0]; + before.graph.edges[0].primaryOutput=true; + source.source={sourceFormat:"MONO",portId:"in:0"}; + const after=clone(before); + after.graph.revision="6";after.graph.rosterRevision="8"; + delete after.graph.channels[0].primaryOutId; + after.graph.edges=[]; + const controller=protocol.createController({emit:()=>{}}); + assert.equal(controller.onSnapshot(before),true); + const cmd=controller.intent("APPLY_WIRE_TRANSACTION",source.id,{changes:[ + {op:"REMOVE",from:source.id,edgeId:before.graph.edges[0].edgeId} + ]}); + assert.equal(cmd.ok,true); + assert.equal(controller.onAck({requestId:cmd.requestId,status:"ACCEPTED", + deviceEpoch:before.device.epoch,graphRevision:"6",rosterRevision:"8", + errorCode:"NONE"}),true); + assert.equal(controller.onSnapshot(after),true); + assert.equal(controller.state().lastError,"ACCEPTED_READBACK"); + assert.equal(controller.state().current.graph.channels[0].source.portId,"in:0"); + assert.equal(controller.state().current.graph.channels[0].primaryOutId,undefined); +}); +test("M/ST after BUS/WIRE uses native ChannelId intent and accepted PCM processing width",()=>{ + const before=acceptedFixture(); + before.graph.capabilities.supportedOps.push("SET_PROCESSING_FORMAT"); + before.graph.channels[0].source={sourceFormat:"MONO",portId:"in:0"}; + const source=before.graph.channels[0].id,events=[]; + const controller=protocol.createController({emit:(name,payload)=> + events.push({name,payload})}); + assert.equal(controller.onSnapshot(before),true); + const change=controller.intent("SET_PROCESSING_FORMAT",source,{format:"STEREO"}); + assert.equal(change.ok,true); + assert.equal(events.at(-1).payload.operation,"SET_PROCESSING_FORMAT"); + assert.equal(events.at(-1).payload.targetChannelId,source); + const after=clone(before); + after.graph.revision="6";after.graph.rosterRevision="8"; + after.graph.channels[0].processingFormat="STEREO"; + assert.equal(controller.onAck({requestId:change.requestId,status:"ACCEPTED", + deviceEpoch:before.device.epoch,graphRevision:"6",rosterRevision:"8", + errorCode:"NONE"}),true); + assert.equal(controller.state().lastError,"PENDING_ACCEPTED_SNAPSHOT"); + assert.equal(controller.onSnapshot(after),true); + assert.equal(controller.state().lastError,"ACCEPTED_READBACK"); + assert.equal(controller.state().current.graph.channels[0].source.portId,"in:0"); + const pending={operation:"SET_PROCESSING_FORMAT",targetChannelId:source, + baseGraphRevision:"5",baseRosterRevision:"7",payload:{format:"STEREO"}}; + const stale=clone(after); + stale.graph.channels[0].processingFormat="MONO"; + assert.equal(protocol.readbackProvesIntent(protocol.normalizeSnapshot(stale),pending),false); + stale.graph.channels[0].processingFormat="STEREO"; + stale.graph.rosterRevision="7"; + assert.equal(protocol.readbackProvesIntent(protocol.normalizeSnapshot(stale),pending),false, + "no M/ST success from a stale native roster revision"); + const bridge=read("web/approved-native-bridge.js"); + const fn=bridge.slice(bridge.indexOf("function requestProcessingFormat(t)"), + bridge.indexOf("function previewNativePan(t,el,event)")); + assert.match(fn,/session\(\)\?\.authority|mixerSession\(\)\?\.authority/); + assert.match(fn,/controller.intent\("SET_PROCESSING_FORMAT",channelId,/); + assert.ok(fn.indexOf('authority==="CHANNEL_ID"')< + fn.indexOf('action:"routingChannelPatch"')); +}); +test("P0 first Add FX discovers real local VST3 lazily without an audio-thread scan",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const native=read("src/Main.cpp"); + const catalog=read("src/PluginCatalog.h"); + assert.match(bridge,/function discoverFxOnFirstPickerOpen\(\)/); + assert.match(bridge,/nativeFxDiscoveryRequested=true;/); + assert.match(bridge,/backend\.emitEvent\("arMixAction",\{action:"scanVst3"\}\)/); + assert.match(bridge,/discoverFxOnFirstPickerOpen\(\);[\s\S]*?scope\?\.openFastPicker/); + assert.match(native,/action == "scanVst3"[\s\S]*?catalog_\.scanDefaults\(\)/); + assert.match(catalog,/struct Scanner final : juce::Thread/); + assert.match(bridge,/scope\?\.setNativeCatalog\?\.\(\[\.\.\.nativeCatalog\.values\(\)\]\)/); + // Neither startup nor audio callback can trigger a surprise system scan. + assert.doesNotMatch(bridge.slice(0,bridge.indexOf("function discoverFxOnFirstPickerOpen")), + /action:"scanVst3"/); +}); + +test("P0 MAIN remains enabled through verified STEREO -> NONE -> STEREO edits",()=>{ + const engine=read("src/LiveAudioEngine.h"); + const host=read("src/Main.cpp"); + const bridge=read("web/approved-native-bridge.js"); + const guard=read("src/NativeTopologyEditSafety.h"); + // First ARM remains strict, including inactive hardware and known VB-Cable loops. + assert.match(engine,/juce::String liveOutputArmFault\(\)\s*\{\s*return liveOutputArmFault\(true\);\s*\}/, + "manual MONITOR always uses strict source verification"); + assert.match(engine,/juce::String liveOutputArmFault\(bool requirePhysicalSource\)/, + "previously-authorized silent MAIN may resume without a physical IN"); + assert.match(engine,/if \(!physicalSource && requirePhysicalSource\)/); + assert.match(engine,/knownVirtualCableFeedbackPair\(currentSetup\.inputDeviceName,/); + assert.match(host,/fault=engine_\.liveOutputArmFault\(\)/); + // Structural SOURCE changes gate physical output only at publication. + // The user's MONITOR decision persists on the same safe device/route. + assert.match(engine,/if\(wasMonitoring\)\s*topologyPublicationMute_\.store\(true,std::memory_order_release\)/); + assert.match(engine,/if\(wasMonitoring && !safeToResume\)setOutputMuted\(true\)/); + assert.match(engine,/topologyPublicationMute_\.store\(false,std::memory_order_release\)/); + assert.match(engine,/monitor_\.load\(std::memory_order_relaxed\) &&\s*!topologyPublicationMute_\.load\(std::memory_order_acquire\)/); + assert.match(engine,/wasMonitoring,sameEpoch,liveOutputArmFault\(false\)\.isEmpty\(\),/); + assert.match(guard,/return previouslyArmed && sameDeviceEpoch && outputArmSafe && !streamArmed/); + assert.match(bridge,/action:"routingSourceSwitch"/); + // The browser must not be the authority for re-arming a previously verified + // route; the engine owns state across silent source changes. + assert.doesNotMatch(bridge,/routingSourceSwitch[^;]+monitor\(false\)/); +}); + +test("P0 post-BUS native IN routes NONE MONO STEREO via one PCM owner",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const host=read("src/Main.cpp"); + const engine=read("src/LiveAudioEngine.h"); + const lab=read("src/LiveDryRoutingLab.h"); + assert.match(bridge,/function dispatchNativeSource\(\)/); + assert.match(bridge,/action:"routingNativeSourcePatch"/); + assert.match(bridge,/arMixNativeSourceAck/); + assert.match(bridge,/pendingNativeSources.set\(id,choice\)/); + assert.match(host,/if\(action=="routingNativeSourcePatch"\)/); + assert.match(host,/engine_\.patchNativeInputSource\(ep,rev,roster,/); + assert.match(lab,/const bool disconnect=!stereo&&physicalLeft==-1&&physicalRight==-1/); + assert.match(lab,/nativeStructureLive_=true; \/\/ M4 source roster no longer authoritative/); + assert.match(engine,/NATIVE_SOURCE_PUBLICATION_EXCEPTION/); +}); +test("P0 actual Add BUS reaches the live ChannelId graph",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const host=read("src/Main.cpp"); + const engine=read("src/LiveAudioEngine.h"); + const lab=read("src/LiveDryRoutingLab.h"); + const projection=read("integration/ApprovedNativeRuntimeSnapshot.h"); + assert.match(bridge,/function requestNativeBusCreate\(\)/); + assert.match(bridge,/action:"routingNativeBusCreate"/); + assert.match(bridge,/target.id==="addBus"/); + assert.match(bridge,/arMixNativeBusAck/); + assert.match(bridge,/addBus.hidden=!nativeAdmitted/); + assert.match(host,/if\(action=="routingNativeBusCreate"\)/); + assert.match(host,/engine_\.editNativeBus\(ep,rev,roster,/); + assert.match(engine,/topologyPublicationMute_\.store\(/); + assert.match(lab,/if\(beforePublish\)beforePublish\(\)/); + assert.match(projection,/available\.add\(juce::String\("CREATE_GROUP"\)\)/); +}); +test("P0 installed ChannelId WIRE capability reaches the GUI",()=>{ + const projection=read("integration/ApprovedNativeRuntimeSnapshot.h"); + const native=read("src/LiveDryRoutingLab.h"); + const bridge=read("web/approved-native-bridge.js"); + assert.match(native,/NATIVE_APPLY_WIRE_TRANSACTION/); + assert.match(projection,/if\(has\("NATIVE_APPLY_WIRE_TRANSACTION"\)\)/); + assert.match(projection,/available\.add\(juce::String\("APPLY_WIRE_TRANSACTION"\)\)/); + assert.match(bridge,/const kind=isPrimary\?"primary"/); + assert.match(bridge,/if \(isPrimary && edge\.gainLinear!==1\)/); + assert.doesNotMatch(bridge,/if \(isMain && edge\.gainLinear!==1\)/); +}); +test("P0 WIRE-to-MAIN and channel OUT use one acknowledged native transaction",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const builder=read("scripts/build_approved_native_gui.py"); + const native=read("src/Main.cpp"); + assert.match(bridge,/function requestPrimaryOut\(t,target\)/); + assert.match(bridge,/session\?\.authority==="CHANNEL_ID"/); + assert.match(bridge,/controller\.intent\("APPLY_WIRE_TRANSACTION",channelId,/); + assert.match(bridge,/const to=target==="MAIN"\?main:destination\?\.id\|\|null/); + assert.match(bridge,/change=\{op:"ROUTE_ONLY",from:channelId,to,/); + assert.match(bridge,/change=\{op:"REMOVE",from:channelId,edgeId:edge\.edgeId\}/); + // Only the accepted PRIMARY edge may be detached. A parallel SEND to + // MAIN must not be misclassified as a physical OUT. + assert.match(bridge,/e\.primaryOutput===true/); + const primaryOutPath=bridge.slice(bridge.indexOf("function requestPrimaryOut"),bridge.indexOf("const pendingNativeSources")); + assert.doesNotMatch(primaryOutPath,/e\.primaryOutput!==false/); + const roster=read("engine/core/DynamicChannelRoster.h"); + const translator=read("integration/ApprovedNativeControlIntent.h"); + assert.match(roster,/target->primaryOutput=true/); + assert.match(roster,/s\.primaryOutput &&/); + assert.doesNotMatch(translator,/WIRE_MAIN_PRIMARY_REQUIRED/); + assert.match(bridge,/const channel=m4Index\(t\)/); + // A native-owned MAIN WIRE never triggers the legacy routingChannelPatch. + const primary=bridge.slice(bridge.indexOf("function requestPrimaryOut(t,target)"), + bridge.indexOf("let pendingFxInsert")); + assert.ok(primary.indexOf('session?.authority==="CHANNEL_ID"')>=0); + assert.ok(primary.indexOf('session?.authority==="CHANNEL_ID"')< + primary.indexOf("const channel=m4Index(t)"), + "ChannelId branch must precede the legacy M4 fallback inside requestPrimaryOut"); + assert.match(bridge,/const isMainConnect=/); + assert.match(bridge,/const isMainRemove=/); + assert.match(bridge,/current\.graph\.edges\.some/); + assert.match(bridge,/if\(requestPrimaryOut\(t,target\)\)/); + assert.match(native,/action=="routingChannelPatch"/); + assert.match(native,/engine_\.repatchDryRoutingLabChannel\(channel,/); + assert.match(bridge,/scope\?\.closeNativePicker\?\.\(\)/); + assert.match(builder,/closeNativePicker\(\)\{setFastPicker\(false\);\}/); + assert.match(builder,/NATIVE JUCE VST3/); + assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); +}); +test("P0 typed mono-stereo, PAN detent, fader geometry & FX failure diagnostics",()=>{ + const page=read("site/preview-v2/index.html"); + const bridge=read("web/approved-native-bridge.js"); + const main=read("src/Main.cpp"); + const snapshot=read("integration/ApprovedNativeRuntimeSnapshot.h"); + const nativeBundle=read("scripts/build_approved_native_gui.py"); + assert.match(nativeBundle,/const FADER_TAPER=Object\.freeze/); + assert.match(nativeBundle,/function faderDbFromTravelPercent\(percent,isSend\)/); + assert.match(nativeBundle,/faderDbFromTravelPercent\(100\*\(1-frac\),max===6\)/); + assert.doesNotMatch(page,/FADER_TAPER/, "public Pages reference remains immutable"); + assert.match(bridge,/function previewNativePan\(t,el,event\)/); + assert.match(bridge,/const width=event\.type==="change"\?12:latched\?12:7/); + assert.match(bridge,/readout\.textContent=value===0\?"C"/); + assert.match(bridge,/function requestProcessingFormat\(t\)/); + assert.match(bridge,/operation:"SET_PROCESSING_FORMAT"/); + assert.match(bridge,/if\(action==="format"&&t\?\.kind==="audio"\)/); + assert.match(main,/operation=="SET_PROCESSING_FORMAT"/); + assert.match(main,/operation,target\)/); + assert.match(snapshot,/verified->setProperty\("channelFormat",format\)/); + assert.match(bridge,/backend\.addEventListener\("arMixNotice"/); + assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); +}); +test("P0 MAIN WIRE unplug uses UI-to-native EdgeId and no fake graph",()=>{ + const adapter=read("web/approved-native-bridge.js"); + assert.match(adapter,/const edgeId=wireByUiId\.get\(op\.edgeId\)/); + assert.match(adapter,/menu\.setAttribute\("aria-busy","true"\)/); + assert.match(adapter,/el\.removeAttribute\("aria-busy"\)/); + assert.doesNotMatch(adapter,/const edgeId=uiByWireId\.get\(op\.edgeId\)/); + assert.match(adapter,/current\.graph\.edges\.some/); + assert.match(adapter,/WIRE BUS\/FX return is not admitted/); + assert.match(adapter,/requestPrimaryOut\(t,target\)/); +}); +test("P0 real slot VST3 power and native editor use verified instance tokens",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const main=read("src/Main.cpp"); + assert.match(bridge,/function verifiedFxFor\(t,slot\)/); + assert.match(bridge,/function requestNativeFxPower\(t,slot,bypass\)/); + assert.match(bridge,/if\(action==="slotPower"\)/); + assert.match(bridge,/if\(action==="fxOn"\)/); + assert.doesNotMatch(bridge,/rackSavedBypass/); + assert.match(bridge,/requestM4RackPower\(t\)/); + assert.match(bridge,/requestAdmittedFxPower\(t,action,btn\)/); + assert.match(bridge,/FX rack unchanged/); + assert.match(bridge,/pendingM4RackPowers/); + assert.match(bridge,/action:"routingFxEditor"/); + assert.match(bridge,/action:"routingFxBypass"/); + assert.match(bridge,/backend\.addEventListener\("arMixRoutingFxBypassAck"/); + assert.match(main,/ack->setProperty\("requestId",args\.getProperty\("requestId",juce::var\(\)\)\)/); + assert.match(main,/action == "routingFxEditor"/); + assert.match(main,/action == "routingFxBypass"/); +}); +test("P0 VST3 preparation runs with old live PCM; monitor closes only at publication",()=>{ + const lab=read("src/LiveDryRoutingLab.h"); + const engine=read("src/LiveAudioEngine.h"); + assert.match(lab,/#include /); + assert.match(lab,/if\(beforePublish\)beforePublish\(\)/); + assert.match(lab,/const auto epochAtPublish=deviceEpoch_\.load/); + assert.match(lab,/next,formats,sampleRate,deviceFrames,true,nullptr,\s*beforePublish/); + assert.match(engine,/bool enteredPublication=false/); + assert.match(engine,/enteredPublication=true;[\s\S]*?if\(wasMonitoring\)\s*topologyPublicationMute_\.store\(true,std::memory_order_release\)/); + assert.match(engine,/if\(!enteredPublication\)return error/); + assert.match(engine,/return finishGuardedDryTopology\(/); + assert.match(engine,/return applyGuardedDryTopology\(epoch,frames,\[&\]\(const auto& beforePublish\)/); + // FX and SOURCE recompiles must inherit the SAME real active fader, pan, + // mute and solo from native ChannelId or M4 before replacing a graph. + assert.match(lab,/juce::String inheritLiveControlsForRecompile\(/); + assert.match(lab,/juce::String insertCatalogFx[\s\S]*?const auto inherited=inheritLiveControlsForRecompile\(\s*command,expectedEpoch\)/); + assert.match(lab,/juce::String publishRevisedTopology[\s\S]*?const auto inherited=inheritLiveControlsForRecompile\(\s*staged,expectedEpoch\)/); + assert.match(lab,/NativeTopologyEditSafety::preserveAcceptedMix\(/); + assert.match(lab,/case Publisher::Result::applied:[\s\S]*?nativeControlDirty_=false/); +}); +test("P0 SOURCE, OUT, M-ST and FX share late-gated graph publication",()=>{ + const lab=read("src/LiveDryRoutingLab.h"); + const engine=read("src/LiveAudioEngine.h"); + // Format/input edits and native VST3 insert must all enter the same gate. + assert.match(lab,/juce::String repatchPhysicalSource[\s\S]*?int deviceFrames,\s*const std::function& beforePublish/); + assert.match(lab,/juce::String repatchChannelStructure[\s\S]*?int deviceFrames,\s*const std::function& beforePublish/); + assert.match(lab,/juce::String publishRevisedTopology[\s\S]*?int deviceFrames,\s*const std::function& beforePublish/); + assert.match(lab,/acceptedFxSelections_,formats,sampleRate,deviceFrames,true,\s*nullptr,beforePublish/); + assert.match(engine,/if\(!structural\)\s*return dryRoutingLab_\.repatchPhysicalSource/); + assert.match(engine,/return applyGuardedDryTopology\(epoch,frames,\[&\]\(const auto& beforePublish\)/); + assert.match(engine,/frames,beforePublish\);/); +}); +test("P0 FX command preflight never mutes monitoring for deterministic rejection",()=>{ + const lab=read("src/LiveDryRoutingLab.h"); + const engine=read("src/LiveAudioEngine.h"); + assert.match(lab,/juce::String fxInsertPreflight\(int lane,int slot/); + assert.match(lab,/const auto preflight=fxInsertPreflight\(/); + assert.match(engine,/dryRoutingLab_\.fxInsertPreflight\(/); + assert.match(engine,/pluginFormat->fileMightContainThisPluginType\(chosen\.path\)/); + assert.match(engine,/FX INSERT: VST3 bundle unavailable or invalid/); +}); +test("P0 JUCE native errors use the actual notice.text event contract",()=>{ + const host=read("src/Main.cpp"); + const bridge=read("web/approved-native-bridge.js"); + assert.match(host,/o->setProperty \("text", message\)/); + assert.match(host,/o->setProperty \("error", error\)/); + assert.match(bridge,/backend\.addEventListener\("arMixNotice",notice=>/); + assert.match(bridge,/const message=notice\?\.text/); + assert.match(bridge,/nativeToast\(message\)/); + assert.doesNotMatch(bridge,/notice\.message/); +}); +test("P0 native WIRE MAIN disconnect requires exact accepted EdgeId or verified M4 route",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const bundle=read("scripts/build_approved_native_gui.py"); + assert.match(bridge,/const edgeId=wireByUiId\.get\(op\.edgeId\)/); + assert.match(bridge,/const graphMainRemove=op\.type==="REMOVE"/); + assert.match(bridge,/const m4MainRemove=op\.type==="REMOVE"/); + assert.match(bridge,/current\?\.admitted!==true/); + assert.match(bridge,/legacy\(\)\?\.channels\?\.\[lane\]\?\.main===true/); + assert.match(bridge,/e\.id===op\.edgeId&&e\.sourceId===op\.sourceId/); + assert.match(bridge,/e\.destId===scope\?\.master\?\.id/); + assert.match(bundle,/get wireEdges\(\)\{return wireEdges;\}/); +}); +test("P0 native-only WIRE cables reflect actual M4 MAIN readback, not demo ghosts",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const bundle=read("scripts/build_approved_native_gui.py"); + assert.match(bridge,/if\(session\.authority==="M4" && m4Verified\(\)\)/); + assert.match(bridge,/scope\?\.syncVerifiedM4Wires\?\.\(session\.channels\.map\(ch=>ch\.source\),m4TrackIds\)/); + assert.match(bundle,/syncVerifiedM4Wires\(rows,ids\)/); + assert.match(bundle,/typeof r\.main!=='boolean'/); + assert.match(bundle,/if\(rows\[i\]\.main\)/); + assert.match(bundle,/nextWireId\+\+/); + assert.match(bundle,/verifiedM4WireDirty/); + assert.match(bundle,/refreshWireRoutingNodes\(\)/); + assert.match(bundle,/!wireGesture&&!faderGesture/); +}); +test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ + const engine=read("src/LiveAudioEngine.h"); + const bridge=read("web/approved-native-bridge.js"); + assert.match(engine,/knownVirtualCableFeedbackPair/); + assert.match(engine,/in\.contains\("cable output"\) && out\.contains\("cable input"\)/); + assert.match(engine,/currentSetup\.inputDeviceName/); + assert.match(engine,/currentSetup\.outputDeviceName/); + assert.match(engine,/MONITOR OFF: VB-Cable capture\/playback self-loop/); + assert.match(bridge,/const virtualCableFeedbackPair=/); + assert.match(bridge,/next\.nativeChannelIdPcmActive===true/); + assert.match(bridge,/if\(firstListen && !virtualCableFeedbackPair\(\)\)/); + assert.match(bridge,/VB-Cable feedback loop; select physical playback/); +}); +test("single /preview/ GUI: channel IN, actual OUT and correlated device safety ACK",()=>{ + const pages=read("scripts/build_pages.py"); + const builder=read("scripts/build_approved_native_gui.py"); + const bridge=read("web/approved-native-bridge.js"); + const native=read("src/Main.cpp"); + assert.match(pages,/buttons_dest=dst\/'preview'/); + assert.match(builder,/public = destination \/ "preview"/); + assert.match(bridge,/source:"\/preview\/ approved compiled Pages GUI"/); + assert.match(bridge,/field==="input"/); + assert.match(bridge,/nativeUiSourcePending=null;[\s\S]*?INPUT timeout/); + assert.match(bridge,/row\?\.main===true/); + assert.match(bridge,/pendingDeviceMute=\{requestId,epoch:String\(hardware\.device\.epoch\)\}/); + assert.match(bridge,/ack\?\.requestId!==pendingDeviceMute\.requestId/); + assert.match(bridge,/VIRTUAL \/ NO SPEAKERS/); + assert.match(bridge,/Advanced driver recovery/); + assert.match(native,/ack->setProperty\("requestId",[\s\S]*?args\.getProperty\("requestId",juce::var\(\)\)/); + assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); +}); test("strict producer rejects JS Number identities, invalid hardware pins and fake LIVE",()=>{ const cases=[ s=>{s.device.epoch=69;}, @@ -325,10 +866,12 @@ test("M2 code edits approved Pages *events* only, not a second native GUI/audio }); test("M3 native-only Pages scope performs real bridge projection, fader intent and ACK readback",()=>{ - const vm=require("node:vm"),sent=[],listeners=new Map(); + const vm=require("node:vm"),sent=[],listeners=new Map(),timers=[],microtasks=[]; let nextId=100,nextEdgeId=200,paints=0,rollbacks=0; const scope={ tracks:[],master:{id:1,name:"Master"},colors:["#568ead"], + get wireEdges(){return this.edges||[];}, + syncNativeWireGains(rows){for(const r of rows){const e=this.edges?.find(e=>e.id===r.id);if(e)e.levelDb=r.levelDb;}}, wireGraph:{validateCandidateGraph:()=>({ok:true})}, make:(name,kind,color)=>({id:nextId++,name,kind,color,selected:false}), render(){paints++;}, @@ -352,7 +895,7 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a }; const window={ __JUCE__:{backend:native},ArSonApprovedNativeContract:protocol, - __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){},setTimeout(){return 0;} + __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){},queueMicrotask(fn){microtasks.push(fn);},setTimeout(fn,ms){timers.push({fn,ms});return timers.length;} }; vm.runInNewContext(read("web/approved-native-bridge.js"),{ window,document,performance:{now:()=>0},console @@ -361,6 +904,13 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a assert.equal(sent[1].name,"arMixConsoleSubscribe"); assert.equal(window.__ARMIX_APPROVED_NATIVE_GUI__.acceptedGraphConnected,false); const accepted=acceptedFixture(); + // The native callback, not this browser fixture, selects ChannelId PCM. + accepted.mixerSession={ + authority:"CHANNEL_ID",deviceEpoch:accepted.device.epoch, + routeRevision:accepted.graph.revision, + rosterRevision:accepted.graph.rosterRevision, + channels:accepted.graph.channels,main:{db:0,mute:false} + }; listeners.get("arMixConsoleSnapshot")(accepted); assert.equal(window.__ARMIX_APPROVED_NATIVE_GUI__.acceptedGraphConnected,true); assert.equal(scope.tracks.length,1); @@ -414,8 +964,385 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a const unwired=clone(updated);unwired.graph.revision="6";unwired.graph.edges=[]; listeners.get("arMixConsoleSnapshot")(unwired); assert.equal(scope.edges.length,0,"accepted snapshot replaces reference wire"); + // A receiver is an ordinary INPUT channel with no physical source. Its + // native ChannelId, never its visual ordinal, must receive the WIRE intent. + const receiver=clone(unwired.graph.channels[0]); + receiver.id="9007199254740995";receiver.name="CH04"; + delete receiver.primaryOutId; + const ready=clone(unwired);ready.graph.revision="7"; + delete ready.graph.channels[0].primaryOutId; + ready.graph.channels.splice(1,0,receiver); + ready.graph.destinations.push({id:receiver.id,role:"INPUT"}); + listeners.get("arMixConsoleSnapshot")(ready); + const receiverUi=scope.tracks.find(t=>t.name==="CH04").id; + assert.equal(window.__ARMIX_NATIVE_M2__.consumeWire([ + {type:"CONNECT",sourceId:sourceUi,destId:receiverUi,mode:"send"} + ]),true); + let send=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; + assert.equal(send.payload.changes[0].to,receiver.id); + assert.equal(scope.edges.length,0,"INPUT WIRE stays pending until native readback"); + const originalSend=send; + const flushMicro=()=>{while(microtasks.length)microtasks.shift()();}; + listeners.get("arMixConsoleAck")({requestId:send.requestId,status:"REJECTED", + errorCode:"STALE_NATIVE_CONTROL_REVISION",deviceEpoch:ready.device.epoch, + graphRevision:"7",rosterRevision:"8"}); + listeners.get("arMixConsoleSnapshot")(ready);flushMicro(); + assert.equal(sent.findLast(x=>x.name==="arMixConsoleIntent").payload.requestId,originalSend.requestId, + "unchanged snapshot cannot authorize replay"); + const fresh=clone(ready);fresh.graph.rosterRevision="8"; + listeners.get("arMixConsoleSnapshot")(fresh);flushMicro(); + send=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; + assert.notEqual(send.requestId,originalSend.requestId,"new ledger ID for one verified rebase"); + assert.equal(send.baseRosterRevision,"8"); + assert.deepEqual(JSON.parse(JSON.stringify(send.payload)),JSON.parse(JSON.stringify(originalSend.payload))); + + listeners.get("arMixConsoleAck")({ + requestId:send.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:ready.device.epoch,graphRevision:"8",rosterRevision:"8" + }); + assert.equal(scope.edges.length,0,"INPUT WIRE ACK alone never paints a cable"); + const routed=clone(ready);routed.graph.revision="8";routed.graph.rosterRevision="8"; + routed.graph.edges=[{edgeId:"9223372036854775810",from:send.targetChannelId, + to:receiver.id,tap:"POST_FADER",gainLinear:1,enabled:true, + primaryOutput:false,signalKind:"AUDIO"}]; + listeners.get("arMixConsoleSnapshot")(routed); + assert.equal(scope.edges.length,1); + assert.equal(scope.edges[0].destId,receiverUi); + assert.equal(window.__ARMIX_NATIVE_M2__.state().pending,null); + // Continuous send gain coalesces the latest gesture while the native ACK + // is outstanding. Gain-only accepted readback must preserve strip DOM. + routed.graph.capabilities.supportedOps.push("SET_WIRE_GAIN"); + listeners.get("arMixConsoleSnapshot")(routed); + const gainUi=scope.edges[0].id,paintBeforeGain=paints; + const pump=()=>{const ready=timers.splice(0);for(const t of ready)if(t.ms===32)t.fn();}; + window.__ARMIX_NATIVE_M2__.consumeWire([{type:"GAIN",sourceId:sourceUi,edgeId:gainUi,levelDb:-6}]); + pump(); + const firstGain=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; + assert.equal(firstGain.operation,"SET_WIRE_GAIN"); + assert.equal(firstGain.payload.edgeId,"9223372036854775810"); + assert.equal(scope.edges[0].levelDb,0,"no optimistic send gain acceptance"); + window.__ARMIX_NATIVE_M2__.consumeWire([{type:"GAIN",sourceId:sourceUi,edgeId:gainUi,levelDb:-9}]); + window.__ARMIX_NATIVE_M2__.consumeWire([{type:"GAIN",sourceId:sourceUi,edgeId:gainUi,levelDb:-12}]); + pump(); + assert.equal(sent.findLast(x=>x.name==="arMixConsoleIntent").payload.requestId,firstGain.requestId); + const ackGain=request=>listeners.get("arMixConsoleAck")({requestId:request.requestId,status:"ACCEPTED", + errorCode:"NONE",deviceEpoch:routed.device.epoch,graphRevision:"8",rosterRevision:"8"}); + ackGain(firstGain); + assert.equal(scope.edges[0].levelDb,0,"ACK alone is not PCM gain readback"); + const gained=clone(routed);gained.graph.edges[0].gainLinear=firstGain.payload.gainLinear; + listeners.get("arMixConsoleSnapshot")(gained); + assert.equal(scope.edges[0].levelDb,-6); + assert.equal(paints,paintBeforeGain,"scalar WIRE gain cannot rebuild mounted strips"); + pump(); + const latestGain=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; + assert.notEqual(latestGain.requestId,firstGain.requestId); + assert.ok(Math.abs(latestGain.payload.gainLinear-Math.pow(10,-12/20))<1e-9); + ackGain(latestGain);gained.graph.edges[0].gainLinear=latestGain.payload.gainLinear; + listeners.get("arMixConsoleSnapshot")(gained); + assert.equal(scope.edges[0].levelDb,-12); + assert.equal(paints,paintBeforeGain); + // OUT uses the same actual INPUT destination as WIRE, not a name-only + // GROUP lookup. An exclusive route promotes the existing native edge. + const hooks=window.__ARMIX_NATIVE_M2__,sourceTrack=scope.tracks[0]; + assert.ok(hooks.outputChoices(sourceTrack).includes("CH04")); + const output={dataset:{field:"output"},value:"CH04",closest:()=>null}; + hooks.consumeField({target:output,type:"change"}); + const outRequest=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; + assert.equal(outRequest.operation,"APPLY_WIRE_TRANSACTION"); + assert.equal(outRequest.payload.changes[0].op,"ROUTE_ONLY"); + assert.equal(outRequest.payload.changes[0].to,receiver.id); + listeners.get("arMixConsoleAck")({requestId:outRequest.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:gained.device.epoch,graphRevision:"9",rosterRevision:"9"}); + const primary=clone(gained);primary.graph.revision="9";primary.graph.rosterRevision="9"; + primary.graph.channels[0].primaryOutId=receiver.id; + primary.graph.edges[0].primaryOutput=true;primary.graph.edges[0].gainLinear=1; + listeners.get("arMixConsoleSnapshot")(primary); + assert.equal(scope.tracks[0].output,"CH04"); + const duplicate=clone(primary),other=clone(receiver); + other.id="9007199254740997";duplicate.graph.channels.splice(2,0,other); + const reserved=clone(receiver);reserved.id="9007199254740999";reserved.name="NONE"; + duplicate.graph.channels.splice(3,0,reserved); + duplicate.graph.revision="10";duplicate.graph.rosterRevision="10"; + listeners.get("arMixConsoleSnapshot")(duplicate); + const choices=hooks.outputChoices(scope.tracks[0]); + assert.ok(choices.includes("CH04 ["+receiver.id+"]")); + assert.ok(choices.includes("CH04 ["+other.id+"]")); + assert.ok(!choices.includes("CH04"),"duplicate names cannot address the wrong native channel"); + assert.ok(!choices.includes("NONE"),"a channel name cannot alias SOURCE ONLY"); + assert.ok(choices.includes("NONE ["+reserved.id+"]")); + output.value="CH04";hooks.consumeField({target:output,type:"change"}); + assert.equal(sent.findLast(x=>x.name==="arMixConsoleIntent").payload.requestId,outRequest.requestId); + output.value="CH04 ["+other.id+"]";hooks.consumeField({target:output,type:"change"}); + assert.equal(sent.findLast(x=>x.name==="arMixConsoleIntent").payload.payload.changes[0].to,other.id); +}); + +test("P0 native FX rack and per-slot readback update mounted strip without replacing fader DOM",()=>{ + const vm=require("node:vm"),listeners=new Map(),sent=[]; + let paints=0,serial=100,wire=300,strip=null; + const scope={ + tracks:[],master:{id:1,name:"Master"},colors:["#456789"], + wireGraph:{validateCandidateGraph:()=>({ok:true})}, + make:(name,kind,color)=>({id:serial++,name,kind,color,selected:false}), + render(){paints++;}, + installGraph(tracks,master,edges){ + this.tracks=tracks;this.master=master;this.edges=edges;this.render(); + }, + allocateWireId:()=>wire++,displayMeterDbfs(){},stopDemo(){} + }; + const native={emitEvent:(name,payload)=>sent.push({name,payload}), + addEventListener:(name,fn)=>listeners.set(name,fn)}; + const info={textContent:""},preview={disabled:false},toast={hidden:true}; + const doc={ + readyState:"complete",documentElement:{dataset:{}}, + getElementById:id=>id==="info"?info:id==="preview"?preview: + id==="armixNativeToast"?toast:null, + querySelector:selector=>selector.startsWith('.strip[data-id=')?strip:null, + addEventListener(){} + }; + const win={__JUCE__:{backend:native},ArSonApprovedNativeContract:protocol, + __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){}, + setTimeout(){return 0},clearTimeout(){},queueMicrotask(fn){fn();}}; + vm.runInNewContext(read("web/approved-native-bridge.js"), + {window:win,document:doc,performance:{now:()=>0},console},{timeout:1500}); + const base=acceptedFixture(); + base.graph.channels[0].fxRackBypassed=false; + base.graph.channels[0].inserts=[ + {id:"vst-live-1",catalogId:"eq-a",name:"EQ",bypassed:false}, + {id:"vst-live-2",catalogId:"comp-b",name:"Compressor",bypassed:true} + ]; + base.mixerSession={authority:"CHANNEL_ID",deviceEpoch:base.device.epoch, + routeRevision:base.graph.revision,rosterRevision:base.graph.rosterRevision, + channels:base.graph.channels,main:{db:0,mute:false}}; + listeners.get("arMixConsoleSnapshot")(base); + assert.equal(win.__ARMIX_APPROVED_NATIVE_GUI__.acceptedGraphConnected,true); + assert.equal(paints,1); + const track=scope.tracks[0]; + const button=()=>({ + attributes:new Map(), + setAttribute(key,val){this.attributes.set(key,String(val));}, + getAttribute(key){return this.attributes.get(key)||null;} + }); + const style=()=>({values:new Set(),toggle(name,enabled){ + if(enabled)this.values.add(name);else this.values.delete(name); + },contains(name){return this.values.has(name);}}); + const header=button(),rows=base.graph.channels[0].inserts.map((entry,i)=>{ + const power=button(); + return {dataset:{slot:String(i),insertId:entry.id},classList:style(), + querySelector:selector=>selector==='[data-action="slotPower"]'?power:null, + power}; + }); + const rack={dataset:{},classList:style(),querySelector(selector){ + return selector==='[data-action="fxOn"]'?header:null; + },querySelectorAll:selector=>selector==='.fxslot-row:not(.is-empty)'?rows:[]}; + const stableStrip={querySelector:selector=> + selector===".fx-section"?rack:null}; + strip=stableStrip; + const snapshot=clone(base); + snapshot.graph.channels[0].fxRackBypassed=true; + listeners.get("arMixConsoleSnapshot")(snapshot); + assert.equal(paints,1,"rack bypass must NOT replace the entire GUI channel DOM"); + assert.equal(strip,stableStrip); + assert.equal(track.fxOn,false); + assert.deepEqual(Array.from(track.slotBypass.slice(0,2)),[false,true], + "header bypass must never overwrite independent insert bypass preferences"); + assert.equal(rack.dataset.fxChainEnabled,"false"); + assert.equal(header.getAttribute("aria-pressed"),"false"); + assert.deepEqual(rows.map(r=>r.power.getAttribute("aria-pressed")),["false","false"]); + assert.deepEqual(rows.map(r=>r.dataset.fxSlotEnabled),["true","false"]); + assert.deepEqual(rows.map(r=>r.dataset.fxEffective),["false","false"]); + assert.ok(rows.every(r=>r.classList.contains("is-bypassed"))); + const restored=clone(snapshot); + restored.graph.channels[0].fxRackBypassed=false; + listeners.get("arMixConsoleSnapshot")(restored); + assert.equal(paints,1,"re-enabling the FX rack preserves mounted controls"); + assert.equal(track.fxOn,true); + assert.deepEqual(rows.map(r=>r.power.getAttribute("aria-pressed")),["true","false"]); + assert.deepEqual(rows.map(r=>r.dataset.fxEffective),["true","false"]); + const individual=clone(restored); + individual.graph.channels[0].inserts[0].bypassed=true; + listeners.get("arMixConsoleSnapshot")(individual); + assert.equal(paints,1,"slot power is a realtime scalar, not a topology edit"); + assert.deepEqual(Array.from(track.slotBypass.slice(0,2)),[true,true]); + assert.deepEqual(rows.map(r=>r.power.getAttribute("aria-pressed")),["false","false"]); + const replaced=clone(individual); + replaced.graph.channels[0].inserts[0].id="new-vst-instance"; + listeners.get("arMixConsoleSnapshot")(replaced); + assert.equal(paints,2,"an actual VST instance identity change MUST re-project"); }); +test("P0 startup banner never demands legacy Patch CH1 / Arm wizard",()=>{ + const bridge=read("web/approved-native-bridge.js"); + assert.match(bridge,/SELECT CHANNEL IN · NATIVE MONITOR AFTER ACK/); + assert.match(bridge,/NO CAPTURE INPUT · OPEN AUDIO I\/O/); + assert.match(bridge,/NO VERIFIED INPUT ROUTE · OPEN AUDIO I\/O/); + assert.doesNotMatch(bridge,/NO AUDIBLE OUTPUT · PATCH INPUT \+ ARM/); + assert.match(bridge,/const preparedFirstSound=session\?\.authority==="NONE"/); + assert.match(bridge,/const deviceReady=\(\)=>/); +}); +test("P0 FIRST SOUND G0 NONE authority exposes verified physical IN before any route and arms only after native ACK",()=>{ + const vm=require("node:vm"),sent=[],listeners=new Map(),renderedChoices=[]; + let win; + const tracks=Array.from({length:10},(_,i)=>({ + id:i+1,kind:"audio",name:"CH "+(i+1),input:"None", + output:"Master",format:"mono",fx:[],slotBypass:[],fxInsertIds:[] + })); + const scope={ + tracks,master:{id:50,kind:"master",output:"Master"}, + findTrack:el=>el?.track||null, + render(){renderedChoices.push([...win.__ARMIX_NATIVE_M2__.inputChoices(tracks[0])]);}, + stopDemo(){} + }; + const backend={ + emitEvent:(name,payload)=>sent.push({name,payload}), + addEventListener:(name,fn)=>listeners.set(name,fn) + }; + const info={textContent:""},preview={disabled:false}; + const document={ + readyState:"complete",documentElement:{dataset:{}},activeElement:null, + querySelector:()=>null, + getElementById:id=>id==="info"?info:id==="preview"?preview:null, + addEventListener(){} + }; + win={ + __JUCE__:{backend},ArSonApprovedNativeContract:protocol, + __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){}, + setTimeout(){return 0},clearTimeout(){},queueMicrotask(fn){fn();} + }; + vm.runInNewContext(read("web/approved-native-bridge.js"),{ + window:win,document,performance:{now:()=>0},console + },{timeout:1500}); + const boot=clone(fixtures.g0); + boot.device.backend="Windows Audio"; + boot.device.captureDevice="Real hardware microphone"; + boot.device.playbackDevice="Speakers"; + boot.legacyM4={active:true,routeAccepted:false,routingRevision:"12"}; + boot.mixerSession={authority:"NONE",deviceEpoch:boot.device.epoch, + routeRevision:"0",rosterRevision:"0",channels:[],main:{outputArmed:false}}; + listeners.get("arMixConsoleSnapshot")(boot); + assert.equal(win.__ARMIX_APPROVED_NATIVE_GUI__.acceptedGraphConnected,false, + "unpatched G0 must not masquerade as ChannelId PCM"); + assert.ok(renderedChoices.length>0, + "first real JUCE pin readback must refresh the previously empty selector"); + assert.deepEqual(renderedChoices.at(-1),["None","Mono · IN 1 [IN 1]"], + "the only offered input is the native enabled physical pin"); + const choose=(label)=>win.__ARMIX_NATIVE_M2__.consumeField({ + type:"change",target:{dataset:{field:"input"},value:label,track:tracks[4]} + }); + assert.equal(choose("Mono · IN 1 [IN 1]"),true); + const source=sent.filter(x=>x.name==="arMixAction"&& + x.payload.action==="routingSourceSwitch"); + assert.equal(source.length,1, + "G0 needs exactly one direct JUCE source command, no Start/Patch/Arm wizard"); + assert.deepEqual([ + source[0].payload.channel,source[0].payload.mode, + source[0].payload.left,source[0].payload.right, + source[0].payload.deviceEpoch,source[0].payload.revision + ],[4,"MONO",0,-1,69,12]); + assert.equal(sent.filter(x=>x.name==="arMixAction"&& + x.payload.action==="monitor").length,0, + "MAIN cannot auto-arm before accepted native source topology"); + // Native control-thread producer ACK, not a fake browser state. + const acceptedRows=Array.from({length:10},(_,i)=>({ + mode:i===4?"MONO":"NONE",left:i===4?0:-1, + right:-1,main:true + })); + listeners.get("arMixSourceSwitchAck")({ + requestId:source[0].payload.requestId,ok:true, + state:{ready:true,epoch:69,revision:13,hasAcceptedRoute:true, + nativeChannelIdPcmActive:false, + channelControls:Array.from({length:10},()=>({db:0,pan:0,mute:false,solo:false})), + acceptedRoute:{channels:acceptedRows}} + }); + const monitors=sent.filter(x=>x.name==="arMixAction"&& + x.payload.action==="monitor"); + assert.equal(monitors.length,1, + "first accepted input routed to MAIN authorizes one automatic safe listen"); + assert.equal(monitors[0].payload.value,true); + assert.equal(monitors[0].payload.expectedEpoch,69); + assert.equal(monitors[0].payload.expectedRevision,13); + assert.equal(tracks[4].input,"None", + "GUI must wait for a subsequent independent native readback"); + const none=clone(boot); + none.device.enabledInputs=[];none.device.inputEndpoints=[]; + listeners.get("arMixConsoleSnapshot")(none); + assert.deepEqual([...win.__ARMIX_NATIVE_M2__.inputChoices(tracks[0])],["None"]); + const commandsBefore=sent.filter(x=>x.name==="arMixAction"&& + x.payload.action==="routingSourceSwitch").length; + assert.equal(choose("Mono · IN 1 [IN 1]"),true); + assert.equal(sent.filter(x=>x.name==="arMixAction"&& + x.payload.action==="routingSourceSwitch").length,commandsBefore, + "never invent physical capture when the driver has no enabled input pins"); +}); +test("P0 native hardware IN remains selectable after ChannelId ownership, failed ACK drains the other channel",()=>{ + const vm=require("node:vm"),listeners=new Map(),sent=[],microtasks=[]; + let ordinal=100,wireId=400; + const scope={ + tracks:[],master:{id:1,name:"Master"},colors:["#456789"], + wireGraph:{validateCandidateGraph:()=>({ok:true})}, + make:(name,kind,color)=>({id:ordinal++,name,kind,color,selected:false}), + render(){}, + installGraph(tracks,main,edges){this.tracks=tracks;this.master=main;this.edges=edges;}, + allocateWireId:()=>wireId++,displayMeterDbfs(){},stopDemo(){}, + findTrack(el){return el.track;} + }; + const backend={emitEvent:(name,payload)=>sent.push({name,payload}), + addEventListener:(name,fn)=>listeners.set(name,fn)}; + const toast={textContent:"",hidden:true},info={textContent:""}; + const doc={ + readyState:"complete",documentElement:{dataset:{}}, + getElementById:id=>id==="info"?info:id==="armixNativeToast"?toast: + id==="preview"?{disabled:true}:null, + querySelector:()=>null,addEventListener(){} + }; + const win={__JUCE__:{backend},ArSonApprovedNativeContract:protocol, + __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){}, + setTimeout(){return 0},clearTimeout(){}, + queueMicrotask(fn){microtasks.push(fn);}}; + vm.runInNewContext(read("web/approved-native-bridge.js"), + {window:win,document:doc,performance:{now:()=>0},console},{timeout:1500}); + const base=acceptedFixture(); + const first=base.graph.channels[0],main=base.graph.mainChannelId; + const second=clone(first);second.id="9007199254740994"; + second.name="Harmony";second.primaryOutId=main; + base.graph.channels.splice(1,0,second); + base.graph.edges.push({...base.graph.edges[0], + edgeId:"9223372036854775809",from:second.id}); + base.device.enabledInputs=[0,1]; + base.device.inputEndpoints=[ + {id:"in:0",port:0,callback:0,label:"Mic A",active:true}, + {id:"in:1",port:1,callback:1,label:"Mic B",active:true} + ]; + // Deliberately stale M4 renderer bit. The accepted ChannelId callback is + // the authority for new physical source changes after BUS/WIRE cutover. + base.legacyM4={active:false,routeAccepted:false,routingRevision:"9"}; + base.mixerSession={authority:"CHANNEL_ID",deviceEpoch:base.device.epoch, + routeRevision:base.graph.revision,rosterRevision:base.graph.rosterRevision, + channels:base.graph.channels,main:{db:0,mute:false}}; + listeners.get("arMixConsoleSnapshot")(base); + assert.equal(win.__ARMIX_APPROVED_NATIVE_GUI__.acceptedGraphConnected,true); + assert.equal(scope.tracks.length,2); + const choose=(track,label)=>win.__ARMIX_NATIVE_M2__.consumeField({ + target:{track,dataset:{field:"input"},value:label},type:"change"}); + assert.equal(choose(scope.tracks[0],"Mono · Mic A [IN 1]"),true); + assert.equal(choose(scope.tracks[1],"Mono · Mic B [IN 2]"),true); + const sourceCommands=()=>sent.filter(x=>x.name==="arMixAction"&& + x.payload.action==="routingNativeSourcePatch"); + assert.equal(sourceCommands().length,1,"first source command sent to real JUCE gateway"); + assert.equal(sourceCommands()[0].payload.channelId,first.id); + assert.equal(sourceCommands()[0].payload.left,0); + const id=sourceCommands()[0].payload.requestId; + listeners.get("arMixNativeSourceAck")({requestId:id,ok:false,error:"STALE_NATIVE_SOURCE"}); + // Rejected source did not mutate graph; later authoritative readback is + // byte-identical. The queued SECOND channel must not be stranded. + listeners.get("arMixConsoleSnapshot")(base); + assert.ok(microtasks.length>0,"unchanged native graph must still drain queued source"); + while(microtasks.length)microtasks.shift()(); + assert.equal(sourceCommands().length,2); + assert.equal(sourceCommands()[1].payload.channelId,second.id); + assert.equal(sourceCommands()[1].payload.left,1); + assert.equal(sourceCommands()[1].payload.graphRevision,base.graph.revision); + assert.notEqual(sourceCommands()[1].payload.requestId,id); +}); test("M3 Windows bundle owns pointerup fader gesture and fences native FX keyboard reorder",()=>{ const builder=read("scripts/build_approved_native_gui.py"); const bridge=read("web/approved-native-bridge.js"); @@ -432,8 +1359,10 @@ test("native Windows operator can explicitly patch first physical input, arm and const js=read("web/approved-native-bridge.js"); const main=read("src/Main.cpp"); const engine=read("src/LiveAudioEngine.h"); - assert.match(js,/REAL AUDIO · FIRST SOUND/); - assert.match(js,/action:"audioSetup"/); + assert.match(js,/AUDIO \/ SAFETY/); + assert.match(js,/function openNativeAudioIO\(\)/); + assert.match(js,/action:"audioDeviceInventory"/); + assert.match(js,/action:"audioDeviceApply"/); assert.match(js,/d\.inputEndpoints\.filter\(p=>/); assert.match(js,/d\.enabledInputs\.includes\(p\.port\)/); assert.match(js,/action:"routingSourceSwitch",requestId:pendingSourceId/); @@ -447,10 +1376,90 @@ test("native Windows operator can explicitly patch first physical input, arm and assert.match(js,/NATIVE PATCH REJECTED:/); assert.match(js,/NO VERIFIED AUDIO DEVICE/); assert.match(js,/NATIVE PCM · HARDWARE FAT PENDING/); - assert.match(js,/MAIN ARMED · PCM NOT YET ADMITTED/); + assert.match(js,/MAIN MONITOR ON · PCM ADMISSION NOT VERIFIED/); assert.match(main,/action=="routingSourceSwitch"/); assert.match(main,/engine_\.liveOutputArmFault\(\)/); assert.match(main,/safe->emitApprovedNativeSnapshot\(\)/); assert.match(engine,/juce::String switchDryRoutingLabSource\(/); assert.match(engine,/setOutputMuted\(true\)/); }); + +// Held-pointer native fader regression runs within existing Windows / Chromium test gates. +require("./live_fader_held_drag.test.cjs"); + +test("live WIRE gain requires exact same-revision sample-target readback and unchanged edge identity",()=>{ + const base=acceptedFixture();delete base.graph.channels[0].primaryOutId; + base.graph.edges[0].primaryOutput=false;base.graph.edges[0].tap="POST_FADER"; + base.graph.capabilities.supportedOps.push("SET_WIRE_GAIN"); + const source=base.graph.channels[0].id,edge=base.graph.edges[0].edgeId; + const create=()=>{const sent=[];const c=protocol.createController({emit:(name,payload)=>sent.push({name,payload})}); + c.onSnapshot(clone(base));return {c,sent};}; + const accept=(c,r)=>c.onAck({requestId:r.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:base.device.epoch,graphRevision:base.graph.revision,rosterRevision:base.graph.rosterRevision}); + for(const corrupt of [s=>{s.graph.edges[0].gainLinear=.5;},s=>{s.graph.edges[0].tap="PRE_FADER";}, + s=>{s.graph.edges[0].primaryOutput=true;}]){ + const {c}=create();const r=c.intent("SET_WIRE_GAIN",source,{edgeId:edge,gainLinear:.25}); + assert.ok(r.ok);accept(c,r); + const bad=clone(base);bad.graph.edges[0].gainLinear=.25;corrupt(bad); + assert.equal(c.onSnapshot(bad),false); + assert.equal(c.state().lastError,"ACK_READBACK_EFFECT_MISMATCH"); + assert.equal(c.state().current.graph.edges[0].gainLinear,1); + } + const {c}=create();const r=c.intent("SET_WIRE_GAIN",source,{edgeId:edge,gainLinear:.25}); + accept(c,r);assert.equal(c.state().current.graph.edges[0].gainLinear,1); + const good=clone(base);good.graph.edges[0].gainLinear=.25; + assert.ok(c.onSnapshot(good));assert.equal(c.state().pending,null); + assert.equal(c.state().current.graph.revision,base.graph.revision); + assert.equal(c.state().current.graph.edges[0].gainLinear,.25); + assert.equal(c.intent("SET_WIRE_GAIN",source,{edgeId:"99999",gainLinear:.5}).ok,false); +}); + +test("native FX remove/reorder/transfer requires exact token, ACK and ordered readback",()=>{ + const setup=()=>{ + const base=acceptedFixture(),source=base.graph.channels.find(c=>c.role==='INPUT'); + source.inserts=[{id:'fx-a',catalogId:'a',name:'A',bypassed:false},{id:'fx-b',catalogId:'b',name:'B',bypassed:true}]; + const dest=clone(source);dest.id='9007199254740997';dest.inserts=[]; + base.graph.channels.splice(1,0,dest);base.graph.capabilities.supportedOps.push('MOVE_INSERT','REMOVE_INSERT'); + const emitted=[],controller=protocol.createController({emit:(n,p)=>emitted.push({n,p})}); + assert.ok(controller.onSnapshot(base));return {base,source,dest,controller,emitted}; + }; + const apply=(ctx,op,payload,change)=>{ + const {base,source,controller:c,emitted}=ctx; + assert.ok(c.intent(op,source.id,payload).ok);const request=emitted.findLast(e=>e.n==='arMixConsoleIntent').p; + c.onAck({requestId:request.requestId,status:'ACCEPTED',errorCode:'NONE',deviceEpoch:base.device.epoch, + graphRevision:'6',rosterRevision:'8'}); + assert.equal(c.state().current.graph.channels.find(x=>x.id===source.id).inserts.length,2,'ACK alone mutated FX'); + const next=clone(base);next.graph.revision='6';next.graph.rosterRevision='8';change(next); + assert.ok(c.onSnapshot(next));assert.equal(c.state().pending,null); + }; + let t=setup();apply(t,'MOVE_INSERT',{slot:0,instanceId:'fx-a',toChannelId:t.source.id,toSlot:1}, + s=>s.graph.channels[0].inserts.reverse()); + assert.deepEqual(t.controller.state().current.graph.channels[0].inserts.map(x=>x.id),['fx-b','fx-a']); + t=setup();apply(t,'MOVE_INSERT',{slot:0,instanceId:'fx-a',toChannelId:t.dest.id,toSlot:0},s=>{ + const moved=s.graph.channels[0].inserts.splice(0,1)[0];s.graph.channels[1].inserts.push(moved); + }); + assert.equal(t.controller.state().current.graph.channels[1].inserts[0].id,'fx-a'); + t=setup();apply(t,'REMOVE_INSERT',{slot:0,instanceId:'fx-a'},s=>s.graph.channels[0].inserts.splice(0,1)); + assert.equal(t.controller.state().current.graph.channels[0].inserts[0].id,'fx-b'); + t=setup();assert.equal(t.controller.intent('REMOVE_INSERT',t.source.id,{slot:0,instanceId:'stale'}).ok,false); + t=setup();const c=t.controller; + assert.ok(c.intent('MOVE_INSERT',t.source.id,{slot:0,instanceId:'fx-a',toChannelId:t.dest.id,toSlot:0}).ok); + const request=t.emitted.findLast(e=>e.n==='arMixConsoleIntent').p; + c.onAck({requestId:request.requestId,status:'ACCEPTED',errorCode:'NONE',deviceEpoch:t.base.device.epoch,graphRevision:'6',rosterRevision:'8'}); + const wrong=clone(t.base);wrong.graph.revision='6';wrong.graph.rosterRevision='8'; + wrong.graph.channels[1].inserts.push(clone(wrong.graph.channels[0].inserts[0])); + assert.equal(c.onSnapshot(wrong),false,'name/token copy cannot masquerade as MOVE'); + assert.equal(c.state().lastError,'ACK_READBACK_EFFECT_MISMATCH'); +}); + +test("native vendor editor retention follows current PCM ownership, not inactive M4 slots",()=>{ + const main=read('src/Main.cpp'),lab=read('src/LiveDryRoutingLab.h'); + assert.match(main,/engine_\.retainsRoutedFxEditor\(routedEditorEpoch_,routedEditorOwner_\)/); + assert.match(main,/routedEditorEpoch_=retainedEpoch/); + assert.match(main,/retainedEpoch=ep/); + assert.match(lab,/nativeAccepted_\.fxOwners->retainsEditor\(owner\)/); + const editor=main.slice(main.indexOf('if(owner && owner->processor)'),main.indexOf('if(owner && owner->processor)')+700); + assert.ok(editor.indexOf('closePluginEditor();') accepted publisher -> sample renderer. +// Offline PCM evidence, never an assertion of physical ASIO/VST vendor FAT. +#include "../integration/ApprovedNativeControlIntent.h" +#include "../engine/core/DynamicAcceptedSession.h" +#if defined(NDEBUG) +#undef NDEBUG +#endif +#include +#include +#include +#include +#include +#include + +static std::atomic allocations{0}; +void* operator new(std::size_t n) { + allocations.fetch_add(1,std::memory_order_relaxed); + if(auto* p=std::malloc(n?n:1))return p; + throw std::bad_alloc(); +} +void* operator new[](std::size_t n){return ::operator new(n);} +void operator delete(void* p) noexcept {std::free(p);} +void operator delete[](void* p) noexcept {std::free(p);} +void operator delete(void* p,std::size_t) noexcept {std::free(p);} +void operator delete[](void* p,std::size_t) noexcept {std::free(p);} + +using namespace armix::mixer; +using namespace armix::console; +static bool near(float a,float b){return std::abs(a-b)<3.e-5f;} +static juce::String textId(std::uint64_t n){return juce::String(std::to_string(n));} +static juce::var object(){return juce::var(new juce::DynamicObject());} +static void put(const juce::var& v,const char* k,const juce::var& value) { + v.getDynamicObject()->setProperty(k,value); +} +static const char* roleName(ChannelRole role) { + switch(role) { + case ChannelRole::input:return "INPUT"; + case ChannelRole::group:return "GROUP"; + case ChannelRole::fxReturn:return "FX_RETURN"; + case ChannelRole::main:return "MAIN"; + case ChannelRole::monitor:return "MONITOR"; + } + return "INVALID"; +} + +struct PcmHost { + DynamicAcceptedSession pcm; + DynamicGraphRequest io; + std::uint64_t epoch=91,serial=0; + std::array channels{}; + ChannelId bus{},main{}; + std::array a{},b{},mic{},left{},right{}; + std::array peaksL{},peaksR{}; + bool fxBypass=false; + std::array calls{}; + DynamicAcceptedSession::Result last; + juce::String lastError; + struct Result {bool accepted=false;const char* error="PCM_REJECTED";}; + + PcmHost() { + io.physicalInputs=3;io.maxFrames=64; + std::vector create; + for(int i=0;i<12;++i) { + ChannelEdit e;e.kind=ChannelEdit::Kind::add;e.position=i; + e.role=i<10?ChannelRole::input:i==10?ChannelRole::group:ChannelRole::main; + e.format=ProcessingFormat::stereo;e.text="CH "+std::to_string(i+1); + create.push_back(e); + } + auto added=pcm.edit(0,0,create,io,epoch,epoch,true); + assert(added.ok()); + for(int i=0;i<10;++i)channels[i]=added.edit.createdIds[i]; + bus=added.edit.createdIds[10];main=added.edit.createdIds[11]; + io.sources={{channels[2],0,1,true},{channels[6],2,-1,false}}; + std::vector links; + for(auto from:{channels[2],channels[3],channels[6],bus}) { + WireChange w;w.kind=WireChange::Kind::routeOnly; + w.from=from;w.to=main;links.push_back(w); + } + assert(pcm.wireTransaction(1,1,links,io,epoch,epoch,true).ok()); + a.fill(.25f);b.fill(.125f);mic.fill(.1f); + assert(pcm.setLiveMix(epoch,2,channels[3],.5f,0.f)); + } + Result applyNativeWireTransaction(std::uint64_t ep,std::uint64_t rev, + std::uint64_t roster,std::span edits) { + last=pcm.wireTransaction(roster,rev,edits,io,ep,epoch,false); + return {last.ok(),last.ok()?"":"PCM_REJECTED"}; + } + bool setNativeWireGain(std::uint64_t ep,std::uint64_t rev,std::uint64_t roster, + ChannelId source,std::uint64_t edgeId,float gain) { + return roster==pcm.acceptedRosterRevision()&& + pcm.setLiveWireGain(ep,rev,source,edgeId,gain); + } + bool setNativeInputMix(std::uint64_t ep,std::uint64_t rev, + ChannelId id,float gain,float pan) { + return pcm.setLiveMix(ep,rev,id,gain,pan); + } + bool setNativeBusMix(std::uint64_t ep,std::uint64_t rev, + ChannelId id,float gain,float pan) { + return pcm.setLiveMix(ep,rev,id,gain,pan); + } + bool setNativeInputMuteSolo(std::uint64_t ep,std::uint64_t rev, + ChannelId id,bool mute,bool solo) { + return pcm.setLiveMuteSolo(ep,rev,id,mute,solo); + } + // Serialize ONLY the accepted native roster/edge inventory. No guessed + // channel labels or browser graph can authorize a destination here. + juce::var readback() const { + const auto rev=pcm.acceptedGraphRevision(); + const auto* view=pcm.acceptedRouting(epoch,rev); + assert(view); + auto result=object();put(result,"graphRevision",textId(rev)); + put(result,"rosterRevision",textId(pcm.acceptedRosterRevision())); + juce::Array rows,edges,ops; + ops.add("NATIVE_APPLY_WIRE_TRANSACTION"); + ops.add("NATIVE_SET_WIRE_GAIN"); + for(std::size_t i=0;ichannels.size();++i) { + const auto& ch=view->channels[i]; + const auto* def=pcm.acceptedRoster().find(ch.id);assert(def); + auto row=object();put(row,"id",textId(ch.id.value)); + put(row,"name",juce::String(ch.name));put(row,"role",roleName(ch.role)); + put(row,"format",ch.format==ProcessingFormat::stereo?"STEREO":"MONO"); + put(row,"primaryOutput",textId(ch.primaryOutput.value)); + put(row,"fader",def->faderLinear);put(row,"pan",def->pan); + put(row,"mute",def->mute);put(row,"solo",def->solo); + put(row,"inserts",juce::var(juce::Array{})); + put(row,"peakL",peaksL[i]);put(row,"peakR",peaksR[i]);rows.add(row); + } + for(const auto& e:view->edges) { + auto edge=object();put(edge,"edgeId",textId(e.edgeId)); + put(edge,"from",textId(e.from.value));put(edge,"to",textId(e.to.value)); + put(edge,"gainLinear",e.gainLinear);put(edge,"primaryOutput",e.primaryOutput); + put(edge,"tap",e.preFader?"PRE_FADER":"POST_FADER");edges.add(edge); + } + put(result,"channels",juce::var(rows));put(result,"edges",juce::var(edges)); + put(result,"supportedOps",juce::var(ops));return result; + } + juce::var snapshot(const juce::var& native) const { + auto s=juce::JSON::parse(R"({"device":{"epoch":"91"},"graph":{ + "capabilities":{}},"telemetry":{}})"); + put(s.getProperty("device",{}),"epoch",textId(epoch)); + assert(projectApprovedNativeV8(s,native,true));return s; + } + juce::var request(const juce::var& edit) { + auto r=object();put(r,"requestId","pcm-wire-"+textId(++serial)); + put(r,"operation","APPLY_WIRE_TRANSACTION"); + put(r,"targetChannelId",edit.getProperty("from",{})); + put(r,"deviceEpoch",textId(epoch)); + put(r,"baseGraphRevision",textId(pcm.acceptedGraphRevision())); + put(r,"baseRosterRevision",textId(pcm.acceptedRosterRevision())); + auto payload=object();juce::Array edits;edits.add(edit); + put(payload,"changes",juce::var(edits));put(r,"payload",payload);return r; + } + bool apply(const juce::var& edit) { + const auto native=readback();const auto r=request(edit); + const auto decoded=translateApprovedNativeControl(r,snapshot(native),native); + assert(decoded.ok()); + lastError.clear(); + const bool result=executeApprovedNativeControl(*this,decoded.translated,&lastError); + pcm.pollRetirement();return result; + } + juce::var gainRequest(ChannelId source,std::uint64_t edge,float gain) { + auto edit=object();put(edit,"from",textId(source.value)); + auto r=request(edit);put(r,"operation","SET_WIRE_GAIN"); + auto payload=object();put(payload,"edgeId",textId(edge));put(payload,"gainLinear",gain); + put(r,"payload",payload);return r; + } + std::uint64_t sendEdge(ChannelId source,ChannelId destination) const { + for(const auto& edge:pcm.acceptedRoster().find(source)->sends) + if(edge.destination==destination)return edge.edgeId; + assert(false);return 0; + } + bool gain(ChannelId source,std::uint64_t edge,float value) { + const auto native=readback(); + const auto decoded=translateApprovedNativeControl(gainRequest(source,edge,value),snapshot(native),native); + assert(decoded.ok());return executeApprovedNativeControl(*this,decoded.translated); + } + void render() { + const float* pins[]{a.data(),b.data(),mic.data()};calls.fill(0); + const auto fx=[&](ChannelId id,float* l,float* r,int n) noexcept { + const auto slot=static_cast(id.value-1);++calls[slot]; + if(id==channels[3]&&!fxBypass) + for(int f=0;f(edge.getProperty("primaryOutput",false))) { + put(e,"edgeId",edge.getProperty("edgeId",{}));return e; + } + assert(false);return {}; +} +int main() { + PcmHost h;const auto ch3=h.channels[2],ch4=h.channels[3]; + constexpr float mono=.1f*.7071067811865475f; + h.render();assert(near(h.left[63],.25f+mono));assert(h.peaksL[3]==0.f); + // Ordinary WIRE CH03 -> CH04: same decoder used by Windows Main.cpp. + assert(h.apply(link("CONNECT",ch3,ch4))); + h.render();assert(near(h.peaksL[3],.0625f)); + assert(near(h.left[63],.3125f+mono)); // deliberate parallel path + const auto send=h.sendEdge(ch3,ch4),sameGraph=h.pcm.acceptedGraphRevision(), + sameRoster=h.pcm.acceptedRosterRevision(); + assert(h.gain(ch3,send,.5f)); + h.render();assert(h.left[0]>h.left[63]); // actual 64-sample gain slew + h.render();assert(near(h.peaksL[3],.03125f)&&near(h.left[63],.28125f+mono)); + assert(h.pcm.acceptedGraphRevision()==sameGraph&&h.pcm.acceptedRosterRevision()==sameRoster); + const auto* gainView=h.pcm.acceptedRouting(h.epoch,sameGraph); + assert(near(gainView->find(ch3)->parallelSends[0].gain,.5f)); + assert(near(h.pcm.acceptedRoster().find(ch3)->sends.back().gain,.5f)); + const auto gainNative=h.readback(),gainPublic=h.snapshot(gainNative); + assert(translateApprovedNativeControl(h.gainRequest(ch3,h.sendEdge(ch3,h.main),.5f), + gainPublic,gainNative).error=="WIRE_PRIMARY_GAIN_FIXED"); + assert(translateApprovedNativeControl(h.gainRequest(ch4,send,.5f), + gainPublic,gainNative).error=="WIRE_STALE_EDGE"); + assert(translateApprovedNativeControl(h.gainRequest(ch3,send,5.f), + gainPublic,gainNative).error=="INVALID_NATIVE_WIRE_GAIN"); + assert(!h.setNativeWireGain(h.epoch+1,sameGraph,sameRoster,ch3,send,.5f)); + assert(!h.setNativeWireGain(h.epoch,sameGraph,sameRoster-1,ch3,send,.5f)); + assert(h.gain(ch3,send,1.f));h.render();h.render(); + auto rb=h.readback();auto s=h.snapshot(rb); + assert(s.getProperty("graph",{}).getProperty("destinations",{}).size()==12); + assert(near(static_cast(s.getProperty("telemetry",{}) + .getProperty("channelMeterRmsPeak",{}).getProperty(textId(ch4.value),{}) + .getProperty("peakL",0.)),.0625f)); + // ROUTE ONLY promotes the existing send EdgeId without double-dry. + juce::String wireId; + for(const auto& edge:*rb.getProperty("edges",{}).getArray()) + if(edge.getProperty("from","").toString()==textId(ch3.value)&& + edge.getProperty("to","").toString()==textId(ch4.value)) + wireId=edge.getProperty("edgeId",{}).toString(); + assert(wireId.isNotEmpty()); + assert(h.apply(link("ROUTE_ONLY",ch3,ch4))); + h.render();assert(near(h.left[63],.0625f+mono)); + const auto* view=h.pcm.acceptedRouting(h.epoch,h.pcm.acceptedGraphRevision()); + assert(view->find(ch3)->primaryOutput==ch4); + bool retained=false; + for(const auto& e:view->edges)if(e.from==ch3&&e.to==ch4) + retained=textId(e.edgeId)==wireId; + assert(retained); + // Disconnect MAIN from receiver: both source and receiver DSP/meters + // remain alive. Only the unrelated CH07 still reaches MAIN. + const auto staleRemove=removePrimary(h,ch4); + const auto staleRequest=h.request(staleRemove); + assert(h.apply(staleRemove));h.render(); + assert(near(h.left[63],mono)&&near(h.peaksL[2],.25f)); + assert(near(h.peaksL[3],.0625f)&&h.calls[3]==1); + // Live fader, stereo PAN, FX bypass, MUTE/SOLO while source-only. + auto rev=h.pcm.acceptedGraphRevision(); + assert(h.pcm.setLiveMix(h.epoch,rev,ch4,.25f,1.f)); + h.render();h.render();assert(h.peaksL[3]==0.f&&near(h.peaksR[3],.015625f)); + h.fxBypass=true;h.render();assert(near(h.peaksR[3],.03125f)); + assert(h.pcm.setLiveMuteSolo(h.epoch,rev,ch4,true,false)); + h.render();h.render();assert(h.peaksR[3]==0.f); + assert(h.pcm.setLiveMuteSolo(h.epoch,rev,ch4,false,true)); + h.render();h.render();assert(near(h.peaksR[3],.03125f)); + assert(h.left[63]==0.f&&h.right[63]==0.f); // unrelated CH07 solo-suppressed + assert(h.pcm.setLiveMuteSolo(h.epoch,rev,ch4,false,false)); + assert(h.pcm.setLiveMix(h.epoch,rev,ch4,.5f,0.f));h.fxBypass=false; + h.render();h.render(); + // Serial CH03 -> CH04 -> BUS -> MAIN, then source-only at CH03. + assert(h.apply(link("ROUTE_ONLY",ch4,h.bus)));h.render(); + assert(near(h.left[63],.0625f+mono)&&near(h.peaksL[10],.0625f)); + assert(h.apply(removePrimary(h,ch3)));h.render(); + assert(near(h.peaksL[2],.25f)&&h.peaksL[3]==0.f); + assert(near(h.left[63],mono)); + // Reconnect without touching physical IN; retarget the SAME EdgeId. + assert(h.apply(link("ROUTE_ONLY",ch3,ch4)));h.render(); + auto retarget=removePrimary(h,ch3);put(retarget,"op","RETARGET"); + put(retarget,"to",textId(h.bus.value)); + assert(h.apply(retarget));h.render();assert(near(h.left[63],.25f+mono)); + // Hardware + WIRE are summed BEFORE receiver FX/fader, exactly once. + auto io=h.io;io.sources.push_back({ch4,0,1,true}); + ChannelEdit width;width.kind=ChannelEdit::Kind::setFormat; + width.id=ch4;width.format=ProcessingFormat::stereo; + assert(h.pcm.edit(h.pcm.acceptedRosterRevision(),h.pcm.acceptedGraphRevision(), + std::span(&width,1),io,h.epoch,h.epoch,true).ok()); + h.io=io;h.pcm.pollRetirement(); + assert(h.apply(link("ROUTE_ONLY",ch3,ch4)));h.render(); + assert(near(h.peaksL[3],.125f)&&near(h.left[63],.125f+mono)); + // Feedback cycle is rejected atomically by the actual graph compiler. + const auto beforeRev=h.pcm.acceptedGraphRevision(); + assert(!h.apply(link("CONNECT",ch4,ch3))); + assert(h.lastError=="PCM_REJECTED"); // preserve native reason through IPC executor + assert(h.last.native.graphError.fault==DynamicGraphFault::cycle); + assert(h.pcm.acceptedGraphRevision()==beforeRev);h.render(); + assert(near(h.left[63],.125f+mono)); + const auto current=h.readback();const auto accepted=h.snapshot(current); + assert(translateApprovedNativeControl(staleRequest,accepted,current).error== + "STALE_NATIVE_CONTROL_REVISION"); + auto wrongRole=juce::JSON::parse(juce::JSON::toString(current)); + put(wrongRole.getProperty("channels",{})[3],"role","MONITOR"); + auto fresh=h.request(link("CONNECT",ch3,ch4)); + assert(translateApprovedNativeControl(fresh,accepted,wrongRole).error== + "WIRE_UNSUPPORTED_DESTINATION"); + h.epoch=92; // stale generation must not receive cached source PCM + const float* pins[]{h.a.data(),h.b.data(),h.mic.data()}; + assert(!h.pcm.render(h.epoch,pins,3,h.left.data(),h.right.data(),64,false, + +[](ChannelId,float*,float*,int) noexcept {})); + assert(h.left[63]==0.f&&h.right[63]==0.f); + PcmHost reconnected;reconnected.render(); + assert(near(reconnected.left[63],.25f+mono)); + // Configure a dormant send BEFORE assigning its hardware IN. The + // remembered live level must seed its later real PCM preparation. + PcmHost dormant;const auto empty=dormant.channels[7],receiver=dormant.channels[3]; + assert(dormant.apply(link("CONNECT",empty,receiver))); + const auto dormantEdge=dormant.sendEdge(empty,receiver); + assert(dormant.gain(empty,dormantEdge,.25f));dormant.render(); + assert(dormant.peaksL[7]==0.f&&near(dormant.left[63],.25f+mono)); + dormant.io.sources.push_back({empty,0,1,true}); + width.id=empty; + assert(dormant.pcm.edit(dormant.pcm.acceptedRosterRevision(),dormant.pcm.acceptedGraphRevision(), + std::span(&width,1),dormant.io,dormant.epoch,dormant.epoch,true).ok()); + dormant.render();assert(near(dormant.peaksL[3],.015625f)); + assert(near(dormant.left[63],.265625f+mono)); +} diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index 335593c5a..dced419c2 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -33,6 +33,10 @@ struct NativeControlProbe { lastEpoch=e;lastRevision=r;lastId=id.value; lastMute=m;lastSolo=s;return true; } + bool setNativeBusMuteSolo(std::uint64_t e,std::uint64_t r, + armix::mixer::ChannelId id,bool m,bool s) { + return setNativeInputMuteSolo(e,r,id,m,s); + } }; static juce::var parse(const char* bytes) { auto json=juce::JSON::parse(juce::String::fromUTF8(bytes)); @@ -70,6 +74,38 @@ static juce::var realBusReadbackFixture() { ] })JSON"); } +static void nativeInsertCatalogInstanceProjectionRegression() { + auto source=realBusReadbackFixture(); + auto item=std::make_unique(); + item->setProperty("instanceId","vst3-instance-unique-7"); + item->setProperty("id","vendor.eq.catalog"); + item->setProperty("name","Vendor EQ"); + item->setProperty("bypassed",false); + juce::Array inserts; + inserts.add(juce::var(item.release())); + source.getProperty("channels",{})[0].getDynamicObject() + ->setProperty("inserts",juce::var(inserts)); + source.getProperty("channels",{})[0].getDynamicObject() + ->setProperty("fxRackBypassed",true); + auto snapshot=canonicalSnapshot(); + assert(projectApprovedNativeV8(snapshot,source,true)); + const auto live=snapshot.getProperty("graph",{}) + .getProperty("channels",{})[0].getProperty("inserts",{})[0]; + assert(live.getProperty("id","").toString()=="vst3-instance-unique-7"); + assert(live.getProperty("catalogId","").toString()=="vendor.eq.catalog"); + assert(!static_cast(live.getProperty("bypassed",true))); + assert(static_cast(snapshot.getProperty("graph",{}) + .getProperty("channels",{})[0].getProperty("fxRackBypassed",false))); + // A missing catalog token must not be projected as a verified processor. + auto invalid=juce::JSON::parse(juce::JSON::toString(source,false)); + invalid.getProperty("channels",{})[0].getProperty("inserts",{})[0] + .getDynamicObject()->removeProperty("id"); + auto untouched=canonicalSnapshot(); + const auto before=juce::JSON::toString(untouched,false); + assert(!projectApprovedNativeV8(untouched,invalid,true)); + assert(juce::JSON::toString(untouched,false)==before); +} + static void noMutationOnReject(juce::var snapshot,juce::var bus,bool admitted) { const auto before=juce::JSON::toString(snapshot,false); assert(!projectApprovedNativeV8(snapshot,bus,admitted)); @@ -243,6 +279,289 @@ static void controlIntentTranslationCases(const juce::var& canonical, } +// P1 WIRE gateway regression: all ChannelId/EdgeId conversion is validated +// on the CONTROL thread. A test probe is not a hardware PCM producer. +struct NativeWireProbe : NativeControlProbe { + std::uint64_t epoch=0,pcmRevision=0,rosterRevision=0; + std::vector applied; + // Match the actual LiveDryRoutingLab::NativeBusResult ABI. + struct Result { bool accepted=false; const char* error="NATIVE_REJECTED"; }; + Result applyNativeWireTransaction(std::uint64_t ep,std::uint64_t rev, + std::uint64_t roster,std::span edits) { + epoch=ep;pcmRevision=rev;rosterRevision=roster; + applied.assign(edits.begin(),edits.end()); + return {true,""}; + } +}; +// Processing-width intent is an admitted ChannelId operation, not the M4 +// channel ordinal. Probe tests exact 64-bit IDs without claiming hardware. +struct NativeFormatProbe : NativeControlProbe { + std::uint64_t epoch=0,revision=0,rosterRevision=0,id=0; + armix::mixer::ProcessingFormat width=armix::mixer::ProcessingFormat::mono; + struct Result {bool accepted=false;const char* error="REJECTED";}; + Result editNativeProcessingFormat(std::uint64_t ep,std::uint64_t rev, + std::uint64_t roster,armix::mixer::ChannelId target, + armix::mixer::ProcessingFormat next) { + epoch=ep;revision=rev;rosterRevision=roster; + id=target.value;width=next; + return {true,""}; + } +}; +static void approvedNativeMstTranslationRegression() { + auto installed=realBusReadbackFixture(); + juce::Array nativeOps; + nativeOps.add("NATIVE_SET_PROCESSING_FORMAT"); + installed.getDynamicObject()->setProperty("supportedOps",juce::var(nativeOps)); + auto accepted=canonicalSnapshot(); + assert(projectApprovedNativeV8(accepted,installed,true)); + juce::Array publicOps; + publicOps.add("SET_PROCESSING_FORMAT"); + accepted.getProperty("graph",{}).getProperty("capabilities",{}) + .getDynamicObject()->setProperty("supportedOps",juce::var(publicOps)); + auto payload=std::make_unique(); + payload->setProperty("format","STEREO"); + auto command=std::make_unique(); + command->setProperty("requestId","native-mst-test-1"); + command->setProperty("deviceEpoch","91"); + command->setProperty("baseGraphRevision","25"); + command->setProperty("baseRosterRevision","9"); + command->setProperty("targetChannelId","9007199254740993"); + command->setProperty("operation","SET_PROCESSING_FORMAT"); + command->setProperty("payload",juce::var(payload.release())); + auto intent=juce::var(command.release()); + const auto result=translateApprovedNativeControl(intent,accepted,installed); + assert(result.ok()); + assert(result.translated.getProperty("operation","").toString() + =="NATIVE_SET_PROCESSING_FORMAT"); + NativeFormatProbe probe; + assert(executeApprovedNativeControl(probe,result.translated)); + assert(probe.epoch==91 && probe.revision==25 && probe.rosterRevision==9); + assert(probe.id==9007199254740993ULL); + assert(probe.width==armix::mixer::ProcessingFormat::stereo); + + auto stale=juce::JSON::parse(juce::JSON::toString(intent,false)); + stale.getDynamicObject()->setProperty("baseRosterRevision","8"); + assert(!translateApprovedNativeControl(stale,accepted,installed).ok()); + auto wrong=juce::JSON::parse(juce::JSON::toString(intent,false)); + wrong.getProperty("payload",{}).getDynamicObject() + ->setProperty("format","MONO"); + assert(translateApprovedNativeControl(wrong,accepted,installed).error + =="INVALID_NATIVE_PROCESSING_FORMAT"); + auto main=juce::JSON::parse(juce::JSON::toString(intent,false)); + main.getDynamicObject()->setProperty("targetChannelId","18446744073709551615"); + assert(!translateApprovedNativeControl(main,accepted,installed).ok()); + auto noNative=juce::JSON::parse(juce::JSON::toString(installed,false)); + noNative.getDynamicObject()->setProperty( + "supportedOps",juce::var(juce::Array{})); + assert(!translateApprovedNativeControl(intent,accepted,noNative).ok()); +} + +static void approvedNativeGroupMuteSoloRegression() { + auto installed=realBusReadbackFixture(); + auto group=std::make_unique(); + group->setProperty("id","9007199254740994"); + group->setProperty("name","Bus A"); + group->setProperty("role","GROUP"); + group->setProperty("format","STEREO"); + group->setProperty("primaryOutput","0"); + group->setProperty("fader",1.0); + group->setProperty("pan",0.0); + group->setProperty("mute",false); + group->setProperty("solo",false); + group->setProperty("inserts",juce::var(juce::Array{})); + installed.getProperty("channels",{}).getArray()->add( + juce::var(group.release())); + juce::Array nativeOps;nativeOps.add("NATIVE_SET_BUS_MUTE_SOLO"); + installed.getDynamicObject()->setProperty("supportedOps",juce::var(nativeOps)); + auto publicSnapshot=canonicalSnapshot(); + assert(projectApprovedNativeV8(publicSnapshot,installed,true)); + juce::Array publicOps; + publicOps.add("SET_MUTE");publicOps.add("SET_SOLO"); + publicSnapshot.getProperty("graph",{}).getProperty("capabilities",{}) + .getDynamicObject()->setProperty("supportedOps",juce::var(publicOps)); + auto makeRequest=[&](const char* op,bool newValue,const char* id){ + auto payload=std::make_unique(); + payload->setProperty("value",newValue); + auto request=std::make_unique(); + request->setProperty("requestId","group-control-1"); + request->setProperty("deviceEpoch","91"); + request->setProperty("baseGraphRevision","25"); + request->setProperty("baseRosterRevision","9"); + request->setProperty("targetChannelId",id); + request->setProperty("operation",op); + request->setProperty("payload",juce::var(payload.release())); + return juce::var(request.release()); + }; + NativeControlProbe probe; + const auto busId="9007199254740994"; + auto muted=translateApprovedNativeControl( + makeRequest("SET_MUTE",true,busId),publicSnapshot,installed); + assert(muted.ok()); + assert(muted.translated.getProperty("operation","").toString()== + "NATIVE_SET_BUS_MUTE_SOLO"); + assert(executeApprovedNativeControl(probe,muted.translated)); + assert(probe.lastId==9007199254740994ULL&&probe.lastMute&&!probe.lastSolo); + auto solo=translateApprovedNativeControl( + makeRequest("SET_SOLO",true,busId),publicSnapshot,installed); + assert(solo.ok()); + assert(executeApprovedNativeControl(probe,solo.translated)); + assert(probe.lastSolo&&!probe.lastMute); + // MAIN remains immutable through the BUS-specific control gate. + auto denied=translateApprovedNativeControl( + makeRequest("SET_MUTE",true,"18446744073709551615"), + publicSnapshot,installed); + assert(!denied.ok()); +} + +static void approvedNativeVst3LoadContractRegression( + const juce::var& canonical,const juce::var& producer) { + // Native VST3 command admission is independent of a fabricated vendor + // fixture. No processor is created here: the real JUCE host resolves + // the opaque catalog key and the live publisher proves PCM after ACK. + auto accepted=juce::JSON::parse(juce::JSON::toString(canonical,false)); + auto bus=juce::JSON::parse(juce::JSON::toString(producer,false)); + juce::Array pubOps,nativeOps; + pubOps.add("LOAD_INSERT"); + nativeOps.add("NATIVE_LOAD_INSERT"); + accepted.getProperty("graph",{}).getProperty("capabilities",{}) + .getDynamicObject()->setProperty("supportedOps",juce::var(pubOps)); + bus.getDynamicObject()->setProperty("supportedOps",juce::var(nativeOps)); + auto payload=std::make_unique(); + payload->setProperty("catalogId","test.vendor.vst3"); + payload->setProperty("slot",0); + auto intent=std::make_unique(); + intent->setProperty("operation","LOAD_INSERT"); + intent->setProperty("requestId","fx-canonical-test"); + intent->setProperty("targetChannelId","9007199254740993"); + intent->setProperty("deviceEpoch","91"); + intent->setProperty("baseGraphRevision","25"); + intent->setProperty("baseRosterRevision","9"); + intent->setProperty("payload",juce::var(payload.release())); + const juce::var request(intent.release()); + const auto translated=translateApprovedNativeControl(request,accepted,bus); + assert(translated.ok()); + assert(translated.translated.getProperty("operation","").toString() + =="NATIVE_LOAD_INSERT"); + assert(translated.translated.getProperty("payload",{}) + .getProperty("catalogId","").toString()=="test.vendor.vst3"); + const auto noChange=[&](juce::var cmd,juce::var live,juce::var native){ + const auto before=juce::JSON::toString(native,false); + const auto result=translateApprovedNativeControl(cmd,live,native); + assert(!result.ok()&&!result.translated.isObject()); + assert(juce::JSON::toString(native,false)==before); + }; + auto stale=juce::JSON::parse(juce::JSON::toString(request,false)); + stale.getDynamicObject()->setProperty("baseGraphRevision","24"); + noChange(stale,accepted,bus); + auto gap=juce::JSON::parse(juce::JSON::toString(request,false)); + gap.getProperty("payload",{}).getDynamicObject()->setProperty("slot",1); + noChange(gap,accepted,bus); + auto empty=juce::JSON::parse(juce::JSON::toString(request,false)); + empty.getProperty("payload",{}).getDynamicObject() + ->setProperty("catalogId",""); + noChange(empty,accepted,bus); + auto unsupported=juce::JSON::parse(juce::JSON::toString(bus,false)); + unsupported.getDynamicObject()->setProperty( + "supportedOps",juce::var(juce::Array{})); + noChange(request,accepted,unsupported); + auto falseRole=juce::JSON::parse(juce::JSON::toString(accepted,false)); + falseRole.getProperty("graph",{}).getProperty("channels",{})[0] + .getDynamicObject()->setProperty("role","MAIN"); + noChange(request,falseRole,bus); +} +static void approvedWireTranslationRegression(const juce::var& canonical, + const juce::var& producer) { + auto accepted=juce::JSON::parse(juce::JSON::toString(canonical,false)); + auto bus=juce::JSON::parse(juce::JSON::toString(producer,false)); + juce::Array publicOps,nativeOps; + publicOps.add("APPLY_WIRE_TRANSACTION"); + nativeOps.add("NATIVE_APPLY_WIRE_TRANSACTION"); + accepted.getProperty("graph",{}).getProperty("capabilities",{}) + .getDynamicObject()->setProperty("supportedOps",juce::var(publicOps)); + bus.getDynamicObject()->setProperty("supportedOps",juce::var(nativeOps)); + const juce::String id="9007199254740993"; + const juce::String edge="9223372036854775808"; + auto request=std::make_unique(); + request->setProperty("requestId","p1-wire-control-test"); + request->setProperty("operation","APPLY_WIRE_TRANSACTION"); + request->setProperty("targetChannelId",id); + request->setProperty("deviceEpoch","91"); + request->setProperty("baseGraphRevision","25"); + request->setProperty("baseRosterRevision","9"); + auto one=std::make_unique(); + one->setProperty("op","REMOVE"); + one->setProperty("from",id); + one->setProperty("edgeId",edge); + juce::Array changes;changes.add(juce::var(one.release())); + auto payload=std::make_unique(); + payload->setProperty("changes",juce::var(changes)); + request->setProperty("payload",juce::var(payload.release())); + const auto original=juce::var(request.release()); + const auto translated=translateApprovedNativeControl(original,accepted,bus); + assert(translated.ok()); + assert(translated.translated.getProperty("operation","").toString() + =="NATIVE_APPLY_WIRE_TRANSACTION"); + NativeWireProbe native; + assert(executeApprovedNativeControl(native,translated.translated)); + assert(native.epoch==91&&native.pcmRevision==25&&native.rosterRevision==9); + assert(native.applied.size()==1); + assert(native.applied[0].kind==armix::mixer::WireChange::Kind::remove); + assert(native.applied[0].from.value==9007199254740993ULL); + assert(native.applied[0].edgeId==9223372036854775808ULL); + // The accepted ChannelId MAIN is a valid ROUTE_ONLY target from a + // real UI OUT gesture (even though the decoder formerly rejected it). + auto reconnect=juce::JSON::parse(juce::JSON::toString(original,false)); + auto wire=std::make_unique(); + wire->setProperty("op","ROUTE_ONLY"); + wire->setProperty("from",id); + wire->setProperty("to","18446744073709551615"); + wire->setProperty("tap","POST_FADER"); + wire->setProperty("gainLinear",1.0); + juce::Array reconnectChanges; + reconnectChanges.add(juce::var(wire.release())); + reconnect.getProperty("payload",{}).getDynamicObject() + ->setProperty("changes",juce::var(reconnectChanges)); + auto back=translateApprovedNativeControl(reconnect,accepted,bus); + assert(back.ok()); + assert(executeApprovedNativeControl(native,back.translated)); + assert(native.applied.size()==1); + assert(native.applied.front().kind==armix::mixer::WireChange::Kind::routeOnly); + assert(native.applied.front().to.value==18446744073709551615ULL); + + auto fail=[&](juce::var intent,juce::var acceptedState,juce::var nativeState){ + const auto before=juce::JSON::toString(nativeState,false); + const auto result=translateApprovedNativeControl(intent,acceptedState,nativeState); + assert(!result.ok());assert(!result.translated.isObject()); + assert(juce::JSON::toString(nativeState,false)==before); + return result.error; + }; + auto forged=juce::JSON::parse(juce::JSON::toString(original,false)); + forged.getProperty("payload",{}).getProperty("changes",{})[0] + .getDynamicObject()->setProperty("edgeId","9223372036854775807"); + assert(fail(forged,accepted,bus)=="WIRE_STALE_EDGE"); + auto wrongSource=juce::JSON::parse(juce::JSON::toString(original,false)); + wrongSource.getProperty("payload",{}).getProperty("changes",{})[0] + .getDynamicObject()->setProperty("from","18446744073709551615"); + assert(fail(wrongSource,accepted,bus)=="WIRE_SOURCE_OR_OPERATION_INVALID"); + auto stale=juce::JSON::parse(juce::JSON::toString(original,false)); + stale.getDynamicObject()->setProperty("baseGraphRevision","24"); + assert(fail(stale,accepted,bus)=="STALE_NATIVE_CONTROL_REVISION"); + auto noNative=juce::JSON::parse(juce::JSON::toString(bus,false)); + noNative.getDynamicObject()->setProperty("supportedOps", + juce::var(juce::Array{})); + assert(fail(original,accepted,noNative)=="NATIVE_WIRE_NOT_ADMITTED"); + auto fractionalMain=juce::JSON::parse(juce::JSON::toString(reconnect,false)); + fractionalMain.getProperty("payload",{}).getProperty("changes",{})[0] + .getDynamicObject()->setProperty("gainLinear",0.8); + assert(fail(fractionalMain,accepted,bus)=="WIRE_UNSUPPORTED_TAP_OR_GAIN"); + auto invalidTap=juce::JSON::parse(juce::JSON::toString(original,false)); + auto edit=invalidTap.getProperty("payload",{}).getProperty("changes",{})[0]; + edit.getDynamicObject()->setProperty("op","CONNECT"); + edit.getDynamicObject()->setProperty("to","18446744073709551615"); + edit.getDynamicObject()->setProperty("tap","PRE_FADER"); + edit.getDynamicObject()->setProperty("gainLinear",1.0); + assert(fail(invalidTap,accepted,bus)=="WIRE_UNSUPPORTED_TAP_OR_GAIN"); +} static void installedCallbackAdmissionRegression(const juce::var& rawBus) { // This fixture is ONLY accepted native readback; not a hardware device. // It proves Main.cpp cannot publish a fake live graph from G0/M4 JSON. @@ -260,6 +579,11 @@ static void installedCallbackAdmissionRegression(const juce::var& rawBus) { "nativeChannelIdPcmActive":true,"epoch":91}})JSON"); live.getProperty("dryRoutingLab",{}).getDynamicObject() ->setProperty("nativeBus",rawBus); + // The physical master is post-ChannelId host PCM, not the generic + // roster's default 0 dB. Keep its accepted gain and mute across native + // projection, even when the source input fader changes independently. + live.getDynamicObject()->setProperty("masterDb",-13.5); + live.getDynamicObject()->setProperty("masterMute",true); auto fail=[&](const juce::var& candidate) { auto before=juce::JSON::toString(snap,false); assert(!projectInstalledNativeChannelIdGraph(snap,candidate)); @@ -290,6 +614,29 @@ static void installedCallbackAdmissionRegression(const juce::var& rawBus) { fail(deny); assert(synchronizeApprovedRouteDeviceEpoch(snap,live)); assert(projectInstalledNativeChannelIdGraph(snap,live)); + const auto projectedRows=snap.getProperty("graph",{}).getProperty("channels",{}); + const auto* projected=projectedRows.getArray(); + assert(projected && projected->size()==2); + bool physicalMasterFound=false; + for(const auto& row:*projected) + if(row.getProperty("role",{}).toString()=="MAIN") { + const auto ctl=row.getProperty("controls",{}); + assert(std::abs(static_cast(ctl.getProperty("faderDb",{})) + -(-13.5))<0.00001); + assert(static_cast(ctl.getProperty("mute",false))); + physicalMasterFound=true; + } + assert(physicalMasterFound); + publishAuthoritativeMixerSession(snap); + const auto session=snap.getProperty("mixerSession",{}); + assert(session.getProperty("authority","").toString()=="CHANNEL_ID"); + assert(session.getProperty("deviceEpoch","").toString()=="91"); + assert(session.getProperty("routeRevision","").toString()=="25"); + assert(session.getProperty("channels",{}).getArray()->size()==2); + assert(session.getProperty("channels",{})[0].getProperty("id","").toString() + =="9007199254740993"); + assert(std::abs(static_cast(session.getProperty("main",{}) + .getProperty("db",0.))-(-13.5))<0.00001); // Real restart: lab routing epoch counts STOP+START, unlike M2 // deviceStartCount. This G0-to-native authority switch must advance. auto disconnected=canonicalSnapshot(); @@ -309,6 +656,9 @@ static void installedCallbackAdmissionRegression(const juce::var& rawBus) { assert(disconnected.getProperty("device",{}) .getProperty("epoch","").toString()=="93"); assert(!projectInstalledNativeChannelIdGraph(disconnected,dead)); + publishAuthoritativeMixerSession(disconnected); + assert(disconnected.getProperty("mixerSession",{}) + .getProperty("authority","").toString()=="NONE"); const auto ghost=disconnected.getProperty("graph",{}); assert(!static_cast(ghost.getProperty("capabilities",{}) .getProperty("callbackOwnsChannelIds",false))); @@ -332,6 +682,35 @@ static void installedCallbackAdmissionRegression(const juce::var& rawBus) { assert(graph.getProperty("channels",{}).getArray()->size()==2); assert(graph.getProperty("capabilities",{}) .getProperty("supportedOps",{}).getArray()->isEmpty()); + // Only a real installed callback may advertise WIRE; G0 and producer + // snapshots without the corresponding capability remain fail-closed. + auto wiredBus=juce::JSON::parse(juce::JSON::toString(rawBus,false)); + juce::Array nativeWireOps; + nativeWireOps.add("NATIVE_APPLY_WIRE_TRANSACTION"); + wiredBus.getDynamicObject()->setProperty( + "supportedOps",juce::var(nativeWireOps)); + auto wiredLive=juce::JSON::parse(juce::JSON::toString(live,false)); + wiredLive.getProperty("dryRoutingLab",{}).getDynamicObject() + ->setProperty("nativeBus",wiredBus); + auto wiredSnap=canonicalSnapshot(); + auto* wiredDevice=wiredSnap.getProperty("device",{}).getDynamicObject(); + wiredDevice->setProperty("sampleRate",48000.0); + wiredDevice->setProperty("bufferFrames",256); + wiredDevice->setProperty("enabledInputs",juce::var(inputs)); + wiredDevice->setProperty("enabledOutputs",juce::var(outputs)); + assert(synchronizeApprovedRouteDeviceEpoch(wiredSnap,wiredLive)); + assert(projectInstalledNativeChannelIdGraph(wiredSnap,wiredLive)); + const auto wireCaps=wiredSnap.getProperty("graph",{}) + .getProperty("capabilities",{}).getProperty("supportedOps",{}); + assert(wireCaps.getArray()&& + wireCaps.getArray()->contains("APPLY_WIRE_TRANSACTION")); + nativeWireOps.add("NATIVE_CREATE_GROUP_SELECTED"); + wiredBus.getDynamicObject()->setProperty( + "supportedOps",juce::var(nativeWireOps)); + assert(projectInstalledNativeChannelIdGraph(wiredSnap,wiredLive)); + assert(wiredSnap.getProperty("graph",{}).getProperty("capabilities",{}) + .getProperty("supportedOps",{}).getArray()->contains("CREATE_GROUP")); + assert(!static_cast(wiredSnap.getProperty("productionCallbackLive",false))); assert(!static_cast(snap.getProperty("productionCallbackLive",false))); } @@ -368,6 +747,58 @@ static void firstSoundRouteAdmissionRegression() { assert(publishVerifiedFirstSoundState(snapshot,live)); m4=snapshot.getProperty("legacyM4",{}); assert(static_cast(m4.getProperty("routeAccepted",false))); + // First hardware choice may target CH05 (not hardcoded CH01). All ten + // rows must project from native accepted data, never demo INPUT 1. + juce::Array rows; + for(int i=0;i<10;++i) { + auto row=std::make_unique(); + row->setProperty("mode",i==4?"MONO":"NONE"); + row->setProperty("left",i==4?0:-1); + row->setProperty("right",-1); + row->setProperty("main",true); + rows.add(juce::var(row.release())); + } + auto accepted=std::make_unique(); + accepted->setProperty("channels",juce::var(rows)); + live.getProperty("dryRoutingLab",{}).getDynamicObject()->setProperty( + "acceptedRoute",juce::var(accepted.release())); + assert(publishVerifiedFirstSoundState(snapshot,live)); + m4=snapshot.getProperty("legacyM4",{}); + const auto physicalRows=m4.getProperty("channels",{}); + assert(physicalRows.isArray()); + assert(physicalRows.getArray()->size()==10); + assert(physicalRows.getArray()->getReference(4).getProperty("mode",{}).toString()=="MONO"); + assert(static_cast(physicalRows.getArray()->getReference(4).getProperty("left",-1))==0); + // One internal BUS must NOT invalidate the ten-lane native projection + // or erase physical CH05 input/controls, which are still accepted PCM. + auto withBus=juce::JSON::parse(juce::JSON::toString(live,false)); + withBus.getProperty("dryRoutingLab",{}) + .getProperty("acceptedRoute",{}).getProperty("channels",{}) + .getArray()->getReference(2).getDynamicObject()->setProperty("mode","BUS"); + assert(publishVerifiedFirstSoundState(snapshot,withBus)); + auto busReadback=snapshot.getProperty("legacyM4",{}).getProperty("channels",{}); + assert(busReadback.isArray()&&busReadback.getArray()->size()==10); + assert(busReadback[2].getProperty("mode","").toString()=="BUS"); + assert(static_cast(busReadback[2].getProperty("left",0))==-1); + assert(busReadback[4].getProperty("mode","").toString()=="MONO"); + assert(static_cast(busReadback[4].getProperty("left",-1))==0); + auto invalidBus=juce::JSON::parse(juce::JSON::toString(withBus,false)); + invalidBus.getProperty("dryRoutingLab",{}) + .getProperty("acceptedRoute",{}).getProperty("channels",{}) + .getArray()->getReference(2).getDynamicObject()->setProperty("left",7); + assert(publishVerifiedFirstSoundState(snapshot,invalidBus)); + assert(snapshot.getProperty("legacyM4",{}) + .getProperty("channels",{}).getArray()->isEmpty()); + assert(publishVerifiedFirstSoundState(snapshot,live)); + // Disabled hardware input is never presented as accepted physical PCM. + auto badPins=juce::JSON::parse(juce::JSON::toString(live,false)); + badPins.getProperty("dryRoutingLab",{}).getProperty("acceptedRoute",{}) + .getProperty("channels",{}).getArray()->getReference(4) + .getDynamicObject()->setProperty("left",7); + assert(publishVerifiedFirstSoundState(snapshot,badPins)); + assert(snapshot.getProperty("legacyM4",{}).getProperty("channels",{}).getArray()->isEmpty()); + // Restore valid accepted rows for the stale epoch/fail-closed matrix. + assert(publishVerifiedFirstSoundState(snapshot,live)); auto reject=[&](const juce::var& degraded) { auto fresh=juce::JSON::parse(juce::JSON::toString(snapshot,false)); assert(!publishVerifiedFirstSoundState(fresh,degraded)); @@ -398,6 +829,66 @@ static void firstSoundRouteAdmissionRegression() { assert(!publishVerifiedFirstSoundState(withoutInput,live)); } +// Control-only fixture: validates exclusive M4 session normalization, +// never claims that fixture data is a hardware PCM recording. +static void milestoneAM4SessionProjectionRegression() { + auto snapshot=canonicalSnapshot(); + snapshot.getProperty("device",{}).getDynamicObject()->setProperty("epoch","33"); + auto m4=std::make_unique(); + m4->setProperty("active",true); + m4->setProperty("routeAccepted",true); + m4->setProperty("nativeBusStructural",false); + m4->setProperty("routingRevision","19"); + m4->setProperty("masterDb",-7.5); + m4->setProperty("masterMute",false); + juce::Array sources,controls,peaksL,peaksR,rackFlags; + for(int i=0;i<10;++i) { + auto src=std::make_unique(); + src->setProperty("mode",i==4?"MONO":"NONE"); + src->setProperty("left",i==4?2:-1); + src->setProperty("right",-1); + src->setProperty("main",true); + sources.add(juce::var(src.release())); + auto ctl=std::make_unique(); + ctl->setProperty("db",i==4?-6.:0.); + ctl->setProperty("pan",i==4?25.:0.); + ctl->setProperty("mute",false); + ctl->setProperty("solo",false); + controls.add(juce::var(ctl.release())); + peaksL.add(i==4?0.125:0.0); + peaksR.add(i==4?0.25:0.0); + rackFlags.add(i==4); + } + m4->setProperty("channels",juce::var(sources)); + m4->setProperty("channelControls",juce::var(controls)); + m4->setProperty("channelPeaksL",juce::var(peaksL)); + m4->setProperty("channelPeaksR",juce::var(peaksR)); + m4->setProperty("fxRackBypassed",juce::var(rackFlags)); + snapshot.getDynamicObject()->setProperty("legacyM4",juce::var(m4.release())); + publishAuthoritativeMixerSession(snapshot); + const auto session=snapshot.getProperty("mixerSession",{}); + assert(session.getProperty("authority","").toString()=="M4"); + assert(session.getProperty("deviceEpoch","").toString()=="33"); + assert(session.getProperty("routeRevision","").toString()=="19"); + const auto rows=session.getProperty("channels",{}); + assert(rows.isArray()&&rows.getArray()->size()==10); + assert(rows[4].getProperty("id","").toString()=="m4:05"); + assert(rows[4].getProperty("fxRackBypassed",{}).isBool()); + assert(static_cast(rows[4].getProperty("fxRackBypassed",false))); + assert(std::abs(static_cast(rows[4].getProperty("controls",{}) + .getProperty("faderDb",0.0))+6.)<0.00001); + assert(std::abs(static_cast(rows[4].getProperty("controls",{}) + .getProperty("pan",0.0))-.25)<0.00001); + assert(std::abs(static_cast(session.getProperty("main",{}) + .getProperty("db",0.0))+7.5)<0.00001); + // Reject corrupt producer readback atomically, not just the bad strip. + snapshot.getProperty("legacyM4",{}).getProperty("channelControls",{}) + .getArray()->getReference(4).getDynamicObject()->setProperty("db",55.); + publishAuthoritativeMixerSession(snapshot); + assert(snapshot.getProperty("mixerSession",{}) + .getProperty("authority","").toString()=="NONE"); +} + static void firstSoundMeasuredSignalEvidenceRegression() { auto live=parse(R"JSON({ "connected":true,"directRouteAuthorized":true, @@ -457,7 +948,39 @@ static void firstSoundMeasuredSignalEvidenceRegression() { assert(!static_cast(signal(live,true,true).getProperty("captureObserved",true))); } +static void retainedDocumentDoesNotAdmitPcm() { + auto snapshot=canonicalSnapshot(); + snapshot.getProperty("device",{}).getDynamicObject() + ->setProperty("outputArmed",false); + auto bus=realBusReadbackFixture(); + auto live=parse(R"JSON({ + "masterDb":-9.0,"masterMute":true, + "dryRoutingLab":{"nativeChannelIdPcmActive":false} + })JSON"); + auto* route=live.getProperty("dryRoutingLab",{}).getDynamicObject(); + route->setProperty("nativeBus",bus); + assert(!projectRetainedNativeChannelIdGraph(snapshot,live)); + route->setProperty("retainedNativeBus",bus); + assert(projectRetainedNativeChannelIdGraph(snapshot,live)); + publishAuthoritativeMixerSession(snapshot); + const auto graph=snapshot.getProperty("graph",{}); + const auto caps=graph.getProperty("capabilities",{}); + assert(graph.getProperty("bindingState",{}).toString()=="NEEDS_REMAP"); + assert(graph.getProperty("channels",{})[0].getProperty("id",{}).toString()=="9007199254740993"); + assert(graph.getProperty("edges",{})[0].getProperty("edgeId",{}).toString()=="9223372036854775808"); + assert(!static_cast(caps.getProperty("callbackOwnsChannelIds",true))); + assert(caps.getProperty("supportedOps",{}).getArray()->isEmpty()); + assert(snapshot.getProperty("telemetry",{}).getProperty("channelMeterRmsPeak",{}) + .getDynamicObject()->getProperties().size()==0); + const auto session=snapshot.getProperty("mixerSession",{}); + assert(session.getProperty("bindingState",{}).toString()=="NEEDS_REMAP"); + assert(static_cast(session.getProperty("main",{}).getProperty("db",0.0))==-9.0); + route->setProperty("nativeChannelIdPcmActive",true); + assert(!projectRetainedNativeChannelIdGraph(snapshot,live)); +} + int main() { + retainedDocumentDoesNotAdmitPcm(); auto snap=canonicalSnapshot(); auto bus=realBusReadbackFixture(); // Merely having matching native-shaped JSON cannot enable fake LIVE. @@ -488,9 +1011,19 @@ int main() { assert(!static_cast(snap.getProperty("productionCallbackLive",false))); controlIntentTranslationCases(snap,bus); + nativeInsertCatalogInstanceProjectionRegression(); + approvedNativeMstTranslationRegression(); + approvedNativeGroupMuteSoloRegression(); + approvedNativeVst3LoadContractRegression(snap,bus); + approvedWireTranslationRegression(snap,bus); installedCallbackAdmissionRegression(bus); firstSoundRouteAdmissionRegression(); + milestoneAM4SessionProjectionRegression(); firstSoundMeasuredSignalEvidenceRegression(); + auto unadmitted=canonicalSnapshot(); + publishAuthoritativeMixerSession(unadmitted); + assert(unadmitted.getProperty("mixerSession",{}) + .getProperty("authority","").toString()=="NONE"); auto missingMain=realBusReadbackFixture(); missingMain.getProperty("channels",{})[1].getDynamicObject() diff --git a/tests/approved_native_wire_gain_smoke.py b/tests/approved_native_wire_gain_smoke.py new file mode 100644 index 000000000..23880055c --- /dev/null +++ b/tests/approved_native_wire_gain_smoke.py @@ -0,0 +1,154 @@ +"""Actual compiled native DOM/keyboard -> intent -> ACK -> accepted readback. + +The WebView backend is emulated for UI isolation. Native PCM/sample/ramp +evidence comes from P0ApprovedDecoderChannelToChannelAndSourceOnlyPCM CTest. +""" +import copy +import importlib.util +import json +from pathlib import Path +import tempfile +from playwright.sync_api import sync_playwright + +ROOT = Path(__file__).resolve().parents[1] +SOURCE, RECEIVER, MAIN = "9007199254740993", "9007199254740995", "18446744073709551615" +SEND = "9223372036854775810" + + +def snapshot(): + s = json.loads((ROOT / "integration/console-v6/fixtures.json").read_text())["g0"] + g = s["graph"] + g.update(revision="2", rosterRevision="2", mainChannelId=MAIN) + g["capabilities"].update(callbackOwnsChannelIds=True, + supportedOps=["SET_WIRE_GAIN", "APPLY_WIRE_TRANSACTION"]) + g["channels"] = [ + {"id": ident, "name": name, "role": role, "processingFormat": "STEREO", + "controls": {"faderDb": 0, "pan": 0, "mute": False, "solo": False}, + "inserts": [], "sends": []} + for ident, name, role in [(SOURCE, "CH03", "INPUT"), + (RECEIVER, "CH04", "INPUT"), (MAIN, "MAIN", "MAIN")]] + for ch in g["channels"][:2]: + ch["primaryOutId"] = MAIN + g["edges"] = [ + {"edgeId": "9223372036854775808", "from": SOURCE, "to": MAIN, "primaryOutput": True, "gainLinear": 1}, + {"edgeId": SEND, "from": SOURCE, "to": RECEIVER, "primaryOutput": False, "gainLinear": .5}, + {"edgeId": "9223372036854775812", "from": RECEIVER, "to": MAIN, "primaryOutput": True, "gainLinear": 1}] + for edge in g["edges"]: + edge.update(tap="POST_FADER", enabled=True, signalKind="AUDIO") + g["destinations"] = [{k: ch[k] for k in ("id", "role", "name")} for ch in g["channels"]] + s["mixerSession"] = {"authority": "CHANNEL_ID", "deviceEpoch": s["device"]["epoch"], + "routeRevision": "2", "rosterRevision": "2", "channels": copy.deepcopy(g["channels"]), + "main": {"db": 0, "mute": False}} + return s + + +def emit(page, name, payload): + page.evaluate("([name,payload])=>window.__nativeListeners.get(name)?.(payload)", [name, payload]) + + +def ack(page, state, intent): + emit(page, "arMixConsoleAck", {"requestId": intent["requestId"], "status": "ACCEPTED", + "errorCode": "NONE", "deviceEpoch": state["device"]["epoch"], + "graphRevision": state["graph"]["revision"], "rosterRevision": state["graph"]["rosterRevision"]}) + + +def main(): + spec = importlib.util.spec_from_file_location("native_bundle", ROOT / "scripts/build_approved_native_gui.py") + bundle = importlib.util.module_from_spec(spec) + spec.loader.exec_module(bundle) + with tempfile.TemporaryDirectory(prefix="arsonmix-native-send-") as directory: + out = Path(directory) + bundle.stage(out) + with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + for width, height in [(1366, 768), (1680, 900), (1920, 1080)]: + page = browser.new_page(viewport={"width": width, "height": height}) + errors = [] + page.on("pageerror", lambda error: errors.append(str(error))) + page.add_init_script("""window.__nativeListeners=new Map();window.__nativeIntents=[]; + window.__JUCE__={backend:{ + emitEvent(name,payload){if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload);}, + addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") + page.goto((out / "index.html").as_uri()) + page.wait_for_function("()=>window.__ARMIX_NATIVE_M2__?.enabled") + state = snapshot() + emit(page, "arMixConsoleSnapshot", state) + page.wait_for_selector('#tracks .strip[data-id="2"]') + if "collapsed-send" in (page.locator(".console-body").get_attribute("class") or ""): + page.locator('.section-rail [data-section="send"]').click() + page.locator('#tracks .strip[data-id="1"] .wire-node-out').click() + knob = page.locator('#tracks .strip[data-id="2"] .wire-gain') + knob.wait_for(state="visible") + page.evaluate("""()=>{window.__heldWireInput=document.querySelector('#tracks .strip[data-id="2"] .wire-gain'); + window.__heldStrip=document.querySelector('#tracks .strip[data-id="2"]');}""") + knob.focus() + knob.press("End") + page.wait_for_function("()=>window.__nativeIntents.filter(x=>x.operation==='SET_WIRE_GAIN').length===1") + first = page.evaluate("()=>window.__nativeIntents.at(-1)") + assert first["payload"]["edgeId"] == SEND + knob.press("Home") + page.wait_for_timeout(70) + assert page.evaluate("()=>window.__nativeIntents.length") == 1, "must coalesce behind ACK" + state["graph"]["edges"][1]["gainLinear"] = first["payload"]["gainLinear"] + ack(page, state, first) + emit(page, "arMixConsoleSnapshot", state) + page.wait_for_function("()=>window.__nativeIntents.length===2") + assert page.evaluate("()=>window.__heldWireInput===document.querySelector('#tracks .strip[data-id=\"2\"] .wire-gain')"), "ACK detached held gain control" + latest = page.evaluate("()=>window.__nativeIntents.at(-1)") + assert abs(latest["payload"]["gainLinear"] - .001) < 1e-8 + state["graph"]["edges"][1]["gainLinear"] = latest["payload"]["gainLinear"] + ack(page, state, latest) + emit(page, "arMixConsoleSnapshot", state) + knob.press("Tab") + emit(page, "arMixConsoleSnapshot", state) + assert page.evaluate("()=>window.__heldStrip===document.querySelector('#tracks .strip[data-id=\"2\"]')"), "scalar edit rebuilt strip" + assert float(page.locator('#tracks .strip[data-id="2"] .wire-gain').input_value()) == -60 + # Drag the actual receiving knob with native ACKs mid-gesture. + pot = knob.locator("..").bounding_box() + assert pot + x, y = pot["x"]+pot["width"]/2, pot["y"]+pot["height"]/2 + page.mouse.move(x,y) + page.mouse.down() + page.mouse.move(x,y-32,steps=5) + page.wait_for_function("()=>window.__nativeIntents.length===3") + coarse = page.evaluate("()=>window.__nativeIntents.at(-1)") + assert float(knob.input_value()) == -56 + page.keyboard.down("Shift") + page.mouse.move(x,y-56,steps=4) + page.keyboard.up("Shift") + assert float(knob.input_value()) == -55.5 + state["graph"]["edges"][1]["gainLinear"] = coarse["payload"]["gainLinear"] + ack(page,state,coarse) + emit(page,"arMixConsoleSnapshot",state) + assert float(knob.input_value()) == -55.5 + page.mouse.up() + page.wait_for_function("()=>window.__nativeIntents.length===4") + final = page.evaluate("()=>window.__nativeIntents.at(-1)") + assert abs(final["payload"]["gainLinear"] - 10**(-55.5/20)) < 1e-8 + state["graph"]["edges"][1]["gainLinear"] = final["payload"]["gainLinear"] + ack(page,state,final) + emit(page,"arMixConsoleSnapshot",state) + # OUT to the same INPUT is the existing exclusive native transaction. + page.locator('#tracks .strip[data-id="1"] select[data-field="output"]').select_option(label="CH04") + route = page.evaluate("()=>window.__nativeIntents.at(-1)") + assert route["operation"] == "APPLY_WIRE_TRANSACTION" + assert route["payload"]["changes"][0]["to"] == RECEIVER + assert route["payload"]["changes"][0]["op"] == "ROUTE_ONLY" + state["graph"].update(revision="3", rosterRevision="3") + state["graph"]["channels"][0]["primaryOutId"] = RECEIVER + state["graph"]["edges"].pop(0) + state["graph"]["edges"][0].update(primaryOutput=True, gainLinear=1) + state["mixerSession"].update(routeRevision="3", rosterRevision="3", + channels=copy.deepcopy(state["graph"]["channels"])) + ack(page, state, route) + emit(page, "arMixConsoleSnapshot", state) + assert page.locator('#tracks .strip[data-id="2"] .wire-gain').is_disabled(), "primary OUT gain must stay unity" + assert not errors, errors + page.screenshot(path=f"native-wire-gain-{width}.png") + page.close() + browser.close() + print("PASS native WIRE gain: real keyboard, coalesced ACK/readback, stable DOM, INPUT OUT, 3 viewports (UI only)") + + +if __name__ == "__main__": + main() diff --git a/tests/approved_operator_ux_chromium_fat.py b/tests/approved_operator_ux_chromium_fat.py index f48567703..dcf481b68 100644 --- a/tests/approved_operator_ux_chromium_fat.py +++ b/tests/approved_operator_ux_chromium_fat.py @@ -1,4 +1,4 @@ -"""Product UX FAT (real Chromium) for the SINGLE assembled public /preview/ GUI without native Windows release. +"""Product UX FAT (real Chromium) for the SINGLE assembled /preview/ and native WebView HTML. Checks rendering in CSS-pixel viewports corresponding to 100/125/150% Windows display scaling. DeviceScaleFactor alone does not reduce usable CSS height, @@ -235,13 +235,24 @@ def check_identity_zero_reflow(page,width,height,scale,channel): flush=True) def main(): - import sys + import argparse import subprocess - with tempfile.TemporaryDirectory(prefix="arsonmix-pages-ux-fat-") as td, sync_playwright() as p: - subprocess.run([sys.executable,str(ROOT/'scripts/build_pages.py'), - '--out',td,'--sha','pages-gui-qualified'], - cwd=ROOT,check=True) - staged=Path(td)/'preview' + import sys + parser=argparse.ArgumentParser() + parser.add_argument('--public',action='store_true',help='Exercise the public Pages bundle') + args=parser.parse_args() + surface='public Pages' if args.public else 'native-assembled' + with tempfile.TemporaryDirectory(prefix="arsonmix-ux-fat-") as td, sync_playwright() as p: + if args.public: + subprocess.run([sys.executable,str(ROOT/'scripts/build_pages.py'), + '--out',td,'--sha','pages-gui-qualified'], + cwd=ROOT,check=True) + staged=Path(td)/'preview' + else: + sys.path.insert(0,str(ROOT/'scripts')) + import build_approved_native_gui as build + staged=Path(td)/'native' + build.stage(staged) browser=p.chromium.launch(headless=True) try: for width,height,scale in CASES: @@ -253,6 +264,6 @@ def main(): assert not errors,(width,height,errors) page.close() finally:browser.close() - print('PASS operator UX: actual public Pages Chromium layout/interaction across display scales') + print(f'PASS operator UX: actual {surface} Chromium layout/interaction across display scales') if __name__=='__main__':main() diff --git a/tests/approved_operator_ux_native_identity_smoke.py b/tests/approved_operator_ux_native_identity_smoke.py new file mode 100644 index 000000000..d3fad1e2f --- /dev/null +++ b/tests/approved_operator_ux_native_identity_smoke.py @@ -0,0 +1,176 @@ +"""Actual compiled native Pages UI: channel identity requires disk-backed host ACK. + +No optimistic JS rename, no localStorage source of authority, no synthetic +PCM graph operation. C++ NativeChannelAppearanceStore CTest independently +proves durable disk/lease validation and guards corruption/restart. +""" +from pathlib import Path +import tempfile +import sys +import copy +from playwright.sync_api import sync_playwright +from approved_native_wire_gain_smoke import snapshot, emit, SOURCE, RECEIVER +from approved_operator_ux_chromium_fat import IDENTITY_GEOMETRY, assert_still + +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/"scripts")) +import build_approved_native_gui as bundle + +def main(): + with tempfile.TemporaryDirectory(prefix="armix-native-identity-") as temp, sync_playwright() as p: + out=Path(temp)/"native" + bundle.stage(out) + browser=p.chromium.launch(headless=True) + context=browser.new_context(viewport={"width":1366,"height":768}) + errors=[] + def open_page(): + page=context.new_page() + page.on("pageerror",lambda e:errors.append(str(e))) + page.add_init_script("""window.__nativeListeners=new Map();window.__nativeIntents=[];window.__nativeEvents=[]; + window.__JUCE__={backend:{ + emitEvent(name,payload){window.__nativeEvents.push({name,payload}); + if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload);}, + addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") + page.goto((out/"index.html").as_uri()) + page.wait_for_function("()=>window.__ARMIX_NATIVE_M2__?.enabled") + return page + state=snapshot() + appearance={"schema":"arsonmix.native.channel-appearance.v1", + "revision":"0","readOnly":False,"entries":[]} + state["channelAppearance"]=appearance + page=open_page() + ready=page.evaluate("()=>window.__nativeEvents.find(e=>e.name==='arMixGuiReady')?.payload") + assert ready and ready["viewportWidth"]==1366 and ready["viewportHeight"]==768 + # No unimplemented native functionality advertised as a working action. + for id in ("saveScene","recallScene","copy","paste","group","ungroup", + "preview","clearCue","reset","sofToggle","sofTarget"): + el=page.locator("#"+id) + assert el.is_hidden() and el.is_disabled(),id + assert page.locator("#pluginsButton").is_visible() + emit(page,"arMixConsoleSnapshot",state) + strip=page.locator('#tracks .strip[data-id="1"]') + strip.wait_for(state="visible") + # Native DAW convention: one click selects, double-click opens editor. + strip.locator(".strip-identity-top").click() + before_editor=page.evaluate(IDENTITY_GEOMETRY) + editor=page.locator("#channelIdentity") + assert editor.is_hidden(),"single click should only select" + strip.locator(".strip-identity-top").dblclick() + assert editor.is_visible(),"double-click header should edit" + assert_still(before_editor,page.evaluate(IDENTITY_GEOMETRY),"native double-click") + page.locator("#identityName").fill("Studio Vox") + color="#c32974" + page.locator(f'#identityColors [data-identity-color="{color}"]').click() + icon="🎹" + page.locator(f'#identityIcons [data-identity-icon="{icon}"]').click() + page.locator("#identitySave").click() + assert editor.is_visible(),"native identity edited before ACK" + assert "Studio Vox" not in strip.inner_text(),"optimistic rename without native evidence" + req=page.evaluate("""()=>window.__nativeEvents.filter(e=> + e.name==='arMixChannelIdentitySet').at(-1)?.payload""") + assert req and req["channelId"]==SOURCE,req + assert req["appearanceRevision"]=="0" and req["name"]=="Studio Vox" + assert req["color"]==color and req["icon"]==icon + assert page.locator("#identitySave").is_disabled() + assert page.evaluate("()=>window.__nativeIntents.length")==0 + + # Bad/stale native ACK: editor remains open and value stays untouched. + emit(page,"arMixChannelIdentityAck", + {"requestId":req["requestId"],"ok":False, + "error":"STALE_CHANNEL_APPEARANCE_REVISION"}) + assert editor.is_visible() + assert page.locator("#identitySave").is_enabled() + assert "Studio Vox" not in strip.inner_text() + assert_still(before_editor,page.evaluate(IDENTITY_GEOMETRY),"native negative ACK") + # Retry after a fresh accepted snapshot. + emit(page,"arMixConsoleSnapshot",state) + page.locator("#identitySave").click() + req=page.evaluate("""()=>window.__nativeEvents.filter(e=> + e.name==='arMixChannelIdentitySet').at(-1)?.payload""") + emit(page,"arMixChannelIdentityAck", + {"requestId":req["requestId"],"ok":True,"error":""}) + # ACK alone MUST NOT rename or close the editor. + assert editor.is_visible() + assert "Studio Vox" not in strip.inner_text() + appearance["revision"]="1" + appearance["entries"]=[{"id":SOURCE,"name":"Studio Vox","color":color,"icon":icon}] + emit(page,"arMixConsoleSnapshot",copy.deepcopy(state)) + page.wait_for_function("""()=>document.querySelector('#channelIdentity').hidden && + document.querySelector('#tracks .strip[data-id="1"]').textContent.includes('Studio Vox')""",timeout=5000) + assert page.evaluate("()=>window.__nativeIntents.length")==0 + assert page.evaluate("()=>localStorage.getItem('arsonmix.native.channel-presentation.v1')") is None + + # A second channel cannot take an existing visible name; rejected + # locally AND independently by the native store's CTest. + other=page.locator('#tracks .strip[data-id="2"]') + other.locator(".footer-label .name").click() + assert editor.is_hidden(),"footer single-click should only select" + other.locator(".footer-label .name").dblclick() + page.locator("#identityName").fill("Studio Vox") + before=page.evaluate("()=>window.__nativeEvents.filter(e=>e.name==='arMixChannelIdentitySet').length") + page.locator("#identitySave").click() + after=page.evaluate("()=>window.__nativeEvents.filter(e=>e.name==='arMixChannelIdentitySet').length") + assert before==after and editor.is_visible() + page.locator("#identityCancel").click() + assert editor.is_hidden() + # Restore the WebView from the same durable *native* snapshot, with + # no shared JS localStorage or reconstructed PCM graph. + page.close() + page=open_page() + # Each WebView reload creates a new page: never reuse old locators. + editor=page.locator("#channelIdentity") + emit(page,"arMixConsoleSnapshot",copy.deepcopy(state)) + page.wait_for_selector('#tracks .strip[data-id="1"]') + assert "Studio Vox" in page.locator('#tracks .strip[data-id="1"]').inner_text() + page.locator('#tracks .strip[data-id="2"] .strip-identity-top').click() + before_f2=page.evaluate(IDENTITY_GEOMETRY) + page.keyboard.press('F2') + assert editor.is_visible(),"F2 should open editor" + assert_still(before_f2,page.evaluate(IDENTITY_GEOMETRY),"native F2") + page.locator('#identityCancel').click() + page.evaluate("() => new Promise(done => requestAnimationFrame(done))") + assert_still(before_f2,page.evaluate(IDENTITY_GEOMETRY),"native F2 Cancel") + page.locator('#tracks .strip[data-id="2"] .footer-label .name').focus() + before_enter=page.evaluate(IDENTITY_GEOMETRY) + page.keyboard.press('Enter') + assert editor.is_visible(),"Enter should open editor" + assert_still(before_enter,page.evaluate(IDENTITY_GEOMETRY),"native Enter") + page.keyboard.press('Escape') + assert editor.is_hidden() + assert_still(before_enter,page.evaluate(IDENTITY_GEOMETRY),"native Escape") + assert page.evaluate("()=>window.__nativeIntents.length")==0 + # Upgrade old WebView cache exactly once; no optimistic local rename. + # The emulated host starts with a clean native workspace and accepts + # the import ONLY after native ACK and revisioned readback. + page.evaluate("""(id)=>localStorage.setItem( + 'arsonmix.native.channel-presentation.v1', + JSON.stringify({version:1,channels:{[id]:{ + name:'Legacy Vocal',color:'#c32974',icon:'🎹'}}}))""",SOURCE) + page.close() + page=open_page() + fresh=copy.deepcopy(state) + fresh["channelAppearance"]={ + "schema":"arsonmix.native.channel-appearance.v1", + "revision":"0","readOnly":False,"entries":[]} + emit(page,"arMixConsoleSnapshot",fresh) + page.wait_for_function("""()=>window.__nativeEvents.some(e=> + e.name==='arMixChannelIdentitySet'&&e.payload.name==='Legacy Vocal')""") + req=page.evaluate("""()=>window.__nativeEvents.find(e=> + e.name==='arMixChannelIdentitySet'&&e.payload.name==='Legacy Vocal').payload""") + assert req["channelId"]==SOURCE and req["appearanceRevision"]=="0" + assert "Legacy Vocal" not in page.locator('#tracks .strip[data-id="1"]').inner_text() + assert page.evaluate("()=>window.__nativeIntents.length")==0 + emit(page,"arMixChannelIdentityAck",{"requestId":req["requestId"],"ok":True,"error":""}) + fresh["channelAppearance"]["revision"]="1" + fresh["channelAppearance"]["entries"]=[{ + "id":SOURCE,"name":"Legacy Vocal","color":"#c32974","icon":"🎹"}] + emit(page,"arMixConsoleSnapshot",fresh) + page.wait_for_function("""()=>document.querySelector( + '#tracks .strip[data-id="1"]').textContent.includes('Legacy Vocal') && + localStorage.getItem('arsonmix.native.channel-presentation.v1')===null""") + assert page.evaluate("()=>window.__nativeIntents.length")==0 + assert not errors,errors + page.close();context.close();browser.close() + print("PASS native identity double-click/ACK/readback/reject/restart/legacy migration with zero PCM graph intents") + +if __name__=="__main__":main() diff --git a/tests/approved_operator_ux_smoke.py b/tests/approved_operator_ux_smoke.py index eb7e089dc..9ff66b0a6 100644 --- a/tests/approved_operator_ux_smoke.py +++ b/tests/approved_operator_ux_smoke.py @@ -66,8 +66,40 @@ def test_native_peq_close_matches_mixer_floating_windows(self): self.assertIn('background:#962f38',css) self.assertIn('width:29px;height:29px',css) - # Native identity/ASIO assertions remain owned by #418's Windows branch. - # Public Pages qualification checks only GUI composition, never native DSP. + def test_native_hooks_and_audio_input_default(self): + build=(ROOT/"scripts/build_approved_native_gui.py").read_text(encoding="utf-8") + bridge=(ROOT/"web/approved-native-bridge.js").read_text(encoding="utf-8") + engine=(ROOT/"src/LiveAudioEngine.h").read_text(encoding="utf-8") + self.assertIn("openChannelIdentity,closeChannelIdentity",build) + self.assertIn("?.applyIdentity?.())return;",build) + self.assertIn("openNativeIdentity(t,event.target)",bridge) + self.assertIn('if(action==="editIdentity"||action==="rename")',bridge) + self.assertIn("return true;\n }\n if ([\"wireExpand\",\"wireSource\",\"wireRoute\"].includes(action))",bridge) + self.assertIn("openNativeIdentity(t,event.target)",bridge) + self.assertIn('event.key!=="F2"',bridge) + self.assertIn("identityChannelFor=t=>",bridge) + self.assertIn("Channel updated and stored in native workspace",bridge) + self.assertIn("channelIcons:CHANNEL_ICONS",build) + self.assertIn("appearanceFromNative(next)",bridge) + self.assertIn("arMixChannelIdentitySet",bridge) + self.assertIn("arMixChannelIdentityAck",bridge) + self.assertIn('const legacyIdentityKey="arsonmix.native.channel-presentation.v1"',bridge) + self.assertIn("retireLegacyRow(p.channelId)",bridge) + self.assertNotIn("const identityStoreKey=",bridge) + appearance=(ROOT/"src/NativeChannelAppearanceStore.h").read_text(encoding="utf-8") + self.assertIn("CANNOT_ATOMICALLY_COMMIT_CHANNEL_APPEARANCE",appearance) + self.assertIn("STALE_CHANNEL_APPEARANCE_REVISION",appearance) + self.assertIn("CHANNEL_NAME_ALREADY_IN_USE",appearance) + self.assertIn("deviceManager_.initialise (2, 2, savedSettings, !savedRoute)",engine) + self.assertIn("active.enabledInputs",bridge) + self.assertIn("data-audio-asio4all-hint",bridge) + self.assertIn("armix-floating-close",bridge) + self.assertIn("viewportWidth:Math.round(window.innerWidth)",bridge) + self.assertIn("presentNativeOnlyTools()",bridge) + main=(ROOT/"src/Main.cpp").read_text(encoding="utf-8") + self.assertIn("browser_.resized(); // first visible HWND",main) + self.assertIn("available.getWidth() - 24",main) + self.assertNotIn("A virtual cable does not automatically play through headphones",bridge) if __name__=="__main__": unittest.main() diff --git a/tests/asio_backend_registration_test.cpp b/tests/asio_backend_registration_test.cpp index e936486ee..b861f8d41 100644 --- a/tests/asio_backend_registration_test.cpp +++ b/tests/asio_backend_registration_test.cpp @@ -1,8 +1,27 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/device/AsioPriorityDeviceManager.h" +#include "../engine/device/AudioSetupRecoveryPolicy.h" #include int main() { + using P=armix::device::AudioSetupRecoveryPolicy; + constexpr auto wasapi=P::select(true,true,false,true); + static_assert(wasapi.reuseActivePins && !wasapi.recreateDevice && + wasapi.priorKnownOpen && !wasapi.verifyAsioPinIdentity); + constexpr auto asio=P::select(true,true,true,true); + static_assert(asio.reuseActivePins && asio.recreateDevice && + asio.priorKnownOpen && asio.verifyAsioPinIdentity); + constexpr auto closedAsio=P::select(true,false,true,true); + static_assert(!closedAsio.reuseActivePins && closedAsio.recreateDevice && + !closedAsio.priorKnownOpen && !closedAsio.verifyAsioPinIdentity); + constexpr auto closedWasapi=P::select(true,false,false,true); + static_assert(!closedWasapi.reuseActivePins && closedWasapi.recreateDevice); + constexpr auto freshBackend=P::select(false,true,true,true); + static_assert(!freshBackend.reuseActivePins && !freshBackend.recreateDevice && + freshBackend.priorKnownOpen && !freshBackend.verifyAsioPinIdentity); + constexpr auto noPinDraft=P::select(true,true,true,false); + static_assert(!noPinDraft.reuseActivePins && noPinDraft.recreateDevice && + !noPinDraft.verifyAsioPinIdentity); #if defined(_WIN32) // A headless CI runner need NOT own an ASIO interface. But the Windows // app MUST ship a functioning ASIO backend type, not just a GUI label. diff --git a/tests/builtin_channel_eq_test.cpp b/tests/builtin_channel_eq_test.cpp new file mode 100644 index 000000000..bd6c280d4 --- /dev/null +++ b/tests/builtin_channel_eq_test.cpp @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/builtin_fx/ChannelEq.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +std::atomic noHeap{false}; +[[noreturn]] void fail(const char* test) noexcept { + std::fprintf(stderr, "FAIL: %s\n", test); + std::abort(); +} +void check(bool ok, const char* test) noexcept { if (!ok) fail(test); } +bool near(double actual, double expected, double tolerance) noexcept { + return std::abs(actual-expected) <= tolerance; +} +} // namespace + +// Optional hard tripwire: processing/configuration must never request heap. +void* operator new(std::size_t n) { + if (noHeap.load(std::memory_order_relaxed)) fail("heap allocation in built-in DSP"); + if (auto* p=std::malloc(n?n:1)) return p; + throw std::bad_alloc(); +} +void* operator new[](std::size_t n) { + if (noHeap.load(std::memory_order_relaxed)) fail("heap allocation in built-in DSP[]"); + if (auto* p=std::malloc(n?n:1)) return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept { std::free(p); } +void operator delete[](void* p) noexcept { std::free(p); } +void operator delete(void* p, std::size_t) noexcept { std::free(p); } +void operator delete[](void* p, std::size_t) noexcept { std::free(p); } + +using namespace armix::builtin_fx; +static Band onBand(ChannelEq& eq, std::size_t slot, float freq, float gain=0.0f, + float q=1.0f, Slope slope=Slope::db12) { + Band b=eq.band(slot); + b.enabled=true; b.frequencyHz=freq; b.gainDb=gain; b.q=q; b.slope=slope; + check(eq.setBand(slot,b),"set band accepted"); + return b; +} +static void runUntilSettled(ChannelEq& eq) { + std::array l{},r{}; + while(eq.transitioning())eq.processStereo(l.data(),r.data(),l.size()); +} +static void testCatalogAndDefault() { + check(channelEqId=="armix.builtin.channel-eq.v1","stable built-in ID"); + check(ChannelEq::bandCount==8,"eight slots exactly"); + check(channelEqSlots[0].kind==FilterKind::highPass,"fixed HPF slot"); + check(channelEqSlots[7].kind==FilterKind::lowPass,"fixed LPF slot"); + for(int rate : {44100,48000,96000}) { + ChannelEq eq; + check(eq.prepare(rate),"prepare sample rate"); + check(eq.activeBands()==0,"all filters off on first launch"); + check(eq.addedLatencySamples()==0,"no buffering/lookahead"); + std::array l{},r{}; + for (std::size_t i=0;i(i)*0.001f - 0.05f; + r[i]=1.0f-l[i]; + } + const auto unchangedL=l,unchangedR=r; + eq.processStereo(l.data(),r.data(),l.size()); + check(l==unchangedL&&r==unchangedR,"exact transparent disabled stereo"); + eq.processMono(l.data(),l.size()); + check(l==unchangedL,"exact transparent disabled mono"); + eq.processStereo(nullptr,nullptr,128); + eq.processMono(nullptr,128); + } + ChannelEq lowSample; + check(lowSample.prepare(8000),"8k rate supported"); + check(lowSample.band(7).frequencyHz<=3600.f,"disabled default clamps below Nyquist"); + check(!lowSample.prepare(0)&&!lowSample.prepare(std::numeric_limits::infinity()),"invalid sample rate rejected"); +} +static void testResponse() { + ChannelEq eq; + check(eq.prepare(48000),"prepare"); + check(near(eq.responseDb(1000),0,1e-10),"off response flat"); + onBand(eq,2,1000,6,1); + check(near(eq.responseDb(1000),6,0.07),"PEQ +6 dB center"); + check(std::abs(eq.responseDb(30))<1,"bell does not affect DC region much"); + onBand(eq,1,160,5,1); + check(eq.responseDb(30)>4,"low shelf +5dB low frequency"); + onBand(eq,6,8000,-5,1); + check(eq.responseDb(15000)<-3,"high shelf attenuates high frequencies"); + ChannelEq cuts; + check(cuts.prepare(48000),"prepare cuts"); + onBand(cuts,0,100,0,.707f,Slope::db12); + const double hpf12=cuts.responseDb(25); + check(hpf12<-22 && hpf12>-29,"HPF 12 dB/oct falloff"); + onBand(cuts,0,100,0,.707f,Slope::db24); + check(cuts.responseDb(25)::infinity(), + std::numeric_limits::quiet_NaN()}) { + auto b=base;b.enabled=true;b.frequencyHz=invalid; + check(!eq.setBand(3,b),"invalid frequency rejected"); + } + auto b=base;b.enabled=true;b.gainDb=21.f; + check(!eq.setBand(3,b),"invalid gain rejected"); + b=base;b.enabled=true;b.q=0.0f; + check(!eq.setBand(3,b),"invalid q rejected"); + b=base;b.enabled=true;b.slope=static_cast(99); + check(!eq.setBand(3,b),"invalid slope rejected"); + check(!eq.setBand(8,base),"invalid slot rejected"); + check(eq.activeBands()==0,"failed writes leave existing state unchanged"); + onBand(eq,2,1000,9); + runUntilSettled(eq); + const auto before=eq.band(2); + auto wrong=before;wrong.frequencyHz=30000; + check(!eq.setBand(2,wrong),"failed update leaves active filter untouched"); + check(eq.band(2).frequencyHz==before.frequencyHz,"readback unchanged on rejected edit"); + check(eq.resetToFlat(),"reset all in one transition"); + runUntilSettled(eq); + check(eq.activeBands()==0 && near(eq.responseDb(1000),0,0.0001),"flat reset"); + check(!eq.transitioning(),"reset fade completed"); +} +static void testAudibleProcessingAndIndependence() { + ChannelEq eq; + check(eq.prepare(48000),"prepare"); + onBand(eq,2,1000,12,0.7f); + runUntilSettled(eq); + constexpr int n=128; + std::array left{}, right{}; + left[0]=1.0f; + eq.processStereo(left.data(),right.data(),left.size()); + check(left[0]>0.0f,"first sample delivered, no initial buffer/latency"); + check(std::all_of(right.begin(),right.end(),[](float v){return v==0.f;}),"no L->R leakage"); + ChannelEq mono; + check(mono.prepare(48000),"mono prepare"); + onBand(mono,2,1000,12,0.7f); + runUntilSettled(mono); + std::array x{};x[0]=1; + mono.processStereo(x.data(),x.data(),x.size()); // alias -> once only + check(near(x[0],left[0],1e-6),"alias-safe stereo uses mono path once"); + + ChannelEq gate; + check(gate.prepare(48000),"gate prepare"); + onBand(gate,1,160,6,1); + runUntilSettled(gate); + std::array held{};held.fill(1.f); + for(int i=0;i<16;++i) { held.fill(1.f); gate.processMono(held.data(),held.size()); } + check(held.back()>1.7,"actual LF shelf modifies PCM"); + const float previousWet = held.back(); + check(gate.resetToFlat(),"bypass request"); + held.fill(1.f); + gate.processMono(held.data(),held.size()); + check(std::abs(held[0]-previousWet)<0.1f,"start bypass transition follows last wet output"); + check(near(held.back(),1.0,1e-6),"finished bypass returns exact dry PCM"); + check(!gate.transitioning(),"bypass ramp completed"); +} +static void testFourteenIndependentChannels() { + // 10 CH + 4 AUX. Test per-channel filter/history isolation, not 14 EQs + // accidentally chained into a single PCM buffer. + std::array lanes{}; + for(auto& eq:lanes)check(eq.prepare(48000),"14 independent preparations"); + onBand(lanes[0],2,1000,9,0.7f); + runUntilSettled(lanes[0]); + onBand(lanes[13],0,120,0,0.707f,Slope::db24); + runUntilSettled(lanes[13]); + std::array,14> left{},right{}; + std::array reference1000{},reference60{}; + for(unsigned repeat=0;repeat<64;++repeat) { + for(std::size_t i=0;i(repeat*reference1000.size()+i)/48000.0; + reference1000[i]=0.1f*std::sin(6.283185307179586*t*1000.0); + reference60[i]=0.1f*std::sin(6.283185307179586*t*60.0); + } + for(std::size_t lane=0;lane(reference1000[i])*reference1000[i]; + boost1000+=static_cast(left[0][i])*left[0][i]; + dry60+=static_cast(reference60[i])*reference60[i]; + cut60+=static_cast(left[13][i])*left[13][i]; + } + check(boost1000>dry1000*4,"CH01 independent PEQ boost is audible PCM"); + check(cut60 l{},r{}; + l[0]=1.f; + noHeap.store(true,std::memory_order_release); + const bool accepted=eq.applyPreparedBand(packet); + if(accepted)eq.processStereo(l.data(),r.data(),l.size()); + noHeap.store(false,std::memory_order_release); + check(accepted,"audio owner applies precomputed packet"); + check(eq.activeBands()==1&&eq.band(4).gainDb==7.0f,"accepted DSP readback"); + check(l[0]>0.0f,"precomputed audio sample delivered"); + + ChannelEq changedRate; + check(changedRate.prepare(44100),"changed rate instance"); + check(!changedRate.applyPreparedBand(packet),"stale sample rate packet rejected"); + check(changedRate.activeBands()==0,"stale packet no partial application"); + ChannelEq::PreparedBandEdit invalidPacket=packet; + invalidPacket.sections=99; + check(!eq.applyPreparedBand(invalidPacket),"untrusted section count rejected"); + invalidPacket=packet; + invalidPacket.coefficients[0][0]=std::numeric_limits::quiet_NaN(); + // Force meaningful change so duplicate same-state shortcut cannot conceal + // a malformed coefficient payload. + invalidPacket.band.gainDb=8.0f; + check(!eq.applyPreparedBand(invalidPacket),"malformed filter coefficient rejected"); + check(eq.band(4).gainDb==7.0f,"rejected packet does not replace DSP state"); +} +static void testNoHeapAndVariableQuantum() { + ChannelEq eq; + check(eq.prepare(48000),"prepare"); + std::array l{},r{}; + for (auto count : {32u,64u,128u,512u}) { + l.fill(0.12f);r.fill(-0.07f); + auto hp=eq.band(0);hp.enabled=true;hp.frequencyHz=90+static_cast(count)/10.f; + hp.slope=Slope::db24; + ChannelEq::PreparedBandEdit prepared{}; + check(ChannelEq::prepareBandEdit(0,hp,48000,prepared),"control precomputes HPF"); + noHeap.store(true,std::memory_order_release); + const bool ok=eq.applyPreparedBand(prepared); + if(ok)eq.processStereo(l.data(),r.data(),count); + noHeap.store(false,std::memory_order_release); + check(ok,"parameter writes without allocation"); + check(std::isfinite(l[0])&&std::isfinite(l[count-1])&& + std::isfinite(r[count-1]),"variable quantum finite stereo"); + } +} +int main() { + testCatalogAndDefault(); + testResponse(); + testValidationAndReset(); + testAudibleProcessingAndIndependence(); + testPrecomputedControlToAudioBoundary(); + testNoHeapAndVariableQuantum(); + testFourteenIndependentChannels(); + std::puts("PASS: ArSonMix built-in 8-slot native Channel EQ; no ArSonEQ/VST3 dependency"); +} diff --git a/tests/ci_workflow_efficiency_test.mjs b/tests/ci_workflow_efficiency_test.mjs index f3b9d2050..51227772d 100644 --- a/tests/ci_workflow_efficiency_test.mjs +++ b/tests/ci_workflow_efficiency_test.mjs @@ -68,10 +68,14 @@ test('native PCM and device changes always use Windows/CTest, never Chromium by assert.equal(selected(uiPush, filename), false, filename + ' wrongly triggers browser main'); } assert.match(native, /ctest --test-dir build -C Release --output-on-failure/); - for (const target of [ - 'ARMixPreparedMixerBlockTests', 'ARMixNativeMixerSessionTests', - 'ARMixLiveRoutingEpochTests', 'ARMixRTTests', 'ARMixLiveChannelFxTests' - ]) assert.ok(native.includes(target), 'Missing vital audio test ' + target); +}); + +test('Windows builds the default CMake graph before running all CTests', () => { + assert.match(native, /-DBUILD_TESTING=ON/); + const build = native.indexOf('run: cmake --build build --config Release --parallel 2'); + const ctest = native.indexOf('run: ctest --test-dir build -C Release --output-on-failure'); + assert.ok(build >= 0 && ctest > build, 'Build all default targets before CTest'); + assert.doesNotMatch(native, /cmake --build [^\r\n]*--target\b/); }); test('approved Pages to JUCE build seam is a native gate, never an unrelated CSS-only job', () => { @@ -129,8 +133,24 @@ test('ordinary GUI PR and main use current targeted checks; full history is expl assert.match(ui, /python tests\/pages_v55_context_wire_fader_smoke.py/); assert.match(ui, /node tests\/wire_main_native_handoff_contract.test.cjs/); assert.match(ui, /python tests\/pages_v51_portrait_led_peak_hold_smoke.py/); - const fullOnly = [...ui.matchAll(/^\s{8}if: .*workflow_dispatch.*integration\/product-/gm)].length; - assert.ok(fullOnly >= 35, 'Historical/extended GUI steps must be opt-in, found ' + fullOnly); + assert.match(ui,/historical_css:\n\s+description:.*\n\s+type: boolean\n\s+required: false\n\s+default: false/); + const start=ui.indexOf(' - name: Mount pinned V24 historical CSS fixture'); + const end=ui.indexOf(' - name: Verify V28 exact approved /preview/ source'); + assert.ok(start>0&&end>start,'archived fixtures and current product checks must remain distinct'); + const archived=ui.slice(start,end).split(/(?= - name: )/).filter(s=>s.trim()); + assert.equal(archived.length,28,'all archived tests and mount/restore steps remain available'); + for(const step of archived) + assert.match(step,/if: \$\{\{ github\.event_name == 'workflow_dispatch' && inputs\.historical_css == true \}\}/); + // Real product functional/geometry/provenance checks must never inherit + // the historical opt-in or disappear with the old fixture mounts. + for(const file of ['pages_wire_incoming_v43_smoke.py','preview_v15_drag_wire_smoke.py', + 'pages_m1_meter_gain_calibration_smoke.py','pages_m3_operator_visual_interaction_smoke.py', + 'pages_wire_v44_finish_smoke.py','pages_wire_v45_socket_layout_smoke.py', + 'pages_wire_v46_precision_smoke.py']) { + const step=ui.split(/(?= - name: )/).find(s=>s.includes('python tests/'+file)); + assert.ok(step,file+' stays required in current UI qualification'); + assert.ok(!step.includes('inputs.historical_css'),file+' was incorrectly made historical'); + } assert.match(ui, /python tests\/pages_css_architecture_v27_smoke.py/); assert.match(ui, /retention-days: 3/); }); @@ -143,7 +163,7 @@ test('Windows realtime CTest is explicit for PR milestones; packaging requires d assert.match(native,/^ windows-build:[\s\S]*?needs: quick\n/m); assert.match(native,/github\.event_name != 'pull_request'/); const fatOnly = [...native.matchAll(/^ if: .*inputs\.package_fat == true.*$/gm)].length; - assert.equal(fatOnly,4,'Packaging, FactoryFX stage, ZIP verify and upload require manual FAT'); + assert.equal(fatOnly,7,'Portable FAT and Inno installer build/verify/upload all require deliberate manual opt-in'); assert.match(native,/FAT_EXACT_PR_HEAD_CHECKOUT/); assert.match(native,/ctest --test-dir build -C Release --output-on-failure/); assert.ok(native.indexOf('scripts/verify_native_windows_artifact.ps1 -OutputDir dist') < diff --git a/tests/crackle_evidence_window_test.cpp b/tests/crackle_evidence_window_test.cpp index 90dffd479..710ff024b 100644 --- a/tests/crackle_evidence_window_test.cpp +++ b/tests/crackle_evidence_window_test.cpp @@ -38,6 +38,37 @@ int main() check(window.ready() && window.elapsedMs==4500); check(delta(window,E::Counter::renderedCallbacks).comparable); check(delta(window,E::Counter::renderedCallbacks).value==450); + // A known Windows RAM load at a marked glitch is contextual evidence, + // not a DSP change, physical xrun, or source of invented hard faults. + tracker.reset(); + auto memoryBase=sample(1000); + memoryBase.memory={71,2800,440,690,1000,true,true}; + tracker.push(memoryBase); + for(std::uint64_t ms=2000;ms<=4000;ms+=1000) { + auto point=sample(ms); + point.memory={static_cast(ms==3000?78:74), + 2100,460,710,1000+ms/10,true,true}; + tracker.push(point); + } + auto memoryMark=sample(5000); + memoryMark.memory={75,2200,490,740,1450,true,true}; + const auto pressure=tracker.mark(memoryMark); + check(pressure.ready() && pressure.loadComparable); + check(pressure.memoryBefore.systemLoadPercent==71); + check(pressure.memoryAtMark.systemLoadPercent==75); + check(pressure.peakLoadPercent==78); + check(pressure.processPageFaults.comparable); + check(pressure.processPageFaults.value==450); + auto memoryReset=sample(5000); + memoryReset.memory={76,2000,500,760,999,true,true}; + const auto afterReset=tracker.mark(memoryReset); + check(afterReset.ready()&&!afterReset.processPageFaults.comparable); + auto absent=sample(5000); + absent.memory.systemAvailable=false; + check(!tracker.mark(absent).loadComparable); + tracker.reset(); + for(std::uint64_t ms=1000;ms<=6000;ms+=1000) + tracker.push(sample(ms)); check(delta(window,E::Counter::overBudgetCallbacks).comparable); check(delta(window,E::Counter::overBudgetCallbacks).value==0); check(!delta(window,E::Counter::wasapiCaptureDiscontinuities).comparable); diff --git a/tests/device_session_transition_policy_test.cpp b/tests/device_session_transition_policy_test.cpp new file mode 100644 index 000000000..2c28e9a69 --- /dev/null +++ b/tests/device_session_transition_policy_test.cpp @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/device/DeviceSessionTransitionPolicy.h" +#include +#include +using armix::device::DeviceSessionDecision; +using armix::device::decideDeviceSession; + +int main() +{ + using armix::device::retainedMixerQuantum; + static_assert(retainedMixerQuantum(256,1024,8192,false,true)==256); + static_assert(retainedMixerQuantum(256,64,8192,false,true)==64); + static_assert(retainedMixerQuantum(64,512,8192,false,true)==64); + static_assert(retainedMixerQuantum(256,512,8192,true,false)==256); + static_assert(retainedMixerQuantum(256,512,8192,true,true)==0); + static_assert(retainedMixerQuantum(256,8193,8192,false,false)==0); + static_assert(retainedMixerQuantum(0,512,8192,false,false)==0); + // Opening and closing the dialog without a real hardware generation + // change never discards an accepted mixer, regardless of its contents. + static_assert(decideDeviceSession(true, true, true) == + DeviceSessionDecision::retainBoundMixer); + static_assert(decideDeviceSession(true, true, false) == + DeviceSessionDecision::retainBoundMixer); + // A failed open cannot create a default mixer or grant output permission. + static_assert(decideDeviceSession(false, false, true) == + DeviceSessionDecision::rejectedDevice); + static_assert(decideDeviceSession(false, false, false) == + DeviceSessionDecision::rejectedDevice); + // A new driver epoch with user-authored routing/FX is a NEEDS-REBIND + // state, never a permission to overwrite the document with 10ch defaults. + static_assert(decideDeviceSession(true, false, true) == + DeviceSessionDecision::retainUnboundMixer); + // Only a genuinely blank first-run mixer can start from the silent graph. + static_assert(decideDeviceSession(true, false, false) == + DeviceSessionDecision::createFirstSilentMixer); + for (bool verified : {false, true}) { + for (bool bound : {false, true}) { + for (bool edited : {false, true}) { + const auto decision = decideDeviceSession(verified,bound,edited); + assert(decision != DeviceSessionDecision::createFirstSilentMixer || + (verified && !bound && !edited)); + } + } + } +} diff --git a/tests/direct_restore_recovery_contract_test.mjs b/tests/direct_restore_recovery_contract_test.mjs index 0c1d381ee..6139a50f0 100644 --- a/tests/direct_restore_recovery_contract_test.mjs +++ b/tests/direct_restore_recovery_contract_test.mjs @@ -47,8 +47,7 @@ test('restore retry is bounded and disabled on success, explicit direct and setu assert.match(main,/SMART_CLOCK_RECOVERY/); assert.match(main,/annotateRecovery \(status\)/); assert.match(main,/annotateRecovery \(state\)/); - assert.match(cmake,/BoundedDirectDeviceRecovery/); - assert.match(workflow,/ARMixRecoveryTests/); + assert.match(cmake,/add_test\(NAME BoundedDirectDeviceRecovery COMMAND ARMixRecoveryTests\)/); assert.match(workflow,/direct_restore_recovery_contract_test.mjs/); }); test('verified native FAT package preserves actual beta live-bridge provenance, not older offline-only claim',()=>{ diff --git a/tests/dynamic_accepted_session_test.cpp b/tests/dynamic_accepted_session_test.cpp index d39762988..85c1d3eb7 100644 --- a/tests/dynamic_accepted_session_test.cpp +++ b/tests/dynamic_accepted_session_test.cpp @@ -235,7 +235,7 @@ static void verifyAtomicWireTransactionAndZeroSampleHops() { w.from=from;w.edgeId=id;return w; }; const std::array initial{ - connect(one,main),connect(two,main),connect(three,main) + routeOnly(one,main),routeOnly(two,main),routeOnly(three,main) }; a=session.wireTransaction(1,1,initial,physical,epoch,epoch,true); assert(a.ok()&&a.graphRevision==2&&a.edit.createdEdgeIds.size()==3); @@ -355,6 +355,93 @@ static void verifyAtomicWireTransactionAndZeroSampleHops() { assert(a.ok() && a.graphRevision==7); assert(findEdge(one,main,7)==chainId && !findEdge(one,two,7)); assert(render() && near(left[11],.3f*center)); + + // MAIN is a valid ROUTE_ONLY destination while the physical output is + // armed. GROUP -> MAIN is one exclusive path, never double dry PCM. + a=session.wireTransaction(7,7,hop1,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==8); + assert(!findEdge(one,main,8) && findEdge(one,two,8)); + assert(render() && near(left[11],.3f*center)); + // Deliberately connect an independent 40%-gain parallel send to MAIN. + const std::array parallelMain{connect(one,main,.4f)}; + a=session.wireTransaction(8,8,parallelMain,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==9); + const auto parallelEdge=findEdge(one,main,9); + assert(parallelEdge && findEdge(one,two,9)); + assert(render() && near(left[11],.3f*1.4f*center,1e-4f)); + // ROUTE_ONLY to MAIN promotes that same EdgeId, removes only the + // previous primary to GROUP, and forces unity post-fader output. + const std::array backToMain{routeOnly(one,main)}; + a=session.wireTransaction(9,9,backToMain,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==10); + const auto* afterMain=session.acceptedRouting(epoch,10); + assert(afterMain && afterMain->find(one)->primaryOutput==main); + assert(!findEdge(one,two,10) && findEdge(one,main,10)==parallelEdge); + assert(std::count_if(afterMain->edges.begin(),afterMain->edges.end(), + [&](const auto& edge){return edge.from==one;})==1); + assert(render() && near(left[11],.3f*center,1e-4f)); + a=session.wireTransaction(10,10,backToMain,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==11); + assert(findEdge(one,main,11)==parallelEdge); + assert(render() && near(left[11],.3f*center,1e-4f)); + auto staleMain=session.wireTransaction(10,10,backToMain, + physical,epoch,epoch,false); + assert(staleMain.fault==DynamicAcceptedSession::Fault::staleRoster); + assert(session.acceptedGraphRevision()==11); + assert(render() && near(left[11],.3f*center,1e-4f)); + + // GUI SOURCE ONLY: unplug only the actual accepted primary MAIN edge. + // The capture source and other channels stay in the same installed + // graph; MAIN is silent until a later explicit WIRE reconnect. + const std::array sourceOnly{remove(one,parallelEdge)}; + a=session.wireTransaction(11,11,sourceOnly,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==12); + assert(!session.acceptedRouting(epoch,12)->find(one)->primaryOutput.value); + assert(!findEdge(one,main,12)); + assert(session.acceptedPhysicalRequest().sources.size()==1); + assert(session.acceptedPhysicalRequest().sources.front().id==one); + assert(render() && near(left[11],0.f,1e-5f) && + near(right[11],0.f,1e-5f)); + // Replug MAIN via the same menu/socket. No external monitor ARM or + // hardware source patch is required, and exactly one path resumes PCM. + a=session.wireTransaction(12,12,backToMain,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==13); + assert(findEdge(one,main,13)!=0); + assert(session.acceptedRouting(epoch,13)->find(one)->primaryOutput==main); + assert(render() && near(left[11],.3f*center,1e-4f)); + + // Installed PCM regression: a deliberate parallel MAIN send must survive + // a later exclusive BUS retarget. The GUI used to reject the successful + // readback merely because it saw any MAIN edge, even a NON-primary send. + a=session.wireTransaction(13,13,hop1,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==14); + assert(findEdge(one,two,14) && !findEdge(one,main,14)); + const std::array extraMain{connect(one,main,.25f)}; + a=session.wireTransaction(14,14,extraMain,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==15); + const auto preservedSend=findEdge(one,main,15); + assert(preservedSend && render() && + near(left[11],.3f*1.25f*center,1e-4f)); + const std::array switchBus{routeOnly(one,three)}; + a=session.wireTransaction(15,15,switchBus,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==16); + const auto* preserved=session.acceptedRouting(epoch,16); + assert(preserved && preserved->find(one)->primaryOutput==three); + assert(!findEdge(one,two,16) && findEdge(one,main,16)==preservedSend); + const auto parallelNative=std::find_if(preserved->edges.begin(), + preserved->edges.end(),[&](const auto& edge) { + return edge.edgeId==preservedSend; + }); + assert(parallelNative!=preserved->edges.end() && + !parallelNative->primaryOutput); + assert(render() && near(left[11],.3f*1.25f*center,1e-4f)); + // Detach the independent parallel MAIN send by the same stable EdgeId, + // keeping the BUS primary and returning to exactly one PCM path. + const std::array removeExtra{remove(one,preservedSend)}; + a=session.wireTransaction(16,16,removeExtra,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==17); + assert(!findEdge(one,main,17) && findEdge(one,three,17)); + assert(render() && near(left[11],.3f*center,1e-4f)); session.unpublish(); session.pollRetirement(); } @@ -449,6 +536,83 @@ static void verifyPrimaryOutKeepsCanonicalEdgeIdentity() { session.pollRetirement(); } +// Real PCM golden regression for a HELD operator fader, not a mouse-up-only +// scalar. Between each input move, the installed native DSP renders another +// callback block and must audibly change the waveform. Structural revision +// stays constant; there is no second callback or graph compilation. +static void verifyHeldDragIntermediatePcmOnOriginalChannels() { + constexpr std::uint64_t epoch=94021; + constexpr float center=.7071067811865475f; + DynamicAcceptedSession pcm; + DynamicGraphRequest physical; + physical.physicalInputs=4; + physical.maxFrames=64; + std::vector initial; + for(int i=0;i<10;++i) + initial.push_back(add(static_cast(i), + ChannelRole::input,"HELD ORIGINAL CH")); + initial.push_back(add(10,ChannelRole::main,"MAIN", + ProcessingFormat::stereo)); + const auto accepted=pcm.edit(0,0,initial,physical,epoch,epoch,true); + assert(accepted.ok() && accepted.edit.createdIds.size()==11); + const auto& ids=accepted.edit.createdIds; + const auto main=ids[10]; + const std::array channels{ids[0],ids[1],ids[4],ids[9]}; + const std::array links{ + output(channels[0],main),output(channels[1],main), + output(channels[2],main),output(channels[3],main)}; + for(std::size_t i=0;i(i),-1,false}); + const auto patched=pcm.edit(1,1,links,physical,epoch,epoch,true); + assert(patched.ok() && pcm.acceptedGraphRevision()==2); + std::array a{},b{},c{},d{},left{},right{}; + a.fill(.1f);b.fill(.2f);c.fill(.3f);d.fill(.4f); + const float* pins[]{a.data(),b.data(),c.data(),d.data()}; + const std::array signal{.1f,.2f,.3f,.4f}; + std::array levels{1.f,1.f,1.f,1.f}; + const auto noFx=+[](ChannelId,float*,float*,int) noexcept {}; + const auto renderAndCheck=[&] { + assert(pcm.render(epoch,pins,4,left.data(),right.data(),64, + false,noFx)); + float sum=0.f; + for(std::size_t i=0;ifaderLinear, + linear)); + assert(pcm.acceptedGraphRevision()==2); + } + // Release is merely the last target: no structural commit and no + // newly armed audio path is required to restore the baseline. + assert(pcm.setLiveMix(epoch,2,channels[i],1.f,0.f)); + levels[i]=1.f; + assert(near(renderAndCheck(),center)); + } + // A stale epoch/revision cannot mutate an otherwise live fader or PCM. + assert(!pcm.setLiveMix(epoch-1,2,channels[2],0.f,0.f)); + assert(!pcm.setLiveMix(epoch,1,channels[2],0.f,0.f)); + assert(near(renderAndCheck(),center)); + pcm.unpublish(); + pcm.pollRetirement(); +} + // Original CH1-10 do not get a different fader/solo DSP owner from CH11. // This is an actual accepted native publisher PCM test, not a mock GUI reducer. static void verifyOriginalAndAddedInputsShareNativePcmControls() { @@ -522,7 +686,121 @@ static void verifyOriginalAndAddedInputsShareNativePcmControls() { pcm.pollRetirement(); } +// Real sample-block regression for DAW semantics: SOURCE ONLY retains its +// physical input, independent CONNECT to MAIN is a parallel SEND, and the +// subsequent explicit ROUTE_ONLY promotes that exact edge to primary. +static void verifySourceOnlyParallelMainVsExclusivePrimaryPcm() { + constexpr std::uint64_t ep=99221; + constexpr float center=.7071067811865475f; + DynamicAcceptedSession pcm; + DynamicGraphRequest io;io.physicalInputs=1;io.maxFrames=64; + const std::array create{ + add(0,ChannelRole::input,"VOCAL"), + add(1,ChannelRole::main,"MAIN",ProcessingFormat::stereo) + }; + auto state=pcm.edit(0,0,create,io,ep,ep,true); + assert(state.ok()&&state.edit.createdIds.size()==2); + const auto vocal=state.edit.createdIds[0],main=state.edit.createdIds[1]; + io.sources={{vocal,0,-1,false}}; + WireChange primary;primary.kind=WireChange::Kind::routeOnly; + primary.from=vocal;primary.to=main;primary.gain=1.f; + const std::array toMain{primary}; + state=pcm.wireTransaction(1,1,toMain,io,ep,ep,true); + assert(state.ok()&&pcm.acceptedGraphRevision()==2); + const auto* first=pcm.acceptedRouting(ep,2); + assert(first&&first->edges.size()==1); + const auto primaryEdge=first->edges[0].edgeId; + std::array impulse{},l{},r{}; + impulse[9]=.25f; + const float* pins[]{impulse.data()}; + const auto render=[&]{ + return pcm.render(ep,pins,1,l.data(),r.data(),64,false, + +[](ChannelId,float*,float*,int) noexcept {}); + }; + assert(render()&&near(l[9],.25f*center)&&near(r[9],.25f*center)); + WireChange unplug;unplug.kind=WireChange::Kind::remove; + unplug.from=vocal;unplug.edgeId=primaryEdge; + const std::array remove{unplug}; + state=pcm.wireTransaction(2,2,remove,io,ep,ep,false); + assert(state.ok()&&pcm.acceptedGraphRevision()==3); + assert(pcm.acceptedRouting(ep,3)->find(vocal)->primaryOutput.value==0); + assert(render()&&near(l[9],0.f)&&near(r[9],0.f)); + // No source deletion: physical impulse remains available after unplug. + WireChange parallel;parallel.kind=WireChange::Kind::connect; + parallel.from=vocal;parallel.to=main;parallel.gain=.4f; + const std::array sendToMain{parallel}; + state=pcm.wireTransaction(3,3,sendToMain,io,ep,ep,false); + assert(state.ok()&&pcm.acceptedGraphRevision()==4); + const auto* withSend=pcm.acceptedRouting(ep,4); + assert(withSend&&withSend->find(vocal)->primaryOutput.value==0); + assert(withSend->find(vocal)->parallelSends.size()==1); + assert(withSend->edges.size()==1&&!withSend->edges[0].primaryOutput); + const auto parallelEdge=withSend->edges[0].edgeId; + assert(render()&&near(l[9],.25f*.4f*center)&& + near(r[9],.25f*.4f*center)); + // Exclusive routing promotes existing EdgeId; no double dry mix. + state=pcm.wireTransaction(4,4,toMain,io,ep,ep,false); + assert(state.ok()&&pcm.acceptedGraphRevision()==5); + const auto* exclusive=pcm.acceptedRouting(ep,5); + assert(exclusive&&exclusive->edges.size()==1); + assert(exclusive->edges[0].edgeId==parallelEdge); + assert(exclusive->edges[0].primaryOutput); + assert(exclusive->find(vocal)->parallelSends.empty()); + assert(exclusive->find(vocal)->primaryOutput==main); + assert(render()&&near(l[9],.25f*center)&&near(r[9],.25f*center)); + // A stale EdgeId must never disconnect the promoted primary. + const std::array staleRemove{unplug}; + const auto rejected=pcm.wireTransaction(5,5,staleRemove,io,ep,ep,false); + assert(rejected.fault==DynamicAcceptedSession::Fault::editRejected); + assert(pcm.acceptedGraphRevision()==5); + assert(render()&&near(l[9],.25f*center)); +} + +// Actual GROUP post-insert PCM must be silenced by its own realtime MUTE, +// with no graph rebuild, physical source reset or lost monitor state. +static void verifyGroupMuteAffectsRealNativePcm() { + constexpr std::uint64_t ep=99222; + DynamicAcceptedSession pcm; + DynamicGraphRequest io;io.physicalInputs=1;io.maxFrames=64; + const std::array created{ + add(0,ChannelRole::input,"VOICE"), + add(1,ChannelRole::group,"BUS A",ProcessingFormat::stereo), + add(2,ChannelRole::main,"MAIN",ProcessingFormat::stereo) + }; + auto state=pcm.edit(0,0,created,io,ep,ep,true); + assert(state.ok()&&state.edit.createdIds.size()==3); + const auto voice=state.edit.createdIds[0]; + const auto bus=state.edit.createdIds[1]; + const auto main=state.edit.createdIds[2]; + io.sources={{voice,0,-1,false}}; + const std::array serial{output(voice,bus),output(bus,main)}; + state=pcm.edit(1,1,serial,io,ep,ep,true); + assert(state.ok()&&pcm.acceptedGraphRevision()==2); + std::array mono{},l{},r{}; + mono.fill(.25f); + const float* pins[]{mono.data()}; + const auto render=[&]{ + return pcm.render(ep,pins,1,l.data(),r.data(),64,false, + +[](ChannelId,float*,float*,int) noexcept {}); + }; + assert(render()); + const float audible=l[63]; + assert(audible>.05f&&near(r[63],audible)); + assert(pcm.setLiveMuteSolo(ep,2,bus,true,false)); + assert(render()&&near(l[63],0.f,1e-4f)&&near(r[63],0.f,1e-4f)); + assert(pcm.acceptedRoster().find(bus)->mute); + assert(pcm.setLiveMuteSolo(ep,2,bus,false,false)); + assert(render()&&near(l[63],audible,1e-4f)&&near(r[63],audible,1e-4f)); + assert(!pcm.setLiveMuteSolo(ep-1,2,bus,true,false)); + assert(!pcm.setLiveMuteSolo(ep,1,bus,true,false)); + assert(pcm.acceptedGraphRevision()==2); + assert(render()&&near(l[63],audible,1e-4f)); +} + int main() { + verifyGroupMuteAffectsRealNativePcm(); + verifySourceOnlyParallelMainVsExclusivePrimaryPcm(); + verifyHeldDragIntermediatePcmOnOriginalChannels(); verifyOriginalAndAddedInputsShareNativePcmControls(); verifyPrimaryOutKeepsCanonicalEdgeIdentity(); verifyDefaultNativeMainEdgeAndDisconnectedRestore(); diff --git a/tests/dynamic_latency_compensation_test.cpp b/tests/dynamic_latency_compensation_test.cpp new file mode 100644 index 000000000..e2d1db28d --- /dev/null +++ b/tests/dynamic_latency_compensation_test.cpp @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/core/DynamicNativeSessionPublisher.h" +#ifdef NDEBUG +#undef NDEBUG +#endif +#include +#include +#include +#include +static std::size_t allocations=0; +void* operator new(std::size_t n){++allocations;if(auto* p=std::malloc(n?n:1))return p;throw std::bad_alloc();} +void* operator new[](std::size_t n){return ::operator new(n);} +void operator delete(void* p) noexcept {std::free(p);} +void operator delete[](void* p) noexcept {std::free(p);} +void operator delete(void* p,std::size_t) noexcept {std::free(p);} +void operator delete[](void* p,std::size_t) noexcept {std::free(p);} +using namespace armix::mixer; +struct Effects { + ChannelId a{},receiver{}; + armix::dsp::StereoLatencyDelay delayA,delayReceiver; + int latency(ChannelId id) const noexcept{return id==a?7:id==receiver?3:0;} + void render(ChannelId id,float* l,float* r,int n) noexcept { + auto* delay=id==a?&delayA:id==receiver?&delayReceiver:nullptr; + if(delay)for(int i=0;iprocess(l[i],r[i]); + } +}; +int main(){ + for(bool pre:{false,true}) { + DynamicChannelRoster roster; + std::vector edits; + for(int i=0;i<5;++i){ChannelEdit e;e.kind=ChannelEdit::Kind::add; + e.position=i;e.role=i==3?ChannelRole::main:i==4?ChannelRole::monitor:ChannelRole::input; + e.format=ProcessingFormat::stereo;e.text="node";edits.push_back(e);} + const auto added=roster.edit(0,edits);assert(added.ok()); + const auto ids=added.createdIds;const auto a=ids[0],b=ids[1],r=ids[2],main=ids[3],monitor=ids[4]; + std::vector sends; + const auto send=[&](ChannelId from,ChannelId to,bool before=false){ChannelEdit e; + e.kind=ChannelEdit::Kind::addSendReference;e.id=from;e.target=to;e.value=1;e.preFader=before;sends.push_back(e);}; + send(a,main);send(a,r,pre);send(b,r);send(r,main);send(b,monitor); + assert(roster.edit(1,sends).ok()); + // Physical receiver input is mixed alongside internally delayed PCM. + DynamicGraphRequest request;request.physicalInputs=6;request.maxFrames=16; + request.sources={{a,0,1,true},{b,2,3,true},{r,4,5,true}}; + auto fx=std::make_shared();fx->a=a;fx->receiver=r; + assert(fx->delayA.prepare(7)&&fx->delayReceiver.prepare(3)); + DynamicNativeSessionPublisher publisher; + DynamicNativeSessionPublisher::FxPlan plan; + plan.owner=fx;plan.context=fx.get();plan.deviceEpoch=9;plan.graphRevision=1; + plan.render=+[](void* p,ChannelId id,float* l,float* r,int n) noexcept {static_cast(p)->render(id,l,r,n);}; + plan.latency=+[](void* p,ChannelId id) noexcept{return static_cast(p)->latency(id);}; + assert(publisher.commit(roster,request,0,9,9,true,plan).ok()); + assert(publisher.latencySamples(9,1)==10); + std::array inA{},inB{},inR{},l{},right{},ml{},mr{}; + int time=0; + for(int n:{3,1,7,5,16}){ + inA.fill(0);inB.fill(0);inR.fill(0); + if(time==0){inA[0]=1;inB[0]=2;inR[0]=4;} + const float* physical[]{inA.data(),inA.data(),inB.data(),inB.data(),inR.data(),inR.data()}; + const auto before=allocations; + assert(publisher.render(9,physical,6,l.data(),right.data(),n,false, + [](ChannelId,float*,float*,int) noexcept {},ml.data(),mr.data())); + assert(allocations==before); + for(int i=0;i{ const fence=r('engine/device/IndependentStreamFormatFence.h'); const cmake=r('CMakeLists.txt'); - const workflow=r('.github/workflows/p1-windows.yml'); assert.match(fence,/class IndependentStreamFormatFence final/); assert.match(fence,/bool observeCallbackChannels/); assert.match(fence,/lifecyclePeriod/); @@ -45,8 +44,7 @@ test('P0 immutable independent stream format fence blocks silent device/period/m assert.match(device,/formatFence_\.resetStopped\(\)/); assert.match(engine,/bridgeNegotiationFault/); assert.match(host,/getProperty \("bridgeNegotiationFault", "NONE"\)/); - assert.match(cmake,/IndependentStreamNegotiatedFormatFence/); - assert.match(workflow,/ARMixIndependentFormatTests/); + assert.match(cmake,/add_test\(NAME IndependentStreamNegotiatedFormatFence COMMAND ARMixIndependentFormatTests\)/); }); test('live deployment preserves direct ASIO and bounded rollback semantics',()=>{ @@ -143,7 +141,8 @@ test('ASIO is the preferred first-run live backend only for one same-driver dupl test('saved ASIO startup failure keeps the host callback registered for manual AUDIO SETUP recovery',()=>{ const registration=engine.indexOf('deviceManager_.addAudioCallback (this);'); - const initialise=engine.indexOf('auto error = deviceManager_.initialise (1, 2, savedSettings, !savedRoute);'); + // Product default requests stereo IN 1+2; saved explicit masks remain authoritative. + const initialise=engine.indexOf('auto error = deviceManager_.initialise (2, 2, savedSettings, !savedRoute);'); assert.ok(registration>=0 && registration& buffer,juce::MidiBuffer&)override{ for(int c=0;c makeGraph(float firstFx,float returnFx,bool withFx=true) { @@ -178,7 +186,18 @@ static void verifyUniversalChannelIdFxLeaseAndLivePcm() { auto second=newFx(1.25f,"ch11-second-vst3"); assert(Bank::appendOwned(epoch,3,bank,ch11,ProcessingFormat::mono, second,expanded)==Bank::Fault::none); + // Rack OFF applies to the new plugin too; old per-plugin OFF remains + // untouched and native append carries the same authoritative override. + assert(bank.setRackBypass(epoch,2,ch11,true)); + assert(bank.rackBypassed(ch11)); assert(expanded.insertCount(ch11)==2); + // expanded was already created before the OFF gesture. Its revision + // holds the same shared rack gate, so it observes the control live. + assert(expanded.rackBypassed(ch11)); + assert(!expanded.setRackBypass(epoch,2,ch11,false)); // stale version + assert(expanded.setRackBypass(epoch,3,ch11,false)); + assert(!bank.rackBypassed(ch11)); + assert(!expanded.rackBypassed(ch11)); assert(expanded.insertCount(ch1)==bank.insertCount(ch1)); assert((*expanded.ownerForControl(ch11,0))->instanceId== (*bank.ownerForControl(ch11,0))->instanceId); @@ -199,9 +218,8 @@ static void verifyUniversalChannelIdFxLeaseAndLivePcm() { alias[1].inserts=first.inserts; // same native processor twice assert(Bank::prepare(epoch,2,alias,blocked)==Bank::Fault::duplicateInstance); assert(blocked.lanes()==0); - // Native PDC is not yet installed. A real JUCE AudioProcessor reporting - // 64 samples of plugin delay must be rejected BEFORE accepted PCM/lease - // publication; mixing uncompensated Return with MAIN is phase-unsafe. + // A fixed-latency VST lease is admitted; the PCM publisher consumes its + // exact inventory to prepare fan-in compensation before publication. auto latentProcessor=std::make_unique(1.5f); latentProcessor->setLatencySamples(64); latentProcessor->prepareToPlay(48000.0,64); @@ -211,8 +229,8 @@ static void verifyUniversalChannelIdFxLeaseAndLivePcm() { std::move(latentProcessor),"latent-vst","latency-64",64)); const std::array latentScene{latent}; assert(Bank::prepare(epoch,2,latentScene,blocked)== - Bank::Fault::uncompensatedLatency); - assert(blocked.lanes()==0); // failed admission cannot mutate previous bank + Bank::Fault::none); + assert(blocked.latencySamples(ch11)==64); assert(Bank::prepare(epoch,2,assignments,blocked)==Bank::Fault::none); const auto token=original->insertInstanceId(0,0); auto migrated=*bank.ownerForControl(ch1,0); @@ -1871,9 +1889,257 @@ static void verifyChannelIdGroupPreservesHostedFx() { assert(heapCalls.load(std::memory_order_relaxed)==heapBefore); assert(GainFx::living==pluginCount&&fallbackCalls==0); assert(!live.setLiveMix(epoch,2,voice,0.f,0.f)); + Bank rebound; + assert(Bank::rebindSameFormat(epoch,4,*nextBank,rebound)==Bank::Fault::invalidEpoch); + assert(nextBank->setRackBypass(epoch,3,voice,true)); + assert(Bank::rebindSameFormat(epoch+1,4,*nextBank,rebound)==Bank::Fault::none); + assert(rebound.ownerForControl(voice,0)->get()==nextBank->ownerForControl(voice,0)->get()); + assert(rebound.rackBypassed(voice)); + assert(!rebound.setInsertBypass(epoch,4,voice,0,token,true)); + assert(rebound.setInsertBypass(epoch+1,4,voice,0,token,true)); + assert(GainFx::living==pluginCount); live.unpublish();live.pollRetirement(); } +static void verifyLatencyAlignedBypass() { + // Real JUCE processing (not merely reporting a latency value): an impulse + // remains at sample 7 through wet, individual bypass and rack bypass. + for(int mode=0;mode<3;++mode){ + auto p=std::make_unique(1.f,7);p->prepareToPlay(48000,64); + LiveChannelFxGraph::FxInstance fx(std::move(p),"delayed","7 samples",64); + fx.bypassRequested.store(mode==1); + std::array l{},r{}; + // Reach the bypass envelope's steady state first. + for(int block=0;block<10;++block){l.fill(0);r.fill(0);fx.render(l.data(),r.data(),64,mode==2);} + l.fill(0);r.fill(0);l[0]=r[0]=1; + const auto before=heapCalls.load(); + fx.render(l.data(),r.data(),64,mode==2); + assert(heapCalls.load()==before); + for(int i=0;i<64;++i)assert(near(l[i],i==7?1.f:0.f)&&near(l[i],r[i])); + fx.processor->setLatencySamples(8); + assert(fx.latencyChanged.load()); // no unaligned wet enters accepted PCM + l.fill(0);r.fill(0);l[0]=r[0]=1; + fx.render(l.data(),r.data(),64,mode==2); + for(int i=0;i<64;++i)assert(near(l[i],i==7?1.f:0.f)); + } +} +static void verifyNativeFxRackTransactions() { + DynamicChannelRoster roster; + std::vector add; + for(int i=0;i<3;++i){ChannelEdit e;e.kind=ChannelEdit::Kind::add;e.position=i; + e.role=i==2?ChannelRole::main:ChannelRole::input;e.format=ProcessingFormat::stereo;e.text="channel";add.push_back(e);} + const auto created=roster.edit(0,add);assert(created.ok()); + const auto source=created.createdIds[0],dest=created.createdIds[1],main=created.createdIds[2]; + std::vector refs; + for(auto label:{"gain","offset"}){ChannelEdit e;e.kind=ChannelEdit::Kind::addInsertReference;e.id=source;e.text=label;refs.push_back(e);} + for(auto id:{source,dest}){ChannelEdit e;e.kind=ChannelEdit::Kind::setPrimaryOutput;e.id=id;e.target=main;refs.push_back(e);} + assert(roster.edit(1,refs).ok()); + auto gain=std::make_unique(2.f);gain->prepareToPlay(48000,64); + auto offset=std::make_unique(1.f,0,1.f);offset->prepareToPlay(48000,64); + auto a=std::make_shared(std::move(gain),"gain","gain",64); + auto b=std::make_shared(std::move(offset),"offset","offset",64); + DynamicChannelFxLeaseBank::Assignment binding;binding.id=source;binding.inserts={a,b}; + DynamicChannelFxLeaseBank initial; + assert(DynamicChannelFxLeaseBank::prepare(11,1,std::span(&binding,1),initial)==DynamicChannelFxLeaseBank::Fault::none); + auto bank=std::make_shared(std::move(initial)); + DynamicNativeSessionPublisher publisher;DynamicGraphRequest request; + request.physicalInputs=4;request.maxFrames=64;request.sources={{source,0,1,true},{dest,2,3,true}}; + std::uint64_t revision=0; + const auto publish=[&](){ + DynamicNativeSessionPublisher::FxPlan fx;fx.owner=bank;fx.context=bank.get();fx.deviceEpoch=11;fx.graphRevision=revision+1; + fx.render=+[](void* p,ChannelId id,float* l,float* r,int n) noexcept{(*static_cast(p))(id,l,r,n);}; + fx.latency=+[](void* p,ChannelId id) noexcept{return static_cast(p)->latencySamples(id);}; + assert(publisher.commit(roster,request,revision,11,11,false,fx,false,true).ok());++revision; + }; + const auto samples=[&](float expected){ + std::array input{},other{},l{},r{};input.fill(.25f);other.fill(.1f); + const float* pins[]{input.data(),input.data(),other.data(),other.data()};const auto count=heapCalls.load(); + assert(publisher.render(11,pins,4,l.data(),r.data(),64,false,[](ChannelId,float*,float*,int) noexcept{})); + assert(heapCalls.load()==count);for(int i=0;i<64;++i)assert(near(l[i],expected)&&near(l[i],r[i])); + }; + publish();samples(1.6f);const int prepares=GainFx::prepared; + const auto edit=[&](ChannelId from,std::size_t slot,const juce::String& token,ChannelId to,std::size_t pos){ + DynamicChannelRoster next;DynamicChannelFxLeaseBank owners; + assert(prepareNativeFxRackEdit(11,revision,roster.revision(),roster,*bank,from,slot,token,to,pos,next,owners)); + roster=std::move(next);bank=std::make_shared(std::move(owners));publish(); + assert(GainFx::prepared==prepares); // no scan, instantiation or prepare/reset + }; + DynamicChannelRoster rejected;DynamicChannelFxLeaseBank rejectedBank; + assert(!prepareNativeFxRackEdit(11,revision,roster.revision(),roster,*bank,source,0,"wrong",dest,0,rejected,rejectedBank)); + assert(!prepareNativeFxRackEdit(12,revision,roster.revision(),roster,*bank,source,0,a->instanceId,dest,0,rejected,rejectedBank)); + assert(!prepareNativeFxRackEdit(11,revision,roster.revision()-1,roster,*bank,source,0,a->instanceId,dest,0,rejected,rejectedBank)); + assert(!prepareNativeFxRackEdit(11,revision,roster.revision(),roster,*bank,source,0,a->instanceId,dest,9,rejected,rejectedBank)); + samples(1.6f); + edit(source,0,a->instanceId,source,1);samples(2.6f);assert(bank->retainsEditor(a)); + edit(source,1,a->instanceId,dest,0);samples(1.45f); + assert(bank->retainsEditor(a)&&(*bank->ownerForControl(dest,0)).get()==a.get()); + assert(roster.find(source)->insertCatalogIds==std::vector{"offset"}); + assert(roster.find(dest)->insertCatalogIds==std::vector{"gain"}); + edit(source,0,b->instanceId,{},0);samples(.45f);assert(!bank->retainsEditor(b)); + edit(dest,0,a->instanceId,{},0);samples(.35f);assert(!bank->retainsEditor(a)); +} + +// Native eight-band Parametric EQ must be the exact ordered rack lease in PCM, +// not an independent "pre-VST" bank, a JS preview or a second audio callback. +// Verifies asynchronous audio-owned ACK while the same insert is bypassed, +// graph revision-safe reorder, and no allocations in the hot render call. +static void verifyNativeBuiltinEqOrderedPcmAndBypassAck() { + using Bank=DynamicChannelFxLeaseBank; + using Eq=armix::builtin_fx::ChannelEqProcessor; + constexpr std::uint64_t ep=10997,revision=11; + const ChannelId ch{12345678901234ULL}; + std::unique_ptr eq=std::make_unique(); + eq->prepareToPlay(48000.,64); + assert(eq->isReady()); + Eq* live=eq.get(); + auto eqLease=std::make_shared( + std::move(eq),Eq::catalogIdentity,"Parametric EQ",64); + auto other=std::make_unique(1.0f,0,.2f); + other->prepareToPlay(48000.,64); + auto offsetLease=std::make_shared( + std::move(other),"nonlinear-order-probe","Offset after EQ",64); + Bank::Assignment a;a.id=ch;a.format=ProcessingFormat::stereo; + a.inserts={eqLease,offsetLease}; + std::array assignment{a}; + Bank graph; + assert(Bank::prepare(ep,revision,assignment,graph)==Bank::Fault::none); + assert(graph.insertCount(ch)==2 && graph.latencySamples(ch)==0); + assert((*graph.ownerForControl(ch,0))->instanceId==eqLease->instanceId); + assert((*graph.ownerForControl(ch,1))->instanceId==offsetLease->instanceId); + armix::builtin_fx::Band hp{}; + hp.enabled=true;hp.frequencyHz=1000.f;hp.gainDb=0.f; + hp.q=.70710678f;hp.slope=armix::builtin_fx::Slope::db12; + assert(live->queueBand(0,hp,1)); + std::array l{},r{}; + const auto renderBlocks=[&](const Bank& bank,int blocks) { + const auto allocations=heapCalls.load(std::memory_order_relaxed); + for(int b=0;bpollCompletion(done)&&done.applied&&done.requestId==1); + assert(done.bandIndex==0&&live->acceptedBands()[0].enabled); + // A constant .5 enters HPF, then post-EQ vendor offset +.2 survives. + assert(std::abs(l.back()-.2f)<.04f &&std::abs(r.back()-.2f)<.04f); + const auto token=eqLease->instanceId; + assert(!graph.setInsertBypass(ep,revision-1,ch,0,token,true)); + assert(!graph.setInsertBypass(ep,revision,ch,0,"wrong",true)); + assert(graph.setInsertBypass(ep,revision,ch,0,token,true)); + renderBlocks(graph,64); + assert(std::abs(l.back()-.7f)<.04f); + // Fully bypassed native EQ still consumes audio-synchronized commands; + // no ACK may be fabricated from the control-thread enqueue itself. + hp.frequencyHz=1600.f; + assert(live->queueBand(0,hp,2)); + assert(!live->pollCompletion(done)); + renderBlocks(graph,2); + assert(live->pollCompletion(done)&&done.applied&&done.requestId==2); + assert(std::abs(live->acceptedBands()[0].frequencyHz-1600.f)<.01f); + assert(graph.setInsertBypass(ep,revision,ch,0,token,false)); + renderBlocks(graph,64); + assert(std::abs(l.back()-.2f)<.04f); + Bank moved; + assert(Bank::editOwned(ep,revision+1,graph,ch,0,token, + ch,1,ProcessingFormat::stereo,moved)==Bank::Fault::none); + assert(moved.insertCount(ch)==2); + assert((*moved.ownerForControl(ch,1)).get()==eqLease.get()); + assert((*moved.ownerForControl(ch,0)).get()==offsetLease.get()); + // Exact EQ now comes AFTER the offset-producing FX, so the HPF removes + // DC from both input and offset. This distinguishes true PCM FX ordering. + renderBlocks(moved,64); + assert(std::abs(l.back())<.04f && std::abs(r.back())<.04f); + assert(!moved.setInsertBypass(ep,revision,ch,1,token,true)); + assert(moved.leaseEditor(ep,revision+1,ch,1,token).get()==eqLease.get()); +} + +// Binary EQ state is captured only when the audio mailbox has settled. +// The verifier covers the pending/ACK window, state fidelity and the +// pre-publication restore rule without touching live device or worker threads. +static void verifyNativeEqCaptureRequiresAcceptedDspAndOfflineRestore() { + using Eq=armix::builtin_fx::ChannelEqProcessor; + auto processor=std::make_unique(); + processor->prepareToPlay(48000.0,64); + assert(processor->isReady()); + Eq* live=processor.get(); + auto owner=std::make_shared( + std::move(processor),Eq::catalogIdentity,"Parametric EQ",64); + armix::builtin_fx::Band b{}; + b.enabled=true;b.frequencyHz=2500.f;b.gainDb=5.f;b.q=1.2f; + b.slope=armix::builtin_fx::Slope::db12; + assert(live->queueBand(2,b,501)); + juce::MemoryBlock saved; + assert(!owner->tryCaptureState(saved)); // queued, not audio-owned + std::array left{},right{}; + left.fill(.1f);right.fill(.1f); + const auto heapBefore=heapCalls.load(std::memory_order_relaxed); + owner->render(left.data(),right.data(),64); + assert(heapCalls.load(std::memory_order_relaxed)==heapBefore); + assert(!owner->tryCaptureState(saved)); // applied but not ACK-consumed + Eq::Completion ack{}; + assert(live->pollCompletion(ack)&&ack.applied&&ack.requestId==501); + assert(ack.bandIndex==2&&ack.band.gainDb==5.f); + assert(owner->tryCaptureState(saved)); // control state now stable + assert(saved.getSize()==8+8*14); + assert(!live->restoreUnpublishedState(saved.getData(), + static_cast(saved.getSize()))); // published LIVE = immutable + + // A newly built Show candidate may restore before preparation. + Eq restored; + assert(restored.restoreUnpublishedState(saved.getData(), + static_cast(saved.getSize()))); + assert(restored.acceptedBands()[2].enabled); + assert(restored.acceptedBands()[2].frequencyHz==2500.f); + assert(restored.acceptedBands()[2].gainDb==5.f); + restored.prepareToPlay(44100.0,64); + assert(restored.isReady()); + assert(restored.acceptedBands()[2].q==1.2f); + + // The existing Show pipeline restores vendor states after preparation. + // That must work too, but only while the candidate is NOT published. + auto prepared=std::make_unique(); + prepared->prepareToPlay(96000.0,128); + assert(prepared->restoreUnpublishedState(saved.getData(), + static_cast(saved.getSize()))); + assert(prepared->acceptedBands()[2].gainDb==5.f); + juce::MemoryBlock bad(saved); + static_cast(bad.getData())[0]^=0x5f; + assert(!prepared->restoreUnpublishedState(bad.getData(), + static_cast(bad.getSize()))); + assert(prepared->acceptedBands()[2].gainDb==5.f); + auto sealed=std::make_shared( + std::move(prepared),Eq::catalogIdentity,"Restored EQ",128); + auto* sealedEq=dynamic_cast(sealed->processor.get()); + assert(sealedEq&&!sealedEq->restoreUnpublishedState(saved.getData(), + static_cast(saved.getSize()))); + assert(sealed->tryCaptureState(bad)); // restored bank is quiescent + + // At 48 kHz a disabled high band can remember 20 kHz; restoring the + // same Show at 44.1 kHz clamps ONLY that inactive band to the safe cap. + auto source=std::make_unique(); + source->prepareToPlay(48000.0,64); + auto* sourceEq=source.get(); + auto sourceOwner=std::make_shared( + std::move(source),Eq::catalogIdentity,"High band",64); + armix::builtin_fx::Band inactive{}; + inactive.enabled=false;inactive.frequencyHz=20000.f; + assert(sourceEq->queueBand(7,inactive,502)); + sourceOwner->render(left.data(),right.data(),64); + Eq::Completion highAck{}; + assert(sourceEq->pollCompletion(highAck)&&highAck.applied); + juce::MemoryBlock highState; + assert(sourceOwner->tryCaptureState(highState)); + Eq lowerRate; + lowerRate.prepareToPlay(44100.0,64); + assert(lowerRate.restoreUnpublishedState(highState.getData(), + static_cast(highState.getSize()))); + assert(lowerRate.acceptedBands()[7].frequencyHz<=19845.f); +} + int main(int argc,char** argv) { if(argc==2 && std::string(argv[1])=="--emit-console-s0-json") { verifyNativePuzzleV8FixtureAndWire(); @@ -2246,6 +2512,33 @@ int main(int argc,char** argv) { assert(heapCalls.load(std::memory_order_relaxed)==beforeNextProcess); assert(left[0]>.3f); } + // FX RACK POWER: one atomic master overrides effective processing, + // without destroying the ON/OFF preferences of individual inserts. + { + auto graph=makeGraph(2.f,3.f); + const auto token=graph->insertInstanceId(0); + assert(!graph->rackBypassed(0)); + assert(graph->setInsertBypass(0,0,token,true)); // individual OFF + assert(graph->insertBypassed(0,0)); + assert(graph->setRackBypass(0,true)); // master OFF + assert(graph->rackBypassed(0)&&graph->insertBypassed(0,0)); + assert(graph->setRackBypass(0,false)); // master ON + assert(!graph->rackBypassed(0)); + assert(graph->insertBypassed(0,0)); // stays OFF + assert(graph->setInsertBypass(0,0,token,false)); + assert(graph->setRackBypass(0,true)); + assert(graph->setRackBypass(0,false)); + assert(!graph->insertBypassed(0,0)); // returns to ON + assert(!graph->setRackBypass(-1,true)); + assert(!graph->setRackBypass(LiveChannelFxGraph::fxSlots,true)); + auto moved=makeGraph(1.f,1.f,false); + assert(graph->setRackBypass(0,true)); + assert(moved->reuse(0,*graph,"vst3-ch1-id")); + assert(moved->rackBypassed(0)); // graph retirement retains gate + assert(moved->insertBypassed(0,0)==graph->insertBypassed(0,0)); + assert(moved->setRackBypass(0,false)); + assert(!moved->insertBypassed(0,0)); // saved ON restored + } // Run M5 AFTER the legacy suite: older M4 tests use absolute global // GainFx::living/released counters as their own lifetime oracle. Running // M5 before them changes those historical baseline counts, not DSP. @@ -2258,6 +2551,10 @@ int main(int argc,char** argv) { verifyFirstSoundOnePinNativeSourceDraft(); verifyNativePuzzleV8FixtureAndWire(); verifyChannelIdGroupPreservesHostedFx(); + verifyLatencyAlignedBypass(); + verifyNativeFxRackTransactions(); + verifyNativeBuiltinEqOrderedPcmAndBypassAck(); + verifyNativeEqCaptureRequiresAcceptedDspAndOfflineRestore(); // Tests above use a real JUCE AudioProcessor processing seam. Vendor // VST3 formats and sound quality require separate Windows hardware FAT. } diff --git a/tests/live_fader_held_drag.test.cjs b/tests/live_fader_held_drag.test.cjs new file mode 100644 index 000000000..d6edfd800 --- /dev/null +++ b/tests/live_fader_held_drag.test.cjs @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// P0: native fader targets must leave the GUI while the pointer is still held. +// This is a bridge/ACK regression, NOT a physical speaker FAT. +const test=require("node:test"); +const assert=require("node:assert/strict"); +const {readFileSync}=require("node:fs"); +const vm=require("node:vm"); +const protocol=require("../web/approved-native-contract.js"); +const read=p=>readFileSync(p,"utf8"); +const clone=x=>JSON.parse(JSON.stringify(x)); +const fixture=JSON.parse(read("integration/console-v6/fixtures.json")).g0; +function nativeChannelIdFixture(){ + const s=clone(fixture),main="18446744073709551615"; + s.device.epoch="18446744073709551610"; + s.productionCallbackLive=true; + s.graph.revision="5";s.graph.rosterRevision="7"; + s.graph.mainChannelId=main; + s.graph.capabilities.callbackOwnsChannelIds=true; + s.graph.capabilities.supportedOps=["SET_FADER","SET_PAN","SET_MUTE","APPLY_WIRE_TRANSACTION"]; + const ids=Array.from({length:10},(_,i)=>String(9007199254740994n+BigInt(i))); + s.graph.channels=ids.map((id,i)=>({ + id,role:"INPUT",name:"CH"+(i+1),processingFormat:"MONO", + primaryOutId:main, + controls:{faderDb:-6,pan:0,mute:false,solo:false},inserts:[],sends:[] + })); + s.graph.channels.push({ + id:main,role:"MAIN",name:"MAIN",processingFormat:"STEREO", + controls:{faderDb:0,pan:0,mute:false,solo:false},inserts:[],sends:[] + }); + s.graph.destinations=[{id:main}];s.graph.edges=[]; + s.legacyM4={routingRevision:"3"}; + s.mixerSession={ + authority:"CHANNEL_ID",deviceEpoch:s.device.epoch, + routeRevision:s.graph.revision,rosterRevision:s.graph.rosterRevision, + channels:s.graph.channels,main:{db:0,mute:false} + }; + return s; +} +function harness({m4=false}={}){ + const sent=[],listeners=new Map(),timers=[],visual=[],meters=[]; + const m4Tracks=m4?Array.from({length:10},(_,i)=>({ + id:1000+i,name:"CH"+(i+1),kind:"audio",format:"mono",level:-6, + pan:0,mute:false,solo:false,input:"None",output:"Master",fxOn:true, + fx:Array(8).fill("None"),slotBypass:Array(8).fill(false) + })):[]; + const roots=new Map(m4Tracks.map(t=>[t.id,{ + isConnected:true, + querySelector:q=>q===".meter-fill.left"?{lane:t.id,side:"L"}: + q===".meter-fill.right"?{lane:t.id,side:"R"}:null + }])); + let now=1000,nextId=100; + const scope={ + tracks:m4Tracks,master:{id:1,name:"MAIN",kind:"master",level:0, + pan:0,mute:false,output:"Realtek"},colors:["#568ead"], + wireGraph:{validateCandidateGraph:()=>({ok:true})}, + make:(name,kind,color)=>({id:nextId++,name,kind,color,selected:false}), + render(){},findTrack(el){return this.tracks[el.lane||0];}, + displayMeterDbfs(fill,db){meters.push({fill,db});}, + refreshStrip(){},allocateWireId(){return nextId++;}, + installGraph(channels,master,edges){this.tracks=channels;this.master=master;this.edges=edges;}, + syncFaderVisual(t){visual.push({id:t.id,db:t.level});}, + stopDemo(){} + }; + const backend={ + emitEvent:(name,payload)=>sent.push({name,payload}), + addEventListener:(name,fn)=>listeners.set(name,fn) + }; + const document={ + readyState:"complete",documentElement:{dataset:{}}, + getElementById:id=>id==="info"?{textContent:""}: + id==="preview"?{disabled:false,setAttribute(){}}:null, + querySelector:q=>{ + const match=/\.strip\[data-id="(\d+)"\]/.exec(q); + return match?roots.get(Number(match[1]))||null:null; + },addEventListener(){} + }; + const window={ + __JUCE__:{backend},ArSonApprovedNativeContract:protocol, + __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){}, + setTimeout(fn,delay=0){timers.push({fn,at:now+Math.max(0,Number(delay)||0)});return timers.length;} + }; + vm.runInNewContext(read("web/approved-native-bridge.js"),{ + window,document,performance:{now:()=>now},console + },{timeout:2500}); + return {scope,window,backend,sent,listeners,timers,visual,meters, + tick(ms=40){ + now+=ms; + for(let i=0;inow){i++;continue;} + timers.splice(i,1);timer.fn(); + } + } + }; +} +test("held ChannelId drag publishes first gain and coalesces latest BEFORE release",()=>{ + const h=harness(),s=nativeChannelIdFixture(); + h.listeners.get("arMixConsoleSnapshot")(s); + assert.equal(h.window.__ARMIX_APPROVED_NATIVE_GUI__.acceptedGraphConnected,true); + // Pointerdown and successive pointermoves: the approved Pages setFaderFromPointer + // calls handleField(type=input), which the native-only builder forwards here. + const fader={dataset:{field:"level"},lane:4,value:"-12",min:"-60",max:"10",closest:()=>null}; + const move=db=>{ + fader.value=String(db); + assert.equal(h.window.__ARMIX_NATIVE_M2__.consumeField({target:fader,type:"input"}),true); + }; + move(-12); // pointerdown (button still pressed) + assert.equal(h.visual.at(-1).db,-12,"readout immediately follows finger, not native ACK"); + const first=h.sent.findLast(e=>e.name==="arMixConsoleIntent").payload; + assert.equal(first.operation,"SET_FADER"); + assert.equal(first.targetChannelId,s.graph.channels[4].id,"CH5 exact native ChannelId"); + assert.equal(first.payload.valueDb,-12,"native target emitted without pointerup"); + move(-18);move(-24);h.tick(); + assert.equal(h.window.__ARMIX_NATIVE_M2__.state().pending?.operation,"SET_FADER", + "a 40ms UI tick must NEVER execute the native 8000ms timeout"); + assert.equal(h.sent.filter(e=>e.name==="arMixConsoleIntent").length,1, + "one in-flight native ACK: latest queued, no unbounded event storm"); + assert.equal(h.visual.at(-1).db,-24,"CH5 readout updates during mouse hold"); + const old=clone(s); // ACK alone does not repaint the accepted model + h.listeners.get("arMixConsoleAck")({ + requestId:first.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:s.device.epoch,graphRevision:"5",rosterRevision:"7" + }); + assert.equal(h.scope.tracks[4].level,-6); + old.graph.channels[4].controls.faderDb=-12; + h.listeners.get("arMixConsoleSnapshot")(old); + assert.equal(h.visual.at(-1).db,-24, + "old native ACK/readback may update model, never snap the visual fader backwards"); + h.tick(); + const second=h.sent.filter(e=>e.name==="arMixConsoleIntent").at(-1).payload; + assert.equal(second.payload.valueDb,-24, + "latest intermediate target sent while pointer remains HELD"); + assert.notEqual(second.requestId,first.requestId); + // This is still BEFORE pointerup; the native backend can apply a second + // PCM gain target through its existing atomic ChannelId SET_FADER setter. + h.listeners.get("arMixConsoleAck")({ + requestId:second.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:s.device.epoch,graphRevision:"5",rosterRevision:"7" + }); + const updated=clone(old);updated.graph.channels[4].controls.faderDb=-24; + h.listeners.get("arMixConsoleSnapshot")(updated); + assert.equal(h.scope.tracks[4].level,-24); + move(-30); // final mouse pointerup will commit this new value + h.window.__ARMIX_NATIVE_M2__.consumeField({target:fader,type:"change"}); + // Pointer capture has ended. A delayed old native snapshot is NOT permission + // to replace the final target that is still in flight. + h.listeners.get("arMixConsoleSnapshot")(clone(updated)); + assert.equal(h.visual.at(-1).db,-30,"released cap holds final latest target"); + const final=h.sent.filter(e=>e.name==="arMixConsoleIntent").at(-1).payload; + assert.equal(final.payload.valueDb,-30,"release flushes final value"); + assert.equal(h.scope.tracks[4].level,-24,"no optimistic native readback"); + h.listeners.get("arMixConsoleAck")({ + requestId:final.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:s.device.epoch,graphRevision:"5",rosterRevision:"7" + }); + const accepted=clone(updated);accepted.graph.channels[4].controls.faderDb=-30; + h.listeners.get("arMixConsoleSnapshot")(accepted); + assert.equal(h.scope.tracks[4].level,-30); +}); +test("all CH1/CH2/CH5/CH10 and MAIN pointermove use native scalar path",()=>{ + const source=read("site/preview-v2/index.html"); + const builder=read("scripts/build_approved_native_gui.py"); + const bridge=read("web/approved-native-bridge.js"); + const native=read("src/LiveDryRoutingLab.h"); + assert.match(source,/function setFaderFromPointer\(ev,gesture\)/); + assert.match(source,/handleField\(\{target:input,type:'input'/); + assert.match(source,/if\(!faderGesture\|\|ev.pointerId!==faderGesture.pointerId\)return;\s*setFaderFromPointer\(ev,faderGesture\);/); + assert.match(builder,/window\.__ARMIX_NATIVE_M2__\?\.consumeField\?\.\(event\)/); + assert.match(bridge,/mixerSession\(\)\?\.authority==="CHANNEL_ID"/); + assert.match(bridge,/parameter==="faderDb"\?"SET_FADER":"SET_PAN"/); + assert.match(native,/updated\.linear=value<= -60\.f\?0\.f:std::pow\(10\.f,value\/20\.f\)/); + assert.match(native,/setNativeInputMix\(expectedEpoch,nativeAccepted_\.pcmRevision/); + // Valid input faders retain strict ChannelId mapping across a channel reorder. + // A real callback/PCM FAT is still required; gain math alone is NOT a sound test. + const h=harness(),s=nativeChannelIdFixture(); + // The physical-host MAIN gateway uses safe integer transport tokens, while + // ChannelId itself deliberately remains an exact uint64 decimal string. + s.device.epoch="77";s.mixerSession.deviceEpoch="77"; + h.listeners.get("arMixConsoleSnapshot")(s); + let accepted=s; + for(const lane of [0,1,4,9]){ + const value=-8-lane; + const fader={dataset:{field:"level"},lane,value:String(value)}; + assert.equal(h.window.__ARMIX_NATIVE_M2__.consumeField({target:fader,type:"input"}),true); + const cmd=h.sent.filter(e=>e.name==="arMixConsoleIntent").at(-1).payload; + assert.equal(cmd.targetChannelId,accepted.graph.channels[lane].id, + "CH"+(lane+1)+" exact ChannelId before pointerup"); + assert.equal(cmd.payload.valueDb,value); + h.listeners.get("arMixConsoleAck")({ + requestId:cmd.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:accepted.device.epoch,graphRevision:"5",rosterRevision:"7" + }); + const next=clone(accepted);next.graph.channels[lane].controls.faderDb=value; + h.listeners.get("arMixConsoleSnapshot")(next); + assert.equal(h.scope.tracks[lane].level,value); + accepted=next;h.tick(); + } + const master={dataset:{field:"level"},lane:10,value:"-9"}; + h.scope.findTrack=el=>el.lane===10?h.scope.master:h.scope.tracks[el.lane||0]; + assert.equal(h.window.__ARMIX_NATIVE_M2__.consumeField({target:master,type:"input"}),true); + const main=h.sent.filter(e=>e.name==="arMixAction").at(-1); + assert.equal(main.payload.action,"routingM4Control"); + assert.equal(main.payload.channel,-1); + assert.equal(main.payload.parameter,"masterGain"); + assert.equal(main.payload.controlValue,-9); + assert.match(bridge,/edit\.t\?\.kind==="master"\s*\|\|\s*m4ControlIsOwner\(\)/, + "MAIN scalar uses guarded native host gain"); +}); + +test("pending M4 fader ACK never stalls independently accepted meters, FX rack or mute",()=>{ + const h=harness({m4:true}),s=clone(fixture),rev="3"; + const controls=()=>({faderDb:-6,pan:0,mute:false,solo:false}); + const source=()=>({mode:"MONO",left:0,right:-1,main:true,channelFormat:"MONO"}); + s.legacyM4={ + active:true,routeAccepted:true,routingRevision:rev, + channelControls:Array.from({length:10},controls), + channels:Array.from({length:10},source), + fxInstances:Array.from({length:10},()=>Array(8).fill(null)) + }; + s.mixerSession={ + authority:"M4",deviceEpoch:s.device.epoch,routeRevision:rev, + channels:Array.from({length:10},()=>({ + source:source(),main:true,channelFormat:"MONO",controls:controls(), + fxRackBypassed:false,peakL:0.1,peakR:0.1 + })),main:{db:0,mute:false} + }; + const snapshot=h.listeners.get("arMixConsoleSnapshot"); + snapshot(s); + assert.equal(h.meters.length,20,"ten-channel hardware meters are live"); + const ch5={dataset:{field:"level"},lane:4,value:"-12",min:"-60",max:"10"}; + assert.equal(h.window.__ARMIX_NATIVE_M2__.consumeField({ + target:ch5,type:"input" + }),true); + const command=h.sent.findLast(e=> + e.name==="arMixAction"&&e.payload.action==="routingM4Control")?.payload; + assert.equal(command?.channel,4); + assert.equal(command.parameter,"faderDb"); + assert.equal(command.controlValue,-12); + const next=clone(s); + next.mixerSession.channels[0].fxRackBypassed=true; + next.mixerSession.channels[3].controls.mute=true; + next.mixerSession.channels[4].peakL=0.45; + snapshot(next); + assert.equal(h.meters.length,40, + "pending CH5 gain must not freeze all 20 physical meter taps"); + assert.equal(h.scope.tracks[0].fxOn,false, + "CH1 real rack state stays independent of CH5 pending gain"); + assert.equal(h.scope.tracks[3].mute,true, + "CH4 accepted mute stays independent of CH5 pending gain"); + assert.equal(h.scope.tracks[4].level,-6, + "unacknowledged CH5 gain must not appear as accepted PCM"); + assert.equal(h.visual.at(-1)?.db,-12, + "the CH5 held fader cap keeps the latest unacknowledged target"); + h.listeners.get("arMixM4ControlAck")({ + requestId:command.requestId,ok:true,deviceEpoch:s.device.epoch, + routingRevision:rev,channel:4,parameter:"faderDb" + }); + const accepted=clone(next); + accepted.mixerSession.channels[4].controls.faderDb=-12; + accepted.legacyM4.channelControls[4].faderDb=-12; + snapshot(accepted); + assert.equal(h.scope.tracks[4].level,-12); + assert.equal(h.meters.length,60); +}); diff --git a/tests/live_graph_contract_test.mjs b/tests/live_graph_contract_test.mjs index 6edcd12f1..77df0958a 100644 --- a/tests/live_graph_contract_test.mjs +++ b/tests/live_graph_contract_test.mjs @@ -62,7 +62,10 @@ test('bypass is sample-smoothed by one original CH1 DSP owner for M4 and native 'native and M4 must share the original CH1 sample-accurate DSP owner'); const originalDSP=e.slice(start,legacy); const adapters=e.slice(legacy,end); - assert.match(originalDSP,/bypass\.request\(graph\.bypassFlags/); + assert.match(originalDSP,/bypass\.request\(graph\.rackBypassed\.load/); + assert.match(originalDSP,/graph\.bypassFlags\[physical\]\.load/); + assert.match(originalDSP,/\|\|/, "rack override must OR with individual insert bypass"); + assert.match(originalDSP,/slot\.processor->processBlock\(buffer,midi\)/); assert.match(originalDSP,/bypass\.transitioning\(\)/); assert.match(originalDSP,/graph\.dryScratch\.getWritePointer\(0\)/); @@ -186,14 +189,20 @@ test('R0B B3 always-on native 10CH startup is verified, muted and unpatched',()= test('R0B B3 preserves diagnostic isolation without exposing an accepted patch',()=>{ const diagnostic=e.slice(e.indexOf('juce::String setDiagnosticRoute'), e.indexOf('armix::diagnostics::Route diagnosticRoute()')); - assert.match(diagnostic,/dryRoutingLab_\.hasExplicitRoute\(\)/); + // Endpoint isolation is allowed for the unedited silent graph, but an + // authored native WIRE/FX session must never be discarded on device change. + assert.match(diagnostic,/dryRoutingLab_\.hasAuthoredMixerContent\(\)/); assert.match(diagnostic,/dryRoutingLab_\.disable\(\)/); assert.match(diagnostic,/startUnpatchedProductionSession\(\)/); assert.match(diagnostic,/resumeVerifiedDirectRoute\(\)/); const manual=e.slice(e.indexOf('void beginManualAudioSetup()'), e.indexOf('bool independentClockActive()')); assert.match(manual,/setOutputMuted\(true\)/); - assert.match(manual,/dryRoutingLab_\.disable\(\)/); + assert.match(manual,/secondaryOutput_\.disarm\(\)/); + assert.doesNotMatch(manual,/dryRoutingLab_\.disable\(\)/); + assert.match(manual,/decideDeviceSession\(/); + assert.match(manual,/Decision::retainBoundMixer/); + assert.match(manual,/Decision::retainUnboundMixer/); assert.match(manual,/startUnpatchedProductionSession\(\)/); assert.doesNotMatch(manual,/setOutputMuted\(false\)/); }); @@ -221,7 +230,7 @@ test('R0B B3 never processes MASTER FX, strips or AUX until explicit ACK',()=>{ lab.indexOf('juce::var status(')); const zero=body.indexOf('FloatVectorOperations::clear(outputs[c],frames)'); const guard=body.indexOf('!userPatched_.load(std::memory_order_acquire)'); - const lease=body.indexOf('publisher_.acquire()'); + const lease=body.indexOf('publisher_.acquire(channelIdRender)'); const dsp=body.indexOf('snapshot->prepared->process('); assert.ok(zero>=0&&guard>zero&&lease>guard&&dsp>lease); assert.match(body,/if\(!userPatched_\.load\(std::memory_order_acquire\)\)/); diff --git a/tests/live_port_epoch_publisher_test.cpp b/tests/live_port_epoch_publisher_test.cpp index cdd09ecd3..a74ec5a91 100644 --- a/tests/live_port_epoch_publisher_test.cpp +++ b/tests/live_port_epoch_publisher_test.cpp @@ -79,6 +79,20 @@ int main() { assert(SpyGraph::alive==1); assert(p.publish(makeGraph(8,1,201),0,8)==Publisher::Result::applied); { auto v=p.acquire();assert(v.get(8)->prepared->value==201); } + { + auto live=p.acquire(); + assert(!p.rebindQuiescent(8,9,[]() noexcept {return true;})); + assert(live.get(8) && !live.get(9)); + } + assert(!p.rebindQuiescent(8,9,[]() noexcept {return false;})); + assert(p.controlPrepared(8,1) && !p.controlPrepared(9,1)); + const auto* retained=p.controlPrepared(8,1); + assert(p.rebindQuiescent(8,9,[&]() noexcept { + auto blocked=p.acquire(); + return !blocked.get(8) && !blocked.get(9); + })); + assert(p.controlPrepared(9,1)==retained && !p.controlPrepared(8,1)); + assert(p.lastRevision()==1); p.unpublish(); assert(p.pollRetirement()); assert(SpyGraph::alive==0); diff --git a/tests/live_routing_ui_contract_test.mjs b/tests/live_routing_ui_contract_test.mjs index 454b8e8e9..2adbad5d1 100644 --- a/tests/live_routing_ui_contract_test.mjs +++ b/tests/live_routing_ui_contract_test.mjs @@ -59,7 +59,7 @@ test("STOP-race is fail closed: all outputs are written to silence without CH1 f assert.match(branch,/const float right=routed\?dryRoutingLab_\.peakRight\(\):0\.f/); }); test("MUTE gate precedes processing and suppresses previous audible crossfade",()=>{ - const start=lab.indexOf("if(snapshot->graphRevision!=audioRevision_"); + const start=lab.indexOf("if(renderRevision!=audioRevision_"); const beforeRender=lab.indexOf("snapshot->prepared->process(",start); const silent=lab.indexOf("if(masterMuted) {",start); assert.ok(start>=0&&silent>start&&beforeRender>silent); @@ -67,7 +67,9 @@ test("MUTE gate precedes processing and suppresses previous audible crossfade",( assert.match(gate,/fadeRemaining_=rampFrames/); assert.match(gate,/fadeFromL_=fadeFromR_=0\.f/); assert.match(gate,/lastOutputL_=lastOutputR_=0\.f/); - assert.match(gate,/return true/); + assert.match(gate,/if\(!meterOnly\)\{silence\(\);return true;\}/); + assert.match(gate,/meterOnly\?mutedMain_\[0\]\.data\(\):mainL\+offset/); + assert.match(lab,/if\(outputs\[c\] && \(meterOnly \|\|/); assert.ok(!lab.includes("masterMuted?0.f:std::clamp(masterGain"), "don't mute before fade and then reintroduce old samples"); }); @@ -197,9 +199,7 @@ test("P1K truly keeps ten physical INPUT strips and adds four independent native assert.match(app,/auxes:draftAux\.map/); assert.match(app,/data-aux-fx/); const cmake=readFileSync(new URL("../CMakeLists.txt",import.meta.url),"utf8"); - const workflow=readFileSync(new URL("../.github/workflows/p1-windows.yml",import.meta.url),"utf8"); - assert.match(cmake,/P1KTenIndependentInputsAndFourDedicatedAuxReturns/); - assert.match(workflow,/ARMixDedicatedAuxBusTests/); + assert.match(cmake,/add_test\(NAME P1KTenIndependentInputsAndFourDedicatedAuxReturns COMMAND ARMixDedicatedAuxBusTests\)/); }); diff --git a/tests/milestone_a_single_authority.test.cjs b/tests/milestone_a_single_authority.test.cjs new file mode 100644 index 000000000..08bb77170 --- /dev/null +++ b/tests/milestone_a_single_authority.test.cjs @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Milestone A real producer wiring contract, not a hardware FAT certificate. +const test=require("node:test"),assert=require("node:assert/strict"); +const fs=require("node:fs"); +const read=p=>fs.readFileSync(p,"utf8"); + +test("only installed callback determines GUI channel control authority",()=>{ + const producer=read("integration/ApprovedNativeRuntimeSnapshot.h"); + const host=read("src/Main.cpp"),adapter=read("web/approved-native-bridge.js"); + assert.match(host,/publishAuthoritativeMixerSession\(accepted\)/); + assert.match(producer,/const auto authority=hasChannelId\?"CHANNEL_ID":validM4\?"M4":"NONE"/); + assert.match(producer,/row->setProperty\("id","m4:"/); + assert.match(adapter,/if\(session\.authority==="M4" && m4Verified\(\)\)/); + assert.match(adapter,/const nativeAdmitted=session\.authority==="CHANNEL_ID"/); + assert.match(adapter,/m4ControlIsOwner\(\)&&m4Verified\(\)&&m4Index\(t\)>=0/); + assert.doesNotMatch(adapter,/rackSavedBypass/); + assert.match(adapter,/const ctl=session\.channels\.map\(row=>row\.controls\)/); + assert.match(adapter,/session\.channels\.map\(ch=>ch\.source\)/); + assert.match(producer,/row->setProperty\("fxRackBypassed",rackFlags\[i\]\)/); + assert.doesNotMatch(adapter,/AudioContext|AudioWorklet/); +}); +test("M4 scalar commands require correlated ACK then later publisher snapshot",()=>{ + const host=read("src/Main.cpp"),adapter=read("web/approved-native-bridge.js"); + for(const name of ["deviceEpoch","routingRevision","channel","parameter"]) + assert.match(host,new RegExp('ack->setProperty\\("'+name+'"')); + assert.match(adapter,/pendingM4Controls\.set\(key/); + assert.match(adapter,/if\(!item\)return/); + assert.match(adapter,/p\.acked=true/); + assert.match(adapter,/reconcileM4ControlReadback\(next\)/); + assert.match(adapter,/session\?\.channels\?\.\[p\.channel\]/); +}); +test("FX rack parent is a producer gate with independent slot preferences",()=>{ + const host=read("src/Main.cpp"),adapter=read("web/approved-native-bridge.js"); + const fx=read("engine/core/LiveChannelFxGraph.h"); + const lease=read("engine/core/DynamicChannelFxLeaseBank.h"); + assert.match(host,/action=="routingFxRackBypass"/); + assert.match(host,/setDryRoutingLabFxRackBypass/); + assert.match(host,/routingNativeFxRackBypass/); + assert.match(adapter,/requestM4RackPower\(t\)/); + assert.match(adapter,/requestAdmittedFxPower\(t,action,btn\)/); + assert.match(adapter,/reconcileM4RackReadback\(next\)/); + assert.match(fx,/rackBypassed_\[strip\]/); + assert.match(lease,/setRackBypass\(/); + assert.doesNotMatch(adapter,/rackSavedBypass/); +}); +test("native ChannelId source preserves post-fader physical MAIN and VST3",()=>{ + const producer=read("integration/ApprovedNativeRuntimeSnapshot.h"); + const host=read("src/Main.cpp"); + const engine=read("src/LiveAudioEngine.h"); + assert.match(producer,/physicalMasterDb/); + assert.match(host,/channel==-1 \|\|/); + assert.match(engine,/setDryRoutingLabParameter/); + assert.match(engine,/insertDryRoutingLabFx/); + assert.match(engine,/applyGuardedDryTopology/); +}); diff --git a/tests/mixer_io_smoke.py b/tests/mixer_io_smoke.py index 6f47d8cdb..42f0cbee5 100644 --- a/tests/mixer_io_smoke.py +++ b/tests/mixer_io_smoke.py @@ -53,9 +53,18 @@ async def main(): assert all(abs(a-b)<1 for a,b in zip(sizes,after)),(sizes,after) await page.locator('[data-mix-mode="ROUTE"]').click() assert "UNPATCHED" in await page.locator('[data-strip="1"] .arBankOutput').inner_text() - palette=await page.evaluate("""() => ['FX','ROUTE'].map(x=>getComputedStyle( - document.querySelector('[data-mix-mode="'+x+'"]')).backgroundColor)""") - assert palette[0]!=palette[1],palette + # Physical BTN-180 is a layered gradient. backgroundColor alone is + # not the live visual state; verify the actual active token and ARIA. + modes=await page.evaluate("""() => ['FX','ROUTE'].map(x=>{ + const button=document.querySelector('[data-mix-mode="'+x+'"]'); + const css=getComputedStyle(button); + return {active:button.classList.contains('active'), + pressed:button.getAttribute('aria-pressed'), + edge:css.getPropertyValue('--b180-border').trim()}; + })""") + assert modes[0]['active'] is False and modes[0]['pressed']=='false',modes + assert modes[1]['active'] is True and modes[1]['pressed']=='true',modes + assert modes[0]['edge']!=modes[1]['edge'],modes await page.locator('[data-strip="0"] select.arBankSource').select_option("MONO:0") assert "PENDING" in await page.locator('[data-strip="0"] .arBankStage').inner_text() assert await page.locator('[data-strip="0"] .arBankSource').is_disabled() diff --git a/tests/native_artifact_packaging_contract_test.mjs b/tests/native_artifact_packaging_contract_test.mjs index 126c24cda..eacc94ebd 100644 --- a/tests/native_artifact_packaging_contract_test.mjs +++ b/tests/native_artifact_packaging_contract_test.mjs @@ -10,6 +10,8 @@ import './m3e_fat_evidence_gate.test.mjs'; const read=path=>readFileSync(path,'utf8'); const workflow=read('.github/workflows/p1-windows.yml'); const packaging=read('scripts/package_native_windows.ps1'); +const pythonProvenance=read('scripts/resolve_approved_gui_python.ps1'); +const iconVerifier=read('scripts/verify_windows_pe_brand_icon.py'); const verify=read('scripts/verify_native_windows_artifact.ps1'); const nativeMain=read('src/Main.cpp'); const cmake=read('CMakeLists.txt'); @@ -17,6 +19,33 @@ const generator=read('scripts/build_approved_native_gui.py'); const adapter=read('web/approved-native-bridge.js'); const fat=read('docs/HARDWARE_FAT_GUI10_ENGINE_P012_20261027.md'); + +test('packaging and independent ZIP verifier use the exact CMake Python, never PATH python for icon recompression',()=>{ + for(const script of [packaging,verify]){ + assert.match(script,/resolve_approved_gui_python\.ps1/); + assert.match(script,/Resolve-ArSonMixApprovedGuiPython/); + assert.match(script,/& \$approvedGuiPython scripts\/build_approved_native_gui\.py --out \$approvedGuiDir --verify/); + assert.doesNotMatch(script,/& python scripts\/build_approved_native_gui\.py/); + } + assert.match(cmake,/approved-gui-python\.txt/); + assert.match(pythonProvenance,/approved-gui-python\.txt/); + assert.match(pythonProvenance,/Test-Path -LiteralPath \$selected -PathType Leaf/); + assert.match(pythonProvenance,/refusing unverified GUI regeneration/); +}); + +test('EXE and independently ZIP-distributed PE icons must match approved source RGBA',()=>{ + for(const script of [packaging,verify]){ + assert.match(script,/& \$approvedGuiPython scripts\/verify_windows_pe_brand_icon\.py --exe/); + assert.match(script,/--approved assets\/icon\/arsonmix-256\.png/); + assert.match(script,/LASTEXITCODE -ne 0/); + } + assert.match(iconVerifier,/RT_GROUP_ICON\/RT_ICON/); + assert.match(iconVerifier,/read_png\(expected\)/); + assert.match(iconVerifier,/actual_rows\s*=\s*read_png/); + assert.match(iconVerifier,/old\[pos\+3\]!=actual\[pos\+3\]/); + assert.match(iconVerifier,/required=\{16,32,48,256\}/); +}); + test('native FAT picks exact JUCE GUI target, not a test executable',()=>{ assert.match(cmake,/juce_add_gui_app\(ARMixConsole/); assert.match(cmake,/PRODUCT_NAME "AR MIX Studio"/); diff --git a/tests/native_channel_appearance_store_test.cpp b/tests/native_channel_appearance_store_test.cpp new file mode 100644 index 000000000..4011f2e5e --- /dev/null +++ b/tests/native_channel_appearance_store_test.cpp @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#ifdef NDEBUG + #undef NDEBUG +#endif +#include +#include +#include +#include +#include "../src/NativeChannelAppearanceStore.h" + +using armix::appearance::Store; +static juce::var object(){return juce::var(new juce::DynamicObject());} +static void set(juce::var& value,const char* k,const juce::var& v){ + value.getDynamicObject()->setProperty(k,v); +} +static juce::var nativeGraph(){ + auto root=object(),device=object(),graph=object(),caps=object(),session=object(); + set(device,"epoch","7"); + set(graph,"revision","9");set(graph,"rosterRevision","11"); + set(caps,"callbackOwnsChannelIds",true);set(graph,"capabilities",caps); + juce::Array channels; + for(const auto& [id,name]:std::vector>{ + {"9007199254740993","Vocal"},{"9007199254740995","Guitar"}, + {"18446744073709551615","MAIN"}}){ + auto row=object();set(row,"id",id);set(row,"name",name);channels.add(row); + } + set(graph,"channels",juce::var(channels));set(root,"graph",graph); + set(root,"device",device);set(session,"authority","CHANNEL_ID"); + set(root,"mixerSession",session); + return root; +} +static juce::var edit(const juce::String& id,const juce::String& name, + const juce::String& color="#c32974", + const juce::String& icon=juce::String::fromUTF8("\xF0\x9F\x8E\xB9")){ + auto v=object(); + set(v,"channelId",id);set(v,"name",name); + set(v,"color",color);set(v,"icon",icon); + set(v,"deviceEpoch","7");set(v,"graphRevision","9"); + set(v,"rosterRevision","11");set(v,"appearanceRevision","0"); + return v; +} +int main(){ + const auto dir=juce::File::getSpecialLocation(juce::File::tempDirectory) + .getNonexistentChildFile("ArSonMixChannelIdentity","",false); + assert(dir.createDirectory().wasOk()); + const auto g=nativeGraph(); + // Match the production transport: apply takes the accepted envelope, + // while snapshot projects appearances against its nested channel graph. + const auto graph=g.getProperty("graph",{}); + // Raw UTF-8 bytes are a compiler-charset-independent ground truth. + const auto keyboard=juce::String::fromUTF8("\xF0\x9F\x8E\xB9"); + assert(Store::validIcon(keyboard)); + assert(edit("9007199254740993","Studio Vox").getProperty("icon",{}).toString()==keyboard); + const juce::String vocalId="9007199254740993"; + const juce::String guitarId="9007199254740995"; + { + Store store(dir); + assert(store.error().isEmpty()); + auto req=edit(vocalId,"Studio Vox"); + // Fail closed on non-graph identity or stale lease. + set(req,"channelId","9007199254740994"); + const auto missing=store.apply(req,g); + if(missing!="CHANNEL_NOT_IN_NATIVE_ROSTER") { + std::cerr<<"Non-roster guard returned: "<"); + assert(store.apply(req,g)=="INVALID_CHANNEL_NAME_COLOR_OR_ICON"); + set(req,"icon",keyboard); + assert(store.apply(req,g).isEmpty()); + auto snap=store.snapshot(graph); + assert(snap.getProperty("revision","").toString()=="1"); + const auto stored=snap.getProperty("entries",{}); + const auto* rows=stored.getArray(); + assert(rows && rows->size()==1); + assert((*rows)[0].getProperty("id","").toString()==vocalId); + assert((*rows)[0].getProperty("color","").toString()=="#c32974"); + auto stale=edit(guitarId,"Studio Guitar"); + assert(store.apply(stale,g)=="STALE_CHANNEL_APPEARANCE_REVISION"); + set(stale,"appearanceRevision","1"); + set(stale,"name","Studio Vox"); + assert(store.apply(stale,g)=="CHANNEL_NAME_ALREADY_IN_USE"); + set(stale,"name","Guitar New"); + assert(store.apply(stale,g).isEmpty()); + assert(store.snapshot(graph).getProperty("revision","").toString()=="2"); + } + { + Store reboot(dir); // No WebView/localStorage or device required. + assert(reboot.error().isEmpty()); + const auto snap=reboot.snapshot(graph); + const auto entries=snap.getProperty("entries",{}); + assert(entries.isArray() && entries.getArray()->size()==2); + auto req=edit(vocalId,"Studio Vox"); + set(req,"appearanceRevision","2"); + assert(reboot.apply(req,g).isEmpty()); // idempotent, no extra disk write + assert(reboot.snapshot(graph).getProperty("revision","").toString()=="2"); + set(req,"name","Studio Vox 2"); + set(req,"deviceEpoch","8"); + assert(reboot.apply(req,g)=="STALE_CHANNEL_IDENTITY_OR_GRAPH"); + } + // A corrupted existing document is read-only, not silently erased. + auto path=dir.getChildFile("channel-appearance.v1.json"); + assert(path.replaceWithText("{corrupt")); + Store damaged(dir); + assert(damaged.error().isNotEmpty()); + auto req=edit(vocalId,"Try overwrite"); + assert(damaged.apply(req,g)==damaged.error()); + assert(path.loadFileAsString()=="{corrupt"); + assert(dir.deleteRecursively()); + std::cout << "PASS native appearance disk + exact uint64 IDs + atomic revision + readback\n"; +} diff --git a/tests/native_dry_route_command_test.cpp b/tests/native_dry_route_command_test.cpp index 4b8d3239f..3b2e5e951 100644 --- a/tests/native_dry_route_command_test.cpp +++ b/tests/native_dry_route_command_test.cpp @@ -1,6 +1,10 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/core/NativeDryRouteCommand.h" #include "../engine/core/PreparedMixerBlock.h" +#include "../src/NativeVerifiedSourcePatch.h" +#include "../src/NativeTopologyEditSafety.h" +#include "../src/NativeSessionToken.h" +#include #if defined(NDEBUG) #undef NDEBUG #endif @@ -10,6 +14,51 @@ using namespace armix::mixer; static bool near(float a,float b){return std::abs(a-b)<0.00001f;} int main(){ + // P0 First Sound: live same-format pin moves must remain atomic even + // during MAIN/STREAM, but a structural change cannot publish while + // STREAM is consuming the old graph. Physical re-arm is never implicit + // after a device epoch change or unsafe / unpatched output. + using Guard=NativeTopologyEditSafety; + // JUCE WebView JSON can carry whole numbers as Double. Native routing + // commands must accept the SAME epoch/revision but reject stale/fractional + // and JS-inexact tokens, regardless of action (FX/OUT/M4). + using armix::console::nativeSessionTokenMatches; + using armix::console::nativeSessionTokenValid; + const juce::var epoch=juce::int64(91); + assert(nativeSessionTokenMatches(juce::var(91),epoch)); + assert(nativeSessionTokenMatches(juce::var(91.0),epoch)); + assert(nativeSessionTokenMatches(juce::var(juce::int64(91)),epoch)); + assert(!nativeSessionTokenMatches(juce::var(92.0),epoch)); + assert(!nativeSessionTokenMatches(juce::var(91.5),epoch)); + assert(!nativeSessionTokenMatches(juce::var("91"),epoch)); + assert(!nativeSessionTokenValid(juce::var(0.0))); + assert(!nativeSessionTokenValid(juce::var(-1.0))); + assert(!nativeSessionTokenValid(juce::var(9007199254740992.0))); + assert(!nativeSessionTokenValid( + juce::var(std::numeric_limits::quiet_NaN()))); + assert(!nativeSessionTokenValid( + juce::var(std::numeric_limits::infinity()))); + static_assert(!Guard::structuralSource(true,true)); + static_assert( Guard::structuralSource(true,false)); + static_assert( Guard::structuralSource(false,true)); + assert(Guard::mayEdit(false,true)); + assert(Guard::mayEdit(true,false)); + assert(!Guard::mayEdit(true,true)); + assert(Guard::mayRestoreMonitor(true,true,true,false)); + assert(!Guard::mayRestoreMonitor(true,false,true,false)); + assert(!Guard::mayRestoreMonitor(true,true,false,false)); + assert(!Guard::mayRestoreMonitor(true,true,true,true)); + assert(!Guard::mayRestoreMonitor(false,true,true,false)); + constexpr Guard::MixSnapshot oldM4{0.25f,-0.25f,false,false}; + constexpr Guard::MixSnapshot acceptedNative{0.75f,0.5f,true,true}; + constexpr auto migrated=Guard::preserveAcceptedMix( + oldM4,acceptedNative,true); + static_assert(migrated.linear==0.75f && migrated.pan==0.5f && + migrated.mute && migrated.solo); + constexpr auto legacyOnly=Guard::preserveAcceptedMix( + oldM4,acceptedNative,false); + static_assert(legacyOnly.linear==0.25f && legacyOnly.pan==-0.25f && + !legacyOnly.mute && !legacyOnly.solo); juce::String json=R"({"channels":[)"; for(int i=0;isetProperty("deviceEpoch",juce::int64(91)); + typed.getDynamicObject()->setProperty("revision",juce::int64(7)); + juce::var sourceCleared, rejectedClear; + const auto activePins=std::span(ports.data(),ports.size()); + assert(NativeVerifiedSourcePatch::prepare( + typed,0,"NONE",-1,-1,activePins,91,7,sourceCleared).isEmpty()); + const auto cleared=sourceCleared.getProperty("channels",{}) + .getArray()->getReference(0); + assert(cleared.getProperty("mode",{}).toString()=="NONE"); + assert(cleared.getProperty("sourceKind",{}).toString()=="NONE"); + assert(cleared.getProperty("sourceFormat",{}).toString()=="NONE"); + assert(cleared.getProperty("channelFormat",{}).toString()=="STEREO"); + assert(static_cast(cleared.getProperty("left",-2))==-1); + assert(static_cast(cleared.getProperty("right",-2))==-1); + assert(typed.getProperty("channels",{}).getArray()->getReference(0) + .getProperty("sourceKind",{}).toString()=="PHYSICAL"); + NativeDryRouteCommand disconnectedPlan; + // CH1 still owns two PRE/POST sends to BUS channels. Clearing its + // hardware source while those sends remain must be rejected, not + // silently create a dangling audio path. + assert(!NativeDryRouteCommand::decode(sourceCleared,disconnectedPlan,error)); + assert(error.containsIgnoreCase("Enable a sender")); + // After the operator explicitly disconnects those sends, the very + // same accepted NONE source must compile to physical silence. + auto disconnectedNoSends=juce::JSON::parse( + juce::JSON::toString(sourceCleared,false)); + disconnectedNoSends.getDynamicObject()->setProperty("sends", + juce::var(juce::Array{})); + assert(NativeDryRouteCommand::decode(disconnectedNoSends, + disconnectedPlan,error)); + assert(disconnectedPlan.channels.stripsAndMaster.strips[0].source + ==SourceMode::disconnected); + assert(!NativeVerifiedSourcePatch::prepare( + typed,0,"NONE",2,-1,activePins,91,7,rejectedClear).isEmpty()); + assert(!NativeVerifiedSourcePatch::prepare( + typed,0,"NONE",-1,-1,activePins,90,7,rejectedClear).isEmpty()); + assert(v2.channels.stripsAndMaster.strips[0].source==SourceMode::mono); assert(v2.channels.formats[0]==ChannelFormat::stereo); assert(v2.channels.stripsAndMaster.strips[1].source==SourceMode::disconnected); diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp new file mode 100644 index 000000000..724d32219 --- /dev/null +++ b/tests/native_mixer_session_store_test.cpp @@ -0,0 +1,414 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#ifdef NDEBUG + #undef NDEBUG +#endif +#include +#include +#include "../src/NativeMixerSessionStore.h" +#include "../src/LiveDryRoutingLab.h" +#include "../src/NativeMixerSessionFxRestore.h" + +using namespace armix::mixer; +using namespace armix::session; +using armix::shows::BinaryState; + +static MixerSessionDocument makeSession() { + MixerSessionDocument d; + d.id="11111111-2222-4333-8444-555555555555"; + d.savedMs=1762520000000LL; + d.binding={"ASIO","Verified ASIO","Verified ASIO","3","3",48000.,256}; + d.outputs={2,0,1,-1,-1,false}; + d.request.physicalInputs=2;d.request.maxFrames=256; + d.request.maxScratchBytes=32u*1024u*1024u; + d.masterGain=.7f;d.masterMute=true;d.masterMono=false; + std::vector rows; + for(int i=1;i<=10;++i) { + ChannelStripDefinition row; + row.id={static_cast(i)}; + row.role=ChannelRole::input; + row.name="CH "+std::to_string(i); + row.format=i==1?ProcessingFormat::mono:ProcessingFormat::stereo; + if(i==1){ + row.sends.push_back({{16},1.f,false,0.f,true,100}); + row.sends.push_back({{11},.3f,true,-.25f,false,101}); + } else if(i==2)row.sends.push_back({{15},1.f,false,0.f,true,102}); + rows.push_back(std::move(row)); + d.legacyIds.inputs[i-1]={static_cast(i)}; + } + for(int i=0;i<4;++i) { + ChannelStripDefinition aux; + aux.id={static_cast(11+i)}; + aux.role=ChannelRole::fxReturn; + aux.format=ProcessingFormat::stereo; + aux.name="AUX "+std::to_string(i+1); + aux.sends.push_back({{15},1.f,false,0.f,true, + static_cast(200+i)}); + d.legacyIds.aux[i]=aux.id; + rows.push_back(std::move(aux)); + } + ChannelStripDefinition group; + group.id={16};group.role=ChannelRole::group; + group.name="Vocal Group";group.format=ProcessingFormat::stereo; + group.sends.push_back({{15},1.f,false,0.f,true,105}); + rows.push_back(std::move(group)); + ChannelStripDefinition main; + main.id={15};main.role=ChannelRole::main; + main.name="MAIN";main.format=ProcessingFormat::stereo; + rows.push_back(std::move(main)); + d.legacyIds.main={15}; + d.acceptedRevision=52; + assert(d.roster.restoreExact(d.acceptedRevision,rows)); + d.request.sources.push_back({{1},0,-1,false}); + d.rackBypassed.push_back({1}); + return d; +} +class FixtureDevice final : public juce::AudioIODevice { +public: + FixtureDevice():AudioIODevice("Verified WASAPI fixture","Windows Audio") { + inputMask.setRange(0,2,true); + outputMask.setRange(0,2,true); + } + juce::StringArray getOutputChannelNames() override {return {"Main L","Main R"};} + juce::StringArray getInputChannelNames() override {return {"Capture L","Capture R"};} + juce::Array getAvailableSampleRates() override {return {48000.,44100.};} + juce::Array getAvailableBufferSizes() override {return {480,512};} + int getDefaultBufferSize() override {return 480;} + juce::String open(const juce::BigInteger&,const juce::BigInteger&,double,int) override {return {};} + void close() override {} + bool isOpen() override {return true;} + void start(juce::AudioIODeviceCallback*) override {} + void stop() override {} + bool isPlaying() override {return true;} + juce::String getLastError() override {return {};} + int getCurrentBufferSizeSamples() override {return frames;} + double getCurrentSampleRate() override {return rate;} + int getCurrentBitDepth() override {return 32;} + juce::BigInteger getActiveOutputChannels() const override {return outputMask;} + juce::BigInteger getActiveInputChannels() const override {return inputMask;} + int getOutputLatencyInSamples() override {return 0;} + int getInputLatencyInSamples() override {return 0;} + juce::BigInteger inputMask,outputMask; + int frames=480; + double rate=48000.; +}; + +static void nativeDeviceRecovery() { + FixtureDevice device; + auto saved=makeSession(); + saved.binding={"Windows Audio","VB-Cable","Realtek","3","3",48000.,480}; + saved.request.maxFrames=480; + saved.request.sources={{ChannelId{1},0,1,true}}; + saved.rackBypassed.clear(); + auto rows=saved.roster.channels(); + rows.front().format=ProcessingFormat::stereo; + rows.front().sends.push_back({{2},.15f,false,0.f,false,110}); + const auto eqId=armix::builtin_fx::ChannelEqProcessor::catalogIdentity; + rows.front().insertCatalogIds.push_back(juce::String(eqId).toStdString()); + assert(saved.roster.restoreExact(saved.acceptedRevision,rows)); + BinaryState binary; + armix::builtin_fx::ChannelEqProcessor eq; + eq.prepareToPlay(48000.,480); + eq.getStateInformation(binary.bytes); + binary.sha256=juce::SHA256(binary.bytes).toHexString(); + saved.inserts.push_back({{1},0,eqId,{},binary.sha256,"EQ",0,false}); + // Validate the same durable document used at app startup. + MixerSessionDocument verified; + assert(Codec::decode(Codec::encode(saved),verified)); + std::vector blobs{binary}; + juce::AudioPluginFormatManager formats; + { + LiveDryRoutingLab fresh; + fresh.prepareDevice(&device); + assert(fresh.startUnpatchedSession(true,false,0,formats,48000.,480).isEmpty()); + assert(fresh.ready() && !fresh.hasExplicitRoute()); + } + + LiveDryRoutingLab mixer; + mixer.prepareDevice(&device); + const auto restore=[&](const MixerSessionDocument& doc, + const std::vector& states,bool disarmed, + bool replaceActive=false) { + armix::device::JuceActivePortSnapshot pins; + armix::device::JuceActivePortSnapshot::Fault fault; + assert(armix::device::JuceActivePortSnapshot::capture(&device,mixer.epoch(),pins,fault)); + std::shared_ptr bank; + const auto preparation=NativeMixerSessionFxRestore::prepare(doc,states,formats, + device.rate,doc.request.maxFrames,pins.epoch,mixer.nativeGraphRevisionForRestore(),bank); + if(preparation.isNotEmpty())return preparation; + return mixer.restoreNativeMixerSession(doc,std::move(bank),pins,disarmed,replaceActive); + }; + assert(!mixer.ready() && mixer.revision()==0); // no compatibility PCM publisher + assert(restore(verified,{},true).isNotEmpty()); + assert(restore(verified,blobs,false).isNotEmpty()); + assert(!mixer.channelIdPhysicalPcmActive()); + assert(restore(verified,blobs,true).isEmpty()); + const auto firstEpoch=mixer.epoch(); + assert(mixer.ready() && mixer.controlRevision()>0 && mixer.revision()==0); + assert(mixer.status(&device).getProperty("mainOutputs",{}).getArray()->size()==2); + + std::array inL,inR,outL,outR; + inL.fill(.2f);inR.fill(.1f); + const float* in[]={inL.data(),inR.data()}; + float* out[]={outL.data(),outR.data()}; + const auto process=[&](bool muted) { + outL.fill(1.f);outR.fill(1.f); + assert(mixer.process(in,device.inputMask.countNumberOfSetBits(),out,2,480,1.f,muted, + nullptr,nullptr,false,nullptr,nullptr,true)); + }; + process(true); + assert(outL.back()==0.f && outR.back()==0.f && mixer.peakLeft()==0.f); + auto graph=mixer.nativeBusStatus(); + const auto channels=graph.getProperty("channels",{}); + assert(static_cast(channels.getArray()->getReference(0).getProperty("peakL",0.))>0.); + process(false); + assert(outL.back()>.05f && outR.back()>.025f); + + // Portable Open may replace a live session only on an explicit muted + // publication. Invalid FX must leave the accepted graph and PCM intact. + const auto liveRevision=mixer.controlRevision(); + assert(restore(verified,blobs,true).isNotEmpty()); + assert(restore(verified,{},true,true).isNotEmpty()); + assert(mixer.controlRevision()==liveRevision); + process(false); + assert(outL.back()>.05f && outR.back()>.025f); + assert(restore(verified,blobs,true,true).isEmpty()); + assert(mixer.controlRevision()>liveRevision); + process(false); + assert(outL.back()>.05f && outR.back()>.025f); + + // Reopen repeatedly. The field failure had retained channels, FX and + // WIRE, but no live legacy lease for the new 48 kHz/480 frame epoch. + for(int attempt=0;attempt<3;++attempt) { + const auto prior=mixer.epoch(); + mixer.deviceStopped(); + mixer.prepareDevice(&device); + assert(!mixer.ready() && mixer.revision()==0); + assert(mixer.status(&device).getProperty("retainedNativeBus",{}).isObject()); + process(true); + assert(outL.back()==0.f && outR.back()==0.f); + assert(mixer.rebindVerifiedDevice(prior,mixer.epoch(),480,false)); + assert(mixer.channelIdPhysicalPcmActive()); + assert(!mixer.setNativeInputMuteSolo(firstEpoch,mixer.controlRevision(),{1},true,false)); + process(true); + assert(outL.back()==0.f && outR.back()==0.f); + process(false); + assert(outL.back()>.05f && outR.back()>.025f); + } + const auto ep=mixer.epoch(); + auto rev=mixer.controlRevision(); + assert(mixer.setNativeInputMuteSolo(ep,rev,{1},true,false)); + process(false); + assert(outL.back()==0.f && outR.back()==0.f); + assert(mixer.setNativeInputMuteSolo(ep,rev,{1},false,false)); + assert(mixer.setNativeInputMix(ep,rev,{1},.5f,0.f)); + process(false); + assert(outL.back()>.02f && outL.back()<.19f); + MixerSessionDocument current; + std::vector currentStates; + assert(mixer.captureNativeMixerSession(current,currentStates).isEmpty()); + assert(current.roster.find({1})->sends[1].edgeId==101); + assert(current.roster.find({1})->faderLinear==.5f); + assert(current.inserts.size()==1 && current.inserts[0].catalogId==eqId); + current.binding=saved.binding; + + mixer.deviceStopped(); + device.inputMask.clearBit(1); + device.rate=44100.; + device.frames=512; + mixer.prepareDevice(&device); + auto nextBinding=current.binding; + nextBinding.inputMask="1";nextBinding.rate=device.rate;nextBinding.frames=device.frames; + const auto pair=MixerDeviceBindingPolicy::proposedOutputs(current,nextBinding,2); + assert(MixerDeviceBindingPolicy::apply(current,nextBinding,pair,1,false).isNotEmpty()); + assert(MixerDeviceBindingPolicy::apply(current,nextBinding,pair,1,true).isEmpty()); + assert(current.request.sources.empty()); // lost stereo half is never borrowed + assert(current.roster.find({1})->sends[1].edgeId==101); + current.request.maxFrames=512; + assert(restore(current,currentStates,true).isEmpty()); + process(false); + assert(outL.back()==0.f && outR.back()==0.f); + auto patch=mixer.patchNativeInputSource(mixer.epoch(),mixer.controlRevision(), + current.roster.revision(),{1},0,-1,false,true); + assert(patch.accepted); + process(false); + assert(outL.back()>.02f && outR.back()>.02f); + const std::array sourceOnly{{ + {WireChange::Kind::remove,{1},{16},100}, + {WireChange::Kind::remove,{1},{11},101}, + {WireChange::Kind::remove,{1},{2},110} + }}; + auto wire=mixer.applyNativeWireTransaction(mixer.epoch(),patch.pcmRevision, + patch.rosterRevision,sourceOnly); + assert(wire.accepted); + process(false); + assert(outL.back()==0.f && outR.back()==0.f); + graph=mixer.nativeBusStatus(); + assert(static_cast(graph.getProperty("channels",{}).getArray()-> + getReference(0).getProperty("peakL",0.))>0.); + const std::array reconnect{{ + {WireChange::Kind::routeOnly,{1},{16},0,1.f} + }}; + wire=mixer.applyNativeWireTransaction(mixer.epoch(),wire.pcmRevision, + wire.rosterRevision,reconnect); + assert(wire.accepted); + process(false); + assert(outL.back()>.02f && outR.back()>.02f); + std::cout<<"Native callback cold restore, muted meters, repeated reopen, FX, sparse remap and PCM: PASS\n"; +} + +int main(){ + nativeDeviceRecovery(); + auto d=makeSession(); + const auto before=Codec::encode(d); + MixerSessionDocument restored; + assert(Codec::decode(before,restored)); + assert(restored.roster.size()==16); + assert(restored.roster.revision()==52); + assert(Codec::encode(restored)==before); + const auto* vocal=restored.roster.find({1}); + assert(vocal&&vocal->sends.size()==2); + assert(vocal->sends[0].edgeId==100&&vocal->sends[0].destination.value==16); + assert(vocal->sends[1].preFader&&vocal->sends[1].gain==.3f); + assert(restored.request.sources.size()==1); + assert(restored.request.sources[0].inputL==0); + assert(restored.binding.backend=="ASIO"); + assert(restored.outputs.mainR==1); + // Refuse unconfirmed or incompatible device remaps without mutating + // the saved ChannelId/EdgeId graph; accept only a verified live pair. + auto remap=d; + HardwareBinding replacement={"WASAPI","New capture","New playback", + "5","c",44100.,512}; + VerifiedNativeOutputs verifiedPair={2,1,0,-1,-1,false}; + const auto graphBefore=Codec::encode(remap); + auto refusal=MixerDeviceBindingPolicy::apply(remap,replacement, + verifiedPair,2,false); + assert(refusal.startsWith("NEEDS_REMAP")); + assert(Codec::encode(remap)==graphBefore); + refusal=MixerDeviceBindingPolicy::apply(remap,replacement, + verifiedPair,1,true); + assert(refusal.startsWith("NEEDS_REMAP")); + assert(Codec::encode(remap)==graphBefore); + assert(MixerDeviceBindingPolicy::apply(remap,replacement, + verifiedPair,2,true).isEmpty()); + assert(remap.binding.backend=="WASAPI" && remap.outputs.mainL==1); + assert(remap.roster.revision()==d.roster.revision()); + assert(remap.roster.find({1})->sends.size()==2 && + remap.roster.find({1})->sends[0].edgeId==100); + auto exact=d; + assert(MixerDeviceBindingPolicy::apply(exact,d.binding,d.outputs,2,false) + .isEmpty()); + assert(Codec::encode(exact)==graphBefore); + ChannelEdit newChannel; + newChannel.kind=ChannelEdit::Kind::add; + newChannel.position=15;newChannel.role=ChannelRole::input; + newChannel.format=ProcessingFormat::stereo; + newChannel.text="Added after restart"; + const std::array edits{newChannel}; + auto result=restored.roster.edit(restored.roster.revision(),edits); + assert(result.ok()&&result.createdIds.size()==1&&result.createdIds[0].value==17); + // Bad IDs, duplicate EdgeIDs or missing physical binding cannot be + // imported into an accepted PCM graph. + std::vector duplicate=d.roster.channels(); + duplicate[1].id=duplicate[0].id; + DynamicChannelRoster invalid; + assert(!invalid.restoreExact(1,duplicate)); + duplicate=d.roster.channels(); + duplicate[1].sends[0].edgeId=duplicate[0].sends[0].edgeId; + assert(!invalid.restoreExact(1,duplicate)); + auto bad=juce::JSON::parse(before); + bad.getDynamicObject()->setProperty("schema","untrusted.version"); + assert(!Codec::decode(juce::JSON::toString(bad,false),restored)); + bad=juce::JSON::parse(before); + auto binds=bad.getProperty("binding",{}); + binds.getDynamicObject()->setProperty("rate",0.0); + assert(!Codec::decode(juce::JSON::toString(bad,false),restored)); + + // Immutable generation chain with a REAL vendor state hash. + const auto base=juce::File::getSpecialLocation(juce::File::tempDirectory) + .getNonexistentChildFile("ArSonMixDynamicSession","",false); + const auto studio=base.getChildFile("Studio"); + assert(studio.createDirectory().wasOk()); + NativeMixerSessionStore store(studio); + BinaryState binary; + const char bytes[]={'V','S','T','3','-','S','T','A','T','E',0,1,2}; + binary.bytes.append(bytes,sizeof(bytes)); + binary.sha256=juce::SHA256(binary.bytes).toHexString(); + d.inserts.push_back({{1},0,"TestVendor|9|0","C:/FX/Test.vst3", + binary.sha256,"EQ",9,false}); + { + auto installed=d.roster.channels(); + installed[0].insertCatalogIds.push_back("TestVendor|9|0"); + assert(d.roster.restoreExact(d.acceptedRevision,installed)); + } + // Semantic corruption must be rejected, even if the surrounding JSON + // is otherwise well-formed or would have a valid SHA-256 on disk. + const auto validWithFx=Codec::encode(d); + MixerSessionDocument rejected; + auto damaged=juce::JSON::parse(validWithFx); + auto channels=damaged.getProperty("channels",{}); + auto* entries=channels.getArray(); + assert(entries && !entries->isEmpty()); + auto catalog=entries->getReference(0).getProperty("catalogs",{}); + catalog.getArray()->clear(); + assert(!Codec::decode(juce::JSON::toString(damaged,false),rejected)); + // A ghost slot may not point past the one accepted catalog entry. + damaged=juce::JSON::parse(validWithFx); + auto inserts=damaged.getProperty("inserts",{}); + inserts.getArray()->getReference(0).getDynamicObject()->setProperty("slot",1); + assert(!Codec::decode(juce::JSON::toString(damaged,false),rejected)); + // Wrong plugin on the same slot is not a valid ChannelId FX recovery. + damaged=juce::JSON::parse(validWithFx); + inserts=damaged.getProperty("inserts",{}); + inserts.getArray()->getReference(0).getDynamicObject() + ->setProperty("catalogId","OtherVendor|99|0"); + assert(!Codec::decode(juce::JSON::toString(damaged,false),rejected)); + assert(store.commit(d,{binary}).isEmpty()); + MixerSessionDocument loaded; + std::vector readback; + assert(store.load(loaded,readback).isEmpty()); + assert(readback.size()==1&&readback[0].bytes==binary.bytes); + // Legacy JSON lacks a preference. Both explicit settings survive checkpoint + // round trips, and portable files cannot request MAIN authorization. + assert(!loaded.resumeMain.has_value()); + d.resumeMain=true; + MixerSessionDocument roundTrip; + assert(Codec::decode(Codec::encode(d),roundTrip)&&roundTrip.resumeMain==true); + d.resumeMain=false; + assert(Codec::decode(Codec::encode(d),roundTrip)&&roundTrip.resumeMain==false); + const auto portable=studio.getChildFile("Live.smix"); + assert(NativeMixerSessionStore::writeFile(portable,d,{binary}).isEmpty()); + assert(NativeMixerSessionStore::readFile(portable,roundTrip,readback).isEmpty()); + assert(!roundTrip.resumeMain.has_value()); + assert(roundTrip.request.sources.size()==d.request.sources.size()); + assert(readback.size()==1&&readback[0].bytes==binary.bytes); + auto tampered=juce::JSON::parse(portable.loadFileAsString()); + tampered.getProperty("pluginState",{}).getDynamicObject()->setProperty(binary.sha256,"AAAA"); + assert(portable.replaceWithText(juce::JSON::toString(tampered))); + assert(NativeMixerSessionStore::readFile(portable,roundTrip,readback).isNotEmpty()); + assert(readback.size()==1&&readback[0].bytes==binary.bytes); + const auto firstId=studio.getChildFile("MixerSession").getChildFile("HEAD") + .loadFileAsString().trim(); + assert(armix::shows::detail::uuid(firstId)); + d.masterGain=.35f;d.savedMs+=1000; + assert(store.commit(d,{binary}).isEmpty()); + assert(store.load(loaded,readback).isEmpty()); + assert(loaded.masterGain==.35f); + assert(store.recoverPrevious().isNotEmpty()); // NEVER roll back valid HEAD + const auto head=studio.getChildFile("MixerSession").getChildFile("HEAD"); + const auto secondId=head.loadFileAsString().trim(); + const auto vendor=studio.getChildFile("MixerSession").getChildFile("versions") + .getChildFile(secondId).getChildFile("blobs") + .getChildFile(binary.sha256+".bin"); + assert(vendor.appendText("CORRUPTED")); + assert(store.load(loaded,readback).isNotEmpty()); + assert(loaded.masterGain==.35f); // rejection did not replace output + assert(store.recoverPrevious().isEmpty()); + assert(store.load(loaded,readback).isEmpty()); + assert(loaded.masterGain==.7f); + assert(readback[0].bytes==binary.bytes); + assert(!store.recoverPrevious().isEmpty()); + assert(base.deleteRecursively()); + std::cout<<"PASS: dynamic ChannelId/EdgeId graph, persistent vendor blobs and" + " explicit verified HEAD recovery\n"; + return 0; +} diff --git a/tests/native_peq_assembly_test.py b/tests/native_peq_assembly_test.py new file mode 100644 index 000000000..f3d3dd576 --- /dev/null +++ b/tests/native_peq_assembly_test.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""Native PEQ vertical-integration invariants in the one approved Pages GUI.""" +from pathlib import Path +import sys +import unittest + +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/"scripts")) +from compose_native_peq import apply_native_peq +from approved_fx_rack_power import apply_authoritative_fx_power + +class NativeParametricEqIntegration(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.original=(ROOT/"site/preview-v2/index.html").read_text("utf-8") + cls.assembled=apply_native_peq(apply_authoritative_fx_power(cls.original)) + + def test_one_authoritative_mixer(self): + self.assertEqual(self.assembled.count("function sectionFx(t){"),1) + self.assertEqual(self.assembled.count("function renderFastPicker(){"),1) + self.assertEqual(self.assembled.count("function insertChosenNativeEq(){"),1) + self.assertEqual(self.assembled.count('id="fastPicker"'),1) + self.assertNotIn("preview-v3",self.assembled) + self.assertEqual(self.assembled.count('src="assets/mixer-native-peq.js?v=eq-graph1"'),1) + + def test_native_rack_uses_regular_insert_slot(self): + self.assertIn("host.insert(activeFxTarget)",self.assembled) + self.assertNotIn("__ARMIX_NATIVE_M2__",self.assembled) + self.assertIn("if(t.fx[index]==='Parametric EQ')",self.assembled) + # Does not fabricate a second EQ rack row or a special before-VST bank. + self.assertNotIn("builtinEq.slotMarkup",self.assembled) + self.assertNotIn("PRE VST3",self.assembled) + self.assertEqual(self.assembled.count('data-fast-native-eq="1"'),1) + + def test_single_style_owner(self): + # The approved CSS compiler requires exactly 18 component-owner links. + # Native EQ styles live within the existing FX rack owner, not a 19th link. + self.assertNotIn('href="assets/mixer-native-peq.css',self.assembled) + css=(ROOT/"site/preview-v2/assets/mixer-fx-rack.css").read_text("utf-8") + self.assertIn(".mx-peq[hidden]{display:none}",css) + self.assertIn("grid-template-columns:minmax(0,1fr) 143px",css) + script=(ROOT/"site/preview-v2/assets/mixer-native-peq.js").read_text("utf-8") + self.assertIn('const LOG=Math.log(1000)',script) + self.assertIn('document.createElementNS(NS,"svg")',script) + self.assertIn('arMixBuiltinEqAck',script) + self.assertNotIn("new AudioContext",script) + + def test_fail_closed_on_repeat(self): + with self.assertRaises(ValueError): + apply_native_peq(self.assembled) + with self.assertRaises(ValueError): + apply_native_peq(self.original.replace("function renderFastPicker(){", + "function renderFastPickerRenamed(){")) + +if __name__=="__main__": + unittest.main() diff --git a/tests/native_show_store_test.cpp b/tests/native_show_store_test.cpp index a591ad592..007837504 100644 --- a/tests/native_show_store_test.cpp +++ b/tests/native_show_store_test.cpp @@ -106,19 +106,50 @@ int main() { assert(store.load(show.id,loaded,retrieved).isEmpty()); assert(retrieved[0].name=="Performance Ready"); + // A valid current performance cannot be overwritten with older recovery. + assert(store.recoverPrevious(show.id).isNotEmpty()); + assert(store.currentGeneration(show.id)==second); + ShowV2 previousShow;std::vector previousItems; + juce::String previousGeneration; + assert(store.loadPrevious(show.id,previousShow,previousItems,&previousGeneration).isEmpty()); + assert(previousGeneration==first.getFileName()); + assert(previousItems.size()==1 && previousItems[0].name=="Soundcheck"); + // Missing/corrupt payload never partially replaces the accepted outputs. const auto vendor=second.getChildFile("blobs").getChildFile(blob.sha256+".bin"); assert(vendor.appendText("damaged")); assert(store.load(show.id,loaded,retrieved).isNotEmpty()); assert(retrieved.size()==1&&retrieved[0].name=="Performance Ready"); - // Bad HEAD rejected before using unsafe path; backup remains intact. + // Read-only recovery inspection never mutates HEAD even after blob corruption. + assert(store.loadPrevious(show.id,previousShow,previousItems).isEmpty()); + assert(store.currentGeneration(show.id)==second); + + // Explicit recovery validates prior JSON and BOTH vendor state hashes. + // A corrupt latest blob is not silently accepted by normal load. + const auto priorPointer=workspace.getChildFile("Shows").getChildFile(show.id) + .getChildFile("PREVIOUS"); + assert(priorPointer.existsAsFile()); + assert(priorPointer.loadFileAsString().trim()==first.getFileName()); + assert(store.recoverPrevious(show.id).isEmpty()); + assert(store.currentGeneration(show.id)==first); + restoredStates.clear(); + assert(store.loadWithStates(show.id,fxShow,fxSnaps,restoredStates).isEmpty()); + assert(restoredStates.size()==2 && fxSnaps[0].name=="Soundcheck"); + + // Bad HEAD rejected before using unsafe path; recovery must remain possible. auto head=workspace.getChildFile("Shows").getChildFile(show.id).getChildFile("HEAD"); assert(head.replaceWithText("../unsafe")); assert(store.load(show.id,loaded,retrieved).isNotEmpty()); assert(store.currentGeneration(show.id)==juce::File{}); assert(first.isDirectory()); + assert(store.recoverPrevious(show.id).isEmpty()); + assert(store.currentGeneration(show.id)==first); + // Corrupt PREVIOUS must never clobber the last accepted HEAD. + assert(priorPointer.replaceWithText("../../outside")); + assert(store.recoverPrevious(show.id).isNotEmpty()); + assert(store.currentGeneration(show.id)==first); base.deleteRecursively(); - std::cout<<"PASS: immutable Shows generation, staged VST3 hash, atomic HEAD, no partial recovery\n"; + std::cout<<"PASS: immutable Shows, staged VST3 hashes, explicit last-known-good recovery\n"; return 0; } diff --git a/tests/p0_diagnostic_contract_test.mjs b/tests/p0_diagnostic_contract_test.mjs index 53aa9db6c..9813362a5 100644 --- a/tests/p0_diagnostic_contract_test.mjs +++ b/tests/p0_diagnostic_contract_test.mjs @@ -56,7 +56,13 @@ test('P0 crackle marker records a bounded pre-event source-labeled evidence wind assert.match(host,/timerTicks_ % 12 == 0 && !browser_\.loaded/); assert.match(host,/crackleEvidence_\.push \(makeEvidenceSample \(health\)\)/); assert.doesNotMatch(host,/approvedNativeSnapshot \(health\)/); - assert.match(host,/crackleEvidence_\.mark \(makeEvidenceSample\(status\)\)/); + assert.match(host,/crackleEvidence_\.mark\s*\(\s*makeEvidenceSample\(status\)\s*\)/); + assert.match(host,/AUDIO_GLITCH_MEMORY/); + assert.match(host,/compactMemoryWindowReport/); + assert.match(host,/GlobalMemoryStatusEx/); + assert.match(host,/GetProcessMemoryInfo/); + assert.match(evidence,/struct MemoryPressure/); + assert.match(evidence,/peakLoadPercent/); assert.match(host,/if \(timerTicks_ % 12 == 0\)/); assert.match(build,/P0PreMarkerFiveSecondEvidenceWindow/); assert.doesNotMatch(engine,/CrackleEvidenceWindow/); diff --git a/tests/pages_contextual_buttons_smoke.py b/tests/pages_contextual_buttons_smoke.py index a0e145f14..0f25a9e7d 100644 --- a/tests/pages_contextual_buttons_smoke.py +++ b/tests/pages_contextual_buttons_smoke.py @@ -6,6 +6,7 @@ from pathlib import Path import subprocess,sys,tempfile from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT=Path(__file__).resolve().parents[1] OWNER='mixer-contextual-buttons.css' @@ -96,7 +97,7 @@ def check_page(browser,path,label): assert page.locator('#tracks .strip[data-id="1"] .wire-node-out').count()==1 assert page.locator('#tracks .strip[data-id="1"] .wire-node-in').count()==1 assert not errors,(label,'page errors',errors) - if label=='published-approved': + if label=='png': page.screenshot(path='pages-v6-contextual-buttons-1440.png') page.close() @@ -113,27 +114,23 @@ def main(): subprocess.run([sys.executable,str(ROOT/'scripts/build_pages.py'), '--out',str(dist),'--sha','v6-ci','--branch','main'], cwd=ROOT,check=True,capture_output=True,text=True) - # One actual published GUI is /preview/. Legacy /preview-v2/ and - # /preview-buttons/ are redirect shells, NEVER secondary renderers. - assets=dist/'preview/assets' + published=published_console(dist) + assets=published.parent/'assets' assert (assets/OWNER).read_bytes()==(ROOT/'site/preview-v2/assets'/OWNER).read_bytes() assert (assets/SCRIPT).read_bytes()==(ROOT/'site/preview-v2/assets'/SCRIPT).read_bytes() - for legacy in ('preview-v2','preview-buttons'): - html=(dist/legacy/'index.html').read_text('utf-8') - assert 'url=../preview/' in html,legacy - assert not (dist/legacy/'assets').exists(),(legacy,'alternative public renderer') png_src=ROOT/'site/preview-buttons/assets' + png_pub=assets for file in ('mixer-control-keys.css','mixer-control-keys.js','mute-solo-pfl-56x37.png'): - assert (assets/file).read_bytes()==(png_src/file).read_bytes(),file + assert (png_pub/file).read_bytes()==(png_src/file).read_bytes(),file with sync_playwright() as p: browser=p.chromium.launch(headless=True) for file,label in ( - (CANON,'canonical-source'), - (dist/'preview/index.html','published-approved') + (CANON,'canonical'), + (published,'png') ): check_page(browser,file,label) browser.close() - print('PASS V6 OTHER buttons: canonical source + sole /preview/ route, PNG protected, action release, native latches,') + print('PASS V6 OTHER buttons: authoring source + sole approved /preview/, PNG protected, action release, native latches,') print('micro geometry, fixed MAIN size, no pointer-focus or layout scroll') diff --git a/tests/pages_contextual_contrast_smoke.py b/tests/pages_contextual_contrast_smoke.py index d1bc627a1..1faabf800 100644 --- a/tests/pages_contextual_contrast_smoke.py +++ b/tests/pages_contextual_contrast_smoke.py @@ -10,6 +10,7 @@ from pathlib import Path import subprocess, sys, tempfile from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT=Path(__file__).resolve().parents[1] PAGE=ROOT/"site/preview-v2/index.html" @@ -116,14 +117,13 @@ def main(): with sync_playwright() as p: browser=p.chromium.launch(headless=True) for path,label in ((PAGE,"canonical"), - (dst/"preview/mixer.html","published-mixer"), - (dst/"preview-buttons/index.html","approved-png")): + (published_console(dst),"approved-png")): page=browser.new_page(viewport={"width":1680,"height":900}) verify(page,label,path) page.close() browser.close() print("PASS arrow OFF/ON icon contrast, unchanged geometry, Route to Bus dark microcopy,") - print("WIRE linked/legacy semantic contrast, and PNG reference route 3/3") + print("WIRE linked/legacy semantic contrast, authoring source + approved PNG /preview/") if __name__=="__main__": diff --git a/tests/pages_m1_meter_gain_calibration_smoke.py b/tests/pages_m1_meter_gain_calibration_smoke.py index a34c63b23..ff075e657 100644 --- a/tests/pages_m1_meter_gain_calibration_smoke.py +++ b/tests/pages_m1_meter_gain_calibration_smoke.py @@ -11,6 +11,7 @@ from pathlib import Path from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT = Path(__file__).resolve().parents[1] CANON = ROOT / "site/preview-v2/index.html" @@ -20,7 +21,14 @@ def close(a, b, tolerance=0.65): assert abs(a - b) <= tolerance, (a, b, tolerance) def geometry(page, density, label): - page.locator("#densitySelect").select_option(density) + picker=page.locator("#densitySelect") + if picker.is_visible(): + picker.select_option(density) + else: + # Approved Pages V29 is a single comfort-only product; density + # testing still covers all three variants in the historical source. + assert density=="comfort" and picker.is_hidden() + assert page.locator(".console-body").get_attribute("data-density")=="comfort" page.wait_for_selector("#tracks .strip[data-id='1'] .fader-scale") out = page.evaluate("""() => { const strip=document.querySelector('#tracks .strip[data-id="1"]'); @@ -199,17 +207,9 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), "--out",str(dist),"--sha","m1-calibrated","--branch","m1"], cwd=ROOT,check=True,capture_output=True,text=True) - published=dist/"preview/mixer.html" - assert published.read_bytes()==CANON.read_bytes(),"Published mixer source drift" - expected_ruler_keys={ - "mixer-fader-assembly.css":"css-owner-v27-fader-rollback-pre-v52-tail", - "mixer-meter-display.css":"css-owner-v27-meter-pruned", - } - for name,key in expected_ruler_keys.items(): - assert f"assets/{name}?v={key}" in published.read_text("utf-8"),( - "stale ruler cache URL",name,key) - for name in ("mixer-fader-assembly.css","mixer-meter-display.css"): - assert (dist/"preview/assets"/name).read_bytes()==(ASSETS/name).read_bytes(),name + # The shared provenance gate verifies every compiled ruler owner and + # its content-addressed runtime bundle against the exact source. + published=published_console(dist) with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) for html,label,width,height in ( @@ -217,23 +217,26 @@ def main(): (CANON,"canonical",1680,900), (CANON,"canonical",1920,1080), (published,"pages",1680,900), - (dist/"preview-buttons/index.html","png",1366,768)): + (published,"png",1366,768)): page=browser.new_page(viewport={"width":width,"height":height}) errors=[] page.on("pageerror",lambda exc:errors.append(str(exc))) page.goto(html.as_uri()) - for density in ("comfort","standard","compact"): + modes=("comfort","standard","compact") if label=="canonical" else ("comfort",) + for density in modes: data=geometry(page,density,label) if width==1680 and label=="pages" and density=="comfort": page.locator("#tracks .strip[data-id='1'] .fader-section").screenshot( path="m1-calibrated-fader-meter-1680.png") - if label=="pages":page.locator("#densitySelect").select_option("comfort") + if label=="pages": + assert page.locator("#densitySelect").is_hidden() + assert page.locator(".console-body").get_attribute("data-density")=="comfort" math_and_preview(page,label) assert not errors,(label,width,errors) page.close() browser.close() print("PASS M1: dBFS meter and gain rulers calibrated to physical travel; " - "preview demo displays real dBFS percentages, 3 densities × 3 sizes × 3 Pages routes") + "preview demo displays real dBFS, source 3 densities × 3 viewports and the approved public comfort view") if __name__=="__main__": main() diff --git a/tests/pages_micro_fader_visual_v18_smoke.py b/tests/pages_micro_fader_visual_v18_smoke.py index cb7446100..151567f7e 100644 --- a/tests/pages_micro_fader_visual_v18_smoke.py +++ b/tests/pages_micro_fader_visual_v18_smoke.py @@ -7,6 +7,7 @@ import sys import tempfile from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT=Path(__file__).resolve().parents[1] SOURCE=ROOT/"site/preview-v2/index.html" @@ -53,8 +54,16 @@ def check(page,path,label): # No dB scale positions or real input values change: only typography and # major/minor rendering. The two physical ruler ends match the cap travel. - for density in ("comfort","standard","compact"): - page.locator("#densitySelect").select_option(density) + # Only the historical authoring source exposes density selection. + # The shipping /preview/ has one approved comfort view, with the + # compatibility dropdown intentionally hidden (V29 operator decision). + picker=page.locator("#densitySelect") + modes=("comfort","standard","compact") if picker.is_visible() else ("comfort",) + if not picker.is_visible(): + assert picker.is_hidden() and page.locator(".console-body").get_attribute("data-density")=="comfort",label + for density in modes: + if picker.is_visible(): + picker.select_option(density) page.wait_for_selector(channel+" .gain-scale-travel") tick=page.evaluate("""(sel)=>{ const strip=document.querySelector(sel); @@ -111,13 +120,12 @@ def main(): with sync_playwright() as playwright: browser=playwright.chromium.launch(headless=True) for path,label in ((SOURCE,"canonical"), - (dist/"preview/mixer.html","public"), - (dist/"preview-buttons/index.html","png")): + (published_console(dist),"png")): page=browser.new_page(viewport={"width":1680,"height":900},device_scale_factor=1) check(page,path,label) browser.close() print("PASS V18: Material delete+phase, 17px square buttons, calibrated rulers,") - print("no label overlaps across densities, PNG preserved, 3 real preview routes") + print("no ruler overlaps: 3 source densities + approved public comfort, original PNG preserved") if __name__=="__main__": main() diff --git a/tests/pages_png_buttons_wire_reconciliation_smoke.py b/tests/pages_png_buttons_wire_reconciliation_smoke.py index 036003f62..9640417b6 100644 --- a/tests/pages_png_buttons_wire_reconciliation_smoke.py +++ b/tests/pages_png_buttons_wire_reconciliation_smoke.py @@ -7,13 +7,13 @@ """ import hashlib import json -import re import struct import subprocess import sys import tempfile from pathlib import Path from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT=Path(__file__).resolve().parents[1] REFERENCE=ROOT/"site/preview-v2" @@ -37,27 +37,30 @@ def verify_bundle(dist): assert "url=../preview/" in (dist/"preview-buttons/index.html").read_text(encoding="utf-8") assert 'http-equiv="refresh"' in (dist/"preview/mixer.html").read_text(encoding="utf-8") - # Strip only the two deliberate fingerprinted CSS/JS URLs. Everything - # else, including the V46+ WIRE model and channel events, must be 1:1. - stripped=html + # The shipped page uses the current authoritative-FX transformation and + # one compiled CSS bundle. The independent gate reconstructs/compares ALL + # generated HTML and owner CSS bytes, including approved PNG revisions. + assert published_console(dist)==generated/"index.html" for name in SPECIAL: - path="assets/"+name - original_url=re.search(re.escape(path)+r'(?:\?[^"\s>]+)?',original) - current_url=re.search(re.escape(path)+r'\?rev=([0-9a-f]{16})',stripped) - assert original_url and current_url,(name,"missing cache-safe URL") expected=hashlib.sha256((OWNER/name).read_bytes()).hexdigest()[:16] - assert current_url.group(1)==expected,(name,"wrong asset revision") - stripped=stripped[:current_url.start()]+original_url.group(0)+stripped[current_url.end():] + assert meta["button_css_js_revisions"][name]==expected,name assert (generated/"assets"/name).read_bytes()==(OWNER/name).read_bytes(),name - assert stripped==original,"User-approved button variant modified the real WIRE mixer" - - # Removing old snapshots makes every extra asset a current-source - # dependency, never a cloned V45 file frozen across future WIRE updates. canonical={f.name for f in (REFERENCE/"assets").iterdir() if f.is_file()} published={f.name for f in (generated/"assets").iterdir() if f.is_file()} - assert published==canonical|{SPRITE},("asset set drift",published^canonical) + # The approved app branding now adds exactly three favicon resources to + # the compiled /preview/ folder. Keep the asset set strict and verify + # byte identity against this build's generated public root, not unrelated + # developer-local files or an older locked GUI reference. + favicons={"favicon.ico","favicon-16x16.png","favicon-32x32.png"} + expected=canonical|{SPRITE,"arsonmix-approved-runtime.css"}|favicons + assert published==expected,("asset set drift",published^expected) + for name in favicons: + assert (generated/"assets"/name).read_bytes()==(dist/name).read_bytes(),name for name in canonical-set(SPECIAL): - assert (generated/"assets"/name).read_bytes()==(REFERENCE/"assets"/name).read_bytes(),name + # Compiled CSS is checked byte-for-byte by published_console above. + # Uncompiled JS/SVG/font/artwork assets must remain exact source bytes. + if not name.endswith(".css"): + assert (generated/"assets"/name).read_bytes()==(REFERENCE/"assets"/name).read_bytes(),name png=(generated/"assets"/SPRITE).read_bytes() assert png==(ROOT/"site/preview-v34/assets"/SPRITE).read_bytes() diff --git a/tests/pages_wire_first_canonical_main_smoke.py b/tests/pages_wire_first_canonical_main_smoke.py index 944b9cbde..b2012166f 100644 --- a/tests/pages_wire_first_canonical_main_smoke.py +++ b/tests/pages_wire_first_canonical_main_smoke.py @@ -3,7 +3,12 @@ from pathlib import Path from playwright.sync_api import sync_playwright -PAGE=Path(__file__).resolve().parents[1]/"site/preview-v2/index.html" +import subprocess,sys,tempfile +from approved_publication_fixture import published_console +ROOT=Path(__file__).resolve().parents[1] +_current_gui=tempfile.TemporaryDirectory(prefix="arsonmix-approved-interaction-") +subprocess.run([sys.executable,str(ROOT/'scripts/build_pages.py'),'--out',_current_gui.name],cwd=ROOT,check=True,capture_output=True) +PAGE=published_console(Path(_current_gui.name)) def edge(page, channel, endpoint): selector=(f'#tracks .strip[data-id="{channel}"] .wire-node-out' @@ -80,20 +85,27 @@ def drag_to(point,escape=False): def audit_visual_matrix(browser): - """Nine real Chromium renders: viewport, density, focus, collapse, plug.""" + """Nine real Chromium renders: viewport, actual operator focus/fold states and plug.""" for width,height in ((1366,768),(1680,900),(1920,1080)): - for density in ("comfort","standard","compact"): + for presentation in ("default","folded","refocused"): page=browser.new_page(viewport={"width":width,"height":height}, reduced_motion="reduce") errors=[] page.on("pageerror",lambda exc: errors.append(str(exc))) page.goto(PAGE.as_uri()) - page.locator("#densitySelect").select_option(density) body=page.locator(".console-body") - # Narrow/Compact intentionally locks the WIRE bay folded to keep - # 23px physical geometry. It has graph-bound compact contacts, - # not a full cable overlay; the rail refuses expansion by design. - if density=="compact": + # V29 has ONE operator comfort view. The original density select + # remains as a hidden, inert compatibility ID, not a public tool. + # Audit meaningful operator fold and focus states instead of + # selecting an invisible legacy dropdown and timing out. + assert page.locator("#densitySelect").is_hidden() + assert body.get_attribute("data-density")=="comfort" + if presentation=="folded": + if "collapsed-send" not in (body.get_attribute("class") or ""): + page.locator('.section-rail [data-section="send"]').click() + assert "collapsed-send" in (body.get_attribute("class") or "") + # Folded visual sockets may disappear; canonical MAIN EdgeId + # and other channels' connections must not be discarded. assert "collapsed-send" in (body.get_attribute("class") or "") initial=edge(page,1,"out") assert initial, "folded view must retain the canonical MAIN graph edge" @@ -105,62 +117,32 @@ def audit_visual_matrix(browser): ).get_attribute("data-wire-main-edge") is None assert page.locator('#tracks .strip[data-id="1"] .wire-fold-summary .has-out').count()==0 assert page.locator(".wire-main-fragment").count()==0 - page.screenshot(path=str(PAGE.parents[2]/ - f"pages-wire-main-{width}x{height}-{density}.png")) - assert not errors,(width,height,density,errors) + page.screenshot(path=str(ROOT/ + f"pages-wire-main-{width}x{height}-{presentation}.png")) + assert not errors,(width,height,presentation,errors) page.close() continue if "collapsed-send" in (body.get_attribute("class") or ""): page.locator('.section-rail [data-section="send"]').click() - pair=page.evaluate("""() => { - const src=document.querySelector('#tracks .strip[data-id="1"]'); - const main=document.querySelector('#master'); - const fragment=src?.querySelector('.wire-main-fragment'); - const incoming=main?.querySelector('.wire-main-fragment'); - const dot=src?.querySelector('.wire-node-out .wire-pin'); - const jack=main?.querySelector('.wire-node-in .wire-arrow'); - function position(svg,pin){ - if(!svg||!pin)return null; - const r=svg.getBoundingClientRect(),p=pin.getBoundingClientRect(); - const c=svg.querySelector('.wire-main-plug'); - const x=Number(c?.getAttribute('cx')),y=Number(c?.getAttribute('cy')); - if(!Number.isFinite(x)||!Number.isFinite(y))return null; - return {error:Math.hypot(r.left+x-(p.left+p.width/2), - r.top+y-(p.top+p.height/2)), - bounded:x>0&&x0&&yx.querySelector('.wire-node-out[data-wire-main-edge]')).length, - painted:strips.filter(x=>x.querySelector('.wire-main-fragment')).length}; - }""") - assert pair["source"] and pair["source"]==pair["main"]==pair["connected"],( - width,height,density,"MAIN fragments do not share exact graph edge",pair) - assert pair["sources"]>=1 and pair["painted"]==1,( - width,height,density,"only selected channel may paint MAIN fragment",pair) - for side in ("sourceGeometry","mainGeometry"): - geom=pair[side] - assert geom and geom["bounded"] and geom["cubic"] and geom["error"]<=1.1,( - width,height,density,side,"misaligned or clipped MAIN plug",geom) - # Selection moves the SINGLE physical source fragment, never graph edges. + initial=edge(page,1,"out") + assert initial,"quiet MAIN must retain the real graph edge" + assert page.locator('.wire-main-fragment').count()==0 + assert page.locator('#tracks .strip[data-id="1"] .wire-node-out').get_attribute('data-wire-main-edge')==initial + if presentation=="refocused": + page.locator('#tracks .strip[data-id="2"] .strip-identity-top').click() + assert edge(page,2,"out"), "refocus must preserve the other MAIN EdgeId" page.locator('#tracks .strip[data-id="5"] .strip-identity-top').click() - assert page.locator('#tracks .strip[data-id="1"] .wire-main-fragment').count()==0 - assert page.locator('#tracks .wire-main-fragment').count()==1 - focused=page.locator('#master .wire-main-fragment').get_attribute("data-edge-id") - assert focused==edge(page,5,"out") and focused!=pair["source"],( - width,height,density,"focused MAIN edge selection") + focused=edge(page,5,"out") + assert page.locator('#master .wire-node-in').get_attribute('data-wire-main-edge')==focused + assert page.locator('.wire-main-fragment').count()==0 page.locator('.section-rail [data-section="send"]').click() - assert page.locator('.wire-main-fragment').count()==0,( - width,height,density,"collapsed MAIN fragments not retired") + assert page.locator('.wire-main-fragment').count()==0 page.locator('.section-rail [data-section="send"]').click() - assert page.locator('#master .wire-main-fragment').get_attribute("data-edge-id")==focused - page.screenshot(path=str(PAGE.parents[2]/ - f"pages-wire-main-{width}x{height}-{density}.png")) - assert not errors,(width,height,density,errors) + assert page.locator('.wire-main-fragment').count()==0 + assert edge(page,1,"out")==initial and edge(page,5,"out")==focused + page.screenshot(path=str(ROOT/ + f"pages-wire-main-{width}x{height}-{presentation}.png")) + assert not errors,(width,height,presentation,errors) page.close() def run(): @@ -185,17 +167,10 @@ def run(): assert page.locator('#master .wire-node-in').get_attribute("data-wire-main-edge") is None page.locator('.section-rail [data-section="send"]').click() assert page.locator('#master .wire-node-in').get_attribute("data-wire-main-edge")==initial - # One graph edge paints TWO measured local cubic cables, never a - # cross-bank line. Geometry and edge identity survive all widths. - source_stub=page.locator('#tracks .strip[data-id="5"] .wire-main-fragment') - main_stub=page.locator('#master .wire-main-fragment') - assert source_stub.count()==1 and main_stub.count()==1,( - width,"missing paired physical MAIN cables") - assert source_stub.get_attribute("data-edge-id")==initial - assert main_stub.get_attribute("data-edge-id")==initial - assert " C" in source_stub.locator(".wire-main-jacket").get_attribute("d") - assert " C" in main_stub.locator(".wire-main-jacket").get_attribute("d") - assert page.locator('#tracks .strip[data-id="6"] .wire-main-fragment').count()==0 + # MAIN is still routable/reversible but intentionally has no + # source-down or master-down decorative cable fragments. + assert page.locator('.wire-main-fragment').count()==0 + assert page.locator('#tracks .strip[data-id="5"] .wire-node-out').get_attribute('data-wire-main-edge')==initial # Distinct disconnect is reversible and only affects this channel. control.click() @@ -257,7 +232,7 @@ def run(): page.locator("#wireWsUndo").click() assert edge(page,5,"out")==initial,"MAIN pointer undo changed edge identity" page.locator("#wireNavigatorToggle").click() - page.screenshot(path=str(PAGE.parents[2]/"pages-wire-main-1680.png")) + page.screenshot(path=str(ROOT/"pages-wire-main-1680.png")) page.locator('#tracks .strip[data-id="5"] .wire-node-out').click() page.locator('#tracks .strip[data-id="3"] .wire-node-in').click() assert page.locator('#tracks .strip[data-id="3"] .wire-gain').count()==1 @@ -298,7 +273,7 @@ def run(): assert edge(page,5,"out") is None,"Snapshot SAFE overwrote live MAIN route" page.close() browser.close() - print("PASS WIRE A: nine Chromium viewport/density cable audits plus exact-edge MAIN gesture, Scene/SAFE, Undo") + print("PASS WIRE A: nine Chromium viewport/operator-state cable audits plus exact-edge MAIN gesture, Scene/SAFE, Undo") if __name__=="__main__": run() diff --git a/tests/pages_wire_incoming_v43_smoke.py b/tests/pages_wire_incoming_v43_smoke.py index 8c6b3f33f..a914c947a 100644 --- a/tests/pages_wire_incoming_v43_smoke.py +++ b/tests/pages_wire_incoming_v43_smoke.py @@ -3,6 +3,7 @@ from pathlib import Path import math,re,subprocess,sys,tempfile from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT=Path(__file__).resolve().parents[1] CANONICAL=ROOT/"site/preview-v2/index.html" @@ -53,11 +54,9 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"),"--out",str(dst), "--sha","v43-ci-source","--branch","main"],check=True, cwd=ROOT,capture_output=True,text=True) - public=dst/"preview/index.html" + public=published_console(dst) shared=dst/"preview/assets/mixer-wire-dots.css" - assert "mixer-control-keys.css?rev=" in public.read_text("utf-8"),"Published /preview/ lost approved PNG hardware keys" assert shared.read_bytes()==WIRE_CSS.read_bytes(),"Approved /preview/ did not publish the effective WIRE CSS" - assert 'assets/mixer-wire-dots.css?v=v59-selected-wire-quiet' in public.read_text("utf-8") with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) for width in (1366,1680): diff --git a/tests/pages_wire_v44_finish_smoke.py b/tests/pages_wire_v44_finish_smoke.py index b06887855..3838be598 100644 --- a/tests/pages_wire_v44_finish_smoke.py +++ b/tests/pages_wire_v44_finish_smoke.py @@ -3,6 +3,7 @@ from pathlib import Path import subprocess,sys,tempfile from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console from pages_wire_incoming_v43_smoke import center, impact_peak ROOT=Path(__file__).resolve().parents[1] @@ -20,10 +21,8 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), "--out",str(dst),"--sha","v44-ui-smoke","--branch","gui-v44"], cwd=ROOT,capture_output=True,text=True,check=True) - public=dst/"preview/mixer.html" - assert public.read_bytes()==SRC.read_bytes(),"published /preview/ differs from canonical GUI" + public=published_console(dst) assert (dst/"preview/assets/mixer-wire-dots.css").read_bytes()==CSS.read_bytes(),"published WIRE style missing" - assert 'assets/mixer-wire-dots.css?v=v59-selected-wire-quiet' in public.read_text("utf-8") with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) for width in (1366,1680): diff --git a/tests/pages_wire_v45_socket_layout_smoke.py b/tests/pages_wire_v45_socket_layout_smoke.py index 9c5f2773c..f8bd626ad 100644 --- a/tests/pages_wire_v45_socket_layout_smoke.py +++ b/tests/pages_wire_v45_socket_layout_smoke.py @@ -6,6 +6,7 @@ from pathlib import Path import subprocess,sys,tempfile from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console from pages_wire_incoming_v43_smoke import center ROOT=Path(__file__).resolve().parents[1] @@ -61,10 +62,8 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), "--out",str(dist),"--sha","v45-browser","--branch","v45"], cwd=ROOT,capture_output=True,text=True,check=True) - public=dist/"preview/mixer.html" - assert public.read_bytes()==HTML.read_bytes(),"Pages did not publish canonical V45 console" + public=published_console(dist) assert (dist/"preview/assets/mixer-wire-dots.css").read_bytes()==STYLE.read_bytes(),"Pages lost WIRE CSS" - assert "assets/mixer-wire-dots.css?v=v59-selected-wire-quiet" in public.read_text("utf-8") with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) for width in (1366,1680,1920): @@ -106,9 +105,13 @@ def main(): p.locator('#tracks .strip[data-id="3"] .strip-identity-top').click() restored=channel_ring(dest) assert restored["arrival"]=="true" and restored["border"]==connected["border"] and restored["background"]==connected["background"],(width,"visible accepted cable must relight destination",restored) - # Compact is a spatial fallback, not a different hit-test or route state. + # The historical source supports Compact; the compiled public GUI + # deliberately hides the selector. Never simulate an unsupported mode. if width==1366: - p.locator('#densitySelect').select_option(label="Compact") + picker=p.locator('#densitySelect') + if picker.is_visible():picker.select_option(label="Compact") + else: + assert picker.is_hidden() and body.get_attribute("data-density")=="comfort" label_geometry(p,width) assert not errors,(width,errors) p.close() diff --git a/tests/pages_wire_v46_precision_smoke.py b/tests/pages_wire_v46_precision_smoke.py index 95a8f1e0d..5c7442c3a 100644 --- a/tests/pages_wire_v46_precision_smoke.py +++ b/tests/pages_wire_v46_precision_smoke.py @@ -10,6 +10,7 @@ from pathlib import Path from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT=Path(__file__).resolve().parents[1] HTML=ROOT/"site/preview-v2/index.html" @@ -49,12 +50,9 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), "--out",str(dist),"--sha","v46-dot-anchors","--branch","v46"], cwd=ROOT,capture_output=True,text=True,check=True) - public=dist/"preview/mixer.html" - assert public.read_bytes()==HTML.read_bytes(),"published /preview/ HTML is stale" + public=published_console(dist) assert (dist/"preview/assets/mixer-wire-dots.css").read_bytes()==CSS.read_bytes(),"public WIRE CSS differs" - assert "assets/mixer-wire-dots.css?v=v59-selected-wire-quiet" in public.read_text("utf-8") assert (dist/"preview/assets/mixer-wire-out-align-v48.css").read_bytes()==(ROOT/"site/preview-v2/assets/mixer-wire-out-align-v48.css").read_bytes(), "V48 alignment stylesheet missing from /preview/" - assert "assets/mixer-wire-out-align-v48.css?v=out-center-v48" in public.read_text("utf-8") with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) @@ -143,8 +141,12 @@ def main(): lit=incoming_colors(dest) assert lit["connected"] and lit["center"]==lit["ring"] and lit["center"]!="rgb(75, 83, 91)",(width,"focus return must restore accepted visible endpoint",lit) if width==1366: - page.locator('#densitySelect').select_option(label="Compact") - exact(center(dest_pin),center(dest),width,"compact socket no longer concentric",.32) + picker=page.locator('#densitySelect') + if picker.is_visible():picker.select_option(label="Compact") + else: + assert picker.is_hidden() + assert page.locator(".console-body").get_attribute("data-density")=="comfort" + exact(center(dest_pin),center(dest),width,"responsive socket no longer concentric",.32) assert not errors,(width,errors) page.close() browser.close() diff --git a/tests/plugin_vault_contract_test.mjs b/tests/plugin_vault_contract_test.mjs index 6a117de8a..5ff3eb680 100644 --- a/tests/plugin_vault_contract_test.mjs +++ b/tests/plugin_vault_contract_test.mjs @@ -5,7 +5,7 @@ import {readFileSync} from 'node:fs'; const read=p=>readFileSync(p,'utf8'); const vault=read('src/PluginVault.h'), catalog=read('src/PluginCatalog.h'), main=read('src/Main.cpp'), cmake=read('CMakeLists.txt'), - workflow=read('.github/workflows/p1-windows.yml'), testNative=read('tests/plugin_vault_test.cpp'); + testNative=read('tests/plugin_vault_test.cpp'); test('manual VST3 import physically copies whole plugin into the user workspace, not mere absolute source registration',()=>{ assert.match(catalog,/scan \(juce::StringArray \{ file\.getFullPathName\(\) \}, copyToVault\)/); @@ -40,9 +40,7 @@ test('no all-PC scan required for three manually selected VSTs; no third-party c assert.match(catalog,/scan \(juce::StringArray \{ file\.getFullPathName\(\) \}, copyToVault\)/); }); test('Windows CTest exercises full VST bundle resources and preserves original files/versions',()=>{ - assert.match(cmake,/ARMixVaultTests/); - assert.match(cmake,/SelectiveVst3BundleVaultImport/); - assert.match(workflow,/ARMixVaultTests/); + assert.match(cmake,/add_test\(NAME SelectiveVst3BundleVaultImport COMMAND ARMixVaultTests\)/); assert.match(testNative,/Contents\/x86_64-win\/MyVerb\.vst3/); assert.match(testNative,/Contents\/Resources\/moduleinfo\.json/); assert.match(testNative,/NEVER delete user source VST/); diff --git a/tests/portable_workspace_contract_test.mjs b/tests/portable_workspace_contract_test.mjs index c0f7fec9d..d233b274c 100644 --- a/tests/portable_workspace_contract_test.mjs +++ b/tests/portable_workspace_contract_test.mjs @@ -37,9 +37,7 @@ test('plugin catalog and native vendor ZIP persist workspace refs without changi assert.match(main,/presets_ \(settingsDirectory\(\)\.getChildFile \("presets"\), settingsDirectory\(\)\)/); }); test('real Windows-native USB move test is built in existing CTest and release includes marker',()=>{ - assert.match(cmake,/ARMixWorkspaceTests/); - assert.match(cmake,/PortableStudioUsbRelocation/); - assert.match(workflow,/ARMixWorkspaceTests/); + assert.match(cmake,/add_test\(NAME PortableStudioUsbRelocation COMMAND ARMixWorkspaceTests\)/); assert.match(workflow,/portable_workspace_contract_test\.mjs/); assert.match(packaging,/ARSONMIX_PORTABLE_WORKSPACE_V1/); assert.match(packaging,/portable_mode\.txt/); diff --git a/tests/prepared_native_mixer_session_test.cpp b/tests/prepared_native_mixer_session_test.cpp index ea8251b8e..79b2479b9 100644 --- a/tests/prepared_native_mixer_session_test.cpp +++ b/tests/prepared_native_mixer_session_test.cpp @@ -8,7 +8,107 @@ #include using namespace armix::mixer; static bool near(float a,float b){return std::abs(a-b)<1.e-5f;} +// Real prepared native DSP kernel: deterministic multichannel PCM through +// the existing production mixer/publisher, NOT browser-mock or hardware FAT. +static void multiChannelGoldenPcm() { + PreparedNativeMixerSession native; + ChannelRoutingConfig cfg;SendRequest sends; + juce::BigInteger inputsMask,outputsMask; + for(int pin=0;pin<3;++pin)inputsMask.setBit(pin); + outputsMask.setBit(0);outputsMask.setBit(1); + cfg.stripsAndMaster.strips[0]={SourceMode::mono,0,-1,.8f,-1.f,false,false}; + cfg.stripsAndMaster.strips[4]={SourceMode::stereo,1,2,.5f,0.f,false,false}; + cfg.stripsAndMaster.strips[9]={SourceMode::mono,2,-1,.25f,1.f,false,false}; + cfg.stripsAndMaster.master.gainLinear=.5f; + std::uint64_t revision=0; + auto publish=[&](){ + PreparedNativeMixerSession::PrepareResult result; + auto candidate=PreparedNativeMixerSession::prepare( + cfg,sends,inputsMask,outputsMask,77,revision+1,64,result); + assert(candidate); + assert(native.publish(std::move(candidate),revision,77)== + PreparedNativeMixerSession::PublishResult::applied); + ++revision; + (void)native.pollRetirement(); + }; + const std::array a{.1f,.1f,.1f,.1f,.1f,.1f,.1f,.1f}; + const std::array b{.2f,.2f,.2f,.2f,.2f,.2f,.2f,.2f}; + const std::array c{.4f,.4f,.4f,.4f,.4f,.4f,.4f,.4f}; + const float* inputs[]{a.data(),b.data(),c.data()}; + std::array l{},r{}; + auto noop=[](int,float*,float*,int) noexcept {}; + auto check=[&](float left,float right){ + assert(native.render(inputs,3,l.data(),r.data(),2,8,77,noop)); + for(int i=0;i<8;++i){assert(near(l[i],left));assert(near(r[i],right));} + }; + publish();check(.09f,.15f); // CH01+CH05+CH10, true mono/stereo PCM + cfg.stripsAndMaster.strips[4].solo=true; + publish();check(.05f,.10f); // native SOLO excludes both other inputs + cfg.stripsAndMaster.strips[4].solo=false; + cfg.stripsAndMaster.strips[9].mute=true; + publish();check(.09f,.10f); // native per-lane MUTE + cfg.stripsAndMaster.master.mute=true; + publish();check(0.f,0.f); // real PCM post-mixer MAIN mute + auto invalid=cfg; + invalid.stripsAndMaster.strips[0].inputA=7; + PreparedNativeMixerSession::PrepareResult result; + auto rejected=PreparedNativeMixerSession::prepare( + invalid,sends,inputsMask,outputsMask,77,revision+1,64,result); + assert(!rejected);check(0.f,0.f); // invalid pin never replaces graph + cfg.stripsAndMaster.master.mute=false; + cfg.stripsAndMaster.strips[9].mute=false; + cfg.stripsAndMaster.strips[0].inputA=2; + publish();check(.21f,.15f); // source switch, retained lane controls + // Production PCM regression: connected input -> NONE -> same input. + // Every control/other channel stays attached; silence never changes + // physical MAIN authorization, which belongs to LiveAudioEngine. + const auto ch1=cfg.stripsAndMaster.strips[0]; + const auto ch5=cfg.stripsAndMaster.strips[4]; + const auto ch10=cfg.stripsAndMaster.strips[9]; + cfg.stripsAndMaster.strips[0].source=SourceMode::disconnected; + cfg.stripsAndMaster.strips[0].inputA=-1; + cfg.stripsAndMaster.strips[0].inputB=-1; + publish();check(.05f,.15f); // CH5+CH10 still sound + cfg.stripsAndMaster.strips[0]=ch1; + publish();check(.21f,.15f); // CH1 resumes without resetting gain + cfg.stripsAndMaster.strips[4].source=SourceMode::disconnected; + cfg.stripsAndMaster.strips[4].inputA=-1; + cfg.stripsAndMaster.strips[4].inputB=-1; + publish();check(.16f,.05f); // CH5 stereo->NONE, others still sound + cfg.stripsAndMaster.strips[4]=ch5; + publish();check(.21f,.15f); // CH5 stereo resumes + cfg.stripsAndMaster.strips[9].source=SourceMode::disconnected; + cfg.stripsAndMaster.strips[9].inputA=-1; + cfg.stripsAndMaster.strips[9].inputB=-1; + publish();check(.21f,.10f); // CH10 mono->NONE + cfg.stripsAndMaster.strips[9]=ch10; + publish();check(.21f,.15f); // CH10 mono resumes + // An explicitly muted MAIN remains silent through both graph edits. + cfg.stripsAndMaster.master.mute=true; + cfg.stripsAndMaster.strips[4].source=SourceMode::disconnected; + cfg.stripsAndMaster.strips[4].inputA=-1; + cfg.stripsAndMaster.strips[4].inputB=-1; + publish();check(0.f,0.f); + cfg.stripsAndMaster.strips[4]=ch5; + publish();check(0.f,0.f); + cfg.stripsAndMaster.master.mute=false; + publish();check(.21f,.15f); + auto stale=PreparedNativeMixerSession::prepare( + cfg,sends,inputsMask,outputsMask,77,revision+1,64,result); + assert(stale); + assert(native.publish(std::move(stale),revision-1,77)!= + PreparedNativeMixerSession::PublishResult::applied); + check(.21f,.15f); // rejected stale revision cannot change PCM + cfg.stripsAndMaster.strips[3]=cfg.stripsAndMaster.strips[0]; + cfg.stripsAndMaster.strips[0]=StripConfig{}; + publish();check(.21f,.15f); // lane reorder preserves actual routing PCM + l.fill(8.f);r.fill(8.f); + assert(!native.render(inputs,3,l.data(),r.data(),2,8,78,noop)); + assert(l[0]==0.f&&r[0]==0.f); // device hotplug epoch fails silent + native.unpublish(); +} int main(){ + multiChannelGoldenPcm(); PreparedNativeMixerSession session; ChannelRoutingConfig cfg; SendRequest sends; juce::BigInteger in,out; diff --git a/tests/preview_v2_v7_visual_smoke.py b/tests/preview_v2_v7_visual_smoke.py index 09f095a73..b5d789e6a 100644 --- a/tests/preview_v2_v7_visual_smoke.py +++ b/tests/preview_v2_v7_visual_smoke.py @@ -1,14 +1,15 @@ #!/usr/bin/env python3 """Run headless real-Chromium physical geometry and workflow audit for Pages V7. -This is an independent review of the published /preview-v2/ snapshot in main, -NOT a validation of native ASIO/VST3 audio. Screenshots are uploaded by UI smoke. -No external web request; local site/preview-v2/index.html only. +Review both the internal authoring source and the sole published /preview/. +This does not validate native ASIO/VST3 audio. Screenshots are uploaded by UI +smoke. All browser pages are local deterministic build outputs. """ from __future__ import annotations from pathlib import Path -import subprocess, sys, re +import subprocess, sys from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT = Path(__file__).resolve().parents[1] PAGE = (ROOT / "site/preview-v2/index.html").resolve() @@ -96,8 +97,101 @@ def audit_geometry(page, title): + +def audit_v29_operator_collapse(page, label): + """Real published V29: one comfort layout, frame-synchronized 50:50. + + Keep all eight actual operator fold combinations, not the obsolete V7 + fixed-viewport fader-height law. Legacy V7 geometry remains independently + tested by audit_p0_collapse on the unassembled authoring source. + """ + body=page.locator(".console-body") + assert page.locator("#densitySelect").is_hidden(), label + assert body.get_attribute("data-density")=="comfort", label + keys=("route","fx","send") + rail={key:page.locator(f'.section-rail [data-section="{key}"]') for key in keys} + original=tuple("collapsed-"+key in (body.get_attribute("class") or "") for key in keys) + initial_edge=page.locator('#tracks .strip[data-id="5"] .wire-node-out').get_attribute("data-wire-main-edge") + assert initial_edge, (label,"missing original MAIN EdgeId") + seen=set() + try: + for n in range(8): + target=tuple(bool(n & (1< { + const root=document.querySelector('.console-body'), + strip=document.querySelector('#tracks .strip[data-id="1"]'), + master=document.querySelector('#master .strip'), + rail=document.querySelector('.section-rail'); + const box=node=>{const b=node.getBoundingClientRect();return {top:b.top,bottom:b.bottom,height:b.height};}; + const cells=['identity','route','fx','send','pan','switch','fader','footer']; + const slot=k=>k==='identity'?'.strip-identity-top':k==='footer'?'.bottom-section':'.'+k+'-section'; + const rows=Object.fromEntries(cells.map(k=>[ + k,{strip:box(strip.querySelector(slot(k))),rail:box(rail.querySelector('.rail-cell.'+k))}])); + return {root:box(root),rows,master:box(master.querySelector('.bottom-section')), + fxList:strip.querySelector('.fxslot-list').getBoundingClientRect().height, + wireDeck:getComputedStyle(strip.querySelector('.wire-deck')).display, + wireTray:getComputedStyle(strip.querySelector('.wire-tray')).display, + wireSvg:getComputedStyle(document.querySelector('#wireLayer')).display, + sendExpanded:rail.querySelector('[data-section="send"]').getAttribute('aria-expanded'), + overflow:strip.getBoundingClientRect().bottom-box(strip.querySelector('.bottom-section')).bottom}; + }""") + rows=data["rows"] + for key,part in rows.items(): + actual,expected=part["strip"],part["rail"] + assert abs(actual["top"]-expected["top"])<=1.5 and abs(actual["bottom"]-expected["bottom"])<=1.5,( + label,status,key,"rail/channel misaligned",actual,expected) + assert rows["fader"]["strip"]["height"]>=120,(label,status,"fader below usable limit",data) + assert rows["footer"]["strip"]["height"]>=32,(label,status,"missing channel labels",data) + assert abs(data["overflow"])<=3,(label,status,"strip footer truncated",data) + assert abs(data["master"]["bottom"]-rows["footer"]["strip"]["bottom"])<=2,( + label,status,"pinned MAIN footer not aligned",data) + if target[1]: + assert rows["fx"]["strip"]["height"]>=20,(label,status,"FX fold lost rack header",data) + else: + assert data["fxList"]>=88,(label,status,"expanded FX rack cannot show inserts",data) + if target[2]: + assert rows["send"]["strip"]["height"]<=29,(label,status,"WIRE fold not compact",data) + assert data["wireDeck"]=="none" and data["wireTray"]=="none" and data["wireSvg"]=="none",( + label,status,"WIRE fold leaves painted cables",data) + assert data["sendExpanded"]=="false",(label,status,"WIRE rail fold ARIA drift") + else: + assert rows["send"]["strip"]["height"]>=100,(label,status,"expanded WIRE bay missing",data) + assert data["wireDeck"]!="none" and data["wireTray"]!="none",( + label,status,"WIRE dock unexpectedly hidden",data) + assert data["sendExpanded"]=="true",(label,status,"WIRE rail expand ARIA drift") + # For ALL expanded upper modules the native V29 50:50 split + # must be actual computed geometry, not a forced old pixel target. + if not any(target): + upper=rows["pan"]["strip"]["top"]-data["root"]["top"] + lower=rows["footer"]["strip"]["bottom"]-rows["pan"]["strip"]["top"] + assert abs(upper-lower)<=3,(label,"V29 halves must be equal",upper,lower,data) + assert page.locator('#tracks .strip[data-id="5"] .wire-node-out').get_attribute("data-wire-main-edge")==initial_edge,( + label,status,"fold changed accepted MAIN EdgeId") + finally: + for i,key in enumerate(keys): + if ("collapsed-"+key in (body.get_attribute("class") or ""))!=original[i]: + rail[key].click() + page.wait_for_timeout(60) + assert len(seen)==8,(label,"missing actual operator fold states",seen) + assert tuple("collapsed-"+key in (body.get_attribute("class") or "") for key in keys)==original,( + label,"initial fold state was not restored") + return {"states":seen} + + def audit_p0_collapse(page, label): """Every ROUTE/FX/SEND combination preserves PAN/SWITCH/FADER/FOOTER.""" + if page.locator("#densitySelect").is_hidden(): + return audit_v29_operator_collapse(page,label) result=page.evaluate("""() => { const body=document.querySelector('.console-body'); const rail=document.querySelector('.section-rail'); @@ -296,15 +390,9 @@ def main(): "--out", str(ROOT / "_preview-public-qa"), "--sha", "qa"], check=True) assert PAGE.exists() and PUBLIC.exists(), (PAGE, PUBLIC) - assembled=PUBLIC.read_text(encoding="utf-8") - raw=PAGE.read_text(encoding="utf-8") - for asset in ("mixer-control-keys.css","mixer-control-keys.js"): - token="assets/"+asset - source_link=re.search(re.escape(token)+r'(?:\?[^"\s>]+)?',raw) - assert source_link,(asset,"source link missing") - assembled=re.sub(re.escape(token)+r'\?rev=[0-9a-f]{16}', - lambda _: source_link.group(0),assembled) - assert assembled==raw, "Public /preview/ must preserve every GUI interaction and differ only in approved PNG key URLs" + # Verify the exact current assembler (approved PNG, FX semantics and + # compiled CSS), not a comparison against the unassembled authoring HTML. + assert published_console(PUBLIC.parent.parent)==PUBLIC assert 'http-equiv="refresh"' in (PUBLIC.parent/"mixer.html").read_text(encoding="utf-8") count = 0 with sync_playwright() as playwright: diff --git a/tests/smart_audio_diagnostic_contract_test.mjs b/tests/smart_audio_diagnostic_contract_test.mjs index 3147a8afd..7865acd51 100644 --- a/tests/smart_audio_diagnostic_contract_test.mjs +++ b/tests/smart_audio_diagnostic_contract_test.mjs @@ -13,7 +13,6 @@ const bridge=read('engine/device/AdaptiveClockBridge.h'); const policy=read('engine/device/AudioProfilePolicy.h'); const health=read('engine/core/RealtimeHealthHistogram.h'); const cmake=read('CMakeLists.txt'); -const flow=read('.github/workflows/p1-windows.yml'); test('native one-click copy uses system clipboard and includes last event markers',()=>{ assert.match(host,/if \(action == "copyDiagnosticReport"\)/); @@ -45,8 +44,7 @@ test('P0 capability report uses real independent endpoints and never auto-applie assert.match(host,/NOT_FAT_QUALIFIED_DO_NOT_AUTO_APPLY/); assert.match(host,/WASAPI shared can/); assert.match(adapter,/std::span/); - assert.match(cmake,/NativeDriverPeriodEvidence/); - assert.match(flow,/ARMixPeriodEvidenceTests/); + assert.match(cmake,/add_test\(NAME NativeDriverPeriodEvidence COMMAND ARMixPeriodEvidenceTests\)/); assert.match(policy,/unqualifiedLowLatency/); assert.match(policy,/explicitExclusiveApprovalRequired/); }); @@ -73,8 +71,7 @@ test('P0 ASIO native COM-driver registration attestation runs only on control pl assert.match(engine,/asioPinnedRegistration_\.sameDriverClass/); assert.match(engine,/asioRegisteredClassHash/); assert.match(host,/WINDOWS ASIO DRIVER REGISTRATION/); - assert.match(cmake,/AsioDriverClassRegistryAttestation/); - assert.match(flow,/ARMixAsioRegistryIdentityTests/); + assert.match(cmake,/add_test\(NAME AsioDriverClassRegistryAttestation COMMAND ARMixAsioRegistryIdentityTests\)/); }); test('P0 render callback cadence uses previous quantum and labels provenance rather than inventing XRUNs',()=>{ const cadence=read('engine/core/CallbackCadenceEvidence.h'); @@ -90,8 +87,7 @@ test('P0 render callback cadence uses previous quantum and labels provenance rat assert.match(engine,/callbackCadenceComparedIntervals/); assert.match(engine,/callbackCadenceClockRegressions/); assert.match(host,/START-to-START estimates use PREVIOUS callback frame count/); - assert.match(cmake,/P0RenderCallbackVariableQuantumCadence/); - assert.match(flow,/ARMixCadenceTests/); + assert.match(cmake,/add_test\(NAME P0RenderCallbackVariableQuantumCadence COMMAND ARMixCadenceTests\)/); assert.doesNotMatch(engine,/previousCallbackStartUs_/); }); test('telemetry distinguishes measured host budget fractions from unobservable output underrun',()=>{ @@ -111,8 +107,7 @@ test('P0 deterministic virtual clock soak is enforced in Windows CTest',()=>{ assert.match(soak,/steadyUnderflow/); assert.match(soak,/p99Budget/); assert.doesNotMatch(soak,/std::this_thread::sleep_for\s*\(|std::random_device\s*[({]/); - assert.match(cmake,/IndependentClockASRCDriftJitterSoak/); - assert.match(flow,/ARMixVirtualClockSoakTests/); + assert.match(cmake,/add_test\(NAME IndependentClockASRCDriftJitterSoak COMMAND ARMixVirtualClockSoakTests\)/); }); test('clock bridge has no callback alloc / blocking and is gated behind independent stream adapter',()=>{ assert.match(bridge,/class AdaptiveClockBridge final/); @@ -128,7 +123,7 @@ test('clock bridge has no callback alloc / blocking and is gated behind independ assert.match(cmake,/RealtimeHealthHistogram/); for (const target of ['ARMixClockBridgeTests','ARMixVirtualClockSoakTests', 'ARMixHealthTests','ARMixPolicyTests']) - assert.ok(flow.includes(target), 'Windows CI is missing ' + target); + assert.match(cmake, new RegExp('add_test\\(NAME \\w+ COMMAND '+target+'\\)')); assert.match(policy,/class AudioProfilePolicy final/); assert.match(policy,/clockSharedByHardware/); assert.match(policy,/unsupportedClockAdapter/); @@ -148,6 +143,5 @@ test('P0 capture block-head evidence is a single-pass RT heuristic, not invented assert.match(engine,/captureNonFiniteSamples/); assert.doesNotMatch(engine,/rawCapturePeak=juce::jmax\(/); assert.match(fixture,/100000/); - assert.match(cmake,/P0CaptureZeroHeadBoundaryCandidates/); - assert.match(flow,/ARMixCaptureBoundaryTests/); + assert.match(cmake,/add_test\(NAME P0CaptureZeroHeadBoundaryCandidates COMMAND ARMixCaptureBoundaryTests\)/); }); diff --git a/tests/studio_backup_contract_test.mjs b/tests/studio_backup_contract_test.mjs index ec9723983..d6988d32f 100644 --- a/tests/studio_backup_contract_test.mjs +++ b/tests/studio_backup_contract_test.mjs @@ -34,9 +34,7 @@ test('backup is non realtime and fail-closed, not a browser localStorage illusio assert.doesNotMatch(read('src/LiveAudioEngine.h'),/StudioBackup::/); }); test('Windows CI compiles and runs native corruption/USB backup tests in existing job',()=>{ - assert.match(cmake,/ARMixBackupTests/); - assert.match(cmake,/VerifiedPortableStudioBackup/); - assert.match(workflow,/ARMixBackupTests/); + assert.match(cmake,/add_test\(NAME VerifiedPortableStudioBackup COMMAND ARMixBackupTests\)/); assert.match(workflow,/studio_backup_contract_test\.mjs/); assert.match(fixture,/StudioBackup::verify/); assert.match(fixture,/INJECTED\.vst3/); diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs new file mode 100644 index 000000000..cefe9ee4b --- /dev/null +++ b/tests/windows_installer_contract_test.mjs @@ -0,0 +1,24 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +const read=p=>readFileSync(p,'utf8'); +const iss=read('installer/ArSonMix.iss'); +const ps=read('scripts/build_verify_windows_installer.ps1'); +const ci=read('.github/workflows/p1-windows.yml'); +test('Inno RC is per-user, 64-bit, no automatic activation or Studio deletion',()=>{ + for(const item of ['PrivilegesRequired=lowest','DefaultDirName={localappdata}', + 'ArchitecturesAllowed=x64compatible','CloseApplications=no','RestartApplications=no', + 'UNQUALIFIED','verified-gui.exe','BUILD_PROVENANCE.json']) assert.ok(iss.includes(item),item); + assert.doesNotMatch(iss,/^\[(Run|UninstallDelete)\]/m); + assert.doesNotMatch(iss,/^Source:.*portable_mode\.txt/m); +}); +test('installer only derives from verified FAT PE and tests uninstall safely',()=>{ + for(const item of ['manifest.sourceCommit','manifest.exeSha256','manifest.fatStatus', + 'assets/icon/arsonmix-app.ico','FactoryFX','Start-Process -FilePath $setup', + 'Start-Process -FilePath $uninstall','Test-Path -LiteralPath $sentinel', + 'PHYSICAL_FAT_PENDING','INSTALLER_PROVENANCE.json'])assert.ok(ps.includes(item),item); + const verifyStep=ci.indexOf(' - name: Independently verify release ZIP and embedded GUI/engine before upload'); + const installerStep=ci.indexOf(' - name: Compile and validate per-user Windows RC installer from exact FAT PE'); + assert.ok(verifyStep>=0 && installerStep>verifyStep); + assert.match(ci,/ArSonMix-Windows-Installer-UNQUALIFIED/); +}); diff --git a/tests/wire_graph_canonical_model.test.cjs b/tests/wire_graph_canonical_model.test.cjs index a8a5a2aeb..22968b8e5 100644 --- a/tests/wire_graph_canonical_model.test.cjs +++ b/tests/wire_graph_canonical_model.test.cjs @@ -13,6 +13,20 @@ const main1=state.edges.find(e=>e.sourceId===1); const unplug=graph.applyWireTransaction(state,[{type:'REMOVE',sourceId:1,edgeId:main1.id}]); assert.equal(unplug.ok,true); assert.equal(unplug.edges.filter(e=>e.destId===9).length,2); +// An explicit parallel MAIN send does not secretly replace SOURCE ONLY. +const parallelMain=graph.applyWireTransaction( + {...state,edges:unplug.edges,nextId:unplug.nextId}, + [{type:'CONNECT',sourceId:1,destId:9,mode:'send'}]); +assert.equal(parallelMain.ok,true); +const sendToMain=parallelMain.edges.find(e=>e.sourceId===1&&e.destId===9); +assert.equal(sendToMain.kind,'send');assert.equal(sendToMain.mode,'send'); +assert.equal(parallelMain.edges.filter(e=>e.sourceId===1&&e.kind==='primary').length,0); +// Default WIRE to MAIN remains a primary; explicit mode is required for SEND. +const defaultMain=graph.applyWireTransaction( + {...state,edges:unplug.edges,nextId:unplug.nextId}, + [{type:'CONNECT',sourceId:1,destId:9}]); +assert.equal(defaultMain.ok,true); +assert.equal(defaultMain.edges.find(e=>e.sourceId===1&&e.destId===9)?.kind,'primary'); const unchanged=JSON.stringify(state); const connected=graph.applyWireTransaction({...state,edges:unplug.edges,nextId:unplug.nextId}, [{type:'CONNECT',sourceId:1,destId:3}]); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 212cd2d9f..4920ac149 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -16,10 +16,233 @@ const uiByNativeId = new Map(); // EXACT uint64 string -> local view-only ordinal const wireByUiId = new Map(); // view-only EdgeId -> EXACT decimal-string native EdgeId const uiByWireId = new Map(); - let lastPaintedSignature = "", lastNativeError = "NATIVE_NOT_SUBSCRIBED"; + + // Native owns durable channel presentation. The approved Pages model only + // renders native readback; no localStorage authority, fake PCM rename or + // UI-ordinal-dependent alias. All IDs remain exact uint64 decimal strings. + const channelPresentation=new Map(); + let appearanceRevision="0",appearanceWritable=false; + let pendingIdentity=null,identityRequestSerial=0; + const legalName=name=>typeof name==="string"&&name.length>0&&name.length<=30&& + name===name.trim()&&!/[\x00-\x1f\x7f]/.test(name); + const legalColor=color=>typeof color==="string"&&/^#[0-9a-fA-F]{6}$/.test(color); + const legalIcon=icon=>typeof icon==="string"&& + ["♩","♫","♬","🎙","🎸","🎹","🥁","🎧","▥","◉","◎","⊞"].includes(icon); + const displayNameFor=ch=>channelPresentation.get(ch.id)?.name||ch.name; + // Legacy WebView aliases are an import queue ONLY, never rendered or written + // as authoritative state. Each imported row must receive a native ACK plus + // readback before its browser cache entry can be retired. + const legacyIdentityKey="arsonmix.native.channel-presentation.v1"; + const legacyImport=new Map(), legacyDeferred=new Set(); + try { + const prior=JSON.parse(window.localStorage?.getItem(legacyIdentityKey)||"{}"); + if(prior?.version===1&&prior.channels&&typeof prior.channels==="object"){ + for(const [id,p] of Object.entries(prior.channels).slice(0,128)){ + if(protocol.decimal(id)===null||!p||!legalName(p.name)|| + !legalColor(p.color)||!legalIcon(p.icon))continue; + legacyImport.set(id,{name:p.name,color:p.color,icon:p.icon}); + } + } + }catch(_){ /* Native readback remains authoritative on corrupt WebView cache. */ } + function retireLegacyRow(id){ + legacyImport.delete(id); + try { + const prior=JSON.parse(window.localStorage?.getItem(legacyIdentityKey)||"{}"); + if(prior?.version!==1||!prior.channels||typeof prior.channels!=="object")return; + delete prior.channels[id]; + if(Object.keys(prior.channels).length) + window.localStorage.setItem(legacyIdentityKey,JSON.stringify(prior)); + else window.localStorage.removeItem(legacyIdentityKey); + }catch(_){status("Native identity saved; legacy cache cleanup unavailable");} + } + function maybeMigrateLegacy(next){ + if(!appearanceWritable||pendingIdentity||!legacyImport.size|| + !(next?.admitted||next?.retained)|| + next?.raw?.mixerSession?.authority!=="CHANNEL_ID")return; + for(const [id,p] of legacyImport){ + if(legacyDeferred.has(id)||!next.graph.channels.some(ch=>ch.id===id))continue; + const authoritative=channelPresentation.get(id); + if(authoritative){ + // Never overwrite a genuine native edit with older browser data. + if(authoritative.name===p.name&&authoritative.color===p.color&& + authoritative.icon===p.icon)retireLegacyRow(id); + else legacyDeferred.add(id); + continue; + } + if(next.graph.channels.some(ch=>ch.id!==id&& + displayNameFor(ch).toLowerCase()===p.name.toLowerCase())){ + legacyDeferred.add(id); + status("Legacy channel identity name conflicts with native graph; cache preserved"); + continue; + } + const requestId="appearance-import-"+Date.now().toString(36)+"-"+(++identityRequestSerial); + pendingIdentity={requestId,channelId:id,...p,acked:false,migration:true}; + backend.emitEvent("arMixChannelIdentitySet",{ + requestId,channelId:id,...p,appearanceRevision, + deviceEpoch:next.device.epoch,graphRevision:next.graph.revision, + rosterRevision:next.graph.rosterRevision + }); + window.setTimeout(()=>{ + if(pendingIdentity?.requestId!==requestId)return; + legacyDeferred.add(id); + rejectIdentity("Legacy channel identity import timed out; old cache preserved"); + controller?.subscribe(); + },8000); + return; // one crash-recoverable, revision-serialized transaction + } + } + function appearanceFromNative(next){ + const data=next?.raw?.channelAppearance; + if(!data || data.schema!=="arsonmix.native.channel-appearance.v1" || + protocol.decimal(data.revision)===null || !Array.isArray(data.entries) || + typeof data.readOnly!=="boolean"){ + appearanceWritable=false;return; + } + const liveIds=new Set(next.graph.channels.map(ch=>ch.id)); + const observed=new Map(); + for(const p of data.entries){ + if(!p||!liveIds.has(p.id)||observed.has(p.id)|| + !legalName(p.name)||!legalColor(p.color)||!legalIcon(p.icon)){ + appearanceWritable=false; + status("Native channel identity readback invalid; no UI change"); + return; + } + observed.set(p.id,{name:p.name,color:p.color,icon:p.icon}); + } + channelPresentation.clear(); + for(const [id,p] of observed)channelPresentation.set(id,p); + appearanceRevision=data.revision; + appearanceWritable=!data.readOnly; + if(pendingIdentity?.acked){ + const p=pendingIdentity,confirmed=channelPresentation.get(p.channelId); + if(confirmed?.name===p.name&&confirmed.color===p.color&&confirmed.icon===p.icon){ + pendingIdentity=null; + if(p.migration){ + retireLegacyRow(p.channelId); + status("Legacy channel identity migrated to native workspace · "+p.name); + }else{ + const apply=document.getElementById("identitySave"); + if(apply)apply.disabled=false; + scope?.closeChannelIdentity?.(); + status("Channel updated and stored in native workspace · "+p.name); + } + } + } + maybeMigrateLegacy(next); + } + function rejectIdentity(reason){ + pendingIdentity=null; + const apply=document.getElementById("identitySave"); + if(apply)apply.disabled=false; + status(reason); + } + // A channel's cosmetic identity can be edited when its exact native id is + // present in the current acknowledged OR retained graph. No physical + // audio device, output arm or PCM graph mutation is required. + const identityChannelFor=t=>{ + const id=nativeIdFor(t),current=controller?.state()?.current; + return id && (current?.admitted||current?.retained) && + current.graph?.channels?.some(ch=>ch.id===id)?id:null; + }; + const identityEligible=t=>Boolean(identityChannelFor(t)); + let lastEditedChannelId=null; + function openNativeIdentity(t,anchor){ + if(!identityEligible(t)){ + nativeToast("Channel identity unavailable until its native channel is loaded"); + return false; + } + lastEditedChannelId=t.id; + scope?.openChannelIdentity?.(t,anchor); + return true; + } + function acceptIdentityPresentation(){ + if(!connected)return false; + const localId=scope?.identityTrackId, + track=scope?.tracks?.concat(scope.master||[])?.find(x=>x.id===localId), + channelId=nativeIdFor(track),current=controller?.state()?.current; + const rawName=String(document.getElementById("identityName")?.value||""); + const name=rawName.trim().replace(/\s+/g," "); + if(!channelId||!current||(current?.raw?.mixerSession?.authority!=="CHANNEL_ID")|| + !(current.admitted||current.retained)||!appearanceWritable){ + status("Native channel identity unavailable · verify saved native graph"); + return false; + } + if(controller.state().pending||pendingIdentity){ + status("Finish the current native operation before editing identity"); + return false; + } + const color=scope?.identityColor,icon=scope?.identityIcon; + if(!legalName(name)||!legalColor(color)||!legalIcon(icon)){ + status("Enter a valid channel name, color and icon");return false; + } + const seen=current.graph.channels.some(ch=> + ch.id!==channelId&&displayNameFor(ch).toLowerCase()===name.toLowerCase()); + if(seen){status("Channel name is already used");return false;} + const requestId="appearance-"+Date.now().toString(36)+"-"+(++identityRequestSerial); + pendingIdentity={requestId,channelId,name,color,icon,acked:false, + deviceEpoch:current.device.epoch,graphRevision:current.graph.revision, + rosterRevision:current.graph.rosterRevision}; + const apply=document.getElementById("identitySave"); + if(apply)apply.disabled=true; + backend.emitEvent("arMixChannelIdentitySet",{ + requestId,channelId,name,color,icon, + appearanceRevision,deviceEpoch:current.device.epoch, + graphRevision:current.graph.revision, + rosterRevision:current.graph.rosterRevision + }); + status("Saving native channel identity · "+name); + window.setTimeout(()=>{ + if(pendingIdentity?.requestId!==requestId)return; + rejectIdentity("Native identity ACK/readback timed out; original identity retained"); + controller?.subscribe(); + },8000); + return false; // Prevent original Pages demo mutation until authoritative readback. + } + const pendingWireGains=new Map(); + let wireGainFlushQueued=false; + let startupWire=null, startupWireSerial=0, activeWireAttempt=null; + function deferStartupWire(ops,retries=0){ + if(!Array.isArray(ops)||ops.length!==1|| + !["CONNECT","ROUTE_ONLY"].includes(ops[0].type)||!deviceReady())return false; + const current=controller?.state()?.current,op=ops[0]; + const epoch=current?.device?.epoch||String(hardware?.device?.epoch||""); + if(!/^[1-9][0-9]*$/.test(epoch))return false; + const token=++startupWireSerial; + startupWire={ops:ops.map(x=>({...x})),epoch,token,retries,identity:current?.identity, + source:nativeByUiId.get(op.sourceId),destination:nativeByUiId.get(op.destId)}; + status("WIRE · completing initial native input admission"); + controller?.subscribe(); + window.setTimeout(()=>{ + if(startupWire?.token!==token)return; + startupWire=null;status("WIRE not applied · native admission timed out; previous audio preserved"); + },8000); + return true; + } + function flushStartupWire(){ + if(!startupWire)return; + const state=controller?.state(),current=state?.current,p=startupWire,op=p.ops[0]; + if(current?.device?.epoch!==p.epoch){startupWire=null;return;} + if(state.pending||activeNativeSource||nativeUiSourcePending|| + pendingNativeSources.size||pendingSourceQueue.size|| + !flags.acceptedGraphConnected||!current?.admitted)return; + if(p.retries&¤t.identity===p.identity)return; // require a later revision before rebasing + startupWire=null; + if((p.source&&nativeByUiId.get(op.sourceId)!==p.source)|| + (p.destination&&nativeByUiId.get(op.destId)!==p.destination))return; + const from=nativeByUiId.get(op.sourceId),to=nativeByUiId.get(op.destId); + if(op.type==="CONNECT"&¤t.graph.edges.some(e=>e.enabled&&e.from===from&&e.to===to)) { + status("WIRE connected · independently accepted native route");return; + } + nativeHooks.consumeWire(p.ops,p.retries); + } + + let lastPaintedSignature = "",lastNativeTopologySignature = "", + lastNativeError = "NATIVE_NOT_SUBSCRIBED"; // B-stage: attached-node-only meter caches; a structural render invalidates // them atomically. Never retain detached WebView2 strips or stale channel IDs. const meterElements = new Map(); + let nativeFxPowerSerial=0,pendingNativeFxPower=null; + const pendingM4RackPowers=new Map(); let controller = null; const status = message => { lastNativeError = message; @@ -42,6 +265,45 @@ document.documentElement.dataset.armixNativeAuthority = authority; }; const nativeIdFor = t => nativeByUiId.get(t?.id) || null; + function queueWireGainFlush(){ + if(wireGainFlushQueued)return; + wireGainFlushQueued=true; + window.setTimeout(()=>{wireGainFlushQueued=false;flushWireGains();},32); + } + function flushWireGains(){ + const state=controller?.state(),current=state?.current; + if(state?.pending||!current?.admitted)return; + for(const [edgeId,edit] of pendingWireGains){ + pendingWireGains.delete(edgeId); + if(current.identity!==edit.identity)continue; // never replay into a new graph/device + const edge=current.graph.edges.find(e=>e.enabled&&e.edgeId===edgeId&&e.from===edit.source); + if(!edge||edge.primaryOutput!==false)continue; + if(Math.abs(edge.gainLinear-edit.gain)<.00001)continue; + const result=controller.intent("SET_WIRE_GAIN",edit.source,{edgeId,gainLinear:edit.gain}); + if(result.ok)window.setTimeout(()=>controller?.expire(result.requestId),8000); + else status("WIRE gain rejected · "+result.error); + return; // next coalesced target follows ACK + independent readback + } + } + function requestWireGain(op){ + const current=controller?.state()?.current; + const edgeId=wireByUiId.get(op.edgeId),source=nativeByUiId.get(op.sourceId); + const db=Number(op.levelDb); + if(!current?.admitted||!current.graph.capabilities.supportedOps.includes("SET_WIRE_GAIN")|| + !Number.isFinite(db)||db< -60||db>6)return false; + const edge=current.graph.edges.find(e=>e.enabled&&e.edgeId===edgeId&&e.from===source); + if(!edge||edge.primaryOutput!==false)return false; + pendingWireGains.set(edgeId,{source,gain:Math.pow(10,db/20),identity:current.identity}); + queueWireGainFlush();return true; + } + function nativeOutputTargets(t,channels=controller?.state()?.current?.graph?.channels||[]){ + const source=nativeIdFor(t),reserved=["Master","SOURCE ONLY (No Main)","MAIN","NONE"]; + return channels.filter(ch=>ch.id!==source&&["INPUT","GROUP","FX_RETURN"].includes(ch.role)) + .map(ch=>{const label=displayNameFor(ch); + return {id:ch.id,label:reserved.includes(label)|| + channels.filter(other=>displayNameFor(other)===label).length>1? + label+" ["+ch.id+"]":label};}); + } const intent = (operation,t,payload) => { if (!flags.acceptedGraphConnected) { status("NATIVE: accepted graph not projected; control unchanged"); @@ -54,7 +316,7 @@ return result.ok; }; function projection(native) { - if (!native?.admitted || !Array.isArray(native.graph.edges) || + if ((!native?.admitted && !native?.retained) || !Array.isArray(native.graph.edges) || !scope?.make || !scope?.render || !scope?.wireGraph || !scope?.installGraph || !scope?.allocateWireId) return false; const accepted = native.graph; @@ -63,25 +325,47 @@ !["faderDb","pan","mute","solo"].every(k => Object.hasOwn(ch.controls,k)))) return false; const previous = new Map(scope.tracks.concat(scope.master).map(t=>[t.id,t])); const nextTracks = [], localByNative = new Map(), nextNativeByUi = new Map(); - let nextMaster = null; + let nextMaster = null, inputOrdinal=0; for (const [index,ch] of accepted.channels.entries()) { const kind = ch.role==="MAIN"?"master":ch.role==="GROUP"?"bus": ch.role==="FX_RETURN"?"fx":"audio"; - const savedId = uiByNativeId.get(ch.id); + // Preserve approved CH01..CH10 DOM/model identities across M4 G0 + // -> native ChannelId admission -> any later G0 fallback. A new + // temporary track ID would silently move hardware to another strip. + const m4Id=ch.role==="INPUT"?m4TrackIds[inputOrdinal++]:undefined; + const savedId = uiByNativeId.get(ch.id) ?? m4Id; const t = savedId !== undefined && previous.has(savedId) ? previous.get(savedId) : scope.make(ch.name,kind,scope.colors[index%scope.colors.length]||"#568ead"); if (savedId !== undefined) t.id = savedId; // No Number(ch.id): all native identities stay canonical uint64 strings. localByNative.set(ch.id,t.id); nextNativeByUi.set(t.id,ch.id); - t.name=ch.name;t.kind=kind; + t.name=displayNameFor(ch);t.kind=kind; + const appearance=channelPresentation.get(ch.id); + if(appearance?.color)t.color=appearance.color; + if(appearance?.icon)t.icon=appearance.icon; t.format=ch.processingFormat.toLowerCase(); t.level=ch.controls.faderDb; // Native PAN is normalized [-1,+1]; approved fader console uses [-100,+100]. t.pan=ch.controls.pan*100; t.mute=ch.controls.mute; t.solo=ch.controls.solo; + // Admitted ChannelId readback already carries actual physical pins. + // Do not retain the public demo's "None" when native PCM is active. + if(ch.role==="INPUT"){ + const src=ch.source||{},l=/^in:(\d+)$/.exec(src.portId||""), + r=/^in:(\d+)$/.exec(src.portIdRight||""); + t.input=native.retained && src.bindingState==="NEEDS_REMAP"? + NEEDS_REMAP:l?inputLabelFor({mode:src.sourceFormat==="STEREO"?"STEREO":"MONO", + left:Number(l[1]),right:r?Number(r[1]):-1}):"None"; + } + const out=accepted.channels.find(dest=>dest.id===ch.primaryOutId); + // Identity-safe labels also handle duplicate names and reserved labels. + const target=out&&nativeOutputTargets(t,accepted.channels).find(x=>x.id===out.id); + if(ch.role!=="MAIN")t.output=out?.role==="MAIN"?"Master": + (target?.label||"SOURCE ONLY (No Main)"); t.selected=previous.get(t.id)?.selected || false; + if(typeof ch.fxRackBypassed==="boolean")t.fxOn=!ch.fxRackBypassed; if (Array.isArray(ch.inserts)) { t.fx=Array.from({length:8},(_,i)=>ch.inserts[i]?.name||"None"); t.slotBypass=Array.from({length:8},(_,i)=>Boolean(ch.inserts[i]?.bypassed)); @@ -100,11 +384,12 @@ const source=accepted.channels.find(ch=>ch.id===edge.from); const isMain=edge.to===accepted.mainChannelId; const isPrimary=source?.primaryOutId===edge.to; - const kind=isMain||isPrimary?"primary":edge.tap==="SPLIT_PRE"||edge.tap==="SPLIT_POST"?"split":"send"; - const mode=isMain?"postFader":kind==="primary"?"routeOnly": + // An independent SEND to MAIN is not the source's primary OUT. + const kind=isPrimary?"primary":edge.tap==="SPLIT_PRE"||edge.tap==="SPLIT_POST"?"split":"send"; + const mode=isMain?(isPrimary?"postFader":"send"):kind==="primary"?"routeOnly": kind==="split"?(edge.tap==="SPLIT_PRE"?"splitPre":"splitPost"):"send"; - if (isMain && edge.gainLinear!==1) return false; - const gainDb=isMain?0:Math.round(Math.max(-60,Math.min(6, + if (isPrimary && edge.gainLinear!==1) return false; + const gainDb=isPrimary?0:Math.round(Math.max(-60,Math.min(6, edge.gainLinear>0?20*Math.log10(edge.gainLinear):-60))*10)/10; let uiId=uiByWireId.get(edge.edgeId); if (uiId===undefined) uiId=scope.allocateWireId(); @@ -125,9 +410,133 @@ scope.installGraph(nextTracks,nextMaster,edges); return true; } + // Rack and individual FX power are scalar native DSP controls, NOT a + // structural graph change. Updating them must not replace DOM strips, + // steal focus, interrupt a fader drag or reallocate WIRE render objects. + // The verified individual bypass flag stays distinct from rack bypass. + function paintNativeFxPowerReadback(ch,t){ + if(typeof ch.fxRackBypassed!=="boolean"||!Array.isArray(ch.inserts)) + return true; // never synthesize missing DSP readback + const enabled=!ch.fxRackBypassed; + const strip=document.querySelector('.strip[data-id="'+t.id+'"]'); + const rack=strip?.querySelector(".fx-section"); + // Virtualized mobile banks may have no mounted strip. The model still + // receives verified state; normal bank render creates the right buttons. + if(rack){ + const header=rack.querySelector('[data-action="fxOn"]'); + const rows=[...rack.querySelectorAll('.fxslot-row:not(.is-empty)')]; + if(!header||rows.length!==ch.inserts.length)return false; + for(let slot=0;slot + r.dataset.slot===String(slot)); + if(!insert||typeof insert.bypassed!=="boolean"|| + !row||row.dataset.insertId!==insert.id|| + !row.querySelector('[data-action="slotPower"]')) + return false; // structural re-render, never modify wrong FX owner + } + } + t.fxOn=enabled; + if(!Array.isArray(t.slotBypass))t.slotBypass=Array(8).fill(false); + for(let slot=0;slotr.dataset.slot===String(slot)); + const effective=enabled&&!insert.bypassed; + if(insert.latencyChanged===true) + row.title="Plugin delay changed · aligned dry signal retained; reload the plugin before using its new delay"; + else if(Number.isInteger(insert.latencySamples)) + row.title="Plugin delay: "+insert.latencySamples+" samples · compensated"; + row.dataset.fxSlotEnabled=String(!insert.bypassed); + row.dataset.fxEffective=String(effective); + row.classList.toggle("is-active",effective); + row.classList.toggle("is-bypassed",!effective); + const button=row.querySelector('[data-action="slotPower"]'); + button.setAttribute("aria-pressed",String(effective)); + button.title=(insert.bypassed?"Enable":"Bypass")+ + " only insert "+(slot+1); + button.setAttribute("aria-label", + (insert.bypassed?"Enable":"Bypass")+" only FX insert "+ + (slot+1)+" in "+t.name); + } + return true; + } + function projectNativeGraphWithoutFocusLoss(next) { + // Only identity, order, processing width, source and edges are structural. + // Rack/slot bypass is applied in-place from independent readback below. + const structure=JSON.stringify([ + appearanceRevision, // cosmetic readback invalidates DOM projection + next.graph.channels.map(ch=>[ch.id,ch.role,ch.name, + ch.processingFormat,ch.source,ch.primaryOutId, + ch.inserts?.map(fx=>[fx.id,fx.catalogId,fx.name])]), + next.graph.edges.map(e=>[e.edgeId,e.from,e.to,e.tap,e.enabled,e.primaryOutput])]); + if(structure!==lastNativeTopologySignature){ + if(!projection(next))return false; + lastNativeTopologySignature=structure; + return true; + } + scope?.syncNativeWireGains?.(next.graph.edges.filter(e=>e.enabled&&e.primaryOutput===false) + .map(e=>({id:uiByWireId.get(e.edgeId),pending:pendingWireGains.has(e.edgeId),levelDb:Math.round(Math.max(-60,Math.min(6, + e.gainLinear>0?20*Math.log10(e.gainLinear):-60))*10)/10}))); + // Immutable graph topology is identical: update actual scalar controls + // only. Never detach the active HTML select or the captured fader pointer. + for(const ch of next.graph.channels){ + const id=uiByNativeId.get(ch.id); + const t=id===scope?.master?.id?scope.master: + scope?.tracks?.find(x=>x.id===id); + if(!t||!ch.controls)continue; + if(!paintNativeFxPowerReadback(ch,t)){ + // A plugin owner or strip DOM changed under us: do not paint an + // unrelated instance. Rebuild from the accepted native graph. + if(!projection(next))return false; + lastNativeTopologySignature=structure; + return true; + } + const c=ch.controls; + const db=c.faderDb,pan=c.pan*100; + const faderChanged=Number.isFinite(db)&&Math.abs(t.level-db)>.015; + const visualDb=Number.isFinite(db)?pendingFaderVisualDb(t,db):null; + const switchChanged=t.mute!==c.mute||t.solo!==c.solo; + if(faderChanged)t.level=db; + if(Number.isFinite(pan))t.pan=pan; + t.mute=c.mute;t.solo=c.solo; + if(switchChanged && scope.activeFaderId!==t.id){ + scope.refreshStrip?.(t); + if(visualDb!==null)scope.syncFaderVisual?.({...t,level:visualDb}); + meterElements.delete(t.id); + }else if(faderChanged&&scope.activeFaderId!==t.id&&visualDb===null) + scope.syncFaderVisual?.(t); + const root=document.querySelector('.strip[data-id="'+t.id+'"]'); + const knob=root?.querySelector('.center-pan'); + if(knob&&scope.activeFaderId!==t.id&& + document.activeElement!==knob && Number.isFinite(pan)) + knob.value=String(pan); + } + return true; + } // Native telemetry owns the physical meter. When no measured per-channel // samples are published, leave the meter dark; never use Pages sine demo. function paintNativeMeters(next) { + for(const edge of next.graph.edges||[]){ + const ui=uiByWireId.get(edge.edgeId); + if(ui===undefined)continue; + for(const input of document.querySelectorAll?.('.wire-gain[data-wire-id="'+ui+'"]')||[]){ + const fixed=edge.primaryOutput===true; + const disabled=fixed || next.retained; + if(input.disabled!==disabled)input.disabled=disabled; + const title="Primary OUT is unity gain · use the destination fader"; + if(fixed&&input.title!==title)input.title=title; + } + } if (!scope?.displayMeterDbfs)return; const data=next.telemetry?.channelMeterRmsPeak; if (!data || typeof data!=="object")return; @@ -173,25 +582,790 @@ return Number.isSafeInteger(number)&&number>0?number:null; }; const legacy=()=>hardware?.raw?.legacyM4; + // One native SessionSnapshot, not an independently reconstructed M4 model. + const mixerSession=()=>hardware?.raw?.mixerSession; + const m4ControlIsOwner=()=>mixerSession()?.authority==="M4"; + const nativeMasterReady=()=>mixerSession()?.authority==="CHANNEL_ID" && + safeNativeCounter(hardware?.device?.epoch)!==null && + safeNativeCounter(legacy()?.routingRevision)!==null && + Number.isFinite(mixerSession()?.main?.db) && + typeof mixerSession()?.main?.mute==="boolean"; + // The shipped /preview/ IN dropdown is the sole normal hardware source + // selector. Build options exclusively from JUCE-reported active pins, never + // the public browser demo's hardcoded "Input 1 / CABLE / Realtek" strings. + const hardwarePins=()=>Array.isArray(hardware?.device?.inputEndpoints)? + hardware.device.inputEndpoints.filter(p=>p.active===true && + Number.isInteger(p.port) && hardware.device.enabledInputs.includes(p.port)):[]; + // BUS is verified engine state, not an available hardware input choice. + const INTERNAL_BUS="Internal BUS (read-only)"; + const NEEDS_REMAP="NEEDS REMAP"; + const monoLabel=p=>"Mono · "+p.label+" [IN "+(p.port+1)+"]"; + const stereoLabel=(a,b)=>"Stereo · IN "+(a.port+1)+" + "+(b.port+1); + const inputChoicesFor=()=>{ + const pins=hardwarePins(),entries=[{label:"None",mode:"NONE",left:-1,right:-1}]; + for(const p of pins)entries.push({ + label:monoLabel(p),mode:"MONO",left:p.port,right:-1}); + // Expose real adjacent physical stereo pairs, never guess disabled pins. + for(let i=0;i+1{ + if(!row||row.mode==="NONE")return "None"; + if(row.mode==="BUS")return INTERNAL_BUS; + const entries=inputChoicesFor(); + const exact=entries.find(x=>x.mode===row.mode && + x.left===row.left && x.right===row.right); + return exact?.label||"None"; + }; + // ChannelId and the existing M4 use the SAME ten native input ordinals. + // GUI track reorder must never silently repatch a different physical lane. + const m4TrackIds=Array.isArray(scope?.tracks)? + scope.tracks.filter(t=>t.kind==="audio").slice(0,10).map(t=>t.id):[]; + const m4Index=t=>t?.kind==="audio"?m4TrackIds.indexOf(t.id):-1; + let lastM4UiSignature="",lastM4Controls="",nativeUiSourcePending=null; + let lastM4PortSignature="",pendingOutputPatch=null,m4RequestSerial=0,outputSerial=7000; + const pendingSourceQueue=new Map(); + function requestProcessingFormat(t){ + // Once the native ChannelId callback owns PCM, the old M4 routing + // revision is no longer authoritative. Send M/ST through the SAME + // admitted epoch/revision/roster transaction as WIRE and SOURCE. + if(mixerSession()?.authority==="CHANNEL_ID"){ + const current=controller?.state()?.current; + const channelId=nativeIdFor(t); + const source=current?.graph?.channels?.find(ch=>ch.id===channelId); + if(!current?.admitted || !channelId || source?.role!=="INPUT" || + !current.graph.capabilities.supportedOps.includes("SET_PROCESSING_FORMAT")){ + status("M/ST unavailable · native processing format not admitted"); + return false; + } + const target=source.processingFormat==="MONO"?"STEREO":"MONO"; + const request=controller.intent("SET_PROCESSING_FORMAT",channelId, + {format:target}); + if(!request.ok){ + status("M/ST rejected · "+request.error); + return false; + } + window.setTimeout(()=>controller?.expire(request.requestId),8000); + status(t.name+" M/ST → "+target+" · verifying native PCM readback"); + return true; + } + const channel=m4Index(t); + const ep=safeNativeCounter(hardware?.device?.epoch), + rev=safeNativeCounter(legacy()?.routingRevision); + if(!m4Verified()||channel<0||channel>=10|| + ep===null||rev===null||pendingOutputPatch||nativeUiSourcePending|| + !deviceReady()){ + status("M/ST unavailable · wait for accepted hardware route"); + return false; + } + const target=t.format==="mono"?"STEREO":"MONO"; + const requestId=++outputSerial; + pendingOutputPatch={requestId,channel,target,epoch:ep, + operation:"SET_PROCESSING_FORMAT"}; + backend.emitEvent("arMixAction",{action:"routingChannelPatch", + operation:"SET_PROCESSING_FORMAT",requestId,channel,target, + deviceEpoch:ep,revision:rev}); + status("CH "+(channel+1)+" processing "+target+" · verifying native PCM"); + window.setTimeout(()=>{ + if(pendingOutputPatch?.requestId!==requestId)return; + pendingOutputPatch=null; + status("CH "+(channel+1)+" M/ST timed out · prior format preserved"); + controller?.subscribe(); + },8000); + return true; + } + function previewNativePan(t,el,event){ + let value=Math.max(-100,Math.min(100,Number(el.value))); + if(!Number.isFinite(value))return null; + // Identical center latch to the approved Pages mixer: capture at 7, + // hold until 12, snap on release. No fake demo-model DSP mutation. + const keyboard=el.dataset.panKeyboard==="true"; + const bypass=!!event.altKey||el.dataset.panAltPointer==="true"; + const latched=el.dataset.panDetent==="true"; + const width=event.type==="change"?12:latched?12:7; + if(!keyboard&&!bypass&&Math.abs(value)<=width){value=0;el.value="0";} + el.dataset.panDetent=String(!keyboard&&value===0&&!bypass); + if(event.type==="change")delete el.dataset.panKeyboard; + el.setAttribute?.("aria-valuetext",value===0?"Center": + value<0?"Left "+Math.abs(value):"Right "+value); + const container=el.closest?.(".pan-control"); + if(container){ + const left=Math.min(50,50+value/2),right=Math.max(50,50+value/2); + container.style?.setProperty("--pan-start",left+"%"); + container.style?.setProperty("--pan-end",right+"%"); + container.classList?.toggle("is-centered",value===0); + const readout=container.nextElementSibling; + if(readout)readout.textContent=value===0?"C": + value<0?"L"+Math.abs(value):"R"+value; + } + return value; + } + // One request/ACK/readback path for BOTH the ordinary OUT select and the + // hardware-like OUT→MAIN WIRE jack. No browser graph mutation on click. + function requestPrimaryOut(t,target){ + // Exactly ONE PCM route authority: the admitted ChannelId publisher + // owns all MAIN/Group WIRE and OUT mutations, including original CH1-10. + // Calling the old M4 structural patch after native WIRE admission would + // reject valid routes or attempt to resurrect an incompatible M4 graph. + const session=mixerSession(),current=controller?.state()?.current; + if(session?.authority==="CHANNEL_ID"){ + const channelId=nativeIdFor(t); + const ch=current?.graph?.channels?.find(row=>row.id===channelId); + const main=current?.graph?.mainChannelId; + if(!current?.admitted || !channelId || !ch || !main || + !current.graph.capabilities.supportedOps.includes("APPLY_WIRE_TRANSACTION") || + !["INPUT","GROUP","FX_RETURN"].includes(ch.role) || + !target)return false; + const destination=nativeOutputTargets(t).find(row=>row.label===target); + const to=target==="MAIN"?main:destination?.id||null; + if(target!=="NONE"&&!to)return false; + const dest=ch.primaryOutId||null; + if((to&&dest===to)||(target==="NONE"&&!dest)){ + controller.subscribe();return true; + } + let change; + if(to){ + change={op:"ROUTE_ONLY",from:channelId,to, + tap:"POST_FADER",gainLinear:1}; + }else{ + // Exact EdgeId from the independent native readback; never invent a + // disconnect ID or remove an unrelated parallel SEND. + const edge=current.graph.edges.find(e=>e.enabled && + e.from===channelId && e.to===dest && + e.primaryOutput===true); + if(!edge)return false; + change={op:"REMOVE",from:channelId,edgeId:edge.edgeId}; + } + const accepted=controller.intent("APPLY_WIRE_TRANSACTION",channelId, + {changes:[change]}); + if(!accepted.ok){status("Native OUT rejected · "+accepted.error);return false;} + window.setTimeout(()=>controller?.expire(accepted.requestId),8000); + status(t.name+" OUT → "+(target==="NONE"?"SOURCE ONLY":target)+ + " · native PCM readback pending"); + return true; + } + const channel=m4Index(t); + const ep=safeNativeCounter(hardware?.device?.epoch), + rev=safeNativeCounter(legacy()?.routingRevision); + if(!m4Verified()||channel<0||channel>=10|| + (target!=="MAIN"&&target!=="NONE")||ep===null||rev===null|| + pendingOutputPatch||!deviceReady())return false; + const accepted=legacy()?.channels?.[channel]; + if(accepted?.main===(target==="MAIN")){ + status("CH "+(channel+1)+" OUT already "+ + (target==="MAIN"?"MAIN":"SOURCE ONLY")+" · native readback"); + controller?.subscribe();return true; // no need to blink audio + } + const requestId=++outputSerial; + pendingOutputPatch={requestId,channel,target,epoch:ep,operation:"SET_PRIMARY_OUT"}; + const menu=document.querySelector('.strip[data-id="'+t.id+'"] select[data-field="output"]'); + // A draft visibly stays selected while pending, but t.output and + // audio graph remain exclusively the native accepted readback. + if(menu){ + menu.value=target==="MAIN"?"Master":"SOURCE ONLY (No Main)"; + menu.setAttribute("aria-busy","true"); + menu.title="Routing pending · awaiting native ACK and PCM readback"; + } + backend.emitEvent("arMixAction",{action:"routingChannelPatch", + requestId,channel,target,deviceEpoch:ep,revision:rev}); + window.setTimeout(()=>{ + if(pendingOutputPatch?.requestId!==requestId)return; + pendingOutputPatch=null; + status("CH "+(channel+1)+" OUT timed out · restoring verified native route"); + controller?.subscribe(); + },8000); + return true; + } + const pendingNativeSources=new Map(); + let activeNativeSource=null,nativeSourceSerial=0; + function dispatchNativeSource(){ + if(activeNativeSource||!pendingNativeSources.size)return; + const current=controller?.state()?.current; + if(!current?.admitted||mixerSession()?.authority!=="CHANNEL_ID")return; + const [id,choice]=pendingNativeSources.entries().next().value; + pendingNativeSources.delete(id); + if(!current.graph.channels.some(ch=>ch.id===id&&ch.role==="INPUT")) + return nativeToast("Source identity changed · refresh native mixer"); + const requestId="source-native-"+(++nativeSourceSerial); + activeNativeSource={requestId,id,choice}; + backend.emitEvent("arMixAction",{ + action:"routingNativeSourcePatch",requestId,channelId:id, + deviceEpoch:current.device.epoch,graphRevision:current.graph.revision, + rosterRevision:current.graph.rosterRevision, + mode:choice.mode,left:choice.left,right:choice.right}); + status("Input "+choice.label+" · native PCM readback pending"); + window.setTimeout(()=>{ + if(activeNativeSource?.requestId!==requestId)return; + activeNativeSource=null; + nativeToast("Source ACK timed out · previous PCM preserved"); + controller?.subscribe(); + },8000); + } + let pendingBusCreate=null,busRequestSerial=0; + function requestNativeBusCreate(){ + const accepted=controller?.state()?.current; + const session=mixerSession(); + const capabilities=accepted?.graph?.capabilities?.supportedOps; + if(pendingBusCreate||session?.authority!=="CHANNEL_ID"|| + !accepted?.admitted||!Array.isArray(capabilities)|| + !capabilities.includes("CREATE_GROUP")){ + nativeToast("BUS needs the verified native ChannelId graph"); + return false; + } + const requestId="bus-"+(++busRequestSerial); + pendingBusCreate={requestId}; + backend.emitEvent("arMixAction",{ + action:"routingNativeBusCreate",requestId, + deviceEpoch:accepted.device.epoch, + graphRevision:accepted.graph.revision, + rosterRevision:accepted.graph.rosterRevision}); + status("Adding a real stereo BUS → MAIN · native PCM pending"); + window.setTimeout(()=>{ + if(pendingBusCreate?.requestId!==requestId)return; + pendingBusCreate=null; + status("Add BUS timed out · old PCM kept"); + controller?.subscribe(); + },8000); + return true; + } + let pendingFxInsert=null,fxRequestSerial=0,nativeCatalog=new Map(); + let nativeFxDiscoveryRequested=false,nativeFxCatalogScanning=false; + // Lazy USER-triggered discovery: the first Add FX opens immediately and + // starts real JUCE VST3 scanning on its dedicated non-audio worker. Never + // scan during cold device startup, on a timer, or on the RT callback. + function discoverFxOnFirstPickerOpen(){ + if(!connected||nativeCatalog.size||nativeFxDiscoveryRequested|| + nativeFxCatalogScanning)return; + nativeFxDiscoveryRequested=true; + backend.emitEvent("arMixAction",{action:"scanVst3"}); + status("FX · scanning installed VST3 on background worker; picker updates automatically"); + } + const pendingSlotPowers=new Map(); // ACK/readback, never demo FX flags + // The rack header restores exact prior per-insert state, including + // deliberately bypassed plugins; it never blindly turns ALL FX on. + function verifiedFxFor(t,slot){ + const lane=m4Index(t),live=legacy()?.fxInstances?.[lane]?.[slot]; + return lane>=0 && Number.isInteger(slot) && slot>=0&&slot<8 && + live && typeof live.instanceId==="string" && + live.instanceId && typeof live.catalogId==="string"? + {lane,slot,live}:null; + } + function editNativeFx(t,slot,target,position,token){ + const current=controller?.state()?.current,id=nativeIdFor(t); + const actual=current?.graph?.channels.find(c=>c.id===id)?.inserts?.[slot]; + const to=target?nativeIdFor(target):null,operation=target?"MOVE_INSERT":"REMOVE_INSERT"; + if(!current?.admitted||!actual||actual.id!==token||!current.graph.capabilities.supportedOps.includes(operation)){ + status("FX edit unavailable · refresh accepted native instance");return false; + } + if(target&&to===id&&slot===position)return false; + const payload={slot,instanceId:token}; + if(target){payload.toChannelId=to;payload.toSlot=position;} + const result=controller.intent(operation,id,payload); + if(!result.ok){status("FX edit rejected · "+result.error);return false;} + window.setTimeout(()=>controller?.expire(result.requestId),8000); + status(target?"Moving native FX · awaiting accepted readback":"Removing native FX · awaiting accepted readback"); + return true; + } + function requestNativeFxPower(t,slot,bypass){ + const picked=verifiedFxFor(t,slot); + if(!picked||!m4Verified())return false; + const ep=safeNativeCounter(hardware?.device?.epoch), + rev=safeNativeCounter(legacy()?.routingRevision); + const {lane,live}=picked,requestId="fxpower-"+(++fxRequestSerial); + if(ep===null||rev===null||pendingSlotPowers.has(lane+":"+slot)) + return false; + pendingSlotPowers.set(lane+":"+slot,{requestId,token:live.instanceId,bypass}); + backend.emitEvent("arMixAction",{action:"routingFxBypass", + requestId,channel:lane,slot,instanceId:live.instanceId, + deviceEpoch:ep,revision:rev,value:bypass}); + window.setTimeout(()=>{ + if(pendingSlotPowers.get(lane+":"+slot)?.requestId!==requestId)return; + pendingSlotPowers.delete(lane+":"+slot); + status("FX bypass timed out · restoring real rack state"); + controller?.subscribe(); + },5000); + return true; + } + // M4 remains an internal PCM implementation; only native mixerSession + // readback commits UI state. Rack gate never rewrites saved plugin flags. + function requestM4RackPower(t){ + const lane=m4Index(t),session=mixerSession(),row=session?.channels?.[lane]; + const ep=safeNativeCounter(session?.deviceEpoch), + rev=safeNativeCounter(session?.routeRevision); + if(session?.authority!=="M4"||lane<0||!row || + typeof row.fxRackBypassed!=="boolean"||ep===null||rev===null|| + pendingM4RackPowers.has(lane))return false; + const bypassed=!row.fxRackBypassed,requestId="rack-m4-"+(++nativeFxPowerSerial); + pendingM4RackPowers.set(lane,{requestId,channel:lane,bypassed, + epoch:String(ep),revision:String(rev),acked:false}); + backend.emitEvent("arMixAction",{action:"routingFxRackBypass", + requestId,channel:lane,deviceEpoch:ep,revision:rev,value:bypassed}); + window.setTimeout(()=>{ + if(pendingM4RackPowers.get(lane)?.requestId!==requestId)return; + pendingM4RackPowers.delete(lane); + status("Native rack gate timed out · restoring accepted readback"); + controller?.subscribe(); + },8000); + return true; + } + function reconcileM4RackReadback(next){ + const session=next?.raw?.mixerSession; + for(const [lane,p] of pendingM4RackPowers){ + if(session?.authority!=="M4"|| + session.deviceEpoch!==p.epoch||session.routeRevision!==p.revision){ + pendingM4RackPowers.delete(lane);continue; + } + const actual=session.channels?.[lane]?.fxRackBypassed; + if(p.acked && actual===p.bypassed)pendingM4RackPowers.delete(lane); + } + } + function requestAdmittedFxPower(t,action,button){ + const session=mixerSession(),current=controller?.state()?.current; + const channelId=nativeIdFor(t); + const ch=current?.graph?.channels?.find(x=>x.id===channelId); + if(session?.authority!=="CHANNEL_ID"||!current?.admitted|| + !channelId||!ch||pendingNativeFxPower)return false; + const rack=action==="fxOn",slot=Number(button?.dataset?.slot); + const insert=!rack&&Number.isInteger(slot)&&slot>=0&&slot<8? + ch.inserts?.[slot]:null; + if((rack&&typeof ch.fxRackBypassed!=="boolean")|| + (!rack&&(!insert||typeof insert.id!=="string"|| + !insert.id||typeof insert.bypassed!=="boolean")))return false; + const bypassed=rack?!ch.fxRackBypassed:!insert.bypassed; + const requestId="native-rack-"+(++nativeFxPowerSerial); + pendingNativeFxPower={requestId,channelId,kind:rack?"rack":"insert", + insertId:insert?.id,bypassed,acked:false}; + backend.emitEvent("arMixAction",{action:rack? + "routingNativeFxRackBypass":"routingNativeFxInsertBypass", + requestId,channelId,deviceEpoch:current.device.epoch, + revision:current.graph.revision,value:bypassed, + ...(rack?{}:{slot,insertId:insert.id})}); + window.setTimeout(()=>{ + if(pendingNativeFxPower?.requestId!==requestId)return; + pendingNativeFxPower=null; + status("Native FX power timed out · accepted state preserved"); + controller?.subscribe(); + },8000); + return true; + } + let pendingNativeControl=new Map(),lastNativeControlSent=new Map(); + const m4Meters=new Map(); + const m4Verified=()=>{ + const m=legacy(),d=hardware?.device; + return m4TrackIds.length===10 && + new Set(m4TrackIds).size===10 && + m?.active===true && m.routeAccepted===true && + m.nativeBusStructural!==true && + Array.isArray(m.channelControls) && + m.channelControls.length===10 && m.channels?.length===10 && + safeNativeCounter(d?.epoch)!==null && + safeNativeCounter(m.routingRevision)!==null; + }; + + // Live gestures choose the installed PCM authority. The M4 ordinal is + // NEVER a native ChannelId: a ChannelId graph uses its exact admitted id + // and its existing ACK + later readback contract. MAIN is a physical host + // scalar and retains its guarded routingM4Control gateway. + const controlKey=(parameter,t)=>parameter+":"+(t?.kind==="master"?"main":t?.id); + const channelIdScalarReady=(parameter,t)=>{ + const current=controller?.state()?.current; + return t?.kind!=="master" && + mixerSession()?.authority==="CHANNEL_ID" && + flags.acceptedGraphConnected && current?.admitted===true && + !!nativeIdFor(t) && + current.graph.capabilities.supportedOps.includes( + parameter==="faderDb"?"SET_FADER":"SET_PAN"); + }; + function liveScalarReady(parameter,t) { + if(t?.kind==="master")return parameter==="masterGain" && + (m4Verified()||nativeMasterReady()); + if(m4ControlIsOwner())return m4Verified()&&m4Index(t)>=0; + return channelIdScalarReady(parameter,t); + } + const nativeEditIdentity=(t)=>({ + epoch:String(hardware?.device?.epoch), + authority:mixerSession()?.authority, + channelId:t?.kind==="master"?null:nativeIdFor(t) + }); + function sameNativeEditIdentity(edit) { + const now=nativeEditIdentity(edit.t); + return edit.epoch===now.epoch && + edit.authority===now.authority && + edit.channelId===now.channelId; + } + // Only the last gesture target owns the visual fader cap until the + // producer independently reads that SAME target back. Earlier ACKs and + // snapshot ticks must not move the cap backwards after pointer release. + // The track model always remains native-owned (not optimistically edited). + const liveFaderVisualTargets=new Map(); + function pendingFaderVisualDb(t,actualDb){ + const key=controlKey(t?.kind==="master"?"masterGain":"faderDb",t); + const pending=liveFaderVisualTargets.get(key); + if(!pending)return null; + if(!sameNativeEditIdentity(pending)){ + liveFaderVisualTargets.delete(key);return null; + } + if(Math.abs(actualDb-pending.value)<=.11){ + liveFaderVisualTargets.delete(key);return null; + } + return pending.value; + } + // null means an admitted ChannelId intent is already awaiting its ACK / + // producer readback. Keep ONLY the newest dB target, never drop release. + function dispatchLiveScalar(edit) { + if(!sameNativeEditIdentity(edit) || + !liveScalarReady(edit.parameter,edit.t))return false; + if(edit.t?.kind==="master" || m4ControlIsOwner()) + return sendM4Control(edit.parameter,edit.t,edit.value); + if(controller?.state()?.pending)return null; + return intent(edit.parameter==="faderDb"?"SET_FADER":"SET_PAN", + edit.t,edit.parameter==="faderDb"? + {valueDb:edit.value}:{value:edit.value/100}); + } + function flushLiveScalars() { + for(const [key,edit] of pendingNativeControl) { + const result=dispatchLiveScalar(edit); + if(result===null)continue; + pendingNativeControl.delete(key); + if(result)lastNativeControlSent.set(key,performance.now()); + else { + if(liveFaderVisualTargets.get(key)===edit) + liveFaderVisualTargets.delete(key); + status("LIVE PCM scalar rejected · native identity changed"); + } + } + } + function streamFaderControl(parameter,t,value,final){ + if(!liveScalarReady(parameter,t))return false; + const key=controlKey(parameter,t),now=performance.now(); + const edit={parameter,t,value,...nativeEditIdentity(t)}; + pendingNativeControl.set(key,edit); // coalesce: last writer always wins + if(parameter==="faderDb"||parameter==="masterGain") + liveFaderVisualTargets.set(key,edit); + const last=lastNativeControlSent.get(key); + if(final||last===undefined||now-last>=30) + flushLiveScalars(); // pointermove publishes BEFORE pointerup + if(pendingNativeControl.has(key))queueLiveControlFlush(); + return true; + } + // A queued ChannelId target is retried only after its real ACK/readback + // completes (see onStatus), not by a second timer polling the audio engine. + let nativeControlFlushQueued=false; + function queueLiveControlFlush(){ + if(nativeControlFlushQueued)return; + nativeControlFlushQueued=true; + window.setTimeout(()=>{ + nativeControlFlushQueued=false; + flushLiveScalars(); + },32); + } + function previewFaderWithoutModelMutation(t,db){ + if(!Number.isFinite(db)||!t)return; + scope?.syncFaderVisual?.({...t,level:db}); + } + function paintM4FxInstances(m) { + // Catalog refresh is metadata, never permission to replace a native + // rack with an inactive compatibility graph's old/empty FX inventory. + if(mixerSession()?.authority==="CHANNEL_ID")return; + if(!Array.isArray(m?.fxInstances)||!scope?.tracks)return; + for(let lane=0;lane<10;lane++){ + const t=scope.tracks.find(x=>x.id===m4TrackIds[lane]); + const rows=m.fxInstances[lane]; + if(!t||!Array.isArray(rows))continue; + let change=false; + const acceptedRack=mixerSession()?.authority==="M4"? + mixerSession()?.channels?.[lane]?.fxRackBypassed:undefined; + if(typeof acceptedRack==="boolean" && t.fxOn===acceptedRack){ + t.fxOn=!acceptedRack;change=true; + } + for(let slot=0;slot<8;slot++){ + const live=rows[slot],entry=nativeCatalog.get(live?.catalogId); + const name=live?(entry?.name||"VST3 Loaded"):"None"; + if(t.fx[slot]!==name || t.slotBypass[slot]!==Boolean(live?.bypassed) || + (t.fxInsertIds?.[slot]?.id||null)!==(live?.instanceId||null)){ + t.fx[slot]=name; + t.slotBypass[slot]=Boolean(live?.bypassed); + if(!Array.isArray(t.fxInsertIds))t.fxInsertIds=Array(8).fill(null); + t.fxInsertIds[slot]=live?{id:live.instanceId,name}:null; + change=true; + } + } + if(change && scope.activeFaderId!==t.id) + scope.refreshStrip?.(t); + } + } + function sendM4Control(parameter,t,value) { + if((t?.kind!=="master"&&!m4ControlIsOwner()) || + !(m4Verified()||(t?.kind==="master"&&nativeMasterReady())) || + (typeof value!=="boolean"&&!Number.isFinite(value))) + return false; + const channel=t?.kind==="master"?-1:m4Index(t); + if(channel<0 && t?.kind!=="master")return false; + const ep=safeNativeCounter(hardware.device.epoch), + rev=safeNativeCounter(legacy().routingRevision); + if(ep===null||rev===null)return false; + const requestId="m4-"+(++m4RequestSerial); + const key=m4ControlKey(parameter,channel); + pendingM4Controls.set(key,{requestId,channel,parameter,value, + epoch:String(ep),revision:String(rev),acked:false}); + backend.emitEvent("arMixAction",{action:"routingM4Control", + requestId,channel,parameter,controlValue:value,deviceEpoch:ep, + revision:rev}); + window.setTimeout(()=>{ + if(pendingM4Controls.get(key)?.requestId!==requestId)return; + pendingM4Controls.delete(key); + status("M4 control ACK/readback timed out · restoring native state"); + controller?.subscribe(); + },8000); + return true; + } + // Correlate each scalar edit, including simultaneous different-channel + // gestures. An ACK is only permission to request an INDEPENDENT readback. + const pendingM4Controls=new Map(); + const m4ControlKey=(parameter,channel)=>parameter+":"+channel; + function reconcileM4ControlReadback(next) { + let awaiting=false; + const session=next?.raw?.mixerSession; + for(const [key,p] of pendingM4Controls) { + const revision=p.channel===-1? + next?.raw?.legacyM4?.routingRevision:session?.routeRevision; + if(next.device.epoch!==p.epoch || revision!==p.revision || + (p.channel!==-1 && session?.authority!=="M4")) { + pendingM4Controls.delete(key); + status("STALE M4 control · device/route changed; restoring readback"); + continue; + } + const row=p.channel===-1?null:session?.channels?.[p.channel]; + const value=p.channel===-1? + (p.parameter==="masterGain"?session?.main?.db:session?.main?.mute): + p.parameter==="faderDb"?row?.controls?.faderDb: + p.parameter==="pan"?row?.controls?.pan*100: + row?.controls?.[p.parameter]; + const matches=typeof p.value==="boolean"?value===p.value: + Number.isFinite(value)&&Math.abs(value-p.value)<= + (p.parameter==="pan"?.8:.11); + if(p.acked && matches)pendingM4Controls.delete(key); + else awaiting=true; + } + return awaiting; + } + function paintM4Fallback(next) { + if(!m4Verified()||!Array.isArray(scope?.tracks))return; + const session=next.raw?.mixerSession,m=next.raw?.legacyM4; + if(session?.authority!=="M4"||!Array.isArray(session.channels)||session.channels.length!==10)return; + const ctl=session.channels.map(row=>row.controls); + paintM4FxInstances(m); + const controlSignature=JSON.stringify([next.device.epoch, + session.routeRevision,ctl,session.main]); + if(controlSignature!==lastM4Controls) { + lastM4Controls=controlSignature; + for(let i=0;i<10;i++){ + const t=scope.tracks.find(x=>x.id===m4TrackIds[i]),c=ctl[i]; + const db=c?.faderDb,pan=c?.pan*100; + if(!t||!c||!Number.isFinite(db)||!Number.isFinite(pan)|| + typeof c.mute!=="boolean"||typeof c.solo!=="boolean")return; + const oldDb=t.level; + const visualDb=pendingFaderVisualDb(t,db); + const switchChanged=t.mute!==c.mute||t.solo!==c.solo; + t.level=db;t.pan=pan;t.mute=c.mute;t.solo=c.solo; + if(switchChanged && scope.activeFaderId!==t.id){ + scope.refreshStrip?.(t); + if(visualDb!==null)scope.syncFaderVisual?.({...t,level:visualDb}); + m4Meters.delete(t.id); + }else if(Math.abs(oldDb-db)>.015 && + scope.activeFaderId!==t.id&&visualDb===null) + scope.syncFaderVisual?.(t); + const panKnob=document.querySelector( + '.strip[data-id="'+t.id+'"] .center-pan'); + if(panKnob && document.activeElement!==panKnob) + panKnob.value=String(pan); + } + if(scope.master && Number.isFinite(session.main?.db) && + Math.abs(scope.master.level-session.main.db)>.015){ + const visualDb=pendingFaderVisualDb(scope.master,session.main.db); + scope.master.level=session.main.db; + if(scope.activeFaderId!==scope.master.id && visualDb===null) + scope.syncFaderVisual?.(scope.master); + } + if(scope.master && typeof session.main?.mute==="boolean" && + scope.master.mute!==session.main.mute){ + scope.master.mute=session.main.mute; + if(scope.activeFaderId!==scope.master.id) + scope.refreshStrip?.(scope.master); + } + } + // Only measured JUCE callback peaks are painted. Cache actual live DOM + // fills to avoid repeated selector searches for every timer/signal tick. + if(!scope?.displayMeterDbfs)return; + const now=performance.now(); + for(let i=0;i<10;i++){ + const t=scope.tracks.find(x=>x.id===m4TrackIds[i]); + if(!t)continue; + let entry=m4Meters.get(t.id); + if(!entry?.root?.isConnected){ + const root=document.querySelector('.strip[data-id="'+t.id+'"]'); + if(!root)continue; + entry={root,left:root.querySelector(".meter-fill.left"), + right:root.querySelector(".meter-fill.right")}; + m4Meters.set(t.id,entry); + } + for(const side of ["left","right"]){ + const peak=side==="left"?session.channels[i].peakL:session.channels[i].peakR; + if(!Number.isFinite(peak)||peak<0)continue; + const fill=entry[side];if(!fill)continue; + scope.displayMeterDbfs(fill,peak===0?-90: + Math.max(-90,Math.min(6,20*Math.log10(peak))), + now,"native-m4:"+i+":"+side); + } + } + } + function refreshRealM4Inputs(next){ + if(!scope?.tracks || next?.admitted || !Array.isArray(scope.tracks) || + scope.tracks.length<10) return; + const session=next?.raw?.mixerSession; + const m4=next?.raw?.legacyM4; + const acceptedM4=session?.authority==="M4" && + Array.isArray(session.channels)&&session.channels.length===10; + // An UNPATCHED prepared native M4 renderer has no accepted route yet, + // so the SessionSnapshot deliberately reports authority NONE. The + // operator must still SEE its verified physical IN choices to create + // the first route. Previously an early return left every dropdown at + // "None" forever; requiring a patched route to display the first pin + // created a circular bootstrap dependency. + const preparedFirstSound=session?.authority==="NONE" && + m4?.active===true && m4?.routeAccepted===false; + if(!acceptedM4&&!preparedFirstSound)return; + const rows=acceptedM4?session.channels.map(ch=>ch.source):null; + const signature=JSON.stringify([session.authority,next?.device?.epoch, + next?.device?.enabledInputs,next?.device?.inputEndpoints, + m4?.active,m4?.routingRevision,rows]); + if(signature===lastM4UiSignature)return; + lastM4UiSignature=signature; + for(let i=0;i<10;++i){ + const t=scope.tracks.find(x=>x.id===m4TrackIds[i]); + if(t?.kind!=="audio")continue; + // An unpatched session has NO physical row. Keep the model at None, + // while rendering the native pin choices for the initial operator + // selection. Do not borrow source/OUT data from the demo or a prior + // device session. + const row=acceptedM4?rows[i]:null; + t.input=inputLabelFor(row); + if(row && typeof row.main==="boolean") + t.output=row.main?"Master":"SOURCE ONLY (No Main)"; + if(row && ["MONO","STEREO"].includes(row.channelFormat)){ + const format=row.channelFormat.toLowerCase(); + if(t.format!==format){ + t.format=format; + if((scope.activeFaderId??-1)!==t.id && + !document.activeElement?.matches?.(".strip select")) + scope.refreshStrip?.(t); + } + } + } + // A source ACK changes only affected fields; never replace the whole + // mixer while another select is open or another fader is being dragged. + const ports=JSON.stringify([next?.device?.epoch, + next?.device?.enabledInputs,next?.device?.inputEndpoints]); + if(ports!==lastM4PortSignature){ + lastM4PortSignature=ports; + if((scope.activeFaderId??-1)<0 && + !document.activeElement?.matches?.('.strip select')) + scope.render?.(); // refresh all hardware choices ONLY after device setup + }else{ + for(let i=0;i<10;++i){ + const t=scope.tracks.find(x=>x.id===m4TrackIds[i]); + if(!t)continue; + const root=document.querySelector('.strip[data-id="'+t.id+'"]'); + for(const field of ["input","output"]){ + const element=root?.querySelector('select[data-field="'+field+'"]'); + if(field==="output"&&pendingOutputPatch?.channel===i && + pendingOutputPatch?.operation==="SET_PRIMARY_OUT")continue; + if(element && document.activeElement!==element && + element.value!==t[field])element.value=t[field]; + } + } + } + } + + const virtualCableFeedbackPair=()=>{ + const capture=String(hardware?.device?.captureDevice||"").toLowerCase(); + const playback=String(hardware?.device?.playbackDevice||"").toLowerCase(); + return (capture.includes("vb-audio")||playback.includes("vb-audio")) && + capture.includes("cable output") && playback.includes("cable input"); + }; + // ChannelId requires its installed accepted callback. Before the FIRST + // source selection there is intentionally no ChannelId or M4 route yet: + // authoritative SessionSnapshot is NONE, but legacyM4.active means the + // JUCE callback has independently prepared a real SILENT M4 graph and + // verified sparse physical pins. Let THAT state accept the first IN patch. + // Never infer readiness from the Pages/demo tracks or the presence of a + // Windows playback device alone. const deviceReady=()=>!!(hardware?.device?.backend && - hardware.device.sampleRate>0 && + // ChannelId generation is a full uint64 decimal string and MUST NOT + // round through JS Number.MAX_SAFE_INTEGER. M4 numeric event tokens + // remain separately range-checked before their actual dispatch. + protocol.decimal(hardware.device.epoch)!==null && + hardware.device.epoch!=="0" && + hardware.device.sampleRate>0 && hardware.device.bufferFrames>0 && + Array.isArray(hardware.device.enabledInputs) && hardware.device.enabledInputs.length>0 && - hardware.device.enabledOutputs.length>=2 && legacy()?.active===true); + Array.isArray(hardware.device.enabledOutputs) && + hardware.device.enabledOutputs.length>=2 && + (mixerSession()?.authority==="CHANNEL_ID" + ? controller?.state()?.current?.admitted===true && + flags.acceptedGraphConnected + : (mixerSession()?.authority==="M4" || + mixerSession()?.authority==="NONE") && + legacy()?.active===true && + safeNativeCounter(legacy()?.routingRevision)!==null)); + function syncMonitorButton(d) { + const monitorButton=document.querySelector?.("[data-native-monitor]"); + if(monitorButton){ + monitorButton.textContent=d?.outputArmed?"Monitor On":"Monitor Off"; + monitorButton.setAttribute("aria-pressed",String(!!d?.outputArmed)); + monitorButton.title=d?.outputArmed? + "Mute actual MAIN output immediately":"Listen through verified MAIN hardware output"; + monitorButton.disabled=!d?.outputArmed && !deviceReady(); + monitorButton.dataset.armed=String(!!d?.outputArmed); + } + } function updateHardwarePanel(next) { hardware=next || null; + refreshRealM4Inputs(next); const d=next?.device; const deviceOpen=Boolean(d?.backend && d.sampleRate>0 && d.enabledOutputs.length>=2); const label=document.getElementById("transport"); - const transport=!deviceOpen?"Device not ready": - d.outputArmed?"Output armed":"Output muted"; + const playback=String(d?.playbackDevice||"unknown output"); + const virtualOut=/VB-Audio Virtual Cable|CABLE Input/i.test(playback); + syncMonitorButton(d); + const mainOutput=next?.retained?NEEDS_REMAP:deviceOpen?playback:null; + if(scope?.master && mainOutput && scope.master.output!==mainOutput){ + scope.master.output=mainOutput; + if(!next?.admitted && !next?.retained)scope.render?.(); + } + const transport=next?.retained?"MONITOR OFF · OUT NEEDS REMAP": + !deviceOpen?"Audio device not ready": + (d.outputArmed?"MONITOR ON":"MONITOR OFF")+" · OUT "+playback+ + (virtualOut?" · VIRTUAL / NO SPEAKERS":""); if(label && label.textContent!==transport)label.textContent=transport; const warning=document.querySelector?.(".status-bar .warning"); - const warningText=!deviceOpen?"NO VERIFIED AUDIO DEVICE": + // A silent first-sound session is not an operator failure and does + // not require Patch CH1 / Arm / Start controls. The real IN dropdown + // initiates native source publication; only its correlated ACK may + // request a safe first MONITOR. If the driver exposes no physical IN, + // guide the operator to the existing Audio I/O panel instead. + const warningText=next?.retained?"NEEDS REMAP · MIXER RETAINED · OUTPUT MUTED": + !deviceOpen?"NO VERIFIED AUDIO DEVICE": d.outputArmed?(next.admitted?"NATIVE PCM · HARDWARE FAT PENDING": - "MAIN ARMED · PCM NOT YET ADMITTED"): - legacy()?.routeAccepted?"INPUT PATCHED · OUTPUT MUTED": - "NO AUDIBLE OUTPUT · PATCH INPUT + ARM"; + "MAIN MONITOR ON · PCM ADMISSION NOT VERIFIED"): + !d.enabledInputs?.length?"NO CAPTURE INPUT · OPEN AUDIO I/O": + legacy()?.routeAccepted?"NATIVE INPUT ROUTED · MONITOR OFF": + deviceReady()?"SELECT CHANNEL IN · NATIVE MONITOR AFTER ACK": + "NO VERIFIED INPUT ROUTE · OPEN AUDIO I/O"; if(warning && warning.textContent!==warningText)warning.textContent=warningText; if(!inputSelect)return; const pins=deviceOpen?d.inputEndpoints.filter(p=> @@ -231,6 +1405,301 @@ if(hardwareNote.textContent!==note)hardwareNote.textContent=note; } } + // Compact DAW-style device preferences INSIDE the approved Windows GUI. + // Only the existing AudioDeviceManager inventory/APPLY API is used. This + // replaces the 740x590 default JUCE dialog for normal operator setup. + let devicePanel=null,deviceInventory=null,deviceBusy=false, + deviceRequest=0,pendingDeviceMute=null,deviceChoice=null,deviceResult="", + offeredPinRemap=null; + let toastTimer=0; + function nativeToast(message){ + let element=document.getElementById("armixNativeToast"); + if(!element){ + element=document.createElement("div"); + element.id="armixNativeToast"; + element.setAttribute("role","status"); + element.style.cssText="position:fixed;right:16px;bottom:36px;z-index:99999;"+ + "max-width:min(390px,88vw);padding:9px 13px;border:1px solid #426f7e;"+ + "border-radius:6px;background:#123240;color:#dff8fd;"+ + "font:12px system-ui,sans-serif;box-shadow:0 9px 28px #0008"; + document.body.appendChild(element); + } + element.textContent=message;element.hidden=false; + window.clearTimeout(toastTimer); + toastTimer=window.setTimeout(()=>{element.hidden=true;},3400); + } + function openNativeAudioIO(){ + if(!devicePanel){ + const style=document.createElement("style"); + style.textContent=` + .armix-audio-shade{position:fixed;inset:0;background:#020b12b8;z-index:99998; + display:flex;align-items:center;justify-content:center} + .armix-audio-shade[hidden]{display:none} + .armix-audio-dialog{background:#142631;border:1px solid #467083;border-radius:8px; + box-shadow:0 16px 56px #0009;color:#e3eff4;width:min(480px,94vw); + padding:17px;display:grid;gap:11px;font:12px system-ui,sans-serif} + .armix-audio-dialog h2{font-size:14px;font-weight:600;margin:0} + .armix-audio-top{display:flex;align-items:center;justify-content:space-between;gap:10px} + .armix-audio-dialog .armix-floating-close{display:flex;align-items:center;justify-content:center; + width:29px;height:29px;min-height:29px;padding:0;border-radius:3px;flex:0 0 29px} + .armix-audio-dialog .armix-floating-close:active{background:#a42e3d;border-color:#e75f65;color:#fff} + .armix-floating-close svg{width:20px;height:20px;display:block;pointer-events:none} + .armix-audio-dialog label{display:grid;gap:5px;color:#a9c5d2} + .armix-audio-dialog select{background:#09202c;border:1px solid #476778; + border-radius:4px;color:#edf9ff;min-height:30px;width:100%;padding:3px 7px} + .armix-audio-dialog button{background:#244254;border:1px solid #557b8d; + border-radius:4px;color:#e9f8ff;min-height:30px;padding:4px 12px} + .armix-audio-dialog button:disabled{opacity:.45} + .armix-audio-dialog .armix-device-actions{display:flex;gap:8px;justify-content:flex-end} + .armix-audio-dialog .armix-device-note{color:#a4c4d0;line-height:1.4} + .armix-audio-dialog details{border-top:1px solid #345666;padding-top:8px} + .armix-audio-dialog summary{cursor:pointer;color:#c5e1ed} + .armix-audio-pins{display:grid;grid-template-columns:1fr 1fr;gap:8px; + max-height:135px;overflow:auto;padding:5px 0} + .armix-audio-pins label{display:flex;align-items:center;gap:5px;font-size:11px} + `; + document.head.appendChild(style); + devicePanel=document.createElement("div"); + devicePanel.className="armix-audio-shade"; + devicePanel.innerHTML=``; + devicePanel.querySelector("[data-audio-close]").onclick=()=>{ + devicePanel.hidden=true; + }; + devicePanel.addEventListener("click",e=>{ + if(e.target===devicePanel)devicePanel.hidden=true; + }); + devicePanel.addEventListener("change",e=>{ + if(!deviceChoice)return; + offeredPinRemap=null; + deviceResult=""; + const pinSide=e.target.dataset.audioPin; + if(pinSide==="input"||pinSide==="output"){ + const index=Number(e.target.dataset.pinIndex); + const key=pinSide==="input"?"inputPins":"outputPins"; + if(!Number.isInteger(index)||!Array.isArray(deviceChoice[key]))return; + const next=new Set(deviceChoice[key]); + if(e.target.checked)next.add(index);else next.delete(index); + deviceChoice[key]=[...next].sort((a,b)=>a-b); + renderDevicePanel();return; + } + const field=e.target.dataset.audioField; + if(!field)return; + if(field==="backend"){ + deviceChoice.backend=e.target.value; + const t=deviceInventory?.types?.find(x=>x.name===deviceChoice.backend); + deviceChoice.capture=t?.inputs?.[0]||""; + deviceChoice.playback=t?.separate?t?.outputs?.[0]||"":deviceChoice.capture; + deviceChoice.inputPins=null;deviceChoice.outputPins=null; + deviceChoice.rate=0;deviceChoice.buffer=0; + }else if(field==="capture"){ + deviceChoice.capture=e.target.value; + const t=deviceInventory?.types?.find(x=>x.name===deviceChoice.backend); + if(t&&!t.separate)deviceChoice.playback=e.target.value; + deviceChoice.inputPins=null;deviceChoice.outputPins=null; + }else if(field==="playback"){ + deviceChoice.playback=e.target.value; + deviceChoice.inputPins=null;deviceChoice.outputPins=null; + }else if(field==="rate")deviceChoice.rate=Number(e.target.value)||0; + else if(field==="buffer")deviceChoice.buffer=Number(e.target.value)||0; + renderDevicePanel(); + }); + devicePanel.querySelector("[data-audio-apply]").onclick=()=>{ + if(deviceBusy||pendingDeviceMute||!deviceChoice||!deviceInventory?.active)return; + const draft=deviceChoice,active=deviceInventory.active; + if(!draft.backend||!draft.capture||!draft.playback)return; + if(hardware?.device?.outputArmed){ + // Correlate one deliberate MUTE to this Apply. An unrelated ACK + // must never authorize a hardware switch. + const requestId="device-mute-"+(++deviceRequest); + pendingDeviceMute={requestId,epoch:String(hardware.device.epoch)}; + devicePanel.querySelector("[data-audio-apply]").disabled=true; + devicePanel.querySelector("[data-audio-active]").textContent= + "Muting current output before changing driver…"; + backend.emitEvent("arMixAction",{action:"monitor",value:false,requestId}); + window.setTimeout(()=>{ + if(pendingDeviceMute?.requestId!==requestId)return; + pendingDeviceMute=null; + deviceResult="Driver change cancelled: no verified MUTE acknowledgement."; + renderDevicePanel(); + },8000); + }else sendDeviceApply(); + }; + devicePanel.querySelector("[data-audio-remap]").onclick=()=>{ + if(!deviceBusy && !pendingDeviceMute && offeredPinRemap!==null && + !hardware?.device?.outputArmed) + sendDeviceApply(true); + }; + document.body.appendChild(devicePanel); + } + devicePanel.hidden=false; + const active=devicePanel.querySelector("[data-audio-active]"); + deviceResult=""; + offeredPinRemap=null; + if(active)active.textContent="Reading verified audio devices…"; + backend.emitEvent("arMixAction",{action:"audioDeviceInventory"}); + } + function fillAudioSelect(name,values,current){ + const el=devicePanel?.querySelector('[data-audio-field="'+name+'"]'); + if(!el)return; + el.replaceChildren(...values.map(value=>{ + const option=document.createElement("option"); + option.value=value;option.textContent=value;return option; + })); + if(values.includes(current))el.value=current; + el.disabled=deviceBusy; + } + function renderDevicePanel(){ + if(!devicePanel||devicePanel.hidden||!deviceInventory)return; + const active=deviceInventory.active||{},types=deviceInventory.types||[]; + if(!deviceChoice){ + const backendName=active.backend||types[0]?.name||""; + const selected=types.find(x=>x.name===backendName); + const capture=active.captureDevice||selected?.inputs?.[0]||""; + deviceChoice={backend:backendName,capture, + playback:active.playbackDevice|| + (selected?.separate?selected?.outputs?.[0]:capture)||"", + inputPins:Array.isArray(active.enabledInputs)?active.enabledInputs.slice():null, + outputPins:Array.isArray(active.enabledOutputs)?active.enabledOutputs.slice():null, + rate:0,buffer:0}; + } + const t=types.find(x=>x.name===deviceChoice.backend); + const asio4allHint=devicePanel.querySelector("[data-audio-asio4all-hint]"); + if(asio4allHint)asio4allHint.hidden=!( + deviceChoice.backend==="ASIO"&&/asio4all/i.test(deviceChoice.capture)); + fillAudioSelect("backend",types.map(x=>x.name),deviceChoice.backend); + fillAudioSelect("capture",t?.inputs||[],deviceChoice.capture); + fillAudioSelect("playback",t?.outputs||[],deviceChoice.playback); + const same=active.open&&active.backend===deviceChoice.backend&& + active.captureDevice===deviceChoice.capture&& + active.playbackDevice===deviceChoice.playback; + const rates=same?active.rates||[]:[]; + const buffers=same?active.buffers||[]:[]; + fillAudioSelect("rate",["0",...rates.map(String)],String(deviceChoice.rate||0)); + fillAudioSelect("buffer",["0",...buffers.map(String)],String(deviceChoice.buffer||0)); + const rateSelect=devicePanel.querySelector('[data-audio-field="rate"]'); + const bufferSelect=devicePanel.querySelector('[data-audio-field="buffer"]'); + if(rateSelect){rateSelect.options[0].textContent="Driver default";rateSelect.disabled=!same||deviceBusy;} + if(bufferSelect){bufferSelect.options[0].textContent="Driver default";bufferSelect.disabled=!same||deviceBusy;} + const pins=document.querySelector(".armix-audio-dialog [data-audio-pins]"); + if(pins){ + pins.replaceChildren(); + if(same){ + const container=document.createElement("div"); + container.className="armix-audio-pins"; + for(const [side,names,key,enabled] of [ + ["input",active.inputNames,"inputPins",active.enabledInputs], + ["output",active.outputNames,"outputPins",active.enabledOutputs]]){ + const group=document.createElement("div"); + const title=document.createElement("strong"); + title.textContent=side==="input"?"Capture pins":"Playback pins"; + group.appendChild(title); + (names||[]).forEach((name,index)=>{ + const label=document.createElement("label"); + const control=document.createElement("input"); + control.type="checkbox";control.dataset.audioPin=side; + control.dataset.pinIndex=String(index); + control.checked=(deviceChoice[key]||enabled||[]).includes(index); + control.disabled=deviceBusy; + label.append(control,document.createTextNode(String(name))); + group.appendChild(label); + }); + container.appendChild(group); + } + pins.appendChild(container); + }else pins.textContent="Apply this device first to inspect its real enabled pins."; + } + const activeText=devicePanel.querySelector("[data-audio-active]"); + if(activeText && !deviceBusy)activeText.textContent=deviceResult||(active.open? + "ACTIVE · "+active.backend+" · "+active.rate+" Hz / "+active.buffer+" samples": + "No verified audio device. Select a supported input and output."); + devicePanel.querySelector("[data-audio-apply]").disabled=deviceBusy|| + !!pendingDeviceMute||!deviceChoice.backend||!deviceChoice.capture|| + !deviceChoice.playback; + const remap=devicePanel.querySelector("[data-audio-remap]"); + remap.hidden=!same || offeredPinRemap!==active.deviceGeneration; + remap.disabled=deviceBusy || !!pendingDeviceMute; + remap.title="Reuse existing input and output pin numbers on the selected device. MONITOR stays off."; + } + function sendDeviceApply(confirmRetainedPinMapping=false){ + if(!deviceChoice||!deviceInventory?.active)return; + const c=deviceChoice,a=deviceInventory.active; + const same=a.open&&a.backend===c.backend&& + a.captureDevice===c.capture&&a.playbackDevice===c.playback; + if(confirmRetainedPinMapping && (!same || offeredPinRemap!==a.deviceGeneration))return; + deviceBusy=true; + const requestId="approved-io-"+(++deviceRequest); + devicePanel.dataset.pendingRequest=requestId; + devicePanel.querySelector("[data-audio-active]").textContent= + "Applying audio device; verifying native readback…"; + backend.emitEvent("arMixAction",{action:"audioDeviceApply", + requestId,expectedDeviceGeneration:Number(a.deviceGeneration), + config:{backend:c.backend,captureDevice:c.capture, + playbackDevice:c.playback, + sampleRate:confirmRetainedPinMapping?a.rate:same?c.rate:0, + bufferSize:confirmRetainedPinMapping?a.buffer:same?c.buffer:0, + enabledInputs:same?c.inputPins:[], + enabledOutputs:same?c.outputPins:[], + ...(confirmRetainedPinMapping?{confirmRetainedPinMapping:true}:{})}}); + } + if(connected){ + backend.addEventListener("arMixAudioDeviceInventory",inventory=>{ + if(!inventory||!Array.isArray(inventory.types))return; + deviceInventory=inventory; + if(!deviceBusy)deviceChoice=null; + renderDevicePanel(); + }); + backend.addEventListener("arMixAudioDeviceApplyAck",ack=>{ + if(!devicePanel||ack?.requestId!==devicePanel.dataset.pendingRequest)return; + deviceBusy=false; + if(ack.active)deviceInventory.active=ack.active; + offeredPinRemap=ack.state==="NEEDS_REMAP" && ack.canReusePins===true && + ack.active?.open===true && ack.active?.authorized===true && + Number.isSafeInteger(ack.active.deviceGeneration)? + ack.active.deviceGeneration:null; + const accepted=ack.ok===true&&ack.state==="ACCEPTED_MUTED" && + ack.active?.open===true && ack.active?.authorized===true && + Array.isArray(ack.active.enabledInputs) && + ack.active.enabledInputs.length>0 && + Array.isArray(ack.active.enabledOutputs) && + ack.active.enabledOutputs.length>=2; + deviceResult=accepted? + (ack.mixerBound?"Mixer ready · MONITOR OFF":"Audio device ready · choose an IN on any channel"): + ack.state==="NEEDS_REMAP"? + "NEEDS REMAP · "+ack.error: + "Device rejected · "+(ack.error||"native hardware readback failed"); + deviceChoice=null; + if(accepted){ + devicePanel.hidden=true; + status("DEVICE READY · "+ack.active.backend+" · "+ + ack.active.rate+" Hz / "+ack.active.buffer+" samples · MONITOR OFF"); + nativeToast(ack.mixerBound?"Mixer ready · MONITOR OFF": + "Audio device connected · "+ack.active.backend+" · "+ack.active.rate+" Hz · choose channel IN"); + controller?.subscribe(); + }else renderDevicePanel(); + }); + } + function installFirstSoundMenu() { const menu=document.querySelector?.("#moreTools .more-tools-panel"); if(!menu || typeof document.createElement!=="function")return; @@ -240,11 +1709,13 @@ if(tag==="button")el.type="button"; return el; }; - const caption=item("span","more-tools-caption","REAL AUDIO · FIRST SOUND"); - const setup=item("button","tool","Audio Setup"); + const caption=item("span","more-tools-caption","AUDIO / SAFETY"); + const setup=item("button","tool","Audio I/O"); setup.addEventListener("click",()=>{ - backend.emitEvent("arMixAction",{action:"audioSetup"}); - status("NATIVE: select actual ASIO/WASAPI input + output in Audio Setup."); + // Reuse the EXISTING custom driver/endpoint pane. The stock JUCE + // selector is reserved for explicitly requested advanced recovery. + // Never create a second Audio Setup workflow from the More menu. + openNativeAudioIO(); }); inputSelect=item("select","toolbar-select",""); inputSelect.setAttribute("aria-label","JUCE physical input for CH1"); @@ -286,37 +1757,361 @@ }); hardwareNote=item("span","more-tools-caption","Device not initialized"); hardwareNote.style.whiteSpace="normal"; - menu.append(caption,setup,inputSelect,routeBtn,armBtn,muteBtn,hardwareNote); + // Everyday I/O remains in the one approved /preview/ mixer. Keep the + // raw JUCE selector as an explicitly advanced recovery tool only. + inputSelect.hidden=true;routeBtn.hidden=true;armBtn.hidden=true; + const advanced=document.createElement("details"); + advanced.className="arNativeAdvancedRecovery"; + const summary=item("summary","more-tools-caption","Advanced driver recovery"); + const driver=item("button","tool","Open JUCE driver recovery"); + driver.addEventListener("click",()=>{ + backend.emitEvent("arMixAction",{action:"audioSetup"}); + }); + advanced.append(summary,driver); + // First Sound P0: these are REAL JUCE diagnostic actions, not demo + // toggles. The marker snapshots the 5-second PRE-event counters and + // Windows RAM/process paging context from the existing 1 Hz control + // timer. No sampling or file I/O happens in the ASIO callback. + const healthTitle=item("span","more-tools-caption","AUDIO HEALTH"); + const mark=item("button","tool","Mark Crackle"); + mark.title="Capture 5s before an audible crackle, including Windows memory"; + mark.addEventListener("click",()=>{ + backend.emitEvent("arMixAction",{action:"diagnosticMark"}); + nativeToast("Audio glitch marked · pre-event counters and RAM saved"); + status("Crackle marker sent to JUCE diagnostics"); + }); + const report=item("button","tool","Copy Audio Report"); + report.title="Copy real JUCE timing / driver / memory evidence to clipboard"; + report.addEventListener("click",()=>{ + backend.emitEvent("arMixAction",{action:"copyDiagnosticReport"}); + status("Preparing JUCE audio diagnostic report on control thread"); + }); + backend.addEventListener("arMixDiagnosticReportCopied",ack=>{ + const bytes=Number(ack?.bytes); + if(Number.isFinite(bytes)&&bytes>0) + nativeToast("Audio report copied · paste into engineering chat"); + }); + // Native-only access to EXISTING JUCE Show storage, not browser scenes. + // ShowV2 is 10CH+4AUX; unsupported dynamic WIRE/GROUP is rejected by + // native capture rather than silently truncated. + const showHeading=item("span","more-tools-caption","STUDIO / VERIFIED SHOWS"); + const showSave=item("button","tool","Save Show"); + const showUpdate=item("button","tool","Save New Version"); + const showBrowse=item("button","tool","Browse Shows"); + const showSelect=item("select","toolbar-select",""); + const showRecall=item("button","tool","Recall Show"); + const showRecover=item("button","tool","Recover Last Good"); + const showNote=item("span","more-tools-caption", + "Verified Shows only · full dynamic-session autosave is not yet available"); + showNote.style.whiteSpace="normal"; + showSelect.setAttribute("aria-label","Saved native Show"); + showSelect.style.maxWidth="210px";showSelect.style.fontSize="11px"; + showSelect.hidden=true;showUpdate.hidden=true; + showRecall.hidden=true;showRecover.hidden=true; + const showUuid=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + let showBusy=false; + const showEntries=new Map(); + const showOption=(name,value)=>{ + const option=document.createElement("option"); + option.textContent=name;option.value=value;return option; + }; + function showControls(){ + const entry=showEntries.get(showSelect.value); + const muted=hardware?.device?.outputArmed===false && + hardware?.raw?.monitor!==true; + showSave.disabled=showBusy; + showBrowse.disabled=showBusy; + showUpdate.disabled=showBusy||!muted||!entry||entry.needsRecovery; + showRecall.disabled=showBusy||!muted||!entry||entry.needsRecovery; + showRecover.disabled=showBusy||!muted||!entry||!entry.hasPrevious; + } + function showRefresh(){ + showBusy=true;showControls(); + showNote.textContent="Browsing verified native Shows…"; + backend.emitEvent("arMixAction",{action:"routingDryShowList"}); + } + showSave.addEventListener("click",()=>{ + if(showBusy)return; + if(hardware?.device?.outputArmed!==false||hardware?.raw?.monitor===true){ + status("SHOW SAVE requires MUTED output");return; + } + showBusy=true;showControls(); + showNote.textContent="Capturing accepted routing and VST3 state…"; + backend.emitEvent("arMixAction",{action:"routingDryShowSave"}); + }); + showUpdate.addEventListener("click",()=>{ + const id=showSelect.value,entry=showEntries.get(id); + if(showBusy||!entry||entry.needsRecovery||!showUuid.test(id)|| + hardware?.device?.outputArmed!==false)return; + showBusy=true;showControls(); + showNote.textContent="Saving verified next generation · previous Show retained…"; + backend.emitEvent("arMixAction",{action:"routingDryShowSave",value:id}); + }); + showBrowse.addEventListener("click",()=>{if(!showBusy)showRefresh();}); + showSelect.addEventListener("change",showControls); + showRecall.addEventListener("click",()=>{ + const id=showSelect.value,entry=showEntries.get(id); + if(showBusy||!entry||entry.needsRecovery||!showUuid.test(id)|| + hardware?.device?.outputArmed!==false)return; + showBusy=true;showControls(); + showNote.textContent="Verifying Show / preparing native FX · output stays MUTED…"; + backend.emitEvent("arMixAction",{action:"routingDryShowRecall",value:id}); + }); + showRecover.addEventListener("click",()=>{ + const id=showSelect.value,entry=showEntries.get(id); + if(showBusy||!entry?.hasPrevious||!showUuid.test(id)|| + hardware?.device?.outputArmed!==false)return; + showBusy=true;showControls(); + showNote.textContent="Verifying previous generation · valid latest will NOT be overwritten…"; + backend.emitEvent("arMixAction",{action:"routingDryShowRecover",value:id}); + }); + backend.addEventListener("arMixNativeShowSaveAck",ack=>{ + showBusy=false;showControls(); + if(ack?.ok===true){ + status("SHOW SAVED · native verified state · OUTPUT MUTED"); + showRefresh(); + }else{ + showNote.textContent="Save rejected: "+String(ack?.error||"Native capture rejected"); + status(showNote.textContent); + } + }); + backend.addEventListener("arMixNativeShowListAck",ack=>{ + showBusy=false;showEntries.clear(); + showSelect.replaceChildren(showOption("Choose verified Show…","")); + if(ack?.ok===true&&Array.isArray(ack.items)){ + for(const entry of ack.items.slice(0,64)){ + if(!showUuid.test(entry?.id))continue; + showEntries.set(entry.id,{ + hasPrevious:entry.hasPrevious===true, + needsRecovery:entry.needsRecovery===true + }); + showSelect.append(showOption( + String(entry.name||"Saved Show")+(entry.needsRecovery?" · RECOVERY":""), + entry.id)); + } + } + showSelect.hidden=false;showUpdate.hidden=false; + showRecall.hidden=false;showRecover.hidden=false; + showNote.textContent=ack?.ok===true + ?showEntries.size+" saved Shows · mute output before recall/recovery" + :"Browse rejected: "+String(ack?.error||"Native storage unavailable"); + showControls(); + }); + backend.addEventListener("arMixNativeShowRecallAck",ack=>{ + showBusy=false;showControls(); + showNote.textContent=ack?.ok===true + ?"SHOW RESTORED · OUTPUT MUTED; verify physical pins before MONITOR ON" + :"Recall rejected: "+String(ack?.error||"Native route unchanged"); + if(ack?.ok===true)controller?.subscribe(); + status(showNote.textContent); + }); + backend.addEventListener("arMixNativeShowRecoverAck",ack=>{ + showBusy=false;showControls(); + if(ack?.ok===true){ + status("Last verified Show restored on disk · muted; recall explicitly"); + showRefresh(); + }else{ + showNote.textContent="Recovery rejected: "+String(ack?.error||"Previous generation invalid"); + status(showNote.textContent); + } + }); + + backend.addEventListener("arMixNativeSessionAck",ack=>{ + const save=ack?.operation==="SAVE"; + if(!save&&ack?.operation!=="OPEN")return; + if(ack.ok!==true){ + const error=String(ack.error||"Mixer file operation failed"); + status(error);nativeToast(error); + return; + } + const message=save?"Mixer saved as .smix":"Mixer opened"; + status(message);nativeToast(message); + if(!save)controller?.subscribe(); + }); + menu.append(caption,setup,muteBtn,hardwareNote, + healthTitle,mark,report,advanced, + showHeading,showSave,showBrowse,showSelect,showUpdate,showRecall,showRecover,showNote); + // Single discoverable AUDIO I/O button next to ordinary mixer tools. + // The existing More entry remains a shortcut to THIS SAME panel. + const toolbar=document.querySelector(".command-bar"); + if(toolbar && !toolbar.querySelector("[data-native-io]")){ + const firstTool=toolbar.firstElementChild; + for(const [caption,action,icon] of [ + ["Save","nativeMixerFileSave","mixer-save.svg"], + ["Open","nativeMixerFileOpen","mixer-open.svg"] + ]){ + const button=item("button","tool mixer-file-tool",caption); + button.type="button"; + button.title=caption+" mixer (.smix)"; + const image=document.createElement("img"); + image.src="assets/"+icon; + image.alt=""; + image.width=image.height=16; + button.prepend(image); + button.addEventListener("click",()=>backend.emitEvent("arMixAction",{action})); + toolbar.insertBefore(button,firstTool); + } + const io=item("button","tool","Audio I/O"); + io.dataset.nativeIo="true"; + io.title="Select ASIO/WASAPI driver and capture/playback device"; + io.addEventListener("click",openNativeAudioIO); + toolbar.insertBefore(io,document.getElementById("moreTools")); + const monitor=item("button","tool","Monitor Off"); + monitor.dataset.nativeMonitor="true"; + monitor.addEventListener("click",()=>{ + const armed=hardware?.device?.outputArmed===true; + if(!armed && (!deviceReady()|| + (mixerSession()?.authority!=="CHANNEL_ID"&&legacy()?.routeAccepted!==true)|| + virtualCableFeedbackPair())){ + status("MONITOR OFF · select real input and safe playback device"); + return; + } + const ep=safeNativeCounter(hardware?.device?.epoch), + rev=safeNativeCounter(mixerSession()?.authority==="CHANNEL_ID"? + mixerSession()?.routeRevision:legacy()?.routingRevision); + if(!armed&&(ep===null||rev===null))return; + backend.emitEvent("arMixAction",{action:"monitor",value:!armed, + requestId:"manual-monitor-"+(++m4RequestSerial), + ...(armed?{}:{expectedEpoch:ep,expectedRevision:rev})}); + status(armed?"Hardware MUTE requested":"MAIN monitor verifying hardware route"); + }); + toolbar.insertBefore(monitor,io); + } updateHardwarePanel(hardware); } + // One control-thread routing transaction at a time, but NEVER lock other + // dropdowns or lose their choices. Latest choice wins per channel. + function dispatchQueuedSource(){ + if(nativeUiSourcePending||pendingSourceQueue.size===0)return; + if(!deviceReady()){pendingSourceQueue.clear();return;} + const [channel,choice]=pendingSourceQueue.entries().next().value; + pendingSourceQueue.delete(channel); + const ep=safeNativeCounter(hardware?.device?.epoch), + rev=safeNativeCounter(legacy()?.routingRevision); + if(ep===null||rev===null)return; + const requestId=++sourceSerial; + nativeUiSourcePending={requestId,channel,choice,epoch:ep,revision:rev, + autoListen:legacy()?.routeAccepted!==true && + hardware?.device?.outputArmed!==true}; + backend.emitEvent("arMixAction",{action:"routingSourceSwitch", + requestId,channel,mode:choice.mode,left:choice.left,right:choice.right, + deviceEpoch:ep,revision:rev}); + window.setTimeout(()=>{ + if(nativeUiSourcePending?.requestId!==requestId)return; + nativeUiSourcePending=null; + status("CH "+(channel+1)+" INPUT timeout · native state preserved"); + controller.subscribe(); + },8000); + } function onNativeReadback(next) { + scope?.syncNativeWireGains?.([]); // flush accepted paint after pointer release + appearanceFromNative(next); updateHardwarePanel(next); + // The installed native SessionSnapshot selects exactly one UI authority. + const session=next?.raw?.mixerSession; + if(!session || session.deviceEpoch!==next.device.epoch) { + flags.acceptedGraphConnected=false; + status("NATIVE SESSION UNAVAILABLE · controls unchanged"); + return; + } + // Never paint unacknowledged controls; pending slider caps are kept + // separately by pendingFaderVisualDb while accepted telemetry continues. + // A pending scalar ACK is not a global snapshot gate. Only accepted producer + // data can update controls; independent meters and FX racks keep moving. + reconcileM4ControlReadback(next); + reconcileM4RackReadback(next); + if(session.authority==="M4" && m4Verified()) { + paintM4Fallback(next); + scope?.syncVerifiedM4Wires?.(session.channels.map(ch=>ch.source),m4TrackIds); + } + // A second channel's IN can be selected while the first transaction is + // in flight. Always dispatch its latest choice with a FRESH native route + // revision, not stale tokens captured before the previous ACK. + if(!nativeUiSourcePending && pendingSourceQueue.size) + window.queueMicrotask(()=>dispatchQueuedSource()); const caps=next?.graph?.capabilities; - const nativeAdmitted=next.admitted && caps?.callbackOwnsChannelIds===true; + const nativeAdmitted=session.authority==="CHANNEL_ID" && + next.admitted && caps?.callbackOwnsChannelIds===true; + const addBus=document.getElementById("addBus"); + if(addBus){ + addBus.hidden=!nativeAdmitted || + !caps?.supportedOps?.includes("CREATE_GROUP"); + addBus.disabled=!!pendingBusCreate; + } + if (nativeAdmitted && !activeNativeSource && pendingNativeSources.size) { + // A rejected/timeout source command may leave the graph revision + // unchanged. Drain the next distinct channel after this authoritative + // snapshot even if the GUI signature is otherwise identical. + window.queueMicrotask(dispatchNativeSource); + } + if (next.retained && !nativeAdmitted) { + flags.productionCallbackLive=false;flags.acceptedGraphConnected=false; + pendingNativeSources.clear();pendingSourceQueue.clear(); + activeNativeSource=null;nativeUiSourcePending=null; + pendingOutputPatch=null;pendingNativeFxPower=null;pendingBusCreate=null; + pendingFxInsert=null;startupWire=null;activeWireAttempt=null; + pendingWireGains.clear();pendingNativeControl.clear();liveFaderVisualTargets.clear(); + const signature="retained|"+next.identity+"|"+appearanceRevision; + if(lastPaintedSignature!==signature && projectNativeGraphWithoutFocusLoss(next)) + lastPaintedSignature=signature; + stopDemo(); + paintNativeMeters(next); + status("NEEDS REMAP · mixer retained · output muted"); + return; + } if (!nativeAdmitted) { flags.productionCallbackLive=false;flags.acceptedGraphConnected=false; - lastPaintedSignature=""; + lastPaintedSignature="";lastNativeTopologySignature=""; stopDemo(); - status("NATIVE G0 · PATCH CH1/ARM tersedia pada device terverifikasi; kontrol ChannelId/WIRE menunggu PCM native."); + status(m4Verified()? + "NATIVE M4 · real PCM faders and meters · ChannelId buses not yet admitted": + deviceReady()? + "NATIVE G0 · verified physical IN ready · select a channel input": + hardware?.device?.enabledInputs?.length===0? + "NO CAPTURE PINS · Audio I/O: enable an actual hardware input": + "NATIVE G0 NOT READY · open Audio I/O and verify device / native route"); return; } // Control readback may change at the SAME structural graph revision. // Compare the actual accepted controls/edges, never skip native fader updates. const signature=next.identity+"|"+JSON.stringify(next.graph.channels.map(ch=>[ - ch.id,ch.controls,ch.inserts,ch.primaryOutId]))+"|"+JSON.stringify(next.graph.edges); + ch.id,ch.controls,ch.inserts,ch.fxRackBypassed,ch.primaryOutId]))+"|"+JSON.stringify(next.graph.edges)+"|"+appearanceRevision; if (signature===lastPaintedSignature) { // Telemetry often advances without a structural graph revision. paintNativeMeters(next); + if(startupWire)window.queueMicrotask(flushStartupWire); return; } - if (!projection(next)) { + if (!projectNativeGraphWithoutFocusLoss(next)) { flags.acceptedGraphConnected=false;flags.productionCallbackLive=false; stopDemo();status("NATIVE READBACK INVALID · existing GUI controls unchanged"); return; } flags.productionCallbackLive=next.productLive;flags.acceptedGraphConnected=true; + syncMonitorButton(next.device); lastPaintedSignature=signature;stopDemo();paintNativeMeters(next); + if(pendingFxInsert?.authority==="CHANNEL_ID"){ + const p=pendingFxInsert; + const inserted=next.graph.channels.find(ch=>ch.id===p.channelId) + ?.inserts?.[p.slot]; + // The selected catalog key is NOT the live VST3 instance token. + // Match catalog against catalog, while requiring a real processor ID. + if(inserted?.catalogId===p.id && + typeof inserted.id==="string" && inserted.id.length>0){ + pendingFxInsert=null; + scope?.closeNativePicker?.(); + status("VST3 loaded · "+inserted.name+" · native PCM readback verified"); + } + } + if(pendingNativeFxPower?.acked){ + const p=pendingNativeFxPower; + const ch=next.graph.channels.find(x=>x.id===p.channelId); + const actual=p.kind==="rack"?ch?.fxRackBypassed: + ch?.inserts?.find(x=>x.id===p.insertId)?.bypassed; + if(actual===p.bypassed)pendingNativeFxPower=null; + } + if(startupWire)window.queueMicrotask(flushStartupWire); status((next.productLive?"NATIVE PRODUCT LIVE":"NATIVE PCM GRAPH ACCEPTED · FAT PENDING")+ " · device "+next.device.epoch+ " · graph "+next.graph.revision+" · roster "+next.graph.rosterRevision); @@ -328,13 +2123,48 @@ onStatus:state=>{ if(state.lastError==="PENDING_NATIVE_ACK"||state.lastError==="PENDING_ACCEPTED_SNAPSHOT") status("NATIVE "+state.lastError+" · awaiting authoritative readback"); - else if(state.lastError!=="ACCEPTED_READBACK"&&state.lastError!=="NONE"&& - state.lastError!=="NATIVE_NOT_SUBSCRIBED") { + if(!state.pending && state.lastError==="ACCEPTED_READBACK" && + pendingNativeControl.size)queueLiveControlFlush(); + if(!state.pending&&state.lastError==="ACCEPTED_READBACK"&&pendingWireGains.size) + queueWireGainFlush(); + // Rejection cleanup and native rollback must BOTH run. + // Former else-if was unreachable after the cleanup branch matched. + const failed=!state.pending && + state.lastError!=="ACCEPTED_READBACK" && + state.lastError!=="NONE" && + state.lastError!=="NATIVE_NOT_SUBSCRIBED"; + if(!state.pending&&state.lastError==="ACCEPTED_READBACK"&&startupWire) + window.queueMicrotask(flushStartupWire); + if(!state.pending&&state.lastError==="ACCEPTED_READBACK")activeWireAttempt=null; + if(failed&&startupWire?.retries===1&& + ["STALE_NATIVE_CONTROL_REVISION","STALE_NATIVE_WIRE_GRAPH"].includes(state.lastError)) { + window.queueMicrotask(flushStartupWire);return; + } + if(failed){ + const wire=activeWireAttempt;activeWireAttempt=null; + // One stale-revision rebase of a new connection only. A fresh + // independent snapshot must still prove device/endpoints. Never + // replay retarget/remove, a changed epoch, or a rejected cycle. + if(wire&&wire.retries===0&& + ["STALE_NATIVE_CONTROL_REVISION","STALE_NATIVE_WIRE_GRAPH"].includes(state.lastError)&& + state.current?.device?.epoch===wire.epoch&&deferStartupWire(wire.ops,1))return; + startupWire=null; + pendingWireGains.clear(); + if(pendingFxInsert?.authority==="CHANNEL_ID"){ + pendingFxInsert=null; + nativeToast("VST3 insert rejected · "+state.lastError); + } + for(const [key,edit] of pendingNativeControl) + if(edit.authority==="CHANNEL_ID")pendingNativeControl.delete(key); + for(const [key,edit] of liveFaderVisualTargets) + if(edit.authority==="CHANNEL_ID")liveFaderVisualTargets.delete(key); lastNativeError=state.lastError; - // Native REJECTED / STALE / timeout must roll back a temporary fader - // cap and every input value; no optimistic GUI state survives. - if (!state.pending && flags.acceptedGraphConnected && scope?.render) { - scope.render(); + // Never destroy an active pointer capture. Once the user releases, + // restore only the last independently accepted native controls. + if(flags.acceptedGraphConnected && (scope.activeFaderId??-1)<0){ + if(!scope.wireGainDragging && !document.activeElement?.matches?.(".strip select,.wire-gain")) + scope.render?.(); + controller.subscribe(); if(state.current)paintNativeMeters(state.current); } } @@ -349,7 +2179,92 @@ finally{profiler.sample("nativeSnapshotJsMs",performance.now()-started);} }); backend.addEventListener("arMixConsoleAck", ack=>controller.onAck(ack)); + backend.addEventListener("arMixChannelIdentityAck", ack=>{ + if(!pendingIdentity||ack?.requestId!==pendingIdentity.requestId)return; + if(ack.ok!==true){ + if(pendingIdentity.migration)legacyDeferred.add(pendingIdentity.channelId); + rejectIdentity("Native channel identity rejected · "+String(ack.error||"Unknown error")); + controller?.subscribe();return; + } + pendingIdentity.acked=true; + controller?.subscribe(); + }); + backend.addEventListener("arMixNativeSourceAck",ack=>{ + if(!activeNativeSource||activeNativeSource.requestId!==ack?.requestId)return; + activeNativeSource=null; + if(ack.ok!==true) + nativeToast("Native input rejected · "+(ack?.error||"stale PCM")); + else status("Native input accepted · checking subsequent PCM readback"); + controller?.subscribe(); + }); + backend.addEventListener("arMixNativeBusAck",ack=>{ + if(!pendingBusCreate||pendingBusCreate.requestId!==ack?.requestId)return; + pendingBusCreate=null; + if(ack.ok===true && typeof ack.createdId==="string" && + /^[1-9]\d*$/.test(ack.createdId)) + status("BUS accepted by native PCM · verifying later graph readback"); + else nativeToast("Add BUS rejected · "+(ack?.error||"native graph error")); + controller?.subscribe(); + }); + backend.addEventListener("arMixNativeFxPowerAck",ack=>{ + const p=pendingNativeFxPower; + if(!p||ack?.requestId!==p.requestId)return; + if(ack?.ok!==true || ack?.channelId!==p.channelId || + ack?.bypassed!==p.bypassed){ + pendingNativeFxPower=null; + status("NATIVE FX rejected · "+(ack?.error||"stale epoch or insert")); + }else p.acked=true; + controller.subscribe(); // ACK is not independently observed PCM state + }); + backend.addEventListener("arMixRoutingFxRackAck",ack=>{ + const p=pendingM4RackPowers.get(ack?.channel); + if(!p||ack?.requestId!==p.requestId)return; + if(ack?.ok!==true || String(ack.deviceEpoch)!==p.epoch || + String(ack.routingRevision)!==p.revision || + ack.bypassed!==p.bypassed){ + pendingM4RackPowers.delete(p.channel); + status("Native M4 rack gate rejected · "+(ack?.error||"stale route")); + }else p.acked=true; + controller.subscribe(); // later authoritative M4 snapshot required + }); backend.addEventListener("arMixSourceSwitchAck", ack=>{ + if(nativeUiSourcePending && + ack?.requestId===nativeUiSourcePending.requestId) { + const p=nativeUiSourcePending; + nativeUiSourcePending=null; + const next=ack?.state||{},row=next.acceptedRoute?.channels?.[p.channel]; + const verified=ack.ok===true && next.ready===true && + Number(next.epoch)===p.epoch && next.hasAcceptedRoute===true && + Number(next.revision)>=p.revision && + row?.mode===p.choice.mode && row?.left===p.choice.left && + row?.right===p.choice.right; + if(verified) { + // Native publisher + engine own the accepted graph; refresh the + // UI only from a subsequent authoritative snapshot. + controller.subscribe(); + const firstListen=p.autoListen && row?.main===true && + (next.nativeChannelIdPcmActive===true || + (Array.isArray(next.channelControls)&&next.channelControls.length===10)) && + hardware?.device?.epoch===String(p.epoch); + // Never arm physical audio when the GUI still lacks admitted PCM + // controls, or when capture and playback feed the *same* VB Cable. + // Native C++ enforces the feedback policy a second time. + if(firstListen && !virtualCableFeedbackPair()) { + backend.emitEvent("arMixAction",{action:"monitor",value:true, + expectedEpoch:p.epoch,expectedRevision:Number(next.revision)}); + } + if(firstListen && virtualCableFeedbackPair()) + status("MONITOR OFF · VB-Cable feedback loop; select physical playback"); + else if(p.autoListen && !firstListen) + status("CH "+(p.channel+1)+" routed · PCM controls not yet admitted; MONITOR OFF"); + else + status("CH "+(p.channel+1)+" native input accepted"); + } else { + status("NATIVE INPUT REJECTED · "+(ack?.error||"stale routing")); + controller.subscribe(); + } + return; + } if(!pendingSourceId||ack?.requestId!==pendingSourceId)return; pendingSourceId=0; if(ack.ok===true) { @@ -358,7 +2273,131 @@ }else status("NATIVE PATCH REJECTED: "+(ack?.error||"stale physical route")); updateHardwarePanel(hardware); }); + backend.addEventListener("arMixM4ControlAck",ack=>{ + const item=[...pendingM4Controls].find(([,p])=>p.requestId===ack?.requestId); + if(!item)return; // late, unrelated and superseded ACKs cannot commit + const [key,p]=item; + const accepted=ack.ok===true && + String(ack.deviceEpoch)===p.epoch && + String(ack.routingRevision)===p.revision && + ack.channel===p.channel && ack.parameter===p.parameter; + if(!accepted) { + pendingM4Controls.delete(key); + if(p.parameter==="masterGain")liveFaderVisualTargets.delete("masterGain:main"); + else if(p.parameter==="faderDb") + liveFaderVisualTargets.delete("faderDb:"+m4TrackIds[p.channel]); + status("NATIVE M4 REJECTED · "+(ack?.error||"stale control token")); + } else p.acked=true; + controller.subscribe(); // request later independent producer readback + }); + backend.addEventListener("arMixChannelPatchAck",ack=>{ + if(!pendingOutputPatch||ack?.requestId!==pendingOutputPatch.requestId)return; + const p=pendingOutputPatch; + pendingOutputPatch=null; + const t=scope?.tracks?.find(x=>m4Index(x)===p.channel); + const el=t?document.querySelector( + '.strip[data-id="'+t.id+'"] select[data-field="output"]'):null; + if(el){ + el.removeAttribute("aria-busy"); + el.title="Primary output · verified native routing"; + } + const row=ack?.state?.acceptedRoute?.channels?.[p.channel]; + const accepted=ack?.ok===true && Number(ack.state?.epoch)===p.epoch && + (p.operation==="SET_PROCESSING_FORMAT"? + row?.channelFormat===p.target: + row?.main===(p.target==="MAIN")); + if(accepted) { + if(el&&p.operation==="SET_PRIMARY_OUT") + el.value=p.target==="MAIN"?"Master":"SOURCE ONLY (No Main)"; + status("CH "+(p.channel+1)+" "+ + (p.operation==="SET_PROCESSING_FORMAT"?"M/ST ":"OUT ")+p.target+ + " accepted · verifying native PCM"); + } else { + if(el)el.value=t?.output||"Master"; + status("CH "+(p.channel+1)+" "+ + (p.operation==="SET_PROCESSING_FORMAT"?"M/ST":"OUT")+ + " rejected · "+(ack?.error||"stale route")); + nativeToast(ack?.error||"Native channel route rejected"); + } + controller.subscribe(); + }); + backend.addEventListener("arMixRoutingFxBypassAck",ack=>{ + const key=(Number(ack?.channel)||0)+":"+Number(ack?.slot); + // Legacy ACKs without channel/requestId can never authorize an + // arbitrary in-flight slot or paint an invented bypass state. + const pending=pendingSlotPowers.get(key); + if(!pending||pending.requestId!==ack?.requestId)return; + pendingSlotPowers.delete(key); + if(ack?.ok!==true) + nativeToast(ack?.error||"Native VST3 bypass rejected"); + controller?.subscribe(); // real FxInstance state owns visual power + }); + backend.addEventListener("arMixRoutingFxEditorAck",ack=>{ + if(ack?.ok!==true) + nativeToast(ack?.error||"VST3 editor could not open"); + else status("Native VST3 editor opened"); + }); + backend.addEventListener("arMixRoutingFxInsertAck",ack=>{ + if(!pendingFxInsert||pendingFxInsert.authority==="CHANNEL_ID"|| + ack?.requestId!==pendingFxInsert.requestId)return; + const p=pendingFxInsert;pendingFxInsert=null; + const actual=ack?.state?.fxInstances?.[p.channel]?.[p.slot]; + if(ack?.ok===true && actual?.catalogId===p.id && + typeof actual?.instanceId==="string"&&actual.instanceId.length){ + status("CH "+(p.channel+1)+" FX loaded · verified native VST3"); + scope?.closeNativePicker?.(); + scope?.setNativeCatalog?.([...nativeCatalog.values()]); + controller.subscribe(); + }else { + const reason=ack?.error||"native FX instance missing from accepted PCM"; + status("FX INSERT REJECTED · "+reason); + nativeToast(reason); + controller.subscribe(); + } + }); + backend.addEventListener("arMixCatalog",catalog=>{ + if(!Array.isArray(catalog?.items))return; + nativeFxCatalogScanning=catalog.scanning===true; + nativeCatalog=new Map(catalog.items.filter(p=> + p&&typeof p.id==="string"&&p.id.length>0&& + typeof p.name==="string"&&p.name.length>0).map(p=>[p.id,p])); + scope?.setNativeCatalog?.([...nativeCatalog.values()]); + if(nativeFxDiscoveryRequested&&!nativeFxCatalogScanning&&nativeCatalog.size===0) + status("No installed VST3 discovered · use Import VST3 in Plugin Manager"); + if(hardware?.raw?.legacyM4)paintM4FxInstances(hardware.raw.legacyM4); + const count=document.getElementById("pluginCount"); + if(count)count.title="Verified JUCE native VST3 catalog"; + }); + backend.addEventListener("arMixScanProgress",progress=>{ + const statusEl=document.getElementById("pluginScanStatus"); + if(statusEl)statusEl.textContent=progress?.active? + "Scanning real VST3… "+(progress.done||0)+"/"+(progress.total||"…"): + "Native VST3 scan finished; results from JUCE catalog"; + }); + backend.addEventListener("arMixNotice",notice=>{ + // ConsoleWindow::emitNotice publishes {text,error}, never {message}. + // The mismatched field hid native VST3 layout/latency, driver and + // routing failures behind rapid meter/readback status updates. + const message=notice?.text; + if(notice?.error===true && typeof message==="string" && message.length){ + nativeToast(message); // physical FX/driver failures remain visible + status("JUCE · "+message); + } + }); backend.addEventListener("arMixAudioArmAck", ack=>{ + if(pendingDeviceMute){ + // Reject any stale/unrelated ACK and any device epoch change. + if(ack?.requestId!==pendingDeviceMute.requestId)return; + const epochMatches=String(ack?.deviceEpoch)===pendingDeviceMute.epoch; + pendingDeviceMute=null; + if(ack?.ok===true && ack?.armed===false && epochMatches) + sendDeviceApply(); + else if(devicePanel){ + deviceResult="Device change rejected: MUTE or audio epoch not verified."; + renderDevicePanel(); + } + return; + } if(ack?.ok===true){ status(ack.armed?"NATIVE: user ARM accepted; checking real PCM.": "NATIVE: output muted."); @@ -368,16 +2407,134 @@ } const nativeHooks=Object.freeze({ enabled:connected, + inputChoices(t) { + if(t?.kind!=="audio")return ["None"]; + if(controller?.state()?.current?.retained)return [t.input||"None"]; + const choices=inputChoicesFor().map(x=>x.label); + // The native BUS lane is selectable only for display: never invent a + // hardware pin or promote the internal BUS to a writable physical IN. + if(t.input===INTERNAL_BUS)choices.push(INTERNAL_BUS); + return choices; + }, + outputChoices(t) { + if(t?.kind==="master") + return [hardware?.retained?NEEDS_REMAP: + String(hardware?.device?.playbackDevice||t.output||"Choose audio output")]; + if(t?.kind!=="master"){ + // M4 accepts MAIN or source-only. Bus routing is via native WIRE, + // never pretend the demo's other destinations have native PCM. + const options=["Master","SOURCE ONLY (No Main)"]; + const graph=controller?.state()?.current?.graph; + if(mixerSession()?.authority==="CHANNEL_ID"&&graph?.channels) + for(const target of nativeOutputTargets(t))options.push(target.label); + if(t.output&&!options.includes(t.output))options.push(t.output); + return options; + } + return [t?.output||"None"]; + }, consumeField(event) { if (!connected)return false; const el=event.target,field=el?.dataset?.field; if (!field)return false; const t=scope?.findTrack?.(el) || null; if (!t)return true; + if(controller?.state()?.current?.retained){ + if(field==="output" && t.kind==="master" && event.type==="change") + openNativeAudioIO(); + if(field==="level" || field==="pan" || field==="input" || field==="output") + el.value=String(t[field]); + return true; + } + if(field==="wireGain"){ + const edge=scope?.wireEdges?.find(e=>e.id===Number(el.dataset.wireId)&&e.destId===t.id); + if(!edge||!requestWireGain({sourceId:edge.sourceId,edgeId:edge.id,levelDb:Number(el.value)})) + status("WIRE gain unavailable · accepted parallel send required"); + else scope.paintWireKnob?.(el,Number(el.value)); + return true; + } + if(field==="input"){ + // Input selection is independent of Record Arm, transport START and + // ChannelId admission. A physical mixer strip can receive ANY active + // source, including the very first source in an unpatched session. + if(event.type!=="change")return true; + const channel=m4Index(t); + const choice=inputChoicesFor().find(x=>x.label===el.value); + // After BUS/WIRE the installed ChannelId graph is sole PCM owner. + // Original ten channels must not send source edits to stale M4. + if(mixerSession()?.authority==="CHANNEL_ID"){ + const current=controller?.state()?.current; + const id=nativeIdFor(t); + if(!choice||!id||!current?.admitted||!deviceReady()){ + nativeToast("Select a verified physical input"); + el.value=t.input;return true; + } + if(choice.label!==t.input){ + pendingNativeSources.set(id,choice); + dispatchNativeSource(); + } + el.value=t.input; // no optimistic browser patch + return true; + } + const ep=safeNativeCounter(hardware?.device?.epoch); + const rev=safeNativeCounter(legacy()?.routingRevision); + if(channel<0||channel>=10||!choice||!deviceReady()|| + ep===null||rev===null){ + status("INPUT REJECTED · refresh verified hardware pins"); + el.value=t.input;return true; + } + if(choice.label===t.input&&!pendingSourceQueue.has(channel)){ + el.value=t.input;return true; + } + pendingSourceQueue.set(channel,choice); + // No browser demo optimistic patch. The selector stays operable for + // every channel during a previous JUCE routing transaction. + el.value=t.input; + if(nativeUiSourcePending) + status("CH "+(channel+1)+" input queued behind native route ACK"); + else dispatchQueuedSource(); + return true; + } + if(field==="output"){ + if(event.type!=="change")return true; + if(t.kind==="master"){ + el.value=t.output;openNativeAudioIO();return true; + } + const graph=controller?.state()?.current?.graph; + const destination=nativeOutputTargets(t).find(ch=>ch.label===el.value); + const target=el.value==="Master"?"MAIN": + el.value==="SOURCE ONLY (No Main)"?"NONE": + destination?destination.label:null; + // No optimistic GUI state. Both this menu and the WIRE jack use + // the same ID/epoch-guarded, acknowledged native route transaction. + if(el.value!==t.output && !requestPrimaryOut(t,target)){ + el.value=t.output; + status("OUT unavailable · verify device, MAIN route and pending edit"); + } + // No instantaneous snap-back on a valid pending native transaction. + return true; + } + // ONE realtime PCM control for original ten channels and MAIN, + // regardless of whether the admitted ChannelId callback or M4 renders. + // <=33 commands/s/control while dragging; always flush on release. + if((field==="level"||field==="pan") && + liveScalarReady(field==="level"? + (t.kind==="master"?"masterGain":"faderDb"):"pan",t)){ + const numeric=Number(el.value); + if(!Number.isFinite(numeric))return true; + const normalized=field==="pan"? + previewNativePan(t,el,event):numeric; + if(normalized===null)return true; + const key=field==="level"? + (t.kind==="master"?"masterGain":"faderDb"):"pan"; + if(field==="level")previewFaderWithoutModelMutation(t,numeric); + if(!streamFaderControl(key,t,normalized,event.type==="change")) + status("LIVE PCM control rejected; checking route identity"); + return true; + } if (!flags.acceptedGraphConnected) { if (field==="level")el.value=String(t.level); else if (field==="pan")el.value=String(t.pan); - status("NATIVE: ChannelId PCM not admitted; control unchanged"); + status("LIVE PCM control unavailable · selected route not admitted"); return true; } // During a native pointer drag move the approved fader *cap* only. @@ -414,20 +2571,171 @@ consumeAction(t,action,btn) { if (!connected)return false; // Selection, WIRE inspection and section presentation are UI-only. - if (["wireExpand","wireSource","wireRoute","editIdentity","rename"].includes(action)) - return !["wireExpand","wireSource","wireRoute"].includes(action); + if(action==="editIdentity"||action==="rename"){ + // DAW convention: one click only selects/focuses this channel. + // The existing native consumeDoubleClick opens the identity editor; + // never open it from the click event preceding a double-click. + return true; + } + if (["wireExpand","wireSource","wireRoute"].includes(action)) + return false; + if(action==="removeFx") { + const slot=Number(btn?.dataset.slot),id=nativeIdFor(t),current=controller?.state()?.current; + const token=current?.graph?.channels.find(ch=>ch.id===id)?.inserts?.[slot]?.id; + editNativeFx(t,slot,null,0,token);return true; + } + if(action==="openPlugin"){ + if(mixerSession()?.authority==="CHANNEL_ID") { + const current=controller?.state()?.current,id=nativeIdFor(t),slot=Number(btn?.dataset.slot); + const insert=current?.graph?.channels.find(ch=>ch.id===id)?.inserts?.[slot]; + if(current?.admitted&&insert?.id&&Number.isInteger(slot)&&slot>=0&&slot<8) { + if(insert.catalogId==='armix.builtin.channel-eq.v1') { + window.ArSonMixNativeEq?.open(t,slot); + } else backend.emitEvent("arMixAction",{action:"routingFxEditor",channelId:id,slot, + instanceId:insert.id,deviceEpoch:current.device.epoch,revision:current.graph.revision}); + } else {discoverFxOnFirstPickerOpen();scope?.openFastPicker?.(t,slot,btn);} + return true; + } + const slot=Number(btn?.dataset.slot),instance=verifiedFxFor(t,slot); + if(instance){ + const ep=safeNativeCounter(hardware?.device?.epoch), + rev=safeNativeCounter(legacy()?.routingRevision); + if(ep!==null&&rev!==null) + backend.emitEvent("arMixAction",{action:"routingFxEditor", + channel:instance.lane,slot, + instanceId:instance.live.instanceId,deviceEpoch:ep,revision:rev}); + else nativeToast("VST3 editor · refresh native device and FX instance"); + }else { + discoverFxOnFirstPickerOpen(); + scope?.openFastPicker?.(t,slot,btn); + } + return true; + } + if(action==="slotPower"){ + if(mixerSession()?.authority==="CHANNEL_ID"){ + if(!requestAdmittedFxPower(t,action,btn)) + nativeToast("Native FX slot unavailable · accepted insert/epoch required"); + }else{ + const slot=Number(btn?.dataset.slot),instance=verifiedFxFor(t,slot); + if(!m4ControlIsOwner()||!instance|| + !requestNativeFxPower(t,slot,!instance.live.bypassed)) + nativeToast("FX bypass unavailable · select an accepted VST3 slot"); + } + return true; + } + if(action==="fxOn"){ + const authority=mixerSession()?.authority; + const ok=authority==="M4"?requestM4RackPower(t): + authority==="CHANNEL_ID"?requestAdmittedFxPower(t,action,btn):false; + if(!ok){ + nativeToast("FX header requires an accepted native rack gate"); + status("FX rack unchanged · native PCM authority or readback unavailable"); + } + return true; + } + if(action==="format"&&t?.kind==="audio"){ + requestProcessingFormat(t);return true; + } + if(action==="cue"){ + // PFL must use a separate physical pre-fader monitor bus; do not + // make a GUI-only toggle or mix a cue into audience MAIN. + nativeToast("PFL requires a separate MONITOR L/R pair; MAIN unchanged"); + status("PFL not armed · independent physical MONITOR output required"); + return true; + } if (action==="mute"||action==="solo") { + if((m4Verified()||nativeMasterReady()) && + t.kind==="master" && action==="mute"){ + if(!sendM4Control("masterMute",t,!t.mute)) + status("Native MAIN mute rejected"); + return true; + } + if(m4ControlIsOwner()&&m4Verified()&&m4Index(t)>=0){ + if(!sendM4Control(action,t,!t[action])) + status("Native M4 mute/solo rejected"); + return true; + } const key=action==="mute"?"SET_MUTE":"SET_SOLO"; intent(key,t,{value:!t[action],enabled:!t[action]});return true; } status("NATIVE: "+action+" is not an accepted ChannelId operation");return true; }, - consumeWire(ops) { + consumeWire(ops,retries=0) { if (!connected)return false; + const state=controller?.state(); + // A first drag may arrive before SOURCE's later accepted snapshot. + // Preserve that one operator intent; resolve only against fresh native + // identities, never require a hidden OUT-dropdown priming operation. + if((!flags.acceptedGraphConnected||!state?.current?.admitted||state.pending|| + activeNativeSource||nativeUiSourcePending||pendingNativeSources.size||pendingSourceQueue.size)&& + deferStartupWire(ops,retries))return true; + if(Array.isArray(ops)&&ops.length===1&&ops[0].type==="GAIN"){ + if(!requestWireGain(ops[0]))status("WIRE gain unavailable · accepted parallel send required"); + return true; + } + // Sends-on-faders creates a new send plus its initial gain atomically; + // its draft UI EdgeId must never be sent as an accepted native EdgeId. + if(Array.isArray(ops)&&ops.length===2&&ops[0].type==="CONNECT"&& + ops[1].type==="GAIN"&&ops[0].sourceId===ops[1].sourceId&& + !wireByUiId.has(ops[1].edgeId)&&Number.isFinite(ops[1].levelDb)) + ops=[{...ops[0],mode:"send",levelDb:ops[1].levelDb}]; const current=controller?.state().current; + // P0 first-sound WIRE to MAIN is the very same native M4 PRIMARY_OUT + // transaction as the ordinary OUT drop-down. Do not reject a real + // physical CH→MAIN connection merely because P1 dynamic BUS/WIRE + // transaction capability has not been admitted yet. + if(Array.isArray(ops)&&ops.length===1){ + const op=ops[0]; + const t=scope?.tracks?.find(x=>x.id===op.sourceId); + const sourceId=t?nativeByUiId.get(t.id):null; + // Ordinary MAIN jack is a primary ROUTE_ONLY. An explicitly selected + // send mode must pass through native CONNECT instead, preserving the + // old primary BUS (or the absence of a primary in SOURCE ONLY). + const isMainConnect=(op.type==="ROUTE_ONLY" || + (op.type==="CONNECT" && (!op.mode || + op.mode==="postFader" || op.mode==="routeOnly"))) && + op.destId===scope?.master?.id; + // WIRE gesture carries a UI edge id. wireByUiId is UI→native; + // uiByWireId is the inverse. The old inverse lookup always returned + // undefined, so unplugging an existing MAIN wire was impossible. + const edgeId=wireByUiId.get(op.edgeId); + const lane=m4Index(t); + const graphMainRemove=op.type==="REMOVE" && sourceId && + current?.admitted===true && + current.graph.edges.some(e=>e.enabled&&e.edgeId===edgeId&& + e.from===sourceId&&e.to===current.graph.mainChannelId&& + e.primaryOutput===true); + // The approved M4 renderer remains the accepted First Sound owner + // if ChannelId projection was not admitted. Verify BOTH an exact UI + // PRIMARY edge and the producer's real MAIN readback before removing. + // When native ChannelId *is* admitted, never replace its edge-token + // guard with an M4 label. No invented browser-only PCM or routing. + const m4MainRemove=op.type==="REMOVE" && current?.admitted!==true && + lane>=0 && m4Verified() && + legacy()?.channels?.[lane]?.main===true && + Array.isArray(scope?.wireEdges) && + scope.wireEdges.some(e=>e.enabled&&e.kind==="primary"&& + e.id===op.edgeId&&e.sourceId===op.sourceId&& + e.destId===scope?.master?.id); + const isMainRemove=graphMainRemove||m4MainRemove; + // Admitted new ChannelIds after CH10 have no M4 lane ordinal. + if(t&&(lane>=0||(current?.admitted===true&&sourceId))&& + (isMainConnect||isMainRemove)){ + const target=isMainRemove?"NONE":"MAIN"; + if(requestPrimaryOut(t,target)) + status(t.name+" WIRE → "+ + (target==="MAIN"?"MAIN":"SOURCE ONLY")+ + " · native ACK/readback required"); + else nativeToast("WIRE MAIN unavailable · verify channel and routing state"); + return true; // original Pages reducer never simulates native PCM + } + } if (!flags.acceptedGraphConnected || !current?.admitted || !current.graph.capabilities.supportedOps.includes("APPLY_WIRE_TRANSACTION")) { - status("NATIVE: WIRE transaction not admitted; graph unchanged");return true; + const reason="WIRE BUS/FX return is not admitted by the installed PCM graph"; + status("NATIVE: "+reason+" · no audio reroute"); + nativeToast(reason); + return true; } const changes=[]; for (const op of ops) { @@ -462,23 +2770,97 @@ return true; } const accepted=controller.intent("APPLY_WIRE_TRANSACTION",source,{changes}); + if(accepted.ok&&ops.length===1&&ops[0].type==="CONNECT") + activeWireAttempt={ops:ops.map(x=>({...x})),epoch:current.device.epoch,retries}; if (!accepted.ok)status("NATIVE: "+accepted.error+"; WIRE unchanged"); else window.setTimeout(()=>controller?.expire(accepted.requestId),8000); return true; }, consumeUndo() {if (!connected)return false;status("NATIVE: WIRE undo requires accepted native transaction");return true;}, + moveFx(sourceId,slot,destId,position,token){ + const all=[...(scope?.tracks||[]),scope?.master]; + const source=all.find(t=>t?.id===sourceId),dest=all.find(t=>t?.id===destId); + return !!source&&!!dest&&editNativeFx(source,slot,dest,position,token); + }, + nativeIdFor(t){return nativeIdFor(t);}, + insertPlugin(id,target){ + if(pendingFxInsert){status("FX INSERT · wait for previous native ACK");return true;} + const plugin=nativeCatalog.get(id) || + (id==='armix.builtin.channel-eq.v1'?{id,name:'Parametric EQ'}:null); + const track=scope?.tracks?.find(x=>x.id===target?.channelId)|| + (scope?.master?.id===target?.channelId?scope.master:null); + const channel=m4Index(track),slot=Number(target?.slot); + const accepted=controller?.state().current; + const nativeId=nativeIdFor(track); + const nativeCh=accepted?.graph?.channels?.find(ch=>ch.id===nativeId); + if(accepted?.admitted && nativeCh) { + if(!plugin || !["INPUT","GROUP","FX_RETURN","MAIN"].includes(nativeCh.role) || + !accepted.graph.capabilities.supportedOps.includes("LOAD_INSERT") || + !Number.isInteger(slot)||slot<0||slot>=8 || + !Array.isArray(nativeCh.inserts)||nativeCh.inserts.length!==slot){ + status("VST3 unavailable · select an empty native ChannelId FX slot"); + return true; + } + const request=controller.intent("LOAD_INSERT",nativeId, + {catalogId:id,slot}); + if(!request.ok){status("VST3 rejected · "+request.error);return true;} + pendingFxInsert={authority:"CHANNEL_ID",requestId:request.requestId, + id,channelId:nativeId,slot}; + status(track.name+" · preparing VST3 without stopping MAIN"); + window.setTimeout(()=>{ + if(pendingFxInsert?.requestId!==request.requestId)return; + pendingFxInsert=null; + status("Native VST3 timed out · accepted audio left unchanged"); + controller.subscribe(); + },15000); + return true; + } + const ep=safeNativeCounter(hardware?.device?.epoch); + const rev=safeNativeCounter(legacy()?.routingRevision); + const existing=legacy()?.fxInstances?.[channel]||[]; + if(!plugin||!m4Verified()||channel<0|| + !Number.isInteger(slot)||slot<0||slot>=8 || + ep===null||rev===null||existing[slot] || + (slot>0&&!existing[slot-1])){ + status("FX INSERT REJECTED · choose an empty consecutive slot on a native CH with verified route/catalog"); + return true; + } + const requestId="fx-"+(++fxRequestSerial); + pendingFxInsert={requestId,id,channel,slot}; + backend.emitEvent("arMixAction",{action:"routingFxInsert", + requestId,id,channel,slot,deviceEpoch:ep,revision:rev}); + status("CH "+(channel+1)+" · preparing real VST3, awaiting native ACK"); + window.setTimeout(()=>{ + if(pendingFxInsert?.requestId!==requestId)return; + pendingFxInsert=null; + status("FX INSERT timeout; accepted routing preserved"); + controller.subscribe(); + },15000); + return true; + }, consumeDoubleClick(event,t) { if (!connected)return false; - if (event.target.classList.contains("fader"))intent("SET_FADER",t,{valueDb:0}); - else if(event.target.classList.contains("center-pan"))intent("SET_PAN",t,{value:0}); - else status("NATIVE: identity editor unavailable until native ACK contract"); + if (event.target.classList.contains("fader")){ + if((m4ControlIsOwner()&&m4Verified()) || + (t?.kind==="master"&&(m4Verified()||nativeMasterReady()))) + sendM4Control(t?.kind==="master"?"masterGain":"faderDb",t,0); + else intent("SET_FADER",t,{valueDb:0}); + } + else if(event.target.classList.contains("center-pan")){ + if(m4ControlIsOwner()&&m4Verified())sendM4Control("pan",t,0); + else intent("SET_PAN",t,{value:0}); + } + else if(event.target.closest?.(".footer-label,.strip-identity-top")) + openNativeIdentity(t,event.target); return true; }, + applyIdentity:acceptIdentityPresentation, state:()=>controller?.state() || null }); window.__ARMIX_NATIVE_M2__ = nativeHooks; + window.ArSonFxRackAuthority=Object.freeze({move:(...args)=>nativeHooks.moveFx(...args)}); const descriptor = Object.freeze({ - source:"site/preview-v2 + site/preview-buttons", + source:"/preview/ approved compiled Pages GUI", pagesRoute:"/preview/", nativeTransport:connected, get acceptedGraphConnected(){return flags.acceptedGraphConnected;}, @@ -494,6 +2876,8 @@ // Presentation-only bank/selection remains available. document.addEventListener("pointerdown",event=>{ if (flags.acceptedGraphConnected) return; + const t=scope?.findTrack?.(event.target); + if(m4Verified() && (t?.kind==="audio"||t?.kind==="master"))return; if (!event.target.closest?.(".fader-box,.center-pan")) return; event.preventDefault();event.stopImmediatePropagation(); status("NATIVE G0: physical gain/pan unavailable until engine graph admission"); @@ -501,21 +2885,129 @@ // Reference-only buttons outside strips must not mutate fake Show/FX state. document.addEventListener("click",event=>{ const target=event.target.closest?.( - "#preview,#addTrack,#addBus,#addFx,#reset,#saveScene,#recallScene,#sceneSafe,#group,#ungroup,#copy,#paste,#clearCue,#pluginsButton,#pluginScan,#pluginImport,#pluginAddPath"); + "#preview,#addTrack,#addBus,#addFx,#reset,#saveScene,#recallScene,#sceneSafe,#group,#ungroup,#copy,#paste,#clearCue,#pluginScan,#pluginImport,#pluginAddPath"); if(!target)return; event.preventDefault();event.stopImmediatePropagation(); - status("NATIVE: "+target.id+" requires real engine admission and readback"); + const action=target.id==="pluginScan"?"scanVst3": + target.id==="pluginImport"?"importVst3": + target.id==="pluginAddPath"?"addScanFolder":null; + if(action){ + backend.emitEvent("arMixAction",{action}); + status("PLUGIN MANAGER · "+action+" requested from native JUCE"); + return; + } + if(target.id==="addBus"){ + requestNativeBusCreate();return; + } + status("NATIVE: "+target.id+" requires admitted engine operation"); },true); // Native fader is committed exactly once INSIDE the original GUI's // finishFaderPointer via build_approved_native_gui.py hook. A later // window.pointerup listener would run after that handler clears the gesture. + + // Editing is accessible without a mouse. F2 operates on the selected + // loaded channel; Enter/Space activates the focusable footer name. + document.addEventListener("keydown",event=>{ + if(!connected||event.altKey||event.ctrlKey||event.metaKey)return; + const target=event.target; + const editorHidden=Boolean(document.getElementById("channelIdentity")?.hidden); + const textEntry=target?.closest?.('input,textarea,select,[contenteditable="true"]'); + // Closing the editor can leave DOM focus on its now-hidden input under + // WebView2. F2 must still reopen the last selected channel, rather than + // being swallowed by the generic text-entry shortcut guard. + if(textEntry && !(event.key==="F2" && editorHidden && + target?.id==="identityName"))return; + const focused=target?.closest?.('.footer-label .name'); + if(focused && ["Enter"," "].includes(event.key)){ + const track=scope?.tracks?.concat(scope.master||[])?.find( + item=>item.id===Number(focused.closest(".strip")?.dataset.id)); + event.preventDefault();event.stopImmediatePropagation(); + openNativeIdentity(track,focused);return; + } + if(event.key!=="F2")return; + const tracks=scope?.tracks?.concat(scope.master||[])||[]; + const focusedTrack=target?.closest?.(".strip")?.dataset.id; + const selected=tracks.find(t=>t.id===Number(focusedTrack))|| + tracks.find(t=>t.selected && identityEligible(t))|| + tracks.find(t=>t.id===lastEditedChannelId && identityEligible(t)); + if(!selected)return; + event.preventDefault();event.stopImmediatePropagation(); + const anchor=document.querySelector('.strip[data-id="'+selected.id+'"] .footer-label')|| + document.querySelector('.strip[data-id="'+selected.id+'"] .strip-identity-top'); + openNativeIdentity(selected,anchor); + },true); + + // Preserve keyboard focus when closing the modeless identity window. + // The original Pages close handlers own visibility; never replace them. + for(const id of ["identityCancel","identityClose","identitySave"]){ + document.getElementById(id)?.addEventListener("click",()=>{ + requestAnimationFrame(()=>{ + if(!document.getElementById("channelIdentity")?.hidden)return; + const name=document.querySelector('.strip[data-id="'+lastEditedChannelId+'"] .footer-label .name'); + name?.focus?.({preventScroll:true}); + }); + }); + } + + // Pages' reference-only controls must not masquerade as working native + // operations. Keep REAL audio/FX/WIRE/device controls fully interactive; + // until full device-independent Show is implemented, hide unsafe demo + // shortcuts instead of silently intercepting and leaving broken buttons. + const nativeReferenceOnly=Object.freeze({ + sceneSelect:"Native full-session Show is not yet available", + sofToggle:"Sends on Faders requires acknowledged native send-gain routing", + sofTarget:"Sends on Faders requires acknowledged native send-gain routing", + saveScene:"Native full-session Show is not yet available", + recallScene:"Native full-session Show is not yet available", + sceneSafe:"Show safe requires native session snapshots", + group:"Native channel grouping not yet admitted", + ungroup:"Native channel grouping not yet admitted", + copy:"Native channel copy not yet admitted", + paste:"Native channel paste not yet admitted", + clearCue:"PFL requires dedicated physical monitoring", + preview:"Demo meters never run inside the native audio host", + reset:"Demo reset must not erase a live mixer", + addTrack:"Native channel creation requires graph admission", + addFx:"Use a verified FX insert slot on an admitted channel" + }); + function presentNativeOnlyTools(){ + for(const [id,reason] of Object.entries(nativeReferenceOnly)){ + const el=document.getElementById(id); + if(!el)continue; + el.disabled=true; + el.title=reason; + if(el.dataset)el.dataset.nativeUnavailable=reason; + // Do not advertise an interactive click target that native cannot + // fulfill. Internal IDs survive for the approved Pages DOM contract. + el.style?.setProperty?.("display","none","important"); + el.setAttribute?.("aria-hidden","true"); + } + const select=document.getElementById("sceneSelect"); + const label=document.querySelector('label[for="sceneSelect"]'); + if(select&&label)label.style?.setProperty?.("display","none","important"); + // Keyboard shortcuts in Pages call the demo reducer directly, bypassing + // the click capture guard below. Suppress that route only in JUCE native. + document.addEventListener("keydown",event=>{ + if(!(event.ctrlKey||event.metaKey))return; + if(event.target?.closest?.('input,textarea,select,[contenteditable="true"]'))return; + if(["c","v","g"].includes(event.key.toLowerCase())){ + event.preventDefault();event.stopImmediatePropagation(); + nativeToast("Native channel copy/group requires accepted mixer session support"); + } + },true); + } const ready=()=>{ + presentNativeOnlyTools(); installFirstSoundMenu(); + scope?.setNativeCatalog?.([]); // no synthetic/demo VST3 in Windows host updateHardwarePanel(null); stopDemo(); status("NATIVE: subscribed · waiting for true device and accepted ChannelId graph"); backend.emitEvent("arMixGuiReady",{ - gui:"APPROVED_PAGES_PREVIEW_BUTTONS",visualReady:true,audioReady:false + gui:"APPROVED_PAGES_PREVIEW_BUTTONS",visualReady:true,audioReady:false, + viewportWidth:Math.round(window.innerWidth), + viewportHeight:Math.round(window.innerHeight), + devicePixelRatio:window.devicePixelRatio }); controller.subscribe(); }; diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index 264fb72b1..1da1ea8d0 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -79,11 +79,9 @@ // FAT. Never equate an installed PCM graph with a release-ready product. // Conversely, callbackOwnsChannelIds is ONLY advertised by the real // installed callback; the legacy M4/Pages demo must remain unadmitted. - const admitted = caps.callbackOwnsChannelIds === true && + const hasAcceptedGraph = cmp(d.epoch,"0") > 0 && cmp(g.revision,"0") > 0 && - d.sampleRate > 0 && d.bufferFrames > 0 && - d.enabledOutputs.length > 0 && d.outputEndpoints.length > 0 && - Array.isArray(g.edges) && g.channels.length > 0 && mainCount === 1 && + cmp(g.rosterRevision,"0") > 0 && Array.isArray(g.edges) && g.channels.length > 0 && mainCount === 1 && typeof g.mainChannelId === "string" && g.channels.some(ch => ch.id === g.mainChannelId && ch.role === "MAIN") && g.channels.every(ch => fields(ch,["controls","inserts","sends"]) && @@ -92,11 +90,20 @@ Number.isFinite(ch.controls.pan) && isBool(ch.controls.mute) && isBool(ch.controls.solo) && Array.isArray(ch.inserts) && Array.isArray(ch.sends)); + const retained = g.bindingState === "NEEDS_REMAP"; + if (retained && (!hasAcceptedGraph || caps.callbackOwnsChannelIds || + caps.supportedOps.length !== 0 || d.outputArmed || + raw.mixerSession?.authority !== "CHANNEL_ID" || + raw.mixerSession?.bindingState !== "NEEDS_REMAP" || + raw.mixerSession?.deviceEpoch !== d.epoch)) return null; + const admitted = caps.callbackOwnsChannelIds === true && hasAcceptedGraph && + d.sampleRate > 0 && d.bufferFrames > 0 && + d.enabledOutputs.length > 0 && d.outputEndpoints.length > 0; // A producer may stage PCM without claiming full release/UAT. A producer // must NEVER claim product LIVE without an admitted PCM graph. if (raw.productionCallbackLive && !admitted) return null; if (caps.callbackOwnsChannelIds && !admitted) return null; - return { raw, device:d, graph:g, telemetry:t, admitted, + return { raw, device:d, graph:g, telemetry:t, admitted, retained, productLive:admitted && raw.productionCallbackLive, identity: d.epoch + ":" + g.revision + ":" + g.rosterRevision }; } @@ -116,6 +123,41 @@ if (operation === "SET_MUTE" || operation === "SET_SOLO") return typeof payload.value==="boolean" && ch.controls[operation==="SET_MUTE"?"mute":"solo"]===payload.value; + if (operation === "SET_PROCESSING_FORMAT") + return ["MONO","STEREO"].includes(payload.format) && + cmp(next.graph.revision,pending.baseGraphRevision)>0 && + cmp(next.graph.rosterRevision,pending.baseRosterRevision)>0 && + ch.processingFormat===payload.format; + if (operation === "LOAD_INSERT") + return cmp(next.graph.revision,pending.baseGraphRevision)>0 && + cmp(next.graph.rosterRevision,pending.baseRosterRevision)>0 && + Number.isInteger(payload.slot)&&payload.slot>=0 && + typeof payload.catalogId==="string" && + Array.isArray(ch.inserts)&&ch.inserts.length===payload.slot+1 && + ch.inserts[payload.slot]?.catalogId===payload.catalogId && + typeof ch.inserts[payload.slot]?.id==="string" && + ch.inserts[payload.slot].id.length>0 && + !ch.inserts.slice(0,payload.slot).some(insert=> + insert.id===ch.inserts[payload.slot].id); + if(operation==="REMOVE_INSERT"||operation==="MOVE_INSERT") { + const expected=pending.fxExpected; + if(!expected||cmp(next.graph.revision,pending.baseGraphRevision)<=0|| + cmp(next.graph.rosterRevision,pending.baseRosterRevision)<=0)return false; + const ids=id=>(next.graph.channels.find(c=>c.id===id)?.inserts||[]).map(x=>x.id); + const equal=(a,b)=>a.length===b.length&&a.every((x,i)=>x===b[i]); + if(!equal(ids(targetChannelId),expected.source))return false; + if(expected.to&&!equal(ids(expected.to),expected.destination))return false; + const copies=next.graph.channels.reduce((n,c)=>n+c.inserts.filter(x=>x.id===payload.instanceId).length,0); + return copies===(operation==="REMOVE_INSERT"?0:1); + } + if (operation === "SET_WIRE_GAIN") { + const before=pending.wireIdentity; + const edge=next.graph.edges.find(e=>e.enabled&&e.edgeId===payload.edgeId&&e.from===targetChannelId); + return !!before && !!edge && edge.primaryOutput===false && + edge.to===before.to && edge.tap===before.tap && + Number.isFinite(payload.gainLinear)&&Number.isFinite(edge.gainLinear)&& + Math.abs(edge.gainLinear-payload.gainLinear)<=0.0001; + } if (operation !== "APPLY_WIRE_TRANSACTION" || !Array.isArray(payload.changes) || !payload.changes.length) return false; // A structural WIRE transaction must advance the actual PCM graph. @@ -166,10 +208,17 @@ if (pending.originalPrimaryOutId && pending.originalPrimaryOutId!==edit.to && edges.some(e=>e.from===edit.from&& - e.to===pending.originalPrimaryOutId)) + e.to===pending.originalPrimaryOutId&& + // A remembered parallel send is NOT the former primary. + // Unknown/legacy edge identity stays fail-closed. + e.primaryOutput!==false)) return false; if (edit.to!==next.graph.mainChannelId && - edges.some(e=>e.from===edit.from&&e.to===next.graph.mainChannelId)) + edges.some(e=>e.from===edit.from&& + e.to===next.graph.mainChannelId&& + // ROUTE_ONLY replaces only the primary. A deliberate + // independent parallel MAIN send must remain audible. + e.primaryOutput!==false)) return false; } return true; @@ -242,7 +291,7 @@ cmp(next.graph.rosterRevision,current.graph.rosterRevision) < 0))) { lastError="OLD_NATIVE_REVISION";notify();return false; } - if (pending && epochCompare !== 0) { + if (pending && (epochCompare !== 0 || next.retained)) { pending=null;lastError="STALE_DEVICE"; } } @@ -290,12 +339,40 @@ lastError="UNKNOWN_CHANNEL_ID";notify();return {ok:false,error:lastError}; } if (!object(payload)) {lastError="INVALID_PAYLOAD";notify();return {ok:false,error:lastError};} + let fxExpected=null; + if(operation==="REMOVE_INSERT"||operation==="MOVE_INSERT") { + const source=current.graph.channels.find(c=>c.id===targetChannelId); + const slot=payload.slot,token=payload.instanceId; + if(!Number.isInteger(slot)||slot<0||source?.inserts?.[slot]?.id!==token) + return {ok:false,error:"STALE_FX_INSTANCE"}; + const ids=source.inserts.map(x=>x.id);ids.splice(slot,1); + fxExpected={source:ids}; + if(operation==="MOVE_INSERT") { + const dest=current.graph.channels.find(c=>c.id===payload.toChannelId),pos=payload.toSlot; + const same=dest?.id===targetChannelId; + const list=same?ids:dest?.inserts?.map(x=>x.id); + if(!dest||!["INPUT","GROUP","FX_RETURN","MAIN"].includes(dest.role)|| + !list||list.length>=8||!Number.isInteger(pos)||pos<0||pos>list.length) + return {ok:false,error:"INVALID_FX_DESTINATION"}; + list.splice(pos,0,token); + if(!same){fxExpected.to=dest.id;fxExpected.destination=list;} + } + } + let wireIdentity=null; + if(operation==="SET_WIRE_GAIN") { + const edge=current.graph.edges.find(e=>e.enabled&&e.edgeId===payload.edgeId&&e.from===targetChannelId); + if(!edge||edge.primaryOutput!==false||!Number.isFinite(payload.gainLinear)|| + payload.gainLinear<0||payload.gainLinear>4) { + lastError="INVALID_WIRE_GAIN_TARGET";notify();return {ok:false,error:lastError}; + } + wireIdentity={to:edge.to,tap:edge.tap}; + } const requestId=session+"-"+(++lastRequest); const msg={requestId,deviceEpoch:current.device.epoch, baseGraphRevision:current.graph.revision, baseRosterRevision:current.graph.rosterRevision, operation,targetChannelId,payload}; - pending={requestId,operation,targetChannelId,payload, + pending={requestId,operation,targetChannelId,payload,wireIdentity,fxExpected, originalPrimaryOutId:current.graph.channels.find( ch=>ch.id===targetChannelId)?.primaryOutId||null, deviceEpoch:msg.deviceEpoch,baseGraphRevision:msg.baseGraphRevision,