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>
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
// calsa-shim.h
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
//
|
||||
// Single include point for the ALSA C library (libasound), used by
|
||||
// ALSAAudioDriver on Linux. Kept as a shim header rather than pointing the
|
||||
// module map straight at <alsa/asoundlib.h> so the include path resolves the
|
||||
// same way regardless of where the distribution installs the ALSA headers.
|
||||
|
||||
#ifndef LYREBIRD_CALSA_SHIM_H
|
||||
#define LYREBIRD_CALSA_SHIM_H
|
||||
|
||||
#include <alsa/asoundlib.h>
|
||||
|
||||
#endif /* LYREBIRD_CALSA_SHIM_H */
|
||||
@@ -0,0 +1,5 @@
|
||||
module CALSA [system] {
|
||||
header "include/calsa-shim.h"
|
||||
link "asound"
|
||||
export *
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
@@ -40,3 +41,4 @@ public struct LyrebirdAUFactoryPreset: Sendable {
|
||||
self.sourceSlots = sourceSlots
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
@@ -26,3 +27,4 @@ public struct LyrebirdAUParameterEntry {
|
||||
/// and to write new values via `_writeAtomicValue`.
|
||||
public let node: any LiveParameterValue
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import AudioToolbox
|
||||
@@ -74,3 +75,4 @@ public let lyrebirdAUParameterDefaultFlags: AudioUnitParameterOptions = [
|
||||
.flag_IsWritable,
|
||||
.flag_CanRamp,
|
||||
]
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import AudioToolbox
|
||||
@@ -100,3 +101,4 @@ public enum LyrebirdAUParameterMapping {
|
||||
return (tree, nodes)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
@@ -118,3 +119,4 @@ public enum LyrebirdAUPresetSourceRegistry {
|
||||
return _factories.keys.sorted()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
@@ -136,3 +137,4 @@ public final class LyrebirdAUVoicePoolBinding<S: SynthesizerBase> {
|
||||
/// `Double(velocity) / Double(midiVelocityMax)` yields the conventional `[0,1]`
|
||||
/// range used by `@LiveParam` amplitude parameters.
|
||||
public let midiVelocityMax: UInt8 = 127
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import AudioToolbox
|
||||
@@ -721,3 +722,4 @@ public let lyrebirdAUFullStateSourcesKey: String = "sources"
|
||||
/// Sub-key inside the root payload that holds the per-parameter source-slot
|
||||
/// generator type IDs: `[paramName: presetTypeID]`.
|
||||
public let lyrebirdAUFullStateSourceTypesKey: String = "sourceTypes"
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,648 @@
|
||||
// ALSAAudioDriver.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Linux live audio. `CALSA` (libasound) is only a dependency of `LyrebirdSynth`
|
||||
// on Linux — see Package.swift — so on Apple platforms this file compiles away
|
||||
// entirely and `CoreAudioDriver` / `iOSAudioDriver` remain the only RT drivers.
|
||||
#if canImport(CALSA)
|
||||
import CALSA
|
||||
import Foundation
|
||||
import Synchronization
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
/// A real-time ALSA driver that connects a ``SynthesisEngine`` to Linux audio
|
||||
/// hardware.
|
||||
///
|
||||
/// The transport is a blocking `snd_pcm_writei` loop on a dedicated thread —
|
||||
/// the simplest shape that is correct: no callback re-entrancy, no ALSA async
|
||||
/// handler restrictions, and back-pressure comes for free from the device.
|
||||
/// Every buffer is allocated in ``setup(engine:)``, so the loop body itself
|
||||
/// performs no allocation.
|
||||
///
|
||||
/// **Typical usage**:
|
||||
/// ```swift
|
||||
/// let driver = ALSAAudioDriver()
|
||||
/// let engine = SynthesisEngine(
|
||||
/// blockSize: 512, sampleRate: 44100,
|
||||
/// numOutputChannels: 2, numInputChannels: 0,
|
||||
/// driver: driver
|
||||
/// )
|
||||
/// try engine.start()
|
||||
/// // … audio running …
|
||||
/// engine.stop()
|
||||
/// ```
|
||||
///
|
||||
/// **Duplex** — when the engine requests input channels, a capture PCM is
|
||||
/// opened as well and `snd_pcm_link` ties the two streams to one clock so they
|
||||
/// cannot drift. If the device pair refuses to link, the driver still runs
|
||||
/// (read-then-write ordering keeps them approximately aligned) and reports it
|
||||
/// through ``linkedStreams``.
|
||||
///
|
||||
/// **Sample format** — `SND_PCM_FORMAT_FLOAT_LE`, matching the engine's `Float`
|
||||
/// buses exactly, so no conversion or dithering happens anywhere in the path.
|
||||
/// ALSA converts to the hardware's own format underneath.
|
||||
///
|
||||
/// > Note: this driver has been verified to build and to fail cleanly with no
|
||||
/// > sound device present; it has not yet been run against real Linux audio
|
||||
/// > hardware. See LINUX_PLAN.md.
|
||||
public final class ALSAAudioDriver: AudioDriver, @unchecked Sendable {
|
||||
|
||||
// Unchecked Sendable: every stored property is written either in `init` or
|
||||
// in `setup`/`start` before the render thread exists, and read-only
|
||||
// afterwards, except `_isRunning` / `_hasRealtimePriority` (atomic) and
|
||||
// `_lastError` (mutex), which the render thread writes while it runs.
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// ALSA device name for playback. `"default"` follows the user's
|
||||
/// `~/.asoundrc` / system configuration, which is what a desktop app wants;
|
||||
/// `"hw:0,0"` addresses a card directly and bypasses dmix.
|
||||
public var device: String = "default"
|
||||
|
||||
/// ALSA device name for capture. Used only when the engine requests input
|
||||
/// channels.
|
||||
public var captureDevice: String = "default"
|
||||
|
||||
/// Ring-buffer depth as a multiple of the engine's block size. Larger
|
||||
/// tolerates more scheduling jitter at the cost of latency.
|
||||
public var periodsPerBuffer: Int = defaultPeriodsPerBuffer
|
||||
|
||||
/// When `true`, ALSA resamples if the hardware cannot do the engine's rate.
|
||||
/// When `false`, a rate the device cannot produce is an error instead of a
|
||||
/// silent quality loss.
|
||||
public var allowSoftwareResampling: Bool = false
|
||||
|
||||
/// When `true`, the render thread asks for `SCHED_FIFO`. Failure is not
|
||||
/// fatal — unprivileged processes normally cannot get it, and the driver
|
||||
/// runs at normal priority instead (see ``hasRealtimePriority``).
|
||||
public var requestsRealtimePriority: Bool = true
|
||||
|
||||
// MARK: - Status
|
||||
|
||||
/// Whether `SCHED_FIFO` was actually granted to the render thread.
|
||||
///
|
||||
/// Set by the render thread itself, after `start()` has already returned,
|
||||
/// so it is atomic rather than a plain `var` — a caller polling it right
|
||||
/// after `start()` would otherwise race the write.
|
||||
public var hasRealtimePriority: Bool { _hasRealtimePriority.load(ordering: .acquiring) }
|
||||
|
||||
/// Whether capture and playback were successfully clock-linked. Always
|
||||
/// `false` when the engine requests no input channels.
|
||||
public private(set) var linkedStreams: Bool = false
|
||||
|
||||
/// The error that ended the render loop, if it ended on its own.
|
||||
///
|
||||
/// Written by the render thread as it exits and read from wherever `stop()`
|
||||
/// is called, so it is behind a mutex — the lock is only ever taken on the
|
||||
/// failure path and by callers, never in the steady-state loop.
|
||||
public var lastError: ALSAError? { _lastError.withLock { $0 } }
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Four periods is the usual desktop compromise: enough slack that an
|
||||
/// ordinary scheduling hiccup does not underrun, short enough to stay
|
||||
/// playable.
|
||||
private static let defaultPeriodsPerBuffer: Int = 4
|
||||
private static let microsecondsPerSecond: Double = 1_000_000
|
||||
/// `SCHED_FIFO` priority as a fraction of the policy's usable range. Well
|
||||
/// clear of the top so a runaway render loop cannot lock out the kernel's
|
||||
/// own high-priority threads.
|
||||
private static let realtimePriorityFraction: Double = 0.75
|
||||
/// How long `stop()` waits for the render thread to leave its loop before
|
||||
/// closing the PCM handles anyway.
|
||||
private static let threadJoinTimeout: TimeInterval = 2.0
|
||||
/// `snd_pcm_recover` argument: 1 silences its own logging to stderr.
|
||||
private static let recoverSilently: Int32 = 1
|
||||
/// How long `snd_pcm_wait` blocks for the device to become writable again
|
||||
/// after a would-block return, in milliseconds. Waiting beats spinning: the
|
||||
/// render thread may hold `SCHED_FIFO`, where a busy loop starves the box.
|
||||
private static let deviceWaitMilliseconds: Int32 = 200
|
||||
/// Consecutive no-progress transfers (would-block, or zero frames moved)
|
||||
/// tolerated before the stream is declared dead. At the wait above this is
|
||||
/// ~2 s of a device that never becomes ready, which no working
|
||||
/// configuration does.
|
||||
@_spi(LyrebirdExtensions)
|
||||
public static let maxConsecutiveStalls: Int = 10
|
||||
/// Consecutive signal interruptions tolerated. Far larger than the stall
|
||||
/// budget because a signal says nothing about the device's health — this is
|
||||
/// a bound only so a pathological signal source cannot spin the loop.
|
||||
private static let maxConsecutiveInterrupts: Int = 1000
|
||||
|
||||
// MARK: - State
|
||||
|
||||
private var playbackPCM: OpaquePointer?
|
||||
private var capturePCM: OpaquePointer?
|
||||
|
||||
private var engineRef: Unmanaged<SynthesisEngine>?
|
||||
private var blockSize: Int = 0
|
||||
private var sampleRate: Double = 0
|
||||
private var outputChannels: Int = 0
|
||||
private var inputChannels: Int = 0
|
||||
|
||||
/// Interleaved staging buffers handed to ALSA. Raw pointers rather than
|
||||
/// arrays so their addresses are stable for the thread's lifetime.
|
||||
private var interleavedOutput: UnsafeMutablePointer<Float>?
|
||||
private var interleavedInput: UnsafeMutablePointer<Float>?
|
||||
|
||||
/// Planar input handed to `processBlock`, pre-allocated so the loop never
|
||||
/// grows it.
|
||||
private var inputStagingBuffers: [[Float]] = []
|
||||
|
||||
private let _isRunning: Atomic<Bool> = Atomic<Bool>(false)
|
||||
private let _hasRealtimePriority: Atomic<Bool> = Atomic<Bool>(false)
|
||||
/// Set when a `stop()` gave up waiting for the render thread. The thread is
|
||||
/// still out there, still testing `_isRunning`, so the driver must never
|
||||
/// start another one: a wedged transfer that finally returns would find the
|
||||
/// flag true again and resume rendering alongside its replacement.
|
||||
private let _abandonedThread: Atomic<Bool> = Atomic<Bool>(false)
|
||||
private let _lastError: Mutex<ALSAError?> = Mutex<ALSAError?>(nil)
|
||||
private var renderThread: Thread?
|
||||
private let threadExited: DispatchSemaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
public init() {
|
||||
// Initialise the RT-identity TLS key from this known non-RT call site,
|
||||
// so the render thread's first `markCurrentThreadAsRT()` cannot be the
|
||||
// allocating one.
|
||||
RTThreadIdentity.warmUp()
|
||||
}
|
||||
|
||||
deinit {
|
||||
stop()
|
||||
// Belt and braces: `Thread { [weak self] in self?.renderLoop(...) }`
|
||||
// holds `self` strongly for the whole call, so `deinit` cannot actually
|
||||
// run while an abandoned loop is still inside it. If that ever changes,
|
||||
// freeing these buffers would be a use-after-free, so the guard stays.
|
||||
guard !_abandonedThread.load(ordering: .acquiring) else { return }
|
||||
interleavedOutput?.deallocate()
|
||||
interleavedInput?.deallocate()
|
||||
}
|
||||
|
||||
/// ALSA's period granularity is the engine block, so control-rate
|
||||
/// resolution matches the other live drivers.
|
||||
public var suggestedControlBlockSize: Int? { lyrebirdDefaultControlBlockSize }
|
||||
|
||||
// MARK: - AudioDriver
|
||||
|
||||
public func setup(engine: SynthesisEngine) throws {
|
||||
guard !_abandonedThread.load(ordering: .acquiring) else {
|
||||
// Reallocating the staging buffers would pull them out from under
|
||||
// the thread that never came back.
|
||||
throw ALSAError.renderThreadDidNotExit
|
||||
}
|
||||
engineRef = Unmanaged.passUnretained(engine)
|
||||
blockSize = engine.blockSize
|
||||
sampleRate = engine.sampleRate
|
||||
outputChannels = engine.numOutputChannels
|
||||
inputChannels = engine.numInputChannels
|
||||
|
||||
interleavedOutput?.deallocate()
|
||||
interleavedOutput = UnsafeMutablePointer<Float>.allocate(
|
||||
capacity: blockSize * max(outputChannels, 1)
|
||||
)
|
||||
interleavedOutput?.initialize(repeating: 0, count: blockSize * max(outputChannels, 1))
|
||||
|
||||
interleavedInput?.deallocate()
|
||||
interleavedInput = nil
|
||||
inputStagingBuffers = []
|
||||
if inputChannels > 0 {
|
||||
let inputPointer: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(
|
||||
capacity: blockSize * inputChannels
|
||||
)
|
||||
inputPointer.initialize(repeating: 0, count: blockSize * inputChannels)
|
||||
interleavedInput = inputPointer
|
||||
inputStagingBuffers = [[Float]](
|
||||
repeating: [Float](repeating: 0, count: blockSize),
|
||||
count: inputChannels
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
public func start() throws {
|
||||
guard engineRef != nil, blockSize > 0 else { throw ALSAError.notConfigured }
|
||||
guard !_abandonedThread.load(ordering: .acquiring) else {
|
||||
// A previous render thread never came back. Starting a second one
|
||||
// would put two threads on one engine the moment the first unwedges.
|
||||
throw ALSAError.renderThreadDidNotExit
|
||||
}
|
||||
guard !_isRunning.load(ordering: .acquiring) else { return }
|
||||
|
||||
// A loop that ended on its own leaves a finished thread and a signalled
|
||||
// semaphore behind; clear them before starting another.
|
||||
if renderThread != nil { stop() }
|
||||
// That `stop()` can itself time out and latch — re-check, or the exact
|
||||
// state the latch exists to prevent gets created a few lines below.
|
||||
guard !_abandonedThread.load(ordering: .acquiring) else {
|
||||
throw ALSAError.renderThreadDidNotExit
|
||||
}
|
||||
|
||||
_lastError.withLock { $0 = nil }
|
||||
do {
|
||||
try openPlayback()
|
||||
if inputChannels > 0 {
|
||||
try openCapture()
|
||||
}
|
||||
} catch {
|
||||
// Never leave a half-open device: a playback handle that opened
|
||||
// before capture failed would otherwise stay claimed until deinit.
|
||||
closeDevices()
|
||||
throw error
|
||||
}
|
||||
|
||||
// Drain a stale signal from a previous run that timed out in `stop()`
|
||||
// and whose thread signalled afterwards; leaving it pending would make
|
||||
// the next `stop()` return from its wait immediately.
|
||||
while threadExited.wait(timeout: .now()) == .success {}
|
||||
|
||||
_hasRealtimePriority.store(false, ordering: .releasing)
|
||||
_isRunning.store(true, ordering: .releasing)
|
||||
|
||||
// The engine is held unowned for the driver's normal life (it owns the
|
||||
// driver, so retaining it back would be a cycle), but the render thread
|
||||
// must not outlive it — and an abandoned thread can, since nothing can
|
||||
// stop it. Retain for exactly the thread's lifetime: the loop's `defer`
|
||||
// releases, so a thread that never returns pins the engine forever,
|
||||
// which is the point.
|
||||
//
|
||||
// `retain()` bumps the pointee's count without ever materialising a
|
||||
// Swift reference — `takeUnretainedValue()` on a since-freed engine
|
||||
// would be undefined behaviour, not a recoverable `nil`. `engineRef` is
|
||||
// already known non-nil (checked at the top of `start()`).
|
||||
guard let engineUnmanaged: Unmanaged<SynthesisEngine> = engineRef else {
|
||||
_isRunning.store(false, ordering: .releasing)
|
||||
throw ALSAError.notConfigured
|
||||
}
|
||||
// Carried across the thread boundary as a bit pattern: `Thread`'s
|
||||
// closure is `@Sendable`, and neither `Unmanaged` nor a raw pointer is
|
||||
// Sendable under Swift 6 — the same reason `SynthesizerBase` stores its
|
||||
// engine binding as an `Atomic<UInt>`. The retain is real; the loop's
|
||||
// `defer` releases it.
|
||||
let engineBits: UInt = Self.retainForRenderThread(engineUnmanaged)
|
||||
let thread: Thread = Thread { [weak self] in
|
||||
guard let self: ALSAAudioDriver = self else {
|
||||
Self.releaseEngine(bits: engineBits)
|
||||
return
|
||||
}
|
||||
self.renderLoop(engineBits: engineBits)
|
||||
}
|
||||
thread.name = "lyrebird.alsa.render"
|
||||
renderThread = thread
|
||||
thread.start()
|
||||
}
|
||||
|
||||
public func stop() {
|
||||
// Already abandoned: that thread is gone as far as this driver is
|
||||
// concerned and its resources are deliberately leaked, so `renderThread`
|
||||
// must not be touched again. A `deinit`-driven `stop()` can run on the
|
||||
// render thread itself once a wedged transfer finally returns, which
|
||||
// would race the original `stop()`'s write from the caller's thread.
|
||||
guard !_abandonedThread.load(ordering: .acquiring) else { return }
|
||||
|
||||
_isRunning.store(false, ordering: .releasing)
|
||||
guard renderThread != nil else {
|
||||
closeDevices()
|
||||
return
|
||||
}
|
||||
// Join whenever a thread was launched — including one that already
|
||||
// exited on its own error path. Closing the PCM handles while the
|
||||
// thread could still touch them is a use-after-free, so the wait is not
|
||||
// conditional on the running flag. The loop tests the flag once per
|
||||
// block and so leaves within roughly one block period.
|
||||
let exited: Bool = threadExited.wait(timeout: .now() + Self.threadJoinTimeout) == .success
|
||||
renderThread = nil
|
||||
guard exited else {
|
||||
// The thread is stuck inside a transfer. Closing its PCM handles or
|
||||
// freeing the buffers it is reading would be exactly the
|
||||
// use-after-free the join exists to prevent, so abandon them
|
||||
// instead: a leak is recoverable, a wild write is not. The handles
|
||||
// stay open until the process exits, so a subsequent `start()` may
|
||||
// fail with the device busy — which is the truth, and better than
|
||||
// pretending the stop succeeded.
|
||||
// Nothing is written here on purpose. The thread that owns these
|
||||
// handles and buffers is still alive and still reading them; the
|
||||
// abandon latch is what keeps every later path — `closeDevices()`,
|
||||
// `deinit`, a second `start()` — from touching them. Clearing the
|
||||
// properties would be its own data race, on top of the
|
||||
// use-after-free the join exists to prevent.
|
||||
_lastError.withLock { $0 = .renderThreadDidNotExit }
|
||||
_abandonedThread.store(true, ordering: .releasing)
|
||||
return
|
||||
}
|
||||
closeDevices()
|
||||
}
|
||||
|
||||
// MARK: - Device setup
|
||||
|
||||
private func openPlayback() throws {
|
||||
var pcm: OpaquePointer?
|
||||
let openResult: Int32 = snd_pcm_open(&pcm, device, SND_PCM_STREAM_PLAYBACK, 0)
|
||||
guard openResult >= 0, let handle: OpaquePointer = pcm else {
|
||||
throw ALSAError.playbackDeviceOpenFailed(device: device, code: Int(openResult))
|
||||
}
|
||||
playbackPCM = handle
|
||||
try configure(handle, channels: outputChannels, stream: "playback")
|
||||
}
|
||||
|
||||
private func openCapture() throws {
|
||||
var pcm: OpaquePointer?
|
||||
let openResult: Int32 = snd_pcm_open(&pcm, captureDevice, SND_PCM_STREAM_CAPTURE, 0)
|
||||
guard openResult >= 0, let handle: OpaquePointer = pcm else {
|
||||
throw ALSAError.captureDeviceOpenFailed(device: captureDevice, code: Int(openResult))
|
||||
}
|
||||
capturePCM = handle
|
||||
try configure(handle, channels: inputChannels, stream: "capture")
|
||||
|
||||
// One clock for both streams — without this, two independently clocked
|
||||
// devices drift and the loop eventually blocks on one of them.
|
||||
if let playback: OpaquePointer = playbackPCM {
|
||||
linkedStreams = snd_pcm_link(handle, playback) >= 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies format, access mode, rate, channel count, and latency in one
|
||||
/// call. `snd_pcm_set_params` is ALSA's own convenience over the hw/sw
|
||||
/// params dance and negotiates a period for the requested latency.
|
||||
private func configure(_ pcm: OpaquePointer, channels: Int, stream: String) throws {
|
||||
let latencySeconds: Double =
|
||||
Double(blockSize * periodsPerBuffer) / sampleRate
|
||||
let latencyMicroseconds: UInt32 = UInt32(latencySeconds * Self.microsecondsPerSecond)
|
||||
let softResample: Int32 = allowSoftwareResampling ? 1 : 0
|
||||
|
||||
let paramResult: Int32 = snd_pcm_set_params(
|
||||
pcm,
|
||||
SND_PCM_FORMAT_FLOAT_LE,
|
||||
SND_PCM_ACCESS_RW_INTERLEAVED,
|
||||
UInt32(channels),
|
||||
UInt32(sampleRate),
|
||||
softResample,
|
||||
latencyMicroseconds
|
||||
)
|
||||
guard paramResult >= 0 else {
|
||||
throw ALSAError.parameterNegotiationFailed(stream: stream, code: Int(paramResult))
|
||||
}
|
||||
|
||||
let prepareResult: Int32 = snd_pcm_prepare(pcm)
|
||||
guard prepareResult >= 0 else {
|
||||
throw ALSAError.prepareFailed(stream: stream, code: Int(prepareResult))
|
||||
}
|
||||
}
|
||||
|
||||
private func closeDevices() {
|
||||
// A thread we gave up waiting for still owns these handles. Closing
|
||||
// them out from under it is the use-after-free this whole path exists
|
||||
// to avoid; they stay open until the process exits.
|
||||
guard !_abandonedThread.load(ordering: .acquiring) else { return }
|
||||
if let capture: OpaquePointer = capturePCM {
|
||||
// Unlink before closing so a restart can link a fresh pair.
|
||||
if linkedStreams { snd_pcm_unlink(capture) }
|
||||
snd_pcm_drop(capture)
|
||||
snd_pcm_close(capture)
|
||||
capturePCM = nil
|
||||
}
|
||||
if let playback: OpaquePointer = playbackPCM {
|
||||
snd_pcm_drop(playback)
|
||||
snd_pcm_close(playback)
|
||||
playbackPCM = nil
|
||||
}
|
||||
linkedStreams = false
|
||||
}
|
||||
|
||||
// MARK: - Render thread
|
||||
|
||||
/// Retains `engine` for the render thread and returns its pointer as a bit
|
||||
/// pattern — the form that survives `Thread`'s `@Sendable` closure boundary.
|
||||
/// Balanced by exactly one ``releaseEngine(bits:)``.
|
||||
///
|
||||
/// Exposed so the retain/release round trip can be pinned by a test: the
|
||||
/// balance across the render loop's exit paths only runs against real
|
||||
/// hardware, and an imbalance here is a leak or a use-after-free.
|
||||
@_spi(LyrebirdExtensions)
|
||||
public static func retainForRenderThread(_ engine: Unmanaged<SynthesisEngine>) -> UInt {
|
||||
UInt(bitPattern: engine.retain().toOpaque())
|
||||
}
|
||||
|
||||
/// Balances one ``retainForRenderThread(_:)``.
|
||||
@_spi(LyrebirdExtensions)
|
||||
public static func releaseEngine(bits: UInt) {
|
||||
guard let pointer: UnsafeMutableRawPointer = UnsafeMutableRawPointer(bitPattern: bits) else { return }
|
||||
Unmanaged<SynthesisEngine>.fromOpaque(pointer).release()
|
||||
}
|
||||
|
||||
private func renderLoop(engineBits: UInt) {
|
||||
guard let enginePointer: UnsafeMutableRawPointer = UnsafeMutableRawPointer(bitPattern: engineBits) else {
|
||||
// Unreachable: `engineBits` is the bit pattern of a live heap
|
||||
// pointer, never 0. Balance the retain anyway so the one path that
|
||||
// does not reach the `defer` below cannot leak the engine.
|
||||
Self.releaseEngine(bits: engineBits)
|
||||
_lastError.withLock { $0 = .renderLoopPreconditionFailed }
|
||||
_isRunning.store(false, ordering: .releasing)
|
||||
threadExited.signal()
|
||||
return
|
||||
}
|
||||
let retainedEngine: Unmanaged<SynthesisEngine> = Unmanaged.fromOpaque(enginePointer)
|
||||
RTThreadIdentity.markCurrentThreadAsRT()
|
||||
enableFlushToZero()
|
||||
if requestsRealtimePriority {
|
||||
_hasRealtimePriority.store(Self.raiseCurrentThreadPriority(), ordering: .releasing)
|
||||
}
|
||||
defer {
|
||||
// Clear the flag on every exit, including the error paths, so the
|
||||
// driver's state matches reality and a later `start()` is not
|
||||
// silently ignored. Signalled last: `stop()` closes the PCM handles
|
||||
// as soon as it sees this, and by then the loop must be done with
|
||||
// them.
|
||||
_isRunning.store(false, ordering: .releasing)
|
||||
// Balances the `passRetained` in `start()`. Reached on every exit
|
||||
// path this loop has; only a thread that never returns keeps the
|
||||
// engine alive, which is exactly the case that needs it.
|
||||
retainedEngine.release()
|
||||
threadExited.signal()
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = retainedEngine.takeUnretainedValue()
|
||||
guard let playback: OpaquePointer = playbackPCM,
|
||||
let output: UnsafeMutablePointer<Float> = interleavedOutput else {
|
||||
// Exiting here produces silence with no other symptom, so record why
|
||||
// rather than letting a driver that never ran look healthy.
|
||||
_lastError.withLock { $0 = .renderLoopPreconditionFailed }
|
||||
return
|
||||
}
|
||||
|
||||
// Read once, before the loop. The abandon path deliberately writes
|
||||
// nothing, but `closeDevices()` does nil these after a clean join, and
|
||||
// hoisting means the loop body does not depend on that ordering
|
||||
// holding at every iteration.
|
||||
let capture: OpaquePointer? = capturePCM
|
||||
let input: UnsafeMutablePointer<Float>? = interleavedInput
|
||||
|
||||
while _isRunning.load(ordering: .acquiring) {
|
||||
if let capture: OpaquePointer = capture,
|
||||
let input: UnsafeMutablePointer<Float> = input {
|
||||
guard transfer(pcm: capture, buffer: input, isCapture: true) else { return }
|
||||
lyrebirdDeinterleave(
|
||||
input,
|
||||
into: &inputStagingBuffers,
|
||||
frameCount: blockSize,
|
||||
channelCount: inputChannels
|
||||
)
|
||||
}
|
||||
|
||||
engine.processBlock(inputSamples: inputStagingBuffers)
|
||||
|
||||
lyrebirdInterleave(
|
||||
engine.audioBuses,
|
||||
into: output,
|
||||
frameCount: blockSize,
|
||||
channelCount: outputChannels
|
||||
)
|
||||
guard transfer(pcm: playback, buffer: output, isCapture: false) else { return }
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves exactly `blockSize` frames in or out, resuming after short
|
||||
/// transfers and recovering from underruns.
|
||||
///
|
||||
/// - Returns: `false` when the stream is unrecoverable or the driver was
|
||||
/// asked to stop, meaning the render loop should exit.
|
||||
private func transfer(
|
||||
pcm: OpaquePointer,
|
||||
buffer: UnsafeMutablePointer<Float>,
|
||||
isCapture: Bool
|
||||
) -> Bool {
|
||||
let channels: Int = isCapture ? inputChannels : outputChannels
|
||||
var framesDone: Int = 0
|
||||
var consecutiveStalls: Int = 0
|
||||
var consecutiveInterrupts: Int = 0
|
||||
|
||||
while framesDone < blockSize {
|
||||
guard _isRunning.load(ordering: .acquiring) else { return false }
|
||||
let cursor: UnsafeMutablePointer<Float> = buffer + framesDone * channels
|
||||
let remaining: UInt = UInt(blockSize - framesDone)
|
||||
let result: Int = isCapture
|
||||
? snd_pcm_readi(pcm, cursor, remaining)
|
||||
: snd_pcm_writei(pcm, cursor, remaining)
|
||||
|
||||
switch ALSARecoveryAction.classify(result) {
|
||||
case .transferred(let frames):
|
||||
framesDone += frames
|
||||
// A zero-frame transfer makes no progress, so it cannot reset
|
||||
// the budget — otherwise a device that keeps returning 0 spins
|
||||
// this loop forever at `SCHED_FIFO`, which is the failure the
|
||||
// budget exists to stop.
|
||||
if frames > 0 {
|
||||
consecutiveStalls = 0
|
||||
consecutiveInterrupts = 0
|
||||
} else if !tolerateStall(result: result, isCapture: isCapture, count: &consecutiveStalls) {
|
||||
return false
|
||||
}
|
||||
case .interrupted:
|
||||
// A signal, not a device problem: reissue without spending the
|
||||
// stall budget, since profilers and interval timers deliver
|
||||
// these to perfectly healthy streams. Still bounded, and with a
|
||||
// yield — a signal source faster than the syscall would
|
||||
// otherwise busy-spin a `SCHED_FIFO` thread with nothing but
|
||||
// `_isRunning` to break out.
|
||||
consecutiveInterrupts += 1
|
||||
guard consecutiveInterrupts <= Self.maxConsecutiveInterrupts else {
|
||||
_lastError.withLock {
|
||||
$0 = .transferFailed(
|
||||
stream: isCapture ? "capture" : "playback",
|
||||
code: result
|
||||
)
|
||||
}
|
||||
return false
|
||||
}
|
||||
sched_yield()
|
||||
continue
|
||||
case .wouldBlock:
|
||||
// A blocking PCM should not return would-block, but a plugin
|
||||
// chain (dmix, a non-blocking `.asoundrc` device) can. Spinning
|
||||
// on it from a `SCHED_FIFO` thread would starve the machine, so
|
||||
// sleep on the device and give up if it never becomes ready.
|
||||
guard tolerateStall(result: result, isCapture: isCapture, count: &consecutiveStalls) else {
|
||||
return false
|
||||
}
|
||||
_ = snd_pcm_wait(pcm, Self.deviceWaitMilliseconds)
|
||||
case .recover:
|
||||
// Underrun or suspend: re-prepare and reissue from the same
|
||||
// frame. The samples already handed over are gone either way.
|
||||
// An xrun moves no frames, so it spends the budget like any
|
||||
// other no-progress result — clearing it here let a device
|
||||
// alternating underruns with would-block returns loop forever.
|
||||
guard tolerateStall(result: result, isCapture: isCapture, count: &consecutiveStalls) else {
|
||||
return false
|
||||
}
|
||||
if snd_pcm_recover(pcm, Int32(result), Self.recoverSilently) < 0 {
|
||||
_lastError.withLock {
|
||||
$0 = .prepareFailed(
|
||||
stream: isCapture ? "capture" : "playback",
|
||||
code: result
|
||||
)
|
||||
}
|
||||
return false
|
||||
}
|
||||
case .fail:
|
||||
_lastError.withLock {
|
||||
$0 = .transferFailed(
|
||||
stream: isCapture ? "capture" : "playback",
|
||||
code: result
|
||||
)
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// Counts one transfer that moved no frames, and reports whether the
|
||||
/// stream has any patience left.
|
||||
///
|
||||
/// - Returns: `false` once the budget is spent, having recorded the error.
|
||||
private func tolerateStall(result: Int, isCapture: Bool, count: inout Int) -> Bool {
|
||||
count += 1
|
||||
guard Self.stallBudgetExhausted(consecutiveStalls: count) else { return true }
|
||||
_lastError.withLock {
|
||||
$0 = .transferFailed(
|
||||
stream: isCapture ? "capture" : "playback",
|
||||
code: result
|
||||
)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// Whether this many consecutive no-progress transfers means the stream is
|
||||
/// dead rather than merely slow.
|
||||
///
|
||||
/// Exposed so the boundary can be pinned by a test: the loop that consults
|
||||
/// it only runs against real hardware, and an off-by-one here either kills
|
||||
/// a healthy stream one attempt early or never gives up at all.
|
||||
@_spi(LyrebirdExtensions)
|
||||
public static func stallBudgetExhausted(consecutiveStalls: Int) -> Bool {
|
||||
consecutiveStalls > maxConsecutiveStalls
|
||||
}
|
||||
|
||||
/// Asks the kernel for `SCHED_FIFO` on the calling thread.
|
||||
///
|
||||
/// - Returns: `true` if granted. Denial is the normal case for an
|
||||
/// unprivileged process and is not an error — audio still runs, just
|
||||
/// without scheduling protection.
|
||||
private static func raiseCurrentThreadPriority() -> Bool {
|
||||
let lowest: Int32 = sched_get_priority_min(SCHED_FIFO)
|
||||
let highest: Int32 = sched_get_priority_max(SCHED_FIFO)
|
||||
guard lowest >= 0, highest > lowest else { return false }
|
||||
let span: Double = Double(highest - lowest)
|
||||
var params: sched_param = sched_param()
|
||||
params.sched_priority = lowest + Int32(span * realtimePriorityFraction)
|
||||
return pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶ms) == 0
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,37 @@
|
||||
// ALSAError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Errors thrown by `ALSAAudioDriver` during setup or start.
|
||||
///
|
||||
/// Every case carries the raw ALSA return code where one exists; pass it to
|
||||
/// `snd_strerror` for the system's own description. Declared unconditionally
|
||||
/// (not behind the Linux guard) so cross-platform code can name the type.
|
||||
public enum ALSAError: Error, Equatable, Sendable {
|
||||
/// `snd_pcm_open` failed for the playback device. Associated values are the
|
||||
/// device name asked for and the ALSA error code.
|
||||
case playbackDeviceOpenFailed(device: String, code: Int)
|
||||
/// `snd_pcm_open` failed for the capture device.
|
||||
case captureDeviceOpenFailed(device: String, code: Int)
|
||||
/// `snd_pcm_set_params` rejected the requested format, rate, channel count,
|
||||
/// or latency for the named stream.
|
||||
case parameterNegotiationFailed(stream: String, code: Int)
|
||||
/// `snd_pcm_prepare` failed — either before the render loop started, or
|
||||
/// when recovering from an underrun inside it.
|
||||
case prepareFailed(stream: String, code: Int)
|
||||
/// A `snd_pcm_writei` / `snd_pcm_readi` transfer failed with an error the
|
||||
/// render loop cannot recover from (device removed, bad descriptor).
|
||||
case transferFailed(stream: String, code: Int)
|
||||
/// `setup(engine:)` was never called, so there is nothing to start.
|
||||
case notConfigured
|
||||
/// The render thread did not leave its loop within the stop timeout —
|
||||
/// almost always a transfer wedged inside the driver. The PCM handles and
|
||||
/// staging buffers are deliberately leaked rather than freed under a thread
|
||||
/// that may still be using them.
|
||||
case renderThreadDidNotExit
|
||||
/// The render loop exited before it could start: the engine reference or a
|
||||
/// staging buffer was missing.
|
||||
case renderLoopPreconditionFailed
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// ALSARecoveryAction.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// What an ALSA PCM transfer's return value tells the render loop to do next.
|
||||
///
|
||||
/// `snd_pcm_writei` / `snd_pcm_readi` return a frame count on success and a
|
||||
/// negative errno on failure, and the correct response differs per error: an
|
||||
/// underrun is routine and recoverable, a signal interruption just needs the
|
||||
/// same call again, and anything else means the device is gone. Getting this
|
||||
/// wrong is how a driver either spins forever or dies on the first xrun. The
|
||||
/// two transient cases are kept apart deliberately: a signal is not a device
|
||||
/// problem and must not consume the patience budget that a device which never
|
||||
/// becomes ready does.
|
||||
///
|
||||
/// The classification is pure arithmetic over the return value, so it is
|
||||
/// tested on every platform even though the driver that consumes it
|
||||
/// (`ALSAAudioDriver`) only compiles on Linux.
|
||||
public enum ALSARecoveryAction: Equatable, Sendable {
|
||||
/// Transfer succeeded. The associated value is the number of frames moved,
|
||||
/// which may be fewer than requested — the caller must resume from there.
|
||||
case transferred(frames: Int)
|
||||
/// A signal interrupted the call (`-EINTR`). Reissue immediately: nothing
|
||||
/// is wrong with the device, and a profiler or interval timer can deliver
|
||||
/// signals indefinitely without the stream being unhealthy.
|
||||
case interrupted
|
||||
/// The device is not ready (`-EAGAIN`). Wait for it, and give up if it
|
||||
/// never becomes ready — this one *is* evidence of a sick stream.
|
||||
case wouldBlock
|
||||
/// Underrun/overrun (`-EPIPE`) or suspend (`-ESTRPIPE`). Call
|
||||
/// `snd_pcm_recover` (or `snd_pcm_prepare`), then reissue.
|
||||
case recover
|
||||
/// Unrecoverable. Surface the error and stop the render thread.
|
||||
case fail
|
||||
|
||||
// Linux errno values, spelled out rather than imported. ALSA is a Linux
|
||||
// API, so these are the numbers it returns wherever this code is compiled;
|
||||
// taking them from the host's `errno.h` instead would make the same input
|
||||
// classify differently on a non-Linux host (`EAGAIN` is 11 on Linux and 35
|
||||
// on Darwin), which would make the tests lie.
|
||||
private static let eintr: Int = 4
|
||||
private static let eagain: Int = 11
|
||||
private static let epipe: Int = 32
|
||||
private static let estrpipe: Int = 86
|
||||
|
||||
/// Classifies the return value of an ALSA PCM transfer call.
|
||||
///
|
||||
/// - Parameter result: Value returned by `snd_pcm_writei` / `snd_pcm_readi`
|
||||
/// — frames transferred when non-negative, negative errno otherwise.
|
||||
/// - Returns: The action the render loop should take.
|
||||
public static func classify(_ result: Int) -> ALSARecoveryAction {
|
||||
if result >= 0 {
|
||||
return .transferred(frames: result)
|
||||
}
|
||||
switch -result {
|
||||
case eintr:
|
||||
return .interrupted
|
||||
case eagain:
|
||||
return .wouldBlock
|
||||
case epipe, estrpipe:
|
||||
return .recover
|
||||
default:
|
||||
return .fail
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
import AVFoundation
|
||||
@@ -510,3 +511,4 @@ public let auv3DriverDefaultMaxFramesToRender: Int = 1024
|
||||
/// the ring. Larger values give more slack for hosts that pull busses
|
||||
/// asynchronously at the cost of memory.
|
||||
public let auv3RingBufferHeadroomFactor: Int = 2
|
||||
#endif
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if canImport(AudioToolbox)
|
||||
import CoreAudio
|
||||
import AudioToolbox
|
||||
import Synchronization
|
||||
@@ -822,3 +823,4 @@ private func lyrebirdRenderCallback(
|
||||
)
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// DefaultAudioDriver.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Returns the live-audio driver for the platform this build targets.
|
||||
///
|
||||
/// Which drivers exist is not a property of the operating system alone — the
|
||||
/// Linux `ALSAAudioDriver` is present only when the build linked libasound
|
||||
/// (see the `LYREBIRD_DISABLE_ALSA` opt-out in `Package.swift`, and note that a
|
||||
/// Linux binary cross-compiled from macOS has no ALSA at all). Only code inside
|
||||
/// this module can see that, so any `#if` written in *consumer* code to pick a
|
||||
/// driver is guessing. Call this instead:
|
||||
///
|
||||
/// ```swift
|
||||
/// let engine = SynthesisEngine(
|
||||
/// blockSize: 512, sampleRate: 44100,
|
||||
/// numOutputChannels: 2, numInputChannels: 0,
|
||||
/// driver: makeDefaultAudioDriver()
|
||||
/// )
|
||||
/// ```
|
||||
///
|
||||
/// Resolution order: `iOSAudioDriver` on iOS, `CoreAudioDriver` on macOS,
|
||||
/// `ALSAAudioDriver` on a Linux build with ALSA, and ``OfflineDriver`` where
|
||||
/// no live backend exists. (`ALSAAudioDriver` is written in code font rather
|
||||
/// than as a symbol link because it does not exist in an Apple build, where
|
||||
/// this documentation is generated.)
|
||||
///
|
||||
/// > Important: the ``OfflineDriver`` fallback runs the graph on demand and
|
||||
/// > produces no sound. Check ``isLiveAudioAvailable`` when silence would be a
|
||||
/// > surprise — for example before printing "now playing" to a user.
|
||||
public func makeDefaultAudioDriver() -> any AudioDriver {
|
||||
#if canImport(AudioToolbox)
|
||||
#if os(iOS)
|
||||
return iOSAudioDriver()
|
||||
#else
|
||||
return CoreAudioDriver()
|
||||
#endif
|
||||
#elseif canImport(CALSA)
|
||||
return ALSAAudioDriver()
|
||||
#else
|
||||
return OfflineDriver()
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Whether this build has a live-audio backend at all.
|
||||
///
|
||||
/// `false` means ``makeDefaultAudioDriver()`` returns an ``OfflineDriver`` and
|
||||
/// nothing will reach a speaker: a Linux build without libasound, a Linux
|
||||
/// binary cross-compiled from macOS, or a platform with no driver yet.
|
||||
public var isLiveAudioAvailable: Bool {
|
||||
#if canImport(AudioToolbox) || canImport(CALSA)
|
||||
return true
|
||||
#else
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// InterleaveHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Channel-layout conversion shared by audio drivers whose hardware API wants
|
||||
// interleaved frames while the engine works in per-channel planar buses.
|
||||
//
|
||||
// Deliberately free of any platform import: the ALSA driver that consumes these
|
||||
// only compiles on Linux, but the conversion itself is ordinary arithmetic and
|
||||
// is the easiest part of a driver to get subtly wrong (transposed indices
|
||||
// produce audio that is quiet, channel-swapped, or aliased rather than silent).
|
||||
// Keeping it here means it compiles — and is tested — on every platform.
|
||||
|
||||
/// Writes `frameCount` frames of planar `buses` into an interleaved buffer.
|
||||
///
|
||||
/// Channels beyond `buses.count`, and frames beyond a bus's own length, are
|
||||
/// written as silence, so a short or missing bus can never read out of bounds.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buses: Planar per-channel sample buffers. Only the first `channelCount`
|
||||
/// are read.
|
||||
/// - out: Destination for `frameCount * channelCount` interleaved samples.
|
||||
/// Must have room for all of them.
|
||||
/// - frameCount: Frames to write.
|
||||
/// - channelCount: Channels per frame in `out`.
|
||||
@_spi(LyrebirdExtensions)
|
||||
public func lyrebirdInterleave(
|
||||
_ buses: [[Float]],
|
||||
into out: UnsafeMutablePointer<Float>,
|
||||
frameCount: Int,
|
||||
channelCount: Int
|
||||
) {
|
||||
for channel: Int in 0..<channelCount {
|
||||
// Binding the row to a local `[Float]` would retain/release it once per
|
||||
// channel per block on the render thread; borrowing it in place through
|
||||
// `withUnsafeBufferPointer` does not.
|
||||
guard channel < buses.count else {
|
||||
for frame: Int in 0..<frameCount {
|
||||
out[frame * channelCount + channel] = 0
|
||||
}
|
||||
continue
|
||||
}
|
||||
buses[channel].withUnsafeBufferPointer { src in
|
||||
guard let base: UnsafePointer<Float> = src.baseAddress else { return }
|
||||
let available: Int = min(frameCount, src.count)
|
||||
for frame: Int in 0..<available {
|
||||
out[frame * channelCount + channel] = base[frame]
|
||||
}
|
||||
for frame: Int in available..<frameCount {
|
||||
out[frame * channelCount + channel] = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Scatters `frameCount` interleaved frames into planar `buses`.
|
||||
///
|
||||
/// The inverse of ``lyrebirdInterleave(_:into:frameCount:channelCount:)``.
|
||||
/// Buses shorter than `frameCount` are filled as far as they go; channels
|
||||
/// beyond `buses.count` are dropped. Nothing is resized, so this is safe to
|
||||
/// call on the render thread once the buses are pre-allocated.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - src: Source of `frameCount * channelCount` interleaved samples.
|
||||
/// - buses: Planar destination buffers, pre-allocated by the caller.
|
||||
/// - frameCount: Frames to read.
|
||||
/// - channelCount: Channels per frame in `src`.
|
||||
@_spi(LyrebirdExtensions)
|
||||
public func lyrebirdDeinterleave(
|
||||
_ src: UnsafePointer<Float>,
|
||||
into buses: inout [[Float]],
|
||||
frameCount: Int,
|
||||
channelCount: Int
|
||||
) {
|
||||
let channels: Int = min(channelCount, buses.count)
|
||||
for channel: Int in 0..<channels {
|
||||
buses[channel].withUnsafeMutableBufferPointer { dst in
|
||||
guard let base: UnsafeMutablePointer<Float> = dst.baseAddress else { return }
|
||||
let available: Int = min(frameCount, dst.count)
|
||||
for frame: Int in 0..<available {
|
||||
base[frame] = src[frame * channelCount + channel]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,20 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
#if canImport(AudioToolbox)
|
||||
import AudioToolbox
|
||||
#endif
|
||||
|
||||
/// Non-Real-Time audio driver. Renders synchronously to a soundfile in the
|
||||
/// container/encoding chosen at init (``AudioFileFormat``, default `.cafFloat32`).
|
||||
/// `start()` blocks until rendering is complete — suitable for score/script workflows.
|
||||
///
|
||||
/// On Apple platforms every ``AudioFileFormat`` is available (via `ExtAudioFile`
|
||||
/// and, for the RF64 cases, ``RF64Writer``). Off Apple the driver uses the
|
||||
/// portable WAV codec (``WavFileWriter`` / ``WavFileReader``): the WAV encodings
|
||||
/// (`.wavFloat32` / `.wavInt16` / `.wavInt24`) render and WAV inputs read; the
|
||||
/// Apple-only containers (CAF / AIFF-C / AAC / ALAC) throw
|
||||
/// ``NRTDriverError/unsupportedFormatOnPlatform(_:)``.
|
||||
public final class NRTDriver: AudioDriver {
|
||||
|
||||
private let outputURL: URL
|
||||
@@ -25,18 +34,20 @@ public final class NRTDriver: AudioDriver {
|
||||
/// Pre-allocated interleaved write buffer: blockSize * numOutputChannels floats.
|
||||
private var writeBuffer: [Float] = []
|
||||
|
||||
private var inputChannelCount: Int = 0
|
||||
// Pre-allocated input staging — no alloc during the render loop.
|
||||
private var inputStagingBuffers: [[Float]] = [] // [channel][sample], blockSize each
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
// Input file state — opened in setup(), disposed in start()'s defer block.
|
||||
private var inputFileRef: ExtAudioFileRef?
|
||||
private var inputChannelCount: Int = 0
|
||||
|
||||
// Pre-allocated input buffers — no alloc during the render loop.
|
||||
private var inputReadBuffer: [Float] = [] // interleaved: blockSize × inputChannelCount
|
||||
private var inputStagingBuffers: [[Float]] = [] // [channel][sample], blockSize each
|
||||
#else
|
||||
private var inputReader: WavFileReader?
|
||||
#endif
|
||||
|
||||
/// Optional trigger listener. When set, `_drainSync` is called after each `processBlock`
|
||||
/// so that trigger handlers can add new synthesizers that render in subsequent blocks.
|
||||
/// Handlers receive a `LyrebirdMessageContext(nrtEngine:)` — `ctx.add(synth)` enqueues
|
||||
/// directly to `pendingQueue` without a `DispatchQueue.main.async` hop.
|
||||
public var triggerListener: TriggerListener?
|
||||
|
||||
/// - Parameters:
|
||||
@@ -44,14 +55,10 @@ public final class NRTDriver: AudioDriver {
|
||||
/// (`.caf` / `.wav` / `.aiff`); see ``AudioFileFormat/fileExtension``.
|
||||
/// - duration: Render duration in seconds.
|
||||
/// - format: Container and PCM encoding for the output file. Defaults to
|
||||
/// `.cafFloat32`. CAF is 64-bit-sized (no 4 GB cap) and carries any channel
|
||||
/// count, so it suits long or multichannel offline renders; `.wavFloat32` /
|
||||
/// `.aiffFloat32` / the integer WAV cases are available for interchange.
|
||||
/// `.cafFloat32`. Off Apple, choose a `.wav*` case (CAF/AIFF/AAC throw).
|
||||
/// - inputURL: Optional soundfile whose samples are written to the engine's input buses
|
||||
/// each block, as if they came from a microphone. Channels are mapped in order starting
|
||||
/// at input bus 0. The engine's `numInputChannels` must be ≥ the file's channel count
|
||||
/// (extra input buses receive silence). If the file is shorter than `duration`, the
|
||||
/// remaining blocks receive silence.
|
||||
/// each block. Off Apple the input must be a WAV file **at the engine sample rate** —
|
||||
/// the portable reader does no sample-rate conversion (the Apple `ExtAudioFile` path does).
|
||||
/// - inputStartOffset: Seconds to skip into `inputURL` before rendering begins. Clamped
|
||||
/// to 0 if negative.
|
||||
public init(
|
||||
@@ -61,7 +68,6 @@ public final class NRTDriver: AudioDriver {
|
||||
inputURL: URL? = nil,
|
||||
inputStartOffset: Double = 0.0
|
||||
) {
|
||||
|
||||
self.outputURL = outputURL
|
||||
self.outputFormat = format
|
||||
self.duration = duration
|
||||
@@ -79,6 +85,7 @@ public final class NRTDriver: AudioDriver {
|
||||
|
||||
guard let inputURL: URL else { return }
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
// Open the input file.
|
||||
var rawInputFileRef: ExtAudioFileRef?
|
||||
let openStatus: OSStatus = ExtAudioFileOpenURL(inputURL as CFURL, &rawInputFileRef)
|
||||
@@ -100,7 +107,6 @@ public final class NRTDriver: AudioDriver {
|
||||
inputChannelCount = min(Int(fileFmt.mChannelsPerFrame), engine.numInputChannels)
|
||||
|
||||
// Set client format: interleaved Float32 at engine sample rate.
|
||||
// ExtAudioFile handles sample-rate conversion automatically if file SR differs.
|
||||
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: engine.sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
@@ -135,36 +141,34 @@ public final class NRTDriver: AudioDriver {
|
||||
inputReadBuffer = [Float](repeating: 0, count: engine.blockSize * inputChannelCount)
|
||||
inputStagingBuffers = [[Float]](repeating: [Float](repeating: 0, count: engine.blockSize),
|
||||
count: inputChannelCount)
|
||||
#else
|
||||
// Portable WAV input.
|
||||
let reader: WavFileReader = try WavFileReader(url: inputURL)
|
||||
inputChannelCount = min(reader.channels, engine.numInputChannels)
|
||||
if inputStartOffset > 0 {
|
||||
let skipFrames: Int = Int(inputStartOffset * reader.sampleRate)
|
||||
if skipFrames > 0 { try reader.skip(frames: skipFrames) }
|
||||
}
|
||||
inputReader = reader
|
||||
inputStagingBuffers = [[Float]](repeating: [Float](repeating: 0, count: engine.blockSize),
|
||||
count: inputChannelCount)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Render synchronously to the output file.
|
||||
///
|
||||
/// - Throws: `NRTDriverError.invalidDuration` if `duration` is negative, NaN,
|
||||
/// or infinite; `NRTDriverError.fileTooLargeForContainer` if a WAV/AIFF render
|
||||
/// is projected past the 4 GB RIFF cap (use `.cafFloat32` for long renders);
|
||||
/// or the file/IO error cases on create/write failure. For the `.rf64*`
|
||||
/// formats, a ``RF64WriterError`` may surface instead of an `NRTDriverError`.
|
||||
/// Render synchronously to the output file. See ``NRTDriverError`` for the
|
||||
/// failure cases (invalid duration, 4 GB container overflow, format
|
||||
/// unsupported off Apple, and the underlying I/O errors).
|
||||
public func start() throws {
|
||||
guard let engine: SynthesisEngine else { return }
|
||||
|
||||
// Validate duration before any Double→Int conversion: Int(_:) traps on a
|
||||
// non-finite or out-of-range value, and a negative duration would make the
|
||||
// render loop's `0..<totalBlocks` range crash. Throw instead.
|
||||
// The `< Double(Int.max)` bound also rejects a finite-but-astronomical
|
||||
// duration whose block count would overflow the `Int(_:)` conversion.
|
||||
// Validate duration before any Double→Int conversion.
|
||||
let blocksDouble: Double = (duration * engine.sampleRate / Double(engine.blockSize)).rounded(.up)
|
||||
guard duration.isFinite, duration >= 0, blocksDouble < Double(Int.max) else {
|
||||
throw NRTDriverError.invalidDuration(duration)
|
||||
}
|
||||
|
||||
// Total render blocks — computed once and shared by the large-file guard and
|
||||
// the render loop below, so the two can never drift out of sync.
|
||||
let totalBlocks: Int = Int(blocksDouble)
|
||||
|
||||
// Large-file guard: reject a WAV/AIFF render projected past the 4 GB RIFF/AIFF
|
||||
// cap before opening the file, so we never emit a truncated/corrupt output.
|
||||
// CAF is exempt. `projectedByteCount` (inside riffOverflow) saturates on
|
||||
// overflow, so a frame count near Int.max still yields the correct decision.
|
||||
// Large-file guard: reject a WAV/AIFF render past the 4 GB RIFF/AIFF cap.
|
||||
let (projectedFrames, framesOverflow): (Int, Bool) =
|
||||
totalBlocks.multipliedReportingOverflow(by: engine.blockSize)
|
||||
let effectiveFrames: Int = framesOverflow ? Int.max : projectedFrames
|
||||
@@ -176,17 +180,18 @@ public final class NRTDriver: AudioDriver {
|
||||
)
|
||||
}
|
||||
|
||||
let bs: Int = engine.blockSize
|
||||
let nch: Int = engine.numOutputChannels
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
// Dispose the input file regardless of which output backend construction (or
|
||||
// the render) throws below — registered before backend selection so an early
|
||||
// throw can't leak it.
|
||||
// the render) throws below.
|
||||
defer {
|
||||
if let ref: ExtAudioFileRef = inputFileRef { ExtAudioFileDispose(ref) }
|
||||
inputFileRef = nil
|
||||
}
|
||||
|
||||
// Choose the output backend: RF64Writer (hand-rolled 64-bit WAV) for the RF64
|
||||
// cases, else ExtAudioFile for CAF / WAV / AIFF. The engine renders Float32, so
|
||||
// both back-ends receive native Float32 interleaved samples.
|
||||
// Choose the output backend: RF64Writer for the RF64 cases, else ExtAudioFile.
|
||||
let rf64Writer: RF64Writer? = outputFormat.usesRF64Writer
|
||||
? try RF64Writer(url: outputURL, format: outputFormat,
|
||||
sampleRate: engine.sampleRate, channels: engine.numOutputChannels)
|
||||
@@ -210,8 +215,6 @@ public final class NRTDriver: AudioDriver {
|
||||
guard status == noErr, let createdRef: ExtAudioFileRef else {
|
||||
throw NRTDriverError.cannotCreateFile(status)
|
||||
}
|
||||
// Client format: always native Float32 interleaved. ExtAudioFile converts
|
||||
// Float32 → int16/int24 on write for the integer WAV formats.
|
||||
var clientFormat: AudioStreamBasicDescription = outputFormat.makeClientASBD(
|
||||
sampleRate: engine.sampleRate,
|
||||
channels: engine.numOutputChannels
|
||||
@@ -226,7 +229,6 @@ public final class NRTDriver: AudioDriver {
|
||||
ExtAudioFileDispose(createdRef)
|
||||
throw NRTDriverError.cannotSetFormat(status)
|
||||
}
|
||||
// Compressed (AAC) formats: push the target bitrate into the encoder.
|
||||
let encoderStatus: OSStatus = outputFormat.applyEncoderConfig(to: createdRef)
|
||||
guard encoderStatus == noErr else {
|
||||
ExtAudioFileDispose(createdRef)
|
||||
@@ -235,53 +237,16 @@ public final class NRTDriver: AudioDriver {
|
||||
extFileRef = createdRef
|
||||
}
|
||||
|
||||
// Guarantee disposal even if an error is thrown mid-render.
|
||||
defer {
|
||||
if let ref: ExtAudioFileRef = extFileRef { ExtAudioFileDispose(ref) }
|
||||
try? rf64Writer?.close() // idempotent; explicit close below patches ds64 sizes
|
||||
try? rf64Writer?.close()
|
||||
}
|
||||
|
||||
// Render loop — synchronous, no RT constraints. `totalBlocks` was computed
|
||||
// once above (shared with the large-file guard).
|
||||
let bs: Int = engine.blockSize
|
||||
let nch: Int = engine.numOutputChannels
|
||||
|
||||
for _ in 0..<totalBlocks {
|
||||
// Build input for this block.
|
||||
let inputSamples: [[Float]]
|
||||
if let inputRef: ExtAudioFileRef = inputFileRef {
|
||||
// Zero staging so that EOF blocks and unused trailing frames are silent.
|
||||
for ch: Int in 0..<inputChannelCount {
|
||||
for i: Int in 0..<bs { inputStagingBuffers[ch][i] = 0 }
|
||||
}
|
||||
var framesToRead: UInt32 = UInt32(bs)
|
||||
let readStatus: OSStatus = inputReadBuffer.withUnsafeMutableBufferPointer { ptr in
|
||||
var bufList: AudioBufferList = AudioBufferList(
|
||||
mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(
|
||||
mNumberChannels: UInt32(inputChannelCount),
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: ptr.baseAddress
|
||||
)
|
||||
)
|
||||
return ExtAudioFileRead(inputRef, &framesToRead, &bufList)
|
||||
}
|
||||
guard readStatus == noErr else { throw NRTDriverError.inputReadFailed(readStatus) }
|
||||
let framesRead: Int = Int(framesToRead)
|
||||
for f: Int in 0..<framesRead {
|
||||
for ch: Int in 0..<inputChannelCount {
|
||||
inputStagingBuffers[ch][f] = inputReadBuffer[f * inputChannelCount + ch]
|
||||
}
|
||||
}
|
||||
inputSamples = inputStagingBuffers
|
||||
} else {
|
||||
inputSamples = []
|
||||
}
|
||||
|
||||
let inputSamples: [[Float]] = try _readInputBlock(bs: bs)
|
||||
engine.processBlock(inputSamples: inputSamples)
|
||||
triggerListener?._drainSync()
|
||||
|
||||
// Interleave output buses into the write buffer
|
||||
for ch: Int in 0..<nch {
|
||||
let bus: [Float] = engine.audioBuses[ch]
|
||||
for s: Int in 0..<bs {
|
||||
@@ -289,8 +254,6 @@ public final class NRTDriver: AudioDriver {
|
||||
}
|
||||
}
|
||||
|
||||
// Write interleaved block to file — a failure means a corrupt or truncated
|
||||
// file, so we throw rather than silently swallow the error.
|
||||
if let rf64Writer: RF64Writer {
|
||||
try writeBuffer.withUnsafeBufferPointer { ptr in
|
||||
try rf64Writer.writeFloat32Interleaved(ptr, frames: bs)
|
||||
@@ -314,14 +277,43 @@ public final class NRTDriver: AudioDriver {
|
||||
}
|
||||
}
|
||||
|
||||
// Patch the RF64 ds64 sizes now (idempotent with the defer) so the file is
|
||||
// finalised before this method returns.
|
||||
try rf64Writer?.close()
|
||||
|
||||
// Synchronous render is done and the freeWorker timer only starts after this
|
||||
// returns — emit any per-block event-drop warning here so it reaches the console
|
||||
// even if the process exits before that timer (or `stop()`) runs.
|
||||
engine.drainPerBlockEventDropWarning()
|
||||
|
||||
#else
|
||||
// Portable WAV render path.
|
||||
// Close the input reader's file handle regardless of how the render exits
|
||||
// (mirrors the Apple branch's ExtAudioFileDispose defer).
|
||||
defer {
|
||||
inputReader?.close()
|
||||
inputReader = nil
|
||||
}
|
||||
let encoding: WavEncoding = try Self.wavEncoding(for: outputFormat)
|
||||
let writer: WavFileWriter = try WavFileWriter(
|
||||
url: outputURL, channels: nch, sampleRate: engine.sampleRate, encoding: encoding
|
||||
)
|
||||
// Mirror the Apple branch's `ExtAudioFileDispose` defer: a throw from
|
||||
// `processBlock` or a write would otherwise leave the handle open and
|
||||
// the file's RIFF/`data` sizes at zero. `finalize()` is idempotent, so
|
||||
// the explicit call below is unaffected.
|
||||
defer { try? writer.finalize() }
|
||||
|
||||
for _ in 0..<totalBlocks {
|
||||
let inputSamples: [[Float]] = try _readInputBlock(bs: bs)
|
||||
engine.processBlock(inputSamples: inputSamples)
|
||||
triggerListener?._drainSync()
|
||||
|
||||
for ch: Int in 0..<nch {
|
||||
let bus: [Float] = engine.audioBuses[ch]
|
||||
for s: Int in 0..<bs {
|
||||
writeBuffer[s * nch + ch] = bus[s]
|
||||
}
|
||||
}
|
||||
try writer.write(interleaved: writeBuffer, frames: bs)
|
||||
}
|
||||
try writer.finalize()
|
||||
engine.drainPerBlockEventDropWarning()
|
||||
#endif
|
||||
}
|
||||
|
||||
public func stop() {
|
||||
@@ -329,8 +321,76 @@ public final class NRTDriver: AudioDriver {
|
||||
}
|
||||
|
||||
/// Requests sample-accurate control resolution by default.
|
||||
/// Override by passing an explicit `controlBlockSize` to `SynthesisEngine.init`.
|
||||
public var suggestedControlBlockSize: Int? { lyrebirdSampleAccurateControlBlockSize }
|
||||
|
||||
// MARK: - Input block assembly
|
||||
|
||||
/// Reads one block of input into the pre-allocated staging buffers (zero-filled
|
||||
/// past EOF) and returns them. Returns `[]` when no input file is configured.
|
||||
///
|
||||
/// A read error must not be swallowed: an offline render that silently
|
||||
/// substitutes silence for a truncated or unreadable input file reports
|
||||
/// success and produces a wrong result, which is far worse than failing.
|
||||
/// On Apple this throws ``NRTDriverError/inputReadFailed(_:)`` (the
|
||||
/// `ExtAudioFile` status); off Apple the underlying ``WavFileError`` from
|
||||
/// the portable reader propagates as-is.
|
||||
private func _readInputBlock(bs: Int) throws -> [[Float]] {
|
||||
guard inputChannelCount > 0 else { return [] }
|
||||
for ch: Int in 0..<inputChannelCount {
|
||||
for i: Int in 0..<bs { inputStagingBuffers[ch][i] = 0 }
|
||||
}
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
guard let inputRef: ExtAudioFileRef = inputFileRef else { return [] }
|
||||
var framesToRead: UInt32 = UInt32(bs)
|
||||
let readStatus: OSStatus = inputReadBuffer.withUnsafeMutableBufferPointer { ptr in
|
||||
var bufList: AudioBufferList = AudioBufferList(
|
||||
mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(
|
||||
mNumberChannels: UInt32(inputChannelCount),
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: ptr.baseAddress
|
||||
)
|
||||
)
|
||||
return ExtAudioFileRead(inputRef, &framesToRead, &bufList)
|
||||
}
|
||||
guard readStatus == noErr else { throw NRTDriverError.inputReadFailed(readStatus) }
|
||||
let framesRead: Int = Int(framesToRead)
|
||||
for f: Int in 0..<framesRead {
|
||||
for ch: Int in 0..<inputChannelCount {
|
||||
inputStagingBuffers[ch][f] = inputReadBuffer[f * inputChannelCount + ch]
|
||||
}
|
||||
}
|
||||
#else
|
||||
guard let reader: WavFileReader = inputReader else { return [] }
|
||||
let fileChannels: Int = reader.channels
|
||||
let block: [Float] = try reader.read(frames: bs)
|
||||
let framesRead: Int = fileChannels > 0 ? block.count / fileChannels : 0
|
||||
for f: Int in 0..<framesRead {
|
||||
for ch: Int in 0..<inputChannelCount {
|
||||
inputStagingBuffers[ch][f] = block[f * fileChannels + ch]
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return inputStagingBuffers
|
||||
}
|
||||
|
||||
#if !canImport(AudioToolbox)
|
||||
/// Maps a WAV ``AudioFileFormat`` to a ``WavEncoding``; the Apple-only
|
||||
/// containers throw ``NRTDriverError/unsupportedFormatOnPlatform(_:)``.
|
||||
private 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 NRTDriverError.unsupportedFormatOnPlatform(format)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Errors
|
||||
@@ -347,8 +407,9 @@ public enum NRTDriverError: Error {
|
||||
/// `duration` was negative, NaN, or infinite. Pass a finite, non-negative value.
|
||||
case invalidDuration(Double)
|
||||
/// The render is projected to exceed the output container's 4 GB (32-bit size
|
||||
/// field) limit. Only WAV/AIFF are capped; CAF is exempt. `projectedBytes` is
|
||||
/// the estimated audio-data size, `cap` is `lyrebirdMaxRIFFBytes`. Re-run with
|
||||
/// `format: .cafFloat32` (64-bit sizes, uncapped) or shorten the duration.
|
||||
/// field) limit. Only WAV/AIFF are capped; CAF is exempt.
|
||||
case fileTooLargeForContainer(projectedBytes: Int, cap: Int)
|
||||
/// The requested format is not available on this (non-Apple) platform. Only the
|
||||
/// WAV encodings render off Apple; use `.wavFloat32` / `.wavInt16` / `.wavInt24`.
|
||||
case unsupportedFormatOnPlatform(AudioFileFormat)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(iOS)
|
||||
#if canImport(AudioToolbox)
|
||||
import CoreAudio
|
||||
import AudioToolbox
|
||||
import AVFoundation
|
||||
@@ -339,3 +340,4 @@ private func lyrebirdIOSRenderCallback(
|
||||
)
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
// AudioFileFormat+AudioToolbox.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// AudioToolbox-backed members of `AudioFileFormat`: `ExtAudioFile` container
|
||||
// type IDs, the file/client `AudioStreamBasicDescription` factories, and the
|
||||
// compressed-encoder configuration. Split out from the portable enum so the
|
||||
// core (and every soundfile-format consumer) builds on platforms without
|
||||
// AudioToolbox; on Linux/Windows these members simply do not exist and the
|
||||
// portable WAV codec is used instead.
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import AudioToolbox
|
||||
|
||||
extension AudioFileFormat {
|
||||
|
||||
/// AudioToolbox container type ID passed to `ExtAudioFileCreateWithURL`.
|
||||
///
|
||||
/// Not meaningful for the RF64 cases (they are written by ``RF64Writer``, not
|
||||
/// `ExtAudioFile`); those return `kAudioFileWAVEType` as an inert default.
|
||||
public var audioFileTypeID: AudioFileTypeID {
|
||||
switch self {
|
||||
case .wavFloat32, .wavInt16, .wavInt24, .rf64Float32, .rf64Int24:
|
||||
return kAudioFileWAVEType
|
||||
case .aiffFloat32:
|
||||
return kAudioFileAIFCType // AIFF-C: carries Float32; classic AIFF does not
|
||||
case .cafFloat32:
|
||||
return kAudioFileCAFType
|
||||
case .aacHigh, .aacMedium, .alac:
|
||||
return kAudioFileM4AType
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ASBD factories (module-internal)
|
||||
|
||||
/// Encoder packet geometry (samples per packet) for the compressed codecs.
|
||||
private let aacFramesPerPacket: UInt32 = 1024
|
||||
private let alacFramesPerPacket: UInt32 = 4096
|
||||
|
||||
extension AudioFileFormat {
|
||||
|
||||
/// Build the *file* `AudioStreamBasicDescription` for this format: linear PCM
|
||||
/// with the case's bit depth, encoding flags, and endianness, interleaved
|
||||
/// across `channels`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sampleRate: Sample rate embedded in the file header, in Hz.
|
||||
/// - channels: Interleaved channel count. Must be ≥ 1.
|
||||
func makeFileASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription {
|
||||
if isCompressed {
|
||||
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||
asbd.mSampleRate = sampleRate
|
||||
asbd.mChannelsPerFrame = UInt32(channels)
|
||||
if aacBitrate != nil {
|
||||
asbd.mFormatID = kAudioFormatMPEG4AAC
|
||||
asbd.mFramesPerPacket = aacFramesPerPacket
|
||||
} else {
|
||||
asbd.mFormatID = kAudioFormatAppleLossless
|
||||
asbd.mFramesPerPacket = alacFramesPerPacket
|
||||
asbd.mFormatFlags = kAppleLosslessFormatFlag_24BitSourceData
|
||||
}
|
||||
return asbd
|
||||
}
|
||||
|
||||
let bytesPerSample: UInt32 = fileBitsPerChannel / Self.bitsPerByte
|
||||
let bytesPerFrame: UInt32 = bytesPerSample * UInt32(channels)
|
||||
|
||||
var flags: AudioFormatFlags = kAudioFormatFlagIsPacked
|
||||
flags |= isFloatEncoding ? kAudioFormatFlagIsFloat : kAudioFormatFlagIsSignedInteger
|
||||
if isBigEndian { flags |= kAudioFormatFlagIsBigEndian }
|
||||
|
||||
return AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: flags,
|
||||
mBytesPerPacket: bytesPerFrame,
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: bytesPerFrame,
|
||||
mChannelsPerFrame: UInt32(channels),
|
||||
mBitsPerChannel: fileBitsPerChannel,
|
||||
mReserved: 0
|
||||
)
|
||||
}
|
||||
|
||||
/// Build the *client* `AudioStreamBasicDescription`: always native-endian
|
||||
/// Float32 interleaved across `channels`, independent of the file encoding.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sampleRate: Sample rate, in Hz. Should match the file ASBD.
|
||||
/// - channels: Interleaved channel count. Must be ≥ 1.
|
||||
func makeClientASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription {
|
||||
let bytesPerFrame: UInt32 = lyrebirdBytesPerSample * UInt32(channels)
|
||||
return AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: bytesPerFrame,
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: bytesPerFrame,
|
||||
mChannelsPerFrame: UInt32(channels),
|
||||
mBitsPerChannel: lyrebirdBitsPerSample,
|
||||
mReserved: 0
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Compressed encoder configuration
|
||||
|
||||
extension AudioFileFormat {
|
||||
|
||||
/// After an `ExtAudioFile` for a compressed format has been created and its client
|
||||
/// (Float32) format set, push the target AAC bitrate into the underlying
|
||||
/// `AudioConverter`. No-op for non-AAC formats.
|
||||
///
|
||||
/// Returns `noErr` on success (or when nothing needed doing), else the failing
|
||||
/// `OSStatus`. Call from a non-RT thread, before the first `ExtAudioFileWrite`.
|
||||
func applyEncoderConfig(to fileRef: ExtAudioFileRef) -> OSStatus {
|
||||
guard let bitrate: Int = aacBitrate else { return noErr }
|
||||
|
||||
var converter: AudioConverterRef?
|
||||
var converterSize: UInt32 = UInt32(MemoryLayout<AudioConverterRef?>.size)
|
||||
let getStatus: OSStatus = ExtAudioFileGetProperty(
|
||||
fileRef, kExtAudioFileProperty_AudioConverter, &converterSize, &converter
|
||||
)
|
||||
guard getStatus == noErr, let converter: AudioConverterRef else { return getStatus }
|
||||
|
||||
var rate: UInt32 = UInt32(bitrate)
|
||||
let setStatus: OSStatus = AudioConverterSetProperty(
|
||||
converter, kAudioConverterEncodeBitRate, UInt32(MemoryLayout<UInt32>.size), &rate
|
||||
)
|
||||
guard setStatus == noErr else { return setStatus }
|
||||
|
||||
var config: CFPropertyList? = nil
|
||||
return withUnsafePointer(to: &config) { ptr in
|
||||
ExtAudioFileSetProperty(
|
||||
fileRef, kExtAudioFileProperty_ConverterConfig,
|
||||
UInt32(MemoryLayout<CFPropertyList?>.size), ptr
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -4,28 +4,23 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import AudioToolbox
|
||||
|
||||
/// Container-and-encoding format shared by every Lyrebird soundfile writer:
|
||||
/// ``LyrebirdBuffer/write(to:format:sampleRate:)`` (offline buffer dump),
|
||||
/// ``DiskOut/Audio`` (real-time streaming recorder), and the NRT driver
|
||||
/// (offline score render).
|
||||
///
|
||||
/// Each case pins both the container (WAV / AIFF-C / CAF) and the PCM sample
|
||||
/// encoding (Float32, or signed-integer 16/24-bit). Writers always hand
|
||||
/// `ExtAudioFile` native-Float32 samples as the *client* format (see
|
||||
/// `makeClientASBD(sampleRate:channels:)`) and let it convert to the *file*
|
||||
/// format (`makeFileASBD(sampleRate:channels:)`) — so integer encodings cost
|
||||
/// the caller nothing beyond selecting the case.
|
||||
/// encoding (Float32, or signed-integer 16/24-bit). The enum and its derived
|
||||
/// properties are pure Swift and portable; the AudioToolbox-backed members
|
||||
/// (`ExtAudioFile` type IDs and `AudioStreamBasicDescription` factories) live in
|
||||
/// `AudioFileFormat+AudioToolbox.swift` under `#if canImport(AudioToolbox)`.
|
||||
///
|
||||
/// ## Container notes
|
||||
/// - **WAV** — little-endian, cross-platform standard. Supports Float32 and
|
||||
/// signed-integer PCM. Classic RIFF caps total file size at 4 GB (32-bit size
|
||||
/// fields); large renders should fall back to `.cafFloat32`.
|
||||
/// - **AIFF-C** (`.aiffFloat32`) — big-endian by spec. Uses `kAudioFileAIFCType`
|
||||
/// (not classic `kAudioFileAIFFType`, which is integer-only) so it can carry
|
||||
/// Float32 while keeping the `.aiff` extension. Best restricted to ≤ 2 channels
|
||||
/// for compatibility with legacy readers; also 4 GB-capped.
|
||||
/// - **AIFF-C** (`.aiffFloat32`) — big-endian by spec. Best restricted to
|
||||
/// ≤ 2 channels for compatibility with legacy readers; also 4 GB-capped.
|
||||
/// - **CAF** (`.cafFloat32`) — Apple's flexible container: any sample rate, any
|
||||
/// channel count up to `lyrebirdMaxFileChannelCount`, 64-bit sizes (no 4 GB
|
||||
/// cap). Default for buffer and NRT writes.
|
||||
@@ -79,24 +74,7 @@ public enum AudioFileFormat: Sendable {
|
||||
/// CAF / Float32. Alias for ``cafFloat32``.
|
||||
public static let caf: AudioFileFormat = .cafFloat32
|
||||
|
||||
// MARK: - Derived properties
|
||||
|
||||
/// AudioToolbox container type ID passed to `ExtAudioFileCreateWithURL`.
|
||||
///
|
||||
/// Not meaningful for the RF64 cases (they are written by ``RF64Writer``, not
|
||||
/// `ExtAudioFile`); those return `kAudioFileWAVEType` as an inert default.
|
||||
public var audioFileTypeID: AudioFileTypeID {
|
||||
switch self {
|
||||
case .wavFloat32, .wavInt16, .wavInt24, .rf64Float32, .rf64Int24:
|
||||
return kAudioFileWAVEType
|
||||
case .aiffFloat32:
|
||||
return kAudioFileAIFCType // AIFF-C: carries Float32; classic AIFF does not
|
||||
case .cafFloat32:
|
||||
return kAudioFileCAFType
|
||||
case .aacHigh, .aacMedium, .alac:
|
||||
return kAudioFileM4AType
|
||||
}
|
||||
}
|
||||
// MARK: - Derived properties (portable)
|
||||
|
||||
/// Filesystem extension for the output file (no leading dot).
|
||||
public var fileExtension: String {
|
||||
@@ -154,8 +132,8 @@ public enum AudioFileFormat: Sendable {
|
||||
/// Target AAC encode bitrate in bits/second, or `nil` for non-AAC formats.
|
||||
public var aacBitrate: Int? {
|
||||
switch self {
|
||||
case .aacHigh: return aacHighBitrate
|
||||
case .aacMedium: return aacMediumBitrate
|
||||
case .aacHigh: return Self.aacHighBitrate
|
||||
case .aacMedium: return Self.aacMediumBitrate
|
||||
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32,
|
||||
.rf64Float32, .rf64Int24, .alac:
|
||||
return nil
|
||||
@@ -171,8 +149,6 @@ public enum AudioFileFormat: Sendable {
|
||||
/// ``RF64Writer`` — see ``usesRF64Writer``.
|
||||
public var supportsLargeFiles: Bool {
|
||||
switch self {
|
||||
// CAF/RF64 are 64-bit-sized; the compressed M4A cases are not RIFF at all,
|
||||
// so the 4 GB RIFF/AIFF guard never applies to them either.
|
||||
case .cafFloat32, .rf64Float32, .rf64Int24, .aacHigh, .aacMedium, .alac:
|
||||
return true
|
||||
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32:
|
||||
@@ -193,7 +169,7 @@ public enum AudioFileFormat: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Large-file guard
|
||||
// MARK: - Large-file guard (portable)
|
||||
|
||||
extension AudioFileFormat {
|
||||
|
||||
@@ -203,11 +179,9 @@ extension AudioFileFormat {
|
||||
///
|
||||
/// Pure integer arithmetic — safe to evaluate for hypothetical sizes without
|
||||
/// allocating anything. **Saturates to `Int.max` on overflow** rather than
|
||||
/// trapping: any frame count large enough to overflow the byte product is, by
|
||||
/// definition, far past any container cap, so a saturated value gives the guard
|
||||
/// the correct "over cap" answer without a crash.
|
||||
/// trapping.
|
||||
func projectedByteCount(frameCount: Int, channels: Int) -> Int {
|
||||
let bytesPerSample: Int = Int(fileBitsPerChannel / bitsPerByte)
|
||||
let bytesPerSample: Int = Int(fileBitsPerChannel / Self.bitsPerByte)
|
||||
let (samples, sampleOverflow): (Int, Bool) = frameCount.multipliedReportingOverflow(by: channels)
|
||||
if sampleOverflow { return Int.max }
|
||||
let (bytes, byteOverflow): (Int, Bool) = samples.multipliedReportingOverflow(by: bytesPerSample)
|
||||
@@ -217,10 +191,6 @@ extension AudioFileFormat {
|
||||
/// Returns `(projected, cap)` when writing `frameCount × channels` frames in
|
||||
/// this format would overflow the container's addressable size, or `nil` when
|
||||
/// the write fits (or the container is 64-bit — see ``supportsLargeFiles``).
|
||||
///
|
||||
/// The single decision point behind both the `LyrebirdBuffer.write` and
|
||||
/// `NRTDriver` large-file guards, so the guard reads off the format rather
|
||||
/// than a hardcoded case list.
|
||||
func riffOverflow(frameCount: Int, channels: Int) -> (projected: Int, cap: Int)? {
|
||||
guard !supportsLargeFiles else { return nil }
|
||||
let projected: Int = projectedByteCount(frameCount: frameCount, channels: channels)
|
||||
@@ -228,134 +198,18 @@ extension AudioFileFormat {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ASBD factories (module-internal)
|
||||
|
||||
/// Number of bits in a byte — names the `/ 8` in bytes-per-sample derivations.
|
||||
private let bitsPerByte: UInt32 = 8
|
||||
|
||||
/// Encoder packet geometry (samples per packet) for the compressed codecs.
|
||||
private let aacFramesPerPacket: UInt32 = 1024
|
||||
private let alacFramesPerPacket: UInt32 = 4096
|
||||
|
||||
/// AAC target bitrates (bits/second) for the two quality tiers.
|
||||
private let aacHighBitrate: Int = 256_000
|
||||
private let aacMediumBitrate: Int = 128_000
|
||||
// MARK: - Shared format constants
|
||||
|
||||
extension AudioFileFormat {
|
||||
// Nested rather than file-scope: these are visible across files (the
|
||||
// `+AudioToolbox` extension needs them), and names this generic do not
|
||||
// belong in the module's global namespace.
|
||||
|
||||
/// Build the *file* `AudioStreamBasicDescription` for this format: linear PCM
|
||||
/// with the case's bit depth, encoding flags, and endianness, interleaved
|
||||
/// across `channels`.
|
||||
///
|
||||
/// This is the descriptor handed to `ExtAudioFileCreateWithURL`. Pair it with
|
||||
/// `makeClientASBD(sampleRate:channels:)` as the client format so
|
||||
/// `ExtAudioFile` performs any Float32 → integer / endian conversion.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sampleRate: Sample rate embedded in the file header, in Hz.
|
||||
/// - channels: Interleaved channel count. Must be ≥ 1.
|
||||
func makeFileASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription {
|
||||
// Compressed codecs (AAC / ALAC): the encoder fills in the packet geometry.
|
||||
// We supply the format ID, channel count, sample rate, and frames-per-packet;
|
||||
// `AudioConverter` (behind `ExtAudioFile`) computes the rest.
|
||||
if isCompressed {
|
||||
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||
asbd.mSampleRate = sampleRate
|
||||
asbd.mChannelsPerFrame = UInt32(channels)
|
||||
// AAC vs ALAC: the AAC tiers carry a bitrate, ALAC does not. Deriving the
|
||||
// codec from `aacBitrate` avoids a `switch self` with an unreachable
|
||||
// default that could silently leave `mFormatID == 0` for a future case.
|
||||
if aacBitrate != nil {
|
||||
asbd.mFormatID = kAudioFormatMPEG4AAC
|
||||
asbd.mFramesPerPacket = aacFramesPerPacket
|
||||
} else {
|
||||
asbd.mFormatID = kAudioFormatAppleLossless
|
||||
asbd.mFramesPerPacket = alacFramesPerPacket
|
||||
asbd.mFormatFlags = kAppleLosslessFormatFlag_24BitSourceData
|
||||
}
|
||||
return asbd
|
||||
}
|
||||
/// Number of bits in a byte — names the `/ 8` in bytes-per-sample derivations.
|
||||
static let bitsPerByte: UInt32 = 8
|
||||
|
||||
let bytesPerSample: UInt32 = fileBitsPerChannel / bitsPerByte
|
||||
let bytesPerFrame: UInt32 = bytesPerSample * UInt32(channels)
|
||||
|
||||
var flags: AudioFormatFlags = kAudioFormatFlagIsPacked
|
||||
flags |= isFloatEncoding ? kAudioFormatFlagIsFloat : kAudioFormatFlagIsSignedInteger
|
||||
if isBigEndian { flags |= kAudioFormatFlagIsBigEndian }
|
||||
|
||||
return AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: flags,
|
||||
mBytesPerPacket: bytesPerFrame,
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: bytesPerFrame,
|
||||
mChannelsPerFrame: UInt32(channels),
|
||||
mBitsPerChannel: fileBitsPerChannel,
|
||||
mReserved: 0
|
||||
)
|
||||
}
|
||||
|
||||
/// Build the *client* `AudioStreamBasicDescription`: always native-endian
|
||||
/// Float32 interleaved across `channels`, independent of the file encoding.
|
||||
///
|
||||
/// Every Lyrebird writer feeds `ExtAudioFile` Float32 samples; the file format
|
||||
/// (from `makeFileASBD(sampleRate:channels:)`) drives the conversion.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sampleRate: Sample rate, in Hz. Should match the file ASBD.
|
||||
/// - channels: Interleaved channel count. Must be ≥ 1.
|
||||
func makeClientASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription {
|
||||
let bytesPerFrame: UInt32 = lyrebirdBytesPerSample * UInt32(channels)
|
||||
return AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: bytesPerFrame,
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: bytesPerFrame,
|
||||
mChannelsPerFrame: UInt32(channels),
|
||||
mBitsPerChannel: lyrebirdBitsPerSample,
|
||||
mReserved: 0
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Compressed encoder configuration
|
||||
|
||||
extension AudioFileFormat {
|
||||
|
||||
/// After an `ExtAudioFile` for a compressed format has been created and its client
|
||||
/// (Float32) format set, push the target AAC bitrate into the underlying
|
||||
/// `AudioConverter`. No-op for non-AAC formats (ALAC has no bitrate; PCM has none).
|
||||
///
|
||||
/// Returns `noErr` on success (or when nothing needed doing), else the failing
|
||||
/// `OSStatus`. Call from a non-RT thread, before the first `ExtAudioFileWrite`.
|
||||
func applyEncoderConfig(to fileRef: ExtAudioFileRef) -> OSStatus {
|
||||
guard let bitrate: Int = aacBitrate else { return noErr }
|
||||
|
||||
var converter: AudioConverterRef?
|
||||
var converterSize: UInt32 = UInt32(MemoryLayout<AudioConverterRef?>.size)
|
||||
let getStatus: OSStatus = ExtAudioFileGetProperty(
|
||||
fileRef, kExtAudioFileProperty_AudioConverter, &converterSize, &converter
|
||||
)
|
||||
guard getStatus == noErr, let converter: AudioConverterRef else { return getStatus }
|
||||
|
||||
var rate: UInt32 = UInt32(bitrate)
|
||||
let setStatus: OSStatus = AudioConverterSetProperty(
|
||||
converter, kAudioConverterEncodeBitRate, UInt32(MemoryLayout<UInt32>.size), &rate
|
||||
)
|
||||
guard setStatus == noErr else { return setStatus }
|
||||
|
||||
// Notify ExtAudioFile that the converter config changed so it re-reads it.
|
||||
// The property value is a `CFPropertyList?` = NULL; pass a pointer to a nil
|
||||
// variable (NOT a null data pointer — CoreAudio dereferences the pointer).
|
||||
var config: CFPropertyList? = nil
|
||||
return withUnsafePointer(to: &config) { ptr in
|
||||
ExtAudioFileSetProperty(
|
||||
fileRef, kExtAudioFileProperty_ConverterConfig,
|
||||
UInt32(MemoryLayout<CFPropertyList?>.size), ptr
|
||||
)
|
||||
}
|
||||
}
|
||||
/// AAC target bitrate (bits/second) for the high-quality tier.
|
||||
static let aacHighBitrate: Int = 256_000
|
||||
/// AAC target bitrate (bits/second) for the medium-quality tier.
|
||||
static let aacMediumBitrate: Int = 128_000
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
import Synchronization
|
||||
|
||||
|
||||
@@ -5,12 +5,15 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
#if canImport(AudioToolbox)
|
||||
import AudioToolbox
|
||||
#endif
|
||||
|
||||
// MARK: - LyrebirdBufferIOError
|
||||
|
||||
/// Errors thrown by `LyrebirdBuffer` file I/O methods.
|
||||
public enum LyrebirdBufferIOError: Error, Equatable {
|
||||
#if canImport(AudioToolbox)
|
||||
/// `ExtAudioFileOpenURL` failed with the given status code.
|
||||
case cannotOpenFile(OSStatus)
|
||||
/// Querying the file's `AudioStreamBasicDescription` failed.
|
||||
@@ -21,22 +24,30 @@ public enum LyrebirdBufferIOError: Error, Equatable {
|
||||
case cannotSetClientFormat(OSStatus)
|
||||
/// `ExtAudioFileRead` returned a non-zero status.
|
||||
case readFailed(OSStatus)
|
||||
/// The requested channel index is outside the range of channels in the file.
|
||||
case channelOutOfRange(requested: Int, available: Int)
|
||||
/// The file's ASBD reports a channel count that is 0 or exceeds `lyrebirdMaxFileChannelCount`.
|
||||
/// This guard fires in `queryFileProperties` before any allocation using the channel count.
|
||||
case invalidChannelCount(Int)
|
||||
/// `ExtAudioFileCreateWithURL` failed when creating the output file.
|
||||
case cannotCreateOutputFile(OSStatus)
|
||||
/// Setting the output file's client format failed.
|
||||
case cannotSetOutputFormat(OSStatus)
|
||||
/// `ExtAudioFileWrite` returned a non-zero status.
|
||||
case writeFailed(OSStatus)
|
||||
#endif
|
||||
/// The requested channel index is outside the range of channels in the file.
|
||||
case channelOutOfRange(requested: Int, available: Int)
|
||||
/// The file's ASBD reports a channel count that is 0 or exceeds `lyrebirdMaxFileChannelCount`.
|
||||
/// This guard fires in `queryFileProperties` before any allocation using the channel count.
|
||||
case invalidChannelCount(Int)
|
||||
/// The requested WAV/AIFF write is projected to exceed the container's 4 GB
|
||||
/// (32-bit size field) limit. `projectedBytes` is the estimated audio-data
|
||||
/// size; `cap` is `lyrebirdMaxRIFFBytes`. Re-issue the write with `.cafFloat32`
|
||||
/// (64-bit sizes, uncapped), shorten the buffer, or split it.
|
||||
case fileTooLargeForContainer(projectedBytes: Int, cap: Int)
|
||||
#if !canImport(AudioToolbox)
|
||||
/// A non-WAV container (`.caf` / `.aiff` / `.aac` / `.alac` / RF64) was
|
||||
/// requested for `write(to:format:)` off Apple, where only the portable WAV
|
||||
/// encodings are available. Reading uses the portable ``WavFileReader``,
|
||||
/// whose failures surface as ``WavFileError``.
|
||||
case unsupportedFormatOnPlatform(AudioFileFormat)
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Constants
|
||||
@@ -45,8 +56,10 @@ public enum LyrebirdBufferIOError: Error, Equatable {
|
||||
/// Small enough to keep stack pressure low; large enough to amortize the per-call overhead.
|
||||
private let lyrebirdFileIOChunkFrames: Int = 4096
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
/// Bit depth of the Float32 client format used for all file I/O reads and writes.
|
||||
private let lyrebirdFileIOBitsPerSample: UInt32 = 32
|
||||
#endif
|
||||
|
||||
// MARK: - LyrebirdBuffer + File I/O
|
||||
|
||||
@@ -77,6 +90,7 @@ public extension LyrebirdBuffer {
|
||||
channel: Int = 0,
|
||||
normalise: Bool = false
|
||||
) throws -> LyrebirdBuffer {
|
||||
#if canImport(AudioToolbox)
|
||||
var fileRef: ExtAudioFileRef?
|
||||
let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef)
|
||||
guard openStatus == noErr, let fileRef: ExtAudioFileRef else {
|
||||
@@ -103,6 +117,27 @@ public extension LyrebirdBuffer {
|
||||
normalise: normalise
|
||||
)
|
||||
return buffer
|
||||
#else
|
||||
// Portable WAV read. `WavFileReader` throws `WavFileError` on a bad or
|
||||
// non-WAV file. Like the Apple path, the buffer keeps the file's own
|
||||
// sample rate — neither path resamples on load.
|
||||
let reader: WavFileReader = try WavFileReader(url: url)
|
||||
defer { reader.close() }
|
||||
let fileChannelCount: Int = reader.channels
|
||||
guard channel < fileChannelCount else {
|
||||
throw LyrebirdBufferIOError.channelOutOfRange(
|
||||
requested: channel, available: fileChannelCount
|
||||
)
|
||||
}
|
||||
let fileFrameCount: Int = reader.frameCount
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: max(1, fileFrameCount))
|
||||
buffer.setSampleRate(reader.sampleRate)
|
||||
try portableReadMono(
|
||||
reader, into: buffer, channel: channel,
|
||||
framesToRead: fileFrameCount, normalise: normalise
|
||||
)
|
||||
return buffer
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - loadAllChannels(url:normalise:)
|
||||
@@ -126,6 +161,7 @@ public extension LyrebirdBuffer {
|
||||
url: URL,
|
||||
normalise: Bool = false
|
||||
) throws -> LyrebirdBuffer {
|
||||
#if canImport(AudioToolbox)
|
||||
var fileRef: ExtAudioFileRef?
|
||||
let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef)
|
||||
guard openStatus == noErr, let fileRef: ExtAudioFileRef else {
|
||||
@@ -150,6 +186,25 @@ public extension LyrebirdBuffer {
|
||||
normalise: normalise
|
||||
)
|
||||
return buffer
|
||||
#else
|
||||
let reader: WavFileReader = try WavFileReader(url: url)
|
||||
defer { reader.close() }
|
||||
let fileChannelCount: Int = reader.channels
|
||||
guard fileChannelCount >= 1 && fileChannelCount <= lyrebirdMaxFileChannelCount else {
|
||||
throw LyrebirdBufferIOError.invalidChannelCount(fileChannelCount)
|
||||
}
|
||||
let fileFrameCount: Int = reader.frameCount
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(
|
||||
count: max(1, fileFrameCount),
|
||||
channelCount: fileChannelCount
|
||||
)
|
||||
buffer.setSampleRate(reader.sampleRate)
|
||||
try portableReadAllChannels(
|
||||
reader, into: buffer,
|
||||
framesToRead: fileFrameCount, normalise: normalise
|
||||
)
|
||||
return buffer
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - fill(fromFile:channel:normalise:)
|
||||
@@ -178,6 +233,8 @@ public extension LyrebirdBuffer {
|
||||
)
|
||||
precondition(isValid, "fill(fromFile:) called on an invalidated LyrebirdBuffer")
|
||||
|
||||
let framesToRead: Int
|
||||
#if canImport(AudioToolbox)
|
||||
var fileRef: ExtAudioFileRef?
|
||||
let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef)
|
||||
guard openStatus == noErr, let fileRef: ExtAudioFileRef else {
|
||||
@@ -193,7 +250,7 @@ public extension LyrebirdBuffer {
|
||||
}
|
||||
|
||||
self.setSampleRate(fileSampleRate)
|
||||
let framesToRead: Int = min(fileFrameCount, count)
|
||||
framesToRead = min(fileFrameCount, count)
|
||||
try readSamples(
|
||||
from: fileRef,
|
||||
into: self,
|
||||
@@ -203,6 +260,22 @@ public extension LyrebirdBuffer {
|
||||
framesToRead: framesToRead,
|
||||
normalise: normalise
|
||||
)
|
||||
#else
|
||||
let reader: WavFileReader = try WavFileReader(url: url)
|
||||
defer { reader.close() }
|
||||
let fileChannelCount: Int = reader.channels
|
||||
guard channel < fileChannelCount else {
|
||||
throw LyrebirdBufferIOError.channelOutOfRange(
|
||||
requested: channel, available: fileChannelCount
|
||||
)
|
||||
}
|
||||
self.setSampleRate(reader.sampleRate)
|
||||
framesToRead = min(reader.frameCount, count)
|
||||
try portableReadMono(
|
||||
reader, into: self, channel: channel,
|
||||
framesToRead: framesToRead, normalise: normalise
|
||||
)
|
||||
#endif
|
||||
|
||||
// Zero-pad if the file was shorter than the buffer.
|
||||
if framesToRead < count {
|
||||
@@ -294,6 +367,7 @@ public extension LyrebirdBuffer {
|
||||
return
|
||||
}
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
// File format: container/encoding/endianness per `format`.
|
||||
var fileFormat: AudioStreamBasicDescription =
|
||||
format.makeFileASBD(sampleRate: sampleRate, channels: channelCount)
|
||||
@@ -366,11 +440,57 @@ public extension LyrebirdBuffer {
|
||||
srcOffset += samplesThisChunk
|
||||
}
|
||||
}
|
||||
#else
|
||||
// Portable WAV output. The Apple-only containers (CAF / AIFF-C / AAC /
|
||||
// ALAC) have no portable encoder; RF64 was already handled above by the
|
||||
// cross-platform `RF64Writer`. Everything else is a classic-RIFF WAV.
|
||||
let encoding: WavEncoding = try Self.wavEncoding(for: format)
|
||||
let writer: WavFileWriter = try WavFileWriter(
|
||||
url: url, channels: channelCount, sampleRate: sampleRate, encoding: encoding
|
||||
)
|
||||
// Finalize even if a write throws partway, so the file's header sizes
|
||||
// are patched rather than left at zero. `finalize()` is idempotent.
|
||||
defer { try? writer.finalize() }
|
||||
let samplesPerChunk: Int = lyrebirdFileIOChunkFrames * channelCount
|
||||
var writeBuf: [Float] = [Float](repeating: 0, count: samplesPerChunk)
|
||||
try withStorage { storage, frameCount, nch in
|
||||
let totalSamples: Int = frameCount * nch
|
||||
var srcOffset: Int = 0
|
||||
while srcOffset < totalSamples {
|
||||
let samplesThisChunk: Int = min(samplesPerChunk, totalSamples - srcOffset)
|
||||
let framesThisChunk: Int = samplesThisChunk / nch
|
||||
for i: Int in 0..<samplesThisChunk {
|
||||
writeBuf[i] = Float(storage[srcOffset + i])
|
||||
}
|
||||
try writer.write(interleaved: writeBuf, frames: framesThisChunk)
|
||||
srcOffset += samplesThisChunk
|
||||
}
|
||||
}
|
||||
try writer.finalize()
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !canImport(AudioToolbox)
|
||||
/// Maps a WAV ``AudioFileFormat`` to a ``WavEncoding`` for the portable
|
||||
/// writer; the Apple-only containers throw
|
||||
/// ``LyrebirdBufferIOError/unsupportedFormatOnPlatform(_:)``. RF64 is written
|
||||
/// by ``RF64Writer`` before this is reached.
|
||||
static func wavEncoding(for format: AudioFileFormat) throws -> WavEncoding {
|
||||
switch format {
|
||||
case .wavFloat32: return .float32
|
||||
case .wavInt16: return .int16
|
||||
case .wavInt24: return .int24
|
||||
case .rf64Float32, .rf64Int24, .cafFloat32, .aiffFloat32, .aacHigh, .aacMedium, .alac:
|
||||
throw LyrebirdBufferIOError.unsupportedFormatOnPlatform(format)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Private helpers
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
|
||||
/// Query an open `ExtAudioFileRef` for its frame count, channel count, and sample rate.
|
||||
///
|
||||
/// Validates that `mChannelsPerFrame` is in `[1, lyrebirdMaxFileChannelCount]` before
|
||||
@@ -588,3 +708,84 @@ private func readAllChannels(
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
|
||||
// MARK: - Portable read helpers (non-Apple)
|
||||
|
||||
/// Reads one channel of a WAV into a mono buffer's storage, in chunks, with
|
||||
/// optional peak normalisation. Mirrors the Apple ``readSamples`` helper.
|
||||
private func portableReadMono(
|
||||
_ reader: WavFileReader,
|
||||
into buffer: LyrebirdBuffer,
|
||||
channel: Int,
|
||||
framesToRead: Int,
|
||||
normalise: Bool
|
||||
) throws {
|
||||
let fileChannelCount: Int = reader.channels
|
||||
try buffer.withMutableStorage { storage, _, _ in
|
||||
var destOffset: Int = 0
|
||||
while destOffset < framesToRead {
|
||||
let framesThisChunk: Int = min(lyrebirdFileIOChunkFrames, framesToRead - destOffset)
|
||||
let block: [Float] = try reader.read(frames: framesThisChunk)
|
||||
let framesRead: Int = fileChannelCount > 0 ? block.count / fileChannelCount : 0
|
||||
if framesRead == 0 { break }
|
||||
for i: Int in 0..<framesRead {
|
||||
storage[destOffset + i] = Double(block[i * fileChannelCount + channel])
|
||||
}
|
||||
destOffset += framesRead
|
||||
}
|
||||
|
||||
if normalise && framesToRead > 0 {
|
||||
var peak: Double = 0.0
|
||||
for i: Int in 0..<framesToRead {
|
||||
let v: Double = abs(storage[i])
|
||||
if v > peak { peak = v }
|
||||
}
|
||||
if peak > 0.0 {
|
||||
for i: Int in 0..<framesToRead { storage[i] /= peak }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads every channel of a WAV into an interleaved multichannel buffer, in
|
||||
/// chunks, with optional global-peak normalisation. Mirrors ``readAllChannels``.
|
||||
private func portableReadAllChannels(
|
||||
_ reader: WavFileReader,
|
||||
into buffer: LyrebirdBuffer,
|
||||
framesToRead: Int,
|
||||
normalise: Bool
|
||||
) throws {
|
||||
let fileChannelCount: Int = reader.channels
|
||||
let bufChannelCount: Int = buffer.channelCount
|
||||
try buffer.withMutableStorage { storage, _, _ in
|
||||
var destFrame: Int = 0
|
||||
while destFrame < framesToRead {
|
||||
let framesThisChunk: Int = min(lyrebirdFileIOChunkFrames, framesToRead - destFrame)
|
||||
let block: [Float] = try reader.read(frames: framesThisChunk)
|
||||
let framesRead: Int = fileChannelCount > 0 ? block.count / fileChannelCount : 0
|
||||
if framesRead == 0 { break }
|
||||
for f: Int in 0..<framesRead {
|
||||
for ch: Int in 0..<bufChannelCount {
|
||||
storage[(destFrame + f) * bufChannelCount + ch] =
|
||||
Double(block[f * fileChannelCount + ch])
|
||||
}
|
||||
}
|
||||
destFrame += framesRead
|
||||
}
|
||||
|
||||
if normalise && framesToRead > 0 {
|
||||
let totalSamples: Int = framesToRead * bufChannelCount
|
||||
var peak: Double = 0.0
|
||||
for i: Int in 0..<totalSamples {
|
||||
let v: Double = abs(storage[i])
|
||||
if v > peak { peak = v }
|
||||
}
|
||||
if peak > 0.0 {
|
||||
for i: Int in 0..<totalSamples { storage[i] /= peak }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
// MARK: - LyrebirdBuffer wavetable generation extensions
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// WavEncoding.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// PCM sample encodings supported by Lyrebird's portable WAV reader/writer.
|
||||
///
|
||||
/// The portable WAV codec exists so offline render (`NRTDriver`), disk streaming
|
||||
/// generators, and buffer file I/O keep working on platforms without Apple's
|
||||
/// `AudioToolbox`/`ExtAudioFile`. It handles canonical RIFF/WAVE with a single
|
||||
/// `fmt ` chunk and a single `data` chunk — the format every tool writes and
|
||||
/// reads. CAF and AIFF containers remain Apple-only (they route through
|
||||
/// `ExtAudioFile` under `#if canImport(AudioToolbox)`).
|
||||
public enum WavEncoding: Sendable, Equatable {
|
||||
/// 32-bit IEEE float (WAVE format tag 3). The default — lossless for the
|
||||
/// engine's internal `Double`/`Float` sample representation.
|
||||
case float32
|
||||
/// 16-bit signed integer PCM (WAVE format tag 1).
|
||||
case int16
|
||||
/// 24-bit signed integer PCM, packed 3 bytes/sample (WAVE format tag 1).
|
||||
case int24
|
||||
|
||||
/// WAVE `wFormatTag`: 1 = integer PCM, 3 = IEEE float.
|
||||
var formatTag: UInt16 {
|
||||
switch self {
|
||||
case .float32: return 3
|
||||
case .int16, .int24: return 1
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes per single-channel sample.
|
||||
var bytesPerSample: Int {
|
||||
switch self {
|
||||
case .float32: return 4
|
||||
case .int16: return 2
|
||||
case .int24: return 3
|
||||
}
|
||||
}
|
||||
|
||||
/// Bits per single-channel sample (WAVE `wBitsPerSample`).
|
||||
var bitsPerSample: UInt16 {
|
||||
UInt16(bytesPerSample * 8)
|
||||
}
|
||||
|
||||
/// Whether this is an integer PCM tag.
|
||||
///
|
||||
/// RIFF holds non-PCM tags to a stricter header: the `fmt ` body must
|
||||
/// declare `cbSize` (18 bytes rather than 16) and the file must carry a
|
||||
/// `fact` chunk. `WavFileWriter` branches on this.
|
||||
var isPCM: Bool {
|
||||
switch self {
|
||||
case .int16, .int24: return true
|
||||
case .float32: return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// WavFileError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Errors thrown by the portable WAV reader/writer.
|
||||
public enum WavFileError: Error, Equatable {
|
||||
/// The destination file could not be created.
|
||||
case cannotCreate(URL)
|
||||
/// The source file could not be opened for reading.
|
||||
case cannotOpen(URL)
|
||||
/// The file is not a RIFF/WAVE container (bad magic).
|
||||
case notWave
|
||||
/// The file's `fmt ` chunk describes an encoding the portable codec does not
|
||||
/// handle (only int16 / int24 / float32 PCM are supported; use the
|
||||
/// `AudioToolbox` path on Apple for compressed or exotic formats).
|
||||
case unsupportedFormat(formatTag: UInt16, bitsPerSample: UInt16)
|
||||
/// The file ended before the header or declared data could be read. Also
|
||||
/// covers a `fmt ` chunk too short to hold the fields it must declare.
|
||||
case truncated
|
||||
/// A plain WAV cannot describe more than 4 GB — its RIFF and `data` sizes
|
||||
/// are 32-bit. Writing past that needs RF64/W64 instead.
|
||||
case fileTooLarge(bytes: Int)
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
// WavFileReader.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Streaming reader for canonical RIFF/WAVE PCM files, portable to every
|
||||
/// platform (no `AudioToolbox` dependency).
|
||||
///
|
||||
/// Parses the `fmt ` and `data` chunks at construction, then serves interleaved
|
||||
/// `Float` samples in `[-1, 1]` a block at a time via ``read(frames:)`` — the
|
||||
/// mirror of ``WavFileWriter`` and the shape `NRTDriver`'s input path needs.
|
||||
public final class WavFileReader {
|
||||
|
||||
/// Interleaved channel count.
|
||||
public let channels: Int
|
||||
/// Sample rate in Hz.
|
||||
public let sampleRate: Double
|
||||
/// Total number of frames (per-channel sample groups) in the file.
|
||||
public let frameCount: Int
|
||||
/// Decoded PCM encoding.
|
||||
public let encoding: WavEncoding
|
||||
|
||||
private let handle: FileHandle
|
||||
private let bytesPerFrame: Int
|
||||
private var framesRemaining: Int
|
||||
|
||||
/// Opens `url` and parses its WAVE header.
|
||||
public init(url: URL) throws {
|
||||
guard let h: FileHandle = try? FileHandle(forReadingFrom: url) else {
|
||||
throw WavFileError.cannotOpen(url)
|
||||
}
|
||||
self.handle = h
|
||||
|
||||
// RIFF/WAVE magic: "RIFF" <size:4> "WAVE".
|
||||
let riff: Data = try Self.readExact(h, 12)
|
||||
guard riff.prefix(4).elementsEqual(Array("RIFF".utf8)),
|
||||
riff.subdata(in: 8..<12).elementsEqual(Array("WAVE".utf8)) else {
|
||||
throw WavFileError.notWave
|
||||
}
|
||||
|
||||
var fmtTag: UInt16 = 0
|
||||
var numChannels: UInt16 = 0
|
||||
var rate: UInt32 = 0
|
||||
var bits: UInt16 = 0
|
||||
var dataLength: Int = 0
|
||||
var foundFmt: Bool = false
|
||||
var foundData: Bool = false
|
||||
// File length, for clamping a `data` size the file cannot back. Taken
|
||||
// by seeking to the end and back rather than stat-ing the path, so it
|
||||
// describes the handle actually being read.
|
||||
let scanStart: UInt64 = try h.offset()
|
||||
let fileByteCount: Int = Int(try h.seekToEnd())
|
||||
try h.seek(toOffset: scanStart)
|
||||
|
||||
// Walk chunks until the data chunk is located (its body is left unread
|
||||
// so reads stream from the current file offset).
|
||||
while true {
|
||||
guard let chunkHeader: Data = try? Self.readExact(h, 8), chunkHeader.count == 8 else {
|
||||
break
|
||||
}
|
||||
let id: Data = chunkHeader.prefix(4)
|
||||
let size: Int = Int(Self.readLE32(chunkHeader, at: 4))
|
||||
if id.elementsEqual(Array("fmt ".utf8)) {
|
||||
// A `fmt ` chunk always carries at least the 16 PCM bytes.
|
||||
// Anything shorter is malformed, and reading the fields at
|
||||
// their fixed offsets would index past the chunk and trap.
|
||||
guard size >= Self.minimumFmtChunkSize else { throw WavFileError.truncated }
|
||||
let fmt: Data = try Self.readExact(h, size)
|
||||
guard fmt.count >= Self.minimumFmtChunkSize else { throw WavFileError.truncated }
|
||||
fmtTag = Self.readLE16(fmt, at: 0)
|
||||
numChannels = Self.readLE16(fmt, at: 2)
|
||||
rate = Self.readLE32(fmt, at: 4)
|
||||
bits = Self.readLE16(fmt, at: 14)
|
||||
// WAVE_FORMAT_EXTENSIBLE is what most 24-bit and multichannel
|
||||
// writers emit; the real encoding lives in the first two bytes
|
||||
// of the SubFormat GUID, and the rest of the header is
|
||||
// identical. Rejecting it outright would refuse ordinary files.
|
||||
if fmtTag == Self.waveFormatExtensible, fmt.count >= Self.extensibleFmtChunkSize {
|
||||
fmtTag = Self.readLE16(fmt, at: Self.subFormatTagOffset)
|
||||
}
|
||||
foundFmt = true
|
||||
// Chunks are word-aligned: skip a pad byte after an odd size.
|
||||
if size % 2 == 1 { _ = try? Self.readExact(h, 1) }
|
||||
} else if id.elementsEqual(Array("data".utf8)) {
|
||||
// Trust the file, but not past its own end: streaming writers
|
||||
// leave a placeholder size (often 0xFFFFFFFF) they never patch,
|
||||
// and believing it yields a nonsense frame count and a
|
||||
// `.truncated` throw partway through a render instead of a
|
||||
// clean EOF.
|
||||
let remaining: Int = max(0, fileByteCount - Int(try h.offset()))
|
||||
dataLength = min(size, remaining)
|
||||
foundData = true
|
||||
break
|
||||
} else {
|
||||
// Unknown chunk (e.g. "fact", "LIST"): skip its padded body by
|
||||
// seeking. Reading it would materialise the whole thing just to
|
||||
// discard it, and a file with embedded artwork or a large
|
||||
// "LIST" ahead of `data` makes that a real allocation.
|
||||
let skip: Int = size + (size % 2)
|
||||
let current: UInt64 = try h.offset()
|
||||
let target: UInt64 = current + UInt64(max(0, skip))
|
||||
guard target <= UInt64(fileByteCount) else { break }
|
||||
try h.seek(toOffset: target)
|
||||
}
|
||||
}
|
||||
|
||||
guard foundFmt, foundData else { throw WavFileError.truncated }
|
||||
guard let enc: WavEncoding = Self.encoding(formatTag: fmtTag, bits: bits) else {
|
||||
throw WavFileError.unsupportedFormat(formatTag: fmtTag, bitsPerSample: bits)
|
||||
}
|
||||
|
||||
self.encoding = enc
|
||||
self.channels = Int(numChannels)
|
||||
self.sampleRate = Double(rate)
|
||||
self.bytesPerFrame = Int(numChannels) * enc.bytesPerSample
|
||||
let totalFrames: Int = bytesPerFrame > 0 ? dataLength / bytesPerFrame : 0
|
||||
self.frameCount = totalFrames
|
||||
self.framesRemaining = totalFrames
|
||||
}
|
||||
|
||||
/// Reads up to `frames` frames, returning interleaved `Float` samples. The
|
||||
/// returned array holds `framesRead * channels` values; `framesRead` may be
|
||||
/// smaller than requested at end of file (and zero once exhausted).
|
||||
public func read(frames: Int) throws -> [Float] {
|
||||
let toRead: Int = min(frames, framesRemaining)
|
||||
guard toRead > 0 else { return [] }
|
||||
let byteCount: Int = toRead * bytesPerFrame
|
||||
let raw: Data = try Self.readExact(handle, byteCount)
|
||||
framesRemaining -= toRead
|
||||
|
||||
let sampleCount: Int = toRead * channels
|
||||
var out: [Float] = [Float](repeating: 0, count: sampleCount)
|
||||
raw.withUnsafeBytes { (rawPtr: UnsafeRawBufferPointer) in
|
||||
switch encoding {
|
||||
case .float32:
|
||||
for i: Int in 0..<sampleCount {
|
||||
let bits: UInt32 = Self.loadLE32(rawPtr, byteOffset: i * 4)
|
||||
out[i] = Float(bitPattern: bits)
|
||||
}
|
||||
case .int16:
|
||||
let inv: Float = 1.0 / 32768.0
|
||||
for i: Int in 0..<sampleCount {
|
||||
let v: Int16 = Int16(bitPattern: Self.loadLE16(rawPtr, byteOffset: i * 2))
|
||||
out[i] = Float(v) * inv
|
||||
}
|
||||
case .int24:
|
||||
let inv: Float = 1.0 / 8388608.0
|
||||
for i: Int in 0..<sampleCount {
|
||||
let b0: Int32 = Int32(rawPtr[i * 3])
|
||||
let b1: Int32 = Int32(rawPtr[i * 3 + 1])
|
||||
let b2: Int32 = Int32(rawPtr[i * 3 + 2])
|
||||
var v: Int32 = b0 | (b1 << 8) | (b2 << 16)
|
||||
if (v & 0x0080_0000) != 0 { v |= ~0x00FF_FFFF } // sign-extend 24→32
|
||||
out[i] = Float(v) * inv
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Advances past `frames` frames without materialising them.
|
||||
///
|
||||
/// Seeks rather than reading: skipping into a long file — a start offset a
|
||||
/// minute into a stereo 48 kHz recording is ~23 M samples — would otherwise
|
||||
/// allocate the whole skipped region just to discard it. Skipping past the
|
||||
/// end simply exhausts the reader.
|
||||
///
|
||||
/// - Parameter frames: Frames to advance by. Non-positive values do nothing.
|
||||
public func skip(frames: Int) throws {
|
||||
let toSkip: Int = min(frames, framesRemaining)
|
||||
guard toSkip > 0 else { return }
|
||||
let current: UInt64 = try handle.offset()
|
||||
try handle.seek(toOffset: current + UInt64(toSkip * bytesPerFrame))
|
||||
framesRemaining -= toSkip
|
||||
}
|
||||
|
||||
/// Closes the underlying file handle.
|
||||
public func close() {
|
||||
try? handle.close()
|
||||
}
|
||||
|
||||
// MARK: - Parsing helpers
|
||||
|
||||
/// Smallest legal `fmt ` chunk: the 16 bytes of a plain PCM header.
|
||||
private static let minimumFmtChunkSize: Int = 16
|
||||
/// `fmt ` size that carries the full `WAVEFORMATEXTENSIBLE` payload.
|
||||
private static let extensibleFmtChunkSize: Int = 40
|
||||
/// Byte offset of the SubFormat GUID's leading format tag within `fmt `.
|
||||
private static let subFormatTagOffset: Int = 24
|
||||
/// `WAVE_FORMAT_EXTENSIBLE` — the real tag hides in the SubFormat GUID.
|
||||
private static let waveFormatExtensible: UInt16 = 0xFFFE
|
||||
|
||||
private static func encoding(formatTag: UInt16, bits: UInt16) -> WavEncoding? {
|
||||
switch (formatTag, bits) {
|
||||
case (3, 32): return .float32
|
||||
case (1, 16): return .int16
|
||||
case (1, 24): return .int24
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
|
||||
private static func readExact(_ h: FileHandle, _ count: Int) throws -> Data {
|
||||
guard count > 0 else { return Data() }
|
||||
guard let d: Data = try h.read(upToCount: count), d.count == count else {
|
||||
throw WavFileError.truncated
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
private static func readLE16(_ d: Data, at offset: Int) -> UInt16 {
|
||||
let base: Data.Index = d.startIndex + offset
|
||||
return UInt16(d[base]) | (UInt16(d[base + 1]) << 8)
|
||||
}
|
||||
|
||||
private static func readLE32(_ d: Data, at offset: Int) -> UInt32 {
|
||||
let base: Data.Index = d.startIndex + offset
|
||||
return UInt32(d[base]) | (UInt32(d[base + 1]) << 8)
|
||||
| (UInt32(d[base + 2]) << 16) | (UInt32(d[base + 3]) << 24)
|
||||
}
|
||||
|
||||
private static func loadLE16(_ p: UnsafeRawBufferPointer, byteOffset: Int) -> UInt16 {
|
||||
UInt16(p[byteOffset]) | (UInt16(p[byteOffset + 1]) << 8)
|
||||
}
|
||||
|
||||
private static func loadLE32(_ p: UnsafeRawBufferPointer, byteOffset: Int) -> UInt32 {
|
||||
UInt32(p[byteOffset]) | (UInt32(p[byteOffset + 1]) << 8)
|
||||
| (UInt32(p[byteOffset + 2]) << 16) | (UInt32(p[byteOffset + 3]) << 24)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
// WavFileWriter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Streaming writer for canonical RIFF/WAVE PCM files, portable to every
|
||||
/// platform (no `AudioToolbox` dependency).
|
||||
///
|
||||
/// Designed for the offline-render block model: construct once, call
|
||||
/// ``write(interleaved:frames:)`` per rendered block, then ``finalize()`` to
|
||||
/// patch the RIFF/`data` chunk sizes. Samples are supplied interleaved
|
||||
/// (`frame0ch0, frame0ch1, frame1ch0, …`) as `Float` in `[-1, 1]`; integer
|
||||
/// encodings clamp and round, float32 stores losslessly.
|
||||
public final class WavFileWriter {
|
||||
|
||||
private let channels: Int
|
||||
private let encoding: WavEncoding
|
||||
private let handle: FileHandle
|
||||
private var dataBytesWritten: Int = 0
|
||||
private var finalized: Bool = false
|
||||
/// Whether the RIFF word-align pad byte has already been appended.
|
||||
private var padByteWritten: Bool = false
|
||||
/// Byte count of this file's header, which depends on the encoding — see
|
||||
/// ``headerSize(for:)``.
|
||||
private let headerByteCount: Int
|
||||
/// Offset of the `data` chunk's size field, patched by ``finalize()``.
|
||||
private let dataChunkSizeOffset: UInt64
|
||||
|
||||
// Integer PCM uses the canonical 44-byte header: 12 RIFF/WAVE + 24 `fmt `
|
||||
// (8 header + 16 body) + 8 `data` header.
|
||||
private static let pcmHeaderSize: Int = 44
|
||||
/// Non-PCM tags (float32) must declare `cbSize`, making the `fmt ` body 18
|
||||
/// bytes, and must carry a `fact` chunk. That is 2 more `fmt ` bytes plus a
|
||||
/// 12-byte `fact` chunk: 44 + 2 + 12.
|
||||
private static let nonPCMHeaderSize: Int = 58
|
||||
private static let riffChunkSizeOffset: UInt64 = 4
|
||||
/// `fact`'s sample-count field, present only in the non-PCM layout.
|
||||
private static let factSampleCountOffset: UInt64 = 46
|
||||
private static let pcmDataChunkSizeOffset: UInt64 = 40
|
||||
private static let nonPCMDataChunkSizeOffset: UInt64 = 54
|
||||
/// `fmt ` body size for plain PCM tags, and for tags that need `cbSize`.
|
||||
private static let pcmFmtBodySize: UInt32 = 16
|
||||
private static let extendedFmtBodySize: UInt32 = 18
|
||||
/// `fact` chunk body: one `UInt32` sample count.
|
||||
private static let factBodySize: UInt32 = 4
|
||||
|
||||
/// Header length for `encoding`. Non-PCM formats carry more (see above).
|
||||
private static func headerSize(for encoding: WavEncoding) -> Int {
|
||||
encoding.isPCM ? pcmHeaderSize : nonPCMHeaderSize
|
||||
}
|
||||
|
||||
/// - Parameters:
|
||||
/// - url: Destination file path. Overwritten if it exists.
|
||||
/// - channels: Interleaved channel count. Must be ≥ 1.
|
||||
/// - sampleRate: Sample rate in Hz.
|
||||
/// - encoding: PCM encoding. Defaults to ``WavEncoding/float32``.
|
||||
public init(
|
||||
url: URL,
|
||||
channels: Int,
|
||||
sampleRate: Double,
|
||||
encoding: WavEncoding = .float32
|
||||
) throws {
|
||||
precondition(channels >= 1, "WavFileWriter requires at least one channel")
|
||||
self.channels = channels
|
||||
self.encoding = encoding
|
||||
self.headerByteCount = Self.headerSize(for: encoding)
|
||||
self.dataChunkSizeOffset = encoding.isPCM
|
||||
? Self.pcmDataChunkSizeOffset
|
||||
: Self.nonPCMDataChunkSizeOffset
|
||||
|
||||
let header: Data = Self.makeHeader(
|
||||
channels: channels,
|
||||
sampleRate: sampleRate,
|
||||
encoding: encoding
|
||||
)
|
||||
let fm: FileManager = FileManager.default
|
||||
guard fm.createFile(atPath: url.path, contents: header) else {
|
||||
throw WavFileError.cannotCreate(url)
|
||||
}
|
||||
self.handle = try FileHandle(forWritingTo: url)
|
||||
try handle.seekToEnd()
|
||||
}
|
||||
|
||||
/// Appends one block of interleaved `Float` samples.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - samples: Interleaved buffer, length ≥ `frames * channels`.
|
||||
/// - frames: Number of frames (per-channel sample groups) to write.
|
||||
public func write(interleaved samples: [Float], frames: Int) throws {
|
||||
let needed: Int = frames * channels
|
||||
precondition(samples.count >= needed, "interleaved buffer shorter than frames * channels")
|
||||
var out: Data = Data(capacity: needed * encoding.bytesPerSample)
|
||||
switch encoding {
|
||||
case .float32:
|
||||
for i: Int in 0..<needed {
|
||||
var le: UInt32 = samples[i].bitPattern.littleEndian
|
||||
withUnsafeBytes(of: &le) { out.append(contentsOf: $0) }
|
||||
}
|
||||
case .int16:
|
||||
// Full-scale maps to 32767 / 8388607, not 32768 / 8388608, so an
|
||||
// input of exactly +1.0 cannot overflow the signed range. The
|
||||
// reader divides by the power of two, which is the usual pairing;
|
||||
// the resulting round-trip difference is ~0.003 %, well below the
|
||||
// quantisation step.
|
||||
let scale: Float = 32767.0
|
||||
for i: Int in 0..<needed {
|
||||
let clamped: Float = min(1.0, max(-1.0, samples[i]))
|
||||
var le: Int16 = Int16((clamped * scale).rounded()).littleEndian
|
||||
withUnsafeBytes(of: &le) { out.append(contentsOf: $0) }
|
||||
}
|
||||
case .int24:
|
||||
let scale: Float = 8388607.0
|
||||
for i: Int in 0..<needed {
|
||||
let clamped: Float = min(1.0, max(-1.0, samples[i]))
|
||||
let v: Int32 = Int32((clamped * scale).rounded())
|
||||
out.append(UInt8(truncatingIfNeeded: v))
|
||||
out.append(UInt8(truncatingIfNeeded: v >> 8))
|
||||
out.append(UInt8(truncatingIfNeeded: v >> 16))
|
||||
}
|
||||
}
|
||||
try handle.write(contentsOf: out)
|
||||
dataBytesWritten += out.count
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Last-resort finalize: a writer dropped without one leaves an open
|
||||
// descriptor and a header whose sizes are still zero, i.e. a file no
|
||||
// reader can use. Errors here have nowhere to go, hence `try?`.
|
||||
try? finalize()
|
||||
}
|
||||
|
||||
/// Patches the RIFF and `data` chunk sizes and closes the file. Idempotent.
|
||||
public func finalize() throws {
|
||||
guard !finalized else { return }
|
||||
// Chunks are word-aligned: an odd `data` payload (possible with int24)
|
||||
// needs a pad byte, which counts toward the RIFF size but not the
|
||||
// `data` size. Recorded before the patch sequence below, so a
|
||||
// `finalize()` that throws partway and is retried — by an explicit
|
||||
// second call, or by `deinit` — does not append a second pad byte while
|
||||
// sizing the file for one.
|
||||
let padByteCount: Int = dataBytesWritten % 2
|
||||
if padByteCount > 0 && !padByteWritten {
|
||||
try handle.seekToEnd()
|
||||
try handle.write(contentsOf: [UInt8(0)])
|
||||
padByteWritten = true
|
||||
}
|
||||
let riffChunkSize: UInt32 = try Self.riffChunkSize(
|
||||
headerBytes: headerByteCount,
|
||||
dataBytes: dataBytesWritten + padByteCount
|
||||
)
|
||||
let dataChunkSize: UInt32 = UInt32(dataBytesWritten)
|
||||
|
||||
try handle.seek(toOffset: Self.riffChunkSizeOffset)
|
||||
try handle.write(contentsOf: Self.leBytes(riffChunkSize))
|
||||
if !encoding.isPCM {
|
||||
// `fact` carries the per-channel sample count, which is only known
|
||||
// now that writing has finished.
|
||||
let bytesPerFrame: Int = channels * encoding.bytesPerSample
|
||||
let frames: UInt32 = bytesPerFrame > 0
|
||||
? UInt32(dataBytesWritten / bytesPerFrame)
|
||||
: 0
|
||||
try handle.seek(toOffset: Self.factSampleCountOffset)
|
||||
try handle.write(contentsOf: Self.leBytes(frames))
|
||||
}
|
||||
try handle.seek(toOffset: dataChunkSizeOffset)
|
||||
try handle.write(contentsOf: Self.leBytes(dataChunkSize))
|
||||
try handle.close()
|
||||
// Set last: a throw above must leave the writer retryable rather than
|
||||
// latching "finalized" over a file whose sizes are still zero.
|
||||
finalized = true
|
||||
}
|
||||
|
||||
/// RIFF chunk size for a file with this header and payload.
|
||||
///
|
||||
/// Split out so the 4 GB boundary can be tested without writing 4 GB: the
|
||||
/// conversion below would *trap* rather than throw, and a trap in a render
|
||||
/// that has been running for an hour is the worst possible outcome.
|
||||
///
|
||||
/// - Throws: ``WavFileError/fileTooLarge(bytes:)`` past `UInt32.max`.
|
||||
@_spi(LyrebirdExtensions)
|
||||
public static func riffChunkSize(headerBytes: Int, dataBytes: Int) throws -> UInt32 {
|
||||
let payload: Int = headerBytes - 8 + dataBytes
|
||||
guard payload <= Int(UInt32.max) else {
|
||||
throw WavFileError.fileTooLarge(bytes: payload)
|
||||
}
|
||||
return UInt32(payload)
|
||||
}
|
||||
|
||||
// MARK: - Header
|
||||
|
||||
private static func makeHeader(
|
||||
channels: Int,
|
||||
sampleRate: Double,
|
||||
encoding: WavEncoding
|
||||
) -> Data {
|
||||
let numChannels: UInt16 = UInt16(channels)
|
||||
let rate: UInt32 = UInt32(sampleRate.rounded())
|
||||
let blockAlign: UInt16 = UInt16(channels * encoding.bytesPerSample)
|
||||
let byteRate: UInt32 = rate * UInt32(blockAlign)
|
||||
// RIFF requires a non-PCM tag to declare `cbSize` (so the `fmt ` body
|
||||
// is 18 bytes, not 16) and to carry a `fact` chunk. Strict readers
|
||||
// reject a float32 file that omits either.
|
||||
let isPCM: Bool = encoding.isPCM
|
||||
let subchunk1Size: UInt32 = isPCM ? pcmFmtBodySize : extendedFmtBodySize
|
||||
|
||||
var d: Data = Data(capacity: headerSize(for: encoding))
|
||||
d.append(contentsOf: Array("RIFF".utf8))
|
||||
d.append(contentsOf: leBytes(UInt32(0))) // patched in finalize
|
||||
d.append(contentsOf: Array("WAVE".utf8))
|
||||
d.append(contentsOf: Array("fmt ".utf8))
|
||||
d.append(contentsOf: leBytes(subchunk1Size))
|
||||
d.append(contentsOf: leBytes(encoding.formatTag))
|
||||
d.append(contentsOf: leBytes(numChannels))
|
||||
d.append(contentsOf: leBytes(rate))
|
||||
d.append(contentsOf: leBytes(byteRate))
|
||||
d.append(contentsOf: leBytes(blockAlign))
|
||||
d.append(contentsOf: leBytes(encoding.bitsPerSample))
|
||||
if !isPCM {
|
||||
d.append(contentsOf: leBytes(UInt16(0))) // cbSize: no extension
|
||||
d.append(contentsOf: Array("fact".utf8))
|
||||
d.append(contentsOf: leBytes(factBodySize))
|
||||
d.append(contentsOf: leBytes(UInt32(0))) // patched in finalize
|
||||
}
|
||||
d.append(contentsOf: Array("data".utf8))
|
||||
d.append(contentsOf: leBytes(UInt32(0))) // patched in finalize
|
||||
return d
|
||||
}
|
||||
|
||||
// Extract bytes low-first from the native value. The right shifts already
|
||||
// yield little-endian order on any host, so no `.littleEndian` pre-swap
|
||||
// (which, combined with these shifts, would double-transform on a big-endian host).
|
||||
private static func leBytes(_ value: UInt32) -> [UInt8] {
|
||||
return [UInt8(truncatingIfNeeded: value), UInt8(truncatingIfNeeded: value >> 8),
|
||||
UInt8(truncatingIfNeeded: value >> 16), UInt8(truncatingIfNeeded: value >> 24)]
|
||||
}
|
||||
|
||||
private static func leBytes(_ value: UInt16) -> [UInt8] {
|
||||
return [UInt8(truncatingIfNeeded: value), UInt8(truncatingIfNeeded: value >> 8)]
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
// MARK: - WavetableSet
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Per-child scratch audio bus memory for `ParallelGroup` concurrent evaluation.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,17 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Thread-local-storage APIs: pthread (`pthread_key_*` / `*specific`) on Apple &
|
||||
// POSIX, Win32 (`Tls*`) on Windows.
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif canImport(WinSDK)
|
||||
import WinSDK
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
/// Identifies whether the calling thread is currently inside an audio driver's
|
||||
/// render callback.
|
||||
@@ -25,31 +35,54 @@ import Darwin
|
||||
/// at one TLS pointer read in the steady state.
|
||||
internal enum RTThreadIdentity {
|
||||
|
||||
// MARK: - pthread TLS key
|
||||
// MARK: - TLS key
|
||||
|
||||
/// Sentinel bit pattern stored in the TLS slot to mark "this is an RT
|
||||
/// thread". Stored as `UInt` (Sendable) and bridged to the pointer type
|
||||
/// expected by `pthread_setspecific` / `pthread_getspecific` at use sites.
|
||||
/// thread". Bridged to the pointer type the TLS APIs expect at use sites.
|
||||
/// Any non-zero bit pattern works; `1` is distinct from any real heap
|
||||
/// address.
|
||||
private static let _markerBitPattern: UInt = 1
|
||||
|
||||
/// pthread TLS key. Created lazily on first access — always from a
|
||||
/// non-RT call site (engine init / driver setup) because
|
||||
/// ``warmUp()`` is invoked there. RT call sites read this after the
|
||||
/// warm-up, so `pthread_key_create` never runs on the RT thread.
|
||||
///
|
||||
/// `nonisolated(unsafe)` because `pthread_key_t` (a `CUnsignedInt` on
|
||||
/// Darwin) is a trivially-Sendable scalar; the strict-concurrency
|
||||
/// checker can't see through the C typealias. The key is written exactly
|
||||
/// once during the lazy init closure (synchronised by Swift's static-let
|
||||
/// guarantee) and read-only thereafter.
|
||||
/// TLS key/index. Created lazily on first access — always from a non-RT
|
||||
/// call site (engine init / driver setup) because ``warmUp()`` is invoked
|
||||
/// there, so the allocating call (`pthread_key_create` / `TlsAlloc`) never
|
||||
/// runs on the RT thread. Written exactly once (Swift's static-let
|
||||
/// guarantee), read-only thereafter.
|
||||
#if canImport(WinSDK)
|
||||
private static let _tlsIndex: DWORD = {
|
||||
let index: DWORD = TlsAlloc()
|
||||
// TLS_OUT_OF_INDEXES == 0xFFFFFFFF == DWORD.max.
|
||||
precondition(index != DWORD.max, "TlsAlloc failed")
|
||||
return index
|
||||
}()
|
||||
#else
|
||||
private static let _key: pthread_key_t = {
|
||||
var key: pthread_key_t = 0
|
||||
let status: Int32 = pthread_key_create(&key, nil)
|
||||
precondition(status == 0, "pthread_key_create failed with status \(status)")
|
||||
return key
|
||||
}()
|
||||
#endif
|
||||
|
||||
/// Read the calling thread's TLS slot. O(1), allocation-free, RT-safe.
|
||||
@inline(__always)
|
||||
private static func _tlsGet() -> UnsafeMutableRawPointer? {
|
||||
#if canImport(WinSDK)
|
||||
return TlsGetValue(_tlsIndex)
|
||||
#else
|
||||
return pthread_getspecific(_key)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Write the calling thread's TLS slot. O(1), allocation-free, RT-safe.
|
||||
@inline(__always)
|
||||
private static func _tlsSet(_ value: UnsafeMutableRawPointer?) {
|
||||
#if canImport(WinSDK)
|
||||
_ = TlsSetValue(_tlsIndex, value)
|
||||
#else
|
||||
pthread_setspecific(_key, value)
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - API
|
||||
|
||||
@@ -57,19 +90,23 @@ internal enum RTThreadIdentity {
|
||||
/// site (engine init / driver setup). Avoids a first-touch allocation on
|
||||
/// the RT thread.
|
||||
internal static func warmUp() {
|
||||
#if canImport(WinSDK)
|
||||
_ = _tlsIndex
|
||||
#else
|
||||
_ = _key
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Mark the calling thread as an RT render thread. Idempotent — safe to
|
||||
/// call on every render callback entry; only writes the TLS slot when it
|
||||
/// isn't already marked.
|
||||
///
|
||||
/// RT-safe: at most one `pthread_setspecific` call per thread, otherwise
|
||||
/// a single TLS pointer comparison. No allocation, no locking.
|
||||
/// RT-safe: at most one TLS write per thread, otherwise a single TLS
|
||||
/// pointer comparison. No allocation, no locking.
|
||||
internal static func markCurrentThreadAsRT() {
|
||||
let sentinel: UnsafeMutableRawPointer? = UnsafeMutableRawPointer(bitPattern: _markerBitPattern)
|
||||
if pthread_getspecific(_key) != sentinel {
|
||||
pthread_setspecific(_key, sentinel)
|
||||
if _tlsGet() != sentinel {
|
||||
_tlsSet(sentinel)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +116,7 @@ internal enum RTThreadIdentity {
|
||||
/// any thread.
|
||||
internal static var isCurrentThreadRT: Bool {
|
||||
let sentinel: UnsafeMutableRawPointer? = UnsafeMutableRawPointer(bitPattern: _markerBitPattern)
|
||||
return pthread_getspecific(_key) == sentinel
|
||||
return _tlsGet() == sentinel
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
@@ -87,11 +124,11 @@ internal enum RTThreadIdentity {
|
||||
///
|
||||
/// Production never unmarks — an RT render thread stays an RT render thread for the
|
||||
/// engine's life. But tests that call ``markCurrentThreadAsRT()`` on a transient
|
||||
/// `DispatchQueue(label:)` worker must clear it before that pthread returns to the
|
||||
/// `DispatchQueue(label:)` worker must clear it before that thread returns to the
|
||||
/// system pool; otherwise the stale marker can false-trip `_lyrebirdAssertNotOnRTThread`
|
||||
/// in a later test that the pool hands the same thread. Not compiled in release.
|
||||
internal static func _clearCurrentThreadRTMarkForTesting() {
|
||||
pthread_setspecific(_key, nil)
|
||||
_tlsSet(nil)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
import Synchronization
|
||||
|
||||
@@ -901,9 +901,7 @@ public final class SynthesisEngine {
|
||||
self.bufferSwapKillQueue = SPSCQueue<UnsafeRawPointer>(
|
||||
capacity: SynthesisEngine.bufferSwapKillQueueCapacity
|
||||
)
|
||||
var tbInfo: mach_timebase_info_data_t = mach_timebase_info_data_t()
|
||||
mach_timebase_info(&tbInfo)
|
||||
_machTicksToNs = Double(tbInfo.numer) / Double(tbInfo.denom)
|
||||
_machTicksToNs = LyrebirdMonotonicClock.ticksToNanos
|
||||
_blockDurationNs = (Double(blockSize) / sampleRate) * SynthesisEngine.nanosecondsPerSecond
|
||||
|
||||
// Install mainGroup as the sole initial child of rootGroup. This runs pre-start on the
|
||||
@@ -1163,13 +1161,25 @@ public final class SynthesisEngine {
|
||||
/// Steps:
|
||||
/// 1. Drain `pendingQueue` of any events that never reached `applyEvent`,
|
||||
/// releasing `.remove` events' retained refs to balance ARC.
|
||||
/// 2. `mainGroup._drainNodes` drops every direct child; ARC cascades
|
||||
/// through nested `PreparedNode` chains to release entire subtrees.
|
||||
/// 2. `mainGroup._drainNodes` drops every direct child, unbinding each
|
||||
/// drained synth (and every synth nested inside a drained `Group`
|
||||
/// subtree) from `self` via `_unbindNodeAndDescendants(_:)` before ARC
|
||||
/// cascades through the nested `PreparedNode` chains to release the
|
||||
/// entire subtree.
|
||||
/// 3. Walk `rootGroup` and preserve only the `PreparedNode` that wraps
|
||||
/// `mainGroup`. All other direct children (`.before(mainGroup)` /
|
||||
/// `.after(mainGroup)` installations) are unlinked.
|
||||
/// `.after(mainGroup)` installations) are unlinked and unbound the
|
||||
/// same way.
|
||||
/// 4. Reset `_synthesizerCount` / `_groupCount` to zero.
|
||||
/// 5. Reseed `nodeTreeMirror` so SwiftUI observers see the empty baseline.
|
||||
///
|
||||
/// Unbinding here (rather than leaving it to ARC) is what lets a caller
|
||||
/// re-`add` the same synth instance — to this engine or a different one —
|
||||
/// immediately after `stop()` returns, with no `EngineAddError.doubleAdd`
|
||||
/// and no "wait one processBlock" constraint (unlike `remove(_:)`, whose
|
||||
/// unbind races the RT thread and therefore documents that wait). `stop()`
|
||||
/// has already halted the RT thread via `driver.stop()`, so there is no
|
||||
/// such race here.
|
||||
private func _drainAllNonPersistentNodes() {
|
||||
// 1. Pending queue (events posted by main but never dequeued by the RT
|
||||
// thread). `.remove` carries an `Unmanaged.passRetained` ref that
|
||||
@@ -1196,9 +1206,12 @@ public final class SynthesisEngine {
|
||||
// `carryOverEvents`'s and is wiped at the top of the next block,
|
||||
// so any release here would also double-fire.
|
||||
_releaseRemoveRefs(in: &carryOverEvents)
|
||||
// 3. mainGroup direct children — ARC cascades to nested chains.
|
||||
mainGroup._drainNodes { _ in }
|
||||
// 4. rootGroup: preserve only the mainGroup PreparedNode.
|
||||
// 3. mainGroup direct children — unbind each drained synth (and its
|
||||
// nested-Group descendants), then let ARC cascade release the
|
||||
// subtree as before.
|
||||
mainGroup._drainNodes { n in self._unbindNodeAndDescendants(n) }
|
||||
// 4. rootGroup: preserve only the mainGroup PreparedNode; unbind and
|
||||
// unlink everything else.
|
||||
_drainRootKeepingMainGroup()
|
||||
// 5. Counters and mirror.
|
||||
_synthesizerCount.store(0, ordering: .relaxed)
|
||||
@@ -1206,6 +1219,30 @@ public final class SynthesisEngine {
|
||||
nodeTreeMirror.reset(rootGroup: rootGroup, mainGroup: mainGroup)
|
||||
}
|
||||
|
||||
/// Unbind `node.synth` from `self` (no-op if `node.synth` is not a
|
||||
/// `SynthesizerBase`, or is already unbound), then recurse into a nested
|
||||
/// `Group`'s children so every synth in a drained subtree is fully
|
||||
/// detached — not just the top-level node the caller drained.
|
||||
///
|
||||
/// `ParallelGroup` children are intentionally not descended into: they are
|
||||
/// added via `ParallelGroup.add(_:)` rather than `engine.add(_:)`, so they
|
||||
/// were never individually bound in the first place (only the enclosing
|
||||
/// `ParallelGroup` synth — which is not a `SynthesizerBase` either — was
|
||||
/// ever passed to `engine.add`). Same opaque-`ParallelGroup` convention as
|
||||
/// `Group.removeRecursive` / `Group._walkSubtreeForCountDecrement`.
|
||||
///
|
||||
/// Called only from `stop()`'s teardown path, after `driver.stop()` has
|
||||
/// returned — main thread, RT thread not running, safe to call `_unbind`.
|
||||
private func _unbindNodeAndDescendants(_ node: PreparedNode) {
|
||||
(node.synth as? SynthesizerBase)?._unbind(from: self)
|
||||
guard let nested: Group = node.groupRef else { return }
|
||||
var child: PreparedNode? = nested.head
|
||||
while let n: PreparedNode = child {
|
||||
_unbindNodeAndDescendants(n)
|
||||
child = n.next
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk `buf` and release any `.remove` event's `Unmanaged.passRetained`
|
||||
/// ref, then clear the array keeping its reserved capacity. Used during
|
||||
/// `stop()` teardown to balance ARC on events that were staged on the RT
|
||||
@@ -1222,7 +1259,10 @@ public final class SynthesisEngine {
|
||||
/// Walk `rootGroup`'s linked list, preserve only the `PreparedNode` whose
|
||||
/// `synth === mainGroup`, and unlink everything else. Pre/post-main user
|
||||
/// nodes (installed via `.before(mainGroup)` / `.after(mainGroup)`) are
|
||||
/// dropped; their refs release via ARC as the enclosing scope ends.
|
||||
/// unbound (see `_unbindNodeAndDescendants(_:)`) and dropped; their refs
|
||||
/// release via ARC as the enclosing scope ends. `mainGroup` itself is left
|
||||
/// untouched — never unbound (it is not a `SynthesizerBase` to begin with)
|
||||
/// and never unlinked.
|
||||
private func _drainRootKeepingMainGroup() {
|
||||
var mainNode: PreparedNode? = nil
|
||||
var node: PreparedNode? = rootGroup.head
|
||||
@@ -1232,6 +1272,8 @@ public final class SynthesisEngine {
|
||||
n.prev = nil
|
||||
if n.synth === mainGroup {
|
||||
mainNode = n
|
||||
} else {
|
||||
_unbindNodeAndDescendants(n)
|
||||
}
|
||||
node = next
|
||||
}
|
||||
@@ -1516,7 +1558,7 @@ public final class SynthesisEngine {
|
||||
/// Process one block of audio.
|
||||
/// Called by the Core Audio render callback and directly by tests / NRTDriver.
|
||||
public func processBlock(inputSamples: [[Float]]) {
|
||||
let blockStartTick: UInt64 = mach_absolute_time()
|
||||
let blockStartTick: UInt64 = LyrebirdMonotonicClock.ticks()
|
||||
// 1. Zero all audio buses (control buses are never zeroed — they persist)
|
||||
for i: Int in 0..<audioBuses.count {
|
||||
audioBuses[i].withUnsafeMutableBufferPointer { buf in
|
||||
@@ -1632,7 +1674,7 @@ public final class SynthesisEngine {
|
||||
_currentTime.store(blockStart + SampleTime(blockSize), ordering: .releasing)
|
||||
|
||||
// 5. CPU usage statistics — RT-private EMA + atomic publish.
|
||||
let elapsedNs: Double = Double(mach_absolute_time() &- blockStartTick) * _machTicksToNs
|
||||
let elapsedNs: Double = Double(LyrebirdMonotonicClock.ticks() &- blockStartTick) * _machTicksToNs
|
||||
let cpuLoad: Double = elapsedNs / _blockDurationNs
|
||||
|
||||
if _cpuEMAInitialized {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
// MARK: - Block-constant generator read helper
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
/// Peak ODF value across one audio block. Onsets are impulsive, so the max
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// File-scope zero-fill block for RunningMax — fallback when upstream returns no channel.
|
||||
private let runningMaxZeroBlock: [Double] = [Double](
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// File-scope zero-fill block for RunningMin — fallback when upstream returns no channel.
|
||||
private let runningMinZeroBlock: [Double] = [Double](
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// File-scope zero-fill block for Slope — fallback when upstream returns no channel.
|
||||
private let slopeZeroBlock: [Double] = [Double](
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// File-scope zero-fill block for ZeroCrossing — fallback when upstream returns no channel.
|
||||
private let zeroCrossingZeroBlock: [Double] = [Double](
|
||||
|
||||
@@ -5,8 +5,10 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
import Synchronization
|
||||
#if canImport(AudioToolbox)
|
||||
import AudioToolbox
|
||||
#endif
|
||||
|
||||
/// Streaming soundfile input generators.
|
||||
///
|
||||
@@ -133,7 +135,20 @@ public enum DiskIn {
|
||||
|
||||
// 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
|
||||
|
||||
@@ -160,6 +175,9 @@ public enum DiskIn {
|
||||
/// 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,
|
||||
@@ -188,7 +206,13 @@ public enum DiskIn {
|
||||
_zeroFallback = makeSampleBuffer()
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
|
||||
// Open file
|
||||
// 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 {
|
||||
@@ -196,7 +220,6 @@ public enum DiskIn {
|
||||
}
|
||||
_fileRef = rawRef
|
||||
|
||||
// Query file channel count
|
||||
var fileFmt: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||
var propSize: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
|
||||
let queryStatus: OSStatus = ExtAudioFileGetProperty(rawRef,
|
||||
@@ -206,11 +229,10 @@ public enum DiskIn {
|
||||
ExtAudioFileDispose(rawRef)
|
||||
throw DiskInError.cannotOpenFile(queryStatus)
|
||||
}
|
||||
let fileChannels: Int = min(Int(fileFmt.mChannelsPerFrame), channelCount)
|
||||
fileChannels = min(Int(fileFmt.mChannelsPerFrame), channelCount)
|
||||
_fileChannelCount = fileChannels
|
||||
_readRateScale = 1.0
|
||||
|
||||
// Set client format: interleaved Float32 at engine SR.
|
||||
// ExtAudioFile performs SR conversion transparently.
|
||||
let float32ByteSize: UInt32 = UInt32(MemoryLayout<Float>.size)
|
||||
let float32BitsPerChannel: UInt32 = 32
|
||||
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
@@ -234,6 +256,17 @@ public enum DiskIn {
|
||||
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.
|
||||
@@ -281,7 +314,11 @@ public enum DiskIn {
|
||||
// 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
|
||||
@@ -326,14 +363,17 @@ public enum DiskIn {
|
||||
}
|
||||
|
||||
guard !_atEOF || loop else { return 0 }
|
||||
guard let fileRef: ExtAudioFileRef = _fileRef 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
|
||||
@@ -350,10 +390,29 @@ public enum DiskIn {
|
||||
)
|
||||
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 readStatus == noErr else { break }
|
||||
guard readOK else { break }
|
||||
|
||||
let framesRead: Int = Int(framesToRead)
|
||||
for f: Int in 0..<framesRead {
|
||||
for ch: Int in 0..<_fileChannelCount {
|
||||
_halfBuffers[halfIdx][ch][totalRead + f] =
|
||||
@@ -364,9 +423,21 @@ public enum DiskIn {
|
||||
|
||||
if framesRead < remaining {
|
||||
if loop {
|
||||
#if canImport(AudioToolbox)
|
||||
let seekStatus: OSStatus = ExtAudioFileSeek(fileRef, 0)
|
||||
guard seekStatus == noErr else { _atEOF = true; break }
|
||||
// Continue the loop to fill the rest from the file start.
|
||||
#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
|
||||
@@ -451,7 +522,7 @@ public enum DiskIn {
|
||||
|
||||
let rate: Double = min(rateClampHigh,
|
||||
max(rateClampLow, Double(rateSamples[i])))
|
||||
_readPos += rate
|
||||
_readPos += rate * _readRateScale
|
||||
}
|
||||
|
||||
return _result
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import AudioToolbox
|
||||
|
||||
// MARK: - Errors
|
||||
@@ -12,3 +13,4 @@ public enum DiskInError: Error {
|
||||
case cannotOpenFile(OSStatus)
|
||||
case cannotSetFormat(OSStatus)
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
#if canImport(AudioToolbox)
|
||||
import AudioToolbox
|
||||
#endif
|
||||
import Synchronization
|
||||
|
||||
/// Streaming soundfile output generators.
|
||||
@@ -21,6 +23,24 @@ import Synchronization
|
||||
/// 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
|
||||
@@ -122,11 +142,17 @@ public enum DiskOut {
|
||||
|
||||
// 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.
|
||||
@@ -215,6 +241,7 @@ public enum DiskOut {
|
||||
// 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(
|
||||
@@ -266,6 +293,19 @@ public enum DiskOut {
|
||||
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()
|
||||
@@ -283,6 +323,7 @@ public enum DiskOut {
|
||||
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
|
||||
@@ -293,6 +334,12 @@ public enum DiskOut {
|
||||
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 {
|
||||
@@ -303,11 +350,15 @@ public enum DiskOut {
|
||||
// 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
|
||||
@@ -342,7 +393,11 @@ public enum DiskOut {
|
||||
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).
|
||||
@@ -374,6 +429,7 @@ public enum DiskOut {
|
||||
_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) }
|
||||
@@ -398,6 +454,12 @@ public enum DiskOut {
|
||||
}
|
||||
}
|
||||
}
|
||||
#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
|
||||
}
|
||||
|
||||
@@ -4,7 +4,11 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import AudioToolbox
|
||||
// `OSStatus` comes from Darwin on Apple; off Apple it is the shim in
|
||||
// PlatformCompat.swift (same module, no import needed).
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
// MARK: - Errors
|
||||
|
||||
@@ -16,4 +20,8 @@ public enum DiskOutError: Error {
|
||||
/// for `DiskOut`, and render offline (`LyrebirdBuffer.write` / `NRTDriver`) for
|
||||
/// AAC / ALAC output.
|
||||
case compressedFormatNotSupported(AudioFileFormat)
|
||||
/// The requested container is not available on this (non-Apple) platform.
|
||||
/// Only the WAV encodings stream off Apple; use `.wavFloat32` / `.wavInt16` /
|
||||
/// `.wavInt24`.
|
||||
case unsupportedFormatOnPlatform(AudioFileFormat)
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Multi-source audio-bus summing generator.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Envelope follower with asymmetric attack and release smoothing.
|
||||
///
|
||||
@@ -170,7 +170,6 @@ public enum AmplitudeFollower {
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
// Bypass sub-block loop: smoothing state must update once per audio block.
|
||||
// Sub-blocking would apply the coeff N times per block, making time constants N× shorter.
|
||||
public func calculatedSamples(
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Smallest positive `hp` cutoff allowed. Below this the one-pole integrator coefficient
|
||||
/// would round to `1.0` (comp → 0), freezing the mean-square estimate. Clamps `hp` here.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Feed-forward dynamic range compressor with optional soft knee.
|
||||
///
|
||||
@@ -235,7 +235,6 @@ public enum Compressor {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 1.0 // matches _prevGain initial value
|
||||
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to compress.
|
||||
/// - threshold: Compression threshold in dB (e.g. `−6.0`). Gain reduction is applied above this level. Typical range −60 to 0. Defaults to `−6.0`.
|
||||
@@ -259,7 +258,6 @@ public enum Compressor {
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
// Bypass sub-block loop: _prevGain must advance once per audio block.
|
||||
// Sub-blocking would apply the gain smoother N times per block, shrinking time constants by N×.
|
||||
public func calculatedSamples(
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
// MARK: - Asymmetric attack/release smoother
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Downward expander and noise gate with optional soft knee.
|
||||
///
|
||||
@@ -230,7 +230,6 @@ public enum Expander {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 1.0 // matches _prevGain initial value
|
||||
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to expand.
|
||||
/// - threshold: Expansion threshold in dB. Gain is reduced for signal levels below this threshold. Defaults to `−40.0`.
|
||||
@@ -251,7 +250,6 @@ public enum Expander {
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
// Bypass sub-block loop: _prevGain must advance once per audio block.
|
||||
// Sub-blocking would apply the gain smoother N times per block, shrinking time constants by N×.
|
||||
public func calculatedSamples(
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Monophonic pitch tracker using the YIN algorithm (de Cheveigné & Kawahara 2002).
|
||||
///
|
||||
@@ -97,7 +97,6 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Fan-out cache
|
||||
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to track.
|
||||
/// - fftSize: Analysis window in **decimated** samples. Power of 2 in [64, 512].
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
/// True look-ahead limiter. Delays the output by `lookAheadTime` seconds and uses
|
||||
/// the look-ahead window to compute gain reduction before peaks arrive, guaranteeing
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Look-ahead peak normalizer. Delays the output by `dur` seconds and uses the look-ahead
|
||||
/// window to scale the signal so its peak tracks `level` — scaling **up** quiet passages and
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
/// Cascaded Butterworth bandpass filter, orders 1–8 per section (2 × order total poles).
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
/// Cascaded Butterworth band-reject (notch) filter, orders 1–8 per section (2 × order total poles).
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
/// Internal cascade engine for a single Butterworth LP or HP section.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Leaky integrator with 60 dB decay time.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Two-integrator decay that rounds off the sharp attack of ``Decay``.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// FOF-like resonant filter parameterised by attack and decay times.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Number of channels (= per-resonator parameters) required by ``Klank``: `freq`, `amp`,
|
||||
/// `decay`. Each ``LyrebirdBuffer`` frame supplies one resonator's parameters. The channel
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// One-pole exponential smoother with 60 dB lag time.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Two-cascaded one-pole smoother — smoother transition curve than a single ``Lag``.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Two-cascaded asymmetric one-pole smoother with separate 60 dB lag times for rising and falling.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
// Shared 60 dB coefficient helper for Lag, Decay, and LeakDC family generators.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Asymmetric one-pole smoother with separate 60 dB lag times for rising and falling signals.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Default DC-blocking coefficient for audio-rate `LeakDC`.
|
||||
public let leakDCDefaultAudioCoef: Double = 0.995
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Resonance feedback gain factor: `k = 4 · resonance`. `resonance = 1.0`
|
||||
/// corresponds to `k = 4.0`, the classic ladder self-oscillation threshold
|
||||
@@ -179,7 +178,7 @@ public enum MoogLadder {
|
||||
let scalarK: Double
|
||||
if !cutoffIsGenerator && !resonanceIsGenerator {
|
||||
let fc: Double = max(moogLadderMinCutoffHz, scalarCutoff)
|
||||
scalarG = min(moogLadderMaxCutoffCoeff, 1.0 - Darwin.exp(-twoPiOverSrOs * fc))
|
||||
scalarG = min(moogLadderMaxCutoffCoeff, 1.0 - exp(-twoPiOverSrOs * fc))
|
||||
let r: Double = min(moogLadderMaxResonance, max(0.0, scalarResonance))
|
||||
scalarK = moogLadderResonanceGain * r
|
||||
} else {
|
||||
@@ -206,7 +205,7 @@ public enum MoogLadder {
|
||||
rawRes = scalarResonance
|
||||
}
|
||||
let fc: Double = max(moogLadderMinCutoffHz, rawCutoff)
|
||||
g = min(moogLadderMaxCutoffCoeff, 1.0 - Darwin.exp(-twoPiOverSrOs * fc))
|
||||
g = min(moogLadderMaxCutoffCoeff, 1.0 - exp(-twoPiOverSrOs * fc))
|
||||
let r: Double = min(moogLadderMaxResonance, max(0.0, rawRes))
|
||||
k = moogLadderResonanceGain * r
|
||||
} else {
|
||||
@@ -237,15 +236,15 @@ public enum MoogLadder {
|
||||
private func ladderStep(input x: Double, g: Double, k: Double) -> Double {
|
||||
// half-sample feedback compensation: xfb = x − k·(y4 − 0.5·x)
|
||||
let xfb: Double = x - k * (y4 - moogLadderHalfSampleComp * x)
|
||||
let s: Double = Darwin.tanh(xfb)
|
||||
let s: Double = tanh(xfb)
|
||||
|
||||
y1 = y1 + g * (s - Darwin.tanh(y1))
|
||||
let t1: Double = Darwin.tanh(y1)
|
||||
y2 = y2 + g * (t1 - Darwin.tanh(y2))
|
||||
let t2: Double = Darwin.tanh(y2)
|
||||
y3 = y3 + g * (t2 - Darwin.tanh(y3))
|
||||
let t3: Double = Darwin.tanh(y3)
|
||||
y4 = y4 + g * (t3 - Darwin.tanh(y4))
|
||||
y1 = y1 + g * (s - tanh(y1))
|
||||
let t1: Double = tanh(y1)
|
||||
y2 = y2 + g * (t1 - tanh(y2))
|
||||
let t2: Double = tanh(y2)
|
||||
y3 = y3 + g * (t2 - tanh(y3))
|
||||
let t3: Double = tanh(y3)
|
||||
y4 = y4 + g * (t3 - tanh(y4))
|
||||
|
||||
y1 = denormalsToZero(y1)
|
||||
y2 = denormalsToZero(y2)
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Mu-Tron III auto-wah / envelope-controlled filter.
|
||||
///
|
||||
@@ -296,10 +295,10 @@ public enum MuTronIII {
|
||||
let sweep: Double = _directionUp ? env : (1.0 - env)
|
||||
|
||||
// Exponential pitch sweep from freqLo to freqHi.
|
||||
let cutoff: Double = safeFreqLo * Darwin.pow(safeFreqHi / safeFreqLo, sweep)
|
||||
let cutoff: Double = safeFreqLo * pow(safeFreqHi / safeFreqLo, sweep)
|
||||
|
||||
// Chamberlin SVF frequency coefficient.
|
||||
let f: Double = min(fCoeffMax, 2.0 * Darwin.sin(piOverSr * cutoff))
|
||||
let f: Double = min(fCoeffMax, 2.0 * sin(piOverSr * cutoff))
|
||||
|
||||
// Chamberlin SVF recurrence.
|
||||
_svfLow = _svfLow + f * _svfBand
|
||||
@@ -383,7 +382,6 @@ public enum MuTronIII {
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
|
||||
// Bypass sub-block loop: IIR state (envelope follower + SVF) must advance exactly
|
||||
// once per audio block, processing each input sample exactly once.
|
||||
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
@@ -467,8 +465,8 @@ public enum MuTronIII {
|
||||
|
||||
let env: Double = max(0.0, min(_prevAmp, 1.0))
|
||||
let sweep: Double = _directionUp ? env : (1.0 - env)
|
||||
let cutoff: Double = safeFreqLo * Darwin.pow(safeFreqHi / safeFreqLo, sweep)
|
||||
let f: Double = min(fCoeffMax, 2.0 * Darwin.sin(piOverSr * cutoff))
|
||||
let cutoff: Double = safeFreqLo * pow(safeFreqHi / safeFreqLo, sweep)
|
||||
let f: Double = min(fCoeffMax, 2.0 * sin(piOverSr * cutoff))
|
||||
|
||||
_svfLow = _svfLow + f * _svfBand
|
||||
let high: Double = x - _svfLow - q1 * _svfBand
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Number of channels (= per-resonator parameters) required by ``ResonatorBank``: `freq`,
|
||||
/// `decay`, `amp`. Each ``LyrebirdBuffer`` frame supplies one resonator's parameters.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Minimum damping denominator — prevents the `1/q` divide-by-zero in the SVF.
|
||||
let svfMinQDamping: Double = 0.0001
|
||||
@@ -63,7 +63,7 @@ func runSVFBlock(
|
||||
// generator — matching the original per-sample formula for that mixed case.
|
||||
let scalarFCoeff: Double = freqIsGenerator
|
||||
? 0.0
|
||||
: min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * scalarFreq)))
|
||||
: min(fCoeffMax, max(0.0, 2.0 * sin(piOverSr * scalarFreq)))
|
||||
let scalarQ1: Double = qIsGenerator ? 0.0 : 1.0 / max(minQDamping, scalarQ)
|
||||
|
||||
// Block-boundary cutoff-coefficient ramp for the generator-driven case.
|
||||
@@ -74,8 +74,8 @@ func runSVFBlock(
|
||||
let lastRaw: Double = fs[min(fs.count - 1, count - 1)]
|
||||
// `max(0.0, ...)` matches the scalar path: a freq above the sample rate makes
|
||||
// `sin(π·freq/sr)` negative, which would destabilise the Chamberlin recurrence.
|
||||
let cFirst: Double = firstRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * firstRaw))) : 0.0
|
||||
let cLast: Double = lastRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * lastRaw))) : 0.0
|
||||
let cFirst: Double = firstRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * sin(piOverSr * firstRaw))) : 0.0
|
||||
let cLast: Double = lastRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * sin(piOverSr * lastRaw))) : 0.0
|
||||
fFirst = cFirst
|
||||
fStep = count > 1 ? (cLast - cFirst) / Double(count - 1) : 0.0
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Linear slew-rate limiter. Equivalent to SuperCollider `Slew`.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Passive guitar-amplifier tone stack (bass / mid / treble) — the interactive Fender /
|
||||
/// Marshall / Vox EQ network, not three independent bands.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
/// Maps pan position in [−1, 1] to angle in [0, π/2] for equal-power panning.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
/// Pre-computed constant: tableSize / (2π), converts FM modulator [-1,1] output to
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
// MARK: - File-scope constants
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
/// Granular synthesizer that records a live audio input into a circular capture buffer
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
/// Granular synthesizer that generates a windowed sine tone inside each grain.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
public enum TimeStretch {
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Tunable grain-pool granular pitch shifter on live audio input.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// The four arithmetic operators `BinaryOpGenerator` can dispatch to vDSP. A
|
||||
/// generator built from an arbitrary closure (not one of these four) carries no
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
// MARK: - LinLin
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
// Vectorised inner loops for the unary math waveshapers (Sin / Cos / Exp / Log /
|
||||
// Sqrt / Floor / Ceil / Abs). Each `.Audio._computeSamples` resolves its input
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Real-time neural guitar-amp inference: a single-layer LSTM followed by a dense output,
|
||||
/// run one audio sample at a time. This is the GuitarML "Proteus" / NeuralPi topology —
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// 1st-order B-format Ambisonics decoder.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Angle scale: maps pan position in [−1, 1] to angle in [0, π/2].
|
||||
/// Pre-computed as a module-level constant; warmed up in SynthesisEngine.start() so the
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Open base class for 4-speaker equal-power square panners.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
/// Equal-power 4-speaker square panner driven by a polar **azimuth** angle.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
/// Equal-power 4-speaker square panner with polar (azimuth + distance) position
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// π/2 — the angle scale for PanN equal-power interpolation between adjacent speakers.
|
||||
/// Pre-computed at module load time; warmed up in `SynthesisEngine.start()`.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Equal-power 4-speaker square panner driven by cartesian `x` / `y` coordinates.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
|
||||
/// Equal-power 4-speaker square panner with source-distance modelling.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
// MARK: - ConvolutionReverb constants
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Single-channel extractor for multi-output generators.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Half-pi constant for CrossFade equal-power gain derivation.
|
||||
private let crossFadeHalfPi: Double = .pi / 2
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Multi-channel-to-mono fold-down generator.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Additive resynthesis from a `SpectralFrameBuffer`.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Foundation
|
||||
import Synchronization
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Per-bin spectral delay with per-bin feedback.
|
||||
///
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Synchronization
|
||||
|
||||
/// Magnitude moving-average ("box blur") across complex bins. Smears spectral
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Synchronization
|
||||
|
||||
/// Hard brick-wall spectral filter. Zeroes magnitudes (and DC/Nyquist when
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
import Synchronization
|
||||
|
||||
/// Random-access spectral buffer playback via a normalized position pointer.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Consolidated short-time Fourier transform pipeline. A single audio-rate
|
||||
/// Generator that owns the entire chain: input accumulation, windowed forward
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import LyrebirdDSP
|
||||
|
||||
/// Context passed to a ``SpectralComplexClosureBody`` on each FFT hop.
|
||||
///
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user