0.42.0 (78): preset randomizer for five devices (Android and iOS)

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 <TYPE> <seed> [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
<cstdint> 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 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-18 20:55:23 +01:00
co-authored by Claude Opus 5
parent e78b2c1418
commit 0d6ed4694f
18 changed files with 1033 additions and 4 deletions
+1
View File
@@ -12,6 +12,7 @@
// thread. Toolbox values are text (sizzle::Params), as ToolboxSlot's map is.
#include <array>
#include <cstdint>
#include <string>
#include <vector>
#include "sizzle/Params.hpp"
+56
View File
@@ -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 <cstdint>
#include <string>
#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
+468
View File
@@ -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 <cmath>
#include <cstring>
#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 N> 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
+270
View File
@@ -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 <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#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<float> &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<TestVoice> 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<float> 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<Effect> fx = Effect::create(type, SR);
if (!fx) return Level{};
fx->update(p, 120.f);
const int n = (int)(2.0 * SR);
std::vector<float> 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 <TYPE> <seed> [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<float> 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;
}