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,148 @@
|
||||
# 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.
|
||||
@@ -52,6 +52,7 @@ Two engines do not magically share object graphs. Runtime binding checks enforce
|
||||
- Cleared on `engine.remove(_:)` after the matching `processBlock` cycle.
|
||||
- Cross-engine sharing throws `EngineAddError.boundToOtherEngine(current:prior:)` — both UUIDs are reported.
|
||||
- Same-engine re-add without an intervening `remove` throws `EngineAddError.doubleAdd(engine:)`.
|
||||
- `engine.stop()` also releases the exclusive binding for every non-persistent synth the engine was hosting — including synths nested inside drained `Group` subtrees (not `ParallelGroup` children, which are never bound individually). Because `stop()` has already halted the RT thread before this unbind pass runs, a stop-then-re-add of the same instance — to the same engine or a different one — needs no intervening `processBlock`, unlike the `remove(_:)` path. See [`synthesis-engine.md` § `stop()` node-tree teardown contract](synthesis-engine.md#stop-node-tree-teardown-contract).
|
||||
- Pattern for "the same synth, on two engines": construct a fresh instance per engine. Synth construction is cheap; the build closure is the canonical place to express the graph.
|
||||
|
||||
**LyrebirdBuffer**
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# Portable WAV codec
|
||||
|
||||
`WavFileWriter` / `WavFileReader` (`Sources/Lyrebird/Buffers/`) are Lyrebird's
|
||||
own RIFF/WAVE implementation. They exist so offline render (`NRTDriver`), disk
|
||||
streaming, and buffer file I/O keep working where Apple's `ExtAudioFile` does
|
||||
not — that is, everywhere except macOS and iOS. On Apple platforms these types
|
||||
are still present but unused; the `AudioToolbox` path takes over.
|
||||
|
||||
Scope is deliberate: canonical RIFF/WAVE with one `fmt ` chunk and one `data`
|
||||
chunk, in `float32`, `int16`, or `int24`. CAF, AIFF, AAC, and ALAC stay
|
||||
Apple-only and throw `NRTDriverError.unsupportedFormatOnPlatform` off Apple.
|
||||
|
||||
## Writing
|
||||
|
||||
```swift
|
||||
let writer: WavFileWriter = try WavFileWriter(
|
||||
url: url, channels: 2, sampleRate: 48000, encoding: .float32
|
||||
)
|
||||
try writer.write(interleaved: block, frames: frameCount) // once per render block
|
||||
try writer.finalize()
|
||||
```
|
||||
|
||||
The header is written up front with placeholder sizes, blocks append, and
|
||||
`finalize()` seeks back to patch them. Three properties of that contract are
|
||||
worth knowing, because tests pin them:
|
||||
|
||||
- **`finalize()` is idempotent, and only latches on success.** A second call is
|
||||
a no-op; a call that throws partway leaves the writer retryable rather than
|
||||
stuck with a file whose sizes are still zero.
|
||||
- **`deinit` finalizes best-effort.** A writer dropped without an explicit
|
||||
`finalize()` still produces a readable file rather than leaking its
|
||||
descriptor, though errors there have nowhere to go — call `finalize()`
|
||||
yourself when you need to know it worked.
|
||||
- **A 4 GB render throws rather than trapping.** RIFF sizes are 32-bit, and the
|
||||
conversion would trap; `WavFileError.fileTooLarge` is raised instead. Use
|
||||
RF64 (Apple only, for now) for longer material.
|
||||
|
||||
### Header layout
|
||||
|
||||
Integer PCM gets the canonical 44-byte header. Non-PCM tags do not: RIFF
|
||||
requires `float32` to declare `cbSize` — an 18-byte `fmt ` body — and to carry
|
||||
a `fact` chunk with the per-channel sample count, which `finalize()` patches
|
||||
along with the sizes. Strict readers reject float files that omit either, so
|
||||
the writer emits a 58-byte header for `.float32`.
|
||||
|
||||
Chunks are word-aligned. An odd `data` payload (reachable with `int24`) is
|
||||
followed by a pad byte, counted in the RIFF size but **not** in the `data`
|
||||
size.
|
||||
|
||||
## Reading
|
||||
|
||||
```swift
|
||||
let reader: WavFileReader = try WavFileReader(url: url)
|
||||
let block: [Float] = try reader.read(frames: 512) // interleaved, [-1, 1]
|
||||
try reader.skip(frames: 44_100) // seeks; does not read
|
||||
reader.close()
|
||||
```
|
||||
|
||||
- **`WAVE_FORMAT_EXTENSIBLE` is understood.** Most 24-bit and multichannel
|
||||
writers emit tag `0xFFFE` with the real format in the SubFormat GUID;
|
||||
rejecting it would refuse ordinary files.
|
||||
- **The `data` size is clamped to the bytes the file actually holds.**
|
||||
Streaming writers leave a placeholder size they never patch, and believing it
|
||||
yields a nonsense frame count and a mid-render `.truncated` throw instead of
|
||||
a clean end of file.
|
||||
- **`skip(frames:)` seeks.** Reading and discarding a start offset a minute
|
||||
into a stereo 48 kHz file would allocate ~23 M samples for nothing.
|
||||
- A `fmt ` chunk too short to hold the fields it must declare throws
|
||||
`.truncated` rather than reading past its end.
|
||||
|
||||
## Errors
|
||||
|
||||
`WavFileError` — `.cannotCreate`, `.cannotOpen`, `.notWave`,
|
||||
`.unsupportedFormat(formatTag:bitsPerSample:)`, `.truncated`,
|
||||
`.fileTooLarge(bytes:)`.
|
||||
|
||||
These escape `NRTDriver` and `LyrebirdBuffer` file I/O **on non-Apple
|
||||
platforms**, where this codec is the backend. Error handling written against
|
||||
`NRTDriverError` alone will miss them — see `docs/tooling/nrt-guide.md`.
|
||||
|
||||
## Related
|
||||
|
||||
- `docs/tooling/nrt-guide.md` — offline render, formats, and the error table.
|
||||
- `docs/engine/alsa-audio-driver.md` — the other half of "Lyrebird works off
|
||||
Apple": live audio on Linux.
|
||||
@@ -171,6 +171,16 @@ engine.stop() // calls driver.stop(), sets isRunning = false
|
||||
|
||||
Bus memory (`audioBuses`, `controlBuses`) is allocated in `start()` and is empty before start. After `stop()`, the existing bus arrays remain in memory but are not updated further.
|
||||
|
||||
### `stop()` node-tree teardown contract
|
||||
|
||||
`stop()` does more than halt the driver: after `driver.stop()` returns (the RT thread is no longer running), it tears down every non-persistent node in the tree **and unbinds every non-persistent synth it was hosting**:
|
||||
|
||||
- `rootGroup` and `mainGroup` are persistent — they survive `stop()` intact and are never unbound (they are not `SynthesizerBase` instances to begin with; only `mainGroup`'s `PreparedNode` remains as `rootGroup`'s sole child).
|
||||
- Every other node — direct children of `mainGroup`, pre/post-main nodes installed via `.before(mainGroup)` / `.after(mainGroup)`, and every synth nested inside a drained `Group` subtree — is unlinked from the tree and, if it is a `SynthesizerBase`, has `_unbind(from:)` called on it. `synthesizerCount` / `groupCount` reset to zero.
|
||||
- `ParallelGroup` children are not individually unbound — they were never individually bound in the first place (added via `ParallelGroup.add(_:)`, not `engine.add(_:)`), so only the enclosing `ParallelGroup` node itself is drained.
|
||||
|
||||
The practical effect: **a synth instance that was active when `stop()` was called can be `add`ed again immediately** — to the same engine or a different one — with no `EngineAddError.doubleAdd` / `.boundToOtherEngine` and no need to wait for a `processBlock` first. This is a stronger guarantee than `remove(_:)` (see [Ownership Binding](#ownership-binding-engineadd-throws) below), because `stop()` has already halted the RT thread before the unbind pass runs — there is no add-vs-evaluate race to protect against, unlike the `remove` → re-add path.
|
||||
|
||||
## Engine Identity
|
||||
|
||||
Every `SynthesisEngine` carries a process-unique `identifier: UUID`, assigned at `init` and immutable for the engine's lifetime. The identifier surfaces in:
|
||||
@@ -200,6 +210,8 @@ All four throw `EngineAddError`:
|
||||
|
||||
Internally, every add path calls `synth._bind(to: self)` before any RT-visible side effect. `_bind` is a single-shot acquire-release `compareExchange` on `SynthesizerBase._engineBinding: Atomic<UInt>` storing the raw bit pattern of an `UnsafeMutableRawPointer` to the bound engine. Zero RT cost — the binding atomic is read only on the main thread during add. `remove(_:)` synchronously calls `_unbind` on successful enqueue so a subsequent re-add (after one `processBlock`) does not collide with `.doubleAdd`.
|
||||
|
||||
`engine.stop()` also releases this binding for every non-persistent synth it was hosting — see [`stop()` node-tree teardown contract](#stop-node-tree-teardown-contract) above. Unlike `remove(_:)`, a stop-then-re-add needs no intervening `processBlock`: the RT thread is already halted by the time `stop()`'s unbind pass runs.
|
||||
|
||||
`Group` instances are not bound — they are persistent node-tree fixtures and do not subclass `SynthesizerBase`.
|
||||
|
||||
`LyrebirdBuffer` has an opt-in two-tier binding API for cross-engine sharing — see [Multi-Core Audio § Multiple Engines](multi-core.md) and the `EngineHost` doc.
|
||||
|
||||
Reference in New Issue
Block a user