From 7bc54e6466ec13e91ac1fa685c80202814fbeb1c Mon Sep 17 00:00:00 2001 From: Reactorcoremeltdown Date: Mon, 16 Nov 2026 01:50:51 +0100 Subject: [PATCH] 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 --- ios/CHANGELOG.md | 11 + ios/Makefile | 12 +- ios/PORTING.md | 29 + ios/core/include/sizzle/Engine.hpp | 141 ++++ ios/core/include/sizzle/Model.hpp | 7 +- ios/core/include/sizzle/Params.hpp | 6 +- ios/core/src/engine/ChannelArp.hpp | 112 +++ ios/core/src/engine/Engine.cpp | 1260 ++++++++++++++++++++++++++++ ios/core/src/io/KotlinText.cpp | 215 +++++ ios/core/src/io/KotlinText.hpp | 55 ++ ios/core/src/io/PresetIo.cpp | 69 ++ ios/core/src/io/PresetIo.hpp | 23 + ios/core/src/io/ProjectIo.cpp | 295 +++++++ ios/core/src/io/ProjectIo.hpp | 32 + ios/core/src/io/SngFormat.cpp | 302 +++++++ ios/core/src/io/SngFormat.hpp | 29 + ios/core/src/model/Model.cpp | 382 ++++++++- ios/core/tests/engine_test.cpp | 238 ++++++ ios/core/tests/io_test.cpp | 565 +++++++++++++ versions.properties | 4 +- 20 files changed, 3746 insertions(+), 41 deletions(-) create mode 100644 ios/core/include/sizzle/Engine.hpp create mode 100644 ios/core/src/engine/ChannelArp.hpp create mode 100644 ios/core/src/engine/Engine.cpp create mode 100644 ios/core/src/io/KotlinText.cpp create mode 100644 ios/core/src/io/KotlinText.hpp create mode 100644 ios/core/src/io/PresetIo.cpp create mode 100644 ios/core/src/io/PresetIo.hpp create mode 100644 ios/core/src/io/ProjectIo.cpp create mode 100644 ios/core/src/io/ProjectIo.hpp create mode 100644 ios/core/src/io/SngFormat.cpp create mode 100644 ios/core/src/io/SngFormat.hpp create mode 100644 ios/core/tests/engine_test.cpp create mode 100644 ios/core/tests/io_test.cpp diff --git a/ios/CHANGELOG.md b/ios/CHANGELOG.md index 57270c6..3df6ea8 100644 --- a/ios/CHANGELOG.md +++ b/ios/CHANGELOG.md @@ -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, diff --git a/ios/Makefile b/ios/Makefile index f1d76d7..09518b8 100644 --- a/ios/Makefile +++ b/ios/Makefile @@ -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 diff --git a/ios/PORTING.md b/ios/PORTING.md index f756614..a680e82 100644 --- a/ios/PORTING.md +++ b/ios/PORTING.md @@ -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`, diff --git a/ios/core/include/sizzle/Engine.hpp b/ios/core/include/sizzle/Engine.hpp new file mode 100644 index 0000000..20d3286 --- /dev/null +++ b/ios/core/include/sizzle/Engine.hpp @@ -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 +#include +#include + +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; +}; + +} // namespace sizzle::engine diff --git a/ios/core/include/sizzle/Model.hpp b/ios/core/include/sizzle/Model.hpp index d537d33..9cf86a1 100644 --- a/ios/core/include/sizzle/Model.hpp +++ b/ios/core/include/sizzle/Model.hpp @@ -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 diff --git a/ios/core/include/sizzle/Params.hpp b/ios/core/include/sizzle/Params.hpp index aca582c..2f66abe 100644 --- a/ios/core/include/sizzle/Params.hpp +++ b/ios/core/include/sizzle/Params.hpp @@ -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); diff --git a/ios/core/src/engine/ChannelArp.hpp b/ios/core/src/engine/ChannelArp.hpp new file mode 100644 index 0000000..755736c --- /dev/null +++ b/ios/core/src/engine/ChannelArp.hpp @@ -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 +#include + +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 diff --git a/ios/core/src/engine/Engine.cpp b/ios/core/src/engine/Engine.cpp new file mode 100644 index 0000000..76a32d2 --- /dev/null +++ b/ios/core/src/engine/Engine.cpp @@ -0,0 +1,1260 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +// Port of AudioEngine.kt, line for line where it makes sound. Kotlin's types are +// kept (Float -> float, Double -> double); kotlin.math goes through KotlinMath.hpp. +// Volatile Kotlin references (project, playlist, channelChains) become atomics; +// replaced playlists / chains are retired and freed by a later main-thread rebuild +// once the audio thread has finished a block after the swap. + +#pragma clang fp contract(off) + +#include "sizzle/Engine.hpp" + +#include +#include +#include +#include +#include +#include + +#include "KotlinMath.hpp" +#include "engine/ChannelArp.hpp" +#include "echofield/GrainCloud.hpp" +#include "frasil/FrasilVoice.hpp" +#include "model/TimeDivision.hpp" +#include "sampler/SampleStore.hpp" +#include "sampler/SampleVoice.hpp" +#include "sizzle/Effect.hpp" +#include "sizzle/Model.hpp" +#include "sizzle/Specs.hpp" +#include "synth/SynthPatch.hpp" +#include "synth/SynthVoice.hpp" +#include "wavetable/WaveVoice.hpp" + +namespace sizzle::engine { + +using model::Project; +using model::ToolboxSlot; +using sampler::SampleVoice; +using sampler::VoiceSample; +using synth::SynthPatch; +using synth::SynthVoice; +using echofield::GrainCloud; +using echofield::GrainPatch; + +namespace { + +constexpr int TRACK_COUNT = model::Pattern::TRACK_COUNT; +constexpr int LANE_COUNT = model::Arrangement::LANE_COUNT; + +constexpr float MASTER_MAKEUP = 1.5f; +constexpr float LIM_CEILING = 0.97f; +constexpr int LIM_LOOKAHEAD = 64; +constexpr int LIM_HOLD_EXTRA = 8; +constexpr float LIM_RELEASE = 0.00025f; +constexpr float LIVE_GAIN = 0.5f; +constexpr float METER_DECAY = 0.96f; +constexpr float METER_CLIP_LEVEL = 0.999f; +constexpr int METER_CLIP_HOLD_BLOCKS = 200; +constexpr float SOFT_KNEE = 0.6f; +constexpr float NaNf = std::numeric_limits::quiet_NaN(); + +/** Continuous soft-knee limiter (AudioEngine.softClip). */ +float softClip(float x) { + const float a = x < 0.f ? -x : x; + if (a <= SOFT_KNEE) return x; + const float k = 1.f - SOFT_KNEE; + const float comp = SOFT_KNEE + k * kt::tanhf_((a - SOFT_KNEE) / k); + return x < 0.f ? -comp : comp; +} + +/** Math.max(float, float) (NaN wins; operands here are non-negative). */ +float jmax(float a, float b) { + if (a != a) return a; + return a >= b ? a : b; +} + +bool is(const ToolboxSlot *s, const char *type) { return s && s->type == type; } +bool hasType(const ToolboxSlot *s) { return s && !s->type.empty(); } + +/** The slot types whose notes a SynthVoice plays with a parsed SynthPatch. */ +bool hasSynthPatch(const ToolboxSlot *s) { + return is(s, "NES_SYNTH") || is(s, "MORPH_PAD") || is(s, "WAVETABLE"); +} + +/** Version as Kotlin's Int, widened so -1 can mean "never". */ +int64_t ver(const ToolboxSlot &s) { return (int64_t)(int32_t)s.version; } + +struct FxUnit { + ToolboxSlot *slot; + std::unique_ptr effect; + int64_t lastVersion = -1; + float lastTempo = NaNf; +}; + +struct Chains { + std::vector ch[TRACK_COUNT]; +}; + +const Sample *storeLookup(void *ctx, const char *id) { + return static_cast(ctx)->get(id); +} + +} // namespace + +class Engine::Impl { +public: + Impl(int sr, sampler::SampleStore *store, const EngineGlobals &g); + ~Impl(); + + const int sampleRate; + sampler::SampleStore *const store; + + // Kotlin globals, owned here (declared before the voices that reference them). + frasil::FrasilClock clock; + frasil::FrasilSeeds frasilSeeds; + echofield::GrainSeeds grainSeeds; + + std::vector> seqVoices; // TRACK_COUNT * POLYPHONY + std::vector> sampleVoices; // TRACK_COUNT * POLYPHONY + int synthAlloc[TRACK_COUNT] = {}; + int sampleAlloc[TRACK_COUNT] = {}; + std::vector> liveVoices; + std::vector> auditionSampleVoices; + std::vector> busVoices; // TRACK_COUNT * BUS_POLYPHONY + std::vector> busSampleVoices; + ChannelArp arps[LANE_COUNT * TRACK_COUNT]; + int lineTriggerGen = 0; + int trackLastChannel[LANE_COUNT * TRACK_COUNT]; + + // ---- outgoing MIDI + std::atomic midiOutEnabled{false}; + int moutRing[256] = {}; + std::atomic moutHead{0}; + std::atomic moutTail{0}; + int moutNote[LANE_COUNT * TRACK_COUNT]; + int moutCh[LANE_COUNT * TRACK_COUNT] = {}; + + // ---- Grain Cloud + std::vector> clouds; + bool cloudOn[TRACK_COUNT] = {}; + int64_t cloudVer[TRACK_COUNT]; + float cloudTempo[TRACK_COUNT]; + std::unique_ptr auditionCloud; + int64_t auditionCloudVer = -1; + float auditionCloudTempo = NaNf; + bool auditionCloudActive = false; + + // ---- cached synth patches (null in Kotlin == !has) + SynthPatch synthPatch[TRACK_COUNT]; + bool synthPatchHas[TRACK_COUNT] = {}; + int64_t synthPatchVer[TRACK_COUNT]; + float synthPatchTempo[TRACK_COUNT]; + int auditionSlotIdx = -1; + SynthPatch auditionPatch; + bool auditionPatchHas = false; + int64_t auditionPatchVer = -1; + float auditionPatchTempo = NaNf; + + // ---- FX chains (volatile in Kotlin) + std::atomic channelChains{nullptr}; + float channelSum[TRACK_COUNT] = {}; + + // ---- master limiter + float limDelayL[LIM_LOOKAHEAD] = {}; + float limDelayR[LIM_LOOKAHEAD] = {}; + int limPos = 0; + float limGain = 1.f; + int limHold = 0; + float limOutL = 0.f, limOutR = 0.f; + + // ---- meters + float chBlockPeak[TRACK_COUNT] = {}; + std::atomic chMeter[TRACK_COUNT]; + std::atomic chClipHold[TRACK_COUNT]; + + // ---- per-block active lists + std::vector actSeq, actSmp, actBus, actBSmp, actLive, actASmp; + int actSeqN = 0, actSmpN = 0, actBusN = 0, actBSmpN = 0, actLiveN = 0, actASmpN = 0; + std::vector seqGen, smpGen; + int blockGen = 0; + + std::atomic project{nullptr}; + std::atomic playing{false}; + + // ---- position (audio thread; reset from the main thread like the Kotlin) + double samplesIntoLine = 0.0; + bool pendingTrigger = true; + double blockSamplesPerLine = 1.0; + int currentLine = 0; + bool arrangementMode = false; + std::atomic *> playlist{nullptr}; + int playlistIndex = 0; + int lineInBeat = 0; + int arrPlayLine = 0; + + // TransportState, packed: line | beat << 31 | playing << 62. + std::atomic transportPacked{0}; + + // ---- recording + MasterSink *sink = nullptr; + std::atomic recordArmed{false}; + std::atomic recTailBars{0}; + std::atomic recCapturing{false}; + std::atomic extClockRunning{false}; + bool recWasPlaying = false; + int recTailRemaining = 0; + + // ---- MIDI LFO + uint32_t rngState = 0x9E3779B9u; + double lfoPhase[Project::TOOLBOX_SLOTS] = {}; + double lfoSampleHold[Project::TOOLBOX_SLOTS] = {}; + + // ---- retiring swapped-out chains / playlists (main thread) + std::atomic blocksDone{0}; + struct RetiredChains { std::unique_ptr p; uint64_t at; }; + struct RetiredList { std::unique_ptr> p; uint64_t at; }; + std::vector retiredChains; + std::vector retiredLists; + void collectRetired(); + + // ---- AudioEngine + SynthVoice &allocSynthVoice(int bus); + SampleVoice &allocSampleVoice(int bus); + void queueSeq(int i) { if (seqGen[i] != blockGen) { seqGen[i] = blockGen; actSeq[actSeqN++] = i; } } + void queueSmp(int i) { if (smpGen[i] != blockGen) { smpGen[i] = blockGen; actSmp[actSmpN++] = i; } } + void releaseBus(int bus); + + void maybeStartRecording(); + void recordSample(Project *proj, float left, float right); + + void setProject(Project *p); + void rebuildFxChains(); + void rebuildArrangement(); + void refreshLoopPlaylist(); + std::vector *buildPlaylist(const model::Arrangement &arr); + + void play(int startBeat); + void pause(); + void panic(); + void stop(); + void liveNoteOn(int pitch, int velocity); + void liveNoteOff(int pitch); + + void fillBlock(float *out, int frames); + void masterLimit(float inL, float inR); + void updateFxParams(Project &proj); + float nextRandomUnit(); + void applyLfos(Project &proj); + void advanceSequencer(Project &proj); + void advancePatternLoop(Project &proj); + void triggerPatternLine(Project &proj, const model::Pattern &pattern, int line); + void triggerCell(Project &proj, int lane, int track, const model::Cell &cell); + void releaseTrack(Project &proj, int lane, int track); + void releaseLane(Project &proj, int lane); + void releaseTrackVoices(int trackKey); + void playNote(Project &proj, int bus, int note, int velocity, int ownerTrack = -1); + bool voiceSample(const ToolboxSlot *slot, int note, VoiceSample &out) const; + void resetBarArps(); + const ToolboxSlot *channelArpSlot(Project &proj, int track) const; + void advanceArps(Project &proj); + int channelTranspose(Project &proj, int track) const; + void auditionSlotOn(int slotIndex, int midi); + void auditionSlotOff(int midi); + void busNoteOn(int midiChannel, int midi, int velocity); + void busNoteOff(int midiChannel, int midi); + std::string describeBusTargets(int midiChannel, int midi) const; + void advanceArrangement(Project &proj); + void triggerArrangementLine(Project &proj, const model::Arrangement &arr, int beat, int lineInBeat, + int linesPerBeat); + static SynthPatch patchForSlot(const ToolboxSlot *slot, float tempoBpm); + void refreshSynthPatches(Project &proj); + double samplesPerLine(const Project &proj) const { + return sampleRate * (60.0 / proj.tempoBpm) / model::info(proj.timeSignature).linesPerBeat; + } + void allSeqVoicesOff(); + void emitMidi(int status, int d1, int d2); + void emitNoteOn(int ch, int note, int vel); + void emitNoteOff(int ch, int note); + void allMidiNotesOff(); + int pollMidiOut(); + void publish(); + + static const ToolboxSlot *slotAt(const Project &proj, int idx) { + return idx >= 0 && idx < Project::TOOLBOX_SLOTS ? &proj.toolbox[idx] : nullptr; + } + static ToolboxSlot *slotAt(Project &proj, int idx) { + return idx >= 0 && idx < Project::TOOLBOX_SLOTS ? &proj.toolbox[idx] : nullptr; + } +}; + +// ------------------------------------------------------------------ construction + +Engine::Impl::Impl(int sr, sampler::SampleStore *st, const EngineGlobals &g) : sampleRate(sr), store(st) { + clock.seconds = g.clockSeconds; + frasilSeeds.seeds = g.frasilSeeds; + grainSeeds.seeds = g.grainSeeds; + // AudioEngine's field order: every SynthVoice takes the next FrasilVoice seed, + // every GrainCloud the next cloud seed. + for (int i = 0; i < TRACK_COUNT * POLYPHONY; ++i) + seqVoices.push_back(std::make_unique(sr, clock, frasilSeeds.next())); + for (int i = 0; i < TRACK_COUNT * POLYPHONY; ++i) sampleVoices.push_back(std::make_unique(sr)); + for (int i = 0; i < LIVE_POLYPHONY; ++i) + liveVoices.push_back(std::make_unique(sr, clock, frasilSeeds.next())); + for (int i = 0; i < AUDITION_POLYPHONY; ++i) auditionSampleVoices.push_back(std::make_unique(sr)); + for (int i = 0; i < TRACK_COUNT * BUS_POLYPHONY; ++i) + busVoices.push_back(std::make_unique(sr, clock, frasilSeeds.next())); + for (int i = 0; i < TRACK_COUNT * BUS_POLYPHONY; ++i) busSampleVoices.push_back(std::make_unique(sr)); + for (int &c : trackLastChannel) c = -1; + for (int &n : moutNote) n = -1; + for (int i = 0; i < TRACK_COUNT; ++i) { + clouds.push_back(std::make_unique(sr, grainSeeds.next())); + cloudVer[i] = -1; + cloudTempo[i] = NaNf; + synthPatchVer[i] = -1; + synthPatchTempo[i] = NaNf; + chMeter[i].store(0.f); + chClipHold[i].store(0); + } + auditionCloud = std::make_unique(sr, grainSeeds.next()); + if (store) { + for (auto &c : clouds) c->setSampleLookup(&storeLookup, store); + auditionCloud->setSampleLookup(&storeLookup, store); + } + + actSeq.assign(seqVoices.size(), 0); + actSmp.assign(sampleVoices.size(), 0); + actBus.assign(busVoices.size(), 0); + actBSmp.assign(busSampleVoices.size(), 0); + actLive.assign(liveVoices.size(), 0); + actASmp.assign(auditionSampleVoices.size(), 0); + seqGen.assign(seqVoices.size(), 0); + smpGen.assign(sampleVoices.size(), 0); + + // Kotlin: DoubleArray { Math.random() * 2 - 1 }. + std::random_device rd; + std::uniform_real_distribution uni(0.0, 1.0); + for (double &v : lfoSampleHold) v = uni(rd) * 2 - 1; + + channelChains.store(new Chains()); + playlist.store(new std::vector()); +} + +Engine::Impl::~Impl() { + delete channelChains.load(); + delete playlist.load(); +} + +void Engine::Impl::collectRetired() { + const uint64_t done = blocksDone.load(); + for (size_t i = 0; i < retiredChains.size();) + if (done > retiredChains[i].at) retiredChains.erase(retiredChains.begin() + (long)i); else ++i; + for (size_t i = 0; i < retiredLists.size();) + if (done > retiredLists[i].at) retiredLists.erase(retiredLists.begin() + (long)i); else ++i; +} + +// ------------------------------------------------------------------ voice pools + +SynthVoice &Engine::Impl::allocSynthVoice(int bus) { + const int base = bus * POLYPHONY; + for (int i = 0; i < POLYPHONY; ++i) { + SynthVoice &v = *seqVoices[base + i]; + if (!v.isActive()) { queueSeq(base + i); return v; } + } + const int idx = synthAlloc[bus]; + synthAlloc[bus] = (idx + 1) % POLYPHONY; + SynthVoice &v = *seqVoices[base + idx]; + v.kill(); + queueSeq(base + idx); + return v; +} + +SampleVoice &Engine::Impl::allocSampleVoice(int bus) { + const int base = bus * POLYPHONY; + for (int i = 0; i < POLYPHONY; ++i) { + SampleVoice &v = *sampleVoices[base + i]; + if (!v.isActive()) { queueSmp(base + i); return v; } + } + const int idx = sampleAlloc[bus]; + sampleAlloc[bus] = (idx + 1) % POLYPHONY; + SampleVoice &v = *sampleVoices[base + idx]; + queueSmp(base + idx); + return v; +} + +void Engine::Impl::releaseBus(int bus) { + clouds[bus]->releaseSequenced(); + const int base = bus * POLYPHONY; + for (int i = 0; i < POLYPHONY; ++i) { + seqVoices[base + i]->noteOff(); + sampleVoices[base + i]->noteOff(); + } +} + +// ------------------------------------------------------------------ recording + +void Engine::Impl::maybeStartRecording() { + if (!recordArmed.load()) return; + if (!sink) return; + if (sink->isActive()) return; + if (!sink->begin()) return; + recTailRemaining = -1; + recWasPlaying = true; + recCapturing.store(true); +} + +void Engine::Impl::recordSample(Project *proj, float left, float right) { + const bool nowPlaying = playing.load(std::memory_order_relaxed) || extClockRunning.load(std::memory_order_relaxed); + if (recWasPlaying && !nowPlaying) { + recTailRemaining = proj == nullptr ? 0 + : (int)(recTailBars.load(std::memory_order_relaxed) * model::info(proj->timeSignature).linesPerBar() + * samplesPerLine(*proj)); + } + recWasPlaying = nowPlaying; + sink->write(left, right); + if (!nowPlaying) { + if (recTailRemaining <= 0) { + recCapturing.store(false, std::memory_order_relaxed); + sink->endCapture(); + } else { + recTailRemaining--; + } + } +} + +// ------------------------------------------------------------------ song + +void Engine::Impl::setProject(Project *p) { + project.store(p); + rebuildArrangement(); + rebuildFxChains(); +} + +void Engine::Impl::rebuildFxChains() { + Project *proj = project.load(); + if (!proj) return; + collectRetired(); + auto next = std::make_unique(); + for (int ch = 0; ch < TRACK_COUNT; ++ch) { + for (int slotIndex : proj->mixer.channels[ch].fxSlots) { + if (slotIndex < 0) continue; + ToolboxSlot *slot = slotAt(*proj, slotIndex); + if (!slot || slot->type.empty()) continue; + if (auto fx = Effect::create(slot->type.c_str(), sampleRate)) { + FxUnit u{slot, std::move(fx)}; + next->ch[ch].push_back(std::move(u)); + } + } + } + Chains *old = channelChains.exchange(next.release()); + retiredChains.push_back({std::unique_ptr(old), blocksDone.load()}); +} + +void Engine::Impl::rebuildArrangement() { + Project *proj = project.load(); + if (!proj) return; + collectRetired(); + const auto &arr = proj->arrangement; + bool any = false; + for (const auto &lane : arr.slots) { + for (int v : lane) if (v != model::Arrangement::EMPTY) { any = true; break; } + if (any) break; + } + arrangementMode = any; + std::vector *old = playlist.exchange(buildPlaylist(arr)); + retiredLists.push_back({std::unique_ptr>(old), blocksDone.load()}); + playlistIndex = 0; + lineInBeat = 0; + arrPlayLine = 0; +} + +void Engine::Impl::refreshLoopPlaylist() { + Project *proj = project.load(); + if (!proj) return; + if (!arrangementMode) return; + collectRetired(); + std::vector *old = playlist.exchange(buildPlaylist(proj->arrangement)); + retiredLists.push_back({std::unique_ptr>(old), blocksDone.load()}); +} + +std::vector *Engine::Impl::buildPlaylist(const model::Arrangement &arr) { + const auto &a = arr.regionA; + const auto &b = arr.regionB; + auto *out = new std::vector(); + if (!arr.loopEnabled || (!a.isValid() && !b.isValid())) { + int end = arr.lastFilledBeat() + 1; + if (end < 0) end = 0; + for (int i = 0; i < end; ++i) out->push_back(i); + return out; + } + if (a.isValid()) for (int r = 0; r < a.repeats; ++r) for (int beat = a.start; beat < a.end; ++beat) out->push_back(beat); + if (b.isValid()) for (int r = 0; r < b.repeats; ++r) for (int beat = b.start; beat < b.end; ++beat) out->push_back(beat); + return out; +} + +// ------------------------------------------------------------------ transport + +void Engine::Impl::play(int startBeat) { + rebuildArrangement(); + rebuildFxChains(); + if (startBeat >= 0) { + if (arrangementMode) { + const std::vector &list = *playlist.load(); + int seek = -1; + for (size_t i = 0; i < list.size(); ++i) if (list[i] == startBeat) { seek = (int)i; break; } + if (seek >= 0) { + playlistIndex = seek; lineInBeat = 0; arrPlayLine = 0; samplesIntoLine = 0.0; + } + } else { + Project *proj = project.load(); + if (proj) { + const auto &pat = proj->activePattern(); + currentLine = kt::coerceIn(startBeat * model::info(proj->timeSignature).linesPerBeat, 0, pat.length - 1); + samplesIntoLine = 0.0; + } + } + } + pendingTrigger = true; + playing.store(true); + maybeStartRecording(); + publish(); +} + +void Engine::Impl::pause() { + playing.store(false); + extClockRunning.store(false); + allSeqVoicesOff(); + publish(); +} + +void Engine::Impl::panic() { + for (auto &c : clouds) c->kill(); + auditionCloud->kill(); + for (auto &v : seqVoices) v->kill(); + for (auto &v : sampleVoices) v->kill(); + for (auto &v : liveVoices) v->kill(); + for (auto &v : auditionSampleVoices) v->kill(); + for (auto &v : busVoices) v->kill(); + for (auto &v : busSampleVoices) v->kill(); + for (auto &a : arps) a.stop(); + for (int &c : trackLastChannel) c = -1; + allMidiNotesOff(); +} + +void Engine::Impl::stop() { + extClockRunning.store(false); + if (!playing.load() && currentLine == 0 && playlistIndex == 0 && lineInBeat == 0) return; + const bool wasStopped = !playing.load(); + playing.store(false); + allSeqVoicesOff(); + if (wasStopped) { + currentLine = 0; samplesIntoLine = 0.0; + playlistIndex = 0; lineInBeat = 0; + arrPlayLine = 0; + } + publish(); +} + +void Engine::Impl::liveNoteOn(int pitch, int velocity) { + SynthVoice *v = nullptr; + for (auto &lv : liveVoices) if (!lv->isActive()) { v = lv.get(); break; } + if (!v) { v = liveVoices[0].get(); v->kill(); } + v->noteOn(pitch, velocity, SynthPatch::defaults()); +} + +void Engine::Impl::liveNoteOff(int pitch) { + SynthVoice *v = nullptr; + for (auto &lv : liveVoices) if (lv->pitch() == pitch && lv->isGated()) { v = lv.get(); break; } + if (!v) for (auto &lv : liveVoices) if (lv->isActive() && lv->pitch() == pitch) { v = lv.get(); break; } + if (v) v->noteOff(); +} + +// ------------------------------------------------------------------ render + +void Engine::Impl::fillBlock(float *out, int frames) { + Project *proj = project.load(std::memory_order_acquire); + if (store) store->quiescent(); + clock.advance(frames, sampleRate); + if (proj) { + applyLfos(*proj); + updateFxParams(*proj); + refreshSynthPatches(*proj); + blockSamplesPerLine = samplesPerLine(*proj); + } + const bool anySolo = proj ? proj->mixer.anySolo() : false; + Chains *chains = channelChains.load(std::memory_order_acquire); + + blockGen++; + actSeqN = 0; actSmpN = 0; actBusN = 0; actBSmpN = 0; actLiveN = 0; actASmpN = 0; + for (int ch = 0; ch < TRACK_COUNT; ++ch) chBlockPeak[ch] = 0.f; + for (int i = 0; i < (int)seqVoices.size(); ++i) if (seqVoices[i]->isActive()) { seqGen[i] = blockGen; actSeq[actSeqN++] = i; } + for (int i = 0; i < (int)sampleVoices.size(); ++i) if (sampleVoices[i]->isActive()) { smpGen[i] = blockGen; actSmp[actSmpN++] = i; } + for (int i = 0; i < (int)busVoices.size(); ++i) if (busVoices[i]->isActive()) actBus[actBusN++] = i; + for (int i = 0; i < (int)busSampleVoices.size(); ++i) if (busSampleVoices[i]->isActive()) actBSmp[actBSmpN++] = i; + for (int i = 0; i < (int)liveVoices.size(); ++i) if (liveVoices[i]->isActive()) actLive[actLiveN++] = i; + auditionCloudActive = auditionCloud->isActive(); + for (int i = 0; i < (int)auditionSampleVoices.size(); ++i) if (auditionSampleVoices[i]->isActive()) actASmp[actASmpN++] = i; + + for (int i = 0; i < frames; ++i) { + if (playing.load(std::memory_order_relaxed) && proj) advanceSequencer(*proj); + + float mixL = 0.f; + float mixR = 0.f; + if (proj) { + for (float &s : channelSum) s = 0.f; + for (int k = 0; k < actSeqN; ++k) { const int vi = actSeq[k]; channelSum[vi / POLYPHONY] += seqVoices[vi]->render(); } + for (int k = 0; k < actSmpN; ++k) { const int vi = actSmp[k]; channelSum[vi / POLYPHONY] += sampleVoices[vi]->render(); } + for (int k = 0; k < actBusN; ++k) { const int vi = actBus[k]; channelSum[vi / BUS_POLYPHONY] += busVoices[vi]->render(); } + for (int k = 0; k < actBSmpN; ++k) { const int vi = actBSmp[k]; channelSum[vi / BUS_POLYPHONY] += busSampleVoices[vi]->render(); } + for (int ch = 0; ch < TRACK_COUNT; ++ch) if (cloudOn[ch]) channelSum[ch] += clouds[ch]->render(); + for (int ch = 0; ch < TRACK_COUNT; ++ch) { + const auto &mc = proj->mixer.channels[ch]; + float s = mc.audible(anySolo) ? channelSum[ch] * mc.volume : 0.f; + for (FxUnit &u : chains->ch[ch]) s = u.effect->process(s); + if (!std::isfinite(s)) s = 0.f; + if (mc.limiter) s = softClip(s); + const float a = s < 0.f ? -s : s; + if (a > chBlockPeak[ch]) chBlockPeak[ch] = a; + mixL += s; mixR += s; + } + } + for (int k = 0; k < actLiveN; ++k) { const float v = liveVoices[actLive[k]]->render() * LIVE_GAIN; mixL += v; mixR += v; } + if (auditionCloudActive) { const float v = auditionCloud->render() * LIVE_GAIN; mixL += v; mixR += v; } + for (int k = 0; k < actASmpN; ++k) { const float v = auditionSampleVoices[actASmp[k]]->render() * LIVE_GAIN; mixL += v; mixR += v; } + masterLimit(mixL * MASTER_MAKEUP, mixR * MASTER_MAKEUP); + const float oL = limOutL; + const float oR = limOutR; + out[2 * i] = oL; + out[2 * i + 1] = oR; + if (recCapturing.load(std::memory_order_relaxed) && sink) recordSample(proj, oL, oR); + } + + for (int ch = 0; ch < TRACK_COUNT; ++ch) { + const float peak = chBlockPeak[ch]; + const float decayed = chMeter[ch].load(std::memory_order_relaxed) * METER_DECAY; + chMeter[ch].store(peak > decayed ? peak : decayed, std::memory_order_relaxed); + if (peak >= METER_CLIP_LEVEL) chClipHold[ch].store(METER_CLIP_HOLD_BLOCKS, std::memory_order_relaxed); + else if (chClipHold[ch].load(std::memory_order_relaxed) > 0) chClipHold[ch].fetch_sub(1, std::memory_order_relaxed); + } + blocksDone.fetch_add(1); +} + +void Engine::Impl::masterLimit(float inL, float inR) { + const float dL = limDelayL[limPos]; + const float dR = limDelayR[limPos]; + limDelayL[limPos] = inL; + limDelayR[limPos] = inR; + limPos++; if (limPos >= LIM_LOOKAHEAD) limPos = 0; + + const float peak = jmax(std::fabs(inL), std::fabs(inR)); + const float target = peak > LIM_CEILING ? LIM_CEILING / peak : 1.f; + if (target < limGain) { limGain = target; limHold = LIM_LOOKAHEAD + LIM_HOLD_EXTRA; } + else if (limHold > 0) limHold--; + else limGain += (1.f - limGain) * LIM_RELEASE; + + float oL = dL * limGain; + float oR = dR * limGain; + if (oL > LIM_CEILING) oL = LIM_CEILING; else if (oL < -LIM_CEILING) oL = -LIM_CEILING; + if (oR > LIM_CEILING) oR = LIM_CEILING; else if (oR < -LIM_CEILING) oR = -LIM_CEILING; + limOutL = std::isfinite(oL) ? oL : 0.f; + limOutR = std::isfinite(oR) ? oR : 0.f; +} + +void Engine::Impl::updateFxParams(Project &proj) { + const float tempo = proj.tempoBpm; + Chains *chains = channelChains.load(std::memory_order_acquire); + for (int ch = 0; ch < TRACK_COUNT; ++ch) { + for (FxUnit &u : chains->ch[ch]) { + const int64_t v = ver(*u.slot); + if (v != u.lastVersion || tempo != u.lastTempo) { + u.effect->update(u.slot->values, tempo); + u.lastVersion = v; + u.lastTempo = tempo; + } + } + } +} + +float Engine::Impl::nextRandomUnit() { + uint32_t s = rngState; + s ^= s << 13; s ^= s >> 17; s ^= s << 5; + rngState = s; + return (float)s * 2.3283064e-10f; +} + +void Engine::Impl::applyLfos(Project &proj) { + const double secondsPerBeat = 60.0 / proj.tempoBpm; + const double blockSeconds = (double)BLOCK_FRAMES / sampleRate; + for (int i = 0; i < Project::TOOLBOX_SLOTS; ++i) { + ToolboxSlot &lfo = proj.toolbox[i]; + if (lfo.type != "LFO") continue; + const char *target = lfo.s("target"); + const char *colon = std::strchr(target, ':'); + const int sep = colon ? (int)(colon - target) : -1; + if (sep <= 0) continue; + uint32_t tIdx = 0; + bool validIdx = true; + for (int ci = 0; ci < sep; ++ci) { + const char ch = target[ci]; + if (ch < '0' || ch > '9') { validIdx = false; break; } + tIdx = tIdx * 10u + (uint32_t)(ch - '0'); + } + if (!validIdx || (int32_t)tIdx == i) continue; + ToolboxSlot *tSlot = slotAt(proj, (int32_t)tIdx); + if (!tSlot || tSlot->type.empty()) continue; + const DeviceSpec *dev = findDevice(tSlot->type.c_str()); + if (!dev) continue; + const char *key = target + sep + 1; + const size_t keyLen = std::strlen(key); + int specIdx = -1; + for (int pi = 0; pi < dev->paramCount; ++pi) { + const char *k = dev->params[pi].key; + if (std::strlen(k) == keyLen && std::memcmp(k, key, keyLen) == 0) { specIdx = pi; break; } + } + if (specIdx < 0) continue; + const ParamSpec &spec = dev->params[specIdx]; + + const auto div = model::fromIndex(kt::toInt(lfo.f("division", 3.f))); + double period = model::beatFraction(div) * secondsPerBeat; + if (period < 1e-6) period = 1e-6; + const double freq = 1.0 / period; + const double advanced = lfoPhase[i] + freq * blockSeconds; + if (advanced >= 1.0) lfoSampleHold[i] = nextRandomUnit() * 2.0 - 1.0; + lfoPhase[i] = std::fmod(advanced, 1.0); + const double phase = std::fmod(lfoPhase[i] + lfo.f("phase", 0.f), 1.0); + + const char *wave = lfo.s("wave", "Sine"); + double value; + if (std::strcmp(wave, "Triangle") == 0) value = 1.0 - 4.0 * std::fabs(phase - 0.5); + else if (std::strcmp(wave, "Saw") == 0) value = 2.0 * phase - 1.0; + else if (std::strcmp(wave, "Square") == 0) value = phase < 0.5 ? 1.0 : -1.0; + else if (std::strcmp(wave, "SampleHold") == 0) value = lfoSampleHold[i]; + else value = std::sin(2 * M_PI * phase); + const double center = (double)lfo.f("center", spec.def); + const double half = (spec.max - spec.min) / 2.0; + const double modulated = kt::coerceIn(center + lfo.f("depth", 0.5f) * value * half, + (double)spec.min, (double)spec.max); + tSlot->set(spec.key, (float)modulated); + } +} + +void Engine::Impl::advanceSequencer(Project &proj) { + if (arrangementMode) advanceArrangement(proj); else advancePatternLoop(proj); + advanceArps(proj); +} + +void Engine::Impl::advancePatternLoop(Project &proj) { + const model::Pattern &pattern = proj.activePattern(); + const double spl = blockSamplesPerLine; + + if (pendingTrigger) { + const int linesPerBar = model::info(proj.timeSignature).linesPerBar(); + if (linesPerBar > 0 && currentLine % linesPerBar == 0) resetBarArps(); + triggerPatternLine(proj, pattern, currentLine); + pendingTrigger = false; + } + samplesIntoLine += 1.0; + if (samplesIntoLine >= spl) { + samplesIntoLine -= spl; + currentLine++; + if (currentLine >= pattern.length) currentLine = 0; + pendingTrigger = true; + publish(); + } +} + +void Engine::Impl::triggerPatternLine(Project &proj, const model::Pattern &pattern, int line) { + lineTriggerGen++; + for (int t = 0; t < TRACK_COUNT; ++t) { + const model::Cell &cell = pattern.cell(t, line); + if (cell.isNoteOff()) triggerCell(proj, 0, t, cell); + } + for (int t = 0; t < TRACK_COUNT; ++t) { + const model::Cell &cell = pattern.cell(t, line); + if (cell.isPlayable()) triggerCell(proj, 0, t, cell); + } +} + +void Engine::Impl::triggerCell(Project &proj, int lane, int track, const model::Cell &cell) { + const int trackKey = lane * TRACK_COUNT + track; + if (cell.isNoteOff()) { releaseTrack(proj, lane, track); return; } + if (!cell.isPlayable()) return; + trackLastChannel[trackKey] = cell.channel; + if (moutNote[trackKey] >= 0) emitNoteOff(moutCh[trackKey], moutNote[trackKey]); + emitNoteOn(cell.channel, cell.note, cell.velocity); + moutNote[trackKey] = cell.note; moutCh[trackKey] = cell.channel; + releaseTrackVoices(trackKey); + for (int bus = 0; bus < TRACK_COUNT; ++bus) { + if (proj.mixer.channels[bus].midiChannel != cell.channel) continue; + ChannelArp &arp = arps[lane * TRACK_COUNT + bus]; + const int velocity = kt::coerceIn(cell.velocity, 0, 127); + const int note = kt::coerceIn(cell.note + channelTranspose(proj, bus), 0, 127); + const ToolboxSlot *arpSlot = channelArpSlot(proj, bus); + if (arpSlot) { + const int octaves = kt::toInt(arpSlot->f("octaves", 1.f)); + const auto div = model::fromIndex(kt::toInt(arpSlot->f("division", 3.f))); + const double stepSamples = model::beatFraction(div) * (60.0 / proj.tempoBpm) * sampleRate; + const char *mode = arpSlot->s("mode", "Up"); + const bool resetBar = std::strcmp(arpSlot->s("resetbar", "Off"), "On") == 0; + if (arp.active() && arp.genStamp == lineTriggerGen) { + arp.addNote(note); + arp.refresh(octaves, mode, stepSamples, resetBar); + } else if (arp.active()) { + arp.resetChord(note, velocity, octaves, mode, stepSamples, resetBar); + arp.genStamp = lineTriggerGen; + } else { + arp.startChord(note, velocity, octaves, mode, stepSamples, resetBar); + arp.genStamp = lineTriggerGen; + releaseBus(bus); + playNote(proj, bus, arp.currentNote(), velocity); + } + } else { + arp.stop(); + playNote(proj, bus, note, velocity, trackKey); + } + } +} + +void Engine::Impl::releaseTrack(Project &proj, int lane, int track) { + const int trackKey = lane * TRACK_COUNT + track; + if (moutNote[trackKey] >= 0) { emitNoteOff(moutCh[trackKey], moutNote[trackKey]); moutNote[trackKey] = -1; } + const int ch = trackLastChannel[trackKey]; + if (ch < 0) return; + for (int bus = 0; bus < TRACK_COUNT; ++bus) { + if (proj.mixer.channels[bus].midiChannel != ch) continue; + arps[lane * TRACK_COUNT + bus].stop(); + releaseBus(bus); + } +} + +void Engine::Impl::releaseLane(Project &proj, int lane) { + for (int t = 0; t < TRACK_COUNT; ++t) releaseTrack(proj, lane, t); +} + +void Engine::Impl::releaseTrackVoices(int trackKey) { + for (auto &c : clouds) c->releaseOwner(trackKey); + for (auto &v : seqVoices) if (v->ownerTrack == trackKey && v->isGated()) v->noteOff(); + for (auto &v : sampleVoices) if (v->ownerTrack == trackKey && v->isGated()) v->noteOff(); +} + +void Engine::Impl::playNote(Project &proj, int bus, int note, int velocity, int ownerTrack) { + const ToolboxSlot *slot = slotAt(proj, proj.mixer.channels[bus].instrumentSlot); + VoiceSample vs; + if (voiceSample(slot, note, vs)) { + SampleVoice &v = allocSampleVoice(bus); + v.ownerTrack = ownerTrack; + v.noteOn(*vs.sample, note, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume, + vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs); + } else if (!hasType(slot) || is(slot, "SAMPLER")) { + // Empty bus or a Sampler with an empty pad: silent. + } else if (is(slot, "GRAIN_CLOUD")) { + clouds[bus]->noteOn(note, velocity, ownerTrack >= 0 ? ownerTrack : GrainCloud::OWNER_SEQ); + } else { + SynthVoice &v = allocSynthVoice(bus); + v.ownerTrack = ownerTrack; + if (synthPatchHas[bus]) v.noteOn(note, velocity, synthPatch[bus]); + else v.noteOn(note, velocity, patchForSlot(slot, proj.tempoBpm)); + } +} + +bool Engine::Impl::voiceSample(const ToolboxSlot *slot, int note, VoiceSample &out) const { + if (!slot || !store || slot->type.empty()) return false; + return sampler::voiceSample(slot->type.c_str(), slot->values, *store, note, out); +} + +void Engine::Impl::resetBarArps() { + for (auto &a : arps) if (a.active() && a.resetOnBar) a.resetToBar(); +} + +const ToolboxSlot *Engine::Impl::channelArpSlot(Project &proj, int track) const { + for (int idx : proj.mixer.channels[track].fxSlots) { + if (idx < 0) continue; + const ToolboxSlot *slot = slotAt(proj, idx); + if (!slot) continue; + if (is(slot, "ARPEGGIATOR")) return slot; + } + return nullptr; +} + +void Engine::Impl::advanceArps(Project &proj) { + for (int i = 0; i < LANE_COUNT * TRACK_COUNT; ++i) { + ChannelArp &a = arps[i]; + if (!a.active()) continue; + a.samplesLeft -= 1.0; + if (a.samplesLeft <= 0.0) { + if (!a.consumePendingReset()) a.advance(); + const int bus = i % TRACK_COUNT; + releaseBus(bus); + playNote(proj, bus, a.currentNote(), a.velocity); + a.samplesLeft += a.stepSamples; + } + } +} + +int Engine::Impl::channelTranspose(Project &proj, int track) const { + int semis = 0; + for (int idx : proj.mixer.channels[track].fxSlots) { + if (idx < 0) continue; + const ToolboxSlot *slot = slotAt(proj, idx); + if (!slot) continue; + if (is(slot, "TRANSPOSER")) + semis += kt::toInt(slot->f("semitones", 0.f)) + kt::toInt(slot->f("octaves", 0.f)) * 12; + } + return semis; +} + +// ------------------------------------------------------------------ audition + +void Engine::Impl::auditionSlotOn(int slotIndex, int midi) { + Project *proj = project.load(); + if (!proj) return; + const ToolboxSlot *slot = slotAt(*proj, slotIndex); + VoiceSample vs; + if (voiceSample(slot, midi, vs)) { + SampleVoice *v = nullptr; + for (auto &sv : auditionSampleVoices) if (!sv->isActive()) { v = sv.get(); break; } + if (!v) { v = auditionSampleVoices[0].get(); v->kill(); } + v->noteOn(*vs.sample, midi, 110, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume, + vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs); + return; + } + if (is(slot, "SAMPLER")) return; + if (is(slot, "GRAIN_CLOUD")) { + if (auditionSlotIdx != slotIndex || ver(*slot) != auditionCloudVer) { + auditionCloud->setPatch(GrainPatch::from(&slot->values, proj->tempoBpm)); + auditionCloudVer = ver(*slot); + } + auditionSlotIdx = slotIndex; + auditionCloud->noteOn(midi, 110, GrainCloud::OWNER_LIVE); + return; + } + if (hasSynthPatch(slot)) auditionSlotIdx = slotIndex; + SynthVoice *v = nullptr; + for (auto &lv : liveVoices) if (!lv->isActive()) { v = lv.get(); break; } + if (!v) { v = liveVoices[0].get(); v->kill(); } + v->noteOn(midi, 110, patchForSlot(slot, proj->tempoBpm)); +} + +void Engine::Impl::auditionSlotOff(int midi) { + auditionCloud->noteOff(midi); + SynthVoice *v = nullptr; + for (auto &lv : liveVoices) if (lv->pitch() == midi && lv->isGated()) { v = lv.get(); break; } + if (!v) for (auto &lv : liveVoices) if (lv->isActive() && lv->pitch() == midi) { v = lv.get(); break; } + if (v) v->noteOff(); + SampleVoice *s = nullptr; + for (auto &sv : auditionSampleVoices) if (sv->pitch == midi && sv->isGated()) { s = sv.get(); break; } + if (!s) for (auto &sv : auditionSampleVoices) if (sv->isActive() && sv->pitch == midi) { s = sv.get(); break; } + if (s) s->noteOff(); +} + +void Engine::Impl::busNoteOn(int midiChannel, int midi, int velocity) { + Project *proj = project.load(); + if (!proj) return; + for (int ch = 0; ch < TRACK_COUNT; ++ch) { + if (proj->mixer.channels[ch].midiChannel != midiChannel) continue; + const ToolboxSlot *slot = slotAt(*proj, proj->mixer.channels[ch].instrumentSlot); + if (!hasType(slot)) continue; + const int base = ch * BUS_POLYPHONY; + VoiceSample vs; + if (voiceSample(slot, midi, vs)) { + SampleVoice *v = nullptr; + for (int i = 0; i < BUS_POLYPHONY; ++i) if (!busSampleVoices[base + i]->isActive()) { v = busSampleVoices[base + i].get(); break; } + if (!v) { v = busSampleVoices[base].get(); v->kill(); } + v->noteOn(*vs.sample, midi, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume, + vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs); + } else if (is(slot, "SAMPLER")) { + } else if (is(slot, "GRAIN_CLOUD")) { + clouds[ch]->noteOn(midi, velocity, GrainCloud::OWNER_LIVE); + } else { + SynthVoice *v = nullptr; + for (int i = 0; i < BUS_POLYPHONY; ++i) if (!busVoices[base + i]->isActive()) { v = busVoices[base + i].get(); break; } + if (!v) { v = busVoices[base].get(); v->kill(); } + if (synthPatchHas[ch]) v->noteOn(midi, velocity, synthPatch[ch]); + else v->noteOn(midi, velocity, patchForSlot(slot, proj->tempoBpm)); + } + } +} + +std::string Engine::Impl::describeBusTargets(int midiChannel, int midi) const { + Project *proj = project.load(); + if (!proj) return "no project"; + std::string out; + for (int ch = 0; ch < TRACK_COUNT; ++ch) { + if (proj->mixer.channels[ch].midiChannel != midiChannel) continue; + const ToolboxSlot *slot = slotAt(*proj, proj->mixer.channels[ch].instrumentSlot); + std::string part = "strip" + std::to_string(ch + 1) + " "; + VoiceSample vs; + if (!hasType(slot)) part += "no instrument (silent)"; + else if (is(slot, "SAMPLER")) { + const int pad = sampler::SamplerPads::padFor(midi); + part += "SAMPLER pad" + std::to_string(pad + 1) + (voiceSample(slot, midi, vs) ? "" : " empty (silent)"); + } else { + part += slot->type + (!voiceSample(slot, midi, vs) && is(slot, "SOUNDFONT") ? " no sample" : ""); + } + if (!out.empty()) out += " | "; + out += part; + } + return out.empty() ? "no strip on channel " + std::to_string(midiChannel) : out; +} + +void Engine::Impl::busNoteOff(int midiChannel, int midi) { + Project *proj = project.load(); + if (!proj) return; + for (int ch = 0; ch < TRACK_COUNT; ++ch) { + if (proj->mixer.channels[ch].midiChannel != midiChannel) continue; + clouds[ch]->noteOff(midi); + const int base = ch * BUS_POLYPHONY; + for (int i = 0; i < BUS_POLYPHONY; ++i) { + if (busVoices[base + i]->isActive() && busVoices[base + i]->pitch() == midi) busVoices[base + i]->noteOff(); + if (busSampleVoices[base + i]->isActive() && busSampleVoices[base + i]->pitch == midi) busSampleVoices[base + i]->noteOff(); + } + } +} + +// ------------------------------------------------------------------ arrangement + +void Engine::Impl::advanceArrangement(Project &proj) { + const model::Arrangement &arr = proj.arrangement; + const std::vector &list = *playlist.load(std::memory_order_acquire); + if (list.empty()) { playing.store(false); publish(); return; } + const int size = (int)list.size(); + const int linesPerBeat = model::info(proj.timeSignature).linesPerBeat; + const double spl = blockSamplesPerLine; + const int beat = list[kt::coerceIn(playlistIndex, 0, size - 1)]; + + if (pendingTrigger) { + const int beatsPerBar = model::info(proj.timeSignature).beatsPerBar; + if (lineInBeat == 0 && beatsPerBar > 0 && beat % beatsPerBar == 0) resetBarArps(); + triggerArrangementLine(proj, arr, beat, lineInBeat, linesPerBeat); + pendingTrigger = false; + } + + samplesIntoLine += 1.0; + if (samplesIntoLine >= spl) { + samplesIntoLine -= spl; + lineInBeat++; + if (lineInBeat >= linesPerBeat) { + lineInBeat = 0; + playlistIndex++; + if (playlistIndex >= size) { + if (arr.loopEnabled) { + playlistIndex = 0; + } else { + playing.store(false); allSeqVoicesOff(); publish(); return; + } + } + } + pendingTrigger = true; + publish(); + } +} + +void Engine::Impl::triggerArrangementLine(Project &proj, const model::Arrangement &arr, int beat, int lineInBeat_, + int linesPerBeat) { + lineTriggerGen++; + for (int pass = 0; pass <= 1; ++pass) { + for (int lane = 0; lane < LANE_COUNT; ++lane) { + if (arr.laneMuted[lane]) continue; + const int p = arr.patternAt(lane, beat); + if (p == model::Arrangement::EMPTY) continue; + if (p == model::Arrangement::NOTE_OFF) { + if (pass == 0 && lineInBeat_ == 0) releaseLane(proj, lane); + continue; + } + const model::Pattern *pat = proj.pattern(p); + if (!pat) continue; + int runStart = beat; + while (runStart > 0 && arr.hasBlockAt(lane, runStart - 1)) runStart--; + int blockBeats = pat->length / linesPerBeat; + if (blockBeats < 1) blockBeats = 1; + const int patLine = ((beat - runStart) % blockBeats) * linesPerBeat + lineInBeat_; + if (pass == 0 && p == proj.activePatternId) arrPlayLine = kt::coerceIn(patLine, 0, pat->length - 1); + if (patLine >= pat->length) continue; + for (int t = 0; t < TRACK_COUNT; ++t) { + const model::Cell &cell = pat->cell(t, patLine); + if (pass == 0) { if (cell.isNoteOff()) triggerCell(proj, lane, t, cell); } + else { if (cell.isPlayable()) triggerCell(proj, lane, t, cell); } + } + } + } +} + +// ------------------------------------------------------------------ patches + +SynthPatch Engine::Impl::patchForSlot(const ToolboxSlot *slot, float tempoBpm) { + if (is(slot, "NES_SYNTH")) return SynthPatch::from(&slot->values, tempoBpm); + if (is(slot, "MORPH_PAD")) return SynthPatch::forPad(frasil::FrasilPatch::from(&slot->values)); + if (is(slot, "WAVETABLE")) return SynthPatch::forWave(wavetable::WavePatch::from(&slot->values, tempoBpm)); + return SynthPatch::defaults(); +} + +void Engine::Impl::refreshSynthPatches(Project &proj) { + const float tempo = proj.tempoBpm; + for (int ch = 0; ch < TRACK_COUNT; ++ch) { + const ToolboxSlot *slot = slotAt(proj, proj.mixer.channels[ch].instrumentSlot); + if (is(slot, "GRAIN_CLOUD")) { + if (!cloudOn[ch] || ver(*slot) != cloudVer[ch] || tempo != cloudTempo[ch]) { + clouds[ch]->setPatch(GrainPatch::from(&slot->values, tempo)); + cloudVer[ch] = ver(*slot); + cloudTempo[ch] = tempo; + } + cloudOn[ch] = true; + } else if (cloudOn[ch]) { + cloudOn[ch] = false; + clouds[ch]->kill(); + } + if (!slot || !hasSynthPatch(slot)) { synthPatchHas[ch] = false; synthPatchVer[ch] = -1; continue; } + if (!synthPatchHas[ch] || ver(*slot) != synthPatchVer[ch] || tempo != synthPatchTempo[ch]) { + synthPatch[ch] = patchForSlot(slot, tempo); + synthPatchHas[ch] = true; + synthPatchVer[ch] = ver(*slot); + synthPatchTempo[ch] = tempo; + } + const SynthPatch &p = synthPatch[ch]; + const int sbase = ch * POLYPHONY; + for (int i = 0; i < POLYPHONY; ++i) if (seqVoices[sbase + i]->isActive()) seqVoices[sbase + i]->setPatch(p); + const int bbase = ch * BUS_POLYPHONY; + for (int i = 0; i < BUS_POLYPHONY; ++i) if (busVoices[bbase + i]->isActive()) busVoices[bbase + i]->setPatch(p); + } + const ToolboxSlot *aslot = slotAt(proj, auditionSlotIdx); + if (is(aslot, "GRAIN_CLOUD") && (ver(*aslot) != auditionCloudVer || tempo != auditionCloudTempo)) { + auditionCloud->setPatch(GrainPatch::from(&aslot->values, tempo)); + auditionCloudVer = ver(*aslot); + auditionCloudTempo = tempo; + } + if (aslot && hasSynthPatch(aslot)) { + if (!auditionPatchHas || ver(*aslot) != auditionPatchVer || tempo != auditionPatchTempo) { + auditionPatch = patchForSlot(aslot, tempo); + auditionPatchHas = true; + auditionPatchVer = ver(*aslot); + auditionPatchTempo = tempo; + } + for (auto &v : liveVoices) if (v->isActive()) v->setPatch(auditionPatch); + } +} + +void Engine::Impl::allSeqVoicesOff() { + for (auto &c : clouds) c->releaseSequenced(); + for (auto &v : seqVoices) v->noteOff(); + for (auto &v : sampleVoices) v->noteOff(); + for (auto &a : arps) a.stop(); + allMidiNotesOff(); +} + +// ------------------------------------------------------------------ outgoing MIDI + +void Engine::Impl::emitMidi(int status, int d1, int d2) { + if (!midiOutEnabled.load(std::memory_order_relaxed)) return; + const int h = moutHead.load(std::memory_order_relaxed); + const int next = (h + 1) & 255; + if (next == moutTail.load(std::memory_order_acquire)) return; + moutRing[h] = (status << 16) | ((d1 & 0x7F) << 8) | (d2 & 0x7F); + moutHead.store(next, std::memory_order_release); +} + +void Engine::Impl::emitNoteOn(int ch, int note, int vel) { + if (ch < 1) return; + emitMidi(0x90 | ((ch - 1) & 0x0F), kt::coerceIn(note, 0, 127), kt::coerceIn(vel, 1, 127)); +} + +void Engine::Impl::emitNoteOff(int ch, int note) { + if (ch < 1) return; + emitMidi(0x80 | ((ch - 1) & 0x0F), kt::coerceIn(note, 0, 127), 0); +} + +void Engine::Impl::allMidiNotesOff() { + for (int k = 0; k < LANE_COUNT * TRACK_COUNT; ++k) + if (moutNote[k] >= 0) { emitNoteOff(moutCh[k], moutNote[k]); moutNote[k] = -1; } +} + +int Engine::Impl::pollMidiOut() { + const int t = moutTail.load(std::memory_order_relaxed); + if (t == moutHead.load(std::memory_order_acquire)) return -1; + const int v = moutRing[t]; + moutTail.store((t + 1) & 255, std::memory_order_release); + return v; +} + +void Engine::Impl::publish() { + Project *proj = project.load(std::memory_order_relaxed); + const int linesPerBeat = proj ? model::info(proj->timeSignature).linesPerBeat : 4; + int line, beat; + if (arrangementMode) { + const std::vector &list = *playlist.load(std::memory_order_acquire); + beat = !list.empty() ? list[kt::coerceIn(playlistIndex, 0, (int)list.size() - 1)] : 0; + line = arrPlayLine; + } else { + line = currentLine; + beat = currentLine / linesPerBeat; + } + const uint64_t packed = ((uint64_t)(uint32_t)line & 0x7FFFFFFFu) | (((uint64_t)(uint32_t)beat & 0x7FFFFFFFu) << 31) + | ((uint64_t)(playing.load(std::memory_order_relaxed) ? 1 : 0) << 62); + transportPacked.store(packed, std::memory_order_relaxed); +} + +// ------------------------------------------------------------------ Engine + +Engine::Engine(int sampleRate, sampler::SampleStore *store, const EngineGlobals &globals) + : impl(std::make_unique(sampleRate, store, globals)) {} +Engine::~Engine() = default; + +int Engine::sampleRate() const { return impl->sampleRate; } +void Engine::setProject(model::Project *p) { impl->setProject(p); } +void Engine::rebuildFxChains() { impl->rebuildFxChains(); } +void Engine::rebuildArrangement() { impl->rebuildArrangement(); } +void Engine::refreshLoopPlaylist() { impl->refreshLoopPlaylist(); } +void Engine::play(int startBeat) { impl->play(startBeat); } +void Engine::pause() { impl->pause(); } +void Engine::stop() { impl->stop(); } +void Engine::panic() { impl->panic(); } + +TransportState Engine::transport() const { + const uint64_t v = impl->transportPacked.load(std::memory_order_relaxed); + TransportState t; + t.currentLine = (int)(v & 0x7FFFFFFFu); + t.currentBeat = (int)((v >> 31) & 0x7FFFFFFFu); + t.isPlaying = ((v >> 62) & 1) != 0; + return t; +} +bool Engine::isPlaying() const { return impl->playing.load(); } + +void Engine::fillBlock(float *out, int frames) { impl->fillBlock(out, frames); } + +void Engine::liveNoteOn(int pitch, int velocity) { impl->liveNoteOn(pitch, velocity); } +void Engine::liveNoteOff(int pitch) { impl->liveNoteOff(pitch); } +void Engine::auditionSlotOn(int slotIndex, int midi) { impl->auditionSlotOn(slotIndex, midi); } +void Engine::auditionSlotOff(int midi) { impl->auditionSlotOff(midi); } +void Engine::busNoteOn(int midiChannel, int midi, int velocity) { impl->busNoteOn(midiChannel, midi, velocity); } +void Engine::busNoteOff(int midiChannel, int midi) { impl->busNoteOff(midiChannel, midi); } +std::string Engine::describeBusTargets(int midiChannel, int midi) const { + return impl->describeBusTargets(midiChannel, midi); +} + +float Engine::channelMeter(int ch) const { + return ch >= 0 && ch < TRACK_COUNT ? impl->chMeter[ch].load(std::memory_order_relaxed) : 0.f; +} +bool Engine::channelClipped(int ch) const { + return ch >= 0 && ch < TRACK_COUNT && impl->chClipHold[ch].load(std::memory_order_relaxed) > 0; +} +int Engine::effectScope(int, float *, int) const { return -1; } +float Engine::effectPlayhead(int) const { return -1.f; } + +void Engine::setMidiOutEnabled(bool on) { impl->midiOutEnabled.store(on); } +bool Engine::midiOutEnabled() const { return impl->midiOutEnabled.load(); } +int Engine::pollMidiOut() { return impl->pollMidiOut(); } + +void Engine::setMasterSink(MasterSink *sink) { impl->sink = sink; } +void Engine::setRecordingArm(bool armed, int tailBars) { + impl->recordArmed.store(armed); + impl->recTailBars.store(kt::coerceIn(tailBars, 0, 8)); +} +void Engine::setRecordTailBars(int tailBars) { impl->recTailBars.store(kt::coerceIn(tailBars, 0, 8)); } +bool Engine::recordArmed() const { return impl->recordArmed.load(); } +void Engine::externalClockStart() { + impl->extClockRunning.store(true); + impl->maybeStartRecording(); +} +void Engine::externalClockStop() { impl->extClockRunning.store(false); } + +} // namespace sizzle::engine diff --git a/ios/core/src/io/KotlinText.cpp b/ios/core/src/io/KotlinText.cpp new file mode 100644 index 0000000..f1f00bf --- /dev/null +++ b/ios/core/src/io/KotlinText.cpp @@ -0,0 +1,215 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "io/KotlinText.hpp" + +#include +#include +#include +#include +#include +#include + +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 lines(const std::string &text) { + std::vector 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 split(const std::string &s, char c) { + std::vector 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 diff --git a/ios/core/src/io/KotlinText.hpp b/ios/core/src/io/KotlinText.hpp new file mode 100644 index 0000000..c10b63e --- /dev/null +++ b/ios/core/src/io/KotlinText.hpp @@ -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 +#include + +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 lines(const std::string &text); +/** String.trim(). */ +std::string trim(const std::string &s); +/** String.split(c): every part, empty ones included. */ +std::vector 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 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 diff --git a/ios/core/src/io/PresetIo.cpp b/ios/core/src/io/PresetIo.cpp new file mode 100644 index 0000000..6dcb817 --- /dev/null +++ b/ios/core/src/io/PresetIo.cpp @@ -0,0 +1,69 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "io/PresetIo.hpp" + +#include +#include +#include +#include +#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> map; // a LinkedHashMap + std::unordered_map 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 diff --git a/ios/core/src/io/PresetIo.hpp b/ios/core/src/io/PresetIo.hpp new file mode 100644 index 0000000..dcddb29 --- /dev/null +++ b/ios/core/src/io/PresetIo.hpp @@ -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 +#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 diff --git a/ios/core/src/io/ProjectIo.cpp b/ios/core/src/io/ProjectIo.cpp new file mode 100644 index 0000000..f8f6c72 --- /dev/null +++ b/ios/core/src/io/ProjectIo.cpp @@ -0,0 +1,295 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "io/ProjectIo.hpp" + +#include +#include +#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 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 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 &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 &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 diff --git a/ios/core/src/io/ProjectIo.hpp b/ios/core/src/io/ProjectIo.hpp new file mode 100644 index 0000000..56bb8bf --- /dev/null +++ b/ios/core/src/io/ProjectIo.hpp @@ -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 +#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 diff --git a/ios/core/src/io/SngFormat.cpp b/ios/core/src/io/SngFormat.cpp new file mode 100644 index 0000000..acc65f4 --- /dev/null +++ b/ios/core/src/io/SngFormat.cpp @@ -0,0 +1,302 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "io/SngFormat.hpp" + +#include +#include +#include +#include +#include +#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::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; + +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 or -1 for none). */ +std::pair 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 blocksToKeep(const std::vector &lines, size_t slots) { + std::vector 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 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(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 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 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 diff --git a/ios/core/src/io/SngFormat.hpp b/ios/core/src/io/SngFormat.hpp new file mode 100644 index 0000000..3bc31e4 --- /dev/null +++ b/ios/core/src/io/SngFormat.hpp @@ -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 +#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 diff --git a/ios/core/src/model/Model.cpp b/ios/core/src/model/Model.cpp index 58cbfaf..3c03458 100644 --- a/ios/core/src/model/Model.cpp +++ b/ios/core/src/model/Model.cpp @@ -4,8 +4,8 @@ #include "sizzle/Model.hpp" #include -#include #include +#include #include #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(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 diff --git a/ios/core/tests/engine_test.cpp b/ios/core/tests/engine_test.cpp new file mode 100644 index 0000000..4ab3680 --- /dev/null +++ b/ios/core/tests/engine_test.cpp @@ -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 /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 +#include +#include +#include +#include +#include +#include +#include +#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 readF32(const std::string &path) { + std::ifstream f(path, std::ios::binary); + std::vector bytes((std::istreambuf_iterator(f)), {}); + std::vector 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(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 split(const std::string &s, char c) { + std::vector 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 [SONG ...]\n", argv[0]); return 2; } + std::string dir = argv[1]; + std::vector 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 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 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; +} diff --git a/ios/core/tests/io_test.cpp b/ios/core/tests/io_test.cpp new file mode 100644 index 0000000..ab34a00 --- /dev/null +++ b/ios/core/tests/io_test.cpp @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#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 &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(f), {}); + return true; +} + +std::vector listDir(const std::string &dir, const std::string &suffix) { + std::vector 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] : "", y = i < b.size() ? b[i] : ""; + 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 ` 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 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 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 \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; +} diff --git a/versions.properties b/versions.properties index d75d871..294a448 100644 --- a/versions.properties +++ b/versions.properties @@ -17,8 +17,8 @@ android.versionCode = 70 # iOS/iPadOS (cc.tiredsysadmin.ios.sizzle): the AUv3 plugin app in ios/app; the # Makefile there passes these to Xcode and names the .ipa by versionCode. (The # TrollStore spike in ios/spike keeps its own version in its project.yml.) -ios.versionName = 0.3.0 -ios.versionCode = 6 +ios.versionName = 0.3.1 +ios.versionCode = 7 macos.versionName = - linux.versionName = - bsd.versionName = -