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

590 lines
28 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.
// DiskOut.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
#if canImport(AudioToolbox)
import AudioToolbox
#endif
import Synchronization
/// Streaming soundfile output generators.
///
/// `DiskOut.Audio` writes the signal graph output to a soundfile in real time.
/// The RT thread writes frames into a pre-allocated ring buffer; a background
/// `DispatchQueue` drains the ring buffer via `ExtAudioFileWrite`.
///
/// `DiskOut.Audio` conforms to ``RootRegistering``. Constructed inside
/// ``SynthesizerBase/build()`` it auto-registers as a synth root — no explicit
/// ``SynthesizerBase/addOutputGenerator(_:)`` call is required and the return value
/// may be discarded. The passthrough output remains available for callers who want
/// to monitor while recording.
public enum DiskOut {
#if !canImport(AudioToolbox)
/// Maps a WAV ``AudioFileFormat`` to a ``WavEncoding`` for the portable
/// backend; the Apple-only containers throw
/// ``DiskOutError/unsupportedFormatOnPlatform(_:)``.
static func wavEncoding(for format: AudioFileFormat) throws -> WavEncoding {
switch format {
case .wavFloat32: return .float32
case .wavInt16: return .int16
case .wavInt24: return .int24
// RF64 needs 64-bit `ds64` sizing the portable classic-RIFF writer does
// not emit; mapping it to a 32-bit WAV would silently truncate/trap past
// 4 GB. Unsupported off Apple until a portable RF64 writer exists.
case .rf64Float32, .rf64Int24, .cafFloat32, .aiffFloat32, .aacHigh, .aacMedium, .alac:
throw DiskOutError.unsupportedFormatOnPlatform(format)
}
}
#endif
/// Audio-rate streaming recorder to a soundfile.
///
/// The generator passes the input signal through as its output, so it can be
/// placed inline in a signal chain. To use it purely as a sink, ignore the
/// output or wire it through `Out` to a bus that is not monitored.
///
/// Call `close()` from the language side when recording is finished.
/// `close()` blocks until all buffered frames are flushed to disk, then
/// disposes the file handle.
///
/// **Thread safety** (`@unchecked Sendable` — manually verified):
/// - The ring is raw storage (`_ringStorage`), not a Swift `[[Float]]`, so
/// concurrent RT-write / BG-read access carries no shared array metadata to
/// race on — only the sample slots, which the frame-counter fence orders.
/// - RT writes to `_ringStorage[ch * _ringSize + ((wHead + i) & _ringMask)]`.
/// BG reads from `_ringStorage[ch * _ringSize + (rHead & _ringMask)]`.
/// The overflow guard (`used + count <= _ringSize`) ensures indices never alias.
/// - `_framesWritten` is stored by RT with `.releasing`; BG loads with `.acquiring`.
/// - `_framesRead` is stored by BG with `.releasing`; RT loads with `.acquiring`.
/// - `_fileRef`, `_rf64Writer`, `_cumulativeFramesWritten`, and
/// `_interleavedWriteBuf` are BG-only after `init`.
///
/// ## Usage
/// ```swift
/// let osc = OscSin.Audio(freq: 440)
/// let diskOut = try DiskOut.Audio(source: osc, channelCount: 1,
/// url: outputURL,
/// sampleRate: engine.sampleRate,
/// format: .wav)
/// final class Writer: SynthesizerBase {
/// override func build() {
/// output(bus: 0, source: diskOut[0]) // pass-through to bus 0
/// }
/// }
/// try engine.add(Writer())
/// try engine.start() // render / play
/// diskOut.close() // flush remaining frames and close the file
/// ```
///
/// - Parameters:
/// - source: Audio source to record and pass through.
/// - channelCount: Number of channels to record and pass through. Must be ≥ 1.
/// - url: Output file path. Created (or overwritten) immediately in `init`.
/// - sampleRate: Sample rate written into the file header. Defaults to 48000 Hz.
/// - format: Container and PCM encoding (``AudioFileFormat``). Defaults to `.aiffFloat32`.
/// - bufferFrames: Ring buffer capacity in frames. Must be a power of two. Defaults to 8192.
/// - mul: Output scale factor. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Audio: GeneratorBase, @unchecked Sendable, AudioGenerator, RootRegistering {
// MARK: - Generator protocol
// MARK: - Public configuration
/// Number of channels recorded and passed through (fixed at init).
public let channelCount: Int
// MARK: - Input
private let _source: any ValidGeneratorInput
// MARK: - Ring buffer (RT writes, BG reads)
/// Contiguous ring storage, channel-major: frame `pos` of channel `ch`
/// lives at `_ringStorage[ch * _ringSize + pos]`.
///
/// RAW memory, deliberately **not** a Swift `[[Float]]`. The RT writer
/// (`_computeSamples`) and the background drainer (`_drainAndWrite`) touch
/// the ring concurrently — at disjoint frame ranges, fenced by the
/// `_framesWritten` / `_framesRead` release-acquire pair. Swift `Array`
/// access is **not** race-free under concurrency even at disjoint indices:
/// the subscript (and any mutating use, e.g. `withUnsafeMutableBufferPointer`,
/// which temporarily empties the array) reads/writes the array's shared
/// storage pointer and CoW / refcount bookkeeping. That shared metadata —
/// not the sample data — was the data race ThreadSanitizer flagged. Raw
/// pointers carry no such metadata, so the frame-counter fence alone makes
/// the handoff correct. Allocated in `init`, freed in `deinit`.
private let _ringStorage: UnsafeMutableBufferPointer<Float>
private let _ringSize: Int // == bufferFrames (power of two)
private let _ringMask: Int // == _ringSize − 1
// Monotonically increasing frame counters — never wrapped (Int64-range safe).
private let _framesWritten: Atomic<Int> = Atomic(0)
private let _framesRead: Atomic<Int> = Atomic(0)
// MARK: - BG write scratch (BG-only after init)
private var _interleavedWriteBuf: [Float]
/// Cumulative frames written to the file across the whole session. BG-only
/// (touched only in `_drainAndWrite`). Drives the large-file guard.
private var _cumulativeFramesWritten: Int = 0
// MARK: - Pass-through output
private var _mulAdd: MulAddSpec
public override var outputChannelCount: Int { channelCount }
// MARK: - BG file state (BG-only after init)
#if canImport(AudioToolbox)
private var _fileRef: ExtAudioFileRef?
/// RF64 backend for the `.rf64Float32` / `.rf64Int24` formats (`ExtAudioFile`
/// can't write RF64). Exactly one of `_fileRef` / `_rf64Writer` is non-nil.
private var _rf64Writer: RF64Writer?
#else
/// Portable WAV backend (off Apple). The WAV encodings stream; the
/// Apple-only containers throw at init.
private var _wavWriter: WavFileWriter?
#endif
/// Output container/encoding — fixed at init. Read by the BG drain's
/// large-file guard (`riffOverflow`); CAF/RF64 are exempt.
private let _outputFormat: AudioFileFormat
private let _backgroundQueue: DispatchQueue
private let _stopped: Atomic<Bool> = Atomic(false)
private let _writeError: Atomic<Bool> = Atomic(false)
private let _fileTooLarge: Atomic<Bool> = Atomic(false)
/// `true` if any `ExtAudioFileWrite` call failed during recording.
/// Poll from a non-RT context after `close()` to detect disk write errors.
public var writeError: Bool { _writeError.load(ordering: .acquiring) }
/// `true` if recording stopped early because the file reached the WAV/AIFF
/// 4 GB container cap (see `lyrebirdMaxRIFFBytes`). Frames past the cap are
/// dropped rather than corrupting the file; audio already written stays
/// valid. Always `false` for `.cafFloat32` (CAF is 64-bit, uncapped). Poll
/// from a non-RT context.
public var fileTooLarge: Bool { _fileTooLarge.load(ordering: .acquiring) }
// MARK: - Init
/// Create a streaming disk recorder.
///
/// The output file is created (or overwritten) immediately in `init`.
///
/// - Parameters:
/// - source: Audio source to record. For multi-channel recording, pass a
/// multi-channel generator; individual channels can be selected with the
/// `[n]` subscript before passing here.
/// - channelCount: Number of channels to record and pass through.
/// - url: Output file path. Created or overwritten immediately.
/// - sampleRate: Engine sample rate written into the file header. Defaults
/// to 48 000 Hz.
/// - format: Container and PCM encoding. Defaults to `.aiffFloat32`.
/// - bufferFrames: Ring buffer capacity 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: ``DiskOutError`` on file-create/format failure for the
/// `ExtAudioFile`-backed formats. For the `.rf64*` formats, a
/// ``RF64WriterError`` may surface instead.
public init(
source: any ValidGeneratorInput,
channelCount: Int,
url: URL,
sampleRate: Double = 48000,
format: AudioFileFormat = .aiffFloat32,
bufferFrames: Int = 8192,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) throws {
precondition(channelCount >= 1,
"DiskOut.Audio: channelCount must be >= 1")
precondition(
bufferFrames > 0 && bufferFrames & (bufferFrames - 1) == 0,
"DiskOut.Audio: bufferFrames \(bufferFrames) must be a power of two"
)
// Streaming a compressed encoder (priming/latency/flush) is out of scope —
// reject before any allocation. AAC / ALAC render offline instead.
guard !format.isCompressed else {
throw DiskOutError.compressedFormatNotSupported(format)
}
let resolvedSource: any ValidGeneratorInput = source._resolvedInput()
self.channelCount = channelCount
self._source = resolvedSource
self._outputFormat = format
self._ringSize = bufferFrames
self._ringMask = bufferFrames - 1
let ringCapacity: Int = bufferFrames * channelCount
_ringStorage = UnsafeMutableBufferPointer<Float>.allocate(capacity: ringCapacity)
_ringStorage.initialize(repeating: 0)
_interleavedWriteBuf = [Float](repeating: 0,
count: bufferFrames * channelCount)
_mulAdd = MulAddSpec(mul: mul, add: add)
_backgroundQueue = DispatchQueue(label: "com.lyrebird.diskout",
qos: .userInitiated)
// Create the output file. RF64 (64-bit WAV) goes through RF64Writer;
// everything else through ExtAudioFile. Client samples are always native
// Float32 interleaved — ExtAudioFile handles Float32 → int16/int24, and
// RF64Writer handles Float32 → RF64 float/int24, transparently.
#if canImport(AudioToolbox)
if format.usesRF64Writer {
do {
_rf64Writer = try RF64Writer(
url: url, format: format, sampleRate: sampleRate, channels: channelCount
)
} catch {
// Pre-`super.init()` throw — `deinit` won't run; free the ring.
// Rethrow the RF64WriterError directly (init throws are untyped).
_ringStorage.deallocate()
throw error
}
} else {
var fileFmt: AudioStreamBasicDescription =
format.makeFileASBD(sampleRate: sampleRate, channels: channelCount)
var rawRef: ExtAudioFileRef?
let createStatus: OSStatus = ExtAudioFileCreateWithURL(
url as CFURL,
format.audioFileTypeID,
&fileFmt,
nil,
AudioFileFlags.eraseFile.rawValue,
&rawRef
)
guard createStatus == noErr, let rawRef: ExtAudioFileRef else {
// These guards throw before `super.init()`, so `deinit` will not
// run — free the raw ring storage explicitly or it leaks. (The
// former `[[Float]]` ring was ARC-managed and torn down here for
// free; raw memory is not.)
_ringStorage.deallocate()
throw DiskOutError.cannotCreateFile(createStatus)
}
_fileRef = rawRef
// Client format is always Float32 interleaved, regardless of the file
// encoding. ExtAudioFile converts float→int when writing to the file.
var clientFmt: AudioStreamBasicDescription =
format.makeClientASBD(sampleRate: sampleRate, channels: channelCount)
let setFmtStatus: OSStatus = ExtAudioFileSetProperty(
rawRef,
kExtAudioFileProperty_ClientDataFormat,
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
&clientFmt
)
guard setFmtStatus == noErr else {
ExtAudioFileDispose(rawRef)
_fileRef = nil
// Pre-`super.init()` throw — `deinit` won't run; free the ring.
_ringStorage.deallocate()
throw DiskOutError.cannotSetFormat(setFmtStatus)
}
}
#else
// Portable WAV backend. Off Apple, only the WAV encodings stream.
do {
let encoding: WavEncoding = try DiskOut.wavEncoding(for: format)
_wavWriter = try WavFileWriter(
url: url, channels: channelCount, sampleRate: sampleRate, encoding: encoding
)
} catch {
// Pre-`super.init()` throw — `deinit` won't run; free the ring.
_ringStorage.deallocate()
throw error
}
#endif
super.init(channels: channelCount)
_startBGLoop()
_registerAsRootIfBuilding()
}
// MARK: - Language-side API
/// Flush all buffered frames to disk and close the file.
///
/// Call this after removing the containing synthesizer from the engine so
/// that the RT thread is no longer writing to the ring buffer. `close()`
/// blocks until the background flush completes, then disposes the file handle.
public func close() {
guard !_stopped.load(ordering: .acquiring) else { return }
_stopped.store(true, ordering: .releasing)
_backgroundQueue.sync { } // wait for BG poll loop to exit and final drain
#if canImport(AudioToolbox)
if let ref: ExtAudioFileRef = _fileRef {
ExtAudioFileDispose(ref)
_fileRef = nil
}
if let writer: RF64Writer = _rf64Writer {
// Patch the ds64 sizes and close. A failure here means the size fields
// stay unpatched; surface it via the same flag as write errors.
do { try writer.close() } catch { _writeError.store(true, ordering: .releasing) }
_rf64Writer = nil
}
#else
if let writer: WavFileWriter = _wavWriter {
do { try writer.finalize() } catch { _writeError.store(true, ordering: .releasing) }
_wavWriter = nil
}
#endif
}
deinit {
if !_stopped.load(ordering: .acquiring) {
_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) }
// RF64Writer.close() patches the ds64 sizes; its own deinit is a
// best-effort fallback, but call it here so a forgotten close() still
// finalises the file. Safe for the same no-concurrent-BG reason above.
try? _rf64Writer?.close()
#else
try? _wavWriter?.finalize()
#endif
}
// Free the raw ring storage. Safe here for the same reason the file
// disposal is: the BG loop upgrades its `[weak self]` to a strong
// reference for the whole iteration, so `deinit` cannot run while
// `_drainAndWrite` is mid-read of the ring.
_ringStorage.deallocate()
}
// MARK: - Background internals
private func _startBGLoop() {
// BG polls _framesWritten rather than blocking on a semaphore. Calling
// DispatchSemaphore.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 ring-buffer fill time
_backgroundQueue.async { [weak self] in
while true {
guard let self: DiskOut.Audio else { return }
if self._stopped.load(ordering: .acquiring) {
self._drainAndWrite() // flush remaining frames before exit
return
}
self._drainAndWrite()
Thread.sleep(forTimeInterval: pollInterval)
}
}
}
/// Read all available ring buffer frames, interleave, and write to file.
/// Called exclusively from the BG thread.
private func _drainAndWrite() {
let rHead: Int = _framesRead.load(ordering: .relaxed)
let wHead: Int = _framesWritten.load(ordering: .acquiring)
let available: Int = wHead - rHead
#if canImport(AudioToolbox)
guard available > 0, (_fileRef != nil || _rf64Writer != nil) else { return }
#else
guard available > 0, _wavWriter != nil else { return }
#endif
// Once the file has hit the container cap, discard remaining frames
// without writing (keeps the ring draining so the RT side never stalls).
if _fileTooLarge.load(ordering: .acquiring) {
_framesRead.store(rHead + available, ordering: .releasing)
return
}
// Drain in chunks no larger than the interleaved write buffer capacity.
let chunkFrames: Int = _interleavedWriteBuf.count / channelCount // == _ringSize
var totalDrained: Int = 0
while totalDrained < available {
let toWrite: Int = min(chunkFrames, available - totalDrained)
// Large-file guard: for WAV/AIFF (32-bit-sized), stop before a write
// that would push the file past the 4 GB cap. CAF → riffOverflow nil,
// so this is a no-op for the default streaming format.
if _outputFormat.riffOverflow(
frameCount: _cumulativeFramesWritten + toWrite, channels: channelCount
) != nil {
_fileTooLarge.store(true, ordering: .releasing)
break
}
for f: Int in 0..<toWrite {
let pos: Int = (rHead + totalDrained + f) & _ringMask
for ch: Int in 0..<channelCount {
_interleavedWriteBuf[f * channelCount + ch] = _ringStorage[ch * _ringSize + pos]
}
}
#if canImport(AudioToolbox)
if let rf64Writer: RF64Writer = _rf64Writer {
_interleavedWriteBuf.withUnsafeBufferPointer { ptr in
do { try rf64Writer.writeFloat32Interleaved(ptr, frames: toWrite) }
catch { _writeError.store(true, ordering: .releasing) }
}
} else if let fileRef: ExtAudioFileRef = _fileRef {
_interleavedWriteBuf.withUnsafeMutableBufferPointer { ptr in
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
let frames: UInt32 = UInt32(toWrite)
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(channelCount),
mDataByteSize: UInt32(
toWrite * channelCount * MemoryLayout<Float>.size),
mData: base
)
)
let writeStatus: OSStatus = ExtAudioFileWrite(fileRef, frames, &bufList)
if writeStatus != noErr {
_writeError.store(true, ordering: .releasing)
}
}
}
#else
if let wavWriter: WavFileWriter = _wavWriter {
do { try wavWriter.write(interleaved: _interleavedWriteBuf, frames: toWrite) }
catch { _writeError.store(true, ordering: .releasing) }
}
#endif
_cumulativeFramesWritten += toWrite
totalDrained += toWrite
}
// Advance the read head by everything that was available — including any
// frames skipped after an overflow break — so the ring keeps draining.
_framesRead.store(rHead + available, ordering: .releasing)
}
// 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)
guard count > 0 else { return _result }
let inputSamples: [[Double]] = _source.calculatedSamples(graph: graph, count: count)
let inputChannels: Int = inputSamples.count
// Hoist block-invariant state. `_ringMask = _ringSize - 1`
// so `idx & _ringMask` is the canonical fast wrap on the PoT ring.
let mask: Int = _ringMask
let chCount: Int = channelCount
let wHead: Int = _framesWritten.load(ordering: .relaxed)
let rHead: Int = _framesRead.load(ordering: .acquiring)
let used: Int = wHead - rHead
let canWrite: Bool = used + count <= _ringSize
// Mono fast path — dominant case for streaming recorders. Single per-sample
// loop fuses ring-buffer write with `_result` pass-through, both lifted to
// raw pointers. Channel 0 of the ring is `_ringStorage`'s base (offset 0);
// the input row enters the closure tree only when present — no RT-path heap
// allocation in the degenerate `inputChannels == 0` branch.
if chCount == 1 {
guard let rbP: UnsafeMutablePointer<Float> = _ringStorage.baseAddress else {
for i: Int in 0..<count { _result[0][i] = 0 }
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
if inputChannels > 0 {
inputSamples[0].withUnsafeBufferPointer { (src: UnsafeBufferPointer<Double>) in
guard let p: UnsafePointer<Double> = src.baseAddress else {
// Empty input row — fall through to the silence branch below.
if canWrite {
for i: Int in 0..<count {
rbP[(wHead + i) & mask] = 0
dstP[i] = 0
}
} else {
for i: Int in 0..<count { dstP[i] = 0 }
}
return
}
let n: Int = src.count
if canWrite {
for i: Int in 0..<count {
let v: Double = i < n ? p[i] : 0
rbP[(wHead + i) & mask] = Float(v)
dstP[i] = v
}
} else {
// Ring full — drop ring writes, still pass through.
for i: Int in 0..<count {
dstP[i] = i < n ? p[i] : 0
}
}
}
} else {
// No input row at all: write silence to ring + result.
if canWrite {
for i: Int in 0..<count {
rbP[(wHead + i) & mask] = 0
dstP[i] = 0
}
} else {
for i: Int in 0..<count { dstP[i] = 0 }
}
}
}
if canWrite {
_framesWritten.store(wHead + count, ordering: .releasing)
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
// Multi-channel general path. Fused ring-write + passthrough; channel-count
// mismatch (`ch >= inputChannels`) writes silence in that row. Raw-pointer
// hoist of per-channel `[[Float]]` ring rows / `[[Double]]` result rows
// would require chCount-deep closure nesting; kept on the bounds-checked
// path for now (multi-channel disk recording is the less-common case).
if canWrite {
for i: Int in 0..<count {
let pos: Int = (wHead + i) & mask
for ch: Int in 0..<chCount {
let v: Double = ch < inputChannels ? inputSamples[ch][i] : 0
_ringStorage[ch * _ringSize + pos] = Float(v)
_result[ch][i] = v
}
}
_framesWritten.store(wHead + count, ordering: .releasing)
} else {
// Ring full — drop ring writes, still pass through.
for i: Int in 0..<count {
for ch: Int in 0..<chCount {
_result[ch][i] = ch < inputChannels ? inputSamples[ch][i] : 0
}
}
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
}
// GeneratorEnum conformance intentionally omitted — Audio-only.