Compare commits

..
2 Commits
Author SHA1 Message Date
ReactorcoremeltdownandClaude Opus 5 3453f9f003 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>
2026-11-03 20:28:51 +01:00
ReactorcoremeltdownandClaude Opus 5 208de84012 Separate the flick from the tap on the tracker and arrangement canvases (v0.23.0)
Both canvases detected their tap with detectTapGestures, which is the wrong
tool next to a scroll container for two reasons:

  - it CONSUMES the initial down, so the scrollable/horizontalScroll wrapped
    around the canvas had to fight for the gesture. A quick flick frequently
    did nothing, or landed as a tap and moved the cursor; only a slow,
    deliberate drag scrolled reliably.
  - it knows nothing about an in-flight fling, so tapping to halt a flick — the
    reflex every scrolling surface trains — selected a cell under a view that
    was still moving.

Replaced with detectScrollAwareTaps, shared by both canvases: it leaves the
down unconsumed so the scroll container sees the whole gesture, drops the tap
as soon as the finger travels past touch slop or the container claims a drag,
and treats a touch landing on a moving view as "stop here" rather than
"select".

Also fixes a regression from v0.22.1: keeping the cursor row on screen was
written as a standing clamp inside the scroll accessor, which made it a
constraint on the viewport rather than a reaction to the cursor moving. With
the cursor on line 0 it pinned the grid to the top and no amount of dragging
could scroll it. It is now a snapshotFlow on the cursor line that nudges the
offset only when the cursor actually moves off screen, so free scrolling is
unconstrained and a tapped cell still never moves.

Verified on an emulator (Pixel, API 34): a fast flick on the pattern grid now
flings across the whole 64-line pattern where it previously did not move at
all; a slow drag tracks 1:1 with no overshoot; a tap lands on the exact cell
and leaves the view still; the arrangement roll flings from bar 1 to bar 31 and
taps the right lane/bar. The tap-stops-a-fling path is not covered — adb cannot
inject a tap inside the fling window.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-03 20:06:14 +01:00
6 changed files with 260 additions and 29 deletions
@@ -4,6 +4,7 @@
package cc.tiredsysadmin.android.sizzle.audio package cc.tiredsysadmin.android.sizzle.audio
import kotlin.math.abs import kotlin.math.abs
import kotlin.math.exp
import kotlin.math.sin import kotlin.math.sin
import kotlin.math.tan import kotlin.math.tan
@@ -55,6 +56,18 @@ class SynthVoice(private val sampleRate: Int) {
private var shValue = 0f private var shValue = 0f
private var rng = 0x2545F491 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 ampEnv = Adsr()
private val filtEnv = Adsr() private val filtEnv = Adsr()
@@ -77,6 +90,9 @@ class SynthVoice(private val sampleRate: Int) {
lfoInc = patch.lfoHz.toDouble() / sampleRate lfoInc = patch.lfoHz.toDouble() / sampleRate
lfoPhase = 0.0 // retrigger the LFO per note for predictable modulation lfoPhase = 0.0 // retrigger the LFO per note for predictable modulation
ctrl = 0 // force a cutoff recompute on the first sample 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 // Precompute oscillator tuning so the per-sample loop skips Math.pow unless
// pitch is actually being modulated (the common case). // pitch is actually being modulated (the common case).
computeTuning() computeTuning()
@@ -187,7 +203,11 @@ class SynthVoice(private val sampleRate: Int) {
val filtered = svf(mix) val filtered = svf(mix)
// ---- amplifier ---- // ---- 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 if (a < 0f) a = 0f
val y = filtered * a * OUT_GAIN val y = filtered * a * OUT_GAIN
return if (y.isFinite()) y else 0f return if (y.isFinite()) y else 0f
@@ -296,6 +316,10 @@ class SynthVoice(private val sampleRate: Int) {
companion object { companion object {
private const val OUT_GAIN = 0.5f private const val OUT_GAIN = 0.5f
private const val CTRL_INTERVAL = 16 // samples between cutoff recomputes 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). */ /** 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) fun midiToHz(midi: Int): Double = 440.0 * Math.pow(2.0, (midi - 69) / 12.0)
} }
@@ -7,7 +7,6 @@ import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
@@ -217,11 +216,12 @@ fun ArrangementRoll(vm: AppViewModel) {
Modifier Modifier
.width(beatWidth * lengthBeats) .width(beatWidth * lengthBeats)
.fillMaxHeight() .fillMaxHeight()
// Tap selects a single cell (no toggle). The ruler is // Tap selects a single cell (no toggle); a flick scrolls
// display-only, so ruler taps are ignored. // the roll and never selects. The ruler is display-only,
.pointerInput(arr, sig) { // so ruler taps are ignored.
detectTapGestures { off -> .pointerInput(arr, sig, scroll) {
if (off.y < rulerHeightPx) return@detectTapGestures detectScrollAwareTaps(scroll) { off ->
if (off.y < rulerHeightPx) return@detectScrollAwareTaps
val laneH = (size.height - rulerHeightPx) / ArrModel.LANE_COUNT val laneH = (size.height - rulerHeightPx) / ArrModel.LANE_COUNT
val lane = ((off.y - rulerHeightPx) / laneH).toInt() val lane = ((off.y - rulerHeightPx) / laneH).toInt()
.coerceIn(0, ArrModel.LANE_COUNT - 1) .coerceIn(0, ArrModel.LANE_COUNT - 1)
@@ -7,14 +7,15 @@ import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.ScrollableState import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.scrollable import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Offset
@@ -89,13 +90,8 @@ fun PatternGrid(vm: AppViewModel, modifier: Modifier = Modifier) {
// Vertical scroll model. While PLAYING the view auto-centres on the playhead; // Vertical scroll model. While PLAYING the view auto-centres on the playhead;
// a finger flick detaches it into free inertial scrolling, and switching to // a finger flick detaches it into free inertial scrolling, and switching to
// another block re-attaches (both states are keyed on `pattern`). // another block re-attaches (both states are keyed on `pattern`). While NOT
// // playing `scrollPx` is simply where the finger left the view.
// While NOT playing the view holds still and only ever scrolls far enough to
// keep the cursor row on screen. It deliberately does NOT re-centre on the
// cursor: the cursor moves because the user just tapped a cell, and centring
// would yank that cell out from under their finger — on a pattern long enough
// to overflow, the tapped row visibly jumps to the middle of the viewport.
val following = remember(pattern) { mutableStateOf(true) } val following = remember(pattern) { mutableStateOf(true) }
val scrollPx = remember(pattern) { mutableStateOf(0f) } val scrollPx = remember(pattern) { mutableStateOf(0f) }
@@ -108,13 +104,28 @@ fun PatternGrid(vm: AppViewModel, modifier: Modifier = Modifier) {
fun effScrollPx(): Float { fun effScrollPx(): Float {
val t = transportState.value val t = transportState.value
if (t.isPlaying && following.value) return playheadScrollPx(t.currentLine) if (t.isPlaying && following.value) return playheadScrollPx(t.currentLine)
// Minimal scroll-into-view around the cursor row: `lo` is the offset that return scrollPx.value.coerceIn(0f, maxScrollPx)
// puts the cursor on the last visible line, `hi` the one that puts it on }
// the first. Anything between leaves the view exactly where it is.
val top = vm.cursorLine * rowPx // Scroll the cursor back into view when it MOVES off screen (arrow keys,
// punch-in advancing a row). Deliberately minimal and deliberately reactive:
//
// - minimal, because re-centring would yank a cell out from under the finger
// that just tapped it — on a pattern long enough to overflow, the tapped
// row visibly jumped to the middle of the viewport;
// - reactive rather than a clamp inside effScrollPx(), because a clamp is a
// standing constraint on the viewport. With the cursor on line 0 it pinned
// the view to the top and the grid could not be scrolled at all.
//
// snapshotFlow keeps this out of composition: a cursor move invalidates the
// draw phase alone, as a playhead tick does.
LaunchedEffect(pattern, rowPx, heightPx, maxScrollPx) {
snapshotFlow { vm.cursorLine }.collect { line ->
val top = line * rowPx
val lo = (top + rowPx - heightPx).coerceIn(0f, maxScrollPx) val lo = (top + rowPx - heightPx).coerceIn(0f, maxScrollPx)
val hi = top.coerceIn(lo, maxScrollPx) val hi = top.coerceIn(lo, maxScrollPx)
return scrollPx.value.coerceIn(lo, hi) scrollPx.value = effScrollPx().coerceIn(lo, hi)
}
} }
// Fling/drag scrolling. The first delta seeds the free position from wherever // Fling/drag scrolling. The first delta seeds the free position from wherever
@@ -153,11 +164,11 @@ fun PatternGrid(vm: AppViewModel, modifier: Modifier = Modifier) {
.clipToBounds() .clipToBounds()
// Inertial vertical scrolling (fling), detaching the playhead follow. // Inertial vertical scrolling (fling), detaching the playhead follow.
.scrollable(orientation = Orientation.Vertical, state = scrollState) .scrollable(orientation = Orientation.Vertical, state = scrollState)
.pointerInput(pattern, widthPx, heightPx) { .pointerInput(pattern, widthPx, heightPx, scrollState) {
// Tap moves the cursor to the cell/column. Note entry is done with // Tap moves the cursor to the cell/column; a flick scrolls and
// the punch-in keyboard or external controllers — there is no // never selects. Note entry is done with the punch-in keyboard or
// long-press cell editor. // external controllers — there is no long-press cell editor.
detectTapGestures { off -> detectScrollAwareTaps(scrollState) { off ->
hitTest(off.x, off.y)?.let { (t, col, line) -> vm.focusCell(t, line, col) } hitTest(off.x, off.y)?.let { (t, col, line) -> vm.focusCell(t, line, col) }
} }
}, },
@@ -0,0 +1,68 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.ui.tracker
import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerInputScope
import androidx.compose.ui.input.pointer.changedToUp
import androidx.compose.ui.input.pointer.positionChange
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
/**
* Tap-to-select for a canvas that also scrolls, keeping the tap strictly separate
* from the flick that scrolls it.
*
* `detectTapGestures` is the obvious tool and the wrong one here, for two reasons:
*
* - it **consumes the initial down**, which starves the scroll container wrapped
* around the canvas of the gesture. A quick flick then had to fight for the
* pointer, so it often did nothing at all, or landed as a tap and moved the
* cursor instead of scrolling. Only a slow, deliberate drag scrolled reliably.
* - it knows nothing about an **in-flight fling**, so tapping to halt a flick —
* the reflex every scrolling surface trains — selected a cell under a view that
* was still moving, which is never what was aimed at.
*
* This detector leaves the down unconsumed so the scroll container still sees the
* whole gesture; abandons the tap as soon as the finger travels past touch slop or
* the container consumes a drag; and treats a touch that lands on a moving view as
* "stop here" rather than "select".
*
* @param scrollState the scroll container this canvas lives in, consulted for an
* in-flight fling and preempted to stop one.
* @param onTap called with the canvas-local position of a tap that was not a scroll.
*/
suspend fun PointerInputScope.detectScrollAwareTaps(
scrollState: ScrollableState,
onTap: (Offset) -> Unit,
) = coroutineScope {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
// A touch that lands while the view is still flinging means "stop", not
// "select". An empty scroll block preempts the fling's mutation and ends
// immediately, leaving the state free for the drag that may follow.
val haltsFling = scrollState.isScrollInProgress
if (haltsFling) launch { scrollState.scroll { } }
// Total travel, not net displacement: a wobbly hold that wanders past slop
// is a scroll attempt (or a shaky finger), not a cell the user aimed at.
var travel = 0f
var isTap = true
while (true) {
val event = awaitPointerEvent()
val change = event.changes.firstOrNull { it.id == down.id } ?: break
travel += change.positionChange().getDistance()
// `isConsumed` == the scroll container has claimed this as a drag.
if (travel > viewConfiguration.touchSlop || change.isConsumed) isTap = false
if (change.changedToUp()) {
if (isTap && !haltsFling) onTap(change.position)
break
}
if (!change.pressed) break
}
}
}
@@ -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
}
}
+2 -2
View File
@@ -8,8 +8,8 @@
# or polish. android.versionCode is monotonic and bumps by 1 on every release, # or polish. android.versionCode is monotonic and bumps by 1 on every release,
# because F-Droid and the Android package manager order installs by it alone. # because F-Droid and the Android package manager order installs by it alone.
android.versionName = 0.22.1 android.versionName = 0.23.1
android.versionCode = 50 android.versionCode = 52
# No desktop builds exist yet. These lines are the agreed slots so a port starts # No desktop builds exist yet. These lines are the agreed slots so a port starts
# with a version instead of inventing one; `-` means "not built on this # with a version instead of inventing one; `-` means "not built on this