Files
JustOneCacophony/tests/test_core.cpp
T
TheM14 29f4f83c29
ci / ubuntu-latest (push) Failing after 17s
ci / macos-latest (push) Canceled after 0s
ci / windows-latest (push) Canceled after 0s
ci / release (push) Canceled after 0s
Render SOFA through a point-source reference with an optional project room
Replace the Rosella table-A reference environment with a point-source reference:
the ADM position now selects a listener-frame direction and a distance scaled by
the mode's reference distance (near/mid/far 1.00000465/2.19327927/6.40177584 m,
overridable with --source-reference-distance-m). The direct level is an
equal-power coefficient rather than a 1/r attenuation, and the measured SOFA
response stays as measured: no rigid-sphere radial correction and no Voronoi
centre spectrum any more.

--sofa-room couples the direct path to this project's own room. It is generated
in code, not loaded from an asset: room_tables.cpp runs the four-line Hadamard
FDN with two all-pass diffusers and low-pass damping into a float64 FIR, and
shoebox_room.cpp computes the six first-order image sources, which are rendered
through the same HRIR field with fractional delays. The late tail is convolved
in 1536-sample batches. Near/Mid default to the compact room and Far to the
legacy one; --sofa-room-preset selects explicitly, and the room is off by
default.

Filter changes are scheduled at the parameter alignment delay instead of being
applied on the spot, and the LFE band starts at latency + recording origin - 64,
both matching the reference implementation. joc_task_config goes to version 5
and joc_stream_config gains the same fields; the stream API renders a SOFA
directly instead of compiling it.
2026-11-01 17:20:27 +08:00

1532 lines
67 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Unit tests for the engine's self-contained parts: no test data files, no
// reference implementation, no external framework. Run with `ctest` or directly.
#include <algorithm>
#include <cmath>
#include <filesystem>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include "adm/adm_metadata.h"
#include "eac3_transport/eac3_reader.h"
#include "eac3joc_core.h"
#include "foundation/bit_reader.h"
#include "foundation/fs_utf8.h"
#include "foundation/geometry.h"
#include "hrtf/jochrtf.h"
#include "binaural/point_source.h"
#include "binaural/reference_distance.h"
#include "binaural/shoebox_room.h"
#include "hrtf/full_hrir_field.h"
#include "hrtf/partitioned_convolution.h"
#include "hrtf/sofa.h"
#include "hrtf/sofa_cache.h"
#include "hrtf/rosella_model.h"
#include "hrtf/rosella_renderer.h"
#include "hrtf/sofa_field.h"
#include "hrtf/spherical_mesh.h"
#include "foundation/mini_json.h"
#include "foundation/sha256.h"
#include "io/inflate.h"
#include "io/hdf5.h"
#include "io/npy_writer.h"
#include "io/npy.h"
#include "io/process.h"
#include "io/wav_writer.h"
#include "io/zip_reader.h"
#include "joc_bitstream/bed_layout_map.h"
#include "oamd/oamd_parser.h"
#include "stream/stream.h"
#include "task/task.h"
namespace {
int g_failures = 0;
int g_checks = 0;
void check(bool condition, const char* expression, const char* file, int line) {
++g_checks;
if (!condition) {
++g_failures;
std::printf("FAIL %s:%d %s\n", file, line, expression);
}
}
#define CHECK(expression) check((expression), #expression, __FILE__, __LINE__)
void test_sha256() {
CHECK(joc::crypto::sha256_hex("", 0) ==
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
CHECK(joc::crypto::sha256_hex("abc", 3) ==
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
const char* two_block = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
CHECK(joc::crypto::sha256_hex(two_block, std::strlen(two_block)) ==
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1");
std::vector<char> million(1000000, 'a');
CHECK(joc::crypto::sha256_hex(million.data(), million.size()) ==
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0");
// Incremental updates must equal a single-shot hash.
joc::crypto::Sha256 incremental;
incremental.update("ab", 2);
incremental.update("c", 1);
CHECK(incremental.finish_hex() == joc::crypto::sha256_hex("abc", 3));
}
void test_crc32_and_inflate() {
CHECK(joc::io::crc32_of(reinterpret_cast<const std::uint8_t*>("123456789"), 9) == 0xCBF43926u);
// One stored DEFLATE block: BFINAL=1, BTYPE=00, LEN=3, NLEN=~LEN, "abc".
const std::uint8_t stored[] = {0x01, 0x03, 0x00, 0xFC, 0xFF, 'a', 'b', 'c'};
std::vector<std::uint8_t> out;
CHECK(joc::io::inflate_raw(stored, sizeof(stored), &out));
CHECK(out.size() == 3 && std::memcmp(out.data(), "abc", 3) == 0);
const std::uint8_t truncated[] = {0x01, 0x10, 0x00, 0xEF, 0xFF, 'a'};
CHECK(!joc::io::inflate_raw(truncated, sizeof(truncated), &out));
}
void test_bit_reader() {
const std::uint8_t data[] = {0xB2, 0x5D}; // 1011 0010 0101 1101
joc::bits::BitReader reader(data, sizeof(data));
CHECK(reader.read(3) == 0x5);
CHECK(reader.read(5) == 0x12);
CHECK(reader.read(8) == 0x5D);
CHECK(reader.position() == 16);
CHECK(!reader.failed());
joc::bits::BitReader short_read(data, 1);
CHECK(short_read.read(9) == 0);
CHECK(short_read.failed());
CHECK(short_read.error() == JOC_ERR_BITSTREAM_TRUNCATED);
CHECK(short_read.position() == 0);
joc::bits::BitReader limited(data, sizeof(data));
limited.set_limit_bits(4);
CHECK(limited.read(4) == 0xB);
CHECK(limited.read(1) == 0 && limited.failed());
}
// Writes MSB-first bits; used only to build test vectors.
class BitWriter {
public:
void write(std::uint32_t value, unsigned count) {
for (unsigned i = count; i-- > 0;) {
const std::uint8_t bit = static_cast<std::uint8_t>((value >> i) & 1u);
if (used_ == 0) {
bytes_.push_back(0);
}
bytes_.back() |= static_cast<std::uint8_t>(bit << (7u - used_));
used_ = (used_ + 1u) % 8u;
}
}
const std::vector<std::uint8_t>& bytes() const { return bytes_; }
private:
std::vector<std::uint8_t> bytes_;
unsigned used_ = 0;
};
void test_variable_bits() {
// 300 with width 8 is two groups: 0 (continue) then 44 (stop).
BitWriter writer;
writer.write(0, 8);
writer.write(1, 1);
writer.write(44, 8);
writer.write(0, 1);
joc::bits::BitReader reader(writer.bytes().data(), writer.bytes().size());
std::uint32_t value = 0;
CHECK(joc::bits::variable_bits(reader, 8, 8, &value));
CHECK(value == 300);
// Eight continuation groups exceed the limit and must fail, not loop.
BitWriter endless;
for (int group = 0; group < 8; ++group) {
endless.write(0, 8);
endless.write(1, 1);
}
joc::bits::BitReader endless_reader(endless.bytes().data(), endless.bytes().size());
CHECK(!joc::bits::variable_bits(endless_reader, 8, 8, &value));
CHECK(endless_reader.error() == JOC_ERR_EMDF_SYNTAX);
}
void test_eac3_frame_bytes() {
std::vector<std::uint8_t> frame(3072, 0);
frame[0] = 0x0B;
frame[1] = 0x77;
frame[2] = 0x05;
frame[3] = 0xFF; // frmsiz words = 1536 -> 3072 bytes
frame[5] = 0x80; // bsid (bits 40..44) = 16 marks E-AC-3
std::size_t size = 0;
CHECK(joc::eac3::FrameReader::frame_bytes(frame.data(), frame.size(), 0, &size) == JOC_OK);
CHECK(size == 3072);
CHECK(joc::eac3::FrameReader::frame_bytes(frame.data(), 100, 0, &size) ==
JOC_ERR_BITSTREAM_TRUNCATED);
frame[1] = 0x78;
CHECK(joc::eac3::FrameReader::frame_bytes(frame.data(), frame.size(), 0, &size) ==
JOC_ERR_EAC3_SYNCFRAME);
// bsid <= 8 is AC-3: the frame length comes from fscod/frmsizecod instead.
std::vector<std::uint8_t> ac3(2560, 0);
ac3[0] = 0x0B;
ac3[1] = 0x77;
ac3[4] = 0x24; // fscod = 0, frmsizecod = 36 -> 1280 words -> 2560 bytes
ac3[5] = 0x30; // bsid = 6
CHECK(joc::eac3::FrameReader::frame_bytes(ac3.data(), ac3.size(), 0, &size) == JOC_OK);
CHECK(size == 2560);
CHECK(joc::eac3::FrameReader::frame_bytes(ac3.data(), ac3.size() - 1, 0, &size) ==
JOC_ERR_BITSTREAM_TRUNCATED);
}
void test_mini_json() {
const std::string text = R"({"a":1,"b":"x\ny","c":{"d":true},"e":-2.5})";
std::vector<joc::json::Member> members;
std::string error;
CHECK(joc::json::parse_object(text, &members, &error));
double number = 0.0;
CHECK(joc::json::as_number(*joc::json::find(members, "a"), &number) && number == 1.0);
CHECK(joc::json::as_number(*joc::json::find(members, "e"), &number) && number == -2.5);
std::string value;
CHECK(joc::json::as_string(*joc::json::find(members, "b"), &value) && value == "x\ny");
CHECK(joc::json::find(members, "c")->raw == R"({"d":true})");
std::vector<joc::json::Member> duplicate;
CHECK(!joc::json::parse_object(R"({"a":1,"a":2})", &duplicate, &error));
CHECK(!joc::json::parse_object("[1,2]", &duplicate, &error));
}
void test_json_text() {
// Escaping matches json.dumps(..., ensure_ascii=False): the named escapes,
// \u00XX for the other control characters, UTF-8 bytes passed through.
CHECK(joc::json::quote("") == "\"\"");
CHECK(joc::json::quote("a\"b\\c") == "\"a\\\"b\\\\c\"");
CHECK(joc::json::quote("x\ny\tz") == "\"x\\ny\\tz\"");
CHECK(joc::json::quote(std::string("\b\f", 2u)) == "\"\\b\\f\"");
CHECK(joc::json::quote("\x01") == "\"\\u0001\"");
CHECK(joc::json::quote("月と私") == "\"月と私\"");
// Two-space indentation, one member per line, no trailing newline.
CHECK(joc::json::pretty_object({}) == "{}");
const std::string document = joc::json::pretty_object({
{"status", "0"},
{"message", joc::json::quote("cannot open C:\\out\\a.wav")},
});
CHECK(document == "{\n \"status\": 0,\n \"message\": "
"\"cannot open C:\\\\out\\\\a.wav\"\n}");
std::vector<joc::json::Member> members;
std::string error;
CHECK(joc::json::parse_object(document, &members, &error));
std::string message;
CHECK(joc::json::as_string(*joc::json::find(members, "message"), &message) &&
message == "cannot open C:\\out\\a.wav");
}
void test_task_result_json() {
joc_task_result result{};
result.struct_size = sizeof(result);
result.status = JOC_TASK_FAILED;
result.error_code = JOC_ERR_OUTPUT_OPEN;
std::snprintf(result.error_stage, sizeof(result.error_stage), "%s", "output");
// A Windows path and a quote in the message: the document has to stay valid.
std::snprintf(result.error_message, sizeof(result.error_message), "%s",
"cannot write \"C:\\out\\a.wav\"");
result.output_peak = 1.5;
result.t_total = 6.355818;
std::string text;
CHECK(joc::task::result_to_json(result, &text).ok());
CHECK(text.find("\n \"error_message\": ") != std::string::npos);
std::vector<joc::json::Member> members;
std::string error;
CHECK(joc::json::parse_object(text, &members, &error));
std::string message;
CHECK(joc::json::as_string(*joc::json::find(members, "error_message"), &message) &&
message == "cannot write \"C:\\out\\a.wav\"");
double number = 0.0;
CHECK(joc::json::as_number(*joc::json::find(members, "output_peak"), &number) && number == 1.5);
CHECK(joc::json::as_number(*joc::json::find(members, "t_total"), &number) &&
number == 6.355818);
}
void test_npy() {
// Build a minimal <f8 (2,) image in memory, padded the way NumPy pads it.
std::string header = "{'descr': '<f8', 'fortran_order': False, 'shape': (2,), }";
const std::size_t prefix = 10; // magic + version + uint16 header length
while ((prefix + header.size() + 1) % 64 != 0) {
header.push_back(' ');
}
header.push_back('\n');
std::vector<std::uint8_t> image;
const char magic[6] = {'\x93', 'N', 'U', 'M', 'P', 'Y'};
image.insert(image.end(), magic, magic + 6);
image.push_back(1);
image.push_back(0);
image.push_back(static_cast<std::uint8_t>(header.size() & 0xFFu));
image.push_back(static_cast<std::uint8_t>(header.size() >> 8));
image.insert(image.end(), header.begin(), header.end());
const double values[2] = {1.5, -0.25};
const std::uint8_t* raw = reinterpret_cast<const std::uint8_t*>(values);
image.insert(image.end(), raw, raw + sizeof(values));
joc::io::NpyArray array;
std::string error;
CHECK(joc::io::parse_npy(image.data(), image.size(), &array, &error));
CHECK(array.descr == "<f8");
CHECK(array.shape.size() == 1 && array.shape[0] == 2);
CHECK(!array.fortran_order);
std::vector<double> loaded;
CHECK(joc::io::npy_to_double(array, &loaded, &error));
CHECK(loaded.size() == 2 && loaded[0] == 1.5 && loaded[1] == -0.25);
}
void test_oamd_and_adm_helpers() {
CHECK(joc::oamd::q_of(0, 62) == 0);
CHECK(joc::oamd::q_of(62, 62) == 32767);
CHECK(joc::oamd::q_of(31, 62) == 16384);
CHECK(joc::oamd::q_of(15, 15) == 32767);
CHECK(joc::adm::ts(0.0) == "00:00:00.00000");
CHECK(joc::adm::ts(1.5) == "00:00:01.50000");
CHECK(joc::adm::ts(3661.25) == "01:01:01.25000");
// 0.999999 s rounds to the next second, not to 100000 microseconds.
CHECK(joc::adm::ts(0.999999) == "00:00:01.00000");
double x = 0.0;
double y = 0.0;
double z = 0.0;
joc::geometry::q_to_adm_xyz(0, 32767, 0, &x, &y, &z);
CHECK(x == -1.0 && y == -1.0 && z == 0.0);
joc::geometry::q_to_adm_xyz(32767, 0, 0, &x, &y, &z);
CHECK(x == 1.0 && y == 1.0 && z == 0.0);
}
// DBMD segment 10: the nine configuration trims must default to automatic (bit 0
// of each trim's first byte), and every other field of the block must keep the
// layout the writer has always produced.
// Spherical interpolation mesh: a 200-point Fibonacci sphere exercises the hull,
// the barycentric weights and the Voronoi areas against values captured from the
// reference implementation.
void test_spherical_mesh() {
constexpr int kPoints = 200;
const double pi = 3.14159265358979323846;
std::vector<double> directions;
directions.reserve(static_cast<std::size_t>(kPoints) * 3u);
for (int index = 0; index < kPoints; ++index) {
const double z = 1.0 - 2.0 * (static_cast<double>(index) + 0.5) / kPoints;
const double phi = static_cast<double>(index) * pi * (3.0 - std::sqrt(5.0));
const double radius = std::sqrt(std::max(0.0, 1.0 - z * z));
directions.push_back(radius * std::cos(phi));
directions.push_back(radius * std::sin(phi));
directions.push_back(z);
}
joc::hrtf::SphericalMesh mesh;
joc::Status status = mesh.build(directions, kPoints);
CHECK(status.ok());
CHECK(mesh.vertex_count() == 200u);
CHECK(mesh.face_count() == 396u);
const double query[3] = {0.30304576336566319, 0.5050762722761053, 0.80812203564176865};
const int expected_ids[3] = {16, 11, 24};
const double expected_weights[3] = {0.18552244832037465, 0.23319383531074916,
0.5812837163688762};
std::vector<int> ids;
std::vector<double> weights;
status = mesh.weights(query, &ids, &weights);
CHECK(status.ok());
CHECK(ids.size() == 3u);
double difference = 0.0;
for (std::size_t index = 0; index < ids.size(); ++index) {
double expected = 0.0;
for (int corner = 0; corner < 3; ++corner) {
if (expected_ids[corner] == ids[index]) {
expected = expected_weights[corner];
}
}
difference += std::fabs(weights[index] - expected);
}
CHECK(difference < 1e-9);
CHECK(std::fabs(weights[0] + weights[1] + weights[2] - 1.0) < 1e-12);
std::vector<double> areas;
mesh.voronoi_areas(&areas);
CHECK(areas.size() == 200u);
double smallest = areas[0];
double largest = areas[0];
double total = 0.0;
for (const double area : areas) {
smallest = std::min(smallest, area);
largest = std::max(largest, area);
total += area;
}
CHECK(std::fabs(total - 1.0) < 1e-12);
CHECK(std::fabs(largest / smallest - 1.1197648114672005) < 1e-9);
}
// Point-source reference: the ADM position selects a listener-frame direction and
// a distance scaled by the mode's reference distance.
void test_reference_distance() {
double near = 0.0;
double mid = 0.0;
double far = 0.0;
CHECK(joc::binaural::source_reference_distance("near", &near).ok());
CHECK(joc::binaural::source_reference_distance("mid", &mid).ok());
CHECK(joc::binaural::source_reference_distance("far", &far).ok());
CHECK(std::fabs(near - 1.00000465) < 1e-12);
CHECK(std::fabs(mid - 2.19327927) < 1e-12);
CHECK(std::fabs(far - 6.40177584) < 1e-12);
CHECK(!joc::binaural::source_reference_distance("wide", &near).ok());
joc::binaural::DistanceState state;
state.profile = "near";
state.physical_distance_m = 2.0;
state.normalized_radius = 0.5;
CHECK(joc::binaural::direct_level_gain(state) == 1.0);
CHECK(std::fabs(joc::binaural::late_send(state) - 0.042426406871192854) < 1e-15);
state.profile = "mid";
CHECK(std::fabs(joc::binaural::direct_level_gain(state) - 0.97463184619707621) < 1e-15);
CHECK(std::fabs(joc::binaural::late_send(state) - 0.11313708498984762) < 1e-15);
state.profile = "far";
CHECK(std::fabs(joc::binaural::late_send(state) - 0.19798989873223333) < 1e-15);
const std::array<double, 3> front = {0.0, 1.0, 0.0};
CHECK(joc::binaural::map_adm_position(front, "mid", &state).ok());
CHECK(std::fabs(state.physical_distance_m - 2.19327927) < 1e-12);
CHECK(std::fabs(state.direction_adm[1] - 1.0) < 1e-15);
const std::array<double, 3> origin = {0.0, 0.0, 0.0};
CHECK(joc::binaural::map_adm_position(origin, "mid", &state).ok());
CHECK(std::fabs(state.physical_distance_m - joc::binaural::kMinimumSourceDistanceM) < 1e-15);
double gain = 0.0;
CHECK(joc::binaural::inverse_distance_gain(1.2, 2.4, &gain).ok());
CHECK(std::fabs(gain - 0.5) < 1e-15);
CHECK(!joc::binaural::inverse_distance_gain(1.2, 0.0, &gain).ok());
}
void test_point_source() {
joc::binaural::PointSourceReference reference;
CHECK(reference.configure("mid", false, 0.0).ok());
CHECK(reference.mode() == "mid");
CHECK(std::fabs(reference.reference_distance_m() - 2.19327927) < 1e-12);
const std::array<double, 3> front = {0.0, 1.0, 0.0};
joc::binaural::PointSourcePosition position;
CHECK(reference.map_position(front, nullptr, &position).ok());
CHECK(std::fabs(position.direction[0] - 1.0) < 1e-15);
CHECK(std::fabs(position.direction[1]) < 1e-15);
CHECK(std::fabs(position.distance_m - 2.1932792700000001) < 1e-12);
CHECK(std::fabs(position.normalized_radius - 1.0) < 1e-15);
const std::array<double, 3> side = {-0.8, 0.2, 0.6};
CHECK(reference.map_position(side, nullptr, &position).ok());
CHECK(std::fabs(position.direction[0] - 0.19611613513818402) < 1e-12);
CHECK(std::fabs(position.direction[1] - 0.7844645405527361) < 1e-12);
CHECK(std::fabs(position.distance_m - 2.2367147592977079) < 1e-12);
const std::array<double, 3> origin = {0.0, 0.0, 0.0};
const std::array<double, 3> previous = {0.0, -1.0, 0.0};
CHECK(reference.map_position(origin, &previous, &position).ok());
CHECK(std::fabs(position.direction[1] + 1.0) < 1e-15);
CHECK(reference.map_position(origin, nullptr, &position).ok());
CHECK(std::fabs(position.direction[0] - 1.0) < 1e-15);
joc::binaural::PointSourceReference overridden;
CHECK(overridden.configure("far", true, 3.5).ok());
CHECK(overridden.mode() == "far");
CHECK(std::fabs(overridden.reference_distance_m() - 3.5) < 1e-15);
CHECK(!overridden.configure("far", true, 0.0).ok());
}
// Six first-order image sources of the project shoebox, against the reference.
void test_shoebox_room() {
const joc::binaural::ShoeboxRoomConfig config;
CHECK(config.validate().ok());
joc::binaural::ShoeboxRoomConfig invalid;
invalid.listener_position_m = {0.0, 9.0, 7.0};
CHECK(!invalid.validate().ok());
const std::array<double, 3> direction = {0.0, 1.0, 0.0};
std::vector<joc::binaural::EarlyReflection> paths;
CHECK(joc::binaural::first_order_image_sources(direction, 2.0, 48000.0, config, &paths).ok());
CHECK(paths.size() == 6u);
const char* const walls[6] = {"left", "right", "back", "front", "floor", "ceiling"};
const double distances[6] = {18.110770276275, 18.110770276275, 20.0, 16.0,
14.142135623731, 14.142135623731};
const double delays[6] = {2252.598232627999, 2252.598232627999, 2516.749198951355,
1957.471599184387, 1697.706116921310, 1697.706116921310};
const double gains[6] = {0.600341066264, 0.580975225417, 0.559491370220, 0.593156903749,
0.507524274007, 0.546564602777};
for (std::size_t index = 0; index < 6u; ++index) {
CHECK(paths[index].wall == walls[index]);
CHECK(std::fabs(paths[index].path_distance_m - distances[index]) < 1e-9);
CHECK(std::fabs(paths[index].extra_delay_samples - delays[index]) < 1e-6);
CHECK(std::fabs(paths[index].reflection_gain - gains[index]) < 1e-9);
}
CHECK(std::fabs(paths[0].direction_adm[0] + 0.993883734674) < 1e-9);
CHECK(std::fabs(paths[1].direction_adm[0] - 0.993883734674) < 1e-9);
CHECK(std::fabs(paths[2].direction_adm[1] + 1.0) < 1e-12);
// A source outside the shoebox is rejected instead of producing a path.
std::vector<joc::binaural::EarlyReflection> outside;
CHECK(!joc::binaural::first_order_image_sources(direction, 12.0, 48000.0, config, &outside).ok());
joc::binaural::ShoeboxRoomConfig compact;
compact.dimensions_m = {8.5, 11.3, 5.2};
compact.listener_position_m = {4.25, 5.65, 2.6};
CHECK(compact.validate().ok());
}
void test_dbmd_auto_trim() {
std::string dbmd;
CHECK(joc::adm::build_dbmd(25, joc::adm::BinauralMode::Mid, &dbmd).ok());
std::string segment10;
std::size_t offset = 4;
while (offset + 2 < dbmd.size() && static_cast<unsigned char>(dbmd[offset]) != 0) {
const std::size_t size =
static_cast<std::size_t>(static_cast<unsigned char>(dbmd[offset + 1])) |
(static_cast<std::size_t>(static_cast<unsigned char>(dbmd[offset + 2])) << 8);
const std::size_t start = offset + 3;
CHECK(start + size + 1 <= dbmd.size());
unsigned sum = static_cast<unsigned>(size);
for (std::size_t i = 0; i < size; ++i) {
sum += static_cast<unsigned char>(dbmd[start + i]);
}
sum += static_cast<unsigned char>(dbmd[start + size]);
CHECK((sum & 0xFFu) == 0u);
if (static_cast<unsigned char>(dbmd[offset]) == 10) {
segment10 = dbmd.substr(start, size);
}
offset = start + size + 1;
}
CHECK(segment10.size() == 292);
CHECK(static_cast<unsigned char>(segment10[0]) == 0xBD);
CHECK(static_cast<unsigned char>(segment10[1]) == 0x6F);
CHECK(static_cast<unsigned char>(segment10[2]) == 0x72);
CHECK(static_cast<unsigned char>(segment10[3]) == 0xF8);
CHECK(static_cast<unsigned char>(segment10[4]) == 25);
CHECK(static_cast<unsigned char>(segment10[5]) == 0);
CHECK(static_cast<unsigned char>(segment10[6]) == 0);
// Nine 15-byte configuration trims: automatic, payload untouched.
for (std::size_t layout = 0; layout < 9; ++layout) {
const std::size_t flag = 7 + 15 * layout;
CHECK(static_cast<unsigned char>(segment10[flag]) == 0x01);
for (std::size_t i = 1; i < 15; ++i) {
CHECK(static_cast<unsigned char>(segment10[flag + i]) == 0);
}
}
// One trim-bypass byte per track stays clear.
for (std::size_t i = 7 + 9 * 15; i < 7 + 9 * 15 + 25; ++i) {
CHECK(static_cast<unsigned char>(segment10[i]) == 0);
}
// Headphone modes: bed tracks clear, the object slots carry the mode value.
for (std::size_t i = 0; i < 25; ++i) {
const unsigned char expected = i < 10 ? 0x00 : 0x03;
CHECK(static_cast<unsigned char>(segment10[7 + 9 * 15 + 25 + i]) == expected);
}
// Nothing between the mode array and the trailing template fill changed.
for (std::size_t i = 7 + 9 * 15 + 2 * 25; i < 5 + 262; ++i) {
CHECK(static_cast<unsigned char>(segment10[i]) == 0);
}
for (std::size_t i = 5 + 262; i < segment10.size(); ++i) {
CHECK(static_cast<unsigned char>(segment10[i]) == 0x84);
}
}
void test_int24_packing() {
// Interleaved (L,R) for two frames: 0.0, +1.0, -1.0, +2.0 (clips).
const float values[4] = {0.0f, 1.0f, -1.0f, 2.0f};
std::string packed;
joc::io::pack_int24(values, 2, 2, &packed);
CHECK(packed.size() == 12);
auto byte = [&](std::size_t index) {
return static_cast<std::uint8_t>(packed[index]);
};
CHECK(byte(0) == 0x00 && byte(1) == 0x00 && byte(2) == 0x00); // 0.0
CHECK(byte(3) == 0xFF && byte(4) == 0xFF && byte(5) == 0x7F); // +1.0
CHECK(byte(6) == 0x01 && byte(7) == 0x00 && byte(8) == 0x80); // -1.0
CHECK(byte(9) == 0xFF && byte(10) == 0xFF && byte(11) == 0x7F); // +2.0 clips
}
void test_utf8_paths() {
// Non-ASCII paths must survive the OS boundary on every platform: this is the
// regression guard for the ANSI-code-page bug class (a Japanese path used to
// reach ffmpeg as mojibake on Windows).
const std::string directory = joc::fs_utf8::temp_directory();
CHECK(!directory.empty());
const std::string path = joc::fs_utf8::from_path(
joc::fs_utf8::to_path(directory) / joc::fs_utf8::to_path("joc_テスト_須田景凪_测试.bin"));
CHECK(joc::fs_utf8::from_path(joc::fs_utf8::to_path(path)) == path);
std::FILE* file = joc::fs_utf8::fopen(path, "wb");
CHECK(file != nullptr);
if (file != nullptr) {
const char payload[] = "joc-utf8";
CHECK(std::fwrite(payload, 1, sizeof(payload) - 1u, file) == sizeof(payload) - 1u);
std::fclose(file);
}
CHECK(joc::fs_utf8::exists(path));
std::error_code error;
CHECK(joc::fs_utf8::file_size(path, error) == sizeof("joc-utf8") - 1u);
std::ifstream input = joc::fs_utf8::open_input(path);
CHECK(input.good());
std::string content(sizeof("joc-utf8") - 1u, '\0');
input.read(content.data(), static_cast<std::streamsize>(content.size()));
CHECK(content == "joc-utf8");
input.close();
std::ofstream output = joc::fs_utf8::open_output(path + ".copy");
CHECK(output.good());
output << content;
output.close();
CHECK(joc::fs_utf8::exists(path + ".copy"));
CHECK(joc::fs_utf8::remove(path) == 0);
CHECK(joc::fs_utf8::remove(path + ".copy") == 0);
CHECK(!joc::fs_utf8::exists(path));
}
void test_process_runner() {
// The ffmpeg boundary must surface both the exit code and the child's stderr.
#if defined(_WIN32)
const std::vector<std::string> command = {"cmd.exe", "/c", "echo boom 1>&2 & exit 3"};
#else
const std::vector<std::string> command = {"/bin/sh", "-c", "echo boom 1>&2; exit 3"};
#endif
joc::io::ProcessResult result;
const joc::Status status = joc::io::run_process(command, &result);
CHECK(!status.ok());
CHECK(result.exit_code == 3u);
CHECK(result.output.find("boom") != std::string::npos);
}
void test_find_executable() {
// An executable reference has to become a concrete path: that is what turns the
// default "ffmpeg" into something a child process starts without a PATH search of
// its own, on both platforms.
const std::string bare =
#if defined(_WIN32)
"cmd";
#else
"sh";
#endif
const std::string resolved = joc::fs_utf8::find_executable(bare);
CHECK(!resolved.empty());
CHECK(resolved.find_first_of("/\\") != std::string::npos);
CHECK(joc::fs_utf8::exists(resolved));
// An already concrete path is kept verbatim instead of being searched for again.
CHECK(joc::fs_utf8::find_executable(resolved) == resolved);
CHECK(joc::fs_utf8::find_executable("").empty());
CHECK(joc::fs_utf8::find_executable("joc_no_such_program_9f2c").empty());
// A reference with a directory separator names a location, so it is never answered
// by a same-named program found somewhere else.
CHECK(joc::fs_utf8::find_executable("joc_no_such_dir/joc_no_such_program_9f2c").empty());
#if !defined(_WIN32)
// Without the execute bit the kernel refuses the file, so it is not a match.
const std::string plain = joc::fs_utf8::from_path(
joc::fs_utf8::to_path(joc::fs_utf8::temp_directory()) /
joc::fs_utf8::to_path("joc_not_executable_9f2c"));
std::FILE* file = joc::fs_utf8::fopen(plain, "wb");
CHECK(file != nullptr);
if (file != nullptr) {
std::fclose(file);
}
CHECK(joc::fs_utf8::find_executable(plain).empty());
CHECK(joc::fs_utf8::remove(plain) == 0);
#endif
}
void test_npy_and_zip_writers() {
using joc::io::NpyMember;
// Python's repr, which is what json.dumps writes into the cache metadata.
CHECK(joc::io::python_float_repr(48000.0) == "48000.0");
CHECK(joc::io::python_float_repr(1.0) == "1.0");
CHECK(joc::io::python_float_repr(0.001) == "0.001");
CHECK(joc::io::python_float_repr(1.0e-5) == "1e-05");
CHECK(joc::io::python_float_repr(1.5) == "1.5");
CHECK(joc::io::python_float_repr(-2.25) == "-2.25");
CHECK(joc::io::python_float_repr(1.0e16) == "1e+16");
CHECK(joc::io::python_float_repr(1234567890123456.0) == "1234567890123456.0");
// An NPY image must round-trip through the reader that loads the cache.
const std::vector<double> values = {1.5, -2.25, 3.75, 4.0, 0.5, 0.25};
std::vector<std::uint8_t> payload(values.size() * sizeof(double));
std::memcpy(payload.data(), values.data(), payload.size());
const std::vector<std::uint8_t> image = joc::io::npy_image("<f8", {2u, 3u}, payload);
joc::io::NpyArray array;
std::string error;
CHECK(joc::io::parse_npy(image.data(), image.size(), &array, &error));
CHECK(array.descr == "<f8");
CHECK(joc::io::npy_shape_is(array, {2, 3}));
std::vector<double> restored;
CHECK(joc::io::npy_to_double(array, &restored, &error));
CHECK(restored.size() == values.size());
bool same = restored.size() == values.size();
for (std::size_t index = 0; index < restored.size() && same; ++index) {
same = restored[index] == values[index];
}
CHECK(same);
// A Unicode scalar string member, as the cache stores its metadata.
const std::string text = "{\"k\":\"v\"}";
const std::vector<std::uint8_t> unicode = joc::io::utf8_to_utf32le(text);
CHECK(unicode.size() == text.size() * 4u);
CHECK(unicode[0] == static_cast<std::uint8_t>('{') && unicode[1] == 0u &&
unicode[3] == 0u);
const std::vector<std::uint8_t> text_image =
joc::io::npy_image("<U" + std::to_string(text.size()), {}, unicode);
CHECK(joc::io::parse_npy(text_image.data(), text_image.size(), &array, &error));
std::string decoded;
CHECK(joc::io::npy_unicode_to_utf8(array, &decoded, &error));
CHECK(decoded == text);
// The ZIP container round-trips through the archive reader.
const std::string path = joc::fs_utf8::temp_directory() + "/joc_writer_test.jochrtf";
std::vector<NpyMember> members;
NpyMember member;
member.name = "band_center_frequencies_hz";
member.descr = "<f8";
member.shape = {2u, 3u};
member.data = payload;
members.push_back(member);
CHECK(joc::io::write_zip(path, members, &error));
joc::io::ZipArchive archive;
CHECK(archive.open(path, &error));
CHECK(archive.entries().size() == 1u);
std::vector<std::uint8_t> read_back;
CHECK(archive.read_member("band_center_frequencies_hz.npy", &read_back, &error));
CHECK(read_back.size() == image.size());
CHECK(read_back.size() == image.size() &&
std::memcmp(read_back.data(), image.data(), image.size()) == 0);
CHECK(joc::fs_utf8::remove(path) == 0);
}
// ---------------------------------------------------------------------------
// HRTF import and compile path.
//
// Everything below builds its input in memory, so the suite reads no external
// files; the parts that need one are exercised through their error paths.
// ---------------------------------------------------------------------------
constexpr double kPi = 3.14159265358979323846;
// A SimpleFreeFieldHRIR set with `measurements` directions on one 1 m shell and
// `taps` decaying taps per ear. The values are closed-form placeholders; what
// the canonicaliser and the spherical-harmonic fit actually read is the
// geometry and the shape.
joc::hrtf::SofaHrir synthetic_sofa(std::uint32_t measurements, std::uint32_t taps) {
joc::hrtf::SofaHrir sofa;
sofa.sample_rate = 48000.0;
sofa.sampling_rate_units = "hertz";
sofa.ir_count = measurements;
sofa.ir_length = taps;
sofa.conventions = "SOFA";
sofa.sofa_conventions = "SimpleFreeFieldHRIR";
sofa.convention_version = "1.0";
sofa.version = "1.0";
sofa.data_type = "FIR";
sofa.room_type = "free field";
sofa.receiver_position[0] = 0.0;
sofa.receiver_position[1] = 0.09;
sofa.receiver_position[2] = 0.0;
sofa.receiver_position[3] = 0.0;
sofa.receiver_position[4] = -0.09;
sofa.receiver_position[5] = 0.0;
sofa.source_position_coordinates.type = "spherical";
sofa.source_position_coordinates.units = "degree, degree, metre";
sofa.emitter_position_coordinates.type = "cartesian";
sofa.emitter_position_coordinates.units = "metre";
sofa.listener_position_coordinates.type = "cartesian";
sofa.listener_position_coordinates.units = "metre";
sofa.listener_view_coordinates.type = "cartesian";
sofa.listener_view_coordinates.units = "metre";
sofa.receiver_position_coordinates.type = "cartesian";
sofa.receiver_position_coordinates.units = "metre";
sofa.source_sha256 = std::string(64u, '0');
sofa.source_position.assign(static_cast<std::size_t>(measurements) * 3u, 0.0);
sofa.ir.assign(static_cast<std::size_t>(measurements) * 2u * taps, 0.0);
for (std::uint32_t index = 0; index < measurements; ++index) {
// Fibonacci sphere: an even spread over the whole sphere, every point at
// one metre, so the set is a single shell.
const double unit = (static_cast<double>(index) + 0.5) / static_cast<double>(measurements);
const double elevation = std::asin(2.0 * unit - 1.0);
const double azimuth =
2.0 * kPi * std::fmod(static_cast<double>(index) * 0.6180339887498949, 1.0);
sofa.source_position[index * 3u + 0u] = azimuth * 180.0 / kPi;
sofa.source_position[index * 3u + 1u] = elevation * 180.0 / kPi;
sofa.source_position[index * 3u + 2u] = 1.0;
for (std::uint32_t ear = 0; ear < 2u; ++ear) {
for (std::uint32_t tap = 0; tap < taps; ++tap) {
const double decay =
std::exp(-4.0 * static_cast<double>(tap) / static_cast<double>(taps));
const double phase = 0.2 * static_cast<double>(tap) +
0.05 * static_cast<double>(index) +
1.5 * static_cast<double>(ear) + elevation;
sofa.ir[(static_cast<std::size_t>(index) * 2u + ear) * taps + tap] =
decay * std::sin(phase);
}
}
}
return sofa;
}
void test_sofa_canonicalize() {
const joc::hrtf::SofaHrir sofa = synthetic_sofa(64u, 64u);
joc::hrtf::CanonicalHrtf canonical;
const joc::Status status = joc::hrtf::canonicalize_sofa(sofa, &canonical);
CHECK(status.ok());
if (!status.ok()) {
std::printf(" canonicalize_sofa failed: %s\n", status.message().c_str());
return;
}
CHECK(canonical.measurements == 64u && canonical.taps == 64u);
CHECK(canonical.sample_rate_hz == 48000.0);
CHECK(canonical.hrir.size() == 64u * 2u * 64u);
CHECK(canonical.delay_samples.size() == 64u * 2u);
CHECK(canonical.unit_directions.size() == 64u * 3u);
CHECK(canonical.source_position_cartesian_m.size() == 64u * 3u);
CHECK(canonical.left_receiver_index != canonical.right_receiver_index);
CHECK(canonical.left_receiver_index >= 0 && canonical.left_receiver_index < 2);
CHECK(canonical.right_receiver_index >= 0 && canonical.right_receiver_index < 2);
bool unit_length = canonical.unit_directions.size() == 64u * 3u;
bool one_shell = canonical.measurement_radius_m.size() == 64u;
for (std::size_t index = 0u; index < 64u; ++index) {
const double x = canonical.unit_directions[index * 3u + 0u];
const double y = canonical.unit_directions[index * 3u + 1u];
const double z = canonical.unit_directions[index * 3u + 2u];
unit_length = unit_length && std::abs(x * x + y * y + z * z - 1.0) < 1.0e-9;
one_shell = one_shell && std::abs(canonical.measurement_radius_m[index] - 1.0) < 1.0e-9;
}
CHECK(unit_length);
CHECK(one_shell);
// The shell the compile step selects, and the radius it reports for it.
double actual_radius = 0.0;
const std::vector<std::size_t> shell =
joc::hrtf::canonical_shell_indices(canonical, 0.5, &actual_radius);
CHECK(shell.size() == 64u);
CHECK(std::abs(actual_radius - 1.0) < 1.0e-9);
// The import is strict: each of these is a rejection, never a silent repair.
joc::hrtf::CanonicalHrtf rejected;
joc::hrtf::SofaHrir broken = sofa;
broken.conventions = "not-sofa";
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
broken = sofa;
broken.sofa_conventions = "SimpleFreeFieldHRTF";
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
broken = sofa;
broken.convention_version = "9.9";
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
broken = sofa;
broken.data_type = "FLOAT";
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
broken = sofa;
broken.room_type = "";
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
broken = sofa;
broken.sampling_rate_units = "furlongs";
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
broken = sofa;
broken.sample_rate = 0.0;
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
broken = sofa;
broken.ir[0] = std::numeric_limits<double>::quiet_NaN();
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
broken = sofa;
broken.delay[1] = -1.0;
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
broken = sofa;
broken.emitter_position[0] = 0.5;
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
broken = sofa;
broken.listener_view[0] = broken.listener_view[1] = broken.listener_view[2] = 0.0;
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
broken = sofa;
broken.listener_up[0] = 1.0; // parallel to ListenerView
broken.listener_up[1] = 0.0;
broken.listener_up[2] = 0.0;
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
broken = sofa;
broken.source_position[2] = -1.0; // a negative spherical radius
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
broken = sofa;
broken.ir.resize(7u);
CHECK(!joc::hrtf::canonicalize_sofa(broken, &rejected).ok());
}
void test_sofa_compile_and_cache() {
const joc::hrtf::SofaHrir sofa = synthetic_sofa(64u, 64u);
const joc::hrtf::CompileOptions options = joc::hrtf::CompileOptions();
joc::hrtf::Field field;
// The runtime field is fixed at fifth order and at 48 kHz.
joc::hrtf::CompileOptions wrong_order = options;
wrong_order.order = 3;
CHECK(!joc::hrtf::compile_sofa_field(sofa, wrong_order, &field).ok());
joc::hrtf::SofaHrir wrong_rate = sofa;
wrong_rate.sample_rate = 44100.0;
CHECK(!joc::hrtf::compile_sofa_field(wrong_rate, options, &field).ok());
const joc::Status status = joc::hrtf::compile_sofa_field(sofa, options, &field);
CHECK(status.ok());
if (!status.ok()) {
std::printf(" compile_sofa_field failed: %s\n", status.message().c_str());
return;
}
CHECK(field.order == 5);
CHECK(field.measurement_radius_m == 1.0);
CHECK(field.band_centers_hz.size() == 77u);
CHECK(field.coefficients.size() == 36u * 2u * 77u * 2u);
CHECK(field.delay_coefficients.size() == 36u * 2u);
CHECK(field.delay_bounds.size() == 4u);
CHECK(!field.cache_key.empty() && !field.payload_sha256.empty());
CHECK(!field.metadata_json.empty() && !field.delay_source.empty());
bool finite = true;
for (const double value : field.coefficients) {
finite = finite && std::isfinite(value);
}
for (const double value : field.delay_coefficients) {
finite = finite && std::isfinite(value);
}
CHECK(finite);
// The payload digest is a pure function of the compiled arrays.
CHECK(joc::hrtf::field_payload_sha256(field) == field.payload_sha256);
// The cache round-trips through the shipped writer and loader.
const std::string cache_path = joc::fs_utf8::temp_directory() + "/joc_test_cache.jochrtf";
CHECK(joc::hrtf::write_jochrtf(field, cache_path).ok());
joc::hrtf::Field reloaded;
const joc::Status loaded = joc::hrtf::load_jochrtf(cache_path, &reloaded);
CHECK(loaded.ok());
if (loaded.ok()) {
CHECK(reloaded.cache_key == field.cache_key);
CHECK(reloaded.source_sha256 == field.source_sha256);
CHECK(reloaded.order == field.order);
CHECK(reloaded.measurement_radius_m == field.measurement_radius_m);
CHECK(reloaded.band_centers_hz == field.band_centers_hz);
CHECK(reloaded.coefficients == field.coefficients);
CHECK(reloaded.delay_coefficients == field.delay_coefficients);
CHECK(reloaded.delay_bounds == field.delay_bounds);
CHECK(reloaded.payload_sha256 == field.payload_sha256);
}
// A cache is trusted only after its key and payload verify; a damaged one is
// rejected instead of being used.
CHECK(joc::hrtf::validate_jochrtf(cache_path, field.source_sha256, field.cache_key, nullptr)
.ok());
CHECK(!joc::hrtf::validate_jochrtf(cache_path, field.source_sha256, "00", nullptr).ok());
CHECK(joc::fs_utf8::remove(cache_path) == 0);
const std::string poisoned = joc::fs_utf8::temp_directory() + "/joc_test_poisoned.jochrtf";
CHECK(joc::io::write_zip(poisoned, {}, nullptr));
CHECK(!joc::hrtf::validate_jochrtf(poisoned, field.source_sha256, field.cache_key, nullptr)
.ok());
CHECK(!joc::hrtf::load_jochrtf(poisoned, &reloaded).ok());
CHECK(joc::fs_utf8::remove(poisoned) == 0);
}
void test_sofa_reader_errors() {
// No SOFA file is needed to check that the reader answers correctly: a path
// that does not exist and a file that is not HDF5 are distinct, reported
// errors rather than a partially filled structure.
joc::hrtf::SofaHrir sofa;
const std::string missing = joc::fs_utf8::temp_directory() + "/joc_absent.sofa";
const joc::Status absent = joc::hrtf::load_sofa(missing, &sofa);
CHECK(!absent.ok());
CHECK(!absent.message().empty());
CHECK(!joc::hrtf::load_sofa(std::string(), &sofa).ok());
CHECK(!joc::hrtf::load_sofa(missing, nullptr).ok());
const std::string garbage = joc::fs_utf8::temp_directory() + "/joc_garbage.sofa";
{
std::ofstream stream = joc::fs_utf8::open_output(garbage);
stream << "this is not an HDF5 container";
}
const joc::Status malformed = joc::hrtf::load_sofa(garbage, &sofa);
CHECK(!malformed.ok());
CHECK(!malformed.message().empty());
CHECK(joc::fs_utf8::remove(garbage) == 0);
}
void test_hrtf_cache_policy() {
// The policy parser and the miss path of the cache layer, neither of which
// needs a SOFA file.
joc::hrtf::CachePolicy policy = joc::hrtf::CachePolicy::None;
CHECK(joc::hrtf::parse_cache_policy("none", &policy).ok() &&
policy == joc::hrtf::CachePolicy::None);
CHECK(joc::hrtf::parse_cache_policy("memory", &policy).ok() &&
policy == joc::hrtf::CachePolicy::Memory);
CHECK(joc::hrtf::parse_cache_policy("disk", &policy).ok() &&
policy == joc::hrtf::CachePolicy::Disk);
CHECK(!joc::hrtf::parse_cache_policy("sometimes", &policy).ok());
joc::hrtf::SofaFieldRequest request;
request.sofa_path = joc::fs_utf8::temp_directory() + "/joc_absent.sofa";
request.policy = joc::hrtf::CachePolicy::Disk;
request.cache_dir = joc::fs_utf8::temp_directory() + "/joc_absent_cache";
joc::hrtf::Field field;
std::string written = "sentinel";
CHECK(!joc::hrtf::load_or_compile_sofa_field(request, &field, &written).ok());
}
void test_rosella_model_errors() {
// A real model is proprietary user data and is not part of this repository.
// What can be checked without one is that every malformed input is reported
// instead of being half-loaded.
joc::hrtf::RosellaModel model;
const std::string missing = joc::fs_utf8::temp_directory() + "/joc_absent.headphone";
CHECK(!joc::hrtf::load_personalized_headphone(missing, &model).ok());
CHECK(!joc::hrtf::load_personalized_headphone(missing, nullptr).ok());
const std::string raw = joc::fs_utf8::temp_directory() + "/joc_raw.headphone";
{
std::ofstream stream = joc::fs_utf8::open_output(raw);
stream << "rp binary model, not JSON";
}
const joc::Status raw_status = joc::hrtf::load_personalized_headphone(raw, &model);
CHECK(!raw_status.ok());
CHECK(raw_status.message().find("JSON") != std::string::npos);
CHECK(joc::fs_utf8::remove(raw) == 0);
const std::string empty = joc::fs_utf8::temp_directory() + "/joc_empty.headphone";
{
std::ofstream stream = joc::fs_utf8::open_output(empty);
stream << "{}";
}
CHECK(!joc::hrtf::load_personalized_headphone(empty, &model).ok());
CHECK(joc::fs_utf8::remove(empty) == 0);
const std::string no_coefficients = joc::fs_utf8::temp_directory() + "/joc_no_coeff.headphone";
{
std::ofstream stream = joc::fs_utf8::open_output(no_coefficients);
stream << "{\"personalized_hrtf\":{\"virtualizer_parameters\":{}}}";
}
const joc::Status status =
joc::hrtf::load_personalized_headphone(no_coefficients, &model);
CHECK(!status.ok());
CHECK(status.message().find("rosella_coefficients") != std::string::npos);
CHECK(joc::fs_utf8::remove(no_coefficients) == 0);
}
void test_builtin_kernel_tables() {
// The filterbank tables are compiled in, and their content must stay identical
// to the standard-defined archive the file loader accepts. The hashes below are
// the SHA-256 of each member's C-order bytes.
const joc::hrtf::Kernels& kernels = joc::hrtf::builtin_kernels();
CHECK(kernels.qmf_analysis.size() == 640);
CHECK(kernels.hybrid_low.size() == 2496);
CHECK(kernels.hybrid_indices.size() == 616);
CHECK(kernels.hybrid_values.size() == 154);
CHECK(kernels.qmf_basis.size() == 32768);
CHECK(kernels.qmf_taps.size() == 2560);
CHECK(kernels.hybrid_count == 154);
auto hash_floats = [](const std::vector<double>& values, bool narrow) {
joc::crypto::Sha256 hash;
if (narrow) {
std::vector<float> raw(values.size());
for (std::size_t i = 0; i < values.size(); ++i) {
raw[i] = static_cast<float>(values[i]);
}
hash.update(raw.data(), raw.size() * sizeof(float));
} else {
hash.update(values.data(), values.size() * sizeof(double));
}
return hash.finish_hex();
};
CHECK(hash_floats(kernels.qmf_analysis, true) ==
"aeff6c7117d41664b9c4bf03bbf563f5319ec1b8c551f171adbb90cf19d9d306");
CHECK(hash_floats(kernels.hybrid_low, true) ==
"d00d36133b81ba699a7630c4df1be203fa1b7e371e595eaaebbe8957db322627");
CHECK(hash_floats(kernels.hybrid_values, true) ==
"99409fdd9d20d1d7c2be16bbc1e2159c8042487227c72160850745164c9cee7f");
CHECK(hash_floats(kernels.qmf_basis, false) ==
"a0c4a55385f6d6c7c92d7615c83ad5fbda51046d9ef785cac0b9ac9a760dc527");
CHECK(hash_floats(kernels.qmf_taps, false) ==
"cd7756d060d51fbf02f44c1ce53cb6225b221099505c94c3f58d3bee6f428150");
joc::crypto::Sha256 indices;
indices.update(kernels.hybrid_indices.data(),
kernels.hybrid_indices.size() * sizeof(std::int16_t));
CHECK(indices.finish_hex() ==
"f5beb3220e4530fcf28e7f4da7f07e821074265d118c911d61a590e00753a573");
}
// Drives one objects16 stream over `block` and returns what it renders. With
// `frame_at_a_time` each push carries a single frame; otherwise the whole batch
// goes in at once. `peak` reports the largest backlog a push left behind.
std::vector<float> drive_objects16_stream(const std::vector<float>& block, std::size_t frames,
bool frame_at_a_time, std::size_t* peak) {
constexpr std::size_t kFrameValues = JOC_OUTPUT_CHANNELS * JOC_FRAME_SAMPLES;
joc::stream::Stream stream;
joc::stream::Config config;
config.input = JOC_STREAM_IN_PCM_OBJECTS16;
config.output = JOC_STREAM_OUT_SPEAKER;
config.layout = "5.1";
const joc::Status created = stream.create(config);
CHECK(created.ok());
if (!created.ok()) {
return {};
}
const std::size_t channels = stream.info().output_channels;
CHECK(channels != 0u);
std::vector<float> pulled(4096u * channels);
std::vector<float> rendered;
const auto drain = [&] {
for (;;) {
std::size_t produced = 0;
const joc::Status status = stream.pull(pulled.data(), 4096u, &produced);
CHECK(status.ok());
if (!status.ok() || produced == 0u) {
return;
}
rendered.insert(rendered.end(), pulled.begin(),
pulled.begin() + static_cast<std::ptrdiff_t>(produced * channels));
}
};
std::size_t consumed = 0;
while (consumed < frames) {
const std::size_t count = frame_at_a_time ? 1u : frames - consumed;
std::size_t taken = 0;
const joc::Status pushed = stream.push_objects16(
block.data() + consumed * kFrameValues, count * JOC_FRAME_SAMPLES, &taken);
CHECK(pushed.ok());
if (!pushed.ok()) {
return rendered;
}
// A push takes everything it is given; only the rendering is bounded.
CHECK(taken == count * JOC_FRAME_SAMPLES);
*peak = std::max(*peak, stream.buffered_samples());
consumed += taken / JOC_FRAME_SAMPLES;
drain();
}
CHECK(stream.flush().ok());
drain();
return rendered;
}
void test_rosella_filterbank_config() {
// validate() reports a selector it cannot honour instead of ignoring it: the
// captured bank needs the Rosella model, and any other value is out of range.
const auto reported = [](std::uint32_t selector, const char* personalized) {
joc_task_config config{};
config.struct_size = sizeof(config);
config.struct_version = JOC_TASK_CONFIG_VERSION;
config.input_path = "input.eac3";
config.output_path = "output.wav";
config.operation = JOC_OP_BINAURAL;
config.binaural_mode = JOC_BINAURAL_MID;
config.personalized_headphone_path = personalized;
config.hrtf_path = personalized == nullptr ? "cache.jochrtf" : nullptr;
config.rosella_filterbank = selector;
std::vector<joc_validation_issue> issues;
std::uint32_t errors = 0;
joc::task::validate(config, &issues, &errors);
for (const joc_validation_issue& issue : issues) {
if (std::string(issue.field) == "rosella_filterbank") {
return true;
}
}
return false;
};
CHECK(!reported(JOC_ROSELLA_FILTERBANK_PUBLIC, "model.personalized_headphone"));
CHECK(!reported(JOC_ROSELLA_FILTERBANK_CAPTURED, "model.personalized_headphone"));
CHECK(reported(3u, "model.personalized_headphone"));
CHECK(reported(JOC_ROSELLA_FILTERBANK_CAPTURED, nullptr));
}
// A push renders every frame it makes ready, so the stream bounds how far ahead of
// the caller it renders. A batch pushed at once must therefore leave a bounded
// backlog, and it must render the same samples as pushing one frame at a time.
void test_stream_render_ahead() {
constexpr std::size_t kFrames = 32;
constexpr std::size_t kFrameValues = JOC_OUTPUT_CHANNELS * JOC_FRAME_SAMPLES;
std::vector<float> block(kFrames * kFrameValues);
for (std::size_t index = 0; index < block.size(); ++index) {
block[index] = static_cast<float>(std::sin(static_cast<double>(index) * 0.0007) * 0.25);
}
std::size_t frame_peak = 0;
const std::vector<float> reference =
drive_objects16_stream(block, kFrames, true, &frame_peak);
std::size_t batch_peak = 0;
const std::vector<float> batched = drive_objects16_stream(block, kFrames, false, &batch_peak);
CHECK(!reference.empty());
CHECK(batched == reference);
// The batch is larger than the bound, so it cannot all be rendered at once.
CHECK(batch_peak < kFrames * JOC_FRAME_SAMPLES / 2u);
}
} // namespace
// The JOC clipgain is the analysis-side scalar's per-frame factor: it scales the
// frame that carries it, ramps over that frame's first 256 samples, starts from
// the frame's own value after a reset, and never reaches LFE.
struct ClipGainInputs {
std::vector<float> bed;
std::vector<float> lfe;
std::vector<std::uint8_t> n_bands;
std::vector<std::uint8_t> n_dpoints;
std::vector<std::uint8_t> slope;
std::vector<std::uint8_t> offsets;
std::vector<double> dq;
ClipGainInputs()
: bed(EJOC_CORE_CHANNELS * EJOC_FRAME_SAMPLES, 0.0f),
lfe(EJOC_FRAME_SAMPLES, 0.0f),
n_bands(EJOC_MAX_OBJECTS, 0),
n_dpoints(EJOC_MAX_OBJECTS, 0),
slope(EJOC_MAX_OBJECTS, 0),
offsets(EJOC_MAX_OBJECTS * EJOC_MAX_DPOINTS, 0),
dq(static_cast<std::size_t>(EJOC_MAX_OBJECTS) * EJOC_MAX_DPOINTS *
EJOC_MAX_CORE_CHANNELS * EJOC_MAX_PARAMETER_BANDS,
0.0) {
const double two_pi = 6.283185307179586476925286766559;
for (int sample = 0; sample < EJOC_FRAME_SAMPLES; ++sample) {
const double t = static_cast<double>(sample) / 48000.0;
bed[sample] = static_cast<float>(0.05 * std::sin(two_pi * 440.0 * t));
lfe[sample] = static_cast<float>(0.02 * std::sin(two_pi * 55.0 * t));
}
// Object 0 passes the first core channel through one parameter band.
n_bands[0] = 1;
n_dpoints[0] = 1;
dq[0] = 1.0;
}
};
bool clipgain_process(ejoc_renderer_handle handle, const ClipGainInputs& in, double clipgain,
std::vector<float>* out) {
out->assign(static_cast<std::size_t>(EJOC_OUTPUT_CHANNELS) * EJOC_FRAME_SAMPLES, 0.0f);
return ejoc_renderer_process(handle, in.bed.data(), in.lfe.data(), EJOC_CORE_CHANNELS, 0u, 1u,
in.n_bands.data(), in.n_dpoints.data(), in.slope.data(),
in.offsets.data(), in.dq.data(), clipgain, 0.0625f, 1.0f,
out->data()) == 0;
}
void test_clipgain_first_frame_uses_its_own_gain() {
const ClipGainInputs in;
std::vector<float> unity;
std::vector<float> doubled;
auto render = [&in](double clipgain, std::vector<float>* out) {
ejoc_renderer_handle handle = ejoc_renderer_create();
ejoc_renderer_set_threads(handle, 1);
const bool ok = clipgain_process(handle, in, clipgain, out);
ejoc_renderer_destroy(handle);
return ok;
};
CHECK(render(1.0, &unity));
CHECK(render(2.0, &doubled));
float peak = 0.0f;
bool scaled = true;
for (int sample = 0; sample < EJOC_FRAME_SAMPLES; ++sample) {
const float value = unity[EJOC_FRAME_SAMPLES + sample]; // object 0 is channel 1
peak = std::max(peak, std::fabs(value));
if (doubled[EJOC_FRAME_SAMPLES + sample] != 2.0f * value) {
scaled = false;
}
}
// A fresh handle takes the current gain with no transition.
CHECK(peak > 1.0e-3f);
CHECK(scaled);
// LFE bypasses the scalar, so its samples are bit-identical.
CHECK(std::memcmp(unity.data(), doubled.data(), sizeof(float) * EJOC_FRAME_SAMPLES) == 0);
}
void test_clipgain_change_applies_to_the_current_frame() {
const ClipGainInputs in;
std::vector<float> changed;
std::vector<float> held;
auto run = [&in](double second_gain, std::vector<float>* out) {
ejoc_renderer_handle handle = ejoc_renderer_create();
ejoc_renderer_set_threads(handle, 1);
std::vector<float> first;
const bool ok = clipgain_process(handle, in, 1.0, &first) &&
clipgain_process(handle, in, second_gain, out);
ejoc_renderer_destroy(handle);
return ok;
};
CHECK(run(2.0, &changed));
CHECK(run(1.0, &held));
// The change has to land in the frame carrying it; a one-frame-late gain
// would make these two frames identical.
double difference = 0.0;
double energy = 0.0;
for (int object = 1; object < EJOC_OUTPUT_CHANNELS; ++object) {
for (int sample = 0; sample < EJOC_FRAME_SAMPLES; ++sample) {
const std::size_t index =
static_cast<std::size_t>(object) * EJOC_FRAME_SAMPLES + sample;
difference += std::fabs(static_cast<double>(changed[index]) - held[index]);
energy += std::fabs(static_cast<double>(held[index]));
}
}
CHECK(difference > 0.05 * energy);
// The analysis delay lines and the QMF windows hold the new gain back by
// about 1400 samples, so the start of the frame still carries the old value
// and the end is scaled by the new one.
bool head_intact = true;
for (int sample = 0; sample < 256; ++sample) {
const std::size_t index = static_cast<std::size_t>(EJOC_FRAME_SAMPLES) + sample;
if (changed[index] != held[index]) {
head_intact = false;
}
}
CHECK(head_intact);
double tail = 0.0;
for (int sample = 1504; sample < EJOC_FRAME_SAMPLES; ++sample) {
const std::size_t index = static_cast<std::size_t>(EJOC_FRAME_SAMPLES) + sample;
tail = std::max(tail, std::fabs(static_cast<double>(changed[index]) -
2.0 * static_cast<double>(held[index])));
}
CHECK(tail < 1.0e-4);
}
void test_clipgain_reset_clears_the_previous_gain() {
const ClipGainInputs in;
std::vector<float> scratch;
std::vector<float> after_reset;
std::vector<float> fresh;
ejoc_renderer_handle handle = ejoc_renderer_create();
ejoc_renderer_set_threads(handle, 1);
CHECK(clipgain_process(handle, in, 3.0, &scratch));
CHECK(clipgain_process(handle, in, 3.0, &scratch));
CHECK(ejoc_renderer_reset(handle) == 0);
CHECK(clipgain_process(handle, in, 1.0, &after_reset));
ejoc_renderer_destroy(handle);
ejoc_renderer_handle pristine = ejoc_renderer_create();
ejoc_renderer_set_threads(pristine, 1);
CHECK(clipgain_process(pristine, in, 1.0, &fresh));
ejoc_renderer_destroy(pristine);
// No gain state may survive the reset: the first frame must match a fresh
// renderer instead of ramping down from the previous 3x.
CHECK(after_reset.size() == fresh.size());
CHECK(std::memcmp(after_reset.data(), fresh.data(),
sizeof(float) * after_reset.size()) == 0);
}
// CBA bed:每个声道的方位来自它的标签(ETSI TS 103 420 V1.2.1 table B.10),
// 声道顺序来自 table 12/13,因此 bed 声道不会随输出布局移动。
void test_bed_layout_map() {
using joc::joc::BedChannel;
using joc::joc::BedLayout;
double xyz[3] = {0.0, 0.0, 0.0};
CHECK(joc::joc::bed_channel_adm_position(BedChannel::kLeft, xyz));
CHECK(xyz[0] == -1.0 && xyz[1] == 1.0 && xyz[2] == 0.0);
CHECK(joc::joc::bed_channel_adm_position(BedChannel::kCenter, xyz));
CHECK(xyz[0] == 0.0 && xyz[1] == 1.0 && xyz[2] == 0.0);
CHECK(joc::joc::bed_channel_adm_position(BedChannel::kTopFrontLeft, xyz));
CHECK(xyz[0] == -1.0 && xyz[1] == 1.0 && xyz[2] == 1.0);
CHECK(joc::joc::bed_channel_adm_position(BedChannel::kTopFrontRight, xyz));
CHECK(xyz[0] == 1.0 && xyz[1] == 1.0 && xyz[2] == 1.0);
CHECK(joc::joc::bed_channel_adm_position(BedChannel::kTopSideLeft, xyz));
CHECK(xyz[0] == -1.0 && xyz[1] == 0.0 && xyz[2] == 1.0);
CHECK(joc::joc::bed_channel_adm_position(BedChannel::kTopBackLeft, xyz));
CHECK(xyz[0] == -1.0 && xyz[1] == -1.0 && xyz[2] == 1.0);
CHECK(joc::joc::bed_channel_adm_position(BedChannel::kTopBackRight, xyz));
CHECK(xyz[0] == 1.0 && xyz[1] == -1.0 && xyz[2] == 1.0);
CHECK(joc::joc::bed_channel_adm_position(BedChannel::kLeftWide, xyz));
CHECK(xyz[0] == -1.0 && xyz[1] == 21.0 / 31.0 && xyz[2] == 0.0);
CHECK(joc::joc::bed_channel_adm_position(BedChannel::kRightWide, xyz));
CHECK(xyz[0] == 1.0 && xyz[1] == 21.0 / 31.0 && xyz[2] == 0.0);
CHECK(joc::joc::bed_channel_adm_position(BedChannel::kLfe, xyz));
CHECK(xyz[0] == -1.0 && xyz[1] == 1.0 && xyz[2] == -1.0);
CHECK(joc::joc::bed_channel_adm_position(BedChannel::kLfe2, xyz));
CHECK(xyz[0] == 1.0 && xyz[1] == 1.0 && xyz[2] == -1.0);
std::uint16_t q15[3] = {0, 0, 0};
CHECK(joc::joc::bed_channel_q15(BedChannel::kLeft, q15));
CHECK(q15[0] == 0 && q15[1] == 0 && q15[2] == 0);
CHECK(joc::joc::bed_channel_q15(BedChannel::kTopFrontLeft, q15));
CHECK(q15[0] == 0 && q15[1] == 0 && q15[2] == 32767);
CHECK(joc::joc::bed_channel_q15(BedChannel::kLeftWide, q15));
CHECK(q15[0] == 0 && q15[1] == 5285 && q15[2] == 0);
CHECK(joc::joc::bed_channel_q15(BedChannel::kTopBackLeft, q15));
CHECK(q15[0] == 0 && q15[1] == 32767 && q15[2] == 32767);
// table 12:0x0F 是 5.1,0x1FF 是 9.1.6(不含 LFE2)。
std::vector<joc::oamd::BedAssignment> standard(1);
standard[0].standard = true;
standard[0].mask = 0x0Fu;
const BedLayout five_one = joc::joc::resolve_bed_layout(standard, true);
CHECK(five_one.present && five_one.bed_only && five_one.complete);
CHECK(std::string(five_one.name) == "5.1");
CHECK(five_one.channels.size() == 5);
CHECK(five_one.channels[0] == BedChannel::kLeft);
CHECK(five_one.channels[1] == BedChannel::kRight);
CHECK(five_one.channels[2] == BedChannel::kCenter);
CHECK(five_one.channels[3] == BedChannel::kLeftSurround);
CHECK(five_one.channels[4] == BedChannel::kRightSurround);
standard[0].mask = 0x1FFu;
const BedLayout nine_six = joc::joc::resolve_bed_layout(standard, true);
CHECK(std::string(nine_six.name) == "9.1.6");
CHECK(nine_six.channels.size() == 15);
CHECK(nine_six.channels[0] == BedChannel::kLeft);
CHECK(nine_six.channels[2] == BedChannel::kCenter);
CHECK(nine_six.channels[3] == BedChannel::kLeftSurround);
CHECK(nine_six.channels[7] == BedChannel::kTopFrontLeft);
CHECK(nine_six.channels[9] == BedChannel::kTopSideLeft);
CHECK(nine_six.channels[11] == BedChannel::kTopBackLeft);
CHECK(nine_six.channels[13] == BedChannel::kLeftWide);
CHECK(nine_six.channels[14] == BedChannel::kRightWide);
// LFE 留在声明掩码里,但不占 JOC 对象槽。
CHECK(joc::joc::bed_layout_has(nine_six, BedChannel::kLfe));
bool lfe_slot = false;
for (const BedChannel channel : nine_six.channels) {
lfe_slot = lfe_slot || channel == BedChannel::kLfe ||
channel == BedChannel::kLfe2;
}
CHECK(!lfe_slot);
CHECK(joc::joc::bed_layout_has(nine_six, BedChannel::kRightWide));
// table 13:17 bit 掩码的 channel order 与 table 12 相同。
std::vector<joc::oamd::BedAssignment> nonstandard(1);
nonstandard[0].standard = false;
nonstandard[0].mask = 0x3Fu;
const BedLayout ns_five = joc::joc::resolve_bed_layout(nonstandard, true);
CHECK(ns_five.channels.size() == 5);
CHECK(ns_five.channels[0] == BedChannel::kLeft);
CHECK(ns_five.channels[4] == BedChannel::kRightSurround);
nonstandard[0].mask = 0xFFFFu;
const BedLayout ns_nine = joc::joc::resolve_bed_layout(nonstandard, true);
CHECK(ns_nine.channels.size() == 15);
CHECK(ns_nine.channels[0] == BedChannel::kLeft);
CHECK(ns_nine.channels[13] == BedChannel::kLeftWide);
CHECK(ns_nine.channels[14] == BedChannel::kRightWide);
}
// Partitioned convolution: overlap-add with a shared input history and a filter
// crossfade. The expected values come from the reference
// partitioned_convolution.py running the same filters and blocks.
void test_partitioned_convolution() {
constexpr std::size_t kBlock = 128;
constexpr std::size_t kTaps = 300;
constexpr std::size_t kMaxTaps = 512;
constexpr std::size_t kOutputs = 2;
auto make_filter = [](double step, double decay, bool cosine, double offset) {
std::vector<double> values(kOutputs * kTaps);
for (std::size_t output = 0; output < kOutputs; ++output) {
for (std::size_t tap = 0; tap < kTaps; ++tap) {
const double angle = step * static_cast<double>(tap + 1) *
(static_cast<double>(output) + offset);
const double trig = cosine ? std::cos(angle) : std::sin(angle);
values[output * kTaps + tap] = trig * std::exp(-static_cast<double>(tap) / decay);
}
}
return values;
};
joc::hrtf::UniformPartitionedConvolver convolver(kOutputs, kMaxTaps, kBlock);
const std::vector<double> first = make_filter(0.017, 100.0, false, 1.0);
CHECK(convolver.set_filter(first.data(), kTaps, 0).ok());
CHECK(!convolver.transition_active());
std::vector<double> block(kBlock);
std::vector<double> out(kBlock * kOutputs);
std::vector<double> rendered;
for (std::size_t index = 0; index < 8; ++index) {
for (std::size_t sample = 0; sample < kBlock; ++sample) {
const double n = static_cast<double>(index * kBlock + sample);
block[sample] = std::sin(0.01 * n) + 0.5 * std::cos(0.003 * n);
}
CHECK(convolver.process_block(block.data(), out.data()).ok());
rendered.insert(rendered.end(), out.begin(), out.end());
}
CHECK(rendered.size() == 8 * kBlock * kOutputs);
CHECK(std::fabs(rendered[0] - 0.0084995905892490953) < 1e-9);
CHECK(std::fabs(rendered[1] - 0.016996724855971479) < 1e-9);
CHECK(std::fabs(rendered[2] - 0.025497145937656285) < 1e-9);
CHECK(std::fabs(rendered[63] - 8.1367456949245849) < 1e-9);
CHECK(std::fabs(rendered[64] - 4.6183248807335495) < 1e-9);
CHECK(std::fabs(rendered[65] - 8.5945567424849969) < 1e-9);
CHECK(std::fabs(rendered[127] - 24.744288415490566) < 1e-8);
CHECK(std::fabs(rendered[128] - 16.21718594261781) < 1e-8);
CHECK(std::fabs(rendered[129] - 25.258064041591062) < 1e-8);
CHECK(std::fabs(rendered[255] - 42.867139711879446) < 1e-8);
CHECK(std::fabs(rendered[256] - 47.087759632531053) < 1e-8);
CHECK(std::fabs(rendered[511] - 30.307479702394744) < 1e-8);
CHECK(std::fabs(rendered[512] - 64.6869976138059) < 1e-8);
CHECK(std::fabs(rendered[700] - 26.847289638199864) < 1e-8);
CHECK(std::fabs(rendered[701] - 2.9756928363101984) < 1e-8);
CHECK(std::fabs(rendered[1023] - -25.703654152948225) < 1e-8);
CHECK(std::fabs(rendered[1024] - -43.300148318757053) < 1e-8);
// A two-block crossfade keeps both filters' overlap tails alive.
const std::vector<double> second = make_filter(0.011, 140.0, true, 2.0);
CHECK(convolver.set_filter(second.data(), kTaps, 2).ok());
CHECK(convolver.transition_active());
std::vector<double> faded;
for (std::size_t index = 0; index < 4; ++index) {
for (std::size_t sample = 0; sample < kBlock; ++sample) {
const double n = 1000.0 + static_cast<double>(index * kBlock + sample);
block[sample] = std::sin(0.02 * n) + 0.3;
}
CHECK(convolver.process_block(block.data(), out.data()).ok());
faded.insert(faded.end(), out.begin(), out.end());
}
CHECK(!convolver.transition_active());
CHECK(std::fabs(faded[0] - -31.254215789646686) < 1e-8);
CHECK(std::fabs(faded[1] - -30.520784088408671) < 1e-8);
CHECK(std::fabs(faded[2] - -31.64727283056877) < 1e-8);
CHECK(std::fabs(faded[127] - 45.044850086774559) < 1e-8);
CHECK(std::fabs(faded[128] - 16.242938783563034) < 1e-8);
CHECK(std::fabs(faded[129] - 45.566945939182197) < 1e-8);
CHECK(std::fabs(faded[255] - -11.640284877460564) < 1e-8);
CHECK(std::fabs(faded[256] - 20.660738168974696) < 1e-8);
CHECK(std::fabs(faded[383] - -24.027948887675439) < 1e-8);
CHECK(std::fabs(faded[384] - -41.675076381317034) < 1e-8);
CHECK(std::fabs(faded[511] - 34.95547294171444) < 1e-8);
CHECK(std::fabs(faded[512] - -4.9486250951335764) < 1e-8);
convolver.reset();
CHECK(!convolver.transition_active());
}
int main() {
test_sha256();
test_crc32_and_inflate();
test_bit_reader();
test_variable_bits();
test_eac3_frame_bytes();
test_mini_json();
test_json_text();
test_task_result_json();
test_npy();
test_oamd_and_adm_helpers();
test_bed_layout_map();
test_partitioned_convolution();
test_spherical_mesh();
test_reference_distance();
test_point_source();
test_shoebox_room();
test_dbmd_auto_trim();
test_int24_packing();
test_utf8_paths();
test_process_runner();
test_find_executable();
test_builtin_kernel_tables();
test_npy_and_zip_writers();
test_sofa_canonicalize();
test_sofa_compile_and_cache();
test_sofa_reader_errors();
test_hrtf_cache_policy();
test_rosella_model_errors();
test_rosella_filterbank_config();
test_stream_render_ahead();
test_clipgain_first_frame_uses_its_own_gain();
test_clipgain_change_applies_to_the_current_frame();
test_clipgain_reset_clears_the_previous_gain();
std::printf("%d checks, %d failure(s)\n", g_checks, g_failures);
return g_failures == 0 ? 0 : 1;
}