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>
272 lines
12 KiB
Swift
272 lines
12 KiB
Swift
// BufferRead.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import Synchronization
|
||
|
||
/// Normalized-position random-access audio buffer reader.
|
||
///
|
||
/// `BufferRead` reads a `LyrebirdBuffer` at a caller-controlled normalized position each sample
|
||
/// (Audio) or each block (Control), with no internal looping or play-head advancement. Position
|
||
/// is entirely external — drive it with a `Phasor`, an LFO, a closure, or any `ValidGeneratorInput`.
|
||
///
|
||
/// ## Position semantics
|
||
///
|
||
/// `position` is a normalized `[0.0, 1.0]` value:
|
||
/// - `0.0` → first frame (frame 0)
|
||
/// - `1.0` → last frame (`buffer.count − 1`)
|
||
/// - Values outside `[0.0, 1.0]` are clamped before frame lookup.
|
||
///
|
||
/// ## Multi-channel output
|
||
///
|
||
/// Output channel count equals `buffer.channelCount`. Wire via `output(bus:source:)` to
|
||
/// write all channels, or extract individual channels inline using the `[n]` subscript.
|
||
///
|
||
/// ## Phasor integration
|
||
///
|
||
/// `LyrebirdBuffer.phasorFrequency` returns the frequency needed to sweep position 0→1
|
||
/// in exactly one buffer duration when `buffer.sampleRate` is set:
|
||
///
|
||
/// ```swift
|
||
/// let buf = try LyrebirdBuffer.loadAllChannels(url: url)
|
||
/// let reader = BufferRead.Audio(buffer: buf, position: Phasor.Audio(freq: buf.phasorFrequency ?? 1.0))
|
||
/// ```
|
||
public enum BufferRead {
|
||
|
||
// MARK: - Audio
|
||
|
||
/// Audio-rate buffer reader — computes one interpolated output per sample.
|
||
///
|
||
/// Position is sampled at audio rate; pass any audio-rate generator, LFO, or constant.
|
||
///
|
||
/// Supports live buffer swap via ``setBuffer(_:engine:)``. The output channel count
|
||
/// is fixed at init from the initial buffer's `channelCount` — any swapped-in buffer
|
||
/// must match.
|
||
///
|
||
/// - Parameters:
|
||
/// - buffer: Source buffer. Output channel count is fixed at init to
|
||
/// `buffer.channelCount`; any buffer later passed to
|
||
/// ``setBuffer(_:engine:)`` must match this channel count.
|
||
/// - position: Normalized read position `[0.0, 1.0]`. Clamped at compute time.
|
||
/// Accepts any `ValidGeneratorInput` — constant, generator, parameter key, closure.
|
||
/// - interpolation: Sample interpolation quality. Defaults to `.linear`.
|
||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||
/// - add: Offset added after multiplier. Defaults to `0.0`.
|
||
public final class Audio: GeneratorBase, AudioGenerator {
|
||
|
||
private let _slot: RTBufferSlot
|
||
private let _channelCount: Int
|
||
private let _position: any ValidGeneratorInput
|
||
private let _interpolation: TableInterpolation
|
||
private var _mulAdd: MulAddSpec
|
||
private let _zeroFallback: [Double]
|
||
|
||
public override var outputChannelCount: Int { _channelCount }
|
||
|
||
/// - Parameters:
|
||
/// - buffer: Source buffer. Output channel count is fixed at init to
|
||
/// `buffer.channelCount`; any buffer later passed to
|
||
/// ``setBuffer(_:engine:)`` must match this channel count.
|
||
/// - position: Normalized read position `[0.0, 1.0]`. Clamped at compute time.
|
||
/// Accepts any `ValidGeneratorInput` — constant, generator, parameter key, closure.
|
||
/// - interpolation: Sample interpolation quality. Defaults to `.linear`.
|
||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||
/// - add: Offset added after multiplier. Defaults to `0.0`.
|
||
public init(
|
||
buffer: LyrebirdBuffer,
|
||
position: any ValidGeneratorInput = 0.0,
|
||
interpolation: TableInterpolation = .linear,
|
||
mul: any ValidGeneratorInput = 1.0,
|
||
add: any ValidGeneratorInput = 0.0
|
||
) {
|
||
let resolvedPosition: any ValidGeneratorInput = position._resolvedInput()
|
||
_slot = RTBufferSlot(initial: buffer)
|
||
_channelCount = buffer.channelCount
|
||
_position = resolvedPosition
|
||
_interpolation = interpolation
|
||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||
_zeroFallback = makeSampleBuffer()
|
||
super.init(channels: buffer.channelCount)
|
||
}
|
||
|
||
/// Replace the buffer being read. Pass `nil` to silence the reader.
|
||
///
|
||
/// The new buffer's `channelCount` must equal the channel count this reader was
|
||
/// initialised with — output channel count is fixed at init. The previously
|
||
/// installed buffer's retain is routed through `engine.freeQueue` for off-RT
|
||
/// release. Must be called from a non-RT thread.
|
||
///
|
||
/// - Parameters:
|
||
/// - buffer: New buffer, or `nil` to silence.
|
||
/// - engine: Engine whose `freeQueue` receives the previous buffer's ref.
|
||
public func setBuffer(_ buffer: LyrebirdBuffer?, engine: SynthesisEngine) {
|
||
if let buffer: LyrebirdBuffer {
|
||
precondition(
|
||
buffer.channelCount == _channelCount,
|
||
"BufferRead.Audio.setBuffer: channelCount mismatch — reader is \(_channelCount), buffer is \(buffer.channelCount)"
|
||
)
|
||
}
|
||
_slot.swap(buffer, engine: engine)
|
||
}
|
||
|
||
public func _computeSamples(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
_checkCount(count)
|
||
|
||
guard let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid, buffer.count > 0 else {
|
||
for ch: Int in 0..<_channelCount {
|
||
for i: Int in 0..<count { _result[ch][i] = 0 }
|
||
}
|
||
return _result
|
||
}
|
||
|
||
let bufFrames: Int = buffer.count
|
||
let posSamples: [Double] = _position.calculatedSamples(graph: graph, count: count).first
|
||
?? _zeroFallback
|
||
let maxFrame: Double = Double(bufFrames - 1)
|
||
|
||
for i: Int in 0..<count {
|
||
let normPos: Double = max(0.0, min(1.0, posSamples[i]))
|
||
let frameF: Double = normPos * maxFrame
|
||
for ch: Int in 0..<_channelCount {
|
||
_result[ch][i] = lyrebirdBufferRead(
|
||
buffer, channel: ch, phase: frameF,
|
||
interpolation: _interpolation, loop: false
|
||
)
|
||
}
|
||
}
|
||
|
||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||
return _result
|
||
}
|
||
}
|
||
|
||
// MARK: - Control
|
||
|
||
/// Control-rate buffer reader — computes one interpolated output per audio block.
|
||
///
|
||
/// Position is sampled once per block; the output is a linear ramp from the previous
|
||
/// block's value to the current one, matching the `ControlGenerator` ramp convention.
|
||
/// Supports multi-channel buffers — each channel ramps independently.
|
||
///
|
||
/// Supports live buffer swap via ``setBuffer(_:engine:)``. The output channel count
|
||
/// is fixed at init from the initial buffer's `channelCount` — any swapped-in buffer
|
||
/// must match.
|
||
///
|
||
/// - Parameters:
|
||
/// - buffer: Source buffer. Output channel count is fixed at init to
|
||
/// `buffer.channelCount`; any buffer later passed to
|
||
/// ``setBuffer(_:engine:)`` must match this channel count.
|
||
/// - position: Normalized read position `[0.0, 1.0]`. Evaluated once per block.
|
||
/// Accepts any `ValidGeneratorInput` — constant, generator, parameter key, closure.
|
||
/// - interpolation: Sample interpolation quality. Defaults to `.linear`.
|
||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||
/// - add: Offset added after multiplier. Defaults to `0.0`.
|
||
public final class Control: GeneratorBase, BlockRateControlGenerator {
|
||
|
||
public var previousOutputValue: Double = 0.0
|
||
|
||
private let _slot: RTBufferSlot
|
||
private let _channelCount: Int
|
||
private let _position: any ValidGeneratorInput
|
||
private let _interpolation: TableInterpolation
|
||
private var _mulAdd: MulAddSpec
|
||
private var _rampTargets: [Double]
|
||
|
||
public override var outputChannelCount: Int { _channelCount }
|
||
|
||
/// - Parameters:
|
||
/// - buffer: Source buffer. Output channel count is fixed at init to
|
||
/// `buffer.channelCount`; any buffer later passed to
|
||
/// ``setBuffer(_:engine:)`` must match this channel count.
|
||
/// - position: Normalized read position `[0.0, 1.0]`. Evaluated once per block.
|
||
/// Accepts any `ValidGeneratorInput` — constant, generator, parameter key, closure.
|
||
/// - interpolation: Sample interpolation quality. Defaults to `.linear`.
|
||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||
/// - add: Offset added after multiplier. Defaults to `0.0`.
|
||
public init(
|
||
buffer: LyrebirdBuffer,
|
||
position: any ValidGeneratorInput = 0.0,
|
||
interpolation: TableInterpolation = .linear,
|
||
mul: any ValidGeneratorInput = 1.0,
|
||
add: any ValidGeneratorInput = 0.0
|
||
) {
|
||
let resolvedPosition: any ValidGeneratorInput = position._resolvedInput()
|
||
_slot = RTBufferSlot(initial: buffer)
|
||
_channelCount = buffer.channelCount
|
||
_position = resolvedPosition
|
||
_interpolation = interpolation
|
||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||
_rampTargets = [Double](repeating: 0, count: buffer.channelCount)
|
||
super.init(channels: buffer.channelCount)
|
||
}
|
||
|
||
/// Replace the buffer being read. Pass `nil` to silence the reader.
|
||
///
|
||
/// The new buffer's `channelCount` must equal the channel count this reader was
|
||
/// initialised with — output channel count is fixed at init. The previously
|
||
/// installed buffer's retain is routed through `engine.freeQueue` for off-RT
|
||
/// release. Must be called from a non-RT thread.
|
||
///
|
||
/// - Parameters:
|
||
/// - buffer: New buffer, or `nil` to silence.
|
||
/// - engine: Engine whose `freeQueue` receives the previous buffer's ref.
|
||
public func setBuffer(_ buffer: LyrebirdBuffer?, engine: SynthesisEngine) {
|
||
if let buffer: LyrebirdBuffer {
|
||
precondition(
|
||
buffer.channelCount == _channelCount,
|
||
"BufferRead.Control.setBuffer: channelCount mismatch — reader is \(_channelCount), buffer is \(buffer.channelCount)"
|
||
)
|
||
}
|
||
_slot.swap(buffer, engine: engine)
|
||
}
|
||
|
||
|
||
public func _computeSamples(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
_checkCount(count)
|
||
guard count > 0 else { return _result }
|
||
|
||
guard let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid, buffer.count > 0 else {
|
||
for ch: Int in 0..<_channelCount {
|
||
for i: Int in 0..<count { _result[ch][i] = 0 }
|
||
}
|
||
previousOutputValue = 0
|
||
return _result
|
||
}
|
||
|
||
let bufFrames: Int = buffer.count
|
||
let normPos: Double = max(0.0, min(1.0, _position.floatValue(graph: graph)))
|
||
let frameF: Double = normPos * Double(bufFrames - 1)
|
||
|
||
for ch: Int in 0..<_channelCount {
|
||
let target: Double = lyrebirdBufferRead(
|
||
buffer, channel: ch, phase: frameF,
|
||
interpolation: _interpolation, loop: false
|
||
)
|
||
let rampStart: Double = _rampTargets[ch]
|
||
let rampStep: Double = (target - rampStart) / Double(count)
|
||
_rampTargets[ch] = target
|
||
for i: Int in 0..<count {
|
||
_result[ch][i] = rampStart + rampStep * Double(i + 1)
|
||
}
|
||
}
|
||
|
||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||
previousOutputValue = _result[0][count - 1]
|
||
return _result
|
||
}
|
||
}
|
||
}
|
||
|
||
extension BufferRead: GeneratorEnum {
|
||
public typealias AudioType = BufferRead.Audio
|
||
public typealias ControlType = BufferRead.Control
|
||
}
|