v1.4.0 release: live-coding scratch editor, interpreted Graph DSL, ClosureSynthesizer + SampleLoop
This commit is contained in:
@@ -38,6 +38,22 @@ open class GeneratorBase {
|
||||
/// resize after `init`; never touch this from the RT thread except to write samples.
|
||||
public var _result: [[Double]]
|
||||
|
||||
/// Optional human-readable label for this generator, for debugging only.
|
||||
///
|
||||
/// Set from `build()` (or right after construction) to identify an inner node in the
|
||||
/// debugger — an LLDB conditional breakpoint can then key on the tag instead of a raw
|
||||
/// pointer, e.g. break in `_computeSamples` when `self.debugTag == "mod"`. Never read
|
||||
/// on the RT thread by framework code; it exists purely so a debugger and hand-written
|
||||
/// debug taps can recognise a specific instance.
|
||||
///
|
||||
/// `nonisolated(unsafe)`: a plain optional written on the main thread before the add
|
||||
/// barrier and inspected only from a debugger — never read on the RT thread. Present in
|
||||
/// all build configurations (a nil `String?` costs one pointer per instance) so that
|
||||
/// `.debugTag` references and DocC symbol links resolve unconditionally.
|
||||
///
|
||||
/// See <doc:Debugging> for the breakpoint recipes that key on this tag.
|
||||
public nonisolated(unsafe) var debugTag: String?
|
||||
|
||||
/// Default channel count — `1`. Multi-row generators MUST override.
|
||||
///
|
||||
/// See `Generator.outputChannelCount` for the contract. The default returns mono so
|
||||
|
||||
@@ -32,8 +32,11 @@ public enum DiskOut {
|
||||
/// disposes the file handle.
|
||||
///
|
||||
/// **Thread safety** (`@unchecked Sendable` — manually verified):
|
||||
/// - RT writes to `_ringBuffer[ch][(wHead + i) & _ringMask]`.
|
||||
/// BG reads from `_ringBuffer[ch][rHead & _ringMask]`.
|
||||
/// - The ring is raw storage (`_ringStorage`), not a Swift `[[Float]]`, so
|
||||
/// concurrent RT-write / BG-read access carries no shared array metadata to
|
||||
/// race on — only the sample slots, which the frame-counter fence orders.
|
||||
/// - RT writes to `_ringStorage[ch * _ringSize + ((wHead + i) & _ringMask)]`.
|
||||
/// BG reads from `_ringStorage[ch * _ringSize + (rHead & _ringMask)]`.
|
||||
/// The overflow guard (`used + count <= _ringSize`) ensures indices never alias.
|
||||
/// - `_framesWritten` is stored by RT with `.releasing`; BG loads with `.acquiring`.
|
||||
/// - `_framesRead` is stored by BG with `.releasing`; RT loads with `.acquiring`.
|
||||
@@ -71,7 +74,21 @@ public enum DiskOut {
|
||||
|
||||
// MARK: - Ring buffer (RT writes, BG reads)
|
||||
|
||||
private var _ringBuffer: [[Float]] // [channel][frame % _ringSize]
|
||||
/// Contiguous ring storage, channel-major: frame `pos` of channel `ch`
|
||||
/// lives at `_ringStorage[ch * _ringSize + pos]`.
|
||||
///
|
||||
/// RAW memory, deliberately **not** a Swift `[[Float]]`. The RT writer
|
||||
/// (`_computeSamples`) and the background drainer (`_drainAndWrite`) touch
|
||||
/// the ring concurrently — at disjoint frame ranges, fenced by the
|
||||
/// `_framesWritten` / `_framesRead` release-acquire pair. Swift `Array`
|
||||
/// access is **not** race-free under concurrency even at disjoint indices:
|
||||
/// the subscript (and any mutating use, e.g. `withUnsafeMutableBufferPointer`,
|
||||
/// which temporarily empties the array) reads/writes the array's shared
|
||||
/// storage pointer and CoW / refcount bookkeeping. That shared metadata —
|
||||
/// not the sample data — was the data race ThreadSanitizer flagged. Raw
|
||||
/// pointers carry no such metadata, so the frame-counter fence alone makes
|
||||
/// the handoff correct. Allocated in `init`, freed in `deinit`.
|
||||
private let _ringStorage: UnsafeMutableBufferPointer<Float>
|
||||
private let _ringSize: Int // == bufferFrames (power of two)
|
||||
private let _ringMask: Int // == _ringSize − 1
|
||||
|
||||
@@ -142,10 +159,9 @@ public enum DiskOut {
|
||||
self._ringSize = bufferFrames
|
||||
self._ringMask = bufferFrames - 1
|
||||
|
||||
_ringBuffer = Array(
|
||||
repeating: [Float](repeating: 0, count: bufferFrames),
|
||||
count: channelCount
|
||||
)
|
||||
let ringCapacity: Int = bufferFrames * channelCount
|
||||
_ringStorage = UnsafeMutableBufferPointer<Float>.allocate(capacity: ringCapacity)
|
||||
_ringStorage.initialize(repeating: 0)
|
||||
_interleavedWriteBuf = [Float](repeating: 0,
|
||||
count: bufferFrames * channelCount)
|
||||
|
||||
@@ -191,6 +207,11 @@ public enum DiskOut {
|
||||
&rawRef
|
||||
)
|
||||
guard createStatus == noErr, let rawRef: ExtAudioFileRef else {
|
||||
// These guards throw before `super.init()`, so `deinit` will not
|
||||
// run — free the raw ring storage explicitly or it leaks. (The
|
||||
// former `[[Float]]` ring was ARC-managed and torn down here for
|
||||
// free; raw memory is not.)
|
||||
_ringStorage.deallocate()
|
||||
throw DiskOutError.cannotCreateFile(createStatus)
|
||||
}
|
||||
_fileRef = rawRef
|
||||
@@ -218,6 +239,8 @@ public enum DiskOut {
|
||||
guard setFmtStatus == noErr else {
|
||||
ExtAudioFileDispose(rawRef)
|
||||
_fileRef = nil
|
||||
// Pre-`super.init()` throw — `deinit` won't run; free the ring.
|
||||
_ringStorage.deallocate()
|
||||
throw DiskOutError.cannotSetFormat(setFmtStatus)
|
||||
}
|
||||
|
||||
@@ -253,6 +276,11 @@ public enum DiskOut {
|
||||
// is not being accessed concurrently; direct disposal is safe.
|
||||
if let ref: ExtAudioFileRef = _fileRef { ExtAudioFileDispose(ref) }
|
||||
}
|
||||
// Free the raw ring storage. Safe here for the same reason the file
|
||||
// disposal is: the BG loop upgrades its `[weak self]` to a strong
|
||||
// reference for the whole iteration, so `deinit` cannot run while
|
||||
// `_drainAndWrite` is mid-read of the ring.
|
||||
_ringStorage.deallocate()
|
||||
}
|
||||
|
||||
// MARK: - Background internals
|
||||
@@ -292,7 +320,7 @@ public enum DiskOut {
|
||||
for f: Int in 0..<toWrite {
|
||||
let pos: Int = (rHead + totalDrained + f) & _ringMask
|
||||
for ch: Int in 0..<channelCount {
|
||||
_interleavedWriteBuf[f * channelCount + ch] = _ringBuffer[ch][pos]
|
||||
_interleavedWriteBuf[f * channelCount + ch] = _ringStorage[ch * _ringSize + pos]
|
||||
}
|
||||
}
|
||||
_interleavedWriteBuf.withUnsafeMutableBufferPointer { ptr in
|
||||
@@ -346,14 +374,17 @@ public enum DiskOut {
|
||||
|
||||
// Mono fast path — dominant case for streaming recorders. Single per-sample
|
||||
// loop fuses ring-buffer write with `_result` pass-through, both lifted to
|
||||
// raw pointers via `withUnsafe(Mutable)BufferPointer`. The input row enters
|
||||
// the closure tree only when present — no RT-path heap allocation in the
|
||||
// degenerate `inputChannels == 0` branch.
|
||||
// raw pointers. Channel 0 of the ring is `_ringStorage`'s base (offset 0);
|
||||
// the input row enters the closure tree only when present — no RT-path heap
|
||||
// allocation in the degenerate `inputChannels == 0` branch.
|
||||
if chCount == 1 {
|
||||
_ringBuffer[0].withUnsafeMutableBufferPointer { (rb: inout UnsafeMutableBufferPointer<Float>) in
|
||||
guard let rbP: UnsafeMutablePointer<Float> = rb.baseAddress else { return }
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
guard let rbP: UnsafeMutablePointer<Float> = _ringStorage.baseAddress else {
|
||||
for i: Int in 0..<count { _result[0][i] = 0 }
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
if inputChannels > 0 {
|
||||
inputSamples[0].withUnsafeBufferPointer { (src: UnsafeBufferPointer<Double>) in
|
||||
guard let p: UnsafePointer<Double> = src.baseAddress else {
|
||||
@@ -394,7 +425,6 @@ public enum DiskOut {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if canWrite {
|
||||
_framesWritten.store(wHead + count, ordering: .releasing)
|
||||
}
|
||||
@@ -412,7 +442,7 @@ public enum DiskOut {
|
||||
let pos: Int = (wHead + i) & mask
|
||||
for ch: Int in 0..<chCount {
|
||||
let v: Double = ch < inputChannels ? inputSamples[ch][i] : 0
|
||||
_ringBuffer[ch][pos] = Float(v)
|
||||
_ringStorage[ch * _ringSize + pos] = Float(v)
|
||||
_result[ch][i] = v
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
// 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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
# Debugging Synthesizers and Generators
|
||||
|
||||
Inspect live RT-thread state — output samples, inner-node values, per-sample
|
||||
compute — without breaking real-time safety.
|
||||
|
||||
## Overview
|
||||
|
||||
Two problems bring you here:
|
||||
|
||||
- **A Synthesizer subclass produces wrong or no output.** You want to see what a
|
||||
specific voice — often one instance out of a polyphonic pool — is actually
|
||||
emitting, and what its internal generators are doing.
|
||||
- **A new Generator's `_computeSamples` is off.** You want to step the compute
|
||||
loop for one instance and watch its state and output evolve.
|
||||
|
||||
Both run on the **RT render thread**, where the usual rules apply: no allocation,
|
||||
locks, `print`, or `String` construction (see <doc:SignalFlow> and the
|
||||
`SynthesisEngine` contract). A *breakpoint* is safe — it halts the thread and you
|
||||
inspect at leisure. Any *code* you add to a debug hook is not exempt from the RT
|
||||
rules. This article covers both: setting instance-scoped breakpoints, and reading
|
||||
state safely.
|
||||
|
||||
The tap's **invocation** is compiled out of release builds (the call site in
|
||||
`evaluate(graph:count:)` is wrapped in `#if DEBUG`), and it is gated per-instance, so
|
||||
nothing you add for debugging runs in shipping audio. The `debugTap` method and the
|
||||
`debugTapEnabled` flag still exist in release — an override compiles unconditionally — but
|
||||
the hook is simply never called there.
|
||||
|
||||
## The debug tap — a per-instance breakpoint
|
||||
|
||||
``SynthesizerBase/evaluate(graph:count:)`` is `final`, so you cannot hook it
|
||||
directly. Instead override ``SynthesizerBase/debugTap(graph:count:outputs:)`` — an
|
||||
`open` no-op the engine calls once per scheduling segment, **after** every output
|
||||
generator has run, but only when ``SynthesizerBase/debugTapEnabled`` is set on that
|
||||
instance.
|
||||
|
||||
```swift
|
||||
final class FMTone: SynthesizerBase {
|
||||
@LiveParam var carrierFreq: Double = 440.0
|
||||
|
||||
override func build() {
|
||||
let mod: any Generator = OscSin.Audio(freq: 220.0) * 660.0
|
||||
output(bus: 0, source: OscSin.Audio(freq: $carrierFreq + mod) * 0.18)
|
||||
}
|
||||
|
||||
override func debugTap(
|
||||
graph: SynthGraph,
|
||||
count: Int,
|
||||
outputs: [any Generator]
|
||||
) {
|
||||
// Breakpoint here. The RT thread halts with self, outputs, and graph
|
||||
// in scope:
|
||||
// po self.carrierFreq
|
||||
// po outputs.first?._cachedResult // Out's samples this block
|
||||
// po outputs.first?._result[0].prefix(8) // first 8 samples
|
||||
let block: Int = count
|
||||
_ = block
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Enable it per instance — flip only the voice you want to inspect:
|
||||
|
||||
```swift
|
||||
let voice: FMTone = FMTone()
|
||||
#if DEBUG
|
||||
voice.debugTapEnabled = true // main thread, before add — only this voice taps
|
||||
#endif
|
||||
try engine.add(voice)
|
||||
```
|
||||
|
||||
In a polyphonic pool, gate the flag so a single note breaks:
|
||||
|
||||
```swift
|
||||
for note: Int in chord {
|
||||
let v: FMTone = FMTone()
|
||||
v.debugTapEnabled = (note == 60) // break only middle C
|
||||
try engine.add(v)
|
||||
}
|
||||
```
|
||||
|
||||
### What is in scope when it halts
|
||||
|
||||
| In scope | Holds |
|
||||
|---|---|
|
||||
| `self` | Every `let` / `@LiveParam` on the voice. |
|
||||
| `outputs` | This instance's registered output-generator tree (roots only — typically `Out` / `ReplaceOut`). Each generator's `_cachedResult` / `_result` = samples just computed for this block. |
|
||||
| `graph.engine` | Sample rate, block size, bus pool — read a bus mid-render. |
|
||||
| `count` | Samples in this **scheduling segment** (`≤ 512`). The engine splits an audio block at sample-accurate scheduled-event boundaries, so a block containing scheduled events fires the tap once per segment — `count` is the segment length, not necessarily the full block. |
|
||||
|
||||
## Inspecting inner nodes
|
||||
|
||||
`outputs` gives you the **roots** only. Every generator stores its inputs
|
||||
`private` (`BinaryOpGenerator.lhs` / `rhs`, oscillator freq inputs, …), so you
|
||||
**cannot walk the tree down** to an interior node like the `mod` above from
|
||||
outside. To inspect an inner node, keep a reference to it in `build()`:
|
||||
|
||||
```swift
|
||||
final class FMTone: SynthesizerBase {
|
||||
@LiveParam var carrierFreq: Double = 440.0
|
||||
#if DEBUG
|
||||
// nonisolated(unsafe): written in build() on main before the add barrier,
|
||||
// read on the RT thread in debugTap — same happens-before as outputGenerators.
|
||||
private nonisolated(unsafe) var _dbgMod: (any Generator)?
|
||||
#endif
|
||||
|
||||
override func build() {
|
||||
let mod: any Generator = OscSin.Audio(freq: 220.0) * 660.0
|
||||
output(bus: 0, source: OscSin.Audio(freq: $carrierFreq + mod) * 0.18)
|
||||
#if DEBUG
|
||||
_dbgMod = mod
|
||||
(mod as? GeneratorBase)?.debugTag = "mod"
|
||||
#endif
|
||||
}
|
||||
|
||||
override func debugTap(
|
||||
graph: SynthGraph,
|
||||
count: Int,
|
||||
outputs: [any Generator]
|
||||
) {
|
||||
#if DEBUG
|
||||
let modOut: [Double]? = _dbgMod?._cachedResult.first
|
||||
_ = modOut // po modOut?.prefix(8) — mod's samples this block
|
||||
#endif
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `_cachedResult` vs `_result`, and why the read is free
|
||||
|
||||
The tap fires **after** the generator loop, so `mod` has already run this block —
|
||||
the fan-out cache (see <doc:GeneratorProtocol>) holds its output. Reading
|
||||
`_dbgMod?._cachedResult` is a post-hoc read of that cache; it does **not**
|
||||
recompute. Calling `_dbgMod?.calculatedSamples(graph:count:)` again would also just
|
||||
return the cache (same `_segmentSerial`), so it will not re-enter the compute loop
|
||||
either. For a mono generator `_cachedResult[0]` shares backing storage with
|
||||
`_result[0]` — either is fine to read.
|
||||
|
||||
### `debugTag` for identifying an instance
|
||||
|
||||
``GeneratorBase/debugTag`` (DEBUG-only) is a human-readable label you set in
|
||||
`build()` so a debugger can recognise one specific instance among many that share
|
||||
the same class. It is never read by framework code on the RT thread — it exists
|
||||
purely for LLDB conditions and hand-written taps, as shown next.
|
||||
|
||||
## Stepping into a Generator's compute loop
|
||||
|
||||
The tap is post-hoc: it shows results, not the live per-sample computation. To step
|
||||
the actual loop for one instance, breakpoint the generator's own
|
||||
`_computeSamples` (see <doc:WritingGenerators>) and **scope it to your instance** —
|
||||
otherwise you stop on every oscillator/multiply in the program.
|
||||
|
||||
Using `debugTag`:
|
||||
|
||||
```
|
||||
(lldb) b BinaryOpGenerator._computeSamples
|
||||
(lldb) breakpoint modify -c 'self.debugTag == "mod"'
|
||||
```
|
||||
|
||||
Or, if you did not set a tag, capture identity from the tap and match on the
|
||||
pointer:
|
||||
|
||||
```
|
||||
(lldb) p _dbgMod! // hit the tap first
|
||||
(lldb) breakpoint modify -c 'ObjectIdentifier(self) == ObjectIdentifier(<ref>)'
|
||||
```
|
||||
|
||||
Continue — you now step the multiply loop for that one `mod`, sample by sample. To
|
||||
step into the modulator oscillator instead, hold and tag *it* too (`let modOsc =
|
||||
OscSin.Audio(...)`; `modOsc.debugTag = "modOsc"`) and breakpoint
|
||||
`OscSin.Audio._computeSamples` with the same condition.
|
||||
|
||||
> Note: `_computeSamples` may run several times per audio block in sub-block mode
|
||||
> (`ControlGenerator`) — `count` is the sub-block length, not the full block. See
|
||||
> <doc:WritingGenerators> for when the sub-block loop runs.
|
||||
|
||||
## RT rules while debugging
|
||||
|
||||
- A **breakpoint** anywhere on the RT thread is fine — it stops everything and you
|
||||
look. This is the primary technique.
|
||||
- **Code** inside ``SynthesizerBase/debugTap(graph:count:outputs:)`` (or any RT
|
||||
path) still obeys the RT rules: no allocation, locks, `print`, or `String`
|
||||
construction. Reading a pre-computed buffer and comparing numbers is fine;
|
||||
formatting a log line is not.
|
||||
- Want **continuous** inspection without halting? Snapshot the values you care
|
||||
about into a **pre-allocated** ring buffer inside the tap, and drain/format them
|
||||
on the main thread. This is exactly how `NodeTreeMirror` publishes RT state to
|
||||
the UI — see <doc:DiagnosticsGuide>.
|
||||
|
||||
## When to reach for other tools
|
||||
|
||||
| Symptom | Tool |
|
||||
|---|---|
|
||||
| Need user-visible runtime messages, or a live node-tree view | <doc:DiagnosticsGuide> (`LyrebirdMessage`, `NodeTreeMirror`) |
|
||||
| Want to inspect a whole signal offline, sample by sample | <doc:NRTGuide> — render to a buffer/file and analyse the samples |
|
||||
| Verifying scheduling / timing | <doc:Scheduling> |
|
||||
| A new Generator is structurally wrong (not just numerically) | <doc:WritingGenerators> testing checklist |
|
||||
|
||||
## Topics
|
||||
|
||||
### Related
|
||||
|
||||
- <doc:SynthesizerProtocol>
|
||||
- <doc:GeneratorProtocol>
|
||||
- <doc:WritingGenerators>
|
||||
- <doc:DiagnosticsGuide>
|
||||
@@ -22,6 +22,10 @@ you need to react to RT lifecycle events from the UI, the existing
|
||||
``SynthesisEngineListener`` hook is the only fan-out the engine exposes
|
||||
today.
|
||||
|
||||
> Note: This guide covers user-visible runtime surfaces. For **developer-side**
|
||||
> inspection — breakpointing a specific voice on the RT thread, reading a
|
||||
> generator's live output and inner state — see <doc:Debugging>.
|
||||
|
||||
---
|
||||
|
||||
## Part 1 — `LyrebirdMessage`
|
||||
|
||||
@@ -179,6 +179,10 @@ addOutputGenerator(outR)
|
||||
Implement `_computeSamples` in your generators, not `calculatedSamples`. The cache is managed
|
||||
automatically. See <doc:WritingGenerators> for the full pattern.
|
||||
|
||||
> Tip: Because the cache holds a generator's last output for the current segment, you can
|
||||
> read an inner node's samples post-block from a Synthesizer debug tap without recomputing.
|
||||
> See <doc:Debugging>.
|
||||
|
||||
## Pre-Allocated Output Buffer Pattern
|
||||
|
||||
Every generator pre-allocates `_result` to `lyrebirdDefaultResultBufferSize` (512) samples in
|
||||
|
||||
@@ -215,6 +215,16 @@ let speakers = zip(speakerAzDeg.degreesToRadians(), [0.0, 0.0, 0.0, 0.0])
|
||||
The `Pan2` / `PanN` / `PanXY` family takes normalised positions in `[-1, 1]`,
|
||||
not radians — those generators apply their own internal `× π/2` or `× π/4` scale.
|
||||
|
||||
## Custom multi-channel DSP — `SampleLoop`
|
||||
|
||||
``SampleLoop`` — the closure escape hatch for custom per-sample DSP — is channel-aware on
|
||||
both ends. Its output channel count is inferred as `max` over its inputs' `outputChannelCount`
|
||||
(or set explicitly via `channels:`), each input is broadcast up to that width (mono spreads;
|
||||
a channel count that is neither `1` nor the output width `precondition`-traps, matching
|
||||
``BinaryOpGenerator``), and the body receives `numChannels` so one width-agnostic loop covers
|
||||
mono, stereo, or N-channel signals. Per-channel feedback state is sized from `numChannels` via
|
||||
its `makeState` argument. See ``SampleLoop`` for the full contract.
|
||||
|
||||
## See Also
|
||||
|
||||
- <doc:BusSystem>
|
||||
|
||||
@@ -6,6 +6,12 @@
|
||||
|
||||
A step-by-step guide to implementing correct, RT-safe generators in Lyrebird.
|
||||
|
||||
> Before you write a whole type: for one-off custom sample-accurate DSP — especially a
|
||||
> **single-sample feedback loop** (one-pole, waveguide, comb/allpass) — reach for
|
||||
> ``SampleLoop`` first. It gives you an RT-safe, allocation-free per-sample body with typed
|
||||
> feedback state and channel inference, no new `Generator` declaration. Promote to a full
|
||||
> generator (this guide) when you want parameters, Quick Help, reuse, and raw-pointer speed.
|
||||
|
||||
## 1. Protocol Choice — AudioGenerator vs ControlGenerator
|
||||
|
||||
| Criterion | Use `AudioGenerator` | Use `ControlGenerator` |
|
||||
@@ -497,3 +503,11 @@ override func build() {
|
||||
```
|
||||
|
||||
See <doc:MultiChannel> for the full multi-channel expansion guide.
|
||||
|
||||
## Debugging a New Generator
|
||||
|
||||
When a generator's `_computeSamples` produces the wrong numbers, you need to step
|
||||
its compute loop for one instance and watch its state. Tag the instance with
|
||||
``GeneratorBase/debugTag`` and set an LLDB conditional breakpoint on
|
||||
`_computeSamples`, or read its post-block output from a Synthesizer's debug tap.
|
||||
See <doc:Debugging> for the full workflow.
|
||||
|
||||
@@ -33,6 +33,7 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
|
||||
- <doc:WritingGenerators>
|
||||
- <doc:MultiChannel>
|
||||
- ``GeneratorEnum``
|
||||
- ``SampleLoop``
|
||||
|
||||
### Oscillators and Noise
|
||||
|
||||
@@ -173,6 +174,10 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
|
||||
- <doc:RoutineTask>
|
||||
- ``LyrebirdClock``
|
||||
|
||||
### Debugging Tools
|
||||
|
||||
- <doc:Debugging>
|
||||
|
||||
### Diagnostics
|
||||
|
||||
- <doc:DiagnosticsGuide>
|
||||
|
||||
@@ -72,6 +72,10 @@ class SineTone: SynthesizerBase {
|
||||
- `evaluate(graph:count:)` is `final` — the engine drives it automatically.
|
||||
- Do not override `evaluate` in subclasses; override `build` instead.
|
||||
|
||||
> Tip: To inspect a specific instance's output and inner state on the RT thread —
|
||||
> or to set a breakpoint on one voice out of a pool — override
|
||||
> ``SynthesizerBase/debugTap(graph:count:outputs:)``. See <doc:Debugging>.
|
||||
|
||||
## Parameters
|
||||
|
||||
Declare live parameters as `@LiveParam` (or `@UIParam` for SwiftUI binding) properties on
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// ClosureSynthesizer.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// A `SynthesizerBase` whose signal graph is supplied by a closure instead of a
|
||||
// `build()` override. The escape hatch for "just play this generator graph"
|
||||
// without declaring a named `Synthesizer` subclass — the fastest path from a
|
||||
// bare graph to audible sound (scratchpads, demos, tests, one-off voices).
|
||||
|
||||
/// A `SynthesizerBase` that builds its output graph from a closure.
|
||||
///
|
||||
/// Skips the usual "declare a subclass, override `build()`" ceremony when all
|
||||
/// you want is to hear a generator graph:
|
||||
///
|
||||
/// ```swift
|
||||
/// try engine.add(ClosureSynthesizer { OscSin.Audio(freq: 440, mul: 0.1) })
|
||||
/// try engine.add(ClosureSynthesizer(bus: 0) { Pan2(input: saw, pan: 0) })
|
||||
/// ```
|
||||
///
|
||||
/// The closure runs inside ``build()`` — once, on the main thread, when the
|
||||
/// synthesizer is added to an engine. Each instance is its own graph, so
|
||||
/// **construct the generators inside the closure** rather than handing it
|
||||
/// generator instances shared with another synthesizer (the same
|
||||
/// graph-copy-per-instance rule that applies to any `SynthesizerBase`).
|
||||
///
|
||||
/// A multi-channel source (e.g. a `Pan2`) fans out across consecutive buses
|
||||
/// starting at `bus`, exactly as ``SynthesizerBase/output(bus:source:)`` does.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: The output bus the graph is written to. A multi-channel source
|
||||
/// continues into the following buses. Defaults to `0`.
|
||||
/// - make: Builds and returns the output graph. Called once per instance,
|
||||
/// inside `build()`.
|
||||
public final class ClosureSynthesizer: SynthesizerBase {
|
||||
|
||||
private let outputBus: any ValidBus
|
||||
private let make: () -> any ValidGeneratorInput
|
||||
|
||||
/// - Parameters:
|
||||
/// - bus: The output bus the graph is written to. A multi-channel source
|
||||
/// continues into the following buses. Defaults to `0`.
|
||||
/// - make: Builds and returns the output graph. Called once per instance,
|
||||
/// inside `build()`. Construct the generators inside the closure.
|
||||
public init(
|
||||
bus: any ValidBus = 0,
|
||||
_ make: @escaping () -> any ValidGeneratorInput
|
||||
) {
|
||||
self.outputBus = bus
|
||||
self.make = make
|
||||
super.init()
|
||||
}
|
||||
|
||||
public override func build() {
|
||||
output(bus: outputBus, source: make())
|
||||
}
|
||||
}
|
||||
@@ -433,8 +433,69 @@ open class SynthesizerBase: Synthesizer {
|
||||
for generator: any Generator in outputGenerators {
|
||||
_ = generator.calculatedSamples(graph: localGraph, count: count)
|
||||
}
|
||||
#if DEBUG
|
||||
if debugTapEnabled {
|
||||
debugTap(graph: localGraph, count: count, outputs: outputGenerators)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Debug tap (RT thread)
|
||||
|
||||
/// Lock-free backing store for ``debugTapEnabled``.
|
||||
private nonisolated let _debugTapEnabled: Atomic<Bool> = Atomic<Bool>(false)
|
||||
|
||||
/// Enable the per-instance debug tap.
|
||||
///
|
||||
/// Set from the main thread — typically right after constructing the voice, though it is
|
||||
/// safe to toggle on an already-added, already-playing instance too. The RT thread reads
|
||||
/// it as a single relaxed atomic load per scheduling segment. Off by default — only the
|
||||
/// instances you flip pay for ``debugTap(graph:count:outputs:)``.
|
||||
///
|
||||
/// Backed by an `Atomic<Bool>` so the main-thread write and the RT-thread read never race:
|
||||
/// a plain `Bool` toggled on an already-running voice would be an unsynchronised access.
|
||||
/// The `Atomic` load also carries no data-race hazard for a flag flipped mid-render — a
|
||||
/// stale read only mis-fires (or mis-skips) the no-op default hook for one segment.
|
||||
///
|
||||
/// - Note: The tap's *invocation* is compiled out of release builds (`#if DEBUG` around the
|
||||
/// call site in ``evaluate(graph:count:)``). This property and ``debugTap(graph:count:outputs:)``
|
||||
/// still exist in release so an override compiles unconditionally, but in a release build
|
||||
/// the hook is never called regardless of this flag.
|
||||
public nonisolated var debugTapEnabled: Bool {
|
||||
get { _debugTapEnabled.load(ordering: .relaxed) }
|
||||
set { _debugTapEnabled.store(newValue, ordering: .relaxed) }
|
||||
}
|
||||
|
||||
/// Debug hook fired once per scheduling segment, after every output generator has run.
|
||||
///
|
||||
/// Default is a no-op. Override in a subclass to inspect the live signal graph
|
||||
/// mid-render — the canonical place to set a breakpoint on a specific instance.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - graph: The `SynthGraph` used for this segment. Reaches `graph.engine`
|
||||
/// (sample rate, block size) and the bus pool.
|
||||
/// - count: Samples in this segment. `≤ 512`. The engine splits an audio block into
|
||||
/// separate scheduling segments at sample-accurate scheduled-event boundaries, so a
|
||||
/// block that contains scheduled events fires this hook once per segment — `count` is
|
||||
/// the segment length, not necessarily the full block size.
|
||||
/// - outputs: This instance's registered output-generator tree. Each generator's
|
||||
/// `_cachedResult` / `_result` holds the samples just computed for this block.
|
||||
/// - Warning: Runs on the RT render thread. A breakpoint here is fine — it halts
|
||||
/// the thread with `self`, `outputs`, and `graph` in scope. Any *code* you add
|
||||
/// obeys the RT rules: no allocation, locks, `print`, or `String` construction.
|
||||
/// For continuous inspection without halting, snapshot into a pre-allocated
|
||||
/// ring and drain it on the main thread instead.
|
||||
/// - Note: Invoked only in `#if DEBUG` builds — the call site in ``evaluate(graph:count:)``
|
||||
/// is compiled out of release. An override still compiles in release; it simply never runs.
|
||||
///
|
||||
/// See <doc:Debugging> for the full workflow, including inspecting inner nodes
|
||||
/// and stepping a generator's compute loop.
|
||||
nonisolated open func debugTap(
|
||||
graph: SynthGraph,
|
||||
count: Int,
|
||||
outputs: [any Generator]
|
||||
) {}
|
||||
|
||||
// MARK: - Bus / Input-Output convenience helpers
|
||||
|
||||
/// Create an `Out` generator for the given audio bus and register it as an output.
|
||||
|
||||
Reference in New Issue
Block a user