From 15c986b549a07b9153bd1588383e61d88aab492e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 14 Nov 2026 11:43:52 +0700 Subject: [PATCH 1/7] feat(sonku-p71): quiescent true-XYZ measured direct HRIR plus physically consistent six-surface elevation geometry --- .../builtin_fx/sonku/SonKuEarlyReflections.h | 43 +++++++++-- .../builtin_fx/sonku/SonKuSourcePlacement3D.h | 33 +++++++++ engine/builtin_fx/sonku/SonKuSpatialCore.h | 73 ++++++++++++++++++- .../sonku/SonKuVerticalImageSource.h | 10 +-- 4 files changed, 144 insertions(+), 15 deletions(-) create mode 100644 engine/builtin_fx/sonku/SonKuSourcePlacement3D.h diff --git a/engine/builtin_fx/sonku/SonKuEarlyReflections.h b/engine/builtin_fx/sonku/SonKuEarlyReflections.h index 26d496819..d9f4418d0 100644 --- a/engine/builtin_fx/sonku/SonKuEarlyReflections.h +++ b/engine/builtin_fx/sonku/SonKuEarlyReflections.h @@ -11,6 +11,9 @@ #if defined(SONKU_P7_MEASURED_ELEVATION_RESEARCH) && SONKU_P7_MEASURED_ELEVATION_RESEARCH #include "SonKuMeasuredHrir3D.h" #include "SonKuVerticalImageSource.h" +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH +#include "SonKuSourcePlacement3D.h" +#endif #endif // Bounded first-order image-source room (Allen & Berkley JASA, 1979). @@ -172,7 +175,11 @@ class SonKuEarlyReflections final { if(enabled && profile_==SonKuReflectionProfile::SixSurfaceKemarResearch && !sixsurface::fitsDelayRing( {g.heightMeters,g.listenerHeightMeters,g.sourceHeightMeters}, - g.distanceMeters,rate_,ringFrames,hrir::taps))return false; + (g.distanceMeters!=0.f? + std::sqrt(std::max(0.f,g.distanceMeters*g.distanceMeters- + (g.sourceHeightMeters-g.listenerHeightMeters)* + (g.sourceHeightMeters-g.listenerHeightMeters))):0.f), + rate_,ringFrames,hrir::taps))return false; #endif if(!active() && enabled && amount>0.f){ validFrames_=0; lowpass_.fill(0.f); @@ -339,6 +346,17 @@ class SonKuEarlyReflections final { void updateGeometry(double azimuth,float spread) noexcept { constexpr float pi=3.14159265358979323846f; const float sourceDistance=custom_?geometry_.distanceMeters:1.60f; + // The existing four-wall path stays bit-exact at equal source/ear + // height. Only explicitly enabled research geometry projects true XYZ. + float horizontalDistance=sourceDistance,dz=0.f; +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH + if(profile_==SonKuReflectionProfile::SixSurfaceKemarResearch && + geometry_.sourceHeightMeters!=geometry_.listenerHeightMeters) { + dz=geometry_.sourceHeightMeters-geometry_.listenerHeightMeters; + horizontalDistance=std::sqrt(std::max(0.f, + sourceDistance*sourceDistance-dz*dz)); + } +#endif // Preserve the approved 7.2m/1.6m path exactly when custom_ is false. // A wider room changes physical image paths, not KEMAR azimuth signs. const float halfWidth=custom_?geometry_.widthMeters*.5f: @@ -354,16 +372,18 @@ class SonKuEarlyReflections final { const float degrees=static_cast(azimuth) +(source==0?-.5f:.5f)*spread; const float rad=degrees*(pi/180.f); - const float sx=sourceDistance*std::sin(rad); - const float sy=sourceDistance*std::cos(rad); + const float sx=horizontalDistance*std::sin(rad); + const float sy=horizontalDistance*std::cos(rad); const std::array,wallCount> images{{ {{-2.f*halfWidth-sx,sy}},{{2.f*halfWidth-sx,sy}}, {{sx,2.f*halfDepth-sy}},{{sx,-2.f*halfDepth-sy}} }}; for(int wall=0;wall(pos),0, hrir::directions-1); @@ -400,6 +430,7 @@ class SonKuEarlyReflections final { if(!primed_)tap.kernel[ear][k]=value; } } + } } if(!primed_){ tap.delayL=tap.targetDelayL; @@ -421,7 +452,7 @@ class SonKuEarlyReflections final { const auto boundary=i==0?sixsurface::Boundary::Floor: sixsurface::Boundary::Ceiling; const auto arrival=sixsurface::image( - heights,sourceDistance,sourceAz,boundary,rate_); + heights,horizontalDistance,sourceAz,boundary,rate_); auto& p=tap_[source][wallCount+i]; // Measured HRIR already contains directional ITD/ILD. // No invented extra ear delay, EQ or pseudo elevation. diff --git a/engine/builtin_fx/sonku/SonKuSourcePlacement3D.h b/engine/builtin_fx/sonku/SonKuSourcePlacement3D.h new file mode 100644 index 000000000..74f87f4ba --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuSourcePlacement3D.h @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +// Exact source-to-listener spherical -> Cartesian geometry, research only. +// No new parameter/schema; this is a quiescent off-line native DSP control. +#include +#include +namespace armix::sonku::xyz { +struct Placement { + float horizontalMeters=1.6f; + float sourceHeightMeters=1.45f; + float heightDeltaMeters=0.f; + float directDistanceMeters=1.6f; +}; +inline bool project(float radialMeters,float elevationDegrees, + float listenerHeight,float roomHeight, + Placement& result) noexcept { + if(!std::isfinite(radialMeters)||!std::isfinite(elevationDegrees)|| + !std::isfinite(listenerHeight)||!std::isfinite(roomHeight)|| + radialMeters<1.6f||radialMeters>10.f|| + elevationDegrees< -40.f||elevationDegrees>60.f|| + roomHeight<2.4f||roomHeight>12.f|| + listenerHeight<.5f||listenerHeight>roomHeight-.5f)return false; + constexpr float radians=.017453292519943295769f; + const float z=radialMeters*std::sin(elevationDegrees*radians); + const float horizontal=radialMeters*std::cos(elevationDegrees*radians); + const float height=listenerHeight+z; + if(height<.5f||height>roomHeight-.5f||horizontal<.7f)return false; + const float distance=std::hypot(horizontal,z); + if(!(distance>0.f)||!std::isfinite(distance))return false; + result={horizontal,height,z,radialMeters}; + return true; +} +} // namespace armix::sonku::xyz diff --git a/engine/builtin_fx/sonku/SonKuSpatialCore.h b/engine/builtin_fx/sonku/SonKuSpatialCore.h index c56c3fe02..3867748d0 100644 --- a/engine/builtin_fx/sonku/SonKuSpatialCore.h +++ b/engine/builtin_fx/sonku/SonKuSpatialCore.h @@ -4,6 +4,9 @@ #include "SonKuEarlyReflections.h" #include "SonKuMusicalReverb.h" #include "SonKuStereoIntegrity.h" +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH +#include "SonKuSourcePlacement3D.h" +#endif #include #include #include @@ -75,6 +78,12 @@ class SonKuSpatialCore final { distanceSlew_=static_cast(1.-std::exp(-1./(rate*0.030))); bassSlew_=static_cast(1.-std::exp(-2.*3.14159265358979323846*180./rate)); limiterRelease_=static_cast(1./(rate*0.080)); +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH + // The special elevation control is not serialized or published to + // a public host. Downgrading the prepared profile clears it. + if(profile!=SonKuReflectionProfile::SixSurfaceKemarResearch) + researchElevationDegrees_=0.f; +#endif if(!room_.prepare(rate,profile)||!reverb_.prepare(rate)|| !integrity_.prepare(rate))return false; reset(); @@ -102,6 +111,9 @@ class SonKuSpatialCore final { degrees_=wrapDegrees(settings_.startAzimuthDegrees); haveKernel_=false; room_.reset(); +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH + researchPcmStarted_=false; +#endif reverb_.reset(); integrity_.reset(); } @@ -126,6 +138,31 @@ class SonKuSpatialCore final { return true; } Settings settings() const noexcept {return settings_;} +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH + // Only quiescent, unpublished *research* cores may change source XYZ. + // This is intentionally NOT a new FX/state/UI/ACK field. No race with + // a live PCM callback and no possibility of hidden session mutations. + bool setResearchDirectElevation(float degrees) noexcept { + if(!ready_||researchPcmStarted_|| + room_.preparedProfile()!=SonKuReflectionProfile::SixSurfaceKemarResearch) + return false; + xyz::Placement projected{}; + const float h=settings_.spacePreset==1?3.2f: + settings_.spacePreset==2?4.8f:7.2f; + if(!xyz::project(settings_.sourceDistanceMeters,degrees,1.45f,h,projected)) + return false; + const float old=researchElevationDegrees_; + researchElevationDegrees_=degrees; + if(!applyAcousticSettings(settings_)) { + researchElevationDegrees_=old; + return false; + } + remaining_=0; + haveKernel_=false; + return true; + } + float researchDirectElevation() const noexcept {return researchElevationDegrees_;} +#endif // A/B-only control pending room's headphone/device qualification. // Legacy live insert remains room-free until product evidence is accepted. bool setEarlyReflectionsAmount(float amount) noexcept { @@ -168,6 +205,9 @@ class SonKuSpatialCore final { // No vector, heap, blocking calls, I/O or filter bank allocation. void process(float* left,float* right,int samples) noexcept { if(!ready_ || !left || !right || samples<=0)return; +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH + researchPcmStarted_=true; +#endif const double step=(settings_.moving ? (settings_.clockwise?1.:-1.)*360./(sampleRate_*settings_.revolutionSeconds) : 0.); const float distanceGain=room_.relativeDistanceGain(); @@ -315,12 +355,22 @@ class SonKuSpatialCore final { bool applyAcousticSettings(const Settings& s) noexcept { const float width=s.spacePreset==1?7.2f: s.spacePreset==2?14.4f:28.8f; + const float roomHeight=s.spacePreset==1?3.2f: + s.spacePreset==2?4.8f:7.2f; + float sourceHeight=1.45f; +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH + if(room_.preparedProfile()==SonKuReflectionProfile::SixSurfaceKemarResearch){ + xyz::Placement xyzSource{}; + if(!xyz::project(s.sourceDistanceMeters,researchElevationDegrees_, + 1.45f,roomHeight,xyzSource))return false; + sourceHeight=xyzSource.sourceHeightMeters; + } +#endif const SonKuRoomGeometry geometry{ width,width,s.spacePreset? s.sourceDistanceMeters:1.6f, - // The P7 research room is 3D; public P6/legacy do not - // read the additional height fields. - s.spacePreset==1?3.2f:s.spacePreset==2?4.8f:7.2f, - 1.45f,1.45f}; + // P7.1 keeps the user's radial source distance authoritative. + // Source XYZ only affects the explicit offline research profile. + roomHeight,1.45f,sourceHeight}; const auto preset=s.spacePreset==3?SonKuReverbPreset::LargeRoom: s.spacePreset==2?SonKuReverbPreset::AiryChamber: SonKuReverbPreset::StudioGlue; @@ -332,6 +382,17 @@ class SonKuSpatialCore final { // symmetric opposite-ear swapping for left hemisphere, not yaw-panning. using EarKernel=std::array,2>; void interpolate(EarKernel& destination,double azimuth) noexcept { +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH + if(room_.preparedProfile()==SonKuReflectionProfile::SixSurfaceKemarResearch && + researchElevationDegrees_!=0.f){ + // Both stereo emitters AND the coherent MID correction use the + // very same truly measured direct elevation, no third FIR. + hrir3d::interpolate(static_cast(azimuth), + researchElevationDegrees_, + std::abs(sampleRate_-44100.)<=.1,destination); + return; + } +#endif const double norm=wrapDegrees(azimuth); const bool swapped=norm>180.; const double positive=swapped?360.-norm:norm; @@ -407,5 +468,9 @@ class SonKuSpatialCore final { bool ready_=false; bool haveKernel_=false; bool nativeSpaceEverUsed_=false; +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH + float researchElevationDegrees_=0.f; + bool researchPcmStarted_=false; +#endif }; } // namespace armix::sonku diff --git a/engine/builtin_fx/sonku/SonKuVerticalImageSource.h b/engine/builtin_fx/sonku/SonKuVerticalImageSource.h index 362f025e0..824e7ff7a 100644 --- a/engine/builtin_fx/sonku/SonKuVerticalImageSource.h +++ b/engine/builtin_fx/sonku/SonKuVerticalImageSource.h @@ -20,9 +20,7 @@ inline bool validHeight(RoomHeight g) noexcept { std::isfinite(g.source) && g.room>=2.4f&&g.room<=12.f&& g.listener>=.5f&&g.source>=.5f&& g.listener<=g.room-.5f&&g.source<=g.room-.5f&& - // Until direct elevation HRTF is published, the source is at - // listener ear height. Do not claim a true elevated DIRECT source. - std::abs(g.source-g.listener)<1.e-4f; + true; // P7.1 may admit validated true XYZ source placement. } inline Arrival image(const RoomHeight g,float horizontalDistance, float azimuthDegrees,Boundary boundary,float sampleRate) noexcept { @@ -34,14 +32,16 @@ inline Arrival image(const RoomHeight g,float horizontalDistance, const float z=boundary==Boundary::Floor ?-g.source-g.listener:(2.f*g.room-g.source-g.listener); const float path=std::sqrt(x*x+y*y+z*z); + const float direct=std::hypot(horizontalDistance,g.source-g.listener); return {azimuthDegrees,std::atan2(z,horizontalDistance)*180.f/pi, - path,(path-horizontalDistance)*sampleRate/soundSpeed, + path,(path-direct)*sampleRate/soundSpeed, .28f*.70f*(1.6f/path)}; } inline bool fitsDelayRing(RoomHeight g,float horizontalDistance, float rate,int ringFrames,int firTaps) noexcept { if(!validHeight(g)||!std::isfinite(horizontalDistance)|| - horizontalDistance<1.6f||horizontalDistance>10.f)return false; + horizontalDistance<.7f||horizontalDistance>10.f||!std::isfinite(rate)|| + rate<44099.9f||rate>48000.1f)return false; const auto a=image(g,horizontalDistance,0.f,Boundary::Floor,rate); const auto b=image(g,horizontalDistance,0.f,Boundary::Ceiling,rate); return std::max(a.delaySamples,b.delaySamples) Date: Sat, 14 Nov 2026 11:45:36 +0700 Subject: [PATCH 2/7] test(sonku-p71): validate measured XYZ direct and six-boundary PCM and render twelve headphone WAVs --- .github/workflows/sonku-p7-research.yml | 9 ++ tests/sonku_p71_xyz_direct_test.cpp | 119 ++++++++++++++++++++++++ tests/sonku_p7_six_surface_test.cpp | 3 +- tools/sonku_offline_listening.cpp | 47 +++++++++- 4 files changed, 174 insertions(+), 4 deletions(-) create mode 100644 tests/sonku_p71_xyz_direct_test.cpp diff --git a/.github/workflows/sonku-p7-research.yml b/.github/workflows/sonku-p7-research.yml index bb532fe36..64e05c43f 100644 --- a/.github/workflows/sonku-p7-research.yml +++ b/.github/workflows/sonku-p7-research.yml @@ -7,6 +7,7 @@ on: paths: - 'engine/builtin_fx/sonku/**' - 'tests/sonku_p7_*' + - 'tests/sonku_p71_*' - 'tools/sonku_offline_listening.cpp' - 'tools/sonku_p7_cpu.cpp' - '.github/workflows/sonku-p7-research.yml' @@ -47,12 +48,20 @@ jobs: run: | g++ -std=c++20 -O2 -Wall -Wextra -pedantic -DSONKU_P7_MEASURED_ELEVATION_RESEARCH=1 tests/sonku_p7_six_surface_test.cpp -o /tmp/p7 /tmp/p7 + - name: P7.1 true XYZ source direct HRTF 44.1/48k and phase-safe spatial PCM + run: | + g++ -std=c++20 -O2 -Wall -Wextra -pedantic -DSONKU_P7_MEASURED_ELEVATION_RESEARCH=1 -DSONKU_P71_DIRECT_XYZ_RESEARCH=1 tests/sonku_p71_xyz_direct_test.cpp -o /tmp/p71 + /tmp/p71 - name: Four matched P6 four-wall versus P7 six-plane realtime ROOM WAV pairs run: | g++ -std=c++20 -O2 -Wall -Wextra -pedantic -DSONKU_P7_MEASURED_ELEVATION_RESEARCH=1 tools/sonku_offline_listening.cpp -o /tmp/p7-render mkdir -p sonku-p7-evidence /tmp/p7-render sonku-p7-evidence --p7-six-surface-only python tests/sonku_p7_six_surface_audio_audit.py sonku-p7-evidence + - name: P7.1 measured direct elevation original same-source 12 WAVs + run: | + g++ -std=c++20 -O2 -Wall -Wextra -pedantic -DSONKU_P7_MEASURED_ELEVATION_RESEARCH=1 -DSONKU_P71_DIRECT_XYZ_RESEARCH=1 tools/sonku_offline_listening.cpp -o /tmp/p71-render + /tmp/p71-render sonku-p7-evidence --p71-xyz-direct-only - name: Informational CPU 1/2/4 inserts P6 versus P7 48k/128 run: | g++ -std=c++20 -O2 -Wall -Wextra -pedantic -DSONKU_P7_MEASURED_ELEVATION_RESEARCH=1 tools/sonku_p7_cpu.cpp -o /tmp/p7-bench diff --git a/tests/sonku_p71_xyz_direct_test.cpp b/tests/sonku_p71_xyz_direct_test.cpp new file mode 100644 index 000000000..83990c5d7 --- /dev/null +++ b/tests/sonku_p71_xyz_direct_test.cpp @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#if defined(NDEBUG) +#undef NDEBUG +#endif +#if !defined(SONKU_P7_MEASURED_ELEVATION_RESEARCH) || !defined(SONKU_P71_DIRECT_XYZ_RESEARCH) +#error P7.1 true XYZ measurement must be tested under both research flags +#endif +#include "../engine/builtin_fx/sonku/SonKuSpatialCore.h" +#include +#include +#include +#include +#include +#include +int main(){ + using namespace armix::sonku; + constexpr float pi=3.14159265358979323846f; + for(double rate:{44100.,48000.}){ + for(float elev:{-25.f,0.f,25.f,45.f}){ + xyz::Placement projected{}; + assert(xyz::project(1.6f,elev,1.45f,3.2f,projected)); + assert(std::abs(std::hypot(projected.horizontalMeters, + projected.heightDeltaMeters)-1.6f)<1e-5f); + assert(std::abs(projected.sourceHeightMeters- + (1.45f+projected.heightDeltaMeters))<1e-6f); + assert(sixsurface::validHeight({3.2f,1.45f,projected.sourceHeightMeters})); + const float az=75.f; + const auto floor=sixsurface::image( + {3.2f,1.45f,projected.sourceHeightMeters},projected.horizontalMeters, + az,sixsurface::Boundary::Floor,static_cast(rate)); + const auto ceil=sixsurface::image( + {3.2f,1.45f,projected.sourceHeightMeters},projected.horizontalMeters, + az,sixsurface::Boundary::Ceiling,static_cast(rate)); + assert(floor.elevation<0.f&&ceil.elevation>0.f); + assert(floor.delaySamples>0.f&&ceil.delaySamples>0.f); + assert(floor.pathMeters>1.6f&&ceil.pathMeters>1.6f); + assert(sixsurface::fitsDelayRing( + {3.2f,1.45f,projected.sourceHeightMeters},projected.horizontalMeters, + static_cast(rate),8192,140)); + } + xyz::Placement rejected{}; + for(float invalid:{-40.f,60.f,75.f}) { + assert(!xyz::project(1.6f,invalid,1.45f,3.2f,rejected)); + } + assert(!xyz::project(1.6f,NAN,1.45f,3.2f,rejected)); + assert(!xyz::project(10.f,25.f,1.45f,3.2f,rejected)); + assert(!xyz::project(1.6f,25.f,1.45f,2.f,rejected)); + // Real measured direct HRTF, not synthetic equalization; ear mirror. + for(float elevation:{-25.f,25.f,45.f}){ + hrir3d::EarBank left{},right{},horizontal{}; + hrir3d::interpolate(73.f,elevation,rate==44100.,left); + hrir3d::interpolate(-73.f,elevation,rate==44100.,right); + hrir3d::interpolate(73.f,0.f,rate==44100.,horizontal); + double difference=0.; + for(int ear=0;ear<2;++ear) + for(int k=0;k.05); + } + for(float elev:{-25.f,25.f,45.f}){ + for(float spread:{0.f,60.f}){ + auto base=std::make_unique(); + auto exact=std::make_unique(); + auto chunks=std::make_unique(); + assert(base->prepare(rate,SonKuReflectionProfile::SixSurfaceKemarResearch)); + assert(exact->prepare(rate,SonKuReflectionProfile::SixSurfaceKemarResearch)); + assert(chunks->prepare(rate,SonKuReflectionProfile::SixSurfaceKemarResearch)); + assert(exact->setResearchDirectElevation(elev)); + assert(chunks->setResearchDirectElevation(elev)); + assert(!exact->setResearchDirectElevation(-40.f)); // impossible room + assert(exact->researchDirectElevation()==elev); + Settings s{}; + s.startAzimuthDegrees=33.f;s.moving=true;s.revolutionSeconds=3.1f; + s.stereoSpreadDegrees=spread;s.spacePreset=1;s.roomAmount=.6f; + s.ambience=.15f;s.sourceDistanceMeters=1.6f;s.outputTrim=.55f; + assert(base->setSettings(s)&&exact->setSettings(s)&&chunks->setSettings(s)); + constexpr int length=16384; + std::array la{},ra{},lb{},rb{},lc{},rc{}; + for(int i=0;i(i/rate); + const float bass=.12f*std::sin(2.f*pi*220.f*t); + const float treble=.06f*std::sin(2.f*pi*3200.f*t); + const float voice=.03f*std::sin(2.f*pi*550.f*t); + la[i]=lb[i]=lc[i]=bass+treble+voice; + ra[i]=rb[i]=rc[i]=bass-treble+.7f*voice; + } + base->process(la.data(),ra.data(),length); + exact->process(lb.data(),rb.data(),length); + for(int at=0;atprocess(lc.data()+at,rc.data()+at,n);at+=n; + } + double energy=0.,difference=0.,early=0.; + for(int i=0;i=48 && i<400)early+=std::abs(lb[i]-la[i])+std::abs(rb[i]-ra[i]); + } + assert(energy>.01&&difference>.1&&early>1e-5); + assert(!exact->setResearchDirectElevation(0.f)); // never mutate running PCM + assert(exact->researchDirectElevation()==elev); + assert(std::abs(exact->azimuthDegrees()-chunks->azimuthDegrees())<1e-7); + // Device re-prepare uses the same explicit research placement, + // but a switch to P6 clears research-only elevation. + assert(exact->prepare(rate,SonKuReflectionProfile::SixSurfaceKemarResearch)); + assert(exact->researchDirectElevation()==elev); + assert(exact->prepare(rate,SonKuReflectionProfile::DirectionalKemar)); + assert(exact->researchDirectElevation()==0.f); + assert(!exact->setResearchDirectElevation(25.f)); + } + } + } + std::puts("PASS SonKu P7.1 true XYZ: measured direct/room, bounded placement, mirrored HRTF, 44.1/48k, 64/257 PCM, quiescent-only control"); +} diff --git a/tests/sonku_p7_six_surface_test.cpp b/tests/sonku_p7_six_surface_test.cpp index 9c8d20780..f4bddf348 100644 --- a/tests/sonku_p7_six_surface_test.cpp +++ b/tests/sonku_p7_six_surface_test.cpp @@ -43,7 +43,8 @@ int main(){ const auto h=sixsurface::RoomHeight{3.2f,1.45f,1.45f}; assert(sixsurface::validHeight(h)); assert(!sixsurface::validHeight({2.0f,1.45f,1.45f})); - assert(!sixsurface::validHeight({3.2f,1.45f,1.65f})); + assert(sixsurface::validHeight({3.2f,1.45f,1.65f})); + assert(!sixsurface::validHeight({3.2f,1.45f,2.85f})); assert(sixsurface::fitsDelayRing(h,1.6f,rate,8192,140)); auto floor=sixsurface::image(h,1.6f,0.f,sixsurface::Boundary::Floor, static_cast(rate)); diff --git a/tools/sonku_offline_listening.cpp b/tools/sonku_offline_listening.cpp index bc91986b2..f2ec5d4ce 100644 --- a/tools/sonku_offline_listening.cpp +++ b/tools/sonku_offline_listening.cpp @@ -406,7 +406,8 @@ std::vector directionalRoomAudio(int azimuth,bool measured, // Same source and saved user scene, light vs opt-in P2/P3/P4 full KEMAR. // Unlike P2 offline setAmount fixtures this exercises native setRealtimeRoom. std::vector realtimeRoomAudio(int azimuth,float spread, - bool directional,bool sixSurface=false){ + bool directional,bool sixSurface=false, + float directElevation=0.f){ SonKuSpatialCore dsp; auto profile=directional ?armix::sonku::SonKuReflectionProfile::DirectionalKemar @@ -418,6 +419,13 @@ std::vector realtimeRoomAudio(int azimuth,float spread, #endif if(!dsp.prepare(rate,profile)) throw std::runtime_error("P6 native profile prepare failed"); +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH + if(directElevation!=0.f && !dsp.setResearchDirectElevation(directElevation)) + throw std::runtime_error("P7.1 room placement rejected"); +#else + if(directElevation!=0.f) + throw std::runtime_error("P7.1 research is compiled out"); +#endif Settings scene=fixed(static_cast(azimuth)); scene.spacePreset=1;scene.sourceDistanceMeters=1.6f; scene.roomAmount=.65f;scene.ambience=.20f; @@ -497,6 +505,31 @@ void writeP7SixSurfaceAudio(const std::filesystem::path& dir){ <<"Not a proof of natural externalization or preference.\n"; } #endif +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH +void writeP71DirectXyzAudio(const std::filesystem::path& dir){ + for(int azimuth:{0,180}){ + const std::string side=azimuth==0?"front":"rear"; + for(int spread:{0,60}){ + const std::string name=side+"-spread"+std::to_string(spread); + writeWav(dir/("sonku-p71-horizontal-"+name+".wav"), + realtimeRoomAudio(azimuth,static_cast(spread),true,true,0.f)); + writeWav(dir/("sonku-p71-up25-"+name+".wav"), + realtimeRoomAudio(azimuth,static_cast(spread),true,true,25.f)); + writeWav(dir/("sonku-p71-down25-"+name+".wav"), + realtimeRoomAudio(azimuth,static_cast(spread),true,true,-25.f)); + } + } + std::ofstream guide(dir/"P71-DIRECT-XYZ-HEADPHONE-AB.txt"); + if(!guide)throw std::runtime_error("P7.1 headphone guide unavailable"); + guide<<"12 original 3s 48k/16bit stereo WAVs: 4 matched A/B/C scenes.\\n" + <<"Horizontal direct=0°, elevated direct +25°, lowered direct -25°.\\n" + <<"Actual measured MIT KEMAR DIRECT HRIR and all six first-order room\\n" + <<"image sources are geometrically consistent. FRONT/REAR, spread 0/60.\\n" + <<"Same independent bass + inverted treble musical source and gain.\\n" + <<"No proprietary dearVR data, personalized HRTF or head tracking.\\n" + <<"Headphones only, safe playback, disable OS spatial effects.\\n"; +} +#endif void writeP4ContiguousAudio(const std::filesystem::path& dir){ for(int azimuth:{0,180}){ const std::string side=azimuth==0?"front":"rear"; @@ -587,12 +620,20 @@ int main(int argc,char** argv){ std::string(argv[2])=="--p3-fusion-only" || std::string(argv[2])=="--p4-contiguous-only" || std::string(argv[2])=="--p6-realtime-only" || - std::string(argv[2])=="--p7-six-surface-only"))) + std::string(argv[2])=="--p7-six-surface-only" || + std::string(argv[2])=="--p71-xyz-direct-only"))) throw std::runtime_error("Usage: sonku-offline-demo OUTPUT_DIRECTORY [--music-integrity-only]"); const std::filesystem::path dir(argv[1]); std::filesystem::create_directories(dir); if(argc==3){ - if(std::string(argv[2])=="--p7-six-surface-only") { + if(std::string(argv[2])=="--p71-xyz-direct-only") { +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH + writeP71DirectXyzAudio(dir); + std::cout<<"P71 direct XYZ 12 measured-Elevation A/B/C WAV rendered\\n"; +#else + throw std::runtime_error("P7.1 direct XYZ research not compiled"); +#endif + } else if(std::string(argv[2])=="--p7-six-surface-only") { #if defined(SONKU_P7_MEASURED_ELEVATION_RESEARCH) && SONKU_P7_MEASURED_ELEVATION_RESEARCH writeP7SixSurfaceAudio(dir); std::cout<<"P7 six-surface original 8 WAV rendered\n"; From ff5093e2cc1f322e45ba776c7ccf754680717d70 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 14 Nov 2026 11:48:11 +0700 Subject: [PATCH 3/7] =?UTF-8?q?test(sonku-p71):=20measure=20direct=20XYZ?= =?UTF-8?q?=20musical=20tonality,=20ILD/phase=20and=201=E2=80=934=20instan?= =?UTF-8?q?ce=20callback=20cost?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/sonku-p7-research.yml | 7 ++ ...P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md | 56 +++++++++++ tests/sonku_p71_xyz_audio_audit.py | 99 +++++++++++++++++++ tools/sonku_p7_cpu.cpp | 27 ++++- 4 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 docs/SONKU_P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md create mode 100644 tests/sonku_p71_xyz_audio_audit.py diff --git a/.github/workflows/sonku-p7-research.yml b/.github/workflows/sonku-p7-research.yml index 64e05c43f..4398b8cfb 100644 --- a/.github/workflows/sonku-p7-research.yml +++ b/.github/workflows/sonku-p7-research.yml @@ -62,10 +62,17 @@ jobs: run: | g++ -std=c++20 -O2 -Wall -Wextra -pedantic -DSONKU_P7_MEASURED_ELEVATION_RESEARCH=1 -DSONKU_P71_DIRECT_XYZ_RESEARCH=1 tools/sonku_offline_listening.cpp -o /tmp/p71-render /tmp/p71-render sonku-p7-evidence --p71-xyz-direct-only + - name: P7.1 measure same-source XYZ direct stereo musical integrity / per-ear acoustics + run: | + python tests/sonku_p71_xyz_audio_audit.py sonku-p7-evidence - name: Informational CPU 1/2/4 inserts P6 versus P7 48k/128 run: | g++ -std=c++20 -O2 -Wall -Wextra -pedantic -DSONKU_P7_MEASURED_ELEVATION_RESEARCH=1 tools/sonku_p7_cpu.cpp -o /tmp/p7-bench /tmp/p7-bench | tee sonku-p7-evidence/SONKU-P7-CPU-REPORT.txt + - name: Informational P7.1 direct XYZ CPU 1/2/4 inserts, 0/+25/-25 degrees + run: | + g++ -std=c++20 -O2 -Wall -Wextra -pedantic -DSONKU_P7_MEASURED_ELEVATION_RESEARCH=1 -DSONKU_P71_DIRECT_XYZ_RESEARCH=1 tools/sonku_p7_cpu.cpp -o /tmp/p71-bench + /tmp/p71-bench | grep SONKU_P71_CPU | tee sonku-p7-evidence/SONKU-P71-CPU-REPORT.txt - name: Upload 8 matched lossless WAV and JSON/CPU evidence if: ${{ always() }} uses: actions/upload-artifact@v4 diff --git a/docs/SONKU_P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md b/docs/SONKU_P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md new file mode 100644 index 000000000..f2df96bd9 --- /dev/null +++ b/docs/SONKU_P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md @@ -0,0 +1,56 @@ +# SonKu P7.1 — source XYZ / measured DIRECT HRTF, experiment + +2026-11-14 | stacked PR #681 → P7 #679 → P6 #678 → P0–P5 #674. +**This milestone is research implementation, not Windows ASIO or dearVR +parity certification.** No main/installer change. + +## Physics, source of truth and control-plane safety + +The 44.1k/48k MIT KEMAR 14-band measurement bank already pinned in P7 +is reused for the **direct** binaural FIR (L/R emitters *and* coherent +MID correction) with no extra convolution or per-tap magic EQ. +Source radial distance remains the original accepted 1.6–10m, projected +at a measured elevation to horizontal distance = r*cos(theta) and +source height = earHeight + r*sin(theta). First-order wall image sources +use (x,y,z) path length, arrival elevation/azimuth and measured KEMAR +coefficients, while floor/ceiling images use the true reflected source +height and subtract the **3D source radial path**, not an incorrect +horizontal-only direct distance. At elevation 0, original four walls, +P7 vertical reflections and direct measured horizontal bank are preserved. + +A single `SonKuSpatialCore::setResearchDirectElevation()` accepts only +a pre-prepared `SixSurfaceKemarResearch` instance before *any* PCM +has been processed, validates source clearance within the current +3D room, rejects NaN and impossible positions, and does not add a +public FX parameter, .smix version, GUI gesture or audio callback mutation. +It is guarded by BOTH `SONKU_P7_MEASURED_ELEVATION_RESEARCH=1` +and `SONKU_P71_DIRECT_XYZ_RESEARCH=1`; neither appears in public JUCE. +Per-frame FIR tap count remains 140; moving source orientation is the +original azimuth clock and the new elevation is constant within a +quiescent research render. A real user-controllable XYZ scene requires +a **separate approved host UI/state/ACK design**, not an invisible knob. + +## Evidence and disqualifiers + +The native CI covers 44.1/48k, true distance projection, room-clearance +rejection, above/below path geometry and direct HRIR ear mirror, +mid/side phase and chunk-parity with 64/257 irregular partitions, +no post-publish changes, and prepared restart/downgrade to P6. +A/B/C 12 lossless original source 48k stereo WAVs compare horizontal +versus +25°/-25° direct placement in FRONT/REAR and 0/60° spread. +Goertzel offline instrument evidence measures 220/660/940/3200/4700Hz +per-ear level, interaural level and phase, flags significant spectral +changes for human review; these are not perceptual quality scores. + +Performance measurement is only same-runner Linux C++ timing of 1/2/4 +concurrent stereo instances; the new measured-elevation interpolation +updates every 16 direct/64 reflection PCM frames and introduces no new +FIR in the callback. This **does not** qualify p99/XRUN on physical ASIO. +No hidden adaptive DSP mode switch, plugin duplication, bit-depth +truncation, per-buffer heap/clock, synchronous logging or background work. + +P7.1 source-level milestone can be marked complete after the exact +CI SHA passes, but public feature remains vetoed until actual +Windows ASIO, performance headroom, author-approved FX/UX workflow, +.lsmix/.smix persistence and headphone blind tests versus dearVR are +satisfactory. Do not merge stacked drafts prematurely. diff --git a/tests/sonku_p71_xyz_audio_audit.py b/tests/sonku_p71_xyz_audio_audit.py new file mode 100644 index 000000000..4740b01a2 --- /dev/null +++ b/tests/sonku_p71_xyz_audio_audit.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""P7.1: same stereo source, fixed gain, three DIRECT elevation angles. +Only numeric diagnostics; musical preference/externalization needs human A/B. +No numpy and no audio generation in this audit: WAVs are native C++ outputs. +""" +import json +import math +import pathlib +import struct +import sys +import wave + +RATE=48000 +FRAMES=RATE*3 +FREQUENCIES=(220,660,940,3200,4700) +def read(path): + with wave.open(str(path),'rb') as wav: + shape=(wav.getnchannels(),wav.getsampwidth(), + wav.getframerate(),wav.getnframes()) + if shape!=(2,2,RATE,FRAMES): + raise AssertionError(f'unexpected P7.1 source WAV {path}: {shape}') + buf=wav.readframes(FRAMES) + return struct.unpack('<'+'h'*(len(buf)//2),buf) + +def spectral(pcm,ear,frequency): + # Goertzel at an exact 1-second integer-bin frequency; no FFT dependency. + phase=2*math.pi*frequency/RATE + a=2*math.cos(phase) + p1=p2=0. + for frame in range(RATE,2*RATE): + x=pcm[2*frame+ear]/32768. + q=x+a*p1-p2 + p2,p1=p1,q + re=p1-p2*math.cos(phase) + im=p2*math.sin(phase) + return 2*math.hypot(re,im)/RATE,math.atan2(im,re) +def delta_phase(a,b): + return (a-b+math.pi)%(2*math.pi)-math.pi +def rms_delta(a,b,begin): + count=2*(FRAMES-begin) + return math.sqrt(sum(((a[i]-b[i])/32768.)**2 + for i in range(begin*2,FRAMES*2))/count) +def main(directory): + directory=pathlib.Path(directory) + report={'evidence':'P7.1 original native measured KEMAR direct XYZ A/B/C', + 'limitations':'not a dearVR/headphone preference or Windows ASIO test', + 'pairs':{}} + for side in ('front','rear'): + for spread in (0,60): + ident=f'{side}-spread{spread}' + samples={kind:read(directory/f'sonku-p71-{kind}-{ident}.wav') + for kind in ('horizontal','up25','down25')} + baseline=samples['horizontal'] + entry={} + for kind in ('up25','down25'): + candidate=samples[kind] + immediate=rms_delta(baseline,candidate,0) + full=rms_delta(baseline,candidate,2500) + # The first 96 direct frames precede any causal reflection. + # Nonzero measured direct elevation MUST alter that prefix. + prefix=sum(abs(baseline[i]-candidate[i]) + for i in range(96*2)) + peak=max(abs(i) for i in candidate)/32768. + rms=math.sqrt(sum((x/32768.)**2 for x in candidate)/len(candidate)) + assert full>1e-6 and immediate>1e-6 and prefix>0,(ident,kind,full,prefix) + assert math.isfinite(rms) and 1e-4=1.5: + flags.append(f'{hz}Hz ear{e+1} {db:+.2f} dB') + entryPhase=delta_phase(current[0][1],current[1][1]) + oldPhase=delta_phase(prev[0][1],prev[1][1]) + freq_data[str(hz)]={ + 'earGainChangeDb':levels, + 'interauralLevelDifferenceChangeDb':round(levels[0]-levels[1],4), + 'interauralPhaseChangeDeg':round( + delta_phase(entryPhase,oldPhase)*180/math.pi,4)} + entry[kind]={'fullRmsDifference':round(full,8), + 'sourceRms':round(rms,8), + 'samplePeak':round(peak,8), + 'directPrefixChangedSamplesLsb':prefix, + 'instrumentSpectralAndEarMetrics':freq_data, + 'tonalityReviewFlags':flags} + report['pairs'][ident]=entry + target=directory/'SONKU-P71-XYZ-DIRECT-MUSIC-METRICS.json' + target.write_text(json.dumps(report,sort_keys=True,indent=2)+'\n') + print('PASS P7.1 12 native FRONT/REAR XYZ measured direct WAVs, headroom, causal direct change, interaural/spectral evidence') +if __name__=='__main__': + if len(sys.argv)!=2:raise SystemExit('Usage: sonku_p71_xyz_audio_audit.py DIRECTORY') + main(sys.argv[1]) diff --git a/tools/sonku_p7_cpu.cpp b/tools/sonku_p7_cpu.cpp index a32d3be48..c92bdc79e 100644 --- a/tools/sonku_p7_cpu.cpp +++ b/tools/sonku_p7_cpu.cpp @@ -13,7 +13,7 @@ #include namespace { struct Result {double ms,p50,p95,p99,ratio;}; -Result bench(int count,float spread,bool six){ +Result bench(int count,float spread,bool six,float elevation=0.f){ using namespace armix::sonku; constexpr int n=128,frames=48000; std::vector> processors; @@ -22,6 +22,12 @@ Result bench(int count,float spread,bool six){ if(!dsp->prepare(48000.,six?SonKuReflectionProfile::SixSurfaceKemarResearch: SonKuReflectionProfile::DirectionalKemar)) throw "invalid P7 core"; +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH + if(elevation!=0.f && !dsp->setResearchDirectElevation(elevation)) + throw "invalid P7.1 quiescent XYZ placement"; +#else + if(elevation!=0.f)throw "P7.1 bench not compiled"; +#endif Settings s{};s.spacePreset=1;s.roomAmount=.65f;s.ambience=.2f; s.stereoSpreadDegrees=spread;s.moving=true;s.revolutionSeconds=4.f; if(!dsp->setSettings(s))throw "invalid P7 scene"; @@ -65,5 +71,24 @@ int main(){ spread,n,base.ms,six.ms,six.ms/base.ms, six.p50,six.p95,six.p99,six.ratio); } +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH + // Exact same six-boundary FIR count, source, ROOM and 1s clock. + // A measured-elevation SOURCE does not admit a new convolution. + for(float spread:{0.f,60.f}){ + for(int n:{1,2,4}){ + const auto horizontal=bench(n,spread,true,0.f); + const auto elevated=bench(n,spread,true,25.f); + const auto below=bench(n,spread,true,-25.f); + std::printf("SONKU_P71_CPU rate=48000 block=128 spread=%.0f inserts=%d " + "zero_p99us=%.3f up25_p99us=%.3f down25_p99us=%.3f " + "up_over_zero=%.3f down_over_zero=%.3f " + "up_buffer_ratio=%.3f down_buffer_ratio=%.3f " + "NOTE=hosted_linux_not_ASIO\n", + spread,n,horizontal.p99,elevated.p99,below.p99, + elevated.ms/horizontal.ms,below.ms/horizontal.ms, + elevated.ratio,below.ratio); + } + } +#endif }catch(...){std::puts("FAIL SonKu P7 CPU research");return 1;} } From f6a5148b0b57fed1870e63a19f2018c08dc02350 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 14 Nov 2026 11:50:07 +0700 Subject: [PATCH 4/7] perf(sonku-p71): split full-tap FIR from bounded warm-up without per-tap epoch branch; prove PCM LSB parity --- .github/workflows/sonku-p7-research.yml | 5 +++ ...P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md | 16 ++++++++ .../builtin_fx/sonku/SonKuEarlyReflections.h | 28 +++++++++++++ tests/sonku_p71_fir_parity_audit.py | 40 +++++++++++++++++++ 4 files changed, 89 insertions(+) create mode 100644 tests/sonku_p71_fir_parity_audit.py diff --git a/.github/workflows/sonku-p7-research.yml b/.github/workflows/sonku-p7-research.yml index 4398b8cfb..4faf0f5c3 100644 --- a/.github/workflows/sonku-p7-research.yml +++ b/.github/workflows/sonku-p7-research.yml @@ -62,6 +62,11 @@ jobs: run: | g++ -std=c++20 -O2 -Wall -Wextra -pedantic -DSONKU_P7_MEASURED_ELEVATION_RESEARCH=1 -DSONKU_P71_DIRECT_XYZ_RESEARCH=1 tools/sonku_offline_listening.cpp -o /tmp/p71-render /tmp/p71-render sonku-p7-evidence --p71-xyz-direct-only + - name: P7.1 fused FIR fast path against exact P7 original WAV reference + run: | + mkdir -p /tmp/sonku-p71-fir-fast + /tmp/p71-render /tmp/sonku-p71-fir-fast --p7-six-surface-only + python tests/sonku_p71_fir_parity_audit.py sonku-p7-evidence /tmp/sonku-p71-fir-fast - name: P7.1 measure same-source XYZ direct stereo musical integrity / per-ear acoustics run: | python tests/sonku_p71_xyz_audio_audit.py sonku-p7-evidence diff --git a/docs/SONKU_P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md b/docs/SONKU_P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md index f2df96bd9..7415f662f 100644 --- a/docs/SONKU_P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md +++ b/docs/SONKU_P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md @@ -54,3 +54,19 @@ CI SHA passes, but public feature remains vetoed until actual Windows ASIO, performance headroom, author-approved FX/UX workflow, .lsmix/.smix persistence and headphone blind tests versus dearVR are satisfactory. Do not merge stacked drafts prematurely. + +## P7.1 FIR fast-path experiment + +A second, macro-gated FIR implementation splits the convolution into +**valid epoch samples** and **warm-up kernel advancement**. Once the delay +ring is warm, the full 140-tap reflection convolution does not execute +the former per-tap stale-history conditional. The filter kernel still +slews for every tap, including silent warm-up samples, and the exact +P3 0° stereo fusion/0–60° states remain. This is not truncation, +interpolation approximation, a hidden adaptive DSP path, or a new mixer. + +The scoped native CI compiles the original P7 C++ room WAV fixture twice, +with and without the P7.1 macro, for FRONT/REAR, 0°/60°, four-wall/six-surface, +then compares all 8 × 144000 × 2 samples at <= 1 signed-16-bit LSB. +CPU 1/2/4 insert timing is informational and must demonstrate real +benefit before shipping any optimization. diff --git a/engine/builtin_fx/sonku/SonKuEarlyReflections.h b/engine/builtin_fx/sonku/SonKuEarlyReflections.h index d9f4418d0..42b312d85 100644 --- a/engine/builtin_fx/sonku/SonKuEarlyReflections.h +++ b/engine/builtin_fx/sonku/SonKuEarlyReflections.h @@ -263,6 +263,33 @@ class SonKuEarlyReflections final { // One source of truth for the coefficient slew and ear // FIR arithmetic; only history address selection varies. // Advance kernels even while history is warming. +#if defined(SONKU_P71_DIRECT_XYZ_RESEARCH) && SONKU_P71_DIRECT_XYZ_RESEARCH + // P7.1 measured-only hot path. In the overwhelmingly + // common fully warm ring, the 140-tap FIR has NO + // per-tap fresh-history comparison. Warm-up still + // advances ALL filter kernels, but reads no pre-OFF + // samples: zero extra heap, tables, clocks or FIRs. + const auto advance=[&](int k) noexcept { + auto& hL=p.kernel[0][k]; + auto& hR=p.kernel[1][k]; + hL+=kernelSlew_*(p.targetKernel[0][k]-hL); + hR+=kernelSlew_*(p.targetKernel[1][k]-hR); + if(fused){ + tap_[1][wall].kernel[0][k]=hL; + tap_[1][wall].kernel[1][k]=hR; + } + return std::array{hL,hR}; + }; + const auto render=[&](auto&& sample) noexcept { + for(int k=0;k=freshTaps) @@ -278,6 +305,7 @@ class SonKuEarlyReflections final { l+=v*hL;r+=v*hR; } }; +#endif if(fastContiguousHrir_ && idx>=hrir::taps){ // For 8052/8192 ring positions the entire 140-tap // window is continuous; no wrap mask inside FIR. diff --git a/tests/sonku_p71_fir_parity_audit.py b/tests/sonku_p71_fir_parity_audit.py new file mode 100644 index 000000000..9363b7fb1 --- /dev/null +++ b/tests/sonku_p71_fir_parity_audit.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""P7.1: compare every PCM sample from original P7 reference vs optimized FIR. +The same original C++ wav renderer is compiled once with each macro set. +Do not use duration-only heuristic: compare bit depth and 1-LSB worst case. +""" +import json +import pathlib +import struct +import sys +import wave + +def read(path): + with wave.open(str(path),'rb') as w: + shape=(w.getnchannels(),w.getsampwidth(),w.getframerate(),w.getnframes()) + assert shape==(2,2,48000,144000),(path,shape) + pcm=w.readframes(w.getnframes()) + return struct.unpack('<'+'h'*(len(pcm)//2),pcm) + +def main(original,optimized): + original,optimized=pathlib.Path(original),pathlib.Path(optimized) + evidence={} + for side in ('front','rear'): + for spread in (0,60): + name=f'{side}-spread{spread}' + for profile in ('four-wall','six-surface'): + filename=f'sonku-p7-{profile}-{name}.wav' + a=read(original/filename);b=read(optimized/filename) + differences=[abs(v-w) for v,w in zip(a,b)] + peak=max(differences) + changed=sum(x!=0 for x in differences) + if peak>1: + raise AssertionError(f'FIR PCM regression: {filename}, max {peak} LSB') + evidence[filename]={'maximumSampleDifferenceLsb':peak, + 'nonidenticalSamples':changed} + dest=original/'SONKU-P71-FIR-P7-REFERENCE-PARITY.json' + dest.write_text(json.dumps(evidence,indent=2,sort_keys=True)+'\n') + print('PASS P7.1 FIR optimized 8 reference WAVs across all PCM: max 1 LSB, 48k FRONT/REAR spread 0/60') +if __name__=='__main__': + if len(sys.argv)!=3:raise SystemExit('Usage: sonku_p71_fir_parity_audit.py REF_DIR FAST_DIR') + main(sys.argv[1],sys.argv[2]) From 866c2006ed8caf52903a5516f7fc37f3d43b8ae7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 14 Nov 2026 11:52:59 +0700 Subject: [PATCH 5/7] fix(sonku-p71): preserve strict quiescent edit gate through reset and remove FIR warning; constrain OFF-scene XYZ --- docs/SONKU_P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md | 11 +++++++++++ engine/builtin_fx/sonku/SonKuEarlyReflections.h | 2 ++ engine/builtin_fx/sonku/SonKuSpatialCore.h | 10 +++++----- engine/builtin_fx/sonku/SonKuVerticalImageSource.h | 3 +-- tests/sonku_p71_xyz_direct_test.cpp | 2 ++ 5 files changed, 21 insertions(+), 7 deletions(-) diff --git a/docs/SONKU_P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md b/docs/SONKU_P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md index 7415f662f..1480dc608 100644 --- a/docs/SONKU_P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md +++ b/docs/SONKU_P71_DIRECT_XYZ_MEASURED_SOURCE_20261114.md @@ -70,3 +70,14 @@ with and without the P7.1 macro, for FRONT/REAR, 0°/60°, four-wall/six-surface then compares all 8 × 144000 × 2 samples at <= 1 signed-16-bit LSB. CPU 1/2/4 insert timing is informational and must demonstrate real benefit before shipping any optimization. + +### Closure / immutability guarantee + +The research edit gate now stays closed after any PCM has run even if +`reset()` is called. Only `prepare()` may explicitly re-enter an +unpublished research session, preventing a reset-based concurrent +control bypass. OFF scene placement uses conservative 3.2 m height +validation so future selection of SQUARE cannot silently accept an +impossible elevated source. Physical XYZ editing during playback and +host ACK remain **not supported** until an explicit realtime architecture +is approved; this avoids fake editor/control state. diff --git a/engine/builtin_fx/sonku/SonKuEarlyReflections.h b/engine/builtin_fx/sonku/SonKuEarlyReflections.h index 42b312d85..4af600b96 100644 --- a/engine/builtin_fx/sonku/SonKuEarlyReflections.h +++ b/engine/builtin_fx/sonku/SonKuEarlyReflections.h @@ -259,7 +259,9 @@ class SonKuEarlyReflections final { // Zero-filling a 64KiB ring inside the callback is banned. const int freshTaps=realtimeMode_? std::clamp(validFrames_-d,0,hrir::taps):hrir::taps; +#if !defined(SONKU_P71_DIRECT_XYZ_RESEARCH) || !SONKU_P71_DIRECT_XYZ_RESEARCH const bool warming=freshTaps=2.4f&&g.room<=12.f&& g.listener>=.5f&&g.source>=.5f&& - g.listener<=g.room-.5f&&g.source<=g.room-.5f&& - true; // P7.1 may admit validated true XYZ source placement. + g.listener<=g.room-.5f&&g.source<=g.room-.5f; } inline Arrival image(const RoomHeight g,float horizontalDistance, float azimuthDegrees,Boundary boundary,float sampleRate) noexcept { diff --git a/tests/sonku_p71_xyz_direct_test.cpp b/tests/sonku_p71_xyz_direct_test.cpp index 83990c5d7..ccd627f5b 100644 --- a/tests/sonku_p71_xyz_direct_test.cpp +++ b/tests/sonku_p71_xyz_direct_test.cpp @@ -103,6 +103,8 @@ int main(){ } assert(energy>.01&&difference>.1&&early>1e-5); assert(!exact->setResearchDirectElevation(0.f)); // never mutate running PCM + exact->reset(); + assert(!exact->setResearchDirectElevation(0.f)); // reset is NOT unpublish assert(exact->researchDirectElevation()==elev); assert(std::abs(exact->azimuthDegrees()-chunks->azimuthDegrees())<1e-7); // Device re-prepare uses the same explicit research placement, From 444ec9b44cc076f4fe0b804e5cd3902a8bff2cb3 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 14 Nov 2026 11:54:45 +0700 Subject: [PATCH 6/7] test(sonku-p71): correct reset-vs-orbit assertion order and qualify XYZ on targeted Windows MSVC --- .github/workflows/sonku-p71-windows-core.yml | 54 ++++++++++++++++++++ tests/sonku_p71_windows/CMakeLists.txt | 16 ++++++ tests/sonku_p71_xyz_direct_test.cpp | 4 +- 3 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/sonku-p71-windows-core.yml create mode 100644 tests/sonku_p71_windows/CMakeLists.txt diff --git a/.github/workflows/sonku-p71-windows-core.yml b/.github/workflows/sonku-p71-windows-core.yml new file mode 100644 index 000000000..5f18d8884 --- /dev/null +++ b/.github/workflows/sonku-p71-windows-core.yml @@ -0,0 +1,54 @@ +name: SonKu P7.1 native Windows core — focused and no JUCE SDK +# P7.1 research only, independent of installer, ASIO, and Vocal Harmony. +on: + pull_request: + types: [opened, reopened, synchronize, ready_for_review] + paths: + - 'engine/builtin_fx/sonku/SonKuSpatialCore.h' + - 'engine/builtin_fx/sonku/SonKuEarlyReflections.h' + - 'engine/builtin_fx/sonku/SonKuVerticalImageSource.h' + - 'engine/builtin_fx/sonku/SonKuSourcePlacement3D.h' + - 'engine/builtin_fx/sonku/SonKuMeasuredHrir3D.h' + - 'tests/sonku_p71_xyz_direct_test.cpp' + - 'tests/sonku_p71_windows/CMakeLists.txt' + - '.github/workflows/sonku-p71-windows-core.yml' +permissions: + contents: read +concurrency: + group: sonku-p71-win-${{ github.event.pull_request.number }} + cancel-in-progress: true +jobs: + native: + name: Windows MSVC 20 — P7.1 XYZ and P6 default PCM (two tiny targets) + runs-on: windows-2022 + timeout-minutes: 12 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + - name: Refuse stale/incorrect source SHA + shell: pwsh + env: + EXPECTED_SHA: ${{ github.event.pull_request.head.sha }} + run: | + $actual=(& git rev-parse HEAD).Trim() + if($LASTEXITCODE -ne 0 -or $actual -ne $env:EXPECTED_SHA) { + throw "SONKU_P71_SHA_MISMATCH expected=$env:EXPECTED_SHA actual=$actual" + } + Write-Host "SONKU_P71_WINDOWS_CORE_SHA=$actual" + - name: Configure isolated MSVC source tests (no JUCE or WebView2) + shell: pwsh + run: | + cmake -S tests/sonku_p71_windows -B build-p71-win -G "Visual Studio 17 2022" -A x64 + if($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Compile two exact native C++20 source regression targets + shell: pwsh + run: | + cmake --build build-p71-win --config Release --parallel 2 --target SonKuP71XYZSource SonKuP6DefaultRegression + if($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: 44.1k/48k measured HRTF XYZ PCM and P6 default assertions + shell: pwsh + run: | + ctest --test-dir build-p71-win -C Release --output-on-failure + if($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + Write-Host 'SONKU_P71_MSVC_SOURCE_PCM=PASS no_ASIO_hardware_claim' diff --git a/tests/sonku_p71_windows/CMakeLists.txt b/tests/sonku_p71_windows/CMakeLists.txt new file mode 100644 index 000000000..47bd32039 --- /dev/null +++ b/tests/sonku_p71_windows/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.22) +project(SonKuP71FocusedNative LANGUAGES CXX) +# Independent Windows native C++ quality gate; no JUCE SDK/installer, +# WebView2 NuGet, full ArSonMix target or unrelated plugin dependencies. +enable_testing() +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +get_filename_component(ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../.." ABSOLUTE) +add_executable(SonKuP71XYZSource "${ROOT}/tests/sonku_p71_xyz_direct_test.cpp") +target_compile_definitions(SonKuP71XYZSource PRIVATE + SONKU_P7_MEASURED_ELEVATION_RESEARCH=1 + SONKU_P71_DIRECT_XYZ_RESEARCH=1) +add_test(NAME SonKuP71TrueXYZNativeWin COMMAND SonKuP71XYZSource) +add_executable(SonKuP6DefaultRegression "${ROOT}/tests/sonku_p6_realtime_quality_test.cpp") +add_test(NAME SonKuP6NativeDefaultWin COMMAND SonKuP6DefaultRegression) diff --git a/tests/sonku_p71_xyz_direct_test.cpp b/tests/sonku_p71_xyz_direct_test.cpp index ccd627f5b..dc84de660 100644 --- a/tests/sonku_p71_xyz_direct_test.cpp +++ b/tests/sonku_p71_xyz_direct_test.cpp @@ -102,11 +102,11 @@ int main(){ if(i>=48 && i<400)early+=std::abs(lb[i]-la[i])+std::abs(rb[i]-ra[i]); } assert(energy>.01&&difference>.1&&early>1e-5); + assert(std::abs(exact->azimuthDegrees()-chunks->azimuthDegrees())<1e-7); assert(!exact->setResearchDirectElevation(0.f)); // never mutate running PCM - exact->reset(); + exact->reset(); // legitimately repositions the orbit to the scene start assert(!exact->setResearchDirectElevation(0.f)); // reset is NOT unpublish assert(exact->researchDirectElevation()==elev); - assert(std::abs(exact->azimuthDegrees()-chunks->azimuthDegrees())<1e-7); // Device re-prepare uses the same explicit research placement, // but a switch to P6 clears research-only elevation. assert(exact->prepare(rate,SonKuReflectionProfile::SixSurfaceKemarResearch)); From 9332029e3345a4bab37a4dba0f06461a38724513 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 14 Nov 2026 11:58:08 +0700 Subject: [PATCH 7/7] bench(sonku-p71): interleaved old-vs-new 4-insert warm-FIR CPU evidence before optimizing verdict --- .github/workflows/sonku-p7-research.yml | 5 ++ tests/sonku_p71_interleaved_cpu_audit.py | 54 +++++++++++++++++++ tools/sonku_p71_hotpath_benchmark.cpp | 66 ++++++++++++++++++++++++ 3 files changed, 125 insertions(+) create mode 100644 tests/sonku_p71_interleaved_cpu_audit.py create mode 100644 tools/sonku_p71_hotpath_benchmark.cpp diff --git a/.github/workflows/sonku-p7-research.yml b/.github/workflows/sonku-p7-research.yml index 4faf0f5c3..c9815b0c7 100644 --- a/.github/workflows/sonku-p7-research.yml +++ b/.github/workflows/sonku-p7-research.yml @@ -78,6 +78,11 @@ jobs: run: | g++ -std=c++20 -O2 -Wall -Wextra -pedantic -DSONKU_P7_MEASURED_ELEVATION_RESEARCH=1 -DSONKU_P71_DIRECT_XYZ_RESEARCH=1 tools/sonku_p7_cpu.cpp -o /tmp/p71-bench /tmp/p71-bench | grep SONKU_P71_CPU | tee sonku-p7-evidence/SONKU-P71-CPU-REPORT.txt + - name: P7.1 controlled interleaved old-vs-fast FIR benchmark (informational) + run: | + g++ -std=c++20 -O2 -Wall -Wextra -pedantic -DSONKU_P7_MEASURED_ELEVATION_RESEARCH=1 tools/sonku_p71_hotpath_benchmark.cpp -o /tmp/p71-original + g++ -std=c++20 -O2 -Wall -Wextra -pedantic -DSONKU_P7_MEASURED_ELEVATION_RESEARCH=1 -DSONKU_P71_DIRECT_XYZ_RESEARCH=1 tools/sonku_p71_hotpath_benchmark.cpp -o /tmp/p71-fast + python tests/sonku_p71_interleaved_cpu_audit.py /tmp/p71-original /tmp/p71-fast sonku-p7-evidence - name: Upload 8 matched lossless WAV and JSON/CPU evidence if: ${{ always() }} uses: actions/upload-artifact@v4 diff --git a/tests/sonku_p71_interleaved_cpu_audit.py b/tests/sonku_p71_interleaved_cpu_audit.py new file mode 100644 index 000000000..92517b077 --- /dev/null +++ b/tests/sonku_p71_interleaved_cpu_audit.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Interleaved exact-source FIR benchmark, not a CI hard CPU-speed gate.""" +import json +import pathlib +import re +import statistics +import subprocess +import sys + +KEYS=("total_ms","p50_us","p95_us","p99_us") +def run(exe): + output=subprocess.check_output([str(exe)],text=True,timeout=45) + line=next((v for v in output.splitlines() + if v.startswith("SONKU_P71_HOTPATH ")),None) + if line is None: + raise AssertionError(f"Missing native CPU results: {exe}") + parsed=dict(re.findall(r"([a-z][a-z0-9_]*)=([0-9]+(?:\.[0-9]+)?)",line)) + record={key:float(parsed[key]) for key in KEYS} + if any(x<=0 or x>100000 for x in record.values()): + raise AssertionError(f"Bad CPU values {record}") + return record + +def main(baseline,fast,outdir): + original=pathlib.Path(baseline) + optimized=pathlib.Path(fast) + reports={"old":[],"candidate":[]} + # ABBA order cancels some warm/cold runner frequency, scheduler and + # thermal monotonicity. The baseline is a separately compiled P7 source, + # NOT a hardcoded speed claim or a different plugin engine. + schedule=("old","candidate","candidate","old")*3 + for item in schedule: + exe=original if item=="old" else optimized + reports[item].append(run(exe)) + medians={name:{key:statistics.median(v[key] for v in records) + for key in KEYS} for name,records in reports.items()} + speed=medians["old"]["total_ms"]/medians["candidate"]["total_ms"] + medianp99=medians["old"]["p99_us"]/medians["candidate"]["p99_us"] + evidence={ + "method":"same-source separate old/optimized P7 binaries, interleaved ABBA x3, warm steady DSP", + "limitations":"shared Linux runner; not Windows ASIO, no hard real-time speed guarantee", + "profile":"48kHz/128, 4 concurrent inserts, 60 degree spread, active ROOM", + "median":medians,"pairedTotalSpeedup":round(speed,5), + "p99RatioOldOverCandidate":round(medianp99,5), + "trials":reports} + outdir=pathlib.Path(outdir);outdir.mkdir(exist_ok=True,parents=True) + (outdir/"SONKU-P71-FIR-INTERLEAVED-CPU.json").write_text( + json.dumps(evidence,indent=2,sort_keys=True)+"\n") + print(f"SONKU_P71_INTERLEAVED median_wallclock_speedup={speed:.4f} " + f"median_p99_old_over_fast={medianp99:.4f} " + "note=informational_linux_not_ASIO") +if __name__=="__main__": + if len(sys.argv)!=4: + raise SystemExit("Usage: sonku_p71_interleaved_cpu_audit.py ORIGINAL FAST OUTDIR") + main(*sys.argv[1:]) diff --git a/tools/sonku_p71_hotpath_benchmark.cpp b/tools/sonku_p71_hotpath_benchmark.cpp new file mode 100644 index 000000000..aaa3903fe --- /dev/null +++ b/tools/sonku_p71_hotpath_benchmark.cpp @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Exact static source/scenes for old P7 vs P7.1 warmup-split FIR. +// This is an informational Linux runner process-time experiment: NOT ASIO. +#ifndef SONKU_P7_MEASURED_ELEVATION_RESEARCH +#error P7 HRTF bank must be used in both identical comparison binaries +#endif +#include "../engine/builtin_fx/sonku/SonKuSpatialCore.h" +#include +#include +#include +#include +#include +#include +#include +int main(){ + using namespace armix::sonku; + constexpr int block=128,frames=48000,instances=4; + constexpr float pi=3.14159265358979323846f; + std::array,instances> dsps{}; + for(auto& dsp:dsps){ + dsp=std::make_unique(); + if(!dsp->prepare(48000.,SonKuReflectionProfile::SixSurfaceKemarResearch)) + return 2; + Settings s{}; + s.spacePreset=1;s.roomAmount=.65f;s.ambience=.2f; + s.stereoSpreadDegrees=60.f;s.startAzimuthDegrees=35.f; + s.moving=true;s.revolutionSeconds=4.f;s.outputTrim=.65f; + if(!dsp->setSettings(s))return 3; + } + std::array l{},r{}; + for(int k=0;k(k)/48000.f; + l[k]=.11f*std::sin(2.f*pi*220.f*t)+ + .05f*std::sin(2.f*pi*3200.f*t); + r[k]=.11f*std::sin(2.f*pi*220.f*t)- + .05f*std::sin(2.f*pi*3200.f*t); + } + // Separate non-timed warmup; all FIR delay epochs and room transition + // have reached steady state before measured PCM callback starts. + for(int sample=0;sampleprocess(a.data(),b.data(),block);} + std::vector us; + us.reserve(frames/block); + auto first=std::chrono::steady_clock::now(); + for(int sample=0;sampleprocess(a.data(),b.data(),block); + if(!std::isfinite(a[0])||!std::isfinite(b[0]))return 4; + } + const auto end=std::chrono::steady_clock::now(); + us.push_back(std::chrono::duration(end-start).count()); + } + const auto last=std::chrono::steady_clock::now(); + std::sort(us.begin(),us.end()); + const auto quantile=[&](float q){ + const size_t k=std::clamp(static_cast(std::ceil(q*us.size())), + size_t(1),us.size()); + return us[k-1]; + }; + const double total=std::chrono::duration(last-first).count(); + std::printf("SONKU_P71_HOTPATH block=128 rate=48000 inserts=4 spread=60 " + "total_ms=%.3f p50_us=%.3f p95_us=%.3f p99_us=%.3f\n", + total,quantile(.50f),quantile(.95f),quantile(.99f)); +}