diff --git a/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenInstruments.kt b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenInstruments.kt index 0ba87b3..96cd1d1 100644 --- a/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenInstruments.kt +++ b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenInstruments.kt @@ -9,6 +9,7 @@ import cc.tiredsysadmin.android.sizzle.echofield.GrainPatch import cc.tiredsysadmin.android.sizzle.frasil.FrasilClock import cc.tiredsysadmin.android.sizzle.frasil.FrasilPatch import cc.tiredsysadmin.android.sizzle.frasil.FrasilVoice +import cc.tiredsysadmin.android.sizzle.model.SamplerPads import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot import cc.tiredsysadmin.android.sizzle.model.ToolboxType import cc.tiredsysadmin.android.sizzle.wavetable.WavePatch @@ -35,9 +36,19 @@ import kotlin.math.roundToInt * script ("on ", "off ") * and the length ("frames") * ___.f32 the output, raw little-endian float32 + * TABLE__.scn / .f32 each factory wavetable's data, all mip levels + * concatenated (checks the table generators) + * + * The Morph Pad and Grain Cloud seed each new voice from a private global counter; + * "seeds " records both counters right before the scenario builds + * its voices (render() builds a SynthVoice, whose FrasilVoice takes the next + * Frasil seed, then a FrasilVoice, then a GrainCloud). * * Kinds: SYNTH = SynthVoice with the engine's patch (Synth, Morph Pad, Wavetable); - * FRASIL = FrasilVoice alone; WAVE = WaveVoice alone; GRAIN = GrainCloud. + * FRASIL = FrasilVoice alone; WAVE = WaveVoice alone; GRAIN = GrainCloud; + * SAMPLE = SampleVoice with the engine's voiceSample() settings (Sampler pads 0 and + * 7, SF2/XI loader). SAMPLE scenarios also write the test sample as + * .smp.f32 and a line "sample ". */ class IosGoldenInstruments { @@ -46,6 +57,10 @@ class IosGoldenInstruments { /** Two notes: the second starts after the first's release has begun, so both * attack, release and retrigger paths run. GRAIN adds an overlapping third. */ private fun script(kind: String): List { + if (kind == "SAMPLE") return listOf( // Sampler pads 0 and 7 (C2, G2); SF2 plays any note + Ev(0, true, 36, 100), Ev(at(0.35), false, 36, 0), + Ev(at(0.50), true, 43, 64), Ev(at(0.90), false, 43, 0), + ) val s = mutableListOf( Ev(0, true, 60, 100), Ev(at(0.35), false, 60, 0), Ev(at(0.50), true, 67, 64), Ev(at(0.90), false, 67, 0), @@ -62,27 +77,100 @@ class IosGoldenInstruments { val out = File(dir!!).apply { mkdirs() } WaveTables.prewarmBlocking() GrainSources.prewarmBlocking() + exportTables(out) val kinds = listOf( "SYNTH" to ToolboxType.NES_SYNTH, "SYNTH" to ToolboxType.MORPH_PAD, "SYNTH" to ToolboxType.WAVETABLE, "FRASIL" to ToolboxType.MORPH_PAD, "WAVE" to ToolboxType.WAVETABLE, "GRAIN" to ToolboxType.GRAIN_CLOUD, + "SAMPLE" to ToolboxType.SAMPLER, "SAMPLE" to ToolboxType.SOUNDFONT, ) + // 0.6 s at 44.1 kHz (so playback resamples): a decaying saw plus a little + // noise; loop points for the SF2 path. + var seed = 0x2468ACE + val smp = SampleStore.Sample(FloatArray(26_460) { i -> + seed = seed * 1103515245 + 12345 + val t = i / 44_100.0 + (0.7 * (2 * ((t * 220) % 1.0) - 1) * kotlin.math.exp(-t * 3)).toFloat() + + ((seed ushr 8) and 0xFFFF) / 65535f * 0.05f - 0.025f + }, 44_100, loopStart = 8_000, loopEnd = 20_000) + SampleStore.put(SAMPLE_ID, smp) for ((kind, type) in kinds) for ((variant, values) in variants(type)) { val slot = ToolboxSlot(0).apply { fill(type) } values.forEach { (k, v) -> slot.set(k, v) } + if (kind == "SAMPLE") sampleSlot(type, variant, slot) val events = script(kind) val clock0 = FrasilClock.seconds + val seeds = "${counter(FrasilVoice::class.java)} ${counter(GrainCloud::class.java)}" val y = render(kind, type, slot, events) val base = "${kind}_${type.name}__$variant" File(out, "$base.scn").writeText(buildString { append("kind $kind\ntype ${type.name}\nsr $SR\ntempo $TEMPO\nblock $BLOCK\n") - append("clock ${java.lang.Double.toString(clock0)}\nframes $FRAMES\n") + append("clock ${java.lang.Double.toString(clock0)}\nframes $FRAMES\nseeds $seeds\n") slot.values.toSortedMap().forEach { (k, v) -> append("p $k $v\n") } + if (kind == "SAMPLE") append("sample ${smp.sampleRate} ${smp.loopStart} ${smp.loopEnd}\n") events.forEach { e -> append(if (e.on) "on ${e.frame} ${e.midi} ${e.vel}\n" else "off ${e.frame} ${e.midi}\n") } }) val bb = ByteBuffer.allocate(y.size * 4).order(ByteOrder.LITTLE_ENDIAN) y.forEach { bb.putFloat(it) } File(out, "$base.f32").writeBytes(bb.array()) + if (kind == "SAMPLE") { + val sb = ByteBuffer.allocate(smp.data.size * 4).order(ByteOrder.LITTLE_ENDIAN) + smp.data.forEach { sb.putFloat(it) } + File(out, "$base.smp.f32").writeBytes(sb.array()) + } + } + } + + /** The private `seeds` counter a voice class takes its next seed from. */ + private fun counter(c: Class<*>): Int { + val f = runCatching { c.getDeclaredField("seeds") }.getOrElse { + Class.forName(c.name + "\$Companion").getDeclaredField("seeds") + } + f.isAccessible = true + return f.getInt(null) + } + + private fun exportTables(out: File) { + for (name in WaveTables.FACTORY_NAMES) { + val t = WaveTables.factory(name)!! + val all = (0 until t.data.size).flatMap { t.data[it].asList() } + val bb = ByteBuffer.allocate(all.size * 4).order(ByteOrder.LITTLE_ENDIAN) + all.forEach { bb.putFloat(it) } + val base = "TABLE__" + name.replace(Regex("[^A-Za-z0-9]"), "_") + File(out, "$base.scn").writeText("kind TABLE\ntype WAVETABLE\ntable $name\n") + File(out, "$base.f32").writeBytes(bb.array()) + } + } + + /** Point the slot at the test sample: Sampler pads 0 and 7 with per-variant + * slices and volumes, or the SF2/XI loader's sample with root note 60. */ + private fun sampleSlot(type: ToolboxType, variant: String, slot: ToolboxSlot) { + if (type == ToolboxType.SOUNDFONT) { + slot.set("sfSample", SAMPLE_ID); slot.set("sfRoot", 60f) + return + } + for (pad in listOf(0, 7)) { + slot.set(SamplerPads.key(pad), SAMPLE_ID) + when (variant) { + "high" -> { slot.set(SamplerPads.sliceStartKey(pad), 0.1f); slot.set(SamplerPads.sliceEndKey(pad), 0.8f); slot.set(SamplerPads.volumeKey(pad), 1f) } + "low" -> { slot.set(SamplerPads.sliceStartKey(pad), 0.7f); slot.set(SamplerPads.sliceEndKey(pad), 0.2f); slot.set(SamplerPads.volumeKey(pad), 0.3f) } + } + } + } + + /** The engine's voiceSample(): which sample a note plays and how. */ + private fun sampleNoteOn(v: SampleVoice, slot: ToolboxSlot, type: ToolboxType, note: Int, velocity: Int) { + if (type == ToolboxType.SAMPLER) { + val pad = SamplerPads.padFor(note) + if (pad !in 0 until SamplerPads.COUNT) return + val s = SampleStore.get(slot.string(SamplerPads.key(pad))) ?: return + v.noteOn(s, note, velocity, note, slot.float(SamplerPads.sliceStartKey(pad), 0f), + slot.float(SamplerPads.sliceEndKey(pad), 1f), slot.float(SamplerPads.volumeKey(pad), SamplerPads.DEFAULT_VOLUME)) + } else { + val s = SampleStore.get(slot.string("sfSample")) ?: return + v.noteOn(s, note, velocity, slot.float("sfRoot", 60f).toInt(), 0f, 1f, slot.float("volume", 0.8f), + slot.float("attack", 0.005f), slot.float("decay", 0.10f), slot.float("sustain", 1f), + slot.float("release", 0.20f), slot.string("loop", "Off") == "On", slot.float("loopXfade", 0f)) } } @@ -91,6 +179,7 @@ class IosGoldenInstruments { val frasil = FrasilVoice(SR) val wave = WaveVoice(SR) val cloud = GrainCloud(SR) + val sampler = SampleVoice(SR) val synthPatch = when (type) { ToolboxType.NES_SYNTH -> SynthPatch.from(slot, TEMPO) ToolboxType.MORPH_PAD -> SynthPatch.forPad(FrasilPatch.from(slot)) @@ -112,12 +201,14 @@ class IosGoldenInstruments { "FRASIL" -> if (e.on) frasil.noteOn(e.midi, e.vel / 127f, frasilPatch!!) else frasil.noteOff() "WAVE" -> if (e.on) wave.noteOn(e.midi, e.vel / 127f, wavePatch!!) else wave.noteOff() "GRAIN" -> if (e.on) cloud.noteOn(e.midi, e.vel, GrainCloud.OWNER_LIVE) else cloud.noteOff(e.midi) + "SAMPLE" -> if (e.on) sampleNoteOn(sampler, slot, type, e.midi, e.vel) else sampler.noteOff() } } y[i] = when (kind) { "SYNTH" -> synth.render() "FRASIL" -> frasil.render() "WAVE" -> wave.render() + "SAMPLE" -> sampler.render() else -> cloud.render() } } @@ -143,5 +234,6 @@ class IosGoldenInstruments { const val TEMPO = 120f const val BLOCK = 256 const val FRAMES = 72_000 // 1.5 s + const val SAMPLE_ID = "ios-golden-sample" } } diff --git a/ios/core/include/sizzle/TestVoice.hpp b/ios/core/include/sizzle/TestVoice.hpp index 1922fcc..ebf667f 100644 --- a/ios/core/include/sizzle/TestVoice.hpp +++ b/ios/core/include/sizzle/TestVoice.hpp @@ -29,6 +29,15 @@ struct TestVoiceSetup { int sampleRate; float tempoBpm; double clock0; // FrasilClock.seconds when the scenario started + // kind "SAMPLE": the test sample (mono), its rate and loop points (-1 = none) + const float *sample = nullptr; + int sampleLength = 0; + int sampleRate2 = 0; + int loopStart = -1, loopEnd = -1; + // Kotlin's global seed counters right before the scenario built its voices + // (FrasilVoice, GrainCloud): a SynthVoice's Morph Pad voice takes the next + // Frasil seed, then the FRASIL kind's voice, then the GrainCloud the next grain one. + uint32_t frasilSeeds = 0, grainSeeds = 0; }; /** kind "SYNTH": SynthVoice with the engine's patch for [setup.type]. */ @@ -39,6 +48,9 @@ std::unique_ptr makeFrasilTestVoice(const TestVoiceSetup &setup); std::unique_ptr makeWaveTestVoice(const TestVoiceSetup &setup); /** kind "GRAIN": GrainCloud (Grain Cloud), notes owned by live input. */ std::unique_ptr makeGrainTestVoice(const TestVoiceSetup &setup); +/** kind "SAMPLE": SampleVoice with the engine's voiceSample() settings for + * [setup.type] (SAMPLER: pads by note; SOUNDFONT: sfRoot, envelope, loop). */ +std::unique_ptr makeSampleTestVoice(const TestVoiceSetup &setup); std::unique_ptr makeTestVoice(const char *kind, const TestVoiceSetup &setup); diff --git a/ios/core/src/TestVoices.cpp b/ios/core/src/TestVoices.cpp index 5aa9912..dc20acd 100644 --- a/ios/core/src/TestVoices.cpp +++ b/ios/core/src/TestVoices.cpp @@ -16,12 +16,14 @@ SIZZLE_TEST_MAKER(makeSynthTestVoice) SIZZLE_TEST_MAKER(makeFrasilTestVoice) SIZZLE_TEST_MAKER(makeWaveTestVoice) SIZZLE_TEST_MAKER(makeGrainTestVoice) +SIZZLE_TEST_MAKER(makeSampleTestVoice) std::unique_ptr 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; } diff --git a/ios/core/src/echofield/EchofieldDefs.hpp b/ios/core/src/echofield/EchofieldDefs.hpp new file mode 100644 index 0000000..4dce016 --- /dev/null +++ b/ios/core/src/echofield/EchofieldDefs.hpp @@ -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 diff --git a/ios/core/src/echofield/GrainCloud.cpp b/ios/core/src/echofield/GrainCloud.cpp new file mode 100644 index 0000000..ff98f5d --- /dev/null +++ b/ios/core/src/echofield/GrainCloud.cpp @@ -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 +#include +#include +#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 diff --git a/ios/core/src/echofield/GrainCloud.hpp b/ios/core/src/echofield/GrainCloud.hpp new file mode 100644 index 0000000..5065412 --- /dev/null +++ b/ios/core/src/echofield/GrainCloud.hpp @@ -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 +#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 diff --git a/ios/core/src/echofield/GrainSources.cpp b/ios/core/src/echofield/GrainSources.cpp new file mode 100644 index 0000000..a284e49 --- /dev/null +++ b/ios/core/src/echofield/GrainSources.cpp @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include "EchofieldDefs.hpp" + +namespace sizzle::echofield::GrainSources { +namespace { + +constexpr double SECONDS = 6.0; +const int N = (int)(RATE * SECONDS); + +using Buf = std::vector; + +// ------------------------------------------------------------------ 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> &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 +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 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> 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> 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> 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> 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 ready[COUNT]; +std::mutex buildLock; // builders only (never the audio thread) +std::atomic 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 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 diff --git a/ios/core/src/echofield/GrainSources.hpp b/ios/core/src/echofield/GrainSources.hpp new file mode 100644 index 0000000..e91833b --- /dev/null +++ b/ios/core/src/echofield/GrainSources.hpp @@ -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 diff --git a/ios/core/src/echofield/GrainTestVoice.cpp b/ios/core/src/echofield/GrainTestVoice.cpp new file mode 100644 index 0000000..b32e030 --- /dev/null +++ b/ios/core/src/echofield/GrainTestVoice.cpp @@ -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 +#include +#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 makeGrainTestVoice(const TestVoiceSetup &setup) { + echofield::GrainSources::prewarmBlocking(); + return std::make_unique(setup, exportSeed(setup)); +} + +} // namespace sizzle diff --git a/ios/core/src/echofield/Sample.hpp b/ios/core/src/echofield/Sample.hpp new file mode 100644 index 0000000..795fba7 --- /dev/null +++ b/ios/core/src/echofield/Sample.hpp @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +// The part of SampleStore.kt the Grain Cloud needs: SampleStore.Sample, mono float +// PCM at its own rate. Minimal on purpose; the sampler port (core/src/sampler) can +// adopt or replace it. + +#include + +namespace sizzle::echofield { + +struct Sample { + std::vector data; + int sampleRate = 0; + int loopStart = -1; + int loopEnd = -1; +}; + +} // namespace sizzle::echofield diff --git a/ios/core/src/frasil/FrasilDefs.cpp b/ios/core/src/frasil/FrasilDefs.cpp new file mode 100644 index 0000000..85b5bce --- /dev/null +++ b/ios/core/src/frasil/FrasilDefs.cpp @@ -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 +#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 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 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 diff --git a/ios/core/src/frasil/FrasilTestVoice.cpp b/ios/core/src/frasil/FrasilTestVoice.cpp new file mode 100644 index 0000000..09400b9 --- /dev/null +++ b/ios/core/src/frasil/FrasilTestVoice.cpp @@ -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 +#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 makeFrasilTestVoice(const TestVoiceSetup &setup) { + return std::make_unique(setup); +} + +} // namespace sizzle diff --git a/ios/core/src/frasil/FrasilVoice.cpp b/ios/core/src/frasil/FrasilVoice.cpp new file mode 100644 index 0000000..b09e1c5 --- /dev/null +++ b/ios/core/src/frasil/FrasilVoice.cpp @@ -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 +#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 diff --git a/ios/core/src/frasil/FrasilVoice.hpp b/ios/core/src/frasil/FrasilVoice.hpp new file mode 100644 index 0000000..24a3a68 --- /dev/null +++ b/ios/core/src/frasil/FrasilVoice.hpp @@ -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 + +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 diff --git a/ios/core/src/wavetable/JavaRandom.hpp b/ios/core/src/wavetable/JavaRandom.hpp new file mode 100644 index 0000000..7995008 --- /dev/null +++ b/ios/core/src/wavetable/JavaRandom.hpp @@ -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 +#include + +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 diff --git a/ios/core/src/wavetable/WaveDefs.cpp b/ios/core/src/wavetable/WaveDefs.cpp new file mode 100644 index 0000000..623f188 --- /dev/null +++ b/ios/core/src/wavetable/WaveDefs.cpp @@ -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 diff --git a/ios/core/src/wavetable/WaveDefs.hpp b/ios/core/src/wavetable/WaveDefs.hpp new file mode 100644 index 0000000..94ede94 --- /dev/null +++ b/ios/core/src/wavetable/WaveDefs.hpp @@ -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 diff --git a/ios/core/src/wavetable/WaveTables.cpp b/ios/core/src/wavetable/WaveTables.cpp new file mode 100644 index 0000000..21ac944 --- /dev/null +++ b/ios/core/src/wavetable/WaveTables.cpp @@ -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 +#include +#include +#include +#include +#include +#include +#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>; + +// Tables are never freed (lookups are lock-free from the audio thread). +std::atomic gFactory[FACTORY_COUNT]; +std::mutex gBuildMutex; +std::atomic gStarted{false}; + +// ------------------------------------------------------------ building --- + +/** In-place radix-2 complex FFT; [inverse] uses e^{+i} and no 1/N (the synthesis sum). */ +void fft(std::vector &re, std::vector &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 resample(const std::vector &x, int n) { + std::vector 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 &cycle0) { + unsigned sz = (unsigned)cycle0.size(); + bool pow2 = sz != 0 && (sz & (sz - 1)) == 0; // Integer.bitCount(size) == 1 + std::vector resampled; + if (!pow2) resampled = resample(cycle0, 2048); + const std::vector &cycle = pow2 ? cycle0 : resampled; + int m = (int)cycle.size(); + std::vector 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 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 fromSpectra(const char *name, const std::vector &spectra) { + int nf = (int)spectra.size(); + auto table = std::make_unique(name, nf); + for (int k = 0; k < WaveTable::LEVELS; ++k) { + int n = WaveTable::SIZES[k]; + int hk = WaveTable::harmonics(k); + std::vector re(n), im(n); + float *data = table->data(k); + for (int f = 0; f < nf; ++f) { + const std::vector &c = spectra[f].first; + const std::vector &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 fromCycles(const char *name, const std::vector> &cycles) { + std::vector 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 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 makeFactory(int id) { + static double glass[FRAMES][40]; + if (id == 9) makeGlass(glass); + std::vector> cycles(FRAMES); + std::vector 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 state{FREE}; + char id[KEY_LEN] = {}; + int frameLen = 0; + std::atomic table{nullptr}; +}; +CustomEntry gCustom[MAX_CUSTOM]; +std::atomic 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 buildFromSource(const char *id, int frameLen) { + SampleSource src = gSource.load(); + if (!src) return nullptr; + std::vector 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 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 lock(gCustomMutex); + std::unique_ptr 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 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 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 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> 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 diff --git a/ios/core/src/wavetable/WaveTables.hpp b/ios/core/src/wavetable/WaveTables.hpp new file mode 100644 index 0000000..ba479d5 --- /dev/null +++ b/ios/core/src/wavetable/WaveTables.hpp @@ -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 +#include +#include +#include + +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 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 &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 fromSamples(const char *name, const float *x, int n, int frameLen0); + +} // namespace WaveTables + +} // namespace sizzle::wavetable diff --git a/ios/core/src/wavetable/WaveTestVoice.cpp b/ios/core/src/wavetable/WaveTestVoice.cpp new file mode 100644 index 0000000..6c257ad --- /dev/null +++ b/ios/core/src/wavetable/WaveTestVoice.cpp @@ -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 +#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 makeWaveTestVoice(const TestVoiceSetup &setup) { + wavetable::WaveTables::prewarmBlocking(); + return std::make_unique(setup); +} + +} // namespace sizzle diff --git a/ios/core/src/wavetable/WaveVoice.cpp b/ios/core/src/wavetable/WaveVoice.cpp new file mode 100644 index 0000000..e820161 --- /dev/null +++ b/ios/core/src/wavetable/WaveVoice.cpp @@ -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 +#include +#include +#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 diff --git a/ios/core/src/wavetable/WaveVoice.hpp b/ios/core/src/wavetable/WaveVoice.hpp new file mode 100644 index 0000000..fc31471 --- /dev/null +++ b/ios/core/src/wavetable/WaveVoice.hpp @@ -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 +#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 diff --git a/ios/core/tests/golden_test.cpp b/ios/core/tests/golden_test.cpp index 1b990ff..b4c0e0f 100644 --- a/ios/core/tests/golden_test.cpp +++ b/ios/core/tests/golden_test.cpp @@ -22,6 +22,7 @@ #include #include "sizzle/Effect.hpp" #include "sizzle/TestVoice.hpp" +#include "wavetable/WaveTables.hpp" using namespace sizzle; @@ -57,6 +58,9 @@ int main(int argc, char **argv) { int sr = 48000, block = 256, frames = 0; float tempo = 120.f; double clock0 = 0; + int smpRate = 0, loopStart = -1, loopEnd = -1; + long long frasilSeeds = 0, grainSeeds = 0; + std::string table; struct Ev { int frame; bool on; int midi, vel; }; std::vector evs; Params p; @@ -70,6 +74,9 @@ int main(int argc, char **argv) { else if (tag == "block") ls >> block; else if (tag == "frames") ls >> frames; else if (tag == "clock") ls >> clock0; + else if (tag == "sample") ls >> smpRate >> loopStart >> loopEnd; + else if (tag == "seeds") ls >> frasilSeeds >> grainSeeds; + else if (tag == "table") { std::getline(ls, table); if (!table.empty() && table[0] == ' ') table.erase(0, 1); } else if (tag == "on") { Ev e{0, true, 0, 0}; ls >> e.frame >> e.midi >> e.vel; evs.push_back(e); } else if (tag == "off") { Ev e{0, false, 0, 0}; ls >> e.frame >> e.midi; evs.push_back(e); } else if (tag == "p") { @@ -81,8 +88,35 @@ int main(int argc, char **argv) { std::string label = kind.empty() ? type : kind + "_" + type; if (!only.empty() && std::find(only.begin(), only.end(), type) == only.end() && std::find(only.begin(), only.end(), label) == only.end()) continue; + if (kind == "TABLE") { + std::vector want = readF32(dir + "/" + base + ".f32"), got; + wavetable::WaveTables::prewarmBlocking(); + if (const wavetable::WaveTable *t = wavetable::WaveTables::factory(table.c_str())) + for (int l = 0; l < wavetable::WaveTable::LEVELS; ++l) + got.insert(got.end(), t->data(l), t->data(l) + (size_t)t->frames * t->size(l)); + double maxErr = got.size() == want.size() ? 0 : 1e9; size_t at = 0; + for (size_t i = 0; i < got.size() && i < want.size(); ++i) { + double e = std::fabs((double)got[i] - want[i]); + if (!(e <= maxErr)) { maxErr = e; at = i; } + } + bool ok = maxErr < 1e-4; + std::printf("%s %-36s max diff %.3g at %zu\n", ok ? "PASS" : "FAIL", base.c_str(), maxErr, at); + ok ? ++pass : ++fail; + continue; + } if (!kind.empty()) { TestVoiceSetup setup{type.c_str(), &p, sr, tempo, clock0}; + setup.frasilSeeds = (uint32_t)frasilSeeds; + setup.grainSeeds = (uint32_t)grainSeeds; + std::vector smp; + if (smpRate > 0) { + smp = readF32(dir + "/" + base + ".smp.f32"); + setup.sample = smp.data(); + setup.sampleLength = (int)smp.size(); + setup.sampleRate2 = smpRate; + setup.loopStart = loopStart; + setup.loopEnd = loopEnd; + } auto v = makeTestVoice(kind.c_str(), setup); if (!v) { std::printf("SKIP %-36s (not ported)\n", base.c_str()); ++skip; continue; } std::vector want = readF32(dir + "/" + base + ".f32");