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,324 @@
|
||||
# Cross-Platform Feasibility — Linux / Windows
|
||||
|
||||
> Status: **investigation** (branch `feasibility/cross-platform-linux-windows`).
|
||||
> Not a commitment to ship. This document records the measured non-portable
|
||||
> surface of the codebase and the paths that could carry Lyrebird off Apple
|
||||
> platforms, ranked by effort.
|
||||
|
||||
## Summary
|
||||
|
||||
Lyrebird is currently welded to Apple platforms in `Package.swift`
|
||||
(`.macOS(.v15), .iOS(.v18)`) and links five Apple-only frameworks
|
||||
(`CoreAudio`, `AudioToolbox`, `Accelerate`, `CoreMIDI`, `AVFoundation`).
|
||||
|
||||
Two independent porting jobs stand between today and a Linux/Windows build:
|
||||
|
||||
1. **DSP kernel** — 73 files call `vDSP_*` (Accelerate) directly. This is the
|
||||
dominant cost. No portable fallback exists.
|
||||
2. **Audio + MIDI I/O** — live drivers (CoreAudio/RemoteIO), audio file codec
|
||||
(ExtAudioFile), and MIDI (CoreMIDI) all need per-platform implementations.
|
||||
|
||||
Everything except vDSP is already folder-isolated behind a small number of
|
||||
files, so the porting surface outside the DSP kernel is small.
|
||||
|
||||
`Synchronization.Atomic` (52 files) is **not** a blocker — it is a stdlib
|
||||
module and works on Linux/Windows with Swift 6.x. The CLAUDE.md note
|
||||
"requires macOS 15" refers to Apple-availability, not portability.
|
||||
|
||||
## Measured non-portable surface (core `LyrebirdSynth` module)
|
||||
|
||||
| Blocker | Files | Nature | Isolated |
|
||||
|---|---|---|---|
|
||||
| Accelerate / vDSP | 73 | Pervasive across 62 generators + Spectral/Buffers/Engine | No |
|
||||
| Audio file I/O (ExtAudioFile) | ~6 (`Buffers/AudioFileFormat`, `Buffers/LyrebirdBufferFileIO`, `Generators/BufferIO/DiskIn`,`DiskOut`+errors) | WAV/AIFF read+write | Yes |
|
||||
| CoreMIDI | 3 (`MIDI/`) | MIDI in/out | Yes |
|
||||
| Live audio drivers | 4 (`AudioDrivers/`) | CoreAudio/RemoteIO/AUv3/NRT | Yes (protocol seam exists) |
|
||||
| AUv3 | 7 (`AUv3/`) | Apple plugin format — **exclude** off-Apple | Yes |
|
||||
|
||||
Not blockers for core: `AVFoundation` (8 files, all AUv3/iOS/CLI-scaffolder),
|
||||
`Foundation` (293 files, mostly portable via swift-corelibs-foundation).
|
||||
|
||||
## The abstraction seams that already exist
|
||||
|
||||
- `AudioDrivers/AudioDriver.swift` — protocol (`setup`/`start`/`stop` +
|
||||
`suggestedControlBlockSize`) with `OfflineDriver` no-op already present. A
|
||||
`LinuxAudioDriver` / `WindowsAudioDriver` slots in here without engine
|
||||
changes.
|
||||
- `MIDI/` — three files, self-contained CoreMIDI usage.
|
||||
- `LyrebirdGraphDSL` target — documented pure-Swift, no swiftc/AppKit →
|
||||
portable once core compiles.
|
||||
|
||||
Missing seam: **there is no vDSP abstraction layer.** Generators call
|
||||
`vDSP_vmulD`, `vDSP_vsmaD`, `vDSP_biquadD`, `vDSP_fft_zrip`, etc. directly.
|
||||
|
||||
## Proposed architecture (the one lever that unblocks everything)
|
||||
|
||||
Introduce `LyrebirdDSP` — a thin vector-math shim behind
|
||||
`#if canImport(Accelerate)`:
|
||||
|
||||
```swift
|
||||
// Apple: forwards to vDSP (zero cost).
|
||||
// Elsewhere: scalar/SIMD fallback, or link OpenBLAS + pffft/FFTW.
|
||||
@inline(__always) func lb_vmul(_ a: UnsafePointer<Double>, _ b: ..., ...) { ... }
|
||||
```
|
||||
|
||||
Do this first. It is the single change that unblocks offline render, headless
|
||||
live audio, and both target OSes at once, and costs nothing on macOS (pure
|
||||
forwarding). The 73 call sites migrate to the shim mechanically.
|
||||
|
||||
FFT is the sharpest sub-problem: `vDSP_fft_zrip` has no drop-in portable twin
|
||||
— candidates are pffft, FFTW (GPL — licensing), or a pure-Swift radix-2.
|
||||
|
||||
## Toolchains
|
||||
|
||||
### Linux
|
||||
- Manager: `swiftly` (official). Latest stable Swift **6.3.3**.
|
||||
- Distro builds: Ubuntu/Debian/Fedora/RHEL/Amazon Linux + static-Linux (musl) SDK.
|
||||
- CI: official `swift:6.3.3` Docker image.
|
||||
- Live audio: new `LinuxAudioDriver` — PipeWire (preferred) or ALSA via C-interop.
|
||||
- MIDI: ALSA seq or RtMidi.
|
||||
|
||||
### Windows
|
||||
- Install: `winget install --id Swift.Toolchain`. **`swiftly` not yet on Windows.**
|
||||
- Prereqs: Visual Studio 2022 / Build Tools (MSVC + Windows SDK).
|
||||
- Tier-2 after Linux: larger Foundation gaps, rougher SPM ergonomics.
|
||||
- Live audio: WASAPI (built-in) or ASIO (low-latency, Steinberg-licensed SDK).
|
||||
- MIDI: WinMM or RtMidi.
|
||||
|
||||
### IDE (base library, off Xcode)
|
||||
- **VS Code + Swift extension** (official) — recommended. LSP + LLDB + tests.
|
||||
- Cursor/Windsurf (same extension), Zed, Neovim + sourcekit-lsp, JetBrains CLion.
|
||||
- Xcode-exclusive loss that matters: SwiftUI previews — `LyrebirdUI` only.
|
||||
|
||||
## SwiftUI off-Apple
|
||||
|
||||
SwiftUI does **not** exist on Linux or Windows and no port is planned.
|
||||
`LyrebirdUI` (31 SwiftUI/AppKit/UIKit files) stays Apple-exclusive.
|
||||
|
||||
| Path | Target | Note |
|
||||
|---|---|---|
|
||||
| Skip | Android | wrong target for desktop |
|
||||
| swift-cross-ui | Linux/Win desktop | SwiftUI-*like*, not SwiftUI; rewrite; immature |
|
||||
| TokamakUI | Web (WASM) | largely stalled |
|
||||
| GTK/Qt Swift bindings | native | most work, no SwiftUI idiom |
|
||||
| External UI (Flutter/Tauri) over headless engine | any | pragmatic; IPC boundary |
|
||||
|
||||
**Recommendation:** keep Lyrebird headless off-Apple (CLI + GraphDSL + OSC/MIDI),
|
||||
let external UIs drive it — mirrors the SuperCollider server/client split.
|
||||
|
||||
## Paths ranked by effort
|
||||
|
||||
| # | Path | Effort | Blockers to clear |
|
||||
|---|---|---|---|
|
||||
| 1 | Linux offline/NRT render + CLI + GraphDSL | Low–Med | vDSP shim, portable file codec, drop platform pin, exclude AUv3 |
|
||||
| 2 | Linux live audio (headless engine) | +Med | `LinuxAudioDriver` (PipeWire/ALSA) + MIDI port |
|
||||
| 3 | Windows headless engine | +Med | reuse vDSP shim; WASAPI/ASIO driver; MSVC/Foundation friction |
|
||||
| 4 | Cross-platform GUI | High | swift-cross-ui rewrite OR external UI over IPC — not real SwiftUI |
|
||||
|
||||
## First cross-compile attempt (this branch)
|
||||
|
||||
Static Linux SDK `swift-6.3.3-RELEASE_static-linux-0.1.0` installed
|
||||
(checksum-verified). `Package.swift` linker settings made Apple-only via
|
||||
`.when(platforms: [.macOS, .iOS])` — macOS build unaffected (verified, 2.6s).
|
||||
|
||||
Cross-compile `swift build --swift-sdk aarch64-swift-linux-musl --target
|
||||
LyrebirdSynth`:
|
||||
|
||||
- Reached **625/625** compile tasks.
|
||||
- **1244 of 1245 errors are a single cause:** `Foundation` — "compiled module
|
||||
was created by an older version of the compiler; rebuild 'Foundation'".
|
||||
- **Zero** `no such module 'Accelerate' / 'CoreAudio'` errors — those imports
|
||||
are never reached, because the compiler bails at `import Foundation` first.
|
||||
|
||||
**Diagnosis: toolchain↔SDK mismatch, not a Lyrebird code result.** The active
|
||||
toolchain is Xcode's (`swiftlang-6.3.3.1.3`); the Static Linux SDK's prebuilt
|
||||
`Foundation.swiftmodule` was built by swift.org's 6.3.3 toolchain. `.swiftmodule`
|
||||
format is not stable across compiler *builds* at the same version. No swift.org
|
||||
toolchain is installed (`/Library/Developer/Toolchains/` empty).
|
||||
|
||||
The real (masked) break set — Accelerate + audio frameworks — cannot be read
|
||||
until the toolchains match.
|
||||
|
||||
## Second cross-compile — under matching swift.org toolchain
|
||||
|
||||
Installed swift.org toolchain `swift-6.3.3-RELEASE` (Apple-notarized,
|
||||
Developer ID "Swift Open Source", user-home install, no sudo) and re-ran:
|
||||
|
||||
```
|
||||
~/Library/Developer/Toolchains/swift-6.3.3-RELEASE.xctoolchain/usr/bin/swift \
|
||||
build --swift-sdk aarch64-swift-linux-musl --target LyrebirdSynth --scratch-path .build-linux
|
||||
```
|
||||
|
||||
Result — **the Foundation mismatch is gone.** Foundation (the 293-file base)
|
||||
compiles for Linux. The remaining error is `no such module 'AudioToolbox'`
|
||||
(first reached in `AUv3/`). Behind it sit Accelerate / CoreAudio / CoreMIDI —
|
||||
the compiler aborts module-emit at the first missing framework, so it reveals
|
||||
them one layer at a time, but there are **no surprise errors**: the blocker set
|
||||
is exactly the five Apple frameworks from the static inventory. No Foundation
|
||||
API gaps, no stdlib breakage.
|
||||
|
||||
### Headline feasibility number
|
||||
|
||||
Of **621** files in `Sources/Lyrebird`:
|
||||
|
||||
- **529 (85%) are framework-free** — Foundation/stdlib only, and Foundation is
|
||||
now confirmed to compile for Linux.
|
||||
- **92 (15%) touch an Apple framework** — the entire porting surface:
|
||||
|
||||
| Folder | Files | Job |
|
||||
|---|---|---|
|
||||
| Generators | 66 | vDSP → `LyrebirdDSP` shim (the wall) |
|
||||
| AUv3 | 7 | exclude off-Apple |
|
||||
| Buffers | 5 | portable WAV/AIFF codec |
|
||||
| AudioDrivers | 4 | per-OS live drivers |
|
||||
| Spectral | 3 | portable FFT |
|
||||
| MIDI | 3 | CoreMIDI → RtMidi/ALSA |
|
||||
| Engine / Buses / NodeTree / GeneratorCore | 4 | small Accelerate helpers |
|
||||
|
||||
**Conclusion: feasible.** 85% of the tree is portable as-is; the work is
|
||||
concentrated in a 92-file surface dominated by ~69 Accelerate/vDSP files that a
|
||||
single `LyrebirdDSP` shim addresses centrally. No architectural blocker found —
|
||||
this is mechanical porting, not a redesign.
|
||||
|
||||
## `LyrebirdDSP` shim — built and proven
|
||||
|
||||
New target `Sources/LyrebirdDSP` (wired in `Package.swift`, a dependency of
|
||||
`LyrebirdSynth`):
|
||||
|
||||
- `AccelerateShim.swift` — `#if canImport(Accelerate)` → `@_exported import
|
||||
Accelerate`; `#else` → vDSP/vForce API-compatible shims + `vDSP_Length` /
|
||||
`vDSP_Stride` typealiases, delegating to the scalar cores. Non-Apple math
|
||||
(`sin`/`cos`/…) imported from `Glibc`/`Musl`/`ucrt`.
|
||||
- `ScalarDSP.swift` — portable scalar cores, generic over `BinaryFloatingPoint`,
|
||||
compiled on **all** platforms so they are testable against real vDSP.
|
||||
- All 71 core `import Accelerate` lines migrated to `import LyrebirdDSP` (pure
|
||||
rename; on Apple the re-export makes the code byte-identical).
|
||||
|
||||
Verified:
|
||||
|
||||
- macOS full `swift build` green (unchanged behaviour — real vDSP via re-export).
|
||||
- `LyrebirdDSP` **cross-compiles clean to `aarch64-swift-linux-musl`** in
|
||||
isolation (0.84s).
|
||||
- `Tests/LyrebirdDSPTests/ScalarDSPParityTests` — 8 tests compare each scalar
|
||||
core to the real vDSP on Apple (incl. the operand-order-sensitive
|
||||
`vsub`/`vdiv`); all pass. This is the guarantee the Linux fallback matches
|
||||
Accelerate.
|
||||
- Full-core cross-compile: the **Accelerate wall is gone** — the next
|
||||
`no such module` is `AudioToolbox` (the compiler aborts at the first
|
||||
unguarded framework, so blockers surface one layer at a time).
|
||||
|
||||
Deliberately deferred in the shim (compile to a precise "cannot find …" off
|
||||
Apple, which is the burn-down list): FFT family (`vDSP_fft_zrip`, `ctoz`, …),
|
||||
biquad-setup family (`vDSP_biquad*`), `vDSP_mmulD`, `vDSP_vrampmul`,
|
||||
`vDSP_vdpsp`. These need real portable replacements, not one-line loops.
|
||||
|
||||
## AudioToolbox layer — module walls cleared
|
||||
|
||||
Portable WAV codec + platform guards landed. **Every `no such module` wall is
|
||||
now gone** — the Linux cross-compile no longer aborts on a missing Apple
|
||||
framework; what remains is symbol-level (the deferred DSP), not module-level.
|
||||
|
||||
Done this stage:
|
||||
|
||||
- **Portable WAV codec** (`Buffers/WavEncoding.swift`, `WavFileWriter.swift`,
|
||||
`WavFileReader.swift`, `WavFileError.swift`) — streaming RIFF/WAVE PCM
|
||||
read+write (float32 / int16 / int24), pure Foundation, no AudioToolbox.
|
||||
4 round-trip tests (float32 exact; int16/int24 within quantization; non-WAVE
|
||||
rejected). This is the ExtAudioFile replacement for offline render / disk I/O.
|
||||
- **Guarded the Apple-only framework files** with `#if canImport(...)`:
|
||||
AudioToolbox (17: AUv3 + drivers + file I/O), CoreMIDI (3, `MIDI/`),
|
||||
Network (2, `OSC/`).
|
||||
- **Conditional C-library import** (`#if canImport(Darwin) … #elseif Glibc /
|
||||
Musl`) across 16 files (`RTThreadIdentity` pthread TLS + 15 math users).
|
||||
|
||||
Verified: macOS full build green; 12 new tests pass; the Linux cross-compile
|
||||
now reaches the symbol-level remainder below (no module aborts).
|
||||
|
||||
## Milestone: the LyrebirdSynth core cross-compiles to Linux
|
||||
|
||||
`swift build --swift-sdk aarch64-swift-linux-musl --target LyrebirdSynth`
|
||||
**completes with 0 errors.** The full synthesis core builds on Linux; macOS
|
||||
build is unchanged and its 19 DSP/WAV parity tests pass. Getting here took, in
|
||||
order: matching toolchain → `LyrebirdDSP` vDSP/vForce shim → portable WAV codec
|
||||
+ framework guards → deferred DSP (FFT/biquad/mmul) → mach-time + FoundationXML
|
||||
→ AudioFileFormat split + OSStatus → NRTDriver/DiskOut WAV backend.
|
||||
|
||||
What works on Linux today: the entire generator/synthesizer graph, offline
|
||||
(NRT) render **to WAV**, WAV disk streaming (`DiskOut`) and reading, the graph
|
||||
DSL, MIDI/OSC/AUv3/CoreAudio-drivers excluded (guarded). Apple builds keep every
|
||||
format and driver.
|
||||
|
||||
Still to do for a *runnable* Linux binary (beyond compiling the library):
|
||||
a live `LinuxAudioDriver` (PipeWire/ALSA), building the `LyrebirdCLI`/other
|
||||
targets for Linux, and a Linux CI lane. FFT/biquad are compile-parity-tested but
|
||||
not yet golden-value-tested through the actual spectral generators on Linux.
|
||||
|
||||
## Deferred DSP — complete
|
||||
|
||||
`LyrebirdDSP` now provides an Apple-forward + portable implementation of **every**
|
||||
vDSP/vForce symbol the core uses. Portable pieces (compiled off Apple; on Apple
|
||||
the real Accelerate is re-exported):
|
||||
|
||||
- Vector ops + vForce (`ScalarDSP.swift`) — earlier stage.
|
||||
- `vDSP_vdpsp` (double→float), `vDSP_mmulD` (row-major matmul), biquad family
|
||||
(`PortableBiquad.swift`, DF-II, opaque setup), `vDSP_vrampmul`,
|
||||
`vDSP_hann_window` (periodic Hann), `vvatan2f`.
|
||||
- Real FFT — radix-2 complex core (`ComplexFFTCore.swift`) + real forward/inverse
|
||||
matching vDSP's `zrip` packing (DC→`realp[0]`, Nyquist→`imagp[0]`) and scaling
|
||||
(forward ×2/bin, forward→inverse ×2N); `PortableFFT.swift` shims
|
||||
`create/destroy_fftsetup`, `fft_zrip`, `ctoz`, `ztoc`, `zvmags`, `zvma`;
|
||||
`DSPComplex`/`DSPSplitComplex` mirror types.
|
||||
|
||||
**All parity-tested against real vDSP on Apple** (`LyrebirdDSPTests`, 15 tests):
|
||||
FFT forward + round-trip, biquad, matmul, vdpsp, vrampmul, Hann, and the vector
|
||||
ops — the guarantee the Linux fallback matches Accelerate. Linux cross-compile:
|
||||
**zero unresolved DSP symbols.**
|
||||
|
||||
## Remaining (non-DSP; the last mile to a compiling Linux core)
|
||||
|
||||
Errors down to ~1497, now exclusively:
|
||||
|
||||
1. **Mach time** — `mach_absolute_time`, `mach_timebase_info(_data_t)`,
|
||||
`clock_gettime_nsec_np`, `CLOCK_UPTIME_RAW` (monotonic clock). Port to
|
||||
`clock_gettime(CLOCK_MONOTONIC)` on Linux — small, localized.
|
||||
2. **`FoundationXML`** — `XMLParser`/`XMLParserDelegate` moved out of `Foundation`
|
||||
on Linux; `#if canImport(FoundationXML) import FoundationXML` in the 3
|
||||
`Score/MusicXML/` files.
|
||||
3. **File-I/O cross-references** — `AudioFileFormat`, `DiskOut`, `NRTDriver`,
|
||||
`OSStatus` referenced from portable code (SynthesisEngine, EngineHost, NRTJob,
|
||||
LyrebirdEventList/Process, RF64Writer, DiskOutFormat). These are the
|
||||
entanglement from guarding the AudioToolbox file-I/O out; resolve by wiring
|
||||
the (already-built, tested) portable WAV codec into NRTDriver / DiskIn/DiskOut
|
||||
and guarding the residual `OSStatus`/AU references.
|
||||
|
||||
## Remaining (symbol-level, no longer module walls)
|
||||
|
||||
1. **Deferred DSP** — the shim intentionally omits these off-Apple; they need
|
||||
real portable implementations, and they are what the Linux compile now
|
||||
reports as `cannot find …`:
|
||||
- FFT family — `vDSP_fft_zrip`, `vDSP_create_fftsetup`, `vDSP_ctoz`/`ztoc`,
|
||||
`DSPSplitComplex`, `DSPComplex`, `FFTDirection`/`FFTRadix` (Spectral,
|
||||
ConvolutionReverb). Needs a portable FFT (pffft / pure-Swift radix-2).
|
||||
- Biquad-setup family — `vDSP_biquad*` (Butterworth, Klank, ResonatorBank,
|
||||
Moog/MuTron/SVF helpers). Needs a portable biquad.
|
||||
- `vDSP_mmulD` (AmbiDecoder1, Pan2/PanN), `vDSP_vdpsp` (double→float in
|
||||
SynthesisEngine/ScratchBuses/RF64Writer). Small portable replacements.
|
||||
2. **C-lib qualified refs** — a handful of `Darwin.foo` / `memcpy` / bare
|
||||
`cos`/`sin` call sites in the above files need the platform C-lib in scope
|
||||
(mechanical, folds into stage 1 as those files are touched).
|
||||
3. **Live drivers / AUv3 / MIDI / OSC** — currently guarded *out* off-Apple.
|
||||
Restoring capability needs `LinuxAudioDriver` (PipeWire/ALSA), a WAV-backed
|
||||
NRT driver (codec now exists — wiring pending), RtMidi, POSIX-socket OSC.
|
||||
|
||||
Before any merge: run full `swift test` on macOS + `/lyrebird_review`. The
|
||||
import migrations are semantic no-ops via re-export/guards on Apple, but CI must
|
||||
confirm.
|
||||
|
||||
### Reproduce the cross-compile
|
||||
|
||||
```
|
||||
swift sdk install <static-linux-sdk-url> --checksum <sha>
|
||||
# matching swift.org toolchain required (Xcode's will not pair with the SDK):
|
||||
~/Library/Developer/Toolchains/swift-6.3.3-RELEASE.xctoolchain/usr/bin/swift \
|
||||
build --swift-sdk aarch64-swift-linux-musl --target LyrebirdSynth --scratch-path .build-linux
|
||||
```
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
# Lyrebird on Linux — getting started
|
||||
|
||||
Lyrebird began as a macOS/iOS framework; a cross-platform port makes its non-UI
|
||||
core — the engine, generators, CLI, offline render, live ALSA audio, ALSA MIDI,
|
||||
and OSC — build and run on Linux. This guide gets you from a bare Ubuntu box to a
|
||||
built tree, a passing test suite, and a rendered sample.
|
||||
|
||||
> **Status.** The headless surface is complete and CI-tested on x86_64. Live
|
||||
> audio (ALSA) and MIDI are built but their on-hardware acceptance is still being
|
||||
> verified — see `LINUX_PLAN.md`. The macOS SwiftUI UI (`LyrebirdUI`) is Apple-only,
|
||||
> but an **experimental, opt-in** GTK4 UI (`LyrebirdUILinux`, on
|
||||
> [SwiftOpenUI](https://github.com/codelynx/SwiftOpenUI)) builds under a flag and
|
||||
> ships a runnable knob demo — see [Run a sample](#4-run-a-sample). It currently
|
||||
> depends on a personal fork carrying an unmerged gesture fix.
|
||||
|
||||
## 1. Prerequisites
|
||||
|
||||
**Distribution.** Ubuntu 24.04 LTS is the tested target — it is what the CI image
|
||||
(`swift:6.3.3`) and the cross-compile SDK are built against. Other modern glibc
|
||||
distros work but are untested.
|
||||
|
||||
**Swift toolchain.** Use the **swift.org** toolchain (6.0 or newer), not a distro
|
||||
package. The easiest installer is [swiftly](https://www.swift.org/install/linux/):
|
||||
|
||||
```bash
|
||||
curl -O https://download.swift.org/swiftly/linux/swiftly-$(uname -m).tar.gz
|
||||
tar zxf swiftly-$(uname -m).tar.gz && ./swiftly init
|
||||
# then, in a new shell:
|
||||
swiftly install latest
|
||||
swift --version
|
||||
```
|
||||
|
||||
`swiftly init` appends its environment to `~/.bashrc`, but if a new shell can't
|
||||
find `swiftly` or `swift`, add its bin directory to `PATH` yourself and reload:
|
||||
|
||||
```bash
|
||||
echo 'export PATH="$HOME/.local/share/swiftly/bin:$PATH"' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
```
|
||||
|
||||
**System packages.**
|
||||
|
||||
```bash
|
||||
# Always needed to build/link the test suite:
|
||||
sudo apt install build-essential pkg-config
|
||||
|
||||
# Live audio + MIDI (the ALSA backends). Without this the package still builds
|
||||
# with LYREBIRD_DISABLE_ALSA=1, but there is no sound or MIDI:
|
||||
sudo apt install libasound2-dev
|
||||
|
||||
# Only for the GTK4 GUI spike (spikes/SwiftOpenUIKnob/):
|
||||
sudo apt install libgtk-4-dev
|
||||
```
|
||||
|
||||
## 2. IDE
|
||||
|
||||
There is no Xcode on Linux. The maintained path is **VS Code + the official Swift
|
||||
extension** (`swiftlang.swift-vscode`): SourceKit-LSP autocomplete and
|
||||
diagnostics, LLDB debugging, a test explorer, and SwiftPM integration.
|
||||
|
||||
```bash
|
||||
code --install-extension swiftlang.swift-vscode
|
||||
```
|
||||
|
||||
Open the repository folder; the extension picks up `Package.swift` automatically.
|
||||
Neovim/Emacs with `sourcekit-lsp` also work if you prefer.
|
||||
|
||||
## 3. Get the source and build
|
||||
|
||||
```bash
|
||||
git clone git@bitbucket.org:realizedsound/lyrebird.git
|
||||
cd lyrebird
|
||||
swift build
|
||||
```
|
||||
|
||||
On a Linux host the package manifest omits the Apple-only targets (`LyrebirdUI`,
|
||||
the AudioToolbox-importing test targets, the benchmarks), so `swift build` /
|
||||
`swift test` compile only the portable surface — the core engine + generators
|
||||
(`LyrebirdSynth`), the interpreted graph DSL (`LyrebirdGraphDSL`), and the CLI.
|
||||
|
||||
Run the tests. `--no-parallel` is the canonical command (the parallel runner has
|
||||
a known teardown flake):
|
||||
|
||||
```bash
|
||||
swift test --no-parallel
|
||||
```
|
||||
|
||||
No sound stack? Build and test everything except the ALSA driver:
|
||||
|
||||
```bash
|
||||
LYREBIRD_DISABLE_ALSA=1 swift test --no-parallel
|
||||
```
|
||||
|
||||
## 4. Run a sample
|
||||
|
||||
### Offline render — works with no audio device
|
||||
|
||||
The surest first run: scaffold a project that renders a soundfile, no hardware
|
||||
involved. It exercises the whole engine end to end and drops a WAV next to the
|
||||
sources.
|
||||
|
||||
```bash
|
||||
swift run LyrebirdCLI new MyRender --template nrt
|
||||
cd MyRender
|
||||
swift run # renders output.wav
|
||||
```
|
||||
|
||||
The `score` template does the same from notation, writing a MusicXML file and a
|
||||
WAV.
|
||||
|
||||
### Live audio — needs a working sound device
|
||||
|
||||
Once ALSA sees a device (in a VM, make sure the guest has audio; test with
|
||||
`aplay -l`), the real-time templates play to the speakers. The generated project
|
||||
calls `makeDefaultAudioDriver()`, which resolves to `ALSAAudioDriver` on Linux:
|
||||
|
||||
```bash
|
||||
swift run LyrebirdCLI new MyTone --template quickstart
|
||||
cd MyTone
|
||||
swift run # a 440 Hz sine for a few seconds
|
||||
```
|
||||
|
||||
`isLiveAudioAvailable` reports `false` if the build has no live backend (e.g.
|
||||
built with `LYREBIRD_DISABLE_ALSA=1`), in which case `makeDefaultAudioDriver()`
|
||||
returns a silent `OfflineDriver`.
|
||||
|
||||
### REPL and live coding
|
||||
|
||||
```bash
|
||||
swift run LyrebirdCLI repl
|
||||
```
|
||||
|
||||
builds the package and drops into a Swift REPL with `import LyrebirdSynth` wired
|
||||
up — define generators and synthesizers and add them to a running engine live.
|
||||
|
||||
### The GUI demo (experimental)
|
||||
|
||||
An opt-in GTK4 knob demo drives a live sine tone from `LyrebirdUILinux`. It needs
|
||||
`libgtk-4-dev` (and `libasound2-dev` + a device for sound) and a display, and it
|
||||
pulls a personal fork of SwiftOpenUI carrying an unmerged gesture fix, so it is
|
||||
behind the `LYREBIRD_ENABLE_LINUX_UI` flag and not part of the default build:
|
||||
|
||||
```bash
|
||||
LYREBIRD_ENABLE_LINUX_UI=1 swift run LyrebirdUILinuxDemo
|
||||
```
|
||||
|
||||
A window opens with live CPU-load meters, a live oscilloscope of the stereo
|
||||
output, a static plot of an example envelope, and controls for two parameters
|
||||
(frequency, amplitude): an
|
||||
XY pad driving both at once, a knob, a slider, and a value readout for each, a
|
||||
gate toggle, and a reset button. Drag any control; with a live ALSA device the
|
||||
tone tracks in real time and the scope shows the waveform. Because
|
||||
every control bound to a parameter observes the same `@UIParam` node, moving one
|
||||
(say the freq knob) updates the others (the freq slider and readout) live — the
|
||||
same parameter model the macOS SwiftUI controls use.
|
||||
|
||||
> The one-time dependency resolve writes the fork pin into `Package.resolved`.
|
||||
> That pin is intentionally **not** committed — run `git checkout Package.resolved`
|
||||
> if you plan to commit, to keep the default build fork-free.
|
||||
|
||||
The earlier, self-contained `spikes/SwiftOpenUIKnob/` (run with `cd
|
||||
spikes/SwiftOpenUIKnob && swift run`) remains as the isolated gesture-fix
|
||||
reproduction; see its README.
|
||||
|
||||
## What is and isn't available on Linux
|
||||
|
||||
| Capability | Linux | Notes |
|
||||
|---|---|---|
|
||||
| Core engine + generators | ✅ | `LyrebirdSynth` |
|
||||
| Interpreted graph DSL | ✅ | `LyrebirdGraphDSL` |
|
||||
| CLI / REPL / scaffolding | ✅ | glibc; not built under musl |
|
||||
| Offline render (NRT → WAV) | ✅ | portable WAV codec; CAF/AIFF/AAC are Apple-only |
|
||||
| Soundfile load / DiskIn | ✅ | WAV only off Apple |
|
||||
| Live audio | ✅ built | ALSA; needs `libasound2-dev` + a device |
|
||||
| MIDI in/out | ✅ built | ALSA sequencer; needs a controller to verify |
|
||||
| OSC | ✅ | POSIX UDP; loopback-verified |
|
||||
| SwiftUI UI (`LyrebirdUI`) | ❌ | Apple-only |
|
||||
| GTK4 UI (`LyrebirdUILinux`) | ⚗️ opt-in | Experimental; `LYREBIRD_ENABLE_LINUX_UI=1`; on a SwiftOpenUI fork; knob/slider/label/button/XY + scope + envelope + CPU status ported + demo |
|
||||
| AUv3 plugin | ❌ | Apple-only |
|
||||
|
||||
## Reference
|
||||
|
||||
- `LINUX_PLAN.md` — port status, remaining work, and how it was built.
|
||||
- `docs/cross-platform-feasibility.md` — the porting approach.
|
||||
- `docs/engine/alsa-audio-driver.md` — the Linux audio driver.
|
||||
- `docs/engine/portable-wav-codec.md` — the off-Apple WAV read/write path.
|
||||
@@ -262,7 +262,7 @@ SynthesisEngine
|
||||
|
||||
## `@LiveParam` and `@UIParam` — Live Parameters
|
||||
|
||||
`@LiveParam` (in `Lyrebird`) and `@UIParam` (in `LyrebirdUI`) are the only live-parameter
|
||||
`@LiveParam` and `@UIParam` (both in `Lyrebird`) are the only live-parameter
|
||||
mechanisms. Both auto-register at `build()` time via `Mirror` reflection — no
|
||||
`declareParameter` call is required.
|
||||
|
||||
|
||||
@@ -447,6 +447,17 @@ if task.terminationStatus == 0 {
|
||||
| Silent output / all-zeros file | Synthesizers added after `start()` | Move all `engine.add()` calls before `start()` |
|
||||
| File truncated short | `duration` too short for the patch | Increase `NRTDriver` duration |
|
||||
|
||||
> **Off Apple (Linux/Windows):** the portable WAV codec backs these renders, so
|
||||
> a `WavFileError` — `.cannotCreate`, `.cannotOpen`, `.notWave`,
|
||||
> `.unsupportedFormat`, `.truncated`, `.fileTooLarge` — can also escape
|
||||
> `NRTDriver.setup`/`start`. A handler written against `NRTDriverError` alone
|
||||
> will miss those. The Apple-only containers (CAF, AIFF-C, AAC, ALAC) throw
|
||||
> `NRTDriverError.unsupportedFormatOnPlatform` there; render to
|
||||
> `.wavFloat32` / `.wavInt16` / `.wavInt24` instead. The codec's own contract —
|
||||
> streaming write, idempotent `finalize()`, header layout, and the read-side
|
||||
> clamps — is documented in `docs/engine/portable-wav-codec.md`.
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Reference Docs
|
||||
|
||||
@@ -9,8 +9,8 @@ The core `Lyrebird` module has **no UI dependency** — `LyrebirdUI` is imported
|
||||
targets that need GUI windows.
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth // engine, protocols, generators — no UI
|
||||
import LyrebirdUI // LyrebirdWindow, @UIParam, ParameterSlider, etc.
|
||||
import LyrebirdSynth // engine, protocols, generators, @UIParam — no UI
|
||||
import LyrebirdUI // LyrebirdWindow, ParameterSlider, etc.
|
||||
```
|
||||
|
||||
---
|
||||
@@ -21,7 +21,7 @@ Lyrebird provides two property wrappers for RT-safe parameters:
|
||||
|
||||
| | `@LiveParam` | `@UIParam` |
|
||||
|---|---|---|
|
||||
| Module | `Lyrebird` (no UI) | `LyrebirdUI` |
|
||||
| Module | `Lyrebird` (no UI) | `Lyrebird` (UI-observable) |
|
||||
| Projected value | `ParameterNode` | `UIParamNode` |
|
||||
| IS a `Generator`? | Yes (`AudioGenerator`) | No (`ValidGeneratorInput` only) |
|
||||
| RT delivery to oscillators/filters | Per-sample linear ramp | Block-constant (atomic read) |
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
<!--
|
||||
linux-parity-plan.md
|
||||
Lyrebird
|
||||
Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
SPDX-License-Identifier: MIT
|
||||
-->
|
||||
|
||||
# Linux parity plan — the two must-dos + the scratch window
|
||||
|
||||
Where Lyrebird's Linux GUI stands and what closes the gap to a defensible
|
||||
"parity with macOS" claim. The interactive widget layer is done and validated:
|
||||
every control/view is ported to a GTK4 `#else` body, and the SwiftOpenUI fork's
|
||||
narrow-mutation path (Patches A–F) makes them behave like real SwiftUI, not a
|
||||
degraded port. What remains are two functional gaps and one follow-on.
|
||||
|
||||
Prereq context: `docs/ui/linux-view-port-plan.md` (the view ports),
|
||||
`spikes/SwiftOpenUIKnob/FORK_PATCH_PLAN.md` + `NARROW_PATH_GENERALIZATION_PLAN.md`
|
||||
(the fork), and the `linux-gui-swiftopenui` memory. The fork is pinned by
|
||||
revision in `Package.swift`; this Mac cannot build the GTK4 backend, so every
|
||||
change is prepare-diff → push fork → bump pin → validate on the Linux VM.
|
||||
|
||||
Ordering: **(1) LyrebirdWindow → (2) MouseTracker → (3) scratch window.**
|
||||
The scratch window depends on (1). (1) and (2) are independent of each other.
|
||||
|
||||
---
|
||||
|
||||
## Must-do 1 — `LyrebirdWindow` (host-window abstraction) — ✅ DONE
|
||||
|
||||
**Status (branch `parity/linux-window-mousetracker`).** Shipped. A `#elseif
|
||||
os(Linux)` body backs `LyrebirdWindow` with a runtime-opened
|
||||
`GtkApplicationWindow` via a new fork API `GTK4Backend.openStandaloneWindow`
|
||||
(+ `gtk_swift_get_default_gtk_application`); `presentInWindow` is ported on all
|
||||
six views and the EngineStatus "Open Window" buttons are re-enabled. VM-runtime
|
||||
confirmed. **Design note that DIVERGES from the original plan below:** the Linux
|
||||
`LyrebirdWindow` / `presentInWindow` are **nonisolated**, NOT `@MainActor` — the
|
||||
whole Linux/GTK4 UI is confined to the GTK main loop (not the Swift main actor),
|
||||
and keeping `@MainActor` forced an `assumeIsolated` hop that captured
|
||||
task-isolated `self` → a "sending self risks data races" error. Only the
|
||||
`@MainActor` `LyrebirdMessageCenter.shared` access needs a self-less
|
||||
`assumeIsolated`. The original recommendation below to "Keep it `@MainActor`" is
|
||||
therefore superseded — do not follow it.
|
||||
|
||||
**Why it was a must-do.** There was no first-class way to open/manage a window on
|
||||
Linux. `LyrebirdWindow` was Apple-only (`NSWindow` + `NSHostingController`);
|
||||
every view's `presentInWindow(...)` convenience, and the EngineStatus "Open
|
||||
Window" buttons, were therefore macOS-only. The demo hand-rolls a single GTK
|
||||
window via SwiftOpenUI's `App`/`Scene`/`WindowGroup` scene model — there's no
|
||||
imperative "open another window hosting this view" equivalent.
|
||||
|
||||
**Current Apple surface** (`Sources/LyrebirdUI/LyrebirdWindow.swift`):
|
||||
`@MainActor final class LyrebirdWindow` — `init(title:width:height:)`,
|
||||
`open<Content: View>(@ViewBuilder content:)` (wraps `NSHostingController`),
|
||||
`close()`, `nsWindow`, and an `NSWindowDelegate` that nils the reference on user
|
||||
close. Consumed by `presentInWindow` on EngineStatus / NodeTree / Message /
|
||||
EventList / Process / RunningProcesses views.
|
||||
|
||||
**Linux approach.** Add a GTK4 `#else` body with the same public API, backed by a
|
||||
`GtkWindow`:
|
||||
- `open(content:)` → create a `GtkApplicationWindow` (or `GtkWindow`), set title +
|
||||
default size, `gtkRenderView(content())` (BackendGTK4) as the child, `present`.
|
||||
- `close()` → destroy the window; wire the `close-request` / destroy signal to nil
|
||||
the reference (parity with the `NSWindowDelegate`).
|
||||
- Keep it `@MainActor`.
|
||||
|
||||
**Key unknown to resolve first (spike).** GTK needs a running `GtkApplication` +
|
||||
main loop before a window can present. Two questions:
|
||||
1. Does SwiftOpenUI already expose a way to open a standalone window at runtime
|
||||
outside the `App`/`WindowGroup` scene (an imperative `GTK4Backend`
|
||||
window API)? If yes, build on it. If not, `LyrebirdWindow` must own the
|
||||
`gtk_init` + application + main-loop lifecycle itself.
|
||||
2. **App entry point.** On macOS `LyrebirdWindow` works standalone (implicit
|
||||
`NSApp`). On Linux, opening a window from a CLI/REPL with no scene needs an
|
||||
owned GTK app + loop. Decide: does `LyrebirdWindow` bootstrap GTK if none is
|
||||
running (so `presentInWindow` works headless-of-a-scene), or is it only valid
|
||||
inside a `GTK4Backend().run(App)` context? Recommendation: make it work in an
|
||||
existing loop first (covers the in-app "Open Window" buttons), then add a
|
||||
bootstrap path for standalone use.
|
||||
|
||||
**Effort:** moderate–substantial. The view hosting is straightforward
|
||||
(`gtkRenderView`); the GTK app/main-loop lifecycle + multi-window management is
|
||||
the real work, sized by what SwiftOpenUI already gives us (the spike answers it).
|
||||
|
||||
**Validation:** `presentInWindow` on EngineStatus/NodeTree/Message from the demo
|
||||
opens a second GTK window that renders + tracks; closing it (button + WM close)
|
||||
nils cleanly; no leak/crash on repeated open/close.
|
||||
|
||||
**Fork implication:** if SwiftOpenUI lacks a standalone-window API, that's a fork
|
||||
addition (a `GTK4Backend.openWindow(title:size:content:)`), upstreamable.
|
||||
|
||||
---
|
||||
|
||||
## Must-do 2 — `MouseTracker` / `MouseInput` (Linux pointer source) — ✅ DONE
|
||||
|
||||
**Status (branch `parity/linux-window-mousetracker`).** Shipped the window-local
|
||||
baseline. A `#elseif os(Linux)` `MouseTracker` (`MouseInputBridge` subclass,
|
||||
`Atomic<Double>` x/y/button, nonisolated) is fed by a new fork API
|
||||
`GTK4PointerTracking` — a `GtkEventControllerMotion` + window-level
|
||||
`GtkGestureClick` attached to every window the backend opens, forwarding
|
||||
normalized (y-flipped) coordinates to a process-wide sink. `installShared()`
|
||||
registers both `MouseInput.install(self)` and the sink; install timing is not
|
||||
sensitive (controllers read the sink at event time). x/y fully covered, button
|
||||
best-effort. Validated by `LYREBIRD_DEMO=mouse`. The X11-global enhancement below
|
||||
remains an optional future add.
|
||||
|
||||
**Why it was a must-do.** The `Mouse.X` / `Mouse.Y` / `Mouse.Click` *generators*
|
||||
(core, `Sources/Lyrebird/Generators/UI/`) read from `MouseInput`, which is fed by
|
||||
a `MouseInputBridge`. The only bridge is `MouseTracker` (AppKit `NSEvent` global
|
||||
monitors) — Apple-only. On Linux the generators silently read the default
|
||||
`0.5/0.5/0` — any patch using mouse control does nothing.
|
||||
|
||||
**Current seam (already platform-neutral — this is the good news):**
|
||||
- `open class MouseInputBridge` (`x`/`y`/`button`, default 0.5/0.5/0) — core.
|
||||
- `enum MouseInput` with `install(_ bridge:)` / `currentX/Y/Button` — core seam.
|
||||
- `MouseTracker: MouseInputBridge` (AppKit) installs `NSEvent` global monitors and
|
||||
overrides `x/y/button` from atomics — Apple-only, in `LyrebirdUI`.
|
||||
|
||||
So the port is a **new `MouseInputBridge` conformer for Linux** + installing it at
|
||||
startup via `MouseInput.install`. No core changes.
|
||||
|
||||
**Linux approach — pick the pointer source (design decision):**
|
||||
- **Window-local (recommended baseline, portable):** a `GtkEventControllerMotion`
|
||||
on the app window updates x/y (normalized to the window), plus a click gesture
|
||||
for `button`. Works on both X11 and Wayland. Limitation: only tracks while the
|
||||
pointer is over a Lyrebird window (not truly global) — acceptable for a synth
|
||||
control surface, and matches how you'd actually perform with it.
|
||||
- **Global (X11-only enhancement):** poll `XQueryPointer` (or XInput2) on a
|
||||
timer/thread for screen-global position. True parity with the macOS global
|
||||
monitor, but **X11 only** — Wayland forbids global pointer access (needs a
|
||||
portal). Gate behind an availability check; fall back to window-local.
|
||||
|
||||
Recommendation: ship window-local first (covers the real use case, no display-
|
||||
server dependency), add X11-global as an optional path if global is wanted.
|
||||
|
||||
**Effort:** moderate. The bridge + install is small; the pointer plumbing
|
||||
(GTK motion controller, or X11 polling) is the work. Live values are read on the
|
||||
RT-adjacent path via atomics exactly as the AppKit tracker does — mirror that.
|
||||
|
||||
**Validation:** a patch with `Mouse.X.Control()` driving a parameter responds to
|
||||
pointer motion over the window on the VM; `MouseInput.currentX/Y/Button` update.
|
||||
|
||||
**Placement:** the Linux bridge lives in `LyrebirdUI` (like `MouseTracker`),
|
||||
conforms to the core `MouseInputBridge`, installed via `MouseInput.install` at app
|
||||
startup — same contract as macOS.
|
||||
|
||||
---
|
||||
|
||||
## Follow-on — the LiveCompile scratch window (after 1 & 2)
|
||||
|
||||
The live-coding scratchpad (`LiveCompile/` sub-package) is macOS-only. It has two
|
||||
layers with very different portability; full detail lives with the engine spike,
|
||||
summarized here for sequencing.
|
||||
|
||||
- **Engine (`LyrebirdLiveCompile`, ~3.3k LOC) — moderate, independent of 1 & 2.**
|
||||
`LiveCompiler` shells `swiftc -emit-library` → dylib, `dlopen`/`dlsym`;
|
||||
`SourceKitLSPClient` drives `sourcekit-lsp`. All portable (Linux toolchain ships
|
||||
`swiftc`, `dlopen`, `sourcekit-lsp`). Adapt: `.dylib`→`.so`, drop `xcrun`
|
||||
(PATH), Linux `-target`/SDK + module paths, dynamic-link the snippet against one
|
||||
`libLyrebird.so` (Linux analog of the `libLyrebirdDynamic.dylib` design), and a
|
||||
Linux `SwiftToolchainStatus`.
|
||||
- **Spike first (½ day, do before committing):** prove a `swiftc → .so → dlopen`
|
||||
snippet resolves Lyrebird's symbols on the VM against the shared
|
||||
`libLyrebird.so`. Swift-on-Linux cross-`.so` symbol/metadata resolution is the
|
||||
one real unknown; go/no-go for the whole path.
|
||||
|
||||
- **Editor UI (`LyrebirdLiveCompileUI`, ~3.1k LOC) — depends on Must-do 1.**
|
||||
Built on `NSTextView` (`ScratchTextView`, `NSViewRepresentable`, AppKit menus) +
|
||||
hand-rolled highlighter/gutter/LSP-completion/position-mapping. Two landings:
|
||||
- **Minimal (modest):** a `LyrebirdWindow` hosting SwiftOpenUI `TextEditor` +
|
||||
Run/Stop + console + the ported `LyrebirdScopeView`. No highlighting/completion.
|
||||
- **Full parity (large, fork work):** wrap **GtkSourceView** (GTK's code editor —
|
||||
syntax highlighting, gutter, completion, UTF-8) as a new SwiftOpenUI widget,
|
||||
rewire `ScratchModel`, feed it the LSP completions. GtkSourceView gives the
|
||||
highlighting/gutter/completion for *less* custom code than the AppKit version,
|
||||
but wrapping it in SwiftOpenUI is a genuine new-backend-widget project.
|
||||
|
||||
**Scratch-window sequencing:** engine spike → engine port (anytime) → Must-do 1 →
|
||||
minimal scratch window → (optional) full GtkSourceView editor.
|
||||
|
||||
---
|
||||
|
||||
## Cross-cutting (applies to all three)
|
||||
|
||||
- **Fork discipline.** Any SwiftOpenUI gap (standalone window API, GtkSourceView
|
||||
widget) is a fork commit: push `joshpar/SwiftOpenUI` `develop`, bump the
|
||||
`Package.swift` revision, validate on the VM. Keep each a clean upstreamable
|
||||
delta (see `FORK_PATCH_PLAN.md`).
|
||||
- **No Linux UI CI.** Core CI skips the UI (needs GTK). Before calling any of this
|
||||
"done", add at least a Linux **build** job for the UI + demo so regressions
|
||||
surface (a compile-only GTK4 job via the `swift:6.x` + `libgtk-4-dev` container
|
||||
noted in `linux-ci-x86-verification`).
|
||||
- **Validate on display, not just compile.** The Process/EventList/Message-family
|
||||
views compile but aren't exercised on the VM yet; fold them into the demo while
|
||||
doing Must-do 1 (they're what `presentInWindow` opens).
|
||||
|
||||
## Definition of "Linux at parity" (the checklist this plan satisfies)
|
||||
|
||||
1. ✅ `LyrebirdWindow` opens/manages GTK windows; `presentInWindow` works for
|
||||
every view; the EngineStatus "Open Window" buttons return.
|
||||
2. ✅ `Mouse.X/Y/Click` generators respond to the pointer on Linux
|
||||
(window-local baseline).
|
||||
3. ◐ Fork on a tagged release + UI has a Linux build job. The Linux CI job is in
|
||||
(`bitbucket-pipelines.yml` — one GTK-enabled build+test step compiles the UI
|
||||
graph). The fork is pinned to its first tagged release, `joshpar/SwiftOpenUI`
|
||||
`0.1.0`, instead of a bare commit. Still open: upstreaming the GTK4 patches to
|
||||
`codelynx/SwiftOpenUI` (externally gated — one maintainer, a prior PR went
|
||||
stale), after which the pin can move to an upstream version.
|
||||
4. ✅ Ported views exercised on display (VM-confirmed): EngineStatus (+ node-tree
|
||||
/ messages detached windows), the mouse demo, and — via `LYREBIRD_DEMO=events`
|
||||
— the Process/EventList family (`LyrebirdEventListPerformanceView` inline,
|
||||
hosting `LyrebirdEventListView` + per-process `LyrebirdProcessView` strips,
|
||||
plus `presentInWindow` for EventListPerformance / EventList / RunningProcesses).
|
||||
5. (Stretch) live-coding scratchpad usable on Linux — not started.
|
||||
@@ -0,0 +1,168 @@
|
||||
<!--
|
||||
linux-view-port-plan.md
|
||||
Lyrebird
|
||||
Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
SPDX-License-Identifier: MIT
|
||||
-->
|
||||
|
||||
# Linux view-port hand-off
|
||||
|
||||
Instructions for porting the remaining **Apple-only** `LyrebirdUI` views to the
|
||||
Linux/GTK4 backend, so a fresh agent can pick this up cold. Prereq context:
|
||||
`spikes/SwiftOpenUIKnob/FORK_PATCH_PLAN.md` (the SwiftOpenUI fork + drag fix) and
|
||||
the `linux-gui-swiftopenui` memory.
|
||||
|
||||
## Where things stand
|
||||
|
||||
`LyrebirdUI` is now **one cross-platform module** (parity steps B + C, done and
|
||||
VM-validated). Every control/view switches its body by backend:
|
||||
|
||||
```swift
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
public struct Foo: View { /* real SwiftUI body */ }
|
||||
#else
|
||||
import SwiftOpenUI
|
||||
import BackendGTK4 // Cairo DrawingContext drawing methods
|
||||
import LyrebirdSynth
|
||||
public struct Foo: View { /* SwiftOpenUI/GTK4 body — same public API */ }
|
||||
#endif
|
||||
```
|
||||
|
||||
The 8 stock controls/views are already dual-body and are your **templates**:
|
||||
- Canvas + drag: `Controls/ParameterKnob.swift`, `Controls/ParameterXY.swift`,
|
||||
`Controls/ParameterSlider.swift`
|
||||
- Canvas + a polled `@Observable` model: `LyrebirdScopeView.swift` +
|
||||
`LyrebirdScopeModel.swift`
|
||||
- Layout + `ForEach` + action: `LyrebirdStatusView.swift`,
|
||||
`Controls/ParameterButton.swift`, `Controls/ParameterLabel.swift`
|
||||
|
||||
The Apple-only views are currently wrapped whole in `#if canImport(SwiftUI)` (so
|
||||
they compile to nothing on Linux). **Porting one = add its `#else` body** in the
|
||||
same file and drop the outer guard (or convert the guard to `#if/#else`).
|
||||
|
||||
## Backend capabilities (SwiftOpenUI/GTK4) — what you have and don't
|
||||
|
||||
Confirmed present (`~/Documents/src/SwiftOpenUI/Sources/SwiftOpenUI/Views/`):
|
||||
`VStack`/`HStack`/`LazyVStack`, `ScrollView`, `List`, `ForEach`, `Text`,
|
||||
`Canvas`, `.onDrag`, `@State`/`@Binding`/`@Observable`. **Missing:** `Table`
|
||||
(use `ScrollView` + `ForEach` rows), `GeometryReader` (unverified — check; a
|
||||
`Canvas` renderer gets its `size` directly, prefer that).
|
||||
|
||||
Hard gaps to design around:
|
||||
- **`DrawingContext` has NO text primitive.** A Canvas body cannot draw text
|
||||
labels (axis ticks, value readouts). Either overlay real `Text` widgets on top
|
||||
of the Canvas (compose in a `ZStack`/stack), or leave labels off on Linux (as
|
||||
`LyrebirdEnvelopeView`'s "L"/"R" markers already do). Adding a text primitive
|
||||
to SwiftOpenUI's `DrawingContext` is the proper upstream fix.
|
||||
- **`DrawingContext` API is imperative Cairo**, not SwiftUI `GraphicsContext`:
|
||||
`setColor(r:g:b:)` / `setLineWidth(_:)` / `moveTo(x:y:)` / `lineTo(x:y:)` /
|
||||
`rectangle(x:y:width:height:)` / `arc(centerX:centerY:radius:startAngle:endAngle:)`
|
||||
/ `stroke()` / `fill()`. A `GraphicsContext`+`Path` body must be rewritten to
|
||||
these calls (see `ParameterKnob`/`ParameterSlider` `#else` bodies).
|
||||
- **`@Observable` needs an explicit `import Observation`** on Linux (SwiftOpenUI
|
||||
does not re-export it the way SwiftUI does).
|
||||
- **`.task` runs OFF the main thread** on SwiftOpenUI (unlike SwiftUI). For
|
||||
periodic polling use a Foundation `Timer` on `RunLoop.main` — see
|
||||
`LyrebirdScopeModel` / the `LinuxStatusModel` inside `LyrebirdStatusView.swift`.
|
||||
- **`Color`** is a SwiftOpenUI type on Linux, not SwiftUI's; `PlatformColors`
|
||||
(AppKit/UIKit) is Apple-only. Use raw colors in the `#else` body.
|
||||
- **Live cross-control redraw already works** in the fork (global interaction
|
||||
deferral + per-drag subtree redraw); Canvas bodies that read a shared value
|
||||
will track during a drag with no extra work. Native widgets (e.g. `GtkScale`)
|
||||
do not — that's why the slider was made Canvas-drawn. Draw with `Canvas` if the
|
||||
control must live-link.
|
||||
|
||||
## The views to port
|
||||
|
||||
**Status: all view ports below are DONE** — each has a `#else` SwiftOpenUI/GTK4
|
||||
body added in-place, same public API/init as the Apple side, and the macOS side
|
||||
stays green (`swift build --target LyrebirdUI`). Every SwiftOpenUI symbol used was
|
||||
checked against the fork source. **Still needs Linux/VM validation** per the
|
||||
workflow below (compile + eyeball) — no Linux build has run yet.
|
||||
|
||||
| View | ~LOC | Kind | Status | Linux notes |
|
||||
|---|---|---|---|---|
|
||||
| **LyrebirdSynthView** | 177 | layout | ✅ done | Adaptive `LazyVGrid(columns:data:)` (SwiftOpenUI's data-based form) of `ParameterKnob`s. |
|
||||
| **LyrebirdSpectrumView** | 234 | Canvas | ✅ done | `DrawingContext` rewrite; FFT polled by `Timer`+`@Observable` model. No axis text (Apple draws none either). |
|
||||
| **LyrebirdScatterView** | 121 | Canvas | ✅ done | `DrawingContext` `arc`+`fill` dots; reuses `_linuxEnvelopeYBounds`. |
|
||||
| **MultiSlider** | 137 | Canvas+drag | ✅ done | Fixed `columnWidth`; Canvas + `.onDrag`, pointer-x→column, pointer-y→value. |
|
||||
| **LyrebirdEngineStatusView** | 603 | layout | ✅ done | `Timer`+`@Observable` model; CPU bars are `Canvas` (not GeometryReader); Picker/Stepper/Toggle/FocusState all exist in the fork. "Open Window" buttons work on Linux too (node-tree / messages open detached windows) now that `LyrebirdWindow` has a GTK4 body; sections also still expand inline. |
|
||||
| **LyrebirdMessageBanner** / **LyrebirdMessageView** / **LyrebirdMessageHelpers** | 128 / 277 / 33 | layout | ✅ done | `@Bindable center` — the GTK4 view host evaluates bodies under `withObservationTracking`, so plain `@Observable` reads live-update (no polling needed). MessageView **dropped** auto-scroll + text selection. |
|
||||
| **LyrebirdNodeTreeView** | 266 | layout | ✅ done | Indented `ForEach` rows; SF chevrons → text glyphs (▼/▶/•). Live via `mirror.snapshot` observation. |
|
||||
| **LyrebirdEventListView** | 335 | layout | ✅ done | `Timer`+`@Observable` model; native `Slider` + `TextField`. (Did not need `List`.) |
|
||||
| **LyrebirdEventListPerformanceView** / **LyrebirdRunningProcessesView** / **LyrebirdProcessView** | 167 / 197 / 224 | layout | ✅ done | `Timer`+`@Observable` models; identity-stable child reassignment preserved; `DbSliderConversion` reused; native `Slider`. |
|
||||
|
||||
Also added a **Linux branch to `PlatformColors`** (`Color.lyrebirdControlBackground`
|
||||
/ `lyrebirdSeparator` as fixed neutral SwiftOpenUI tones) — the Apple file had
|
||||
no `#else`, which blocked every layout port that used those colours.
|
||||
|
||||
Cross-cutting decisions worth knowing for the next port/review:
|
||||
- Every periodic-poll view uses the `LyrebirdScopeModel` pattern (`@Observable`
|
||||
`@unchecked Sendable` model + Foundation `Timer` on `RunLoop.main`), **not**
|
||||
`.task` (off-main on SwiftOpenUI).
|
||||
- SF Symbols don't resolve on GTK4 → text glyphs.
|
||||
- `Font.monospaced()` is not a `Font` method on SwiftOpenUI (it's a separate
|
||||
case) → use the `.monospacedDigit()` **view** modifier instead.
|
||||
- SwiftOpenUI `Color` exposes `.red/.green/.blue/.alpha`, so a `Color` parameter
|
||||
(e.g. Scatter's `pointColor`) feeds `DrawingContext.setColor` directly.
|
||||
|
||||
### Separate subsystems (not simple view ports — scope carefully) — STILL TODO
|
||||
|
||||
- **LyrebirdWindow** (163 L, `NSWindow`). No portable equivalent. Needs a new
|
||||
cross-platform host-window abstraction backed by GTK4 on Linux (the demo,
|
||||
`Sources/LyrebirdUILinuxDemo/main.swift`, stands up a GTK window ad hoc today —
|
||||
start from that). Design work, not a mechanical port. Do this before shipping a
|
||||
first-class Linux app entry point.
|
||||
- **MouseTracker** (165 L, `NSEvent`) + `MouseInput` / `MouseInputBridge`. This
|
||||
feeds the `Mouse.X` / `Mouse.Y` / `Mouse.Click` **generators** (core, in
|
||||
`Sources/Lyrebird/Generators/UI/`), not a view. The core protocol
|
||||
(`MouseInputBridge`) is platform-neutral; nothing conforms to it on GTK4. Needs
|
||||
a GTK global-pointer (or X11/evdev) source installed via `MouseInput.install`.
|
||||
Separate from the view work; do it if the mouse generators are wanted on Linux.
|
||||
|
||||
## Validation workflow (important)
|
||||
|
||||
**You cannot build the GTK4 backend on macOS** — `LyrebirdUI`'s `#else` bodies
|
||||
compile only on Linux. Two rules:
|
||||
|
||||
1. Verify the **Apple** side here after any edit: `swift build --target LyrebirdUI`
|
||||
(must stay green — you are only adding `#else` branches, so it should).
|
||||
2. Verify the **Linux** side on the Linux box / VM. Push to the branch, then on
|
||||
the VM:
|
||||
```bash
|
||||
git pull
|
||||
swift build # builds LyrebirdUI (needs libgtk-4-dev + the fork)
|
||||
LYREBIRD_DEMO=full swift run LyrebirdUILinuxDemo
|
||||
```
|
||||
The ported views are wired into the demo under a new `monitors` mode —
|
||||
`LYREBIRD_DEMO=monitors swift run LyrebirdUILinuxDemo` shows the `LyrebirdSynthView`
|
||||
parameter grid, `LyrebirdScatterView`, a `MultiSlider`, and `LyrebirdEngineStatusView`
|
||||
(which embeds the node-tree + message sections). The Process/EventList family
|
||||
is not yet in the demo (needs a `LyrebirdEventList` + running processes to
|
||||
scaffold). For headless-core-only checks (no GTK) use
|
||||
`swift build --target LyrebirdSynth`, or the emulated x86 route in the
|
||||
`linux-ci-x86-verification` memory.
|
||||
|
||||
If you have Docker, an arm64 `swift:6.3.3` container with `libgtk-4-dev` installed
|
||||
can compile-check the Linux bodies without a display (build only, no run).
|
||||
|
||||
## Gotchas already paid for (don't rediscover)
|
||||
|
||||
- GTK4 reuses a child's cached render node — `queue_draw` must walk the subtree
|
||||
(`gtkQueueDrawSubtree` in the fork). Live redraw during drag already handled.
|
||||
- Drag gesture survival + linked live-update are solved in the fork
|
||||
(`FORK_PATCH_PLAN.md`); Canvas bodies get it for free.
|
||||
- Keep `#if canImport(SwiftUI)` as the discriminator (Linux's SwiftOpenUI does
|
||||
not vend a `SwiftUI` module). Not `#if os(...)`.
|
||||
- SPDX header stays first-5-lines; put `#if` after it, before imports.
|
||||
|
||||
## Definition of done (per view)
|
||||
|
||||
1. `#else` body added, same public API/init as the Apple side.
|
||||
2. `swift build --target LyrebirdUI` green on macOS.
|
||||
3. `swift build` + demo green on the Linux VM; the view renders and (if
|
||||
interactive) tracks.
|
||||
4. If it drops a feature on Linux (e.g. text labels), document it in the file
|
||||
header the way `LyrebirdEnvelopeView` does.
|
||||
@@ -0,0 +1,225 @@
|
||||
# Windows Support Plan
|
||||
|
||||
> Companion to `docs/cross-platform-feasibility.md`. That doc took the
|
||||
> `LyrebirdSynth` core to a clean Linux cross-compile; this one is the actionable
|
||||
> plan to bring the same core up on **Windows 11**, verified locally in a
|
||||
> Parallels VM. Branch: `feasibility/cross-platform-linux-windows`.
|
||||
|
||||
## Why Windows is close, not a fresh port
|
||||
|
||||
The Linux work forced a platform-neutral design — `LyrebirdDSP` (`@_exported`
|
||||
Accelerate on Apple / portable fallbacks off Apple), the portable WAV codec, and
|
||||
`#if canImport(...)` framework guards. Most of that lights up on Windows for
|
||||
free. `LyrebirdDSP`'s math shim already carries a `#elseif canImport(ucrt)`
|
||||
branch, `OSStatus` is shimmed for any non-Darwin platform, and libdispatch +
|
||||
`Synchronization.Atomic` both ship for Windows on Swift 6.x.
|
||||
|
||||
**The whole incremental Windows job is: 2 small platform-abstraction branches +
|
||||
a local verify loop + (later) a WASAPI driver.**
|
||||
|
||||
## Environment: Parallels Windows 11 (Apple Silicon → ARM64)
|
||||
|
||||
On an Apple Silicon Mac, Parallels runs **Windows 11 on ARM64**, so the Swift
|
||||
target is `aarch64-unknown-windows-msvc`. Swift.org ships ARM64 Windows
|
||||
toolchains, but ARM64 Windows Swift is **less battle-tested than x86_64** — expect
|
||||
a few more rough edges (some may be toolchain bugs, not our code). (If this were
|
||||
an Intel Mac it'd be x64 Windows = the most-tested path.)
|
||||
|
||||
### Step 1 — Install the toolchain (inside the VM)
|
||||
|
||||
1. Install **Visual Studio** (MSVC + Windows 11 SDK). Swift.org requires
|
||||
**"2022 or newer"; Community edition is sufficient.** VS 2022 is the
|
||||
documented/tested baseline; **VS 2026 Community should work** (Swift finds VS
|
||||
via `vswhere`, version-agnostic) but is not officially validated against the
|
||||
current Swift 6.3.x toolchain — if `swift build` can't find the MSVC
|
||||
environment, install **VS 2022 Build Tools alongside** (they coexist) as the
|
||||
fallback.
|
||||
- In the VS Installer: **"Desktop development with C++"** workload, plus these
|
||||
components — **`Windows 11 SDK`**, **`VC.Tools.ARM64`** (the ARM64 MSVC
|
||||
toolset — REQUIRED for `aarch64-windows`, easy to miss), and
|
||||
`VC.Tools.x86.x64`.
|
||||
- Enable **Developer Mode** (Windows Settings → For developers).
|
||||
2. Install the **Swift toolchain**:
|
||||
- `winget install --id Swift.Toolchain -e`
|
||||
- (No `swiftly` on Windows yet — winget/MSI is the path.)
|
||||
3. New terminal, verify: `swift --version` (expect Swift 6.3.x, target
|
||||
`aarch64-unknown-windows-msvc`). Confirm a hello-world `swift build` works
|
||||
before Lyrebird, to prove the MSVC env is wired.
|
||||
|
||||
### Step 2 — Get the code into the VM (native FS, NOT a shared folder)
|
||||
|
||||
Building from a Parallels **shared Mac folder** hits path/case/CRLF/file-lock
|
||||
quirks under SwiftPM. Clone into the VM's own filesystem instead:
|
||||
|
||||
```
|
||||
git clone <this-repo-url> C:\src\Lyrebird
|
||||
cd C:\src\Lyrebird
|
||||
git checkout feasibility/cross-platform-linux-windows
|
||||
```
|
||||
|
||||
(Or add the Mac repo as a remote over the Parallels network share and `git pull`
|
||||
from it — just don't *build* on the share.)
|
||||
|
||||
Set `git config core.autocrlf false` in the clone so the SPDX headers / fixtures
|
||||
don't get CRLF-mangled.
|
||||
|
||||
### Step 3 — First build + the verify loop
|
||||
|
||||
```
|
||||
swift build --target LyrebirdSynth 2>&1 | tee build.log
|
||||
```
|
||||
|
||||
Expect errors. Copy `build.log` back to the Mac side (paste into the session).
|
||||
The loop, exactly as we did for Linux:
|
||||
|
||||
1. You run `swift build` in the VM, paste the break-set.
|
||||
2. I categorize + fix on the Mac, commit.
|
||||
3. You `git pull`, rebuild, paste again.
|
||||
4. Repeat until `LyrebirdSynth` builds, then `swift test`.
|
||||
|
||||
## The two KNOWN code gaps (ready to fix)
|
||||
|
||||
Both are self-contained platform-abstraction files built for exactly this. Fixes
|
||||
below are ready to drop in; they are **blind until the VM verifies them**.
|
||||
|
||||
### Gap 1 — `Sources/Lyrebird/Utilities/MonotonicClock.swift`
|
||||
|
||||
The `#else` branch uses POSIX `clock_gettime(CLOCK_MONOTONIC)` / `timespec`,
|
||||
which Windows UCRT does **not** provide. Add a WinSDK branch using
|
||||
`QueryPerformanceCounter` / `QueryPerformanceFrequency`.
|
||||
|
||||
```swift
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(WinSDK)
|
||||
import WinSDK
|
||||
#endif
|
||||
|
||||
enum LyrebirdMonotonicClock {
|
||||
#if canImport(Darwin)
|
||||
// ... existing mach_absolute_time path (unchanged) ...
|
||||
#elseif canImport(WinSDK)
|
||||
static let ticksToNanos: Double = {
|
||||
var freq: LARGE_INTEGER = LARGE_INTEGER()
|
||||
QueryPerformanceFrequency(&freq)
|
||||
return 1_000_000_000.0 / Double(freq.QuadPart) // QPC ticks → ns
|
||||
}()
|
||||
@inline(__always)
|
||||
static func ticks() -> UInt64 {
|
||||
var counter: LARGE_INTEGER = LARGE_INTEGER()
|
||||
QueryPerformanceCounter(&counter)
|
||||
return UInt64(counter.QuadPart)
|
||||
}
|
||||
#else
|
||||
// ... existing clock_gettime(CLOCK_MONOTONIC) path (Linux) ...
|
||||
#endif
|
||||
}
|
||||
```
|
||||
|
||||
QPC is monotonic, high-resolution, allocation-free → RT-safe. Note it returns a
|
||||
tick count (not ns), so `ticksToNanos` scales by `1e9/frequency` — same
|
||||
tick+factor shape as the Apple mach path (the Linux path returns ns directly and
|
||||
uses factor 1.0).
|
||||
|
||||
### Gap 2 — `Sources/Lyrebird/Engine/RTThreadIdentity.swift`
|
||||
|
||||
Uses pthread TLS (`pthread_key_create`/`getspecific`/`setspecific`). Windows has
|
||||
no pthread. Use Fiber-Local Storage (`FlsAlloc`/`FlsGetValue`/`FlsSetValue`) from
|
||||
WinSDK — the Windows analogue of a TLS slot, and the pattern Swift's own runtime
|
||||
uses. Keep `markCurrentThreadAsRT()` allocation-free (it runs on the render
|
||||
thread).
|
||||
|
||||
```swift
|
||||
#elseif canImport(WinSDK)
|
||||
import WinSDK
|
||||
// _key: DWORD from FlsAlloc(nil) (lazy, non-RT — via warmUp()).
|
||||
// markCurrentThreadAsRT(): FlsSetValue(_key, sentinel) if FlsGetValue(_key) != sentinel
|
||||
// isCurrentThreadRT: FlsGetValue(_key) == sentinel
|
||||
```
|
||||
|
||||
`FlsGetValue`/`FlsSetValue` are O(1) pointer ops, no allocation → RT-safe, same
|
||||
contract as the pthread path. Sentinel = a non-null `UnsafeMutableRawPointer`
|
||||
(bit pattern 1), exactly like the pthread version.
|
||||
|
||||
> Design note: RTThreadIdentity is deliberately the one file that keeps a local
|
||||
> platform `#if` (it's threading plumbing, not a DSP primitive). Adding the
|
||||
> WinSDK branch keeps that boundary — generators stay platform-free.
|
||||
|
||||
## Step 4 — Expected further break-set (unknowns to watch)
|
||||
|
||||
Beyond the 2 known gaps, the VM build will likely surface:
|
||||
|
||||
- **Foundation gaps.** Windows Foundation is less complete than Linux's. Watch
|
||||
`FileHandle` (the WAV codec's `seek`/`write(contentsOf:)`/`read(upToCount:)`),
|
||||
`FileManager.createFile(atPath:)`, `URL.path` (backslash paths), `Data`.
|
||||
- **Path separators.** WAV codec + any file I/O uses `url.path`; on Windows that's
|
||||
`C:\...`. Should be handled by Foundation, but test round-trips.
|
||||
- **CRLF / text.** MusicXML + any text parsing — line-ending assumptions.
|
||||
- **`Thread.sleep` / `DispatchQueue`** — should work (libdispatch ships for
|
||||
Windows) but the DiskOut BG-drain loop is worth a smoke test.
|
||||
- **`Synchronization.Atomic`** — expected fine on 6.x; confirm.
|
||||
- **FoundationXML** — MusicXML uses `#if canImport(FoundationXML)`; verify the
|
||||
module exists on Windows (it may, may not — `canImport` handles either way,
|
||||
but if `XMLParser` isn't in plain Foundation *or* FoundationXML on Windows,
|
||||
MusicXML needs guarding).
|
||||
|
||||
## Step 5 — Milestone: `LyrebirdSynth` builds + tests on Windows
|
||||
|
||||
Same bar as Linux: `swift build --target LyrebirdSynth` clean, then
|
||||
`swift test --no-parallel` green (or the DSP/WAV subset first:
|
||||
`swift test --filter "ScalarDSPParityTests|WavCodecTests"`). The DSP parity tests
|
||||
are Apple-only (`#if canImport(Accelerate)`), so on Windows they compile away —
|
||||
Windows relies on the *same portable cores* Linux exercises, plus the WAV
|
||||
round-trip tests which DO run everywhere.
|
||||
|
||||
## Step 6 — Live audio + MIDI (after headless core is green)
|
||||
|
||||
- **Audio out:** `WindowsAudioDriver: AudioDriver` — **WASAPI** (built-in,
|
||||
~10–30 ms; shared or exclusive mode) first; **ASIO** later for low latency
|
||||
(<10 ms) — note the Steinberg ASIO SDK is **license-restricted / not
|
||||
redistributable**, a legal step, and users install their own ASIO driver.
|
||||
- **MIDI:** WinMM (legacy, simple) or WinRT MIDI (modern).
|
||||
- NRT-to-WAV already works via the portable codec, so offline render is
|
||||
available on Windows the moment the core builds.
|
||||
|
||||
## Step 7 — CI (optional, later)
|
||||
|
||||
A GitHub Actions `windows-latest` lane (`winget install Swift.Toolchain` + VS
|
||||
Build Tools) locks in the Windows build so it can't silently regress. The
|
||||
Parallels loop is for *bring-up*; CI is for *keeping it green*. (Note:
|
||||
`windows-latest` runners are x86_64 — if the local VM is ARM64, CI covers the
|
||||
x64 triple and the VM covers ARM64; together that's good coverage.)
|
||||
|
||||
## Quick-start checklist (when you return)
|
||||
|
||||
- [ ] VM: install VS 2022 Build Tools (Desktop C++ workload) + Swift toolchain
|
||||
- [ ] VM: `git clone` the repo natively (not a shared folder), checkout this branch, `core.autocrlf false`
|
||||
- [ ] VM: `swift build --target LyrebirdSynth 2>&1 | tee build.log`
|
||||
- [ ] Paste `build.log` into the session
|
||||
- [ ] (Mac) land Gap 1 + Gap 2 fixes, iterate the break-set to zero
|
||||
- [ ] VM: `swift test --no-parallel`
|
||||
- [ ] Then: WASAPI driver, MIDI, CI
|
||||
|
||||
## What's already committed vs pending
|
||||
|
||||
- Committed on this branch: the entire portable core (Linux-verified), incl. the
|
||||
`ucrt` math branch and `OSStatus` shim that Windows reuses.
|
||||
- **Both WinSDK branches are now written (blind, awaiting VM verification):**
|
||||
- `MonotonicClock.swift` — `#elseif canImport(WinSDK)` using
|
||||
`QueryPerformanceCounter` / `QueryPerformanceFrequency`.
|
||||
- `RTThreadIdentity.swift` — `#elseif canImport(WinSDK)` using
|
||||
`TlsAlloc` / `TlsGetValue` / `TlsSetValue` (chose `Tls*` over the plan's
|
||||
original `Fls*` — `Tls*` is the direct thread-local analogue; `Fls*` is
|
||||
fiber-scoped). Refactored the pthread call sites through inline
|
||||
`_tlsGet`/`_tlsSet` helpers so the RT methods are platform-agnostic;
|
||||
macOS + Linux re-verified (build + 22 targeted tests) — no regression.
|
||||
- Neither is verified on Windows yet — that's the first thing the VM build
|
||||
checks. Likely correction points: exact WinSDK symbol names / `LARGE_INTEGER`
|
||||
field access (`.QuadPart`), `DWORD.max` vs a `TLS_OUT_OF_INDEXES` constant,
|
||||
and whether `QueryPerformance*`/`Tls*` are imported into Swift as-is.
|
||||
- **Still pending:** the unknown Foundation/path break-set (Step 4) — only the VM
|
||||
can surface it.
|
||||
Reference in New Issue
Block a user