0.37.0 (71): one engine, one version for Android and iOS
- Three source trees: core/ (shared C++ engine, moved from ios/core), app/ (Android UI), ios/app/ (iOS UI) - Android plays through core/ via JNI (EngineHost, jni_engine.cpp): the Oboe callback renders natively; the Kotlin model is mirrored as project text and applied as a diff, so playback continues through edits - The Kotlin engine moves to the unit tests as ReferenceEngine (golden reference) - Shared MasterRecorder in core/src/host, used by both apps; host_test - versions.properties: one versionName/versionCode for both platforms, continuing Android's numbering (iOS 0.6.0/11 -> 0.37.0/71) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
64e21e0bcc
commit
2bc5cb1cbb
@@ -0,0 +1,238 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// Renders the whole songs exported by IosGoldenSongs (Kotlin) through the C++
|
||||
// engine and compares with AudioEngine's output sample by sample:
|
||||
// Engine(sr) -> setProject -> play() -> fillBlock(buf, block) repeated.
|
||||
//
|
||||
// engine_test <golden dir>/songs [SONG ...]
|
||||
//
|
||||
// PASS when the largest difference over the whole render is below 1e-4. Prints the
|
||||
// max diff and the first sample (frame, channel) that differs by more than 1e-6.
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "echofield/GrainSources.hpp"
|
||||
#include "sampler/SampleStore.hpp"
|
||||
#include "sizzle/Engine.hpp"
|
||||
#include "sizzle/Model.hpp"
|
||||
#include "wavetable/WaveTables.hpp"
|
||||
|
||||
#if __has_include("io/ProjectIo.hpp")
|
||||
#include "io/ProjectIo.hpp"
|
||||
#define HAVE_PROJECT_IO 1
|
||||
#else
|
||||
#define HAVE_PROJECT_IO 0
|
||||
#endif
|
||||
|
||||
using namespace sizzle;
|
||||
|
||||
static std::vector<float> readF32(const std::string &path) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
std::vector<char> bytes((std::istreambuf_iterator<char>(f)), {});
|
||||
std::vector<float> out(bytes.size() / 4);
|
||||
std::memcpy(out.data(), bytes.data(), out.size() * 4);
|
||||
return out;
|
||||
}
|
||||
|
||||
static std::string readText(const std::string &path) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
return std::string((std::istreambuf_iterator<char>(f)), {});
|
||||
}
|
||||
|
||||
#if !HAVE_PROJECT_IO
|
||||
// TEMPORARY: a minimal ProjectIo.loadInto for the .szg fields the engine reads, until
|
||||
// core/src/io/ProjectIo.hpp exists (then the real loader is used automatically).
|
||||
namespace tmpio {
|
||||
static std::vector<std::string> split(const std::string &s, char c) {
|
||||
std::vector<std::string> out; std::string cur;
|
||||
for (char ch : s) { if (ch == c) { out.push_back(cur); cur.clear(); } else cur += ch; }
|
||||
out.push_back(cur);
|
||||
return out;
|
||||
}
|
||||
static std::string attr(const std::string &line, const std::string &key) {
|
||||
std::string inner = line.substr(1, line.size() - 2);
|
||||
for (const auto &tok : split(inner, ' ')) {
|
||||
size_t eq = tok.find('=');
|
||||
if (eq != std::string::npos && tok.substr(0, eq) == key) return tok.substr(eq + 1);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
static int toInt(const std::string &s, int fb) { try { return std::stoi(s); } catch (...) { return fb; } }
|
||||
static void region(model::LoopRegion &r, const std::string &line) {
|
||||
r.enabled = attr(line, "en") == "1";
|
||||
r.start = toInt(attr(line, "s"), 0);
|
||||
r.end = toInt(attr(line, "e"), 0);
|
||||
r.repeats = toInt(attr(line, "r"), 2);
|
||||
}
|
||||
static void loadInto(model::Project &p, const std::string &text) {
|
||||
p.patterns.clear();
|
||||
for (auto &lane : p.arrangement.slots) std::fill(lane.begin(), lane.end(), model::Arrangement::EMPTY);
|
||||
p.arrangement.laneMuted.fill(false);
|
||||
for (auto &s : p.toolbox) s.clearSlot();
|
||||
for (auto &ch : p.mixer.channels) {
|
||||
ch.instrumentSlot = -1; ch.fxSlots.fill(-1); ch.midiChannel = 0;
|
||||
ch.volume = 0.8f; ch.mute = ch.solo = ch.limiter = false;
|
||||
}
|
||||
std::string section;
|
||||
model::Pattern *cur = nullptr;
|
||||
std::istringstream in(text);
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
while (!line.empty() && (line.back() == '\r' || line.back() == ' ')) line.pop_back();
|
||||
if (line.empty() || line.rfind("SIZZLETRACKER", 0) == 0) continue;
|
||||
if (line.rfind("[PATTERN", 0) == 0) {
|
||||
p.patterns.emplace_back(toInt(attr(line, "id"), (int)p.patterns.size()), attr(line, "name"),
|
||||
toInt(attr(line, "len"), 16));
|
||||
cur = &p.patterns.back();
|
||||
section = "PATTERN";
|
||||
} else if (line.rfind("[ARRANGEMENT", 0) == 0) {
|
||||
p.arrangement.lengthBars = toInt(attr(line, "bars"), model::Arrangement::MAX_BARS);
|
||||
p.arrangement.loopEnabled = attr(line, "loop") == "1";
|
||||
std::string m = attr(line, "mutes");
|
||||
for (size_t i = 0; i < m.size() && i < p.arrangement.laneMuted.size(); ++i) p.arrangement.laneMuted[i] = m[i] == '1';
|
||||
section = "ARRANGEMENT";
|
||||
} else if (line.rfind("[REGION A", 0) == 0) region(p.arrangement.regionA, line);
|
||||
else if (line.rfind("[REGION B", 0) == 0) region(p.arrangement.regionB, line);
|
||||
else if (line.rfind("[MIXER]", 0) == 0) section = "MIXER";
|
||||
else if (line.rfind("[TOOLBOX]", 0) == 0) section = "TOOLBOX";
|
||||
else if (section.empty()) {
|
||||
size_t eq = line.find('=');
|
||||
if (eq == std::string::npos) continue;
|
||||
std::string k = line.substr(0, eq), v = line.substr(eq + 1);
|
||||
if (k == "NAME") p.name = v;
|
||||
else if (k == "TEMPO") p.tempoBpm = std::stof(v);
|
||||
else if (k == "SIG") {
|
||||
for (int i = 0; i < model::TIME_SIGNATURE_COUNT; ++i)
|
||||
if (v == model::info((model::TimeSignature)i).name) p.timeSignature = (model::TimeSignature)i;
|
||||
} else if (k == "ROOT") p.rootNote = toInt(v, 0);
|
||||
else if (k == "ACTIVE") p.activePatternId = toInt(v, 0);
|
||||
} else if (section == "PATTERN") {
|
||||
auto f = split(line, ',');
|
||||
if (f.size() < 5 || !cur) continue;
|
||||
int t = toInt(f[0], -1), ln = toInt(f[1], -1);
|
||||
if (t < 0 || t >= model::Pattern::TRACK_COUNT || ln < 0 || ln >= cur->length) continue;
|
||||
auto &c = cur->cell(t, ln);
|
||||
c.note = toInt(f[2], model::Cell::EMPTY);
|
||||
c.velocity = std::clamp(toInt(f[3], 127), 0, 127);
|
||||
c.channel = std::clamp(toInt(f[4], 1), 1, 16);
|
||||
} else if (section == "ARRANGEMENT") {
|
||||
auto f = split(line, ',');
|
||||
if (f.size() >= 3) p.arrangement.set(toInt(f[0], 0), toInt(f[1], 0), toInt(f[2], 0));
|
||||
} else if (section == "MIXER") {
|
||||
auto f = split(line, ',');
|
||||
if (f.size() < 10) continue;
|
||||
auto &ch = p.mixer.channels[toInt(f[0], 0)];
|
||||
ch.instrumentSlot = toInt(f[1], -1);
|
||||
for (int i = 0; i < 4; ++i) ch.fxSlots[i] = toInt(f[2 + i], -1);
|
||||
ch.midiChannel = toInt(f[6], 0);
|
||||
ch.volume = std::stof(f[7]);
|
||||
ch.mute = f[8] == "1"; ch.solo = f[9] == "1"; ch.limiter = f.size() > 10 && f[10] == "1";
|
||||
} else if (section == "TOOLBOX") {
|
||||
size_t eq = line.find('=');
|
||||
int idx = toInt(line.substr(0, eq), -1);
|
||||
auto parts = split(line.substr(eq + 1), ';');
|
||||
if (idx < 0 || idx >= model::Project::TOOLBOX_SLOTS || parts.size() < 2) continue;
|
||||
auto &slot = p.toolbox[idx];
|
||||
slot.fill(parts[0]);
|
||||
slot.name = parts[1];
|
||||
if (parts.size() >= 3 && !parts[2].empty())
|
||||
for (const auto &kv : split(parts[2], ',')) {
|
||||
size_t e = kv.find('=');
|
||||
if (e != std::string::npos) slot.set(kv.substr(0, e).c_str(), kv.substr(e + 1).c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int id = 0; id < model::Arrangement::LANE_COUNT; ++id) {
|
||||
bool has = false;
|
||||
for (auto &pt : p.patterns) has |= pt.id == id;
|
||||
if (!has) p.patterns.emplace_back(id, "BLK" + std::to_string(id + 1), 16);
|
||||
}
|
||||
std::sort(p.patterns.begin(), p.patterns.end(), [](const model::Pattern &a, const model::Pattern &b) { return a.id < b.id; });
|
||||
p.activePatternId = std::clamp(p.activePatternId, 0, (int)p.patterns.size() - 1);
|
||||
}
|
||||
} // namespace tmpio
|
||||
#endif
|
||||
|
||||
static void loadProject(model::Project &p, const std::string &text) {
|
||||
#if HAVE_PROJECT_IO
|
||||
io::ProjectIo::loadInto(p, text);
|
||||
#else
|
||||
tmpio::loadInto(p, text);
|
||||
#endif
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 2) { std::fprintf(stderr, "usage: %s <songs dir> [SONG ...]\n", argv[0]); return 2; }
|
||||
std::string dir = argv[1];
|
||||
std::vector<std::string> songs(argv + 2, argv + argc);
|
||||
if (songs.empty()) songs = {"demo", "mix", "waltz", "midifx"};
|
||||
wavetable::WaveTables::prewarmBlocking();
|
||||
echofield::GrainSources::prewarmBlocking();
|
||||
#if !HAVE_PROJECT_IO
|
||||
std::printf("note: io/ProjectIo.hpp not found, using the test's temporary .szg loader\n");
|
||||
#endif
|
||||
|
||||
int pass = 0, fail = 0;
|
||||
for (const auto &song : songs) {
|
||||
std::ifstream mf(dir + "/" + song + ".meta");
|
||||
if (!mf) { std::printf("FAIL %-10s no %s.meta\n", song.c_str(), song.c_str()); ++fail; continue; }
|
||||
int sr = 48000, block = 256;
|
||||
double seconds = 0;
|
||||
engine::EngineGlobals g;
|
||||
std::string sampleId;
|
||||
int smpRate = 0, loopStart = -1, loopEnd = -1;
|
||||
std::string line;
|
||||
while (std::getline(mf, line)) {
|
||||
std::istringstream ls(line);
|
||||
std::string tag; ls >> tag;
|
||||
if (tag == "sr") ls >> sr;
|
||||
else if (tag == "block") ls >> block;
|
||||
else if (tag == "seconds") ls >> seconds;
|
||||
else if (tag == "clock") { std::string v; ls >> v; g.clockSeconds = std::strtod(v.c_str(), nullptr); }
|
||||
else if (tag == "seeds") { long long f, gr; ls >> f >> gr; g.frasilSeeds = (uint32_t)f; g.grainSeeds = (uint32_t)gr; }
|
||||
else if (tag == "sample") ls >> sampleId >> smpRate >> loopStart >> loopEnd;
|
||||
}
|
||||
if (seconds <= 0) continue;
|
||||
|
||||
sampler::SampleStore store;
|
||||
if (!sampleId.empty())
|
||||
store.put(sampleId, Sample(readF32(dir + "/" + song + ".smp.f32"), smpRate, loopStart, loopEnd));
|
||||
|
||||
model::Project project;
|
||||
loadProject(project, readText(dir + "/" + song + ".szg"));
|
||||
|
||||
std::vector<float> want = readF32(dir + "/" + song + ".render.f32");
|
||||
const int frames = (int)(seconds * sr) / block * block;
|
||||
engine::Engine eng(sr, &store, g);
|
||||
eng.setProject(&project);
|
||||
eng.play();
|
||||
std::vector<float> buf((size_t)block * 2);
|
||||
double maxErr = (size_t)frames * 2 == want.size() ? 0 : 1e9;
|
||||
size_t maxAt = 0, firstAt = (size_t)-1;
|
||||
for (int b = 0; b < frames / block; ++b) {
|
||||
eng.fillBlock(buf.data(), block);
|
||||
for (int k = 0; k < block * 2; ++k) {
|
||||
const size_t i = (size_t)b * block * 2 + k;
|
||||
if (i >= want.size()) break;
|
||||
const double e = std::fabs((double)buf[k] - (double)want[i]);
|
||||
if (!(e <= maxErr)) { maxErr = e; maxAt = i; }
|
||||
if (firstAt == (size_t)-1 && !(e <= 1e-6)) firstAt = i;
|
||||
}
|
||||
}
|
||||
const bool ok = maxErr < 1e-4;
|
||||
std::printf("%s %-10s max diff %.3g at frame %zu", ok ? "PASS" : "FAIL", song.c_str(), maxErr, maxAt / 2);
|
||||
if (firstAt != (size_t)-1)
|
||||
std::printf(", first > 1e-6 at frame %zu ch %zu (%.3f s)", firstAt / 2, firstAt % 2, (double)(firstAt / 2) / sr);
|
||||
std::printf("\n");
|
||||
ok ? ++pass : ++fail;
|
||||
}
|
||||
std::printf("engine: %d passed, %d failed\n", pass, fail);
|
||||
return fail == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// Renders every reference scenario exported by IosGoldenExport / IosGoldenInstruments
|
||||
// (Kotlin) through the C++ core and compares sample by sample. Effect scenarios
|
||||
// process input.f32; instrument scenarios ("kind" line) play their note script.
|
||||
//
|
||||
// golden_test <golden dir> [TYPE ...]
|
||||
//
|
||||
// A scenario passes when the largest difference is below 1e-4 (float rounding and
|
||||
// libm vs Java Math differ by an ulp here and there). Types with no C++ port yet are
|
||||
// listed as SKIP. Exit status is non-zero if any scenario fails.
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <dirent.h>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "sizzle/Effect.hpp"
|
||||
#include "sizzle/TestVoice.hpp"
|
||||
#include "wavetable/WaveTables.hpp"
|
||||
|
||||
using namespace sizzle;
|
||||
|
||||
static std::vector<float> readF32(const std::string &path) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
std::vector<char> bytes((std::istreambuf_iterator<char>(f)), {});
|
||||
std::vector<float> out(bytes.size() / 4);
|
||||
std::memcpy(out.data(), bytes.data(), out.size() * 4);
|
||||
return out;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 2) { std::fprintf(stderr, "usage: %s <golden dir> [TYPE ...]\n", argv[0]); return 2; }
|
||||
std::string dir = argv[1];
|
||||
std::vector<std::string> only(argv + 2, argv + argc);
|
||||
std::vector<float> input = readF32(dir + "/input.f32");
|
||||
if (input.empty()) { std::fprintf(stderr, "no input.f32 in %s (run make -C ios golden)\n", dir.c_str()); return 2; }
|
||||
|
||||
std::vector<std::string> scns;
|
||||
if (DIR *d = opendir(dir.c_str())) {
|
||||
while (dirent *e = readdir(d)) {
|
||||
std::string n = e->d_name;
|
||||
if (n.size() > 4 && n.compare(n.size() - 4, 4, ".scn") == 0) scns.push_back(n.substr(0, n.size() - 4));
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
std::sort(scns.begin(), scns.end());
|
||||
|
||||
int pass = 0, fail = 0, skip = 0;
|
||||
for (const auto &base : scns) {
|
||||
std::ifstream f(dir + "/" + base + ".scn");
|
||||
std::string line, type, kind;
|
||||
int sr = 48000, block = 256, frames = 0;
|
||||
float tempo = 120.f;
|
||||
double clock0 = 0;
|
||||
int smpRate = 0, loopStart = -1, loopEnd = -1;
|
||||
long long frasilSeeds = 0, grainSeeds = 0;
|
||||
std::string table;
|
||||
struct Ev { int frame; bool on; int midi, vel; };
|
||||
std::vector<Ev> evs;
|
||||
Params p;
|
||||
while (std::getline(f, line)) {
|
||||
std::istringstream ls(line);
|
||||
std::string tag; ls >> tag;
|
||||
if (tag == "type") ls >> type;
|
||||
else if (tag == "sr") ls >> sr;
|
||||
else if (tag == "tempo") ls >> tempo;
|
||||
else if (tag == "kind") ls >> kind;
|
||||
else if (tag == "block") ls >> block;
|
||||
else if (tag == "frames") ls >> frames;
|
||||
else if (tag == "clock") ls >> clock0;
|
||||
else if (tag == "sample") ls >> smpRate >> loopStart >> loopEnd;
|
||||
else if (tag == "seeds") ls >> frasilSeeds >> grainSeeds;
|
||||
else if (tag == "table") { std::getline(ls, table); if (!table.empty() && table[0] == ' ') table.erase(0, 1); }
|
||||
else if (tag == "on") { Ev e{0, true, 0, 0}; ls >> e.frame >> e.midi >> e.vel; evs.push_back(e); }
|
||||
else if (tag == "off") { Ev e{0, false, 0, 0}; ls >> e.frame >> e.midi; evs.push_back(e); }
|
||||
else if (tag == "p") {
|
||||
std::string key, val; ls >> key; std::getline(ls, val);
|
||||
if (!val.empty() && val[0] == ' ') val.erase(0, 1);
|
||||
p.set(key.c_str(), val.c_str());
|
||||
}
|
||||
}
|
||||
std::string label = kind.empty() ? type : kind + "_" + type;
|
||||
if (!only.empty() && std::find(only.begin(), only.end(), type) == only.end()
|
||||
&& std::find(only.begin(), only.end(), label) == only.end()) continue;
|
||||
if (kind == "TABLE") {
|
||||
std::vector<float> want = readF32(dir + "/" + base + ".f32"), got;
|
||||
wavetable::WaveTables::prewarmBlocking();
|
||||
if (const wavetable::WaveTable *t = wavetable::WaveTables::factory(table.c_str()))
|
||||
for (int l = 0; l < wavetable::WaveTable::LEVELS; ++l)
|
||||
got.insert(got.end(), t->data(l), t->data(l) + (size_t)t->frames * t->size(l));
|
||||
double maxErr = got.size() == want.size() ? 0 : 1e9; size_t at = 0;
|
||||
for (size_t i = 0; i < got.size() && i < want.size(); ++i) {
|
||||
double e = std::fabs((double)got[i] - want[i]);
|
||||
if (!(e <= maxErr)) { maxErr = e; at = i; }
|
||||
}
|
||||
bool ok = maxErr < 1e-4;
|
||||
std::printf("%s %-36s max diff %.3g at %zu\n", ok ? "PASS" : "FAIL", base.c_str(), maxErr, at);
|
||||
ok ? ++pass : ++fail;
|
||||
continue;
|
||||
}
|
||||
if (!kind.empty()) {
|
||||
TestVoiceSetup setup{type.c_str(), &p, sr, tempo, clock0};
|
||||
setup.frasilSeeds = (uint32_t)frasilSeeds;
|
||||
setup.grainSeeds = (uint32_t)grainSeeds;
|
||||
std::vector<float> smp;
|
||||
if (smpRate > 0) {
|
||||
smp = readF32(dir + "/" + base + ".smp.f32");
|
||||
setup.sample = smp.data();
|
||||
setup.sampleLength = (int)smp.size();
|
||||
setup.sampleRate2 = smpRate;
|
||||
setup.loopStart = loopStart;
|
||||
setup.loopEnd = loopEnd;
|
||||
}
|
||||
auto v = makeTestVoice(kind.c_str(), setup);
|
||||
if (!v) { std::printf("SKIP %-36s (not ported)\n", base.c_str()); ++skip; continue; }
|
||||
std::vector<float> want = readF32(dir + "/" + base + ".f32");
|
||||
double maxErr = 0; size_t at = 0, next = 0;
|
||||
for (int i = 0; i < frames && i < (int)want.size(); ++i) {
|
||||
if (i % block == 0) v->blockStart(block);
|
||||
while (next < evs.size() && evs[next].frame == i) {
|
||||
const Ev &e = evs[next++];
|
||||
if (e.on) v->noteOn(e.midi, e.vel); else v->noteOff(e.midi);
|
||||
}
|
||||
double err = std::fabs((double)v->render() - (double)want[i]);
|
||||
if (!(err <= maxErr)) { maxErr = err; at = (size_t)i; }
|
||||
}
|
||||
bool ok = maxErr < 1e-4 && (int)want.size() == frames;
|
||||
std::printf("%s %-36s max diff %.3g at sample %zu\n", ok ? "PASS" : "FAIL", base.c_str(), maxErr, at);
|
||||
ok ? ++pass : ++fail;
|
||||
continue;
|
||||
}
|
||||
auto fx = Effect::create(type.c_str(), sr);
|
||||
if (!fx) { std::printf("SKIP %-36s (not ported)\n", base.c_str()); ++skip; continue; }
|
||||
std::vector<float> want = readF32(dir + "/" + base + ".f32");
|
||||
fx->update(p, tempo);
|
||||
double maxErr = 0; size_t at = 0;
|
||||
for (size_t i = 0; i < input.size() && i < want.size(); ++i) {
|
||||
float y = fx->process(input[i]);
|
||||
double e = std::fabs((double)y - (double)want[i]);
|
||||
if (!(e <= maxErr)) { maxErr = e; at = i; } // NaN counts as worst
|
||||
}
|
||||
bool ok = maxErr < 1e-4 && want.size() == input.size();
|
||||
std::printf("%s %-36s max diff %.3g at sample %zu\n", ok ? "PASS" : "FAIL", base.c_str(), maxErr, at);
|
||||
ok ? ++pass : ++fail;
|
||||
}
|
||||
std::printf("\n%d passed, %d failed, %d not ported\n", pass, fail, skip);
|
||||
return fail ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// host::EngineHost: renders a song exactly as the bare engine does, and a synced
|
||||
// project text ends up as the engine's song without stopping playback.
|
||||
// argv[1]: the reference songs folder (core/golden/songs).
|
||||
|
||||
#include "host/EngineHost.hpp"
|
||||
#include "echofield/GrainSources.hpp"
|
||||
#include "io/ProjectIo.hpp"
|
||||
#include "wavetable/WaveTables.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
using namespace sizzle;
|
||||
|
||||
static int failures = 0;
|
||||
#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++failures; } } while (0)
|
||||
|
||||
static std::string readFile(const std::string &path) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
std::stringstream ss;
|
||||
ss << f.rdbuf();
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 2) { std::printf("usage: host_test <songs dir>\n"); return 2; }
|
||||
// midifx: arp, transposer and the MIDI LFO (which writes its target slot as it plays).
|
||||
const std::string text = readFile(std::string(argv[1]) + "/midifx.szg");
|
||||
const std::string plain = readFile(std::string(argv[1]) + "/mix.szg");
|
||||
CHECK(!text.empty() && !plain.empty());
|
||||
wavetable::WaveTables::prewarmBlocking(); // the host builds them in the background
|
||||
echofield::GrainSources::prewarmBlocking();
|
||||
constexpr int SR = 48000, FRAMES = 48000;
|
||||
|
||||
// 1. The host renders what the engine renders (odd buffer sizes, 192-frame blocks inside).
|
||||
{
|
||||
host::EngineHost h(SR);
|
||||
h.loadProjectText(text);
|
||||
h.rebuildArrangement();
|
||||
h.rebuildFxChains();
|
||||
h.play();
|
||||
std::vector<float> a(FRAMES * 2);
|
||||
for (int done = 0; done < FRAMES;) {
|
||||
const int n = std::min(384, FRAMES - done); // whole blocks: the LFO steps per block
|
||||
h.render(a.data() + 2 * done, n);
|
||||
done += n;
|
||||
}
|
||||
model::Project p;
|
||||
io::ProjectIo::loadInto(p, text);
|
||||
engine::Engine e(SR);
|
||||
e.setProject(&p);
|
||||
e.rebuildArrangement();
|
||||
e.rebuildFxChains();
|
||||
e.play();
|
||||
std::vector<float> b(FRAMES * 2);
|
||||
for (int done = 0; done < FRAMES; done += 192) e.fillBlock(b.data() + 2 * done, std::min(192, FRAMES - done));
|
||||
double peak = 0, diff = 0;
|
||||
for (size_t i = 0; i < a.size(); ++i) { peak = std::max(peak, (double)std::fabs(a[i])); diff = std::max(diff, (double)std::fabs(a[i] - b[i])); }
|
||||
CHECK(peak > 0.01);
|
||||
CHECK(diff == 0);
|
||||
}
|
||||
|
||||
// 2. Syncing an edited song changes the engine's song, playing on.
|
||||
{
|
||||
const std::string &text = plain; // no LFO rewriting a slot meanwhile
|
||||
host::EngineHost h(SR);
|
||||
h.loadProjectText(text);
|
||||
h.play();
|
||||
std::vector<float> buf(2 * 4800);
|
||||
h.render(buf.data(), 4800);
|
||||
model::Project p;
|
||||
io::ProjectIo::loadInto(p, text);
|
||||
p.tempoBpm = 97.f;
|
||||
p.patterns[0].tracks[1][3] = model::Cell{64, 90, 2};
|
||||
p.mixer.channels[2].volume = 0.5f;
|
||||
p.toolbox[0].set("cutoff", 0.25f);
|
||||
p.arrangement.set(3, 5, 2);
|
||||
const std::string edited = io::ProjectIo::save(p);
|
||||
h.syncProjectText(edited);
|
||||
CHECK(h.isPlaying());
|
||||
h.render(buf.data(), 4800);
|
||||
CHECK(h.projectText() == edited);
|
||||
h.syncProjectText(text); // and back
|
||||
CHECK(h.projectText() == io::ProjectIo::save([&] { model::Project q; io::ProjectIo::loadInto(q, text); return q; }()));
|
||||
}
|
||||
|
||||
std::printf(failures ? "host_test: %d failure(s)\n" : "host_test: ok\n", failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,565 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// core/src/io against files the Kotlin app wrote (core/golden/songs): every .szg,
|
||||
// .sng and .szp is parsed and written back byte for byte (a [TOOLBOX] line's
|
||||
// key=value pairs compared as a set: Kotlin writes them in ConcurrentHashMap
|
||||
// order; the two places where Kotlin itself doesn't round-trip are spelled out
|
||||
// below), .szg -> .sng and .szg -> .szp across formats, plus SngFormatTest,
|
||||
// SngMikroSeqImportTest, ProjectIoNameTest and ArrangementNoteOffTest translated,
|
||||
// Float.toString / toFloatOrNull samples (JDK 17.0.14's output) and malformed
|
||||
// input. Plain asserts; prints PASS/FAIL per check, exits non-zero on failure.
|
||||
//
|
||||
// build/core/io_test core/golden/songs ../app/src/test/resources/mikroseq
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <dirent.h>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "io/KotlinText.hpp"
|
||||
#include "io/PresetIo.hpp"
|
||||
#include "io/ProjectIo.hpp"
|
||||
#include "io/SngFormat.hpp"
|
||||
#include "sizzle/Model.hpp"
|
||||
#include "sizzle/Specs.hpp"
|
||||
|
||||
using namespace sizzle;
|
||||
using namespace sizzle::model;
|
||||
using io::PresetIo;
|
||||
using io::ProjectIo;
|
||||
using io::SngFormat;
|
||||
|
||||
namespace {
|
||||
|
||||
int failures = 0, passes = 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 std::string &name, const std::function<void()> &fn) {
|
||||
current = true;
|
||||
fn();
|
||||
std::printf("%s %s\n", current ? "PASS" : "FAIL", name.c_str());
|
||||
if (current) ++passes; else ++failures;
|
||||
}
|
||||
|
||||
bool readFile(const std::string &path, std::string &out) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
if (!f) return false;
|
||||
out.assign(std::istreambuf_iterator<char>(f), {});
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::string> listDir(const std::string &dir, const std::string &suffix) {
|
||||
std::vector<std::string> out;
|
||||
if (DIR *d = opendir(dir.c_str())) {
|
||||
while (dirent *e = readdir(d)) {
|
||||
std::string n = e->d_name;
|
||||
if (n.size() > suffix.size() && n.compare(n.size() - suffix.size(), suffix.size(), suffix) == 0) out.push_back(n);
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
std::sort(out.begin(), out.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
/** First differing line, for the failure message. */
|
||||
void reportDiff(const std::string &want, const std::string &got) {
|
||||
auto a = io::kt::split(want, '\n'), b = io::kt::split(got, '\n');
|
||||
for (size_t i = 0; i < std::max(a.size(), b.size()); ++i) {
|
||||
const std::string x = i < a.size() ? a[i] : "<none>", y = i < b.size() ? b[i] : "<none>";
|
||||
if (x != y) { std::printf(" line %zu\n want: %s\n got: %s\n", i + 1, x.c_str(), y.c_str()); return; }
|
||||
}
|
||||
}
|
||||
|
||||
bool sameBytes(const std::string &want, const std::string &got) {
|
||||
if (want == got) return true;
|
||||
reportDiff(want, got);
|
||||
return false;
|
||||
}
|
||||
|
||||
/** [TOOLBOX] lines with their key=value pairs sorted; everything else as is. */
|
||||
std::string normalizeToolbox(const std::string &text) {
|
||||
std::string out;
|
||||
bool toolbox = false;
|
||||
auto lines = io::kt::split(text, '\n');
|
||||
for (size_t i = 0; i < lines.size(); ++i) {
|
||||
std::string l = lines[i];
|
||||
if (toolbox && !l.empty()) {
|
||||
auto parts = io::kt::split(l, ';');
|
||||
if (parts.size() >= 3) {
|
||||
auto kv = io::kt::split(parts[2], ',');
|
||||
std::sort(kv.begin(), kv.end());
|
||||
std::string joined;
|
||||
for (size_t k = 0; k < kv.size(); ++k) joined += (k ? "," : "") + kv[k];
|
||||
l = parts[0] + ";" + parts[1] + ";" + joined;
|
||||
for (size_t k = 3; k < parts.size(); ++k) l += ";" + parts[k];
|
||||
}
|
||||
}
|
||||
if (l == "[TOOLBOX]") toolbox = true;
|
||||
out += l;
|
||||
if (i + 1 < lines.size()) out += '\n';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string noteNames(const Project &p, int n) {
|
||||
std::string s;
|
||||
for (int i = 0; i < n; ++i) s += (i ? "|" : "") + p.patterns[i].name;
|
||||
return s;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ reference files
|
||||
|
||||
void goldenFiles(const std::string &dir) {
|
||||
const auto szgs = listDir(dir, ".szg");
|
||||
run("reference files present (" + std::to_string(szgs.size()) + " songs)", [&] { CHECK(szgs.size() >= 5); });
|
||||
for (const std::string &f : szgs) {
|
||||
const std::string song = f.substr(0, f.size() - 4);
|
||||
std::string szg, sng;
|
||||
readFile(dir + "/" + f, szg);
|
||||
const bool haveSng = readFile(dir + "/" + song + ".sng", sng);
|
||||
|
||||
run(song + ".szg: load + save (toolbox pairs as sets)", [&] {
|
||||
Project p;
|
||||
ProjectIo::loadInto(p, szg);
|
||||
const std::string out = ProjectIo::save(p);
|
||||
CHECK(sameBytes(normalizeToolbox(szg), normalizeToolbox(out)));
|
||||
// Saving what was loaded again is byte-identical to our own first save.
|
||||
Project q;
|
||||
ProjectIo::loadInto(q, out);
|
||||
CHECK(sameBytes(out, ProjectIo::save(q)));
|
||||
});
|
||||
// A `track Tn <channel>` line's channel is the mixer channel's MIDI channel
|
||||
// minus one, and importInto leaves the mixer alone: into a fresh project
|
||||
// (mixer on channel 0) Kotlin writes 0 there too.
|
||||
run(song + ".sng: import into a fresh project + export (track channels -> 0)", [&] {
|
||||
CHECK(haveSng);
|
||||
Project p;
|
||||
SngFormat::importInto(p, sng);
|
||||
std::string want;
|
||||
for (const std::string &l : io::kt::split(sng, '\n')) {
|
||||
std::string x = l;
|
||||
if (io::kt::startsWith(l, "track ")) x = l.substr(0, l.rfind(' ')) + " 0";
|
||||
want += x + "\n";
|
||||
}
|
||||
want.pop_back();
|
||||
CHECK(sameBytes(want, SngFormat::exportText(p)));
|
||||
});
|
||||
run(song + ".sng: import into its own .szg project + export", [&] {
|
||||
Project p;
|
||||
ProjectIo::loadInto(p, szg);
|
||||
SngFormat::importInto(p, sng);
|
||||
CHECK(sameBytes(sng, SngFormat::exportText(p)));
|
||||
});
|
||||
run(song + ".szg -> .sng", [&] {
|
||||
Project p;
|
||||
ProjectIo::loadInto(p, szg);
|
||||
CHECK(sameBytes(sng, SngFormat::exportText(p)));
|
||||
});
|
||||
for (int slot = 0; slot < Project::TOOLBOX_SLOTS; ++slot) {
|
||||
std::string szp;
|
||||
if (!readFile(dir + "/" + song + ".slot" + std::to_string(slot) + ".szp", szp)) continue;
|
||||
const std::string tag = song + ".slot" + std::to_string(slot) + ".szp";
|
||||
// PresetIo.import applies NAME before fill(), which resets the name to
|
||||
// the device's display name: Kotlin loses a renamed slot's NAME too.
|
||||
run(tag + ": import + export (NAME -> display name)", [&] {
|
||||
ToolboxSlot s;
|
||||
CHECK(PresetIo::importText(s, szp));
|
||||
std::string want = szp;
|
||||
const size_t a = want.find("\nNAME="), z = want.find('\n', a + 1);
|
||||
CHECK(a != std::string::npos && z != std::string::npos);
|
||||
if (a != std::string::npos && z != std::string::npos)
|
||||
want.replace(a + 6, z - a - 6, findDevice(s.type.c_str())->displayName);
|
||||
CHECK(sameBytes(want, PresetIo::exportText(s)));
|
||||
if (want != szp) std::printf(" note: %s is named \"%s\", which import drops (as in Kotlin)\n",
|
||||
tag.c_str(), szp.substr(a + 6, z - a - 6).c_str());
|
||||
});
|
||||
run(song + ".szg -> " + tag, [&] {
|
||||
Project p;
|
||||
ProjectIo::loadInto(p, szg);
|
||||
CHECK(!p.toolbox[slot].isEmpty());
|
||||
CHECK(sameBytes(szp, PresetIo::exportText(p.toolbox[slot])));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------- SngFormatTest.kt
|
||||
|
||||
const char *kReference =
|
||||
"version 1\n"
|
||||
"bpm 120\n"
|
||||
"sig 4 4\n"
|
||||
"\n"
|
||||
"block A 16 4\n"
|
||||
"roll ####\n"
|
||||
"track T1 0\n"
|
||||
"0 C-4 64 01\n"
|
||||
"4 E-4 .. ..\n"
|
||||
"8 OFF .. ..\n"
|
||||
"endblock";
|
||||
|
||||
void sngFormatTest() {
|
||||
run("SngFormatTest.parsesReferenceExample", [] {
|
||||
Project p;
|
||||
SngFormat::importInto(p, kReference);
|
||||
CHECK(std::fabs(p.tempoBpm - 120.f) < 0.001f);
|
||||
CHECK(p.timeSignature == TimeSignature::FOUR_FOUR);
|
||||
const Pattern &block = p.patterns[0];
|
||||
CHECK(block.name == "A");
|
||||
CHECK(block.length == 16);
|
||||
const Cell &c0 = block.cell(0, 0);
|
||||
CHECK(c0.note == io::pitchParse("C-4"));
|
||||
CHECK(c0.velocity == 0x64);
|
||||
CHECK(c0.channel == 1);
|
||||
const Cell &c4 = block.cell(0, 4);
|
||||
CHECK(c4.note == io::pitchParse("E-4"));
|
||||
CHECK(c4.velocity == 0x7F);
|
||||
CHECK(c4.channel == 1);
|
||||
CHECK(block.cell(0, 8).isNoteOff());
|
||||
for (int beat = 0; beat <= 3; ++beat) CHECK(p.arrangement.patternAt(0, beat) != Arrangement::EMPTY);
|
||||
CHECK(p.arrangement.patternAt(0, 4) == Arrangement::EMPTY);
|
||||
});
|
||||
run("SngFormatTest.roundTripsNotesAndRoll", [] {
|
||||
Project p;
|
||||
p.tempoBpm = 140.f;
|
||||
p.timeSignature = TimeSignature::FIVE_FOUR;
|
||||
p.patterns[0].cell(0, 0) = Cell{60, 0x40, 3};
|
||||
p.patterns[0].cell(1, 5) = Cell{67, 0x7F, 2};
|
||||
p.arrangement.set(0, 0, 0);
|
||||
p.arrangement.set(0, 1, 0);
|
||||
Project restored;
|
||||
SngFormat::importInto(restored, SngFormat::exportText(p));
|
||||
CHECK(std::fabs(restored.tempoBpm - 140.f) < 0.001f);
|
||||
CHECK(restored.timeSignature == TimeSignature::FIVE_FOUR);
|
||||
const Cell &a = restored.patterns[0].cell(0, 0);
|
||||
CHECK(a.note == 60 && a.velocity == 0x40 && a.channel == 3);
|
||||
const Cell &b = restored.patterns[0].cell(1, 5);
|
||||
CHECK(b.note == 67 && b.velocity == 0x7F && b.channel == 2);
|
||||
CHECK(restored.arrangement.patternAt(0, 0) != Arrangement::EMPTY);
|
||||
CHECK(restored.arrangement.patternAt(0, 1) != Arrangement::EMPTY);
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------- SngMikroSeqImportTest.kt
|
||||
|
||||
void sngMikroSeqImportTest(const std::string &dir) {
|
||||
run("SngMikroSeqImportTest.fourFour", [&] {
|
||||
std::string text;
|
||||
CHECK(readFile(dir + "/sig44.sng", text));
|
||||
CHECK(SngFormat::looksLikeSng(text));
|
||||
Project p;
|
||||
SngFormat::importInto(p, text);
|
||||
CHECK(std::fabs(p.tempoBpm - 97.f) < 0.001f);
|
||||
CHECK(p.timeSignature == TimeSignature::FOUR_FOUR);
|
||||
CHECK(p.arrangement.loopEnabled);
|
||||
CHECK(noteNames(p, 4) == "C1|C1 muted|C2|C6");
|
||||
CHECK(p.patterns[0].length == 16 && p.patterns[1].length == 16 && p.patterns[2].length == 48 &&
|
||||
p.patterns[3].length == 64);
|
||||
const Pattern &c1 = p.patterns[0];
|
||||
CHECK(c1.cell(0, 0).note == io::pitchParse("C-2"));
|
||||
CHECK(c1.cell(0, 0).channel == 10);
|
||||
CHECK(c1.cell(0, 0).velocity == 0x6E);
|
||||
CHECK(c1.cell(0, 1).note == Cell::OFF);
|
||||
CHECK(c1.cell(2, 2).note == io::pitchParse("F#2"));
|
||||
const Pattern &c2 = p.patterns[2];
|
||||
CHECK(c2.cell(3, 0).note == io::pitchParse("B-1"));
|
||||
CHECK(c2.cell(3, 0).channel == 1);
|
||||
CHECK(c2.cell(3, 6).note == io::pitchParse("C#2"));
|
||||
CHECK(c2.cell(3, 9).note == Cell::OFF);
|
||||
CHECK(p.patterns[3].cell(0, 0).channel == 3);
|
||||
for (int lane : {0, 2, 3}) {
|
||||
CHECK(p.arrangement.patternAt(lane, 0) == lane);
|
||||
CHECK(p.arrangement.patternAt(lane, 95) == lane);
|
||||
CHECK(p.arrangement.patternAt(lane, 96) == Arrangement::EMPTY);
|
||||
}
|
||||
CHECK(p.arrangement.patternAt(1, 0) == Arrangement::EMPTY);
|
||||
CHECK(p.arrangement.lengthBars >= 24);
|
||||
});
|
||||
run("SngMikroSeqImportTest.threeFour", [&] {
|
||||
std::string text;
|
||||
CHECK(readFile(dir + "/sig34.sng", text));
|
||||
Project p;
|
||||
SngFormat::importInto(p, text);
|
||||
CHECK(p.timeSignature == TimeSignature::THREE_FOUR);
|
||||
CHECK(noteNames(p, 4) == "C1|C1 muted|C2|C6");
|
||||
CHECK(p.patterns[0].length == 12 && p.patterns[1].length == 12 && p.patterns[2].length == 36 &&
|
||||
p.patterns[3].length == 48);
|
||||
const Pattern &c1 = p.patterns[0];
|
||||
for (int step : {0, 3, 6, 9}) CHECK(c1.cell(0, step).note == io::pitchParse("C-2"));
|
||||
for (int step : {1, 4, 7, 10}) CHECK(c1.cell(0, step).note == Cell::OFF);
|
||||
CHECK(p.patterns[1].cell(1, 3).note == io::pitchParse("D-2"));
|
||||
const Pattern &c2 = p.patterns[2];
|
||||
CHECK(c2.cell(3, 5).note == io::pitchParse("C#2"));
|
||||
CHECK(c2.cell(3, 7).note == Cell::OFF);
|
||||
CHECK(c2.cell(3, 16).note == Cell::OFF);
|
||||
CHECK(p.arrangement.patternAt(2, 95) == 2);
|
||||
CHECK(p.arrangement.patternAt(2, 96) == Arrangement::EMPTY);
|
||||
CHECK(p.arrangement.lengthBars >= 96 / 3);
|
||||
});
|
||||
run("SngMikroSeqImportTest.moreBlocksThanLanesKeepsTheOnesOnTheRoll", [] {
|
||||
std::string text = "version 1\nbpm 120\nsig 4 4\n";
|
||||
for (int c = 1; c <= 8; ++c) {
|
||||
const std::string n = std::to_string(c);
|
||||
text += "block C" + n + " 16 1\nroll ####\ntrack T1 0\n0 C-4 64 ..\nendblock\n";
|
||||
text += "block C" + n + " muted 16 1\ntrack T2 0\n0 D-4 64 ..\nendblock\n";
|
||||
}
|
||||
Project p;
|
||||
SngFormat::importInto(p, text);
|
||||
CHECK(noteNames(p, 8) == "C1|C2|C3|C4|C5|C6|C7|C8");
|
||||
for (int lane = 0; lane < 8; ++lane) CHECK(p.arrangement.patternAt(lane, 0) == lane);
|
||||
});
|
||||
run("SngMikroSeqImportTest.trackNumbersBeyondFourTakeFreeSlotsAndExtraTracksAreDropped", [] {
|
||||
const char *text =
|
||||
"version 1\nblock A 16 6\ntrack T1 0\n0 C-4 .. ..\ntrack T7 1\n0 D-4 .. ..\ntrack T2 2\n0 E-4 .. ..\n"
|
||||
"track T9 3\n0 F-4 .. ..\ntrack T12 4\n0 G-4 .. ..\nendblock";
|
||||
Project p;
|
||||
const Pattern &b = SngFormat::importInto(p, text).patterns[0];
|
||||
CHECK(b.cell(0, 0).note == io::pitchParse("C-4"));
|
||||
CHECK(b.cell(1, 0).note == io::pitchParse("D-4"));
|
||||
CHECK(b.cell(2, 0).note == io::pitchParse("E-4"));
|
||||
CHECK(b.cell(3, 0).note == io::pitchParse("F-4"));
|
||||
for (int t = 0; t < 4; ++t) CHECK(b.cell(t, 0).note != io::pitchParse("G-4"));
|
||||
});
|
||||
run("SngMikroSeqImportTest.absurdBlockLengthIsBounded", [] {
|
||||
Project p;
|
||||
SngFormat::importInto(p, "version 1\nblock A 999999999 1\nendblock\n");
|
||||
CHECK(p.patterns[0].length == SngFormat::MAX_BLOCK_LENGTH);
|
||||
});
|
||||
run("SngMikroSeqImportTest.plainTextIsNotASong", [] {
|
||||
CHECK(!SngFormat::looksLikeSng("shopping list\nmilk\neggs"));
|
||||
CHECK(SngFormat::looksLikeSng("hello\n bpm 90"));
|
||||
CHECK(!SngFormat::looksLikeSng("versions 1\nblocked"));
|
||||
CHECK(SngFormat::looksLikeSng("x\r\nsig 4 4"));
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------- ProjectIoNameTest.kt
|
||||
|
||||
void projectIoNameTest() {
|
||||
run("ProjectIoNameTest.namesWithSpacesAndEscapesRoundTrip", [] {
|
||||
const std::vector<std::string> names = {"C1 muted", "50% ]x", "%20 literal", "plain"};
|
||||
Project p;
|
||||
for (size_t i = 0; i < names.size(); ++i) p.patterns[i].name = names[i];
|
||||
Project back;
|
||||
ProjectIo::loadInto(back, ProjectIo::save(p));
|
||||
for (size_t i = 0; i < names.size(); ++i) CHECK(back.patterns[i].name == names[i]);
|
||||
});
|
||||
run("ProjectIoNameTest.olderFilesWithoutEscapesLoadAsWritten", [] {
|
||||
CHECK(ProjectIo::decodeName("50%") == "50%");
|
||||
CHECK(ProjectIo::decodeName("C1") == "C1");
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------- ArrangementNoteOffTest.kt
|
||||
|
||||
Project projectWithMarker() {
|
||||
Project p;
|
||||
p.arrangement.set(0, 0, 0);
|
||||
p.arrangement.set(0, 1, Arrangement::NOTE_OFF);
|
||||
p.arrangement.set(0, 2, 0);
|
||||
return p;
|
||||
}
|
||||
|
||||
void arrangementNoteOffTest() {
|
||||
run("ArrangementNoteOffTest.markerSurvivesAProjectRoundTrip", [] {
|
||||
Project back;
|
||||
ProjectIo::loadInto(back, ProjectIo::save(projectWithMarker()));
|
||||
CHECK(back.arrangement.patternAt(0, 0) == 0);
|
||||
CHECK(back.arrangement.patternAt(0, 1) == Arrangement::NOTE_OFF);
|
||||
CHECK(back.arrangement.patternAt(0, 2) == 0);
|
||||
});
|
||||
run("ArrangementNoteOffTest.markerSurvivesAnSngRoundTrip", [] {
|
||||
const std::string text = SngFormat::exportText(projectWithMarker());
|
||||
CHECK(text.find("roll #x#") != std::string::npos);
|
||||
Project back;
|
||||
SngFormat::importInto(back, text);
|
||||
CHECK(back.arrangement.patternAt(0, 0) == 0);
|
||||
CHECK(back.arrangement.patternAt(0, 1) == Arrangement::NOTE_OFF);
|
||||
CHECK(back.arrangement.patternAt(0, 2) == 0);
|
||||
});
|
||||
run("ArrangementNoteOffTest.anUnknownRollCharacterReadsAsEmpty", [] {
|
||||
Project p;
|
||||
SngFormat::importInto(p, "version 1\nbpm 120\nsig 4 4\n\nblock A 4 4\nroll #?#\nendblock");
|
||||
CHECK(p.arrangement.patternAt(0, 0) == 0);
|
||||
CHECK(p.arrangement.patternAt(0, 1) == Arrangement::EMPTY);
|
||||
CHECK(p.arrangement.patternAt(0, 2) == 0);
|
||||
});
|
||||
run("ArrangementNoteOffTest.markerIsFilledButIsNotABlock", [] {
|
||||
Arrangement arr;
|
||||
arr.set(0, 5, Arrangement::NOTE_OFF);
|
||||
CHECK(arr.lastFilledBeat() == 5);
|
||||
CHECK(!arr.hasBlockAt(0, 5));
|
||||
CHECK(arr.patternAt(0, 5) != Arrangement::EMPTY);
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------- Kotlin text semantics
|
||||
|
||||
void kotlinSemantics() {
|
||||
run("Float.toString matches JDK 17.0.14 (sample; the port was swept over all 2^32 floats)", [] {
|
||||
const struct { uint32_t bits; const char *text; } cases[] = {
|
||||
{0x42f00000, "120.0"}, {0x3f4ccccd, "0.8"}, {0x38d1b717, "1.0E-4"}, {0x501502f9, "1.0E10"},
|
||||
{0x00800000, "1.17549435E-38"}, {0x00000001, "1.4E-45"}, {0x7f7fffff, "3.4028235E38"},
|
||||
{0x3a83126f, "0.001"}, {0x3a83126e, "9.999999E-4"}, {0x4b189680, "1.0E7"}, {0x4b18967f, "9999999.0"},
|
||||
{0x3eaaaaab, "0.33333334"}, {0x32abcc77, "2.0E-8"}, {0x3dcccccd, "0.1"}, {0x3f19999a, "0.6"},
|
||||
{0x80000000, "-0.0"}, {0x3727c5ac, "1.0E-5"}, {0x47f12065, "123456.79"}, {0x7f61b1e6, "3.0E38"},
|
||||
{0x0000025f, "8.5E-43"}, {0x6363aeb5, "4.2E21"}, {0x3ec99326, "0.39370078"}, {0x4b800000, "1.6777216E7"},
|
||||
{0x4c000001, "3.3554436E7"}, {0x7fc00000, "NaN"}, {0xff800000, "-Infinity"}, {0xbf4ccccd, "-0.8"},
|
||||
};
|
||||
for (const auto &c : cases) {
|
||||
float f; std::memcpy(&f, &c.bits, 4);
|
||||
const std::string got = kotlinFloatToString(f);
|
||||
if (got != c.text) std::printf(" %08x: want %s, got %s\n", c.bits, c.text, got.c_str());
|
||||
CHECK(got == c.text);
|
||||
}
|
||||
ToolboxSlot s;
|
||||
s.set("x", 0.8f);
|
||||
CHECK(std::string(s.s("x")) == "0.8");
|
||||
});
|
||||
run("toFloatOrNull follows Java's Float.parseFloat grammar", [] {
|
||||
const struct { const char *in; bool ok; uint32_t bits; } cases[] = {
|
||||
{"1e3f", true, 0x447a0000}, {" 0.5 ", true, 0x3f000000}, {"0x1p-2", true, 0x3e800000},
|
||||
{".5", true, 0x3f000000}, {"5.", true, 0x40a00000}, {"1e", false, 0}, {"abc", false, 0},
|
||||
{"+.5e-1D", true, 0x3d4ccccd}, {"0x.8p1", true, 0x3f800000}, {"-Infinity", true, 0xff800000},
|
||||
{"1_0", false, 0}, {"0x1p", false, 0}, {"1.0E-46", true, 0}, {"\xc2\xa0" "0.5", false, 0},
|
||||
{"3.4028236e38", true, 0x7f800000}, {"", false, 0}, {".", false, 0}, {"-", false, 0},
|
||||
};
|
||||
for (const auto &c : cases) {
|
||||
float f = 0;
|
||||
const bool ok = io::kt::toFloatOrNull(c.in, f);
|
||||
uint32_t bits; std::memcpy(&bits, &f, 4);
|
||||
if (ok != c.ok || (ok && bits != c.bits)) std::printf(" [%s]: got %d %08x\n", c.in, ok, bits);
|
||||
CHECK(ok == c.ok && (!ok || bits == c.bits));
|
||||
}
|
||||
float f = 0;
|
||||
CHECK(io::kt::toFloatOrNull("NaN", f) && std::isnan(f));
|
||||
});
|
||||
run("toIntOrNull, trim and lines follow Kotlin", [] {
|
||||
int v = 0;
|
||||
CHECK(io::kt::toIntOrNull("+5", v) && v == 5);
|
||||
CHECK(io::kt::toIntOrNull("-2147483648", v) && v == INT32_MIN);
|
||||
CHECK(!io::kt::toIntOrNull("2147483648", v));
|
||||
CHECK(!io::kt::toIntOrNull("-", v) && !io::kt::toIntOrNull("", v) && !io::kt::toIntOrNull(" 1", v));
|
||||
CHECK(io::kt::toIntOrNull("\xd9\xa4", v) && v == 4); // Arabic-Indic four
|
||||
CHECK(io::kt::toIntOrNull("7F", v, 16) && v == 127);
|
||||
CHECK(io::kt::toIntOrNull("\xef\xbc\xa6", v, 16) && v == 15); // fullwidth F
|
||||
CHECK(io::kt::trim("\xc2\xa0 x \xe3\x80\x80\t") == "x");
|
||||
auto l = io::kt::lines("a\r\nb\rc\n");
|
||||
CHECK(l.size() == 4 && l[0] == "a" && l[1] == "b" && l[2] == "c" && l[3].empty());
|
||||
CHECK(io::kt::hexUpper(-1) == "-1" && io::kt::hexUpper(0x6e) == "6E");
|
||||
CHECK(io::kt::floatToInt(NAN) == 0 && io::kt::floatToInt(1e20f) == INT32_MAX);
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------- tolerance and malformed input
|
||||
|
||||
void tolerance(const std::string &dir) {
|
||||
run("ProjectIo: missing sections and bad lines fall back like Kotlin", [] {
|
||||
Project p;
|
||||
p.name = "kept";
|
||||
ProjectIo::loadInto(p,
|
||||
"garbage line\nTEMPO=fast\nSIG=SEVEN_EIGHT\nSCALE=MAJOR\nACTIVE=99\n"
|
||||
"[PATTERN id=3 name=Hi%20there len=-4]\n" // negative length: Kotlin throws, line skipped
|
||||
"[PATTERN id=2 name=Two len=8]\n0,1,60,500,99\n9,1,60,1,1\n0,8,60,1,1\n0,2,x,y,z\n"
|
||||
"[MIXER]\n1,5,1,2,3,4,7,oops,1,0\n2,1\n"
|
||||
"[TOOLBOX]\n3=NOPE;x;\n4=FILTER;My;cutoff=0.3,bad,=v\n20=FILTER;x;\n");
|
||||
CHECK(p.name == "kept");
|
||||
CHECK(p.tempoBpm == 120.f);
|
||||
CHECK(p.timeSignature == TimeSignature::FOUR_FOUR);
|
||||
CHECK(p.scale == Scale::MAJOR);
|
||||
CHECK(p.activePatternId == 7); // coerced into 0..patterns.size-1
|
||||
CHECK(p.patterns.size() == 8);
|
||||
const Pattern *two = p.pattern(2);
|
||||
CHECK(two && two->name == "Two" && two->length == 8);
|
||||
CHECK(two && two->cell(0, 1).note == 60 && two->cell(0, 1).velocity == 127 && two->cell(0, 1).channel == 16);
|
||||
CHECK(two && two->cell(0, 2).note == Cell::EMPTY && two->cell(0, 2).channel == 1);
|
||||
CHECK(p.pattern(3) && p.pattern(3)->name == "BLK4" && p.pattern(3)->length == 16);
|
||||
CHECK(p.mixer.channels[1].instrumentSlot == 5 && p.mixer.channels[1].volume == 0.8f && p.mixer.channels[1].mute);
|
||||
CHECK(p.toolbox[3].isEmpty());
|
||||
CHECK(p.toolbox[4].type == "FILTER" && p.toolbox[4].name == "My" && std::string(p.toolbox[4].s("cutoff")) == "0.3");
|
||||
CHECK(std::string(p.toolbox[4].s("", "none")) == "v");
|
||||
});
|
||||
run("SngFormat: bpm clamps, unknown lines ignored, steps outside a block dropped", [] {
|
||||
Project p;
|
||||
SngFormat::importInto(p, "# c\nbpm 999\nsig 5 4\n0 C-4 7F 01\nblock\ntrack\n0 C-4 zz ..\n99 C-4 .. ..\nendblock\nbpm NaN");
|
||||
CHECK(p.tempoBpm == 300.f);
|
||||
CHECK(p.timeSignature == TimeSignature::FIVE_FOUR);
|
||||
CHECK(p.patterns[0].name == "PTN");
|
||||
CHECK(p.patterns[0].cell(0, 0).note == 60 && p.patterns[0].cell(0, 0).velocity == 127);
|
||||
});
|
||||
run("PresetIo: no TYPE fails, NAME is overwritten by fill, duplicates keep first position", [] {
|
||||
ToolboxSlot s;
|
||||
CHECK(!PresetIo::importText(s, "SIZZLE-PRESET 1\nNAME=x\ncutoff=0.2"));
|
||||
CHECK(s.isEmpty() && s.name == "x");
|
||||
CHECK(PresetIo::importText(s, "TYPE=FILTER\nNAME=Mine\nzz=1\ncutoff=0.2\nzz=2\nnot a line\n"));
|
||||
CHECK(s.type == "FILTER" && s.name == "Filter (LP/HP/BP)");
|
||||
CHECK(std::string(s.s("zz")) == "2" && std::string(s.s("cutoff")) == "0.2");
|
||||
const std::string out = PresetIo::exportText(s);
|
||||
CHECK(out.size() > 6 && out.compare(out.size() - 5, 5, "zz=2\n") == 0);
|
||||
CHECK(PresetIo::exportText(ToolboxSlot()) == "SIZZLE-PRESET 1\nTYPE=EMPTY");
|
||||
CHECK(!PresetIo::importText(s, "TYPE=FILTER\nTYPE=NOPE")); // a later bad TYPE wins
|
||||
});
|
||||
run("malformed input never crashes (mutated reference files)", [&] {
|
||||
std::vector<std::string> inputs;
|
||||
for (const char *ext : {".szg", ".sng", ".szp"})
|
||||
for (const auto &f : listDir(dir, ext)) { std::string t; readFile(dir + "/" + f, t); inputs.push_back(t); }
|
||||
uint32_t seed = 0x1234567;
|
||||
auto rnd = [&] { seed ^= seed << 13; seed ^= seed >> 17; seed ^= seed << 5; return seed; };
|
||||
const char junk[] = {'\0', '\n', '\r', ',', ';', '=', '[', ']', ' ', '-', '9', '#', 'x', '%', '\xc2', '\xa0', '\xff'};
|
||||
int runs = 0;
|
||||
for (const std::string &base : inputs) {
|
||||
for (int k = 0; k < 40; ++k) {
|
||||
std::string t = base;
|
||||
const int edits = 1 + (int)(rnd() % 20);
|
||||
for (int e = 0; e < edits && !t.empty(); ++e) {
|
||||
const size_t at = rnd() % t.size();
|
||||
switch (rnd() % 4) {
|
||||
case 0: t[at] = junk[rnd() % sizeof junk]; break;
|
||||
case 1: t.erase(at, 1 + rnd() % 8); break;
|
||||
case 2: t.insert(at, 1, junk[rnd() % sizeof junk]); break;
|
||||
default: t.insert(at, "99999999999"); break;
|
||||
}
|
||||
}
|
||||
Project p;
|
||||
ProjectIo::loadInto(p, t);
|
||||
ProjectIo::save(p);
|
||||
SngFormat::exportText(p);
|
||||
Project q;
|
||||
SngFormat::importInto(q, t);
|
||||
SngFormat::exportText(q);
|
||||
SngFormat::looksLikeSng(t);
|
||||
ToolboxSlot s;
|
||||
PresetIo::importText(s, t);
|
||||
PresetIo::exportText(s);
|
||||
++runs;
|
||||
}
|
||||
}
|
||||
Project big;
|
||||
ProjectIo::loadInto(big, "[PATTERN id=0 len=2147483647]\n[PATTERN id=1 len=4000000]\n0,0,60,1,1\n");
|
||||
CHECK(big.patterns.size() == 8 && big.pattern(1)->length == 16);
|
||||
CHECK(runs > 0);
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 3) { std::fprintf(stderr, "usage: %s <songs dir> <mikroseq dir>\n", argv[0]); return 2; }
|
||||
goldenFiles(argv[1]);
|
||||
sngFormatTest();
|
||||
sngMikroSeqImportTest(argv[2]);
|
||||
projectIoNameTest();
|
||||
arrangementNoteOffTest();
|
||||
kotlinSemantics();
|
||||
tolerance(argv[1]);
|
||||
std::printf("io_test: %d passed, %d failed\n", passes, failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// sizzle/Midi.hpp against the behaviour the Android unit tests pin down
|
||||
// (MidiByteParserTest, MidiSoundModuleTest) and MidiClock's tempo follow.
|
||||
|
||||
#include "sizzle/Midi.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace sizzle::midi;
|
||||
|
||||
static int failures = 0;
|
||||
#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++failures; } } while (0)
|
||||
|
||||
struct Rec : NoteSink {
|
||||
std::vector<std::string> log;
|
||||
void busNoteOn(int ch, int n, int v) override { log.push_back("on " + std::to_string(ch) + " " + std::to_string(n) + " " + std::to_string(v)); }
|
||||
void busNoteOff(int ch, int n) override { log.push_back("off " + std::to_string(ch) + " " + std::to_string(n)); }
|
||||
};
|
||||
|
||||
int main() {
|
||||
// ---- parser
|
||||
std::vector<std::vector<int>> msgs;
|
||||
std::vector<int> rt;
|
||||
MidiByteParser p([&](int s, int a, int b) { msgs.push_back({s, a, b}); }, [&](int s) { rt.push_back(s); });
|
||||
const uint8_t a[] = {0x90, 60, 100, 62, 90}; // running status
|
||||
p.feed(a, sizeof a);
|
||||
CHECK(msgs.size() == 2 && msgs[1] == (std::vector<int>{0x90, 62, 90}));
|
||||
const uint8_t b1[] = {0x80, 60}, b2[] = {0xF8, 0}; // split + realtime inside
|
||||
p.feed(b1, 2); p.feed(b2, 2);
|
||||
CHECK(msgs.size() == 3 && msgs[2] == (std::vector<int>{0x80, 60, 0}) && rt == std::vector<int>{0xF8});
|
||||
const uint8_t c[] = {0xC3, 5, 0xF0, 1, 2, 3, 0xF7, 7}; // program change, SysEx skipped, stray byte
|
||||
p.feed(c, sizeof c);
|
||||
CHECK(msgs.size() == 4 && msgs[3] == (std::vector<int>{0xC3, 5, 0}));
|
||||
const uint8_t d[] = {0xF2, 1, 2, 64, 0xB0, 123, 0}; // system common cancels running status
|
||||
msgs.clear(); p.feed(d, sizeof d);
|
||||
CHECK(msgs.size() == 1 && msgs[0] == (std::vector<int>{0xB0, 123, 0}));
|
||||
|
||||
// ---- sound module
|
||||
Rec r;
|
||||
MidiSoundModule m(r);
|
||||
std::vector<std::string> mirror;
|
||||
m.listener = [&](bool on, int ch, int n, int) { mirror.push_back((on ? "+" : "-") + std::to_string(ch) + ":" + std::to_string(n)); };
|
||||
m.sourceConnected(1); m.sourceConnected(2);
|
||||
CHECK(m.onChannelMessage(1, 0x90, 60, 100));
|
||||
CHECK(m.onChannelMessage(2, 0x91, 64, 80));
|
||||
CHECK(m.onChannelMessage(1, 0x90, 60, 0)); // velocity 0 = off
|
||||
CHECK(m.heldNotes(1).empty() && m.heldNotes(2).size() == 1);
|
||||
CHECK(!m.onChannelMessage(1, 0xB0, 7, 100)); // other CCs are the caller's
|
||||
m.onChannelMessage(1, 0x92, 70, 90);
|
||||
CHECK(m.onChannelMessage(2, 0xB2, 123, 0)); // channel 3 off from any source
|
||||
CHECK(m.heldNotes(1).empty());
|
||||
r.log.clear();
|
||||
m.sourceDisconnected(2); // releases its held note
|
||||
CHECK(r.log == std::vector<std::string>{"off 2 64"} && m.sourceCount() == 1);
|
||||
CHECK(mirror.front() == "+1:60" && mirror.back() == "-2:64");
|
||||
|
||||
// ---- clock follow: 24 pulses at 125 BPM = 20 ms each
|
||||
ClockFollower f;
|
||||
float bpm = 0; int starts = 0, stops = 0;
|
||||
f.onTempo = [&](float b) { bpm = b; };
|
||||
f.onTransport = [&](bool s) { s ? ++starts : ++stops; };
|
||||
f.realtime(0xFA, 0);
|
||||
for (int i = 0; i <= 24; ++i) f.realtime(0xF8, 1'000'000'000LL + i * 20'000'000LL);
|
||||
f.realtime(0xFC, 0);
|
||||
CHECK(starts == 1 && stops == 1 && bpm > 124.99f && bpm < 125.01f);
|
||||
|
||||
std::printf(failures ? "midi_test: %d failure(s)\n" : "midi_test: ok\n", failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
// 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 <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unistd.h>
|
||||
#include "SampleStore.hpp"
|
||||
#include "SampleVoice.hpp"
|
||||
#include "SoundFontLoader.hpp"
|
||||
|
||||
using namespace sizzle;
|
||||
using namespace sizzle::sampler;
|
||||
using Bytes = std::vector<uint8_t>;
|
||||
|
||||
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<SoundFontLoader::Loaded> 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<int> &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<float>(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<float>(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<float>(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;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// io/Zip: round trips, damage, unsafe names; argv[1]: an archive java.util.zip wrote
|
||||
// (with data descriptors, as Android's ZipOutputStream does), holding a.txt = "hello\n"
|
||||
// and dir/b.bin; argv[2]: where to write an archive for `unzip -t`.
|
||||
|
||||
#include "io/Zip.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
|
||||
using namespace sizzle::io;
|
||||
|
||||
static int failures = 0;
|
||||
#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++failures; } } while (0)
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
std::vector<zip::Entry> in = {{"project.szg", std::vector<uint8_t>(5000, 'x')}, {"empty", {}},
|
||||
{"samples/0.wav", {}}};
|
||||
for (int i = 0; i < 3000; ++i) in[2].data.push_back((uint8_t)(i * 7919 >> 3));
|
||||
auto bytes = zip::write(in);
|
||||
std::vector<zip::Entry> out;
|
||||
CHECK(zip::read(bytes.data(), bytes.size(), out));
|
||||
CHECK(out.size() == 3 && out[0].name == "project.szg" && out[0].data == in[0].data && out[1].data.empty() && out[2].data == in[2].data);
|
||||
CHECK(bytes.size() < 5000); // deflated
|
||||
|
||||
auto bad = bytes;
|
||||
bad[50] ^= 0xFF; // inside the first entry's data
|
||||
CHECK(!zip::read(bad.data(), bad.size(), out) && out.empty());
|
||||
CHECK(!zip::read(bytes.data(), bytes.size() - 10, out));
|
||||
CHECK(!zip::read(bytes.data(), bytes.size(), out, 1000)); // over the size budget
|
||||
CHECK(!zip::read(bytes.data(), bytes.size(), out, 1 << 30, 2));
|
||||
|
||||
CHECK(zip::safeName("songs/a b.szg") && zip::safeName("x"));
|
||||
CHECK(!zip::safeName("../x") && !zip::safeName("a/../../x") && !zip::safeName("/etc/x") && !zip::safeName("a\\b") && !zip::safeName(""));
|
||||
|
||||
if (argc > 1) {
|
||||
std::ifstream f(argv[1], std::ios::binary);
|
||||
std::vector<uint8_t> j((std::istreambuf_iterator<char>(f)), {});
|
||||
CHECK(zip::read(j.data(), j.size(), out));
|
||||
bool a = false, b = false;
|
||||
for (auto &e : out) {
|
||||
if (e.name == "a.txt") a = std::string(e.data.begin(), e.data.end()) == "hello\n";
|
||||
if (e.name == "dir/b.bin") b = e.data.size() == 4096;
|
||||
}
|
||||
CHECK(a && b);
|
||||
}
|
||||
if (argc > 2) { std::ofstream o(argv[2], std::ios::binary); o.write((const char *)bytes.data(), (std::streamsize)bytes.size()); }
|
||||
|
||||
std::printf(failures ? "zip_test: %d failure(s)\n" : "zip_test: ok\n", failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
Reference in New Issue
Block a user