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
+215
View File
@@ -0,0 +1,215 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "io/KotlinText.hpp"
#include <climits>
#include <clocale>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
namespace sizzle::io::kt {
unsigned decodeUtf8(const std::string &s, size_t &i) {
const unsigned char c0 = (unsigned char)s[i];
if (c0 < 0x80) { ++i; return c0; }
int n; unsigned cp, min;
if ((c0 & 0xE0) == 0xC0) { n = 1; cp = c0 & 0x1F; min = 0x80; }
else if ((c0 & 0xF0) == 0xE0) { n = 2; cp = c0 & 0x0F; min = 0x800; }
else if ((c0 & 0xF8) == 0xF0) { n = 3; cp = c0 & 0x07; min = 0x10000; }
else { ++i; return 0xFFFD; }
if (i + (size_t)n >= s.size()) { ++i; return 0xFFFD; }
for (int k = 1; k <= n; ++k) {
const unsigned char c = (unsigned char)s[i + (size_t)k];
if ((c & 0xC0) != 0x80) { ++i; return 0xFFFD; }
cp = (cp << 6) | (c & 0x3F);
}
if (cp < min || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) { ++i; return 0xFFFD; }
i += (size_t)n + 1;
return cp;
}
bool isWhitespace(unsigned cp) {
return (cp >= 0x09 && cp <= 0x0D) || (cp >= 0x1C && cp <= 0x20) || cp == 0xA0 || cp == 0x1680 ||
(cp >= 0x2000 && cp <= 0x200A) || cp == 0x2028 || cp == 0x2029 || cp == 0x202F || cp == 0x205F ||
cp == 0x3000;
}
// Zeros of the BMP's Nd (decimal digit) runs, Unicode 13 (JDK 17). Supplementary
// digits arrive in Kotlin as surrogate pairs, which are not digits.
static const unsigned kDigitZeros[] = {
0x0030, 0x0660, 0x06F0, 0x07C0, 0x0966, 0x09E6, 0x0A66, 0x0AE6, 0x0B66, 0x0BE6, 0x0C66, 0x0CE6,
0x0D66, 0x0DE6, 0x0E50, 0x0ED0, 0x0F20, 0x1040, 0x1090, 0x17E0, 0x1810, 0x1946, 0x19D0, 0x1A80,
0x1A90, 0x1B50, 0x1BB0, 0x1C40, 0x1C50, 0xA620, 0xA8D0, 0xA900, 0xA9D0, 0xA9F0, 0xAA50, 0xABF0, 0xFF10};
int decimalDigit(unsigned cp) {
for (unsigned z : kDigitZeros)
if (cp >= z && cp < z + 10) return (int)(cp - z);
return -1;
}
/** Character.digit(cp, radix). */
static int digitOf(unsigned cp, int radix) {
int d = decimalDigit(cp);
if (d < 0) {
if (cp >= 'a' && cp <= 'z') d = (int)(cp - 'a') + 10;
else if (cp >= 'A' && cp <= 'Z') d = (int)(cp - 'A') + 10;
else if (cp >= 0xFF41 && cp <= 0xFF5A) d = (int)(cp - 0xFF41) + 10;
else if (cp >= 0xFF21 && cp <= 0xFF3A) d = (int)(cp - 0xFF21) + 10;
}
return d >= 0 && d < radix ? d : -1;
}
std::vector<std::string> lines(const std::string &text) {
std::vector<std::string> out;
size_t start = 0;
for (size_t i = 0; i < text.size(); ++i) {
if (text[i] == '\n' || text[i] == '\r') {
out.emplace_back(text, start, i - start);
if (text[i] == '\r' && i + 1 < text.size() && text[i + 1] == '\n') ++i;
start = i + 1;
}
}
out.emplace_back(text, start, text.size() - start);
return out;
}
std::string trim(const std::string &s) {
size_t first = s.size(), last = 0; // [first, last) of non-whitespace
size_t i = 0;
while (i < s.size()) {
size_t at = i;
unsigned cp = decodeUtf8(s, i);
if (!isWhitespace(cp)) { if (first == s.size()) first = at; last = i; }
}
return first == s.size() ? std::string() : s.substr(first, last - first);
}
std::vector<std::string> split(const std::string &s, char c) {
std::vector<std::string> out;
size_t start = 0;
for (size_t i = 0; i < s.size(); ++i)
if (s[i] == c) { out.emplace_back(s, start, i - start); start = i + 1; }
out.emplace_back(s, start, s.size() - start);
return out;
}
size_t utf16Length(const std::string &s) {
size_t n = 0;
forEachIndexed(s, [&](size_t idx, unsigned cp) { n = idx + (cp >= 0x10000 ? 2 : 1); });
return n;
}
bool startsWith(const std::string &s, const char *prefix) {
size_t n = std::strlen(prefix);
return s.size() >= n && s.compare(0, n, prefix) == 0;
}
bool toIntOrNull(const std::string &s, int &out, int radix) {
if (s.empty()) return false;
size_t i = 0;
bool negative = false;
if ((unsigned char)s[0] < '0') { // a possible sign (Kotlin: firstChar < '0')
if (s.size() == 1) return false;
if (s[0] == '-') negative = true;
else if (s[0] != '+') return false;
i = 1;
}
int64_t v = 0;
const int64_t limit = negative ? -(int64_t)INT_MIN : (int64_t)INT_MAX;
while (i < s.size()) {
int d = digitOf(decodeUtf8(s, i), radix);
if (d < 0) return false;
v = v * radix + d;
if (v > limit) return false;
}
out = (int)(negative ? -v : v);
return true;
}
// Java's Double.valueOf grammar (what Kotlin screens toFloatOrNull with):
// [\x00-\x20]*[+-]?(NaN|Infinity|((Number)[fFdD]?))[\x00-\x20]*
bool toFloatOrNull(const std::string &str, float &out) {
size_t b = 0, e = str.size();
while (b < e && (unsigned char)str[b] <= 0x20) ++b;
while (e > b && (unsigned char)str[e - 1] <= 0x20) --e;
if (b == e) return false;
std::string s = str.substr(b, e - b);
size_t i = 0;
bool neg = false;
if (s[i] == '+' || s[i] == '-') { neg = s[i] == '-'; ++i; }
std::string rest = s.substr(i);
if (rest == "NaN") { out = NAN; return true; }
if (rest == "Infinity") { out = neg ? -INFINITY : INFINITY; return true; }
auto isDec = [](char c) { return c >= '0' && c <= '9'; };
auto isHex = [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); };
size_t j = i;
auto run = [&](auto pred) { size_t n = 0; while (j < s.size() && pred(s[j])) { ++j; ++n; } return n; };
if (j + 1 < s.size() && s[j] == '0' && (s[j + 1] == 'x' || s[j + 1] == 'X')) {
j += 2;
size_t a = run(isHex), f = 0;
bool dot = j < s.size() && s[j] == '.';
if (dot) { ++j; f = run(isHex); }
if (a == 0 && f == 0) return false;
if (j >= s.size() || (s[j] != 'p' && s[j] != 'P')) return false;
++j;
if (j < s.size() && (s[j] == '+' || s[j] == '-')) ++j;
if (run(isDec) == 0) return false;
} else {
size_t a = run(isDec), f = 0;
if (j < s.size() && s[j] == '.') { ++j; f = run(isDec); }
if (a == 0 && f == 0) return false;
if (j < s.size() && (s[j] == 'e' || s[j] == 'E')) {
++j;
if (j < s.size() && (s[j] == '+' || s[j] == '-')) ++j;
if (run(isDec) == 0) return false;
}
}
size_t numEnd = j;
if (j < s.size() && (s[j] == 'f' || s[j] == 'F' || s[j] == 'd' || s[j] == 'D')) ++j;
if (j != s.size()) return false;
std::string num = s.substr(0, numEnd);
// strtof reads the C locale's decimal point; keep it right if a host changed it.
const char *dp = std::localeconv()->decimal_point;
if (dp && std::strcmp(dp, ".") != 0) {
size_t p = num.find('.');
if (p != std::string::npos) num.replace(p, 1, dp);
}
out = std::strtof(num.c_str(), nullptr);
return true;
}
int floatToInt(float v) {
if (std::isnan(v)) return 0;
if (v >= 2147483648.f) return INT_MAX;
if (v <= -2147483648.f) return INT_MIN;
return (int)v;
}
std::string hexUpper(int v) {
uint32_t m = v < 0 ? (uint32_t)0 - (uint32_t)v : (uint32_t)v;
std::string r;
do { r.insert(r.begin(), "0123456789ABCDEF"[m & 15]); m >>= 4; } while (m);
return v < 0 ? "-" + r : r;
}
std::string padStart(const std::string &s, size_t n, char c) {
size_t len = utf16Length(s);
return len >= n ? s : std::string(n - len, c) + s;
}
std::string replaceAll(const std::string &s, const std::string &from, const std::string &to) {
if (from.empty()) return s;
std::string out;
size_t pos = 0;
for (size_t f; (f = s.find(from, pos)) != std::string::npos; pos = f + from.size()) {
out.append(s, pos, f - pos);
out += to;
}
out.append(s, pos, std::string::npos);
return out;
}
} // namespace sizzle::io::kt
+55
View File
@@ -0,0 +1,55 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Kotlin/JVM string semantics the file formats rely on, for UTF-8 text: lines
// (lineSequence), trim (Char.isWhitespace), split (keeps empty parts), lengths and
// indices in UTF-16 units (String.length, forEachIndexed), toIntOrNull (Unicode
// decimal digits, as Character.digit) and toFloatOrNull (Java's Float.parseFloat
// grammar). Malformed UTF-8 bytes are kept as they are and count as one unit each.
#include <string>
#include <vector>
namespace sizzle::io::kt {
/** One code point at s[i], advancing i; malformed bytes come back one at a time. */
unsigned decodeUtf8(const std::string &s, size_t &i);
/** Kotlin's Char.isWhitespace (Character.isWhitespace || isSpaceChar), BMP. */
bool isWhitespace(unsigned cp);
/** Character.isDigit's decimal value of [cp] (0..9), or -1. */
int decimalDigit(unsigned cp);
/** text.lineSequence(): split on CRLF, LF and CR. */
std::vector<std::string> lines(const std::string &text);
/** String.trim(). */
std::string trim(const std::string &s);
/** String.split(c): every part, empty ones included. */
std::vector<std::string> split(const std::string &s, char c);
/** String.length (UTF-16 units). */
size_t utf16Length(const std::string &s);
/** The code points of [s] with their UTF-16 index (as forEachIndexed sees them). */
template <typename F> void forEachIndexed(const std::string &s, F f) {
size_t i = 0, idx = 0;
while (i < s.size()) {
unsigned cp = decodeUtf8(s, i);
f(idx, cp);
idx += cp >= 0x10000 ? 2 : 1;
}
}
bool startsWith(const std::string &s, const char *prefix);
/** String.toIntOrNull(radix). */
bool toIntOrNull(const std::string &s, int &out, int radix = 10);
/** String.toFloatOrNull(). */
bool toFloatOrNull(const std::string &s, float &out);
/** Float.toInt(): NaN -> 0, saturating. */
int floatToInt(float v);
/** Integer.toString(v, 16), upper-cased. */
std::string hexUpper(int v);
/** padStart(n, '0'). */
std::string padStart(const std::string &s, size_t n, char c = '0');
/** replace(from, to) on every non-overlapping occurrence, left to right. */
std::string replaceAll(const std::string &s, const std::string &from, const std::string &to);
} // namespace sizzle::io::kt
+69
View File
@@ -0,0 +1,69 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "io/PresetIo.hpp"
#include <cstring>
#include <unordered_map>
#include <utility>
#include <vector>
#include "io/KotlinText.hpp"
#include "sizzle/Specs.hpp"
namespace sizzle::io {
using namespace model;
std::string PresetIo::exportText(const ToolboxSlot &slot) {
if (slot.isEmpty()) return std::string(HEADER) + "\nTYPE=EMPTY";
const DeviceSpec *spec = findDevice(slot.type.c_str());
std::string o;
auto line = [&](const std::string &s) { o += s; o += '\n'; };
line(HEADER);
line("TYPE=" + slot.type);
line("NAME=" + slot.name);
// Params in the type's declared order, then any extra keys the slot holds.
const int n = spec ? spec->paramCount : 0;
for (int i = 0; i < n; ++i) {
const ParamSpec &p = spec->params[i];
line(std::string(p.key) + "=" + slot.s(p.key, kotlinFloatToString(p.def).c_str()));
}
for (int i = 0; i < slot.values.size(); ++i) {
const char *key = slot.values.keyAt(i);
bool declared = false;
for (int k = 0; k < n && !declared; ++k) declared = std::strcmp(spec->params[k].key, key) == 0;
if (!declared) line(std::string(key) + "=" + slot.values.valueAt(i));
}
return o;
}
bool PresetIo::importText(ToolboxSlot &slot, const std::string &text) {
std::vector<std::pair<std::string, std::string>> map; // a LinkedHashMap
std::unordered_map<std::string, size_t> index;
std::string type;
bool hasType = false;
for (const std::string &raw : kt::lines(text)) {
const std::string line = kt::trim(raw);
if (line.empty() || line == HEADER) continue;
const size_t eq = line.find('=');
if (eq == std::string::npos) continue;
std::string key = line.substr(0, eq), value = line.substr(eq + 1);
if (key == "TYPE") {
hasType = value.find('\0') == std::string::npos && findDevice(value.c_str()) != nullptr;
type = hasType ? value : std::string();
} else if (key == "NAME") {
slot.name = value;
} else {
auto it = index.find(key);
if (it != index.end()) map[it->second].second = std::move(value);
else { index.emplace(key, map.size()); map.emplace_back(std::move(key), std::move(value)); }
}
}
if (!hasType) return false;
slot.fill(type); // reset to defaults for the type (and its display name) ...
if (kt::trim(slot.name).empty()) slot.name = findDevice(type.c_str())->displayName;
for (const auto &kv : map) slot.set(kv.first.c_str(), kv.second.c_str()); // ... then the saved values
return true;
}
} // namespace sizzle::io
+23
View File
@@ -0,0 +1,23 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of io/PresetIo.kt: one device's settings as text ("SIZZLE-PRESET 1",
// TYPE=, NAME=, then key=value in the device's parameter order, then any extra
// keys the slot holds, e.g. sample ids).
#include <string>
#include "sizzle/Model.hpp"
namespace sizzle::io {
struct PresetIo {
static constexpr const char *HEADER = "SIZZLE-PRESET 1";
static std::string exportText(const model::ToolboxSlot &slot);
/** Parse preset [text] into [slot]; false (slot settings untouched) unless a
* known TYPE is found. As in Kotlin, the slot's name ends up as the device's
* display name: NAME is applied before fill(), which overwrites it. */
static bool importText(model::ToolboxSlot &slot, const std::string &text);
};
} // namespace sizzle::io
+295
View File
@@ -0,0 +1,295 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "io/ProjectIo.hpp"
#include <algorithm>
#include <map>
#include "io/KotlinText.hpp"
#include "sizzle/Specs.hpp"
namespace sizzle::io {
using namespace model;
static const char *HEADER = "SIZZLETRACKER-SNG 1";
static const char *b(bool v) { return v ? "1" : "0"; }
// ------------------------------------------------------------------- write
std::string ProjectIo::save(const Project &project) {
std::string o;
auto line = [&](const std::string &s) { o += s; o += '\n'; };
auto num = [](int v) { return std::to_string(v); };
line(HEADER);
line("NAME=" + project.name);
line("TEMPO=" + kotlinFloatToString(project.tempoBpm));
line(std::string("SIG=") + info(project.timeSignature).name);
line(std::string("SCALE=") + info(project.scale).name);
line("ROOT=" + num(project.rootNote));
line("ACTIVE=" + num(project.activePatternId));
for (const Pattern &p : project.patterns) {
line("[PATTERN id=" + num(p.id) + " name=" + encodeName(p.name) + " len=" + num(p.length) + "]");
for (int t = 0; t < Pattern::TRACK_COUNT; ++t) {
const int n = std::min(p.length, (int)p.tracks[t].size());
for (int ln = 0; ln < n; ++ln) {
const Cell &c = p.tracks[t][ln];
if (!c.isEmpty())
line(num(t) + "," + num(ln) + "," + num(c.note) + "," + num(c.velocity) + "," + num(c.channel));
}
}
}
const Arrangement &arr = project.arrangement;
std::string mutes;
for (bool m : arr.laneMuted) mutes += m ? '1' : '0';
line("[ARRANGEMENT bars=" + num(arr.lengthBars) + " loop=" + b(arr.loopEnabled) + " mutes=" + mutes + "]");
const int usedBeats = arr.lastFilledBeat() + 1;
for (int lane = 0; lane < Arrangement::LANE_COUNT; ++lane) {
for (int beat = 0; beat < usedBeats; ++beat) {
const int pid = arr.slots[lane][beat];
// >= 0 is a block id; NOTE_OFF is a marker and must survive too.
if (pid >= 0 || pid == Arrangement::NOTE_OFF) line(num(lane) + "," + num(beat) + "," + num(pid));
}
}
auto region = [&](const char *n, const LoopRegion &r) {
line(std::string("[REGION ") + n + " en=" + b(r.enabled) + " s=" + num(r.start) + " e=" + num(r.end) +
" r=" + num(r.repeats) + "]");
};
region("A", arr.regionA);
region("B", arr.regionB);
line("[MIXER]");
for (const MixerChannel &ch : project.mixer.channels) {
std::string s = num(ch.index) + "," + num(ch.instrumentSlot) + ",";
for (int i = 0; i < MixerChannel::FX_SLOTS; ++i) s += (i ? "," : "") + num(ch.fxSlots[i]);
s += "," + num(ch.midiChannel) + "," + kotlinFloatToString(ch.volume) + "," + b(ch.mute) + "," +
b(ch.solo) + "," + b(ch.limiter);
line(s);
}
line("[TOOLBOX]");
for (const ToolboxSlot &slot : project.toolbox) {
if (slot.isEmpty()) continue;
std::string s = num(slot.index) + "=" + slot.type + ";" + slot.name + ";";
for (int i = 0; i < slot.values.size(); ++i) {
if (i) s += ',';
s += slot.values.keyAt(i);
s += '=';
s += slot.values.valueAt(i);
}
line(s);
}
return o;
}
// -------------------------------------------------------------------- read
namespace {
/** parseAttrs: "[NAME k=v k=v]" -> {k: v}; the last duplicate wins. */
std::map<std::string, std::string> parseAttrs(const std::string &line) {
size_t a = 0, z = line.size();
while (a < z && (line[a] == '[' || line[a] == ']')) ++a;
while (z > a && (line[z - 1] == '[' || line[z - 1] == ']')) --z;
const std::string inner = line.substr(a, z - a);
const size_t sp = inner.find(' ');
std::map<std::string, std::string> out;
if (sp == std::string::npos) return out;
for (const std::string &tok : kt::split(inner.substr(sp + 1), ' ')) {
const size_t eq = tok.find('=');
if (eq != std::string::npos) out[tok.substr(0, eq)] = tok.substr(eq + 1);
}
return out;
}
const std::string *get(const std::map<std::string, std::string> &m, const char *k) {
auto it = m.find(k);
return it == m.end() ? nullptr : &it->second;
}
int intOr(const std::string *s, int fallback) {
int v;
return s && kt::toIntOrNull(*s, v) ? v : fallback;
}
int intOr(const std::string &s, int fallback) { return intOr(&s, fallback); }
void applyHeaderField(Project &p, const std::string &line) {
const size_t eq = line.find('=');
const std::string k = line.substr(0, eq), v = line.substr(eq + 1);
if (k == "NAME") p.name = v;
else if (k == "TEMPO") { float f; p.tempoBpm = kt::toFloatOrNull(v, f) ? f : 120.f; }
else if (k == "SIG") {
p.timeSignature = TimeSignature::FOUR_FOUR;
for (int i = 0; i < TIME_SIGNATURE_COUNT; ++i)
if (v == info((TimeSignature)i).name) p.timeSignature = (TimeSignature)i;
} else if (k == "SCALE") {
p.scale = Scale::CHROMATIC;
for (int i = 0; i < SCALE_COUNT; ++i)
if (v == info((Scale)i).name) p.scale = (Scale)i;
} else if (k == "ROOT") p.rootNote = intOr(v, 0);
else if (k == "ACTIVE") p.activePatternId = intOr(v, 0);
}
void applyPatternCell(Pattern *pattern, const std::string &line) {
if (!pattern) return;
Pattern &p = *pattern;
const auto f = kt::split(line, ',');
if (f.size() < 5) return;
int t, ln;
if (!kt::toIntOrNull(f[0], t) || !kt::toIntOrNull(f[1], ln)) return;
if (t < 0 || t >= Pattern::TRACK_COUNT || ln < 0 || ln >= p.length || ln >= (int)p.tracks[t].size()) return;
Cell &c = p.tracks[t][ln];
c.note = intOr(f[2], Cell::EMPTY);
c.velocity = std::clamp(intOr(f[3], Cell::MAX_VELOCITY), 0, (int)Cell::MAX_VELOCITY);
c.channel = std::clamp(intOr(f[4], 1), 1, (int)Cell::MAX_CHANNEL);
}
void applyArrangementSlot(Project &p, const std::string &line) {
const auto f = kt::split(line, ',');
if (f.size() < 3) return;
int lane, beat, pid;
if (!kt::toIntOrNull(f[0], lane) || !kt::toIntOrNull(f[1], beat) || !kt::toIntOrNull(f[2], pid)) return;
p.arrangement.set(lane, beat, pid);
}
void applyRegion(LoopRegion &r, const std::map<std::string, std::string> &a) {
const std::string *en = get(a, "en");
r.enabled = en && *en == "1";
r.start = intOr(get(a, "s"), 0);
r.end = intOr(get(a, "e"), 0);
r.repeats = intOr(get(a, "r"), 2);
}
void applyMixerRow(Project &p, const std::string &line) {
const auto f = kt::split(line, ',');
if (f.size() < 10) return;
int idx;
if (!kt::toIntOrNull(f[0], idx) || idx < 0 || idx >= Mixer::CHANNEL_COUNT) return;
MixerChannel &ch = p.mixer.channels[idx];
ch.instrumentSlot = intOr(f[1], -1);
for (int i = 0; i < Mixer::FX_SLOTS; ++i) ch.fxSlots[i] = intOr(f[2 + i], -1);
ch.midiChannel = intOr(f[6], 0);
float v;
ch.volume = kt::toFloatOrNull(f[7], v) ? v : 0.8f;
ch.mute = f[8] == "1";
ch.solo = f[9] == "1";
ch.limiter = f.size() > 10 && f[10] == "1"; // optional: absent in older saves
}
void applyToolboxRow(Project &p, const std::string &line) {
const size_t eq = line.find('=');
int idx;
if (!kt::toIntOrNull(line.substr(0, eq), idx)) return;
const std::string rest = eq == std::string::npos ? line : line.substr(eq + 1);
const auto parts = kt::split(rest, ';');
if (parts.size() < 2) return;
if (!findDevice(parts[0].c_str()) || parts[0].find('\0') != std::string::npos) return;
if (idx < 0 || idx >= Project::TOOLBOX_SLOTS) return;
ToolboxSlot &slot = p.toolbox[idx];
slot.fill(parts[0]);
slot.name = parts[1];
if (parts.size() >= 3 && !kt::trim(parts[2]).empty()) {
for (const std::string &kv : kt::split(parts[2], ',')) {
const size_t e = kv.find('=');
if (e != std::string::npos) slot.set(kv.substr(0, e).c_str(), kv.substr(e + 1).c_str());
}
}
}
} // namespace
model::Project &ProjectIo::loadInto(Project &project, const std::string &text) {
// Reset everything Kotlin resets to a clean slate first.
project.patterns.clear();
for (auto &lane : project.arrangement.slots) std::fill(lane.begin(), lane.end(), Arrangement::EMPTY);
project.arrangement.laneMuted.fill(false);
for (auto &slot : project.toolbox) slot.clearSlot();
for (auto &ch : project.mixer.channels) {
ch.instrumentSlot = -1; ch.fxSlots.fill(-1); ch.midiChannel = 0;
ch.volume = 0.8f; ch.mute = false; ch.solo = false; ch.limiter = false;
}
std::string section;
int current = -1; // index into project.patterns (Kotlin keeps a reference)
long cells = 0;
for (const std::string &raw : kt::lines(text)) {
const std::string line = kt::trim(raw);
if (line.empty()) continue;
if (line == HEADER) {
} else if (kt::startsWith(line, "[PATTERN")) {
const auto attrs = parseAttrs(line);
const int id = intOr(get(attrs, "id"), (int)project.patterns.size());
const std::string *name = get(attrs, "name");
const int len = intOr(get(attrs, "len"), 16);
// Kotlin: a negative length throws in Pattern's constructor (line skipped);
// a huge one runs out of memory (also skipped).
if (len < 0 || cells + 4L * len > MAX_TOTAL_CELLS) continue;
cells += 4L * len;
project.patterns.emplace_back(id, name ? decodeName(*name) : std::string("PTN"), len);
current = (int)project.patterns.size() - 1;
section = "PATTERN";
} else if (kt::startsWith(line, "[ARRANGEMENT")) {
const auto attrs = parseAttrs(line);
// "bars" is the canvas unit; older files stored "len" in beats and get the
// default 256-bar canvas.
project.arrangement.lengthBars = intOr(get(attrs, "bars"), Arrangement::MAX_BARS);
const std::string *loop = get(attrs, "loop");
project.arrangement.loopEnabled = loop && *loop == "1";
if (const std::string *m = get(attrs, "mutes")) {
auto &lanes = project.arrangement.laneMuted;
kt::forEachIndexed(*m, [&](size_t i, unsigned cp) {
if (i < lanes.size()) lanes[i] = cp == '1';
});
}
section = "ARRANGEMENT";
} else if (kt::startsWith(line, "[REGION A")) {
applyRegion(project.arrangement.regionA, parseAttrs(line));
} else if (kt::startsWith(line, "[REGION B")) {
applyRegion(project.arrangement.regionB, parseAttrs(line));
} else if (kt::startsWith(line, "[MIXER]")) {
section = "MIXER";
} else if (kt::startsWith(line, "[TOOLBOX]")) {
section = "TOOLBOX";
} else if (line.find('=') != std::string::npos && line[0] != '[' && section.empty()) {
applyHeaderField(project, line);
} else if (section == "PATTERN") {
applyPatternCell(current >= 0 ? &project.patterns[current] : nullptr, line);
} else if (section == "ARRANGEMENT") {
applyArrangementSlot(project, line);
} else if (section == "MIXER") {
applyMixerRow(project, line);
} else if (section == "TOOLBOX") {
applyToolboxRow(project, line);
}
}
// One block per lane (lane i is tied to block i): pad any the file did not define.
for (int id = 0; id < Arrangement::LANE_COUNT; ++id) {
if (!project.pattern(id)) project.patterns.emplace_back(id, "BLK" + std::to_string(id + 1), 16);
}
std::stable_sort(project.patterns.begin(), project.patterns.end(),
[](const Pattern &a, const Pattern &b) { return a.id < b.id; });
project.activePatternId = std::clamp(project.activePatternId, 0, (int)project.patterns.size() - 1);
return project;
}
std::string ProjectIo::encodeName(const std::string &name) {
std::string o;
for (char c : name) {
switch (c) {
case '%': o += "%25"; break;
case ' ': o += "%20"; break;
case ']': o += "%5D"; break;
case '\t': case '\n': case '\r': o += "%20"; break;
default: o += c;
}
}
return o;
}
std::string ProjectIo::decodeName(const std::string &text) {
return kt::replaceAll(kt::replaceAll(kt::replaceAll(text, "%20", " "), "%5D", "]"), "%25", "%");
}
} // namespace sizzle::io
+32
View File
@@ -0,0 +1,32 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of io/ProjectIo.kt: the full project format (.szg, "SIZZLETRACKER-SNG 1").
// Files written by the Kotlin app load and save back byte for byte, except that
// each [TOOLBOX] line lists its key=value pairs in the slot's insertion order where
// Kotlin wrote ConcurrentHashMap order (both read back the same).
#include <string>
#include "sizzle/Model.hpp"
namespace sizzle::io {
struct ProjectIo {
static std::string save(const model::Project &project);
/** Parse [text] into the existing [project], replacing its contents (what
* Kotlin resets; header fields missing from the file keep their values).
* Malformed lines are skipped one by one, as Kotlin's runCatching does. */
static model::Project &loadInto(model::Project &project, const std::string &text);
/** Block names go into a whitespace-split header: escape space, '%' and ']'. */
static std::string encodeName(const std::string &name);
static std::string decodeName(const std::string &text);
/** Not in Kotlin (it would run out of memory and skip the line): a [PATTERN]
* line whose length would take the file's patterns past this many cells is
* skipped, so an untrusted file can't allocate without bound. */
static constexpr long MAX_TOTAL_CELLS = 1L << 22;
};
} // namespace sizzle::io
+302
View File
@@ -0,0 +1,302 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "io/SngFormat.hpp"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <set>
#include "io/KotlinText.hpp"
namespace sizzle::io {
using namespace model;
static const char *const NAMES[12] = {"C-", "C#", "D-", "D#", "E-", "F-", "F#", "G-", "G#", "A-", "A#", "B-"};
std::string pitchName(int midi) {
if (midi < Pitch::LOWEST || midi > Pitch::HIGHEST) return "...";
return std::string(NAMES[midi % 12]) + std::to_string(midi / 12 - 1);
}
int pitchParse(const std::string &text) {
const std::string t = kt::trim(text);
if (t == "OFF" || t == "===") return Cell::OFF;
if (kt::utf16Length(t) < 3 || t[0] == '.') return Cell::EMPTY;
int idx = -1;
for (int i = 0; i < 12; ++i)
if (t.compare(0, 2, NAMES[i]) == 0) { idx = i; break; }
if (idx < 0) return Cell::EMPTY;
int octave;
if (!kt::toIntOrNull(t.substr(2), octave)) return Cell::EMPTY;
// Kotlin Int arithmetic wraps before the clamp.
const int32_t v = (int32_t)((uint32_t)((int64_t)octave + 1) * 12u + (uint32_t)idx);
return std::clamp((int)v, (int)Pitch::LOWEST, (int)Pitch::HIGHEST);
}
// ------------------------------------------------------------------- write
std::string SngFormat::exportText(const Project &project) {
std::string o;
auto line = [&](const std::string &s) { o += s; o += '\n'; };
const int beatsPerBar = info(project.timeSignature).beatsPerBar;
line("version 1");
line("bpm " + std::to_string(kt::floatToInt(project.tempoBpm)));
line("sig " + std::to_string(beatsPerBar) + " 4");
line("");
const Arrangement &arr = project.arrangement;
const int usedBeats = arr.lastFilledBeat() + 1;
for (const Pattern &block : project.patterns) {
bool rollUsed = false, hasNotes = false;
for (int beat = 0; beat < usedBeats && !rollUsed; ++beat)
rollUsed = arr.patternAt(block.id, beat) != Arrangement::EMPTY;
auto len = [&](int t) { return std::min(block.length, (int)block.tracks[t].size()); };
for (int t = 0; t < Pattern::TRACK_COUNT && !hasNotes; ++t)
for (int l = 0; l < len(t) && !hasNotes; ++l) hasNotes = !block.tracks[t][l].isEmpty();
if (!rollUsed && !hasNotes) continue; // skip untouched blocks
line("block " + block.name + " " + std::to_string(block.length) + " " + std::to_string(beatsPerBar));
// '#' = play this block, 'x' = release this lane, '.' = nothing.
std::string roll;
for (int beat = 0; beat < usedBeats; ++beat) {
const int pid = arr.patternAt(block.id, beat);
roll += pid == Arrangement::EMPTY ? '.' : pid == Arrangement::NOTE_OFF ? 'x' : '#';
}
while (!roll.empty() && roll.back() == '.') roll.pop_back();
if (!roll.empty()) line("roll " + roll);
for (int t = 0; t < Pattern::TRACK_COUNT; ++t) {
bool any = false;
for (int l = 0; l < len(t) && !any; ++l) any = !block.tracks[t][l].isEmpty();
if (!any) continue;
const int defChannel = std::max(project.mixer.channels[t].midiChannel - 1, 0);
line("track T" + std::to_string(t + 1) + " " + std::to_string(defChannel));
for (int l = 0; l < len(t); ++l) {
const Cell &c = block.tracks[t][l];
if (c.isEmpty()) continue;
// A note-off has no velocity/channel: those columns are "..".
const std::string note = c.isNoteOff() ? "OFF" : pitchName(c.note);
const std::string vel = c.isNoteOff() ? ".." : kt::padStart(kt::hexUpper(c.velocity), 2);
const std::string chan = c.isNoteOff() ? ".." : kt::padStart(std::to_string(c.channel), 2);
line(std::to_string(l) + " " + note + " " + vel + " " + chan);
}
}
line("endblock");
line("");
}
return o;
}
// -------------------------------------------------------------------- read
// Java's \s (no UNICODE_CHARACTER_CLASS): [ \t\n\x0B\f\r].
static bool isRegexSpace(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\x0B' || c == '\f' || c == '\r'; }
// Regex("(?m)^\\s*(version|bpm|sig|block)\\b").containsMatchIn(text)
bool SngFormat::looksLikeSng(const std::string &text) {
static const char *const KEYS[] = {"version", "bpm", "sig", "block"};
auto lineStart = [&](size_t i) {
if (i == 0) return true;
if (i >= text.size()) return false; // MULTILINE ^ never matches at the very end
const unsigned char p = (unsigned char)text[i - 1];
if (p == '\n') return true;
if (p == '\r') return text[i] != '\n'; // no ^ between \r and \n
// U+0085, U+2028, U+2029 end lines too.
if (i >= 2 && (unsigned char)text[i - 2] == 0xC2 && p == 0x85) return true;
if (i >= 3 && (unsigned char)text[i - 3] == 0xE2 && (unsigned char)text[i - 2] == 0x80 && (p == 0xA8 || p == 0xA9))
return true;
return false;
};
// \b after the keyword: the next character is not a word character. Java 17's
// \b counts letters and digits of any script; any non-ASCII byte counts as one.
auto wordChar = [](unsigned char c) { return std::isalnum(c) || c == '_' || c >= 0x80; };
for (size_t i = 0; i <= text.size(); ++i) {
if (!lineStart(i)) continue;
size_t j = i;
while (j < text.size() && isRegexSpace(text[j])) ++j;
for (const char *k : KEYS) {
const size_t n = std::char_traits<char>::length(k);
if (text.compare(j, n, k) == 0 && (j + n >= text.size() || !wordChar((unsigned char)text[j + n])))
return true;
}
}
return false;
}
namespace {
using Tokens = std::vector<std::string>;
Tokens splitWhitespace(const std::string &line) { // line.split(Regex("\\s+")), line trimmed
Tokens out;
std::string cur;
size_t i = 0;
while (i < line.size()) {
if (isRegexSpace(line[i])) {
out.push_back(cur); cur.clear();
while (i < line.size() && isRegexSpace(line[i])) ++i;
} else {
cur += line[i++];
}
}
out.push_back(cur);
return out;
}
const std::string *at(const Tokens &t, size_t i) { return i < t.size() ? &t[i] : nullptr; }
/** `block <name...> <length> [<numTracks>]` -> (name, length or -1 for none). */
std::pair<std::string, bool> blockHeader(const Tokens &tok, int &length) {
const Tokens rest(tok.begin() + 1, tok.end());
int trailing = 0, v;
for (size_t i = rest.size(); i-- > 0 && kt::toIntOrNull(rest[i], v);) ++trailing;
trailing = std::min(trailing, 2);
bool hasLength = false;
if (trailing == 2) hasLength = kt::toIntOrNull(rest[rest.size() - 2], length);
else if (trailing == 1) hasLength = kt::toIntOrNull(rest.back(), length);
std::string name;
for (size_t i = 0; i + (size_t)trailing < rest.size(); ++i) name += (i ? " " : "") + rest[i];
if (name.empty()) name = rest.empty() ? "PTN" : rest.front();
return {name, hasLength};
}
/** Which block ordinals get one of the [slots] patterns: on-roll blocks first. */
std::set<int> blocksToKeep(const std::vector<Tokens> &lines, size_t slots) {
std::vector<bool> onRoll;
for (const Tokens &tok : lines) {
if (tok[0] == "block") onRoll.push_back(false);
else if (tok[0] == "roll" && !onRoll.empty() && tok.size() > 1 && tok[1].find('#') != std::string::npos)
onRoll.back() = true;
}
std::vector<int> order;
for (size_t i = 0; i < onRoll.size(); ++i) if (onRoll[i]) order.push_back((int)i);
for (size_t i = 0; i < onRoll.size(); ++i) if (!onRoll[i]) order.push_back((int)i);
if (order.size() > slots) order.resize(slots);
return std::set<int>(order.begin(), order.end());
}
void applyStep(Pattern *block, int track, int trackChannel, const Tokens &tok) {
if (!block) return;
int tick;
if (!kt::toIntOrNull(tok[0], tick)) return;
if (tick < 0 || tick >= block->length || tick >= (int)block->tracks[track].size()) return;
Cell &c = block->tracks[track][tick];
c.note = pitchParse(tok.size() > 1 ? tok[1] : "...");
int v;
c.velocity = std::clamp(tok.size() > 2 && tok[2] != ".." && kt::toIntOrNull(tok[2], v, 16) ? v : (int)Cell::MAX_VELOCITY,
0, (int)Cell::MAX_VELOCITY);
c.channel = std::clamp(tok.size() > 3 && tok[3] != ".." && kt::toIntOrNull(tok[3], v) ? v : trackChannel,
1, (int)Cell::MAX_CHANNEL);
}
} // namespace
model::Project &SngFormat::importInto(Project &project, const std::string &text) {
// Clear blocks and arrangement (keep the lane-blocks, wipe their cells).
for (Pattern &p : project.patterns)
for (auto &track : p.tracks)
for (Cell &c : track) c.clear();
for (auto &lane : project.arrangement.slots) std::fill(lane.begin(), lane.end(), Arrangement::EMPTY);
project.arrangement.laneMuted.fill(false);
std::vector<Tokens> lines;
for (const std::string &raw : kt::lines(text)) {
const std::string line = kt::trim(raw);
if (line.empty() || line[0] == '#') continue;
lines.push_back(splitWhitespace(line));
}
const std::set<int> keep = blocksToKeep(lines, project.patterns.size());
int blockOrdinal = -1; // index of the block in the file
size_t nextPattern = 0; // next free pattern (lane) to fill
Pattern *current = nullptr;
int track = -1, trackChannel = 1;
bool usedTracks[Pattern::TRACK_COUNT] = {};
size_t maxRoll = 0;
for (const Tokens &tok : lines) {
const std::string &k = tok[0];
if (k == "version" || k == "group" || k == "scale" || k == "root" || k == "kind" || k == "intro") {
} else if (k == "bpm") {
float f;
if (tok.size() > 1 && kt::toFloatOrNull(tok[1], f) && std::isfinite(f))
project.tempoBpm = std::clamp(f, 20.f, 300.f);
} else if (k == "sig") {
int n = 0;
const bool ok = tok.size() > 1 && kt::toIntOrNull(tok[1], n);
project.timeSignature = ok && n == 3 ? TimeSignature::THREE_FOUR
: ok && n == 5 ? TimeSignature::FIVE_FOUR : TimeSignature::FOUR_FOUR;
} else if (k == "loop") {
if (tok.size() >= 3) project.arrangement.loopEnabled = true;
} else if (k == "block") {
blockOrdinal++;
current = nullptr;
if (keep.count(blockOrdinal)) {
const size_t n = nextPattern++;
if (n < project.patterns.size()) current = &project.patterns[n];
}
if (current) {
int length = 0;
auto [name, hasLength] = blockHeader(tok, length);
current->name = name;
if (hasLength) current->resize(std::clamp(length, 1, MAX_BLOCK_LENGTH));
}
track = -1; trackChannel = 1;
std::fill(std::begin(usedTracks), std::end(usedTracks), false);
} else if (k == "roll") {
if (current) {
const std::string roll = tok.size() > 1 ? tok[1] : "";
const int id = current->id;
kt::forEachIndexed(roll, [&](size_t beat, unsigned ch) {
if (beat > (size_t)Arrangement::MAX_BEATS) return;
if (ch == '#') project.arrangement.set(id, (int)beat, id);
else if (ch == 'x') project.arrangement.set(id, (int)beat, Arrangement::NOTE_OFF);
});
maxRoll = std::max(maxRoll, kt::utf16Length(roll));
}
} else if (k == "track") {
int wanted = -1;
bool hasWanted = false;
if (const std::string *name = at(tok, 1)) {
std::string digits; // filter { it.isDigit() }
size_t i = 0;
while (i < name->size()) {
const size_t from = i;
const unsigned cp = kt::decodeUtf8(*name, i);
if (kt::decimalDigit(cp) >= 0) digits.append(*name, from, i - from);
}
hasWanted = kt::toIntOrNull(digits, wanted);
if (hasWanted) wanted -= 1; // digits only: wanted >= 0, no overflow
}
if (hasWanted && wanted >= 0 && wanted < Pattern::TRACK_COUNT && !usedTracks[wanted]) {
track = wanted;
} else {
track = -1;
for (int t = 0; t < Pattern::TRACK_COUNT; ++t) if (!usedTracks[t]) { track = t; break; }
}
if (track >= 0) usedTracks[track] = true;
int ch;
trackChannel = tok.size() > 2 && kt::toIntOrNull(tok[2], ch)
? std::clamp((int)(int32_t)((uint32_t)ch + 1u), 1, 16) : 1;
} else if (k == "endblock") {
current = nullptr; track = -1;
} else if (track >= 0) {
applyStep(current, track, trackChannel, tok);
}
}
// Grow the canvas (in bars) if the imported roll is longer than the default.
if (maxRoll > 0) {
const long beatsPerBar = info(project.timeSignature).beatsPerBar;
// Kotlin: (maxRoll + beatsPerBar - 1) / beatsPerBar in Int (a roll longer
// than Int.MAX_VALUE can't come from a String).
const long neededBars = ((long)maxRoll + beatsPerBar - 1) / beatsPerBar;
project.arrangement.lengthBars =
(int)std::min(std::max((long)project.arrangement.lengthBars, neededBars), (long)Arrangement::MAX_BARS);
}
project.activePatternId = 0;
return project;
}
} // namespace sizzle::io
+29
View File
@@ -0,0 +1,29 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of io/SngFormat.kt: the desktop sizzletracker `.sng` interchange format
// (musical data only: tempo, signature, blocks, rolls, steps).
#include <string>
#include "sizzle/Model.hpp"
namespace sizzle::io {
struct SngFormat {
/** Longest block accepted (the desktop tracker's bound). */
static constexpr int MAX_BLOCK_LENGTH = 1024;
static std::string exportText(const model::Project &project);
/** Cheap content sniff: does [text] look like a `.sng` at all? */
static bool looksLikeSng(const std::string &text);
/** Parse `.sng` [text] into the existing [project] (its blocks and arrangement
* are reset; mixer and toolbox are kept). */
static model::Project &importInto(model::Project &project, const std::string &text);
};
/** Pitch.name / Pitch.parse (model/Music.kt): "C-4" <-> 60, "OFF", "...". */
std::string pitchName(int midi);
int pitchParse(const std::string &text);
} // namespace sizzle::io