Wavetable instrument: two-oscillator band-limited wavetable synth (0.32.0)

Written for Sizzle (the hub's candidates are GPL-3.0-only, so nothing was
copied): tables kept as spectra and rendered per octave by inverse FFT with
a taper, level picked per control block so high notes don't alias; twelve
generated tables plus Serum / WaveEdit WAV import (clm chunk, frame-size
guessing, rebuilt from the kept WAV after a restart); two oscillators with
position, phase bend and up to 4-voice unison, sub, noise, drive, SVF,
amp and mod envelopes, tempo-synced LFO. 12 factory presets. Played inside
SynthVoice like the Morph Pad.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-13 09:30:09 +01:00
co-authored by Claude Opus 5.5
parent aa023d1f01
commit c8d760ed17
18 changed files with 1172 additions and 33 deletions
@@ -105,6 +105,7 @@ class SizzleApp : Application() {
// The Grain Cloud's built-in sources are synthesised, not shipped: render them
// in the background now so they're ready before anyone plays one.
cc.tiredsysadmin.android.sizzle.audio.GrainSources.prewarm()
cc.tiredsysadmin.android.sizzle.wavetable.WaveTables.prewarm()
// Crash recovery: restore the last autosaved project before the engine or
// UI read it, so a crash / process-death resumes where the user left off.
projectStore.restore(project)
@@ -10,6 +10,7 @@ import cc.tiredsysadmin.android.sizzle.echofield.GrainCloud
import cc.tiredsysadmin.android.sizzle.echofield.GrainPatch
import cc.tiredsysadmin.android.sizzle.frasil.FrasilClock
import cc.tiredsysadmin.android.sizzle.frasil.FrasilPatch
import cc.tiredsysadmin.android.sizzle.wavetable.WavePatch
import cc.tiredsysadmin.android.sizzle.model.Arrangement
import cc.tiredsysadmin.android.sizzle.model.Pattern
import cc.tiredsysadmin.android.sizzle.model.Project
@@ -1492,11 +1493,13 @@ class AudioEngine(
private fun patchForSlot(slot: ToolboxSlot?, tempoBpm: Float): SynthPatch = when (slot?.type) {
ToolboxType.NES_SYNTH -> SynthPatch.from(slot, tempoBpm)
ToolboxType.MORPH_PAD -> SynthPatch.forPad(FrasilPatch.from(slot))
ToolboxType.WAVETABLE -> SynthPatch.forWave(WavePatch.from(slot, tempoBpm))
else -> SynthPatch.DEFAULT
}
/** The slot types whose notes a [SynthVoice] plays with a parsed [SynthPatch]. */
private fun hasSynthPatch(type: ToolboxType?) = type == ToolboxType.NES_SYNTH || type == ToolboxType.MORPH_PAD
private fun hasSynthPatch(type: ToolboxType?) =
type == ToolboxType.NES_SYNTH || type == ToolboxType.MORPH_PAD || type == ToolboxType.WAVETABLE
/**
* Once per block: refresh each bus's cached synth patch (reparsing only when the
@@ -4,6 +4,7 @@
package cc.tiredsysadmin.android.sizzle.audio
import cc.tiredsysadmin.android.sizzle.frasil.FrasilPatch
import cc.tiredsysadmin.android.sizzle.wavetable.WavePatch
import cc.tiredsysadmin.android.sizzle.model.SynthDefs
import cc.tiredsysadmin.android.sizzle.model.TimeDivision
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
@@ -45,6 +46,8 @@ class SynthPatch(
/** Set for a Morph Pad slot: the voice then plays FRASIL's drone voice from this
* instead of the subtractive path (see [SynthVoice]); everything above is unused. */
val pad: FrasilPatch? = null,
/** Set for a Wavetable slot: the voice plays [WaveVoice] from this. */
val wave: WavePatch? = null,
) {
companion object {
const val OSC_COUNT = SynthDefs.OSC_COUNT
@@ -106,5 +109,11 @@ class SynthPatch(
SynthPatch(oscWave, oscOct, oscSemi, oscFine, oscLevel, noiseLevel, cutoff, resonance, keytrack,
filterEnvAmt, fA, fD, fS, fR, aA, aD, aS, aR, lfoWave, lfoHz, lfoPhase, modSrc, modDst, modAmt, pad)
}
/** A Wavetable patch: the default synth fields, carrying [wave]. */
fun forWave(wave: WavePatch): SynthPatch = with(DEFAULT) {
SynthPatch(oscWave, oscOct, oscSemi, oscFine, oscLevel, noiseLevel, cutoff, resonance, keytrack,
filterEnvAmt, fA, fD, fS, fR, aA, aD, aS, aR, lfoWave, lfoHz, lfoPhase, modSrc, modDst, modAmt, null, wave)
}
}
}
@@ -4,6 +4,7 @@
package cc.tiredsysadmin.android.sizzle.audio
import cc.tiredsysadmin.android.sizzle.frasil.FrasilVoice
import cc.tiredsysadmin.android.sizzle.wavetable.WaveVoice
import kotlin.math.abs
import kotlin.math.exp
import kotlin.math.sin
@@ -72,30 +73,43 @@ class SynthVoice(private val sampleRate: Int) {
private val ampEnv = Adsr()
private val filtEnv = Adsr()
// A Morph Pad note plays FRASIL's drone voice instead of the subtractive path. It
// lives inside this class so every synth pool (sequencer, mix-bus, audition) can
// play a pad with no change to how voices are allocated, stolen or released.
// A Morph Pad note plays FRASIL's drone voice, a Wavetable note the wavetable
// voice, instead of the subtractive path. They live inside this class so every
// synth pool (sequencer, mix-bus, audition) plays them with no change to how
// voices are allocated, stolen or released. [mode]: MODE_SYNTH / _PAD / _WAVE.
private val pad = FrasilVoice(sampleRate)
private var padMode = false
private val wave = WaveVoice(sampleRate)
private var mode = MODE_SYNTH
private val padMode get() = mode == MODE_PAD
val isActive: Boolean get() = if (padMode) pad.isActive else ampEnv.active
val isActive: Boolean get() = when (mode) { MODE_PAD -> pad.isActive; MODE_WAVE -> wave.isActive; else -> ampEnv.active }
/** Gate is still open (attack/decay/sustain) — the note is *held*. A voice in its
* release tail is still [isActive] but no longer gated; distinguishing the two
* lets a note-off target the held voice instead of one that's already ringing
* out (which otherwise leaves the held note stuck under rapid re-tapping). */
val isGated: Boolean get() = if (padMode) pad.isGated else ampEnv.gateOpen
val isGated: Boolean get() = when (mode) { MODE_PAD -> pad.isGated; MODE_WAVE -> wave.isGated; else -> ampEnv.gateOpen }
/** Start (or steal-and-restart) this voice with the given [patch]. */
fun noteOn(midi: Int, velocity: Int, patch: SynthPatch) {
val padPatch = patch.pad
val wavePatch = patch.wave
val want = if (padPatch != null) MODE_PAD else if (wavePatch != null) MODE_WAVE else MODE_SYNTH
if (want != mode) { // a slot switched kinds: the old engine stops
ampEnv.kill(); filtEnv.kill(); pad.kill(); wave.kill()
mode = want
}
if (padPatch != null) {
if (!padMode) { ampEnv.kill(); filtEnv.kill(); padMode = true }
this.patch = patch
pitch = midi
pad.noteOn(midi, velocity / 127f, padPatch)
return
}
if (padMode) { pad.kill(); padMode = false }
if (wavePatch != null) {
this.patch = patch
pitch = midi
wave.noteOn(midi, velocity / 127f, wavePatch)
return
}
this.patch = patch
pitch = midi
this.velocity = (velocity / 127f).coerceIn(0f, 1f)
@@ -114,12 +128,15 @@ class SynthVoice(private val sampleRate: Int) {
computeTuning()
}
fun noteOff() { if (padMode) pad.noteOff() else { ampEnv.gateOff(); filtEnv.gateOff() } }
fun noteOff() {
when (mode) { MODE_PAD -> pad.noteOff(); MODE_WAVE -> wave.noteOff(); else -> { ampEnv.gateOff(); filtEnv.gateOff() } }
}
/** Hard stop with no release tail (transport stop / voice steal). */
fun kill() {
ampEnv.kill(); filtEnv.kill()
pad.kill()
wave.kill()
pitch = -1
ownerTrack = -1
icB = 0f; icL = 0f
@@ -132,10 +149,12 @@ class SynthVoice(private val sampleRate: Int) {
fun setPatch(p: SynthPatch) {
if (p === patch) return
val padPatch = p.pad
if (padMode || padPatch != null) {
// Only within the same kind: a pad note follows pad edits, a synth note synth
// edits; a slot switched between the two takes effect on the next note.
if (padMode && padPatch != null) { patch = p; pad.setPatch(padPatch) }
val wavePatch = p.wave
if (mode != MODE_SYNTH || padPatch != null || wavePatch != null) {
// Only within the same kind: a pad note follows pad edits, a wavetable note
// wavetable edits; a slot switched between kinds takes effect on the next note.
if (mode == MODE_PAD && padPatch != null) { patch = p; pad.setPatch(padPatch) }
if (mode == MODE_WAVE && wavePatch != null) { patch = p; wave.setPatch(wavePatch) }
return
}
patch = p
@@ -154,7 +173,8 @@ class SynthVoice(private val sampleRate: Int) {
}
fun render(): Float {
if (padMode) return pad.render()
if (mode == MODE_PAD) return pad.render()
if (mode == MODE_WAVE) return wave.render()
if (!ampEnv.active) return 0f
val dt = 1f / sampleRate
val ampE = ampEnv.advance(dt)
@@ -346,6 +366,9 @@ class SynthVoice(private val sampleRate: Int) {
}
companion object {
private const val MODE_SYNTH = 0
private const val MODE_PAD = 1
private const val MODE_WAVE = 2
private const val OUT_GAIN = 0.5f
private const val CTRL_INTERVAL = 16 // samples between cutoff recomputes
/** One-pole time constant for amp modulation. Long enough to band-limit a
@@ -6,6 +6,7 @@ package cc.tiredsysadmin.android.sizzle.io
import cc.tiredsysadmin.android.sizzle.audio.SampleStore
import cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs
import cc.tiredsysadmin.android.sizzle.wavetable.WaveDefs
import cc.tiredsysadmin.android.sizzle.model.AmbiencePresets
import cc.tiredsysadmin.android.sizzle.model.MixTightenerPresets
import cc.tiredsysadmin.android.sizzle.model.NesSynthPresets
@@ -60,6 +61,9 @@ class PresetLibrary(private val baseDir: File) {
seedType(ToolboxType.GRAIN_CLOUD, EchofieldDefs.FACTORY.map { it.name }) { slot, name ->
EchofieldDefs.FACTORY.first { it.name == name }.values.forEach { (k, v) -> slot.set(k, v) }
}
seedType(ToolboxType.WAVETABLE, WaveDefs.FACTORY.map { it.name }) { slot, name ->
WaveDefs.FACTORY.first { it.name == name }.values.forEach { (k, v) -> slot.set(k, v) }
}
seedType(ToolboxType.MIX_TIGHTENER, MixTightenerPresets.FACTORY.map { it.name }) { slot, name ->
MixTightenerPresets.apply(slot, MixTightenerPresets.FACTORY.first { it.name == name })
}
@@ -147,8 +151,8 @@ class PresetLibrary(private val baseDir: File) {
}
preset.writeText(exportSoundFont(slot, rel))
}
ToolboxType.GRAIN_CLOUD -> {
// A custom grain source travels with the preset as a WAV, like the SF2/XI
ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE -> {
// A custom grain source or wavetable travels with the preset as a WAV, like the SF2/XI
// loader's; the built-in sources need nothing.
val sample = SampleStore.get(slot.string("sfSample"))
if (sample != null) {
@@ -181,7 +185,7 @@ class PresetLibrary(private val baseDir: File) {
}
if (type == ToolboxType.SAMPLER) {
for (p in 0 until SamplerPads.COUNT) File(dir, "${base}_pad$p.wav").delete()
} else if (type == ToolboxType.SOUNDFONT || type == ToolboxType.GRAIN_CLOUD) {
} else if (type == ToolboxType.SOUNDFONT || type == ToolboxType.GRAIN_CLOUD || type == ToolboxType.WAVETABLE) {
File(dir, "${base}_sf.wav").delete()
}
return preset.delete()
@@ -198,7 +202,7 @@ class PresetLibrary(private val baseDir: File) {
project.toolbox.forEach { slot ->
when (slot.type) {
ToolboxType.SAMPLER -> resolvePads(slot, typeDir(ToolboxType.SAMPLER))
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD -> resolveSoundFont(slot, typeDir(ToolboxType.SOUNDFONT))
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE -> resolveSoundFont(slot, typeDir(ToolboxType.SOUNDFONT))
else -> {}
}
}
@@ -213,7 +217,7 @@ class PresetLibrary(private val baseDir: File) {
val dir = file.parentFile ?: typeDir(type)
when (slot.type) {
ToolboxType.SAMPLER -> resolvePads(slot, dir)
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD -> resolveSoundFont(slot, dir)
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE -> resolveSoundFont(slot, dir)
else -> {}
}
true
@@ -230,7 +234,7 @@ class PresetLibrary(private val baseDir: File) {
val type = slot.type ?: return false
when (type) {
ToolboxType.SAMPLER -> resolvePads(slot, typeDir(type))
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD -> resolveSoundFont(slot, typeDir(type))
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE -> resolveSoundFont(slot, typeDir(type))
else -> {}
}
save(slot, slot.name.ifBlank { type.displayName })
@@ -271,7 +275,7 @@ class PresetLibrary(private val baseDir: File) {
if (!PresetIo.import(slot, text)) return false
when (slot.type) {
ToolboxType.SAMPLER -> resolvePads(slot, scratch)
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD -> resolveSoundFont(slot, scratch)
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE -> resolveSoundFont(slot, scratch)
else -> {}
}
// Persist a self-contained copy into the real library folder.
@@ -288,7 +292,9 @@ class PresetLibrary(private val baseDir: File) {
fun bundleForShare(type: ToolboxType, name: String): File? {
val preset = File(typeDir(type), sanitize(name) + PRESET_EXT)
if (!preset.exists()) return null
if (type != ToolboxType.SAMPLER && type != ToolboxType.SOUNDFONT && type != ToolboxType.GRAIN_CLOUD) return preset
if (type != ToolboxType.SAMPLER && type != ToolboxType.SOUNDFONT && type != ToolboxType.GRAIN_CLOUD &&
type != ToolboxType.WAVETABLE
) return preset
val bundles = File(baseDir, BUNDLE_DIR).apply { mkdirs() }
val zip = File(bundles, sanitize(name) + ".zip")
@@ -112,7 +112,7 @@ object ProjectBundleIo {
ToolboxType.SAMPLER -> for (p in 0 until SamplerPads.COUNT) {
idToPath[slot.string(SamplerPads.key(p))]?.let { slot.set("pad${p}File", it) }
}
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD -> idToPath[slot.string("sfSample")]?.let { slot.set("sfFile", it) }
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE -> idToPath[slot.string("sfSample")]?.let { slot.set("sfFile", it) }
else -> {}
}
}
@@ -127,7 +127,7 @@ object ProjectBundleIo {
ToolboxType.SAMPLER -> for (p in 0 until SamplerPads.COUNT) {
slot.string(SamplerPads.key(p)).takeIf { it.isNotBlank() }?.let { ids.add(it) }
}
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD ->
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE ->
slot.string("sfSample").takeIf { it.isNotBlank() }?.let { ids.add(it) }
else -> {}
}
@@ -5,6 +5,7 @@ package cc.tiredsysadmin.android.sizzle.model
import cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs
import cc.tiredsysadmin.android.sizzle.wavetable.WaveDefs
/**
* The third tab is a toolbox of 16 slots. Every slot can hold one instrument OR
@@ -126,6 +127,11 @@ enum class ToolboxType(
// or your own sample ("sfSample", as the SF2/XI loader keeps it); held notes pitch
// the grains. Rendered by GrainCloud in AudioEngine; edited by GrainCloudEditor.
GRAIN_CLOUD(ToolboxKind.INSTRUMENT, "Grain Cloud", EchofieldDefs.PARAMS),
// A two-oscillator wavetable synth (Sizzle's own, see the wavetable package): 12
// generated tables or an imported Serum / WaveEdit WAV ("sfSample"), band-limited
// per octave, position swept by an envelope and LFO, unison, SVF filter. Rendered
// by WaveVoice inside SynthVoice; edited by WavetableEditor + the paged list.
WAVETABLE(ToolboxKind.INSTRUMENT, "Wavetable", WaveDefs.PARAMS),
// ---------- Effects ----------
ARPEGGIATOR(
@@ -1093,17 +1093,47 @@ class AppViewModel(
slot: cc.tiredsysadmin.android.sizzle.model.ToolboxSlot,
sample: cc.tiredsysadmin.android.sizzle.audio.SampleStore.Sample,
) {
storeSlotSample(slot, sample, cc.tiredsysadmin.android.sizzle.model.ToolboxType.GRAIN_CLOUD)
slot.set("source", cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs.CUSTOM)
touched()
}
/** Keep [sample] as [slot]'s own sound: a WAV copy in [type]'s preset folder, the
* slot pointing at it by id (`sfSample`) and path (`sfFile`). Returns the id. */
private fun storeSlotSample(
slot: cc.tiredsysadmin.android.sizzle.model.ToolboxSlot,
sample: cc.tiredsysadmin.android.sizzle.audio.SampleStore.Sample,
type: cc.tiredsysadmin.android.sizzle.model.ToolboxType,
): String {
val store = cc.tiredsysadmin.android.sizzle.audio.SampleStore
val dir = java.io.File(presetLibrary.typeDir(cc.tiredsysadmin.android.sizzle.model.ToolboxType.GRAIN_CLOUD), "sources")
.apply { mkdirs() }
val dir = java.io.File(presetLibrary.typeDir(type), "sources").apply { mkdirs() }
val file = java.io.File(dir, "source-${System.currentTimeMillis()}.wav")
runCatching { file.writeBytes(store.encodeWav(sample)) }
val id = "file:" + file.absolutePath
store.put(id, sample)
slot.set(cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs.SAMPLE_KEY, id)
slot.set("sfSample", id)
if (file.exists()) slot.set("sfFile", file.absolutePath)
slot.set("source", cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs.CUSTOM)
return id
}
/**
* Load a wavetable WAV into Wavetable [slot]: Serum's (its `clm ` chunk gives the
* frame length), WaveEdit's (64 x 256) or any file of power-of-two frames. The
* table is built here (off the audio thread) and oscillator 1 switches to it.
*/
fun loadWavetable(slot: cc.tiredsysadmin.android.sizzle.model.ToolboxSlot, bytes: ByteArray): Boolean {
val tables = cc.tiredsysadmin.android.sizzle.wavetable.WaveTables
val defs = cc.tiredsysadmin.android.sizzle.wavetable.WaveDefs
val sample = cc.tiredsysadmin.android.sizzle.audio.SampleStore.decodeWav(bytes) ?: return false
if (sample.data.size < 64) return false
val frameLen = tables.detectFrameLength(bytes, sample.data.size)
val label = frameLen.toString().takeIf { it in defs.FRAME_SIZES } ?: defs.FRAME_SIZES[0]
val id = storeSlotSample(slot, sample, cc.tiredsysadmin.android.sizzle.model.ToolboxType.WAVETABLE)
slot.set("wtframe", label)
tables.buildForSample(id, label.toIntOrNull() ?: 0)
slot.set("o1table", tables.CUSTOM)
touched()
return true
}
/** Point an LFO slot at another device's parameter, capturing that param's
@@ -59,6 +59,7 @@ import androidx.compose.ui.unit.sp
import androidx.core.content.FileProvider
import cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs
import cc.tiredsysadmin.android.sizzle.wavetable.WaveDefs
import cc.tiredsysadmin.android.sizzle.model.ParamSpec
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
import cc.tiredsysadmin.android.sizzle.model.ToolboxType
@@ -298,7 +299,7 @@ private fun ParamEditor(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> Unit
// the toolbox / tracker keyboards), so their controls scroll in a weighted region
// above the keyboard rather than the whole editor scrolling as one.
val pinnedKeyboard = type == ToolboxType.SOUNDFONT || type == ToolboxType.NES_SYNTH ||
type == ToolboxType.MORPH_PAD || type == ToolboxType.GRAIN_CLOUD
type == ToolboxType.MORPH_PAD || type == ToolboxType.GRAIN_CLOUD || type == ToolboxType.WAVETABLE
// The Sampler pins its 16-pad grid at the bottom in that same region, so the
// playable pads are the same height as the keyboards across every instrument editor.
val pinnedBottom = pinnedKeyboard || type == ToolboxType.SAMPLER
@@ -345,6 +346,10 @@ private fun ParamEditor(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> Unit
ToolboxType.DELAY -> DelayEditor(vm, slot)
ToolboxType.AMBIENCE -> AmbiencePager(vm, slot)
ToolboxType.MORPH_PAD -> SectionPager(vm, slot, FrasilDefs.SECTIONS, 300.dp)
ToolboxType.WAVETABLE -> {
WavetableEditor(vm, slot)
SectionPager(vm, slot, WaveDefs.SECTIONS, 300.dp)
}
ToolboxType.GRAIN_CLOUD -> {
GrainCloudEditor(vm, slot)
SectionPager(vm, slot, EchofieldDefs.SECTIONS, 300.dp)
@@ -0,0 +1,106 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.ui.toolbox
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
import cc.tiredsysadmin.android.sizzle.ui.AppViewModel
import cc.tiredsysadmin.android.sizzle.ui.components.RetroButton
import cc.tiredsysadmin.android.sizzle.ui.theme.LocalRetro
import cc.tiredsysadmin.android.sizzle.wavetable.WaveDefs
import cc.tiredsysadmin.android.sizzle.wavetable.WaveTables
/**
* The Wavetable's table strip: LOAD TABLE (a Serum / WaveEdit / power-of-two-frame
* WAV becomes the "Custom" table) and a view of oscillator 1's table, every frame
* stacked back to front with the one at its POSITION lit.
*/
@Composable
fun WavetableEditor(vm: AppViewModel, slot: ToolboxSlot) {
val c = LocalRetro.current
val context = LocalContext.current
@Suppress("UNUSED_VARIABLE") val rev = vm.revision
var importError by remember(slot.index) { mutableStateOf<String?>(null) }
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
val bytes = runCatching { context.contentResolver.openInputStream(uri)?.use { readCapped(it) } }.getOrNull()
when {
bytes == null -> importError =
"Couldn't read the file, or it's larger than ${MAX_IMPORT_BYTES / (1024 * 1024)} MB."
!vm.loadWavetable(slot, bytes) -> importError =
"Couldn't load this wavetable. Use an uncompressed .wav (Serum, WaveEdit, or frames of 256–2048 samples)."
}
}
val name = slot.string("o1table", WaveDefs.TABLES[0])
val frame = slot.string("wtframe", WaveDefs.FRAME_SIZES[0]).toIntOrNull() ?: 0
val table = if (name == WaveTables.CUSTOM) WaveTables.forSample(slot.string(WaveDefs.SAMPLE_KEY), frame) else WaveTables.factory(name)
val pos = slot.float("o1pos", 0f)
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
RetroButton("LOAD TABLE") { picker.launch(arrayOf("*/*")) }
Text(
if (table == null) "Osc 1: $name (preparing…)" else "Osc 1: ${if (name == WaveTables.CUSTOM) "your table" else name} · ${table.frames} frames",
color = c.textDim, fontFamily = FontFamily.Monospace, fontSize = 10.sp,
)
if (table != null) {
// 128 points of each frame's richest level, stacked; recomputed per table only
val curves = remember(table) {
val n = table.size(0); val step = maxOf(1, table.frames / 16)
(0 until table.frames step step).map { f -> FloatArray(128) { i -> table.data[0][f * n + i * n / 128] } to f }
}
val lit = (pos * (table.frames - 1) + 0.5f).toInt()
Canvas(Modifier.fillMaxWidth().height(110.dp).background(c.surface)) {
val k = curves.size
val rowH = size.height * 0.45f
for ((idx, cf) in curves.withIndex().reversed()) {
val (pts, f) = cf
val depth = if (k > 1) idx.toFloat() / (k - 1) else 0f
val x0 = size.width * 0.04f + depth * size.width * 0.18f
val w = size.width * 0.76f
val yMid = size.height * 0.72f - depth * size.height * 0.45f
val near = kotlin.math.abs(f - lit) * 2 <= maxOf(1, table.frames / curves.size)
val col = if (near) c.accent else c.text.copy(alpha = 0.25f)
for (i in 1 until pts.size) {
drawLine(col,
Offset(x0 + w * (i - 1) / pts.size, yMid - pts[i - 1] * rowH * 0.5f),
Offset(x0 + w * i / pts.size, yMid - pts[i] * rowH * 0.5f),
strokeWidth = if (near) 2f else 1f)
}
}
}
}
}
importError?.let { msg ->
AlertDialog(
onDismissRequest = { importError = null },
title = { Text("Import failed") },
text = { Text(msg) },
confirmButton = { TextButton(onClick = { importError = null }) { Text("OK") } },
)
}
}
@@ -0,0 +1,111 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.wavetable
import cc.tiredsysadmin.android.sizzle.model.ParamSpec
import cc.tiredsysadmin.android.sizzle.model.TimeDivision
/** The wavetable synth's settings, editor pages and factory presets. */
object WaveDefs {
val TABLES: List<String> = WaveTables.FACTORY_NAMES + WaveTables.CUSTOM
val FILTER_TYPES = listOf("Low", "Band", "High")
val LFO_WAVES = listOf("Sine", "Tri", "Saw", "Square", "S&H")
val FRAME_SIZES = listOf("Auto", "256", "512", "1024", "2048")
/** A custom table's WAV lives under the SF2/XI loader's keys, so presets, project
* bundles and startup rehydration carry it (see PresetLibrary). */
const val SAMPLE_KEY = "sfSample"
val PARAMS: List<ParamSpec> by lazy {
buildList {
for (o in 1..2) {
add(ParamSpec("o${o}table", "Osc$o Table", choices = TABLES))
add(ParamSpec("o${o}pos", "Osc$o Position", if (o == 1) 0f else 0.3f, 0f, 1f))
add(ParamSpec("o${o}oct", "Osc$o Oct", 0f, -2f, 2f, isInt = true))
add(ParamSpec("o${o}semi", "Osc$o Semi", 0f, -12f, 12f, isInt = true))
add(ParamSpec("o${o}fine", "Osc$o Fine", if (o == 1) 0f else 7f, -50f, 50f))
add(ParamSpec("o${o}level", "Osc$o Level", if (o == 1) 0.8f else 0f, 0f, 1f))
add(ParamSpec("o${o}bend", "Osc$o Bend", 0f, -1f, 1f))
}
add(ParamSpec("unison", "Unison", 1f, 1f, 4f, isInt = true))
add(ParamSpec("spread", "Spread", 0.3f, 0f, 1f))
add(ParamSpec("sub", "Sub", 0f, 0f, 1f))
add(ParamSpec("noise", "Noise", 0f, 0f, 1f))
add(ParamSpec("velsens", "Velocity", 0.5f, 0f, 1f))
add(ParamSpec("wtframe", "Frame Size", choices = FRAME_SIZES))
add(ParamSpec("ftype", "Filter", choices = FILTER_TYPES))
add(ParamSpec("cutoff", "Cutoff", 0.75f, 0f, 1f))
add(ParamSpec("reso", "Resonance", 0.15f, 0f, 1f))
add(ParamSpec("keytrack", "Key Track", 0.4f, 0f, 1f))
add(ParamSpec("fenv", "Env Amount", 0.2f, -1f, 1f))
add(ParamSpec("drive", "Drive", 0f, 0f, 1f))
add(ParamSpec("attack", "Attack", 0.01f, 0f, 5f))
add(ParamSpec("decay", "Decay", 0.3f, 0f, 5f))
add(ParamSpec("sustain", "Sustain", 0.8f, 0f, 1f))
add(ParamSpec("release", "Release", 0.4f, 0f, 8f))
add(ParamSpec("mattack", "Mod Attack", 0.5f, 0f, 10f))
add(ParamSpec("mdecay", "Mod Decay", 2f, 0f, 10f))
add(ParamSpec("msustain", "Mod Sustain", 0.5f, 0f, 1f))
add(ParamSpec("mrelease", "Mod Release", 1f, 0f, 10f))
add(ParamSpec("menvpos", "Env > Position", 0.3f, -1f, 1f))
add(ParamSpec("lfowave", "LFO Wave", choices = LFO_WAVES))
add(ParamSpec("lfodiv", "LFO Sync", 1f, 0f, (TimeDivision.entries.size - 1).toFloat(), isInt = true))
add(ParamSpec("lfopos", "LFO > Position", 0.15f, 0f, 1f))
add(ParamSpec("lfopitch", "LFO > Pitch", 0f, 0f, 1f))
add(ParamSpec("lfocut", "LFO > Cutoff", 0f, 0f, 1f))
}
}
val SECTIONS: List<Pair<String, List<String>>> = listOf(
"Osc 1" to listOf("o1table", "o1pos", "o1oct", "o1semi", "o1fine", "o1level", "o1bend"),
"Osc 2" to listOf("o2table", "o2pos", "o2oct", "o2semi", "o2fine", "o2level", "o2bend"),
"Voice" to listOf("unison", "spread", "sub", "noise", "velsens", "wtframe"),
"Filter" to listOf("ftype", "cutoff", "reso", "keytrack", "fenv", "drive"),
"Amp Env" to listOf("attack", "decay", "sustain", "release"),
"Mod Env" to listOf("mattack", "mdecay", "msustain", "mrelease", "menvpos"),
"LFO" to listOf("lfowave", "lfodiv", "lfopos", "lfopitch", "lfocut"),
)
class Preset(val name: String, val values: Map<String, String>)
val FACTORY: List<Preset> by lazy {
fun p(name: String, vararg v: Pair<String, Any>): Preset {
val m = LinkedHashMap<String, String>()
for (spec in PARAMS) m[spec.key] = if (spec.isEnum) spec.choices[0] else spec.default.toString()
for ((k, x) in v) m[k] = x.toString()
return Preset(name, m)
}
listOf(
p("Morph Lead", "o1table" to "Classic", "o1pos" to 0.4f, "menvpos" to 0.5f, "mattack" to 0.01f, "mdecay" to 0.8f, "msustain" to 0.2f,
"cutoff" to 0.8f, "reso" to 0.25f, "lfopitch" to 0.15f, "lfodiv" to 3, "release" to 0.25f),
p("Vowel Pad", "o1table" to "Vowels", "o1pos" to 0f, "o2table" to "Vowels", "o2pos" to 0.5f, "o2level" to 0.6f, "o2fine" to 9f,
"unison" to 3, "spread" to 0.4f, "attack" to 0.8f, "release" to 2.5f, "mattack" to 3f, "mdecay" to 4f, "msustain" to 0.7f,
"menvpos" to 0.6f, "lfopos" to 0.2f, "lfodiv" to 0, "cutoff" to 0.7f),
p("PWM Strings", "o1table" to "PWM", "o1pos" to 0.2f, "o2table" to "PWM", "o2pos" to 0.6f, "o2level" to 0.7f, "o2fine" to -8f,
"unison" to 2, "spread" to 0.5f, "attack" to 0.4f, "release" to 1.2f, "lfopos" to 0.4f, "lfodiv" to 1, "menvpos" to 0f,
"cutoff" to 0.65f, "reso" to 0.1f),
p("Sync Sweep", "o1table" to "Sync", "o1pos" to 0f, "menvpos" to 0.9f, "mattack" to 0f, "mdecay" to 0.6f, "msustain" to 0.1f,
"cutoff" to 0.85f, "fenv" to 0.3f, "decay" to 0.5f, "sustain" to 0.6f, "release" to 0.2f, "drive" to 0.3f),
p("FM Bells", "o1table" to "FM", "o1pos" to 0.6f, "menvpos" to -0.6f, "mattack" to 0f, "mdecay" to 1.5f, "msustain" to 0f,
"attack" to 0f, "decay" to 2.5f, "sustain" to 0f, "release" to 2f, "cutoff" to 0.9f, "keytrack" to 0.8f, "fenv" to 0f),
p("Glass Keys", "o1table" to "Glass", "o1pos" to 0.2f, "o2table" to "Classic", "o2pos" to 0f, "o2oct" to 1, "o2level" to 0.3f,
"attack" to 0.005f, "decay" to 1.2f, "sustain" to 0.3f, "release" to 1f, "menvpos" to 0.4f, "mdecay" to 1.2f, "msustain" to 0.2f,
"mattack" to 0f, "cutoff" to 0.75f),
p("Organ Drift", "o1table" to "Organ", "o1pos" to 0f, "lfopos" to 0.5f, "lfodiv" to 0, "lfowave" to "Tri", "attack" to 0.02f,
"sustain" to 1f, "release" to 0.15f, "menvpos" to 0f, "cutoff" to 0.9f, "reso" to 0f),
p("Fold Bass", "o1table" to "Fold", "o1pos" to 0.1f, "o1oct" to -1, "sub" to 0.5f, "menvpos" to 0.7f, "mattack" to 0f,
"mdecay" to 0.3f, "msustain" to 0f, "attack" to 0f, "decay" to 0.4f, "sustain" to 0.7f, "release" to 0.15f,
"cutoff" to 0.55f, "fenv" to 0.35f, "drive" to 0.4f),
p("Digital Grit", "o1table" to "Digital", "o1pos" to 0.3f, "o2table" to "Digital", "o2pos" to 0.9f, "o2level" to 0.5f,
"o2semi" to 7, "lfopos" to 0.6f, "lfowave" to "S&H", "lfodiv" to 4, "menvpos" to 0f, "cutoff" to 0.8f, "reso" to 0.3f),
p("Comb Choir", "o1table" to "Comb", "o1pos" to 0f, "unison" to 4, "spread" to 0.45f, "attack" to 1.2f, "release" to 3f,
"mattack" to 6f, "mdecay" to 6f, "msustain" to 1f, "menvpos" to 1f, "cutoff" to 0.7f, "lfocut" to 0.2f, "lfodiv" to 0),
p("Odd Even Pluck", "o1table" to "Odd Even", "o1pos" to 1f, "menvpos" to -1f, "mattack" to 0f, "mdecay" to 0.5f, "msustain" to 0f,
"attack" to 0f, "decay" to 0.6f, "sustain" to 0f, "release" to 0.4f, "cutoff" to 0.7f, "fenv" to 0.4f, "reso" to 0.3f),
p("Harmonic Rise", "o1table" to "Harmonic Sweep", "o1pos" to 0f, "o2table" to "Harmonic Sweep", "o2pos" to 0f, "o2level" to 0.6f,
"o2fine" to 10f, "unison" to 2, "spread" to 0.3f, "attack" to 2f, "release" to 3f, "mattack" to 5f, "mdecay" to 8f,
"msustain" to 1f, "menvpos" to 1f, "cutoff" to 0.85f, "reso" to 0.05f),
)
}
}
@@ -0,0 +1,333 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.wavetable
import cc.tiredsysadmin.android.sizzle.audio.SampleStore
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.exp
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
import kotlin.math.round
import kotlin.math.sin
import kotlin.math.sqrt
/**
* A wavetable ready to play: [frames] single cycles, each kept as band-limited
* copies, one per octave ("mip levels"). Level k holds at most `512 >> k`
* harmonics in a cycle of [size]`(k)` samples (at least four samples per top
* harmonic, so linear interpolation is clean); the top quarter of each level's
* harmonics is faded out with a raised cosine, so moving from one level to the next
* as the pitch rises is not heard as a step. The voice picks the level whose top
* harmonic stays under Nyquist.
*/
class WaveTable(val name: String, val frames: Int, /** [level][frame * size(level) + i] */ val data: Array<FloatArray>) {
fun size(level: Int) = SIZES[level]
companion object {
const val MAX_HARMONICS = 512
const val LEVELS = 10
val SIZES = IntArray(LEVELS) { k -> max(64, 4 * (MAX_HARMONICS shr k)) }
/** Harmonics level k carries. */
fun harmonics(level: Int) = MAX_HARMONICS shr level
}
}
/**
* The wavetable synth's tables: twelve factory tables made here from formulas (no
* audio files ship), and tables imported from WAV files (Serum's 2048-sample frames,
* WaveEdit's 256, or any power-of-two frame length).
*
* Everything is built off the audio thread: [prewarm] makes the factory set in the
* background at startup; an imported table is built when it is loaded, or — after a
* restart, when only its WAV comes back — on a worker the first time a voice asks
* ([forSample]). Lookups never block; a table that isn't ready yet is silent.
*
* All original work for Sizzle: the method (spectra, an inverse FFT per octave with
* a taper at the top) is the textbook way to band-limit a wavetable.
*/
object WaveTables {
const val FRAMES = 16
private const val GEN = 4096 // the cycle length the formulas are sampled at
val FACTORY_NAMES = listOf(
"Classic", "PWM", "Vowels", "Harmonic Sweep", "Sync", "FM",
"Organ", "Fold", "Digital", "Glass", "Odd Even", "Comb",
)
const val CUSTOM = "Custom"
private val cache = ConcurrentHashMap<String, WaveTable>()
private val building = ConcurrentHashMap.newKeySet<String>()
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "sizzle-wavetables").apply { isDaemon = true; priority = Thread.MIN_PRIORITY } }
@Volatile private var started = false
fun factory(name: String): WaveTable? = cache[name]
/** The table built from the custom sample [id] cut in [frameLen]-sample frames (0: detect),
* or null while it is being built (it is then queued once). */
fun forSample(id: String, frameLen: Int): WaveTable? {
if (id.isEmpty()) return null
val key = "$id#$frameLen"
cache[key]?.let { return it }
if (building.add(key)) worker.execute {
SampleStore.get(id)?.let { s -> cache[key] = fromSamples(CUSTOM, s.data, frameLen) }
building.remove(key)
}
return null
}
/** Build a custom table now (the caller is off the audio thread) and cache it. */
fun buildForSample(id: String, frameLen: Int): WaveTable? {
val s = SampleStore.get(id) ?: return null
return fromSamples(CUSTOM, s.data, frameLen).also { cache["$id#$frameLen"] = it }
}
fun prewarm() {
if (started) return
started = true
worker.execute { prewarmBlocking() }
}
fun prewarmBlocking() {
for (n in FACTORY_NAMES) if (!cache.containsKey(n)) cache[n] = makeFactory(n)
}
// ------------------------------------------------------------ building ---
/** A table from cycles given as time-domain samples ([cycles] of equal power-of-two length). */
private fun fromCycles(name: String, cycles: List<FloatArray>): WaveTable {
val spectra = cycles.map { spectrum(it) }
return fromSpectra(name, spectra)
}
/** [spectra]: per frame, cosine and sine amplitudes of harmonics 1..512 (index h-1). */
private fun fromSpectra(name: String, spectra: List<Pair<FloatArray, FloatArray>>): WaveTable {
val nf = spectra.size
val data = Array(WaveTable.LEVELS) { k -> FloatArray(nf * WaveTable.SIZES[k]) }
for (k in 0 until WaveTable.LEVELS) {
val n = WaveTable.SIZES[k]
val hk = WaveTable.harmonics(k)
val re = DoubleArray(n); val im = DoubleArray(n)
for (f in 0 until nf) {
val (c, s) = spectra[f]
re.fill(0.0); im.fill(0.0)
for (h in 1..min(hk, c.size)) {
val taper = taper(h, hk)
if (taper <= 0.0) continue
re[h] = c[h - 1] * taper
im[h] = -s[h - 1] * taper
}
fft(re, im, inverse = true)
val base = f * n
for (i in 0 until n) data[k][base + i] = re[i].toFloat()
}
}
return WaveTable(name, nf, data)
}
/** The top quarter of a level's harmonics fades out (raised cosine). */
private fun taper(h: Int, hk: Int): Double {
if (hk <= 4) return if (h <= hk) 1.0 else 0.0
val a = 0.75 * hk
return when {
h <= a -> 1.0
h > hk -> 0.0
else -> 0.5 + 0.5 * cos(PI * (h - a) / (hk - a + 1))
}
}
/** Harmonics 1..512 of one cycle (any power-of-two length; others are resampled). */
private fun spectrum(cycle0: FloatArray): Pair<FloatArray, FloatArray> {
val cycle = if (Integer.bitCount(cycle0.size) == 1) cycle0 else resample(cycle0, 2048)
val m = cycle.size
val re = DoubleArray(m) { cycle[it].toDouble() }
val im = DoubleArray(m)
fft(re, im, inverse = false)
val hn = min(WaveTable.MAX_HARMONICS, m / 2 - 1)
val c = FloatArray(WaveTable.MAX_HARMONICS); val s = FloatArray(WaveTable.MAX_HARMONICS)
for (h in 1..hn) { c[h - 1] = (2.0 * re[h] / m).toFloat(); s[h - 1] = (-2.0 * im[h] / m).toFloat() }
return c to s
}
private fun resample(x: FloatArray, n: Int): FloatArray = FloatArray(n) { i ->
val p = i.toDouble() * x.size / n
val j = p.toInt(); val fr = (p - j).toFloat()
x[j % x.size] + (x[(j + 1) % x.size] - x[j % x.size]) * fr
}
/** In-place radix-2 complex FFT; [inverse] uses e^{+i} and no 1/N (the synthesis sum). */
private fun fft(re: DoubleArray, im: DoubleArray, inverse: Boolean) {
val n = re.size
var j = 0
for (i in 1 until n) {
var bit = n shr 1
while (j and bit != 0) { j = j xor bit; bit = bit shr 1 }
j = j xor bit
if (i < j) { var t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t }
}
var len = 2
while (len <= n) {
val ang = 2 * PI / len * (if (inverse) 1 else -1)
val wr = cos(ang); val wi = sin(ang)
var i = 0
while (i < n) {
var cr = 1.0; var ci = 0.0
for (k in 0 until len / 2) {
val ar = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci
val ai = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr
re[i + k + len / 2] = re[i + k] - ar; im[i + k + len / 2] = im[i + k] - ai
re[i + k] += ar; im[i + k] += ai
val ncr = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = ncr
}
i += len
}
len = len shl 1
}
}
// -------------------------------------------------------------- import ---
/**
* The frame length of a wavetable WAV: Serum's `clm ` chunk ("<!>2048 …") when
* present, else WaveEdit's 64 x 256 layout, else 2048 or 256 if the length divides,
* else the whole file as one cycle (0).
*/
fun detectFrameLength(wavBytes: ByteArray, frames: Int): Int {
val clm = indexOf(wavBytes, "clm ".toByteArray())
if (clm >= 0) {
val text = String(wavBytes, clm + 8, min(32, wavBytes.size - clm - 8), Charsets.US_ASCII)
Regex("<!>(\\d{2,5})").find(text)?.groupValues?.get(1)?.toIntOrNull()?.let { if (it in 16..8192 && frames % it == 0) return it }
}
return guessFrameLength(frames)
}
fun guessFrameLength(frames: Int): Int = when {
frames == 64 * 256 -> 256
frames % 2048 == 0 && frames / 2048 in 1..256 -> 2048
frames % 256 == 0 && frames / 256 in 1..256 -> 256
frames % 1024 == 0 && frames / 1024 in 1..256 -> 1024
frames % 512 == 0 && frames / 512 in 1..256 -> 512
else -> 0
}
private fun indexOf(h: ByteArray, n: ByteArray): Int {
outer@ for (i in 0..h.size - n.size) { for (j in n.indices) if (h[i + j] != n[j]) continue@outer; return i }
return -1
}
/** A table from a sample cut into [frameLen0]-sample cycles (0: detect; at most 256 frames). */
fun fromSamples(name: String, x: FloatArray, frameLen0: Int): WaveTable {
val frameLen = if (frameLen0 > 0) frameLen0 else guessFrameLength(x.size)
val cycles = if (frameLen <= 0 || x.size < frameLen) listOf(x.copyOf())
else {
val n = min(256, x.size / frameLen)
val step = (x.size / frameLen).toDouble() / n
List(n) { i -> val f = (i * step).toInt(); x.copyOfRange(f * frameLen, (f + 1) * frameLen) }
}
var pk = 1e-9f
for (c in cycles) for (v in c) pk = max(pk, abs(v))
val g = 1f / pk
return fromCycles(name, cycles.map { c -> FloatArray(c.size) { c[it] * g } })
}
// ------------------------------------------------------------- factory ---
private fun makeFactory(name: String): WaveTable {
val cycles = List(FRAMES) { f ->
val t = f / (FRAMES - 1.0)
val x = DoubleArray(GEN) { i -> sample(name, t, f, i.toDouble() / GEN) }
val dc = x.average()
var pk = 1e-9
for (i in x.indices) { x[i] -= dc; pk = max(pk, abs(x[i])) }
FloatArray(GEN) { (x[it] / pk).toFloat() }
}
return fromCycles(name, cycles)
}
private fun saw(p: Double) = 2 * (p - floor(p)) - 1
private fun pulse(p: Double, w: Double) = if (p - floor(p) < w) 1.0 else -1.0
private fun tri(p: Double) = 1 - 4 * abs((p - floor(p)) - 0.5)
private fun sine(p: Double) = sin(2 * PI * p)
/** Additive: harmonics 1..n with amplitude a(h), all sine phase. */
private inline fun additive(p: Double, n: Int, a: (Int) -> Double): Double {
var s = 0.0
for (h in 1..n) { val v = a(h); if (v != 0.0) s += v * sin(2 * PI * h * p) }
return s
}
private val VOWELS = arrayOf( // formant centre frequencies (Hz): a, e, i, o, u
doubleArrayOf(800.0, 1150.0, 2900.0), doubleArrayOf(400.0, 1600.0, 2700.0), doubleArrayOf(300.0, 2300.0, 3000.0),
doubleArrayOf(450.0, 800.0, 2830.0), doubleArrayOf(325.0, 700.0, 2530.0),
)
private val DRAWBARS = arrayOf( // levels of harmonics 1, 2, 3, 4, 6, 8 (and the 16' sub as h1)
doubleArrayOf(8.0, 8.0, 8.0, 0.0, 0.0, 0.0), doubleArrayOf(8.0, 0.0, 8.0, 6.0, 0.0, 4.0),
doubleArrayOf(6.0, 8.0, 4.0, 8.0, 3.0, 2.0), doubleArrayOf(8.0, 3.0, 0.0, 8.0, 8.0, 8.0),
)
/** Glass: sparse prime and square-ish harmonics at seeded levels, a new set every
* four frames, crossfaded between. */
private val GLASS: Array<DoubleArray> by lazy {
val primes = setOf(1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)
val squares = setOf(1, 2, 4, 6, 9, 12, 16, 20, 25, 30, 36)
val sets = Array(FRAMES / 4 + 2) { k ->
val rng = java.util.Random(0x61A55L + k)
val pick = if (k % 2 == 0) primes else squares
DoubleArray(40) { h -> if ((h + 1) in pick) 0.2 + 0.8 * rng.nextDouble() else 0.0 }
}
Array(FRAMES) { f ->
val k = f / 4; val fr = (f % 4) / 4.0
DoubleArray(40) { h -> sets[k][h] * (1 - fr) + sets[k + 1][h] * fr }
}
}
private val CLASSIC: Array<(Double) -> Double> = arrayOf({ q -> sine(q) }, { q -> tri(q) }, { q -> saw(q) },
{ q -> pulse(q, 0.5) }, { q -> pulse(q, 0.25) })
private fun sample(name: String, t: Double, f: Int, p: Double): Double = when (name) {
"Classic" -> {
val x = t * 4; val i = min(3, x.toInt()); val fr = x - i
CLASSIC[i](p) * (1 - fr) + CLASSIC[i + 1](p) * fr
}
"PWM" -> pulse(p, 0.5 - 0.46 * t)
"Vowels" -> {
val x = t * 4; val i = min(3, x.toInt()); val fr = x - i
additive(p, 60) { h ->
val hz = h * 110.0
var a = 0.0
for (k in 0 until 3) {
val fc = VOWELS[i][k] * (1 - fr) + VOWELS[i + 1][k] * fr
val bw = 80.0 + 40.0 * k
a += exp(-((hz - fc) / bw).pow(2)) * (if (k == 0) 1.0 else 0.6)
}
(a + 0.02) / sqrt(h.toDouble())
}
}
"Harmonic Sweep" -> {
val n = 1.0 + 2.0.pow(t * 6)
additive(p, 65) { h -> if (h <= n) 1.0 / h else if (h - 1 < n) (n - (h - 1)) / h else 0.0 }
}
"Sync" -> saw(p * (1 + 7 * t)) * (1 - 0.3 * t * p)
"FM" -> sin(2 * PI * p + 7 * t * sin(2 * PI * p) + 1.5 * t * t * sin(4 * PI * p))
"Organ" -> {
val x = t * 3; val i = min(2, x.toInt()); val fr = x - i
val hs = intArrayOf(1, 2, 3, 4, 6, 8)
var s = 0.0
for (k in hs.indices) s += (DRAWBARS[i][k] * (1 - fr) + DRAWBARS[i + 1][k] * fr) / 8 * sine(hs[k] * p)
s
}
"Fold" -> sin((1 + 7 * t) * sin(2 * PI * p) * PI / 2)
"Digital" -> { val steps = 2.0.pow(6 - 5 * t); round(sine(p) * steps) / steps }
"Glass" -> additive(p, 40) { h -> GLASS[f][h - 1] / h.toDouble().pow(0.6) }
"Odd Even" -> additive(p, 64) { h -> if (h % 2 == 1) (1 - t) / h + t * 0.3 / h else t / h * (if (h == 2) 1.6 else 1.0) }
"Comb" -> additive(p, 64) { h -> abs(cos(PI * h * (0.02 + 0.23 * t))) / h }
else -> sine(p)
}
}
@@ -0,0 +1,290 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.wavetable
import cc.tiredsysadmin.android.sizzle.model.TimeDivision
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
import kotlin.math.PI
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
import kotlin.math.sin
import kotlin.math.sqrt
import kotlin.math.tan
import kotlin.math.tanh
/** A parsed Wavetable slot (built once per slot change, off the sample loop). */
class WavePatch(
val table: Array<String>, val pos: FloatArray, val semis: FloatArray, val level: FloatArray, val bend: FloatArray,
val unison: Int, val spread: Float, val sub: Float, val noise: Float, val velSens: Float,
val customId: String, val frameLen: Int,
val filterType: Int, val cutoff: Float, val reso: Float, val keytrack: Float, val fenv: Float, val drive: Float,
val a: Float, val d: Float, val s: Float, val r: Float,
val ma: Float, val md: Float, val ms: Float, val mr: Float, val menvPos: Float,
val lfoWave: Int, val lfoHz: Float, val lfoPos: Float, val lfoPitch: Float, val lfoCut: Float,
) {
companion object {
fun from(slot: ToolboxSlot?, tempoBpm: Float): WavePatch {
fun f(k: String, d: Float) = slot?.float(k, d) ?: d
fun c(k: String, choices: List<String>) = choices.indexOf(slot?.string(k, choices[0]) ?: choices[0]).coerceAtLeast(0)
val tables = Array(2) { o -> slot?.string("o${o + 1}table", WaveDefs.TABLES[0]) ?: WaveDefs.TABLES[0] }
val semis = FloatArray(2) { o ->
val n = o + 1
f("o${n}oct", 0f).toInt().coerceIn(-2, 2) * 12f + f("o${n}semi", 0f).toInt().coerceIn(-12, 12) +
f("o${n}fine", if (n == 1) 0f else 7f).coerceIn(-50f, 50f) / 100f
}
val frame = WaveDefs.FRAME_SIZES[c("wtframe", WaveDefs.FRAME_SIZES)].toIntOrNull() ?: 0
val beat = TimeDivision.fromIndex(f("lfodiv", 1f).toInt()).beatFraction.toFloat()
return WavePatch(
table = tables,
pos = FloatArray(2) { o -> f("o${o + 1}pos", if (o == 0) 0f else 0.3f).coerceIn(0f, 1f) },
semis = semis,
level = FloatArray(2) { o -> f("o${o + 1}level", if (o == 0) 0.8f else 0f).coerceIn(0f, 1f) },
bend = FloatArray(2) { o -> f("o${o + 1}bend", 0f).coerceIn(-1f, 1f) },
unison = f("unison", 1f).toInt().coerceIn(1, 4), spread = f("spread", 0.3f).coerceIn(0f, 1f),
sub = f("sub", 0f).coerceIn(0f, 1f), noise = f("noise", 0f).coerceIn(0f, 1f), velSens = f("velsens", 0.5f).coerceIn(0f, 1f),
customId = slot?.string(WaveDefs.SAMPLE_KEY, "") ?: "", frameLen = frame,
filterType = c("ftype", WaveDefs.FILTER_TYPES), cutoff = f("cutoff", 0.75f).coerceIn(0f, 1f),
reso = f("reso", 0.15f).coerceIn(0f, 1f), keytrack = f("keytrack", 0.4f).coerceIn(0f, 1f),
fenv = f("fenv", 0.2f).coerceIn(-1f, 1f), drive = f("drive", 0f).coerceIn(0f, 1f),
a = f("attack", 0.01f), d = f("decay", 0.3f), s = f("sustain", 0.8f).coerceIn(0f, 1f), r = f("release", 0.4f),
ma = f("mattack", 0.5f), md = f("mdecay", 2f), ms = f("msustain", 0.5f).coerceIn(0f, 1f), mr = f("mrelease", 1f),
menvPos = f("menvpos", 0.3f).coerceIn(-1f, 1f),
lfoWave = c("lfowave", WaveDefs.LFO_WAVES),
lfoHz = if (beat > 0f) (tempoBpm / 60f) / beat else 1f,
lfoPos = f("lfopos", 0.15f).coerceIn(0f, 1f), lfoPitch = f("lfopitch", 0f).coerceIn(0f, 1f),
lfoCut = f("lfocut", 0f).coerceIn(0f, 1f),
)
}
val DEFAULT: WavePatch by lazy { from(null, 120f) }
}
}
/**
* One note of the wavetable synth:
*
* 2 wavetable oscillators (each: table, position through its frames, pitch, level,
* phase bend, up to 4 unison copies) + a sub sine + noise → drive → state-variable
* filter (low / band / high) → amp envelope
*
* A second envelope and a tempo-synced LFO move the table position, the cutoff and
* (LFO) the pitch. Every [CTRL] samples the voice re-reads its tables, positions and
* filter, and picks per oscillator the band-limited level whose top harmonic stays
* under Nyquist — counting how much BEND steepens the wave — so nothing aliases.
* Reads are linear within a cycle (each level keeps four samples per top harmonic)
* and linear between the two neighbouring frames.
*
* BEND is a two-segment phase warp (as in phase-distortion synthesis): the first
* half of the cycle is squeezed (bend > 0) or stretched (bend < 0), sharpening the
* wave without changing its pitch.
*/
class WaveVoice(private val fs: Int) {
private val fsf = fs.toFloat()
private var patch = WavePatch.DEFAULT
var note = -1; private set
private var vel = 0f
private var baseHz = 440f
private val amp = Env()
private val mod = Env()
// oscillators: [osc * MAX_UNISON + u]
private val phase = DoubleArray(2 * MAX_UNISON)
private val inc = DoubleArray(2 * MAX_UNISON)
private val oscTable = arrayOfNulls<WaveTable>(2)
private val oscLevel = IntArray(2)
private val oscFrame = FloatArray(2)
private val oscWarpM = FloatArray(2)
private var subPhase = 0.0
private var subInc = 0.0
// filter (topology-preserving SVF)
private var s1 = 0f; private var s2 = 0f
private var fa1 = 0f; private var fa2 = 0f; private var fa3 = 0f; private var fk = 1f
private var lfoPh = 0.0
private var lfoVal = 0f
private var shVal = 0f
private var ctrl = 0
private var rng = 0x6C8E9CF5
val isActive: Boolean get() = amp.active
val isGated: Boolean get() = amp.gate
fun noteOn(midi: Int, velocity: Float, p: WavePatch) {
val fresh = !amp.active
patch = p
note = midi
vel = velocity.coerceIn(0f, 1f)
baseHz = (440.0 * 2.0.pow((midi - 69) / 12.0)).toFloat()
amp.on(p.a, p.d, p.s, p.r)
mod.on(p.ma, p.md, p.ms, p.mr)
if (fresh) {
s1 = 0f; s2 = 0f; lfoPh = 0.0
for (i in phase.indices) phase[i] = if (i % MAX_UNISON == 0 && p.unison == 1) 0.0 else rand01().toDouble()
subPhase = 0.0
}
ctrl = 0
}
fun noteOff() { amp.off(); mod.off() }
fun kill() { amp.kill(); mod.kill(); note = -1; s1 = 0f; s2 = 0f }
fun setPatch(p: WavePatch) { patch = p; amp.retime(p.a, p.d, p.s, p.r); mod.retime(p.ma, p.md, p.ms, p.mr) }
fun render(): Float {
if (!amp.active) return 0f
if (ctrl <= 0) { control(); ctrl = CTRL }
ctrl--
val p = patch
var mix = 0f
val uni = p.unison
val uniGain = 1f / sqrt(uni.toFloat())
for (o in 0 until 2) {
val t = oscTable[o] ?: continue
val lvl = p.level[o]
if (lvl <= 0.0001f) continue
val lv = oscLevel[o]
val size = t.size(lv)
val data = t.data[lv]
val fpos = oscFrame[o]
val f0 = fpos.toInt().coerceAtMost(t.frames - 1)
val f1 = min(f0 + 1, t.frames - 1)
val ff = fpos - f0
val b0 = f0 * size; val b1 = f1 * size
val mask = size - 1
val m = oscWarpM[o]
var acc = 0f
for (u in 0 until uni) {
val k = o * MAX_UNISON + u
var ph = phase[k] + inc[k]
if (ph >= 1.0) ph -= 1.0
phase[k] = ph
// BEND: the cycle's first part squeezed into half (m < 0.5) or stretched (m > 0.5)
val pw = if (m == 0.5f) ph.toFloat() else {
val q = ph.toFloat()
if (q < m) 0.5f * q / m else 0.5f + 0.5f * (q - m) / (1f - m)
}
val x = pw * size
val i0 = x.toInt() and mask
val i1 = (i0 + 1) and mask
val fr = x - x.toInt()
val a0 = data[b0 + i0] + (data[b0 + i1] - data[b0 + i0]) * fr
val a1 = data[b1 + i0] + (data[b1 + i1] - data[b1 + i0]) * fr
acc += a0 + (a1 - a0) * ff
}
mix += acc * uniGain * lvl
}
if (p.sub > 0.0001f) {
subPhase += subInc
if (subPhase >= 1.0) subPhase -= 1.0
mix += p.sub * sin(2.0 * PI * subPhase).toFloat()
}
if (p.noise > 0.0001f) mix += p.noise * 0.5f * (rand01() * 2f - 1f)
if (p.drive > 0.001f) { val g = 1f + 4f * p.drive; mix = tanh(mix * g) / tanh(g) }
// the state-variable filter (Zavalishin / Simper TPT form)
val v3 = mix - s2
val v1 = fa1 * s1 + fa2 * v3
val v2 = s2 + fa2 * s1 + fa3 * v3
s1 = 2f * v1 - s1
s2 = 2f * v2 - s2
val y = when (p.filterType) { 1 -> v1; 2 -> mix - fk * v1 - v2; else -> v2 }
val e = amp.next(1f / fsf)
mod.next(1f / fsf)
val out = y * e * (1f - p.velSens + p.velSens * vel) * OUT_GAIN
return if (out.isFinite()) out else { kill(); 0f }
}
private fun control() {
val p = patch
val dt = CTRL / fsf
// LFO
lfoPh += p.lfoHz * dt
if (lfoPh >= 1.0) { lfoPh -= floor(lfoPh); shVal = rand01() * 2f - 1f }
val ph = lfoPh.toFloat()
lfoVal = when (p.lfoWave) {
1 -> 1f - 4f * kotlin.math.abs(ph - 0.5f)
2 -> 2f * ph - 1f
3 -> if (ph < 0.5f) 1f else -1f
4 -> shVal
else -> sin(2f * PI.toFloat() * ph)
}
val menv = mod.level
val vibCents = p.lfoPitch * 50f * lfoVal // up to ±50 cents
for (o in 0 until 2) {
val t = if (p.table[o] == WaveTables.CUSTOM) WaveTables.forSample(p.customId, p.frameLen) else WaveTables.factory(p.table[o])
oscTable[o] = t
if (t == null) continue
val pos = (p.pos[o] + p.menvPos * menv + p.lfoPos * 0.5f * lfoVal).coerceIn(0f, 1f)
oscFrame[o] = pos * (t.frames - 1)
val b = p.bend[o]
val m = if (b >= 0f) 0.5f * (1f - 0.9f * b) else 0.5f * (1f + 0.9f * -b)
oscWarpM[o] = m
val slope = 0.5f / min(m, 1f - m)
val hz = baseHz * 2f.pow((p.semis[o] + vibCents / 100f) / 12f)
val uni = p.unison
var top = hz
for (u in 0 until uni) {
val cents = if (uni == 1) 0f else p.spread * 30f * (2f * u / (uni - 1) - 1f)
val f = hz * 2f.pow(cents / 1200f)
inc[o * MAX_UNISON + u] = (f / fsf).toDouble()
if (f > top) top = f
}
// the band-limited level: its top harmonic (times BEND's steepening) under 0.45 fs
val hmax = 0.45f * fsf / (top * slope)
oscLevel[o] = if (hmax >= WaveTable.MAX_HARMONICS) 0
else ceil(ln(WaveTable.MAX_HARMONICS / max(1f, hmax)) / LN2).toInt().coerceIn(0, WaveTable.LEVELS - 1)
}
subInc = (baseHz * 0.5f * 2f.pow(p.semis[0] / 12f) / fsf).toDouble()
// filter: cutoff 20 Hz .. 20 kHz on an exponential scale, key tracking around C4
val c = p.cutoff + p.keytrack * (note - 60) / 120f + p.fenv * menv * 0.6f + p.lfoCut * 0.3f * lfoVal
val fc = (20f * 1000f.pow(c.coerceIn(0f, 1f))).coerceAtMost(0.45f * fsf)
val g = tan(PI.toFloat() * fc / fsf)
fk = 2f - 1.96f * p.reso
fa1 = 1f / (1f + g * (g + fk)); fa2 = g * fa1; fa3 = g * fa2
}
private fun rand01(): Float {
var x = rng
x = x xor (x shl 13); x = x xor (x ushr 17); x = x xor (x shl 5)
rng = x
return (x ushr 8) * (1f / 16777216f)
}
/** Linear ADSR, levels 0..1; a release reaches 0 in its time from any level. */
private class Env {
private var stage = 0 // 0 idle, 1 attack, 2 decay, 3 sustain, 4 release
var level = 0f; private set
private var a = 0.01f; private var d = 0.1f; private var s = 0.7f; private var r = 0.2f
val active get() = stage != 0
val gate get() = stage in 1..3
fun on(aa: Float, dd: Float, ss: Float, rr: Float) { retime(aa, dd, ss, rr); stage = 1 }
fun retime(aa: Float, dd: Float, ss: Float, rr: Float) { a = max(aa, 0.0005f); d = max(dd, 0.001f); s = ss; r = max(rr, 0.001f) }
fun off() { if (stage != 0) stage = 4 }
fun kill() { stage = 0; level = 0f }
fun next(dt: Float): Float {
when (stage) {
1 -> { level += dt / a; if (level >= 1f) { level = 1f; stage = 2 } }
2 -> { level -= dt / d * (1f - s); if (level <= s) { level = s; stage = 3 } }
4 -> { level -= dt / r; if (level <= 0f) { level = 0f; stage = 0 } }
}
return level
}
}
companion object {
const val MAX_UNISON = 4
private const val CTRL = 16
private const val OUT_GAIN = 0.45f
private val LN2 = ln(2f)
}
}
@@ -0,0 +1,152 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.wavetable
import cc.tiredsysadmin.android.sizzle.audio.SampleStore
import cc.tiredsysadmin.android.sizzle.audio.SynthPatch
import cc.tiredsysadmin.android.sizzle.audio.SynthVoice
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
import cc.tiredsysadmin.android.sizzle.model.ToolboxType
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.BeforeClass
import org.junit.Test
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.round
import kotlin.math.sin
import kotlin.math.sqrt
class WavetableTest {
companion object {
@JvmStatic @BeforeClass fun tables() = WaveTables.prewarmBlocking()
}
private val fs = 48_000
private fun slot(preset: String? = null, vararg extra: Pair<String, String>): ToolboxSlot =
ToolboxSlot(0).apply {
fill(ToolboxType.WAVETABLE)
preset?.let { n -> WaveDefs.FACTORY.first { it.name == n }.values.forEach { (k, v) -> set(k, v) } }
extra.forEach { (k, v) -> set(k, v) }
}
private fun voice(s: ToolboxSlot, note: Int, vel: Float = 0.8f) =
WaveVoice(fs).apply { noteOn(note, vel, WavePatch.from(s, 120f)) }
/** |DFT|^2 of x (Hann-windowed) at bins 0..n/2. */
private fun power(x: FloatArray): DoubleArray {
val n = x.size
val w = DoubleArray(n) { x[it] * (0.5 - 0.5 * cos(2 * PI * it / n)) }
return DoubleArray(n / 2) { k ->
var re = 0.0; var im = 0.0
val a = 2 * PI * k / n
for (i in 0 until n) { re += w[i] * cos(a * i); im -= w[i] * sin(a * i) }
re * re + im * im
}
}
@Test fun factoryTablesAreBuiltAndBandLimited() {
for (name in WaveTables.FACTORY_NAMES) {
val t = WaveTables.factory(name)!!
assertEquals(name, WaveTables.FRAMES, t.frames)
for (k in 0 until WaveTable.LEVELS) assertTrue(name, t.data[k].all { it.isFinite() && abs(it) < 2f })
// level 4 keeps 32 harmonics: nothing from harmonic 33 on, in any frame
val k = 4; val n = t.size(k)
for (f in 0 until t.frames) {
val x = FloatArray(n) { t.data[k][f * n + it] }
val p = DoubleArray(n / 2) { h ->
var re = 0.0; var im = 0.0
for (i in 0 until n) { re += x[i] * cos(2 * PI * h * i / n); im += x[i] * sin(2 * PI * h * i / n) }
re * re + im * im
}
val total = p.sum() + 1e-12
val above = p.drop(WaveTable.harmonics(k) + 1).sum()
assertTrue("$name frame $f above-band ${above / total}", above / total < 1e-6)
}
}
}
@Test fun aHighSawDoesNotAlias() {
// Classic at 0.5 is the saw; C7 (2093 Hz) has only 10 harmonics under Nyquist
val v = voice(slot(null, "o1table" to "Classic", "o1pos" to "0.5", "menvpos" to "0.0", "lfopos" to "0.0",
"cutoff" to "1.0", "reso" to "0.0", "keytrack" to "0.0", "fenv" to "0.0", "sustain" to "1.0"), 96)
repeat(fs / 10) { v.render() }
val n = 4096
val x = FloatArray(n) { v.render() }
val p = power(x)
val f0 = 440.0 * Math.pow(2.0, (96 - 69) / 12.0)
var harm = 0.0; var total = 0.0
for (k in p.indices) {
total += p[k]
val hz = k.toDouble() * fs / n
val h = round(hz / f0)
if (h >= 1 && abs(hz - h * f0) <= 4.0 * fs / n) harm += p[k]
}
val alias = 1 - harm / total
println("C7 saw: off-harmonic energy ${"%.2e".format(alias)}")
assertTrue("aliased energy $alias", alias < 1e-3)
}
@Test fun pitchFollowsTheNote() {
val v = voice(slot(null, "o1table" to "Classic", "o1pos" to "0.0", "menvpos" to "0.0", "lfopos" to "0.0", "cutoff" to "1.0", "sustain" to "1.0"), 69)
repeat(fs / 10) { v.render() }
var prev = v.render(); var crossings = 0
repeat(fs) { val x = v.render(); if (prev < 0f && x >= 0f) crossings++; prev = x }
assertEquals(440, crossings)
}
@Test fun serumAndWaveEditFrameLengthsAreDetected() {
val serum = FloatArray(4 * 2048) { sin(2 * PI * (it % 2048) / 2048.0).toFloat() * 0.5f }
val bytes = SampleStore.encodeWav(SampleStore.Sample(serum, 44100)) +
"clm ".toByteArray() + byteArrayOf(16, 0, 0, 0) + "<!>2048 01000000".toByteArray()
assertEquals(2048, WaveTables.detectFrameLength(bytes, serum.size))
assertEquals(256, WaveTables.guessFrameLength(64 * 256)) // WaveEdit
assertEquals(2048, WaveTables.guessFrameLength(16 * 2048))
val t = WaveTables.fromSamples("t", serum, 2048)
assertEquals(4, t.frames)
val n = t.size(0)
val peak = (0 until n).maxOf { abs(t.data[0][it]) }
assertEquals(1f, peak, 0.02f) // normalised
}
@Test fun everyFactoryPresetPlaysAndFrees() {
assertEquals(12, WaveDefs.FACTORY.size)
for (p in WaveDefs.FACTORY) {
val v = voice(slot(p.name), 57)
var s = 0.0; var finite = true; var peak = 0f
repeat(fs * 2) { val x = v.render(); if (!x.isFinite()) finite = false; s += x * x; peak = maxOf(peak, abs(x)) }
val rms = sqrt(s / (fs * 2)).toFloat()
println("${p.name}: rms ${"%.3f".format(rms)} peak ${"%.3f".format(peak)}")
assertTrue(p.name, finite && rms > 0.01f && peak < 1.2f)
v.noteOff()
var frames = 0
while (v.isActive && frames < fs * 10) { v.render(); frames++ }
assertFalse("${p.name} frees", v.isActive)
}
}
@Test fun aWavetableNoteIsAboutAsLoudAsASynthNote() {
fun rms(v: SynthVoice): Float { repeat(fs / 2) { v.render() }; var s = 0.0; repeat(fs) { val x = v.render(); s += x * x }; return sqrt(s / fs).toFloat() }
val wt = SynthVoice(fs).apply { noteOn(60, 100, SynthPatch.forWave(WavePatch.from(slot("Morph Lead"), 120f))) }
val syn = SynthVoice(fs).apply { noteOn(60, 100, SynthPatch.DEFAULT) }
val ratio = rms(wt) / rms(syn)
println("wavetable/synth rms ratio $ratio")
assertTrue("ratio $ratio within -6..+6 dB", ratio in 0.5f..2f)
}
@Test fun cpuBudgetForFullPolyphony() {
val s = slot("Vowel Pad", "unison" to "4", "o2level" to "0.8")
val voices = Array(32) { voice(s, 40 + it) }
repeat(fs / 2) { for (v in voices) v.render() }
val t0 = System.nanoTime()
repeat(fs * 2) { for (v in voices) v.render() }
val load = (System.nanoTime() - t0) / 1e9 / 2
println("32 wavetable voices, 2 osc x 4 unison: ${"%.1f".format(load * 100)} % of real time on this host")
assertTrue(load < 1.0)
}
}