// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later // Unit tests for core/src/sampler: SoundFontLoaderTest.kt translated (hostile SF2 // headers must fail fast, never hang or crash), plus WAV decode/encode, SF2/XI // parsing of small synthetic files, and the SampleStore's reclamation rules. // Plain asserts; prints PASS/FAIL per test, exits non-zero on any failure. // // Build (from ios/): // c++ -std=c++17 -O2 -Wall -Wextra -Icore/include -Icore/src -Icore/src/fx \ // -Icore/src/sampler -o build/core/sampler_test core/src/Params.cpp core/src/Specs.cpp \ // core/src/sampler/SampleStore.cpp core/src/sampler/SoundFontLoader.cpp core/src/sampler/SampleVoice.cpp \ // core/tests/sampler_test.cpp #include #include #include #include #include #include #include "SampleStore.hpp" #include "SampleVoice.hpp" #include "SoundFontLoader.hpp" using namespace sizzle; using namespace sizzle::sampler; using Bytes = std::vector; namespace { int failures = 0; bool current = true; #define CHECK(c) do { if (!(c)) { std::printf(" check failed: %s (line %d)\n", #c, __LINE__); current = false; } } while (0) void run(const char *name, void (*fn)()) { current = true; fn(); std::printf("%s %s\n", current ? "PASS" : "FAIL", name); if (!current) ++failures; } void w(Bytes &b, const char *tag) { b.insert(b.end(), tag, tag + std::strlen(tag)); } void le32(Bytes &b, int32_t v) { for (int i = 0; i < 4; ++i) b.push_back((uint8_t)((uint32_t)v >> (8 * i))); } void le16(Bytes &b, int v) { b.push_back((uint8_t)v); b.push_back((uint8_t)(v >> 8)); } void zeros(Bytes &b, size_t n) { b.insert(b.end(), n, 0); } /** SoundFontLoaderTest.sf2 { }: "RIFF", size 0, "sfbk", then the body. */ Bytes sf2Head() { Bytes b; w(b, "RIFF"); le32(b, 0); w(b, "sfbk"); return b; } std::optional load(const Bytes &b) { return SoundFontLoader::load(b.data(), b.size()); } // ---------------------------------------------------- SoundFontLoaderTest.kt void negativeChunkSizeDoesNotHang() { Bytes b = sf2Head(); w(b, "LIST"); le32(b, -8); zeros(b, 64); CHECK(!load(b)); } void negativeSubChunkSizeDoesNotHang() { Bytes b = sf2Head(); w(b, "LIST"); le32(b, 256); w(b, "pdta"); w(b, "shdr"); le32(b, -16); zeros(b, 240); CHECK(!load(b)); } void zeroSizeChunkDoesNotHang() { Bytes b = sf2Head(); for (int i = 0; i < 8; ++i) { w(b, "junk"); le32(b, 0); } CHECK(!load(b)); } void hugeSampleRegionIsCapped() { Bytes b = sf2Head(); w(b, "LIST"); le32(b, 12); w(b, "sdta"); w(b, "smpl"); le32(b, 0); w(b, "LIST"); le32(b, 4 + 8 + 46); w(b, "pdta"); w(b, "shdr"); le32(b, 46); zeros(b, 20); // sample name le32(b, 0); // start le32(b, 0x7FFFFFFF); // end: a 2-billion-frame claim le32(b, 0); le32(b, 0); le32(b, 44100); zeros(b, 46 - 40); auto r = load(b); // must return (capped or rejected) without allocating 8 GB CHECK(!r || (int)r->sample.data.size() <= SoundFontLoader::MAX_FRAMES); } void truncatedInputIsRejected() { Bytes full = sf2Head(); w(full, "LIST"); le32(full, 12); w(full, "sdta"); w(full, "smpl"); le32(full, 0); for (size_t n = 0; n <= full.size(); ++n) { Bytes cut(full.begin(), full.begin() + (long)n); (void)SoundFontLoader::load(cut.empty() ? nullptr : cut.data(), cut.size()); // must not crash } } // ---------------------------------------------------------------- SF2 / XI /** A minimal valid SF2: 8 frames of PCM, root 64, 22050 Hz, loop [2, 6). */ Bytes goodSf2(int32_t start, int32_t end, int32_t ls, int32_t le, int32_t rate, int key) { Bytes b = sf2Head(); const int16_t pcm[8] = {0, 8192, 16384, 32767, -32768, -16384, -8192, 1}; w(b, "LIST"); le32(b, 4 + 8 + 16); w(b, "sdta"); w(b, "smpl"); le32(b, 16); for (int16_t v : pcm) le16(b, (uint16_t)v); w(b, "LIST"); le32(b, 4 + 8 + 46); w(b, "pdta"); w(b, "shdr"); le32(b, 46); zeros(b, 20); le32(b, start); le32(b, end); le32(b, ls); le32(b, le); le32(b, rate); b.push_back((uint8_t)key); zeros(b, 46 - 41); return b; } void sf2FirstSampleRootAndLoop() { auto r = load(goodSf2(0, 8, 2, 6, 22050, 64)); CHECK(r.has_value()); if (!r) return; CHECK(r->rootNote == 64); CHECK(r->sample.sampleRate == 22050); CHECK(r->sample.data.size() == 8); CHECK(r->sample.data[1] == 8192 / 32768.f); CHECK(r->sample.data[3] == 32767 / 32768.f); CHECK(r->sample.data[4] == -1.f); CHECK(r->sample.loopStart == 2 && r->sample.loopEnd == 6); } void sf2RegionLoopAndFallbacks() { // start 2: data from frame 2, loop made relative; key 0 -> 60; rate 1000 -> 44100. auto r = load(goodSf2(2, 8, 3, 7, 1000, 0)); CHECK(r.has_value()); if (!r) return; CHECK(r->rootNote == 60 && r->sample.sampleRate == 44100); CHECK(r->sample.data.size() == 6 && r->sample.data[0] == 16384 / 32768.f); CHECK(r->sample.loopStart == 1 && r->sample.loopEnd == 5); // A loop outside the region is dropped; end <= start is rejected. auto r2 = load(goodSf2(0, 8, 6, 20, 44100, 60)); CHECK(r2 && r2->sample.loopStart == -1 && r2->sample.loopEnd == -1); CHECK(!load(goodSf2(5, 5, 0, 0, 44100, 60))); // A shdr chunk that claims 46 bytes but is cut short is rejected. Bytes cut = goodSf2(0, 8, 2, 6, 22050, 64); cut.resize(cut.size() - 10); CHECK(!load(cut)); } /** An XI file: header, one 40-byte sample header, delta-encoded data. */ Bytes xi(bool is16, int loopType, int32_t loopStartB, int32_t loopLenB, int relNote, const std::vector &deltas) { Bytes b; w(b, "Extended Instrument: "); b.resize(296, 0); le16(b, 1); // numSamples at 296 const int32_t len = (int32_t)deltas.size() * (is16 ? 2 : 1); le32(b, len); le32(b, loopStartB); le32(b, loopLenB); // 298, 302, 306 b.push_back(64); b.push_back(0); // volume, finetune (310, 311) b.push_back((uint8_t)((is16 ? 0x10 : 0) | loopType)); // type at 312 b.push_back(128); // panning 313 b.push_back((uint8_t)(int8_t)relNote); // relative note 314 b.resize(298 + 40, 0); for (int d : deltas) { if (is16) le16(b, d & 0xFFFF); else b.push_back((uint8_t)d); } return b; } void xi8BitDeltaLoopAndRoot() { // Deltas 10, 10, -30, 5 -> 10, 20, -10, -5 (8-bit wrapping sums). auto r = load(xi(false, 1, 1, 2, 12, {10, 10, -30, 5})); CHECK(r.has_value()); if (!r) return; CHECK(r->sample.sampleRate == 8363 && r->rootNote == 48); CHECK(r->sample.data.size() == 4); CHECK(r->sample.data[0] == 10 / 128.f && r->sample.data[1] == 20 / 128.f); CHECK(r->sample.data[2] == -10 / 128.f && r->sample.data[3] == -5 / 128.f); CHECK(r->sample.loopStart == 1 && r->sample.loopEnd == 3); } void xi16BitAndLoopChecks() { // 16-bit deltas wrap mod 65536: 30000 + 10000 -> -25536. Loop bytes halve. auto r = load(xi(true, 2, 2, 4, -3, {30000, 10000, -40000 & 0xFFFF})); CHECK(r.has_value()); if (!r) return; CHECK(r->rootNote == 63); CHECK(r->sample.data.size() == 3); CHECK(r->sample.data[0] == 30000 / 32768.f); CHECK(r->sample.data[1] == -25536 / 32768.f); CHECK(r->sample.loopStart == 1 && r->sample.loopEnd == 3); // No loop type, or a loop running past the data, means no loop. auto r2 = load(xi(false, 0, 0, 2, 0, {1, 2, 3})); CHECK(r2 && r2->sample.loopStart == -1); auto r3 = load(xi(false, 1, 2, 5, 0, {1, 2, 3})); CHECK(r3 && r3->sample.loopStart == -1); // A loop length that wraps Int is rejected, not read. auto r4 = load(xi(false, 1, 0x7FFFFFF0, 0x7FFFFFF0, 0, {1, 2, 3})); CHECK(r4 && r4->sample.loopStart == -1); // Header promising more samples than the file holds: data start past the end. Bytes many = xi(false, 0, 0, 0, 0, {1, 2}); many[296] = 0xFF; CHECK(!load(many)); // Truncated XI files of every length: no crash. Bytes full = xi(true, 1, 0, 2, 0, {1, 2, 3, 4}); for (size_t n = 0; n <= full.size(); ++n) { Bytes cut(full.begin(), full.begin() + (long)n); (void)load(cut); } } // ------------------------------------------------------------------- WAV Bytes wavHeader(int format, int channels, int rate, int bits, int32_t dataSize) { Bytes b; w(b, "RIFF"); le32(b, 36 + dataSize); w(b, "WAVE"); w(b, "fmt "); le32(b, 16); le16(b, format); le16(b, channels); le32(b, rate); le32(b, rate * channels * bits / 8); le16(b, channels * bits / 8); le16(b, bits); w(b, "data"); le32(b, dataSize); return b; } void wavRoundTrip() { Sample s({0.f, 0.5f, -0.5f, 1.f, -1.f, 2.f, -2.f, 0.25f}, 22050); Bytes b = SampleStore::encodeWav(s); CHECK(b.size() == 44 + 16); CHECK(std::memcmp(b.data(), "RIFF", 4) == 0 && std::memcmp(b.data() + 8, "WAVEfmt ", 8) == 0); CHECK(b[4] == 36 + 16 && b[24] == (22050 & 0xFF) && b[34] == 16); CHECK(b[44 + 2] == (16383 & 0xFF) && b[44 + 3] == (16383 >> 8)); // 0.5 -> 16383 (truncated) auto d = SampleStore::decodeWav(b.data(), b.size()); CHECK(d.has_value()); if (!d) return; CHECK(d->sampleRate == 22050 && d->data.size() == 8); CHECK(d->loopStart == -1 && d->loopEnd == -1); for (size_t i = 0; i < 8; ++i) { float want = std::fmax(-1.f, std::fmin(1.f, s.data[i])); CHECK(std::fabs(d->data[i] - want) <= 1.f / 32767.f); } CHECK(d->data[3] == 32767 / 32768.f && d->data[4] == -32767 / 32768.f); } void wavFormats() { { // 8-bit unsigned, stereo -> mono average Bytes b = wavHeader(1, 2, 8000, 8, 4); b.push_back(255); b.push_back(128); b.push_back(0); b.push_back(64); auto d = SampleStore::decodeWav(b.data(), b.size()); CHECK(d && d->data.size() == 2 && d->sampleRate == 8000); if (d) { CHECK(d->data[0] == (127 / 128.f + 0.f) / 2); CHECK(d->data[1] == (-1.f + -64 / 128.f) / 2); } } { // 24-bit signed Bytes b = wavHeader(1, 1, 48000, 24, 6); b.push_back(0x00); b.push_back(0x00); b.push_back(0x40); // 0x400000 b.push_back(0xFF); b.push_back(0xFF); b.push_back(0xFF); // -1 auto d = SampleStore::decodeWav(b.data(), b.size()); CHECK(d && d->data.size() == 2); if (d) { CHECK(d->data[0] == 0.5f); CHECK(d->data[1] == -1 / 8388608.f); } } { // 32-bit float and 32-bit int Bytes f = wavHeader(3, 1, 44100, 32, 4); float v = -0.75f; uint32_t u; std::memcpy(&u, &v, 4); le32(f, (int32_t)u); auto d = SampleStore::decodeWav(f.data(), f.size()); CHECK(d && d->data.size() == 1 && d->data[0] == -0.75f); Bytes i = wavHeader(1, 1, 44100, 32, 4); le32(i, 0x40000000); auto e = SampleStore::decodeWav(i.data(), i.size()); CHECK(e && e->data.size() == 1 && e->data[0] == 0.5f); } { // unsupported bit depth, zero bytes per sample, missing data chunk, not RIFF Bytes b = wavHeader(1, 1, 44100, 12, 4); zeros(b, 4); CHECK(!SampleStore::decodeWav(b.data(), b.size())); Bytes z = wavHeader(1, 1, 44100, 4, 4); zeros(z, 4); CHECK(!SampleStore::decodeWav(z.data(), z.size())); Bytes n; w(n, "RIFF"); le32(n, 36); w(n, "WAVE"); w(n, "junk"); le32(n, 24); zeros(n, 24); CHECK(!SampleStore::decodeWav(n.data(), n.size())); Bytes x = wavHeader(1, 1, 44100, 16, 4); zeros(x, 4); x[0] = 'X'; CHECK(!SampleStore::decodeWav(x.data(), x.size())); } } void wavHostileHeaders() { // An over-reported data length is clamped to the bytes present. Bytes b = wavHeader(1, 1, 44100, 16, 1000); le16(b, 1000); le16(b, 2000); auto d = SampleStore::decodeWav(b.data(), b.size()); CHECK(d && d->data.size() == 2); // A negative chunk size stops the walk (data never found -> null). Bytes neg; w(neg, "RIFF"); le32(neg, 0); w(neg, "WAVE"); w(neg, "junk"); le32(neg, -4); zeros(neg, 40); CHECK(!SampleStore::decodeWav(neg.data(), neg.size())); // An odd chunk ending exactly at the file end: the pad-byte seek is past the // limit, which throws in Kotlin -> null. Bytes odd = wavHeader(1, 1, 44100, 16, 3); odd.push_back(1); odd.push_back(2); odd.push_back(3); CHECK(!SampleStore::decodeWav(odd.data(), odd.size())); // An fmt chunk cut short by the end of the file -> null. Bytes fmt; w(fmt, "RIFF"); le32(fmt, 0); w(fmt, "WAVE"); zeros(fmt, 24); w(fmt, "fmt "); le32(fmt, 16); zeros(fmt, 8); CHECK(!SampleStore::decodeWav(fmt.data(), fmt.size())); // Truncations of a valid file: never crash. Bytes full = SampleStore::encodeWav(Sample({0.1f, 0.2f, 0.3f}, 44100)); for (size_t n = 0; n <= full.size(); ++n) (void)SampleStore::decodeWav(full.data(), n); // load() accepts a plain WAV with root 60. auto l = load(full); CHECK(l && l->rootNote == 60 && l->sample.data.size() == 3); } // ------------------------------------------------------------- SampleStore void storeGetPutRemove() { SampleStore st; CHECK(st.get("a") == nullptr && st.get("") == nullptr && st.get(nullptr) == nullptr); const Sample *a = st.put("a", Sample({1.f, 2.f}, 44100)); st.put("c", Sample({3.f}, 48000)); st.put("b", Sample({4.f}, 48000)); CHECK(st.get("a") == a && st.get("b") && st.get("c") && !st.get("d")); CHECK(st.get("b")->data[0] == 4.f); st.put("", Sample({5.f}, 1)); // Kotlin stores it, but get("") is always null CHECK(st.get("") == nullptr); const Sample *a2 = st.put("a", Sample({9.f}, 1)); CHECK(st.get("a") == a2 && a2 != a); st.remove("b"); CHECK(!st.get("b") && st.get("c")); st.remove("nope"); st.remove(""); } void storeReclaimsOnlyAfterQuiescentAndUnpin() { SampleStore st; st.put("x", Sample(std::vector(1000, 0.5f), 48000, 10, 900)); st.quiescent(); st.collect(); CHECK(st.retiredCount() == 0); // A voice is playing "x" when the UI removes it. SampleVoice v(48000); const Sample *x = st.get("x"); CHECK(x != nullptr); v.noteOn(*x, 60, 100, 60, 0.f, 1.f, 1.f, 0.002f, 0.f, 1.f, 0.02f, true, 5.f); CHECK(x->users.load() == 1); st.remove("x"); CHECK(!st.get("x")); st.collect(); CHECK(st.retiredCount() == 2); // old snapshot + the sample: no quiescent yet st.quiescent(); st.collect(); CHECK(st.retiredCount() == 1); // snapshot freed, the sample is still pinned float sum = 0; for (int i = 0; i < 2000; ++i) sum += v.render(); // still plays it (looping) CHECK(v.isActive() && sum > 0.f); v.noteOff(); for (int i = 0; i < 48000 && v.isActive(); ++i) v.render(); CHECK(!v.isActive()); CHECK(x->users.load() == 0); st.collect(); CHECK(st.retiredCount() == 0); } void voiceOneShotEndsAndUnpins() { Sample s(std::vector(480, 0.25f), 48000); SampleVoice v(48000); v.noteOn(s, 40, 127, 40, 0.f, 1.f, 1.f); CHECK(v.isGated() && s.users.load() == 1); int n = 0; while (v.isActive() && n < 10000) { v.render(); ++n; } CHECK(!v.isActive() && n <= 480 && s.users.load() == 0); // An empty sample plays nothing (Kotlin would throw in coerceIn). Sample empty; v.noteOn(empty, 40, 127, 40, 0.f, 1.f, 1.f); CHECK(!v.isActive() && empty.users.load() == 0); // kill() lets go too. v.noteOn(s, 40, 127, 40, 0.f, 1.f, 1.f); v.kill(); CHECK(!v.isActive() && s.users.load() == 0); } void voiceSampleFromParams() { SampleStore st; st.put("kick", Sample(std::vector(100, 0.1f), 44100, -1, -1)); Params p; p.set("pad3", "kick"); p.set("pad3S", 0.25f); p.set("pad3V", 0.5f); VoiceSample vs; CHECK(voiceSample("SAMPLER", p, st, SamplerPads::noteFor(3), vs)); CHECK(vs.sample == st.get("kick") && vs.root == 39 && vs.sliceStart == 0.25f && vs.sliceEnd == 1.f && vs.volume == 0.5f); CHECK(vs.attack == 0.002f && vs.release == 0.02f && !vs.loop); CHECK(!voiceSample("SAMPLER", p, st, 35, vs)); // below pad 0 CHECK(!voiceSample("SAMPLER", p, st, 52, vs)); // pad 16 CHECK(!voiceSample("SAMPLER", p, st, 38, vs)); // pad 2 has no sample CHECK(std::strcmp(SamplerPads::sliceEndKey(15).s, "pad15E") == 0); Params f; f.set("sfSample", "kick"); f.set("sfRoot", 64.7f); f.set("loop", "On"); CHECK(voiceSample("SOUNDFONT", f, st, 70, vs)); CHECK(vs.root == 64 && vs.volume == 0.8f && vs.attack == 0.005f && vs.decay == 0.10f); CHECK(vs.sustain == 1.f && vs.release == 0.20f && vs.loop && vs.crossfadeMs == 0.f); CHECK(!voiceSample("NES_SYNTH", f, st, 70, vs)); } } // namespace int main() { alarm(30); // the Kotlin tests' timeouts: a hang is a failure (SIGALRM ends the run) run("negativeChunkSizeDoesNotHang", negativeChunkSizeDoesNotHang); run("negativeSubChunkSizeDoesNotHang", negativeSubChunkSizeDoesNotHang); run("zeroSizeChunkDoesNotHang", zeroSizeChunkDoesNotHang); run("hugeSampleRegionIsCapped", hugeSampleRegionIsCapped); run("truncatedInputIsRejected", truncatedInputIsRejected); run("sf2FirstSampleRootAndLoop", sf2FirstSampleRootAndLoop); run("sf2RegionLoopAndFallbacks", sf2RegionLoopAndFallbacks); run("xi8BitDeltaLoopAndRoot", xi8BitDeltaLoopAndRoot); run("xi16BitAndLoopChecks", xi16BitAndLoopChecks); run("wavRoundTrip", wavRoundTrip); run("wavFormats", wavFormats); run("wavHostileHeaders", wavHostileHeaders); run("storeGetPutRemove", storeGetPutRemove); run("storeReclaimsOnlyAfterQuiescentAndUnpin", storeReclaimsOnlyAfterQuiescentAndUnpin); run("voiceOneShotEndsAndUnpins", voiceOneShotEndsAndUnpins); run("voiceSampleFromParams", voiceSampleFromParams); std::printf("\n%s (%d failed)\n", failures ? "FAIL" : "PASS", failures); return failures ? 1 : 0; }