// PlayBuffer.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Synchronization // MARK: - Buffer read helper /// Interpolated read from `buffer` at a fractional frame `phase` for one `channel`. /// /// - For `loop == true`: frames wrap modulo `buffer.loopLength` (seamless looping). /// `wrappedFrame` handles negative frame indices via `r += frameCount`, so backward /// reads across the loop point are correct. /// - For `loop == false`: frames are clamped to `[0, buffer.loopLength − 1]` (hold at ends). /// /// `buffer.loopLength` defaults to `buffer.count` (full-buffer looping) but may be /// narrowed at runtime — e.g. a looper pedal that recorded a take shorter than its /// max-duration buffer allocation — to bound wrap/clamp to just the recorded region. /// /// Used by `PlayBuffer.Audio` and `PlayBuffer.Control`; exposed as `internal` for reuse by /// future buffer-reading generators (e.g. `BufferGrain`). @inline(__always) internal func lyrebirdBufferRead( _ buffer: LyrebirdBuffer, channel: Int, phase: Double, interpolation: TableInterpolation, loop: Bool ) -> Double { let frameCount: Int = buffer.loopLength @inline(__always) func clampedFrame(_ f: Int) -> Int { max(0, min(f, frameCount - 1)) } @inline(__always) func wrappedFrame(_ f: Int) -> Int { var r: Int = f % frameCount if r < 0 { r += frameCount } return r } @inline(__always) func frame(_ f: Int) -> Double { let idx: Int = loop ? wrappedFrame(f) : clampedFrame(f) return buffer[idx, channel] } switch interpolation { case .none: return frame(Int(phase.rounded(.down))) case .linear: let intPhase: Int = Int(phase.rounded(.down)) let frac: Double = phase - Double(intPhase) let s0: Double = frame(intPhase) let s1: Double = frame(intPhase + 1) return s0 + frac * (s1 - s0) case .cubic: let intPhase: Int = Int(phase.rounded(.down)) let t: Double = phase - Double(intPhase) let pM1: Double = frame(intPhase - 1) let p0: Double = frame(intPhase) let p1: Double = frame(intPhase + 1) let p2: Double = frame(intPhase + 2) return catmullRomCubic(pM1, p0, p1, p2, t: t) } } // MARK: - PlayBuffer /// Table of playback generators with audio-rate and control-rate variants. /// /// `PlayBuffer.Audio` reads one buffer frame per sample (audio rate) with interpolation. /// `PlayBuffer.Control` reads one buffer frame per block (control rate) and produces a /// linear-ramp output — useful for playing back automation curves recorded by /// `RecordBuffer.Control`. /// /// ## Sample-rate compensation /// /// When playing a file loaded at a different sample rate than the engine, ask the /// buffer for the correcting `rate` multiplier: /// /// ```swift /// let buf = try LyrebirdBuffer.loadAllChannels(url: url) // buf.sampleRate set automatically /// /// final class SamplePlayer: SynthesizerBase { /// override func build() { /// let rateScale = buf.nativeRateScale(engineSampleRate: engine.sampleRate) /// let player = PlayBuffer.Audio(buffer: buf, loop: false, /// doneAction: .freeNode, rate: rateScale) /// output(bus: 0, source: player) /// } /// } /// ``` /// /// ## Generator-driven rate (varispeed / vibrato) /// /// Pass any `ValidGeneratorInput` as `rate:` to modulate playback speed sample-accurately: /// /// ```swift /// let lfo = OscSin.Audio(freq: 5.0, mul: 0.05, add: 1.0) // vibrato ±5% /// let player = PlayBuffer.Audio(buffer: buf, loop: true, rate: lfo) /// ``` /// /// ## 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: /// /// ```swift /// let player = PlayBuffer.Audio(buffer: stereoBuffer) /// output(bus: 0, source: player[0]) // left channel only /// output(bus: 2, source: player[1]) // right → bus 2 /// /// // Apply per-channel processing: /// let rev = SomeReverb(input: player[0]) /// output(bus: 0, source: player[0] * 0.7 + rev * 0.3) /// output(bus: 1, source: player[1]) /// ``` /// /// ## Trigger /// /// Pass any `ValidGeneratorInput` as `trigger:`. A 0 → positive edge resets the play head /// to frame 0. Pass an `Impulse.Audio` to retrigger sample-accurately: /// /// ```swift /// let imp = Impulse.Audio(freq: 2.0) // retrigger twice per second /// let player = PlayBuffer.Audio(buffer: oneShot, loop: false, trigger: imp) /// ``` public enum PlayBuffer { // MARK: - Shared base /// Shared fields and initialisation for both rate variants. /// Not for direct use — instantiate `PlayBuffer.Audio` or `PlayBuffer.Control`. public class _Base: GeneratorBase { // MARK: - Rate and trigger inputs /// Playback rate input. `1.0` = original speed, `-1.0` = reverse at original speed. let _rateInput: any ValidGeneratorInput /// `true` when `rate` was a `Generator` at init — never re-checked on the RT thread. let _rateIsGenerator: Bool /// Trigger input. A 0 → positive edge resets the play head to frame 0. let _triggerInput: any ValidGeneratorInput /// `true` when `trigger` was a `Generator` at init — never re-checked on the RT thread. let _triggerIsGenerator: Bool // MARK: - Configuration /// Atomic slot holding the source buffer. Supports live swap via /// ``setBuffer(_:engine:)``. RT path reads once per block. let _slot: RTBufferSlot /// Action taken when the play head reaches the end of the buffer (`loop == false` only). private let _doneAction: DoneAction var doneAction: DoneAction { _doneAction } let loop: Bool let interpolation: TableInterpolation let channelCount: Int // MARK: - State var _phase: Double var _prevTrigger: Double = 0.0 var _isDone: Bool = false let _needsFree: Atomic = Atomic(false) /// `true` when `doneAction == .freeNode` and playback has finished. /// /// 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 var _mulAdd: MulAddSpec public override var outputChannelCount: Int { channelCount } // MARK: - Init init( buffer: LyrebirdBuffer, loop: Bool, interpolation: TableInterpolation, doneAction: DoneAction, startPos: Double, rate: any ValidGeneratorInput = 1.0, trigger: any ValidGeneratorInput = 0.0, mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0 ) { precondition( startPos >= 0 && startPos < Double(buffer.count), "PlayBuffer startPos \(startPos) out of range [0, \(buffer.count))" ) let resolvedRate: any ValidGeneratorInput = rate._resolvedInput() let resolvedTrigger: any ValidGeneratorInput = trigger._resolvedInput() self._slot = RTBufferSlot(initial: buffer) self.loop = loop self.interpolation = interpolation self._doneAction = doneAction self.channelCount = buffer.channelCount self._phase = startPos self._rateInput = resolvedRate self._rateIsGenerator = resolvedRate is any Generator self._triggerInput = resolvedTrigger self._triggerIsGenerator = resolvedTrigger is any Generator self._mulAdd = MulAddSpec(mul: mul, add: add) super.init(channels: buffer.channelCount) } /// Replace the source buffer. Pass `nil` to silence the player. /// /// The new buffer's `channelCount` must equal the initial buffer's `channelCount` /// — output buffer shape is fixed at init. The new buffer's frame count may /// differ; phase wrapping uses the loaded buffer's `count` on each block. If /// `_phase` is out of range for the new (smaller) buffer, the next sample read /// is clamped or wrapped by ``lyrebirdBufferRead`` and the in-loop wrap logic /// brings `_phase` back into range. /// /// 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, "PlayBuffer.setBuffer: channelCount mismatch — player is \(channelCount), buffer is \(buffer.channelCount)" ) } _slot.swap(buffer, engine: engine) } // MARK: - Shared func handleEndOfBuffer( terminalPhase: Double, wrapPhase: Double ) { _isDone = true _phase = terminalPhase switch doneAction { case .nothing: break case .loop: _isDone = false _phase = wrapPhase case .freeNode: _needsFree.store(true, ordering: .releasing) } } } // MARK: - Audio /// Audio-rate playback — reads one buffer frame per sample with interpolation. /// /// Output channel count equals `buffer.channelCount`. Wire through `output(bus:source:)` /// — `Out` automatically fans multi-channel output to consecutive buses. /// /// - Parameters: /// - buffer: Source buffer. Output channel count equals `buffer.channelCount`. /// - loop: `true` (default) wraps play head at end-of-buffer. `false` fires `doneAction`. /// - interpolation: Sample interpolation quality. Defaults to `.linear`. /// - doneAction: Behaviour when playback ends (`loop == false`). Defaults to `.nothing`. /// - startPos: Initial phase (fractional frame index). Default `0.0`. Set to /// `Double(buffer.count - 1)` to start at the last frame for reverse playback. /// - rate: Playback rate multiplier. `1.0` = original speed, `2.0` = double speed, /// `-1.0` = reverse. Accepts any `ValidGeneratorInput` for generator-driven varispeed. /// Defaults to `1.0`. /// - trigger: Trigger input. A ≤0 → >0 edge resets the play head to frame 0 and /// clears the `_isDone` flag. Accepts any `ValidGeneratorInput` for sample-accurate /// triggering (e.g. `Impulse.Audio`). Defaults to `0.0` (no trigger). /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. public final class Audio: _Base, AudioGenerator, DoneActionWatchable { // MARK: - Public API forwarded from internal _Base public override var doneAction: DoneAction { super.doneAction } public override var needsFree: Bool { super.needsFree } /// - Parameters: /// - buffer: Source buffer. Output channel count equals `buffer.channelCount`. /// - loop: `true` (default) wraps play head at end-of-buffer. `false` fires `doneAction`. /// - interpolation: Sample interpolation quality. Defaults to `.linear`. /// - doneAction: Behaviour when playback ends (`loop == false`). Defaults to `.nothing`. /// - startPos: Initial phase (fractional frame index). Default `0.0`. Set to /// `Double(buffer.count - 1)` to start at the last frame for reverse playback. /// - rate: Playback rate multiplier. `1.0` = original speed, `2.0` = double speed, /// `-1.0` = reverse. Accepts any `ValidGeneratorInput` for generator-driven varispeed. /// Defaults to `1.0`. /// - trigger: Trigger input. A ≤0 → >0 edge resets the play head to frame 0 and /// clears the `_isDone` flag. Accepts any `ValidGeneratorInput` for sample-accurate /// triggering (e.g. `Impulse.Audio`). Defaults to `0.0` (no trigger). /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. public override init( buffer: LyrebirdBuffer, loop: Bool = true, interpolation: TableInterpolation = .linear, doneAction: DoneAction = .nothing, startPos: Double = 0.0, rate: any ValidGeneratorInput = 1.0, trigger: any ValidGeneratorInput = 0.0, mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0 ) { super.init( buffer: buffer, loop: loop, interpolation: interpolation, doneAction: doneAction, startPos: startPos, rate: rate, trigger: trigger, mul: mul, add: add ) _registerAutoFreeIfNeeded(doneAction) } public func _computeSamples( graph: SynthGraph, count: Int ) -> [[Double]] { _checkCount(count) // Evaluate rate input — generator path reads a full per-sample buffer; // scalar path computes one constant value and skips array allocation. let rateSamples: [Double]? let scalarRate: Double if _rateIsGenerator { rateSamples = _rateInput.calculatedSamples(graph: graph, count: count).first scalarRate = 0 } else { rateSamples = nil scalarRate = _rateInput.floatValue(graph: graph) } // Evaluate trigger input — same two-path pattern. let triggerSamples: [Double]? let scalarTrigger: Double if _triggerIsGenerator { triggerSamples = _triggerInput.calculatedSamples(graph: graph, count: count).first scalarTrigger = 0 } else { triggerSamples = nil scalarTrigger = _triggerInput.floatValue(graph: graph) } guard let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid else { for ch: Int in 0.. Double { rateSamples?[i] ?? scalarRate } @inline(__always) func triggerAt(_ i: Int) -> Double { triggerSamples?[i] ?? scalarTrigger } for i: Int in 0..0 resets play head. let trig: Double = triggerAt(i) if trig > 0 && _prevTrigger <= 0 { _phase = 0.0 _isDone = false } _prevTrigger = trig if _isDone { for ch: Int in 0..= bufferFrames { if loop { _phase = _phase.truncatingRemainder(dividingBy: bufferFrames) } else { handleEndOfBuffer(terminalPhase: bufferFrames - 1, wrapPhase: 0) } } else if _phase < 0 { if loop { _phase = _phase.truncatingRemainder(dividingBy: bufferFrames) if _phase < 0 { _phase += bufferFrames } } else { handleEndOfBuffer(terminalPhase: 0, wrapPhase: bufferFrames - 1) } } } _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) return _result } } // MARK: - Control /// Control-rate playback — advances phase once per block. /// /// Use for playing back control automation data recorded by `RecordBuffer.Control`. /// Output is a linear ramp from the previous block's buffer value to the current one, /// matching the `ControlGenerator` ramp convention. /// /// Requires a **mono** buffer (`channelCount == 1`). For multi-channel playback use /// `PlayBuffer.Audio`. /// /// - Parameters: /// - buffer: Mono source buffer (`channelCount == 1`). /// - loop: `true` (default) wraps play head at end-of-buffer. `false` fires `doneAction`. /// - interpolation: Sample interpolation quality. Defaults to `.linear`. /// - doneAction: Behaviour when playback ends (`loop == false`). Defaults to `.nothing`. /// - startPos: Initial phase (fractional frame index). Default `0.0`. Set to /// `Double(buffer.count - 1)` to start at the last frame for reverse playback. /// - rate: Playback rate multiplier. `1.0` = original speed, `2.0` = double speed, /// `-1.0` = reverse. Accepts any `ValidGeneratorInput`. Defaults to `1.0`. /// - trigger: Trigger input. A ≤0 → >0 edge (evaluated at block rate from the last /// sample) resets the play head to frame 0. Accepts any `ValidGeneratorInput`. /// Defaults to `0.0` (no trigger). /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. public final class Control: _Base, ControlGenerator, DoneActionWatchable { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 0.0 // MARK: - Public API forwarded from internal _Base public override var doneAction: DoneAction { super.doneAction } public override var needsFree: Bool { super.needsFree } /// - Parameters: /// - buffer: Mono source buffer (`channelCount == 1`). /// - loop: `true` (default) wraps play head at end-of-buffer. `false` fires `doneAction`. /// - interpolation: Sample interpolation quality. Defaults to `.linear`. /// - doneAction: Behaviour when playback ends (`loop == false`). Defaults to `.nothing`. /// - startPos: Initial phase (fractional frame index). Default `0.0`. Set to /// `Double(buffer.count - 1)` to start at the last frame for reverse playback. /// - rate: Playback rate multiplier. `1.0` = original speed, `2.0` = double speed, /// `-1.0` = reverse. Accepts any `ValidGeneratorInput`. Defaults to `1.0`. /// - trigger: Trigger input. A ≤0 → >0 edge (evaluated at block rate from the last /// sample) resets the play head to frame 0. Accepts any `ValidGeneratorInput`. /// Defaults to `0.0` (no trigger). /// - mul: Output multiplier applied after synthesis. Defaults to `1.0`. /// - add: Offset added after multiplier. Defaults to `0.0`. public override init( buffer: LyrebirdBuffer, loop: Bool = true, interpolation: TableInterpolation = .linear, doneAction: DoneAction = .nothing, startPos: Double = 0.0, rate: any ValidGeneratorInput = 1.0, trigger: any ValidGeneratorInput = 0.0, mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0 ) { precondition( buffer.channelCount == 1, "PlayBuffer.Control requires a mono buffer (channelCount == 1); " + "got channelCount == \(buffer.channelCount). " + "For multi-channel playback use PlayBuffer.Audio." ) super.init( buffer: buffer, loop: loop, interpolation: interpolation, doneAction: doneAction, startPos: startPos, rate: rate, trigger: trigger, mul: mul, add: add ) _setupSubBlockBuffer() _registerAutoFreeIfNeeded(doneAction) } // Bypass sub-block loop: PlayBuffer.Control advances _phase once per audio block. // Sub-blocking would advance it N times per block, running playback at N× speed. public func calculatedSamples( graph: SynthGraph, count: Int ) -> [[Double]] { _calculatedSamplesBlockRate(graph: graph, count: count) } public func _computeSamples( graph: SynthGraph, count: Int ) -> [[Double]] { _checkCount(count) guard count > 0 else { return _result } let rateVal: Double = lastGeneratorSampleOrFloat( _rateInput, isGenerator: _rateIsGenerator, graph: graph, count: count ) let triggerVal: Double = lastGeneratorSampleOrFloat( _triggerInput, isGenerator: _triggerIsGenerator, graph: graph, count: count ) // Trigger edge detection at block rate. if triggerVal > 0 && _prevTrigger <= 0 { _phase = 0.0 _isDone = false } _prevTrigger = triggerVal // Read one output value for this block. let outputVal: Double if let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid, !_isDone { let bufferFrames: Double = Double(buffer.loopLength) outputVal = lyrebirdBufferRead( buffer, channel: 0, phase: _phase, interpolation: interpolation, loop: loop ) _phase += rateVal if _phase >= bufferFrames { if loop { _phase = _phase.truncatingRemainder(dividingBy: bufferFrames) } else { handleEndOfBuffer(terminalPhase: bufferFrames - 1, wrapPhase: 0) } } else if _phase < 0 { if loop { _phase = _phase.truncatingRemainder(dividingBy: bufferFrames) if _phase < 0 { _phase += bufferFrames } } else { handleEndOfBuffer(terminalPhase: 0, wrapPhase: bufferFrames - 1) } } } else { outputVal = 0 } // Output: linear ramp from previous block value to current output value. let rampStart: Double = _rampTarget _rampTarget = outputVal previousOutputValue = fillRampedResult( into: &_result, from: rampStart, to: outputVal, mulAdd: _mulAdd, graph: graph, count: count) return _result } } } extension PlayBuffer: GeneratorEnum { public typealias AudioType = PlayBuffer.Audio public typealias ControlType = PlayBuffer.Control } @available(*, deprecated, renamed: "PlayBuffer") public typealias PlayBuf = PlayBuffer