Files
josh 8983e8829e feat(pedals): oversample nonlinear drive stages; Sustainer safety limiter
Anti-aliasing (Tier 1): every hard nonlinearity ran at the engine rate, so the
harmonics it generated folded back as inharmonic aliasing — worst on loud/bright
input at high drive. Add two oversampled RT generators built on Lyrebird's
halfband up/down-samplers and move the drive pedals onto them:

- OversampledSaturator (+ SaturationCurve) — tanh / normalised soft-clip /
  tanh+hard-clip curves at 2× or 4×. DistortionPedal now does its tanh→gain→hard
  clip at 4× (clip before the tone low-pass), with a final hard clip after the
  low-pass to re-establish the strict output bound; FuzzPedal (tanh) and
  OverdrivePedal (soft-clip) at 2×.
- OversampledRingModulator — input × sine carrier at 2×, carrier synthesized at
  the oversampled rate so the sum sideband can't alias. Phase wraps both
  directions (safe for negative carrier frequencies) and a sampleRate guard
  prevents NaN latching. RingModulatorPedal uses it.

Dynamics (Tier 2): SustainerPedal gains an opt-in Safety switch (off by default)
that inserts a brick-wall LookAheadLimiter after its compressor to catch the
transient overshoot a low-threshold/high-makeup setting can push past full scale.

Tests: generator-level alias-reduction proofs (Goertzel alias/fundamental ratio
vs a naive base-rate baseline) for both oversampled generators, hard-clip/soft
bounds, negative-carrier stability, distortion output-bound at high drive, and
Sustainer safety switch exposure + peak-capping. Full suite 478 pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-31 20:41:06 -07:00

144 lines
6.4 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// OversampledRingModulator.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import Darwin
/// Shared zero-fill fallback block, allocated once at module load. Returned when an upstream
/// input yields no channel for a `_computeSamples` call, so the RT path never allocates.
private let oversampledRingModZeroBlock: [Double] = makeSampleBuffer()
/// Ring modulator (`input × sine carrier`) evaluated at 2× or 4× the engine sample rate.
///
/// A ring modulator's product produces sum-and-difference sidebands at `f_in ± f_carrier`. The
/// sum sideband can land above the engine Nyquist and fold back as an inharmonic alias —
/// worst with a high carrier and bright input. Evaluating the multiply at an oversampled rate
/// (the input upsampled through a halfband FIR, the carrier generated directly at the
/// oversampled rate) pushes the sum term below the upsampled Nyquist, then the matching
/// downsampler filters it out before returning to the engine rate.
///
/// Output is mono (channel 0 of the input is used).
///
/// - Parameters:
/// - input: Signal to modulate.
/// - freq: Carrier frequency in Hz. Read once per block. Defaults to `220.0`.
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`.
public final class OversampledRingModulator: GeneratorBase, AudioGenerator {
/// Resolved input signal (classified once at `init`, never on the RT thread).
private let inputSource: any ValidGeneratorInput
/// Resolved carrier-frequency control. Read once per block.
private let freqInput: any ValidGeneratorInput
/// Oversampling factor — `2` or `4`, fixed at init.
private let oversampleFactor: Int
/// Carrier phase in radians, advanced at the oversampled rate and wrapped to `[0, 2π)`.
private var phase: Double = 0.0
/// 2× halfband oversampling state (used when `oversampleFactor == 2`).
private var upsampler2x: HalfbandUpsampler2x
private var downsampler2x: HalfbandDownsampler2x
/// 4× halfband oversampling state (used when `oversampleFactor == 4`).
private var upsampler4x: HalfbandUpsampler4x
private var downsampler4x: HalfbandDownsampler4x
private let twoPi: Double = 2.0 * Double.pi
/// Creates an oversampled ring modulator.
///
/// - Parameters:
/// - input: Signal to modulate.
/// - freq: Carrier frequency in Hz. Read once per block. Defaults to `220.0`.
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`.
public init(
_ input: any ValidGeneratorInput,
freq: any ValidGeneratorInput = 220.0,
oversample: Int = 2
) {
precondition(
oversample == 2 || oversample == 4,
"OversampledRingModulator: oversample must be 2 or 4"
)
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
inputSource = resolvedInput
freqInput = resolvedFreq
oversampleFactor = oversample
upsampler2x = HalfbandUpsampler2x()
downsampler2x = HalfbandDownsampler2x()
upsampler4x = HalfbandUpsampler4x()
downsampler4x = HalfbandDownsampler4x()
super.init()
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
let input: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first
?? oversampledRingModZeroBlock
let sr: Double = graph.engine.sampleRate
// A degenerate sample rate would make phaseInc NaN/Inf and latch NaN into the
// persisted phase; zero-fill and bail, matching MoogLadder's guard.
guard sr >= 1.0 else {
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
for i: Int in 0..<count { dstP[i] = 0 }
}
return _result
}
let freq: Double = freqInput.floatValue(graph: graph)
let inCount: Int = input.count
let useFourX: Bool = oversampleFactor == 4
// Phase increment per oversampled sample.
let factor: Double = useFourX ? 4.0 : 2.0
let phaseInc: Double = twoPi * freq / (sr * factor)
var localPhase: Double = phase
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
if useFourX {
for i: Int in 0..<count {
let x: Double = i < inCount ? input[i] : 0
let (a, b, c, d) = upsampler4x.process(x)
let ya: Double = a * sin(localPhase); localPhase += phaseInc
let yb: Double = b * sin(localPhase); localPhase += phaseInc
let yc: Double = c * sin(localPhase); localPhase += phaseInc
let yd: Double = d * sin(localPhase); localPhase += phaseInc
// Wrap both directions — a negative carrier frequency drives phaseInc
// negative, so an upward-only wrap would let the phase grow unbounded.
if localPhase >= twoPi || localPhase < 0 {
localPhase = localPhase.truncatingRemainder(dividingBy: twoPi)
if localPhase < 0 { localPhase += twoPi }
}
dstP[i] = downsampler4x.process(ya, yb, yc, yd)
}
} else {
for i: Int in 0..<count {
let x: Double = i < inCount ? input[i] : 0
let (a, b) = upsampler2x.process(x)
let ya: Double = a * sin(localPhase); localPhase += phaseInc
let yb: Double = b * sin(localPhase); localPhase += phaseInc
// Wrap both directions (see 4× branch).
if localPhase >= twoPi || localPhase < 0 {
localPhase = localPhase.truncatingRemainder(dividingBy: twoPi)
if localPhase < 0 { localPhase += twoPi }
}
dstP[i] = downsampler2x.process(ya, yb)
}
}
}
phase = localPhase
return _result
}
}