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:
co-authored by
Claude Opus 5.5
parent
b1dc5ed8db
commit
7bc54e6466
@@ -3,6 +3,17 @@
|
||||
Sizzle for iOS/iPadOS (`cc.tiredsysadmin.ios.sizzle`). One entry per version in
|
||||
`../versions.properties` (`ios.versionName` / `ios.versionCode`).
|
||||
|
||||
## 0.3.1 (build 7)
|
||||
|
||||
- Fix: a sample loaded into the Sampler or the SF2/XI loader stayed silent. Its
|
||||
id (file name plus a unique suffix) was longer than the 31 characters a setting
|
||||
could hold, so the stored id was cut and matched nothing. Settings now hold up
|
||||
to 255 characters (file paths too).
|
||||
- Under the hood (not used by the app yet): the song model, the project / .sng /
|
||||
preset file formats and the sequencer-and-mixer engine in C++, checked against
|
||||
the Android app (four whole songs render the same; files round-trip byte for
|
||||
byte).
|
||||
|
||||
## 0.3.0 (build 6)
|
||||
|
||||
- Plugin editors like the Android app's: tabs of titled cards tinted by role,
|
||||
|
||||
+11
-1
@@ -70,10 +70,20 @@ build/core/sampler_test: $(CORE_SRC) $(CORE_HDR) core/tests/sampler_test.cpp
|
||||
mkdir -p build/core
|
||||
$(CXX) $(CXXFLAGS) -Icore/src/sampler -o $@ $(CORE_SRC) core/tests/sampler_test.cpp
|
||||
|
||||
core-test: build/core/golden_test build/core/sampler_test
|
||||
build/core/engine_test: $(CORE_SRC) $(CORE_HDR) core/tests/engine_test.cpp
|
||||
mkdir -p build/core
|
||||
$(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) core/tests/engine_test.cpp
|
||||
|
||||
build/core/io_test: $(CORE_SRC) $(CORE_HDR) core/tests/io_test.cpp
|
||||
mkdir -p build/core
|
||||
$(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) core/tests/io_test.cpp
|
||||
|
||||
core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/io_test
|
||||
@test -f $(GOLDEN)/input.f32 || $(MAKE) --no-print-directory golden
|
||||
build/core/golden_test $(GOLDEN) $(TYPES)
|
||||
build/core/sampler_test
|
||||
build/core/engine_test $(GOLDEN)/songs
|
||||
build/core/io_test $(GOLDEN)/songs ../app/src/test/resources/mikroseq
|
||||
|
||||
# ------------------------------------------------------------------ app
|
||||
AU_SRC := app/FX/SizzleDeviceAU.mm app/FX/SizzleEffectAU.mm app/FX/SizzleInstrumentAU.mm
|
||||
|
||||
@@ -84,6 +84,35 @@ All fourteen together come to about 38% of one core; the A8 has two. The C++ DSP
|
||||
cheap enough for the whole suite on this iPad. What made AUM struggle with a few
|
||||
AUv3s is the per-plugin process round trip, which the in-app host avoids.
|
||||
|
||||
- 2026-11-15: the engine (`core/src/engine`, `sizzle::engine::Engine`): AudioEngine.kt's
|
||||
sequencer, arrangement playlist with loop regions, note-offs, arpeggiator,
|
||||
transposer, MIDI LFO, mixer, FX chains and master limiter. `core/tests/engine_test`
|
||||
renders the four reference songs (demo, mix, waltz, midifx) and matches Kotlin
|
||||
(demo and midifx bit for bit; mix and waltz within 1e-5, from the Tape Engine's
|
||||
known one-ulp difference fed through the rest of the song). Not ported: audio
|
||||
output (the app calls `fillBlock`), WAV writing (`MasterSink`), CoreMIDI (the
|
||||
engine fills the outgoing queue, `pollMidiOut`), effect scope/playhead views.
|
||||
Decisions: the voice pools are built in AudioEngine's field order from
|
||||
`EngineGlobals` (clock and seed counters); swapped FX chains and playlists are
|
||||
freed by a later main-thread rebuild once the audio thread has finished a block;
|
||||
the live note calls touch voices directly like the Kotlin, so the app must call
|
||||
them on the audio thread (or serialise them with it). The MIDI LFO writes its
|
||||
value into the target slot as text every block, like Kotlin; that goes through
|
||||
`kotlinFloatToChars` (no allocation).
|
||||
|
||||
- 2026-11-16: file formats (`core/src/io`, `sizzle::io`): `ProjectIo` (.szg),
|
||||
`SngFormat` (.sng) and `PresetIo` (.szp), ported from io/*.kt with Kotlin's
|
||||
string semantics (`io/KotlinText`: lineSequence, Unicode trim, toIntOrNull with
|
||||
Unicode digits, toFloatOrNull with Java's parseFloat grammar). `core/tests/io_test`
|
||||
re-writes every reference file byte for byte, except [TOOLBOX] pairs (Kotlin
|
||||
writes ConcurrentHashMap order; compared as sets), and checks .szg -> .sng / .szp.
|
||||
`model::kotlinFloatToString` is JDK 17's FloatingDecimal ported line for line and
|
||||
was compared with JDK 17.0.14 on all 2^32 float bit patterns. Kotlin's own lossy
|
||||
spots, kept as is: PresetIo.import drops NAME (fill() overwrites it); a .sng
|
||||
`track` channel comes from the mixer, which import leaves alone; names with `;`,
|
||||
values with `,` or `=` break a [TOOLBOX] line. `Params` caps keys at 23 bytes,
|
||||
values at 31 and slots at 96 keys, so a long sample path would be cut short.
|
||||
|
||||
Notes for the engine port (from the voice ports):
|
||||
- Kotlin seeds every new FrasilVoice and GrainCloud from global counters, and every
|
||||
SynthVoice builds a FrasilVoice. The C++ engine owns one `frasil::FrasilSeeds`,
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
|
||||
// The sequencer and mixer engine: a port of audio/AudioEngine.kt (plus its
|
||||
// ChannelArp, the MIDI LFO, the transposer, the arrangement playlist with loop
|
||||
// regions, note-offs, mutes/solo, per-channel FX chains, the master limiter).
|
||||
// Checked against whole songs rendered by the Kotlin engine (core/tests/engine_test).
|
||||
//
|
||||
// Not here: the audio output (the app calls fillBlock from its AVAudioEngine
|
||||
// render callback), WAV writing for master recording (plug in a MasterSink),
|
||||
// CoreMIDI (the engine fills an outgoing MIDI queue; the app drains pollMidiOut).
|
||||
//
|
||||
// Threads, as in the Kotlin: setProject / play / pause / stop / rebuild* run on
|
||||
// the main thread, fillBlock on the audio thread (no allocation, no locks). The
|
||||
// live note calls (liveNoteOn, auditionSlotOn, busNoteOn, panic, ...) touch the
|
||||
// voices directly, as the Kotlin does: call them from the audio thread (e.g. drain
|
||||
// a queue before fillBlock) or otherwise serialise them with it.
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace sizzle::model {
|
||||
struct Project;
|
||||
}
|
||||
namespace sizzle::sampler {
|
||||
class SampleStore;
|
||||
}
|
||||
|
||||
namespace sizzle::engine {
|
||||
|
||||
/** TransportState.kt: where playback is, for the playhead. */
|
||||
struct TransportState {
|
||||
bool isPlaying = false;
|
||||
/** Absolute line index within the currently-playing pattern. */
|
||||
int currentLine = 0;
|
||||
/** Beat index within the arrangement. */
|
||||
int currentBeat = 0;
|
||||
};
|
||||
|
||||
/** Kotlin's process-wide voice state at the moment the engine is built: the Morph
|
||||
* Pad's shared clock (FrasilClock.seconds) and the seed counters every new
|
||||
* FrasilVoice / GrainCloud draws from. The defaults are a fresh process's. */
|
||||
struct EngineGlobals {
|
||||
double clockSeconds = 0.0;
|
||||
uint32_t frasilSeeds = 0x2545F491u;
|
||||
uint32_t grainSeeds = 0x1234567u;
|
||||
};
|
||||
|
||||
/** Where a master recording goes (MasterRecorder.kt, minus the file): begin() when
|
||||
* an armed take starts (false = can't record), write() per output frame on the
|
||||
* audio thread (must not block), endCapture() after the FX tail. */
|
||||
class MasterSink {
|
||||
public:
|
||||
virtual ~MasterSink() = default;
|
||||
virtual bool isActive() const = 0;
|
||||
virtual bool begin() = 0;
|
||||
virtual void write(float left, float right) = 0;
|
||||
virtual void endCapture() = 0;
|
||||
};
|
||||
|
||||
class Engine {
|
||||
public:
|
||||
static constexpr int BLOCK_FRAMES = 192; // the Kotlin's block (the MIDI LFO steps by it)
|
||||
static constexpr int POLYPHONY = 8;
|
||||
static constexpr int LIVE_POLYPHONY = 8;
|
||||
static constexpr int AUDITION_POLYPHONY = 8;
|
||||
static constexpr int BUS_POLYPHONY = 8;
|
||||
|
||||
/** [store]: where Sampler / SF2 / Grain Cloud samples are looked up (may be null:
|
||||
* no samples). Builds every voice in AudioEngine's order from [globals]. */
|
||||
explicit Engine(int sampleRate = 48000, sampler::SampleStore *store = nullptr,
|
||||
const EngineGlobals &globals = {});
|
||||
~Engine();
|
||||
Engine(const Engine &) = delete;
|
||||
Engine &operator=(const Engine &) = delete;
|
||||
|
||||
int sampleRate() const;
|
||||
|
||||
// ---- song (main thread)
|
||||
/** The song to play; it must outlive the engine or the next setProject. */
|
||||
void setProject(model::Project *p);
|
||||
/** Re-resolve each channel's FX slots into effect processors (routing changed). */
|
||||
void rebuildFxChains();
|
||||
/** Rebuild the arrangement playlist and reset the position. */
|
||||
void rebuildArrangement();
|
||||
/** Rebuild the playlist (loop region edits) without moving the position. */
|
||||
void refreshLoopPlaylist();
|
||||
|
||||
// ---- transport (main thread)
|
||||
void play(int startBeat = -1);
|
||||
void pause();
|
||||
/** Stop; if already stopped, rewind to the top. */
|
||||
void stop();
|
||||
/** Hard-silence every voice and cancel the arpeggiators. */
|
||||
void panic();
|
||||
TransportState transport() const;
|
||||
bool isPlaying() const;
|
||||
|
||||
// ---- audio thread
|
||||
/** Render [frames] interleaved stereo frames into [out] (frames * 2 floats). */
|
||||
void fillBlock(float *out, int frames);
|
||||
|
||||
// ---- live notes (see the thread note above)
|
||||
void liveNoteOn(int pitch, int velocity);
|
||||
void liveNoteOff(int pitch);
|
||||
void auditionSlotOn(int slotIndex, int midi);
|
||||
void auditionSlotOff(int midi);
|
||||
void busNoteOn(int midiChannel, int midi, int velocity);
|
||||
void busNoteOff(int midiChannel, int midi);
|
||||
/** For a MIDI trace: what busNoteOn would play (allocates; not for the audio thread). */
|
||||
std::string describeBusTargets(int midiChannel, int midi) const;
|
||||
|
||||
// ---- mixer meters (any thread, display only)
|
||||
float channelMeter(int ch) const;
|
||||
bool channelClipped(int ch) const;
|
||||
/** Effect visualisation isn't ported: always -1 (nothing to draw). */
|
||||
int effectScope(int slotIndex, float *out, int capacity) const;
|
||||
float effectPlayhead(int slotIndex) const;
|
||||
|
||||
// ---- outgoing MIDI: (status << 16) | (data1 << 8) | data2, or -1 when empty
|
||||
void setMidiOutEnabled(bool on);
|
||||
bool midiOutEnabled() const;
|
||||
int pollMidiOut();
|
||||
|
||||
// ---- master recording
|
||||
void setMasterSink(MasterSink *sink);
|
||||
void setRecordingArm(bool armed, int tailBars);
|
||||
void setRecordTailBars(int tailBars);
|
||||
bool recordArmed() const;
|
||||
void externalClockStart();
|
||||
void externalClockStop();
|
||||
|
||||
class Impl;
|
||||
|
||||
private:
|
||||
std::unique_ptr<Impl> impl;
|
||||
};
|
||||
|
||||
} // namespace sizzle::engine
|
||||
@@ -133,7 +133,7 @@ struct ToolboxSlot {
|
||||
void clearSlot();
|
||||
float f(const char *key, float fallback = 0.f) const { return values.f(key, fallback); }
|
||||
const char *s(const char *key, const char *fallback = "") const { return values.s(key, fallback); }
|
||||
void set(const char *key, float v); // stored as Kotlin's Float.toString text
|
||||
void set(const char *key, float v); // stored as Kotlin's Float.toString text (no allocation)
|
||||
void set(const char *key, const char *v);
|
||||
};
|
||||
|
||||
@@ -160,5 +160,10 @@ struct Project {
|
||||
/** Kotlin's Float.toString (JDK 17's algorithm), e.g. "120.0", "0.8", "1.0E-4":
|
||||
* what Android writes into settings and files. */
|
||||
std::string kotlinFloatToString(float v);
|
||||
/** Buffer size for kotlinFloatToChars (at most 26 chars + NUL). */
|
||||
inline constexpr int KOTLIN_FLOAT_CHARS = 32;
|
||||
/** The same text written into [out] (KOTLIN_FLOAT_CHARS bytes), NUL-terminated;
|
||||
* returns its length. No allocation: safe on the audio thread. */
|
||||
int kotlinFloatToChars(float v, char *out);
|
||||
|
||||
} // namespace sizzle::model
|
||||
|
||||
@@ -17,9 +17,9 @@ namespace sizzle {
|
||||
*/
|
||||
class Params {
|
||||
public:
|
||||
static constexpr int kMax = 96;
|
||||
static constexpr int kKeyLen = 24;
|
||||
static constexpr int kValLen = 32;
|
||||
static constexpr int kMax = 128;
|
||||
static constexpr int kKeyLen = 32;
|
||||
static constexpr int kValLen = 256; // sample ids and file paths
|
||||
|
||||
/** All of [spec]'s defaults, like ToolboxSlot.fill(). */
|
||||
void fill(const DeviceSpec &spec);
|
||||
|
||||
@@ -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
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// Renders the whole songs exported by IosGoldenSongs (Kotlin) through the C++
|
||||
// engine and compares with AudioEngine's output sample by sample:
|
||||
// Engine(sr) -> setProject -> play() -> fillBlock(buf, block) repeated.
|
||||
//
|
||||
// engine_test <golden dir>/songs [SONG ...]
|
||||
//
|
||||
// PASS when the largest difference over the whole render is below 1e-4. Prints the
|
||||
// max diff and the first sample (frame, channel) that differs by more than 1e-6.
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "echofield/GrainSources.hpp"
|
||||
#include "sampler/SampleStore.hpp"
|
||||
#include "sizzle/Engine.hpp"
|
||||
#include "sizzle/Model.hpp"
|
||||
#include "wavetable/WaveTables.hpp"
|
||||
|
||||
#if __has_include("io/ProjectIo.hpp")
|
||||
#include "io/ProjectIo.hpp"
|
||||
#define HAVE_PROJECT_IO 1
|
||||
#else
|
||||
#define HAVE_PROJECT_IO 0
|
||||
#endif
|
||||
|
||||
using namespace sizzle;
|
||||
|
||||
static std::vector<float> readF32(const std::string &path) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
std::vector<char> bytes((std::istreambuf_iterator<char>(f)), {});
|
||||
std::vector<float> out(bytes.size() / 4);
|
||||
std::memcpy(out.data(), bytes.data(), out.size() * 4);
|
||||
return out;
|
||||
}
|
||||
|
||||
static std::string readText(const std::string &path) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
return std::string((std::istreambuf_iterator<char>(f)), {});
|
||||
}
|
||||
|
||||
#if !HAVE_PROJECT_IO
|
||||
// TEMPORARY: a minimal ProjectIo.loadInto for the .szg fields the engine reads, until
|
||||
// core/src/io/ProjectIo.hpp exists (then the real loader is used automatically).
|
||||
namespace tmpio {
|
||||
static std::vector<std::string> split(const std::string &s, char c) {
|
||||
std::vector<std::string> out; std::string cur;
|
||||
for (char ch : s) { if (ch == c) { out.push_back(cur); cur.clear(); } else cur += ch; }
|
||||
out.push_back(cur);
|
||||
return out;
|
||||
}
|
||||
static std::string attr(const std::string &line, const std::string &key) {
|
||||
std::string inner = line.substr(1, line.size() - 2);
|
||||
for (const auto &tok : split(inner, ' ')) {
|
||||
size_t eq = tok.find('=');
|
||||
if (eq != std::string::npos && tok.substr(0, eq) == key) return tok.substr(eq + 1);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
static int toInt(const std::string &s, int fb) { try { return std::stoi(s); } catch (...) { return fb; } }
|
||||
static void region(model::LoopRegion &r, const std::string &line) {
|
||||
r.enabled = attr(line, "en") == "1";
|
||||
r.start = toInt(attr(line, "s"), 0);
|
||||
r.end = toInt(attr(line, "e"), 0);
|
||||
r.repeats = toInt(attr(line, "r"), 2);
|
||||
}
|
||||
static void loadInto(model::Project &p, const std::string &text) {
|
||||
p.patterns.clear();
|
||||
for (auto &lane : p.arrangement.slots) std::fill(lane.begin(), lane.end(), model::Arrangement::EMPTY);
|
||||
p.arrangement.laneMuted.fill(false);
|
||||
for (auto &s : p.toolbox) s.clearSlot();
|
||||
for (auto &ch : p.mixer.channels) {
|
||||
ch.instrumentSlot = -1; ch.fxSlots.fill(-1); ch.midiChannel = 0;
|
||||
ch.volume = 0.8f; ch.mute = ch.solo = ch.limiter = false;
|
||||
}
|
||||
std::string section;
|
||||
model::Pattern *cur = nullptr;
|
||||
std::istringstream in(text);
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
while (!line.empty() && (line.back() == '\r' || line.back() == ' ')) line.pop_back();
|
||||
if (line.empty() || line.rfind("SIZZLETRACKER", 0) == 0) continue;
|
||||
if (line.rfind("[PATTERN", 0) == 0) {
|
||||
p.patterns.emplace_back(toInt(attr(line, "id"), (int)p.patterns.size()), attr(line, "name"),
|
||||
toInt(attr(line, "len"), 16));
|
||||
cur = &p.patterns.back();
|
||||
section = "PATTERN";
|
||||
} else if (line.rfind("[ARRANGEMENT", 0) == 0) {
|
||||
p.arrangement.lengthBars = toInt(attr(line, "bars"), model::Arrangement::MAX_BARS);
|
||||
p.arrangement.loopEnabled = attr(line, "loop") == "1";
|
||||
std::string m = attr(line, "mutes");
|
||||
for (size_t i = 0; i < m.size() && i < p.arrangement.laneMuted.size(); ++i) p.arrangement.laneMuted[i] = m[i] == '1';
|
||||
section = "ARRANGEMENT";
|
||||
} else if (line.rfind("[REGION A", 0) == 0) region(p.arrangement.regionA, line);
|
||||
else if (line.rfind("[REGION B", 0) == 0) region(p.arrangement.regionB, line);
|
||||
else if (line.rfind("[MIXER]", 0) == 0) section = "MIXER";
|
||||
else if (line.rfind("[TOOLBOX]", 0) == 0) section = "TOOLBOX";
|
||||
else if (section.empty()) {
|
||||
size_t eq = line.find('=');
|
||||
if (eq == std::string::npos) continue;
|
||||
std::string k = line.substr(0, eq), v = line.substr(eq + 1);
|
||||
if (k == "NAME") p.name = v;
|
||||
else if (k == "TEMPO") p.tempoBpm = std::stof(v);
|
||||
else if (k == "SIG") {
|
||||
for (int i = 0; i < model::TIME_SIGNATURE_COUNT; ++i)
|
||||
if (v == model::info((model::TimeSignature)i).name) p.timeSignature = (model::TimeSignature)i;
|
||||
} else if (k == "ROOT") p.rootNote = toInt(v, 0);
|
||||
else if (k == "ACTIVE") p.activePatternId = toInt(v, 0);
|
||||
} else if (section == "PATTERN") {
|
||||
auto f = split(line, ',');
|
||||
if (f.size() < 5 || !cur) continue;
|
||||
int t = toInt(f[0], -1), ln = toInt(f[1], -1);
|
||||
if (t < 0 || t >= model::Pattern::TRACK_COUNT || ln < 0 || ln >= cur->length) continue;
|
||||
auto &c = cur->cell(t, ln);
|
||||
c.note = toInt(f[2], model::Cell::EMPTY);
|
||||
c.velocity = std::clamp(toInt(f[3], 127), 0, 127);
|
||||
c.channel = std::clamp(toInt(f[4], 1), 1, 16);
|
||||
} else if (section == "ARRANGEMENT") {
|
||||
auto f = split(line, ',');
|
||||
if (f.size() >= 3) p.arrangement.set(toInt(f[0], 0), toInt(f[1], 0), toInt(f[2], 0));
|
||||
} else if (section == "MIXER") {
|
||||
auto f = split(line, ',');
|
||||
if (f.size() < 10) continue;
|
||||
auto &ch = p.mixer.channels[toInt(f[0], 0)];
|
||||
ch.instrumentSlot = toInt(f[1], -1);
|
||||
for (int i = 0; i < 4; ++i) ch.fxSlots[i] = toInt(f[2 + i], -1);
|
||||
ch.midiChannel = toInt(f[6], 0);
|
||||
ch.volume = std::stof(f[7]);
|
||||
ch.mute = f[8] == "1"; ch.solo = f[9] == "1"; ch.limiter = f.size() > 10 && f[10] == "1";
|
||||
} else if (section == "TOOLBOX") {
|
||||
size_t eq = line.find('=');
|
||||
int idx = toInt(line.substr(0, eq), -1);
|
||||
auto parts = split(line.substr(eq + 1), ';');
|
||||
if (idx < 0 || idx >= model::Project::TOOLBOX_SLOTS || parts.size() < 2) continue;
|
||||
auto &slot = p.toolbox[idx];
|
||||
slot.fill(parts[0]);
|
||||
slot.name = parts[1];
|
||||
if (parts.size() >= 3 && !parts[2].empty())
|
||||
for (const auto &kv : split(parts[2], ',')) {
|
||||
size_t e = kv.find('=');
|
||||
if (e != std::string::npos) slot.set(kv.substr(0, e).c_str(), kv.substr(e + 1).c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int id = 0; id < model::Arrangement::LANE_COUNT; ++id) {
|
||||
bool has = false;
|
||||
for (auto &pt : p.patterns) has |= pt.id == id;
|
||||
if (!has) p.patterns.emplace_back(id, "BLK" + std::to_string(id + 1), 16);
|
||||
}
|
||||
std::sort(p.patterns.begin(), p.patterns.end(), [](const model::Pattern &a, const model::Pattern &b) { return a.id < b.id; });
|
||||
p.activePatternId = std::clamp(p.activePatternId, 0, (int)p.patterns.size() - 1);
|
||||
}
|
||||
} // namespace tmpio
|
||||
#endif
|
||||
|
||||
static void loadProject(model::Project &p, const std::string &text) {
|
||||
#if HAVE_PROJECT_IO
|
||||
io::ProjectIo::loadInto(p, text);
|
||||
#else
|
||||
tmpio::loadInto(p, text);
|
||||
#endif
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 2) { std::fprintf(stderr, "usage: %s <songs dir> [SONG ...]\n", argv[0]); return 2; }
|
||||
std::string dir = argv[1];
|
||||
std::vector<std::string> songs(argv + 2, argv + argc);
|
||||
if (songs.empty()) songs = {"demo", "mix", "waltz", "midifx"};
|
||||
wavetable::WaveTables::prewarmBlocking();
|
||||
echofield::GrainSources::prewarmBlocking();
|
||||
#if !HAVE_PROJECT_IO
|
||||
std::printf("note: io/ProjectIo.hpp not found, using the test's temporary .szg loader\n");
|
||||
#endif
|
||||
|
||||
int pass = 0, fail = 0;
|
||||
for (const auto &song : songs) {
|
||||
std::ifstream mf(dir + "/" + song + ".meta");
|
||||
if (!mf) { std::printf("FAIL %-10s no %s.meta\n", song.c_str(), song.c_str()); ++fail; continue; }
|
||||
int sr = 48000, block = 256;
|
||||
double seconds = 0;
|
||||
engine::EngineGlobals g;
|
||||
std::string sampleId;
|
||||
int smpRate = 0, loopStart = -1, loopEnd = -1;
|
||||
std::string line;
|
||||
while (std::getline(mf, line)) {
|
||||
std::istringstream ls(line);
|
||||
std::string tag; ls >> tag;
|
||||
if (tag == "sr") ls >> sr;
|
||||
else if (tag == "block") ls >> block;
|
||||
else if (tag == "seconds") ls >> seconds;
|
||||
else if (tag == "clock") { std::string v; ls >> v; g.clockSeconds = std::strtod(v.c_str(), nullptr); }
|
||||
else if (tag == "seeds") { long long f, gr; ls >> f >> gr; g.frasilSeeds = (uint32_t)f; g.grainSeeds = (uint32_t)gr; }
|
||||
else if (tag == "sample") ls >> sampleId >> smpRate >> loopStart >> loopEnd;
|
||||
}
|
||||
if (seconds <= 0) continue;
|
||||
|
||||
sampler::SampleStore store;
|
||||
if (!sampleId.empty())
|
||||
store.put(sampleId, Sample(readF32(dir + "/" + song + ".smp.f32"), smpRate, loopStart, loopEnd));
|
||||
|
||||
model::Project project;
|
||||
loadProject(project, readText(dir + "/" + song + ".szg"));
|
||||
|
||||
std::vector<float> want = readF32(dir + "/" + song + ".render.f32");
|
||||
const int frames = (int)(seconds * sr) / block * block;
|
||||
engine::Engine eng(sr, &store, g);
|
||||
eng.setProject(&project);
|
||||
eng.play();
|
||||
std::vector<float> buf((size_t)block * 2);
|
||||
double maxErr = (size_t)frames * 2 == want.size() ? 0 : 1e9;
|
||||
size_t maxAt = 0, firstAt = (size_t)-1;
|
||||
for (int b = 0; b < frames / block; ++b) {
|
||||
eng.fillBlock(buf.data(), block);
|
||||
for (int k = 0; k < block * 2; ++k) {
|
||||
const size_t i = (size_t)b * block * 2 + k;
|
||||
if (i >= want.size()) break;
|
||||
const double e = std::fabs((double)buf[k] - (double)want[i]);
|
||||
if (!(e <= maxErr)) { maxErr = e; maxAt = i; }
|
||||
if (firstAt == (size_t)-1 && !(e <= 1e-6)) firstAt = i;
|
||||
}
|
||||
}
|
||||
const bool ok = maxErr < 1e-4;
|
||||
std::printf("%s %-10s max diff %.3g at frame %zu", ok ? "PASS" : "FAIL", song.c_str(), maxErr, maxAt / 2);
|
||||
if (firstAt != (size_t)-1)
|
||||
std::printf(", first > 1e-6 at frame %zu ch %zu (%.3f s)", firstAt / 2, firstAt % 2, (double)(firstAt / 2) / sr);
|
||||
std::printf("\n");
|
||||
ok ? ++pass : ++fail;
|
||||
}
|
||||
std::printf("engine: %d passed, %d failed\n", pass, fail);
|
||||
return fail == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,565 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// core/src/io against files the Kotlin app wrote (core/golden/songs): every .szg,
|
||||
// .sng and .szp is parsed and written back byte for byte (a [TOOLBOX] line's
|
||||
// key=value pairs compared as a set: Kotlin writes them in ConcurrentHashMap
|
||||
// order; the two places where Kotlin itself doesn't round-trip are spelled out
|
||||
// below), .szg -> .sng and .szg -> .szp across formats, plus SngFormatTest,
|
||||
// SngMikroSeqImportTest, ProjectIoNameTest and ArrangementNoteOffTest translated,
|
||||
// Float.toString / toFloatOrNull samples (JDK 17.0.14's output) and malformed
|
||||
// input. Plain asserts; prints PASS/FAIL per check, exits non-zero on failure.
|
||||
//
|
||||
// build/core/io_test core/golden/songs ../app/src/test/resources/mikroseq
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <dirent.h>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "io/KotlinText.hpp"
|
||||
#include "io/PresetIo.hpp"
|
||||
#include "io/ProjectIo.hpp"
|
||||
#include "io/SngFormat.hpp"
|
||||
#include "sizzle/Model.hpp"
|
||||
#include "sizzle/Specs.hpp"
|
||||
|
||||
using namespace sizzle;
|
||||
using namespace sizzle::model;
|
||||
using io::PresetIo;
|
||||
using io::ProjectIo;
|
||||
using io::SngFormat;
|
||||
|
||||
namespace {
|
||||
|
||||
int failures = 0, passes = 0;
|
||||
bool current = true;
|
||||
|
||||
#define CHECK(c) do { if (!(c)) { std::printf(" check failed: %s (line %d)\n", #c, __LINE__); current = false; } } while (0)
|
||||
|
||||
void run(const std::string &name, const std::function<void()> &fn) {
|
||||
current = true;
|
||||
fn();
|
||||
std::printf("%s %s\n", current ? "PASS" : "FAIL", name.c_str());
|
||||
if (current) ++passes; else ++failures;
|
||||
}
|
||||
|
||||
bool readFile(const std::string &path, std::string &out) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
if (!f) return false;
|
||||
out.assign(std::istreambuf_iterator<char>(f), {});
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::string> listDir(const std::string &dir, const std::string &suffix) {
|
||||
std::vector<std::string> out;
|
||||
if (DIR *d = opendir(dir.c_str())) {
|
||||
while (dirent *e = readdir(d)) {
|
||||
std::string n = e->d_name;
|
||||
if (n.size() > suffix.size() && n.compare(n.size() - suffix.size(), suffix.size(), suffix) == 0) out.push_back(n);
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
std::sort(out.begin(), out.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
/** First differing line, for the failure message. */
|
||||
void reportDiff(const std::string &want, const std::string &got) {
|
||||
auto a = io::kt::split(want, '\n'), b = io::kt::split(got, '\n');
|
||||
for (size_t i = 0; i < std::max(a.size(), b.size()); ++i) {
|
||||
const std::string x = i < a.size() ? a[i] : "<none>", y = i < b.size() ? b[i] : "<none>";
|
||||
if (x != y) { std::printf(" line %zu\n want: %s\n got: %s\n", i + 1, x.c_str(), y.c_str()); return; }
|
||||
}
|
||||
}
|
||||
|
||||
bool sameBytes(const std::string &want, const std::string &got) {
|
||||
if (want == got) return true;
|
||||
reportDiff(want, got);
|
||||
return false;
|
||||
}
|
||||
|
||||
/** [TOOLBOX] lines with their key=value pairs sorted; everything else as is. */
|
||||
std::string normalizeToolbox(const std::string &text) {
|
||||
std::string out;
|
||||
bool toolbox = false;
|
||||
auto lines = io::kt::split(text, '\n');
|
||||
for (size_t i = 0; i < lines.size(); ++i) {
|
||||
std::string l = lines[i];
|
||||
if (toolbox && !l.empty()) {
|
||||
auto parts = io::kt::split(l, ';');
|
||||
if (parts.size() >= 3) {
|
||||
auto kv = io::kt::split(parts[2], ',');
|
||||
std::sort(kv.begin(), kv.end());
|
||||
std::string joined;
|
||||
for (size_t k = 0; k < kv.size(); ++k) joined += (k ? "," : "") + kv[k];
|
||||
l = parts[0] + ";" + parts[1] + ";" + joined;
|
||||
for (size_t k = 3; k < parts.size(); ++k) l += ";" + parts[k];
|
||||
}
|
||||
}
|
||||
if (l == "[TOOLBOX]") toolbox = true;
|
||||
out += l;
|
||||
if (i + 1 < lines.size()) out += '\n';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string noteNames(const Project &p, int n) {
|
||||
std::string s;
|
||||
for (int i = 0; i < n; ++i) s += (i ? "|" : "") + p.patterns[i].name;
|
||||
return s;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ reference files
|
||||
|
||||
void goldenFiles(const std::string &dir) {
|
||||
const auto szgs = listDir(dir, ".szg");
|
||||
run("reference files present (" + std::to_string(szgs.size()) + " songs)", [&] { CHECK(szgs.size() >= 5); });
|
||||
for (const std::string &f : szgs) {
|
||||
const std::string song = f.substr(0, f.size() - 4);
|
||||
std::string szg, sng;
|
||||
readFile(dir + "/" + f, szg);
|
||||
const bool haveSng = readFile(dir + "/" + song + ".sng", sng);
|
||||
|
||||
run(song + ".szg: load + save (toolbox pairs as sets)", [&] {
|
||||
Project p;
|
||||
ProjectIo::loadInto(p, szg);
|
||||
const std::string out = ProjectIo::save(p);
|
||||
CHECK(sameBytes(normalizeToolbox(szg), normalizeToolbox(out)));
|
||||
// Saving what was loaded again is byte-identical to our own first save.
|
||||
Project q;
|
||||
ProjectIo::loadInto(q, out);
|
||||
CHECK(sameBytes(out, ProjectIo::save(q)));
|
||||
});
|
||||
// A `track Tn <channel>` line's channel is the mixer channel's MIDI channel
|
||||
// minus one, and importInto leaves the mixer alone: into a fresh project
|
||||
// (mixer on channel 0) Kotlin writes 0 there too.
|
||||
run(song + ".sng: import into a fresh project + export (track channels -> 0)", [&] {
|
||||
CHECK(haveSng);
|
||||
Project p;
|
||||
SngFormat::importInto(p, sng);
|
||||
std::string want;
|
||||
for (const std::string &l : io::kt::split(sng, '\n')) {
|
||||
std::string x = l;
|
||||
if (io::kt::startsWith(l, "track ")) x = l.substr(0, l.rfind(' ')) + " 0";
|
||||
want += x + "\n";
|
||||
}
|
||||
want.pop_back();
|
||||
CHECK(sameBytes(want, SngFormat::exportText(p)));
|
||||
});
|
||||
run(song + ".sng: import into its own .szg project + export", [&] {
|
||||
Project p;
|
||||
ProjectIo::loadInto(p, szg);
|
||||
SngFormat::importInto(p, sng);
|
||||
CHECK(sameBytes(sng, SngFormat::exportText(p)));
|
||||
});
|
||||
run(song + ".szg -> .sng", [&] {
|
||||
Project p;
|
||||
ProjectIo::loadInto(p, szg);
|
||||
CHECK(sameBytes(sng, SngFormat::exportText(p)));
|
||||
});
|
||||
for (int slot = 0; slot < Project::TOOLBOX_SLOTS; ++slot) {
|
||||
std::string szp;
|
||||
if (!readFile(dir + "/" + song + ".slot" + std::to_string(slot) + ".szp", szp)) continue;
|
||||
const std::string tag = song + ".slot" + std::to_string(slot) + ".szp";
|
||||
// PresetIo.import applies NAME before fill(), which resets the name to
|
||||
// the device's display name: Kotlin loses a renamed slot's NAME too.
|
||||
run(tag + ": import + export (NAME -> display name)", [&] {
|
||||
ToolboxSlot s;
|
||||
CHECK(PresetIo::importText(s, szp));
|
||||
std::string want = szp;
|
||||
const size_t a = want.find("\nNAME="), z = want.find('\n', a + 1);
|
||||
CHECK(a != std::string::npos && z != std::string::npos);
|
||||
if (a != std::string::npos && z != std::string::npos)
|
||||
want.replace(a + 6, z - a - 6, findDevice(s.type.c_str())->displayName);
|
||||
CHECK(sameBytes(want, PresetIo::exportText(s)));
|
||||
if (want != szp) std::printf(" note: %s is named \"%s\", which import drops (as in Kotlin)\n",
|
||||
tag.c_str(), szp.substr(a + 6, z - a - 6).c_str());
|
||||
});
|
||||
run(song + ".szg -> " + tag, [&] {
|
||||
Project p;
|
||||
ProjectIo::loadInto(p, szg);
|
||||
CHECK(!p.toolbox[slot].isEmpty());
|
||||
CHECK(sameBytes(szp, PresetIo::exportText(p.toolbox[slot])));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------- SngFormatTest.kt
|
||||
|
||||
const char *kReference =
|
||||
"version 1\n"
|
||||
"bpm 120\n"
|
||||
"sig 4 4\n"
|
||||
"\n"
|
||||
"block A 16 4\n"
|
||||
"roll ####\n"
|
||||
"track T1 0\n"
|
||||
"0 C-4 64 01\n"
|
||||
"4 E-4 .. ..\n"
|
||||
"8 OFF .. ..\n"
|
||||
"endblock";
|
||||
|
||||
void sngFormatTest() {
|
||||
run("SngFormatTest.parsesReferenceExample", [] {
|
||||
Project p;
|
||||
SngFormat::importInto(p, kReference);
|
||||
CHECK(std::fabs(p.tempoBpm - 120.f) < 0.001f);
|
||||
CHECK(p.timeSignature == TimeSignature::FOUR_FOUR);
|
||||
const Pattern &block = p.patterns[0];
|
||||
CHECK(block.name == "A");
|
||||
CHECK(block.length == 16);
|
||||
const Cell &c0 = block.cell(0, 0);
|
||||
CHECK(c0.note == io::pitchParse("C-4"));
|
||||
CHECK(c0.velocity == 0x64);
|
||||
CHECK(c0.channel == 1);
|
||||
const Cell &c4 = block.cell(0, 4);
|
||||
CHECK(c4.note == io::pitchParse("E-4"));
|
||||
CHECK(c4.velocity == 0x7F);
|
||||
CHECK(c4.channel == 1);
|
||||
CHECK(block.cell(0, 8).isNoteOff());
|
||||
for (int beat = 0; beat <= 3; ++beat) CHECK(p.arrangement.patternAt(0, beat) != Arrangement::EMPTY);
|
||||
CHECK(p.arrangement.patternAt(0, 4) == Arrangement::EMPTY);
|
||||
});
|
||||
run("SngFormatTest.roundTripsNotesAndRoll", [] {
|
||||
Project p;
|
||||
p.tempoBpm = 140.f;
|
||||
p.timeSignature = TimeSignature::FIVE_FOUR;
|
||||
p.patterns[0].cell(0, 0) = Cell{60, 0x40, 3};
|
||||
p.patterns[0].cell(1, 5) = Cell{67, 0x7F, 2};
|
||||
p.arrangement.set(0, 0, 0);
|
||||
p.arrangement.set(0, 1, 0);
|
||||
Project restored;
|
||||
SngFormat::importInto(restored, SngFormat::exportText(p));
|
||||
CHECK(std::fabs(restored.tempoBpm - 140.f) < 0.001f);
|
||||
CHECK(restored.timeSignature == TimeSignature::FIVE_FOUR);
|
||||
const Cell &a = restored.patterns[0].cell(0, 0);
|
||||
CHECK(a.note == 60 && a.velocity == 0x40 && a.channel == 3);
|
||||
const Cell &b = restored.patterns[0].cell(1, 5);
|
||||
CHECK(b.note == 67 && b.velocity == 0x7F && b.channel == 2);
|
||||
CHECK(restored.arrangement.patternAt(0, 0) != Arrangement::EMPTY);
|
||||
CHECK(restored.arrangement.patternAt(0, 1) != Arrangement::EMPTY);
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------- SngMikroSeqImportTest.kt
|
||||
|
||||
void sngMikroSeqImportTest(const std::string &dir) {
|
||||
run("SngMikroSeqImportTest.fourFour", [&] {
|
||||
std::string text;
|
||||
CHECK(readFile(dir + "/sig44.sng", text));
|
||||
CHECK(SngFormat::looksLikeSng(text));
|
||||
Project p;
|
||||
SngFormat::importInto(p, text);
|
||||
CHECK(std::fabs(p.tempoBpm - 97.f) < 0.001f);
|
||||
CHECK(p.timeSignature == TimeSignature::FOUR_FOUR);
|
||||
CHECK(p.arrangement.loopEnabled);
|
||||
CHECK(noteNames(p, 4) == "C1|C1 muted|C2|C6");
|
||||
CHECK(p.patterns[0].length == 16 && p.patterns[1].length == 16 && p.patterns[2].length == 48 &&
|
||||
p.patterns[3].length == 64);
|
||||
const Pattern &c1 = p.patterns[0];
|
||||
CHECK(c1.cell(0, 0).note == io::pitchParse("C-2"));
|
||||
CHECK(c1.cell(0, 0).channel == 10);
|
||||
CHECK(c1.cell(0, 0).velocity == 0x6E);
|
||||
CHECK(c1.cell(0, 1).note == Cell::OFF);
|
||||
CHECK(c1.cell(2, 2).note == io::pitchParse("F#2"));
|
||||
const Pattern &c2 = p.patterns[2];
|
||||
CHECK(c2.cell(3, 0).note == io::pitchParse("B-1"));
|
||||
CHECK(c2.cell(3, 0).channel == 1);
|
||||
CHECK(c2.cell(3, 6).note == io::pitchParse("C#2"));
|
||||
CHECK(c2.cell(3, 9).note == Cell::OFF);
|
||||
CHECK(p.patterns[3].cell(0, 0).channel == 3);
|
||||
for (int lane : {0, 2, 3}) {
|
||||
CHECK(p.arrangement.patternAt(lane, 0) == lane);
|
||||
CHECK(p.arrangement.patternAt(lane, 95) == lane);
|
||||
CHECK(p.arrangement.patternAt(lane, 96) == Arrangement::EMPTY);
|
||||
}
|
||||
CHECK(p.arrangement.patternAt(1, 0) == Arrangement::EMPTY);
|
||||
CHECK(p.arrangement.lengthBars >= 24);
|
||||
});
|
||||
run("SngMikroSeqImportTest.threeFour", [&] {
|
||||
std::string text;
|
||||
CHECK(readFile(dir + "/sig34.sng", text));
|
||||
Project p;
|
||||
SngFormat::importInto(p, text);
|
||||
CHECK(p.timeSignature == TimeSignature::THREE_FOUR);
|
||||
CHECK(noteNames(p, 4) == "C1|C1 muted|C2|C6");
|
||||
CHECK(p.patterns[0].length == 12 && p.patterns[1].length == 12 && p.patterns[2].length == 36 &&
|
||||
p.patterns[3].length == 48);
|
||||
const Pattern &c1 = p.patterns[0];
|
||||
for (int step : {0, 3, 6, 9}) CHECK(c1.cell(0, step).note == io::pitchParse("C-2"));
|
||||
for (int step : {1, 4, 7, 10}) CHECK(c1.cell(0, step).note == Cell::OFF);
|
||||
CHECK(p.patterns[1].cell(1, 3).note == io::pitchParse("D-2"));
|
||||
const Pattern &c2 = p.patterns[2];
|
||||
CHECK(c2.cell(3, 5).note == io::pitchParse("C#2"));
|
||||
CHECK(c2.cell(3, 7).note == Cell::OFF);
|
||||
CHECK(c2.cell(3, 16).note == Cell::OFF);
|
||||
CHECK(p.arrangement.patternAt(2, 95) == 2);
|
||||
CHECK(p.arrangement.patternAt(2, 96) == Arrangement::EMPTY);
|
||||
CHECK(p.arrangement.lengthBars >= 96 / 3);
|
||||
});
|
||||
run("SngMikroSeqImportTest.moreBlocksThanLanesKeepsTheOnesOnTheRoll", [] {
|
||||
std::string text = "version 1\nbpm 120\nsig 4 4\n";
|
||||
for (int c = 1; c <= 8; ++c) {
|
||||
const std::string n = std::to_string(c);
|
||||
text += "block C" + n + " 16 1\nroll ####\ntrack T1 0\n0 C-4 64 ..\nendblock\n";
|
||||
text += "block C" + n + " muted 16 1\ntrack T2 0\n0 D-4 64 ..\nendblock\n";
|
||||
}
|
||||
Project p;
|
||||
SngFormat::importInto(p, text);
|
||||
CHECK(noteNames(p, 8) == "C1|C2|C3|C4|C5|C6|C7|C8");
|
||||
for (int lane = 0; lane < 8; ++lane) CHECK(p.arrangement.patternAt(lane, 0) == lane);
|
||||
});
|
||||
run("SngMikroSeqImportTest.trackNumbersBeyondFourTakeFreeSlotsAndExtraTracksAreDropped", [] {
|
||||
const char *text =
|
||||
"version 1\nblock A 16 6\ntrack T1 0\n0 C-4 .. ..\ntrack T7 1\n0 D-4 .. ..\ntrack T2 2\n0 E-4 .. ..\n"
|
||||
"track T9 3\n0 F-4 .. ..\ntrack T12 4\n0 G-4 .. ..\nendblock";
|
||||
Project p;
|
||||
const Pattern &b = SngFormat::importInto(p, text).patterns[0];
|
||||
CHECK(b.cell(0, 0).note == io::pitchParse("C-4"));
|
||||
CHECK(b.cell(1, 0).note == io::pitchParse("D-4"));
|
||||
CHECK(b.cell(2, 0).note == io::pitchParse("E-4"));
|
||||
CHECK(b.cell(3, 0).note == io::pitchParse("F-4"));
|
||||
for (int t = 0; t < 4; ++t) CHECK(b.cell(t, 0).note != io::pitchParse("G-4"));
|
||||
});
|
||||
run("SngMikroSeqImportTest.absurdBlockLengthIsBounded", [] {
|
||||
Project p;
|
||||
SngFormat::importInto(p, "version 1\nblock A 999999999 1\nendblock\n");
|
||||
CHECK(p.patterns[0].length == SngFormat::MAX_BLOCK_LENGTH);
|
||||
});
|
||||
run("SngMikroSeqImportTest.plainTextIsNotASong", [] {
|
||||
CHECK(!SngFormat::looksLikeSng("shopping list\nmilk\neggs"));
|
||||
CHECK(SngFormat::looksLikeSng("hello\n bpm 90"));
|
||||
CHECK(!SngFormat::looksLikeSng("versions 1\nblocked"));
|
||||
CHECK(SngFormat::looksLikeSng("x\r\nsig 4 4"));
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------- ProjectIoNameTest.kt
|
||||
|
||||
void projectIoNameTest() {
|
||||
run("ProjectIoNameTest.namesWithSpacesAndEscapesRoundTrip", [] {
|
||||
const std::vector<std::string> names = {"C1 muted", "50% ]x", "%20 literal", "plain"};
|
||||
Project p;
|
||||
for (size_t i = 0; i < names.size(); ++i) p.patterns[i].name = names[i];
|
||||
Project back;
|
||||
ProjectIo::loadInto(back, ProjectIo::save(p));
|
||||
for (size_t i = 0; i < names.size(); ++i) CHECK(back.patterns[i].name == names[i]);
|
||||
});
|
||||
run("ProjectIoNameTest.olderFilesWithoutEscapesLoadAsWritten", [] {
|
||||
CHECK(ProjectIo::decodeName("50%") == "50%");
|
||||
CHECK(ProjectIo::decodeName("C1") == "C1");
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------- ArrangementNoteOffTest.kt
|
||||
|
||||
Project projectWithMarker() {
|
||||
Project p;
|
||||
p.arrangement.set(0, 0, 0);
|
||||
p.arrangement.set(0, 1, Arrangement::NOTE_OFF);
|
||||
p.arrangement.set(0, 2, 0);
|
||||
return p;
|
||||
}
|
||||
|
||||
void arrangementNoteOffTest() {
|
||||
run("ArrangementNoteOffTest.markerSurvivesAProjectRoundTrip", [] {
|
||||
Project back;
|
||||
ProjectIo::loadInto(back, ProjectIo::save(projectWithMarker()));
|
||||
CHECK(back.arrangement.patternAt(0, 0) == 0);
|
||||
CHECK(back.arrangement.patternAt(0, 1) == Arrangement::NOTE_OFF);
|
||||
CHECK(back.arrangement.patternAt(0, 2) == 0);
|
||||
});
|
||||
run("ArrangementNoteOffTest.markerSurvivesAnSngRoundTrip", [] {
|
||||
const std::string text = SngFormat::exportText(projectWithMarker());
|
||||
CHECK(text.find("roll #x#") != std::string::npos);
|
||||
Project back;
|
||||
SngFormat::importInto(back, text);
|
||||
CHECK(back.arrangement.patternAt(0, 0) == 0);
|
||||
CHECK(back.arrangement.patternAt(0, 1) == Arrangement::NOTE_OFF);
|
||||
CHECK(back.arrangement.patternAt(0, 2) == 0);
|
||||
});
|
||||
run("ArrangementNoteOffTest.anUnknownRollCharacterReadsAsEmpty", [] {
|
||||
Project p;
|
||||
SngFormat::importInto(p, "version 1\nbpm 120\nsig 4 4\n\nblock A 4 4\nroll #?#\nendblock");
|
||||
CHECK(p.arrangement.patternAt(0, 0) == 0);
|
||||
CHECK(p.arrangement.patternAt(0, 1) == Arrangement::EMPTY);
|
||||
CHECK(p.arrangement.patternAt(0, 2) == 0);
|
||||
});
|
||||
run("ArrangementNoteOffTest.markerIsFilledButIsNotABlock", [] {
|
||||
Arrangement arr;
|
||||
arr.set(0, 5, Arrangement::NOTE_OFF);
|
||||
CHECK(arr.lastFilledBeat() == 5);
|
||||
CHECK(!arr.hasBlockAt(0, 5));
|
||||
CHECK(arr.patternAt(0, 5) != Arrangement::EMPTY);
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------- Kotlin text semantics
|
||||
|
||||
void kotlinSemantics() {
|
||||
run("Float.toString matches JDK 17.0.14 (sample; the port was swept over all 2^32 floats)", [] {
|
||||
const struct { uint32_t bits; const char *text; } cases[] = {
|
||||
{0x42f00000, "120.0"}, {0x3f4ccccd, "0.8"}, {0x38d1b717, "1.0E-4"}, {0x501502f9, "1.0E10"},
|
||||
{0x00800000, "1.17549435E-38"}, {0x00000001, "1.4E-45"}, {0x7f7fffff, "3.4028235E38"},
|
||||
{0x3a83126f, "0.001"}, {0x3a83126e, "9.999999E-4"}, {0x4b189680, "1.0E7"}, {0x4b18967f, "9999999.0"},
|
||||
{0x3eaaaaab, "0.33333334"}, {0x32abcc77, "2.0E-8"}, {0x3dcccccd, "0.1"}, {0x3f19999a, "0.6"},
|
||||
{0x80000000, "-0.0"}, {0x3727c5ac, "1.0E-5"}, {0x47f12065, "123456.79"}, {0x7f61b1e6, "3.0E38"},
|
||||
{0x0000025f, "8.5E-43"}, {0x6363aeb5, "4.2E21"}, {0x3ec99326, "0.39370078"}, {0x4b800000, "1.6777216E7"},
|
||||
{0x4c000001, "3.3554436E7"}, {0x7fc00000, "NaN"}, {0xff800000, "-Infinity"}, {0xbf4ccccd, "-0.8"},
|
||||
};
|
||||
for (const auto &c : cases) {
|
||||
float f; std::memcpy(&f, &c.bits, 4);
|
||||
const std::string got = kotlinFloatToString(f);
|
||||
if (got != c.text) std::printf(" %08x: want %s, got %s\n", c.bits, c.text, got.c_str());
|
||||
CHECK(got == c.text);
|
||||
}
|
||||
ToolboxSlot s;
|
||||
s.set("x", 0.8f);
|
||||
CHECK(std::string(s.s("x")) == "0.8");
|
||||
});
|
||||
run("toFloatOrNull follows Java's Float.parseFloat grammar", [] {
|
||||
const struct { const char *in; bool ok; uint32_t bits; } cases[] = {
|
||||
{"1e3f", true, 0x447a0000}, {" 0.5 ", true, 0x3f000000}, {"0x1p-2", true, 0x3e800000},
|
||||
{".5", true, 0x3f000000}, {"5.", true, 0x40a00000}, {"1e", false, 0}, {"abc", false, 0},
|
||||
{"+.5e-1D", true, 0x3d4ccccd}, {"0x.8p1", true, 0x3f800000}, {"-Infinity", true, 0xff800000},
|
||||
{"1_0", false, 0}, {"0x1p", false, 0}, {"1.0E-46", true, 0}, {"\xc2\xa0" "0.5", false, 0},
|
||||
{"3.4028236e38", true, 0x7f800000}, {"", false, 0}, {".", false, 0}, {"-", false, 0},
|
||||
};
|
||||
for (const auto &c : cases) {
|
||||
float f = 0;
|
||||
const bool ok = io::kt::toFloatOrNull(c.in, f);
|
||||
uint32_t bits; std::memcpy(&bits, &f, 4);
|
||||
if (ok != c.ok || (ok && bits != c.bits)) std::printf(" [%s]: got %d %08x\n", c.in, ok, bits);
|
||||
CHECK(ok == c.ok && (!ok || bits == c.bits));
|
||||
}
|
||||
float f = 0;
|
||||
CHECK(io::kt::toFloatOrNull("NaN", f) && std::isnan(f));
|
||||
});
|
||||
run("toIntOrNull, trim and lines follow Kotlin", [] {
|
||||
int v = 0;
|
||||
CHECK(io::kt::toIntOrNull("+5", v) && v == 5);
|
||||
CHECK(io::kt::toIntOrNull("-2147483648", v) && v == INT32_MIN);
|
||||
CHECK(!io::kt::toIntOrNull("2147483648", v));
|
||||
CHECK(!io::kt::toIntOrNull("-", v) && !io::kt::toIntOrNull("", v) && !io::kt::toIntOrNull(" 1", v));
|
||||
CHECK(io::kt::toIntOrNull("\xd9\xa4", v) && v == 4); // Arabic-Indic four
|
||||
CHECK(io::kt::toIntOrNull("7F", v, 16) && v == 127);
|
||||
CHECK(io::kt::toIntOrNull("\xef\xbc\xa6", v, 16) && v == 15); // fullwidth F
|
||||
CHECK(io::kt::trim("\xc2\xa0 x \xe3\x80\x80\t") == "x");
|
||||
auto l = io::kt::lines("a\r\nb\rc\n");
|
||||
CHECK(l.size() == 4 && l[0] == "a" && l[1] == "b" && l[2] == "c" && l[3].empty());
|
||||
CHECK(io::kt::hexUpper(-1) == "-1" && io::kt::hexUpper(0x6e) == "6E");
|
||||
CHECK(io::kt::floatToInt(NAN) == 0 && io::kt::floatToInt(1e20f) == INT32_MAX);
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------- tolerance and malformed input
|
||||
|
||||
void tolerance(const std::string &dir) {
|
||||
run("ProjectIo: missing sections and bad lines fall back like Kotlin", [] {
|
||||
Project p;
|
||||
p.name = "kept";
|
||||
ProjectIo::loadInto(p,
|
||||
"garbage line\nTEMPO=fast\nSIG=SEVEN_EIGHT\nSCALE=MAJOR\nACTIVE=99\n"
|
||||
"[PATTERN id=3 name=Hi%20there len=-4]\n" // negative length: Kotlin throws, line skipped
|
||||
"[PATTERN id=2 name=Two len=8]\n0,1,60,500,99\n9,1,60,1,1\n0,8,60,1,1\n0,2,x,y,z\n"
|
||||
"[MIXER]\n1,5,1,2,3,4,7,oops,1,0\n2,1\n"
|
||||
"[TOOLBOX]\n3=NOPE;x;\n4=FILTER;My;cutoff=0.3,bad,=v\n20=FILTER;x;\n");
|
||||
CHECK(p.name == "kept");
|
||||
CHECK(p.tempoBpm == 120.f);
|
||||
CHECK(p.timeSignature == TimeSignature::FOUR_FOUR);
|
||||
CHECK(p.scale == Scale::MAJOR);
|
||||
CHECK(p.activePatternId == 7); // coerced into 0..patterns.size-1
|
||||
CHECK(p.patterns.size() == 8);
|
||||
const Pattern *two = p.pattern(2);
|
||||
CHECK(two && two->name == "Two" && two->length == 8);
|
||||
CHECK(two && two->cell(0, 1).note == 60 && two->cell(0, 1).velocity == 127 && two->cell(0, 1).channel == 16);
|
||||
CHECK(two && two->cell(0, 2).note == Cell::EMPTY && two->cell(0, 2).channel == 1);
|
||||
CHECK(p.pattern(3) && p.pattern(3)->name == "BLK4" && p.pattern(3)->length == 16);
|
||||
CHECK(p.mixer.channels[1].instrumentSlot == 5 && p.mixer.channels[1].volume == 0.8f && p.mixer.channels[1].mute);
|
||||
CHECK(p.toolbox[3].isEmpty());
|
||||
CHECK(p.toolbox[4].type == "FILTER" && p.toolbox[4].name == "My" && std::string(p.toolbox[4].s("cutoff")) == "0.3");
|
||||
CHECK(std::string(p.toolbox[4].s("", "none")) == "v");
|
||||
});
|
||||
run("SngFormat: bpm clamps, unknown lines ignored, steps outside a block dropped", [] {
|
||||
Project p;
|
||||
SngFormat::importInto(p, "# c\nbpm 999\nsig 5 4\n0 C-4 7F 01\nblock\ntrack\n0 C-4 zz ..\n99 C-4 .. ..\nendblock\nbpm NaN");
|
||||
CHECK(p.tempoBpm == 300.f);
|
||||
CHECK(p.timeSignature == TimeSignature::FIVE_FOUR);
|
||||
CHECK(p.patterns[0].name == "PTN");
|
||||
CHECK(p.patterns[0].cell(0, 0).note == 60 && p.patterns[0].cell(0, 0).velocity == 127);
|
||||
});
|
||||
run("PresetIo: no TYPE fails, NAME is overwritten by fill, duplicates keep first position", [] {
|
||||
ToolboxSlot s;
|
||||
CHECK(!PresetIo::importText(s, "SIZZLE-PRESET 1\nNAME=x\ncutoff=0.2"));
|
||||
CHECK(s.isEmpty() && s.name == "x");
|
||||
CHECK(PresetIo::importText(s, "TYPE=FILTER\nNAME=Mine\nzz=1\ncutoff=0.2\nzz=2\nnot a line\n"));
|
||||
CHECK(s.type == "FILTER" && s.name == "Filter (LP/HP/BP)");
|
||||
CHECK(std::string(s.s("zz")) == "2" && std::string(s.s("cutoff")) == "0.2");
|
||||
const std::string out = PresetIo::exportText(s);
|
||||
CHECK(out.size() > 6 && out.compare(out.size() - 5, 5, "zz=2\n") == 0);
|
||||
CHECK(PresetIo::exportText(ToolboxSlot()) == "SIZZLE-PRESET 1\nTYPE=EMPTY");
|
||||
CHECK(!PresetIo::importText(s, "TYPE=FILTER\nTYPE=NOPE")); // a later bad TYPE wins
|
||||
});
|
||||
run("malformed input never crashes (mutated reference files)", [&] {
|
||||
std::vector<std::string> inputs;
|
||||
for (const char *ext : {".szg", ".sng", ".szp"})
|
||||
for (const auto &f : listDir(dir, ext)) { std::string t; readFile(dir + "/" + f, t); inputs.push_back(t); }
|
||||
uint32_t seed = 0x1234567;
|
||||
auto rnd = [&] { seed ^= seed << 13; seed ^= seed >> 17; seed ^= seed << 5; return seed; };
|
||||
const char junk[] = {'\0', '\n', '\r', ',', ';', '=', '[', ']', ' ', '-', '9', '#', 'x', '%', '\xc2', '\xa0', '\xff'};
|
||||
int runs = 0;
|
||||
for (const std::string &base : inputs) {
|
||||
for (int k = 0; k < 40; ++k) {
|
||||
std::string t = base;
|
||||
const int edits = 1 + (int)(rnd() % 20);
|
||||
for (int e = 0; e < edits && !t.empty(); ++e) {
|
||||
const size_t at = rnd() % t.size();
|
||||
switch (rnd() % 4) {
|
||||
case 0: t[at] = junk[rnd() % sizeof junk]; break;
|
||||
case 1: t.erase(at, 1 + rnd() % 8); break;
|
||||
case 2: t.insert(at, 1, junk[rnd() % sizeof junk]); break;
|
||||
default: t.insert(at, "99999999999"); break;
|
||||
}
|
||||
}
|
||||
Project p;
|
||||
ProjectIo::loadInto(p, t);
|
||||
ProjectIo::save(p);
|
||||
SngFormat::exportText(p);
|
||||
Project q;
|
||||
SngFormat::importInto(q, t);
|
||||
SngFormat::exportText(q);
|
||||
SngFormat::looksLikeSng(t);
|
||||
ToolboxSlot s;
|
||||
PresetIo::importText(s, t);
|
||||
PresetIo::exportText(s);
|
||||
++runs;
|
||||
}
|
||||
}
|
||||
Project big;
|
||||
ProjectIo::loadInto(big, "[PATTERN id=0 len=2147483647]\n[PATTERN id=1 len=4000000]\n0,0,60,1,1\n");
|
||||
CHECK(big.patterns.size() == 8 && big.pattern(1)->length == 16);
|
||||
CHECK(runs > 0);
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 3) { std::fprintf(stderr, "usage: %s <songs dir> <mikroseq dir>\n", argv[0]); return 2; }
|
||||
goldenFiles(argv[1]);
|
||||
sngFormatTest();
|
||||
sngMikroSeqImportTest(argv[2]);
|
||||
projectIoNameTest();
|
||||
arrangementNoteOffTest();
|
||||
kotlinSemantics();
|
||||
tolerance(argv[1]);
|
||||
std::printf("io_test: %d passed, %d failed\n", passes, failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
Reference in New Issue
Block a user