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
@@ -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)
}
}