Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-audio

Source of release 0.4.2

0.4.2 / src / effects.lucb

## Effects for sends and inserts: a plate reverb after Dattorro and the
## Lexicon 224 (the Blade Runner and Mercury7 sound), tape/BBD/digital echo
## after the RE-201 and BBD chips, Juno and Dimension choruses, a compressor
## with OTO BOUM's one-knob macro, and the Rhodes Suitcase's tremolo. Each
## runs stereo on an effect unit's one voice. Sources: reports/Analog synth
## component emulation.md. Nothing here allocates or traps.
import dsp
import analog
import kinds
from dsp import State, Ports, clampf, absf, exp2, decibels

# ---------------------------------------------------------------- delay lines
#
# A State's `line` holds several delay lines one after another; line `n`
# starts at `bases[n]`, is `lengths[n]` long, and writes at `s.heads[n]`.

## The sample written `delay` samples ago (1 ≤ delay ≤ length).
pub inline func tap(line: f32[], base: usize, length: usize, head: u32, delay: usize) -> f32:
    var at = (usize)head + length - (delay if delay <= length else length)
    if at >= length: at -= length
    return line[base + at]

## The same with a fractional delay, linearly interpolated.
pub inline func tap_frac(line: f32[], base: usize, length: usize, head: u32, delay: f32) -> f32:
    let whole = (usize)delay
    let frac = delay - (f32)whole
    let a = tap(line, base, length, head, whole if whole >= 1 else 1)
    let b = tap(line, base, length, head, whole + 1 if whole + 1 <= length else length)
    return a + (b - a) * frac

pub inline func put(line: f32[], base: usize, length: usize, head: u32*, value: f32):
    line[base + (usize)*head] = value
    var next = *head + 1
    if (usize)next >= length: next = 0
    *head = next

## A Schroeder allpass on line `n`: (g + z^-D) / (1 + g z^-D).
pub inline func allpass(line: f32[], base: usize, length: usize, head: u32*, x: f32, g: f32) -> f32:
    let d = tap(line, base, length, *head, length)
    let v = x - g * d
    put(line, base, length, head, v)
    return d + g * v

# ---------------------------------------------------------------- plate

## Dattorro's lengths at 29761 Hz (Effect Design Part 1, Fig. 1): four input
## diffusers, then each tank half's modulated allpass, delay, allpass, delay.
let plate_lengths: f32[12] = [142.0, 107.0, 379.0, 277.0, 672.0, 4453.0, 1800.0, 3720.0, 908.0, 4217.0, 2656.0, 3163.0]
## Its output taps (Table 2), as (line, offset, sign) for left then right.
let plate_taps_left: f32[21] = [9.0, 266.0, 1.0, 9.0, 2974.0, 1.0, 10.0, 1913.0, -1.0, 11.0, 1996.0, 1.0, 5.0, 1990.0, -1.0, 6.0, 187.0, -1.0, 7.0, 1066.0, -1.0]
let plate_taps_right: f32[21] = [5.0, 353.0, 1.0, 5.0, 3627.0, 1.0, 6.0, 1228.0, -1.0, 7.0, 2673.0, 1.0, 9.0, 2111.0, -1.0, 10.0, 335.0, -1.0, 11.0, 121.0, -1.0]
let most_size: f32 = 2.0
let most_predelay: f32 = 0.5

## The plate's lengths at `rate` and `size`, and where each starts.
func plate_layout(rate: f32, size: f32, lengths: usize[], bases: usize[]) -> usize:
    var at: usize = 0
    for n in 0..<12:
        let scale = rate / 29761.0 * (size if n >= 4 else 1.0)
        var length = (usize)(plate_lengths[n] * scale) + 2
        # The modulated allpasses need room to swing.
        if n == 4 or n == 8: length += 64
        lengths[n] = length
        bases[n] = at
        at += length
    # The predelay line last.
    lengths[12] = (usize)(most_predelay * rate) + 2
    bases[12] = at
    return at + lengths[12]

## A plate reverb, Dattorro's figure-eight in the style of Griesinger: four
## input diffusers, then two tank halves feeding each other through a
## chorused allpass, a long delay, damping, a second allpass and delay, read
## out by Dattorro's taps. Decay is the reverb time in seconds; Vintage runs
## the tank at half the rate behind a 9 kHz band limit, as the Lexicon 224
## did at 20 kHz (the dark long tails of Blade Runner).
## Inputs: left, right. Params: Decay (s), Size, Predelay (ms), Damping,
## Density (input diffusion), Mod Depth, Mod Rate (Hz), Low Cut (Hz), Mix,
## Vintage.
pub func plate(s: State*, p: Ports*):
    let left_in = p.inputs[0]
    let right_in = p.inputs[1] if p.wired[1] else p.inputs[0]
    let left = p.outputs[0]
    let right = p.outputs[1]
    let vintage = p.params[9] > 0.5
    let rate = p.rate * (0.5 if vintage else 1.0)
    let size = clampf(p.params[1], 0.3, most_size)
    var lengths: usize[13]
    var bases: usize[13]
    let used = plate_layout(rate, size, lengths, bases)
    let line = s.line
    if used > line.length:
        for i in 0..<p.frames:
            left[i] = left_in[i]
            right[i] = right_in[i]
        return
    # A tank loop is the two halves' four lengths; four decay gains on the way.
    var loop: f32 = 0.0
    for n in 4..<12: loop += (f32)lengths[n]
    let damping = clampf(p.params[3], 0.0, 0.95)
    # Damping drains the broadband energy too (measured: the tail lasts
    # 1 - 0.75 damping of its loop gain's time); aim past it.
    let t60 = clampf(p.params[0], 0.2, 60.0) / (1.0 - 0.75 * damping)
    let decay = exp2(-9.965784 * loop / (rate * t60) * 0.25)
    let density = clampf(p.params[4], 0.0, 1.0)
    let in1 = 0.75 * density
    let in2 = 0.625 * density
    let dd1: f32 = 0.70
    let dd2 = clampf(decay + 0.15, 0.25, 0.5)
    let excursion = clampf(p.params[5], 0.0, 1.0) * 30.0 * rate / 48000.0
    let lfo_step = clampf(p.params[6], 0.05, 5.0) / rate
    let predelay = clampf(p.params[2] * 0.001 * rate, 1.0, (f32)(lengths[12] - 1))
    let low_cut = analog.one_pole(clampf(p.params[7], 10.0, 1000.0), p.rate)
    let wet = clampf(p.params[8], 0.0, 1.0)
    let band = 0.9995 if not vintage else analog.one_pole(9000.0, p.rate)
    var lfo = (f32)s.a
    var bw = (f32)s.b
    var damp_l = (f32)s.c
    var damp_r = (f32)s.d
    var end_l = (f32)s.more[0]
    var end_r = (f32)s.more[1]
    var hp = (f32)s.more[2]
    var held_l = (f32)s.more[3]
    var held_r = (f32)s.more[4]
    var last_l = (f32)s.more[5]
    var last_r = (f32)s.more[6]
    var parity = s.heads[15]
    var gathered = (f32)s.more[7]
    for i in 0..<p.frames:
        let dry_l = left_in[i]
        let dry_r = right_in[i]
        var mono = (dry_l + dry_r) * 0.5
        hp = hp + (mono - hp) * low_cut
        mono = mono - hp
        var out_l = held_l
        var out_r = held_r
        var step = true
        if vintage:
            # Half the rate: the tank runs on every second sample's average.
            bw = bw + (mono - bw) * band
            if parity == 0:
                gathered = bw
                parity = 1
                step = false
            else:
                mono = (gathered + bw) * 0.5
                parity = 0
        if step:
            put(line, bases[12], lengths[12], &s.heads[12], mono)
            var x = tap_frac(line, bases[12], lengths[12], s.heads[12], predelay)
            if not vintage:
                bw = bw + (x - bw) * band
                x = bw
            x = allpass(line, bases[0], lengths[0], &s.heads[0], x, in1)
            x = allpass(line, bases[1], lengths[1], &s.heads[1], x, in1)
            x = allpass(line, bases[2], lengths[2], &s.heads[2], x, in2)
            x = allpass(line, bases[3], lengths[3], &s.heads[3], x, in2)
            lfo += lfo_step
            if lfo >= 1.0: lfo -= 1.0
            let swing_l = excursion * (1.0 + dsp.sin_turns(lfo)) * 0.5
            let swing_r = excursion * (1.0 + dsp.sin_turns(lfo + 0.25)) * 0.5
            # Left half, fed by the right half's end.
            var a = x + decay * end_r
            a = mod_allpass(line, bases[4], lengths[4], &s.heads[4], a, -dd1, (f32)(lengths[4] - 64) + swing_l)
            put(line, bases[5], lengths[5], &s.heads[5], a)
            var d = tap(line, bases[5], lengths[5], s.heads[5], lengths[5])
            damp_l = d + (damp_l - d) * damping
            d = damp_l * decay
            d = allpass(line, bases[6], lengths[6], &s.heads[6], d, dd2)
            put(line, bases[7], lengths[7], &s.heads[7], d)
            let next_l = tap(line, bases[7], lengths[7], s.heads[7], lengths[7]) * decay
            # Right half, fed by the left half's end.
            var b = x + decay * end_l
            b = mod_allpass(line, bases[8], lengths[8], &s.heads[8], b, -dd1, (f32)(lengths[8] - 64) + swing_r)
            put(line, bases[9], lengths[9], &s.heads[9], b)
            var e = tap(line, bases[9], lengths[9], s.heads[9], lengths[9])
            damp_r = e + (damp_r - e) * damping
            e = damp_r * decay
            e = allpass(line, bases[10], lengths[10], &s.heads[10], e, dd2)
            put(line, bases[11], lengths[11], &s.heads[11], e)
            end_r = tap(line, bases[11], lengths[11], s.heads[11], lengths[11]) * decay
            end_l = next_l
            # Dattorro's taps.
            let scale = rate / 29761.0 * size
            var yl: f32 = 0.0
            var yr: f32 = 0.0
            var t: usize = 0
            while t < 21:
                let n = (usize)plate_taps_left[t]
                let offset = (usize)(plate_taps_left[t + 1] * scale) + 1
                yl += plate_taps_left[t + 2] * tap(line, bases[n], lengths[n], s.heads[n], offset if offset < lengths[n] else lengths[n] - 1)
                let m = (usize)plate_taps_right[t]
                let offset_r = (usize)(plate_taps_right[t + 1] * scale) + 1
                yr += plate_taps_right[t + 2] * tap(line, bases[m], lengths[m], s.heads[m], offset_r if offset_r < lengths[m] else lengths[m] - 1)
                t += 3
            last_l = held_l
            last_r = held_r
            held_l = yl * 0.6
            held_r = yr * 0.6
            out_l = held_l
            out_r = held_r
        if vintage and parity == 1:
            # Between tank steps: halfway from the last output.
            out_l = (last_l + held_l) * 0.5
            out_r = (last_r + held_r) * 0.5
        left[i] = dry_l + (out_l - dry_l) * wet
        right[i] = dry_r + (out_r - dry_r) * wet
    s.a = (f64)lfo
    s.b = (f64)bw
    s.c = (f64)damp_l
    s.d = (f64)damp_r
    s.more[0] = (f64)end_l
    s.more[1] = (f64)end_r
    s.more[2] = (f64)hp
    s.more[3] = (f64)held_l
    s.more[4] = (f64)held_r
    s.more[5] = (f64)last_l
    s.more[6] = (f64)last_r
    s.more[7] = (f64)gathered
    s.heads[15] = parity

## An allpass whose delay `delay` (≤ length) swings.
inline func mod_allpass(line: f32[], base: usize, length: usize, head: u32*, x: f32, g: f32, delay: f32) -> f32:
    let d = tap_frac(line, base, length, *head, clampf(delay, 1.0, (f32)(length - 1)))
    let v = x - g * d
    put(line, base, length, head, v)
    return d + g * v

# ---------------------------------------------------------------- echo

let most_echo: f32 = 2.2

## Tape, BBD and digital echo. Tape (the RE-201): the time glides to where
## it is set (rising over 1.9 s, falling over 1.1 s — the twiddle), wow and
## flutter wobble it, each repeat runs through a saturating head and a band
## pass that darkens with Age. BBD: the line's bandwidth falls as the time
## grows (a 4096-stage chip's clock), its compander grits. Digital: clean.
## Ping-Pong crosses the repeats.
## Inputs: left, right, time (s, added).
## Params: Mode, Time (s), Feedback, Mix, Tone (Hz), Low Cut (Hz), Wow,
## Flutter, Drive (dB), Ping-Pong.
pub func echo(s: State*, p: Ports*):
    let left_in = p.inputs[0]
    let right_in = p.inputs[1] if p.wired[1] else p.inputs[0]
    let times = p.inputs[2]
    let left = p.outputs[0]
    let right = p.outputs[1]
    let mode = (i32)p.params[0]
    let feedback = clampf(p.params[2], 0.0, 1.1)
    let wet = clampf(p.params[3], 0.0, 1.0)
    let tone_hz = clampf(p.params[4], 300.0, 18000.0)
    let low_cut = analog.one_pole(clampf(p.params[5], 10.0, 2000.0), p.rate)
    let wow = clampf(p.params[6], 0.0, 1.0)
    let flutter = clampf(p.params[7], 0.0, 1.0)
    let drive = decibels(p.params[8])
    let crossed = p.params[9] > 0.5
    let length = (usize)(most_echo * p.rate) + 4
    let line = s.line
    if line.length < 2 * length:
        for i in 0..<p.frames:
            left[i] = left_in[i]
            right[i] = right_in[i]
        return
    var time = (f32)s.a
    var wander = (f32)s.b
    var flutter_phase = (f32)s.c
    var seed = s.seed
    var lp_l = s.damp[0]
    var lp_r = s.damp[1]
    var hp_l = s.damp[2]
    var hp_r = s.damp[3]
    let up = 1.0 / (1.89 * p.rate)
    let down = 1.0 / (1.07 * p.rate)
    for i in 0..<p.frames:
        var target = p.params[1]
        if p.wired[2]: target = target + times[i]
        target = clampf(target, 0.001, most_echo - 0.05)
        if time <= 0.0: time = target
        if mode == 0:
            time += (target - time) * (up if target > time else down)
        else:
            time += (target - time) * 0.0005
        # Wow: noise below 1 Hz; flutter: a ~9 Hz wobble. Tape only.
        var wobble: f32 = 0.0
        if mode == 0:
            wander = wander + (dsp.white(&seed) - wander) * (6.2831855 * 1.0 / p.rate)
            flutter_phase += 9.0 / p.rate
            if flutter_phase >= 1.0: flutter_phase -= 1.0
            wobble = wander * wow * 0.06 + dsp.sin_turns(flutter_phase) * flutter * 0.0004
        let delay = clampf((time + wobble * time) * p.rate, 1.0, (f32)(length - 2))
        var yl = tap_frac(line, 0, length, s.heads[0], delay)
        var yr = tap_frac(line, length, length, s.heads[1], delay)
        # The repeat's color.
        var cutoff = tone_hz
        if mode == 1:
            # A 4096-stage BBD at this time clocks at 2048/time; half that passes.
            let clock_limit = 1024.0 / time
            cutoff = cutoff if cutoff < clock_limit else clock_limit
        let lp = analog.one_pole(cutoff, p.rate)
        lp_l = lp_l + (yl - lp_l) * lp
        lp_r = lp_r + (yr - lp_r) * lp
        hp_l = hp_l + (lp_l - hp_l) * low_cut
        hp_r = hp_r + (lp_r - hp_r) * low_cut
        yl = lp_l - hp_l
        yr = lp_r - hp_r
        if mode != 2:
            yl = analog.tanh(yl * drive) / drive
            yr = analog.tanh(yr * drive) / drive
        if crossed:
            # Ping-pong: the input enters on the left; each side feeds the other.
            put(line, 0, length, &s.heads[0], (left_in[i] + right_in[i]) * 0.5 + feedback * yr)
            put(line, length, length, &s.heads[1], feedback * yl)
        else:
            put(line, 0, length, &s.heads[0], left_in[i] + feedback * yl)
            put(line, length, length, &s.heads[1], right_in[i] + feedback * yr)
        left[i] = left_in[i] + (yl - left_in[i]) * wet
        right[i] = right_in[i] + (yr - right_in[i]) * wet
    s.a = (f64)time
    s.b = (f64)wander
    s.c = (f64)flutter_phase
    s.seed = seed
    s.damp[0] = lp_l
    s.damp[1] = lp_r
    s.damp[2] = hp_l
    s.damp[3] = hp_r

# ---------------------------------------------------------------- chorus

let most_chorus: f32 = 0.03

## BBD choruses: Juno I (0.513 Hz, ±0.5 ms), II (0.863 Hz, ±1.1 ms) and I+II
## around 3.5 ms, the two sides swept in opposite phase (the KR-106's
## measurements); Dimension (shallow, its wet sides crossed in antiphase);
## Ensemble (three taps 120° apart, each with a slow and a fast wobble).
## Inputs: left, right. Params: Mode, Rate (scale), Depth (scale), Mix, Tone (Hz).
pub func chorus(s: State*, p: Ports*):
    let left_in = p.inputs[0]
    let right_in = p.inputs[1] if p.wired[1] else p.inputs[0]
    let left = p.outputs[0]
    let right = p.outputs[1]
    let mode = (i32)p.params[0]
    let rate_scale = clampf(p.params[1], 0.1, 10.0)
    let depth_scale = clampf(p.params[2], 0.0, 3.0)
    let wet = clampf(p.params[3], 0.0, 1.0)
    let tone = analog.one_pole(clampf(p.params[4], 1000.0, 20000.0), p.rate)
    let length = (usize)(most_chorus * p.rate) + 4
    let line = s.line
    if line.length < length:
        for i in 0..<p.frames:
            left[i] = left_in[i]
            right[i] = right_in[i]
        return
    var slow = (f32)s.a
    var fast = (f32)s.b
    var lp = (f32)s.c
    let ms = p.rate * 0.001
    for i in 0..<p.frames:
        let mono = (left_in[i] + right_in[i]) * 0.5
        lp = lp + (mono - lp) * tone
        put(line, 0, length, &s.heads[0], analog.tanh(lp))
        var wl: f32 = 0.0
        var wr: f32 = 0.0
        if mode <= 2:
            var rate: f32 = 0.513
            var depth: f32 = 0.5
            if mode == 1:
                rate = 0.863
                depth = 1.1
            elif mode == 2:
                rate = 9.75
                depth = 0.25
            slow += rate * rate_scale / p.rate
            if slow >= 1.0: slow -= 1.0
            let tri = 4.0 * absf(slow - 0.5) - 1.0
            wl = tap_frac(line, 0, length, s.heads[0], (3.5 + tri * depth * depth_scale) * ms)
            wr = tap_frac(line, 0, length, s.heads[0], (3.5 - tri * depth * depth_scale) * ms)
        elif mode == 3:
            slow += 0.25 * rate_scale / p.rate
            if slow >= 1.0: slow -= 1.0
            let sweep = dsp.sin_turns(slow) * 0.4 * depth_scale
            let a = tap_frac(line, 0, length, s.heads[0], (2.6 + sweep) * ms)
            let b = tap_frac(line, 0, length, s.heads[0], (2.6 - sweep) * ms)
            wl = a - 0.3 * b
            wr = b - 0.3 * a
        else:
            slow += 0.6 * rate_scale / p.rate
            if slow >= 1.0: slow -= 1.0
            fast += 6.0 * rate_scale / p.rate
            if fast >= 1.0: fast -= 1.0
            var taps: f32[3]
            for k in 0..<3:
                let turn = (f32)k / 3.0
                let wobble = dsp.sin_turns(slow + turn) * 1.5 + dsp.sin_turns(fast + turn) * 0.15
                taps[k] = tap_frac(line, 0, length, s.heads[0], (5.0 + wobble * depth_scale) * ms)
            wl = taps[0] + 0.7 * taps[1]
            wr = taps[2] + 0.7 * taps[1]
            wl *= 0.6
            wr *= 0.6
        left[i] = left_in[i] * (1.0 - wet * 0.5) + wl * wet
        right[i] = right_in[i] * (1.0 - wet * 0.5) + wr * wet
    s.a = (f64)slow
    s.b = (f64)fast
    s.c = (f64)lp

# ---------------------------------------------------------------- dynamics

## A feed-forward compressor (Giannoulis, Massberg & Reiss): a soft-knee
## gain computer in dB, attack and release smoothing of the gain, a stereo
## link and makeup. Squash is OTO BOUM's one knob: 0 is 1:1, the middle ∞:1,
## past it the ratio turns negative (louder input, quieter output). When
## Squash is used it sets threshold and ratio; Grit drives a saturator harder
## as the gain falls.
## Inputs: left, right, key (sidechain, optional).
## Params: Threshold (dB), Ratio, Attack (ms), Release (ms), Knee (dB),
## Makeup (dB), Squash, Grit, Mix.
pub func compressor(s: State*, p: Ports*):
    let left_in = p.inputs[0]
    let right_in = p.inputs[1] if p.wired[1] else p.inputs[0]
    let key = p.inputs[2]
    let left = p.outputs[0]
    let right = p.outputs[1]
    var threshold = p.params[0]
    var slope = 1.0 / clampf(p.params[1], 1.0, 100.0)
    let squash = clampf(p.params[6], 0.0, 1.0)
    if squash > 0.0:
        threshold = -30.0 * squash
        slope = 1.0 - 2.0 * squash
    let attack = exp2(-3.1699 / (clampf(p.params[2], 0.05, 500.0) * 0.001 * p.rate))
    let release = exp2(-3.1699 / (clampf(p.params[3], 5.0, 5000.0) * 0.001 * p.rate))
    let knee = clampf(p.params[4], 0.0, 24.0)
    var makeup = p.params[5]
    if squash > 0.0: makeup = makeup + 30.0 * squash * (1.0 - slope) * 0.5
    let grit = clampf(p.params[7], 0.0, 1.0)
    let wet = clampf(p.params[8], 0.0, 1.0)
    var reduction = (f32)s.a
    for i in 0..<p.frames:
        let l = left_in[i]
        let r = right_in[i]
        var level = absf(l) if absf(l) > absf(r) else absf(r)
        if p.wired[2]: level = absf(key[i])
        let db = 20.0 * log10_cheap(level + 1.0e-9)
        # The gain computer, soft knee.
        var target = db
        let over = db - threshold
        if knee > 0.0 and 2.0 * absf(over) <= knee:
            let into = over + knee * 0.5
            target = db + (slope - 1.0) * into * into / (2.0 * knee)
        elif over > 0.0:
            target = threshold + over * slope
        let wanted = target - db
        let coef = attack if wanted < reduction else release
        reduction = wanted + (reduction - wanted) * coef
        let gain = decibels(reduction + makeup)
        var yl = l * gain
        var yr = r * gain
        if grit > 0.0:
            let push = 1.0 + grit * clampf(-reduction, 0.0, 30.0) * 0.06
            yl = analog.tanh(yl * push) / push
            yr = analog.tanh(yr * push) / push
        left[i] = l + (yl - l) * wet
        right[i] = r + (yr - r) * wet
    s.a = (f64)reduction

## log10 within 1e-3 dB for our purposes: exponent bits and a quartic.
inline func log10_cheap(x: f32) -> f32:
    let bits = x.bits()
    let exponent = (f32)(i32)((bits >> 23) & 255) - 127.0
    let m = f32.bits((bits & 0x7fffff) | 0x3f800000)
    let log2 = exponent + (-2.4967738 + (4.0283728 + (-2.0810602 + (0.62881573 - 0.079150366 * m) * m) * m) * m)
    return log2 * 0.30103

# ---------------------------------------------------------------- tremolo

## The Rhodes Suitcase's vibrato (really a stereo autopan; mono, a
## tremolo): a sine turned toward a square by Shape, through the light
## dependent resistor's lag (fast on, slower off), moving the two sides
## against each other.
## Inputs: left, right. Params: Rate (Hz), Depth, Shape, Stereo.
pub func tremolo(s: State*, p: Ports*):
    let left_in = p.inputs[0]
    let right_in = p.inputs[1] if p.wired[1] else p.inputs[0]
    let left = p.outputs[0]
    let right = p.outputs[1]
    let rate = clampf(p.params[0], 0.05, 20.0)
    let depth = clampf(p.params[1], 0.0, 1.0)
    let shape = clampf(p.params[2], 0.0, 1.0)
    let stereo = p.params[3] > 0.5
    let rise = analog.one_pole(1.0 / (6.2831855 * 0.005), p.rate)
    let fall = analog.one_pole(1.0 / (6.2831855 * 0.02), p.rate)
    var phase = (f32)s.a
    var light = (f32)s.b
    for i in 0..<p.frames:
        phase += rate / p.rate
        if phase >= 1.0: phase -= 1.0
        let sine = dsp.sin_turns(phase)
        let wave = analog.tanh(sine * (1.0 + shape * 8.0)) / analog.tanh(1.0 + shape * 8.0)
        light = light + (wave - light) * (rise if wave > light else fall)
        let gl = 1.0 - depth * (0.5 + 0.5 * light)
        let gr = 1.0 - depth * (0.5 - 0.5 * light) if stereo else gl
        left[i] = left_in[i] * gl
        right[i] = right_in[i] * gr
    s.a = (f64)phase
    s.b = (f64)light

# ---------------------------------------------------------------- memory

## The line memory (samples) a voice of `kind` needs at `rate`.
pub func memory_of(kind: u32, rate: f64) -> usize:
    if kind == kinds.plate:
        var lengths: usize[13]
        var bases: usize[13]
        return plate_layout((f32)rate, most_size, lengths, bases) + 16
    # The same f32 arithmetic the kernels use, so the sizes agree exactly.
    if kind == kinds.echo:
        return 2 * ((usize)(most_echo * (f32)rate) + 4)
    if kind == kinds.chorus:
        return (usize)(most_chorus * (f32)rate) + 4
    if kind == kinds.phaser:
        return 48
    if kind == kinds.flanger:
        return 2 * ((usize)(most_flange * (f32)rate) + 4)
    return 0

# ---------------------------------------------------------------- lo-fi

## OTO BISCUIT / BIM style degradation: a diode-clipped input, a sample
## clock that drops the rate (aliasing on purpose) with a little jitter, the
## sample's bits cut down, then a resonant low pass to tame or ring it.
## Inputs: in, rate (octaves, added). Params: Bits, Rate (Hz), Jitter,
## Drive (dB), Cutoff (Hz), Resonance, Mix.
pub func lofi(s: State*, p: Ports*):
    let source = p.inputs[0]
    let moves = p.inputs[1]
    let out = p.outputs[0]
    let bits = clampf(p.params[0], 1.0, 16.0)
    let steps = exp2(bits - 1.0)
    let jitter = clampf(p.params[2], 0.0, 1.0)
    let drive = decibels(p.params[3])
    let g = dsp.tan_turns(clampf(p.params[4], 50.0, p.rate * 0.45) / p.rate * 0.5)
    let k = 2.0 - 2.0 * clampf(p.params[5], 0.0, 0.97)
    let wet = clampf(p.params[6], 0.0, 1.0)
    var clock = (f32)s.a
    var held = (f32)s.b
    var ic1 = (f32)s.c
    var ic2 = (f32)s.d
    var seed = s.seed
    for i in 0..<p.frames:
        var rate = p.params[1]
        if p.wired[1]: rate = rate * exp2(moves[i])
        let x = source[i]
        clock += clampf(rate, 50.0, p.rate) / p.rate * (1.0 + jitter * 0.3 * dsp.white(&seed))
        if clock >= 1.0:
            clock -= dsp.floorf(clock)
            let clipped = analog.diode_clip(x * drive, 0.1) / analog.tanh(clampf(drive, 1.0, 4.0))
            held = dsp.floorf(clipped * steps + 0.5) / steps
        let a1 = 1.0 / (1.0 + g * (g + k))
        let a2 = g * a1
        let a3 = g * a2
        let v3 = held - ic2
        let v1 = a1 * ic1 + a2 * v3
        let v2 = ic2 + a2 * ic1 + a3 * v3
        ic1 = 2.0 * v1 - ic1
        ic2 = 2.0 * v2 - ic2
        out[i] = x + (v2 - x) * wet
    s.a = (f64)clock
    s.b = (f64)held
    s.c = (f64)ic1
    s.d = (f64)ic2
    s.seed = seed

# ---------------------------------------------------------------- phaser and flanger

## A phaser: a chain of first-order allpasses swept exponentially between
## Low and High by a sine LFO, fed back on itself, the right side's sweep
## offset by Spread; Barberpole sweeps one way forever (two sawtooth
## sweeps crossfaded, as Polymoon's).
## Inputs: left, right. Params: Stages (4|6|8|12), Rate (Hz), Low (Hz),
## High (Hz), Feedback, Spread, Mix, Barberpole.
pub func phaser(s: State*, p: Ports*):
    let left_in = p.inputs[0]
    let right_in = p.inputs[1] if p.wired[1] else p.inputs[0]
    let left = p.outputs[0]
    let right = p.outputs[1]
    let choice = (i32)p.params[0]
    let stages: usize = 4 if choice == 0 else (6 if choice == 1 else (8 if choice == 2 else 12))
    let rate = clampf(p.params[1], 0.01, 10.0)
    let low = clampf(p.params[2], 20.0, 5000.0)
    let high = clampf(p.params[3], low * 1.5, 16000.0)
    let octaves = log2_approx(high / low)
    let feedback = clampf(p.params[4], -0.95, 0.95)
    let spread = clampf(p.params[5], 0.0, 0.5)
    let wet = clampf(p.params[6], 0.0, 1.0)
    let barber = p.params[7] > 0.5
    let memory = s.line
    if memory.length < 48:
        for i in 0..<p.frames:
            left[i] = left_in[i]
            right[i] = right_in[i]
        return
    var phase = (f32)s.a
    var fb_l = (f32)s.b
    var fb_r = (f32)s.c
    for i in 0..<p.frames:
        phase += rate / p.rate
        if phase >= 1.0: phase -= 1.0
        var yl: f32 = 0.0
        var yr: f32 = 0.0
        for side: usize in 0..<2:
            let offset = 0.0 if side == 0 else spread
            var sweep: f32 = 0.0
            if barber:
                var t = phase + offset
                t = t - dsp.floorf(t)
                sweep = t
            else:
                sweep = 0.5 + 0.5 * dsp.sin_turns(phase + offset)
            let fc = low * exp2(octaves * sweep)
            let g = dsp.tan_turns(clampf(fc, 20.0, p.rate * 0.45) / p.rate * 0.5)
            let a = (g - 1.0) / (g + 1.0)
            var x = (left_in[i] if side == 0 else right_in[i]) + (fb_l if side == 0 else fb_r) * feedback
            for k in 0..<stages:
                let index = side * 12 + k
                # y = a x + x1 - a y1, the first-order allpass.
                let y = a * x + memory[index] - a * memory[24 + index]
                memory[index] = x
                memory[24 + index] = y
                x = y
            if side == 0:
                fb_l = x
                yl = x
            else:
                fb_r = x
                yr = x
        # Dry and phased in equal parts at full mix: the notches.
        left[i] = left_in[i] * (1.0 - 0.5 * wet) + yl * 0.5 * wet
        right[i] = right_in[i] * (1.0 - 0.5 * wet) + yr * 0.5 * wet
    s.a = (f64)phase
    s.b = (f64)fb_l
    s.c = (f64)fb_r

## log2 for the phaser's span.
inline func log2_approx(x: f32) -> f32:
    let bits = x.bits()
    let exponent = (f32)(i32)((bits >> 23) & 255) - 127.0
    let m = f32.bits((bits & 0x7fffff) | 0x3f800000)
    return exponent + (-2.4967738 + (4.0283728 + (-2.0810602 + (0.62881573 - 0.079150366 * m) * m) * m) * m)

let most_flange: f32 = 0.025

## A flanger: a short delay (Delay ± Depth) swept by a triangle, fed back
## positive or negative; Through-Zero also delays the dry path so the sweep
## crosses it (the tape-flange null). The right side's sweep is offset.
## Inputs: left, right. Params: Delay (ms), Depth (ms), Rate (Hz),
## Feedback, Mix, Through-Zero, Spread.
pub func flanger(s: State*, p: Ports*):
    let left_in = p.inputs[0]
    let right_in = p.inputs[1] if p.wired[1] else p.inputs[0]
    let left = p.outputs[0]
    let right = p.outputs[1]
    let center = clampf(p.params[0], 0.1, 10.0)
    let depth = clampf(p.params[1], 0.0, center)
    let rate = clampf(p.params[2], 0.01, 10.0)
    let feedback = clampf(p.params[3], -0.95, 0.95)
    let wet = clampf(p.params[4], 0.0, 1.0)
    let through_zero = p.params[5] > 0.5
    let spread = clampf(p.params[6], 0.0, 0.5)
    let length = (usize)(most_flange * p.rate) + 4
    let line = s.line
    if line.length < 2 * length:
        for i in 0..<p.frames:
            left[i] = left_in[i]
            right[i] = right_in[i]
        return
    let ms = p.rate * 0.001
    var phase = (f32)s.a
    var fb_l = (f32)s.b
    var fb_r = (f32)s.c
    for i in 0..<p.frames:
        phase += rate / p.rate
        if phase >= 1.0: phase -= 1.0
        let tri_l = 4.0 * absf(phase - 0.5) - 1.0
        var shifted = phase + spread
        shifted = shifted - dsp.floorf(shifted)
        let tri_r = 4.0 * absf(shifted - 0.5) - 1.0
        put(line, 0, length, &s.heads[0], left_in[i] + fb_l * feedback)
        put(line, length, length, &s.heads[1], right_in[i] + fb_r * feedback)
        let wl = tap_frac(line, 0, length, s.heads[0], (center + tri_l * depth) * ms + 1.0)
        let wr = tap_frac(line, length, length, s.heads[1], (center + tri_r * depth) * ms + 1.0)
        fb_l = wl
        fb_r = wr
        var dry_l = left_in[i]
        var dry_r = right_in[i]
        if through_zero:
            dry_l = tap_frac(line, 0, length, s.heads[0], center * ms + 1.0)
            dry_r = tap_frac(line, length, length, s.heads[1], center * ms + 1.0)
        # Through-zero subtracts: where the sweep crosses the dry path, a null.
        let sign: f32 = -1.0 if through_zero else 1.0
        left[i] = dry_l * (1.0 - 0.5 * wet) + wl * 0.5 * wet * sign
        right[i] = dry_r * (1.0 - 0.5 * wet) + wr * 0.5 * wet * sign
    s.a = (f64)phase
    s.b = (f64)fb_l
    s.c = (f64)fb_r