Files
Lyrebird/Sources/Lyrebird/Generators/Gendy/Gendy3.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

323 lines
15 KiB
Swift

// Gendy3.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Placeholder segment length used before the first `_computeSamples` call sets the real value
/// from `freq` and `knum`. Any positive value works; the actual duration is recalculated on the
/// first block boundary crossing.
private let gendyDefaultSegLen: Double = 100.0
/// Stochastic waveform generator using `N` breakpoints with linear interpolation.
/// Only amplitude is updated stochastically; segment durations are fixed by the
/// `freq` parameter.
///
/// `Gendy3` is a simplified variant of `Gendy1` where the duration of each segment
/// is determined by a fundamental frequency rather than being stochastically perturbed.
/// This produces stochastic amplitude variation over a stable rhythmic structure.
///
/// Modelled after SuperCollider's `Gendy3` UGen.
///
/// - Parameters:
/// - ampdist: Distribution used to perturb breakpoint amplitudes. Defaults to `.gauss`.
/// - adparam: Shape parameter for `ampdist`. Meaning depends on distribution. Defaults to `1.0`.
/// - freq: Fundamental frequency in Hz determining segment duration. Defaults to `440.0`.
/// - ampscale: Scale of amplitude 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 enum Gendy3 {
// MARK: - _Base — shared state for Audio + Control
/// Shared stored properties and init for `Gendy3.Audio` and `Gendy3.Control`.
/// Differs from `Gendy1._Base` / `Gendy2._Base`: no `_durs` array (segment length
/// is derived from `freq` / `knum` each block), no `durdist` / `ddparam` /
/// `durscale` / `minfreq` / `maxfreq` inputs.
public class _Base: GeneratorBase {
// Inputs
let adparamInput: any ValidGeneratorInput
let freqInput: any ValidGeneratorInput
let ampscaleInput: any ValidGeneratorInput
let knumInput: any ValidGeneratorInput
// Distribution config (static)
let ampdist: DistributionKind
let initCPs: Int
// DSP state
var _amps: [Double]
var _cpIndex: Int = 0
var _segPos: Double = 0.0
var _curAmp: Double
var _nextAmp: Double
/// Length of the current segment in samples. Set to `gendyDefaultSegLen` at init,
/// recomputed each block from `freq` / `knum`.
var _segLen: Double = gendyDefaultSegLen
var _rng: UInt64
// Output
var _mulAdd: MulAddSpec
init(
ampdist: DistributionKind,
adparam: any ValidGeneratorInput,
freq: any ValidGeneratorInput,
ampscale: any ValidGeneratorInput,
initCPs: Int,
knum: any ValidGeneratorInput,
mul: any ValidGeneratorInput,
add: any ValidGeneratorInput,
seed: UInt64?,
seedMixConstant: UInt64
) {
precondition(initCPs >= 2, "Gendy3: initCPs must be >= 2, got \(initCPs)")
let resolvedAdparam: any ValidGeneratorInput = adparam._resolvedInput()
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
let resolvedAmpscale: any ValidGeneratorInput = ampscale._resolvedInput()
let resolvedKnum: any ValidGeneratorInput = knum._resolvedInput()
self.ampdist = ampdist
self.adparamInput = resolvedAdparam
self.freqInput = resolvedFreq
self.ampscaleInput = resolvedAmpscale
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)
for idx: Int in 0..<initCPs {
amps[idx] = xorshift64Next(&rng)
}
self._amps = amps
self._curAmp = amps[0]
self._nextAmp = amps[1]
self._rng = rng
super.init()
}
}
// MARK: - Audio
/// Audio-rate Gendy3 stochastic waveform generator (fixed duration, stochastic amplitude).
///
/// Each segment has a duration fixed by `freq / knum` Hz (one complete cycle at `freq`
/// spans all `knum` segments). Only breakpoint amplitudes are updated stochastically —
/// the timing structure is deterministic.
///
/// - Parameters:
/// - ampdist: Distribution used to perturb breakpoint amplitudes. Defaults to `.gauss`.
/// - adparam: Shape parameter for `ampdist`. Defaults to `1.0`.
/// - freq: Fundamental frequency in Hz. Defaults to `440.0`. No internal clamping; stay above 0.
/// - ampscale: Scale of amplitude 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`.
/// - adparam: Shape parameter for `ampdist`. Defaults to `1.0`.
/// - freq: Fundamental frequency in Hz. Defaults to `440.0`.
/// - ampscale: Scale of amplitude 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,
adparam: any ValidGeneratorInput = 1.0,
freq: any ValidGeneratorInput = 440.0,
ampscale: 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, adparam: adparam,
freq: freq, ampscale: ampscale,
initCPs: initCPs, knum: knum,
mul: mul, add: add,
seed: seed,
// Unique to Gendy3.Audio — decorrelates from LpRandNoise
// and other generators that previously shared this constant.
seedMixConstant: 0x7654_3210_BA98_FEDC
)
}
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 freq: Double = max(freqInput.floatValue(graph: graph), Double.leastNonzeroMagnitude)
let ampscale: Double = ampscaleInput.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 }
// Fixed segment length: one full cycle at `freq` spans all `knum` breakpoints.
let cycleSamples: Double = sampleRate / freq
let segmentDuration: Double = max(cycleSamples / Double(knum), 1.0)
for i: Int in 0..<count {
let segLenSafe: Double = max(_segLen, 1.0)
let frac: Double = _segPos / segLenSafe
_result[0][i] = _curAmp + (_nextAmp - _curAmp) * frac
_segPos += 1.0
if _segPos >= _segLen {
_segPos = 0.0
// Stochastic update of amplitude only.
let ampStep: Double = gendySampleDist(ampdist, param: adparam, rng: &_rng) * ampscale
_amps[_cpIndex] = gendyClamp(_amps[_cpIndex] + ampStep, lo: -1.0, hi: 1.0)
// Advance to next breakpoint.
_cpIndex = (_cpIndex + 1) % knum
let nextIndex: Int = (_cpIndex + 1) % knum
_curAmp = _amps[_cpIndex]
_nextAmp = _amps[nextIndex]
_segLen = segmentDuration
}
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
// MARK: - Control
/// Control-rate Gendy3 stochastic waveform generator (fixed duration, stochastic amplitude).
///
/// The breakpoint state machine advances by `count` samples per block. The output buffer
/// is filled with the single linearly interpolated value at the new phase position,
/// producing a block-rate stepped signal that downstream audio-rate consumers receive as a ramp.
///
/// Segment durations are fixed by `freq / knum` Hz (same as the Audio variant). Only
/// breakpoint amplitudes are updated stochastically.
///
/// - Parameters:
/// - ampdist: Distribution used to perturb breakpoint amplitudes. Defaults to `.gauss`.
/// - adparam: Shape parameter for `ampdist`. Defaults to `1.0`.
/// - freq: Fundamental frequency in Hz. Defaults to `440.0`.
/// - ampscale: Scale of amplitude 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`.
/// - adparam: Shape parameter for `ampdist`. Defaults to `1.0`.
/// - freq: Fundamental frequency in Hz. Defaults to `440.0`.
/// - ampscale: Scale of amplitude 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,
adparam: any ValidGeneratorInput = 1.0,
freq: any ValidGeneratorInput = 440.0,
ampscale: 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, adparam: adparam,
freq: freq, ampscale: ampscale,
initCPs: initCPs, knum: knum,
mul: mul, add: add,
seed: seed,
seedMixConstant: 0x0123_4567_FEDC_BA98
)
}
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 freq: Double = max(freqInput.floatValue(graph: graph), Double.leastNonzeroMagnitude)
let ampscale: Double = ampscaleInput.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 cycleSamples: Double = sampleRate / freq
let segmentDuration: Double = max(cycleSamples / Double(knum), 1.0)
// Update _segLen each block since freq/knum can change.
// If freq increased such that _segPos is now past the new _segLen, reset to segment start.
_segLen = segmentDuration
if _segPos >= _segLen { _segPos = 0.0 }
// Advance phase by `count` samples, firing stochastic amplitude updates at boundaries.
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)
_cpIndex = (_cpIndex + 1) % knum
let nextIndex: Int = (_cpIndex + 1) % knum
_curAmp = _amps[_cpIndex]
_nextAmp = _amps[nextIndex]
_segLen = segmentDuration
} else {
_segPos += remaining
remaining = 0.0
}
}
// Linear interpolation 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 Gendy3: GeneratorEnum {
public typealias AudioType = Gendy3.Audio
public typealias ControlType = Gendy3.Control
}