From 0d6ed4694f08f3e2a213899499ad0e6ce3c5b811 Mon Sep 17 00:00:00 2001 From: Reactorcoremeltdown Date: Wed, 18 Nov 2026 20:54:34 +0100 Subject: [PATCH] 0.42.0 (78): preset randomizer for five devices (Android and iOS) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A RANDOM button in the preset bar of the Synth, Morph Pad, Grain Cloud, Wavetable and Ambience Reverb editors: it rolls a playable patch and names it. The rules live in core/src/model/Randomizer.cpp and are shared, so a seed gives the same patch on both platforms. Android reaches it over JNI as preset text and imports it; iOS writes the Params into the slot. Neither touches the slot's own files — a loaded sample or an imported wavetable survives a roll, because the dice are for the settings, not for the sounds. Scattering values over the parameter ranges produces silence and the occasional scream, so the rules encode three things instead: something always sounds (a layer is always up, an envelope that decays to nothing gets a body, a filter is never shut, a reverb is never fully dry); levels share a budget and resonance, drive and saturation stay out of the range where a patch screams; and tunings come from consonant intervals rather than a uniform draw. core/tests/randomizer_test.cpp is the specification: it renders every device over hundreds of seeds through the real voice and fails on anything out of range, silent, clipping or non-finite. Every bound that looks arbitrary was put there by a seed it caught — a band-pass parked above the note (peak 0.010 against a 0.3 median), a Vel -> Cutoff mod slot closing the filter (0.41 -> 0.02), a choir-only Morph Pad through its own band-pass, and MORPH TO, which a roll now leaves alone because MORPH TIME carries a held note all the way onto a factory drone at a level the randomizer never chose (1.33 with every layer of its own at zero). --dump [key=value ...] re-renders one roll with overrides, which is how each of those was found. Also fixes the shared engine not compiling outside Apple's toolchain: a missing in core/include/sizzle/Model.hpp. No change to the apps, but the engine's tests and benchmark now build with GCC too — which is how the rules above were iterated while the Mac was unreachable. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 17 + app/src/main/cpp/jni_engine.cpp | 20 + .../android/sizzle/audio/NativeEngine.kt | 15 + .../android/sizzle/ui/AppViewModel.kt | 26 + .../sizzle/ui/toolbox/ToolboxScreen.kt | 13 + core/include/sizzle/Model.hpp | 1 + core/include/sizzle/Randomizer.hpp | 56 +++ core/src/model/Randomizer.cpp | 468 ++++++++++++++++++ core/tests/randomizer_test.cpp | 270 ++++++++++ docs/DEVELOPER_HANDOVER.md | 59 ++- docs/USER_GUIDE.md | 22 + ios/CHANGELOG.md | 11 + ios/Makefile | 9 +- ios/README.md | 1 + ios/app/Host/Screens/Toolbox/SlotEditor.swift | 10 + ios/app/Host/SizzleSession.h | 6 + ios/app/Host/SizzleSession.mm | 29 ++ versions.properties | 4 +- 18 files changed, 1033 insertions(+), 4 deletions(-) create mode 100644 core/include/sizzle/Randomizer.hpp create mode 100644 core/src/model/Randomizer.cpp create mode 100644 core/tests/randomizer_test.cpp diff --git a/CHANGELOG.md b/CHANGELOG.md index 96dd139..c1973c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,23 @@ version in `versions.properties`; versions before 0.28.0 are described in the gi log (one commit per version). Since 0.37.0 Android and iOS share one version and one feature set; the iOS side of each version is in `ios/CHANGELOG.md`. +## 0.42.0 (versionCode 78) + +- **RANDOM:** the Synth, Morph Pad, Grain Cloud, Wavetable and Ambience Reverb + editors have a RANDOM button in the preset bar. It throws a new patch into the + editor and names it ("Hazy Drift"). It is a starting point rather than a slot + machine: a roll is always something you can hear and never something that + clips, because levels, filters and envelopes are drawn inside ranges that keep a + patch in that territory instead of scattered over the whole knob. It replaces + the editor's settings like loading a preset does, so SAVE first if you want to + keep what is there — but it never touches a sample you loaded or a wavetable you + imported. The other devices have none on purpose: a Sampler is only as + interesting as the sound you put in it, and the MIDI effects have too few + settings for a dice roll to say anything. (iOS has the same in 0.42.0.) +- Fix: the shared engine did not compile outside Apple's toolchain — a missing + `` in `core/include/sizzle/Model.hpp`. No change to the apps; it means + the engine's tests and benchmark now build with GCC too. + ## 0.41.1 (versionCode 77) <<<<<<< HEAD diff --git a/app/src/main/cpp/jni_engine.cpp b/app/src/main/cpp/jni_engine.cpp index 1a2c369..b8e86ee 100644 --- a/app/src/main/cpp/jni_engine.cpp +++ b/app/src/main/cpp/jni_engine.cpp @@ -12,6 +12,7 @@ #include #include "host/EngineHost.hpp" +#include "sizzle/Randomizer.hpp" using sizzle::host::EngineHost; @@ -127,6 +128,25 @@ JNI_FN(void, nativeEndCapture)(JNIEnv *, jobject) { H->recorder().endCapture(); JNI_FN(void, nativeExternalClockStart)(JNIEnv *, jobject) { H->externalClockStart(); } JNI_FN(void, nativeExternalClockStop)(JNIEnv *, jobject) { H->externalClockStop(); } +// The preset randomizer (core/src/model/Randomizer.cpp). Pure functions of type and +// seed — no engine involved — so unlike everything above they work before +// nativeCreate and cannot be affected by what the audio thread is doing. +JNI_FN(jboolean, nativeCanRandomize)(JNIEnv *env, jobject, jstring type) { + return sizzle::model::canRandomize(str(env, type).c_str()) ? JNI_TRUE : JNI_FALSE; +} + +/** A random patch as preset text (io/PresetIo's format), for PresetIo.import. */ +JNI_FN(jstring, nativeRandomPreset)(JNIEnv *env, jobject, jstring type, jint seed) { + const std::string text = sizzle::model::randomPresetText(str(env, type).c_str(), (uint32_t)seed); + return env->NewStringUTF(text.c_str()); +} + +/** The name that goes with that seed (PresetIo.import does not carry NAME through). */ +JNI_FN(jstring, nativeRandomName)(JNIEnv *env, jobject, jstring type, jint seed) { + const std::string name = sizzle::model::randomName(str(env, type).c_str(), (uint32_t)seed); + return env->NewStringUTF(name.c_str()); +} + /** The AudioTrack fallback's render: [frames] interleaved stereo frames into [out]. */ JNI_FN(void, nativeRender)(JNIEnv *env, jobject, jfloatArray out, jint frames) { EngineHost *h = host(); diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/NativeEngine.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/NativeEngine.kt index 26768c6..c66a1bb 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/NativeEngine.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/NativeEngine.kt @@ -27,6 +27,18 @@ object NativeEngine { fun removeSample(id: String) { if (created) nativeRemoveSample(id) } + // ---- the preset randomizer (core/src/model/Randomizer.cpp) ---- + // Gated on [loaded], not [created]: these need no engine, only the library. + + /** Does this device type have a randomizer? */ + fun canRandomize(type: String): Boolean = loaded && nativeCanRandomize(type) + + /** A random patch for [type] as preset text, or "" — feed it to PresetIo.import. */ + fun randomPreset(type: String, seed: Int): String = if (loaded) nativeRandomPreset(type, seed) else "" + + /** The name belonging to that same [seed]. */ + fun randomName(type: String, seed: Int): String = if (loaded) nativeRandomName(type, seed) else "" + external fun nativeCreate(sampleRate: Int) external fun nativeLoad(text: String) external fun nativeSync(text: String) @@ -62,4 +74,7 @@ object NativeEngine { external fun nativeExternalClockStart() external fun nativeExternalClockStop() external fun nativeRender(out: FloatArray, frames: Int) + external fun nativeCanRandomize(type: String): Boolean + external fun nativeRandomPreset(type: String, seed: Int): String + external fun nativeRandomName(type: String, seed: Int): String } diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt index de485f4..2d2d438 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt @@ -1405,6 +1405,32 @@ class AppViewModel( return ok } + /** Does this device have a dice button? (The randomizer lives in core/.) */ + fun canRandomize(type: cc.tiredsysadmin.android.sizzle.model.ToolboxType): Boolean = + cc.tiredsysadmin.android.sizzle.audio.NativeEngine.canRandomize(type.name) + + /** + * Roll a new patch into [slot]: a playable one, generated by core/'s randomizer + * (the same rules and the same seeds as iOS). The slot's own files are kept — + * a loaded sample or an imported wavetable is the user's, and a dice roll of the + * *settings* must not throw it away — so the keys the device's parameter list + * doesn't name (`sfSample`, `sfFile`, the Sampler's pads) are put back afterwards. + */ + fun randomizeSlot(slot: cc.tiredsysadmin.android.sizzle.model.ToolboxSlot): Boolean { + val type = slot.type ?: return false + val seed = java.util.concurrent.ThreadLocalRandom.current().nextInt() + val text = cc.tiredsysadmin.android.sizzle.audio.NativeEngine.randomPreset(type.name, seed) + if (text.isBlank()) return false + val keep = slot.values.filterKeys { key -> type.params.none { it.key == key } } + if (!cc.tiredsysadmin.android.sizzle.io.PresetIo.import(slot, text)) return false + keep.forEach { (k, v) -> slot.set(k, v) } + slot.name = cc.tiredsysadmin.android.sizzle.audio.NativeEngine.randomName(type.name, seed) + .ifBlank { type.displayName } + engine.rebuildFxChains() + touched() + return true + } + /** Import a preset from picked bytes: a `.zip` bundle (Sampler) or plain text. */ fun importPreset(slot: cc.tiredsysadmin.android.sizzle.model.ToolboxSlot, bytes: ByteArray): Boolean { val isZip = bytes.size >= 2 && bytes[0] == 'P'.code.toByte() && bytes[1] == 'K'.code.toByte() diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ToolboxScreen.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ToolboxScreen.kt index 42a4b0a..e319020 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ToolboxScreen.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ToolboxScreen.kt @@ -49,8 +49,10 @@ import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow @@ -532,6 +534,7 @@ private fun MidiLearnPopup(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> U private fun PresetBar(vm: AppViewModel, slot: ToolboxSlot) { val c = LocalRetro.current val context = LocalContext.current + val haptics = LocalHapticFeedback.current @Suppress("UNUSED_VARIABLE") val rev = vm.revision // refresh the list after save/import val type = slot.type ?: return @@ -589,6 +592,16 @@ private fun PresetBar(vm: AppViewModel, slot: ToolboxSlot) { RetroButton("DELETE", danger = true) { confirmDelete = current } Spacer(Modifier.width(20.dp)) } + // RANDOM only for the devices core/'s randomizer covers (the Synth, Morph + // Pad, Grain Cloud, Wavetable and Ambience). It replaces the settings in + // place, like loading a preset; the slot's own sample or table is kept. + if (vm.canRandomize(type)) { + RetroButton("RANDOM") { + haptics.performHapticFeedback(HapticFeedbackType.LongPress) + vm.randomizeSlot(slot) + selected = null + } + } RetroButton("SAVE") { showSave = true } RetroButton("IMPORT") { // Accept text presets and (for the Sampler) zip bundles. diff --git a/core/include/sizzle/Model.hpp b/core/include/sizzle/Model.hpp index 9cf86a1..22f0c68 100644 --- a/core/include/sizzle/Model.hpp +++ b/core/include/sizzle/Model.hpp @@ -12,6 +12,7 @@ // thread. Toolbox values are text (sizzle::Params), as ToolboxSlot's map is. #include +#include #include #include #include "sizzle/Params.hpp" diff --git a/core/include/sizzle/Randomizer.hpp b/core/include/sizzle/Randomizer.hpp new file mode 100644 index 0000000..fbc0510 --- /dev/null +++ b/core/include/sizzle/Randomizer.hpp @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +// The preset pseudorandomizer: a playable patch from a seed, for the five devices +// where "surprise me" is a musical thing to ask for. Shared by both apps (handover +// §5.4.2's parity rule), so a roll of the dice gives the same patch on Android and +// on iOS for the same seed. +// +// "Playable" is the whole point, and it is what makes this more than scattering +// values over the parameter ranges: +// +// - audible. Something always sounds: at least one oscillator or layer is up, an +// amp envelope that decays to nothing gets a body, a filter is never shut, and +// a reverb is never fully dry. +// - inside the rails. Oscillator levels share a budget, resonance, drive and +// saturation stay below the range where a patch screams, and the reverb's wet +// and dry cannot both sit at 0 dB. `randomizer_test` renders every device over +// many seeds and fails if a patch comes out silent or clipping. +// - musical where it matters. Tunings come from consonant intervals rather than +// a uniform draw over ±12 semitones, detune stays inside a chorus, and pitch +// modulation is small enough to stay in tune. +// +// Nothing structural is rolled: a sample or an imported wavetable is the user's +// choice, so "Custom" sources and tables are never picked, and the sample keys a +// slot already holds are left alone. + +#include +#include + +#include "sizzle/Params.hpp" + +namespace sizzle::model { + +/** True when [type] (a ToolboxType name) has a randomizer: NES_SYNTH, MORPH_PAD, + * GRAIN_CLOUD, WAVETABLE and AMBIENCE. The UI shows its dice button for these. */ +bool canRandomize(const char *type); + +/** Fill [out] with a playable random patch for [type]. Every value is written + * through the device's own ParamSpec, so nothing can land outside its range or + * off an enum's choices. [seed] makes it reproducible: the same seed is the same + * patch, here and on the other platform. Returns false, leaving [out] untouched, + * for a type with no randomizer. */ +bool randomize(const char *type, uint32_t seed, Params &out); + +/** A short two-word name for the patch [seed] produces ("Hazy Drift"), so a roll + * arrives with something to call it and SAVE has a name to offer. Empty for a + * type with no randomizer. */ +std::string randomName(const char *type, uint32_t seed); + +/** The whole thing as preset text (io::PresetIo's format, NAME included) — what + * the Android app receives over JNI and hands to PresetIo.import. Empty for a + * type with no randomizer. */ +std::string randomPresetText(const char *type, uint32_t seed); + +} // namespace sizzle::model diff --git a/core/src/model/Randomizer.cpp b/core/src/model/Randomizer.cpp new file mode 100644 index 0000000..9f73b1b --- /dev/null +++ b/core/src/model/Randomizer.cpp @@ -0,0 +1,468 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +// See sizzle/Randomizer.hpp for what a "playable" patch means here and why the +// rules look the way they do. Choice lists are never repeated in this file: every +// enum is picked by index out of the device's own ParamSpec, so a list that gains +// or loses an entry in Kotlin carries through on its own. + +#include "sizzle/Randomizer.hpp" + +#include +#include + +#include "KotlinMath.hpp" +#include "io/PresetIo.hpp" +#include "sizzle/Model.hpp" +#include "sizzle/Specs.hpp" + +namespace sizzle::model { + +namespace { + +constexpr const char *kRandomizable[] = {"NES_SYNTH", "MORPH_PAD", "GRAIN_CLOUD", "WAVETABLE", "AMBIENCE"}; + +/** The engine's xorshift, so a seed means the same thing here as everywhere else. */ +struct Rng { + uint32_t s; + explicit Rng(uint32_t seed) : s(seed ? seed : 0x9E3779B9u) {} + uint32_t next() { s ^= s << 13; s ^= s >> 17; s ^= s << 5; return s; } + /** 0 .. 1 (never quite 1). */ + float unit() { return (float)next() * 2.3283064e-10f; } + float range(float lo, float hi) { return lo + unit() * (hi - lo); } + /** Like range, but bunched toward [lo]: `power` 2 spends most draws in the + * lower third. Times, amounts and anything where "a little" is the common + * musical answer and "a lot" is the exception. */ + float curve(float lo, float hi, float power) { return lo + std::pow(unit(), power) * (hi - lo); } + int intIn(int lo, int hi) { return hi <= lo ? lo : lo + (int)(next() % (uint32_t)(hi - lo + 1)); } + bool chance(float p) { return unit() < p; } + template int pick(const int (&a)[N]) { return a[intIn(0, N - 1)]; } +}; + +const ParamSpec *specFor(const DeviceSpec &dev, const char *key) { + for (int i = 0; i < dev.paramCount; ++i) + if (std::strcmp(dev.params[i].key, key) == 0) return &dev.params[i]; + return nullptr; +} + +/** Write a number, clamped to the parameter's own range and snapped if it is an + * int. A rule with a bound slightly off therefore still produces a legal patch; + * the bounds are musical intent, this is the rail. Unknown keys are dropped. */ +void put(Params &p, const DeviceSpec &dev, const char *key, float v) { + const ParamSpec *ps = specFor(dev, key); + if (!ps) return; + float x = kt::coerceIn(v, ps->min, ps->max); + if (ps->isInt) x = (float)kt::roundToInt(x); + p.set(key, x); +} + +/** Write an enum by index into its own choice list (clamped). */ +void putChoice(Params &p, const DeviceSpec &dev, const char *key, int index) { + const ParamSpec *ps = specFor(dev, key); + if (!ps || !ps->isEnum()) return; + const int n = ps->choiceCount(); + if (n <= 0) return; + p.set(key, ps->choices[kt::coerceIn(index, 0, n - 1)]); +} + +int choiceCount(const DeviceSpec &dev, const char *key) { + const ParamSpec *ps = specFor(dev, key); + return ps && ps->isEnum() ? ps->choiceCount() : 0; +} + +/** A random choice index, with the last [skipTail] entries left out — the lists + * that end in "Custom" mean "the user's own sample", which a dice roll must not + * invent. */ +int pickChoice(Rng &r, const DeviceSpec &dev, const char *key, int skipTail = 0) { + const int n = choiceCount(dev, key) - skipTail; + return n <= 0 ? 0 : r.intIn(0, n - 1); +} + +/** A cutoff that suits the filter type. Both the Morph Pad and the Wavetable offer + * the same Low / Band / High list, and only Low is open at the top: a band-pass has + * to sit near the played pitch to pass it and a high-pass has to stay under it, so + * rolling the whole 0..1 range for those two is how a patch comes out silent with + * every oscillator up. (Measured: the quietest rolls of both devices were a band-pass + * at 0.83 and 0.95, peaking at 0.010 and 0.025 against a median near 0.3.) */ +float cutoffFor(Rng &r, int filterType, float lowLo, float lowHi) { + switch (filterType) { + case 1: return r.range(0.20f, 0.60f); // Band: around the note, not above it + case 2: return r.range(0.10f, 0.45f); // High: under it, or nothing is left + default: return r.range(lowLo, lowHi); // Low: open at the top + } +} + +/** Consonant intervals, in semitones: a dice roll over ±12 mostly lands on + * something sour, and these are what a second oscillator is usually set to. */ +constexpr int kIntervals[] = {0, 0, 0, 3, 4, 5, 7, 12, -12}; +/** Octave offsets, weighted toward the root's own octave. */ +constexpr int kOctaves[] = {-1, 0, 0, 0, 1}; + +// ------------------------------------------------------------------ the synth + +void randomizeSynth(Rng &r, const DeviceSpec &dev, Params &p) { + // Oscillators. The voice sums them straight (SynthVoice: `mix += wave * level`) + // before a filter that can add resonant gain of its own, so the levels share a + // budget rather than each taking the full range. + constexpr float kLevelBudget = 1.25f; + const int active = r.chance(0.55f) ? 2 : (r.chance(0.5f) ? 1 : 3); + float level[3] = {0.f, 0.f, 0.f}; + + for (int i = 0; i < 3; ++i) { + putChoice(p, dev, (std::string("osc") + std::to_string(i) + "wave").c_str(), + pickChoice(r, dev, "osc0wave")); + const std::string pre = "osc" + std::to_string(i); + if (i >= active) { put(p, dev, (pre + "level").c_str(), 0.f); continue; } + if (i == 0) { + // Oscillator 1 is the pitch the player hears: it stays at the root. + put(p, dev, (pre + "oct").c_str(), 0.f); + put(p, dev, (pre + "semi").c_str(), 0.f); + put(p, dev, (pre + "fine").c_str(), r.range(-4.f, 4.f)); + level[i] = r.range(0.55f, 0.90f); + } else { + put(p, dev, (pre + "oct").c_str(), (float)r.pick(kOctaves)); + put(p, dev, (pre + "semi").c_str(), (float)r.pick(kIntervals)); + put(p, dev, (pre + "fine").c_str(), r.range(-10.f, 10.f)); + level[i] = r.range(0.25f, 0.65f); + } + } + const float noise = r.chance(0.3f) ? r.curve(0.f, 0.18f, 2.f) : 0.f; + float sum = noise; + for (float l : level) sum += l; + const float scale = sum > kLevelBudget ? kLevelBudget / sum : 1.f; + for (int i = 0; i < 3; ++i) + put(p, dev, (std::string("osc") + std::to_string(i) + "level").c_str(), level[i] * scale); + put(p, dev, "noise", noise * scale); + + // Filter. Never shut (nothing would come out) and never near self-oscillation. + // A negative contour sweeps the cutoff *down* as the note sounds, so it only + // gets a patch that starts open — otherwise the two together close the filter + // on a sound that has not been heard yet. + const bool downwardSweep = !r.chance(0.75f); + const float fenvamt = downwardSweep ? r.range(-0.50f, -0.10f) : r.range(0.10f, 0.80f); + put(p, dev, "cutoff", downwardSweep ? r.range(0.65f, 0.95f) : r.range(0.40f, 0.95f)); + put(p, dev, "reso", r.curve(0.f, 0.45f, 1.6f)); + put(p, dev, "keytrack", r.range(0.15f, 0.80f)); + put(p, dev, "fenvamt", fenvamt); + put(p, dev, "fatk", r.curve(0.001f, 0.60f, 2.2f)); + put(p, dev, "fdec", r.curve(0.05f, 1.50f, 1.6f)); + put(p, dev, "fsus", r.range(0.15f, 0.90f)); + put(p, dev, "frel", r.curve(0.05f, 1.50f, 1.6f)); + + // Amp envelope. A quiet sustain with a quick decay is a click, not a patch, so + // a low sustain buys a longer decay to speak through. + put(p, dev, "attack", r.curve(0.001f, 0.50f, 2.4f)); + const float sustain = r.range(0.30f, 0.95f); + float decay = r.curve(0.05f, 1.20f, 1.6f); + if (sustain < 0.40f) decay = kt::coerceAtLeast(decay, 0.40f); + put(p, dev, "decay", decay); + put(p, dev, "sustain", sustain); + put(p, dev, "release", r.curve(0.06f, 1.40f, 1.6f)); + + putChoice(p, dev, "lfowave", pickChoice(r, dev, "lfowave")); + put(p, dev, "lfodiv", (float)r.intIn(0, 6)); + putChoice(p, dev, "lfophase", pickChoice(r, dev, "lfophase")); + + // Mod matrix: clear it, then light up a couple of slots. + const int srcCount = choiceCount(dev, "m0src"); + const int dstCount = choiceCount(dev, "m0dst"); + for (int n = 0; n < 4; ++n) { + const std::string pre = "m" + std::to_string(n); + putChoice(p, dev, (pre + "src").c_str(), 0); // "Off" + putChoice(p, dev, (pre + "dst").c_str(), 0); + put(p, dev, (pre + "amt").c_str(), 0.f); + } + const int slots = r.intIn(0, 2); + for (int n = 0; n < slots; ++n) { + const std::string pre = "m" + std::to_string(n); + const int dst = dstCount > 0 ? r.intIn(0, dstCount - 1) : 0; + putChoice(p, dev, (pre + "src").c_str(), srcCount > 1 ? r.intIn(1, srcCount - 1) : 0); + putChoice(p, dev, (pre + "dst").c_str(), dst); + // MOD_DST is Pitch, Osc2, Osc3, Cutoff, PWM, Amp. Four of the six can take a + // healthy patch down to nothing on their own, so they are bounded instead of + // getting the full range — and Cutoff asymmetrically, because opening a + // filter is free and closing it is not. (Measured: a Vel -> Cutoff slot at + // -0.69 turned a patch with a square at 0.87 and the cutoff at 0.66 from + // peak 0.41 into peak 0.02.) + float lo = -0.70f, hi = 0.70f; + switch (dst) { + case 0: lo = -0.18f; hi = 0.18f; break; // Pitch: a patch should stay in tune + case 3: lo = -0.30f; hi = 0.70f; break; // Cutoff: open freely, close a little + case 4: lo = -0.45f; hi = 0.45f; break; // PWM: past this a pulse is a sliver + case 5: lo = -0.30f; hi = 0.30f; break; // Amp: never enough to gate the voice off + default: break; // Osc2 / Osc3 levels + } + put(p, dev, (pre + "amt").c_str(), r.range(lo, hi)); + } +} + +// --------------------------------------------------------------- the morph pad + +void randomizeMorphPad(Rng &r, const DeviceSpec &dev, Params &p) { + // Three layers, summed into one voice: at least one has to carry the sound, and + // all three near the top is where a pad stops being a pad and starts clipping, + // so they share a budget the way the synth's oscillators do. + constexpr float kLayerBudget = 1.45f; + float choir = r.chance(0.80f) ? r.range(0.35f, 0.95f) : 0.f; + float partials = r.chance(0.80f) ? r.range(0.30f, 0.95f) : 0.f; + float breath = r.chance(0.60f) ? r.range(0.10f, 0.60f) : 0.f; + if (choir + partials + breath < 0.50f) choir = r.range(0.60f, 0.95f); + const float layers = choir + partials + breath; + if (layers > kLayerBudget) { + const float scale = kLayerBudget / layers; + choir *= scale; partials *= scale; breath *= scale; + } + put(p, dev, "choir", choir); + put(p, dev, "partials", partials); + put(p, dev, "breath", breath); + + put(p, dev, "timbre", r.range(0.20f, 0.85f)); + put(p, dev, "warmth", r.curve(0.f, 0.45f, 1.8f)); // drive: modest, or it buzzes + put(p, dev, "body", r.range(0.55f, 1.0f)); // the high-pass: keep the fundamental + put(p, dev, "attack", r.range(0.25f, 0.95f)); // a pad, so never a transient + put(p, dev, "release", r.range(0.40f, 0.95f)); + put(p, dev, "velsens", r.range(0.10f, 0.70f)); + put(p, dev, "motion", r.range(0.10f, 0.80f)); + put(p, dev, "mrate", r.range(0.20f, 0.80f)); + put(p, dev, "tide", r.range(0.f, 0.60f)); + put(p, dev, "tperiod", r.range(0.20f, 0.80f)); + put(p, dev, "detune", r.range(0.20f, 0.75f)); + + // Choir filter, with a cutoff that suits the type (see cutoffFor). It filters the + // choir alone — the partials and the breath go round it — so a patch whose choir + // is the only thing sounding has nothing left if that filter is a narrow band. + // It gets a plain low-pass instead, and an open one. (Measured: the quietest roll + // of all was exactly this, choir 0.82 alone through a band-pass, peak 0.017.) + const bool choirAlone = partials <= 0.f && breath <= 0.f; + const int ctype = choirAlone ? 0 : (r.chance(0.60f) ? 0 : (r.chance(0.62f) ? 1 : 2)); + putChoice(p, dev, "ctype", ctype); + put(p, dev, "cfilter", choirAlone ? r.range(0.45f, 0.90f) : cutoffFor(r, ctype, 0.25f, 0.85f)); + put(p, dev, "creso", r.curve(0.f, 0.50f, 1.8f)); + put(p, dev, "shape", r.range(0.f, 0.70f)); + put(p, dev, "soft", r.range(0.f, 0.70f)); + putChoice(p, dev, "interval", pickChoice(r, dev, "interval")); + + put(p, dev, "tilt", r.range(0.20f, 0.85f)); + put(p, dev, "odd", r.range(0.f, 0.70f)); + put(p, dev, "stretch", r.curve(0.f, 0.50f, 2.f)); + put(p, dev, "evolve", r.range(0.f, 0.70f)); + put(p, dev, "beat", r.range(0.f, 0.50f)); + put(p, dev, "formant", r.range(0.20f, 0.90f)); + put(p, dev, "peak", r.curve(0.f, 0.50f, 1.8f)); + + put(p, dev, "bres", r.range(0.30f, 0.90f)); + put(p, dev, "color", r.range(0.f, 0.80f)); + put(p, dev, "grain", r.curve(0.f, 0.50f, 2.f)); + putChoice(p, dev, "bpitch", pickChoice(r, dev, "bpitch")); + put(p, dev, "btone", r.range(0.20f, 0.85f)); + put(p, dev, "air", r.curve(0.f, 0.50f, 2.f)); + + // MORPH TO stays Off, and it is the one knob here a roll deliberately leaves + // alone. Two reasons, and the first is measured: a target is one of FRASIL's + // factory drones, MORPH TIME carries a held note all the way onto it, and from + // then on the note *is* that preset at a level this randomizer never chose — + // seeds that landed on "Static" peaked at 1.33 with every layer of their own + // turned down to zero. Budgeting cannot reach past the morph. The second is + // that "morph toward this named sound" is a musical decision between two + // sounds, like picking a sample: the roll gives a fresh sound to start from and + // leaves the destination to the player. + putChoice(p, dev, "morphTo", 0); + put(p, dev, "morph", 0.f); + put(p, dev, "mtime", 0.f); +} + +// -------------------------------------------------------------- the grain cloud + +void randomizeGrainCloud(Rng &r, const DeviceSpec &dev, Params &p) { + // SOURCES ends in "Custom" (the user's own sample): never rolled. + putChoice(p, dev, "source", pickChoice(r, dev, "source", 1)); + putChoice(p, dev, "mode", pickChoice(r, dev, "mode")); + putChoice(p, dev, "window", pickChoice(r, dev, "window")); + putChoice(p, dev, "freeze", 0); // "Off": frozen is a performance move, not a patch + + put(p, dev, "position", r.range(0.05f, 0.90f)); + put(p, dev, "texture", r.range(0.25f, 0.95f)); + put(p, dev, "scatter", r.range(0.05f, 0.80f)); + put(p, dev, "drift", r.range(0.f, 0.70f)); + put(p, dev, "motion", r.range(0.f, 0.70f)); + put(p, dev, "pitch", (float)r.pick(kIntervals)); + put(p, dev, "harmony", r.range(0.f, 0.60f)); + put(p, dev, "size_mul", r.range(-1.0f, 1.2f)); + put(p, dev, "dens_mul", r.range(-0.3f, 1.4f)); // low enough and the cloud thins to nothing + put(p, dev, "scan", r.range(-0.6f, 0.6f)); + put(p, dev, "reverse", r.curve(0.f, 0.50f, 1.6f)); + put(p, dev, "pitch_rand", r.curve(0.f, 5.f, 1.8f)); + put(p, dev, "size_rand", r.range(0.f, 0.70f)); + put(p, dev, "grain_tone", r.range(-0.6f, 0.6f)); + put(p, dev, "attack", r.range(0.05f, 0.60f)); + put(p, dev, "release", r.range(0.20f, 0.80f)); + put(p, dev, "velo", r.range(0.20f, 0.80f)); + + // The window into the source has to be wide enough to hold grains. + const float start = r.range(0.f, 0.50f); + put(p, dev, "start", start); + put(p, dev, "end", kt::coerceIn(start + r.range(0.30f, 1.0f), 0.f, 1.f)); + // The cloud auto-levels itself toward one loudness, so this is really how hard + // the overlapping grains are allowed to stack on top of that. + put(p, dev, "level", r.range(0.45f, 0.68f)); +} + +// ---------------------------------------------------------------- the wavetable + +void randomizeWavetable(Rng &r, const DeviceSpec &dev, Params &p) { + // TABLES ends in "Custom" (an imported WAV): never rolled. + constexpr float kLevelBudget = 1.30f; + const bool twoOsc = r.chance(0.60f); + float l1 = r.range(0.55f, 0.90f); + float l2 = twoOsc ? r.range(0.25f, 0.60f) : 0.f; + + putChoice(p, dev, "o1table", pickChoice(r, dev, "o1table", 1)); + put(p, dev, "o1pos", r.range(0.f, 0.85f)); + put(p, dev, "o1oct", (float)r.pick(kOctaves)); + put(p, dev, "o1semi", 0.f); + put(p, dev, "o1fine", r.range(-6.f, 6.f)); + put(p, dev, "o1bend", r.range(-0.50f, 0.50f)); + + putChoice(p, dev, "o2table", pickChoice(r, dev, "o2table", 1)); + put(p, dev, "o2pos", r.range(0.f, 0.85f)); + put(p, dev, "o2oct", twoOsc ? (float)r.pick(kOctaves) : 0.f); + put(p, dev, "o2semi", twoOsc ? (float)r.pick(kIntervals) : 0.f); + put(p, dev, "o2fine", twoOsc ? r.range(-14.f, 14.f) : 0.f); + put(p, dev, "o2bend", r.range(-0.50f, 0.50f)); + + const float sub = r.curve(0.f, 0.40f, 1.5f); + const float noise = r.curve(0.f, 0.12f, 2.f); + const float sum = l1 + l2 + sub + noise; + const float scale = sum > kLevelBudget ? kLevelBudget / sum : 1.f; + put(p, dev, "o1level", l1 * scale); + put(p, dev, "o2level", l2 * scale); + put(p, dev, "sub", sub * scale); + put(p, dev, "noise", noise * scale); + + put(p, dev, "unison", (float)r.intIn(1, 4)); + put(p, dev, "spread", r.range(0.10f, 0.60f)); + put(p, dev, "velsens", r.range(0.20f, 0.80f)); + putChoice(p, dev, "wtframe", 0); // "Auto": frame size belongs to an imported table + + // FILTER_TYPES is Low / Band / High, same shape as the Morph Pad's. + const int ftype = r.chance(0.60f) ? 0 : (r.chance(0.62f) ? 1 : 2); + putChoice(p, dev, "ftype", ftype); + put(p, dev, "cutoff", cutoffFor(r, ftype, 0.45f, 1.0f)); + put(p, dev, "reso", r.curve(0.f, 0.40f, 1.7f)); + put(p, dev, "keytrack", r.range(0.20f, 0.80f)); + put(p, dev, "fenv", r.range(-0.40f, 0.70f)); + put(p, dev, "drive", r.curve(0.f, 0.35f, 1.8f)); // tanh: past this it is all fuzz + + put(p, dev, "attack", r.curve(0.002f, 1.20f, 2.2f)); + const float sustain = r.range(0.35f, 0.95f); + float decay = r.curve(0.10f, 2.0f, 1.6f); + if (sustain < 0.45f) decay = kt::coerceAtLeast(decay, 0.50f); + put(p, dev, "decay", decay); + put(p, dev, "sustain", sustain); + put(p, dev, "release", r.curve(0.15f, 3.0f, 1.6f)); + + put(p, dev, "mattack", r.curve(0.f, 3.0f, 1.8f)); + put(p, dev, "mdecay", r.curve(0.20f, 5.0f, 1.5f)); + put(p, dev, "msustain", r.range(0.20f, 0.90f)); + put(p, dev, "mrelease", r.curve(0.20f, 4.0f, 1.5f)); + put(p, dev, "menvpos", r.range(-0.60f, 0.60f)); + + putChoice(p, dev, "lfowave", pickChoice(r, dev, "lfowave")); + const ParamSpec *div = specFor(dev, "lfodiv"); + put(p, dev, "lfodiv", div ? (float)r.intIn((int)div->min, (int)div->max) : 1.f); + put(p, dev, "lfopos", r.range(0.f, 0.45f)); + put(p, dev, "lfopitch", r.curve(0.f, 0.08f, 2.f)); // small: a patch should stay in tune + put(p, dev, "lfocut", r.range(0.f, 0.50f)); +} + +// ------------------------------------------------------------- ambience reverb + +void randomizeAmbience(Rng &r, const DeviceSpec &dev, Params &p) { + putChoice(p, dev, "algo", pickChoice(r, dev, "algo")); + put(p, dev, "predelay", r.curve(0.f, 120.f, 1.5f)); + put(p, dev, "roomsize", r.range(0.50f, 1.80f)); + put(p, dev, "decay", r.curve(0.40f, 8.0f, 1.7f)); // the range runs to 20 s: a drone, not a space + put(p, dev, "hfdamp", r.range(0.15f, 0.80f)); // always some: an undamped tail piles up + put(p, dev, "lfabsorb", r.curve(0.f, 0.50f, 1.5f)); + put(p, dev, "diffusion", r.range(0.45f, 1.0f)); + put(p, dev, "modamt", r.curve(0.f, 0.50f, 1.4f)); + put(p, dev, "modrate", r.range(0.10f, 1.20f)); + put(p, dev, "erlevel", r.range(0.20f, 0.90f)); + put(p, dev, "saturation", r.curve(0.f, 0.30f, 1.8f)); + + // Wet and dry are the headroom. Both at 0 dB is the loudest thing this device + // can be asked for, and a full-level reverb summed with a full-level dry signal + // is where an insert chain starts clipping — so the wet sits below the dry. + put(p, dev, "wet", r.range(-20.f, -8.f)); + put(p, dev, "dry", r.range(-3.f, 0.f)); + + if (r.chance(0.35f)) { + put(p, dev, "duckamt", r.range(3.f, 10.f)); + put(p, dev, "duckthresh", r.range(-26.f, -12.f)); + put(p, dev, "duckattack", r.curve(1.f, 40.f, 1.5f)); + put(p, dev, "duckrelease", r.curve(40.f, 800.f, 1.4f)); + } else { + put(p, dev, "duckamt", 0.f); + } +} + +// -------------------------------------------------------------------- the name + +/** Two words from the seed. Deliberately atmospheric rather than descriptive — + * the patch is a surprise, and a name like "Dim Drift" is easier to tell apart in + * the preset list than "Random 7". */ +const char *const kAdjectives[] = { + "Hazy", "Glass", "Dim", "Warm", "Wire", "Soft", "Iron", "Pale", + "Deep", "Dry", "Slow", "Bright","Hollow","Velvet","Rust", "Frost", +}; +const char *const kNouns[] = { + "Drift", "Bloom", "Field", "Choir", "Signal","Tide", "Ember", "Static", + "Garden","Column","Current","Veil", "Spark", "Hollow","Echo", "Grain", +}; + +} // namespace + +bool canRandomize(const char *type) { + if (!type) return false; + for (const char *t : kRandomizable) + if (std::strcmp(type, t) == 0) return true; + return false; +} + +bool randomize(const char *type, uint32_t seed, Params &out) { + if (!canRandomize(type)) return false; + const DeviceSpec *dev = findDevice(type); + if (!dev) return false; + + Rng r(seed); + Params p; + p.fill(*dev); // defaults first, so nothing is left unset + + if (std::strcmp(type, "NES_SYNTH") == 0) randomizeSynth(r, *dev, p); + else if (std::strcmp(type, "MORPH_PAD") == 0) randomizeMorphPad(r, *dev, p); + else if (std::strcmp(type, "GRAIN_CLOUD") == 0) randomizeGrainCloud(r, *dev, p); + else if (std::strcmp(type, "WAVETABLE") == 0) randomizeWavetable(r, *dev, p); + else if (std::strcmp(type, "AMBIENCE") == 0) randomizeAmbience(r, *dev, p); + + out = p; + return true; +} + +std::string randomName(const char *type, uint32_t seed) { + if (!canRandomize(type)) return std::string(); + // A stream of its own, so the name does not depend on how many draws a device's + // rules happen to make. + Rng r(seed ^ 0x5BD1E995u); + return std::string(kAdjectives[r.intIn(0, 15)]) + " " + kNouns[r.intIn(0, 15)]; +} + +std::string randomPresetText(const char *type, uint32_t seed) { + ToolboxSlot slot; + if (!canRandomize(type)) return std::string(); + slot.fill(type); + if (!randomize(type, seed, slot.values)) return std::string(); + slot.name = randomName(type, seed); + return io::PresetIo::exportText(slot); +} + +} // namespace sizzle::model diff --git a/core/tests/randomizer_test.cpp b/core/tests/randomizer_test.cpp new file mode 100644 index 0000000..e3d1b04 --- /dev/null +++ b/core/tests/randomizer_test.cpp @@ -0,0 +1,270 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +// The randomizer's promise, checked by playing what it produces: over many seeds, +// every device must come out in range, audible, and with headroom left. A rule in +// Randomizer.cpp that drifts into silence or into clipping fails here rather than +// in someone's track. +// +// randomizer_test [seeds] (default 200 per device) +// +// Per seed it checks three things: +// 1. every value is inside its own ParamSpec (and an enum is one of its choices) +// 2. rendering a note (or, for the reverb, a test signal) is AUDIBLE +// 3. ...and stays under the clipping ceiling, and finite throughout +// +// The thresholds are deliberately generous: this is a net under the rules, not a +// taste test. It prints the measured spread per device so a tightening or a new +// device can be judged against real numbers. + +#include +#include +#include +#include +#include +#include +#include + +#include "echofield/GrainSources.hpp" +#include "sizzle/Effect.hpp" +#include "sizzle/Model.hpp" +#include "sizzle/Randomizer.hpp" +#include "sizzle/Specs.hpp" +#include "voices/TestVoice.hpp" +#include "wavetable/WaveTables.hpp" + +using namespace sizzle; + +namespace { + +constexpr int SR = 48000; + +/** Peak and RMS of a render, and whether every sample was finite. */ +struct Level { + float peak = 0.f; + float rms = 0.f; + size_t peakAt = 0; // sample index of the peak — a startup transient shows up here + bool finite = true; +}; + +Level measure(const std::vector &v) { + Level l; + double sum = 0; + for (size_t i = 0; i < v.size(); ++i) { + const float x = v[i]; + if (!std::isfinite(x)) { l.finite = false; continue; } + const float a = std::fabs(x); + if (a > l.peak) { l.peak = a; l.peakAt = i; } + sum += (double)x * x; + } + l.rms = v.empty() ? 0.f : (float)std::sqrt(sum / (double)v.size()); + return l; +} + +/** One held note through the instrument voice the engine would use, then its tail. */ +Level playInstrument(const char *type, const Params &p, double holdSec, double tailSec) { + const char *kind = std::strcmp(type, "GRAIN_CLOUD") == 0 ? "GRAIN" : "SYNTH"; + TestVoiceSetup setup; + setup.type = type; + setup.params = &p; + setup.sampleRate = SR; + setup.tempoBpm = 120.f; + setup.clock0 = 0.0; + std::unique_ptr voice = makeTestVoice(kind, setup); + if (!voice) return Level{}; + + const int block = 192; + const int hold = (int)(holdSec * SR) / block; + const int tail = (int)(tailSec * SR) / block; + std::vector out; + out.reserve((size_t)(hold + tail) * block); + + voice->blockStart(block); + voice->noteOn(60, 100); + for (int b = 0; b < hold; ++b) { + voice->blockStart(block); + for (int i = 0; i < block; ++i) out.push_back(voice->render()); + } + voice->noteOff(60); + for (int b = 0; b < tail; ++b) { + voice->blockStart(block); + for (int i = 0; i < block; ++i) out.push_back(voice->render()); + } + return measure(out); +} + +/** A test signal through the effect: a decaying saw burst, noise, then silence for + * the tail — the same shape the golden scenarios use. */ +Level playEffect(const char *type, const Params &p) { + std::unique_ptr fx = Effect::create(type, SR); + if (!fx) return Level{}; + fx->update(p, 120.f); + + const int n = (int)(2.0 * SR); + std::vector out; + out.reserve((size_t)n); + uint32_t seed = 0x1234567u; + for (int i = 0; i < n; ++i) { + const double t = (double)i / SR; + float x = 0.f; + if (t < 0.6) { + x = (float)(0.6 * (2.0 * std::fmod(t * 110.0, 1.0) - 1.0) * std::exp(-t * 4.0)); + } else if (t < 1.0) { + seed = seed * 1103515245u + 12345u; + x = (float)((seed >> 8) & 0xFFFF) / 65535.f * 0.5f - 0.25f; + } + out.push_back(fx->process(x)); + } + return measure(out); +} + +/** Every value the randomizer wrote must belong to the device and sit in range. */ +bool checkRanges(const DeviceSpec &dev, const Params &p, std::string &why) { + for (int i = 0; i < p.size(); ++i) { + const char *key = p.keyAt(i); + const ParamSpec *ps = nullptr; + for (int k = 0; k < dev.paramCount; ++k) + if (std::strcmp(dev.params[k].key, key) == 0) { ps = &dev.params[k]; break; } + if (!ps) { why = std::string("unknown key ") + key; return false; } + if (ps->isEnum()) { + bool found = false; + for (int c = 0; c < ps->choiceCount(); ++c) + if (std::strcmp(ps->choices[c], p.valueAt(i)) == 0) { found = true; break; } + if (!found) { why = std::string(key) + " = '" + p.valueAt(i) + "' is not one of its choices"; return false; } + } else { + const float v = p.f(key, ps->def); + if (!std::isfinite(v) || v < ps->min - 1e-4f || v > ps->max + 1e-4f) { + why = std::string(key) + " = " + std::to_string(v) + " outside [" + + std::to_string(ps->min) + ", " + std::to_string(ps->max) + "]"; + return false; + } + } + } + return true; +} + +struct Device { + const char *type; + double hold, tail; // instruments only + float minPeak; // below this, nobody would hear it + float maxPeak; // above this, the patch is into the limiter +}; + +// The floors and ceilings are per device because the voices do not share a gain +// structure: SynthVoice ends in OUT_GAIN 0.5, the Grain Cloud auto-levels itself +// near RMS 0.126, and the reverb is measured wet+dry at its own levels. Each floor +// sits at roughly half the quietest roll measured over 400 seeds — loose enough not +// to flake on a seed nobody has drawn yet, tight enough that a rule sliding toward +// silence (a filter parked off the note, a layer budget scaled too hard) fails here. +const Device kDevices[] = { + {"NES_SYNTH", 1.5, 1.0, 0.060f, 1.0f}, + {"MORPH_PAD", 3.0, 1.5, 0.012f, 1.0f}, // a pad is genuinely the quietest of these + {"GRAIN_CLOUD", 3.0, 1.0, 0.015f, 1.0f}, // the cloud's auto-level needs a moment to come up + {"WAVETABLE", 1.5, 1.0, 0.030f, 1.0f}, + {"AMBIENCE", 0.0, 0.0, 0.200f, 1.0f}, +}; + +} // namespace + +/** `randomizer_test --dump [key=value ...]`: what that roll actually + * set, and what it measured. The overrides make it a probe — re-render the same + * patch with one value changed to find which one is responsible for a bad peak. */ +int dumpOne(const char *type, uint32_t seed, int nOverride, char **override) { + const DeviceSpec *dev = findDevice(type); + if (!dev) { std::printf("no such device: %s\n", type); return 2; } + Params p; + if (!model::randomize(type, seed, p)) { std::printf("%s is not randomizable\n", type); return 2; } + for (int i = 0; i < nOverride; ++i) { + const char *eq = std::strchr(override[i], '='); + if (!eq) continue; + const std::string key(override[i], eq - override[i]); + p.set(key.c_str(), eq + 1); + std::printf(" (override %s = %s)\n", key.c_str(), eq + 1); + } + std::printf("%s seed %u -- \"%s\"\n", type, seed, model::randomName(type, seed).c_str()); + for (int i = 0; i < p.size(); ++i) std::printf(" %-12s %s\n", p.keyAt(i), p.valueAt(i)); + for (const Device &d : kDevices) { + if (std::strcmp(d.type, type) != 0) continue; + const Level l = dev->kind == Kind::Instrument ? playInstrument(type, p, d.hold, d.tail) + : playEffect(type, p); + std::printf(" -> peak %.4f at %.3f s rms %.5f %s\n", l.peak, (double)l.peakAt / SR, l.rms, + l.finite ? "finite" : "NON-FINITE"); + } + return 0; +} + +int main(int argc, char **argv) { + if (argc > 3 && std::strcmp(argv[1], "--dump") == 0) { + wavetable::WaveTables::prewarmBlocking(); + echofield::GrainSources::prewarmBlocking(); + return dumpOne(argv[2], (uint32_t)std::strtoul(argv[3], nullptr, 10), argc - 4, argv + 4); + } + const int seeds = argc > 1 ? std::atoi(argv[1]) : 200; + wavetable::WaveTables::prewarmBlocking(); + echofield::GrainSources::prewarmBlocking(); + + int pass = 0, fail = 0; + std::printf("randomizer: %d seeds per device\n", seeds); + std::printf(" %-13s %9s %9s %9s %9s %7s\n", "device", "peak min", "peak med", "peak max", "rms min", "result"); + + for (const Device &d : kDevices) { + const DeviceSpec *dev = findDevice(d.type); + if (!dev) { std::printf(" FAIL %s: no device spec\n", d.type); ++fail; continue; } + if (!model::canRandomize(d.type)) { std::printf(" FAIL %s: not randomizable\n", d.type); ++fail; continue; } + + std::vector peaks; + peaks.reserve((size_t)seeds); + float worstRms = 1e9f; + float worstPeak = 1e9f; + uint32_t worstSeed = 0; + int bad = 0; + std::string firstProblem; + + for (int s = 0; s < seeds; ++s) { + const uint32_t seed = (uint32_t)(s * 2654435761u + 12345u); + Params p; + if (!model::randomize(d.type, seed, p)) { + if (firstProblem.empty()) firstProblem = "randomize() returned false"; + ++bad; continue; + } + std::string why; + if (!checkRanges(*dev, p, why)) { + if (firstProblem.empty()) firstProblem = "seed " + std::to_string(seed) + ": " + why; + ++bad; continue; + } + + const Level l = dev->kind == Kind::Instrument ? playInstrument(d.type, p, d.hold, d.tail) + : playEffect(d.type, p); + peaks.push_back(l.peak); + if (l.rms < worstRms) worstRms = l.rms; + if (l.peak < worstPeak) { worstPeak = l.peak; worstSeed = seed; } + + const char *problem = nullptr; + if (!l.finite) problem = "non-finite output"; + else if (l.peak < d.minPeak) problem = "inaudible"; + else if (l.peak > d.maxPeak) problem = "clipping"; + if (problem) { + if (firstProblem.empty()) + firstProblem = "seed " + std::to_string(seed) + ": " + problem + + " (peak " + std::to_string(l.peak) + ", rms " + std::to_string(l.rms) + ")"; + ++bad; + } + } + + std::sort(peaks.begin(), peaks.end()); + const float lo = peaks.empty() ? 0.f : peaks.front(); + const float mid = peaks.empty() ? 0.f : peaks[peaks.size() / 2]; + const float hi = peaks.empty() ? 0.f : peaks.back(); + std::printf(" %-13s %9.4f %9.4f %9.4f %9.5f %7s quietest seed %u\n", d.type, lo, mid, hi, worstRms, + bad == 0 ? "PASS" : "FAIL", worstSeed); + if (bad != 0) { + std::printf(" %d/%d bad; first: %s\n", bad, seeds, firstProblem.c_str()); + ++fail; + } else { + ++pass; + } + } + + std::printf("randomizer: %d passed, %d failed\n", pass, fail); + return fail == 0 ? 0 : 1; +} diff --git a/docs/DEVELOPER_HANDOVER.md b/docs/DEVELOPER_HANDOVER.md index e1f2e3c..13c8dff 100644 --- a/docs/DEVELOPER_HANDOVER.md +++ b/docs/DEVELOPER_HANDOVER.md @@ -252,7 +252,7 @@ cc.tiredsysadmin.android.sizzle │ └── EchofieldDefs.kt Its settings, 14 factory presets, the source list │ ├── cpp/native_audio.cpp Low-latency Oboe stream; its RT callback renders core/ directly -├── cpp/jni_engine.cpp The JNI surface of core/src/host/EngineHost +├── cpp/jni_engine.cpp The JNI surface of core/src/host/EngineHost (+ the preset randomizer) │ ├── io/ Human-readable text persistence │ ├── PresetIo.kt Instrument/effect preset <-> KEY=VALUE text @@ -457,6 +457,60 @@ connected BLE MIDI peripherals are remembered and reconnected at launch through CoreBluetooth (best effort: iOS decides whether that brings the CoreMIDI source back without the panel). +### 5.4.4 The preset randomizer (0.42.0) + +`core/src/model/Randomizer.cpp` turns a seed into a playable patch for the five +devices where "surprise me" is a musical thing to ask: **Synth**, **Morph Pad**, +**Grain Cloud**, **Wavetable** and **Ambience Reverb**. Both apps show it as a +**RANDOM** button in the shared preset bar, and the same seed gives the same patch +on both (`model::randomize(type, seed, Params&)`). + +**Why it is not just `random()` over each range.** Scattering values over the +parameter ranges mostly produces silence and the occasional scream. The rules +encode three things instead: + +- *audible*: something always sounds. One oscillator or layer is always up, an + envelope that decays to nothing is given a body, a filter is never shut, and a + reverb is never fully dry. +- *inside the rails*: oscillator levels share a budget, resonance, drive and + saturation stay out of the range where a patch screams, and the reverb's wet sits + under its dry. +- *musical where it matters*: tunings come from consonant intervals, detune stays + inside a chorus, and pitch modulation stays small enough to keep a patch in tune. + +**Nothing structural is rolled.** "Custom" sources and tables are never picked and +the slot's own keys (`sfSample`, `sfFile`, the Sampler's pads) survive a roll — a +sample or an imported wavetable is the user's, and the dice are for the settings. +`MORPH TO` is left Off for the same reason *and* for a measured one (below). + +**The test is the specification.** `core/tests/randomizer_test.cpp` (part of +`make -C ios core-test`) renders every device over hundreds of seeds through the +real voice — the golden tests' `TestVoice` wrappers — and fails on a patch that +is out of range, silent, clipping or non-finite. Every bound in Randomizer.cpp +that looks arbitrary was put there by a seed this test caught; four worth knowing, +because each is a trap the next device will have too: + +| What it caught | Why | +|---|---| +| A band-pass parked above the note | Only a *low*-pass is open at the top. Band and high need a cutoff near or under the played pitch, or a patch with every oscillator up is silent (peak 0.010 against a median of 0.3). `cutoffFor` is the shared fix. | +| `Vel → Cutoff` at −0.69 | A mod slot can close the filter. Pitch, Cutoff, PWM and Amp get bounded amounts; Cutoff asymmetrically, since opening is free and closing is not. | +| A choir-only Morph Pad through a band-pass | That filter is on the choir layer alone — the partials and breath go round it — so a patch whose choir is its only layer gets a plain open low-pass. | +| `MORPH TO` + `MORPH TIME` | A held note travels all the way onto a factory drone and *is* that preset from then on, at a level the randomizer never chose (peak 1.33 with every layer of its own at zero). Budgeting cannot reach past a morph, so a roll does not pick a target. | + +`randomizer_test --dump [key=value …]` prints one roll and what it +measured, with overrides, which is how each of those was found: re-render the same +patch with one value changed until the peak moves. + +**How it reaches the apps.** Android: `nativeCanRandomize` / `nativeRandomPreset` / +`nativeRandomName` in `jni_engine.cpp` (pure functions — no engine, so they work +before `nativeCreate`), the patch arriving as `PresetIo` text that +`AppViewModel.randomizeSlot` imports. iOS: `SizzleSession.randomizeSlot` writes the +`Params` into the slot directly. Both keep the slot's non-parameter keys. + +**Adding a device to it** means writing its rules in Randomizer.cpp, adding its +name to `kRandomizable`, and adding a row to `kDevices` in the test with a floor +and a ceiling. The button then appears on both platforms with no UI change. + ### 5.5 Sizzle as a background MIDI sound module Goal: another app (Mikro Seq, a DAW, a controller app) plays Sizzle's mixer over @@ -742,6 +796,9 @@ of real time on a desktop JVM. - **Keep the reference in step**: mirror the change in the Kotlin file under `app/src/test/.../audio` (or `frasil` / `echofield` / `wavetable`), then `make -C ios golden core-test` to check the two sample for sample. +4. Optionally give it a **RANDOM** button: rules in `core/src/model/Randomizer.cpp`, + its name in `kRandomizable`, a row in `randomizer_test`'s `kDevices`. See §5.4.4 — + and read its table of traps before inventing bounds. The Toolbox picker, parameter editor, and preset save/load all work automatically from the `ParamSpec` list (the editor then shows one card with every parameter). 3. Group its controls: add a case to `DeviceLayouts.pagesFor` (cards, tones, diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index 0092ef3..690f307 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -345,6 +345,8 @@ its number to switch it off/on: Every device editor has a preset bar at the top: - **PRESET** dropdown — load a saved preset. +- **RANDOM** — roll a new patch (Synth, Morph Pad, Grain Cloud, Wavetable and + Ambience Reverb only; see below). - **SAVE** — save the current settings as a named preset. - **DELETE** — remove the selected preset (asks to confirm). - **IMPORT** — load a preset from a file (Sampler presets can be imported from a @@ -355,6 +357,26 @@ Presets are plain text (`.szp`), stored per device type in the app's storage. Factory presets are seeded automatically and reappear as new ones ship, but ones you delete stay deleted. +### RANDOM + +The five devices with the most knobs — **Synth**, **Morph Pad**, **Grain Cloud**, +**Wavetable** and **Ambience Reverb** — have a **RANDOM** button that throws a new +patch into the editor and gives it a name ("Hazy Drift"). It is a starting point, +not a slot machine: a roll is always something you can hear and never something +that clips, because the levels, the filters and the envelopes are drawn inside +ranges that keep a patch in that territory rather than scattered over the whole +knob. Expect a usable sound most of the time and a keeper now and then. + +RANDOM replaces the settings in the editor, exactly like loading a preset, so +**SAVE** anything you want to keep first. It does *not* touch a sample you have +loaded or a wavetable you have imported — the roll is of the settings, not of +your sounds. Roll again as often as you like; when one is worth keeping, SAVE it. + +The other devices have no RANDOM, and that is deliberate: a Sampler or an SF2/XI +loader is only as interesting as the sound you put in it, and the MIDI effects +(arpeggiator, transposer, LFO) have so few settings that a dice roll says nothing +a glance at them would not. + --- ## Setup tab diff --git a/ios/CHANGELOG.md b/ios/CHANGELOG.md index 6241081..b771731 100644 --- a/ios/CHANGELOG.md +++ b/ios/CHANGELOG.md @@ -5,6 +5,17 @@ Sizzle for iOS/iPadOS (`cc.tiredsysadmin.ios.sizzle`). One entry per version in is shared with Android, continuing Android's numbering, and both apps ship the same features; the Android side of each version is in `../CHANGELOG.md`. +## 0.42.0 (build 78) + +- RANDOM: the Synth, Morph Pad, Grain Cloud, Wavetable and Ambience Reverb + editors have a RANDOM button in the preset bar, which rolls a new patch and + names it. Always audible, never clipping — the ranges it draws from are picked + to keep a patch there rather than scattered over the whole knob. It replaces the + editor's settings like a preset does (SAVE first to keep what is there) and + leaves a loaded sample or an imported wavetable alone. The same rules and the + same seeds as Android, from `core/src/model/Randomizer.cpp`. + (Android has the same in 0.42.0.) + ## 0.41.1 (build 77) <<<<<<< HEAD diff --git a/ios/Makefile b/ios/Makefile index 47b5917..e3c5510 100644 --- a/ios/Makefile +++ b/ios/Makefile @@ -100,6 +100,12 @@ build/core/oneshot_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/oneshot_test.cpp mkdir -p build/core $(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/oneshot_test.cpp +# The randomizer plays what it generates, so it links the golden tests' TestVoice +# wrappers too (see VOICE_SRC). +build/core/randomizer_test: $(CORE_SRC) $(CORE_HDR) $(VOICE_SRC) $(VOICE_HDR) ../core/tests/randomizer_test.cpp + mkdir -p build/core + $(CXX) $(CXXFLAGS) -I../core/tests -o $@ $(CORE_SRC) $(VOICE_SRC) ../core/tests/randomizer_test.cpp + build/core/bench: $(CORE_SRC) $(CORE_HDR) ../core/tests/bench.cpp mkdir -p build/core $(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/bench.cpp @@ -125,7 +131,7 @@ zip-test: build/core/zip_test build/core/zip_test build/core/java.zip build/core/ours.zip unzip -tq build/core/ours.zip -core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/io_test build/core/midi_test build/core/host_test build/core/midimap_test build/core/bundle_test build/core/oneshot_test zip-test +core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/io_test build/core/midi_test build/core/host_test build/core/midimap_test build/core/bundle_test build/core/oneshot_test build/core/randomizer_test zip-test @test -f $(GOLDEN)/input.f32 || $(MAKE) --no-print-directory golden build/core/golden_test $(GOLDEN) $(TYPES) build/core/sampler_test @@ -136,6 +142,7 @@ core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/midimap_test ../app/src/test/resources/midimap/filter.szm build/core/oneshot_test build/core/bundle_test $(GOLDEN)/bundles/android_sampler.zip ../app/src/test/resources/presetbundle/ios_sampler.zip + build/core/randomizer_test $(SEEDS) # ------------------------------------------------------------------ app AU_SRC := app/FX/SizzleDeviceAU.mm app/FX/SizzleEffectAU.mm app/FX/SizzleInstrumentAU.mm app/FX/SizzleDeviceAU+Sources.mm diff --git a/ios/README.md b/ios/README.md index ab96d89..3ca4234 100644 --- a/ios/README.md +++ b/ios/README.md @@ -12,6 +12,7 @@ Makefile (`make -C ios help`). | `../core/tests/golden_test.cpp` | Compares the core with audio the Kotlin code renders | | `../core/tests/voices/` | The `TestVoice` wrappers `golden_test` drives the instruments through. Under `tests/`, not `src/`, so neither app compiles them | | `../core/tests/bench.cpp` | `make bench`: what the FX chain and each effect cost. Asserts nothing, so it is not part of `core-test` | +| `../core/tests/randomizer_test.cpp` | Plays what the preset randomizer generates over many seeds: in range, audible, not clipping. `--dump [key=value …]` inspects one roll | | `app/components.txt` | The plugin list (AU type, subtype, device, name) | | `app/FX/` | The plugin extension: `SizzleDeviceAU` (shared: parameters, presets, state), `SizzleEffectAU` (aufx), `SizzleInstrumentAU` (aumu), `SizzleFXViewController` (factory + editor). The app compiles the same classes to host them itself | | `app/Host/SizzleSession*` | The bridge to the C++ song + engine (audio output, song lock, live-note queue); one category per screen | diff --git a/ios/app/Host/Screens/Toolbox/SlotEditor.swift b/ios/app/Host/Screens/Toolbox/SlotEditor.swift index 2d782b5..3d71996 100644 --- a/ios/app/Host/Screens/Toolbox/SlotEditor.swift +++ b/ios/app/Host/Screens/Toolbox/SlotEditor.swift @@ -246,6 +246,16 @@ private struct PresetBar: View { MixKit.Button(label: "DELETE", danger: true) { confirmDelete = current } Spacer().frame(width: 20) } + // RANDOM, for the devices core/'s randomizer covers (the Synth, + // Morph Pad, Grain Cloud, Wavetable and Ambience). It replaces the + // settings in place, the way loading a preset does. + if session.canRandomizeType(type) { + MixKit.Button(label: "RANDOM") { + guard session.randomizeSlot(slot) != nil else { return } + selected = nil + model.refresh() + } + } MixKit.Button(label: "SAVE") { saveName = slotName.trimmingCharacters(in: .whitespaces).isEmpty ? displayName : slotName saving = true diff --git a/ios/app/Host/SizzleSession.h b/ios/app/Host/SizzleSession.h index 36a8730..ed06c7b 100644 --- a/ios/app/Host/SizzleSession.h +++ b/ios/app/Host/SizzleSession.h @@ -136,6 +136,12 @@ NS_SWIFT_UI_ACTOR /// Factory preset names for a device type (Android's PresetLibrary set). - (NSArray *)factoryPresetsForType:(NSString *)type; - (void)applyFactoryPreset:(NSString *)name toSlot:(NSInteger)slot; +/// Does this device type have a preset randomizer (core/src/model/Randomizer.cpp)? +- (BOOL)canRandomizeType:(NSString *)type; +/// Roll a playable patch into [slot] and return the name it came with, or nil when +/// the slot's device has no randomizer. The slot's own files — a loaded sample, an +/// imported wavetable — are kept: the roll is of the settings, not of the sounds. +- (nullable NSString *)randomizeSlot:(NSInteger)slot; #pragma mark - Live notes (keyboard, MIDI): queued to the audio thread - (void)noteOn:(NSInteger)note velocity:(NSInteger)velocity midiChannel:(NSInteger)channel; diff --git a/ios/app/Host/SizzleSession.mm b/ios/app/Host/SizzleSession.mm index 0e3d109..657ef38 100644 --- a/ios/app/Host/SizzleSession.mm +++ b/ios/app/Host/SizzleSession.mm @@ -21,6 +21,7 @@ #include "sizzle/DeviceSpecs.gen.hpp" #include "sizzle/Engine.hpp" #include "sizzle/Model.hpp" +#include "sizzle/Randomizer.hpp" using namespace sizzle; @@ -498,6 +499,34 @@ bool isSampleKey(const char *key) { }]; } +- (BOOL)canRandomizeType:(NSString *)type { + return type.length && model::canRandomize(type.UTF8String) ? YES : NO; +} + +- (nullable NSString *)randomizeSlot:(NSInteger)slot { + if (slot < 0 || slot >= 16) return nil; + const std::string type = [self typeOfSlot:slot].UTF8String; + if (!model::canRandomize(type.c_str())) return nil; + + const uint32_t seed = arc4random(); + Params rolled; + if (!model::randomize(type.c_str(), seed, rolled)) return nil; + const std::string name = model::randomName(type.c_str(), seed); + + [self edit:^(model::Project &p, engine::Engine &e) { + model::ToolboxSlot &s = p.toolbox[(size_t)slot]; + // Only the keys the roll produced are written, and those are exactly the + // device's own parameters. Anything else the slot holds — the sample a Grain + // Cloud reads, the WAV behind a custom wavetable — is therefore left in + // place: the roll is of the settings, not of the sounds. Writing through + // set() also bumps the slot version, so the engine re-reads it. + for (int i = 0; i < rolled.size(); ++i) s.set(rolled.keyAt(i), rolled.valueAt(i)); + s.name = name; + e.rebuildFxChains(); + }]; + return @(name.c_str()); +} + #pragma mark - live notes - (void)noteOn:(NSInteger)note velocity:(NSInteger)velocity midiChannel:(NSInteger)ch { diff --git a/versions.properties b/versions.properties index dc8addd..bc4b2ef 100644 --- a/versions.properties +++ b/versions.properties @@ -12,8 +12,8 @@ # or polish. versionCode is monotonic and bumps by 1 on every release, # because F-Droid and the Android package manager order installs by it alone. -versionName = 0.41.1 -versionCode = 77 +versionName = 0.42.0 +versionCode = 78 # Namespace for every platform: cc.tiredsysadmin..sizzle. Android: # cc.tiredsysadmin.android.sizzle (app/), iOS/iPadOS: cc.tiredsysadmin.ios.sizzle