diff --git a/CMakeLists.txt b/CMakeLists.txt index 00e39a7..f9e565d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -92,14 +92,8 @@ set(JOC_REUSED_SOURCES set(JOC_INTERNAL_SOURCES src/adm/adm_metadata.cpp src/adm/adm_tracks.cpp - src/binaural/binaural_runtime.cpp - src/binaural/direct_sofa_runtime.cpp - src/binaural/point_source.cpp - src/binaural/reference_distance.cpp - src/binaural/room_tables.cpp - src/binaural/shoebox_room.cpp - src/binaural/sofa_room.cpp - src/binaural/sofa_binaural_renderer.cpp + src/binaural/jochrtf_runtime.cpp + src/binaural/jochrtf_renderer.cpp src/eac3_transport/eac3_reader.cpp src/emdf/emdf_parser.cpp src/foundation/bit_reader.cpp @@ -114,14 +108,7 @@ set(JOC_INTERNAL_SOURCES src/hrtf/rosella_filterbank.cpp src/hrtf/rosella_model.cpp src/hrtf/rosella_renderer.cpp - src/hrtf/rosella_reference.cpp src/hrtf/kernel_tables.cpp - src/hrtf/full_hrir_field.cpp - src/hrtf/partitioned_convolution.cpp - src/hrtf/sofa.cpp - src/hrtf/sofa_cache.cpp - src/hrtf/sofa_field.cpp - src/hrtf/spherical_mesh.cpp src/io/adm_writer.cpp src/io/hdf5.cpp src/io/inflate.cpp @@ -314,20 +301,10 @@ if(JOC_BUILD_DEVTOOLS) add_executable(joc_dump devtools/joc_dump/main.cpp) target_link_libraries(joc_dump PRIVATE joc_core joc_core_impl) target_include_directories(joc_dump PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") - # SOFA reader probe: the C++ side of devtools/checks/check_sofa.py. - add_executable(joc_sofa_field_probe devtools/sofa_field_probe/main.cpp) - add_executable(joc_dictionary_probe devtools/sofa_field_probe/dictionary_main.cpp) - target_link_libraries(joc_dictionary_probe PRIVATE joc_core_impl) - target_include_directories(joc_dictionary_probe PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") - target_link_libraries(joc_sofa_field_probe PRIVATE joc_core_impl) - target_include_directories(joc_sofa_field_probe PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") # Rosella model probe: the C++ side of devtools/checks/check_rosella.py. add_executable(joc_rosella_probe devtools/rosella_probe/main.cpp) target_link_libraries(joc_rosella_probe PRIVATE joc_core_impl) target_include_directories(joc_rosella_probe PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") - add_executable(joc_sofa_probe devtools/sofa_probe/main.cpp) - target_link_libraries(joc_sofa_probe PRIVATE joc_core_impl) - target_include_directories(joc_sofa_probe PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") # Probe for the streaming surface: the acceptance harness and the usage # example for joc_stream.h. Not shipped: a player integrates the library. add_executable(joc_stream_probe devtools/joc_stream/main.cpp) @@ -342,7 +319,6 @@ if(JOC_BUILD_TESTS) list(APPEND JOC_MSVC_TARGETS joc_tests joc_rosella_filterbank_tests joc_headers_c joc_headers_cpp) endif() if(JOC_BUILD_DEVTOOLS) - list(APPEND JOC_MSVC_TARGETS joc_rosella_probe joc_dump joc_stream_probe joc_sofa_probe joc_sofa_field_probe joc_dictionary_probe) endif() if(MSVC) diff --git a/README.en.md b/README.en.md index 442cad5..d9afafd 100644 --- a/README.en.md +++ b/README.en.md @@ -6,8 +6,8 @@ The C++ implementation of JustOneCacophony: an execution core for E-AC-3 JOC bitstream parsing, object reconstruction and rendering. It extracts EMDF, ID14 JOC parameters and ID11 OAMD metadata from E-AC-3 syncframes, combines them with the core 5.1 PCM decoded by FFmpeg to rebuild the LFE and 15 object signals, and writes -ADM BWF, a WAV for a chosen speaker layout, or a binaural WAV rendered directly from -full SOFA HRIRs (or from a compiled `.jochrtf` directional field). +ADM BWF, a WAV for a chosen speaker layout, or a binaural WAV using a compiled HRTF +directional field. This is research code, not a complete, standard-conformant or production JOC decoder. It covers the bitstream forms it implements and reports an explicit error @@ -30,7 +30,7 @@ The heaviest binaural loops are **runtime-dispatched**: one binary carries sever ISA variants and picks the widest one at startup from CPUID/XGETBV, with the output byte-identical either way (see [SIMD dispatch](docs/simd.en.md)). `JOC_ENABLE_AVX2` / `JOC_ENABLE_AVX512` (both ON by default) only decide whether those units are linked -in: carrying the AVX2 unit buys 12.4% on the SOFA binaural kernel and 1.8% on +in: carrying the AVX2 unit buys 12.4% on the .jochrtf binaural kernel and 1.8% on Rosella, while a CPU without AVX2 still runs the baseline (SSE2) path. To produce a baseline-only binary: @@ -77,9 +77,10 @@ joc_cli input.m4a -o out/adm.wav # explicit output joc_cli input.m4a --speaker-layout 5.1 # -> output/.5.1.wav joc_cli input.m4a --speaker-layout 7.1.4 --speaker-output out/714.wav --speaker-format int24 -# Binaural (HRTF defaults to /HRTF/binaural.sofa, then /HRTF/binaural.personalized_headphone) +# Binaural (defaults to /HRTF/binaural.personalized_headphone) joc_cli input.m4a --binaural -joc_cli input.m4a --binaural --sofa-hrtf HRTF/other.sofa # another SOFA +joc_cli input.m4a --binaural --compiled-hrtf-cache HRTF/subject.jochrtf # offline compiled field +joc_cli input.m4a --binaural --compiled-hrtf-cache HRTF/subject.jochrtf --jochrtf-room off joc_cli input.m4a --binaural --personalized-headphone # Rosella personalisation # -> output/.binaural.wav joc_cli input.m4a --binaural --personalized-headphone --rosella-filterbank 2 # captured bank @@ -100,7 +101,7 @@ defaults. A run always writes `.report.json` (`--report-json` overrides path: `1` (default) is the public 13-tap / 6-slot bank, `2` is the captured 11-tap / 3-slot bank. Their latencies are 961 and 448 samples, and each keeps its own coefficients, history and flush capacity. The option only applies to the Rosella -model; the SOFA and `.jochrtf` paths reject it. See +model; the `.jochrtf` path rejects it. See [Rosella filterbank](docs/rosella_filterbank.en.md). **Differences from the reference:** `--backend python` and the metadata sidecars @@ -224,11 +225,7 @@ The extra pair's **identity** never reaches the DSP (section 10.1): when the dep renders, with the bed mapping following the channel codes the `chanmap` declares. The bed layout the OAMD declares may hold more channels than the core substream codes (a 9.1.6 bed with a 5.1 core, for example): only a core channel missing from that layout counts as a -mismatch. For bed-only content the 15 JOC object slots are the bed channels, each rendered as -a point source at the fixed position its channel label defines (ETSI TS 103 420 table B.10); -speaker, ADM and binaural output share those source coordinates and never re-place them per -layout, while LFE keeps its separate path. When one audio frame holds several EMDF -containers carrying ID11/ID14, they +mismatch. When one audio frame holds several EMDF containers carrying ID11/ID14, they are scored by the association rule of section 8.2 and its Table 56: a container whose OAMD and JOC payloads share a group id and whose ID14 parses completely wins, then one whose ID14 merely parses; only a unique best score is used and the others are recorded as a diagnostic diff --git a/README.md b/README.md index e6b5ca4..6fa7dd5 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,8 @@ JustOneCacophony 的 C++ 实现:E-AC-3 JOC 码流解析、对象重建与渲染的执行内核。它从 E-AC-3 同步帧中提取 EMDF、ID14 JOC 参数与 ID11 OAMD 元数据,结合 FFmpeg 解码出的核心 PCM(N=5 或 7) -重建 LFE 与 15 路对象 PCM,并输出 ADM BWF、指定扬声器布局的 WAV,或按完整 HRIR 直接 -渲染双耳 WAV(SOFA),也可以读入编译好的 `.jochrtf` 方向场渲染。 +重建 LFE 与 15 路对象 PCM,并输出 ADM BWF、指定扬声器布局的 WAV,或用编译好的 HRTF 方向场 +直接输出双耳 WAV。 这是研究代码,不是完整、标准兼容或生产级的 JOC 解码器。它只覆盖已实现的码流形态,遇到未知 变体时明确报错,而不是假装一切都很和谐。 @@ -24,7 +24,7 @@ Windows(MSVC / VS 2022,静态 CRT)、Linux 与 macOS 由 `.github/workflow 最重的双耳循环由**运行时派发**:同一份二进制里装多套 ISA 代码,启动时按 CPUID/XGETBV 选最宽 的一套,输出逐字节不变(见 [SIMD 与运行时派发](docs/simd.md))。`JOC_ENABLE_AVX2` / -`JOC_ENABLE_AVX512`(默认都 ON)只决定是否把这些单元编进二进制:带上 AVX2 单元让 SOFA 双耳 +`JOC_ENABLE_AVX512`(默认都 ON)只决定是否把这些单元编进二进制:带上 AVX2 单元让 `.jochrtf` 双耳 内核快 12.4%、Rosella 快 1.8%,而没有 AVX2 的 CPU 仍走基线(SSE2)路径。要产出只带基线 ISA 的二进制: @@ -67,10 +67,11 @@ joc_cli input.m4a -o out/adm.wav # 指定输出 joc_cli input.m4a --speaker-layout 5.1 # -> output/<名称>.5.1.wav joc_cli input.m4a --speaker-layout 7.1.4 --speaker-output out/714.wav --speaker-format int24 -# 双耳(HRTF 默认取 /HRTF/binaural.sofa,其次 /HRTF/binaural.personalized_headphone) +# 双耳(默认取 /HRTF/binaural.personalized_headphone) joc_cli input.m4a --binaural -joc_cli input.m4a --binaural --sofa-hrtf HRTF/other.sofa # 换一个 SOFA joc_cli input.m4a --binaural --personalized-headphone # Rosella 个性化模型 +joc_cli input.m4a --binaural --compiled-hrtf-cache HRTF/subject.jochrtf # 离线编译的 .jochrtf +joc_cli input.m4a --binaural --compiled-hrtf-cache HRTF/subject.jochrtf --jochrtf-room off # -> output/<名称>.binaural.wav joc_cli input.m4a --binaural --personalized-headphone --rosella-filterbank 2 # 新版 Rosella 滤波器组 @@ -87,7 +88,7 @@ joc_cli input.eac3 --metadata-only --print-metadata summary # 只解析并打 `--rosella-filterbank 1|2` 选择 Rosella 个性化模型使用的滤波器组:`1`(默认)是 13 taps / 6 slots 的公开滤波器组,`2` 是 11 taps / 3 slots 的捕获版。两者延迟分别为 961 / 448 samples, -系数、历史缓冲与 flush 容量各自独立;该选项只作用于 `.personalized_headphone`,SOFA 与 +系数、历史缓冲与 flush 容量各自独立;该选项只作用于 `.personalized_headphone`, `.jochrtf` 路径给出时直接报错。详见 [Rosella 滤波器组](docs/rosella_filterbank.en.md)。 **与上游参数的差异**:`--backend python` 与 metadata sidecar(`--metadata-dir`/ @@ -191,8 +192,6 @@ ffmpeg 侧只在 $N=5$ 档位传 `-ac 6`;$N=7$ 档位不传 `-ac`,保留解 拒绝。额外那一对的**身份**只进元数据、不进 DSP(§10.1):依赖子流 `chanmap` 与 $k$ 不一致、或 OAMD 声明的 bed 布局可以比核心子流实际编码的声道多(例如 9.1.6 bed 只编 5.1 核心),只有核心 声道在 bed 布局里找不到位置才记 diagnostics 并照常解码,床映射按 `chanmap` 的通道码走。 -bed-only 内容的 15 路 JOC 对象就是 bed 声道:每一路按其声道标签的固定方位(ETSI TS 103 420 -Table B.10)作为点声源渲染,扬声器、ADM 与双耳共用同一组源坐标,不随输出布局改变;LFE 独立处理。 同一音频帧里出现多个含 ID11/ID14 的 EMDF 容器时,按规格 §8.2 + Table 56 的关联规则打分: OAMD 与 JOC 载荷 groupid 相同且 ID14 能完整解析的优先,其次只看 ID14 能否解析;唯一最高分才用, 其余记入 diagnostics(`emdf/extra_container_ignored`)。额外那一对在 10 槽 ADM 骨架上的落位 diff --git a/docs/binaural.en.md b/docs/binaural.en.md index c4acc54..990b264 100644 --- a/docs/binaural.en.md +++ b/docs/binaural.en.md @@ -2,102 +2,26 @@ [中文](binaural.md) · [Back to README](../README.en.md) -JustOneCacophony's binaural backend supports three HRTF sources: -`SimpleFreeFieldHRIR` SOFA, the Rosella `.personalized_headphone` model exported -by Dolby's official personalization scan (its JSON parsing is implemented by -this project and invokes no Dolby software), and `.jochrtf` (a JOC compiled HRTF -cache). - -SOFA keeps its full HRIRs and renders directly through a configured reference -environment; it is no longer compiled into a directional field: +JustOneCacophony's binaural backend supports two HRTF sources: the Rosella +`.personalized_headphone` model exported by Dolby's official personalization scan +(its JSON parsing is implemented by this project and invokes no Dolby software), +and an offline compiled `.jochrtf` directional-field cache. A `.jochrtf` file is +a disposable, reproducible JOC compiled HRTF cache, not an interchange format. ```text -SOFA full HRIR [M,2,N] - -> CanonicalHrtf (48 kHz / one radius shell) - -> delay-aligned complex spectra (200-1500 Hz phase fit, Data.Delay included) - -> spherical-triangle barycentric interpolation (lf_logmag_phase or lf_mca_zero) - -> rigid-sphere radial correction (reference-environment distance) - -> per-object partitioned convolution (block 128, FFT = max(2048, >=2*support)) - -> reference-environment recursive room model - -> float64 stereo (one common latency removed) +.jochrtf + -> 77-band directional field + delay model + -> 64-QMF / 77-hybrid analysis + -> per-object direct + optional early reflections + -> optional shared unitary-FDN late room + -> stereo float64 ``` -`.jochrtf` stays an explicit input (`--compiled-hrtf-cache`) and keeps the -real-SH field renderer; passing `--hrtf-cache-policy` / `--hrtf-cache-dir` -selects the legacy "SOFA -> `.jochrtf`" compile path. - -## Point-source reference scale - -Near/Mid/Far use reference distances of 1.00000465 / 2.19327927 / 6.40177584 m; -`--source-reference-distance-m` overrides the selected mode. For an ADM -right/front/up position `p = (x, y, z)`: - -```text -q_SOFA = (y, -x, z) / ||p|| -d_nominal = reference_distance_m * ||p|| -H_render = H_selected_shell(q_SOFA) -``` - -The reference distance only gives object coordinates a nominal metric scale. It -does not turn a 1.2 m measurement radius into a 2.193 m ground truth and does not -rewrite the SOFA metadata. The default direct mode adds no 1/r attenuation, no -head-sphere distance ratio, no synthetic centre response, no room send and no -target-distance propagation delay; programme gain and the SOFA response scale -are preserved. - -A coincident source has no defined direction, so the object keeps its last valid -direction, or front when there is no history. Finite positions outside the unit -box keep their metadata distance factor and are not clamped. - -## Optional project room - -`--sofa-room` is off by default and reuses the project's own room algorithms: -six first-order image reflections plus a shared FDN tail with a four-channel -orthogonal Hadamard feedback matrix, two all-pass diffusers and low-pass damping. -It is a listening preset of this project, not a measured BRIR or an external -standard room, and it does not use the Rosella room tables. - -When enabled, Near/Mid default to the `compact` room and Far to the `legacy` -room; `--sofa-room-preset compact|legacy` selects explicitly. The compact -geometry follows -[Zahorik 2009, Table 1 model 9](https://pmc.ncbi.nlm.nih.gov/articles/PMC2730711/), -keeping the original image/FDN algorithm while scaling late delay, diffusion -time and RT60 by the `V/S` ratio; the parameters and their source are recorded -in the asset metadata. Only the geometry is borrowed, not that paper's BRIR -algorithm. - -The full-HRIR route queries an HRIR for each of the six arrival directions and -applies the fractional delay as a phase ramp on the full frequency grid; the -extra flight time of a reflection is `(L_path - L_direct)/c`, preserving the -original `Data.Delay`. Direct sound, reflections and the late send use the -project's original gain formulas. - -The late FDN is rendered at 48 kHz with a unit impulse into a two-channel float64 -FIR cut at 2*RT60: 37,383 taps (RT60 about 0.3894 s) for the compact room and -81,600 taps (RT60 0.85 s) for the legacy one. The FIR is produced at startup by -the four-line Hadamard feedback loop, the two all-pass diffusers and the low-pass -damping in `src/binaural/room_tables.cpp`; no audio asset ships with the binary. -At runtime the same LTI system is applied by PCM-domain FFT convolution in -1536-sample batches, the early reflections still use the selected SOFA, and the -LFE channel never enters the room. These states are neither generated nor kept -when the room is off, and batch padding is trimmed on flush. - ## Inputs -A SOFA input renders directly from its full HRIRs and only needs the SOFA file: - -```powershell -joc_cli input.m4a --binaural ` - --sofa-hrtf HRTF\subject.sofa ` - --binaural-mode mid --sofa-interpolation lf_logmag_phase - -joc_cli input.m4a --binaural --sofa-hrtf HRTF\subject.sofa --sofa-room -joc_cli input.m4a --binaural --sofa-hrtf HRTF\subject.sofa --sofa-room --sofa-room-preset legacy -``` - -A `.jochrtf` input (and `.personalized_headphone`) also needs the shared filterbank -tables. Both are read-only inputs; parsing and coordinate validation happen while the -model is loaded, and nothing is converted again during rendering. +The binaural backend consumes a compiled directional field (a JOC compiled HRTF cache, +`.jochrtf`) plus the shared filterbank tables. Both are read-only inputs: this library +performs no parsing or conversion of measurement data formats. ```powershell joc_cli input.m4a --binaural ` @@ -106,15 +30,8 @@ joc_cli input.m4a --binaural ` --binaural-mode mid --binaural-tail-seconds 5.0 ``` -A multi-radius SOFA requires `--hrtf-radius-m`; a single shell is selected -automatically. `--sofa-interpolation` picks the local interpolation of the full HRIR: -`lf_logmag_phase` (default, log magnitude plus phase) or `lf_mca_zero` (auditory-band -magnitude correction). - The library exposes the same fields: `joc_task_config` for a file task, -`joc_stream_config` for streaming, where `hrtf_sofa_path` (or `hrtf_path`), -`sofa_interpolation`, `hrtf_radius_m`, `source_reference_distance_m`, `sofa_room`, -`sofa_room_preset`, `sofa_room_asset_dir`, `hrtf_compile`, `kernels_path`, +`joc_stream_config` for streaming, where `hrtf_path`, `kernels_path`, `binaural_mode` and `binaural_tail_seconds` configure the binaural path. The `.jochrtf` file is an **input**, not a product of this library: compiling it from @@ -139,41 +56,6 @@ input E-AC-3 JOC bitstream: entries unchanged; the default is `mid`, and `off` explicitly disables the binaural metadata hint. -## Canonical SOFA contract - -The strict importer currently accepts: - -- `Conventions=SOFA`; -- `SOFAConventions=SimpleFreeFieldHRIR`, version `0.4`, `1.0`, or `1.1`; -- `DataType=FIR` and `Data.IR[M,2,N]`; -- one positive finite `Data.SamplingRate` in hertz/Hz; -- spherical or Cartesian `SourcePosition`; -- singleton or per-measurement `ListenerPosition/View/Up`; -- two receivers whose listener-local lateral geometry uniquely identifies L/R; -- one zero-offset emitter; -- causal `Data.Delay[I,2]` or `[M,2]`; -- an explicitly free-field/anechoic `RoomType`. - -Receiver order comes from geometry, never from the receiver array index. SOFA -listener coordinates are $+X$ front, -$+Y$ left, -$+Z$ up; ADM coordinates are -$+X$ right, -$+Y$ front, -$+Z$ up: - -$$\bigl(x_{\mathrm{SOFA}},\ y_{\mathrm{SOFA}},\ z_{\mathrm{SOFA}}\bigr) = \bigl(y_{\mathrm{ADM}},\ -x_{\mathrm{ADM}},\ z_{\mathrm{ADM}}\bigr)$$ - -`CanonicalHrtf` keeps `Data.IR` and `Data.Delay` separate. Only a time-domain -baseline calls `materialized_measurement()` to apply delay once; the runtime SH -path never materializes and then restores the delay. Non-48-kHz HRIRs are -normalized with float64 `scipy.signal.resample_poly`, and delay samples scale by -the same ratio. - -GeneralFIR, BRIR, TF, multiple emitters, ambiguous receivers, and non-free-field -data require convention-specific adapters. They cannot enter the core importer -through a reshape. - ## Exactly-once delay and phase The compiler recognizes three mutually exclusive representations: @@ -188,13 +70,9 @@ The compiler recognizes three mutually exclusive representations: No path may add a second ear delay or phase-group delay. -The direct SOFA path does not use this compile-time policy: it keeps the full IRs and -estimates the arrival time with a 200-1500 Hz phase fit, so `Data.Delay` and the fitted -delay are each applied once (the delay is removed first and restored afterwards). - ## Public filterbank and directional field -The SOFA and `.jochrtf` runtime is fixed at: +The `.jochrtf` runtime is fixed at: - 48 kHz; - a 64-sample QMF hop; @@ -314,7 +192,7 @@ Dolby. The binaural renderer is implemented inside this library: the filterbank, the SH directional-field evaluation, the per-object early/direct histories and the shared -FDN all run in `joc_core` (the `ejoc_sofa_binaural_*` kernel), consuming a compiled +FDN all run in `joc_core` (the `ejoc_jochrtf_*` kernel), consuming a compiled directional field and 512-sample metadata updates. ## Technical references and rights boundary diff --git a/docs/binaural.md b/docs/binaural.md index da25fa1..c3a40c3 100644 --- a/docs/binaural.md +++ b/docs/binaural.md @@ -2,100 +2,36 @@ [English](binaural.en.md) · [返回 README](../README.md) -JustOneCacophony 的双耳后端支持三种 HRTF 来源:`SimpleFreeFieldHRIR` SOFA、 -杜比官方软件个性化扫描导出的 Rosella `.personalized_headphone`(JSON 解析由本项目 -自行实现,不调用杜比软件),以及 `.jochrtf`(JOC compiled HRTF cache)。 - -SOFA 默认保留完整 HRIR,按点声源参考直连渲染,不编译成方向场: +JustOneCacophony 的双耳后端支持两种 HRTF 来源:杜比官方软件个性化扫描导出的 +Rosella `.personalized_headphone`(JSON 解析由本项目自行实现,不调用杜比软件),以及 +离线编译好的 `.jochrtf` 方向场缓存。`.jochrtf` 是可删除、可重建的 JOC compiled HRTF +cache,不是交换格式。 ```text -SOFA 完整 HRIR [M,2,N] - -> CanonicalHrtf(48 kHz / 单 radius shell) - -> 延迟对齐的复数频谱(200-1500 Hz 相位拟合,含 Data.Delay) - -> 球面三角形重心插值(lf_logmag_phase 或 lf_mca_zero) - -> 点声源参考尺度(方向 + 档位参考距离,无径向修正) - -> 逐对象 partitioned convolution(block 128,FFT = max(2048, ≥2×support)) - -> 可选项目房间(六路一阶镜像 + 共享 FDN 晚期 FIR) - -> stereo float64(统一扣除 latency) +.jochrtf + -> 77 带方向场 + 延迟模型 + -> 64-QMF / 77-hybrid analysis + -> 逐对象 direct + 可选 early reflections + -> 可选 shared unitary-FDN late room + -> stereo float64 ``` -`.jochrtf` 仍是显式输入(`--compiled-hrtf-cache`),走球谐方向场渲染;显式给出 -`--hrtf-cache-policy` / `--hrtf-cache-dir` 会回到旧的“SOFA → `.jochrtf`”编译路径。 - -## 点声源参考尺度 - -Near/Mid/Far 的参考距离分别为 1.00000465 / 2.19327927 / 6.40177584 m,可用 -`--source-reference-distance-m` 覆盖所选档位。对于 ADM 右/前/上坐标 `p=(x,y,z)`: - -```text -q_SOFA = (y, -x, z) / ||p|| -d_nominal = reference_distance_m * ||p|| -H_render = H_selected_shell(q_SOFA) -``` - -参考距离只给对象坐标规定标称米制尺度,不会把测量半径为 1.2 m 的 HRIR 合成成 2.193 m -的真值,也不改动 SOFA 测量元数据。默认直达声模式不额外应用 1/r 衰减、球头距离比值、 -人工中心响应、房间发送或目标距离传播延迟;节目增益与 SOFA 响应刻度保持不变。 - -声源与听者重合时方向没有定义,沿用该对象最后一个有效方向;没有历史时取正前方。 -有限盒外坐标保留元数据距离因子,不裁回单位盒。 - -## 可选项目房间 - -`--sofa-room` 默认关闭,复用项目原有的房间算法:六个一阶镜像反射,以及四路正交 -Hadamard 反馈、两级全通扩散、低通阻尼的共享 FDN 晚期。它是项目自有的听感预设, -不是测量 BRIR 或外部标准房间,也不依赖 Rosella 房间表。 - -启用后 Near/Mid 默认使用 `compact` 紧凑房间,Far 默认使用 `legacy` 原大房间; -`--sofa-room-preset compact|legacy` 可显式选择。紧凑房间尺寸取自 -[Zahorik 2009 表 1 模型 9](https://pmc.ncbi.nlm.nih.gov/articles/PMC2730711/), -保留原镜像/FDN 算法,将晚期延迟、扩散时间与 RT60 参数按 `V/S` 比例缩短;参数与来源 -记录在资产元数据中,借用的只是文献几何,不是该论文 BRIR 算法的复现。 - -完整 HRIR 路线对六个到达方向分别查询 HRIR,以完整频率网格上的相位斜坡实现分数采样 -延迟;反射路径相对直达路径的额外时间为 `(L_path - L_direct)/c`,保留原 HRIR 的 -`Data.Delay`。直接声、反射与晚期发送使用项目原有的增益公式。 - -晚期 FDN 在 48 kHz 下用单位脉冲生成双声道 float64 FIR,长度截到 2×RT60:紧凑版 -37,383 点、RT60 参数约 0.3894 s,原版 81,600 点、RT60 参数 0.85 s。FIR 由 -`src/binaural/room_tables.cpp` 里的四路 Hadamard 反馈、两级全通扩散与低通阻尼在启动时 -现场渲染,不读取任何随包发布的音频资产。运行时按 1536 样本批次在 PCM 域做 FFT 卷积, -早期反射仍使用所选 SOFA;LFE 声道不进房间。房间关闭时既不生成也不保留这些状态, -排空时裁去批处理填充。 - -指向同一声道的直达声是延迟对齐后的完整 HRIR 插值结果;文件任务的 latency 由 field -(FFT/2 与 recording origin)决定,输出前统一扣除。 - ## 输入接口 -SOFA 输入直接按完整 HRIR 渲染,只需要 SOFA 本身: - -```powershell -joc_cli input.m4a --binaural ` - --sofa-hrtf HRTF\subject.sofa ` - --binaural-mode mid --sofa-interpolation lf_logmag_phase - -joc_cli input.m4a --binaural --sofa-hrtf HRTF\subject.sofa --sofa-room -joc_cli input.m4a --binaural --sofa-hrtf HRTF\subject.sofa --sofa-room --sofa-room-preset legacy -``` - -`.jochrtf` 输入(以及 `.personalized_headphone`)需要共享滤波器组表,两者都是只读输入: +双耳后端消费两种输入:已编译的方向场(JOC compiled HRTF cache,`.jochrtf`)配共享滤波器组表, +或者是 Rosella `.personalized_headphone` 模型。两者都是只读输入,本库不做测量数据格式的解析: ```powershell joc_cli input.m4a --binaural ` --compiled-hrtf-cache path\to\subject.jochrtf ` --kernels data\rosella_kernels.npz ` + --jochrtf-room on ` --binaural-mode mid --binaural-tail-seconds 5.0 +joc_cli input.m4a --binaural --personalized-headphone HRTF\binaural.personalized_headphone ``` -多球壳 SOFA 必须用 `--hrtf-radius-m` 指定球壳(单球壳自动选择);`--hrtf-radius-m` -对已编译的 `.jochrtf` 不再生效。`--sofa-interpolation` 选择完整 HRIR 的局部插值: -`lf_logmag_phase`(默认,对数幅度 + 相位)或 `lf_mca_zero`(听觉带幅度修正)。 - 库接口使用同一组字段:文件任务用 `joc_task_config`,流式用 `joc_stream_config`, -其中 `hrtf_sofa_path`(或 `hrtf_path`)、`sofa_interpolation`、`hrtf_radius_m`、 -`source_reference_distance_m`、`sofa_room`、`sofa_room_preset`、`sofa_room_asset_dir`、 -`hrtf_compile`、`kernels_path`、`binaural_mode`、`binaural_tail_seconds` 决定双耳通路。 +其中 `hrtf_path`、`kernels_path`、`binaural_mode`、`binaural_tail_seconds` 决定双耳通路。 `.jochrtf` 是**输入**而不是本库的产物:从 SOFA 或测量数据编译该缓存属于工具链的职责, 与本仓库解耦。缓存加载时会校验成员集合、dtype 与形状、C 连续性、CRC-32 以及按成员重算的 @@ -114,39 +50,6 @@ joc_cli input.m4a --binaural ` `off=0/near=1/far=2/mid=3`,前 10 个 bed 保持不变,默认 `mid`;`off` 用于显式 关闭双耳元数据提示。 -## Canonical SOFA 契约 - -当前 strict importer 接受: - -- `Conventions=SOFA`; -- `SOFAConventions=SimpleFreeFieldHRIR`,version `0.4`、`1.0` 或 `1.1`; -- `DataType=FIR`,`Data.IR[M,2,N]`; -- 单一正有限 `Data.SamplingRate`,单位为 hertz/Hz; -- spherical 或 Cartesian `SourcePosition`; -- 单值或 per-measurement 的 `ListenerPosition/View/Up`; -- 两个能由 listener-local lateral 坐标唯一识别左右的 receiver; -- 单一且零偏移的 emitter; -- causal `Data.Delay[I,2]` 或 `[M,2]`; -- 明确的 free-field/anechoic `RoomType`。 - -receiver 左右顺序由几何决定,不能假定 `Data.IR` 的 receiver index。SOFA listener -坐标为 $+X$ front、 -$+Y$ left、 -$+Z$ up;ADM 坐标为 -$+X$ right、 -$+Y$ front、 -$+Z$ up,转换为: - -$$\bigl(x_{\mathrm{SOFA}},\ y_{\mathrm{SOFA}},\ z_{\mathrm{SOFA}}\bigr) = \bigl(y_{\mathrm{ADM}},\ -x_{\mathrm{ADM}},\ z_{\mathrm{ADM}}\bigr)$$ - -`CanonicalHrtf` 将 `Data.IR` 与 `Data.Delay` 分开保存。只有时域 baseline 才调用 -`materialized_measurement()` 将 delay 应用一次;运行时 SH 路径不先 materialize。 -非 48 kHz HRIR 使用 float64 `scipy.signal.resample_poly` 规范化,delay samples 按 -相同比例缩放。 - -GeneralFIR、BRIR、TF、多 emitter、多义 receiver 或非 free-field 数据需要单独的 -convention adapter,不能只通过 reshape 进入核心 importer。 - ## Delay/phase:exactly once 编译器只允许三种互斥语义: @@ -159,9 +62,6 @@ convention adapter,不能只通过 reshape 进入核心 importer。 任何路径都不能再叠加第二套 ear delay 或 phase-group delay。 -SOFA 直连路径不走这套编译期语义:它保留完整 IR,用 200-1500 Hz 相位拟合估计到达时间, -`Data.Delay` 与拟合出的延迟各应用一次(先去掉 `Data.Delay`,再用插值后的延迟复原)。 - ## 公开 filterbank 与方向场 运行时固定为: @@ -232,8 +132,7 @@ loader 使用 `allow_pickle=False`,并在构造对象前检查 ZIP 成员集 dtype、端序、连续布局、有限值、delay bounds、band centers、payload hash 和 cache key。writer 使用同目录临时文件、`fsync`、进程持有的 OS 文件锁和原子 `os.replace`;对应的隐藏 `.lock` sidecar 可保留,但不代表仍有 writer 持锁。 -旧版本、损坏或配置不匹配的 cache 不能命中;从 SOFA 启动时会重建,显式 cache -入口则直接报错。 +旧版本、损坏或配置不匹配的 cache 不会命中,而是直接报错。 删除磁盘 cache 后,从同一 SOFA 和同一编译配置得到的场与渲染结果不得改变。 @@ -251,7 +150,7 @@ key。writer 使用同目录临时文件、`fsync`、进程持有的 OS 文件 | 取值 | 滤波器组 | 低频 hybrid | 高频 slot delay | 延迟 | | --- | --- | --- | --- | ---: | -| `1`(默认) | `PublicFilterbank`(与 SOFA 路径共用) | 13 taps | 6 slots | 961 samples | +| `1`(默认) | `PublicFilterbank`(与 Rosella 路径共用) | 13 taps | 6 slots | 961 samples | | `2` | `RosellaFilterbank`(从参考渲染器捕获) | 11 taps | 3 slots | 448 samples | 两套实现通过同一组四个有状态 half-step 调用,因此切换时系数、高频 delay、历史缓冲 @@ -275,7 +174,7 @@ unitary FDN、LFE 120–180 Hz cosine-squared 低通及 room calibration 都是 项目定义行为,不是 SOFA 或 Dolby 公布常数。 双耳渲染在本库内实现:filterbank、SH 方向场求值、逐对象 early/direct 历史与共享 FDN -全部执行于 `joc_core`(`ejoc_sofa_binaural_*` 内核),对外只消费编译好的方向场与 +全部执行于 `joc_core`(`ejoc_jochrtf_*` 内核),对外只消费编译好的方向场与 512-sample 粒度的元数据更新。 ## 技术引用与权利边界 diff --git a/include/eac3joc_core.h b/include/eac3joc_core.h index d6487a5..811274e 100644 --- a/include/eac3joc_core.h +++ b/include/eac3joc_core.h @@ -188,19 +188,19 @@ per-object whole-QMF-slot delay histories, six first-order image-source early reflections, the shared unitary-FDN late room, the 120-180 Hz LFE low-pass and the 961-sample latency compensation. The caller configures the filterbank tables, the compiled HRTF field and the room constants once, then per 512-sample -block updates every source with ejoc_sofa_binaural_set_source() and calls -ejoc_sofa_binaural_process(). Process returns the number of trimmed stereo +block updates every source with ejoc_jochrtf_set_source() and calls +ejoc_jochrtf_process(). Process returns the number of trimmed stereo samples written; the first 961 processed samples across calls are discarded. */ -typedef void* ejoc_sofa_binaural_handle; +typedef void* ejoc_jochrtf_handle; -EJOC_API ejoc_sofa_binaural_handle EJOC_CALL ejoc_sofa_binaural_create(void); -EJOC_API void EJOC_CALL ejoc_sofa_binaural_destroy(ejoc_sofa_binaural_handle handle); -EJOC_API int EJOC_CALL ejoc_sofa_binaural_reset(ejoc_sofa_binaural_handle handle); -EJOC_API const char* EJOC_CALL ejoc_sofa_binaural_last_error( - ejoc_sofa_binaural_handle handle); -EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_kernels( - ejoc_sofa_binaural_handle handle, +EJOC_API ejoc_jochrtf_handle EJOC_CALL ejoc_jochrtf_create(void); +EJOC_API void EJOC_CALL ejoc_jochrtf_destroy(ejoc_jochrtf_handle handle); +EJOC_API int EJOC_CALL ejoc_jochrtf_reset(ejoc_jochrtf_handle handle); +EJOC_API const char* EJOC_CALL ejoc_jochrtf_last_error( + ejoc_jochrtf_handle handle); +EJOC_API int EJOC_CALL ejoc_jochrtf_configure_kernels( + ejoc_jochrtf_handle handle, const double* qmf_analysis, const double* hybrid_low, const int16_t* hybrid_indices, @@ -208,15 +208,15 @@ EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_kernels( uint32_t hybrid_count, const double* qmf_basis, const double* qmf_taps); -EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_field( - ejoc_sofa_binaural_handle handle, +EJOC_API int EJOC_CALL ejoc_jochrtf_configure_field( + ejoc_jochrtf_handle handle, const double* coefficients, const double* delay_coefficients, const double* delay_bounds, const double* band_centers, double measurement_radius_m); -EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_room( - ejoc_sofa_binaural_handle handle, +EJOC_API int EJOC_CALL ejoc_jochrtf_configure_room( + ejoc_jochrtf_handle handle, const double* room_dims, const double* listener_pos, const double* wall_gains, @@ -229,8 +229,8 @@ EJOC_API int EJOC_CALL ejoc_sofa_binaural_configure_room( const double* allpass_gains, uint32_t enable_early_reflections, uint32_t enable_late_room); -EJOC_API int EJOC_CALL ejoc_sofa_binaural_set_source( - ejoc_sofa_binaural_handle handle, +EJOC_API int EJOC_CALL ejoc_jochrtf_set_source( + ejoc_jochrtf_handle handle, uint32_t source, const double* position_adm, uint32_t profile, @@ -238,14 +238,14 @@ EJOC_API int EJOC_CALL ejoc_sofa_binaural_set_source( uint32_t enabled, uint32_t special_lfe, uint32_t fade); -EJOC_API int EJOC_CALL ejoc_sofa_binaural_process( - ejoc_sofa_binaural_handle handle, +EJOC_API int EJOC_CALL ejoc_jochrtf_process( + ejoc_jochrtf_handle handle, const double* input16_interleaved, uint32_t sample_count, double output_gain, double* output_stereo_interleaved); -EJOC_API int EJOC_CALL ejoc_sofa_binaural_finish( - ejoc_sofa_binaural_handle handle, +EJOC_API int EJOC_CALL ejoc_jochrtf_finish( + ejoc_jochrtf_handle handle, uint32_t flush_samples, double* output_stereo_interleaved, uint32_t capacity); diff --git a/include/joc_core.h b/include/joc_core.h index e9407b8..428597b 100644 --- a/include/joc_core.h +++ b/include/joc_core.h @@ -39,7 +39,7 @@ #define JOC_ABI_VERSION 5u #define JOC_FRAME_PARAMS_VERSION 1u #define JOC_EMDF_INFO_VERSION 1u -#define JOC_TASK_CONFIG_VERSION 5u +#define JOC_TASK_CONFIG_VERSION 4u #define JOC_TASK_RESULT_VERSION 2u #define JOC_EVENT_VERSION 1u @@ -358,20 +358,6 @@ typedef enum joc_clip_action { JOC_CLIP_ABORT = 3 /* fail the task */ } joc_clip_action; -/* Local interpolation of the full-HRIR SOFA field (config version 3). */ -typedef enum joc_sofa_interpolation { - JOC_SOFA_INTERPOLATION_LOGMAG_PHASE = 0, /* delay-aligned log-magnitude/phase */ - JOC_SOFA_INTERPOLATION_MCA_ZERO = 1 /* auditory-band magnitude correction */ -} joc_sofa_interpolation; - -/* Compiled-HRTF cache policy for the legacy SOFA compile step; the .jochrtf - * itself stays an explicit input (hrtf_path). */ -typedef enum joc_hrtf_cache_policy { - JOC_HRTF_CACHE_NONE = 0, /* compile and discard */ - JOC_HRTF_CACHE_MEMORY = 1, /* compile and keep in this process (default) */ - JOC_HRTF_CACHE_DISK = 2 /* compile, reuse and write /.jochrtf */ -} joc_hrtf_cache_policy; - /* Which 64-QMF / 77-hybrid filterbank the Rosella .personalized_headphone path * renders through. The two banks differ in coefficients, hybrid tap count, * high-band slot delay and total latency, so they are not interchangeable; the @@ -430,24 +416,11 @@ typedef struct joc_task_config { joc_cancel_token* cancel; /* optional */ - /* Binaural HRTF input: when hrtf_sofa_path is set the SOFA renders directly - * from its full HRIRs through the reference environment (config version 3) - * and hrtf_path is unused. hrtf_path stays the advanced override that reads - * a .jochrtf directly with the compiled-field renderer. */ - const char* hrtf_sofa_path; /* SOFA SimpleFreeFieldHRIR input */ + /* Binaural input (config version 2): a compiled .jochrtf field (hrtf_path) + * or a Rosella .personalized_headphone model. */ const char* personalized_headphone_path; /* Rosella .personalized_headphone input */ - const char* hrtf_cache_dir; /* disk policy directory */ - uint32_t hrtf_cache_policy; /* joc_hrtf_cache_policy */ uint32_t rosella_filterbank; /* joc_rosella_filterbank; 0 = PUBLIC */ - double hrtf_radius_m; /* SOFA shell radius; <= 0 = automatic */ - /* Direct SOFA rendering (config version 5). */ - uint32_t sofa_interpolation; /* joc_sofa_interpolation */ - double source_reference_distance_m; /* > 0 overrides the mode's reference distance */ - uint32_t sofa_room; /* non-zero enables the project room */ - const char* sofa_room_preset; /* "compact" or "legacy"; NULL = by mode */ - /* Nonzero keeps the legacy SOFA compile step (hrtf_cache_policy/hrtf_cache_dir - * decide where the .jochrtf lands); zero renders the SOFA directly. */ - uint32_t hrtf_compile; + uint32_t jochrtf_room; /* non-zero enables the project room */ } joc_task_config; typedef enum joc_task_status { diff --git a/include/joc_stream.h b/include/joc_stream.h index 27c02a5..7511483 100644 --- a/include/joc_stream.h +++ b/include/joc_stream.h @@ -64,20 +64,10 @@ typedef struct joc_stream_config { double gain_db; /* default 0 */ uint32_t native_threads; uint32_t rosella_filterbank; /* joc_rosella_filterbank; Rosella input, 0 = PUBLIC */ - /* Binaural HRTF input, the same three shapes joc_task_config accepts: when - * hrtf_sofa_path is set the library compiles it with hrtf_cache_policy / - * hrtf_cache_dir / hrtf_radius_m and hrtf_path is unused; when - * personalized_headphone_path is set the Rosella runtime renders instead. - * hrtf_path stays the fallback/advanced input that reads a .jochrtf directly. */ - const char* hrtf_sofa_path; /* SOFA SimpleFreeFieldHRIR input */ + /* Binaural input, the same shapes joc_task_config accepts: a compiled + * .jochrtf field (hrtf_path) or a Rosella .personalized_headphone model. */ const char* personalized_headphone_path; /* Rosella .personalized_headphone input */ - const char* hrtf_cache_dir; /* disk cache directory for SOFA compilation */ - uint32_t hrtf_cache_policy; /* joc_hrtf_cache_policy: 0 none, 1 memory, 2 disk */ - double hrtf_radius_m; /* SOFA measurement-radius shell, default 1.0 */ - /* Direct SOFA rendering: the same fields joc_task_config carries. */ - double source_reference_distance_m; /* > 0 overrides the mode's reference distance */ - uint32_t sofa_room; /* non-zero enables the project room */ - const char* sofa_room_preset; /* "compact" or "legacy"; NULL = by mode */ + uint32_t jochrtf_room; /* non-zero enables the project room */ } joc_stream_config; typedef struct joc_stream_buffer { diff --git a/src/api/joc_stream_api.cpp b/src/api/joc_stream_api.cpp index 43e125c..6cb6bf0 100644 --- a/src/api/joc_stream_api.cpp +++ b/src/api/joc_stream_api.cpp @@ -36,23 +36,15 @@ joc::stream::Config to_config(const joc_stream_config& config) { } out.gain_db = config.gain_db; out.native_threads = config.native_threads; - // The binaural HRTF inputs of joc_task_config, copied with the same defaults: - // the policy is taken verbatim (0 is "none", a real choice, not "unset") and - // the radius keeps its documented default of 1.0 when the field is not set. - if (config.hrtf_sofa_path != nullptr) { out.hrtf_sofa_path = config.hrtf_sofa_path; } if (config.personalized_headphone_path != nullptr) { out.personalized_headphone_path = config.personalized_headphone_path; } - if (config.hrtf_cache_dir != nullptr) { out.hrtf_cache_dir = config.hrtf_cache_dir; } - out.hrtf_cache_policy = config.hrtf_cache_policy; - if (config.hrtf_radius_m > 0.0) { out.hrtf_radius_m = config.hrtf_radius_m; } + // 0 is the documented "off" spelling for the room switch. + out.jochrtf_room = config.jochrtf_room; // 0 is "unset" here as well: the Rosella path defaults to the public bank. if (config.rosella_filterbank != 0u) { out.rosella_filterbank = config.rosella_filterbank; } - out.source_reference_distance_m = config.source_reference_distance_m; - out.sofa_room = config.sofa_room != 0u; - if (config.sofa_room_preset != nullptr) { out.sofa_room_preset = config.sofa_room_preset; } return out; } diff --git a/src/binaural/direct_sofa_runtime.cpp b/src/binaural/direct_sofa_runtime.cpp deleted file mode 100644 index 851c871..0000000 --- a/src/binaural/direct_sofa_runtime.cpp +++ /dev/null @@ -1,432 +0,0 @@ -#include "binaural/direct_sofa_runtime.h" - -#include -#include -#include - -#include "foundation/fft.h" -#include "hrtf/sofa.h" -#include "hrtf/sofa_field.h" - -namespace joc::binaural { -namespace { - -constexpr double kPi = 3.141592653589793238462643383279502884; - -Status runtime_error(const char* message) { - return Status::fail(JOC_ERR_INVALID_ARGUMENT, joc::stage::kRender, message); -} - -Status render_fail(const char* message) { - return Status::fail(JOC_ERR_HRTF_FORMAT, joc::stage::kDsp, message); -} - -// One ear of a measured HRIR: inverse real transform, then undo the common delay. -void ear_impulse(const std::vector>& spectrum, std::size_t ear, - std::size_t bins, std::size_t fft_size, std::vector* out) { - std::vector> buffer(fft_size, std::complex(0.0, 0.0)); - for (std::size_t bin = 0; bin < bins; ++bin) { - buffer[bin] = spectrum[ear * bins + bin]; - } - for (std::size_t bin = 1; bin + 1 < bins; ++bin) { - buffer[fft_size - bin] = std::conj(spectrum[ear * bins + bin]); - } - dsp::fft_radix2(&buffer, true); - out->resize(fft_size); - for (std::size_t sample = 0; sample < fft_size; ++sample) { - (*out)[(sample + fft_size / 2u) % fft_size] = buffer[sample].real(); - } -} - -// scipy.signal.firwin(129, 150, fs=48000): windowed-sinc, unit DC gain. -std::vector lowpass_150(double sample_rate) { - constexpr int kTaps = 129; - const double cutoff = 150.0 / (sample_rate * 0.5); - std::vector taps(kTaps, 0.0); - double total = 0.0; - for (int index = 0; index < kTaps; ++index) { - const double position = static_cast(index) - 0.5 * (kTaps - 1); - double value = 0.0; - if (std::fabs(position) < 1e-12) { - value = cutoff; - } else { - value = cutoff * std::sin(kPi * cutoff * position) / (kPi * position); - } - const double window = 0.54 - 0.46 * std::cos(2.0 * kPi * index / (kTaps - 1)); - taps[static_cast(index)] = value * window; - total += value * window; - } - for (double& value : taps) { - value /= total; - } - return taps; -} - -} // namespace - -DirectSofaRuntime::DirectSofaRuntime() = default; -DirectSofaRuntime::~DirectSofaRuntime() = default; - -Status DirectSofaRuntime::open(const std::string& sofa_path, const DirectSofaOptions& options) { - output_gain_ = options.output_gain; - Status status = reference_.configure(options.mode, options.has_reference_distance, - options.reference_distance_m); - if (!status.ok()) { - return status; - } - hrtf::SofaHrir sofa; - status = hrtf::load_sofa(sofa_path, &sofa); - if (!status.ok()) { - return status; - } - hrtf::CanonicalHrtf canonical; - status = hrtf::canonicalize_sofa(sofa, &canonical); - if (!status.ok()) { - return status; - } - hrtf::FullHrirOptions field_options; - field_options.method = options.interpolation; - field_options.has_shell_radius = options.has_shell_radius; - field_options.shell_radius_m = options.shell_radius_m; - status = field_.build(canonical, field_options); - if (!status.ok()) { - return status; - } - fft_size_ = field_.fft_size(); - bins_ = field_.frequency_bins(); - origin_samples_ = field_.recording_origin_samples(); - if (origin_samples_ < 0) { - return runtime_error("negative recording origin requires an explicit time base"); - } - latency_samples_ = field_.common_latency_samples(); - filter_taps_ = fft_size_; - - if (options.sofa_room) { - const std::string preset = options.room_preset.empty() - ? (reference_.mode() == "far" ? "legacy" : "compact") - : options.room_preset; - if (preset != "compact" && preset != "legacy") { - return runtime_error("room preset must be compact or legacy"); - } - status = room_.configure(static_cast(kDirectSofaSources), reference_, - latency_samples_, origin_samples_, preset); - if (!status.ok()) { - return status; - } - filter_taps_ = room_.filter_budget(field_); - } - convolver_.configure(static_cast(kDirectSofaSources), kDirectSofaBlock, - filter_taps_, 2u); - status = build_lfe_filter(); - if (!status.ok()) { - return status; - } - hop_block_.assign(kDirectSofaBlock * kDirectSofaSources, 0.0); - staging_.assign(static_cast(kDirectSofaFrame) * kDirectSofaSources, 0.0); - direct_.assign(kDirectSofaBlock * 2u, 0.0); - distance_states_.assign(kDirectSofaSources, PointSourcePosition{}); - has_state_.assign(kDirectSofaSources, 0); - std::memset(last_key_, 0, sizeof(last_key_)); - pending_filters_.clear(); - return reset(); -} - -Status DirectSofaRuntime::build_lfe_filter() { - const std::vector lowpass = lowpass_150(48000.0); - lfe_filter_.assign(2u * fft_size_, 0.0); - const int start = latency_samples_ + std::max(origin_samples_, 0) - 64; - if (start < 0 || static_cast(start) + lowpass.size() > fft_size_) { - return render_fail("LFE latency exceeds the filter budget"); - } - const double scale = 1.0 / std::sqrt(2.0); - for (std::size_t ear = 0; ear < 2u; ++ear) { - for (std::size_t tap = 0; tap < lowpass.size(); ++tap) { - lfe_filter_[ear * fft_size_ + static_cast(start) + tap] = - lowpass[tap] * scale; - } - } - return Status::success(); -} - -Status DirectSofaRuntime::reset() { - convolver_.reset(); - room_.reset(); - timeline_.reset(); - output_.clear(); - pending_filters_.clear(); - std::fill(has_state_.begin(), has_state_.end(), 0); - std::memset(last_key_, 0, sizeof(last_key_)); - input_samples_ = 0; - processed_input_samples_ = 0; - parameter_updates_ = 0; - output_samples_ = 0; - latency_remaining_ = latency_samples_; - return Status::success(); -} - -void DirectSofaRuntime::schedule_filter(std::size_t source, - const std::vector& filters, std::size_t taps, - bool first, bool fade) { - if (first) { - convolver_.set_filter(source, filters.data(), taps, 0u); - return; - } - const std::int64_t due = - processed_input_samples_ + static_cast(field_.common_latency_samples()); - for (std::size_t index = pending_filters_.size(); index-- > 0;) { - if (pending_filters_[index].due != due) { - break; - } - if (pending_filters_[index].source == source) { - pending_filters_[index].filters = filters; - pending_filters_[index].taps = taps; - pending_filters_[index].fade_blocks = fade ? 1u : 0u; - return; - } - } - PendingFilter pending; - pending.due = due; - pending.source = source; - pending.filters = filters; - pending.taps = taps; - pending.fade_blocks = fade ? 1u : 0u; - pending_filters_.push_back(std::move(pending)); -} - -void DirectSofaRuntime::apply_due_filters() { - while (!pending_filters_.empty() && - pending_filters_.front().due <= processed_input_samples_) { - PendingFilter pending = std::move(pending_filters_.front()); - pending_filters_.pop_front(); - convolver_.set_filter(pending.source, pending.filters.data(), pending.taps, - pending.fade_blocks); - } -} - -Status DirectSofaRuntime::set_source(int source, const double position[3], double gain, - bool special_lfe, bool fade) { - if (source < 0 || source >= kDirectSofaSources) { - return runtime_error("source index is out of range"); - } - if (!std::isfinite(gain)) { - return runtime_error("source gain must be finite"); - } - const std::size_t slot = static_cast(source); - double key[5] = {position[0], position[1], position[2], gain, special_lfe ? 1.0 : 0.0}; - bool unchanged = has_state_[slot] != 0; - for (int axis = 0; axis < 5 && unchanged; ++axis) { - unchanged = last_key_[slot][axis] == key[axis]; - } - if (unchanged) { - return Status::success(); - } - for (int axis = 0; axis < 5; ++axis) { - last_key_[slot][axis] = key[axis]; - } - const bool first = processed_input_samples_ == 0; - if (special_lfe) { - if (room_.active()) { - const Status room_status = room_.set_source(slot, nullptr, gain, first, true); - if (!room_status.ok()) { - return room_status; - } - } - std::vector filters = lfe_filter_; - for (double& value : filters) { - value *= gain; - } - schedule_filter(slot, filters, fft_size_, first, fade); - } else { - const std::array xyz = {position[0], position[1], position[2]}; - const std::array* previous = - has_state_[slot] != 0 ? &distance_states_[slot].direction : nullptr; - PointSourcePosition state; - Status status = reference_.map_position(xyz, previous, &state); - if (!status.ok()) { - return status; - } - std::vector filters; - std::size_t taps = 0; - if (room_.active()) { - status = room_.full_hrir(field_, state, filter_taps_, &filters); - if (!status.ok()) { - return status; - } - taps = filter_taps_; - } else { - std::vector> spectrum; - status = field_.spectrum(state.direction.data(), &spectrum); - if (!status.ok()) { - return status; - } - filters.assign(2u * fft_size_, 0.0); - std::vector impulse; - for (std::size_t ear = 0; ear < 2u; ++ear) { - ear_impulse(spectrum, ear, bins_, fft_size_, &impulse); - std::copy(impulse.begin(), impulse.end(), - filters.begin() + static_cast(ear * fft_size_)); - } - taps = fft_size_; - } - for (double& value : filters) { - value *= gain; - } - schedule_filter(slot, filters, taps, first, fade); - distance_states_[slot] = state; - if (room_.active()) { - status = room_.set_source(slot, &state, gain, first, false); - if (!status.ok()) { - return status; - } - } - } - has_state_[slot] = 1; - ++parameter_updates_; - return Status::success(); -} - -Status DirectSofaRuntime::process_block() { - apply_due_filters(); - const Status status = convolver_.process_block(hop_block_.data(), direct_.data()); - if (!status.ok()) { - return status; - } - processed_input_samples_ += static_cast(kDirectSofaBlock); - if (room_.active()) { - bool produced = false; - const Status room_status = room_.process(hop_block_.data(), kDirectSofaSources, - direct_.data(), &room_out_, &produced); - if (!room_status.ok()) { - return room_status; - } - if (produced) { - emit(room_out_.data(), room_out_.size() / 2u); - } - return Status::success(); - } - emit(direct_.data(), kDirectSofaBlock); - return Status::success(); -} - -void DirectSofaRuntime::emit(const double* interleaved, std::size_t samples) { - const std::size_t skip = static_cast( - std::min(static_cast(samples), latency_remaining_)); - latency_remaining_ -= static_cast(skip); - for (std::size_t sample = skip; sample < samples; ++sample) { - output_.push_back(interleaved[sample * 2u] * output_gain_); - output_.push_back(interleaved[sample * 2u + 1u] * output_gain_); - } - output_samples_ += samples - skip; -} - -Status DirectSofaRuntime::submit_frame(const float* objects16_planar, - const oamd::OamdUpdate* update, - std::int64_t /*frame_index*/, - std::int64_t outer_sample_offset, - std::int64_t object_delay_samples) { - if (objects16_planar == nullptr) { - return runtime_error("frame buffer is null"); - } - for (std::size_t channel = 0; channel < kDirectSofaSources; ++channel) { - for (std::size_t sample = 0; sample < static_cast(kDirectSofaFrame); - ++sample) { - staging_[sample * kDirectSofaSources + channel] = - static_cast(objects16_planar[channel * kDirectSofaFrame + sample]); - } - } - if (update != nullptr) { - const Status status = timeline_.submit_update(*update, input_samples_, - outer_sample_offset, - object_delay_samples, - processed_input_samples_); - if (!status.ok()) { - return status; - } - } - input_samples_ += kDirectSofaFrame; - double positions[timeline::kTimelineObjects][3] = {}; - for (std::size_t block = 0; block < 12u; ++block) { - Status status = timeline_.positions_at(processed_input_samples_, positions); - if (!status.ok()) { - return status; - } - status = set_source(0, kDirectSofaLfePosition, 1.0, true, true); - if (!status.ok()) { - return status; - } - for (int object = 0; object < timeline::kTimelineObjects; ++object) { - status = set_source(object + 1, positions[object], 1.0, false, true); - if (!status.ok()) { - return status; - } - } - for (std::size_t sample = 0; sample < kDirectSofaBlock; ++sample) { - for (std::size_t channel = 0; channel < kDirectSofaSources; ++channel) { - hop_block_[sample * kDirectSofaSources + channel] = - staging_[(block * kDirectSofaBlock + sample) * kDirectSofaSources + channel]; - } - } - status = process_block(); - if (!status.ok()) { - return status; - } - } - return Status::success(); -} - -std::uint32_t DirectSofaRuntime::finish_capacity(double tail_seconds) const { - const double samples = tail_seconds * 48000.0 + static_cast(latency_samples_) + - static_cast(filter_taps_); - const double blocks = std::ceil(samples / 128.0); - return static_cast(std::max(0.0, blocks * 128.0)); -} - -Status DirectSofaRuntime::finish(std::uint32_t flush_samples, std::vector* out) { - if (out == nullptr) { - return runtime_error("finish output is null"); - } - const std::size_t before = output_.size(); - std::size_t count = flush_samples; - const std::int64_t expected = std::max( - 0, processed_input_samples_ + static_cast(count) - latency_samples_ - - static_cast(output_samples_)); - if (room_.active()) { - const std::size_t pending = room_.pending_samples(); - const double batches = std::ceil(static_cast(count + pending) / - static_cast(kSofaRoomBatchSamples)); - count = static_cast( - std::max(0.0, batches * static_cast(kSofaRoomBatchSamples) - - static_cast(pending))); - } - std::fill(hop_block_.begin(), hop_block_.end(), 0.0); - double positions[timeline::kTimelineObjects][3] = {}; - for (std::size_t block = 0; block < count / kDirectSofaBlock; ++block) { - Status status = timeline_.positions_at(processed_input_samples_, positions); - if (!status.ok()) { - return status; - } - status = set_source(0, kDirectSofaLfePosition, 1.0, true, true); - if (!status.ok()) { - return status; - } - for (int object = 0; object < timeline::kTimelineObjects; ++object) { - status = set_source(object + 1, positions[object], 1.0, false, true); - if (!status.ok()) { - return status; - } - } - status = process_block(); - if (!status.ok()) { - return status; - } - } - std::vector tail(output_.begin() + static_cast(before), output_.end()); - if (static_cast(tail.size() / 2u) > expected) { - tail.resize(static_cast(expected) * 2u); - } - output_.resize(before + tail.size()); - out->swap(tail); - return Status::success(); -} - -} // namespace joc::binaural diff --git a/src/binaural/direct_sofa_runtime.h b/src/binaural/direct_sofa_runtime.h deleted file mode 100644 index d49580b..0000000 --- a/src/binaural/direct_sofa_runtime.h +++ /dev/null @@ -1,133 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include "binaural/point_source.h" -#include "binaural/sofa_room.h" -#include "foundation/status.h" -#include "hrtf/full_hrir_field.h" -#include "hrtf/partitioned_convolution.h" -#include "oamd/oamd_parser.h" -#include "timeline/position_timeline.h" - -// Direct SOFA renderer: full HRIR per source, point-source coordinates, and the -// optional project-owned room. Ported from the reference src/sofa_direct_backend.py; -// there is no distance-dependent HRTF adaptation and no external reference model. -namespace joc::binaural { - -inline constexpr int kDirectSofaSources = 16; -inline constexpr std::size_t kDirectSofaBlock = 128; -inline constexpr int kDirectSofaFrame = 1536; -inline constexpr double kDirectSofaLfePosition[3] = {0.0, 1.0, 0.0}; - -struct DirectSofaOptions { - std::string mode; // near/mid/far; empty selects mid - bool has_reference_distance = false; - double reference_distance_m = 0.0; - hrtf::HrirInterpolation interpolation = hrtf::HrirInterpolation::kLogMagnitudePhase; - bool has_shell_radius = false; - double shell_radius_m = 0.0; - double output_gain = 1.0; - // Optional project room; `room_preset` is compact/legacy (empty selects - // legacy for far and compact otherwise). - bool sofa_room = false; - std::string room_preset; - std::int64_t object_delay_samples = 1473; - double tail_seconds = 5.0; -}; - -class DirectSofaRuntime { -public: - DirectSofaRuntime(); - ~DirectSofaRuntime(); - DirectSofaRuntime(const DirectSofaRuntime&) = delete; - DirectSofaRuntime& operator=(const DirectSofaRuntime&) = delete; - - Status open(const std::string& sofa_path, const DirectSofaOptions& options); - - // objects16_planar is channel-major: channel * 1536 + sample. - Status submit_frame(const float* objects16_planar, const oamd::OamdUpdate* update, - std::int64_t frame_index, std::int64_t outer_sample_offset, - std::int64_t object_delay_samples); - - Status finish(std::uint32_t flush_samples, std::vector* out); - std::uint32_t finish_capacity(double tail_seconds) const; - Status reset(); - - const std::vector& output() const { return output_; } - void take_output(std::vector* out) { - out->swap(output_); - output_.clear(); - } - - void set_fixed_position(int object_index, const double position[3]) { - timeline_.set_fixed_position(object_index, position); - } - - const timeline::OamdPositionTimeline& timeline() const { return timeline_; } - std::uint64_t input_samples() const { return input_samples_; } - std::uint64_t processed_input_samples() const { return processed_input_samples_; } - std::uint64_t parameter_updates() const { return parameter_updates_; } - int latency_samples() const { return latency_samples_; } - int recording_origin_samples() const { return origin_samples_; } - std::size_t filter_taps() const { return filter_taps_; } - bool room_active() const { return room_.active(); } - const std::string& room_preset() const { return room_.preset(); } - const hrtf::FullHrirField& field() const { return field_; } - const PointSourceReference& reference() const { return reference_; } - -private: - struct PendingFilter { - std::int64_t due = 0; - std::size_t source = 0; - std::vector filters; - std::size_t taps = 0; - std::uint32_t fade_blocks = 0; - }; - - Status set_source(int source, const double position[3], double gain, bool special_lfe, - bool fade); - void schedule_filter(std::size_t source, const std::vector& filters, - std::size_t taps, bool first, bool fade); - void apply_due_filters(); - Status process_block(); - void emit(const double* interleaved, std::size_t samples); - Status build_lfe_filter(); - - PointSourceReference reference_; - hrtf::FullHrirField field_; - SofaRoom room_; - hrtf::MultiSourcePartitionedConvolver convolver_; - - std::vector lfe_filter_; // [2][fft_size] - std::deque pending_filters_; - - std::vector distance_states_; - std::vector has_state_; - double last_key_[kDirectSofaSources][5] = {}; - - std::vector hop_block_; // [128][sources] - std::vector staging_; // [1536][sources] - std::vector direct_; // [128][2] - std::vector room_out_; // [1536][2] when the room produced a batch - std::vector output_; - - timeline::OamdPositionTimeline timeline_; - std::int64_t input_samples_ = 0; - std::int64_t processed_input_samples_ = 0; - std::uint64_t parameter_updates_ = 0; - std::uint64_t output_samples_ = 0; - int origin_samples_ = 0; - int latency_samples_ = 0; - std::size_t filter_taps_ = 0; - std::size_t fft_size_ = 0; - std::size_t bins_ = 0; - std::int64_t latency_remaining_ = 0; - double output_gain_ = 1.0; -}; - -} // namespace joc::binaural diff --git a/src/binaural/sofa_binaural_renderer.cpp b/src/binaural/jochrtf_renderer.cpp similarity index 98% rename from src/binaural/sofa_binaural_renderer.cpp rename to src/binaural/jochrtf_renderer.cpp index f13fefd..49e86d0 100644 --- a/src/binaural/sofa_binaural_renderer.cpp +++ b/src/binaural/jochrtf_renderer.cpp @@ -1,7 +1,7 @@ // Derived from the upstream native/src/sofa_binaural_renderer.cpp (JustOneCacophony // @ 6bc2c2885666bb151bb66af93472199af9a99b81, sha256 81b485e4c71907672ab308ddc38228 // 4acf29161cee93d7906785a4cce58941c7) and a drop-in replacement for it: the same -// ejoc_sofa_binaural_* C ABI. The changes are table hoisting, result memoisation, +// ejoc_jochrtf_* C ABI. The changes are table hoisting, result memoisation, // input validation and a dispatched SIMD cascade -- no arithmetic is reordered, // reassociated or contracted, so the output is bit-identical to the upstream // implementation (verified: identical FNV-1a over the exact output bit patterns at @@ -1378,7 +1378,7 @@ using ejoc::sofa_binaural::Renderer; extern "C" { -ejoc_sofa_binaural_handle EJOC_CALL ejoc_sofa_binaural_create(void) { +ejoc_jochrtf_handle EJOC_CALL ejoc_jochrtf_create(void) { try { return new (std::nothrow) Renderer(); } catch (...) { @@ -1386,21 +1386,21 @@ ejoc_sofa_binaural_handle EJOC_CALL ejoc_sofa_binaural_create(void) { } } -void EJOC_CALL ejoc_sofa_binaural_destroy(ejoc_sofa_binaural_handle handle) { +void EJOC_CALL ejoc_jochrtf_destroy(ejoc_jochrtf_handle handle) { delete static_cast(handle); } -int EJOC_CALL ejoc_sofa_binaural_reset(ejoc_sofa_binaural_handle handle) { +int EJOC_CALL ejoc_jochrtf_reset(ejoc_jochrtf_handle handle) { return handle ? static_cast(handle)->reset() : -1; } -const char* EJOC_CALL ejoc_sofa_binaural_last_error( - ejoc_sofa_binaural_handle handle) { +const char* EJOC_CALL ejoc_jochrtf_last_error( + ejoc_jochrtf_handle handle) { return handle ? static_cast(handle)->error() : "null handle"; } -int EJOC_CALL ejoc_sofa_binaural_configure_kernels( - ejoc_sofa_binaural_handle handle, const double* qmf_analysis, +int EJOC_CALL ejoc_jochrtf_configure_kernels( + ejoc_jochrtf_handle handle, const double* qmf_analysis, const double* hybrid_low, const int16_t* hybrid_indices, const double* hybrid_values, uint32_t hybrid_count, const double* qmf_basis, const double* qmf_taps) { @@ -1409,8 +1409,8 @@ int EJOC_CALL ejoc_sofa_binaural_configure_kernels( qmf_basis, qmf_taps) : -1; } -int EJOC_CALL ejoc_sofa_binaural_configure_field( - ejoc_sofa_binaural_handle handle, const double* coefficients, +int EJOC_CALL ejoc_jochrtf_configure_field( + ejoc_jochrtf_handle handle, const double* coefficients, const double* delay_coefficients, const double* delay_bounds, const double* band_centers, double measurement_radius_m) { return handle ? static_cast(handle)->configure_field( @@ -1418,8 +1418,8 @@ int EJOC_CALL ejoc_sofa_binaural_configure_field( measurement_radius_m) : -1; } -int EJOC_CALL ejoc_sofa_binaural_configure_room( - ejoc_sofa_binaural_handle handle, const double* room_dims, +int EJOC_CALL ejoc_jochrtf_configure_room( + ejoc_jochrtf_handle handle, const double* room_dims, const double* listener_pos, const double* wall_gains, double speed_of_sound, const uint32_t* fdn_delays, const double* fdn_feedback, double damping, double fdn_output_gain, const uint32_t* allpass_delays, @@ -1430,24 +1430,24 @@ int EJOC_CALL ejoc_sofa_binaural_configure_room( enable_early, enable_late) : -1; } -int EJOC_CALL ejoc_sofa_binaural_set_source( - ejoc_sofa_binaural_handle handle, uint32_t source, const double* position_adm, +int EJOC_CALL ejoc_jochrtf_set_source( + ejoc_jochrtf_handle handle, uint32_t source, const double* position_adm, uint32_t profile, double gain, uint32_t enabled, uint32_t special_lfe, uint32_t fade) { return handle ? static_cast(handle)->set_source( source, position_adm, profile, gain, enabled, special_lfe, fade) : -1; } -int EJOC_CALL ejoc_sofa_binaural_process( - ejoc_sofa_binaural_handle handle, const double* input16_interleaved, +int EJOC_CALL ejoc_jochrtf_process( + ejoc_jochrtf_handle handle, const double* input16_interleaved, uint32_t sample_count, double output_gain, double* output_stereo_interleaved) { return handle ? static_cast(handle)->process( input16_interleaved, sample_count, output_gain, output_stereo_interleaved) : -1; } -int EJOC_CALL ejoc_sofa_binaural_finish( - ejoc_sofa_binaural_handle handle, uint32_t flush_samples, +int EJOC_CALL ejoc_jochrtf_finish( + ejoc_jochrtf_handle handle, uint32_t flush_samples, double* output_stereo_interleaved, uint32_t capacity) { return handle ? static_cast(handle)->finish( flush_samples, output_stereo_interleaved, capacity) : -1; diff --git a/src/binaural/binaural_runtime.cpp b/src/binaural/jochrtf_runtime.cpp similarity index 84% rename from src/binaural/binaural_runtime.cpp rename to src/binaural/jochrtf_runtime.cpp index a25ace0..11eebdc 100644 --- a/src/binaural/binaural_runtime.cpp +++ b/src/binaural/jochrtf_runtime.cpp @@ -1,4 +1,4 @@ -#include "binaural/binaural_runtime.h" +#include "binaural/jochrtf_runtime.h" #include #include @@ -29,14 +29,14 @@ bool profile_from_name(const char* name, Profile* out) { return false; } -SofaBinauralRuntime::~SofaBinauralRuntime() { +JochrtfRuntime::~JochrtfRuntime() { if (handle_ != nullptr) { - ejoc_sofa_binaural_destroy(handle_); + ejoc_jochrtf_destroy(handle_); handle_ = nullptr; } } -Status SofaBinauralRuntime::open(const hrtf::Field& field, const hrtf::Kernels& kernels, +Status JochrtfRuntime::open(const hrtf::Field& field, const hrtf::Kernels& kernels, Profile profile, const RoomConstants& room) { if (handle_ != nullptr) { return Status::fail(JOC_ERR_STATE, stage::kRender, "binaural runtime already open"); @@ -47,36 +47,36 @@ Status SofaBinauralRuntime::open(const hrtf::Field& field, const hrtf::Kernels& return Status::fail(JOC_ERR_HRTF_FORMAT, stage::kRender, "compiled HRTF field has unexpected array sizes"); } - handle_ = ejoc_sofa_binaural_create(); + handle_ = ejoc_jochrtf_create(); if (handle_ == nullptr) { return Status::fail(JOC_ERR_OUT_OF_MEMORY, stage::kRender, - "ejoc_sofa_binaural_create failed"); + "ejoc_jochrtf_create failed"); } profile_ = profile; - if (ejoc_sofa_binaural_configure_kernels( + if (ejoc_jochrtf_configure_kernels( handle_, kernels.qmf_analysis.data(), kernels.hybrid_low.data(), kernels.hybrid_indices.data(), kernels.hybrid_values.data(), kernels.hybrid_count, kernels.qmf_basis.data(), kernels.qmf_taps.data()) != 0) { - const char* message = ejoc_sofa_binaural_last_error(handle_); + const char* message = ejoc_jochrtf_last_error(handle_); return Status::fail(JOC_ERR_HRTF_FORMAT, stage::kRender, std::string("configure_kernels failed: ") + (message != nullptr ? message : "unknown")); } - if (ejoc_sofa_binaural_configure_field(handle_, field.coefficients.data(), + if (ejoc_jochrtf_configure_field(handle_, field.coefficients.data(), field.delay_coefficients.data(), field.delay_bounds.data(), field.band_centers_hz.data(), field.measurement_radius_m) != 0) { - const char* message = ejoc_sofa_binaural_last_error(handle_); + const char* message = ejoc_jochrtf_last_error(handle_); return Status::fail(JOC_ERR_HRTF_FORMAT, stage::kRender, std::string("configure_field failed: ") + (message != nullptr ? message : "unknown")); } - if (ejoc_sofa_binaural_configure_room( + if (ejoc_jochrtf_configure_room( handle_, room.dims, room.listener, room.walls, room.speed_of_sound, room.fdn_delays, room.fdn_feedback, room.damping, room.fdn_output_gain, room.allpass_delays, room.allpass_gains, room.enable_early_reflections, room.enable_late_room) != 0) { - const char* message = ejoc_sofa_binaural_last_error(handle_); + const char* message = ejoc_jochrtf_last_error(handle_); return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender, std::string("configure_room failed: ") + (message != nullptr ? message : "unknown")); @@ -95,7 +95,7 @@ Status SofaBinauralRuntime::open(const hrtf::Field& field, const hrtf::Kernels& return Status::success(); } -Status SofaBinauralRuntime::process_block() { +Status JochrtfRuntime::process_block() { double positions[timeline::kTimelineObjects][3] = {}; const Status queried = timeline_.positions_at(static_cast(processed_samples_), positions); @@ -106,28 +106,28 @@ Status SofaBinauralRuntime::process_block() { // backend default (fade enabled) applies - the per-object path crossfade is // part of the reference behaviour, not an optional extra. constexpr std::uint32_t kFade = 1u; - if (ejoc_sofa_binaural_set_source(handle_, 0u, kLfePosition, + if (ejoc_jochrtf_set_source(handle_, 0u, kLfePosition, static_cast(profile_), 1.0, 1u, 1u, kFade) != 0) { - const char* message = ejoc_sofa_binaural_last_error(handle_); + const char* message = ejoc_jochrtf_last_error(handle_); return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender, std::string("set_source(LFE) failed: ") + (message != nullptr ? message : "unknown")); } for (std::uint32_t source = 0; source < timeline::kTimelineObjects; ++source) { - if (ejoc_sofa_binaural_set_source(handle_, source + 1u, positions[source], + if (ejoc_jochrtf_set_source(handle_, source + 1u, positions[source], static_cast(profile_), 1.0, 1u, 0u, kFade) != 0) { - const char* message = ejoc_sofa_binaural_last_error(handle_); + const char* message = ejoc_jochrtf_last_error(handle_); return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender, std::string("set_source(object ") + std::to_string(source + 1u) + ") failed: " + (message != nullptr ? message : "unknown")); } } - const int trimmed = ejoc_sofa_binaural_process(handle_, staging_.data(), kBlockSamples, 1.0, + const int trimmed = ejoc_jochrtf_process(handle_, staging_.data(), kBlockSamples, 1.0, block_output_.data()); if (trimmed < 0) { - const char* message = ejoc_sofa_binaural_last_error(handle_); + const char* message = ejoc_jochrtf_last_error(handle_); return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender, std::string("sofa process failed: ") + (message != nullptr ? message : "unknown")); @@ -142,7 +142,7 @@ Status SofaBinauralRuntime::process_block() { return Status::success(); } -Status SofaBinauralRuntime::submit_frame(const float* objects16_planar, +Status JochrtfRuntime::submit_frame(const float* objects16_planar, const oamd::OamdUpdate* update, std::int64_t frame_index, std::int64_t outer_sample_offset, std::int64_t object_delay_samples) { @@ -186,7 +186,7 @@ Status SofaBinauralRuntime::submit_frame(const float* objects16_planar, return Status::success(); } -std::uint32_t SofaBinauralRuntime::finish_capacity(double tail_seconds) const { +std::uint32_t JochrtfRuntime::finish_capacity(double tail_seconds) const { std::int64_t requested = tail_samples_; if (tail_seconds >= 0.0) { requested = static_cast(std::ceil(tail_seconds * 48000.0 - 1e-9)); @@ -198,11 +198,11 @@ std::uint32_t SofaBinauralRuntime::finish_capacity(double tail_seconds) const { return static_cast(drain); } -Status SofaBinauralRuntime::reset() { +Status JochrtfRuntime::reset() { if (handle_ == nullptr) { return Status::fail(JOC_ERR_STATE, stage::kRender, "binaural runtime is not open"); } - if (ejoc_sofa_binaural_reset(handle_) != 0) { + if (ejoc_jochrtf_reset(handle_) != 0) { return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender, "sofa reset failed"); } timeline_.reset(); @@ -214,7 +214,7 @@ Status SofaBinauralRuntime::reset() { return Status::success(); } -Status SofaBinauralRuntime::finish(std::uint32_t flush_samples, std::vector* out) { +Status JochrtfRuntime::finish(std::uint32_t flush_samples, std::vector* out) { if (handle_ == nullptr) { return Status::fail(JOC_ERR_STATE, stage::kRender, "binaural runtime is not open"); } @@ -230,9 +230,9 @@ Status SofaBinauralRuntime::finish(std::uint32_t flush_samples, std::vector 0) { const std::uint32_t request = std::min(remaining, kBlockSamples); - const int produced = ejoc_sofa_binaural_finish(handle_, request, chunk.data(), request); + const int produced = ejoc_jochrtf_finish(handle_, request, chunk.data(), request); if (produced < 0) { - const char* message = ejoc_sofa_binaural_last_error(handle_); + const char* message = ejoc_jochrtf_last_error(handle_); return Status::fail(JOC_ERR_RENDER_FAILED, stage::kRender, std::string("sofa finish failed: ") + (message != nullptr ? message : "unknown")); diff --git a/src/binaural/binaural_runtime.h b/src/binaural/jochrtf_runtime.h similarity index 92% rename from src/binaural/binaural_runtime.h rename to src/binaural/jochrtf_runtime.h index db9fc75..1466f87 100644 --- a/src/binaural/binaural_runtime.h +++ b/src/binaural/jochrtf_runtime.h @@ -38,13 +38,13 @@ enum class Profile : std::uint32_t { Near = 0, Mid = 1, Far = 2 }; bool profile_from_name(const char* name, Profile* out); -class SofaBinauralRuntime { +class JochrtfRuntime { public: - SofaBinauralRuntime() = default; - ~SofaBinauralRuntime(); + JochrtfRuntime() = default; + ~JochrtfRuntime(); - SofaBinauralRuntime(const SofaBinauralRuntime&) = delete; - SofaBinauralRuntime& operator=(const SofaBinauralRuntime&) = delete; + JochrtfRuntime(const JochrtfRuntime&) = delete; + JochrtfRuntime& operator=(const JochrtfRuntime&) = delete; Status open(const hrtf::Field& field, const hrtf::Kernels& kernels, Profile profile, const RoomConstants& room = RoomConstants{}); @@ -83,7 +83,7 @@ public: private: Status process_block(); - ejoc_sofa_binaural_handle handle_ = nullptr; + ejoc_jochrtf_handle handle_ = nullptr; Profile profile_ = Profile::Mid; timeline::OamdPositionTimeline timeline_; std::vector staging_; diff --git a/src/binaural/point_source.cpp b/src/binaural/point_source.cpp deleted file mode 100644 index 46461ee..0000000 --- a/src/binaural/point_source.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include "binaural/point_source.h" - -#include -#include - -#include "binaural/reference_distance.h" - -namespace joc::binaural { -namespace { - -Status argument_error(const char* message) { - return Status::fail(JOC_ERR_INVALID_ARGUMENT, joc::stage::kRender, message); -} - -} // namespace - -Status PointSourceReference::configure(const std::string& mode, bool has_reference_distance, - double reference_distance_m) { - Status status = normalize_mode_name(mode.empty() ? std::string("mid") : mode, &mode_); - if (!status.ok()) { - return status; - } - if (has_reference_distance) { - if (!std::isfinite(reference_distance_m) || reference_distance_m <= 0.0) { - return argument_error("source reference distance must be finite and positive"); - } - reference_distance_m_ = reference_distance_m; - return Status::success(); - } - return source_reference_distance(mode_, &reference_distance_m_); -} - -Status PointSourceReference::map_position(const std::array& position, - const std::array* previous_direction, - PointSourcePosition* out) const { - if (out == nullptr) { - return argument_error("point source output is null"); - } - for (const double value : position) { - if (!std::isfinite(value)) { - return argument_error("source position must contain three finite values"); - } - if (std::fabs(value) > 50.1 + 1e-8) { - return argument_error("source position exceeds the finite metadata domain"); - } - } - const double radius = std::sqrt(position[0] * position[0] + position[1] * position[1] + - position[2] * position[2]); - // ADM (+x right, +y front, +z up) to the listener frame (+x front, +y left). - std::array direction = {position[1], -position[0], position[2]}; - if (radius > 1e-12) { - for (double& value : direction) { - value /= radius; - } - } else if (previous_direction == nullptr) { - direction = {1.0, 0.0, 0.0}; - } else { - direction = *previous_direction; - } - out->direction = direction; - out->distance_m = radius * reference_distance_m_; - out->normalized_radius = radius; - return Status::success(); -} - -} // namespace joc::binaural diff --git a/src/binaural/point_source.h b/src/binaural/point_source.h deleted file mode 100644 index e0c4326..0000000 --- a/src/binaural/point_source.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include -#include - -#include "foundation/status.h" - -// Listener-centred point-source coordinates for direct HRTF rendering, ported -// from the reference src/point_source.py: the ADM position selects a direction -// in the listener frame and a distance scaled by the mode's reference distance. -// There is no distance-dependent HRTF adaptation; the measured SOFA response is -// kept as it was measured. -namespace joc::binaural { - -struct PointSourcePosition { - std::array direction = {1.0, 0.0, 0.0}; // listener frame, unit - double distance_m = 0.0; - double normalized_radius = 0.0; -}; - -class PointSourceReference { -public: - // `mode` is near/mid/far (empty selects mid). `has_reference_distance` - // overrides the mode's reference distance, as the reference CLI option does. - Status configure(const std::string& mode, bool has_reference_distance, - double reference_distance_m); - - const std::string& mode() const { return mode_; } - double reference_distance_m() const { return reference_distance_m_; } - - // `previous_direction` resolves a coincident position (nullptr keeps front). - Status map_position(const std::array& position, - const std::array* previous_direction, - PointSourcePosition* out) const; - -private: - std::string mode_ = "mid"; - double reference_distance_m_ = 0.0; -}; - -} // namespace joc::binaural diff --git a/src/binaural/reference_distance.cpp b/src/binaural/reference_distance.cpp deleted file mode 100644 index bd08d5b..0000000 --- a/src/binaural/reference_distance.cpp +++ /dev/null @@ -1,131 +0,0 @@ -#include "binaural/reference_distance.h" - -#include -#include - -namespace joc::binaural { -namespace { - -using ArgumentError = joc::Status; - -Status argument_error(const char* message) { - return Status::fail(JOC_ERR_INVALID_ARGUMENT, joc::stage::kRender, message); -} - -struct ModePreset { - const char* name; - double reference_distance_m; - double late_send; -}; - -constexpr ModePreset kModes[3] = { - {"near", 1.00000465, 0.06}, - {"mid", 2.19327927, 0.16}, - {"far", 6.40177584, 0.28}, -}; - -const ModePreset* find_mode(const std::string& mode) { - for (const ModePreset& preset : kModes) { - if (mode == preset.name) { - return &preset; - } - } - return nullptr; -} - -} // namespace - -Status normalize_mode_name(const std::string& mode, std::string* out) { - if (out == nullptr) { - return argument_error("mode output is null"); - } - std::string lowered; - lowered.reserve(mode.size()); - for (const char value : mode) { - if (value == ' ' || value == '\t') { - continue; - } - lowered.push_back(static_cast(std::tolower(static_cast(value)))); - } - if (find_mode(lowered) == nullptr) { - return argument_error("distance profile must be near, mid, or far"); - } - *out = lowered; - return Status::success(); -} - -Status source_reference_distance(const std::string& mode, double* out) { - std::string normalized; - Status status = normalize_mode_name(mode, &normalized); - if (!status.ok()) { - return status; - } - if (out == nullptr) { - return argument_error("reference distance output is null"); - } - *out = find_mode(normalized)->reference_distance_m; - return Status::success(); -} - -Status map_adm_position(const std::array& position, const std::string& mode, - DistanceState* out) { - if (out == nullptr) { - return argument_error("distance state output is null"); - } - for (const double value : position) { - if (!std::isfinite(value)) { - return argument_error("ADM position must contain three finite Cartesian values"); - } - } - std::string normalized; - Status status = normalize_mode_name(mode, &normalized); - if (!status.ok()) { - return status; - } - const double radius = std::sqrt(position[0] * position[0] + position[1] * position[1] + - position[2] * position[2]); - std::array direction = {0.0, 1.0, 0.0}; - if (radius > 1.0e-15) { - direction[0] = position[0] / radius; - direction[1] = position[1] / radius; - direction[2] = position[2] / radius; - } - const double reference = find_mode(normalized)->reference_distance_m; - out->profile = normalized; - out->normalized_radius = radius; - out->reference_distance_m = reference; - out->physical_distance_m = std::max(kMinimumSourceDistanceM, radius * reference); - out->direction_adm = direction; - return Status::success(); -} - -double direct_level_gain(const DistanceState& state) { - if (state.profile == "near") { - return 1.0; - } - const double distance = state.physical_distance_m; - return 1.0 / std::sqrt(1.0 + kRoomEnergyCouplingPerM2 * distance * distance); -} - -double late_send(const DistanceState& state) { - const ModePreset* preset = find_mode(state.profile); - const double base = preset == nullptr ? 0.16 : preset->late_send; - const double radial = std::sqrt(std::max(state.normalized_radius, 0.0)); - return base * std::min(std::max(radial, 0.25), 1.5); -} - -Status inverse_distance_gain(double measurement_radius_m, double path_distance_m, double* out) { - if (!std::isfinite(measurement_radius_m) || !std::isfinite(path_distance_m)) { - return argument_error("measurement and path distances must be finite"); - } - if (measurement_radius_m <= 0.0 || path_distance_m <= 0.0) { - return argument_error("measurement and path distances must be positive"); - } - if (out == nullptr) { - return argument_error("gain output is null"); - } - *out = measurement_radius_m / path_distance_m; - return Status::success(); -} - -} // namespace joc::binaural diff --git a/src/binaural/reference_distance.h b/src/binaural/reference_distance.h deleted file mode 100644 index e82db0b..0000000 --- a/src/binaural/reference_distance.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include -#include - -#include "foundation/status.h" - -// Project-owned distance policy for the SOFA renderer, ported from the -// reference src/reference_distance.py. These are presentation presets of this -// project, not a claim about an external standard: the reference distances are -// the nominal object-coordinate scales, the direct level is an equal-power dry -// coefficient (never a raw 1/r attenuation of authored programme gain), and the -// late send is a fixed per-mode share scaled by the object radius. -namespace joc::binaural { - -inline constexpr double kMinimumSourceDistanceM = 0.10; -inline constexpr double kRoomEnergyCouplingPerM2 = 0.01318359375; -inline constexpr double kPublicRoomCalibrationGain = 1.4; - -// Reference distance of one mode, in metres. -Status source_reference_distance(const std::string& mode, double* out); -// Validates a mode name ("near", "mid" or "far") and stores its canonical spelling. -Status normalize_mode_name(const std::string& mode, std::string* out); - -struct DistanceState { - std::string profile = "mid"; - double normalized_radius = 0.0; - double reference_distance_m = 0.0; - double physical_distance_m = 0.0; - std::array direction_adm = {0.0, 1.0, 0.0}; -}; - -// Resolves an ADM position on one reference distance profile. -Status map_adm_position(const std::array& position, const std::string& mode, - DistanceState* out); - -// Equal-power dry coefficient: unity for near, 1/sqrt(1+coupling*d^2) otherwise. -double direct_level_gain(const DistanceState& state); -// Per-mode late send, scaled by the square root of the normalized radius. -double late_send(const DistanceState& state); -// measurement radius / path distance, the image-source level of one reflection. -Status inverse_distance_gain(double measurement_radius_m, double path_distance_m, double* out); - -} // namespace joc::binaural diff --git a/src/binaural/room_tables.cpp b/src/binaural/room_tables.cpp deleted file mode 100644 index b647cfc..0000000 --- a/src/binaural/room_tables.cpp +++ /dev/null @@ -1,267 +0,0 @@ -#include "binaural/room_tables.h" - -#include -#include -#include - -namespace joc::binaural { -namespace { - -Status room_error(const char* message) { - return Status::fail(JOC_ERR_HRTF_FORMAT, joc::stage::kRender, message); -} - -bool is_prime(int value) { - if (value < 2) { - return false; - } - if (value % 2 == 0) { - return value == 2; - } - for (int divisor = 3; divisor * divisor <= value; divisor += 2) { - if (value % divisor == 0) { - return false; - } - } - return true; -} - -int next_prime(int value) { - int candidate = std::max(2, value); - while (!is_prime(candidate)) { - ++candidate; - } - return candidate; -} - -// One Schroeder all-pass section; the sign convention follows the reference. -class SchroederAllpass { -public: - void configure(int delay_samples, double gain) { - delay_ = std::max(delay_samples, 1); - gain_ = gain; - buffer_.assign(static_cast(delay_), 0.0); - position_ = 0; - } - - void reset() { - std::fill(buffer_.begin(), buffer_.end(), 0.0); - position_ = 0; - } - - void process(const double* input, double* output, std::size_t count) { - for (std::size_t index = 0; index < count; ++index) { - const double value = input[index]; - const double delayed = buffer_[static_cast(position_)]; - const double result = delayed - gain_ * value; - buffer_[static_cast(position_)] = value + gain_ * result; - position_ = (position_ + 1) % delay_; - output[index] = result; - } - } - -private: - int delay_ = 1; - double gain_ = 0.0; - std::vector buffer_; - int position_ = 0; -}; - -constexpr double kHadamard4[4][4] = { - {0.5, 0.5, 0.5, 0.5}, - {0.5, -0.5, 0.5, -0.5}, - {0.5, 0.5, -0.5, -0.5}, - {0.5, -0.5, -0.5, 0.5}, -}; - -constexpr double kInputVector[4] = {0.5, -0.5, 0.5, 0.5}; -constexpr double kOutputMatrix[2][4] = { - {0.5, 0.5, -0.5, -0.5}, - {0.5, -0.5, 0.5, -0.5}, -}; - -struct Fdn { - std::array, 4> buffers; - std::array positions = {}; - std::array delays = {}; - std::array feedback_gain = {}; - std::array damping_state = {}; - SchroederAllpass diffusers[2]; - double damping = 0.0; - double output_gain = 0.0; - - void reset() { - for (std::vector& buffer : buffers) { - std::fill(buffer.begin(), buffer.end(), 0.0); - } - positions.fill(0); - damping_state.fill(0.0); - for (SchroederAllpass& diffuser : diffusers) { - diffuser.reset(); - } - } - - void process(const double* input, double* left, double* right, std::size_t count) { - std::vector diffused(input, input + count); - std::vector stage(count); - for (SchroederAllpass& diffuser : diffusers) { - diffuser.process(diffused.data(), stage.data(), count); - diffused.swap(stage); - } - for (std::size_t sample = 0; sample < count; ++sample) { - std::array delayed = {}; - for (int line = 0; line < 4; ++line) { - delayed[static_cast(line)] = - buffers[static_cast(line)] - [static_cast(positions[static_cast(line)])]; - } - for (int line = 0; line < 4; ++line) { - const std::size_t index = static_cast(line); - damping_state[index] = - damping * damping_state[index] + (1.0 - damping) * delayed[index]; - } - left[sample] = output_gain * (kOutputMatrix[0][0] * damping_state[0] + - kOutputMatrix[0][1] * damping_state[1] + - kOutputMatrix[0][2] * damping_state[2] + - kOutputMatrix[0][3] * damping_state[3]); - right[sample] = output_gain * (kOutputMatrix[1][0] * damping_state[0] + - kOutputMatrix[1][1] * damping_state[1] + - kOutputMatrix[1][2] * damping_state[2] + - kOutputMatrix[1][3] * damping_state[3]); - std::array feedback = {}; - for (int row = 0; row < 4; ++row) { - double sum = 0.0; - for (int column = 0; column < 4; ++column) { - sum += kHadamard4[row][column] * - (damping_state[static_cast(column)] * - feedback_gain[static_cast(column)]); - } - feedback[static_cast(row)] = sum; - } - for (int line = 0; line < 4; ++line) { - const std::size_t index = static_cast(line); - const double write = - kInputVector[index] * diffused[sample] + feedback[index]; - buffers[index][static_cast(positions[index])] = write; - positions[index] = (positions[index] + 1) % delays[index]; - } - } - } -}; - -double volume_over_area(const std::array& dimensions) { - const double volume = dimensions[0] * dimensions[1] * dimensions[2]; - const double area = 2.0 * (dimensions[0] * dimensions[1] + - dimensions[0] * dimensions[2] + - dimensions[1] * dimensions[2]); - return volume / area; -} - -struct FdnConfig { - double sample_rate_hz = 48000.0; - double rt60_seconds = 0.85; - double damping = 0.32; - double output_gain = 0.22; - std::array delay_seconds = {0.0297, 0.0371, 0.0411, 0.0437}; - std::array allpass_seconds = {0.0023, 0.0067}; - std::array allpass_gain = {0.63, 0.51}; -}; - -} // namespace - -Status render_late_fir(double sample_rate_hz, double rt60_seconds, double damping, - double output_gain, const std::array& delay_seconds, - const std::array& allpass_seconds, - const std::array& allpass_gain, std::size_t impulse_samples, - std::vector* left, std::vector* right) { - if (left == nullptr || right == nullptr || impulse_samples == 0u) { - return room_error("late FDN output is invalid"); - } - if (!(sample_rate_hz > 0.0) || !(rt60_seconds > 0.0) || !std::isfinite(damping) || - damping < 0.0 || damping >= 1.0 || !std::isfinite(output_gain)) { - return room_error("invalid FDN sample rate, RT60, damping or output gain"); - } - Fdn fdn; - fdn.damping = damping; - fdn.output_gain = output_gain; - for (int line = 0; line < 4; ++line) { - const double seconds = delay_seconds[static_cast(line)]; - if (!(seconds > 0.0)) { - return room_error("FDN requires four positive delay times"); - } - const int delay = next_prime( - static_cast(std::lround(seconds * sample_rate_hz))); - fdn.delays[static_cast(line)] = delay; - fdn.feedback_gain[static_cast(line)] = - std::pow(10.0, -3.0 * static_cast(delay) / (rt60_seconds * sample_rate_hz)); - fdn.buffers[static_cast(line)].assign(static_cast(delay), 0.0); - } - for (int stage = 0; stage < 2; ++stage) { - const double seconds = allpass_seconds[static_cast(stage)]; - const double gain = allpass_gain[static_cast(stage)]; - if (!(seconds > 0.0) || !(std::fabs(gain) < 1.0)) { - return room_error("FDN requires two positive all-pass delays and gains"); - } - fdn.diffusers[stage].configure( - next_prime(static_cast(std::lround(seconds * sample_rate_hz))), gain); - } - // The probe is the part beyond the FIR that the reference discards. - const std::size_t probe = - static_cast(std::ceil(rt60_seconds * sample_rate_hz)); - std::vector impulse(impulse_samples + probe, 0.0); - impulse[0] = 1.0; - left->assign(impulse.size(), 0.0); - right->assign(impulse.size(), 0.0); - fdn.process(impulse.data(), left->data(), right->data(), impulse.size()); - left->resize(impulse_samples); - right->resize(impulse_samples); - return Status::success(); -} - -Status build_room_preset(const std::string& preset, RoomPreset* out) { - if (out == nullptr) { - return room_error("room preset output is null"); - } - FdnConfig config; - ShoeboxRoomConfig early; - double scale = 1.0; - if (preset == "compact") { - const std::array dimensions = {8.5, 11.3, 5.2}; - early.dimensions_m = dimensions; - early.listener_position_m = {dimensions[0] * 0.5, dimensions[1] * 0.5, - dimensions[2] * 0.5}; - scale = volume_over_area(dimensions) / - volume_over_area(std::array{18.0, 18.0, 14.0}); - config.rt60_seconds *= scale; - for (double& value : config.delay_seconds) { - value *= scale; - } - for (double& value : config.allpass_seconds) { - value *= scale; - } - } else if (preset != "legacy") { - return room_error("room preset must be compact or legacy"); - } - const Status validated = early.validate(); - if (!validated.ok()) { - return validated; - } - const std::size_t taps = static_cast( - std::ceil(2.0 * config.rt60_seconds * config.sample_rate_hz)); - std::vector left; - std::vector right; - const Status rendered = render_late_fir( - config.sample_rate_hz, config.rt60_seconds, config.damping, config.output_gain, - config.delay_seconds, config.allpass_seconds, config.allpass_gain, taps, &left, &right); - if (!rendered.ok()) { - return rendered; - } - out->early = early; - out->late_fir[0] = std::move(left); - out->late_fir[1] = std::move(right); - out->rt60_seconds = config.rt60_seconds; - out->size_time_scale = scale; - return Status::success(); -} - -} // namespace joc::binaural diff --git a/src/binaural/room_tables.h b/src/binaural/room_tables.h deleted file mode 100644 index 754d097..0000000 --- a/src/binaural/room_tables.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "binaural/shoebox_room.h" -#include "foundation/status.h" - -// The project's own room, generated in code: a shared unitary FDN (four -// orthogonal Hadamard feedback lines, two Schroeder all-pass diffusers and -// low-pass damping) rendered to a two-channel float64 FIR, plus the shoebox -// geometry its first-order images are computed from. Ported from the reference -// src/public_room.py; there is no measured BRIR and no external model behind it. -namespace joc::binaural { - -struct RoomPreset { - ShoeboxRoomConfig early; - std::vector late_fir[2]; // [2][taps] - double rt60_seconds = 0.0; - double size_time_scale = 1.0; -}; - -// "legacy" is the original project room; "compact" keeps the same algorithm with -// the Zahorik-table geometry and the late time constants scaled by V/S. -Status build_room_preset(const std::string& preset, RoomPreset* out); - -// One FDN realization: the response to a unit impulse, cut to 2*RT60. -Status render_late_fir(double sample_rate_hz, double rt60_seconds, double damping, - double output_gain, const std::array& delay_seconds, - const std::array& allpass_seconds, - const std::array& allpass_gain, - std::size_t impulse_samples, std::vector* left, - std::vector* right); - -} // namespace joc::binaural diff --git a/src/binaural/shoebox_room.cpp b/src/binaural/shoebox_room.cpp deleted file mode 100644 index 52b3cac..0000000 --- a/src/binaural/shoebox_room.cpp +++ /dev/null @@ -1,125 +0,0 @@ -#include "binaural/shoebox_room.h" - -#include -#include - -namespace joc::binaural { -namespace { - -Status argument_error(const char* message) { - return Status::fail(JOC_ERR_INVALID_ARGUMENT, joc::stage::kRender, message); -} - -const char* const kWallNames[6] = {"left", "right", "back", "front", "floor", "ceiling"}; - -} // namespace - -Status ShoeboxRoomConfig::validate() const { - for (const double value : dimensions_m) { - if (!std::isfinite(value) || value <= 0.0) { - return argument_error("room dimensions must be three positive finite values"); - } - } - for (int axis = 0; axis < 3; ++axis) { - const double value = listener_position_m[static_cast(axis)]; - if (!std::isfinite(value) || value <= 0.0 || - value >= dimensions_m[static_cast(axis)]) { - return argument_error("listener must be strictly inside the shoebox"); - } - } - for (const double gain : wall_reflection_gain) { - if (!std::isfinite(gain) || std::fabs(gain) >= 1.0) { - return argument_error("six finite wall gains must have magnitude below one"); - } - } - if (!std::isfinite(speed_of_sound_m_s) || speed_of_sound_m_s <= 0.0) { - return argument_error("speed of sound must be positive"); - } - return Status::success(); -} - -Status first_order_image_sources(const std::array& direction_adm, - double source_distance_m, double sample_rate_hz, - const ShoeboxRoomConfig& config, - std::vector* out) { - if (out == nullptr) { - return argument_error("reflection output is null"); - } - const Status validated = config.validate(); - if (!validated.ok()) { - return validated; - } - for (const double value : direction_adm) { - if (!std::isfinite(value)) { - return argument_error( - "reflection direction must contain three finite ADM values"); - } - } - const double norm = std::sqrt(direction_adm[0] * direction_adm[0] + - direction_adm[1] * direction_adm[1] + - direction_adm[2] * direction_adm[2]); - const std::array direction = norm <= 1.0e-15 - ? std::array{0.0, 1.0, 0.0} - : std::array{ - direction_adm[0] / norm, - direction_adm[1] / norm, - direction_adm[2] / norm}; - if (!std::isfinite(source_distance_m) || source_distance_m <= 0.0 || - !std::isfinite(sample_rate_hz) || sample_rate_hz <= 0.0) { - return argument_error("source distance and sample rate must be positive"); - } - std::array source = {}; - for (int axis = 0; axis < 3; ++axis) { - source[static_cast(axis)] = - config.listener_position_m[static_cast(axis)] + - direction[static_cast(axis)] * source_distance_m; - const double value = source[static_cast(axis)]; - if (value <= 0.0 || value >= config.dimensions_m[static_cast(axis)]) { - return argument_error( - "source lies outside the configured public shoebox; enlarge the room"); - } - } - std::array, 6> images = {}; - for (int axis = 0; axis < 3; ++axis) { - std::array low = source; - low[static_cast(axis)] = -source[static_cast(axis)]; - std::array high = source; - high[static_cast(axis)] = - 2.0 * config.dimensions_m[static_cast(axis)] - - source[static_cast(axis)]; - images[static_cast(axis * 2)] = low; - images[static_cast(axis * 2 + 1)] = high; - } - out->clear(); - out->reserve(6); - for (int index = 0; index < 6; ++index) { - const std::array& image = images[static_cast(index)]; - std::array vector = {}; - for (int axis = 0; axis < 3; ++axis) { - vector[static_cast(axis)] = - image[static_cast(axis)] - - config.listener_position_m[static_cast(axis)]; - } - const double path_distance = std::sqrt(vector[0] * vector[0] + vector[1] * vector[1] + - vector[2] * vector[2]); - if (!(path_distance > 0.0)) { - return argument_error("image source coincides with the listener"); - } - EarlyReflection reflection; - reflection.wall = kWallNames[index]; - for (int axis = 0; axis < 3; ++axis) { - reflection.direction_adm[static_cast(axis)] = - vector[static_cast(axis)] / path_distance; - } - reflection.path_distance_m = path_distance; - const double extra_metres = std::max(path_distance - source_distance_m, 0.0); - reflection.extra_delay_samples = extra_metres * sample_rate_hz / config.speed_of_sound_m_s; - const double air = std::exp(-0.002 * extra_metres); - reflection.reflection_gain = - config.wall_reflection_gain[static_cast(index)] * air; - out->push_back(reflection); - } - return Status::success(); -} - -} // namespace joc::binaural diff --git a/src/binaural/shoebox_room.h b/src/binaural/shoebox_room.h deleted file mode 100644 index 0314d7a..0000000 --- a/src/binaural/shoebox_room.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "foundation/status.h" - -// Project-owned shoebox geometry and first-order image sources, ported from the -// reference src/public_room.py. The room is this project's own construction, not -// a measured BRIR and not an external model: one rectangular room, one listener -// position, six wall gains and a speed of sound. -namespace joc::binaural { - -struct ShoeboxRoomConfig { - std::array dimensions_m = {18.0, 18.0, 14.0}; - std::array listener_position_m = {9.0, 9.0, 7.0}; - std::array wall_reflection_gain = {0.62, 0.60, 0.58, 0.61, 0.52, 0.56}; - double speed_of_sound_m_s = 343.3; - - Status validate() const; -}; - -struct EarlyReflection { - std::string wall; - std::array direction_adm = {0.0, 1.0, 0.0}; - double path_distance_m = 0.0; - double extra_delay_samples = 0.0; - double reflection_gain = 0.0; -}; - -// Six first-order image-source paths for one object at `direction_adm` and -// `source_distance_m` metres from the listener. -Status first_order_image_sources(const std::array& direction_adm, - double source_distance_m, double sample_rate_hz, - const ShoeboxRoomConfig& config, - std::vector* out); - -} // namespace joc::binaural diff --git a/src/binaural/sofa_room.cpp b/src/binaural/sofa_room.cpp deleted file mode 100644 index e87a8fa..0000000 --- a/src/binaural/sofa_room.cpp +++ /dev/null @@ -1,292 +0,0 @@ -#include "binaural/sofa_room.h" - -#include -#include - -#include "foundation/fft.h" - -namespace joc::binaural { -namespace { - -constexpr double kPi = 3.141592653589793238462643383279502884; - -Status argument_error(const char* message) { - return Status::fail(JOC_ERR_INVALID_ARGUMENT, joc::stage::kRender, message); -} - -// Inverse real transform of one half spectrum on a power-of-two grid. -void irfft_row(const std::vector>& half, std::size_t fft_size, - std::vector* out, std::size_t out_offset, std::size_t out_stride) { - std::vector> buffer(fft_size, std::complex(0.0, 0.0)); - const std::size_t bins = half.size(); - for (std::size_t bin = 0; bin < bins; ++bin) { - buffer[bin] = half[bin]; - } - for (std::size_t bin = 1; bin + 1 < bins; ++bin) { - buffer[fft_size - bin] = std::conj(half[bin]); - } - dsp::fft_radix2(&buffer, true); - for (std::size_t sample = 0; sample < fft_size; ++sample) { - (*out)[out_offset + (sample % out_stride)] = buffer[sample].real(); - } -} - -// Real block (zero padded to `fft_size`) to its first `fft_size/2+1` bins. -void rfft_row(const std::vector& time, std::size_t fft_size, - std::vector>* out) { - std::vector> buffer(fft_size, std::complex(0.0, 0.0)); - for (std::size_t sample = 0; sample < fft_size && sample < time.size(); ++sample) { - buffer[sample] = std::complex(time[sample], 0.0); - } - dsp::fft_radix2(&buffer, false); - out->assign(buffer.begin(), buffer.begin() + static_cast(fft_size / 2u + 1u)); -} - -} // namespace - -Status SofaRoom::configure(std::size_t source_count, const PointSourceReference& reference, - int implementation_latency, int recording_origin, - const std::string& preset) { - reference_ = reference; - RoomPreset generated; - const Status status = build_room_preset(preset, &generated); - if (!status.ok()) { - return status; - } - preset_ = preset; - config_ = generated.early; - rt60_seconds_ = generated.rt60_seconds; - alignment_samples_ = static_cast(implementation_latency) + - static_cast(std::max(recording_origin, 0)); - const std::size_t taps = generated.late_fir[0].size(); - const std::size_t aligned = static_cast(alignment_samples_) + taps; - std::vector kernel(2u * aligned, 0.0); - for (std::size_t row = 0; row < 2u; ++row) { - std::copy(generated.late_fir[row].begin(), generated.late_fir[row].end(), - kernel.begin() + static_cast( - row * aligned + static_cast(alignment_samples_))); - } - convolver_.configure(2u, aligned, kSofaRoomBatchSamples); - const Status filtered = convolver_.set_filter(kernel.data(), aligned, 0u); - if (!filtered.ok()) { - return filtered; - } - current_.assign(source_count, 0.0); - target_.assign(source_count, 0.0); - pending_mono_.clear(); - pending_direct_.clear(); - pending_blocks_ = 0; - maximum_early_delay_samples_ = 0.0; - valid_ = true; - return Status::success(); -} - -void SofaRoom::distance_state(const PointSourcePosition& state, DistanceState* out) const { - out->profile = reference_.mode(); - out->normalized_radius = state.normalized_radius; - out->reference_distance_m = reference_.reference_distance_m(); - out->physical_distance_m = std::max(kMinimumSourceDistanceM, state.distance_m); - // Listener frame (+x front, +y left) back to ADM (+x right, +y front). - out->direction_adm = {-state.direction[1], state.direction[0], state.direction[2]}; -} - -void SofaRoom::reset() { - if (!valid_) { - return; - } - std::fill(current_.begin(), current_.end(), 0.0); - std::fill(target_.begin(), target_.end(), 0.0); - pending_mono_.clear(); - pending_direct_.clear(); - pending_blocks_ = 0; - maximum_early_delay_samples_ = 0.0; - convolver_.reset(); -} - -Status SofaRoom::set_source(std::size_t source, const PointSourcePosition* state, double gain, - bool first, bool special_lfe) { - if (source >= current_.size()) { - return argument_error("room source index is out of range"); - } - double value = 0.0; - if (!special_lfe && state != nullptr) { - DistanceState distance; - distance_state(*state, &distance); - value = gain * kPublicRoomCalibrationGain * late_send(distance); - } - target_[source] = value; - if (first) { - current_[source] = value; - } - return Status::success(); -} - -Status SofaRoom::radians_paths(const PointSourcePosition& state, - std::vector* paths) { - DistanceState distance; - distance_state(state, &distance); - const Status status = first_order_image_sources(distance.direction_adm, - distance.physical_distance_m, 48000.0, - config_, paths); - if (!status.ok()) { - return status; - } - for (const EarlyReflection& path : *paths) { - maximum_early_delay_samples_ = - std::max(maximum_early_delay_samples_, path.extra_delay_samples); - } - return Status::success(); -} - -double SofaRoom::early_delay_bound_samples() const { - double extent = 0.0; - for (int axis = 0; axis < 3; ++axis) { - const double listener = config_.listener_position_m[static_cast(axis)]; - const double dimension = config_.dimensions_m[static_cast(axis)]; - extent = std::max(extent, std::max(listener, dimension - listener)); - } - return 2.0 * extent * 48000.0 / config_.speed_of_sound_m_s; -} - -std::size_t SofaRoom::filter_budget(const hrtf::FullHrirField& field) const { - const double needed = static_cast(field.fft_size()) + - std::ceil(early_delay_bound_samples()) + 64.0; - std::size_t length = 1; - while (static_cast(length) < needed) { - length <<= 1u; - } - return length; -} - -double SofaRoom::direct_gain(const PointSourcePosition& state) const { - DistanceState distance; - distance_state(state, &distance); - return direct_level_gain(distance); -} - -double SofaRoom::early_gain(const EarlyReflection& reflection, double measurement_radius_m) const { - return kPublicRoomCalibrationGain * reflection.reflection_gain * measurement_radius_m / - reflection.path_distance_m; -} - -Status SofaRoom::full_hrir(hrtf::FullHrirField& field, const PointSourcePosition& state, - std::size_t output_taps, std::vector* hrir) { - if (hrir == nullptr || output_taps < field.fft_size() || output_taps % 2u != 0) { - return argument_error("room HRIR output is invalid"); - } - const std::size_t fft_size = field.fft_size(); - const std::size_t field_bins = field.frequency_bins(); - const std::size_t bins = output_taps / 2u + 1u; - std::vector omega(bins); - for (std::size_t bin = 0; bin < bins; ++bin) { - omega[bin] = 2.0 * kPi * static_cast(bin) / static_cast(output_taps); - } - std::vector> spectrum(2u * bins, std::complex(0.0, 0.0)); - std::vector impulse(fft_size); - std::vector padded(output_taps, 0.0); - std::vector> half(field_bins); - std::vector> bins_out; - - const auto accumulate = [&](const std::array& direction, double extra_delay, - double gain) -> Status { - std::vector> value; - const Status status = field.spectrum(direction.data(), &value); - if (!status.ok()) { - return status; - } - for (int ear = 0; ear < 2; ++ear) { - for (std::size_t bin = 0; bin < field_bins; ++bin) { - half[bin] = value[static_cast(ear) * field_bins + bin]; - } - irfft_row(half, fft_size, &impulse, 0u, fft_size); - std::fill(padded.begin(), padded.end(), 0.0); - for (std::size_t sample = 0; sample < fft_size; ++sample) { - padded[(sample + fft_size / 2u) % fft_size] = impulse[sample]; - } - rfft_row(padded, output_taps, &bins_out); - for (std::size_t bin = 0; bin < bins; ++bin) { - const std::complex rotation = - extra_delay == 0.0 - ? std::complex(1.0, 0.0) - : std::exp(std::complex(0.0, -omega[bin] * extra_delay)); - spectrum[static_cast(ear) * bins + bin] += - bins_out[bin] * rotation * gain; - } - } - return Status::success(); - }; - - Status status = accumulate(state.direction, 0.0, direct_gain(state)); - if (!status.ok()) { - return status; - } - std::vector paths; - status = radians_paths(state, &paths); - if (!status.ok()) { - return status; - } - const double radius = field.measurement_radius_m(); - for (const EarlyReflection& path : paths) { - // ADM (+x right, +y front) back to the listener frame (+x front, +y left). - const std::array direction = {path.direction_adm[1], -path.direction_adm[0], - path.direction_adm[2]}; - status = accumulate(direction, path.extra_delay_samples, early_gain(path, radius)); - if (!status.ok()) { - return status; - } - } - - hrir->assign(2u * output_taps, 0.0); - std::vector> row(bins); - for (int ear = 0; ear < 2; ++ear) { - for (std::size_t bin = 0; bin < bins; ++bin) { - row[bin] = spectrum[static_cast(ear) * bins + bin]; - } - irfft_row(row, output_taps, hrir, static_cast(ear) * output_taps, - output_taps); - } - return Status::success(); -} - -Status SofaRoom::process(const double* block, std::size_t sources, const double* direct, - std::vector* out, bool* produced) { - if (!valid_ || block == nullptr || direct == nullptr || out == nullptr || - produced == nullptr) { - return argument_error("room process arguments are invalid"); - } - *produced = false; - const std::size_t offset = pending_mono_.size(); - pending_mono_.resize(offset + 128u, 0.0); - for (std::size_t sample = 0; sample < 128u; ++sample) { - const double amount = static_cast(sample + 1u) / 128.0; - double mono = 0.0; - for (std::size_t source = 0; source < sources; ++source) { - const double send = - current_[source] + (target_[source] - current_[source]) * amount; - mono += block[sample * sources + source] * send; - } - pending_mono_[offset + sample] = mono; - } - pending_direct_.insert(pending_direct_.end(), direct, direct + 256u); - current_ = target_; - ++pending_blocks_; - if (pending_blocks_ * 128u < kSofaRoomBatchSamples) { - return Status::success(); - } - std::vector late(kSofaRoomBatchSamples * 2u, 0.0); - const Status status = convolver_.process_block(pending_mono_.data(), late.data()); - if (!status.ok()) { - return status; - } - out->assign(pending_direct_.size(), 0.0); - for (std::size_t index = 0; index < pending_direct_.size(); ++index) { - (*out)[index] = pending_direct_[index] + late[index]; - } - pending_mono_.clear(); - pending_direct_.clear(); - pending_blocks_ = 0; - *produced = true; - return Status::success(); -} - -} // namespace joc::binaural diff --git a/src/binaural/sofa_room.h b/src/binaural/sofa_room.h deleted file mode 100644 index 0484b0a..0000000 --- a/src/binaural/sofa_room.h +++ /dev/null @@ -1,77 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "binaural/point_source.h" -#include "binaural/reference_distance.h" -#include "binaural/room_tables.h" -#include "binaural/shoebox_room.h" -#include "foundation/status.h" -#include "hrtf/full_hrir_field.h" -#include "hrtf/partitioned_convolution.h" - -// Optional coupling of the SOFA direct path to this project's own room: six -// first-order image sources rendered through the same HRIR field, plus the late -// FDN tail. Ported from the reference src/sofa_room.py; the room is generated by -// this project's own model (see room_tables.h), not a measured BRIR. -namespace joc::binaural { - -inline constexpr std::size_t kSofaRoomBatchSamples = 1536; - -class SofaRoom { -public: - Status configure(std::size_t source_count, const PointSourceReference& reference, - int implementation_latency, int recording_origin, - const std::string& preset); - - bool active() const { return valid_; } - const std::string& preset() const { return preset_; } - double rt60_seconds() const { return rt60_seconds_; } - - // Sends for one source; `state` is null for the LFE channel. - Status set_source(std::size_t source, const PointSourcePosition* state, double gain, - bool first, bool special_lfe); - - Status radians_paths(const PointSourcePosition& state, - std::vector* paths); - double direct_gain(const PointSourcePosition& state) const; - double early_gain(const EarlyReflection& reflection, double measurement_radius_m) const; - const ShoeboxRoomConfig& early_config() const { return config_; } - double early_delay_bound_samples() const; - double maximum_early_delay_samples() const { return maximum_early_delay_samples_; } - - // HRIR of the direct sound plus the six first-order reflections. - Status full_hrir(hrtf::FullHrirField& field, const PointSourcePosition& state, - std::size_t output_taps, std::vector* hrir); - std::size_t filter_budget(const hrtf::FullHrirField& field) const; - - // One 128-sample block: returns false while the 1536-sample batch is filling. - Status process(const double* block, std::size_t sources, const double* direct, - std::vector* out, bool* produced); - - std::size_t pending_samples() const { return pending_blocks_ * 128u; } - // Clears the send state and the pending batch but keeps the loaded room. - void reset(); - -private: - void distance_state(const PointSourcePosition& state, DistanceState* out) const; - - bool valid_ = false; - std::string preset_; - PointSourceReference reference_; - ShoeboxRoomConfig config_; - double rt60_seconds_ = 0.0; - double alignment_samples_ = 0.0; - hrtf::UniformPartitionedConvolver convolver_; - std::vector current_; - std::vector target_; - std::vector pending_mono_; - std::vector pending_direct_; - std::size_t pending_blocks_ = 0; - double maximum_early_delay_samples_ = 0.0; -}; - -} // namespace joc::binaural diff --git a/src/cli/joc_cli.cpp b/src/cli/joc_cli.cpp index 0fc9cee..9a509c9 100644 --- a/src/cli/joc_cli.cpp +++ b/src/cli/joc_cli.cpp @@ -4,7 +4,7 @@ // choices and defaults, and the same default output naming under output/. // // Options that exist only because this build has no Python side or no Rosella -// import chain (--backend python, --sofa-hrtf, --personalized-headphone, +// import chain (--backend python, --personalized-headphone, // metadata sidecars) fail with an explicit message instead of being ignored. #include #include @@ -40,19 +40,12 @@ struct Options { std::string clip_action = "ask"; int speaker_metadata_offset = 1473; std::string binaural_mode = "mid"; - std::string sofa_hrtf; std::string compiled_hrtf_cache; + std::string jochrtf_room = "on"; std::string personalized_headphone; bool personalized_headphone_used = false; int rosella_filterbank = 1; bool rosella_filterbank_set = false; - std::string hrtf_cache_policy; - std::string hrtf_cache_dir; - double hrtf_radius_m = 0.0; // 0 selects the single measurement shell - std::string sofa_interpolation; - double source_reference_distance_m = 0.0; - bool sofa_room = false; - std::string sofa_room_preset; double binaural_tail_seconds = 5.0; double binaural_tail_threshold = 1.0e-8; int binaural_chunk_frames = 64; @@ -121,18 +114,12 @@ void print_usage() { " --speaker-metadata-offset N 扬声器渲染 metadata 相对帧偏移,默认 1473 samples\n" " --binaural-mode M 双耳渲染模式 off|near|mid|far,默认 mid;\n" " off 仅用于 ADM BWF(关闭 DBMD 双耳提示)\n" - " --sofa-hrtf PATH SOFA SimpleFreeFieldHRIR 输入;.jochrtf 由本工具内部编译\n" " --personalized-headphone [PATH] Rosella 个性化模型,默认 " "HRTF/binaural.personalized_headphone\n" " --rosella-filterbank N Rosella 模型滤波器组:1=13 taps/6 slots(默认),\n" " 2=11 taps/3 slots;仅作用于个性化模型\n" - " --compiled-hrtf-cache PATH 直接读取 .jochrtf(高级用法,跳过 SOFA 编译)\n" - " --source-reference-distance-m R 覆盖档位的点声源参考距离(米)\n" - " --sofa-room 可选:为 SOFA 启用项目自有房间,默认关闭\n" - " --sofa-room-preset P 房间预设 compact|legacy;默认 near/mid 用 compact、far 用 legacy\n" - " --hrtf-cache-policy P SOFA 编译缓存策略 none|memory|disk,默认 memory\n" - " --hrtf-cache-dir DIR disk cache 目录,默认 /output/hrtf-cache\n" - " --hrtf-radius-m R 选择最近的 SOFA measurement-radius shell,默认 1.0 m\n" + " --compiled-hrtf-cache PATH 读取离线编译好的 .jochrtf\n" + " --jochrtf-room on|off .jochrtf 的项目房间,默认 on;off 只输出直达声\n" " --binaural-tail-seconds S 双耳 room/filterbank flush 上限,默认 5 秒\n" " --binaural-tail-threshold T 双耳尾声裁切阈值,默认 1e-8;主体至少保留原时长\n" " --binaural-chunk-frames N 双耳内部批处理帧数,默认 64(本构建按 512 块渲染,\n" @@ -238,8 +225,8 @@ void parse_args(const std::vector& arguments, Options* options) { to_int(require_value(arguments, &index), "--speaker-metadata-offset")); } else if (arg == "--binaural-mode") { options->binaural_mode = require_value(arguments, &index); } - else if (arg == "--sofa-hrtf") { options->sofa_hrtf = require_value(arguments, &index); } else if (arg == "--compiled-hrtf-cache") { options->compiled_hrtf_cache = require_value(arguments, &index); } + else if (arg == "--jochrtf-room") { options->jochrtf_room = require_value(arguments, &index); } else if (arg == "--personalized-headphone") { options->personalized_headphone_used = true; // nargs="?": the path is optional, so the next token may be the input. @@ -254,13 +241,6 @@ void parse_args(const std::vector& arguments, Options* options) { to_int(require_value(arguments, &index), "--rosella-filterbank")); options->rosella_filterbank_set = true; } - else if (arg == "--hrtf-cache-policy") { options->hrtf_cache_policy = require_value(arguments, &index); } - else if (arg == "--hrtf-cache-dir") { options->hrtf_cache_dir = require_value(arguments, &index); } - else if (arg == "--hrtf-radius-m") { options->hrtf_radius_m = to_double(require_value(arguments, &index), "--hrtf-radius-m"); } - else if (arg == "--source-reference-distance-m") { options->source_reference_distance_m = to_double(require_value(arguments, &index), "--source-reference-distance-m"); } - else if (arg == "--sofa-room") { options->sofa_room = true; } - else if (arg == "--sofa-room-preset") { options->sofa_room_preset = require_value(arguments, &index); } - else if (arg == "--sofa-interpolation") { options->sofa_interpolation = require_value(arguments, &index); } else if (arg == "--binaural-tail-seconds") { options->binaural_tail_seconds = to_double(require_value(arguments, &index), "--binaural-tail-seconds"); } else if (arg == "--binaural-tail-threshold") { options->binaural_tail_threshold = to_double(require_value(arguments, &index), "--binaural-tail-threshold"); } else if (arg == "--binaural-chunk-frames") { options->binaural_chunk_frames = static_cast(to_int(require_value(arguments, &index), "--binaural-chunk-frames")); } @@ -356,18 +336,12 @@ std::string find_kernels(const Options& options, const std::string& argv0) { return options.kernels; } -// Mirrors the reference binaural HRTF resolution (main.py:89-160): the SOFA file -// is the user-facing input and the .jochrtf is only its compiled cache. Paths -// are anchored at the executable directory, as the reference anchors them at the -// project directory. +// The binaural input is either an explicitly compiled .jochrtf field or a Rosella +// .personalized_headphone model. Paths are anchored at the executable directory, +// as the reference anchors them at the project directory. struct HrtfInput { - std::string sofa_path; // compile this - std::string compiled_path; // or read this .jochrtf directly - std::string cache_dir; // disk policy directory + std::string compiled_path; // read this .jochrtf std::string personalized_path; // Rosella .personalized_headphone - std::string interpolation; // SOFA local interpolation - bool disk = false; - bool compile = false; }; std::string resolve_compiled_hrtf(const Options& options, const std::string& project_directory) { @@ -375,9 +349,7 @@ std::string resolve_compiled_hrtf(const Options& options, const std::string& pro return options.compiled_hrtf_cache; } const std::string directory_utf8 = - options.hrtf_cache_dir.empty() - ? fs_utf8::from_path(fs_utf8::to_path(project_directory) / "output" / "hrtf-cache") - : options.hrtf_cache_dir; + fs_utf8::from_path(fs_utf8::to_path(project_directory) / "output" / "hrtf-cache"); if (!fs_utf8::is_directory(directory_utf8)) { return std::string(); } @@ -391,34 +363,18 @@ std::string resolve_compiled_hrtf(const Options& options, const std::string& pro std::sort(candidates.begin(), candidates.end()); if (candidates.size() > 1u) { fail(directory_utf8 + - " 下有多个 .jochrtf 缓存,无法自动选择;请用 --sofa-hrtf PATH 或 " - "--compiled-hrtf-cache PATH 显式指定"); + " 下有多个 .jochrtf 缓存,无法自动选择;请用 --compiled-hrtf-cache PATH 显式指定"); } return candidates.empty() ? std::string() : fs_utf8::from_path(candidates.front()); } HrtfInput resolve_hrtf_input(const Options& options, const std::string& project_directory) { HrtfInput input; - const std::string default_sofa = - fs_utf8::from_path(fs_utf8::to_path(project_directory) / "HRTF" / "binaural.sofa"); const std::string default_private = fs_utf8::from_path( fs_utf8::to_path(project_directory) / "HRTF" / "binaural.personalized_headphone"); const std::string default_cache_dir = fs_utf8::from_path(fs_utf8::to_path(project_directory) / "output" / "hrtf-cache"); - if (!options.compiled_hrtf_cache.empty() && !options.hrtf_cache_policy.empty()) { - fail("显式 .jochrtf 输入不能再指定 --hrtf-cache-policy"); - } - if (!options.compiled_hrtf_cache.empty() && options.hrtf_radius_m > 0.0) { - fail("显式 .jochrtf 输入不能再选择 SOFA radius shell"); - } - if (options.personalized_headphone_used && - (!options.hrtf_cache_policy.empty() || !options.hrtf_cache_dir.empty() || - options.hrtf_radius_m > 0.0)) { - fail("Rosella 模型输入不能使用 --hrtf-cache-policy/--hrtf-cache-dir/--hrtf-radius-m"); - } - - std::string sofa = options.sofa_hrtf; std::string compiled = options.compiled_hrtf_cache; std::string personalized = options.personalized_headphone_used ? options.personalized_headphone : std::string(); @@ -426,16 +382,11 @@ HrtfInput resolve_hrtf_input(const Options& options, const std::string& project_ // "--personalized-headphone" without a path means the project default. personalized = default_private; } - if (sofa.empty() && compiled.empty() && personalized.empty()) { - // The reference order: the SOFA file, then the unique compiled cache, then the - // personalized model. - if (fs_utf8::exists(default_sofa)) { - sofa = default_sofa; - } else { - compiled = resolve_compiled_hrtf(options, project_directory); - if (compiled.empty() && fs_utf8::exists(default_private)) { - personalized = default_private; - } + if (compiled.empty() && personalized.empty()) { + // The compiled cache, then the personalized model. + compiled = resolve_compiled_hrtf(options, project_directory); + if (compiled.empty() && fs_utf8::exists(default_private)) { + personalized = default_private; } } if (!personalized.empty()) { @@ -445,37 +396,12 @@ HrtfInput resolve_hrtf_input(const Options& options, const std::string& project_ input.personalized_path = personalized; return input; } - if (sofa.empty() && compiled.empty()) { - if (!options.hrtf_cache_policy.empty() || !options.hrtf_cache_dir.empty() || - options.hrtf_radius_m > 0.0) { - fail("HRTF cache/radius 选项需要 --sofa-hrtf"); - } - fail("--binaural 未找到 HRTF 输入:默认 " + default_sofa + "、" + default_private + - " 或 " + default_cache_dir + - " 下的 .jochrtf 都不存在,请用 --sofa-hrtf PATH、--personalized-headphone PATH " - "或 --compiled-hrtf-cache PATH 指定"); - } - if (sofa.empty() && (!options.hrtf_cache_policy.empty() || !options.hrtf_cache_dir.empty() || - options.hrtf_radius_m > 0.0)) { - fail("HRTF cache/radius 选项需要 --sofa-hrtf"); - } - if (sofa.empty()) { - input.compiled_path = compiled; - return input; - } - const std::string effective_policy = - options.hrtf_cache_policy.empty() ? "memory" : options.hrtf_cache_policy; - input.compile = !options.hrtf_cache_policy.empty() || !options.hrtf_cache_dir.empty(); - if (!options.hrtf_cache_dir.empty() && effective_policy != "disk") { - fail("--hrtf-cache-dir 需要 SOFA 与 disk cache policy 一起使用"); - } - input.sofa_path = sofa; - input.disk = effective_policy == "disk"; - input.interpolation = options.sofa_interpolation; - input.cache_dir = options.hrtf_cache_dir.empty() ? default_cache_dir : options.hrtf_cache_dir; - if (!fs_utf8::exists(input.sofa_path)) { - fail("SOFA HRTF 不存在: " + input.sofa_path); + if (compiled.empty()) { + fail("--binaural 未找到 HRTF 输入:默认 " + default_private + " 与 " + default_cache_dir + + " 下的 .jochrtf 都不存在,请用 --personalized-headphone PATH 或 " + "--compiled-hrtf-cache PATH 指定"); } + input.compiled_path = compiled; return input; } @@ -579,21 +505,9 @@ int main(int argc, char** argv) { {"ask", "continue", "float32", "abort"}); check_choice(options.binaural_mode, "--binaural-mode", {"off", "near", "mid", "far"}); check_choice(options.trajectory_mode, "--trajectory-mode", {"compact", "dense64"}); - if (!options.sofa_interpolation.empty()) { - check_choice(options.sofa_interpolation, "--sofa-interpolation", - {"lf_logmag_phase", "lf_mca_zero"}); - } - if (!options.sofa_room_preset.empty()) { - check_choice(options.sofa_room_preset, "--sofa-room-preset", - {"compact", "legacy"}); - } check_choice(options.backend, "--backend", {"auto", "native", "python"}); check_choice(options.print_metadata, "--print-metadata", {"none", "summary", "frames"}); check_choice(options.metadata_backend, "--metadata-backend", {"auto", "emdf", "sidecar"}); - if (!options.hrtf_cache_policy.empty()) { - check_choice(options.hrtf_cache_policy, "--hrtf-cache-policy", - {"none", "memory", "disk"}); - } if (options.rosella_filterbank != 1 && options.rosella_filterbank != 2) { fail("--rosella-filterbank: invalid choice: " + std::to_string(options.rosella_filterbank) + " (choose from 1, 2)"); @@ -625,10 +539,10 @@ int main(int argc, char** argv) { if (options.speaker_metadata_offset < 0) { fail("speaker-metadata-offset 不能为负数"); } + check_choice(options.jochrtf_room, "--jochrtf-room", {"on", "off"}); const bool hrtf_options_used = - !options.sofa_hrtf.empty() || !options.compiled_hrtf_cache.empty() || - options.personalized_headphone_used || !options.hrtf_cache_policy.empty() || - !options.hrtf_cache_dir.empty() || options.hrtf_radius_m > 0.0; + !options.compiled_hrtf_cache.empty() || options.personalized_headphone_used || + options.jochrtf_room != "on"; if (hrtf_options_used && !binaural_mode) { fail("SOFA/HRTF 选项仅与 --binaural 一起使用"); } @@ -646,9 +560,6 @@ int main(int argc, char** argv) { if (options.binaural_chunk_frames <= 0) { fail("binaural-chunk-frames 必须大于 0"); } - if (!std::isfinite(options.hrtf_radius_m) || options.hrtf_radius_m < 0.0) { - fail("hrtf-radius-m 必须是正有限值"); - } if (options.duration_set && options.duration <= 0.0) { fail("duration 必须大于 0"); } @@ -737,26 +648,18 @@ int main(int argc, char** argv) { if (options.quiet) { config.flags |= JOC_TASK_F_QUIET; } std::string hrtf_path; - std::string hrtf_sofa_path; - std::string hrtf_cache_dir; std::string personalized_path; std::string kernels_path; - std::string hrtf_interpolation; - bool hrtf_compile = false; if (binaural_mode) { try { const HrtfInput input = resolve_hrtf_input(options, project_directory); hrtf_path = input.compiled_path; - hrtf_sofa_path = input.sofa_path; - hrtf_cache_dir = input.cache_dir; - hrtf_interpolation = input.interpolation; - hrtf_compile = input.compile; personalized_path = input.personalized_path; kernels_path = find_kernels(options, arguments.empty() ? std::string() : arguments.front()); if (options.rosella_filterbank_set && personalized_path.empty()) { fail("--rosella-filterbank 只作用于 Rosella .personalized_headphone 输入;" - "当前 SOFA/.jochrtf 路径不使用该滤波器组"); + "当前 .jochrtf 路径不使用该滤波器组"); } } catch (const std::exception& error) { std::fprintf(stderr, "joc_cli: error: %s\n", error.what()); @@ -764,22 +667,9 @@ int main(int argc, char** argv) { } } config.hrtf_path = hrtf_path.empty() ? nullptr : hrtf_path.c_str(); - config.hrtf_sofa_path = hrtf_sofa_path.empty() ? nullptr : hrtf_sofa_path.c_str(); - config.hrtf_cache_dir = hrtf_cache_dir.empty() ? nullptr : hrtf_cache_dir.c_str(); config.personalized_headphone_path = personalized_path.empty() ? nullptr : personalized_path.c_str(); - config.hrtf_cache_policy = options.hrtf_cache_policy == "disk" ? JOC_HRTF_CACHE_DISK - : options.hrtf_cache_policy == "none" ? JOC_HRTF_CACHE_NONE - : JOC_HRTF_CACHE_MEMORY; - config.hrtf_radius_m = options.hrtf_radius_m; - config.source_reference_distance_m = options.source_reference_distance_m; - config.sofa_room = options.sofa_room ? 1u : 0u; - config.sofa_room_preset = - options.sofa_room_preset.empty() ? nullptr : options.sofa_room_preset.c_str(); - config.sofa_interpolation = hrtf_interpolation == "lf_mca_zero" - ? JOC_SOFA_INTERPOLATION_MCA_ZERO - : JOC_SOFA_INTERPOLATION_LOGMAG_PHASE; - config.hrtf_compile = hrtf_compile ? 1u : 0u; + config.jochrtf_room = options.jochrtf_room == "off" ? 0u : 1u; config.kernels_path = kernels_path.empty() ? nullptr : kernels_path.c_str(); joc_validation_issue issues[32]; diff --git a/src/hrtf/full_hrir_field.cpp b/src/hrtf/full_hrir_field.cpp deleted file mode 100644 index c9162ca..0000000 --- a/src/hrtf/full_hrir_field.cpp +++ /dev/null @@ -1,601 +0,0 @@ - -#include "hrtf/full_hrir_field.h" - -#include -#include -#include -#include -#include - -#include "foundation/fft.h" -#include "hrtf/sofa_field.h" - -namespace joc::hrtf { -namespace { - -constexpr double kPi = 3.141592653589793238462643383279502884; -constexpr double kSoundSpeed = 343.3; -constexpr double kScanTolerance = 1.0e-10; -constexpr int kMcaBands = 41; - -Status field_error(const char* message) { - return Status::fail(JOC_ERR_HRTF_FORMAT, joc::stage::kRender, message); -} - -Status argument_error(const char* message) { - return Status::fail(JOC_ERR_INVALID_ARGUMENT, joc::stage::kRender, message); -} - -// Unnormalised forward transform of a real block, first n/2+1 bins (numpy rfft). -void real_fft(const double* time, std::size_t count, std::vector>* out) { - std::vector> buffer(count); - for (std::size_t index = 0; index < count; ++index) { - buffer[index] = std::complex(time[index], 0.0); - } - dsp::fft_radix2(&buffer, false); - out->assign(buffer.begin(), buffer.begin() + static_cast(count / 2 + 1)); -} - -// In-place phase unwrapping (numpy.unwrap with the default 2*pi period). -void unwrap_phase(const std::vector& wrapped, std::vector* out) { - out->assign(wrapped.size(), 0.0); - if (wrapped.empty()) { - return; - } - (*out)[0] = wrapped[0]; - for (std::size_t index = 1; index < wrapped.size(); ++index) { - double delta = wrapped[index] - wrapped[index - 1]; - delta -= 2.0 * kPi * std::round(delta / (2.0 * kPi)); - (*out)[index] = (*out)[index - 1] + delta; - } -} - -double median(std::vector values) { - if (values.empty()) { - return 0.0; - } - const std::size_t middle = values.size() / 2; - std::nth_element(values.begin(), values.begin() + static_cast(middle), - values.end()); - if (values.size() % 2 != 0) { - return values[middle]; - } - const double upper = values[middle]; - std::nth_element(values.begin(), values.begin() + static_cast(middle - 1), - values.end()); - return 0.5 * (values[middle - 1] + upper); -} - -// scipy.signal._cubic edge/interior slopes of PchipInterpolator. -double pchip_edge(double h0, double h1, double m0, double m1) { - double derivative = ((2.0 * h0 + h1) * m0 - h0 * m1) / (h0 + h1); - const bool opposite = std::signbit(derivative) != std::signbit(m0); - const bool clamp = (std::signbit(m0) != std::signbit(m1)) && - (std::fabs(derivative) > 3.0 * std::fabs(m0)); - if (opposite) { - derivative = 0.0; - } else if (clamp) { - derivative = 3.0 * m0; - } - return derivative; -} - -class PchipEvaluator { -public: - void build(const std::vector& x, const std::vector& y) { - x_ = x; - y_ = y; - const std::size_t count = x.size(); - d_.assign(count, 0.0); - std::vector h(count - 1); - std::vector delta(count - 1); - for (std::size_t index = 0; index + 1 < count; ++index) { - h[index] = x[index + 1] - x[index]; - delta[index] = h[index] != 0.0 ? (y[index + 1] - y[index]) / h[index] : 0.0; - } - if (count == 2) { - d_[0] = delta[0]; - d_[1] = delta[0]; - return; - } - d_[0] = pchip_edge(h[0], h[1], delta[0], delta[1]); - d_[count - 1] = pchip_edge(h[count - 2], h[count - 3], delta[count - 2], delta[count - 3]); - for (std::size_t index = 1; index + 1 < count; ++index) { - if (delta[index - 1] * delta[index] <= 0.0) { - d_[index] = 0.0; - continue; - } - const double w1 = 2.0 * h[index] + h[index - 1]; - const double w2 = h[index] + 2.0 * h[index - 1]; - d_[index] = (w1 + w2) / (w1 / delta[index - 1] + w2 / delta[index]); - } - } - - double evaluate(double value) const { - const std::size_t count = x_.size(); - if (count < 2) { - return count == 1 ? y_[0] : 0.0; - } - std::size_t index = 0; - if (value >= x_.back()) { - index = count - 2; - } else if (value > x_.front()) { - index = static_cast( - std::upper_bound(x_.begin(), x_.end(), value) - x_.begin()) - 1; - } - const double h = x_[index + 1] - x_[index]; - if (h == 0.0) { - return y_[index]; - } - const double t = (value - x_[index]) / h; - const double t2 = t * t; - const double t3 = t2 * t; - return (2.0 * t3 - 3.0 * t2 + 1.0) * y_[index] + - (t3 - 2.0 * t2 + t) * h * d_[index] + - (-2.0 * t3 + 3.0 * t2) * y_[index + 1] + - (t3 - t2) * h * d_[index + 1]; - } - -private: - std::vector x_; - std::vector y_; - std::vector d_; -}; - -} // namespace - -Status FullHrirField::build(const CanonicalHrtf& canonical, const FullHrirOptions& options) { - method_ = options.method; - if (std::fabs(canonical.sample_rate_hz - 48000.0) > 1e-9) { - return field_error("full HRIR renderer requires 48000 Hz"); - } - if (canonical.measurements == 0 || canonical.taps == 0) { - return field_error("canonical HRIR set is empty"); - } - if (canonical.hrir.size() < static_cast(canonical.measurements) * 2u * - canonical.taps || - canonical.delay_samples.size() < static_cast(canonical.measurements) * 2u) { - return field_error("canonical HRIR set is truncated"); - } - - // Shell selection: an explicit radius wins, otherwise a single shell is required. - std::vector shells(canonical.measurement_radius_m.begin(), - canonical.measurement_radius_m.end()); - std::sort(shells.begin(), shells.end()); - shells.erase(std::unique(shells.begin(), shells.end(), - [](double a, double b) { return std::fabs(a - b) < 1e-9; }), - shells.end()); - if (!options.has_shell_radius && shells.size() != 1) { - return field_error("multi-radius SOFA requires an explicit shell radius"); - } - if (options.has_shell_radius && (!std::isfinite(options.shell_radius_m) || - options.shell_radius_m <= 0.0)) { - return field_error("shell radius must be finite and positive"); - } - const double requested = options.has_shell_radius ? options.shell_radius_m : shells[0]; - double actual_radius = 0.0; - const std::vector selected = - canonical_shell_indices(canonical, requested, &actual_radius); - - // Every selected ear must carry energy; delays size the FFT budget. - double maximum_delay = 0.0; - for (const std::size_t row : selected) { - for (int ear = 0; ear < 2; ++ear) { - double energy = 0.0; - const double* taps = canonical.hrir.data() + - (row * 2u + static_cast(ear)) * canonical.taps; - for (std::uint32_t tap = 0; tap < canonical.taps; ++tap) { - energy += taps[tap] * taps[tap]; - } - if (!(energy > 0.0)) { - return field_error("each selected HRIR ear must contain signal energy"); - } - maximum_delay = std::max(maximum_delay, - canonical.delay_samples[row * 2u + - static_cast(ear)]); - } - } - taps_ = canonical.taps; - std::vector radii; - radii.reserve(selected.size()); - for (const std::size_t row : selected) { - radii.push_back(canonical.measurement_radius_m[row]); - } - measurement_radius_m_ = median(radii); - const double support = static_cast(canonical.taps) + - std::ceil(maximum_delay) + 1.0; - std::size_t fft_size = options.fft_size; - if (fft_size == 0) { - fft_size = 2048; - while (fft_size < static_cast(2.0 * support - 1.0)) { - fft_size <<= 1u; - } - if (fft_size > 16384) { - return field_error("HRIR and Data.Delay exceed the automatic FFT budget"); - } - } - if (fft_size < 64 || fft_size % 2 != 0 || - static_cast(canonical.taps) + maximum_delay >= - static_cast(fft_size / 2)) { - return field_error("HRIR and Data.Delay exceed the selected FFT time budget"); - } - fft_size_ = fft_size; - bins_ = fft_size / 2 + 1; - - // Frequencies and phase-fit grid. - frequencies_.resize(bins_); - omega_.resize(bins_); - for (std::size_t bin = 0; bin < bins_; ++bin) { - frequencies_[bin] = static_cast(bin) * 48000.0 / static_cast(fft_size_); - omega_[bin] = 2.0 * kPi * frequencies_[bin] / 48000.0; - } - std::size_t fit_begin = 0; - std::size_t fit_end = 0; - double omega_mean = 0.0; - for (std::size_t bin = 0; bin < bins_; ++bin) { - if (frequencies_[bin] >= 200.0 && frequencies_[bin] <= 1500.0) { - if (fit_end == fit_begin) { - fit_begin = bin; - } - fit_end = bin + 1; - } - } - if (fit_end <= fit_begin) { - return field_error("the phase-fit band is empty"); - } - for (std::size_t bin = fit_begin; bin < fit_end; ++bin) { - omega_mean += omega_[bin]; - } - omega_mean /= static_cast(fit_end - fit_begin); - double x_squares = 0.0; - std::vector x_fit(fit_end - fit_begin); - for (std::size_t bin = fit_begin; bin < fit_end; ++bin) { - x_fit[bin - fit_begin] = omega_[bin] - omega_mean; - x_squares += x_fit[bin - fit_begin] * x_fit[bin - fit_begin]; - } - - // Raw spectra, then delay estimation and alignment. - const std::size_t rows = selected.size(); - std::vector> raw(rows * 2 * bins_); - for (std::size_t row = 0; row < rows; ++row) { - for (int ear = 0; ear < 2; ++ear) { - const double* taps = canonical.hrir.data() + - (selected[row] * 2u + static_cast(ear)) * - canonical.taps; - std::vector padded(fft_size_, 0.0); - std::memcpy(padded.data(), taps, sizeof(double) * canonical.taps); - std::vector> spectrum; - real_fft(padded.data(), fft_size_, &spectrum); - std::copy(spectrum.begin(), spectrum.end(), - raw.begin() + static_cast((row * 2u + - static_cast(ear)) * - bins_)); - } - } - delays_.assign(rows * 2, 0.0); - std::vector residuals; - std::vector wrapped(bins_); - std::vector unwrapped; - for (std::size_t row = 0; row < rows; ++row) { - for (int ear = 0; ear < 2; ++ear) { - const std::complex* spectrum = - raw.data() + (row * 2u + static_cast(ear)) * bins_; - for (std::size_t bin = 0; bin < bins_; ++bin) { - wrapped[bin] = std::arg(spectrum[bin]); - } - unwrap_phase(wrapped, &unwrapped); - double numerator = 0.0; - for (std::size_t bin = fit_begin; bin < fit_end; ++bin) { - numerator += x_fit[bin - fit_begin] * unwrapped[bin]; - } - const double data_delay = - canonical.delay_samples[selected[row] * 2u + static_cast(ear)]; - delays_[row * 2u + static_cast(ear)] = - -numerator / x_squares + data_delay; - } - } - // Residual phase spread of the estimate (reported, not used downstream). - for (std::size_t row = 0; row < rows; ++row) { - for (int ear = 0; ear < 2; ++ear) { - const std::complex* spectrum = - raw.data() + (row * 2u + static_cast(ear)) * bins_; - for (std::size_t bin = 0; bin < bins_; ++bin) { - wrapped[bin] = std::arg(spectrum[bin]); - } - unwrap_phase(wrapped, &unwrapped); - const double data_delay = - canonical.delay_samples[selected[row] * 2u + static_cast(ear)]; - const double delay = delays_[row * 2u + static_cast(ear)]; - double mean = 0.0; - std::vector residual(fit_end - fit_begin); - for (std::size_t bin = fit_begin; bin < fit_end; ++bin) { - residual[bin - fit_begin] = unwrapped[bin] + (delay - data_delay) * omega_[bin]; - mean += residual[bin - fit_begin]; - } - mean /= static_cast(residual.size()); - double squares = 0.0; - for (double& value : residual) { - value -= mean; - squares += value * value; - } - residuals.push_back(std::sqrt(squares / static_cast(residual.size()))); - } - } - std::sort(residuals.begin(), residuals.end()); - phase_fit_rms_rad_p95_ = residuals.empty() - ? 0.0 - : residuals[static_cast( - std::floor(0.95 * static_cast(residuals.size())))]; - - // Recording origin: the median mean delay over the measurements. - std::vector row_means(rows, 0.0); - for (std::size_t row = 0; row < rows; ++row) { - row_means[row] = 0.5 * (delays_[row * 2u] + delays_[row * 2u + 1u]); - } - recording_origin_samples_ = static_cast(std::llround(median(row_means))); - - // Physical spectra (Data.Delay removed) and the alignment delay. - std::vector> physical(raw.size()); - double maximum = 0.0; - for (std::size_t row = 0; row < rows; ++row) { - for (int ear = 0; ear < 2; ++ear) { - const std::size_t base = (row * 2u + static_cast(ear)) * bins_; - const double data_delay = - canonical.delay_samples[selected[row] * 2u + static_cast(ear)]; - for (std::size_t bin = 0; bin < bins_; ++bin) { - const std::complex rotation = - std::exp(std::complex(0.0, -1.0) * omega_[bin] * data_delay); - physical[base + bin] = raw[base + bin] * rotation; - maximum = std::max(maximum, std::abs(physical[base + bin])); - } - } - } - floor_ = std::max(maximum * 1e-6, 1e-15); - - // Directions: deduplicate coincident measurements, keeping the first, then the - // mesh over that set. - std::vector directions; - directions.reserve(rows * 3); - std::vector kept_rows; - for (std::size_t row = 0; row < rows; ++row) { - const double* unit = canonical.unit_directions.data() + selected[row] * 3u; - bool merged = false; - for (std::size_t existing = 0; existing < kept_rows.size(); ++existing) { - const double* other = canonical.unit_directions.data() + kept_rows[existing] * 3u; - if (std::round(unit[0] * 1e10) == std::round(other[0] * 1e10) && - std::round(unit[1] * 1e10) == std::round(other[1] * 1e10) && - std::round(unit[2] * 1e10) == std::round(other[2] * 1e10)) { - // Coincident measurements must agree, as the reference requires. - for (std::size_t tap = 0; tap < canonical.taps * 2u; ++tap) { - const double a = canonical.hrir[selected[row] * 2u * canonical.taps + tap]; - const double b = canonical.hrir[kept_rows[existing] * 2u * canonical.taps + tap]; - if (std::fabs(a - b) > 1e-10 + 1e-8 * std::fabs(b)) { - return field_error("coincident SOFA measurements disagree"); - } - } - merged = true; - break; - } - } - if (merged) { - continue; - } - kept_rows.push_back(selected[row]); - directions.push_back(unit[0]); - directions.push_back(unit[1]); - directions.push_back(unit[2]); - } - const Status mesh_status = mesh_.build(directions, kept_rows.size()); - if (!mesh_status.ok()) { - return mesh_status; - } - // The measurements must enclose the listener: every hull face must sit in - // front of the unit sphere's centre. - for (std::size_t face = 0; face < mesh_.face_count(); ++face) { - const int* ids = mesh_.faces().data() + face * 3; - const double* a = mesh_.directions().data() + ids[0] * 3; - const double* b = mesh_.directions().data() + ids[1] * 3; - const double* c = mesh_.directions().data() + ids[2] * 3; - double one[3]; - double two[3]; - for (int axis = 0; axis < 3; ++axis) { - one[axis] = b[axis] - a[axis]; - two[axis] = c[axis] - a[axis]; - } - double normal[3] = {one[1] * two[2] - one[2] * two[1], - one[2] * two[0] - one[0] * two[2], - one[0] * two[1] - one[1] * two[0]}; - const double length = std::sqrt(normal[0] * normal[0] + normal[1] * normal[1] + - normal[2] * normal[2]); - if (!(length > 0.0)) { - return field_error("ill-conditioned spherical interpolation mesh"); - } - for (double& value : normal) { - value /= length; - } - const double distance = normal[0] * a[0] + normal[1] * a[1] + normal[2] * a[2]; - if (std::fabs(distance) < 1e-9) { - return field_error("SOFA must enclose the listener"); - } - if (distance < 0.0) { - return field_error("ill-conditioned spherical interpolation mesh"); - } - } - - // Aligned spectra and the magnitude representation used by the interpolation. - aligned_.assign(rows * 2 * bins_, std::complex(0.0, 0.0)); - log_magnitude_.assign(rows * 2 * bins_, 0.0); - for (std::size_t row = 0; row < rows; ++row) { - for (int ear = 0; ear < 2; ++ear) { - const std::size_t index = row * 2u + static_cast(ear); - const double delay = delays_[index]; - for (std::size_t bin = 0; bin < bins_; ++bin) { - aligned_[index * bins_ + bin] = - physical[index * bins_ + bin] * - std::exp(std::complex(0.0, omega_[bin] * delay)); - log_magnitude_[index * bins_ + bin] = - std::log(std::max(std::abs(physical[index * bins_ + bin]), floor_)); - } - } - } - - if (method_ == HrirInterpolation::kMcaZero) { - // 41 auditory bands (reference: erb-spaced centres, rounded exponential bank). - centres_hz_.resize(kMcaBands); - const auto erb = [](double frequency) { - return 21.4 * std::log10(1.0 + 0.00437 * frequency); - }; - const double low = erb(50.0); - const double high = erb(20000.0); - for (int band = 0; band < kMcaBands; ++band) { - const double position = low + (high - low) * band / (kMcaBands - 1); - centres_hz_[static_cast(band)] = - (std::pow(10.0, position / 21.4) - 1.0) / 0.00437; - } - bank_.assign(kMcaBands * bins_, 0.0); - for (int band = 0; band < kMcaBands; ++band) { - const double centre = centres_hz_[static_cast(band)]; - const double width = 1.019 * 24.7 * (1.0 + 0.00437 * centre); - double total = 0.0; - for (std::size_t bin = 0; bin < bins_; ++bin) { - const double ratio = (frequencies_[bin] - centre) / width; - double value = std::pow(1.0 + ratio * ratio, -4.0); - if (bin != 0 && bin + 1 != bins_) { - value *= 2.0; - } - bank_[static_cast(band) * bins_ + bin] = value; - total += value; - } - for (std::size_t bin = 0; bin < bins_; ++bin) { - bank_[static_cast(band) * bins_ + bin] /= total; - } - } - auditory_.assign(rows * 2 * kMcaBands, 0.0); - std::vector power(bins_, 0.0); - for (std::size_t row = 0; row < rows; ++row) { - for (int ear = 0; ear < 2; ++ear) { - const std::size_t index = row * 2u + static_cast(ear); - for (std::size_t bin = 0; bin < bins_; ++bin) { - power[bin] = std::norm(physical[index * bins_ + bin]); - } - for (int band = 0; band < kMcaBands; ++band) { - double sum = 0.0; - for (std::size_t bin = 0; bin < bins_; ++bin) { - sum += power[bin] * - bank_[static_cast(band) * bins_ + bin]; - } - auditory_[index * kMcaBands + static_cast(band)] = - 10.0 * std::log10(std::max(sum, 1e-24)); - } - } - } - } - return Status::success(); -} - -Status FullHrirField::spectrum(const double direction[3], - std::vector>* out) { - if (out == nullptr) { - return argument_error("spectrum output is null"); - } - std::vector ids; - std::vector weights; - const Status status = mesh_.weights(direction, &ids, &weights); - if (!status.ok()) { - return status; - } - if (ids.empty()) { - return field_error("no interpolation weights for the direction"); - } - double delay[2] = {0.0, 0.0}; - for (std::size_t index = 0; index < ids.size(); ++index) { - const std::size_t id = static_cast(ids[index]); - for (int ear = 0; ear < 2; ++ear) { - delay[ear] += weights[index] * delays_[id * 2u + static_cast(ear)]; - } - } - out->assign(2 * bins_, std::complex(0.0, 0.0)); - for (std::size_t index = 0; index < ids.size(); ++index) { - const std::size_t id = static_cast(ids[index]); - for (int ear = 0; ear < 2; ++ear) { - const std::complex* aligned = - aligned_.data() + (id * 2u + static_cast(ear)) * bins_; - for (std::size_t bin = 0; bin < bins_; ++bin) { - (*out)[static_cast(ear) * bins_ + bin] += - weights[index] * aligned[bin]; - } - } - } - for (int ear = 0; ear < 2; ++ear) { - for (std::size_t bin = 0; bin < bins_; ++bin) { - (*out)[static_cast(ear) * bins_ + bin] *= - std::exp(std::complex(0.0, -omega_[bin] * - delay[static_cast(ear)])); - } - } - if (ids.size() > 1) { - if (method_ == HrirInterpolation::kLogMagnitudePhase) { - for (int ear = 0; ear < 2; ++ear) { - std::vector magnitude(bins_, 0.0); - for (std::size_t index = 0; index < ids.size(); ++index) { - const std::size_t id = static_cast(ids[index]); - const double* values = - log_magnitude_.data() + - (id * 2u + static_cast(ear)) * bins_; - for (std::size_t bin = 0; bin < bins_; ++bin) { - magnitude[bin] += weights[index] * values[bin]; - } - } - for (std::size_t bin = 0; bin < bins_; ++bin) { - std::complex& value = - (*out)[static_cast(ear) * bins_ + bin]; - const double target = std::exp(magnitude[bin]); - value = target * value / - std::max(std::abs(value), floor_); - } - } - } else { - for (int ear = 0; ear < 2; ++ear) { - std::vector target(kMcaBands, 0.0); - for (std::size_t index = 0; index < ids.size(); ++index) { - const std::size_t id = static_cast(ids[index]); - const double* values = - auditory_.data() + - (id * 2u + static_cast(ear)) * kMcaBands; - for (int band = 0; band < kMcaBands; ++band) { - target[static_cast(band)] += weights[index] * values[band]; - } - } - // Auditory band levels of the interpolated spectrum. - std::vector power(bins_, 0.0); - for (std::size_t bin = 0; bin < bins_; ++bin) { - power[bin] = std::norm((*out)[static_cast(ear) * bins_ + bin]); - } - std::vector difference(kMcaBands, 0.0); - for (int band = 0; band < kMcaBands; ++band) { - double sum = 0.0; - for (std::size_t bin = 0; bin < bins_; ++bin) { - sum += power[bin] * - bank_[static_cast(band) * bins_ + bin]; - } - difference[static_cast(band)] = - target[static_cast(band)] - - 10.0 * std::log10(std::max(sum, 1e-24)); - } - PchipEvaluator interpolator; - interpolator.build(centres_hz_, difference); - for (std::size_t bin = 0; bin < bins_; ++bin) { - const double frequency = - std::clamp(frequencies_[bin], centres_hz_.front(), centres_hz_.back()); - const double correction = std::clamp(interpolator.evaluate(frequency), - -12.0, 12.0); - (*out)[static_cast(ear) * bins_ + bin] *= - std::pow(10.0, correction / 20.0); - } - } - } - } - return Status::success(); -} - -} // namespace joc::hrtf diff --git a/src/hrtf/full_hrir_field.h b/src/hrtf/full_hrir_field.h deleted file mode 100644 index 508dbdf..0000000 --- a/src/hrtf/full_hrir_field.h +++ /dev/null @@ -1,77 +0,0 @@ - -#pragma once - -#include -#include -#include -#include - -#include "foundation/status.h" -#include "hrtf/spherical_mesh.h" - -// Full-HRIR directional field, ported from the reference sofa_hrir.py: the -// selected measurement shell keeps its complete FIR support, the interpolation -// works on delay-aligned complex spectra inside the containing spherical -// triangle, and the radial model is the analytic rigid-sphere series. This -// replaces the compiled 77-band/SH field for SOFA inputs. -namespace joc::hrtf { - -struct CanonicalHrtf; - -enum class HrirInterpolation : std::uint32_t { - kLogMagnitudePhase = 0, // lf_logmag_phase: geometric mean magnitude, interpolated phase - kMcaZero = 1, // lf_mca_zero: auditory-band magnitude correction -}; - -struct FullHrirOptions { - HrirInterpolation method = HrirInterpolation::kLogMagnitudePhase; - bool has_shell_radius = false; - double shell_radius_m = 0.0; - std::size_t fft_size = 0; // 0 selects the automatic size -}; - -class FullHrirField { -public: - // Builds the field from a canonical SimpleFreeFieldHRIR set (48 kHz only). - Status build(const CanonicalHrtf& canonical, const FullHrirOptions& options); - - std::size_t fft_size() const { return fft_size_; } - std::size_t frequency_bins() const { return bins_; } - const std::vector& frequencies() const { return frequencies_; } - const std::vector& omega() const { return omega_; } - double measurement_radius_m() const { return measurement_radius_m_; } - std::size_t direction_count() const { return mesh_.vertex_count(); } - std::size_t triangle_count() const { return mesh_.face_count(); } - int recording_origin_samples() const { return recording_origin_samples_; } - int common_latency_samples() const { return static_cast(fft_size_ / 2); } - double max_triangle_edge_degrees() const { return mesh_.max_triangle_edge_degrees(); } - double phase_fit_rms_rad_p95() const { return phase_fit_rms_rad_p95_; } - double floor() const { return floor_; } - HrirInterpolation method() const { return method_; } - - // Interpolated two-ear spectrum at a direction (`out` is [2][bins] complex). - Status spectrum(const double direction[3], std::vector>* out); - -private: - Status build_interpolation(const CanonicalHrtf& canonical, const FullHrirOptions& options); - - std::size_t fft_size_ = 0; - std::size_t bins_ = 0; - std::size_t taps_ = 0; - HrirInterpolation method_ = HrirInterpolation::kLogMagnitudePhase; - SphericalMesh mesh_; - std::vector frequencies_; // [bins] - std::vector omega_; // [bins] - std::vector delays_; // [M][2] samples (estimated + Data.Delay) - std::vector> aligned_; // [M][2][bins] - std::vector log_magnitude_; // [M][2][bins] - std::vector auditory_; // [M][2][41] (MCA method only) - std::vector centres_hz_; // [41] (MCA method only) - std::vector bank_; // [41][bins] (MCA method only) - double measurement_radius_m_ = 0.0; - double floor_ = 1.0e-15; - int recording_origin_samples_ = 0; - double phase_fit_rms_rad_p95_ = 0.0; -}; - -} // namespace joc::hrtf diff --git a/src/hrtf/partitioned_convolution.cpp b/src/hrtf/partitioned_convolution.cpp deleted file mode 100644 index 637db5f..0000000 --- a/src/hrtf/partitioned_convolution.cpp +++ /dev/null @@ -1,336 +0,0 @@ - -#include "hrtf/partitioned_convolution.h" - -#include -#include -#include - -namespace joc::hrtf { -namespace { - -using joc::dsp::Complex; - -bool is_power_of_two(std::size_t value) { return value != 0 && (value & (value - 1)) == 0; } - -Status argument_error(const char* message) { - return Status::fail(JOC_ERR_INVALID_ARGUMENT, joc::stage::kDsp, message); -} - -} // namespace - -UniformPartitionedConvolver::UniformPartitionedConvolver(std::size_t outputs, - std::size_t max_filter_taps, - std::size_t block_size) { - configure(outputs, max_filter_taps, block_size); -} - -void UniformPartitionedConvolver::configure(std::size_t outputs, std::size_t max_filter_taps, - std::size_t block_size) { - outputs_ = outputs; - max_filter_taps_ = max_filter_taps; - block_size_ = block_size; - fft_size_ = 2 * block_size; - bins_ = block_size + 1; - partitions_ = block_size == 0 ? 0 : (max_filter_taps + block_size - 1) / block_size; - history_.assign(partitions_ * bins_, Complex{}); - spectra_.assign(outputs_ * partitions_ * bins_, Complex{}); - target_spectra_.assign(outputs_ * partitions_ * bins_, Complex{}); - overlap_.assign(outputs_ * block_size, 0.0); - target_overlap_.assign(outputs_ * block_size, 0.0); - work_.assign(bins_, Complex{}); - fft_buffer_.assign(fft_size_, Complex{}); - time_work_.assign(fft_size_, 0.0); - ordered_.assign(partitions_ * bins_, Complex{}); - if (is_power_of_two(fft_size_)) { - forward_plan_ = std::make_unique(fft_size_, false); - inverse_plan_ = std::make_unique(fft_size_, true); - } else { - forward_plan_.reset(); - inverse_plan_.reset(); - } - write_index_ = -1; - processed_blocks_ = 0; - target_active_ = false; - fade_samples_ = 0; - fade_position_ = 0; -} - -void UniformPartitionedConvolver::reset() { - std::fill(history_.begin(), history_.end(), Complex{}); - std::fill(overlap_.begin(), overlap_.end(), 0.0); - std::fill(target_overlap_.begin(), target_overlap_.end(), 0.0); - std::fill(target_spectra_.begin(), target_spectra_.end(), Complex{}); - write_index_ = -1; - processed_blocks_ = 0; - target_active_ = false; - fade_samples_ = 0; - fade_position_ = 0; -} - -void UniformPartitionedConvolver::real_spectrum(const double* time, - std::vector* out) const { - // numpy.fft.rfft of a real block: the unnormalised forward transform, first - // block_size+1 bins of the size-2*block_size complex transform. - std::fill(fft_buffer_.begin(), fft_buffer_.end(), Complex{}); - for (std::size_t i = 0; i < fft_size_; ++i) { - fft_buffer_[i] = Complex(time[i], 0.0); - } - if (forward_plan_) { - dsp::fft_radix2(&fft_buffer_, *forward_plan_); - } else { - std::vector transformed; - dsp::fft_any(fft_buffer_, false, &transformed); - fft_buffer_ = std::move(transformed); - } - out->assign(fft_buffer_.begin(), fft_buffer_.begin() + static_cast(bins_)); -} - -void UniformPartitionedConvolver::real_signal(const std::vector& spectrum, - double* out) const { - // numpy.fft.irfft: rebuild the Hermitian half, inverse transform (1/N), real part. - std::fill(fft_buffer_.begin(), fft_buffer_.end(), Complex{}); - for (std::size_t bin = 0; bin < bins_; ++bin) { - fft_buffer_[bin] = spectrum[bin]; - } - for (std::size_t bin = 1; bin + 1 < bins_; ++bin) { - fft_buffer_[fft_size_ - bin] = std::conj(spectrum[bin]); - } - if (inverse_plan_) { - dsp::fft_radix2(&fft_buffer_, *inverse_plan_); - } else { - std::vector transformed; - dsp::fft_any(fft_buffer_, true, &transformed); - fft_buffer_ = std::move(transformed); - } - for (std::size_t i = 0; i < fft_size_; ++i) { - out[i] = fft_buffer_[i].real(); - } -} - -void UniformPartitionedConvolver::partition(const double* filters, std::size_t taps, - std::vector* out) { - std::vector padded(fft_size_); - out->assign(outputs_ * partitions_ * bins_, Complex{}); - for (std::size_t partition_index = 0; partition_index < partitions_; ++partition_index) { - const std::size_t start = partition_index * block_size_; - if (start >= taps) { - break; - } - const std::size_t stop = std::min(start + block_size_, taps); - for (std::size_t output = 0; output < outputs_; ++output) { - std::fill(padded.begin(), padded.end(), 0.0); - const double* row = filters + output * taps; - std::memcpy(padded.data(), row + start, sizeof(double) * (stop - start)); - real_spectrum(padded.data(), &work_); - std::copy(work_.begin(), work_.end(), - out->begin() + static_cast( - (output * partitions_ + partition_index) * bins_)); - } - } -} - -void UniformPartitionedConvolver::order_history() { - // index 0 is the block just written; index p is p blocks ago. - for (std::size_t partition_index = 0; partition_index < partitions_; ++partition_index) { - std::ptrdiff_t index = 0; - if (write_index_ >= 0) { - const std::ptrdiff_t count = static_cast(partitions_); - index = (write_index_ - static_cast(partition_index) + count) % count; - } - std::copy(history_.begin() + index * static_cast(bins_), - history_.begin() + (index + 1) * static_cast(bins_), - ordered_.begin() + static_cast(partition_index * bins_)); - } -} - -void UniformPartitionedConvolver::convolution_block(const std::vector& spectra, - const std::vector& overlap, - double* out, double* next_overlap) { - order_history(); - for (std::size_t output = 0; output < outputs_; ++output) { - std::fill(work_.begin(), work_.end(), Complex{}); - for (std::size_t partition_index = 0; partition_index < partitions_; ++partition_index) { - const Complex* input = ordered_.data() + partition_index * bins_; - const Complex* filter = - spectra.data() + (output * partitions_ + partition_index) * bins_; - for (std::size_t bin = 0; bin < bins_; ++bin) { - work_[bin] += input[bin] * filter[bin]; - } - } - real_signal(work_, time_work_.data()); - for (std::size_t sample = 0; sample < block_size_; ++sample) { - out[output * block_size_ + sample] = - time_work_[sample] + overlap[output * block_size_ + sample]; - next_overlap[output * block_size_ + sample] = time_work_[block_size_ + sample]; - } - } -} - -void UniformPartitionedConvolver::overlap_for_previous_block( - const std::vector& spectra, double* overlap) { - if (processed_blocks_ == 0) { - std::fill(overlap, overlap + outputs_ * block_size_, 0.0); - return; - } - order_history(); - for (std::size_t output = 0; output < outputs_; ++output) { - std::fill(work_.begin(), work_.end(), Complex{}); - for (std::size_t partition_index = 0; partition_index < partitions_; ++partition_index) { - const Complex* input = ordered_.data() + partition_index * bins_; - const Complex* filter = - spectra.data() + (output * partitions_ + partition_index) * bins_; - for (std::size_t bin = 0; bin < bins_; ++bin) { - work_[bin] += input[bin] * filter[bin]; - } - } - real_signal(work_, time_work_.data()); - std::memcpy(overlap + output * block_size_, time_work_.data() + block_size_, - sizeof(double) * block_size_); - } -} - -Status UniformPartitionedConvolver::set_filter(const double* filters, std::size_t taps, - std::size_t fade_blocks) { - if ((filters == nullptr && taps != 0) || block_size_ == 0 || outputs_ == 0 || - taps > max_filter_taps_) { - return argument_error("filter update exceeds the configured tap budget"); - } - for (std::size_t i = 0; i < outputs_ * taps; ++i) { - if (!std::isfinite(filters[i])) { - return argument_error("filter update contains a non-finite value"); - } - } - partition(filters, taps, &target_spectra_); - if (fade_blocks == 0) { - spectra_ = target_spectra_; - overlap_for_previous_block(spectra_, overlap_.data()); - target_active_ = false; - fade_samples_ = 0; - fade_position_ = 0; - return Status::success(); - } - overlap_for_previous_block(target_spectra_, target_overlap_.data()); - target_active_ = true; - fade_samples_ = static_cast(fade_blocks * block_size_); - fade_position_ = 0; - return Status::success(); -} - -Status UniformPartitionedConvolver::process_block(const double* block, double* out) { - if (block == nullptr || out == nullptr) { - return argument_error("block pointer is null"); - } - for (std::size_t i = 0; i < block_size_; ++i) { - if (!std::isfinite(block[i])) { - return argument_error("input block contains a non-finite value"); - } - } - std::fill(time_work_.begin(), time_work_.end(), 0.0); - std::memcpy(time_work_.data(), block, sizeof(double) * block_size_); - real_spectrum(time_work_.data(), &work_); - write_index_ = (write_index_ + 1) % static_cast(partitions_); - std::copy(work_.begin(), work_.end(), - history_.begin() + write_index_ * static_cast(bins_)); - - std::vector current(outputs_ * block_size_); - std::vector next_current_overlap(outputs_ * block_size_); - convolution_block(spectra_, overlap_, current.data(), next_current_overlap.data()); - if (!target_active_) { - overlap_ = next_current_overlap; - ++processed_blocks_; - for (std::size_t sample = 0; sample < block_size_; ++sample) { - for (std::size_t output = 0; output < outputs_; ++output) { - out[sample * outputs_ + output] = current[output * block_size_ + sample]; - } - } - return Status::success(); - } - - std::vector target(outputs_ * block_size_); - std::vector next_target_overlap(outputs_ * block_size_); - convolution_block(target_spectra_, target_overlap_, target.data(), - next_target_overlap.data()); - const double fade = static_cast(fade_samples_); - for (std::size_t sample = 0; sample < block_size_; ++sample) { - const double position = - static_cast(fade_position_ + static_cast(sample) + 1); - const double amount = - std::clamp(fade > 0.0 ? position / fade : 1.0, 0.0, 1.0); - for (std::size_t output = 0; output < outputs_; ++output) { - const double dry = current[output * block_size_ + sample]; - const double wet = target[output * block_size_ + sample]; - out[sample * outputs_ + output] = dry * (1.0 - amount) + wet * amount; - } - } - fade_position_ += static_cast(block_size_); - overlap_ = next_current_overlap; - target_overlap_ = next_target_overlap; - if (fade_position_ >= fade_samples_) { - spectra_ = target_spectra_; - overlap_ = target_overlap_; - target_active_ = false; - fade_samples_ = 0; - fade_position_ = 0; - } - ++processed_blocks_; - return Status::success(); -} - -MultiSourcePartitionedConvolver::MultiSourcePartitionedConvolver( - std::size_t source_count, std::size_t block_size, std::size_t max_filter_taps, - std::size_t output_channels) { - configure(source_count, block_size, max_filter_taps, output_channels); -} - -void MultiSourcePartitionedConvolver::configure(std::size_t source_count, - std::size_t block_size, - std::size_t max_filter_taps, - std::size_t output_channels) { - block_size_ = block_size; - max_filter_taps_ = max_filter_taps; - output_channels_ = output_channels; - convolvers_.clear(); - convolvers_.resize(source_count); - for (UniformPartitionedConvolver& convolver : convolvers_) { - convolver.configure(output_channels, max_filter_taps, block_size); - } - source_block_.assign(block_size, 0.0); - partial_.assign(block_size * output_channels, 0.0); -} - -void MultiSourcePartitionedConvolver::reset() { - for (UniformPartitionedConvolver& convolver : convolvers_) { - convolver.reset(); - } -} - -Status MultiSourcePartitionedConvolver::set_filter(std::size_t source, const double* filters, - std::size_t taps, std::size_t fade_blocks) { - if (source >= convolvers_.size()) { - return argument_error("source index is out of range"); - } - return convolvers_[source].set_filter(filters, taps, fade_blocks); -} - -Status MultiSourcePartitionedConvolver::process_block(const double* sources, double* out) { - if (sources == nullptr || out == nullptr) { - return argument_error("block pointer is null"); - } - std::fill(out, out + block_size_ * output_channels_, 0.0); - for (std::size_t source = 0; source < convolvers_.size(); ++source) { - for (std::size_t sample = 0; sample < block_size_; ++sample) { - source_block_[sample] = sources[sample * convolvers_.size() + source]; - } - const Status status = - convolvers_[source].process_block(source_block_.data(), partial_.data()); - if (!status.ok()) { - return status; - } - for (std::size_t i = 0; i < partial_.size(); ++i) { - out[i] += partial_[i]; - } - } - return Status::success(); -} - -} // namespace joc::hrtf diff --git a/src/hrtf/partitioned_convolution.h b/src/hrtf/partitioned_convolution.h deleted file mode 100644 index 4cc809e..0000000 --- a/src/hrtf/partitioned_convolution.h +++ /dev/null @@ -1,118 +0,0 @@ - -#pragma once - -#include -#include -#include -#include -#include - -#include "foundation/fft.h" -#include "foundation/status.h" - -// Uniform partitioned convolution, ported from the reference -// partitioned_convolution.py. One input history is shared by the outputs of a -// source; a filter replacement can crossfade the output over a number of blocks -// while both the old and the new filter keep their own overlap tail. -namespace joc::hrtf { - -class UniformPartitionedConvolver { -public: - UniformPartitionedConvolver() = default; - UniformPartitionedConvolver(std::size_t outputs, std::size_t max_filter_taps, - std::size_t block_size); - - void configure(std::size_t outputs, std::size_t max_filter_taps, std::size_t block_size); - - std::size_t outputs() const { return outputs_; } - std::size_t block_size() const { return block_size_; } - std::size_t fft_size() const { return fft_size_; } - std::size_t max_filter_taps() const { return max_filter_taps_; } - bool transition_active() const { return target_active_; } - - // `filters` is [outputs][taps] row-major and `taps` <= max_filter_taps. A zero - // fade applies the filter immediately and rebuilds the overlap tail from the - // blocks already processed, so an impulse in flight is not dropped. - Status set_filter(const double* filters, std::size_t taps, std::size_t fade_blocks); - - // `block` is block_size doubles; `out` is block_size*outputs, sample-major. - Status process_block(const double* block, double* out); - - void reset(); - -private: - void partition(const double* filters, std::size_t taps, - std::vector>* out); - void convolution_block(const std::vector>& spectra, - const std::vector& overlap, double* out, - double* next_overlap); - void overlap_for_previous_block(const std::vector>& spectra, - double* overlap); - void order_history(); - void real_spectrum(const double* time, std::vector>* out) const; - void real_signal(const std::vector>& spectrum, double* out) const; - - std::size_t outputs_ = 0; - std::size_t max_filter_taps_ = 0; - std::size_t block_size_ = 0; - std::size_t fft_size_ = 0; - std::size_t bins_ = 0; - std::size_t partitions_ = 0; - - std::unique_ptr forward_plan_; - std::unique_ptr inverse_plan_; - mutable std::vector> fft_buffer_; - - std::vector> history_; // [partitions][bins] - std::vector> spectra_; // [outputs][partitions][bins] - std::vector> target_spectra_; - std::vector overlap_; // [outputs][block] - std::vector target_overlap_; // [outputs][block] - std::vector> work_; // [bins] scratch - std::vector time_work_; // [fft_size] scratch - std::vector> ordered_; // [partitions][bins] scratch - - std::ptrdiff_t write_index_ = -1; - std::uint64_t processed_blocks_ = 0; - bool target_active_ = false; - std::int64_t fade_samples_ = 0; - std::int64_t fade_position_ = 0; -}; - -class MultiSourcePartitionedConvolver { -public: - MultiSourcePartitionedConvolver() = default; - MultiSourcePartitionedConvolver(std::size_t source_count, std::size_t block_size, - std::size_t max_filter_taps, - std::size_t output_channels = 2); - - void configure(std::size_t source_count, std::size_t block_size, - std::size_t max_filter_taps, std::size_t output_channels = 2); - - std::size_t source_count() const { return convolvers_.size(); } - std::size_t block_size() const { return block_size_; } - std::size_t output_channels() const { return output_channels_; } - std::size_t max_filter_taps() const { return max_filter_taps_; } - const UniformPartitionedConvolver& convolver(std::size_t source) const { - return convolvers_[source]; - } - - Status set_filter(std::size_t source, const double* filters, std::size_t taps, - std::size_t fade_blocks); - - // `sources` is block_size*source_count (sample-major); `out` is - // block_size*output_channels and is overwritten. - Status process_block(const double* sources, double* out); - - void reset(); - -private: - std::vector convolvers_; - std::size_t block_size_ = 0; - std::size_t max_filter_taps_ = 0; - std::size_t output_channels_ = 2; - std::vector source_block_; - std::vector partial_; -}; - -} // namespace joc::hrtf diff --git a/src/hrtf/rosella_reference.cpp b/src/hrtf/rosella_reference.cpp deleted file mode 100644 index cd72bc8..0000000 --- a/src/hrtf/rosella_reference.cpp +++ /dev/null @@ -1,854 +0,0 @@ -#include "hrtf/rosella_reference.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "foundation/fft.h" -#include "hrtf/public_filterbank.h" -#include "hrtf/rosella_renderer.h" -#include "simd/simd.h" - -// The reference arithmetic of the Rosella ".personalized_headphone" renderer -// (rosella_model.py, rosella_direct.py and rosella_room.py). rosella_renderer.cpp -// drives these through RosellaRuntime, and a renderer built on another field format -// calls them directly; the bodies are lifted unchanged from the renderer, so their -// operation order and their literals are part of the interface. - -namespace joc::hrtf { - -namespace { - -constexpr int kDirectionTerms = 36; -constexpr int kRoomBands = 64; -constexpr double kRoomInputGain = 0.70710677; -constexpr double kCentreEqual = 0.9998489618301392; -constexpr double kCentreAlternate = 0.7070000171661377; - -// The fixed sixteen-band low-pass a special (LFE) source is rendered through; the -// constants are the float32 bit patterns of rosella_direct._SPECIAL_LFE_LOW_16. -constexpr std::uint32_t kSpecialLfeLowBits[16] = { - 0x402695EAu, 0x3FE75979u, 0x3F28CAAAu, 0xBCE1FB2Eu, 0xBDD8AF65u, 0xBD8F426Eu, - 0x3D996821u, 0xBC16B3A0u, 0x3B64BAF1u, 0xBC81ECFDu, 0xBA3D892Fu, 0x3AF6A9F0u, - 0xB9DD1C5Fu, 0x380A193Fu, 0x38052059u, 0x351BCB34u}; - -Status render_fail(joc_error code, const std::string& message) { - return Status::fail(code, stage::kRender, message); -} - -std::vector special_lfe_low() { - std::vector values(kHybridBands, 0.0); - for (int index = 0; index < 16; ++index) { - float narrowed = 0.0f; - const std::uint32_t bits = kSpecialLfeLowBits[index]; - std::memcpy(&narrowed, &bits, sizeof(float)); - values[static_cast(index)] = static_cast(narrowed); - } - return values; -} - -// rosella_direct._round_away_from_zero. -double round_away_from_zero(double value) { - return value >= 0.0 ? std::floor(value + 0.5) : std::ceil(value - 0.5); -} - -// rosella_direct._q15_position: ADM coordinates on the Rosella metadata grid. -void q15_position(const double position[3], int encoded[3]) { - const double raw[3] = { - std::min(std::max((position[0] + 1.0) * 0.5, 0.0), 1.0), - std::min(std::max((1.0 - position[1]) * 0.5, 0.0), 1.0), - std::min(std::max(position[2], -1.0), 1.0), - }; - for (int axis = 0; axis < 3; ++axis) { - encoded[axis] = static_cast( - std::min(round_away_from_zero(raw[axis] * 32768.0), 32767.0)); - } -} - -struct EarGeometry { - double basis_minus[kDirectionTerms] = {}; - double basis_plus[kDirectionTerms] = {}; - double path_minus = 0.0; - double path_plus = 0.0; -}; - -// rosella_direct._ear_geometry. -EarGeometry ear_geometry(const RosellaModel& model, const RosellaDistanceProfile& profile, - const double direction[3], double clamped, double offset, - double correction) { - const double x = direction[0]; - const double y = direction[1]; - const double z = direction[2]; - const double inverse_distance = static_cast(profile.inverse_distance_per_m); - const double ear = offset * inverse_distance / clamped; - const double y_minus = y - ear; - const double y_plus = y + ear; - const double common = x * x + z * z; - const double length_minus = std::sqrt(y_minus * y_minus + common); - const double length_plus = std::sqrt(y_plus * y_plus + common); - EarGeometry result; - direction_basis(x / length_minus, y_minus / length_minus, z / length_minus, - result.basis_minus); - direction_basis(x / length_plus, y_plus / length_plus, z / length_plus, result.basis_plus); - result.path_minus = length_minus * clamped; - result.path_plus = length_plus * clamped; - if (correction != 0.0) { - const double multiplier = 2.0 * correction * inverse_distance; - double left = 0.0; - double right = 0.0; - for (int term = 0; term < kDirectionTerms; ++term) { - left += static_cast(model.vector_left[static_cast(term)]) * - result.basis_minus[term]; - right += static_cast(model.vector_right[static_cast(term)]) * - result.basis_plus[term]; - } - result.path_minus += std::max(left, 0.0) * multiplier; - result.path_plus += std::max(right, 0.0) * multiplier; - } - return result; -} - -// rosella_direct._phase_groups. -void phase_groups(const RosellaModel& model, double delay_samples, Complex* out) { - // The reference starts from np.ones(77) and only rewrites the flagged bands. - std::fill(out, out + kHybridBands, Complex(1.0, 0.0)); - Complex current(1.0, 0.0); - Complex step(1.0, 0.0); - std::size_t value_index = 0u; - for (std::size_t band = 0u; band < model.hybrid_flags.size() && band < kHybridBands; ++band) { - const int flag = model.hybrid_flags[band]; - if (flag != 2) { - if (flag == 1) { - const double angle = - static_cast(model.hybrid_values[value_index]) * delay_samples; - ++value_index; - step = Complex(std::cos(angle), std::sin(angle)); - } - current *= step; - } - out[band] = current; - } -} - -} // namespace - -// rosella_model.direction_basis: the observed 36-term basis. The operation order is -// part of the model, so the intermediates are named after the reference's. -void direction_basis(double x, double y, double z, double* out) { - const double yz = y * z; - const double x2 = x * x; - const double y2 = y * y; - const double x2m02 = x2 - 0.2; - const double xy = x * y; - out[0] = 1.0; - out[1] = x; - out[2] = y; - out[3] = z; - out[4] = x2 - (1.0 / 3.0); - out[5] = xy; - out[6] = x * z; - out[7] = y2 - (1.0 / 3.0); - out[8] = yz; - out[9] = (x2 - 0.6) * x; - out[10] = x2m02 * y; - out[11] = x2m02 * z; - out[12] = (y2 - 0.2) * x; - out[13] = yz * x; - out[14] = (y2 - 0.6) * y; - out[15] = (y2 - 0.2) * z; - out[16] = x2 * x2 - 0.2; - out[17] = xy * x2; - out[18] = (x * z) * x2; - out[19] = y2 * x2 - (1.0 / 15.0); - out[20] = yz * x2; - out[21] = x * y2 * y; - out[22] = x * y2 * z; - out[23] = y2 * y2 - 0.2; - const double x4 = x2 * x2; - const double x2y2 = y2 * x2; - const double y4 = y2 * y2; - out[24] = yz * y2; - out[25] = (x4 - (3.0 / 7.0)) * x; - out[26] = (x4 - (3.0 / 35.0)) * y; - out[27] = (x4 - (3.0 / 35.0)) * z; - out[28] = (x2y2 - (3.0 / 35.0)) * x; - out[29] = (x2 * z) * xy; - out[30] = (x2y2 - (3.0 / 35.0)) * y; - out[31] = (x2y2 - (1.0 / 35.0)) * z; - out[32] = (y4 - (3.0 / 35.0)) * x; - out[33] = (y2 * z) * xy; - out[34] = (y4 - (3.0 / 7.0)) * y; - out[35] = (y4 - (3.0 / 35.0)) * z; -} - -// rosella_direct._logical_field: the padded lane grid as [77][36][2] float64. -std::vector rosella_logical_field(const std::vector& padded) { - std::vector out; - out.assign(static_cast(kHybridBands) * kDirectionTerms * 2u, 0.0); - for (int band = 0; band < kHybridBands; ++band) { - const int block = band / 4; - const int lane = band % 4; - for (int term = 0; term < kDirectionTerms; ++term) { - for (int component = 0; component < 2; ++component) { - const std::size_t source = - static_cast(lane + 4 * (term * 2 + component + 72 * block)); - out[(static_cast(band) * kDirectionTerms + - static_cast(term)) * 2u + - static_cast(component)] = - source < padded.size() ? static_cast(padded[source]) : 0.0; - } - } - } - return out; -} - -// rosella_direct._profile_geometry. -Status profile_geometry(const RosellaModel& model, const double position[3], int profile_index, - ProfileGeometry* out) { - const RosellaDistanceProfile& profile = model.profiles[static_cast(profile_index)]; - int encoded[3] = {0, 0, 0}; - q15_position(position, encoded); - const double q_front = 1.0 - 2.0 * static_cast(encoded[1]) / 32768.0; - const double q_x = 2.0 * static_cast(encoded[0]) / 32768.0 - 1.0; - const double q_vertical = static_cast(encoded[2]) / 32768.0; - double mapped_front = q_front; - double mapped_lateral = -q_x; - double mapped_vertical = q_vertical; - if (model.header_integer_fields[0] != 0) { - if (q_x == 0.0 && q_front == 0.0) { - mapped_front = 0.0; - mapped_lateral = 0.0; - mapped_vertical = q_vertical; - } else { - const double horizontal_max = std::max(std::abs(q_x), std::abs(q_front)); - const double horizontal_norm = (q_x / horizontal_max) * (q_x / horizontal_max) + - (q_front / horizontal_max) * (q_front / horizontal_max); - double vertical_norm = 1.0; - if (q_vertical != 0.0) { - const double smaller = std::min(std::abs(q_vertical), horizontal_max); - const double larger = std::max(std::abs(q_vertical), horizontal_max); - vertical_norm = 1.0 + (smaller / larger) * (smaller / larger); - } - const double horizontal_factor = 1.0 / std::sqrt(horizontal_norm * vertical_norm); - const double vertical_factor = 1.0 / std::sqrt(vertical_norm); - mapped_front = q_front * horizontal_factor; - mapped_lateral = -q_x * horizontal_factor; - mapped_vertical = q_vertical * vertical_factor; - } - } - double scaled[3] = {mapped_front * static_cast(profile.axis_scales_internal[2]), - mapped_lateral * static_cast(profile.axis_scales_internal[0]), - mapped_vertical * static_cast(profile.axis_scales_internal[1])}; - double ray = 1.0; - for (int axis = 0; axis < 3; ++axis) { - const double value = scaled[axis]; - const double lower = static_cast(profile.bounds[static_cast(axis) * 2u]); - const double upper = - static_cast(profile.bounds[static_cast(axis) * 2u + 1u]); - if (value < lower) { - ray = std::min(ray, lower / value); - } else if (value > upper) { - ray = std::min(ray, upper / value); - } - } - if (ray < 1.0) { - scaled[0] *= ray; - scaled[1] *= ray; - scaled[2] *= ray; - } - ProfileGeometry result; - result.radius = std::sqrt(scaled[0] * scaled[0] + scaled[1] * scaled[1] + - scaled[2] * scaled[2]); - result.clamped = std::max(result.radius, static_cast(profile.minimum_normalized_radius)); - result.alpha = result.radius / result.clamped; - if (result.radius > 1.0e-30) { - for (int axis = 0; axis < 3; ++axis) { - result.direction[axis] = scaled[axis] / result.radius; - } - } - *out = result; - return Status::success(); -} - -// rosella_direct.special_lfe_direct. -const DirectResult& special_lfe_direct() { - static const DirectResult result = [] { - DirectResult direct; - const std::vector low = special_lfe_low(); - for (int ear = 0; ear < 2; ++ear) { - for (int band = 0; band < kHybridBands; ++band) { - direct.gains[ear][band] = Complex(low[static_cast(band)], 0.0); - } - } - return direct; - }(); - return result; -} - -// rosella_direct.direct_and_room_send. -Status direct_and_room_send(const RosellaModel& model, const std::vector& field_left, - const std::vector& field_right, const double position[3], - int profile_index, DirectResult* out) { - const RosellaDistanceProfile& profile = - model.profiles[static_cast(profile_index)]; - ProfileGeometry geometry; - const Status geometry_status = profile_geometry(model, position, profile_index, &geometry); - if (!geometry_status.ok()) { - return geometry_status; - } - - const EarGeometry delay_ears = - ear_geometry(model, profile, geometry.direction, geometry.clamped, - static_cast(model.model_scalars[1]), - static_cast(model.model_scalars[2])); - const double delay = std::abs(delay_ears.path_plus - delay_ears.path_minus) * - static_cast(profile.distance_scale_m) * - (static_cast(model.sample_rate) / 343.3) * geometry.alpha; - int delayed_ear = -1; - if (delay_ears.path_minus > delay_ears.path_plus) { - delayed_ear = 0; - } else if (delay_ears.path_plus > delay_ears.path_minus) { - delayed_ear = 1; - } - - const EarGeometry weight_ears = - ear_geometry(model, profile, geometry.direction, geometry.clamped, - static_cast(model.model_scalars[3]), - static_cast(model.model_scalars[4])); - const double weight_norm = - std::sqrt(weight_ears.path_minus * weight_ears.path_minus + - weight_ears.path_plus * weight_ears.path_plus); - const double weight_left = weight_ears.path_plus / weight_norm; - const double weight_right = weight_ears.path_minus / weight_norm; - - const double final_offset = static_cast(model.model_scalars[0]); - double basis_minus[kDirectionTerms] = {}; - double basis_plus[kDirectionTerms] = {}; - if (final_offset == 0.0) { - direction_basis(geometry.direction[0], geometry.direction[1], geometry.direction[2], - basis_minus); - std::copy(basis_minus, basis_minus + kDirectionTerms, basis_plus); - } else { - const double x = geometry.direction[0]; - const double y = geometry.direction[1]; - const double z = geometry.direction[2]; - const double ear = - final_offset * static_cast(profile.inverse_distance_per_m) / geometry.clamped; - const double y_minus = y - ear; - const double y_plus = y + ear; - const double common_length = x * x + z * z; - const double length_minus = std::sqrt(y_minus * y_minus + common_length); - const double length_plus = std::sqrt(y_plus * y_plus + common_length); - direction_basis(x / length_minus, y_minus / length_minus, z / length_minus, basis_minus); - direction_basis(x / length_plus, y_plus / length_plus, z / length_plus, basis_plus); - } - - DirectResult result; - Complex left[kHybridBands] = {}; - Complex right[kHybridBands] = {}; - for (int band = 0; band < kHybridBands; ++band) { - double left_real = 0.0; - double left_imag = 0.0; - double right_real = 0.0; - double right_imag = 0.0; - for (int term = 0; term < kDirectionTerms; ++term) { - const std::size_t index = - (static_cast(band) * kDirectionTerms + static_cast(term)) * - 2u; - left_real += field_left[index] * basis_minus[term]; - left_imag += field_left[index + 1u] * basis_minus[term]; - right_real += field_right[index] * basis_plus[term]; - right_imag += field_right[index + 1u] * basis_plus[term]; - } - left[band] = Complex(left_real, left_imag); - right[band] = Complex(right_real, right_imag); - } - if (delayed_ear >= 0) { - Complex phase[kHybridBands]; - phase_groups(model, delay, phase); - Complex* target = delayed_ear == 0 ? left : right; - for (int band = 0; band < kHybridBands; ++band) { - target[band] *= phase[band]; - } - } - - const double effective_radius = - geometry.radius * static_cast(model.header_float_scalars[0]) * - static_cast(profile.distance_scale_m); - double common = 1.0; - double room_send = 0.0; - if (profile_index == static_cast(RosellaProfile::Far) || - profile_index == static_cast(RosellaProfile::Mid)) { - common = 1.0 / std::sqrt(1.0 + static_cast(model.header_float_scalars[1]) * - effective_radius * effective_radius); - room_send = effective_radius * common; - } - - Complex left_term0[kHybridBands]; - Complex right_term0[kHybridBands]; - for (int band = 0; band < kHybridBands; ++band) { - const std::size_t index = static_cast(band) * kDirectionTerms * 2u; - left_term0[band] = Complex(field_left[index], field_left[index + 1u]); - right_term0[band] = Complex(field_right[index], field_right[index + 1u]); - } - const bool weights_are_default_equal = - static_cast(model.model_scalars[3]) == 0.0 && - static_cast(model.model_scalars[4]) == 0.0; - double centre_left = 0.0; - double centre_right = 0.0; - double right_direction_weight = weight_right; - if (weights_are_default_equal) { - centre_left = weight_left * (1.0 - geometry.alpha) * kCentreEqual; - centre_right = centre_left; - right_direction_weight = weight_left; - } else { - centre_left = (1.0 - geometry.alpha) * kCentreAlternate; - centre_right = centre_left; - } - for (int band = 0; band < kHybridBands; ++band) { - result.gains[0][band] = - common * (left[band] * (weight_left * geometry.alpha) + left_term0[band] * centre_left); - result.gains[1][band] = common * (right[band] * (right_direction_weight * geometry.alpha) + - right_term0[band] * centre_right); - } - result.room_send = room_send; - result.physical_radius_m = static_cast(profile.distance_scale_m) * geometry.radius; - result.normalized_radius = geometry.radius; - result.clamped_radius = geometry.clamped; - result.delay_samples = delay; - result.delayed_ear = delayed_ear; - *out = result; - return Status::success(); -} - -namespace { - -// rosella_room._RosellaRoomState: the recursive table-A room model. -class RoomState { -public: - explicit RoomState(const RosellaModel& model) : model_(model) { - bands_ = std::min(64, model.table_a_dimension); - delays_ = model.table_a_four_integers; - capacity_ = 0; - for (const int delay : delays_) { - capacity_ = std::max(capacity_, delay); - } - // The vectors are stored column-major (numpy's order="F"). - matrix_.assign(16u, 0.0); - for (int row = 0; row < 4; ++row) { - for (int column = 0; column < 4; ++column) { - matrix_[static_cast(row) + 4u * static_cast(column)] = - static_cast(model.table_a_vector16[static_cast(row) + - 4u * static_cast(column)]); - } - } - const std::vector& f8 = model.table_a_filter_8x64_padded; - const std::vector& f4 = model.table_a_filter_4x64_padded; - const std::vector& f16 = model.table_a_filter_16x64_padded; - feedback_real_.assign(static_cast(bands_) * 4u, 0.0); - feedback_imag_.assign(static_cast(bands_) * 4u, 0.0); - output_tap_.assign(static_cast(bands_) * 4u, 0.0); - left_real_.assign(static_cast(bands_) * 4u, 0.0); - left_imag_.assign(static_cast(bands_) * 4u, 0.0); - right_real_.assign(static_cast(bands_) * 4u, 0.0); - right_imag_.assign(static_cast(bands_) * 4u, 0.0); - for (int band = 0; band < bands_; ++band) { - const int group = band / 4; - const int lane = band % 4; - for (int tap = 0; tap < 4; ++tap) { - const std::size_t target = static_cast(band) * 4u + - static_cast(tap); - const std::size_t g8 = ((static_cast(group) * 4u + - static_cast(tap)) * 2u) * - 4u + - static_cast(lane); - feedback_real_[target] = static_cast(f8[g8]); - feedback_imag_[target] = static_cast(f8[g8 + 4u]); - output_tap_[target] = static_cast( - f4[(static_cast(group) * 4u + static_cast(tap)) * 4u + - static_cast(lane)]); - const std::size_t g16 = ((static_cast(group) * 4u + - static_cast(tap)) * 4u) * - 4u; - left_real_[target] = static_cast(f16[g16 + static_cast(lane)]); - left_imag_[target] = - static_cast(f16[g16 + 4u + static_cast(lane)]); - right_real_[target] = - static_cast(f16[g16 + 8u + static_cast(lane)]); - right_imag_[target] = - static_cast(f16[g16 + 12u + static_cast(lane)]); - } - } - allpass_gain_.resize(model.table_a_option_values.size()); - for (std::size_t index = 0u; index < model.table_a_option_values.size(); ++index) { - allpass_gain_[index] = static_cast(model.table_a_option_values[index]); - } - allpass_delay_ = model.table_a_option_ids; - for (const int delay : allpass_delay_) { - allpass_real_.emplace_back(static_cast(delay) * - static_cast(bands_), - 0.0); - allpass_imag_.emplace_back(static_cast(delay) * - static_cast(bands_), - 0.0); - } - allpass_position_.assign(allpass_real_.size(), 0); - memory_real_.assign(static_cast(capacity_) * static_cast(bands_) * 4u, - 0.0); - memory_imag_.assign(memory_real_.size(), 0.0); - extra_matrices_.resize(model.table_a_extra_indices.size()); - for (std::size_t index = 0u; index < extra_matrices_.size(); ++index) { - extra_matrices_[index].assign(16u, 0.0); - for (int row = 0; row < 4; ++row) { - for (int column = 0; column < 4; ++column) { - extra_matrices_[index][static_cast(row) + - 4u * static_cast(column)] = - static_cast( - model.table_a_extra_vectors[index * 16u + static_cast(row) + - 4u * static_cast(column)]); - } - } - } - } - - void reset() { - for (std::vector& value : allpass_real_) { - std::fill(value.begin(), value.end(), 0.0); - } - for (std::vector& value : allpass_imag_) { - std::fill(value.begin(), value.end(), 0.0); - } - std::fill(allpass_position_.begin(), allpass_position_.end(), 0); - std::fill(memory_real_.begin(), memory_real_.end(), 0.0); - std::fill(memory_imag_.begin(), memory_imag_.end(), 0.0); - position_ = 0; - } - - Status process_slot(const Complex* room_send, Complex* output) { - if (static_cast(model_.table_a_scalar) >= 0.5) { - return render_fail(JOC_ERR_NOT_SUPPORTED, "alternate Rosella table-A room mode"); - } - const std::size_t bands = static_cast(bands_); - std::vector input_real(bands, 0.0); - std::vector input_imag(bands, 0.0); - for (std::size_t band = 0u; band < bands; ++band) { - input_real[band] = room_send[band].real() * kRoomInputGain; - input_imag[band] = room_send[band].imag() * kRoomInputGain; - } - for (std::size_t index = 0u; index < allpass_gain_.size(); ++index) { - const std::size_t delay = static_cast(allpass_delay_[index]); - const std::size_t position = static_cast(allpass_position_[index]); - const double gain = allpass_gain_[index]; - for (std::size_t band = 0u; band < bands; ++band) { - const std::size_t cell = position * bands + band; - const double previous_real = allpass_real_[index][cell]; - const double previous_imag = allpass_imag_[index][cell]; - const double residual_real = input_real[band] - previous_real * gain; - const double residual_imag = input_imag[band] - previous_imag * gain; - input_real[band] = residual_real * gain + previous_real; - input_imag[band] = residual_imag * gain + previous_imag; - allpass_real_[index][cell] = residual_real; - allpass_imag_[index][cell] = residual_imag; - } - allpass_position_[index] = static_cast((position + 1u) % delay); - } - - std::vector branch_real(bands * 4u, 0.0); - std::vector branch_imag(bands * 4u, 0.0); - std::vector delayed_real(bands * 4u, 0.0); - std::vector delayed_imag(bands * 4u, 0.0); - for (int branch = 0; branch < 4; ++branch) { - const std::size_t slot = - static_cast((position_ - delays_[static_cast(branch)] + - capacity_) % - capacity_); - for (std::size_t band = 0u; band < bands; ++band) { - const std::size_t source = (slot * bands + band) * 4u + static_cast(branch); - delayed_real[band * 4u + static_cast(branch)] = memory_real_[source]; - delayed_imag[band * 4u + static_cast(branch)] = memory_imag_[source]; - } - } - for (std::size_t band = 0u; band < bands; ++band) { - for (int row = 0; row < 4; ++row) { - double real = input_real[band]; - double imag = input_imag[band]; - for (int column = 0; column < 4; ++column) { - const double coefficient = - matrix_[static_cast(row) + 4u * static_cast(column)]; - real += delayed_real[band * 4u + static_cast(column)] * coefficient; - imag += delayed_imag[band * 4u + static_cast(column)] * coefficient; - } - branch_real[band * 4u + static_cast(row)] = real; - branch_imag[band * 4u + static_cast(row)] = imag; - } - } - - const std::size_t tap_slot = static_cast( - (position_ - model_.table_a_integer + capacity_) % capacity_); - std::vector tap_real(bands * 4u, 0.0); - std::vector tap_imag(bands * 4u, 0.0); - for (std::size_t band = 0u; band < bands; ++band) { - for (int lane = 0; lane < 4; ++lane) { - const std::size_t source = (tap_slot * bands + band) * 4u + static_cast(lane); - tap_real[band * 4u + static_cast(lane)] = memory_real_[source]; - tap_imag[band * 4u + static_cast(lane)] = memory_imag_[source]; - } - } - for (std::size_t cell = 0u; cell < branch_real.size(); ++cell) { - const double real = branch_real[cell]; - const double imag = branch_imag[cell]; - memory_real_[(static_cast(position_) * bands) * 4u + cell] = - real * feedback_real_[cell] - imag * feedback_imag_[cell]; - memory_imag_[(static_cast(position_) * bands) * 4u + cell] = - imag * feedback_real_[cell] + real * feedback_imag_[cell]; - } - position_ = (position_ + 1) % capacity_; - - std::vector extra_real(bands * 4u, 0.0); - std::vector extra_imag(bands * 4u, 0.0); - for (std::size_t index = 0u; index < model_.table_a_extra_indices.size(); ++index) { - const std::size_t delay = - static_cast(model_.table_a_extra_indices[index]); - const std::size_t slot = static_cast( - (position_ - static_cast(delay) - 1 + capacity_ * 2) % capacity_); - for (std::size_t band = 0u; band < bands; ++band) { - for (int row = 0; row < 4; ++row) { - double mixed_real = 0.0; - double mixed_imag = 0.0; - for (int column = 0; column < 4; ++column) { - const std::size_t source = - (slot * bands + band) * 4u + static_cast(column); - const double coefficient = - extra_matrices_[index][static_cast(row) + - 4u * static_cast(column)]; - mixed_real += memory_real_[source] * coefficient; - mixed_imag += memory_imag_[source] * coefficient; - } - const int group = static_cast(band) / 4; - const int lane = static_cast(band) % 4; - const std::size_t field = - (index * 20u + static_cast(group)) * 2u * 4u; - const double coefficient_real = static_cast( - model_.table_a_extra_fields_padded[field + static_cast(lane)]); - const double coefficient_imag = static_cast( - model_.table_a_extra_fields_padded[field + 4u + static_cast(lane)]); - const std::size_t target = band * 4u + static_cast(row); - extra_real[target] += - mixed_real * coefficient_real - mixed_imag * coefficient_imag; - extra_imag[target] += - mixed_imag * coefficient_real + mixed_real * coefficient_imag; - } - } - } - - for (std::size_t band = 0u; band < bands; ++band) { - double left_real = 0.0; - double left_imag = 0.0; - double right_real = 0.0; - double right_imag = 0.0; - for (int lane = 0; lane < 4; ++lane) { - const std::size_t cell = band * 4u + static_cast(lane); - const double real = tap_real[cell] * output_tap_[cell] + extra_real[cell]; - const double imag = tap_imag[cell] * output_tap_[cell] + extra_imag[cell]; - left_real += left_real_[cell] * real - left_imag_[cell] * imag; - left_imag += left_imag_[cell] * real + left_real_[cell] * imag; - right_real += right_real_[cell] * real - right_imag_[cell] * imag; - right_imag += right_imag_[cell] * real + right_real_[cell] * imag; - } - output[band] = Complex(left_real, left_imag); - output[kHybridBands + band] = Complex(right_real, right_imag); - } - return Status::success(); - } - -private: - const RosellaModel& model_; - int bands_ = 0; - std::array delays_{}; - int capacity_ = 0; - std::vector matrix_; - std::vector feedback_real_; - std::vector feedback_imag_; - std::vector output_tap_; - std::vector left_real_; - std::vector left_imag_; - std::vector right_real_; - std::vector right_imag_; - std::vector allpass_gain_; - std::vector allpass_delay_; - std::vector> allpass_real_; - std::vector> allpass_imag_; - std::vector allpass_position_; - std::vector memory_real_; - std::vector memory_imag_; - int position_ = 0; - std::vector> extra_matrices_; -}; - -} // namespace - -RosellaRoomFir::RosellaRoomFir() = default; -RosellaRoomFir::~RosellaRoomFir() = default; - -Status RosellaRoomFir::configure(const RosellaModel& model, int impulse_slots) { - length_ = impulse_slots; - RoomState reference(model); - kernel_.assign(static_cast(length_) * 2u * kRoomBands, Complex(0.0, 0.0)); - Complex slot_output[2 * kHybridBands]; - for (int slot = 0; slot < length_; ++slot) { - Complex impulse[kHybridBands]; - for (int band = 0; band < kHybridBands; ++band) { - impulse[band] = Complex(slot == 0 && band < kRoomBands ? 1.0 : 0.0, 0.0); - } - const Status status = reference.process_slot(impulse, slot_output); - if (!status.ok()) { - return status; - } - for (int ear = 0; ear < 2; ++ear) { - for (int band = 0; band < kRoomBands; ++band) { - kernel_[(static_cast(slot) * 2u + static_cast(ear)) * - kRoomBands + - static_cast(band)] = - slot_output[ear * kHybridBands + band]; - } - } - } - tail_.assign(static_cast(length_ - 1) * 2u * kRoomBands, Complex(0.0, 0.0)); - valid_ = true; - return Status::success(); -} - -bool RosellaRoomFir::valid() const { return valid_; } - -void RosellaRoomFir::reset() { - std::fill(tail_.begin(), tail_.end(), Complex(0.0, 0.0)); - fft_cache_size_ = 0u; - forward_plan_.reset(); - inverse_plan_.reset(); -} - -// rosella_room.RosellaRoomFir.process_chunk. -Status RosellaRoomFir::process_chunk(const std::vector>& values, - std::size_t slots, - std::vector>* output) { - output->assign(slots * 2u * kHybridBands, Complex(0.0, 0.0)); - if (slots == 0u) { - return Status::success(); - } - const std::size_t needed = slots + static_cast(length_) - 1u; - std::size_t fft_size = 1u; - while (fft_size < needed) { - fft_size <<= 1u; - } - if (fft_size != fft_cache_size_) { - kernel_fft_.assign(fft_size * 2u * kRoomBands, Complex(0.0, 0.0)); - // The room transforms a fixed length for the whole chunk, so the radix-2 - // twiddle recurrences are materialised once here rather than re-derived - // inside every butterfly of every one of the 3 * kRoomBands transforms. - forward_plan_ = std::make_unique(fft_size, false); - inverse_plan_ = std::make_unique(fft_size, true); - line_.assign(fft_size, Complex(0.0, 0.0)); - for (int ear = 0; ear < 2; ++ear) { - for (int band = 0; band < kRoomBands; ++band) { - for (int slot = 0; slot < length_; ++slot) { - line_[static_cast(slot)] = - kernel_[(static_cast(slot) * 2u + - static_cast(ear)) * - kRoomBands + - static_cast(band)]; - } - std::fill(line_.begin() + length_, line_.end(), Complex(0.0, 0.0)); - dsp::fft_radix2(&line_, *forward_plan_); - for (std::size_t index = 0u; index < fft_size; ++index) { - // Band-major, so that the spectrum multiply below reads both - // of its operands as runs instead of striding through them - // one complex per cache line. Same values, same places. - kernel_fft_[(static_cast(ear) * kRoomBands + - static_cast(band)) * - fft_size + - index] = line_[index]; - } - } - } - fft_cache_size_ = fft_size; - } - // input_fft_ and block_ are indexed linearly and every entry of each is written - // before it is read (the per-band forward transform fills input_fft_ column by - // column, and the inverse transform fills block_ entry by entry), so their zero - // fills were dead. The line buffer, by contrast, is handed to fft_radix2, - // which transforms exactly data->size() entries -- it therefore has to keep the - // exact length and the exact initialisation it had as a local. - if (line_.size() != fft_size) { - line_.assign(fft_size, Complex(0.0, 0.0)); - } - const std::size_t input_fft_size = fft_size * kRoomBands; - if (input_fft_.size() < input_fft_size) { - input_fft_.resize(input_fft_size); - } - for (int band = 0; band < kRoomBands; ++band) { - for (std::size_t slot = 0u; slot < slots; ++slot) { - line_[slot] = values[slot * kHybridBands + static_cast(band)]; - } - std::fill(line_.begin() + static_cast(slots), line_.end(), - Complex(0.0, 0.0)); - dsp::fft_radix2(&line_, *forward_plan_); - for (std::size_t index = 0u; index < fft_size; ++index) { - // Band-major, matching kernel_fft_, so that the spectrum multiply - // reads both operands as runs. - input_fft_[static_cast(band) * fft_size + index] = line_[index]; - } - } - const std::size_t block_size = needed * 2u * kRoomBands; - if (block_.size() < block_size) { - block_.resize(block_size); - } - for (int ear = 0; ear < 2; ++ear) { - for (int band = 0; band < kRoomBands; ++band) { - // Both planes are band-major now, so this is one contiguous complex - // product per (ear, band) and the dispatched kernel puts neighbouring - // complexes in its lanes; each product keeps the caller's four - // multiplies and two roundings. - simd::complex_multiply( - reinterpret_cast(line_.data()), - reinterpret_cast( - input_fft_.data() + static_cast(band) * fft_size), - reinterpret_cast( - kernel_fft_.data() + - (static_cast(ear) * kRoomBands + - static_cast(band)) * - fft_size), - fft_size); - dsp::fft_radix2(&line_, *inverse_plan_); - for (std::size_t slot = 0u; slot < needed; ++slot) { - block_[(slot * 2u + static_cast(ear)) * kRoomBands + - static_cast(band)] = line_[slot]; - } - } - } - const std::size_t tail_length = static_cast(length_ - 1); - for (std::size_t index = 0u; index < tail_length * 2u * kRoomBands; ++index) { - block_[index] += tail_[index]; - } - for (std::size_t slot = 0u; slot < slots; ++slot) { - for (int ear = 0; ear < 2; ++ear) { - for (int band = 0; band < kRoomBands; ++band) { - (*output)[slot * 2u * kHybridBands + static_cast(ear) * kHybridBands + - static_cast(band)] = - block_[(slot * 2u + static_cast(ear)) * kRoomBands + - static_cast(band)]; - } - } - } - for (std::size_t index = 0u; index < tail_length * 2u * kRoomBands; ++index) { - tail_[index] = block_[slots * 2u * kRoomBands + index]; - } - return Status::success(); -} - -} // namespace joc::hrtf diff --git a/src/hrtf/rosella_reference.h b/src/hrtf/rosella_reference.h deleted file mode 100644 index d1e2c02..0000000 --- a/src/hrtf/rosella_reference.h +++ /dev/null @@ -1,107 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "foundation/status.h" -#include "hrtf/rosella_model.h" - -// One of the room's transforms is a radix-2 FFT plan, so the type is named here and -// kept out of the interface. -namespace joc::dsp { -class FftPlan; -} // namespace joc::dsp - -// The reference arithmetic of the Rosella ".personalized_headphone" renderer -// (rosella_model.py, rosella_direct.py and rosella_room.py): the direction basis and -// the padded lane grid, the per-source direct gains and room send, and the recursive -// table-A room model. rosella_renderer.cpp drives these through RosellaRuntime; a -// renderer built on another field format can call them directly and get the same -// samples, so the operation order and the literals in the definitions are part of -// the interface. -namespace joc::hrtf { - -// rosella_direct._profile_geometry: a virtual position resolved on one distance -// profile's grid, as the direction of the direct path plus the radius factors the -// gain weights are scaled by. -struct ProfileGeometry { - double direction[3] = {1.0, 0.0, 0.0}; - double radius = 0.0; - double clamped = 0.0; - double alpha = 0.0; -}; - -// Quantises `position` onto the profile's metadata grid, maps it through the -// profile's axis scales and clamps it to the profile bounds; `out` takes the result. -Status profile_geometry(const RosellaModel& model, const double position[3], int profile_index, - ProfileGeometry* out); - -// rosella_model.direction_basis: the observed 36-term basis of one unit vector. -void direction_basis(double x, double y, double z, double out[36]); - -// rosella_direct._logical_field: the padded lane grid as [77][36][2] float64. -std::vector rosella_logical_field(const std::vector& padded); - -// One source's direct-path gains and room send, plus the radii and the interaural -// delay the caller reports. `delayed_ear` is -1 when neither ear is delayed, -// otherwise it is the ear (0 = left, 1 = right) whose phase carries -// `delay_samples`. -struct DirectResult { - std::complex gains[2][77] = {}; - double room_send = 0.0; - double physical_radius_m = 0.0; - double normalized_radius = 0.0; - double clamped_radius = 0.0; - double delay_samples = 0.0; - int delayed_ear = -1; -}; - -// rosella_direct.special_lfe_direct: the response a special (LFE) source is -// rendered with, built once. -const DirectResult& special_lfe_direct(); - -// rosella_direct.direct_and_room_send: the direct gains and the room send of the -// position `position` on profile `profile_index`, read through the logical field -// grids of `field_left`/`field_right`. -Status direct_and_room_send(const RosellaModel& model, const std::vector& field_left, - const std::vector& field_right, const double position[3], - int profile_index, DirectResult* out); - -// rosella_room.RosellaRoomFir: the recursive table-A room model, its room FIR and the -// overlap-add convolution that applies the FIR in the hybrid band domain. State is -// per instance and not thread-safe. -class RosellaRoomFir { -public: - RosellaRoomFir(); - ~RosellaRoomFir(); - RosellaRoomFir(const RosellaRoomFir&) = delete; - RosellaRoomFir& operator=(const RosellaRoomFir&) = delete; - - // Builds the room impulse response from `model` over `impulse_slots` slots. The - // room can only be processed once this succeeds; the alternate table-A mode is - // rejected here, as the reference rejects it. - Status configure(const RosellaModel& model, int impulse_slots); - // `values` is [slots][2][77], `output` is [slots][2][77] and stays zero outside - // the room bands. - Status process_chunk(const std::vector>& values, std::size_t slots, - std::vector>* output); - void reset(); - bool valid() const; - -private: - int length_ = 0; - bool valid_ = false; - std::vector> kernel_; - std::vector> tail_; - std::vector> kernel_fft_; - std::size_t fft_cache_size_ = 0u; - std::vector> line_; // scratch, exactly fft_size entries - std::vector> input_fft_; // scratch, [fft_size][64], fully written - std::vector> block_; // scratch, [needed][2][64], fully written - std::unique_ptr forward_plan_; - std::unique_ptr inverse_plan_; -}; - -} // namespace joc::hrtf diff --git a/src/hrtf/rosella_renderer.cpp b/src/hrtf/rosella_renderer.cpp index a78f3ca..31f9462 100644 --- a/src/hrtf/rosella_renderer.cpp +++ b/src/hrtf/rosella_renderer.cpp @@ -1,14 +1,18 @@ #include "hrtf/rosella_renderer.h" +#include "simd/simd.h" + #include +#include #include #include +#include #include #include #include +#include "foundation/fft.h" #include "hrtf/rosella_bank.h" -#include "hrtf/rosella_reference.h" namespace joc::hrtf { @@ -16,14 +20,850 @@ namespace { constexpr int kSourceChannels = 16; constexpr int kOutputChannels = 2; +constexpr int kDirectionTerms = 36; constexpr int kBlockSamples = 512; constexpr int kFrameSamples = 1536; +constexpr int kRoomBands = 64; constexpr double kPi = 3.14159265358979323846; +constexpr double kRoomInputGain = 0.70710677; +constexpr double kCentreEqual = 0.9998489618301392; +constexpr double kCentreAlternate = 0.7070000171661377; + +// The fixed sixteen-band low-pass a special (LFE) source is rendered through; the +// constants are the float32 bit patterns of rosella_direct._SPECIAL_LFE_LOW_16. +constexpr std::uint32_t kSpecialLfeLowBits[16] = { + 0x402695EAu, 0x3FE75979u, 0x3F28CAAAu, 0xBCE1FB2Eu, 0xBDD8AF65u, 0xBD8F426Eu, + 0x3D996821u, 0xBC16B3A0u, 0x3B64BAF1u, 0xBC81ECFDu, 0xBA3D892Fu, 0x3AF6A9F0u, + 0xB9DD1C5Fu, 0x380A193Fu, 0x38052059u, 0x351BCB34u}; Status render_fail(joc_error code, const std::string& message) { return Status::fail(code, stage::kRender, message); } +std::vector special_lfe_low() { + std::vector values(kHybridBands, 0.0); + for (int index = 0; index < 16; ++index) { + float narrowed = 0.0f; + const std::uint32_t bits = kSpecialLfeLowBits[index]; + std::memcpy(&narrowed, &bits, sizeof(float)); + values[static_cast(index)] = static_cast(narrowed); + } + return values; +} + +// rosella_model.direction_basis: the observed 36-term basis. The operation order is +// part of the model, so the intermediates are named after the reference's. +void direction_basis(double x, double y, double z, double* out) { + const double yz = y * z; + const double x2 = x * x; + const double y2 = y * y; + const double x2m02 = x2 - 0.2; + const double xy = x * y; + out[0] = 1.0; + out[1] = x; + out[2] = y; + out[3] = z; + out[4] = x2 - (1.0 / 3.0); + out[5] = xy; + out[6] = x * z; + out[7] = y2 - (1.0 / 3.0); + out[8] = yz; + out[9] = (x2 - 0.6) * x; + out[10] = x2m02 * y; + out[11] = x2m02 * z; + out[12] = (y2 - 0.2) * x; + out[13] = yz * x; + out[14] = (y2 - 0.6) * y; + out[15] = (y2 - 0.2) * z; + out[16] = x2 * x2 - 0.2; + out[17] = xy * x2; + out[18] = (x * z) * x2; + out[19] = y2 * x2 - (1.0 / 15.0); + out[20] = yz * x2; + out[21] = x * y2 * y; + out[22] = x * y2 * z; + out[23] = y2 * y2 - 0.2; + const double x4 = x2 * x2; + const double x2y2 = y2 * x2; + const double y4 = y2 * y2; + out[24] = yz * y2; + out[25] = (x4 - (3.0 / 7.0)) * x; + out[26] = (x4 - (3.0 / 35.0)) * y; + out[27] = (x4 - (3.0 / 35.0)) * z; + out[28] = (x2y2 - (3.0 / 35.0)) * x; + out[29] = (x2 * z) * xy; + out[30] = (x2y2 - (3.0 / 35.0)) * y; + out[31] = (x2y2 - (1.0 / 35.0)) * z; + out[32] = (y4 - (3.0 / 35.0)) * x; + out[33] = (y2 * z) * xy; + out[34] = (y4 - (3.0 / 7.0)) * y; + out[35] = (y4 - (3.0 / 35.0)) * z; +} + +// rosella_direct._logical_field: the padded lane grid as [77][36][2] float64. +void logical_field(const std::vector& padded, std::vector* out) { + out->assign(static_cast(kHybridBands) * kDirectionTerms * 2u, 0.0); + for (int band = 0; band < kHybridBands; ++band) { + const int block = band / 4; + const int lane = band % 4; + for (int term = 0; term < kDirectionTerms; ++term) { + for (int component = 0; component < 2; ++component) { + const std::size_t source = + static_cast(lane + 4 * (term * 2 + component + 72 * block)); + (*out)[(static_cast(band) * kDirectionTerms + + static_cast(term)) * 2u + + static_cast(component)] = + source < padded.size() ? static_cast(padded[source]) : 0.0; + } + } + } +} + +// rosella_direct._round_away_from_zero. +double round_away_from_zero(double value) { + return value >= 0.0 ? std::floor(value + 0.5) : std::ceil(value - 0.5); +} + +// rosella_direct._q15_position: ADM coordinates on the Rosella metadata grid. +void q15_position(const double position[3], int encoded[3]) { + const double raw[3] = { + std::min(std::max((position[0] + 1.0) * 0.5, 0.0), 1.0), + std::min(std::max((1.0 - position[1]) * 0.5, 0.0), 1.0), + std::min(std::max(position[2], -1.0), 1.0), + }; + for (int axis = 0; axis < 3; ++axis) { + encoded[axis] = static_cast( + std::min(round_away_from_zero(raw[axis] * 32768.0), 32767.0)); + } +} + +struct ProfileGeometry { + double direction[3] = {1.0, 0.0, 0.0}; + double radius = 0.0; + double clamped = 0.0; + double alpha = 0.0; +}; + +// rosella_direct._profile_geometry. +ProfileGeometry profile_geometry(const RosellaModel& model, const double position[3], + int profile_index) { + const RosellaDistanceProfile& profile = model.profiles[static_cast(profile_index)]; + int encoded[3] = {0, 0, 0}; + q15_position(position, encoded); + const double q_front = 1.0 - 2.0 * static_cast(encoded[1]) / 32768.0; + const double q_x = 2.0 * static_cast(encoded[0]) / 32768.0 - 1.0; + const double q_vertical = static_cast(encoded[2]) / 32768.0; + double mapped_front = q_front; + double mapped_lateral = -q_x; + double mapped_vertical = q_vertical; + if (model.header_integer_fields[0] != 0) { + if (q_x == 0.0 && q_front == 0.0) { + mapped_front = 0.0; + mapped_lateral = 0.0; + mapped_vertical = q_vertical; + } else { + const double horizontal_max = std::max(std::abs(q_x), std::abs(q_front)); + const double horizontal_norm = (q_x / horizontal_max) * (q_x / horizontal_max) + + (q_front / horizontal_max) * (q_front / horizontal_max); + double vertical_norm = 1.0; + if (q_vertical != 0.0) { + const double smaller = std::min(std::abs(q_vertical), horizontal_max); + const double larger = std::max(std::abs(q_vertical), horizontal_max); + vertical_norm = 1.0 + (smaller / larger) * (smaller / larger); + } + const double horizontal_factor = 1.0 / std::sqrt(horizontal_norm * vertical_norm); + const double vertical_factor = 1.0 / std::sqrt(vertical_norm); + mapped_front = q_front * horizontal_factor; + mapped_lateral = -q_x * horizontal_factor; + mapped_vertical = q_vertical * vertical_factor; + } + } + double scaled[3] = {mapped_front * static_cast(profile.axis_scales_internal[2]), + mapped_lateral * static_cast(profile.axis_scales_internal[0]), + mapped_vertical * static_cast(profile.axis_scales_internal[1])}; + double ray = 1.0; + for (int axis = 0; axis < 3; ++axis) { + const double value = scaled[axis]; + const double lower = static_cast(profile.bounds[static_cast(axis) * 2u]); + const double upper = + static_cast(profile.bounds[static_cast(axis) * 2u + 1u]); + if (value < lower) { + ray = std::min(ray, lower / value); + } else if (value > upper) { + ray = std::min(ray, upper / value); + } + } + if (ray < 1.0) { + scaled[0] *= ray; + scaled[1] *= ray; + scaled[2] *= ray; + } + ProfileGeometry result; + result.radius = std::sqrt(scaled[0] * scaled[0] + scaled[1] * scaled[1] + + scaled[2] * scaled[2]); + result.clamped = std::max(result.radius, static_cast(profile.minimum_normalized_radius)); + result.alpha = result.radius / result.clamped; + if (result.radius > 1.0e-30) { + for (int axis = 0; axis < 3; ++axis) { + result.direction[axis] = scaled[axis] / result.radius; + } + } + return result; +} + +struct EarGeometry { + double basis_minus[kDirectionTerms] = {}; + double basis_plus[kDirectionTerms] = {}; + double path_minus = 0.0; + double path_plus = 0.0; +}; + +// rosella_direct._ear_geometry. +EarGeometry ear_geometry(const RosellaModel& model, const RosellaDistanceProfile& profile, + const double direction[3], double clamped, double offset, + double correction) { + const double x = direction[0]; + const double y = direction[1]; + const double z = direction[2]; + const double inverse_distance = static_cast(profile.inverse_distance_per_m); + const double ear = offset * inverse_distance / clamped; + const double y_minus = y - ear; + const double y_plus = y + ear; + const double common = x * x + z * z; + const double length_minus = std::sqrt(y_minus * y_minus + common); + const double length_plus = std::sqrt(y_plus * y_plus + common); + EarGeometry result; + direction_basis(x / length_minus, y_minus / length_minus, z / length_minus, + result.basis_minus); + direction_basis(x / length_plus, y_plus / length_plus, z / length_plus, result.basis_plus); + result.path_minus = length_minus * clamped; + result.path_plus = length_plus * clamped; + if (correction != 0.0) { + const double multiplier = 2.0 * correction * inverse_distance; + double left = 0.0; + double right = 0.0; + for (int term = 0; term < kDirectionTerms; ++term) { + left += static_cast(model.vector_left[static_cast(term)]) * + result.basis_minus[term]; + right += static_cast(model.vector_right[static_cast(term)]) * + result.basis_plus[term]; + } + result.path_minus += std::max(left, 0.0) * multiplier; + result.path_plus += std::max(right, 0.0) * multiplier; + } + return result; +} + +// rosella_direct._phase_groups. +void phase_groups(const RosellaModel& model, double delay_samples, Complex* out) { + // The reference starts from np.ones(77) and only rewrites the flagged bands. + std::fill(out, out + kHybridBands, Complex(1.0, 0.0)); + Complex current(1.0, 0.0); + Complex step(1.0, 0.0); + std::size_t value_index = 0u; + for (std::size_t band = 0u; band < model.hybrid_flags.size() && band < kHybridBands; ++band) { + const int flag = model.hybrid_flags[band]; + if (flag != 2) { + if (flag == 1) { + const double angle = + static_cast(model.hybrid_values[value_index]) * delay_samples; + ++value_index; + step = Complex(std::cos(angle), std::sin(angle)); + } + current *= step; + } + out[band] = current; + } +} + +struct DirectResult { + Complex gains[2][kHybridBands] = {}; + double room_send = 0.0; + double physical_radius_m = 0.0; + double normalized_radius = 0.0; + double clamped_radius = 0.0; + double delay_samples = 0.0; + int delayed_ear = -1; +}; + +// rosella_direct.special_lfe_direct. +const DirectResult& special_lfe_direct() { + static const DirectResult result = [] { + DirectResult direct; + const std::vector low = special_lfe_low(); + for (int ear = 0; ear < 2; ++ear) { + for (int band = 0; band < kHybridBands; ++band) { + direct.gains[ear][band] = Complex(low[static_cast(band)], 0.0); + } + } + return direct; + }(); + return result; +} + +// rosella_direct.direct_and_room_send. +DirectResult direct_and_room_send(const RosellaModel& model, + const std::vector& field_left, + const std::vector& field_right, const double position[3], + int profile_index) { + const RosellaDistanceProfile& profile = + model.profiles[static_cast(profile_index)]; + const ProfileGeometry geometry = profile_geometry(model, position, profile_index); + + const EarGeometry delay_ears = + ear_geometry(model, profile, geometry.direction, geometry.clamped, + static_cast(model.model_scalars[1]), + static_cast(model.model_scalars[2])); + const double delay = std::abs(delay_ears.path_plus - delay_ears.path_minus) * + static_cast(profile.distance_scale_m) * + (static_cast(model.sample_rate) / 343.3) * geometry.alpha; + int delayed_ear = -1; + if (delay_ears.path_minus > delay_ears.path_plus) { + delayed_ear = 0; + } else if (delay_ears.path_plus > delay_ears.path_minus) { + delayed_ear = 1; + } + + const EarGeometry weight_ears = + ear_geometry(model, profile, geometry.direction, geometry.clamped, + static_cast(model.model_scalars[3]), + static_cast(model.model_scalars[4])); + const double weight_norm = + std::sqrt(weight_ears.path_minus * weight_ears.path_minus + + weight_ears.path_plus * weight_ears.path_plus); + const double weight_left = weight_ears.path_plus / weight_norm; + const double weight_right = weight_ears.path_minus / weight_norm; + + const double final_offset = static_cast(model.model_scalars[0]); + double basis_minus[kDirectionTerms] = {}; + double basis_plus[kDirectionTerms] = {}; + if (final_offset == 0.0) { + direction_basis(geometry.direction[0], geometry.direction[1], geometry.direction[2], + basis_minus); + std::copy(basis_minus, basis_minus + kDirectionTerms, basis_plus); + } else { + const double x = geometry.direction[0]; + const double y = geometry.direction[1]; + const double z = geometry.direction[2]; + const double ear = + final_offset * static_cast(profile.inverse_distance_per_m) / geometry.clamped; + const double y_minus = y - ear; + const double y_plus = y + ear; + const double common_length = x * x + z * z; + const double length_minus = std::sqrt(y_minus * y_minus + common_length); + const double length_plus = std::sqrt(y_plus * y_plus + common_length); + direction_basis(x / length_minus, y_minus / length_minus, z / length_minus, basis_minus); + direction_basis(x / length_plus, y_plus / length_plus, z / length_plus, basis_plus); + } + + DirectResult result; + Complex left[kHybridBands] = {}; + Complex right[kHybridBands] = {}; + for (int band = 0; band < kHybridBands; ++band) { + double left_real = 0.0; + double left_imag = 0.0; + double right_real = 0.0; + double right_imag = 0.0; + for (int term = 0; term < kDirectionTerms; ++term) { + const std::size_t index = + (static_cast(band) * kDirectionTerms + static_cast(term)) * + 2u; + left_real += field_left[index] * basis_minus[term]; + left_imag += field_left[index + 1u] * basis_minus[term]; + right_real += field_right[index] * basis_plus[term]; + right_imag += field_right[index + 1u] * basis_plus[term]; + } + left[band] = Complex(left_real, left_imag); + right[band] = Complex(right_real, right_imag); + } + if (delayed_ear >= 0) { + Complex phase[kHybridBands]; + phase_groups(model, delay, phase); + Complex* target = delayed_ear == 0 ? left : right; + for (int band = 0; band < kHybridBands; ++band) { + target[band] *= phase[band]; + } + } + + const double effective_radius = + geometry.radius * static_cast(model.header_float_scalars[0]) * + static_cast(profile.distance_scale_m); + double common = 1.0; + double room_send = 0.0; + if (profile_index == static_cast(RosellaProfile::Far) || + profile_index == static_cast(RosellaProfile::Mid)) { + common = 1.0 / std::sqrt(1.0 + static_cast(model.header_float_scalars[1]) * + effective_radius * effective_radius); + room_send = effective_radius * common; + } + + Complex left_term0[kHybridBands]; + Complex right_term0[kHybridBands]; + for (int band = 0; band < kHybridBands; ++band) { + const std::size_t index = static_cast(band) * kDirectionTerms * 2u; + left_term0[band] = Complex(field_left[index], field_left[index + 1u]); + right_term0[band] = Complex(field_right[index], field_right[index + 1u]); + } + const bool weights_are_default_equal = + static_cast(model.model_scalars[3]) == 0.0 && + static_cast(model.model_scalars[4]) == 0.0; + double centre_left = 0.0; + double centre_right = 0.0; + double right_direction_weight = weight_right; + if (weights_are_default_equal) { + centre_left = weight_left * (1.0 - geometry.alpha) * kCentreEqual; + centre_right = centre_left; + right_direction_weight = weight_left; + } else { + centre_left = (1.0 - geometry.alpha) * kCentreAlternate; + centre_right = centre_left; + } + for (int band = 0; band < kHybridBands; ++band) { + result.gains[0][band] = + common * (left[band] * (weight_left * geometry.alpha) + left_term0[band] * centre_left); + result.gains[1][band] = common * (right[band] * (right_direction_weight * geometry.alpha) + + right_term0[band] * centre_right); + } + result.room_send = room_send; + result.physical_radius_m = static_cast(profile.distance_scale_m) * geometry.radius; + result.normalized_radius = geometry.radius; + result.clamped_radius = geometry.clamped; + result.delay_samples = delay; + result.delayed_ear = delayed_ear; + return result; +} + +// rosella_room._RosellaRoomState: the recursive table-A room model. +class RoomState { +public: + explicit RoomState(const RosellaModel& model) : model_(model) { + bands_ = std::min(64, model.table_a_dimension); + delays_ = model.table_a_four_integers; + capacity_ = 0; + for (const int delay : delays_) { + capacity_ = std::max(capacity_, delay); + } + // The vectors are stored column-major (numpy's order="F"). + matrix_.assign(16u, 0.0); + for (int row = 0; row < 4; ++row) { + for (int column = 0; column < 4; ++column) { + matrix_[static_cast(row) + 4u * static_cast(column)] = + static_cast(model.table_a_vector16[static_cast(row) + + 4u * static_cast(column)]); + } + } + const std::vector& f8 = model.table_a_filter_8x64_padded; + const std::vector& f4 = model.table_a_filter_4x64_padded; + const std::vector& f16 = model.table_a_filter_16x64_padded; + feedback_real_.assign(static_cast(bands_) * 4u, 0.0); + feedback_imag_.assign(static_cast(bands_) * 4u, 0.0); + output_tap_.assign(static_cast(bands_) * 4u, 0.0); + left_real_.assign(static_cast(bands_) * 4u, 0.0); + left_imag_.assign(static_cast(bands_) * 4u, 0.0); + right_real_.assign(static_cast(bands_) * 4u, 0.0); + right_imag_.assign(static_cast(bands_) * 4u, 0.0); + for (int band = 0; band < bands_; ++band) { + const int group = band / 4; + const int lane = band % 4; + for (int tap = 0; tap < 4; ++tap) { + const std::size_t target = static_cast(band) * 4u + + static_cast(tap); + const std::size_t g8 = ((static_cast(group) * 4u + + static_cast(tap)) * 2u) * + 4u + + static_cast(lane); + feedback_real_[target] = static_cast(f8[g8]); + feedback_imag_[target] = static_cast(f8[g8 + 4u]); + output_tap_[target] = static_cast( + f4[(static_cast(group) * 4u + static_cast(tap)) * 4u + + static_cast(lane)]); + const std::size_t g16 = ((static_cast(group) * 4u + + static_cast(tap)) * 4u) * + 4u; + left_real_[target] = static_cast(f16[g16 + static_cast(lane)]); + left_imag_[target] = + static_cast(f16[g16 + 4u + static_cast(lane)]); + right_real_[target] = + static_cast(f16[g16 + 8u + static_cast(lane)]); + right_imag_[target] = + static_cast(f16[g16 + 12u + static_cast(lane)]); + } + } + allpass_gain_.resize(model.table_a_option_values.size()); + for (std::size_t index = 0u; index < model.table_a_option_values.size(); ++index) { + allpass_gain_[index] = static_cast(model.table_a_option_values[index]); + } + allpass_delay_ = model.table_a_option_ids; + for (const int delay : allpass_delay_) { + allpass_real_.emplace_back(static_cast(delay) * + static_cast(bands_), + 0.0); + allpass_imag_.emplace_back(static_cast(delay) * + static_cast(bands_), + 0.0); + } + allpass_position_.assign(allpass_real_.size(), 0); + memory_real_.assign(static_cast(capacity_) * static_cast(bands_) * 4u, + 0.0); + memory_imag_.assign(memory_real_.size(), 0.0); + extra_matrices_.resize(model.table_a_extra_indices.size()); + for (std::size_t index = 0u; index < extra_matrices_.size(); ++index) { + extra_matrices_[index].assign(16u, 0.0); + for (int row = 0; row < 4; ++row) { + for (int column = 0; column < 4; ++column) { + extra_matrices_[index][static_cast(row) + + 4u * static_cast(column)] = + static_cast( + model.table_a_extra_vectors[index * 16u + static_cast(row) + + 4u * static_cast(column)]); + } + } + } + } + + void reset() { + for (std::vector& value : allpass_real_) { + std::fill(value.begin(), value.end(), 0.0); + } + for (std::vector& value : allpass_imag_) { + std::fill(value.begin(), value.end(), 0.0); + } + std::fill(allpass_position_.begin(), allpass_position_.end(), 0); + std::fill(memory_real_.begin(), memory_real_.end(), 0.0); + std::fill(memory_imag_.begin(), memory_imag_.end(), 0.0); + position_ = 0; + } + + Status process_slot(const Complex* room_send, Complex* output) { + if (static_cast(model_.table_a_scalar) >= 0.5) { + return render_fail(JOC_ERR_NOT_SUPPORTED, "alternate Rosella table-A room mode"); + } + const std::size_t bands = static_cast(bands_); + std::vector input_real(bands, 0.0); + std::vector input_imag(bands, 0.0); + for (std::size_t band = 0u; band < bands; ++band) { + input_real[band] = room_send[band].real() * kRoomInputGain; + input_imag[band] = room_send[band].imag() * kRoomInputGain; + } + for (std::size_t index = 0u; index < allpass_gain_.size(); ++index) { + const std::size_t delay = static_cast(allpass_delay_[index]); + const std::size_t position = static_cast(allpass_position_[index]); + const double gain = allpass_gain_[index]; + for (std::size_t band = 0u; band < bands; ++band) { + const std::size_t cell = position * bands + band; + const double previous_real = allpass_real_[index][cell]; + const double previous_imag = allpass_imag_[index][cell]; + const double residual_real = input_real[band] - previous_real * gain; + const double residual_imag = input_imag[band] - previous_imag * gain; + input_real[band] = residual_real * gain + previous_real; + input_imag[band] = residual_imag * gain + previous_imag; + allpass_real_[index][cell] = residual_real; + allpass_imag_[index][cell] = residual_imag; + } + allpass_position_[index] = static_cast((position + 1u) % delay); + } + + std::vector branch_real(bands * 4u, 0.0); + std::vector branch_imag(bands * 4u, 0.0); + std::vector delayed_real(bands * 4u, 0.0); + std::vector delayed_imag(bands * 4u, 0.0); + for (int branch = 0; branch < 4; ++branch) { + const std::size_t slot = + static_cast((position_ - delays_[static_cast(branch)] + + capacity_) % + capacity_); + for (std::size_t band = 0u; band < bands; ++band) { + const std::size_t source = (slot * bands + band) * 4u + static_cast(branch); + delayed_real[band * 4u + static_cast(branch)] = memory_real_[source]; + delayed_imag[band * 4u + static_cast(branch)] = memory_imag_[source]; + } + } + for (std::size_t band = 0u; band < bands; ++band) { + for (int row = 0; row < 4; ++row) { + double real = input_real[band]; + double imag = input_imag[band]; + for (int column = 0; column < 4; ++column) { + const double coefficient = + matrix_[static_cast(row) + 4u * static_cast(column)]; + real += delayed_real[band * 4u + static_cast(column)] * coefficient; + imag += delayed_imag[band * 4u + static_cast(column)] * coefficient; + } + branch_real[band * 4u + static_cast(row)] = real; + branch_imag[band * 4u + static_cast(row)] = imag; + } + } + + const std::size_t tap_slot = static_cast( + (position_ - model_.table_a_integer + capacity_) % capacity_); + std::vector tap_real(bands * 4u, 0.0); + std::vector tap_imag(bands * 4u, 0.0); + for (std::size_t band = 0u; band < bands; ++band) { + for (int lane = 0; lane < 4; ++lane) { + const std::size_t source = (tap_slot * bands + band) * 4u + static_cast(lane); + tap_real[band * 4u + static_cast(lane)] = memory_real_[source]; + tap_imag[band * 4u + static_cast(lane)] = memory_imag_[source]; + } + } + for (std::size_t cell = 0u; cell < branch_real.size(); ++cell) { + const double real = branch_real[cell]; + const double imag = branch_imag[cell]; + memory_real_[(static_cast(position_) * bands) * 4u + cell] = + real * feedback_real_[cell] - imag * feedback_imag_[cell]; + memory_imag_[(static_cast(position_) * bands) * 4u + cell] = + imag * feedback_real_[cell] + real * feedback_imag_[cell]; + } + position_ = (position_ + 1) % capacity_; + + std::vector extra_real(bands * 4u, 0.0); + std::vector extra_imag(bands * 4u, 0.0); + for (std::size_t index = 0u; index < model_.table_a_extra_indices.size(); ++index) { + const std::size_t delay = + static_cast(model_.table_a_extra_indices[index]); + const std::size_t slot = static_cast( + (position_ - static_cast(delay) - 1 + capacity_ * 2) % capacity_); + for (std::size_t band = 0u; band < bands; ++band) { + for (int row = 0; row < 4; ++row) { + double mixed_real = 0.0; + double mixed_imag = 0.0; + for (int column = 0; column < 4; ++column) { + const std::size_t source = + (slot * bands + band) * 4u + static_cast(column); + const double coefficient = + extra_matrices_[index][static_cast(row) + + 4u * static_cast(column)]; + mixed_real += memory_real_[source] * coefficient; + mixed_imag += memory_imag_[source] * coefficient; + } + const int group = static_cast(band) / 4; + const int lane = static_cast(band) % 4; + const std::size_t field = + (index * 20u + static_cast(group)) * 2u * 4u; + const double coefficient_real = static_cast( + model_.table_a_extra_fields_padded[field + static_cast(lane)]); + const double coefficient_imag = static_cast( + model_.table_a_extra_fields_padded[field + 4u + static_cast(lane)]); + const std::size_t target = band * 4u + static_cast(row); + extra_real[target] += + mixed_real * coefficient_real - mixed_imag * coefficient_imag; + extra_imag[target] += + mixed_imag * coefficient_real + mixed_real * coefficient_imag; + } + } + } + + for (std::size_t band = 0u; band < bands; ++band) { + double left_real = 0.0; + double left_imag = 0.0; + double right_real = 0.0; + double right_imag = 0.0; + for (int lane = 0; lane < 4; ++lane) { + const std::size_t cell = band * 4u + static_cast(lane); + const double real = tap_real[cell] * output_tap_[cell] + extra_real[cell]; + const double imag = tap_imag[cell] * output_tap_[cell] + extra_imag[cell]; + left_real += left_real_[cell] * real - left_imag_[cell] * imag; + left_imag += left_imag_[cell] * real + left_real_[cell] * imag; + right_real += right_real_[cell] * real - right_imag_[cell] * imag; + right_imag += right_imag_[cell] * real + right_real_[cell] * imag; + } + output[band] = Complex(left_real, left_imag); + output[kHybridBands + band] = Complex(right_real, right_imag); + } + return Status::success(); + } + +private: + const RosellaModel& model_; + int bands_ = 0; + std::array delays_{}; + int capacity_ = 0; + std::vector matrix_; + std::vector feedback_real_; + std::vector feedback_imag_; + std::vector output_tap_; + std::vector left_real_; + std::vector left_imag_; + std::vector right_real_; + std::vector right_imag_; + std::vector allpass_gain_; + std::vector allpass_delay_; + std::vector> allpass_real_; + std::vector> allpass_imag_; + std::vector allpass_position_; + std::vector memory_real_; + std::vector memory_imag_; + int position_ = 0; + std::vector> extra_matrices_; +}; + +// rosella_room.RosellaRoomFir: the room FIR plus its overlap-add convolution. +class RoomFir { +public: + RoomFir(const RosellaModel& model, int impulse_slots) : length_(impulse_slots) { + RoomState reference(model); + kernel_.assign(static_cast(length_) * 2u * kRoomBands, Complex(0.0, 0.0)); + Complex slot_output[2 * kHybridBands]; + for (int slot = 0; slot < length_; ++slot) { + Complex impulse[kHybridBands]; + for (int band = 0; band < kHybridBands; ++band) { + impulse[band] = Complex(slot == 0 && band < kRoomBands ? 1.0 : 0.0, 0.0); + } + const Status status = reference.process_slot(impulse, slot_output); + if (!status.ok()) { + return; + } + for (int ear = 0; ear < 2; ++ear) { + for (int band = 0; band < kRoomBands; ++band) { + kernel_[(static_cast(slot) * 2u + static_cast(ear)) * + kRoomBands + + static_cast(band)] = + slot_output[ear * kHybridBands + band]; + } + } + } + tail_.assign(static_cast(length_ - 1) * 2u * kRoomBands, Complex(0.0, 0.0)); + valid_ = true; + } + + bool valid() const { return valid_; } + + void reset() { + std::fill(tail_.begin(), tail_.end(), Complex(0.0, 0.0)); + fft_cache_size_ = 0u; + forward_plan_.reset(); + inverse_plan_.reset(); + } + + // rosella_room.RosellaRoomFir.process_chunk. + Status process_chunk(const std::vector& values, std::size_t slots, + std::vector* output) { + output->assign(slots * 2u * kHybridBands, Complex(0.0, 0.0)); + if (slots == 0u) { + return Status::success(); + } + const std::size_t needed = slots + static_cast(length_) - 1u; + std::size_t fft_size = 1u; + while (fft_size < needed) { + fft_size <<= 1u; + } + if (fft_size != fft_cache_size_) { + kernel_fft_.assign(fft_size * 2u * kRoomBands, Complex(0.0, 0.0)); + // The room transforms a fixed length for the whole chunk, so the radix-2 + // twiddle recurrences are materialised once here rather than re-derived + // inside every butterfly of every one of the 3 * kRoomBands transforms. + forward_plan_ = std::make_unique(fft_size, false); + inverse_plan_ = std::make_unique(fft_size, true); + line_.assign(fft_size, Complex(0.0, 0.0)); + for (int ear = 0; ear < 2; ++ear) { + for (int band = 0; band < kRoomBands; ++band) { + for (int slot = 0; slot < length_; ++slot) { + line_[static_cast(slot)] = + kernel_[(static_cast(slot) * 2u + + static_cast(ear)) * + kRoomBands + + static_cast(band)]; + } + std::fill(line_.begin() + length_, line_.end(), Complex(0.0, 0.0)); + dsp::fft_radix2(&line_, *forward_plan_); + for (std::size_t index = 0u; index < fft_size; ++index) { + // Band-major, so that the spectrum multiply below reads both + // of its operands as runs instead of striding through them + // one complex per cache line. Same values, same places. + kernel_fft_[(static_cast(ear) * kRoomBands + + static_cast(band)) * + fft_size + + index] = line_[index]; + } + } + } + fft_cache_size_ = fft_size; + } + // input_fft_ and block_ are indexed linearly and every entry of each is written + // before it is read (the per-band forward transform fills input_fft_ column by + // column, and the inverse transform fills block_ entry by entry), so their zero + // fills were dead. The line buffer, by contrast, is handed to fft_radix2, + // which transforms exactly data->size() entries -- it therefore has to keep the + // exact length and the exact initialisation it had as a local. + if (line_.size() != fft_size) { + line_.assign(fft_size, Complex(0.0, 0.0)); + } + const std::size_t input_fft_size = fft_size * kRoomBands; + if (input_fft_.size() < input_fft_size) { + input_fft_.resize(input_fft_size); + } + for (int band = 0; band < kRoomBands; ++band) { + for (std::size_t slot = 0u; slot < slots; ++slot) { + line_[slot] = values[slot * kHybridBands + static_cast(band)]; + } + std::fill(line_.begin() + static_cast(slots), line_.end(), + Complex(0.0, 0.0)); + dsp::fft_radix2(&line_, *forward_plan_); + for (std::size_t index = 0u; index < fft_size; ++index) { + // Band-major, matching kernel_fft_, so that the spectrum multiply + // reads both operands as runs. + input_fft_[static_cast(band) * fft_size + index] = line_[index]; + } + } + const std::size_t block_size = needed * 2u * kRoomBands; + if (block_.size() < block_size) { + block_.resize(block_size); + } + for (int ear = 0; ear < 2; ++ear) { + for (int band = 0; band < kRoomBands; ++band) { + // Both planes are band-major now, so this is one contiguous complex + // product per (ear, band) and the dispatched kernel puts neighbouring + // complexes in its lanes; each product keeps the caller's four + // multiplies and two roundings. + simd::complex_multiply( + reinterpret_cast(line_.data()), + reinterpret_cast( + input_fft_.data() + static_cast(band) * fft_size), + reinterpret_cast( + kernel_fft_.data() + + (static_cast(ear) * kRoomBands + + static_cast(band)) * + fft_size), + fft_size); + dsp::fft_radix2(&line_, *inverse_plan_); + for (std::size_t slot = 0u; slot < needed; ++slot) { + block_[(slot * 2u + static_cast(ear)) * kRoomBands + + static_cast(band)] = line_[slot]; + } + } + } + const std::size_t tail_length = static_cast(length_ - 1); + for (std::size_t index = 0u; index < tail_length * 2u * kRoomBands; ++index) { + block_[index] += tail_[index]; + } + for (std::size_t slot = 0u; slot < slots; ++slot) { + for (int ear = 0; ear < 2; ++ear) { + for (int band = 0; band < kRoomBands; ++band) { + (*output)[slot * 2u * kHybridBands + static_cast(ear) * kHybridBands + + static_cast(band)] = + block_[(slot * 2u + static_cast(ear)) * kRoomBands + + static_cast(band)]; + } + } + } + for (std::size_t index = 0u; index < tail_length * 2u * kRoomBands; ++index) { + tail_[index] = block_[slots * 2u * kRoomBands + index]; + } + return Status::success(); + } + +private: + int length_ = 0; + bool valid_ = false; + std::vector kernel_; + std::vector tail_; + std::vector kernel_fft_; + std::size_t fft_cache_size_ = 0u; + std::vector line_; // scratch, exactly fft_size entries + std::vector input_fft_; // scratch, [fft_size][kRoomBands], fully written + std::vector block_; // scratch, [needed][2][kRoomBands], fully written + std::unique_ptr forward_plan_; + std::unique_ptr inverse_plan_; +}; + // rosella_core.RosellaRenderer: per-source direct gains plus the room send. class Core { public: @@ -32,10 +872,9 @@ public: model_ = &model; field_left_ = &field_left; field_right_ = &field_right; - room_ = std::make_unique(); - const Status room_status = room_->configure(model, room_impulse_slots); - if (!room_status.ok()) { - return room_status; + room_ = std::make_unique(model, room_impulse_slots); + if (!room_->valid()) { + return render_fail(JOC_ERR_NOT_SUPPORTED, "alternate Rosella table-A room mode"); } gains_.assign(static_cast(kSourceChannels) * 2u * kHybridBands, Complex(0.0, 0.0)); @@ -69,11 +908,8 @@ public: if (special_lfe) { result = special_lfe_direct(); } else { - const Status status = direct_and_room_send(*model_, *field_left_, *field_right_, - position, effective_profile, &result); - if (!status.ok()) { - return status; - } + result = direct_and_room_send(*model_, *field_left_, *field_right_, position, + effective_profile); } for (int ear = 0; ear < 2; ++ear) { for (int band = 0; band < kHybridBands; ++band) { @@ -153,7 +989,7 @@ private: const RosellaModel* model_ = nullptr; const std::vector* field_left_ = nullptr; const std::vector* field_right_ = nullptr; - std::unique_ptr room_; + std::unique_ptr room_; std::vector gains_; std::vector room_sends_; std::vector keys_; @@ -244,8 +1080,8 @@ struct RosellaRuntime::Impl { static_cast(first_slot * kHybridBands)); } // The room runs once for the whole chunk, as the reference does. Its output - // keeps a zero fill of its own: only the first 64 of the 77 bands of each ear - // are written, and the caller adds the whole 77-band slot back into `rendered`. + // keeps a zero fill of its own: only the first kRoomBands of each ear are + // written, and the caller adds the whole 77-band slot back into `rendered`. Status status = core.room_process(room_sends_buffer_, slots, &room_out_); if (!status.ok()) { return status; @@ -360,8 +1196,8 @@ Status RosellaRuntime::open(const RosellaModel& model, const RosellaRenderOption } impl_->model = model; impl_->options = options; - impl_->field_left = rosella_logical_field(impl_->model.field_left_padded); - impl_->field_right = rosella_logical_field(impl_->model.field_right_padded); + logical_field(impl_->model.field_left_padded, &impl_->field_left); + logical_field(impl_->model.field_right_padded, &impl_->field_right); // The core and the room keep references, so they must point at this runtime's // own copy of the model rather than at the caller's. Status status = impl_->core.configure(impl_->model, impl_->field_left, impl_->field_right, @@ -507,7 +1343,7 @@ void RosellaRuntime::take_output(std::vector* out) { if (out == nullptr) { return; } - // Replace semantics, exactly like SofaBinauralRuntime::take_output: the caller's + // Replace semantics, exactly like JochrtfRuntime::take_output: the caller's // previous contents are discarded, and the internal buffer is emptied afterwards // because the swap leaves it holding whatever the caller had. out->swap(impl_->output); diff --git a/src/hrtf/sofa.cpp b/src/hrtf/sofa.cpp deleted file mode 100644 index c05c0ac..0000000 --- a/src/hrtf/sofa.cpp +++ /dev/null @@ -1,255 +0,0 @@ -#include "hrtf/sofa.h" - -#include -#include -#include -#include -#include -#include - -#include "foundation/fs_utf8.h" -#include "foundation/sha256.h" -#include "io/hdf5.h" - -namespace joc::hrtf { - -namespace { - -Status sofa_fail(joc_error code, const std::string& message) { - return Status::fail(code, stage::kRender, message); -} - -std::string format_number(double value) { - if (std::isfinite(value) && value == std::floor(value) && std::fabs(value) < 1.0e15) { - return std::to_string(static_cast(value)); - } - char buffer[32]; - std::snprintf(buffer, sizeof(buffer), "%.6g", value); - return std::string(buffer); -} - -// Every array is checked against the element count the convention prescribes, so -// a file whose shape disagrees with its metadata is rejected instead of silently -// producing a shifted impulse response. -Status read_doubles(const io::Hdf5File& file, const std::string& path, std::uint64_t expected, - std::vector* out) { - if (!file.has_dataset(path)) { - return sofa_fail(JOC_ERR_HRTF_FORMAT, "SOFA file has no " + path + " dataset"); - } - const Status status = file.read_dataset_double(path, out); - if (!status.ok()) { - return sofa_fail(JOC_ERR_HRTF_FORMAT, "SOFA dataset " + path + ": " + status.message()); - } - if (out->size() != expected) { - return sofa_fail(JOC_ERR_HRTF_FORMAT, - "SOFA dataset " + path + " holds " + std::to_string(out->size()) + - " values, expected " + std::to_string(expected)); - } - return Status::success(); -} - -Status read_text(const io::Hdf5File& file, const std::string& name, bool required, - std::string* out) { - io::Hdf5Attribute attribute; - const Status status = file.attribute("", name, &attribute); - if (!status.ok()) { - if (required) { - return sofa_fail(JOC_ERR_HRTF_FORMAT, - "SOFA file has no root attribute " + name + ": " + status.message()); - } - return Status::success(); - } - *out = attribute.text; - return Status::success(); -} - -// SHA-256 of the whole file: the compiled-cache key is derived from it, so the -// digest is taken over the exact bytes the parse consumed. -std::string file_digest(const std::string& path) { - std::ifstream stream = fs_utf8::open_input(path); - if (!stream.good()) { - return std::string(); - } - crypto::Sha256 hash; - std::vector buffer(1u << 20); - while (stream.good()) { - stream.read(buffer.data(), static_cast(buffer.size())); - const std::streamsize count = stream.gcount(); - if (count > 0) { - hash.update(buffer.data(), static_cast(count)); - } - } - return hash.finish_hex(); -} - -// The coordinate declaration of one dataset, when the file carries it. -void read_coordinates(const io::Hdf5File& file, const std::string& dataset, - SofaCoordinate* out) { - io::Hdf5Attribute attribute; - if (file.attribute(dataset, "Type", &attribute).ok()) { - out->type = attribute.text; - } - if (file.attribute(dataset, "Units", &attribute).ok()) { - out->units = attribute.text; - } -} - -} // namespace - -std::string SofaHrir::summary() const { - return "SOFA " + sofa_conventions + ", " + std::to_string(ir_count) + " IRs x " + - std::to_string(ir_length) + " taps @ " + format_number(sample_rate) + " Hz"; -} - -Status load_sofa(const std::string& path, SofaHrir* out) { - if (out == nullptr) { - return sofa_fail(JOC_ERR_INVALID_ARGUMENT, "null SOFA destination"); - } - if (!fs_utf8::exists(path)) { - return sofa_fail(JOC_ERR_HRTF_NOT_FOUND, "SOFA file not found: " + path); - } - io::Hdf5File file; - Status status = file.open(path); - if (!status.ok()) { - return sofa_fail(JOC_ERR_HRTF_FORMAT, "SOFA file " + path + ": " + status.message()); - } - - SofaHrir sofa; - sofa.source_path = path; - sofa.source_sha256 = file_digest(path); - for (char& character : sofa.source_sha256) { - character = static_cast(std::toupper(static_cast(character))); - } - status = read_text(file, "Conventions", true, &sofa.conventions); - if (!status.ok()) { - return status; - } - status = read_text(file, "SOFAConventions", true, &sofa.sofa_conventions); - if (!status.ok()) { - return status; - } - if (sofa.conventions != "SOFA" || sofa.sofa_conventions != "SimpleFreeFieldHRIR") { - return sofa_fail(JOC_ERR_HRTF_UNSUPPORTED_CONVENTION, - "SOFA conventions " + sofa.conventions + "/" + sofa.sofa_conventions + - " are not SimpleFreeFieldHRIR"); - } - status = read_text(file, "SOFAConventionsVersion", false, &sofa.convention_version); - if (!status.ok()) { - return status; - } - status = read_text(file, "Version", false, &sofa.version); - if (!status.ok()) { - return status; - } - status = read_text(file, "DataType", false, &sofa.data_type); - if (!status.ok()) { - return status; - } - status = read_text(file, "RoomType", false, &sofa.room_type); - if (!status.ok()) { - return status; - } - status = read_text(file, "Title", false, &sofa.title); - if (!status.ok()) { - return status; - } - status = read_text(file, "DatabaseName", false, &sofa.database_name); - if (!status.ok()) { - return status; - } - status = read_text(file, "ListenerShortName", false, &sofa.listener_short_name); - if (!status.ok()) { - return status; - } - status = read_text(file, "Comment", false, &sofa.comment); - if (!status.ok()) { - return status; - } - - io::Hdf5DatasetInfo info; - status = file.dataset_info("Data.IR", &info); - if (!status.ok()) { - return sofa_fail(JOC_ERR_HRTF_FORMAT, - "SOFA file has no usable Data.IR dataset: " + status.message()); - } - if (info.shape.size() != 3u || info.shape[1] != 2u || info.shape[0] == 0u || - info.shape[2] == 0u) { - return sofa_fail(JOC_ERR_HRTF_FORMAT, "SOFA Data.IR is not shaped (M, 2, N)"); - } - if (info.shape[0] > 0xFFFFFFFFull || info.shape[2] > 0xFFFFFFFFull) { - return sofa_fail(JOC_ERR_HRTF_FORMAT, "SOFA Data.IR is larger than this reader accepts"); - } - sofa.ir_count = static_cast(info.shape[0]); - sofa.ir_length = static_cast(info.shape[2]); - const std::uint64_t taps = static_cast(sofa.ir_count) * 2u * sofa.ir_length; - status = read_doubles(file, "Data.IR", taps, &sofa.ir); - if (!status.ok()) { - return status; - } - - std::vector scalar; - status = read_doubles(file, "Data.SamplingRate", 1u, &scalar); - if (!status.ok()) { - return status; - } - sofa.sample_rate = scalar[0]; - io::Hdf5Attribute attribute; - if (file.attribute("Data.SamplingRate", "Units", &attribute).ok()) { - sofa.sampling_rate_units = attribute.text; - } - - // Data.Delay is optional in the wild; absent means "no delay was measured". - if (file.has_dataset("Data.Delay")) { - std::vector delay; - status = read_doubles(file, "Data.Delay", 2u, &delay); - if (!status.ok()) { - return status; - } - sofa.delay[0] = delay[0]; - sofa.delay[1] = delay[1]; - } - - const std::uint64_t measurements = sofa.ir_count; - status = read_doubles(file, "SourcePosition", measurements * 3u, &sofa.source_position); - if (!status.ok()) { - return status; - } - read_coordinates(file, "SourcePosition", &sofa.source_position_coordinates); - - std::vector vector; - status = read_doubles(file, "ListenerPosition", 3u, &vector); - if (!status.ok()) { - return status; - } - std::copy(vector.begin(), vector.end(), sofa.listener_position); - read_coordinates(file, "ListenerPosition", &sofa.listener_position_coordinates); - status = read_doubles(file, "ListenerView", 3u, &vector); - if (!status.ok()) { - return status; - } - std::copy(vector.begin(), vector.end(), sofa.listener_view); - read_coordinates(file, "ListenerView", &sofa.listener_view_coordinates); - status = read_doubles(file, "ListenerUp", 3u, &vector); - if (!status.ok()) { - return status; - } - std::copy(vector.begin(), vector.end(), sofa.listener_up); - read_coordinates(file, "ListenerUp", &sofa.listener_up_coordinates); - status = read_doubles(file, "EmitterPosition", 3u, &vector); - if (!status.ok()) { - return status; - } - std::copy(vector.begin(), vector.end(), sofa.emitter_position); - read_coordinates(file, "EmitterPosition", &sofa.emitter_position_coordinates); - status = read_doubles(file, "ReceiverPosition", 6u, &vector); - if (!status.ok()) { - return status; - } - std::copy(vector.begin(), vector.end(), sofa.receiver_position); - read_coordinates(file, "ReceiverPosition", &sofa.receiver_position_coordinates); - - *out = std::move(sofa); - return Status::success(); -} - -} // namespace joc::hrtf diff --git a/src/hrtf/sofa.h b/src/hrtf/sofa.h deleted file mode 100644 index 101b033..0000000 --- a/src/hrtf/sofa.h +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "foundation/status.h" - -namespace joc::hrtf { - -// Coordinate declaration of one SOFA variable: Type ("spherical"/"cartesian") and -// Units. Empty when the file does not declare them (ListenerUp inherits). -struct SofaCoordinate { - std::string type; - std::string units; -}; - -// SOFA SimpleFreeFieldHRIR as this project consumes it: the impulse responses, -// the measurement geometry and the metadata needed to report what was loaded. -// All angles are degrees, all distances metres, exactly as the file stores them. -struct SofaHrir { - double sample_rate = 0.0; - std::uint32_t ir_count = 0; // M: number of measurements - std::uint32_t ir_length = 0; // N: taps per impulse response - std::vector ir; // C order [M][2][N] - double delay[2] = {0.0, 0.0}; - std::vector source_position; // M*3 - double listener_position[3] = {0.0, 0.0, 0.0}; - double listener_view[3] = {1.0, 0.0, 0.0}; - double listener_up[3] = {0.0, 0.0, 1.0}; - double emitter_position[3] = {0.0, 0.0, 0.0}; - double receiver_position[6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; - std::string conventions; - std::string sofa_conventions; - std::string convention_version; - std::string version; - std::string data_type; - std::string room_type; - std::string title; - std::string database_name; - std::string listener_short_name; - std::string comment; - std::string sampling_rate_units; - SofaCoordinate source_position_coordinates; - SofaCoordinate listener_position_coordinates; - SofaCoordinate listener_view_coordinates; - SofaCoordinate listener_up_coordinates; - SofaCoordinate emitter_position_coordinates; - SofaCoordinate receiver_position_coordinates; - // Identity of the file itself, needed for the compiled-cache key. - std::string source_path; - std::string source_sha256; - - // One line for reports and logs: - // "SOFA SimpleFreeFieldHRIR, IRs x taps @ Hz". - std::string summary() const; -}; - -Status load_sofa(const std::string& path, SofaHrir* out); - -} // namespace joc::hrtf diff --git a/src/hrtf/sofa_cache.cpp b/src/hrtf/sofa_cache.cpp deleted file mode 100644 index f49b92f..0000000 --- a/src/hrtf/sofa_cache.cpp +++ /dev/null @@ -1,237 +0,0 @@ -#include "hrtf/sofa_cache.h" - -#include -#include -#include -#include -#include -#include - -#include "foundation/fs_utf8.h" -#include "hrtf/sofa.h" - -namespace joc::hrtf { - -namespace { - -namespace fs = std::filesystem; - -// Small process-local cache: the reference keeps the last eight compiled fields. -constexpr std::size_t kMemoryCacheEntries = 8; - -struct MemoryEntry { - std::string key; - Field field; -}; - -std::mutex& memory_mutex() { - static std::mutex mutex; - return mutex; -} - -std::list& memory_cache() { - static std::list cache; - return cache; -} - -bool memory_cache_get(const std::string& key, Field* out) { - std::lock_guard lock(memory_mutex()); - std::list& cache = memory_cache(); - for (auto entry = cache.begin(); entry != cache.end(); ++entry) { - if (entry->key == key) { - *out = entry->field; - cache.splice(cache.begin(), cache, entry); - return true; - } - } - return false; -} - -void memory_cache_put(const std::string& key, const Field& field) { - std::lock_guard lock(memory_mutex()); - std::list& cache = memory_cache(); - for (auto entry = cache.begin(); entry != cache.end(); ++entry) { - if (entry->key == key) { - entry->field = field; - cache.splice(cache.begin(), cache, entry); - return; - } - } - cache.push_front(MemoryEntry{key, field}); - while (cache.size() > kMemoryCacheEntries) { - cache.pop_back(); - } -} - -Status cache_fail(joc_error code, const std::string& message) { - return Status::fail(code, stage::kRender, message); -} - -std::string upper(std::string text) { - std::transform(text.begin(), text.end(), text.begin(), [](unsigned char value) { - return static_cast(std::toupper(value)); - }); - return text; -} - -} // namespace - -Status parse_cache_policy(const std::string& text, CachePolicy* out) { - if (out == nullptr) { - return cache_fail(JOC_ERR_INVALID_ARGUMENT, "null cache policy"); - } - if (text == "none") { - *out = CachePolicy::None; - return Status::success(); - } - if (text == "memory") { - *out = CachePolicy::Memory; - return Status::success(); - } - if (text == "disk") { - *out = CachePolicy::Disk; - return Status::success(); - } - return cache_fail(JOC_ERR_INVALID_CONFIG, "cache_policy must be none, memory, or disk"); -} - -Status validate_jochrtf(const std::string& path, const std::string& source_sha256, - const std::string& cache_key, Field* out) { - Field field; - const Status status = load_jochrtf(path, &field); - if (!status.ok()) { - return status; - } - if (!source_sha256.empty() && field.source_sha256 != upper(source_sha256)) { - return cache_fail(JOC_ERR_HRTF_HASH, "compiled HRTF source hash mismatch"); - } - if (!cache_key.empty() && field.cache_key != upper(cache_key)) { - return cache_fail(JOC_ERR_HRTF_HASH, "compiled HRTF configuration hash mismatch"); - } - if (out != nullptr) { - *out = std::move(field); - } - return Status::success(); -} - -Status save_jochrtf_atomic(const Field& field, const std::string& path) { - if (path.empty()) { - return cache_fail(JOC_ERR_INVALID_ARGUMENT, "empty compiled HRTF cache path"); - } - const fs::path target = fs_utf8::to_path(path); - std::error_code error; - if (target.has_parent_path()) { - fs::create_directories(target.parent_path(), error); - if (error) { - return cache_fail(JOC_ERR_OUTPUT_OPEN, - "cannot create " + fs_utf8::from_path(target.parent_path())); - } - } - const std::string temporary = path + ".tmp"; - Status status = write_jochrtf(field, temporary); - if (!status.ok()) { - return status; - } - // The rename is what makes a half-written cache impossible to observe. - fs::rename(fs_utf8::to_path(temporary), target, error); - if (error) { - fs::remove(fs_utf8::to_path(temporary), error); - return cache_fail(JOC_ERR_OUTPUT_WRITE, "cannot replace " + path); - } - return Status::success(); -} - -Status load_or_compile_sofa_field(const SofaFieldRequest& request, Field* out, - std::string* cache_path) { - if (out == nullptr) { - return cache_fail(JOC_ERR_INVALID_ARGUMENT, "null compiled HRTF destination"); - } - if (request.sofa_path.empty()) { - return cache_fail(JOC_ERR_INVALID_ARGUMENT, "no SOFA path for the compiled HRTF field"); - } - if (request.policy == CachePolicy::Disk && request.cache_dir.empty()) { - return cache_fail(JOC_ERR_INVALID_CONFIG, "the disk cache policy needs a cache directory"); - } - SofaHrir sofa; - Status status = load_sofa(request.sofa_path, &sofa); - if (!status.ok()) { - return status; - } - CanonicalHrtf canonical; - status = canonicalize_sofa(sofa, &canonical); - if (!status.ok()) { - return status; - } - // The key depends on the shell that the radius selects, exactly as upstream. - double actual_radius = request.options.shell_radius_m; - (void)canonical_shell_indices(canonical, request.options.shell_radius_m, &actual_radius); - const std::string key = compiled_hrtf_cache_key( - canonical.source_sha256, canonical.sample_rate_hz, actual_radius, request.options.order, - request.options.projection_ridge, request.options.sh_ridge); - if (cache_path != nullptr) { - cache_path->clear(); - } - - std::string target; - if (request.policy == CachePolicy::Disk) { - target = request.cache_dir; - if (!target.empty() && target.back() != '/' && target.back() != '\\') { - target += "/"; - } - target += cache_file_name(canonical.source_path.empty() - ? std::string() - : canonical.source_path, - key); - if (fs_utf8::exists(target)) { - Field cached_field; - const Status cached = - validate_jochrtf(target, canonical.source_sha256, key, &cached_field); - if (cached.ok()) { - memory_cache_put(key, cached_field); - *out = std::move(cached_field); - if (cache_path != nullptr) { - *cache_path = target; - } - return Status::success(); - } - } - } - Field field; - if (request.policy != CachePolicy::None && memory_cache_get(key, &field)) { - // A memory hit still materialises the disk cache the caller asked for. - if (request.policy == CachePolicy::Disk) { - status = save_jochrtf_atomic(field, target); - if (!status.ok()) { - return status; - } - if (cache_path != nullptr) { - *cache_path = target; - } - } - *out = std::move(field); - return Status::success(); - } - status = compile_canonical_field(canonical, request.options, &field); - if (!status.ok()) { - return status; - } - if (field.cache_key != key) { - return cache_fail(JOC_ERR_INTERNAL, "internal compiled HRTF cache-key mismatch"); - } - if (request.policy == CachePolicy::Disk) { - status = save_jochrtf_atomic(field, target); - if (!status.ok()) { - return status; - } - if (cache_path != nullptr) { - *cache_path = target; - } - } - if (request.policy != CachePolicy::None) { - memory_cache_put(key, field); - } - *out = std::move(field); - return Status::success(); -} - -} // namespace joc::hrtf diff --git a/src/hrtf/sofa_cache.h b/src/hrtf/sofa_cache.h deleted file mode 100644 index 08f0bc3..0000000 --- a/src/hrtf/sofa_cache.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include - -#include "foundation/status.h" -#include "hrtf/jochrtf.h" -#include "hrtf/sofa_field.h" - -// Compiled-field cache: the .jochrtf is an internal artifact, so the caller only -// names the SOFA file and the policy. "memory" keeps the compiled field in this -// process, "disk" additionally reuses (and writes) /..jochrtf. -namespace joc::hrtf { - -enum class CachePolicy { None, Memory, Disk }; - -struct SofaFieldRequest { - std::string sofa_path; - CompileOptions options; - CachePolicy policy = CachePolicy::Memory; - std::string cache_dir; // required for the disk policy -}; - -// Parses "none"/"memory"/"disk"; anything else is rejected. -Status parse_cache_policy(const std::string& text, CachePolicy* out); - -// Returns the compiled field, reusing a valid cache when the policy allows it. -// `cache_path` (optional) receives the cache file that was read or written. -Status load_or_compile_sofa_field(const SofaFieldRequest& request, Field* out, - std::string* cache_path); - -// Writes the field to `path` through a temporary file and an atomic rename. -Status save_jochrtf_atomic(const Field& field, const std::string& path); - -// Verifies that a cache file belongs to `source_sha256` and `cache_key`. -Status validate_jochrtf(const std::string& path, const std::string& source_sha256, - const std::string& cache_key, Field* out); - -} // namespace joc::hrtf diff --git a/src/hrtf/sofa_field.cpp b/src/hrtf/sofa_field.cpp deleted file mode 100644 index 5bd7931..0000000 --- a/src/hrtf/sofa_field.cpp +++ /dev/null @@ -1,1830 +0,0 @@ -#include "hrtf/sofa_field.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "foundation/fft.h" -#include "foundation/mini_json.h" -#include "foundation/sha256.h" -#include "hrtf/public_filterbank.h" -#include "io/npy_writer.h" - -namespace joc::hrtf { - -namespace { - -using Complex = std::complex; - -constexpr double kPi = 3.14159265358979323846; -constexpr int kParameterCount = 2 * kHybridBands; -constexpr std::int32_t kFilterbankFormatVersion = 1; -constexpr int kQmfBands = 64; - -// Hybrid-band centre frequencies of the public analysis bank at 48 kHz -// (public_filterbank._BAND_CENTER_FREQUENCIES_HZ; part of the cache contract). -const double kBandCenters[kHybridBands] = { - 53.19564095937407, 26.3876219849709, 140.9074183269806, 98.55238901464415, - 234.09258166297573, 344.8745321543293, 321.80435900819805, 401.38762185365727, - 476.19239745597804, 473.552388917001, 648.8076026837931, 719.8745321201852, - 780.1254679168173, 851.1923973714038, 1023.8076024849751, 1155.125467695814, - 1293.0325067063661, 1668.032511377253, 2043.0325074138086, 2456.967490229666, - 2831.96748495363, 3206.967488172826, 3581.9675052705525, 3918.0325089666067, - 4331.967500201844, 4706.967500350216, 5043.032510771545, 5456.9674914391635, - 5831.967490225267, 6168.0324885741875, 6543.032508972284, 6956.96748844665, - 7293.032503259869, 7668.032503551393, 8043.032504806491, 8418.032498852166, - 8793.032502508235, 9206.967488589786, 9543.032511549152, 9956.967486913867, - 10293.032513008677, 10668.032507835102, 11043.032513641429, 11456.967482937946, - 11793.032513984212, 12206.967486015788, 12543.032517062376, 12956.96748635822, - 13331.967492165066, 13706.967486991198, 14043.032513086031, 14456.967488451, - 14793.032511410214, 15206.967497492202, 15581.967501147887, 15956.967495193188, - 16331.96749644876, 16706.967496740173, 17043.03251155318, 17456.96749102773, - 17831.967511425748, 18168.032509774734, 18543.032508560515, 18956.967489228293, - 19293.032499649784, 19668.032499798002, 20081.967491033392, 20418.0324947296, - 20793.032511827063, 21168.032515046092, 21543.032509770488, 21956.967492586176, - 22331.96748862257, 22706.967493293465, 23043.03251375972, 23418.03251061199, - 23831.96749768645, -}; - -Status field_fail(joc_error code, const std::string& message) { - return Status::fail(code, stage::kRender, message); -} - -double dot3(const double* a, const double* b) { - return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; -} - -void cross3(const double* a, const double* b, double* out) { - out[0] = a[1] * b[2] - a[2] * b[1]; - out[1] = a[2] * b[0] - a[0] * b[2]; - out[2] = a[0] * b[1] - a[1] * b[0]; -} - -bool normalize3(double* value) { - const double length = std::sqrt(dot3(value, value)); - if (!std::isfinite(length) || length <= 1.0e-15) { - return false; - } - value[0] /= length; - value[1] /= length; - value[2] /= length; - return true; -} - -// Python's round-half-even, used for the reference's shell and direction keys. -double round_half_even(double value, int digits) { - const double scale = std::pow(10.0, digits); - const double scaled = value * scale; - const double lower = std::floor(scaled); - const double fraction = scaled - lower; - double rounded = lower; - if (fraction > 0.5 || (fraction == 0.5 && std::fmod(lower, 2.0) != 0.0)) { - rounded = lower + 1.0; - } - return rounded / scale; -} - -// numpy.percentile with linear interpolation. -double percentile(std::vector values, double percent) { - if (values.empty()) { - return 0.0; - } - std::sort(values.begin(), values.end()); - const double position = (static_cast(values.size()) - 1.0) * percent / 100.0; - const std::size_t lower = static_cast(std::floor(position)); - const std::size_t upper = static_cast(std::ceil(position)); - if (lower == upper || upper >= values.size()) { - return values[std::min(lower, values.size() - 1u)]; - } - const double fraction = position - static_cast(lower); - return values[lower] * (1.0 - fraction) + values[upper] * fraction; -} - - -// Port of sofa_canonical.shift_signal_fft: positive shift delays, negative advances. -std::vector shift_signal_fft(const std::vector& values, double shift) { - const std::size_t count = values.size(); - std::vector result(count, 0.0); - if (std::abs(shift) < 1.0e-12) { - return values; - } - const std::size_t guard = - std::max(128u, static_cast(std::ceil(std::abs(shift))) + 64u); - const std::size_t fft_size = dsp::next_fast_len(count + 2u * guard); - std::vector spectrum(fft_size, Complex(0.0, 0.0)); - for (std::size_t index = 0u; index < count; ++index) { - spectrum[guard + index] = Complex(values[index], 0.0); - } - std::vector transformed; - dsp::fft_any(spectrum, false, &transformed); - const std::size_t half = fft_size / 2u; - for (std::size_t bin = 0u; bin <= half; ++bin) { - const double angle = -2.0 * kPi * static_cast(bin) * shift / - static_cast(fft_size); - transformed[bin] *= std::polar(1.0, angle); - } - for (std::size_t bin = half + 1u; bin < fft_size; ++bin) { - const double angle = -2.0 * kPi * static_cast(bin - fft_size) * shift / - static_cast(fft_size); - transformed[bin] *= std::polar(1.0, angle); - } - std::vector restored; - dsp::fft_any(transformed, true, &restored); - for (std::size_t index = 0u; index < count; ++index) { - result[index] = restored[guard + index].real(); - } - return result; -} - -// public_filterbank.hybrid_gain_synthesis_dictionary for one FIR length. -std::vector hybrid_gain_synthesis_dictionary(std::size_t sample_count, - const Kernels& kernels) { - const std::size_t total = - ((kLatencySamples + sample_count + 512u + kQmfHop - 1u) / kQmfHop) * kQmfHop; - const std::size_t slots = total / kQmfHop; - std::vector impulse(total, 0.0); - impulse[0] = 1.0; - PublicFilterbank analysis_bank(kernels, 1u); - std::vector base; - analysis_bank.analyze_full_rate(impulse, slots, &base); - - std::vector hybrid(slots * kParameterCount * kHybridBands, Complex(0.0, 0.0)); - for (std::size_t slot = 0u; slot < slots; ++slot) { - for (int band = 0; band < kHybridBands; ++band) { - const Complex value = base[slot * kHybridBands + static_cast(band)]; - hybrid[(slot * kParameterCount + static_cast(2 * band)) * kHybridBands + - static_cast(band)] = value; - hybrid[(slot * kParameterCount + static_cast(2 * band + 1)) * kHybridBands + - static_cast(band)] = Complex(0.0, 1.0) * value; - } - } - PublicFilterbank synthesis_bank(kernels, kParameterCount); - std::vector rendered; - synthesis_bank.synthesize_full_rate(hybrid, slots, &rendered); - std::vector dictionary(sample_count * kParameterCount, 0.0); - for (std::size_t tap = 0u; tap < sample_count; ++tap) { - for (int parameter = 0; parameter < kParameterCount; ++parameter) { - dictionary[tap * kParameterCount + static_cast(parameter)] = - rendered[(kLatencySamples + tap) * kParameterCount + static_cast(parameter)]; - } - } - return dictionary; -} - - -// -------------------------------------------------------- linear algebra ---- - -// LU with partial pivoting, complex (mirrors the LAPACK zgesv path the reference -// takes when the ridge system is cast to complex for a complex right-hand side). -bool lu_solve_complex(std::vector* matrix, int order, std::vector* rhs, - int columns) { - std::vector pivot(static_cast(order)); - for (int step = 0; step < order; ++step) { - int best = step; - double best_magnitude = std::abs((*matrix)[static_cast(step) * order + step]); - for (int row = step + 1; row < order; ++row) { - const double magnitude = - std::abs((*matrix)[static_cast(row) * order + step]); - if (magnitude > best_magnitude) { - best_magnitude = magnitude; - best = row; - } - } - pivot[static_cast(step)] = best; - if (best != step) { - for (int column = 0; column < order; ++column) { - std::swap((*matrix)[static_cast(step) * order + column], - (*matrix)[static_cast(best) * order + column]); - } - } - const Complex diagonal = (*matrix)[static_cast(step) * order + step]; - if (std::abs(diagonal) <= 1.0e-300) { - return false; - } - for (int row = step + 1; row < order; ++row) { - const Complex factor = - (*matrix)[static_cast(row) * order + step] / diagonal; - (*matrix)[static_cast(row) * order + step] = factor; - for (int column = step + 1; column < order; ++column) { - (*matrix)[static_cast(row) * order + column] -= - factor * (*matrix)[static_cast(step) * order + column]; - } - } - } - for (int column = 0; column < columns; ++column) { - for (int step = 0; step < order; ++step) { - const int source = pivot[static_cast(step)]; - if (source != step) { - std::swap((*rhs)[static_cast(step) * columns + column], - (*rhs)[static_cast(source) * columns + column]); - } - } - for (int row = 1; row < order; ++row) { - Complex sum = (*rhs)[static_cast(row) * columns + column]; - for (int column2 = 0; column2 < row; ++column2) { - sum -= (*matrix)[static_cast(row) * order + column2] * - (*rhs)[static_cast(column2) * columns + column]; - } - (*rhs)[static_cast(row) * columns + column] = sum; - } - for (int row = order - 1; row >= 0; --row) { - Complex sum = (*rhs)[static_cast(row) * columns + column]; - for (int column2 = row + 1; column2 < order; ++column2) { - sum -= (*matrix)[static_cast(row) * order + column2] * - (*rhs)[static_cast(column2) * columns + column]; - } - (*rhs)[static_cast(row) * columns + column] = - sum / (*matrix)[static_cast(row) * order + row]; - } - } - return true; -} - -// LU with partial pivoting, real (the LAPACK dgesv path). -bool lu_solve_real(std::vector* matrix, int order, std::vector* rhs, int columns) { - std::vector pivot(static_cast(order)); - for (int step = 0; step < order; ++step) { - int best = step; - double best_magnitude = std::abs((*matrix)[static_cast(step) * order + step]); - for (int row = step + 1; row < order; ++row) { - const double magnitude = std::abs((*matrix)[static_cast(row) * order + step]); - if (magnitude > best_magnitude) { - best_magnitude = magnitude; - best = row; - } - } - pivot[static_cast(step)] = best; - if (best != step) { - for (int column = 0; column < order; ++column) { - std::swap((*matrix)[static_cast(step) * order + column], - (*matrix)[static_cast(best) * order + column]); - } - } - const double diagonal = (*matrix)[static_cast(step) * order + step]; - if (std::abs(diagonal) <= 1.0e-300) { - return false; - } - for (int row = step + 1; row < order; ++row) { - const double factor = (*matrix)[static_cast(row) * order + step] / diagonal; - (*matrix)[static_cast(row) * order + step] = factor; - for (int column = step + 1; column < order; ++column) { - (*matrix)[static_cast(row) * order + column] -= - factor * (*matrix)[static_cast(step) * order + column]; - } - } - } - for (int column = 0; column < columns; ++column) { - for (int step = 0; step < order; ++step) { - const int source = pivot[static_cast(step)]; - if (source != step) { - std::swap((*rhs)[static_cast(step) * columns + column], - (*rhs)[static_cast(source) * columns + column]); - } - } - for (int row = 1; row < order; ++row) { - double sum = (*rhs)[static_cast(row) * columns + column]; - for (int column2 = 0; column2 < row; ++column2) { - sum -= (*matrix)[static_cast(row) * order + column2] * - (*rhs)[static_cast(column2) * columns + column]; - } - (*rhs)[static_cast(row) * columns + column] = sum; - } - for (int row = order - 1; row >= 0; --row) { - double sum = (*rhs)[static_cast(row) * columns + column]; - for (int column2 = row + 1; column2 < order; ++column2) { - sum -= (*matrix)[static_cast(row) * order + column2] * - (*rhs)[static_cast(column2) * columns + column]; - } - (*rhs)[static_cast(row) * columns + column] = - sum / (*matrix)[static_cast(row) * order + row]; - } - } - return true; -} - -// ---------------------------------------------------- spherical harmonics --- - -// P_degree^order(x) with the Condon-Shortley phase (spherical_harmonics.py). -double associated_legendre(int order, int degree, double x) { - double p_mm = 1.0; - if (order != 0) { - double double_factorial = 1.0; - for (int value = 1; value < 2 * order; value += 2) { - double_factorial *= static_cast(value); - } - p_mm = (order % 2 == 0 ? 1.0 : -1.0) * double_factorial * - std::pow(std::max(0.0, 1.0 - x * x), 0.5 * static_cast(order)); - } - if (degree == order) { - return p_mm; - } - double previous_previous = p_mm; - double previous = x * static_cast(2 * order + 1) * p_mm; - if (degree == order + 1) { - return previous; - } - for (int current = order + 2; current <= degree; ++current) { - const double value = - (static_cast(2 * current - 1) * x * previous - - static_cast(current + order - 1) * previous_previous) / - static_cast(current - order); - previous_previous = previous; - previous = value; - } - return previous; -} - -double factorial(int value) { - double result = 1.0; - for (int index = 2; index <= value; ++index) { - result *= static_cast(index); - } - return result; -} - -// [M, (order+1)^2] orthonormal real harmonics in ACN order. -void real_spherical_harmonics(const std::vector& directions, std::size_t count, int order, - std::vector* basis) { - const std::size_t terms = static_cast((order + 1) * (order + 1)); - basis->assign(count * terms, 0.0); - for (std::size_t point = 0u; point < count; ++point) { - double unit[3] = {directions[point * 3u], directions[point * 3u + 1u], - directions[point * 3u + 2u]}; - if (!normalize3(unit)) { - unit[0] = 1.0; - unit[1] = 0.0; - unit[2] = 0.0; - } - const double azimuth = std::atan2(unit[1], unit[0]); - const double cos_colatitude = std::min(1.0, std::max(-1.0, unit[2])); - std::size_t column = 0u; - for (int degree = 0; degree <= order; ++degree) { - for (int m = -degree; m <= degree; ++m) { - const int absolute = std::abs(m); - const double normalization = - std::sqrt((2.0 * static_cast(degree) + 1.0) / (4.0 * kPi) * - factorial(degree - absolute) / factorial(degree + absolute)); - const double legendre = associated_legendre(absolute, degree, cos_colatitude); - double value = 0.0; - if (m < 0) { - value = std::sqrt(2.0) * normalization * legendre * - std::sin(static_cast(absolute) * azimuth); - } else if (m > 0) { - value = std::sqrt(2.0) * normalization * legendre * - std::cos(static_cast(m) * azimuth); - } else { - value = normalization * legendre; - } - (*basis)[point * terms + column] = value; - ++column; - } - } - } -} - -// Area weights of an irregular full-sphere grid (spherical_harmonics.py). -// -// The Voronoi cell of p_i is the intersection of the hemispheres -// dot(x, p_i - p_j) >= 0. Projected gnomonicly onto the tangent plane at p_i -// that intersection is a convex polygon of half-planes, so the cell can be -// clipped directly without building a convex hull: this has no triangulation -// ambiguity on cocircular grids (latitude rings) and reproduces the reference's -// spherical Voronoi areas to roundoff. The spherical area is the solid-angle fan -// from p_i over the cell's corners. -std::vector spherical_voronoi_weights(const std::vector& directions, - std::size_t count) { - std::vector weights(count, 1.0 / static_cast(count)); - if (count < 4u) { - return weights; - } - constexpr double kBox = 4.0; // a cap of ~76 degrees: far larger than any cell - std::vector areas(count, 0.0); - std::vector> polygon; - std::vector> clipped; - for (std::size_t point = 0u; point < count; ++point) { - double p[3] = {directions[point * 3u], directions[point * 3u + 1u], - directions[point * 3u + 2u]}; - if (!normalize3(p)) { - return weights; - } - double helper[3] = {0.0, 0.0, 1.0}; - if (std::abs(p[2]) >= 0.9) { - helper[0] = 1.0; - helper[2] = 0.0; - } - double east[3]; - double north[3]; - cross3(helper, p, east); - if (!normalize3(east)) { - return weights; - } - cross3(p, east, north); - - polygon.clear(); - polygon.emplace_back(-kBox, -kBox); - polygon.emplace_back(kBox, -kBox); - polygon.emplace_back(kBox, kBox); - polygon.emplace_back(-kBox, kBox); - for (std::size_t other = 0u; other < count && polygon.size() >= 3u; ++other) { - if (other == point) { - continue; - } - const double* q = directions.data() + other * 3u; - const double cosine = dot3(p, q); - const double a = dot3(east, q); - const double b = dot3(north, q); - clipped.clear(); - for (std::size_t index = 0u; index < polygon.size(); ++index) { - const std::pair& current = polygon[index]; - const std::pair& next = polygon[(index + 1u) % polygon.size()]; - const double value = (1.0 - cosine) - current.first * a - current.second * b; - const double next_value = (1.0 - cosine) - next.first * a - next.second * b; - if (value >= 0.0) { - clipped.push_back(current); - } - if ((value >= 0.0) != (next_value >= 0.0)) { - const double fraction = value / (value - next_value); - clipped.emplace_back(current.first + fraction * (next.first - current.first), - current.second + fraction * (next.second - current.second)); - } - } - polygon.swap(clipped); - } - if (polygon.size() < 3u) { - return weights; // a cell that does not close: keep the uniform fallback - } - double area = 0.0; - for (std::size_t index = 0u; index < polygon.size(); ++index) { - const std::pair& current = polygon[index]; - const std::pair& next = polygon[(index + 1u) % polygon.size()]; - double first[3] = {p[0] + current.first * east[0] + current.second * north[0], - p[1] + current.first * east[1] + current.second * north[1], - p[2] + current.first * east[2] + current.second * north[2]}; - double second[3] = {p[0] + next.first * east[0] + next.second * north[0], - p[1] + next.first * east[1] + next.second * north[1], - p[2] + next.first * east[2] + next.second * north[2]}; - if (!normalize3(first) || !normalize3(second)) { - return weights; - } - double cross[3]; - cross3(first, second, cross); - const double determinant = dot3(p, cross); - const double denominator = - 1.0 + dot3(p, first) + dot3(first, second) + dot3(second, p); - area += std::abs(2.0 * std::atan2(determinant, denominator)); - } - if (!std::isfinite(area) || area <= 0.0) { - return weights; - } - areas[point] = area; - } - double sum = 0.0; - for (const double area : areas) { - sum += area; - } - if (!(sum > 0.0) || !std::isfinite(sum)) { - return weights; - } - for (std::size_t point = 0u; point < count; ++point) { - weights[point] = areas[point] / sum; - } - return weights; -} -// ---------------------------------------------------------- coordinates ----- - -double length_factor(const std::string& token, bool* found) { - static const std::pair kTable[] = { - {"m", 1.0}, {"metre", 1.0}, {"metres", 1.0}, {"meter", 1.0}, - {"meters", 1.0}, {"cm", 1.0e-2}, {"centimetre", 1.0e-2}, {"centimetres", 1.0e-2}, - {"centimeter", 1.0e-2}, {"centimeters", 1.0e-2}, {"mm", 1.0e-3}, {"millimetre", 1.0e-3}, - {"millimetres", 1.0e-3}, {"millimeter", 1.0e-3}, {"millimeters", 1.0e-3}, - }; - for (const auto& entry : kTable) { - if (token == entry.first) { - *found = true; - return entry.second; - } - } - *found = false; - return 0.0; -} - -bool angle_in_radians(const std::string& token, double value, double* out) { - if (token == "degree" || token == "degrees") { - *out = value * (kPi / 180.0); - return true; - } - if (token == "radian" || token == "radians") { - *out = value; - return true; - } - return false; -} - -std::vector split_units(const std::string& units) { - std::vector tokens; - std::string current; - for (const char character : units) { - if (character == ',') { - const std::size_t begin = current.find_first_not_of(" \t"); - const std::size_t end = current.find_last_not_of(" \t"); - if (begin != std::string::npos) { - std::string token = current.substr(begin, end - begin + 1u); - std::transform(token.begin(), token.end(), token.begin(), - [](unsigned char value) { - return static_cast(std::tolower(value)); - }); - tokens.push_back(token); - } - current.clear(); - } else { - current.push_back(character); - } - } - const std::size_t begin = current.find_first_not_of(" \t"); - const std::size_t end = current.find_last_not_of(" \t"); - if (begin != std::string::npos) { - std::string token = current.substr(begin, end - begin + 1u); - std::transform(token.begin(), token.end(), token.begin(), [](unsigned char value) { - return static_cast(std::tolower(value)); - }); - tokens.push_back(token); - } - return tokens; -} - -std::string lowered(const std::string& text) { - std::string result = text; - const std::size_t begin = result.find_first_not_of(" \t"); - const std::size_t end = result.find_last_not_of(" \t"); - result = begin == std::string::npos ? std::string() : result.substr(begin, end - begin + 1u); - std::transform(result.begin(), result.end(), result.begin(), [](unsigned char value) { - return static_cast(std::tolower(value)); - }); - return result; -} - -// coordinates_to_cartesian_m: spherical or Cartesian rows to metres, in place. -Status convert_coordinates(const std::vector& values, std::size_t rows, - const std::string& type, const std::string& units, - const std::string& variable, std::vector* out) { - if (values.size() != rows * 3u) { - return field_fail(JOC_ERR_HRTF_FORMAT, variable + " must contain finite C=3 coordinates"); - } - for (const double value : values) { - if (!std::isfinite(value)) { - return field_fail(JOC_ERR_HRTF_FORMAT, - variable + " must contain finite C=3 coordinates"); - } - } - const std::string kind = lowered(type); - const std::vector tokens = split_units(units); - out->assign(values.size(), 0.0); - if (kind == "cartesian") { - double factors[3] = {0.0, 0.0, 0.0}; - if (tokens.size() == 1u) { - bool found = false; - const double factor = length_factor(tokens[0], &found); - if (!found) { - return field_fail(JOC_ERR_HRTF_FORMAT, - "unsupported Cartesian units for " + variable + ": " + units); - } - factors[0] = factors[1] = factors[2] = factor; - } else if (tokens.size() == 3u) { - for (int axis = 0; axis < 3; ++axis) { - bool found = false; - factors[axis] = length_factor(tokens[static_cast(axis)], &found); - if (!found) { - return field_fail(JOC_ERR_HRTF_FORMAT, - "unsupported Cartesian units for " + variable + ": " + units); - } - } - } else { - return field_fail(JOC_ERR_HRTF_FORMAT, - "unsupported Cartesian units for " + variable + ": " + units); - } - for (std::size_t row = 0u; row < rows; ++row) { - for (int axis = 0; axis < 3; ++axis) { - (*out)[row * 3u + static_cast(axis)] = - values[row * 3u + static_cast(axis)] * factors[axis]; - } - } - return Status::success(); - } - if (kind != "spherical" || tokens.size() != 3u) { - return field_fail(JOC_ERR_HRTF_FORMAT, "unsupported coordinates for " + variable + - ": Type=" + type + ", Units=" + units); - } - bool radius_found = false; - const double radius_factor = length_factor(tokens[2], &radius_found); - if (!radius_found) { - return field_fail(JOC_ERR_HRTF_FORMAT, - "unsupported spherical radius unit for " + variable + ": " + units); - } - for (std::size_t row = 0u; row < rows; ++row) { - double azimuth = 0.0; - double elevation = 0.0; - if (!angle_in_radians(tokens[0], values[row * 3u], &azimuth) || - !angle_in_radians(tokens[1], values[row * 3u + 1u], &elevation)) { - return field_fail(JOC_ERR_HRTF_FORMAT, - "unsupported spherical angle units for " + variable + ": " + units); - } - const double radius = values[row * 3u + 2u] * radius_factor; - if (radius < 0.0) { - return field_fail(JOC_ERR_HRTF_FORMAT, - variable + " contains a negative spherical radius"); - } - const double horizontal = std::cos(elevation); - (*out)[row * 3u] = radius * horizontal * std::cos(azimuth); - (*out)[row * 3u + 1u] = radius * horizontal * std::sin(azimuth); - (*out)[row * 3u + 2u] = radius * std::sin(elevation); - } - return Status::success(); -} - -// ------------------------------------------------------------- JSON --------- - -// The cache metadata is the compact form the reference writes -// (json.dumps(sort_keys=True, separators=(",", ":"))), so only the escaping is -// shared with the indented report and metadata documents. -std::string json_escape(const std::string& text) { return json::quote(text); } - -std::string json_number(double value) { return io::python_float_repr(value); } - -// Python's float.hex(), the representation json.dumps uses for the cache-key -// payload, so the key matches the reference byte for byte. -std::string python_hex(double value) { - if (std::isnan(value)) { - return "nan"; - } - if (std::isinf(value)) { - return value > 0.0 ? "inf" : "-inf"; - } - if (value == 0.0) { - return std::signbit(value) ? "-0x0.0p+0" : "0x0.0p+0"; - } - std::uint64_t bits = 0u; - std::memcpy(&bits, &value, sizeof(bits)); - const bool negative = (bits >> 63u) != 0u; - const int exponent = static_cast((bits >> 52u) & 0x7FFu); - const std::uint64_t mantissa = bits & 0xFFFFFFFFFFFFFull; - char buffer[40]; - if (exponent == 0) { - std::snprintf(buffer, sizeof(buffer), "%s0x0.%013llxp-1022", negative ? "-" : "", - static_cast(mantissa)); - } else { - std::snprintf(buffer, sizeof(buffer), "%s0x1.%013llxp%+d", negative ? "-" : "", - static_cast(mantissa), exponent - 1023); - } - return buffer; -} - -using JsonMembers = std::vector>; - -std::string json_object(JsonMembers members) { - std::sort(members.begin(), members.end(), - [](const std::pair& left, - const std::pair& right) { - return left.first < right.first; - }); - std::string out = "{"; - for (std::size_t index = 0u; index < members.size(); ++index) { - if (index != 0u) { - out += ","; - } - out += json_escape(members[index].first) + ":" + members[index].second; - } - out += "}"; - return out; -} - -std::string json_array(const std::vector& values) { - std::string out = "["; - for (std::size_t index = 0u; index < values.size(); ++index) { - if (index != 0u) { - out += ","; - } - out += values[index]; - } - out += "]"; - return out; -} - -// ------------------------------------------------------- cache contract ----- - -std::string sha256_hex_upper(const void* data, std::size_t size) { - crypto::Sha256 hash; - hash.update(data, size); - std::string digest = hash.finish_hex(); - std::transform(digest.begin(), digest.end(), digest.begin(), [](unsigned char value) { - return static_cast(std::toupper(value)); - }); - return digest; -} - -std::string to_upper(std::string text) { - std::transform(text.begin(), text.end(), text.begin(), [](unsigned char value) { - return static_cast(std::toupper(value)); - }); - return text; -} - -// filterbank_fingerprint(): stable identifiers of the embedded public tables. -std::string filterbank_fingerprint_json() { - const Kernels& kernels = builtin_kernels(); - auto hash_float32 = [](const std::vector& values) { - std::vector narrowed(values.size()); - for (std::size_t index = 0u; index < values.size(); ++index) { - narrowed[index] = static_cast(values[index]); - } - return sha256_hex_upper(narrowed.data(), narrowed.size() * sizeof(float)); - }; - auto hash_float64 = [](const std::vector& values) { - return sha256_hex_upper(values.data(), values.size() * sizeof(double)); - }; - const std::string band_centers_sha = - sha256_hex_upper(kBandCenters, static_cast(kHybridBands) * sizeof(double)); - const JsonMembers arrays = { - // The fingerprint also covers the archive's format_version member. - {"format_version", - json_escape(sha256_hex_upper(&kFilterbankFormatVersion, sizeof(kFilterbankFormatVersion)))}, - {"hybrid_analysis_low_kernel", json_escape(hash_float32(kernels.hybrid_low))}, - {"hybrid_synthesis_indices", - json_escape(sha256_hex_upper(kernels.hybrid_indices.data(), - kernels.hybrid_indices.size() * sizeof(std::int16_t)))}, - {"hybrid_synthesis_values", json_escape(hash_float32(kernels.hybrid_values))}, - {"qmf_analysis_coefficients", json_escape(hash_float32(kernels.qmf_analysis))}, - {"qmf_synthesis_basis", json_escape(hash_float64(kernels.qmf_basis))}, - {"qmf_synthesis_taps", json_escape(hash_float64(kernels.qmf_taps))}, - }; - return json_object({ - {"archive_sha256", json_escape(kFilterbankArchiveSha256)}, - {"array_sha256", json_object(arrays)}, - {"band_centers_sha256", json_escape(band_centers_sha)}, - {"table_version", json_escape(kFilterbankTableVersion)}, - }); -} - -} // namespace - -std::vector hybrid_gain_synthesis_dictionary_for_check(std::size_t sample_count) { - return hybrid_gain_synthesis_dictionary(sample_count, builtin_kernels()); -} - -std::vector analysis_impulse_for_check(std::size_t total_samples) { - const std::size_t slots = total_samples / kQmfHop; - std::vector impulse(total_samples, 0.0); - impulse[0] = 1.0; - PublicFilterbank bank(builtin_kernels(), 1u); - std::vector base; - bank.analyze_full_rate(impulse, slots, &base); - std::vector out(base.size() * 2u, 0.0); - for (std::size_t index = 0u; index < base.size(); ++index) { - out[index * 2u] = base[index].real(); - out[index * 2u + 1u] = base[index].imag(); - } - return out; -} - -const std::vector& hybrid_band_center_frequencies_hz() { - static const std::vector centers(kBandCenters, kBandCenters + kHybridBands); - return centers; -} - -std::string compiled_hrtf_cache_key(const std::string& source_sha256, double sample_rate_hz, - double shell_radius_m, int order, double projection_ridge, - double sh_ridge) { - const std::string payload = json_object({ - {"compiler_version", json_escape(kCompilerVersion)}, - {"filterbank", filterbank_fingerprint_json()}, - {"order", std::to_string(order)}, - {"phase_policy_version", json_escape(kPhasePolicyVersion)}, - {"projection_ridge", json_escape(python_hex(projection_ridge))}, - {"sh_convention", json_escape(kShConvention)}, - {"shell_radius_m", json_escape(python_hex(shell_radius_m))}, - {"source_sha256", json_escape(to_upper(source_sha256))}, - {"spherical_harmonic_ridge", json_escape(python_hex(sh_ridge))}, - {"target_sample_rate_hz", json_escape(python_hex(sample_rate_hz))}, - }); - const std::string encoded = std::string("JOC-HRTF-CACHE-KEY-V1\0", 22u) + payload; - return to_upper(sha256_hex_upper(encoded.data(), encoded.size())); -} - -std::string field_payload_sha256(const Field& field) { - crypto::Sha256 hash; - const char prefix[] = "JOC-HRTF-CACHE-PAYLOAD-V1"; - hash.update(prefix, sizeof(prefix) - 1u); - const std::uint8_t zero = 0u; - hash.update(&zero, 1u); - auto feed = [&](const char* name, const char* dtype, const std::string& shape, - const void* data, std::size_t size) { - const std::string name_text(name); - const std::string dtype_text(dtype); - hash.update(name_text.data(), name_text.size()); - hash.update(&zero, 1u); - hash.update(dtype_text.data(), dtype_text.size()); - hash.update(&zero, 1u); - hash.update(shape.data(), shape.size()); - hash.update(&zero, 1u); - hash.update(data, size); - }; - feed("band_center_frequencies_hz", "= 'A' && character <= 'Z') || - (character >= 'a' && character <= 'z') || - (character >= '0' && character <= '9') || character == '.' || - character == '_' || character == '-'; - safe.push_back(allowed ? character : '_'); - } - const std::size_t begin = safe.find_first_not_of("._"); - const std::size_t end = safe.find_last_not_of("._"); - safe = begin == std::string::npos ? std::string() : safe.substr(begin, end - begin + 1u); - if (safe.empty()) { - safe = "hrtf"; - } - return safe + "." + cache_key.substr(0u, 20u) + ".jochrtf"; -} - -Status write_jochrtf(const Field& field, const std::string& path) { - if (field.metadata_json.empty() || field.payload_sha256.empty()) { - return field_fail(JOC_ERR_INVALID_ARGUMENT, - "compiled HRTF field has no metadata to write"); - } - std::vector members; - auto add_real = [&](const char* name, const std::vector& values, - std::vector shape) { - io::NpyMember member; - member.name = name; - member.descr = "& basis, std::size_t count, int terms, - const std::vector& weights, double ridge, - std::vector* system, std::vector* weighted_basis) { - weighted_basis->assign(count * static_cast(terms), 0.0); - for (std::size_t row = 0u; row < count; ++row) { - for (int term = 0; term < terms; ++term) { - (*weighted_basis)[row * static_cast(terms) + static_cast(term)] = - basis[row * static_cast(terms) + static_cast(term)] * - weights[row]; - } - } - system->assign(static_cast(terms) * static_cast(terms), 0.0); - for (std::size_t row = 0u; row < count; ++row) { - for (int left = 0; left < terms; ++left) { - const double value = - basis[row * static_cast(terms) + static_cast(left)]; - if (value == 0.0) { - continue; - } - for (int right = 0; right < terms; ++right) { - (*system)[static_cast(left) * static_cast(terms) + - static_cast(right)] += - value * (*weighted_basis)[row * static_cast(terms) + - static_cast(right)]; - } - } - } - double trace = 0.0; - for (int term = 0; term < terms; ++term) { - trace += (*system)[static_cast(term) * static_cast(terms) + - static_cast(term)]; - } - const double scale = trace / static_cast(terms); - for (int term = 0; term < terms; ++term) { - (*system)[static_cast(term) * static_cast(terms) + - static_cast(term)] += ridge * scale; - } -} - -// fit_real_spherical_harmonics for complex targets: [terms, columns]. -std::vector fit_complex(const std::vector& basis, std::size_t count, int terms, - const std::vector& weights, double ridge, - const std::vector& values, std::size_t columns) { - std::vector system; - std::vector weighted_basis; - normal_system(basis, count, terms, weights, ridge, &system, &weighted_basis); - std::vector matrix(system.size()); - for (std::size_t index = 0u; index < system.size(); ++index) { - matrix[index] = Complex(system[index], 0.0); - } - std::vector right(static_cast(terms) * columns, Complex(0.0, 0.0)); - for (std::size_t row = 0u; row < count; ++row) { - for (int term = 0; term < terms; ++term) { - const double basis_value = - basis[row * static_cast(terms) + static_cast(term)]; - if (basis_value == 0.0) { - continue; - } - for (std::size_t column = 0u; column < columns; ++column) { - right[static_cast(term) * columns + column] += - basis_value * weights[row] * values[row * columns + column]; - } - } - } - lu_solve_complex(&matrix, terms, &right, static_cast(columns)); - return right; -} - -// fit_real_spherical_harmonics for real targets: [terms, columns]. -std::vector fit_real(const std::vector& basis, std::size_t count, int terms, - const std::vector& weights, double ridge, - const std::vector& values, std::size_t columns) { - std::vector system; - std::vector weighted_basis; - normal_system(basis, count, terms, weights, ridge, &system, &weighted_basis); - std::vector right(static_cast(terms) * columns, 0.0); - for (std::size_t row = 0u; row < count; ++row) { - for (int term = 0; term < terms; ++term) { - const double basis_value = - basis[row * static_cast(terms) + static_cast(term)]; - if (basis_value == 0.0) { - continue; - } - for (std::size_t column = 0u; column < columns; ++column) { - right[static_cast(term) * columns + column] += - basis_value * weights[row] * values[row * columns + column]; - } - } - } - lu_solve_real(&system, terms, &right, static_cast(columns)); - return right; -} - -// --------------------------------------------------------- time alignment --- - -// sofa_canonical._subsample_peak: parabolic peak of |values|. -double subsample_peak(const std::vector& values) { - std::size_t index = 0u; - double magnitude = -1.0; - for (std::size_t position = 0u; position < values.size(); ++position) { - const double current = std::abs(values[position]); - if (current > magnitude) { - magnitude = current; - index = position; - } - } - if (index == 0u || index + 1u >= values.size()) { - return static_cast(index); - } - const double previous = std::abs(values[index - 1u]); - const double current = std::abs(values[index]); - const double next = std::abs(values[index + 1u]); - const double denominator = previous - 2.0 * current + next; - double correction = 0.0; - if (std::abs(denominator) >= 1.0e-30) { - correction = 0.5 * (previous - next) / denominator; - } - correction = std::min(0.5, std::max(-0.5, correction)); - return static_cast(index) + correction; -} - -struct AlignedHrtf { - std::vector aligned; // [M,2,N] - std::vector runtime_delay; // [M,2] - std::vector embedded_removed; // [M,2] - std::string delay_source; -}; - -// sofa_canonical.time_align_hrtf: separate exactly one delay representation. -AlignedHrtf time_align_hrtf(const CanonicalHrtf& canonical) { - AlignedHrtf result; - const std::size_t measurements = canonical.measurements; - const std::size_t taps = canonical.taps; - result.aligned = canonical.hrir; - result.runtime_delay.assign(measurements * 2u, 0.0); - result.embedded_removed.assign(measurements * 2u, 0.0); - double maximum = 0.0; - for (const double value : canonical.delay_samples) { - maximum = std::max(maximum, std::abs(value)); - } - if (maximum > 1.0e-12) { - result.runtime_delay = canonical.delay_samples; - result.delay_source = "Data.Delay (external; applied once at render time)"; - return result; - } - std::size_t used_peak = 0u; - std::size_t retained = 0u; - std::vector ear(taps, 0.0); - // hrir[measurement][channel] as a tap range. - auto ear_range = [&](std::size_t measurement, int channel) { - const std::size_t first = (measurement * 2u + static_cast(channel)) * taps; - return std::make_pair(canonical.hrir.begin() + static_cast(first), - canonical.hrir.begin() + static_cast(first + taps)); - }; - for (std::size_t measurement = 0u; measurement < measurements; ++measurement) { - double peaks[2] = {0.0, 0.0}; - for (int channel = 0; channel < 2; ++channel) { - const auto range = ear_range(measurement, channel); - std::copy(range.first, range.second, ear.begin()); - peaks[channel] = subsample_peak(ear); - } - if (std::max(peaks[0], peaks[1]) > 2.0) { - ++used_peak; - } else { - peaks[0] = 0.0; - peaks[1] = 0.0; - ++retained; - } - for (int channel = 0; channel < 2; ++channel) { - const std::size_t ear_index = measurement * 2u + static_cast(channel); - result.runtime_delay[ear_index] = peaks[channel]; - result.embedded_removed[ear_index] = peaks[channel]; - if (peaks[channel] != 0.0) { - const auto range = ear_range(measurement, channel); - std::copy(range.first, range.second, ear.begin()); - const std::vector shifted = shift_signal_fft(ear, -peaks[channel]); - std::copy(shifted.begin(), shifted.end(), - result.aligned.begin() + static_cast(ear_index * taps)); - } - } - } - result.delay_source = "embedded Data.IR arrival separation: peak=" + - std::to_string(used_peak) + - ", zero-origin embedded phase retained=" + std::to_string(retained) + - "; positive onset restored once at render time"; - return result; -} - -// ------------------------------------------------------------- pipeline ----- - -// canonical.shell_indices: the measurements on the shell nearest to radius_m. -} // namespace - -std::vector canonical_shell_indices(const CanonicalHrtf& canonical, double radius_m, - double* actual_radius_m) { - std::vector shells; - for (const double radius : canonical.measurement_radius_m) { - const double rounded = round_half_even(radius, 9); - if (std::find(shells.begin(), shells.end(), rounded) == shells.end()) { - shells.push_back(rounded); - } - } - std::sort(shells.begin(), shells.end()); - double shell = shells.empty() ? radius_m : shells.front(); - double best = std::numeric_limits::infinity(); - for (const double candidate : shells) { - const double distance = std::abs(candidate - radius_m); - if (distance < best) { - best = distance; - shell = candidate; - } - } - std::vector indices; - double total = 0.0; - for (std::size_t index = 0u; index < canonical.measurement_radius_m.size(); ++index) { - if (std::abs(canonical.measurement_radius_m[index] - shell) <= 5.0e-7) { - indices.push_back(index); - total += canonical.measurement_radius_m[index]; - } - } - *actual_radius_m = indices.empty() ? shell : total / static_cast(indices.size()); - return indices; -} - -namespace { - -// _group_coincident: merge measurements that share a direction (keys are the -// directions rounded to ten decimals, grouped in sorted key order). -void group_coincident(const std::vector& directions, std::size_t count, - const std::vector& gains, std::size_t columns, - const std::vector& delays, std::vector* out_directions, - std::vector* out_gains, std::vector* out_delays) { - struct Key { - double value[3]; - std::size_t first; - }; - std::vector keys(count); - for (std::size_t index = 0u; index < count; ++index) { - for (int axis = 0; axis < 3; ++axis) { - keys[index].value[axis] = - round_half_even(directions[index * 3u + static_cast(axis)], 10); - } - keys[index].first = index; - } - std::sort(keys.begin(), keys.end(), [](const Key& left, const Key& right) { - for (int axis = 0; axis < 3; ++axis) { - if (left.value[axis] != right.value[axis]) { - return left.value[axis] < right.value[axis]; - } - } - return left.first < right.first; - }); - std::vector unique; - std::vector group_of(count, 0u); - for (const Key& key : keys) { - if (unique.empty() || unique.back().value[0] != key.value[0] || - unique.back().value[1] != key.value[1] || unique.back().value[2] != key.value[2]) { - unique.push_back(key); - } else if (key.first < unique.back().first) { - unique.back().first = key.first; - } - group_of[key.first] = unique.size() - 1u; - } - const std::size_t groups = unique.size(); - out_directions->assign(groups * 3u, 0.0); - out_gains->assign(groups * columns, Complex(0.0, 0.0)); - out_delays->assign(groups * 2u, 0.0); - std::vector counts(groups, 0.0); - for (std::size_t index = 0u; index < count; ++index) { - const std::size_t group = group_of[index]; - ++counts[group]; - for (int axis = 0; axis < 3; ++axis) { - (*out_directions)[group * 3u + static_cast(axis)] += - directions[index * 3u + static_cast(axis)]; - } - for (std::size_t column = 0u; column < columns; ++column) { - (*out_gains)[group * columns + column] += gains[index * columns + column]; - } - for (std::size_t ear = 0u; ear < 2u; ++ear) { - (*out_delays)[group * 2u + ear] += delays[index * 2u + ear]; - } - } - for (std::size_t group = 0u; group < groups; ++group) { - for (std::size_t column = 0u; column < columns; ++column) { - (*out_gains)[group * columns + column] /= counts[group]; - } - for (std::size_t ear = 0u; ear < 2u; ++ear) { - (*out_delays)[group * 2u + ear] /= counts[group]; - } - } -} - -std::string basename_of(const std::string& path) { - const std::size_t slash = path.find_last_of("/\\"); - return slash == std::string::npos ? path : path.substr(slash + 1u); -} - -// sofa_canonical._processing_label: the non-empty identifying attributes. -std::string processing_label(const SofaHrir& sofa) { - std::vector parts; - const std::string candidates[4] = {sofa.database_name, sofa.title, sofa.listener_short_name, - sofa.comment}; - for (const std::string& value : candidates) { - const std::size_t begin = value.find_first_not_of(" \t"); - const std::size_t end = value.find_last_not_of(" \t"); - if (begin == std::string::npos) { - continue; - } - const std::string trimmed = value.substr(begin, end - begin + 1u); - if (std::find(parts.begin(), parts.end(), trimmed) == parts.end()) { - parts.push_back(trimmed); - } - } - std::string label; - for (std::size_t index = 0u; index < parts.size(); ++index) { - if (index != 0u) { - label += " | "; - } - label += parts[index]; - } - return label; -} - -double minimum_of(const std::vector& values) { - double result = std::numeric_limits::infinity(); - for (const double value : values) { - result = std::min(result, value); - } - return values.empty() ? 0.0 : result; -} - -double maximum_of(const std::vector& values) { - double result = -std::numeric_limits::infinity(); - for (const double value : values) { - result = std::max(result, value); - } - return values.empty() ? 0.0 : result; -} - -} // namespace - -Status canonicalize_sofa(const SofaHrir& sofa, CanonicalHrtf* out) { - if (out == nullptr) { - return field_fail(JOC_ERR_INVALID_ARGUMENT, "null canonical HRTF destination"); - } - if (sofa.conventions != "SOFA") { - return field_fail(JOC_ERR_HRTF_UNSUPPORTED_CONVENTION, "Conventions must be SOFA"); - } - if (sofa.sofa_conventions != "SimpleFreeFieldHRIR") { - return field_fail(JOC_ERR_HRTF_UNSUPPORTED_CONVENTION, - "unsupported SOFAConventions=" + sofa.sofa_conventions + - "; convert explicitly first"); - } - if (sofa.convention_version != "0.4" && sofa.convention_version != "1.0" && - sofa.convention_version != "1.1") { - return field_fail(JOC_ERR_HRTF_UNSUPPORTED_CONVENTION, - "unsupported SimpleFreeFieldHRIR version " + sofa.convention_version); - } - if (sofa.data_type != "FIR") { - return field_fail(JOC_ERR_HRTF_FORMAT, "DataType must be FIR"); - } - const std::string room_type = lowered(sofa.room_type); - if (room_type != "free field" && room_type != "free-field" && room_type != "anechoic" && - room_type != "hemi-anechoic") { - return field_fail(JOC_ERR_HRTF_FORMAT, - "RoomType must explicitly be free-field, got " + sofa.room_type); - } - const std::size_t measurements = sofa.ir_count; - const std::size_t taps = sofa.ir_length; - if (measurements == 0u || taps == 0u || sofa.ir.size() != measurements * 2u * taps) { - return field_fail(JOC_ERR_HRTF_FORMAT, "Data.IR must have shape [M,R=2,N]"); - } - for (const double value : sofa.ir) { - if (!std::isfinite(value)) { - return field_fail(JOC_ERR_HRTF_FORMAT, "Data.IR contains non-finite values"); - } - } - if (!std::isfinite(sofa.sample_rate) || sofa.sample_rate <= 0.0) { - return field_fail(JOC_ERR_HRTF_FORMAT, - "Data.SamplingRate must contain one positive finite value"); - } - const std::string rate_units = lowered(sofa.sampling_rate_units); - if (rate_units != "hertz" && rate_units != "hz") { - return field_fail(JOC_ERR_HRTF_FORMAT, - "Data.SamplingRate Units must be hertz, got " + sofa.sampling_rate_units); - } - std::vector delay(2u, 0.0); - for (std::size_t ear = 0u; ear < 2u; ++ear) { - const double value = sofa.delay[ear]; - if (!std::isfinite(value)) { - return field_fail(JOC_ERR_HRTF_FORMAT, "Data.Delay must be finite"); - } - if (value < -1.0e-9) { - return field_fail(JOC_ERR_HRTF_FORMAT, - "negative Data.Delay is outside the supported causal contract"); - } - delay[ear] = std::max(0.0, value); - } - - const std::vector emitter_values(sofa.emitter_position, - sofa.emitter_position + 3); - std::vector emitter; - Status status = convert_coordinates(emitter_values, 1u, sofa.emitter_position_coordinates.type, - sofa.emitter_position_coordinates.units, "EmitterPosition", - &emitter); - if (!status.ok()) { - return status; - } - for (const double value : emitter) { - if (std::abs(value) > 1.0e-9) { - return field_fail(JOC_ERR_HRTF_FORMAT, - "non-zero EmitterPosition needs a separate source-pose adapter"); - } - } - - const std::vector position_values(sofa.listener_position, - sofa.listener_position + 3); - const std::vector view_values(sofa.listener_view, sofa.listener_view + 3); - const std::vector up_values(sofa.listener_up, sofa.listener_up + 3); - std::vector listener_position; - std::vector listener_view; - std::vector listener_up_raw; - status = convert_coordinates(position_values, 1u, sofa.listener_position_coordinates.type, - sofa.listener_position_coordinates.units, "ListenerPosition", - &listener_position); - if (!status.ok()) { - return status; - } - status = convert_coordinates(view_values, 1u, sofa.listener_view_coordinates.type, - sofa.listener_view_coordinates.units, "ListenerView", &listener_view); - if (!status.ok()) { - return status; - } - // ListenerUp inherits ListenerView's Type/Units when it declares none. - const std::string up_type = sofa.listener_up_coordinates.type.empty() ? sofa.listener_view_coordinates.type - : sofa.listener_up_coordinates.type; - const std::string up_units = sofa.listener_up_coordinates.units.empty() - ? sofa.listener_view_coordinates.units - : sofa.listener_up_coordinates.units; - status = convert_coordinates(up_values, 1u, up_type, up_units, "ListenerUp", &listener_up_raw); - if (!status.ok()) { - return status; - } - double forward[3] = {listener_view[0], listener_view[1], listener_view[2]}; - if (!normalize3(forward)) { - return field_fail(JOC_ERR_HRTF_FORMAT, "ListenerView must be non-zero"); - } - double left[3]; - cross3(listener_up_raw.data(), forward, left); - if (!normalize3(left)) { - return field_fail(JOC_ERR_HRTF_FORMAT, "ListenerUp must not be parallel to ListenerView"); - } - double up[3]; - cross3(forward, left, up); - - std::vector source_world; - status = convert_coordinates(sofa.source_position, measurements, sofa.source_position_coordinates.type, - sofa.source_position_coordinates.units, "SourcePosition", - &source_world); - if (!status.ok()) { - return status; - } - if (source_world.size() != measurements * 3u) { - return field_fail(JOC_ERR_HRTF_FORMAT, "SourcePosition must have shape [M,C=3]"); - } - std::vector source_local(measurements * 3u, 0.0); - std::vector radii(measurements, 0.0); - for (std::size_t row = 0u; row < measurements; ++row) { - const double relative[3] = {source_world[row * 3u] - listener_position[0], - source_world[row * 3u + 1u] - listener_position[1], - source_world[row * 3u + 2u] - listener_position[2]}; - source_local[row * 3u] = dot3(relative, forward); - source_local[row * 3u + 1u] = dot3(relative, left); - source_local[row * 3u + 2u] = dot3(relative, up); - radii[row] = std::sqrt(source_local[row * 3u] * source_local[row * 3u] + - source_local[row * 3u + 1u] * source_local[row * 3u + 1u] + - source_local[row * 3u + 2u] * source_local[row * 3u + 2u]); - if (!std::isfinite(radii[row]) || radii[row] <= 1.0e-8) { - return field_fail(JOC_ERR_HRTF_FORMAT, - "every source measurement must have a positive radius"); - } - } - - // ReceiverPosition is [R=2,C=3,I]; the two receivers are converted separately - // so their units are validated the same way as every other coordinate row. - std::vector receiver_cartesian(6u, 0.0); - for (std::size_t receiver = 0u; receiver < 2u; ++receiver) { - const std::vector row(sofa.receiver_position + receiver * 3u, - sofa.receiver_position + receiver * 3u + 3u); - std::vector converted; - status = convert_coordinates(row, 1u, sofa.receiver_position_coordinates.type, - sofa.receiver_position_coordinates.units, "ReceiverPosition", - &converted); - if (!status.ok()) { - return status; - } - for (int axis = 0; axis < 3; ++axis) { - receiver_cartesian[receiver * 3u + static_cast(axis)] = - converted[static_cast(axis)]; - } - } - int left_index = 0; - int right_index = 1; - const double lateral = receiver_cartesian[1] - receiver_cartesian[4]; - if (lateral <= 1.0e-5) { - if (lateral >= -1.0e-5) { - return field_fail(JOC_ERR_HRTF_FORMAT, - "ReceiverPosition does not identify one consistently-left and one " - "consistently-right receiver"); - } - left_index = 1; - right_index = 0; - } - - CanonicalHrtf canonical; - canonical.source_path = sofa.source_path; - canonical.source_sha256 = to_upper(sofa.source_sha256); - canonical.convention = sofa.sofa_conventions; - canonical.convention_version = sofa.convention_version; - canonical.processing_label = processing_label(sofa); - canonical.sample_rate_hz = sofa.sample_rate; - canonical.measurements = static_cast(measurements); - canonical.taps = static_cast(taps); - canonical.left_receiver_index = left_index; - canonical.right_receiver_index = right_index; - canonical.receiver_position_cartesian_m.assign(6u, 0.0); - for (int ear = 0; ear < 2; ++ear) { - const int receiver = ear == 0 ? left_index : right_index; - for (int axis = 0; axis < 3; ++axis) { - canonical.receiver_position_cartesian_m[static_cast(ear * 3 + axis)] = - receiver_cartesian[static_cast(receiver * 3 + axis)]; - } - } - canonical.source_position_cartesian_m = source_local; - canonical.unit_directions.resize(measurements * 3u, 0.0); - for (std::size_t row = 0u; row < measurements; ++row) { - for (int axis = 0; axis < 3; ++axis) { - canonical.unit_directions[row * 3u + static_cast(axis)] = - source_local[row * 3u + static_cast(axis)] / radii[row]; - } - } - canonical.measurement_radius_m = radii; - canonical.hrir.assign(measurements * 2u * taps, 0.0); - canonical.delay_samples.assign(measurements * 2u, 0.0); - for (std::size_t row = 0u; row < measurements; ++row) { - for (std::size_t ear = 0u; ear < 2u; ++ear) { - const std::size_t source_ear = ear == 0u ? static_cast(left_index) - : static_cast(right_index); - std::copy(sofa.ir.begin() + - static_cast((row * 2u + source_ear) * taps), - sofa.ir.begin() + - static_cast((row * 2u + source_ear + 1u) * taps), - canonical.hrir.begin() + static_cast((row * 2u + ear) * taps)); - canonical.delay_samples[row * 2u + ear] = delay[source_ear]; - } - } - *out = std::move(canonical); - return Status::success(); -} - -Status compile_canonical_field(const CanonicalHrtf& canonical, const CompileOptions& options, - Field* out) { - if (out == nullptr) { - return field_fail(JOC_ERR_INVALID_ARGUMENT, "null field destination"); - } - if (options.order != kFieldOrder) { - return field_fail(JOC_ERR_HRTF_FORMAT, "the runtime HRTF field is fixed at fifth order"); - } - if (!std::isfinite(canonical.sample_rate_hz) || - std::abs(canonical.sample_rate_hz - kFieldSampleRateHz) > 1.0e-9) { - return field_fail(JOC_ERR_HRTF_FORMAT, "SOFA HRTF fields must be compiled at 48 kHz"); - } - if (!std::isfinite(options.shell_radius_m) || options.shell_radius_m <= 0.0) { - return field_fail(JOC_ERR_HRTF_FORMAT, "shell_radius_m must be positive and finite"); - } - if (!std::isfinite(options.projection_ridge) || options.projection_ridge < 0.0 || - !std::isfinite(options.sh_ridge) || options.sh_ridge < 0.0) { - return field_fail(JOC_ERR_HRTF_FORMAT, - "compiler ridge values must be finite and non-negative"); - } - if (canonical.measurements == 0u || canonical.taps == 0u) { - return field_fail(JOC_ERR_HRTF_FORMAT, "canonical HRTF is empty"); - } - const std::size_t terms = static_cast(kFieldTerms); - const std::size_t gains_per_direction = static_cast(kParameterCount); - const std::size_t columns = static_cast(kParameterCount); - - const AlignedHrtf aligned = time_align_hrtf(canonical); - double shell_radius = options.shell_radius_m; - const std::vector indices = - canonical_shell_indices(canonical, options.shell_radius_m, &shell_radius); - if (indices.size() < terms) { - return field_fail(JOC_ERR_HRTF_FORMAT, - "fifth-order SH needs at least 36 measurements on one shell, got " + - std::to_string(indices.size())); - } - const std::size_t selected = indices.size(); - - // Project the selected HRIRs onto the public analysis/gain/synthesis dictionary. - const Kernels& kernels = builtin_kernels(); - const std::vector dictionary = hybrid_gain_synthesis_dictionary(canonical.taps, kernels); - std::vector system(columns * columns, 0.0); - for (std::size_t left = 0u; left < columns; ++left) { - for (std::size_t right = 0u; right < columns; ++right) { - double sum = 0.0; - for (std::size_t tap = 0u; tap < canonical.taps; ++tap) { - sum += dictionary[tap * columns + left] * dictionary[tap * columns + right]; - } - system[left * columns + right] = sum; - } - } - double trace = 0.0; - for (std::size_t parameter = 0u; parameter < columns; ++parameter) { - trace += system[parameter * columns + parameter]; - } - const double scale = trace / static_cast(columns); - for (std::size_t parameter = 0u; parameter < columns; ++parameter) { - system[parameter * columns + parameter] += options.projection_ridge * scale; - } - - // target[tap][measurement*2 + ear], the reference's reshape(-1, N).T. - const std::size_t target_columns = selected * 2u; - std::vector target(canonical.taps * target_columns, 0.0); - for (std::size_t row = 0u; row < selected; ++row) { - for (std::size_t ear = 0u; ear < 2u; ++ear) { - const std::size_t column = row * 2u + ear; - for (std::size_t tap = 0u; tap < canonical.taps; ++tap) { - target[tap * target_columns + column] = - canonical.hrir[(indices[row] * 2u + ear) * canonical.taps + tap]; - } - } - } - std::vector parameters(columns * target_columns, 0.0); - for (std::size_t tap = 0u; tap < canonical.taps; ++tap) { - for (std::size_t parameter = 0u; parameter < columns; ++parameter) { - const double value = dictionary[tap * columns + parameter]; - if (value == 0.0) { - continue; - } - for (std::size_t column = 0u; column < target_columns; ++column) { - parameters[parameter * target_columns + column] += - value * target[tap * target_columns + column]; - } - } - } - if (!lu_solve_real(&system, static_cast(columns), ¶meters, - static_cast(target_columns))) { - return field_fail(JOC_ERR_HRTF_FORMAT, "HRTF projection system is singular"); - } - - // Hybrid gains [measurement][ear*77 + band] with the known embedded delay - // removed exactly once (parameters[parameter][measurement*2 + ear]). - std::vector selected_removed(selected * 2u, 0.0); - std::vector gains_by_direction(selected * gains_per_direction, Complex(0.0, 0.0)); - for (std::size_t row = 0u; row < selected; ++row) { - for (std::size_t ear = 0u; ear < 2u; ++ear) { - const std::size_t column = row * 2u + ear; - const double removed = aligned.embedded_removed[indices[row] * 2u + ear]; - selected_removed[column] = removed; - for (int band = 0; band < kHybridBands; ++band) { - const double real = parameters[static_cast(2 * band) * target_columns + column]; - const double imaginary = - parameters[static_cast(2 * band + 1) * target_columns + column]; - const double removal = - 2.0 * kPi * removed * kBandCenters[band] / canonical.sample_rate_hz; - gains_by_direction[row * gains_per_direction + ear * kHybridBands + - static_cast(band)] = - Complex(real, imaginary) * std::polar(1.0, removal); - } - } - } - std::vector signal_to_noise(target_columns, 0.0); - double maximum_gain = 0.0; - for (const Complex value : gains_by_direction) { - maximum_gain = std::max(maximum_gain, std::abs(value)); - } - for (std::size_t column = 0u; column < target_columns; ++column) { - double reference_energy = 0.0; - double error_energy = 0.0; - for (std::size_t tap = 0u; tap < canonical.taps; ++tap) { - double reconstructed = 0.0; - for (std::size_t parameter = 0u; parameter < columns; ++parameter) { - reconstructed += dictionary[tap * columns + parameter] * - parameters[parameter * target_columns + column]; - } - const double value = target[tap * target_columns + column]; - reference_energy += value * value; - const double error = value - reconstructed; - error_energy += error * error; - } - signal_to_noise[column] = - 10.0 * std::log10(std::max(reference_energy, 1.0e-300) / - std::max(error_energy, 1.0e-300)); - } - - std::vector directions; - std::vector gains; - std::vector runtime_delay; - std::vector selected_directions(selected * 3u, 0.0); - std::vector selected_delays(selected * 2u, 0.0); - for (std::size_t row = 0u; row < selected; ++row) { - for (int axis = 0; axis < 3; ++axis) { - selected_directions[row * 3u + static_cast(axis)] = - canonical.unit_directions[indices[row] * 3u + static_cast(axis)]; - } - for (std::size_t ear = 0u; ear < 2u; ++ear) { - selected_delays[row * 2u + ear] = aligned.runtime_delay[indices[row] * 2u + ear]; - } - } - group_coincident(selected_directions, selected, gains_by_direction, gains_per_direction, - selected_delays, &directions, &gains, &runtime_delay); - const std::size_t unique = directions.size() / 3u; - if (unique < terms) { - return field_fail(JOC_ERR_HRTF_FORMAT, - "coincident-direction merging left fewer than 36 directions"); - } - - std::vector basis; - real_spherical_harmonics(directions, unique, options.order, &basis); - const std::vector weights = spherical_voronoi_weights(directions, unique); - const std::vector coefficients = fit_complex( - basis, unique, kFieldTerms, weights, options.sh_ridge, gains, gains_per_direction); - const std::vector delay_coefficients = - fit_real(basis, unique, kFieldTerms, weights, options.sh_ridge, runtime_delay, 2u); - - // Reconstruction error of the reported fit. - std::vector relative_error; - std::vector magnitude_error_db; - std::vector delay_error; - relative_error.reserve(unique * kHybridBands); - magnitude_error_db.reserve(unique * kHybridBands); - delay_error.reserve(unique * 2u); - for (std::size_t row = 0u; row < unique; ++row) { - for (std::size_t ear = 0u; ear < 2u; ++ear) { - double reconstructed_delay = 0.0; - for (std::size_t term = 0u; term < terms; ++term) { - reconstructed_delay += basis[row * terms + term] * delay_coefficients[term * 2u + ear]; - } - const double reference_delay = runtime_delay[row * 2u + ear]; - delay_error.push_back(reconstructed_delay - reference_delay); - for (int band = 0; band < kHybridBands; ++band) { - Complex reconstructed_aligned(0.0, 0.0); - for (std::size_t term = 0u; term < terms; ++term) { - reconstructed_aligned += - basis[row * terms + term] * - coefficients[term * gains_per_direction + ear * kHybridBands + - static_cast(band)]; - } - const Complex reference = - gains[row * gains_per_direction + ear * kHybridBands + - static_cast(band)] * - std::polar(1.0, -2.0 * kPi * reference_delay * kBandCenters[band] / - canonical.sample_rate_hz); - const Complex reconstructed = - reconstructed_aligned * - std::polar(1.0, -2.0 * kPi * reconstructed_delay * kBandCenters[band] / - canonical.sample_rate_hz); - const double magnitude_reference = std::max(std::abs(reference), 1.0e-12); - relative_error.push_back(std::abs(reconstructed - reference) / magnitude_reference); - magnitude_error_db.push_back( - std::abs(20.0 * std::log10(std::max(std::abs(reconstructed), 1.0e-12)) - - 20.0 * std::log10(magnitude_reference))); - } - } - } - double delay_square_sum = 0.0; - double delay_maximum = 0.0; - for (const double value : delay_error) { - delay_square_sum += value * value; - delay_maximum = std::max(delay_maximum, std::abs(value)); - } - - // Delay bounds per ear, and the four arrays the cache stores. - std::vector delay_bounds(4u, 0.0); - for (std::size_t ear = 0u; ear < 2u; ++ear) { - double minimum = std::numeric_limits::infinity(); - double maximum = -std::numeric_limits::infinity(); - for (std::size_t row = 0u; row < unique; ++row) { - minimum = std::min(minimum, runtime_delay[row * 2u + ear]); - maximum = std::max(maximum, runtime_delay[row * 2u + ear]); - } - delay_bounds[ear * 2u] = minimum; - delay_bounds[ear * 2u + 1u] = maximum; - } - std::vector flat_coefficients(terms * 2u * kHybridBands * 2u, 0.0); - for (std::size_t term = 0u; term < terms; ++term) { - for (std::size_t ear = 0u; ear < 2u; ++ear) { - for (int band = 0; band < kHybridBands; ++band) { - const Complex value = - coefficients[term * gains_per_direction + ear * kHybridBands + - static_cast(band)]; - const std::size_t offset = - ((term * 2u + ear) * kHybridBands + static_cast(band)) * 2u; - flat_coefficients[offset] = value.real(); - flat_coefficients[offset + 1u] = value.imag(); - } - } - } - - Field field; - field.source_sha256 = to_upper(canonical.source_sha256); - field.source_display_name = basename_of(canonical.source_path); - field.measurement_radius_m = shell_radius; - field.order = options.order; - field.projection_ridge = options.projection_ridge; - field.spherical_harmonic_ridge = options.sh_ridge; - field.compiler_version = kCompilerVersion; - field.phase_policy_version = kPhasePolicyVersion; - field.sh_convention = kShConvention; - field.filterbank_json = filterbank_fingerprint_json(); - field.delay_source = aligned.delay_source; - field.band_centers_hz.assign(kBandCenters, kBandCenters + kHybridBands); - field.coefficients = std::move(flat_coefficients); - field.delay_coefficients = std::move(delay_coefficients); - field.delay_bounds = std::move(delay_bounds); - field.cache_key = compiled_hrtf_cache_key(field.source_sha256, canonical.sample_rate_hz, - shell_radius, options.order, - options.projection_ridge, options.sh_ridge); - field.fit_report_json = json_object({ - {"complex_relative_error_median", json_number(percentile(relative_error, 50.0))}, - {"complex_relative_error_p95", json_number(percentile(relative_error, 95.0))}, - {"delay_error_samples_max", json_number(delay_maximum)}, - {"delay_error_samples_rms", - json_number(std::sqrt(delay_square_sum / static_cast(delay_error.size())))}, - {"delay_source", json_escape(aligned.delay_source)}, - {"format", json_escape("SOFA FIR -> public 64-QMF/77-hybrid -> ACN/N3D real SH")}, - {"input_measurements", std::to_string(selected)}, - {"magnitude_error_db_median", json_number(percentile(magnitude_error_db, 50.0))}, - {"magnitude_error_db_p95", json_number(percentile(magnitude_error_db, 95.0))}, - {"order", std::to_string(options.order)}, - {"phase_policy_version", json_escape(kPhasePolicyVersion)}, - {"precision", json_escape("float64/complex128")}, - {"projection", - json_object({ - {"dictionary_shape", - json_array({std::to_string(canonical.taps), std::to_string(kParameterCount)})}, - {"embedded_delay_samples_max", json_number(maximum_of(selected_removed))}, - {"embedded_delay_samples_min", json_number(minimum_of(selected_removed))}, - {"fir_reconstruction_snr_db_median", json_number(percentile(signal_to_noise, 50.0))}, - {"fir_reconstruction_snr_db_min", json_number(minimum_of(signal_to_noise))}, - {"fir_reconstruction_snr_db_p05", json_number(percentile(signal_to_noise, 5.0))}, - {"maximum_absolute_hybrid_gain", json_number(maximum_gain)}, - {"method", json_escape("regularized public analysis/gain/synthesis dictionary")}, - {"precision", json_escape("float64/complex128")}, - {"real_parameters", std::to_string(kParameterCount)}, - {"ridge", json_number(options.projection_ridge)}, - })}, - {"shell_radius_m", json_number(shell_radius)}, - {"spherical_harmonic_ridge", json_number(options.sh_ridge)}, - {"terms", std::to_string(kFieldTerms)}, - {"unique_directions", std::to_string(unique)}, - }); - field.payload_sha256 = field_payload_sha256(field); - field.metadata_json = json_object({ - {"cache_key", json_escape(field.cache_key)}, - {"cache_key_version", "1"}, - {"cache_schema", json_escape(std::string(kCacheSchema))}, - {"compiler_version", json_escape(field.compiler_version)}, - {"delay_source", json_escape(field.delay_source)}, - {"filterbank", field.filterbank_json}, - {"fit_report", field.fit_report_json}, - {"format_version", std::to_string(kFormatVersion)}, - {"magic", json_escape(std::string(kMagic))}, - {"measurement_radius_m", json_number(field.measurement_radius_m)}, - {"order", std::to_string(field.order)}, - {"payload_sha256", json_escape(field.payload_sha256)}, - {"phase_policy_version", json_escape(field.phase_policy_version)}, - {"projection_ridge", json_number(field.projection_ridge)}, - {"sample_rate_hz", json_number(canonical.sample_rate_hz)}, - {"sh_convention", json_escape(field.sh_convention)}, - {"source_display_name", json_escape(field.source_display_name)}, - {"source_sha256", json_escape(field.source_sha256)}, - {"spherical_harmonic_ridge", json_number(field.spherical_harmonic_ridge)}, - }); - *out = std::move(field); - return Status::success(); -} - -void shell_directions_and_weights_for_check(const SofaHrir& sofa, double radius_m, - std::vector* directions, - std::vector* weights) { - CanonicalHrtf canonical; - if (!canonicalize_sofa(sofa, &canonical).ok()) { - return; - } - double actual = radius_m; - const std::vector indices = canonical_shell_indices(canonical, radius_m, &actual); - directions->assign(indices.size() * 3u, 0.0); - for (std::size_t row = 0u; row < indices.size(); ++row) { - for (int axis = 0; axis < 3; ++axis) { - (*directions)[row * 3u + static_cast(axis)] = - canonical.unit_directions[indices[row] * 3u + static_cast(axis)]; - } - } - *weights = spherical_voronoi_weights(*directions, indices.size()); -} -Status compile_sofa_field(const SofaHrir& sofa, const CompileOptions& options, Field* out) { - CanonicalHrtf canonical; - const Status status = canonicalize_sofa(sofa, &canonical); - if (!status.ok()) { - return status; - } - return compile_canonical_field(canonical, options, out); -} - -} // namespace joc::hrtf diff --git a/src/hrtf/sofa_field.h b/src/hrtf/sofa_field.h deleted file mode 100644 index 61313ba..0000000 --- a/src/hrtf/sofa_field.h +++ /dev/null @@ -1,106 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "foundation/status.h" -#include "hrtf/jochrtf.h" -#include "hrtf/sofa.h" - -// SOFA SimpleFreeFieldHRIR -> compiled directional field, ported from the -// reference chain (sofa_canonical.py + sofa_hrtf_field.py + the public -// filterbank): the measurement shell is selected, one delay representation is -// separated, the FIRs are projected onto the 64-QMF/77-hybrid filterbank and the -// result is fitted with fifth-order ACN/N3D real spherical harmonics. -namespace joc::hrtf { - -inline constexpr int kFieldOrder = 5; -inline constexpr int kFieldTerms = 36; -inline constexpr double kFieldSampleRateHz = 48000.0; -inline constexpr double kDefaultShellRadiusM = 1.0; -inline constexpr double kDefaultProjectionRidge = 1.0e-3; -inline constexpr double kDefaultSphericalHarmonicRidge = 1.0e-5; -inline constexpr const char* kCompilerVersion = "joc-sofa-compiler-v1"; -inline constexpr const char* kPhasePolicyVersion = "sofa-delay-exactly-once-v1"; -inline constexpr const char* kShConvention = "ACN/N3D real"; -inline constexpr const char* kFilterbankTableVersion = "joc-public-64qmf-77hybrid-v1"; -// SHA-256 of the standard filterbank archive the embedded tables came from. It -// participates in the cache key, so it is part of the file-format contract. -inline constexpr const char* kFilterbankArchiveSha256 = - "C05BEF4D26E96ECBD4694E2572F05DA400255C777BA5047300B9D3B1F81081CD"; - -struct CompileOptions { - double shell_radius_m = kDefaultShellRadiusM; - int order = kFieldOrder; - double projection_ridge = kDefaultProjectionRidge; - double sh_ridge = kDefaultSphericalHarmonicRidge; -}; - -// Canonical HRIR set: Data.IR and Data.Delay stay separate, the listener frame is -// applied to the source positions and the ears are ordered left/right. -struct CanonicalHrtf { - std::string source_path; - std::string source_sha256; - std::string convention; - std::string convention_version; - std::string processing_label; - double sample_rate_hz = 0.0; - std::uint32_t measurements = 0; - std::uint32_t taps = 0; - int left_receiver_index = 0; - int right_receiver_index = 1; - std::vector source_position_cartesian_m; // [M,3] listener-local - std::vector unit_directions; // [M,3] - std::vector measurement_radius_m; // [M] - std::vector hrir; // [M,2,N] canonical L/R - std::vector delay_samples; // [M,2], not applied - // ReceiverPosition in listener-local metres, left then right (the SOFA - // variable is one constant pair for the whole file). - std::vector receiver_position_cartesian_m; // [2,3] -}; - -// Port of load_simple_free_field_hrir(): strict SimpleFreeFieldHRIR import. -Status canonicalize_sofa(const SofaHrir& sofa, CanonicalHrtf* out); - -// Compiles the canonical set into the runtime field (port of SofaHrtfField.fit). -Status compile_sofa_field(const SofaHrir& sofa, const CompileOptions& options, Field* out); - -// The measurements on the shell nearest to radius_m; actual_radius_m receives the -// mean radius of that shell (upstream CanonicalHrtf.shell_indices). -std::vector canonical_shell_indices(const CanonicalHrtf& canonical, double radius_m, - double* actual_radius_m); - -// Compiles an already canonicalized set (used by tests and the cache layer). -Status compile_canonical_field(const CanonicalHrtf& canonical, const CompileOptions& options, - Field* out); - -// Configuration hash that names the cache file (upstream compiled_hrtf_cache_key). -std::string compiled_hrtf_cache_key(const std::string& source_sha256, double sample_rate_hz, - double shell_radius_m, int order, double projection_ridge, - double sh_ridge); - -// Payload hash over the four arrays (upstream _payload_sha256). -std::string field_payload_sha256(const Field& field); - -// "..jochrtf", the upstream cache file name. -std::string cache_file_name(const std::string& display_name, const std::string& cache_key); - -// Serializes the field as a .jochrtf cache the upstream loader also accepts. -Status write_jochrtf(const Field& field, const std::string& path); - -// The analysis/gain/synthesis dictionary the projection solves against (dev check). -std::vector hybrid_gain_synthesis_dictionary_for_check(std::size_t sample_count); - -// Shell directions and their spherical Voronoi weights (dev check). -void shell_directions_and_weights_for_check(const SofaHrir& sofa, double radius_m, - std::vector* directions, - std::vector* weights); - -// PublicAnalysis77 on a unit impulse, interleaved complex (dev check). -std::vector analysis_impulse_for_check(std::size_t total_samples); - -// The 77 hybrid-band centre frequencies at 48 kHz. -const std::vector& hybrid_band_center_frequencies_hz(); - -} // namespace joc::hrtf diff --git a/src/hrtf/spherical_mesh.cpp b/src/hrtf/spherical_mesh.cpp deleted file mode 100644 index f093dfd..0000000 --- a/src/hrtf/spherical_mesh.cpp +++ /dev/null @@ -1,531 +0,0 @@ - -#include "hrtf/spherical_mesh.h" - -#include -#include -#include -#include - -namespace joc::hrtf { -namespace { - -constexpr double kPi = 3.141592653589793238462643383279502884; - -Status mesh_error(const char* message) { - return Status::fail(JOC_ERR_INVALID_ARGUMENT, joc::stage::kRender, message); -} - -void normalize(double vector[3]) { - const double length = std::sqrt(vector[0] * vector[0] + vector[1] * vector[1] + - vector[2] * vector[2]); - if (length > 0.0) { - vector[0] /= length; - vector[1] /= length; - vector[2] /= length; - } -} - -void cross(const double a[3], const double b[3], double out[3]) { - out[0] = a[1] * b[2] - a[2] * b[1]; - out[1] = a[2] * b[0] - a[0] * b[2]; - out[2] = a[0] * b[1] - a[1] * b[0]; -} - -double dot(const double a[3], const double b[3]) { - return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; -} - -// Solid angle of the spherical triangle (a, b, c), Van Oosterom & Strackee. -double triangle_area(const double a[3], const double b[3], const double c[3]) { - const double determinant = a[0] * (b[1] * c[2] - b[2] * c[1]) - - a[1] * (b[0] * c[2] - b[2] * c[0]) + - a[2] * (b[0] * c[1] - b[1] * c[0]); - const double denominator = 1.0 + dot(a, b) + dot(b, c) + dot(c, a); - return 2.0 * std::atan2(std::fabs(determinant), denominator); -} - -// In-place inverse of a row-major 3x3 matrix. Returns false when singular. -bool invert3(const double matrix[9], double out[9]) { - const double c00 = matrix[4] * matrix[8] - matrix[5] * matrix[7]; - const double c01 = matrix[5] * matrix[6] - matrix[3] * matrix[8]; - const double c02 = matrix[3] * matrix[7] - matrix[4] * matrix[6]; - const double determinant = matrix[0] * c00 + matrix[1] * c01 + matrix[2] * c02; - if (!std::isfinite(determinant) || std::fabs(determinant) < 1e-12) { - return false; - } - const double inverse = 1.0 / determinant; - out[0] = c00 * inverse; - out[1] = (matrix[2] * matrix[7] - matrix[1] * matrix[8]) * inverse; - out[2] = (matrix[1] * matrix[5] - matrix[2] * matrix[4]) * inverse; - out[3] = c01 * inverse; - out[4] = (matrix[0] * matrix[8] - matrix[2] * matrix[6]) * inverse; - out[5] = (matrix[2] * matrix[3] - matrix[0] * matrix[5]) * inverse; - out[6] = c02 * inverse; - out[7] = (matrix[1] * matrix[6] - matrix[0] * matrix[7]) * inverse; - out[8] = (matrix[0] * matrix[4] - matrix[1] * matrix[3]) * inverse; - return true; -} - -struct HullFace { - int vertex[3] = {0, 0, 0}; - double normal[3] = {0.0, 0.0, 0.0}; - bool alive = true; -}; - -} // namespace - -Status SphericalMesh::build(const std::vector& directions, std::size_t count) { - if (count < 4 || directions.size() < count * 3) { - return mesh_error("spherical mesh needs at least four directions"); - } - directions_.clear(); - faces_.clear(); - inverse_.clear(); - max_triangle_edge_degrees_ = 0.0; - - // Merge coincident directions, keeping the first occurrence (reference order). - std::vector rounded(count * 3); - for (std::size_t index = 0; index < count * 3; ++index) { - rounded[index] = std::round(directions[index] * 1e10) / 1e10; - } - std::vector kept; - std::size_t slot_count = 0; - for (std::size_t index = 0; index < count; ++index) { - std::size_t found = slot_count; - for (std::size_t slot = 0; slot < kept.size(); ++slot) { - const std::size_t first = kept[slot]; - if (rounded[first * 3] == rounded[index * 3] && - rounded[first * 3 + 1] == rounded[index * 3 + 1] && - rounded[first * 3 + 2] == rounded[index * 3 + 2]) { - found = slot; - break; - } - } - if (found == slot_count) { - kept.push_back(index); - ++slot_count; - } - } - if (kept.size() < 4) { - return mesh_error("spherical mesh needs four distinct directions"); - } - directions_.resize(kept.size() * 3); - for (std::size_t slot = 0; slot < kept.size(); ++slot) { - double value[3] = {directions[kept[slot] * 3], directions[kept[slot] * 3 + 1], - directions[kept[slot] * 3 + 2]}; - if (!std::isfinite(value[0]) || !std::isfinite(value[1]) || !std::isfinite(value[2])) { - return mesh_error("measurement direction is not finite"); - } - normalize(value); - std::copy(value, value + 3, directions_.begin() + static_cast(slot * 3)); - } - build_faces(); - compute_face_inverses(); - return Status::success(); -} - -void SphericalMesh::build_faces() { - const std::size_t count = vertex_count(); - const auto point = [this](std::size_t index) { - return directions_.data() + index * 3; - }; - - // Initial tetrahedron: the farthest pair, then the farthest point from that - // line, then the farthest point from that plane. - std::size_t i0 = 0; - std::size_t i1 = 0; - double best = -1.0; - for (std::size_t index = 0; index < count; ++index) { - const double dx = point(index)[0] - point(i0)[0]; - const double dy = point(index)[1] - point(i0)[1]; - const double dz = point(index)[2] - point(i0)[2]; - const double distance = dx * dx + dy * dy + dz * dz; - if (distance > best) { - best = distance; - i1 = index; - } - } - if (best <= 0.0) { - return; - } - std::size_t i2 = 0; - best = -1.0; - double edge[3]; - for (std::size_t index = 0; index < count; ++index) { - double a[3]; - double b[3]; - for (int axis = 0; axis < 3; ++axis) { - a[axis] = point(i1)[axis] - point(i0)[axis]; - b[axis] = point(index)[axis] - point(i0)[axis]; - } - cross(a, b, edge); - const double area = dot(edge, edge); - if (area > best) { - best = area; - i2 = index; - } - } - if (best <= 1e-24) { - return; - } - std::size_t i3 = 0; - best = -1.0; - double plane[3]; - { - double a[3]; - double b[3]; - for (int axis = 0; axis < 3; ++axis) { - a[axis] = point(i1)[axis] - point(i0)[axis]; - b[axis] = point(i2)[axis] - point(i0)[axis]; - } - cross(a, b, plane); - } - for (std::size_t index = 0; index < count; ++index) { - double delta[3]; - for (int axis = 0; axis < 3; ++axis) { - delta[axis] = point(index)[axis] - point(i0)[axis]; - } - const double volume = std::fabs(dot(plane, delta)); - if (volume > best) { - best = volume; - i3 = index; - } - } - if (best <= 1e-24) { - return; - } - - // Centroid of the tetrahedron is strictly inside the hull, so a face normal is - // outward when it points away from it. - double centroid[3] = {0.0, 0.0, 0.0}; - const std::size_t seed[4] = {i0, i1, i2, i3}; - for (std::size_t index = 0; index < 4; ++index) { - for (int axis = 0; axis < 3; ++axis) { - centroid[axis] += point(seed[index])[axis] * 0.25; - } - } - std::vector faces; - faces.reserve(count * 2); - const int seed_index[4] = {static_cast(i0), static_cast(i1), - static_cast(i2), static_cast(i3)}; - const int initial[4][3] = {{0, 1, 2}, {0, 1, 3}, {0, 2, 3}, {1, 2, 3}}; - for (const int* triple : initial) { - HullFace face; - for (int corner = 0; corner < 3; ++corner) { - face.vertex[corner] = seed_index[triple[corner]]; - } - double a[3]; - double b[3]; - for (int axis = 0; axis < 3; ++axis) { - a[axis] = point(face.vertex[1])[axis] - point(face.vertex[0])[axis]; - b[axis] = point(face.vertex[2])[axis] - point(face.vertex[0])[axis]; - } - cross(a, b, face.normal); - double to_center[3]; - for (int axis = 0; axis < 3; ++axis) { - to_center[axis] = centroid[axis] - point(face.vertex[0])[axis]; - } - if (dot(face.normal, to_center) > 0.0) { - std::swap(face.vertex[1], face.vertex[2]); - for (int axis = 0; axis < 3; ++axis) { - face.normal[axis] = -face.normal[axis]; - } - } - faces.push_back(face); - } - - struct Edge { - int a; - int b; - int count; - }; - std::vector boundary; - std::vector visible; - for (std::size_t index = 0; index < count; ++index) { - const double* p = point(index); - bool seed_point = false; - for (int corner = 0; corner < 4; ++corner) { - if (seed_index[corner] == static_cast(index)) { - seed_point = true; - break; - } - } - if (seed_point) { - continue; - } - visible.clear(); - for (std::size_t face_index = 0; face_index < faces.size(); ++face_index) { - HullFace& face = faces[face_index]; - if (!face.alive) { - continue; - } - double delta[3]; - for (int axis = 0; axis < 3; ++axis) { - delta[axis] = p[axis] - point(face.vertex[0])[axis]; - } - if (dot(face.normal, delta) > 1e-12) { - visible.push_back(face_index); - } - } - if (visible.empty()) { - continue; - } - boundary.clear(); - const auto add_edge = [&boundary](int a, int b) { - for (Edge& edge : boundary) { - if ((edge.a == a && edge.b == b) || (edge.a == b && edge.b == a)) { - ++edge.count; - return; - } - } - boundary.push_back(Edge{a, b, 1}); - }; - for (const std::size_t face_index : visible) { - const HullFace& face = faces[face_index]; - add_edge(face.vertex[0], face.vertex[1]); - add_edge(face.vertex[1], face.vertex[2]); - add_edge(face.vertex[2], face.vertex[0]); - } - for (const std::size_t face_index : visible) { - faces[face_index].alive = false; - } - for (const Edge& edge : boundary) { - if (edge.count != 1) { - continue; - } - HullFace face; - face.vertex[0] = edge.a; - face.vertex[1] = edge.b; - face.vertex[2] = static_cast(index); - double a[3]; - double b[3]; - for (int axis = 0; axis < 3; ++axis) { - a[axis] = point(face.vertex[1])[axis] - point(face.vertex[0])[axis]; - b[axis] = point(face.vertex[2])[axis] - point(face.vertex[0])[axis]; - } - cross(a, b, face.normal); - double inside[3]; - for (int axis = 0; axis < 3; ++axis) { - inside[axis] = centroid[axis] - point(face.vertex[0])[axis]; - } - if (dot(face.normal, inside) > 0.0) { - std::swap(face.vertex[1], face.vertex[2]); - for (int axis = 0; axis < 3; ++axis) { - face.normal[axis] = -face.normal[axis]; - } - } - faces.push_back(face); - } - } - - faces_.clear(); - max_triangle_edge_degrees_ = 0.0; - for (const HullFace& face : faces) { - if (!face.alive) { - continue; - } - faces_.push_back(face.vertex[0]); - faces_.push_back(face.vertex[1]); - faces_.push_back(face.vertex[2]); - const double* a = point(face.vertex[0]); - const double* b = point(face.vertex[1]); - const double* c = point(face.vertex[2]); - for (int first = 0; first < 3; ++first) { - for (int second = first + 1; second < 3; ++second) { - const double* u = point(face.vertex[first]); - const double* v = point(face.vertex[second]); - const double edge_dot = std::clamp(dot(u, v), -1.0, 1.0); - const double degrees = std::acos(edge_dot) * 180.0 / kPi; - max_triangle_edge_degrees_ = std::max(max_triangle_edge_degrees_, degrees); - } - } - } -} - -void SphericalMesh::compute_face_inverses() { - inverse_.assign(face_count() * 9, 0.0); - std::vector kept; - for (std::size_t face_index = 0; face_index < face_count(); ++face_index) { - const int* ids = faces_.data() + face_index * 3; - double matrix[9]; - // Columns are the vertices: the barycentric weights of q are the solution - // of matrix * w = q, so the inverse is applied to the query afterwards. - for (int corner = 0; corner < 3; ++corner) { - const double* vertex = directions_.data() + ids[corner] * 3; - for (int axis = 0; axis < 3; ++axis) { - matrix[axis * 3 + corner] = vertex[axis]; - } - } - if (!invert3(matrix, inverse_.data() + face_index * 9)) { - continue; - } - kept.push_back(static_cast(face_index)); - } - if (kept.size() != face_count()) { - // Drop singular faces: they cannot contain a query direction strictly. - std::vector compact; - std::vector compact_inverse; - for (const int face_index : kept) { - for (int corner = 0; corner < 3; ++corner) { - compact.push_back(faces_[face_index * 3 + corner]); - } - for (int value = 0; value < 9; ++value) { - compact_inverse.push_back(inverse_[face_index * 9 + value]); - } - } - faces_ = compact; - inverse_ = compact_inverse; - } -} - -std::size_t SphericalMesh::nearest(const double direction[3], double* distance) const { - const std::size_t count = vertex_count(); - std::size_t best = 0; - double best_distance = std::numeric_limits::infinity(); - for (std::size_t index = 0; index < count; ++index) { - const double* vertex = directions_.data() + index * 3; - const double dx = vertex[0] - direction[0]; - const double dy = vertex[1] - direction[1]; - const double dz = vertex[2] - direction[2]; - const double squared = dx * dx + dy * dy + dz * dz; - if (squared < best_distance) { - best_distance = squared; - best = index; - } - } - if (distance != nullptr) { - *distance = std::sqrt(best_distance); - } - return best; -} - -Status SphericalMesh::weights(const double direction[3], std::vector* ids, - std::vector* weights) const { - if (ids == nullptr || weights == nullptr) { - return mesh_error("weight output is null"); - } - double query[3] = {direction[0], direction[1], direction[2]}; - const double length = std::sqrt(dot(query, query)); - if (!std::isfinite(length) || length <= 1e-12) { - return mesh_error("query direction is degenerate"); - } - normalize(query); - double distance = 0.0; - const std::size_t nearest_index = nearest(query, &distance); - ids->clear(); - weights->clear(); - if (distance < 1e-10) { - ids->push_back(static_cast(nearest_index)); - weights->push_back(1.0); - return Status::success(); - } - for (std::size_t face_index = 0; face_index < face_count(); ++face_index) { - const double* inverse = inverse_.data() + face_index * 9; - const double barycentric[3] = { - inverse[0] * query[0] + inverse[1] * query[1] + inverse[2] * query[2], - inverse[3] * query[0] + inverse[4] * query[1] + inverse[5] * query[2], - inverse[6] * query[0] + inverse[7] * query[1] + inverse[8] * query[2]}; - if (std::min({barycentric[0], barycentric[1], barycentric[2]}) < -1e-10) { - continue; - } - double total = 0.0; - double clamped[3]; - for (int corner = 0; corner < 3; ++corner) { - clamped[corner] = std::max(barycentric[corner], 0.0); - total += clamped[corner]; - } - if (total <= 0.0) { - continue; - } - for (int corner = 0; corner < 3; ++corner) { - ids->push_back(faces_[face_index * 3 + corner]); - weights->push_back(clamped[corner] / total); - } - return Status::success(); - } - // The query fell outside every triangle (only possible on numerical margins). - ids->push_back(static_cast(nearest_index)); - weights->push_back(1.0); - return Status::success(); -} - -void SphericalMesh::voronoi_areas(std::vector* areas) const { - const std::size_t vertices = vertex_count(); - const std::size_t face_total = face_count(); - areas->assign(vertices, 0.0); - if (vertices == 0 || face_total == 0) { - return; - } - // Circumcenter of a triangle of unit vectors is its normalized face normal. - std::vector circumcenters(face_total * 3, 0.0); - for (std::size_t face_index = 0; face_index < face_total; ++face_index) { - const int* ids = faces_.data() + face_index * 3; - const double* a = directions_.data() + ids[0] * 3; - const double* b = directions_.data() + ids[1] * 3; - const double* c = directions_.data() + ids[2] * 3; - double normal[3]; - double edge_one[3]; - double edge_two[3]; - for (int axis = 0; axis < 3; ++axis) { - edge_one[axis] = b[axis] - a[axis]; - edge_two[axis] = c[axis] - a[axis]; - } - cross(edge_one, edge_two, normal); - normalize(normal); - std::copy(normal, normal + 3, - circumcenters.begin() + static_cast(face_index * 3)); - } - std::vector> incident(vertices); - for (std::size_t face_index = 0; face_index < face_total; ++face_index) { - for (int corner = 0; corner < 3; ++corner) { - incident[static_cast(faces_[face_index * 3 + corner])] - .push_back(face_index); - } - } - std::vector> ordered; - double total = 0.0; - for (std::size_t vertex = 0; vertex < vertices; ++vertex) { - const double* centre = directions_.data() + vertex * 3; - if (incident[vertex].size() < 3) { - continue; - } - // Tangent basis at the vertex. - double tangent[3] = {0.0, 0.0, 0.0}; - if (std::fabs(centre[0]) < 0.9) { - tangent[0] = 1.0; - } else { - tangent[1] = 1.0; - } - const double projection = dot(tangent, centre); - double axis_one[3]; - double axis_two[3]; - for (int axis = 0; axis < 3; ++axis) { - axis_one[axis] = tangent[axis] - projection * centre[axis]; - } - normalize(axis_one); - cross(centre, axis_one, axis_two); - ordered.clear(); - for (const std::size_t face_index : incident[vertex]) { - const double* point = circumcenters.data() + face_index * 3; - const double angle = std::atan2(dot(point, axis_two), dot(point, axis_one)); - ordered.emplace_back(angle, face_index); - } - std::sort(ordered.begin(), ordered.end()); - double area = 0.0; - for (std::size_t index = 0; index < ordered.size(); ++index) { - const double* first = circumcenters.data() + ordered[index].second * 3; - const double* second = - circumcenters.data() + ordered[(index + 1) % ordered.size()].second * 3; - area += triangle_area(centre, first, second); - } - (*areas)[vertex] = area; - total += area; - } - if (total > 0.0) { - for (double& value : *areas) { - value /= total; - } - } -} - -} // namespace joc::hrtf diff --git a/src/hrtf/spherical_mesh.h b/src/hrtf/spherical_mesh.h deleted file mode 100644 index c292555..0000000 --- a/src/hrtf/spherical_mesh.h +++ /dev/null @@ -1,50 +0,0 @@ - -#pragma once - -#include -#include - -#include "foundation/status.h" - -// Spherical interpolation mesh over the measurement directions, ported from the -// reference sofa_hrir.FullHrirField: the convex hull of the unit directions gives -// the containing spherical triangle, its barycentric weights give the local -// interpolation, and the spherical Voronoi cells give the centre weighting. -namespace joc::hrtf { - -class SphericalMesh { -public: - // `directions` is [count][3]; entries need not be unit length. Coincident - // directions are merged (first occurrence wins) and their duplicates must be - // identical, as the reference requires. - Status build(const std::vector& directions, std::size_t count); - - std::size_t vertex_count() const { return directions_.size() / 3; } - std::size_t face_count() const { return faces_.size() / 3; } - const std::vector& directions() const { return directions_; } - const std::vector& faces() const { return faces_; } - double max_triangle_edge_degrees() const { return max_triangle_edge_degrees_; } - - // Barycentric interpolation weights of a query direction: an exact measurement - // returns one id with weight 1, otherwise the containing triangle's vertices - // with non-negative weights summing to one. - Status weights(const double direction[3], std::vector* ids, - std::vector* weights) const; - - // Spherical Voronoi area of every vertex, normalized to sum to one. - void voronoi_areas(std::vector* areas) const; - - // Nearest measurement direction (exact search; the vertex count is small). - std::size_t nearest(const double direction[3], double* distance) const; - -private: - void build_faces(); - void compute_face_inverses(); - - std::vector directions_; // [V][3] unit - std::vector faces_; // [F][3] - std::vector inverse_; // [F][9] row-major inverse of the vertex matrix - double max_triangle_edge_degrees_ = 0.0; -}; - -} // namespace joc::hrtf diff --git a/src/joc_bitstream/bed_layout_map.cpp b/src/joc_bitstream/bed_layout_map.cpp index d3a0e1d..d5aae8d 100644 --- a/src/joc_bitstream/bed_layout_map.cpp +++ b/src/joc_bitstream/bed_layout_map.cpp @@ -3,6 +3,8 @@ #include +#include "speaker/speaker_layouts.h" + namespace joc::joc { namespace { @@ -29,16 +31,16 @@ constexpr StandardBit kStandardBits[10] = { {BedChannel::kLfe2, BedChannel::kCount}, }; -// Table 13 的 17 bit 非标准掩码,按 channel order 排列:RC_L 是最先的声道 -// (array position 16),落在 LSB;RC_LFE2 最后(array position 0)。 +// Table 13 的 17 bit 非标准掩码(LSB 在前)。 constexpr BedChannel kNonStandardBits[17] = { - BedChannel::kLeft, BedChannel::kRight, BedChannel::kCenter, - BedChannel::kLfe, BedChannel::kLeftSurround, BedChannel::kRightSurround, - BedChannel::kLeftRearSurround, BedChannel::kRightRearSurround, - BedChannel::kTopFrontLeft, BedChannel::kTopFrontRight, - BedChannel::kTopSideLeft, BedChannel::kTopSideRight, - BedChannel::kTopBackLeft, BedChannel::kTopBackRight, - BedChannel::kLeftWide, BedChannel::kRightWide, BedChannel::kLfe2, + BedChannel::kLfe2, BedChannel::kRightWide, BedChannel::kLeftWide, + BedChannel::kTopBackRight, BedChannel::kTopBackLeft, + BedChannel::kTopSideRight, BedChannel::kTopSideLeft, + BedChannel::kTopFrontRight, BedChannel::kTopFrontLeft, + BedChannel::kRightRearSurround, BedChannel::kLeftRearSurround, + BedChannel::kRightSurround, BedChannel::kLeftSurround, + BedChannel::kLfe, BedChannel::kCenter, BedChannel::kRight, + BedChannel::kLeft, }; struct ChannelSpec { @@ -48,27 +50,24 @@ struct ChannelSpec { double xyz[3]; }; -// 固定方位:ETSI TS 103 420 V1.2.1 clause B.2.1.4 Table B.10 的 ADM 笛卡尔坐标 -// (x 右、y 前、z 上)。bed 声道的位置只由声道标签决定,与目标输出布局无关。 -// Table B.10 把 Lw/Rw 的 Y 记作 0,677419,即 ADM 62 级网格上的 42/62 = 21/31。 constexpr ChannelSpec kChannels[] = { {BedChannel::kLeft, "L", "RC_L", {-1.0, 1.0, 0.0}}, {BedChannel::kRight, "R", "RC_R", {1.0, 1.0, 0.0}}, {BedChannel::kCenter, "C", "RC_C", {0.0, 1.0, 0.0}}, - {BedChannel::kLfe, "LFE", "RC_LFE", {-1.0, 1.0, -1.0}}, + {BedChannel::kLfe, "LFE", "RC_LFE", {0.0, 0.0, 0.0}}, {BedChannel::kLeftSurround, "Ls", "RC_LS", {-1.0, 0.0, 0.0}}, {BedChannel::kRightSurround, "Rs", "RC_RS", {1.0, 0.0, 0.0}}, {BedChannel::kLeftRearSurround, "Lrs", "RC_LB", {-1.0, -1.0, 0.0}}, {BedChannel::kRightRearSurround, "Rrs", "RC_RB", {1.0, -1.0, 0.0}}, - {BedChannel::kTopFrontLeft, "Ltf", "RC_TFL", {-1.0, 1.0, 1.0}}, - {BedChannel::kTopFrontRight, "Rtf", "RC_TFR", {1.0, 1.0, 1.0}}, + {BedChannel::kTopFrontLeft, "Ltf", "RC_TFL", {-0.5, 0.5, 1.0}}, + {BedChannel::kTopFrontRight, "Rtf", "RC_TFR", {0.5, 0.5, 1.0}}, {BedChannel::kTopSideLeft, "Ltm", "RC_TSL", {-1.0, 0.0, 1.0}}, {BedChannel::kTopSideRight, "Rtm", "RC_TSR", {1.0, 0.0, 1.0}}, - {BedChannel::kTopBackLeft, "Ltr", "RC_TBL", {-1.0, -1.0, 1.0}}, - {BedChannel::kTopBackRight, "Rtr", "RC_TBR", {1.0, -1.0, 1.0}}, - {BedChannel::kLeftWide, "Lw", "RC_LW", {-1.0, 21.0 / 31.0, 0.0}}, - {BedChannel::kRightWide, "Rw", "RC_RW", {1.0, 21.0 / 31.0, 0.0}}, - {BedChannel::kLfe2, "LFE2", "RC_LFE2", {1.0, 1.0, -1.0}}, + {BedChannel::kTopBackLeft, "Ltr", "RC_TBL", {-0.5, -0.5, 1.0}}, + {BedChannel::kTopBackRight, "Rtr", "RC_TBR", {0.5, -0.5, 1.0}}, + {BedChannel::kLeftWide, "Lw", "RC_LW", {-1.0, 0.5, 0.0}}, + {BedChannel::kRightWide, "Rw", "RC_RW", {1.0, 0.5, 0.0}}, + {BedChannel::kLfe2, "LFE2", "RC_LFE2", {0.0, 0.0, 0.0}}, }; const ChannelSpec* spec_of(BedChannel channel) { @@ -169,6 +168,38 @@ const char* layout_name_for(std::uint32_t mask) { return ""; } +// 每个扬声器布局的标准声道名(按该布局的标准声道顺序排列)。 +struct LayoutChannels { + std::uint32_t out_ch_config; + std::uint32_t count; + const char* names[16]; +}; + +constexpr LayoutChannels kLayoutChannels[] = { + {0, 2, {"L", "R"}}, + {3, 4, {"L", "R", "C", "LFE"}}, + {255, 4, {"L", "R", "Lrs", "Rrs"}}, + {7, 6, {"L", "R", "C", "LFE", "Ls", "Rs"}}, + {11, 8, {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs"}}, + {13, 8, {"L", "R", "C", "LFE", "Ls", "Rs", "Ltm", "Rtm"}}, + {14, 10, {"L", "R", "C", "LFE", "Ls", "Rs", "Ltf", "Rtf", "Ltr", "Rtr"}}, + {15, 10, {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs", "Ltm", "Rtm"}}, + {16, 12, {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs", "Ltf", "Rtf", "Ltr", "Rtr"}}, + {19, 14, {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs", "Lw", "Rw", + "Ltf", "Rtf", "Ltr", "Rtr"}}, + {20, 16, {"L", "R", "C", "LFE", "Ls", "Rs", "Lrs", "Rrs", "Lw", "Rw", + "Ltf", "Rtf", "Ltm", "Rtm", "Ltr", "Rtr"}}, +}; + +const ejoc::speaker_tables::LayoutGeometry* geometry_for(std::uint32_t out_ch_config) { + for (const ejoc::speaker_tables::LayoutGeometry& layout : ejoc::speaker_tables::kLayouts) { + if (layout.out_ch_config == out_ch_config) { + return &layout; + } + } + return nullptr; +} + } // namespace BedLayout resolve_bed_layout(const std::vector& assignments, @@ -253,4 +284,48 @@ bool bed_channel_q15(BedChannel channel, std::uint16_t q15[3]) { return true; } +bool layout_bed_anchor(std::uint32_t out_ch_config, BedChannel channel, + std::uint16_t q15[3]) { + if (q15 == nullptr) { + return false; + } + const char* name = bed_channel_short_name(channel); + if (name == nullptr || name[0] == '\0' || std::strcmp(name, "LFE") == 0) { + return false; + } + const LayoutChannels* table = nullptr; + for (const LayoutChannels& entry : kLayoutChannels) { + if (entry.out_ch_config == out_ch_config) { + table = &entry; + break; + } + } + const ejoc::speaker_tables::LayoutGeometry* geometry = geometry_for(out_ch_config); + if (table == nullptr || geometry == nullptr) { + return false; + } + int standard_index = -1; + for (std::uint32_t index = 0; index < table->count; ++index) { + if (std::strcmp(table->names[index], name) == 0) { + standard_index = static_cast(index); + break; + } + } + if (standard_index < 0) { + return false; + } + const std::uint8_t internal = geometry->standard_from_internal[standard_index]; + const ejoc::speaker_tables::RegionGeometry& region = geometry->regions[0]; + for (std::uint32_t point = 0; point < region.point_count; ++point) { + if (region.points[point].speaker_id != internal) { + continue; + } + for (int axis = 0; axis < 3; ++axis) { + q15[axis] = region.points[point].coordinate_q15[axis]; + } + return true; + } + return false; +} + } // namespace joc::joc diff --git a/src/joc_bitstream/bed_layout_map.h b/src/joc_bitstream/bed_layout_map.h index 0936fa6..306c2d3 100644 --- a/src/joc_bitstream/bed_layout_map.h +++ b/src/joc_bitstream/bed_layout_map.h @@ -57,8 +57,12 @@ const char* bed_channel_short_name(BedChannel channel); const char* bed_channel_label(BedChannel channel); // 固定方位:ADM 笛卡尔坐标(x 右、y 前、z 上)与渲染器使用的 Q15 方位。 -// 位置只由声道标签决定(ETSI TS 103 420 Table B.10),与目标输出布局无关。 bool bed_channel_adm_position(BedChannel channel, double xyz[3]); bool bed_channel_q15(BedChannel channel, std::uint16_t q15[3]); +// 目标布局里同名扬声器的 Q15 方位:bed 声道直连到该扬声器,而不是参与声像。 +// 目标布局没有这个声道时返回 false。 +bool layout_bed_anchor(std::uint32_t out_ch_config, BedChannel channel, + std::uint16_t q15[3]); + } // namespace joc::joc diff --git a/src/stream/stream.cpp b/src/stream/stream.cpp index ed18f67..8112ba2 100644 --- a/src/stream/stream.cpp +++ b/src/stream/stream.cpp @@ -7,9 +7,7 @@ #include "adm/adm_metadata.h" #include "foundation/status.h" #include "hrtf/jochrtf.h" -#include "binaural/direct_sofa_runtime.h" #include "hrtf/rosella_model.h" -#include "hrtf/sofa_cache.h" #include "joc_bitstream/bed_layout_map.h" #include "joc_bitstream/joc_parser.h" #include "joc_core/objects16.h" @@ -65,9 +63,6 @@ void Stream::reset_state() { if (binaural_ready_) { binaural_.reset(); } - if (sofa_direct_ready_) { - sofa_direct_.reset(); - } if (rosella_ready_) { rosella_.reset(); } @@ -147,30 +142,6 @@ Status Stream::create(const Config& config) { hrtf::Field field; hrtf::Kernels kernels; Status status = Status::success(); - if (!config_.hrtf_sofa_path.empty()) { - // A SOFA renders from its full HRIRs; the .jochrtf stays the - // compiled input of hrtf_path. - binaural::DirectSofaOptions options; - options.mode = config_.binaural_mode == JOC_BINAURAL_NEAR - ? "near" - : (config_.binaural_mode == JOC_BINAURAL_FAR ? "far" : "mid"); - options.has_reference_distance = config_.source_reference_distance_m > 0.0; - options.reference_distance_m = config_.source_reference_distance_m; - options.has_shell_radius = config_.hrtf_radius_m > 0.0; - options.shell_radius_m = config_.hrtf_radius_m; - options.sofa_room = config_.sofa_room != 0u; - options.room_preset = config_.sofa_room_preset; - options.object_delay_samples = config_.object_delay_samples; - options.tail_seconds = config_.tail_seconds; - status = sofa_direct_.open(config_.hrtf_sofa_path, options); - if (status.ok()) { - sofa_direct_ready_ = true; - output_channels_ = 2; - return Status::success(); - } - return Status::fail(status.code(), stage::kRender, - "binaural setup failed: " + status.message()); - } status = hrtf::load_jochrtf(config_.hrtf_path, &field); if (status.ok()) { status = config_.kernels_path.empty() @@ -184,7 +155,10 @@ Status Stream::create(const Config& config) { profile = binaural::Profile::Far; } if (status.ok()) { - status = binaural_.open(field, kernels, profile); + binaural::RoomConstants room; + room.enable_early_reflections = config_.jochrtf_room ? 1u : 0u; + room.enable_late_room = room.enable_early_reflections; + status = binaural_.open(field, kernels, profile, room); } if (!status.ok()) { return status; @@ -222,9 +196,6 @@ void Stream::apply_bed_positions(const FrameMetadata& entry) { if (binaural_ready_) { binaural_.set_fixed_position(static_cast(slot) + 1, xyz); } - if (sofa_direct_ready_) { - sofa_direct_.set_fixed_position(static_cast(slot) + 1, xyz); - } if (rosella_ready_) { rosella_.set_fixed_position(static_cast(slot) + 1, xyz); } @@ -233,8 +204,8 @@ void Stream::apply_bed_positions(const FrameMetadata& entry) { continue; } std::uint16_t q15[3] = {0, 0, 0}; - // bed 声道是固定位置的源:方位由声道标签决定,与目标布局无关。 - if (!::joc::joc::bed_channel_q15(channel, q15)) { + if (!::joc::joc::layout_bed_anchor(speaker_.layout.out_ch_config, channel, q15) && + !::joc::joc::bed_channel_q15(channel, q15)) { continue; } speaker_.bed_override[slot] = true; @@ -623,27 +594,6 @@ Status Stream::render_objects16(const std::vector& objects16) { if (rosella_ready_) { return render_rosella_objects16(objects16); } - if (sofa_direct_ready_) { - const Status submitted = - sofa_direct_.submit_frame(objects16.data(), - pending_metadata_.has_update - ? &pending_metadata_.update - : nullptr, - static_cast(info_.frames_out), - pending_metadata_.outer_offset, - static_cast(config_.object_delay_samples)); - if (!submitted.ok()) { - return submitted; - } - sofa_direct_.take_output(&produced_); - output_.reserve(output_.size() + produced_.size()); - for (const double value : produced_) { - output_.push_back(static_cast(value)); - } - info_.frames_out++; - info_.samples_out += produced_.size() / 2u; - return Status::success(); - } const Status submitted = binaural_.submit_frame(objects16.data(), @@ -758,19 +708,6 @@ Status Stream::flush() { if (!objects.ok()) { return objects; } - if (sofa_direct_ready_) { - std::vector tail; - const Status drained = - sofa_direct_.finish(sofa_direct_.finish_capacity(config_.tail_seconds), &tail); - if (!drained.ok()) { - return drained; - } - output_.reserve(output_.size() + tail.size()); - for (const double value : tail) { - output_.push_back(static_cast(value)); - } - info_.samples_out += tail.size() / 2u; - } if (binaural_ready_) { std::vector tail; const Status drained = diff --git a/src/stream/stream.h b/src/stream/stream.h index 88942aa..760ac94 100644 --- a/src/stream/stream.h +++ b/src/stream/stream.h @@ -6,8 +6,7 @@ #include #include -#include "binaural/binaural_runtime.h" -#include "binaural/direct_sofa_runtime.h" +#include "binaural/jochrtf_runtime.h" #include "eac3_transport/eac3_reader.h" #include "foundation/status.h" #include "hrtf/rosella_renderer.h" @@ -31,17 +30,10 @@ struct Config { std::uint32_t object_delay_samples = 1473; double gain_db = 0.0; std::uint32_t native_threads = 0; - // The three HRTF shapes of joc_task_config, in its precedence order: a Rosella - // model wins over a SOFA, and hrtf_path (.jochrtf) is the fallback. - std::string hrtf_sofa_path; + // Binaural inputs of joc_task_config: a Rosella model wins over hrtf_path + // (.jochrtf). std::string personalized_headphone_path; - std::string hrtf_cache_dir; - std::uint32_t hrtf_cache_policy = JOC_HRTF_CACHE_MEMORY; - double hrtf_radius_m = 1.0; - // Direct SOFA rendering: the same fields joc_task_config carries. - double source_reference_distance_m = 0.0; - std::uint32_t sofa_room = 0; - std::string sofa_room_preset; + std::uint32_t jochrtf_room = 1; // Filterbank of the Rosella path; the other binaural inputs ignore it. std::uint32_t rosella_filterbank = JOC_ROSELLA_FILTERBANK_PUBLIC; }; @@ -175,8 +167,7 @@ private: ejoc_renderer_handle rebuilder_ = nullptr; speaker::SpeakerStep speaker_; - binaural::SofaBinauralRuntime binaural_; - binaural::DirectSofaRuntime sofa_direct_; + binaural::JochrtfRuntime binaural_; hrtf::RosellaRuntime rosella_; std::vector rosella_pending_; std::size_t rosella_read_offset_ = 0; @@ -184,7 +175,6 @@ private: bool speaker_enabled_ = false; bool binaural_enabled_ = false; bool binaural_ready_ = false; - bool sofa_direct_ready_ = false; bool bed_positions_ready_ = false; bool rosella_ready_ = false; float gain_ = 1.0f; diff --git a/src/task/task.cpp b/src/task/task.cpp index 9b565e9..88ff446 100644 --- a/src/task/task.cpp +++ b/src/task/task.cpp @@ -28,8 +28,7 @@ #include "adm/adm_metadata.h" #include "adm/adm_tracks.h" -#include "binaural/binaural_runtime.h" -#include "binaural/direct_sofa_runtime.h" +#include "binaural/jochrtf_runtime.h" #include "eac3_transport/eac3_reader.h" #include "emdf/emdf_parser.h" #include "foundation/mini_json.h" @@ -38,7 +37,6 @@ #include "hrtf/rosella_bank.h" #include "hrtf/rosella_model.h" #include "hrtf/rosella_renderer.h" -#include "hrtf/sofa_cache.h" #include "io/adm_writer.h" #include "io/process.h" #include "io/wav_writer.h" @@ -95,16 +93,8 @@ struct Settings { std::string layout; std::string hrtf_path; std::string kernels_path; - std::string hrtf_sofa_path; - std::uint32_t sofa_interpolation = JOC_SOFA_INTERPOLATION_LOGMAG_PHASE; - double source_reference_distance_m = 0.0; - bool sofa_room = false; - std::string sofa_room_preset; - bool hrtf_compile = false; std::string personalized_headphone_path; - std::string hrtf_cache_dir; - std::uint32_t hrtf_cache_policy = JOC_HRTF_CACHE_MEMORY; - double hrtf_radius_m = 1.0; + std::uint32_t jochrtf_room = 1; std::uint32_t rosella_filterbank = JOC_ROSELLA_FILTERBANK_PUBLIC; std::uint32_t operation = JOC_OP_ADM_BWF; std::uint32_t output_format = JOC_FORMAT_FLOAT32; @@ -150,18 +140,10 @@ Settings normalise(const joc_task_config& raw) { if (raw.output_path != nullptr) { cfg.output_path = raw.output_path; } if (raw.speaker_layout_name != nullptr) { cfg.layout = raw.speaker_layout_name; } if (raw.hrtf_path != nullptr) { cfg.hrtf_path = raw.hrtf_path; } - if (raw.hrtf_sofa_path != nullptr) { cfg.hrtf_sofa_path = raw.hrtf_sofa_path; } - cfg.sofa_interpolation = raw.sofa_interpolation; - cfg.source_reference_distance_m = raw.source_reference_distance_m; - cfg.sofa_room = raw.sofa_room != 0u; - if (raw.sofa_room_preset != nullptr) { cfg.sofa_room_preset = raw.sofa_room_preset; } - cfg.hrtf_compile = raw.hrtf_compile != 0u; if (raw.personalized_headphone_path != nullptr) { cfg.personalized_headphone_path = raw.personalized_headphone_path; } - if (raw.hrtf_cache_dir != nullptr) { cfg.hrtf_cache_dir = raw.hrtf_cache_dir; } - cfg.hrtf_cache_policy = raw.hrtf_cache_policy; - cfg.hrtf_radius_m = raw.hrtf_radius_m; + cfg.jochrtf_room = raw.jochrtf_room; // Kept verbatim so validate() can reject an out-of-range value; 0 is the // documented "unset" spelling of the public bank. cfg.rosella_filterbank = raw.rosella_filterbank; @@ -1085,36 +1067,17 @@ Status validate(const joc_task_config& raw, std::vector* i } } if (cfg.operation == JOC_OP_BINAURAL) { - if (cfg.hrtf_path.empty() && cfg.hrtf_sofa_path.empty() && - cfg.personalized_headphone_path.empty()) { + if (cfg.hrtf_path.empty() && cfg.personalized_headphone_path.empty()) { fail(JOC_ERR_INVALID_CONFIG, "hrtf_path", - "a SOFA input, a Rosella model or a compiled HRTF (.jochrtf) is required for the " + "a Rosella model or a compiled HRTF (.jochrtf) is required for the " "binaural operation"); } else if (!cfg.personalized_headphone_path.empty() && !fs_utf8::exists(cfg.personalized_headphone_path)) { fail(JOC_ERR_HRTF_NOT_FOUND, "personalized_headphone_path", "personalized headphone model not found: " + cfg.personalized_headphone_path); - } else if (!cfg.hrtf_sofa_path.empty() && !fs_utf8::exists(cfg.hrtf_sofa_path)) { - fail(JOC_ERR_HRTF_NOT_FOUND, "hrtf_sofa_path", - "SOFA HRTF not found: " + cfg.hrtf_sofa_path); - } else if (cfg.hrtf_sofa_path.empty() && cfg.personalized_headphone_path.empty() && - !fs_utf8::exists(cfg.hrtf_path)) { + } else if (cfg.personalized_headphone_path.empty() && !fs_utf8::exists(cfg.hrtf_path)) { fail(JOC_ERR_HRTF_NOT_FOUND, "hrtf_path", "HRTF cache not found: " + cfg.hrtf_path); } - if (!cfg.hrtf_sofa_path.empty()) { - if (cfg.hrtf_cache_policy > JOC_HRTF_CACHE_DISK) { - fail(JOC_ERR_INVALID_CONFIG, "hrtf_cache_policy", - "hrtf_cache_policy must be none, memory or disk"); - } - if (cfg.hrtf_cache_policy == JOC_HRTF_CACHE_DISK && cfg.hrtf_cache_dir.empty()) { - fail(JOC_ERR_INVALID_CONFIG, "hrtf_cache_dir", - "the disk cache policy needs a cache directory"); - } - if (!std::isfinite(cfg.hrtf_radius_m) || cfg.hrtf_radius_m < 0.0) { - fail(JOC_ERR_INVALID_CONFIG, "hrtf_radius_m", - "hrtf_radius_m must be finite and not negative"); - } - } // The filterbank tables are compiled in; a path is only a verification override. if (!cfg.kernels_path.empty() && !fs_utf8::exists(cfg.kernels_path)) { fail(JOC_ERR_HRTF_NOT_FOUND, "kernels_path", @@ -1365,9 +1328,7 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu speaker.layout.channel_count)); } - ::joc::binaural::SofaBinauralRuntime binaural; - ::joc::binaural::DirectSofaRuntime sofa_direct; - bool use_reference = false; + ::joc::binaural::JochrtfRuntime binaural; ::joc::hrtf::RosellaRuntime rosella; const bool binaural_enabled = cfg.operation == JOC_OP_BINAURAL; const bool rosella_enabled = !cfg.personalized_headphone_path.empty(); @@ -1411,88 +1372,33 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu ::joc::hrtf::Kernels kernels; ::joc::binaural::Profile profile = ::joc::binaural::Profile::Mid; Status status = Status::success(); - if (!cfg.hrtf_sofa_path.empty() && !cfg.hrtf_compile) { - // The SOFA keeps its full HRIRs: the direct path renders through the - // reference environment, and a .jochrtf stays an explicit input below. - ::joc::binaural::DirectSofaOptions options; - options.mode = cfg.binaural_mode == JOC_BINAURAL_NEAR - ? "near" - : (cfg.binaural_mode == JOC_BINAURAL_FAR ? "far" : "mid"); - options.has_reference_distance = cfg.source_reference_distance_m > 0.0; - options.reference_distance_m = cfg.source_reference_distance_m; - options.interpolation = - cfg.sofa_interpolation == JOC_SOFA_INTERPOLATION_MCA_ZERO - ? ::joc::hrtf::HrirInterpolation::kMcaZero - : ::joc::hrtf::HrirInterpolation::kLogMagnitudePhase; - options.has_shell_radius = cfg.hrtf_radius_m > 0.0; - options.shell_radius_m = cfg.hrtf_radius_m; - options.sofa_room = cfg.sofa_room; - options.room_preset = cfg.sofa_room_preset; - options.object_delay_samples = cfg.object_delay_samples; - options.tail_seconds = cfg.tail_seconds; - status = sofa_direct.open(cfg.hrtf_sofa_path, options); - use_reference = status.ok(); - if (status.ok()) { - bus.emit(JOC_EV_HRTF_LOADED, JOC_STAGE_RENDER, JOC_LOG_INFO, - fmt("SOFA full-HRIR field: %zu bins, %zu directions, %zu triangles, " - "latency %d samples, room %s", - sofa_direct.field().fft_size(), - sofa_direct.field().direction_count(), - sofa_direct.field().triangle_count(), - sofa_direct.latency_samples(), - sofa_direct.room_active() - ? sofa_direct.room_preset().c_str() - : "off")); - } - } else { - if (!cfg.hrtf_sofa_path.empty()) { - // Explicit legacy compile: the SOFA becomes a .jochrtf cache. - ::joc::hrtf::SofaFieldRequest request; - request.sofa_path = cfg.hrtf_sofa_path; - request.options.shell_radius_m = - cfg.hrtf_radius_m > 0.0 ? cfg.hrtf_radius_m : 1.0; - request.cache_dir = cfg.hrtf_cache_dir; - switch (cfg.hrtf_cache_policy) { - case JOC_HRTF_CACHE_NONE: request.policy = ::joc::hrtf::CachePolicy::None; break; - case JOC_HRTF_CACHE_DISK: request.policy = ::joc::hrtf::CachePolicy::Disk; break; - default: request.policy = ::joc::hrtf::CachePolicy::Memory; break; - } - std::string cache_path; - status = ::joc::hrtf::load_or_compile_sofa_field(request, &field, &cache_path); - if (status.ok()) { - bus.emit(JOC_EV_HRTF_LOADED, JOC_STAGE_RENDER, JOC_LOG_INFO, - "SOFA HRTF compiled: " + field.source_sha256.substr(0, 16) + - (cache_path.empty() ? std::string() : " -> " + cache_path)); - } - } else { - status = ::joc::hrtf::load_jochrtf(cfg.hrtf_path, &field); - if (status.ok()) { - bus.emit(JOC_EV_HRTF_LOADED, JOC_STAGE_RENDER, JOC_LOG_INFO, - "compiled HRTF: " + field.source_sha256.substr(0, 16)); - } - } - if (status.ok()) { - status = cfg.kernels_path.empty() - ? (kernels = ::joc::hrtf::builtin_kernels(), Status::success()) - : ::joc::hrtf::load_kernels(cfg.kernels_path, &kernels); - } - if (status.ok() && cfg.binaural_mode == JOC_BINAURAL_NEAR) { - profile = ::joc::binaural::Profile::Near; - } else if (status.ok() && cfg.binaural_mode == JOC_BINAURAL_FAR) { - profile = ::joc::binaural::Profile::Far; - } - if (status.ok()) { - status = binaural.open(field, kernels, profile); - } + status = ::joc::hrtf::load_jochrtf(cfg.hrtf_path, &field); + if (status.ok()) { + bus.emit(JOC_EV_HRTF_LOADED, JOC_STAGE_RENDER, JOC_LOG_INFO, + "compiled HRTF: " + field.source_sha256.substr(0, 16)); + } + if (status.ok()) { + status = cfg.kernels_path.empty() + ? (kernels = ::joc::hrtf::builtin_kernels(), Status::success()) + : ::joc::hrtf::load_kernels(cfg.kernels_path, &kernels); + } + if (status.ok() && cfg.binaural_mode == JOC_BINAURAL_NEAR) { + profile = ::joc::binaural::Profile::Near; + } else if (status.ok() && cfg.binaural_mode == JOC_BINAURAL_FAR) { + profile = ::joc::binaural::Profile::Far; + } + if (status.ok()) { + ::joc::binaural::RoomConstants room; + room.enable_early_reflections = cfg.jochrtf_room ? 1u : 0u; + room.enable_late_room = room.enable_early_reflections; + status = binaural.open(field, kernels, profile, room); } if (!status.ok()) { return finalize_with_error(status.code(), "render", "binaural setup failed: " + status.message()); } bus.emit(JOC_EV_RENDERER_INITIALIZED, JOC_STAGE_RENDER, JOC_LOG_INFO, - use_reference - ? "binaural runtime ready (full-HRIR SOFA direct path)" - : "binaural runtime ready (the first 961 samples are the kernel latency)"); + "binaural runtime ready (the first 961 samples are the kernel latency)"); } } @@ -1849,13 +1755,8 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu static_cast(slot) + 1, xyz[0], xyz[1], xyz[2]); if (binaural_enabled) { - if (use_reference) { - sofa_direct.set_fixed_position( - static_cast(slot) + 1, xyz); - } else { - binaural.set_fixed_position( - static_cast(slot) + 1, xyz); - } + binaural.set_fixed_position( + static_cast(slot) + 1, xyz); } if (rosella_enabled) { rosella.set_fixed_position( @@ -1865,10 +1766,11 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu if (!speaker_enabled) { continue; } - // bed 声道是固定位置的源:方位由声道标签决定, - // 与目标布局无关,按对象路径声像。 + // 目标布局有同名扬声器时直连该声道,否则按标准方位声像。 std::uint16_t q15[3] = {0, 0, 0}; - if (!::joc::joc::bed_channel_q15(channel, q15)) { + if (!::joc::joc::layout_bed_anchor( + speaker.layout.out_ch_config, channel, q15) && + !::joc::joc::bed_channel_q15(channel, q15)) { continue; } speaker.bed_override[slot] = true; @@ -2032,26 +1934,19 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu failed = true; } } else { - Status submitted = Status::success(); - if (rosella_enabled) { - submitted = rosella.submit_frame( - frame.objects16.data(), - frame.has_update ? &frame.update : nullptr, - static_cast(frame.index), frame.outer_offset, - static_cast(cfg.object_delay_samples)); - } else if (use_reference) { - submitted = sofa_direct.submit_frame( - frame.objects16.data(), - frame.has_update ? &frame.update : nullptr, - static_cast(frame.index), frame.outer_offset, - static_cast(cfg.object_delay_samples)); - } else { - submitted = binaural.submit_frame( - frame.objects16.data(), - frame.has_update ? &frame.update : nullptr, - static_cast(frame.index), frame.outer_offset, - static_cast(cfg.object_delay_samples)); - } + const Status submitted = + rosella_enabled + ? rosella.submit_frame(frame.objects16.data(), + frame.has_update ? &frame.update : nullptr, + static_cast(frame.index), + frame.outer_offset, + static_cast(cfg.object_delay_samples)) + : binaural.submit_frame(frame.objects16.data(), + frame.has_update ? &frame.update : nullptr, + static_cast(frame.index), + frame.outer_offset, + static_cast( + cfg.object_delay_samples)); if (!submitted.ok()) { failures.record(frame.index, StageRank::kDsp, submitted.code(), "render", "frame " + std::to_string(frame.index) + ": " + @@ -2093,8 +1988,6 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu } else { if (rosella_enabled) { rosella.take_output(&pending.dsp); - } else if (use_reference) { - sofa_direct.take_output(&pending.dsp); } else { binaural.take_output(&pending.dsp); } @@ -2133,18 +2026,13 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu static_cast(written_samples) / 48000.0); bus.emit(JOC_EV_OAMD_STATS, JOC_STAGE_METADATA, JOC_LOG_DEBUG, fmt("oamd payloads=%llu transitions=%llu", - static_cast( - !binaural_enabled - ? 0ull - : (use_reference - ? sofa_direct.timeline().payload_count() - : binaural.timeline().payload_count())), - static_cast( - !binaural_enabled - ? 0ull - : (use_reference - ? sofa_direct.timeline().transition_count() - : binaural.timeline().transition_count())))); + static_cast(binaural_enabled + ? binaural.timeline().payload_count() + : 0ull), + static_cast(binaural_enabled + ? binaural.timeline() + .transition_count() + : 0ull))); } } @@ -2250,17 +2138,10 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu const std::uint64_t program_samples = written_samples; if (binaural_enabled) { std::vector tail; - Status drained_tail = Status::success(); - if (rosella_enabled) { - drained_tail = - rosella.finish(rosella.finish_capacity(cfg.tail_seconds), &tail); - } else if (use_reference) { - drained_tail = sofa_direct.finish( - sofa_direct.finish_capacity(cfg.tail_seconds), &tail); - } else { - drained_tail = - binaural.finish(binaural.finish_capacity(cfg.tail_seconds), &tail); - } + const Status drained_tail = + rosella_enabled + ? rosella.finish(rosella.finish_capacity(cfg.tail_seconds), &tail) + : binaural.finish(binaural.finish_capacity(cfg.tail_seconds), &tail); if (!drained_tail.ok()) { return finalize_with_error(drained_tail.code(), "output", drained_tail.message()); @@ -2367,16 +2248,9 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu out->output_over_unity_values = over_unity; out->output_file_bytes = file_bytes; std::snprintf(out->output_sha256, sizeof(out->output_sha256), "%s", digest.c_str()); - out->oamd_payloads = - !binaural_enabled - ? out->oamd_payloads - : (use_reference ? sofa_direct.timeline().payload_count() - : binaural.timeline().payload_count()); + out->oamd_payloads = binaural_enabled ? binaural.timeline().payload_count() : out->oamd_payloads; out->oamd_transitions = - !binaural_enabled - ? out->oamd_transitions - : (use_reference ? sofa_direct.timeline().transition_count() - : binaural.timeline().transition_count()); + binaural_enabled ? binaural.timeline().transition_count() : out->oamd_transitions; out->t_decode_bed = t_decode; out->t_render = t_render; out->t_write = write_seconds; diff --git a/tests/test_core.cpp b/tests/test_core.cpp index 93592a9..242b980 100644 --- a/tests/test_core.cpp +++ b/tests/test_core.cpp @@ -17,17 +17,8 @@ #include "foundation/fs_utf8.h" #include "foundation/geometry.h" #include "hrtf/jochrtf.h" -#include "binaural/point_source.h" -#include "binaural/reference_distance.h" -#include "binaural/shoebox_room.h" -#include "hrtf/full_hrir_field.h" -#include "hrtf/partitioned_convolution.h" -#include "hrtf/sofa.h" -#include "hrtf/sofa_cache.h" #include "hrtf/rosella_model.h" #include "hrtf/rosella_renderer.h" -#include "hrtf/sofa_field.h" -#include "hrtf/spherical_mesh.h" #include "foundation/mini_json.h" #include "foundation/sha256.h" #include "io/inflate.h" @@ -37,7 +28,6 @@ #include "io/process.h" #include "io/wav_writer.h" #include "io/zip_reader.h" -#include "joc_bitstream/bed_layout_map.h" #include "oamd/oamd_parser.h" #include "stream/stream.h" #include "task/task.h" @@ -301,178 +291,6 @@ void test_oamd_and_adm_helpers() { // DBMD segment 10: the nine configuration trims must default to automatic (bit 0 // of each trim's first byte), and every other field of the block must keep the // layout the writer has always produced. -// Spherical interpolation mesh: a 200-point Fibonacci sphere exercises the hull, -// the barycentric weights and the Voronoi areas against values captured from the -// reference implementation. -void test_spherical_mesh() { - constexpr int kPoints = 200; - const double pi = 3.14159265358979323846; - std::vector directions; - directions.reserve(static_cast(kPoints) * 3u); - for (int index = 0; index < kPoints; ++index) { - const double z = 1.0 - 2.0 * (static_cast(index) + 0.5) / kPoints; - const double phi = static_cast(index) * pi * (3.0 - std::sqrt(5.0)); - const double radius = std::sqrt(std::max(0.0, 1.0 - z * z)); - directions.push_back(radius * std::cos(phi)); - directions.push_back(radius * std::sin(phi)); - directions.push_back(z); - } - joc::hrtf::SphericalMesh mesh; - joc::Status status = mesh.build(directions, kPoints); - CHECK(status.ok()); - CHECK(mesh.vertex_count() == 200u); - CHECK(mesh.face_count() == 396u); - - const double query[3] = {0.30304576336566319, 0.5050762722761053, 0.80812203564176865}; - const int expected_ids[3] = {16, 11, 24}; - const double expected_weights[3] = {0.18552244832037465, 0.23319383531074916, - 0.5812837163688762}; - std::vector ids; - std::vector weights; - status = mesh.weights(query, &ids, &weights); - CHECK(status.ok()); - CHECK(ids.size() == 3u); - double difference = 0.0; - for (std::size_t index = 0; index < ids.size(); ++index) { - double expected = 0.0; - for (int corner = 0; corner < 3; ++corner) { - if (expected_ids[corner] == ids[index]) { - expected = expected_weights[corner]; - } - } - difference += std::fabs(weights[index] - expected); - } - CHECK(difference < 1e-9); - CHECK(std::fabs(weights[0] + weights[1] + weights[2] - 1.0) < 1e-12); - - std::vector areas; - mesh.voronoi_areas(&areas); - CHECK(areas.size() == 200u); - double smallest = areas[0]; - double largest = areas[0]; - double total = 0.0; - for (const double area : areas) { - smallest = std::min(smallest, area); - largest = std::max(largest, area); - total += area; - } - CHECK(std::fabs(total - 1.0) < 1e-12); - CHECK(std::fabs(largest / smallest - 1.1197648114672005) < 1e-9); -} - -// Point-source reference: the ADM position selects a listener-frame direction and -// a distance scaled by the mode's reference distance. -void test_reference_distance() { - double near = 0.0; - double mid = 0.0; - double far = 0.0; - CHECK(joc::binaural::source_reference_distance("near", &near).ok()); - CHECK(joc::binaural::source_reference_distance("mid", &mid).ok()); - CHECK(joc::binaural::source_reference_distance("far", &far).ok()); - CHECK(std::fabs(near - 1.00000465) < 1e-12); - CHECK(std::fabs(mid - 2.19327927) < 1e-12); - CHECK(std::fabs(far - 6.40177584) < 1e-12); - CHECK(!joc::binaural::source_reference_distance("wide", &near).ok()); - - joc::binaural::DistanceState state; - state.profile = "near"; - state.physical_distance_m = 2.0; - state.normalized_radius = 0.5; - CHECK(joc::binaural::direct_level_gain(state) == 1.0); - CHECK(std::fabs(joc::binaural::late_send(state) - 0.042426406871192854) < 1e-15); - state.profile = "mid"; - CHECK(std::fabs(joc::binaural::direct_level_gain(state) - 0.97463184619707621) < 1e-15); - CHECK(std::fabs(joc::binaural::late_send(state) - 0.11313708498984762) < 1e-15); - state.profile = "far"; - CHECK(std::fabs(joc::binaural::late_send(state) - 0.19798989873223333) < 1e-15); - - const std::array front = {0.0, 1.0, 0.0}; - CHECK(joc::binaural::map_adm_position(front, "mid", &state).ok()); - CHECK(std::fabs(state.physical_distance_m - 2.19327927) < 1e-12); - CHECK(std::fabs(state.direction_adm[1] - 1.0) < 1e-15); - const std::array origin = {0.0, 0.0, 0.0}; - CHECK(joc::binaural::map_adm_position(origin, "mid", &state).ok()); - CHECK(std::fabs(state.physical_distance_m - joc::binaural::kMinimumSourceDistanceM) < 1e-15); - - double gain = 0.0; - CHECK(joc::binaural::inverse_distance_gain(1.2, 2.4, &gain).ok()); - CHECK(std::fabs(gain - 0.5) < 1e-15); - CHECK(!joc::binaural::inverse_distance_gain(1.2, 0.0, &gain).ok()); -} - -void test_point_source() { - joc::binaural::PointSourceReference reference; - CHECK(reference.configure("mid", false, 0.0).ok()); - CHECK(reference.mode() == "mid"); - CHECK(std::fabs(reference.reference_distance_m() - 2.19327927) < 1e-12); - - const std::array front = {0.0, 1.0, 0.0}; - joc::binaural::PointSourcePosition position; - CHECK(reference.map_position(front, nullptr, &position).ok()); - CHECK(std::fabs(position.direction[0] - 1.0) < 1e-15); - CHECK(std::fabs(position.direction[1]) < 1e-15); - CHECK(std::fabs(position.distance_m - 2.1932792700000001) < 1e-12); - CHECK(std::fabs(position.normalized_radius - 1.0) < 1e-15); - - const std::array side = {-0.8, 0.2, 0.6}; - CHECK(reference.map_position(side, nullptr, &position).ok()); - CHECK(std::fabs(position.direction[0] - 0.19611613513818402) < 1e-12); - CHECK(std::fabs(position.direction[1] - 0.7844645405527361) < 1e-12); - CHECK(std::fabs(position.distance_m - 2.2367147592977079) < 1e-12); - - const std::array origin = {0.0, 0.0, 0.0}; - const std::array previous = {0.0, -1.0, 0.0}; - CHECK(reference.map_position(origin, &previous, &position).ok()); - CHECK(std::fabs(position.direction[1] + 1.0) < 1e-15); - CHECK(reference.map_position(origin, nullptr, &position).ok()); - CHECK(std::fabs(position.direction[0] - 1.0) < 1e-15); - - joc::binaural::PointSourceReference overridden; - CHECK(overridden.configure("far", true, 3.5).ok()); - CHECK(overridden.mode() == "far"); - CHECK(std::fabs(overridden.reference_distance_m() - 3.5) < 1e-15); - CHECK(!overridden.configure("far", true, 0.0).ok()); -} - -// Six first-order image sources of the project shoebox, against the reference. -void test_shoebox_room() { - const joc::binaural::ShoeboxRoomConfig config; - CHECK(config.validate().ok()); - joc::binaural::ShoeboxRoomConfig invalid; - invalid.listener_position_m = {0.0, 9.0, 7.0}; - CHECK(!invalid.validate().ok()); - - const std::array direction = {0.0, 1.0, 0.0}; - std::vector paths; - CHECK(joc::binaural::first_order_image_sources(direction, 2.0, 48000.0, config, &paths).ok()); - CHECK(paths.size() == 6u); - const char* const walls[6] = {"left", "right", "back", "front", "floor", "ceiling"}; - const double distances[6] = {18.110770276275, 18.110770276275, 20.0, 16.0, - 14.142135623731, 14.142135623731}; - const double delays[6] = {2252.598232627999, 2252.598232627999, 2516.749198951355, - 1957.471599184387, 1697.706116921310, 1697.706116921310}; - const double gains[6] = {0.600341066264, 0.580975225417, 0.559491370220, 0.593156903749, - 0.507524274007, 0.546564602777}; - for (std::size_t index = 0; index < 6u; ++index) { - CHECK(paths[index].wall == walls[index]); - CHECK(std::fabs(paths[index].path_distance_m - distances[index]) < 1e-9); - CHECK(std::fabs(paths[index].extra_delay_samples - delays[index]) < 1e-6); - CHECK(std::fabs(paths[index].reflection_gain - gains[index]) < 1e-9); - } - CHECK(std::fabs(paths[0].direction_adm[0] + 0.993883734674) < 1e-9); - CHECK(std::fabs(paths[1].direction_adm[0] - 0.993883734674) < 1e-9); - CHECK(std::fabs(paths[2].direction_adm[1] + 1.0) < 1e-12); - - // A source outside the shoebox is rejected instead of producing a path. - std::vector outside; - CHECK(!joc::binaural::first_order_image_sources(direction, 12.0, 48000.0, config, &outside).ok()); - - joc::binaural::ShoeboxRoomConfig compact; - compact.dimensions_m = {8.5, 11.3, 5.2}; - compact.listener_position_m = {4.25, 5.65, 2.6}; - CHECK(compact.validate().ok()); -} - void test_dbmd_auto_trim() { std::string dbmd; CHECK(joc::adm::build_dbmd(25, joc::adm::BinauralMode::Mid, &dbmd).ok()); @@ -714,261 +532,10 @@ constexpr double kPi = 3.14159265358979323846; // `taps` decaying taps per ear. The values are closed-form placeholders; what // the canonicaliser and the spherical-harmonic fit actually read is the // geometry and the shape. -joc::hrtf::SofaHrir synthetic_sofa(std::uint32_t measurements, std::uint32_t taps) { - joc::hrtf::SofaHrir sofa; - sofa.sample_rate = 48000.0; - sofa.sampling_rate_units = "hertz"; - sofa.ir_count = measurements; - sofa.ir_length = taps; - sofa.conventions = "SOFA"; - sofa.sofa_conventions = "SimpleFreeFieldHRIR"; - sofa.convention_version = "1.0"; - sofa.version = "1.0"; - sofa.data_type = "FIR"; - sofa.room_type = "free field"; - sofa.receiver_position[0] = 0.0; - sofa.receiver_position[1] = 0.09; - sofa.receiver_position[2] = 0.0; - sofa.receiver_position[3] = 0.0; - sofa.receiver_position[4] = -0.09; - sofa.receiver_position[5] = 0.0; - sofa.source_position_coordinates.type = "spherical"; - sofa.source_position_coordinates.units = "degree, degree, metre"; - sofa.emitter_position_coordinates.type = "cartesian"; - sofa.emitter_position_coordinates.units = "metre"; - sofa.listener_position_coordinates.type = "cartesian"; - sofa.listener_position_coordinates.units = "metre"; - sofa.listener_view_coordinates.type = "cartesian"; - sofa.listener_view_coordinates.units = "metre"; - sofa.receiver_position_coordinates.type = "cartesian"; - sofa.receiver_position_coordinates.units = "metre"; - sofa.source_sha256 = std::string(64u, '0'); - sofa.source_position.assign(static_cast(measurements) * 3u, 0.0); - sofa.ir.assign(static_cast(measurements) * 2u * taps, 0.0); - for (std::uint32_t index = 0; index < measurements; ++index) { - // Fibonacci sphere: an even spread over the whole sphere, every point at - // one metre, so the set is a single shell. - const double unit = (static_cast(index) + 0.5) / static_cast(measurements); - const double elevation = std::asin(2.0 * unit - 1.0); - const double azimuth = - 2.0 * kPi * std::fmod(static_cast(index) * 0.6180339887498949, 1.0); - sofa.source_position[index * 3u + 0u] = azimuth * 180.0 / kPi; - sofa.source_position[index * 3u + 1u] = elevation * 180.0 / kPi; - sofa.source_position[index * 3u + 2u] = 1.0; - for (std::uint32_t ear = 0; ear < 2u; ++ear) { - for (std::uint32_t tap = 0; tap < taps; ++tap) { - const double decay = - std::exp(-4.0 * static_cast(tap) / static_cast(taps)); - const double phase = 0.2 * static_cast(tap) + - 0.05 * static_cast(index) + - 1.5 * static_cast(ear) + elevation; - sofa.ir[(static_cast(index) * 2u + ear) * taps + tap] = - decay * std::sin(phase); - } - } - } - return sofa; -} -void test_sofa_canonicalize() { - const joc::hrtf::SofaHrir sofa = synthetic_sofa(64u, 64u); - joc::hrtf::CanonicalHrtf canonical; - const joc::Status status = joc::hrtf::canonicalize_sofa(sofa, &canonical); - CHECK(status.ok()); - if (!status.ok()) { - std::printf(" canonicalize_sofa failed: %s\n", status.message().c_str()); - return; - } - CHECK(canonical.measurements == 64u && canonical.taps == 64u); - CHECK(canonical.sample_rate_hz == 48000.0); - CHECK(canonical.hrir.size() == 64u * 2u * 64u); - CHECK(canonical.delay_samples.size() == 64u * 2u); - CHECK(canonical.unit_directions.size() == 64u * 3u); - CHECK(canonical.source_position_cartesian_m.size() == 64u * 3u); - CHECK(canonical.left_receiver_index != canonical.right_receiver_index); - CHECK(canonical.left_receiver_index >= 0 && canonical.left_receiver_index < 2); - CHECK(canonical.right_receiver_index >= 0 && canonical.right_receiver_index < 2); - bool unit_length = canonical.unit_directions.size() == 64u * 3u; - bool one_shell = canonical.measurement_radius_m.size() == 64u; - for (std::size_t index = 0u; index < 64u; ++index) { - const double x = canonical.unit_directions[index * 3u + 0u]; - const double y = canonical.unit_directions[index * 3u + 1u]; - const double z = canonical.unit_directions[index * 3u + 2u]; - unit_length = unit_length && std::abs(x * x + y * y + z * z - 1.0) < 1.0e-9; - one_shell = one_shell && std::abs(canonical.measurement_radius_m[index] - 1.0) < 1.0e-9; - } - CHECK(unit_length); - CHECK(one_shell); - // The shell the compile step selects, and the radius it reports for it. - double actual_radius = 0.0; - const std::vector shell = - joc::hrtf::canonical_shell_indices(canonical, 0.5, &actual_radius); - CHECK(shell.size() == 64u); - CHECK(std::abs(actual_radius - 1.0) < 1.0e-9); - // The import is strict: each of these is a rejection, never a silent repair. - joc::hrtf::CanonicalHrtf rejected; - joc::hrtf::SofaHrir broken = sofa; - broken.conventions = "not-sofa"; - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); - broken = sofa; - broken.sofa_conventions = "SimpleFreeFieldHRTF"; - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); - broken = sofa; - broken.convention_version = "9.9"; - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); - broken = sofa; - broken.data_type = "FLOAT"; - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); - broken = sofa; - broken.room_type = ""; - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); - broken = sofa; - broken.sampling_rate_units = "furlongs"; - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); - broken = sofa; - broken.sample_rate = 0.0; - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); - broken = sofa; - broken.ir[0] = std::numeric_limits::quiet_NaN(); - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); - broken = sofa; - broken.delay[1] = -1.0; - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); - broken = sofa; - broken.emitter_position[0] = 0.5; - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); - broken = sofa; - broken.listener_view[0] = broken.listener_view[1] = broken.listener_view[2] = 0.0; - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); - broken = sofa; - broken.listener_up[0] = 1.0; // parallel to ListenerView - broken.listener_up[1] = 0.0; - broken.listener_up[2] = 0.0; - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); - broken = sofa; - broken.source_position[2] = -1.0; // a negative spherical radius - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); - broken = sofa; - broken.ir.resize(7u); - CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok()); -} - -void test_sofa_compile_and_cache() { - const joc::hrtf::SofaHrir sofa = synthetic_sofa(64u, 64u); - const joc::hrtf::CompileOptions options = joc::hrtf::CompileOptions(); - joc::hrtf::Field field; - - // The runtime field is fixed at fifth order and at 48 kHz. - joc::hrtf::CompileOptions wrong_order = options; - wrong_order.order = 3; - CHECK(!joc::hrtf::compile_sofa_field(sofa, wrong_order, &field).ok()); - joc::hrtf::SofaHrir wrong_rate = sofa; - wrong_rate.sample_rate = 44100.0; - CHECK(!joc::hrtf::compile_sofa_field(wrong_rate, options, &field).ok()); - - const joc::Status status = joc::hrtf::compile_sofa_field(sofa, options, &field); - CHECK(status.ok()); - if (!status.ok()) { - std::printf(" compile_sofa_field failed: %s\n", status.message().c_str()); - return; - } - CHECK(field.order == 5); - CHECK(field.measurement_radius_m == 1.0); - CHECK(field.band_centers_hz.size() == 77u); - CHECK(field.coefficients.size() == 36u * 2u * 77u * 2u); - CHECK(field.delay_coefficients.size() == 36u * 2u); - CHECK(field.delay_bounds.size() == 4u); - CHECK(!field.cache_key.empty() && !field.payload_sha256.empty()); - CHECK(!field.metadata_json.empty() && !field.delay_source.empty()); - bool finite = true; - for (const double value : field.coefficients) { - finite = finite && std::isfinite(value); - } - for (const double value : field.delay_coefficients) { - finite = finite && std::isfinite(value); - } - CHECK(finite); - // The payload digest is a pure function of the compiled arrays. - CHECK(joc::hrtf::field_payload_sha256(field) == field.payload_sha256); - - // The cache round-trips through the shipped writer and loader. - const std::string cache_path = joc::fs_utf8::temp_directory() + "/joc_test_cache.jochrtf"; - CHECK(joc::hrtf::write_jochrtf(field, cache_path).ok()); - joc::hrtf::Field reloaded; - const joc::Status loaded = joc::hrtf::load_jochrtf(cache_path, &reloaded); - CHECK(loaded.ok()); - if (loaded.ok()) { - CHECK(reloaded.cache_key == field.cache_key); - CHECK(reloaded.source_sha256 == field.source_sha256); - CHECK(reloaded.order == field.order); - CHECK(reloaded.measurement_radius_m == field.measurement_radius_m); - CHECK(reloaded.band_centers_hz == field.band_centers_hz); - CHECK(reloaded.coefficients == field.coefficients); - CHECK(reloaded.delay_coefficients == field.delay_coefficients); - CHECK(reloaded.delay_bounds == field.delay_bounds); - CHECK(reloaded.payload_sha256 == field.payload_sha256); - } - // A cache is trusted only after its key and payload verify; a damaged one is - // rejected instead of being used. - CHECK(joc::hrtf::validate_jochrtf(cache_path, field.source_sha256, field.cache_key, nullptr) - .ok()); - CHECK(!joc::hrtf::validate_jochrtf(cache_path, field.source_sha256, "00", nullptr).ok()); - CHECK(joc::fs_utf8::remove(cache_path) == 0); - - const std::string poisoned = joc::fs_utf8::temp_directory() + "/joc_test_poisoned.jochrtf"; - CHECK(joc::io::write_zip(poisoned, {}, nullptr)); - CHECK(!joc::hrtf::validate_jochrtf(poisoned, field.source_sha256, field.cache_key, nullptr) - .ok()); - CHECK(!joc::hrtf::load_jochrtf(poisoned, &reloaded).ok()); - CHECK(joc::fs_utf8::remove(poisoned) == 0); -} - -void test_sofa_reader_errors() { - // No SOFA file is needed to check that the reader answers correctly: a path - // that does not exist and a file that is not HDF5 are distinct, reported - // errors rather than a partially filled structure. - joc::hrtf::SofaHrir sofa; - const std::string missing = joc::fs_utf8::temp_directory() + "/joc_absent.sofa"; - const joc::Status absent = joc::hrtf::load_sofa(missing, &sofa); - CHECK(!absent.ok()); - CHECK(!absent.message().empty()); - CHECK(!joc::hrtf::load_sofa(std::string(), &sofa).ok()); - CHECK(!joc::hrtf::load_sofa(missing, nullptr).ok()); - - const std::string garbage = joc::fs_utf8::temp_directory() + "/joc_garbage.sofa"; - { - std::ofstream stream = joc::fs_utf8::open_output(garbage); - stream << "this is not an HDF5 container"; - } - const joc::Status malformed = joc::hrtf::load_sofa(garbage, &sofa); - CHECK(!malformed.ok()); - CHECK(!malformed.message().empty()); - CHECK(joc::fs_utf8::remove(garbage) == 0); -} - -void test_hrtf_cache_policy() { - // The policy parser and the miss path of the cache layer, neither of which - // needs a SOFA file. - joc::hrtf::CachePolicy policy = joc::hrtf::CachePolicy::None; - CHECK(joc::hrtf::parse_cache_policy("none", &policy).ok() && - policy == joc::hrtf::CachePolicy::None); - CHECK(joc::hrtf::parse_cache_policy("memory", &policy).ok() && - policy == joc::hrtf::CachePolicy::Memory); - CHECK(joc::hrtf::parse_cache_policy("disk", &policy).ok() && - policy == joc::hrtf::CachePolicy::Disk); - CHECK(!joc::hrtf::parse_cache_policy("sometimes", &policy).ok()); - - joc::hrtf::SofaFieldRequest request; - request.sofa_path = joc::fs_utf8::temp_directory() + "/joc_absent.sofa"; - request.policy = joc::hrtf::CachePolicy::Disk; - request.cache_dir = joc::fs_utf8::temp_directory() + "/joc_absent_cache"; - joc::hrtf::Field field; - std::string written = "sentinel"; - CHECK(!joc::hrtf::load_or_compile_sofa_field(request, &field, &written).ok()); -} void test_rosella_model_errors() { // A real model is proprietary user data and is not part of this repository. @@ -1312,186 +879,6 @@ void test_clipgain_reset_clears_the_previous_gain() { sizeof(float) * after_reset.size()) == 0); } -// CBA bed:每个声道的方位来自它的标签(ETSI TS 103 420 V1.2.1 table B.10), -// 声道顺序来自 table 12/13,因此 bed 声道不会随输出布局移动。 -void test_bed_layout_map() { - using joc::joc::BedChannel; - using joc::joc::BedLayout; - - double xyz[3] = {0.0, 0.0, 0.0}; - CHECK(joc::joc::bed_channel_adm_position(BedChannel::kLeft, xyz)); - CHECK(xyz[0] == -1.0 && xyz[1] == 1.0 && xyz[2] == 0.0); - CHECK(joc::joc::bed_channel_adm_position(BedChannel::kCenter, xyz)); - CHECK(xyz[0] == 0.0 && xyz[1] == 1.0 && xyz[2] == 0.0); - CHECK(joc::joc::bed_channel_adm_position(BedChannel::kTopFrontLeft, xyz)); - CHECK(xyz[0] == -1.0 && xyz[1] == 1.0 && xyz[2] == 1.0); - CHECK(joc::joc::bed_channel_adm_position(BedChannel::kTopFrontRight, xyz)); - CHECK(xyz[0] == 1.0 && xyz[1] == 1.0 && xyz[2] == 1.0); - CHECK(joc::joc::bed_channel_adm_position(BedChannel::kTopSideLeft, xyz)); - CHECK(xyz[0] == -1.0 && xyz[1] == 0.0 && xyz[2] == 1.0); - CHECK(joc::joc::bed_channel_adm_position(BedChannel::kTopBackLeft, xyz)); - CHECK(xyz[0] == -1.0 && xyz[1] == -1.0 && xyz[2] == 1.0); - CHECK(joc::joc::bed_channel_adm_position(BedChannel::kTopBackRight, xyz)); - CHECK(xyz[0] == 1.0 && xyz[1] == -1.0 && xyz[2] == 1.0); - CHECK(joc::joc::bed_channel_adm_position(BedChannel::kLeftWide, xyz)); - CHECK(xyz[0] == -1.0 && xyz[1] == 21.0 / 31.0 && xyz[2] == 0.0); - CHECK(joc::joc::bed_channel_adm_position(BedChannel::kRightWide, xyz)); - CHECK(xyz[0] == 1.0 && xyz[1] == 21.0 / 31.0 && xyz[2] == 0.0); - CHECK(joc::joc::bed_channel_adm_position(BedChannel::kLfe, xyz)); - CHECK(xyz[0] == -1.0 && xyz[1] == 1.0 && xyz[2] == -1.0); - CHECK(joc::joc::bed_channel_adm_position(BedChannel::kLfe2, xyz)); - CHECK(xyz[0] == 1.0 && xyz[1] == 1.0 && xyz[2] == -1.0); - - std::uint16_t q15[3] = {0, 0, 0}; - CHECK(joc::joc::bed_channel_q15(BedChannel::kLeft, q15)); - CHECK(q15[0] == 0 && q15[1] == 0 && q15[2] == 0); - CHECK(joc::joc::bed_channel_q15(BedChannel::kTopFrontLeft, q15)); - CHECK(q15[0] == 0 && q15[1] == 0 && q15[2] == 32767); - CHECK(joc::joc::bed_channel_q15(BedChannel::kLeftWide, q15)); - CHECK(q15[0] == 0 && q15[1] == 5285 && q15[2] == 0); - CHECK(joc::joc::bed_channel_q15(BedChannel::kTopBackLeft, q15)); - CHECK(q15[0] == 0 && q15[1] == 32767 && q15[2] == 32767); - - // table 12:0x0F 是 5.1,0x1FF 是 9.1.6(不含 LFE2)。 - std::vector standard(1); - standard[0].standard = true; - standard[0].mask = 0x0Fu; - const BedLayout five_one = joc::joc::resolve_bed_layout(standard, true); - CHECK(five_one.present && five_one.bed_only && five_one.complete); - CHECK(std::string(five_one.name) == "5.1"); - CHECK(five_one.channels.size() == 5); - CHECK(five_one.channels[0] == BedChannel::kLeft); - CHECK(five_one.channels[1] == BedChannel::kRight); - CHECK(five_one.channels[2] == BedChannel::kCenter); - CHECK(five_one.channels[3] == BedChannel::kLeftSurround); - CHECK(five_one.channels[4] == BedChannel::kRightSurround); - - standard[0].mask = 0x1FFu; - const BedLayout nine_six = joc::joc::resolve_bed_layout(standard, true); - CHECK(std::string(nine_six.name) == "9.1.6"); - CHECK(nine_six.channels.size() == 15); - CHECK(nine_six.channels[0] == BedChannel::kLeft); - CHECK(nine_six.channels[2] == BedChannel::kCenter); - CHECK(nine_six.channels[3] == BedChannel::kLeftSurround); - CHECK(nine_six.channels[7] == BedChannel::kTopFrontLeft); - CHECK(nine_six.channels[9] == BedChannel::kTopSideLeft); - CHECK(nine_six.channels[11] == BedChannel::kTopBackLeft); - CHECK(nine_six.channels[13] == BedChannel::kLeftWide); - CHECK(nine_six.channels[14] == BedChannel::kRightWide); - // LFE 留在声明掩码里,但不占 JOC 对象槽。 - CHECK(joc::joc::bed_layout_has(nine_six, BedChannel::kLfe)); - bool lfe_slot = false; - for (const BedChannel channel : nine_six.channels) { - lfe_slot = lfe_slot || channel == BedChannel::kLfe || - channel == BedChannel::kLfe2; - } - CHECK(!lfe_slot); - CHECK(joc::joc::bed_layout_has(nine_six, BedChannel::kRightWide)); - - // table 13:17 bit 掩码的 channel order 与 table 12 相同。 - std::vector nonstandard(1); - nonstandard[0].standard = false; - nonstandard[0].mask = 0x3Fu; - const BedLayout ns_five = joc::joc::resolve_bed_layout(nonstandard, true); - CHECK(ns_five.channels.size() == 5); - CHECK(ns_five.channels[0] == BedChannel::kLeft); - CHECK(ns_five.channels[4] == BedChannel::kRightSurround); - nonstandard[0].mask = 0xFFFFu; - const BedLayout ns_nine = joc::joc::resolve_bed_layout(nonstandard, true); - CHECK(ns_nine.channels.size() == 15); - CHECK(ns_nine.channels[0] == BedChannel::kLeft); - CHECK(ns_nine.channels[13] == BedChannel::kLeftWide); - CHECK(ns_nine.channels[14] == BedChannel::kRightWide); -} - -// Partitioned convolution: overlap-add with a shared input history and a filter -// crossfade. The expected values come from the reference -// partitioned_convolution.py running the same filters and blocks. -void test_partitioned_convolution() { - constexpr std::size_t kBlock = 128; - constexpr std::size_t kTaps = 300; - constexpr std::size_t kMaxTaps = 512; - constexpr std::size_t kOutputs = 2; - - auto make_filter = [](double step, double decay, bool cosine, double offset) { - std::vector values(kOutputs * kTaps); - for (std::size_t output = 0; output < kOutputs; ++output) { - for (std::size_t tap = 0; tap < kTaps; ++tap) { - const double angle = step * static_cast(tap + 1) * - (static_cast(output) + offset); - const double trig = cosine ? std::cos(angle) : std::sin(angle); - values[output * kTaps + tap] = trig * std::exp(-static_cast(tap) / decay); - } - } - return values; - }; - - joc::hrtf::UniformPartitionedConvolver convolver(kOutputs, kMaxTaps, kBlock); - const std::vector first = make_filter(0.017, 100.0, false, 1.0); - CHECK(convolver.set_filter(first.data(), kTaps, 0).ok()); - CHECK(!convolver.transition_active()); - - std::vector block(kBlock); - std::vector out(kBlock * kOutputs); - std::vector rendered; - for (std::size_t index = 0; index < 8; ++index) { - for (std::size_t sample = 0; sample < kBlock; ++sample) { - const double n = static_cast(index * kBlock + sample); - block[sample] = std::sin(0.01 * n) + 0.5 * std::cos(0.003 * n); - } - CHECK(convolver.process_block(block.data(), out.data()).ok()); - rendered.insert(rendered.end(), out.begin(), out.end()); - } - CHECK(rendered.size() == 8 * kBlock * kOutputs); - CHECK(std::fabs(rendered[0] - 0.0084995905892490953) < 1e-9); - CHECK(std::fabs(rendered[1] - 0.016996724855971479) < 1e-9); - CHECK(std::fabs(rendered[2] - 0.025497145937656285) < 1e-9); - CHECK(std::fabs(rendered[63] - 8.1367456949245849) < 1e-9); - CHECK(std::fabs(rendered[64] - 4.6183248807335495) < 1e-9); - CHECK(std::fabs(rendered[65] - 8.5945567424849969) < 1e-9); - CHECK(std::fabs(rendered[127] - 24.744288415490566) < 1e-8); - CHECK(std::fabs(rendered[128] - 16.21718594261781) < 1e-8); - CHECK(std::fabs(rendered[129] - 25.258064041591062) < 1e-8); - CHECK(std::fabs(rendered[255] - 42.867139711879446) < 1e-8); - CHECK(std::fabs(rendered[256] - 47.087759632531053) < 1e-8); - CHECK(std::fabs(rendered[511] - 30.307479702394744) < 1e-8); - CHECK(std::fabs(rendered[512] - 64.6869976138059) < 1e-8); - CHECK(std::fabs(rendered[700] - 26.847289638199864) < 1e-8); - CHECK(std::fabs(rendered[701] - 2.9756928363101984) < 1e-8); - CHECK(std::fabs(rendered[1023] - -25.703654152948225) < 1e-8); - CHECK(std::fabs(rendered[1024] - -43.300148318757053) < 1e-8); - - // A two-block crossfade keeps both filters' overlap tails alive. - const std::vector second = make_filter(0.011, 140.0, true, 2.0); - CHECK(convolver.set_filter(second.data(), kTaps, 2).ok()); - CHECK(convolver.transition_active()); - std::vector faded; - for (std::size_t index = 0; index < 4; ++index) { - for (std::size_t sample = 0; sample < kBlock; ++sample) { - const double n = 1000.0 + static_cast(index * kBlock + sample); - block[sample] = std::sin(0.02 * n) + 0.3; - } - CHECK(convolver.process_block(block.data(), out.data()).ok()); - faded.insert(faded.end(), out.begin(), out.end()); - } - CHECK(!convolver.transition_active()); - CHECK(std::fabs(faded[0] - -31.254215789646686) < 1e-8); - CHECK(std::fabs(faded[1] - -30.520784088408671) < 1e-8); - CHECK(std::fabs(faded[2] - -31.64727283056877) < 1e-8); - CHECK(std::fabs(faded[127] - 45.044850086774559) < 1e-8); - CHECK(std::fabs(faded[128] - 16.242938783563034) < 1e-8); - CHECK(std::fabs(faded[129] - 45.566945939182197) < 1e-8); - CHECK(std::fabs(faded[255] - -11.640284877460564) < 1e-8); - CHECK(std::fabs(faded[256] - 20.660738168974696) < 1e-8); - CHECK(std::fabs(faded[383] - -24.027948887675439) < 1e-8); - CHECK(std::fabs(faded[384] - -41.675076381317034) < 1e-8); - CHECK(std::fabs(faded[511] - 34.95547294171444) < 1e-8); - CHECK(std::fabs(faded[512] - -4.9486250951335764) < 1e-8); - - convolver.reset(); - CHECK(!convolver.transition_active()); -} - int main() { test_sha256(); test_crc32_and_inflate(); @@ -1503,12 +890,6 @@ int main() { test_task_result_json(); test_npy(); test_oamd_and_adm_helpers(); - test_bed_layout_map(); - test_partitioned_convolution(); - test_spherical_mesh(); - test_reference_distance(); - test_point_source(); - test_shoebox_room(); test_dbmd_auto_trim(); test_int24_packing(); test_utf8_paths(); @@ -1516,10 +897,6 @@ int main() { test_find_executable(); test_builtin_kernel_tables(); test_npy_and_zip_writers(); - test_sofa_canonicalize(); - test_sofa_compile_and_cache(); - test_sofa_reader_errors(); - test_hrtf_cache_policy(); test_rosella_model_errors(); test_rosella_filterbank_config(); test_stream_render_ahead();