Files
Lyrebird/Sources/Lyrebird/Generators/BufferIO/DiskIn.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

535 lines
24 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.
// DiskIn.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Synchronization
#if canImport(AudioToolbox)
import AudioToolbox
#endif
/// Streaming soundfile input generators.
///
/// `DiskIn.Audio` streams audio from disk using a double-buffer scheme.
/// A background `DispatchQueue` fills the inactive half via `ExtAudioFileRead`
/// while the RT thread reads the active half. No disk I/O or blocking calls
/// occur on the RT thread after initialisation.
public enum DiskIn {
/// Audio-rate streaming playback from a soundfile.
///
/// All memory is pre-allocated at `init`; no RT allocation occurs.
///
/// **Thread safety** (`@unchecked Sendable` — manually verified):
/// - `_halfBuffers[_activeHalf]` is exclusively **read** by the RT thread.
/// - `_halfBuffers[1 − _activeHalf]` is exclusively **written** by the BG thread.
/// - `_half0Ready` / `_half1Ready` atomics gate the handoff: BG stores `true`
/// with `.releasing` after every write; RT loads with `.acquiring` before
/// reading — all BG writes are guaranteed visible to RT.
/// - `_eofHalfIdx` is stored by BG with `.releasing`; RT loads with `.acquiring`.
/// - `_interleavedReadBuf`, `_fileRef`, `_atEOF` are BG-only after `init`.
///
/// ## Usage
/// ```swift
/// let player = try DiskIn.Audio(url: fileURL, channelCount: 2,
/// sampleRate: engine.sampleRate)
/// final class FilePlayer: SynthesizerBase {
/// override func build() {
/// output(bus: 0, source: player[0])
/// output(bus: 1, source: player[1])
/// }
/// }
/// ```
public final class Audio: GeneratorBase, @unchecked Sendable, AudioGenerator, DoneActionWatchable {
// MARK: - Generator protocol
// MARK: - Public configuration
/// Number of output channels (fixed at init).
public let channelCount: Int
// MARK: - Private configuration
private let bufferFrames: Int
private let loop: Bool
private let _doneAction: DoneAction
private let rateClampLow: Double = 0.1
private let rateClampHigh: Double = 4.0
// MARK: - Rate input
private let _rateSource: any ValidGeneratorInput
// MARK: - Pre-allocated buffers
/// Double buffer: `_halfBuffers[half][channel][frame]`.
/// BG owns the inactive half; RT owns the active half — they never alias.
private var _halfBuffers: [[[Float]]]
/// Interleaved scratch for BG reads (never touched by RT).
private var _interleavedReadBuf: [Float]
private let _zeroFallback: [Double]
private var _mulAdd: MulAddSpec
public override var outputChannelCount: Int { channelCount }
// MARK: - RT-only state
private var _activeHalf: Int = 0
private var _readPos: Double = 0
private var _isDone: Bool = false
// MARK: - Shared atomics
// Stored as two separate properties because Atomic<T> is non-copyable
// and cannot be placed in an Array<T>.
/// BG sets `true` (releasing) after filling half 0;
/// RT sets `false` (releasing) before enqueuing a refill request.
private let _half0Ready: Atomic<Bool>
/// BG sets `true` (releasing) after filling half 1;
/// RT sets `false` (releasing) before enqueuing a refill request.
private let _half1Ready: Atomic<Bool>
/// Index of the half that BG partially filled (EOF reached). −1 = no EOF.
/// RT checks at each half-boundary crossing to detect end-of-stream.
private let _eofHalfIdx: Atomic<Int>
private let _needsFree: Atomic<Bool> = Atomic(false)
/// `true` when `doneAction == .freeNode` and playback has reached end-of-file.
/// Poll from a non-RT context to schedule node removal via `engine.remove`.
public var needsFree: Bool { _needsFree.load(ordering: .acquiring) }
// MARK: - Helpers for half-indexed atomic access
@inline(__always)
private func _halfIsReady(_ idx: Int) -> Bool {
idx == 0
? _half0Ready.load(ordering: .acquiring)
: _half1Ready.load(ordering: .acquiring)
}
@inline(__always)
private func _setHalfReady(
_ idx: Int,
_ value: Bool
) {
if idx == 0 { _half0Ready.store(value, ordering: .releasing) }
else { _half1Ready.store(value, ordering: .releasing) }
}
// MARK: - RT→BG signaling
/// RT enqueues the half index to refill; BG dequeues and fills it.
private let _refillQueue: SPSCQueue<Int>
private let _backgroundQueue: DispatchQueue
private let _stopped: Atomic<Bool> = Atomic(false)
// MARK: - BG-only file state (never accessed from RT after init)
#if canImport(AudioToolbox)
private var _fileRef: ExtAudioFileRef?
#else
/// Portable WAV reader. Reopened from `_wavURL` to loop back to the start,
/// since the reader is forward-only.
private var _wavReader: WavFileReader?
private let _wavURL: URL
#endif
/// Multiplies the read-position advance so a file whose sample rate
/// differs from the engine's plays at the right speed and pitch.
/// `1.0` on Apple, where `ExtAudioFile` has already resampled to the
/// engine rate; `fileSampleRate / engineSampleRate` off Apple, where the
/// portable reader hands back the file's native frames.
private let _readRateScale: Double
private let _fileChannelCount: Int // min(file channels, channelCount)
private var _atEOF: Bool = false
// MARK: - Init
/// Create a streaming disk reader.
///
/// Disk I/O occurs in `init` (initial buffer fill) and on a dedicated
/// background `DispatchQueue`. The RT audio callback never touches the
/// file or any blocking operation.
///
/// - Parameters:
/// - url: Soundfile URL. Most formats supported (WAV, AIFF, CAF, …).
/// - channelCount: Number of output channels. File channels beyond this
/// count are ignored; output channels beyond the file's channel count
/// are silent.
/// - sampleRate: Engine sample rate. `ExtAudioFile` performs sample-rate
/// conversion transparently when the file's native SR differs.
/// Defaults to 48 000 Hz.
/// - rate: Playback rate (0.1–4.0, forward only). `1.0` = original speed.
/// - loop: When `true`, seek to file start on EOF (seamless looping).
/// - doneAction: Action taken when EOF is reached with `loop == false`.
/// - bufferFrames: Size of each half-buffer in frames. Must be a power of
/// two. Default 8 192 (≈ 170 ms at 48 kHz).
/// - mul: Output scale factor. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
/// - Throws: On Apple, `DiskInError` (`cannotOpenFile` / `cannotSetFormat`).
/// Off Apple, the `WavFileError` from the portable reader propagates
/// directly — a cross-platform caller should catch both.
public init(
url: URL,
channelCount: Int,
sampleRate: Double = 48000,
rate: any ValidGeneratorInput = 1.0 as Double,
loop: Bool = false,
doneAction: DoneAction = .nothing,
bufferFrames: Int = 8192,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) throws {
precondition(channelCount >= 1,
"DiskIn.Audio: channelCount must be >= 1")
precondition(
bufferFrames > 0 && bufferFrames & (bufferFrames - 1) == 0,
"DiskIn.Audio: bufferFrames \(bufferFrames) must be a power of two"
)
self.channelCount = channelCount
self.bufferFrames = bufferFrames
self.loop = loop
self._doneAction = doneAction
let resolvedRate: any ValidGeneratorInput = rate._resolvedInput()
self._rateSource = resolvedRate
_zeroFallback = makeSampleBuffer()
_mulAdd = MulAddSpec(mul: mul, add: add)
// Open the file and learn its channel count. On Apple the client
// format is set to interleaved Float32 at the engine rate, so
// `ExtAudioFile` resamples transparently; off Apple the portable
// reader returns the file's native frames and the sample-rate ratio
// is folded into the read-position advance instead.
let fileChannels: Int
#if canImport(AudioToolbox)
var rawRef: ExtAudioFileRef?
let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &rawRef)
guard openStatus == noErr, let rawRef: ExtAudioFileRef else {
throw DiskInError.cannotOpenFile(openStatus)
}
_fileRef = rawRef
var fileFmt: AudioStreamBasicDescription = AudioStreamBasicDescription()
var propSize: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
let queryStatus: OSStatus = ExtAudioFileGetProperty(rawRef,
kExtAudioFileProperty_FileDataFormat,
&propSize, &fileFmt)
guard queryStatus == noErr else {
ExtAudioFileDispose(rawRef)
throw DiskInError.cannotOpenFile(queryStatus)
}
fileChannels = min(Int(fileFmt.mChannelsPerFrame), channelCount)
_fileChannelCount = fileChannels
_readRateScale = 1.0
let float32ByteSize: UInt32 = UInt32(MemoryLayout<Float>.size)
let float32BitsPerChannel: UInt32 = 32
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
mSampleRate: sampleRate,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
mBytesPerPacket: float32ByteSize * UInt32(fileChannels),
mFramesPerPacket: 1,
mBytesPerFrame: float32ByteSize * UInt32(fileChannels),
mChannelsPerFrame: UInt32(fileChannels),
mBitsPerChannel: float32BitsPerChannel,
mReserved: 0
)
let setFmtStatus: OSStatus = ExtAudioFileSetProperty(
rawRef,
kExtAudioFileProperty_ClientDataFormat,
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
&clientFmt
)
guard setFmtStatus == noErr else {
ExtAudioFileDispose(rawRef)
throw DiskInError.cannotSetFormat(setFmtStatus)
}
#else
// Throws `WavFileError` on a bad or non-WAV file — matching the
// portable `NRTDriver` input path, which lets that error propagate
// rather than wrapping it.
_wavURL = url
let reader: WavFileReader = try WavFileReader(url: url)
fileChannels = min(reader.channels, channelCount)
_fileChannelCount = fileChannels
_readRateScale = reader.sampleRate > 0 ? reader.sampleRate / sampleRate : 1.0
_wavReader = reader
#endif
// Pre-allocate double buffer: 2 halves × channelCount × bufferFrames.
// Channels beyond _fileChannelCount are zero-initialised and never written.
_halfBuffers = Array(
repeating: Array(
repeating: [Float](repeating: 0, count: bufferFrames),
count: channelCount
),
count: 2
)
_interleavedReadBuf = [Float](repeating: 0,
count: bufferFrames * fileChannels)
_half0Ready = Atomic<Bool>(false)
_half1Ready = Atomic<Bool>(false)
_eofHalfIdx = Atomic<Int>(-1)
let refillQueueCapacity: Int = 4 // 2 halves × 2 extra slots for in-flight swaps
_refillQueue = SPSCQueue<Int>(capacity: refillQueueCapacity)
_backgroundQueue = DispatchQueue(label: "com.lyrebird.diskin",
qos: .userInitiated)
super.init(channels: channelCount)
// Fill both halves synchronously (init runs on the user thread — disk I/O OK).
let frames0: Int = _fillHalf(0)
if frames0 < bufferFrames && !loop {
_eofHalfIdx.store(0, ordering: .releasing)
}
_half0Ready.store(true, ordering: .releasing)
let frames1: Int = _fillHalf(1)
if frames1 < bufferFrames && !loop
&& _eofHalfIdx.load(ordering: .relaxed) == -1 {
_eofHalfIdx.store(1, ordering: .releasing)
}
_half1Ready.store(true, ordering: .releasing)
_startBGLoop()
_registerAutoFreeIfNeeded(doneAction)
}
deinit {
_stopped.store(true, ordering: .releasing)
// Do NOT call _backgroundQueue.sync {} here: if BG's per-iteration
// guard-let released the last strong reference, deinit runs on the BG
// thread — calling sync on the same serial queue deadlocks. BG has
// finished its current iteration before deinit can start, so _fileRef
// is not being accessed concurrently; direct disposal is safe.
#if canImport(AudioToolbox)
if let ref: ExtAudioFileRef = _fileRef { ExtAudioFileDispose(ref) }
#else
_wavReader?.close()
#endif
}
// MARK: - Background internals
private func _startBGLoop() {
// BG polls _refillQueue with a short sleep rather than blocking on a
// semaphore. Semaphore.signal() from the RT thread causes a kernel trap
// when the waiter is present — forbidden on the RT audio callback.
let pollInterval: Double = 0.0005 // 500 µs — well under any realistic half-buffer duration
_backgroundQueue.async { [weak self] in
while true {
// Re-acquire weak self on every iteration so deinit can proceed
// between poll cycles without a retain cycle.
guard let self: DiskIn.Audio, !self._stopped.load(ordering: .acquiring) else { return }
if let halfIdx: Int = self._refillQueue.dequeue() {
// Mark not-ready before writing so RT won't read a partial half.
self._setHalfReady(halfIdx, false)
let framesRead: Int = self._fillHalf(halfIdx)
// Record the first EOF half (don't overwrite an earlier one).
if framesRead < self.bufferFrames && !self.loop
&& self._eofHalfIdx.load(ordering: .relaxed) == -1 {
self._eofHalfIdx.store(halfIdx, ordering: .releasing)
}
// Releasing store — RT's acquiring load on the half-ready atomic
// synchronises with this, making all _halfBuffers writes visible to RT.
self._setHalfReady(halfIdx, true)
} else {
Thread.sleep(forTimeInterval: pollInterval)
}
}
}
}
/// Read up to `bufferFrames` frames from the file into `_halfBuffers[halfIdx]`.
/// Returns the number of frames actually written.
/// Called from the BG thread (or from `init` before BG starts).
@discardableResult
private func _fillHalf(_ halfIdx: Int) -> Int {
// Zero the entire half first: extra channels and EOF tail stay silent.
for ch: Int in 0..<channelCount {
for i: Int in 0..<bufferFrames { _halfBuffers[halfIdx][ch][i] = 0 }
}
guard !_atEOF || loop else { return 0 }
var totalRead: Int = 0
let maxAttempts: Int = 16 // guard against zero-length files in loop mode
for _ in 0..<maxAttempts where totalRead < bufferFrames {
let remaining: Int = bufferFrames - totalRead
var framesRead: Int = 0
var readOK: Bool = true
#if canImport(AudioToolbox)
guard let fileRef: ExtAudioFileRef = _fileRef else { return totalRead }
var framesToRead: UInt32 = UInt32(remaining)
let readStatus: OSStatus = _interleavedReadBuf
.withUnsafeMutableBufferPointer { ptr in
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return OSStatus(-1) }
var bl: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(_fileChannelCount),
mDataByteSize: UInt32(
remaining * _fileChannelCount
* MemoryLayout<Float>.size),
mData: base
)
)
return ExtAudioFileRead(fileRef, &framesToRead, &bl)
}
readOK = readStatus == noErr
framesRead = Int(framesToRead)
#else
// The portable reader hands back interleaved frames. A read
// error (a truncated file) ends the half rather than throwing,
// matching the Apple branch's `break` on a non-`noErr` status.
guard let reader: WavFileReader = _wavReader else { return totalRead }
do {
let block: [Float] = try reader.read(frames: remaining)
framesRead = _fileChannelCount > 0 ? block.count / _fileChannelCount : 0
for f: Int in 0..<framesRead {
for ch: Int in 0..<_fileChannelCount {
_interleavedReadBuf[f * _fileChannelCount + ch] =
block[f * _fileChannelCount + ch]
}
}
} catch {
readOK = false
}
#endif
guard readOK else { break }
for f: Int in 0..<framesRead {
for ch: Int in 0..<_fileChannelCount {
_halfBuffers[halfIdx][ch][totalRead + f] =
_interleavedReadBuf[f * _fileChannelCount + ch]
}
}
totalRead += framesRead
if framesRead < remaining {
if loop {
#if canImport(AudioToolbox)
let seekStatus: OSStatus = ExtAudioFileSeek(fileRef, 0)
guard seekStatus == noErr else { _atEOF = true; break }
#else
// The portable reader is forward-only, so loop by
// reopening from the top. A reopen failure ends playback.
_wavReader?.close()
guard let rewound: WavFileReader = try? WavFileReader(url: _wavURL) else {
_wavReader = nil
_atEOF = true
break
}
_wavReader = rewound
#endif
// Continue to fill the rest from the file start.
} else {
_atEOF = true
break
}
}
}
return totalRead
}
// MARK: - AudioGenerator
public func floatValue(graph: SynthGraph) -> Double {
calculatedSamples(graph: graph, count: graph.engine.blockSize)
.first?.first ?? 0
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
defer { _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count) }
if _isDone {
for ch: Int in 0..<channelCount {
for i: Int in 0..<count { _result[ch][i] = 0 }
}
return _result
}
let rateSamples: [Double] = _rateSource
.calculatedSamples(graph: graph, count: count).first ?? _zeroFallback
for i: Int in 0..<count {
// Resolve any pending half-boundary crossing before reading.
// `while` handles the (rare) case where a high rate overshoots by > bufferFrames.
while _readPos >= Double(bufferFrames) {
let newHalf: Int = 1 - _activeHalf
// Check whether we just exhausted the EOF half.
if _eofHalfIdx.load(ordering: .acquiring) == _activeHalf {
_isDone = true
_stopped.store(true, ordering: .releasing) // stop BG polling
if _doneAction == .freeNode {
_needsFree.store(true, ordering: .releasing)
}
for ch: Int in 0..<channelCount {
for j: Int in i..<count { _result[ch][j] = 0 }
}
return _result
}
if _halfIsReady(newHalf) {
// Swap to the new half and schedule a background refill.
_readPos -= Double(bufferFrames)
let oldHalf: Int = _activeHalf
_activeHalf = newHalf
_setHalfReady(oldHalf, false)
_refillQueue.enqueue(oldHalf) // BG poll loop picks this up
} else {
// Buffer underrun: output silence for the rest of this block.
// _readPos stays >= bufferFrames; next block retries the swap.
for ch: Int in 0..<channelCount {
for j: Int in i..<count { _result[ch][j] = 0 }
}
return _result
}
}
// Linear interpolation within the active half.
let intPos: Int = Int(_readPos)
let frac: Double = _readPos - Double(intPos)
let intPos1: Int = min(intPos + 1, bufferFrames - 1)
for ch: Int in 0..<channelCount {
let s0: Double = Double(_halfBuffers[_activeHalf][ch][intPos])
let s1: Double = Double(_halfBuffers[_activeHalf][ch][intPos1])
_result[ch][i] = s0 + frac * (s1 - s0)
}
let rate: Double = min(rateClampHigh,
max(rateClampLow, Double(rateSamples[i])))
_readPos += rate * _readRateScale
}
return _result
}
}
}
// GeneratorEnum conformance intentionally omitted — Audio-only.