b6fdee8bfc
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>
649 lines
29 KiB
Swift
649 lines
29 KiB
Swift
// 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
|