Files
Lyrebird/Sources/Lyrebird/Buffers/LyrebirdBuffer.swift
T
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI,
REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable
WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux
live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive.
See RELEASES.md and LINUX_README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-10 21:09:11 -07:00

967 lines
46 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// LyrebirdBuffer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdDSP
import Foundation
import Synchronization
/// A pre-allocated, RT-safe memory buffer for audio data.
///
/// `LyrebirdBuffer` allocates raw memory on the calling (non-RT) thread and exposes a
/// handful of fill methods for populating standard waveforms and windows. Generators hold
/// a strong reference to a buffer and check `isValid` (acquiring load) at the top of each
/// `calculatedSamples` call. Calling `invalidate()` on a non-RT thread sets `isValid` to
/// `false` with a releasing store; the next block the RT thread sees the flag and outputs
/// silence.
///
/// The underlying memory is NOT freed by `invalidate()`. It stays allocated until this
/// object's `deinit` runs — which happens when the last strong reference (typically the
/// generator holding it) is released via ARC, always off the RT thread via
/// `SynthesisEngine.freeQueue`.
///
/// ## Multichannel layout
///
/// When `channelCount > 1`, samples are stored **interleaved**:
/// `[L0, R0, L1, R1, …, L(n-1), R(n-1)]`.
/// `count` is always the **frame count**; `totalSampleCount == count × channelCount` is
/// the number of `Double` values actually allocated.
///
/// Use `buffer[frame: i, channel: ch]` for named multi-channel access.
/// The single-argument subscript `buffer[index]` is a raw linear-offset read into the
/// storage array — for mono buffers this equals the frame index.
///
/// ## Wavetable use
///
/// `OscSin` and `OscTable` require mono (`channelCount == 1`) buffers and enforce this
/// with a `precondition` at init time. The fill methods (`fillSine`, `fillHanning`,
/// `fill(with:)`, `fill(using:)`) are likewise mono-only and will `precondition`-trap
/// if called on a multichannel buffer.
///
/// ## Lifecycle
///
/// 1. Create and fill on a non-RT thread (main thread or background queue).
/// 2. Pass to one or more generators. Each generator holds a strong reference.
/// 3. When done, call `invalidate()` on a non-RT thread.
/// 4. Remove the generators from the engine. When the last generator is freed via
/// `freeQueue`, ARC releases the buffer and `deinit` deallocates the pointer.
///
/// ## Memory management
///
/// Memory is freed in `deinit` by `_storage.deallocate()`. `invalidate()` does NOT
/// free memory — it only flips the RT-visible validity flag so RT readers output
/// silence. Memory is reclaimed when the last strong ARC reference goes away.
///
/// Two cases:
///
/// 1. **Buffer never wired to a generator** — your own reference is the only one.
/// Dropping it (e.g. `buffer = nil` or letting it leave scope) deinits the
/// buffer right there and deallocates the storage. `invalidate()` is not
/// required in this case.
///
/// 2. **Buffer wired to one or more generators in a running engine** — each
/// generator holds a strong reference. The correct teardown is:
///
/// ```swift
/// buffer.invalidate() // RT thread starts seeing isValid == false
/// // remove the generators from the engine (the node-tree removal routes
/// // their final release through SynthesisEngine.freeQueue, off the RT thread)
/// buffer = nil // drop your own reference last
/// ```
///
/// When the last generator is drained from `freeQueue`, ARC releases the
/// buffer on a non-RT thread and `deinit` calls `_storage.deallocate()` there.
///
/// **RT-thread deinit gotcha.** `_storage.deallocate()` is not RT-safe. If the
/// last strong reference is dropped on the RT thread, `deinit` runs on the RT
/// thread and the deallocate call violates the no-allocation rule. The
/// `freeQueue` pattern exists to prevent this — always remove generators via the
/// engine's node-tree API so their final release lands off the RT thread. Do
/// not retain a `LyrebirdBuffer` inside an RT-thread-owned closure or struct.
///
/// **Performance-end background write.** Dumping captured input buffers to
/// disk at the end of a performance is safe from a background `Task` when
/// the writers (RT-side `RecordBuffer.Audio` generators) are freed first so
/// no concurrent RT write races the disk read. ``LyrebirdEventList/onKillAll``
/// is the recommended hook — it fires synchronously on the main thread at
/// the top of ``LyrebirdEventList/killAll()`` so the caller can free the
/// input synths and launch the write before any teardown begins. The launched
/// task captures **strong refs** to the buffers, so `_storage` stays alive
/// even after ARC drops every other reference. The Process System article
/// ("Persisting Captured Input Buffers") documents the full pattern,
/// including the `Task<Void, Never>?` + next-session `await` gate that
/// prevents a transient 2× memory peak under rapid stop / start.
///
/// **Replacing a buffer on a running generator.** Most buffer-consuming
/// generators (`PlayBuffer`, `BufferRead`, `OscTable`, `BufferGrain`,
/// `TimeStretch`, `VectorOscillator`, `ResonatorBank.Audio`,
/// `SpectralBinDelay`, `SpectralMagnitudeMap`) hold their source via
/// ``RTBufferSlot`` and expose a `setBuffer(_:engine:)` (or `setTable(_:engine:)`
/// / `setWindow(_:engine:)` / `setDelayTimes(_:engine:)` / etc.) method.
/// Calling that setter with a new buffer or `nil` is the preferred way to
/// change what the generator reads — the previously installed buffer is
/// released by `engine.bufferSwapKillQueue` on a background thread, never on
/// the RT thread. `invalidate()` remains useful when you want to temporarily
/// silence consumers without releasing the buffer object.
///
/// ## Power-of-two sizes (wavetable use)
///
/// Use sizes that are powers of two (e.g. `lyrebirdDefaultTableSize = 32768`) when passing
/// a buffer to an oscillator. Power-of-two sizes allow bitmask wrapping in the inner loop
/// instead of integer modulo, which is measurably faster at audio rate.
///
/// ## Atomic ordering
///
/// `invalidate()` uses a `.releasing` store; `isValid` uses an `.acquiring` load.
/// `LyrebirdBuffer` is safe to share across threads:
/// - The validity flag is protected by `Atomic<Bool>`.
/// - `loopLength` is likewise an `Atomic<Int>` (`.acquiring` load / `.releasing` store
/// via ``setLoopLength(_:)``) — read every sample by `PlayBuffer`-family generators,
/// written once (non-RT) after e.g. a looper pedal finishes recording a take.
/// - `channelCount` and `count` are `let` constants — freely readable on any thread.
/// - Sample data can be written from the RT thread by `RecordBuffer` via the internal
/// `write(_:frame:channel:)` method. The buffer is **not safe for concurrent non-RT
/// reads while recording is active** — finish recording before reading on another thread.
/// Non-recording use (read-only from RT after `fill` on non-RT) remains safe.
///
/// ## Live language-side writes
///
/// `setValue(_:at:)`, `setValue(_:frame:channel:)`, `setRangeValues(_:startingAt:)`,
/// and `clear()` allow the language side to update samples while the RT thread is reading the buffer.
/// They are intended for **parameter / lookup-table buffers** that an RT generator
/// snapshots once per audio block (or once per FFT hop), not for long audio buffers
/// being scrubbed sample-by-sample mid-block.
///
/// Concurrent language-side callers are serialised by an internal `NSLock`; the RT
/// thread does NOT take that lock. Memory-model details:
///
/// - **Writer side:** the setter writes `_storage[i] = value` while holding the lock.
/// `NSLock.unlock()` on Darwin emits a release barrier, so all stores performed
/// inside the critical section are observable to other cores after `unlock` returns.
/// - **Reader side:** on arm64 and x86_64, an aligned 8-byte `Double` store is
/// observed atomically at the cache-line level — another core reads the cell as
/// either the old or the new value, never as a torn half-write. The RT thread does
/// not take the lock and does not perform an explicit acquire fence on the storage
/// read; partial-range visibility during a `setRangeValues` call (some elements
/// updated, some not) is **accepted** for the block-rate-snapshot use case.
/// - **Reader contract:** RT consumers should snapshot the buffer once at the top of
/// `_computeSamples` (typically `memcpy` into a pre-allocated scratch pointer) and
/// then process from the scratch buffer for the rest of the block.
///
/// Suggested use cases:
///
/// - **Per-bin spectral parameters** driven by a SwiftUI `MultiSlider` or a SC-style
/// multi-slider: `SpectralBinDelay` reading per-bin delay times and feedbacks from
/// two `LyrebirdBuffer`s, snapshotted at the top of each FFT hop.
/// - **Magnitude-transfer curves** for `SpectralMagnitudeMap` edited live by the user
/// (drawing into a transfer-function display).
/// - **MIDI-CC- or OSC-driven control surfaces** that publish a small parameter vector
/// at language rate where each value feeds an RT generator sampled once per block.
///
/// Use `fill(with:)` / `fill(using:)` only for the "set-once-before-use" case; they
/// assume no concurrent RT reader and trap on multichannel buffers.
public final class LyrebirdBuffer: @unchecked Sendable {
// MARK: - Storage
/// Raw sample storage. Allocated in `init`, deallocated in `deinit`.
/// Layout: interleaved — `[ch0_frame0, ch1_frame0, …, ch0_frame1, ch1_frame1, …]`.
private let _storage: UnsafeMutablePointer<Double>
/// Number of audio frames in this buffer.
///
/// For mono buffers this equals the total number of samples.
/// For multichannel buffers, total samples = `count × channelCount`.
public let count: Int
/// Number of channels stored in this buffer.
///
/// Always ≥ 1. Wavetable oscillators (`OscSin`, `OscTable`) require `channelCount == 1`.
public let channelCount: Int
/// Total number of `Double` values allocated: `count × channelCount`.
public var totalSampleCount: Int { count * channelCount }
/// Sample rate of the audio data stored in this buffer, in Hz.
///
/// Set automatically by `LyrebirdBuffer.load(url:)`, `loadAllChannels(url:)`, and
/// `fill(fromFile:)`. For manually-filled buffers, set explicitly via
/// ``setSampleRate(_:)`` before passing to `PlayBuffer.Audio` or `PlayBuffer.Control`
/// if sample-rate compensation is needed.
///
/// `nil` (default) means the rate is unknown. ``nativeRateScale(engineSampleRate:)``
/// returns `1.0` when this is `nil`.
///
/// > Note: Read-only externally. Mutated only at load time (file I/O) or via
/// > ``setSampleRate(_:)``, both of which take `_writeLock`. The RT thread reads
/// > this property without locking; setters are serialised so the property is not
/// > torn under concurrent language-side writers, and is expected to be initialised
/// > before any RT consumer reads it.
public private(set) var sampleRate: Double?
/// Set the buffer's `sampleRate`. Lock-protected against other language-side writers.
/// Call before passing the buffer to any RT consumer.
public func setSampleRate(_ rate: Double?) {
_writeLock.lock()
defer { _writeLock.unlock() }
sampleRate = rate
}
/// Duration of the buffer in seconds. `nil` when `sampleRate` is `nil`.
public var duration: Double? { sampleRate.map { Double(count) / $0 } }
/// Frequency to pass to `Phasor` to sweep position 0→1 in exactly one buffer duration.
/// `nil` when `sampleRate` is `nil`.
public var phasorFrequency: Double? { duration.map { 1.0 / $0 } }
/// Returns the playback-rate multiplier that compensates for a sample-rate mismatch
/// between this buffer and the engine.
///
/// Pass the result as the `rate:` parameter of any buffer-consuming generator
/// (`PlayBuffer`, granular family, future warp/scrubbers) so that a `44.1 kHz`
/// recording plays at original pitch on a `48 kHz` engine, and vice versa.
///
/// `sampleRate` is set automatically when loading from a file via
/// `LyrebirdBuffer.load(url:)` or `loadAllChannels(url:)`. For manually-filled
/// buffers, call ``setSampleRate(_:)`` before invoking this helper.
///
/// Returns `1.0` when `sampleRate` is `nil` (rate unknown — safest no-op).
///
/// Evaluate on the non-RT thread, typically inside `Synthesizer.build()`:
///
/// ```swift
/// let rateScale = buf.nativeRateScale(engineSampleRate: engine.sampleRate)
/// let player = PlayBuffer.Audio(buffer: buf, rate: rateScale)
/// ```
///
/// - Parameter engineSampleRate: The engine's sample rate in Hz.
/// - Returns: `buffer.sampleRate / engineSampleRate`, or `1.0` if unknown.
public func nativeRateScale(engineSampleRate: Double) -> Double {
guard let bufRate: Double = sampleRate else { return 1.0 }
return bufRate / engineSampleRate
}
/// Number of frames that `PlayBuffer`-family generators should wrap (looping) or
/// clamp (non-looping) against, distinct from `count` (the full allocated size).
///
/// Defaults to `count` at init, matching the historical full-buffer looping
/// behaviour. Narrow this after recording a take that is shorter than the
/// buffer's max-duration allocation — e.g. a looper pedal that pre-allocates
/// 60 seconds but records a shorter take — so playback wraps only over the
/// actually-recorded region without reallocating the buffer.
///
/// **RT contract.** Stored as an `Atomic<Int>` rather than behind `_writeLock`:
/// this value is read on every sample inside `PlayBuffer`'s per-sample read loop
/// (`lyrebirdBufferRead`), so a lock acquired every sample would be the wrong
/// tool. An atomic load costs nothing close to a lock and gives torn-free reads
/// of a single `Int`. Set from a non-RT thread via ``setLoopLength(_:)``, e.g.
/// once after recording stops.
private let _loopLength: Atomic<Int>
/// Current loop/clamp bound for `PlayBuffer`-family generators, in frames.
///
/// `1...count`, defaulting to `count`. Read with an `.acquiring` load — safe to
/// call from the RT thread inside a per-sample read loop.
public var loopLength: Int {
_loopLength.load(ordering: .acquiring)
}
/// Narrow (or restore) the frame count that `PlayBuffer`-family generators wrap
/// or clamp against.
///
/// Call from a non-RT thread — typically once, right after recording stops
/// (e.g. a looper pedal calling this with the frame count `RecordBuffer`
/// actually wrote, so playback loops over just the recorded take instead of
/// the full max-duration allocation).
///
/// - Parameter length: Desired loop length in frames. Clamped to `[1, count]`.
public func setLoopLength(_ length: Int) {
let clamped: Int = max(1, min(length, count))
_loopLength.store(clamped, ordering: .releasing)
}
/// Atomic validity flag. `true` after `init`, `false` after `invalidate()`.
private let _isValid: Atomic<Bool>
/// Serialises concurrent **language-side** writers of `setValue` / `setRangeValues`
/// / `invalidate`. The RT thread NEVER takes this lock — it reads `_storage`
/// directly. See the class-level "Live language-side writes" doc-comment for the
/// RT-thread contract.
private let _writeLock: NSLock = NSLock()
// MARK: - Engine binding (opt-in)
/// Maximum CAS passes in `bindExclusive`. See
/// `SynthesizerBase.bindMaxPasses` for the rationale.
private static let bindMaxPasses: Int = 2
/// Set-once atomic binding to an owning `SynthesisEngine` for the
/// exclusive-mutable tier. Stored as the `UInt` bit pattern
/// of an `UnsafeMutableRawPointer` to the bound engine; zero = unbound.
///
/// **Opt-in.** Existing buffer callers continue to share `LyrebirdBuffer`
/// instances freely across engines — the legacy unbound state is the
/// default and remains the common case. The binding API is for
/// power users who want to enforce one-engine-ownership at runtime.
///
/// The exclusive tier and the read-only tier are mutually exclusive:
/// `bindExclusive(to:)` fails if the buffer has any active read-only
/// holders, and `bindReadOnly(to:)` fails if the buffer is already
/// exclusively bound.
internal let _engineBinding: Atomic<UInt> = Atomic<UInt>(0)
/// Refcount of read-only multi-engine holders. Incremented
/// by `bindReadOnly(to:)`, decremented by `unbindReadOnly(from:)`.
/// Mutually exclusive with `_engineBinding` (non-zero refcount blocks
/// exclusive bind and vice versa).
///
/// Plain `Int` count — does not track *which* engines hold read-only
/// references, only how many. Misuse (unbind without matching bind)
/// is debuggable but not strictly detected; treat the refcount as an
/// advisory.
internal let _readOnlyRefcount: Atomic<Int> = Atomic<Int>(0)
/// Attempt to claim exclusive ownership of this buffer for `engine`.
/// Succeeds only if the buffer is unbound and has no read-only
/// holders. Idempotent against re-binding to the same engine.
///
/// - Parameter engine: The engine claiming exclusive ownership.
/// - Throws:
/// - `EngineAddError.doubleAdd(engine:)` — already exclusively bound
/// to the same engine.
/// - `EngineAddError.boundToOtherEngine(current:prior:)` — already
/// bound to a different engine, or has active read-only holders.
public func bindExclusive(to engine: SynthesisEngine) throws {
// Refcount load and exclusive CAS are
// intentionally split; the read-only tier is documented as opt-in
// advisory, so a concurrent `bindReadOnly` slipping between the
// load and the CAS produces an exclusive+reader pair that
// violates the documented invariant but does not crash. Auditing
// for the invariant happens at the binding sites — this advisory
// surface deliberately does not promote the check to a single
// atomic transaction to avoid bit-packing the refcount and
// exclusive owner into one word.
let readers: Int = _readOnlyRefcount.load(ordering: .acquiring)
if readers > 0 {
// Read-only refcount tier does not track per-engine identity;
// `prior` reports `nil` for the "unknown holder" case.
throw EngineAddError.boundToOtherEngine(
current: engine.identifier,
prior: nil
)
}
let rawPointer: UnsafeMutableRawPointer = Unmanaged.passUnretained(engine).toOpaque()
let target: UInt = UInt(bitPattern: rawPointer)
// Stale-pointer-aware CAS-loop. See SynthesizerBase._bind for
// the full rationale. Pass cap matches
// `SynthesizerBase.bindMaxPasses`.
for _: Int in 0..<LyrebirdBuffer.bindMaxPasses {
let (exchanged, original): (Bool, UInt) = _engineBinding.compareExchange(
expected: 0,
desired: target,
ordering: .acquiringAndReleasing
)
if exchanged { return }
if original == target {
throw EngineAddError.doubleAdd(engine: engine.identifier)
}
let priorEngine: SynthesisEngine? = EngineLifecycleCoordinator.shared.engines.first { other in
let otherRaw: UnsafeMutableRawPointer = Unmanaged.passUnretained(other).toOpaque()
return UInt(bitPattern: otherRaw) == original
}
if priorEngine == nil {
_ = _engineBinding.compareExchange(
expected: original,
desired: 0,
ordering: .releasing
)
continue
}
throw EngineAddError.boundToOtherEngine(
current: engine.identifier,
prior: priorEngine?.identifier
)
}
throw EngineAddError.boundToOtherEngine(
current: engine.identifier,
prior: nil
)
}
/// Release this buffer's exclusive binding to `engine`. Idempotent;
/// no-op if the binding is cleared or held by a different engine.
///
/// - Parameter engine: The engine releasing exclusive ownership.
public func unbindExclusive(from engine: SynthesisEngine) {
let rawPointer: UnsafeMutableRawPointer = Unmanaged.passUnretained(engine).toOpaque()
let target: UInt = UInt(bitPattern: rawPointer)
_ = _engineBinding.compareExchange(
expected: target,
desired: 0,
ordering: .releasing
)
}
/// Claim a read-only share of this buffer for `engine`. Multi-engine
/// safe — any number of engines may hold read-only shares
/// simultaneously. Fails if the buffer is already exclusively bound
/// to any engine.
///
/// Read-only callers must not invoke `setValue`, `setRangeValues`,
/// `clear`, `fill*`, or `invalidate` while holding a read-only share.
/// This invariant is documented but not enforced — violating it is
/// undefined behaviour, not a runtime trap (existing mutation API
/// stays unguarded to preserve the legacy tear-free single-engine
/// model).
///
/// - Parameter engine: The engine claiming a read-only share.
/// - Throws: `EngineAddError.boundToOtherEngine` if the buffer is
/// currently held under exclusive binding.
public func bindReadOnly(to engine: SynthesisEngine) throws {
let exclusive: UInt = _engineBinding.load(ordering: .acquiring)
if exclusive != 0 {
let priorUUID: UUID? = EngineLifecycleCoordinator.shared.engines.first { other in
let otherRaw: UnsafeMutableRawPointer = Unmanaged.passUnretained(other).toOpaque()
return UInt(bitPattern: otherRaw) == exclusive
}?.identifier
throw EngineAddError.boundToOtherEngine(
current: engine.identifier,
prior: priorUUID
)
}
// Refcount overflow on `wrappingAdd`
// would be programmatic misuse, not a steady-state concern. A
// realistic worst-case is dozens of concurrent engines holding
// read-only shares — well below Int.max. Keep wrappingAdd; the
// unbind side uses wrappingSubtract for symmetry. The opt-in
// advisory contract makes runtime guards over-engineering here.
_ = _readOnlyRefcount.wrappingAdd(1, ordering: .acquiringAndReleasing)
}
/// Release a read-only share of this buffer. Saturated at zero —
/// unbalanced calls (more `unbindReadOnly` than `bindReadOnly`) are
/// no-ops rather than underflowing the refcount. Without saturation
/// an unbalanced unbind would wrap to `Int.max`, permanently
/// blocking any subsequent `bindExclusive` because the load check
/// would see a huge positive count.
///
/// - Parameter engine: The engine releasing a read-only share.
/// Currently unused (refcount tier does not track per-engine
/// identity) but accepted for symmetry with `bindReadOnly(to:)`
/// and forward-compatibility if the tier ever upgrades to
/// per-engine tracking.
public func unbindReadOnly(from engine: SynthesisEngine) {
_ = engine // currently unused; see doc
// CAS-loop saturated subtract. Load → if positive, CAS to
// value − 1; retry on contention. Skip the decrement entirely
// if the count is already zero, so the refcount cannot
// underflow under misuse.
while true {
let current: Int = _readOnlyRefcount.load(ordering: .acquiring)
if current <= 0 { return }
let (exchanged, _): (Bool, Int) = _readOnlyRefcount.compareExchange(
expected: current,
desired: current - 1,
ordering: .acquiringAndReleasing
)
if exchanged { return }
}
}
// MARK: - Init / deinit
/// Allocate a zeroed buffer of `count` frames and `channelCount` channels.
///
/// Must be called on a non-RT thread.
///
/// - Parameters:
/// - count: Number of audio frames. Must be > 0.
/// - channelCount: Number of channels. Must be in `[1, lyrebirdMaxFileChannelCount]`.
/// Defaults to `lyrebirdBufferMonoChannelCount` (1) for full backward compatibility.
public init(
count: Int,
channelCount: Int = lyrebirdBufferMonoChannelCount
) {
precondition(count > 0, "LyrebirdBuffer count must be > 0")
precondition(
channelCount >= lyrebirdBufferMonoChannelCount
&& channelCount <= lyrebirdMaxFileChannelCount,
"LyrebirdBuffer channelCount must be in "
+ "[\(lyrebirdBufferMonoChannelCount), \(lyrebirdMaxFileChannelCount)]; got \(channelCount)"
)
// Guard against totalSampleCount overflow before multiplying.
precondition(
count <= Int.max / channelCount,
"LyrebirdBuffer count × channelCount would overflow Int"
)
self.count = count
self.channelCount = channelCount
let total: Int = count * channelCount
_storage = UnsafeMutablePointer<Double>.allocate(capacity: total)
_storage.initialize(repeating: 0, count: total)
_isValid = Atomic<Bool>(true)
_loopLength = Atomic<Int>(count)
}
deinit {
_storage.deallocate()
}
// MARK: - RT-safe read access
/// Whether this buffer is still valid for RT-thread reads.
///
/// Generators must check this (acquiring load) before accessing samples. When `false`,
/// output silence rather than reading from the underlying storage.
public var isValid: Bool {
_isValid.load(ordering: .acquiring)
}
/// Read a sample at the given **linear storage offset**.
///
/// For mono buffers, `index` is the frame index.
/// For multichannel buffers the raw offset is `frame × channelCount + channel` —
/// prefer `buffer[frame: i, channel: ch]` for clarity.
///
/// Debug builds assert that `index` is in `[0, totalSampleCount)`.
public subscript(index: Int) -> Double {
assert(index >= 0 && index < totalSampleCount,
"LyrebirdBuffer subscript out of bounds: \(index) not in [0, \(totalSampleCount))")
return _storage[index]
}
/// Raw read-only pointer to the interleaved sample storage.
///
/// Stride = `channelCount` frames. Sample at frame `f`, channel `ch` lives at
/// `_rawStorage[f * channelCount + ch]`. Caller is responsible for bounds checking
/// — there are no debug asserts on this path.
///
/// **RT contract.** Use to hoist the storage base pointer once at the top of
/// `_computeSamples` and index directly in inner loops, eliminating per-access
/// class-property loads through `self`.
///
/// The pointer is stable for the lifetime of *this* `LyrebirdBuffer` instance.
/// `_storage` is never resized after construction. If the consumer accesses the
/// buffer through an atomic slot (`RTBufferSlot`) that may swap in a different
/// `LyrebirdBuffer`, reload the pointer once per audio block from the freshly-loaded
/// instance.
@_spi(LyrebirdExtensions)
public var _rawStorage: UnsafePointer<Double> {
UnsafePointer(_storage)
}
/// Raw read-write pointer to the interleaved sample storage.
///
/// Same indexing as `_rawStorage` (`storage[f * channelCount + ch]`). Returned as
/// `UnsafeMutablePointer<Double>` so owners can write samples on the RT thread
/// without going through the locked `setFrame(_:channel:value:)` setter.
///
/// **Exclusive-write contract.** Use ONLY when the caller has exclusive write
/// access to the buffer for the duration of the write — typically when the
/// buffer is owned by `self` (a Generator's private circular capture buffer)
/// and no other thread can read or write it concurrently. The non-RT
/// `setFrame(_:channel:value:)` setter takes `_writeLock`; this raw accessor
/// bypasses the lock entirely and so must not be used on buffers that are
/// shared with a non-RT writer.
///
/// Same lifetime contract as `_rawStorage`: pointer stable for the lifetime
/// of this `LyrebirdBuffer` instance; reload across `RTBufferSlot` swaps.
@_spi(LyrebirdExtensions)
public var _rawStorageMutable: UnsafeMutablePointer<Double> {
_storage
}
/// Read a sample by frame index and channel index.
///
/// - Parameters:
/// - frame: Frame index in `[0, count)`.
/// - channel: Channel index in `[0, channelCount)`.
///
/// Debug builds assert both indices are in range.
public subscript(frame: Int, channel: Int) -> Double {
assert(frame >= 0 && frame < count,
"LyrebirdBuffer frame index out of bounds: \(frame) not in [0, \(count))")
assert(channel >= 0 && channel < channelCount,
"LyrebirdBuffer channel index out of bounds: \(channel) not in [0, \(channelCount))")
return _storage[frame * channelCount + channel]
}
// MARK: - Live language-side writes (safe while RT thread reads at block-rate)
// These setters allow a non-RT thread (UI, MIDI handler, OSC handler, scheduled
// routine, etc.) to update sample values in a buffer that is currently being read
// by the RT thread. They are intended for **parameter / lookup-table buffers** that
// an RT generator snapshots once per audio block (or once per FFT hop), NOT for
// long audio buffers being scrubbed sample-by-sample mid-block.
//
// ## RT-side contract
//
// A generator that consumes a buffer mutated by these setters MUST snapshot it once
// at the top of `_computeSamples` (typically `memcpy` into a pre-allocated scratch
// pointer) and then process from the snapshot for the rest of the block. The RT
// thread never takes `_writeLock` — synchronisation between writers is done via
// `_writeLock`, and visibility to the RT thread relies on naturally-aligned 8-byte
// (`Double`) stores being atomic at the hardware level on arm64 / x86_64. This
// means an interleaved RT read CAN observe a partial range update (some indices
// already written, some not) but never a torn `Double` value.
//
// For UI sliders, MIDI CC, and OSC parameter streams that map onto bin-rate
// FFT processors (`SpectralBinDelay`, `SpectralMagnitudeMap` curve, etc.), this is
// the ergonomic and right-cost trade-off. For whole-buffer atomic replacement of
// sample data being read at audio rate, use a fresh `LyrebirdBuffer` and swap the
// generator's reference on the main thread instead.
/// Set a single sample at the given **linear storage offset**.
///
/// For mono buffers, `index` is the frame index. For multichannel buffers the raw
/// offset is `frame × channelCount + channel` — prefer the
/// `setValue(_:frame:channel:)` overload for clarity.
///
/// Safe to call from a non-RT thread while the RT thread reads this buffer at
/// block rate (see the section comment above for the RT-side snapshot contract).
/// Concurrent language-side callers are serialised by `_writeLock`. The RT thread
/// never takes the lock and never blocks.
///
/// The bounds precondition runs **before** the validity check, so an out-of-range
/// index traps regardless of whether the buffer has been invalidated. After the
/// bounds check, the write is a no-op when `isValid == false` — this matches the
/// `RecordBuffer.write` semantic of "drop writes after invalidate".
///
/// - Parameters:
/// - value: Sample value to write.
/// - index: Linear storage offset in `[0, totalSampleCount)`.
public func setValue(
_ value: Double,
at index: Int
) {
precondition(index >= 0 && index < totalSampleCount,
"LyrebirdBuffer.setValue: index \(index) out of range [0, \(totalSampleCount))")
_writeLock.lock()
defer { _writeLock.unlock() }
guard _isValid.load(ordering: .acquiring) else { return }
_storage[index] = value
}
/// Set a single sample by frame index and channel index.
///
/// Safe to call from a non-RT thread while the RT thread reads this buffer at
/// block rate (see the section comment above for the RT-side snapshot contract).
///
/// The bounds preconditions run **before** the validity check, so out-of-range
/// frame or channel still traps regardless of `isValid`. After bounds, the write
/// is a no-op when `isValid == false`.
///
/// - Parameters:
/// - value: Sample value to write.
/// - frame: Frame index in `[0, count)`.
/// - channel: Channel index in `[0, channelCount)`.
public func setValue(
_ value: Double,
frame: Int,
channel: Int
) {
precondition(frame >= 0 && frame < count,
"LyrebirdBuffer.setValue: frame \(frame) out of range [0, \(count))")
precondition(channel >= 0 && channel < channelCount,
"LyrebirdBuffer.setValue: channel \(channel) out of range [0, \(channelCount))")
_writeLock.lock()
defer { _writeLock.unlock() }
guard _isValid.load(ordering: .acquiring) else { return }
_storage[frame * channelCount + channel] = value
}
/// Write `values` into the storage starting at the given linear offset.
///
/// `index + values.count` must be `≤ totalSampleCount`. The whole range is
/// written under `_writeLock` so no other language-side writer interleaves; the
/// RT thread can still observe a mid-write partial state for an in-flight range
/// (some elements updated, some not), which is acceptable for parameter buffers
/// snapshotted at block rate.
///
/// The bounds precondition runs **before** the validity check; out-of-range
/// arguments trap regardless of `isValid`. After bounds, the write is a no-op
/// when `isValid == false`.
///
/// - Parameters:
/// - values: Sample values to write.
/// - index: Linear storage offset in `[0, totalSampleCount − values.count]`.
public func setRangeValues(
_ values: [Double],
startingAt index: Int
) {
precondition(index >= 0,
"LyrebirdBuffer.setRangeValues: index \(index) must be non-negative")
precondition(values.count <= totalSampleCount - index,
"LyrebirdBuffer.setRangeValues: index \(index) + \(values.count) "
+ "exceeds totalSampleCount \(totalSampleCount)")
_writeLock.lock()
defer { _writeLock.unlock() }
guard _isValid.load(ordering: .acquiring) else { return }
values.withUnsafeBufferPointer { src in
guard let base: UnsafePointer<Double> = src.baseAddress else { return }
_storage.advanced(by: index).update(from: base, count: values.count)
}
}
/// Zero every sample in the buffer (all channels), in-place.
///
/// Intended for "reset and play again" workflows where a pre-allocated buffer is
/// reused across passes. Works for any `channelCount` (mono and multichannel).
///
/// Safe to call from a non-RT thread while the RT thread reads this buffer at
/// block rate, under the same partial-visibility caveat as `setRangeValues`: an
/// in-flight RT reader may observe a mixture of "already zeroed" and "not yet
/// zeroed" samples for a single block, but never a torn `Double` value. RT
/// consumers that snapshot the buffer once per block see a fully-zeroed buffer
/// from the following block onward.
///
/// Concurrent language-side callers are serialised by `_writeLock`. The RT
/// thread never takes the lock and never blocks. The clear is a no-op when
/// `isValid == false`.
public func clear() {
_writeLock.lock()
defer { _writeLock.unlock() }
guard _isValid.load(ordering: .acquiring) else { return }
vDSP_vclrD(_storage, 1, vDSP_Length(totalSampleCount))
}
// MARK: - Fill methods (non-RT thread, mono buffers only)
// WARNING: Fill methods must not be called after any generator holding this buffer has been
// added to a running engine. The RT render thread reads `_storage` lock-free; a concurrent
// fill is an unsynchronized data race. Fill all content before scheduling the generator,
// or use a fresh `LyrebirdBuffer` and replace the generator on the main thread.
// The narrower `setValue` / `setRangeValues` API above IS safe to call concurrently with
// an RT reader that snapshots the buffer once per block.
/// Fill every sample with a constant `value`.
///
/// Requires `channelCount == 1`. Use `loadAllChannels(url:)` or write directly to
/// storage via `withMutableStorage` for multichannel buffers.
///
/// Must be called before `invalidate()`.
public func fill(with value: Double) {
precondition(
channelCount == lyrebirdBufferMonoChannelCount,
"fill(with:) requires a mono buffer (channelCount == 1); "
+ "this buffer has channelCount == \(channelCount)."
)
precondition(_isValid.load(ordering: .relaxed), "fill(with:) called on an invalidated LyrebirdBuffer")
_storage.update(repeating: value, count: count)
}
/// Fill using a closure: `body(frameIndex, totalFrameCount) → Double`.
///
/// Requires `channelCount == 1`.
///
/// ```swift
/// buffer.fill { i, n in Double(i) / Double(n) } // sawtooth 0→1
/// ```
///
/// Must be called before `invalidate()`.
public func fill(using body: (Int, Int) -> Double) {
precondition(
channelCount == lyrebirdBufferMonoChannelCount,
"fill(using:) requires a mono buffer (channelCount == 1); "
+ "this buffer has channelCount == \(channelCount)."
)
precondition(_isValid.load(ordering: .relaxed), "fill(using:) called on an invalidated LyrebirdBuffer")
for i: Int in 0..<count {
_storage[i] = body(i, count)
}
}
/// Fill with a single-cycle sine wave in `[-1, 1]`.
///
/// Requires `channelCount == 1`.
/// Must be called before `invalidate()`.
public func fillSine() {
precondition(
channelCount == lyrebirdBufferMonoChannelCount,
"fillSine() requires a mono buffer (channelCount == 1); "
+ "this buffer has channelCount == \(channelCount)."
)
precondition(_isValid.load(ordering: .relaxed), "fillSine() called on an invalidated LyrebirdBuffer")
let countFloat: Double = Double(count)
let twoPi: Double = 2.0 * .pi
for i: Int in 0..<count {
_storage[i] = sin(twoPi * Double(i) / countFloat)
}
}
/// Fill with a Hanning (raised-cosine) window in `[0, 1]`.
///
/// `w[i] = 0.5 × (1 − cos(2π × i / N))`
///
/// Requires `channelCount == 1`.
/// Must be called before `invalidate()`.
public func fillHanning() {
precondition(
channelCount == lyrebirdBufferMonoChannelCount,
"fillHanning() requires a mono buffer (channelCount == 1); "
+ "this buffer has channelCount == \(channelCount)."
)
precondition(_isValid.load(ordering: .relaxed), "fillHanning() called on an invalidated LyrebirdBuffer")
let countFloat: Double = Double(count)
let twoPi: Double = 2.0 * .pi
for i: Int in 0..<count {
_storage[i] = 0.5 * (1.0 - cos(twoPi * Double(i) / countFloat))
}
}
/// Fill this buffer with a triangular (Bartlett) window.
///
/// `w[i] = 1 − |2i/N − 1|` — rises linearly from 0 at `i=0` to 1 at `i=N/2`,
/// then falls linearly back to 0 at `i=N`.
///
/// Satisfies the constant OLA condition at 4:1 overlap (sum per sample = 2.0),
/// making it the recommended window for granular pitch shifting at that overlap ratio.
public func fillTriangle() {
precondition(
channelCount == lyrebirdBufferMonoChannelCount,
"fillTriangle() requires a mono buffer (channelCount == 1); "
+ "this buffer has channelCount == \(channelCount)."
)
precondition(_isValid.load(ordering: .relaxed), "fillTriangle() called on an invalidated LyrebirdBuffer")
let n: Double = Double(count)
for i: Int in 0..<count {
_storage[i] = 1.0 - abs(2.0 * Double(i) / n - 1.0)
}
}
// MARK: - Invalidate (non-RT thread only)
/// Signal to the RT thread that this buffer is no longer valid.
///
/// Performs a `.releasing` store of `false` into the validity flag. Any generator
/// holding this buffer will see `isValid == false` on its next `.acquiring` load and
/// will output silence instead of reading samples.
///
/// The underlying memory remains allocated until this object is deallocated via ARC.
/// See the "Memory management" section in the class-level doc for the full teardown
/// pattern and the RT-thread deinit gotcha. Must be called from a non-RT thread.
///
/// Takes `_writeLock` so no in-flight `setValue` / `setRangeValues` can complete
/// after the validity flag is cleared — once `invalidate()` returns, every
/// subsequent setter call is a no-op.
public func invalidate() {
_writeLock.lock()
defer { _writeLock.unlock() }
_isValid.store(false, ordering: .releasing)
}
// MARK: - RT write access (used by RecordBuffer)
/// Write a single sample at `frame` / `channel` from the RT audio thread.
///
/// No bounds-checking in release builds. Only call from within `_computeSamples`
/// after verifying `frame < count` and `channel < channelCount`.
@inline(__always)
internal func write(
_ value: Double,
frame: Int,
channel: Int
) {
assert(frame >= 0 && frame < count,
"LyrebirdBuffer write frame out of bounds: \(frame) not in [0, \(count))")
assert(channel >= 0 && channel < channelCount,
"LyrebirdBuffer write channel out of bounds: \(channel) not in [0, \(channelCount))")
_storage[frame * channelCount + channel] = value
}
// MARK: - Internal validity check (used by LyrebirdBufferWavetable.swift extensions)
/// Returns `true` when this buffer has not been invalidated, using a relaxed load.
///
/// Intended solely for `precondition` guards in fill extensions defined in other files.
/// The relaxed ordering is sufficient here because the check is advisory (a race between
/// filling and invalidating is a programmer error regardless of ordering).
internal var _isValidForFill: Bool {
_isValid.load(ordering: .relaxed)
}
// MARK: - Internal storage access (used by LyrebirdBufferFileIO.swift)
// WARNING: these give raw pointer access to the underlying sample storage.
// They exist solely for the file I/O extension — do not use them in RT code paths.
/// Calls `body` with a mutable pointer to the raw sample storage, the frame count,
/// and the channel count. The closure runs synchronously; the pointer is valid only
/// for its duration.
internal func withMutableStorage<T>(
_ body: (UnsafeMutablePointer<Double>, Int, Int) throws -> T
) rethrows -> T {
try body(_storage, count, channelCount)
}
/// Calls `body` with a read-only pointer to the raw sample storage, the frame count,
/// and the channel count. The closure runs synchronously; the pointer is valid only
/// for its duration.
internal func withStorage<T>(
_ body: (UnsafePointer<Double>, Int, Int) throws -> T
) rethrows -> T {
try body(_storage, count, channelCount)
}
// MARK: - FFT window factory methods
/// Returns a Hanning (von Hann) window of `size` samples using vDSP's DENORM convention.
///
/// `w[n] = 0.5 - 0.5 × cos(2πn/size)`, with `sum(w) = size/2`.
///
/// - COLA at 50 % overlap: `Σ w[n-kH] = 1.0` (constant) ✓
/// - WOLA COLA at 75 % overlap: `Σ w²[n-kH] = 1.5` (constant) ✓ — use as both
/// analysis and synthesis window in `SpectralChain.Audio` at 75 % overlap.
///
/// Pass to `SpectralChain.Audio(analysisWindow:synthesisWindow:)`.
public static func hanningWindow(size: Int) -> [Float] {
precondition(size >= 1, "LyrebirdBuffer.hanningWindow: size must be >= 1, got \(size)")
var w: [Float] = [Float](repeating: 0, count: size)
w.withUnsafeMutableBufferPointer { ptr in
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
vDSP_hann_window(base, vDSP_Length(size), Int32(vDSP_HANN_DENORM))
}
return w
}
/// Returns a rectangular (boxcar) window of `size` samples — all values `1.0`.
///
/// Using rectangular as the synthesis window leaves the analysis Hanning window
/// as the sole OLA contribution. The OLA sum of Hanning at 50 %/75 % overlap is
/// constant, giving unity gain without modifying IFFT frames.
///
/// Pass to `SpectralChain.Audio(synthesisWindow:)` when you want analysis-only OLA
/// (no synthesis taper).
public static func rectangularWindow(size: Int) -> [Float] {
precondition(size >= 1, "LyrebirdBuffer.rectangularWindow: size must be >= 1, got \(size)")
return [Float](repeating: 1.0, count: size)
}
/// Returns a sine window of `size` samples.
///
/// `w[n] = sin(πn/size)` for `n = 0 ..< size`.
///
/// - WOLA COLA at 50 % overlap: `Σ w²[n-kH] = 1.0` (constant) ✓ — sine is the
/// recommended analysis/synthesis window pair at 50 % overlap.
///
/// Pass to `SpectralChain.Audio(analysisWindow:synthesisWindow:)` at 50 % overlap
/// for per-sample unity-gain reconstruction. Default for `SpectralChain.Audio` when
/// no window args are supplied.
public static func sineWindow(size: Int) -> [Float] {
precondition(size >= 1, "LyrebirdBuffer.sineWindow: size must be >= 1, got \(size)")
var w: [Float] = [Float](repeating: 0, count: size)
let n: vDSP_Length = vDSP_Length(size)
var start: Float = 0
var step: Float = Float.pi / Float(size)
vDSP_vramp(&start, &step, &w, 1, n) // w[i] = i × π/size
w.withUnsafeMutableBufferPointer { ptr in
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
var count: Int32 = Int32(size)
vvsinf(base, base, &count) // w[i] = sin(i × π/size)
}
return w
}
}