Band-limit amp modulation so a Square/Saw LFO no longer clicks (v0.23.1)

The amplifier is the only modulation destination with nothing downstream to
absorb a discontinuity. Pitch feeds a phase accumulator and cutoff feeds filter
coefficients, both of which integrate a step away; the amp multiplies the
output sample directly:

    a = ampE * velocity * (1 + mAmp)
    y = filtered * a * OUT_GAIN

A Saw, Square or S&H LFO steps instantaneously, so wiring one to Amp put a
full-scale jump straight on the output — a broadband click at every edge, and
at a musical LFO rate (8 Hz is a 1/8 note at 120 BPM) that is a stream of
clicks several times a second: the reported crackle. Sine and Triangle were
unaffected because they are continuous, which is why only the stepping
waveforms were reported.

mAmp now runs through a 2 ms one-pole, so each edge becomes a short ramp. At
8 Hz a half cycle is 62 ms, so 2 ms is 3% of it and a chop still reads as a
chop. The envelope itself is deliberately NOT smoothed — it is already
continuous, and rounding it there would soften every attack. A note starts at
its modulated level rather than ramping up to it, so triggering on a square
LFO's quiet half does not blip before ducking.

Measured by the new SynthAmpModTest, worst single-sample output jump during
sustain (C3 triangle, filter wide open, LFO -> Amp at full depth):

    waveform     before     after
    Square       0.804      0.018
    S&H          0.705      0.017
    Saw          0.590      0.011
    (no mod)     0.003      0.003

Not addressed, and worth a separate look: the toolbox LFO *device* writes its
target parameter once per ~4 ms block, which steps every target for every
waveform. That is a different mechanism from the synth's own mod matrix and was
not what was reported here.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-03 20:28:51 +01:00
co-authored by Claude Opus 5
parent 208de84012
commit 3453f9f003
3 changed files with 155 additions and 3 deletions
@@ -4,6 +4,7 @@
package cc.tiredsysadmin.android.sizzle.audio
import kotlin.math.abs
import kotlin.math.exp
import kotlin.math.sin
import kotlin.math.tan
@@ -55,6 +56,18 @@ class SynthVoice(private val sampleRate: Int) {
private var shValue = 0f
private var rng = 0x2545F491
// Smoothed amplifier modulation. The amp is the one destination with nothing
// after it to absorb a discontinuity — pitch feeds a phase accumulator and
// cutoff feeds filter coefficients, both of which integrate a step away, but
// the amp multiplies the output sample directly. A Saw, Square or S&H
// modulator steps instantaneously, so routing one to Amp put a full-scale jump
// straight on the output: a click at every edge, which at a musical LFO rate
// is heard as crackling. A one-pole spreads each edge over AMP_MOD_SMOOTH_SEC.
private var ampMod = 0f
private var ampModPrimed = false
private val ampModCoeff =
(1.0 - exp(-1.0 / (sampleRate * AMP_MOD_SMOOTH_SEC))).toFloat()
private val ampEnv = Adsr()
private val filtEnv = Adsr()
@@ -77,6 +90,9 @@ class SynthVoice(private val sampleRate: Int) {
lfoInc = patch.lfoHz.toDouble() / sampleRate
lfoPhase = 0.0 // retrigger the LFO per note for predictable modulation
ctrl = 0 // force a cutoff recompute on the first sample
// Start the note AT its modulated level rather than ramping up to it, so a
// note triggered on a square LFO's quiet half does not blip before ducking.
ampModPrimed = false
// Precompute oscillator tuning so the per-sample loop skips Math.pow unless
// pitch is actually being modulated (the common case).
computeTuning()
@@ -187,7 +203,11 @@ class SynthVoice(private val sampleRate: Int) {
val filtered = svf(mix)
// ---- amplifier ----
var a = ampE * velocity * (1f + mAmp)
// Smooth the modulation, not the envelope: the ADSR is already continuous,
// and rounding it here would soften every attack.
if (ampModPrimed) ampMod += (mAmp - ampMod) * ampModCoeff
else { ampMod = mAmp; ampModPrimed = true }
var a = ampE * velocity * (1f + ampMod)
if (a < 0f) a = 0f
val y = filtered * a * OUT_GAIN
return if (y.isFinite()) y else 0f
@@ -296,6 +316,10 @@ class SynthVoice(private val sampleRate: Int) {
companion object {
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
* square edge, short enough that a chop still reads as a chop: at 8 Hz a
* half-cycle is 62 ms, so 2 ms is 3% of it. */
private const val AMP_MOD_SMOOTH_SEC = 0.002
/** Equal-tempered MIDI note -> frequency in Hz (A4 = 69 = 440 Hz). */
fun midiToHz(midi: Int): Double = 440.0 * Math.pow(2.0, (midi - 69) / 12.0)
}
@@ -0,0 +1,128 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.audio
import cc.tiredsysadmin.android.sizzle.model.SynthDefs
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.abs
/**
* The amplifier is the one modulation destination with no filter, no interpolation
* and no envelope between the modulator and the speaker: `y = filtered * gain`. A
* modulator that steps — a Square LFO's two edges per cycle, a Saw's wrap — steps
* the gain instantaneously, and an instantaneous gain step is a click. At a musical
* LFO rate that is a stream of clicks a few times a second: the reported crackle.
*
* These tests measure the worst sample-to-sample jump in the rendered output while
* the note sustains. The source is a single triangle oscillator an octave below
* middle C with the filter wide open, so the waveform itself moves only ~0.003 per
* sample — anything bigger comes from the gain, not the oscillator.
*/
class SynthAmpModTest {
private val sr = 48_000
/** Worst |y[n] - y[n-1]| over [seconds] of sustain, after the attack settles. */
private fun maxStep(patch: SynthPatch, seconds: Double = 0.5): Float {
val v = SynthVoice(sr)
v.noteOn(48, 127, patch) // C3: slow enough that the triangle itself is smooth
repeat(sr / 20) { v.render() } // 50 ms: let the attack and the smoother settle
var prev = v.render()
var worst = 0f
repeat((sr * seconds).toInt()) {
val y = v.render()
val step = abs(y - prev)
if (step > worst) worst = step
prev = y
}
return worst
}
/** A triangle-oscillator patch with one mod slot wired LFO -> Amp at full depth. */
private fun ampModPatch(lfoWave: String, amount: Float = 1f): SynthPatch {
val n = SynthDefs.OSC_COUNT
return SynthPatch(
oscWave = IntArray(n) { 0 }, // Tri on every oscillator
oscOct = IntArray(n), oscSemi = IntArray(n), oscFine = FloatArray(n),
oscLevel = FloatArray(n) { if (it == 0) 0.9f else 0f },
noiseLevel = 0f,
cutoff = 1f, resonance = 0f, keytrack = 0f, filterEnvAmt = 0f,
fA = 0f, fD = 0f, fS = 1f, fR = 0.1f,
aA = 0.001f, aD = 0f, aS = 1f, aR = 0.1f, // flat sustain: no envelope motion
lfoWave = SynthDefs.LFO_WAVES.indexOf(lfoWave),
lfoHz = 8f, // 1/8 note at 120 BPM
modSrc = IntArray(SynthPatch.MOD_SLOTS) { if (it == 0) 1 else 0 }, // LFO
modDst = IntArray(SynthPatch.MOD_SLOTS) { if (it == 0) 5 else 0 }, // Amp
modAmt = FloatArray(SynthPatch.MOD_SLOTS) { if (it == 0) amount else 0f },
)
}
/** The oscillator's own contribution, with nothing modulating the amp. The
* budget below is calibrated against this: a C3 triangle moves this little per
* sample, so a bigger jump can only have come from the gain. */
@Test fun unmodulatedToneIsSmooth() {
val step = maxStep(ampModPatch("Tri", amount = 0f))
assertTrue("a plain C3 triangle should not jump (was $step)", step < 0.01f)
}
@Test fun squareLfoToAmpDoesNotClick() {
val step = maxStep(ampModPatch("Square"))
assertTrue(
"a Square LFO on Amp stepped the gain by $step in one sample — that is " +
"the crackle; the gain must ramp instead",
step < CLICK_THRESHOLD,
)
}
@Test fun sawLfoToAmpDoesNotClick() {
val step = maxStep(ampModPatch("Saw"))
assertTrue(
"a Saw LFO on Amp stepped the gain by $step at the waveform wrap",
step < CLICK_THRESHOLD,
)
}
/** Sample & Hold steps at every clock too, for the same reason. */
@Test fun sampleHoldLfoToAmpDoesNotClick() {
val step = maxStep(ampModPatch("S&H"))
assertTrue("an S&H LFO on Amp stepped the gain by $step", step < CLICK_THRESHOLD)
}
/** The smoothing must not flatten the tremolo: a square LFO still has to swing
* the level most of the way between its two states within a half-cycle. */
@Test fun squareLfoStillModulatesTheLevel() {
val v = SynthVoice(sr)
v.noteOn(48, 127, ampModPatch("Square"))
val period = sr / 8 // 8 Hz
// The LFO retriggers at phase 0 on note-on, so a whole period lands back on
// an edge with the attack long settled. Windows must be aligned to the half
// cycles or they straddle both states and read the same peak.
repeat(period) { v.render() }
// Peak over the back three-quarters of a half cycle, skipping the ramp in.
fun halfCyclePeak(): Float {
val half = period / 2
var peak = 0f
repeat(half) { i ->
val y = v.render()
if (i > half / 4) peak = maxOf(peak, abs(y))
}
return peak
}
val loud = halfCyclePeak() // LFO == +1 -> gain 2
val quiet = halfCyclePeak() // LFO == -1 -> gain 0
assertTrue(
"the LFO should still chop the level (loud=$loud quiet=$quiet)",
quiet < loud * 0.25f,
)
}
private companion object {
/** Generous: still ~30x the unmodulated tone's own per-sample motion, but
* far below the ~1.0 full-scale jump an unsmoothed square edge produces. */
const val CLICK_THRESHOLD = 0.08f
}
}