232 lines
12 KiB
Swift
232 lines
12 KiB
Swift
// SampleLoop.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// MARK: - SampleLoop
|
|
|
|
/// A user-supplied per-sample DSP body with pre-allocated output and typed feedback state.
|
|
///
|
|
/// `SampleLoop` is the RT-safe escape hatch for custom sample-accurate DSP — including
|
|
/// **single-sample feedback loops** (one-pole filters, waveguides, comb/allpass structures)
|
|
/// — without declaring a whole new `Generator` type. It owns its output buffer (inherited
|
|
/// `_result`), resolves its inputs once per block via the fan-out cache, and hands both to
|
|
/// your closure to fill.
|
|
///
|
|
/// Unlike ``Closure`` — which allocates a fresh `[Double]` every block and evaluates one
|
|
/// sample at a time through a value-returning body — `SampleLoop` performs **no per-block
|
|
/// allocation** and lets you write the whole block in one pass with your own inner loop.
|
|
///
|
|
/// ## Channels
|
|
/// The output channel count is **inferred from the inputs** — `max` over each input's
|
|
/// `outputChannelCount`, or `1` when there are no inputs — and passed to the body as
|
|
/// `numChannels`. Pass an explicit `channels:` to override (a pure multi-channel source has
|
|
/// no input to infer from; an up-mix wants more channels than its input). Each input is
|
|
/// **broadcast up to `numChannels` rows** (mono spreads to every channel), so `inputs[k][ch]`
|
|
/// is always valid inside the body and the same body scales to any width. An input whose
|
|
/// channel count is neither `1` nor `numChannels` `precondition`-traps at construction —
|
|
/// matching ``BinaryOpGenerator``'s policy.
|
|
///
|
|
/// ## Feedback state
|
|
/// State is built by `makeState(numChannels)` and passed `inout` to the body. Sizing it from
|
|
/// `numChannels` keeps per-channel state (e.g. `[Double]`, one slot per channel) correct even
|
|
/// when the width is inferred. Because `build()` runs once per Synthesizer instance
|
|
/// (graph-copy-per-instance), each voice gets its own `SampleLoop` with its own `state` — no
|
|
/// shared mutable state, no retain cycle from capturing the enclosing Synthesizer.
|
|
///
|
|
/// ```swift
|
|
/// // Per-channel one-pole feedback lowpass — works for mono, stereo, or N-channel input.
|
|
/// let coefficient: Double = 0.85
|
|
/// let lowpass = SampleLoop(
|
|
/// makeState: { channelCount in [Double](repeating: 0.0, count: channelCount) },
|
|
/// inputs: [signal]
|
|
/// ) { previousOutput, inputs, channelCount, output, sampleCount, _ in
|
|
/// for sample: Int in 0..<sampleCount {
|
|
/// for channel: Int in 0..<channelCount {
|
|
/// let filtered: Double = (1 - coefficient) * inputs[0][channel][sample]
|
|
/// + coefficient * previousOutput[channel]
|
|
/// output[channel][sample] = filtered
|
|
/// previousOutput[channel] = filtered
|
|
/// }
|
|
/// }
|
|
/// }
|
|
/// ```
|
|
///
|
|
/// - Parameters:
|
|
/// - makeState: Builds the initial feedback / memory state from the resolved output channel
|
|
/// count. Size per-channel state from it; ignore the argument for scalar state.
|
|
/// - inputs: Signals read inside the body, `inputs[k]` in call order. `[]` for a pure source.
|
|
/// - channels: Output channel count; `nil` infers `max` over the inputs (or `1` if none).
|
|
/// - mul: Output multiplier applied after the body. Defaults to `1.0`.
|
|
/// - add: Output offset applied after the body. Defaults to `0.0`.
|
|
/// - body: The per-sample DSP closure. See ``Body``.
|
|
///
|
|
/// - Warning: The body runs on the **RT render thread**. It obeys the same rules as any
|
|
/// `_computeSamples`: no allocation, locks, `print`, or `String` construction. The type
|
|
/// guarantees an allocation-free frame (buffer + input resolution); the body's contents
|
|
/// are your responsibility. Do **not** capture the `SampleLoop` (or its enclosing
|
|
/// Synthesizer) inside the body — the instance stores the body, so capturing itself forms a
|
|
/// strong reference cycle; drive feedback through the `inout State` argument instead.
|
|
/// Prototype here, then promote hot paths to a concrete `AudioGenerator` when you want
|
|
/// parameters, Quick Help, reuse, and raw-pointer speed.
|
|
///
|
|
/// See <doc:Debugging> for inspecting a live `SampleLoop`'s state and output.
|
|
public final class SampleLoop<State>: GeneratorBase, AudioGenerator {
|
|
|
|
/// The per-sample DSP body.
|
|
///
|
|
/// - Parameters:
|
|
/// - state: Feedback / memory state, mutated in place across samples and blocks.
|
|
/// - inputs: `inputs[input][channel][sample]`. Every input is broadcast to `numChannels`
|
|
/// rows, so `channel` is always valid up to `numChannels`.
|
|
/// - numChannels: Output channel count for this instance (also the row count of every
|
|
/// `inputs[input]` and of `output`).
|
|
/// - output: Output buffers, `numChannels` rows. Pre-zeroed each block, so a body that
|
|
/// writes fewer than `sampleCount` samples leaves silence — never stale data — in the
|
|
/// gaps. Writes go straight into the pre-allocated result; no allocation.
|
|
/// - sampleCount: Samples to produce this segment.
|
|
/// - graph: The current synthesis graph (for `graph.engine.sampleRate`, buses, etc.).
|
|
public typealias Body = (
|
|
_ state: inout State,
|
|
_ inputs: [[[Double]]],
|
|
_ numChannels: Int,
|
|
_ output: inout [[Double]],
|
|
_ sampleCount: Int,
|
|
_ graph: SynthGraph
|
|
) -> Void
|
|
|
|
/// Typed feedback / memory state, passed `inout` to the body each block.
|
|
public var state: State
|
|
|
|
/// Fixed output channel count, set at `init`. See ``outputChannelCount``.
|
|
private let channels: Int
|
|
|
|
/// Resolved inputs, pulled once per block.
|
|
private let inputs: [any ValidGeneratorInput]
|
|
|
|
/// Whether each resolved input is a `Generator` (block-rate `calculatedSamples`) or a
|
|
/// scalar (block-constant `floatValue`). Classified once at `init` — never `is`-tested on
|
|
/// the RT thread. Scalars must not go through `calculatedSamples`, which allocates a fresh
|
|
/// block for a bare `Double` every call.
|
|
private let inputIsGenerator: [Bool]
|
|
|
|
/// Each input's channel count, captured at `init` (`1` ⇒ broadcast, else `== channels`).
|
|
private let inputChannels: [Int]
|
|
|
|
/// Privately-owned `[input][channel][sample]` scratch, each row pre-allocated to
|
|
/// `lyrebirdDefaultResultBufferSize` at `init`. Input samples are **copied** into it each
|
|
/// block — never aliased — so no reference to an upstream generator's `_result` survives
|
|
/// across blocks (which would force a copy-on-write allocation inside that generator's
|
|
/// next in-place write). Copying into these uniquely-owned rows is allocation-free.
|
|
private var _resolvedInputs: [[[Double]]]
|
|
|
|
/// The user-supplied per-sample DSP body.
|
|
private let body: Body
|
|
|
|
/// Post-body output scaling (`mul` / `add`), applied only when non-identity.
|
|
private let _mulAdd: MulAddSpec
|
|
|
|
public override var outputChannelCount: Int { channels }
|
|
|
|
/// - Parameters:
|
|
/// - makeState: Builds the initial feedback / memory state, given the resolved output
|
|
/// channel count. Size per-channel state from it (e.g. `{ n in [Double](repeating: 0, count: n) }`);
|
|
/// for a scalar state ignore the argument (`{ _ in 0.0 }`).
|
|
/// - inputs: Signals read inside the body, exposed as `inputs[k]` in call order. Pass `[]`
|
|
/// for a pure source. Scalars and generators are both accepted; each is broadcast to
|
|
/// `numChannels` rows.
|
|
/// - channels: Output channel count. `nil` (default) infers `max` over the inputs'
|
|
/// channel counts, or `1` when there are no inputs. Provide explicitly for a pure
|
|
/// multi-channel source or an up-mix.
|
|
/// - mul: Output multiplier applied after the body. Defaults to `1.0`.
|
|
/// - add: Output offset applied after the body. Defaults to `0.0`.
|
|
/// - body: The per-sample DSP closure. See ``Body``.
|
|
public init(
|
|
makeState: (_ numChannels: Int) -> State,
|
|
inputs: [any ValidGeneratorInput] = [],
|
|
channels: Int? = nil,
|
|
mul: any ValidGeneratorInput = 1.0,
|
|
add: any ValidGeneratorInput = 0.0,
|
|
body: @escaping Body
|
|
) {
|
|
let resolved: [any ValidGeneratorInput] = inputs.map { $0._resolvedInput() }
|
|
let genFlags: [Bool] = resolved.map { $0 is any Generator }
|
|
let perInputChannels: [Int] = resolved.map { ($0 as? any Generator)?.outputChannelCount ?? 1 }
|
|
let outChannels: Int = channels ?? (perInputChannels.max() ?? 1)
|
|
precondition(outChannels >= 1, "SampleLoop channels must be >= 1, got \(outChannels).")
|
|
for idx: Int in 0..<perInputChannels.count {
|
|
let ch: Int = perInputChannels[idx]
|
|
precondition(
|
|
ch == 1 || ch == outChannels,
|
|
"SampleLoop input \(idx) has \(ch) channels; must be mono or \(outChannels)."
|
|
)
|
|
}
|
|
self.channels = outChannels
|
|
self.inputs = resolved
|
|
self.inputIsGenerator = genFlags
|
|
self.inputChannels = perInputChannels
|
|
self._resolvedInputs = resolved.map { _ in
|
|
(0..<outChannels).map { _ in makeSampleBuffer() }
|
|
}
|
|
self.body = body
|
|
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
|
self.state = makeState(outChannels)
|
|
super.init(channels: outChannels)
|
|
}
|
|
|
|
public func _computeSamples(
|
|
graph: SynthGraph,
|
|
count: Int
|
|
) -> [[Double]] {
|
|
_checkCount(count)
|
|
// Copy inputs into privately-owned scratch, broadcasting mono inputs across channels.
|
|
// Copying (not aliasing) keeps every upstream `_result` uniquely owned across blocks,
|
|
// and routing scalars through `floatValue` avoids the per-block block allocation a bare
|
|
// `Double.calculatedSamples` would incur. Both keep the RT path allocation-free.
|
|
for k: Int in 0..<inputs.count {
|
|
if inputIsGenerator[k] {
|
|
let block: [[Double]] = inputs[k].calculatedSamples(graph: graph, count: count)
|
|
if inputChannels[k] == 1 {
|
|
copyBroadcast(block.first ?? [], into: k, count: count)
|
|
} else {
|
|
for ch: Int in 0..<channels {
|
|
let src: [Double] = ch < block.count ? block[ch] : []
|
|
copyRow(src, into: k, channel: ch, count: count)
|
|
}
|
|
}
|
|
} else {
|
|
fillScalar(inputs[k].floatValue(graph: graph), into: k, count: count)
|
|
}
|
|
}
|
|
// Pre-zero the live region of every output channel: gaps read as silence. A body that
|
|
// writes all `count` samples per channel overwrites this immediately — the cost is the
|
|
// price of the safety for partial-write bodies.
|
|
for ch: Int in 0..<channels {
|
|
for i: Int in 0..<count { _result[ch][i] = 0.0 }
|
|
}
|
|
body(&state, _resolvedInputs, channels, &_result, count, graph)
|
|
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
|
return _result
|
|
}
|
|
|
|
/// Copy `src` into scratch channel `channel` of input `k`, zero-padding past `src`.
|
|
private func copyRow(_ src: [Double], into k: Int, channel: Int, count: Int) {
|
|
let m: Int = Swift.min(count, src.count)
|
|
for i: Int in 0..<m { _resolvedInputs[k][channel][i] = src[i] }
|
|
for i: Int in m..<count { _resolvedInputs[k][channel][i] = 0.0 }
|
|
}
|
|
|
|
/// Copy one `src` row into every channel of input `k` (mono broadcast).
|
|
private func copyBroadcast(_ src: [Double], into k: Int, count: Int) {
|
|
for ch: Int in 0..<channels { copyRow(src, into: k, channel: ch, count: count) }
|
|
}
|
|
|
|
/// Fill every channel of input `k` with the block-constant scalar `value`.
|
|
private func fillScalar(_ value: Double, into k: Int, count: Int) {
|
|
for ch: Int in 0..<channels {
|
|
for i: Int in 0..<count { _resolvedInputs[k][ch][i] = value }
|
|
}
|
|
}
|
|
}
|