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>
149 lines
7.1 KiB
Markdown
149 lines
7.1 KiB
Markdown
# ALSAAudioDriver — live audio on Linux
|
||
|
||
`ALSAAudioDriver` (`Sources/Lyrebird/AudioDrivers/ALSAAudioDriver.swift`) is the
|
||
real-time driver for Linux, the counterpart to `CoreAudioDriver` on macOS and
|
||
`iOSAudioDriver` on iOS. Without it a Linux build can only render offline to
|
||
WAV through `NRTDriver`.
|
||
|
||
## Getting one
|
||
|
||
Do not name the driver directly unless you mean to require that platform. Which
|
||
drivers exist is not decided by the operating system alone — see
|
||
[Build requirement](#build-requirement-libasound) — so consumer code cannot
|
||
test for it with its own `#if`. Ask the library:
|
||
|
||
```swift
|
||
let engine = SynthesisEngine(
|
||
blockSize: 512, sampleRate: 44100,
|
||
numOutputChannels: 2, numInputChannels: 0,
|
||
driver: makeDefaultAudioDriver()
|
||
)
|
||
try engine.start()
|
||
```
|
||
|
||
`makeDefaultAudioDriver()` resolves to `iOSAudioDriver`, `CoreAudioDriver`,
|
||
`ALSAAudioDriver`, or — where no live backend exists — `OfflineDriver`, which
|
||
runs the graph and makes no sound. `isLiveAudioAvailable` tells you which side
|
||
of that you landed on, so an app can say so instead of appearing to hang
|
||
silently.
|
||
|
||
## Transport
|
||
|
||
A blocking `snd_pcm_writei` loop on a dedicated thread, rather than an ALSA
|
||
async handler. That is the shape with the fewest ways to be wrong: no callback
|
||
re-entrancy, none of the async-handler restrictions on what may be called, and
|
||
back-pressure arrives for free — the write blocks until the device wants more.
|
||
|
||
- **Sample format** — `SND_PCM_FORMAT_FLOAT_LE`, which is exactly the engine's
|
||
`Float` bus format, so nothing in the path converts, scales, or dithers. ALSA
|
||
converts to the hardware's own format below us.
|
||
- **Device setup** — `snd_pcm_set_params`, ALSA's own convenience over the
|
||
hw/sw-params dance. Latency is requested as
|
||
`blockSize × periodsPerBuffer / sampleRate`; ALSA picks a period for it.
|
||
- **Per block** — read capture (duplex only) → `engine.processBlock` →
|
||
interleave the output buses → write. The interleave/deinterleave staging
|
||
buffers are allocated in `setup(engine:)`; the loop body allocates nothing.
|
||
- **Thread** — marks itself with `RTThreadIdentity.markCurrentThreadAsRT()` and
|
||
calls `enableFlushToZero()` (thread-local, so per-thread, not per-process).
|
||
|
||
## Duplex
|
||
|
||
Requesting input channels opens a capture PCM as well and `snd_pcm_link`s it to
|
||
playback so both run off one clock; unlinked streams on separate clocks drift
|
||
until one of them wedges. `linkedStreams` reports whether the kernel accepted
|
||
the link — a device pair that refuses still runs, with read-then-write ordering
|
||
keeping them approximately aligned.
|
||
|
||
## Realtime priority
|
||
|
||
The render thread requests `SCHED_FIFO` at 75 % of the policy's range, well
|
||
clear of the top so a runaway loop cannot lock out kernel threads. Denial is
|
||
the normal case for an unprivileged process and is **not** an error: audio runs
|
||
at normal priority instead. `hasRealtimePriority` reports what was granted (it
|
||
is written by the render thread after `start()` returns, so it is atomic).
|
||
Granting it to a user needs a `limits.conf` / `rtkit` configuration on the host.
|
||
|
||
## Xrun and error policy
|
||
|
||
`ALSARecoveryAction.classify(_:)` turns a transfer's return value into the one
|
||
correct response:
|
||
|
||
| Return | Action | Why |
|
||
|---|---|---|
|
||
| `>= 0` | `.transferred(frames:)` | may be a short transfer — resume from there |
|
||
| `-EINTR` | `.interrupted` | a signal, not a device fault: reissue at once |
|
||
| `-EAGAIN` | `.wouldBlock` | device not ready: wait for it |
|
||
| `-EPIPE`, `-ESTRPIPE` | `.recover` | underrun/suspend — `snd_pcm_recover`, reissue |
|
||
| anything else | `.fail` | device gone; stop the loop, record `lastError` |
|
||
|
||
The errno values are written out as Linux constants rather than imported from
|
||
the host's `errno.h`, so the classification cannot mean different things on
|
||
different platforms (`EAGAIN` is 11 on Linux, 35 on Darwin) and the tests that
|
||
pin it stay honest.
|
||
|
||
Anything that moves no frames spends a shared patience budget, and only a
|
||
transfer that actually moves frames clears it — so a device alternating
|
||
underruns with not-ready returns cannot loop forever. That covers three cases:
|
||
a `.wouldBlock` (which also sleeps on `snd_pcm_wait` rather than spinning — a
|
||
blocking PCM should never return would-block, but a plugin chain can, and
|
||
spinning from a `SCHED_FIFO` thread starves the machine), a `.recover`, and a
|
||
`.transferred(frames: 0)`. `.interrupted` is deliberately outside that budget,
|
||
since a signal says nothing about the device's health; it yields and reissues,
|
||
under a much larger bound that exists only so a pathological signal source
|
||
cannot spin the loop.
|
||
|
||
## Lifecycle
|
||
|
||
`stop()` clears the run flag and then waits for the render thread to leave its
|
||
loop **before** closing the PCM handles — closing them under a live thread is a
|
||
use-after-free. If the thread does not exit within the timeout (only possible
|
||
with a transfer wedged inside ALSA), the handles and staging buffers are
|
||
deliberately **abandoned rather than freed**: a leak is recoverable, a wild
|
||
write is not.
|
||
|
||
Abandonment latches. From that point `lastError` reads
|
||
`.renderThreadDidNotExit`, and `setup()` and `start()` **throw that error
|
||
immediately** — no device is probed, because reallocating the staging buffers
|
||
or launching a second thread would both land on the one that never came back.
|
||
`stop()` and `deinit` likewise stop touching those resources. The engine is
|
||
retained for the render thread's lifetime, so an abandoned thread cannot end up
|
||
calling into a deallocated engine. The device stays claimed until the process
|
||
exits.
|
||
|
||
`start()` also drains any stale exit signal before launching a thread, so a
|
||
timed-out stop cannot make the *next* stop return early.
|
||
|
||
Two other `ALSAError` cases report where a run went wrong rather than how it
|
||
was configured: `.transferFailed` — the stream died mid-transfer, or spent its
|
||
patience budget; `.renderLoopPreconditionFailed` — the loop found no engine or
|
||
no output buffer and exited before rendering anything, which would otherwise
|
||
present as silence with no explanation.
|
||
|
||
## Build requirement (libasound)
|
||
|
||
The `CALSA` system-library target (`Sources/CALSA/`) needs ALSA's headers:
|
||
|
||
```bash
|
||
apt-get install libasound2-dev pkg-config
|
||
```
|
||
|
||
`Package.swift` adds that target only when the manifest is evaluated **on a
|
||
Linux host**. Consequences worth knowing:
|
||
|
||
- macOS/iOS builds never see it.
|
||
- **A Linux binary cross-compiled from a Mac has no live-audio driver** — the
|
||
manifest host was macOS. Build natively on Linux for sound.
|
||
- Without the package, a native Linux build fails at
|
||
`'alsa/asoundlib.h' file not found`. Set `LYREBIRD_DISABLE_ALSA=1` to build
|
||
everything except the driver on a box with no audio stack. Because SwiftPM
|
||
caches evaluated manifests, changing that variable may need the cache
|
||
cleared (`rm -rf .build`) before it takes effect.
|
||
|
||
## Status
|
||
|
||
Built and tested headless — the paths that need no hardware (unopenable device,
|
||
start-before-setup, repeated stop, the recovery classification, the interleave
|
||
conversion) are covered by `Tests/LyrebirdPortableTests` and run in Linux CI on
|
||
x86_64. It has **not** been run against real audio hardware; see `LINUX_PLAN.md`
|
||
Item 1 for the checks still outstanding.
|