409 lines
20 KiB
Swift
409 lines
20 KiB
Swift
// 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
|
|
}
|