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
+112
View File
@@ -0,0 +1,112 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// AudioEngine.ChannelArp: per-(lane,track) arpeggiator. Notes are kept sorted
// ascending; the linear step sequence is octave-major (all chord notes in octave 0,
// then octave 1, ...), walked up / down / up-down / randomly by advance(). genStamp
// identifies the line whose chord this holds (the engine's lineTriggerGen).
#include <cstdint>
#include <cstring>
namespace sizzle::engine {
class ChannelArp {
public:
int velocity = 100;
double stepSamples = 0.0, samplesLeft = 0.0;
bool resetOnBar = false;
int genStamp = -1;
int noteCount() const { return noteCount_; }
/** Active while it holds at least one note. */
bool active() const { return noteCount_ > 0; }
/** Start a fresh chord on [note], resetting the phase to step 0. */
void startChord(int note, int vel, int octs, const char *modeStr, double stepSamp, bool resetBar) {
noteCount_ = 0; addNote(note); velocity = vel; octaves = clamp(octs, 1, 4);
mode = modeOf(modeStr);
stepSamples = stepSamp < 1.0 ? 1.0 : stepSamp; samplesLeft = stepSamples; step = 0; dir = 1;
resetOnBar = resetBar; pendingReset = false;
}
/** Replace the chord with [note] while keeping the running phase. */
void resetChord(int note, int vel, int octs, const char *modeStr, double stepSamp, bool resetBar) {
noteCount_ = 0; addNote(note); velocity = vel;
refresh(octs, modeStr, stepSamp, resetBar);
}
/** Add a note to the held chord (sorted ascending, de-duplicated). */
void addNote(int note) {
const int n = clamp(note, 0, 127);
int i = 0;
while (i < noteCount_ && notes[i] < n) i++;
if (i < noteCount_ && notes[i] == n) return;
if (noteCount_ >= MAX_CHORD) return;
for (int j = noteCount_; j >= i + 1; --j) notes[j] = notes[j - 1];
notes[i] = n; noteCount_++;
}
/** Update params without resetting the running phase. */
void refresh(int octs, const char *modeStr, double stepSamp, bool resetBar) {
octaves = clamp(octs, 1, 4);
mode = modeOf(modeStr);
stepSamples = stepSamp < 1.0 ? 1.0 : stepSamp;
resetOnBar = resetBar;
}
void resetToBar() { step = 0; dir = 1; samplesLeft = 0.0; pendingReset = true; }
bool consumePendingReset() { bool p = pendingReset; pendingReset = false; return p; }
void stop() { noteCount_ = 0; genStamp = -1; }
int currentNote() const {
if (noteCount_ <= 0) return 0;
const int idx = clamp(step, 0, total() - 1);
const int oct = idx / noteCount_;
return clamp(notes[idx % noteCount_] + 12 * oct, 0, 127);
}
void advance() {
const int t = total();
switch (mode) {
case 1: step = (step - 1 + t) % t; break;
case 2:
if (t > 1) {
step += dir;
if (step >= t - 1) { step = t - 1; dir = -1; }
else if (step <= 0) { step = 0; dir = 1; }
}
break;
case 3: step = t > 1 ? rnd(t) : 0; break;
default: step = (step + 1) % t; break;
}
}
private:
static constexpr int MAX_CHORD = 8;
static int clamp(int v, int lo, int hi) { return v < lo ? lo : (v > hi ? hi : v); }
static int modeOf(const char *m) {
if (std::strcmp(m, "Down") == 0) return 1;
if (std::strcmp(m, "UpDown") == 0) return 2;
if (std::strcmp(m, "Random") == 0) return 3;
return 0;
}
int total() const { int t = noteCount_ * octaves; return t < 1 ? 1 : t; }
int rnd(int bound) {
uint32_t s = rng;
s ^= s << 13; s ^= s >> 17; s ^= s << 5;
rng = s;
return (int)(s % (uint32_t)bound);
}
int notes[MAX_CHORD] = {};
int noteCount_ = 0;
int octaves = 1, mode = 0;
int step = 0, dir = 1;
bool pendingReset = false;
uint32_t rng = 0x2545F491u;
};
} // namespace sizzle::engine
File diff suppressed because it is too large Load Diff
+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
+348 -34
View File
@@ -4,8 +4,8 @@
#include "sizzle/Model.hpp"
#include <algorithm>
#include <charconv>
#include <cmath>
#include <cstdint>
#include <cstring>
#include "sizzle/Specs.hpp"
@@ -49,6 +49,9 @@ int Arrangement::canvasBeats(TimeSignature sig) const {
}
int Arrangement::patternAt(int lane, int beat) const {
// Kotlin throws for a lane outside 0..7 (a block id from a hand-edited file can
// be anything); here that reads as empty instead of out of bounds.
if (lane < 0 || lane >= LANE_COUNT) return EMPTY;
return beat >= 0 && beat < MAX_BEATS ? slots[lane][beat] : EMPTY;
}
@@ -91,7 +94,12 @@ void ToolboxSlot::fill(const std::string &newType) {
}
void ToolboxSlot::clearSlot() { type.clear(); name.clear(); values = Params(); ++version; }
void ToolboxSlot::set(const char *key, float v) { values.set(key, kotlinFloatToString(v).c_str()); ++version; }
void ToolboxSlot::set(const char *key, float v) {
char buf[KOTLIN_FLOAT_CHARS]; // no allocation: the engine calls this per block
kotlinFloatToChars(v, buf);
values.set(key, buf);
++version;
}
void ToolboxSlot::set(const char *key, const char *v) { values.set(key, v); ++version; }
Project::Project() {
@@ -113,39 +121,345 @@ Pattern &Project::activePattern() {
return p ? *p : patterns.front();
}
// Shortest round-trip digits in Java's layout: plain for 1e-3 <= |v| < 1e7
// ("120.0", "0.8"), else computerized scientific ("1.0E-4", "1.2345678E7").
// JDK 17's FloatingDecimal is not always shortest; the file-format port pins it
// down against the reference files.
std::string kotlinFloatToString(float v) {
if (std::isnan(v)) return "NaN";
if (std::isinf(v)) return v > 0 ? "Infinity" : "-Infinity";
if (v == 0.f) return std::signbit(v) ? "-0.0" : "0.0";
char buf[64];
auto r = std::to_chars(buf, buf + sizeof buf, v, std::chars_format::scientific);
std::string sci(buf, r.ptr); // d.dddde±XX
size_t e = sci.find('e');
std::string mant = sci.substr(0, e);
int exp = std::stoi(sci.substr(e + 1));
bool neg = mant[0] == '-';
if (neg) mant.erase(0, 1);
std::string digits;
for (char c : mant) if (c != '.') digits += c;
std::string out;
float a = std::fabs(v);
if (a >= 1e-3f && a < 1e7f) {
if (exp >= 0) {
std::string ip = digits.substr(0, std::min<size_t>(digits.size(), (size_t)exp + 1));
while ((int)ip.size() < exp + 1) ip += '0';
std::string fp = (size_t)exp + 1 < digits.size() ? digits.substr((size_t)exp + 1) : "0";
out = ip + "." + fp;
} else {
out = "0." + std::string((size_t)(-exp - 1), '0') + digits;
}
} else {
out = digits.substr(0, 1) + "." + (digits.size() > 1 ? digits.substr(1) : "0") + "E" + std::to_string(exp);
// ---------------------------------------------------------------------------
// Kotlin's Float.toString: JDK 17's FloatingDecimal (BinaryToASCIIBuffer.dtoa with
// isCompatibleFormat = true, then getChars), ported line for line. It is not the
// shortest representation everywhere (e.g. 1.0E10f prints via the "insignificant
// digits" rounding, and the first digit's stopping test differs from later ones),
// which is why this is a port and not std::to_chars. Java int/long overflow wraps,
// so the arithmetic below is done in unsigned types and cast back.
// Checked against JDK 17.0.14 on all 2^32 float bit patterns when ported (an
// FNV hash per 2^20-pattern chunk, Java vs C++); core/tests/io_test.cpp keeps a sample.
namespace {
const int N_5_BITS[] = {0, 3, 5, 7, 10, 12, 14, 17, 19, 21, 24, 26, 28, 31, 33, 35, 38, 40, 42, 45, 47, 49, 52, 54, 56, 59, 61};
constexpr int N_5_BITS_LEN = 27;
constexpr int LONG_5_POW_LEN = 27;
const int insignificantDigitsNumber[] = {
0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7,
8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14,
15, 15, 15, 15, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19};
constexpr int EXP_SHIFT = 52, SINGLE_EXP_SHIFT = 23;
constexpr int MAX_SMALL_BIN_EXP = 62, MIN_SMALL_BIN_EXP = -(63 / 3);
int64_t long5pow(int i) { int64_t v = 1; while (i-- > 0) v *= 5; return v; }
int32_t small5pow(int i) { int32_t v = 1; while (i-- > 0) v *= 5; return v; }
int32_t wrap32(int64_t v) { return (int32_t)(uint32_t)(uint64_t)v; }
int64_t wrap64(uint64_t v) { return (int64_t)v; }
int insignificantDigitsForPow2(int p2) {
return p2 > 1 && p2 < (int)(sizeof insignificantDigitsNumber / sizeof(int)) ? insignificantDigitsNumber[p2] : 0;
}
// Exact non-negative big integer (FDBigInteger's role; its operations here are all
// exact, so plain schoolbook arithmetic gives the same numbers). Fixed capacity, no
// allocation: a float's B, S, M and 10S stay under 2^200 (denormals: S ~ 2^176).
struct Big {
static constexpr int CAP = 16;
uint32_t w[CAP] = {};
int n = 0; // used words, no leading zeros
static Big of(uint64_t v) { Big b; while (v && b.n < CAP) { b.w[b.n++] = (uint32_t)v; v >>= 32; } return b; }
void trim() { while (n > 0 && w[n - 1] == 0) --n; }
void mulSmall(uint32_t m) {
uint64_t carry = 0;
for (int i = 0; i < n; ++i) { uint64_t t = (uint64_t)w[i] * m + carry; w[i] = (uint32_t)t; carry = t >> 32; }
if (carry && n < CAP) w[n++] = (uint32_t)carry;
trim();
}
return neg ? "-" + out : out;
void mulPow5(int p5) { while (p5 >= 13) { mulSmall(1220703125u); p5 -= 13; } if (p5 > 0) mulSmall((uint32_t)small5pow(p5)); }
void shl(int s) {
if (n == 0 || s <= 0) return;
int words = s / 32, bits = s % 32;
if (n + words + 1 > CAP) words = CAP - n - 1; // unreachable for floats
if (bits) {
uint32_t carry = 0;
for (int i = 0; i < n; ++i) { uint32_t nx = (w[i] << bits) | carry; carry = w[i] >> (32 - bits); w[i] = nx; }
if (carry) w[n++] = carry;
}
if (words > 0) {
for (int i = n - 1; i >= 0; --i) w[i + words] = w[i];
for (int i = 0; i < words; ++i) w[i] = 0;
n += words;
}
}
static Big pow52(int p5, int p2) { Big b = of(1); b.mulPow5(p5); b.shl(p2); return b; }
static int cmp(const Big &a, const Big &b) {
if (a.n != b.n) return a.n < b.n ? -1 : 1;
for (int i = a.n; i-- > 0;)
if (a.w[i] != b.w[i]) return a.w[i] < b.w[i] ? -1 : 1;
return 0;
}
static Big add(const Big &a, const Big &b) {
Big r; uint64_t carry = 0;
int m = std::max(a.n, b.n);
for (int i = 0; i < m; ++i) {
uint64_t t = carry + (i < a.n ? a.w[i] : 0) + (i < b.n ? b.w[i] : 0);
r.w[i] = (uint32_t)t; carry = t >> 32;
}
r.n = m;
if (carry && r.n < CAP) r.w[r.n++] = (uint32_t)carry;
r.trim();
return r;
}
void sub(const Big &b) { // requires *this >= b
int64_t borrow = 0;
for (int i = 0; i < n; ++i) {
int64_t t = (int64_t)w[i] - (i < b.n ? b.w[i] : 0) - borrow;
borrow = t < 0; if (t < 0) t += (int64_t)1 << 32;
w[i] = (uint32_t)t;
}
trim();
}
/** quoRemIteration: q = this / s (< 10), this = (this % s) * 10. */
int quoRem(const Big &s) {
int q = 0;
while (q < 10 && cmp(*this, s) >= 0) { sub(s); ++q; }
mulSmall(10);
return q;
}
};
struct FloatDigits {
char digits[20];
int firstDigitIndex = 0, nDigits = 0, decExponent = 0;
void developLongDigits(int decExp, int64_t lvalue, int insignificant) {
if (insignificant != 0) {
int64_t pow10 = long5pow(insignificant) << insignificant;
int64_t residue = lvalue % pow10;
lvalue /= pow10;
decExp += insignificant;
if (residue >= (pow10 >> 1)) lvalue++;
}
int digitno = 19, c;
c = (int)(lvalue % 10); lvalue /= 10;
while (c == 0) { decExp++; c = (int)(lvalue % 10); lvalue /= 10; }
while (lvalue != 0) { digits[digitno--] = (char)(c + '0'); decExp++; c = (int)(lvalue % 10); lvalue /= 10; }
digits[digitno] = (char)(c + '0');
decExponent = decExp + 1;
firstDigitIndex = digitno;
nDigits = 20 - digitno;
}
void roundup() {
int i = firstDigitIndex + nDigits - 1;
int q = digits[i];
if (q == '9') {
while (q == '9' && i > firstDigitIndex) { digits[i] = '0'; q = digits[--i]; }
if (q == '9') { decExponent += 1; digits[firstDigitIndex] = '1'; return; }
}
digits[i] = (char)(q + 1);
}
static int estimateDecExp(int64_t fractBits, int binExp) {
const uint64_t SIGNIF = 0x000FFFFFFFFFFFFFull, EXPMASK = 0x7FF0000000000000ull, EXP_ONE = 0x3FF0000000000000ull;
uint64_t b2 = EXP_ONE | ((uint64_t)fractBits & SIGNIF);
double d2; std::memcpy(&d2, &b2, 8);
double d = (d2 - 1.5) * 0.289529654 + 0.176091259 + (double)binExp * 0.301029995663981;
uint64_t dBits; std::memcpy(&dBits, &d, 8);
int exponent = (int)((dBits & EXPMASK) >> EXP_SHIFT) - 1023;
bool isNegative = (dBits >> 63) != 0;
if (exponent >= 0 && exponent < 52) {
uint64_t mask = SIGNIF >> exponent;
int r = (int)(((dBits & SIGNIF) | (1ull << 52)) >> (EXP_SHIFT - exponent));
return isNegative ? (((mask & dBits) == 0) ? -r : -r - 1) : r;
} else if (exponent < 0) {
return ((dBits & ~(1ull << 63)) == 0) ? 0 : (isNegative ? -1 : 0);
} else {
return (int)d;
}
}
void dtoa(int binExp, int64_t fractBits, int nSignificantBits) {
const bool isCompatibleFormat = true;
const int tailZeros = __builtin_ctzll((uint64_t)fractBits);
const int nFractBits = EXP_SHIFT + 1 - tailZeros;
int nTinyBits = std::max(0, nFractBits - binExp - 1);
if (binExp <= MAX_SMALL_BIN_EXP && binExp >= MIN_SMALL_BIN_EXP) {
if (nTinyBits < LONG_5_POW_LEN && (nFractBits + N_5_BITS[nTinyBits]) < 64) {
if (nTinyBits == 0) {
int insignificant = binExp > nSignificantBits ? insignificantDigitsForPow2(binExp - nSignificantBits - 1) : 0;
if (binExp >= EXP_SHIFT) fractBits = wrap64((uint64_t)fractBits << (binExp - EXP_SHIFT));
else fractBits = (int64_t)((uint64_t)fractBits >> (EXP_SHIFT - binExp));
developLongDigits(0, fractBits, insignificant);
return;
}
}
}
int decExp = estimateDecExp(fractBits, binExp);
int B5 = std::max(0, -decExp);
int B2 = B5 + nTinyBits + binExp;
int S5 = std::max(0, decExp);
int S2 = S5 + nTinyBits;
int M5 = B5;
int M2 = B2 - nSignificantBits;
fractBits = (int64_t)((uint64_t)fractBits >> tailZeros);
B2 -= nFractBits - 1;
int common2factor = std::min(B2, S2);
B2 -= common2factor; S2 -= common2factor; M2 -= common2factor;
if (nFractBits == 1) M2 -= 1;
if (M2 < 0) { B2 -= M2; S2 -= M2; M2 = 0; }
int ndigit = 0;
bool low, high;
int64_t lowDigitDifference;
int q;
int Bbits = nFractBits + B2 + (B5 < N_5_BITS_LEN ? N_5_BITS[B5] : B5 * 3);
int tenSbits = S2 + 1 + ((S5 + 1) < N_5_BITS_LEN ? N_5_BITS[S5 + 1] : (S5 + 1) * 3);
if (Bbits < 64 && tenSbits < 64) {
if (Bbits < 32 && tenSbits < 32) {
int32_t b = wrap32((int64_t)(uint32_t)((uint32_t)(int32_t)fractBits * (uint32_t)small5pow(B5)) << B2);
int32_t s = wrap32((int64_t)small5pow(S5) << S2);
int32_t m = wrap32((int64_t)small5pow(M5) << M2);
int32_t tens = wrap32((int64_t)s * 10);
q = b / s;
b = wrap32((int64_t)10 * (b % s));
m = wrap32((int64_t)m * 10);
low = b < m;
high = wrap32((int64_t)b + m) > tens;
if (q == 0 && !high) decExp--;
else digits[ndigit++] = (char)('0' + q);
if (!isCompatibleFormat || decExp < -3 || decExp >= 8) high = low = false;
while (!low && !high) {
q = b / s;
b = wrap32((int64_t)10 * (b % s));
m = wrap32((int64_t)m * 10);
if (m > 0) { low = b < m; high = wrap32((int64_t)b + m) > tens; }
else { low = true; high = true; }
digits[ndigit++] = (char)('0' + q);
}
// Java: (b<<1) - tens in int arithmetic, widened to long afterwards.
lowDigitDifference = (int64_t)wrap32((int64_t)wrap32((int64_t)b * 2) - (int64_t)tens);
} else {
int64_t b = wrap64((uint64_t)fractBits * (uint64_t)long5pow(B5) << B2);
int64_t s = wrap64((uint64_t)long5pow(S5) << S2);
int64_t m = wrap64((uint64_t)long5pow(M5) << M2);
int64_t tens = wrap64((uint64_t)s * 10u);
q = (int)(b / s);
b = wrap64(10u * (uint64_t)(b % s));
m = wrap64((uint64_t)m * 10u);
low = b < m;
high = wrap64((uint64_t)b + (uint64_t)m) > tens;
if (q == 0 && !high) decExp--;
else digits[ndigit++] = (char)('0' + q);
if (!isCompatibleFormat || decExp < -3 || decExp >= 8) high = low = false;
while (!low && !high) {
q = (int)(b / s);
b = wrap64(10u * (uint64_t)(b % s));
m = wrap64((uint64_t)m * 10u);
if (m > 0) { low = b < m; high = wrap64((uint64_t)b + (uint64_t)m) > tens; }
else { low = true; high = true; }
digits[ndigit++] = (char)('0' + q);
}
lowDigitDifference = wrap64(((uint64_t)b << 1) - (uint64_t)tens);
}
} else {
// FDBigInteger path. Its normalization shift scales B, S, M and 10S alike,
// so it changes no quotient or comparison and is left out here.
Big Sval = Big::pow52(S5, S2);
Big Bval = Big::of((uint64_t)fractBits); Bval.mulPow5(B5); Bval.shl(B2);
Big Mval = Big::pow52(M5 + 1, M2 + 1);
Big tenSval = Big::pow52(S5 + 1, S2 + 1);
q = Bval.quoRem(Sval);
low = Big::cmp(Bval, Mval) < 0;
high = Big::cmp(tenSval, Big::add(Bval, Mval)) <= 0;
if (q == 0 && !high) decExp--;
else digits[ndigit++] = (char)('0' + q);
if (!isCompatibleFormat || decExp < -3 || decExp >= 8) high = low = false;
while (!low && !high) {
q = Bval.quoRem(Sval);
Mval.mulSmall(10);
low = Big::cmp(Bval, Mval) < 0;
high = Big::cmp(tenSval, Big::add(Bval, Mval)) <= 0;
digits[ndigit++] = (char)('0' + q);
}
if (high && low) { Bval.shl(1); lowDigitDifference = Big::cmp(Bval, tenSval); }
else lowDigitDifference = 0;
}
decExponent = decExp + 1;
firstDigitIndex = 0;
nDigits = ndigit;
if (high) {
if (low) {
if (lowDigitDifference == 0) { if ((digits[firstDigitIndex + nDigits - 1] & 1) != 0) roundup(); }
else if (lowDigitDifference > 0) roundup();
} else {
roundup();
}
}
}
/** getChars: writes at most 26 chars + NUL into out, returns the length. */
int chars(bool isNegative, char *out) const {
int i = 0;
if (isNegative) out[i++] = '-';
const char *d = digits + firstDigitIndex;
auto put = [&](const char *src, int len) { std::memcpy(out + i, src, (size_t)len); i += len; };
if (decExponent > 0 && decExponent < 8) {
int charLength = std::min(nDigits, decExponent);
put(d, charLength);
if (charLength < decExponent) {
for (int k = 0; k < decExponent - charLength; ++k) out[i++] = '0';
out[i++] = '.'; out[i++] = '0';
} else {
out[i++] = '.';
if (charLength < nDigits) put(d + charLength, nDigits - charLength);
else out[i++] = '0';
}
} else if (decExponent <= 0 && decExponent > -3) {
out[i++] = '0'; out[i++] = '.';
for (int k = 0; k < -decExponent; ++k) out[i++] = '0';
put(d, nDigits);
} else {
out[i++] = d[0];
out[i++] = '.';
if (nDigits > 1) put(d + 1, nDigits - 1);
else out[i++] = '0';
out[i++] = 'E';
int e;
if (decExponent <= 0) { out[i++] = '-'; e = -decExponent + 1; }
else e = decExponent - 1;
if (e <= 9) out[i++] = (char)(e + '0');
else if (e <= 99) { out[i++] = (char)(e / 10 + '0'); out[i++] = (char)(e % 10 + '0'); }
else { out[i++] = (char)(e / 100 + '0'); e %= 100; out[i++] = (char)(e / 10 + '0'); out[i++] = (char)(e % 10 + '0'); }
}
out[i] = '\0';
return i;
}
};
} // namespace
int kotlinFloatToChars(float f, char *out) {
auto lit = [&](const char *t) { int n = (int)std::strlen(t); std::memcpy(out, t, (size_t)n + 1); return n; };
uint32_t fBits; std::memcpy(&fBits, &f, 4);
bool isNegative = (fBits & 0x80000000u) != 0;
int32_t fractBits = (int32_t)(fBits & 0x007FFFFFu);
int binExp = (int)((fBits & 0x7F800000u) >> SINGLE_EXP_SHIFT);
if (binExp == 0xFF) return lit(fractBits == 0 ? (isNegative ? "-Infinity" : "Infinity") : "NaN");
int nSignificantBits;
if (binExp == 0) {
if (fractBits == 0) return lit(isNegative ? "-0.0" : "0.0");
int leadingZeros = __builtin_clz((uint32_t)fractBits);
int shift = leadingZeros - (31 - SINGLE_EXP_SHIFT);
fractBits <<= shift;
binExp = 1 - shift;
nSignificantBits = 32 - leadingZeros;
} else {
fractBits |= 1 << SINGLE_EXP_SHIFT;
nSignificantBits = SINGLE_EXP_SHIFT + 1;
}
binExp -= 127;
FloatDigits buf;
buf.dtoa(binExp, (int64_t)fractBits << (EXP_SHIFT - SINGLE_EXP_SHIFT), nSignificantBits);
return buf.chars(isNegative, out);
}
std::string kotlinFloatToString(float f) {
char buf[KOTLIN_FLOAT_CHARS];
int n = kotlinFloatToChars(f, buf);
return std::string(buf, (size_t)n);
}
} // namespace sizzle::model