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
+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