Files
Lyrebird/Sources/Lyrebird/Generators/BufferIO/RecordBuffer.swift
T
josh f8878324fd v2.1.1 release: delay-click fix + internal consolidation
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>
2026-10-07 21:20:49 -07:00

637 lines
32 KiB
Swift

// RecordBuffer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Synchronization
/// Table of record-buffer generators with audio-rate and control-rate variants.
///
/// `RecordBuffer.Audio` writes one buffer frame per sample (audio rate) and passes the input
/// signal through as audio output. `RecordBuffer.Control` writes one buffer frame per block
/// (control rate) and produces a linear-ramp passthrough output.
///
/// ## Multi-channel (Audio variant only)
///
/// For a stereo buffer (`channelCount == 2`) supply a two-channel source — typically a
/// `GeneratorArray` from `expand(...)` or `Pan2`. Control variant requires mono.
///
/// ## Auto-registration
///
/// Both variants conform to ``RootRegistering``. Constructed inside ``SynthesizerBase/build()``
/// they auto-register as synth roots — no ``SynthesizerBase/addOutputGenerator(_:)`` or
/// ``SynthesizerBase/output(bus:source:)`` call is required and the return value may be
/// discarded (`let _ = RecordBuffer.Audio(...)`). The passthrough output remains available
/// for callers who still want to wire the recorder inline.
///
/// ## RT-safety
///
/// Both variants write to `LyrebirdBuffer` storage from the RT audio thread. The buffer is
/// **not safe for concurrent non-RT reads** while recording is active. Finish recording
/// (set `run = 0` or wait for `needsFree`) before reading the buffer on another thread.
///
/// ## Usage
///
/// ```swift
/// // Audio-rate: record stereo mic input
/// final class Looper: SynthesizerBase {
/// let buf = LyrebirdBuffer(count: 44100, channelCount: 2)
/// lazy var recorder = RecordBuffer.Audio(input: expand([osc, osc]) { $0 }, buffer: buf)
/// override func build() { output(bus: 0, source: recorder) }
/// }
/// looper.recorder.run = 0.0 // pause recording
///
/// // Control-rate: record an LFO automation curve
/// let automationBuf = LyrebirdBuffer(count: 1000)
/// let lfo = OscSin.Control(freq: 0.5)
/// let recorder = RecordBuffer.Control(input: lfo, buffer: automationBuf, loop: false)
/// ```
public enum RecordBuffer {
// MARK: - Shared base
/// Shared fields and initialisation for both rate variants.
/// Not for direct use — instantiate `RecordBuffer.Audio` or `RecordBuffer.Control`.
public class _Base: GeneratorBase {
// MARK: - Parameters
/// Recording gate: > 0 = recording, ≤ 0 = paused (write head holds position).
@LiveParam public var run: Double = 1.0
/// Scale applied to incoming signal before writing. `1.0` = full level.
@LiveParam public var recLevel: Double = 1.0
/// Scale applied to existing buffer content before mixing. `0.0` = overwrite,
/// `1.0` = full mix with existing content.
@LiveParam public var preLevel: Double = 0.0
// MARK: - Configuration
/// The target buffer. Frames are written in order starting at frame 0.
public let buffer: LyrebirdBuffer
/// Action taken when the write head reaches the end of the buffer.
private let _doneAction: DoneAction
var doneAction: DoneAction { _doneAction }
let loop: Bool
let channelCount: Int
// MARK: - Input
let inputSource: any ValidGeneratorInput
let inputIsGenerator: Bool
// MARK: - State
var writePos: Int = 0
var _isDone: Bool = false
let _needsFree: Atomic<Bool> = Atomic(false)
/// Set by `requestReset()` on a non-RT thread, consumed once at the top of the
/// next `_computeSamples` call on the RT thread.
let _resetRequested: Atomic<Bool> = Atomic(false)
/// Block-rate snapshot of `writePos`, published once per audio block rather
/// than per sample to avoid extra atomic-store overhead in the hot per-sample
/// write loops. Updated at the end of every `_computeSamples` call.
let _writePosSnapshot: Atomic<Int> = Atomic(0)
/// Number of frames written to `buffer` so far, safe to read from a non-RT
/// thread.
///
/// `writePos` itself is a plain `var` mutated per-sample on the RT thread and
/// is not safe for concurrent non-RT reads. This snapshot is published once
/// per audio block (`.releasing` store at the end of `_computeSamples`) and
/// read here with an `.acquiring` load, so a caller can safely read "how many
/// frames were recorded" after stopping recording (e.g. setting `run = 0`) —
/// for example a looper pedal narrowing `buffer.loopLength` to the actually
/// recorded region once the take finishes.
public var recordedFrameCount: Int { _writePosSnapshot.load(ordering: .acquiring) }
/// `true` when `doneAction == .freeNode` and recording has completed.
///
/// Read from a non-RT context after `processBlock` returns and schedule
/// node removal via `engine.remove`.
var needsFree: Bool { _needsFree.load(ordering: .acquiring) }
// MARK: - Generator protocol
let _zeroFallback: [Double]
public override var outputChannelCount: Int { channelCount }
// MARK: - Init
init(
input: any ValidGeneratorInput,
buffer: LyrebirdBuffer,
loop: Bool,
doneAction: DoneAction
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
self.inputSource = resolvedInput
self.inputIsGenerator = resolvedInput is any Generator
self.buffer = buffer
self.loop = loop
self._doneAction = doneAction
self.channelCount = buffer.channelCount
self._zeroFallback = makeSampleBuffer()
super.init(channels: buffer.channelCount)
}
// MARK: - Shared
/// Requests that recording restart from frame 0 on the next processed block.
///
/// Safe to call from any non-RT thread at any time (e.g. a "reset" UI action on
/// a looper pedal). Sets an `Atomic<Bool>` flag consumed once at the top of the
/// next `_computeSamples` call — `writePos` is reset to `0`, `_isDone` cleared,
/// and any pending `.freeNode` completion (`needsFree`) is cleared so the same
/// instance can be reused for a fresh take. Because the flag is only checked at
/// block boundaries, the reset takes effect at the start of the next block, not
/// mid-block — acceptable for a user-triggered action.
///
/// Does **not** touch `buffer` contents or `buffer.loopLength`. Callers that want
/// a fully blank take should also call `buffer.clear()` and
/// `buffer.setLoopLength(buffer.count)` themselves before or after calling this.
public func requestReset() {
_resetRequested.store(true, ordering: .releasing)
}
/// Consumes a pending reset request, if any. Call once at the top of
/// `_computeSamples` before touching `writePos` / `_isDone`.
@inline(__always)
func _consumeResetIfRequested() {
let (exchanged, _): (Bool, Bool) = _resetRequested.compareExchange(
expected: true,
desired: false,
ordering: .acquiringAndReleasing
)
if exchanged {
writePos = 0
_isDone = false
_needsFree.store(false, ordering: .releasing)
}
}
func handleEndOfBuffer() {
_isDone = true
writePos = buffer.loopLength - 1
switch doneAction {
case .nothing:
break
case .loop:
_isDone = false
writePos = 0
case .freeNode:
_needsFree.store(true, ordering: .releasing)
}
}
}
// MARK: - Audio
/// Audio-rate record buffer — writes one buffer frame per sample.
///
/// Output channel count equals `buffer.channelCount`. The input signal is passed through
/// unchanged so `RecordBuffer.Audio` can be inserted inline in a signal chain.
///
/// Supports mono and multi-channel buffers. For a stereo buffer supply a two-channel
/// `GeneratorArray`; channel count mismatch is caught at `init` time.
///
/// - Parameters:
/// - input: Signal to record. Mono `Generator`, scalar literal, or
/// `GeneratorArray` matching `buffer.channelCount`. Mismatched
/// channel counts trap at `init`.
/// - buffer: Destination `LyrebirdBuffer`. Frames are written in order
/// starting at frame 0.
/// - loop: `true` wraps the write head at end-of-buffer; `false` fires
/// `doneAction` and stops recording. Default `true`.
/// - doneAction: Behaviour when the write head reaches the end of the
/// buffer (`loop == false`). Default `.nothing`.
public final class Audio: _Base, AudioGenerator, DoneActionWatchable, RootRegistering {
// MARK: - Public API forwarded from internal _Base
public override var doneAction: DoneAction { super.doneAction }
public override var needsFree: Bool { super.needsFree }
// MARK: - Fan-out cache (Generator protocol requirements)
/// - Parameters:
/// - input: Signal to record. For stereo, supply a `GeneratorArray` with 2 channels.
/// - buffer: Destination buffer. `channelCount` must match `input`'s channel count.
/// - loop: `true` (default) wraps write head at end-of-buffer. `false` fires `doneAction`.
/// - doneAction: Behaviour when write head reaches end (loop == false). Default `.nothing`.
public override init(
input: any ValidGeneratorInput,
buffer: LyrebirdBuffer,
loop: Bool = true,
doneAction: DoneAction = .nothing
) {
super.init(input: input, buffer: buffer, loop: loop, doneAction: doneAction)
// Channel-count validation caught here on the non-RT thread instead of
// at first-block precondition trap.
if inputIsGenerator, let gen: any Generator = inputSource as? any Generator {
precondition(
gen.outputChannelCount == buffer.channelCount,
"RecordBuffer.Audio channel mismatch: input has \(gen.outputChannelCount) "
+ "channel(s), buffer expects \(buffer.channelCount). Supply a GeneratorArray "
+ "with \(buffer.channelCount) channel(s) or create a single-channel buffer."
)
} else {
precondition(
buffer.channelCount == 1,
"RecordBuffer.Audio: scalar input cannot feed a \(buffer.channelCount)-channel buffer. "
+ "Supply a GeneratorArray with \(buffer.channelCount) channel(s) or use a mono buffer."
)
}
_registerAutoFreeIfNeeded(doneAction)
_registerAsRootIfBuilding()
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
_consumeResetIfRequested()
// Publish `writePos` once per block (not per sample) for non-RT readers —
// see `recordedFrameCount` doc-comment.
defer { _writePosSnapshot.store(writePos, ordering: .releasing) }
let runSamples: [Double] = $run.calculatedSamples(graph: graph, count: count).first
?? _zeroFallback
let recSamples: [Double] = $recLevel.calculatedSamples(graph: graph, count: count).first
?? _zeroFallback
let preSamples: [Double] = $preLevel.calculatedSamples(graph: graph, count: count).first
?? _zeroFallback
let chCount: Int = channelCount
let bufferIsLive: Bool = buffer.isValid
// Wrap/overrun bound is the caller-narrowed `loopLength` (defaults to `count`), for
// both `loop == true` (a looping overdub recorder re-writes exactly the recorded
// take instead of the full allocated buffer) and `loop == false` (the overrun pins
// `writePos` to `loopLength - 1` via `handleEndOfBuffer()`, consistent with this bound
// regardless of when the caller narrows `loopLength`).
let bufferCount: Int = buffer.loopLength
let canRecord: Bool = bufferIsLive && !_isDone
let localLoop: Bool = loop
// Block-constant fast-path detection. `run` / `recLevel` / `preLevel` are
// `@LiveParam`s. `ParameterNode` produces monotonic linear ramps from the
// previous block's endpoint to the current target value over one block,
// so first + last sample agreement implies the whole block is constant.
// (Non-monotonic mid-block excursions are not possible from `@LiveParam`
// smoothing; if a future ParameterNode variant emits non-monotonic ramps
// this fast-path detection would need a per-sample sweep.)
//
// Exact `==` on `preBlockZero` / `recBlockOne` survives because the user
// typically leaves the defaults (`recLevel = 1.0`, `preLevel = 0.0`).
// A one-time `recLevel = 1.0` set from a different value takes one
// smoothing block before this fast path engages — acceptable.
let runStable: Bool = runSamples[0] > 0.0 && runSamples[count - 1] > 0.0
let preBlockZero: Bool = preSamples[0] == 0.0 && preSamples[count - 1] == 0.0
let recBlockOne: Bool = recSamples[0] == 1.0 && recSamples[count - 1] == 1.0
// Raw mutable pointer to buffer storage — interleaved `[frame * chCount + ch]`.
// `RecordBuffer` is the sole writer for the duration of recording, so the
// exclusive-write contract of `_rawStorageMutable` is met. Bound once per block.
let bufferStorage: UnsafeMutablePointer<Double> = buffer._rawStorageMutable
// ----- Scalar (constant) input — mono only (validated at init).
if !inputIsGenerator {
let scalar: Double = inputSource.floatValue(graph: graph)
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
for i: Int in 0..<count { dstP[i] = scalar }
}
if canRecord {
runSamples.withUnsafeBufferPointer { (runBP: UnsafeBufferPointer<Double>) in
recSamples.withUnsafeBufferPointer { (recBP: UnsafeBufferPointer<Double>) in
preSamples.withUnsafeBufferPointer { (preBP: UnsafeBufferPointer<Double>) in
guard let runP: UnsafePointer<Double> = runBP.baseAddress,
let recP: UnsafePointer<Double> = recBP.baseAddress,
let preP: UnsafePointer<Double> = preBP.baseAddress else { return }
var wp: Int = writePos
var done: Bool = false
for i: Int in 0..<count {
if done { break }
if runStable || runP[i] > 0.0 {
bufferStorage[wp] =
recP[i] * scalar + preP[i] * bufferStorage[wp]
wp += 1
if wp >= bufferCount {
if localLoop {
wp = 0
} else {
handleEndOfBuffer()
wp = writePos
done = true
}
}
}
}
writePos = wp
}
}
}
}
return _result
}
// ----- Generator input. Channel count validated at init.
let inputChannels: [[Double]] = inputSource.calculatedSamples(graph: graph, count: count)
// ----- Mono specialization — dominant case. Fused fill+write loop.
if chCount == 1 {
inputChannels[0].withUnsafeBufferPointer { (srcBP: UnsafeBufferPointer<Double>) in
guard let srcP: UnsafePointer<Double> = srcBP.baseAddress else { return }
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
if !canRecord {
// Passthrough only — no recording.
for i: Int in 0..<count { dstP[i] = srcP[i] }
return
}
runSamples.withUnsafeBufferPointer { (runBP: UnsafeBufferPointer<Double>) in
recSamples.withUnsafeBufferPointer { (recBP: UnsafeBufferPointer<Double>) in
preSamples.withUnsafeBufferPointer { (preBP: UnsafeBufferPointer<Double>) in
guard let runP: UnsafePointer<Double> = runBP.baseAddress,
let recP: UnsafePointer<Double> = recBP.baseAddress,
let preP: UnsafePointer<Double> = preBP.baseAddress else { return }
var wp: Int = writePos
var done: Bool = false
if runStable && preBlockZero && recBlockOne {
// Hottest case (loop+continuous record, defaults):
// direct overwrite, single mul-free store.
for i: Int in 0..<count {
let s: Double = srcP[i]
dstP[i] = s
if !done {
bufferStorage[wp] = s
wp += 1
if wp >= bufferCount {
if localLoop {
wp = 0
} else {
handleEndOfBuffer()
wp = writePos
done = true
}
}
}
}
} else if runStable && preBlockZero {
// pre == 0 → no buffer read, single mul + store.
for i: Int in 0..<count {
let s: Double = srcP[i]
dstP[i] = s
if !done {
bufferStorage[wp] = recP[i] * s
wp += 1
if wp >= bufferCount {
if localLoop {
wp = 0
} else {
handleEndOfBuffer()
wp = writePos
done = true
}
}
}
}
} else if runStable {
// Full mix, gate always on.
for i: Int in 0..<count {
let s: Double = srcP[i]
dstP[i] = s
if !done {
bufferStorage[wp] =
recP[i] * s + preP[i] * bufferStorage[wp]
wp += 1
if wp >= bufferCount {
if localLoop {
wp = 0
} else {
handleEndOfBuffer()
wp = writePos
done = true
}
}
}
}
} else {
// General: per-sample gate.
for i: Int in 0..<count {
let s: Double = srcP[i]
dstP[i] = s
if !done && runP[i] > 0.0 {
bufferStorage[wp] =
recP[i] * s + preP[i] * bufferStorage[wp]
wp += 1
if wp >= bufferCount {
if localLoop {
wp = 0
} else {
handleEndOfBuffer()
wp = writePos
done = true
}
}
}
}
}
writePos = wp
}
}
}
}
}
return _result
}
// ----- Multi-channel path. Fused fill+write, sample-outer / channel-inner.
// Single shared `writePos` across channels: per sample we advance once after
// writing all channels (interleaved storage layout `[wp * chCount + ch]`).
runSamples.withUnsafeBufferPointer { (runBP: UnsafeBufferPointer<Double>) in
recSamples.withUnsafeBufferPointer { (recBP: UnsafeBufferPointer<Double>) in
preSamples.withUnsafeBufferPointer { (preBP: UnsafeBufferPointer<Double>) in
guard let runP: UnsafePointer<Double> = runBP.baseAddress,
let recP: UnsafePointer<Double> = recBP.baseAddress,
let preP: UnsafePointer<Double> = preBP.baseAddress else { return }
var wp: Int = writePos
var done: Bool = !canRecord
for i: Int in 0..<count {
let gateOpen: Bool = !done && (runStable || runP[i] > 0.0)
let rec: Double = recP[i]
let pre: Double = preP[i]
if gateOpen {
let baseIdx: Int = wp * chCount
if preBlockZero && recBlockOne {
for ch: Int in 0..<chCount {
let s: Double = inputChannels[ch][i]
_result[ch][i] = s
bufferStorage[baseIdx + ch] = s
}
} else if preBlockZero {
for ch: Int in 0..<chCount {
let s: Double = inputChannels[ch][i]
_result[ch][i] = s
bufferStorage[baseIdx + ch] = rec * s
}
} else {
for ch: Int in 0..<chCount {
let s: Double = inputChannels[ch][i]
_result[ch][i] = s
let existing: Double = bufferStorage[baseIdx + ch]
bufferStorage[baseIdx + ch] = rec * s + pre * existing
}
}
wp += 1
if wp >= bufferCount {
if localLoop {
wp = 0
} else {
handleEndOfBuffer()
wp = writePos
done = true
}
}
} else {
// Gate closed — fill _result only.
for ch: Int in 0..<chCount {
_result[ch][i] = inputChannels[ch][i]
}
}
}
writePos = wp
}
}
}
return _result
}
}
// MARK: - Control
/// Control-rate record buffer — writes one buffer frame per block.
///
/// Use for recording automation data (LFO outputs, envelope followers, parameter curves)
/// at block rate. The output is a linear ramp from the previous block's value to the
/// current input value — identical to the `ControlGenerator` ramp convention.
///
/// Requires a **mono** buffer (`channelCount == 1`). For multi-channel recording use
/// `RecordBuffer.Audio`.
///
/// - Parameters:
/// - input: Control-rate signal source. Mono only; scalar literals are
/// block-constant.
/// - buffer: Mono destination `LyrebirdBuffer` (`channelCount == 1`).
/// - loop: `true` wraps the write head at end-of-buffer; `false` fires
/// `doneAction` and stops recording. Default `true`.
/// - doneAction: Behaviour when the write head reaches the end of the
/// buffer (`loop == false`). Default `.nothing`.
public final class Control: _Base, BlockRateControlGenerator, DoneActionWatchable, RootRegistering {
public var previousOutputValue: Double = 0.0
// MARK: - Public API forwarded from internal _Base
public override var doneAction: DoneAction { super.doneAction }
public override var needsFree: Bool { super.needsFree }
// MARK: - Fan-out cache (Generator protocol requirements)
/// - Parameters:
/// - input: Control-rate signal source. Mono only; scalar literals are block-constant.
/// - buffer: Mono destination buffer (`channelCount == 1`).
/// - loop: `true` (default) wraps write head at end-of-buffer. `false` fires `doneAction`.
/// - doneAction: Behaviour when write head reaches end (loop == false). Default `.nothing`.
public override init(
input: any ValidGeneratorInput,
buffer: LyrebirdBuffer,
loop: Bool = true,
doneAction: DoneAction = .nothing
) {
precondition(
buffer.channelCount == 1,
"RecordBuffer.Control requires a mono buffer (channelCount == 1); "
+ "got channelCount == \(buffer.channelCount). "
+ "For multi-channel recording use RecordBuffer.Audio."
)
super.init(input: input, buffer: buffer, loop: loop, doneAction: doneAction)
_registerAutoFreeIfNeeded(doneAction)
_registerAsRootIfBuilding()
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
_consumeResetIfRequested()
// Publish `writePos` once per block (not per sample) for non-RT readers —
// see `recordedFrameCount` doc-comment.
defer { _writePosSnapshot.store(writePos, ordering: .releasing) }
// Evaluate params: advance ParameterNode state; use settled (last-sample) value.
let runSamples: [Double] = $run.calculatedSamples(graph: graph, count: count).first
?? _zeroFallback
let recSamples: [Double] = $recLevel.calculatedSamples(graph: graph, count: count).first
?? _zeroFallback
let preSamples: [Double] = $preLevel.calculatedSamples(graph: graph, count: count).first
?? _zeroFallback
let runVal: Double = runSamples[count - 1]
let recVal: Double = recSamples[count - 1]
let preVal: Double = preSamples[count - 1]
// One input value per block (block-constant for scalars; last sample for generators).
let inputVal: Double
if inputIsGenerator {
let inSamples: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first
?? _zeroFallback
inputVal = inSamples[count - 1]
} else {
inputVal = inputSource.floatValue(graph: graph)
}
// Write one frame to the buffer if recording is active.
if buffer.isValid && !_isDone && runVal > 0 {
let existing: Double = buffer[writePos, 0]
buffer.write(recVal * inputVal + preVal * existing, frame: writePos, channel: 0)
writePos += 1
if writePos >= buffer.loopLength {
if loop { writePos = 0 }
else { handleEndOfBuffer() }
}
}
// Output: linear ramp from previous block value to current input value.
fillScalarRampedResult(
into: &_result,
previousOutputValue: &previousOutputValue,
target: inputVal,
count: count
)
return _result
}
}
}
extension RecordBuffer: GeneratorEnum {
public typealias AudioType = RecordBuffer.Audio
public typealias ControlType = RecordBuffer.Control
}
@available(*, deprecated, renamed: "RecordBuffer")
public typealias RecordBuf = RecordBuffer