From 5d6c6bc45c389a563973bb383dcee069052d5c5e Mon Sep 17 00:00:00 2001 From: TheM14 Date: Sun, 1 Nov 2026 19:37:51 +0800 Subject: [PATCH] Sync the kernel copy and drop the SOFA source choice The kernel copy follows the new kernel: the SOFA reader, its compile cache and the field fit are gone, the compiled-field renderer is jochrtf_renderer.cpp with jochrtf_runtime.*, and joc_kernel.vcxproj lists the new translation units. With the Rosella model as the only user-facing input, the preferences page loses its SOFA radio and the settings drop HrtfSource, hrtf_source, hrtf_cache_policy, hrtf_cache_dir and hrtf_radius_m. Decoding always sets personalized_headphone_path, the default lookup is HRTF\binaural.personalized_headphone, and the page hint names that file alone. The compiled .jochrtf stays internal: the page names a model file, never a cache. Builds Release-Static|x64 (foo_input_joc.dll and joc_kernel.lib). --- kernel/include/eac3joc_core.h | 40 +- kernel/include/joc_core.h | 19 +- kernel/include/joc_stream.h | 12 +- kernel/joc_kernel.vcxproj | 12 +- kernel/src/api/joc_stream_api.cpp | 9 +- ...ural_renderer.cpp => jochrtf_renderer.cpp} | 36 +- ...naural_runtime.cpp => jochrtf_runtime.cpp} | 52 +- .../{binaural_runtime.h => jochrtf_runtime.h} | 12 +- kernel/src/cli/joc_cli.cpp | 127 +- kernel/src/hrtf/rosella_renderer.cpp | 2 +- kernel/src/hrtf/sofa.cpp | 255 --- kernel/src/hrtf/sofa.h | 61 - kernel/src/hrtf/sofa_cache.cpp | 237 --- kernel/src/hrtf/sofa_cache.h | 38 - kernel/src/hrtf/sofa_field.cpp | 1822 ----------------- kernel/src/hrtf/sofa_field.h | 103 - kernel/src/stream/stream.cpp | 27 +- kernel/src/stream/stream.h | 13 +- kernel/src/task/task.cpp | 73 +- src/joc_decode.cpp | 14 +- src/joc_decode.h | 11 - src/prefs.cpp | 14 +- src/prefs.rc | 7 +- src/settings.cpp | 30 +- src/settings.h | 14 +- 25 files changed, 144 insertions(+), 2896 deletions(-) rename kernel/src/binaural/{sofa_binaural_renderer.cpp => jochrtf_renderer.cpp} (98%) rename kernel/src/binaural/{binaural_runtime.cpp => jochrtf_runtime.cpp} (84%) rename kernel/src/binaural/{binaural_runtime.h => jochrtf_runtime.h} (92%) delete mode 100644 kernel/src/hrtf/sofa.cpp delete mode 100644 kernel/src/hrtf/sofa.h delete mode 100644 kernel/src/hrtf/sofa_cache.cpp delete mode 100644 kernel/src/hrtf/sofa_cache.h delete mode 100644 kernel/src/hrtf/sofa_field.cpp delete mode 100644 kernel/src/hrtf/sofa_field.h diff --git a/kernel/include/eac3joc_core.h b/kernel/include/eac3joc_core.h index d6487a5..811274e 100644 --- a/kernel/include/eac3joc_core.h +++ b/kernel/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/kernel/include/joc_core.h b/kernel/include/joc_core.h index 1369317..428597b 100644 --- a/kernel/include/joc_core.h +++ b/kernel/include/joc_core.h @@ -358,14 +358,6 @@ typedef enum joc_clip_action { JOC_CLIP_ABORT = 3 /* fail the task */ } joc_clip_action; -/* Compiled-HRTF cache policy for a SOFA input; the .jochrtf itself is an - * internal artifact of the compile step. */ -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 @@ -424,16 +416,11 @@ typedef struct joc_task_config { joc_cancel_token* cancel; /* optional */ - /* Binaural HRTF input (config version 2): 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. hrtf_path stays the advanced override that reads - * a .jochrtf directly. */ - 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 measurement-radius shell */ + uint32_t jochrtf_room; /* non-zero enables the project room */ } joc_task_config; typedef enum joc_task_status { diff --git a/kernel/include/joc_stream.h b/kernel/include/joc_stream.h index b942f4f..7511483 100644 --- a/kernel/include/joc_stream.h +++ b/kernel/include/joc_stream.h @@ -64,16 +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 */ + uint32_t jochrtf_room; /* non-zero enables the project room */ } joc_stream_config; typedef struct joc_stream_buffer { diff --git a/kernel/joc_kernel.vcxproj b/kernel/joc_kernel.vcxproj index 310aa92..96443f5 100644 --- a/kernel/joc_kernel.vcxproj +++ b/kernel/joc_kernel.vcxproj @@ -149,8 +149,8 @@ - - + + @@ -166,9 +166,6 @@ - - - @@ -226,7 +223,7 @@ - + @@ -245,9 +242,6 @@ - - - diff --git a/kernel/src/api/joc_stream_api.cpp b/kernel/src/api/joc_stream_api.cpp index bca9fa7..6cb6bf0 100644 --- a/kernel/src/api/joc_stream_api.cpp +++ b/kernel/src/api/joc_stream_api.cpp @@ -36,16 +36,11 @@ 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; diff --git a/kernel/src/binaural/sofa_binaural_renderer.cpp b/kernel/src/binaural/jochrtf_renderer.cpp similarity index 98% rename from kernel/src/binaural/sofa_binaural_renderer.cpp rename to kernel/src/binaural/jochrtf_renderer.cpp index f13fefd..49e86d0 100644 --- a/kernel/src/binaural/sofa_binaural_renderer.cpp +++ b/kernel/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/kernel/src/binaural/binaural_runtime.cpp b/kernel/src/binaural/jochrtf_runtime.cpp similarity index 84% rename from kernel/src/binaural/binaural_runtime.cpp rename to kernel/src/binaural/jochrtf_runtime.cpp index a25ace0..11eebdc 100644 --- a/kernel/src/binaural/binaural_runtime.cpp +++ b/kernel/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/kernel/src/binaural/binaural_runtime.h b/kernel/src/binaural/jochrtf_runtime.h similarity index 92% rename from kernel/src/binaural/binaural_runtime.h rename to kernel/src/binaural/jochrtf_runtime.h index db9fc75..1466f87 100644 --- a/kernel/src/binaural/binaural_runtime.h +++ b/kernel/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/kernel/src/cli/joc_cli.cpp b/kernel/src/cli/joc_cli.cpp index 98441f1..9a509c9 100644 --- a/kernel/src/cli/joc_cli.cpp +++ b/kernel/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,15 +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 = 1.0; double binaural_tail_seconds = 5.0; double binaural_tail_threshold = 1.0e-8; int binaural_chunk_frames = 64; @@ -117,15 +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" - " --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" @@ -231,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. @@ -247,9 +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 == "--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")); } @@ -345,16 +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 - bool disk = false; }; std::string resolve_compiled_hrtf(const Options& options, const std::string& project_directory) { @@ -362,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(); } @@ -378,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 != 1.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 != 1.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(); @@ -413,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()) { @@ -432,35 +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 != 1.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 != 1.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; - 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.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; } @@ -567,10 +508,6 @@ int main(int argc, char** argv) { 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)"); @@ -602,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 != 1.0; + !options.compiled_hrtf_cache.empty() || options.personalized_headphone_used || + options.jochrtf_room != "on"; if (hrtf_options_used && !binaural_mode) { fail("SOFA/HRTF 选项仅与 --binaural 一起使用"); } @@ -623,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"); } @@ -714,22 +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; 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; 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()); @@ -737,14 +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.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/kernel/src/hrtf/rosella_renderer.cpp b/kernel/src/hrtf/rosella_renderer.cpp index 488df9e..31f9462 100644 --- a/kernel/src/hrtf/rosella_renderer.cpp +++ b/kernel/src/hrtf/rosella_renderer.cpp @@ -1343,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/kernel/src/hrtf/sofa.cpp b/kernel/src/hrtf/sofa.cpp deleted file mode 100644 index c05c0ac..0000000 --- a/kernel/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/kernel/src/hrtf/sofa.h b/kernel/src/hrtf/sofa.h deleted file mode 100644 index 101b033..0000000 --- a/kernel/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/kernel/src/hrtf/sofa_cache.cpp b/kernel/src/hrtf/sofa_cache.cpp deleted file mode 100644 index f49b92f..0000000 --- a/kernel/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/kernel/src/hrtf/sofa_cache.h b/kernel/src/hrtf/sofa_cache.h deleted file mode 100644 index 08f0bc3..0000000 --- a/kernel/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/kernel/src/hrtf/sofa_field.cpp b/kernel/src/hrtf/sofa_field.cpp deleted file mode 100644 index 70909cd..0000000 --- a/kernel/src/hrtf/sofa_field.cpp +++ /dev/null @@ -1,1822 +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.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/kernel/src/hrtf/sofa_field.h b/kernel/src/hrtf/sofa_field.h deleted file mode 100644 index bb80fba..0000000 --- a/kernel/src/hrtf/sofa_field.h +++ /dev/null @@ -1,103 +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 -}; - -// 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/kernel/src/stream/stream.cpp b/kernel/src/stream/stream.cpp index de00edd..8112ba2 100644 --- a/kernel/src/stream/stream.cpp +++ b/kernel/src/stream/stream.cpp @@ -8,7 +8,6 @@ #include "foundation/status.h" #include "hrtf/jochrtf.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" @@ -143,26 +142,7 @@ Status Stream::create(const Config& config) { hrtf::Field field; hrtf::Kernels kernels; Status status = Status::success(); - if (!config_.hrtf_sofa_path.empty()) { - // The .jochrtf is an internal cache: the SOFA is the user-facing input. - hrtf::SofaFieldRequest request; - request.sofa_path = config_.hrtf_sofa_path; - request.options.shell_radius_m = config_.hrtf_radius_m; - request.cache_dir = config_.hrtf_cache_dir; - switch (config_.hrtf_cache_policy) { - case JOC_HRTF_CACHE_NONE: request.policy = hrtf::CachePolicy::None; break; - case JOC_HRTF_CACHE_DISK: request.policy = hrtf::CachePolicy::Disk; break; - default: request.policy = hrtf::CachePolicy::Memory; break; - } - std::string cache_path; - status = hrtf::load_or_compile_sofa_field(request, &field, &cache_path); - if (!status.ok()) { - return Status::fail(status.code(), stage::kRender, - "binaural setup failed: " + status.message()); - } - } else { - status = hrtf::load_jochrtf(config_.hrtf_path, &field); - } + status = hrtf::load_jochrtf(config_.hrtf_path, &field); if (status.ok()) { status = config_.kernels_path.empty() ? (kernels = hrtf::builtin_kernels(), Status::success()) @@ -175,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; diff --git a/kernel/src/stream/stream.h b/kernel/src/stream/stream.h index 80030b3..760ac94 100644 --- a/kernel/src/stream/stream.h +++ b/kernel/src/stream/stream.h @@ -6,7 +6,7 @@ #include #include -#include "binaural/binaural_runtime.h" +#include "binaural/jochrtf_runtime.h" #include "eac3_transport/eac3_reader.h" #include "foundation/status.h" #include "hrtf/rosella_renderer.h" @@ -30,13 +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; + 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; }; @@ -170,7 +167,7 @@ private: ejoc_renderer_handle rebuilder_ = nullptr; speaker::SpeakerStep speaker_; - binaural::SofaBinauralRuntime binaural_; + binaural::JochrtfRuntime binaural_; hrtf::RosellaRuntime rosella_; std::vector rosella_pending_; std::size_t rosella_read_offset_ = 0; diff --git a/kernel/src/task/task.cpp b/kernel/src/task/task.cpp index 21cdaec..88ff446 100644 --- a/kernel/src/task/task.cpp +++ b/kernel/src/task/task.cpp @@ -28,7 +28,7 @@ #include "adm/adm_metadata.h" #include "adm/adm_tracks.h" -#include "binaural/binaural_runtime.h" +#include "binaural/jochrtf_runtime.h" #include "eac3_transport/eac3_reader.h" #include "emdf/emdf_parser.h" #include "foundation/mini_json.h" @@ -37,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" @@ -94,11 +93,8 @@ struct Settings { std::string layout; std::string hrtf_path; std::string kernels_path; - std::string hrtf_sofa_path; 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; @@ -144,13 +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; } 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; @@ -1074,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 positive and finite"); - } - } // 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", @@ -1354,7 +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::JochrtfRuntime binaural; ::joc::hrtf::RosellaRuntime rosella; const bool binaural_enabled = cfg.operation == JOC_OP_BINAURAL; const bool rosella_enabled = !cfg.personalized_headphone_path.empty(); @@ -1398,30 +1372,10 @@ 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()) { - // The .jochrtf is an internal cache: the SOFA is the user-facing input. - ::joc::hrtf::SofaFieldRequest request; - request.sofa_path = cfg.hrtf_sofa_path; - request.options.shell_radius_m = cfg.hrtf_radius_m; - 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)); - } + 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() @@ -1434,7 +1388,10 @@ Status run(const joc_task_config& raw, const joc_event_sink* sink, joc_task_resu profile = ::joc::binaural::Profile::Far; } if (status.ok()) { - status = binaural.open(field, kernels, profile); + ::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", diff --git a/src/joc_decode.cpp b/src/joc_decode.cpp index b555398..2d403e5 100644 --- a/src/joc_decode.cpp +++ b/src/joc_decode.cpp @@ -455,9 +455,7 @@ std::string resolve_hrtf_file(const Settings& settings) { if (directory.empty()) return {}; // Same convention as the reference CLI next to its executable: // \HRTF\binaural.sofa or \HRTF\binaural.personalized_headphone. - const char* name = (settings.hrtf_source == HrtfSource::kRosella) - ? "binaural.personalized_headphone" - : "binaural.sofa"; + const char* name = "binaural.personalized_headphone"; return directory + "\\HRTF\\" + name; } @@ -1012,16 +1010,8 @@ bool Engine::start(const std::string& input_path, const Settings& settings, std: } return false; } - if (settings.hrtf_source == HrtfSource::kRosella) { - config.personalized_headphone_path = hrtf_file.c_str(); - } else { - config.hrtf_sofa_path = hrtf_file.c_str(); - } + config.personalized_headphone_path = hrtf_file.c_str(); } - config.hrtf_cache_policy = settings.hrtf_cache_policy; - config.hrtf_cache_dir = - settings.hrtf_cache_dir.empty() ? nullptr : settings.hrtf_cache_dir.c_str(); - config.hrtf_radius_m = settings.hrtf_radius_m; config.binaural_tail_seconds = settings.tail_seconds; config.object_delay_samples = settings.object_delay_samples; config.gain_db = settings.gain_db; diff --git a/src/joc_decode.h b/src/joc_decode.h index 44d2a6c..6a7111f 100644 --- a/src/joc_decode.h +++ b/src/joc_decode.h @@ -44,13 +44,6 @@ enum class Output { kSpeaker = 1, // N channels, named layout }; -// Which HRTF to render with. Both inputs are user-facing model/data files; how -// the renderer gets from them to its internal filter field is its own business. -enum class HrtfSource { - kSofa = 0, - kRosella = 1, -}; - // Where the E-AC-3 syncframes come from. A bare stream is read straight from the // file; inside a container the track has to be extracted first (ffmpeg, stream copy). enum class InputKind { @@ -64,12 +57,8 @@ struct Settings { // Which of the container's audio tracks holds the E-AC-3 stream, 0-based. unsigned audio_index = 0; std::string speaker_layout = "7.1"; - HrtfSource hrtf_source = HrtfSource::kSofa; // Empty means the default file in the default folder, see resolve_hrtf_file(). std::string hrtf_file; - std::string hrtf_cache_dir; // SOFA compile cache (disk policy) - unsigned hrtf_cache_policy = 1; // 0 none, 1 memory, 2 disk - double hrtf_radius_m = 1.0; // SOFA measurement-radius shell std::uint32_t binaural_mode = 3; // JOC_BINAURAL_MID double gain_db = 0.0; double tail_seconds = 5.0; diff --git a/src/prefs.cpp b/src/prefs.cpp index d8c2e74..3e0b928 100644 --- a/src/prefs.cpp +++ b/src/prefs.cpp @@ -404,10 +404,6 @@ private: void load_values(const joc_settings::Values& values) { CheckRadioButton(m_hwnd, IDC_RADIO_BINAURAL, IDC_RADIO_SPEAKER, values.output == 0 ? IDC_RADIO_BINAURAL : IDC_RADIO_SPEAKER); - CheckRadioButton(m_hwnd, IDC_RADIO_HRTF_SOFA, IDC_RADIO_HRTF_ROSELLA, - values.hrtf_source == joc_settings::HrtfSource::kRosella - ? IDC_RADIO_HRTF_ROSELLA - : IDC_RADIO_HRTF_SOFA); set_text(GetDlgItem(m_hwnd, IDC_EDIT_HRTF), values.hrtf_file); set_text(GetDlgItem(m_hwnd, IDC_EDIT_FFMPEG), values.ffmpeg_path); @@ -464,9 +460,6 @@ private: static_cast(SendDlgItemMessageW(m_hwnd, IDC_COMBO_MODE, CB_GETCURSEL, 0, 0)); values.binaural_mode = mode_value(mode_sel < 0 ? 1u : static_cast(mode_sel)); - values.hrtf_source = IsDlgButtonChecked(m_hwnd, IDC_RADIO_HRTF_ROSELLA) == BST_CHECKED - ? joc_settings::HrtfSource::kRosella - : joc_settings::HrtfSource::kSofa; values.hrtf_file = get_text(GetDlgItem(m_hwnd, IDC_EDIT_HRTF)); values.ffmpeg_path = get_text(GetDlgItem(m_hwnd, IDC_EDIT_FFMPEG)); values.tail_seconds = @@ -503,13 +496,9 @@ private: set_text(GetDlgItem(m_hwnd, IDC_LABEL_OUTPUT_STATUS), output_status); joc_decode::Settings effective = joc_settings::current(); - effective.hrtf_source = static_cast(values.hrtf_source); effective.hrtf_file = values.hrtf_file; const std::string file = joc_decode::resolve_hrtf_file(effective); - const joc_lang::Text source = values.hrtf_source == joc_settings::HrtfSource::kRosella - ? joc_lang::Text::kHrtfSourceRosella - : joc_lang::Text::kHrtfSourceSofa; - std::string hrtf_status = joc_lang::get(language, source); + std::string hrtf_status = joc_lang::get(language, joc_lang::Text::kHrtfSourceRosella); hrtf_status += joc_lang::get(language, joc_lang::Text::kSeparator); if (values.hrtf_file.empty()) { hrtf_status += joc_lang::get(language, joc_lang::Text::kHrtfDefault); @@ -538,7 +527,6 @@ private: const joc_settings::Values now = read_controls(); if (now.output != m_initial.output) return true; if (now.speaker_layout != m_initial.speaker_layout) return true; - if (now.hrtf_source != m_initial.hrtf_source) return true; if (now.hrtf_file != m_initial.hrtf_file) return true; if (now.binaural_mode != m_initial.binaural_mode) return true; if (now.gain_enabled != m_initial.gain_enabled) return true; diff --git a/src/prefs.rc b/src/prefs.rc index c75a6e0..692d967 100644 --- a/src/prefs.rc +++ b/src/prefs.rc @@ -39,14 +39,11 @@ BEGIN LTEXT "切换后需刷新文件信息", IDC_LABEL_INT24_HINT, 176, 65, 136, 10 GROUPBOX "HRTF", IDC_GROUP_HRTF, 7, 79, 316, 92 - CONTROL "SOFA 文件", IDC_RADIO_HRTF_SOFA, "Button", - BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 16, 91, 50, 10 - CONTROL "Rosella 个性化模型", IDC_RADIO_HRTF_ROSELLA, "Button", - BS_AUTORADIOBUTTON | WS_TABSTOP, 70, 91, 146, 10 + LTEXT "Rosella 个性化模型", IDC_RADIO_HRTF_ROSELLA, 16, 91, 146, 10 LTEXT "HRTF 文件", IDC_LABEL_HRTF, 16, 106, 40, 10 EDITTEXT IDC_EDIT_HRTF, 58, 103, 186, 13, ES_AUTOHSCROLL PUSHBUTTON "浏览…", IDC_BROWSE_HRTF, 248, 103, 52, 13 - LTEXT "留空时读组件目录下 HRTF\\binaural.sofa 或 HRTF\\binaural.personalized_headphone。", + LTEXT "留空时读组件目录下 HRTF\\binaural.personalized_headphone。", IDC_LABEL_HRTF_HINT, 16, 121, 300, 20 LTEXT "", IDC_LABEL_STATUS, 16, 143, 300, 20 diff --git a/src/settings.cpp b/src/settings.cpp index 4da6c1e..bfb3875 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -24,7 +24,6 @@ constexpr GUID kGuidLayout = {0x7b62e5d1, 0x14a8, 0x4c07, {0x83, 0x2f, 0x6b, 0x9 // Reused from the previous build, where it stored the .jochrtf path: it still // holds "the HRTF file", so the meaning is unchanged for anyone upgrading. constexpr GUID kGuidHrtfFile = {0x4e8a1f36, 0x2c95, 0x47d0, {0xb1, 0x68, 0x3e, 0xa2, 0x77, 0x09, 0xf5, 0x8c}}; -constexpr GUID kGuidHrtfSource = {0xa3d51b72, 0x6f48, 0x4c19, {0x9e, 0x04, 0x2b, 0x87, 0xd1, 0x53, 0x6a, 0x20}}; constexpr GUID kGuidBinauralMode = {0x1a57c9e4, 0x83b6, 0x42f1, {0x9c, 0x50, 0x24, 0xfd, 0x6a, 0x18, 0x73, 0x0e}}; constexpr GUID kGuidGainEnabled = {0x74b1e5c8, 0x2a39, 0x4d16, {0x8f, 0x62, 0x0d, 0x51, 0xb7, 0x3c, 0x9a, 0x28}}; constexpr GUID kGuidGain = {0x6c04d8b2, 0xe75f, 0x4a39, {0x8d, 0x26, 0x51, 0xb3, 0xc8, 0x40, 0x9e, 0x27}}; @@ -37,7 +36,6 @@ constexpr GUID kGuidLanguage = {0x58e17a04, 0x3d92, 0x4f6b, {0xa1, 0x27, 0x94, 0 cfg_uint g_output(kGuidOutput, 0); cfg_string g_layout(kGuidLayout, "7.1"); // 0 = SOFA, 1 = Rosella model, 2 = compiled .jochrtf (advanced) -cfg_uint g_hrtf_source(kGuidHrtfSource, 0); cfg_string g_hrtf_file(kGuidHrtfFile, ""); cfg_uint g_binaural_mode(kGuidBinauralMode, 3); cfg_bool g_gain_enabled(kGuidGainEnabled, true); @@ -99,18 +97,7 @@ bool env_string(const char* name, std::string* out) { namespace joc_settings { -const char* hrtf_source_name(HrtfSource source) { - return source == HrtfSource::kRosella ? "Rosella 个性化模型" : "SOFA"; -} - -const char* hrtf_source_extension(HrtfSource source) { - return source == HrtfSource::kRosella ? "personalized_headphone" : "sofa"; -} - -const char* hrtf_default_file_name(HrtfSource source) { - return source == HrtfSource::kRosella ? "binaural.personalized_headphone" - : "binaural.sofa"; -} +const char* hrtf_default_file_name() { return "binaural.personalized_headphone"; } Values defaults() { return Values(); } @@ -131,8 +118,6 @@ Values read() { } values.speaker_layout = "7.1"; } - const unsigned source = static_cast(g_hrtf_source); - values.hrtf_source = (source == 1u) ? HrtfSource::kRosella : HrtfSource::kSofa; values.hrtf_file = g_hrtf_file.get_ptr(); values.binaural_mode = static_cast(g_binaural_mode); values.gain_enabled = static_cast(g_gain_enabled); @@ -162,7 +147,6 @@ Values read() { void write(const Values& values) { g_output = static_cast(values.output); g_layout = values.speaker_layout.c_str(); - g_hrtf_source = static_cast(values.hrtf_source); g_hrtf_file = values.hrtf_file.c_str(); g_binaural_mode = values.binaural_mode; g_gain_enabled = values.gain_enabled; @@ -182,9 +166,6 @@ joc_decode::Settings current() { if (env_string("JOC_OUTPUT", &text)) values.output = (text == "speaker") ? 1 : 0; if (env_string("JOC_LAYOUT", &text)) values.speaker_layout = text; (void)env_string("JOC_HRTF", &values.hrtf_file); - if (env_string("JOC_HRTF_SOURCE", &text)) { - values.hrtf_source = (text == "rosella") ? HrtfSource::kRosella : HrtfSource::kSofa; - } (void)env_string("JOC_FFMPEG", &values.ffmpeg_path); if (env_string("JOC_BINAURAL_MODE", &text)) { values.binaural_mode = (text == "near") ? 1u : (text == "far") ? 2u : 3u; @@ -200,7 +181,6 @@ joc_decode::Settings current() { settings.output = (values.output == 0) ? joc_decode::Output::kBinaural : joc_decode::Output::kSpeaker; settings.speaker_layout = values.speaker_layout; - settings.hrtf_source = static_cast(values.hrtf_source); settings.hrtf_file = values.hrtf_file; settings.binaural_mode = values.binaural_mode; // The switch is explicit rather than implied by the value: binaural rendering @@ -219,9 +199,8 @@ std::string describe(const joc_decode::Settings& settings) { char text[640] = {}; if (settings.output == joc_decode::Output::kBinaural) { std::snprintf(text, sizeof(text), - "binaural, hrtf=%s(%s), mode=%u, gain=%.2f dB, tail=%.2f s, delay=%u, " + "binaural, hrtf=%s, mode=%u, gain=%.2f dB, tail=%.2f s, delay=%u, " "threads=%u, ffmpeg=%s", - hrtf_source_name(static_cast(settings.hrtf_source)), settings.hrtf_file.empty() ? "(默认位置)" : settings.hrtf_file.c_str(), settings.binaural_mode, settings.gain_db, settings.tail_seconds, settings.object_delay_samples, settings.native_threads, @@ -244,10 +223,9 @@ std::string describe(const joc_decode::Settings& settings) { std::string describe(const Values& values) { char text[640] = {}; std::snprintf(text, sizeof(text), - "output=%d layout=%s hrtf=%s(%s) mode=%u gain=%s%.2f dB tail=%.2f s delay=%u " + "output=%d layout=%s hrtf=%s mode=%u gain=%s%.2f dB tail=%.2f s delay=%u " "threads=%u ffmpeg=\"%s\"", - values.output, values.speaker_layout.c_str(), - hrtf_source_name(values.hrtf_source), values.hrtf_file.c_str(), + values.output, values.speaker_layout.c_str(), values.hrtf_file.c_str(), values.binaural_mode, values.gain_enabled ? "" : "(off) ", values.gain_db, values.tail_seconds, values.object_delay_samples, values.native_threads, values.ffmpeg_path.c_str()); diff --git a/src/settings.h b/src/settings.h index a9b0736..bc67d55 100644 --- a/src/settings.h +++ b/src/settings.h @@ -17,24 +17,14 @@ namespace joc_settings { -// Which HRTF the binaural renderer uses. Only these two inputs exist: everything -// else (compiling a SOFA into the renderer's field, caching it) is internal. -enum class HrtfSource { - kSofa = 0, // SOFA SimpleFreeFieldHRIR, compiled by the renderer - kRosella = 1, // Rosella .personalized_headphone model -}; - -const char* hrtf_source_name(HrtfSource source); -const char* hrtf_source_extension(HrtfSource source); // The file looked up in the default folder (next to the component) when no path -// is configured; same names the reference CLI uses. -const char* hrtf_default_file_name(HrtfSource source); +// is configured; same name the reference CLI uses. +const char* hrtf_default_file_name(); // The stored values, exactly as the preferences page shows them. struct Values { int output = 0; // 0 = binaural, 1 = speaker layout std::string speaker_layout = "7.1"; - HrtfSource hrtf_source = HrtfSource::kSofa; // Empty means "the default file in the default folder". std::string hrtf_file; unsigned binaural_mode = 3; // JOC_BINAURAL_NEAR/FAR/MID = 1/2/3