diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 2dac405ab..15054d67d 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -180,6 +180,18 @@ jobs: node --check web/approved-native-bridge.js node --check web/approved-native-contract.js node --test --test-name-pattern="ASIO4ALL|ASIO restart" tests/mixer_io_operator_contract_test.mjs + node --test tests/audio_continuity_contract_test.mjs + # This is also in the full Windows contract set; enforce it on the + # fast runner so a stale device-persistence assertion cannot waste + # a complete JUCE/MSVC job again. + node --test tests/direct_restore_recovery_contract_test.mjs + g++ -std=c++20 -O2 -Wall -Wextra -Werror tests/audio_continuity_policy_test.cpp -o "$RUNNER_TEMP/armix-audio-continuity" + "$RUNNER_TEMP/armix-audio-continuity" + # SonKu has >192 KiB acoustic rings per DSP instance. Prove the + # actual PCM assertions under a Windows-sized 1 MiB stack *before* + # allocating a full MSVC runner; never skip the native Windows CTest. + g++ -std=c++20 -O2 -Wall -Wextra -Werror tests/sonku_spatial_core_test.cpp -o "$RUNNER_TEMP/armix-sonku-spatial-core" + (ulimit -s 1024; "$RUNNER_TEMP/armix-sonku-spatial-core") g++ -std=c++20 -O2 -Wall -Wextra -Werror tests/first_run_endpoint_policy_test.cpp -o "$RUNNER_TEMP/armix-first-run-policy" "$RUNNER_TEMP/armix-first-run-policy" node --test tests/native_first_run_bootstrap_contract.test.mjs @@ -188,6 +200,7 @@ jobs: # inspector Python child must explicitly select UTF-8. PYTHONIOENCODING=cp1252 node --test --test-name-pattern="WIRE inspector controls PRIMARY BUS" tests/approved_native_m2_contract.test.cjs python -m unittest discover -s tests -p approved_native_gui_bundle_test.py -v + python -m unittest discover -s tests -p test_embedded_gui_resources.py -v python -m unittest discover -s scripts/tests -p test_factoryfx_release_bundle.py -v # Portable ChannelId PCM routing MUST be checked in under a minute, # before allocating a Windows JUCE/MSVC runner (93-CTest suite). @@ -647,7 +660,7 @@ jobs: sonku-p90-source: # Runs only on the P9 research PR, even while its production jobs skip. name: SonKu P9 exact-source C++ PCM preflight - if: ${{ github.event_name == 'pull_request' && startsWith(github.event.pull_request.head.ref, 'research/sonku-p90-') }} + if: ${{ github.event_name == 'pull_request' && (startsWith(github.event.pull_request.head.ref, 'research/sonku-p90-') || startsWith(github.event.pull_request.head.ref, 'research/sonku-p91-p92-')) }} runs-on: ubuntu-latest timeout-minutes: 10 steps: @@ -664,6 +677,8 @@ jobs: FLAGS="-std=c++20 -O2 -Wall -Wextra -Werror -pedantic -DSONKU_P7_MEASURED_ELEVATION_RESEARCH=1 -DSONKU_P71_DIRECT_XYZ_RESEARCH=1 -DSONKU_P72_NATIVE_XYZ_RT=1 -DSONKU_P75_MUSIC_SAFE_RESEARCH=1 -DSONKU_P80_TRANSPARENT_BASS_RESEARCH=1 -DSONKU_P82_MULTIBAND_ROOM_RESEARCH=1 -DSONKU_P83_PHYSICAL_SPEAKER_RESEARCH=1 -DSONKU_P84_SINGLE_CORE_FUSION_RESEARCH=1 -DSONKU_P85_WORLD_COHERENCE_RESEARCH=1 -DSONKU_P86_HORIZONTAL_FOCUS_RESEARCH=1 -DSONKU_P87_MUSIC_BODY_RESEARCH=1 -DSONKU_P88_PERCEPTUAL_ALIGNMENT_RESEARCH=1 -DSONKU_P89_DEPTH_COHERENCE_RESEARCH=1 -DSONKU_P90_TRUE_EXTERNAL_RESEARCH=1" g++ $FLAGS tests/sonku_p90_true_external_source_test.cpp -o /tmp/sonku-p90 /tmp/sonku-p90 + g++ $FLAGS tests/sonku_p91_p92_music_bass_foundation_test.cpp -o /tmp/sonku-p91p92 + /tmp/sonku-p91p92 g++ $FLAGS tests/sonku_p89_stereo_room_depth_source_test.cpp -o /tmp/sonku-p89 /tmp/sonku-p89 echo "SONKU_P90_NATIVE_SOURCE_CTEST_PASSED" @@ -671,7 +686,7 @@ jobs: sonku-p90-windows-fat: name: SonKu P9 actual JUCE / GUI portable x64 needs: sonku-p90-source - if: ${{ github.event_name == 'pull_request' && startsWith(github.event.pull_request.head.ref, 'research/sonku-p90-') }} + if: ${{ github.event_name == 'pull_request' && (startsWith(github.event.pull_request.head.ref, 'research/sonku-p90-') || startsWith(github.event.pull_request.head.ref, 'research/sonku-p91-p92-')) }} runs-on: windows-2022 timeout-minutes: 55 steps: @@ -717,12 +732,12 @@ jobs: - name: Build real native JUCE PCM, state ACK, and Windows GUI shell: pwsh run: | - cmake --build build --config Release --parallel 2 --target ARMixSonKuP90NativeTests ARMixSonKuP90SourceTests ARMixSonKuP89NativeTests ARMixSonKuP89SourceTests ARMixConsole + cmake --build build --config Release --parallel 2 --target ARMixSonKuP91P92MusicBassTests ARMixSonKuP90NativeTests ARMixSonKuP90SourceTests ARMixSonKuP89NativeTests ARMixSonKuP89SourceTests ARMixConsole if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } if (-not (Test-Path -LiteralPath 'build/ARMixConsole_artefacts/Release/AR MIX Studio.exe' -PathType Leaf)) { throw 'SONKU_P90_NATIVE_GUI_EXE_MISSING' } - ctest --test-dir build -C Release --output-on-failure -R '^NativeSonKuP(89RoomAnchoredStereoAndP88GoldenParity|89JuceV10AppliedAckAndV9Restore|90StereoExternalizationSource|90JuceV11AppliedAckAndLegacyRestore)$' + ctest --test-dir build -C Release --output-on-failure -R '^NativeSonKuP(89RoomAnchoredStereoAndP88GoldenParity|89JuceV10AppliedAckAndV9Restore|90StereoExternalizationSource|90JuceV11AppliedAckAndLegacyRestore|91P92MusicFidelityWorldBassAndRoom)$' if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Verified portable package, no installer or release shell: pwsh @@ -735,12 +750,13 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } Copy-Item docs/THIRD_PARTY_8D_SONKU_HRTF.md dist/THIRD_PARTY_8D_SONKU_HRTF.md Copy-Item docs/SONKU_P90_TRUE_EXTERNAL_SPEAKER_FAT_20261115.md dist/SONKU_P90_FIELD_FAT.md + Copy-Item docs/SONKU_P91_P92_RECONCILED_MUSIC_FIDELITY_BASS_FAT_20261116.md dist/SONKU_P91_P92_FIELD_FAT.md $provenance = Get-Content -LiteralPath dist/BUILD_PROVENANCE.json -Raw | ConvertFrom-Json if ($provenance.sourceCommit -ne (git rev-parse HEAD).Trim()) { throw 'SONKU_P90_SOURCE_COMMIT_MISMATCH' } $provenance | Add-Member -Force -NotePropertyName sonkuExperiment -NotePropertyValue @{ - mode = 'P9.0_TRUE_EXTERNAL_SPEAKER' + mode = 'P9.1_P9.2_MUSIC_FIDELITY_PHYSICAL_BASS' stateSchema = 11 headphoneFat = 'PENDING' publicRelease = $false diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 4dae65547..510ff54de 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -394,6 +394,37 @@ jobs: if-no-files-found: ignore retention-days: 7 + + mixer-global-fx-visual: + name: Global FX hardware power + PAN real Chromium (3 viewports) + needs: quick + # Deliberately scoped: one current GUI milestone, no generic full-suite, + # no unrelated SonKu, GAIN or paid Windows native rebuild. + if: ${{ github.event_name == 'pull_request' && startsWith(github.head_ref, 'feat/mixer-global-fx-ab-') }} + runs-on: ubuntu-latest + timeout-minutes: 12 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Install one Chromium + run: | + python -m pip install playwright + python -m playwright install --with-deps chromium + - name: Assemble exact PR head /preview/ assets + run: python scripts/build_pages.py --out dist-pages --sha "${{ github.event.pull_request.head.sha }}" --branch main + - name: Verify FX master power face and individual state; PAN no-collision + run: python tests/pages_global_fx_ab_pan_wire_smoke.py + - name: Retain ON/OFF screenshots from all viewports + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ArSonMix-Global-FX-PAN-${{ github.run_id }} + path: arsonmix-global-fx-*.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. @@ -470,6 +501,8 @@ jobs: 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: Global FX A/B, PAN extremes and GAIN/WIRE state (real Chromium) + run: python tests/pages_global_fx_ab_pan_wire_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 diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d9ebab73..d8491880c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -338,6 +338,10 @@ target_link_libraries(ARMixConsole PRIVATE include(CTest) if(BUILD_TESTING) + # Pure-C++ P0 audio-continuity gate: display idle must never reset MAIN. + add_executable(ARMixAudioContinuityPolicyTests tests/audio_continuity_policy_test.cpp) + target_compile_features(ARMixAudioContinuityPolicyTests PRIVATE cxx_std_20) + add_test(NAME P0DisplayIdlePreservesAudioAndDeviceRecoveryIntent COMMAND ARMixAudioContinuityPolicyTests) juce_add_console_app(ARMixFactoryFxRegistryTests PRODUCT_NAME "ArSonMix Factory FX Integrity Tests") target_sources(ARMixFactoryFxRegistryTests PRIVATE tests/factory_fx_registry_test.cpp src/FactoryFxRegistry.h) target_link_libraries(ARMixFactoryFxRegistryTests PRIVATE juce::juce_core juce::juce_cryptography juce::juce_recommended_config_flags) @@ -793,6 +797,26 @@ if(BUILD_TESTING) SONKU_P90_TRUE_EXTERNAL_RESEARCH=1) add_test(NAME NativeSonKuP90StereoExternalizationSource COMMAND ARMixSonKuP90SourceTests) + add_executable(ARMixSonKuP91P92MusicBassTests + tests/sonku_p91_p92_music_bass_foundation_test.cpp) + target_compile_features(ARMixSonKuP91P92MusicBassTests PRIVATE cxx_std_20) + target_compile_definitions(ARMixSonKuP91P92MusicBassTests PRIVATE + SONKU_P7_MEASURED_ELEVATION_RESEARCH=1 + SONKU_P71_DIRECT_XYZ_RESEARCH=1 + SONKU_P72_NATIVE_XYZ_RT=1 + SONKU_P75_MUSIC_SAFE_RESEARCH=1 + SONKU_P80_TRANSPARENT_BASS_RESEARCH=1 + SONKU_P82_MULTIBAND_ROOM_RESEARCH=1 + SONKU_P83_PHYSICAL_SPEAKER_RESEARCH=1 + SONKU_P84_SINGLE_CORE_FUSION_RESEARCH=1 + SONKU_P85_WORLD_COHERENCE_RESEARCH=1 + SONKU_P86_HORIZONTAL_FOCUS_RESEARCH=1 + SONKU_P87_MUSIC_BODY_RESEARCH=1 + SONKU_P88_PERCEPTUAL_ALIGNMENT_RESEARCH=1 + SONKU_P89_DEPTH_COHERENCE_RESEARCH=1 + SONKU_P90_TRUE_EXTERNAL_RESEARCH=1) + add_test(NAME NativeSonKuP91P92MusicFidelityWorldBassAndRoom + COMMAND ARMixSonKuP91P92MusicBassTests) juce_add_console_app(ARMixSonKuP90NativeTests PRODUCT_NAME "ArSonMix SonKu P90 JUCE v11 State Tests") target_sources(ARMixSonKuP90NativeTests PRIVATE diff --git a/docs/SONKU_P91_P92_RECONCILED_MUSIC_FIDELITY_BASS_FAT_20261116.md b/docs/SONKU_P91_P92_RECONCILED_MUSIC_FIDELITY_BASS_FAT_20261116.md new file mode 100644 index 000000000..d5ac4f53c --- /dev/null +++ b/docs/SONKU_P91_P92_RECONCILED_MUSIC_FIDELITY_BASS_FAT_20261116.md @@ -0,0 +1,47 @@ +# SonKu P9.1 + P9.2 — Reconciled Music Fidelity and World-Anchored Bass + +**Status:** PRIVATE HEADPHONE FAT CANDIDATE — NOT RELEASED, NOT dearVR PARITY + +## Reconciliation (performed first) + +- Starting P9 HEAD `cd85ffee054dad6b3b752b5351d34921ddc92717` (draft PR #717). +- Production `main` `37985f02caecd93b22f853183888d81e18dc6736` already contains #713 ASIO/WASAPI continuity, operator MAIN intent, audio graph/global FX and saved-session safeguards. +- New two-parent reconciliation commit `ea0a7c0a5bb3afb2c4295176447c2eb78bb6835b`, with main as direct ancestor. Imported the 30 main-changed files and applied 29 exact-context patch hunks for the four overlapping files: `src/Main.cpp`, `CMakeLists.txt`, `p1-windows.yml`, `mixer-fx-rack.css`. No production branch changed or merged. +- The new acoustic development and GUI belong to `research/sonku-p91-p92-fidelity-bass-reconciled-20261116`, PR #719, based on PR #717. + +## Why the previous default was not acceptable + +Old P9 used legacy output trim 0.75 (about -2.5 dB) and HRTF wet factor 0.5. Critically, P90 inherited P8.2 `transparentBass`: the low part of the world HRTF was *subtracted* and the original headphone-locked L/R bass was brought back. That violated the world-speaker premise. The original P8.2 bass-shelf 0.82 (+5.2 dB when fully active) was also still applied to the P9 branch with room ON, so a naive LF enhancement stacked gains and clipped musical intent. + +The operator's field setting (82° speakers, near 1.6m, Large 28.8m room, +7 dB output, reflections 100%, reverb 62%) is a crucial listening reference; copying that full +7 dB and 100% wet as default would hide the bug. + +## Integrated native DSP architecture + +1. Keep the existing measured 2x2 KEMAR direct HRIR and P9 coherence-safe MID/SIDE compositor. Only P9 mode 9 routes into the new LF foundation. +2. Complementary two-pole lowpass at 165 Hz: `HRTF(high)=HRTF - LP(HRTF)` and `worldLow = W_L*LP(L) + W_R*LP(R)`. BOTH use the same lowpass topology, avoiding a disconnected high-pass and duplicated low energy. Source weights are `0.5*(1 +/- 0.27*sin(headAngle))`, with a 361-point sine lookup prepared once. They follow the existing world-speaker and head-yaw angles; no original headphone L/R dry-low return. +3. P9 only, use 0.72 scene binaural gain and no legacy room loudness multiplier 1.12 or legacy +0.82 LF shelf. The full original peak protection remains. Native P8.2–P8.9 behavior is unchanged. +4. Room EARLY now receives independent L/R with the actual P9 speaker angle. The eight-line late FDN receives the true L/R, not a duplicate MID source. Speaker azimuth and world/head rotation apply to the early image reflections. +5. Three lightweight axial mode resonators per room (Studio 7.2, Chamber 14.4, Large 28.8m) are computed from `f=n*343/(2*L)` nearest preselected LF clusters and a stable Q=2.0/2.8/3.8 bandpass. Bounded wet weights 0.14/0.105/0.075 and 60ms room/size smoothing; ROOM OFF is strictly zero. This is *not* a personalized/physical subwoofer driver/cabinet IR, nor measured modal BRIR. +6. On the first intentional switch from an *untouched legacy factory scene* to P9, an isolated native-ACKed close music stage initializes: 82° source spread, 1.6m, Large, 78% ER, 33% FDN, 0 dB output, orbit OFF. Existing .smix and manually adjusted states do not reset. No new state version or GUI visual redesign. + +## Objective PCM admission + +Tests use real native C++ at both 44.1 and 48 kHz. Check full source-referenced 70/116Hz+5.2kHz steady-state input/output RMS at output gain 0dB, loudness floor/ceiling, finite peaks below the same 0.98 linked guard, 128/256 block bit parity, left/right/anti-phase, 0% ROOM modal bit-exact zero, nonzero room response, and head-yaw changes. An additional isolated *70Hz-only* WorldBass test verifies left/right ear dominance reverses when the listener rotates, so treble cannot camouflage headlocked bass. + +Reference PCM result after gain correction (source sum RMS 0.40890): +- 44.1k P9 sum RMS 0.41656, approximately +0.16 dB; P8.9 0.37159. +- 48k P9 sum RMS 0.41477, approximately +0.12 dB; P8.9 0.37152. + +These are NOT music integrated LUFS, not physical headphone acoustic dB, and not proof of perceptual externalization. The new isolated 70Hz rotation test and Windows JUCE CTest must pass for its own exact commit, not inherited from an earlier source run. + +## Required headphone FAT + +- Compare raw stereo versus P8.2, P8.9, reconciled P9.1/P9.2 and dearVR PRO 2 under matched output LUFS within +/-0.5 LU. Disable all other FX and parallel dearVR insert while testing each. +- Material: percussion kick, bass guitar/sub 30–120Hz, orchestral ensemble, centered vocal, sibilance/transients, anti-phase stereo torture and real recordings with substantial 60–180Hz. +- Positions: 82°/120°/180° speaker spread, 1.6/3/6.7m, yaw -90/0/90/180. Toggle Large/Chamber/OFF with same level; distinguish bass *impact* from low-frequency bass *boom* and transient masking. +- Analysis: frequency response, LF group delay and modal decay, true IACC/ILD/ITD, DRR, headphone correction, CPU P95 per callback, silence/denormal/NaN and resumed device handling. Existing +7dB user A/B can be monitored but must NOT become default gain. +- Record scene, capture screenshots, compare with dearVR by listening. Do not claim measured dearVR feature parity or commercial release before FAT. + +## Engineering constraints + +No heap, locks, SIMD prerequisites, FFT allocation, filesystem calls or extra callback inside PCM. Coefficients are prepared once, weights small fixed arrays, single native route. Room modes are low-level bounded returns, not uncontrolled feedback. Preserve previous saved session schemas v1..v11, global FX gate, MAIN continuity and ASIO priority. Production main and P8.2–P8.9 remain unmodified. diff --git a/engine/builtin_fx/sonku/SonKuP91P92WorldBassFoundation.h b/engine/builtin_fx/sonku/SonKuP91P92WorldBassFoundation.h new file mode 100644 index 000000000..938cb96a5 --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuP91P92WorldBassFoundation.h @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include + +// P9.1+P9.2: one existing 2x2 HRTF callback, no second audio graph. +// A complementary LF handover replaces only the direct HRIR's low portion +// with two WORLD-anchored loudspeaker sources, never headphone-locked L/R. +// Source signals are kept independent (anti-phase is NOT rectified). +// Very small measured-room-inspired axial modal returns are optional and +// separate from the DIRECT bass. This is a parametric model, NOT a measured +// subwoofer cabinet or an asserted dearVR algorithm. +namespace armix::sonku::p92 { +class WorldBassFoundation final { +public: + struct Ears {float left=0.f,right=0.f;}; + bool prepare(double sampleRate) noexcept { + if(!std::isfinite(sampleRate) || + (std::abs(sampleRate-44100.)>.1 && std::abs(sampleRate-48000.)>.1)) + return false; + constexpr double pi=3.1415926535897932384626433832795; + const double cutoff=165.; + lowAlpha_=static_cast(1.-std::exp(-2.*pi*cutoff/sampleRate)); + roomAlpha_=static_cast(1.-std::exp(-1./(sampleRate*.060))); + // Angle lookup avoids trig/heap in the 16-frame realtime FIR update. + for(std::size_t i=0;i(std::sin((2.*pi*i)/360.)); + constexpr std::array roomWidths{7.2,14.4,28.8}; + constexpr std::array frequencies{48.,75.,112.}; + constexpr std::array qualities{2.0,2.8,3.8}; + for(std::size_t room=0;room<3;++room){ + for(std::size_t band=0;band<3;++band){ + // Real axial harmonic: n*c/(2*room-width), rounded to a + // musically relevant LF cluster. Never invent a subharmonic. + const double n=std::max(1.,std::round(2.*roomWidths[room]* + frequencies[band]/343.)); + const double hz=n*343./(2.*roomWidths[room]); + resonators_[room][band].coeff=bandpass(sampleRate,hz,qualities[band]); + } + } + reset(); + return true; + } + void reset() noexcept { + for(auto& s:inputLow_)s={}; + for(auto& s:earLow_)s={}; + for(auto& room:resonators_)for(auto& resonator:room) + resonator.state={}; + weights_={{{.62f,.38f},{.38f,.62f}}}; + roomWeights_={}; + roomGain_=0.f; + } + void updateDirections(float leftHead,float rightHead) noexcept { + const float angles[2]{leftHead,rightHead}; + for(int source=0;source<2;++source){ + const float lean=.27f*lookupSine(angles[source]); + weights_[source][0]=.5f*(1.f-lean); + weights_[source][1]=.5f*(1.f+lean); + } + } + Ears process(float inputLeft,float inputRight,float& hrtfLeft, + float& hrtfRight,int roomPreset,float roomAmount) noexcept { + // Two identical minimum-phase lowpasses on BOTH paths: the high + // direct HRIR remains exactly HRIR - LP(HRIR), without double bass. + const float inputs[2]{inputLeft,inputRight}; + float lowSrc[2]{}; + for(int c=0;c<2;++c){ + inputLow_[c][0]+=lowAlpha_*(inputs[c]-inputLow_[c][0]); + inputLow_[c][1]+=lowAlpha_*(inputLow_[c][0]-inputLow_[c][1]); + lowSrc[c]=inputLow_[c][1]; + } + float* ears[2]{&hrtfLeft,&hrtfRight}; + float world[2]{}; + for(int ear=0;ear<2;++ear){ + earLow_[ear][0]+=lowAlpha_*(*ears[ear]-earLow_[ear][0]); + earLow_[ear][1]+=lowAlpha_*(earLow_[ear][0]-earLow_[ear][1]); + // With the old P8.2 +0.82 shelf disabled, a stereo 2x LF + // return matches the measured input RMS within ~0.5dB for + // our 70/116Hz + 5.2kHz reference at the protected P9 gain. + // The shared FIR output remains a single stereo signal. + world[ear]=2.f*(weights_[0][ear]*lowSrc[0]+ + weights_[1][ear]*lowSrc[1]); + *ears[ear]=*ears[ear]-earLow_[ear][1]+world[ear]; + } + const int room=std::clamp(roomPreset-1,0,2); + const float target=roomPreset>0? + std::clamp(roomAmount,0.f,1.f):0.f; + roomGain_+=roomAlpha_*(target-roomGain_); + Ears modal{}; + constexpr std::array modeWeights{.14f,.105f,.075f}; + for(int r=0;r<3;++r){ + const float active=r==room?1.f:0.f; + roomWeights_[r]+=roomAlpha_*(active-roomWeights_[r]); + for(int b=0;b<3;++b){ + // Tiny modal bandpass; finite decay, zero at DC, no phase + // cancellation of the direct LOW, no positive feedback. + auto& resonator=resonators_[r][b]; + const float l=resonator.state[0].run(resonator.coeff,world[0]); + const float rr=resonator.state[1].run(resonator.coeff,world[1]); + const float level=roomWeights_[r]*roomGain_*modeWeights[b]; + modal.left+=level*l; + modal.right+=level*rr; + } + } + return modal; + } +private: + struct Coeff {float b0=0.f,b1=0.f,b2=0.f,a1=0.f,a2=0.f;}; + struct State { + float z1=0.f,z2=0.f; + float run(const Coeff& c,float input) noexcept { + const float y=c.b0*input+z1; + z1=c.b1*input-c.a1*y+z2; + z2=c.b2*input-c.a2*y; + return y; + } + }; + struct Resonator {Coeff coeff{};std::array state{};}; + static Coeff bandpass(double rate,double hz,double q) noexcept { + constexpr double pi=3.1415926535897932384626433832795; + const double w=2.*pi*hz/rate; + const double a=std::sin(w)/(2.*q); + const double inv=1./(1.+a); + return {static_cast(a*inv),0.f, + static_cast(-a*inv), + static_cast(-2.*std::cos(w)*inv), + static_cast((1.-a)*inv)}; + } + float lookupSine(float degrees) const noexcept { + if(!std::isfinite(degrees))return 0.f; + float bounded=degrees; + while(bounded<0.f)bounded+=360.f; + while(bounded>=360.f)bounded-=360.f; + const int lo=static_cast(bounded); + const float frac=bounded-lo; + return sine_[lo]*(1.f-frac)+sine_[lo+1]*frac; + } + std::array,2> weights_{{{{.62f,.38f}},{{.38f,.62f}}}}; + std::array,2> inputLow_{},earLow_{}; + std::array,3> resonators_{}; + std::array sine_{}; + std::array roomWeights_{}; + float roomGain_=0.f,lowAlpha_=0.f,roomAlpha_=0.f; +}; +} // namespace armix::sonku::p92 diff --git a/engine/builtin_fx/sonku/SonKuSpatialCore.h b/engine/builtin_fx/sonku/SonKuSpatialCore.h index 68ca3d80d..5b8e26eaf 100644 --- a/engine/builtin_fx/sonku/SonKuSpatialCore.h +++ b/engine/builtin_fx/sonku/SonKuSpatialCore.h @@ -21,6 +21,7 @@ #include "SonKuP84FusedMusicHrir.h" #if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH #include "SonKuP90StereoDecoder.h" +#include "SonKuP91P92WorldBassFoundation.h" #endif #endif #if defined(SONKU_P87_MUSIC_BODY_RESEARCH) && SONKU_P87_MUSIC_BODY_RESEARCH @@ -202,6 +203,7 @@ class SonKuSpatialCore final { if(!p84MusicKernel_.prepare(rate))return false; #if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH if(!p90Decoder_.prepare(rate))return false; + if(!p92Bass_.prepare(rate))return false; #endif #endif #if defined(SONKU_P87_MUSIC_BODY_RESEARCH) && SONKU_P87_MUSIC_BODY_RESEARCH @@ -269,6 +271,7 @@ class SonKuSpatialCore final { integrity_.reset(); #if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH p90Decoder_.reset(); + p92Bass_.reset(); #endif #if defined(SONKU_P83_PHYSICAL_SPEAKER_RESEARCH) && SONKU_P83_PHYSICAL_SPEAKER_RESEARCH p83LowFrequency_.reset(); @@ -312,6 +315,15 @@ class SonKuSpatialCore final { #if defined(SONKU_P87_MUSIC_BODY_RESEARCH) && SONKU_P87_MUSIC_BODY_RESEARCH if(s.renderMode!=settings_.renderMode || s.spacePreset!=settings_.spacePreset)p87Body_.reset(); +#endif +#if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH + // Native mode changes are already zero-gated by JUCE. Reset only + // small P9 LF/coherence memories when entering or leaving mode 9: + // a frozen previous P9 scene must never leak stale bass after P8 A/B. + if((s.renderMode==9)!=(settings_.renderMode==9)){ + p90Decoder_.reset(); + p92Bass_.reset(); + } #endif settings_=s; #if defined(SONKU_P83_PHYSICAL_SPEAKER_RESEARCH) && SONKU_P83_PHYSICAL_SPEAKER_RESEARCH @@ -519,7 +531,13 @@ class SonKuSpatialCore final { const bool roomEnabled=settings_.spacePreset!=0; #if defined(SONKU_P80_TRANSPARENT_BASS_RESEARCH) && SONKU_P80_TRANSPARENT_BASS_RESEARCH const bool transparentBass= - room_.preparedProfile()==SonKuReflectionProfile::SixSurfaceKemarResearch && !positionedMode; + room_.preparedProfile()==SonKuReflectionProfile::SixSurfaceKemarResearch && !positionedMode +#if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH + // P9 owns its complementary WORLD LF return. Never replace it + // with P8.2's original headphone-locked low frequencies. + && p83Mode_!=p83::Mode::MusicSpatialP90 +#endif + ; #else constexpr bool transparentBass=false; #endif @@ -586,6 +604,11 @@ class SonKuSpatialCore final { #endif ; #endif +#endif +#if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH + const bool p90World=p83Mode_==p83::Mode::MusicSpatialP90; +#else + constexpr bool p90World=false; #endif // Deliberate music-monitor compensation: real distance perception // still comes from direct/reflected ratio and high-frequency cues, @@ -652,7 +675,9 @@ class SonKuSpatialCore final { // Preserve HRTF-only stored-state arithmetic exactly; scene ON // uses an actual full-output gain (dry+wet) instead of trim-only. const float legacyBinauralLevel=.5f*smoothedMix_*smoothedTrim_; - const float sceneBinauralLevel=.5f*smoothedMix_; + // P9: remove the legacy monitor attenuation only for the new + // spatialized-world scene; the linked peak guard is unchanged. + const float sceneBinauralLevel=(p90World?.72f:.5f)*smoothedMix_; if(remaining_==0) { updateKernels(); remaining_=updateInterval; @@ -732,7 +757,17 @@ class SonKuSpatialCore final { } } #if defined(SONKU_P80_TRANSPARENT_BASS_RESEARCH) && SONKU_P80_TRANSPARENT_BASS_RESEARCH - if(transparentBass || positionedMode) +#if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH + p92::WorldBassFoundation::Ears p92RoomBass{}; + if(p90World)p92RoomBass=p92Bass_.process( + x0,x1,ears[0],ears[1], + settings_.spacePreset,settings_.roomAmount); +#endif + if(transparentBass || positionedMode +#if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH + || p90World +#endif + ) tonalCalibration_.process(ears[0],ears[1]); #if defined(SONKU_P87_MUSIC_BODY_RESEARCH) && SONKU_P87_MUSIC_BODY_RESEARCH if(musicalBody && roomEnabled) @@ -744,9 +779,9 @@ class SonKuSpatialCore final { p83LowFrequency_.process(x0,x1,ears[0],ears[1]); #endif auto reflection=room_.active() - ?room_.process(transparentBass?x0:(musicSafe?inputMid:x0), - transparentBass?x1:(musicSafe?inputMid:x1), - degrees_,transparentBass?settings_.stereoSpreadDegrees: + ?room_.process((p90World||transparentBass)?x0:(musicSafe?inputMid:x0), + (p90World||transparentBass)?x1:(musicSafe?inputMid:x1), + degrees_,(p90World||transparentBass)?settings_.stereoSpreadDegrees: ((musicSafe||monoObject)?0.f:settings_.stereoSpreadDegrees) #if defined(SONKU_P83_PHYSICAL_SPEAKER_RESEARCH) && SONKU_P83_PHYSICAL_SPEAKER_RESEARCH #if defined(SONKU_P84_SINGLE_CORE_FUSION_RESEARCH) && SONKU_P84_SINGLE_CORE_FUSION_RESEARCH @@ -761,8 +796,8 @@ class SonKuSpatialCore final { ) :SonKuEarlyReflections::Ears{}; auto late=reverb_.active() - ?reverb_.process(transparentBass?x0:(musicSafe?inputMid:x0), - transparentBass?x1:(musicSafe?inputMid:x1)) + ?reverb_.process((p90World||transparentBass)?x0:(musicSafe?inputMid:x0), + (p90World||transparentBass)?x1:(musicSafe?inputMid:x1)) :SonKuMusicalReverb::Ears{}; #if defined(SONKU_P87_MUSIC_BODY_RESEARCH) && SONKU_P87_MUSIC_BODY_RESEARCH if(musicalBody && roomEnabled){ @@ -778,7 +813,8 @@ class SonKuSpatialCore final { if(p83Stem_!=p83::Stem::Late)late={}; } #endif - if(!transparentBass && !nativeSpace && settings_.outputTrim<=1.f && + if(!transparentBass && !nativeSpace && !p90World && + settings_.outputTrim<=1.f && smoothedTrim_<=1.f) { // Preserve byte-for-byte original HRTF/old .smix output for // ROOM OFF and gain <= unity. Newly boosted GAIN > unity @@ -798,9 +834,9 @@ class SonKuSpatialCore final { smoothedDistanceGain_+=distanceSlew_* (targetDistance-smoothedDistanceGain_); smoothedRoomLevel_+=distanceSlew_* - (((roomEnabled&&!positionedMode)?1.12f:1.f)-smoothedRoomLevel_); + (((roomEnabled&&!positionedMode&&!p90World)?1.12f:1.f)-smoothedRoomLevel_); smoothedBassShelf_+=distanceSlew_* - (((roomEnabled&&!positionedMode)?0.82f:0.f)-smoothedBassShelf_); + (((roomEnabled&&!positionedMode&&!p90World)?0.82f:0.f)-smoothedBassShelf_); // The original experimental return levels were intentionally // near-silent: ER base 0.28 * wall 0.70 * 1/r and diffuse FDN // output 0.23 * amount, followed by another 0.5 * trim. @@ -841,6 +877,14 @@ class SonKuSpatialCore final { float spatialR=smoothedDistanceGain_*ears[1]+ smoothedErPresence_*reflection.right+ smoothedTailPresence_*late.right; +#if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH + if(p90World){ + // Position-aware LF modes return separately from direct + // pressure; room OFF is exactly zero, no added dry SIDE. + spatialL+=p92RoomBass.left; + spatialR+=p92RoomBass.right; + } +#endif #if defined(SONKU_P80_TRANSPARENT_BASS_RESEARCH) && SONKU_P80_TRANSPARENT_BASS_RESEARCH if(transparentBass){ // Decompose DIRECT HRTF only. Room returns remain true @@ -1102,8 +1146,10 @@ class SonKuSpatialCore final { interpolate(targets_[0],positions.leftHead); interpolate(targets_[1],positions.rightHead); #if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH - if(p83Mode_==p83::Mode::MusicSpatialP90) + if(p83Mode_==p83::Mode::MusicSpatialP90){ p90Decoder_.compose(centerTarget_,targets_[0],targets_[1]); + p92Bass_.updateDirections(positions.leftHead,positions.rightHead); + } else #endif p84MusicKernel_.merge(centerTarget_,targets_[0],targets_[1]); @@ -1202,6 +1248,7 @@ class SonKuSpatialCore final { p84::FusedMusicHrir p84MusicKernel_{}; #if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH p90::StereoDecoder p90Decoder_{}; + p92::WorldBassFoundation p92Bass_{}; #endif #if defined(SONKU_P87_MUSIC_BODY_RESEARCH) && SONKU_P87_MUSIC_BODY_RESEARCH p87::MusicalAirBody p87Body_{}; diff --git a/engine/core/DynamicChannelFxLeaseBank.h b/engine/core/DynamicChannelFxLeaseBank.h index ee47cdb40..e28eb2243 100644 --- a/engine/core/DynamicChannelFxLeaseBank.h +++ b/engine/core/DynamicChannelFxLeaseBank.h @@ -212,6 +212,11 @@ class DynamicChannelFxLeaseBank final { row->rackBypassed->store(bypass,std::memory_order_release); return true; } + // CONTROL once before publishing the bank. Shared control owner's + // lifetime must cover every retired audio snapshot; no RT refcounting. + void bindGlobalRackOverride(const std::atomic* flag) noexcept { + globalRackOverride_=flag; + } bool rackBypassed(ChannelId id) const noexcept { const auto* row=find(id); return row&&row->rackBypassed && @@ -416,8 +421,10 @@ class DynamicChannelFxLeaseBank final { if(external_.id.value && external_.id==id && external_.render) { external_.render(external_.context,left,right,frames); }else if(row){ - const bool rackOff=row->rackBypassed && - row->rackBypassed->load(std::memory_order_acquire); + const bool rackOff=(globalRackOverride_ && + globalRackOverride_->load(std::memory_order_acquire)) || + (row->rackBypassed && + row->rackBypassed->load(std::memory_order_acquire)); for(std::size_t i=0;icount;++i) row->raw[i]->render(left,right,frames,rackOff); } @@ -431,6 +438,9 @@ class DynamicChannelFxLeaseBank final { } private: + // Immutable graph pointer; published FX uses only one atomic read to + // bypass every lane, preserving per-channel and per-insert saved state. + const std::atomic* globalRackOverride_=nullptr; struct MusicGuideTarget final { ChannelId target{}; armix::builtin_fx::ChannelHarmonyProcessor* processor=nullptr; diff --git a/engine/core/LiveChannelFxGraph.h b/engine/core/LiveChannelFxGraph.h index 1ca1d5c53..9e0f2da93 100644 --- a/engine/core/LiveChannelFxGraph.h +++ b/engine/core/LiveChannelFxGraph.h @@ -313,6 +313,11 @@ class LiveChannelFxGraph final { } // One atomic rack override per channel. Individual slot bypass flags stay // unchanged; ON restores the previous enabled/disabled combination. + // Prepared M4 graph and ChannelId owner share a single physical A/B gate. + // The pointer is installed before publication and never changed on RT. + void bindGlobalRackOverride(const std::atomic* flag) noexcept { + globalRackOverride_=flag; + } bool setRackBypass(int strip,bool bypass) noexcept { if(strip<0||strip>=fxSlots)return false; rackBypassed_[strip].store(bypass,std::memory_order_release); @@ -394,7 +399,9 @@ class LiveChannelFxGraph final { (int strip,float* l,float* r,int samples) noexcept { if(strip<0||strip>=fxSlots)return; const int count=counts_[strip]; // immutable, prepared OFF RT - const bool rackOff=rackBypassed_[strip].load(std::memory_order_acquire); + const bool rackOff=(globalRackOverride_ && + globalRackOverride_->load(std::memory_order_acquire)) || + rackBypassed_[strip].load(std::memory_order_acquire); if(count>0) { for(int slot=0;slot counts_ {}; std::array,fxSlots> rackBypassed_{}; // CONTROL write; one RT read per lane + const std::atomic* globalRackOverride_=nullptr; // prepared before publication int activeInserts_=0; int pluginQuantum_=512; int mainOutputLeft_=0,mainOutputRight_=1; diff --git a/engine/core/UnifiedLegacyProductionAdmission.h b/engine/core/UnifiedLegacyProductionAdmission.h index ba55ee45a..09baa7c1f 100644 --- a/engine/core/UnifiedLegacyProductionAdmission.h +++ b/engine/core/UnifiedLegacyProductionAdmission.h @@ -105,7 +105,8 @@ class UnifiedLegacyProductionAdmission final { bool allOutputsDisarmed, DynamicNativeSessionPublisher& publisher, UnifiedLegacyAccepted& accepted, - DynamicChannelFxLeaseBank::ExternalLease externalCh1={}) { + DynamicChannelFxLeaseBank::ExternalLease externalCh1={}, + const std::atomic* globalFxOverride=nullptr) { Report result; if(!hardware.valid() || hardware.monitorEnabled!=acceptedM4Fx.monitorEnabled() || @@ -180,6 +181,7 @@ class UnifiedLegacyProductionAdmission final { result.fault=Fault::fxLeaseInvalid;return result; } auto owner=std::make_shared(std::move(bank)); + owner->bindGlobalRackOverride(globalFxOverride); // before PCM publication DynamicNativeSessionPublisher::FxPlan plan; plan.owner=std::static_pointer_cast(owner); plan.context=owner.get(); diff --git a/engine/device/AudioContinuityPolicy.h b/engine/device/AudioContinuityPolicy.h new file mode 100644 index 000000000..16556966e --- /dev/null +++ b/engine/device/AudioContinuityPolicy.h @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include + +namespace armix::device { + +// UI/display power is deliberately NOT audio power. These notifications must +// never change the operator's mixer graph, MAIN intent or driver selection. +enum class NativePowerEvent : std::uint8_t { + displayOff, displayOn, systemSuspend, systemResume +}; +struct AudioPowerPolicy final { + static constexpr bool inspectDevice(NativePowerEvent event) noexcept { + return event == NativePowerEvent::systemResume; + } + static constexpr bool changeMixerIntent(NativePowerEvent) noexcept { + return false; + } +}; + +// Desired MAIN/monitoring state belongs to the operator, not the JUCE device +// callback lifetime. Only a user mute/explicit stop clears it. Hardware loss +// gates physical output separately; same verified endpoint may resume later. +// A real MAIN mute and a safety feedback latch remain independent of this. +class OutputContinuityIntent final { +public: + void operatorRequested(bool active) noexcept { + desired_.store(active, std::memory_order_release); + interrupted_.store(false, std::memory_order_release); + } + void deviceInterrupted() noexcept { + if (desired_.load(std::memory_order_acquire)) + interrupted_.store(true, std::memory_order_release); + } + void deviceRecovered() noexcept { + interrupted_.store(false, std::memory_order_release); + } + bool desired() const noexcept { + return desired_.load(std::memory_order_acquire); + } + bool interrupted() const noexcept { + return interrupted_.load(std::memory_order_acquire); + } +private: + std::atomic desired_{false}, interrupted_{false}; +}; + +// CONTROL-thread scheduler: event-driven, non-blocking and generation-safe. +// A device can be absent for hours; never exhaust all attempts permanently, +// spin on each 12Hz tick, or substitute the Windows default audio endpoint. +class AudioContinuityRetry final { +public: + void fault(std::uint64_t now) noexcept { + if (pending_) return; + pending_ = true; + attempts_ = 0; + dueMs_ = now + 350; + ++generation_; + } + void endpointReturned(std::uint64_t now) noexcept { + if (pending_) dueMs_ = now + 350; + } + bool due(std::uint64_t now) const noexcept { + return pending_ && now >= dueMs_; + } + void failed(std::uint64_t now) noexcept { + if (!pending_) return; + ++attempts_; + const auto waitMs = attempts_ == 1 ? 1000ull + : attempts_ == 2 ? 3000ull + : attempts_ == 3 ? 8000ull : 30000ull; + dueMs_ = now > UINT64_MAX - waitMs ? UINT64_MAX : now + waitMs; + } + void recovered() noexcept { cancel(); } + void cancel() noexcept { + ++generation_; + pending_ = false; + attempts_ = 0; + dueMs_ = 0; + } + bool pending() const noexcept { return pending_; } + unsigned attempts() const noexcept { return attempts_; } + std::uint64_t generation() const noexcept { return generation_; } +private: + bool pending_ = false; + unsigned attempts_ = 0; + std::uint64_t generation_ = 0, dueMs_ = 0; +}; +} // namespace armix::device diff --git a/scripts/verify_embedded_gui_resources.py b/scripts/verify_embedded_gui_resources.py new file mode 100644 index 000000000..5beb05ec9 --- /dev/null +++ b/scripts/verify_embedded_gui_resources.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Fast, byte-exact attestation of the GUI resources INSIDE a Windows EXE. + +The Pages assembler already creates one approved GUI and the native bundler +adds only an explicitly reversed JUCE event seam. This verifies the actual +distributed executable, not merely a manifest or CMake's input directory. + +Use a read-only mmap and its native substring search rather than a PowerShell +byte-by-byte scan over a multi-megabyte EXE for every PNG. Fail closed for +missing, altered, duplicate or path-escaping staged resources. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import mmap +from pathlib import Path, PurePosixPath +import re + + +class EmbeddedGuiError(ValueError): + """An approved resource cannot be attested to the executable.""" + + +def verify(exe: Path, bundle: Path, manifest_path: Path) -> int: + if not exe.is_file() or exe.stat().st_size == 0: + raise EmbeddedGuiError(f"Missing/empty native executable: {exe}") + if not manifest_path.is_file(): + raise EmbeddedGuiError(f"Missing native GUI manifest: {manifest_path}") + doc = json.loads(manifest_path.read_text(encoding="utf-8")) + if doc.get("schema") != "arsonmix.approved-native-pages-bundle.v2": + raise EmbeddedGuiError("Unknown approved GUI manifest schema") + entries = doc.get("files") + if not isinstance(entries, list) or not entries: + raise EmbeddedGuiError("Empty or invalid approved GUI resource list") + + root = bundle.resolve(strict=True) + seen: set[str] = set() + with exe.open("rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as image: + for entry in entries: + if not isinstance(entry, dict): + raise EmbeddedGuiError("Malformed approved GUI resource record") + rel, digest = entry.get("path"), entry.get("sha256") + if not isinstance(rel, str) or not isinstance(digest, str): + raise EmbeddedGuiError("Missing approved GUI path/hash") + posix = PurePosixPath(rel) + if ( + rel in seen or posix.is_absolute() or "\\" in rel + or any(part in (".", "..") for part in rel.split("/")) + or not (rel == "index.html" or rel.startswith("assets/")) + or not re.fullmatch(r"[0-9a-f]{64}", digest) + ): + raise EmbeddedGuiError(f"Unsafe/duplicate approved GUI resource: {rel}") + seen.add(rel) + path = (root / rel).resolve() + if not path.is_relative_to(root) or not path.is_file(): + raise EmbeddedGuiError(f"Missing or escaped staged GUI resource: {rel}") + raw = path.read_bytes() + if not raw or hashlib.sha256(raw).hexdigest() != digest: + raise EmbeddedGuiError(f"Staged GUI resource SHA mismatch: {rel}") + if image.find(raw) < 0: + raise EmbeddedGuiError( + f"APPROVED GUI BYTE RESOURCE NOT IN WINDOWS EXE: {rel}" + ) + + if "index.html" not in seen: + raise EmbeddedGuiError("Approved GUI index.html not in manifest") + return len(seen) + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--exe", type=Path, required=True) + ap.add_argument("--bundle", type=Path, required=True) + ap.add_argument("--manifest", type=Path, required=True) + args = ap.parse_args() + count = verify(args.exe, args.bundle, args.manifest) + print(f"APPROVED_GUI_EMBEDDED_BYTES_OK resources={count}") + + +if __name__ == "__main__": + main() diff --git a/scripts/verify_native_windows_artifact.ps1 b/scripts/verify_native_windows_artifact.ps1 index 37c54134b..d0e02feb2 100644 --- a/scripts/verify_native_windows_artifact.ps1 +++ b/scripts/verify_native_windows_artifact.ps1 @@ -131,42 +131,17 @@ if (-not $cmakeSource.Contains('juce_add_binary_data(ARMixAssets SOURCES') -or } # PNG artwork is binary; CSS/JS/SVG/HTML are compared as exact UTF8 text, # rather than mere marker matches. Each staged resource is also SHA-attested. -function Test-EmbeddedBytes([byte[]]$haystack, [byte[]]$needle) { - if ($needle.Length -eq 0 -or $needle.Length -gt $haystack.Length) { return $false } - $last = $haystack.Length - $needle.Length - for ($i = 0; $i -le $last; $i++) { - if ($haystack[$i] -ne $needle[0]) { continue } - $found = $true - for ($j = 1; $j -lt $needle.Length; $j++) { - if ($haystack[$i + $j] -ne $needle[$j]) { $found = $false; break } - } - if ($found) { return $true } - } - return $false -} +# Byte-identical GUI parity is verified against the DISTRIBUTED executable, +# not just source manifests. Python mmap.find is compiled/native and avoids +# the former PowerShell O(EXE_size * resource_count * resource_size) loop. +# Keep the PowerShell PE/header, icon and release provenance checks above. +& $approvedGuiPython scripts/verify_embedded_gui_resources.py --exe $exePath --bundle $approvedGuiDir --manifest $approvedPath +if ($LASTEXITCODE -ne 0) { + throw "REJECT: APPROVED GUI BYTE RESOURCE NOT IN WINDOWS EXE" +} +# Human-readable startup markers are additional checks, never a substitute +# for the raw byte fingerprint of every HTML/CSS/JS/SVG/PNG resource. $embeddedText = [Text.Encoding]::UTF8.GetString($bytes) -foreach ($item in $approved.files) { - $rel = [string]$item.path - $resourcePath = Join-Path $approvedGuiDir $rel - if (-not (Test-Path -LiteralPath $resourcePath -PathType Leaf)) { - throw "REJECT: compiled GUI missing staged asset $rel" - } - $real = (Get-FileHash -LiteralPath $resourcePath -Algorithm SHA256).Hash.ToLowerInvariant() - if ($real -ne $item.sha256) { - throw "REJECT: approved GUI staged resource digest differs: $rel" - } - $resourceBytes = [IO.File]::ReadAllBytes((Resolve-Path -LiteralPath $resourcePath).Path) - $present = if ($rel.EndsWith(".png", [StringComparison]::OrdinalIgnoreCase)) { - Test-EmbeddedBytes $bytes $resourceBytes - } else { - $sourceText = [Text.Encoding]::UTF8.GetString($resourceBytes) - $sourceText.Length -gt 0 -and - $embeddedText.IndexOf($sourceText, [StringComparison]::Ordinal) -ge 0 - } - if (-not $present) { - throw "REJECT: APPROVED GUI BYTE RESOURCE NOT IN WINDOWS EXE: $rel" - } -} if ($embeddedText.IndexOf('APPROVED_PAGES_PREVIEW_BUTTONS', [StringComparison]::Ordinal) -lt 0 -or $embeddedText.IndexOf('M1_VISUAL_BUNDLE_ONLY__NOT_AUDIO_READY', [StringComparison]::Ordinal) -lt 0 -or $embeddedText.IndexOf('WEBVIEW2_GUI_READY_TIMEOUT', [StringComparison]::Ordinal) -lt 0 -or diff --git a/site/preview-v2/assets/mixer-console-foundation.css b/site/preview-v2/assets/mixer-console-foundation.css index b0c99e972..ea57f9eb7 100644 --- a/site/preview-v2/assets/mixer-console-foundation.css +++ b/site/preview-v2/assets/mixer-console-foundation.css @@ -58,3 +58,36 @@ button:disabled{opacity:.45;cursor:not-allowed} .app .console-pane{min-width:0} .app .tracks-viewport{min-width:0} } + +/* One physical FX toolbar button: the standard contextual metal owner + paints the ENTIRE button green when FX is enabled and silver when + bypassed. Text and unframed SVG share the button's normal ink. */ +.app .command-bar #globalFxToggle{ + display:inline-flex!important;align-items:center!important;justify-content:center!important; + gap:4px; + width:52px;min-width:52px;max-width:52px;flex:0 0 52px; + height:23px;min-height:23px;padding:0 6px!important; + /* Inherit exact font, baseline, line-height and ink from .command-bar .tool. + The old 14px text linebox + translateY(1px) shifted FX away from the + adjacent GAIN / FX RACK / Sends on Faders labels. */ + +} +/* Caption occupies the same natural linebox as every other toolbar label. + No optical transform, forced line-height, separate type scale or baseline. */ +.app .command-bar #globalFxToggle .global-fx-label{ + display:block;flex:0 0 auto;align-self:center; + line-height:inherit!important; + margin:0;padding:0;border:0;transform:none!important;white-space:nowrap; +} +.app .command-bar #globalFxToggle svg.global-fx-power-icon{ + display:block;align-self:center;flex:0 0 14px;width:14px;height:14px; + vertical-align:middle;padding:0;margin:0;border:0;box-shadow:none; + background:none!important;filter:none;pointer-events:none; + fill:currentColor;color:inherit!important; +} +.app .command-bar #globalFxToggle:focus-visible{ + outline:2px solid #94d9e8;outline-offset:2px; +} +.app .command-bar #globalFxToggle[aria-busy="true"]{ + opacity:.75;cursor:progress; +} diff --git a/site/preview-v2/assets/mixer-contextual-buttons.css b/site/preview-v2/assets/mixer-contextual-buttons.css index 58774e33a..49e345b66 100644 --- a/site/preview-v2/assets/mixer-contextual-buttons.css +++ b/site/preview-v2/assets/mixer-contextual-buttons.css @@ -81,7 +81,7 @@ } /* Keep hardware action color local to its semantic role, not a generic glow. */ .app :is( - #wireMaster,#routeOnly,#routeParallel,#identitySave + #wireMaster,#routeOnly,#routeParallel,#identitySave,#globalFxToggle ){--ari-on-top:#3b8c6e;--ari-on-hi:#50a783;--ari-on-mid:#3d956f;--ari-on-bottom:#308665;--ari-on-edge:#266347;--ari-on-ink:#f0fff7} .app :is(#mode,#wireNavigatorToggle,#wireMatrixToggle,#pluginsButton) {--ari-on-top:#388ea9;--ari-on-hi:#54aec6;--ari-on-mid:#3e94ae;--ari-on-bottom:#2d839c;--ari-on-edge:#246577;--ari-on-ink:#152b36} diff --git a/site/preview-v2/assets/mixer-fx-rack.css b/site/preview-v2/assets/mixer-fx-rack.css index 77d732b4b..4e4829591 100644 --- a/site/preview-v2/assets/mixer-fx-rack.css +++ b/site/preview-v2/assets/mixer-fx-rack.css @@ -1372,6 +1372,12 @@ .mx-sonku #skFarSources .sk-src{filter:drop-shadow(0 1px 2px rgba(0,0,0,.3))} .mx-sonku #skNearSources .sk-src{filter:drop-shadow(0 3px 6px rgba(0,0,0,.72))} +/* A native rack readback may repaint its local status while global bypass + remains engaged. No FX label appears enabled until the global gate is ON. */ +.console-body.global-fx-bypassed .strip .fx-section .fxslot-row:not(.is-empty) .fx-pick{ + color:#849ca7!important; +} + /* SonKu v4 research controls share the existing lightweight FX skin. Hidden unless the real native processor reports P8.3 capability. */ .mx-sonku .sk-render-row[hidden]{display:none!important} diff --git a/site/preview-v2/assets/mixer-native-sonku.js b/site/preview-v2/assets/mixer-native-sonku.js index 5ad8c9597..c093df5b5 100644 --- a/site/preview-v2/assets/mixer-native-sonku.js +++ b/site/preview-v2/assets/mixer-native-sonku.js @@ -195,7 +195,7 @@ const depthLayers={far:$("skFarSources"),near:$("skNearSources")}; const mount=()=>{if(!root.isConnected)document.body.append(root)}; if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",mount,{once:true});else mount(); let current=null,accepted=defaults(),draft=defaults(),pending=null,latest=null, - xyzCapable=false,p83Capable=false,p84Capable=false,p85Capable=false,p86Capable=false,p87Capable=false,p88Capable=false,p89Capable=false,p90Capable=false,musicSafeStereo=false,p8TransparentBass=false,p82MultibandRoom=false, + xyzCapable=false,p83Capable=false,p84Capable=false,p85Capable=false,p86Capable=false,p87Capable=false,p88Capable=false,p89Capable=false,p90Capable=false,p91p92Capable=false,musicSafeStereo=false,p8TransparentBass=false,p82MultibandRoom=false, readId="",readSentAt=0,seq=1,clock=null,frame=null,observed=0,observedAt=0, drag=null,dialDrag=null,rangeEdits=new Set(),gestureStart=new Map(), visualPhase=0,visualAt=0,liveTimer=null,lastLiveAt=0; @@ -215,7 +215,7 @@ function render(){ const row=$("skRenderRow");row.hidden=!(p83Capable||p84Capable); if(p83Capable||p84Capable){ const picker=$("skRenderMode"); - if(p90Capable && picker.dataset.nativeModeSet!=="p90"){ + if(p90Capable && picker.dataset.nativeModeSet!==(p91p92Capable?"p91p92":"p90")){ picker.innerHTML=''+ ''+ ''+ @@ -223,9 +223,12 @@ function render(){ ''+ ''+ ''+ - ''; - picker.dataset.nativeModeSet="p90"; - root.querySelector(".sk-render-label").textContent="RENDER MODE · P9.0 HEADPHONE FAT"; + (p91p92Capable? + '': + ''); + picker.dataset.nativeModeSet=p91p92Capable?"p91p92":"p90"; + root.querySelector(".sk-render-label").textContent=p91p92Capable? + "RENDER MODE · P9.1 + P9.2 FAT":"RENDER MODE · P9.0 HEADPHONE FAT"; }else if(!p90Capable && p89Capable && picker.dataset.nativeModeSet!=="p89"){ picker.innerHTML=''+ ''+ @@ -345,8 +348,10 @@ function render(){ if(!rangeEdits.has("skHrtfAlign"))align.value=String(s.hrtfElevationTrimDegrees); $("skHrtfAlignValue").textContent=(s.hrtfElevationTrimDegrees>=0?"+":"")+s.hrtfElevationTrimDegrees.toFixed(1)+"°"; } - root.querySelector(".sk-stage-caption").textContent=p90Capable&&s.renderMode===9? - "P9.0 MEASURED TWIN-SPEAKER HRIR · WORLD-LOCKED STEREO · FAT REQUIRED": + root.querySelector(".sk-stage-caption").textContent=p91p92Capable&&s.renderMode===9? + "P9.1 + P9.2 · MUSIC FIDELITY · WORLD BASS · ROOM MODES · FAT REQUIRED": + p90Capable&&s.renderMode===9? + "P9.0 · MEASURED TWIN-SPEAKER HRIR · HEADPHONE FAT REQUIRED": p89Capable&&s.renderMode===8? "P8.9 ROOM-ANCHORED STEREO · DIRECT MUSICAL BODY PRESERVED · FAT REQUIRED": p88Capable&&s.renderMode===7? @@ -390,7 +395,8 @@ function render(){ // redrawn at 60 Hz. The native audio callback remains the time authority. drawSpeakers(); $("skMode").textContent=native()?(context()? - (p90Capable&&s.renderMode===9?"NATIVE P9.0 TRUE EXTERNAL · TEST": + (p91p92Capable&&s.renderMode===9?"NATIVE P9.1+P9.2 WORLD BASS · FAT": + p90Capable&&s.renderMode===9?"NATIVE P9.0 TRUE EXTERNAL · TEST": p89Capable&&s.renderMode===8?"NATIVE P8.9 STEREO + ROOM · TEST": p88Capable&&s.renderMode===7?"NATIVE P8.8 EAR ALIGN + DISTANCE · TEST": p87Capable&&s.renderMode===6?"NATIVE P8.7 MUSICAL AIR + BODY · TEST": @@ -556,6 +562,8 @@ backend()?.addEventListener?.("arMixBuiltinSonKuSnapshot",r=>{ Number.isFinite(incoming.headYawDegrees); p90Capable=r.schemaVersion===11 && r.p90TrueExternalSpeaker===true && Number.isFinite(incoming.hrtfElevationTrimDegrees); + // Separate from schema v11: old P9.0 DSP must not receive the P9.1/9.2 label. + p91p92Capable=p90Capable && r.p91p92MusicBassFoundation===true; p89Capable=(r.schemaVersion===10||p90Capable) && r.p89StereoRoomDepth===true && Number.isFinite(incoming.hrtfElevationTrimDegrees); p88Capable=(r.schemaVersion===9||p89Capable) && r.p88PerceptualAlignment===true && @@ -606,7 +614,7 @@ backend()?.addEventListener?.("arMixBuiltinSonKuSnapshot",r=>{ } render(); }); -$("skClose").addEventListener("click",()=>{root.hidden=true;current=null;xyzCapable=false;p85Capable=false;p86Capable=false;p87Capable=false;p88Capable=false;p89Capable=false;p90Capable=false;musicSafeStereo=false;p8TransparentBass=false;p82MultibandRoom=false; +$("skClose").addEventListener("click",()=>{root.hidden=true;current=null;xyzCapable=false;p85Capable=false;p86Capable=false;p87Capable=false;p88Capable=false;p89Capable=false;p90Capable=false;p91p92Capable=false;musicSafeStereo=false;p8TransparentBass=false;p82MultibandRoom=false; cancelLiveTimer();pending=null;latest=null;readId="";readSentAt=0;dialDrag=null; drag=null;rangeEdits.clear();gestureStart.clear();lastLiveAt=0; if(clock!==null){clearInterval(clock);clock=null;} @@ -623,6 +631,23 @@ $("skRenderMode").addEventListener("change",()=>{ p84Capable?(v==="clarity"?3:0): v==="mono"?1:v==="physical"||v==="musiclf"?2:0; const scene={...draft,renderMode:mode,musicCompatibleLowFrequency:v==="musiclf"}; + // P9.1/P9.2: a factory-new P8.2 state is NOT a musical P9 default. + // Only on first user selection of P9, and only when every relevant + // parameter still matches the legacy factory values, initialize a + // real close-room music stage. Saved .smix/manual settings are untouched. + // The entire scene goes through the existing native ACK, never optimistic DSP. + const legacy=draft.renderMode===0 && draft.spacePreset===0 && + draft.startAzimuthDegrees===0 && draft.moving===true && + Math.abs(draft.stereoSpreadDegrees-60)<.001 && + Math.abs(draft.outputTrim-.75)<.001 && + Math.abs(draft.roomAmount-.55)<.001 && + Math.abs(draft.ambience-.30)<.001 && + Math.abs(draft.sourceDistanceMeters-1.6)<.001; + if(mode===9 && p90Capable && legacy){ + Object.assign(scene,{moving:false,stereoSpreadDegrees:82, + outputTrim:1,spacePreset:3,sourceDistanceMeters:1.6, + roomAmount:.78,ambience:.33}); + } // Mode changes in v6 must not reset the owner scene, yaw or motion. if(mode!==0 && !p85Capable){ scene.moving=false; diff --git a/site/preview-v2/assets/mixer-pan-controls.css b/site/preview-v2/assets/mixer-pan-controls.css index be60f4311..6e7cbc3f5 100644 --- a/site/preview-v2/assets/mixer-pan-controls.css +++ b/site/preview-v2/assets/mixer-pan-controls.css @@ -4,7 +4,7 @@ .pan-section{height:var(--pan-h);display:flex;align-items:center;gap:4px;padding:0 6px} .pan-section input{min-width:0;max-width:100%;accent-color:#9ba7aa} .pan-section .pan-icon{font-size:15px;color:#9a9fa1} -.pan-section output{font-size:9px;min-width:0;text-align:right;color:#6bafc2;white-space:nowrap;overflow:hidden} +.pan-section output{font-size:9px;min-width:0;text-align:right;color:#6bafc2;white-space:nowrap;overflow:hidden;font-variant-numeric:tabular-nums} .pan-control{height:17px;flex:1;min-width:0;position:relative;display:flex;align-items:center;isolation:isolate} .pan-control:after{content:"";pointer-events:none;position:absolute;top:1px;bottom:0;left:50%;border-left:1px solid #91c1cb;opacity:.95} .center-pan{width:100%!important;flex:1;min-width:0;height:18px!important;appearance:none;-webkit-appearance:none;background:transparent;cursor:ew-resize;margin:0;position:relative;z-index:2} @@ -13,7 +13,7 @@ .center-pan::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:9px;height:14px;margin-top:-5px;border-radius:2px;background:linear-gradient(#d4dadd,#879fa9);border:1px solid #151b1d} .center-pan::-moz-range-thumb{width:9px;height:14px;border-radius:2px;background:#acc2cb;border:1px solid #151b1d} .console-body .pan-section{height:var(--pan-h);flex:0 0 var(--pan-h);display:grid;grid-template-columns:17px minmax(0,1fr) 29px;gap:5px;padding:0 7px;} -.console-body .pan-section output{font-size:11px;text-align:right;color:#a0dff0} +.console-body .pan-section output{font-size:9px;font-weight:500;letter-spacing:-.15px;text-align:right;color:#a0dff0;justify-self:end} .console-body .pan-icon{color:#c0d0d5} .console-body .pan-control{height:23px;max-width:none} .console-body .center-pan{min-width:0} @@ -21,7 +21,12 @@ .console-body .center-pan::-webkit-slider-thumb{width:15px;height:19px;margin-top:-7px;border:1px solid #344b55;border-radius:3px;background:linear-gradient(#f0f5f7,#9bafba 47%,#556e7e 49%,#dce6e9 65%,#728f9f);box-shadow:0 1px 2px #111} .console-body .center-pan::-moz-range-thumb{width:15px;height:19px;border-radius:3px;border:1px solid #344b55;background:linear-gradient(#f0f5f7,#9bafba 47%,#556e7e)} .console-body[data-density="compact"] .pan-section{grid-template-columns:12px minmax(0,1fr) 18px;gap:1px;padding:0 3px} -.console-body .pan-section{grid-template-columns:23px minmax(0,1fr) 23px!important;gap:3px!important;padding:0 4px!important;} +/* Equal 25px gutters keep PAN and its 9px L100/R100 caption in their + respective cells without collision. Grid symmetry keeps the slider center + at strip center, even at extremes and across strip density changes. */ +.console-body .pan-section{grid-template-columns:25px minmax(0,1fr) 25px!important;gap:3px!important;padding:0 4px!important;} +.console-body.narrow .pan-section .pan-control{justify-self:center;width:min(100%,43px)} + .console-body .pan-icon{font-size:9px!important} .console-body .center-pan{height:40px!important;min-height:40px!important;max-height:40px!important;width:100%!important;appearance:none!important;-webkit-appearance:none!important;background:transparent!important;padding:0!important} .console-body .center-pan::-webkit-slider-runnable-track{height:5px!important;border:1px solid #0a1218!important;background:linear-gradient(to right,#0b151a 0%,#0b151a var(--pan-start),#42b5ca var(--pan-start),#42b5ca var(--pan-end),#0b151a var(--pan-end),#0b151a 100%)!important} diff --git a/site/preview-v2/assets/mixer-utility-controls.css b/site/preview-v2/assets/mixer-utility-controls.css index b83dd206c..dbeaf8ad8 100644 --- a/site/preview-v2/assets/mixer-utility-controls.css +++ b/site/preview-v2/assets/mixer-utility-controls.css @@ -175,3 +175,12 @@ outline:2px solid #9bd9e8;outline-offset:1px; } /* No new button element, JS state, opacity animation or tool-tip overlay. */ + +/* Global FX bypass is an effective state. Keep individual saved bypass + switches intact, but display their existing grey OFF tile as long as the + master gate is off. The moment it returns ON, per-slot states reappear. */ +.app .console-body.global-fx-bypassed .strip button.mx-util-key[data-util-kind="fx-main"], +.app .console-body.global-fx-bypassed .strip button.mx-util-key[data-util-kind="fx-slot"]{ + --mx-micro-x:0%; + color:#788891; +} diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index 1dcc61587..ed6a565b9 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -47,6 +47,7 @@ + @@ -208,7 +209,7 @@ }));}catch(error){/* Manager still works without browser storage. */} } const tracksEl=document.getElementById('tracks'),masterEl=document.getElementById('master'),info=document.getElementById('info'); -let nextId=1,nextGroup=1,tracks=[],master,preview=false,meterFrame=0,lastTick=0,clipboard=null,scenes=[],stripView="fx",sofEnabled=false,sofTarget="Bus A",sofTargetId=null,wireSourceId=1,wireEdges=[],nextWireId=1,selectedWireEdgeId=null,wireMode='send',wireAnchorId=null,wireHoverId=null,wireGesture=null,wireSuppressClick=false,pendingBusRoute=null,wireView='focus',wireSourcePinned=false,wireIntent=false; +let nextId=1,nextGroup=1,tracks=[],master,preview=false,meterFrame=0,lastTick=0,clipboard=null,scenes=[],stripView="fx",globalFxOn=true,wireBeforeGain=null,sofEnabled=false,sofTarget="Bus A",sofTargetId=null,wireSourceId=1,wireEdges=[],nextWireId=1,selectedWireEdgeId=null,wireMode='send',wireAnchorId=null,wireHoverId=null,wireGesture=null,wireSuppressClick=false,pendingBusRoute=null,wireView='focus',wireSourcePinned=false,wireIntent=false; const clone=x=>JSON.parse(JSON.stringify(x)); const selection=()=>tracks.concat(master).filter(t=>t.selected); const make=(name,kind,color)=>{ @@ -401,9 +402,9 @@ const used=t.fx.map((name,i)=>({name,i})).filter(x=>x.name!=='None'); const first=t.fx.findIndex(x=>x==='None'); const rows=used.concat(first<0?[]:[{name:'None',i:first}]); - let out='
fxFX '+used.length+'
'; + let out='
fxFX '+used.length+'
'; for(const {name,i} of rows){ - out+='
'+ + out+='
'+ (name==='None'?'': ''); out+=''; @@ -693,7 +694,7 @@ '
'+wireTray(t)+compactWireSummary(t)+'
'; } function formatDb(n){return n<=-60?'-∞':(n>0?'+':'')+Number(n).toFixed(1);} -function panLabel(n){return Number(n)===0?'C':n<0?'L'+Math.abs(n):'R'+n;} +function panLabel(n){return Number(n)===0?'CEN':n<0?'L'+Math.abs(n):'R'+n;} function panStyle(n){const left=Math.min(50,50+n/2),right=Math.max(50,50+n/2);return '--pan-start:'+left+'%;--pan-end:'+right+'%';} /* One shared visual travel contract for fader, ticks, pointer and detent. dBFS meter calibration is separate; neither GUI is an audio DSP authority. */ @@ -897,6 +898,7 @@ } const context=document.getElementById('mixContext'); if(context)context.textContent=sofEnabled?'SEND MIX → '+sofTarget:'MAIN MIX'; + syncGlobalFxButton(); masterEl.innerHTML=strip(master); document.getElementById('viewport').scrollLeft=0; document.getElementById('bankPrev').disabled=count<=1; @@ -2793,6 +2795,40 @@ window.addEventListener('blur',()=>{ if(armedWireSource()&&!wireGesture&&!pendingBusRoute)clearWireIntent(); }); + +/* Workspace contract: GAIN makes the WIRE patch bay visible without moving + PAN / M-S-PFL / fader. On return to FX, restore the operator's previous + WIRE state unless they explicitly changed the rail while in GAIN. */ +function setWireExpansion(expanded){ + const body=document.querySelector('.console-body'); + const rail=body?.querySelector('.section-rail [data-section="send"]'); + if(!body||!rail)return false; + body.classList.toggle('collapsed-send',!expanded); + rail.classList.toggle('collapsed',!expanded); + rail.setAttribute('aria-expanded',String(expanded)); + rail.setAttribute('aria-pressed',String(expanded)); + rail.title=expanded?'Collapse WIRE section':'Expand WIRE section'; + requestAnimationFrame(renderWireRouting); + return true; +} +function syncGlobalFxButton(){ + const btn=document.getElementById('globalFxToggle'); + if(!btn)return; + btn.dataset.fxPowerState=globalFxOn?'on':'bypassed'; + btn.classList.toggle('active',globalFxOn); + btn.classList.toggle('is-bypassed',!globalFxOn); + btn.setAttribute('aria-pressed',String(globalFxOn)); + btn.setAttribute('aria-label',globalFxOn?'FX power ON. Bypass all mixer effects':'FX power BYPASSED. Enable all mixer effects'); + btn.title=(globalFxOn?'FX ON':'FX BYPASSED')+' · all channels, buses, returns and MAIN · individual FX settings preserved'; + document.querySelector('.console-body')?.classList.toggle('global-fx-bypassed',!globalFxOn); +} +/* Native-only readback hook. A pending JUCE command never paints a false + bypass state; the native bridge calls this only with published FX status. */ +window.__ARMIX_SET_GLOBAL_FX_VIEW__=(enabled)=>{ + if(typeof enabled!=='boolean')return false; + if(globalFxOn===enabled){syncGlobalFxButton();return true;} + globalFxOn=enabled;render();return true; +}; document.querySelector('.section-rail').addEventListener('click',e=>{ const button=e.target.closest('[data-section]');if(!button)return; const name=button.dataset.section,body=document.querySelector('.console-body'); @@ -2800,6 +2836,7 @@ say('Exit Narrow view before expanding '+name.toUpperCase());return; } const collapsed=body.classList.toggle('collapsed-'+name); + if(name==='send'&&stripView==='gain')wireBeforeGain=null; // manual rail decision wins button.classList.toggle('collapsed',collapsed); button.setAttribute('aria-expanded',String(!collapsed)); button.setAttribute('aria-pressed',String(!collapsed)); @@ -3025,12 +3062,31 @@ say('INPUT GAIN unavailable · no channel has an acknowledged native gain stage'); return; } - // View selection is presentation-only; the DSP insert chain stays resident. + // Changing workspace never edits a plugin or physical WIRE. Only the + // presentation section expands/collapses; restore the prior user layout. + if(value==='gain'&&stripView!=='gain'){ + const body=document.querySelector('.console-body'); + wireBeforeGain=body?.classList.contains('collapsed-send')??null; + setWireExpansion(true); + }else if(value==='fx'&&stripView==='gain'){ + if(wireBeforeGain!==null)setWireExpansion(!wireBeforeGain); + wireBeforeGain=null; + } stripView=value;render(); say(value==='gain'?'Digital INPUT GAIN · each knob follows accepted channel readback': 'FX RACK · existing inserts preserved'); }); } +document.getElementById('globalFxToggle').addEventListener('click',()=>{ + if(window.__JUCE__?.backend){ + if(!window.__ARMIX_NATIVE_GLOBAL_FX__?.toggle?.()) + say('Global FX unavailable · native PCM or verified readback required'); + return; + } + globalFxOn=!globalFxOn; + render(); + say('ALL FX '+(globalFxOn?'ON · individual FX settings restored':'OFF · bypass audition only; presets unchanged')); +}); document.getElementById('sofToggle').addEventListener('click',()=>toggleSof()); document.getElementById('sofTarget').addEventListener('change',()=>{ const id=Number(document.getElementById('sofTarget').value); diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index cb6ad2e4e..f7bee36fa 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -25,6 +25,7 @@ #include "../engine/device/AsioRegistryIdentityProbe.h" #include "../engine/device/DirectRouteFence.h" #include "../engine/device/DeviceSessionTransitionPolicy.h" +#include "../engine/device/AudioContinuityPolicy.h" #include "../engine/device/WasapiEndpointIdentityGuard.h" #include "../engine/core/FxOrderPlan.h" #include "../engine/core/FxMoveRamp.h" @@ -101,6 +102,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback std::array slots {}; std::array, maxFx> bypassFlags {}; std::atomic rackBypassed{false}; // does not overwrite per-slot flags + // Stable, CONTROL-bound pointer to lab's single global bypass atomic. + const std::atomic* globalRackOverride=nullptr; // Owned and advanced exclusively by the realtime render callback. // Physical-slot identity survives an atomic logical reorder (PR #102). std::array bypassEnvelope {}; @@ -118,6 +121,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback scratch_.setSize (2, maxFrames, false, true, false); // CH1 bypass scratch now belongs to its shared Graph lifetime so // a ChannelId PCM snapshot can retain the SAME original FX state. + graphOwned_->globalRackOverride=dryRoutingLab_.globalFxBypassFlag(); handoff_.initialize (graphOwned_.get()); } @@ -395,8 +399,19 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return "No physical input assigned. Connect CH1/CH2 first."; return {}; } - void setMonitorEnabled (bool value) noexcept { monitor_.store (value); } - bool isMonitorEnabled() const noexcept { return monitor_.load(); } + // User/approved-workflow MAIN intent is NOT the volatile JUCE callback gate. + // Screen-off does not touch either; device stop gates only physical output. + void setMonitorEnabled (bool value) noexcept { + mainOutputIntent_.operatorRequested(value); + monitor_.store(value,std::memory_order_release); + if (!value) resumeMainAfterAsioReset_.store(false,std::memory_order_release); + } + bool isMonitorEnabled() const noexcept { return monitor_.load(std::memory_order_acquire); } + bool wantsMainContinuation() const noexcept { return mainOutputIntent_.desired(); } + bool mainInterruptedByDevice() const noexcept { return mainOutputIntent_.interrupted(); } + std::uint64_t directCallbackCount() const noexcept { + return callbackCount_.load(std::memory_order_relaxed); + } // Emergency output mute, not a prerequisite for receiving audio. void setOutputMuted (bool mute) noexcept { monitor_.store (!mute, std::memory_order_release); } bool isOutputMuted() const noexcept { return !monitor_.load (std::memory_order_acquire); } @@ -414,7 +429,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void beginManualAudioSetup(bool preserveMonitorIntent=false) noexcept { offeredWasapiBinding_.reset(); if(!preserveMonitorIntent)resumeMainAfterAsioReset_.store(false,std::memory_order_release); - else if(isMonitorEnabled())resumeMainAfterAsioReset_.store(true,std::memory_order_release); + else if(wantsMainContinuation())resumeMainAfterAsioReset_.store(true,std::memory_order_release); setOutputMuted(true); secondaryOutput_.disarm(); directFence_.suspend(); @@ -971,6 +986,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback std::unique_ptr preparedFxEdit() const { auto next=std::make_unique(); + next->globalRackOverride=dryRoutingLab_.globalFxBypassFlag(); + next->rackBypassed.store( + graphOwned_->rackBypassed.load(std::memory_order_acquire), + std::memory_order_relaxed); next->count=graphOwned_->count; // A previous lock-free MOVE may have changed logical order, not // physical plugin addresses. Normalize only in the NEW graph. @@ -1197,6 +1216,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Ownership stays with the control thread. The audio thread switches // only an immutable pointer at a callback boundary (never detach). auto staged = std::make_unique(); + staged->globalRackOverride=dryRoutingLab_.globalFxBypassFlag(); staged->slots = std::move (stagedSlots); staged->count = static_cast (snapshot.effects.size()); staged->hasRecallState = true; @@ -1794,13 +1814,15 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const auto mute=document.masterMute; const auto mono=document.masterMono; const bool monitoring=isMonitorEnabled(); - if(monitoring)setMonitorEnabled(false); + // Graph publication is a temporary PHYSICAL silence, not a user MUTE. + // Retain MAIN intent across the accepted ChannelId/FX rebind. + if(monitoring)setOutputMuted(true); 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); + setOutputMuted(false); // same user intent; safe original graph return applied; } acceptedWasapiBinding_=std::move(profile); @@ -2242,6 +2264,19 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return dryRoutingLab_.bypassNativeInsert(epoch,revision,id,slot, token,bypass); } + // Native global A/B is one DSP atomic, never N per-lane intents. All + // processors retain their slot bypass and latency-aligned fade envelopes. + bool setGlobalFxBypassed(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 || + independent_.active())return false; + return dryRoutingLab_.setGlobalFxBypassed(epoch,revision,bypass); + } + bool globalFxBypassed() const noexcept { + return dryRoutingLab_.globalFxBypassed(); + } bool bypassNativeFxRack(std::uint64_t epoch,std::uint64_t revision, armix::mixer::ChannelId id,bool bypass) noexcept { if(routeReconfiguring_.load(std::memory_order_acquire)|| @@ -2888,6 +2923,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Temporary publication silence never changes operator MONITOR or MAIN MUTE. // The DIRECT device fence and physical-output verification remain separate. std::atomic topologyPublicationMute_ { false }; + // Persistent in-process operator intent; independent of audio device epoch. + armix::device::OutputContinuityIntent mainOutputIntent_; std::atomic resumeMainAfterAsioReset_{false}; std::atomic monitor_ { false }, channelMute_ { false }, masterMute_ { false }, masterMono_ { false }, dryTest_ { false }; std::atomic masterGain_ { 1.f }, channelGain_ { 1.f }, channelPan_ { 0.f }; @@ -2978,9 +3015,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Some ASIO implementations announce a new callback before STOP. // Remember the existing MAIN intent before muting this epoch; only // the verified same-driver CONTROL rebind may resume it. No RT work. - if(monitor_.load(std::memory_order_acquire)) + if(mainOutputIntent_.desired()) { + mainOutputIntent_.deviceInterrupted(); resumeMainAfterAsioReset_.store(true,std::memory_order_release); - setOutputMuted(true); + } + setOutputMuted(true); // transient hardware gate, NOT an operator MUTE secondaryOutput_.invalidateSource(); // source clock may have changed dryRoutingLab_.prepareDevice(d); // exact active mask, before callback if (!independent_.active()) @@ -3034,8 +3073,13 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void audioDeviceStopped() override { - if(monitor_.exchange(false,std::memory_order_acq_rel)) + // Never turn a device STOP into a persistent MUTE. Display idle is not + // a device event, and even a genuine device STOP preserves desired MAIN. + if(mainOutputIntent_.desired()) { + mainOutputIntent_.deviceInterrupted(); resumeMainAfterAsioReset_.store(true,std::memory_order_release); + } + monitor_.store(false,std::memory_order_release); secondaryOutput_.invalidateSource(); // explicit reconnect required after device stop masterLoudness_.prepare (0.0); // clear validity across device epoch dryRoutingLab_.deviceStopped(); @@ -3070,6 +3114,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if(!slot.processor)continue; auto& bypass=graph.bypassEnvelope[physical]; bypass.request(graph.rackBypassed.load(std::memory_order_acquire) || + (graph.globalRackOverride && + graph.globalRackOverride->load(std::memory_order_acquire)) || graph.bypassFlags[physical].load(std::memory_order_acquire)); const bool blend=bypass.transitioning(); if(blend) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index cc6587749..02292934a 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -324,6 +324,8 @@ class LiveDryRoutingLab final { next->graphRevision=revision; next->prepared=std::make_unique(plan,Block::hardFrameLimit, juce::jlimit(32,Block::hardFrameLimit,deviceFrames)); + // Immutable pointer to one global RT atomic; prepared before publish. + next->prepared->bindGlobalRackOverride(&globalFxBypassed_); if(!next->prepared || next->prepared->capacity()==0) return "Cannot allocate routing workspace"; if(!next->prepared->setMainOutputPair( @@ -1236,7 +1238,8 @@ class LiveDryRoutingLab final { occupiedExternalCh1Fx>0,hw, frames,32u*1024u*1024u, nativePublisher_.acceptedRevision(),generation,epoch(), - true,nativePublisher_,nativeAccepted_,std::move(externalCh1)); + true,nativePublisher_,nativeAccepted_,std::move(externalCh1), + &globalFxBypassed_); if(!applied.ok() || generation!=epoch() || m4Revision!=revision()) return false; // selected M4 PCM owns the safe fallback nativeControlDirty_=false; // fresh accepted legacy/native control baseline @@ -1322,6 +1325,7 @@ class LiveDryRoutingLab final { } auto owner=std::make_shared( std::move(prepared)); + owner->bindGlobalRackOverride(&globalFxBypassed_); DynamicNativeSessionPublisher::FxPlan fx; fx.owner=std::static_pointer_cast(owner); fx.context=owner.get(); @@ -1370,6 +1374,7 @@ class LiveDryRoutingLab final { reply.error="NATIVE_FX_RACK_IDENTITY_OR_POSITION_REJECTED";return reply; } auto owner=std::make_shared(std::move(prepared)); + owner->bindGlobalRackOverride(&globalFxBypassed_); 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 { @@ -1436,6 +1441,31 @@ class LiveDryRoutingLab final { nativeAccepted_.fxOwners->externalChannel()==target && target==nativeAccepted_.graph.ids.inputs[0]; } + // Single global A/B override for M4 and the authoritative ChannelId PCM + // graph. Never rewrite saved rack/slot bypass flags or rebuild processors. + // A physical ACK requires an accepted CURRENT epoch/revision. + bool setGlobalFxBypassed(std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,bool bypass) noexcept { + if(!ready() || expectedEpoch!=epoch() || !expectedRevision)return false; + if(channelIdPhysicalPcmActive()) { + if(!nativeAccepted_.fxOwners || + nativeAccepted_.deviceEpoch!=expectedEpoch || + nativeAccepted_.pcmRevision!=expectedRevision)return false; + } else { + if(!hasExplicitRoute() || expectedRevision!=revision() || + !publisher_.controlPrepared(expectedEpoch,expectedRevision))return false; + } + globalFxBypassed_.store(bypass,std::memory_order_release); + return true; + } + // Pointer is assigned to the original CH1 Graph on CONTROL before + // publication. Lab lifetime exceeds every accepted audio callback lease. + const std::atomic* globalFxBypassFlag() const noexcept { + return &globalFxBypassed_; + } + bool globalFxBypassed() const noexcept { + return globalFxBypassed_.load(std::memory_order_acquire); + } bool bypassNativeRack(std::uint64_t epochAtEdit,std::uint64_t pcmRevision, armix::mixer::ChannelId target,bool bypass) noexcept { return nativeAccepted_.setFxRackBypass(nativePublisher_,epochAtEdit, @@ -1515,6 +1545,7 @@ class LiveDryRoutingLab final { } auto owner=std::make_shared( std::move(bank)); + owner->bindGlobalRackOverride(&globalFxBypassed_); DynamicNativeSessionPublisher::FxPlan fx; fx.owner=std::static_pointer_cast(owner); fx.context=owner.get(); @@ -1612,6 +1643,7 @@ class LiveDryRoutingLab final { } auto owner=std::make_shared( std::move(bank)); + owner->bindGlobalRackOverride(&globalFxBypassed_); DynamicNativeSessionPublisher::FxPlan fx; fx.owner=std::static_pointer_cast(owner); fx.context=owner.get(); @@ -1774,6 +1806,7 @@ class LiveDryRoutingLab final { reply.error="NATIVE_FX_LEASE_REJECTED";return reply; } auto owner=std::make_shared(std::move(bank)); + owner->bindGlobalRackOverride(&globalFxBypassed_); DynamicNativeSessionPublisher::FxPlan fx; fx.owner=std::static_pointer_cast(owner); fx.context=owner.get(); @@ -1851,6 +1884,7 @@ class LiveDryRoutingLab final { reply.error="NATIVE_TRACK_FX_RELEASE_REJECTED";return reply; } auto owner=std::make_shared(std::move(bank)); + owner->bindGlobalRackOverride(&globalFxBypassed_); DynamicNativeSessionPublisher::FxPlan fx; fx.owner=std::static_pointer_cast(owner); fx.context=owner.get(); @@ -1941,6 +1975,7 @@ class LiveDryRoutingLab final { reply.error="NATIVE_FX_LEASE_REJECTED";return reply; } auto owner=std::make_shared(std::move(bank)); + owner->bindGlobalRackOverride(&globalFxBypassed_); DynamicNativeSessionPublisher::FxPlan fx; fx.owner=std::static_pointer_cast(owner); fx.context=owner.get(); @@ -2016,6 +2051,7 @@ class LiveDryRoutingLab final { r.error="NATIVE_WIRE_FX_LEASE_REJECTED";return r; } auto owner=std::make_shared(std::move(nextBank)); + owner->bindGlobalRackOverride(&globalFxBypassed_); DynamicNativeSessionPublisher::FxPlan fx; fx.owner=std::static_pointer_cast(owner); fx.context=owner.get(); @@ -2088,6 +2124,7 @@ class LiveDryRoutingLab final { r.error="NATIVE_WIRE_FX_LEASE_REJECTED";return r; } auto owner=std::make_shared(std::move(bank)); + owner->bindGlobalRackOverride(&globalFxBypassed_); DynamicNativeSessionPublisher::FxPlan fx; fx.owner=std::static_pointer_cast(owner); fx.context=owner.get(); @@ -2519,6 +2556,7 @@ class LiveDryRoutingLab final { try { document.request.maxScratchBytes=32U*1024U*1024U; const auto previous=nativePublisher_.acceptedRevision(); + bank->bindGlobalRackOverride(&globalFxBypassed_); DynamicNativeSessionPublisher::FxPlan fx; fx.owner=std::static_pointer_cast(bank); fx.context=bank.get(); @@ -2877,6 +2915,7 @@ class LiveDryRoutingLab final { if(DynamicChannelFxLeaseBank::rebindSameFormat( newEpoch,revision+1,*nativeAccepted_.fxOwners,*owner)!= DynamicChannelFxLeaseBank::Fault::none)return false; + owner->bindGlobalRackOverride(&globalFxBypassed_); DynamicNativeSessionPublisher::FxPlan fx; fx.owner=owner;fx.context=owner.get(); fx.deviceEpoch=newEpoch;fx.graphRevision=revision+1; @@ -3457,6 +3496,9 @@ class LiveDryRoutingLab final { return juce::var(out.release()); } private: + // Never heap/lock in RT; every prepared graph references this same stable + // scalar. OFF means bypass all FX, while per-rack/slot states are untouched. + std::atomic globalFxBypassed_{false}; std::vector waitingAsioInputs_; std::vector externalOutputAssignments_; std::vector externalOutputVerified_; // per amplifier, CONTROL only diff --git a/src/Main.cpp b/src/Main.cpp index 3a9937b8d..b2fec3726 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -24,9 +24,11 @@ #if defined(_WIN32) #include "../engine/device/WasapiCapabilityProbe.h" #include +#include // SetWindowSubclass: observe REAL system resume without touching JUCE audio #include #if defined(_MSC_VER) #pragma comment(lib, "Psapi.lib") +#pragma comment(lib, "Comctl32.lib") #endif #endif #include "PluginCatalog.h" @@ -411,6 +413,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr { hotkeys_.detach(); // release global keys before the JUCE HWND disappears stopTimer(); +#if defined(_WIN32) + if (powerNoticeHwnd_) { + RemoveWindowSubclass(powerNoticeHwnd_, &ConsoleWindow::audioPowerWndProc, 0xA50); + powerNoticeHwnd_ = nullptr; + } +#endif orbit_.stop(); catalog_.onChanged = nullptr; closePluginEditor(); @@ -421,7 +429,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr 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(); + // A driver STOP may have gated hardware already. Preserve the + // operator's intended MAIN state in the crash-safe .smix checkpoint. + const bool resumeMain=engine_.wantsMainContinuation() && !operatorOutputMuted_; engine_.setOutputMuted(true); engine_.disconnectSecondaryOutput(); mixerSessionWorker_.finishForShutdown(logicalVendorEditor_.has_value()); @@ -432,7 +442,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (!updaterProbeMode_ && (static_cast(lab.getProperty("nativeChannelIdPcmActive",false)) || logicalMixer_.loaded())) { - const auto error=saveMixerSession(resumeMain); + const auto error=saveMixerSession(resumeMain,{},true); // shutdown checkpoint, not timer autosave if(error.isNotEmpty()) diagnostics_.record("DYNAMIC_MIXER_EXIT_SAVE_REJECTED",error); } @@ -639,6 +649,48 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } } bool deviceSettingsDirty_ = false; + // P0: last verified DIRECT WASAPI profile survives missing hardware; + // never replace it with JUCE's incidental default after hotplug. + std::optional verifiedWasapiSetup_; + armix::device::AudioContinuityRetry wasapiRecovery_; + std::uint64_t callbackWatchTickMs_=0, callbackProgressMs_=0; + std::uint64_t callbackWatchCount_=0; + bool directCallbackStalled_=false, feedbackMasterTripNotified_=false; +#if defined(_WIN32) + HWND powerNoticeHwnd_=nullptr; + bool actualSystemResumePending_=false; + bool actualSystemSuspendObserved_=false; + + static LRESULT CALLBACK audioPowerWndProc(HWND hwnd,UINT message,WPARAM wp, + LPARAM lp,UINT_PTR id,DWORD_PTR ref) { + auto* self=reinterpret_cast(ref); + if(message==WM_POWERBROADCAST && self) { + // Screen/monitor power events are NOT a system suspend. + // Never gate PCM, mutate MAIN intent, or reopen a healthy device. + if(wp==PBT_APMSUSPEND) + self->actualSystemSuspendObserved_=true; + else if(wp==PBT_APMRESUMEAUTOMATIC && + armix::device::AudioPowerPolicy::inspectDevice( + armix::device::NativePowerEvent::systemResume)) + self->actualSystemResumePending_=true; + } + if(message==WM_NCDESTROY) { + RemoveWindowSubclass(hwnd,&ConsoleWindow::audioPowerWndProc,id); + if(self && self->powerNoticeHwnd_==hwnd)self->powerNoticeHwnd_=nullptr; + } + return DefSubclassProc(hwnd,message,wp,lp); + } + void attachAudioPowerNotifications(void* nativeHandle) { + auto* hwnd=static_cast(nativeHandle); + if(!hwnd || hwnd==powerNoticeHwnd_)return; + if(powerNoticeHwnd_) + RemoveWindowSubclass(powerNoticeHwnd_,&ConsoleWindow::audioPowerWndProc,0xA50); + powerNoticeHwnd_=nullptr; + if(SetWindowSubclass(hwnd,&ConsoleWindow::audioPowerWndProc,0xA50, + reinterpret_cast(this))) + powerNoticeHwnd_=hwnd; + } +#endif bool unexpectedRouteNoticeSent_ = false; armix::device::DirectRestoreBackoff directRestore_; armix::diagnostics::CrackleEvidenceWindow crackleEvidence_; // 1Hz message-thread snapshots @@ -1647,7 +1699,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void fireNativeHotkey(const armix::hotkey::Mapping& mapping) { if(mapping.operation=="PANIC_MUTE") { - engine_.setOutputMuted(true); + // PANIC is explicit user intent, unlike device stop/restart. + operatorOutputMuted_=true; + engine_.setMonitorEnabled(false); + engine_.cancelAsioResetMonitorIntent(); + autoMainEpoch_=0; emitApprovedNativeSnapshot(); return; } @@ -1775,6 +1831,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr accepted.getDynamicObject()->setProperty("logicalMixer",logicalMixer_.readback()); } if(auto* obj=accepted.getDynamicObject()) { + // PCM-authoritative global A/B readback; not a mirrored button state. + obj->setProperty("globalFxBypassed",engine_.globalFxBypassed()); obj->setProperty("channelAppearance",channelAppearance_.snapshot(accepted.getProperty("graph",{}))); obj->setProperty("waitingAsioInputs",live.getProperty("waitingAsioInputs",0)); obj->setProperty("externalOutputs", @@ -1964,8 +2022,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr engine_.setChannelPan (valueNumber * 0.01f); else if (name == "mute" && channel == 1 && value.isBool()) engine_.setChannelMuted (bool (value)); - else if (name == "masterMute" && value.isBool()) + else if (name == "masterMute" && value.isBool()) { engine_.setMasterMuted (bool (value)); + if (!bool(value)) feedbackMasterTripNotified_=false; + } else if (name == "masterMono" && value.isBool()) engine_.setMasterMono (bool (value)); } @@ -2243,7 +2303,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Only same-epoch, driver-verified pins qualify (not stale .smix text). const bool requireInput=autoMainRequiresInput_ && !engine_.hasVerifiedExternalOutputIntent(); - if(engine_.liveOutputArmFault(requireInput).isNotEmpty())return; + const auto fault=engine_.liveOutputArmFault(requireInput); + if(fault.isNotEmpty()) { + protectKnownFeedbackLoop(fault); + return; + } autoMainCheckedRevision_=revision; engine_.setMonitorEnabled(true); autoMainEpoch_=0; @@ -2507,6 +2571,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr deviceSettingsDirty_=true; directRestore_.cancel(); asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); + // New explicit selection supersedes any old automatic reopen. + verifiedWasapiSetup_.reset(); + wasapiRecovery_.cancel(); diagnostics_.record("CUSTOM_AUDIO_APPLY_OK", typeName+" | "+juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); requestAutomaticMain(); @@ -3056,6 +3123,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr reply->setProperty("p88PerceptualAlignment",true); reply->setProperty("p89StereoRoomDepth",true); reply->setProperty("p90TrueExternalSpeaker",true); + // This capability is emitted only by the new reconciled DSP build. + // Older v11 P9.0 binaries must NOT be advertised as P9.1+P9.2. + reply->setProperty("p91p92MusicBassFoundation",true); } #elif defined(ARMIX_SONKU_EXPERIMENTAL_P89_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P89_NATIVE_RT if(processor && processor->preparedReflectionProfile()== @@ -3588,7 +3658,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return {}; } - juce::String saveMixerSession(bool resumeMain, const juce::File& exportFile={}) { + juce::String saveMixerSession(bool resumeMain, const juce::File& exportFile={}, + bool shutdownCheckpoint=false) { const bool automatic=exportFile==juce::File{}; ensureLogicalWorkspace(); if(mixerSessionWorker_.busy()||nativeShowBusy_||studioBackupBusy_|| @@ -3615,18 +3686,33 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } if(automatic&&mixerSessionRecoveryPending_) return "The retained mixer checkpoint is awaiting a verified device"; + // Auto-checkpoints must never replace an acknowledged .smix with a + // transient STOP/default/empty device state. Keep the last verified + // file on disk until the original physical route has returned. + if(automatic && !shutdownCheckpoint) { + auto* audio=engine_.devices().getCurrentAudioDevice(); + if(!audio || !audio->isOpen() || !engine_.directRouteAuthorized() || + engine_.mainInterruptedByDevice()) + return "Automatic checkpoint paused until audio device recovery"; + } 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); + // Temporary capture fence is NOT an operator MUTE. Keep the + // persisted MAIN desire intact across device loss during Save. + if(monitoring)engine_.setOutputMuted(true); 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); + engine_.setOutputMuted(false); // restore the existing operator intent if(error.isNotEmpty())return error; - if(automatic)doc.resumeMain=resumeMain; + // The periodic autosave caller passes false because speakers must + // be gated for snapshot capture. That does NOT mean the operator + // disabled MAIN. Capture desired intent independently of the gate. + if(automatic)doc.resumeMain=resumeMain || + (engine_.wantsMainContinuation() && !operatorOutputMuted_); doc.id=mixerSessionId_.isNotEmpty()?mixerSessionId_: juce::Uuid().toDashedString().toLowerCase(); // Shortcut entries are additive .smix data, never callback state. @@ -4724,6 +4810,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr action == "scanVst3" || action == "routingDryApply" || action == "routingFxBypass" || action == "routingNativeFxRackBypass" || + action == "routingGlobalFxBypass" || action == "routingNativeFxInsertBypass" || action == "routingFxRackBypass" || action == "nativeEqSetBand" || action == "nativeCompSet" || @@ -4756,6 +4843,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr browser_.emitEventIfBrowserIsVisible( "arMixRoutingFxRackAck",juce::var(ack.release())); } + if(action=="routingGlobalFxBypass" && browser_.loaded) { + auto ack=std::make_unique(); + ack->setProperty("requestId",args.getProperty("requestId",{})); + ack->setProperty("ok",false); + ack->setProperty("error",reason); + browser_.emitEventIfBrowserIsVisible( + "arMixGlobalFxAck",juce::var(ack.release())); + } if((action=="routingNativeFxRackBypass" || action=="routingNativeFxInsertBypass") && browser_.loaded) { auto ack=std::make_unique(); @@ -5510,8 +5605,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr static_cast(numeric)); else if(applied && name=="masterGain") engine_.setMasterGainDb(static_cast(numeric)); - else if(applied && name=="masterMute") + else if(applied && name=="masterMute") { engine_.setMasterMuted(bool(val)); + if(!bool(val))feedbackMasterTripNotified_=false; + } auto ack=std::make_unique(); ack->setProperty("requestId",requestId); ack->setProperty("ok",applied); @@ -5781,6 +5878,50 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(!ok)emitNotice("Live AUX send rejected; refresh accepted routing.",true); return; } + // The only global FX A/B authority. One atomic read by all active + // native PCM inserts (including BUS and FX_RETURN), with each plugin's + // existing latency-aligned bypass envelope. Never touch rack/slot + // settings, change topology or publish a competing M4 graph. + if(action=="routingGlobalFxBypass") { + const auto request=args.getProperty("requestId",{}).toString(); + const auto rawEpoch=args.getProperty("deviceEpoch",{}); + const auto rawRevision=args.getProperty("revision",{}); + const auto desired=args.getProperty("value",{}); + const auto accepted=approvedNativeSnapshot(); + const auto authority=accepted.getProperty("mixerSession",{}) + .getProperty("authority","").toString(); + std::uint64_t ep=0,rev=0; + const bool valid=request.startsWith("global-fx-") && + request.length()<=90 && desired.isBool() && + armix::console::approvedNativeId(rawEpoch,ep) && + armix::console::approvedNativeId(rawRevision,rev) && + (authority=="CHANNEL_ID"||authority=="M4") && + !acceptedControlRequests_.contains(request) && + !studioBackupBusy_&&!nativeShowBusy_ && + !deviceApply_.busy()&&!engine_.independentClockActive(); + bool applied=false; + if(valid) { + acceptedControlRequests_.add(request); + if(acceptedControlRequests_.size()>512) + acceptedControlRequests_.remove(0); + applied=engine_.setGlobalFxBypassed( + ep,rev,static_cast(desired)); + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("ok",applied); + ack->setProperty("bypassed",engine_.globalFxBypassed()); + ack->setProperty("error",applied?juce::String(): + "Global FX requires a current accepted physical PCM epoch/revision"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixGlobalFxAck",juce::var(ack.release())); + if(applied) { + diagnostics_.record("GLOBAL_FX_AB", + engine_.globalFxBypassed()?"BYPASS_ALL":"ENABLE_RESTORED"); + emitApprovedNativeSnapshot(); + } + 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 @@ -7247,6 +7388,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (arm && fault.isEmpty() && engine_.diagnosticRoute()==armix::diagnostics::Route::normal) fault=engine_.liveOutputArmFault(); + if (fault.isNotEmpty())protectKnownFeedbackLoop(fault); if (fault.isEmpty()) { operatorOutputMuted_=!arm; // an explicit user control, not setup mute autoMainEpoch_=0; @@ -7318,7 +7460,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const bool retained=engine_.hasRetainedNativeSession(); const bool silent=!mixerSessionRecoveryPending_ && engine_.hasPristineSilentMixerAwaitingAsio(); - if(epoch==asioRecoveryEpoch_ || (!retained && !silent) || + auto* current=engine_.devices().getCurrentAudioDevice(); + const bool missingDevice=!current || !current->isOpen(); + if((epoch==asioRecoveryEpoch_ && !missingDevice && + !directCallbackStalled_ && !engine_.mainInterruptedByDevice()) || + (!retained && !silent) || deviceApply_.busy() || (audioSetupWindow_ && audioSetupWindow_->isVisible()) || nativeShowBusy_ || studioBackupBusy_ || mixerSessionWorker_.busy() || catalog_.busy() || engine_.isGraphSwitchPending() || engine_.independentClockActive() || @@ -7327,6 +7473,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(device) { if(device->getTypeName()!="ASIO" || !engine_.sameRetainedAsioDriver())return; + if(device->isOpen() && !directCallbackStalled_ && + engine_.directRouteAuthorized() && engine_.hasBoundMixerRoute()) { + // Do not reopen a healthy ASIO stream on display idle. + if(engine_.mainInterruptedByDevice() && + engine_.wantsMainContinuation() && !operatorOutputMuted_) + requestAutomaticMain(false); + asioRecoveryEpoch_=epoch; + return; + } } else if(!engine_.selectedRetainedAsioDriverForReopen()) { // The device pointer disappeared: never open an unapproved or // guessed driver name, even if ASIO4ALL happens to be installed. @@ -7338,7 +7493,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr auto applying=deviceApply_.tryBegin( armix::device::NativeDeviceApplyCoordinator::Purpose::asioRecovery); if(!applying)return; - if(!device || !device->isOpen() || + if(!device || !device->isOpen() || directCallbackStalled_ || device->getActiveOutputChannels().countNumberOfSetBits()<2) { // A missing, closed or output-less ASIO device requires a vendor call. // Never reopen it repeatedly on each UI timer tick. @@ -7356,7 +7511,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr asioRecoveryGate_.driverTransaction(now); if(!device)diagnostics_.record("ASIO_DEVICE_MISSING", "Reopening previously approved registered ASIO driver; no fallback"); - const auto error=openSelectedAudioDevice("ASIO",setup,true); + const auto error=openSelectedAudioDevice("ASIO",setup,true); // force fresh driver stream, not a no-op same setup asioRecoveryGate_.carryInternalEpoch(engine_.dryRoutingLabEpoch()); device=engine_.devices().getCurrentAudioDevice(); if(error.isNotEmpty() || !device || !device->isOpen()) { @@ -7434,24 +7589,216 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr asioRecoveryGate_.recovered(); mixerSessionStatus_="RESTORED_MUTED"; mixerSessionError_.clear(); - if(engine_.takeAsioResetMonitorIntent())requestAutomaticMain(false); + const bool previousMain=engine_.takeAsioResetMonitorIntent(); + if((previousMain || engine_.wantsMainContinuation()) && !operatorOutputMuted_) + requestAutomaticMain(false); if(engine_.isMonitorEnabled())mixerSessionStatus_="RESTORED_MONITORING"; diagnostics_.record("ASIO_REATTACHED","Verified driver and current MAIN pair"); emitApprovedNativeSnapshot(); } + // Load only the previously committed device XML, even when hardware + // is absent at cold start. A JUCE default is never an approved profile. + void rememberSavedWasapiProfile(const juce::XmlElement* saved) { + if(!saved || saved->getTagName()!="DEVICESETUP" || + saved->getStringAttribute("deviceType")!="Windows Audio")return; + juce::AudioDeviceManager::AudioDeviceSetup setup; + setup.inputDeviceName=saved->getStringAttribute("audioInputDeviceName"); + setup.outputDeviceName=saved->getStringAttribute("audioOutputDeviceName"); + if(setup.outputDeviceName.isEmpty())return; + setup.sampleRate=saved->getDoubleAttribute("audioDeviceRate",0.); + setup.bufferSize=saved->getIntAttribute("audioDeviceBufferSize",0); + if(saved->hasAttribute("audioDeviceInChans")) { + setup.useDefaultInputChannels=false; + setup.inputChannels.parseString(saved->getStringAttribute("audioDeviceInChans"),2); + } + if(saved->hasAttribute("audioDeviceOutChans")) { + setup.useDefaultOutputChannels=false; + setup.outputChannels.parseString(saved->getStringAttribute("audioDeviceOutChans"),2); + } + verifiedWasapiSetup_=std::move(setup); + } + + // Read back both physical device names AND actual pin masks. Backend + // name alone does not prove a Windows default-endpoint switch retained + // the selected speakers. A default pin mask becomes fixed only after the + // user's device actually opens and is verified, not at a missing-device + // startup. Never route audio to another Windows Audio endpoint. + static bool matchesPinnedWasapiReadback( + const juce::AudioDeviceManager::AudioDeviceSetup& wanted, + const juce::AudioDeviceManager::AudioDeviceSetup& actual, + juce::AudioIODevice* device) noexcept { + return device && device->isOpen() && + wanted.outputDeviceName.isNotEmpty() && + actual.inputDeviceName==wanted.inputDeviceName && + actual.outputDeviceName==wanted.outputDeviceName && + device->getActiveOutputChannels().countNumberOfSetBits()>=2 && + (wanted.useDefaultInputChannels || + device->getActiveInputChannels()==wanted.inputChannels) && + (wanted.useDefaultOutputChannels || + device->getActiveOutputChannels()==wanted.outputChannels); + } + + // Recovery only for a verified saved Windows Audio endpoint; no + // fallback, no graph CLEAR, no attempt while an explicit device dialog + // owns the lifecycle. The current native graph remains the PCM authority. + void rememberVerifiedWasapiSetup() { + if(!audioEngineStarted_ || deviceApply_.busy() || + engine_.independentClockActive() || + engine_.diagnosticRoute()!=armix::diagnostics::Route::normal || + !engine_.directRouteAuthorized() || + engine_.hasRetainedUnboundMixer())return; + auto& manager=engine_.devices(); + auto* device=manager.getCurrentAudioDevice(); + if(!device || !device->isOpen())return; + if(manager.getCurrentAudioDeviceType()!="Windows Audio" || + device->getTypeName()!="Windows Audio") { + // An explicitly approved ASIO replaces the old WASAPI intent. + verifiedWasapiSetup_.reset(); + wasapiRecovery_.cancel(); + return; + } + juce::AudioDeviceManager::AudioDeviceSetup actual; + manager.getAudioDeviceSetup(actual); + if(!verifiedWasapiSetup_ && actual.outputDeviceName.isNotEmpty() && + device->getActiveOutputChannels().countNumberOfSetBits()>=2) + verifiedWasapiSetup_=actual; + if(verifiedWasapiSetup_ && + matchesPinnedWasapiReadback(*verifiedWasapiSetup_,actual,device)) { + // JUCE "default channel" requests are resolved now. Remember + // exact physical masks so later driver re-enumeration cannot + // silently substitute another stereo output or microphone. + auto& pinned=*verifiedWasapiSetup_; + if(pinned.useDefaultInputChannels) { + pinned.inputChannels=device->getActiveInputChannels(); + pinned.useDefaultInputChannels=false; + } + if(pinned.useDefaultOutputChannels) { + pinned.outputChannels=device->getActiveOutputChannels(); + pinned.useDefaultOutputChannels=false; + } + if(!directCallbackStalled_)wasapiRecovery_.recovered(); + } + } + + void observeNativeCallbackHeartbeat() { + const auto now=monotonicMilliseconds(); + const auto count=engine_.directCallbackCount(); + // A long message-loop pause (including true laptop sleep) is NOT + // proof of a dead audio callback. Restart the observation window. + if(callbackWatchTickMs_==0 || now1500 || count!=callbackWatchCount_) { + callbackProgressMs_=now; + directCallbackStalled_=false; + } else { + auto* device=engine_.devices().getCurrentAudioDevice(); + directCallbackStalled_=device && device->isOpen() && + engine_.directRouteAuthorized() && !engine_.independentClockActive() && + engine_.hasBoundMixerRoute() && now>=callbackProgressMs_ && + now-callbackProgressMs_>=3500; + } + callbackWatchTickMs_=now; + callbackWatchCount_=count; + } + + void serviceWasapiDeviceContinuity() { + if(!audioEngineStarted_ || !verifiedWasapiSetup_ || + engine_.independentClockActive() || deviceApply_.busy() || + (audioSetupWindow_ && audioSetupWindow_->isVisible()) || + nativeShowBusy_ || studioBackupBusy_ || mixerSessionWorker_.busy() || + catalog_.busy() || engine_.isGraphSwitchPending() || + engine_.diagnosticRoute()!=armix::diagnostics::Route::normal)return; + auto& manager=engine_.devices(); + auto* device=manager.getCurrentAudioDevice(); + juce::AudioDeviceManager::AudioDeviceSetup live; + manager.getAudioDeviceSetup(live); + const bool expected=device && device->isOpen() && + manager.getCurrentAudioDeviceType()=="Windows Audio" && + device->getTypeName()=="Windows Audio" && engine_.directRouteAuthorized() && + !engine_.hasRetainedUnboundMixer() && + matchesPinnedWasapiReadback(*verifiedWasapiSetup_,live,device); + if(expected && !directCallbackStalled_) { + wasapiRecovery_.recovered(); + // A short JUCE STOP/START must not leave MAIN latched off. + if(engine_.mainInterruptedByDevice() && engine_.wantsMainContinuation() && + !operatorOutputMuted_)requestAutomaticMain(false); + return; + } + // Healthy intentionally selected ASIO is never replaced by an old + // WASAPI profile. Nor is an unknown fallback given sound permission. + if(expected==false && device && device->isOpen() && + manager.getCurrentAudioDeviceType()!="Windows Audio" && + engine_.directRouteAuthorized())return; + const auto now=monotonicMilliseconds(); + wasapiRecovery_.fault(now); + if(!wasapiRecovery_.due(now))return; + auto applying=deviceApply_.tryBegin( + armix::device::NativeDeviceApplyCoordinator::Purpose::wasapiRecovery); + if(!applying)return; + const auto wanted=*verifiedWasapiSetup_; + engine_.beginManualAudioSetup(true); + auto error=openSelectedAudioDevice("Windows Audio",wanted, + !device || !device->isOpen() || directCallbackStalled_); + if(error.isEmpty()) { + auto* opened=manager.getCurrentAudioDevice(); + juce::AudioDeviceManager::AudioDeviceSetup actual; + manager.getAudioDeviceSetup(actual); + if(!opened || !opened->isOpen() || + manager.getCurrentAudioDeviceType()!="Windows Audio" || + actual.inputDeviceName!=wanted.inputDeviceName || + actual.outputDeviceName!=wanted.outputDeviceName || + !matchesPinnedWasapiReadback(wanted,actual,opened)) + error="Previously verified WASAPI endpoints are not available"; + else if(!finishAudioSetupAndRecoverMixer()) + error="WASAPI reopened, but retained native mixer binding is not ready"; + } + if(error.isEmpty()) { + wasapiRecovery_.recovered(); + directCallbackStalled_=false; + callbackProgressMs_=monotonicMilliseconds(); + if(engine_.wantsMainContinuation() && !operatorOutputMuted_) + requestAutomaticMain(false); + diagnostics_.record("WASAPI_CONTINUITY_RESTORED", + "Exact saved endpoint and native mixer verified; MAIN intent preserved"); + emitApprovedNativeSnapshot(); + } else { + wasapiRecovery_.failed(now); + diagnostics_.record("WASAPI_CONTINUITY_RETRY",error); + // Do not persist the temporary null/default manager setup. + } + } + + // Only a positively identified virtual-cable self-loop trips the true + // MASTER mute; an ordinary device/driver fault never touches that fader. + // Internal graph cycles are rejected by the existing native DAG compiler. + void protectKnownFeedbackLoop(const juce::String& fault) { + if(!fault.contains("VB-Cable capture/playback self-loop"))return; + engine_.setMasterMuted(true); + if(!feedbackMasterTripNotified_) { + feedbackMasterTripNotified_=true; + diagnostics_.record("MASTER_FEEDBACK_AUTO_MUTE", + "Identical VB-Cable capture/playback route detected"); + emitNotice("Feedback loop detected. MASTER MUTE engaged; correct the input/output route.",true); + emitApprovedNativeSnapshot(); + } + } + void changeListenerCallback (juce::ChangeBroadcaster*) override { if(deviceApply_.busy())return; // synchronous transaction owns recovery - // Save device state only after a real change, not on every 3-second tick. - deviceSettingsDirty_ = true; + // An OS/JUCE device notification is NOT an operator configuration + // edit. A missing device or temporary default must never overwrite + // the last verified audio-devices.xml selection. // 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"); + if(engine_.wantsMainContinuation() && !operatorOutputMuted_) + requestAutomaticMain(false); // same verified pair only + diagnostics_.record("DYNAMIC_MIXER_REATTACHED", + "Verified WASAPI callback epoch; previous MAIN intent retained"); emitApprovedNativeSnapshot(); } } @@ -7462,8 +7809,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // A startup splash can delay HWND creation; attach once the real JUCE // peer exists. Never install a low-level keyboard hook. if (!updaterProbeMode_) - if(auto* peer=getPeer()) + if(auto* peer=getPeer()) { hotkeys_.attach(peer->getNativeHandle()); + attachAudioPowerNotifications(peer->getNativeHandle()); + } #endif if(deviceApply_.busy())return; // a vendor modal loop may re-enter JUCE // Always disabled unless the user explicitly starts a bounded trace. @@ -7528,6 +7877,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } auto saved = juce::XmlDocument::parse ( machineSettingsDirectory().getChildFile ("audio-devices.xml")); + rememberSavedWasapiProfile(saved.get()); startupError_ = engine_.start (saved.get()); engine_.devices().addChangeListener (this); diagnostics_.record ("STARTUP", @@ -7585,7 +7935,21 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr juce::Time::getMillisecondCounter()-startupFxGuardTick_>=15000u) { if(startupFxGuard_->complete())startupFxGuard_.reset(); } + observeNativeCallbackHeartbeat(); +#if defined(_WIN32) + if(actualSystemResumePending_) { + actualSystemResumePending_=false; + diagnostics_.record("WINDOWS_SYSTEM_RESUME", + actualSystemSuspendObserved_?"Real suspend/resume":"Resume event"); + actualSystemSuspendObserved_=false; + // Do not restart a healthy audio device after a display-only event. + if(engine_.mainInterruptedByDevice() || !engine_.directRouteAuthorized()) + wasapiRecovery_.endpointReturned(monotonicMilliseconds()); + } +#endif serviceAsioMixerRestart(); + serviceWasapiDeviceContinuity(); + rememberVerifiedWasapiSetup(); // ONE actionable notice per unexpected DIRECT reroute. The audio // callback has already zero-filled output atomically; status, log and // WebView notifications belong only on this JUCE control timer. @@ -7669,15 +8033,17 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (deviceSettingsDirty_) { - deviceSettingsDirty_ = false; - // DeviceManager signals even when a temporary capture-only / - // output-only route is selected. Never persist that test route. + // Keep a newly approved device selection pending while the + // driver is temporarily closed; never serialize JUCE's empty + // default and never silently discard the unsaved user binding. + auto* activeDevice=engine_.devices().getCurrentAudioDevice(); if (!engine_.hasTemporaryDiagnosticDevice() && !engine_.independentClockActive() && engine_.directRouteAuthorized() && !engine_.hasRetainedUnboundMixer() && (audioSetupWindow_ == nullptr || !audioSetupWindow_->isVisible()) && - engine_.devices().getCurrentAudioDevice() != nullptr) + activeDevice != nullptr && activeDevice->isOpen()) if (auto xml = engine_.devices().createStateXml()) { + deviceSettingsDirty_ = false; const auto text = xml->toString(); if (text != lastAudioXml_) { diff --git a/src/NativeDeviceApplyCoordinator.h b/src/NativeDeviceApplyCoordinator.h index 404050d22..05be3e717 100644 --- a/src/NativeDeviceApplyCoordinator.h +++ b/src/NativeDeviceApplyCoordinator.h @@ -16,7 +16,7 @@ class NativeDeviceApplyCoordinator final { public: // Every possible JUCE driver mutation uses the same control-thread gate: // explicit UI Apply, native modal selector, and bounded ASIO recovery. - enum class Purpose : std::uint8_t { none, explicitApply, setupDialog, asioRecovery }; + enum class Purpose : std::uint8_t { none, explicitApply, setupDialog, asioRecovery, wasapiRecovery }; class Lease final { public: @@ -314,7 +314,9 @@ class NativeDeviceApplyCoordinator final { if(record)record("CLOSE_PREVIOUS | "+manager.getCurrentAudioDeviceType()); manager.closeAudioDevice(); if(record)record("OPEN_SELECTED | "+backend); - return manager.initialise(2,2,xml.get(),false); + // OUTPUT ONLY must not invent a microphone or require absent IN pins. + return manager.initialise(setup.inputDeviceName.isEmpty()?0:2, + 2,xml.get(),false); } private: diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 02a428f75..5a87e39dd 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -985,7 +985,8 @@ test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ assert.match(bridge,/const virtualCableFeedbackPair=/); const native=read("src/Main.cpp"); assert.match(native,/const bool requireInput=autoMainRequiresInput_ &&\s*!engine_\.hasVerifiedExternalOutputIntent\(\)/); - assert.match(native,/if\(engine_\.liveOutputArmFault\(requireInput\)\.isNotEmpty\(\)\)return;/); + assert.ok(native.includes("const auto fault=engine_.liveOutputArmFault(requireInput);")); + assert.ok(native.includes("protectKnownFeedbackLoop(fault);")); assert.match(native,/autoMainEpoch_!=engine_\.dryRoutingLabEpoch\(\)/); }); test("single /preview/ GUI: channel IN, actual OUT and correlated device safety ACK",()=>{ diff --git a/tests/audio_continuity_contract_test.mjs b/tests/audio_continuity_contract_test.mjs new file mode 100644 index 000000000..1a9cd9783 --- /dev/null +++ b/tests/audio_continuity_contract_test.mjs @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +const read=p=>readFileSync(new URL('../'+p,import.meta.url),'utf8'); +const main=read('src/Main.cpp'); +const engine=read('src/LiveAudioEngine.h'); +const policy=read('engine/device/AudioContinuityPolicy.h'); +const coordinator=read('src/NativeDeviceApplyCoordinator.h'); +const cmake=read('CMakeLists.txt'); + +test('display sleep never changes logical mixer intent or device configuration',()=>{ + assert.match(main,/WM_POWERBROADCAST/); + assert.match(main,/PBT_APMSUSPEND/); + assert.match(main,/PBT_APMRESUMEAUTOMATIC/); + assert.match(main,/Screen\/monitor power events are NOT a system suspend/); + assert.match(policy,/displayOff, displayOn, systemSuspend, systemResume/); + assert.match(policy,/changeMixerIntent\(NativePowerEvent\)/); + assert.match(engine,/mainOutputIntent_\.operatorRequested\(value\)/); + assert.match(engine,/mainOutputIntent_\.deviceInterrupted\(\)/); + const listener=main.split('void changeListenerCallback (juce::ChangeBroadcaster*) override')[1] + .split('void timerCallback() override')[0]; + assert.doesNotMatch(listener,/deviceSettingsDirty_\s*=\s*true/); +}); + +test('reconnect is to the exact previously selected endpoint without silent fallback',()=>{ + assert.match(main,/rememberSavedWasapiProfile\(saved.get\(\)\)/); + assert.match(main,/verifiedWasapiSetup_/); + assert.match(main,/serviceWasapiDeviceContinuity\(\)/); + assert.match(main,/finishAudioSetupAndRecoverMixer\(\)/); + assert.match(main,/!device \|\| !device->isOpen\(\) \|\| directCallbackStalled_/); + assert.match(main,/actual\.outputDeviceName!=wanted\.outputDeviceName/); + assert.match(main,/actual\.inputDeviceName!=wanted\.inputDeviceName/); + assert.match(coordinator,/wasapiRecovery/); + assert.match(coordinator,/setup\.inputDeviceName\.isEmpty\(\)\?0:2/); + assert.match(main,/if\(powerNoticeHwnd_\)/); + assert.doesNotMatch(main,/new juce::AudioDeviceManager/); +}); + +test('master mute is only automatic for a positively identified feedback self loop',()=>{ + const protector=main.split('void protectKnownFeedbackLoop(const juce::String& fault)')[1] + .split('void changeListenerCallback')[0]; + assert.match(protector,/VB-Cable capture\/playback self-loop/); + assert.match(protector,/engine_\.setMasterMuted\(true\)/); + assert.doesNotMatch(protector,/engine_\.setOutputMuted\(true\)/); + const stopped=engine.split('void audioDeviceStopped() override')[1] + .split('static void renderOriginalChannelOneGraph')[0]; + assert.doesNotMatch(stopped,/setMasterMuted/); + assert.match(engine,/mainOutputIntent_\.deviceInterrupted\(\)/); +}); + + +test('WASAPI recovery fails closed against substituted endpoint names or pin masks',()=>{ + const comparison=main.split('static bool matchesPinnedWasapiReadback(')[1] + .split('void rememberVerifiedWasapiSetup()')[0]; + assert.match(comparison,/actual\.inputDeviceName==wanted\.inputDeviceName/); + assert.match(comparison,/actual\.outputDeviceName==wanted\.outputDeviceName/); + assert.match(comparison,/getActiveInputChannels\(\)==wanted\.inputChannels/); + assert.match(comparison,/getActiveOutputChannels\(\)==wanted\.outputChannels/); + const reconnect=main.split('void serviceWasapiDeviceContinuity()')[1] + .split('void protectKnownFeedbackLoop(')[0]; + assert.match(reconnect,/matchesPinnedWasapiReadback\(\*verifiedWasapiSetup_,live,device\)/); + assert.match(reconnect,/matchesPinnedWasapiReadback\(wanted,actual,opened\)/); + const remember=main.split('void rememberVerifiedWasapiSetup()')[1] + .split('void observeNativeCallbackHeartbeat()')[0]; + assert.match(remember,/pinned\.useDefaultOutputChannels=false/); + assert.match(remember,/pinned\.useDefaultInputChannels=false/); +}); + +test('session capture and shutdown keep requested MAIN through a device STOP',()=>{ + const capture=main.split('juce::String saveMixerSession(bool resumeMain')[1] + .split('const auto canonical=')[0]; + assert.match(capture,/if\(monitoring\)engine_\.setOutputMuted\(true\)/); + assert.match(capture,/engine_\.setOutputMuted\(false\)/); + assert.doesNotMatch(capture,/engine_\.setMonitorEnabled\(/); + const shutdown=main.split('~ConsoleWindow() override')[1] + .split('engine_.stop();')[0]; + assert.match(shutdown,/engine_\.wantsMainContinuation\(\) && !operatorOutputMuted_/); + assert.match(shutdown,/saveMixerSession\(resumeMain,\{\},true\)/); +}); + +test('automatic checkpoints cannot overwrite saved MAIN and device binding during STOP',()=>{ + const save=main.split('juce::String saveMixerSession(bool resumeMain')[1] + .split('void openMixerFile(')[0]; + assert.match(save,/!audio \|\| !audio->isOpen\(\)/); + assert.match(save,/if\(automatic && !shutdownCheckpoint\)/); + assert.match(save,/engine_\.mainInterruptedByDevice\(\)/); + assert.match(save,/doc\.resumeMain=resumeMain \|\|/); + assert.match(save,/engine_\.wantsMainContinuation\(\) && !operatorOutputMuted_/); + const persistence=main.split('if (deviceSettingsDirty_)')[1] + .split('if (timerTicks_')[0]; + assert.match(persistence,/activeDevice != nullptr && activeDevice->isOpen\(\)/); + assert.match(persistence,/deviceSettingsDirty_ = false/); + assert.ok(persistence.indexOf('deviceSettingsDirty_ = false')> + persistence.indexOf('activeDevice->isOpen()'), + 'Do not consume a pending device profile while its driver is absent'); +}); + +test('bounded retry + callback watchdog cannot spin in realtime PCM',()=>{ + assert.match(policy,/30000ull/); + assert.match(main,/callbackWatchTickMs_/); + assert.match(main,/now-callbackProgressMs_>=3500/); + assert.match(main,/now-callbackWatchTickMs_>1500/); + assert.match(main,/AudioContinuityRetry wasapiRecovery_/); + assert.match(cmake,/P0DisplayIdlePreservesAudioAndDeviceRecoveryIntent/); +}); diff --git a/tests/audio_continuity_policy_test.cpp b/tests/audio_continuity_policy_test.cpp new file mode 100644 index 000000000..6b7501a7f --- /dev/null +++ b/tests/audio_continuity_policy_test.cpp @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/device/AudioContinuityPolicy.h" +#include +#include + +int main() { + using namespace armix::device; + static_assert(!AudioPowerPolicy::inspectDevice(NativePowerEvent::displayOff)); + static_assert(!AudioPowerPolicy::inspectDevice(NativePowerEvent::displayOn)); + static_assert(!AudioPowerPolicy::inspectDevice(NativePowerEvent::systemSuspend)); + static_assert(AudioPowerPolicy::inspectDevice(NativePowerEvent::systemResume)); + static_assert(!AudioPowerPolicy::changeMixerIntent(NativePowerEvent::systemResume)); + + OutputContinuityIntent output; + output.operatorRequested(true); + output.deviceInterrupted(); + assert(output.desired() && output.interrupted()); + output.deviceInterrupted(); // repeated callback STOP is idempotent + assert(output.desired()); + output.deviceRecovered(); + assert(output.desired() && !output.interrupted()); + output.deviceInterrupted(); + output.operatorRequested(false); // explicit operator MUTE wins + assert(!output.desired() && !output.interrupted()); + output.deviceRecovered(); + assert(!output.desired()); // cannot silently undo explicit MUTE + + AudioContinuityRetry retry; + retry.fault(100); + const auto generation=retry.generation(); + assert(!retry.due(449) && retry.due(450)); + retry.failed(450); + assert(!retry.due(1449) && retry.due(1450)); + retry.failed(1450); + assert(retry.due(4450)); + retry.failed(4450); + assert(retry.due(12450)); + retry.failed(12450); + assert(retry.due(42450)); // bounded cadence but never permanently exhausted + retry.endpointReturned(42500); + assert(!retry.due(42849) && retry.due(42850)); + retry.recovered(); + assert(!retry.pending() && retry.generation()>generation); + retry.fault(50000); + assert(retry.pending()); + retry.cancel(); + assert(!retry.pending()); +} diff --git a/tests/direct_restore_recovery_contract_test.mjs b/tests/direct_restore_recovery_contract_test.mjs index f91ce6bc8..25bc60235 100644 --- a/tests/direct_restore_recovery_contract_test.mjs +++ b/tests/direct_restore_recovery_contract_test.mjs @@ -81,7 +81,18 @@ test('healthy independent sessions never arm restoration; setup can replace miss assert.match(engine,/bool abandonPendingDirectRestoreForSetup\(\)/); assert.match(engine,/deviceManager_\.addAudioCallback \(this\)/); assert.match(main,/DIRECT_RESTORE_ABANDON/); - assert.match(main,/engine_\.devices\(\)\.getCurrentAudioDevice\(\) != nullptr/); + // A selected JUCE device pointer can survive while its driver is CLOSED. + // Persist only once a physical, authorized native device is actually open. + const persistence=main.split('if (deviceSettingsDirty_)')[1] + .split('// A hidden/reloading WebView')[0]; + assert.ok(persistence, 'device-profile persistence path must exist'); + assert.match(persistence, /activeDevice=engine_\.devices\(\)\.getCurrentAudioDevice\(\)/); + assert.match(persistence, /engine_\.directRouteAuthorized\(\)/); + assert.match(persistence, /!engine_\.hasRetainedUnboundMixer\(\)/); + assert.match(persistence, /activeDevice != nullptr && activeDevice->isOpen\(\)/); + assert.ok(persistence.indexOf('deviceSettingsDirty_ = false') > + persistence.indexOf('activeDevice->isOpen()'), + 'pending user binding must survive a temporary closed driver'); assert.match(main,/Choose a replacement in AUDIO SETUP/); }); diff --git a/tests/live_channel_fx_graph_test.cpp b/tests/live_channel_fx_graph_test.cpp index bed90b133..7437310bb 100644 --- a/tests/live_channel_fx_graph_test.cpp +++ b/tests/live_channel_fx_graph_test.cpp @@ -2558,6 +2558,40 @@ int main(int argc,char** argv) { assert(moved->setRackBypass(0,false)); assert(!moved->insertBypassed(0,0)); // saved ON restored } + // One global physical A/B atomic bypasses INPUT and BUS processors + // together, without editing rack/slot state, adding an audio callback + // allocation, or changing fader/WIRE/PAN. Each plugin uses its existing + // latency-safe smooth wet/dry bypass envelope on the same PCM graph. + { + auto graph=makeGraph(2.f,3.f); + std::atomic globalOff{false}; + graph->bindGlobalRackOverride(&globalOff); + std::array source{},silent{},left{},right{}; + source.fill(.4f); + const float* pins[]{source.data(),silent.data(),silent.data()}; + const auto render80=[&]() { + const auto allocated=heapCalls.load(std::memory_order_relaxed); + for(int i=0;i<80;++i) + assert(graph->process(pins,3,left.data(),right.data(),8)); + assert(heapCalls.load(std::memory_order_relaxed)==allocated); + return left[7]; + }; + const float wet=render80(); + const bool rackBefore=graph->rackBypassed(0); + const bool slotBefore=graph->insertBypassed(0,0); + globalOff.store(true,std::memory_order_release); + const float dry=render80(); // 640 samples, beyond 8 ms fade + constexpr float center=.7071067811865475f; + assert(std::abs(dry-.4f*.5f*center)<.001f); + assert(wet>dry*3.f); + assert(graph->rackBypassed(0)==rackBefore); + assert(graph->insertBypassed(0,0)==slotBefore); + globalOff.store(false,std::memory_order_release); + const float wetRestored=render80(); + assert(std::abs(wetRestored-wet)<.001f); + assert(graph->rackBypassed(0)==rackBefore); + assert(graph->insertBypassed(0,0)==slotBefore); + } // 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. diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index 18da83a06..d3b86326a 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -209,7 +209,8 @@ test('DEVICE1 existing matrix drives real JUCE manager with gated native readbac assert.match(native,/openSelectedAudioDevice\(typeName,candidate\)/); assert.match(native,/openSelectedAudioDevice\(previousType,before\)/); assert.match(coordinator,/setAudioDeviceSetup\(setup,true\)/); - assert.match(coordinator,/manager\.initialise\(2,2,xml\.get\(\),false\)/); + // OUTPUT ONLY has no physical microphone; do not invent input pins. + assert.ok(coordinator.includes('manager.initialise(setup.inputDeviceName.isEmpty()?0:2,')); assert.match(coordinator,/manager\.closeAudioDevice\(\);[\s\S]*manager\.initialise/); assert.doesNotMatch(coordinator,/manager\.setCurrentAudioDeviceType\(/); assert.match(native,/beginManualAudioSetup\(\)/); @@ -670,7 +671,10 @@ test('ASIO restart cannot strand MAIN off after temporary graph readiness faults assert.ok(arm.indexOf('liveOutputArmFault(autoMainRequiresInput_)')< arm.indexOf('autoMainCheckedRevision_=revision;'),'only a verified ARM consumes the revision'); const begin=engine.slice(engine.indexOf('void audioDeviceAboutToStart ('),engine.indexOf('void audioDeviceStopped()')); - assert.match(begin,/if\(monitor_\.load\(std::memory_order_acquire\)\)/); + // Operator-approved MAIN intent survives callback STOP, even though the + // hardware monitor bit is forcibly gated during a device restart. + assert.ok(begin.includes('if(mainOutputIntent_.desired())')); + assert.ok(begin.includes('mainOutputIntent_.deviceInterrupted()')); assert.match(begin,/resumeMainAfterAsioReset_\.store\(true/); assert.ok(begin.indexOf('resumeMainAfterAsioReset_.store(true'){ + const slider=row.querySelector('input.center-pan'); + slider.value=String(value); + slider.dispatchEvent(new Event('input',{bubbles:true})); + slider.dispatchEvent(new Event('change',{bubbles:true})); + const text=row.querySelector('output'), r=text.getBoundingClientRect(), + track=row.querySelector('.pan-control').getBoundingClientRect(), + strip=row.closest('.strip').getBoundingClientRect(); + return {text:text.textContent, clipped:text.scrollWidth>text.clientWidth+1, + overflow:r.right>strip.right+0.8, right:r.right, strip:strip.right, + font:parseFloat(getComputedStyle(text).fontSize), + panFont:parseFloat(getComputedStyle(row.querySelector('.pan-icon')).fontSize), + gap:r.left-track.right,sliderWidth:track.width,readoutWidth:r.width, + centerError:Math.abs((track.left+track.right)/2-(strip.left+strip.right)/2), + sliderCenter:(track.left+track.right)/2,stripCenter:(strip.left+strip.right)/2}; + }""", value) + + +def rack(page, channel): + return page.locator(f'#tracks .strip[data-id="{channel}"] .fx-section').evaluate( + """el=>({rack:el.dataset.fxChainEnabled,global:el.dataset.globalFxEnabled, + slots:[...el.querySelectorAll('.fxslot-row:not(.is-empty)')].map(row=>({ + id:row.dataset.insertId,individual:row.dataset.fxSlotEnabled, + effective:row.dataset.fxEffective + }))})""") + + +def run(page, width, height): + errors=[] + page.on("pageerror",lambda error:errors.append(str(error))) + page.goto(PAGE.as_uri()) + page.locator('#tracks .strip[data-id="1"]').wait_for() + # Legacy density select is hidden in the approved operator GUI. + # Dispatch the actual reducer event rather than a user gesture on a + # hidden element or a value-only assignment that never updates layout. + for density in ("comfort","standard","compact"): + page.locator("#densitySelect").evaluate( + "(select,value)=>{select.value=value;select.dispatchEvent(new Event('change',{bubbles:true}));}",density) + for value,label in [(-100,"L100"),(0,"CEN"),(100,"R100")]: + seen=pan(page,value) + assert seen["text"]==label,(width,density,label,seen) + assert not seen["clipped"] and not seen["overflow"],(width,density,label,seen) + assert 8.9<=seen["font"]<=9.1,(width,density,"caption font",seen) + assert abs(seen["font"]-seen["panFont"])<.2,(width,density,"PAN typography match",seen) + assert seen["gap"]>=0 and seen["sliderWidth"]>=30,(width,density,"PAN collision",seen) + if label in ("L100","R100"): + assert 24<=seen["readoutWidth"]<=26,(width,density,"caption yields to slider",seen) + if label=="CEN": + assert 12<=seen["readoutWidth"]<25,(width,density,"CEN remains inside gutter",seen) + assert seen["centerError"]<=1,(width,density,"slider must be centered",seen) + page.locator("#densitySelect").evaluate( + "(select)=>{select.value='comfort';select.dispatchEvent(new Event('change',{bubbles:true}));}") + # The operator's folded WIRE intent must be restored on FX mode. + body=page.locator('.console-body') + assert "collapsed-send" in (body.get_attribute("class") or "") + page.locator('#gainView').click() + assert "collapsed-send" not in (body.get_attribute("class") or "") + assert page.locator('.section-rail [data-section="send"]').get_attribute( + "aria-expanded")=="true" + page.locator('#fxView').click() + assert "collapsed-send" in (body.get_attribute("class") or "") + # A manual WIRE rail choice in GAIN is a stronger operator intent. + page.locator('#gainView').click() + page.locator('.section-rail [data-section="send"]').click() + page.locator('.section-rail [data-section="send"]').click() + page.locator('#fxView').click() + assert "collapsed-send" not in (body.get_attribute("class") or "") + # Global A/B overrides effective FX only; insert IDs, individual rack + # and slot flags remain preserved. Master is included, not just CH01. + ch_before=rack(page,1) + main_before=page.locator('.strip.master .fx-section').evaluate( + "el=>el.dataset.fxChainEnabled") + assert ch_before["slots"] and ch_before["slots"][0]["effective"]=="true" + assert main_before=="true" + toggle=page.locator('#globalFxToggle') + power=toggle.locator('.global-fx-power-icon') + assert toggle.inner_text().strip()=="FX" + assert power.evaluate("el=>el.tagName.toLowerCase()")=="svg" + assert toggle.locator("button").count()==0 + assert power.evaluate("el=>getComputedStyle(el).backgroundImage")=="none" + def check_fx_vertical_center(state): + # Compare rendered text glyph positions with the real neighbouring + # toolbar captions. Checking only the FX button's own center failed: + # a special 14px linebox/1px offset had moved its baseline. + positions=toggle.evaluate("""button=>{ + const selectors=['#gainView','#fxView','#sofToggle','#saveScene']; + const center=r=>(r.top+r.bottom)/2; + const measure=(element,caption)=>{ + const buttonRect=element.getBoundingClientRect(),range=document.createRange(); + range.selectNodeContents(caption); + const ink=range.getBoundingClientRect(),style=getComputedStyle(caption); + return {local:center(ink)-center(buttonRect),absolute:center(ink), + size:style.fontSize,weight:style.fontWeight,line:style.lineHeight, + font:style.fontFamily}; + }; + const caption=button.querySelector('.global-fx-label'); + const icon=button.querySelector('.global-fx-power-icon').getBoundingClientRect(); + return {fx:measure(button,caption), + controls:selectors.map(s=>{let el=document.querySelector(s);return {id:s,...measure(el,el)}}), + iconOffset:center(icon)-center(button.getBoundingClientRect()), + labelTransform:getComputedStyle(caption).transform}; + }""") + assert positions["labelTransform"]=="none",(width,state,positions) + assert abs(positions["iconOffset"])<=.75,(width,state,positions) + for ref in positions["controls"]: + assert positions["fx"]["size"]==ref["size"],(width,state,"font size",positions) + assert positions["fx"]["weight"]==ref["weight"],(width,state,"font weight",positions) + assert positions["fx"]["line"]==ref["line"],(width,state,"line-height",positions) + assert positions["fx"]["font"]==ref["font"],(width,state,"font family",positions) + assert abs(positions["fx"]["local"]-ref["local"])<=.6,( + width,state,"FX caption must share toolbar caption baseline",positions) + check_fx_vertical_center("ON") + # The full physical button face, not only its glyph, becomes green. + # The label and icon must share exactly the parent's ON/OFF text ink. + on_face=toggle.evaluate("""el=>({ + bg:getComputedStyle(el).backgroundImage, + ink:getComputedStyle(el).color, + label:getComputedStyle(el.querySelector('.global-fx-label')).color, + glyph:getComputedStyle(el.querySelector('svg.global-fx-power-icon')).color + })""") + assert "rgb(59, 140, 110)" in on_face["bg"],on_face + assert on_face["ink"]==on_face["label"]==on_face["glyph"]=="rgb(240, 255, 247)",on_face + slot_power=page.locator('#tracks .strip[data-id="1"] [data-util-kind="fx-slot"]').first + assert slot_power.evaluate("el=>getComputedStyle(el).backgroundPositionX")=="100%" + toggle.click() + assert toggle.get_attribute("aria-pressed")=="false" + assert toggle.get_attribute("data-fx-power-state")=="bypassed" + check_fx_vertical_center("BYPASS") + off_face=toggle.evaluate("""el=>({ + bg:getComputedStyle(el).backgroundImage, + ink:getComputedStyle(el).color, + label:getComputedStyle(el.querySelector('.global-fx-label')).color, + glyph:getComputedStyle(el.querySelector('svg.global-fx-power-icon')).color + })""") + normal_face=page.locator('#gainView').evaluate("el=>getComputedStyle(el).backgroundImage") + assert off_face["bg"]==normal_face and off_face["bg"]!=on_face["bg"],off_face + assert off_face["ink"]==off_face["label"]==off_face["glyph"],off_face + assert slot_power.evaluate("el=>getComputedStyle(el).backgroundPositionX")=="0%" + assert page.locator(".console-body").evaluate("el=>el.classList.contains('global-fx-bypassed')") + during=rack(page,1) + assert during["global"]=="false" + assert [v["id"] for v in during["slots"]]==[v["id"] for v in ch_before["slots"]] + assert [v["individual"] for v in during["slots"]]==[ + v["individual"] for v in ch_before["slots"]] + assert all(v["effective"]=="false" for v in during["slots"]) + master=page.locator('.strip.master .fx-section') + assert master.get_attribute("data-global-fx-enabled")=="false" + assert master.get_attribute("data-fx-chain-enabled")=="true" + page.screenshot(path=f"arsonmix-global-fx-{width}-bypassed.png") + toggle.click() + after=rack(page,1) + assert after==ch_before | {"global":"true"},(ch_before,after) + assert toggle.evaluate("el=>getComputedStyle(el).backgroundImage")==on_face["bg"] + assert power.evaluate("el=>getComputedStyle(el).color")==on_face["glyph"] + assert slot_power.evaluate("el=>getComputedStyle(el).backgroundPositionX")=="100%" + page.screenshot(path=f"arsonmix-global-fx-{width}-enabled.png") + # Individual OFF remains OFF across the master A/B roundtrip. + slot_power.click() + assert slot_power.get_attribute("aria-pressed")=="false" + toggle.click() + toggle.click() + assert slot_power.evaluate("el=>getComputedStyle(el).backgroundPositionX")=="0%" + assert rack(page,1)["slots"][0]["individual"]=="false" + assert not errors,errors + page.close() + + +def main(): + assert PAGE.is_file(),"Publish Pages into dist-pages/ before browser test" + with sync_playwright() as pw: + browser=pw.chromium.launch(headless=True) + try: + for width,height in [(390,844),(1366,768),(1680,900)]: + page=browser.new_page(viewport={"width":width,"height":height}) + run(page,width,height) + finally: + browser.close() + print("PASS PAN L100/R100 + GAIN/WIRE + non-destructive GLOBAL FX A/B") + + +if __name__=="__main__": + main() diff --git a/tests/sonku_p90_dropdown_stability_test.cjs b/tests/sonku_p90_dropdown_stability_test.cjs index 890d0de90..b583c0686 100644 --- a/tests/sonku_p90_dropdown_stability_test.cjs +++ b/tests/sonku_p90_dropdown_stability_test.cjs @@ -7,13 +7,13 @@ const assert=require("node:assert/strict"); const fs=require("node:fs"); const vm=require("node:vm"); const source=fs.readFileSync("site/preview-v2/assets/mixer-native-sonku.js","utf8"); -const start=source.indexOf(' if(p90Capable && picker.dataset.nativeModeSet!=="p90"){'); +const start=source.indexOf(' if(p90Capable && picker.dataset.nativeModeSet!==(p91p92Capable?"p91p92":"p90")){'); const end=source.indexOf(" const v=p90Capable?",start); assert(start!==-1&&end>start,"Locate actual native SonKu mode menu reconciliation"); const actualReconcile=source.slice(start,end); const renderMenu=vm.runInNewContext( '(function(picker,root,cap){ const {'+ - 'p90Capable,p89Capable,p88Capable,p87Capable,p86Capable,'+ + 'p90Capable,p91p92Capable,p89Capable,p88Capable,p87Capable,p86Capable,'+ 'p85Capable,p84Capable,p83Capable}=cap;\n'+ actualReconcile+'\n})',{} ); @@ -45,13 +45,14 @@ const label={textContent:""}; const root={querySelector(selector){ assert.equal(selector,".sk-render-label");return label; }}; -const full={p90Capable:true,p89Capable:true,p88Capable:true, +const full={p90Capable:true,p91p92Capable:true,p89Capable:true,p88Capable:true, p87Capable:true,p86Capable:true,p85Capable:true,p84Capable:true, p83Capable:false}; renderMenu(picker,root,full); -assert.equal(picker.dataset.nativeModeSet,"p90"); +assert.equal(picker.dataset.nativeModeSet,"p91p92"); assert.match(picker.innerHTML,/value="external"/); -assert.match(label.textContent,/P9\.0 HEADPHONE FAT/); +assert.match(picker.innerHTML,/P9\.1 \+ P9\.2 · MUSIC \/ BASS/); +assert.match(label.textContent,/P9\.1 \+ P9\.2 FAT/); syncSelection(picker,"external"); assert.equal(picker.value,"external"); const writesAfterChoice=picker.valueWrites; @@ -68,19 +69,37 @@ assert.equal(picker.valueWrites,writesAfterChoice, "Native ACK polling must not programmatically re-select the same option"); assert.equal(picker.value,"external"); assert.match(picker.innerHTML,/value="external"/); -// Actual capability downgrade or upgrade is an allowed, one-time menu switch. -const p89={...full,p90Capable:false}; +// Capability loss: an older native v11 P9.0 build must NOT claim P9.1/9.2. +// Exactly one rebuild on a REAL capability change is allowed with popup closed. +const p90Only={...full,p91p92Capable:false}; +renderMenu(picker,root,p90Only); +assert.equal(picker.dataset.nativeModeSet,"p90"); +assert.equal(optionWrites.length,2); +assert.match(picker.innerHTML,/P9\.0 · TRUE EXTERNAL/); +assert.doesNotMatch(picker.innerHTML,/P9\.1 \+ P9\.2/); +assert.match(label.textContent,/P9\.0 HEADPHONE FAT/); +picker.isOpen=true; +for(let i=0;i<12;++i)renderMenu(picker,root,p90Only); +picker.isOpen=false; +assert.equal(optionWrites.length,2); +const p89={...p90Only,p90Capable:false}; renderMenu(picker,root,p89); assert.equal(picker.dataset.nativeModeSet,"p89"); -assert.equal(optionWrites.length,2); +assert.equal(optionWrites.length,3); assert.doesNotMatch(picker.innerHTML,/value="external"/); for(let i=0;i<12;++i)renderMenu(picker,root,p89); -assert.equal(optionWrites.length,2); +assert.equal(optionWrites.length,3); const p88={...p89,p89Capable:false}; renderMenu(picker,root,p88); assert.equal(picker.dataset.nativeModeSet,"p88"); -assert.equal(optionWrites.length,3); -renderMenu(picker,root,full); -assert.equal(picker.dataset.nativeModeSet,"p90"); assert.equal(optionWrites.length,4); -console.log("PASS P90 dropdown remains mounted during 40 native readbacks; no P8.9 oscillation, no selection writes, transitions exactly once"); +renderMenu(picker,root,full); +assert.equal(picker.dataset.nativeModeSet,"p91p92"); +assert.equal(optionWrites.length,5); +// Native capability is authoritative; a UI-only version string is insufficient. +const nativeSource=fs.readFileSync("src/Main.cpp","utf8"); +assert.match(nativeSource,/reply->setProperty\("p91p92MusicBassFoundation",true\)/); +assert.match(source,/p91p92Capable=p90Capable && r\.p91p92MusicBassFoundation===true;/); +assert.match(source,/p91p92Capable&&s\.renderMode===9/); +assert.match(source,/NATIVE P9\.1\+P9\.2 WORLD BASS/); +console.log("PASS P91P92 dropdown: native capability-gated milestone, stable 40 readbacks, P9.0 fallback, correct one-time transitions"); diff --git a/tests/sonku_p91_p92_music_bass_foundation_test.cpp b/tests/sonku_p91_p92_music_bass_foundation_test.cpp new file mode 100644 index 000000000..7cdf4870d --- /dev/null +++ b/tests/sonku_p91_p92_music_bass_foundation_test.cpp @@ -0,0 +1,142 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// P9.1+P9.2: real SonKu native stereo PCM, non-proprietary source material. +#if defined(NDEBUG) +#undef NDEBUG +#endif +#if !defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) || !SONKU_P90_TRUE_EXTERNAL_RESEARCH +#error P9.1+P9.2 requires the isolated P9 DSP switch +#endif +#include "../engine/builtin_fx/sonku/SonKuSpatialCore.h" +#include "../engine/builtin_fx/sonku/SonKuP91P92WorldBassFoundation.h" +#include +#include +#include +#include +#include +#include +#include +using namespace armix::sonku; +using Stereo=std::array,2>; +static Stereo simulate(int rate,int mode,int room,float roomWet, + float yaw,int source,int frames=48000,int block=128){ + auto processor=std::make_unique(); + assert(processor->prepare(rate,SonKuReflectionProfile::SixSurfaceKemarResearch)); + Settings s{}; + s.renderMode=mode;s.moving=false;s.startAzimuthDegrees=0.f; + s.stereoSpreadDegrees=82.f;s.headYawDegrees=yaw; + s.outputTrim=1.f;s.spatialMix=1.f; + s.spacePreset=room;s.roomAmount=roomWet;s.ambience=room?0.32f:0.f; + s.sourceDistanceMeters=1.6f; + assert(valid(s)&&processor->setSettings(s)); + Stereo pcm{std::vector(frames),std::vector(frames)}; + for(int i=0;iprocess(pcm[0].data()+i,pcm[1].data()+i, + std::min(block,frames-i)); + for(int ear=0;ear<2;++ear)for(float x:pcm[ear]) + assert(std::isfinite(x)&&std::abs(x)<.981f); + return pcm; +} +static double rms(const Stereo& p,int ear,int skip=12000){ + double e=0.; + for(std::size_t i=skip;i(); + assert(bass->prepare(rate)); + constexpr float pi=3.14159265358979323846f; + const auto measure=[&](float leftAzimuth,float rightAzimuth,int source){ + bass->reset(); + bass->updateDirections(leftAzimuth,rightAzimuth); + double left=0.,right=0.; + const int duration=rate/2; + for(int i=0;iprocess(source==0?wave:0.f, + source==1?wave:0.f,hL,hR,0,0.f); + assert(modal.left==0.f && modal.right==0.f); + if(i>rate/10){left+=double(hL)*hL;right+=double(hR)*hR;} + } + return std::array{left,right}; + }; + const auto leftSpeaker=measure(-41.f,41.f,0); + const auto rightSpeaker=measure(-41.f,41.f,1); + const auto rotated=measure(-221.f,-139.f,0); + // This isolates 70Hz; treble cannot masquerade as directional LF. + assert(leftSpeaker[0]>1.3*leftSpeaker[1]); + assert(rightSpeaker[1]>1.3*rightSpeaker[0]); + assert(rotated[1]>1.3*rotated[0]); + std::printf("P91P92_WORLD_BASS_ONLY,%d,L/R=%.4f,R/L=%.4f,rotated_R/L=%.4f\\n", + rate,leftSpeaker[0]/leftSpeaker[1], + rightSpeaker[1]/rightSpeaker[0],rotated[1]/rotated[0]); +} +int main(){ + for(int rate:{44100,48000}){ + worldBassDirectionalOnly(rate); + const auto p9=simulate(rate,9,3,.80f,0.f,2,rate); + const auto p9Block=simulate(rate,9,3,.80f,0.f,2,rate,256); + assert(difference(p9,p9Block)==0. && "ASIO block size changed PCM"); + const auto p89=simulate(rate,8,3,.80f,0.f,2,rate); + assert(difference(p9,p89)>1.e-4); + const auto dry=simulate(rate,9,0,0.f,0.f,2,rate); + assert(difference(p9,dry)>1.e-4 && "Room model inaudible"); + // The P9 direct stereo scene is now 0.72 rather than the old + // 0.5 attenuation. It should not be quieter than old P8.9 for + // this bounded 70/116Hz and 5.2k stimulus. + const double p9TotalRms=rms(p9,0)+rms(p9,1); + const double sourceTotalRms=2.*std::sqrt( + (.24*.24+.14*.14+.08*.08)/2.); + // Musical default must not simply win A/B by being twice as loud. + // A narrow test tone is not integrated LUFS; this bounds only the + // deterministic steady-state electrical gain to within ~2.5 dB. + std::fprintf(stderr,"P91P92_LEVEL_%d input=%.8f actual=%.8f ratio=%.5f\n", + rate,sourceTotalRms,p9TotalRms,p9TotalRms/sourceTotalRms); + assert(p9TotalRms>.75*sourceTotalRms && + p9TotalRms<1.33*sourceTotalRms && + "P9 has excessive loss or hidden makeup gain"); + assert(p9TotalRms>.78*(rms(p89,0)+rms(p89,1))); + const auto left=simulate(rate,9,3,.8f,0.f,0,rate); + const auto right=simulate(rate,9,3,.8f,0.f,1,rate); + assert(difference(left,right)>1.e-4); + const auto rotated=simulate(rate,9,3,.8f,90.f,0,rate); + assert(difference(left,rotated)>1.e-4); + // Anti-phase is not rebuilt as synthetic mono bass. + const auto anti=simulate(rate,9,3,.8f,0.f,3,rate); + assert(rms(anti,0)+rms(anti,1)>1.e-4); + // Room modal return is exactly zero with Room OFF; a zero-wet + // scene cannot invent resonant gain. + auto core=std::make_unique(); + assert(core->prepare(rate)); + core->updateDirections(-41.f,41.f); + for(int i=0;iprocess(.01f,.01f,h0,h1,0,1.f); + assert(out.left==0.f && out.right==0.f); + } + const auto withModes=simulate(rate,9,3,1.f,0.f,0,rate); + const auto noModes=simulate(rate,9,3,0.f,0.f,0,rate); + assert(difference(withModes,noModes)>1.e-5); + std::printf("P91P92_RATE,%d,p9_rms=%.7f,p89_rms=%.7f,room_delta=%.7f\n", + rate,rms(p9,0)+rms(p9,1),rms(p89,0)+rms(p89,1),difference(withModes,noModes)); + } + std::puts("PASS P91P92 MUSIC/BASS PCM: 44.1/48k, world-locked separated LF, no dry SIDE, 3-room axial modes, anti-phase, finite output, 128/256 parity"); +} diff --git a/tests/sonku_spatial_core_test.cpp b/tests/sonku_spatial_core_test.cpp index 9b5980e02..d3befa9e7 100644 --- a/tests/sonku_spatial_core_test.cpp +++ b/tests/sonku_spatial_core_test.cpp @@ -10,236 +10,32 @@ #include #include -// Measurable failure case from the listening report: two equal-angle virtual -// emitters fed opposite-polarity stereo cancel in each ear HRTF summation. -// Test the actual native PCM path, not a JS animation or guessed acoustics. -static void verifySonKuMusicIntegrity(double rate) { - using namespace armix::sonku; - Settings s{}; - s.moving=false;s.stereoSpreadDegrees=0.f;s.spatialMix=1.f; - s.outputTrim=.75f;s.spacePreset=0; - // A perfectly coherent stereo center must remain the exact old measured - // impulse, including coefficient, amplitude, phase and callback timing. - { - auto center=std::make_unique(); - assert(center->prepare(rate)&¢er->setSettings(s)); - std::array l{},r{}; - l[0]=r[0]=.24f; - center->process(l.data(),r.data(),static_cast(l.size())); - const auto& h=(std::abs(rate-44100.)<.1)? - hrir::normal44100:hrir::normal48000; - for(int i=0;i(h[0][0][i])/32768.f; - const float expectedR=.24f*s.outputTrim* - static_cast(h[0][1][i])/32768.f; - assert(std::abs(l[i]-expectedL)<3.e-6f); - assert(std::abs(r[i]-expectedR)<3.e-6f); - } - } - constexpr int n=16384; - constexpr float pi=3.14159265358979323846f; - for (float angle : {0.f,90.f,180.f,270.f}) { - auto whole=std::make_unique(); - auto partition=std::make_unique(); - s.startAzimuthDegrees=angle; - assert(whole->prepare(rate)&&partition->prepare(rate)); - assert(whole->setSettings(s)&&partition->setSettings(s)); - std::vector l(n),r(n),cl(n),cr(n); - for(int i=0;i(i)/static_cast(rate)); - l[i]=cl[i]=v; - r[i]=cr[i]=-v; - } - whole->process(l.data(),r.data(),n); - for(int at=0;atprocess(cl.data()+at,cr.data()+at, - std::min(128,n-at)); - double leftEnergy=0.,rightEnergy=0.,crossEnergy=0.; - for(int i=0;in/2){ - leftEnergy+=static_cast(l[i])*l[i]; - rightEnergy+=static_cast(r[i])*r[i]; - crossEnergy+=static_cast(l[i])*r[i]; - } - } - const double rmsL=std::sqrt(leftEnergy/(n/2-1)); - const double rmsR=std::sqrt(rightEnergy/(n/2-1)); - // Original SonKu collapses to zero at FRONT/REAR and zero SPREAD. - // The phase-aware branch must preserve a musical stereo side signal - // without converting it into a mono HRTF object. - assert(rmsL>.065&&rmsR>.065); - if(angle==0.f||angle==180.f)assert(crossEnergy<0.); - } - // Mixed stereo without strong anti-correlation never activates recovery: - // a mono-correlated signal is not given a phantom second bed. - { - SonKuStereoIntegrity guard; - assert(guard.prepare(rate)); - for(int i=0;i<8000;++i){ - float v=.4f*std::sin(2.f*pi*160.f* - static_cast(i)/static_cast(rate)); - assert(guard.preservedSide(v,.7f*v)==0.f); - } - assert(guard.recoveryAmount()==0.f); - assert(guard.coherentAmount()>.95f); - guard.reset(); - assert(guard.coherentAmount()==0.f); - for(int i=0;i<8000;++i){ - float v=.4f*std::sin(2.f*pi*160.f* - static_cast(i)/static_cast(rate)); - (void)guard.preservedSide(v,-v); - } - assert(guard.recoveryAmount()>.95f); - assert(guard.coherentAmount()<.01f); - for(int i=0;i<25000;++i) - assert(guard.preservedSide(0.f,0.f)==0.f); - assert(guard.recoveryAmount()<.05f); - assert(guard.coherentAmount()<.05f); - assert(guard.prepare(rate)); // device restart must not remember polarity - assert(guard.recoveryAmount()==0.f); - assert(guard.coherentAmount()==0.f); - } - // A fully coherent music MID should take one center KEMAR HRIR instead - // of the comb-filtered mean of two spatially separated virtual speakers. - // This exercises the REAL native FIR in steady state (not a UI pan). - { - Settings coherent=s; - coherent.startAzimuthDegrees=180.f; - coherent.stereoSpreadDegrees=60.f; - coherent.spatialMix=1.f; - coherent.outputTrim=.6f; - auto mid=std::make_unique(); - assert(mid->prepare(rate)&&mid->setSettings(coherent)); - constexpr int frames=32768; - constexpr double frequency=2000.; - std::vector left(frames),right(frames); - for(int i=0;i( - std::sin(2.*3.14159265358979323846*frequency*i/rate)); - mid->process(left.data(),right.data(),frames); - double sum=0.; - for(int i=frames-8192;i(left[i])*left[i]; - const double observed=std::sqrt(sum/8192.)*std::sqrt(2.); - const auto& h=(std::abs(rate-44100.)<.1)? - hrir::normal44100:hrir::normal48000; - auto response=[&](int azimuth,int ear) { - double real=0.,imag=0.; - for(int i=0;i{real,imag}; - }; - const auto center=response(180,0); - const double expected=.04*coherent.outputTrim* - std::hypot(center[0],center[1]); - assert(expected>.005 && observed/expected>.86 - && observed/expected<1.14); - if(std::abs(rate-48000.)<.1){ - const auto a=response(150,0),b=response(150,1); - const double oldMean=.5*std::hypot(a[0]+b[0],a[1]+b[1]); - const double newCenter=std::hypot(center[0],center[1]); - // Independent frequency-domain HRTF audit: REAR 2kHz old - // 60deg coherent stereo comb ~11.6dB, center is much clearer. - assert(newCenter>oldMean*2.5); - } - } - // The exact native ROOM ON path uses the SAME phase guard. Live room - // reflections and the FDN cannot silently drop the side content, exceed - // peak bounds or depend on host block partition. This is actual PCM. - { - auto live=std::make_unique(); - auto chunks=std::make_unique(); - Settings scene=s; - scene.startAzimuthDegrees=180.f; - scene.stereoSpreadDegrees=0.f; - scene.spatialMix=1.f; - scene.outputTrim=.65f; - scene.spacePreset=2; // 14.4m chamber, 5m source - scene.sourceDistanceMeters=5.f; - scene.roomAmount=.55f; - scene.ambience=.32f; - assert(valid(scene)); - assert(live->prepare(rate)&&chunks->prepare(rate)); - assert(live->setSettings(scene)&&chunks->setSettings(scene)); - constexpr int sceneFrames=16384; - std::vector l(sceneFrames),r(sceneFrames), - cl(sceneFrames),cr(sceneFrames); - for(int i=0;i( - std::sin(2.*3.14159265358979323846*440.*i/rate)); - l[i]=cl[i]=v;r[i]=cr[i]=-v; - } - live->process(l.data(),r.data(),sceneFrames); - for(int at=0;atprocess(cl.data()+at,cr.data()+at, - std::min(256,sceneFrames-at)); - double leftPower=0.,rightPower=0.; - for(int i=0;i=sceneFrames/2) { - leftPower+=static_cast(l[i])*l[i]; - rightPower+=static_cast(r[i])*r[i]; - } - } - assert(std::sqrt(leftPower/(sceneFrames/2))>.025); - assert(std::sqrt(rightPower/(sceneFrames/2))>.025); - } - // Mix=0 preserves the source channels as dry, including negative phase. - { - auto dry=std::make_unique(); - s.spatialMix=0.f;s.startAzimuthDegrees=0.f; - assert(dry->prepare(rate)&&dry->setSettings(s)); - // The original engine intentionally slews MIX edits for de-click; - // exact dry identity applies after the accepted transition settles. - std::array warmL{},warmR{}; - for(int k=0;k<48;++k) - dry->process(warmL.data(),warmR.data(),256); - std::array l{},r{}; - for(int i=0;i(l.size());++i){ - l[i]=.15f*std::sin(i*.017f);r[i]=-l[i]; - } - const auto before=l; - dry->process(l.data(),r.data(),static_cast(l.size())); - for(int i=0;i(l.size());++i){ - assert(l[i]==before[i]&&r[i]==-before[i]); - } - } -} - int main() { using namespace armix::sonku; - for(double r:{44100.,48000.})verifySonKuMusicIntegrity(r); - SonKuSpatialCore rejected; - assert(!rejected.prepare(96000.)); - assert(!rejected.prepare(std::numeric_limits::infinity())); - assert(!rejected.ready()); + // Large fixed acoustic delay rings belong on the heap in the *test*. + // 8x4096 FDN + 2x8192 ER float samples alone exceed 192 KiB per + // SonKuSpatialCore, and 12 stack-local fixtures overflow the default + // 1 MiB Windows executable stack before assertions can run. Keep every + // real PCM/partition/direction assertion unchanged; no DSP or stack-size + // linker override is involved. + auto rejected=std::make_unique(); + assert(!rejected->prepare(96000.)); + assert(!rejected->prepare(std::numeric_limits::infinity())); + assert(!rejected->ready()); for(double rate:{44100.,48000.}) { - SonKuSpatialCore core; - assert(core.prepare(rate)); + auto core=std::make_unique(); + assert(core->prepare(rate)); Settings s{}; s.moving=false; s.stereoSpreadDegrees=0.f; s.spatialMix=1.f; s.outputTrim=0.8f; - assert(core.setSettings(s)); + assert(core->setSettings(s)); constexpr int frames=512; std::array frontL{},frontR{},rearL{},rearR{},rightL{},rightR{}; auto impulse=[&](float angle,std::array& a,std::array& b) { - core.reset();Settings pos=s;pos.startAzimuthDegrees=angle; - assert(core.setSettings(pos)); + core->reset();Settings pos=s;pos.startAzimuthDegrees=angle; + assert(core->setSettings(pos)); a.fill(0.f);b.fill(0.f);a[0]=1.f; - core.process(a.data(),b.data(),frames); + core->process(a.data(),b.data(),frames); }; impulse(0.f,frontL,frontR); impulse(180.f,rearL,rearR); @@ -269,27 +65,28 @@ int main() { moving.revolutionSeconds=0.5f; moving.stereoSpreadDegrees=50.f; moving.outputTrim=0.5f; - assert(core.setSettings(moving)); - assert(!core.setSettings(Settings{0.f,0.f,60.f,1.f,0.5f,true,true})); + assert(core->setSettings(moving)); + assert(!core->setSettings(Settings{0.f,0.f,60.f,1.f,0.5f,true,true})); constexpr int longFrames=1024; std::array oneL{},oneR{},chunkL{},chunkR{}; for(int i=0;i(); + auto chunked=std::make_unique(); + assert(whole->prepare(rate)&&chunked->prepare(rate)); + assert(whole->setSettings(moving)&&chunked->setSettings(moving)); + whole->process(oneL.data(),oneR.data(),longFrames); + chunked->process(chunkL.data(),chunkR.data(),128); + chunked->process(chunkL.data()+128,chunkR.data()+128,384); + chunked->process(chunkL.data()+512,chunkR.data()+512,512); for(int i=0;iazimuthDegrees()-chunked->azimuthDegrees())<1.e-10); // V2 A/B: room OFF is the verified original renderer; room ON // produces only delayed acoustic energy, without modifying first // arrival, direction signs or host buffer partition behavior. @@ -297,18 +94,20 @@ int main() { std::array noL{},noR{},wetL{},wetR{},partL{},partR{}; noL[0]=wetL[0]=partL[0]=.5f; noR[0]=wetR[0]=partR[0]=.5f; - SonKuSpatialCore noRoom,withRoom,partRoom; - assert(noRoom.prepare(rate)&&withRoom.prepare(rate)&&partRoom.prepare(rate)); + auto noRoom=std::make_unique(); + auto withRoom=std::make_unique(); + auto partRoom=std::make_unique(); + assert(noRoom->prepare(rate)&&withRoom->prepare(rate)&&partRoom->prepare(rate)); Settings roomSettings=s;roomSettings.startAzimuthDegrees=0.f; - assert(noRoom.setSettings(roomSettings)&&withRoom.setSettings(roomSettings) - &&partRoom.setSettings(roomSettings)); - assert(withRoom.setEarlyReflectionsAmount(.55f)); - assert(partRoom.setEarlyReflectionsAmount(.55f)); - noRoom.process(noL.data(),noR.data(),roomFrames); - withRoom.process(wetL.data(),wetR.data(),roomFrames); - partRoom.process(partL.data(),partR.data(),128); - partRoom.process(partL.data()+128,partR.data()+128,384); - partRoom.process(partL.data()+512,partR.data()+512,roomFrames-512); + assert(noRoom->setSettings(roomSettings)&&withRoom->setSettings(roomSettings) + &&partRoom->setSettings(roomSettings)); + assert(withRoom->setEarlyReflectionsAmount(.55f)); + assert(partRoom->setEarlyReflectionsAmount(.55f)); + noRoom->process(noL.data(),noR.data(),roomFrames); + withRoom->process(wetL.data(),wetR.data(),roomFrames); + partRoom->process(partL.data(),partR.data(),128); + partRoom->process(partL.data()+128,partR.data()+128,384); + partRoom->process(partL.data()+512,partR.data()+512,roomFrames-512); double roomDifference=0.; for(int i=0;i(); - SonKuSpatialCore glow,glowChunks; - assert(approvedSquare->prepare(rate)&&glow.prepare(rate)&&glowChunks.prepare(rate)); + auto glow=std::make_unique(); + auto glowChunks=std::make_unique(); + assert(approvedSquare->prepare(rate)&&glow->prepare(rate)&&glowChunks->prepare(rate)); assert(approvedSquare->setEarlyReflectionsShape(SonKuRoomShape::Square)); - assert(glow.setEarlyReflectionsShape(SonKuRoomShape::Square)); - assert(glowChunks.setEarlyReflectionsShape(SonKuRoomShape::Square)); + assert(glow->setEarlyReflectionsShape(SonKuRoomShape::Square)); + assert(glowChunks->setEarlyReflectionsShape(SonKuRoomShape::Square)); assert(approvedSquare->setSettings(roomSettings)&& - glow.setSettings(roomSettings)&&glowChunks.setSettings(roomSettings)); + glow->setSettings(roomSettings)&&glowChunks->setSettings(roomSettings)); assert(approvedSquare->setEarlyReflectionsAmount(.55f)&& - glow.setEarlyReflectionsAmount(.55f)&& - glowChunks.setEarlyReflectionsAmount(.55f)); - assert(glow.setMusicalReverbAmount(.42f)&&glowChunks.setMusicalReverbAmount(.42f)); + glow->setEarlyReflectionsAmount(.55f)&& + glowChunks->setEarlyReflectionsAmount(.55f)); + assert(glow->setMusicalReverbAmount(.42f)&&glowChunks->setMusicalReverbAmount(.42f)); std::array squareL{},squareR{},tailL{},tailR{},splitL{},splitR{}; squareL[0]=squareR[0]=tailL[0]=tailR[0]=splitL[0]=splitR[0]=.5f; approvedSquare->process(squareL.data(),squareR.data(),roomFrames); - glow.process(tailL.data(),tailR.data(),roomFrames); - glowChunks.process(splitL.data(),splitR.data(),128); - glowChunks.process(splitL.data()+128,splitR.data()+128,384); - glowChunks.process(splitL.data()+512,splitR.data()+512,roomFrames-512); + glow->process(tailL.data(),tailR.data(),roomFrames); + glowChunks->process(splitL.data(),splitR.data(),128); + glowChunks->process(splitL.data()+128,splitR.data()+128,384); + glowChunks->process(splitL.data()+512,splitR.data()+512,roomFrames-512); double lateDifference=0.; for(int i=0;iREAR teleport must not replace 560 FIR coefficients // at the next 16-sample boundary. Compare the identical dry/PCM // history before and immediately after reposition. - SonKuSpatialCore teleport,stationary; - assert(teleport.prepare(rate)&&stationary.prepare(rate)); + auto teleport=std::make_unique(); + auto stationary=std::make_unique(); + assert(teleport->prepare(rate)&&stationary->prepare(rate)); Settings frontPose=s;frontPose.startAzimuthDegrees=0.f; - assert(teleport.setSettings(frontPose)&&stationary.setSettings(frontPose)); + assert(teleport->setSettings(frontPose)&&stationary->setSettings(frontPose)); std::array preL{},preR{},sameL{},sameR{}; preL.fill(.12f);preR.fill(-.10f);sameL=preL;sameR=preR; - teleport.process(preL.data(),preR.data(),512); - stationary.process(sameL.data(),sameR.data(),512); + teleport->process(preL.data(),preR.data(),512); + stationary->process(sameL.data(),sameR.data(),512); Settings rearPose=frontPose;rearPose.startAzimuthDegrees=180.f; - assert(teleport.setSettings(rearPose)); + assert(teleport->setSettings(rearPose)); std::array stepL{},stepR{},refL{},refR{}; stepL.fill(.12f);stepR.fill(-.10f);refL=stepL;refR=stepR; - teleport.process(stepL.data(),stepR.data(),1024); - stationary.process(refL.data(),refR.data(),1024); + teleport->process(stepL.data(),stepR.data(),1024); + stationary->process(refL.data(),refR.data(),1024); assert(std::abs(stepL[0]-refL[0])<.008f); assert(std::abs(stepR[0]-refR[0])<.008f); double changed=0.; @@ -646,18 +447,18 @@ int main() { changed+=std::abs(stepL[i]-refL[i])+std::abs(stepR[i]-refR[i]); assert(changed>.005); // MIX/trim changes are smoothed on the same audio clock. - SonKuSpatialCore mixCore; - assert(mixCore.prepare(rate)); + auto mixCore=std::make_unique(); + assert(mixCore->prepare(rate)); Settings dry=frontPose;dry.spatialMix=0.f; - assert(mixCore.setSettings(dry)); + assert(mixCore->setSettings(dry)); std::array warmL{},warmR{}; warmL.fill(.19f);warmR.fill(-.13f); - mixCore.process(warmL.data(),warmR.data(),2048); + mixCore->process(warmL.data(),warmR.data(),2048); Settings wet=dry;wet.spatialMix=1.f;wet.outputTrim=.5f; - assert(mixCore.setSettings(wet)); + assert(mixCore->setSettings(wet)); std::array fadeL{},fadeR{}; fadeL.fill(.19f);fadeR.fill(-.13f); - mixCore.process(fadeL.data(),fadeR.data(),1024); + mixCore->process(fadeL.data(),fadeR.data(),1024); assert(std::abs(fadeL[0]-.19f)<.01f); assert(std::abs(fadeR[0]+.13f)<.01f); for(int i=1;i<1024;++i) { @@ -665,16 +466,16 @@ int main() { assert(std::abs(fadeL[i]-fadeL[i-1])<.04f); assert(std::abs(fadeR[i]-fadeR[i-1])<.04f); } - moving.spatialMix=0.f; assert(chunked.setSettings(moving)); + moving.spatialMix=0.f; assert(chunked->setSettings(moving)); // The knob transition is deliberately clickless; zero wet is exact // after its finite smoothing interval, not the first sample. std::array settleL{},settleR{}; for(int block=0;block<80;++block) { settleL.fill(0.f);settleR.fill(0.f); - chunked.process(settleL.data(),settleR.data(),128); + chunked->process(settleL.data(),settleR.data(),128); } std::array dryL{},dryR{};dryL.fill(.17f);dryR.fill(-.29f); - chunked.process(dryL.data(),dryR.data(),32); + chunked->process(dryL.data(),dryR.data(),32); for(int i=0;i<32;++i){assert(std::abs(dryL[i]-.17f)<1.e-6f);assert(std::abs(dryR[i]+.29f)<1.e-6f);} } return 0; diff --git a/tests/test_embedded_gui_resources.py b/tests/test_embedded_gui_resources.py new file mode 100644 index 000000000..c25f384a0 --- /dev/null +++ b/tests/test_embedded_gui_resources.py @@ -0,0 +1,89 @@ +"""Regression for literal embedded Pages/native GUI resource attestation.""" +from __future__ import annotations + +import hashlib +import importlib.util +import json +from pathlib import Path +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location( + "verify_embedded_gui_resources", ROOT / "scripts" / "verify_embedded_gui_resources.py" +) +assert spec and spec.loader +mod = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mod) + + +class NativeGuiEmbeddedBytesTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="armix-exe-byte-qa-") + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.bundle = self.root / "approved_gui" + (self.bundle / "assets").mkdir(parents=True) + self.exe = self.root / "ARMixConsole.exe" + self.manifest = self.bundle / "approved-gui-manifest.json" + self.assets = { + "index.html": "ArSonMix — /preview/".encode("utf-8"), + "assets/mixer.css": b".gain{color:#81b8c6}", + "assets/button.png": b"\x89PNG\r\n\x1a\n\0\xff\x90\x12APPROVED\0", + } + self.records = [ + {"path": name, "sha256": hashlib.sha256(payload).hexdigest()} + for name, payload in self.assets.items() + ] + for name, payload in self.assets.items(): + (self.bundle / name).write_bytes(payload) + self.write_manifest() + self.exe.write_bytes( + b"MZ" + b"\x00" * 128 + + b"\x00".join(self.assets.values()) + + b"\x00" * 64 + ) + + def write_manifest(self): + self.manifest.write_text(json.dumps({ + "schema": "arsonmix.approved-native-pages-bundle.v2", + "files": self.records, + }), encoding="utf-8") + + def test_attests_exact_original_utf8_and_binary_bytes(self): + self.assertEqual(mod.verify(self.exe, self.bundle, self.manifest), 3) + + def test_rejects_staged_png_not_present_in_executable(self): + self.exe.write_bytes(b"MZ" + self.assets["index.html"] + + self.assets["assets/mixer.css"]) + with self.assertRaisesRegex(mod.EmbeddedGuiError, "NOT IN WINDOWS EXE: assets/button.png"): + mod.verify(self.exe, self.bundle, self.manifest) + + def test_rejects_tampered_staged_bytes_even_when_exe_has_old_bytes(self): + (self.bundle / "assets/mixer.css").write_bytes(b".gain{color:orange}") + with self.assertRaisesRegex(mod.EmbeddedGuiError, "SHA mismatch: assets/mixer.css"): + mod.verify(self.exe, self.bundle, self.manifest) + + def test_rejects_duplicate_or_traversal_manifest_entries(self): + self.records.append(self.records[0].copy()) + self.write_manifest() + with self.assertRaisesRegex(mod.EmbeddedGuiError, "duplicate"): + mod.verify(self.exe, self.bundle, self.manifest) + self.records[-1] = {"path": "assets/../index.html", + "sha256": self.records[0]["sha256"]} + self.write_manifest() + with self.assertRaisesRegex(mod.EmbeddedGuiError, "Unsafe"): + mod.verify(self.exe, self.bundle, self.manifest) + + def test_rejects_empty_exe_and_invalid_schema(self): + self.exe.write_bytes(b"") + with self.assertRaisesRegex(mod.EmbeddedGuiError, "empty"): + mod.verify(self.exe, self.bundle, self.manifest) + self.exe.write_bytes(b"MZ" + b"resource") + self.manifest.write_text('{"schema":"invalid","files":[]}', encoding="utf-8") + with self.assertRaisesRegex(mod.EmbeddedGuiError, "schema"): + mod.verify(self.exe, self.bundle, self.manifest) + + +if __name__ == "__main__": + unittest.main() diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index ab0b69837..f9d0b8e29 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -255,6 +255,7 @@ // them atomically. Never retain detached WebView2 strips or stale channel IDs. const meterElements = new Map(); let nativeFxPowerSerial=0,pendingNativeFxPower=null; + let globalFxSerial=0,pendingGlobalFx=null; const pendingM4RackPowers=new Map(); let controller = null; let logicalView=null,pendingLogical=null,logicalSerial=0,logicalRenameId=null; @@ -601,6 +602,7 @@ if(typeof ch.fxRackBypassed!=="boolean"||!Array.isArray(ch.inserts)) return true; // never synthesize missing DSP readback const enabled=!ch.fxRackBypassed; + const globalEnabled=document.querySelector('.console-body')?.classList.contains('global-fx-bypassed')!==true; const strip=document.querySelector('.strip[data-id="'+t.id+'"]'); // GAIN/SOF are alternate views of the FX area; power readback still // updates the model but must not rebuild the rack or steal knob focus. @@ -628,9 +630,10 @@ t.slotBypass[slot]=ch.inserts[slot].bypassed; if(!rack)return true; rack.dataset.fxChainEnabled=String(enabled); - rack.classList.toggle("is-chain-bypassed",!enabled); + rack.dataset.globalFxEnabled=String(globalEnabled); + rack.classList.toggle("is-chain-bypassed",!enabled||!globalEnabled); const header=rack.querySelector('[data-action="fxOn"]'); - header.setAttribute("aria-pressed",String(enabled)); + header.setAttribute("aria-pressed",String(enabled&&globalEnabled)); header.title=(enabled?"Bypass":"Enable")+" all channel FX"; header.setAttribute("aria-label", (enabled?"Bypass":"Enable")+" entire FX chain in "+t.name); @@ -638,7 +641,7 @@ const insert=ch.inserts[slot]; const row=[...rack.querySelectorAll('.fxslot-row:not(.is-empty)')] .find(r=>r.dataset.slot===String(slot)); - const effective=enabled&&!insert.bypassed; + const effective=enabled&&globalEnabled&&!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)) @@ -1495,6 +1498,57 @@ if(p.acked && actual===p.bypassed)pendingM4RackPowers.delete(lane); } } + // Global A/B is a SINGLE native atomic override. Individual racks and + // inserts remain untouched. Never simulate success in WebView while device + // admission or a matching native ACK + subsequent readback is missing. + function globalFxContext(){ + if(logicalView)return null; // an offline .smix has no audible PCM + const current=controller?.state()?.current; + const session=current?.raw?.mixerSession; + if(current?.admitted && session?.authority==="CHANNEL_ID") + return {epoch:String(current.device.epoch), + revision:String(current.graph.revision)}; + if(session?.authority==="M4" && m4Verified()) + return {epoch:String(session.deviceEpoch), + revision:String(session.routeRevision)}; + return null; + } + function syncGlobalFxReadback(snapshot){ + const button=document.getElementById?.("globalFxToggle"); + const actual=snapshot?.globalFxBypassed; + const context=globalFxContext(); + if(pendingGlobalFx?.acked && typeof actual==="boolean" && + actual===pendingGlobalFx.bypassed)pendingGlobalFx=null; + if(typeof actual==="boolean" && !pendingGlobalFx) + window.__ARMIX_SET_GLOBAL_FX_VIEW__?.(!actual); + if(button) { + button.disabled=!context||!!pendingGlobalFx; + button.setAttribute("aria-busy",String(!!pendingGlobalFx)); + if(!context)button.title="Global FX requires admitted physical audio"; + } + } + function toggleGlobalFx(){ + if(pendingGlobalFx)return false; + const ctx=globalFxContext(),current=controller?.state()?.current; + const actual=current?.raw?.globalFxBypassed; + if(!ctx || typeof actual!=="boolean")return false; + const requestId="global-fx-"+(++globalFxSerial); + pendingGlobalFx={requestId,bypassed:!actual,acked:false}; + const button=document.getElementById?.("globalFxToggle"); + if(button){button.disabled=true;button.setAttribute("aria-busy","true");} + backend.emitEvent("arMixAction",{ + action:"routingGlobalFxBypass",requestId, + deviceEpoch:ctx.epoch,revision:ctx.revision,value:!actual + }); + window.setTimeout(()=>{ + if(pendingGlobalFx?.requestId!==requestId)return; + pendingGlobalFx=null; + status("Global FX A/B not confirmed · keeping previous audible state"); + controller?.subscribe(); // Readback is authoritative, never optimistic. + },8000); + return true; + } + window.__ARMIX_NATIVE_GLOBAL_FX__={toggle:toggleGlobalFx}; function requestAdmittedFxPower(t,action,button){ const session=mixerSession(),current=controller?.state()?.current; const channelId=nativeIdFor(t); @@ -3045,11 +3099,13 @@ } }); backend.addEventListener("arMixConsoleSnapshot", snapshot=>{ - // Stage A: do not add time-sampling overhead unless explicitly armed. + // First reconcile the canonical engine snapshot, then the global FX + // view gate. Never infer FX admission from a local button press. + const apply=()=>{controller.onSnapshot(snapshot);syncGlobalFxReadback(snapshot);}; const profiler=window.ArSonMixPerf; - if(!profiler?.active){controller.onSnapshot(snapshot);return;} + if(!profiler?.active){apply();return;} const started=performance.now(); - try{controller.onSnapshot(snapshot);} + try{apply();} finally{profiler.sample("nativeSnapshotJsMs",performance.now()-started);} }); backend.addEventListener("arMixConsoleAck", ack=>controller.onAck(ack)); @@ -3119,6 +3175,15 @@ } controller?.subscribe(); }); + backend.addEventListener("arMixGlobalFxAck",ack=>{ + const pending=pendingGlobalFx; + if(!pending || ack?.requestId!==pending.requestId)return; + if(ack?.ok!==true || ack?.bypassed!==pending.bypassed){ + pendingGlobalFx=null; + status("Global FX rejected · "+String(ack?.error||"stale device revision")); + }else pending.acked=true; + controller?.subscribe(); // ACK alone never establishes physical bypass. + }); backend.addEventListener("arMixNativeFxPowerAck",ack=>{ const p=pendingNativeFxPower; if(!p||ack?.requestId!==p.requestId)return;