0.37.0 (71): one engine, one version for Android and iOS

- Three source trees: core/ (shared C++ engine, moved from ios/core),
  app/ (Android UI), ios/app/ (iOS UI)
- Android plays through core/ via JNI (EngineHost, jni_engine.cpp): the Oboe
  callback renders natively; the Kotlin model is mirrored as project text and
  applied as a diff, so playback continues through edits
- The Kotlin engine moves to the unit tests as ReferenceEngine (golden reference)
- Shared MasterRecorder in core/src/host, used by both apps; host_test
- versions.properties: one versionName/versionCode for both platforms,
  continuing Android's numbering (iOS 0.6.0/11 -> 0.37.0/71)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-16 14:49:46 +01:00
co-authored by Claude Opus 5.5
parent 64e21e0bcc
commit 2bc5cb1cbb
107 changed files with 2921 additions and 1880 deletions
+65
View File
@@ -0,0 +1,65 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "sizzle/Params.hpp"
#include <cctype>
#include <cstdio>
namespace sizzle {
void Params::fill(const DeviceSpec &spec) {
n_ = 0;
for (int i = 0; i < spec.paramCount; ++i) {
const ParamSpec &p = spec.params[i];
if (p.isEnum()) {
int idx = (int)p.def;
int n = p.choiceCount();
if (idx < 0) idx = 0;
if (idx > n - 1) idx = n - 1;
set(p.key, p.choices[idx]);
} else {
set(p.key, p.def);
}
}
}
int Params::find(const char *key) const {
for (int i = 0; i < n_; ++i) if (std::strcmp(keys_[i], key) == 0) return i;
return -1;
}
void Params::set(const char *key, const char *value) {
int i = find(key);
if (i < 0) {
if (n_ >= kMax) return;
i = n_++;
std::snprintf(keys_[i], kKeyLen, "%s", key);
}
std::snprintf(vals_[i], kValLen, "%s", value);
}
void Params::set(const char *key, float value) {
// Shortest text that reads back as the same float (Kotlin stores toString()).
char buf[kValLen];
std::snprintf(buf, sizeof buf, "%.9g", (double)value);
set(key, buf);
}
float Params::f(const char *key, float fallback) const {
int i = find(key);
if (i < 0) return fallback;
const char *s = vals_[i];
while (std::isspace((unsigned char)*s)) ++s;
if (!*s) return fallback;
char *end = nullptr;
float v = std::strtof(s, &end);
while (end && std::isspace((unsigned char)*end)) ++end;
return (end && *end == '\0') ? v : fallback;
}
const char *Params::s(const char *key, const char *fallback) const {
int i = find(key);
return i < 0 ? fallback : vals_[i];
}
} // namespace sizzle
+14
View File
@@ -0,0 +1,14 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include <cstring>
#include "sizzle/DeviceSpecs.gen.hpp"
namespace sizzle {
const DeviceSpec *findDevice(const char *type) {
for (const auto &d : gen::devices) if (std::strcmp(d.type, type) == 0) return &d;
return nullptr;
}
} // namespace sizzle
+30
View File
@@ -0,0 +1,30 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Weak placeholders for the TestVoice makers (see TestVoice.hpp): a port's strong
// definition replaces its placeholder at link time.
#include <cstring>
#include "sizzle/TestVoice.hpp"
#define SIZZLE_TEST_MAKER(fn) \
__attribute__((weak)) std::unique_ptr<TestVoice> fn(const TestVoiceSetup &) { return nullptr; }
namespace sizzle {
SIZZLE_TEST_MAKER(makeSynthTestVoice)
SIZZLE_TEST_MAKER(makeFrasilTestVoice)
SIZZLE_TEST_MAKER(makeWaveTestVoice)
SIZZLE_TEST_MAKER(makeGrainTestVoice)
SIZZLE_TEST_MAKER(makeSampleTestVoice)
std::unique_ptr<TestVoice> makeTestVoice(const char *kind, const TestVoiceSetup &s) {
if (!std::strcmp(kind, "SYNTH")) return makeSynthTestVoice(s);
if (!std::strcmp(kind, "FRASIL")) return makeFrasilTestVoice(s);
if (!std::strcmp(kind, "WAVE")) return makeWaveTestVoice(s);
if (!std::strcmp(kind, "GRAIN")) return makeGrainTestVoice(s);
if (!std::strcmp(kind, "SAMPLE")) return makeSampleTestVoice(s);
return nullptr;
}
} // namespace sizzle
+57
View File
@@ -0,0 +1,57 @@
// SPDX-FileCopyrightText: 2026 Philip Bos (ECHOFIELD)
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown (port for Sizzle)
// SPDX-License-Identifier: MIT
#pragma once
// Port of EchofieldDefs.kt: the Grain Cloud's choice lists and factory presets.
// The parameter specs themselves come from DeviceSpecs.gen.hpp (GRAIN_CLOUD).
namespace sizzle::echofield {
inline constexpr const char *MODES[] = {"Cloud", "Dust", "Tape", "Bloom", "Pulse", "Drift"};
inline constexpr int MODE_COUNT = 6;
inline constexpr const char *WINDOWS[] = {"Auto", "Hann", "Tukey", "Perc", "Swell", "Gauss"};
inline constexpr int WINDOW_COUNT = 6;
inline constexpr const char *CUSTOM = "Custom";
/** The built-in sources (synthesised, see GrainSources), then your own. */
inline constexpr const char *SOURCES[] = {
"Felt Piano", "Bowed Glass", "Music Box", "Warm Pad", "Strings",
"Low Drone", "Rain Field", "Kalimba", "Breath Choir", "Glass Tines", "Custom",
};
inline constexpr int SOURCE_COUNT = 11;
inline constexpr int BUILTIN_SOURCE_COUNT = 10;
/** Where a custom sample's id lives (the SF2/XI loader's key). */
inline constexpr const char *SAMPLE_KEY = "sfSample";
/** A factory preset: every other setting at its default (ParamSpec), then these. */
struct PresetValue { const char *key; float value; };
struct Preset {
const char *name;
const char *source;
int mode;
PresetValue values[8];
int count;
};
/** ECHOFIELD's 14 factory presets (presets.c FACTORY), as in EchofieldDefs.FACTORY. */
inline constexpr Preset FACTORY[] = {
{"Felt Clouds", "Felt Piano", 0, {{"texture", 0.78f}, {"scatter", 0.50f}, {"drift", 0.35f}, {"motion", 0.30f}, {"harmony", 0.35f}}, 5},
{"Glass Choir", "Bowed Glass", 3, {{"texture", 0.70f}, {"scatter", 0.40f}, {"drift", 0.30f}, {"motion", 0.35f}, {"harmony", 0.50f}}, 5},
{"Dust Lights", "Music Box", 1, {{"texture", 0.45f}, {"scatter", 0.70f}, {"drift", 0.30f}, {"motion", 0.40f}, {"harmony", 0.30f}}, 5},
{"Warm Tide", "Warm Pad", 5, {{"texture", 0.70f}, {"scatter", 0.45f}, {"drift", 0.55f}, {"motion", 0.40f}, {"harmony", 0.25f}}, 5},
{"Slow Tapes", "Strings", 2, {{"texture", 0.60f}, {"scatter", 0.25f}, {"drift", 0.40f}, {"motion", 0.35f}, {"harmony", 0.15f}}, 5},
{"Deep Water", "Low Drone", 0, {{"texture", 0.85f}, {"scatter", 0.40f}, {"drift", 0.40f}, {"motion", 0.25f}, {"harmony", 0.40f}}, 5},
{"Rain Cathedral", "Rain Field", 0, {{"texture", 0.88f}, {"scatter", 0.60f}, {"drift", 0.40f}, {"motion", 0.30f}, {"harmony", 0.45f}}, 5},
{"Kalimba Steps", "Kalimba", 4, {{"texture", 0.40f}, {"scatter", 0.60f}, {"drift", 0.30f}, {"motion", 0.30f}, {"harmony", 0.20f}}, 5},
{"Hymn", "Breath Choir", 0, {{"texture", 0.85f}, {"scatter", 0.45f}, {"drift", 0.35f}, {"motion", 0.30f}, {"harmony", 0.40f}}, 5},
{"Breath Choir", "Breath Choir", 3, {{"texture", 0.75f}, {"scatter", 0.50f}, {"drift", 0.40f}, {"motion", 0.40f}, {"harmony", 0.35f}}, 5},
{"Night Current", "Low Drone", 5, {{"texture", 0.65f}, {"scatter", 0.40f}, {"drift", 0.60f}, {"motion", 0.40f}}, 4},
{"Glass Rain", "Glass Tines", 1, {{"texture", 0.35f}, {"scatter", 0.55f}, {"drift", 0.20f}, {"motion", 0.50f}, {"pitch", 12.f}, {"reverse", 0.20f}, {"grain_tone", 0.40f}}, 7},
{"Broken Stars", "Kalimba", 3, {{"texture", 0.60f}, {"scatter", 0.70f}, {"drift", 0.50f}, {"motion", 0.50f}}, 4},
{"Far Broadcast", "Rain Field", 2, {{"texture", 0.50f}, {"scatter", 0.20f}, {"drift", 0.40f}, {"motion", 0.40f}}, 4},
};
inline constexpr int FACTORY_COUNT = 14;
} // namespace sizzle::echofield
+620
View File
@@ -0,0 +1,620 @@
// SPDX-FileCopyrightText: 2026 Philip Bos (ECHOFIELD)
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown (port for Sizzle)
// SPDX-License-Identifier: MIT
// Port of echofield/GrainCloud.kt, line for line with the same names and Float
// precision. No FMA contraction: the grains draw random numbers against
// thresholds, so a one-ulp difference would change which grains are born.
#pragma clang fp contract(off)
#include "GrainCloud.hpp"
#include <algorithm>
#include <cmath>
#include <cstring>
#include "EchofieldDefs.hpp"
#include "GrainSources.hpp"
#include "KotlinMath.hpp"
namespace sizzle::echofield {
namespace {
using kt::coerceIn;
using kt::expf_;
using kt::powf_;
using kt::sinf_;
using kt::cosf_;
using kt::sqrtf_;
constexpr int WIN_N = 256;
constexpr float STEP_MAX = 4.f;
constexpr float LOAD_MAX = 56.f;
constexpr float AGC_TARGET = 0.126f;
/** Brings the auto-levelled cloud to about the level of a Sizzle synth note. */
constexpr float OUT_GAIN = 1.0f;
constexpr float TWO_PI = 6.2831853f;
constexpr float PI_F = 3.14159265f;
constexpr int WIN_HANN = 0, WIN_TUKEY = 1, WIN_PERC = 2, WIN_SWELL = 3, WIN_GAUSS = 4, WIN_COUNT = 5;
constexpr float HARMONY_IV[] = {12.f, 12.f, -12.f, 7.f, 19.f, 24.f, -5.f, 7.f};
constexpr float TAPE_HR[] = {1.f, 0.5f, 2.f};
constexpr float TAPE_HA[] = {1.f, 0.8f, 0.4f};
constexpr float DUST_LEAP[] = {12.f, 19.f, 24.f, 7.f, -12.f};
constexpr float BLOOM_PART[] = {0.f, 12.f, 7.f, -12.f};
inline float ffloor(float x) { return (float)std::floor((double)x); }
inline float semis(float st) { return powf_(2.f, st / 12.f); }
inline float lerp(float a, float b, float t) { return a + (b - a) * t; }
inline float flush(float x) { return (x > -1e-20f && x < 1e-20f) ? 0.f : x; }
inline bool isFinite(float x) { return std::isfinite(x); }
int euclid(int k, int n, int rot) {
int pat = 0;
if (k <= 0) return 0;
for (int i = 0; i < n; ++i) if ((i * k) % n < k) pat = pat | (1 << ((i + rot) % n));
return pat;
}
int indexOfChoice(const char *const *list, int n, const char *s) {
for (int i = 0; i < n; ++i) if (std::strcmp(list[i], s) == 0) return i;
return -1;
}
/** The grain windows (ef_window), 0..1 over WIN_N + 2 points. */
struct WinTab {
float t[WIN_COUNT][WIN_N + 2];
WinTab() {
for (int w = 0; w < WIN_COUNT; ++w)
for (int i = 0; i < WIN_N + 2; ++i) t[w][i] = GrainCloud::window(w, (float)i / WIN_N);
}
};
const WinTab &winTab() { static const WinTab tab; return tab; }
} // namespace
// ------------------------------------------------------------------- patch ---
GrainPatch GrainPatch::from(const Params *slot, float tempoBpm) {
GrainPatch g;
float *p = g.p;
auto f = [&](int i, const char *key, float def) { p[i] = slot ? slot->f(key, def) : def; };
using C = GrainCloud;
f(C::P_POSITION, "position", 0.35f); f(C::P_TEXTURE, "texture", 0.72f);
f(C::P_SCATTER, "scatter", 0.45f); f(C::P_DRIFT, "drift", 0.35f);
f(C::P_MOTION, "motion", 0.35f); f(C::P_PITCH, "pitch", 0.f);
f(C::P_HARMONY, "harmony", 0.30f); f(C::P_SIZE_MUL, "size_mul", 0.f);
f(C::P_DENS_MUL, "dens_mul", 0.f); f(C::P_SCAN, "scan", 0.f);
f(C::P_REVERSE, "reverse", 0.10f); f(C::P_PITCH_RAND, "pitch_rand", 0.f);
f(C::P_SIZE_RAND, "size_rand", 0.3f); f(C::P_GRAIN_TONE, "grain_tone", -0.1f);
f(C::P_ATTACK, "attack", 0.15f); f(C::P_RELEASE, "release", 0.45f);
f(C::P_VELO, "velo", 0.5f); f(C::P_START, "start", 0.f); f(C::P_END, "end", 1.f);
f(C::P_LEVEL, "level", 0.75f);
p[C::P_MODE] = (float)std::max(0, indexOfChoice(MODES, MODE_COUNT, slot ? slot->s("mode", "Cloud") : "Cloud"));
p[C::P_WINDOW] = (float)std::max(0, indexOfChoice(WINDOWS, WINDOW_COUNT, slot ? slot->s("window", "Auto") : "Auto"));
p[C::P_FREEZE] = (slot && std::strcmp(slot->s("freeze", "Off"), "On") == 0) ? 1.f : 0.f;
const char *src = slot ? slot->s("source", SOURCES[0]) : SOURCES[0];
if (std::strcmp(src, CUSTOM) == 0) g.source = SOURCE_CUSTOM;
else { int i = GrainSources::indexOf(src); g.source = i >= 0 ? i : SOURCE_NONE; }
const char *id = slot ? slot->s(SAMPLE_KEY, "") : "";
std::strncpy(g.sampleId, id, ID_LEN - 1);
g.sampleId[ID_LEN - 1] = 0;
g.tempoBpm = tempoBpm;
return g;
}
uint32_t GrainSeeds::next() {
seeds += 0x6D2B79F5u;
return seeds == 0 ? 0x1234567u : seeds;
}
uint32_t GrainSeeds::nth(int n) {
GrainSeeds s;
uint32_t v = 0;
for (int i = 0; i < n; ++i) v = s.next();
return v;
}
// ------------------------------------------------------------------- cloud ---
GrainCloud::GrainCloud(int fs_, uint32_t seed)
: fsf((float)fs_),
smoothA(1.f - expf_((float)-SUB / (0.04f * (float)fs_))),
playK(1.f - powf_(0.99f, 44100.f / (float)fs_)),
rng(seed) {
winTab();
for (int i = 0; i < 16; ++i) stepPos[i] = rndf();
}
bool GrainCloud::isActive() const {
if (nNotes > 0 || env > 0.0005f || playGain > 0.0005f) return true;
for (int k = 0; k < MAX_GRAINS; ++k) if (gOn[k]) return true;
return false;
}
void GrainCloud::noteOn(int note, int velocity, int owner) {
for (int k = 0; k < nNotes; ++k) if (noteNum[k] == note) { noteVel[k] = velocity; noteOwner[k] = owner; noteSeq++; return; }
if (nNotes == MAX_NOTES) removeAt(0); // the oldest makes room
noteNum[nNotes] = note; noteVel[nNotes] = velocity; noteOwner[nNotes] = owner;
nNotes++;
noteSeq++;
}
void GrainCloud::noteOff(int note) {
int k = 0;
while (k < nNotes) if (noteNum[k] == note) removeAt(k); else k++;
}
void GrainCloud::releaseOwner(int owner) {
int k = 0;
while (k < nNotes) if (noteOwner[k] == owner) removeAt(k); else k++;
}
void GrainCloud::releaseSequenced() {
int k = 0;
while (k < nNotes) if (noteOwner[k] != OWNER_LIVE) removeAt(k); else k++;
}
void GrainCloud::kill() {
nNotes = 0; heldN = 0; env = 0.f; playGain = 0.f;
std::fill(gOn, gOn + MAX_GRAINS, false); loadNow = 0.f; pos = SUB;
}
void GrainCloud::removeAt(int k) {
for (int i = k; i < nNotes - 1; ++i) { noteNum[i] = noteNum[i + 1]; noteVel[i] = noteVel[i + 1]; noteOwner[i] = noteOwner[i + 1]; }
nNotes--;
}
float GrainCloud::render() {
if (pos >= SUB) { block(); pos = 0; }
return bus[pos++];
}
// ------------------------------------------------------------------- block ---
void GrainCloud::block() {
if (!hasPatch) { std::fill(bus, bus + SUB, 0.f); return; }
const GrainPatch &pt = patch;
float dt = SUB / fsf;
for (int i = 0; i < P_COUNT; ++i) {
float t = pt.p[i];
sm[i] = (!smPrimed || i == P_MODE || i == P_WINDOW || i == P_FREEZE) ? t : sm[i] + (t - sm[i]) * smoothA;
}
smPrimed = true;
// a new source: fade out, swap, fade in
const Sample *want = pt.source >= 0 ? GrainSources::get(pt.source)
: pt.source == GrainPatch::SOURCE_CUSTOM && lookup ? lookup(lookupCtx, pt.sampleId) : nullptr;
if (want && want->data.size() < 512) want = nullptr;
if (want != src) {
if (src == nullptr || fadeGain <= 0.f) {
src = want;
std::fill(gOn, gOn + MAX_GRAINS, false); loadNow = 0.f;
tapeHead = 0.f;
fadeGain = 0.f;
} else {
fadeGain = std::max(0.f, fadeGain - SUB / (0.02f * fsf));
}
} else if (fadeGain < 1.f) {
fadeGain = std::min(1.f, fadeGain + SUB / (0.02f * fsf));
}
// the gate: keys open it with their attack, release closes it
float atk = 0.005f * powf_(800.f, sm[P_ATTACK]);
float rel = 0.01f * powf_(800.f, sm[P_RELEASE]);
float envTarget = nNotes > 0 ? 1.f : 0.f;
env += (envTarget - env) * std::min(1.f, dt / (envTarget > env ? atk : rel));
computeCtl(dt);
const Sample *s = src;
if (cTape && s != nullptr && !frozen()) {
float a = std::min(sm[P_START], sm[P_END]), b = std::max(sm[P_START], sm[P_END]);
float rlen = std::max(512.f, (b - a) * (float)(int)s->data.size());
tapeHead += cTapeSpeed * SUB * ((float)s->sampleRate / fsf) / rlen;
tapeHead -= ffloor(tapeHead);
}
std::fill(bus, bus + SUB, 0.f);
if (want == src) schedule();
renderGrains();
for (int i = 0; i < SUB; ++i) {
playGain += (env - playGain) * playK;
bus[i] *= playGain * fadeGain;
}
autoLevel();
float level = sm[P_LEVEL] * OUT_GAIN;
for (int i = 0; i < SUB; ++i) {
float y = bus[i] * level;
bus[i] = isFinite(y) ? y : 0.f;
}
}
float GrainCloud::regionSeconds() const {
const Sample *s = src;
if (!s) return 1.f;
float a = std::min(sm[P_START], sm[P_END]), b = std::max(sm[P_START], sm[P_END]);
return (b - a) * (float)(int)s->data.size() / (float)s->sampleRate;
}
void GrainCloud::computeCtl(float dt) {
int mode = kt::toInt(sm[P_MODE]);
float t = sm[P_TEXTURE], sc = sm[P_SCATTER], d = sm[P_DRIFT], m = sm[P_MOTION];
float sizeMul = powf_(2.f, sm[P_SIZE_MUL]), densMul = powf_(2.f, sm[P_DENS_MUL]);
if (!frozen()) {
lfo1 += dt * (0.03f + 0.3f * m);
if (lfo1 > 1.f) lfo1 -= 1.f;
lfo2T += dt * (0.1f + 1.5f * m);
if (lfo2T >= 1.f) { lfo2T -= 1.f; lfo2Tgt = rndb(); }
lfo2Cur += (lfo2Tgt - lfo2Cur) * std::min(1.f, dt * (0.5f + 3.f * m));
float wr = (mode == MODE_DRIFT ? 0.25f + 1.2f * m : 0.08f + 0.4f * m) * dt;
{ float r = rndb(); walkV1 += r * wr * 2.f - walkV1 * wr * 2.f; }
walkPos = coerceIn(walkPos + walkV1 * wr * 4.f - walkPos * wr * 0.3f, -1.f, 1.f);
{ float r = rndb(); walkV2 += r * wr * 2.f - walkV2 * wr * 2.f; }
walkPitch = coerceIn(walkPitch + walkV2 * wr * 4.f - walkPitch * wr * 0.3f, -1.f, 1.f);
{ float r = rndb(); walkSize += (r - walkSize) * dt * 0.3f; }
if (src != nullptr) {
scan += sm[P_SCAN] * dt / std::max(0.05f, std::fabs(regionSeconds()));
scan -= ffloor(scan);
}
}
float lfo = sinf_(TWO_PI * lfo1);
float pos0 = sm[P_POSITION];
cJitter = 0.5f;
cPitchRand = sm[P_PITCH_RAND] + 0.08f + d * 0.3f;
cRevProb = sm[P_REVERSE];
cAmp = 1.f;
cTone = sm[P_GRAIN_TONE];
cToneRand = 0.f;
cWin = WIN_HANN;
cClocked = false;
cTape = false;
cTapeSpeed = 1.f;
float wander = d * 0.3f * walkPos;
switch (mode) {
case MODE_DUST:
cSize = 0.02f * powf_(200.f / 20.f, t);
cDensity = (6.f + 24.f * (1.f - t * 0.5f)) * (0.5f + sc);
cJitter = 0.7f + 0.3f * sc;
cCenter = pos0 + 0.1f * m * lfo + wander;
cScatter = 0.1f + 0.85f * sc;
cRevProb += 0.2f + 0.3f * sc;
cWin = WIN_GAUSS;
cAmp = 0.85f;
cTone = coerceIn(sm[P_GRAIN_TONE] + 0.25f, -1.f, 1.f);
cToneRand = 0.3f;
break;
case MODE_TAPE: {
float target = semis(sm[P_PITCH]) * lerp(1.f, 0.3f, powf_(t, 1.2f));
target *= 1.f + 0.03f * m * lfo2Cur + 0.02f * d * walkPitch;
if (!frozen() && tapeStop <= 0.f && rndf() < m * 0.02f * dt) tapeStop = 1.6f;
if (tapeStop > 0.f) {
tapeStop -= dt;
float ph = 1.6f - tapeStop;
target *= ph < 0.8f ? 1.f - ph / 0.8f : (ph - 0.8f) / 0.8f;
target = std::max(target, 0.02f);
}
tapeSpeed += (target - tapeSpeed) * std::min(1.f, dt * 6.f);
cTape = true;
cTapeSpeed = tapeSpeed;
cSize = 0.18f * (1.f + t);
cDensity = 4.f / cSize;
cJitter = 0.15f;
cCenter = tapeHead;
cScatter = 0.002f + sc * 0.03f;
cPitchRand = sm[P_PITCH_RAND];
break;
}
case MODE_BLOOM:
cSize = 0.6f * powf_(2.5f / 0.6f, t);
cDensity = (3.f + 3.f * t) / cSize * (1.f + 0.5f * m * lfo2Cur);
cJitter = 0.9f;
cCenter = pos0 + 0.2f * m * lfo + wander;
cScatter = 0.08f + 0.5f * sc;
cRevProb += 0.25f;
cTone = coerceIn(sm[P_GRAIN_TONE] + 0.15f, -1.f, 1.f);
cToneRand = 0.25f;
cWin = rndf() < 0.5f ? WIN_HANN : WIN_GAUSS;
cAmp = 0.95f;
break;
case MODE_PULSE:
cClocked = true;
cSize = 0.06f * powf_(1200.f / 60.f, t);
cDensity = 0.f;
cCenter = pos0 + wander;
cScatter = sc;
cWin = t > 0.6f ? WIN_HANN : WIN_PERC;
cJitter = 0.f;
break;
case MODE_DRIFT:
cSize = 0.1f * powf_(12.f, t) * (1.f + 0.5f * walkSize);
cDensity = (2.f + 4.f * t) * (1.f + 0.5f * lfo) / cSize;
cJitter = 0.8f;
cCenter = pos0 + walkPos * (0.1f + 0.5f * sc);
cScatter = 0.03f + 0.3f * sc;
cPitchRand = sm[P_PITCH_RAND] + d * 0.5f;
cRevProb += 0.15f;
cWin = WIN_GAUSS;
break;
default: // CLOUD
cSize = 0.12f * powf_(1500.f / 120.f, t);
cDensity = (4.f + 8.f * t) / cSize * (1.f + 0.4f * m * lfo2Cur);
cJitter = 0.4f + 0.6f * sc;
cCenter = pos0 + 0.15f * m * lfo + wander;
cScatter = 0.03f + 0.6f * powf_(sc, 1.3f);
cRevProb += sc * 0.1f;
break;
}
cSize *= sizeMul;
cDensity *= densMul;
int wsel = kt::toInt(sm[P_WINDOW]);
if (wsel > 0) cWin = wsel - 1;
cRevProb = coerceIn(cRevProb, 0.f, 1.f);
cSize = coerceIn(cSize, 0.004f, 2.5f);
cDensity = coerceIn(cDensity, 0.f, 400.f);
cScatter = coerceIn(cScatter, 0.f, 1.f);
if (!cTape) { float cc = cCenter + scan; cCenter = cc - ffloor(cc); }
}
// ------------------------------------------------------------------ grains ---
void GrainCloud::notesTrack() {
if (nNotes == 0) return;
for (int k = 0; k < nNotes; ++k) { heldNote[k] = noteNum[k] - 60; heldVel[k] = noteVel[k]; }
heldN = nNotes;
}
float GrainCloud::notePitch() {
if (heldN == 0) return 0.f;
int k = (int)((noteRr++ & 0x7FFFFFFFu) % (uint32_t)heldN);
float velo = sm[P_VELO];
ampScale *= (1.f - velo) + velo * (float)heldVel[k] / 127.f;
return (float)heldNote[k];
}
void GrainCloud::spawn(int offset, float amp0, float extraPitch, float posOverride) {
const Sample *s = src;
if (!s) return;
int frames = (int)s->data.size();
int g = -1;
int active = 0;
for (int i = 0; i < MAX_GRAINS; ++i) { if (gOn[i]) active++; else if (g < 0) g = i; }
if (g < 0 || active >= MAX_GRAINS) return;
float ra = std::min(sm[P_START], sm[P_END]), rb = std::max(sm[P_START], sm[P_END]);
float rs = ra * (float)frames, re = rb * (float)frames;
if (re - rs < 512.f) { re = std::min((float)frames - 1.f, rs + 512.f); rs = std::max(0.f, re - 512.f); }
re = std::min(re, (float)frames - 2.f);
float rlen = re - rs;
if (rlen < 64.f) return;
float size = cSize * (1.f + rndb() * sm[P_SIZE_RAND] * 0.7f * (cTape ? 0.3f : 1.f));
int len = kt::toInt(std::max(size, 0.003f) * fsf);
ampScale = amp0;
float pitch = sm[P_PITCH];
pitch = pitch + notePitch();
float harm = 0.f;
if (rndf() < sm[P_HARMONY] * 0.65f) {
harm = HARMONY_IV[nextRand() & 7u];
ampScale *= 0.7f;
}
float step;
if (cTape) {
int head = tapeK;
tapeK = (tapeK + 1) % 3;
step = cTapeSpeed * TAPE_HR[head] * semis(harm + (pitch - sm[P_PITCH]));
ampScale *= TAPE_HA[head];
tapeGrainHead = head;
} else {
float st = pitch + harm + extraPitch;
st = st + rndb() * cPitchRand;
st = coerceIn(st + walkPitch * sm[P_DRIFT] * 2.f, -48.f, 36.f);
step = semis(st);
}
step *= (float)s->sampleRate / fsf;
step = coerceIn(step, 1.f / 64.f, STEP_MAX);
if (loadNow + 1.f + step > LOAD_MAX) return;
if (len < 64) len = 64;
float span = (float)len * step;
if (span > rlen * 0.98f) { len = kt::toInt(rlen * 0.98f / step); span = (float)len * step; }
if (len < 32) return;
bool rev = rndf() < cRevProb;
float center = posOverride >= 0.f ? posOverride : cCenter + rndb() * cScatter * 0.5f;
if (cTape) center = cCenter + (float)tapeGrainHead / 3.f + rndb() * cScatter;
center -= ffloor(center);
float cpos = rs + center * rlen;
float start = !rev ? coerceIn(cpos - span * 0.5f, rs, re - span) : coerceIn(cpos + span * 0.5f, rs + span, re - 1.f);
gPos[g] = (double)std::max(start, 0.f);
gInc[g] = (double)step;
gRev[g] = rev;
gLen[g] = len;
gAge[g] = 0;
gDelay[g] = offset;
gWin[g] = coerceIn(cWin, 0, WIN_COUNT - 1);
gWph[g] = 0.f;
gWstep[g] = (float)WIN_N / (float)len;
gLoad[g] = 1.f + step;
float overlap = std::max(1.f, cDensity * cSize);
gAmp[g] = coerceIn(cAmp * ampScale * 0.75f / sqrtf_(overlap), 0.f, 1.9f);
float tone = coerceIn(cTone + rndb() * cToneRand, -1.f, 1.f);
if (std::fabs(tone) < 0.02f) gTone[g] = 0;
else if (tone < 0.f) { gTone[g] = 1; gToneA[g] = onepole(std::min(18000.f * powf_(0.02f, -tone), std::min(20000.f, 0.45f * fsf))); }
else { gTone[g] = 2; gToneA[g] = onepole(150.f * powf_(30.f, tone)); }
gZ[g] = 0.f;
gOn[g] = true;
loadNow += gLoad[g];
}
void GrainCloud::renderGrains() {
const Sample *s = src;
if (!s) { std::fill(gOn, gOn + MAX_GRAINS, false); loadNow = 0.f; return; }
const float *data = s->data.data();
int last = (int)s->data.size() - 1;
float load = 0.f;
const WinTab &tab = winTab();
for (int k = 0; k < MAX_GRAINS; ++k) {
if (!gOn[k]) continue;
const float *w = tab.t[gWin[k]];
int i = gDelay[k];
gDelay[k] = 0;
double p = gPos[k];
double inc = gInc[k];
bool rev = gRev[k];
int tone = gTone[k];
float ta = gToneA[k];
float z = gZ[k];
float wph = gWph[k];
float wstep = gWstep[k];
float amp = gAmp[k];
int left = gLen[k] - gAge[k];
if (left > SUB - i) left = SUB - i;
gAge[k] += left;
while (left > 0) {
int idx = (int)p; // p stays within the sample, so Double.toInt's saturation never applies
if (p < 0.0 || idx >= last) { gAge[k] = gLen[k]; break; }
float fr = (float)(p - idx);
float x = data[idx] + (data[idx + 1] - data[idx]) * fr;
if (tone != 0) { z += (x - z) * ta; x = tone == 1 ? z : x - z; }
int wi = std::min(kt::toInt(wph), WIN_N);
float wv = w[wi] + (w[wi + 1] - w[wi]) * (wph - (float)wi);
bus[i] += x * wv * amp;
p = rev ? p - inc : p + inc;
wph = std::min(wph + wstep, (float)WIN_N);
i++; left--;
}
gPos[k] = p; gWph[k] = wph; gZ[k] = flush(z);
if (gAge[k] >= gLen[k]) gOn[k] = false; else load += gLoad[k];
}
loadNow = load;
}
void GrainCloud::schedule() {
notesTrack();
if (src == nullptr || (env <= 0.0005f && nNotes == 0)) return;
if (noteSeq != noteSeqSeen) { // a new key: two grains at once, so the key answers
noteSeqSeen = noteSeq;
if (!cClocked && nNotes > 0) { spawn(0, 1.f, 0.f, -1.f); spawn(0, 0.8f, 0.f, -1.f); }
}
if (cClocked) {
// PULSE: on the song's tempo, its 1/16, 1/8 or 1/4, whichever is nearest ECHOFIELD's own pace
float own = 30.f + 90.f * sm[P_MOTION];
float ext = hasPatch ? patch.tempoBpm : 0.f;
float bpm = own;
if (ext > 0.f) {
float best = 1e9f;
int dv = 1;
while (dv <= 4) {
float r = ext / (float)dv;
float e = r > own ? r / own : own / r;
if (e < best) { best = e; bpm = r; }
dv = dv << 1;
}
}
float stepSamples = fsf * 60.f / bpm / 4.f;
int kk = kt::toInt(coerceIn(5.f + sm[P_DENS_MUL] * 2.5f + 0.5f, 1.f, 16.f));
int pat = euclid(kk, 16, pulseRot);
for (int i = 0; i < SUB; ++i) {
pulseAcc -= 1.f;
if (pulseAcc <= 0.f) {
int st = pulseStep;
pulseAcc += stepSamples * (1.f + ((pulseStep & 1) == 1 ? 0.08f : -0.08f) * sm[P_DRIFT]);
pulseStep = (pulseStep + 1) & 15;
if (st == 0 && !frozen() && rndf() < sm[P_MOTION] * 0.35f) {
int j = kt::toInt(rndf() * 16.f) & 15;
stepPos[j] = rndf();
if (rndf() < sm[P_DRIFT] * 0.5f) stepOct[j] = rndf() < 0.5f ? 12 : 7;
else stepOct[j] = 0;
if (rndf() < sm[P_MOTION] * 0.3f) pulseRot = (pulseRot + 1) & 15;
}
if (((pat >> st) & 1) == 1) {
float p = cCenter + (stepPos[st] - 0.5f) * cScatter;
p -= ffloor(p);
spawn(i, st % 4 == 0 ? 1.1f : 0.77f, (float)stepOct[st], p);
}
}
}
return;
}
if (cDensity <= 0.f) return;
float mean = fsf / cDensity;
int mode = kt::toInt(sm[P_MODE]);
for (int i = 0; i < SUB; ++i) {
spawnWait -= 1.f;
if (spawnWait > 0.f) continue;
spawnWait += mean * (1.f - cJitter + cJitter * 2.f * rndf());
if (spawnWait < 1.f) spawnWait = 1.f;
switch (mode) {
case MODE_DUST: {
if (stutterLeft > 0) { stutterLeft--; spawn(i, 1.f, 0.f, stutterPos); continue; }
if (rndf() < sm[P_MOTION] * 0.05f) {
stutterLeft = 2 + kt::toInt(rndf() * 4.f);
float r = rndb();
stutterPos = cCenter + r * cScatter * 0.5f;
stutterPos -= ffloor(stutterPos);
}
float sp = rndf() < sm[P_SCATTER] * 0.35f ? DUST_LEAP[kt::toInt(rndf() * 5.f) % 5] : 0.f;
spawn(i, 1.f, sp, -1.f);
break;
}
case MODE_BLOOM: {
float r = rndf();
int k = r < 0.55f ? 0 : r < 0.75f ? 1 : r < 0.9f ? 2 : 3;
float a = 0.5f + 0.5f * rndf();
spawn(i, a, BLOOM_PART[k], -1.f);
break;
}
default: spawn(i, 1.f, 0.f, -1.f);
}
}
}
/** ECHOFIELD's auto-level: the cloud held near one loudness whatever its density or
* source; a tail that dies away is never pulled back up. */
void GrainCloud::autoLevel() {
float blk = SUB / fsf;
float ms = 0.f;
for (int i = 0; i < SUB; ++i) ms += bus[i] * bus[i];
ms /= SUB;
float g0 = agcGain;
agcMs += (ms - agcMs) * (1.f - expf_(-blk / 2.5f));
float target = agcGain;
if (agcMs > 1e-6f) target = coerceIn(AGC_TARGET / sqrtf_(agcMs), 0.5f, 4.f);
if (env <= 0.5f && target > agcGain) target = agcGain;
float tc = target < agcGain ? 0.4f : 2.5f;
agcGain += (target - agcGain) * (1.f - expf_(-blk / tc));
for (int i = 0; i < SUB; ++i) bus[i] *= g0 + (agcGain - g0) * (float)i / SUB;
}
// ----------------------------------------------------------------- helpers ---
float GrainCloud::onepole(float hz) const { return 1.f - expf_(-TWO_PI * hz / fsf); }
uint32_t GrainCloud::nextRand() {
uint32_t x = rng;
x = x ^ (x << 13); x = x ^ (x >> 17); x = x ^ (x << 5);
rng = x;
return x;
}
float GrainCloud::rndf() { return (float)(int32_t)(nextRand() >> 8) * (1.f / 16777216.f); }
float GrainCloud::window(int w, float x0) {
float x = coerceIn(x0, 0.f, 1.f);
switch (w) {
case WIN_TUKEY: {
float a = 0.3f;
if (x < a * 0.5f) return 0.5f - 0.5f * cosf_(TWO_PI * x / a);
if (x > 1.f - a * 0.5f) return 0.5f - 0.5f * cosf_(TWO_PI * (1.f - x) / a);
return 1.f;
}
case WIN_PERC: {
float att = 0.03f;
float v = x < att ? sinf_(0.5f * PI_F * x / att) : expf_(-5.f * (x - att) / (1.f - att));
if (x > 0.92f) v *= 0.5f + 0.5f * cosf_(PI_F * (x - 0.92f) / 0.08f);
return v;
}
case WIN_SWELL: return window(WIN_PERC, 1.f - x);
case WIN_GAUSS: {
float d = (x - 0.5f) / 0.16f;
float g = expf_(-0.5f * d * d);
float e = 0.00752f;
return coerceIn((g - e) / (1.f - e), 0.f, 1.f);
}
default: return 0.5f - 0.5f * cosf_(TWO_PI * x);
}
}
} // namespace sizzle::echofield
+197
View File
@@ -0,0 +1,197 @@
// SPDX-FileCopyrightText: 2026 Philip Bos (ECHOFIELD)
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown (port for Sizzle)
// SPDX-License-Identifier: MIT
#pragma once
// Port of echofield/GrainCloud.kt (ECHOFIELD's granular engine): one mixer
// channel's grain cloud. See the Kotlin for the musical description.
//
// Differences from the Kotlin, all about ownership rather than sound:
// - Kotlin seeds each GrainCloud from a global counter (companion `seeds`); here the
// seed is passed in. GrainSeeds reproduces the counter for an owner (the engine)
// that constructs clouds in the same order as AudioEngine.
// - The patch is a fixed-size value (no strings on the heap); setPatch copies it.
// - The custom source ("Custom", SampleStore.get(id) in Kotlin) goes through a
// lookup hook (setSampleLookup), asked once per 64-frame block like the Kotlin.
//
// Allocation- and lock-free after construction.
#include <cstdint>
#include "Sample.hpp"
#include "sizzle/Params.hpp"
namespace sizzle::echofield {
/** A parsed Grain Cloud slot (GrainPatch.kt): the smoothed settings' targets, the
* source to read and the song's tempo. Built off the hot path, per slot change. */
struct GrainPatch {
static constexpr int SOURCE_CUSTOM = -1; // the custom sample [sampleId]
static constexpr int SOURCE_NONE = -2; // a name that is no built-in source
static constexpr int ID_LEN = 64;
float p[23] = {};
/** Index into GrainSources (EchofieldDefs SOURCES), or SOURCE_CUSTOM / SOURCE_NONE. */
int source = 0;
char sampleId[ID_LEN] = {};
float tempoBpm = 120.f;
/** GrainPatch.from(slot, tempoBpm); [slot] may be null (all defaults). */
static GrainPatch from(const Params *slot, float tempoBpm);
};
/** The Kotlin companion's seed counter (GrainCloud.nextSeed), made explicit. */
struct GrainSeeds {
uint32_t seeds = 0x1234567;
uint32_t next();
/** The seed of the [n]-th cloud constructed (1-based) from a fresh counter. */
static uint32_t nth(int n);
};
class GrainCloud {
public:
static constexpr int P_POSITION = 0, P_TEXTURE = 1, P_SCATTER = 2, P_DRIFT = 3;
static constexpr int P_MOTION = 4, P_PITCH = 5, P_HARMONY = 6, P_SIZE_MUL = 7;
static constexpr int P_DENS_MUL = 8, P_SCAN = 9, P_REVERSE = 10, P_PITCH_RAND = 11;
static constexpr int P_SIZE_RAND = 12, P_WINDOW = 13, P_GRAIN_TONE = 14, P_ATTACK = 15;
static constexpr int P_RELEASE = 16, P_VELO = 17, P_START = 18, P_END = 19;
static constexpr int P_MODE = 20, P_FREEZE = 21, P_LEVEL = 22;
static constexpr int P_COUNT = 23;
/** A note from live input (keys, MIDI); OWNER_SEQ one the sequencer played with no track. */
static constexpr int OWNER_LIVE = -1;
static constexpr int OWNER_SEQ = -2;
static constexpr int SUB = 64;
static constexpr int MAX_GRAINS = 32;
static constexpr int MAX_NOTES = 8;
static constexpr int MODE_CLOUD = 0, MODE_DUST = 1, MODE_TAPE = 2;
static constexpr int MODE_BLOOM = 3, MODE_PULSE = 4, MODE_DRIFT = 5;
/** Resolves a custom sample id to its data (the sample store), or nullptr. Called
* on the audio thread once per block: must not block or allocate. */
using SampleLookup = const Sample *(*)(void *ctx, const char *id);
/** [seed]: GrainSeeds::next() of the owner's counter (never 0). */
GrainCloud(int fs, uint32_t seed);
void setPatch(const GrainPatch &p) { patch = p; hasPatch = true; }
void setSampleLookup(SampleLookup fn, void *ctx) { lookup = fn; lookupCtx = ctx; }
void noteOn(int note, int velocity, int owner = OWNER_LIVE);
void noteOff(int note);
/** Let go of every note tracker track [owner] holds. */
void releaseOwner(int owner);
void releaseAll() { nNotes = 0; }
/** Let go of the sequencer's notes (owner >= 0 or OWNER_SEQ), keeping live ones. */
void releaseSequenced();
/** Silence now: every grain off, no tail. */
void kill();
float render();
/** Sounding: a note held, the gate's release still open, or a grain still playing. */
bool isActive() const;
/** The grain window [w] (ef_window) at [x0] in 0..1. */
static float window(int w, float x0);
private:
static constexpr int WIN_N = 256;
static constexpr int WIN_COUNT = 5;
void removeAt(int k);
void block();
bool frozen() const { return sm[P_FREEZE] >= 0.5f; }
float regionSeconds() const;
void computeCtl(float dt);
void notesTrack();
float notePitch();
void spawn(int offset, float amp0, float extraPitch, float posOverride);
void renderGrains();
void schedule();
void autoLevel();
float onepole(float hz) const;
uint32_t nextRand();
float rndf();
float rndb() { return rndf() * 2.f - 1.f; }
float fsf;
GrainPatch patch;
bool hasPatch = false;
SampleLookup lookup = nullptr;
void *lookupCtx = nullptr;
float sm[P_COUNT] = {};
bool smPrimed = false;
float smoothA, playK;
// grains
bool gOn[MAX_GRAINS] = {};
int gWin[MAX_GRAINS] = {};
bool gRev[MAX_GRAINS] = {};
int gTone[MAX_GRAINS] = {};
double gPos[MAX_GRAINS] = {};
double gInc[MAX_GRAINS] = {};
int gLen[MAX_GRAINS] = {};
int gAge[MAX_GRAINS] = {};
int gDelay[MAX_GRAINS] = {};
float gWph[MAX_GRAINS] = {};
float gWstep[MAX_GRAINS] = {};
float gAmp[MAX_GRAINS] = {};
float gToneA[MAX_GRAINS] = {};
float gZ[MAX_GRAINS] = {};
float gLoad[MAX_GRAINS] = {};
float loadNow = 0.f;
// the source and its swap fade
const Sample *src = nullptr;
float fadeGain = 1.f;
// modes
uint32_t rng; // xorshift state (Kotlin Int)
float spawnWait = 0.f, scan = 0.f;
float walkPos = 0.f, walkPitch = 0.f, walkV1 = 0.f, walkV2 = 0.f;
float walkSize = 0.f;
float lfo1 = 0.f, lfo2Cur = 0.f, lfo2Tgt = 0.f, lfo2T = 0.f;
float tapeHead = 0.f, tapeSpeed = 1.f, tapeStop = 0.f;
int tapeK = 0;
int stutterLeft = 0;
float stutterPos = 0.f;
int pulseStep = 0, pulseRot = 0;
float pulseAcc = 0.f;
float stepPos[16];
int stepOct[16] = {};
float env = 0.f;
float playGain = 0.f;
float agcMs = 0.f;
float agcGain = 1.f;
// notes held now (owner: the tracker track, or OWNER_LIVE)
int noteNum[MAX_NOTES] = {};
int noteVel[MAX_NOTES] = {};
int noteOwner[MAX_NOTES] = {};
int nNotes = 0;
uint32_t noteSeq = 0, noteSeqSeen = 0; // Kotlin Int, wrapping
// the notes grains are born on: those held, or while the release sounds, the last ones held
int heldNote[MAX_NOTES] = {};
int heldVel[MAX_NOTES] = {};
int heldN = 0;
uint32_t noteRr = 0;
// control values (ECHOFIELD's ctl_t), recomputed each sub-block
float cSize = 0.f, cDensity = 0.f, cJitter = 0.f, cCenter = 0.f;
float cScatter = 0.f, cPitchRand = 0.f, cRevProb = 0.f, cAmp = 1.f;
float cTone = 0.f, cToneRand = 0.f;
int cWin = 0;
bool cClocked = false;
bool cTape = false;
float cTapeSpeed = 1.f;
float ampScale = 1.f;
int tapeGrainHead = 0;
float bus[SUB] = {};
int pos = SUB;
};
} // namespace sizzle::echofield
+323
View File
@@ -0,0 +1,323 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of audio/GrainSources.kt, line for line, in the same (double) precision.
#pragma clang fp contract(off)
#include "GrainSources.hpp"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <mutex>
#include <thread>
#include <vector>
#include "EchofieldDefs.hpp"
namespace sizzle::echofield::GrainSources {
namespace {
constexpr double SECONDS = 6.0;
const int N = (int)(RATE * SECONDS);
using Buf = std::vector<float>;
// ------------------------------------------------------------------ helpers ---
constexpr double C4 = 261.6256;
double hz(int semisFromC4) { return C4 * std::pow(2.0, semisFromC4 / 12.0); }
constexpr double TAU = 2 * M_PI;
/** A struck note: partials (ratio, level, decay per second) from [t0] with a soft
* [attack], each partial's decay scaled by its ratio for brighter-dies-first. */
void strike(Buf &out, double t0, double f, const std::vector<std::vector<double>> &partials, double attack, double gain) {
int start = (int)(t0 * RATE);
for (const auto &p : partials) {
double fr = f * p[0];
if (fr > RATE * 0.45) continue;
double w = TAU * fr / RATE;
double ph = std::fmod(p[0] * 1.7, TAU);
for (int i = start; i < N; ++i) {
double t = (double)(i - start) / RATE;
double env = (t < attack ? t / attack : 1.0) * std::exp(-p[2] * t);
if (env < 1e-4 && t > attack) break;
out[i] += (float)(gain * p[1] * env * std::sin(ph));
ph += w;
}
}
}
/** A band-limited saw by its harmonics, with a slow vibrato. */
template <class Env>
void saw(Buf &out, double f, double gain, double vibHz, double vibCents, double phase, Env ampEnv) {
int maxK = std::min(std::max(1, (int)((RATE * 0.45) / f)), 40);
std::vector<double> phs(maxK);
for (int it = 0; it < maxK; ++it) phs[it] = phase * (it + 1);
for (int i = 0; i < N; ++i) {
double t = (double)i / RATE;
double fm = f * std::pow(2.0, vibCents * std::sin(TAU * vibHz * t + phase) / 1200.0);
double s = 0.0;
for (int k = 1; k <= maxK; ++k) {
phs[k - 1] += TAU * fm * k / RATE;
s += std::sin(phs[k - 1]) / k;
}
out[i] += (float)(gain * ampEnv(t) * s);
}
}
/** Kotlin's Int xorshift (wrapping, `ushr` logical). */
struct Rng {
uint32_t s;
explicit Rng(uint32_t seed) : s(seed) {}
uint32_t next() { uint32_t x = s; x ^= x << 13; x ^= x >> 17; x ^= x << 5; s = x; return x; }
double f() { return (int32_t)(next() >> 8) / 16777216.0; }
double b() { return f() * 2 - 1; }
};
/** A two-pole resonant band-pass (RBJ, constant peak gain) run over [x]. */
Buf bandpass(const Buf &x, double f, double q) {
double w = TAU * f / RATE;
double alpha = std::sin(w) / (2 * q);
double a0 = 1 + alpha;
double b0 = alpha / a0, b2 = -alpha / a0;
double a1 = -2 * std::cos(w) / a0, a2 = (1 - alpha) / a0;
Buf y(x.size());
double x1 = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0;
for (size_t i = 0; i < x.size(); ++i) {
double v = b0 * x[i] + b2 * x2 - a1 * y1 - a2 * y2;
x2 = x1; x1 = (double)x[i]; y2 = y1; y1 = v;
y[i] = (float)v;
}
return y;
}
void lowpass(Buf &x, double f) {
double a = 1 - std::exp(-TAU * f / RATE);
double z = 0.0;
for (size_t i = 0; i < x.size(); ++i) { z += a * (x[i] - z); x[i] = (float)z; }
}
Buf normalize(Buf x) {
float pk = 1e-9f;
for (float v : x) pk = std::max(pk, std::fabs(v));
float g = 0.89f / pk;
int fade = RATE / 50;
int size = (int)x.size();
for (int i = 0; i < size; ++i) {
float e = 1.f;
if (i < fade) e = (float)i / fade;
if (i > size - fade) e = (float)(size - i) / fade;
x[i] *= g * e;
}
return x;
}
// ------------------------------------------------------------------ recipes ---
const int PENT[] = {0, 2, 4, 7, 9, 12, 14, 16, 19, 21, 24};
Buf feltPiano() {
Buf out(N);
std::vector<std::vector<double>> partials(8);
for (int k = 0; k < 8; ++k)
partials[k] = {k + 1.0 + 0.0008 * (k + 1) * (k + 1), 1.0 / std::pow((double)(k + 1), 1.6), 0.9 + 0.7 * k};
const int melody[] = {0, 7, 4, 11, 2, 9, 7, 16, 12, 4, 14, 7};
for (int n = 0; n < 12; ++n) strike(out, 0.05 + n * 0.48, hz(melody[n]), partials, 0.006, 0.6);
lowpass(out, 3200.0);
return out;
}
Buf bowedGlass() {
Buf out(N);
const double ratios[] = {1.0, 2.32, 4.25, 6.63};
const double levels[] = {1.0, 0.45, 0.22, 0.1};
for (int k = 0; k < 4; ++k) {
double f = hz(12) * ratios[k];
double ph = k * 0.9;
for (int i = 0; i < N; ++i) {
double t = (double)i / RATE;
double env = (1 - std::exp(-t / 1.2)) * (0.85 + 0.15 * std::sin(TAU * 0.23 * t + k));
double vib = 1 + 0.0015 * std::sin(TAU * 4.6 * t);
ph += TAU * f * vib / RATE;
out[i] += (float)(levels[k] * env * std::sin(ph));
}
}
return out;
}
Buf musicBox() {
Buf out(N);
std::vector<std::vector<double>> partials = {{1.0, 1.0, 1.4}, {3.01, 0.32, 3.5}, {5.4, 0.14, 6.0}, {8.9, 0.05, 9.0}};
const int melody[] = {12, 16, 19, 24, 21, 19, 16, 14, 12, 19, 16, 24, 26, 24};
for (int n = 0; n < 14; ++n) strike(out, 0.04 + n * 0.41, hz(melody[n]), partials, 0.002, 0.5);
return out;
}
Buf kalimba() {
Buf out(N);
std::vector<std::vector<double>> partials = {{1.0, 1.0, 1.1}, {5.93, 0.22, 7.0}, {13.4, 0.06, 14.0}};
Rng rng(0x51A1);
double t = 0.03;
while (t < SECONDS - 0.8) {
strike(out, t, hz(PENT[(int)(rng.f() * 8)]), partials, 0.003, 0.55);
t += 0.28 + 0.3 * rng.f();
}
return out;
}
Buf glassTines() {
Buf out(N);
std::vector<std::vector<double>> partials = {{1.0, 1.0, 0.8}, {2.756, 0.4, 1.6}, {5.404, 0.18, 2.8}, {8.93, 0.07, 4.0}};
Rng rng(0x7123);
double t = 0.02;
while (t < SECONDS - 0.6) {
strike(out, t, hz(12 + PENT[(int)(rng.f() * 9)]), partials, 0.002, 0.4);
t += 0.17 + 0.25 * rng.f();
}
return out;
}
Buf warmPad() {
Buf out(N);
const int chord[] = {-12, 0, 4, 7, 11, 14};
for (int n = 0; n < 6; ++n) for (int d = 0; d < 2; ++d) {
double det = d == 0 ? -6.0 : 6.0;
saw(out, hz(chord[n]) * std::pow(2.0, det / 1200), 0.18, 0.2 + 0.05 * n, 4.0, n * 0.7 + d,
[](double t) { return 1 - std::exp(-t / 0.8); });
}
// a slow opening low-pass: three passes at a cutoff that rises over the sound
Buf a = out;
double z1 = 0.0, z2 = 0.0;
for (int i = 0; i < N; ++i) {
double t = (double)i / RATE;
double fc = 500 + 1800 * (0.5 - 0.5 * std::cos(TAU * t / SECONDS));
double k = 1 - std::exp(-TAU * fc / RATE);
z1 += k * (a[i] - z1); z2 += k * (z1 - z2);
out[i] = (float)z2;
}
return out;
}
Buf strings() {
Buf out(N);
const int voices[] = {-12, -5, 0, 4, 7};
for (int n = 0; n < 5; ++n) for (int d = 0; d < 3; ++d) {
double det = (d - 1) * 7.0;
saw(out, hz(voices[n]) * std::pow(2.0, det / 1200), 0.14, 5.1 + 0.4 * d, 9.0, n * 1.3 + d * 0.5,
[n](double t) { return (1 - std::exp(-t / 0.45)) * (0.8 + 0.2 * std::sin(TAU * 0.3 * t + n)); });
}
lowpass(out, 2600.0); lowpass(out, 5000.0);
return out;
}
Buf lowDrone() {
Buf out(N);
const double parts[][2] = {{hz(-24), 1.0}, {hz(-24) * 2.003, 0.5}, {hz(-17), 0.55},
{hz(-17) * 2.0, 0.25}, {hz(-12) * 1.002, 0.3}, {hz(-24) * 3.0, 0.18}};
for (int n = 0; n < 6; ++n) {
const double *p = parts[n];
double ph = n * 1.1;
for (int i = 0; i < N; ++i) {
double t = (double)i / RATE;
ph += TAU * p[0] / RATE;
double am = 0.75 + 0.25 * std::sin(TAU * (0.11 + 0.07 * n) * t + n);
out[i] += (float)(p[1] * am * (std::sin(ph) + 0.15 * std::sin(2 * ph)));
}
}
return out;
}
Buf breathChoir() {
Rng rng(0x0B2E);
Buf noise(N);
for (int i = 0; i < N; ++i) noise[i] = (float)rng.b();
// a voiced source under the breath: a soft buzz at C4 and its fifth
Buf buzz(N);
saw(buzz, hz(0), 0.25, 5.0, 8.0, 0.0, [](double t) { return 1 - std::exp(-t / 0.6); });
saw(buzz, hz(7), 0.18, 4.6, 8.0, 1.0, [](double t) { return 1 - std::exp(-t / 0.9); });
Buf src(N);
for (int i = 0; i < N; ++i) src[i] = noise[i] * 0.6f + buzz[i];
// "ah" formants drifting toward "oh"
Buf f1 = bandpass(src, 750.0, 6.0), f2 = bandpass(src, 1150.0, 8.0), f3 = bandpass(src, 2600.0, 10.0);
Buf g1 = bandpass(src, 500.0, 6.0), g2 = bandpass(src, 900.0, 8.0);
Buf out(N);
for (int i = 0; i < N; ++i) {
double t = (double)i / RATE;
double m = 0.5 - 0.5 * std::cos(TAU * t / SECONDS);
double swell = (1 - std::exp(-t / 0.7)) * (0.7 + 0.3 * std::sin(TAU * 0.4 * t));
out[i] = (float)(swell * ((1 - m) * (f1[i] + 0.7 * f2[i]) + m * (g1[i] + 0.6 * g2[i]) + 0.3 * f3[i]));
}
return out;
}
Buf rainField() {
Buf out(N);
Rng rng(0x2A1F);
// the bed: soft filtered noise
double z = 0.0, z2 = 0.0;
for (int i = 0; i < N; ++i) {
z += 0.08 * (rng.b() - z); z2 += 0.3 * (z - z2);
out[i] = (float)(0.5 * (z - 0.6 * z2));
}
// drops: short pitched blips at random
double t = 0.0;
while (t < SECONDS - 0.1) {
double f = 900 + 3200 * rng.f();
int start = (int)(t * RATE);
double a = 0.15 + 0.35 * rng.f();
double ph = 0.0;
int end = std::min(N, start + RATE / 10);
for (int i = start; i < end; ++i) {
double tt = (double)(i - start) / RATE;
ph += TAU * f * (1 + 0.6 * std::exp(-tt * 60)) / RATE;
out[i] += (float)(a * std::exp(-tt * 55) * std::sin(ph));
}
t += 0.01 + 0.08 * std::pow(rng.f(), 2.0);
}
return out;
}
using Recipe = Buf (*)();
// Same order as EchofieldDefs SOURCES.
const Recipe RECIPES[COUNT] = {
feltPiano, bowedGlass, musicBox, warmPad, strings,
lowDrone, rainField, kalimba, breathChoir, glassTines,
};
Sample cache[COUNT];
std::atomic<bool> ready[COUNT];
std::mutex buildLock; // builders only (never the audio thread)
std::atomic<bool> started{false};
} // namespace
int indexOf(const char *name) {
if (!name) return -1;
for (int i = 0; i < COUNT; ++i) if (std::strcmp(SOURCES[i], name) == 0) return i;
return -1;
}
const Sample *get(int index) {
if (index < 0 || index >= COUNT) return nullptr;
return ready[index].load(std::memory_order_acquire) ? &cache[index] : nullptr;
}
const Sample *get(const char *name) { return get(indexOf(name)); }
void prewarmBlocking() {
std::lock_guard<std::mutex> g(buildLock);
for (int i = 0; i < COUNT; ++i) {
if (ready[i].load(std::memory_order_acquire)) continue;
cache[i].data = normalize(RECIPES[i]());
cache[i].sampleRate = RATE;
ready[i].store(true, std::memory_order_release);
}
}
void prewarm() {
if (started.exchange(true)) return;
std::thread([] { prewarmBlocking(); }).detach();
}
} // namespace sizzle::echofield::GrainSources
+30
View File
@@ -0,0 +1,30 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of audio/GrainSources.kt: the Grain Cloud's ten built-in sources,
// synthesised in code (about six seconds each at RATE, mono, pitched on C).
// Generated off the audio thread: prewarm() renders them on a background thread
// (once), prewarmBlocking() renders them on the calling thread (tests). get()
// never blocks and returns nullptr until a source is ready.
#include "Sample.hpp"
namespace sizzle::echofield::GrainSources {
constexpr int RATE = 24000;
constexpr int COUNT = 10;
/** The source named [name] (EchofieldDefs SOURCES[0..9]) once rendered, else nullptr. */
const Sample *get(const char *name);
/** By index into the built-in list, or nullptr (not ready / out of range). */
const Sample *get(int index);
/** Index of the built-in source [name], or -1. */
int indexOf(const char *name);
/** Render every source on a detached background thread (once). */
void prewarm();
/** Render every source not yet rendered, now, on this thread. */
void prewarmBlocking();
} // namespace sizzle::echofield::GrainSources
+42
View File
@@ -0,0 +1,42 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// The reference-test maker for kind "GRAIN" (see TestVoice.hpp and
// IosGoldenInstruments.kt): a GrainCloud with the slot's patch, notes from live input.
#include <cmath>
#include <memory>
#include "GrainCloud.hpp"
#include "GrainSources.hpp"
#include "sizzle/TestVoice.hpp"
namespace sizzle {
namespace {
/** The seed the Kotlin export's GrainCloud got: the next one after the global
* counter the export recorded right before the scenario built its voices. */
uint32_t exportSeed(const TestVoiceSetup &s) {
echofield::GrainSeeds seeds;
seeds.seeds = s.grainSeeds;
return seeds.next();
}
class GrainTestVoice final : public TestVoice {
echofield::GrainCloud cloud;
public:
GrainTestVoice(const TestVoiceSetup &s, uint32_t seed) : cloud(s.sampleRate, seed) {
cloud.setPatch(echofield::GrainPatch::from(s.params, s.tempoBpm));
}
void noteOn(int midi, int velocity) override { cloud.noteOn(midi, velocity, echofield::GrainCloud::OWNER_LIVE); }
void noteOff(int midi) override { cloud.noteOff(midi); }
float render() override { return cloud.render(); }
};
} // namespace
std::unique_ptr<TestVoice> makeGrainTestVoice(const TestVoiceSetup &setup) {
echofield::GrainSources::prewarmBlocking();
return std::make_unique<GrainTestVoice>(setup, exportSeed(setup));
}
} // namespace sizzle
+11
View File
@@ -0,0 +1,11 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// The Grain Cloud's name for the shared sample type (sizzle/Sample.hpp).
#include "sizzle/Sample.hpp"
namespace sizzle::echofield {
using Sample = sizzle::Sample;
} // namespace sizzle::echofield
+112
View File
@@ -0,0 +1,112 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// AudioEngine.ChannelArp: per-(lane,track) arpeggiator. Notes are kept sorted
// ascending; the linear step sequence is octave-major (all chord notes in octave 0,
// then octave 1, ...), walked up / down / up-down / randomly by advance(). genStamp
// identifies the line whose chord this holds (the engine's lineTriggerGen).
#include <cstdint>
#include <cstring>
namespace sizzle::engine {
class ChannelArp {
public:
int velocity = 100;
double stepSamples = 0.0, samplesLeft = 0.0;
bool resetOnBar = false;
int genStamp = -1;
int noteCount() const { return noteCount_; }
/** Active while it holds at least one note. */
bool active() const { return noteCount_ > 0; }
/** Start a fresh chord on [note], resetting the phase to step 0. */
void startChord(int note, int vel, int octs, const char *modeStr, double stepSamp, bool resetBar) {
noteCount_ = 0; addNote(note); velocity = vel; octaves = clamp(octs, 1, 4);
mode = modeOf(modeStr);
stepSamples = stepSamp < 1.0 ? 1.0 : stepSamp; samplesLeft = stepSamples; step = 0; dir = 1;
resetOnBar = resetBar; pendingReset = false;
}
/** Replace the chord with [note] while keeping the running phase. */
void resetChord(int note, int vel, int octs, const char *modeStr, double stepSamp, bool resetBar) {
noteCount_ = 0; addNote(note); velocity = vel;
refresh(octs, modeStr, stepSamp, resetBar);
}
/** Add a note to the held chord (sorted ascending, de-duplicated). */
void addNote(int note) {
const int n = clamp(note, 0, 127);
int i = 0;
while (i < noteCount_ && notes[i] < n) i++;
if (i < noteCount_ && notes[i] == n) return;
if (noteCount_ >= MAX_CHORD) return;
for (int j = noteCount_; j >= i + 1; --j) notes[j] = notes[j - 1];
notes[i] = n; noteCount_++;
}
/** Update params without resetting the running phase. */
void refresh(int octs, const char *modeStr, double stepSamp, bool resetBar) {
octaves = clamp(octs, 1, 4);
mode = modeOf(modeStr);
stepSamples = stepSamp < 1.0 ? 1.0 : stepSamp;
resetOnBar = resetBar;
}
void resetToBar() { step = 0; dir = 1; samplesLeft = 0.0; pendingReset = true; }
bool consumePendingReset() { bool p = pendingReset; pendingReset = false; return p; }
void stop() { noteCount_ = 0; genStamp = -1; }
int currentNote() const {
if (noteCount_ <= 0) return 0;
const int idx = clamp(step, 0, total() - 1);
const int oct = idx / noteCount_;
return clamp(notes[idx % noteCount_] + 12 * oct, 0, 127);
}
void advance() {
const int t = total();
switch (mode) {
case 1: step = (step - 1 + t) % t; break;
case 2:
if (t > 1) {
step += dir;
if (step >= t - 1) { step = t - 1; dir = -1; }
else if (step <= 0) { step = 0; dir = 1; }
}
break;
case 3: step = t > 1 ? rnd(t) : 0; break;
default: step = (step + 1) % t; break;
}
}
private:
static constexpr int MAX_CHORD = 8;
static int clamp(int v, int lo, int hi) { return v < lo ? lo : (v > hi ? hi : v); }
static int modeOf(const char *m) {
if (std::strcmp(m, "Down") == 0) return 1;
if (std::strcmp(m, "UpDown") == 0) return 2;
if (std::strcmp(m, "Random") == 0) return 3;
return 0;
}
int total() const { int t = noteCount_ * octaves; return t < 1 ? 1 : t; }
int rnd(int bound) {
uint32_t s = rng;
s ^= s << 13; s ^= s >> 17; s ^= s << 5;
rng = s;
return (int)(s % (uint32_t)bound);
}
int notes[MAX_CHORD] = {};
int noteCount_ = 0;
int octaves = 1, mode = 0;
int step = 0, dir = 1;
bool pendingReset = false;
uint32_t rng = 0x2545F491u;
};
} // namespace sizzle::engine
File diff suppressed because it is too large Load Diff
+159
View File
@@ -0,0 +1,159 @@
// SPDX-FileCopyrightText: 2026 Styves Goupil (FRASIL)
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown (Kotlin port for Sizzle, C++ port)
// SPDX-License-Identifier: MPL-2.0
//
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at
// https://mozilla.org/MPL/2.0/ (also in LICENSES/MPL-2.0.txt of this repository).
//
// Port of FrasilDefs.kt (engineFrom, the 36 drone presets) and FrasilPatch.from.
#include <cstring>
#include "frasil/FrasilVoice.hpp"
#include "sizzle/Params.hpp"
#include "KotlinMath.hpp"
namespace sizzle::frasil {
namespace {
using namespace defs;
const char *const INTERVALS[] = {"Unison", "-12", "+7", "+12"};
constexpr float INTERVAL_RATIO[] = {1.f, 0.5f, 1.4983071f, 2.f};
const char *const FILTER_TYPES[] = {"Low", "Band", "High"};
const char *const BREATH_PITCHES[] = {"-12", "Unison", "+12", "+19", "+24"};
constexpr float BREATH_RATIO[] = {0.5f, 1.f, 2.f, 2.9966142f, 4.f};
template <int K> int indexOf(const char *const (&list)[K], const char *s) {
for (int i = 0; i < K; ++i) if (!std::strcmp(list[i], s)) return i;
return -1;
}
float r(int v) { return (float)v / 127.f; }
/** engineFrom: [num](key, def) reads a slider, [choice](key, def) a choice. */
template <class Num, class Choice> int engineFrom(float *e, Num num, Choice choice) {
auto u = [&](const char *key, float def) { return kt::coerceIn(num(key, def), 0.f, 1.f); };
e[CHOIR] = u("choir", r(76)); e[PARTIALS] = u("partials", r(89)); e[BREATH] = u("breath", r(32));
e[WARMTH] = u("warmth", r(19)); e[DETUNE] = u("detune", r(51)); e[CUTOFF] = u("cfilter", r(44));
e[TILT] = u("tilt", r(57)); e[ODD] = u("odd", r(25)); e[STRETCH] = u("stretch", 0.f);
e[RESONANCE] = u("bres", r(70)); e[COLOR] = u("color", 0.f);
e[ATTACK] = u("attack", r(89)); e[RELEASE] = u("release", r(83));
e[MOTION] = u("motion", r(44)); e[MOTION_RATE] = u("mrate", r(51));
e[TIDE] = u("tide", r(25)); e[TIDE_RATE] = u("tperiod", r(38)); e[TIMBRE] = u("timbre", r(64));
e[SHAPE] = u("shape", 0.f); e[CH_RESO] = u("creso", 0.f);
e[EVOLVE] = u("evolve", 0.f); e[BEAT] = u("beat", 0.f);
e[FORMANT] = 3.f * u("formant", r(85)); e[PEAK] = u("peak", 0.f);
e[GRAIN] = u("grain", 0.f);
float tn = u("btone", r(64)) * 127.f;
e[TONE] = tn >= 126.5f ? 1.f : (tn - 64.f) / 63.f;
e[AIR] = u("air", 0.f); e[SOFT] = u("soft", 0.f);
e[VELOCITY] = u("velsens", r(38)); e[BODY] = u("body", 1.f);
e[INTERVAL] = INTERVAL_RATIO[kt::coerceAtLeast(indexOf(INTERVALS, choice("interval", INTERVALS[0])), 0)];
int bp = indexOf(BREATH_PITCHES, choice("bpitch", BREATH_PITCHES[1]));
e[BR_PITCH] = BREATH_RATIO[bp < 0 ? 1 : bp];
return kt::coerceAtLeast(indexOf(FILTER_TYPES, choice("ctype", FILTER_TYPES[0])), 0);
}
// CHO PAR SOU WAR DET FIL TIL ODD STR BRES COL SPR ATT REL MOT RAT TID PER TIM SPA SHP INT CRES TYP EVO BEAT
// FORM PEAK GRN PIT TONE AIR SOFT. SPREAD and SPACE (null) are FRASIL's stereo field and reverb.
constexpr int NCOL = 33;
const char *const COLS[NCOL] = {
"choir", "partials", "breath", "warmth", "detune", "cfilter", "tilt", "odd", "stretch", "bres", "color",
nullptr, "attack", "release", "motion", "mrate", "tide", "tperiod", "timbre", nullptr, "shape", "interval",
"creso", "ctype", "evolve", "beat", "formant", "peak", "grain", "bpitch", "btone", "air", "soft",
};
struct Raw { const char *name; int row[NCOL]; };
const Raw RAW[] = {
{"Mist", {76, 89, 32, 19, 51, 44, 57, 25, 0, 70, 0, 89, 89, 83, 44, 51, 25, 38, 64, 57, 0, 0, 0, 0, 0, 0, 85, 0, 0, 1, 64, 0, 0}},
{"Cathedral", {110, 50, 20, 25, 85, 55, 60, 30, 0, 60, 0, 110, 100, 100, 60, 40, 20, 50, 60, 95, 0, 1, 20, 0, 10, 0, 85, 0, 0, 1, 64, 0, 0}},
{"Glacier", {20, 100, 70, 5, 30, 60, 35, 50, 60, 115, 127, 100, 80, 110, 40, 30, 30, 40, 80, 90, 0, 0, 0, 0, 40, 15, 100, 30, 20, 2, 80, 0, 0}},
{"Abyss", {90, 70, 25, 50, 70, 20, 90, 40, 0, 50, 0, 70, 100, 105, 50, 25, 50, 25, 40, 70, 30, 1, 40, 0, 20, 0, 60, 0, 0, 0, 30, 0, 0}},
{"Aurora", {60, 105, 40, 15, 45, 65, 40, 15, 10, 85, 60, 115, 90, 105, 55, 45, 45, 50, 75, 95, 0, 0, 0, 0, 70, 25, 90, 35, 0, 2, 75, 10, 0}},
{"Ember", {100, 55, 20, 80, 40, 40, 70, 60, 0, 50, 30, 80, 70, 80, 35, 40, 20, 40, 55, 50, 64, 0, 50, 0, 10, 0, 70, 0, 0, 1, 50, 0, 0}},
{"Tide", {80, 80, 45, 25, 60, 45, 55, 30, 10, 75, 40, 100, 95, 100, 70, 30, 110, 60, 60, 70, 0, 0, 30, 0, 30, 0, 85, 0, 0, 1, 64, 0, 0}},
{"Dust", {25, 40, 85, 20, 40, 50, 60, 30, 20, 100, 60, 120, 60, 90, 50, 50, 30, 40, 60, 75, 0, 0, 0, 0, 30, 0, 85, 0, 90, 2, 85, 40, 0}},
{"Wind", {0, 20, 85, 0, 40, 50, 60, 30, 0, 20, 30, 127, 80, 95, 90, 80, 50, 70, 64, 80, 0, 0, 0, 0, 0, 0, 85, 0, 0, 1, 75, 50, 0}},
{"Organ", {40, 115, 10, 30, 10, 50, 45, 0, 0, 60, 0, 60, 40, 60, 15, 40, 10, 40, 64, 50, 0, 2, 0, 0, 0, 0, 85, 0, 0, 1, 64, 0, 0}},
{"Hollow", {105, 80, 25, 20, 35, 50, 50, 110, 0, 70, 64, 90, 80, 90, 40, 45, 25, 40, 60, 65, 64, 0, 40, 1, 15, 0, 85, 0, 0, 1, 60, 0, 0}},
{"Vowel", {65, 125, 15, 10, 30, 55, 30, 20, 0, 70, 0, 85, 90, 95, 45, 35, 60, 45, 64, 70, 0, 0, 60, 1, 20, 0, 95, 105, 0, 1, 64, 0, 0}},
{"Shimmer", {45, 100, 50, 10, 55, 75, 25, 20, 15, 100, 90, 120, 85, 110, 50, 55, 30, 40, 85, 100, 0, 3, 0, 0, 40, 50, 100, 20, 10, 3, 90, 20, 0}},
{"Chanter", {105, 45, 15, 40, 30, 55, 60, 70, 0, 60, 30, 70, 50, 70, 30, 45, 15, 40, 60, 45, 110, 0, 35, 1, 0, 0, 85, 0, 0, 1, 64, 0, 0}},
{"Ensemble", {115, 40, 20, 30, 75, 60, 55, 25, 0, 60, 0, 115, 95, 90, 55, 55, 20, 40, 65, 75, 90, 0, 15, 0, 0, 0, 85, 0, 0, 1, 64, 0, 0}},
{"Bells", {15, 115, 45, 5, 25, 50, 30, 20, 95, 110, 127, 95, 40, 110, 30, 40, 20, 40, 75, 85, 0, 0, 0, 0, 30, 30, 85, 0, 0, 2, 80, 0, 0}},
{"Nocturne", {90, 60, 30, 35, 55, 25, 85, 30, 0, 55, 0, 90, 110, 115, 45, 20, 40, 20, 45, 85, 20, 1, 70, 0, 25, 0, 70, 0, 0, 0, 35, 0, 0}},
{"Haze", {85, 50, 60, 10, 60, 70, 50, 25, 0, 40, 30, 120, 100, 105, 60, 50, 30, 50, 70, 90, 0, 3, 20, 2, 20, 0, 85, 0, 0, 2, 80, 30, 0}},
{"Pulse", {50, 95, 25, 20, 30, 50, 45, 30, 0, 70, 20, 100, 60, 80, 30, 50, 20, 40, 64, 65, 0, 0, 0, 0, 15, 100, 85, 0, 0, 1, 64, 0, 0}},
{"Rime", {30, 110, 70, 0, 20, 80, 20, 40, 30, 120, 100, 110, 70, 100, 35, 60, 20, 40, 90, 90, 0, 3, 0, 2, 30, 20, 110, 40, 40, 4, 100, 15, 0}},
{"Deep", {100, 100, 0, 40, 25, 25, 100, 20, 0, 50, 0, 60, 90, 95, 25, 30, 20, 30, 40, 45, 0, 1, 10, 0, 0, 0, 40, 0, 0, 0, 30, 0, 0}},
{"Spectral", {20, 120, 15, 5, 20, 50, 20, 10, 0, 70, 0, 90, 90, 100, 50, 40, 80, 50, 64, 80, 0, 0, 0, 0, 50, 10, 85, 127, 0, 1, 64, 0, 0}},
{"Rust", {80, 50, 40, 100, 50, 45, 65, 60, 20, 80, 40, 80, 60, 80, 40, 55, 25, 40, 55, 55, 70, 0, 80, 1, 20, 15, 75, 0, 60, 1, 45, 20, 0}},
{"Still", {0, 125, 0, 0, 0, 50, 127, 0, 0, 50, 0, 60, 100, 100, 5, 20, 0, 40, 50, 70, 0, 0, 0, 0, 0, 0, 85, 0, 0, 1, 64, 0, 0}},
{"Velvet", {95, 45, 10, 15, 35, 40, 85, 20, 0, 50, 0, 100, 105, 110, 35, 30, 20, 45, 52, 70, 0, 0, 10, 0, 0, 0, 85, 0, 0, 1, 50, 0, 120}},
{"Chrome", {35, 115, 15, 35, 15, 75, 15, 120, 45, 90, 80, 85, 60, 90, 35, 55, 15, 40, 85, 60, 64, 3, 85, 2, 20, 35, 110, 70, 0, 3, 95, 0, 0}},
{"Swarm", {120, 75, 30, 30, 120, 60, 40, 30, 0, 60, 20, 127, 70, 85, 110, 100, 40, 15, 70, 60, 120, 0, 40, 1, 40, 70, 85, 0, 30, 2, 70, 20, 0}},
{"Foghorn", {127, 60, 15, 70, 20, 22, 95, 90, 0, 40, 0, 50, 120, 120, 20, 20, 60, 70, 35, 65, 64, 1, 60, 0, 0, 0, 40, 30, 0, 0, 30, 0, 30}},
{"Solar", {70, 105, 45, 20, 55, 90, 15, 15, 5, 80, 30, 120, 100, 110, 60, 50, 70, 35, 100, 90, 10, 3, 15, 2, 60, 25, 120, 40, 0, 3, 110, 30, 0}},
{"Cave", {55, 40, 95, 30, 30, 18, 110, 30, 0, 100, 60, 70, 110, 120, 30, 20, 45, 60, 30, 100, 0, 1, 50, 0, 10, 0, 40, 0, 50, 0, 18, 5, 60}},
{"Glass Harp", {10, 120, 20, 0, 12, 60, 30, 10, 25, 100, 90, 110, 50, 120, 25, 30, 15, 55, 90, 95, 0, 3, 0, 0, 45, 40, 120, 110, 0, 4, 100, 0, 127}},
{"Monk", {110, 85, 10, 25, 30, 38, 70, 40, 0, 60, 0, 70, 100, 100, 30, 25, 30, 65, 50, 80, 0, 1, 55, 1, 15, 0, 62, 90, 0, 1, 50, 0, 90}},
{"Static", {35, 40, 127, 15, 40, 70, 40, 50, 0, 110, 90, 127, 40, 70, 80, 110, 20, 20, 80, 55, 30, 0, 30, 2, 0, 0, 85, 0, 85, 3, 100, 40, 0}},
{"Lullaby", {85, 70, 8, 10, 22, 45, 100, 10, 0, 60, 0, 80, 110, 120, 20, 15, 35, 80, 55, 85, 0, 2, 0, 0, 10, 8, 85, 20, 0, 1, 64, 0, 110}},
{"Storm", {80, 40, 110, 90, 70, 28, 90, 40, 0, 70, 40, 127, 90, 110, 100, 85, 120, 25, 40, 75, 30, 1, 70, 0, 50, 20, 60, 0, 70, 0, 35, 60, 20}},
{"Prism", {50, 120, 25, 10, 40, 65, 25, 60, 15, 90, 50, 120, 85, 105, 60, 45, 50, 40, 80, 90, 0, 3, 20, 1, 100, 30, 105, 80, 0, 2, 85, 10, 40}},
};
constexpr int NRAW = (int)(sizeof(RAW) / sizeof(RAW[0]));
int colOf(const char *key) {
for (int c = 0; c < NCOL; ++c) if (COLS[c] && !std::strcmp(COLS[c], key)) return c;
return -1;
}
/** factoryEngine(name): a preset's values as FACTORY stores them (row / 127f as text,
* which round-trips exactly, the choices by name), through engineFrom. */
bool factoryEngine(const char *name, float *e, int &type) {
for (const Raw &p : RAW) {
if (std::strcmp(p.name, name)) continue;
auto num = [&](const char *k, float d) -> float {
if (!std::strcmp(k, "velsens")) return r(38);
if (!std::strcmp(k, "body")) return 1.f;
int c = colOf(k);
return c < 0 ? d : (float)p.row[c] / 127.f;
};
auto choice = [&](const char *k, const char *d) -> const char * {
int c = colOf(k);
if (c < 0) return d;
if (!std::strcmp(k, "interval")) return INTERVALS[p.row[c] % 4];
if (!std::strcmp(k, "ctype")) return FILTER_TYPES[p.row[c] % 3];
if (!std::strcmp(k, "bpitch")) return BREATH_PITCHES[p.row[c] % 5];
return d;
};
type = engineFrom(e, num, choice);
return true;
}
return false;
}
} // namespace
int defs::factoryCount() { return NRAW; }
const char *defs::factoryName(int i) { return i >= 0 && i < NRAW ? RAW[i].name : ""; }
FrasilPatch FrasilPatch::from(const Params *slot) {
FrasilPatch p;
p.aType = engineFrom(
p.a,
[&](const char *k, float d) { return slot ? slot->f(k, d) : d; },
[&](const char *k, const char *d) { return slot ? slot->s(k, d) : d; });
const char *target = slot ? slot->s(MORPH_TO, "Off") : "Off";
int bt = 0;
p.hasB = std::strcmp(target, "Off") != 0 && factoryEngine(target, p.b, bt);
p.bType = p.hasB ? bt : p.aType;
p.morph = kt::coerceIn(slot ? slot->f(MORPH, 0.f) : 0.f, 0.f, 1.f);
p.morphTime = kt::coerceIn(slot ? slot->f(MORPH_TIME, 0.f) : 0.f, 0.f, 120.f);
return p;
}
} // namespace sizzle::frasil
+54
View File
@@ -0,0 +1,54 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// The reference tests' FRASIL maker (see TestVoice.hpp, IosGoldenInstruments.kt).
#include <cmath>
#include "frasil/FrasilVoice.hpp"
#include "sizzle/TestVoice.hpp"
namespace sizzle {
namespace {
using frasil::FrasilClock;
using frasil::FrasilPatch;
using frasil::FrasilSeeds;
using frasil::FrasilVoice;
/**
* The seed the Kotlin export's FrasilVoice got: the export records Kotlin's global
* seed counter right before the scenario built its voices ("seeds" line). The
* SynthVoice built first takes the next seed for its own Morph Pad voice; the
* FrasilVoice takes the one after.
*/
int32_t exportSeed(const TestVoiceSetup &s) {
FrasilSeeds seeds;
seeds.seeds = s.frasilSeeds;
seeds.next(); // the SynthVoice's Morph Pad voice
return seeds.next();
}
class FrasilTestVoice final : public TestVoice {
FrasilClock clock;
FrasilPatch patch;
FrasilVoice voice;
int sampleRate;
public:
explicit FrasilTestVoice(const TestVoiceSetup &s)
: clock{s.clock0}, patch(FrasilPatch::from(s.params)), voice(s.sampleRate, clock, exportSeed(s)),
sampleRate(s.sampleRate) {}
void blockStart(int frames) override { clock.advance(frames, sampleRate); }
void noteOn(int midi, int velocity) override { voice.noteOn(midi, (float)velocity / 127.f, patch); }
void noteOff(int) override { voice.noteOff(); }
float render() override { return voice.render(); }
};
} // namespace
std::unique_ptr<TestVoice> makeFrasilTestVoice(const TestVoiceSetup &setup) {
return std::make_unique<FrasilTestVoice>(setup);
}
} // namespace sizzle
+521
View File
@@ -0,0 +1,521 @@
// SPDX-FileCopyrightText: 2026 Styves Goupil (FRASIL)
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown (Kotlin port for Sizzle, C++ port)
// SPDX-License-Identifier: MPL-2.0
//
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at
// https://mozilla.org/MPL/2.0/ (also in LICENSES/MPL-2.0.txt of this repository).
//
// Port of FrasilVoice.kt, line for line (FRASIL 3.3's drone voice). See the Kotlin
// for the commentary on the sound; comments here are about the port.
#include <cmath>
#include "frasil/FrasilVoice.hpp"
#include "KotlinMath.hpp"
// Kotlin rounds every float operation; no fused multiply-adds.
#if defined(__clang__)
#pragma clang fp contract(off)
#endif
namespace sizzle::frasil {
namespace {
using namespace defs;
constexpr float VOICE_G = 0.2f;
constexpr float TAIL_END = 0.01f;
constexpr float SIDE_GAIN = 0.70710678f;
constexpr float OUT_GAIN = 2.2f;
constexpr float TIDE_SMOOTH_S = 0.5f;
constexpr float PI = 3.14159265f;
constexpr float TWO_PI = 6.2831853f;
constexpr float SIDE[3] = {0.f, -1.f, 1.f};
constexpr float PWR[3] = {0.21f, 0.29f, 0.37f};
constexpr float LOG2K[8] = {0.f, 1.f, 1.5849625f, 2.f, 2.3219281f, 2.5849625f, 2.8073549f, 3.f};
constexpr float BEAT_SPREAD[8] = {0.55f, 1.25f, 0.8f, 1.45f, 0.65f, 1.1f, 0.95f, 1.35f};
/** BREATH's ratios (log2): ln(r) / ln(2) in double, to float. */
struct RatioL2 {
float v[3][3];
RatioL2() {
const double r[3][3] = {{1, 2, 3}, {1, 3, 5}, {1, 2.756f, 5.404f}};
for (int i = 0; i < 3; ++i)
for (int k = 0; k < 3; ++k) v[i][k] = (float)(std::log(r[i][k]) / std::log(2.0));
}
};
const RatioL2 RATIO_L2;
inline float tanf_(float x) { return (float)std::tan((double)x); }
inline float floorf_(float x) { return (float)std::floor((double)x); }
/** A blep with the step's inverse. */
inline float blep(float t0, float dt, float idt) {
if (t0 < dt) { float t = t0 * idt; return t + t - t * t - 1.f; }
if (t0 > 1.f - dt) { float t = (t0 - 1.f) * idt; return t * t + t + t + 1.f; }
return 0.f;
}
inline float flush(float x) { return (x > -1e-20f && x < 1e-20f) ? 0.f : x; }
} // namespace
FrasilVoice::FrasilVoice(int fs_, const FrasilClock &clock_, int32_t seed)
: clock(&clock_), invFs(1.f / (float)fs_), r44(44100.f / (float)fs_), nyq(0.45f * (float)fs_),
patch(FrasilPatch::defaults()), rng((uint32_t)seed),
kdc(brK(0.0014f)), glideK(brK(0.2f)),
tideK(1.f - kt::expf_(-(float)BLOCK / ((float)fs_ * TIDE_SMOOTH_S))) {}
void FrasilVoice::noteOn(int midi, float velocity, const FrasilPatch &p) {
bool fresh = note_ < 0;
note_ = midi;
gate = true;
vel = kt::coerceIn(velocity, 0.f, 1.f);
patch = p;
ageFrames = 0;
ending = false;
chunk = 0;
if (fresh) start();
}
void FrasilVoice::kill() {
note_ = -1; gate = false; env = 0.f; lvl = 0.f; pos = CH; ending = false;
}
float FrasilVoice::render() {
if (pos >= CH) {
if (note_ < 0) return 0.f;
if (ending) { note_ = -1; ending = false; return 0.f; }
renderChunk();
pos = 0;
}
return out[pos++];
}
// ------------------------------------------------------------------- start ---
void FrasilVoice::start() {
env = 0.f; lvl = 0.f; pos = CH; prime = true;
dcState = 0.f; thinState = 0.f; nlp = 0.f;
for (int k = 0; k < 3; ++k) {
cph[k] = urand();
cpw[k] = (float)k * 0.33f;
ouC[k] = randf() * 0.5f;
}
for (float &v : clp) v = 0.f;
for (float &v : cint) v = 0.f;
csvf = false;
for (int k = 0; k < NP; ++k) {
float ph = urand() * TWO_PI;
px[k] = kt::cosf_(ph); py[k] = kt::sinf_(ph);
ps[k] = 0.f; pc[k] = 1.f;
ouPa[k] = randf() * 0.5f; ouPf[k] = randf() * 0.5f;
pac[k] = 0.f; pda[k] = 0.f;
pbt[k] = urand();
}
for (int k = 0; k < NR; ++k) { r1[k] = 0.f; r2[k] = 0.f; ouR[k] = randf() * 0.5f; }
ouCut = randf() * 0.5f;
}
// ------------------------------------------------------------------- block ---
void FrasilVoice::block() {
const FrasilPatch &p = patch;
const float *b = p.hasB ? p.b : nullptr;
float m = b == nullptr ? 0.f : morphPosition(p);
float gk = prime ? 1.f : glideK;
for (int i = 0; i < N; ++i) {
float t = b == nullptr ? p.a[i] : p.a[i] + (b[i] - p.a[i]) * m;
cur[i] += (t - cur[i]) * gk;
}
type = (b != nullptr && m >= 0.5f) ? p.bType : p.aType;
float period = 300.f * kt::powf_(1.f / 30.f, cur[TIDE_RATE]);
double ph = clock->seconds / (double)period;
float tideT = kt::sinf_(TWO_PI * (float)(ph - std::floor(ph)));
tideV = prime ? tideT : tideV + (tideT - tideV) * tideK;
bool wasPrime = prime;
prime = false;
ageFrames += BLOCK;
drift();
voiceBlock(wasPrime);
ka = 1.f - kt::expf_(-CH * invFs * 3.f / (0.005f * kt::powf_(6000.f, cur[ATTACK])));
kr = 1.f - kt::expf_(-CH * invFs * 3.f / (0.05f * kt::powf_(1200.f, cur[RELEASE])));
float full = cur[BODY];
dk = 1.f + 5.f * cur[WARMTH] * full;
dmake = 1.f / kt::tanhf_(dk * 0.35f) * 0.35f;
driveOn = cur[WARMTH] * full > 0.001f;
thin = full < 0.995f;
thinA = 1.f - kt::expf_(-TWO_PI * 20.f * kt::powf_(20.f, 1.f - full) * invFs);
}
float FrasilVoice::morphPosition(const FrasilPatch &p) const {
if (p.morphTime <= 0.f) return p.morph;
float x = kt::coerceIn(((float)ageFrames * invFs) / p.morphTime, 0.f, 1.f);
return p.morph + (1.f - p.morph) * x * x * (3.f - 2.f * x);
}
float FrasilVoice::ou(float x, float th, float s) {
// Kotlin evaluates the three randf() left to right.
float a = randf();
float b = randf();
float c = randf();
return kt::coerceIn(x - th * x + s * (a + b + c), -1.5f, 1.5f);
}
void FrasilVoice::drift() {
float tau = 20.f * kt::powf_(0.025f, cur[MOTION_RATE]);
float th = BLOCK * invFs / tau;
float s = 0.6f * kt::sqrtf_(2.f * th);
float te = th * (1.f + 3.f * cur[EVOLVE]);
float se = 0.6f * kt::sqrtf_(2.f * te);
for (int k = 0; k < 3; ++k) ouC[k] = ou(ouC[k], th, s);
for (int k = 0; k < NP; ++k) { ouPa[k] = ou(ouPa[k], te, se); ouPf[k] = ou(ouPf[k], th, s); }
for (int k = 0; k < NR; ++k) ouR[k] = ou(ouR[k], th, s);
ouCut = ou(ouCut, th, s);
}
void FrasilVoice::voiceBlock(bool fresh) {
const float *c = cur;
float f = 440.f * kt::powf_(2.f, (float)(note_ - 69) / 12.f);
float m = c[MOTION];
float mw = m * (1.f + 2.f * m);
float bright = (c[TIMBRE] - 0.5f) + tideV * c[TIDE] * 0.5f;
float full = c[BODY];
// CHOIR
if (c[CHOIR] > 0.001f) {
float dc = c[DETUNE] * c[DETUNE] * 40.f * (0.2f + 0.8f * full);
float sh = c[SHAPE];
float a = sh < 0.5f ? 2.f * sh : 1.f;
float w = sh < 0.5f ? 0.5f : 0.5f - 0.8f * (sh - 0.5f);
float sw = sh > 0.5f ? 0.03f + 0.18f * (sh - 0.5f) : 0.03f * a;
for (int j = 0; j < 3; ++j) {
float cents = SIDE[j] * dc + mw * 7.f * ouC[j];
cdt[j] = kt::coerceIn(f * (j == 0 ? c[INTERVAL] : 1.f) * kt::powf_(2.f, cents / 1200.f) * invFs, 1e-6f, 0.45f);
cid[j] = 1.f / cdt[j];
cpw[j] += PWR[j] * BLOCK * invFs;
cpw[j] -= floorf_(cpw[j]);
cw[j] = kt::coerceIn(w + sw * kt::sinf_(TWO_PI * cpw[j]) + 0.1f * mw * ouC[j] * a, 0.04f, 0.96f);
}
csh = a;
float ce = kt::coerceIn(c[CUTOFF] + bright * 0.6f + mw * 0.2f * ouCut, 0.f, 1.f);
float hc = 1.f + 39.f * ce * ce;
float fc = kt::coerceIn(f * hc, 20.f, std::fmin(16000.f, nyq));
ca = 1.f - kt::expf_(-TWO_PI * fc * invFs);
float pv = (1.f + a * a) / 3.f - 2.f * a * (1.f / 3.f - 2.f * w * (1.f - w));
cgain = kt::sqrtf_((1.f / 3.f) / (pv > 0.05f ? pv : 0.05f));
if (c[CH_RESO] > 0.002f || type != 0) {
float g = tanf_(PI * fc * invFs);
float q = 0.5f * kt::powf_(40.f, c[CH_RESO]);
float k = 1.f / q;
sa1 = 1.f / (1.f + g * (g + k)); sa2 = g * sa1; sa3 = g * sa2;
switch (type) {
case 1: sc0 = 0.f; sc1 = k * (1.4f + 0.12f * kt::sqrtf_(hc)) * kt::sqrtf_(q); sc2 = 0.f; break;
case 2: {
float mk = kt::coerceIn(kt::sqrtf_(0.75f * hc), 1.f, 4.f);
sc0 = mk; sc1 = -k * mk; sc2 = -mk;
break;
}
default: sc0 = 0.f; sc1 = 0.f; sc2 = 1.f; break;
}
cgain *= 1.f / kt::sqrtf_(1.f + 0.22f * (q - 0.5f));
}
if (fresh) { sp0 = sc0; sp1 = sc1; sp2 = sc2; }
}
// PARTIALS
if (c[PARTIALS] > 0.001f) {
float pe = kt::coerceIn(c[TILT] - bright * 0.7f, 0.f, 1.f);
float pw = 0.3f + 2.7f * pe;
float sx = 1.f + 0.12f * c[STRETCH];
float fnp = 2.f + 6.f * full;
int nmax = kt::toInt(fnp);
float top = fnp - (float)nmax;
if (top > 0.001f) nmax++; else top = 1.f;
if (nmax > NP) nmax = NP;
float sum2 = 0.f;
int n = 0;
for (int j = 0; j < nmax; ++j) {
float fk = f * kt::powf_(2.f, sx * LOG2K[j] + mw * 5.f * ouPf[j] / 1200.f);
if (fk > std::fmin(15000.f, nyq)) break;
float w = TWO_PI * fk * invFs;
float cw0 = kt::cosf_(w); float sn = kt::sinf_(w);
float q = kt::sqrtf_(2.f * (1.f + cw0));
float x = px[j];
float y = (py[j] - x * ps[j]) * pc[j];
float gn = 1.5f - 0.5f * (x * x + y * y);
float shh = sn / q;
float chh = (1.f + cw0) / q;
x *= gn; y *= gn;
ps[j] = shh;
pc[j] = q / (1.f + cw0);
px[j] = x;
py[j] = y * chh + x * shh;
float a = kt::powf_(2.f, -pw * LOG2K[j] + 1.6f * (m + 2.5f * c[EVOLVE]) * ouPa[j]);
if ((j & 1) == 1) a *= 1.f - c[ODD];
float pk = c[PEAK];
if (pk > 0.001f) {
float d = (sx * LOG2K[j] - c[FORMANT]) * (1.5f + 4.f * pk);
float fl = 1.f - 0.97f * pk;
a *= fl + (1.f + 7.f * pk - fl) / (1.f + d * d);
}
if (j + 1 == nmax) a *= top;
pa[j] = a;
sum2 += a * a;
n++;
}
np = n;
float norm = 0.6f / kt::sqrtf_(sum2 + 1e-9f);
for (int j = 0; j < n; ++j) pa[j] *= norm;
if (c[BEAT] > 0.001f) {
float bt = c[BEAT];
float dep = std::fmin(1.f, bt * 1.4f);
float hz = 0.15f + 5.f * bt * bt;
for (int j = 0; j < n; ++j) {
pbt[j] += hz * BEAT_SPREAD[j] * BLOCK * invFs;
pbt[j] -= floorf_(pbt[j]);
pa[j] *= (1.f - dep * (0.5f + 0.5f * kt::sinf_(TWO_PI * pbt[j]))) / (1.f - 0.5f * dep);
}
}
for (int j = 0; j < n; ++j) pda[j] = (pa[j] - pac[j]) / BLOCK;
for (int j = n; j < NP; ++j) { pac[j] = 0.f; pda[j] = 0.f; }
}
// BREATH
if (c[BREATH] > 0.001f) {
float col = kt::coerceIn(c[COLOR], 0.f, 1.f) * 2.f;
bool lo = col < 1.f;
const float *ra = RATIO_L2.v[lo ? 0 : 1];
const float *rb = RATIO_L2.v[lo ? 1 : 2];
if (!lo) col -= 1.f;
float q = 2.f * kt::powf_(300.f, kt::coerceIn(c[RESONANCE] + mw * 0.1f * ouR[0], 0.f, 1.f));
float sb = kt::coerceIn(0.55f + bright * 0.8f, 0.05f, 1.f);
for (int j = 0; j < NR; ++j) {
float l2 = ra[j] + (rb[j] - ra[j]) * col + mw * 12.f * ouR[j] / 1200.f;
float fr = kt::coerceIn(f * c[BR_PITCH] * kt::powf_(2.f, l2), 20.f, std::fmin(16000.f, nyq));
double r = (double)kt::expf_(-PI * fr / q * invFs);
double b1 = 2.0 * r * (double)kt::cosf_(TWO_PI * fr * invFs);
double b2 = r * r;
double ng = (1.0 + b2) / ((1.0 - b2) * ((1.0 + b2) * (1.0 + b2) - b1 * b1));
rb1[j] = (float)b1; rb2[j] = (float)b2;
rg[j] = (float)(0.4 * std::sqrt(3.0 / ng)) * (j == 0 ? 1.f : sb * (j == 2 ? sb : 1.f));
}
}
}
// ------------------------------------------------------------------- chunk ---
void FrasilVoice::renderChunk() {
if (chunk == 0) block();
chunk = (chunk + 1) % (BLOCK / CH);
const float *c = cur;
env += ((gate ? 1.f : 0.f) - env) * (gate ? ka : kr);
float level = (1.f - c[VELOCITY] + c[VELOCITY] * vel) * VOICE_G;
float g1 = (!gate && env < TAIL_END) ? 0.f : level * env * env;
float g = lvl;
lvl = g1;
float dg = (g1 - g) / CH;
for (int i = 0; i < CH; ++i) { bc[i] = 0.f; ba[i] = 0.f; bb[i] = 0.f; }
float full = c[BODY];
if (c[CHOIR] > 0.001f) choirChunk(0.35f * c[CHOIR] * (0.3f + 0.7f * full));
if (c[PARTIALS] > 0.001f) partialsChunk(c[PARTIALS] * (0.7f + 0.3f * full));
if (c[BREATH] > 0.001f) { breathNoise(); souffleChunk(c[BREATH] * full * full); }
float z = bc[CH - 1] + ba[CH - 1] + bb[CH - 1] + bc[CH / 2] + ba[CH / 2] + bb[CH / 2];
if (!(z > -1e4f && z < 1e4f)) {
for (int i = 0; i < CH; ++i) { bc[i] = 0.f; ba[i] = 0.f; bb[i] = 0.f; }
start();
prime = false;
}
float dcs = dcState;
float th = thinState;
for (int i = 0; i < CH; ++i) {
g += dg;
float x = (bc[i] + SIDE_GAIN * (ba[i] + bb[i])) * g;
dcs += kdc * (x - dcs);
x -= dcs;
if (driveOn) x = kt::tanhf_(x * dk) * dmake;
if (thin) { th += thinA * (x - th); x -= th; }
out[i] = x * OUT_GAIN;
}
dcState = flush(dcs);
thinState = thin ? flush(th) : 0.f;
if (g1 == 0.f && !gate && env < TAIL_END) ending = true;
}
void FrasilVoice::choirChunk(float g0) {
bool svf = cur[CH_RESO] > 0.002f || type != 0;
bool sq = cur[SHAPE] > 0.002f;
bool soft = cur[SOFT] > 0.002f;
if (svf != csvf) {
clp[0] = svf ? 0.f : clp[1];
clp[2] = svf ? 0.f : clp[3];
csvf = svf;
}
float g = g0 * cgain;
float p0 = cph[0], p1 = cph[1], p2 = cph[2];
const float d0 = cdt[0], d1 = cdt[1], d2 = cdt[2];
const float i0 = cid[0], i1 = cid[1], i2 = cid[2];
const float sh = csh, w0 = cw[0], w1 = cw[1], w2 = cw[2];
for (int i = 0; i < CH; ++i) {
p0 += d0; if (p0 >= 1.f) p0 -= 1.f;
p1 += d1; if (p1 >= 1.f) p1 -= 1.f;
p2 += d2; if (p2 >= 1.f) p2 -= 1.f;
float s0 = 2.f * p0 - 1.f - blep(p0, d0, i0);
float s1 = 2.f * p1 - 1.f - blep(p1, d1, i1);
float s2 = 2.f * p2 - 1.f - blep(p2, d2, i2);
if (sq) {
float q0 = p0 + w0; if (q0 >= 1.f) q0 -= 1.f;
float q1 = p1 + w1; if (q1 >= 1.f) q1 -= 1.f;
float q2 = p2 + w2; if (q2 >= 1.f) q2 -= 1.f;
s0 -= sh * (2.f * q0 - 1.f - blep(q0, d0, i0));
s1 -= sh * (2.f * q1 - 1.f - blep(q1, d1, i1));
s2 -= sh * (2.f * q2 - 1.f - blep(q2, d2, i2));
}
if (soft) { xc[i] = s0; x0[i] = s1; x1[i] = s2; } else { x0[i] = s0 + s1; x1[i] = s0 + s2; }
}
cph[0] = p0; cph[1] = p1; cph[2] = p2;
if (soft) {
float kc = TWO_PI * d0; float ks = TWO_PI * d1;
float lc = 1.f - 0.15f * kc; float ls = 1.f - 0.15f * ks;
float u = cur[SOFT];
float a0, a1, a2;
if (u < 0.5f) { a0 = kt::cosf_(PI * u); a1 = kt::sinf_(PI * u); a2 = 0.f; }
else { a0 = 0.f; a1 = kt::cosf_(PI * (u - 0.5f)); a2 = kt::sinf_(PI * (u - 0.5f)); }
float c1 = a1 * kc, c2 = a2 * kc * kc, e1 = a1 * ks, e2 = a2 * ks * ks;
float cA = cint[0], cB = cint[1], l1 = cint[2], l2 = cint[3], q1 = cint[4], q2 = cint[5];
for (int j = 0; j < CH; ++j) {
float vc = xc[j], vl = x0[j], vr = x1[j];
cA = lc * cA + vc; cB = lc * cB + cA;
l1 = ls * l1 + vl; l2 = ls * l2 + l1;
q1 = ls * q1 + vr; q2 = ls * q2 + q1;
float cc = a0 * vc + c1 * cA + c2 * cB;
x0[j] = cc + a0 * vl + e1 * l1 + e2 * l2;
x1[j] = cc + a0 * vr + e1 * q1 + e2 * q2;
}
if (!(cB > -1e9f && cB < 1e9f && l2 > -1e9f && l2 < 1e9f && q2 > -1e9f && q2 < 1e9f)) {
cA = 0.f; cB = 0.f; l1 = 0.f; l2 = 0.f; q1 = 0.f; q2 = 0.f;
}
cint[0] = cA; cint[1] = cB; cint[2] = l1; cint[3] = l2; cint[4] = q1; cint[5] = q2;
} else {
for (float &v : cint) v = 0.f;
}
if (svf) {
float o0 = sp0 * g, o1 = sp1 * g, o2 = sp2 * g;
float e0 = (sc0 - sp0) * g / CH, e1 = (sc1 - sp1) * g / CH, e2 = (sc2 - sp2) * g / CH;
svfRun(ba, x0, 0, o0, o1, o2, e0, e1, e2);
svfRun(bb, x1, 2, o0, o1, o2, e0, e1, e2);
} else {
float a = ca;
float l1 = clp[0], l2 = clp[1], q1 = clp[2], q2 = clp[3];
for (int i = 0; i < CH; ++i) {
l1 += a * (x0[i] - l1); l2 += a * (l1 - l2);
q1 += a * (x1[i] - q1); q2 += a * (q1 - q2);
ba[i] += l2 * g; bb[i] += q2 * g;
}
clp[0] = l1; clp[1] = l2; clp[2] = q1; clp[3] = q2;
}
sp0 = sc0; sp1 = sc1; sp2 = sc2;
}
void FrasilVoice::svfRun(float *b, const float *x, int s, float o0i, float o1i, float o2i,
float e0, float e1, float e2) {
float s1 = clp[s], s2 = clp[s + 1];
float o0 = o0i, o1 = o1i, o2 = o2i;
const float a1 = sa1, a2 = sa2, a3 = sa3;
for (int i = 0; i < CH; ++i) {
float v = x[i] - s2;
float t1 = a1 * s1 + a2 * v;
float t2 = s2 + a2 * s1 + a3 * v;
s1 = 2.f * t1 - s1;
s2 = 2.f * t2 - s2;
b[i] += o0 * x[i] + o1 * t1 + o2 * t2;
o0 += e0; o1 += e1; o2 += e2;
}
clp[s] = s1; clp[s + 1] = s2;
}
void FrasilVoice::partialsChunk(float g) {
for (int j = 0; j < np; ++j) {
float *bus = j == 0 ? bc : ((j & 1) == 1 ? ba : bb); // 1, 3, 5, 7 -> ba; 2, 4, 6 -> bb
float x = px[j], y = py[j];
float e = 2.f * ps[j];
float a = pac[j] * g;
float d = pda[j] * g;
for (int i = 0; i < CH; ++i) {
x -= e * y;
y += e * x;
bus[i] += a * x;
a += d;
}
px[j] = x; py[j] = y;
pac[j] += pda[j] * CH;
}
}
void FrasilVoice::breathNoise() {
float grain = cur[GRAIN];
if (grain < 0.002f) {
for (int i = 0; i < CH; ++i) nz[i] = randf();
} else {
float p = kt::powf_(2.f, -13.f * grain) * r44;
float amp = std::fmin(16.f, kt::sqrtf_(1.f / (3.f * 0.5833f * p)));
int32_t th = kt::toInt(p * 16777216.f);
for (int i = 0; i < CH; ++i) {
int32_t r = nextRand();
float a = amp * (0.5f + (float)(r & 255) * (0.5f / 255.f));
nz[i] = (int32_t)((uint32_t)r >> 8) < th ? ((r & 256) != 0 ? a : -a) : 0.f;
}
}
float t = cur[TONE];
if (t < -0.01f) {
float fc = 16000.f * kt::powf_(300.f / 16000.f, -t);
float a = 1.f - kt::expf_(-TWO_PI * std::fmin(fc, nyq) * invFs);
float gn = kt::sqrtf_((2.f - a) / a);
float l = nlp;
for (int i = 0; i < CH; ++i) { l += a * (nz[i] - l); nz[i] = l * gn; }
nlp = flush(l);
} else if (t > 0.01f) {
float fc = 20.f * kt::powf_(150.f, t);
float a = 1.f - kt::expf_(-TWO_PI * fc * invFs);
float gn = 1.f / kt::sqrtf_(1.f + a / (2.f - a) - 2.f * a);
float l = nlp;
for (int i = 0; i < CH; ++i) { l += a * (nz[i] - l); nz[i] = (nz[i] - l) * gn; }
nlp = flush(l);
}
}
void FrasilVoice::souffleChunk(float g) {
float air = cur[AIR];
float ga = air * 0.7f * g;
for (int j = 0; j < NR; ++j) {
float *bus = j == 0 ? bc : (j == 1 ? ba : bb);
float y1 = r1[j], y2 = r2[j];
const float b1 = rb1[j], b2 = rb2[j], gg = rg[j] * g;
bool withAir = j == 0 && air > 0.001f;
for (int i = 0; i < CH; ++i) {
float y = gg * nz[i] + b1 * y1 - b2 * y2;
y2 = y1; y1 = y;
bus[i] += withAir ? y + ga * nz[i] : y;
}
if (y1 > -1e-20f && y1 < 1e-20f && y2 > -1e-20f && y2 < 1e-20f) { y1 = 0.f; y2 = 0.f; }
r1[j] = y1; r2[j] = y2;
}
}
// ----------------------------------------------------------------- helpers ---
float FrasilVoice::brK(float k) const { return 1.f - kt::powf_(1.f - k, r44); }
int32_t FrasilVoice::nextRand() {
uint32_t x = rng;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
rng = x;
return (int32_t)x;
}
float FrasilVoice::randf() { return (float)nextRand() * (1.f / 2147483648.f); }
float FrasilVoice::urand() { return (float)((uint32_t)nextRand() >> 8) * (1.f / 16777216.f); }
} // namespace sizzle::frasil
+186
View File
@@ -0,0 +1,186 @@
// SPDX-FileCopyrightText: 2026 Styves Goupil (FRASIL)
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown (Kotlin port for Sizzle, C++ port)
// SPDX-License-Identifier: MPL-2.0
//
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at
// https://mozilla.org/MPL/2.0/ (also in LICENSES/MPL-2.0.txt of this repository).
//
// Port of frasil/FrasilVoice.kt, FrasilPatch.kt and FrasilDefs.kt (the Morph Pad).
// Kotlin's globals become explicit state: FrasilClock (TIDE's shared time) and
// FrasilSeeds (the companion's seed counter) are owned by the engine and handed in.
#pragma once
#include <cstdint>
namespace sizzle {
class Params;
}
namespace sizzle::frasil {
/** FRASIL's TIDE is one slow sine shared by every voice: the engine advances this
* clock once a block, each voice reads it. Audio thread only. */
struct FrasilClock {
double seconds = 0.0;
void advance(int frames, int sampleRate) { seconds += (double)frames / sampleRate; }
};
/** The Kotlin companion's seed counter (FrasilVoice.nextSeed): each new voice takes
* the next seed. One per engine, so voices get the seeds the Kotlin app gives them. */
struct FrasilSeeds {
uint32_t seeds = 0x2545F491u;
int32_t next() {
seeds += 0x6D2B79F5u;
return seeds == 0 ? (int32_t)0x2545F491 : (int32_t)seeds;
}
};
/** Engine parameter indices (FrasilDefs). */
namespace defs {
constexpr int CHOIR = 0, PARTIALS = 1, BREATH = 2, WARMTH = 3, DETUNE = 4, CUTOFF = 5, TILT = 6,
ODD = 7, STRETCH = 8, RESONANCE = 9, COLOR = 10, ATTACK = 11, RELEASE = 12,
MOTION = 13, MOTION_RATE = 14, TIDE = 15, TIDE_RATE = 16, TIMBRE = 17, SHAPE = 18,
CH_RESO = 19, EVOLVE = 20, BEAT = 21, FORMANT = 22, PEAK = 23, GRAIN = 24, TONE = 25,
AIR = 26, SOFT = 27, VELOCITY = 28, BODY = 29, INTERVAL = 30, BR_PITCH = 31, N = 32;
constexpr const char *MORPH_TO = "morphTo";
constexpr const char *MORPH = "morph";
constexpr const char *MORPH_TIME = "mtime";
/** FRASIL's 36 drone presets (MORPH TO's targets). */
int factoryCount();
const char *factoryName(int i);
} // namespace defs
/** A Morph Pad slot's snapshot (FrasilPatch): build it off the audio thread. */
struct FrasilPatch {
float a[defs::N] = {};
int aType = 0;
bool hasB = false; // Kotlin's b != null
float b[defs::N] = {};
int bType = 0;
/** Where a note starts between a (0) and b (1). */
float morph = 0.f;
/** Seconds a held note takes from morph to b; 0 stays at morph. */
float morphTime = 0.f;
/** FrasilPatch.from(slot); nullptr is Kotlin's from(null) (all defaults). */
static FrasilPatch from(const Params *slot);
static FrasilPatch from(const Params &slot) { return from(&slot); }
/** FrasilPatch.DEFAULT. */
static FrasilPatch defaults() { return from(nullptr); }
};
/** One note of the Morph Pad (FrasilVoice). Allocation-free; the patch is copied in. */
class FrasilVoice {
public:
static constexpr int NP = 8;
static constexpr int NR = 3;
static constexpr int CH = 64;
static constexpr int BLOCK = 256;
/** [clock] must outlive the voice; [seed] from the engine's FrasilSeeds. */
FrasilVoice(int fs, const FrasilClock &clock, int32_t seed);
int note() const { return note_; }
bool isActive() const { return note_ >= 0; }
bool isGated() const { return note_ >= 0 && gate; }
/** Start [midi] at [velocity] (0..1); a sounding voice goes on from where it is. */
void noteOn(int midi, float velocity, const FrasilPatch &p);
void noteOff() { gate = false; }
/** Silence now, no tail. */
void kill();
/** Follow edits while sounding: the values glide there over ~25 ms. */
void setPatch(const FrasilPatch &p) { patch = p; }
/** A gliding engine value now (a defs index), for tests. */
float valueForTest(int i) const { return cur[i]; }
float render();
private:
void start();
void block();
float morphPosition(const FrasilPatch &p) const;
float ou(float x, float th, float s);
void drift();
void voiceBlock(bool fresh);
void renderChunk();
void choirChunk(float g0);
void svfRun(float *b, const float *x, int s, float o0i, float o1i, float o2i, float e0, float e1, float e2);
void partialsChunk(float g);
void breathNoise();
void souffleChunk(float g);
float brK(float k) const;
int32_t nextRand();
float randf();
float urand();
const FrasilClock *clock;
const float invFs;
const float r44;
const float nyq;
int note_ = -1;
bool gate = false;
float vel = 0.f;
float env = 0.f;
float lvl = 0.f;
FrasilPatch patch;
bool prime = true;
float cur[defs::N] = {};
int type = 0;
int64_t ageFrames = 0;
float tideV = 0.f;
uint32_t rng;
// drift
float ouC[3] = {};
float ouCut = 0.f;
float ouPa[NP] = {};
float ouPf[NP] = {};
float ouR[NR] = {};
// CHOIR
float cph[3] = {}, cdt[3] = {}, cid[3] = {}, cw[3] = {}, cpw[3] = {};
float csh = 0.f;
float sc0 = 0.f, sc1 = 0.f, sc2 = 1.f;
float sp0 = 0.f, sp1 = 0.f, sp2 = 1.f;
float clp[4] = {};
float ca = 0.f;
float sa1 = 0.f, sa2 = 0.f, sa3 = 0.f;
float cgain = 1.f;
float cint[6] = {};
bool csvf = false;
// PARTIALS
float px[NP] = {}, py[NP] = {}, pa[NP] = {}, ps[NP] = {}, pc[NP] = {};
float pac[NP] = {}, pda[NP] = {}, pbt[NP] = {};
int np = 0;
// BREATH
float r1[NR] = {}, r2[NR] = {}, rb1[NR] = {}, rb2[NR] = {}, rg[NR] = {};
float nlp = 0.f;
// output stages
float dcState = 0.f;
float thinState = 0.f;
float ka = 0.f, kr = 0.f;
float dk = 1.f, dmake = 1.f;
bool driveOn = false;
float thinA = 0.f;
bool thin = false;
const float kdc;
const float glideK;
const float tideK;
// chunk buffers
float bc[CH] = {}, ba[CH] = {}, bb[CH] = {};
float x0[CH] = {}, x1[CH] = {}, xc[CH] = {};
float nz[CH] = {};
float out[CH] = {};
int pos = CH;
int chunk = 0;
bool ending = false;
};
} // namespace sizzle::frasil
+401
View File
@@ -0,0 +1,401 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of AmbienceReverb.kt: mono 8-line FDN reverb (OTODESK "Ambience" style) with
// predelay, early reflections, input diffusers, nested allpasses, xorshift-noise
// LFOs, ducking and wet saturation. Line-for-line; Float stays float.
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <vector>
#include "sizzle/Effect.hpp"
#include "KotlinMath.hpp"
// The JVM never fuses a*b+c; keep the compiler from contracting into FMA.
#if defined(__clang__)
#pragma clang fp contract(off)
#endif
namespace sizzle {
namespace {
constexpr int N = 8;
const float FWHT_NORM = 1.f / kt::sqrtf_((float)N);
constexpr float LATE_SCALE = 2.f / N;
constexpr int MAX_ER = 12;
constexpr int MAX_ER_ACTIVE = 6;
constexpr float PHI = 1.6180339887f;
constexpr float TWO_PI = 6.28318530718f;
const float ALGO_HF[] = {0.00f, 0.26f, 0.26f, 0.22f, 0.36f, 0.14f, 0.30f};
const float ALGO_OFFSET_DB[] = {0.8f, 0.9f, 0.5f, 0.5f, 1.5f, 0.6f, 0.6f};
const float ALGO_SAT_MUL[] = {0.90f, 0.90f, 0.93f, 0.93f, 1.00f, 1.05f, 1.02f};
const float SIGN_FLIP[N] = {1.f, -1.f, 1.f, -1.f, -1.f, 1.f, -1.f, 1.f};
const char *const ALGORITHMS[] = {"Room 1", "Room 2", "Hall 1", "Hall 2", "Plate", "Spring", "Goldfoil"};
const float ER_ROOM1[] = {
5.2f, 0.65f, 8.7f, 0.58f, 12.4f, 0.52f, 15.8f, 0.46f, 19.3f, 0.42f, 24.1f, 0.36f,
28.6f, 0.32f, 33.5f, 0.28f, 38.9f, 0.24f, 45.2f, 0.20f, 52.8f, 0.16f, 62.4f, 0.13f,
};
const float ER_ROOM2[] = {
7.5f, 0.62f, 12.3f, 0.55f, 17.1f, 0.49f, 22.8f, 0.43f, 28.5f, 0.38f, 34.2f, 0.33f,
41.6f, 0.28f, 49.3f, 0.24f, 57.8f, 0.20f, 67.5f, 0.17f, 78.2f, 0.14f, 90.6f, 0.11f,
};
const float ER_HALL1[] = {
12.0f, 0.58f, 18.5f, 0.52f, 25.7f, 0.47f, 33.4f, 0.42f, 42.1f, 0.38f, 51.6f, 0.33f,
62.3f, 0.29f, 73.9f, 0.25f, 86.5f, 0.21f, 99.8f, 0.18f, 113.4f, 0.15f, 128.7f, 0.12f,
};
const float ER_HALL2[] = {
16.5f, 0.55f, 24.8f, 0.50f, 33.7f, 0.45f, 43.5f, 0.40f, 54.2f, 0.36f, 65.8f, 0.32f,
78.4f, 0.28f, 92.1f, 0.24f, 107.3f, 0.21f, 123.6f, 0.18f, 141.2f, 0.15f, 160.5f, 0.12f,
};
const float *const ER_PATTERNS[] = {ER_ROOM1, ER_ROOM2, ER_HALL1, ER_HALL2, nullptr, nullptr, nullptr};
const int ER_PATTERN_SIZE[] = {24, 24, 24, 24, 0, 0, 0};
inline float lnf_(float x) { return (float)std::log((double)x); }
inline float floorf_(float x) { return (float)std::floor((double)x); }
inline float pow10(float x) { return kt::expf_(x * 2.302585093f); }
inline float db2lin(float db) { return pow10(db / 20.f); }
/** In-place size-N Fast Walsh-Hadamard transform, normalised (÷√N) → orthonormal. */
void fwht(float *v) {
int h = 1;
while (h < N) {
int i = 0;
while (i < N) {
int j = i;
while (j < i + h) {
float a = v[j]; float b = v[j + h];
v[j] = a + b; v[j + h] = a - b;
j++;
}
i += h * 2;
}
h *= 2;
}
for (int k = 0; k < N; ++k) v[k] *= FWHT_NORM;
}
bool isPrime(int n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
int i = 3;
while (i * i <= n) { if (n % i == 0) return false; i += 2; }
return true;
}
bool usedNone(const int *used, int count, int v) {
for (int k = 0; k < count; ++k) if (used[k] == v) return false;
return true;
}
int nearestUniquePrime(int target, const int *used, int count) {
int t = std::max(target, 2);
int offset = 0;
while (offset < 100000) {
int hi = t + offset;
if (isPrime(hi) && usedNone(used, count, hi)) return hi;
int lo = t - offset;
if (offset > 0 && lo >= 2 && isPrime(lo) && usedNone(used, count, lo)) return lo;
offset++;
}
return t;
}
float softClip(float x) {
if (x > 1.f) return 1.f - 1.f / (x + 1.f);
if (x < -1.f) return -1.f + 1.f / (-x + 1.f);
return x;
}
/** A power-of-two circular buffer with fractional (linear-interpolated) reads. */
class DelayLine {
std::vector<float> buf;
int mask;
int w = 0;
public:
explicit DelayLine(int size) {
int p = 1;
while (p < size) p *= 2;
buf.assign((size_t)p, 0.f);
mask = p - 1;
}
float maxDelay() const { return (float)(mask - 2); }
void write(float x) { buf[(size_t)w] = x; w = (w + 1) & mask; }
float read(float delay) const {
float d = kt::coerceIn(delay, 1.f, (float)mask - 1.f);
float rp = (float)w - d;
float i0f = floorf_(rp);
float frac = rp - i0f;
int i0 = kt::toInt(i0f) & mask;
int i1 = (i0 + 1) & mask;
return buf[(size_t)i0] * (1.f - frac) + buf[(size_t)i1] * frac;
}
};
class AmbienceReverb final : public Effect {
float fs;
DelayLine preDelay;
DelayLine erLine;
std::vector<DelayLine> diffusers;
std::vector<DelayLine> fdn;
std::vector<DelayLine> apf;
float fbVec[N] = {};
float fbScratch[N] = {};
float nextFb[N] = {};
float baseDelay[N] = {};
float decayGain[N] = {};
float hfState[N] = {};
float lfState[N] = {};
float freqMod[N];
float apfBase[N];
float diffuserSmp[4];
int32_t lfoState[N];
float lfoSmooth[N] = {};
float lfoCoeff[N] = {};
float lfoRateMul[N];
float hfCoeff = 1.f;
float lfCoeff = 0.f;
float lfAmt = 0.f;
float apfGain = 0.5f;
float diffusionSens = 1.f;
bool bypassER = false;
float makeup = 1.f;
float satMul = 1.f;
float modDepthScale = 1.f;
int erCount = 0;
float erDelaySmp[MAX_ER] = {};
float erGain[MAX_ER] = {};
float wetLin = 0.63f;
float dryLin = 1.f;
float preDelaySmp = 480.f;
float modDepth = 0.f;
float diffGain = 0.63f;
float effApfGain = 0.4f;
float satAmt = 0.f;
float erLevel = 0.6f;
float duckAmtDb = 0.f;
float duckThreshDb = -20.f;
float duckThreshLin = 0.1f;
float duckAtt = 0.01f;
float duckRel = 0.001f;
float duckEnv = 0.f;
float dc1 = 0.f;
float dcY = 0.f;
int lastAlgo = -1;
float lastSize = NAN;
float lastDecay = NAN;
float lastHf = NAN;
float lastLf = NAN;
float lastDiffusion = NAN;
void recompute(int algo, float size, float decay, float hf, float lf, float diffusion) {
(void)diffusion;
switch (algo) {
case 0: case 1: apfGain = 0.3f; diffusionSens = 1.f; bypassER = false; break;
case 2: case 3: apfGain = 0.618f; diffusionSens = 1.f; bypassER = false; break;
case 4: apfGain = 0.7f; diffusionSens = 0.7f; bypassER = true; break;
case 5: apfGain = 0.5f; diffusionSens = 0.5f; bypassER = true; break;
default: apfGain = 0.75f; diffusionSens = 0.8f; bypassER = true; break;
}
float sizeCoeff = kt::coerceIn(size + 0.5f, 0.5f, 2.f);
float minMs = 15.f + sizeCoeff * 7.5f;
float maxMs = 50.f + sizeCoeff * 75.f;
int minS = std::max(11, kt::toInt(minMs * 0.001f * fs));
int maxS = kt::coerceAtLeast(kt::toInt(maxMs * 0.001f * fs), minS + 1);
float logMin = lnf_((float)minS);
float logMax = lnf_((float)maxS);
int used[N] = {};
for (int i = 0; i < N; ++i) {
float t = (float)i / ((float)N - 1.f);
int target = kt::toInt(kt::expf_(logMin + t * (logMax - logMin)));
int p = nearestUniquePrime(target, used, i);
used[i] = p;
baseDelay[i] = kt::coerceAtMost((float)p, fdn[(size_t)i].maxDelay());
}
for (int i = 0; i < N; ++i) {
float tSec = baseDelay[i] / fs;
decayGain[i] = kt::coerceIn(pow10(-3.f * tSec / decay), 0.f, 0.9995f);
}
float totalHf = kt::coerceIn(hf + ALGO_HF[algo], 0.f, 0.95f);
float hfCut = 16000.f * (1.f - totalHf) + 700.f * totalHf;
hfCoeff = kt::coerceIn(1.f - kt::expf_(-TWO_PI * hfCut / fs), 0.02f, 1.f);
lfCoeff = kt::coerceIn(1.f - kt::expf_(-TWO_PI * 200.f / fs), 0.f, 1.f);
lfAmt = lf * 0.9f;
modDepthScale = 1.f + kt::coerceIn((decay - 1.f) * 0.5f, 0.f, 2.f);
float decayCompDb = 7.f * kt::log10f_(kt::coerceAtLeast(decay, 0.1f));
makeup = db2lin(16.f + decayCompDb + ALGO_OFFSET_DB[algo]);
satMul = ALGO_SAT_MUL[algo];
const float *pattern = ER_PATTERNS[algo];
erCount = bypassER ? 0 : std::min(ER_PATTERN_SIZE[algo] / 2, MAX_ER_ACTIVE);
float erSizeScale = 0.5f + size;
for (int t = 0; t < erCount; ++t) {
erDelaySmp[t] = kt::coerceIn(pattern[t * 2] * 0.001f * fs * erSizeScale, 1.f, erLine.maxDelay());
erGain[t] = pattern[t * 2 + 1];
}
}
float nextLfo(int i) {
uint32_t s = (uint32_t)lfoState[i];
s = s ^ (s << 13); s = s ^ (s >> 17); s = s ^ (s << 5);
lfoState[i] = (int32_t)s;
float n = (float)s * 2.3283064e-10f * 2.f - 1.f;
lfoSmooth[i] += (n - lfoSmooth[i]) * lfoCoeff[i];
return lfoSmooth[i];
}
public:
explicit AmbienceReverb(int sampleRate)
: fs((float)sampleRate),
preDelay(kt::toInt(fs * 0.55f)),
erLine(kt::toInt(fs * 0.6f)) {
diffusers.reserve(4);
for (int i = 0; i < 4; ++i) diffusers.emplace_back(kt::toInt(fs * 0.03f));
fdn.reserve(N);
apf.reserve(N);
for (int i = 0; i < N; ++i) fdn.emplace_back(kt::toInt(fs * 0.3f));
for (int i = 0; i < N; ++i) apf.emplace_back(kt::toInt(fs * 0.03f));
for (int it = 0; it < N; ++it) {
freqMod[it] = 0.5f + (1.f - (float)it / ((float)N - 1.f));
apfBase[it] = (2.3f + (float)it * 0.37f) * 0.001f * fs;
lfoState[it] = 12345 + it * 9876;
float a = (float)it * PHI;
lfoRateMul[it] = 0.8f + (a - floorf_(a)) * 0.4f;
}
for (int it = 0; it < 4; ++it) diffuserSmp[it] = (3.f + (float)it * 2.f) * 0.001f * fs;
}
void update(const Params &p, float) override {
const char *algoName = p.s("algo", "Room 1");
int algo = -1;
for (int k = 0; k < 7; ++k) if (std::strcmp(ALGORITHMS[k], algoName) == 0) { algo = k; break; }
algo = kt::coerceIn(algo, 0, 6);
float size = kt::coerceIn(p.f("roomsize", 1.f), 0.3f, 2.f);
float decay = kt::coerceIn(p.f("decay", 1.5f), 0.1f, 20.f);
float hf = kt::coerceIn(p.f("hfdamp", 0.f), 0.f, 1.f);
float lf = kt::coerceIn(p.f("lfabsorb", 0.f), 0.f, 1.f);
float diffusion = kt::coerceIn(p.f("diffusion", 0.7f), 0.f, 1.f);
wetLin = db2lin(p.f("wet", -4.f));
dryLin = db2lin(p.f("dry", 0.f));
preDelaySmp = kt::coerceIn(p.f("predelay", 10.f), 0.f, 500.f) * 0.001f * fs;
erLevel = kt::coerceIn(p.f("erlevel", 0.6f), 0.f, 1.f);
satAmt = kt::coerceIn(p.f("saturation", 0.f), 0.f, 1.f);
float modAmt = kt::coerceIn(p.f("modamt", 0.25f), 0.f, 1.f);
float modRate = kt::coerceIn(p.f("modrate", 0.5f), 0.05f, 2.f);
// Uses the modDepthScale from the previous recompute (as the Kotlin does).
modDepth = modAmt * modAmt * 0.001f * fs * modDepthScale;
for (int i = 0; i < N; ++i) {
lfoCoeff[i] = kt::coerceIn(1.f - kt::expf_(-TWO_PI * modRate * lfoRateMul[i] / fs), 0.0001f, 0.9999f);
}
duckAmtDb = kt::coerceIn(p.f("duckamt", 0.f), 0.f, 20.f);
duckThreshDb = p.f("duckthresh", -20.f);
duckThreshLin = db2lin(duckThreshDb);
duckAtt = 1.f - kt::expf_(-1.f / (fs * kt::coerceAtLeast(p.f("duckattack", 10.f), 0.1f) * 0.001f));
duckRel = 1.f - kt::expf_(-1.f / (fs * kt::coerceAtLeast(p.f("duckrelease", 200.f), 0.1f) * 0.001f));
float effDiff = diffusion * diffusionSens;
diffGain = 0.25f + effDiff * 0.55f;
effApfGain = apfGain * (0.6f + effDiff * 0.4f) * 0.78f;
if (algo != lastAlgo || size != lastSize || decay != lastDecay ||
hf != lastHf || lf != lastLf || diffusion != lastDiffusion) {
lastAlgo = algo; lastSize = size; lastDecay = decay;
lastHf = hf; lastLf = lf; lastDiffusion = diffusion;
recompute(algo, size, decay, hf, lf, diffusion);
float d2 = diffusion * diffusionSens;
diffGain = 0.25f + d2 * 0.55f;
effApfGain = apfGain * (0.6f + d2 * 0.4f) * 0.78f;
}
}
float process(float x) override {
preDelay.write(x);
float din = preDelaySmp > 0.5f ? preDelay.read(preDelaySmp) : x;
float peak = std::fabs(x);
duckEnv += (peak - duckEnv) * (peak > duckEnv ? duckAtt : duckRel);
float duckGain = 1.f;
if (duckAmtDb > 0.001f && duckEnv > duckThreshLin) {
float overDb = 20.f * kt::log10f_(std::max(duckEnv, 1e-6f)) - duckThreshDb;
duckGain = db2lin(-std::min(overDb, duckAmtDb));
}
float fdnIn = din;
for (int i = 0; i < 4; ++i) {
float d = diffusers[(size_t)i].read(diffuserSmp[i]);
float w = fdnIn + diffGain * d;
diffusers[(size_t)i].write(w);
fdnIn = d - diffGain * w;
}
float er = 0.f;
if (!bypassER) {
erLine.write(din);
for (int t = 0; t < erCount; ++t) er += erLine.read(erDelaySmp[t]) * erGain[t] * 0.5f;
fdnIn += er * 0.15f;
}
std::memcpy(fbScratch, fbVec, sizeof(fbScratch));
fwht(fbScratch);
for (int i = 0; i < N; ++i) fbScratch[i] *= SIGN_FLIP[i];
float inPerCh = fdnIn * 0.25f;
float out = 0.f;
for (int i = 0; i < N; ++i) {
float lfo = nextLfo(i);
DelayLine &line = fdn[(size_t)i];
float d = line.read(baseDelay[i] + lfo * modDepth * freqMod[i]);
d *= decayGain[i];
hfState[i] += hfCoeff * (d - hfState[i]); d = hfState[i];
lfState[i] += lfCoeff * (d - lfState[i]); d -= lfAmt * lfState[i];
DelayLine &ap = apf[(size_t)i];
float ad = ap.read(apfBase[i] + lfo * modDepth * 0.1f * freqMod[i]);
float aw = d + effApfGain * ad;
ap.write(aw);
float apfOut = ad - effApfGain * aw;
nextFb[i] = apfOut;
line.write(inPerCh + fbScratch[i]);
out += apfOut;
}
std::memcpy(fbVec, nextFb, sizeof(fbVec));
float late = out * LATE_SCALE * makeup;
float amt = kt::coerceIn(satAmt * satMul, 0.f, 1.f);
if (amt > 0.0001f) late += amt * (kt::tanhf_(late * 2.f) * 0.5f - late);
float wetRaw = (bypassER ? 0.f : er * erLevel) + late;
float dcOut = wetRaw - dc1 + 0.999f * dcY;
dc1 = wetRaw; dcY = dcOut;
float wet = softClip(dcOut * wetLin * duckGain);
return x * dryLin + wet;
}
};
} // namespace
std::unique_ptr<Effect> makeAmbienceReverb(int sampleRate) {
return std::make_unique<AmbienceReverb>(sampleRate);
}
} // namespace sizzle
+42
View File
@@ -0,0 +1,42 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of Bitcrusher (Effects.kt): bit-depth reduction + sample-rate reduction + drive.
#include "sizzle/Effect.hpp"
#include "KotlinMath.hpp"
namespace sizzle {
namespace {
class Bitcrusher final : public Effect {
float levels = 256.f;
int downsample = 1;
float drive = 1.f;
int counter = 0;
float held = 0.f;
public:
void update(const Params &p, float) override {
float bits = kt::coerceIn(p.f("bits", 8.f), 1.f, 16.f);
levels = kt::powf_(2.f, bits);
downsample = kt::coerceAtLeast(kt::toInt(p.f("downsample", 1.f)), 1);
drive = 1.f + p.f("drive", 0.2f) * 4.f;
}
float process(float x) override {
if (counter <= 0) {
counter = downsample;
float driven = kt::tanhf_(x * drive);
held = (float)kt::roundToInt(driven * levels) / levels;
}
counter--;
return held;
}
};
} // namespace
std::unique_ptr<Effect> makeBitcrusher(int) { return std::make_unique<Bitcrusher>(); }
} // namespace sizzle
+111
View File
@@ -0,0 +1,111 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of BiquadFilterEffect (Effects.kt): RBJ LP/HP/BP biquad whose cutoff an
// input-level-gated ADSR opens, plus soft-saturation "warmth".
#include <algorithm>
#include <cmath>
#include <cstring>
#include "sizzle/Effect.hpp"
#include "KotlinMath.hpp"
namespace sizzle {
namespace {
constexpr int CTRL_INTERVAL = 32;
constexpr float GATE_HI = 0.010f;
constexpr float GATE_LO = 0.004f;
class Filter final : public Effect {
double b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0, z1 = 0, z2 = 0;
int sampleRate;
float sr;
enum Type { LPF, HPF, BPF } type = LPF;
float baseCutoff = 0.7f;
double q = 1.0;
float warmth = 0.f, envAmount = 0.f;
enum Phase { IDLE, ATTACK, DECAY, SUSTAIN, RELEASE } phase = IDLE;
float env = 0.f, attackInc = 1.f, decayInc = 1.f, sustainLevel = 1.f;
float releaseSeconds = 0.2f, releaseInc = 1.f, levelEnv = 0.f, levelCoeff = 0.f;
bool gateOpen = false;
int ctrl = 0;
void computeCoefficients(Type t, double freq, double qq) {
double w0 = 2.0 * M_PI * freq / sampleRate;
double cosW = std::cos(w0);
double alpha = std::sin(w0) / (2.0 * qq);
double a0;
switch (t) {
case HPF:
b0 = (1 + cosW) / 2; b1 = -(1 + cosW); b2 = (1 + cosW) / 2;
a0 = 1 + alpha; a1 = -2 * cosW; a2 = 1 - alpha; break;
case BPF:
b0 = alpha; b1 = 0.0; b2 = -alpha;
a0 = 1 + alpha; a1 = -2 * cosW; a2 = 1 - alpha; break;
default:
b0 = (1 - cosW) / 2; b1 = 1 - cosW; b2 = (1 - cosW) / 2;
a0 = 1 + alpha; a1 = -2 * cosW; a2 = 1 - alpha; break;
}
b0 /= a0; b1 /= a0; b2 /= a0; a1 /= a0; a2 /= a0;
}
public:
explicit Filter(int rate) : sampleRate(rate), sr((float)rate) {}
void update(const Params &p, float) override {
const char *t = p.s("type", "LPF");
type = std::strcmp(t, "HPF") == 0 ? HPF : std::strcmp(t, "BPF") == 0 ? BPF : LPF;
baseCutoff = kt::coerceIn(p.f("cutoff", 0.7f), 0.f, 1.f);
q = (double)(0.5 + p.f("resonance", 0.2f) * 8.f);
warmth = kt::coerceIn(p.f("warmth", 0.f), 0.f, 1.f);
envAmount = kt::coerceIn(p.f("envamt", 0.f), 0.f, 1.f);
sustainLevel = kt::coerceIn(p.f("sustain", 1.f), 0.f, 1.f);
attackInc = 1.f / (std::max(p.f("attack", 0.005f), 0.0005f) * sr);
float decay = p.f("decay", 0.10f);
decayInc = decay <= 0.f ? 1.f : (1.f - sustainLevel) / (decay * sr);
releaseSeconds = p.f("release", 0.20f);
levelCoeff = 1.f - kt::expf_(-1.f / (sr * 0.005f));
ctrl = 0;
}
float process(float x) override {
levelEnv += (std::fabs(x) - levelEnv) * levelCoeff;
if (!gateOpen && levelEnv > GATE_HI) {
gateOpen = true; phase = ATTACK;
} else if (gateOpen && levelEnv < GATE_LO) {
gateOpen = false;
releaseInc = releaseSeconds <= 0.f ? 1.f : env / (releaseSeconds * sr);
if (releaseInc <= 0.f) releaseInc = 1.f;
phase = RELEASE;
}
switch (phase) {
case ATTACK: env += attackInc; if (env >= 1.f) { env = 1.f; phase = DECAY; } break;
case DECAY: env -= decayInc; if (env <= sustainLevel) { env = sustainLevel; phase = SUSTAIN; } break;
case RELEASE: env -= releaseInc; if (env <= 0.f) { env = 0.f; phase = IDLE; } break;
default: break;
}
if (ctrl <= 0) {
ctrl = CTRL_INTERVAL;
float eff = kt::coerceIn(baseCutoff + envAmount * env * (1.f - baseCutoff), 0.f, 1.f);
double freq = 20.0 * std::pow(900.0, (double)eff);
computeCoefficients(type, kt::coerceIn(freq, 20.0, sampleRate * 0.45), q);
}
ctrl--;
double input = (double)x;
double out = b0 * input + z1;
z1 = b1 * input - a1 * out + z2;
z2 = b2 * input - a2 * out;
float y = (float)out;
if (warmth > 0.0001f) y += warmth * (kt::tanhf_(y * 1.8f) / 1.8f - y);
return y;
}
};
} // namespace
std::unique_ptr<Effect> makeFilter(int sr) { return std::make_unique<Filter>(sr); }
} // namespace sizzle
+129
View File
@@ -0,0 +1,129 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of GranularGlitch (Effects.kt): a rolling 1 s buffer whose read head randomly
// jumps back to replay short (sometimes octave-shifted) grains, dry in between. Also
// its VizEffect side: a decimated scope of the incoming signal and the read head's
// place in that window, written here with relaxed atomics (plain stores on arm64 and
// x86) and read by the editor from the UI thread. It never feeds back into the audio.
#include <atomic>
#include <cstdint>
#include <vector>
#include "sizzle/Effect.hpp"
#include "KotlinMath.hpp"
namespace sizzle {
namespace {
constexpr float MAX_TRIGGER = 0.0009f;
constexpr float MIN_JUMP_S = 0.03f;
constexpr float MAX_JUMP_S = 0.5f;
constexpr float GRAIN_MIN_S = 0.02f;
constexpr float GRAIN_MAX_S = 0.15f;
constexpr int SCOPE_N = 96; // scope points drawn
constexpr int SCOPE_DECIM = 96; // input samples per point (~192 ms window at 48 kHz)
class GranularGlitch final : public Effect {
int sampleRate;
std::vector<float> buf;
int size;
int writePos = 0;
double readPos = 0.0;
int grainLeft = 0;
double grainRate = 1.0;
float intensity = 0.f;
uint32_t rng = 0x2F6E1DB7u;
// Visualisation: a ring of decimated INPUT samples plus the normalised read head.
std::atomic<float> scope[SCOPE_N];
std::atomic<int> scopeWrite{0};
int decCount = 0;
std::atomic<float> playheadNorm{1.f};
float nextUnit() {
uint32_t s = rng; s ^= s << 13; s ^= s >> 17; s ^= s << 5; rng = s;
return (float)s * 2.3283064e-10f; // 0 … 1
}
bool maybeStartGrain(int wp) {
if (nextUnit() > intensity * intensity * MAX_TRIGGER) return false;
float minJ = MIN_JUMP_S * (float)sampleRate;
float maxJ = (MIN_JUMP_S + intensity * (MAX_JUMP_S - MIN_JUMP_S)) * (float)sampleRate;
float jump = minJ + nextUnit() * (maxJ - minJ);
double rp = (double)wp - (double)jump;
while (rp < 0) rp += size;
readPos = rp;
float lenSec = GRAIN_MAX_S - intensity * (GRAIN_MAX_S - GRAIN_MIN_S);
grainLeft = kt::coerceAtLeast(kt::toInt(lenSec * (float)sampleRate * (0.5f + nextUnit())), 64);
if (nextUnit() < intensity * 0.3f) grainRate = 2.0;
else if (nextUnit() < intensity * 0.2f) grainRate = 0.5;
else grainRate = 1.0;
return true;
}
public:
explicit GranularGlitch(int rate) : sampleRate(rate), buf((size_t)rate, 0.f), size(rate) {
for (auto &v : scope) v.store(0.f, std::memory_order_relaxed);
}
void update(const Params &p, float) override {
intensity = kt::coerceIn(p.f("intensity", 0.3f), 0.f, 1.f);
}
float process(float x) override {
int wp = writePos;
buf[wp] = x;
writePos++; if (writePos >= size) writePos = 0;
float out;
if (grainLeft <= 0 && (intensity < 0.001f || !maybeStartGrain(wp))) {
readPos = (double)wp;
out = x;
} else {
int i0 = (int)readPos % size;
int i1 = (i0 + 1) % size;
float frac = (float)(readPos - (int)readPos);
out = buf[i0] + (buf[i1] - buf[i0]) * frac;
double rp = readPos + grainRate;
if (rp >= size) rp -= size;
if (rp < 0) rp += size;
double gap = wp - rp; if (gap < 0) gap += size;
if (gap < 2.0) { rp = wp - 2.0; if (rp < 0) rp += size; }
readPos = rp;
grainLeft--;
}
// Scope: decimate the incoming signal into the ring.
if (++decCount >= SCOPE_DECIM) {
decCount = 0;
int sw = scopeWrite.load(std::memory_order_relaxed);
scope[sw].store(x, std::memory_order_relaxed);
sw++; if (sw >= SCOPE_N) sw = 0;
scopeWrite.store(sw, std::memory_order_relaxed);
}
// Playhead: where the read head sits within the displayed window (0 oldest … 1 now).
double behind = wp - readPos; if (behind < 0) behind += size;
playheadNorm.store(kt::coerceIn(1.f - (float)behind / (float)(SCOPE_N * SCOPE_DECIM), 0.f, 1.f),
std::memory_order_relaxed);
return out;
}
bool hasScope() const override { return true; }
int copyScope(float *out, int capacity) const override {
int n = capacity < SCOPE_N ? capacity : SCOPE_N;
if (n < 0) n = 0;
int start = scopeWrite.load(std::memory_order_relaxed); // oldest sample in the ring
for (int k = 0; k < n; ++k) out[k] = scope[(start + k) % SCOPE_N].load(std::memory_order_relaxed);
return n;
}
float playhead() const override { return playheadNorm.load(std::memory_order_relaxed); }
};
} // namespace
std::unique_ptr<Effect> makeGranularGlitch(int sr) { return std::make_unique<GranularGlitch>(sr); }
} // namespace sizzle
+67
View File
@@ -0,0 +1,67 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of GraphicEq (Effects.kt): ten peaking biquads at octave-spaced centres.
#include <cmath>
#include "sizzle/Effect.hpp"
#include "KotlinMath.hpp"
namespace sizzle {
namespace {
struct PeakBiquad {
double b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0, z1 = 0, z2 = 0;
void set(int sampleRate, float freq, float gainDb) {
if (freq >= sampleRate * 0.45f) return;
double a = std::pow(10.0, gainDb / 40.0);
double w0 = 2.0 * M_PI * freq / sampleRate;
double cosW = std::cos(w0);
double alpha = std::sin(w0) / (2.0 * 1.0);
double a0 = 1 + alpha / a;
b0 = (1 + alpha * a) / a0;
b1 = (-2 * cosW) / a0;
b2 = (1 - alpha * a) / a0;
a1 = (-2 * cosW) / a0;
a2 = (1 - alpha / a) / a0;
}
float process(float x) {
double input = (double)x;
double out = b0 * input + z1;
z1 = b1 * input - a1 * out + z2;
z2 = b2 * input - a2 * out;
return (float)out;
}
};
class GraphicEq final : public Effect {
static constexpr float centers[10] = {31.f, 63.f, 125.f, 250.f, 500.f, 1000.f, 2000.f, 4000.f, 8000.f, 16000.f};
static constexpr const char *keys[10] = {"band0", "band1", "band2", "band3", "band4",
"band5", "band6", "band7", "band8", "band9"};
PeakBiquad bands[10];
int sampleRate;
public:
explicit GraphicEq(int sr) : sampleRate(sr) {}
void update(const Params &p, float) override {
for (int i = 0; i < 10; ++i) {
float gainDb = kt::coerceIn(p.f(keys[i], 0.f), -1.f, 1.f) * 12.f;
bands[i].set(sampleRate, centers[i], gainDb);
}
}
float process(float x) override {
float y = x;
for (auto &b : bands) y = b.process(y);
return y;
}
};
} // namespace
std::unique_ptr<Effect> makeGraphicEq(int sr) { return std::make_unique<GraphicEq>(sr); }
} // namespace sizzle
+34
View File
@@ -0,0 +1,34 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Kotlin/JVM math semantics, so ports read like the Kotlin and match its output.
// kotlin.math on Float goes through Java's double Math and rounds back to float.
#include <cmath>
namespace sizzle::kt {
inline float tanhf_(float x) { return (float)std::tanh((double)x); }
inline float expf_(float x) { return (float)std::exp((double)x); }
inline float sinf_(float x) { return (float)std::sin((double)x); }
inline float cosf_(float x) { return (float)std::cos((double)x); }
inline float powf_(float a, float b) { return (float)std::pow((double)a, (double)b); }
inline float sqrtf_(float x) { return (float)std::sqrt((double)x); }
inline float log10f_(float x) { return (float)std::log10((double)x); }
/** Float.roundToInt(): Math.round, i.e. floor(x + 0.5). */
inline int roundToInt(float x) { return (int)std::floor((double)x + 0.5); }
inline int roundToInt(double x) { return (int)std::floor(x + 0.5); }
/** Float.toInt(): truncation toward zero, NaN → 0, saturating. */
inline int toInt(float x) {
if (std::isnan(x)) return 0;
if (x >= 2147483647.f) return 2147483647;
if (x <= -2147483648.f) return (-2147483647 - 1);
return (int)x;
}
template <class T> inline T coerceIn(T v, T lo, T hi) { return v < lo ? lo : (v > hi ? hi : v); }
template <class T> inline T coerceAtLeast(T v, T lo) { return v < lo ? lo : v; }
template <class T> inline T coerceAtMost(T v, T hi) { return v > hi ? hi : v; }
} // namespace sizzle::kt
+190
View File
@@ -0,0 +1,190 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of MixTightener (Effects.kt): parametric EQ -> 3-band multiband compressor ->
// peak limiter, morphed by one Strength control; per-band values are hidden params
// set by presets. Includes the private Bq biquad (TDF-II, double state).
#include <cmath>
#include "sizzle/Effect.hpp"
#include "KotlinMath.hpp"
namespace sizzle {
namespace {
class Bq {
double b0 = 1.0, b1 = 0.0, b2 = 0.0;
double a1 = 0.0, a2 = 0.0;
double z1 = 0.0, z2 = 0.0;
void setRaw(double nb0, double nb1, double nb2, double a0, double na1, double na2) {
b0 = nb0 / a0; b1 = nb1 / a0; b2 = nb2 / a0; a1 = na1 / a0; a2 = na2 / a0;
}
public:
void identity() { b0 = 1.0; b1 = 0.0; b2 = 0.0; a1 = 0.0; a2 = 0.0; }
void peak(int sr, float freq, float gainDb, float q) {
float f = kt::coerceIn(freq, 20.f, sr * 0.45f);
double a = std::pow(10.0, gainDb / 40.0);
double w0 = 2.0 * M_PI * f / sr; double cw = std::cos(w0);
double alpha = std::sin(w0) / (2.0 * kt::coerceAtLeast(q, 0.1f));
setRaw(1 + alpha * a, -2 * cw, 1 - alpha * a, 1 + alpha / a, -2 * cw, 1 - alpha / a);
}
void lowShelf(int sr, float freq, float gainDb) {
float f = kt::coerceIn(freq, 20.f, sr * 0.45f);
double a = std::pow(10.0, gainDb / 40.0); double w0 = 2.0 * M_PI * f / sr; double cw = std::cos(w0);
double alpha = std::sin(w0) / 2.0 * std::sqrt(2.0); double ta = 2.0 * std::sqrt(a) * alpha;
setRaw(
a * ((a + 1) - (a - 1) * cw + ta), 2 * a * ((a - 1) - (a + 1) * cw),
a * ((a + 1) - (a - 1) * cw - ta), (a + 1) + (a - 1) * cw + ta,
-2 * ((a - 1) + (a + 1) * cw), (a + 1) + (a - 1) * cw - ta);
}
void highShelf(int sr, float freq, float gainDb) {
float f = kt::coerceIn(freq, 20.f, sr * 0.45f);
double a = std::pow(10.0, gainDb / 40.0); double w0 = 2.0 * M_PI * f / sr; double cw = std::cos(w0);
double alpha = std::sin(w0) / 2.0 * std::sqrt(2.0); double ta = 2.0 * std::sqrt(a) * alpha;
setRaw(
a * ((a + 1) + (a - 1) * cw + ta), -2 * a * ((a - 1) + (a + 1) * cw),
a * ((a + 1) + (a - 1) * cw - ta), (a + 1) - (a - 1) * cw + ta,
2 * ((a - 1) - (a + 1) * cw), (a + 1) - (a - 1) * cw - ta);
}
void lowPass(int sr, float freq, float q) {
float f = kt::coerceIn(freq, 20.f, sr * 0.45f);
double w0 = 2.0 * M_PI * f / sr; double cw = std::cos(w0); double alpha = std::sin(w0) / (2.0 * q);
setRaw((1 - cw) / 2, 1 - cw, (1 - cw) / 2, 1 + alpha, -2 * cw, 1 - alpha);
}
void highPass(int sr, float freq, float q) {
float f = kt::coerceIn(freq, 20.f, sr * 0.45f);
double w0 = 2.0 * M_PI * f / sr; double cw = std::cos(w0); double alpha = std::sin(w0) / (2.0 * q);
setRaw((1 + cw) / 2, -(1 + cw), (1 + cw) / 2, 1 + alpha, -2 * cw, 1 - alpha);
}
void reset() { z1 = 0.0; z2 = 0.0; }
float process(float x) {
double inp = (double)x;
double out = b0 * inp + z1;
z1 = b1 * inp - a1 * out + z2;
z2 = b2 * inp - a2 * out;
if (!std::isfinite(out)) { z1 = 0.0; z2 = 0.0; out = 0.0; }
return (float)out;
}
};
constexpr int CTRL = 16; // samples between (expensive) gain recomputes
constexpr float GAIN_SMOOTH = 0.05f; // per-sample gain ramp toward the control-rate target
class MixTightener final : public Effect {
int sampleRate;
Bq eqLo, eqMid, eqHi;
bool eqActive = false;
Bq xLoLP, xLoHP, xHiLP, xHiHP;
bool compActive = false;
float env[3] = {0.f, 0.f, 0.f};
float gain[3] = {1.f, 1.f, 1.f};
float target[3] = {1.f, 1.f, 1.f};
float atkCoef[3] = {}, relCoef[3] = {};
float thrDb[3] = {}, ratio[3] = {}, makeDb[3] = {};
int ctrl = 0;
float limCeil = 1.f, limRelCoef = 0.f, limEnv = 0.f;
float outGain = 1.f;
float strength = 1.f;
float compScale = 1.f;
static float dbToLin(float db) { return (float)std::pow(10.0, db / 20.0); }
float coefFromMs(float ms) const {
float t = kt::coerceAtLeast(ms, 0.1f) * 0.001f * sampleRate;
return (float)(1.0 - std::exp(-1.0 / t));
}
float compBand(int i, float band) {
float r = std::fabs(band);
float e = env[i];
env[i] = r > e ? e + atkCoef[i] * (r - e) : e + relCoef[i] * (r - e);
gain[i] += GAIN_SMOOTH * (target[i] - gain[i]);
return band * gain[i];
}
public:
explicit MixTightener(int rate) : sampleRate(rate) {}
void update(const Params &p, float) override {
strength = kt::coerceIn(p.f("strength", 1.f), 0.f, 1.f);
float eqS = strength * kt::coerceIn(p.f("eqAmt", 1.f), 0.f, 1.f);
float compAmt = kt::coerceIn(p.f("compAmt", 1.f), 0.f, 1.f);
compScale = strength * compAmt;
float limS = strength * kt::coerceIn(p.f("limAmt", 1.f), 0.f, 1.f);
float loG = kt::coerceIn(p.f("eqLoGain", 0.f), -18.f, 18.f) * eqS;
float midG = kt::coerceIn(p.f("eqMidGain", 0.f), -18.f, 18.f) * eqS;
float hiG = kt::coerceIn(p.f("eqHiGain", 0.f), -18.f, 18.f) * eqS;
if (std::fabs(loG) > 0.1f) eqLo.lowShelf(sampleRate, p.f("eqLoFreq", 120.f), loG); else eqLo.identity();
if (std::fabs(midG) > 0.1f) eqMid.peak(sampleRate, p.f("eqMidFreq", 1000.f), midG,
kt::coerceIn(p.f("eqMidQ", 1.0f), 0.2f, 8.f)); else eqMid.identity();
if (std::fabs(hiG) > 0.1f) eqHi.highShelf(sampleRate, p.f("eqHiFreq", 8000.f), hiG); else eqHi.identity();
eqActive = std::fabs(loG) > 0.1f || std::fabs(midG) > 0.1f || std::fabs(hiG) > 0.1f;
float xl = kt::coerceIn(p.f("xLo", 200.f), 40.f, sampleRate * 0.4f);
float xh = kt::coerceIn(p.f("xHi", 2500.f), xl + 50.f, sampleRate * 0.45f);
xLoLP.lowPass(sampleRate, xl, 0.5f); xLoHP.highPass(sampleRate, xl, 0.5f);
xHiLP.lowPass(sampleRate, xh, 0.5f); xHiHP.highPass(sampleRate, xh, 0.5f);
thrDb[0] = p.f("cLoThr", -24.f); ratio[0] = kt::coerceIn(p.f("cLoRatio", 2.f), 1.f, 20.f);
makeDb[0] = p.f("cLoMk", 0.f); atkCoef[0] = coefFromMs(p.f("cLoAtk", 10.f)); relCoef[0] = coefFromMs(p.f("cLoRel", 120.f));
thrDb[1] = p.f("cMidThr", -22.f); ratio[1] = kt::coerceIn(p.f("cMidRatio", 2.f), 1.f, 20.f);
makeDb[1] = p.f("cMidMk", 0.f); atkCoef[1] = coefFromMs(p.f("cMidAtk", 15.f)); relCoef[1] = coefFromMs(p.f("cMidRel", 140.f));
thrDb[2] = p.f("cHiThr", -24.f); ratio[2] = kt::coerceIn(p.f("cHiRatio", 2.f), 1.f, 20.f);
makeDb[2] = p.f("cHiMk", 0.f); atkCoef[2] = coefFromMs(p.f("cHiAtk", 5.f)); relCoef[2] = coefFromMs(p.f("cHiRel", 90.f));
bool anyRatio = false, anyMake = false;
for (int i = 0; i < 3; i++) {
if (ratio[i] > 1.01f) anyRatio = true;
if (std::fabs(makeDb[i]) > 0.1f) anyMake = true;
}
compActive = compAmt > 0.001f && (anyRatio || anyMake);
limCeil = 1.f + (dbToLin(kt::coerceIn(p.f("limCeil", -0.5f), -24.f, 0.f)) - 1.f) * limS;
limRelCoef = coefFromMs(p.f("limRel", 100.f));
outGain = 1.f + (dbToLin(kt::coerceIn(p.f("outGain", 0.f), -12.f, 18.f)) - 1.f) * limS;
}
float process(float x) override {
if (strength < 0.001f) return x;
float s = x;
if (eqActive) { s = eqLo.process(s); s = eqMid.process(s); s = eqHi.process(s); }
if (compActive) {
float low = xLoLP.process(s);
float hp = xLoHP.process(s);
float mid = xHiLP.process(hp);
float high = xHiHP.process(hp);
if (ctrl <= 0) {
ctrl = CTRL;
for (int i = 0; i < 3; i++) {
float envDb = 20.f * kt::log10f_(env[i] + 1e-9f);
float over = envDb - thrDb[i];
float grDb = over > 0.f ? -over * (1.f - 1.f / ratio[i]) : 0.f;
target[i] = dbToLin(kt::coerceIn((grDb + makeDb[i]) * compScale, -40.f, 24.f));
}
}
ctrl--;
s = compBand(0, low) + compBand(1, mid) + compBand(2, high);
}
float r = std::fabs(s);
limEnv = r > limEnv ? r : limEnv + limRelCoef * (r - limEnv);
if (limEnv > limCeil && limEnv > 1e-6f) s *= limCeil / limEnv;
s *= outGain;
return s > 1.f ? 1.f : s < -1.f ? -1.f : !std::isfinite(s) ? 0.f : s;
}
};
} // namespace
std::unique_ptr<Effect> makeMixTightener(int sampleRate) { return std::make_unique<MixTightener>(sampleRate); }
} // namespace sizzle
+39
View File
@@ -0,0 +1,39 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Effect::create. Each effect lives in src/fx/<Name>.cpp and defines its maker
// below. The defaults here are weak definitions returning nullptr; a port's own
// (strong) definition replaces its default at link time, so a build without some
// of those files still links (lets ports land one by one).
#include <cstring>
#include "sizzle/Effect.hpp"
#define SIZZLE_MAKER(fn) \
__attribute__((weak)) std::unique_ptr<Effect> fn(int) { return nullptr; }
namespace sizzle {
SIZZLE_MAKER(makeBitcrusher);
SIZZLE_MAKER(makeFilter);
SIZZLE_MAKER(makeGraphicEq);
SIZZLE_MAKER(makeTapeDelay);
SIZZLE_MAKER(makeMixTightener);
SIZZLE_MAKER(makeTapeEngine);
SIZZLE_MAKER(makeGranularGlitch);
SIZZLE_MAKER(makeAmbienceReverb);
std::unique_ptr<Effect> Effect::create(const char *type, int sr) {
struct Entry { const char *type; std::unique_ptr<Effect> (*make)(int); };
const Entry table[] = {
{"BITCRUSHER", makeBitcrusher}, {"FILTER", makeFilter},
{"EQ10", makeGraphicEq}, {"DELAY", makeTapeDelay},
{"MIX_TIGHTENER", makeMixTightener}, {"TAPE_ENGINE", makeTapeEngine},
{"GRANULAR", makeGranularGlitch}, {"AMBIENCE", makeAmbienceReverb},
};
for (const auto &e : table)
if (std::strcmp(type, e.type) == 0) return e.make(sr);
return nullptr;
}
} // namespace sizzle
+122
View File
@@ -0,0 +1,122 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of TapeDelay (Effects.kt): one shared delay line read by up to four
// tempo-synced tape heads (averaged), with saturation, a darkening one-pole LP
// in the feedback path and sine wow/flutter, all scaled by "tape".
#include <cmath>
#include <vector>
#include "sizzle/Effect.hpp"
#include "KotlinMath.hpp"
// The JVM never fuses a*b+c; keep clang from contracting into FMAs.
#if defined(__clang__)
#pragma STDC FP_CONTRACT OFF
#endif
namespace sizzle {
namespace {
// DelayDivisions (model/Toolbox.kt).
constexpr int HEADS = 4;
constexpr float MAX_FEEDBACK = 0.9f;
constexpr double BEAT_FRACTIONS[] = {
4.0, // 1/1
3.0, // 1/2.
2.0, // 1/2
1.5, // 1/4.
4.0 / 3.0, // 1/2T
1.0, // 1/4
0.75, // 1/8.
2.0 / 3.0, // 1/4T
0.5, // 1/8
0.375, // 1/16.
1.0 / 3.0, // 1/8T
0.25, // 1/16
1.0 / 6.0, // 1/16T
};
constexpr int DIV_COUNT = (int)(sizeof(BEAT_FRACTIONS) / sizeof(BEAT_FRACTIONS[0]));
constexpr int DIV_DEFAULT = 5; // indexOf("1/4")
inline double beatFraction(int i) { return BEAT_FRACTIONS[kt::coerceIn(i, 0, DIV_COUNT - 1)]; }
constexpr double FLUTTER_HZ = 5.0;
const char *const HEAD_ON_KEYS[HEADS] = {"head0On", "head1On", "head2On", "head3On"};
const char *const HEAD_DIV_KEYS[HEADS] = {"head0Div", "head1Div", "head2Div", "head3Div"};
class TapeDelay final : public Effect {
int sampleRate;
std::vector<float> buffer; // up to 4 s of delay line
int bufferSize;
int writeIndex = 0;
int delaySamples[HEADS];
bool headOn[HEADS] = {};
float feedback = 0.4f;
float dryWet = 0.35f;
float satBlend = 0.f;
float lpAlpha = 1.f;
float lpState = 0.f;
double flutterInc = 0.0;
float flutterDepth = 0.f;
double flutterPhase = 0.0;
public:
explicit TapeDelay(int rate)
: sampleRate(rate), buffer((size_t)rate * 4, 0.f), bufferSize(rate * 4) {
for (int h = 0; h < HEADS; h++) delaySamples[h] = rate / 2;
}
void update(const Params &p, float tempoBpm) override {
double samplesPerBeat = (60.0 / (double)tempoBpm) * sampleRate;
for (int h = 0; h < HEADS; h++) {
headOn[h] = p.f(HEAD_ON_KEYS[h], h == 0 ? 1.f : 0.f) >= 0.5f;
int idx = kt::toInt(p.f(HEAD_DIV_KEYS[h], (float)DIV_DEFAULT));
// Double.toInt(): truncation (values here are small and positive).
double d = beatFraction(idx) * samplesPerBeat;
int ds = std::isnan(d) ? 0 : d >= 2147483647.0 ? 2147483647 : (int)d;
delaySamples[h] = kt::coerceIn(ds, 1, bufferSize - 2);
}
feedback = kt::coerceIn(p.f("feedback", 0.4f), 0.f, MAX_FEEDBACK);
dryWet = kt::coerceIn(p.f("drywet", 0.35f), 0.f, 1.f);
float tape = kt::coerceIn(p.f("tape", 0.3f), 0.f, 1.f);
satBlend = tape;
lpAlpha = 1.f - tape * 0.85f;
flutterInc = 2.0 * M_PI * FLUTTER_HZ / sampleRate;
flutterDepth = tape * (float)sampleRate * 0.0015f;
}
float process(float x) override {
flutterPhase += flutterInc;
if (flutterPhase > 2 * M_PI) flutterPhase -= 2 * M_PI;
float flutter = (float)std::sin(flutterPhase) * flutterDepth;
float wet = 0.f;
int active = 0;
for (int h = 0; h < HEADS; h++) {
if (!headOn[h]) continue;
active++;
float pos = (float)(writeIndex - delaySamples[h]) - flutter;
while (pos < 0.f) pos += (float)bufferSize;
int i0 = kt::toInt(pos) % bufferSize;
int i1 = (i0 + 1) % bufferSize;
float frac = pos - (float)kt::toInt(pos);
wet += buffer[i0] + (buffer[i1] - buffer[i0]) * frac;
}
if (active > 0) wet /= (float)active;
float fb = wet * feedback;
fb += satBlend * (kt::tanhf_(fb) - fb);
lpState += lpAlpha * (fb - lpState);
fb = lpState;
buffer[writeIndex] = x + fb;
writeIndex = (writeIndex + 1) % bufferSize;
return x * (1.f - dryWet) + wet * dryWet;
}
};
} // namespace
std::unique_ptr<Effect> makeTapeDelay(int sampleRate) { return std::make_unique<TapeDelay>(sampleRate); }
} // namespace sizzle
+102
View File
@@ -0,0 +1,102 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of TapeEngine (Effects.kt): a varispeed reel-to-reel. Input is written into
// a ring at rate 1 and read back at a gliding `speed`, with wow/flutter wobble and
// xorshift hiss.
#include <cmath>
#include <cstdint>
#include <vector>
#include "sizzle/Effect.hpp"
#include "KotlinMath.hpp"
namespace sizzle {
namespace {
constexpr int NOMINAL_DELAY = 128;
constexpr float MIN_SPEED = 0.25f;
constexpr float MAX_WOW = 0.03f;
constexpr float MAX_FLUT = 0.008f;
constexpr float MAX_HISS = 0.02f;
constexpr double FLUTTER_HZ = 11.0;
constexpr float SPEED_GLIDE = 0.00012f;
constexpr double MIN_GAP = 2.0;
/** TimeDivision.beatFraction by index, with fromIndex's clamping. */
double beatFraction(int i) {
static constexpr double kFrac[] = {4.0, 2.0, 1.0, 0.5, 0.25, 0.125, 0.75};
return kFrac[kt::coerceIn(i, 0, 6)];
}
class TapeEngine final : public Effect {
int sampleRate;
std::vector<float> buf;
int size;
int writePos = NOMINAL_DELAY;
double readPos = 0.0;
double targetSpeed = 1.0;
double curSpeed = 1.0;
double wowInc = 0.0, wowPhase = 0.0; float wowDepth = 0.f;
double flutInc, flutPhase = 0.0; float flutDepth = 0.f;
float hiss = 0.f;
uint32_t rng = 0x51ED2A19u;
float nextRand() {
uint32_t s = rng; s ^= s << 13; s ^= s >> 17; s ^= s << 5; rng = s;
return (float)(int32_t)s * 4.656613e-10f; // -1 … 1
}
public:
explicit TapeEngine(int rate)
: sampleRate(rate), buf((size_t)rate * 2, 0.f), size(rate * 2),
flutInc(FLUTTER_HZ / rate) {}
void update(const Params &p, float tempoBpm) override {
targetSpeed = (double)kt::coerceIn(p.f("speed", 1.f), MIN_SPEED, 1.f);
wowDepth = kt::coerceIn(p.f("wow", 0.15f), 0.f, 1.f) * MAX_WOW;
flutDepth = kt::coerceIn(p.f("flutter", 0.15f), 0.f, 1.f) * MAX_FLUT;
hiss = kt::coerceIn(p.f("hiss", 0.10f), 0.f, 1.f) * MAX_HISS;
double secPerBeat = 60.0 / (double)tempoBpm;
double frac = beatFraction(kt::toInt(p.f("division", 2.f)));
double wowHz = 1.0 / kt::coerceAtLeast(frac * secPerBeat, 1e-4);
wowInc = wowHz / sampleRate;
flutInc = FLUTTER_HZ / sampleRate;
}
float process(float x) override {
buf[writePos] = x;
writePos++; if (writePos >= size) writePos = 0;
curSpeed += (targetSpeed - curSpeed) * (double)SPEED_GLIDE; // tape inertia
wowPhase += wowInc; if (wowPhase >= 1.0) wowPhase -= 1.0;
flutPhase += flutInc; if (flutPhase >= 1.0) flutPhase -= 1.0;
double wow = std::sin(2.0 * M_PI * wowPhase) * (double)wowDepth;
double flut = std::sin(2.0 * M_PI * flutPhase) * (double)flutDepth;
double rate = curSpeed * (1.0 + wow + flut);
if (rate < 0.01) rate = 0.01;
int i0 = (int)readPos % size;
int i1 = (i0 + 1) % size;
float frac = (float)(readPos - (int)readPos);
float out = buf[i0] + (buf[i1] - buf[i0]) * frac;
double rp = readPos + rate;
if (rp >= size) rp -= size;
double gap = writePos - rp; if (gap < 0) gap += size;
double maxGap = size - 2.0;
if (gap < MIN_GAP) { rp = writePos - MIN_GAP; if (rp < 0) rp += size; }
else if (gap > maxGap) { rp = writePos - maxGap; if (rp < 0) rp += size; }
readPos = rp;
if (hiss > 0.f) out += nextRand() * hiss;
return out;
}
};
} // namespace
std::unique_ptr<Effect> makeTapeEngine(int sr) { return std::make_unique<TapeEngine>(sr); }
} // namespace sizzle
+287
View File
@@ -0,0 +1,287 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "host/EngineHost.hpp"
#include <cstring>
#include <vector>
#include "echofield/GrainSources.hpp"
#include "io/ProjectIo.hpp"
#include "wavetable/WaveDefs.hpp"
#include "wavetable/WaveTables.hpp"
namespace sizzle::host {
namespace {
constexpr int kChunk = engine::Engine::BLOCK_FRAMES; // the MIDI LFO steps by it (see ios/PORTING.md)
/// The store WaveTables reads custom tables from (one host per process).
std::atomic<sampler::SampleStore *> gStore{nullptr};
bool storeSource(const char *id, std::vector<float> &out) {
sampler::SampleStore *store = gStore.load();
const Sample *s = store ? store->get(id) : nullptr;
if (!s) return false;
sampler::SampleStore::pin(s);
out = s->data;
sampler::SampleStore::unpin(s);
return true;
}
// ---- equality, field by field (Params by position: an unchanged map saves in
// the same order; a reordered one is just copied again)
bool same(const Params &a, const Params &b) {
if (a.size() != b.size()) return false;
for (int i = 0; i < a.size(); ++i)
if (std::strcmp(a.keyAt(i), b.keyAt(i)) || std::strcmp(a.valueAt(i), b.valueAt(i))) return false;
return true;
}
bool same(const model::ToolboxSlot &a, const model::ToolboxSlot &b) {
return a.type == b.type && a.name == b.name && same(a.values, b.values);
}
bool sameCells(const model::Pattern &a, const model::Pattern &b) {
for (int t = 0; t < model::Pattern::TRACK_COUNT; ++t) {
if (a.tracks[t].size() != b.tracks[t].size()) return false;
for (size_t l = 0; l < a.tracks[t].size(); ++l) {
const model::Cell &x = a.tracks[t][l], &y = b.tracks[t][l];
if (x.note != y.note || x.velocity != y.velocity || x.channel != y.channel) return false;
}
}
return true;
}
bool same(const model::LoopRegion &a, const model::LoopRegion &b) {
return a.enabled == b.enabled && a.start == b.start && a.end == b.end && a.repeats == b.repeats;
}
bool same(const model::Arrangement &a, const model::Arrangement &b) {
return a.slots == b.slots && a.laneMuted == b.laneMuted && a.lengthBars == b.lengthBars &&
a.loopEnabled == b.loopEnabled && same(a.regionA, b.regionA) && same(a.regionB, b.regionB);
}
bool same(const model::Mixer &a, const model::Mixer &b) {
for (int c = 0; c < model::Mixer::CHANNEL_COUNT; ++c) {
const auto &x = a.channels[c], &y = b.channels[c];
if (x.instrumentSlot != y.instrumentSlot || x.fxSlots != y.fxSlots || x.midiChannel != y.midiChannel ||
x.volume != y.volume || x.mute != y.mute || x.solo != y.solo || x.limiter != y.limiter) return false;
}
return true;
}
/// WaveVoice's frame length: wtframe's choice ("Auto" or unknown -> 0).
int frameLenOf(const model::ToolboxSlot &slot) {
namespace WD = wavetable::WaveDefs;
const char *v = slot.s("wtframe", WD::FRAME_SIZES[0]);
for (int i = 1; i < WD::FRAME_SIZE_COUNT; ++i)
if (!std::strcmp(v, WD::FRAME_SIZES[i])) return std::atoi(WD::FRAME_SIZES[i]);
return 0;
}
bool playsCustom(const model::ToolboxSlot &slot) {
namespace WT = wavetable::WaveTables;
return slot.type == "WAVETABLE" && *slot.s(wavetable::WaveDefs::SAMPLE_KEY, "") &&
(!std::strcmp(slot.s("o1table", ""), WT::CUSTOM) || !std::strcmp(slot.s("o2table", ""), WT::CUSTOM));
}
} // namespace
EngineHost::EngineHost(int sampleRate)
: sampleRate_(sampleRate),
store_(std::make_unique<sampler::SampleStore>()),
project_(std::make_unique<model::Project>()),
shadow_(std::make_unique<model::Project>()),
recorder_(std::make_unique<MasterRecorder>(sampleRate)) {
wavetable::WaveTables::prewarm();
echofield::GrainSources::prewarm();
gStore.store(store_.get());
wavetable::WaveTables::setSampleSource(&storeSource);
engine_ = std::make_unique<engine::Engine>(sampleRate, store_.get());
engine_->setProject(project_.get());
engine_->setMasterSink(recorder_.get());
}
EngineHost::~EngineHost() {
{
std::lock_guard<std::mutex> b(builderLock_);
if (builder_.joinable()) builder_.join();
}
engine_.reset();
gStore.store(nullptr);
}
// ---------------------------------------------------------------- song
void EngineHost::loadProjectText(const std::string &text) {
auto fresh = std::make_unique<model::Project>();
io::ProjectIo::loadInto(*fresh, text);
{
std::lock_guard<std::mutex> g(lock_);
engine_->stop();
*project_ = model::Project();
io::ProjectIo::loadInto(*project_, text);
engine_->setProject(project_.get());
}
shadow_ = std::move(fresh);
lastText_ = text;
scheduleTables();
}
void EngineHost::syncProjectText(const std::string &text) {
if (text == lastText_) return;
auto fresh = std::make_unique<model::Project>();
io::ProjectIo::loadInto(*fresh, text);
const model::Project &old = *shadow_;
// What differs from the last sync, worked out without the lock.
const bool scalars = fresh->name != old.name || fresh->tempoBpm != old.tempoBpm ||
fresh->timeSignature != old.timeSignature || fresh->scale != old.scale ||
fresh->rootNote != old.rootNote || fresh->activePatternId != old.activePatternId;
const bool patternSet = fresh->patterns.size() != old.patterns.size();
std::vector<size_t> cells, patterns; // same shape, other cells / other shape
if (!patternSet) {
for (size_t i = 0; i < fresh->patterns.size(); ++i) {
const auto &a = fresh->patterns[i], &b = old.patterns[i];
if (a.id != b.id || a.name != b.name || a.length != b.length) patterns.push_back(i);
else if (!sameCells(a, b)) cells.push_back(i);
}
}
const bool arrangement = !same(fresh->arrangement, old.arrangement);
const bool mixer = !same(fresh->mixer, old.mixer);
std::vector<size_t> slots;
for (size_t i = 0; i < fresh->toolbox.size(); ++i)
if (!same(fresh->toolbox[i], old.toolbox[i])) slots.push_back(i);
{
std::lock_guard<std::mutex> g(lock_);
model::Project &p = *project_;
if (scalars) {
p.name = fresh->name;
p.tempoBpm = fresh->tempoBpm;
p.timeSignature = fresh->timeSignature;
p.scale = fresh->scale;
p.rootNote = fresh->rootNote;
p.activePatternId = fresh->activePatternId;
}
if (patternSet) p.patterns = fresh->patterns;
for (size_t i : patterns) p.patterns[i] = fresh->patterns[i];
for (size_t i : cells) // same lengths: copy in place, no allocation
for (int t = 0; t < model::Pattern::TRACK_COUNT; ++t)
std::copy(fresh->patterns[i].tracks[t].begin(), fresh->patterns[i].tracks[t].end(), p.patterns[i].tracks[t].begin());
if (arrangement) p.arrangement = fresh->arrangement;
if (mixer) p.mixer = fresh->mixer;
for (size_t i : slots) {
model::ToolboxSlot &s = p.toolbox[i];
s.type = fresh->toolbox[i].type;
s.name = fresh->toolbox[i].name;
s.values = fresh->toolbox[i].values;
++s.version; // the engine re-reads a slot when its version moves
}
}
shadow_ = std::move(fresh);
lastText_ = text;
if (!slots.empty()) scheduleTables();
}
std::string EngineHost::projectText() {
std::lock_guard<std::mutex> g(lock_);
return io::ProjectIo::save(*project_);
}
void EngineHost::rebuildFxChains() { std::lock_guard<std::mutex> g(lock_); engine_->rebuildFxChains(); }
void EngineHost::rebuildArrangement() { std::lock_guard<std::mutex> g(lock_); engine_->rebuildArrangement(); }
void EngineHost::refreshLoopPlaylist() { std::lock_guard<std::mutex> g(lock_); engine_->refreshLoopPlaylist(); }
void EngineHost::play(int startBeat) { std::lock_guard<std::mutex> g(lock_); engine_->play(startBeat); }
void EngineHost::pause() { std::lock_guard<std::mutex> g(lock_); engine_->pause(); }
void EngineHost::stop() { std::lock_guard<std::mutex> g(lock_); engine_->stop(); }
void EngineHost::panic() { std::lock_guard<std::mutex> g(lock_); engine_->panic(); }
void EngineHost::setRecordingArm(bool armed, int tailBars) { engine_->setRecordingArm(armed, tailBars); }
void EngineHost::setRecordTailBars(int tailBars) { engine_->setRecordTailBars(tailBars); }
std::string EngineHost::describeBusTargets(int midiChannel, int midi) {
std::lock_guard<std::mutex> g(lock_);
return engine_->describeBusTargets(midiChannel, midi);
}
// ---------------------------------------------------------------- notes
void EngineHost::push(NoteEvent e) {
std::lock_guard<std::mutex> g(pushLock_);
const uint32_t h = head_.load(std::memory_order_relaxed);
if (h - tail_.load(std::memory_order_acquire) >= ring_.size()) return; // full: drop
ring_[h % ring_.size()] = e;
head_.store(h + 1, std::memory_order_release);
}
void EngineHost::liveNoteOn(int pitch, int velocity) { push({4, pitch, velocity, 0}); }
void EngineHost::liveNoteOff(int pitch) { push({5, pitch, 0, 0}); }
void EngineHost::auditionSlotOn(int slot, int midi) { push({2, slot, midi, 0}); }
void EngineHost::auditionSlotOff(int midi) { push({3, 0, midi, 0}); }
void EngineHost::busNoteOn(int ch, int midi, int velocity) { push({0, ch, midi, velocity}); }
void EngineHost::busNoteOff(int ch, int midi) { push({1, ch, midi, 0}); }
// ---------------------------------------------------------------- audio
void EngineHost::render(float *out, int frames) {
std::unique_lock<std::mutex> g(lock_, std::try_to_lock);
if (!g.owns_lock()) { // an edit is being applied: this block is silent (notes wait)
std::memset(out, 0, sizeof(float) * 2 * (size_t)frames);
return;
}
engine::Engine &e = *engine_;
uint32_t t = tail_.load(std::memory_order_relaxed);
const uint32_t h = head_.load(std::memory_order_acquire);
for (; t != h; ++t) {
const NoteEvent &n = ring_[t % ring_.size()];
switch (n.kind) {
case 0: e.busNoteOn(n.a, n.b, n.c); break;
case 1: e.busNoteOff(n.a, n.b); break;
case 2: e.auditionSlotOn(n.a, n.b); break;
case 3: e.auditionSlotOff(n.b); break;
case 4: e.liveNoteOn(n.a, n.b); break;
case 5: e.liveNoteOff(n.a); break;
}
}
tail_.store(t, std::memory_order_release);
for (int done = 0; done < frames;) {
const int n = std::min(kChunk, frames - done);
e.fillBlock(out + 2 * done, n);
done += n;
}
}
// ---------------------------------------------------------------- samples
void EngineHost::putSample(const std::string &id, Sample sample) {
store_->put(id, std::move(sample));
scheduleTables();
}
void EngineHost::removeSample(const std::string &id) { store_->remove(id); }
/// Ask WaveTables for every Custom table the song plays (recording the request),
/// then build what's missing on a background thread, one build at a time.
void EngineHost::scheduleTables() {
bool missing = false;
{
std::lock_guard<std::mutex> g(lock_);
for (const auto &slot : project_->toolbox)
if (playsCustom(slot) && !wavetable::WaveTables::forSample(slot.s(wavetable::WaveDefs::SAMPLE_KEY, ""), frameLenOf(slot)))
missing = true;
}
std::lock_guard<std::mutex> b(builderLock_);
if (!missing || building_.exchange(true)) return;
if (builder_.joinable()) builder_.join();
builder_ = std::thread([this] {
wavetable::WaveTables::buildRequested();
building_.store(false);
});
}
} // namespace sizzle::host
+117
View File
@@ -0,0 +1,117 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// The engine as an app hosts it: the song, the sample store, the engine, live
// notes queued to the audio thread, the master recorder and custom wavetable
// building, behind one lock the audio thread only ever try-locks (a block that
// meets an edit plays silence instead of waiting).
//
// The Android app drives it through JNI (app/src/main/cpp/jni_engine.cpp): its
// Kotlin model stays the UI's state and is mirrored here as project text
// (syncProjectText), applied as a diff so an edit holds the lock for microseconds.
#pragma once
#include <atomic>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <array>
#include "host/MasterRecorder.hpp"
#include "sampler/SampleStore.hpp"
#include "sizzle/Engine.hpp"
#include "sizzle/Model.hpp"
namespace sizzle::host {
class EngineHost {
public:
explicit EngineHost(int sampleRate);
~EngineHost();
EngineHost(const EngineHost &) = delete;
EngineHost &operator=(const EngineHost &) = delete;
int sampleRate() const { return sampleRate_; }
// ---- the song (main thread)
/** Replace the song with [text] (a .szg project), stopping playback. */
void loadProjectText(const std::string &text);
/** Make the song equal [text], changing only what differs from the last text:
* playback continues. Cheap when nothing changed. */
void syncProjectText(const std::string &text);
void rebuildFxChains();
void rebuildArrangement();
void refreshLoopPlaylist();
// ---- transport (main thread)
void play(int startBeat = -1);
void pause();
void stop();
void panic();
engine::TransportState transport() const { return engine_->transport(); }
bool isPlaying() const { return engine_->isPlaying(); }
// ---- live notes (any thread; queued to the audio thread)
void liveNoteOn(int pitch, int velocity);
void liveNoteOff(int pitch);
void auditionSlotOn(int slot, 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);
// ---- audio thread
/** [frames] interleaved stereo frames into [out], in the engine's 192-frame blocks. */
void render(float *out, int frames);
// ---- display (any thread)
float channelMeter(int ch) const { return engine_->channelMeter(ch); }
bool channelClipped(int ch) const { return engine_->channelClipped(ch); }
int effectScope(int slot, float *out, int capacity) const { return engine_->effectScope(slot, out, capacity); }
float effectPlayhead(int slot) const { return engine_->effectPlayhead(slot); }
// ---- outgoing MIDI
void setMidiOutEnabled(bool on) { engine_->setMidiOutEnabled(on); }
int pollMidiOut() { return engine_->pollMidiOut(); }
// ---- samples (not the audio thread)
void putSample(const std::string &id, Sample sample);
void removeSample(const std::string &id);
sampler::SampleStore &store() { return *store_; }
/** The engine's song as project text (tests, diagnostics). */
std::string projectText();
// ---- master recording
MasterRecorder &recorder() { return *recorder_; }
void setRecordingArm(bool armed, int tailBars);
void setRecordTailBars(int tailBars);
void externalClockStart() { engine_->externalClockStart(); }
void externalClockStop() { engine_->externalClockStop(); }
private:
struct NoteEvent { int kind, a, b, c; };
void push(NoteEvent e);
void scheduleTables();
const int sampleRate_;
std::unique_ptr<sampler::SampleStore> store_;
std::unique_ptr<model::Project> project_; // the engine's song (under lock_)
std::unique_ptr<model::Project> shadow_; // the last synced text, parsed (main thread)
std::string lastText_;
std::unique_ptr<engine::Engine> engine_;
std::unique_ptr<MasterRecorder> recorder_;
std::mutex lock_;
// Live notes: producers serialised by pushLock_, the audio thread drains.
std::array<NoteEvent, 1024> ring_{};
std::atomic<uint32_t> head_{0}, tail_{0};
std::mutex pushLock_;
std::thread builder_;
std::atomic<bool> building_{false};
std::mutex builderLock_; // scheduleTables runs on the main thread and wherever samples arrive
};
} // namespace sizzle::host
+90
View File
@@ -0,0 +1,90 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "host/MasterRecorder.hpp"
#include <algorithm>
#include <chrono>
#include <cstdio>
namespace sizzle::host {
MasterRecorder::MasterRecorder(int sampleRate) : sr_(sampleRate), ring_((size_t)std::max(2, sampleRate * 4)) {}
MasterRecorder::~MasterRecorder() {
capturing_.store(false);
if (writer_.joinable()) writer_.join();
}
bool MasterRecorder::begin() {
if (active_.load() || path_.empty()) return false;
if (writer_.joinable()) writer_.join(); // the previous take's thread is done (active_ is false)
writePos_.store(0);
readPos_.store(0);
active_.store(true);
capturing_.store(true);
const int64_t start = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
const std::string path = path_;
writer_ = std::thread([this, path, start] {
const bool ok = writeLoop(path);
active_.store(false);
if (onFinished) onFinished(ok ? path : std::string(), start);
});
if (onStarted) onStarted();
return true;
}
void MasterRecorder::write(float left, float right) {
if (!capturing_.load(std::memory_order_relaxed)) return;
const uint64_t w = writePos_.load(std::memory_order_relaxed);
if (w - readPos_.load(std::memory_order_acquire) > ring_.size() - 2) return; // writer starved: drop
ring_[w % ring_.size()] = left;
ring_[(w + 1) % ring_.size()] = right;
writePos_.store(w + 2, std::memory_order_release);
}
bool MasterRecorder::writeLoop(const std::string &path) {
FILE *f = std::fopen(path.c_str(), "wb");
if (!f) { capturing_.store(false); return false; }
writeHeader(f, 0);
uint64_t samples = 0;
constexpr size_t chunk = 4096;
uint8_t out[chunk * 2];
bool ok = true;
for (;;) {
const uint64_t w = writePos_.load(std::memory_order_acquire);
const uint64_t r = readPos_.load(std::memory_order_relaxed);
if (r < w) {
const size_t n = (size_t)std::min<uint64_t>(w - r, chunk);
for (size_t i = 0; i < n; ++i) {
const float s = std::clamp(ring_[(r + i) % ring_.size()], -1.f, 1.f);
const int v = (int)(s * 32767.f);
out[i * 2] = (uint8_t)(v & 0xFF);
out[i * 2 + 1] = (uint8_t)((v >> 8) & 0xFF);
}
if (std::fwrite(out, 2, n, f) != n) ok = false;
samples += n;
readPos_.store(r + n, std::memory_order_release);
} else if (!capturing_.load()) {
break;
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
}
writeHeader(f, samples);
return std::fclose(f) == 0 && ok;
}
void MasterRecorder::writeHeader(FILE *f, uint64_t sampleCount) {
const uint32_t data = (uint32_t)(sampleCount * 2);
auto u32 = [f](uint32_t v) { uint8_t b[4] = {(uint8_t)v, (uint8_t)(v >> 8), (uint8_t)(v >> 16), (uint8_t)(v >> 24)}; std::fwrite(b, 1, 4, f); };
auto u16 = [f](uint16_t v) { uint8_t b[2] = {(uint8_t)v, (uint8_t)(v >> 8)}; std::fwrite(b, 1, 2, f); };
std::fseek(f, 0, SEEK_SET);
std::fwrite("RIFF", 1, 4, f); u32(36 + data); std::fwrite("WAVE", 1, 4, f);
std::fwrite("fmt ", 1, 4, f); u32(16); u16(1); u16(2); u32((uint32_t)sr_); u32((uint32_t)sr_ * 4); u16(4); u16(16);
std::fwrite("data", 1, 4, f); u32(data);
std::fseek(f, 0, SEEK_END);
}
} // namespace sizzle::host
+54
View File
@@ -0,0 +1,54 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// The engine's MasterSink as a WAV writer (MasterRecorder.kt): the audio thread
// writes interleaved stereo floats into a single-producer/single-consumer ring
// (about two seconds), a writer thread drains it into a 16-bit stereo WAV at
// [path] and patches the header sizes at the end. No allocation, locks or I/O on
// the audio thread. Used by both apps' engine hosts.
#pragma once
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <functional>
#include <string>
#include <thread>
#include <vector>
#include "sizzle/Engine.hpp"
namespace sizzle::host {
class MasterRecorder final : public engine::MasterSink {
public:
explicit MasterRecorder(int sampleRate);
~MasterRecorder() override;
/** Where the next take is written (set before arming). */
void setPath(std::string path) { path_ = std::move(path); }
/** Called when a take starts capturing (the thread that started it: main or MIDI). */
std::function<void()> onStarted;
/** Called on the writer thread when the file is finished: its path, or "" when
* writing failed, and the take's start in milliseconds since the epoch. */
std::function<void(const std::string &path, int64_t startMillis)> onFinished;
bool isActive() const override { return active_.load(); }
bool begin() override;
void write(float left, float right) override;
void endCapture() override { capturing_.store(false); }
private:
bool writeLoop(const std::string &path);
void writeHeader(FILE *f, uint64_t sampleCount);
const int sr_;
std::vector<float> ring_;
std::string path_;
std::atomic<uint64_t> writePos_{0}, readPos_{0};
std::atomic<bool> capturing_{false}, active_{false};
std::thread writer_;
};
} // namespace sizzle::host
+142
View File
@@ -0,0 +1,142 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "sizzle/Instrument.hpp"
#include <cstring>
#include <string>
#include "echofield/GrainCloud.hpp"
#include "frasil/FrasilVoice.hpp"
#include "sampler/SampleStore.hpp"
#include "sampler/SampleVoice.hpp"
#include "synth/SynthPatch.hpp"
#include "synth/SynthVoice.hpp"
#include "echofield/GrainSources.hpp"
#include "wavetable/WaveTables.hpp"
#include "wavetable/WaveVoice.hpp"
namespace sizzle {
namespace {
constexpr int N = Instrument::POLYPHONY;
/** Synth, Morph Pad, Wavetable: SynthVoice pool with the engine's patch. */
class SynthInstrument final : public Instrument {
public:
enum Kind { SYNTH, PAD, WAVE };
private:
Kind kind;
int sr;
frasil::FrasilClock clock;
frasil::FrasilSeeds seeds;
std::unique_ptr<synth::SynthVoice> voices[N];
synth::SynthPatch patch = synth::SynthPatch::defaults();
int alloc = 0;
public:
SynthInstrument(Kind k, int sampleRate) : kind(k), sr(sampleRate) {
for (auto &v : voices) v = std::make_unique<synth::SynthVoice>(sr, clock, seeds.next());
}
void update(const Params &p, float tempo) override {
switch (kind) {
case PAD: patch = synth::SynthPatch::forPad(frasil::FrasilPatch::from(&p)); break;
case WAVE: patch = synth::SynthPatch::forWave(wavetable::WavePatch::from(&p, tempo)); break;
default: patch = synth::SynthPatch::from(&p, tempo); break;
}
for (auto &v : voices) if (v->isActive()) v->setPatch(patch);
}
void noteOn(int midi, int vel) override {
for (auto &v : voices) if (!v->isActive()) { v->noteOn(midi, vel, patch); return; }
auto &v = voices[alloc];
alloc = (alloc + 1) % N;
v->kill();
v->noteOn(midi, vel, patch);
}
void noteOff(int midi) override {
for (auto &v : voices) if (v->isGated() && v->pitch() == midi) v->noteOff();
}
void allNotesOff() override { for (auto &v : voices) v->noteOff(); }
void kill() override { for (auto &v : voices) v->kill(); }
void blockStart(int frames) override { clock.advance(frames, sr); }
float render() override {
float s = 0.f;
for (auto &v : voices) if (v->isActive()) s += v->render();
return s;
}
};
/** Sampler pads and the SF2/XI loader: SampleVoice pool. */
class SampleInstrument final : public Instrument {
std::string type;
sampler::SampleStore *store;
std::unique_ptr<sampler::SampleVoice> voices[N];
Params params;
int alloc = 0;
public:
SampleInstrument(const char *t, int sr, sampler::SampleStore *s) : type(t), store(s) {
for (auto &v : voices) v = std::make_unique<sampler::SampleVoice>(sr);
}
void update(const Params &p, float) override { params = p; }
void noteOn(int midi, int vel) override {
if (!store) return;
sampler::VoiceSample vs;
if (!sampler::voiceSample(type.c_str(), params, *store, midi, vs)) return;
for (auto &v : voices) if (!v->isActive()) { v->noteOn(vs, midi, vel); return; }
auto &v = voices[alloc];
alloc = (alloc + 1) % N;
v->noteOn(vs, midi, vel); // declicks the hand-off itself
}
void noteOff(int midi) override {
for (auto &v : voices) if (v->isGated() && v->pitch == midi) v->noteOff();
}
void allNotesOff() override { for (auto &v : voices) v->noteOff(); }
void kill() override { for (auto &v : voices) v->kill(); }
void blockStart(int) override { if (store) store->quiescent(); }
float render() override {
float s = 0.f;
for (auto &v : voices) if (v->isActive()) s += v->render();
return s;
}
};
/** Grain Cloud: one polyphonic cloud. */
class GrainInstrument final : public Instrument {
echofield::GrainCloud cloud;
sampler::SampleStore *store;
static const Sample *lookup(void *ctx, const char *id) {
auto *s = static_cast<sampler::SampleStore *>(ctx);
return s ? s->get(id) : nullptr;
}
public:
GrainInstrument(int sr, sampler::SampleStore *s) : cloud(sr, echofield::GrainSeeds{}.next()), store(s) {
cloud.setSampleLookup(&GrainInstrument::lookup, store);
}
void update(const Params &p, float tempo) override { cloud.setPatch(echofield::GrainPatch::from(&p, tempo)); }
void noteOn(int midi, int vel) override { cloud.noteOn(midi, vel, echofield::GrainCloud::OWNER_LIVE); }
void noteOff(int midi) override { cloud.noteOff(midi); }
void allNotesOff() override { cloud.releaseAll(); }
void kill() override { cloud.kill(); }
void blockStart(int) override { if (store) store->quiescent(); }
float render() override { return cloud.render(); }
};
} // namespace
std::unique_ptr<Instrument> Instrument::create(const char *type, int sr, sampler::SampleStore *store) {
auto is = [&](const char *t) { return std::strcmp(type, t) == 0; };
if (is("NES_SYNTH")) return std::make_unique<SynthInstrument>(SynthInstrument::SYNTH, sr);
if (is("MORPH_PAD")) return std::make_unique<SynthInstrument>(SynthInstrument::PAD, sr);
// Wavetables and grain sources are generated once, off the audio thread; until
// they're ready those oscillators / clouds are silent (as on Android, where the
// app starts this at launch). prewarm() returns at once.
if (is("WAVETABLE")) { wavetable::WaveTables::prewarm(); return std::make_unique<SynthInstrument>(SynthInstrument::WAVE, sr); }
if (is("GRAIN_CLOUD")) { echofield::GrainSources::prewarm(); return std::make_unique<GrainInstrument>(sr, store); }
if (is("SAMPLER") || is("SOUNDFONT")) return std::make_unique<SampleInstrument>(type, sr, store);
return nullptr;
}
} // namespace sizzle
+215
View File
@@ -0,0 +1,215 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "io/KotlinText.hpp"
#include <climits>
#include <clocale>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
namespace sizzle::io::kt {
unsigned decodeUtf8(const std::string &s, size_t &i) {
const unsigned char c0 = (unsigned char)s[i];
if (c0 < 0x80) { ++i; return c0; }
int n; unsigned cp, min;
if ((c0 & 0xE0) == 0xC0) { n = 1; cp = c0 & 0x1F; min = 0x80; }
else if ((c0 & 0xF0) == 0xE0) { n = 2; cp = c0 & 0x0F; min = 0x800; }
else if ((c0 & 0xF8) == 0xF0) { n = 3; cp = c0 & 0x07; min = 0x10000; }
else { ++i; return 0xFFFD; }
if (i + (size_t)n >= s.size()) { ++i; return 0xFFFD; }
for (int k = 1; k <= n; ++k) {
const unsigned char c = (unsigned char)s[i + (size_t)k];
if ((c & 0xC0) != 0x80) { ++i; return 0xFFFD; }
cp = (cp << 6) | (c & 0x3F);
}
if (cp < min || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) { ++i; return 0xFFFD; }
i += (size_t)n + 1;
return cp;
}
bool isWhitespace(unsigned cp) {
return (cp >= 0x09 && cp <= 0x0D) || (cp >= 0x1C && cp <= 0x20) || cp == 0xA0 || cp == 0x1680 ||
(cp >= 0x2000 && cp <= 0x200A) || cp == 0x2028 || cp == 0x2029 || cp == 0x202F || cp == 0x205F ||
cp == 0x3000;
}
// Zeros of the BMP's Nd (decimal digit) runs, Unicode 13 (JDK 17). Supplementary
// digits arrive in Kotlin as surrogate pairs, which are not digits.
static const unsigned kDigitZeros[] = {
0x0030, 0x0660, 0x06F0, 0x07C0, 0x0966, 0x09E6, 0x0A66, 0x0AE6, 0x0B66, 0x0BE6, 0x0C66, 0x0CE6,
0x0D66, 0x0DE6, 0x0E50, 0x0ED0, 0x0F20, 0x1040, 0x1090, 0x17E0, 0x1810, 0x1946, 0x19D0, 0x1A80,
0x1A90, 0x1B50, 0x1BB0, 0x1C40, 0x1C50, 0xA620, 0xA8D0, 0xA900, 0xA9D0, 0xA9F0, 0xAA50, 0xABF0, 0xFF10};
int decimalDigit(unsigned cp) {
for (unsigned z : kDigitZeros)
if (cp >= z && cp < z + 10) return (int)(cp - z);
return -1;
}
/** Character.digit(cp, radix). */
static int digitOf(unsigned cp, int radix) {
int d = decimalDigit(cp);
if (d < 0) {
if (cp >= 'a' && cp <= 'z') d = (int)(cp - 'a') + 10;
else if (cp >= 'A' && cp <= 'Z') d = (int)(cp - 'A') + 10;
else if (cp >= 0xFF41 && cp <= 0xFF5A) d = (int)(cp - 0xFF41) + 10;
else if (cp >= 0xFF21 && cp <= 0xFF3A) d = (int)(cp - 0xFF21) + 10;
}
return d >= 0 && d < radix ? d : -1;
}
std::vector<std::string> lines(const std::string &text) {
std::vector<std::string> out;
size_t start = 0;
for (size_t i = 0; i < text.size(); ++i) {
if (text[i] == '\n' || text[i] == '\r') {
out.emplace_back(text, start, i - start);
if (text[i] == '\r' && i + 1 < text.size() && text[i + 1] == '\n') ++i;
start = i + 1;
}
}
out.emplace_back(text, start, text.size() - start);
return out;
}
std::string trim(const std::string &s) {
size_t first = s.size(), last = 0; // [first, last) of non-whitespace
size_t i = 0;
while (i < s.size()) {
size_t at = i;
unsigned cp = decodeUtf8(s, i);
if (!isWhitespace(cp)) { if (first == s.size()) first = at; last = i; }
}
return first == s.size() ? std::string() : s.substr(first, last - first);
}
std::vector<std::string> split(const std::string &s, char c) {
std::vector<std::string> out;
size_t start = 0;
for (size_t i = 0; i < s.size(); ++i)
if (s[i] == c) { out.emplace_back(s, start, i - start); start = i + 1; }
out.emplace_back(s, start, s.size() - start);
return out;
}
size_t utf16Length(const std::string &s) {
size_t n = 0;
forEachIndexed(s, [&](size_t idx, unsigned cp) { n = idx + (cp >= 0x10000 ? 2 : 1); });
return n;
}
bool startsWith(const std::string &s, const char *prefix) {
size_t n = std::strlen(prefix);
return s.size() >= n && s.compare(0, n, prefix) == 0;
}
bool toIntOrNull(const std::string &s, int &out, int radix) {
if (s.empty()) return false;
size_t i = 0;
bool negative = false;
if ((unsigned char)s[0] < '0') { // a possible sign (Kotlin: firstChar < '0')
if (s.size() == 1) return false;
if (s[0] == '-') negative = true;
else if (s[0] != '+') return false;
i = 1;
}
int64_t v = 0;
const int64_t limit = negative ? -(int64_t)INT_MIN : (int64_t)INT_MAX;
while (i < s.size()) {
int d = digitOf(decodeUtf8(s, i), radix);
if (d < 0) return false;
v = v * radix + d;
if (v > limit) return false;
}
out = (int)(negative ? -v : v);
return true;
}
// Java's Double.valueOf grammar (what Kotlin screens toFloatOrNull with):
// [\x00-\x20]*[+-]?(NaN|Infinity|((Number)[fFdD]?))[\x00-\x20]*
bool toFloatOrNull(const std::string &str, float &out) {
size_t b = 0, e = str.size();
while (b < e && (unsigned char)str[b] <= 0x20) ++b;
while (e > b && (unsigned char)str[e - 1] <= 0x20) --e;
if (b == e) return false;
std::string s = str.substr(b, e - b);
size_t i = 0;
bool neg = false;
if (s[i] == '+' || s[i] == '-') { neg = s[i] == '-'; ++i; }
std::string rest = s.substr(i);
if (rest == "NaN") { out = NAN; return true; }
if (rest == "Infinity") { out = neg ? -INFINITY : INFINITY; return true; }
auto isDec = [](char c) { return c >= '0' && c <= '9'; };
auto isHex = [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); };
size_t j = i;
auto run = [&](auto pred) { size_t n = 0; while (j < s.size() && pred(s[j])) { ++j; ++n; } return n; };
if (j + 1 < s.size() && s[j] == '0' && (s[j + 1] == 'x' || s[j + 1] == 'X')) {
j += 2;
size_t a = run(isHex), f = 0;
bool dot = j < s.size() && s[j] == '.';
if (dot) { ++j; f = run(isHex); }
if (a == 0 && f == 0) return false;
if (j >= s.size() || (s[j] != 'p' && s[j] != 'P')) return false;
++j;
if (j < s.size() && (s[j] == '+' || s[j] == '-')) ++j;
if (run(isDec) == 0) return false;
} else {
size_t a = run(isDec), f = 0;
if (j < s.size() && s[j] == '.') { ++j; f = run(isDec); }
if (a == 0 && f == 0) return false;
if (j < s.size() && (s[j] == 'e' || s[j] == 'E')) {
++j;
if (j < s.size() && (s[j] == '+' || s[j] == '-')) ++j;
if (run(isDec) == 0) return false;
}
}
size_t numEnd = j;
if (j < s.size() && (s[j] == 'f' || s[j] == 'F' || s[j] == 'd' || s[j] == 'D')) ++j;
if (j != s.size()) return false;
std::string num = s.substr(0, numEnd);
// strtof reads the C locale's decimal point; keep it right if a host changed it.
const char *dp = std::localeconv()->decimal_point;
if (dp && std::strcmp(dp, ".") != 0) {
size_t p = num.find('.');
if (p != std::string::npos) num.replace(p, 1, dp);
}
out = std::strtof(num.c_str(), nullptr);
return true;
}
int floatToInt(float v) {
if (std::isnan(v)) return 0;
if (v >= 2147483648.f) return INT_MAX;
if (v <= -2147483648.f) return INT_MIN;
return (int)v;
}
std::string hexUpper(int v) {
uint32_t m = v < 0 ? (uint32_t)0 - (uint32_t)v : (uint32_t)v;
std::string r;
do { r.insert(r.begin(), "0123456789ABCDEF"[m & 15]); m >>= 4; } while (m);
return v < 0 ? "-" + r : r;
}
std::string padStart(const std::string &s, size_t n, char c) {
size_t len = utf16Length(s);
return len >= n ? s : std::string(n - len, c) + s;
}
std::string replaceAll(const std::string &s, const std::string &from, const std::string &to) {
if (from.empty()) return s;
std::string out;
size_t pos = 0;
for (size_t f; (f = s.find(from, pos)) != std::string::npos; pos = f + from.size()) {
out.append(s, pos, f - pos);
out += to;
}
out.append(s, pos, std::string::npos);
return out;
}
} // namespace sizzle::io::kt
+55
View File
@@ -0,0 +1,55 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Kotlin/JVM string semantics the file formats rely on, for UTF-8 text: lines
// (lineSequence), trim (Char.isWhitespace), split (keeps empty parts), lengths and
// indices in UTF-16 units (String.length, forEachIndexed), toIntOrNull (Unicode
// decimal digits, as Character.digit) and toFloatOrNull (Java's Float.parseFloat
// grammar). Malformed UTF-8 bytes are kept as they are and count as one unit each.
#include <string>
#include <vector>
namespace sizzle::io::kt {
/** One code point at s[i], advancing i; malformed bytes come back one at a time. */
unsigned decodeUtf8(const std::string &s, size_t &i);
/** Kotlin's Char.isWhitespace (Character.isWhitespace || isSpaceChar), BMP. */
bool isWhitespace(unsigned cp);
/** Character.isDigit's decimal value of [cp] (0..9), or -1. */
int decimalDigit(unsigned cp);
/** text.lineSequence(): split on CRLF, LF and CR. */
std::vector<std::string> lines(const std::string &text);
/** String.trim(). */
std::string trim(const std::string &s);
/** String.split(c): every part, empty ones included. */
std::vector<std::string> split(const std::string &s, char c);
/** String.length (UTF-16 units). */
size_t utf16Length(const std::string &s);
/** The code points of [s] with their UTF-16 index (as forEachIndexed sees them). */
template <typename F> void forEachIndexed(const std::string &s, F f) {
size_t i = 0, idx = 0;
while (i < s.size()) {
unsigned cp = decodeUtf8(s, i);
f(idx, cp);
idx += cp >= 0x10000 ? 2 : 1;
}
}
bool startsWith(const std::string &s, const char *prefix);
/** String.toIntOrNull(radix). */
bool toIntOrNull(const std::string &s, int &out, int radix = 10);
/** String.toFloatOrNull(). */
bool toFloatOrNull(const std::string &s, float &out);
/** Float.toInt(): NaN -> 0, saturating. */
int floatToInt(float v);
/** Integer.toString(v, 16), upper-cased. */
std::string hexUpper(int v);
/** padStart(n, '0'). */
std::string padStart(const std::string &s, size_t n, char c = '0');
/** replace(from, to) on every non-overlapping occurrence, left to right. */
std::string replaceAll(const std::string &s, const std::string &from, const std::string &to);
} // namespace sizzle::io::kt
+69
View File
@@ -0,0 +1,69 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "io/PresetIo.hpp"
#include <cstring>
#include <unordered_map>
#include <utility>
#include <vector>
#include "io/KotlinText.hpp"
#include "sizzle/Specs.hpp"
namespace sizzle::io {
using namespace model;
std::string PresetIo::exportText(const ToolboxSlot &slot) {
if (slot.isEmpty()) return std::string(HEADER) + "\nTYPE=EMPTY";
const DeviceSpec *spec = findDevice(slot.type.c_str());
std::string o;
auto line = [&](const std::string &s) { o += s; o += '\n'; };
line(HEADER);
line("TYPE=" + slot.type);
line("NAME=" + slot.name);
// Params in the type's declared order, then any extra keys the slot holds.
const int n = spec ? spec->paramCount : 0;
for (int i = 0; i < n; ++i) {
const ParamSpec &p = spec->params[i];
line(std::string(p.key) + "=" + slot.s(p.key, kotlinFloatToString(p.def).c_str()));
}
for (int i = 0; i < slot.values.size(); ++i) {
const char *key = slot.values.keyAt(i);
bool declared = false;
for (int k = 0; k < n && !declared; ++k) declared = std::strcmp(spec->params[k].key, key) == 0;
if (!declared) line(std::string(key) + "=" + slot.values.valueAt(i));
}
return o;
}
bool PresetIo::importText(ToolboxSlot &slot, const std::string &text) {
std::vector<std::pair<std::string, std::string>> map; // a LinkedHashMap
std::unordered_map<std::string, size_t> index;
std::string type;
bool hasType = false;
for (const std::string &raw : kt::lines(text)) {
const std::string line = kt::trim(raw);
if (line.empty() || line == HEADER) continue;
const size_t eq = line.find('=');
if (eq == std::string::npos) continue;
std::string key = line.substr(0, eq), value = line.substr(eq + 1);
if (key == "TYPE") {
hasType = value.find('\0') == std::string::npos && findDevice(value.c_str()) != nullptr;
type = hasType ? value : std::string();
} else if (key == "NAME") {
slot.name = value;
} else {
auto it = index.find(key);
if (it != index.end()) map[it->second].second = std::move(value);
else { index.emplace(key, map.size()); map.emplace_back(std::move(key), std::move(value)); }
}
}
if (!hasType) return false;
slot.fill(type); // reset to defaults for the type (and its display name) ...
if (kt::trim(slot.name).empty()) slot.name = findDevice(type.c_str())->displayName;
for (const auto &kv : map) slot.set(kv.first.c_str(), kv.second.c_str()); // ... then the saved values
return true;
}
} // namespace sizzle::io
+23
View File
@@ -0,0 +1,23 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of io/PresetIo.kt: one device's settings as text ("SIZZLE-PRESET 1",
// TYPE=, NAME=, then key=value in the device's parameter order, then any extra
// keys the slot holds, e.g. sample ids).
#include <string>
#include "sizzle/Model.hpp"
namespace sizzle::io {
struct PresetIo {
static constexpr const char *HEADER = "SIZZLE-PRESET 1";
static std::string exportText(const model::ToolboxSlot &slot);
/** Parse preset [text] into [slot]; false (slot settings untouched) unless a
* known TYPE is found. As in Kotlin, the slot's name ends up as the device's
* display name: NAME is applied before fill(), which overwrites it. */
static bool importText(model::ToolboxSlot &slot, const std::string &text);
};
} // namespace sizzle::io
+295
View File
@@ -0,0 +1,295 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "io/ProjectIo.hpp"
#include <algorithm>
#include <map>
#include "io/KotlinText.hpp"
#include "sizzle/Specs.hpp"
namespace sizzle::io {
using namespace model;
static const char *HEADER = "SIZZLETRACKER-SNG 1";
static const char *b(bool v) { return v ? "1" : "0"; }
// ------------------------------------------------------------------- write
std::string ProjectIo::save(const Project &project) {
std::string o;
auto line = [&](const std::string &s) { o += s; o += '\n'; };
auto num = [](int v) { return std::to_string(v); };
line(HEADER);
line("NAME=" + project.name);
line("TEMPO=" + kotlinFloatToString(project.tempoBpm));
line(std::string("SIG=") + info(project.timeSignature).name);
line(std::string("SCALE=") + info(project.scale).name);
line("ROOT=" + num(project.rootNote));
line("ACTIVE=" + num(project.activePatternId));
for (const Pattern &p : project.patterns) {
line("[PATTERN id=" + num(p.id) + " name=" + encodeName(p.name) + " len=" + num(p.length) + "]");
for (int t = 0; t < Pattern::TRACK_COUNT; ++t) {
const int n = std::min(p.length, (int)p.tracks[t].size());
for (int ln = 0; ln < n; ++ln) {
const Cell &c = p.tracks[t][ln];
if (!c.isEmpty())
line(num(t) + "," + num(ln) + "," + num(c.note) + "," + num(c.velocity) + "," + num(c.channel));
}
}
}
const Arrangement &arr = project.arrangement;
std::string mutes;
for (bool m : arr.laneMuted) mutes += m ? '1' : '0';
line("[ARRANGEMENT bars=" + num(arr.lengthBars) + " loop=" + b(arr.loopEnabled) + " mutes=" + mutes + "]");
const int usedBeats = arr.lastFilledBeat() + 1;
for (int lane = 0; lane < Arrangement::LANE_COUNT; ++lane) {
for (int beat = 0; beat < usedBeats; ++beat) {
const int pid = arr.slots[lane][beat];
// >= 0 is a block id; NOTE_OFF is a marker and must survive too.
if (pid >= 0 || pid == Arrangement::NOTE_OFF) line(num(lane) + "," + num(beat) + "," + num(pid));
}
}
auto region = [&](const char *n, const LoopRegion &r) {
line(std::string("[REGION ") + n + " en=" + b(r.enabled) + " s=" + num(r.start) + " e=" + num(r.end) +
" r=" + num(r.repeats) + "]");
};
region("A", arr.regionA);
region("B", arr.regionB);
line("[MIXER]");
for (const MixerChannel &ch : project.mixer.channels) {
std::string s = num(ch.index) + "," + num(ch.instrumentSlot) + ",";
for (int i = 0; i < MixerChannel::FX_SLOTS; ++i) s += (i ? "," : "") + num(ch.fxSlots[i]);
s += "," + num(ch.midiChannel) + "," + kotlinFloatToString(ch.volume) + "," + b(ch.mute) + "," +
b(ch.solo) + "," + b(ch.limiter);
line(s);
}
line("[TOOLBOX]");
for (const ToolboxSlot &slot : project.toolbox) {
if (slot.isEmpty()) continue;
std::string s = num(slot.index) + "=" + slot.type + ";" + slot.name + ";";
for (int i = 0; i < slot.values.size(); ++i) {
if (i) s += ',';
s += slot.values.keyAt(i);
s += '=';
s += slot.values.valueAt(i);
}
line(s);
}
return o;
}
// -------------------------------------------------------------------- read
namespace {
/** parseAttrs: "[NAME k=v k=v]" -> {k: v}; the last duplicate wins. */
std::map<std::string, std::string> parseAttrs(const std::string &line) {
size_t a = 0, z = line.size();
while (a < z && (line[a] == '[' || line[a] == ']')) ++a;
while (z > a && (line[z - 1] == '[' || line[z - 1] == ']')) --z;
const std::string inner = line.substr(a, z - a);
const size_t sp = inner.find(' ');
std::map<std::string, std::string> out;
if (sp == std::string::npos) return out;
for (const std::string &tok : kt::split(inner.substr(sp + 1), ' ')) {
const size_t eq = tok.find('=');
if (eq != std::string::npos) out[tok.substr(0, eq)] = tok.substr(eq + 1);
}
return out;
}
const std::string *get(const std::map<std::string, std::string> &m, const char *k) {
auto it = m.find(k);
return it == m.end() ? nullptr : &it->second;
}
int intOr(const std::string *s, int fallback) {
int v;
return s && kt::toIntOrNull(*s, v) ? v : fallback;
}
int intOr(const std::string &s, int fallback) { return intOr(&s, fallback); }
void applyHeaderField(Project &p, const std::string &line) {
const size_t eq = line.find('=');
const std::string k = line.substr(0, eq), v = line.substr(eq + 1);
if (k == "NAME") p.name = v;
else if (k == "TEMPO") { float f; p.tempoBpm = kt::toFloatOrNull(v, f) ? f : 120.f; }
else if (k == "SIG") {
p.timeSignature = TimeSignature::FOUR_FOUR;
for (int i = 0; i < TIME_SIGNATURE_COUNT; ++i)
if (v == info((TimeSignature)i).name) p.timeSignature = (TimeSignature)i;
} else if (k == "SCALE") {
p.scale = Scale::CHROMATIC;
for (int i = 0; i < SCALE_COUNT; ++i)
if (v == info((Scale)i).name) p.scale = (Scale)i;
} else if (k == "ROOT") p.rootNote = intOr(v, 0);
else if (k == "ACTIVE") p.activePatternId = intOr(v, 0);
}
void applyPatternCell(Pattern *pattern, const std::string &line) {
if (!pattern) return;
Pattern &p = *pattern;
const auto f = kt::split(line, ',');
if (f.size() < 5) return;
int t, ln;
if (!kt::toIntOrNull(f[0], t) || !kt::toIntOrNull(f[1], ln)) return;
if (t < 0 || t >= Pattern::TRACK_COUNT || ln < 0 || ln >= p.length || ln >= (int)p.tracks[t].size()) return;
Cell &c = p.tracks[t][ln];
c.note = intOr(f[2], Cell::EMPTY);
c.velocity = std::clamp(intOr(f[3], Cell::MAX_VELOCITY), 0, (int)Cell::MAX_VELOCITY);
c.channel = std::clamp(intOr(f[4], 1), 1, (int)Cell::MAX_CHANNEL);
}
void applyArrangementSlot(Project &p, const std::string &line) {
const auto f = kt::split(line, ',');
if (f.size() < 3) return;
int lane, beat, pid;
if (!kt::toIntOrNull(f[0], lane) || !kt::toIntOrNull(f[1], beat) || !kt::toIntOrNull(f[2], pid)) return;
p.arrangement.set(lane, beat, pid);
}
void applyRegion(LoopRegion &r, const std::map<std::string, std::string> &a) {
const std::string *en = get(a, "en");
r.enabled = en && *en == "1";
r.start = intOr(get(a, "s"), 0);
r.end = intOr(get(a, "e"), 0);
r.repeats = intOr(get(a, "r"), 2);
}
void applyMixerRow(Project &p, const std::string &line) {
const auto f = kt::split(line, ',');
if (f.size() < 10) return;
int idx;
if (!kt::toIntOrNull(f[0], idx) || idx < 0 || idx >= Mixer::CHANNEL_COUNT) return;
MixerChannel &ch = p.mixer.channels[idx];
ch.instrumentSlot = intOr(f[1], -1);
for (int i = 0; i < Mixer::FX_SLOTS; ++i) ch.fxSlots[i] = intOr(f[2 + i], -1);
ch.midiChannel = intOr(f[6], 0);
float v;
ch.volume = kt::toFloatOrNull(f[7], v) ? v : 0.8f;
ch.mute = f[8] == "1";
ch.solo = f[9] == "1";
ch.limiter = f.size() > 10 && f[10] == "1"; // optional: absent in older saves
}
void applyToolboxRow(Project &p, const std::string &line) {
const size_t eq = line.find('=');
int idx;
if (!kt::toIntOrNull(line.substr(0, eq), idx)) return;
const std::string rest = eq == std::string::npos ? line : line.substr(eq + 1);
const auto parts = kt::split(rest, ';');
if (parts.size() < 2) return;
if (!findDevice(parts[0].c_str()) || parts[0].find('\0') != std::string::npos) return;
if (idx < 0 || idx >= Project::TOOLBOX_SLOTS) return;
ToolboxSlot &slot = p.toolbox[idx];
slot.fill(parts[0]);
slot.name = parts[1];
if (parts.size() >= 3 && !kt::trim(parts[2]).empty()) {
for (const std::string &kv : kt::split(parts[2], ',')) {
const size_t e = kv.find('=');
if (e != std::string::npos) slot.set(kv.substr(0, e).c_str(), kv.substr(e + 1).c_str());
}
}
}
} // namespace
model::Project &ProjectIo::loadInto(Project &project, const std::string &text) {
// Reset everything Kotlin resets to a clean slate first.
project.patterns.clear();
for (auto &lane : project.arrangement.slots) std::fill(lane.begin(), lane.end(), Arrangement::EMPTY);
project.arrangement.laneMuted.fill(false);
for (auto &slot : project.toolbox) slot.clearSlot();
for (auto &ch : project.mixer.channels) {
ch.instrumentSlot = -1; ch.fxSlots.fill(-1); ch.midiChannel = 0;
ch.volume = 0.8f; ch.mute = false; ch.solo = false; ch.limiter = false;
}
std::string section;
int current = -1; // index into project.patterns (Kotlin keeps a reference)
long cells = 0;
for (const std::string &raw : kt::lines(text)) {
const std::string line = kt::trim(raw);
if (line.empty()) continue;
if (line == HEADER) {
} else if (kt::startsWith(line, "[PATTERN")) {
const auto attrs = parseAttrs(line);
const int id = intOr(get(attrs, "id"), (int)project.patterns.size());
const std::string *name = get(attrs, "name");
const int len = intOr(get(attrs, "len"), 16);
// Kotlin: a negative length throws in Pattern's constructor (line skipped);
// a huge one runs out of memory (also skipped).
if (len < 0 || cells + 4L * len > MAX_TOTAL_CELLS) continue;
cells += 4L * len;
project.patterns.emplace_back(id, name ? decodeName(*name) : std::string("PTN"), len);
current = (int)project.patterns.size() - 1;
section = "PATTERN";
} else if (kt::startsWith(line, "[ARRANGEMENT")) {
const auto attrs = parseAttrs(line);
// "bars" is the canvas unit; older files stored "len" in beats and get the
// default 256-bar canvas.
project.arrangement.lengthBars = intOr(get(attrs, "bars"), Arrangement::MAX_BARS);
const std::string *loop = get(attrs, "loop");
project.arrangement.loopEnabled = loop && *loop == "1";
if (const std::string *m = get(attrs, "mutes")) {
auto &lanes = project.arrangement.laneMuted;
kt::forEachIndexed(*m, [&](size_t i, unsigned cp) {
if (i < lanes.size()) lanes[i] = cp == '1';
});
}
section = "ARRANGEMENT";
} else if (kt::startsWith(line, "[REGION A")) {
applyRegion(project.arrangement.regionA, parseAttrs(line));
} else if (kt::startsWith(line, "[REGION B")) {
applyRegion(project.arrangement.regionB, parseAttrs(line));
} else if (kt::startsWith(line, "[MIXER]")) {
section = "MIXER";
} else if (kt::startsWith(line, "[TOOLBOX]")) {
section = "TOOLBOX";
} else if (line.find('=') != std::string::npos && line[0] != '[' && section.empty()) {
applyHeaderField(project, line);
} else if (section == "PATTERN") {
applyPatternCell(current >= 0 ? &project.patterns[current] : nullptr, line);
} else if (section == "ARRANGEMENT") {
applyArrangementSlot(project, line);
} else if (section == "MIXER") {
applyMixerRow(project, line);
} else if (section == "TOOLBOX") {
applyToolboxRow(project, line);
}
}
// One block per lane (lane i is tied to block i): pad any the file did not define.
for (int id = 0; id < Arrangement::LANE_COUNT; ++id) {
if (!project.pattern(id)) project.patterns.emplace_back(id, "BLK" + std::to_string(id + 1), 16);
}
std::stable_sort(project.patterns.begin(), project.patterns.end(),
[](const Pattern &a, const Pattern &b) { return a.id < b.id; });
project.activePatternId = std::clamp(project.activePatternId, 0, (int)project.patterns.size() - 1);
return project;
}
std::string ProjectIo::encodeName(const std::string &name) {
std::string o;
for (char c : name) {
switch (c) {
case '%': o += "%25"; break;
case ' ': o += "%20"; break;
case ']': o += "%5D"; break;
case '\t': case '\n': case '\r': o += "%20"; break;
default: o += c;
}
}
return o;
}
std::string ProjectIo::decodeName(const std::string &text) {
return kt::replaceAll(kt::replaceAll(kt::replaceAll(text, "%20", " "), "%5D", "]"), "%25", "%");
}
} // namespace sizzle::io
+32
View File
@@ -0,0 +1,32 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of io/ProjectIo.kt: the full project format (.szg, "SIZZLETRACKER-SNG 1").
// Files written by the Kotlin app load and save back byte for byte, except that
// each [TOOLBOX] line lists its key=value pairs in the slot's insertion order where
// Kotlin wrote ConcurrentHashMap order (both read back the same).
#include <string>
#include "sizzle/Model.hpp"
namespace sizzle::io {
struct ProjectIo {
static std::string save(const model::Project &project);
/** Parse [text] into the existing [project], replacing its contents (what
* Kotlin resets; header fields missing from the file keep their values).
* Malformed lines are skipped one by one, as Kotlin's runCatching does. */
static model::Project &loadInto(model::Project &project, const std::string &text);
/** Block names go into a whitespace-split header: escape space, '%' and ']'. */
static std::string encodeName(const std::string &name);
static std::string decodeName(const std::string &text);
/** Not in Kotlin (it would run out of memory and skip the line): a [PATTERN]
* line whose length would take the file's patterns past this many cells is
* skipped, so an untrusted file can't allocate without bound. */
static constexpr long MAX_TOTAL_CELLS = 1L << 22;
};
} // namespace sizzle::io
+302
View File
@@ -0,0 +1,302 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "io/SngFormat.hpp"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <set>
#include "io/KotlinText.hpp"
namespace sizzle::io {
using namespace model;
static const char *const NAMES[12] = {"C-", "C#", "D-", "D#", "E-", "F-", "F#", "G-", "G#", "A-", "A#", "B-"};
std::string pitchName(int midi) {
if (midi < Pitch::LOWEST || midi > Pitch::HIGHEST) return "...";
return std::string(NAMES[midi % 12]) + std::to_string(midi / 12 - 1);
}
int pitchParse(const std::string &text) {
const std::string t = kt::trim(text);
if (t == "OFF" || t == "===") return Cell::OFF;
if (kt::utf16Length(t) < 3 || t[0] == '.') return Cell::EMPTY;
int idx = -1;
for (int i = 0; i < 12; ++i)
if (t.compare(0, 2, NAMES[i]) == 0) { idx = i; break; }
if (idx < 0) return Cell::EMPTY;
int octave;
if (!kt::toIntOrNull(t.substr(2), octave)) return Cell::EMPTY;
// Kotlin Int arithmetic wraps before the clamp.
const int32_t v = (int32_t)((uint32_t)((int64_t)octave + 1) * 12u + (uint32_t)idx);
return std::clamp((int)v, (int)Pitch::LOWEST, (int)Pitch::HIGHEST);
}
// ------------------------------------------------------------------- write
std::string SngFormat::exportText(const Project &project) {
std::string o;
auto line = [&](const std::string &s) { o += s; o += '\n'; };
const int beatsPerBar = info(project.timeSignature).beatsPerBar;
line("version 1");
line("bpm " + std::to_string(kt::floatToInt(project.tempoBpm)));
line("sig " + std::to_string(beatsPerBar) + " 4");
line("");
const Arrangement &arr = project.arrangement;
const int usedBeats = arr.lastFilledBeat() + 1;
for (const Pattern &block : project.patterns) {
bool rollUsed = false, hasNotes = false;
for (int beat = 0; beat < usedBeats && !rollUsed; ++beat)
rollUsed = arr.patternAt(block.id, beat) != Arrangement::EMPTY;
auto len = [&](int t) { return std::min(block.length, (int)block.tracks[t].size()); };
for (int t = 0; t < Pattern::TRACK_COUNT && !hasNotes; ++t)
for (int l = 0; l < len(t) && !hasNotes; ++l) hasNotes = !block.tracks[t][l].isEmpty();
if (!rollUsed && !hasNotes) continue; // skip untouched blocks
line("block " + block.name + " " + std::to_string(block.length) + " " + std::to_string(beatsPerBar));
// '#' = play this block, 'x' = release this lane, '.' = nothing.
std::string roll;
for (int beat = 0; beat < usedBeats; ++beat) {
const int pid = arr.patternAt(block.id, beat);
roll += pid == Arrangement::EMPTY ? '.' : pid == Arrangement::NOTE_OFF ? 'x' : '#';
}
while (!roll.empty() && roll.back() == '.') roll.pop_back();
if (!roll.empty()) line("roll " + roll);
for (int t = 0; t < Pattern::TRACK_COUNT; ++t) {
bool any = false;
for (int l = 0; l < len(t) && !any; ++l) any = !block.tracks[t][l].isEmpty();
if (!any) continue;
const int defChannel = std::max(project.mixer.channels[t].midiChannel - 1, 0);
line("track T" + std::to_string(t + 1) + " " + std::to_string(defChannel));
for (int l = 0; l < len(t); ++l) {
const Cell &c = block.tracks[t][l];
if (c.isEmpty()) continue;
// A note-off has no velocity/channel: those columns are "..".
const std::string note = c.isNoteOff() ? "OFF" : pitchName(c.note);
const std::string vel = c.isNoteOff() ? ".." : kt::padStart(kt::hexUpper(c.velocity), 2);
const std::string chan = c.isNoteOff() ? ".." : kt::padStart(std::to_string(c.channel), 2);
line(std::to_string(l) + " " + note + " " + vel + " " + chan);
}
}
line("endblock");
line("");
}
return o;
}
// -------------------------------------------------------------------- read
// Java's \s (no UNICODE_CHARACTER_CLASS): [ \t\n\x0B\f\r].
static bool isRegexSpace(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\x0B' || c == '\f' || c == '\r'; }
// Regex("(?m)^\\s*(version|bpm|sig|block)\\b").containsMatchIn(text)
bool SngFormat::looksLikeSng(const std::string &text) {
static const char *const KEYS[] = {"version", "bpm", "sig", "block"};
auto lineStart = [&](size_t i) {
if (i == 0) return true;
if (i >= text.size()) return false; // MULTILINE ^ never matches at the very end
const unsigned char p = (unsigned char)text[i - 1];
if (p == '\n') return true;
if (p == '\r') return text[i] != '\n'; // no ^ between \r and \n
// U+0085, U+2028, U+2029 end lines too.
if (i >= 2 && (unsigned char)text[i - 2] == 0xC2 && p == 0x85) return true;
if (i >= 3 && (unsigned char)text[i - 3] == 0xE2 && (unsigned char)text[i - 2] == 0x80 && (p == 0xA8 || p == 0xA9))
return true;
return false;
};
// \b after the keyword: the next character is not a word character. Java 17's
// \b counts letters and digits of any script; any non-ASCII byte counts as one.
auto wordChar = [](unsigned char c) { return std::isalnum(c) || c == '_' || c >= 0x80; };
for (size_t i = 0; i <= text.size(); ++i) {
if (!lineStart(i)) continue;
size_t j = i;
while (j < text.size() && isRegexSpace(text[j])) ++j;
for (const char *k : KEYS) {
const size_t n = std::char_traits<char>::length(k);
if (text.compare(j, n, k) == 0 && (j + n >= text.size() || !wordChar((unsigned char)text[j + n])))
return true;
}
}
return false;
}
namespace {
using Tokens = std::vector<std::string>;
Tokens splitWhitespace(const std::string &line) { // line.split(Regex("\\s+")), line trimmed
Tokens out;
std::string cur;
size_t i = 0;
while (i < line.size()) {
if (isRegexSpace(line[i])) {
out.push_back(cur); cur.clear();
while (i < line.size() && isRegexSpace(line[i])) ++i;
} else {
cur += line[i++];
}
}
out.push_back(cur);
return out;
}
const std::string *at(const Tokens &t, size_t i) { return i < t.size() ? &t[i] : nullptr; }
/** `block <name...> <length> [<numTracks>]` -> (name, length or -1 for none). */
std::pair<std::string, bool> blockHeader(const Tokens &tok, int &length) {
const Tokens rest(tok.begin() + 1, tok.end());
int trailing = 0, v;
for (size_t i = rest.size(); i-- > 0 && kt::toIntOrNull(rest[i], v);) ++trailing;
trailing = std::min(trailing, 2);
bool hasLength = false;
if (trailing == 2) hasLength = kt::toIntOrNull(rest[rest.size() - 2], length);
else if (trailing == 1) hasLength = kt::toIntOrNull(rest.back(), length);
std::string name;
for (size_t i = 0; i + (size_t)trailing < rest.size(); ++i) name += (i ? " " : "") + rest[i];
if (name.empty()) name = rest.empty() ? "PTN" : rest.front();
return {name, hasLength};
}
/** Which block ordinals get one of the [slots] patterns: on-roll blocks first. */
std::set<int> blocksToKeep(const std::vector<Tokens> &lines, size_t slots) {
std::vector<bool> onRoll;
for (const Tokens &tok : lines) {
if (tok[0] == "block") onRoll.push_back(false);
else if (tok[0] == "roll" && !onRoll.empty() && tok.size() > 1 && tok[1].find('#') != std::string::npos)
onRoll.back() = true;
}
std::vector<int> order;
for (size_t i = 0; i < onRoll.size(); ++i) if (onRoll[i]) order.push_back((int)i);
for (size_t i = 0; i < onRoll.size(); ++i) if (!onRoll[i]) order.push_back((int)i);
if (order.size() > slots) order.resize(slots);
return std::set<int>(order.begin(), order.end());
}
void applyStep(Pattern *block, int track, int trackChannel, const Tokens &tok) {
if (!block) return;
int tick;
if (!kt::toIntOrNull(tok[0], tick)) return;
if (tick < 0 || tick >= block->length || tick >= (int)block->tracks[track].size()) return;
Cell &c = block->tracks[track][tick];
c.note = pitchParse(tok.size() > 1 ? tok[1] : "...");
int v;
c.velocity = std::clamp(tok.size() > 2 && tok[2] != ".." && kt::toIntOrNull(tok[2], v, 16) ? v : (int)Cell::MAX_VELOCITY,
0, (int)Cell::MAX_VELOCITY);
c.channel = std::clamp(tok.size() > 3 && tok[3] != ".." && kt::toIntOrNull(tok[3], v) ? v : trackChannel,
1, (int)Cell::MAX_CHANNEL);
}
} // namespace
model::Project &SngFormat::importInto(Project &project, const std::string &text) {
// Clear blocks and arrangement (keep the lane-blocks, wipe their cells).
for (Pattern &p : project.patterns)
for (auto &track : p.tracks)
for (Cell &c : track) c.clear();
for (auto &lane : project.arrangement.slots) std::fill(lane.begin(), lane.end(), Arrangement::EMPTY);
project.arrangement.laneMuted.fill(false);
std::vector<Tokens> lines;
for (const std::string &raw : kt::lines(text)) {
const std::string line = kt::trim(raw);
if (line.empty() || line[0] == '#') continue;
lines.push_back(splitWhitespace(line));
}
const std::set<int> keep = blocksToKeep(lines, project.patterns.size());
int blockOrdinal = -1; // index of the block in the file
size_t nextPattern = 0; // next free pattern (lane) to fill
Pattern *current = nullptr;
int track = -1, trackChannel = 1;
bool usedTracks[Pattern::TRACK_COUNT] = {};
size_t maxRoll = 0;
for (const Tokens &tok : lines) {
const std::string &k = tok[0];
if (k == "version" || k == "group" || k == "scale" || k == "root" || k == "kind" || k == "intro") {
} else if (k == "bpm") {
float f;
if (tok.size() > 1 && kt::toFloatOrNull(tok[1], f) && std::isfinite(f))
project.tempoBpm = std::clamp(f, 20.f, 300.f);
} else if (k == "sig") {
int n = 0;
const bool ok = tok.size() > 1 && kt::toIntOrNull(tok[1], n);
project.timeSignature = ok && n == 3 ? TimeSignature::THREE_FOUR
: ok && n == 5 ? TimeSignature::FIVE_FOUR : TimeSignature::FOUR_FOUR;
} else if (k == "loop") {
if (tok.size() >= 3) project.arrangement.loopEnabled = true;
} else if (k == "block") {
blockOrdinal++;
current = nullptr;
if (keep.count(blockOrdinal)) {
const size_t n = nextPattern++;
if (n < project.patterns.size()) current = &project.patterns[n];
}
if (current) {
int length = 0;
auto [name, hasLength] = blockHeader(tok, length);
current->name = name;
if (hasLength) current->resize(std::clamp(length, 1, MAX_BLOCK_LENGTH));
}
track = -1; trackChannel = 1;
std::fill(std::begin(usedTracks), std::end(usedTracks), false);
} else if (k == "roll") {
if (current) {
const std::string roll = tok.size() > 1 ? tok[1] : "";
const int id = current->id;
kt::forEachIndexed(roll, [&](size_t beat, unsigned ch) {
if (beat > (size_t)Arrangement::MAX_BEATS) return;
if (ch == '#') project.arrangement.set(id, (int)beat, id);
else if (ch == 'x') project.arrangement.set(id, (int)beat, Arrangement::NOTE_OFF);
});
maxRoll = std::max(maxRoll, kt::utf16Length(roll));
}
} else if (k == "track") {
int wanted = -1;
bool hasWanted = false;
if (const std::string *name = at(tok, 1)) {
std::string digits; // filter { it.isDigit() }
size_t i = 0;
while (i < name->size()) {
const size_t from = i;
const unsigned cp = kt::decodeUtf8(*name, i);
if (kt::decimalDigit(cp) >= 0) digits.append(*name, from, i - from);
}
hasWanted = kt::toIntOrNull(digits, wanted);
if (hasWanted) wanted -= 1; // digits only: wanted >= 0, no overflow
}
if (hasWanted && wanted >= 0 && wanted < Pattern::TRACK_COUNT && !usedTracks[wanted]) {
track = wanted;
} else {
track = -1;
for (int t = 0; t < Pattern::TRACK_COUNT; ++t) if (!usedTracks[t]) { track = t; break; }
}
if (track >= 0) usedTracks[track] = true;
int ch;
trackChannel = tok.size() > 2 && kt::toIntOrNull(tok[2], ch)
? std::clamp((int)(int32_t)((uint32_t)ch + 1u), 1, 16) : 1;
} else if (k == "endblock") {
current = nullptr; track = -1;
} else if (track >= 0) {
applyStep(current, track, trackChannel, tok);
}
}
// Grow the canvas (in bars) if the imported roll is longer than the default.
if (maxRoll > 0) {
const long beatsPerBar = info(project.timeSignature).beatsPerBar;
// Kotlin: (maxRoll + beatsPerBar - 1) / beatsPerBar in Int (a roll longer
// than Int.MAX_VALUE can't come from a String).
const long neededBars = ((long)maxRoll + beatsPerBar - 1) / beatsPerBar;
project.arrangement.lengthBars =
(int)std::min(std::max((long)project.arrangement.lengthBars, neededBars), (long)Arrangement::MAX_BARS);
}
project.activePatternId = 0;
return project;
}
} // namespace sizzle::io
+29
View File
@@ -0,0 +1,29 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of io/SngFormat.kt: the desktop sizzletracker `.sng` interchange format
// (musical data only: tempo, signature, blocks, rolls, steps).
#include <string>
#include "sizzle/Model.hpp"
namespace sizzle::io {
struct SngFormat {
/** Longest block accepted (the desktop tracker's bound). */
static constexpr int MAX_BLOCK_LENGTH = 1024;
static std::string exportText(const model::Project &project);
/** Cheap content sniff: does [text] look like a `.sng` at all? */
static bool looksLikeSng(const std::string &text);
/** Parse `.sng` [text] into the existing [project] (its blocks and arrangement
* are reset; mixer and toolbox are kept). */
static model::Project &importInto(model::Project &project, const std::string &text);
};
/** Pitch.name / Pitch.parse (model/Music.kt): "C-4" <-> 60, "OFF", "...". */
std::string pitchName(int midi);
int pitchParse(const std::string &text);
} // namespace sizzle::io
+148
View File
@@ -0,0 +1,148 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "io/Zip.hpp"
#include <zlib.h>
#include <cstring>
namespace sizzle::io::zip {
namespace {
void u16(std::vector<uint8_t> &o, uint32_t v) { o.push_back((uint8_t)v); o.push_back((uint8_t)(v >> 8)); }
void u32(std::vector<uint8_t> &o, uint32_t v) { u16(o, v & 0xFFFF); u16(o, v >> 16); }
uint32_t r16(const uint8_t *p) { return (uint32_t)p[0] | ((uint32_t)p[1] << 8); }
uint32_t r32(const uint8_t *p) { return r16(p) | (r16(p + 2) << 16); }
bool deflateRaw(const std::vector<uint8_t> &in, std::vector<uint8_t> &out) {
z_stream z{};
if (deflateInit2(&z, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) return false;
out.resize(deflateBound(&z, (uLong)in.size()));
z.next_in = const_cast<Bytef *>(in.data());
z.avail_in = (uInt)in.size();
z.next_out = out.data();
z.avail_out = (uInt)out.size();
const int rc = deflate(&z, Z_FINISH);
out.resize(z.total_out);
deflateEnd(&z);
return rc == Z_STREAM_END;
}
bool inflateRaw(const uint8_t *in, size_t n, std::vector<uint8_t> &out, size_t expected) {
z_stream z{};
if (inflateInit2(&z, -15) != Z_OK) return false;
out.resize(expected + 1); // one spare byte: an empty entry still has room, and overlong data shows
z.next_in = const_cast<Bytef *>(in);
z.avail_in = (uInt)n;
z.next_out = out.data();
z.avail_out = (uInt)out.size();
const int rc = inflate(&z, Z_FINISH);
const bool ok = rc == Z_STREAM_END && z.total_out == expected;
out.resize(expected);
inflateEnd(&z);
return ok;
}
} // namespace
std::vector<uint8_t> write(const std::vector<Entry> &entries) {
std::vector<uint8_t> o, central;
uint32_t count = 0;
for (const Entry &e : entries) {
const uint32_t crc = (uint32_t)crc32(0, e.data.data(), (uInt)e.data.size());
std::vector<uint8_t> packed;
uint16_t method = 8;
if (!deflateRaw(e.data, packed) || packed.size() >= e.data.size()) { packed = e.data; method = 0; }
const uint32_t offset = (uint32_t)o.size();
auto header = [&](std::vector<uint8_t> &h, bool isCentral) {
u32(h, isCentral ? 0x02014b50 : 0x04034b50);
if (isCentral) u16(h, 20); // made by
u16(h, 20); // needed
u16(h, 0x0800); // flags: UTF-8 names
u16(h, method);
u16(h, 0); u16(h, 0x21); // time, date (1980-01-01)
u32(h, crc);
u32(h, (uint32_t)packed.size());
u32(h, (uint32_t)e.data.size());
u16(h, (uint32_t)e.name.size());
u16(h, 0); // extra
if (isCentral) { u16(h, 0); u16(h, 0); u16(h, 0); u32(h, 0); u32(h, offset); }
h.insert(h.end(), e.name.begin(), e.name.end());
};
header(o, false);
o.insert(o.end(), packed.begin(), packed.end());
header(central, true);
++count;
}
const uint32_t cdOffset = (uint32_t)o.size();
o.insert(o.end(), central.begin(), central.end());
u32(o, 0x06054b50);
u16(o, 0); u16(o, 0);
u16(o, count); u16(o, count);
u32(o, (uint32_t)central.size());
u32(o, cdOffset);
u16(o, 0);
return o;
}
bool read(const uint8_t *b, size_t size, std::vector<Entry> &out, uint64_t maxTotal, size_t maxEntries) {
out.clear();
if (size < 22) return false;
// End of central directory: the last signature within the 64 KiB comment window.
size_t eocd = SIZE_MAX;
const size_t lowest = size > 22 + 65535 ? size - 22 - 65535 : 0;
for (size_t i = size - 22 + 1; i-- > lowest;) {
if (r32(b + i) == 0x06054b50) { eocd = i; break; }
}
if (eocd == SIZE_MAX) return false;
const size_t count = r16(b + eocd + 10);
const size_t cdSize = r32(b + eocd + 12), cdOffset = r32(b + eocd + 16);
if (count > maxEntries || cdOffset > size || cdSize > size - cdOffset) return false;
uint64_t total = 0;
size_t p = cdOffset;
for (size_t k = 0; k < count; ++k) {
if (p + 46 > size || r32(b + p) != 0x02014b50) { out.clear(); return false; }
const uint32_t flags = r16(b + p + 8), method = r16(b + p + 10), crc = r32(b + p + 16);
const size_t csize = r32(b + p + 20), usize = r32(b + p + 24);
const size_t nameLen = r16(b + p + 28), extraLen = r16(b + p + 30), commentLen = r16(b + p + 32);
const size_t local = r32(b + p + 42);
if (p + 46 + nameLen > size) { out.clear(); return false; }
std::string name((const char *)b + p + 46, nameLen);
p += 46 + nameLen + extraLen + commentLen;
if (flags & 1) { out.clear(); return false; } // encrypted
if (!name.empty() && name.back() == '/') continue; // a directory
total += usize;
if (total > maxTotal) { out.clear(); return false; }
if (local + 30 > size || r32(b + local) != 0x04034b50) { out.clear(); return false; }
const size_t data = local + 30 + r16(b + local + 26) + r16(b + local + 28);
if (data > size || csize > size - data) { out.clear(); return false; }
Entry e;
e.name = std::move(name);
if (method == 0) {
if (csize != usize) { out.clear(); return false; }
e.data.assign(b + data, b + data + csize);
} else if (method == 8) {
if (!inflateRaw(b + data, csize, e.data, usize)) { out.clear(); return false; }
} else { out.clear(); return false; }
if ((uint32_t)crc32(0, e.data.data(), (uInt)e.data.size()) != crc) { out.clear(); return false; }
out.push_back(std::move(e));
}
return true;
}
bool safeName(const std::string &name) {
if (name.empty() || name[0] == '/' || name.find('\\') != std::string::npos || name.find('\0') != std::string::npos) return false;
size_t start = 0;
while (start <= name.size()) {
size_t end = name.find('/', start);
if (end == std::string::npos) end = name.size();
const std::string part = name.substr(start, end - start);
if (part == ".." || part == ".") return false;
start = end + 1;
}
return true;
}
} // namespace sizzle::io::zip
+40
View File
@@ -0,0 +1,40 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// A small ZIP reader/writer (zlib) for project bundles (.szgz) and backups, the
// archives java.util.zip writes and reads on Android. Whole archives in memory.
// Writes deflated entries with sizes and CRC in the local headers (no data
// descriptors), so ZipInputStream reads them. Reads through the central directory,
// so entries with data descriptors (what ZipOutputStream writes) are fine. No
// Zip64, no encryption.
#pragma once
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
namespace sizzle::io::zip {
struct Entry {
std::string name;
std::vector<uint8_t> data;
};
/** An archive of [entries], deflated. */
std::vector<uint8_t> write(const std::vector<Entry> &entries);
/**
* Every file entry of the archive in [bytes] (directories skipped). False, with
* [out] cleared, if it isn't a ZIP, is damaged (a CRC mismatch too), uses a
* method other than stored/deflate, has more than [maxEntries] entries or more
* than [maxTotal] bytes uncompressed (Android's ZipLimits budgets).
*/
bool read(const uint8_t *bytes, size_t size, std::vector<Entry> &out,
uint64_t maxTotal = 512ull << 20, size_t maxEntries = 20000);
/** A name that is safe to extract: relative, no "..", no backslashes or NULs. */
bool safeName(const std::string &name);
} // namespace sizzle::io::zip
+465
View File
@@ -0,0 +1,465 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "sizzle/Model.hpp"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
#include "sizzle/Specs.hpp"
namespace sizzle::model {
static const TimeSignatureInfo kSignatures[TIME_SIGNATURE_COUNT] = {
{"THREE_FOUR", "3/4", 3, 3, {12, 24, 48}},
{"FOUR_FOUR", "4/4", 4, 4, {16, 32, 64}},
{"FIVE_FOUR", "5/4", 5, 5, {20, 40, 80}},
};
const TimeSignatureInfo &info(TimeSignature t) { return kSignatures[(int)t]; }
static const ScaleInfo kScales[SCALE_COUNT] = {
{"CHROMATIC", "Chromatic", {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, 12},
{"MAJOR", "Major", {0, 2, 4, 5, 7, 9, 11}, 7},
{"MINOR", "Natural Minor", {0, 2, 3, 5, 7, 8, 10}, 7},
{"HARMONIC_MINOR", "Harmonic Minor", {0, 2, 3, 5, 7, 8, 11}, 7},
{"DORIAN", "Dorian", {0, 2, 3, 5, 7, 9, 10}, 7},
{"PHRYGIAN", "Phrygian", {0, 1, 3, 5, 7, 8, 10}, 7},
{"MIXOLYDIAN", "Mixolydian", {0, 2, 4, 5, 7, 9, 10}, 7},
{"PENTATONIC_MAJOR", "Pentatonic Major", {0, 2, 4, 7, 9}, 5},
{"PENTATONIC_MINOR", "Pentatonic Minor", {0, 3, 5, 7, 10}, 5},
{"BLUES", "Blues", {0, 3, 5, 6, 7, 10}, 6},
};
const ScaleInfo &info(Scale s) { return kScales[(int)s]; }
Pattern::Pattern(int id_, std::string name_, int length_) : id(id_), name(std::move(name_)), length(length_) {
for (auto &t : tracks) t.assign((size_t)length, Cell{Cell::EMPTY, Cell::MAX_VELOCITY, 0});
}
void Pattern::resize(int newLength) {
if (newLength == length) return;
for (auto &t : tracks) t.resize((size_t)newLength, Cell{Cell::EMPTY, Cell::MAX_VELOCITY, 0});
length = newLength;
}
Arrangement::Arrangement() { for (auto &l : slots) l.assign(MAX_BEATS, EMPTY); }
int Arrangement::canvasBeats(TimeSignature sig) const {
return std::clamp(lengthBars * info(sig).beatsPerBar, 1, MAX_BEATS);
}
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;
}
int Arrangement::lastFilledBeat() const {
for (int beat = MAX_BEATS - 1; beat >= 0; --beat)
for (int lane = 0; lane < LANE_COUNT; ++lane)
if (slots[lane][beat] != EMPTY) return beat;
return -1;
}
void Arrangement::set(int lane, int beat, int patternId) {
if (lane >= 0 && lane < LANE_COUNT && beat >= 0 && beat < MAX_BEATS) slots[lane][beat] = patternId;
}
Mixer::Mixer() {
for (int i = 0; i < CHANNEL_COUNT; ++i) { channels[i].index = i; channels[i].midiChannel = 0; }
}
bool Mixer::anySolo() const {
for (auto &c : channels) if (c.solo) return true;
return false;
}
void ToolboxSlot::fill(const std::string &newType) {
type = newType;
values = Params();
const DeviceSpec *spec = findDevice(newType.c_str());
name = spec ? spec->displayName : newType;
if (!spec) return;
for (int i = 0; i < spec->paramCount; ++i) {
const ParamSpec &p = spec->params[i];
if (p.isEnum()) {
int n = p.choiceCount(), idx = std::clamp((int)p.def, 0, n - 1);
values.set(p.key, p.choices[idx]);
} else {
values.set(p.key, kotlinFloatToString(p.def).c_str());
}
}
++version;
}
void ToolboxSlot::clearSlot() { type.clear(); name.clear(); values = Params(); ++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() {
for (int i = 0; i < Arrangement::LANE_COUNT; ++i)
patterns.emplace_back(i, "BLK" + std::to_string(i + 1), info(timeSignature).lengthOptions[0]);
for (int i = 0; i < TOOLBOX_SLOTS; ++i) toolbox[i].index = i;
}
Pattern *Project::pattern(int id) {
for (auto &p : patterns) if (p.id == id) return &p;
return nullptr;
}
const Pattern *Project::pattern(int id) const {
for (auto &p : patterns) if (p.id == id) return &p;
return nullptr;
}
Pattern &Project::activePattern() {
Pattern *p = pattern(activePatternId);
return p ? *p : patterns.front();
}
// ---------------------------------------------------------------------------
// 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();
}
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
+30
View File
@@ -0,0 +1,30 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of TimeDivision (model/Toolbox.kt): tempo-synced note lengths.
namespace sizzle::model {
enum class TimeDivision : int {
WHOLE, HALF, QUARTER, EIGHTH, SIXTEENTH, THIRTYSECOND, DOTTED_EIGHTH
};
constexpr int TIME_DIVISION_COUNT = 7;
/** TimeDivision.entries' labels. */
constexpr const char *TIME_DIVISION_LABELS[TIME_DIVISION_COUNT] = {
"1/1", "1/2", "1/4", "1/8", "1/16", "1/32", "1/8."};
/** TimeDivision.entries' beatFraction (length in beats). */
constexpr double TIME_DIVISION_BEATS[TIME_DIVISION_COUNT] = {4.0, 2.0, 1.0, 0.5, 0.25, 0.125, 0.75};
/** TimeDivision.fromIndex(i): clamps to 0..lastIndex. */
constexpr TimeDivision fromIndex(int i) {
return (TimeDivision)(i < 0 ? 0 : (i > TIME_DIVISION_COUNT - 1 ? TIME_DIVISION_COUNT - 1 : i));
}
constexpr double beatFraction(TimeDivision d) { return TIME_DIVISION_BEATS[(int)d]; }
constexpr const char *label(TimeDivision d) { return TIME_DIVISION_LABELS[(int)d]; }
} // namespace sizzle::model
+245
View File
@@ -0,0 +1,245 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of SampleStore.kt (see SampleStore.hpp for the thread-safety design).
// decodeWav / encodeWav are line for line; Kotlin's ByteBuffer exceptions (a read
// past the end, position() past the limit) become explicit checks that return
// nothing, which is what the Kotlin's catch-all does.
#include "SampleStore.hpp"
#include <algorithm>
#include <cstring>
#include "KotlinMath.hpp"
#if defined(__clang__)
#pragma clang fp contract(off) // Java never fuses multiply-adds
#endif
namespace sizzle::sampler {
namespace {
bool idLess(const std::string &a, const std::string &b) { return std::strcmp(a.c_str(), b.c_str()) < 0; }
// Little-endian reads; callers check bounds first.
inline uint32_t u32le(const uint8_t *p) {
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
inline int32_t i32le(const uint8_t *p) { return (int32_t)u32le(p); }
inline int u16le(const uint8_t *p) { return (int)p[0] | ((int)p[1] << 8); }
inline int16_t i16le(const uint8_t *p) { return (int16_t)(uint16_t)u16le(p); }
inline bool tagIs(const uint8_t *p, const char *t) { return std::memcmp(p, t, 4) == 0; }
inline void putTag(std::vector<uint8_t> &b, const char *t) { b.insert(b.end(), t, t + 4); }
inline void put32(std::vector<uint8_t> &b, uint32_t v) {
b.push_back((uint8_t)v); b.push_back((uint8_t)(v >> 8)); b.push_back((uint8_t)(v >> 16)); b.push_back((uint8_t)(v >> 24));
}
inline void put16(std::vector<uint8_t> &b, uint16_t v) { b.push_back((uint8_t)v); b.push_back((uint8_t)(v >> 8)); }
} // namespace
// ------------------------------------------------------------------ the store
SampleStore::SampleStore() : current(std::make_unique<Snapshot>()) {
snap.store(current.get(), std::memory_order_release);
}
SampleStore::~SampleStore() = default;
const Sample *SampleStore::put(const std::string &id, Sample sample) {
auto owned = std::make_unique<Sample>(std::move(sample));
const Sample *p = owned.get();
std::lock_guard<std::mutex> g(writeLock);
std::unique_ptr<Sample> old;
auto it = std::lower_bound(live.begin(), live.end(), id,
[](const auto &e, const std::string &k) { return idLess(e.first, k); });
if (it != live.end() && it->first == id) {
old = std::move(it->second);
it->second = std::move(owned);
} else {
live.insert(it, {id, std::move(owned)});
}
publishLocked();
if (old) retiredSamples.push_back({std::move(old), epoch.load(std::memory_order_relaxed)});
collectLocked();
return p;
}
void SampleStore::remove(const std::string &id) {
if (id.empty()) return;
std::lock_guard<std::mutex> g(writeLock);
auto it = std::find_if(live.begin(), live.end(), [&](const auto &e) { return e.first == id; });
if (it == live.end()) return;
std::unique_ptr<Sample> old = std::move(it->second);
live.erase(it);
publishLocked();
retiredSamples.push_back({std::move(old), epoch.load(std::memory_order_relaxed)});
collectLocked();
}
void SampleStore::publishLocked() {
auto next = std::make_unique<Snapshot>();
next->entries.reserve(live.size());
for (const auto &e : live) next->entries.emplace_back(e.first, e.second.get());
snap.store(next.get(), std::memory_order_release);
std::unique_ptr<Snapshot> old = std::move(current);
current = std::move(next);
// The epoch moves after the new snapshot is visible: a reader that has seen this
// epoch at quiescent() can only find the new snapshot from then on.
uint64_t e = epoch.fetch_add(1, std::memory_order_acq_rel) + 1;
retiredSnaps.push_back({std::move(old), e});
}
void SampleStore::collect() {
std::lock_guard<std::mutex> g(writeLock);
collectLocked();
}
void SampleStore::collectLocked() {
uint64_t s = seen.load(std::memory_order_acquire);
retiredSnaps.erase(std::remove_if(retiredSnaps.begin(), retiredSnaps.end(),
[s](const RetiredSnapshot &r) { return r.epoch <= s; }), retiredSnaps.end());
retiredSamples.erase(std::remove_if(retiredSamples.begin(), retiredSamples.end(),
[s](const RetiredSample &r) {
return r.epoch <= s && r.sample->users.load(std::memory_order_acquire) == 0;
}), retiredSamples.end());
}
size_t SampleStore::retiredCount() const {
std::lock_guard<std::mutex> g(writeLock);
return retiredSnaps.size() + retiredSamples.size();
}
const Sample *SampleStore::get(const char *id) const {
if (id == nullptr || id[0] == '\0') return nullptr;
const Snapshot *s = snap.load(std::memory_order_acquire);
size_t lo = 0, hi = s->entries.size();
while (lo < hi) {
size_t mid = lo + (hi - lo) / 2;
int c = std::strcmp(s->entries[mid].first.c_str(), id);
if (c == 0) return s->entries[mid].second;
if (c < 0) lo = mid + 1; else hi = mid;
}
return nullptr;
}
void SampleStore::quiescent() {
seen.store(epoch.load(std::memory_order_acquire), std::memory_order_release);
}
// ------------------------------------------------------------------- decodeWav
std::optional<Sample> SampleStore::decodeWav(const uint8_t *bytes, size_t size) {
if (bytes == nullptr || size > 0x7FFFFFFF) return std::nullopt; // a Kotlin ByteArray's limit
const int32_t limit = (int32_t)size;
if (limit < 44) return std::nullopt;
if (bytes[0] != 'R' || bytes[1] != 'I') return std::nullopt; // "RIFF"
int32_t pos = 8;
if (!tagIs(bytes + pos, "WAVE")) return std::nullopt;
pos += 4;
int audioFormat = 1;
int channels = 1;
int32_t sampleRate = 44100;
int bitsPerSample = 16;
int32_t dataOffset = -1;
int32_t dataLength = 0;
// Walk the chunks looking for "fmt " and "data".
while (limit - pos >= 8) {
const uint8_t *tag = bytes + pos;
int32_t size32 = i32le(bytes + pos + 4);
pos += 8;
if (size32 < 0) break; // corrupt chunk size — stop scanning, use what we have
int32_t next = (int32_t)((uint32_t)pos + (uint32_t)size32); // Kotlin Int wraps
if (tagIs(tag, "fmt ")) {
if (limit - pos < 16) return std::nullopt; // BufferUnderflowException
audioFormat = u16le(bytes + pos);
channels = std::max(u16le(bytes + pos + 2), 1);
sampleRate = i32le(bytes + pos + 4);
// byteRate (4), blockAlign (2)
bitsPerSample = u16le(bytes + pos + 14);
pos += 16;
} else if (tagIs(tag, "data")) {
dataOffset = pos; dataLength = size32;
}
if (next >= 0 && next <= limit) {
int32_t np = (int32_t)((uint32_t)next + (uint32_t)(size32 & 1)); // word-aligned
if (np < 0 || np > limit) return std::nullopt; // position() past the limit throws
pos = np;
} else {
break;
}
}
if (dataOffset < 0) return std::nullopt;
// A header can over-report the data length; never read past the actual bytes.
dataLength = kt::coerceIn(dataLength, (int32_t)0, limit - dataOffset);
const int bytesPerSample = bitsPerSample / 8;
if (bytesPerSample == 0) return std::nullopt;
const int32_t frameCount = dataLength / (bytesPerSample * channels);
if (frameCount <= 0) return std::nullopt;
// The Kotlin's `else -> return null` runs on the first sample: decide up front.
const bool isFloat = audioFormat == 3 && bitsPerSample == 32;
if (!isFloat && bitsPerSample != 16 && bitsPerSample != 8 && bitsPerSample != 24 && bitsPerSample != 32)
return std::nullopt;
std::vector<float> out((size_t)frameCount);
const uint8_t *data = bytes + dataOffset;
size_t at = 0;
for (int32_t f = 0; f < frameCount; ++f) {
float acc = 0.f;
for (int c = 0; c < channels; ++c) {
float v;
if (isFloat) {
uint32_t u = u32le(data + at); at += 4;
std::memcpy(&v, &u, 4);
} else if (bitsPerSample == 16) {
v = (float)i16le(data + at) / 32768.f; at += 2;
} else if (bitsPerSample == 8) {
v = (float)((int)data[at] - 128) / 128.f; at += 1;
} else if (bitsPerSample == 24) {
int b0 = data[at], b1 = data[at + 1];
int b2 = (int)(int8_t)data[at + 2]; // signed high byte
at += 3;
v = (float)(int32_t)(((uint32_t)b2 << 16) | ((uint32_t)b1 << 8) | (uint32_t)b0) / 8388608.f;
} else { // 32-bit integer PCM
v = (float)i32le(data + at) / 2147483648.f; at += 4;
}
acc += v;
}
out[(size_t)f] = acc / (float)channels; // down-mix to mono
}
return Sample(std::move(out), sampleRate);
}
// ------------------------------------------------------------------- encodeWav
std::vector<uint8_t> SampleStore::encodeWav(const Sample &sample) {
const int32_t frames = (int32_t)sample.data.size();
const int32_t bytesPerSample = 2;
const int32_t channels = 1;
const uint32_t dataSize = (uint32_t)frames * bytesPerSample * channels;
std::vector<uint8_t> bb;
bb.reserve(44 + (size_t)dataSize);
putTag(bb, "RIFF");
put32(bb, 36u + dataSize);
putTag(bb, "WAVE");
putTag(bb, "fmt ");
put32(bb, 16); // PCM fmt chunk size
put16(bb, 1); // audioFormat = PCM
put16(bb, (uint16_t)channels);
put32(bb, (uint32_t)sample.sampleRate);
put32(bb, (uint32_t)sample.sampleRate * channels * bytesPerSample); // byteRate (wraps like Int)
put16(bb, (uint16_t)(channels * bytesPerSample)); // blockAlign
put16(bb, 16); // bitsPerSample
putTag(bb, "data");
put32(bb, dataSize);
for (float v : sample.data) {
put16(bb, (uint16_t)(int16_t)kt::toInt(kt::coerceIn(v, -1.f, 1.f) * 32767.f));
}
return bb;
}
} // namespace sizzle::sampler
+100
View File
@@ -0,0 +1,100 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of SampleStore.kt: the cache of decoded samples (id -> Sample) the Sampler,
// SoundFont and Grain Cloud play from, plus decodeWav / encodeWav.
//
// Thread safety (the Kotlin uses a ConcurrentHashMap; this is the real-time-safe
// equivalent):
//
// - Writers (put / remove / collect, any non-audio thread) are serialised by a
// mutex. Each change builds a new immutable Snapshot (a sorted id -> Sample*
// array) and publishes it with one atomic pointer store, then bumps an epoch.
// - The audio thread reads with get(): one atomic load and a binary search with
// strcmp. No lock, no allocation, no reference counting.
// - Nothing a reader can still see is freed early. A replaced snapshot and a
// removed (or replaced) sample are retired with the epoch of the change and freed
// by a later writer call (collect(), also run by put/remove) only once
// * the audio thread has called quiescent() after that epoch: it holds no
// pointer from an older snapshot (contract: a pointer from get() that is not
// pinned is used only until the reader's next quiescent(), i.e. within one
// audio block), and
// * the sample's `users` count is 0: no voice still plays it (SampleVoice pins
// from noteOn until it lets go). That is the Kotlin guarantee "any voice
// already playing it keeps its own reference".
// - quiescent() is called by the single reader thread (the engine's render
// callback, at each block start). When no audio thread runs, the owner may call
// it from its own thread to let retired memory go.
// - The store must outlive every reader; the destructor frees everything.
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "sizzle/Sample.hpp"
namespace sizzle::sampler {
class SampleStore {
public:
SampleStore();
~SampleStore();
SampleStore(const SampleStore &) = delete;
SampleStore &operator=(const SampleStore &) = delete;
// ---- writer side (any thread except the audio thread; may allocate)
/** Store [sample] under [id] (replacing any previous one); returns it. */
const Sample *put(const std::string &id, Sample sample);
/** Drop a cached sample. A voice already playing it keeps it alive. */
void remove(const std::string &id);
/** Free retired snapshots/samples no reader can reach any more. */
void collect();
/** Retired objects not freed yet (for tests and diagnostics). */
size_t retiredCount() const;
// ---- reader side (the audio thread; lock- and allocation-free)
/** The sample stored under [id], or null (also for an empty id). */
const Sample *get(const char *id) const;
/** The reader holds no unpinned pointer from get() past this point. */
void quiescent();
/** Pin / unpin a sample a player holds across blocks (Sample::users). */
static void pin(const Sample *s) { if (s) s->users.fetch_add(1, std::memory_order_acq_rel); }
static void unpin(const Sample *s) { if (s) s->users.fetch_sub(1, std::memory_order_acq_rel); }
/**
* Decode a WAV file (the common uncompressed formats) into a mono Sample.
* Supports 8/16/24-bit PCM and 32-bit float, mono or stereo (stereo is
* down-mixed). Returns nothing if the bytes are not a WAV we understand.
*/
static std::optional<Sample> decodeWav(const uint8_t *bytes, size_t size);
/** A 16-bit mono PCM WAV file of [sample] (the inverse of decodeWav). */
static std::vector<uint8_t> encodeWav(const Sample &sample);
private:
struct Snapshot {
std::vector<std::pair<std::string, const Sample *>> entries; // sorted by strcmp
};
struct RetiredSnapshot { std::unique_ptr<Snapshot> snap; uint64_t epoch; };
struct RetiredSample { std::unique_ptr<Sample> sample; uint64_t epoch; };
void publishLocked();
void collectLocked();
mutable std::mutex writeLock;
std::vector<std::pair<std::string, std::unique_ptr<Sample>>> live; // writer-owned, sorted
std::unique_ptr<Snapshot> current; // owner of `snap`
std::atomic<const Snapshot *> snap{nullptr};
std::atomic<uint64_t> epoch{0};
std::atomic<uint64_t> seen{0}; // last epoch the reader passed quiescent() at
std::vector<RetiredSnapshot> retiredSnaps;
std::vector<RetiredSample> retiredSamples;
};
} // namespace sizzle::sampler
+48
View File
@@ -0,0 +1,48 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// The reference-test maker for kind "SAMPLE" (see TestVoice.hpp and
// IosGoldenInstruments.kt): one SampleVoice playing the script with the engine's
// voiceSample() settings; the test sample is put in a store under every id the
// slot names (Sampler pads, SoundFont sfSample).
#include <memory>
#include <vector>
#include "SampleStore.hpp"
#include "SampleVoice.hpp"
#include "sizzle/TestVoice.hpp"
namespace sizzle {
namespace {
class SampleTestVoice final : public TestVoice {
sampler::SampleStore store;
sampler::SampleVoice voice;
const char *type;
const Params *params;
public:
explicit SampleTestVoice(const TestVoiceSetup &s) : voice(s.sampleRate), type(s.type), params(s.params) {
if (s.sample && s.sampleLength > 0) {
Sample smp(std::vector<float>(s.sample, s.sample + s.sampleLength), s.sampleRate2, s.loopStart, s.loopEnd);
auto putId = [&](const char *id) { if (id && id[0]) store.put(id, smp); };
for (int pad = 0; pad < sampler::SamplerPads::COUNT; ++pad)
putId(params->s(sampler::SamplerPads::key(pad).s));
putId(params->s("sfSample"));
}
}
void blockStart(int) override { store.quiescent(); }
void noteOn(int midi, int velocity) override {
sampler::VoiceSample vs;
if (sampler::voiceSample(type, *params, store, midi, vs)) voice.noteOn(vs, midi, velocity);
}
void noteOff(int) override { voice.noteOff(); }
float render() override { return voice.render(); }
};
} // namespace
std::unique_ptr<TestVoice> makeSampleTestVoice(const TestVoiceSetup &setup) {
return std::make_unique<SampleTestVoice>(setup);
}
} // namespace sizzle
+221
View File
@@ -0,0 +1,221 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of SampleVoice.kt and AudioEngine.voiceSample(), line for line: Float ->
// float, Double -> double, kotlin.math on Float through double (KotlinMath.hpp).
#include "SampleVoice.hpp"
#include <cmath>
#include <cstring>
#include "KotlinMath.hpp"
#if defined(__clang__)
#pragma clang fp contract(off) // Java never fuses multiply-adds
#endif
namespace sizzle::sampler {
namespace {
constexpr float FADE_STEP = 0.01f; // ~2 ms end fade at 48 kHz
constexpr double FADE_SAMPLES = 1.0 / (double)FADE_STEP; // output samples the fade spans
constexpr float MIN_ATTACK = 0.0005f; // ~0.5 ms minimum onset ramp
/** kotlin minOf / maxOf on Float (Math.min / Math.max: NaN wins). */
inline float minOf(float a, float b) { return a != a ? a : (b != b ? b : (a <= b ? a : b)); }
inline float maxOf(float a, float b) { return a != a ? a : (b != b ? b : (a >= b ? a : b)); }
/** Double.toInt(): truncation, NaN -> 0, saturating (keeps a wild index defined). */
inline int toInt(double x) {
if (x != x) return 0;
if (x >= 2147483647.0) return 2147483647;
if (x <= -2147483648.0) return (-2147483647 - 1);
return (int)x;
}
} // namespace
// ------------------------------------------------------------- voiceSample
bool voiceSample(const char *type, const Params &slot, const SampleStore &store, int note, VoiceSample &out) {
if (type == nullptr) return false;
if (std::strcmp(type, "SAMPLER") == 0) {
const int pad = SamplerPads::padFor(note);
if (pad < 0 || pad >= SamplerPads::COUNT) return false;
const Sample *s = store.get(slot.s(SamplerPads::key(pad).s));
if (!s) return false;
out = VoiceSample{};
out.sample = s;
out.root = note;
out.sliceStart = slot.f(SamplerPads::sliceStartKey(pad).s, 0.f);
out.sliceEnd = slot.f(SamplerPads::sliceEndKey(pad).s, 1.f);
out.volume = slot.f(SamplerPads::volumeKey(pad).s, SamplerPads::DEFAULT_VOLUME);
return true;
}
if (std::strcmp(type, "SOUNDFONT") == 0) {
const Sample *s = store.get(slot.s("sfSample"));
if (!s) return false;
out = VoiceSample{};
out.sample = s;
out.root = kt::toInt(slot.f("sfRoot", 60.f));
out.sliceStart = 0.f;
out.sliceEnd = 1.f;
out.volume = slot.f("volume", 0.8f);
out.attack = slot.f("attack", 0.005f);
out.decay = slot.f("decay", 0.10f);
out.sustain = slot.f("sustain", 1.f);
out.release = slot.f("release", 0.20f);
out.loop = std::strcmp(slot.s("loop", "Off"), "On") == 0;
out.crossfadeMs = slot.f("loopXfade", 0.f);
return true;
}
return false;
}
// ------------------------------------------------------------- SampleVoice
SampleVoice::SampleVoice(int sr)
: engineSampleRate(sr), declickCoeff(kt::expf_(-1.f / ((float)sr * 0.003f))) {} // ~3 ms decay
SampleVoice::~SampleVoice() { setSample(nullptr); }
void SampleVoice::setSample(const Sample *s) {
if (s == sample) return;
if (s) SampleStore::pin(s);
if (sample) SampleStore::unpin(sample);
sample = s;
}
void SampleVoice::noteOn(const Sample &s, int midi, int velocity, int root,
float sliceStart, float sliceEnd, float volume,
float attack, float decay, float sustain, float release,
bool loop, float crossfadeMs) {
const int len = (int)s.data.size();
// An empty sample would make Kotlin's coerceIn(startIndex + 1, 0) throw; play nothing.
if (len <= 0) return;
// Carry the level we're interrupting so the new note starts continuously.
declick += lastY;
setSample(&s);
pitch = midi;
const float a = kt::coerceIn(sliceStart, 0.f, 1.f);
const float b = kt::coerceIn(sliceEnd, 0.f, 1.f);
startIndex = kt::coerceIn(kt::toInt(minOf(a, b) * (float)len), 0, kt::coerceAtLeast(len - 1, 0));
endIndex = kt::coerceIn(kt::toInt(maxOf(a, b) * (float)len), startIndex + 1, len);
position = (double)startIndex;
// Loop region: prefer the file's loop points (clamped into the played slice);
// otherwise loop the whole slice. Disabled if the resulting span is too short.
if (loop) {
const int fileLs = s.loopStart;
const int fileLe = s.loopEnd;
if (fileLe > fileLs && fileLs >= 0 && fileLe <= len) {
loopStartIdx = kt::coerceIn(fileLs, startIndex, endIndex - 1);
loopEndIdx = kt::coerceIn(fileLe, loopStartIdx + 1, endIndex);
} else {
loopStartIdx = startIndex;
loopEndIdx = endIndex;
}
loopSpan = (double)(loopEndIdx - loopStartIdx);
loopActive = loopSpan >= 2.0;
// Crossfade length in samples, kept under half the loop.
const double xf = loopActive ? (double)(crossfadeMs / 1000.f * (float)engineSampleRate) : 0.0;
xfade = (loopActive && loopSpan >= 4.0) ? kt::coerceIn(xf, 0.0, loopSpan / 2.0 - 1.0) : 0.0;
loopBase = loopStartIdx + xfade;
loopEff = loopSpan - xfade;
} else {
loopActive = false;
xfade = 0.0;
}
// Pitch ratio * sample-rate conversion.
const double semis = (midi - root) / 12.0;
rate = std::pow(2.0, semis) * ((double)s.sampleRate / engineSampleRate);
amp = kt::coerceIn((float)velocity / 127.f, 0.f, 1.f) * volume;
// Envelope: enforce a tiny minimum attack so the onset never clicks.
const float sr = (float)engineSampleRate;
sustainLevel = kt::coerceIn(sustain, 0.f, 1.f);
attackInc = 1.f / (maxOf(attack, MIN_ATTACK) * sr);
decayInc = decay <= 0.f ? 1.f : (1.f - sustainLevel) / (decay * sr);
releaseSeconds = release;
env = 0.f;
phase = Phase::ATTACK;
endGain = 1.f;
}
void SampleVoice::noteOff() {
const float sr = (float)engineSampleRate;
releaseInc = releaseSeconds <= 0.f ? 1.f : env / (releaseSeconds * sr);
if (releaseInc <= 0.f) releaseInc = 1.f;
phase = Phase::RELEASE;
}
void SampleVoice::kill() {
setSample(nullptr); pitch = -1; ownerTrack = -1; env = 0.f; endGain = 1.f;
lastY = 0.f; declick = 0.f; loopActive = false;
}
float SampleVoice::declickTail() {
if (declick == 0.f) { lastY = 0.f; return 0.f; }
const float y = declick;
declick *= declickCoeff;
if (declick < 1e-5f && declick > -1e-5f) declick = 0.f;
lastY = y;
return y;
}
float SampleVoice::render() {
const Sample *s = sample;
if (!s) return declickTail(); // idle -> 0; ring out any declick tail
const float *data = s->data.data();
const int size = (int)s->data.size();
if (loopActive) {
// Wrap the (crossfaded) loop; modulo so a very high rate still lands inside.
if (position >= loopEndIdx) position = loopBase + std::fmod(position - loopBase, loopEff);
// Bounds guard so a malformed loop can never read out of bounds.
if (position >= size - 1 || position < loopStartIdx) position = loopBase;
} else {
const int i = toInt(position);
if (i >= endIndex - 1 || i >= size - 1) { setSample(nullptr); pitch = -1; return declickTail(); }
// Anti-click fade as the slice end approaches (in OUTPUT samples).
if ((endIndex - i) / rate <= FADE_SAMPLES) {
endGain = kt::coerceAtLeast(endGain - FADE_STEP, 0.f);
if (endGain <= 0.f) { setSample(nullptr); pitch = -1; return declickTail(); }
}
}
// Advance the ADSR envelope one output sample.
switch (phase) {
case Phase::ATTACK: env += attackInc; if (env >= 1.f) { env = 1.f; phase = Phase::DECAY; } break;
case Phase::DECAY: env -= decayInc; if (env <= sustainLevel) { env = sustainLevel; phase = Phase::SUSTAIN; } break;
case Phase::SUSTAIN: break;
case Phase::RELEASE: env -= releaseInc; if (env <= 0.f) { setSample(nullptr); pitch = -1; return declickTail(); } break;
}
// Linear interpolation between neighbouring samples (neighbour clamped).
const int i = toInt(position);
const int i1 = i + 1 < size ? i + 1 : i;
const float frac = (float)(position - i);
float out = data[i] + (data[i1] - data[i]) * frac;
// In the crossfade zone, blend the loop tail into its head (reads only within
// [loopStartIdx, loopEndIdx)).
if (loopActive && xfade >= 1.0 && position >= loopEndIdx - xfade) {
const double into = position - (loopEndIdx - xfade); // 0 ... xfade
const float f = (float)(into / xfade); // 0 -> 1 across the zone
const double sp = loopStartIdx + into; // matching head position
const int si = toInt(sp);
const int si1 = si + 1 < size ? si + 1 : si;
const float sfrac = (float)(sp - si);
const float head = data[si] + (data[si1] - data[si]) * sfrac;
out = out * (1.f - f) + head * f;
}
position += rate;
const float y = out * amp * env * endGain + declick;
declick *= declickCoeff;
lastY = y;
return y;
}
} // namespace sizzle::sampler
+146
View File
@@ -0,0 +1,146 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of SampleVoice.kt (the pitched one-shot / looping sample voice of the
// Sampler and SoundFont instruments), AudioEngine.voiceSample() (which sample a
// note plays and how) and SamplerPads (model/Toolbox.kt).
#include "SampleStore.hpp"
#include "sizzle/Params.hpp"
#include "sizzle/Sample.hpp"
namespace sizzle::sampler {
/** SamplerPads: pad n plays MIDI note BASE_NOTE + n; its settings live under
* "pad<n>" (sample id), "pad<n>S"/"pad<n>E" (slice start/end), "pad<n>V" (volume). */
namespace SamplerPads {
inline constexpr int COUNT = 16;
inline constexpr int BASE_NOTE = 36; // C2 (this app uses MIDI 60 == C4)
inline constexpr float DEFAULT_VOLUME = 0.8f;
/** A key built on the stack (no allocation): use `.s`. */
struct Key { char s[16]; };
inline Key make(int pad, char suffix) { // "pad" + decimal pad + suffix, hand-built (no printf on the audio thread)
Key k{};
int n = 0;
k.s[n++] = 'p'; k.s[n++] = 'a'; k.s[n++] = 'd';
unsigned u = pad < 0 ? 0u - (unsigned)pad : (unsigned)pad;
if (pad < 0) k.s[n++] = '-';
char digits[10];
int d = 0;
do { digits[d++] = (char)('0' + u % 10); u /= 10; } while (u != 0);
while (d > 0) k.s[n++] = digits[--d];
if (suffix) k.s[n++] = suffix;
k.s[n] = '\0';
return k;
}
inline Key key(int pad) { return make(pad, 0); }
inline Key sliceStartKey(int pad) { return make(pad, 'S'); }
inline Key sliceEndKey(int pad) { return make(pad, 'E'); }
inline Key volumeKey(int pad) { return make(pad, 'V'); }
/** The MIDI note a pad triggers, and the inverse. */
inline int noteFor(int pad) { return BASE_NOTE + pad; }
inline int padFor(int note) { return note - BASE_NOTE; }
} // namespace SamplerPads
/** AudioEngine.VoiceSample: what SampleVoice::noteOn plays for a note. */
struct VoiceSample {
const Sample *sample = nullptr;
int root = 60;
float sliceStart = 0.f, sliceEnd = 1.f, volume = 0.8f;
float attack = 0.002f, decay = 0.f;
float sustain = 1.f, release = 0.02f;
bool loop = false;
float crossfadeMs = 0.f;
};
/**
* AudioEngine.voiceSample(): the sample [note] plays on a slot of [type] ("SAMPLER":
* the pad the note maps to, root == note so it plays unpitched, one-shot envelope;
* "SOUNDFONT": sfSample at sfRoot with the slot's envelope and loop). False when the
* slot isn't a loaded sample instrument (the engine then uses the synth).
* Audio-thread safe: no allocation, no locks.
*/
bool voiceSample(const char *type, const Params &slot, const SampleStore &store, int note, VoiceSample &out);
/**
* Plays a Sample as a pitched voice: the note's distance from the root sets the
* playback rate, the slice bounds the region, a linear ADSR shapes it, a SoundFont
* can sustain-loop with a crossfaded seam. render() / noteOn() don't allocate.
*
* The voice pins the sample it plays (Sample::users) from noteOn until it lets go,
* so SampleStore never frees a sample still playing.
*/
class SampleVoice {
public:
explicit SampleVoice(int engineSampleRate);
~SampleVoice();
SampleVoice(const SampleVoice &) = delete;
SampleVoice &operator=(const SampleVoice &) = delete;
int pitch = -1;
/** Which tracker (lane,track) started this voice, or -1 if unowned. */
int ownerTrack = -1;
bool isActive() const { return sample != nullptr; }
/** Note is still held (not in its release stage). */
bool isGated() const { return sample != nullptr && phase != Phase::RELEASE; }
/**
* [root]: MIDI note at which the sample plays at its natural pitch;
* [sliceStart]/[sliceEnd]: 0..1 fractions of the sample to play; [volume] 0..1;
* [attack]/[decay]/[release] in seconds; [sustain] level 0..1.
*/
void noteOn(const Sample &s, int midi, int velocity, int root,
float sliceStart, float sliceEnd, float volume,
float attack = 0.002f, float decay = 0.f, float sustain = 1.f, float release = 0.02f,
bool loop = false, float crossfadeMs = 0.f);
void noteOn(const VoiceSample &v, int midi, int velocity) {
if (v.sample) noteOn(*v.sample, midi, velocity, v.root, v.sliceStart, v.sliceEnd, v.volume,
v.attack, v.decay, v.sustain, v.release, v.loop, v.crossfadeMs);
}
/** Enter the release stage: fade from the current level to 0 over the release time. */
void noteOff();
void kill();
float render();
private:
enum class Phase { ATTACK, DECAY, SUSTAIN, RELEASE };
void setSample(const Sample *s); // sample = s, moving the pin
float declickTail();
const int engineSampleRate;
const Sample *sample = nullptr;
double position = 0.0; // fractional read index into sample->data
double rate = 1.0; // samples advanced per output sample
int startIndex = 0;
int endIndex = 0;
float amp = 0.f;
bool loopActive = false;
int loopStartIdx = 0;
int loopEndIdx = 0;
double loopSpan = 0.0;
double xfade = 0.0;
double loopBase = 0.0;
double loopEff = 0.0;
Phase phase = Phase::ATTACK;
float env = 0.f;
float attackInc = 1.f;
float decayInc = 1.f;
float sustainLevel = 1.f;
float releaseSeconds = 0.02f;
float releaseInc = 1.f;
float endGain = 1.f;
float lastY = 0.f;
float declick = 0.f;
const float declickCoeff;
};
} // namespace sizzle::sampler
+188
View File
@@ -0,0 +1,188 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of SoundFontLoader.kt, line for line. Kotlin's runCatching turns any
// ByteBuffer exception into null; here each read that could throw is checked first
// and returns nothing instead. Positions are int64 where the Kotlin resolves in Long.
#include "SoundFontLoader.hpp"
#include <algorithm>
#include <cstring>
#include <vector>
#include "SampleStore.hpp"
#if defined(__clang__)
#pragma clang fp contract(off) // Java never fuses multiply-adds
#endif
namespace sizzle::sampler::SoundFontLoader {
namespace {
constexpr int SHDR_REC = 46;
inline bool tagAt(const uint8_t *b, int64_t size, int64_t off, const char *t) {
return off >= 0 && off + 4 <= size && std::memcmp(b + off, t, 4) == 0;
}
inline int32_t i32(const uint8_t *p) {
return (int32_t)((uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24));
}
inline int u16(const uint8_t *b, int64_t off) { return (int)b[off] | ((int)b[off + 1] << 8); }
inline int64_t u32(const uint8_t *b, int64_t off) { return (int64_t)(uint32_t)i32(b + off); }
// ------------------------------------------------------------------- SF2
bool looksLikeSf2(const uint8_t *b, int64_t n) {
return n > 12 && tagAt(b, n, 0, "RIFF") && tagAt(b, n, 8, "sfbk");
}
std::optional<Loaded> loadSf2(const uint8_t *bytes, int64_t limit) {
int64_t pos = 0;
if (!tagAt(bytes, limit, pos, "RIFF")) return std::nullopt;
pos += 4;
pos += 4; // riff size
if (!tagAt(bytes, limit, pos, "sfbk")) return std::nullopt;
pos += 4;
int64_t smplOff = -1, shdrOff = -1;
int32_t shdrBytes = 0;
// RIFF chunk walk over attacker-controlled sizes; every seek is forced FORWARD
// (a negative or small size would otherwise loop forever).
while (limit - pos >= 8) {
const int64_t chunkStart = pos;
const uint8_t *id = bytes + pos;
const int32_t size = i32(bytes + pos + 4);
pos += 8;
if (size < 0) break; // a size that cannot be honoured ends the walk
const int64_t chunkEnd = std::min(pos + (int64_t)size, limit);
if (std::memcmp(id, "LIST", 4) == 0 && limit - pos >= 4) {
const uint8_t *listType = bytes + pos;
pos += 4;
while (pos + 8 <= chunkEnd) {
const int64_t subStart = pos;
const uint8_t *sid = bytes + pos;
const int32_t ssize = i32(bytes + pos + 4);
pos += 8;
if (ssize < 0) break;
const int64_t dataPos = pos;
if (std::memcmp(listType, "sdta", 4) == 0 && std::memcmp(sid, "smpl", 4) == 0) smplOff = dataPos;
if (std::memcmp(listType, "pdta", 4) == 0 && std::memcmp(sid, "shdr", 4) == 0) { shdrOff = dataPos; shdrBytes = ssize; }
const int64_t next = std::clamp(dataPos + ssize + (ssize & 1), (int64_t)0, limit);
if (next <= subStart) break; // no forward progress
pos = next;
}
}
const int64_t next = std::clamp(chunkEnd + (size & 1), (int64_t)0, limit);
if (next <= chunkStart) break; // no forward progress
pos = next;
}
if (smplOff < 0 || shdrOff < 0 || shdrBytes < SHDR_REC) return std::nullopt;
// First sample header record (46 bytes): 20-byte name, then the fields. The
// chunk may claim more bytes than the file has: the Kotlin's reads would throw.
const int64_t h = shdrOff + 20;
if (h + 21 > limit) return std::nullopt;
const int64_t start = u32(bytes, h);
const int64_t end = u32(bytes, h + 4);
const int64_t startLoop = u32(bytes, h + 8);
const int64_t endLoop = u32(bytes, h + 12);
const int32_t sampleRate = i32(bytes + h + 16);
const int originalKey = bytes[h + 20];
if (end <= start) return std::nullopt;
// Coerce the span as a Long before narrowing (a huge header can't overflow).
const int frames = (int)std::clamp(end - start, (int64_t)0, (int64_t)MAX_FRAMES);
if (frames <= 0) return std::nullopt;
std::vector<float> out((size_t)frames);
// start is a 32-bit unsigned frame index: resolve the offset in 64 bits.
const int64_t readAt = std::clamp(smplOff + start * 2, (int64_t)0, limit);
int64_t db = readAt;
int i = 0;
while (i < frames && limit - db >= 2) {
out[(size_t)i] = (float)(int16_t)(uint16_t)u16(bytes, db) / 32768.f;
db += 2;
i++;
}
const int root = (originalKey >= 1 && originalKey <= 127) ? originalKey : 60;
const int rate = (sampleRate >= 8000 && sampleRate <= 192000) ? sampleRate : 44100;
// Loop points are absolute (same base as start/end): make them relative to the
// extracted region and keep only if they fall inside it.
const int64_t lsRel = startLoop - start;
const int64_t leRel = endLoop - start;
const int loopS = (leRel > lsRel && lsRel >= 0 && leRel <= frames) ? (int)lsRel : -1;
const int loopE = loopS >= 0 ? (int)leRel : -1;
return Loaded{Sample(std::move(out), rate, loopS, loopE), root};
}
// -------------------------------------------------------------------- XI
bool looksLikeXi(const uint8_t *b, int64_t n) {
return n > 300 && std::memcmp(b, "Extended Instru", 15) == 0;
}
std::optional<Loaded> loadXi(const uint8_t *bytes, int64_t size) {
// Fixed XI header layout: number-of-samples word at 296, first 40-byte sample
// header at 298, then delta-encoded sample data after all headers.
const int numSamples = u16(bytes, 296);
if (numSamples < 1) return std::nullopt;
const int hp = 298;
if (hp + 40 > size) return std::nullopt;
const int32_t length = (int32_t)u32(bytes, hp); // sample length in bytes (toInt wraps)
const int type = bytes[hp + 14];
const int relativeNote = (int8_t)bytes[hp + 16]; // signed
const bool is16 = (type & 0x10) != 0;
const int dataStart = hp + numSamples * 40;
if (length <= 0 || dataStart >= size) return std::nullopt;
const int32_t byteLen = (int32_t)std::min((int64_t)length, size - dataStart);
const int div = is16 ? 2 : 1;
const int32_t n = std::min(byteLen / div, (int32_t)MAX_FRAMES);
if (n <= 0) return std::nullopt;
std::vector<float> out((size_t)n);
if (is16) {
int old = 0;
for (int32_t k = 0; k < n; ++k) {
const int16_t d = (int16_t)(uint16_t)u16(bytes, (int64_t)dataStart + 2 * (int64_t)k);
old = (old + d) & 0xFFFF;
out[(size_t)k] = (float)(int16_t)(uint16_t)old / 32768.f;
}
} else {
int old = 0;
for (int32_t k = 0; k < n; ++k) {
old = (old + (int8_t)bytes[dataStart + k]) & 0xFF;
out[(size_t)k] = (float)(int8_t)(uint8_t)old / 128.f;
}
}
// Loop info: type bits 0-1 (0 none, 1 forward, 2 ping-pong); loopStart/loopLen
// are byte offsets (halved for 16-bit). Ping-pong is treated as forward.
const int loopType = type & 0x03;
const int32_t loopStartB = (int32_t)u32(bytes, hp + 4);
const int32_t loopLenB = (int32_t)u32(bytes, hp + 8);
int loopS = -1;
int loopE = -1;
if (loopType != 0 && loopLenB > 0 && loopStartB >= 0) {
const int32_t ls = loopStartB / div;
const int32_t le = (int32_t)((uint32_t)loopStartB + (uint32_t)loopLenB) / div; // Int wraps
if (ls >= 0 && ls < n && le >= ls + 1 && le <= n) { loopS = ls; loopE = le; }
}
// XI/XM samples have no stored rate; C-4 plays at 8363 Hz by convention.
// root = 60 - relativeNote, so that note plays the sample's natural pitch.
const int root = std::clamp(60 - relativeNote, 0, 127);
return Loaded{Sample(std::move(out), 8363, loopS, loopE), root};
}
} // namespace
std::optional<Loaded> load(const uint8_t *bytes, size_t size) {
if (bytes == nullptr || size > 0x7FFFFFFF) return std::nullopt; // a Kotlin ByteArray's limit
const int64_t n = (int64_t)size;
if (looksLikeSf2(bytes, n)) return loadSf2(bytes, n);
if (looksLikeXi(bytes, n)) return loadXi(bytes, n);
if (auto s = SampleStore::decodeWav(bytes, size)) return Loaded{std::move(*s), 60};
return std::nullopt;
}
} // namespace sizzle::sampler::SoundFontLoader
+28
View File
@@ -0,0 +1,28 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of SoundFontLoader.kt: a SoundFont (.sf2) or FastTracker II instrument (.xi)
// file -> its first sample, root note and loop points. A plain WAV is accepted too
// (root 60). The bytes are untrusted: every read is bounds-checked and sizes are
// capped (MAX_FRAMES) as in the Kotlin. Runs on a loader thread (allocates).
#include <cstddef>
#include <cstdint>
#include <optional>
#include "sizzle/Sample.hpp"
namespace sizzle::sampler::SoundFontLoader {
struct Loaded {
Sample sample;
int rootNote = 60;
};
/** Frames cap so a pathologically large sample region can't exhaust memory. */
inline constexpr int MAX_FRAMES = 48000 * 30;
/** The file's sample, or nothing if the bytes are not a format we understand. */
std::optional<Loaded> load(const uint8_t *bytes, size_t size);
} // namespace sizzle::sampler::SoundFontLoader
+48
View File
@@ -0,0 +1,48 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of model/SynthDefs.kt: the option lists the subtractive synth's slot
// values are written with, and its shape constants.
#include <cstring>
namespace sizzle::synth::defs {
/** Oscillator waveforms. */
constexpr const char *WAVES[] = {"Tri", "Saw", "Square", "Pulse25", "Pulse12"};
constexpr int WAVES_COUNT = 5;
/** LFO waveforms. */
constexpr const char *LFO_WAVES[] = {"Tri", "Saw", "Square", "Sine", "S&H"};
constexpr int LFO_WAVES_COUNT = 5;
/** LFO start-phase offsets, eight 45-degree steps. */
constexpr const char *LFO_PHASES[] = {"0°", "45°", "90°", "135°", "180°", "225°", "270°", "315°"};
constexpr int LFO_PHASES_COUNT = 8;
/** Modulation-matrix sources; index 0 ("Off") disables the slot. */
constexpr const char *MOD_SRC[] = {"Off", "LFO", "FiltEnv", "AmpEnv", "Vel", "KeyTrk"};
constexpr int MOD_SRC_COUNT = 6;
/** Modulation-matrix destinations. */
constexpr const char *MOD_DST[] = {"Pitch", "Osc2", "Osc3", "Cutoff", "PWM", "Amp"};
constexpr int MOD_DST_COUNT = 6;
constexpr int OSC_COUNT = 3;
constexpr int MOD_SLOTS = 4;
/** Init-patch oscillator waveforms (per oscillator). */
constexpr const char *DEF_OSC_WAVE[OSC_COUNT] = {"Saw", "Square", "Tri"};
/** Init-patch oscillator mixer levels (only oscillator 1 audible by default). */
constexpr float DEF_OSC_LEVEL[OSC_COUNT] = {0.9f, 0.f, 0.f};
/** List.indexOf: -1 when absent. */
inline int indexOf(const char *const *list, int n, const char *v) {
for (int i = 0; i < n; ++i) if (std::strcmp(list[i], v) == 0) return i;
return -1;
}
/** A LFO_PHASES label as a fraction of one LFO cycle (0..1). */
inline float lfoPhaseFraction(const char *label) {
int i = indexOf(LFO_PHASES, LFO_PHASES_COUNT, label);
return i < 0 ? 0.f : (float)i / (float)LFO_PHASES_COUNT;
}
} // namespace sizzle::synth::defs
+100
View File
@@ -0,0 +1,100 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of SynthPatch.kt, line for line.
#include <atomic>
#include <cstdio>
#include "synth/SynthPatch.hpp"
#include "KotlinMath.hpp"
#include "model/TimeDivision.hpp"
#include "sizzle/Params.hpp"
#if defined(__clang__)
#pragma clang fp contract(off) // Java never fuses multiply-adds
#endif
namespace sizzle::synth {
namespace {
std::atomic<uint32_t> nextId{1};
int idx(int i) { return i < 0 ? 0 : i; }
int waveIndex(const char *s) { return idx(defs::indexOf(defs::WAVES, defs::WAVES_COUNT, s)); }
int lfoWaveIndex(const char *s) { return idx(defs::indexOf(defs::LFO_WAVES, defs::LFO_WAVES_COUNT, s)); }
int srcIndex(const char *s) { return idx(defs::indexOf(defs::MOD_SRC, defs::MOD_SRC_COUNT, s)); }
int dstIndex(const char *s) { return idx(defs::indexOf(defs::MOD_DST, defs::MOD_DST_COUNT, s)); }
} // namespace
SynthPatch SynthPatch::from(const Params *slot, float tempoBpm) {
auto f = [&](const char *k, float d) { return slot ? slot->f(k, d) : d; };
auto s = [&](const char *k, const char *d) { return slot ? slot->s(k, d) : d; };
char key[16];
SynthPatch p;
for (int i = 0; i < OSC_COUNT; ++i) {
std::snprintf(key, sizeof key, "osc%dwave", i);
p.oscWave[i] = waveIndex(s(key, defs::DEF_OSC_WAVE[i]));
std::snprintf(key, sizeof key, "osc%doct", i);
p.oscOct[i] = kt::coerceIn(kt::toInt(f(key, 0.f)), -2, 2);
std::snprintf(key, sizeof key, "osc%dsemi", i);
p.oscSemi[i] = kt::coerceIn(kt::toInt(f(key, 0.f)), -12, 12);
std::snprintf(key, sizeof key, "osc%dfine", i);
p.oscFine[i] = kt::coerceIn(f(key, 0.f), -50.f, 50.f);
std::snprintf(key, sizeof key, "osc%dlevel", i);
p.oscLevel[i] = kt::coerceIn(f(key, defs::DEF_OSC_LEVEL[i]), 0.f, 1.f);
}
int divIdx = kt::toInt(f("lfodiv", 3.f));
float beatFraction = (float)model::beatFraction(model::fromIndex(divIdx));
p.lfoHz = beatFraction > 0.f ? (tempoBpm / 60.f) / beatFraction : 2.f;
for (int n = 0; n < MOD_SLOTS; ++n) {
std::snprintf(key, sizeof key, "m%dsrc", n);
p.modSrc[n] = srcIndex(s(key, "Off"));
std::snprintf(key, sizeof key, "m%ddst", n);
p.modDst[n] = dstIndex(s(key, "Cutoff"));
std::snprintf(key, sizeof key, "m%damt", n);
p.modAmt[n] = kt::coerceIn(f(key, 0.f), -1.f, 1.f);
}
p.noiseLevel = kt::coerceIn(f("noise", 0.f), 0.f, 1.f);
p.cutoff = kt::coerceIn(f("cutoff", 0.55f), 0.f, 1.f);
p.resonance = kt::coerceIn(f("reso", 0.15f), 0.f, 1.f);
p.keytrack = kt::coerceIn(f("keytrack", 0.3f), 0.f, 1.f);
p.filterEnvAmt = kt::coerceIn(f("fenvamt", 0.4f), -1.f, 1.f);
p.fA = f("fatk", 0.005f); p.fD = f("fdec", 0.25f);
p.fS = f("fsus", 0.4f); p.fR = f("frel", 0.2f);
p.aA = f("attack", 0.005f); p.aD = f("decay", 0.2f);
p.aS = f("sustain", 0.7f); p.aR = f("release", 0.2f);
p.lfoWave = lfoWaveIndex(s("lfowave", "Tri"));
// Absent in presets saved before the phase control existed: the default label, 0.
p.lfoPhase = defs::lfoPhaseFraction(s("lfophase", defs::LFO_PHASES[0]));
p.kind = Kind::SYNTH;
p.id = nextId.fetch_add(1, std::memory_order_relaxed);
return p;
}
const SynthPatch &SynthPatch::defaults() {
static const SynthPatch d = from(nullptr, 120.f);
return d;
}
SynthPatch SynthPatch::forPad(const frasil::FrasilPatch &pad) {
SynthPatch p = defaults();
p.kind = Kind::PAD;
p.pad = pad;
p.id = nextId.fetch_add(1, std::memory_order_relaxed);
return p;
}
SynthPatch SynthPatch::forWave(const wavetable::WavePatch &wave) {
SynthPatch p = defaults();
p.kind = Kind::WAVE;
p.wave = wave;
p.id = nextId.fetch_add(1, std::memory_order_relaxed);
return p;
}
} // namespace sizzle::synth
+68
View File
@@ -0,0 +1,68 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of audio/SynthPatch.kt: every parameter of the subtractive synth voice,
// parsed once from a slot. A fixed-size copyable value (no heap). Kotlin's nullable
// `pad` / `wave` fields become [kind] plus the patch value.
#include <cstdint>
#include "frasil/FrasilVoice.hpp"
#include "synth/SynthDefs.hpp"
#include "wavetable/WaveVoice.hpp"
namespace sizzle {
class Params;
}
namespace sizzle::synth {
struct SynthPatch {
static constexpr int OSC_COUNT = defs::OSC_COUNT;
static constexpr int MOD_SLOTS = defs::MOD_SLOTS;
/** Which engine plays the note: Kotlin's pad != null / wave != null. */
enum class Kind : uint8_t { SYNTH, PAD, WAVE };
// ---- oscillators (index 0..2) ----
int oscWave[OSC_COUNT] = {}; // index into WAVES
int oscOct[OSC_COUNT] = {}; // octave transpose, -2..+2
int oscSemi[OSC_COUNT] = {}; // semitone detune, -12..+12
float oscFine[OSC_COUNT] = {}; // fine detune in cents, -50..+50
float oscLevel[OSC_COUNT] = {}; // mixer level, 0..1
float noiseLevel = 0.f;
// ---- filter ----
float cutoff = 0.f, resonance = 0.f, keytrack = 0.f, filterEnvAmt = 0.f;
float fA = 0.f, fD = 0.f, fS = 0.f, fR = 0.f;
// ---- amplifier ----
float aA = 0.f, aD = 0.f, aS = 0.f, aR = 0.f;
// ---- LFO ----
int lfoWave = 0;
float lfoHz = 0.f; // tempo-synced rate
float lfoPhase = 0.f; // start-phase offset, 0..1
// ---- modulation matrix ----
int modSrc[MOD_SLOTS] = {}; // index into MOD_SRC (0 == Off)
int modDst[MOD_SLOTS] = {}; // index into MOD_DST
float modAmt[MOD_SLOTS] = {}; // -1..1
Kind kind = Kind::SYNTH;
/** Valid when kind == PAD (the subtractive fields above are then unused). */
frasil::FrasilPatch pad{};
/** Valid when kind == WAVE. */
wavetable::WavePatch wave{};
/** Stands in for Kotlin's object identity (SynthVoice.setPatch's `p === patch`):
* stamped by each factory below, kept by copies. */
uint32_t id = 0;
/** SynthPatch.from(slot, tempoBpm); [slot] may be null (init patch). */
static SynthPatch from(const Params *slot, float tempoBpm);
/** SynthPatch.DEFAULT: from(null, 120). */
static const SynthPatch &defaults();
/** A Morph Pad patch: the default synth fields, carrying [pad]. */
static SynthPatch forPad(const frasil::FrasilPatch &pad);
/** A Wavetable patch: the default synth fields, carrying [wave]. */
static SynthPatch forWave(const wavetable::WavePatch &wave);
};
} // namespace sizzle::synth
+60
View File
@@ -0,0 +1,60 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// The reference tests' SYNTH maker (see TestVoice.hpp, IosGoldenInstruments.kt):
// a SynthVoice with the patch the engine builds for the slot's type.
#include <cstring>
#include "frasil/FrasilVoice.hpp"
#include "sizzle/TestVoice.hpp"
#include "synth/SynthVoice.hpp"
#include "wavetable/WaveTables.hpp"
namespace sizzle {
namespace {
using frasil::FrasilClock;
using frasil::FrasilSeeds;
using synth::SynthPatch;
using synth::SynthVoice;
SynthPatch enginePatch(const TestVoiceSetup &s) {
if (std::strcmp(s.type, "NES_SYNTH") == 0) return SynthPatch::from(s.params, s.tempoBpm);
if (std::strcmp(s.type, "MORPH_PAD") == 0) return SynthPatch::forPad(frasil::FrasilPatch::from(s.params));
if (std::strcmp(s.type, "WAVETABLE") == 0)
return SynthPatch::forWave(wavetable::WavePatch::from(s.params, s.tempoBpm));
return SynthPatch::defaults();
}
FrasilSeeds seedsAt(uint32_t counter) {
FrasilSeeds seeds;
seeds.seeds = counter;
return seeds;
}
class SynthTestVoice final : public TestVoice {
FrasilClock clock;
FrasilSeeds seeds;
SynthPatch patch;
SynthVoice voice;
int sampleRate;
public:
explicit SynthTestVoice(const TestVoiceSetup &s)
: clock{s.clock0}, seeds(seedsAt(s.frasilSeeds)), patch(enginePatch(s)),
voice(s.sampleRate, clock, seeds.next()), sampleRate(s.sampleRate) {}
void blockStart(int frames) override { clock.advance(frames, sampleRate); }
void noteOn(int midi, int velocity) override { voice.noteOn(midi, velocity, patch); }
void noteOff(int) override { voice.noteOff(); }
float render() override { return voice.render(); }
};
} // namespace
std::unique_ptr<TestVoice> makeSynthTestVoice(const TestVoiceSetup &setup) {
wavetable::WaveTables::prewarmBlocking();
return std::make_unique<SynthTestVoice>(setup);
}
} // namespace sizzle
+286
View File
@@ -0,0 +1,286 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of SynthVoice.kt, line for line. See the Kotlin for the commentary on the
// sound; comments here are about the port.
#include <cmath>
#include "synth/SynthVoice.hpp"
#include "KotlinMath.hpp"
#if defined(__clang__)
#pragma clang fp contract(off) // Java never fuses multiply-adds
#endif
namespace sizzle::synth {
namespace {
constexpr double PI = 3.141592653589793; // Math.PI
constexpr float OUT_GAIN = 0.5f;
constexpr int CTRL_INTERVAL = 16;
constexpr double AMP_MOD_SMOOTH_SEC = 0.002;
double fastPow2(double x) { return std::pow(2.0, x); }
double fastPow(double base, double x) { return std::pow(base, x); }
} // namespace
// ------------------------------------------------------------------- Adsr ---
void SynthVoice::Adsr::gateOn(float aa, float dd, float ss, float rr) {
a = kt::coerceAtLeast(aa, 0.0005f); d = dd; s = kt::coerceIn(ss, 0.f, 1.f); r = rr;
stage = 1;
}
float SynthVoice::Adsr::advance(float dt) {
switch (stage) {
case 1: level += dt / a; if (level >= 1.f) { level = 1.f; stage = 2; } break;
case 2: level -= dt / kt::coerceAtLeast(d, 0.001f) * (1.f - s); if (level <= s) { level = s; stage = 3; } break;
case 3: break;
case 4: level -= dt / kt::coerceAtLeast(r, 0.001f); if (level <= 0.f) { level = 0.f; stage = 0; } break;
default: break;
}
return level;
}
// ------------------------------------------------------------- SynthVoice ---
SynthVoice::SynthVoice(int sampleRate, const frasil::FrasilClock &clock, int32_t padSeed)
: sampleRate(sampleRate), patch(SynthPatch::defaults()),
ampModCoeff((float)(1.0 - std::exp(-1.0 / (sampleRate * AMP_MOD_SMOOTH_SEC)))),
pad(sampleRate, clock, padSeed), wave(sampleRate) {}
double SynthVoice::midiToHz(int midi) { return 440.0 * std::pow(2.0, (midi - 69) / 12.0); }
bool SynthVoice::isActive() const {
switch (mode) {
case MODE_PAD: return pad.isActive();
case MODE_WAVE: return wave.isActive();
default: return ampEnv.active();
}
}
bool SynthVoice::isGated() const {
switch (mode) {
case MODE_PAD: return pad.isGated();
case MODE_WAVE: return wave.isGated();
default: return ampEnv.gateOpen();
}
}
void SynthVoice::noteOn(int midi, int velocity, const SynthPatch &p) {
const bool hasPad = p.kind == SynthPatch::Kind::PAD;
const bool hasWave = p.kind == SynthPatch::Kind::WAVE;
const int want = hasPad ? MODE_PAD : hasWave ? MODE_WAVE : MODE_SYNTH;
if (want != mode) { // a slot switched kinds: the old engine stops
ampEnv.kill(); filtEnv.kill(); pad.kill(); wave.kill();
mode = want;
}
if (hasPad) {
patch = p;
pitch_ = midi;
pad.noteOn(midi, (float)velocity / 127.f, p.pad);
return;
}
if (hasWave) {
patch = p;
pitch_ = midi;
wave.noteOn(midi, (float)velocity / 127.f, p.wave);
return;
}
patch = p;
pitch_ = midi;
this->velocity = kt::coerceIn((float)velocity / 127.f, 0.f, 1.f);
baseFreq = midiToHz(midi);
keyNorm = kt::coerceIn((float)(midi - 60) / 60.f, -1.f, 1.f);
ampEnv.gateOn(patch.aA, patch.aD, patch.aS, patch.aR);
filtEnv.gateOn(patch.fA, patch.fD, patch.fS, patch.fR);
lfoInc = (double)patch.lfoHz / sampleRate;
lfoPhase = 0.0;
ctrl = 0;
ampModPrimed = false;
computeTuning();
}
void SynthVoice::noteOff() {
switch (mode) {
case MODE_PAD: pad.noteOff(); break;
case MODE_WAVE: wave.noteOff(); break;
default: ampEnv.gateOff(); filtEnv.gateOff(); break;
}
}
void SynthVoice::kill() {
ampEnv.kill(); filtEnv.kill();
pad.kill();
wave.kill();
pitch_ = -1;
ownerTrack = -1;
icB = 0.f; icL = 0.f;
}
void SynthVoice::setPatch(const SynthPatch &p) {
if (p.id == patch.id) return;
const bool hasPad = p.kind == SynthPatch::Kind::PAD;
const bool hasWave = p.kind == SynthPatch::Kind::WAVE;
if (mode != MODE_SYNTH || hasPad || hasWave) {
// Only within the same kind; a slot switched kinds takes effect on the next note.
if (mode == MODE_PAD && hasPad) { patch = p; pad.setPatch(p.pad); }
if (mode == MODE_WAVE && hasWave) { patch = p; wave.setPatch(p.wave); }
return;
}
patch = p;
lfoInc = (double)p.lfoHz / sampleRate;
computeTuning();
}
void SynthVoice::computeTuning() {
for (int i = 0; i < OSC_COUNT; ++i) {
float semis = (float)patch.oscOct[i] * 12.f + (float)patch.oscSemi[i] + patch.oscFine[i] / 100.f;
staticSemis[i] = semis;
staticInc[i] = kt::coerceIn(baseFreq * fastPow2(semis / 12.0) / sampleRate, 0.0, 0.49);
modInc[i] = staticInc[i];
}
pitchModActive = false;
for (int n = 0; n < MOD_SLOTS; ++n)
if (patch.modSrc[n] != 0 && patch.modDst[n] >= 0 && patch.modDst[n] <= 2) { pitchModActive = true; break; }
}
float SynthVoice::render() {
if (mode == MODE_PAD) return pad.render();
if (mode == MODE_WAVE) return wave.render();
if (!ampEnv.active()) return 0.f;
const float dt = 1.f / (float)sampleRate;
const float ampE = ampEnv.advance(dt);
const float filtE = filtEnv.advance(dt);
// ---- LFO ----
lfoPhase += lfoInc;
if (lfoPhase >= 1.0) { lfoPhase -= 1.0; shValue = nextRand(); }
const float lfo = lfoValue();
// ---- modulation matrix ----
float mPitch = 0.f, mOsc2 = 0.f, mOsc3 = 0.f;
float mCut = 0.f, mPwm = 0.f, mAmp = 0.f;
for (int n = 0; n < MOD_SLOTS; ++n) {
float s;
switch (patch.modSrc[n]) {
case 1: s = lfo; break;
case 2: s = filtE; break;
case 3: s = ampE; break;
case 4: s = velocity; break;
case 5: s = keyNorm; break;
default: continue;
}
const float v = patch.modAmt[n] * s;
switch (patch.modDst[n]) {
case 0: mPitch += v; break;
case 1: mOsc2 += v; break;
case 2: mOsc3 += v; break;
case 3: mCut += v; break;
case 4: mPwm += v; break;
case 5: mAmp += v; break;
default: break;
}
}
// ---- control-rate update ----
if (ctrl <= 0) {
ctrl = CTRL_INTERVAL;
const float e = kt::coerceIn(patch.cutoff + patch.filterEnvAmt * filtE + patch.keytrack * keyNorm + mCut,
0.f, 1.3f);
const double hz = kt::coerceIn(20.0 * fastPow(1000.0, (double)e), 20.0, sampleRate * 0.45);
const float g = (float)std::tan(PI * hz / sampleRate);
const float k = kt::coerceIn(2.f - 1.96f * patch.resonance, 0.05f, 2.f);
ca1 = 1.f / (1.f + g * (g + k)); ca2 = g * ca1; ca3 = g * ca2;
if (pitchModActive) {
for (int i = 0; i < OSC_COUNT; ++i) {
float semis = staticSemis[i] + mPitch * 12.f;
if (i == 1) semis += mOsc2 * 12.f;
if (i == 2) semis += mOsc3 * 12.f;
modInc[i] = kt::coerceIn(baseFreq * fastPow2(semis / 12.0) / sampleRate, 0.0, 0.49);
}
}
}
ctrl--;
// ---- oscillators + noise ----
float mix = 0.f;
for (int i = 0; i < OSC_COUNT; ++i) {
const float level = patch.oscLevel[i];
if (level <= 0.0001f) continue;
const double inc = pitchModActive ? modInc[i] : staticInc[i];
double ph = phase[i] + inc;
if (ph >= 1.0) ph -= 1.0;
phase[i] = ph;
mix += waveform(patch.oscWave[i], ph, inc, mPwm) * level;
}
if (patch.noiseLevel > 0.0001f) mix += nextRand() * patch.noiseLevel;
// ---- filter ----
const float filtered = svf(mix);
// ---- amplifier ----
if (ampModPrimed) ampMod += (mAmp - ampMod) * ampModCoeff;
else { ampMod = mAmp; ampModPrimed = true; }
float a = ampE * velocity * (1.f + ampMod);
if (a < 0.f) a = 0.f;
const float y = filtered * a * OUT_GAIN;
return std::isfinite(y) ? y : 0.f;
}
float SynthVoice::waveform(int w, double t, double dt, float pwm) const {
switch (w) {
case 1: return (float)(2.0 * t - 1.0 - polyBlep(t, dt)); // Saw
case 2: return pulse(t, dt, kt::coerceIn(0.5f + pwm * 0.45f, 0.02f, 0.98f)); // Square
case 3: return pulse(t, dt, kt::coerceIn(0.25f + pwm * 0.45f, 0.02f, 0.98f)); // Pulse 25%
case 4: return pulse(t, dt, kt::coerceIn(0.125f + pwm * 0.45f, 0.02f, 0.98f)); // Pulse 12.5%
default: return (float)(1.0 - 4.0 * std::fabs(t - 0.5)); // Triangle
}
}
float SynthVoice::pulse(double t, double dt, float w) {
double y = t < (double)w ? 1.0 : -1.0;
y += polyBlep(t, dt);
double t2 = t + (1.0 - (double)w);
if (t2 >= 1.0) t2 -= 1.0;
y -= polyBlep(t2, dt);
return (float)y;
}
double SynthVoice::polyBlep(double t, double dt) {
if (dt <= 0.0) return 0.0;
if (t < dt) { double x = t / dt; return x + x - x * x - 1.0; }
if (t > 1.0 - dt) { double x = (t - 1.0) / dt; return x * x + x + x + 1.0; }
return 0.0;
}
float SynthVoice::lfoValue() const {
double p = lfoPhase + (double)patch.lfoPhase;
if (p >= 1.0) p -= 1.0;
switch (patch.lfoWave) {
case 1: return (float)(2.0 * p - 1.0); // Saw
case 2: return p < 0.5 ? 1.f : -1.f; // Square
case 3: return (float)std::sin(2.0 * PI * p); // Sine
case 4: return shValue; // Sample & Hold
default: return (float)(1.0 - 4.0 * std::fabs(p - 0.5)); // Triangle
}
}
float SynthVoice::svf(float input) {
const float v3 = input - icL;
const float v1 = ca1 * icB + ca2 * v3;
const float v2 = icL + ca2 * icB + ca3 * v3;
icB = 2.f * v1 - icB;
icL = 2.f * v2 - icL;
if (!std::isfinite(v2)) { icB = 0.f; icL = 0.f; return 0.f; }
return v2;
}
float SynthVoice::nextRand() {
uint32_t s = rng;
s ^= s << 13; s ^= s >> 17; s ^= s << 5;
rng = s;
return (float)(int32_t)s * 4.656613e-10f; // -1..1
}
} // namespace sizzle::synth
+107
View File
@@ -0,0 +1,107 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of audio/SynthVoice.kt: one note of the subtractive synth, or (for a Morph
// Pad / Wavetable patch) the Frasil / wavetable voice it holds. noteOn, noteOff,
// setPatch and render never allocate or lock.
#include <cstdint>
#include "frasil/FrasilVoice.hpp"
#include "synth/SynthPatch.hpp"
#include "wavetable/WaveVoice.hpp"
namespace sizzle::synth {
class SynthVoice {
public:
/** [clock] must outlive the voice; [padSeed] is the next seed of the engine's
* FrasilSeeds (Kotlin's FrasilVoice(sampleRate) inside the SynthVoice takes it). */
SynthVoice(int sampleRate, const frasil::FrasilClock &clock, int32_t padSeed);
int pitch() const { return pitch_; }
/** Which tracker (lane,track) started this voice, or -1 if unowned (live/arp). */
int ownerTrack = -1;
bool isActive() const;
/** Gate still open (attack/decay/sustain): the note is held. */
bool isGated() const;
/** Start (or steal-and-restart) this voice with [patch] (copied). */
void noteOn(int midi, int velocity, const SynthPatch &patch);
void noteOff();
/** Hard stop with no release tail (transport stop / voice steal). */
void kill();
/** Swap in updated params for a still-sounding voice; a patch with the same id
* as the current one is ignored (Kotlin's `p === patch`). */
void setPatch(const SynthPatch &p);
float render();
/** Equal-tempered MIDI note -> Hz (A4 = 69 = 440 Hz). */
static double midiToHz(int midi);
private:
/** Linear ADSR envelope (levels 0..1); level is not reset on gate-on. */
class Adsr {
public:
bool active() const { return stage != 0; }
bool gateOpen() const { return stage >= 1 && stage <= 3; }
void gateOn(float aa, float dd, float ss, float rr);
void gateOff() { if (stage != 0) stage = 4; }
void kill() { stage = 0; level = 0.f; }
float advance(float dt);
private:
int stage = 0; // 0 idle, 1 attack, 2 decay, 3 sustain, 4 release
float level = 0.f;
float a = 0.01f, d = 0.1f, s = 0.7f, r = 0.2f;
};
static constexpr int MODE_SYNTH = 0;
static constexpr int MODE_PAD = 1;
static constexpr int MODE_WAVE = 2;
static constexpr int OSC_COUNT = SynthPatch::OSC_COUNT;
static constexpr int MOD_SLOTS = SynthPatch::MOD_SLOTS;
void computeTuning();
float waveform(int wave, double t, double dt, float pwm) const;
static float pulse(double t, double dt, float w);
static double polyBlep(double t, double dt);
float lfoValue() const;
float svf(float input);
float nextRand();
const int sampleRate;
SynthPatch patch;
int pitch_ = -1;
float velocity = 0.f;
double baseFreq = 440.0;
float keyNorm = 0.f;
double phase[OSC_COUNT] = {};
float staticSemis[OSC_COUNT] = {};
double staticInc[OSC_COUNT] = {};
double modInc[OSC_COUNT] = {};
bool pitchModActive = false;
float icB = 0.f, icL = 0.f;
float ca1 = 0.f, ca2 = 0.f, ca3 = 0.f;
int ctrl = 0;
double lfoPhase = 0.0;
double lfoInc = 0.0;
float shValue = 0.f;
uint32_t rng = 0x2545F491u;
float ampMod = 0.f;
bool ampModPrimed = false;
const float ampModCoeff;
Adsr ampEnv;
Adsr filtEnv;
frasil::FrasilVoice pad;
wavetable::WaveVoice wave;
int mode = MODE_SYNTH;
};
} // namespace sizzle::synth
+79
View File
@@ -0,0 +1,79 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// java.util.Random, bit for bit: the 48-bit LCG and the derivations of
// nextInt / nextInt(bound) / nextLong / nextBoolean / nextFloat / nextDouble /
// nextGaussian as OpenJDK implements them. Seeded factory tables (WaveTables'
// Glass) come out exactly as on Android.
#include <cmath>
#include <cstdint>
namespace sizzle::wavetable {
class JavaRandom {
public:
explicit JavaRandom(int64_t seed) { setSeed(seed); }
void setSeed(int64_t seed) {
seed_ = ((uint64_t)seed ^ MULT) & MASK;
haveNextNextGaussian_ = false;
}
/** Random.next(bits): the top [bits] of the 48-bit state, as a (wrapping) Int. */
int32_t next(int bits) {
seed_ = (seed_ * MULT + ADD) & MASK;
return (int32_t)(uint32_t)(seed_ >> (48 - bits));
}
int32_t nextInt() { return next(32); }
/** nextInt(bound), bound > 0 (Java throws otherwise; here 0 is returned). */
int32_t nextInt(int32_t bound) {
if (bound <= 0) return 0;
int32_t r = next(31);
int32_t m = bound - 1;
if ((bound & m) == 0) {
r = (int32_t)(((int64_t)bound * (int64_t)r) >> 31);
} else {
// for (int u = r; u - (r = u % bound) + m < 0; u = next(31)); with Int wrap
for (int32_t u = r;; u = next(31)) {
r = u % bound;
if ((int32_t)((uint32_t)u - (uint32_t)r + (uint32_t)m) >= 0) break;
}
}
return r;
}
int64_t nextLong() { return (int64_t)((uint64_t)(int64_t)next(32) << 32) + (int64_t)next(32); }
bool nextBoolean() { return next(1) != 0; }
float nextFloat() { return (float)next(24) / (float)(1 << 24); }
double nextDouble() { return (double)(((int64_t)next(26) << 27) + next(27)) * 0x1.0p-53; }
/** Marsaglia polar method with the cached second value. Java uses StrictMath
* (fdlibm) log/sqrt; libm's log may differ by an ulp. */
double nextGaussian() {
if (haveNextNextGaussian_) { haveNextNextGaussian_ = false; return nextNextGaussian_; }
double v1, v2, s;
do {
v1 = 2 * nextDouble() - 1;
v2 = 2 * nextDouble() - 1;
s = v1 * v1 + v2 * v2;
} while (s >= 1 || s == 0);
double multiplier = std::sqrt(-2 * std::log(s) / s);
nextNextGaussian_ = v2 * multiplier;
haveNextNextGaussian_ = true;
return v1 * multiplier;
}
private:
static constexpr uint64_t MULT = 0x5DEECE66DULL;
static constexpr uint64_t ADD = 0xBULL;
static constexpr uint64_t MASK = (1ULL << 48) - 1;
uint64_t seed_ = 0;
double nextNextGaussian_ = 0;
bool haveNextNextGaussian_ = false;
};
} // namespace sizzle::wavetable
+71
View File
@@ -0,0 +1,71 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of WaveDefs.kt (choice lists and factory presets). Preset values are the
// text Kotlin's toString() writes (0.4f -> "0.4", 3 -> "3").
#include "WaveDefs.hpp"
#include "sizzle/Specs.hpp"
namespace sizzle::wavetable::WaveDefs {
const char *const TABLES[TABLE_COUNT] = {
"Classic", "PWM", "Vowels", "Harmonic Sweep", "Sync", "FM",
"Organ", "Fold", "Digital", "Glass", "Odd Even", "Comb", "Custom",
};
const char *const FILTER_TYPES[FILTER_TYPE_COUNT] = {"Low", "Band", "High"};
const char *const LFO_WAVES[LFO_WAVE_COUNT] = {"Sine", "Tri", "Saw", "Square", "S&H"};
const char *const FRAME_SIZES[FRAME_SIZE_COUNT] = {"Auto", "256", "512", "1024", "2048"};
namespace {
const char *const MORPH_LEAD[] = {"o1table", "Classic", "o1pos", "0.4", "menvpos", "0.5", "mattack", "0.01", "mdecay", "0.8", "msustain", "0.2",
"cutoff", "0.8", "reso", "0.25", "lfopitch", "0.15", "lfodiv", "3", "release", "0.25", nullptr};
const char *const VOWEL_PAD[] = {"o1table", "Vowels", "o1pos", "0.0", "o2table", "Vowels", "o2pos", "0.5", "o2level", "0.6", "o2fine", "9.0",
"unison", "3", "spread", "0.4", "attack", "0.8", "release", "2.5", "mattack", "3.0", "mdecay", "4.0", "msustain", "0.7",
"menvpos", "0.6", "lfopos", "0.2", "lfodiv", "0", "cutoff", "0.7", nullptr};
const char *const PWM_STRINGS[] = {"o1table", "PWM", "o1pos", "0.2", "o2table", "PWM", "o2pos", "0.6", "o2level", "0.7", "o2fine", "-8.0",
"unison", "2", "spread", "0.5", "attack", "0.4", "release", "1.2", "lfopos", "0.4", "lfodiv", "1", "menvpos", "0.0",
"cutoff", "0.65", "reso", "0.1", nullptr};
const char *const SYNC_SWEEP[] = {"o1table", "Sync", "o1pos", "0.0", "menvpos", "0.9", "mattack", "0.0", "mdecay", "0.6", "msustain", "0.1",
"cutoff", "0.85", "fenv", "0.3", "decay", "0.5", "sustain", "0.6", "release", "0.2", "drive", "0.3", nullptr};
const char *const FM_BELLS[] = {"o1table", "FM", "o1pos", "0.6", "menvpos", "-0.6", "mattack", "0.0", "mdecay", "1.5", "msustain", "0.0",
"attack", "0.0", "decay", "2.5", "sustain", "0.0", "release", "2.0", "cutoff", "0.9", "keytrack", "0.8", "fenv", "0.0", nullptr};
const char *const GLASS_KEYS[] = {"o1table", "Glass", "o1pos", "0.2", "o2table", "Classic", "o2pos", "0.0", "o2oct", "1", "o2level", "0.3",
"attack", "0.005", "decay", "1.2", "sustain", "0.3", "release", "1.0", "menvpos", "0.4", "mdecay", "1.2", "msustain", "0.2",
"mattack", "0.0", "cutoff", "0.75", nullptr};
const char *const ORGAN_DRIFT[] = {"o1table", "Organ", "o1pos", "0.0", "lfopos", "0.5", "lfodiv", "0", "lfowave", "Tri", "attack", "0.02",
"sustain", "1.0", "release", "0.15", "menvpos", "0.0", "cutoff", "0.9", "reso", "0.0", nullptr};
const char *const FOLD_BASS[] = {"o1table", "Fold", "o1pos", "0.1", "o1oct", "-1", "sub", "0.5", "menvpos", "0.7", "mattack", "0.0",
"mdecay", "0.3", "msustain", "0.0", "attack", "0.0", "decay", "0.4", "sustain", "0.7", "release", "0.15",
"cutoff", "0.55", "fenv", "0.35", "drive", "0.4", nullptr};
const char *const DIGITAL_GRIT[] = {"o1table", "Digital", "o1pos", "0.3", "o2table", "Digital", "o2pos", "0.9", "o2level", "0.5",
"o2semi", "7", "lfopos", "0.6", "lfowave", "S&H", "lfodiv", "4", "menvpos", "0.0", "cutoff", "0.8", "reso", "0.3", nullptr};
const char *const COMB_CHOIR[] = {"o1table", "Comb", "o1pos", "0.0", "unison", "4", "spread", "0.45", "attack", "1.2", "release", "3.0",
"mattack", "6.0", "mdecay", "6.0", "msustain", "1.0", "menvpos", "1.0", "cutoff", "0.7", "lfocut", "0.2", "lfodiv", "0", nullptr};
const char *const ODD_EVEN_PLUCK[] = {"o1table", "Odd Even", "o1pos", "1.0", "menvpos", "-1.0", "mattack", "0.0", "mdecay", "0.5", "msustain", "0.0",
"attack", "0.0", "decay", "0.6", "sustain", "0.0", "release", "0.4", "cutoff", "0.7", "fenv", "0.4", "reso", "0.3", nullptr};
const char *const HARMONIC_RISE[] = {"o1table", "Harmonic Sweep", "o1pos", "0.0", "o2table", "Harmonic Sweep", "o2pos", "0.0", "o2level", "0.6",
"o2fine", "10.0", "unison", "2", "spread", "0.3", "attack", "2.0", "release", "3.0", "mattack", "5.0", "mdecay", "8.0",
"msustain", "1.0", "menvpos", "1.0", "cutoff", "0.85", "reso", "0.05", nullptr};
} // namespace
const Preset FACTORY[FACTORY_COUNT] = {
{"Morph Lead", MORPH_LEAD}, {"Vowel Pad", VOWEL_PAD}, {"PWM Strings", PWM_STRINGS},
{"Sync Sweep", SYNC_SWEEP}, {"FM Bells", FM_BELLS}, {"Glass Keys", GLASS_KEYS},
{"Organ Drift", ORGAN_DRIFT}, {"Fold Bass", FOLD_BASS}, {"Digital Grit", DIGITAL_GRIT},
{"Comb Choir", COMB_CHOIR}, {"Odd Even Pluck", ODD_EVEN_PLUCK}, {"Harmonic Rise", HARMONIC_RISE},
};
void applyPreset(int index, Params &out) {
if (index < 0 || index >= FACTORY_COUNT) return;
if (const DeviceSpec *spec = findDevice("WAVETABLE")) {
for (int i = 0; i < spec->paramCount; ++i) {
const ParamSpec &p = spec->params[i];
if (p.isEnum()) out.set(p.key, p.choices[0]);
else out.set(p.key, p.def);
}
}
for (const char *const *v = FACTORY[index].values; *v; v += 2) out.set(v[0], v[1]);
}
} // namespace sizzle::wavetable::WaveDefs
+37
View File
@@ -0,0 +1,37 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of WaveDefs.kt: the wavetable synth's choice lists and factory presets.
// The parameter definitions themselves (WaveDefs.PARAMS) come generated from the
// Android app: findDevice("WAVETABLE") in DeviceSpecs.gen.hpp.
#include "sizzle/Params.hpp"
namespace sizzle::wavetable::WaveDefs {
/** WaveTables.FACTORY_NAMES + "Custom". */
constexpr int TABLE_COUNT = 13;
extern const char *const TABLES[TABLE_COUNT];
constexpr int FILTER_TYPE_COUNT = 3;
extern const char *const FILTER_TYPES[FILTER_TYPE_COUNT]; // Low, Band, High
constexpr int LFO_WAVE_COUNT = 5;
extern const char *const LFO_WAVES[LFO_WAVE_COUNT]; // Sine, Tri, Saw, Square, S&H
constexpr int FRAME_SIZE_COUNT = 5;
extern const char *const FRAME_SIZES[FRAME_SIZE_COUNT]; // Auto, 256, 512, 1024, 2048
/** A custom table's WAV lives under the SF2/XI loader's keys. */
constexpr const char *SAMPLE_KEY = "sfSample";
/** A factory preset: every parameter at its default (enums at their first
* choice), then [values] (key, value text) on top; nullptr-terminated pairs. */
struct Preset {
const char *name;
const char *const *values; // {"k", "v", "k", "v", ..., nullptr}
};
constexpr int FACTORY_COUNT = 12;
extern const Preset FACTORY[FACTORY_COUNT];
/** Fill [out] with preset [index] as WaveDefs.FACTORY's map would hold it. */
void applyPreset(int index, Params &out);
} // namespace sizzle::wavetable::WaveDefs
+453
View File
@@ -0,0 +1,453 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of WaveTables.kt (and WaveTable): band-limited tables built from spectra,
// an inverse FFT per octave with a taper at the top. Doubles stay doubles.
#include "WaveTables.hpp"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstring>
#include <mutex>
#include <thread>
#include <utility>
#include "JavaRandom.hpp"
#if defined(__clang__)
#pragma clang fp contract(off) // Java never fuses multiply-adds
#endif
namespace sizzle::wavetable {
constexpr int WaveTable::SIZES[WaveTable::LEVELS];
WaveTable::WaveTable(const char *name, int frames_) : frames(frames_) {
std::strncpy(name_, name, sizeof name_ - 1);
name_[sizeof name_ - 1] = '\0';
for (int k = 0; k < LEVELS; ++k) data_[k].assign((size_t)frames_ * SIZES[k], 0.f);
}
namespace WaveTables {
const char *const FACTORY_NAMES[FACTORY_COUNT] = {
"Classic", "PWM", "Vowels", "Harmonic Sweep", "Sync", "FM",
"Organ", "Fold", "Digital", "Glass", "Odd Even", "Comb",
};
namespace {
constexpr int GEN = 4096; // the cycle length the formulas are sampled at
constexpr double PI = 3.141592653589793; // kotlin.math.PI
// Math.max semantics (NaN wins); the inputs here are abs() values.
inline double jmax(double a, double b) { return (a != a) ? a : (a >= b ? a : b); }
inline float jmax(float a, float b) { return (a != a) ? a : (a >= b ? a : b); }
using Spectrum = std::pair<std::vector<float>, std::vector<float>>;
// Tables are never freed (lookups are lock-free from the audio thread).
std::atomic<const WaveTable *> gFactory[FACTORY_COUNT];
std::mutex gBuildMutex;
std::atomic<bool> gStarted{false};
// ------------------------------------------------------------ building ---
/** In-place radix-2 complex FFT; [inverse] uses e^{+i} and no 1/N (the synthesis sum). */
void fft(std::vector<double> &re, std::vector<double> &im, bool inverse) {
int n = (int)re.size();
int j = 0;
for (int i = 1; i < n; ++i) {
int bit = n >> 1;
while ((j & bit) != 0) { j = j ^ bit; bit = bit >> 1; }
j = j ^ bit;
if (i < j) { double t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; }
}
int len = 2;
while (len <= n) {
double ang = 2 * PI / len * (inverse ? 1 : -1);
double wr = std::cos(ang), wi = std::sin(ang);
int i = 0;
while (i < n) {
double cr = 1.0, ci = 0.0;
for (int k = 0; k < len / 2; ++k) {
double ar = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci;
double ai = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr;
re[i + k + len / 2] = re[i + k] - ar; im[i + k + len / 2] = im[i + k] - ai;
re[i + k] += ar; im[i + k] += ai;
double ncr = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = ncr;
}
i += len;
}
len = len << 1;
}
}
/** The top quarter of a level's harmonics fades out (raised cosine). */
double taper(int h, int hk) {
if (hk <= 4) return h <= hk ? 1.0 : 0.0;
double a = 0.75 * hk;
if (h <= a) return 1.0;
if (h > hk) return 0.0;
return 0.5 + 0.5 * std::cos(PI * (h - a) / (hk - a + 1));
}
std::vector<float> resample(const std::vector<float> &x, int n) {
std::vector<float> out(n);
int xs = (int)x.size();
for (int i = 0; i < n; ++i) {
double p = (double)i * xs / n;
int j = (int)p; float fr = (float)(p - j);
out[i] = x[j % xs] + (x[(j + 1) % xs] - x[j % xs]) * fr;
}
return out;
}
/** Harmonics 1..512 of one cycle (any power-of-two length; others are resampled). */
Spectrum spectrum(const std::vector<float> &cycle0) {
unsigned sz = (unsigned)cycle0.size();
bool pow2 = sz != 0 && (sz & (sz - 1)) == 0; // Integer.bitCount(size) == 1
std::vector<float> resampled;
if (!pow2) resampled = resample(cycle0, 2048);
const std::vector<float> &cycle = pow2 ? cycle0 : resampled;
int m = (int)cycle.size();
std::vector<double> re(m), im(m, 0.0);
for (int i = 0; i < m; ++i) re[i] = (double)cycle[i];
fft(re, im, false);
int hn = std::min(WaveTable::MAX_HARMONICS, m / 2 - 1);
std::vector<float> c(WaveTable::MAX_HARMONICS, 0.f), s(WaveTable::MAX_HARMONICS, 0.f);
for (int h = 1; h <= hn; ++h) { c[h - 1] = (float)(2.0 * re[h] / m); s[h - 1] = (float)(-2.0 * im[h] / m); }
return {std::move(c), std::move(s)};
}
/** [spectra]: per frame, cosine and sine amplitudes of harmonics 1..512 (index h-1). */
std::unique_ptr<WaveTable> fromSpectra(const char *name, const std::vector<Spectrum> &spectra) {
int nf = (int)spectra.size();
auto table = std::make_unique<WaveTable>(name, nf);
for (int k = 0; k < WaveTable::LEVELS; ++k) {
int n = WaveTable::SIZES[k];
int hk = WaveTable::harmonics(k);
std::vector<double> re(n), im(n);
float *data = table->data(k);
for (int f = 0; f < nf; ++f) {
const std::vector<float> &c = spectra[f].first;
const std::vector<float> &s = spectra[f].second;
std::fill(re.begin(), re.end(), 0.0); std::fill(im.begin(), im.end(), 0.0);
int hTop = std::min(hk, (int)c.size());
for (int h = 1; h <= hTop; ++h) {
double tp = taper(h, hk);
if (tp <= 0.0) continue;
re[h] = c[h - 1] * tp;
im[h] = -s[h - 1] * tp;
}
fft(re, im, true);
int base = f * n;
for (int i = 0; i < n; ++i) data[base + i] = (float)re[i];
}
}
return table;
}
/** A table from cycles given as time-domain samples ([cycles] of equal power-of-two length). */
std::unique_ptr<WaveTable> fromCycles(const char *name, const std::vector<std::vector<float>> &cycles) {
std::vector<Spectrum> spectra;
spectra.reserve(cycles.size());
for (const auto &c : cycles) spectra.push_back(spectrum(c));
return fromSpectra(name, spectra);
}
// ------------------------------------------------------------- factory ---
double saw(double p) { return 2 * (p - std::floor(p)) - 1; }
double pulse(double p, double w) { return p - std::floor(p) < w ? 1.0 : -1.0; }
double tri(double p) { return 1 - 4 * std::fabs((p - std::floor(p)) - 0.5); }
double sine(double p) { return std::sin(2 * PI * p); }
/** Additive: harmonics 1..n with amplitude a(h), all sine phase. */
template <class A> double additive(double p, int n, A a) {
double s = 0.0;
for (int h = 1; h <= n; ++h) { double v = a(h); if (v != 0.0) s += v * std::sin(2 * PI * h * p); }
return s;
}
const double VOWELS[5][3] = { // formant centre frequencies (Hz): a, e, i, o, u
{800.0, 1150.0, 2900.0}, {400.0, 1600.0, 2700.0}, {300.0, 2300.0, 3000.0},
{450.0, 800.0, 2830.0}, {325.0, 700.0, 2530.0},
};
const double DRAWBARS[4][6] = { // levels of harmonics 1, 2, 3, 4, 6, 8
{8.0, 8.0, 8.0, 0.0, 0.0, 0.0}, {8.0, 0.0, 8.0, 6.0, 0.0, 4.0},
{6.0, 8.0, 4.0, 8.0, 3.0, 2.0}, {8.0, 3.0, 0.0, 8.0, 8.0, 8.0},
};
/** Glass: sparse prime and square-ish harmonics at seeded levels, a new set every
* four frames, crossfaded between. [out]: FRAMES x 40. */
void makeGlass(double out[FRAMES][40]) {
static const int primes[] = {1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};
static const int squares[] = {1, 2, 4, 6, 9, 12, 16, 20, 25, 30, 36};
auto in = [](const int *set, int n, int v) { for (int i = 0; i < n; ++i) if (set[i] == v) return true; return false; };
constexpr int NSETS = FRAMES / 4 + 2;
double sets[NSETS][40];
for (int k = 0; k < NSETS; ++k) {
JavaRandom rng(0x61A55LL + k);
bool even = k % 2 == 0;
for (int h = 0; h < 40; ++h) {
bool picked = even ? in(primes, 13, h + 1) : in(squares, 11, h + 1);
sets[k][h] = picked ? 0.2 + 0.8 * rng.nextDouble() : 0.0;
}
}
for (int f = 0; f < FRAMES; ++f) {
int k = f / 4; double fr = (f % 4) / 4.0;
for (int h = 0; h < 40; ++h) out[f][h] = sets[k][h] * (1 - fr) + sets[k + 1][h] * fr;
}
}
double classic(int i, double q) {
switch (i) {
case 0: return sine(q);
case 1: return tri(q);
case 2: return saw(q);
case 3: return pulse(q, 0.5);
default: return pulse(q, 0.25);
}
}
double sample(int id, double t, int f, double p, const double (*glass)[40]) {
switch (id) {
case 0: { // Classic
double x = t * 4; int i = std::min(3, (int)x); double fr = x - i;
return classic(i, p) * (1 - fr) + classic(i + 1, p) * fr;
}
case 1: return pulse(p, 0.5 - 0.46 * t); // PWM
case 2: { // Vowels
double x = t * 4; int i = std::min(3, (int)x); double fr = x - i;
return additive(p, 60, [&](int h) {
double hz = h * 110.0;
double a = 0.0;
for (int k = 0; k < 3; ++k) {
double fc = VOWELS[i][k] * (1 - fr) + VOWELS[i + 1][k] * fr;
double bw = 80.0 + 40.0 * k;
a += std::exp(-std::pow((hz - fc) / bw, 2.0)) * (k == 0 ? 1.0 : 0.6);
}
return (a + 0.02) / std::sqrt((double)h);
});
}
case 3: { // Harmonic Sweep
double n = 1.0 + std::pow(2.0, t * 6);
return additive(p, 65, [&](int h) { return h <= n ? 1.0 / h : (h - 1 < n ? (n - (h - 1)) / h : 0.0); });
}
case 4: return saw(p * (1 + 7 * t)) * (1 - 0.3 * t * p); // Sync
case 5: return std::sin(2 * PI * p + 7 * t * std::sin(2 * PI * p) + 1.5 * t * t * std::sin(4 * PI * p)); // FM
case 6: { // Organ
double x = t * 3; int i = std::min(2, (int)x); double fr = x - i;
static const int hs[] = {1, 2, 3, 4, 6, 8};
double s = 0.0;
for (int k = 0; k < 6; ++k) s += (DRAWBARS[i][k] * (1 - fr) + DRAWBARS[i + 1][k] * fr) / 8 * sine(hs[k] * p);
return s;
}
case 7: return std::sin((1 + 7 * t) * std::sin(2 * PI * p) * PI / 2); // Fold
case 8: { // Digital; kotlin.math.round is half-to-even (Math.rint)
double steps = std::pow(2.0, 6 - 5 * t);
return std::nearbyint(sine(p) * steps) / steps;
}
case 9: return additive(p, 40, [&](int h) { return glass[f][h - 1] / std::pow((double)h, 0.6); }); // Glass
case 10: return additive(p, 64, [&](int h) { // Odd Even
return h % 2 == 1 ? (1 - t) / h + t * 0.3 / h : t / h * (h == 2 ? 1.6 : 1.0);
});
case 11: return additive(p, 64, [&](int h) { return std::fabs(std::cos(PI * h * (0.02 + 0.23 * t))) / h; }); // Comb
default: return sine(p);
}
}
std::unique_ptr<WaveTable> makeFactory(int id) {
static double glass[FRAMES][40];
if (id == 9) makeGlass(glass);
std::vector<std::vector<float>> cycles(FRAMES);
std::vector<double> x(GEN);
for (int f = 0; f < FRAMES; ++f) {
double t = f / (FRAMES - 1.0);
for (int i = 0; i < GEN; ++i) x[i] = sample(id, t, f, (double)i / GEN, glass);
double sum = 0.0; // DoubleArray.average(): sequential sum / count
for (int i = 0; i < GEN; ++i) sum += x[i];
double dc = sum / GEN;
double pk = 1e-9;
for (int i = 0; i < GEN; ++i) { x[i] -= dc; pk = jmax(pk, std::fabs(x[i])); }
cycles[f].resize(GEN);
for (int i = 0; i < GEN; ++i) cycles[f][i] = (float)(x[i] / pk);
}
return fromCycles(FACTORY_NAMES[id], cycles);
}
// -------------------------------------------------------------- custom ---
constexpr int MAX_CUSTOM = 32;
constexpr int KEY_LEN = 64;
enum : int { FREE = 0, CLAIMING = 1, REQUESTED = 2, BUILDING = 3, READY = 4 };
struct CustomEntry {
std::atomic<int> state{FREE};
char id[KEY_LEN] = {};
int frameLen = 0;
std::atomic<const WaveTable *> table{nullptr};
};
CustomEntry gCustom[MAX_CUSTOM];
std::atomic<SampleSource> gSource{nullptr};
std::mutex gCustomMutex; // serializes builders (never taken by the audio thread)
bool keyMatches(const CustomEntry &e, const char *id, int frameLen) {
return e.frameLen == frameLen && std::strncmp(e.id, id, KEY_LEN - 1) == 0;
}
CustomEntry *findEntry(const char *id, int frameLen) {
for (auto &e : gCustom) {
int st = e.state.load(std::memory_order_acquire);
if (st >= REQUESTED && keyMatches(e, id, frameLen)) return &e;
}
return nullptr;
}
CustomEntry *claimEntry(const char *id, int frameLen, int newState) {
for (auto &e : gCustom) {
int expected = FREE;
if (e.state.compare_exchange_strong(expected, CLAIMING, std::memory_order_acquire)) {
std::strncpy(e.id, id, KEY_LEN - 1);
e.id[KEY_LEN - 1] = '\0';
e.frameLen = frameLen;
e.state.store(newState, std::memory_order_release);
return &e;
}
}
return nullptr; // full: the table stays silent
}
std::unique_ptr<WaveTable> buildFromSource(const char *id, int frameLen) {
SampleSource src = gSource.load();
if (!src) return nullptr;
std::vector<float> x;
if (!src(id, x)) return nullptr;
return fromSamples(CUSTOM, x.data(), (int)x.size(), frameLen);
}
int indexOf(const uint8_t *h, size_t hn, const char *n, size_t nn) {
if (hn < nn) return -1;
for (size_t i = 0; i + nn <= hn; ++i) if (std::memcmp(h + i, n, nn) == 0) return (int)i;
return -1;
}
} // namespace
int factoryIndex(const char *name) {
for (int i = 0; i < FACTORY_COUNT; ++i) if (std::strcmp(FACTORY_NAMES[i], name) == 0) return i;
return -1;
}
const WaveTable *factory(int index) {
if (index < 0 || index >= FACTORY_COUNT) return nullptr;
return gFactory[index].load(std::memory_order_acquire);
}
const WaveTable *factory(const char *name) { return factory(factoryIndex(name)); }
void prewarm() {
if (gStarted.exchange(true)) return;
std::thread([] { prewarmBlocking(); }).detach();
}
void prewarmBlocking() {
std::lock_guard<std::mutex> lock(gBuildMutex);
for (int i = 0; i < FACTORY_COUNT; ++i)
if (!gFactory[i].load(std::memory_order_acquire))
gFactory[i].store(makeFactory(i).release(), std::memory_order_release);
}
void setSampleSource(SampleSource source) { gSource.store(source); }
const WaveTable *forSample(const char *id, int frameLen) {
if (!id || !*id) return nullptr;
if (CustomEntry *e = findEntry(id, frameLen)) return e->table.load(std::memory_order_acquire);
claimEntry(id, frameLen, REQUESTED); // queued once
return nullptr;
}
const WaveTable *buildForSample(const char *id, int frameLen) {
if (!id || !*id) return nullptr;
std::lock_guard<std::mutex> lock(gCustomMutex);
std::unique_ptr<WaveTable> t = buildFromSource(id, frameLen);
if (!t) return nullptr;
CustomEntry *e = findEntry(id, frameLen);
if (!e) e = claimEntry(id, frameLen, BUILDING);
const WaveTable *built = t.release(); // replaced tables are kept alive (a voice may hold one)
if (e) { e->table.store(built, std::memory_order_release); e->state.store(READY, std::memory_order_release); }
return built;
}
void buildRequested() {
std::lock_guard<std::mutex> lock(gCustomMutex);
for (auto &e : gCustom) {
int expected = REQUESTED;
if (!e.state.compare_exchange_strong(expected, BUILDING, std::memory_order_acquire)) continue;
std::unique_ptr<WaveTable> t = buildFromSource(e.id, e.frameLen);
if (t) {
e.table.store(t.release(), std::memory_order_release);
e.state.store(READY, std::memory_order_release);
} else {
e.state.store(FREE, std::memory_order_release); // like building.remove(key): asked again later
}
}
}
// -------------------------------------------------------------- import ---
int detectFrameLength(const uint8_t *wavBytes, size_t size, int frames) {
int clm = indexOf(wavBytes, size, "clm ", 4);
if (clm >= 0) {
// String(bytes, clm + 8, min(32, size - clm - 8), US_ASCII), then Regex("<!>(\\d{2,5})").find
long len = std::min(32L, (long)size - clm - 8);
const uint8_t *text = wavBytes + clm + 8;
for (long i = 0; i + 3 <= len; ++i) {
if (text[i] != '<' || text[i + 1] != '!' || text[i + 2] != '>') continue;
int digits = 0, v = 0;
while (digits < 5 && i + 3 + digits < len && text[i + 3 + digits] >= '0' && text[i + 3 + digits] <= '9') {
v = v * 10 + (text[i + 3 + digits] - '0');
++digits;
}
if (digits < 2) continue;
if (v >= 16 && v <= 8192 && frames % v == 0) return v;
break; // only the first match counts
}
}
return guessFrameLength(frames);
}
int guessFrameLength(int frames) {
if (frames == 64 * 256) return 256;
if (frames % 2048 == 0 && frames / 2048 >= 1 && frames / 2048 <= 256) return 2048;
if (frames % 256 == 0 && frames / 256 >= 1 && frames / 256 <= 256) return 256;
if (frames % 1024 == 0 && frames / 1024 >= 1 && frames / 1024 <= 256) return 1024;
if (frames % 512 == 0 && frames / 512 >= 1 && frames / 512 <= 256) return 512;
return 0;
}
std::unique_ptr<WaveTable> fromSamples(const char *name, const float *x, int n, int frameLen0) {
if (n <= 0) return nullptr;
int frameLen = frameLen0 > 0 ? frameLen0 : guessFrameLength(n);
std::vector<std::vector<float>> cycles;
if (frameLen <= 0 || n < frameLen) {
cycles.emplace_back(x, x + n);
} else {
int nc = std::min(256, n / frameLen);
double step = (double)(n / frameLen) / nc;
for (int i = 0; i < nc; ++i) {
int f = (int)(i * step);
cycles.emplace_back(x + (size_t)f * frameLen, x + (size_t)(f + 1) * frameLen);
}
}
float pk = 1e-9f;
for (const auto &c : cycles) for (float v : c) pk = jmax(pk, std::fabs(v));
float g = 1.f / pk;
for (auto &c : cycles) for (float &v : c) v = v * g;
return fromCycles(name, cycles);
}
} // namespace WaveTables
} // namespace sizzle::wavetable
+105
View File
@@ -0,0 +1,105 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of WaveTables.kt: the wavetable synth's band-limited tables.
#include <cstddef>
#include <cstdint>
#include <memory>
#include <vector>
namespace sizzle::wavetable {
/**
* A wavetable ready to play: [frames] single cycles, each kept as band-limited
* copies, one per octave ("mip levels"). Level k holds at most `512 >> k`
* harmonics in a cycle of size(k) samples; the top quarter of each level's
* harmonics is faded out with a raised cosine. Immutable once built.
*/
class WaveTable {
public:
static constexpr int MAX_HARMONICS = 512;
static constexpr int LEVELS = 10;
/** max(64, 4 * (MAX_HARMONICS >> k)) */
static constexpr int SIZES[LEVELS] = {2048, 1024, 512, 256, 128, 64, 64, 64, 64, 64};
/** Harmonics level k carries. */
static constexpr int harmonics(int level) { return MAX_HARMONICS >> level; }
WaveTable(const char *name, int frames);
int size(int level) const { return SIZES[level]; }
/** [frame * size(level) + i] */
const float *data(int level) const { return data_[level].data(); }
float *data(int level) { return data_[level].data(); }
const char *name() const { return name_; }
const int frames;
private:
char name_[32];
std::vector<float> data_[LEVELS];
};
/**
* The tables: twelve factory tables made from formulas (no audio files ship), and
* tables imported from WAV samples (Serum's 2048-sample frames, WaveEdit's 256, or
* any power-of-two frame length).
*
* Everything is built off the audio thread. Factory tables: call prewarm() at
* startup (builds on a background thread) or prewarmBlocking(). Lookups never
* block or allocate; a table that isn't built yet is null (the oscillator is
* silent). Built tables live for the rest of the process, as Kotlin's cache does.
*/
namespace WaveTables {
constexpr int FRAMES = 16;
constexpr int FACTORY_COUNT = 12;
extern const char *const FACTORY_NAMES[FACTORY_COUNT];
constexpr const char *CUSTOM = "Custom";
/** Index of the factory table called [name], or -1. */
int factoryIndex(const char *name);
/** The factory table [index] (FACTORY_NAMES order), or null while not built. Audio-safe. */
const WaveTable *factory(int index);
const WaveTable *factory(const char *name);
/** Build the factory set on a background thread (once). */
void prewarm();
/** Build every factory table not built yet, on the calling thread (not the audio thread). */
void prewarmBlocking();
// ---------------------------------------------------------------- custom ---
//
// Hook for the sample store (not ported yet). Kotlin's forSample queues a build
// on its worker that reads SampleStore.get(id).data. Here the audio thread only
// records the request; whoever owns the samples supplies them through a
// SampleSource and calls buildRequested() (or buildForSample) off the audio thread.
/** Fills [out] with the mono float samples of sample [id]; false if unknown. */
using SampleSource = bool (*)(const char *id, std::vector<float> &out);
void setSampleSource(SampleSource source);
/** The table of custom sample [id] cut in [frameLen]-sample frames (0: detect), or
* null while it isn't built (the request is then recorded once). Audio-safe:
* no allocation, no locks. */
const WaveTable *forSample(const char *id, int frameLen);
/** Build a custom table now from the SampleSource (caller off the audio thread) and cache it. */
const WaveTable *buildForSample(const char *id, int frameLen);
/** Build every table forSample has asked for (caller off the audio thread). */
void buildRequested();
// ---------------------------------------------------------------- import ---
/** The frame length of a wavetable WAV: Serum's `clm ` chunk ("<!>2048 …") when
* present, else WaveEdit's 64 x 256 layout, else 2048 or 256 if the length divides,
* else the whole file as one cycle (0). [frames]: the WAV's sample frames. */
int detectFrameLength(const uint8_t *wavBytes, size_t size, int frames);
int guessFrameLength(int frames);
/** A table from a sample cut into [frameLen0]-sample cycles (0: detect; at most 256
* frames). Null for an empty sample (Kotlin would throw). Not audio-safe. */
std::unique_ptr<WaveTable> fromSamples(const char *name, const float *x, int n, int frameLen0);
} // namespace WaveTables
} // namespace sizzle::wavetable
+35
View File
@@ -0,0 +1,35 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// The reference-test maker for kind "WAVE" (see TestVoice.hpp, IosGoldenInstruments.kt):
// WaveVoice alone, patch from the slot, factory tables built up front.
#include <memory>
#include "sizzle/TestVoice.hpp"
#include "WaveTables.hpp"
#include "WaveVoice.hpp"
namespace sizzle {
namespace {
class WaveTestVoice final : public TestVoice {
public:
explicit WaveTestVoice(const TestVoiceSetup &s)
: voice_(s.sampleRate), patch_(wavetable::WavePatch::from(s.params, s.tempoBpm)) {}
void noteOn(int midi, int velocity) override { voice_.noteOn(midi, (float)velocity / 127.f, patch_); }
void noteOff(int) override { voice_.noteOff(); }
float render() override { return voice_.render(); }
private:
wavetable::WaveVoice voice_;
wavetable::WavePatch patch_;
};
} // namespace
std::unique_ptr<TestVoice> makeWaveTestVoice(const TestVoiceSetup &setup) {
wavetable::WaveTables::prewarmBlocking();
return std::make_unique<WaveTestVoice>(setup);
}
} // namespace sizzle
+292
View File
@@ -0,0 +1,292 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Port of WaveVoice.kt (WavePatch, WaveVoice). Line for line: Float -> float,
// Double -> double, kotlin.math on Float through double (KotlinMath.hpp).
#include "WaveVoice.hpp"
#include <cmath>
#include <cstdio>
#include <cstring>
#include "KotlinMath.hpp"
#include "WaveDefs.hpp"
#include "WaveTables.hpp"
#if defined(__clang__)
#pragma clang fp contract(off) // Java never fuses multiply-adds
#endif
namespace sizzle::wavetable {
namespace {
constexpr int CTRL = 16;
constexpr float OUT_GAIN = 0.45f;
constexpr double PI = 3.141592653589793; // kotlin.math.PI
constexpr float PIf = (float)PI; // PI.toFloat()
const float LN2 = (float)std::log(2.0); // ln(2f)
/** TimeDivision.entries' beatFraction (model/Toolbox.kt), until the model is ported. */
constexpr double TIME_DIVISION_BEATS[] = {4.0, 2.0, 1.0, 0.5, 0.25, 0.125, 0.75};
constexpr int TIME_DIVISION_COUNT = 7;
int indexOf(const char *const *choices, int n, const char *v) {
for (int i = 0; i < n; ++i) if (std::strcmp(choices[i], v) == 0) return i;
return -1;
}
} // namespace
// ---------------------------------------------------------------- WavePatch ---
WavePatch WavePatch::from(const Params *slot, float tempoBpm) {
auto f = [&](const char *k, float d) { return slot ? slot->f(k, d) : d; };
auto c = [&](const char *k, const char *const *choices, int n) {
return kt::coerceAtLeast(indexOf(choices, n, slot ? slot->s(k, choices[0]) : choices[0]), 0);
};
char key[16];
WavePatch p{};
for (int o = 0; o < 2; ++o) {
int n = o + 1;
std::snprintf(key, sizeof key, "o%dtable", n);
const char *name = slot ? slot->s(key, WaveDefs::TABLES[0]) : WaveDefs::TABLES[0];
if (std::strcmp(name, WaveTables::CUSTOM) == 0) p.table[o] = TABLE_CUSTOM;
else { int i = WaveTables::factoryIndex(name); p.table[o] = i >= 0 ? i : TABLE_NONE; }
std::snprintf(key, sizeof key, "o%doct", n);
float oct = (float)kt::coerceIn(kt::toInt(f(key, 0.f)), -2, 2) * 12.f;
std::snprintf(key, sizeof key, "o%dsemi", n);
int semi = kt::coerceIn(kt::toInt(f(key, 0.f)), -12, 12);
std::snprintf(key, sizeof key, "o%dfine", n);
float fine = kt::coerceIn(f(key, n == 1 ? 0.f : 7.f), -50.f, 50.f) / 100.f;
p.semis[o] = oct + (float)semi + fine;
std::snprintf(key, sizeof key, "o%dpos", n);
p.pos[o] = kt::coerceIn(f(key, o == 0 ? 0.f : 0.3f), 0.f, 1.f);
std::snprintf(key, sizeof key, "o%dlevel", n);
p.level[o] = kt::coerceIn(f(key, o == 0 ? 0.8f : 0.f), 0.f, 1.f);
std::snprintf(key, sizeof key, "o%dbend", n);
p.bend[o] = kt::coerceIn(f(key, 0.f), -1.f, 1.f);
}
// FRAME_SIZES[c].toIntOrNull() ?: 0 ("Auto" -> 0)
int fi = c("wtframe", WaveDefs::FRAME_SIZES, WaveDefs::FRAME_SIZE_COUNT);
int frame = fi == 0 ? 0 : std::atoi(WaveDefs::FRAME_SIZES[fi]);
int div = kt::coerceIn(kt::toInt(f("lfodiv", 1.f)), 0, TIME_DIVISION_COUNT - 1);
float beat = (float)TIME_DIVISION_BEATS[div];
p.unison = kt::coerceIn(kt::toInt(f("unison", 1.f)), 1, 4);
p.spread = kt::coerceIn(f("spread", 0.3f), 0.f, 1.f);
p.sub = kt::coerceIn(f("sub", 0.f), 0.f, 1.f);
p.noise = kt::coerceIn(f("noise", 0.f), 0.f, 1.f);
p.velSens = kt::coerceIn(f("velsens", 0.5f), 0.f, 1.f);
std::snprintf(p.customId, sizeof p.customId, "%s", slot ? slot->s(WaveDefs::SAMPLE_KEY, "") : "");
p.frameLen = frame;
p.filterType = c("ftype", WaveDefs::FILTER_TYPES, WaveDefs::FILTER_TYPE_COUNT);
p.cutoff = kt::coerceIn(f("cutoff", 0.75f), 0.f, 1.f);
p.reso = kt::coerceIn(f("reso", 0.15f), 0.f, 1.f);
p.keytrack = kt::coerceIn(f("keytrack", 0.4f), 0.f, 1.f);
p.fenv = kt::coerceIn(f("fenv", 0.2f), -1.f, 1.f);
p.drive = kt::coerceIn(f("drive", 0.f), 0.f, 1.f);
p.a = f("attack", 0.01f);
p.d = f("decay", 0.3f);
p.s = kt::coerceIn(f("sustain", 0.8f), 0.f, 1.f);
p.r = f("release", 0.4f);
p.ma = f("mattack", 0.5f);
p.md = f("mdecay", 2.f);
p.ms = kt::coerceIn(f("msustain", 0.5f), 0.f, 1.f);
p.mr = f("mrelease", 1.f);
p.menvPos = kt::coerceIn(f("menvpos", 0.3f), -1.f, 1.f);
p.lfoWave = c("lfowave", WaveDefs::LFO_WAVES, WaveDefs::LFO_WAVE_COUNT);
p.lfoHz = beat > 0.f ? (tempoBpm / 60.f) / beat : 1.f;
p.lfoPos = kt::coerceIn(f("lfopos", 0.15f), 0.f, 1.f);
p.lfoPitch = kt::coerceIn(f("lfopitch", 0.f), 0.f, 1.f);
p.lfoCut = kt::coerceIn(f("lfocut", 0.f), 0.f, 1.f);
return p;
}
const WavePatch &WavePatch::defaults() {
static const WavePatch d = from(nullptr, 120.f);
return d;
}
// ---------------------------------------------------------------- Env ---
void WaveVoice::Env::retime(float aa, float dd, float ss, float rr) {
a_ = std::fmax(aa, 0.0005f); d_ = std::fmax(dd, 0.001f); s_ = ss; r_ = std::fmax(rr, 0.001f);
}
float WaveVoice::Env::next(float dt) {
switch (stage_) {
case 1: level_ += dt / a_; if (level_ >= 1.f) { level_ = 1.f; stage_ = 2; } break;
case 2: level_ -= dt / d_ * (1.f - s_); if (level_ <= s_) { level_ = s_; stage_ = 3; } break;
case 4: level_ -= dt / r_; if (level_ <= 0.f) { level_ = 0.f; stage_ = 0; } break;
default: break;
}
return level_;
}
// ---------------------------------------------------------------- WaveVoice ---
WaveVoice::WaveVoice(int fs) : fsf_((float)fs), patch_(WavePatch::defaults()) {}
void WaveVoice::noteOn(int midi, float velocity, const WavePatch &p) {
bool fresh = !amp_.active();
patch_ = p;
note_ = midi;
vel_ = kt::coerceIn(velocity, 0.f, 1.f);
baseHz_ = (float)(440.0 * std::pow(2.0, (midi - 69) / 12.0));
amp_.on(p.a, p.d, p.s, p.r);
mod_.on(p.ma, p.md, p.ms, p.mr);
if (fresh) {
s1_ = 0.f; s2_ = 0.f; lfoPh_ = 0.0;
for (int i = 0; i < 2 * MAX_UNISON; ++i)
phase_[i] = (i % MAX_UNISON == 0 && p.unison == 1) ? 0.0 : (double)rand01();
subPhase_ = 0.0;
}
ctrl_ = 0;
}
void WaveVoice::noteOff() { amp_.off(); mod_.off(); }
void WaveVoice::kill() { amp_.kill(); mod_.kill(); note_ = -1; s1_ = 0.f; s2_ = 0.f; }
void WaveVoice::setPatch(const WavePatch &p) {
patch_ = p;
amp_.retime(p.a, p.d, p.s, p.r);
mod_.retime(p.ma, p.md, p.ms, p.mr);
}
float WaveVoice::render() {
if (!amp_.active()) return 0.f;
if (ctrl_ <= 0) { control(); ctrl_ = CTRL; }
ctrl_--;
const WavePatch &p = patch_;
float mix = 0.f;
int uni = p.unison;
float uniGain = 1.f / kt::sqrtf_((float)uni);
for (int o = 0; o < 2; ++o) {
const WaveTable *t = oscTable_[o];
if (!t) continue;
float lvl = p.level[o];
if (lvl <= 0.0001f) continue;
int lv = oscLevel_[o];
int size = t->size(lv);
const float *data = t->data(lv);
float fpos = oscFrame_[o];
int f0 = kt::coerceAtMost(kt::toInt(fpos), t->frames - 1);
int f1 = f0 + 1 < t->frames - 1 ? f0 + 1 : t->frames - 1;
float ff = fpos - (float)f0;
int b0 = f0 * size, b1 = f1 * size;
int mask = size - 1;
float m = oscWarpM_[o];
float acc = 0.f;
for (int u = 0; u < uni; ++u) {
int k = o * MAX_UNISON + u;
double ph = phase_[k] + inc_[k];
if (ph >= 1.0) ph -= 1.0;
phase_[k] = ph;
// BEND: the cycle's first part squeezed into half (m < 0.5) or stretched (m > 0.5)
float pw;
if (m == 0.5f) pw = (float)ph;
else {
float q = (float)ph;
pw = q < m ? 0.5f * q / m : 0.5f + 0.5f * (q - m) / (1.f - m);
}
float x = pw * (float)size;
int xi = kt::toInt(x);
int i0 = xi & mask;
int i1 = (i0 + 1) & mask;
float fr = x - (float)xi;
float a0 = data[b0 + i0] + (data[b0 + i1] - data[b0 + i0]) * fr;
float a1 = data[b1 + i0] + (data[b1 + i1] - data[b1 + i0]) * fr;
acc += a0 + (a1 - a0) * ff;
}
mix += acc * uniGain * lvl;
}
if (p.sub > 0.0001f) {
subPhase_ += subInc_;
if (subPhase_ >= 1.0) subPhase_ -= 1.0;
mix += p.sub * (float)std::sin(2.0 * PI * subPhase_);
}
if (p.noise > 0.0001f) mix += p.noise * 0.5f * (rand01() * 2.f - 1.f);
if (p.drive > 0.001f) { float g = 1.f + 4.f * p.drive; mix = kt::tanhf_(mix * g) / kt::tanhf_(g); }
// the state-variable filter (Zavalishin / Simper TPT form)
float v3 = mix - s2_;
float v1 = fa1_ * s1_ + fa2_ * v3;
float v2 = s2_ + fa2_ * s1_ + fa3_ * v3;
s1_ = 2.f * v1 - s1_;
s2_ = 2.f * v2 - s2_;
float y = p.filterType == 1 ? v1 : p.filterType == 2 ? mix - fk_ * v1 - v2 : v2;
float e = amp_.next(1.f / fsf_);
mod_.next(1.f / fsf_);
float out = y * e * (1.f - p.velSens + p.velSens * vel_) * OUT_GAIN;
if (std::isfinite(out)) return out;
kill();
return 0.f;
}
void WaveVoice::control() {
const WavePatch &p = patch_;
float dt = (float)CTRL / fsf_;
// LFO
lfoPh_ += (double)(p.lfoHz * dt);
if (lfoPh_ >= 1.0) { lfoPh_ -= std::floor(lfoPh_); shVal_ = rand01() * 2.f - 1.f; }
float ph = (float)lfoPh_;
switch (p.lfoWave) {
case 1: lfoVal_ = 1.f - 4.f * std::fabs(ph - 0.5f); break;
case 2: lfoVal_ = 2.f * ph - 1.f; break;
case 3: lfoVal_ = ph < 0.5f ? 1.f : -1.f; break;
case 4: lfoVal_ = shVal_; break;
default: lfoVal_ = kt::sinf_(2.f * PIf * ph); break;
}
float menv = mod_.level();
float vibCents = p.lfoPitch * 50.f * lfoVal_; // up to ±50 cents
for (int o = 0; o < 2; ++o) {
const WaveTable *t = p.table[o] == WavePatch::TABLE_CUSTOM ? WaveTables::forSample(p.customId, p.frameLen)
: WaveTables::factory(p.table[o]);
oscTable_[o] = t;
if (!t) continue;
float pos = kt::coerceIn(p.pos[o] + p.menvPos * menv + p.lfoPos * 0.5f * lfoVal_, 0.f, 1.f);
oscFrame_[o] = pos * (float)(t->frames - 1);
float b = p.bend[o];
float m = b >= 0.f ? 0.5f * (1.f - 0.9f * b) : 0.5f * (1.f + 0.9f * -b);
oscWarpM_[o] = m;
float slope = 0.5f / std::fmin(m, 1.f - m);
float hz = baseHz_ * kt::powf_(2.f, (p.semis[o] + vibCents / 100.f) / 12.f);
int uni = p.unison;
float top = hz;
for (int u = 0; u < uni; ++u) {
float cents = uni == 1 ? 0.f : p.spread * 30.f * (2.f * (float)u / (float)(uni - 1) - 1.f);
float fq = hz * kt::powf_(2.f, cents / 1200.f);
inc_[o * MAX_UNISON + u] = (double)(fq / fsf_);
if (fq > top) top = fq;
}
// the band-limited level: its top harmonic (times BEND's steepening) under 0.45 fs
float hmax = 0.45f * fsf_ / (top * slope);
if (hmax >= (float)WaveTable::MAX_HARMONICS) oscLevel_[o] = 0;
else {
float lnr = (float)std::log((double)((float)WaveTable::MAX_HARMONICS / std::fmax(1.f, hmax)));
float lv = (float)std::ceil((double)(lnr / LN2));
oscLevel_[o] = kt::coerceIn(kt::toInt(lv), 0, WaveTable::LEVELS - 1);
}
}
subInc_ = (double)(baseHz_ * 0.5f * kt::powf_(2.f, p.semis[0] / 12.f) / fsf_);
// filter: cutoff 20 Hz .. 20 kHz on an exponential scale, key tracking around C4
float c = p.cutoff + p.keytrack * (float)(note_ - 60) / 120.f + p.fenv * menv * 0.6f + p.lfoCut * 0.3f * lfoVal_;
float fc = kt::coerceAtMost(20.f * kt::powf_(1000.f, kt::coerceIn(c, 0.f, 1.f)), 0.45f * fsf_);
float g = (float)std::tan((double)(PIf * fc / fsf_));
fk_ = 2.f - 1.96f * p.reso;
fa1_ = 1.f / (1.f + g * (g + fk_)); fa2_ = g * fa1_; fa3_ = g * fa2_;
}
float WaveVoice::rand01() {
uint32_t x = rng_;
x ^= x << 13; x ^= x >> 17; x ^= x << 5; // Int xorshift; ushr = logical shift
rng_ = x;
return (float)(x >> 8) * (1.f / 16777216.f);
}
} // namespace sizzle::wavetable
+116
View File
@@ -0,0 +1,116 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Port of WaveVoice.kt: one note of the wavetable synth, and WavePatch, its
// parsed slot. Tables come from WaveTables (built off the audio thread; see
// WaveTables::prewarm). noteOn / render / noteOff never allocate or lock.
#include <cstdint>
#include "sizzle/Params.hpp"
namespace sizzle::wavetable {
class WaveTable;
/** A parsed Wavetable slot (built once per slot change, off the sample loop). */
struct WavePatch {
/** Oscillator table: an index into WaveTables::FACTORY_NAMES, TABLE_CUSTOM
* (the slot's custom sample), or TABLE_NONE (unknown name: silent). */
static constexpr int TABLE_CUSTOM = 12;
static constexpr int TABLE_NONE = -1;
int table[2];
float pos[2], semis[2], level[2], bend[2];
int unison;
float spread, sub, noise, velSens;
char customId[Params::kValLen];
int frameLen;
int filterType; // 0 low, 1 band, 2 high
float cutoff, reso, keytrack, fenv, drive;
float a, d, s, r;
float ma, md, ms, mr, menvPos;
int lfoWave; // 0 sine, 1 tri, 2 saw, 3 square, 4 S&H
float lfoHz, lfoPos, lfoPitch, lfoCut;
/** WavePatch.from(slot, tempoBpm); [slot] may be null (all defaults). */
static WavePatch from(const Params *slot, float tempoBpm);
/** WavePatch.DEFAULT: from(null, 120). */
static const WavePatch &defaults();
};
/**
* One note: 2 wavetable oscillators (table, position, pitch, level, phase bend,
* up to 4 unison copies) + a sub sine + noise -> drive -> state-variable filter
* (low / band / high) -> amp envelope. A mod envelope and a tempo-synced LFO move
* the table position, the cutoff and (LFO) the pitch, re-read every CTRL samples.
*/
class WaveVoice {
public:
static constexpr int MAX_UNISON = 4;
explicit WaveVoice(int fs);
/** The MIDI note playing, -1 after kill(). */
int note() const { return note_; }
bool isActive() const { return amp_.active(); }
bool isGated() const { return amp_.gate(); }
/** [velocity] 0..1. Copies [p]. */
void noteOn(int midi, float velocity, const WavePatch &p);
void noteOff();
void kill();
void setPatch(const WavePatch &p);
float render();
private:
/** Linear ADSR, levels 0..1; a release reaches 0 in its time from any level. */
class Env {
public:
float level() const { return level_; }
bool active() const { return stage_ != 0; }
bool gate() const { return stage_ >= 1 && stage_ <= 3; }
void on(float aa, float dd, float ss, float rr) { retime(aa, dd, ss, rr); stage_ = 1; }
void retime(float aa, float dd, float ss, float rr);
void off() { if (stage_ != 0) stage_ = 4; }
void kill() { stage_ = 0; level_ = 0.f; }
float next(float dt);
private:
int stage_ = 0; // 0 idle, 1 attack, 2 decay, 3 sustain, 4 release
float level_ = 0.f;
float a_ = 0.01f, d_ = 0.1f, s_ = 0.7f, r_ = 0.2f;
};
void control();
float rand01();
float fsf_;
WavePatch patch_;
int note_ = -1;
float vel_ = 0.f;
float baseHz_ = 440.f;
Env amp_, mod_;
// oscillators: [osc * MAX_UNISON + u]
double phase_[2 * MAX_UNISON] = {};
double inc_[2 * MAX_UNISON] = {};
const WaveTable *oscTable_[2] = {nullptr, nullptr};
int oscLevel_[2] = {0, 0};
float oscFrame_[2] = {0.f, 0.f};
float oscWarpM_[2] = {0.f, 0.f};
double subPhase_ = 0.0;
double subInc_ = 0.0;
// filter (topology-preserving SVF)
float s1_ = 0.f, s2_ = 0.f;
float fa1_ = 0.f, fa2_ = 0.f, fa3_ = 0.f, fk_ = 1.f;
double lfoPh_ = 0.0;
float lfoVal_ = 0.f;
float shVal_ = 0.f;
int ctrl_ = 0;
uint32_t rng_ = 0x6C8E9CF5u;
};
} // namespace sizzle::wavetable