diff --git a/.github/workflows/imersib-scene-panorama-normalize.yml b/.github/workflows/imersib-scene-panorama-normalize.yml new file mode 100644 index 000000000..0e851e449 --- /dev/null +++ b/.github/workflows/imersib-scene-panorama-normalize.yml @@ -0,0 +1,50 @@ +name: ImmerSIB scene panorama normalization (approved photography) +on: + push: + branches: + - feat/imersip-on-sonku-p92-single-engine-20261116 + paths: + - 'scripts/normalize_immersib_scene_assets.py' + - '.github/workflows/imersib-scene-panorama-normalize.yml' + - 'assets/imersip/scenes/*.png' + workflow_dispatch: +permissions: + contents: write +concurrency: + group: immersib-photo-panorama-${{ github.ref }} + cancel-in-progress: true +jobs: + approved-venue-panorama: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: true + - name: Install constrained image tooling + shell: bash + run: python -m pip install --disable-pip-version-check 'Pillow==11.3.0' + - name: Normalize approved venue photos (never re-generate speaker sprites) + shell: bash + run: | + python scripts/normalize_immersib_scene_assets.py + python scripts/normalize_immersib_scene_assets.py --check + - name: Commit corrected full-resolution PNGs only to the isolated PR branch + shell: bash + run: | + git add -- assets/imersip/scenes/scene_*.png + if git diff --cached --quiet; then + echo "All six venue photos already have the required aspect" + exit 0 + fi + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git commit -m "fix(immersib): crop approved six venue photos to 2200x922 without PA stretching" + git push origin "HEAD:${GITHUB_REF_NAME}" + - name: Retain final native-source photo evidence + uses: actions/upload-artifact@v4 + with: + name: ImmerSIB-Approved-2200x922-Venue-Photos-${{ github.run_id }} + path: assets/imersip/scenes/scene_*.png + retention-days: 7 + if-no-files-found: error diff --git a/.github/workflows/imersip-p92-single-engine.yml b/.github/workflows/imersip-p92-single-engine.yml new file mode 100644 index 000000000..57e2b790a --- /dev/null +++ b/.github/workflows/imersip-p92-single-engine.yml @@ -0,0 +1,214 @@ +name: ImerSip P9.2 same native SonKu engine — isolated Windows FAT +on: + pull_request: + types: [opened, reopened, synchronize] + paths: + - '.github/workflows/imersip-p92-single-engine.yml' + - 'CMakeLists.txt' + - 'engine/builtin_fx/ImerSipP92*.h' + - 'assets/imersip/**' + - 'tests/imersip_scene_assets_contract_test.py' + - 'engine/builtin_fx/SonKuSpatialProcessor.h' + - 'engine/builtin_fx/sonku/**' + - 'src/Main.cpp' + - 'src/NativeBuiltInFx.h' + # Native/engine edits only. Documentation and immutable-checkpoint + # ledger changes have a separate fast contract job, not full JUCE. + - 'tests/imersip_p92_native_test.cpp' + - 'tests/imersip_p92_catalog_contract_test.py' + workflow_dispatch: +permissions: + contents: read +concurrency: + group: imersip-p92-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + source: + name: Fast P9 PCM + ImerSip registration guard + runs-on: ubuntu-latest + timeout-minutes: 12 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Gate accepted six real venue PNGs; forbid rejected asset pack + run: python -m unittest discover -s tests -p 'imersip_scene_assets_contract_test.py' -v + - name: Source contract and no accidental shadow DSP + run: | + set -euo pipefail + python -m unittest discover -s tests -p 'imersip_p92_*contract_test.py' -v + - name: Exact P9.1+P9.2 native PCM foundation 44.1/48k + run: | + set -euo pipefail + c++ -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 \ + tests/sonku_p91_p92_music_bass_foundation_test.cpp -o /tmp/p92-source + /tmp/p92-source + - name: Test ImerSip concert preset audibility, anti-phase and wet room + run: | + set -euo pipefail + c++ -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 \ + tests/imersip_p92_factory_music_test.cpp -o /tmp/imersip-p92-presets + /tmp/imersip-p92-presets + - name: ImmerSIB P9.7 Venue golden and P9.8 scene native PCM + run: | + set -euo pipefail + c++ -std=c++20 -O2 -Wall -Wextra -Werror -pedantic \ + -DSONKU_P7_MEASURED_ELEVATION_RESEARCH \ + -DSONKU_P71_DIRECT_XYZ_RESEARCH \ + -DSONKU_P72_NATIVE_XYZ_RT \ + -DSONKU_P75_MUSIC_SAFE_RESEARCH \ + -DSONKU_P80_TRANSPARENT_BASS_RESEARCH \ + -DSONKU_P82_MULTIBAND_ROOM_RESEARCH \ + -DSONKU_P83_PHYSICAL_SPEAKER_RESEARCH \ + -DSONKU_P84_SINGLE_CORE_FUSION_RESEARCH \ + -DSONKU_P85_WORLD_COHERENCE_RESEARCH \ + -DSONKU_P86_HORIZONTAL_FOCUS_RESEARCH \ + -DSONKU_P87_MUSIC_BODY_RESEARCH \ + -DSONKU_P88_PERCEPTUAL_ALIGNMENT_RESEARCH \ + -DSONKU_P89_DEPTH_COHERENCE_RESEARCH \ + -DSONKU_P90_TRUE_EXTERNAL_RESEARCH \ + -DSONKU_P94_FRONT_BACK_DEPTH_RESEARCH \ + -DSONKU_P95_MUSICAL_PRESENCE_RESEARCH \ + -DSONKU_P96_DISTANCE_REINFORCEMENT_RESEARCH \ + -DSONKU_P97_STAGE_IMPACT_RESEARCH \ + -DSONKU_P98_SCENE_VOICING_RESEARCH \ + tests/immersib_p98_native_sonic_gate.cpp -o /tmp/immersib-p98 + /tmp/immersib-p98 + windows: + name: Actual JUCE ImerSip P9.2 insert + Windows GUI + needs: source + runs-on: windows-2022 + timeout-minutes: 50 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Verify immutable source commit + shell: pwsh + env: + EXPECTED_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + run: | + if ((& git rev-parse HEAD).Trim() -ne $env:EXPECTED_SHA) { + throw 'IMERSIP_P92_WRONG_SOURCE_SHA' + } + - uses: actions/checkout@v4 + with: + repository: juce-framework/JUCE + ref: 8.0.15 + path: third_party/JUCE + persist-credentials: false + - name: Obtain pinned WebView2 headers + shell: pwsh + run: | + nuget install Microsoft.Web.WebView2 -Version 1.0.3485.44 -OutputDirectory .deps -NonInteractive + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Configure exact P9 native FX graph and focused CTest + shell: pwsh + run: | + cmake -S . -B build -G "Visual Studio 17 2022" -A x64 ` + -DJUCE_ROOT="$env:GITHUB_WORKSPACE/third_party/JUCE" ` + -DJUCE_WEBVIEW2_PACKAGE_LOCATION="$env:GITHUB_WORKSPACE/.deps" ` + -DARMIX_SONKU_EXPERIMENTAL_NATIVE_XYZ_RT=ON ` + -DARMIX_SONKU_EXPERIMENTAL_MUSIC_SAFE=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P8_TRANSPARENT_BASS=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P82_ROOM=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P83_NATIVE_RT=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P84_NATIVE_RT=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P85_NATIVE_RT=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P86_NATIVE_RT=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P87_NATIVE_RT=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P88_NATIVE_RT=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P89_NATIVE_RT=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P94_FRONT_BACK_DEPTH=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P95_MUSICAL_PRESENCE=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P96_DISTANCE_REINFORCEMENT=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P97_STAGE_IMPACT=ON ` + -DARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING=ON ` + -DBUILD_TESTING=ON + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $tests = (& ctest --test-dir build -C Release --show-only=json-v1 | Out-String | ConvertFrom-Json) + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if ('NativeImerSipP92ExactSonKuCorePCMStateAndACK' -notin + @($tests.tests | ForEach-Object {$_.name})) { + throw 'IMERSIP_P92_NATIVE_TEST_NOT_COMPILED' + } + - name: Compile focused real JUCE audio editor and state first + shell: pwsh + run: | + cmake --build build --config Release --parallel 2 --target ARMixImerSipP92NativeTests + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + ctest --test-dir build -C Release --output-on-failure ` + -R '^NativeImerSipP92ExactSonKuCorePCMStateAndACK$' + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Upload actual JUCE native 100, 125, 150 and 200 percent captures + uses: actions/upload-artifact@v4 + with: + name: ImerSip-P92-Native-JUCE-DPI-Captures-${{ github.run_id }} + path: | + build/ImerSip_P92_JUCE_*.png + build/ImerSip_P92_SCENE_*.png + if-no-files-found: error + retention-days: 14 + - name: Compile authentic production-shaped native GUI research candidate + shell: pwsh + run: | + cmake --build build --config Release --parallel 2 --target ARMixConsole + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $exe = 'build/ARMixConsole_artefacts/Release/AR MIX Studio.exe' + if (-not (Test-Path -LiteralPath $exe -PathType Leaf)) { + throw 'IMERSIP_P92_GUI_MISSING' + } + - name: Package and verify portable Windows application + shell: pwsh + run: | + & ./scripts/package_native_windows.ps1 -BuildDir build -OutputDir dist + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + python scripts/factoryfx_release_bundle.py stage --lock config/factoryfx-approved-releases.json --output dist --best-effort + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & ./scripts/verify_native_windows_artifact.ps1 -OutputDir dist + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + # The release verifier uses a strict dist/ allowlist. Attach the + # acoustic FAT and MIT KEMAR attribution OUTSIDE verified dist/, + # not by making unverified changes to the portable application. + New-Item -ItemType Directory -Path field_candidate -Force | Out-Null + Copy-Item -LiteralPath dist -Destination field_candidate/ArSonMix-Portable -Recurse + Copy-Item -LiteralPath docs/IMERSIP_P92_SINGLE_NATIVE_ENGINE_FAT_20261116.md -Destination field_candidate/IMERSIP_P92_FIELD_FAT.md + Copy-Item -LiteralPath docs/THIRD_PARTY_8D_SONKU_HRTF.md -Destination field_candidate/THIRD_PARTY_8D_SONKU_HRTF.md + - uses: actions/upload-artifact@v4 + with: + name: ImerSip-P92-Shared-Core-Windows-x64-${{ github.run_id }} + path: field_candidate/ + if-no-files-found: error + retention-days: 14 + compression-level: 0 diff --git a/.github/workflows/sonku-p83-native-speaker-gates.yml b/.github/workflows/sonku-p83-native-speaker-gates.yml index ff7353ca2..c7cd22721 100644 --- a/.github/workflows/sonku-p83-native-speaker-gates.yml +++ b/.github/workflows/sonku-p83-native-speaker-gates.yml @@ -21,7 +21,13 @@ concurrency: cancel-in-progress: true jobs: native-source: - name: Native C++ P8.3 source, PCM/stems/no-null and Music Bed invariants + # This is the intentionally REJECTED P8.3 historical acoustic candidate, + # not a generic SonKu, P9.1/P9.2 or ImerSip qualification check. + # Shared SonKu/CMake edits still trigger workflow discovery, but only + # explicit P8.3 research branches (or deliberate manual dispatch) run + # its original STRICT negative acoustic veto. Never weaken the test. + if: ${{ github.event_name == 'workflow_dispatch' || contains(github.head_ref, 'p83') }} + name: P8.3-only historical acoustic veto — never P9 release gate runs-on: ubuntu-latest timeout-minutes: 10 steps: diff --git a/.github/workflows/spatial-audio-authority-fast.yml b/.github/workflows/spatial-audio-authority-fast.yml new file mode 100644 index 000000000..9e80084a3 --- /dev/null +++ b/.github/workflows/spatial-audio-authority-fast.yml @@ -0,0 +1,30 @@ +name: Spatial audio ownership — fast contract (no JUCE) +on: + pull_request: + paths: + - 'config/spatial_audio_authority.json' + - 'docs/SPATIAL_AUDIO_AUTHORITY.md' + - 'docs/IMERSIP_P92_SINGLE_NATIVE_ENGINE_FAT_20261116.md' + - 'tests/imersip_p92_*contract_test.py' + - '.github/workflows/sonku-p83-native-speaker-gates.yml' + - '.github/workflows/spatial-audio-authority-fast.yml' + workflow_dispatch: +permissions: + contents: read +concurrency: + group: spatial-authority-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + authority: + name: Check frozen P9 acoustics and unambiguous P83/ImerSip ownership + runs-on: ubuntu-latest + timeout-minutes: 4 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Validate authority ledger and original acoustic source fingerprints + run: | + set -euo pipefail + python -m unittest discover -s tests -p 'imersip_p92_*contract_test.py' -v diff --git a/CMakeLists.txt b/CMakeLists.txt index d8491880c..a3442e604 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -96,6 +96,41 @@ if(ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT AND NOT ARMIX_SONKU_EXPERIMENTAL_P89_NATIVE_RT) message(FATAL_ERROR "P9.0 requires P8.9 research branch baseline") endif() +# Private P9.4 perceptual A/B: default OFF and never silently changes P9.1. +option(ARMIX_SONKU_EXPERIMENTAL_P94_FRONT_BACK_DEPTH + "Private front/back HRTF/early reflection depth calibration experiment" OFF) +if(ARMIX_SONKU_EXPERIMENTAL_P94_FRONT_BACK_DEPTH AND + NOT ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT) + message(FATAL_ERROR "P9.4 depth cue requires the P9 measured two-speaker engine") +endif() +# Optional P9.5 upward-only, slow electrical musical presence. No public default. +option(ARMIX_SONKU_EXPERIMENTAL_P95_MUSICAL_PRESENCE + "Private P9.5 cinema/venue music-level compensation" OFF) +if(ARMIX_SONKU_EXPERIMENTAL_P95_MUSICAL_PRESENCE AND + NOT ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT) + message(FATAL_ERROR "P9.5 requires P9 measured spatial engine") +endif() +# Private stage-speaker reinforcement, isolated from P9.5 production. +option(ARMIX_SONKU_EXPERIMENTAL_P96_DISTANCE_REINFORCEMENT + "Private P9.6 stage-speaker LF/HF distance retention over 2m" OFF) +if(ARMIX_SONKU_EXPERIMENTAL_P96_DISTANCE_REINFORCEMENT AND + NOT ARMIX_SONKU_EXPERIMENTAL_P95_MUSICAL_PRESENCE) + message(FATAL_ERROR "P9.6 requires P9.5 musical presence and P9 world speaker") +endif() +# P9.7 is research only and never changes the approved P9.6 checkpoint. +option(ARMIX_SONKU_EXPERIMENTAL_P97_STAGE_IMPACT + "Private P9.7 concert bass impact, center HRTF and binaural early air" OFF) +if(ARMIX_SONKU_EXPERIMENTAL_P97_STAGE_IMPACT AND + NOT ARMIX_SONKU_EXPERIMENTAL_P96_DISTANCE_REINFORCEMENT) + message(FATAL_ERROR "P9.7 requires the P9.6 sound-reinforced world-speaker engine") +endif() +# Typed native v12 voicing of Signature/Cinema/Studio: P9.7 Venue remains immutable. +option(ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING + "Private P9.8 scene bass/voice/air voicing; preserve approved P9.7 Venue" OFF) +if(ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING AND + NOT ARMIX_SONKU_EXPERIMENTAL_P97_STAGE_IMPACT) + message(FATAL_ERROR "P9.8 requires P9.7 approved stage; public default OFF") +endif() set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -230,10 +265,25 @@ endif() file(GLOB ARMIX_GUITAR_SKIN_PNGS CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/design-references/guitar-fx/assets/gfx-*.png") list(SORT ARMIX_GUITAR_SKIN_PNGS) +# ImmerSIB embeds only the six approved venue photographs. +# Panel, buttons, sliders and knob are native JUCE paint. +# The six approved photo-real venue scenes are independent full-size PNGs. +# They are embedded into the JUCE executable, with no external image folder. +set(ARMIX_IMERSIB_SCENE_NAMES + scene_live_concert scene_royal_concert_hall scene_arena_thunder + scene_front_row_power scene_symphonic_palace scene_velvet_cinema) +foreach(name IN LISTS ARMIX_IMERSIB_SCENE_NAMES) + set(ARMIX_IMERSIB_SCENE_PNG "${CMAKE_CURRENT_SOURCE_DIR}/assets/imersip/scenes/${name}.png") + if(NOT EXISTS "${ARMIX_IMERSIB_SCENE_PNG}") + message(FATAL_ERROR "Missing ImmerSIB scene art: ${ARMIX_IMERSIB_SCENE_PNG}") + endif() + list(APPEND ARMIX_IMERSIB_SCENE_PNG_SOURCES "${ARMIX_IMERSIB_SCENE_PNG}") +endforeach() juce_add_binary_data(ARMixAssets SOURCES "${ARMIX_APPROVED_GUI_DIR}/index.html" ${ARMIX_APPROVED_GUI_BINARIES} ${ARMIX_GUITAR_SKIN_PNGS} - "${ARMIX_BRAND_DIR}/arsonmix-256.png") + "${ARMIX_BRAND_DIR}/arsonmix-256.png" + ${ARMIX_IMERSIB_SCENE_PNG_SOURCES}) target_include_directories(ARMixConsole PRIVATE "${ARMIX_APPROVED_GUI_DIR}") target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h engine/builtin_fx/HarmonyDsp.h engine/builtin_fx/HarmonyMusicKey.h engine/builtin_fx/ChannelHarmonyProcessor.h engine/builtin_fx/SonKuSpatialProcessor.h engine/builtin_fx/sonku/SonKuSpatialCore.h engine/builtin_fx/sonku/SonKuMeasuredHrir.h src/VstOrbitController.h engine/core/MixerRoutingPlan.h engine/core/ChannelRoutingContract.h engine/core/ChannelSendPlan.h engine/core/AuxBusPlan.h engine/core/PreparedMixerBlock.h engine/core/MasterOutputMonoPolicy.h engine/core/LiveChannelFxGraph.h engine/core/PreparedNativeMixerSession.h engine/core/NativeDryRouteCommand.h engine/core/RealtimeRoutePublisher.h engine/device/LiveInputPortRegistry.h src/LiveDryRoutingLab.h engine/core/OrbitPhase.h engine/core/OrbitControlPolicy.h engine/core/OrbitMotion.h engine/core/OrbitDistanceMapping.h engine/core/DearVrPolarPolicy.h src/PluginCatalog.h src/NativeFxParameterHotkey.h src/FactoryFxRegistry.h src/PluginVault.h src/PortableWorkspace.h src/StudioBackup.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/NativeShowSchema.h src/NativeDryShowRecall.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/core/CallbackCadenceEvidence.h engine/diagnostics/CrackleEvidenceWindow.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h engine/device/PeriodCapabilityEvidence.h engine/device/SessionLifecycle.h engine/device/WasapiCapabilityProbe.h engine/device/JuceIndependentClockDevice.h engine/device/LiveSecondaryOutputDevice.h engine/core/LiveOutputRouteGate.h engine/device/ClockBridgeSizing.h engine/device/IndependentStreamFormatFence.h engine/device/DirectRestoreBackoff.h engine/device/IndependentStreamWatchdog.h engine/device/BridgeContinuityGate.h engine/device/EndpointIdentityPolicy.h engine/device/WasapiEndpointIdentityGuard.h engine/device/AsioStartupPolicy.h engine/device/AsioPriorityDeviceManager.h engine/device/JuceActivePortSnapshot.h engine/device/AsioRegistrationPolicy.h engine/device/AsioRegistryIdentityProbe.h engine/device/DirectRouteFence.h) @@ -312,7 +362,18 @@ target_compile_definitions(ARMixConsole PRIVATE $<$:ARMIX_SONKU_EXPERIMENTAL_P89_NATIVE_RT=1> $<$:SONKU_P89_DEPTH_COHERENCE_RESEARCH=1> $<$:ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT=1> - $<$:SONKU_P90_TRUE_EXTERNAL_RESEARCH=1>) + $<$:SONKU_P90_TRUE_EXTERNAL_RESEARCH=1> + $<$:SONKU_P94_FRONT_BACK_DEPTH_RESEARCH=1> + $<$:ARMIX_SONKU_EXPERIMENTAL_P94_FRONT_BACK_DEPTH=1> + $<$:ARMIX_SONKU_EXPERIMENTAL_P95_MUSICAL_PRESENCE=1> + $<$:SONKU_P95_MUSICAL_PRESENCE_RESEARCH=1> + $<$:SONKU_P96_DISTANCE_REINFORCEMENT_RESEARCH=1> + $<$:ARMIX_SONKU_EXPERIMENTAL_P96_DISTANCE_REINFORCEMENT=1> + $<$:SONKU_P97_STAGE_IMPACT_RESEARCH=1> + $<$:ARMIX_SONKU_EXPERIMENTAL_P97_STAGE_IMPACT=1> + $<$:SONKU_P98_SCENE_VOICING_RESEARCH=1> + $<$:ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING=1>) + if(WIN32) # Windows retains its proven ASIO-first / WASAPI / static WebView2 distribution. # Never link Windows loader or sound APIs into macOS/Linux builds. @@ -323,7 +384,7 @@ if(WIN32) # Dedicated INITGUID TU supplies PKEY_AudioEndpoint_FormFactor and # PKEY_AudioEngine_DeviceFormat to the Windows MMDevice discovery path. target_sources(ARMixConsole PRIVATE engine/device/WindowsAudioPropertyKeys.cpp) - target_link_libraries(ARMixConsole PRIVATE ole32 uuid advapi32) + target_link_libraries(ARMixConsole PRIVATE ole32 uuid advapi32 dwmapi) endif() target_link_libraries(ARMixConsole PRIVATE @@ -850,6 +911,46 @@ if(BUILD_TESTING) SONKU_P90_TRUE_EXTERNAL_RESEARCH=1) add_test(NAME NativeSonKuP90JuceV11AppliedAckAndLegacyRestore COMMAND ARMixSonKuP90NativeTests) + # Same P9.2 core, independent ImerSip identity and IMRS. + juce_add_console_app(ARMixImerSipP92NativeTests + PRODUCT_NAME "ArSonMix ImerSip P92 Native Tests") + target_sources(ARMixImerSipP92NativeTests PRIVATE + tests/imersip_p92_native_test.cpp) + target_compile_features(ARMixImerSipP92NativeTests PRIVATE cxx_std_20) + target_link_libraries(ARMixImerSipP92NativeTests PRIVATE + ARMixAssets + juce::juce_audio_processors + juce::juce_recommended_config_flags) + get_target_property(IMERSIP_P92_DEFINES + ARMixSonKuP90NativeTests COMPILE_DEFINITIONS) + target_compile_definitions(ARMixImerSipP92NativeTests + PRIVATE ${IMERSIP_P92_DEFINES}) + if(ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING) + target_compile_definitions(ARMixImerSipP92NativeTests PRIVATE + SONKU_P94_FRONT_BACK_DEPTH_RESEARCH=1 + ARMIX_SONKU_EXPERIMENTAL_P94_FRONT_BACK_DEPTH=1 + SONKU_P95_MUSICAL_PRESENCE_RESEARCH=1 + ARMIX_SONKU_EXPERIMENTAL_P95_MUSICAL_PRESENCE=1 + SONKU_P96_DISTANCE_REINFORCEMENT_RESEARCH=1 + ARMIX_SONKU_EXPERIMENTAL_P96_DISTANCE_REINFORCEMENT=1 + SONKU_P97_STAGE_IMPACT_RESEARCH=1 + ARMIX_SONKU_EXPERIMENTAL_P97_STAGE_IMPACT=1 + SONKU_P98_SCENE_VOICING_RESEARCH=1 + ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING=1) + endif() + if(ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING) + add_executable(ARMixImmerSIBP98NativeSonicGate + tests/immersib_p98_native_sonic_gate.cpp) + target_compile_features(ARMixImmerSIBP98NativeSonicGate PRIVATE cxx_std_20) + get_target_property(IMMERSIB_NATIVE_P98_DEFINES + ARMixImerSipP92NativeTests COMPILE_DEFINITIONS) + target_compile_definitions(ARMixImmerSIBP98NativeSonicGate + PRIVATE ${IMMERSIB_NATIVE_P98_DEFINES}) + add_test(NAME NativeImmerSIBP98VenueGoldenAndScenePreservation + COMMAND ARMixImmerSIBP98NativeSonicGate) + endif() + add_test(NAME NativeImerSipP92ExactSonKuCorePCMStateAndACK + COMMAND ARMixImerSipP92NativeTests) endif() endif() endif() diff --git a/assets/imersip/scenes/scene_arena_thunder.png b/assets/imersip/scenes/scene_arena_thunder.png new file mode 100644 index 000000000..42b083054 Binary files /dev/null and b/assets/imersip/scenes/scene_arena_thunder.png differ diff --git a/assets/imersip/scenes/scene_front_row_power.png b/assets/imersip/scenes/scene_front_row_power.png new file mode 100644 index 000000000..a1e59793c Binary files /dev/null and b/assets/imersip/scenes/scene_front_row_power.png differ diff --git a/assets/imersip/scenes/scene_live_concert.png b/assets/imersip/scenes/scene_live_concert.png new file mode 100644 index 000000000..87cb8eccf Binary files /dev/null and b/assets/imersip/scenes/scene_live_concert.png differ diff --git a/assets/imersip/scenes/scene_royal_concert_hall.png b/assets/imersip/scenes/scene_royal_concert_hall.png new file mode 100644 index 000000000..434e1a7f8 Binary files /dev/null and b/assets/imersip/scenes/scene_royal_concert_hall.png differ diff --git a/assets/imersip/scenes/scene_symphonic_palace.png b/assets/imersip/scenes/scene_symphonic_palace.png new file mode 100644 index 000000000..28112e610 Binary files /dev/null and b/assets/imersip/scenes/scene_symphonic_palace.png differ diff --git a/assets/imersip/scenes/scene_velvet_cinema.png b/assets/imersip/scenes/scene_velvet_cinema.png new file mode 100644 index 000000000..0b1669936 Binary files /dev/null and b/assets/imersip/scenes/scene_velvet_cinema.png differ diff --git a/config/spatial_audio_authority.json b/config/spatial_audio_authority.json new file mode 100644 index 000000000..f1f626409 --- /dev/null +++ b/config/spatial_audio_authority.json @@ -0,0 +1,201 @@ +{ + "schemaVersion": 1, + "purpose": "Research ownership/acceptance ledger. NOT audio runtime config, session state, or release approval.", + "selectedSonKuBaseline": { + "pr": 719, + "issue": 720, + "immutableCheckpointBranch": "checkpoint/sonku-p91-p92-operator-confirmed-20261116", + "immutableCheckpointSha": "763706a15a2617a10d23b5e2e43eb5689e454ccb", + "nativeRenderer": "SonKuSpatialCore", + "researchRenderMode": 9, + "modeNameInCode": "MusicSpatialP90", + "actualAudioFeatures": "P9.1 + P9.2: world-positioned stereo sources, P9 complementary LF world bass and bounded axial room modes", + "releaseQualified": false, + "acousticSourceBlobSha1": { + "engine/builtin_fx/sonku/SonKuSpatialCore.h": "5b8e26eaf4673fe2235d0b87d60b4ddc619e9602", + "engine/builtin_fx/sonku/SonKuP91P92WorldBassFoundation.h": "938cb96a5b7181d37f5c290c13fd39370ab18826", + "engine/builtin_fx/sonku/SonKuP90StereoDecoder.h": "f760c673dec8031f4dfcc76d6f1fee36beffa043", + "engine/builtin_fx/sonku/SonKuEarlyReflections.h": "46209c6b841bb8eb03bbd2dc65b3ac080586a826", + "engine/builtin_fx/sonku/SonKuMusicalReverb.h": "c2f273ef7c1ee26c5566b05568416e5cedaef6c4", + "engine/builtin_fx/sonku/SonKuMeasuredHrir3D.h": "816e7255939f0bb262374a5b4c0240438ec1e3a0", + "engine/builtin_fx/sonku/SonKuHrtfTonalCalibration.h": "233e2b26caf51e88df4ed82babc442f2b341c2d7" + } + }, + "imersip": { + "activeIntegrationPr": 722, + "basePr": 719, + "catalogIdentity": "armix.builtin.imersip.v1", + "processor": "ImerSipP92Processor", + "nativeRenderer": "SonKuSpatialCore", + "settingsFormat": "IMRS", + "settingsVersion": 7, + "nestedSonKuVersion": 12, + "researchOnly": true, + "independentSpatialDsp": false, + "releaseQualified": false, + "displayName": "ImmerSIB", + "previousDisplayName": "ImerSip", + "renamePolicy": "Display-only rebrand. Preserve catalogIdentity, native API, IMRS wire state and saved .smix." + }, + "audioScenes": { + "operatorCheckpointObservation": { + "speakerSpreadDeg": 82, + "distanceMeters": 1.6, + "spacePreset": 3, + "earlyRoom": 1, + "lateRoom": 0.62, + "spatialMix": 1, + "outputGainDb": 7, + "revolutionSeconds": 8.5, + "notFactoryDefault": true, + "referenceIssue": 720 + }, + "p92NeutralABReference": { + "speakerSpreadDeg": 82, + "distanceMeters": 1.6, + "spacePreset": 3, + "earlyRoom": 0.78, + "lateRoom": 0.33, + "spatialMix": 1, + "outputTrimLinear": 1, + "moving": false, + "internalRegressionOnly": true, + "userVisiblePreset": false + }, + "imersipNewInsertDefault": { + "presetId": 2, + "name": "Live Concert — nearfield vocal clarity candidate", + "speakerSpreadDeg": 112, + "distanceMeters": 3, + "spacePreset": 3, + "earlyRoom": 1.36, + "lateRoom": 0.84, + "spatialMix": 1, + "outputTrimLinear": 1.8, + "sceneVoicing": 4, + "releaseQualified": false, + "outputGainDb": 5.10545 + }, + "imersipAuditionPresetIds": { + "2": "Live Concert — 3.0m, 112°, Early136%, Late84%, vocal-detail4, trim1.8", + "3": "Royal Concert Hall — 3.2m, 106°, Early155%, Late78%, detail4", + "4": "Arena Thunder — 3.7m, 124°, Early145%, Late86%, impact5", + "5": "Front Row Power — 1.4m, 104°, Early126%, Late70%, detail4", + "6": "Symphonic Palace — 2.7m, 118°, Early160%, Late80%, detail4", + "7": "Velvet Cinema — 2.8m, 108°, Early142%, Late82%, Cinema3" + }, + "ownerScreenshotObservation": { + "speakerSpreadDeg": 150, + "distanceMeters": 1.6, + "spacePreset": 3, + "earlyRoom": 1, + "lateRoom": 0.91, + "spatialMix": 1, + "outputGainDb": 4.1, + "notFactoryDefault": true, + "separateFromIssue720": true + } + }, + "nonAuthoritativeCandidates": [ + { + "pr": 706, + "role": "Superseded ImerSip P8 DSP; archived for comparison and IMRS v1-v5 migration" + }, + { + "pr": 718, + "role": "Divergent P9.1/P9.2 acoustic alternative; retained for scientific A/B, not selected renderer" + }, + { + "pr": 717, + "role": "P9.0 ancestor; dependency of selected P9.1/P9.2 #719, not current owner-accepted version" + } + ], + "historicalP83": { + "workflow": ".github/workflows/sonku-p83-native-speaker-gates.yml", + "qualification": "REJECTED_LEGACY_NEGATIVE_ACOUSTIC_EVIDENCE", + "automaticExecution": "only pull request head refs containing p83", + "manualExecution": "workflow_dispatch", + "notP9OrImerSipReleaseGate": true, + "strictOriginalFidelityVetoRetained": true + }, + "production": { + "mainMustRemainUnchanged": true, + "noAutomaticMerge": true, + "physicalHeadphoneAbStillRequired": true + }, + "immersibP98Integration": { + "product": "ImmerSIB", + "reason": "Operator explicitly requested forward-port P9.7 approved Venue and P9.8 voicing without changing production main or the frozen P9.2 checkpoint.", + "venueOperatorCheckpointBranch": "checkpoint/sonku-p97-venue-mega-space-owner-approved-20261116", + "sourceBranch": "feat/sonku-p98-signature-cinema-studio-voicing-20261116", + "venueGolden": { + "stageDegrees": 106, + "distanceMeters": 10, + "spacePreset": 3, + "earlyRoom": 1, + "lateRoom": 1, + "outputTrimLinear": 1.8, + "sceneVoicing": 0 + }, + "nativeRenderMode": 9, + "featureFlag": "ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING", + "releaseQualified": false, + "acousticSourceBlobSha1": { + "engine/builtin_fx/sonku/SonKuSpatialCore.h": "25517a03b6b128a7b0d45436e5e7a1421ff855ce", + "engine/builtin_fx/sonku/SonKuP91P92WorldBassFoundation.h": "63551d22e8dff672fe136131c32d28b568bb3170", + "engine/builtin_fx/sonku/SonKuP94FrontBackDepthCue.h": "f0f88088c68ef6865d64c240c4c87accaf136070", + "engine/builtin_fx/sonku/SonKuP95MusicalPresence.h": "ece40572b04d4b586a61c56cf1fd1f77c1f295e7", + "engine/builtin_fx/sonku/SonKuP96DistanceReinforcement.h": "a32fb6e6fdd431901323d4278c51991607c02d84", + "engine/builtin_fx/sonku/SonKuP97StageImpact.h": "5384fd3cc67c31f0a8038b315856d20933249b5b", + "engine/builtin_fx/sonku/SonKuP98SceneVoicing.h": "90bab191a62601021c4a7a77d64e0e4d408d3011", + "engine/builtin_fx/sonku/SonKuEarlyReflections.h": "5a6a9b48cfdc60729f130c61110c8d8590b20f35", + "engine/builtin_fx/sonku/SonKuSourcePlacement3D.h": "9afb959bed292626c3097c2a382208ce8798e90c" + }, + "productTuning": { + "status": "nearfield_vocal_masking_candidate_owner_not_auditioned", + "archivedP97VenueGolden": "10m / 106° / ER100% / late100% / trim1.8 / voicing0, PRIVATE test-only", + "newFactoryRangeMeters": [ + 1, + 4 + ], + "newEarlyRoomRangePercent": [ + 0, + 180 + ], + "reason": "Owner hears farfield presets as vague and 100% early room too weak; M/S masking relief is source-domain frequency-selective, not stem separation", + "newDSPBlobSha1": { + "engine/builtin_fx/sonku/SonKuSpatialCore.h": "25517a03b6b128a7b0d45436e5e7a1421ff855ce", + "engine/builtin_fx/sonku/SonKuEarlyReflections.h": "5a6a9b48cfdc60729f130c61110c8d8590b20f35", + "engine/builtin_fx/sonku/SonKuP98SceneVoicing.h": "90bab191a62601021c4a7a77d64e0e4d408d3011", + "engine/builtin_fx/sonku/SonKuSourcePlacement3D.h": "9afb959bed292626c3097c2a382208ce8798e90c" + }, + "legacyIMRS": "Old 4-10m restored scenes migrate source distance down to room-safe <=4m; no codec version or FX ID change", + "physicalHeadphoneABRequired": true, + "sceneBalance": "44.1k nearfield PCM showed Symphonic 3.6m was <.85 archival Venue energy; retargeted to 2.7m, Cinema to 2.8m without gain-only inflation.", + "vocalBodyCorrection": { + "status": "audition_candidate_not_owner_approved", + "userEvidence": "Dua Lipa live concert playback: center vocal sounds thin, sharp, and unpleasant after previous 2.05kHz/5.2kHz voicing, despite PCM and Windows builds passing", + "diagnosis": "Stacked 1.9k/2.05k source+ear presence, high-air on side and early reflection, no independent center 285Hz body in ImmerSIB profiles 4/5", + "correctsProfiles": [ + 4, + 5 + ], + "chosenDSP": "pre-KEMAR world-center broad 285Hz body; suppress SIDE upper-mid 2.05k+3.45k; gentle linked-ear 3.45k fatigue notch after render; remove stacked >5.2k boost in profiles 4/5", + "constraints": "No actual vocal stem/AI extraction, no extra HRTF, no output loudness chase, no added latency, no tail/room change, no changes in frozen P9.7 Venue or SONK profiles 0..3", + "beforeVoicingGitBlob": "cc769dade5a752e0f84f02348e07332bce7c268b", + "afterVoicingGitBlob": "90bab191a62601021c4a7a77d64e0e4d408d3011", + "requiredChecks": "Native source & finished stereo tone spectral balance, 44.1/48k exact Venue PCM hash, antiphase, mono, IMRS7/SONK12 state roundtrip, JUCE Windows and portable EXE build, physical loudness-matched Dua Lipa concert FAT", + "qualityGateRevision": { + "reason": "Legacy 85% venue-total-electric-energy gate excluded the vocal chest/body band and rewarded shrillness; replace with whole native scene tonal transfer plus finite peak, anti-phase, PCM hash and 70% minimum electric safety floor", + "wholePcmConditions": [ + "center 285Hz body ratio >1.08 to neutral voicing, same scene", + "SIDE 3.45kHz energy ratio <1.05", + "SIDE 7.4kHz retained >0.65", + "legacy P9.7 44.1/48k PCM hash must remain exact" + ], + "notEvidenceOf": "audible vocal source isolation, mastered-song loudness, subjective preference or universal de-essing" + } + } + } + } +} diff --git a/docs/IMERSIP_P92_SINGLE_NATIVE_ENGINE_FAT_20261116.md b/docs/IMERSIP_P92_SINGLE_NATIVE_ENGINE_FAT_20261116.md new file mode 100644 index 000000000..d2a114ee9 --- /dev/null +++ b/docs/IMERSIP_P92_SINGLE_NATIVE_ENGINE_FAT_20261116.md @@ -0,0 +1,27 @@ +# ImerSip P9.1/P9.2 — single-engine adoption (16 November 2026) + +**User reference:** 8D-SonKu P9.1–P9.2 is reported to sound external and alive on the user's real headphones. Do not replace its acoustic renderer with the older ImerSip P8.2/P8.4 bespoke dry-MID/room-enhancer path. + +**New insert audition default** (after owner headphone feedback): `Live Concert`, 150°/2.2 m/Large/Early 100%/Late 91%/+4.8 dB. The original 82°/1.6 m/78%/33%/0 dB reference remains ONLY as an internal PCM regression reference, not in the preset picker. Owner-visible presets now include Live Concert, Royal Concert Hall, Arena Thunder, Front Row Power, Symphonic Palace, and Velvet Cinema. The original screenshot 150°/1.6 m/100%/91%/+4.1 dB remains documented; Front Row Power develops it into a richer audition scene. This is preset-only product tuning; **not** a change to the P9.2 DSP, and neither enhanced gain nor acoustic realism is guaranteed for full-scale mastered material. + +**Canonical ownership and CI classification:** [SPATIAL_AUDIO_AUTHORITY.md](SPATIAL_AUDIO_AUTHORITY.md) and [machine-readable ledger](../config/spatial_audio_authority.json). The ImerSip factory scene is **not** the operator's louder/roomier #720 headphone-test scene. + +**Baseline:** PR #719 commit `763706a15a2617a10d23b5e2e43eb5689e454ccb`. This integration is a new research branch based on that exact PR, not a merge of divergent #706. Production `main` and both older PRs remain untouched. + +## Design + +- **One PCM authority:** `ImerSipP92Processor` inherits the existing native `SonKuSpatialProcessor`, whose single callback invokes the exact P9.1/P9.2 `SonKuSpatialCore` renderer in mode 9. This is inheritance of transport/control, not another sound engine. No P8-only `ImerSipDsp`, HRTF staging, secondary limiter, headphone SIDE widening, EQ, early-reflection boost, or LF shelf. +- **Product identity:** same ImerSip native catalog ID `armix.builtin.imersip.v1`, its own native editor and IMRS state, existing host FX slot routing/bypass. P9 CMake flag is private/opt-in, so public builds are unaffected. +- **Factory vs reference:** the first ImerSip insert now starts in `Live Concert` and the **P9.2 neutral A/B reference** remains separately selectable. Original SonKu product defaults and restored user sessions remain unchanged. This separation is enforced by source and native JUCE tests. +- **Real controls only:** speaker angle, source distance (bounded by real room geometry), EARLY ROOM, LATE ROOM, spatial mix, output gain, manual yaw, KEMAR ear alignment, preset and native per-slot power/close. UI edits go through existing audio ACK; no optimistic DSP success. +- **Session:** new `IMRS` v6 embeds the accepted native 63-byte `SONK` v11 state. Old IMRS v1–v5 are parsed and deliberately migrated into P9 **without** re-enabling P8-only Bass Impact/Detail/Stereo Keep DSP. These old three controls have no bit-perfect P9 analogue and cannot be claimed lossless. Existing room/distance maps are validated and clamped to physical geometry rather than rejected or rendering stale filters. +- **Research limits:** P9 bass modes are parametric, not a measured commercial BRIR. A byte-level native PCM comparison proves no new audio processing; headphone perception remains a user-listening qualification. + +## Mandatory quality gates + +1. Native JUCE P9 core parity: same PCM sample-for-sample as ImerSip insert at 44.1 and 48 kHz with actual stereo music fixture and late tail. +2. Real native FX catalog registration / editor and native host power after stable insert lease; source-only JS or false WebView2 render is not sufficient. +3. Audio queue ACK after processing, IMRS v6 round-trip, old v1–v5 fail-closed migration, corrupted state rejection and no per-callback dynamic allocation. +4. Full Windows JUCE EXE + isolated artifact. No release/merge until exact Windows gates and real headphone A/B pass. + +**Listening:** Compare 8D-SonKu P9.1–P9.2 and ImerSip at identical *native settings* with no other FX. PCM should match; externalization and bass must not change just because the plugin name changed. Then separately audition ImerSip's scene presets. diff --git a/docs/IMMERSIB_P98_CONCERT_FORWARDPORT_20261116.md b/docs/IMMERSIB_P98_CONCERT_FORWARDPORT_20261116.md new file mode 100644 index 000000000..270876a0b --- /dev/null +++ b/docs/IMMERSIB_P98_CONCERT_FORWARDPORT_20261116.md @@ -0,0 +1,26 @@ +# ImmerSIB private P9.7 Venue + P9.8 native engine port (16 Nov 2026) + +**Scope:** experimental ImmerSIB PR #722 only; production main stays unchanged, old IMRS sessions, stable `armix.builtin.imersip.v1`, and saved .smix identities remain. Preset labels displayed as **ImmerSIB**. GUI art work is independent and not declared visually accepted. + +## Sonic reference +The **owner-approved 8D-SonKu P9.7 Venue Mega Space** is the golden reference, branch `checkpoint/sonku-p97-venue-mega-space-owner-approved-20261116`. P9.8 branch `feat/sonku-p98-signature-cinema-studio-voicing-20261116` includes every P9.4–P9.7 stage contribution, and original P9.8 ear/world-source voicings. The actual renderer remains **one native SonKuSpatialCore, mode 9** via `SonKuSpatialProcessor` and existing SPSC/ACK, not a parallel ImmerSIB DSP. + +**Exact Live Concert Venue world scene:** `moving=false, startAzimuth=0deg, stage=106deg, Large 28.8m, distance=10.0m, Early=100%, Late=100%, MIX=100%, outputTrim=1.8 linear, sceneVoicing=0`. This is the same `VENUE` scene defined by `tests/sonku_p98_integrated_scene_test.cpp`. Using voicing=0 deliberately turns OFF P9.8 extra source/early/ear bands so Venue stays the unaltered P9.7 golden. Tests compare full PCM output hash at 44.1/48k to the explicitly recreated reference. + +Other operator-facing scenes: Royal Concert Hall, Arena Thunder, Front Row Power, Symphonic Palace (P9.8 Signature voicing 1 with differing physical stage/room distances), Velvet Cinema (P9.8 Cinema voicing 3). Those are **audition candidates**, not perceptually approved. There is no actual music stem extraction, content-aware separator, or source classifier. P9.8 center band is a modest bilateral source emphasis fed into measured world HRIR before ears; a realistic subjective claim of independent instrument stems would be false. Premium quality requires matched-loudness user A/B. + +## Engineering +- P9.8 source forwards acoustic modules P9.4 front/back, P9.5 music presence, P9.6 reinforcement, P9.7 stage impact, and P9.8 typed voicing, together with P9.8 core and exact P9.2 foundation. Each imported file is fingerprinted in `config/spatial_audio_authority.json`. +- Native SonKu transport is P9.8 v12 but retains ImmerSIB's restricted derived scene admission, the existing virtual methods, and legacy product ID. The SonKu **default standalone constructor retains its original neutral initial scene** in this branch, avoiding unrelated automatic preset changes. +- The user-approved Venue is not modified by P9.8 voicing: `sceneVoicing=0`. Scene changes use existing native SPSC command/ACK. GUI maintains typed voicing with a single accepted scene. +- An enabled P9.8 private build writes append-only **IMRS v7 = 8-byte IMRS header + 67-byte native SONK v12 = 75 bytes**; strict preflight protects against partial state mutation. Previous **IMRS v6 + SONK v11 (71 bytes)** and older IMRS v1–v5 formats restore with neutral voicing. Existing .smix audio slots use the same identity. +- Private `ARMIX_SONKU_EXPERIMENTAL_P94_...`, `P95`, `P96`, `P97`, `P98` CMake flags stay OFF by default. The dedicated ImmerSIB CI config explicitly enables the full five-stage stack; the standalone PCM check compiles exact equivalent flags to prevent a false-green different renderer. +- The editor supports 10m Venue instead of clipping the value to the previous 7.4m UI limit; scene renderer retains safe speaker geometry. + +## Acceptance boundary +1. Fast source test: exact Venue golden PCM hash, all scene profiles have actual distinct non-NaN output, anti-phase stereo doesn't catastrophically null, linked guard sample peaks <= 0.9805 at 44.1/48k. +2. Windows native JUCE: exact per-slot FX behavior, typed scene presets, native ACK/readback, IMRS v7/v6 and v1-v5 compatibility, editor actual layout and package verifier. +3. Real user headphone acceptance: kick/tom attack, warm/controlled LF resonance, centered vocal intelligibility, preserved cymbal/treble brightness, instrument clarity, front/rear depth and immersive stage. Loudness-match carefully; stronger gain alone is not proof of detail or premium quality. The owner-approved Venue must remain selectable and bit-exact. +4. PR remains Draft; no release/merge until owner validates. + +**Notes:** old `tests/imersip_p92_factory_music_test.cpp` remains the historical P9.2 data fixture built without P9.8 flags. New `tests/immersib_p98_native_sonic_gate.cpp` tests the actual P9.8 world engine. Neither silently re-qualifies P8.3 historical rejected mode. diff --git a/docs/SPATIAL_AUDIO_AUTHORITY.md b/docs/SPATIAL_AUDIO_AUTHORITY.md new file mode 100644 index 000000000..51105fe0f --- /dev/null +++ b/docs/SPATIAL_AUDIO_AUTHORITY.md @@ -0,0 +1,81 @@ +# Spatial audio ownership / qualification — single source of truth + +**Public product name: ImmerSIB.** Former visible label: ImerSip. JUCE processor name, editor title, FX Picker and user-facing errors must use **ImmerSIB**. Preserve the original `armix.builtin.imersip.v1` catalog identity, IMRS state, C++ identifiers, asset paths and existing `.smix` sessions for backwards compatibility. + +**Scope (2026-11-16):** `ArSonMix` experimental spatial FX only. This document explains the machine-readable [research authority ledger](../config/spatial_audio_authority.json). The ledger is **not runtime configuration** and must never become a second audio DSP state or be used to silently migrate a user's `.smix`. + +## Which one do we develop? + +| Role | Authoritative reference | Safe decision | +| --- | --- | --- | +| Confirmed P9.1+P9.2 sound baseline | [#719](https://github.com/masarray/arsonmix/pull/719); frozen [issue #720](https://github.com/masarray/arsonmix/issues/720), SHA `763706a15a2617a10d23b5e2e43eb5689e454ccb` | **Keep immutable**, compare every acoustic change with it | +| Active ImerSip integration | [#722](https://github.com/masarray/arsonmix/pull/722) stacked on #719 | Only ImerSip development direction; same P9 core | +| Old ImerSip P8 DSP | [#706](https://github.com/masarray/arsonmix/pull/706) | SUPERSEDED; retain branch only for historical A/B and IMRS v1-v5 restoration | +| Divergent P9.1/P9.2 trial | [#718](https://github.com/masarray/arsonmix/pull/718) | **NOT** identical to #719; unselected alternative, not to be merged by accident | +| P9.0 | [#717](https://github.com/masarray/arsonmix/pull/717) | Required ancestor of #719, not the P9.1/P9.2 sound reference | +| Legacy P8.3 | `sonku-p83-native-speaker-gates.yml` | Rejected source-quality candidate. Preserve its strict red evidence, but invoke only from P83-specific PRs or deliberately via manual dispatch | + +**Important naming clarification:** `SonKuSpatialCore` uses **`renderMode=9` and internal enum `MusicSpatialP90`** for the reconciled P9.1/P9.2 **algorithm**. That numeric mode is retained for SONK v11 and `.smix` compatibility. It **does not mean** the renderer reverted to P9.0. The P9.1/P9.2 world-bass foundation is inside that same compiled mode. Never invent mode 10, second convolvers, duplicate stereo matrix, or a separate P9-only audio callback just to make a marketing version label match. + +## Sound and factory defaults must not be conflated + +- **New ImerSip insert factory** (`Live Concert`): static FRONT, stage **150°**, distance **2.2 m**, Large 28.8m, EARLY **100%**, LATE **91%**, MIX **100%**, OUTPUT **+4.8 dB**. This is a user-feedback-led audition **candidate**, not guaranteed loudness or perceptual validation. +- **Neutral A/B is removed from the UI entirely**, as requested. The exact original reference remains an **internal test function only** (`imersipP92ReferenceScene()`) for PCM regression, not a user-facing preset, not a hidden selectable item. +- User's **original ImerSip screenshot** remains recorded as evidence: 150°, 1.6m, ER 100%, late 91%, +4.1 dB. It is *not* the older independent #720 SonKu screenshot. The revised `Front Row Power` id 5 intentionally strengthens this close-stage idea (ER 100%, Late 97%, +5.2 dB). +- Revised owner-facing choices: **Live Concert** (positive baseline unchanged), **Royal Concert Hall**, **Arena Thunder**, **Front Row Power**, **Symphonic Palace**, and **Velvet Cinema**. These use one native P9.2 DSP with different direct distance, stage width, early vs late room and gain; descriptions reflect audition intent, not measured acoustic hall certification. +- [Operator's frozen P9 checkpoint #720](https://github.com/masarray/arsonmix/issues/720): screenshot with **82°, 1.6m, Large, reflections 100%, reverb 62%, output +7 dB and revolution time 8.5s**. These are owner test values **not accepted factory defaults**. The moving toggle / static status was not established from the revolution-time readout alone. +- Changing factory presets only affects **new, empty insert instances**. IMRS v6 accepted state and old v1-v5 migration remain unchanged; a saved Custom 150° preset must not be overwritten on reopen. +- A physical speaker farther away changes direct-to-reverberant balance; it does **not automatically eliminate phase cancellation**. Presets use 2.2–3.0 m for audition, maintain independent L/R HRTF and retain the source anti-phase rejection guard. +- The user wants a perceptibly louder, enveloping and rich effect: the output gain candidates are not a blind automatic loudness guarantee. The existing linked 0.98f peak guard protects sample peaks; mastered near-0 dBFS tracks may trigger reduction/compression. Compare actual levels with BS.1770 LUFS and true peak where available, and inspect limiting/noise at native PCM. +- Never overwrite a user's accepted settings with any of these on session restoration. Compare at **identical native scene and matched actual output loudness**, not just equal knob labels. + +## Frozen acoustic source fingerprints + +The ledger pins the **Git blob SHA-1** of seven source files making up the validated P9 acoustic transfer, including the measured HRTF front end, source-to-ear stereo decoder, world-positioned bass, early reflections, and late room. The independent Python contract recomputes each blob from checkout bytes. Any unintended change fails fast **even if `renderMode=9` and all interface names remain unchanged**. An intentional sound update requires a newly recorded operator-approved checkpoint and corresponding ledger review; **do not edit expected hashes merely to turn CI green**. These are source-provenance checks, not a replacement for headphone listening or a claim of identical compiler output on every platform. + +Only native/engine edits trigger the expensive ImerSip Windows FAT; documentation/authority changes use the separate fast `spatial-audio-authority-fast.yml` contract instead. + +## Ownership boundaries and CI classification + +1. **Audio truth:** `SonKuSpatialCore` compiled with explicit isolated P9 research flags. ImerSip is a distinct `armix.builtin.imersip.v1` FX identity but inherits the same `SonKuSpatialProcessor` graph, not the previous `ImerSipDsp`. No unapproved DSP layering. +2. **Persistence truth:** `IMRS v6` wraps real `SONK v11` accepted state. Old IMRS schemas are deliberately mapped to P9 parameters, not acoustically lossless. Invalid v6 must be rejected *before* mutation. GUI effects apply only after real PCM ACK and per-slot host Power uses actual host bypass. +3. **Qualification truth:** PR #722's focused native source PCM, actual Windows JUCE CTest, GUI EXE and package verifier are the relevant **engineering acceptance checks**; the old P8.3 check is an **archived, known-rejected acoustic reference** and is **not** the P9/ImerSip release gate. No strict assertion is removed from P8.3; it still executes on explicitly named P83 PR branches and via manual workflow dispatch. +4. **Release truth:** A green source/Windows CI run does **not** mean perceptual qualification, ASIO hardware FAT, headphone preference parity or public release. Keep PR #722 draft and production `main` untouched until explicit decision. + +## Future safe workflow + +Start from the **immutable checkpoint** for acoustic experiments; use #719 lineage for ImerSip. Run source identity/PCM parity before expensive Windows, then exact-commit native JUCE/state/host-bypass and approved GUI/distribution gates. Require user headphone A/B if altering P9 DSP. For P83-specific research, use a head branch containing `p83` or manually dispatch the archived P83 workflow. Do not delete its recorded rejection or turn an objectively failed P83 sound experiment into an artificial CI success. + +## ImmerSIB P9.7 + P9.8 scene tuning — owner-directed candidate (16 Nov 2026) + +- **Never replace the accepted Venue**: preset ID 2 is P9.7 Venue Mega Space at 10m / 106° / full early and late room / output trim 1.8, with voicing ID 0; all preexisting P9.7 and P9.8 voicing curves 0–3 remain **bit-identical**. +- **Additive P9.8 engine extension**: native voicing ID 4 (`ImmerSIBDetail`) raises the measured-speaker HRIR center presence gently, improves vocal/foreground midband articulation and enhances real directional early-reflection air. ID 5 (`ImmerSIBImpact`) is tuned for physical LF/kick body and stage, within the same world-speaker graph. IDs 4–5 are private candidate *scene parameter profiles*, not extracted instruments/stems. No crossfeed/delay or dry-stereo widening is added. +- Royal Concert Hall, Front Row Power, and Symphonic Palace use ID 4; Arena Thunder ID 5; Velvet Cinema existing Cinema ID 3. Exact preset geometry and gain remain unchanged to isolate voicing effects. +- **Deliberate research hash change**, not accidental DSP drift: `SonKuP98SceneVoicing.h` originally Git blob `78d8ff28aaf9115a0d1cfff99a6cbb08d0b2bf39`; additive extension blob `5b2438d9b743612c0d22a9b7f9984b1a0289ee3a`. Both hashes are recorded in the authority ledger. The P9.7 Venue golden PCM must remain bit-exact at 44.1/48k and the existing 0–3 voicing trajectories remain identical. +- **State compatibility**: the existing serialized SONK v12 / IMRS v7 32-bit voicing field carries IDs 4–5 without format change; IMRS v6 migrates to neutral 0; stored `armix.builtin.imersip.v1` FX identity remains unchanged. +- **Acceptance boundaries**: measured PCM fidelity, finite peaks, anti-phase survival, room/side energy, and Windows JUCE tests qualify a candidate, not proof of isolated instrument stems or owner-approved subjective enjoyment. Physical headphones, matched loudness, and mastered content are mandatory before release. + +## ImmerSIB nearfield vocal priority — 2026-11-16 (owner feedback, CANDIDATE) + +- The operator reported previous 4.5–10m presets as too vague. The public P9.8 factory/GUI now uses **1–4m** only (Studio 7.2m has physical geometry cap 3.05m). Former **10m P9.7 Venue** remains an immutable private audio regression fixture (`imersipP97VenueGoldenScene()`); the public Live Concert is **deliberately revoiced** at 3m and is NOT falsely described as the old Venue PCM. +- Early Room is **0–180%** only for native mode 9. From 0–100%, existing wall gains and PCM are unchanged. >100% physical wall-material tap value stays clamped at 100%, while the bounded independent early-reflection presence factor continues increasing. Late Room remains separately 0–100%; raising early is NOT a separate reverb feedback loop and does not create new reflection times. +- `SonKuP98SceneVoicing` profiles 4 (Detail) and 5 (Impact) now add two stable fixed-biquad SIDE-presence filters and a single-pole SIDE-high-air spectral shape **BEFORE** the original two world-speaker KEMAR HRIRs. This offers restrained frequency-specific masking relief for center-dominant vocals vs lateral material; it **cannot identify vocals, recover multitrack stems, or guarantee source separation**. Fixed coefficients, smoothly interpolated gains (55ms), no allocations, per-sample transcendentals, extra convolution or stereo Haas delay. +- Existing voicing 0–3 remain identical; the original P9.7 Venue PCM on 0..100% Early should stay byte-exact at 44.1/48k. Changed Git blob hashes are explicitly pinned as an intentional new audition milestone. Other P9.7/P9.8 code paths unchanged. +- `IMRS v6/v7` old settings migrate far source distances down to physical <=4m on restore; invalid modes/voicings are still rejected atomically. `.smix` FX catalog identity unchanged. +- Verify headphone listening at **matched level**, center-vocal clarity vs cymbal presence, stereo side retention, mono fold-down, sibilance, and guard action with mastered songs before release. This is an experimental candidate, not an approved listening checkpoint. + +## ImmerSIB 8D-concert vocal anti-thinness correction — 16 Nov 2026 (candidate) + +**Owner feedback:** the prior P9.8 ImmerSIB Detail/Impact PCM built successfully but made a Dua Lipa live-concert lead voice **thin, nasal/shrill and recessed**. Passing RMS energy / distinct scene-hash gates was not evidence that a voice would be musically pleasant. This is a *new tonal correction candidate*, not an approved checkpoint. + +- **Root-cause evidence from source:** `SonKuP97StageImpact` source/direct/final already reinforce 1.9kHz and high-frequency energy; old `SonKuP98SceneVoicing` profile 4 adds center 2.05kHz and EAR 2.05kHz, >5.2kHz SIDE/early/final boost. Those effects can compound while leaving 150–500Hz chest/body relatively weak. Any recorded stereo program has center-panned instrumental content too, so center source bands are **not** source-separated lead vocals. +- **Correction in existing P9.8 scene block only** (profiles 4 and 5): pre-HRTF broad 285Hz center-body reinforcement through the *same* two KEMAR world speakers; reduce the stacked 2.05kHz center/ear emphasis; add gentle broad 3.45kHz SIDE masking relief; limit high-air enhancement previously added on SIDE/early/final; modest per-ear 3.45kHz de-harsh after P9.5 makeup and before existing linked peak guard. Both 44.1 and 48k coefficients are calculated in `prepare()`. One stereo path, fixed filter memory, 55ms smoothly transitioned gains, no allocation or extra latency in the audio callback. +- Preserve P9.7 original **10m/106°/100%/100% Venue PCM** and P9.8 profile IDs 0–3 *exactly*. No public UI or native SONK v12/IMRS v7 data-format change; actual accepted factory IDs 4/5 and 1–4m source limit remain unchanged. No copied instrument stems, phasey stereo delay, static 6dB peak boost or compressed master. +- A new tone gate tests center 285Hz body vs center 2.05kHz, SIDE 2.05/3.45kHz reduction vs >7kHz preservation, mono symmetry and finite output, in addition to the physical 44.1/48k room PCM and frozen Venue hash. **This test cannot simulate a mastered Dua Lipa live recording or prove that vocals are perceptually separated**, so release requires user matched-loudness headphone A/B and checking sibilance/fatigue. +- Source provenance old Git blob `cc769dade5a752e0f84f02348e07332bce7c268b` -> new `90bab191a62601021c4a7a77d64e0e4d408d3011` recorded in `config/spatial_audio_authority.json`. + +### Tonal acceptance replaces misleading total-power ranking + +The historical same-file music fixture is retained **unchanged** for exact frozen Venue 44.1/48k PCM hash verification. It contains 86/117Hz bass and 2210/7400Hz center but **no 285Hz center-vocal chest/body content**. Consequently its earlier broad 85% Venue-power gate disproportionately rewarded treble-rich P9.8 voicings; reducing shrillness made the new voicing fail even when its 285Hz response improved. Do not chase a master-gain increase to satisfy that old artificial metric. + +The new independent whole-PCM native tone transfer gate processes isolated MID 285Hz, SIDE 3450Hz and SIDE 7400Hz through the entire physical six-wall/HRTF/P97/P98/linked-peak output at the **same scene geometry, room and gain**, changing only profile ID 4/5 vs reference ID 0. It asserts warmth grows, harsh side masking does not rise, and high-frequency stereo is not erased. Existing strong fixed-PCM Venue hashes, anti-phase, finite peak, room scene diversity and meaningful electric-power safety floor are still checked. The looser **70% electrical power floor** is *not* claimed to equal perceptual loudness: the more specific native whole-PCM spectral test replaces the invalid assumption that more high-frequency electrical energy necessarily means better listening. diff --git a/engine/builtin_fx/ImerSipP92Editor.h b/engine/builtin_fx/ImerSipP92Editor.h new file mode 100644 index 000000000..e1c1baf8a --- /dev/null +++ b/engine/builtin_fx/ImerSipP92Editor.h @@ -0,0 +1,384 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +// Compact ImmerSIB concert scene + native JUCE control panel. +// Scene photography is image-backed; all control surfaces and icons are JUCE. +// Audio uses the existing SonKu PCM, host bypass, ACK, and IMRS state paths. +#include +#include +#include +#include +#include +#include +#include +#include "ImerSipP92VisualSkin.h" + +namespace armix::builtin_fx { + +class ImerSipP92Editor final : public juce::AudioProcessorEditor, + private juce::Timer { +public: + // Snapshot of actual host PCM control gates, never a GUI-local power flag. + // Slot preference is independent of the additive rack/global gates. + struct HostBypassState final { + bool valid=false; + bool slotBypassed=false; + bool rackBypassed=false; + bool globalBypassed=false; + bool effectiveBypassed() const noexcept { + return valid && (slotBypassed || rackBypassed || globalBypassed); + } + }; + explicit ImerSipP92Editor(ImerSipP92Processor& processor) + :juce::AudioProcessorEditor(processor),fx_(processor) { + // Compact 85% presentation of the audited 1100x680 master canvas. + // The host sees an actual 935x578 editor rather than an oversized FX. + setSize(935,578); + setResizable(false,false); + preset_.setComponentID("imersip.preset"); + preset_.addItem("Custom",1); + for(const auto& scene:imersipP92Presets) + preset_.addItem(juce::String(scene.label),scene.id); + preset_.setLookAndFeel(&skin_); + preset_.onChange=[this]{ + const int id=preset_.getSelectedId(); + if(!imersipP92PresetById(id))return; + visualSceneId_=id; // Art changes only; audio still uses native SonKu. + sync(imersipP92Factory(id)); + submit(); + }; + addAndMakeVisible(preset_); + room_.setComponentID("imersip.room"); + room_.addItem("ROOM OFF",1); + room_.addItem("STUDIO 7.2 M",2); + room_.addItem("CHAMBER 14.4 M",3); + room_.addItem("LARGE 28.8 M",4); + room_.setLookAndFeel(&skin_); + room_.onChange=[this]{ + preset_.setSelectedId(1,juce::dontSendNotification); + submit(); + }; + addAndMakeVisible(room_); + + const char* ids[]={"stage","distance","early","late", + "mix","gain","align","yaw"}; + const char* names[]={"STAGE WIDTH","DISTANCE","EARLY ROOM", + "LATE ROOM","SPATIAL MIX","MASTER GAIN", + "EAR ALIGN","HEAD YAW"}; + const double lower[]={30.,1.0,0.,0.,0.,-12.,-30.,-90.}; + #if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + const double upper[]={180.,4.,180.,100.,100.,6.,20.,90.}; +#else + const double upper[]={180.,7.4,100.,100.,100.,6.,20.,90.}; +#endif + const double step[]={1.,.1,1.,1.,1.,.1,1.,1.}; + for(int i=0;i<8;++i){ + auto& slider=knobs_[static_cast(i)]; + slider.setComponentID(juce::String("imersip.")+ids[i]); + slider.setSliderStyle(i==5? + juce::Slider::RotaryHorizontalVerticalDrag: + juce::Slider::LinearHorizontal); + slider.setTextBoxStyle(juce::Slider::NoTextBox,false,0,0); + slider.setRange(lower[i],upper[i],step[i]); + slider.setLookAndFeel(&skin_); + slider.onValueChange=[this]{ + preset_.setSelectedId(1,juce::dontSendNotification); + submit(); + repaint(); + }; + addAndMakeVisible(slider); + auto& label=labels_[static_cast(i)]; + label.setComponentID(juce::String("imersip.label.")+ids[i]); + label.setText(names[i],juce::dontSendNotification); + label.setJustificationType(juce::Justification::centredLeft); + label.setColour(juce::Label::textColourId,juce::Colour(0xffcbd7dc)); + label.setFont(juce::FontOptions(14.0f)); + addAndMakeVisible(label); + } + power_.setComponentID("imersip.power"); + power_.setButtonText({}); // Icon is drawn by the JUCE LookAndFeel. + power_.setClickingTogglesState(false); // Host readback is authoritative. + power_.setTooltip("FX state unavailable"); + power_.setLookAndFeel(&skin_); + power_.setEnabled(false); // no fake bypass authority + power_.onClick=[this] { + if(!requestBypass_ || !readHostPower_)return; + const auto before=readHostPower_(); + if(!before.valid || before.globalBypassed || + before.rackBypassed) { + status_=before.globalBypassed?"GLOBAL FX BYPASSED - USE MIXER POWER": + before.rackBypassed?"FX RACK BYPASSED - USE RACK POWER": + "FX INSTANCE NO LONGER ACTIVE"; + refreshHostPower(); + repaint(); + return; + } + const bool wanted=!before.slotBypassed; + const bool accepted=requestBypass_(wanted); + const auto after=readHostPower_(); + status_=!accepted?"HOST FX POWER REJECTED - REFRESH FX RACK": + !after.valid?"FX INSTANCE CHANGED - REOPEN EDITOR": + after.slotBypassed!=wanted?"HOST FX POWER NOT CONFIRMED": + wanted?"FX BYPASS ACCEPTED":"FX ENABLE ACCEPTED"; + refreshHostPower(); + repaint(); + }; + addAndMakeVisible(power_); + sync(fx_.acceptedSettings()); + startTimerHz(25); + } + ~ImerSipP92Editor() override { + stopTimer(); + for(auto& slider:knobs_)slider.setLookAndFeel(nullptr); + preset_.setLookAndFeel(nullptr); + room_.setLookAndFeel(nullptr); + power_.setLookAndFeel(nullptr); + } + bool areVisualAssetsReady() const noexcept {return skin_.ready();} + void bindHostPower(std::function request, + std::function readback) { + requestBypass_=std::move(request); + readHostPower_=std::move(readback); + refreshHostPower(); + } + // Called by mixer dispatch after accepted Rack/Global FX ACK on JUCE's + // message thread. Timer polling remains a fallback for external changes. + void synchronizeHostPower() { refreshHostPower(); } + static constexpr float compactScale=0.85f; + // Master canvas and all native hitboxes share exactly one conversion. + void paint(juce::Graphics& g) override { + g.fillAll(juce::Colour(0xff11181d)); + juce::Graphics::ScopedSaveState save(g); + g.addTransform(juce::AffineTransform::scale(compactScale)); + // One authentic photo venue per scene, never the abandoned + // holographic room or stacked artificial speaker sprites. + // Only approved concert photography; rejected procedural art is removed. + skin_.drawScene(g,visualSceneId_); + if(hostBypassed_.value_or(false)) + skin_.drawBypassedVenueOverlay(g); + + // No second header: the native plugin window already owns its title. + // Preserve the venue art's full 1100x461 scene viewport. + + // Flat JUCE-painted panel: no bitmap, bevels, screws, or partitions. + skin_.drawPanel(g); + g.setColour(juce::Colour(0xff33424b)); + g.fillRect(0,461,1100,1); + g.setColour(juce::Colour(0xffbacbd0)); + g.setFont(juce::FontOptions(13.8f)); + g.drawText("PRESET",24,485,208,19,juce::Justification::centredLeft); + g.drawText("ROOM",24,564,208,19,juce::Justification::centredLeft); + + // Seven precise native controls in two relaxed 308px lanes. + // One row owns one label, one drag rail, and one right-aligned + // readback. Avoid four 106px rails squeezed under long labels. + constexpr int ids[]={0,1,2,3,4,6,7}; + for(int j=0;j<7;++j){ + const int idx=ids[j],col=j%2,row=j/2; + const int x=252+317*col,y=485+43*row; + const double v=knobs_[static_cast(idx)].getValue(); + const juce::String value=idx==0?juce::String(v,0)+"°": + idx==1?juce::String(v,1)+" m": + idx==6||idx==7?juce::String(v,0)+"°": + juce::String(v,0)+"%"; + g.setColour(juce::Colour(0xffd6efea)); + g.setFont(juce::FontOptions(13.2f)); + g.drawText(value,x+254,y+3,49,22, + juce::Justification::centredRight); + } + const auto gain=knobs_[5].getValue(); + g.setColour(juce::Colour(0xfff0eafa)); + g.setFont(juce::FontOptions(16.f)); + g.drawText((gain>=0?"+":"")+juce::String(gain,1)+" dB", + 886,611,138,23,juce::Justification::centred); + g.setColour(juce::Colour(0xffb4c3c9)); + g.setFont(juce::FontOptions(12.2f)); + g.drawText("AUDIO / "+status_,24,648,838,23, + juce::Justification::centredLeft); + } + void paintOverChildren(juce::Graphics& g) override { + // Parent paint() cannot dim child Components: JUCE draws their + // labels, sliders and popup controls AFTER parent paint(). + // A distinct ~44% muted charcoal pass makes all inactive + // controls visibly recede, without losing label legibility. + // Exclude FX Power so the host-authoritative toggle remains + // crisp, keyboard/mouse accessible and visually actionable. + if(!hostBypassed_.value_or(false))return; + juce::Graphics::ScopedSaveState saved(g); + const auto panelTop=juce::roundToInt(461.f*compactScale); + const auto panel=juce::Rectangle( + 0,panelTop,getWidth(),getHeight()-panelTop); + g.reduceClipRegion(panel); + g.excludeClipRegion(power_.getBounds()); + g.setColour(juce::Colour(0x7603060a)); // 46% muted neutral charcoal + g.fillRect(panel); + } + void resized() override { + const auto place=[](juce::Component& child,int x,int y,int w,int h){ + child.setBounds(juce::roundToInt(x*compactScale), + juce::roundToInt(y*compactScale), + juce::roundToInt(w*compactScale), + juce::roundToInt(h*compactScale)); + }; + place(preset_,24,507,206,36); + place(room_,24,586,206,36); + constexpr int ids[]={0,1,2,3,4,6,7}; + for(int j=0;j<7;++j){ + const int col=j%2,row=j/2; + const int x=252+317*col,y=485+43*row; + auto& slider=knobs_[static_cast(ids[j])]; + auto& label=labels_[static_cast(ids[j])]; + place(label,x,y,132,24); + place(slider,x+134,y,114,25); + } + // Control order: two slider lanes -> master gain -> host FX Power. + // Right-side power cell is independent of the master rotary hitbox. + place(labels_[5],884,484,139,22); + place(knobs_[5],908,510,98,94); + place(power_,1032,483,44,44); + } +private: + armix::sonku::Settings readControls() const { + auto s=fx_.acceptedSettings(); + s.renderMode=9;s.moving=false;s.startAzimuthDegrees=0.f; +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + s.sceneVoicing=selectedVoicing_; +#endif + s.musicCompatibleLowFrequency=false; + s.spacePreset=std::clamp(room_.getSelectedId()-1,0,3); + s.stereoSpreadDegrees=static_cast(knobs_[0].getValue()); + s.sourceDistanceMeters=std::min( + static_cast(knobs_[1].getValue()), + imersipP92MaxDistance(s.spacePreset)); + s.roomAmount=static_cast(knobs_[2].getValue()*.01); + s.ambience=static_cast(knobs_[3].getValue()*.01); + s.spatialMix=static_cast(knobs_[4].getValue()*.01); + s.outputTrim=static_cast( + std::pow(10.,knobs_[5].getValue()/20.)); + s.hrtfElevationTrimDegrees= + static_cast(knobs_[6].getValue()); + s.headYawDegrees=static_cast(knobs_[7].getValue()); + return s; + } + void sync(const armix::sonku::Settings& s){ +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + selectedVoicing_=s.sceneVoicing; +#endif + room_.setSelectedId(s.spacePreset+1,juce::dontSendNotification); + const double vals[]={s.stereoSpreadDegrees,s.sourceDistanceMeters, + 100.*s.roomAmount,100.*s.ambience,100.*s.spatialMix, + 20.*std::log10(s.outputTrim),s.hrtfElevationTrimDegrees, + s.headYawDegrees}; + for(int i=0;i<8;++i)knobs_[static_cast(i)].setValue( + vals[i],juce::dontSendNotification); + int preset=1; + for(const auto& factory:imersipP92Presets){ + const int id=factory.id; + const auto candidate=imersipP92Factory(id); + if(s.spacePreset==candidate.spacePreset && + std::abs(s.stereoSpreadDegrees-candidate.stereoSpreadDegrees)<.01f && + std::abs(s.sourceDistanceMeters-candidate.sourceDistanceMeters)<.01f && + std::abs(s.roomAmount-candidate.roomAmount)<.001f && + std::abs(s.ambience-candidate.ambience)<.001f && + std::abs(s.spatialMix-candidate.spatialMix)<.001f && + std::abs(s.outputTrim-candidate.outputTrim)<.001f && +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + s.sceneVoicing==candidate.sceneVoicing && +#endif + std::abs(s.headYawDegrees)<.001f && + std::abs(s.hrtfElevationTrimDegrees)<.001f) {preset=id;break;} + } + if(preset!=1)visualSceneId_=preset; + // Adjusting a slider marks "Custom" but deliberately keeps the + // chosen venue image until the operator picks another scene. + preset_.setSelectedId(preset,juce::dontSendNotification); + repaint(); + } + void submit() { + const auto wanted=readControls(); + if(!validImerSipP92Scene(wanted)){ + status_="INVALID ROOM / SOURCE GEOMETRY";repaint();return; + } + if(pending_!=0){ + deferred_=wanted;hasDeferred_=true; + status_="LATEST EDIT QUEUED";repaint();return; + } + const auto id=fx_.nextEditorRequestId(); + if(!fx_.queueSettings(wanted,id)){ + deferred_=wanted;hasDeferred_=true; + status_="WAITING FOR AUDIO CALLBACK";repaint();return; + } + pending_=id; + status_="PENDING NATIVE AUDIO ACK"; + repaint(); + } + void refreshHostPower() { + // One effective state = individual slot OR rack gate OR global A/B. + // Never flatten these independent remembered bypass preferences. + const auto state=readHostPower_?readHostPower_():HostBypassState{}; + const bool valid=state.valid; + const bool bypassed=state.effectiveBypassed(); + const bool enabled=valid && static_cast(requestBypass_) && + !state.rackBypassed && !state.globalBypassed; + // An unbound/offline editor stays inert; avoid a full-scene repaint + // 25 times/second when no physical lease exists. + const bool changed=(valid!=hostBypassed_.has_value()) || + (valid && *hostBypassed_!=bypassed); + if(valid)hostBypassed_=bypassed; + else hostBypassed_.reset(); + power_.setEnabled(enabled); + power_.setToggleState(valid && !bypassed,juce::dontSendNotification); + power_.setTooltip(!valid?"FX instance unavailable - reopen from rack": + state.globalBypassed?"GLOBAL FX BYPASSED - enable mixer FX": + state.rackBypassed?"FX RACK BYPASSED - enable rack power": + state.slotBypassed?"FX BYPASSED - click to enable": + "FX ON - click to bypass"); + // Host changes can arrive from another window while this editor is + // open. 25 Hz control-thread polling updates visual status on change. + if(changed)repaint(); + } + void timerCallback() override { + SonKuSpatialProcessor::Completion done{}; + while(fx_.pollCompletion(done)){} + if(pending_!=0 && fx_.lastCompletedRequestId()==pending_){ + const bool ok=fx_.lastCompletionApplied(); + pending_=0; + status_=ok?"APPLIED TO P9 PCM":"REJECTED BY P9 PCM"; + if(!ok || !hasDeferred_)sync(fx_.acceptedSettings()); + } + if(pending_==0 && hasDeferred_){ + const auto next=deferred_; + hasDeferred_=false; + if(validImerSipP92Scene(next)){ + const auto id=fx_.nextEditorRequestId(); + if(fx_.queueSettings(next,id)){ + pending_=id;status_="APPLYING LATEST EDIT"; + }else{ + deferred_=next;hasDeferred_=true; + } + } + } + refreshHostPower(); + repaint(juce::Rectangle(0,juce::roundToInt(646*compactScale), + getWidth(),juce::roundToInt(34*compactScale))); + } + int visualSceneId_=2; // UI-only scene selection; not IMRS / PCM state. + int selectedVoicing_=0; // UI/control side; native SPSC owns the audio state. + ImerSipP92Processor& fx_; + ImerSipP92VisualSkin skin_; + juce::ComboBox preset_{},room_{}; + juce::TextButton power_{}; + std::array knobs_{}; + std::array labels_{}; + std::function requestBypass_; + std::function readHostPower_; + std::optional hostBypassed_{}; // UI cache of actual host readback only + + armix::sonku::Settings deferred_{}; + std::uint64_t pending_=0; + bool hasDeferred_=false; + juce::String status_="P9.2 CONCERT ENGINE READY"; +}; +inline juce::AudioProcessorEditor* ImerSipP92Processor::createEditor() { + return new ImerSipP92Editor(*this); +} +} // namespace armix::builtin_fx diff --git a/engine/builtin_fx/ImerSipP92Processor.h b/engine/builtin_fx/ImerSipP92Processor.h new file mode 100644 index 000000000..7aa4d895d --- /dev/null +++ b/engine/builtin_fx/ImerSipP92Processor.h @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "ImerSipP92Scene.h" +#include "SonKuSpatialProcessor.h" +#include +#include +#include +#include + +// ImerSip identity/state/UI are independent. Audio uses the SAME +// SonKuSpatialProcessor -> SonKuSpatialCore (mode 9) and same audio ACK. +// No P8 ImerSipDsp, second HRTF, stereo widening or enhancer is instantiated. +namespace armix::builtin_fx { +class ImerSipP92Processor final : public SonKuSpatialProcessor { +public: + // Public name may change; persisted .smix FX ID must not. + static constexpr const char* catalogIdentity="armix.builtin.imersip.v1"; + static constexpr const char* productDisplayName="ImmerSIB"; + ImerSipP92Processor() + : SonKuSpatialProcessor(imersipP92Factory(2)) {} + const juce::String getName() const override {return productDisplayName;} + bool hasEditor() const override {return true;} + juce::AudioProcessorEditor* createEditor() override; + + // Editor gesture serials survive closing/reopening this processor's UI. + std::uint64_t nextEditorRequestId() noexcept { + if(++issued_==0)++issued_; + return issued_; + } + bool queueSettings(const armix::sonku::Settings& scene, + std::uint64_t requestId) noexcept { + if(!validImerSipP92Scene(scene) || requestId==0)return false; + if(requestId>issued_)issued_=requestId; + return SonKuSpatialProcessor::queueSettings(scene,requestId); + } + bool pollCompletion(SonKuSpatialProcessor::Completion& completed) noexcept { + if(!SonKuSpatialProcessor::pollCompletion(completed))return false; + lastCompletedRequest_=completed.requestId; + lastCompletionApplied_=completed.applied; + return true; + } + std::uint64_t lastCompletedRequestId() const noexcept { + return lastCompletedRequest_; + } + bool lastCompletionApplied() const noexcept { + return lastCompletionApplied_; + } + + void getStateInformation(juce::MemoryBlock& destination) override { + // Persist the new IMRS v6 identity, but embed the AUTHORITATIVE + // native SONK v11 settings verbatim, so no shadow state is invented. + // Session capture must use accepted audio settings, not UI drafts. + SonKuSpatialProcessor::Completion done{}; + while(pollCompletion(done)){} + juce::MemoryBlock native; + SonKuSpatialProcessor::getStateInformation(native); + juce::MemoryOutputStream out(destination,false); + out.writeInt(0x494D5253); // IMRS +#if defined(ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING) && ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING + out.writeInt(7); // IMRS v7: SONK v12 + typed scene, 75 bytes +#else + out.writeInt(6); // IMRS v6: SONK v11, 71 bytes +#endif + out.write(native.getData(),native.getSize()); + } + + bool restoreUnpublishedState(const void* data,int bytes) { + if(!data || bytes<8)return false; + juce::MemoryInputStream in(data,static_cast(bytes),false); + if(in.readInt()!=0x494D5253)return false; + const int version=in.readInt(); + if(version==6 +#if defined(ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING) && ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING + || version==7 +#endif + ) { + // Accept historical 71-byte IMRS v6/SONK v11 (voicing=0) + // and new 75-byte IMRS v7/SONK v12 atomically. + const int nativeBytes=version==7?67:63; + if(bytes!=nativeBytes+8)return false; + const auto* raw=static_cast(data)+8; + juce::MemoryInputStream check(raw,static_cast(nativeBytes),false); + if(check.readInt()!=0x534F4E4B || + check.readInt()!=(version==7?12:11))return false; + // Preflight the exact SONK v11 wire schema in a local POD. + // Parent restoration may change its accepted scene/core; doing + // that before validating ImerSip would let an invalid v6 + // session silently replace approved world-speaker P9 mode 9. + auto next=imersipP92ReferenceScene(); + next.startAzimuthDegrees=check.readFloat(); + next.revolutionSeconds=check.readFloat(); + next.stereoSpreadDegrees=check.readFloat(); + next.spatialMix=check.readFloat(); + next.outputTrim=check.readFloat(); + const int moving=check.readByte(); + const int clockwise=check.readByte(); + next.moving=moving!=0; + next.clockwise=clockwise!=0; + next.spacePreset=check.readInt(); + next.sourceDistanceMeters=check.readFloat(); + next.roomAmount=check.readFloat(); + next.ambience=check.readFloat(); + next.directElevationDegrees=check.readFloat(); + next.renderMode=check.readInt(); + const int incompatibleLf=check.readByte(); + next.musicCompatibleLowFrequency=incompatibleLf!=0; + next.headYawDegrees=check.readFloat(); + next.hrtfElevationTrimDegrees=check.readFloat(); +#if defined(ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING) && ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING + if(version==7)next.sceneVoicing=check.readInt(); +#endif + if(!check.isExhausted() || (moving!=0&&moving!=1) || + (clockwise!=0&&clockwise!=1) || + (incompatibleLf!=0&&incompatibleLf!=1) || + !armix::sonku::valid(next) || next.renderMode!=9 || + next.moving || next.musicCompatibleLowFrequency || + next.startAzimuthDegrees!=0.f)return false; + // Existing IMRS v6/v7 sessions may contain far 10m scenes. + // Migrate distance only; preserve accepted voicing/room/gain. + // Keep legacy binary wire length and ID unchanged. + next.sourceDistanceMeters=std::min( + next.sourceDistanceMeters,imersipP92MaxDistance(next.spacePreset)); + return validImerSipP92Scene(next) && adoptUnpublishedScene(next); + } + // Original IMRS v1-v5: read the actual previous format, fail closed + // on corrupt bytes and map only parameters with a real P9 counterpart. + if(version<1||version>5 || + bytes!=(version==1?32:version==2?36: + version==3?44:version==4?48:52))return false; + const int venue=in.readInt(); + const float immersion=in.readFloat(); + const float space=in.readFloat(); + const float width=in.readFloat(); + const float bassImpact=in.readFloat(); + const float trim=in.readFloat(); + const float detail=version>=2?in.readFloat():0.f; + const float stereoKeep=version>=3?in.readFloat():1.f; + const float late=version>=3?in.readFloat():.33f; + const float depth=version>=4?in.readFloat():0.f; + const float earAlign=version>=5?in.readFloat():0.f; + const auto unit=[](float x){return std::isfinite(x)&&x>=0.f&&x<=1.f;}; + if(!in.isExhausted() || venue<0 || venue>2 || + !unit(immersion)||!unit(space)||!unit(width)|| + !unit(bassImpact)||!unit(detail)||!unit(stereoKeep)|| + !unit(late)||!unit(depth)||!std::isfinite(trim)|| + trim<.25f||trim>1.5f||!std::isfinite(earAlign)|| + earAlign< -30.f||earAlign>20.f)return false; + auto next=imersipP92ReferenceScene(); + next.spacePreset=venue==0?3:venue==1?2:1; + next.spatialMix=immersion; + next.roomAmount=space; + next.stereoSpreadDegrees=30.f+150.f*width; + next.ambience=late; + next.sourceDistanceMeters=std::min(1.6f+5.8f*depth, + imersipP92MaxDistance(next.spacePreset)); + next.outputTrim=trim; + next.hrtfElevationTrimDegrees=earAlign; + // Bass Impact, AIR, Stereo Keep were P8-only enhancer axes. + // Deliberately DO NOT recreate P8 dry SIDE/headphone bass, which + // would destroy the owner-approved external P9 scene. + return validImerSipP92Scene(next) && adoptUnpublishedScene(next); + } + // JUCE's public AudioProcessor restore entrypoint is virtual. Without + // this override it would call the inherited SONK parser, silently + // rejecting an IMRS show even though the native FX registry restores it. + void setStateInformation(const void* data,int bytes) override { + (void)restoreUnpublishedState(data,bytes); + } +protected: + bool admitQueuedScene( + const armix::sonku::Settings& next) const noexcept override { + return validImerSipP92Scene(next); + } +private: + std::uint64_t issued_=0,lastCompletedRequest_=0; + bool lastCompletionApplied_=false; +}; +} // namespace armix::builtin_fx +#include "ImerSipP92Editor.h" diff --git a/engine/builtin_fx/ImerSipP92Scene.h b/engine/builtin_fx/ImerSipP92Scene.h new file mode 100644 index 000000000..a0eb44402 --- /dev/null +++ b/engine/builtin_fx/ImerSipP92Scene.h @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "sonku/SonKuSpatialCore.h" +#include +#include +#include + +// Thin ImerSip *product* scene, NOT another binaural DSP. Every PCM sample +// is rendered by the same owner-approved SonKu P9.1/P9.2 core (mode 9). +namespace armix::builtin_fx { +inline armix::sonku::Settings imersipP92ReferenceScene() noexcept { + armix::sonku::Settings s{}; + s.renderMode=9; // P9.1/P9.2 ONE native PCM authority + s.musicCompatibleLowFrequency=false; + s.moving=false; s.clockwise=true; + s.startAzimuthDegrees=0.f; // static world-front speakers + s.headYawDegrees=0.f; + s.directElevationDegrees=0.f; + s.hrtfElevationTrimDegrees=0.f; + s.stereoSpreadDegrees=82.f; + s.sourceDistanceMeters=1.6f; + s.spacePreset=3; // Large 28.8 m, P9 listening reference + s.roomAmount=.78f; // P9 direct/wall architecture untouched + s.ambience=.33f; + s.spatialMix=1.f; + s.outputTrim=1.f; // 0 dB, no P8 ImerSip shelf/limiter + return s; +} +inline float imersipP92MaxDistance(int room) noexcept { + // Six-wall geometry requires 2*(distance+.5)<=room width. +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + return room==1?3.05f:4.f; // user-facing nearfield 1..4m +#else + return room==1?3.05f:room==2?6.65f:7.4f; +#endif +} +inline bool validImerSipP92Scene(const armix::sonku::Settings& s) noexcept { + return armix::sonku::valid(s) && s.renderMode==9 && + !s.moving && !s.musicCompatibleLowFrequency && + s.startAzimuthDegrees==0.f && + s.sourceDistanceMeters<=imersipP92MaxDistance(s.spacePreset); +} +// A single typed preset catalog drives the native UI, state recognition and +// actual SonKu P9 PCM. IDs are UI-only (IMRS persists real accepted settings), +// so removing Neutral from the picker does NOT invalidate old saved sessions. +// Keep Live Concert unchanged: the owner has auditioned and liked it. +// Don't mistake a wide stage/distant source for a guarantee of envelopment. +struct ImerSipP92Preset { + int id; + const char* label; + int spacePreset; + float stageDegrees, distanceMeters; + float earlyAmount, lateAmount, outputDb; + int voicing=0; // P9.8 typed profile; 0 preserves P9.7 Venue PCM +}; +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH +// Archival P9.7 10m Venue remains a golden *private* PCM fixture, not a +// public preset. Current owner explicitly rejects sources beyond 4m. +inline armix::sonku::Settings imersipP97VenueGoldenScene() noexcept { + auto s=imersipP92ReferenceScene(); + s.stereoSpreadDegrees=106.f;s.sourceDistanceMeters=10.f; + s.roomAmount=1.f;s.ambience=1.f;s.outputTrim=1.8f; + return s; +} +// Nearfield factory retains the same P9 world renderer, adds P9.8 +// vocal masking relief, not stem extraction or extra Haas delays. +inline constexpr std::array imersipP92Presets{{ + {2,"Live Concert", 3,112.f,3.0f,1.36f,.84f,5.10545f,4}, + {3,"Royal Concert Hall", 3,106.f,3.2f,1.55f,.78f,5.57507f,4}, + {4,"Arena Thunder", 3,124.f,3.7f,1.45f,.86f,5.45f,5}, + {5,"Front Row Power", 3,104.f,1.4f,1.26f,.70f,5.60f,4}, + {6,"Symphonic Palace", 3,118.f,2.7f,1.60f,.80f,5.25f,4}, + {7,"Velvet Cinema", 3,108.f,2.8f,1.42f,.82f,4.60898f,3} +}}; +#else +// Historical P9.2 candidate stays reproducible when private P9.8 OFF. +inline constexpr std::array imersipP92Presets{{ + {2,"Live Concert", 3,150.f,2.2f,1.f,.91f,4.8f}, + {3,"Royal Concert Hall", 3,155.f,1.8f,1.f,.98f,5.4f}, + {4,"Arena Thunder", 3,164.f,1.7f,1.f,1.00f,5.7f}, + {5,"Front Row Power", 3,150.f,1.6f,1.f,.97f,5.2f}, + {6,"Symphonic Palace", 3,146.f,1.9f,1.f,.99f,5.4f}, + {7,"Velvet Cinema", 2,155.f,1.6f,1.f,1.00f,5.7f} +}}; +#endif +inline const ImerSipP92Preset* imersipP92PresetById(int id) noexcept { + for(const auto& p:imersipP92Presets)if(id==p.id)return &p; + return nullptr; +} +inline float imersipP92DbToLinear(float db) noexcept { + return std::pow(10.f,db/20.f); // editor/control thread, never PCM callback +} +inline armix::sonku::Settings imersipP92Factory(int id) noexcept { + auto s=imersipP92ReferenceScene(); // internal neutral test, not UI entry + if(const auto* p=imersipP92PresetById(id)) { + s.spacePreset=p->spacePreset; + s.stereoSpreadDegrees=p->stageDegrees; + s.sourceDistanceMeters=p->distanceMeters; + s.roomAmount=p->earlyAmount; + s.ambience=p->lateAmount; + s.outputTrim=imersipP92DbToLinear(p->outputDb); +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + s.sceneVoicing=p->voicing; + // Do not let dB conversion alter the exact approved Venue trim hash. + if(id==2)s.outputTrim=1.8f; // preserve level, move to listener nearfield +#endif + } + return s; +} +} // namespace armix::builtin_fx diff --git a/engine/builtin_fx/ImerSipP92VisualSkin.h b/engine/builtin_fx/ImerSipP92VisualSkin.h new file mode 100644 index 000000000..108bb4fdb --- /dev/null +++ b/engine/builtin_fx/ImerSipP92VisualSkin.h @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +// Only six approved concert venue photographs; all controls rendered by JUCE. +// The rejected speaker/button/knob PNG kit must never return. +#include +#include +#include +#include + +namespace armix::builtin_fx { + +class ImerSipP92VisualSkin final : public juce::LookAndFeel_V4 { +public: + // Fixed pixel master matches the 1100x461 logical stage exactly (2x). + static constexpr int photoWidth=2200; + static constexpr int photoHeight=922; + ImerSipP92VisualSkin() + : sceneLive_(load(BinaryData::scene_live_concert_png,BinaryData::scene_live_concert_pngSize)), + sceneRoyal_(load(BinaryData::scene_royal_concert_hall_png,BinaryData::scene_royal_concert_hall_pngSize)), + sceneArena_(load(BinaryData::scene_arena_thunder_png,BinaryData::scene_arena_thunder_pngSize)), + sceneFront_(load(BinaryData::scene_front_row_power_png,BinaryData::scene_front_row_power_pngSize)), + sceneSymphony_(load(BinaryData::scene_symphonic_palace_png,BinaryData::scene_symphonic_palace_pngSize)), + sceneCinema_(load(BinaryData::scene_velvet_cinema_png,BinaryData::scene_velvet_cinema_pngSize)) { + setColour(juce::ComboBox::textColourId,juce::Colour(0xffdce8e9)); + setColour(juce::ComboBox::outlineColourId,juce::Colours::transparentBlack); + setColour(juce::ComboBox::arrowColourId,juce::Colour(0xff55dad0)); + setColour(juce::PopupMenu::backgroundColourId,juce::Colour(0xff17242a)); + setColour(juce::PopupMenu::textColourId,juce::Colour(0xffe0edee)); + setColour(juce::PopupMenu::highlightedBackgroundColourId,juce::Colour(0xff225d65)); + setColour(juce::TextButton::textColourOffId,juce::Colour(0xffeef3f3)); + setColour(juce::TextButton::textColourOnId,juce::Colour(0xffefffff)); + } + bool ready() const noexcept { + return allValid({&sceneLive_,&sceneRoyal_,&sceneArena_, + &sceneFront_,&sceneSymphony_,&sceneCinema_}); + } + bool hasScenes() const noexcept { return ready(); } + void drawScene(juce::Graphics& g,int presetId) const { + const juce::Image* art=&sceneLive_; + switch(presetId){ + case 3: art=&sceneRoyal_; break; + case 4: art=&sceneArena_; break; + case 5: art=&sceneFront_; break; + case 6: art=&sceneSymphony_; break; + case 7: art=&sceneCinema_; break; + default: break; // Custom keeps its last selected venue. + } + // Fail closed on an absent/mismatched scene rather than allowing + // centered 2:1 art to create black matte on either side. + if(art->isNull() || art->getWidth()!=photoWidth || + art->getHeight()!=photoHeight) { + jassertfalse; + return; + } + // The approved 2x PNG has the exact logical viewport ratio. + // Centred placement now fills edge-to-edge, without distortion. + juce::Graphics::ScopedSaveState state(g); + g.setImageResamplingQuality(juce::Graphics::highResamplingQuality); + g.reduceClipRegion(0,0,1100,461); + g.setColour(juce::Colour(0xff0e161c)); + g.fillRect(0,0,1100,461); + g.drawImageWithin(*art,0,0,1100,461, + juce::RectanglePlacement::centred); + } + void drawBypassedVenueOverlay(juce::Graphics& g) const { + // A strong but restrained mute treatment: the six approved concert + // photos remain visible, but stage lights and colours recede into + // charcoal. No new PNGs, image processing, bloom or animation. + g.setColour(juce::Colour(0xb803060a)); // ~72% near-black charcoal veil + g.fillRect(0,0,1100,461); + + // One dominant, unmistakable state label. This deliberately has + // more hierarchy than the original tiny 40px regular typography. + // Keep the entire word inside the scene safe area on every DPI. + const auto label=juce::Rectangle(110,153,880,150); + auto font=juce::Font(juce::FontOptions(76.f,juce::Font::bold)); + font.setExtraKerningFactor(0.055f); + g.setFont(font); + g.setColour(juce::Colour(0xb8000307)); + g.drawText("BYPASSED",label.translated(0,4), + juce::Justification::centred,false); + g.setColour(juce::Colour(0xeeffa53c)); // vivid translucent amber + g.drawText("BYPASSED",label,juce::Justification::centred,false); + } + void drawPanel(juce::Graphics& g) const { + // Premium restraint: one exact flat matte charcoal surface, + // no image texture, gloss, neon edges, bolts, segment borders, + // or geometric noise. DPI-independent and low-cost to render. + g.setColour(juce::Colour(0xff151a20)); + g.fillRect(0,461,1100,219); + } + void drawLinearSlider(juce::Graphics& g,int x,int y,int width,int height, + float sliderPos,float minSliderPos,float maxSliderPos, + const juce::Slider::SliderStyle style, + juce::Slider& slider) override { + if(style!=juce::Slider::LinearHorizontal){ + juce::LookAndFeel_V4::drawLinearSlider(g,x,y,width,height, + sliderPos,minSliderPos,maxSliderPos,style,slider); + return; + } + const float left=float(x+6),right=float(x+width-6); + const float cy=float(y)+float(height)*.5f; + const float thumb=std::clamp(sliderPos,left,right); + // Precise native vector rails avoid scaled PNG artefacts on HiDPI. + g.setColour(juce::Colour(0xff394a54)); + g.fillRoundedRectangle(left,cy-2.f,right-left,4.f,2.f); + if(thumb>left){ + g.setColour(juce::Colour(0xff4ac5bd)); + g.fillRoundedRectangle(left,cy-2.f,thumb-left,4.f,2.f); + } + g.setColour(juce::Colour(0xff0b2229)); + g.fillEllipse(thumb-7.5f,cy-7.5f,15.f,15.f); + g.setColour(juce::Colour(0xff86dbd4)); + g.drawEllipse(thumb-7.f,cy-7.f,14.f,14.f,1.5f); + g.setColour(juce::Colour(0xff9ddfd8)); + g.fillEllipse(thumb-2.f,cy-2.f,4.f,4.f); + } + void drawRotarySlider(juce::Graphics& g,int x,int y,int width,int height, + float proportion,float start,float end, + juce::Slider&) override { + // Native JUCE satin-metal control. No rejected knob PNG. + const float size=std::max(8.f,std::min(float(width),float(height))-5.f); + const float cx=float(x)+float(width)*.5f; + const float cy=float(y)+float(height)*.5f; + const float radius=size*.405f; + g.setColour(juce::Colour(0x5500050b)); + g.fillEllipse(cx-radius-2.f,cy-radius+2.f,2.f*radius+4.f,2.f*radius+4.f); + g.setColour(juce::Colour(0xff536775)); + g.fillEllipse(cx-radius,cy-radius,2.f*radius,2.f*radius); + g.setColour(juce::Colour(0xff0e181f)); + g.fillEllipse(cx-radius+2.f,cy-radius+2.f,2.f*radius-4.f,2.f*radius-4.f); + const float inner=radius*.76f; + g.setGradientFill(juce::ColourGradient( + juce::Colour(0xff344550),cx,cy-inner, + juce::Colour(0xff152129),cx,cy+inner,false)); + g.fillEllipse(cx-inner,cy-inner,2.f*inner,2.f*inner); + const float angle=start+std::clamp(proportion,0.f,1.f)*(end-start); + juce::Path arc; + arc.addCentredArc(cx,cy,radius+7.f,radius+7.f,0.f,start,angle,true); + g.setColour(juce::Colour(0xffbc8de4)); + g.strokePath(arc,juce::PathStrokeType(2.f)); + const float pointer=radius*.59f; + g.setColour(juce::Colour(0xfff0f7f8)); + g.drawLine(cx+std::sin(angle)*pointer*.49f, + cy-std::cos(angle)*pointer*.49f, + cx+std::sin(angle)*pointer, + cy-std::cos(angle)*pointer,2.4f); + } + void drawComboBox(juce::Graphics& g,int width,int height,bool, + int,int,int,int,juce::ComboBox&) override { + const auto bounds=juce::Rectangle(.5f,.5f, + float(width)-1.f,float(height)-1.f); + g.setColour(juce::Colour(0xff1c2c33)); + g.fillRoundedRectangle(bounds,5.f); + g.setColour(juce::Colour(0xff405c64)); + g.drawRoundedRectangle(bounds,5.f,1.f); + juce::Path arrow; + const float cx=float(width)-16.f,cy=float(height)*.52f; + arrow.startNewSubPath(cx-4.f,cy-2.f); + arrow.lineTo(cx,cy+2.f); + arrow.lineTo(cx+4.f,cy-2.f); + g.setColour(juce::Colour(0xff73c5c1)); + g.strokePath(arrow,juce::PathStrokeType(1.4f)); + } + void drawButtonBackground(juce::Graphics& g,juce::Button& button, + const juce::Colour&,bool hover,bool down) override { + if(button.getComponentID()=="imersip.power") { + // Same simple IEC power-ring language as built-in Compressor/EQ. + // Body and glyph are native JUCE; no image, font glyph, LED, + // faux switch, label, or GUI-side invented bypass state. + const auto bounds=juce::Rectangle(.5f,.5f, + float(button.getWidth()-1),float(button.getHeight()-1)); + const bool enabled=button.isEnabled(); + const bool on=enabled && button.getToggleState(); + const auto colour=!enabled?juce::Colour(0xff6b7981): + on?juce::Colour(0xff73d9d0):juce::Colour(0xffa6b6bd); + g.setColour(down?juce::Colour(0xff263941): + hover&&enabled?juce::Colour(0xff21323a): + juce::Colour(0xff1c262d)); + g.fillRoundedRectangle(bounds,6.f); + g.setColour(juce::Colour(hover&&enabled?0xff4c6870:0xff34464e)); + g.drawRoundedRectangle(bounds,6.f,1.f); + const float cx=float(button.getWidth())*.5f; + const float cy=float(button.getHeight())*.52f; + const float radius=std::min(float(button.getWidth()), + float(button.getHeight()))*.244f; + juce::Path powerRing; + powerRing.addCentredArc(cx,cy,radius,radius,0.f, + .63f,juce::MathConstants::twoPi-.63f,true); + g.setColour(colour); + g.strokePath(powerRing,juce::PathStrokeType( + 2.5f,juce::PathStrokeType::curved, + juce::PathStrokeType::rounded)); + g.drawLine(cx,cy-radius-3.f,cx,cy-1.f,2.5f); + return; + } + const auto r=juce::Rectangle(.5f,.5f, + float(button.getWidth()-1),float(button.getHeight()-1)); + const auto background=!button.isEnabled()?juce::Colour(0xff18252b): + down?juce::Colour(0xff28505a): + hover?juce::Colour(0xff29404b):juce::Colour(0xff203039); + g.setColour(background); + g.fillRoundedRectangle(r,5.f); + g.setColour(button.isEnabled() + ?juce::Colour(hover?0xff6fa6aa:0xff455963) + :juce::Colour(0xff34454b)); + g.drawRoundedRectangle(r,5.f,1.f); + } +private: + static bool allValid(std::initializer_list images) noexcept { + for(const auto* image:images) + if(image->isNull() || image->getWidth()!=photoWidth || + image->getHeight()!=photoHeight) return false; + return true; + } + static juce::Image load(const void* bytes,int size) { + return juce::ImageCache::getFromMemory(bytes,size); + } + const juce::Image sceneLive_,sceneRoyal_,sceneArena_, + sceneFront_,sceneSymphony_,sceneCinema_; +}; +} // namespace armix::builtin_fx diff --git a/engine/builtin_fx/SonKuSpatialProcessor.h b/engine/builtin_fx/SonKuSpatialProcessor.h index 6ed46528f..5902dbcab 100644 --- a/engine/builtin_fx/SonKuSpatialProcessor.h +++ b/engine/builtin_fx/SonKuSpatialProcessor.h @@ -10,15 +10,13 @@ // Built-in insert only; JUCE VST3 packaging is a separate adapter/quality gate. // Existing FX instance owns bypass, MIDI scratch, ChannelId, PDC and retirement. namespace armix::builtin_fx { -class SonKuSpatialProcessor final : public juce::AudioProcessor, +class SonKuSpatialProcessor : public juce::AudioProcessor, public armix::mixer::RealtimeNativeFxControl { public: static constexpr const char* catalogIdentity="armix.builtin.8d-sonku.v1"; struct Completion {std::uint64_t requestId=0;armix::sonku::Settings settings{};bool applied=false;}; SonKuSpatialProcessor() - : juce::AudioProcessor(BusesProperties() - .withInput("Input",juce::AudioChannelSet::stereo(),true) - .withOutput("Output",juce::AudioChannelSet::stereo(),true)) {} + : SonKuSpatialProcessor(armix::sonku::Settings{}) {} const juce::String getName() const override {return "8D-SonKu";} bool acceptsMidi() const override {return false;} bool producesMidi() const override {return false;} @@ -127,8 +125,9 @@ class SonKuSpatialProcessor final : public juce::AudioProcessor, // Control thread: returns QUEUED, not accepted/applied. Host native ACK // is permitted only after corresponding completion/readback. bool queueSettings(const armix::sonku::Settings& next,std::uint64_t requestId) noexcept { + // Branded derived FX must reject edits outside its P9 world scene. return ready_&&requestId&&armix::sonku::valid(next) - &&queue_.push(Edit{requestId,next}); + &&admitQueuedScene(next)&&queue_.push(Edit{requestId,next}); } bool pollCompletion(Completion& done) noexcept { if(!complete_.pop(done))return false; @@ -164,7 +163,11 @@ class SonKuSpatialProcessor final : public juce::AudioProcessor, #if defined(ARMIX_SONKU_EXPERIMENTAL_P88_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P88_NATIVE_RT #if defined(ARMIX_SONKU_EXPERIMENTAL_P89_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P89_NATIVE_RT #if defined(ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT +#if defined(ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING) && ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING + out.writeInt(12); // P9.8 append-only typed voicing, 67 bytes +#else out.writeInt(11); // unchanged 63-byte state; P9 mode 9 +#endif #else out.writeInt(10); // 63 bytes v9 layout, opt-in mode 8 #endif @@ -213,6 +216,9 @@ class SonKuSpatialProcessor final : public juce::AudioProcessor, #endif #if defined(ARMIX_SONKU_EXPERIMENTAL_P88_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P88_NATIVE_RT out.writeFloat(accepted_.hrtfElevationTrimDegrees); +#endif +#if defined(ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING) && ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING + out.writeInt(accepted_.sceneVoicing); #endif } bool restoreUnpublishedState(const void* data,int size) { @@ -220,7 +226,11 @@ class SonKuSpatialProcessor final : public juce::AudioProcessor, #if defined(ARMIX_SONKU_EXPERIMENTAL_NATIVE_XYZ_RT) && ARMIX_SONKU_EXPERIMENTAL_NATIVE_XYZ_RT #if defined(ARMIX_SONKU_EXPERIMENTAL_P83_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P83_NATIVE_RT #if defined(ARMIX_SONKU_EXPERIMENTAL_P88_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P88_NATIVE_RT +#if defined(ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING) && ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING + (size!=30&&size!=46&&size!=50&&size!=59&&size!=63&&size!=67)|| +#else (size!=30&&size!=46&&size!=50&&size!=59&&size!=63)|| +#endif #else (size!=30&&size!=46&&size!=50&&size!=59)|| #endif @@ -253,6 +263,9 @@ class SonKuSpatialProcessor final : public juce::AudioProcessor, &&version!=10 #if defined(ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT &&version!=11 +#if defined(ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING) && ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING + &&version!=12 +#endif #endif #endif #endif @@ -281,6 +294,9 @@ class SonKuSpatialProcessor final : public juce::AudioProcessor, ||(version==10&&size!=63) #if defined(ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT ||(version==11&&size!=63) +#if defined(ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING) && ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING + ||(version==12&&size!=67) +#endif #endif #endif #endif @@ -363,11 +379,13 @@ class SonKuSpatialProcessor final : public juce::AudioProcessor, next.renderMode!=7 && next.renderMode!=8)return false; if(version==10 && next.musicCompatibleLowFrequency)return false; #if defined(ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT - if(version==11 && next.renderMode!=0 && next.renderMode!=3 && + // Both v11 and append-only v12 forbid retired P8.3 modes. + // A v12 state with voicing=0 still cannot restore mode 1/2. + if(version>=11 && next.renderMode!=0 && next.renderMode!=3 && next.renderMode!=4 && next.renderMode!=5 && next.renderMode!=6 && next.renderMode!=7 && next.renderMode!=8 && next.renderMode!=9) return false; - if(version==11 && next.musicCompatibleLowFrequency)return false; + if(version>=11 && next.musicCompatibleLowFrequency)return false; #endif #endif #endif @@ -379,6 +397,10 @@ class SonKuSpatialProcessor final : public juce::AudioProcessor, #endif #if defined(ARMIX_SONKU_EXPERIMENTAL_P88_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P88_NATIVE_RT if(version>=9)next.hrtfElevationTrimDegrees=in.readFloat(); +#endif +#if defined(ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING) && ARMIX_SONKU_EXPERIMENTAL_P98_SCENE_VOICING + if(version>=12)next.sceneVoicing=in.readInt(); + // Old v11 sessions restore neutral (exact P9.7) until preset chosen. #endif // v1 OFF, v2 original scene; experimental v3 includes direct // elevation, and is rejected by ordinary public v2 builds. @@ -392,7 +414,35 @@ class SonKuSpatialProcessor final : public juce::AudioProcessor, void setStateInformation(const void* data,int size) override { (void)restoreUnpublishedState(data,size); } -private: +protected: + // Default SonKu accepts its full native settings schema; independent + // product inserts override this for their restricted world-P9 scenes. + virtual bool admitQueuedScene( + const armix::sonku::Settings&) const noexcept {return true;} + + // A product-branded insert may choose a prepared P9 owner-approved + // scene while sharing the exact SonKu DSP and the same SPSC/ACK path. + // Production SonKu's default constructor remains byte-for-byte as before. + explicit SonKuSpatialProcessor(const armix::sonku::Settings& initial) + : juce::AudioProcessor(BusesProperties() + .withInput("Input",juce::AudioChannelSet::stereo(),true) + .withOutput("Output",juce::AudioChannelSet::stereo(),true)), + accepted_(initial) {} + + // Only a *new, unpublished* insert may migrate an earlier state. + // Never modify a published JUCE graph or accept a speculative UI edit. + bool adoptUnpublishedScene(const armix::sonku::Settings& next) noexcept { + if(published_ || !armix::sonku::valid(next) || + !queue_.empty() || !complete_.empty())return false; + if(ready_ && !core_.setSettings(next))return false; + accepted_=next; +#if defined(ARMIX_SONKU_EXPERIMENTAL_P83_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P83_NATIVE_RT + audioSettings_=next; +#endif + observedAzimuthDegrees_.store(next.startAzimuthDegrees, + std::memory_order_relaxed); + return true; + }private: struct Edit {std::uint64_t requestId=0;armix::sonku::Settings settings{};}; armix::sonku::SonKuSpatialCore core_{}; FxSpsc queue_{}; diff --git a/engine/builtin_fx/sonku/SonKuEarlyReflections.h b/engine/builtin_fx/sonku/SonKuEarlyReflections.h index 46209c6b8..5a6a9b48c 100644 --- a/engine/builtin_fx/sonku/SonKuEarlyReflections.h +++ b/engine/builtin_fx/sonku/SonKuEarlyReflections.h @@ -161,7 +161,7 @@ class SonKuEarlyReflections final { !std::isfinite(g.distanceMeters))return false; if(g.widthMeters<5.f||g.depthMeters<5.f|| g.widthMeters>40.f||g.depthMeters>40.f|| - g.distanceMeters<1.6f||g.distanceMeters>10.f|| + g.distanceMeters<1.f||g.distanceMeters>10.f|| 2.f*(g.distanceMeters+.5f)>std::min(g.widthMeters,g.depthMeters)) return false; const float longest=std::max(g.widthMeters,g.depthMeters)+g.distanceMeters; diff --git a/engine/builtin_fx/sonku/SonKuP91P92WorldBassFoundation.h b/engine/builtin_fx/sonku/SonKuP91P92WorldBassFoundation.h index 938cb96a5..63551d22e 100644 --- a/engine/builtin_fx/sonku/SonKuP91P92WorldBassFoundation.h +++ b/engine/builtin_fx/sonku/SonKuP91P92WorldBassFoundation.h @@ -99,7 +99,16 @@ class WorldBassFoundation final { 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]; + // Private P9.5 venue reinforcement: augment the EXISTING + // low-frequency axial room modes slightly, not the direct + // bass, not a duplicate cabinet engine or hard EQ shelf. + // All modes remain damping-controlled with finite Q. +#if defined(SONKU_P95_MUSICAL_PRESENCE_RESEARCH) && SONKU_P95_MUSICAL_PRESENCE_RESEARCH + const float venue=roomPreset==3?1.18f:1.f; +#else + constexpr float venue=1.f; +#endif + const float level=roomWeights_[r]*roomGain_*modeWeights[b]*venue; modal.left+=level*l; modal.right+=level*rr; } diff --git a/engine/builtin_fx/sonku/SonKuP94FrontBackDepthCue.h b/engine/builtin_fx/sonku/SonKuP94FrontBackDepthCue.h new file mode 100644 index 000000000..f0f88088c --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuP94FrontBackDepthCue.h @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include + +// P9.4 private acoustic A/B (NOT a measured BRIR / dearVR clone). +// A front/rear source can collapse inside the head with non-individual KEMAR. +// At CONSTANT physical radius, adjust only the direct/first-reflection +// energy balance near the interaural median plane; measured HRIR spectra, +// ITD/ILD, speaker azimuth, low-frequency world transfer and tail stay intact. +// Must be validated by loudness-matched headphone FAT before release. +namespace armix::sonku::p94 { +class FrontBackDepthCue final { +public: + struct Gains {float direct=1.f,early=1.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; + slew_=static_cast(1.-std::exp(-1./(sampleRate*.045))); + for(std::size_t i=0;i((c*c)*(c*c)); + } + reset(); + return true; + } + void reset() noexcept {target_=0.f;weight_=0.f;enabled_=false;} + // Called at the existing every-16-sample HRTF retarget. Angle MUST be + // center WORLD azimuth - head yaw, never the ellipse's 2D SVG position. + void retarget(float headRelativeAzimuth,bool roomWithEarly) noexcept { + enabled_=roomWithEarly; + if(!enabled_ || !std::isfinite(headRelativeAzimuth)){ + target_=0.f;return; + } + // p83::toHead returns [-180,180], bounded wrap avoids RT fmod/cos. + float d=std::clamp(headRelativeAzimuth,-360.f,360.f); + if(d<0.f)d+=360.f; + if(d>=360.f)d-=360.f; + const int lo=std::clamp(static_cast(d),0,359); + const float frac=d-lo; + target_=shape_[lo]*(1.f-frac)+shape_[lo+1]*frac; + } + Gains next() noexcept { + weight_+=slew_*(target_-weight_); + if(std::abs(weight_-target_)<1.e-6f)weight_=target_; + // Room OFF / ER zero must never perturb the golden P9 PCM. + if(!enabled_)return {}; + const float w=std::clamp(weight_,0.f,1.f); + // At 0/180: direct -0.40 dB, early +2.14 dB. Ratio shifts by + // ~2.54 dB; NOT a source distance or headphone gain multiplier. + // At ±90 the output is mathematically bit-identical to P9.1/P9.2. + return {1.f-.045f*w,1.f+.28f*w}; + } +private: + std::array shape_{}; + float slew_=0.f,target_=0.f,weight_=0.f; + bool enabled_=false; +}; +} // namespace armix::sonku::p94 diff --git a/engine/builtin_fx/sonku/SonKuP95MusicalPresence.h b/engine/builtin_fx/sonku/SonKuP95MusicalPresence.h new file mode 100644 index 000000000..ece40572b --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuP95MusicalPresence.h @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include + +// Optional single-graph music-level *upward-only* compensation. +// In P9 spatial wet transforms the original stereo energy can be lower. +// A slow detector allows a conservative minimum electrical level without +// turning the entire effect into a compressor or defeating user gain. +// The final existing linked 0.98 sample peak safety limiter stays authoritative. +namespace armix::sonku::p95 { +class MusicalPresence final { +public: + bool prepare(double sr) noexcept { + if(!std::isfinite(sr) || (std::abs(sr-44100.)>.1 && std::abs(sr-48000.)>.1)) + return false; + detector_=static_cast(1.-std::exp(-1./(sr*.28))); + slew_=static_cast(1.-std::exp(-1./(sr*.45))); + reset();return true; + } + void reset() noexcept {inPower_=outPower_=0.f;target_=makeup_=1.f;counter_=0;} + float process(float inL,float inR,float wetL,float wetR) noexcept { + const float a=.5f*(inL*inL+inR*inR); + const float b=.5f*(wetL*wetL+wetR*wetR); + inPower_+=detector_*(a-inPower_); + outPower_+=detector_*(b-outPower_); + // At most one square root per 256 samples, outside inner FIR loops. + if(++counter_>=256){ + counter_=0; + if(inPower_>1.e-7f&&outPower_>1.e-9f){ + const float ratio=std::sqrt(inPower_/outPower_); + // 1.12× = +0.98dB *electrical* minimum when possible. + // Never auto-reduce the deliberate user outputTrim boost. + target_=std::clamp(1.12f*ratio,1.f,1.65f); + }else target_=1.f; + } + makeup_+=slew_*(target_-makeup_); + return makeup_; + } + float gain() const noexcept {return makeup_;} +private: + float detector_=0.f,slew_=0.f,inPower_=0.f,outPower_=0.f; + float target_=1.f,makeup_=1.f; + int counter_=0; +}; +} // namespace armix::sonku::p95 diff --git a/engine/builtin_fx/sonku/SonKuP96DistanceReinforcement.h b/engine/builtin_fx/sonku/SonKuP96DistanceReinforcement.h new file mode 100644 index 000000000..a32fb6e6f --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuP96DistanceReinforcement.h @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include + +// Private P9.6 sound-reinforcement hypothesis, downstream of the SAME measured +// two-loudspeaker HRIR and world-anchored LF handover. Split only DIRECT ear +// pressure, not late/early reflections, the original L/R music or dry side. +// The 170 Hz / 4.2 kHz complementary crossovers are causal one-poles; their +// components sum to the exact unfiltered ear signal at equal gains. +// No allocations, FFT, virtual mono sub, added latency or callback trig. +namespace armix::sonku::p96 { +class DistanceReinforcement final { +public: + struct Ears {float left=0.f,right=0.f;}; + bool prepare(double rate) noexcept { + if(!std::isfinite(rate) || + (std::abs(rate-44100.)>.1 && std::abs(rate-48000.)>.1))return false; + constexpr double pi=3.14159265358979323846; + lowAlpha_=static_cast(1.-std::exp(-2.*pi*170./rate)); + highAlpha_=static_cast(1.-std::exp(-2.*pi*4200./rate)); + depthAlpha_=static_cast(1.-std::exp(-1./(rate*.035))); + reset(); + return true; + } + void reset() noexcept {low_.fill(0.f);wide_.fill(0.f);depth_=0.f;} + bool active() const noexcept {return depth_!=0.f;} + Ears process(float left,float right,float distanceGain, + float distanceMeters,bool roomEnabled) noexcept { + // Preserve OFF and <=2m P9.5 PCM exactly. The state filters still + // warm every sample, preventing stale memory on a live distance edit. + const float target=roomEnabled? + std::clamp((distanceMeters-2.f)/8.f,0.f,1.f):0.f; + depth_+=depthAlpha_*(target-depth_); + if(std::abs(depth_-target)<1.e-6f)depth_=target; + const std::array ears{left,right}; + std::array out{}; + for(int c=0;c<2;++c){ + low_[c]+=lowAlpha_*(ears[c]-low_[c]); + wide_[c]+=highAlpha_*(ears[c]-wide_[c]); + } + if(depth_==0.f) + return {distanceGain*left,distanceGain*right}; + // The normal distance cue remains in the mid-band and in the native + // early/late DRR. Reinforced speaker direct LF and HF retain musical + // body/air instead of making 10m sound like only a midrange reverb. + // This is NOT a physical free-field SPL model or a loudness guarantee. + const float reinforcible=std::max(0.f,1.f-distanceGain)*depth_; + const float midGain=distanceGain+.24f*reinforcible; + const float lowLift=.52f*reinforcible; // total LF retention 0.76 + const float highLift=.43f*reinforcible; // total HF retention 0.67 + for(int c=0;c<2;++c) + out[c]=midGain*ears[c]+lowLift*low_[c]+highLift*(ears[c]-wide_[c]); + return {out[0],out[1]}; + } +private: + std::array low_{},wide_{}; + float lowAlpha_=0.f,highAlpha_=0.f,depthAlpha_=0.f,depth_=0.f; +}; +} // namespace armix::sonku::p96 diff --git a/engine/builtin_fx/sonku/SonKuP97StageImpact.h b/engine/builtin_fx/sonku/SonKuP97StageImpact.h new file mode 100644 index 000000000..5384fd3cc --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuP97StageImpact.h @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include + +// PRIVATE P9.7 concert-stage enhancement. No stems, no pseudo-vocal isolation: +// "center presence" applies equally to any center-panned material. Every +// added signal stays in the SAME measured world-speaker binaural graph. +// The source MID band goes THROUGH the existing HRIR. Bass reinforces the +// already HRTF/world-positioned direct ears, and air reinforces actual +// stereo image-source early reflections (not synthetic Haas/stereo widening). +// 0 additional delay; no heap, FFT, worker, I/O, trigonometry or exp in PCM. +namespace armix::sonku::p97 { +class StageImpact final { +public: + struct Stereo {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; + centerCoeff_=bandpass(sampleRate,1900.,.90); + punchCoeff_=bandpass(sampleRate,85.,.85); + subAlpha_=static_cast(1.-std::exp(-2.*pi*62./sampleRate)); + airAlpha_=static_cast(1.-std::exp(-2.*pi*4500./sampleRate)); + finalLowAlpha_=static_cast(1.-std::exp(-2.*pi*135./sampleRate)); + slew_=static_cast(1.-std::exp(-1./(sampleRate*.045))); + reset(); + return true; + } + void reset() noexcept { + vocal_={};vocalSecond_={};vocalDirect_={}; + punch_={};sub_={};earlyAir_={};directAir_={}; + finishLow_={};finishWide_={};stage_=0.f; + } + bool active() const noexcept {return stage_!=0.f;} + float strength() const noexcept {return stage_;} + Stereo source(float left,float right,float meters,bool roomEnabled) noexcept { + // One slow scene-depth transition, shared across the 3 stages. + const float target=roomEnabled? + std::clamp((meters-2.f)/4.f,0.f,1.f):0.f; + stage_+=slew_*(target-stage_); + if(std::abs(stage_-target)<1.e-6f)stage_=target; + const float center=.5f*(left+right); + // Two bandpasses suppress out-of-band leakage, especially cymbals + // >6kHz that a single 1.9kHz BPF would partly phase-cancel. + const float band=vocalSecond_.run(centerCoeff_, + vocal_.run(centerCoeff_,center)); + if(stage_==0.f)return {left,right}; + // Both virtual speakers receive exactly the same center delta. + // Their established HRIRs must render it; NEVER send to dry L/R. + const float delta=.19f*stage_*band; + return {left+delta,right+delta}; + } + Stereo direct(float left,float right) noexcept { + const std::array x{left,right}; + std::array result{}; + for(int c=0;c<2;++c) { + const float punch=punch_[c].run(punchCoeff_,x[c]); + sub_[c]+=subAlpha_*(x[c]-sub_[c]); + directAir_[c]+=airAlpha_*(x[c]-directAir_[c]); + const float voice=vocalDirect_[c][1].run(centerCoeff_, + vocalDirect_[c][0].run(centerCoeff_,x[c])); + // Keep spectral pressure tied to the original KEMAR ears. + // The second gentle vocal filter is NOT a dry/mono stem. + result[c]=stage_==0.f?x[c]: + x[c]+stage_*(.23f*punch+.085f*sub_[c]+ + .085f*voice+.038f*(x[c]-directAir_[c])); + } + return {result[0],result[1]}; + } + Stereo early(float left,float right) noexcept { + const std::array x{left,right}; + std::array result{}; + for(int c=0;c<2;++c){ + earlyAir_[c]+=airAlpha_*(x[c]-earlyAir_[c]); + // Boost only the real, azimuth-dependent first images above 4.5k. + // No channel crossing or artificial stereo delay: retain ILD/ITD. + result[c]=stage_==0.f?x[c]: + x[c]+.24f*stage_*(x[c]-earlyAir_[c]); + } + return {result[0],result[1]}; + } + Stereo finish(float left,float right) noexcept { + // P9.5 upward-only RMS makeup is sensitive to increased broadband + // level: direct/stem boosts can make it reduce its earlier makeup, + // unintentionally darkening cymbals. Only AFTER its detector, but + // BEFORE the existing linked peak guard, restore modest LF/HF + // spectral energy to the already-externalized stereo EAR waveform. + // Shared coefficients; no crossfeed, HRTF replacement, or new delay. + const std::array x{left,right}; + std::array result{}; + for(int c=0;c<2;++c){ + finishLow_[c]+=finalLowAlpha_*(x[c]-finishLow_[c]); + finishWide_[c]+=airAlpha_*(x[c]-finishWide_[c]); + result[c]=stage_==0.f?x[c]: + x[c]+stage_*(.080f*finishLow_[c]+ + .35f*(x[c]-finishWide_[c])); + } + return {result[0],result[1]}; + } + Stereo modal(float left,float right) const noexcept { + if(stage_==0.f)return {left,right}; + // Small damped room mode reinforcement, no feedback alteration. + const float level=1.f+.12f*stage_; + return {left*level,right*level}; + } +private: + struct Coeff {float b0=0.f,b1=0.f,b2=0.f,a1=0.f,a2=0.f;}; + struct Filter { + float z1=0.f,z2=0.f; + float run(const Coeff& c,float in) noexcept { + const float out=c.b0*in+z1; + z1=c.b1*in-c.a1*out+z2; + z2=c.b2*in-c.a2*out; + return out; + } + }; + static Coeff bandpass(double sampleRate,double frequency,double q) noexcept { + constexpr double pi=3.1415926535897932384626433832795; + const double w=2.*pi*frequency/sampleRate; + const double alpha=std::sin(w)/(2.*q); + const double inv=1./(1.+alpha); + return {static_cast(alpha*inv),0.f, + static_cast(-alpha*inv), + static_cast(-2.*std::cos(w)*inv), + static_cast((1.-alpha)*inv)}; + } + Coeff centerCoeff_{},punchCoeff_{}; + Filter vocal_{},vocalSecond_{}; + std::array punch_{}; + std::array,2> vocalDirect_{}; + std::array sub_{},earlyAir_{},directAir_{},finishLow_{},finishWide_{}; + float subAlpha_=0.f,airAlpha_=0.f,finalLowAlpha_=0.f,slew_=0.f,stage_=0.f; +}; +} // namespace armix::sonku::p97 diff --git a/engine/builtin_fx/sonku/SonKuP98SceneVoicing.h b/engine/builtin_fx/sonku/SonKuP98SceneVoicing.h new file mode 100644 index 000000000..90bab191a --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuP98SceneVoicing.h @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include + +// P9.8 PRIVATE named-scene voicings, never a second PCM graph or fake stem +// separator. All bands are processed on world-positioned KEMAR ears or +// genuine directional first images; center emphasis enters the two measured +// loudspeaker HRIRs BEFORE ear rendering. Mode 0 = exact P9.7 Venue/Custom. +// This class never guesses a preset from distance/reverb/gain floats. +namespace armix::sonku::p98 { +class SceneVoicing final { +public: + struct Stereo {float left=0.f,right=0.f;}; + // These IDs are stable native-serialized values, NOT native ROOM sizes. + // 4/5 are opt-in ImmerSIB-only profile IDs. Existing SONK v12 IDs + // 0..3 retain byte-for-byte matching coefficients and meaning. + enum : int { Neutral=0, Signature=1, LiveStudio=2, Cinema=3, + ImmerSIBDetail=4, ImmerSIBImpact=5 }; + 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; + punchCoeff_=bandpass(sampleRate,86.,.85); + voiceCoeff_=bandpass(sampleRate,2050.,.92); + // Product-only voicing 4/5: broad mid-vocal chest/body anchor, + // and upper-mid masking relief. All coefficients prepared OFF RT. + bodyCoeff_=bandpass(sampleRate,285.,.72); + edgeCoeff_=bandpass(sampleRate,3450.,.78); + bassAlpha_=static_cast(1.-std::exp(-2.*pi*130./sampleRate)); + airAlpha_=static_cast(1.-std::exp(-2.*pi*5200./sampleRate)); + slew_=static_cast(1.-std::exp(-1./(sampleRate*.055))); + reset(); + return true; + } + void reset() noexcept { + gains_={};center1_={};center2_={};punch_={};voice_={}; + bass_={};air_={};earlyAir_={};sidePresence1_={}; + sidePresence2_={};sideAirLow_=0.f; + bodyCenter_={};sideEdge_={};earEdge_={}; + } + static constexpr bool valid(int scene) noexcept { + return scene>=Neutral && scene<=ImmerSIBImpact; + } + // Only explicit preset changes set an ID. 55ms interpolates changes in + // gains, with no per-sample coefficient recompute, memory allocation or + // trigonometry. Silent profile defaults never alter P9.7 float order. + Stereo source(float left,float right,int scene,bool enabled) noexcept { + const auto target=curves_[enabled && valid(scene)?scene:Neutral]; + for(unsigned i=0;i5.2kHz. The two + // original KEMAR speaker paths remain the sole binaural renderer. + // Legacy voicing 0..3 has zero extra gains: same PCM arithmetic. + const float side=.5f*(left-right); + const float sideBand=sidePresence2_.run(voiceCoeff_, + sidePresence1_.run(voiceCoeff_,side)); + sideAirLow_+=airAlpha_*(side-sideAirLow_); + // Center-dominant material (often lead vocal, NOT a detected + // vocal stem) receives broad 285Hz body before virtual speakers. + // Instruments in the stereo difference are softly notched around + // 3.45kHz, where guitars/cymbals can mask a center vocal. + const float body=bodyCenter_.run(bodyCoeff_,center); + const float edge=sideEdge_.run(edgeCoeff_,side); + if(gains_[0]==0.f&&gains_[6]==0.f&&gains_[7]==0.f&& + gains_[8]==0.f&&gains_[9]==0.f) + return {left,right}; // profiles 0..3: source stays identical + const float centerBoost=gains_[0]*band+gains_[8]*body; + const float lateralAir=gains_[7]*(side-sideAirLow_); + const float maskedSide=gains_[6]*sideBand+gains_[9]*edge; + return {left+centerBoost-maskedSide+lateralAir, + right+centerBoost+maskedSide-lateralAir}; + } + Stereo early(float left,float right) noexcept { + const std::array x{left,right}; + float out[2]{}; + for(int c=0;c<2;++c){ + earlyAir_[c]+=airAlpha_*(x[c]-earlyAir_[c]); + out[c]=gains_[4]==0.f?x[c]: + x[c]+gains_[4]*(x[c]-earlyAir_[c]); + } + return {out[0],out[1]}; + } + Stereo finish(float left,float right) noexcept { + const std::array x{left,right}; + float out[2]{}; + for(int c=0;c<2;++c){ + const float kick=punch_[c].run(punchCoeff_,x[c]); + const float vocal=voice_[c][1].run(voiceCoeff_, + voice_[c][0].run(voiceCoeff_,x[c])); + bass_[c]+=bassAlpha_*(x[c]-bass_[c]); + air_[c]+=airAlpha_*(x[c]-air_[c]); + const float harsh=earEdge_[c].run(edgeCoeff_,x[c]); + if(gains_[1]==0.f&&gains_[2]==0.f&&gains_[3]==0.f&& + gains_[5]==0.f&&gains_[10]==0.f){ + out[c]=x[c]; + }else{ + // Avoid the old cumulative 2-5kHz presence/air lifts. + // A small broad EAR cut after the original measured HRIR + // helps reduce fatigue, keeping no extra crossfeed/delay. + out[c]=x[c]+gains_[1]*bass_[c]+gains_[2]*kick+ + gains_[3]*vocal+gains_[5]*(x[c]-air_[c])- + gains_[10]*harsh; + } + } + return {out[0],out[1]}; + } +private: + // channels: center-source, bass body, bass kick, vocal presence, + // first-image air, final-ear air, SIDE presence masking relief, + // SIDE high-air field, MID chest body, SIDE harsh relief and EAR + // de-harsh. Prepared filters only; still no FFT, lookahead or stems. + // Signature is designed for high clarity AND physical music body. + // Studio adjustment deliberately gentler than Cinema. Venue profile + // is ALL ZEROS: its approved P9.7 acoustic graph is immutable. + static constexpr std::array,6> curves_{{ + // Columns: upper-mid source; LF; kick; ear-presence; early air; + // ear air; SIDE 2.05k; SIDE HF; center 285Hz body; + // SIDE 3.45k masking; EAR 3.45k fatigue control. + {{0.f,0.f,0.f,0.f,0.f,0.f,0.f,0.f,0.f,0.f,0.f}}, // Venue EXACT + {{.22f,.15f,.17f,.15f,.16f,.070f,0.f,0.f,0.f,0.f,0.f}}, // Signature + {{.035f,.045f,.055f,.045f,.04f,.020f,0.f,0.f,0.f,0.f,0.f}}, // Live Studio + {{.075f,.15f,.15f,.060f,.065f,.035f,0.f,0.f,0.f,0.f,0.f}}, // Cinema + // ImmerSIB-only: warmer front-center body and controlled upper + // mids, not another 2k/5k treble boost. LF concert impact kept. + {{.09f,.11f,.11f,.035f,.025f,.000f,.19f,.015f,.36f,.23f,.13f}}, // Detail Warm + {{.08f,.22f,.20f,.030f,.025f,.000f,.16f,.015f,.29f,.20f,.12f}} // Impact Warm + }}; + struct Coeff {float b0=0,b1=0,b2=0,a1=0,a2=0;}; + struct Filter { + float z1=0,z2=0; + float run(const Coeff& c,float x) noexcept { + const float y=c.b0*x+z1; + z1=c.b1*x-c.a1*y+z2; + z2=c.b2*x-c.a2*y; + return y; + } + }; + 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)}; + } + Coeff punchCoeff_{},voiceCoeff_{},bodyCoeff_{},edgeCoeff_{}; + Filter center1_{},center2_{}; + std::array punch_{}; + std::array,2> voice_{}; + std::array bass_{},air_{},earlyAir_{}; + Filter sidePresence1_{},sidePresence2_{},bodyCenter_{},sideEdge_{}; + std::array earEdge_{}; + float sideAirLow_=0.f; + std::array gains_{}; + float bassAlpha_=0.f,airAlpha_=0.f,slew_=0.f; +}; +} // namespace armix::sonku::p98 diff --git a/engine/builtin_fx/sonku/SonKuSourcePlacement3D.h b/engine/builtin_fx/sonku/SonKuSourcePlacement3D.h index 74f87f4ba..9afb959be 100644 --- a/engine/builtin_fx/sonku/SonKuSourcePlacement3D.h +++ b/engine/builtin_fx/sonku/SonKuSourcePlacement3D.h @@ -16,7 +16,7 @@ inline bool project(float radialMeters,float elevationDegrees, Placement& result) noexcept { if(!std::isfinite(radialMeters)||!std::isfinite(elevationDegrees)|| !std::isfinite(listenerHeight)||!std::isfinite(roomHeight)|| - radialMeters<1.6f||radialMeters>10.f|| + radialMeters<1.f||radialMeters>10.f|| elevationDegrees< -40.f||elevationDegrees>60.f|| roomHeight<2.4f||roomHeight>12.f|| listenerHeight<.5f||listenerHeight>roomHeight-.5f)return false; diff --git a/engine/builtin_fx/sonku/SonKuSpatialCore.h b/engine/builtin_fx/sonku/SonKuSpatialCore.h index 5b8e26eaf..25517a03b 100644 --- a/engine/builtin_fx/sonku/SonKuSpatialCore.h +++ b/engine/builtin_fx/sonku/SonKuSpatialCore.h @@ -22,6 +22,21 @@ #if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH #include "SonKuP90StereoDecoder.h" #include "SonKuP91P92WorldBassFoundation.h" +#if defined(SONKU_P95_MUSICAL_PRESENCE_RESEARCH) && SONKU_P95_MUSICAL_PRESENCE_RESEARCH +#include "SonKuP95MusicalPresence.h" +#endif +#if defined(SONKU_P96_DISTANCE_REINFORCEMENT_RESEARCH) && SONKU_P96_DISTANCE_REINFORCEMENT_RESEARCH +#include "SonKuP96DistanceReinforcement.h" +#endif +#if defined(SONKU_P97_STAGE_IMPACT_RESEARCH) && SONKU_P97_STAGE_IMPACT_RESEARCH +#include "SonKuP97StageImpact.h" +#endif +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH +#include "SonKuP98SceneVoicing.h" +#endif +#if defined(SONKU_P94_FRONT_BACK_DEPTH_RESEARCH) && SONKU_P94_FRONT_BACK_DEPTH_RESEARCH +#include "SonKuP94FrontBackDepthCue.h" +#endif #endif #endif #if defined(SONKU_P87_MUSIC_BODY_RESEARCH) && SONKU_P87_MUSIC_BODY_RESEARCH @@ -76,6 +91,9 @@ struct Settings { int renderMode = 0; bool musicCompatibleLowFrequency = false; float headYawDegrees = 0.f; // deterministic world/head separation +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + int sceneVoicing=0; // 0=unchanged Venue/Custom; 1=Signature; 2=Studio; 3=Cinema +#endif #if defined(SONKU_P88_PERCEPTUAL_ALIGNMENT_RESEARCH) && SONKU_P88_PERCEPTUAL_ALIGNMENT_RESEARCH float hrtfElevationTrimDegrees=0.f; // spectral only, never room XYZ #endif @@ -91,10 +109,26 @@ inline bool valid(const Settings& s) noexcept { std::isfinite(s.spatialMix) && s.spatialMix>=0.f && s.spatialMix<=1.f && std::isfinite(s.outputTrim) && s.outputTrim>=0.f && s.outputTrim<=4.f && s.spacePreset>=0 && s.spacePreset<=3 && - std::isfinite(s.sourceDistanceMeters) && s.sourceDistanceMeters>=1.6f && + std::isfinite(s.sourceDistanceMeters) && s.sourceDistanceMeters>=1.f && s.sourceDistanceMeters<=10.f && - std::isfinite(s.roomAmount) && s.roomAmount>=0.f && s.roomAmount<=1.f && + std::isfinite(s.roomAmount) && s.roomAmount>=0.f && +#if defined(SONKU_P83_PHYSICAL_SPEAKER_RESEARCH) && SONKU_P83_PHYSICAL_SPEAKER_RESEARCH + s.roomAmount<=(s.renderMode==9?1.8f:1.f) && +#else + // Pre-P8.3 Settings has no renderMode. Keep its legacy 0..1 range. + s.roomAmount<=1.f && +#endif std::isfinite(s.ambience) && s.ambience>=0.f && s.ambience<=1.f && +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + p98::SceneVoicing::valid(s.sceneVoicing) && + // v12 deliberately excludes the retired P8.3 physical/mono + // modes 1/2 even when neutral voicing=0. The old P8.3 renderer + // was rejected by the operator; JSON, realtime edits and .smix + // restore must use ONE admission rule, not three distinct gates. + (s.renderMode==0 || (s.renderMode>=3 && s.renderMode<=9)) && + !s.musicCompatibleLowFrequency && + (s.sceneVoicing==0 || s.renderMode==9) && +#endif #if defined(SONKU_P83_PHYSICAL_SPEAKER_RESEARCH) && SONKU_P83_PHYSICAL_SPEAKER_RESEARCH s.renderMode>=0 && #if defined(SONKU_P84_SINGLE_CORE_FUSION_RESEARCH) && SONKU_P84_SINGLE_CORE_FUSION_RESEARCH @@ -204,6 +238,21 @@ class SonKuSpatialCore final { #if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH if(!p90Decoder_.prepare(rate))return false; if(!p92Bass_.prepare(rate))return false; +#if defined(SONKU_P96_DISTANCE_REINFORCEMENT_RESEARCH) && SONKU_P96_DISTANCE_REINFORCEMENT_RESEARCH + if(!p96Reinforcement_.prepare(rate))return false; +#endif +#if defined(SONKU_P97_STAGE_IMPACT_RESEARCH) && SONKU_P97_STAGE_IMPACT_RESEARCH + if(!p97Stage_.prepare(rate))return false; +#endif +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + if(!p98Voicing_.prepare(rate))return false; +#endif +#if defined(SONKU_P95_MUSICAL_PRESENCE_RESEARCH) && SONKU_P95_MUSICAL_PRESENCE_RESEARCH + if(!p95Presence_.prepare(rate))return false; +#endif +#if defined(SONKU_P94_FRONT_BACK_DEPTH_RESEARCH) && SONKU_P94_FRONT_BACK_DEPTH_RESEARCH + if(!p94Depth_.prepare(rate))return false; +#endif #endif #endif #if defined(SONKU_P87_MUSIC_BODY_RESEARCH) && SONKU_P87_MUSIC_BODY_RESEARCH @@ -272,6 +321,21 @@ class SonKuSpatialCore final { #if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH p90Decoder_.reset(); p92Bass_.reset(); +#if defined(SONKU_P96_DISTANCE_REINFORCEMENT_RESEARCH) && SONKU_P96_DISTANCE_REINFORCEMENT_RESEARCH + p96Reinforcement_.reset(); +#endif +#if defined(SONKU_P97_STAGE_IMPACT_RESEARCH) && SONKU_P97_STAGE_IMPACT_RESEARCH + p97Stage_.reset(); +#endif +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + p98Voicing_.reset(); +#endif +#if defined(SONKU_P95_MUSICAL_PRESENCE_RESEARCH) && SONKU_P95_MUSICAL_PRESENCE_RESEARCH + p95Presence_.reset(); +#endif +#if defined(SONKU_P94_FRONT_BACK_DEPTH_RESEARCH) && SONKU_P94_FRONT_BACK_DEPTH_RESEARCH + p94Depth_.reset(); +#endif #endif #if defined(SONKU_P83_PHYSICAL_SPEAKER_RESEARCH) && SONKU_P83_PHYSICAL_SPEAKER_RESEARCH p83LowFrequency_.reset(); @@ -323,6 +387,21 @@ class SonKuSpatialCore final { if((s.renderMode==9)!=(settings_.renderMode==9)){ p90Decoder_.reset(); p92Bass_.reset(); +#if defined(SONKU_P96_DISTANCE_REINFORCEMENT_RESEARCH) && SONKU_P96_DISTANCE_REINFORCEMENT_RESEARCH + p96Reinforcement_.reset(); +#endif +#if defined(SONKU_P97_STAGE_IMPACT_RESEARCH) && SONKU_P97_STAGE_IMPACT_RESEARCH + p97Stage_.reset(); +#endif +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + p98Voicing_.reset(); +#endif +#if defined(SONKU_P95_MUSICAL_PRESENCE_RESEARCH) && SONKU_P95_MUSICAL_PRESENCE_RESEARCH + p95Presence_.reset(); +#endif +#if defined(SONKU_P94_FRONT_BACK_DEPTH_RESEARCH) && SONKU_P94_FRONT_BACK_DEPTH_RESEARCH + p94Depth_.reset(); +#endif } #endif settings_=s; @@ -726,8 +805,33 @@ class SonKuSpatialCore final { if(p83Mode_==p83::Mode::MusicSpatialP90)sideRescue=0.f; #endif #endif - history_[0][write_]=x0; - history_[1][write_]=x1; +#if defined(SONKU_P97_STAGE_IMPACT_RESEARCH) && SONKU_P97_STAGE_IMPACT_RESEARCH + if(p90World && settings_.spatialMix>0.f){ + // Center material is reinforced ONLY before the existing + // world-speaker HRIR; room, P92 LF, and decoder observe + // the original stereo. No center headphone dry injection. + const auto fed=p97Stage_.source(x0,x1, + settings_.sourceDistanceMeters,roomEnabled); + history_[0][write_]=fed.left; + history_[1][write_]=fed.right; + }else +#endif + { + history_[0][write_]=x0; + history_[1][write_]=x1; + } +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + if(p90World && settings_.spatialMix>0.f){ + const auto fed=p98Voicing_.source(history_[0][write_], + history_[1][write_],settings_.sceneVoicing,roomEnabled); + history_[0][write_]=fed.left; + history_[1][write_]=fed.right; + }else{ + // Smoothly return private voicing to neutral without ever + // injecting headphone-dry voice or mutating the original PCM. + (void)p98Voicing_.source(0.f,0.f,0,false); + } +#endif float ears[2]{0.f,0.f}; for(int tap=0;tap0.f){ + // Spectral stage changes remain tied to the HRTF and + // the existing 6-wall first-image / P92 modal fields. + // Identical stereo-ear coefficients do not pan/delay + // sources or manufacture independent mono-bass channels. + const auto punch=p97Stage_.direct(directL,directR); + directL=punch.left;directR=punch.right; + const auto air=p97Stage_.early(reflection.left,reflection.right); + reflection.left=air.left;reflection.right=air.right; + const auto modal=p97Stage_.modal(p92RoomBass.left,p92RoomBass.right); + p92RoomBass.left=modal.left;p92RoomBass.right=modal.right; + } +#endif +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + if(p90World && settings_.spatialMix>0.f && roomEnabled){ + const auto air=p98Voicing_.early(reflection.left,reflection.right); + reflection.left=air.left;reflection.right=air.right; + } +#endif + float spatialL=directL+ + smoothedErPresence_*calibratedEarly*reflection.left+ smoothedTailPresence_*late.left; - float spatialR=smoothedDistanceGain_*ears[1]+ - smoothedErPresence_*reflection.right+ + float spatialR=directR+ + smoothedErPresence_*calibratedEarly*reflection.right+ smoothedTailPresence_*late.right; #if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH if(p90World){ @@ -941,6 +1091,33 @@ class SonKuSpatialCore final { float outR=baseDryR+smoothedTrim_* ((transparentBass?musicLowR:dryLevel*x1)+ sceneBinauralLevel*(transparentBass?1.f:smoothedRoomLevel_)*spatialR)-sideRescue; +#if defined(SONKU_P95_MUSICAL_PRESENCE_RESEARCH) && SONKU_P95_MUSICAL_PRESENCE_RESEARCH + if(p90World){ + // Single native PCM graph, no WebAudio or dynamic makeup + // at 0% spatial MIX. Explicit user GAIN still applies. + if(settings_.spatialMix>0.f){ + const float makeup=p95Presence_.process(x0,x1,outL,outR); + outL*=makeup;outR*=makeup; + } + } +#endif +#if defined(SONKU_P97_STAGE_IMPACT_RESEARCH) && SONKU_P97_STAGE_IMPACT_RESEARCH + if(p90World && settings_.spatialMix>0.f){ + // The finished ear tonal block MUST NOT touch + // 0% MIX (native dry/bypass) even while ROOM remains ON. + const auto finished=p97Stage_.finish(outL,outR); + outL=finished.left;outR=finished.right; + } +#endif +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + if(p90World && settings_.spatialMix>0.f && roomEnabled){ + // Post-adaptive-makeup, PRE-existing 0.98 linked guard. + // The cinema low-end cannot attenuate the whole mix + // via the upstream automatic compensation meter. + const auto voiced=p98Voicing_.finish(outL,outR); + outL=voiced.left;outR=voiced.right; + } +#endif // Zero-lookahead *linked* sample-peak safety guard. Quiet // signals are linear; peaks are gently returned below unity // without routing through a second engine or allocating. @@ -983,7 +1160,11 @@ class SonKuSpatialCore final { const auto preset=s.spacePreset==3?SonKuReverbPreset::LargeRoom: s.spacePreset==2?SonKuReverbPreset::AiryChamber: SonKuReverbPreset::StudioGlue; - return room_.setRealtimeRoom(geometry,s.roomAmount,s.spacePreset!=0) && + return // Physical tap amount stays <=100%. Above 100%, only the + // bounded direct-independent early-presence gain grows. + // <=1 remains bit-identical to the archival P9.7 Venue. + room_.setRealtimeRoom(geometry,std::min(s.roomAmount,1.f), + s.spacePreset!=0) && reverb_.setRealtimeProgram(preset, s.spacePreset!=0?s.ambience:0.f); } @@ -1149,6 +1330,10 @@ class SonKuSpatialCore final { if(p83Mode_==p83::Mode::MusicSpatialP90){ p90Decoder_.compose(centerTarget_,targets_[0],targets_[1]); p92Bass_.updateDirections(positions.leftHead,positions.rightHead); +#if defined(SONKU_P94_FRONT_BACK_DEPTH_RESEARCH) && SONKU_P94_FRONT_BACK_DEPTH_RESEARCH + p94Depth_.retarget(p83::toHead(static_cast(degrees_),p83HeadYaw_), + settings_.spacePreset!=0 && settings_.roomAmount>0.f); +#endif } else #endif @@ -1249,6 +1434,21 @@ class SonKuSpatialCore final { #if defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) && SONKU_P90_TRUE_EXTERNAL_RESEARCH p90::StereoDecoder p90Decoder_{}; p92::WorldBassFoundation p92Bass_{}; +#if defined(SONKU_P96_DISTANCE_REINFORCEMENT_RESEARCH) && SONKU_P96_DISTANCE_REINFORCEMENT_RESEARCH + p96::DistanceReinforcement p96Reinforcement_{}; +#endif +#if defined(SONKU_P97_STAGE_IMPACT_RESEARCH) && SONKU_P97_STAGE_IMPACT_RESEARCH + p97::StageImpact p97Stage_{}; +#endif +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + p98::SceneVoicing p98Voicing_{}; +#endif +#if defined(SONKU_P95_MUSICAL_PRESENCE_RESEARCH) && SONKU_P95_MUSICAL_PRESENCE_RESEARCH + p95::MusicalPresence p95Presence_{}; +#endif +#if defined(SONKU_P94_FRONT_BACK_DEPTH_RESEARCH) && SONKU_P94_FRONT_BACK_DEPTH_RESEARCH + p94::FrontBackDepthCue p94Depth_{}; +#endif #endif #if defined(SONKU_P87_MUSIC_BODY_RESEARCH) && SONKU_P87_MUSIC_BODY_RESEARCH p87::MusicalAirBody p87Body_{}; diff --git a/scripts/normalize_immersib_scene_assets.py b/scripts/normalize_immersib_scene_assets.py new file mode 100644 index 000000000..23020ba0d --- /dev/null +++ b/scripts/normalize_immersib_scene_assets.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: AGPL-3.0-only +"""Normalize ONLY the six approved photo venues to a 2200x922 concert viewport. + +No artificial speaker sprites, no distortion, no black padding, no synthesis. +Original photography remains recoverable from Git history. Idempotent operation. +""" +from __future__ import annotations +import argparse +from pathlib import Path +from PIL import Image + +CANVAS=(2200,922) +SCENE_TOP={ + "scene_live_concert.png":0.50, + "scene_royal_concert_hall.png":0.20, + "scene_arena_thunder.png":0.17, + "scene_front_row_power.png":0.14, + "scene_symphonic_palace.png":0.20, + "scene_velvet_cinema.png":0.50, +} + +def fit_photo(image: Image.Image, name: str) -> tuple[Image.Image,tuple[int,int,int,int]]: + original=image.convert("RGB") + sw,sh=original.size + tw,th=CANVAS + if sw*th>=sh*tw: + cw,ch=max(1,sh*tw//th),sh + else: + cw,ch=sw,max(1,sw*th//tw) + x0=(sw-cw)//2 + y0=round((sh-ch)*SCENE_TOP[name]) + y0=max(0,min(sh-ch,y0)) + crop_rect=(x0,y0,x0+cw,y0+ch) + # LANCZOS is only resampling; never stretch independent X/Y geometries. + return original.crop(crop_rect).resize(CANVAS,Image.Resampling.LANCZOS),crop_rect + +def main()->int: + parser=argparse.ArgumentParser() + parser.add_argument("--directory",type=Path,default=Path("assets/imersip/scenes")) + parser.add_argument("--check",action="store_true") + args=parser.parse_args() + observed={p.name for p in args.directory.glob("*.png")} + expected=set(SCENE_TOP) + if observed!=expected: + raise SystemExit(f"Unexpected photo files: missing={expected-observed} extra={observed-expected}") + failures=[] + for name in SCENE_TOP: + path=args.directory/name + with Image.open(path) as original: + original.load() + if original.size==CANVAS and original.mode in ("RGB","RGBA"): + print(f"PASS {name}: {original.size} {original.mode}");continue + if args.check: + failures.append(f"{name}: {original.size} {original.mode}") + continue + image,box=fit_photo(original,name) + print(f"NORMALIZE {name}: {original.size} -> {image.size} source_crop={box}") + image.save(path,"PNG",optimize=True,compress_level=7) + if failures: + raise SystemExit("PANORAMA CONTRACT FAIL:\n"+"\n".join(failures)) + return 0 +if __name__=="__main__": + raise SystemExit(main()) diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index ed6a565b9..4eeb19998 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -2826,8 +2826,13 @@ 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; + // The bridge has already painted each installed FX row using the SAME + // authoritative PCM snapshot. Only the global button and overall muted + // styling change here; render() would unnecessarily replace faders, rack + // buttons and open editor focus on every global bypass click. + globalFxOn=enabled; + syncGlobalFxButton(); + return true; }; document.querySelector('.section-rail').addEventListener('click',e=>{ const button=e.target.closest('[data-section]');if(!button)return; diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index f7bee36fa..42951518e 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -2258,6 +2258,45 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const armix::mixer::LiveChannelFxGraph::InstanceLease& owner) const noexcept { return dryRoutingLab_.retainsFxEditor(epoch,owner); } + using RetainedFxPowerState=LiveDryRoutingLab::RetainedFxPowerState; + // Same verified control authority as FX Rack, but the native editor + // resolves the CURRENT graph revision for its retained exact instance. + RetainedFxPowerState retainedNativeFxPower( + const armix::mixer::LiveChannelFxGraph::InstanceLease& held, + armix::mixer::ChannelId id,std::size_t slot, + const juce::String& token) const noexcept { + if(routeReconfiguring_.load(std::memory_order_acquire)|| + independent_.active())return {}; + return dryRoutingLab_.retainedNativeFxPower(held,id,slot,token); + } + bool bypassRetainedNativeFx( + const armix::mixer::LiveChannelFxGraph::InstanceLease& held, + armix::mixer::ChannelId id,std::size_t slot, + const juce::String& token,bool bypass) noexcept { + if(routeReconfiguring_.load(std::memory_order_acquire)|| + independent_.active()|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.bypassRetainedNativeFx( + held,id,slot,token,bypass); + } + RetainedFxPowerState retainedRoutedFxPower( + const armix::mixer::LiveChannelFxGraph::InstanceLease& held, + int lane,int slot,const juce::String& token) const noexcept { + if(routeReconfiguring_.load(std::memory_order_acquire)|| + independent_.active())return {}; + return dryRoutingLab_.retainedRoutedFxPower(held,lane,slot,token); + } + bool bypassRetainedRoutedFx( + const armix::mixer::LiveChannelFxGraph::InstanceLease& held, + int lane,int slot,const juce::String& token,bool bypass) noexcept { + if(routeReconfiguring_.load(std::memory_order_acquire)|| + independent_.active()|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.bypassRetainedRoutedFx( + held,lane,slot,token,bypass); + } bool bypassNativeVst3(std::uint64_t epoch,std::uint64_t revision, armix::mixer::ChannelId id,std::size_t slot, const juce::String& token,bool bypass) noexcept { diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 02292934a..418465e7b 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -66,6 +66,14 @@ class LiveDryRoutingLab final { const juce::MemoryBlock* binary=nullptr; }; using FxRestores=std::array,fxSlots>; + // CONTROL/UI-thread snapshot of the three independent audio bypass gates. + // Do not overwrite saved slot/rack flags when global A/B changes. + struct RetainedFxPowerState final { + bool valid=false,slotBypassed=false,rackBypassed=false,globalBypassed=false; + bool effectiveBypassed() const noexcept { + return valid && (slotBypassed || rackBypassed || globalBypassed); + } + }; struct ChannelEdit { float linear=1.f, pan=0.f; bool mute=false, solo=false, mono=false; @@ -1404,6 +1412,56 @@ class LiveDryRoutingLab final { if(prepared->insertInstanceId(lane,slot)==owner->instanceId)return true; return false; } + // The editor may outlive an FX rack MOVE/revision. Resolve the actual + // CURRENT accepted owner, rather than using epoch/revision frozen when + // its window opened. A replaced/retired processor is NEVER controlled. + RetainedFxPowerState retainedNativeFxPower( + const FxGraph::InstanceLease& held,armix::mixer::ChannelId id, + std::size_t slot,const juce::String& token) const noexcept { + RetainedFxPowerState out{}; + if(!held || !id.value || token.isEmpty() || + !channelIdPhysicalPcmActive() || !nativeAccepted_.fxOwners || + nativeAccepted_.deviceEpoch!=epoch() || !ready())return out; + const auto* live=nativeAccepted_.fxOwners->ownerForControl(id,slot); + if(!live || !*live || live->get()!=held.get() || + (*live)->instanceId!=token || !(*live)->processor)return out; + out.valid=true; + out.slotBypassed=held->bypassRequested.load(std::memory_order_acquire); + out.rackBypassed=nativeAccepted_.fxOwners->rackBypassed(id); + out.globalBypassed=globalFxBypassed(); + return out; + } + bool bypassRetainedNativeFx( + const FxGraph::InstanceLease& held,armix::mixer::ChannelId id, + std::size_t slot,const juce::String& token,bool bypass) noexcept { + if(!retainedNativeFxPower(held,id,slot,token).valid)return false; + return nativeAccepted_.setFxBypass(nativePublisher_,epoch(), + nativeAccepted_.pcmRevision,id,slot,token,bypass); + } + RetainedFxPowerState retainedRoutedFxPower( + const FxGraph::InstanceLease& held,int lane,int slot, + const juce::String& token) const noexcept { + RetainedFxPowerState out{}; + if(!held || token.isEmpty() || !ready() || + channelIdPhysicalPcmActive() || !hasExplicitRoute() || + lane<0 || lane>=fxSlots || slot<0 || slot>=maxFxPerLane) + return out; + const auto ep=epoch(),rev=revision(); + const auto* current=publisher_.controlPrepared(ep,rev); + if(!current || current->leaseInsert(lane,slot,token)!=held) + return out; + out.valid=true; + out.slotBypassed=held->bypassRequested.load(std::memory_order_acquire); + out.rackBypassed=current->rackBypassed(lane); + out.globalBypassed=globalFxBypassed(); + return out; + } + bool bypassRetainedRoutedFx( + const FxGraph::InstanceLease& held,int lane,int slot, + const juce::String& token,bool bypass) noexcept { + if(!retainedRoutedFxPower(held,lane,slot,token).valid)return false; + return setFxBypass(lane,slot,epoch(),revision(),token,bypass); + } bool bypassNativeInsert(std::uint64_t epochAtEdit,std::uint64_t pcmRevision, armix::mixer::ChannelId target,std::size_t slot, const juce::String& token,bool bypass) noexcept { diff --git a/src/Main.cpp b/src/Main.cpp index b2fec3726..268e96d1c 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -12,6 +12,7 @@ #include "NativeSessionToken.h" #include "ArSonMixStartupSplash.h" #include "ArSonWindowChrome.h" +#include "NativeOwnedFloatingWindow.h" #include "VstOrbitController.h" #include "../engine/core/OrbitDistanceMapping.h" #include "../engine/core/DearVrPolarPolicy.h" @@ -179,15 +180,28 @@ class Browser final : public juce::WebBrowserComponent class PluginEditorWindow final : public juce::DocumentWindow { public: - PluginEditorWindow (const juce::String& title, juce::AudioProcessorEditor* editor) + PluginEditorWindow (const juce::String& title, juce::AudioProcessorEditor* editor, + juce::Component& mixer) : DocumentWindow (title, juce::Colour (0xff14212a), allButtons) { setUsingNativeTitleBar (true); setIcon (approvedAppIcon()); setContentOwned (editor, true); - setResizable (true, true); + // Do not offer false host resizing for fixed-geometry built-in FX. + setResizable (editor->isResizable(), false); centreWithSize (juce::jmax (380, editor->getWidth()), juce::jmax (300, editor->getHeight())); + // A Win32-owned floating editor stays above THIS mixer, not every app. + // Attach after bounds are set (JUCE 8 native owned-popup coordinates). + (void) armix::ui::attachOwnedFloatingWindow (*this, mixer); setVisible (true); + (void) armix::ui::attachOwnedFloatingWindow (*this, mixer); + present(); + } + void present() + { + if (!isVisible()) setVisible (true); + if (isMinimised()) setMinimised (false); + toFront (true); } void closeButtonPressed() override { setVisible (false); } }; @@ -196,7 +210,8 @@ class AudioSetupWindow final : public juce::DocumentWindow { public: explicit AudioSetupWindow (juce::AudioDeviceManager& manager, - std::function onClosed) + std::function onClosed, + juce::Component& mixer) : juce::DocumentWindow ("AR MIX — ASIO / WASAPI Setup", juce::Colour (0xff14212a), allButtons), onClosed_ (std::move (onClosed)) @@ -217,6 +232,7 @@ class AudioSetupWindow final : public juce::DocumentWindow selector->setSize (720, 550); setContentOwned (selector, false); centreWithSize (740, 590); + (void) armix::ui::attachOwnedFloatingWindow (*this, mixer); } void closeButtonPressed() override { setVisible (false); } void visibilityChanged() override @@ -586,6 +602,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr juce::String lastNativeThrowEpoch_,lastNativeThrowRevision_; armix::mixer::NativeMusicTempoMonitor::State lastMusicTempo_{}; std::unique_ptr editorWindow_; + juce::AudioProcessor* editorProcessor_=nullptr; // identity only, never owns PCM std::unique_ptr audioSetupWindow_; // Persistent modal lease: blocks an Apply/ASIO restart while JUCE's // device selector is open, not merely during the initial show() call. @@ -1028,9 +1045,21 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr browser_.emitEventIfBrowserIsVisible ("arMixPresets", presets_.list()); } + void synchronizeOpenImmerSIBPower() { +#if defined(ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT + // The editor must reflect accepted global/rack/slot PCM state even + // when the gesture originated in the WebView header or FX Rack. + // All these dispatches run on JUCE's UI/message thread. + if(editorWindow_) + if(auto* ui=dynamic_cast( + editorWindow_->getContentComponent())) + ui->synchronizeHostPower(); +#endif + } void closePluginEditor() noexcept { - // JUCE destroys the editor before releasing the owner's processor. + // Dispose the native UI BEFORE dropping the graph/processor lease. editorWindow_.reset(); + editorProcessor_=nullptr; routedEditorOwner_.reset(); routedEditorEpoch_=0; } @@ -1304,23 +1333,32 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } void openLogicalVendorEditor(const juce::var& request) { - if(logicalVendorEditor_ || mixerSessionWorker_.busy() || logicalMixer_.readOnly()) { - emitNotice("Close the current FX editor or wait for the mixer to finish saving",true); - return; - } std::uint64_t channel=0; std::size_t slot=0; if(!logicalFxTarget(request,channel,slot)) { emitNotice("The selected FX slot changed",true); return; } + if(logicalVendorEditor_) { + auto& existing=*logicalVendorEditor_; + if(existing.window)existing.window->present(); + if(existing.workspaceToken==logicalMixer_.workspace().workspaceToken() && + existing.insert.channel==armix::mixer::ChannelId{channel} && existing.insert.slot==slot) + return; // Exact same logical FX: refocus without losing state. + emitNotice("Finish the currently open FX editor first",true); + return; + } + if(mixerSessionWorker_.busy() || logicalMixer_.readOnly()) { + emitNotice("Finish the current mixer save before opening FX",true); + return; + } LogicalVendorEditor prepared; auto error=prepareLogicalFx(logicalMixer_.workspace(),{channel},slot,prepared.insert,prepared.processor); if(error.isEmpty()) { try { if(auto* editor=prepared.processor->createEditorIfNeeded()) { prepared.window=std::make_unique( - prepared.processor->getName(),editor); + prepared.processor->getName(),editor,*this); prepared.workspaceToken=logicalMixer_.workspace().workspaceToken(); logicalVendorEditor_=std::move(prepared); return; @@ -2684,8 +2722,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr : "Choose a working stereo output in Audio I/O. Input hardware is optional.", true); safe->emitApprovedNativeSnapshot(); } - }); + }, *safe); safe->audioSetupWindow_->setVisible (true); + (void) armix::ui::attachOwnedFloatingWindow ( + *safe->audioSetupWindow_, *safe); safe->audioSetupWindow_->toFront (true); // The peer now exists: perform one initial JUCE layout on the // message thread, rather than relying on a manual window drag. @@ -5329,6 +5369,13 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr armix::mixer::LiveChannelFxGraph::InstanceLease{}; auto* p=dynamic_cast( unbound?offline.get():owner?owner->processor.get():nullptr); +#if defined(ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT + // ImerSip reuses SonKu's realtime engine, not its product + // control endpoint. A stale/misrouted SonKu WebView2 event + // must never capture or alter a separately owned ImerSip slot. + if(p && dynamic_cast(p)) + p=nullptr; +#endif if(action=="nativeSonKuSnapshot") { emitNativeSonKuSnapshot(request,rawChannel.toString(), rawEpoch.toString(),rawRevision.toString(),rawInstance.toString(),p); @@ -5548,6 +5595,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr lane,static_cast(static_cast(ep)), static_cast(static_cast(rv)), static_cast(value)); + if(applied)synchronizeOpenImmerSIBPower(); auto ack=std::make_unique(); ack->setProperty("requestId",requestId); ack->setProperty("ok",applied); @@ -5916,6 +5964,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( "arMixGlobalFxAck",juce::var(ack.release())); if(applied) { + synchronizeOpenImmerSIBPower(); diagnostics_.record("GLOBAL_FX_AB", engine_.globalFxBypassed()?"BYPASS_ALL":"ENABLE_RESTORED"); emitApprovedNativeSnapshot(); @@ -5975,6 +6024,13 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr "Native FX power rejected: stale device/revision, Show busy or instance mismatch"); if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( "arMixNativeFxPowerAck",juce::var(ack.release())); + if(applied) { + synchronizeOpenImmerSIBPower(); + // A native slot/rack ACK is not enough to repaint the + // other authority (WebView FX Rack). Publish the accepted + // producer state once per successful gesture, never on hover. + emitApprovedNativeSnapshot(); + } if(applied)diagnostics_.record("NATIVE_FX_POWER", rawId.toString()+(action=="routingNativeFxRackBypass"?" rack":" insert")+ (static_cast(value)?" BYPASS":" ENABLE")); @@ -6447,6 +6503,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr static_cast(args.getProperty("revision",juce::var(0)))); const bool ok=value.isBool()&&engine_.setDryRoutingLabFxBypass( lane,slot,epoch,revision,token,static_cast(value)); + if(ok)synchronizeOpenImmerSIBPower(); auto ack=std::make_unique(); ack->setProperty("ok",ok); ack->setProperty("requestId",args.getProperty("requestId",juce::var())); @@ -6476,6 +6533,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(!nativeShowBusy_&&!studioBackupBusy_&&!engine_.isGraphSwitchPending()) { armix::mixer::LiveChannelFxGraph::InstanceLease owner; std::uint64_t retainedEpoch=epoch; + std::uint64_t retainedRevision=revision,nativeChannel=0; + bool nativeTarget=false; const auto nativeId=args.getProperty("channelId",{}); if(!nativeId.isVoid()) { std::uint64_t id=0,ep=0,rev=0; @@ -6486,16 +6545,71 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr owner=engine_.leaseNativeVst3Editor(ep,rev, armix::mixer::ChannelId{id},static_cast(slot),token); retainedEpoch=ep; + retainedRevision=rev; + nativeChannel=id; + nativeTarget=static_cast(owner); } } else owner=engine_.leaseRoutedFxForEditor(lane,slot,epoch,revision,token); if(owner && owner->processor) { - try { + // A second click must raise an already open OR hidden + // editor for exactly this accepted instance. Do not + // destroy/recreate JUCE's active editor on every click. + if(editorWindow_ && routedEditorOwner_==owner && + routedEditorEpoch_==retainedEpoch && + editorProcessor_==owner->processor.get()) { + editorWindow_->present(); + opened=true; + error.clear(); + } else try { closePluginEditor(); if(auto* editor=owner->processor->createEditorIfNeeded()) { +#if defined(ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT + if(auto* imer=dynamic_cast< + armix::builtin_fx::ImerSipP92Editor*>(editor)) { + // Exact retained processor identity is + // authoritative. Resolve CURRENT published + // PCM revision at each click, not the revision + // cached when the floating editor opened. + // Read all three independent bypass gates so + // global mixer A/B also mutes this editor. + auto held=owner; + const auto readPower=[this,held,nativeTarget, + nativeChannel,lane,slot,token] { + const auto current=nativeTarget? + engine_.retainedNativeFxPower( + held,armix::mixer::ChannelId{nativeChannel}, + static_cast(slot),token): + engine_.retainedRoutedFxPower( + held,lane,slot,token); + armix::builtin_fx::ImerSipP92Editor::HostBypassState state; + state.valid=current.valid; + state.slotBypassed=current.slotBypassed; + state.rackBypassed=current.rackBypassed; + state.globalBypassed=current.globalBypassed; + return state; + }; + imer->bindHostPower( + [this,held,nativeTarget,nativeChannel, + lane,slot,token](bool bypass) { + const bool applied=nativeTarget? + engine_.bypassRetainedNativeFx( + held,armix::mixer::ChannelId{nativeChannel}, + static_cast(slot), + token,bypass): + engine_.bypassRetainedRoutedFx( + held,lane,slot,token,bypass); + if(applied)emitApprovedNativeSnapshot(); + else emitNotice( + "FX Power rejected: accepted graph or instance changed",true); + return applied; + },readPower); + } +#endif routedEditorOwner_=owner; routedEditorEpoch_=retainedEpoch; editorWindow_=std::make_unique( - owner->processor->getName(),editor); + owner->processor->getName(),editor,*this); + editorProcessor_=owner->processor.get(); opened=true; error.clear(); } else error="This VST3 has no native editor"; @@ -7356,14 +7470,31 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Never open an editor for an old graph waiting to be destroyed. if (engine_.isGraphSwitchPending()) return emitNotice ("FX recall is transitioning; open the editor after recall completes.", true); - closePluginEditor(); if (auto* processor = engine_.pluginAt (slot)) { - if (auto* editor = processor->createEditorIfNeeded()) - editorWindow_ = std::make_unique ( - processor->getName(), editor); + if (editorWindow_ && !routedEditorOwner_ && + editorProcessor_ == processor) + { + editorWindow_->present(); // repeated FX Rack click + } else - emitNotice ("This VST3 does not expose a graphical editor.", true); + { + closePluginEditor(); + if (auto* editor = processor->createEditorIfNeeded()) + { + editorWindow_ = std::make_unique ( + processor->getName(), editor, *this); + editorProcessor_=processor; + } + else + emitNotice ("This VST3 does not expose a graphical editor.", true); + } + } + else + { + // The requested slot no longer owns a processor. Never + // leave a floating editor bound to a retired plugin. + closePluginEditor(); } } else if (action == "monitor" && value.isBool()) diff --git a/src/NativeBuiltInFx.h b/src/NativeBuiltInFx.h index 1e98f0a51..1dc3ebcba 100644 --- a/src/NativeBuiltInFx.h +++ b/src/NativeBuiltInFx.h @@ -7,6 +7,9 @@ #include "../engine/builtin_fx/VocalThrowProcessor.h" #include "../engine/builtin_fx/GuitarRigEditor.h" #include "../engine/builtin_fx/SonKuSpatialProcessor.h" +#if defined(ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT +#include "../engine/builtin_fx/ImerSipP92Processor.h" +#endif #include "../engine/core/PreparedMixerBlock.h" #include #include @@ -83,6 +86,16 @@ inline constexpr std::array nativeBuiltInFx{ "NATIVE_SONKU_UNSUPPORTED_AUDIO_FORMAT","NATIVE_SONKU_PREPARE_REJECTED", "NATIVE_SONKU_PREPARE_EXCEPTION","Saved 8D-SonKu state rejected; graph unchanged", prepareNativeBuiltInFx}, +#if defined(ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT) && ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT + // Separate product/slot identity, SAME P9.1/P9.2 native PCM engine. + NativeBuiltInFx{ImerSipP92Processor::catalogIdentity, + ImerSipP92Processor::productDisplayName,"Spatial",true,44100.,48000., + "NATIVE_IMERSIP_HOST_UNAVAILABLE","NATIVE_IMERSIP_DEVICE_CHANGED", + "NATIVE_IMERSIP_UNSUPPORTED_AUDIO_FORMAT","NATIVE_IMERSIP_PREPARE_REJECTED", + "NATIVE_IMERSIP_PREPARE_EXCEPTION", + "Saved ImmerSIB IMRS state rejected; graph unchanged", + prepareNativeBuiltInFx}, +#endif NativeBuiltInFx{GuitarRigProcessor::catalogIdentity,"Guitar FX Rig","Guitar",true,32000.,192000., "NATIVE_GFX_HOST_UNAVAILABLE","NATIVE_GFX_DEVICE_CHANGED", "NATIVE_GFX_UNSUPPORTED_AUDIO_FORMAT","NATIVE_GFX_PREPARE_REJECTED", diff --git a/src/NativeFxWin32Owner.h b/src/NativeFxWin32Owner.h new file mode 100644 index 000000000..acd4bd2a3 --- /dev/null +++ b/src/NativeFxWin32Owner.h @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#if defined(_WIN32) +#include +#include + +namespace armix::ui::win32 { +// Native Windows caption colour is OS-owned. Prefer its supported dark +// presentation to match the mixer; unsupported Windows versions are benign. +// The plugin remains an ordinary non-topmost document window. +inline void preferDarkTitleBar(HWND hwnd) noexcept { + if(!hwnd || !::IsWindow(hwnd))return; + const BOOL dark=TRUE; + constexpr DWORD modernAttribute=20; // DWMWA_USE_IMMERSIVE_DARK_MODE + const auto hr=::DwmSetWindowAttribute(hwnd,modernAttribute,&dark,sizeof(dark)); + if(FAILED(hr)) { + constexpr DWORD olderAttribute=19; // Earlier Windows 10 preview API + (void)::DwmSetWindowAttribute(hwnd,olderAttribute,&dark,sizeof(dark)); + } +} +// UI thread only. GWLP_HWNDPARENT means owner for top-level WS_POPUP/ +// WS_OVERLAPPED windows. Do NOT SetParent(), create WS_CHILD, or set TOPMOST. +inline bool attachOwnedPopup(HWND popup, HWND owner) noexcept { + if (popup == nullptr || owner == nullptr || popup == owner || + !::IsWindow(popup) || !::IsWindow(owner) || + (::GetWindowLongPtrW(popup,GWL_STYLE) & WS_CHILD) != 0) + return false; + if (::GetWindow(popup,GW_OWNER)==owner) return true; + ::SetLastError(0); + const auto previous=::SetWindowLongPtrW( + popup,GWLP_HWNDPARENT,reinterpret_cast(owner)); + if (previous==0 && ::GetLastError()!=0) return false; + return ::GetWindow(popup,GW_OWNER)==owner; +} +} // namespace armix::ui::win32 +#endif diff --git a/src/NativeOwnedFloatingWindow.h b/src/NativeOwnedFloatingWindow.h new file mode 100644 index 000000000..b6d89eaa2 --- /dev/null +++ b/src/NativeOwnedFloatingWindow.h @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include "NativeFxWin32Owner.h" + +namespace armix::ui { +// UI/message-thread only. An HWND owner keeps plugin windows above the mixer +// without making them system-wide topmost or child components of WebView2. +inline bool attachOwnedFloatingWindow(juce::Component& floating, + juce::Component& mixer) noexcept { +#if defined(_WIN32) + const auto* popupPeer=floating.getPeer(); + const auto* mixerPeer=mixer.getPeer(); + if(popupPeer==nullptr || mixerPeer==nullptr)return false; + const auto child=static_cast(popupPeer->getNativeHandle()); + const auto owner=static_cast(mixerPeer->getNativeHandle()); + const bool attached=win32::attachOwnedPopup(child,owner); + win32::preferDarkTitleBar(child); + return attached; +#else + (void)floating; + (void)mixer; + return true; // Native non-Windows foreground policy remains JUCE-owned. +#endif +} +} // namespace armix::ui diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 5a87e39dd..764f0be92 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1475,6 +1475,8 @@ test("P0 native FX rack and per-slot readback update mounted strip without repla vm.runInNewContext(read("web/approved-native-bridge.js"), {window:win,document:doc,performance:{now:()=>0},console},{timeout:1500}); const base=acceptedFixture(); + // Production approvedNativeSnapshot publishes this PCM scalar, not CSS. + base.globalFxBypassed=false; base.graph.channels[0].fxRackBypassed=false; base.graph.channels[0].inserts=[ {id:"vst-live-1",catalogId:"eq-a",name:"EQ",bypassed:false}, @@ -1528,7 +1530,21 @@ test("P0 native FX rack and per-slot readback update mounted strip without repla assert.equal(track.fxOn,true); assert.deepEqual(rows.map(r=>r.power.getAttribute("aria-pressed")),["true","false"]); assert.deepEqual(rows.map(r=>r.dataset.fxEffective),["true","false"]); - const individual=clone(restored); + // One PCM global A/B overrides every displayed FX power without + // changing either remembered individual bypass preference or DOM nodes. + const allBypassed=clone(restored); + allBypassed.globalFxBypassed=true; + listeners.get("arMixConsoleSnapshot")(allBypassed); + assert.equal(paints,1,"global FX is a scalar, not a graph rebuild"); + assert.deepEqual(rows.map(r=>r.dataset.fxEffective),["false","false"]); + assert.deepEqual(rows.map(r=>r.power.getAttribute("aria-pressed")),["false","false"]); + assert.deepEqual(Array.from(track.slotBypass.slice(0,2)),[false,true]); + const restoredGlobal=clone(allBypassed); + restoredGlobal.globalFxBypassed=false; + listeners.get("arMixConsoleSnapshot")(restoredGlobal); + assert.equal(paints,1); + assert.deepEqual(rows.map(r=>r.dataset.fxEffective),["true","false"]); + const individual=clone(restoredGlobal); individual.graph.channels[0].inserts[0].bypassed=true; listeners.get("arMixConsoleSnapshot")(individual); assert.equal(paints,1,"slot power is a realtime scalar, not a topology edit"); @@ -1897,8 +1913,17 @@ test("native vendor editor retention follows current PCM ownership, not inactive assert.match(main,/routedEditorEpoch_=retainedEpoch/); assert.match(main,/retainedEpoch=ep/); assert.match(lab,/nativeAccepted_\.fxOwners->retainsEditor\(owner\)/); - const editor=main.slice(main.indexOf('if(owner && owner->processor)'),main.indexOf('if(owner && owner->processor)')+700); - assert.ok(editor.indexOf('closePluginEditor();')processor)'); + assert.ok(start>=0,'routed FX editor source must exist'); + const editor=main.slice(start,main.indexOf('catch(const std::exception& ex)',start)); + assert.ok(editor.includes('routedEditorOwner_==owner'), + 'reopen only exact current accepted PCM owner'); + assert.ok(editor.includes('editorWindow_->present()'), + 'same FX instance must be focused instead of recreated'); + const fresh=editor.slice(editor.indexOf('} else try {')); + assert.ok(fresh.includes('closePluginEditor();') && + fresh.indexOf('closePluginEditor();')",scene) + self.assertIn('"Royal Concert Hall"',scene) + self.assertIn('"Arena Thunder"',scene) + self.assertIn('"Front Row Power"',scene) + self.assertIn('"Symphonic Palace"',scene) + self.assertIn('"Velvet Cinema"',scene) + ui=source("engine/builtin_fx/ImerSipP92Editor.h") + self.assertIn("ImerSipP92VisualSkin",ui) + self.assertNotIn("imersipP92ConcertBoxes(",ui) + self.assertNotIn("skin_.drawRoom(g)",ui) + self.assertIn("skin_.drawPanel(g)",ui) + self.assertIn("skin_.drawScene(g,visualSceneId_)",ui) + self.assertIn("if(preset!=1)visualSceneId_=preset",ui) + self.assertIn("visualSceneId_=id",ui) + self.assertNotIn("L / WORLD PA",ui) + self.assertNotIn("LIVE CONCERT WORLD",ui) + self.assertNotIn("skin_.drawHeader(g)",ui) + for label in ("PRESET","ROOM","DISTANCE","MASTER GAIN"): + self.assertIn(label,ui) + # Header/footer close chrome is owned by the native plugin window. + self.assertNotIn("SPATIAL CONCERT MONITOR",ui) + self.assertNotIn('g.fillRect(0,0,1100,68)',ui) + self.assertNotIn('close_.setButtonText',ui) + self.assertNotIn("close_",ui) + # Host state is the only authority for the native power glyph. + self.assertIn('power_.setButtonText({})',ui) + self.assertIn('power_.setToggleState(valid && !bypassed',ui) + # The bypass UI is strictly host-readback derived, never click + # optimistic. JUCE paints the veil *after* child controls and + # cuts a hole around the native power icon, leaving it actionable. + self.assertIn("struct HostBypassState final",ui) + self.assertIn("slotBypassed || rackBypassed || globalBypassed",ui) + self.assertIn("state.effectiveBypassed()",ui) + self.assertIn("!state.rackBypassed && !state.globalBypassed",ui) + self.assertIn("synchronizeHostPower()",ui) + host=source("src/Main.cpp") + self.assertIn("engine_.bypassRetainedNativeFx(",host) + self.assertIn("engine_.bypassRetainedRoutedFx(",host) + self.assertIn("engine_.retainedNativeFxPower(",host) + self.assertIn("engine_.retainedRoutedFxPower(",host) + self.assertIn("synchronizeOpenImmerSIBPower()",host) + lab=source("src/LiveDryRoutingLab.h") + self.assertIn("retainedNativeFxPower(",lab) + self.assertIn("retainedRoutedFxPower(",lab) + self.assertIn("nativeAccepted_.pcmRevision,id,slot,token,bypass",lab) + self.assertIn("globalFxBypassed()",lab) + self.assertIn("rackBypassed(id)",lab) + bridge=source("web/approved-native-bridge.js") + self.assertIn("paintNativeFxPowerReadback(ch,t,globalFxBypassed)",bridge) + self.assertIn("const globalEnabled=!globalFxBypassed",bridge) + self.assertIn("paintNativeFxPowerReadback(ch,t,next.raw?.globalFxBypassed)",bridge) + self.assertNotIn("const globalEnabled=document.querySelector",bridge) + self.assertIn("live->get()!=held.get()",lab) + native=source("tests/imersip_p92_native_test.cpp") + self.assertIn("globalBypassed=true",native) + self.assertIn("rackBypassed=true",native) + self.assertIn("hostAvailable=false",native) + self.assertIn("acceptPower=false",native) + self.assertIn("std::optional hostBypassed_",ui) + self.assertIn("hostBypassed_=bypassed",ui) + self.assertIn("if(changed)repaint()",ui) + self.assertIn("paintOverChildren(juce::Graphics& g) override",ui) + self.assertIn("g.excludeClipRegion(power_.getBounds())",ui) + self.assertIn("skin_.drawBypassedVenueOverlay(g)",ui) + skin=source("engine/builtin_fx/ImerSipP92VisualSkin.h") + native=source("tests/imersip_p92_native_test.cpp") + self.assertIn('g.drawText("BYPASSED"',skin) + self.assertIn("juce::FontOptions(76.f,juce::Font::bold)",skin) + self.assertIn("font.setExtraKerningFactor(0.055f)",skin) + self.assertIn("juce::Colour(0xb803060a)",skin) + self.assertIn("juce::Colour(0x7603060a)",ui) + self.assertIn("sceneMutedEnergy*100=15)",native) + self.assertIn("assert(stageDarker>=24)",native) + self.assertIn("assert(amberLetters>=380 && amberRows>=36)",native) + self.assertIn("assert(panelMutedEnergy*100",catalog) + self.assertIn("ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT",catalog) + def test_legacy_and_host_power_are_realtime_owned(self): + p=source("engine/builtin_fx/ImerSipP92Processor.h") + ui=source("engine/builtin_fx/ImerSipP92Editor.h") + host=source("src/Main.cpp") + self.assertIn("restoreUnpublishedState",p) + self.assertIn("out.writeInt(6)",p) + self.assertIn("SonKuSpatialProcessor::getStateInformation",p) + self.assertIn("SonKuSpatialProcessor::queueSettings",p) + self.assertIn("ImerSipP92Editor*>(editor)",host) + self.assertIn("ImerSipP92Processor*>(p)",host) + self.assertIn("admitQueuedScene",source( + "engine/builtin_fx/SonKuSpatialProcessor.h")) + self.assertIn("engine_.bypassNativeVst3(",host) + self.assertIn("engine_.setDryRoutingLabFxBypass(",host) + self.assertIn("power_.setEnabled(false)",ui) + self.assertIn("fx_.lastCompletedRequestId()",ui) + def test_no_shadow_fx_in_public_build(self): + cmake=source("CMakeLists.txt") + self.assertIn("ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT",cmake) + self.assertIn("ARMixImerSipP92NativeTests",cmake) + +if __name__=="__main__": unittest.main() diff --git a/tests/imersip_p92_factory_music_test.cpp b/tests/imersip_p92_factory_music_test.cpp new file mode 100644 index 000000000..1be0607e8 --- /dev/null +++ b/tests/imersip_p92_factory_music_test.cpp @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Product preset audition probes using the *unchanged* P9.1/P9.2 PCM core. +// Tests evidence; neither synthetic signals nor sample RMS proves luxury. +#if defined(NDEBUG) +#undef NDEBUG +#endif +#if !defined(SONKU_P90_TRUE_EXTERNAL_RESEARCH) || !SONKU_P90_TRUE_EXTERNAL_RESEARCH +#error ImerSip P9.2 audition needs the real P9 DSP switch +#endif +#include "../engine/builtin_fx/ImerSipP92Scene.h" +#include +#include +#include +#include +#include +#include +#include + +using namespace armix::sonku; +using armix::builtin_fx::imersipP92Factory; +using armix::builtin_fx::imersipP92ReferenceScene; +using armix::builtin_fx::validImerSipP92Scene; +using Stereo=std::array,2>; +constexpr double pi=3.1415926535897932384626433832795; +constexpr int frames=32768; +constexpr int skip=8192; +enum class Material { Musical, AntiPhase }; + +static Stereo source(int rate,Material material){ + Stereo p{std::vector(frames),std::vector(frames)}; + for(int i=0;i( + .14*std::sin(2*pi*83*t)+.055*std::sin(2*pi*1703*t)); + p[0][i]=s;p[1][i]=-s; + } else { + const float mid=static_cast( + .092*std::sin(2*pi*83*t)+ + .073*std::sin(2*pi*116*t)+ + .065*std::sin(2*pi*371*t)+ + .035*std::sin(2*pi*1900*t)+ + .026*std::sin(2*pi*8500*t)); + const float side=static_cast( + .048*std::sin(2*pi*520*t)+ + .025*std::sin(2*pi*3120*t)); + p[0][i]=mid+side; + p[1][i]=mid-side; + } + } + return p; +} +static Stereo render(int rate,const Settings& scene,Stereo data){ + auto dsp=std::make_unique(); + assert(dsp->prepare(rate,SonKuReflectionProfile::SixSurfaceKemarResearch)); + assert(validImerSipP92Scene(scene)); + assert(dsp->setSettings(scene)); + for(int i=0;iprocess(data[0].data()+i,data[1].data()+i,128); + for(int ear=0;ear<2;++ear) + for(const float s:data[ear])assert(std::isfinite(s)&&std::abs(s)<.981f); + return data; +} +static double energy(const Stereo& p,bool side=false){ + double total=0.; + for(int i=skip;i=1 && s.spacePreset<=3); + const auto heard=render(rate,s,raw); + const double ratio=std::sqrt(energy(heard)/original); + const double side=energy(heard,true); + auto silenceRoom=s; + silenceRoom.roomAmount=0.f; + silenceRoom.ambience=0.f; + const auto withoutRoom=render(rate,silenceRoom,raw); + const double roomDelta=std::sqrt( + nullDelta(heard,withoutRoom)/energy(heard)); + const auto antiWet=render(rate,s,anti); + const double antiRatio=std::sqrt(energy(antiWet)/energy(anti)); + const double antiSide=std::sqrt(energy(antiWet,true)/ + energy(anti,true)); + std::printf("IMERSIP_FACTORY_METRIC,rate=%d,id=%d," + "rmsVsSource=%.4f,rmsVsNeutral=%.4f," + "roomDelta=%.4f,stereoSideEnergy=%.5f," + "antiphaseRms=%.4f,antiphaseSide=%.4f\n", + rate,id,ratio,ratio/neutralRms,roomDelta,side, + antiRatio,antiSide); + assert(std::isfinite(ratio)&&std::isfinite(roomDelta)); + assert(side>1.e-5); + assert(antiRatio>.08 && antiSide>.08); // catastrophic null veto + if(id>=2 && id<=7){ + assert(s.sourceDistanceMeters>=1.6f); // front row is intentionally near + assert(s.outputTrim>1.f); + // A richer room must produce an actual, measurable wet PCM + // difference, not just turn up a headphone-locked dry signal. + assert(roomDelta>.045); + // Factory candidates must not be quieter than selected P9 + // neutral. Mastered material is handled by the linked guard. + assert(ratio>neutralRms*1.05); + } + if(id!=2){ + // New named scenes may not collapse into identical DSP + // settings or a weaker version of the owner's Live Concert. + assert(nullDelta(heard,liveRendered)>.001); + assert(ratio>liveRms*.90); // reject another weak renamed preset + } + if(id==5){ + assert(std::abs(s.stereoSpreadDegrees-150.f)<1.e-4f); + assert(std::abs(s.sourceDistanceMeters-1.6f)<1.e-4f); + assert(std::abs(s.ambience-.97f)<1.e-4f); + } + if(id==7)assert(s.spacePreset==2); + assert(s.outputTrim<=armix::builtin_fx::imersipP92DbToLinear(6.f)); + } +} +int main(){ + verify(44100); + verify(48000); + std::puts("PASS IMERSIP RICH SCENES: six live/room presets, phase, wet/dry, internal neutral-only guard"); +} diff --git a/tests/imersip_p92_native_test.cpp b/tests/imersip_p92_native_test.cpp new file mode 100644 index 000000000..773f06cd2 --- /dev/null +++ b/tests/imersip_p92_native_test.cpp @@ -0,0 +1,648 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#if defined(NDEBUG) +#undef NDEBUG +#endif +#if !defined(ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT) || !ARMIX_SONKU_EXPERIMENTAL_P90_NATIVE_RT +#error ImerSip P9.2 native test requires explicit P9 experimental research +#endif +#include "../engine/builtin_fx/ImerSipP92Processor.h" +#include +#include +#include +#include +#include +#include +#include +#include + +using armix::builtin_fx::ImerSipP92Processor; +using armix::builtin_fx::imersipP92ReferenceScene; +using armix::builtin_fx::imersipP92Factory; +using armix::sonku::SonKuSpatialCore; +constexpr double pi=3.14159265358979323846; + +static juce::MemoryBlock oldImrsV5() { + juce::MemoryBlock bytes; + { + juce::MemoryOutputStream out(bytes,false); + out.writeInt(0x494D5253);out.writeInt(5); + out.writeInt(0); // original concert + out.writeFloat(.88f);out.writeFloat(.78f); + out.writeFloat(.67f);out.writeFloat(.70f); + out.writeFloat(1.f);out.writeFloat(.60f); + out.writeFloat(1.f);out.writeFloat(.25f); + out.writeFloat(.78f);out.writeFloat(0.f); + } + assert(bytes.getSize()==52); + return bytes; +} + +static void nativeParity(int rate) { + auto fx=std::make_unique(); + assert(fx->getName()=="ImmerSIB"); + assert(juce::String(ImerSipP92Processor::catalogIdentity)== + "armix.builtin.imersip.v1"); + fx->prepareToPlay(static_cast(rate),128); + assert(fx->isReady()); + const auto reference=imersipP92Factory(2); + // Reference has NO selectable preset ID. ID 6 is now Symphonic Palace. + const auto neutral=imersipP92ReferenceScene(); + assert(armix::builtin_fx::validImerSipP92Scene(reference)); + assert(armix::builtin_fx::validImerSipP92Scene(neutral)); + const auto actual=fx->acceptedSettings(); + assert(actual.renderMode==9&&!actual.moving); + assert(actual.spacePreset==3); +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + assert(std::abs(actual.stereoSpreadDegrees-112.f)<.001f); + assert(std::abs(actual.sourceDistanceMeters-3.f)<.001f); + assert(actual.roomAmount==1.36f && actual.ambience==.84f); + assert(actual.outputTrim==1.8f && actual.sceneVoicing==4); +#else + assert(std::abs(actual.stereoSpreadDegrees-150.f)<.001f); + assert(std::abs(actual.sourceDistanceMeters-2.2f)<.001f); + assert(std::abs(actual.roomAmount-1.f)<.001f); + assert(std::abs(actual.ambience-.91f)<.001f); + assert(std::abs(actual.outputTrim- + armix::builtin_fx::imersipP92DbToLinear(4.8f))<.001f); +#endif + assert(std::abs(neutral.stereoSpreadDegrees-82.f)<.001f); + assert(std::abs(neutral.ambience-.33f)<.001f); + assert(std::abs(neutral.outputTrim-1.f)<.001f); + assert(!actual.musicCompatibleLowFrequency); + + auto native=std::make_unique(); + assert(native->prepare(rate, + armix::sonku::SonKuReflectionProfile::SixSurfaceKemarResearch)); + assert(native->setSettings(reference)); + + juce::MidiBuffer midi; + juce::AudioBuffer pcm(2,128); + float left[128]{},right[128]{}; + double dryEnergy=0.,changeEnergy=0.,stereoEnergy=0.; + for(int block=0;block<256;++block){ + for(int i=0;i<128;++i) { + const double t=(block*128+i)/static_cast(rate); + const float mid=static_cast( + .15*std::sin(2*pi*311*t)+ + .060*std::sin(2*pi*1130*t)+ + .045*std::sin(2*pi*8250*t)); + const float side=static_cast( + .075*std::sin(2*pi*633*t)+.04*std::sin(2*pi*3200*t)); + left[i]=mid+side;right[i]=mid-side; + pcm.setSample(0,i,left[i]);pcm.setSample(1,i,right[i]); + } + native->process(left,right,128); + fx->processBlock(pcm,midi); + for(int i=0;i<128;++i){ + const float l=pcm.getSample(0,i),r=pcm.getSample(1,i); + assert(std::isfinite(l)&&std::isfinite(r)); + // EXACT same P9.2 native callback, no second ImerSip DSP. + assert(std::abs(l-left[i])<2.e-6f); + assert(std::abs(r-right[i])<2.e-6f); + if(block<32)continue; // settle measured KEMAR/room histories + const double t=(block*128+i)/static_cast(rate); + const double m=.15*std::sin(2*pi*311*t)+ + .060*std::sin(2*pi*1130*t)+ + .045*std::sin(2*pi*8250*t); + const double s=.075*std::sin(2*pi*633*t)+ + .04*std::sin(2*pi*3200*t); + const double dryL=m+s,dryR=m-s; + dryEnergy+=dryL*dryL+dryR*dryR; + changeEnergy+=(l-dryL)*(l-dryL)+(r-dryR)*(r-dryR); + stereoEnergy+=(l-r)*(l-r); + } + } + const double delta=std::sqrt(changeEnergy/(dryEnergy+1.e-15)); + std::fprintf(stderr, + "IMERSIP_P92_NATIVE_PARITY rate=%d delta=%.6f stereo=%.4f\n", + rate,delta,stereoEnergy); + assert(delta>.05 && stereoEnergy>.01); + + // v6 IMRS wraps native SONK v11, not an invented shadow DSP schema. + juce::MemoryBlock state; + fx->getStateInformation(state); +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + assert(state.getSize()==75); +#else + assert(state.getSize()==71); +#endif + auto restored=std::make_unique(); + restored->prepareToPlay(rate,128); + assert(restored->restoreUnpublishedState(state.getData(), + static_cast(state.getSize()))); + assert(restored->acceptedSettings().renderMode==9); + assert(restored->acceptedSettings().stereoSpreadDegrees== + reference.stereoSpreadDegrees); +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + assert(restored->acceptedSettings().sceneVoicing==4); + // Existing IMRS v7 shows saved at 10m are admitted with a nearfield + // distance migration, but preserve voicing, early room, and gain. + auto farState=state; + const float farDistance=10.f; + std::memcpy(static_cast(farState.getData())+42, + &farDistance,sizeof(farDistance)); // SONK v12 distance + auto migratedFar=std::make_unique(); + migratedFar->prepareToPlay(rate,128); + assert(migratedFar->restoreUnpublishedState( + farState.getData(),static_cast(farState.getSize()))); + assert(migratedFar->acceptedSettings().sourceDistanceMeters==4.f); + assert(migratedFar->acceptedSettings().sceneVoicing==4); + assert(migratedFar->acceptedSettings().roomAmount==1.36f); + migratedFar->releaseResources(); + // Compatibility proof: an old IMRS v6 carries SONK v11 exactly + // (63 bytes, no sceneVoicing). Restore it in the P9.8 engine as 0. + juce::MemoryBlock oldV6; + { + juce::MemoryOutputStream wire(oldV6,false); + wire.writeInt(0x494D5253);wire.writeInt(6); + wire.writeInt(0x534F4E4B);wire.writeInt(11); + wire.write(static_cast(state.getData())+16,55); + } + assert(oldV6.getSize()==71); + auto migratedV6=std::make_unique(); + migratedV6->prepareToPlay(rate,128); + assert(migratedV6->restoreUnpublishedState( + oldV6.getData(),static_cast(oldV6.getSize()))); + assert(migratedV6->acceptedSettings().sceneVoicing==0); + assert(migratedV6->acceptedSettings().sourceDistanceMeters<=4.f); + assert(migratedV6->acceptedSettings().stereoSpreadDegrees== + reference.stereoSpreadDegrees); + migratedV6->releaseResources(); +#endif + + // The embedded v11 SONK mode field is at byte 50 of its 63-byte + // record (after the 8-byte IMRS header). Corrupting P9 -> P8.2 mode + // must fail BEFORE modifying a prepared FX's accepted PCM scene. + auto wrongMode=state; + auto* wrongBytes=static_cast(wrongMode.getData()); + assert(wrongBytes[8+50]==9); + wrongBytes[8+50]=0; + assert(!restored->restoreUnpublishedState( + wrongMode.getData(),static_cast(wrongMode.getSize()))); + assert(restored->acceptedSettings().renderMode==9); + auto movingWorld=state; + auto* movingBytes=static_cast(movingWorld.getData()); + movingBytes[8+28]=1; // dynamic orbit not allowed by ImerSip's scene + assert(!restored->restoreUnpublishedState( + movingWorld.getData(),static_cast(movingWorld.getSize()))); + assert(restored->acceptedSettings().renderMode==9); + + // Original IMRS 52-byte v5 restores without silently launching P8 DSP. + auto old=oldImrsV5(); + auto legacy=std::make_unique(); + legacy->prepareToPlay(rate,128); + assert(legacy->restoreUnpublishedState(old.getData(), + static_cast(old.getSize()))); + const auto migrated=legacy->acceptedSettings(); + assert(migrated.renderMode==9 && !migrated.moving); + assert(std::abs(migrated.stereoSpreadDegrees-130.5f)<.01f); + assert(migrated.spacePreset==3); + // Exercise the *virtual JUCE* restoration path as well as registry + // restore. A base-class SONK parser must not swallow ImerSip IMRS. + auto viaJuce=std::make_unique(); + viaJuce->prepareToPlay(rate,128); + juce::AudioProcessor& conventionalHost=*viaJuce; + conventionalHost.setStateInformation( + old.getData(),static_cast(old.getSize())); + assert(std::abs(viaJuce->acceptedSettings().stereoSpreadDegrees- + 130.5f)<.01f); + auto corrupt=old; + corrupt.getData(); // corrupted byte count must reject before mutation + auto invalid=std::make_unique(); + invalid->prepareToPlay(rate,128); + assert(!invalid->restoreUnpublishedState(corrupt.getData(),51)); + + // Edits travel through the SAME native callback and audio ACK. + auto changed=fx->acceptedSettings(); + changed.stereoSpreadDegrees=100.f; + assert(fx->queueSettings(changed,72)); + assert(fx->acceptedSettings().stereoSpreadDegrees== + reference.stereoSpreadDegrees); + pcm.clear(); + fx->processBlock(pcm,midi); + armix::builtin_fx::SonKuSpatialProcessor::Completion ack{}; + assert(fx->pollCompletion(ack)); + assert(ack.requestId==72 && ack.applied); + assert(std::abs(fx->acceptedSettings().stereoSpreadDegrees-100.f)<.01f); + assert(fx->stateSnapshotQuiescent()); + + // Even when the caller holds the SonKu BASE pointer, its public + // settings queue must not admit an old MusicBed or orbit mode into + // an ImerSip world-speaker insert. + armix::builtin_fx::SonKuSpatialProcessor& baseControl=*fx; + auto wrongP8=fx->acceptedSettings(); + wrongP8.renderMode=0; + assert(!baseControl.queueSettings(wrongP8,73)); + auto wrongOrbit=fx->acceptedSettings(); + wrongOrbit.moving=true; + assert(!baseControl.queueSettings(wrongOrbit,74)); + assert(fx->stateSnapshotQuiescent()); + + fx->releaseResources(); + restored->releaseResources(); + legacy->releaseResources(); + viaJuce->releaseResources(); + invalid->releaseResources(); +} +int main() { + juce::ScopedJuceInitialiser_GUI gui; + auto editorFx=std::make_unique(); + editorFx->prepareToPlay(48000.,128); + std::unique_ptr editor(editorFx->createEditor()); + assert(editor && editor->findChildWithID("imersip.preset")); + assert(editor->getWidth()==935 && editor->getHeight()==578); + auto* visualEditor=dynamic_cast(editor.get()); + assert(visualEditor && visualEditor->areVisualAssetsReady()); + + // Actual compact native JUCE hit bounds: no overlapping controls, + // labels/text remain independent from the background PNG scene. + const char* controlIds[]={"imersip.preset","imersip.room", + "imersip.stage","imersip.distance","imersip.early", + "imersip.late","imersip.mix","imersip.gain", + "imersip.align","imersip.yaw","imersip.power"}; + std::array controls{}; + for(std::size_t i=0;ifindChildWithID(controlIds[i]); + assert(controls[i]); + const auto r=controls[i]->getBounds(); + assert(!r.isEmpty()); + assert(editor->getLocalBounds().contains(r)); + for(std::size_t j=0;jgetBounds())); + } + // The native OS close control replaces the redundant in-editor CLOSE. + assert(editor->findChildWithID("imersip.close")==nullptr); + const auto powerBounds=controls[10]->getBounds(); + const auto gainBounds=controls[7]->getBounds(); + assert(powerBounds.getY()>=juce::roundToInt(461.f*.85f)); + assert(powerBounds.getRight()>gainBounds.getRight()); + assert(powerBounds.getX()>gainBounds.getRight()); + assert(powerBounds.getY()( + editor->findChildWithID("imersip.label.distance")); + assert(distanceLabel && distanceLabel->getText()=="DISTANCE"); + auto* masterLabel=dynamic_cast( + editor->findChildWithID("imersip.label.gain")); + assert(masterLabel && masterLabel->getText()=="MASTER GAIN"); + assert(masterLabel->getX()getBounds(); + const auto b=controls[3]->getBounds(); + const auto c=controls[4]->getBounds(); + assert(a.getY()==b.getY() && c.getY()>a.getY()); + assert(a.getX()=200); + + // The rejected synthetic-speaker positioning engine was deleted. + // Test the CURRENT rendering contract instead: full-range UI values + // must keep the actual photo venue and controls inside the editor. + // No audio edit is enqueued by these display-only extreme probes. + auto* stageProbe=dynamic_cast( + editor->findChildWithID("imersip.stage")); + auto* distanceProbe=dynamic_cast( + editor->findChildWithID("imersip.distance")); + assert(stageProbe && distanceProbe); + const auto priorStage=stageProbe->getValue(); + const auto priorDistance=distanceProbe->getValue(); + for(const double angle:{stageProbe->getMinimum(),stageProbe->getMaximum()}){ + for(const double metres:{distanceProbe->getMinimum(), + distanceProbe->getMaximum()}){ + stageProbe->setValue(angle,juce::dontSendNotification); + distanceProbe->setValue(metres,juce::dontSendNotification); + const auto extreme=editor->createComponentSnapshot( + editor->getLocalBounds()); + assert(extreme.isValid() && extreme.getWidth()==935 && + extreme.getHeight()==578); + for(auto* child:controls) + assert(editor->getLocalBounds().contains(child->getBounds())); + } + } + stageProbe->setValue(priorStage,juce::dontSendNotification); + distanceProbe->setValue(priorDistance,juce::dontSendNotification); + auto visual=editor->createComponentSnapshot(editor->getLocalBounds()); + assert(visual.isValid() && visual.getWidth()==935 && + visual.getHeight()==578); + assert(visual.getPixelAt(480,120)!=visual.getPixelAt(480,484)); + // Genuine native JUCE component snapshots, not an HTML or design mock. + // Render all requested Windows framebuffer density ratios while retaining + // the original 1100x680 logical hit-testing and parameter geometry. + for(const auto dpi : {100,125,150,200}) { + const float scale=static_cast(dpi)/100.f; + // JUCE 8.0.15 provides a first-class scale-aware snapshot API. + // paintEntireComponent() into a manually transformed offscreen + // Graphics can produce blank/incorrect images on Windows headless + // runners even when createComponentSnapshot() passes above. + // Keep the strict non-blank/opaque assertions below. + auto frame=editor->createComponentSnapshot( + editor->getLocalBounds(),true,scale); + assert(frame.isValid() && + frame.getWidth()==juce::roundToInt(935.f*scale) && + frame.getHeight()==juce::roundToInt(578.f*scale)); + // A single pixel comparison can falsely fail when two dark metal + // points happen to have the same RGBA. Validate a distributed sample + // of the REAL native pixel buffer instead, and still reject blank art. + const auto first=frame.getPixelAt(frame.getWidth()/10, + frame.getHeight()/10); + int distinct=0,opaque=0; + for(int yy=1;yy<10;++yy) + for(int xx=1;xx<10;++xx){ + const auto sample=frame.getPixelAt( + xx*frame.getWidth()/10, yy*frame.getHeight()/10); + if(sample!=first)++distinct; + if(sample.getAlpha()>0)++opaque; + } + assert(distinct>=8 && opaque>=40); + const auto file=juce::File::getCurrentWorkingDirectory() + .getChildFile("ImerSip_P92_JUCE_"+juce::String(dpi)+".png"); + juce::FileOutputStream output(file); + assert(output.openedOk()); + juce::PNGImageFormat encoder; + assert(encoder.writeImageToStream(frame,output)); + output.flush(); + assert(file.existsAsFile() && file.getSize()>10000); + } + auto* stage=dynamic_cast( + editor->findChildWithID("imersip.stage")); + auto* master=dynamic_cast( + editor->findChildWithID("imersip.gain")); + assert(stage && stage->getSliderStyle()==juce::Slider::LinearHorizontal); + assert(master && master->getSliderStyle()== + juce::Slider::RotaryHorizontalVerticalDrag); + auto* power=dynamic_cast( + editor->findChildWithID("imersip.power")); + assert(power && !power->isEnabled()); + assert(power->getButtonText().isEmpty()); + assert(!power->getToggleState()); + auto* selector=dynamic_cast( + editor->findChildWithID("imersip.preset")); + assert(selector&&selector->getNumItems()==7); // Custom + six strong scenes + assert(selector->getSelectedId()==2); + for(int i=0;igetNumItems();++i){ + const auto name=selector->getItemText(i); + assert(!name.containsIgnoreCase("neutral")); + assert(!name.containsIgnoreCase("a/b")); + } + assert(armix::builtin_fx::imersipP92PresetById(6)!=nullptr); + auto* distanceSlider=dynamic_cast( + editor->findChildWithID("imersip.distance")); + auto* earlySlider=dynamic_cast( + editor->findChildWithID("imersip.early")); + assert(distanceSlider && earlySlider); +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + assert(distanceSlider->getMinimum()==1.0); + assert(distanceSlider->getMaximum()==4.0); + assert(earlySlider->getMaximum()==180.0); +#endif + assert(armix::builtin_fx::imersipP92PresetById(8)==nullptr); + // Front Row Power must be a real applied audio edit, not UI illusion. + selector->setSelectedId(5,juce::sendNotificationSync); + juce::MidiBuffer editMidi; + juce::AudioBuffer editPcm(2,128); + editPcm.clear(); + editorFx->processBlock(editPcm,editMidi); + armix::builtin_fx::SonKuSpatialProcessor::Completion selected{}; + assert(editorFx->pollCompletion(selected)&&selected.applied); +#if defined(SONKU_P98_SCENE_VOICING_RESEARCH) && SONKU_P98_SCENE_VOICING_RESEARCH + assert(std::abs(editorFx->acceptedSettings().stereoSpreadDegrees-104.f)<.001f); + assert(std::abs(editorFx->acceptedSettings().sourceDistanceMeters-1.4f)<.001f); + assert(std::abs(editorFx->acceptedSettings().ambience-.70f)<.001f); + assert(std::abs(editorFx->acceptedSettings().roomAmount-1.26f)<.001f); + assert(editorFx->acceptedSettings().sceneVoicing==4); + juce::MemoryBlock detailState; + editorFx->getStateInformation(detailState); + assert(detailState.getSize()==75); + auto detailRestored=std::make_unique(); + detailRestored->prepareToPlay(48000.,128); + assert(detailRestored->restoreUnpublishedState( + detailState.getData(),static_cast(detailState.getSize()))); + assert(detailRestored->acceptedSettings().sceneVoicing==4); + assert(detailRestored->acceptedSettings().sourceDistanceMeters<=4.f); + assert(detailRestored->acceptedSettings().roomAmount>1.f); + detailRestored->releaseResources(); + assert(std::abs(editorFx->acceptedSettings().outputTrim- + armix::builtin_fx::imersipP92DbToLinear(5.60f))<.001f); +#else + assert(std::abs(editorFx->acceptedSettings().stereoSpreadDegrees-150.f)<.001f); + assert(std::abs(editorFx->acceptedSettings().sourceDistanceMeters-1.6f)<.001f); + assert(std::abs(editorFx->acceptedSettings().ambience-.97f)<.001f); + assert(std::abs(editorFx->acceptedSettings().outputTrim- + armix::builtin_fx::imersipP92DbToLinear(5.2f))<.001f); +#endif + auto* actualEditor=dynamic_cast( + editor.get()); + assert(actualEditor); + bool bypassed=false,rackBypassed=false,globalBypassed=false; + bool hostAvailable=true,acceptPower=true; + int acceptedLocalPower=0; + const auto hostState=[&] { + armix::builtin_fx::ImerSipP92Editor::HostBypassState state{}; + state.valid=hostAvailable; + state.slotBypassed=bypassed; + state.rackBypassed=rackBypassed; + state.globalBypassed=globalBypassed; + return state; + }; + actualEditor->bindHostPower( + [&](bool desired) { + if(!acceptPower)return false; + bypassed=desired; + ++acceptedLocalPower; + return true; + },hostState); + assert(power->isEnabled() && power->getToggleState()); + // Host-connected native screenshots prove the two actual power glyph + // states. The earlier DPI snapshots deliberately test disabled/fail-safe + // before host binding; these frames additionally verify the real bypass + // response without faking a DSP power state in the editor. + const auto savePowerFrame=[&](const char* mode) { + auto frame=editor->createComponentSnapshot(editor->getLocalBounds()); + assert(frame.isValid() && frame.getWidth()==935 && + frame.getHeight()==578); + const auto file=juce::File::getCurrentWorkingDirectory() + .getChildFile("ImerSip_P92_JUCE_POWER_"+juce::String(mode)+".png"); + juce::FileOutputStream output(file); + assert(output.openedOk()); + juce::PNGImageFormat encoder; + assert(encoder.writeImageToStream(frame,output)); + output.flush(); + assert(file.existsAsFile() && file.getSize()>10000); + return frame; + }; + const auto activeFrame=savePowerFrame("ON"); + power->onClick(); + assert(bypassed && !power->getToggleState()); + const auto bypassFrame=savePowerFrame("BYPASSED"); + + // Validate the *real JUCE framebuffer*, not just an ON/OFF flag. + // The stage must darken independently of the amber label, the label + // must be legible near scene centre, and the lower controls must dim + // while the power icon itself remains interactive and visible. + const auto rgbEnergy=[](juce::Colour px){ + return 3*int(px.getRed())+6*int(px.getGreen())+int(px.getBlue()); + }; + int stageDarker=0; + for(const int y:{75,110,150,285,320,350}) + for(const int x:{80,145,210,720,790,845}) + if(rgbEnergy(activeFrame.getPixelAt(x,y))- + rgbEnergy(bypassFrame.getPixelAt(x,y))>=15) + ++stageDarker; + assert(stageDarker>=24); // No washed-out "barely bypassed" venue + // Check relative scene luminance, not just binary "some pixel changed". + // Keep a trace of the venue rather than turning the stage completely black. + std::int64_t sceneOnEnergy=0,sceneMutedEnergy=0; + for(const int y:{75,110,150,285,320,350}) + for(const int x:{80,145,210,720,790,845}) { + sceneOnEnergy+=rgbEnergy(activeFrame.getPixelAt(x,y)); + sceneMutedEnergy+=rgbEnergy(bypassFrame.getPixelAt(x,y)); + } + assert(sceneMutedEnergy*100sceneOnEnergy*18); + + // Enforce actual glyph prominence: broad amber letter coverage across + // at least 36 vertical framebuffer rows; a small thin 40px regular + // caption would not pass this native pixel-level requirement. + int amberLetters=0,amberRows=0; + for(int y=115;y<285;++y) { + int inThisRow=0; + for(int x=200;x<740;x+=2) { + const auto px=bypassFrame.getPixelAt(x,y); + if(px.getRed()>170 && px.getGreen()>85 && + int(px.getRed())>int(px.getGreen())+55 && + int(px.getGreen())>int(px.getBlue())+35) { + ++amberLetters; + ++inThisRow; + } + } + if(inThisRow>=8) ++amberRows; + } + assert(amberLetters>=380 && amberRows>=36); + + std::int64_t panelOnEnergy=0,panelMutedEnergy=0; + for(const int y:{410,435,475,520,552}) + for(const int x:{45,120,225,305,415,550,675,775}) { + panelOnEnergy+=rgbEnergy(activeFrame.getPixelAt(x,y)); + panelMutedEnergy+=rgbEnergy(bypassFrame.getPixelAt(x,y)); + } + // A true UI mute is visually distinct, but labels remain decipherable. + assert(panelMutedEnergy*100panelOnEnergy*35); + + // Power is intentionally excluded from the panel veil. It must remain + // conspicuous and actionable when bypassed, not darkened with the rack. + int powerHighlightPixels=0; + const auto activePowerBounds=power->getBounds(); + for(int y=activePowerBounds.getY()+3;y112 && px.getGreen()>120 && px.getBlue()>125) + ++powerHighlightPixels; + } + assert(powerHighlightPixels>=15); + + int changedPowerPixels=0; + const auto powerRegion=power->getBounds(); + for(int y=powerRegion.getY()+3;y=10); // Visible true host ON/OFF indication + power->onClick(); + assert(!bypassed && power->getToggleState()); + assert(acceptedLocalPower==2); + + // Rejected host commands do not optimistic-toggle the actual PCM state. + acceptPower=false; + power->onClick(); + assert(!bypassed && power->getToggleState()); + assert(acceptedLocalPower==2); + acceptPower=true; + + // Mixer-header FX Power is a GLOBAL override, not a rewrite of + // any slot's remembered bypass preference. With editor still open + // it must immediately show BYPASSED and block misleading local power. + globalBypassed=true; + actualEditor->synchronizeHostPower(); + assert(!bypassed && !power->isEnabled() && !power->getToggleState()); + const auto globalFrame=savePowerFrame("GLOBAL_BYPASSED"); + assert(globalFrame.getPixelAt(450,195)!=activeFrame.getPixelAt(450,195)); + globalBypassed=false; + actualEditor->synchronizeHostPower(); + assert(!bypassed && power->isEnabled() && power->getToggleState()); + + // Rack Power is another independent additive gate; it must dim even + // though this individual slot's preference is still enabled. + rackBypassed=true; + actualEditor->synchronizeHostPower(); + assert(!bypassed && !power->isEnabled() && !power->getToggleState()); + const auto rackFrame=savePowerFrame("RACK_BYPASSED"); + assert(rackFrame.getPixelAt(450,195)!=activeFrame.getPixelAt(450,195)); + rackBypassed=false; + actualEditor->synchronizeHostPower(); + assert(!bypassed && power->isEnabled() && power->getToggleState()); + + // An invalidated processor lease can neither change another slot nor + // pretend that its UI owns an admitted host effect. + hostAvailable=false; + actualEditor->synchronizeHostPower(); + assert(!power->isEnabled() && !power->getToggleState()); + hostAvailable=true; + actualEditor->synchronizeHostPower(); + assert(power->isEnabled() && power->getToggleState()); + + // Original per-insert bypass must survive a global A/B roundtrip. + power->onClick(); + assert(bypassed); + globalBypassed=true; + actualEditor->synchronizeHostPower(); + globalBypassed=false; + actualEditor->synchronizeHostPower(); + assert(bypassed && !power->getToggleState() && power->isEnabled()); + power->onClick(); + assert(!bypassed && power->getToggleState()); + + // Actual JUCE scene renders: exact same embedded venue images as shipped + // with the native app. These captures are NOT HTML concept mockups. + // Each of the six preset IDs must produce a distinct visual composition. + std::uint64_t previousSceneSignature=0; + for(int sceneId=2;sceneId<=7;++sceneId) { + selector->setSelectedId(sceneId,juce::sendNotificationSync); + auto photo=editor->createComponentSnapshot(editor->getLocalBounds()); + assert(photo.isValid() && photo.getWidth()==935 && photo.getHeight()==578); + std::uint64_t signature=14695981039346656037ull; + for(int y=100;y<385;y+=37) + for(int x=65;x<860;x+=53) { + const auto px=photo.getPixelAt(x,y).getARGB(); + signature=(signature ^ static_cast(px)) + *1099511628211ull; + } + assert(sceneId==2 || signature!=previousSceneSignature); + previousSceneSignature=signature; + // The exact same six embedded PNGs must reach BOTH left/right + // viewport edges. Prior centred 2:1 images left uniform matte bands. + for(const int edgeX:{8,photo.getWidth()-9}) { + const auto first=photo.getPixelAt(edgeX,45); + int matteCount=0; + int varied=0; + for(int y=52;y<385;y+=19) { + const auto pixel=photo.getPixelAt(edgeX,y); + if(pixel==juce::Colour(0xff0e161c))++matteCount; + if(pixel!=first)++varied; + } + assert(matteCount<3 && varied>=7); + } + const auto sceneFile=juce::File::getCurrentWorkingDirectory() + .getChildFile("ImerSip_P92_SCENE_"+juce::String(sceneId)+".png"); + juce::FileOutputStream stream(sceneFile); + assert(stream.openedOk()); + juce::PNGImageFormat format; + assert(format.writeImageToStream(photo,stream)); + stream.flush(); + assert(sceneFile.existsAsFile() && sceneFile.getSize()>10000); + } + editor.reset(); + editorFx->releaseResources(); + nativeParity(44100); + nativeParity(48000); + std::puts("PASS IMERSIP P92 JUCE: exact P9 PCM, 44.1/48k, native state, legacy IMRS, editor, audio ACK"); +} diff --git a/tests/imersip_scene_assets_contract_test.py b/tests/imersip_scene_assets_contract_test.py new file mode 100644 index 000000000..d5ca5b45d --- /dev/null +++ b/tests/imersip_scene_assets_contract_test.py @@ -0,0 +1,73 @@ +# SPDX-License-Identifier: AGPL-3.0-only +"""ImmerSIB scene asset FAT: accept six venues only; reject retired sprite pack.""" +import pathlib +import struct +import unittest + +ROOT=pathlib.Path(__file__).resolve().parents[1] +SCENES=("live_concert","royal_concert_hall","arena_thunder", + "front_row_power","symphonic_palace","velvet_cinema") +ASSET=ROOT/"assets"/"imersip" + +class ApprovedSceneAssets(unittest.TestCase): + def test_six_photo_scene_pngs(self): + expected=sorted(ASSET/"scenes"/f"scene_{name}.png" for name in SCENES) + self.assertEqual(sorted((ASSET/"scenes").glob("*.png")),expected) + for path in expected: + with self.subTest(scene=path.name): + with path.open("rb") as f: + header=f.read(33) + self.assertEqual(header[:8],b"\x89PNG\r\n\x1a\n") + self.assertEqual(header[12:16],b"IHDR") + width,height,depth,colour,compression,filtering,interlace=struct.unpack( + ">IIBBBBB",header[16:29]) + # Exact two-times logical venue viewport: no side matte, + # no independent X/Y stretching, no accidental 2:1 fallback. + self.assertEqual((width,height),(2200,922)) + self.assertEqual(width*461,height*1100) + self.assertEqual(depth,8) + self.assertIn(colour,(2,6)) + self.assertEqual((compression,filtering,interlace),(0,0,0)) + + def test_rejected_kit_and_generation_are_gone(self): + for name in ("png","vector","asset_manifest.json", + "imersip_p92_skin_atlas.png","panel_flat_matte.svg"): + self.assertFalse((ASSET/name).exists(),name) + for path in ( + "scripts/generate_imersip_concert_png.py", + "tests/imersip_p92_png_asset_test.py", + ".github/workflows/imersip-p92-materialize-assets.yml", + "docs/IMERSIP_P92_CONCERT_VECTOR_RENDER_QA.md"): + self.assertFalse((ROOT/path).exists(),path) + + def test_no_compilation_or_ci_resurrection(self): + cmake=(ROOT/"CMakeLists.txt").read_text(encoding="utf-8") + skin=(ROOT/"engine/builtin_fx/ImerSipP92VisualSkin.h").read_text(encoding="utf-8") + editor=(ROOT/"engine/builtin_fx/ImerSipP92Editor.h").read_text(encoding="utf-8") + native_test=(ROOT/"tests/imersip_p92_native_test.cpp").read_text(encoding="utf-8") + workflow=(ROOT/".github/workflows/imersip-p92-single-engine.yml").read_text(encoding="utf-8") + self.assertNotIn("imersipP92ConcertBoxes",native_test) + self.assertIn("stageProbe->getMinimum()",native_test) + self.assertIn("distanceProbe->getMaximum()",native_test) + self.assertIn("ARMIX_IMERSIB_SCENE_PNG_SOURCES",cmake) + self.assertIn("BinaryData::scene_live_concert_png",skin) + self.assertIn("BinaryData::scene_velvet_cinema_png",skin) + self.assertIn("getWidth()!=photoWidth",skin) + self.assertIn("getHeight()!=photoHeight",skin) + self.assertIn("photoWidth=2200",skin) + self.assertIn("photoHeight=922",skin) + self.assertIn("int matteCount=0",native_test) + self.assertIn("assert(matteCount<3",native_test) + self.assertIn("skin_.drawScene(g,visualSceneId_)",editor) + self.assertIn("g.fillRect(0,461,1100,219)",skin) + self.assertIn("drawRotarySlider(",skin) + for forbidden in ("ARMIX_IMERSIP_PNG_SOURCES","assets/imersip/png", + "room_background_png","line_array_left_png", + "knob_master_purple_png","slider_thumb_png"): + self.assertNotIn(forbidden,cmake+skin) + for forbidden in ("19-RGBA-PNG-AssetPack","imersip-png-qa", + "all_speakers_composition","generate_imersip_concert_png", + "pillow>=11","test_19_independent_rgba"): + self.assertNotIn(forbidden,workflow) + +if __name__=="__main__":unittest.main() diff --git a/tests/immersib_p98_native_sonic_gate.cpp b/tests/immersib_p98_native_sonic_gate.cpp new file mode 100644 index 000000000..418b5a900 --- /dev/null +++ b/tests/immersib_p98_native_sonic_gate.cpp @@ -0,0 +1,267 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// ImmerSIB P9.7 Venue golden PCM and P9.8 typed scene diversification. +// No claim of actual source/stem separation; synthetic PCM verifies physical +// stage retention, stereo non-null, finite peaks, and distinct sonic programs. +#if defined(NDEBUG) +#undef NDEBUG +#endif +#if !defined(SONKU_P98_SCENE_VOICING_RESEARCH) || !SONKU_P98_SCENE_VOICING_RESEARCH +#error This test must compile the REAL P9.8 world-engine path +#endif +#include "../engine/builtin_fx/ImerSipP92Scene.h" +#include +#include +#include +#include // test-only energy aggregation +#include +#include +#include +#include +#include +#include +using armix::sonku::Settings; +using armix::sonku::SonKuSpatialCore; +using armix::sonku::SonKuReflectionProfile; +using armix::builtin_fx::imersipP92Factory; +using armix::builtin_fx::imersipP92Presets; +constexpr int n=16384; +constexpr double pi=3.1415926535897932384626433832795; +struct Result {std::uint64_t hash;double power,side;float peak;}; +static Result render(int rate,const Settings& s,bool phaseReverse=false){ + auto dsp=std::make_unique(); + assert(dsp->prepare(rate,SonKuReflectionProfile::SixSurfaceKemarResearch)); + assert(armix::sonku::valid(s) && dsp->setSettings(s)); + std::array,2> pcm{std::vector(n),std::vector(n)}; + for(int i=0;iprocess(pcm[0].data()+i,pcm[1].data()+i,128); + Result result{14695981039346656037ull,0.,0.,0.f}; + for(int i=0;i=4096){ + result.power+=double(l)*l+double(r)*r; + result.side+=double(l-r)*double(l-r); + } + for(float value:{l,r}){ + result.hash^=std::bit_cast(value); + result.hash*=1099511628211ull; + } + } + assert(result.power>1.e-4 && result.side>1.e-7); + return result; +} +// Whole-engine tone transfer, including HRTF/world reflections, P9.7 +// stage, P9.8 voicing, P9.5 makeup and peak guard. Real PCM, not just a +// narrow EQ coefficient guess. Short deterministic steady-state fixture. +static double acousticTonePower(int rate,const Settings& scene, + double hz,bool mid) { + auto dsp=std::make_unique(); + assert(dsp->prepare(rate,SonKuReflectionProfile::SixSurfaceKemarResearch)); + assert(dsp->setSettings(scene)); + std::array,2> pcm{ + std::vector(n),std::vector(n)}; + for(int i=0;i( + .065*std::sin(2*pi*hz*i/static_cast(rate))); + pcm[0][i]=a; + pcm[1][i]=mid?a:-a; + } + for(int i=0;iprocess(pcm[0].data()+i,pcm[1].data()+i,128); + double energy=0.; + for(int i=4096;i1.e-7); + return energy; +} +static Settings ownerVenue(){ + Settings s{}; + s.renderMode=9; + s.moving=false; + s.startAzimuthDegrees=0.f; + s.spacePreset=3; // Large + s.sourceDistanceMeters=10.f; // actual approved Venue 10m + s.stereoSpreadDegrees=106.f; + s.roomAmount=1.f; + s.ambience=1.f; + s.spatialMix=1.f; + s.outputTrim=1.8f; + s.sceneVoicing=0; // exact P9.7, no P9.8 tonal overlay + return s; +} +int main(){ + const auto venue=armix::builtin_fx::imersipP97VenueGoldenScene(); + const auto current=imersipP92Factory(2); + const auto golden=ownerVenue(); + assert(venue.renderMode==9 && !venue.moving && venue.sceneVoicing==0); + assert(venue.sourceDistanceMeters==10.f && venue.stereoSpreadDegrees==106.f); + assert(venue.roomAmount==1.f && venue.ambience==1.f); + assert(venue.outputTrim==1.8f && venue.spatialMix==1.f); + assert(venue.startAzimuthDegrees==0.f && venue.spacePreset==3); + assert(imersipP92Presets.size()==6); + // Nearfield source projection now supports 1m in the physical XYZ path. + armix::sonku::xyz::Placement projected{}; + assert(armix::sonku::xyz::project(1.f,0.f,1.45f,7.2f,projected)); + assert(std::abs(projected.horizontalMeters-1.f)<1.e-6f); + assert(!armix::sonku::xyz::project(.9f,0.f,1.45f,7.2f,projected)); + assert(current.sourceDistanceMeters==3.f && + current.roomAmount>1.f && current.sceneVoicing==4); + assert(armix::builtin_fx::validImerSipP92Scene(current)); + for(const auto& preset:imersipP92Presets) { + const auto s=imersipP92Factory(preset.id); + assert(s.sourceDistanceMeters>=1.f && s.sourceDistanceMeters<=4.f); + assert(s.roomAmount>1.f && s.roomAmount<=1.8f); + } + assert(armix::sonku::p98::SceneVoicing::valid(4)); + assert(armix::sonku::p98::SceneVoicing::valid(5)); + assert(!armix::sonku::p98::SceneVoicing::valid(6)); + // Product scene classification: preserve original Venue golden; new + // detail and impact voicings must NEVER silently affect its PCM. + constexpr int expectedProfiles[]{4,4,5,4,4,3}; + for(std::size_t i=0;idouble { + armix::sonku::p98::SceneVoicing fx; + assert(fx.prepare(sr)); + double power=0.; + for(int i=0;i<12000;++i){ + const float v=.10f*std::sin(2*pi*hz*i/double(sr)); + const auto out=fx.source(v,mono?v:-v,scene,true); + assert(std::isfinite(out.left)&&std::isfinite(out.right)); + if(mono)assert(std::abs(out.left-out.right)<1.e-7f); + if(i>=7000){ + const double side=.5*(out.left-out.right); + power+=side*side; + } + } + return power; + }; + const double baselinePresence=spectrum(rate,0,2050,false); + const double protectedPresence=spectrum(rate,4,2050,false); + const double baselineEdge=spectrum(rate,0,3450,false); + const double protectedEdge=spectrum(rate,4,3450,false); + const double baselineAir=spectrum(rate,0,7400,false); + const double lateralAir=spectrum(rate,4,7400,false); + assert(protectedPresence7k stereo is retained. + assert(protectedEdgebaselineAir*.75 && + lateralAirdouble{ + armix::sonku::p98::SceneVoicing fx; + assert(fx.prepare(sr)); + double energy=0.; + for(int i=0;i<12000;++i){ + const float v=.10f*std::sin(2*pi*hz*i/double(sr)); + auto out=fx.source(v,v,scene,true); + if(final)out=fx.finish(out.left,out.right); + assert(std::isfinite(out.left)&&std::isfinite(out.right)); + assert(std::abs(out.left-out.right)<1.e-7f); + if(i>=7000){ + const double mid=.5*(out.left+out.right); + energy+=mid*mid; + } + } + return energy; + }; + const double bodyReference=centeredEnergy(rate,0,285,false); + const double bodyFull=centeredEnergy(rate,4,285,false); + const double noseReference=centeredEnergy(rate,0,2050,false); + const double noseFull=centeredEnergy(rate,4,2050,false); + const double harshReference=centeredEnergy(rate,0,3450,true); + const double harshControlled=centeredEnergy(rate,4,3450,true); + // Genuine center body improvement, not a 2k-only megaphone: + assert(bodyFull>bodyReference*1.20); + assert(noseFull1.08); + assert(edgeRatio<1.05); + assert(airRatio>.65); + } + const auto base=render(rate,golden); + // Baseline acoustic PCM hashes captured BEFORE any ImmerSIB + // nearfield or M/S tuning. Real regression, not self-comparison. + assert(base.hash==(rate==44100?0x4759c0c588e0e421ull: + 0x13a8e95368edcc04ull)); + const auto migrated=render(rate,venue); + // The operator's approved Venue is a bit-exact audio checkpoint. + assert(base.hash==migrated.hash); + std::array uniquePcm{}; + for(const auto& preset:imersipP92Presets){ + const auto s=imersipP92Factory(preset.id); + assert(s.renderMode==9 && !s.moving); + assert(s.spacePreset==3 && s.sourceDistanceMeters<=4.f); + const auto heard=render(rate,s); + const auto inverse=render(rate,s,true); + assert(inverse.side>1.e-7); // no catastrophic antiphase null + assert(heard.hash!=base.hash); + // Always print candidate evidence BEFORE its quality floor; + // std::cout/stdout may be buffered and lost by abort(). + std::fprintf(stderr,"NEARFIELD_DIAG,rate=%d,id=%d,meters=%.2f,early=%.2f,energy=%.6f,venue=%.6f,side=%.6f,peak=%.5f\n", + rate,preset.id,s.sourceDistanceMeters,s.roomAmount, + heard.power,base.power,heard.side,double(heard.peak)); + // Safety floor only: older .85 electrical power gate + // rewarded treble-heavy sound even when the owner heard + // shrill, thin vocals. The independent WHOLE-PCM 285Hz/3.45k + // tonal tests above replace it with a physically appropriate + // transfer quality criterion. Still forbid silent presets. + assert(heard.power>base.power*.70); + uniquePcm[static_cast(preset.id-2)]=heard.hash; + std::printf("IMMERSIB_P98_SCENE,%d,%d,%s,%d,%.6f,%.6f,%.6f,%016llx\n", + rate,preset.id,preset.label,s.sceneVoicing, + heard.power,heard.side,double(heard.peak), + static_cast(heard.hash)); + } + // Every user-facing scene is a physically distinct PCM program. + for(std::size_t i=0;ix.id===id); if(!t||!ch.controls)continue; - if(!paintNativeFxPowerReadback(ch,t)){ + if(!paintNativeFxPowerReadback(ch,t,next.raw?.globalFxBypassed)){ // A plugin owner or strip DOM changed under us: do not paint an // unrelated instance. Rebuild from the accepted native graph. if(!projection(next))return false; @@ -2979,8 +2982,13 @@ } // Control readback may change at the SAME structural graph revision. // Compare the actual accepted controls/edges, never skip native fader updates. - const signature=next.identity+"|"+JSON.stringify(next.graph.channels.map(ch=>[ - ch.id,ch.controls,ch.inserts,ch.fxRackBypassed,ch.primaryOutId]))+"|"+JSON.stringify(next.graph.edges)+"|"+appearanceRevision; + // GLOBAL A/B is a realtime SCALAR with unchanged graph revision and + // unchanged saved insert flags. Include its accepted PCM readback so + // bypassing every FX repaints each mounted rack without rebuilding DOM. + const signature=next.identity+"|"+String(next.raw?.globalFxBypassed)+"|"+ + JSON.stringify(next.graph.channels.map(ch=>[ + ch.id,ch.controls,ch.inserts,ch.fxRackBypassed,ch.primaryOutId]))+"|"+ + JSON.stringify(next.graph.edges)+"|"+appearanceRevision; if (signature===lastPaintedSignature) { // Telemetry-only snapshots should not traverse all channels. But an // expired/rejected edit with unchanged graph values must not strand its