f8878324fd
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>
386 lines
20 KiB
Swift
386 lines
20 KiB
Swift
// Generator.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
/// The base protocol for all signal-producing units in Lyrebird.
|
||
///
|
||
/// A `Generator` reads its inputs, advances internal state, and writes output into a
|
||
/// pre-allocated buffer. Generators are wired into a directed acyclic graph (DAG) inside
|
||
/// a `Synthesizer`; `SynthesisEngine` drives the graph by calling `rootGroup.evaluate`
|
||
/// once per audio block.
|
||
///
|
||
/// **Fan-out caching** — When one generator feeds multiple downstream consumers, the
|
||
/// protocol extension's `calculatedSamples` gateway ensures the generator is evaluated
|
||
/// only once per segment. Implement `_computeSamples` to produce samples; the cache is
|
||
/// managed automatically.
|
||
///
|
||
/// **RT safety** — Conforming types must not allocate memory, acquire locks, or block on
|
||
/// the RT thread. Pre-allocate all output buffers in `init`.
|
||
///
|
||
/// Prefer conforming to `AudioGenerator` or `ControlGenerator` rather than `Generator`
|
||
/// directly — those sub-protocols supply default `rate` implementations.
|
||
///
|
||
/// ```swift
|
||
/// final class MySaw: GeneratorBase, AudioGenerator {
|
||
/// var freq: any ValidGeneratorInput
|
||
///
|
||
/// init(freq: any ValidGeneratorInput) { self.freq = freq }
|
||
///
|
||
/// func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||
/// _checkCount(count)
|
||
/// // fill _result[0][0..<count] with sawtooth samples …
|
||
/// return _result
|
||
/// }
|
||
/// }
|
||
/// ```
|
||
/// `_result` is provided by `GeneratorBase` (mono, pre-allocated, zero-filled). `floatValue`
|
||
/// is provided by the `AudioGenerator` extension. Multi-row generators call
|
||
/// `super.init(channels: N)` and override `outputChannelCount` — no `_result` redeclaration
|
||
/// in the subclass, no post-super reassignment.
|
||
public protocol Generator: AnyObject, ValidGeneratorInput {
|
||
var rate: ProcessingRate { get }
|
||
|
||
/// The number of output channels (rows) this generator's `_result` will produce.
|
||
///
|
||
/// Channel count is **structurally fixed at `init`** and never changes at runtime. Set it
|
||
/// from a `let` constant or from `_result.count` after the buffer is allocated. Generators
|
||
/// that emit a single channel inherit `1` from `GeneratorBase`; multi-row generators
|
||
/// (Pan2/Pan4/PanN/AmbiEncoder1/AmbiDecoder1, SVF, FrequencyShifter.Audio, Chorus.Audio,
|
||
/// GeneratorArray, TimeStretch.Audio, multi-channel In/BufferRead/PlayBuffer, etc.) MUST
|
||
/// override this property.
|
||
///
|
||
/// **Why this matters** — `BinaryOpGenerator` (the `+ - * /` operator backbone) reads
|
||
/// `outputChannelCount` on each operand at construction to decide whether to broadcast a
|
||
/// mono operand to the other side's channel count, run an element-wise N×N path, or trap
|
||
/// on a mismatched N×M (both > 1, N ≠ M). A missing override silently mono-izes a
|
||
/// multi-row generator under arithmetic, dropping every channel beyond row 0.
|
||
///
|
||
/// Reading this property is build-time only (graph construction); never query it from the
|
||
/// RT thread.
|
||
var outputChannelCount: Int { get }
|
||
|
||
/// Compute `count` output samples into the generator's internal buffer and return it.
|
||
///
|
||
/// Implement this method instead of `calculatedSamples` — the caching gateway
|
||
/// `calculatedSamples` (provided by the `Generator` protocol extension) calls
|
||
/// `_computeSamples` on a segment-serial miss and returns the cached result on a hit.
|
||
/// This prevents double state-advance when a generator is shared (fan-out) between
|
||
/// multiple downstream consumers.
|
||
///
|
||
/// - Precondition: `count ≤ lyrebirdDefaultResultBufferSize`.
|
||
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]]
|
||
|
||
func floatValue(graph: SynthGraph) -> Double
|
||
|
||
/// The segment serial from the most recent `calculatedSamples` call.
|
||
///
|
||
/// Compared against `graph.engine.segmentSerial` to detect whether this generator has
|
||
/// already been evaluated in the current segment. Initialise to `0` in each class —
|
||
/// `SynthesisEngine.segmentSerial` starts at `1`, so the very first call always misses.
|
||
var _segmentSerial: UInt64 { get set }
|
||
|
||
/// The cached result from the most recent `_computeSamples` call.
|
||
///
|
||
/// Returned directly on a serial hit to avoid re-evaluating the generator.
|
||
/// Initialise to `[[]]` — the serial guard ensures the sentinel is never returned to
|
||
/// callers before the first `_computeSamples` call populates it.
|
||
///
|
||
/// ## CoW and ARC model
|
||
///
|
||
/// `calculatedSamples` clears `_cachedResult` to `[]` (the empty-array singleton, no
|
||
/// heap allocation) before calling `_computeSamples`. This ensures `_result[0]`'s
|
||
/// backing buffer is uniquely referenced when `_computeSamples` writes into it,
|
||
/// preventing a CoW copy. After computing, `_cachedResult = result` re-acquires a
|
||
/// reference to `_result[0]`'s storage (ARC retain, not a heap allocation). The
|
||
/// remaining ARC traffic (one retain + release per `calculatedSamples` return) is
|
||
/// accepted and consistent with the existing `[[Double]]` protocol contract.
|
||
var _cachedResult: [[Double]] { get set }
|
||
}
|
||
|
||
/// A `Generator` that runs at audio rate — one output sample per engine sample tick.
|
||
///
|
||
/// Conform to `AudioGenerator` (rather than `Generator` directly) to receive the
|
||
/// `rate == .audio` property automatically and to signal to downstream consumers that
|
||
/// your output is sample-accurate.
|
||
///
|
||
/// Pre-allocate a `[[Double]]` result buffer in `init` and write into it in-place
|
||
/// inside `_computeSamples`; return that same buffer to avoid RT heap allocation.
|
||
public protocol AudioGenerator: Generator {}
|
||
|
||
/// A Generator that produces one output value per block, delivered to downstream
|
||
/// audio-rate consumers as a linearly-interpolated ramp within `calculatedSamples`.
|
||
///
|
||
/// **Interpolation convention** — "reaches target at last sample":
|
||
/// Given `previousOutputValue = P` and a new block target `T`, the ramp over N samples is:
|
||
/// ```
|
||
/// step = (T − P) / N
|
||
/// sample[i] = P + step × (i + 1) (i = 0 … N−1)
|
||
/// ```
|
||
/// The last sample (`i = N−1`) equals T exactly. The next block starts its ramp from T.
|
||
///
|
||
/// **Conformance requirements** — a concrete ControlGenerator must provide:
|
||
/// 1. `func floatValue(graph:) -> Double` — the target for the current block.
|
||
/// 2. `var previousOutputValue: Double = 0.0` — stored property for ramp state.
|
||
/// The default `_computeSamples` extension implementation updates this automatically.
|
||
public protocol ControlGenerator: Generator {
|
||
/// The output value at the end of the previous block.
|
||
///
|
||
/// Serves as the ramp start for the next call to `_computeSamples`. Initialise to
|
||
/// `0.0`; the default `_computeSamples` implementation updates it after each block.
|
||
var previousOutputValue: Double { get set }
|
||
|
||
/// Pre-allocated assembly buffer for control sub-block output.
|
||
///
|
||
/// Used by `calculatedSamples` when `controlBlockSize < count` to accumulate
|
||
/// results from multiple `_computeSamples` calls without heap allocation.
|
||
/// Initialise to `[[]]` (via `GeneratorBase` default). A sub-blocking `Control.init`
|
||
/// calls `_setupSubBlockBuffer()` to resize for sub-block assembly (never on the RT
|
||
/// thread); `BlockRateControlGenerator` conformers never sub-block and skip it.
|
||
var _subBlockBuffer: [[Double]] { get set }
|
||
}
|
||
|
||
// MARK: - Caching gateway (provided for all Generator conformers)
|
||
|
||
extension Generator {
|
||
/// Evaluates `count` samples, caching the result for the current segment.
|
||
///
|
||
/// On the first call within a segment (serial miss), delegates to `_computeSamples` and
|
||
/// stores the result in `_cachedResult`. Subsequent calls whose requested `count` is ≤
|
||
/// the cached result's channel length return the cached result immediately, preventing
|
||
/// double state-advance when one generator feeds multiple downstream consumers (fan-out).
|
||
///
|
||
/// The cache is keyed on `graph.engine.segmentSerial`, which is incremented once per
|
||
/// `evaluateSegment` call. Within each segment, a generator's state advances exactly once
|
||
/// regardless of how many consumers evaluate it.
|
||
///
|
||
/// **Count-comparison rule:** a request for fewer samples than the cached count is served
|
||
/// from the cache (e.g. a `floatValue` call that routed through `count = 1` after a full
|
||
/// block was already cached). A request for more samples than the cached count forces a
|
||
/// recompute, guaranteeing callers never receive an undersized buffer.
|
||
///
|
||
/// - Parameters:
|
||
/// - graph: Current synthesis graph context; `graph.engine.segmentSerial` is the cache key.
|
||
/// - count: Number of samples to compute. Must be ≤ `lyrebirdDefaultResultBufferSize`.
|
||
/// - Returns: A 2-D buffer with at least `count` samples in the first channel.
|
||
public func calculatedSamples(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
let currentSerial: UInt64 = graph.engine.segmentSerial
|
||
if _segmentSerial == currentSerial,
|
||
let cachedChannel: [Double] = _cachedResult.first, cachedChannel.count >= count {
|
||
return _cachedResult
|
||
}
|
||
_segmentSerial = currentSerial
|
||
// Clear to the empty-array singleton before computing. This releases the reference
|
||
// stored from the previous block so `_result[0]`'s backing buffer becomes uniquely
|
||
// referenced again. Without this, `_computeSamples` would trigger a CoW copy every
|
||
// block because `_cachedResult[0]` retains the same backing storage as `_result[0]`.
|
||
// Swift's empty-array value (`[]`) uses a shared static singleton — no heap allocation.
|
||
_cachedResult = []
|
||
let result: [[Double]] = _computeSamples(graph: graph, count: count)
|
||
_cachedResult = result
|
||
return result
|
||
}
|
||
|
||
public func intValue(graph: SynthGraph) -> Int { Int(floatValue(graph: graph)) }
|
||
public func needsInterpolation() -> Bool { rate == .control }
|
||
|
||
/// Produces a single-channel sample block by delegating to `calculatedSamples`.
|
||
///
|
||
/// The `previousValue` parameter is **not used** for `Generator` conformers — control-rate
|
||
/// generators track interpolation state internally via `previousOutputValue`.
|
||
/// Audio-rate generators return their block from `calculatedSamples` directly.
|
||
/// The fallback empty-array guard fires only if a conformer incorrectly returns an
|
||
/// empty outer array from `calculatedSamples`.
|
||
public func sampleBlock(
|
||
graph: SynthGraph,
|
||
count: Int,
|
||
previousValue: Double
|
||
) -> [Double] {
|
||
calculatedSamples(graph: graph, count: count).first
|
||
?? [Double](repeating: 0, count: count)
|
||
}
|
||
|
||
/// Bypass-sub-block fan-out cache helper.
|
||
///
|
||
/// The block-rate gateway: runs `_computeSamples` exactly once per audio block,
|
||
/// bypassing the `ControlGenerator` extension's sub-block path. Required for any
|
||
/// generator whose state must advance once per audio block (IIR filters, bus writers,
|
||
/// buffer-position advancers, gain smoothers, trigger detectors, random drawers,
|
||
/// analysers). See `docs/protocols/writing-generators.md` §15.
|
||
///
|
||
/// The standard way to get this behaviour is to conform the control generator to
|
||
/// `BlockRateControlGenerator`, whose `calculatedSamples` default calls this method —
|
||
/// prefer that over hand-writing a `calculatedSamples` forwarder. Call this directly
|
||
/// only when the bypass is needed but the marker cannot apply.
|
||
@inline(__always)
|
||
public func _calculatedSamplesBlockRate(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
let currentSerial: UInt64 = graph.engine.segmentSerial
|
||
if _segmentSerial == currentSerial,
|
||
let cachedChannel: [Double] = _cachedResult.first, cachedChannel.count >= count {
|
||
return _cachedResult
|
||
}
|
||
_segmentSerial = currentSerial
|
||
// Clear to the empty-array singleton before computing — same CoW rationale as
|
||
// the default `calculatedSamples` gateway above: releases the previous block's
|
||
// reference so `_result[0]`'s backing storage becomes uniquely owned again,
|
||
// preventing a CoW copy inside `_computeSamples`.
|
||
_cachedResult = []
|
||
let result: [[Double]] = _computeSamples(graph: graph, count: count)
|
||
_cachedResult = result
|
||
return result
|
||
}
|
||
}
|
||
|
||
// MARK: - ControlGenerator calculatedSamples (sub-block override)
|
||
|
||
extension ControlGenerator {
|
||
/// Overrides the `Generator` extension gateway to support control-rate sub-blocking.
|
||
///
|
||
/// When `graph.engine.controlBlockSize < count`, calls `_computeSamples` in
|
||
/// `controlBlockSize`-sample chunks and assembles the results into `_subBlockBuffer`
|
||
/// (pre-allocated in `GeneratorBase` — no RT heap allocation).
|
||
/// This keeps AudioGenerator tree traversal at full-block rate while ControlGenerators
|
||
/// update their state more frequently.
|
||
///
|
||
/// Multi-channel ControlGenerators must ensure `_subBlockBuffer` has at least as many
|
||
/// rows as their channel count. The `_Base` init for multi-channel generators (e.g.
|
||
/// `In.Control(channels: N)`) sets `_subBlockBuffer` to N rows at construction time.
|
||
///
|
||
/// - Note: AudioGenerator inputs evaluated inside `_computeSamples` receive
|
||
/// `count = subCount`, not `blockSize`. Their state advances `subCount` samples per
|
||
/// sub-block call. For freq-mod inputs, use `floatValue` (block-rate) or a
|
||
/// `ControlGenerator` source to avoid partial phase advancement.
|
||
public func calculatedSamples(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
let currentSerial: UInt64 = graph.engine.segmentSerial
|
||
if _segmentSerial == currentSerial,
|
||
let cachedChannel: [Double] = _cachedResult.first, cachedChannel.count >= count {
|
||
return _cachedResult
|
||
}
|
||
_segmentSerial = currentSerial
|
||
_cachedResult = []
|
||
|
||
let cbs: Int = graph.engine.controlBlockSize
|
||
guard cbs < count else {
|
||
let result: [[Double]] = _computeSamples(graph: graph, count: count)
|
||
_cachedResult = result
|
||
return result
|
||
}
|
||
|
||
// _subBlockBuffer must be pre-allocated via _setupSubBlockBuffer() in Control.init.
|
||
precondition(!_subBlockBuffer.isEmpty && !_subBlockBuffer[0].isEmpty,
|
||
"\(type(of: self)) entered sub-block path with empty _subBlockBuffer — call _setupSubBlockBuffer() in its Control.init")
|
||
|
||
// Sub-block path: call _computeSamples in controlBlockSize-sample chunks.
|
||
// _cachedResult was cleared above so _result[0]'s backing is uniquely owned
|
||
// throughout all _computeSamples calls — no CoW copies inside the loop.
|
||
// Results are assembled into _subBlockBuffer (pre-allocated, no RT heap allocation).
|
||
var offset: Int = 0
|
||
while offset < count {
|
||
let subCount: Int = min(cbs, count - offset)
|
||
let subResult: [[Double]] = _computeSamples(graph: graph, count: subCount)
|
||
let writtenChannels: Int = min(subResult.count, _subBlockBuffer.count)
|
||
for ch: Int in 0..<writtenChannels {
|
||
let src: [Double] = subResult[ch]
|
||
for i: Int in 0..<subCount { _subBlockBuffer[ch][offset + i] = src[i] }
|
||
}
|
||
// Zero channels _computeSamples didn't fill (defensive — no current conformer triggers this).
|
||
for ch: Int in writtenChannels..<_subBlockBuffer.count {
|
||
for i: Int in offset..<(offset + subCount) { _subBlockBuffer[ch][i] = 0 }
|
||
}
|
||
offset += subCount
|
||
}
|
||
_cachedResult = _subBlockBuffer
|
||
return _subBlockBuffer
|
||
}
|
||
}
|
||
|
||
// MARK: - Default _computeSamples for ControlGenerator (state-tracking interpolated ramp)
|
||
|
||
extension ControlGenerator {
|
||
/// Produces an interpolated audio-rate block from `previousOutputValue` to the new
|
||
/// target returned by `floatValue(graph:)`, reaching the target at the last sample.
|
||
///
|
||
/// After each call, `previousOutputValue` is set to `target` so the next block
|
||
/// continues the ramp from there.
|
||
///
|
||
/// ## RT-allocation warning — override required for production use
|
||
///
|
||
/// This default implementation allocates a `[Double]` on every call — **not RT-safe**.
|
||
///
|
||
/// **Why it can't be fixed here:** Swift protocol extensions have no per-instance stored
|
||
/// state. A pre-allocated buffer would require a stored property on each conformer, which
|
||
/// this extension cannot provide. A true fix requires the conformer to own its buffer.
|
||
///
|
||
/// **What to do:** Every production `ControlGenerator` **must** override `_computeSamples`
|
||
/// and write into a `_result` buffer pre-allocated in `init`. All built-in conformers
|
||
/// (oscillators, envelopes, LFOs, math generators, etc.) do this. This default exists
|
||
/// only as a safe fallback during development — treat a hit on this path as a bug.
|
||
///
|
||
/// See `docs/protocols/writing-generators.md` §5 for the canonical override pattern.
|
||
public func _computeSamples(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
let target: Double = floatValue(graph: graph)
|
||
let rampStart: Double = previousOutputValue
|
||
let countFloat: Double = Double(count)
|
||
let step: Double = (target - rampStart) / countFloat
|
||
// Allocates [Double] per call — this default must be overridden in production conformers.
|
||
let samples: [Double] = (0..<count).map { i in rampStart + step * Double(i + 1) }
|
||
previousOutputValue = target
|
||
return [samples]
|
||
}
|
||
}
|
||
|
||
// MARK: - Default rate properties for AudioGenerator and ControlGenerator
|
||
|
||
extension AudioGenerator { public var rate: ProcessingRate { .audio } }
|
||
extension ControlGenerator { public var rate: ProcessingRate { .control } }
|
||
|
||
// MARK: - Default floatValue for ControlGenerator
|
||
|
||
extension ControlGenerator {
|
||
/// Default `floatValue` for control-rate generators — returns the ramp end from the
|
||
/// previous block.
|
||
///
|
||
/// `ControlGenerator._computeSamples` writes a linearly-interpolated ramp from
|
||
/// `previousOutputValue` to the new block target, then updates `previousOutputValue`
|
||
/// to the new target. The scalar value a downstream consumer reads is therefore the
|
||
/// last sample of the previous block — exactly what `previousOutputValue` already
|
||
/// holds.
|
||
///
|
||
/// Override only if your generator needs different scalar semantics (e.g.
|
||
/// `LFStepNoise.Audio` returns `currentValue` because its model isn't ramp-based —
|
||
/// note that one is an `AudioGenerator`, not a `ControlGenerator`, so this default
|
||
/// does not apply to it).
|
||
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
|
||
}
|
||
|
||
// MARK: - Default floatValue for AudioGenerator
|
||
|
||
extension AudioGenerator {
|
||
/// Default `floatValue` for audio-rate generators — first sample of the current block.
|
||
///
|
||
/// Routes through `calculatedSamples(graph:count: blockSize)` so the fan-out cache is
|
||
/// primed identically whether the consumer reads `floatValue` or the full block. The
|
||
/// `?? 0` fallback only fires if a conformer returns an empty outer array (a bug).
|
||
///
|
||
/// Override only if your generator needs different scalar semantics (e.g.
|
||
/// `ConstantGeneratorInput` returns its stored value directly without priming the cache).
|
||
/// `ControlGenerator` conformers provide their own `floatValue` returning the scalar
|
||
/// target for the block — they do not pick up this default.
|
||
public func floatValue(graph: SynthGraph) -> Double {
|
||
calculatedSamples(graph: graph, count: graph.engine.blockSize).first?.first ?? 0
|
||
}
|
||
}
|