1.0.0 release

This commit is contained in:
2026-06-01 18:27:40 -07:00
parent b1ab0f102c
commit 1f20fcab20
1151 changed files with 230703 additions and 14 deletions
@@ -0,0 +1,389 @@
// 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, ControlGenerator {
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
)
_setupSubBlockBuffer()
}
// Bypass sub-block loop: phase position and PRNG must advance exactly once per audio block.
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
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
}
@@ -0,0 +1,408 @@
// Gendy2.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Stochastic waveform generator using `N` breakpoints with **cubic (Catmull-Rom)
/// interpolation** between them. Both amplitude and duration are updated stochastically
/// each cycle using the shared ``DistributionKind`` family.
///
/// `Gendy2` is identical to `Gendy1` in its state machine but produces a smoother
/// waveform by interpolating with a Catmull-Rom spline rather than a straight line.
/// The four control points used are the two breakpoints immediately before and after
/// the current segment, providing C¹ continuity.
///
/// Modelled after SuperCollider's `Gendy2` UGen.
///
/// - 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 enum Gendy2 {
// MARK: - _Base — shared state for Audio + Control
/// Shared stored properties and init for `Gendy2.Audio` and `Gendy2.Control`.
/// State is fully shared; only the per-sample / per-block compute path differs.
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 _segLen: Double
var _rng: UInt64
// Output
var _mulAdd: MulAddSpec
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, "Gendy2: 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)
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._segLen = max(durs[0], 1.0)
self._rng = rng
super.init()
}
}
// MARK: - Audio
/// Audio-rate Gendy2 stochastic waveform generator with Catmull-Rom interpolation.
///
/// Interpolates between `knum` active breakpoints using a Catmull-Rom spline,
/// producing smooth curved shapes between stochastic 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`. 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 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`. 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: 0x2468_1357_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 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
for i: Int in 0..<count {
// Catmull-Rom spline interpolation using four surrounding breakpoints.
// p0 = one before current, p1 = current start, p2 = current end, p3 = one after.
let p1Index: Int = _cpIndex
let p2Index: Int = (_cpIndex + 1) % knum
let p0Index: Int = (_cpIndex + knum - 1) % knum
let p3Index: Int = (_cpIndex + 2) % knum
let p0: Double = _amps[p0Index]
let p1: Double = _amps[p1Index]
let p2: Double = _amps[p2Index]
let p3: Double = _amps[p3Index]
let segLenSafe: Double = max(_segLen, 1.0)
let t: Double = _segPos / segLenSafe
// Catmull-Rom coefficients.
let catmullHalf: Double = 0.5
let t2: Double = t * t
let t3: Double = t2 * t
_result[0][i] = catmullHalf * (
(2.0 * p1)
+ (-p0 + p2) * t
+ (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2
+ (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3
)
_segPos += 1.0
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 next breakpoint.
_cpIndex = (_cpIndex + 1) % knum
_segLen = max(_durs[_cpIndex], 1.0)
}
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
// MARK: - Control
/// Control-rate Gendy2 stochastic waveform generator with Catmull-Rom interpolation.
///
/// The breakpoint state machine advances by `count` samples per block. The output buffer
/// is filled with the single Catmull-Rom interpolated value at the new phase position,
/// producing a block-rate stepped signal that downstream audio-rate consumers receive as a ramp.
///
/// - 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, ControlGenerator {
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: 0xABCD_EF01_2468_1357
)
_setupSubBlockBuffer()
}
// Bypass sub-block loop: phase position and PRNG must advance exactly once per audio block.
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
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
_segLen = max(_durs[_cpIndex], 1.0)
} else {
_segPos += remaining
remaining = 0.0
}
}
// Catmull-Rom interpolation at the new position.
let p1Index: Int = _cpIndex
let p2Index: Int = (_cpIndex + 1) % knum
let p0Index: Int = (_cpIndex + knum - 1) % knum
let p3Index: Int = (_cpIndex + 2) % knum
let p0: Double = _amps[p0Index]
let p1: Double = _amps[p1Index]
let p2: Double = _amps[p2Index]
let p3: Double = _amps[p3Index]
let segLenSafe: Double = max(_segLen, 1.0)
let t: Double = _segPos / segLenSafe
let catmullHalf: Double = 0.5
let t2: Double = t * t
let t3: Double = t2 * t
let target: Double = catmullHalf * (
(2.0 * p1)
+ (-p0 + p2) * t
+ (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2
+ (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3
)
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 Gendy2: GeneratorEnum {
public typealias AudioType = Gendy2.Audio
public typealias ControlType = Gendy2.Control
}
@@ -0,0 +1,327 @@
// 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, ControlGenerator {
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
)
_setupSubBlockBuffer()
}
// Bypass sub-block loop: phase position and PRNG must advance exactly once per audio block.
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
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
}
@@ -0,0 +1,98 @@
// GendyHelpers.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// MARK: - Gendy shared helpers
/// Maps a `DistributionKind` to a zero-centred stochastic step value scaled by `param`.
///
/// Used by `Gendy1`, `Gendy2`, and `Gendy3` to perturb breakpoint amplitudes and durations.
/// The `param` argument is the primary shape parameter for each distribution:
///
/// | Distribution | Meaning of `param` | Output range |
/// |---|---|---|
/// | `.uniform` | half-range | \[-param, +param\] |
/// | `.lpRand` | half-range | \[-param, +param\] biased toward lo |
/// | `.hpRand` | half-range | \[-param, +param\] biased toward hi |
/// | `.meanRand` | half-range | \[-param, +param\] biased toward midpoint |
/// | `.gauss` | standard deviation σ | N(0, σ) |
/// | `.cauchy` | spread | Cauchy(0, param) |
/// | `.laplace` | dispersion b | Laplace(b), symmetric around 0 |
/// | `.alaplace` | dispersion b | Asymmetric Laplace(b) |
/// | `.exponential` | mean (1/λ) | Bipolar exponential |
/// | `.gamma` | shape k | Bipolar gamma(k) |
/// | `.hcos` | dispersion | Half-cosine, output ≈ \[-d/π, +d/π\] |
/// | `.logistic` | scale s | Logistic, symmetric |
/// | `.poisson` | mean λ | Bipolar integer counts / λ |
/// | `.arcsin` | dispersion | Arcsin in \[-disp, +disp\] |
/// | `.betaRand` | shape (alpha=beta) | Beta remapped to \[-param, +param\] |
/// | `.expRand` | scale | Bipolar log-uniform |
///
/// All calls are RT-safe: pure arithmetic, no allocation.
@inline(__always)
func gendySampleDist(
_ dist: DistributionKind,
param: Double,
rng: inout UInt64
) -> Double {
let safeParam: Double = max(abs(param), Double.leastNonzeroMagnitude)
switch dist {
case .uniform:
return _sampleUniform(lo: -safeParam, hi: safeParam, rng: &rng)
case .lpRand:
return _sampleLpRand(lo: -safeParam, hi: safeParam, rng: &rng)
case .hpRand:
return _sampleHpRand(lo: -safeParam, hi: safeParam, rng: &rng)
case .meanRand:
return _sampleMeanRand(lo: -safeParam, hi: safeParam, rng: &rng)
case .expRand:
// Log-uniform in [1/safeParam, safeParam] then reflect to bipolar.
// Extract sign from the high bit of a raw draw — avoids float conversion overhead.
let expLo: Double = min(1.0 / safeParam, safeParam)
let expHi: Double = max(1.0 / safeParam, safeParam)
let expSign: Double = xorshift64NextRaw(&rng) >> 63 == 0 ? 1.0 : -1.0
return expSign * _sampleExpRand(lo: expLo, hi: expHi, rng: &rng)
case .exponential:
// Bipolar: reflect exponential(density=1/safeParam) with equal probability.
// Extract sign from the high bit of a raw draw — avoids float conversion overhead.
let expSign: Double = xorshift64NextRaw(&rng) >> 63 == 0 ? 1.0 : -1.0
return expSign * _sampleExponential(density: 1.0 / safeParam, rng: &rng)
case .gamma:
// Bipolar: reflect gamma(shape=safeParam) with equal probability.
// Extract sign from the high bit of a raw draw — avoids float conversion overhead.
let gammaSign: Double = xorshift64NextRaw(&rng) >> 63 == 0 ? 1.0 : -1.0
return gammaSign * _sampleGamma(shape: safeParam, rng: &rng)
case .laplace:
return _sampleLaplace(dispersion: safeParam, rng: &rng)
case .alaplace:
return _sampleALaplace(dispersion: safeParam, rng: &rng)
case .hcos:
return _sampleHcos(dispersion: safeParam, rng: &rng)
case .logistic:
return _sampleLogistic(dispersion: safeParam, rng: &rng)
case .poisson:
// Bipolar: draw Poisson count, normalise by λ, reflect.
// Extract sign from the high bit of a raw draw — avoids float conversion overhead.
let poissonSign: Double = xorshift64NextRaw(&rng) >> 63 == 0 ? 1.0 : -1.0
let poissonCount: Double = _samplePoisson(mean: safeParam, rng: &rng)
return poissonSign * poissonCount / max(safeParam, 1.0)
case .arcsin:
return _sampleArcsin(dispersion: safeParam, rng: &rng)
case .betaRand:
// Symmetric beta (alpha=beta=safeParam); remap [0,1] → [-safeParam, +safeParam].
let betaRaw: Double = _sampleBetaRand(lo: 0.0, hi: 1.0, alpha: safeParam, beta: safeParam, rng: &rng)
return (betaRaw * 2.0 - 1.0) * safeParam
case .cauchy:
return _sampleCauchy(mean: 0.0, spread: safeParam, posOnly: false, rng: &rng)
case .gauss:
return _sampleGauss(dev: safeParam, mean: 0.0, rng: &rng)
}
}
/// Clamps `value` to the closed interval `[lo, hi]`. RT-safe.
@inline(__always)
func gendyClamp(_ value: Double, lo: Double, hi: Double) -> Double {
return min(max(value, lo), hi)
}