diff --git a/.github/workflows/sonku-p80-acoustic-field.yml b/.github/workflows/sonku-p80-acoustic-field.yml new file mode 100644 index 000000000..8bec9f26b --- /dev/null +++ b/.github/workflows/sonku-p80-acoustic-field.yml @@ -0,0 +1,257 @@ +name: SonKu P8.0 measured-timbre Windows acoustic field candidate +# Isolated opt-in full JUCE app build; no public installer, tag or release. +on: + pull_request: + types: [opened, reopened, synchronize] + paths: + - '.github/workflows/sonku-p75-windows-field.yml' + - 'src/Main.cpp' + - 'src/SonKuNativeBridgeContract.h' + - 'src/LiveAudioEngine.h' + - 'engine/builtin_fx/SonKuSpatialProcessor.h' + - 'engine/builtin_fx/sonku/**' + - 'site/preview-v2/assets/mixer-native-sonku.js' + - 'CMakeLists.txt' + - 'tests/sonku_p72_*' + - 'tests/sonku_p75_*' + - 'tests/sonku_p80_*' + - 'scripts/sonku_p80_evidence.py' + workflow_dispatch: +permissions: + contents: read +concurrency: + group: sonku-p80-acoustics-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + preflight: + name: Isolated fast PCM and GUI preflight + runs-on: ubuntu-latest + timeout-minutes: 8 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Native JS and source GUI capability checks + run: | + set -euo pipefail + node --check site/preview-v2/assets/mixer-native-sonku.js + node tests/sonku_p73_gui_contract_test.js + grep -q "'FIELD_PREVIEW_FULL_CTEST_NOT_RUN'" scripts/m3e_fat_evidence_gate.mjs + python -m unittest discover -s tests -p native_peq_assembly_test.py + - name: 44.1 and 48 kHz prepared PCM source regression + run: | + set -euo pipefail + g++ -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 \ + tests/sonku_p72_realtime_xyz_test.cpp -o /tmp/sonku-p80-legacy-pcm + /tmp/sonku-p80-legacy-pcm + g++ -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 \ + tests/sonku_p75_stereo_integrity_test.cpp -o /tmp/sonku-p75-music + /tmp/sonku-p75-music + # Baseline and measured P8.0 compile the SAME source tree with + # exactly one flag changed. Compare every source and ROOM scene. + mkdir -p evidence + g++ -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 \ + tests/sonku_p80_acoustic_probe.cpp -o /tmp/sonku-p80-baseline + /tmp/sonku-p80-baseline evidence + g++ -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_MEASURED_TIMBRE_RESEARCH=1 \ + tests/sonku_p80_acoustic_probe.cpp -o /tmp/sonku-p80-measured + /tmp/sonku-p80-measured evidence + g++ -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_MEASURED_TIMBRE_RESEARCH=1 \ + tests/sonku_p80_timbre_calibration_test.cpp -o /tmp/sonku-p80-qa + /tmp/sonku-p80-qa + python scripts/sonku_p80_evidence.py evidence + git rev-parse HEAD > evidence/SOURCE_SHA.txt + - name: Upload inspectable source-side acoustic evidence + uses: actions/upload-artifact@v4 + with: + name: SonKu-P80-Objective-Evidence-${{ github.run_id }} + path: evidence/ + retention-days: 21 + if-no-files-found: error + windows-field: + name: Actual full Windows JUCE executable and verified portable field ZIP + needs: preflight + runs-on: windows-2022 + timeout-minutes: 55 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Verify immutable PR head and physical candidate identity + shell: pwsh + env: + EXPECTED_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + run: | + $actual = (& git rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or $actual -ne $env:EXPECTED_SHA -or $actual -notmatch '^[0-9a-f]{40}$') { + throw "SONKU_P80_SOURCE_MISMATCH:$actual" + } + Write-Host "SONKU_P80_EXACT_SOURCE=$actual" + - uses: actions/checkout@v4 + with: + repository: juce-framework/JUCE + ref: 8.0.15 + path: third_party/JUCE + persist-credentials: false + - name: Obtain pinned WebView2 compilation SDK + shell: pwsh + run: | + nuget install Microsoft.Web.WebView2 -Version 1.0.3485.44 -OutputDirectory .deps -NonInteractive + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Configure full native app with research XYZ explicit ON + 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_P80_TIMBRE=ON ` + -DBUILD_TESTING=ON + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $cache = Get-Content -LiteralPath build/CMakeCache.txt -Raw + if ($cache -notmatch 'ARMIX_SONKU_EXPERIMENTAL_NATIVE_XYZ_RT:BOOL=ON' -or + $cache -notmatch 'ARMIX_SONKU_EXPERIMENTAL_MUSIC_SAFE:BOOL=ON' -or + $cache -notmatch 'ARMIX_SONKU_EXPERIMENTAL_P80_TIMBRE:BOOL=ON') { + throw "SONKU_P80_RESEARCH_NOT_ENABLED" + } + $tests = (& ctest --test-dir build -C Release --show-only=json-v1 | Out-String | ConvertFrom-Json) + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $required = @('NativeSonKuP72AtomicXyzLiveEditSource', + 'NativeSonKuP72JuceV3XyzLiveAckV1V2Restore', + 'NativeSonKuSessionV1V2AndAudioAppliedAck', + 'NativeSonKuP75MusicStereoPhaseNoNullAndChunkParity', + 'NativeSonKuP80MeasuredHrtfTimbreAndChunkParity') + $available = @($tests.tests | ForEach-Object { $_.name }) + foreach ($test in $required) { + if ($test -notin $available) { throw "SONKU_P80_MISSING_CTEST:$test" } + } + - name: Compile actual ARMixConsole Windows GUI and focused real JUCE tests + shell: pwsh + run: | + cmake --build build --config Release --parallel 2 --target ` + ARMixConsole ARMixSonKuP72SourceTests ARMixSonKuP72NativeTests ARMixSonKuNativeStateTests ARMixSonKuP75MusicIntegrityTests ARMixSonKuP80MeasuredTimbreTests + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $exe = 'build/ARMixConsole_artefacts/Release/AR MIX Studio.exe' + if (-not (Test-Path -LiteralPath $exe -PathType Leaf)) { throw "SONKU_P80_NO_GUI_EXE" } + if ((Get-Item -LiteralPath $exe).Length -lt 4MB) { throw "SONKU_P80_WRONG_GUI_TARGET" } + - name: Scoped native XYZ state, callback ACK and legacy restoration + shell: pwsh + run: | + ctest --test-dir build -C Release --output-on-failure ` + -R '^NativeSonKu(P72AtomicXyzLiveEditSource|P72JuceV3XyzLiveAckV1V2Restore|SessionV1V2AndAudioAppliedAck|P75MusicStereoPhaseNoNullAndChunkParity|P80MeasuredHrtfTimbreAndChunkParity)$' + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Package real native portable mixer, never an installer + 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 } + - name: Record exact experiment and physical qualification pending + shell: pwsh + run: | + $path = 'dist/BUILD_PROVENANCE.json' + $p = Get-Content -LiteralPath $path -Raw -Encoding utf8 | ConvertFrom-Json + $sha = (& git rev-parse HEAD).Trim() + if ($p.sourceCommit -ne $sha) { throw "SONKU_P80_ARTIFACT_SHA_MISMATCH" } + $p.fatStatus = 'FIELD_PREVIEW_FULL_CTEST_NOT_RUN' + $p | Add-Member -NotePropertyName sonkuExperiment -NotePropertyValue @{ + enabled = $true + nativeXYZ = $true + musicSafeStereo = $true + measuredTimbre = $true + measuredTimbreMaxLowShelfDb = 4.5 + measuredHrtfReference = 'KEMAR_0_90_180_BOTH_EARS_125HZ_VS_1000HZ' + musicSafeAlgorithm = 'MEASURED_CENTER_MID_PLUS_UNCONDITIONAL_STEREO_SIDE_RESEARCH' + stateSchema = 3 + fullWindowsExecutable = $true + publicRelease = $false + physicalAsioQualified = $false + dearVrPerceptualParityProven = $false + qualification = 'SONKU_P80_5_FOCUSED_CTESTS_ONLY_REAL_ASIO_MUSIC_DEARVR_PENDING' + licenseRedistributionApproval = $false + mitKemarNoticeSha256 = (Get-FileHash -LiteralPath docs/THIRD_PARTY_8D_SONKU_HRTF.md -Algorithm SHA256).Hash.ToLowerInvariant() + fieldFatGuideSha256 = (Get-FileHash -LiteralPath docs/SONKU_P80_MEASURED_TIMBRE_FIELD_GUIDE_20261114.md -Algorithm SHA256).Hash.ToLowerInvariant() + } -Force + $p | ConvertTo-Json -Depth 20 | Set-Content -LiteralPath $path -Encoding utf8 + - name: Independent GUI PE, approved resources, provenance and ZIP verification + shell: pwsh + run: | + & ./scripts/verify_native_windows_artifact.ps1 -OutputDir dist + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $p = Get-Content -LiteralPath dist/BUILD_PROVENANCE.json -Raw | ConvertFrom-Json + if (-not $p.sonkuExperiment.enabled -or + -not $p.sonkuExperiment.musicSafeStereo -or + -not $p.sonkuExperiment.measuredTimbre -or + $p.sonkuExperiment.stateSchema -ne 3 -or $p.sonkuExperiment.publicRelease) { + throw 'SONKU_P80_WRONG_FIELD_ARTIFACT' + } + - name: Include mandatory MIT KEMAR notice and physical FAT guide + shell: pwsh + run: | + # Standard distribution allowlist was verified above. Field-only notice. + Copy-Item -LiteralPath docs/THIRD_PARTY_8D_SONKU_HRTF.md -Destination dist/THIRD_PARTY_8D_SONKU_HRTF.md + Copy-Item -LiteralPath docs/SONKU_P80_MEASURED_TIMBRE_FIELD_GUIDE_20261114.md -Destination dist/SONKU_P80_FIELD_FAT.md + $p = Get-Content -LiteralPath dist/BUILD_PROVENANCE.json -Raw | ConvertFrom-Json + $checks = @{ + 'THIRD_PARTY_8D_SONKU_HRTF.md' = [string]$p.sonkuExperiment.mitKemarNoticeSha256 + 'SONKU_P80_FIELD_FAT.md' = [string]$p.sonkuExperiment.fieldFatGuideSha256 + } + foreach ($item in $checks.GetEnumerator()) { + $file = Join-Path dist $item.Key + if ($item.Value -notmatch '^[0-9a-f]{64}$' -or + -not (Test-Path -LiteralPath $file -PathType Leaf)) { + throw "SONKU_P80_FIELD_NOTICE_MISSING:$($item.Key)" + } + $actual = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() + if ($actual -ne $item.Value) { throw "SONKU_P80_FIELD_NOTICE_HASH_MISMATCH:$($item.Key)" } + } + if (Test-Path -LiteralPath dist/Studio) { throw 'SONKU_FIELD_USER_DATA_MUST_NOT_SHIP' } + Write-Host 'SONKU_P80_FIELD_READY: GUI EXE + verified MIT notice + FAT guide' + - name: Include same-head objective A/B evidence in the portable tester + uses: actions/download-artifact@v4 + with: + name: SonKu-P80-Objective-Evidence-${{ github.run_id }} + path: dist/P80_objective_evidence + - name: Verify objective artifact belongs to this exact native EXE + shell: pwsh + run: | + $expected = (& git rev-parse HEAD).Trim() + $source = (Get-Content -LiteralPath dist/P80_objective_evidence/SOURCE_SHA.txt -Raw).Trim() + $report = Get-Content -LiteralPath dist/P80_objective_evidence/sonku_p80_evidence.json -Raw | ConvertFrom-Json + if ($source -ne $expected -or + $report.status -ne 'PASS_OBJECTIVE_SPECTRAL_STEREO_ROOM_PRESENCE_ONLY') { + throw 'SONKU_P80_OBJECTIVE_EVIDENCE_SHA_OR_STATUS_MISMATCH' + } + - uses: actions/upload-artifact@v4 + name: Upload isolated SonKu Windows x64 field candidate + with: + name: ArSonMix-SonKu-P80-Measured-Timbre-Windows-x64-${{ github.run_id }} + path: dist/ + if-no-files-found: error + retention-days: 21 + compression-level: 0 diff --git a/CMakeLists.txt b/CMakeLists.txt index a4f3482f3..ff2e29617 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,6 +19,16 @@ if(ARMIX_SONKU_EXPERIMENTAL_MUSIC_SAFE AND NOT ARMIX_SONKU_EXPERIMENTAL_NATIVE_XYZ_RT) message(FATAL_ERROR "P7.5 music-safe requires explicit native XYZ research ON") endif() +# P8.0: KEMAR-bank measured and *bounded* interaural-common tonal +# calibration. Never enabled in alpha/installer or non-XYZ builds. +option(ARMIX_SONKU_EXPERIMENTAL_P80_TIMBRE + "Unqualified P8.0 measured spectral calibration, P7.5 XYZ required" + OFF) +if(ARMIX_SONKU_EXPERIMENTAL_P80_TIMBRE AND + (NOT ARMIX_SONKU_EXPERIMENTAL_MUSIC_SAFE OR + NOT ARMIX_SONKU_EXPERIMENTAL_NATIVE_XYZ_RT)) + message(FATAL_ERROR "P8.0 measured timbre needs BOTH P7.5 music-safe and P7.2 XYZ research ON") +endif() set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -217,7 +227,8 @@ target_compile_definitions(ARMixConsole PRIVATE $<$:SONKU_P7_MEASURED_ELEVATION_RESEARCH=1> $<$:SONKU_P71_DIRECT_XYZ_RESEARCH=1> $<$:SONKU_P72_NATIVE_XYZ_RT=1> - $<$:SONKU_P75_MUSIC_SAFE_RESEARCH=1>) + $<$:SONKU_P75_MUSIC_SAFE_RESEARCH=1> + $<$:SONKU_P80_MEASURED_TIMBRE_RESEARCH=1>) if(WIN32) # Windows retains its proven ASIO-first / WASAPI / static WebView2 distribution. # Never link Windows loader or sound APIs into macOS/Linux builds. @@ -348,6 +359,23 @@ if(BUILD_TESTING) SONKU_P75_MUSIC_SAFE_RESEARCH=1) add_test(NAME NativeSonKuP75MusicStereoPhaseNoNullAndChunkParity COMMAND ARMixSonKuP75MusicIntegrityTests) + if(ARMIX_SONKU_EXPERIMENTAL_P80_TIMBRE) + # Compile the exact production-source P8.0 header into the JUCE + # native XYZ adapter and each scoped PCM qualification executable. + target_compile_definitions(ARMixSonKuP72NativeTests PRIVATE + SONKU_P80_MEASURED_TIMBRE_RESEARCH=1) + add_executable(ARMixSonKuP80MeasuredTimbreTests + tests/sonku_p80_timbre_calibration_test.cpp) + target_compile_features(ARMixSonKuP80MeasuredTimbreTests PRIVATE cxx_std_20) + target_compile_definitions(ARMixSonKuP80MeasuredTimbreTests PRIVATE + SONKU_P7_MEASURED_ELEVATION_RESEARCH=1 + SONKU_P71_DIRECT_XYZ_RESEARCH=1 + SONKU_P72_NATIVE_XYZ_RT=1 + SONKU_P75_MUSIC_SAFE_RESEARCH=1 + SONKU_P80_MEASURED_TIMBRE_RESEARCH=1) + add_test(NAME NativeSonKuP80MeasuredHrtfTimbreAndChunkParity + COMMAND ARMixSonKuP80MeasuredTimbreTests) + endif() endif() endif() # Pure control-plane first-run routing selection: no JUCE, drivers, diff --git a/docs/SONKU_P80_MEASURED_TIMBRE_FIELD_GUIDE_20261114.md b/docs/SONKU_P80_MEASURED_TIMBRE_FIELD_GUIDE_20261114.md new file mode 100644 index 000000000..5435baa79 --- /dev/null +++ b/docs/SONKU_P80_MEASURED_TIMBRE_FIELD_GUIDE_20261114.md @@ -0,0 +1,28 @@ +# SonKu P8.0 — measured timbre correction field check (research only) + +**Status: CPU/SRC/PCM research, NOT dearVR parity, NOT user-accepted audio quality.** +P7.4 physical report: severe cancellation. P7.5 physical report: thin bass, forward/nasal mid, flat room and undesirable centered/head-locked stereo. These are acceptance FAILS, regardless of green CI. This P8.0 experiment **only targets a measured LF/mid imbalance** and establishes objective direct/ER/late evidence. The stereo spatialization and full room perceptual quality still require a new architecture and independent testing. + +## Exact implementation +`ARMIX_SONKU_EXPERIMENTAL_NATIVE_XYZ_RT=ON` ++ `ARMIX_SONKU_EXPERIMENTAL_MUSIC_SAFE=ON` ++ `ARMIX_SONKU_EXPERIMENTAL_P80_TIMBRE=ON`. +All three OFF in the public installer. The same measured KEMAR bank as native PCM is sampled at 0°, 90° and 180°, both ears, 125 and 1000 Hz on the control thread. A *bounded maximum 4.5 dB* stereo-common RBJ low shelf around 180 Hz is prepared before the callback and applied only to the spatial/binaural field; SIDE anti-phase protection is not filtered/altered. This avoids a fabricated +10 dB bass patch, avoids changing ITD/ILD and stops stacking the older ROOM-only shelf. The result is **not a proprietary Clarity clone**. + +## Objective acceptance +`sonku_p80_evidence.json` is generated by two isolated compiles of the same source commit: P7.5 (baseline flag OFF) and P8.0 (new measured flag ON). Sources are deterministic probes rather than copyrighted program material. The gate checks tonal bass relative to 1 kHz, 8 kHz preservation, opposite-phase SIDE invariance, and that first reflections and late tail are observable separately. Source, compile flags, and sample rate are recorded. The report DOES NOT compare dearVR audio and cannot prove musical naturalness. + +## Physical test, before any promotion +1. Extract only the P8.0 Windows research artifact into a clean portable folder. Confirm `BUILD_PROVENANCE.json`: `measuredTimbre=true`, `publicRelease=false` and exact HEAD SHA. Begin at low monitoring volume. Use ASIO stereo headphone outputs; **Master Mono OFF**. +2. Same native GUI/channel/WIRE/MAIN, with one SonKu insert, 48 kHz, 256 frames. Verify real native v3 ACK and new `MEASURED TIMBRE · RESEARCH` label; if absent, record it as a FAILED test. +3. Using the **same licensed music** and the same interface/headphones/volume: FX Bypass → P7.5 (thin/nasal reference) → P8.0. Test ROOM OFF first; FRONT static, SPREAD 60, SPATIAL MIX 100%, moderate trim. Specifically evaluate whether bass guitar and kick become fuller **without mid/vocal losing clarity or SIDE shrinking**. +4. Then select SQUARE 7.2m with ROOM ON and compare EARLY and LATE settings separately where possible. Check reflections, density, front/back positioning, and whether the room feels cubical rather than a flat echo. +5. For dearVR PRO 2 A/B, log **Clarity** level and **Bass Boost OFF vs ON** separately, plus actual Realtime Auralisation 6-boundary geometry, Reverb ON/OFF, room preset, ER/late filters, master level and output binaural. Loudness match with measured levels, not knob positions. +6. Re-test 44.1/48 kHz 64/128/256 buffers when supported, 1/2/4 inserts with a normal VST3 and WIRE, restart/rebind, .smix save/open, and XRUN/p95/p99. Stop immediately on harsh coloration, bursts, severe cancellation or stereo collapse. + +## Still unresolved / veto +- Stereo source objects need physically spatialized **two-input/two-ear rendering** with content-safe phase handling; P7.5 MID HRTF + unfiltered SIDE is *not* a final stereo design. +- Six-wall ER need calibrated frequency-dependent boundary absorption / reflection direction; late field needs calibrated room-wise band decay / DRR and listening qualification. +- No green CI result, room-label text, or uncalibrated bass lift proves parity with dearVR. Keep this PR Draft and public main untouched until headphone tests pass. + +References: `docs/SONKU_P8_DEARVR_BENCHMARK_ACOUSTIC_ARCHITECTURE_20261114.md`; MIT KEMAR `docs/THIRD_PARTY_8D_SONKU_HRTF.md`. Original implementations only; do not reuse proprietary dearVR DSP/data or patent-protected Clarity. diff --git a/engine/builtin_fx/SonKuSpatialProcessor.h b/engine/builtin_fx/SonKuSpatialProcessor.h index f2e083793..fa31e151f 100644 --- a/engine/builtin_fx/SonKuSpatialProcessor.h +++ b/engine/builtin_fx/SonKuSpatialProcessor.h @@ -84,6 +84,12 @@ class SonKuSpatialProcessor final : public juce::AudioProcessor, armix::sonku::SonKuReflectionProfile preparedReflectionProfile() const noexcept { return core_.preparedReflectionProfile(); } +#if defined(SONKU_P80_MEASURED_TIMBRE_RESEARCH) && SONKU_P80_MEASURED_TIMBRE_RESEARCH + // Constant prepared DSP measurement, never a live UI control. + float preparedTimbreShelfDb() const noexcept { + return core_.p80PreparedShelfDb(); + } +#endif float observedAzimuthDegrees() const noexcept { return observedAzimuthDegrees_.load(std::memory_order_relaxed); } diff --git a/engine/builtin_fx/sonku/SonKuP80TimbreCalibration.h b/engine/builtin_fx/sonku/SonKuP80TimbreCalibration.h new file mode 100644 index 000000000..424db8ab0 --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuP80TimbreCalibration.h @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +// P8.0: experimental direction-INDEPENDENT KEMAR spectral reference. +// Prepare off the audio callback; one identical EQ for both ears preserves +// interaural level/time differences. This is NOT Sennheiser Clarity, +// headphone-specific inverse EQ or a claim of dearVR sonic parity. +#include +#include +#include +#include +#include + +namespace armix::sonku::p80 { +class MeasuredTimbreCalibration final { +public: + static constexpr float maxLowShelfDb=4.5f; + static constexpr float referenceLowHz=125.f; + static constexpr float referenceMidHz=1000.f; + + // Bank: int16 FIR [direction][ear][tap], identical to the SonKu + // source kernel. Coefficients are CONTROL-prepared, not live-sampled. + template + bool prepare(double rate,const std::int16_t (*bank)[2][Taps], + int directionCount,int spacingDegrees) noexcept { + ready_=false; + if(!bank || (std::abs(rate-44100.)>.1 && std::abs(rate-48000.)>.1) || + directionCount<2 || spacingDegrees<=0)return false; + double powerLow=0.,powerMid=0.; + int count=0; + // Reference positions: front, quarter turn and rear. Collect + // both ears to avoid direction-dependent channel gain/ILD shifts. + for(int deg:{0,90,180}) { + const int index=std::clamp(deg/spacingDegrees,0,directionCount-1); + for(int ear=0;ear<2;++ear) { + powerLow+=powerAt(bank[index][ear],rate,referenceLowHz); + powerMid+=powerAt(bank[index][ear],rate,referenceMidHz); + ++count; + } + } + if(count!=6 || powerLow<1.e-12 || powerMid<1.e-12 || + !std::isfinite(powerLow) || !std::isfinite(powerMid))return false; + const double spectralRatioDb=10.*std::log10(powerMid/powerLow); + // Never guess a +10 dB boost from a HRTF notch. A bounded + // low-shelf may improve monitoring without losing safety headroom. + gainDb_=static_cast(std::clamp(spectralRatioDb,0., + static_cast(maxLowShelfDb))); + measuredLowMinusMidDb_=-static_cast(spectralRatioDb); + if(gainDb_>1.e-4f){ + if(!prepareShelf(rate,180.,gainDb_))return false; + }else{ + b0_=1.;b1_=b2_=a1_=a2_=0.; + } + reset(); + ready_=true; + return true; + } + + void reset() noexcept {for(auto& z:memory_)z.fill(0.);} + bool ready() const noexcept{return ready_;} + float shelfGainDb() const noexcept{return gainDb_;} + float measuredLowMinusMidDb() const noexcept{ + return measuredLowMinusMidDb_; + } + void process(float& left,float& right) noexcept { + if(!ready_)return; + left=step(left,memory_[0]); + right=step(right,memory_[1]); + } + +private: + template + static double powerAt(const std::int16_t (&fir)[Taps], + double rate,double frequency) noexcept{ + const double w=6.2831853071795864769*frequency/rate; + double re=0.,im=0.; + for(std::size_t i=0;i(i); + re+=static_cast(fir[i])*std::cos(phase); + im-=static_cast(fir[i])*std::sin(phase); + } + return re*re+im*im; + } + bool prepareShelf(double rate,double cutoff,double db) noexcept { + // RBJ Audio EQ Cookbook low shelf, slope S=1. Same stable + // minimum-phase coefficients on both ears: no differential delay. + constexpr double pi=3.14159265358979323846; + const double A=std::pow(10.,db/40.); + const double w=2.*pi*cutoff/rate; + const double sn=std::sin(w),cs=std::cos(w); + const double alpha=sn/std::sqrt(2.); + const double beta=2.*std::sqrt(A)*alpha; + const double den=(A+1.)+(A-1.)*cs+beta; + if(!std::isfinite(den)||den<=0.)return false; + b0_=A*((A+1.)-(A-1.)*cs+beta)/den; + b1_=2.*A*((A-1.)-(A+1.)*cs)/den; + b2_=A*((A+1.)-(A-1.)*cs-beta)/den; + a1_=-2.*((A-1.)+(A+1.)*cs)/den; + a2_=((A+1.)+(A-1.)*cs-beta)/den; + return std::isfinite(b0_)&&std::isfinite(b1_)&& + std::isfinite(b2_)&&std::isfinite(a1_)&&std::isfinite(a2_); + } + static float clean(double x) noexcept { + return std::isfinite(x) && std::abs(x)<10000.? + static_cast(x):0.f; + } + float step(float input,std::array& z) noexcept { + if(gainDb_<=1.e-4f)return input; + const double in=static_cast(input); + const double y=b0_*in+z[0]; + const double next0=b1_*in-a1_*y+z[1]; + const double next1=b2_*in-a2_*y; + z[0]=std::abs(next0)>1.e-24?next0:0.; + z[1]=std::abs(next1)>1.e-24?next1:0.; + return clean(y); + } + std::array,2> memory_{}; + double b0_=1.,b1_=0.,b2_=0.,a1_=0.,a2_=0.; + float gainDb_=0.,measuredLowMinusMidDb_=0.; + bool ready_=false; +}; +} // namespace armix::sonku::p80 diff --git a/engine/builtin_fx/sonku/SonKuSpatialCore.h b/engine/builtin_fx/sonku/SonKuSpatialCore.h index 010693f74..95fbf1c9d 100644 --- a/engine/builtin_fx/sonku/SonKuSpatialCore.h +++ b/engine/builtin_fx/sonku/SonKuSpatialCore.h @@ -4,6 +4,12 @@ #include "SonKuEarlyReflections.h" #include "SonKuMusicalReverb.h" #include "SonKuStereoIntegrity.h" +#if defined(SONKU_P80_MEASURED_TIMBRE_RESEARCH) && SONKU_P80_MEASURED_TIMBRE_RESEARCH +#include "SonKuP80TimbreCalibration.h" +#if !defined(SONKU_P75_MUSIC_SAFE_RESEARCH) || !SONKU_P75_MUSIC_SAFE_RESEARCH +#error P8.0 measured timbre requires opt-in P7.5 native music renderer +#endif +#endif #if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH #include "SonKuSourcePlacement3D.h" #endif @@ -91,6 +97,12 @@ class SonKuSpatialCore final { std::abs(rate-48000.)>.1))return false; sampleRate_=rate; bank_=(std::abs(rate-44100.)<=.1)?hrir::normal44100:hrir::normal48000; +#if defined(SONKU_P80_MEASURED_TIMBRE_RESEARCH) && SONKU_P80_MEASURED_TIMBRE_RESEARCH + // Own measured KEMAR bank, off RT. A stereo-common correction never + // changes ITD/ILD, and is explicitly OFF in every public build. + if(!timbre_.prepare(rate,bank_,hrir::directions, + hrir::spacingDegrees))return false; +#endif // Prepared control-side: continuous coefficient and gain smoothing // without trigonometric/exponential work in the audio callback. filterSlew_=static_cast(1.-std::exp(-1./(rate*0.006))); @@ -138,6 +150,9 @@ class SonKuSpatialCore final { smoothedErPresence_=1.f; smoothedTailPresence_=1.f; earBass_.fill(0.f); +#if defined(SONKU_P80_MEASURED_TIMBRE_RESEARCH) && SONKU_P80_MEASURED_TIMBRE_RESEARCH + timbre_.reset(); +#endif limiterGain_=1.f; write_=0; remaining_=0; @@ -257,6 +272,16 @@ class SonKuSpatialCore final { return room_.preparedProfile(); } double azimuthDegrees() const noexcept {return degrees_;} +#if defined(SONKU_P80_MEASURED_TIMBRE_RESEARCH) && SONKU_P80_MEASURED_TIMBRE_RESEARCH + // Read-only observed control-side measurements for objective tests; + // NOT a live knob or an unversioned host/session field. + float p80MeasuredLowMinusMidDb() const noexcept { + return timbre_.measuredLowMinusMidDb(); + } + float p80PreparedShelfDb() const noexcept { + return timbre_.shelfGainDb(); + } +#endif // In-place stereo; caller owns valid, non-overlapping L/R PCM pointers. // No vector, heap, blocking calls, I/O or filter bank allocation. void process(float* left,float* right,int samples) noexcept { @@ -267,7 +292,16 @@ class SonKuSpatialCore final { const double step=(settings_.moving ? (settings_.clockwise?1.:-1.)*360./(sampleRate_*settings_.revolutionSeconds) : 0.); const float distanceGain=room_.relativeDistanceGain(); - const bool nativeSpace=nativeSpaceEverUsed_; +#if defined(SONKU_P80_MEASURED_TIMBRE_RESEARCH) && SONKU_P80_MEASURED_TIMBRE_RESEARCH + const bool p80Timbre= + room_.preparedProfile()==SonKuReflectionProfile::SixSurfaceKemarResearch; +#else + constexpr bool p80Timbre=false; +#endif + // P8.0 routes even ROOM OFF through the same sample-exact scene path + // so the measured spectral correction is on BEFORE room activation. + // Previous public/legacy paths remain bit-identical. + const bool nativeSpace=nativeSpaceEverUsed_||p80Timbre; const bool roomEnabled=settings_.spacePreset!=0; #if defined(SONKU_P75_MUSIC_SAFE_RESEARCH) && SONKU_P75_MUSIC_SAFE_RESEARCH // Field-failure quarantine, opt-in ONLY: spatialize the MUSIC MID @@ -380,7 +414,7 @@ class SonKuSpatialCore final { smoothedRoomLevel_+=distanceSlew_* ((roomEnabled?1.12f:1.f)-smoothedRoomLevel_); smoothedBassShelf_+=distanceSlew_* - ((roomEnabled?0.82f:0.f)-smoothedBassShelf_); + ((roomEnabled && !p80Timbre?0.82f:0.f)-smoothedBassShelf_); // The original experimental return levels were intentionally // near-silent: ER base 0.28 * wall 0.70 * 1/r and diffuse FDN // output 0.23 * amount, followed by another 0.5 * trim. @@ -403,6 +437,14 @@ class SonKuSpatialCore final { float spatialR=smoothedDistanceGain_*ears[1]+ smoothedErPresence_*reflection.right+ smoothedTailPresence_*late.right; +#if defined(SONKU_P80_MEASURED_TIMBRE_RESEARCH) && SONKU_P80_MEASURED_TIMBRE_RESEARCH + if(p80Timbre) { + // Identical low-shelf on *measured* left/right binaural + // field. Excludes direct SIDE rescue; avoids double bass + // correction and preserves stereo anti-phase level. + timbre_.process(spatialL,spatialR); + } +#endif // Low-frequency KEMAR response is ~-7..-11 dB below 200Hz. // A gentle bounded *binaural* shelf restores warmth without // mixing dry mono under the HRIR or altering left/right ITD. @@ -557,6 +599,9 @@ class SonKuSpatialCore final { float smoothedBassShelf_=0.f,limiterGain_=1.f; float smoothedErPresence_=1.f,smoothedTailPresence_=1.f; std::array earBass_{}; +#if defined(SONKU_P80_MEASURED_TIMBRE_RESEARCH) && SONKU_P80_MEASURED_TIMBRE_RESEARCH + p80::MeasuredTimbreCalibration timbre_{}; +#endif float filterSlew_=0.f,levelSlew_=0.f; float distanceSlew_=0.f,bassSlew_=0.f,limiterRelease_=0.f; double sampleRate_=0.; diff --git a/scripts/sonku_p80_evidence.py b/scripts/sonku_p80_evidence.py new file mode 100644 index 000000000..af1d25bb5 --- /dev/null +++ b/scripts/sonku_p80_evidence.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""P8.0 quantitative DSP guard: compare exact-source P7.5 vs P8.0 PCM. +No dearVR recording is available in CI. This does NOT pass headphone parity. +Only Python stdlib and deterministic source tables, no fabricated audio data. +""" +import csv +import json +import math +import pathlib +import sys + +def rows(path, keys): + with path.open(encoding="utf-8", newline="") as stream: + result = list(csv.DictReader(stream)) + if not result: + raise ValueError(f"empty evidence: {path}") + index = {} + for row in result: + key = tuple(row[k] for k in keys) + if key in index: + raise ValueError(f"duplicate {key} in {path}") + for col, value in row.items(): + if col in keys or col in {"mode", "source", "room", "scene"}: + continue + if not math.isfinite(float(value)): + raise ValueError(f"nonfinite {col} in {path}: {row}") + index[key] = row + return index + +def safe_db(ratio): + if not math.isfinite(ratio) or ratio <= 0.: + raise ValueError(f"not a finite positive gain ratio: {ratio}") + return 20 * math.log10(ratio) + +def main(directory): + root = pathlib.Path(directory) + keys = ("source", "room", "azimuth", "frequency_hz") + base = rows(root/"sonku_P75_tone.csv", keys) + p80 = rows(root/"sonku_P80_tone.csv", keys) + if base.keys() != p80.keys(): + raise ValueError("P80 cases do not match P75 controls exactly") + room_base = rows(root/"sonku_P75_room.csv", ("scene",)) + room_p80 = rows(root/"sonku_P80_room.csv", ("scene",)) + if room_base.keys() != room_p80.keys(): + raise ValueError("room scenes do not match") + for k in room_base: + for p in (room_base[k], room_p80[k]): + for col in ("first20_energy", "early20_100_energy", "late100_1000_energy"): + if float(p[col]) < 0: + raise ValueError("negative energy") + report = {"status": "MEASUREMENT_ONLY_NOT_DEARVR_PARITY", + "source_cases": len(base), + "room_cases": len(room_base), + "reference": "P75 same-commit alternate C++ compile", + "tonal": {}, "side": {}, "room": {}} + def q(source, azimuth, hz, field): + k = (source, "OFF", str(azimuth), str(hz)) + if k not in base: + raise ValueError(f"missing {k}") + x, y = float(base[k][field]), float(p80[k][field]) + return safe_db(max(y, 1.e-12)/max(x, 1.e-12)) + + for azimuth in (0, 180): + freq_changes = {str(hz): q("MONO", azimuth, hz, "left_amp") + for hz in (80, 125, 250, 500, 1000, 2000, 4000, 8000)} + lf_rel_mid = freq_changes["125"] - freq_changes["1000"] + report["tonal"][str(azimuth)] = { + "ear_left_relative_db": freq_changes, + "LF125_vs_mid1000_improvement_db": lf_rel_mid, + } + # A measured common low shelf must be a measurable LF correction, + # not a broad mid gain or unrestricted +10 dB spectral patch. + if lf_rel_mid < 0.45 or lf_rel_mid > 5.0: + raise AssertionError(f"P8 LF target not proven: {azimuth}: {lf_rel_mid:.3f} dB") + if abs(freq_changes["8000"]) > 0.5: + raise AssertionError(f"P8 erroneously colors treble: {azimuth}") + if abs(freq_changes["1000"]) > 1.6: + raise AssertionError(f"P8 changes vocal mid too much: {azimuth}") + # An exact inverse-polarity source contains only SIDE; P8 must + # leave its level alone. (Tests still check the PCM sample bitflow.) + anti = [q("ANTIPHASE", azimuth, hz, "side_amp") for hz in (125, 1000, 4000)] + report["side"][str(azimuth)] = anti + if any(abs(value) > 0.04 for value in anti): + raise AssertionError(f"anti-phase SIDE changed by correction: {azimuth}: {anti}") + + for key, scene in room_p80.items(): + # rows() intentionally keys even one-column lookups by a tuple. + name = key[0] + report["room"][name] = { + key: float(scene[key]) for key in + ("first20_energy", "early20_100_energy", "late100_1000_energy") + } + dry = report["room"]["SCENE_DRY"] + er = report["room"]["SCENE_ER_ONLY"] + late = report["room"]["SCENE_LATE_ONLY"] + if er["early20_100_energy"] <= dry["early20_100_energy"] + 1.e-10: + raise AssertionError("six-wall reflection 20..100ms energy not observable") + if late["late100_1000_energy"] <= dry["late100_1000_energy"] + 1.e-10: + raise AssertionError("late FDN >100ms energy not observable") + report["status"] = "PASS_OBJECTIVE_SPECTRAL_STEREO_ROOM_PRESENCE_ONLY" + (root/"sonku_p80_evidence.json").write_text( + json.dumps(report, indent=2, sort_keys=True)+"\n", encoding="utf-8") + print(json.dumps({"status": report["status"], "tonal":report["tonal"], + "side":report["side"], "room":report["room"]}, + separators=(",", ":"), sort_keys=True)) + print("NOT TESTED: human music fidelity, naturalness, dearVR parity," + " actual ASIO XRUN, headphone/HRTF listener fit.") + return 0 + +if __name__ == "__main__": + if len(sys.argv) != 2: + raise SystemExit("usage: sonku_p80_evidence.py DIRECTORY") + raise SystemExit(main(sys.argv[1])) diff --git a/site/preview-v2/assets/mixer-native-sonku.js b/site/preview-v2/assets/mixer-native-sonku.js index 07fd02a61..9d96064a2 100644 --- a/site/preview-v2/assets/mixer-native-sonku.js +++ b/site/preview-v2/assets/mixer-native-sonku.js @@ -173,7 +173,7 @@ const depthLayers={far:$("skFarSources"),near:$("skNearSources")}; const mount=()=>{if(!root.isConnected)document.body.append(root)}; if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",mount,{once:true});else mount(); let current=null,accepted=defaults(),draft=defaults(),pending=null,latest=null, - xyzCapable=false,musicSafeStereo=false, + xyzCapable=false,musicSafeStereo=false,p80MeasuredTimbre=false, readId="",readSentAt=0,seq=1,clock=null,frame=null,observed=0,observedAt=0, drag=null,dialDrag=null,rangeEdits=new Set(),gestureStart=new Map(), visualPhase=0,visualAt=0,liveTimer=null,lastLiveAt=0; @@ -231,7 +231,9 @@ function render(){ if(!rangeEdits.has("skElevation"))elevation.value=String(s.directElevationDegrees); $("skElevationValue").textContent=s.directElevationDegrees.toFixed(1)+"°"; } - root.querySelector(".sk-stage-caption").textContent=musicSafeStereo + root.querySelector(".sk-stage-caption").textContent=p80MeasuredTimbre + ?"HEADPHONES · MEASURED TIMBRE · 3D KEMAR · RESEARCH" + :musicSafeStereo ?"HEADPHONES · MEASURED CENTER 3D HRTF + MUSIC SIDE · EXPERIMENT" :xyzCapable?"HEADPHONES · MEASURED 3D HRIR · 44.1 / 48 kHz" :"HEADPHONES · HRIR 0° ELEVATION · 44.1 / 48 kHz"; @@ -253,7 +255,8 @@ function render(){ // redrawn at 60 Hz. The native audio callback remains the time authority. drawSpeakers(); $("skMode").textContent=native()?(context()? - (musicSafeStereo?"NATIVE MUSIC SAFE · RESEARCH":"NATIVE HRTF"): + (p80MeasuredTimbre?"NATIVE TIMBRE P8.0 · RESEARCH": + musicSafeStereo?"NATIVE MUSIC SAFE · RESEARCH":"NATIVE HRTF"): "NATIVE UNAVAILABLE"):"VISUAL ONLY · NO AUDIO"; } function drawSpeakers(){ @@ -400,6 +403,9 @@ backend()?.addEventListener?.("arMixBuiltinSonKuSnapshot",r=>{ // Activation happens only after a fully identity-bound native readback. xyzCapable=measured; musicSafeStereo=measured && r.musicSafeStereo===true; + p80MeasuredTimbre=musicSafeStereo && r.measuredTimbre===true && + Number.isFinite(r.measuredTimbreShelfDb) && + r.measuredTimbreShelfDb>=0 && r.measuredTimbreShelfDb<=4.5001; readId="";readSentAt=0; if(pending) { if(!pending.ack || r.appliedRequestId!==pending.requestId){ @@ -422,7 +428,7 @@ backend()?.addEventListener?.("arMixBuiltinSonKuSnapshot",r=>{ } render(); }); -$("skClose").addEventListener("click",()=>{root.hidden=true;current=null;xyzCapable=false;musicSafeStereo=false; +$("skClose").addEventListener("click",()=>{root.hidden=true;current=null;xyzCapable=false;musicSafeStereo=false;p80MeasuredTimbre=false; cancelLiveTimer();pending=null;latest=null;readId="";readSentAt=0;dialDrag=null; drag=null;rangeEdits.clear();gestureStart.clear();lastLiveAt=0; if(clock!==null){clearInterval(clock);clock=null;} @@ -575,7 +581,7 @@ const api={ cancelLiveTimer();pending=null;latest=null;readId="";readSentAt=0;dialDrag=null; observedAt=0;visualAt=0;visualPhase=0;lastLiveAt=0; drag=null;rangeEdits.clear();gestureStart.clear(); - accepted=defaults();draft=defaults();xyzCapable=false;musicSafeStereo=false; + accepted=defaults();draft=defaults();xyzCapable=false;musicSafeStereo=false;p80MeasuredTimbre=false; current={track,slot,instanceId:null}; const s=snapshot(),id=window.__ARMIX_NATIVE_M2__?.nativeIdFor?.(track); const fx=s?.graph?.channels?.find(x=>x.id===id)?.inserts?.[slot]; diff --git a/src/Main.cpp b/src/Main.cpp index e3090f74e..5dd7f6a7f 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -3040,6 +3040,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(processor && processor->preparedReflectionProfile()== armix::sonku::SonKuReflectionProfile::SixSurfaceKemarResearch) reply->setProperty("musicSafeStereo",true); +#endif +#if defined(SONKU_P80_MEASURED_TIMBRE_RESEARCH) && SONKU_P80_MEASURED_TIMBRE_RESEARCH + if(processor && processor->preparedReflectionProfile()== + armix::sonku::SonKuReflectionProfile::SixSurfaceKemarResearch) { + reply->setProperty("measuredTimbre",true); + reply->setProperty("measuredTimbreShelfDb", + processor->preparedTimbreShelfDb()); + } #endif if(processor) { reply->setProperty("settings", diff --git a/tests/sonku_p80_acoustic_probe.cpp b/tests/sonku_p80_acoustic_probe.cpp new file mode 100644 index 000000000..5f9898dc3 --- /dev/null +++ b/tests/sonku_p80_acoustic_probe.cpp @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// P8.0 objective comparisons across exactly the real SonKuSpatialCore, +// compiled twice from the SAME commit (P7.5 baseline vs measured P8.0). +// Writes deterministic numbers only: no external audio, proprietary IR or +// fabricated subjective dearVR parity. Read with sonku_p80_evidence.py. +#include "../engine/builtin_fx/sonku/SonKuSpatialCore.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace armix::sonku; +constexpr double pi=3.141592653589793238462643; +static constexpr int fs=48000; +static constexpr float inputLevel=.095f; +#if defined(SONKU_P80_MEASURED_TIMBRE_RESEARCH) && SONKU_P80_MEASURED_TIMBRE_RESEARCH +static constexpr const char* mode="P80"; +#else +static constexpr const char* mode="P75"; +#endif + +static std::unique_ptr create(Settings s) { + auto core=std::make_unique(); + if(!core->prepare(fs,SonKuReflectionProfile::SixSurfaceKemarResearch) || + !core->setSettings(s))return {}; + core->reset(); + return core; +} +struct StereoTone { + double l=0.,r=0.,m=0.,s=0.; +}; +static double magnitude(double sinPart,double cosPart,int frames) { + return 2.*std::hypot(sinPart,cosPart)/frames; +} +static StereoTone tone(const Settings& s,double hz,int kind) { + auto core=create(s); + if(!core)std::abort(); + constexpr int warm=4096,measure=8192,frames=warm+measure; + std::array ss{},cc{}; + std::array left{},right{}; + for(int start=0;start(std::sin(2*pi*hz*at/fs)); + left[j]=kind==1?v:(kind==2?0.f:v); + right[j]=kind==1?-v:(kind==2?v:v); + } + core->process(left.data(),right.data(),128); + for(int j=0;j<128;++j){ + const int at=start+j; + if(at signals{ + left[j],right[j],(left[j]+right[j])*.5, + (left[j]-right[j])*.5}; + for(int k=0;k<4;++k){ + ss[k]+=signals[k]*si;cc[k]+=signals[k]*co; + } + } + } + return {magnitude(ss[0],cc[0],measure), + magnitude(ss[1],cc[1],measure), + magnitude(ss[2],cc[2],measure), + magnitude(ss[3],cc[3],measure)}; +} +struct Energies{double direct=0.,early=0.,tail=0.;}; +static Energies impulse(const Settings& s) { + auto core=create(s);if(!core)std::abort(); + constexpr int frames=48000,chunk=128; + std::array l{},r{}; + Energies e{}; + for(int start=0;startprocess(l.data(),r.data(),chunk); + for(int j=0;j freqs{80.,125.,250.,500.,1000.,2000.,4000.,8000.}; + for(const char* scene:{"FRONT","REAR"}) { + s.startAzimuthDegrees=std::string(scene)=="FRONT"?0.f:180.f; + for(int kind=0;kind<3;++kind) { + for(const auto hz:freqs){ + const auto result=tone(s,hz,kind); + csv<,4> rooms{{ + {{0.f,0.f}},{{.65f,0.f}},{{0.f,.45f}},{{.65f,.45f}} + }}; + const std::array labels{ + "SCENE_DRY","SCENE_ER_ONLY","SCENE_LATE_ONLY","SCENE_BOTH" + }; + for(std::size_t n=0;n +#include +#include +#include +#include +#include +using namespace armix::sonku; +constexpr float kPi=3.14159265358979323846f; +static void measuredBinaural(double rate){ + auto core=std::make_unique(); + assert(core->prepare(rate,SonKuReflectionProfile::SixSurfaceKemarResearch)); + const float boost=core->p80PreparedShelfDb(); + const float relative=core->p80MeasuredLowMinusMidDb(); + assert(std::isfinite(relative)&&std::isfinite(boost)); + assert(boost>=0.f&&boost<=4.5001f); + assert(std::abs(std::min(4.5f,std::max(0.f,-relative))-boost)<.003f); + std::printf("P80_CALIBRATION,rate=%.0f,LF125_MINUS_MID1000_DB=%.3f,PREPARED_SHELF_DB=%.3f\n", + rate,relative,boost); + // 0% SPATIAL MIX must remain a true stereo identity, even with P8. + Settings s{};s.moving=false;s.startAzimuthDegrees=0.f; + s.spatialMix=0.f;s.outputTrim=.65f; + assert(core->setSettings(s)); + core->reset(); // control-side prepared state, not a mid-callback edit + constexpr int n=2048;std::vector l(n),r(n); + for(int i=0;iprocess(l.data(),r.data(),n); + for(int i=0;isetSettings(s)); + core->reset(); + for(int i=0;iprocess(l.data(),r.data(),n); + for(int i=0;i(); + auto chunks=std::make_unique(); + assert(one->prepare(rate,SonKuReflectionProfile::SixSurfaceKemarResearch)); + assert(chunks->prepare(rate,SonKuReflectionProfile::SixSurfaceKemarResearch)); + assert(one->setSettings(s)&&chunks->setSettings(s)); + constexpr int frames=8192; + std::vector a(frames),b(frames),ca(frames),cb(frames); + for(int i=0;i(rate)); + const float side=.07f*std::sin(2.f*kPi*1900.f*i/static_cast(rate)); + a[i]=ca[i]=m+side;b[i]=cb[i]=m-side; + } + one->process(a.data(),b.data(),frames); + for(int j=0;jprocess(ca.data()+j,cb.data()+j,nblock); + j+=nblock; + } + double pow=0.; + for(int i=0;i0.1); +} +int main(){ + measuredBinaural(44100.); + measuredBinaural(48000.); + std::puts("PASS P8.0 measured KEMAR reference, bounded stereo-common EQ, dry and anti-phase invariants, ROOM/XYZ chunk parity"); +}