iOS 0.3.1: engine, model and file formats in C++, verified against Kotlin; longer settings

Engine (sequencer, mixer, FX chains, MIDI effects) renders four whole songs like
AudioEngine.kt (two bit-exact, two within 9e-6). ProjectIo / SngFormat / PresetIo
round-trip the Kotlin-written files; Float.toString is JDK 17's, checked on all
2^32 floats. Params now holds 255-character values (sample ids were cut).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-16 01:50:51 +01:00
co-authored by Claude Opus 5.5
parent b1dc5ed8db
commit 7bc54e6466
20 changed files with 3746 additions and 41 deletions
+238
View File
@@ -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;
}
+565
View File
@@ -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;
}