Files
Lyrebird/Sources/Lyrebird/Generators/Gendy/Gendy1.swift
T
josh f8878324fd v2.1.1 release: delay-click fix + internal consolidation
Mirror of Lyrebird dev HEAD (9f791c7c) minus maintainer-only paths. Patch release:
fixes the allpass fractional-delay click (DelayLine/CombFilter/AllpassFilter/
DelayLineFeedback under a modulated delay) and lands the internal code-quality
consolidation pass (~160 deduped sites + shared base classes/helpers, bit-identical
output). No public API removed or changed. See RELEASES.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-07 21:20:49 -07:00

385 lines
19 KiB
Swift

// Gendy1.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Stochastic waveform generator using `N` breakpoints, both amplitude and duration
/// updated stochastically each cycle using the shared ``DistributionKind`` family.
///
/// `Gendy1` constructs a waveform by walking through a ring of `initCPs` control-point
/// breakpoints. Each time the generator reaches a breakpoint, the amplitude and
/// duration of that breakpoint are randomly perturbed using the selected distributions.
/// Output is linearly interpolated between the current and next breakpoint.
///
/// Modelled after SuperCollider's `Gendy1` UGen (Stochastic Synthesis by Iannis Xenakis).
///
/// - Parameters:
/// - ampdist: Distribution used to perturb breakpoint amplitudes. Defaults to `.gauss`.
/// - durdist: Distribution used to perturb breakpoint durations. Defaults to `.gauss`.
/// - adparam: Shape parameter for `ampdist`. Meaning depends on distribution. Defaults to `1.0`.
/// - ddparam: Shape parameter for `durdist`. Meaning depends on distribution. Defaults to `1.0`.
/// - minfreq: Minimum frequency in Hz; sets the maximum segment duration. Defaults to `440.0`.
/// - maxfreq: Maximum frequency in Hz; sets the minimum segment duration. Defaults to `660.0`.
/// - ampscale: Scale of amplitude perturbation steps. `0.0` = no drift; `1.0` = full range per step. Defaults to `0.5`.
/// - durscale: Scale of duration perturbation steps. `0.0` = no drift; `1.0` = full range per step. Defaults to `0.5`.
/// - initCPs: Number of breakpoints. Must be ≥ 2. Static; cannot change after init. Defaults to `12`.
/// - knum: Number of active breakpoints. Clamped to \[1, `initCPs`\] at each block. Defaults to `12.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
/// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed.
public enum Gendy1 {
// MARK: - _Base — shared state for Audio + Control
/// Shared stored properties and init for `Gendy1.Audio` and `Gendy1.Control`.
/// State is fully shared; only the compute path differs between rates.
public class _Base: GeneratorBase {
// Inputs
let adparamInput: any ValidGeneratorInput
let ddparamInput: any ValidGeneratorInput
let minfreqInput: any ValidGeneratorInput
let maxfreqInput: any ValidGeneratorInput
let ampscaleInput: any ValidGeneratorInput
let durscaleInput: any ValidGeneratorInput
let knumInput: any ValidGeneratorInput
// Distribution config (static)
let ampdist: DistributionKind
let durdist: DistributionKind
let initCPs: Int
// DSP state
var _amps: [Double]
var _durs: [Double]
var _cpIndex: Int = 0
var _segPos: Double = 0.0
var _curAmp: Double
var _nextAmp: Double
var _segLen: Double
var _rng: UInt64
// Output
var _mulAdd: MulAddSpec
/// `seedMixConstant` distinguishes Audio and Control PRNG streams so two
/// instances seeded from the same time-derived nanosecond don't produce
/// identical sequences.
init(
ampdist: DistributionKind,
durdist: DistributionKind,
adparam: any ValidGeneratorInput,
ddparam: any ValidGeneratorInput,
minfreq: any ValidGeneratorInput,
maxfreq: any ValidGeneratorInput,
ampscale: any ValidGeneratorInput,
durscale: any ValidGeneratorInput,
initCPs: Int,
knum: any ValidGeneratorInput,
mul: any ValidGeneratorInput,
add: any ValidGeneratorInput,
seed: UInt64?,
seedMixConstant: UInt64
) {
precondition(initCPs >= 2, "Gendy1: initCPs must be >= 2, got \(initCPs)")
let resolvedAdparam: any ValidGeneratorInput = adparam._resolvedInput()
let resolvedDdparam: any ValidGeneratorInput = ddparam._resolvedInput()
let resolvedMinfreq: any ValidGeneratorInput = minfreq._resolvedInput()
let resolvedMaxfreq: any ValidGeneratorInput = maxfreq._resolvedInput()
let resolvedAmpscale: any ValidGeneratorInput = ampscale._resolvedInput()
let resolvedDurscale: any ValidGeneratorInput = durscale._resolvedInput()
let resolvedKnum: any ValidGeneratorInput = knum._resolvedInput()
self.ampdist = ampdist
self.durdist = durdist
self.adparamInput = resolvedAdparam
self.ddparamInput = resolvedDdparam
self.minfreqInput = resolvedMinfreq
self.maxfreqInput = resolvedMaxfreq
self.ampscaleInput = resolvedAmpscale
self.durscaleInput = resolvedDurscale
self.initCPs = initCPs
self.knumInput = resolvedKnum
self._mulAdd = MulAddSpec(mul: mul, add: add)
var rng: UInt64 = lyrebirdSeedXorshift64(from: seed, mixConstant: seedMixConstant)
var amps: [Double] = [Double](repeating: 0, count: initCPs)
var durs: [Double] = [Double](repeating: 0, count: initCPs)
// Use a nominal default duration in samples (mid-range between minfreq/maxfreq
// based on 44100 Hz; will be recomputed from actual sampleRate on first block).
let nominalDefaultDurSamples: Double = 100.0
for idx: Int in 0..<initCPs {
amps[idx] = xorshift64Next(&rng)
durs[idx] = nominalDefaultDurSamples + xorshift64Next(&rng) * (nominalDefaultDurSamples * 0.5)
}
self._amps = amps
self._durs = durs
self._curAmp = amps[0]
self._nextAmp = amps[1]
self._segLen = max(durs[0], 1.0)
self._rng = rng
super.init()
}
}
// MARK: - Audio
/// Audio-rate Gendy1 stochastic waveform generator.
///
/// Linearly interpolates between `knum` active breakpoints. Both amplitude and
/// duration are updated stochastically on each breakpoint crossing.
///
/// - Parameters:
/// - ampdist: Distribution used to perturb breakpoint amplitudes. Defaults to `.gauss`.
/// - durdist: Distribution used to perturb breakpoint durations. Defaults to `.gauss`.
/// - adparam: Shape parameter for `ampdist`. Meaning depends on distribution. Defaults to `1.0`.
/// - ddparam: Shape parameter for `durdist`. Meaning depends on distribution. Defaults to `1.0`.
/// - minfreq: Minimum frequency in Hz; sets the maximum segment duration. Defaults to `440.0`.
/// - maxfreq: Maximum frequency in Hz; sets the minimum segment duration. Defaults to `660.0`.
/// - ampscale: Scale of amplitude perturbation steps in \[0, 1\]. Defaults to `0.5`.
/// - durscale: Scale of duration perturbation steps in \[0, 1\]. Defaults to `0.5`.
/// - initCPs: Number of breakpoints ≥ 2. Static after init. Defaults to `12`.
/// - knum: Active breakpoint count. Clamped to \[1, `initCPs`\] each block. Defaults to `12.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
/// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed.
public final class Audio: _Base, AudioGenerator {
/// - Parameters:
/// - ampdist: Distribution used to perturb breakpoint amplitudes. Defaults to `.gauss`.
/// - durdist: Distribution used to perturb breakpoint durations. Defaults to `.gauss`.
/// - adparam: Shape parameter for `ampdist`. Meaning depends on distribution. Defaults to `1.0`.
/// - ddparam: Shape parameter for `durdist`. Meaning depends on distribution. Defaults to `1.0`.
/// - minfreq: Minimum frequency in Hz; sets the maximum segment duration. Defaults to `440.0`.
/// - maxfreq: Maximum frequency in Hz; sets the minimum segment duration. Defaults to `660.0`.
/// - ampscale: Scale of amplitude perturbation steps in \[0, 1\]. Defaults to `0.5`.
/// - durscale: Scale of duration perturbation steps in \[0, 1\]. Defaults to `0.5`.
/// - initCPs: Number of breakpoints ≥ 2. Static after init. Defaults to `12`.
/// - knum: Active breakpoint count. Clamped to \[1, `initCPs`\] each block. Defaults to `12.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
/// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed.
public init(
ampdist: DistributionKind = .gauss,
durdist: DistributionKind = .gauss,
adparam: any ValidGeneratorInput = 1.0,
ddparam: any ValidGeneratorInput = 1.0,
minfreq: any ValidGeneratorInput = 440.0,
maxfreq: any ValidGeneratorInput = 660.0,
ampscale: any ValidGeneratorInput = 0.5,
durscale: any ValidGeneratorInput = 0.5,
initCPs: Int = 12,
knum: any ValidGeneratorInput = 12.0,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0,
seed: UInt64? = nil
) {
super.init(
ampdist: ampdist, durdist: durdist,
adparam: adparam, ddparam: ddparam,
minfreq: minfreq, maxfreq: maxfreq,
ampscale: ampscale, durscale: durscale,
initCPs: initCPs, knum: knum,
mul: mul, add: add,
seed: seed,
seedMixConstant: 0x1357_2468_ABCD_EF01
)
}
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
let sampleRate: Double = Double(graph.engine.sampleRate)
let adparam: Double = adparamInput.floatValue(graph: graph)
let ddparam: Double = ddparamInput.floatValue(graph: graph)
let minfreq: Double = max(minfreqInput.floatValue(graph: graph), Double.leastNonzeroMagnitude)
let maxfreq: Double = max(maxfreqInput.floatValue(graph: graph), minfreq)
let ampscale: Double = ampscaleInput.floatValue(graph: graph)
let durscale: Double = durscaleInput.floatValue(graph: graph)
let knumRaw: Double = knumInput.floatValue(graph: graph)
let knum: Int = max(1, min(initCPs, Int(knumRaw.rounded())))
// Guard against knum shrinking mid-stream leaving _cpIndex outside the active set.
if _cpIndex >= knum { _cpIndex = 0 }
// Duration bounds in samples: shorter duration = higher frequency.
let minDurSamples: Double = sampleRate / maxfreq
let maxDurSamples: Double = sampleRate / minfreq
let durRange: Double = maxDurSamples - minDurSamples
for i: Int in 0..<count {
// Linear interpolation between curAmp and nextAmp.
let segLenSafe: Double = max(_segLen, 1.0)
let frac: Double = _segPos / segLenSafe
_result[0][i] = _curAmp + (_nextAmp - _curAmp) * frac
_segPos += 1.0
// Check if we reached the end of the current segment.
if _segPos >= _segLen {
_segPos = 0.0
// Stochastic update of the current breakpoint.
let ampStep: Double = gendySampleDist(ampdist, param: adparam, rng: &_rng) * ampscale
_amps[_cpIndex] = gendyClamp(_amps[_cpIndex] + ampStep, lo: -1.0, hi: 1.0)
let durStep: Double = gendySampleDist(durdist, param: ddparam, rng: &_rng) * durscale
let newDur: Double = gendyClamp(_durs[_cpIndex] + durStep * durRange,
lo: minDurSamples, hi: maxDurSamples)
_durs[_cpIndex] = newDur
// Advance to the next breakpoint.
_cpIndex = (_cpIndex + 1) % knum
let nextIndex: Int = (_cpIndex + 1) % knum
_curAmp = _amps[_cpIndex]
_nextAmp = _amps[nextIndex]
_segLen = max(_durs[_cpIndex], 1.0)
}
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
// MARK: - Control
/// Control-rate Gendy1 stochastic waveform generator.
///
/// The breakpoint state machine advances by `count` samples per block. The output buffer
/// is filled with the single interpolated value at the new phase position, producing a
/// block-rate stepped signal that downstream audio-rate consumers receive as a ramp.
///
/// Useful as a slowly-evolving modulation source. At control rate the waveform updates
/// once per block, making it suitable for LFO-range stochastic modulation.
///
/// - Parameters:
/// - ampdist: Distribution used to perturb breakpoint amplitudes. Defaults to `.gauss`.
/// - durdist: Distribution used to perturb breakpoint durations. Defaults to `.gauss`.
/// - adparam: Shape parameter for `ampdist`. Defaults to `1.0`.
/// - ddparam: Shape parameter for `durdist`. Defaults to `1.0`.
/// - minfreq: Minimum frequency in Hz. Defaults to `440.0`.
/// - maxfreq: Maximum frequency in Hz. Defaults to `660.0`.
/// - ampscale: Scale of amplitude perturbation steps in \[0, 1\]. Defaults to `0.5`.
/// - durscale: Scale of duration perturbation steps in \[0, 1\]. Defaults to `0.5`.
/// - initCPs: Number of breakpoints ≥ 2. Static after init. Defaults to `12`.
/// - knum: Active breakpoint count. Clamped to \[1, `initCPs`\] each block. Defaults to `12.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
/// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed.
public final class Control: _Base, BlockRateControlGenerator {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
/// - Parameters:
/// - ampdist: Distribution used to perturb breakpoint amplitudes. Defaults to `.gauss`.
/// - durdist: Distribution used to perturb breakpoint durations. Defaults to `.gauss`.
/// - adparam: Shape parameter for `ampdist`. Defaults to `1.0`.
/// - ddparam: Shape parameter for `durdist`. Defaults to `1.0`.
/// - minfreq: Minimum frequency in Hz. Defaults to `440.0`.
/// - maxfreq: Maximum frequency in Hz. Defaults to `660.0`.
/// - ampscale: Scale of amplitude perturbation steps in \[0, 1\]. Defaults to `0.5`.
/// - durscale: Scale of duration perturbation steps in \[0, 1\]. Defaults to `0.5`.
/// - initCPs: Number of breakpoints ≥ 2. Static after init. Defaults to `12`.
/// - knum: Active breakpoint count. Clamped to \[1, `initCPs`\] each block. Defaults to `12.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
/// - seed: Optional PRNG seed for deterministic output. `nil` uses a time-based seed.
public init(
ampdist: DistributionKind = .gauss,
durdist: DistributionKind = .gauss,
adparam: any ValidGeneratorInput = 1.0,
ddparam: any ValidGeneratorInput = 1.0,
minfreq: any ValidGeneratorInput = 440.0,
maxfreq: any ValidGeneratorInput = 660.0,
ampscale: any ValidGeneratorInput = 0.5,
durscale: any ValidGeneratorInput = 0.5,
initCPs: Int = 12,
knum: any ValidGeneratorInput = 12.0,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0,
seed: UInt64? = nil
) {
super.init(
ampdist: ampdist, durdist: durdist,
adparam: adparam, ddparam: ddparam,
minfreq: minfreq, maxfreq: maxfreq,
ampscale: ampscale, durscale: durscale,
initCPs: initCPs, knum: knum,
mul: mul, add: add,
seed: seed,
seedMixConstant: 0xFEDC_BA98_1357_2468
)
}
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
let sampleRate: Double = Double(graph.engine.sampleRate)
let adparam: Double = adparamInput.floatValue(graph: graph)
let ddparam: Double = ddparamInput.floatValue(graph: graph)
let minfreq: Double = max(minfreqInput.floatValue(graph: graph), Double.leastNonzeroMagnitude)
let maxfreq: Double = max(maxfreqInput.floatValue(graph: graph), minfreq)
let ampscale: Double = ampscaleInput.floatValue(graph: graph)
let durscale: Double = durscaleInput.floatValue(graph: graph)
let knumRaw: Double = knumInput.floatValue(graph: graph)
let knum: Int = max(1, min(initCPs, Int(knumRaw.rounded())))
// Guard against knum shrinking mid-stream leaving _cpIndex outside the active set.
if _cpIndex >= knum { _cpIndex = 0 }
let minDurSamples: Double = sampleRate / maxfreq
let maxDurSamples: Double = sampleRate / minfreq
let durRange: Double = maxDurSamples - minDurSamples
// Advance phase by `count` samples, firing stochastic updates at each segment boundary.
var remaining: Double = Double(count)
while remaining > 0.0 {
let toNextBoundary: Double = _segLen - _segPos
if remaining >= toNextBoundary {
remaining -= toNextBoundary
_segPos = 0.0
let ampStep: Double = gendySampleDist(ampdist, param: adparam, rng: &_rng) * ampscale
_amps[_cpIndex] = gendyClamp(_amps[_cpIndex] + ampStep, lo: -1.0, hi: 1.0)
let durStep: Double = gendySampleDist(durdist, param: ddparam, rng: &_rng) * durscale
let newDur: Double = gendyClamp(_durs[_cpIndex] + durStep * durRange,
lo: minDurSamples, hi: maxDurSamples)
_durs[_cpIndex] = newDur
_cpIndex = (_cpIndex + 1) % knum
let nextIndex: Int = (_cpIndex + 1) % knum
_curAmp = _amps[_cpIndex]
_nextAmp = _amps[nextIndex]
_segLen = max(_durs[_cpIndex], 1.0)
} else {
_segPos += remaining
remaining = 0.0
}
}
// Compute current interpolated value at new position.
let segLenSafe: Double = max(_segLen, 1.0)
let frac: Double = _segPos / segLenSafe
let target: Double = _curAmp + (_nextAmp - _curAmp) * frac
let rampStart: Double = _rampTarget
_rampTarget = target
guard count > 0 else { return _result }
previousOutputValue = fillRampedResult(
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
return _result
}
}
}
extension Gendy1: GeneratorEnum {
public typealias AudioType = Gendy1.Audio
public typealias ControlType = Gendy1.Control
}